inbound.go 103 KB

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