inbound.go 89 KB

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