1
0

inbound.go 116 KB

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