inbound.go 108 KB

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