1
0

inbound.go 94 KB

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