1
0

inbound.go 97 KB

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