1
0

inbound.go 116 KB

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