inbound.go 91 KB

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