1
0

inbound.go 93 KB

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