inbound.go 108 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950
  1. // Package service provides business logic services for the 3x-ui web panel,
  2. // including inbound/outbound management, user administration, settings, and Xray integration.
  3. package service
  4. import (
  5. "context"
  6. "encoding/json"
  7. "fmt"
  8. "sort"
  9. "strconv"
  10. "strings"
  11. "time"
  12. "github.com/google/uuid"
  13. "github.com/mhsanaei/3x-ui/v3/database"
  14. "github.com/mhsanaei/3x-ui/v3/database/model"
  15. "github.com/mhsanaei/3x-ui/v3/logger"
  16. "github.com/mhsanaei/3x-ui/v3/util/common"
  17. "github.com/mhsanaei/3x-ui/v3/web/runtime"
  18. "github.com/mhsanaei/3x-ui/v3/xray"
  19. "gorm.io/gorm"
  20. "gorm.io/gorm/clause"
  21. )
  22. type InboundService struct {
  23. xrayApi xray.XrayAPI
  24. }
  25. func (s *InboundService) runtimeFor(ib *model.Inbound) (runtime.Runtime, error) {
  26. mgr := runtime.GetManager()
  27. if mgr == nil {
  28. return nil, fmt.Errorf("runtime manager not initialised")
  29. }
  30. return mgr.RuntimeFor(ib.NodeID)
  31. }
  32. type CopyClientsResult struct {
  33. Added []string `json:"added"`
  34. Skipped []string `json:"skipped"`
  35. Errors []string `json:"errors"`
  36. }
  37. // enrichClientStats parses each inbound's clients once, fills in the
  38. // UUID/SubId fields on the preloaded ClientStats, and tops up rows owned by
  39. // a sibling inbound (shared-email mode — the row is keyed on email so it
  40. // only preloads on its owning inbound).
  41. func (s *InboundService) enrichClientStats(db *gorm.DB, inbounds []*model.Inbound) {
  42. if len(inbounds) == 0 {
  43. return
  44. }
  45. clientsByInbound := make([][]model.Client, len(inbounds))
  46. seenByInbound := make([]map[string]struct{}, len(inbounds))
  47. missing := make(map[string]struct{})
  48. for i, inbound := range inbounds {
  49. clients, _ := s.GetClients(inbound)
  50. clientsByInbound[i] = clients
  51. seen := make(map[string]struct{}, len(inbound.ClientStats))
  52. for _, st := range inbound.ClientStats {
  53. if st.Email != "" {
  54. seen[strings.ToLower(st.Email)] = struct{}{}
  55. }
  56. }
  57. seenByInbound[i] = seen
  58. for _, c := range clients {
  59. if c.Email == "" {
  60. continue
  61. }
  62. if _, ok := seen[strings.ToLower(c.Email)]; !ok {
  63. missing[c.Email] = struct{}{}
  64. }
  65. }
  66. }
  67. if len(missing) > 0 {
  68. emails := make([]string, 0, len(missing))
  69. for e := range missing {
  70. emails = append(emails, e)
  71. }
  72. var extra []xray.ClientTraffic
  73. if err := db.Model(xray.ClientTraffic{}).Where("email IN ?", emails).Find(&extra).Error; err != nil {
  74. logger.Warning("enrichClientStats:", err)
  75. } else {
  76. byEmail := make(map[string]xray.ClientTraffic, len(extra))
  77. for _, st := range extra {
  78. byEmail[strings.ToLower(st.Email)] = st
  79. }
  80. for i, inbound := range inbounds {
  81. for _, c := range clientsByInbound[i] {
  82. if c.Email == "" {
  83. continue
  84. }
  85. key := strings.ToLower(c.Email)
  86. if _, ok := seenByInbound[i][key]; ok {
  87. continue
  88. }
  89. if st, ok := byEmail[key]; ok {
  90. inbound.ClientStats = append(inbound.ClientStats, st)
  91. seenByInbound[i][key] = struct{}{}
  92. }
  93. }
  94. }
  95. }
  96. }
  97. for i, inbound := range inbounds {
  98. clients := clientsByInbound[i]
  99. if len(clients) == 0 || len(inbound.ClientStats) == 0 {
  100. continue
  101. }
  102. cMap := make(map[string]model.Client, len(clients))
  103. for _, c := range clients {
  104. cMap[strings.ToLower(c.Email)] = c
  105. }
  106. for j := range inbound.ClientStats {
  107. email := strings.ToLower(inbound.ClientStats[j].Email)
  108. if c, ok := cMap[email]; ok {
  109. inbound.ClientStats[j].UUID = c.ID
  110. inbound.ClientStats[j].SubId = c.SubID
  111. }
  112. }
  113. }
  114. }
  115. // GetInbounds retrieves all inbounds for a specific user with client stats.
  116. func (s *InboundService) GetInbounds(userId int) ([]*model.Inbound, error) {
  117. db := database.GetDB()
  118. var inbounds []*model.Inbound
  119. err := db.Model(model.Inbound{}).Preload("ClientStats").Where("user_id = ?", userId).Find(&inbounds).Error
  120. if err != nil && err != gorm.ErrRecordNotFound {
  121. return nil, err
  122. }
  123. s.enrichClientStats(db, inbounds)
  124. return inbounds, nil
  125. }
  126. // GetAllInbounds retrieves all inbounds with client stats.
  127. func (s *InboundService) GetAllInbounds() ([]*model.Inbound, error) {
  128. db := database.GetDB()
  129. var inbounds []*model.Inbound
  130. err := db.Model(model.Inbound{}).Preload("ClientStats").Find(&inbounds).Error
  131. if err != nil && err != gorm.ErrRecordNotFound {
  132. return nil, err
  133. }
  134. s.enrichClientStats(db, inbounds)
  135. return inbounds, nil
  136. }
  137. func (s *InboundService) GetInboundsByTrafficReset(period string) ([]*model.Inbound, error) {
  138. db := database.GetDB()
  139. var inbounds []*model.Inbound
  140. err := db.Model(model.Inbound{}).Where("traffic_reset = ?", period).Find(&inbounds).Error
  141. if err != nil && err != gorm.ErrRecordNotFound {
  142. return nil, err
  143. }
  144. return inbounds, nil
  145. }
  146. func (s *InboundService) GetClients(inbound *model.Inbound) ([]model.Client, error) {
  147. settings := map[string][]model.Client{}
  148. json.Unmarshal([]byte(inbound.Settings), &settings)
  149. if settings == nil {
  150. return nil, fmt.Errorf("setting is null")
  151. }
  152. clients := settings["clients"]
  153. if clients == nil {
  154. return nil, nil
  155. }
  156. return clients, nil
  157. }
  158. func (s *InboundService) getAllEmails() ([]string, error) {
  159. db := database.GetDB()
  160. var emails []string
  161. err := db.Raw(`
  162. SELECT DISTINCT JSON_EXTRACT(client.value, '$.email')
  163. FROM inbounds,
  164. JSON_EACH(JSON_EXTRACT(inbounds.settings, '$.clients')) AS client
  165. `).Scan(&emails).Error
  166. if err != nil {
  167. return nil, err
  168. }
  169. return emails, nil
  170. }
  171. // getAllEmailSubIDs returns email→subId. An email seen with two different
  172. // non-empty subIds is locked (mapped to "") so neither identity can claim it.
  173. func (s *InboundService) getAllEmailSubIDs() (map[string]string, error) {
  174. db := database.GetDB()
  175. var rows []struct {
  176. Email string
  177. SubID string
  178. }
  179. err := db.Raw(`
  180. SELECT JSON_EXTRACT(client.value, '$.email') AS email,
  181. JSON_EXTRACT(client.value, '$.subId') AS sub_id
  182. FROM inbounds,
  183. JSON_EACH(JSON_EXTRACT(inbounds.settings, '$.clients')) AS client
  184. `).Scan(&rows).Error
  185. if err != nil {
  186. return nil, err
  187. }
  188. result := make(map[string]string, len(rows))
  189. for _, r := range rows {
  190. email := strings.ToLower(strings.Trim(r.Email, "\""))
  191. if email == "" {
  192. continue
  193. }
  194. subID := strings.Trim(r.SubID, "\"")
  195. if existing, ok := result[email]; ok {
  196. if existing != subID {
  197. result[email] = ""
  198. }
  199. continue
  200. }
  201. result[email] = subID
  202. }
  203. return result, nil
  204. }
  205. func lowerAll(in []string) []string {
  206. out := make([]string, len(in))
  207. for i, s := range in {
  208. out[i] = strings.ToLower(s)
  209. }
  210. return out
  211. }
  212. // emailUsedByOtherInbounds reports whether email lives in any inbound other
  213. // than exceptInboundId. Empty email returns false.
  214. func (s *InboundService) emailUsedByOtherInbounds(email string, exceptInboundId int) (bool, error) {
  215. if email == "" {
  216. return false, nil
  217. }
  218. db := database.GetDB()
  219. var count int64
  220. err := db.Raw(`
  221. SELECT COUNT(*)
  222. FROM inbounds,
  223. JSON_EACH(JSON_EXTRACT(inbounds.settings, '$.clients')) AS client
  224. WHERE inbounds.id != ?
  225. AND LOWER(JSON_EXTRACT(client.value, '$.email')) = LOWER(?)
  226. `, exceptInboundId, email).Scan(&count).Error
  227. if err != nil {
  228. return false, err
  229. }
  230. return count > 0, nil
  231. }
  232. // checkEmailsExistForClients validates a batch of incoming clients. An email
  233. // collides only when the existing holder has a different (or empty) subId —
  234. // matching non-empty subIds let multiple inbounds share one identity.
  235. func (s *InboundService) checkEmailsExistForClients(clients []model.Client) (string, error) {
  236. emailSubIDs, err := s.getAllEmailSubIDs()
  237. if err != nil {
  238. return "", err
  239. }
  240. seen := make(map[string]string, len(clients))
  241. for _, client := range clients {
  242. if client.Email == "" {
  243. continue
  244. }
  245. key := strings.ToLower(client.Email)
  246. // Within the same payload, the same email must carry the same subId;
  247. // otherwise we would silently merge two distinct identities.
  248. if prev, ok := seen[key]; ok {
  249. if prev != client.SubID || client.SubID == "" {
  250. return client.Email, nil
  251. }
  252. continue
  253. }
  254. seen[key] = client.SubID
  255. if existingSub, ok := emailSubIDs[key]; ok {
  256. if client.SubID == "" || existingSub == "" || existingSub != client.SubID {
  257. return client.Email, nil
  258. }
  259. }
  260. }
  261. return "", nil
  262. }
  263. // normalizeStreamSettings clears StreamSettings for protocols that don't use it.
  264. // Only vmess, vless, trojan, shadowsocks, and hysteria protocols use streamSettings.
  265. func (s *InboundService) normalizeStreamSettings(inbound *model.Inbound) {
  266. protocolsWithStream := map[model.Protocol]bool{
  267. model.VMESS: true,
  268. model.VLESS: true,
  269. model.Trojan: true,
  270. model.Shadowsocks: true,
  271. model.Hysteria: true,
  272. model.Hysteria2: true,
  273. }
  274. if !protocolsWithStream[inbound.Protocol] {
  275. inbound.StreamSettings = ""
  276. }
  277. }
  278. // AddInbound creates a new inbound configuration.
  279. // It validates port uniqueness, client email uniqueness, and required fields,
  280. // then saves the inbound to the database and optionally adds it to the running Xray instance.
  281. // Returns the created inbound, whether Xray needs restart, and any error.
  282. func (s *InboundService) AddInbound(inbound *model.Inbound) (*model.Inbound, bool, error) {
  283. // Normalize streamSettings based on protocol
  284. s.normalizeStreamSettings(inbound)
  285. exist, err := s.checkPortConflict(inbound, 0)
  286. if err != nil {
  287. return inbound, false, err
  288. }
  289. if exist {
  290. return inbound, false, common.NewError("Port already exists:", inbound.Port)
  291. }
  292. inbound.Tag, err = s.resolveInboundTag(inbound, 0)
  293. if err != nil {
  294. return inbound, false, err
  295. }
  296. clients, err := s.GetClients(inbound)
  297. if err != nil {
  298. return inbound, false, err
  299. }
  300. existEmail, err := s.checkEmailsExistForClients(clients)
  301. if err != nil {
  302. return inbound, false, err
  303. }
  304. if existEmail != "" {
  305. return inbound, false, common.NewError("Duplicate email:", existEmail)
  306. }
  307. // Ensure created_at and updated_at on clients in settings
  308. if len(clients) > 0 {
  309. var settings map[string]any
  310. if err2 := json.Unmarshal([]byte(inbound.Settings), &settings); err2 == nil && settings != nil {
  311. now := time.Now().Unix() * 1000
  312. updatedClients := make([]model.Client, 0, len(clients))
  313. for _, c := range clients {
  314. if c.CreatedAt == 0 {
  315. c.CreatedAt = now
  316. }
  317. c.UpdatedAt = now
  318. updatedClients = append(updatedClients, c)
  319. }
  320. settings["clients"] = updatedClients
  321. if bs, err3 := json.MarshalIndent(settings, "", " "); err3 == nil {
  322. inbound.Settings = string(bs)
  323. } else {
  324. logger.Debug("Unable to marshal inbound settings with timestamps:", err3)
  325. }
  326. } else if err2 != nil {
  327. logger.Debug("Unable to parse inbound settings for timestamps:", err2)
  328. }
  329. }
  330. // Secure client ID
  331. for _, client := range clients {
  332. switch inbound.Protocol {
  333. case "trojan":
  334. if client.Password == "" {
  335. return inbound, false, common.NewError("empty client ID")
  336. }
  337. case "shadowsocks":
  338. if client.Email == "" {
  339. return inbound, false, common.NewError("empty client ID")
  340. }
  341. case "hysteria", "hysteria2":
  342. if client.Auth == "" {
  343. return inbound, false, common.NewError("empty client ID")
  344. }
  345. default:
  346. if client.ID == "" {
  347. return inbound, false, common.NewError("empty client ID")
  348. }
  349. }
  350. }
  351. db := database.GetDB()
  352. tx := db.Begin()
  353. defer func() {
  354. if err == nil {
  355. tx.Commit()
  356. } else {
  357. tx.Rollback()
  358. }
  359. }()
  360. err = tx.Save(inbound).Error
  361. if err == nil {
  362. if len(inbound.ClientStats) == 0 {
  363. for _, client := range clients {
  364. s.AddClientStat(tx, inbound.Id, &client)
  365. }
  366. }
  367. } else {
  368. return inbound, false, err
  369. }
  370. needRestart := false
  371. if inbound.Enable {
  372. rt, rterr := s.runtimeFor(inbound)
  373. if rterr != nil {
  374. err = rterr
  375. return inbound, false, err
  376. }
  377. if err1 := rt.AddInbound(context.Background(), inbound); err1 == nil {
  378. logger.Debug("New inbound added on", rt.Name(), ":", inbound.Tag)
  379. } else {
  380. logger.Debug("Unable to add inbound on", rt.Name(), ":", err1)
  381. if inbound.NodeID != nil {
  382. err = err1
  383. return inbound, false, err
  384. }
  385. needRestart = true
  386. }
  387. }
  388. return inbound, needRestart, err
  389. }
  390. func (s *InboundService) DelInbound(id int) (bool, error) {
  391. db := database.GetDB()
  392. needRestart := false
  393. var ib model.Inbound
  394. loadErr := db.Model(model.Inbound{}).Where("id = ? and enable = ?", id, true).First(&ib).Error
  395. if loadErr == nil {
  396. rt, rterr := s.runtimeFor(&ib)
  397. if rterr != nil {
  398. logger.Warning("DelInbound: runtime lookup failed, deleting central row anyway:", rterr)
  399. if ib.NodeID == nil {
  400. needRestart = true
  401. }
  402. } else if err1 := rt.DelInbound(context.Background(), &ib); err1 == nil {
  403. logger.Debug("Inbound deleted on", rt.Name(), ":", ib.Tag)
  404. } else {
  405. logger.Warning("DelInbound on", rt.Name(), "failed, deleting central row anyway:", err1)
  406. if ib.NodeID == nil {
  407. needRestart = true
  408. }
  409. }
  410. } else {
  411. logger.Debug("No enabled inbound found to remove by api, id:", id)
  412. }
  413. // Delete client traffics of inbounds
  414. err := db.Where("inbound_id = ?", id).Delete(xray.ClientTraffic{}).Error
  415. if err != nil {
  416. return false, err
  417. }
  418. inbound, err := s.GetInbound(id)
  419. if err != nil {
  420. return false, err
  421. }
  422. clients, err := s.GetClients(inbound)
  423. if err != nil {
  424. return false, err
  425. }
  426. // Bulk-delete client IPs for every email in this inbound. The previous
  427. // per-client loop fired one DELETE per row — at 7k+ clients that meant
  428. // thousands of synchronous SQL roundtrips and a multi-second freeze.
  429. // Chunked to stay under SQLite's bind-variable limit on huge inbounds.
  430. if len(clients) > 0 {
  431. emails := make([]string, 0, len(clients))
  432. for i := range clients {
  433. if clients[i].Email != "" {
  434. emails = append(emails, clients[i].Email)
  435. }
  436. }
  437. for _, batch := range chunkStrings(uniqueNonEmptyStrings(emails), sqliteMaxVars) {
  438. if err := db.Where("client_email IN ?", batch).
  439. Delete(model.InboundClientIps{}).Error; err != nil {
  440. return false, err
  441. }
  442. }
  443. }
  444. return needRestart, db.Delete(model.Inbound{}, id).Error
  445. }
  446. func (s *InboundService) GetInbound(id int) (*model.Inbound, error) {
  447. db := database.GetDB()
  448. inbound := &model.Inbound{}
  449. err := db.Model(model.Inbound{}).First(inbound, id).Error
  450. if err != nil {
  451. return nil, err
  452. }
  453. return inbound, nil
  454. }
  455. // SetInboundEnable toggles only the enable flag of an inbound, without
  456. // rewriting the (potentially multi-MB) settings JSON. Used by the UI's
  457. // per-row enable switch — for inbounds with thousands of clients the full
  458. // UpdateInbound path is an order of magnitude too slow for an interactive
  459. // toggle (parses + reserialises every client, runs O(N) traffic diff).
  460. //
  461. // Returns (needRestart, error). needRestart is true when the xray runtime
  462. // could not be re-synced from the cached config and a full restart is
  463. // required to pick up the change.
  464. func (s *InboundService) SetInboundEnable(id int, enable bool) (bool, error) {
  465. inbound, err := s.GetInbound(id)
  466. if err != nil {
  467. return false, err
  468. }
  469. if inbound.Enable == enable {
  470. return false, nil
  471. }
  472. db := database.GetDB()
  473. if err := db.Model(model.Inbound{}).Where("id = ?", id).
  474. Update("enable", enable).Error; err != nil {
  475. return false, err
  476. }
  477. inbound.Enable = enable
  478. needRestart := false
  479. rt, rterr := s.runtimeFor(inbound)
  480. if rterr != nil {
  481. if inbound.NodeID != nil {
  482. return false, rterr
  483. }
  484. return true, nil
  485. }
  486. if err := rt.DelInbound(context.Background(), inbound); err != nil &&
  487. !strings.Contains(err.Error(), "not found") {
  488. logger.Debug("SetInboundEnable: DelInbound on", rt.Name(), "failed:", err)
  489. needRestart = true
  490. }
  491. if !enable {
  492. return needRestart, nil
  493. }
  494. addTarget := inbound
  495. if inbound.NodeID == nil {
  496. runtimeInbound, err := s.buildRuntimeInboundForAPI(db, inbound)
  497. if err != nil {
  498. logger.Debug("SetInboundEnable: build runtime config failed:", err)
  499. return true, nil
  500. }
  501. addTarget = runtimeInbound
  502. }
  503. if err := rt.AddInbound(context.Background(), addTarget); err != nil {
  504. logger.Debug("SetInboundEnable: AddInbound on", rt.Name(), "failed:", err)
  505. if inbound.NodeID != nil {
  506. return false, err
  507. }
  508. needRestart = true
  509. }
  510. return needRestart, nil
  511. }
  512. func (s *InboundService) UpdateInbound(inbound *model.Inbound) (*model.Inbound, bool, error) {
  513. // Normalize streamSettings based on protocol
  514. s.normalizeStreamSettings(inbound)
  515. exist, err := s.checkPortConflict(inbound, inbound.Id)
  516. if err != nil {
  517. return inbound, false, err
  518. }
  519. if exist {
  520. return inbound, false, common.NewError("Port already exists:", inbound.Port)
  521. }
  522. oldInbound, err := s.GetInbound(inbound.Id)
  523. if err != nil {
  524. return inbound, false, err
  525. }
  526. tag := oldInbound.Tag
  527. db := database.GetDB()
  528. tx := db.Begin()
  529. defer func() {
  530. if err != nil {
  531. tx.Rollback()
  532. } else {
  533. tx.Commit()
  534. }
  535. }()
  536. err = s.updateClientTraffics(tx, oldInbound, inbound)
  537. if err != nil {
  538. return inbound, false, err
  539. }
  540. // Ensure created_at and updated_at exist in inbound.Settings clients
  541. {
  542. var oldSettings map[string]any
  543. _ = json.Unmarshal([]byte(oldInbound.Settings), &oldSettings)
  544. emailToCreated := map[string]int64{}
  545. emailToUpdated := map[string]int64{}
  546. if oldSettings != nil {
  547. if oc, ok := oldSettings["clients"].([]any); ok {
  548. for _, it := range oc {
  549. if m, ok2 := it.(map[string]any); ok2 {
  550. if email, ok3 := m["email"].(string); ok3 {
  551. switch v := m["created_at"].(type) {
  552. case float64:
  553. emailToCreated[email] = int64(v)
  554. case int64:
  555. emailToCreated[email] = v
  556. }
  557. switch v := m["updated_at"].(type) {
  558. case float64:
  559. emailToUpdated[email] = int64(v)
  560. case int64:
  561. emailToUpdated[email] = v
  562. }
  563. }
  564. }
  565. }
  566. }
  567. }
  568. var newSettings map[string]any
  569. if err2 := json.Unmarshal([]byte(inbound.Settings), &newSettings); err2 == nil && newSettings != nil {
  570. now := time.Now().Unix() * 1000
  571. if nSlice, ok := newSettings["clients"].([]any); ok {
  572. for i := range nSlice {
  573. if m, ok2 := nSlice[i].(map[string]any); ok2 {
  574. email, _ := m["email"].(string)
  575. if _, ok3 := m["created_at"]; !ok3 {
  576. if v, ok4 := emailToCreated[email]; ok4 && v > 0 {
  577. m["created_at"] = v
  578. } else {
  579. m["created_at"] = now
  580. }
  581. }
  582. // Preserve client's updated_at if present; do not bump on parent inbound update
  583. if _, hasUpdated := m["updated_at"]; !hasUpdated {
  584. if v, ok4 := emailToUpdated[email]; ok4 && v > 0 {
  585. m["updated_at"] = v
  586. }
  587. }
  588. nSlice[i] = m
  589. }
  590. }
  591. newSettings["clients"] = nSlice
  592. if bs, err3 := json.MarshalIndent(newSettings, "", " "); err3 == nil {
  593. inbound.Settings = string(bs)
  594. }
  595. }
  596. }
  597. }
  598. oldInbound.Total = inbound.Total
  599. oldInbound.Remark = inbound.Remark
  600. oldInbound.Enable = inbound.Enable
  601. oldInbound.ExpiryTime = inbound.ExpiryTime
  602. oldInbound.TrafficReset = inbound.TrafficReset
  603. oldInbound.Listen = inbound.Listen
  604. oldInbound.Port = inbound.Port
  605. oldInbound.Protocol = inbound.Protocol
  606. oldInbound.Settings = inbound.Settings
  607. oldInbound.StreamSettings = inbound.StreamSettings
  608. oldInbound.Sniffing = inbound.Sniffing
  609. oldInbound.Tag, err = s.resolveInboundTag(inbound, inbound.Id)
  610. if err != nil {
  611. return inbound, false, err
  612. }
  613. needRestart := false
  614. rt, rterr := s.runtimeFor(oldInbound)
  615. if rterr != nil {
  616. if oldInbound.NodeID != nil {
  617. err = rterr
  618. return inbound, false, err
  619. }
  620. needRestart = true
  621. } else {
  622. oldSnapshot := *oldInbound
  623. oldSnapshot.Tag = tag
  624. if oldInbound.NodeID == nil {
  625. if err2 := rt.DelInbound(context.Background(), &oldSnapshot); err2 == nil {
  626. logger.Debug("Old inbound deleted on", rt.Name(), ":", tag)
  627. }
  628. if inbound.Enable {
  629. runtimeInbound, err2 := s.buildRuntimeInboundForAPI(tx, oldInbound)
  630. if err2 != nil {
  631. logger.Debug("Unable to prepare runtime inbound config:", err2)
  632. needRestart = true
  633. } else if err2 := rt.AddInbound(context.Background(), runtimeInbound); err2 == nil {
  634. logger.Debug("Updated inbound added on", rt.Name(), ":", oldInbound.Tag)
  635. } else {
  636. logger.Debug("Unable to update inbound on", rt.Name(), ":", err2)
  637. needRestart = true
  638. }
  639. }
  640. } else {
  641. if !inbound.Enable {
  642. if err2 := rt.DelInbound(context.Background(), &oldSnapshot); err2 != nil {
  643. err = err2
  644. return inbound, false, err
  645. }
  646. } else if err2 := rt.UpdateInbound(context.Background(), &oldSnapshot, oldInbound); err2 != nil {
  647. err = err2
  648. return inbound, false, err
  649. }
  650. }
  651. }
  652. return inbound, needRestart, tx.Save(oldInbound).Error
  653. }
  654. func (s *InboundService) buildRuntimeInboundForAPI(tx *gorm.DB, inbound *model.Inbound) (*model.Inbound, error) {
  655. if inbound == nil {
  656. return nil, fmt.Errorf("inbound is nil")
  657. }
  658. runtimeInbound := *inbound
  659. settings := map[string]any{}
  660. if err := json.Unmarshal([]byte(inbound.Settings), &settings); err != nil {
  661. return nil, err
  662. }
  663. clients, ok := settings["clients"].([]any)
  664. if !ok {
  665. return &runtimeInbound, nil
  666. }
  667. var clientStats []xray.ClientTraffic
  668. err := tx.Model(xray.ClientTraffic{}).
  669. Where("inbound_id = ?", inbound.Id).
  670. Select("email", "enable").
  671. Find(&clientStats).Error
  672. if err != nil {
  673. return nil, err
  674. }
  675. enableMap := make(map[string]bool, len(clientStats))
  676. for _, clientTraffic := range clientStats {
  677. enableMap[clientTraffic.Email] = clientTraffic.Enable
  678. }
  679. finalClients := make([]any, 0, len(clients))
  680. for _, client := range clients {
  681. c, ok := client.(map[string]any)
  682. if !ok {
  683. continue
  684. }
  685. email, _ := c["email"].(string)
  686. if enable, exists := enableMap[email]; exists && !enable {
  687. continue
  688. }
  689. if manualEnable, ok := c["enable"].(bool); ok && !manualEnable {
  690. continue
  691. }
  692. finalClients = append(finalClients, c)
  693. }
  694. settings["clients"] = finalClients
  695. modifiedSettings, err := json.MarshalIndent(settings, "", " ")
  696. if err != nil {
  697. return nil, err
  698. }
  699. runtimeInbound.Settings = string(modifiedSettings)
  700. return &runtimeInbound, nil
  701. }
  702. // updateClientTraffics syncs the ClientTraffic rows with the inbound's clients
  703. // list: removes rows for emails that disappeared, inserts rows for newly-added
  704. // emails. Uses sets for O(N) lookup — the previous nested-loop implementation
  705. // was O(N²) and degraded into multi-second pauses on inbounds with thousands
  706. // of clients (toggling, saving, or deleting any such inbound felt frozen).
  707. func (s *InboundService) updateClientTraffics(tx *gorm.DB, oldInbound *model.Inbound, newInbound *model.Inbound) error {
  708. oldClients, err := s.GetClients(oldInbound)
  709. if err != nil {
  710. return err
  711. }
  712. newClients, err := s.GetClients(newInbound)
  713. if err != nil {
  714. return err
  715. }
  716. // Email is the unique key for ClientTraffic rows. Clients without an
  717. // email have no stats row to sync — skip them on both sides instead of
  718. // risking a unique-constraint hit or accidental delete of an unrelated row.
  719. oldEmails := make(map[string]struct{}, len(oldClients))
  720. for i := range oldClients {
  721. if oldClients[i].Email == "" {
  722. continue
  723. }
  724. oldEmails[oldClients[i].Email] = struct{}{}
  725. }
  726. newEmails := make(map[string]struct{}, len(newClients))
  727. for i := range newClients {
  728. if newClients[i].Email == "" {
  729. continue
  730. }
  731. newEmails[newClients[i].Email] = struct{}{}
  732. }
  733. // Drop stats rows for removed emails — but not when a sibling inbound
  734. // still references the email, since the row is the shared accumulator.
  735. for i := range oldClients {
  736. email := oldClients[i].Email
  737. if email == "" {
  738. continue
  739. }
  740. if _, kept := newEmails[email]; kept {
  741. continue
  742. }
  743. stillUsed, err := s.emailUsedByOtherInbounds(email, oldInbound.Id)
  744. if err != nil {
  745. return err
  746. }
  747. if stillUsed {
  748. continue
  749. }
  750. if err := s.DelClientStat(tx, email); err != nil {
  751. return err
  752. }
  753. }
  754. for i := range newClients {
  755. email := newClients[i].Email
  756. if email == "" {
  757. continue
  758. }
  759. if _, existed := oldEmails[email]; existed {
  760. if err := s.UpdateClientStat(tx, email, &newClients[i]); err != nil {
  761. return err
  762. }
  763. continue
  764. }
  765. if err := s.AddClientStat(tx, oldInbound.Id, &newClients[i]); err != nil {
  766. return err
  767. }
  768. }
  769. return nil
  770. }
  771. func (s *InboundService) AddInboundClient(data *model.Inbound) (bool, error) {
  772. clients, err := s.GetClients(data)
  773. if err != nil {
  774. return false, err
  775. }
  776. var settings map[string]any
  777. err = json.Unmarshal([]byte(data.Settings), &settings)
  778. if err != nil {
  779. return false, err
  780. }
  781. interfaceClients := settings["clients"].([]any)
  782. // Add timestamps for new clients being appended
  783. nowTs := time.Now().Unix() * 1000
  784. for i := range interfaceClients {
  785. if cm, ok := interfaceClients[i].(map[string]any); ok {
  786. if _, ok2 := cm["created_at"]; !ok2 {
  787. cm["created_at"] = nowTs
  788. }
  789. cm["updated_at"] = nowTs
  790. interfaceClients[i] = cm
  791. }
  792. }
  793. existEmail, err := s.checkEmailsExistForClients(clients)
  794. if err != nil {
  795. return false, err
  796. }
  797. if existEmail != "" {
  798. return false, common.NewError("Duplicate email:", existEmail)
  799. }
  800. oldInbound, err := s.GetInbound(data.Id)
  801. if err != nil {
  802. return false, err
  803. }
  804. // Secure client ID
  805. for _, client := range clients {
  806. if strings.TrimSpace(client.Email) == "" {
  807. return false, common.NewError("client email is required")
  808. }
  809. switch oldInbound.Protocol {
  810. case "trojan":
  811. if client.Password == "" {
  812. return false, common.NewError("empty client ID")
  813. }
  814. case "shadowsocks":
  815. if client.Email == "" {
  816. return false, common.NewError("empty client ID")
  817. }
  818. case "hysteria", "hysteria2":
  819. if client.Auth == "" {
  820. return false, common.NewError("empty client ID")
  821. }
  822. default:
  823. if client.ID == "" {
  824. return false, common.NewError("empty client ID")
  825. }
  826. }
  827. }
  828. var oldSettings map[string]any
  829. err = json.Unmarshal([]byte(oldInbound.Settings), &oldSettings)
  830. if err != nil {
  831. return false, err
  832. }
  833. oldClients := oldSettings["clients"].([]any)
  834. oldClients = append(oldClients, interfaceClients...)
  835. oldSettings["clients"] = oldClients
  836. newSettings, err := json.MarshalIndent(oldSettings, "", " ")
  837. if err != nil {
  838. return false, err
  839. }
  840. oldInbound.Settings = string(newSettings)
  841. db := database.GetDB()
  842. tx := db.Begin()
  843. defer func() {
  844. if err != nil {
  845. tx.Rollback()
  846. } else {
  847. tx.Commit()
  848. }
  849. }()
  850. needRestart := false
  851. rt, rterr := s.runtimeFor(oldInbound)
  852. if rterr != nil {
  853. if oldInbound.NodeID != nil {
  854. err = rterr
  855. return false, err
  856. }
  857. needRestart = true
  858. } else if oldInbound.NodeID == nil {
  859. for _, client := range clients {
  860. if len(client.Email) == 0 {
  861. needRestart = true
  862. continue
  863. }
  864. s.AddClientStat(tx, data.Id, &client)
  865. if !client.Enable {
  866. continue
  867. }
  868. cipher := ""
  869. if oldInbound.Protocol == "shadowsocks" {
  870. cipher = oldSettings["method"].(string)
  871. }
  872. err1 := rt.AddUser(context.Background(), oldInbound, map[string]any{
  873. "email": client.Email,
  874. "id": client.ID,
  875. "auth": client.Auth,
  876. "security": client.Security,
  877. "flow": client.Flow,
  878. "password": client.Password,
  879. "cipher": cipher,
  880. })
  881. if err1 == nil {
  882. logger.Debug("Client added on", rt.Name(), ":", client.Email)
  883. } else {
  884. logger.Debug("Error in adding client on", rt.Name(), ":", err1)
  885. needRestart = true
  886. }
  887. }
  888. } else {
  889. for _, client := range clients {
  890. if len(client.Email) > 0 {
  891. s.AddClientStat(tx, data.Id, &client)
  892. }
  893. }
  894. if err1 := rt.UpdateInbound(context.Background(), oldInbound, oldInbound); err1 != nil {
  895. err = err1
  896. return false, err
  897. }
  898. }
  899. return needRestart, tx.Save(oldInbound).Error
  900. }
  901. func (s *InboundService) getClientPrimaryKey(protocol model.Protocol, client model.Client) string {
  902. switch protocol {
  903. case model.Trojan:
  904. return client.Password
  905. case model.Shadowsocks:
  906. return client.Email
  907. case model.Hysteria:
  908. return client.Auth
  909. default:
  910. return client.ID
  911. }
  912. }
  913. func (s *InboundService) writeBackClientSubID(sourceInboundID int, sourceProtocol model.Protocol, client model.Client, subID string) (bool, error) {
  914. client.SubID = subID
  915. client.UpdatedAt = time.Now().UnixMilli()
  916. clientID := s.getClientPrimaryKey(sourceProtocol, client)
  917. if clientID == "" {
  918. return false, common.NewError("empty client ID")
  919. }
  920. settingsBytes, err := json.Marshal(map[string][]model.Client{
  921. "clients": {client},
  922. })
  923. if err != nil {
  924. return false, err
  925. }
  926. updatePayload := &model.Inbound{
  927. Id: sourceInboundID,
  928. Settings: string(settingsBytes),
  929. }
  930. return s.UpdateInboundClient(updatePayload, clientID)
  931. }
  932. func (s *InboundService) generateRandomCredential(targetProtocol model.Protocol) string {
  933. switch targetProtocol {
  934. case model.VMESS, model.VLESS:
  935. return uuid.NewString()
  936. default:
  937. return strings.ReplaceAll(uuid.NewString(), "-", "")
  938. }
  939. }
  940. func (s *InboundService) buildTargetClientFromSource(source model.Client, targetProtocol model.Protocol, email string, flow string) (model.Client, error) {
  941. nowTs := time.Now().UnixMilli()
  942. target := source
  943. target.Email = email
  944. target.CreatedAt = nowTs
  945. target.UpdatedAt = nowTs
  946. target.ID = ""
  947. target.Password = ""
  948. target.Auth = ""
  949. target.Flow = ""
  950. switch targetProtocol {
  951. case model.VMESS:
  952. target.ID = s.generateRandomCredential(targetProtocol)
  953. case model.VLESS:
  954. target.ID = s.generateRandomCredential(targetProtocol)
  955. if flow == "xtls-rprx-vision" || flow == "xtls-rprx-vision-udp443" {
  956. target.Flow = flow
  957. }
  958. case model.Trojan, model.Shadowsocks:
  959. target.Password = s.generateRandomCredential(targetProtocol)
  960. case model.Hysteria:
  961. target.Auth = s.generateRandomCredential(targetProtocol)
  962. default:
  963. target.ID = s.generateRandomCredential(targetProtocol)
  964. }
  965. return target, nil
  966. }
  967. func (s *InboundService) nextAvailableCopiedEmail(originalEmail string, targetID int, occupied map[string]struct{}) string {
  968. base := fmt.Sprintf("%s_%d", originalEmail, targetID)
  969. candidate := base
  970. suffix := 0
  971. for {
  972. if _, exists := occupied[strings.ToLower(candidate)]; !exists {
  973. occupied[strings.ToLower(candidate)] = struct{}{}
  974. return candidate
  975. }
  976. suffix++
  977. candidate = fmt.Sprintf("%s_%d", base, suffix)
  978. }
  979. }
  980. func (s *InboundService) CopyInboundClients(targetInboundID int, sourceInboundID int, clientEmails []string, flow string) (*CopyClientsResult, bool, error) {
  981. result := &CopyClientsResult{
  982. Added: []string{},
  983. Skipped: []string{},
  984. Errors: []string{},
  985. }
  986. if targetInboundID == sourceInboundID {
  987. return result, false, common.NewError("source and target inbounds must be different")
  988. }
  989. targetInbound, err := s.GetInbound(targetInboundID)
  990. if err != nil {
  991. return result, false, err
  992. }
  993. sourceInbound, err := s.GetInbound(sourceInboundID)
  994. if err != nil {
  995. return result, false, err
  996. }
  997. sourceClients, err := s.GetClients(sourceInbound)
  998. if err != nil {
  999. return result, false, err
  1000. }
  1001. if len(sourceClients) == 0 {
  1002. return result, false, nil
  1003. }
  1004. allowedEmails := map[string]struct{}{}
  1005. if len(clientEmails) > 0 {
  1006. for _, email := range clientEmails {
  1007. allowedEmails[strings.ToLower(strings.TrimSpace(email))] = struct{}{}
  1008. }
  1009. }
  1010. occupiedEmails := map[string]struct{}{}
  1011. allEmails, err := s.getAllEmails()
  1012. if err != nil {
  1013. return result, false, err
  1014. }
  1015. for _, email := range allEmails {
  1016. clean := strings.Trim(email, "\"")
  1017. if clean != "" {
  1018. occupiedEmails[strings.ToLower(clean)] = struct{}{}
  1019. }
  1020. }
  1021. newClients := make([]model.Client, 0)
  1022. needRestart := false
  1023. for _, sourceClient := range sourceClients {
  1024. originalEmail := strings.TrimSpace(sourceClient.Email)
  1025. if originalEmail == "" {
  1026. continue
  1027. }
  1028. if len(allowedEmails) > 0 {
  1029. if _, ok := allowedEmails[strings.ToLower(originalEmail)]; !ok {
  1030. continue
  1031. }
  1032. }
  1033. if sourceClient.SubID == "" {
  1034. newSubID := uuid.NewString()
  1035. subNeedRestart, subErr := s.writeBackClientSubID(sourceInbound.Id, sourceInbound.Protocol, sourceClient, newSubID)
  1036. if subErr != nil {
  1037. result.Errors = append(result.Errors, fmt.Sprintf("%s: failed to write source subId: %v", originalEmail, subErr))
  1038. continue
  1039. }
  1040. if subNeedRestart {
  1041. needRestart = true
  1042. }
  1043. sourceClient.SubID = newSubID
  1044. }
  1045. targetEmail := s.nextAvailableCopiedEmail(originalEmail, targetInboundID, occupiedEmails)
  1046. targetClient, buildErr := s.buildTargetClientFromSource(sourceClient, targetInbound.Protocol, targetEmail, flow)
  1047. if buildErr != nil {
  1048. result.Errors = append(result.Errors, fmt.Sprintf("%s: %v", originalEmail, buildErr))
  1049. continue
  1050. }
  1051. newClients = append(newClients, targetClient)
  1052. result.Added = append(result.Added, targetEmail)
  1053. }
  1054. if len(newClients) == 0 {
  1055. return result, needRestart, nil
  1056. }
  1057. settingsPayload, err := json.Marshal(map[string][]model.Client{
  1058. "clients": newClients,
  1059. })
  1060. if err != nil {
  1061. return result, needRestart, err
  1062. }
  1063. addNeedRestart, err := s.AddInboundClient(&model.Inbound{
  1064. Id: targetInboundID,
  1065. Settings: string(settingsPayload),
  1066. })
  1067. if err != nil {
  1068. return result, needRestart, err
  1069. }
  1070. if addNeedRestart {
  1071. needRestart = true
  1072. }
  1073. return result, needRestart, nil
  1074. }
  1075. func (s *InboundService) DelInboundClient(inboundId int, clientId string) (bool, error) {
  1076. oldInbound, err := s.GetInbound(inboundId)
  1077. if err != nil {
  1078. logger.Error("Load Old Data Error")
  1079. return false, err
  1080. }
  1081. var settings map[string]any
  1082. err = json.Unmarshal([]byte(oldInbound.Settings), &settings)
  1083. if err != nil {
  1084. return false, err
  1085. }
  1086. email := ""
  1087. client_key := "id"
  1088. switch oldInbound.Protocol {
  1089. case "trojan":
  1090. client_key = "password"
  1091. case "shadowsocks":
  1092. client_key = "email"
  1093. case "hysteria", "hysteria2":
  1094. client_key = "auth"
  1095. }
  1096. interfaceClients := settings["clients"].([]any)
  1097. var newClients []any
  1098. needApiDel := false
  1099. clientFound := false
  1100. for _, client := range interfaceClients {
  1101. c := client.(map[string]any)
  1102. c_id := c[client_key].(string)
  1103. if c_id == clientId {
  1104. clientFound = true
  1105. email, _ = c["email"].(string)
  1106. needApiDel, _ = c["enable"].(bool)
  1107. } else {
  1108. newClients = append(newClients, client)
  1109. }
  1110. }
  1111. if !clientFound {
  1112. return false, common.NewError("Client Not Found In Inbound For ID:", clientId)
  1113. }
  1114. if len(newClients) == 0 {
  1115. return false, common.NewError("no client remained in Inbound")
  1116. }
  1117. settings["clients"] = newClients
  1118. newSettings, err := json.MarshalIndent(settings, "", " ")
  1119. if err != nil {
  1120. return false, err
  1121. }
  1122. oldInbound.Settings = string(newSettings)
  1123. db := database.GetDB()
  1124. // Keep the client_traffics row and IPs alive when another inbound still
  1125. // references this email — siblings depend on the shared accounting state.
  1126. emailShared, err := s.emailUsedByOtherInbounds(email, inboundId)
  1127. if err != nil {
  1128. return false, err
  1129. }
  1130. if !emailShared {
  1131. err = s.DelClientIPs(db, email)
  1132. if err != nil {
  1133. logger.Error("Error in delete client IPs")
  1134. return false, err
  1135. }
  1136. }
  1137. needRestart := false
  1138. if len(email) > 0 {
  1139. notDepleted := true
  1140. err = db.Model(xray.ClientTraffic{}).Select("enable").Where("email = ?", email).First(&notDepleted).Error
  1141. if err != nil {
  1142. logger.Error("Get stats error")
  1143. return false, err
  1144. }
  1145. if !emailShared {
  1146. err = s.DelClientStat(db, email)
  1147. if err != nil {
  1148. logger.Error("Delete stats Data Error")
  1149. return false, err
  1150. }
  1151. }
  1152. if needApiDel && notDepleted {
  1153. rt, rterr := s.runtimeFor(oldInbound)
  1154. if rterr != nil {
  1155. if oldInbound.NodeID != nil {
  1156. return false, rterr
  1157. }
  1158. needRestart = true
  1159. } else if oldInbound.NodeID == nil {
  1160. err1 := rt.RemoveUser(context.Background(), oldInbound, email)
  1161. if err1 == nil {
  1162. logger.Debug("Client deleted on", rt.Name(), ":", email)
  1163. needRestart = false
  1164. } else if strings.Contains(err1.Error(), fmt.Sprintf("User %s not found.", email)) {
  1165. logger.Debug("User is already deleted. Nothing to do more...")
  1166. } else {
  1167. logger.Debug("Error in deleting client on", rt.Name(), ":", err1)
  1168. needRestart = true
  1169. }
  1170. } else {
  1171. if err1 := rt.UpdateInbound(context.Background(), oldInbound, oldInbound); err1 != nil {
  1172. return false, err1
  1173. }
  1174. }
  1175. }
  1176. }
  1177. return needRestart, db.Save(oldInbound).Error
  1178. }
  1179. func (s *InboundService) UpdateInboundClient(data *model.Inbound, clientId string) (bool, error) {
  1180. // TODO: check if TrafficReset field is updating
  1181. clients, err := s.GetClients(data)
  1182. if err != nil {
  1183. return false, err
  1184. }
  1185. var settings map[string]any
  1186. err = json.Unmarshal([]byte(data.Settings), &settings)
  1187. if err != nil {
  1188. return false, err
  1189. }
  1190. interfaceClients := settings["clients"].([]any)
  1191. oldInbound, err := s.GetInbound(data.Id)
  1192. if err != nil {
  1193. return false, err
  1194. }
  1195. oldClients, err := s.GetClients(oldInbound)
  1196. if err != nil {
  1197. return false, err
  1198. }
  1199. oldEmail := ""
  1200. newClientId := ""
  1201. clientIndex := -1
  1202. for index, oldClient := range oldClients {
  1203. oldClientId := ""
  1204. switch oldInbound.Protocol {
  1205. case "trojan":
  1206. oldClientId = oldClient.Password
  1207. newClientId = clients[0].Password
  1208. case "shadowsocks":
  1209. oldClientId = oldClient.Email
  1210. newClientId = clients[0].Email
  1211. case "hysteria", "hysteria2":
  1212. oldClientId = oldClient.Auth
  1213. newClientId = clients[0].Auth
  1214. default:
  1215. oldClientId = oldClient.ID
  1216. newClientId = clients[0].ID
  1217. }
  1218. if clientId == oldClientId {
  1219. oldEmail = oldClient.Email
  1220. clientIndex = index
  1221. break
  1222. }
  1223. }
  1224. // Validate new client ID
  1225. if newClientId == "" || clientIndex == -1 {
  1226. return false, common.NewError("empty client ID")
  1227. }
  1228. if strings.TrimSpace(clients[0].Email) == "" {
  1229. return false, common.NewError("client email is required")
  1230. }
  1231. if clients[0].Email != oldEmail {
  1232. existEmail, err := s.checkEmailsExistForClients(clients)
  1233. if err != nil {
  1234. return false, err
  1235. }
  1236. if existEmail != "" {
  1237. return false, common.NewError("Duplicate email:", existEmail)
  1238. }
  1239. }
  1240. var oldSettings map[string]any
  1241. err = json.Unmarshal([]byte(oldInbound.Settings), &oldSettings)
  1242. if err != nil {
  1243. return false, err
  1244. }
  1245. settingsClients := oldSettings["clients"].([]any)
  1246. // Preserve created_at and set updated_at for the replacing client
  1247. var preservedCreated any
  1248. if clientIndex >= 0 && clientIndex < len(settingsClients) {
  1249. if oldMap, ok := settingsClients[clientIndex].(map[string]any); ok {
  1250. if v, ok2 := oldMap["created_at"]; ok2 {
  1251. preservedCreated = v
  1252. }
  1253. }
  1254. }
  1255. if len(interfaceClients) > 0 {
  1256. if newMap, ok := interfaceClients[0].(map[string]any); ok {
  1257. if preservedCreated == nil {
  1258. preservedCreated = time.Now().Unix() * 1000
  1259. }
  1260. newMap["created_at"] = preservedCreated
  1261. newMap["updated_at"] = time.Now().Unix() * 1000
  1262. interfaceClients[0] = newMap
  1263. }
  1264. }
  1265. settingsClients[clientIndex] = interfaceClients[0]
  1266. oldSettings["clients"] = settingsClients
  1267. // testseed is only meaningful when at least one VLESS client uses the exact
  1268. // xtls-rprx-vision flow. The client-edit path only rewrites a single client,
  1269. // so re-check the flow set here and strip a stale testseed when nothing in the
  1270. // inbound still warrants it. The full-inbound update path already handles this
  1271. // on the JS side via VLESSSettings.toJson().
  1272. if oldInbound.Protocol == model.VLESS {
  1273. hasVisionFlow := false
  1274. for _, c := range settingsClients {
  1275. cm, ok := c.(map[string]any)
  1276. if !ok {
  1277. continue
  1278. }
  1279. if flow, _ := cm["flow"].(string); flow == "xtls-rprx-vision" {
  1280. hasVisionFlow = true
  1281. break
  1282. }
  1283. }
  1284. if !hasVisionFlow {
  1285. delete(oldSettings, "testseed")
  1286. }
  1287. }
  1288. newSettings, err := json.MarshalIndent(oldSettings, "", " ")
  1289. if err != nil {
  1290. return false, err
  1291. }
  1292. oldInbound.Settings = string(newSettings)
  1293. db := database.GetDB()
  1294. tx := db.Begin()
  1295. defer func() {
  1296. if err != nil {
  1297. tx.Rollback()
  1298. } else {
  1299. tx.Commit()
  1300. }
  1301. }()
  1302. if len(clients[0].Email) > 0 {
  1303. if len(oldEmail) > 0 {
  1304. // Repointing onto an email that already has a row would collide on
  1305. // the unique constraint, so retire the donor and let the surviving
  1306. // row carry the merged identity.
  1307. emailUnchanged := strings.EqualFold(oldEmail, clients[0].Email)
  1308. targetExists := int64(0)
  1309. if !emailUnchanged {
  1310. if err = tx.Model(xray.ClientTraffic{}).Where("email = ?", clients[0].Email).Count(&targetExists).Error; err != nil {
  1311. return false, err
  1312. }
  1313. }
  1314. if emailUnchanged || targetExists == 0 {
  1315. err = s.UpdateClientStat(tx, oldEmail, &clients[0])
  1316. if err != nil {
  1317. return false, err
  1318. }
  1319. err = s.UpdateClientIPs(tx, oldEmail, clients[0].Email)
  1320. if err != nil {
  1321. return false, err
  1322. }
  1323. } else {
  1324. stillUsed, sErr := s.emailUsedByOtherInbounds(oldEmail, data.Id)
  1325. if sErr != nil {
  1326. return false, sErr
  1327. }
  1328. if !stillUsed {
  1329. if err = s.DelClientStat(tx, oldEmail); err != nil {
  1330. return false, err
  1331. }
  1332. if err = s.DelClientIPs(tx, oldEmail); err != nil {
  1333. return false, err
  1334. }
  1335. }
  1336. // Refresh the surviving row with the new client's limits/expiry.
  1337. if err = s.UpdateClientStat(tx, clients[0].Email, &clients[0]); err != nil {
  1338. return false, err
  1339. }
  1340. }
  1341. } else {
  1342. s.AddClientStat(tx, data.Id, &clients[0])
  1343. }
  1344. } else {
  1345. stillUsed, err := s.emailUsedByOtherInbounds(oldEmail, data.Id)
  1346. if err != nil {
  1347. return false, err
  1348. }
  1349. if !stillUsed {
  1350. err = s.DelClientStat(tx, oldEmail)
  1351. if err != nil {
  1352. return false, err
  1353. }
  1354. err = s.DelClientIPs(tx, oldEmail)
  1355. if err != nil {
  1356. return false, err
  1357. }
  1358. }
  1359. }
  1360. needRestart := false
  1361. if len(oldEmail) > 0 {
  1362. rt, rterr := s.runtimeFor(oldInbound)
  1363. if rterr != nil {
  1364. if oldInbound.NodeID != nil {
  1365. err = rterr
  1366. return false, err
  1367. }
  1368. needRestart = true
  1369. } else if oldInbound.NodeID == nil {
  1370. if oldClients[clientIndex].Enable {
  1371. err1 := rt.RemoveUser(context.Background(), oldInbound, oldEmail)
  1372. if err1 == nil {
  1373. logger.Debug("Old client deleted on", rt.Name(), ":", oldEmail)
  1374. } else if strings.Contains(err1.Error(), fmt.Sprintf("User %s not found.", oldEmail)) {
  1375. logger.Debug("User is already deleted. Nothing to do more...")
  1376. } else {
  1377. logger.Debug("Error in deleting client on", rt.Name(), ":", err1)
  1378. needRestart = true
  1379. }
  1380. }
  1381. if clients[0].Enable {
  1382. cipher := ""
  1383. if oldInbound.Protocol == "shadowsocks" {
  1384. cipher = oldSettings["method"].(string)
  1385. }
  1386. err1 := rt.AddUser(context.Background(), oldInbound, map[string]any{
  1387. "email": clients[0].Email,
  1388. "id": clients[0].ID,
  1389. "security": clients[0].Security,
  1390. "flow": clients[0].Flow,
  1391. "auth": clients[0].Auth,
  1392. "password": clients[0].Password,
  1393. "cipher": cipher,
  1394. })
  1395. if err1 == nil {
  1396. logger.Debug("Client edited on", rt.Name(), ":", clients[0].Email)
  1397. } else {
  1398. logger.Debug("Error in adding client on", rt.Name(), ":", err1)
  1399. needRestart = true
  1400. }
  1401. }
  1402. } else {
  1403. if err1 := rt.UpdateInbound(context.Background(), oldInbound, oldInbound); err1 != nil {
  1404. err = err1
  1405. return false, err
  1406. }
  1407. }
  1408. } else {
  1409. logger.Debug("Client old email not found")
  1410. needRestart = true
  1411. }
  1412. return needRestart, tx.Save(oldInbound).Error
  1413. }
  1414. const resetGracePeriodMs int64 = 30000
  1415. // onlineGracePeriodMs must comfortably exceed the 5s traffic-poll interval —
  1416. // Xray's stats counters often report a zero delta for an active session across
  1417. // a single poll, so a 5s grace would still drop the client on the next tick.
  1418. // ~4 polls of slack keeps idle-but-connected clients visible without lingering
  1419. // long after a real disconnect.
  1420. const onlineGracePeriodMs int64 = 20000
  1421. func (s *InboundService) SetRemoteTraffic(nodeID int, snap *runtime.TrafficSnapshot) (bool, error) {
  1422. var structuralChange bool
  1423. err := submitTrafficWrite(func() error {
  1424. var inner error
  1425. structuralChange, inner = s.setRemoteTrafficLocked(nodeID, snap)
  1426. return inner
  1427. })
  1428. return structuralChange, err
  1429. }
  1430. func (s *InboundService) setRemoteTrafficLocked(nodeID int, snap *runtime.TrafficSnapshot) (bool, error) {
  1431. if snap == nil || nodeID <= 0 {
  1432. return false, nil
  1433. }
  1434. db := database.GetDB()
  1435. now := time.Now().UnixMilli()
  1436. var central []model.Inbound
  1437. if err := db.Model(model.Inbound{}).
  1438. Where("node_id = ?", nodeID).
  1439. Find(&central).Error; err != nil {
  1440. return false, err
  1441. }
  1442. tagToCentral := make(map[string]*model.Inbound, len(central))
  1443. for i := range central {
  1444. tagToCentral[central[i].Tag] = &central[i]
  1445. }
  1446. var centralClientStats []xray.ClientTraffic
  1447. if len(central) > 0 {
  1448. ids := make([]int, 0, len(central))
  1449. for i := range central {
  1450. ids = append(ids, central[i].Id)
  1451. }
  1452. if err := db.Model(xray.ClientTraffic{}).
  1453. Where("inbound_id IN ?", ids).
  1454. Find(&centralClientStats).Error; err != nil {
  1455. return false, err
  1456. }
  1457. }
  1458. type csKey struct {
  1459. inboundID int
  1460. email string
  1461. }
  1462. centralCS := make(map[csKey]*xray.ClientTraffic, len(centralClientStats))
  1463. for i := range centralClientStats {
  1464. centralCS[csKey{centralClientStats[i].InboundId, centralClientStats[i].Email}] = &centralClientStats[i]
  1465. }
  1466. var defaultUserId int
  1467. if len(central) > 0 {
  1468. defaultUserId = central[0].UserId
  1469. } else {
  1470. var u model.User
  1471. if err := db.Model(model.User{}).Order("id asc").First(&u).Error; err == nil {
  1472. defaultUserId = u.Id
  1473. } else {
  1474. defaultUserId = 1
  1475. }
  1476. }
  1477. tx := db.Begin()
  1478. committed := false
  1479. defer func() {
  1480. if !committed {
  1481. tx.Rollback()
  1482. }
  1483. }()
  1484. structuralChange := false
  1485. snapTags := make(map[string]struct{}, len(snap.Inbounds))
  1486. for _, snapIb := range snap.Inbounds {
  1487. if snapIb == nil {
  1488. continue
  1489. }
  1490. snapTags[snapIb.Tag] = struct{}{}
  1491. c, ok := tagToCentral[snapIb.Tag]
  1492. if !ok {
  1493. newIb := model.Inbound{
  1494. UserId: defaultUserId,
  1495. NodeID: &nodeID,
  1496. Tag: snapIb.Tag,
  1497. Listen: snapIb.Listen,
  1498. Port: snapIb.Port,
  1499. Protocol: snapIb.Protocol,
  1500. Settings: snapIb.Settings,
  1501. StreamSettings: snapIb.StreamSettings,
  1502. Sniffing: snapIb.Sniffing,
  1503. TrafficReset: snapIb.TrafficReset,
  1504. Enable: snapIb.Enable,
  1505. Remark: snapIb.Remark,
  1506. Total: snapIb.Total,
  1507. ExpiryTime: snapIb.ExpiryTime,
  1508. Up: snapIb.Up,
  1509. Down: snapIb.Down,
  1510. AllTime: snapIb.AllTime,
  1511. }
  1512. if err := tx.Create(&newIb).Error; err != nil {
  1513. logger.Warning("setRemoteTraffic: create central inbound for tag", snapIb.Tag, "failed:", err)
  1514. continue
  1515. }
  1516. tagToCentral[snapIb.Tag] = &newIb
  1517. structuralChange = true
  1518. continue
  1519. }
  1520. inGrace := c.LastTrafficResetTime > 0 && now-c.LastTrafficResetTime < resetGracePeriodMs
  1521. updates := map[string]any{
  1522. "enable": snapIb.Enable,
  1523. "remark": snapIb.Remark,
  1524. "listen": snapIb.Listen,
  1525. "port": snapIb.Port,
  1526. "protocol": snapIb.Protocol,
  1527. "total": snapIb.Total,
  1528. "expiry_time": snapIb.ExpiryTime,
  1529. "settings": snapIb.Settings,
  1530. "stream_settings": snapIb.StreamSettings,
  1531. "sniffing": snapIb.Sniffing,
  1532. "traffic_reset": snapIb.TrafficReset,
  1533. }
  1534. if !inGrace || (snapIb.Up+snapIb.Down) <= (c.Up+c.Down) {
  1535. updates["up"] = snapIb.Up
  1536. updates["down"] = snapIb.Down
  1537. }
  1538. if snapIb.AllTime > c.AllTime {
  1539. updates["all_time"] = snapIb.AllTime
  1540. }
  1541. if c.Settings != snapIb.Settings ||
  1542. c.Remark != snapIb.Remark ||
  1543. c.Listen != snapIb.Listen ||
  1544. c.Port != snapIb.Port ||
  1545. c.Total != snapIb.Total ||
  1546. c.ExpiryTime != snapIb.ExpiryTime ||
  1547. c.Enable != snapIb.Enable {
  1548. structuralChange = true
  1549. }
  1550. if err := tx.Model(model.Inbound{}).
  1551. Where("id = ?", c.Id).
  1552. Updates(updates).Error; err != nil {
  1553. return false, err
  1554. }
  1555. }
  1556. for _, c := range central {
  1557. if _, kept := snapTags[c.Tag]; kept {
  1558. continue
  1559. }
  1560. if err := tx.Where("inbound_id = ?", c.Id).
  1561. Delete(&xray.ClientTraffic{}).Error; err != nil {
  1562. return false, err
  1563. }
  1564. if err := tx.Where("id = ?", c.Id).
  1565. Delete(&model.Inbound{}).Error; err != nil {
  1566. return false, err
  1567. }
  1568. delete(tagToCentral, c.Tag)
  1569. structuralChange = true
  1570. }
  1571. for _, snapIb := range snap.Inbounds {
  1572. if snapIb == nil {
  1573. continue
  1574. }
  1575. c, ok := tagToCentral[snapIb.Tag]
  1576. if !ok {
  1577. continue
  1578. }
  1579. inGrace := c.LastTrafficResetTime > 0 && now-c.LastTrafficResetTime < resetGracePeriodMs
  1580. snapEmails := make(map[string]struct{}, len(snapIb.ClientStats))
  1581. for _, cs := range snapIb.ClientStats {
  1582. snapEmails[cs.Email] = struct{}{}
  1583. existing := centralCS[csKey{c.Id, cs.Email}]
  1584. if existing == nil {
  1585. if err := tx.Create(&xray.ClientTraffic{
  1586. InboundId: c.Id,
  1587. Email: cs.Email,
  1588. Enable: cs.Enable,
  1589. Total: cs.Total,
  1590. ExpiryTime: cs.ExpiryTime,
  1591. Reset: cs.Reset,
  1592. Up: cs.Up,
  1593. Down: cs.Down,
  1594. AllTime: cs.AllTime,
  1595. LastOnline: cs.LastOnline,
  1596. }).Error; err != nil {
  1597. return false, err
  1598. }
  1599. structuralChange = true
  1600. continue
  1601. }
  1602. if existing.Enable != cs.Enable ||
  1603. existing.Total != cs.Total ||
  1604. existing.ExpiryTime != cs.ExpiryTime ||
  1605. existing.Reset != cs.Reset {
  1606. structuralChange = true
  1607. }
  1608. allTime := existing.AllTime
  1609. if cs.AllTime > allTime {
  1610. allTime = cs.AllTime
  1611. }
  1612. if inGrace && cs.Up+cs.Down > 0 {
  1613. if err := tx.Exec(
  1614. `UPDATE client_traffics
  1615. SET enable = ?, total = ?, expiry_time = ?, reset = ?, all_time = ?
  1616. WHERE inbound_id = ? AND email = ?`,
  1617. cs.Enable, cs.Total, cs.ExpiryTime, cs.Reset, allTime, c.Id, cs.Email,
  1618. ).Error; err != nil {
  1619. return false, err
  1620. }
  1621. continue
  1622. }
  1623. if err := tx.Exec(
  1624. `UPDATE client_traffics
  1625. SET up = ?, down = ?, enable = ?, total = ?, expiry_time = ?, reset = ?,
  1626. all_time = ?, last_online = MAX(last_online, ?)
  1627. WHERE inbound_id = ? AND email = ?`,
  1628. cs.Up, cs.Down, cs.Enable, cs.Total, cs.ExpiryTime, cs.Reset, allTime,
  1629. cs.LastOnline, c.Id, cs.Email,
  1630. ).Error; err != nil {
  1631. return false, err
  1632. }
  1633. }
  1634. for k, existing := range centralCS {
  1635. if k.inboundID != c.Id {
  1636. continue
  1637. }
  1638. if _, kept := snapEmails[k.email]; kept {
  1639. continue
  1640. }
  1641. if err := tx.Where("inbound_id = ? AND email = ?", c.Id, existing.Email).
  1642. Delete(&xray.ClientTraffic{}).Error; err != nil {
  1643. return false, err
  1644. }
  1645. structuralChange = true
  1646. }
  1647. }
  1648. if err := tx.Commit().Error; err != nil {
  1649. return false, err
  1650. }
  1651. committed = true
  1652. if p != nil {
  1653. p.SetNodeOnlineClients(nodeID, snap.OnlineEmails)
  1654. }
  1655. return structuralChange, nil
  1656. }
  1657. func (s *InboundService) AddTraffic(inboundTraffics []*xray.Traffic, clientTraffics []*xray.ClientTraffic) (needRestart bool, clientsDisabled bool, err error) {
  1658. err = submitTrafficWrite(func() error {
  1659. var inner error
  1660. needRestart, clientsDisabled, inner = s.addTrafficLocked(inboundTraffics, clientTraffics)
  1661. return inner
  1662. })
  1663. return
  1664. }
  1665. func (s *InboundService) addTrafficLocked(inboundTraffics []*xray.Traffic, clientTraffics []*xray.ClientTraffic) (bool, bool, error) {
  1666. var err error
  1667. db := database.GetDB()
  1668. tx := db.Begin()
  1669. defer func() {
  1670. if err != nil {
  1671. tx.Rollback()
  1672. } else {
  1673. tx.Commit()
  1674. }
  1675. }()
  1676. err = s.addInboundTraffic(tx, inboundTraffics)
  1677. if err != nil {
  1678. return false, false, err
  1679. }
  1680. err = s.addClientTraffic(tx, clientTraffics)
  1681. if err != nil {
  1682. return false, false, err
  1683. }
  1684. needRestart0, count, err := s.autoRenewClients(tx)
  1685. if err != nil {
  1686. logger.Warning("Error in renew clients:", err)
  1687. } else if count > 0 {
  1688. logger.Debugf("%v clients renewed", count)
  1689. }
  1690. disabledClientsCount := int64(0)
  1691. needRestart1, count, err := s.disableInvalidClients(tx)
  1692. if err != nil {
  1693. logger.Warning("Error in disabling invalid clients:", err)
  1694. } else if count > 0 {
  1695. logger.Debugf("%v clients disabled", count)
  1696. disabledClientsCount = count
  1697. }
  1698. needRestart2, count, err := s.disableInvalidInbounds(tx)
  1699. if err != nil {
  1700. logger.Warning("Error in disabling invalid inbounds:", err)
  1701. } else if count > 0 {
  1702. logger.Debugf("%v inbounds disabled", count)
  1703. }
  1704. return needRestart0 || needRestart1 || needRestart2, disabledClientsCount > 0, nil
  1705. }
  1706. func (s *InboundService) addInboundTraffic(tx *gorm.DB, traffics []*xray.Traffic) error {
  1707. if len(traffics) == 0 {
  1708. return nil
  1709. }
  1710. var err error
  1711. for _, traffic := range traffics {
  1712. if traffic.IsInbound {
  1713. err = tx.Model(&model.Inbound{}).Where("tag = ? AND node_id IS NULL", traffic.Tag).
  1714. Updates(map[string]any{
  1715. "up": gorm.Expr("up + ?", traffic.Up),
  1716. "down": gorm.Expr("down + ?", traffic.Down),
  1717. "all_time": gorm.Expr("COALESCE(all_time, 0) + ?", traffic.Up+traffic.Down),
  1718. }).Error
  1719. if err != nil {
  1720. return err
  1721. }
  1722. }
  1723. }
  1724. return nil
  1725. }
  1726. func (s *InboundService) addClientTraffic(tx *gorm.DB, traffics []*xray.ClientTraffic) (err error) {
  1727. if len(traffics) == 0 {
  1728. return nil
  1729. }
  1730. emails := make([]string, 0, len(traffics))
  1731. for _, traffic := range traffics {
  1732. emails = append(emails, traffic.Email)
  1733. }
  1734. dbClientTraffics := make([]*xray.ClientTraffic, 0, len(traffics))
  1735. err = tx.Model(xray.ClientTraffic{}).
  1736. Where("email IN (?) AND inbound_id IN (?)", emails,
  1737. tx.Model(&model.Inbound{}).Select("id").Where("node_id IS NULL")).
  1738. Find(&dbClientTraffics).Error
  1739. if err != nil {
  1740. return err
  1741. }
  1742. // Avoid empty slice error
  1743. if len(dbClientTraffics) == 0 {
  1744. return nil
  1745. }
  1746. dbClientTraffics, err = s.adjustTraffics(tx, dbClientTraffics)
  1747. if err != nil {
  1748. return err
  1749. }
  1750. // Index by email for O(N) merge — the previous nested loop was O(N²)
  1751. // and dominated each cron tick on inbounds with thousands of active
  1752. // clients (7500 × 7500 = 56M string comparisons every 10 seconds).
  1753. trafficByEmail := make(map[string]*xray.ClientTraffic, len(traffics))
  1754. for i := range traffics {
  1755. if traffics[i] != nil {
  1756. trafficByEmail[traffics[i].Email] = traffics[i]
  1757. }
  1758. }
  1759. now := time.Now().UnixMilli()
  1760. for dbTraffic_index := range dbClientTraffics {
  1761. t, ok := trafficByEmail[dbClientTraffics[dbTraffic_index].Email]
  1762. if !ok {
  1763. continue
  1764. }
  1765. dbClientTraffics[dbTraffic_index].Up += t.Up
  1766. dbClientTraffics[dbTraffic_index].Down += t.Down
  1767. dbClientTraffics[dbTraffic_index].AllTime += t.Up + t.Down
  1768. if t.Up+t.Down > 0 {
  1769. dbClientTraffics[dbTraffic_index].LastOnline = now
  1770. }
  1771. }
  1772. err = tx.Save(dbClientTraffics).Error
  1773. if err != nil {
  1774. logger.Warning("AddClientTraffic update data ", err)
  1775. }
  1776. return nil
  1777. }
  1778. func (s *InboundService) adjustTraffics(tx *gorm.DB, dbClientTraffics []*xray.ClientTraffic) ([]*xray.ClientTraffic, error) {
  1779. inboundIds := make([]int, 0, len(dbClientTraffics))
  1780. for _, dbClientTraffic := range dbClientTraffics {
  1781. if dbClientTraffic.ExpiryTime < 0 {
  1782. inboundIds = append(inboundIds, dbClientTraffic.InboundId)
  1783. }
  1784. }
  1785. if len(inboundIds) > 0 {
  1786. var inbounds []*model.Inbound
  1787. err := tx.Model(model.Inbound{}).Where("id IN (?)", inboundIds).Find(&inbounds).Error
  1788. if err != nil {
  1789. return nil, err
  1790. }
  1791. for inbound_index := range inbounds {
  1792. settings := map[string]any{}
  1793. json.Unmarshal([]byte(inbounds[inbound_index].Settings), &settings)
  1794. clients, ok := settings["clients"].([]any)
  1795. if ok {
  1796. var newClients []any
  1797. for client_index := range clients {
  1798. c := clients[client_index].(map[string]any)
  1799. for traffic_index := range dbClientTraffics {
  1800. if dbClientTraffics[traffic_index].ExpiryTime < 0 && c["email"] == dbClientTraffics[traffic_index].Email {
  1801. oldExpiryTime := c["expiryTime"].(float64)
  1802. newExpiryTime := (time.Now().Unix() * 1000) - int64(oldExpiryTime)
  1803. c["expiryTime"] = newExpiryTime
  1804. c["updated_at"] = time.Now().Unix() * 1000
  1805. dbClientTraffics[traffic_index].ExpiryTime = newExpiryTime
  1806. break
  1807. }
  1808. }
  1809. // Backfill created_at and updated_at
  1810. if _, ok := c["created_at"]; !ok {
  1811. c["created_at"] = time.Now().Unix() * 1000
  1812. }
  1813. c["updated_at"] = time.Now().Unix() * 1000
  1814. newClients = append(newClients, any(c))
  1815. }
  1816. settings["clients"] = newClients
  1817. modifiedSettings, err := json.MarshalIndent(settings, "", " ")
  1818. if err != nil {
  1819. return nil, err
  1820. }
  1821. inbounds[inbound_index].Settings = string(modifiedSettings)
  1822. }
  1823. }
  1824. err = tx.Save(inbounds).Error
  1825. if err != nil {
  1826. logger.Warning("AddClientTraffic update inbounds ", err)
  1827. logger.Error(inbounds)
  1828. }
  1829. }
  1830. return dbClientTraffics, nil
  1831. }
  1832. func (s *InboundService) autoRenewClients(tx *gorm.DB) (bool, int64, error) {
  1833. // check for time expired
  1834. var traffics []*xray.ClientTraffic
  1835. now := time.Now().Unix() * 1000
  1836. var err, err1 error
  1837. err = tx.Model(xray.ClientTraffic{}).
  1838. Where("reset > 0 and expiry_time > 0 and expiry_time <= ?", now).
  1839. Where("inbound_id IN (?)", tx.Model(&model.Inbound{}).Select("id").Where("node_id IS NULL")).
  1840. Find(&traffics).Error
  1841. if err != nil {
  1842. return false, 0, err
  1843. }
  1844. // return if there is no client to renew
  1845. if len(traffics) == 0 {
  1846. return false, 0, nil
  1847. }
  1848. var inbound_ids []int
  1849. var inbounds []*model.Inbound
  1850. needRestart := false
  1851. var clientsToAdd []struct {
  1852. protocol string
  1853. tag string
  1854. client map[string]any
  1855. }
  1856. for _, traffic := range traffics {
  1857. inbound_ids = append(inbound_ids, traffic.InboundId)
  1858. }
  1859. // Dedupe so an inbound hosting N expired clients is fetched and saved once
  1860. // per tick instead of N times across chunk boundaries.
  1861. inbound_ids = uniqueInts(inbound_ids)
  1862. // Chunked to stay under SQLite's bind-variable limit when many inbounds
  1863. // are touched in a single tick.
  1864. for _, batch := range chunkInts(inbound_ids, sqliteMaxVars) {
  1865. var page []*model.Inbound
  1866. if err = tx.Model(model.Inbound{}).Where("id IN ?", batch).Find(&page).Error; err != nil {
  1867. return false, 0, err
  1868. }
  1869. inbounds = append(inbounds, page...)
  1870. }
  1871. for inbound_index := range inbounds {
  1872. settings := map[string]any{}
  1873. json.Unmarshal([]byte(inbounds[inbound_index].Settings), &settings)
  1874. clients := settings["clients"].([]any)
  1875. for client_index := range clients {
  1876. c := clients[client_index].(map[string]any)
  1877. for traffic_index, traffic := range traffics {
  1878. if traffic.Email == c["email"].(string) {
  1879. newExpiryTime := traffic.ExpiryTime
  1880. for newExpiryTime < now {
  1881. newExpiryTime += (int64(traffic.Reset) * 86400000)
  1882. }
  1883. c["expiryTime"] = newExpiryTime
  1884. traffics[traffic_index].ExpiryTime = newExpiryTime
  1885. traffics[traffic_index].Down = 0
  1886. traffics[traffic_index].Up = 0
  1887. if !traffic.Enable {
  1888. traffics[traffic_index].Enable = true
  1889. c["enable"] = true
  1890. clientsToAdd = append(clientsToAdd,
  1891. struct {
  1892. protocol string
  1893. tag string
  1894. client map[string]any
  1895. }{
  1896. protocol: string(inbounds[inbound_index].Protocol),
  1897. tag: inbounds[inbound_index].Tag,
  1898. client: c,
  1899. })
  1900. }
  1901. clients[client_index] = any(c)
  1902. break
  1903. }
  1904. }
  1905. }
  1906. settings["clients"] = clients
  1907. newSettings, err := json.MarshalIndent(settings, "", " ")
  1908. if err != nil {
  1909. return false, 0, err
  1910. }
  1911. inbounds[inbound_index].Settings = string(newSettings)
  1912. }
  1913. err = tx.Save(inbounds).Error
  1914. if err != nil {
  1915. return false, 0, err
  1916. }
  1917. err = tx.Save(traffics).Error
  1918. if err != nil {
  1919. return false, 0, err
  1920. }
  1921. if p != nil {
  1922. err1 = s.xrayApi.Init(p.GetAPIPort())
  1923. if err1 != nil {
  1924. return true, int64(len(traffics)), nil
  1925. }
  1926. for _, clientToAdd := range clientsToAdd {
  1927. err1 = s.xrayApi.AddUser(clientToAdd.protocol, clientToAdd.tag, clientToAdd.client)
  1928. if err1 != nil {
  1929. needRestart = true
  1930. }
  1931. }
  1932. s.xrayApi.Close()
  1933. }
  1934. return needRestart, int64(len(traffics)), nil
  1935. }
  1936. func (s *InboundService) disableInvalidInbounds(tx *gorm.DB) (bool, int64, error) {
  1937. now := time.Now().Unix() * 1000
  1938. needRestart := false
  1939. if p != nil {
  1940. var tags []string
  1941. err := tx.Table("inbounds").
  1942. Select("inbounds.tag").
  1943. Where("((total > 0 and up + down >= total) or (expiry_time > 0 and expiry_time <= ?)) and enable = ? and node_id IS NULL", now, true).
  1944. Scan(&tags).Error
  1945. if err != nil {
  1946. return false, 0, err
  1947. }
  1948. s.xrayApi.Init(p.GetAPIPort())
  1949. for _, tag := range tags {
  1950. err1 := s.xrayApi.DelInbound(tag)
  1951. if err1 == nil {
  1952. logger.Debug("Inbound disabled by api:", tag)
  1953. } else {
  1954. logger.Debug("Error in disabling inbound by api:", err1)
  1955. needRestart = true
  1956. }
  1957. }
  1958. s.xrayApi.Close()
  1959. }
  1960. result := tx.Model(model.Inbound{}).
  1961. Where("((total > 0 and up + down >= total) or (expiry_time > 0 and expiry_time <= ?)) and enable = ? and node_id IS NULL", now, true).
  1962. Update("enable", false)
  1963. err := result.Error
  1964. count := result.RowsAffected
  1965. return needRestart, count, err
  1966. }
  1967. func (s *InboundService) disableInvalidClients(tx *gorm.DB) (bool, int64, error) {
  1968. now := time.Now().Unix() * 1000
  1969. needRestart := false
  1970. var depletedRows []xray.ClientTraffic
  1971. err := tx.Model(xray.ClientTraffic{}).
  1972. Where("((total > 0 AND up + down >= total) OR (expiry_time > 0 AND expiry_time <= ?)) AND enable = ?", now, true).
  1973. Where("inbound_id IN (?)", tx.Model(&model.Inbound{}).Select("id").Where("node_id IS NULL")).
  1974. Find(&depletedRows).Error
  1975. if err != nil {
  1976. return false, 0, err
  1977. }
  1978. if len(depletedRows) == 0 {
  1979. return false, 0, nil
  1980. }
  1981. rowByEmail := make(map[string]*xray.ClientTraffic, len(depletedRows))
  1982. depletedEmails := make([]string, 0, len(depletedRows))
  1983. for i := range depletedRows {
  1984. if depletedRows[i].Email == "" {
  1985. continue
  1986. }
  1987. rowByEmail[strings.ToLower(depletedRows[i].Email)] = &depletedRows[i]
  1988. depletedEmails = append(depletedEmails, depletedRows[i].Email)
  1989. }
  1990. // Resolve inbound membership only for the depleted emails — pushing the
  1991. // filter into SQLite avoids dragging every panel client through Go for
  1992. // the common case where most clients are healthy.
  1993. var memberships []struct {
  1994. InboundId int
  1995. Tag string
  1996. Email string
  1997. SubID string `gorm:"column:sub_id"`
  1998. }
  1999. if len(depletedEmails) > 0 {
  2000. err = tx.Raw(`
  2001. SELECT inbounds.id AS inbound_id,
  2002. inbounds.tag AS tag,
  2003. JSON_EXTRACT(client.value, '$.email') AS email,
  2004. JSON_EXTRACT(client.value, '$.subId') AS sub_id
  2005. FROM inbounds,
  2006. JSON_EACH(JSON_EXTRACT(inbounds.settings, '$.clients')) AS client
  2007. WHERE LOWER(JSON_EXTRACT(client.value, '$.email')) IN ?
  2008. `, lowerAll(depletedEmails)).Scan(&memberships).Error
  2009. if err != nil {
  2010. return false, 0, err
  2011. }
  2012. }
  2013. // Discover the row holder's subId per email. Only siblings sharing it
  2014. // get cascaded; legacy data where two identities reuse the same email
  2015. // stays isolated to the row owner.
  2016. holderSub := make(map[string]string, len(rowByEmail))
  2017. for _, m := range memberships {
  2018. email := strings.ToLower(strings.Trim(m.Email, "\""))
  2019. row, ok := rowByEmail[email]
  2020. if !ok || m.InboundId != row.InboundId {
  2021. continue
  2022. }
  2023. holderSub[email] = strings.Trim(m.SubID, "\"")
  2024. }
  2025. type target struct {
  2026. InboundId int
  2027. Tag string
  2028. Email string
  2029. }
  2030. var targets []target
  2031. for _, m := range memberships {
  2032. email := strings.ToLower(strings.Trim(m.Email, "\""))
  2033. row, ok := rowByEmail[email]
  2034. if !ok {
  2035. continue
  2036. }
  2037. expected, hasSub := holderSub[email]
  2038. mSub := strings.Trim(m.SubID, "\"")
  2039. switch {
  2040. case !hasSub || expected == "":
  2041. if m.InboundId != row.InboundId {
  2042. continue
  2043. }
  2044. case mSub != expected:
  2045. continue
  2046. }
  2047. targets = append(targets, target{
  2048. InboundId: m.InboundId,
  2049. Tag: m.Tag,
  2050. Email: strings.Trim(m.Email, "\""),
  2051. })
  2052. }
  2053. if p != nil && len(targets) > 0 {
  2054. s.xrayApi.Init(p.GetAPIPort())
  2055. for _, t := range targets {
  2056. err1 := s.xrayApi.RemoveUser(t.Tag, t.Email)
  2057. if err1 == nil {
  2058. logger.Debug("Client disabled by api:", t.Email)
  2059. } else if strings.Contains(err1.Error(), fmt.Sprintf("User %s not found.", t.Email)) {
  2060. logger.Debug("User is already disabled. Nothing to do more...")
  2061. } else {
  2062. logger.Debug("Error in disabling client by api:", err1)
  2063. needRestart = true
  2064. }
  2065. }
  2066. s.xrayApi.Close()
  2067. }
  2068. result := tx.Model(xray.ClientTraffic{}).
  2069. Where("((total > 0 and up + down >= total) or (expiry_time > 0 and expiry_time <= ?)) and enable = ?", now, true).
  2070. Where("inbound_id IN (?)", tx.Model(&model.Inbound{}).Select("id").Where("node_id IS NULL")).
  2071. Update("enable", false)
  2072. err = result.Error
  2073. count := result.RowsAffected
  2074. if err != nil {
  2075. return needRestart, count, err
  2076. }
  2077. if len(targets) == 0 {
  2078. return needRestart, count, nil
  2079. }
  2080. inboundEmailMap := make(map[int]map[string]struct{})
  2081. for _, t := range targets {
  2082. if inboundEmailMap[t.InboundId] == nil {
  2083. inboundEmailMap[t.InboundId] = make(map[string]struct{})
  2084. }
  2085. inboundEmailMap[t.InboundId][t.Email] = struct{}{}
  2086. }
  2087. inboundIds := make([]int, 0, len(inboundEmailMap))
  2088. for id := range inboundEmailMap {
  2089. inboundIds = append(inboundIds, id)
  2090. }
  2091. var inbounds []*model.Inbound
  2092. if err = tx.Model(model.Inbound{}).Where("id IN ?", inboundIds).Find(&inbounds).Error; err != nil {
  2093. logger.Warning("disableInvalidClients fetch inbounds:", err)
  2094. return needRestart, count, nil
  2095. }
  2096. dirty := make([]*model.Inbound, 0, len(inbounds))
  2097. for _, inbound := range inbounds {
  2098. settings := map[string]any{}
  2099. if jsonErr := json.Unmarshal([]byte(inbound.Settings), &settings); jsonErr != nil {
  2100. continue
  2101. }
  2102. clientsRaw, ok := settings["clients"].([]any)
  2103. if !ok {
  2104. continue
  2105. }
  2106. emailSet := inboundEmailMap[inbound.Id]
  2107. changed := false
  2108. for i := range clientsRaw {
  2109. c, ok := clientsRaw[i].(map[string]any)
  2110. if !ok {
  2111. continue
  2112. }
  2113. email, _ := c["email"].(string)
  2114. if _, shouldDisable := emailSet[email]; !shouldDisable {
  2115. continue
  2116. }
  2117. c["enable"] = false
  2118. if row, ok := rowByEmail[strings.ToLower(email)]; ok {
  2119. c["totalGB"] = row.Total
  2120. c["expiryTime"] = row.ExpiryTime
  2121. }
  2122. c["updated_at"] = now
  2123. clientsRaw[i] = c
  2124. changed = true
  2125. }
  2126. if !changed {
  2127. continue
  2128. }
  2129. settings["clients"] = clientsRaw
  2130. modifiedSettings, jsonErr := json.MarshalIndent(settings, "", " ")
  2131. if jsonErr != nil {
  2132. continue
  2133. }
  2134. inbound.Settings = string(modifiedSettings)
  2135. dirty = append(dirty, inbound)
  2136. }
  2137. if len(dirty) > 0 {
  2138. if err = tx.Save(dirty).Error; err != nil {
  2139. logger.Warning("disableInvalidClients update inbound settings:", err)
  2140. }
  2141. }
  2142. return needRestart, count, nil
  2143. }
  2144. func (s *InboundService) GetInboundTags() (string, error) {
  2145. db := database.GetDB()
  2146. var inboundTags []string
  2147. err := db.Model(model.Inbound{}).Select("tag").Find(&inboundTags).Error
  2148. if err != nil && err != gorm.ErrRecordNotFound {
  2149. return "", err
  2150. }
  2151. tags, _ := json.Marshal(inboundTags)
  2152. return string(tags), nil
  2153. }
  2154. func (s *InboundService) GetClientReverseTags() (string, error) {
  2155. db := database.GetDB()
  2156. var inbounds []model.Inbound
  2157. err := db.Model(model.Inbound{}).Select("settings").Where("protocol = ?", "vless").Find(&inbounds).Error
  2158. if err != nil && err != gorm.ErrRecordNotFound {
  2159. return "[]", err
  2160. }
  2161. tagSet := make(map[string]struct{})
  2162. for _, inbound := range inbounds {
  2163. var settings map[string]any
  2164. if err := json.Unmarshal([]byte(inbound.Settings), &settings); err != nil {
  2165. continue
  2166. }
  2167. clients, ok := settings["clients"].([]any)
  2168. if !ok {
  2169. continue
  2170. }
  2171. for _, client := range clients {
  2172. clientMap, ok := client.(map[string]any)
  2173. if !ok {
  2174. continue
  2175. }
  2176. reverse, ok := clientMap["reverse"].(map[string]any)
  2177. if !ok {
  2178. continue
  2179. }
  2180. tag, _ := reverse["tag"].(string)
  2181. tag = strings.TrimSpace(tag)
  2182. if tag != "" {
  2183. tagSet[tag] = struct{}{}
  2184. }
  2185. }
  2186. }
  2187. rawTags := make([]string, 0, len(tagSet))
  2188. for tag := range tagSet {
  2189. rawTags = append(rawTags, tag)
  2190. }
  2191. sort.Strings(rawTags)
  2192. result, _ := json.Marshal(rawTags)
  2193. return string(result), nil
  2194. }
  2195. func (s *InboundService) MigrationRemoveOrphanedTraffics() {
  2196. db := database.GetDB()
  2197. db.Exec(`
  2198. DELETE FROM client_traffics
  2199. WHERE email NOT IN (
  2200. SELECT JSON_EXTRACT(client.value, '$.email')
  2201. FROM inbounds,
  2202. JSON_EACH(JSON_EXTRACT(inbounds.settings, '$.clients')) AS client
  2203. )
  2204. `)
  2205. }
  2206. // AddClientStat inserts a per-client accounting row, no-op on email
  2207. // conflict. Xray reports traffic per email, so the surviving row acts as
  2208. // the shared accumulator for inbounds that re-use the same identity.
  2209. func (s *InboundService) AddClientStat(tx *gorm.DB, inboundId int, client *model.Client) error {
  2210. clientTraffic := xray.ClientTraffic{
  2211. InboundId: inboundId,
  2212. Email: client.Email,
  2213. Total: client.TotalGB,
  2214. ExpiryTime: client.ExpiryTime,
  2215. Enable: client.Enable,
  2216. Reset: client.Reset,
  2217. }
  2218. return tx.Clauses(clause.OnConflict{Columns: []clause.Column{{Name: "email"}}, DoNothing: true}).
  2219. Create(&clientTraffic).Error
  2220. }
  2221. func (s *InboundService) UpdateClientStat(tx *gorm.DB, email string, client *model.Client) error {
  2222. result := tx.Model(xray.ClientTraffic{}).
  2223. Where("email = ?", email).
  2224. Updates(map[string]any{
  2225. "enable": client.Enable,
  2226. "email": client.Email,
  2227. "total": client.TotalGB,
  2228. "expiry_time": client.ExpiryTime,
  2229. "reset": client.Reset,
  2230. })
  2231. err := result.Error
  2232. return err
  2233. }
  2234. func (s *InboundService) UpdateClientIPs(tx *gorm.DB, oldEmail string, newEmail string) error {
  2235. return tx.Model(model.InboundClientIps{}).Where("client_email = ?", oldEmail).Update("client_email", newEmail).Error
  2236. }
  2237. func (s *InboundService) DelClientStat(tx *gorm.DB, email string) error {
  2238. return tx.Where("email = ?", email).Delete(xray.ClientTraffic{}).Error
  2239. }
  2240. func (s *InboundService) DelClientIPs(tx *gorm.DB, email string) error {
  2241. return tx.Where("client_email = ?", email).Delete(model.InboundClientIps{}).Error
  2242. }
  2243. func (s *InboundService) GetClientInboundByTrafficID(trafficId int) (traffic *xray.ClientTraffic, inbound *model.Inbound, err error) {
  2244. db := database.GetDB()
  2245. var traffics []*xray.ClientTraffic
  2246. err = db.Model(xray.ClientTraffic{}).Where("id = ?", trafficId).Find(&traffics).Error
  2247. if err != nil {
  2248. logger.Warningf("Error retrieving ClientTraffic with trafficId %d: %v", trafficId, err)
  2249. return nil, nil, err
  2250. }
  2251. if len(traffics) > 0 {
  2252. inbound, err = s.GetInbound(traffics[0].InboundId)
  2253. return traffics[0], inbound, err
  2254. }
  2255. return nil, nil, nil
  2256. }
  2257. func (s *InboundService) GetClientInboundByEmail(email string) (traffic *xray.ClientTraffic, inbound *model.Inbound, err error) {
  2258. db := database.GetDB()
  2259. var traffics []*xray.ClientTraffic
  2260. err = db.Model(xray.ClientTraffic{}).Where("email = ?", email).Find(&traffics).Error
  2261. if err != nil {
  2262. logger.Warningf("Error retrieving ClientTraffic with email %s: %v", email, err)
  2263. return nil, nil, err
  2264. }
  2265. if len(traffics) > 0 {
  2266. inbound, err = s.GetInbound(traffics[0].InboundId)
  2267. return traffics[0], inbound, err
  2268. }
  2269. return nil, nil, nil
  2270. }
  2271. func (s *InboundService) GetClientByEmail(clientEmail string) (*xray.ClientTraffic, *model.Client, error) {
  2272. traffic, inbound, err := s.GetClientInboundByEmail(clientEmail)
  2273. if err != nil {
  2274. return nil, nil, err
  2275. }
  2276. if inbound == nil {
  2277. return nil, nil, common.NewError("Inbound Not Found For Email:", clientEmail)
  2278. }
  2279. clients, err := s.GetClients(inbound)
  2280. if err != nil {
  2281. return nil, nil, err
  2282. }
  2283. for _, client := range clients {
  2284. if client.Email == clientEmail {
  2285. return traffic, &client, nil
  2286. }
  2287. }
  2288. return nil, nil, common.NewError("Client Not Found In Inbound For Email:", clientEmail)
  2289. }
  2290. func (s *InboundService) SetClientTelegramUserID(trafficId int, tgId int64) (bool, error) {
  2291. traffic, inbound, err := s.GetClientInboundByTrafficID(trafficId)
  2292. if err != nil {
  2293. return false, err
  2294. }
  2295. if inbound == nil {
  2296. return false, common.NewError("Inbound Not Found For Traffic ID:", trafficId)
  2297. }
  2298. clientEmail := traffic.Email
  2299. oldClients, err := s.GetClients(inbound)
  2300. if err != nil {
  2301. return false, err
  2302. }
  2303. clientId := ""
  2304. for _, oldClient := range oldClients {
  2305. if oldClient.Email == clientEmail {
  2306. switch inbound.Protocol {
  2307. case "trojan":
  2308. clientId = oldClient.Password
  2309. case "shadowsocks":
  2310. clientId = oldClient.Email
  2311. default:
  2312. clientId = oldClient.ID
  2313. }
  2314. break
  2315. }
  2316. }
  2317. if len(clientId) == 0 {
  2318. return false, common.NewError("Client Not Found For Email:", clientEmail)
  2319. }
  2320. var settings map[string]any
  2321. err = json.Unmarshal([]byte(inbound.Settings), &settings)
  2322. if err != nil {
  2323. return false, err
  2324. }
  2325. clients := settings["clients"].([]any)
  2326. var newClients []any
  2327. for client_index := range clients {
  2328. c := clients[client_index].(map[string]any)
  2329. if c["email"] == clientEmail {
  2330. c["tgId"] = tgId
  2331. c["updated_at"] = time.Now().Unix() * 1000
  2332. newClients = append(newClients, any(c))
  2333. }
  2334. }
  2335. settings["clients"] = newClients
  2336. modifiedSettings, err := json.MarshalIndent(settings, "", " ")
  2337. if err != nil {
  2338. return false, err
  2339. }
  2340. inbound.Settings = string(modifiedSettings)
  2341. needRestart, err := s.UpdateInboundClient(inbound, clientId)
  2342. return needRestart, err
  2343. }
  2344. func (s *InboundService) checkIsEnabledByEmail(clientEmail string) (bool, error) {
  2345. _, inbound, err := s.GetClientInboundByEmail(clientEmail)
  2346. if err != nil {
  2347. return false, err
  2348. }
  2349. if inbound == nil {
  2350. return false, common.NewError("Inbound Not Found For Email:", clientEmail)
  2351. }
  2352. clients, err := s.GetClients(inbound)
  2353. if err != nil {
  2354. return false, err
  2355. }
  2356. isEnable := false
  2357. for _, client := range clients {
  2358. if client.Email == clientEmail {
  2359. isEnable = client.Enable
  2360. break
  2361. }
  2362. }
  2363. return isEnable, err
  2364. }
  2365. func (s *InboundService) ToggleClientEnableByEmail(clientEmail string) (bool, bool, error) {
  2366. _, inbound, err := s.GetClientInboundByEmail(clientEmail)
  2367. if err != nil {
  2368. return false, false, err
  2369. }
  2370. if inbound == nil {
  2371. return false, false, common.NewError("Inbound Not Found For Email:", clientEmail)
  2372. }
  2373. oldClients, err := s.GetClients(inbound)
  2374. if err != nil {
  2375. return false, false, err
  2376. }
  2377. clientId := ""
  2378. clientOldEnabled := false
  2379. for _, oldClient := range oldClients {
  2380. if oldClient.Email == clientEmail {
  2381. switch inbound.Protocol {
  2382. case "trojan":
  2383. clientId = oldClient.Password
  2384. case "shadowsocks":
  2385. clientId = oldClient.Email
  2386. default:
  2387. clientId = oldClient.ID
  2388. }
  2389. clientOldEnabled = oldClient.Enable
  2390. break
  2391. }
  2392. }
  2393. if len(clientId) == 0 {
  2394. return false, false, common.NewError("Client Not Found For Email:", clientEmail)
  2395. }
  2396. var settings map[string]any
  2397. err = json.Unmarshal([]byte(inbound.Settings), &settings)
  2398. if err != nil {
  2399. return false, false, err
  2400. }
  2401. clients := settings["clients"].([]any)
  2402. var newClients []any
  2403. for client_index := range clients {
  2404. c := clients[client_index].(map[string]any)
  2405. if c["email"] == clientEmail {
  2406. c["enable"] = !clientOldEnabled
  2407. c["updated_at"] = time.Now().Unix() * 1000
  2408. newClients = append(newClients, any(c))
  2409. }
  2410. }
  2411. settings["clients"] = newClients
  2412. modifiedSettings, err := json.MarshalIndent(settings, "", " ")
  2413. if err != nil {
  2414. return false, false, err
  2415. }
  2416. inbound.Settings = string(modifiedSettings)
  2417. needRestart, err := s.UpdateInboundClient(inbound, clientId)
  2418. if err != nil {
  2419. return false, needRestart, err
  2420. }
  2421. return !clientOldEnabled, needRestart, nil
  2422. }
  2423. // SetClientEnableByEmail sets client enable state to desired value; returns (changed, needRestart, error)
  2424. func (s *InboundService) SetClientEnableByEmail(clientEmail string, enable bool) (bool, bool, error) {
  2425. current, err := s.checkIsEnabledByEmail(clientEmail)
  2426. if err != nil {
  2427. return false, false, err
  2428. }
  2429. if current == enable {
  2430. return false, false, nil
  2431. }
  2432. newEnabled, needRestart, err := s.ToggleClientEnableByEmail(clientEmail)
  2433. if err != nil {
  2434. return false, needRestart, err
  2435. }
  2436. return newEnabled == enable, needRestart, nil
  2437. }
  2438. func (s *InboundService) ResetClientIpLimitByEmail(clientEmail string, count int) (bool, error) {
  2439. _, inbound, err := s.GetClientInboundByEmail(clientEmail)
  2440. if err != nil {
  2441. return false, err
  2442. }
  2443. if inbound == nil {
  2444. return false, common.NewError("Inbound Not Found For Email:", clientEmail)
  2445. }
  2446. oldClients, err := s.GetClients(inbound)
  2447. if err != nil {
  2448. return false, err
  2449. }
  2450. clientId := ""
  2451. for _, oldClient := range oldClients {
  2452. if oldClient.Email == clientEmail {
  2453. switch inbound.Protocol {
  2454. case "trojan":
  2455. clientId = oldClient.Password
  2456. case "shadowsocks":
  2457. clientId = oldClient.Email
  2458. default:
  2459. clientId = oldClient.ID
  2460. }
  2461. break
  2462. }
  2463. }
  2464. if len(clientId) == 0 {
  2465. return false, common.NewError("Client Not Found For Email:", clientEmail)
  2466. }
  2467. var settings map[string]any
  2468. err = json.Unmarshal([]byte(inbound.Settings), &settings)
  2469. if err != nil {
  2470. return false, err
  2471. }
  2472. clients := settings["clients"].([]any)
  2473. var newClients []any
  2474. for client_index := range clients {
  2475. c := clients[client_index].(map[string]any)
  2476. if c["email"] == clientEmail {
  2477. c["limitIp"] = count
  2478. c["updated_at"] = time.Now().Unix() * 1000
  2479. newClients = append(newClients, any(c))
  2480. }
  2481. }
  2482. settings["clients"] = newClients
  2483. modifiedSettings, err := json.MarshalIndent(settings, "", " ")
  2484. if err != nil {
  2485. return false, err
  2486. }
  2487. inbound.Settings = string(modifiedSettings)
  2488. needRestart, err := s.UpdateInboundClient(inbound, clientId)
  2489. return needRestart, err
  2490. }
  2491. func (s *InboundService) ResetClientExpiryTimeByEmail(clientEmail string, expiry_time int64) (bool, error) {
  2492. _, inbound, err := s.GetClientInboundByEmail(clientEmail)
  2493. if err != nil {
  2494. return false, err
  2495. }
  2496. if inbound == nil {
  2497. return false, common.NewError("Inbound Not Found For Email:", clientEmail)
  2498. }
  2499. oldClients, err := s.GetClients(inbound)
  2500. if err != nil {
  2501. return false, err
  2502. }
  2503. clientId := ""
  2504. for _, oldClient := range oldClients {
  2505. if oldClient.Email == clientEmail {
  2506. switch inbound.Protocol {
  2507. case "trojan":
  2508. clientId = oldClient.Password
  2509. case "shadowsocks":
  2510. clientId = oldClient.Email
  2511. default:
  2512. clientId = oldClient.ID
  2513. }
  2514. break
  2515. }
  2516. }
  2517. if len(clientId) == 0 {
  2518. return false, common.NewError("Client Not Found For Email:", clientEmail)
  2519. }
  2520. var settings map[string]any
  2521. err = json.Unmarshal([]byte(inbound.Settings), &settings)
  2522. if err != nil {
  2523. return false, err
  2524. }
  2525. clients := settings["clients"].([]any)
  2526. var newClients []any
  2527. for client_index := range clients {
  2528. c := clients[client_index].(map[string]any)
  2529. if c["email"] == clientEmail {
  2530. c["expiryTime"] = expiry_time
  2531. c["updated_at"] = time.Now().Unix() * 1000
  2532. newClients = append(newClients, any(c))
  2533. }
  2534. }
  2535. settings["clients"] = newClients
  2536. modifiedSettings, err := json.MarshalIndent(settings, "", " ")
  2537. if err != nil {
  2538. return false, err
  2539. }
  2540. inbound.Settings = string(modifiedSettings)
  2541. needRestart, err := s.UpdateInboundClient(inbound, clientId)
  2542. return needRestart, err
  2543. }
  2544. func (s *InboundService) ResetClientTrafficLimitByEmail(clientEmail string, totalGB int) (bool, error) {
  2545. if totalGB < 0 {
  2546. return false, common.NewError("totalGB must be >= 0")
  2547. }
  2548. _, inbound, err := s.GetClientInboundByEmail(clientEmail)
  2549. if err != nil {
  2550. return false, err
  2551. }
  2552. if inbound == nil {
  2553. return false, common.NewError("Inbound Not Found For Email:", clientEmail)
  2554. }
  2555. oldClients, err := s.GetClients(inbound)
  2556. if err != nil {
  2557. return false, err
  2558. }
  2559. clientId := ""
  2560. for _, oldClient := range oldClients {
  2561. if oldClient.Email == clientEmail {
  2562. switch inbound.Protocol {
  2563. case "trojan":
  2564. clientId = oldClient.Password
  2565. case "shadowsocks":
  2566. clientId = oldClient.Email
  2567. default:
  2568. clientId = oldClient.ID
  2569. }
  2570. break
  2571. }
  2572. }
  2573. if len(clientId) == 0 {
  2574. return false, common.NewError("Client Not Found For Email:", clientEmail)
  2575. }
  2576. var settings map[string]any
  2577. err = json.Unmarshal([]byte(inbound.Settings), &settings)
  2578. if err != nil {
  2579. return false, err
  2580. }
  2581. clients := settings["clients"].([]any)
  2582. var newClients []any
  2583. for client_index := range clients {
  2584. c := clients[client_index].(map[string]any)
  2585. if c["email"] == clientEmail {
  2586. c["totalGB"] = totalGB * 1024 * 1024 * 1024
  2587. c["updated_at"] = time.Now().Unix() * 1000
  2588. newClients = append(newClients, any(c))
  2589. }
  2590. }
  2591. settings["clients"] = newClients
  2592. modifiedSettings, err := json.MarshalIndent(settings, "", " ")
  2593. if err != nil {
  2594. return false, err
  2595. }
  2596. inbound.Settings = string(modifiedSettings)
  2597. needRestart, err := s.UpdateInboundClient(inbound, clientId)
  2598. return needRestart, err
  2599. }
  2600. func (s *InboundService) ResetClientTrafficByEmail(clientEmail string) error {
  2601. return submitTrafficWrite(func() error {
  2602. db := database.GetDB()
  2603. return db.Model(xray.ClientTraffic{}).
  2604. Where("email = ?", clientEmail).
  2605. Updates(map[string]any{"enable": true, "up": 0, "down": 0}).Error
  2606. })
  2607. }
  2608. func (s *InboundService) ResetClientTraffic(id int, clientEmail string) (needRestart bool, err error) {
  2609. err = submitTrafficWrite(func() error {
  2610. var inner error
  2611. needRestart, inner = s.resetClientTrafficLocked(id, clientEmail)
  2612. return inner
  2613. })
  2614. return
  2615. }
  2616. func (s *InboundService) resetClientTrafficLocked(id int, clientEmail string) (bool, error) {
  2617. needRestart := false
  2618. traffic, err := s.GetClientTrafficByEmail(clientEmail)
  2619. if err != nil {
  2620. return false, err
  2621. }
  2622. if !traffic.Enable {
  2623. inbound, err := s.GetInbound(id)
  2624. if err != nil {
  2625. return false, err
  2626. }
  2627. clients, err := s.GetClients(inbound)
  2628. if err != nil {
  2629. return false, err
  2630. }
  2631. for _, client := range clients {
  2632. if client.Email == clientEmail && client.Enable {
  2633. rt, rterr := s.runtimeFor(inbound)
  2634. if rterr != nil {
  2635. if inbound.NodeID != nil {
  2636. return false, rterr
  2637. }
  2638. needRestart = true
  2639. break
  2640. }
  2641. cipher := ""
  2642. if string(inbound.Protocol) == "shadowsocks" {
  2643. var oldSettings map[string]any
  2644. err = json.Unmarshal([]byte(inbound.Settings), &oldSettings)
  2645. if err != nil {
  2646. return false, err
  2647. }
  2648. cipher = oldSettings["method"].(string)
  2649. }
  2650. err1 := rt.AddUser(context.Background(), inbound, map[string]any{
  2651. "email": client.Email,
  2652. "id": client.ID,
  2653. "auth": client.Auth,
  2654. "security": client.Security,
  2655. "flow": client.Flow,
  2656. "password": client.Password,
  2657. "cipher": cipher,
  2658. })
  2659. if err1 == nil {
  2660. logger.Debug("Client enabled on", rt.Name(), "due to reset traffic:", clientEmail)
  2661. } else {
  2662. logger.Debug("Error in enabling client on", rt.Name(), ":", err1)
  2663. needRestart = true
  2664. }
  2665. break
  2666. }
  2667. }
  2668. }
  2669. traffic.Up = 0
  2670. traffic.Down = 0
  2671. traffic.Enable = true
  2672. db := database.GetDB()
  2673. err = db.Save(traffic).Error
  2674. if err != nil {
  2675. return false, err
  2676. }
  2677. now := time.Now().UnixMilli()
  2678. _ = db.Model(model.Inbound{}).
  2679. Where("id = ?", id).
  2680. Update("last_traffic_reset_time", now).Error
  2681. inbound, err := s.GetInbound(id)
  2682. if err == nil && inbound != nil && inbound.NodeID != nil {
  2683. if rt, rterr := s.runtimeFor(inbound); rterr == nil {
  2684. if e := rt.ResetClientTraffic(context.Background(), inbound, clientEmail); e != nil {
  2685. logger.Warning("ResetClientTraffic: remote propagation to", rt.Name(), "failed:", e)
  2686. }
  2687. } else {
  2688. logger.Warning("ResetClientTraffic: runtime lookup failed:", rterr)
  2689. }
  2690. }
  2691. return needRestart, nil
  2692. }
  2693. func (s *InboundService) ResetAllClientTraffics(id int) error {
  2694. return submitTrafficWrite(func() error {
  2695. return s.resetAllClientTrafficsLocked(id)
  2696. })
  2697. }
  2698. func (s *InboundService) resetAllClientTrafficsLocked(id int) error {
  2699. db := database.GetDB()
  2700. now := time.Now().Unix() * 1000
  2701. if err := db.Transaction(func(tx *gorm.DB) error {
  2702. whereText := "inbound_id "
  2703. if id == -1 {
  2704. whereText += " > ?"
  2705. } else {
  2706. whereText += " = ?"
  2707. }
  2708. // Reset client traffics
  2709. result := tx.Model(xray.ClientTraffic{}).
  2710. Where(whereText, id).
  2711. Updates(map[string]any{"enable": true, "up": 0, "down": 0})
  2712. if result.Error != nil {
  2713. return result.Error
  2714. }
  2715. // Update lastTrafficResetTime for the inbound(s)
  2716. inboundWhereText := "id "
  2717. if id == -1 {
  2718. inboundWhereText += " > ?"
  2719. } else {
  2720. inboundWhereText += " = ?"
  2721. }
  2722. result = tx.Model(model.Inbound{}).
  2723. Where(inboundWhereText, id).
  2724. Update("last_traffic_reset_time", now)
  2725. return result.Error
  2726. }); err != nil {
  2727. return err
  2728. }
  2729. var inbounds []model.Inbound
  2730. q := db.Model(model.Inbound{}).Where("node_id IS NOT NULL")
  2731. if id != -1 {
  2732. q = q.Where("id = ?", id)
  2733. }
  2734. if err := q.Find(&inbounds).Error; err != nil {
  2735. logger.Warning("ResetAllClientTraffics: discover node inbounds failed:", err)
  2736. return nil
  2737. }
  2738. for i := range inbounds {
  2739. ib := &inbounds[i]
  2740. rt, rterr := s.runtimeFor(ib)
  2741. if rterr != nil {
  2742. logger.Warning("ResetAllClientTraffics: runtime lookup for inbound", ib.Id, "failed:", rterr)
  2743. continue
  2744. }
  2745. if e := rt.ResetInboundClientTraffics(context.Background(), ib); e != nil {
  2746. logger.Warning("ResetAllClientTraffics: remote propagation to", rt.Name(), "failed:", e)
  2747. }
  2748. }
  2749. return nil
  2750. }
  2751. func (s *InboundService) ResetAllTraffics() error {
  2752. return submitTrafficWrite(func() error {
  2753. return s.resetAllTrafficsLocked()
  2754. })
  2755. }
  2756. func (s *InboundService) resetAllTrafficsLocked() error {
  2757. db := database.GetDB()
  2758. now := time.Now().UnixMilli()
  2759. if err := db.Model(model.Inbound{}).
  2760. Where("user_id > ?", 0).
  2761. Updates(map[string]any{
  2762. "up": 0,
  2763. "down": 0,
  2764. "last_traffic_reset_time": now,
  2765. }).Error; err != nil {
  2766. return err
  2767. }
  2768. var inbounds []model.Inbound
  2769. if err := db.Model(model.Inbound{}).
  2770. Where("node_id IS NOT NULL").
  2771. Find(&inbounds).Error; err != nil {
  2772. logger.Warning("ResetAllTraffics: discover node inbounds failed:", err)
  2773. return nil
  2774. }
  2775. for i := range inbounds {
  2776. ib := &inbounds[i]
  2777. rt, rterr := s.runtimeFor(ib)
  2778. if rterr != nil {
  2779. logger.Warning("ResetAllTraffics: runtime lookup for inbound", ib.Id, "failed:", rterr)
  2780. continue
  2781. }
  2782. if e := rt.ResetInboundClientTraffics(context.Background(), ib); e != nil {
  2783. logger.Warning("ResetAllTraffics: remote propagation to", rt.Name(), "failed:", e)
  2784. }
  2785. }
  2786. return nil
  2787. }
  2788. func (s *InboundService) ResetInboundTraffic(id int) error {
  2789. return submitTrafficWrite(func() error {
  2790. db := database.GetDB()
  2791. return db.Model(model.Inbound{}).
  2792. Where("id = ?", id).
  2793. Updates(map[string]any{"up": 0, "down": 0}).Error
  2794. })
  2795. }
  2796. func (s *InboundService) DelDepletedClients(id int) (err error) {
  2797. db := database.GetDB()
  2798. tx := db.Begin()
  2799. defer func() {
  2800. if err == nil {
  2801. tx.Commit()
  2802. } else {
  2803. tx.Rollback()
  2804. }
  2805. }()
  2806. // Collect depleted emails globally — a shared-email row owned by one
  2807. // inbound depletes every sibling that lists the email.
  2808. now := time.Now().Unix() * 1000
  2809. depletedClause := "reset = 0 and ((total > 0 and up + down >= total) or (expiry_time > 0 and expiry_time <= ?))"
  2810. var depletedRows []xray.ClientTraffic
  2811. err = db.Model(xray.ClientTraffic{}).
  2812. Where(depletedClause, now).
  2813. Find(&depletedRows).Error
  2814. if err != nil {
  2815. return err
  2816. }
  2817. if len(depletedRows) == 0 {
  2818. return nil
  2819. }
  2820. depletedEmails := make(map[string]struct{}, len(depletedRows))
  2821. for _, r := range depletedRows {
  2822. if r.Email == "" {
  2823. continue
  2824. }
  2825. depletedEmails[strings.ToLower(r.Email)] = struct{}{}
  2826. }
  2827. if len(depletedEmails) == 0 {
  2828. return nil
  2829. }
  2830. var inbounds []*model.Inbound
  2831. inboundQuery := db.Model(model.Inbound{})
  2832. if id >= 0 {
  2833. inboundQuery = inboundQuery.Where("id = ?", id)
  2834. }
  2835. if err = inboundQuery.Find(&inbounds).Error; err != nil {
  2836. return err
  2837. }
  2838. for _, inbound := range inbounds {
  2839. var settings map[string]any
  2840. if err = json.Unmarshal([]byte(inbound.Settings), &settings); err != nil {
  2841. return err
  2842. }
  2843. rawClients, ok := settings["clients"].([]any)
  2844. if !ok {
  2845. continue
  2846. }
  2847. newClients := make([]any, 0, len(rawClients))
  2848. removed := 0
  2849. for _, client := range rawClients {
  2850. c, ok := client.(map[string]any)
  2851. if !ok {
  2852. newClients = append(newClients, client)
  2853. continue
  2854. }
  2855. email, _ := c["email"].(string)
  2856. if _, isDepleted := depletedEmails[strings.ToLower(email)]; isDepleted {
  2857. removed++
  2858. continue
  2859. }
  2860. newClients = append(newClients, client)
  2861. }
  2862. if removed == 0 {
  2863. continue
  2864. }
  2865. if len(newClients) == 0 {
  2866. s.DelInbound(inbound.Id)
  2867. continue
  2868. }
  2869. settings["clients"] = newClients
  2870. ns, mErr := json.MarshalIndent(settings, "", " ")
  2871. if mErr != nil {
  2872. return mErr
  2873. }
  2874. inbound.Settings = string(ns)
  2875. if err = tx.Save(inbound).Error; err != nil {
  2876. return err
  2877. }
  2878. }
  2879. // Drop now-orphaned rows. With id >= 0, a row is safe to drop only when
  2880. // no out-of-scope inbound still references the email.
  2881. if id < 0 {
  2882. err = tx.Where(depletedClause, now).Delete(xray.ClientTraffic{}).Error
  2883. return err
  2884. }
  2885. emails := make([]string, 0, len(depletedEmails))
  2886. for e := range depletedEmails {
  2887. emails = append(emails, e)
  2888. }
  2889. var stillReferenced []string
  2890. if err = tx.Raw(`
  2891. SELECT DISTINCT LOWER(JSON_EXTRACT(client.value, '$.email'))
  2892. FROM inbounds,
  2893. JSON_EACH(JSON_EXTRACT(inbounds.settings, '$.clients')) AS client
  2894. WHERE LOWER(JSON_EXTRACT(client.value, '$.email')) IN ?
  2895. `, emails).Scan(&stillReferenced).Error; err != nil {
  2896. return err
  2897. }
  2898. stillSet := make(map[string]struct{}, len(stillReferenced))
  2899. for _, e := range stillReferenced {
  2900. stillSet[e] = struct{}{}
  2901. }
  2902. toDelete := make([]string, 0, len(emails))
  2903. for _, e := range emails {
  2904. if _, kept := stillSet[e]; !kept {
  2905. toDelete = append(toDelete, e)
  2906. }
  2907. }
  2908. if len(toDelete) > 0 {
  2909. if err = tx.Where("LOWER(email) IN ?", toDelete).Delete(xray.ClientTraffic{}).Error; err != nil {
  2910. return err
  2911. }
  2912. }
  2913. return nil
  2914. }
  2915. func (s *InboundService) GetClientTrafficTgBot(tgId int64) ([]*xray.ClientTraffic, error) {
  2916. db := database.GetDB()
  2917. var inbounds []*model.Inbound
  2918. // Retrieve inbounds where settings contain the given tgId
  2919. err := db.Model(model.Inbound{}).Where("settings LIKE ?", fmt.Sprintf(`%%"tgId": %d%%`, tgId)).Find(&inbounds).Error
  2920. if err != nil && err != gorm.ErrRecordNotFound {
  2921. logger.Errorf("Error retrieving inbounds with tgId %d: %v", tgId, err)
  2922. return nil, err
  2923. }
  2924. var emails []string
  2925. for _, inbound := range inbounds {
  2926. clients, err := s.GetClients(inbound)
  2927. if err != nil {
  2928. logger.Errorf("Error retrieving clients for inbound %d: %v", inbound.Id, err)
  2929. continue
  2930. }
  2931. for _, client := range clients {
  2932. if client.TgID == tgId {
  2933. emails = append(emails, client.Email)
  2934. }
  2935. }
  2936. }
  2937. // Chunked to stay under SQLite's bind-variable limit when a single Telegram
  2938. // account owns thousands of clients across inbounds.
  2939. uniqEmails := uniqueNonEmptyStrings(emails)
  2940. traffics := make([]*xray.ClientTraffic, 0, len(uniqEmails))
  2941. for _, batch := range chunkStrings(uniqEmails, sqliteMaxVars) {
  2942. var page []*xray.ClientTraffic
  2943. if err = db.Model(xray.ClientTraffic{}).Where("email IN ?", batch).Find(&page).Error; err != nil {
  2944. if err == gorm.ErrRecordNotFound {
  2945. continue
  2946. }
  2947. logger.Errorf("Error retrieving ClientTraffic for emails %v: %v", batch, err)
  2948. return nil, err
  2949. }
  2950. traffics = append(traffics, page...)
  2951. }
  2952. if len(traffics) == 0 {
  2953. logger.Warning("No ClientTraffic records found for emails:", emails)
  2954. return nil, nil
  2955. }
  2956. // Populate UUID and other client data for each traffic record
  2957. for i := range traffics {
  2958. if ct, client, e := s.GetClientByEmail(traffics[i].Email); e == nil && ct != nil && client != nil {
  2959. traffics[i].Enable = client.Enable
  2960. traffics[i].UUID = client.ID
  2961. traffics[i].SubId = client.SubID
  2962. }
  2963. }
  2964. return traffics, nil
  2965. }
  2966. // sqliteMaxVars is a safe ceiling for the number of bind parameters in a
  2967. // single SQL statement. SQLite's SQLITE_MAX_VARIABLE_NUMBER is 999 on builds
  2968. // before 3.32 and 32766 after; staying under 999 keeps queries portable
  2969. // across forks/old binaries and also bounds per-query memory on truly large
  2970. // installs (>32k clients) where even modern SQLite would refuse a single IN.
  2971. const sqliteMaxVars = 900
  2972. // uniqueNonEmptyStrings returns a deduplicated copy of in with empty strings
  2973. // removed, preserving the order of first occurrence.
  2974. func uniqueNonEmptyStrings(in []string) []string {
  2975. if len(in) == 0 {
  2976. return nil
  2977. }
  2978. seen := make(map[string]struct{}, len(in))
  2979. out := make([]string, 0, len(in))
  2980. for _, v := range in {
  2981. if v == "" {
  2982. continue
  2983. }
  2984. if _, ok := seen[v]; ok {
  2985. continue
  2986. }
  2987. seen[v] = struct{}{}
  2988. out = append(out, v)
  2989. }
  2990. return out
  2991. }
  2992. // uniqueInts returns a deduplicated copy of in, preserving order of first occurrence.
  2993. func uniqueInts(in []int) []int {
  2994. if len(in) == 0 {
  2995. return nil
  2996. }
  2997. seen := make(map[int]struct{}, len(in))
  2998. out := make([]int, 0, len(in))
  2999. for _, v := range in {
  3000. if _, ok := seen[v]; ok {
  3001. continue
  3002. }
  3003. seen[v] = struct{}{}
  3004. out = append(out, v)
  3005. }
  3006. return out
  3007. }
  3008. // chunkStrings splits s into consecutive sub-slices of at most size elements.
  3009. // Returns nil for an empty input or non-positive size.
  3010. func chunkStrings(s []string, size int) [][]string {
  3011. if size <= 0 || len(s) == 0 {
  3012. return nil
  3013. }
  3014. out := make([][]string, 0, (len(s)+size-1)/size)
  3015. for i := 0; i < len(s); i += size {
  3016. end := i + size
  3017. if end > len(s) {
  3018. end = len(s)
  3019. }
  3020. out = append(out, s[i:end])
  3021. }
  3022. return out
  3023. }
  3024. // chunkInts splits s into consecutive sub-slices of at most size elements.
  3025. // Returns nil for an empty input or non-positive size.
  3026. func chunkInts(s []int, size int) [][]int {
  3027. if size <= 0 || len(s) == 0 {
  3028. return nil
  3029. }
  3030. out := make([][]int, 0, (len(s)+size-1)/size)
  3031. for i := 0; i < len(s); i += size {
  3032. end := i + size
  3033. if end > len(s) {
  3034. end = len(s)
  3035. }
  3036. out = append(out, s[i:end])
  3037. }
  3038. return out
  3039. }
  3040. func (s *InboundService) GetActiveClientTraffics(emails []string) ([]*xray.ClientTraffic, error) {
  3041. uniq := uniqueNonEmptyStrings(emails)
  3042. if len(uniq) == 0 {
  3043. return nil, nil
  3044. }
  3045. db := database.GetDB()
  3046. traffics := make([]*xray.ClientTraffic, 0, len(uniq))
  3047. for _, batch := range chunkStrings(uniq, sqliteMaxVars) {
  3048. var page []*xray.ClientTraffic
  3049. if err := db.Model(xray.ClientTraffic{}).Where("email IN ?", batch).Find(&page).Error; err != nil {
  3050. return nil, err
  3051. }
  3052. traffics = append(traffics, page...)
  3053. }
  3054. return traffics, nil
  3055. }
  3056. // GetAllClientTraffics returns the full set of client_traffics rows so the
  3057. // websocket broadcasters can ship a complete snapshot every cycle. The old
  3058. // delta-only path (GetActiveClientTraffics on activeEmails) silently dropped
  3059. // the per-client section whenever no client moved bytes in the cycle or a
  3060. // node sync failed, leaving client rows in the UI stuck at stale numbers.
  3061. func (s *InboundService) GetAllClientTraffics() ([]*xray.ClientTraffic, error) {
  3062. db := database.GetDB()
  3063. var traffics []*xray.ClientTraffic
  3064. if err := db.Model(xray.ClientTraffic{}).Find(&traffics).Error; err != nil {
  3065. return nil, err
  3066. }
  3067. return traffics, nil
  3068. }
  3069. type InboundTrafficSummary struct {
  3070. Id int `json:"id"`
  3071. Up int64 `json:"up"`
  3072. Down int64 `json:"down"`
  3073. Total int64 `json:"total"`
  3074. AllTime int64 `json:"allTime"`
  3075. Enable bool `json:"enable"`
  3076. }
  3077. func (s *InboundService) GetInboundsTrafficSummary() ([]InboundTrafficSummary, error) {
  3078. db := database.GetDB()
  3079. var summaries []InboundTrafficSummary
  3080. if err := db.Model(&model.Inbound{}).
  3081. Select("id, up, down, total, all_time, enable").
  3082. Find(&summaries).Error; err != nil {
  3083. return nil, err
  3084. }
  3085. return summaries, nil
  3086. }
  3087. func (s *InboundService) GetClientTrafficByEmail(email string) (traffic *xray.ClientTraffic, err error) {
  3088. // Prefer retrieving along with client to reflect actual enabled state from inbound settings
  3089. t, client, err := s.GetClientByEmail(email)
  3090. if err != nil {
  3091. logger.Warningf("Error retrieving ClientTraffic with email %s: %v", email, err)
  3092. return nil, err
  3093. }
  3094. if t != nil && client != nil {
  3095. t.UUID = client.ID
  3096. t.SubId = client.SubID
  3097. return t, nil
  3098. }
  3099. return nil, nil
  3100. }
  3101. func (s *InboundService) UpdateClientTrafficByEmail(email string, upload int64, download int64) error {
  3102. return submitTrafficWrite(func() error {
  3103. db := database.GetDB()
  3104. err := db.Model(xray.ClientTraffic{}).
  3105. Where("email = ?", email).
  3106. Updates(map[string]any{
  3107. "up": upload,
  3108. "down": download,
  3109. "all_time": gorm.Expr("CASE WHEN COALESCE(all_time, 0) < ? THEN ? ELSE all_time END", upload+download, upload+download),
  3110. }).Error
  3111. if err != nil {
  3112. logger.Warningf("Error updating ClientTraffic with email %s: %v", email, err)
  3113. }
  3114. return err
  3115. })
  3116. }
  3117. func (s *InboundService) GetClientTrafficByID(id string) ([]xray.ClientTraffic, error) {
  3118. db := database.GetDB()
  3119. var traffics []xray.ClientTraffic
  3120. err := db.Model(xray.ClientTraffic{}).Where(`email IN(
  3121. SELECT JSON_EXTRACT(client.value, '$.email') as email
  3122. FROM inbounds,
  3123. JSON_EACH(JSON_EXTRACT(inbounds.settings, '$.clients')) AS client
  3124. WHERE
  3125. JSON_EXTRACT(client.value, '$.id') in (?)
  3126. )`, id).Find(&traffics).Error
  3127. if err != nil {
  3128. logger.Debug(err)
  3129. return nil, err
  3130. }
  3131. // Reconcile enable flag with client settings per email to avoid stale DB value
  3132. for i := range traffics {
  3133. if ct, client, e := s.GetClientByEmail(traffics[i].Email); e == nil && ct != nil && client != nil {
  3134. traffics[i].Enable = client.Enable
  3135. traffics[i].UUID = client.ID
  3136. traffics[i].SubId = client.SubID
  3137. }
  3138. }
  3139. return traffics, err
  3140. }
  3141. func (s *InboundService) SearchClientTraffic(query string) (traffic *xray.ClientTraffic, err error) {
  3142. db := database.GetDB()
  3143. inbound := &model.Inbound{}
  3144. traffic = &xray.ClientTraffic{}
  3145. // Search for inbound settings that contain the query
  3146. err = db.Model(model.Inbound{}).Where("settings LIKE ?", "%\""+query+"\"%").First(inbound).Error
  3147. if err != nil {
  3148. if err == gorm.ErrRecordNotFound {
  3149. logger.Warningf("Inbound settings containing query %s not found: %v", query, err)
  3150. return nil, err
  3151. }
  3152. logger.Errorf("Error searching for inbound settings with query %s: %v", query, err)
  3153. return nil, err
  3154. }
  3155. traffic.InboundId = inbound.Id
  3156. // Unmarshal settings to get clients
  3157. settings := map[string][]model.Client{}
  3158. if err := json.Unmarshal([]byte(inbound.Settings), &settings); err != nil {
  3159. logger.Errorf("Error unmarshalling inbound settings for inbound ID %d: %v", inbound.Id, err)
  3160. return nil, err
  3161. }
  3162. clients := settings["clients"]
  3163. for _, client := range clients {
  3164. if (client.ID == query || client.Password == query) && client.Email != "" {
  3165. traffic.Email = client.Email
  3166. break
  3167. }
  3168. }
  3169. if traffic.Email == "" {
  3170. logger.Warningf("No client found with query %s in inbound ID %d", query, inbound.Id)
  3171. return nil, gorm.ErrRecordNotFound
  3172. }
  3173. // Retrieve ClientTraffic based on the found email
  3174. err = db.Model(xray.ClientTraffic{}).Where("email = ?", traffic.Email).First(traffic).Error
  3175. if err != nil {
  3176. if err == gorm.ErrRecordNotFound {
  3177. logger.Warningf("ClientTraffic for email %s not found: %v", traffic.Email, err)
  3178. return nil, err
  3179. }
  3180. logger.Errorf("Error retrieving ClientTraffic for email %s: %v", traffic.Email, err)
  3181. return nil, err
  3182. }
  3183. return traffic, nil
  3184. }
  3185. func (s *InboundService) GetInboundClientIps(clientEmail string) (string, error) {
  3186. db := database.GetDB()
  3187. InboundClientIps := &model.InboundClientIps{}
  3188. err := db.Model(model.InboundClientIps{}).Where("client_email = ?", clientEmail).First(InboundClientIps).Error
  3189. if err != nil {
  3190. return "", err
  3191. }
  3192. if InboundClientIps.Ips == "" {
  3193. return "", nil
  3194. }
  3195. // Try to parse as new format (with timestamps)
  3196. type IPWithTimestamp struct {
  3197. IP string `json:"ip"`
  3198. Timestamp int64 `json:"timestamp"`
  3199. }
  3200. var ipsWithTime []IPWithTimestamp
  3201. err = json.Unmarshal([]byte(InboundClientIps.Ips), &ipsWithTime)
  3202. // If successfully parsed as new format, return with timestamps
  3203. if err == nil && len(ipsWithTime) > 0 {
  3204. return InboundClientIps.Ips, nil
  3205. }
  3206. // Otherwise, assume it's old format (simple string array)
  3207. // Try to parse as simple array and convert to new format
  3208. var oldIps []string
  3209. err = json.Unmarshal([]byte(InboundClientIps.Ips), &oldIps)
  3210. if err == nil && len(oldIps) > 0 {
  3211. // Convert old format to new format with current timestamp
  3212. newIpsWithTime := make([]IPWithTimestamp, len(oldIps))
  3213. for i, ip := range oldIps {
  3214. newIpsWithTime[i] = IPWithTimestamp{
  3215. IP: ip,
  3216. Timestamp: time.Now().Unix(),
  3217. }
  3218. }
  3219. result, _ := json.Marshal(newIpsWithTime)
  3220. return string(result), nil
  3221. }
  3222. // Return as-is if parsing fails
  3223. return InboundClientIps.Ips, nil
  3224. }
  3225. func (s *InboundService) ClearClientIps(clientEmail string) error {
  3226. db := database.GetDB()
  3227. result := db.Model(model.InboundClientIps{}).
  3228. Where("client_email = ?", clientEmail).
  3229. Update("ips", "")
  3230. err := result.Error
  3231. if err != nil {
  3232. return err
  3233. }
  3234. return nil
  3235. }
  3236. func (s *InboundService) SearchInbounds(query string) ([]*model.Inbound, error) {
  3237. db := database.GetDB()
  3238. var inbounds []*model.Inbound
  3239. err := db.Model(model.Inbound{}).Preload("ClientStats").Where("remark like ?", "%"+query+"%").Find(&inbounds).Error
  3240. if err != nil && err != gorm.ErrRecordNotFound {
  3241. return nil, err
  3242. }
  3243. return inbounds, nil
  3244. }
  3245. func (s *InboundService) MigrationRequirements() {
  3246. db := database.GetDB()
  3247. tx := db.Begin()
  3248. var err error
  3249. defer func() {
  3250. if err == nil {
  3251. tx.Commit()
  3252. if dbErr := db.Exec(`VACUUM "main"`).Error; dbErr != nil {
  3253. logger.Warningf("VACUUM failed: %v", dbErr)
  3254. }
  3255. } else {
  3256. tx.Rollback()
  3257. }
  3258. }()
  3259. // Calculate and backfill all_time from up+down for inbounds and clients
  3260. err = tx.Exec(`
  3261. UPDATE inbounds
  3262. SET all_time = IFNULL(up, 0) + IFNULL(down, 0)
  3263. WHERE IFNULL(all_time, 0) = 0 AND (IFNULL(up, 0) + IFNULL(down, 0)) > 0
  3264. `).Error
  3265. if err != nil {
  3266. return
  3267. }
  3268. err = tx.Exec(`
  3269. UPDATE client_traffics
  3270. SET all_time = IFNULL(up, 0) + IFNULL(down, 0)
  3271. WHERE IFNULL(all_time, 0) = 0 AND (IFNULL(up, 0) + IFNULL(down, 0)) > 0
  3272. `).Error
  3273. if err != nil {
  3274. return
  3275. }
  3276. // Fix inbounds based problems
  3277. var inbounds []*model.Inbound
  3278. err = tx.Model(model.Inbound{}).Where("protocol IN (?)", []string{"vmess", "vless", "trojan"}).Find(&inbounds).Error
  3279. if err != nil && err != gorm.ErrRecordNotFound {
  3280. return
  3281. }
  3282. for inbound_index := range inbounds {
  3283. settings := map[string]any{}
  3284. json.Unmarshal([]byte(inbounds[inbound_index].Settings), &settings)
  3285. clients, ok := settings["clients"].([]any)
  3286. if ok {
  3287. // Fix Client configuration problems
  3288. var newClients []any
  3289. hasVisionFlow := false
  3290. for client_index := range clients {
  3291. c := clients[client_index].(map[string]any)
  3292. // Add email='' if it is not exists
  3293. if _, ok := c["email"]; !ok {
  3294. c["email"] = ""
  3295. }
  3296. // Convert string tgId to int64
  3297. if _, ok := c["tgId"]; ok {
  3298. var tgId any = c["tgId"]
  3299. if tgIdStr, ok2 := tgId.(string); ok2 {
  3300. tgIdInt64, err := strconv.ParseInt(strings.ReplaceAll(tgIdStr, " ", ""), 10, 64)
  3301. if err == nil {
  3302. c["tgId"] = tgIdInt64
  3303. }
  3304. }
  3305. }
  3306. // Remove "flow": "xtls-rprx-direct"
  3307. if _, ok := c["flow"]; ok {
  3308. if c["flow"] == "xtls-rprx-direct" {
  3309. c["flow"] = ""
  3310. }
  3311. }
  3312. if flow, _ := c["flow"].(string); flow == "xtls-rprx-vision" {
  3313. hasVisionFlow = true
  3314. }
  3315. // Backfill created_at and updated_at
  3316. if _, ok := c["created_at"]; !ok {
  3317. c["created_at"] = time.Now().Unix() * 1000
  3318. }
  3319. c["updated_at"] = time.Now().Unix() * 1000
  3320. newClients = append(newClients, any(c))
  3321. }
  3322. settings["clients"] = newClients
  3323. // Drop orphaned testseed: VLESS-only field, only meaningful when at least
  3324. // one client uses the exact xtls-rprx-vision flow. Older versions saved it
  3325. // for any non-empty flow (including the UDP variant) or kept it after the
  3326. // flow was cleared from the client modal — clean those up here.
  3327. if inbounds[inbound_index].Protocol == model.VLESS && !hasVisionFlow {
  3328. delete(settings, "testseed")
  3329. }
  3330. modifiedSettings, err := json.MarshalIndent(settings, "", " ")
  3331. if err != nil {
  3332. return
  3333. }
  3334. inbounds[inbound_index].Settings = string(modifiedSettings)
  3335. }
  3336. // Add client traffic row for all clients which has email
  3337. modelClients, err := s.GetClients(inbounds[inbound_index])
  3338. if err != nil {
  3339. return
  3340. }
  3341. for _, modelClient := range modelClients {
  3342. if len(modelClient.Email) > 0 {
  3343. var count int64
  3344. tx.Model(xray.ClientTraffic{}).Where("email = ?", modelClient.Email).Count(&count)
  3345. if count == 0 {
  3346. s.AddClientStat(tx, inbounds[inbound_index].Id, &modelClient)
  3347. }
  3348. }
  3349. }
  3350. }
  3351. tx.Save(inbounds)
  3352. // Remove orphaned traffics
  3353. tx.Where("inbound_id = 0").Delete(xray.ClientTraffic{})
  3354. // Migrate old MultiDomain to External Proxy
  3355. var externalProxy []struct {
  3356. Id int
  3357. Port int
  3358. StreamSettings []byte
  3359. }
  3360. err = tx.Raw(`select id, port, stream_settings
  3361. from inbounds
  3362. WHERE protocol in ('vmess','vless','trojan')
  3363. AND json_extract(stream_settings, '$.security') = 'tls'
  3364. AND json_extract(stream_settings, '$.tlsSettings.settings.domains') IS NOT NULL`).Scan(&externalProxy).Error
  3365. if err != nil || len(externalProxy) == 0 {
  3366. return
  3367. }
  3368. for _, ep := range externalProxy {
  3369. var reverses any
  3370. var stream map[string]any
  3371. json.Unmarshal(ep.StreamSettings, &stream)
  3372. if tlsSettings, ok := stream["tlsSettings"].(map[string]any); ok {
  3373. if settings, ok := tlsSettings["settings"].(map[string]any); ok {
  3374. if domains, ok := settings["domains"].([]any); ok {
  3375. for _, domain := range domains {
  3376. if domainMap, ok := domain.(map[string]any); ok {
  3377. domainMap["forceTls"] = "same"
  3378. domainMap["port"] = ep.Port
  3379. domainMap["dest"] = domainMap["domain"].(string)
  3380. delete(domainMap, "domain")
  3381. }
  3382. }
  3383. }
  3384. reverses = settings["domains"]
  3385. delete(settings, "domains")
  3386. }
  3387. }
  3388. stream["externalProxy"] = reverses
  3389. newStream, _ := json.MarshalIndent(stream, " ", " ")
  3390. tx.Model(model.Inbound{}).Where("id = ?", ep.Id).Update("stream_settings", newStream)
  3391. }
  3392. err = tx.Raw(`UPDATE inbounds
  3393. SET tag = REPLACE(tag, '0.0.0.0:', '')
  3394. WHERE INSTR(tag, '0.0.0.0:') > 0;`).Error
  3395. if err != nil {
  3396. return
  3397. }
  3398. }
  3399. func (s *InboundService) MigrateDB() {
  3400. s.MigrationRequirements()
  3401. s.MigrationRemoveOrphanedTraffics()
  3402. }
  3403. func (s *InboundService) GetOnlineClients() []string {
  3404. return p.GetOnlineClients()
  3405. }
  3406. func (s *InboundService) SetNodeOnlineClients(nodeID int, emails []string) {
  3407. if p != nil {
  3408. p.SetNodeOnlineClients(nodeID, emails)
  3409. }
  3410. }
  3411. func (s *InboundService) ClearNodeOnlineClients(nodeID int) {
  3412. if p != nil {
  3413. p.ClearNodeOnlineClients(nodeID)
  3414. }
  3415. }
  3416. func (s *InboundService) GetClientsLastOnline() (map[string]int64, error) {
  3417. db := database.GetDB()
  3418. var rows []xray.ClientTraffic
  3419. err := db.Model(&xray.ClientTraffic{}).Select("email, last_online").Find(&rows).Error
  3420. if err != nil && err != gorm.ErrRecordNotFound {
  3421. return nil, err
  3422. }
  3423. result := make(map[string]int64, len(rows))
  3424. for _, r := range rows {
  3425. result[r.Email] = r.LastOnline
  3426. }
  3427. return result, nil
  3428. }
  3429. func (s *InboundService) RefreshOnlineClientsFromMap(lastOnlineMap map[string]int64) {
  3430. now := time.Now().UnixMilli()
  3431. newOnlineClients := make([]string, 0, len(lastOnlineMap))
  3432. for email, lastOnline := range lastOnlineMap {
  3433. if now-lastOnline < onlineGracePeriodMs {
  3434. newOnlineClients = append(newOnlineClients, email)
  3435. }
  3436. }
  3437. if p != nil {
  3438. p.SetOnlineClients(newOnlineClients)
  3439. }
  3440. }
  3441. func (s *InboundService) FilterAndSortClientEmails(emails []string) ([]string, []string, error) {
  3442. db := database.GetDB()
  3443. // Step 1: Get ClientTraffic records for emails in the input list.
  3444. // Chunked to stay under SQLite's bind-variable limit on huge inputs.
  3445. uniqEmails := uniqueNonEmptyStrings(emails)
  3446. clients := make([]xray.ClientTraffic, 0, len(uniqEmails))
  3447. for _, batch := range chunkStrings(uniqEmails, sqliteMaxVars) {
  3448. var page []xray.ClientTraffic
  3449. if err := db.Where("email IN ?", batch).Find(&page).Error; err != nil && err != gorm.ErrRecordNotFound {
  3450. return nil, nil, err
  3451. }
  3452. clients = append(clients, page...)
  3453. }
  3454. // Step 2: Sort clients by (Up + Down) descending
  3455. sort.Slice(clients, func(i, j int) bool {
  3456. return (clients[i].Up + clients[i].Down) > (clients[j].Up + clients[j].Down)
  3457. })
  3458. // Step 3: Extract sorted valid emails and track found ones
  3459. validEmails := make([]string, 0, len(clients))
  3460. found := make(map[string]bool)
  3461. for _, client := range clients {
  3462. validEmails = append(validEmails, client.Email)
  3463. found[client.Email] = true
  3464. }
  3465. // Step 4: Identify emails that were not found in the database
  3466. extraEmails := make([]string, 0)
  3467. for _, email := range emails {
  3468. if !found[email] {
  3469. extraEmails = append(extraEmails, email)
  3470. }
  3471. }
  3472. return validEmails, extraEmails, nil
  3473. }
  3474. func (s *InboundService) DelInboundClientByEmail(inboundId int, email string) (bool, error) {
  3475. oldInbound, err := s.GetInbound(inboundId)
  3476. if err != nil {
  3477. logger.Error("Load Old Data Error")
  3478. return false, err
  3479. }
  3480. var settings map[string]any
  3481. if err := json.Unmarshal([]byte(oldInbound.Settings), &settings); err != nil {
  3482. return false, err
  3483. }
  3484. interfaceClients, ok := settings["clients"].([]any)
  3485. if !ok {
  3486. return false, common.NewError("invalid clients format in inbound settings")
  3487. }
  3488. var newClients []any
  3489. needApiDel := false
  3490. found := false
  3491. for _, client := range interfaceClients {
  3492. c, ok := client.(map[string]any)
  3493. if !ok {
  3494. continue
  3495. }
  3496. if cEmail, ok := c["email"].(string); ok && cEmail == email {
  3497. // matched client, drop it
  3498. found = true
  3499. needApiDel, _ = c["enable"].(bool)
  3500. } else {
  3501. newClients = append(newClients, client)
  3502. }
  3503. }
  3504. if !found {
  3505. return false, common.NewError(fmt.Sprintf("client with email %s not found", email))
  3506. }
  3507. if len(newClients) == 0 {
  3508. return false, common.NewError("no client remained in Inbound")
  3509. }
  3510. settings["clients"] = newClients
  3511. newSettings, err := json.MarshalIndent(settings, "", " ")
  3512. if err != nil {
  3513. return false, err
  3514. }
  3515. oldInbound.Settings = string(newSettings)
  3516. db := database.GetDB()
  3517. // Drop the row and IPs only when this was the last inbound referencing
  3518. // the email — siblings still need the shared accounting state.
  3519. emailShared, err := s.emailUsedByOtherInbounds(email, inboundId)
  3520. if err != nil {
  3521. return false, err
  3522. }
  3523. if !emailShared {
  3524. if err := s.DelClientIPs(db, email); err != nil {
  3525. logger.Error("Error in delete client IPs")
  3526. return false, err
  3527. }
  3528. }
  3529. needRestart := false
  3530. // remove stats too
  3531. if len(email) > 0 && !emailShared {
  3532. traffic, err := s.GetClientTrafficByEmail(email)
  3533. if err != nil {
  3534. return false, err
  3535. }
  3536. if traffic != nil {
  3537. if err := s.DelClientStat(db, email); err != nil {
  3538. logger.Error("Delete stats Data Error")
  3539. return false, err
  3540. }
  3541. }
  3542. if needApiDel {
  3543. rt, rterr := s.runtimeFor(oldInbound)
  3544. if rterr != nil {
  3545. if oldInbound.NodeID != nil {
  3546. return false, rterr
  3547. }
  3548. needRestart = true
  3549. } else if oldInbound.NodeID == nil {
  3550. if err1 := rt.RemoveUser(context.Background(), oldInbound, email); err1 == nil {
  3551. logger.Debug("Client deleted on", rt.Name(), ":", email)
  3552. needRestart = false
  3553. } else if strings.Contains(err1.Error(), fmt.Sprintf("User %s not found.", email)) {
  3554. logger.Debug("User is already deleted. Nothing to do more...")
  3555. } else {
  3556. logger.Debug("Error in deleting client on", rt.Name(), ":", err1)
  3557. needRestart = true
  3558. }
  3559. } else {
  3560. if err1 := rt.UpdateInbound(context.Background(), oldInbound, oldInbound); err1 != nil {
  3561. return false, err1
  3562. }
  3563. }
  3564. }
  3565. }
  3566. return needRestart, db.Save(oldInbound).Error
  3567. }
  3568. type SubLinkProvider interface {
  3569. SubLinksForSubId(host, subId string) ([]string, error)
  3570. LinksForClient(host string, inbound *model.Inbound, email string) []string
  3571. }
  3572. var registeredSubLinkProvider SubLinkProvider
  3573. func RegisterSubLinkProvider(p SubLinkProvider) {
  3574. registeredSubLinkProvider = p
  3575. }
  3576. func (s *InboundService) GetSubLinks(host, subId string) ([]string, error) {
  3577. if registeredSubLinkProvider == nil {
  3578. return nil, common.NewError("sub link provider not registered")
  3579. }
  3580. return registeredSubLinkProvider.SubLinksForSubId(host, subId)
  3581. }
  3582. func (s *InboundService) GetClientLinks(host string, id int, email string) ([]string, error) {
  3583. inbound, err := s.GetInbound(id)
  3584. if err != nil {
  3585. return nil, err
  3586. }
  3587. if registeredSubLinkProvider == nil {
  3588. return nil, common.NewError("sub link provider not registered")
  3589. }
  3590. return registeredSubLinkProvider.LinksForClient(host, inbound, email), nil
  3591. }