inbound.go 94 KB

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