inbound.go 92 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204
  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. }
  432. if !protocolsWithStream[inbound.Protocol] {
  433. inbound.StreamSettings = ""
  434. }
  435. }
  436. // AddInbound creates a new inbound configuration.
  437. // It validates port uniqueness, client email uniqueness, and required fields,
  438. // then saves the inbound to the database and optionally adds it to the running Xray instance.
  439. // Returns the created inbound, whether Xray needs restart, and any error.
  440. func (s *InboundService) AddInbound(inbound *model.Inbound) (*model.Inbound, bool, error) {
  441. // Normalize streamSettings based on protocol
  442. s.normalizeStreamSettings(inbound)
  443. conflict, err := s.checkPortConflict(inbound, 0)
  444. if err != nil {
  445. return inbound, false, err
  446. }
  447. if conflict != nil {
  448. return inbound, false, common.NewError(conflict.String())
  449. }
  450. inbound.Tag, err = s.resolveInboundTag(inbound, 0)
  451. if err != nil {
  452. return inbound, false, err
  453. }
  454. clients, err := s.GetClients(inbound)
  455. if err != nil {
  456. return inbound, false, err
  457. }
  458. existEmail, err := s.clientService.checkEmailsExistForClients(s, clients)
  459. if err != nil {
  460. return inbound, false, err
  461. }
  462. if existEmail != "" {
  463. return inbound, false, common.NewError("Duplicate email:", existEmail)
  464. }
  465. // Ensure created_at and updated_at on clients in settings
  466. if len(clients) > 0 {
  467. var settings map[string]any
  468. if err2 := json.Unmarshal([]byte(inbound.Settings), &settings); err2 == nil && settings != nil {
  469. now := time.Now().Unix() * 1000
  470. updatedClients := make([]model.Client, 0, len(clients))
  471. for _, c := range clients {
  472. if c.CreatedAt == 0 {
  473. c.CreatedAt = now
  474. }
  475. c.UpdatedAt = now
  476. updatedClients = append(updatedClients, c)
  477. }
  478. settings["clients"] = updatedClients
  479. if bs, err3 := json.MarshalIndent(settings, "", " "); err3 == nil {
  480. inbound.Settings = string(bs)
  481. } else {
  482. logger.Debug("Unable to marshal inbound settings with timestamps:", err3)
  483. }
  484. } else if err2 != nil {
  485. logger.Debug("Unable to parse inbound settings for timestamps:", err2)
  486. }
  487. }
  488. // Secure client ID
  489. for _, client := range clients {
  490. switch inbound.Protocol {
  491. case "trojan":
  492. if client.Password == "" {
  493. return inbound, false, common.NewError("empty client ID")
  494. }
  495. case "shadowsocks":
  496. if client.Email == "" {
  497. return inbound, false, common.NewError("empty client ID")
  498. }
  499. case "hysteria":
  500. if client.Auth == "" {
  501. return inbound, false, common.NewError("empty client ID")
  502. }
  503. default:
  504. if client.ID == "" {
  505. return inbound, false, common.NewError("empty client ID")
  506. }
  507. }
  508. }
  509. db := database.GetDB()
  510. tx := db.Begin()
  511. defer func() {
  512. if err == nil {
  513. tx.Commit()
  514. } else {
  515. tx.Rollback()
  516. }
  517. }()
  518. err = tx.Save(inbound).Error
  519. if err == nil {
  520. if len(inbound.ClientStats) == 0 {
  521. for _, client := range clients {
  522. s.AddClientStat(tx, inbound.Id, &client)
  523. }
  524. }
  525. } else {
  526. return inbound, false, err
  527. }
  528. if err = s.clientService.SyncInbound(tx, inbound.Id, clients); err != nil {
  529. return inbound, false, err
  530. }
  531. needRestart := false
  532. if inbound.Enable {
  533. rt, rterr := s.runtimeFor(inbound)
  534. if rterr != nil {
  535. err = rterr
  536. return inbound, false, err
  537. }
  538. if err1 := rt.AddInbound(context.Background(), inbound); err1 == nil {
  539. logger.Debug("New inbound added on", rt.Name(), ":", inbound.Tag)
  540. } else {
  541. logger.Debug("Unable to add inbound on", rt.Name(), ":", err1)
  542. if inbound.NodeID != nil {
  543. err = err1
  544. return inbound, false, err
  545. }
  546. needRestart = true
  547. }
  548. }
  549. return inbound, needRestart, err
  550. }
  551. func (s *InboundService) DelInbound(id int) (bool, error) {
  552. db := database.GetDB()
  553. needRestart := false
  554. var ib model.Inbound
  555. loadErr := db.Model(model.Inbound{}).Where("id = ?", id).First(&ib).Error
  556. if loadErr == nil {
  557. shouldPushToRuntime := ib.NodeID != nil || ib.Enable
  558. if shouldPushToRuntime {
  559. rt, rterr := s.runtimeFor(&ib)
  560. if rterr != nil {
  561. logger.Warning("DelInbound: runtime lookup failed, deleting central row anyway:", rterr)
  562. if ib.NodeID == nil {
  563. needRestart = true
  564. }
  565. } else if err1 := rt.DelInbound(context.Background(), &ib); err1 == nil {
  566. logger.Debug("Inbound deleted on", rt.Name(), ":", ib.Tag)
  567. } else {
  568. logger.Warning("DelInbound on", rt.Name(), "failed, deleting central row anyway:", err1)
  569. if ib.NodeID == nil {
  570. needRestart = true
  571. }
  572. }
  573. } else {
  574. logger.Debug("DelInbound: skipping runtime push for disabled local inbound id:", id)
  575. }
  576. } else {
  577. logger.Debug("DelInbound: inbound not found, id:", id)
  578. }
  579. // Delete client traffics of inbounds
  580. err := db.Where("inbound_id = ?", id).Delete(xray.ClientTraffic{}).Error
  581. if err != nil {
  582. return false, err
  583. }
  584. if err := s.clientService.DetachInbound(db, id); err != nil {
  585. return false, err
  586. }
  587. inbound, err := s.GetInbound(id)
  588. if err != nil {
  589. return false, err
  590. }
  591. clients, err := s.GetClients(inbound)
  592. if err != nil {
  593. return false, err
  594. }
  595. // Bulk-delete client IPs for every email in this inbound. The previous
  596. // per-client loop fired one DELETE per row — at 7k+ clients that meant
  597. // thousands of synchronous SQL roundtrips and a multi-second freeze.
  598. // Chunked to stay under SQLite's bind-variable limit on huge inbounds.
  599. if len(clients) > 0 {
  600. emails := make([]string, 0, len(clients))
  601. for i := range clients {
  602. if clients[i].Email != "" {
  603. emails = append(emails, clients[i].Email)
  604. }
  605. }
  606. for _, batch := range chunkStrings(uniqueNonEmptyStrings(emails), sqliteMaxVars) {
  607. if err := db.Where("client_email IN ?", batch).
  608. Delete(model.InboundClientIps{}).Error; err != nil {
  609. return false, err
  610. }
  611. }
  612. }
  613. return needRestart, db.Delete(model.Inbound{}, id).Error
  614. }
  615. func (s *InboundService) GetInbound(id int) (*model.Inbound, error) {
  616. db := database.GetDB()
  617. inbound := &model.Inbound{}
  618. err := db.Model(model.Inbound{}).First(inbound, id).Error
  619. if err != nil {
  620. return nil, err
  621. }
  622. return inbound, nil
  623. }
  624. // SetInboundEnable toggles only the enable flag of an inbound, without
  625. // rewriting the (potentially multi-MB) settings JSON. Used by the UI's
  626. // per-row enable switch — for inbounds with thousands of clients the full
  627. // UpdateInbound path is an order of magnitude too slow for an interactive
  628. // toggle (parses + reserialises every client, runs O(N) traffic diff).
  629. //
  630. // Returns (needRestart, error). needRestart is true when the xray runtime
  631. // could not be re-synced from the cached config and a full restart is
  632. // required to pick up the change.
  633. func (s *InboundService) SetInboundEnable(id int, enable bool) (bool, error) {
  634. inbound, err := s.GetInbound(id)
  635. if err != nil {
  636. return false, err
  637. }
  638. if inbound.Enable == enable {
  639. return false, nil
  640. }
  641. db := database.GetDB()
  642. if err := db.Model(model.Inbound{}).Where("id = ?", id).
  643. Update("enable", enable).Error; err != nil {
  644. return false, err
  645. }
  646. inbound.Enable = enable
  647. needRestart := false
  648. rt, rterr := s.runtimeFor(inbound)
  649. if rterr != nil {
  650. if inbound.NodeID != nil {
  651. return false, rterr
  652. }
  653. return true, nil
  654. }
  655. // Remote nodes interpret DelInbound as a real row delete (it hits
  656. // panel/api/inbounds/del/:id on the remote), so toggling the enable
  657. // switch on a remote inbound used to wipe the row entirely (#4402).
  658. // PATCH the remote row via UpdateInbound instead — preserves the
  659. // settings/client history and just flips the enable flag.
  660. if inbound.NodeID != nil {
  661. if err := rt.UpdateInbound(context.Background(), inbound, inbound); err != nil {
  662. logger.Debug("SetInboundEnable: remote UpdateInbound on", rt.Name(), "failed:", err)
  663. return false, err
  664. }
  665. return false, nil
  666. }
  667. if err := rt.DelInbound(context.Background(), inbound); err != nil &&
  668. !strings.Contains(err.Error(), "not found") {
  669. logger.Debug("SetInboundEnable: DelInbound on", rt.Name(), "failed:", err)
  670. needRestart = true
  671. }
  672. if !enable {
  673. return needRestart, nil
  674. }
  675. runtimeInbound, err := s.buildRuntimeInboundForAPI(db, inbound)
  676. if err != nil {
  677. logger.Debug("SetInboundEnable: build runtime config failed:", err)
  678. return true, nil
  679. }
  680. if err := rt.AddInbound(context.Background(), runtimeInbound); err != nil {
  681. logger.Debug("SetInboundEnable: AddInbound on", rt.Name(), "failed:", err)
  682. needRestart = true
  683. }
  684. return needRestart, nil
  685. }
  686. func (s *InboundService) UpdateInbound(inbound *model.Inbound) (*model.Inbound, bool, error) {
  687. // Normalize streamSettings based on protocol
  688. s.normalizeStreamSettings(inbound)
  689. conflict, err := s.checkPortConflict(inbound, inbound.Id)
  690. if err != nil {
  691. return inbound, false, err
  692. }
  693. if conflict != nil {
  694. return inbound, false, common.NewError(conflict.String())
  695. }
  696. oldInbound, err := s.GetInbound(inbound.Id)
  697. if err != nil {
  698. return inbound, false, err
  699. }
  700. tag := oldInbound.Tag
  701. db := database.GetDB()
  702. tx := db.Begin()
  703. defer func() {
  704. if err != nil {
  705. tx.Rollback()
  706. } else {
  707. tx.Commit()
  708. }
  709. }()
  710. err = s.updateClientTraffics(tx, oldInbound, inbound)
  711. if err != nil {
  712. return inbound, false, err
  713. }
  714. // Ensure created_at and updated_at exist in inbound.Settings clients
  715. {
  716. var oldSettings map[string]any
  717. _ = json.Unmarshal([]byte(oldInbound.Settings), &oldSettings)
  718. emailToCreated := map[string]int64{}
  719. emailToUpdated := map[string]int64{}
  720. if oldSettings != nil {
  721. if oc, ok := oldSettings["clients"].([]any); ok {
  722. for _, it := range oc {
  723. if m, ok2 := it.(map[string]any); ok2 {
  724. if email, ok3 := m["email"].(string); ok3 {
  725. switch v := m["created_at"].(type) {
  726. case float64:
  727. emailToCreated[email] = int64(v)
  728. case int64:
  729. emailToCreated[email] = v
  730. }
  731. switch v := m["updated_at"].(type) {
  732. case float64:
  733. emailToUpdated[email] = int64(v)
  734. case int64:
  735. emailToUpdated[email] = v
  736. }
  737. }
  738. }
  739. }
  740. }
  741. }
  742. var newSettings map[string]any
  743. if err2 := json.Unmarshal([]byte(inbound.Settings), &newSettings); err2 == nil && newSettings != nil {
  744. now := time.Now().Unix() * 1000
  745. if nSlice, ok := newSettings["clients"].([]any); ok {
  746. for i := range nSlice {
  747. if m, ok2 := nSlice[i].(map[string]any); ok2 {
  748. email, _ := m["email"].(string)
  749. if _, ok3 := m["created_at"]; !ok3 {
  750. if v, ok4 := emailToCreated[email]; ok4 && v > 0 {
  751. m["created_at"] = v
  752. } else {
  753. m["created_at"] = now
  754. }
  755. }
  756. // Preserve client's updated_at if present; do not bump on parent inbound update
  757. if _, hasUpdated := m["updated_at"]; !hasUpdated {
  758. if v, ok4 := emailToUpdated[email]; ok4 && v > 0 {
  759. m["updated_at"] = v
  760. }
  761. }
  762. nSlice[i] = m
  763. }
  764. }
  765. newSettings["clients"] = nSlice
  766. if bs, err3 := json.MarshalIndent(newSettings, "", " "); err3 == nil {
  767. inbound.Settings = string(bs)
  768. }
  769. }
  770. }
  771. }
  772. oldInbound.Total = inbound.Total
  773. oldInbound.Remark = inbound.Remark
  774. oldInbound.Enable = inbound.Enable
  775. oldInbound.ExpiryTime = inbound.ExpiryTime
  776. oldInbound.TrafficReset = inbound.TrafficReset
  777. oldInbound.Listen = inbound.Listen
  778. oldInbound.Port = inbound.Port
  779. oldInbound.Protocol = inbound.Protocol
  780. oldInbound.Settings = inbound.Settings
  781. oldInbound.StreamSettings = inbound.StreamSettings
  782. oldInbound.Sniffing = inbound.Sniffing
  783. oldInbound.Tag, err = s.resolveInboundTag(inbound, inbound.Id)
  784. if err != nil {
  785. return inbound, false, err
  786. }
  787. needRestart := false
  788. rt, rterr := s.runtimeFor(oldInbound)
  789. if rterr != nil {
  790. if oldInbound.NodeID != nil {
  791. err = rterr
  792. return inbound, false, err
  793. }
  794. needRestart = true
  795. } else {
  796. oldSnapshot := *oldInbound
  797. oldSnapshot.Tag = tag
  798. if oldInbound.NodeID == nil {
  799. if err2 := rt.DelInbound(context.Background(), &oldSnapshot); err2 == nil {
  800. logger.Debug("Old inbound deleted on", rt.Name(), ":", tag)
  801. }
  802. if inbound.Enable {
  803. runtimeInbound, err2 := s.buildRuntimeInboundForAPI(tx, oldInbound)
  804. if err2 != nil {
  805. logger.Debug("Unable to prepare runtime inbound config:", err2)
  806. needRestart = true
  807. } else if err2 := rt.AddInbound(context.Background(), runtimeInbound); err2 == nil {
  808. logger.Debug("Updated inbound added on", rt.Name(), ":", oldInbound.Tag)
  809. } else {
  810. logger.Debug("Unable to update inbound on", rt.Name(), ":", err2)
  811. needRestart = true
  812. }
  813. }
  814. } else {
  815. if !inbound.Enable {
  816. if err2 := rt.DelInbound(context.Background(), &oldSnapshot); err2 != nil {
  817. err = err2
  818. return inbound, false, err
  819. }
  820. } else if err2 := rt.UpdateInbound(context.Background(), &oldSnapshot, oldInbound); err2 != nil {
  821. err = err2
  822. return inbound, false, err
  823. }
  824. }
  825. }
  826. if err = tx.Save(oldInbound).Error; err != nil {
  827. return inbound, false, err
  828. }
  829. newClients, gcErr := s.GetClients(oldInbound)
  830. if gcErr != nil {
  831. err = gcErr
  832. return inbound, false, err
  833. }
  834. if err = s.clientService.SyncInbound(tx, oldInbound.Id, newClients); err != nil {
  835. return inbound, false, err
  836. }
  837. return inbound, needRestart, nil
  838. }
  839. func (s *InboundService) buildRuntimeInboundForAPI(tx *gorm.DB, inbound *model.Inbound) (*model.Inbound, error) {
  840. if inbound == nil {
  841. return nil, fmt.Errorf("inbound is nil")
  842. }
  843. runtimeInbound := *inbound
  844. settings := map[string]any{}
  845. if err := json.Unmarshal([]byte(inbound.Settings), &settings); err != nil {
  846. return nil, err
  847. }
  848. clients, ok := settings["clients"].([]any)
  849. if !ok {
  850. return &runtimeInbound, nil
  851. }
  852. var clientStats []xray.ClientTraffic
  853. err := tx.Model(xray.ClientTraffic{}).
  854. Where("inbound_id = ?", inbound.Id).
  855. Select("email", "enable").
  856. Find(&clientStats).Error
  857. if err != nil {
  858. return nil, err
  859. }
  860. enableMap := make(map[string]bool, len(clientStats))
  861. for _, clientTraffic := range clientStats {
  862. enableMap[clientTraffic.Email] = clientTraffic.Enable
  863. }
  864. finalClients := make([]any, 0, len(clients))
  865. for _, client := range clients {
  866. c, ok := client.(map[string]any)
  867. if !ok {
  868. continue
  869. }
  870. email, _ := c["email"].(string)
  871. if enable, exists := enableMap[email]; exists && !enable {
  872. continue
  873. }
  874. if manualEnable, ok := c["enable"].(bool); ok && !manualEnable {
  875. continue
  876. }
  877. finalClients = append(finalClients, c)
  878. }
  879. settings["clients"] = finalClients
  880. modifiedSettings, err := json.MarshalIndent(settings, "", " ")
  881. if err != nil {
  882. return nil, err
  883. }
  884. runtimeInbound.Settings = string(modifiedSettings)
  885. return &runtimeInbound, nil
  886. }
  887. // updateClientTraffics syncs the ClientTraffic rows with the inbound's clients
  888. // list: removes rows for emails that disappeared, inserts rows for newly-added
  889. // emails. Uses sets for O(N) lookup — the previous nested-loop implementation
  890. // was O(N²) and degraded into multi-second pauses on inbounds with thousands
  891. // of clients (toggling, saving, or deleting any such inbound felt frozen).
  892. func (s *InboundService) updateClientTraffics(tx *gorm.DB, oldInbound *model.Inbound, newInbound *model.Inbound) error {
  893. oldClients, err := s.GetClients(oldInbound)
  894. if err != nil {
  895. return err
  896. }
  897. newClients, err := s.GetClients(newInbound)
  898. if err != nil {
  899. return err
  900. }
  901. // Email is the unique key for ClientTraffic rows. Clients without an
  902. // email have no stats row to sync — skip them on both sides instead of
  903. // risking a unique-constraint hit or accidental delete of an unrelated row.
  904. oldEmails := make(map[string]struct{}, len(oldClients))
  905. for i := range oldClients {
  906. if oldClients[i].Email == "" {
  907. continue
  908. }
  909. oldEmails[oldClients[i].Email] = struct{}{}
  910. }
  911. newEmails := make(map[string]struct{}, len(newClients))
  912. for i := range newClients {
  913. if newClients[i].Email == "" {
  914. continue
  915. }
  916. newEmails[newClients[i].Email] = struct{}{}
  917. }
  918. // Drop stats rows for removed emails — but not when a sibling inbound
  919. // still references the email, since the row is the shared accumulator.
  920. for i := range oldClients {
  921. email := oldClients[i].Email
  922. if email == "" {
  923. continue
  924. }
  925. if _, kept := newEmails[email]; kept {
  926. continue
  927. }
  928. stillUsed, err := s.emailUsedByOtherInbounds(email, oldInbound.Id)
  929. if err != nil {
  930. return err
  931. }
  932. if stillUsed {
  933. continue
  934. }
  935. if err := s.DelClientStat(tx, email); err != nil {
  936. return err
  937. }
  938. }
  939. for i := range newClients {
  940. email := newClients[i].Email
  941. if email == "" {
  942. continue
  943. }
  944. if _, existed := oldEmails[email]; existed {
  945. if err := s.UpdateClientStat(tx, email, &newClients[i]); err != nil {
  946. return err
  947. }
  948. continue
  949. }
  950. if err := s.AddClientStat(tx, oldInbound.Id, &newClients[i]); err != nil {
  951. return err
  952. }
  953. }
  954. return nil
  955. }
  956. func (s *InboundService) getClientPrimaryKey(protocol model.Protocol, client model.Client) string {
  957. switch protocol {
  958. case model.Trojan:
  959. return client.Password
  960. case model.Shadowsocks:
  961. return client.Email
  962. case model.Hysteria:
  963. return client.Auth
  964. default:
  965. return client.ID
  966. }
  967. }
  968. func (s *InboundService) writeBackClientSubID(sourceInboundID int, sourceProtocol model.Protocol, client model.Client, subID string) (bool, error) {
  969. client.SubID = subID
  970. client.UpdatedAt = time.Now().UnixMilli()
  971. clientID := s.getClientPrimaryKey(sourceProtocol, client)
  972. if clientID == "" {
  973. return false, common.NewError("empty client ID")
  974. }
  975. settingsBytes, err := json.Marshal(map[string][]model.Client{
  976. "clients": {client},
  977. })
  978. if err != nil {
  979. return false, err
  980. }
  981. updatePayload := &model.Inbound{
  982. Id: sourceInboundID,
  983. Settings: string(settingsBytes),
  984. }
  985. return s.clientService.UpdateInboundClient(s, updatePayload, clientID)
  986. }
  987. func (s *InboundService) generateRandomCredential(targetProtocol model.Protocol) string {
  988. switch targetProtocol {
  989. case model.VMESS, model.VLESS:
  990. return uuid.NewString()
  991. default:
  992. return strings.ReplaceAll(uuid.NewString(), "-", "")
  993. }
  994. }
  995. func (s *InboundService) buildTargetClientFromSource(source model.Client, targetProtocol model.Protocol, email string, flow string) (model.Client, error) {
  996. nowTs := time.Now().UnixMilli()
  997. target := source
  998. target.Email = email
  999. target.CreatedAt = nowTs
  1000. target.UpdatedAt = nowTs
  1001. target.ID = ""
  1002. target.Password = ""
  1003. target.Auth = ""
  1004. target.Flow = ""
  1005. switch targetProtocol {
  1006. case model.VMESS:
  1007. target.ID = s.generateRandomCredential(targetProtocol)
  1008. case model.VLESS:
  1009. target.ID = s.generateRandomCredential(targetProtocol)
  1010. if flow == "xtls-rprx-vision" || flow == "xtls-rprx-vision-udp443" {
  1011. target.Flow = flow
  1012. }
  1013. case model.Trojan, model.Shadowsocks:
  1014. target.Password = s.generateRandomCredential(targetProtocol)
  1015. case model.Hysteria:
  1016. target.Auth = s.generateRandomCredential(targetProtocol)
  1017. default:
  1018. target.ID = s.generateRandomCredential(targetProtocol)
  1019. }
  1020. return target, nil
  1021. }
  1022. func (s *InboundService) nextAvailableCopiedEmail(originalEmail string, targetID int, occupied map[string]struct{}) string {
  1023. base := fmt.Sprintf("%s_%d", originalEmail, targetID)
  1024. candidate := base
  1025. suffix := 0
  1026. for {
  1027. if _, exists := occupied[strings.ToLower(candidate)]; !exists {
  1028. occupied[strings.ToLower(candidate)] = struct{}{}
  1029. return candidate
  1030. }
  1031. suffix++
  1032. candidate = fmt.Sprintf("%s_%d", base, suffix)
  1033. }
  1034. }
  1035. func (s *InboundService) CopyInboundClients(targetInboundID int, sourceInboundID int, clientEmails []string, flow string) (*CopyClientsResult, bool, error) {
  1036. result := &CopyClientsResult{
  1037. Added: []string{},
  1038. Skipped: []string{},
  1039. Errors: []string{},
  1040. }
  1041. if targetInboundID == sourceInboundID {
  1042. return result, false, common.NewError("source and target inbounds must be different")
  1043. }
  1044. targetInbound, err := s.GetInbound(targetInboundID)
  1045. if err != nil {
  1046. return result, false, err
  1047. }
  1048. sourceInbound, err := s.GetInbound(sourceInboundID)
  1049. if err != nil {
  1050. return result, false, err
  1051. }
  1052. sourceClients, err := s.GetClients(sourceInbound)
  1053. if err != nil {
  1054. return result, false, err
  1055. }
  1056. if len(sourceClients) == 0 {
  1057. return result, false, nil
  1058. }
  1059. allowedEmails := map[string]struct{}{}
  1060. if len(clientEmails) > 0 {
  1061. for _, email := range clientEmails {
  1062. allowedEmails[strings.ToLower(strings.TrimSpace(email))] = struct{}{}
  1063. }
  1064. }
  1065. occupiedEmails := map[string]struct{}{}
  1066. allEmails, err := s.getAllEmails()
  1067. if err != nil {
  1068. return result, false, err
  1069. }
  1070. for _, email := range allEmails {
  1071. clean := strings.Trim(email, "\"")
  1072. if clean != "" {
  1073. occupiedEmails[strings.ToLower(clean)] = struct{}{}
  1074. }
  1075. }
  1076. newClients := make([]model.Client, 0)
  1077. needRestart := false
  1078. for _, sourceClient := range sourceClients {
  1079. originalEmail := strings.TrimSpace(sourceClient.Email)
  1080. if originalEmail == "" {
  1081. continue
  1082. }
  1083. if len(allowedEmails) > 0 {
  1084. if _, ok := allowedEmails[strings.ToLower(originalEmail)]; !ok {
  1085. continue
  1086. }
  1087. }
  1088. if sourceClient.SubID == "" {
  1089. newSubID := uuid.NewString()
  1090. subNeedRestart, subErr := s.writeBackClientSubID(sourceInbound.Id, sourceInbound.Protocol, sourceClient, newSubID)
  1091. if subErr != nil {
  1092. result.Errors = append(result.Errors, fmt.Sprintf("%s: failed to write source subId: %v", originalEmail, subErr))
  1093. continue
  1094. }
  1095. if subNeedRestart {
  1096. needRestart = true
  1097. }
  1098. sourceClient.SubID = newSubID
  1099. }
  1100. targetEmail := s.nextAvailableCopiedEmail(originalEmail, targetInboundID, occupiedEmails)
  1101. targetClient, buildErr := s.buildTargetClientFromSource(sourceClient, targetInbound.Protocol, targetEmail, flow)
  1102. if buildErr != nil {
  1103. result.Errors = append(result.Errors, fmt.Sprintf("%s: %v", originalEmail, buildErr))
  1104. continue
  1105. }
  1106. newClients = append(newClients, targetClient)
  1107. result.Added = append(result.Added, targetEmail)
  1108. }
  1109. if len(newClients) == 0 {
  1110. return result, needRestart, nil
  1111. }
  1112. settingsPayload, err := json.Marshal(map[string][]model.Client{
  1113. "clients": newClients,
  1114. })
  1115. if err != nil {
  1116. return result, needRestart, err
  1117. }
  1118. addNeedRestart, err := s.clientService.AddInboundClient(s, &model.Inbound{
  1119. Id: targetInboundID,
  1120. Settings: string(settingsPayload),
  1121. })
  1122. if err != nil {
  1123. return result, needRestart, err
  1124. }
  1125. if addNeedRestart {
  1126. needRestart = true
  1127. }
  1128. return result, needRestart, nil
  1129. }
  1130. const resetGracePeriodMs int64 = 30000
  1131. // onlineGracePeriodMs must comfortably exceed the 5s traffic-poll interval —
  1132. // Xray's stats counters often report a zero delta for an active session across
  1133. // a single poll, so a 5s grace would still drop the client on the next tick.
  1134. // ~4 polls of slack keeps idle-but-connected clients visible without lingering
  1135. // long after a real disconnect.
  1136. const onlineGracePeriodMs int64 = 20000
  1137. func (s *InboundService) SetRemoteTraffic(nodeID int, snap *runtime.TrafficSnapshot) (bool, error) {
  1138. var structuralChange bool
  1139. err := submitTrafficWrite(func() error {
  1140. var inner error
  1141. structuralChange, inner = s.setRemoteTrafficLocked(nodeID, snap)
  1142. return inner
  1143. })
  1144. return structuralChange, err
  1145. }
  1146. func (s *InboundService) setRemoteTrafficLocked(nodeID int, snap *runtime.TrafficSnapshot) (bool, error) {
  1147. if snap == nil || nodeID <= 0 {
  1148. return false, nil
  1149. }
  1150. db := database.GetDB()
  1151. now := time.Now().UnixMilli()
  1152. var central []model.Inbound
  1153. if err := db.Model(model.Inbound{}).
  1154. Where("node_id = ?", nodeID).
  1155. Find(&central).Error; err != nil {
  1156. return false, err
  1157. }
  1158. tagToCentral := make(map[string]*model.Inbound, len(central))
  1159. for i := range central {
  1160. tagToCentral[central[i].Tag] = &central[i]
  1161. }
  1162. var centralClientStats []xray.ClientTraffic
  1163. if len(central) > 0 {
  1164. ids := make([]int, 0, len(central))
  1165. for i := range central {
  1166. ids = append(ids, central[i].Id)
  1167. }
  1168. if err := db.Model(xray.ClientTraffic{}).
  1169. Where("inbound_id IN ?", ids).
  1170. Find(&centralClientStats).Error; err != nil {
  1171. return false, err
  1172. }
  1173. }
  1174. type csKey struct {
  1175. inboundID int
  1176. email string
  1177. }
  1178. centralCS := make(map[csKey]*xray.ClientTraffic, len(centralClientStats))
  1179. centralCSByEmail := make(map[string]*xray.ClientTraffic, len(centralClientStats))
  1180. for i := range centralClientStats {
  1181. centralCS[csKey{centralClientStats[i].InboundId, centralClientStats[i].Email}] = &centralClientStats[i]
  1182. centralCSByEmail[centralClientStats[i].Email] = &centralClientStats[i]
  1183. }
  1184. var defaultUserId int
  1185. if len(central) > 0 {
  1186. defaultUserId = central[0].UserId
  1187. } else {
  1188. var u model.User
  1189. if err := db.Model(model.User{}).Order("id asc").First(&u).Error; err == nil {
  1190. defaultUserId = u.Id
  1191. } else {
  1192. defaultUserId = 1
  1193. }
  1194. }
  1195. tx := db.Begin()
  1196. committed := false
  1197. defer func() {
  1198. if !committed {
  1199. tx.Rollback()
  1200. }
  1201. }()
  1202. structuralChange := false
  1203. snapTags := make(map[string]struct{}, len(snap.Inbounds))
  1204. for _, snapIb := range snap.Inbounds {
  1205. if snapIb == nil {
  1206. continue
  1207. }
  1208. snapTags[snapIb.Tag] = struct{}{}
  1209. c, ok := tagToCentral[snapIb.Tag]
  1210. if !ok {
  1211. newIb := model.Inbound{
  1212. UserId: defaultUserId,
  1213. NodeID: &nodeID,
  1214. Tag: snapIb.Tag,
  1215. Listen: snapIb.Listen,
  1216. Port: snapIb.Port,
  1217. Protocol: snapIb.Protocol,
  1218. Settings: snapIb.Settings,
  1219. StreamSettings: snapIb.StreamSettings,
  1220. Sniffing: snapIb.Sniffing,
  1221. TrafficReset: snapIb.TrafficReset,
  1222. Enable: snapIb.Enable,
  1223. Remark: snapIb.Remark,
  1224. Total: snapIb.Total,
  1225. ExpiryTime: snapIb.ExpiryTime,
  1226. Up: snapIb.Up,
  1227. Down: snapIb.Down,
  1228. }
  1229. if err := tx.Create(&newIb).Error; err != nil {
  1230. logger.Warning("setRemoteTraffic: create central inbound for tag", snapIb.Tag, "failed:", err)
  1231. continue
  1232. }
  1233. tagToCentral[snapIb.Tag] = &newIb
  1234. structuralChange = true
  1235. continue
  1236. }
  1237. inGrace := c.LastTrafficResetTime > 0 && now-c.LastTrafficResetTime < resetGracePeriodMs
  1238. updates := map[string]any{
  1239. "enable": snapIb.Enable,
  1240. "remark": snapIb.Remark,
  1241. "listen": snapIb.Listen,
  1242. "port": snapIb.Port,
  1243. "protocol": snapIb.Protocol,
  1244. "total": snapIb.Total,
  1245. "expiry_time": snapIb.ExpiryTime,
  1246. "settings": snapIb.Settings,
  1247. "stream_settings": snapIb.StreamSettings,
  1248. "sniffing": snapIb.Sniffing,
  1249. "traffic_reset": snapIb.TrafficReset,
  1250. }
  1251. if !inGrace || (snapIb.Up+snapIb.Down) <= (c.Up+c.Down) {
  1252. updates["up"] = snapIb.Up
  1253. updates["down"] = snapIb.Down
  1254. }
  1255. if c.Settings != snapIb.Settings ||
  1256. c.Remark != snapIb.Remark ||
  1257. c.Listen != snapIb.Listen ||
  1258. c.Port != snapIb.Port ||
  1259. c.Total != snapIb.Total ||
  1260. c.ExpiryTime != snapIb.ExpiryTime ||
  1261. c.Enable != snapIb.Enable {
  1262. structuralChange = true
  1263. }
  1264. if err := tx.Model(model.Inbound{}).
  1265. Where("id = ?", c.Id).
  1266. Updates(updates).Error; err != nil {
  1267. return false, err
  1268. }
  1269. }
  1270. for _, c := range central {
  1271. if _, kept := snapTags[c.Tag]; kept {
  1272. continue
  1273. }
  1274. if err := tx.Where("inbound_id = ?", c.Id).
  1275. Delete(&xray.ClientTraffic{}).Error; err != nil {
  1276. return false, err
  1277. }
  1278. if err := tx.Where("id = ?", c.Id).
  1279. Delete(&model.Inbound{}).Error; err != nil {
  1280. return false, err
  1281. }
  1282. delete(tagToCentral, c.Tag)
  1283. structuralChange = true
  1284. }
  1285. for _, snapIb := range snap.Inbounds {
  1286. if snapIb == nil {
  1287. continue
  1288. }
  1289. c, ok := tagToCentral[snapIb.Tag]
  1290. if !ok {
  1291. continue
  1292. }
  1293. inGrace := c.LastTrafficResetTime > 0 && now-c.LastTrafficResetTime < resetGracePeriodMs
  1294. snapEmails := make(map[string]struct{}, len(snapIb.ClientStats))
  1295. for _, cs := range snapIb.ClientStats {
  1296. snapEmails[cs.Email] = struct{}{}
  1297. existing := centralCS[csKey{c.Id, cs.Email}]
  1298. if existing == nil {
  1299. existing = centralCSByEmail[cs.Email]
  1300. }
  1301. if existing == nil {
  1302. row := &xray.ClientTraffic{
  1303. InboundId: c.Id,
  1304. Email: cs.Email,
  1305. Enable: cs.Enable,
  1306. Total: cs.Total,
  1307. ExpiryTime: cs.ExpiryTime,
  1308. Reset: cs.Reset,
  1309. Up: cs.Up,
  1310. Down: cs.Down,
  1311. LastOnline: cs.LastOnline,
  1312. }
  1313. if err := tx.Clauses(clause.OnConflict{Columns: []clause.Column{{Name: "email"}}, DoNothing: true}).
  1314. Create(row).Error; err != nil {
  1315. return false, err
  1316. }
  1317. centralCS[csKey{c.Id, cs.Email}] = row
  1318. centralCSByEmail[cs.Email] = row
  1319. structuralChange = true
  1320. continue
  1321. }
  1322. if existing.Enable != cs.Enable ||
  1323. existing.Total != cs.Total ||
  1324. existing.ExpiryTime != cs.ExpiryTime ||
  1325. existing.Reset != cs.Reset {
  1326. structuralChange = true
  1327. }
  1328. if inGrace && cs.Up+cs.Down > 0 {
  1329. if err := tx.Exec(
  1330. `UPDATE client_traffics
  1331. SET enable = ?, total = ?, expiry_time = ?, reset = ?
  1332. WHERE email = ?`,
  1333. cs.Enable, cs.Total, cs.ExpiryTime, cs.Reset, cs.Email,
  1334. ).Error; err != nil {
  1335. return false, err
  1336. }
  1337. continue
  1338. }
  1339. if err := tx.Exec(
  1340. `UPDATE client_traffics
  1341. SET up = ?, down = ?, enable = ?, total = ?, expiry_time = ?, reset = ?,
  1342. last_online = MAX(last_online, ?)
  1343. WHERE email = ?`,
  1344. cs.Up, cs.Down, cs.Enable, cs.Total, cs.ExpiryTime, cs.Reset,
  1345. cs.LastOnline, cs.Email,
  1346. ).Error; err != nil {
  1347. return false, err
  1348. }
  1349. }
  1350. for k, existing := range centralCS {
  1351. if k.inboundID != c.Id {
  1352. continue
  1353. }
  1354. if _, kept := snapEmails[k.email]; kept {
  1355. continue
  1356. }
  1357. if err := tx.Where("inbound_id = ? AND email = ?", c.Id, existing.Email).
  1358. Delete(&xray.ClientTraffic{}).Error; err != nil {
  1359. return false, err
  1360. }
  1361. structuralChange = true
  1362. }
  1363. }
  1364. type oldSet struct {
  1365. inboundID int
  1366. emails map[string]struct{}
  1367. }
  1368. var perInboundOld []oldSet
  1369. for _, snapIb := range snap.Inbounds {
  1370. if snapIb == nil {
  1371. continue
  1372. }
  1373. c, ok := tagToCentral[snapIb.Tag]
  1374. if !ok {
  1375. continue
  1376. }
  1377. var oldEmailsRows []string
  1378. if err := tx.Table("clients").
  1379. Joins("JOIN client_inbounds ON client_inbounds.client_id = clients.id").
  1380. Where("client_inbounds.inbound_id = ?", c.Id).
  1381. Pluck("email", &oldEmailsRows).Error; err == nil {
  1382. oldEmails := make(map[string]struct{}, len(oldEmailsRows))
  1383. for _, e := range oldEmailsRows {
  1384. if e != "" {
  1385. oldEmails[e] = struct{}{}
  1386. }
  1387. }
  1388. perInboundOld = append(perInboundOld, oldSet{inboundID: c.Id, emails: oldEmails})
  1389. }
  1390. clients, gcErr := s.GetClients(snapIb)
  1391. if gcErr != nil {
  1392. logger.Warning("setRemoteTraffic: parse clients for tag", snapIb.Tag, "failed:", gcErr)
  1393. continue
  1394. }
  1395. csEnableByEmail := make(map[string]bool, len(snapIb.ClientStats))
  1396. for _, cs := range snapIb.ClientStats {
  1397. csEnableByEmail[cs.Email] = cs.Enable
  1398. }
  1399. filtered := clients[:0]
  1400. for i := range clients {
  1401. if isClientEmailTombstoned(clients[i].Email) {
  1402. continue
  1403. }
  1404. if cse, hit := csEnableByEmail[clients[i].Email]; hit && !cse {
  1405. clients[i].Enable = false
  1406. }
  1407. filtered = append(filtered, clients[i])
  1408. }
  1409. if err := s.clientService.SyncInbound(tx, c.Id, filtered); err != nil {
  1410. logger.Warning("setRemoteTraffic: sync clients for tag", snapIb.Tag, "failed:", err)
  1411. }
  1412. }
  1413. for _, old := range perInboundOld {
  1414. var stillAttached []string
  1415. if err := tx.Table("clients").
  1416. Joins("JOIN client_inbounds ON client_inbounds.client_id = clients.id").
  1417. Where("client_inbounds.inbound_id = ?", old.inboundID).
  1418. Pluck("email", &stillAttached).Error; err != nil {
  1419. continue
  1420. }
  1421. stillSet := make(map[string]struct{}, len(stillAttached))
  1422. for _, e := range stillAttached {
  1423. stillSet[e] = struct{}{}
  1424. }
  1425. for email := range old.emails {
  1426. if _, kept := stillSet[email]; kept {
  1427. continue
  1428. }
  1429. var attachmentCount int64
  1430. if err := tx.Table("client_inbounds").
  1431. Joins("JOIN clients ON clients.id = client_inbounds.client_id").
  1432. Where("clients.email = ?", email).
  1433. Count(&attachmentCount).Error; err != nil {
  1434. continue
  1435. }
  1436. if attachmentCount > 0 {
  1437. continue
  1438. }
  1439. if err := tx.Where("email = ?", email).Delete(&model.ClientRecord{}).Error; err != nil {
  1440. logger.Warning("setRemoteTraffic: delete ClientRecord", email, "failed:", err)
  1441. }
  1442. if err := tx.Where("email = ?", email).Delete(&xray.ClientTraffic{}).Error; err != nil {
  1443. logger.Warning("setRemoteTraffic: delete ClientTraffic", email, "failed:", err)
  1444. }
  1445. structuralChange = true
  1446. }
  1447. }
  1448. if err := tx.Commit().Error; err != nil {
  1449. return false, err
  1450. }
  1451. committed = true
  1452. if p != nil {
  1453. p.SetNodeOnlineClients(nodeID, snap.OnlineEmails)
  1454. }
  1455. return structuralChange, nil
  1456. }
  1457. func (s *InboundService) AddTraffic(inboundTraffics []*xray.Traffic, clientTraffics []*xray.ClientTraffic) (needRestart bool, clientsDisabled bool, err error) {
  1458. err = submitTrafficWrite(func() error {
  1459. var inner error
  1460. needRestart, clientsDisabled, inner = s.addTrafficLocked(inboundTraffics, clientTraffics)
  1461. return inner
  1462. })
  1463. return
  1464. }
  1465. func (s *InboundService) addTrafficLocked(inboundTraffics []*xray.Traffic, clientTraffics []*xray.ClientTraffic) (bool, bool, error) {
  1466. var err error
  1467. db := database.GetDB()
  1468. tx := db.Begin()
  1469. defer func() {
  1470. if err != nil {
  1471. tx.Rollback()
  1472. } else {
  1473. tx.Commit()
  1474. }
  1475. }()
  1476. err = s.addInboundTraffic(tx, inboundTraffics)
  1477. if err != nil {
  1478. return false, false, err
  1479. }
  1480. err = s.addClientTraffic(tx, clientTraffics)
  1481. if err != nil {
  1482. return false, false, err
  1483. }
  1484. needRestart0, count, err := s.autoRenewClients(tx)
  1485. if err != nil {
  1486. logger.Warning("Error in renew clients:", err)
  1487. } else if count > 0 {
  1488. logger.Debugf("%v clients renewed", count)
  1489. }
  1490. disabledClientsCount := int64(0)
  1491. needRestart1, count, err := s.disableInvalidClients(tx)
  1492. if err != nil {
  1493. logger.Warning("Error in disabling invalid clients:", err)
  1494. } else if count > 0 {
  1495. logger.Debugf("%v clients disabled", count)
  1496. disabledClientsCount = count
  1497. }
  1498. needRestart2, count, err := s.disableInvalidInbounds(tx)
  1499. if err != nil {
  1500. logger.Warning("Error in disabling invalid inbounds:", err)
  1501. } else if count > 0 {
  1502. logger.Debugf("%v inbounds disabled", count)
  1503. }
  1504. return needRestart0 || needRestart1 || needRestart2, disabledClientsCount > 0, nil
  1505. }
  1506. func (s *InboundService) addInboundTraffic(tx *gorm.DB, traffics []*xray.Traffic) error {
  1507. if len(traffics) == 0 {
  1508. return nil
  1509. }
  1510. var err error
  1511. for _, traffic := range traffics {
  1512. if traffic.IsInbound {
  1513. err = tx.Model(&model.Inbound{}).Where("tag = ? AND node_id IS NULL", traffic.Tag).
  1514. Updates(map[string]any{
  1515. "up": gorm.Expr("up + ?", traffic.Up),
  1516. "down": gorm.Expr("down + ?", traffic.Down),
  1517. }).Error
  1518. if err != nil {
  1519. return err
  1520. }
  1521. }
  1522. }
  1523. return nil
  1524. }
  1525. func (s *InboundService) addClientTraffic(tx *gorm.DB, traffics []*xray.ClientTraffic) (err error) {
  1526. if len(traffics) == 0 {
  1527. return nil
  1528. }
  1529. emails := make([]string, 0, len(traffics))
  1530. for _, traffic := range traffics {
  1531. emails = append(emails, traffic.Email)
  1532. }
  1533. dbClientTraffics := make([]*xray.ClientTraffic, 0, len(traffics))
  1534. err = tx.Model(xray.ClientTraffic{}).
  1535. Where("email IN (?) AND inbound_id IN (?)", emails,
  1536. tx.Model(&model.Inbound{}).Select("id").Where("node_id IS NULL")).
  1537. Find(&dbClientTraffics).Error
  1538. if err != nil {
  1539. return err
  1540. }
  1541. // Avoid empty slice error
  1542. if len(dbClientTraffics) == 0 {
  1543. return nil
  1544. }
  1545. dbClientTraffics, err = s.adjustTraffics(tx, dbClientTraffics)
  1546. if err != nil {
  1547. return err
  1548. }
  1549. // Index by email for O(N) merge — the previous nested loop was O(N²)
  1550. // and dominated each cron tick on inbounds with thousands of active
  1551. // clients (7500 × 7500 = 56M string comparisons every 10 seconds).
  1552. trafficByEmail := make(map[string]*xray.ClientTraffic, len(traffics))
  1553. for i := range traffics {
  1554. if traffics[i] != nil {
  1555. trafficByEmail[traffics[i].Email] = traffics[i]
  1556. }
  1557. }
  1558. now := time.Now().UnixMilli()
  1559. for dbTraffic_index := range dbClientTraffics {
  1560. t, ok := trafficByEmail[dbClientTraffics[dbTraffic_index].Email]
  1561. if !ok {
  1562. continue
  1563. }
  1564. dbClientTraffics[dbTraffic_index].Up += t.Up
  1565. dbClientTraffics[dbTraffic_index].Down += t.Down
  1566. if t.Up+t.Down > 0 {
  1567. dbClientTraffics[dbTraffic_index].LastOnline = now
  1568. }
  1569. }
  1570. err = tx.Save(dbClientTraffics).Error
  1571. if err != nil {
  1572. logger.Warning("AddClientTraffic update data ", err)
  1573. }
  1574. return nil
  1575. }
  1576. func (s *InboundService) adjustTraffics(tx *gorm.DB, dbClientTraffics []*xray.ClientTraffic) ([]*xray.ClientTraffic, error) {
  1577. inboundIds := make([]int, 0, len(dbClientTraffics))
  1578. for _, dbClientTraffic := range dbClientTraffics {
  1579. if dbClientTraffic.ExpiryTime < 0 {
  1580. inboundIds = append(inboundIds, dbClientTraffic.InboundId)
  1581. }
  1582. }
  1583. if len(inboundIds) > 0 {
  1584. var inbounds []*model.Inbound
  1585. err := tx.Model(model.Inbound{}).Where("id IN (?)", inboundIds).Find(&inbounds).Error
  1586. if err != nil {
  1587. return nil, err
  1588. }
  1589. for inbound_index := range inbounds {
  1590. settings := map[string]any{}
  1591. json.Unmarshal([]byte(inbounds[inbound_index].Settings), &settings)
  1592. clients, ok := settings["clients"].([]any)
  1593. if ok {
  1594. var newClients []any
  1595. for client_index := range clients {
  1596. c := clients[client_index].(map[string]any)
  1597. for traffic_index := range dbClientTraffics {
  1598. if dbClientTraffics[traffic_index].ExpiryTime < 0 && c["email"] == dbClientTraffics[traffic_index].Email {
  1599. oldExpiryTime := c["expiryTime"].(float64)
  1600. newExpiryTime := (time.Now().Unix() * 1000) - int64(oldExpiryTime)
  1601. c["expiryTime"] = newExpiryTime
  1602. c["updated_at"] = time.Now().Unix() * 1000
  1603. dbClientTraffics[traffic_index].ExpiryTime = newExpiryTime
  1604. break
  1605. }
  1606. }
  1607. if _, ok := c["created_at"]; !ok {
  1608. c["created_at"] = time.Now().Unix() * 1000
  1609. }
  1610. if _, ok := c["updated_at"]; !ok {
  1611. c["updated_at"] = time.Now().Unix() * 1000
  1612. }
  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. // EmailsByInbound returns the list of client emails currently configured on
  2221. // an inbound's settings.clients[]. Used by the "delete all clients" flow on
  2222. // the inbounds page, which then feeds the list into ClientService.BulkDelete.
  2223. func (s *InboundService) EmailsByInbound(inboundId int) ([]string, error) {
  2224. inbound, err := s.GetInbound(inboundId)
  2225. if err != nil {
  2226. return nil, err
  2227. }
  2228. clients, err := s.GetClients(inbound)
  2229. if err != nil {
  2230. return nil, err
  2231. }
  2232. emails := make([]string, 0, len(clients))
  2233. for _, c := range clients {
  2234. if e := strings.TrimSpace(c.Email); e != "" {
  2235. emails = append(emails, e)
  2236. }
  2237. }
  2238. return emails, nil
  2239. }
  2240. func (s *InboundService) DelDepletedClients(id int) (err error) {
  2241. db := database.GetDB()
  2242. tx := db.Begin()
  2243. defer func() {
  2244. if err == nil {
  2245. tx.Commit()
  2246. } else {
  2247. tx.Rollback()
  2248. }
  2249. }()
  2250. // Collect depleted emails globally — a shared-email row owned by one
  2251. // inbound depletes every sibling that lists the email.
  2252. now := time.Now().Unix() * 1000
  2253. depletedClause := "reset = 0 and ((total > 0 and up + down >= total) or (expiry_time > 0 and expiry_time <= ?))"
  2254. var depletedRows []xray.ClientTraffic
  2255. err = db.Model(xray.ClientTraffic{}).
  2256. Where(depletedClause, now).
  2257. Find(&depletedRows).Error
  2258. if err != nil {
  2259. return err
  2260. }
  2261. if len(depletedRows) == 0 {
  2262. return nil
  2263. }
  2264. depletedEmails := make(map[string]struct{}, len(depletedRows))
  2265. for _, r := range depletedRows {
  2266. if r.Email == "" {
  2267. continue
  2268. }
  2269. depletedEmails[strings.ToLower(r.Email)] = struct{}{}
  2270. }
  2271. if len(depletedEmails) == 0 {
  2272. return nil
  2273. }
  2274. var inbounds []*model.Inbound
  2275. inboundQuery := db.Model(model.Inbound{})
  2276. if id >= 0 {
  2277. inboundQuery = inboundQuery.Where("id = ?", id)
  2278. }
  2279. if err = inboundQuery.Find(&inbounds).Error; err != nil {
  2280. return err
  2281. }
  2282. for _, inbound := range inbounds {
  2283. var settings map[string]any
  2284. if err = json.Unmarshal([]byte(inbound.Settings), &settings); err != nil {
  2285. return err
  2286. }
  2287. rawClients, ok := settings["clients"].([]any)
  2288. if !ok {
  2289. continue
  2290. }
  2291. newClients := make([]any, 0, len(rawClients))
  2292. removed := 0
  2293. for _, client := range rawClients {
  2294. c, ok := client.(map[string]any)
  2295. if !ok {
  2296. newClients = append(newClients, client)
  2297. continue
  2298. }
  2299. email, _ := c["email"].(string)
  2300. if _, isDepleted := depletedEmails[strings.ToLower(email)]; isDepleted {
  2301. removed++
  2302. continue
  2303. }
  2304. newClients = append(newClients, client)
  2305. }
  2306. if removed == 0 {
  2307. continue
  2308. }
  2309. if len(newClients) == 0 {
  2310. s.DelInbound(inbound.Id)
  2311. continue
  2312. }
  2313. settings["clients"] = newClients
  2314. ns, mErr := json.MarshalIndent(settings, "", " ")
  2315. if mErr != nil {
  2316. return mErr
  2317. }
  2318. inbound.Settings = string(ns)
  2319. if err = tx.Save(inbound).Error; err != nil {
  2320. return err
  2321. }
  2322. survivingClients, gcErr := s.GetClients(inbound)
  2323. if gcErr != nil {
  2324. err = gcErr
  2325. return err
  2326. }
  2327. if err = s.clientService.SyncInbound(tx, inbound.Id, survivingClients); err != nil {
  2328. return err
  2329. }
  2330. }
  2331. // Drop now-orphaned rows. With id >= 0, a row is safe to drop only when
  2332. // no out-of-scope inbound still references the email.
  2333. if id < 0 {
  2334. err = tx.Where(depletedClause, now).Delete(xray.ClientTraffic{}).Error
  2335. return err
  2336. }
  2337. emails := make([]string, 0, len(depletedEmails))
  2338. for e := range depletedEmails {
  2339. emails = append(emails, e)
  2340. }
  2341. var stillReferenced []string
  2342. emailExpr := database.JSONFieldText("client.value", "email")
  2343. stillQuery := fmt.Sprintf(
  2344. "SELECT DISTINCT LOWER(%s) %s WHERE LOWER(%s) IN ?",
  2345. emailExpr,
  2346. database.JSONClientsFromInbound(),
  2347. emailExpr,
  2348. )
  2349. if err = tx.Raw(stillQuery, emails).Scan(&stillReferenced).Error; err != nil {
  2350. return err
  2351. }
  2352. stillSet := make(map[string]struct{}, len(stillReferenced))
  2353. for _, e := range stillReferenced {
  2354. stillSet[e] = struct{}{}
  2355. }
  2356. toDelete := make([]string, 0, len(emails))
  2357. for _, e := range emails {
  2358. if _, kept := stillSet[e]; !kept {
  2359. toDelete = append(toDelete, e)
  2360. }
  2361. }
  2362. if len(toDelete) > 0 {
  2363. if err = tx.Where("LOWER(email) IN ?", toDelete).Delete(xray.ClientTraffic{}).Error; err != nil {
  2364. return err
  2365. }
  2366. }
  2367. return nil
  2368. }
  2369. func (s *InboundService) GetClientTrafficTgBot(tgId int64) ([]*xray.ClientTraffic, error) {
  2370. db := database.GetDB()
  2371. var inbounds []*model.Inbound
  2372. // Retrieve inbounds where settings contain the given tgId
  2373. err := db.Model(model.Inbound{}).Where("settings LIKE ?", fmt.Sprintf(`%%"tgId": %d%%`, tgId)).Find(&inbounds).Error
  2374. if err != nil && err != gorm.ErrRecordNotFound {
  2375. logger.Errorf("Error retrieving inbounds with tgId %d: %v", tgId, err)
  2376. return nil, err
  2377. }
  2378. var emails []string
  2379. for _, inbound := range inbounds {
  2380. clients, err := s.GetClients(inbound)
  2381. if err != nil {
  2382. logger.Errorf("Error retrieving clients for inbound %d: %v", inbound.Id, err)
  2383. continue
  2384. }
  2385. for _, client := range clients {
  2386. if client.TgID == tgId {
  2387. emails = append(emails, client.Email)
  2388. }
  2389. }
  2390. }
  2391. // Chunked to stay under SQLite's bind-variable limit when a single Telegram
  2392. // account owns thousands of clients across inbounds.
  2393. uniqEmails := uniqueNonEmptyStrings(emails)
  2394. traffics := make([]*xray.ClientTraffic, 0, len(uniqEmails))
  2395. for _, batch := range chunkStrings(uniqEmails, sqliteMaxVars) {
  2396. var page []*xray.ClientTraffic
  2397. if err = db.Model(xray.ClientTraffic{}).Where("email IN ?", batch).Find(&page).Error; err != nil {
  2398. if err == gorm.ErrRecordNotFound {
  2399. continue
  2400. }
  2401. logger.Errorf("Error retrieving ClientTraffic for emails %v: %v", batch, err)
  2402. return nil, err
  2403. }
  2404. traffics = append(traffics, page...)
  2405. }
  2406. if len(traffics) == 0 {
  2407. logger.Warning("No ClientTraffic records found for emails:", emails)
  2408. return nil, nil
  2409. }
  2410. // Populate UUID and other client data for each traffic record
  2411. for i := range traffics {
  2412. if ct, client, e := s.GetClientByEmail(traffics[i].Email); e == nil && ct != nil && client != nil {
  2413. traffics[i].Enable = client.Enable
  2414. traffics[i].UUID = client.ID
  2415. traffics[i].SubId = client.SubID
  2416. }
  2417. }
  2418. return traffics, nil
  2419. }
  2420. // sqliteMaxVars is a safe ceiling for the number of bind parameters in a
  2421. // single SQL statement. SQLite's SQLITE_MAX_VARIABLE_NUMBER is 999 on builds
  2422. // before 3.32 and 32766 after; staying under 999 keeps queries portable
  2423. // across forks/old binaries and also bounds per-query memory on truly large
  2424. // installs (>32k clients) where even modern SQLite would refuse a single IN.
  2425. const sqliteMaxVars = 900
  2426. // uniqueNonEmptyStrings returns a deduplicated copy of in with empty strings
  2427. // removed, preserving the order of first occurrence.
  2428. func uniqueNonEmptyStrings(in []string) []string {
  2429. if len(in) == 0 {
  2430. return nil
  2431. }
  2432. seen := make(map[string]struct{}, len(in))
  2433. out := make([]string, 0, len(in))
  2434. for _, v := range in {
  2435. if v == "" {
  2436. continue
  2437. }
  2438. if _, ok := seen[v]; ok {
  2439. continue
  2440. }
  2441. seen[v] = struct{}{}
  2442. out = append(out, v)
  2443. }
  2444. return out
  2445. }
  2446. // uniqueInts returns a deduplicated copy of in, preserving order of first occurrence.
  2447. func uniqueInts(in []int) []int {
  2448. if len(in) == 0 {
  2449. return nil
  2450. }
  2451. seen := make(map[int]struct{}, len(in))
  2452. out := make([]int, 0, len(in))
  2453. for _, v := range in {
  2454. if _, ok := seen[v]; ok {
  2455. continue
  2456. }
  2457. seen[v] = struct{}{}
  2458. out = append(out, v)
  2459. }
  2460. return out
  2461. }
  2462. // chunkStrings splits s into consecutive sub-slices of at most size elements.
  2463. // Returns nil for an empty input or non-positive size.
  2464. func chunkStrings(s []string, size int) [][]string {
  2465. if size <= 0 || len(s) == 0 {
  2466. return nil
  2467. }
  2468. out := make([][]string, 0, (len(s)+size-1)/size)
  2469. for i := 0; i < len(s); i += size {
  2470. end := min(i+size, len(s))
  2471. out = append(out, s[i:end])
  2472. }
  2473. return out
  2474. }
  2475. // chunkInts splits s into consecutive sub-slices of at most size elements.
  2476. // Returns nil for an empty input or non-positive size.
  2477. func chunkInts(s []int, size int) [][]int {
  2478. if size <= 0 || len(s) == 0 {
  2479. return nil
  2480. }
  2481. out := make([][]int, 0, (len(s)+size-1)/size)
  2482. for i := 0; i < len(s); i += size {
  2483. end := min(i+size, len(s))
  2484. out = append(out, s[i:end])
  2485. }
  2486. return out
  2487. }
  2488. func (s *InboundService) GetActiveClientTraffics(emails []string) ([]*xray.ClientTraffic, error) {
  2489. uniq := uniqueNonEmptyStrings(emails)
  2490. if len(uniq) == 0 {
  2491. return nil, nil
  2492. }
  2493. db := database.GetDB()
  2494. traffics := make([]*xray.ClientTraffic, 0, len(uniq))
  2495. for _, batch := range chunkStrings(uniq, sqliteMaxVars) {
  2496. var page []*xray.ClientTraffic
  2497. if err := db.Model(xray.ClientTraffic{}).Where("email IN ?", batch).Find(&page).Error; err != nil {
  2498. return nil, err
  2499. }
  2500. traffics = append(traffics, page...)
  2501. }
  2502. return traffics, nil
  2503. }
  2504. // GetAllClientTraffics returns the full set of client_traffics rows so the
  2505. // websocket broadcasters can ship a complete snapshot every cycle. The old
  2506. // delta-only path (GetActiveClientTraffics on activeEmails) silently dropped
  2507. // the per-client section whenever no client moved bytes in the cycle or a
  2508. // node sync failed, leaving client rows in the UI stuck at stale numbers.
  2509. func (s *InboundService) GetAllClientTraffics() ([]*xray.ClientTraffic, error) {
  2510. db := database.GetDB()
  2511. var traffics []*xray.ClientTraffic
  2512. if err := db.Model(xray.ClientTraffic{}).Find(&traffics).Error; err != nil {
  2513. return nil, err
  2514. }
  2515. return traffics, nil
  2516. }
  2517. type InboundTrafficSummary struct {
  2518. Id int `json:"id"`
  2519. Up int64 `json:"up"`
  2520. Down int64 `json:"down"`
  2521. Total int64 `json:"total"`
  2522. Enable bool `json:"enable"`
  2523. }
  2524. func (s *InboundService) GetInboundsTrafficSummary() ([]InboundTrafficSummary, error) {
  2525. db := database.GetDB()
  2526. var summaries []InboundTrafficSummary
  2527. if err := db.Model(&model.Inbound{}).
  2528. Select("id, up, down, total, enable").
  2529. Find(&summaries).Error; err != nil {
  2530. return nil, err
  2531. }
  2532. return summaries, nil
  2533. }
  2534. func (s *InboundService) GetClientTrafficByEmail(email string) (traffic *xray.ClientTraffic, err error) {
  2535. // Prefer retrieving along with client to reflect actual enabled state from inbound settings
  2536. t, client, err := s.GetClientByEmail(email)
  2537. if err != nil {
  2538. logger.Warningf("Error retrieving ClientTraffic with email %s: %v", email, err)
  2539. return nil, err
  2540. }
  2541. if t != nil && client != nil {
  2542. t.UUID = client.ID
  2543. t.SubId = client.SubID
  2544. return t, nil
  2545. }
  2546. return nil, nil
  2547. }
  2548. func (s *InboundService) UpdateClientTrafficByEmail(email string, upload int64, download int64) error {
  2549. return submitTrafficWrite(func() error {
  2550. db := database.GetDB()
  2551. err := db.Model(xray.ClientTraffic{}).
  2552. Where("email = ?", email).
  2553. Updates(map[string]any{
  2554. "up": upload,
  2555. "down": download,
  2556. }).Error
  2557. if err != nil {
  2558. logger.Warningf("Error updating ClientTraffic with email %s: %v", email, err)
  2559. }
  2560. return err
  2561. })
  2562. }
  2563. func (s *InboundService) SearchClientTraffic(query string) (traffic *xray.ClientTraffic, err error) {
  2564. db := database.GetDB()
  2565. inbound := &model.Inbound{}
  2566. traffic = &xray.ClientTraffic{}
  2567. // Search for inbound settings that contain the query
  2568. err = db.Model(model.Inbound{}).Where("settings LIKE ?", "%\""+query+"\"%").First(inbound).Error
  2569. if err != nil {
  2570. if err == gorm.ErrRecordNotFound {
  2571. logger.Warningf("Inbound settings containing query %s not found: %v", query, err)
  2572. return nil, err
  2573. }
  2574. logger.Errorf("Error searching for inbound settings with query %s: %v", query, err)
  2575. return nil, err
  2576. }
  2577. traffic.InboundId = inbound.Id
  2578. // Unmarshal settings to get clients
  2579. settings := map[string][]model.Client{}
  2580. if err := json.Unmarshal([]byte(inbound.Settings), &settings); err != nil {
  2581. logger.Errorf("Error unmarshalling inbound settings for inbound ID %d: %v", inbound.Id, err)
  2582. return nil, err
  2583. }
  2584. clients := settings["clients"]
  2585. for _, client := range clients {
  2586. if (client.ID == query || client.Password == query) && client.Email != "" {
  2587. traffic.Email = client.Email
  2588. break
  2589. }
  2590. }
  2591. if traffic.Email == "" {
  2592. logger.Warningf("No client found with query %s in inbound ID %d", query, inbound.Id)
  2593. return nil, gorm.ErrRecordNotFound
  2594. }
  2595. // Retrieve ClientTraffic based on the found email
  2596. err = db.Model(xray.ClientTraffic{}).Where("email = ?", traffic.Email).First(traffic).Error
  2597. if err != nil {
  2598. if err == gorm.ErrRecordNotFound {
  2599. logger.Warningf("ClientTraffic for email %s not found: %v", traffic.Email, err)
  2600. return nil, err
  2601. }
  2602. logger.Errorf("Error retrieving ClientTraffic for email %s: %v", traffic.Email, err)
  2603. return nil, err
  2604. }
  2605. return traffic, nil
  2606. }
  2607. func (s *InboundService) GetInboundClientIps(clientEmail string) (string, error) {
  2608. db := database.GetDB()
  2609. InboundClientIps := &model.InboundClientIps{}
  2610. err := db.Model(model.InboundClientIps{}).Where("client_email = ?", clientEmail).First(InboundClientIps).Error
  2611. if err != nil {
  2612. return "", err
  2613. }
  2614. if InboundClientIps.Ips == "" {
  2615. return "", nil
  2616. }
  2617. // Try to parse as new format (with timestamps)
  2618. type IPWithTimestamp struct {
  2619. IP string `json:"ip"`
  2620. Timestamp int64 `json:"timestamp"`
  2621. }
  2622. var ipsWithTime []IPWithTimestamp
  2623. err = json.Unmarshal([]byte(InboundClientIps.Ips), &ipsWithTime)
  2624. // If successfully parsed as new format, return with timestamps
  2625. if err == nil && len(ipsWithTime) > 0 {
  2626. return InboundClientIps.Ips, nil
  2627. }
  2628. // Otherwise, assume it's old format (simple string array)
  2629. // Try to parse as simple array and convert to new format
  2630. var oldIps []string
  2631. err = json.Unmarshal([]byte(InboundClientIps.Ips), &oldIps)
  2632. if err == nil && len(oldIps) > 0 {
  2633. // Convert old format to new format with current timestamp
  2634. newIpsWithTime := make([]IPWithTimestamp, len(oldIps))
  2635. for i, ip := range oldIps {
  2636. newIpsWithTime[i] = IPWithTimestamp{
  2637. IP: ip,
  2638. Timestamp: time.Now().Unix(),
  2639. }
  2640. }
  2641. result, _ := json.Marshal(newIpsWithTime)
  2642. return string(result), nil
  2643. }
  2644. // Return as-is if parsing fails
  2645. return InboundClientIps.Ips, nil
  2646. }
  2647. func (s *InboundService) ClearClientIps(clientEmail string) error {
  2648. db := database.GetDB()
  2649. result := db.Model(model.InboundClientIps{}).
  2650. Where("client_email = ?", clientEmail).
  2651. Update("ips", "")
  2652. err := result.Error
  2653. if err != nil {
  2654. return err
  2655. }
  2656. return nil
  2657. }
  2658. func (s *InboundService) SearchInbounds(query string) ([]*model.Inbound, error) {
  2659. db := database.GetDB()
  2660. var inbounds []*model.Inbound
  2661. err := db.Model(model.Inbound{}).Preload("ClientStats").Where("remark like ?", "%"+query+"%").Find(&inbounds).Error
  2662. if err != nil && err != gorm.ErrRecordNotFound {
  2663. return nil, err
  2664. }
  2665. return inbounds, nil
  2666. }
  2667. func (s *InboundService) MigrationRequirements() {
  2668. db := database.GetDB()
  2669. tx := db.Begin()
  2670. var err error
  2671. defer func() {
  2672. if err == nil {
  2673. tx.Commit()
  2674. if !database.IsPostgres() {
  2675. if dbErr := db.Exec(`VACUUM "main"`).Error; dbErr != nil {
  2676. logger.Warningf("VACUUM failed: %v", dbErr)
  2677. }
  2678. }
  2679. } else {
  2680. tx.Rollback()
  2681. }
  2682. }()
  2683. if tx.Migrator().HasColumn(&model.Inbound{}, "all_time") {
  2684. if err = tx.Migrator().DropColumn(&model.Inbound{}, "all_time"); err != nil {
  2685. return
  2686. }
  2687. }
  2688. if tx.Migrator().HasColumn(&xray.ClientTraffic{}, "all_time") {
  2689. if err = tx.Migrator().DropColumn(&xray.ClientTraffic{}, "all_time"); err != nil {
  2690. return
  2691. }
  2692. }
  2693. // Fix inbounds based problems
  2694. var inbounds []*model.Inbound
  2695. err = tx.Model(model.Inbound{}).Where("protocol IN (?)", []string{"vmess", "vless", "trojan", "shadowsocks", "hysteria"}).Find(&inbounds).Error
  2696. if err != nil && err != gorm.ErrRecordNotFound {
  2697. return
  2698. }
  2699. for inbound_index := range inbounds {
  2700. settings := map[string]any{}
  2701. json.Unmarshal([]byte(inbounds[inbound_index].Settings), &settings)
  2702. clients, ok := settings["clients"].([]any)
  2703. if ok {
  2704. // Fix Client configuration problems
  2705. var newClients []any
  2706. hasVisionFlow := false
  2707. for client_index := range clients {
  2708. c := clients[client_index].(map[string]any)
  2709. // Add email='' if it is not exists
  2710. if _, ok := c["email"]; !ok {
  2711. c["email"] = ""
  2712. }
  2713. // Convert string tgId to int64
  2714. if _, ok := c["tgId"]; ok {
  2715. var tgId any = c["tgId"]
  2716. if tgIdStr, ok2 := tgId.(string); ok2 {
  2717. tgIdInt64, err := strconv.ParseInt(strings.ReplaceAll(tgIdStr, " ", ""), 10, 64)
  2718. if err == nil {
  2719. c["tgId"] = tgIdInt64
  2720. }
  2721. }
  2722. }
  2723. // Remove "flow": "xtls-rprx-direct"
  2724. if _, ok := c["flow"]; ok {
  2725. if c["flow"] == "xtls-rprx-direct" {
  2726. c["flow"] = ""
  2727. }
  2728. }
  2729. if flow, _ := c["flow"].(string); flow == "xtls-rprx-vision" {
  2730. hasVisionFlow = true
  2731. }
  2732. // Backfill created_at and updated_at
  2733. if _, ok := c["created_at"]; !ok {
  2734. c["created_at"] = time.Now().Unix() * 1000
  2735. }
  2736. c["updated_at"] = time.Now().Unix() * 1000
  2737. newClients = append(newClients, any(c))
  2738. }
  2739. settings["clients"] = newClients
  2740. // Drop orphaned testseed: VLESS-only field, only meaningful when at least
  2741. // one client uses the exact xtls-rprx-vision flow. Older versions saved it
  2742. // for any non-empty flow (including the UDP variant) or kept it after the
  2743. // flow was cleared from the client modal — clean those up here.
  2744. if inbounds[inbound_index].Protocol == model.VLESS && !hasVisionFlow {
  2745. delete(settings, "testseed")
  2746. }
  2747. modifiedSettings, err := json.MarshalIndent(settings, "", " ")
  2748. if err != nil {
  2749. return
  2750. }
  2751. inbounds[inbound_index].Settings = string(modifiedSettings)
  2752. }
  2753. // Add client traffic row for all clients which has email
  2754. modelClients, err := s.GetClients(inbounds[inbound_index])
  2755. if err != nil {
  2756. return
  2757. }
  2758. for _, modelClient := range modelClients {
  2759. if len(modelClient.Email) > 0 {
  2760. var count int64
  2761. tx.Model(xray.ClientTraffic{}).Where("email = ?", modelClient.Email).Count(&count)
  2762. if count == 0 {
  2763. s.AddClientStat(tx, inbounds[inbound_index].Id, &modelClient)
  2764. }
  2765. }
  2766. }
  2767. // Heal clients table for installs where the one-shot seeder
  2768. // skipped clients due to a tgId-string unmarshal error.
  2769. if syncErr := s.clientService.SyncInbound(tx, inbounds[inbound_index].Id, modelClients); syncErr != nil {
  2770. logger.Warning("MigrationRequirements sync clients failed:", syncErr)
  2771. }
  2772. }
  2773. tx.Save(inbounds)
  2774. // Remove orphaned traffics
  2775. tx.Where("inbound_id = 0").Delete(xray.ClientTraffic{})
  2776. // Migrate old MultiDomain to External Proxy
  2777. var externalProxy []struct {
  2778. Id int
  2779. Port int
  2780. StreamSettings []byte
  2781. }
  2782. err = tx.Raw(`select id, port, stream_settings
  2783. from inbounds
  2784. WHERE protocol in ('vmess','vless','trojan')
  2785. AND json_extract(stream_settings, '$.security') = 'tls'
  2786. AND json_extract(stream_settings, '$.tlsSettings.settings.domains') IS NOT NULL`).Scan(&externalProxy).Error
  2787. if err != nil || len(externalProxy) == 0 {
  2788. return
  2789. }
  2790. for _, ep := range externalProxy {
  2791. var reverses any
  2792. var stream map[string]any
  2793. json.Unmarshal(ep.StreamSettings, &stream)
  2794. if tlsSettings, ok := stream["tlsSettings"].(map[string]any); ok {
  2795. if settings, ok := tlsSettings["settings"].(map[string]any); ok {
  2796. if domains, ok := settings["domains"].([]any); ok {
  2797. for _, domain := range domains {
  2798. if domainMap, ok := domain.(map[string]any); ok {
  2799. domainMap["forceTls"] = "same"
  2800. domainMap["port"] = ep.Port
  2801. domainMap["dest"] = domainMap["domain"].(string)
  2802. delete(domainMap, "domain")
  2803. }
  2804. }
  2805. }
  2806. reverses = settings["domains"]
  2807. delete(settings, "domains")
  2808. }
  2809. }
  2810. stream["externalProxy"] = reverses
  2811. newStream, _ := json.MarshalIndent(stream, " ", " ")
  2812. tx.Model(model.Inbound{}).Where("id = ?", ep.Id).Update("stream_settings", newStream)
  2813. }
  2814. err = tx.Raw(`UPDATE inbounds
  2815. SET tag = REPLACE(tag, '0.0.0.0:', '')
  2816. WHERE INSTR(tag, '0.0.0.0:') > 0;`).Error
  2817. if err != nil {
  2818. return
  2819. }
  2820. }
  2821. func (s *InboundService) MigrateDB() {
  2822. s.MigrationRequirements()
  2823. s.MigrationRemoveOrphanedTraffics()
  2824. }
  2825. func (s *InboundService) GetOnlineClients() []string {
  2826. return p.GetOnlineClients()
  2827. }
  2828. func (s *InboundService) SetNodeOnlineClients(nodeID int, emails []string) {
  2829. if p != nil {
  2830. p.SetNodeOnlineClients(nodeID, emails)
  2831. }
  2832. }
  2833. func (s *InboundService) ClearNodeOnlineClients(nodeID int) {
  2834. if p != nil {
  2835. p.ClearNodeOnlineClients(nodeID)
  2836. }
  2837. }
  2838. func (s *InboundService) GetClientsLastOnline() (map[string]int64, error) {
  2839. db := database.GetDB()
  2840. var rows []xray.ClientTraffic
  2841. err := db.Model(&xray.ClientTraffic{}).Select("email, last_online").Find(&rows).Error
  2842. if err != nil && err != gorm.ErrRecordNotFound {
  2843. return nil, err
  2844. }
  2845. result := make(map[string]int64, len(rows))
  2846. for _, r := range rows {
  2847. result[r.Email] = r.LastOnline
  2848. }
  2849. return result, nil
  2850. }
  2851. func (s *InboundService) RefreshOnlineClientsFromMap(lastOnlineMap map[string]int64) {
  2852. now := time.Now().UnixMilli()
  2853. newOnlineClients := make([]string, 0, len(lastOnlineMap))
  2854. for email, lastOnline := range lastOnlineMap {
  2855. if now-lastOnline < onlineGracePeriodMs {
  2856. newOnlineClients = append(newOnlineClients, email)
  2857. }
  2858. }
  2859. if p != nil {
  2860. p.SetOnlineClients(newOnlineClients)
  2861. }
  2862. }
  2863. func (s *InboundService) FilterAndSortClientEmails(emails []string) ([]string, []string, error) {
  2864. db := database.GetDB()
  2865. // Step 1: Get ClientTraffic records for emails in the input list.
  2866. // Chunked to stay under SQLite's bind-variable limit on huge inputs.
  2867. uniqEmails := uniqueNonEmptyStrings(emails)
  2868. clients := make([]xray.ClientTraffic, 0, len(uniqEmails))
  2869. for _, batch := range chunkStrings(uniqEmails, sqliteMaxVars) {
  2870. var page []xray.ClientTraffic
  2871. if err := db.Where("email IN ?", batch).Find(&page).Error; err != nil && err != gorm.ErrRecordNotFound {
  2872. return nil, nil, err
  2873. }
  2874. clients = append(clients, page...)
  2875. }
  2876. // Step 2: Sort clients by (Up + Down) descending
  2877. sort.Slice(clients, func(i, j int) bool {
  2878. return (clients[i].Up + clients[i].Down) > (clients[j].Up + clients[j].Down)
  2879. })
  2880. // Step 3: Extract sorted valid emails and track found ones
  2881. validEmails := make([]string, 0, len(clients))
  2882. found := make(map[string]bool)
  2883. for _, client := range clients {
  2884. validEmails = append(validEmails, client.Email)
  2885. found[client.Email] = true
  2886. }
  2887. // Step 4: Identify emails that were not found in the database
  2888. extraEmails := make([]string, 0)
  2889. for _, email := range emails {
  2890. if !found[email] {
  2891. extraEmails = append(extraEmails, email)
  2892. }
  2893. }
  2894. return validEmails, extraEmails, nil
  2895. }
  2896. type SubLinkProvider interface {
  2897. SubLinksForSubId(host, subId string) ([]string, error)
  2898. LinksForClient(host string, inbound *model.Inbound, email string) []string
  2899. }
  2900. var registeredSubLinkProvider SubLinkProvider
  2901. func RegisterSubLinkProvider(p SubLinkProvider) {
  2902. registeredSubLinkProvider = p
  2903. }
  2904. func (s *InboundService) GetSubLinks(host, subId string) ([]string, error) {
  2905. if registeredSubLinkProvider == nil {
  2906. return nil, common.NewError("sub link provider not registered")
  2907. }
  2908. return registeredSubLinkProvider.SubLinksForSubId(host, subId)
  2909. }
  2910. func (s *InboundService) GetAllClientLinks(host string, email string) ([]string, error) {
  2911. if email == "" {
  2912. return nil, common.NewError("client email is required")
  2913. }
  2914. if registeredSubLinkProvider == nil {
  2915. return nil, common.NewError("sub link provider not registered")
  2916. }
  2917. rec, err := s.clientService.GetRecordByEmail(nil, email)
  2918. if err != nil {
  2919. return nil, err
  2920. }
  2921. inboundIds, err := s.clientService.GetInboundIdsForRecord(rec.Id)
  2922. if err != nil {
  2923. return nil, err
  2924. }
  2925. var links []string
  2926. for _, ibId := range inboundIds {
  2927. inbound, getErr := s.GetInbound(ibId)
  2928. if getErr != nil {
  2929. return nil, getErr
  2930. }
  2931. links = append(links, registeredSubLinkProvider.LinksForClient(host, inbound, email)...)
  2932. }
  2933. return links, nil
  2934. }