inbound.go 109 KB

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