inbound.go 102 KB

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