1
0

inbound.go 93 KB

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