inbound.go 113 KB

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