inbound.go 108 KB

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