inbound.go 94 KB

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