inbound.go 109 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822
  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. // InboundService provides business logic for managing Xray inbound configurations.
  23. // It handles CRUD operations for inbounds, client management, traffic monitoring,
  24. // and integration with the Xray API for real-time updates.
  25. type InboundService struct {
  26. // xrayApi is retained for backwards compatibility with bulk paths
  27. // that still talk to the local engine directly (e.g. traffic-reset
  28. // jobs that scope to NodeID IS NULL inbounds anyway). New code paths
  29. // route through runtimeFor() instead so they can target remote nodes.
  30. xrayApi xray.XrayAPI
  31. }
  32. // runtimeFor returns the Runtime adapter for an inbound's destination
  33. // engine. Returns the local runtime when the inbound has no NodeID
  34. // (legacy/local inbounds); otherwise the cached Remote for that node.
  35. //
  36. // nil is returned only when the runtime Manager hasn't been wired yet
  37. // (extremely early bootstrap). Callers treat nil as a transient error
  38. // and either fall back to needRestart=true or surface "panel still
  39. // starting" upstream.
  40. func (s *InboundService) runtimeFor(ib *model.Inbound) (runtime.Runtime, error) {
  41. mgr := runtime.GetManager()
  42. if mgr == nil {
  43. return nil, fmt.Errorf("runtime manager not initialised")
  44. }
  45. return mgr.RuntimeFor(ib.NodeID)
  46. }
  47. type CopyClientsResult struct {
  48. Added []string `json:"added"`
  49. Skipped []string `json:"skipped"`
  50. Errors []string `json:"errors"`
  51. }
  52. // enrichClientStats parses each inbound's clients once, fills in the
  53. // UUID/SubId fields on the preloaded ClientStats, and tops up rows owned by
  54. // a sibling inbound (shared-email mode — the row is keyed on email so it
  55. // only preloads on its owning inbound).
  56. func (s *InboundService) enrichClientStats(db *gorm.DB, inbounds []*model.Inbound) {
  57. if len(inbounds) == 0 {
  58. return
  59. }
  60. clientsByInbound := make([][]model.Client, len(inbounds))
  61. seenByInbound := make([]map[string]struct{}, len(inbounds))
  62. missing := make(map[string]struct{})
  63. for i, inbound := range inbounds {
  64. clients, _ := s.GetClients(inbound)
  65. clientsByInbound[i] = clients
  66. seen := make(map[string]struct{}, len(inbound.ClientStats))
  67. for _, st := range inbound.ClientStats {
  68. if st.Email != "" {
  69. seen[strings.ToLower(st.Email)] = struct{}{}
  70. }
  71. }
  72. seenByInbound[i] = seen
  73. for _, c := range clients {
  74. if c.Email == "" {
  75. continue
  76. }
  77. if _, ok := seen[strings.ToLower(c.Email)]; !ok {
  78. missing[c.Email] = struct{}{}
  79. }
  80. }
  81. }
  82. if len(missing) > 0 {
  83. emails := make([]string, 0, len(missing))
  84. for e := range missing {
  85. emails = append(emails, e)
  86. }
  87. var extra []xray.ClientTraffic
  88. if err := db.Model(xray.ClientTraffic{}).Where("email IN ?", emails).Find(&extra).Error; err != nil {
  89. logger.Warning("enrichClientStats:", err)
  90. } else {
  91. byEmail := make(map[string]xray.ClientTraffic, len(extra))
  92. for _, st := range extra {
  93. byEmail[strings.ToLower(st.Email)] = st
  94. }
  95. for i, inbound := range inbounds {
  96. for _, c := range clientsByInbound[i] {
  97. if c.Email == "" {
  98. continue
  99. }
  100. key := strings.ToLower(c.Email)
  101. if _, ok := seenByInbound[i][key]; ok {
  102. continue
  103. }
  104. if st, ok := byEmail[key]; ok {
  105. inbound.ClientStats = append(inbound.ClientStats, st)
  106. seenByInbound[i][key] = struct{}{}
  107. }
  108. }
  109. }
  110. }
  111. }
  112. for i, inbound := range inbounds {
  113. clients := clientsByInbound[i]
  114. if len(clients) == 0 || len(inbound.ClientStats) == 0 {
  115. continue
  116. }
  117. cMap := make(map[string]model.Client, len(clients))
  118. for _, c := range clients {
  119. cMap[strings.ToLower(c.Email)] = c
  120. }
  121. for j := range inbound.ClientStats {
  122. email := strings.ToLower(inbound.ClientStats[j].Email)
  123. if c, ok := cMap[email]; ok {
  124. inbound.ClientStats[j].UUID = c.ID
  125. inbound.ClientStats[j].SubId = c.SubID
  126. }
  127. }
  128. }
  129. }
  130. // GetInbounds retrieves all inbounds for a specific user with client stats.
  131. func (s *InboundService) GetInbounds(userId int) ([]*model.Inbound, error) {
  132. db := database.GetDB()
  133. var inbounds []*model.Inbound
  134. err := db.Model(model.Inbound{}).Preload("ClientStats").Where("user_id = ?", userId).Find(&inbounds).Error
  135. if err != nil && err != gorm.ErrRecordNotFound {
  136. return nil, err
  137. }
  138. s.enrichClientStats(db, inbounds)
  139. return inbounds, nil
  140. }
  141. // GetAllInbounds retrieves all inbounds with client stats.
  142. func (s *InboundService) GetAllInbounds() ([]*model.Inbound, error) {
  143. db := database.GetDB()
  144. var inbounds []*model.Inbound
  145. err := db.Model(model.Inbound{}).Preload("ClientStats").Find(&inbounds).Error
  146. if err != nil && err != gorm.ErrRecordNotFound {
  147. return nil, err
  148. }
  149. s.enrichClientStats(db, inbounds)
  150. return inbounds, nil
  151. }
  152. func (s *InboundService) GetInboundsByTrafficReset(period string) ([]*model.Inbound, error) {
  153. db := database.GetDB()
  154. var inbounds []*model.Inbound
  155. err := db.Model(model.Inbound{}).Where("traffic_reset = ?", period).Find(&inbounds).Error
  156. if err != nil && err != gorm.ErrRecordNotFound {
  157. return nil, err
  158. }
  159. return inbounds, nil
  160. }
  161. func (s *InboundService) GetClients(inbound *model.Inbound) ([]model.Client, error) {
  162. settings := map[string][]model.Client{}
  163. json.Unmarshal([]byte(inbound.Settings), &settings)
  164. if settings == nil {
  165. return nil, fmt.Errorf("setting is null")
  166. }
  167. clients := settings["clients"]
  168. if clients == nil {
  169. return nil, nil
  170. }
  171. return clients, nil
  172. }
  173. func (s *InboundService) getAllEmails() ([]string, error) {
  174. db := database.GetDB()
  175. var emails []string
  176. err := db.Raw(`
  177. SELECT DISTINCT JSON_EXTRACT(client.value, '$.email')
  178. FROM inbounds,
  179. JSON_EACH(JSON_EXTRACT(inbounds.settings, '$.clients')) AS client
  180. `).Scan(&emails).Error
  181. if err != nil {
  182. return nil, err
  183. }
  184. return emails, nil
  185. }
  186. // getAllEmailSubIDs returns email→subId. An email seen with two different
  187. // non-empty subIds is locked (mapped to "") so neither identity can claim it.
  188. func (s *InboundService) getAllEmailSubIDs() (map[string]string, error) {
  189. db := database.GetDB()
  190. var rows []struct {
  191. Email string
  192. SubID string
  193. }
  194. err := db.Raw(`
  195. SELECT JSON_EXTRACT(client.value, '$.email') AS email,
  196. JSON_EXTRACT(client.value, '$.subId') AS sub_id
  197. FROM inbounds,
  198. JSON_EACH(JSON_EXTRACT(inbounds.settings, '$.clients')) AS client
  199. `).Scan(&rows).Error
  200. if err != nil {
  201. return nil, err
  202. }
  203. result := make(map[string]string, len(rows))
  204. for _, r := range rows {
  205. email := strings.ToLower(strings.Trim(r.Email, "\""))
  206. if email == "" {
  207. continue
  208. }
  209. subID := strings.Trim(r.SubID, "\"")
  210. if existing, ok := result[email]; ok {
  211. if existing != subID {
  212. result[email] = ""
  213. }
  214. continue
  215. }
  216. result[email] = subID
  217. }
  218. return result, nil
  219. }
  220. func lowerAll(in []string) []string {
  221. out := make([]string, len(in))
  222. for i, s := range in {
  223. out[i] = strings.ToLower(s)
  224. }
  225. return out
  226. }
  227. // emailUsedByOtherInbounds reports whether email lives in any inbound other
  228. // than exceptInboundId. Empty email returns false.
  229. func (s *InboundService) emailUsedByOtherInbounds(email string, exceptInboundId int) (bool, error) {
  230. if email == "" {
  231. return false, nil
  232. }
  233. db := database.GetDB()
  234. var count int64
  235. err := db.Raw(`
  236. SELECT COUNT(*)
  237. FROM inbounds,
  238. JSON_EACH(JSON_EXTRACT(inbounds.settings, '$.clients')) AS client
  239. WHERE inbounds.id != ?
  240. AND LOWER(JSON_EXTRACT(client.value, '$.email')) = LOWER(?)
  241. `, exceptInboundId, email).Scan(&count).Error
  242. if err != nil {
  243. return false, err
  244. }
  245. return count > 0, nil
  246. }
  247. // checkEmailsExistForClients validates a batch of incoming clients. An email
  248. // collides only when the existing holder has a different (or empty) subId —
  249. // matching non-empty subIds let multiple inbounds share one identity.
  250. func (s *InboundService) checkEmailsExistForClients(clients []model.Client) (string, error) {
  251. emailSubIDs, err := s.getAllEmailSubIDs()
  252. if err != nil {
  253. return "", err
  254. }
  255. seen := make(map[string]string, len(clients))
  256. for _, client := range clients {
  257. if client.Email == "" {
  258. continue
  259. }
  260. key := strings.ToLower(client.Email)
  261. // Within the same payload, the same email must carry the same subId;
  262. // otherwise we would silently merge two distinct identities.
  263. if prev, ok := seen[key]; ok {
  264. if prev != client.SubID || client.SubID == "" {
  265. return client.Email, nil
  266. }
  267. continue
  268. }
  269. seen[key] = client.SubID
  270. if existingSub, ok := emailSubIDs[key]; ok {
  271. if client.SubID == "" || existingSub == "" || existingSub != client.SubID {
  272. return client.Email, nil
  273. }
  274. }
  275. }
  276. return "", nil
  277. }
  278. // AddInbound creates a new inbound configuration.
  279. // It validates port uniqueness, client email uniqueness, and required fields,
  280. // then saves the inbound to the database and optionally adds it to the running Xray instance.
  281. // Returns the created inbound, whether Xray needs restart, and any error.
  282. func (s *InboundService) AddInbound(inbound *model.Inbound) (*model.Inbound, bool, error) {
  283. exist, err := s.checkPortConflict(inbound, 0)
  284. if err != nil {
  285. return inbound, false, err
  286. }
  287. if exist {
  288. return inbound, false, common.NewError("Port already exists:", inbound.Port)
  289. }
  290. // pick a tag that won't collide with an existing row. for the common
  291. // case this is the same "inbound-<port>" string the controller already
  292. // set; only when this port already has another inbound on a different
  293. // transport (now possible after the transport-aware port check) does
  294. // this disambiguate with a -tcp/-udp suffix. see #4103.
  295. inbound.Tag, err = s.generateInboundTag(inbound, 0)
  296. if err != nil {
  297. return inbound, false, err
  298. }
  299. clients, err := s.GetClients(inbound)
  300. if err != nil {
  301. return inbound, false, err
  302. }
  303. existEmail, err := s.checkEmailsExistForClients(clients)
  304. if err != nil {
  305. return inbound, false, err
  306. }
  307. if existEmail != "" {
  308. return inbound, false, common.NewError("Duplicate email:", existEmail)
  309. }
  310. // Ensure created_at and updated_at on clients in settings
  311. if len(clients) > 0 {
  312. var settings map[string]any
  313. if err2 := json.Unmarshal([]byte(inbound.Settings), &settings); err2 == nil && settings != nil {
  314. now := time.Now().Unix() * 1000
  315. updatedClients := make([]model.Client, 0, len(clients))
  316. for _, c := range clients {
  317. if c.CreatedAt == 0 {
  318. c.CreatedAt = now
  319. }
  320. c.UpdatedAt = now
  321. updatedClients = append(updatedClients, c)
  322. }
  323. settings["clients"] = updatedClients
  324. if bs, err3 := json.MarshalIndent(settings, "", " "); err3 == nil {
  325. inbound.Settings = string(bs)
  326. } else {
  327. logger.Debug("Unable to marshal inbound settings with timestamps:", err3)
  328. }
  329. } else if err2 != nil {
  330. logger.Debug("Unable to parse inbound settings for timestamps:", err2)
  331. }
  332. }
  333. // Secure client ID
  334. for _, client := range clients {
  335. switch inbound.Protocol {
  336. case "trojan":
  337. if client.Password == "" {
  338. return inbound, false, common.NewError("empty client ID")
  339. }
  340. case "shadowsocks":
  341. if client.Email == "" {
  342. return inbound, false, common.NewError("empty client ID")
  343. }
  344. case "hysteria", "hysteria2":
  345. if client.Auth == "" {
  346. return inbound, false, common.NewError("empty client ID")
  347. }
  348. default:
  349. if client.ID == "" {
  350. return inbound, false, common.NewError("empty client ID")
  351. }
  352. }
  353. }
  354. db := database.GetDB()
  355. tx := db.Begin()
  356. defer func() {
  357. if err == nil {
  358. tx.Commit()
  359. } else {
  360. tx.Rollback()
  361. }
  362. }()
  363. err = tx.Save(inbound).Error
  364. if err == nil {
  365. if len(inbound.ClientStats) == 0 {
  366. for _, client := range clients {
  367. s.AddClientStat(tx, inbound.Id, &client)
  368. }
  369. }
  370. } else {
  371. return inbound, false, err
  372. }
  373. needRestart := false
  374. if inbound.Enable {
  375. rt, rterr := s.runtimeFor(inbound)
  376. if rterr != nil {
  377. // Fail-fast on remote routing errors. Assign to the named
  378. // `err` so the deferred tx handler rolls back the central
  379. // DB row that tx.Save just inserted — otherwise we'd leave
  380. // an orphan that the user sees succeed despite the toast.
  381. err = rterr
  382. return inbound, false, err
  383. }
  384. if err1 := rt.AddInbound(context.Background(), inbound); err1 == nil {
  385. logger.Debug("New inbound added on", rt.Name(), ":", inbound.Tag)
  386. } else {
  387. logger.Debug("Unable to add inbound on", rt.Name(), ":", err1)
  388. if inbound.NodeID != nil {
  389. // Remote add failed — roll back so central + node stay
  390. // in sync (no row on either side).
  391. err = err1
  392. return inbound, false, err
  393. }
  394. // Local: keep the existing fall-through-to-restart behaviour.
  395. needRestart = true
  396. }
  397. }
  398. return inbound, needRestart, err
  399. }
  400. // DelInbound deletes an inbound configuration by ID.
  401. // It removes the inbound from the database and the running Xray instance if active.
  402. // Returns whether Xray needs restart and any error.
  403. func (s *InboundService) DelInbound(id int) (bool, error) {
  404. db := database.GetDB()
  405. needRestart := false
  406. // Load the full inbound (not just the tag) so we know its NodeID and
  407. // can route the runtime call to the right engine. Skip-on-not-found
  408. // preserves the old "no-op when DB row doesn't exist" behaviour.
  409. var ib model.Inbound
  410. loadErr := db.Model(model.Inbound{}).Where("id = ? and enable = ?", id, true).First(&ib).Error
  411. if loadErr == nil {
  412. // Delete is best-effort on the runtime side: the user's intent is
  413. // to get rid of the inbound, so a missing node row, an offline
  414. // node, or a remote-side "already gone" should NEVER block the
  415. // central DB cleanup. Worst case the remote keeps an orphan that
  416. // the user can clean up manually — far less painful than the row
  417. // being stuck on central.
  418. rt, rterr := s.runtimeFor(&ib)
  419. if rterr != nil {
  420. logger.Warning("DelInbound: runtime lookup failed, deleting central row anyway:", rterr)
  421. if ib.NodeID == nil {
  422. needRestart = true
  423. }
  424. } else if err1 := rt.DelInbound(context.Background(), &ib); err1 == nil {
  425. logger.Debug("Inbound deleted on", rt.Name(), ":", ib.Tag)
  426. } else {
  427. logger.Warning("DelInbound on", rt.Name(), "failed, deleting central row anyway:", err1)
  428. if ib.NodeID == nil {
  429. needRestart = true
  430. }
  431. }
  432. } else {
  433. logger.Debug("No enabled inbound found to remove by api, id:", id)
  434. }
  435. // Delete client traffics of inbounds
  436. err := db.Where("inbound_id = ?", id).Delete(xray.ClientTraffic{}).Error
  437. if err != nil {
  438. return false, err
  439. }
  440. inbound, err := s.GetInbound(id)
  441. if err != nil {
  442. return false, err
  443. }
  444. clients, err := s.GetClients(inbound)
  445. if err != nil {
  446. return false, err
  447. }
  448. // Bulk-delete client IPs for every email in this inbound. The previous
  449. // per-client loop fired one DELETE per row — at 7k+ clients that meant
  450. // thousands of synchronous SQL roundtrips and a multi-second freeze.
  451. // Chunked to stay under SQLite's bind-variable limit on huge inbounds.
  452. if len(clients) > 0 {
  453. emails := make([]string, 0, len(clients))
  454. for i := range clients {
  455. if clients[i].Email != "" {
  456. emails = append(emails, clients[i].Email)
  457. }
  458. }
  459. for _, batch := range chunkStrings(uniqueNonEmptyStrings(emails), sqliteMaxVars) {
  460. if err := db.Where("client_email IN ?", batch).
  461. Delete(model.InboundClientIps{}).Error; err != nil {
  462. return false, err
  463. }
  464. }
  465. }
  466. return needRestart, db.Delete(model.Inbound{}, id).Error
  467. }
  468. func (s *InboundService) GetInbound(id int) (*model.Inbound, error) {
  469. db := database.GetDB()
  470. inbound := &model.Inbound{}
  471. err := db.Model(model.Inbound{}).First(inbound, id).Error
  472. if err != nil {
  473. return nil, err
  474. }
  475. return inbound, nil
  476. }
  477. // SetInboundEnable toggles only the enable flag of an inbound, without
  478. // rewriting the (potentially multi-MB) settings JSON. Used by the UI's
  479. // per-row enable switch — for inbounds with thousands of clients the full
  480. // UpdateInbound path is an order of magnitude too slow for an interactive
  481. // toggle (parses + reserialises every client, runs O(N) traffic diff).
  482. //
  483. // Returns (needRestart, error). needRestart is true when the xray runtime
  484. // could not be re-synced from the cached config and a full restart is
  485. // required to pick up the change.
  486. func (s *InboundService) SetInboundEnable(id int, enable bool) (bool, error) {
  487. inbound, err := s.GetInbound(id)
  488. if err != nil {
  489. return false, err
  490. }
  491. if inbound.Enable == enable {
  492. return false, nil
  493. }
  494. db := database.GetDB()
  495. if err := db.Model(model.Inbound{}).Where("id = ?", id).
  496. Update("enable", enable).Error; err != nil {
  497. return false, err
  498. }
  499. inbound.Enable = enable
  500. // Sync xray runtime via the Runtime adapter. For local inbounds we
  501. // also rebuild the runtime config (drops clients flagged as disabled
  502. // in ClientTraffic) so the live xray sees the same filtered view it
  503. // did pre-refactor. Remote runtimes ship the unfiltered inbound —
  504. // the remote panel does its own filtering before pushing to its xray.
  505. needRestart := false
  506. rt, rterr := s.runtimeFor(inbound)
  507. if rterr != nil {
  508. if inbound.NodeID != nil {
  509. return false, rterr
  510. }
  511. return true, nil
  512. }
  513. if err := rt.DelInbound(context.Background(), inbound); err != nil &&
  514. !strings.Contains(err.Error(), "not found") {
  515. logger.Debug("SetInboundEnable: DelInbound on", rt.Name(), "failed:", err)
  516. needRestart = true
  517. }
  518. if !enable {
  519. return needRestart, nil
  520. }
  521. addTarget := inbound
  522. if inbound.NodeID == nil {
  523. runtimeInbound, err := s.buildRuntimeInboundForAPI(db, inbound)
  524. if err != nil {
  525. logger.Debug("SetInboundEnable: build runtime config failed:", err)
  526. return true, nil
  527. }
  528. addTarget = runtimeInbound
  529. }
  530. if err := rt.AddInbound(context.Background(), addTarget); err != nil {
  531. logger.Debug("SetInboundEnable: AddInbound on", rt.Name(), "failed:", err)
  532. if inbound.NodeID != nil {
  533. return false, err
  534. }
  535. needRestart = true
  536. }
  537. return needRestart, nil
  538. }
  539. // UpdateInbound modifies an existing inbound configuration.
  540. // It validates changes, updates the database, and syncs with the running Xray instance.
  541. // Returns the updated inbound, whether Xray needs restart, and any error.
  542. func (s *InboundService) UpdateInbound(inbound *model.Inbound) (*model.Inbound, bool, error) {
  543. exist, err := s.checkPortConflict(inbound, inbound.Id)
  544. if err != nil {
  545. return inbound, false, err
  546. }
  547. if exist {
  548. return inbound, false, common.NewError("Port already exists:", inbound.Port)
  549. }
  550. oldInbound, err := s.GetInbound(inbound.Id)
  551. if err != nil {
  552. return inbound, false, err
  553. }
  554. tag := oldInbound.Tag
  555. db := database.GetDB()
  556. tx := db.Begin()
  557. defer func() {
  558. if err != nil {
  559. tx.Rollback()
  560. } else {
  561. tx.Commit()
  562. }
  563. }()
  564. err = s.updateClientTraffics(tx, oldInbound, inbound)
  565. if err != nil {
  566. return inbound, false, err
  567. }
  568. // Ensure created_at and updated_at exist in inbound.Settings clients
  569. {
  570. var oldSettings map[string]any
  571. _ = json.Unmarshal([]byte(oldInbound.Settings), &oldSettings)
  572. emailToCreated := map[string]int64{}
  573. emailToUpdated := map[string]int64{}
  574. if oldSettings != nil {
  575. if oc, ok := oldSettings["clients"].([]any); ok {
  576. for _, it := range oc {
  577. if m, ok2 := it.(map[string]any); ok2 {
  578. if email, ok3 := m["email"].(string); ok3 {
  579. switch v := m["created_at"].(type) {
  580. case float64:
  581. emailToCreated[email] = int64(v)
  582. case int64:
  583. emailToCreated[email] = v
  584. }
  585. switch v := m["updated_at"].(type) {
  586. case float64:
  587. emailToUpdated[email] = int64(v)
  588. case int64:
  589. emailToUpdated[email] = v
  590. }
  591. }
  592. }
  593. }
  594. }
  595. }
  596. var newSettings map[string]any
  597. if err2 := json.Unmarshal([]byte(inbound.Settings), &newSettings); err2 == nil && newSettings != nil {
  598. now := time.Now().Unix() * 1000
  599. if nSlice, ok := newSettings["clients"].([]any); ok {
  600. for i := range nSlice {
  601. if m, ok2 := nSlice[i].(map[string]any); ok2 {
  602. email, _ := m["email"].(string)
  603. if _, ok3 := m["created_at"]; !ok3 {
  604. if v, ok4 := emailToCreated[email]; ok4 && v > 0 {
  605. m["created_at"] = v
  606. } else {
  607. m["created_at"] = now
  608. }
  609. }
  610. // Preserve client's updated_at if present; do not bump on parent inbound update
  611. if _, hasUpdated := m["updated_at"]; !hasUpdated {
  612. if v, ok4 := emailToUpdated[email]; ok4 && v > 0 {
  613. m["updated_at"] = v
  614. }
  615. }
  616. nSlice[i] = m
  617. }
  618. }
  619. newSettings["clients"] = nSlice
  620. if bs, err3 := json.MarshalIndent(newSettings, "", " "); err3 == nil {
  621. inbound.Settings = string(bs)
  622. }
  623. }
  624. }
  625. }
  626. oldInbound.Up = inbound.Up
  627. oldInbound.Down = inbound.Down
  628. oldInbound.Total = inbound.Total
  629. oldInbound.Remark = inbound.Remark
  630. oldInbound.Enable = inbound.Enable
  631. oldInbound.ExpiryTime = inbound.ExpiryTime
  632. oldInbound.TrafficReset = inbound.TrafficReset
  633. oldInbound.Listen = inbound.Listen
  634. oldInbound.Port = inbound.Port
  635. oldInbound.Protocol = inbound.Protocol
  636. oldInbound.Settings = inbound.Settings
  637. oldInbound.StreamSettings = inbound.StreamSettings
  638. oldInbound.Sniffing = inbound.Sniffing
  639. // regenerate tag with collision-aware logic. for this row we pass
  640. // inbound.Id as ignoreId so it doesn't see its own old tag in the db.
  641. oldInbound.Tag, err = s.generateInboundTag(inbound, inbound.Id)
  642. if err != nil {
  643. return inbound, false, err
  644. }
  645. needRestart := false
  646. rt, rterr := s.runtimeFor(oldInbound)
  647. if rterr != nil {
  648. if oldInbound.NodeID != nil {
  649. err = rterr
  650. return inbound, false, err
  651. }
  652. needRestart = true
  653. } else {
  654. // Use a snapshot of the OLD tag so the remote can resolve its
  655. // remote-id even when the new tag has changed (port/listen edit).
  656. oldSnapshot := *oldInbound
  657. oldSnapshot.Tag = tag
  658. if oldInbound.NodeID == nil {
  659. // Local: keep the old del-then-add-filtered behaviour to
  660. // preserve runtime client filtering.
  661. if err2 := rt.DelInbound(context.Background(), &oldSnapshot); err2 == nil {
  662. logger.Debug("Old inbound deleted on", rt.Name(), ":", tag)
  663. }
  664. if inbound.Enable {
  665. runtimeInbound, err2 := s.buildRuntimeInboundForAPI(tx, oldInbound)
  666. if err2 != nil {
  667. logger.Debug("Unable to prepare runtime inbound config:", err2)
  668. needRestart = true
  669. } else if err2 := rt.AddInbound(context.Background(), runtimeInbound); err2 == nil {
  670. logger.Debug("Updated inbound added on", rt.Name(), ":", oldInbound.Tag)
  671. } else {
  672. logger.Debug("Unable to update inbound on", rt.Name(), ":", err2)
  673. needRestart = true
  674. }
  675. }
  676. } else {
  677. // Remote: a single UpdateInbound call (the Remote adapter
  678. // resolves remote-id by old tag, then POSTs /update/{id}).
  679. // Assign to the outer `err` on failure so the deferred tx
  680. // handler rolls back the central DB write.
  681. if !inbound.Enable {
  682. if err2 := rt.DelInbound(context.Background(), &oldSnapshot); err2 != nil {
  683. err = err2
  684. return inbound, false, err
  685. }
  686. } else if err2 := rt.UpdateInbound(context.Background(), &oldSnapshot, oldInbound); err2 != nil {
  687. err = err2
  688. return inbound, false, err
  689. }
  690. }
  691. }
  692. return inbound, needRestart, tx.Save(oldInbound).Error
  693. }
  694. func (s *InboundService) buildRuntimeInboundForAPI(tx *gorm.DB, inbound *model.Inbound) (*model.Inbound, error) {
  695. if inbound == nil {
  696. return nil, fmt.Errorf("inbound is nil")
  697. }
  698. runtimeInbound := *inbound
  699. settings := map[string]any{}
  700. if err := json.Unmarshal([]byte(inbound.Settings), &settings); err != nil {
  701. return nil, err
  702. }
  703. clients, ok := settings["clients"].([]any)
  704. if !ok {
  705. return &runtimeInbound, nil
  706. }
  707. var clientStats []xray.ClientTraffic
  708. err := tx.Model(xray.ClientTraffic{}).
  709. Where("inbound_id = ?", inbound.Id).
  710. Select("email", "enable").
  711. Find(&clientStats).Error
  712. if err != nil {
  713. return nil, err
  714. }
  715. enableMap := make(map[string]bool, len(clientStats))
  716. for _, clientTraffic := range clientStats {
  717. enableMap[clientTraffic.Email] = clientTraffic.Enable
  718. }
  719. finalClients := make([]any, 0, len(clients))
  720. for _, client := range clients {
  721. c, ok := client.(map[string]any)
  722. if !ok {
  723. continue
  724. }
  725. email, _ := c["email"].(string)
  726. if enable, exists := enableMap[email]; exists && !enable {
  727. continue
  728. }
  729. if manualEnable, ok := c["enable"].(bool); ok && !manualEnable {
  730. continue
  731. }
  732. finalClients = append(finalClients, c)
  733. }
  734. settings["clients"] = finalClients
  735. modifiedSettings, err := json.MarshalIndent(settings, "", " ")
  736. if err != nil {
  737. return nil, err
  738. }
  739. runtimeInbound.Settings = string(modifiedSettings)
  740. return &runtimeInbound, nil
  741. }
  742. // updateClientTraffics syncs the ClientTraffic rows with the inbound's clients
  743. // list: removes rows for emails that disappeared, inserts rows for newly-added
  744. // emails. Uses sets for O(N) lookup — the previous nested-loop implementation
  745. // was O(N²) and degraded into multi-second pauses on inbounds with thousands
  746. // of clients (toggling, saving, or deleting any such inbound felt frozen).
  747. func (s *InboundService) updateClientTraffics(tx *gorm.DB, oldInbound *model.Inbound, newInbound *model.Inbound) error {
  748. oldClients, err := s.GetClients(oldInbound)
  749. if err != nil {
  750. return err
  751. }
  752. newClients, err := s.GetClients(newInbound)
  753. if err != nil {
  754. return err
  755. }
  756. // Email is the unique key for ClientTraffic rows. Clients without an
  757. // email have no stats row to sync — skip them on both sides instead of
  758. // risking a unique-constraint hit or accidental delete of an unrelated row.
  759. oldEmails := make(map[string]struct{}, len(oldClients))
  760. for i := range oldClients {
  761. if oldClients[i].Email == "" {
  762. continue
  763. }
  764. oldEmails[oldClients[i].Email] = struct{}{}
  765. }
  766. newEmails := make(map[string]struct{}, len(newClients))
  767. for i := range newClients {
  768. if newClients[i].Email == "" {
  769. continue
  770. }
  771. newEmails[newClients[i].Email] = struct{}{}
  772. }
  773. // Drop stats rows for removed emails — but not when a sibling inbound
  774. // still references the email, since the row is the shared accumulator.
  775. for i := range oldClients {
  776. email := oldClients[i].Email
  777. if email == "" {
  778. continue
  779. }
  780. if _, kept := newEmails[email]; kept {
  781. continue
  782. }
  783. stillUsed, err := s.emailUsedByOtherInbounds(email, oldInbound.Id)
  784. if err != nil {
  785. return err
  786. }
  787. if stillUsed {
  788. continue
  789. }
  790. if err := s.DelClientStat(tx, email); err != nil {
  791. return err
  792. }
  793. }
  794. // Added clients — create their stats rows.
  795. for i := range newClients {
  796. email := newClients[i].Email
  797. if email == "" {
  798. continue
  799. }
  800. if _, existed := oldEmails[email]; existed {
  801. continue
  802. }
  803. if err := s.AddClientStat(tx, oldInbound.Id, &newClients[i]); err != nil {
  804. return err
  805. }
  806. }
  807. return nil
  808. }
  809. func (s *InboundService) AddInboundClient(data *model.Inbound) (bool, error) {
  810. clients, err := s.GetClients(data)
  811. if err != nil {
  812. return false, err
  813. }
  814. var settings map[string]any
  815. err = json.Unmarshal([]byte(data.Settings), &settings)
  816. if err != nil {
  817. return false, err
  818. }
  819. interfaceClients := settings["clients"].([]any)
  820. // Add timestamps for new clients being appended
  821. nowTs := time.Now().Unix() * 1000
  822. for i := range interfaceClients {
  823. if cm, ok := interfaceClients[i].(map[string]any); ok {
  824. if _, ok2 := cm["created_at"]; !ok2 {
  825. cm["created_at"] = nowTs
  826. }
  827. cm["updated_at"] = nowTs
  828. interfaceClients[i] = cm
  829. }
  830. }
  831. existEmail, err := s.checkEmailsExistForClients(clients)
  832. if err != nil {
  833. return false, err
  834. }
  835. if existEmail != "" {
  836. return false, common.NewError("Duplicate email:", existEmail)
  837. }
  838. oldInbound, err := s.GetInbound(data.Id)
  839. if err != nil {
  840. return false, err
  841. }
  842. // Secure client ID
  843. for _, client := range clients {
  844. switch oldInbound.Protocol {
  845. case "trojan":
  846. if client.Password == "" {
  847. return false, common.NewError("empty client ID")
  848. }
  849. case "shadowsocks":
  850. if client.Email == "" {
  851. return false, common.NewError("empty client ID")
  852. }
  853. case "hysteria", "hysteria2":
  854. if client.Auth == "" {
  855. return false, common.NewError("empty client ID")
  856. }
  857. default:
  858. if client.ID == "" {
  859. return false, common.NewError("empty client ID")
  860. }
  861. }
  862. }
  863. var oldSettings map[string]any
  864. err = json.Unmarshal([]byte(oldInbound.Settings), &oldSettings)
  865. if err != nil {
  866. return false, err
  867. }
  868. oldClients := oldSettings["clients"].([]any)
  869. oldClients = append(oldClients, interfaceClients...)
  870. oldSettings["clients"] = oldClients
  871. newSettings, err := json.MarshalIndent(oldSettings, "", " ")
  872. if err != nil {
  873. return false, err
  874. }
  875. oldInbound.Settings = string(newSettings)
  876. db := database.GetDB()
  877. tx := db.Begin()
  878. defer func() {
  879. if err != nil {
  880. tx.Rollback()
  881. } else {
  882. tx.Commit()
  883. }
  884. }()
  885. needRestart := false
  886. rt, rterr := s.runtimeFor(oldInbound)
  887. if rterr != nil {
  888. if oldInbound.NodeID != nil {
  889. err = rterr
  890. return false, err
  891. }
  892. needRestart = true
  893. } else if oldInbound.NodeID == nil {
  894. // Local: per-client AddUser keeps existing connections alive
  895. // (incremental hot-add). Walk every new client; on any failure
  896. // fall back to needRestart so cron rebuilds from scratch.
  897. for _, client := range clients {
  898. if len(client.Email) == 0 {
  899. needRestart = true
  900. continue
  901. }
  902. s.AddClientStat(tx, data.Id, &client)
  903. if !client.Enable {
  904. continue
  905. }
  906. cipher := ""
  907. if oldInbound.Protocol == "shadowsocks" {
  908. cipher = oldSettings["method"].(string)
  909. }
  910. err1 := rt.AddUser(context.Background(), oldInbound, map[string]any{
  911. "email": client.Email,
  912. "id": client.ID,
  913. "auth": client.Auth,
  914. "security": client.Security,
  915. "flow": client.Flow,
  916. "password": client.Password,
  917. "cipher": cipher,
  918. })
  919. if err1 == nil {
  920. logger.Debug("Client added on", rt.Name(), ":", client.Email)
  921. } else {
  922. logger.Debug("Error in adding client on", rt.Name(), ":", err1)
  923. needRestart = true
  924. }
  925. }
  926. } else {
  927. // Remote: a single UpdateInbound ships the new clients in one
  928. // HTTP round-trip rather than N. Settings are already mutated
  929. // in-memory (oldInbound.Settings) so the remote sees the final
  930. // state. Per-client ClientStat rows still need the central DB
  931. // update so the loop runs that branch first.
  932. for _, client := range clients {
  933. if len(client.Email) > 0 {
  934. s.AddClientStat(tx, data.Id, &client)
  935. }
  936. }
  937. if err1 := rt.UpdateInbound(context.Background(), oldInbound, oldInbound); err1 != nil {
  938. err = err1
  939. return false, err
  940. }
  941. }
  942. return needRestart, tx.Save(oldInbound).Error
  943. }
  944. func (s *InboundService) getClientPrimaryKey(protocol model.Protocol, client model.Client) string {
  945. switch protocol {
  946. case model.Trojan:
  947. return client.Password
  948. case model.Shadowsocks:
  949. return client.Email
  950. case model.Hysteria:
  951. return client.Auth
  952. default:
  953. return client.ID
  954. }
  955. }
  956. func (s *InboundService) writeBackClientSubID(sourceInboundID int, sourceProtocol model.Protocol, client model.Client, subID string) (bool, error) {
  957. client.SubID = subID
  958. client.UpdatedAt = time.Now().UnixMilli()
  959. clientID := s.getClientPrimaryKey(sourceProtocol, client)
  960. if clientID == "" {
  961. return false, common.NewError("empty client ID")
  962. }
  963. settingsBytes, err := json.Marshal(map[string][]model.Client{
  964. "clients": {client},
  965. })
  966. if err != nil {
  967. return false, err
  968. }
  969. updatePayload := &model.Inbound{
  970. Id: sourceInboundID,
  971. Settings: string(settingsBytes),
  972. }
  973. return s.UpdateInboundClient(updatePayload, clientID)
  974. }
  975. func (s *InboundService) generateRandomCredential(targetProtocol model.Protocol) string {
  976. switch targetProtocol {
  977. case model.VMESS, model.VLESS:
  978. return uuid.NewString()
  979. default:
  980. return strings.ReplaceAll(uuid.NewString(), "-", "")
  981. }
  982. }
  983. func (s *InboundService) buildTargetClientFromSource(source model.Client, targetProtocol model.Protocol, email string, flow string) (model.Client, error) {
  984. nowTs := time.Now().UnixMilli()
  985. target := source
  986. target.Email = email
  987. target.CreatedAt = nowTs
  988. target.UpdatedAt = nowTs
  989. target.ID = ""
  990. target.Password = ""
  991. target.Auth = ""
  992. target.Flow = ""
  993. switch targetProtocol {
  994. case model.VMESS:
  995. target.ID = s.generateRandomCredential(targetProtocol)
  996. case model.VLESS:
  997. target.ID = s.generateRandomCredential(targetProtocol)
  998. if flow == "xtls-rprx-vision" || flow == "xtls-rprx-vision-udp443" {
  999. target.Flow = flow
  1000. }
  1001. case model.Trojan, model.Shadowsocks:
  1002. target.Password = s.generateRandomCredential(targetProtocol)
  1003. case model.Hysteria:
  1004. target.Auth = s.generateRandomCredential(targetProtocol)
  1005. default:
  1006. target.ID = s.generateRandomCredential(targetProtocol)
  1007. }
  1008. return target, nil
  1009. }
  1010. func (s *InboundService) nextAvailableCopiedEmail(originalEmail string, targetID int, occupied map[string]struct{}) string {
  1011. base := fmt.Sprintf("%s_%d", originalEmail, targetID)
  1012. candidate := base
  1013. suffix := 0
  1014. for {
  1015. if _, exists := occupied[strings.ToLower(candidate)]; !exists {
  1016. occupied[strings.ToLower(candidate)] = struct{}{}
  1017. return candidate
  1018. }
  1019. suffix++
  1020. candidate = fmt.Sprintf("%s_%d", base, suffix)
  1021. }
  1022. }
  1023. func (s *InboundService) CopyInboundClients(targetInboundID int, sourceInboundID int, clientEmails []string, flow string) (*CopyClientsResult, bool, error) {
  1024. result := &CopyClientsResult{
  1025. Added: []string{},
  1026. Skipped: []string{},
  1027. Errors: []string{},
  1028. }
  1029. if targetInboundID == sourceInboundID {
  1030. return result, false, common.NewError("source and target inbounds must be different")
  1031. }
  1032. targetInbound, err := s.GetInbound(targetInboundID)
  1033. if err != nil {
  1034. return result, false, err
  1035. }
  1036. sourceInbound, err := s.GetInbound(sourceInboundID)
  1037. if err != nil {
  1038. return result, false, err
  1039. }
  1040. sourceClients, err := s.GetClients(sourceInbound)
  1041. if err != nil {
  1042. return result, false, err
  1043. }
  1044. if len(sourceClients) == 0 {
  1045. return result, false, nil
  1046. }
  1047. allowedEmails := map[string]struct{}{}
  1048. if len(clientEmails) > 0 {
  1049. for _, email := range clientEmails {
  1050. allowedEmails[strings.ToLower(strings.TrimSpace(email))] = struct{}{}
  1051. }
  1052. }
  1053. occupiedEmails := map[string]struct{}{}
  1054. allEmails, err := s.getAllEmails()
  1055. if err != nil {
  1056. return result, false, err
  1057. }
  1058. for _, email := range allEmails {
  1059. clean := strings.Trim(email, "\"")
  1060. if clean != "" {
  1061. occupiedEmails[strings.ToLower(clean)] = struct{}{}
  1062. }
  1063. }
  1064. newClients := make([]model.Client, 0)
  1065. needRestart := false
  1066. for _, sourceClient := range sourceClients {
  1067. originalEmail := strings.TrimSpace(sourceClient.Email)
  1068. if originalEmail == "" {
  1069. continue
  1070. }
  1071. if len(allowedEmails) > 0 {
  1072. if _, ok := allowedEmails[strings.ToLower(originalEmail)]; !ok {
  1073. continue
  1074. }
  1075. }
  1076. if sourceClient.SubID == "" {
  1077. newSubID := uuid.NewString()
  1078. subNeedRestart, subErr := s.writeBackClientSubID(sourceInbound.Id, sourceInbound.Protocol, sourceClient, newSubID)
  1079. if subErr != nil {
  1080. result.Errors = append(result.Errors, fmt.Sprintf("%s: failed to write source subId: %v", originalEmail, subErr))
  1081. continue
  1082. }
  1083. if subNeedRestart {
  1084. needRestart = true
  1085. }
  1086. sourceClient.SubID = newSubID
  1087. }
  1088. targetEmail := s.nextAvailableCopiedEmail(originalEmail, targetInboundID, occupiedEmails)
  1089. targetClient, buildErr := s.buildTargetClientFromSource(sourceClient, targetInbound.Protocol, targetEmail, flow)
  1090. if buildErr != nil {
  1091. result.Errors = append(result.Errors, fmt.Sprintf("%s: %v", originalEmail, buildErr))
  1092. continue
  1093. }
  1094. newClients = append(newClients, targetClient)
  1095. result.Added = append(result.Added, targetEmail)
  1096. }
  1097. if len(newClients) == 0 {
  1098. return result, needRestart, nil
  1099. }
  1100. settingsPayload, err := json.Marshal(map[string][]model.Client{
  1101. "clients": newClients,
  1102. })
  1103. if err != nil {
  1104. return result, needRestart, err
  1105. }
  1106. addNeedRestart, err := s.AddInboundClient(&model.Inbound{
  1107. Id: targetInboundID,
  1108. Settings: string(settingsPayload),
  1109. })
  1110. if err != nil {
  1111. return result, needRestart, err
  1112. }
  1113. if addNeedRestart {
  1114. needRestart = true
  1115. }
  1116. return result, needRestart, nil
  1117. }
  1118. func (s *InboundService) DelInboundClient(inboundId int, clientId string) (bool, error) {
  1119. oldInbound, err := s.GetInbound(inboundId)
  1120. if err != nil {
  1121. logger.Error("Load Old Data Error")
  1122. return false, err
  1123. }
  1124. var settings map[string]any
  1125. err = json.Unmarshal([]byte(oldInbound.Settings), &settings)
  1126. if err != nil {
  1127. return false, err
  1128. }
  1129. email := ""
  1130. client_key := "id"
  1131. switch oldInbound.Protocol {
  1132. case "trojan":
  1133. client_key = "password"
  1134. case "shadowsocks":
  1135. client_key = "email"
  1136. case "hysteria", "hysteria2":
  1137. client_key = "auth"
  1138. }
  1139. interfaceClients := settings["clients"].([]any)
  1140. var newClients []any
  1141. needApiDel := false
  1142. clientFound := false
  1143. for _, client := range interfaceClients {
  1144. c := client.(map[string]any)
  1145. c_id := c[client_key].(string)
  1146. if c_id == clientId {
  1147. clientFound = true
  1148. email, _ = c["email"].(string)
  1149. needApiDel, _ = c["enable"].(bool)
  1150. } else {
  1151. newClients = append(newClients, client)
  1152. }
  1153. }
  1154. if !clientFound {
  1155. return false, common.NewError("Client Not Found In Inbound For ID:", clientId)
  1156. }
  1157. if len(newClients) == 0 {
  1158. return false, common.NewError("no client remained in Inbound")
  1159. }
  1160. settings["clients"] = newClients
  1161. newSettings, err := json.MarshalIndent(settings, "", " ")
  1162. if err != nil {
  1163. return false, err
  1164. }
  1165. oldInbound.Settings = string(newSettings)
  1166. db := database.GetDB()
  1167. // Keep the client_traffics row and IPs alive when another inbound still
  1168. // references this email — siblings depend on the shared accounting state.
  1169. emailShared, err := s.emailUsedByOtherInbounds(email, inboundId)
  1170. if err != nil {
  1171. return false, err
  1172. }
  1173. if !emailShared {
  1174. err = s.DelClientIPs(db, email)
  1175. if err != nil {
  1176. logger.Error("Error in delete client IPs")
  1177. return false, err
  1178. }
  1179. }
  1180. needRestart := false
  1181. if len(email) > 0 {
  1182. notDepleted := true
  1183. err = db.Model(xray.ClientTraffic{}).Select("enable").Where("email = ?", email).First(&notDepleted).Error
  1184. if err != nil {
  1185. logger.Error("Get stats error")
  1186. return false, err
  1187. }
  1188. if !emailShared {
  1189. err = s.DelClientStat(db, email)
  1190. if err != nil {
  1191. logger.Error("Delete stats Data Error")
  1192. return false, err
  1193. }
  1194. }
  1195. if needApiDel && notDepleted {
  1196. rt, rterr := s.runtimeFor(oldInbound)
  1197. if rterr != nil {
  1198. if oldInbound.NodeID != nil {
  1199. return false, rterr
  1200. }
  1201. needRestart = true
  1202. } else if oldInbound.NodeID == nil {
  1203. err1 := rt.RemoveUser(context.Background(), oldInbound, email)
  1204. if err1 == nil {
  1205. logger.Debug("Client deleted on", rt.Name(), ":", email)
  1206. needRestart = false
  1207. } else if strings.Contains(err1.Error(), fmt.Sprintf("User %s not found.", email)) {
  1208. logger.Debug("User is already deleted. Nothing to do more...")
  1209. } else {
  1210. logger.Debug("Error in deleting client on", rt.Name(), ":", err1)
  1211. needRestart = true
  1212. }
  1213. } else {
  1214. // Remote: settings already mutated above; one UpdateInbound
  1215. // ships the post-deletion state to the node.
  1216. if err1 := rt.UpdateInbound(context.Background(), oldInbound, oldInbound); err1 != nil {
  1217. return false, err1
  1218. }
  1219. }
  1220. }
  1221. }
  1222. return needRestart, db.Save(oldInbound).Error
  1223. }
  1224. func (s *InboundService) UpdateInboundClient(data *model.Inbound, clientId string) (bool, error) {
  1225. // TODO: check if TrafficReset field is updating
  1226. clients, err := s.GetClients(data)
  1227. if err != nil {
  1228. return false, err
  1229. }
  1230. var settings map[string]any
  1231. err = json.Unmarshal([]byte(data.Settings), &settings)
  1232. if err != nil {
  1233. return false, err
  1234. }
  1235. interfaceClients := settings["clients"].([]any)
  1236. oldInbound, err := s.GetInbound(data.Id)
  1237. if err != nil {
  1238. return false, err
  1239. }
  1240. oldClients, err := s.GetClients(oldInbound)
  1241. if err != nil {
  1242. return false, err
  1243. }
  1244. oldEmail := ""
  1245. newClientId := ""
  1246. clientIndex := -1
  1247. for index, oldClient := range oldClients {
  1248. oldClientId := ""
  1249. switch oldInbound.Protocol {
  1250. case "trojan":
  1251. oldClientId = oldClient.Password
  1252. newClientId = clients[0].Password
  1253. case "shadowsocks":
  1254. oldClientId = oldClient.Email
  1255. newClientId = clients[0].Email
  1256. case "hysteria", "hysteria2":
  1257. oldClientId = oldClient.Auth
  1258. newClientId = clients[0].Auth
  1259. default:
  1260. oldClientId = oldClient.ID
  1261. newClientId = clients[0].ID
  1262. }
  1263. if clientId == oldClientId {
  1264. oldEmail = oldClient.Email
  1265. clientIndex = index
  1266. break
  1267. }
  1268. }
  1269. // Validate new client ID
  1270. if newClientId == "" || clientIndex == -1 {
  1271. return false, common.NewError("empty client ID")
  1272. }
  1273. if len(clients[0].Email) > 0 && clients[0].Email != oldEmail {
  1274. existEmail, err := s.checkEmailsExistForClients(clients)
  1275. if err != nil {
  1276. return false, err
  1277. }
  1278. if existEmail != "" {
  1279. return false, common.NewError("Duplicate email:", existEmail)
  1280. }
  1281. }
  1282. var oldSettings map[string]any
  1283. err = json.Unmarshal([]byte(oldInbound.Settings), &oldSettings)
  1284. if err != nil {
  1285. return false, err
  1286. }
  1287. settingsClients := oldSettings["clients"].([]any)
  1288. // Preserve created_at and set updated_at for the replacing client
  1289. var preservedCreated any
  1290. if clientIndex >= 0 && clientIndex < len(settingsClients) {
  1291. if oldMap, ok := settingsClients[clientIndex].(map[string]any); ok {
  1292. if v, ok2 := oldMap["created_at"]; ok2 {
  1293. preservedCreated = v
  1294. }
  1295. }
  1296. }
  1297. if len(interfaceClients) > 0 {
  1298. if newMap, ok := interfaceClients[0].(map[string]any); ok {
  1299. if preservedCreated == nil {
  1300. preservedCreated = time.Now().Unix() * 1000
  1301. }
  1302. newMap["created_at"] = preservedCreated
  1303. newMap["updated_at"] = time.Now().Unix() * 1000
  1304. interfaceClients[0] = newMap
  1305. }
  1306. }
  1307. settingsClients[clientIndex] = interfaceClients[0]
  1308. oldSettings["clients"] = settingsClients
  1309. // testseed is only meaningful when at least one VLESS client uses the exact
  1310. // xtls-rprx-vision flow. The client-edit path only rewrites a single client,
  1311. // so re-check the flow set here and strip a stale testseed when nothing in the
  1312. // inbound still warrants it. The full-inbound update path already handles this
  1313. // on the JS side via VLESSSettings.toJson().
  1314. if oldInbound.Protocol == model.VLESS {
  1315. hasVisionFlow := false
  1316. for _, c := range settingsClients {
  1317. cm, ok := c.(map[string]any)
  1318. if !ok {
  1319. continue
  1320. }
  1321. if flow, _ := cm["flow"].(string); flow == "xtls-rprx-vision" {
  1322. hasVisionFlow = true
  1323. break
  1324. }
  1325. }
  1326. if !hasVisionFlow {
  1327. delete(oldSettings, "testseed")
  1328. }
  1329. }
  1330. newSettings, err := json.MarshalIndent(oldSettings, "", " ")
  1331. if err != nil {
  1332. return false, err
  1333. }
  1334. oldInbound.Settings = string(newSettings)
  1335. db := database.GetDB()
  1336. tx := db.Begin()
  1337. defer func() {
  1338. if err != nil {
  1339. tx.Rollback()
  1340. } else {
  1341. tx.Commit()
  1342. }
  1343. }()
  1344. if len(clients[0].Email) > 0 {
  1345. if len(oldEmail) > 0 {
  1346. // Repointing onto an email that already has a row would collide on
  1347. // the unique constraint, so retire the donor and let the surviving
  1348. // row carry the merged identity.
  1349. emailUnchanged := strings.EqualFold(oldEmail, clients[0].Email)
  1350. targetExists := int64(0)
  1351. if !emailUnchanged {
  1352. if err = tx.Model(xray.ClientTraffic{}).Where("email = ?", clients[0].Email).Count(&targetExists).Error; err != nil {
  1353. return false, err
  1354. }
  1355. }
  1356. if emailUnchanged || targetExists == 0 {
  1357. err = s.UpdateClientStat(tx, oldEmail, &clients[0])
  1358. if err != nil {
  1359. return false, err
  1360. }
  1361. err = s.UpdateClientIPs(tx, oldEmail, clients[0].Email)
  1362. if err != nil {
  1363. return false, err
  1364. }
  1365. } else {
  1366. stillUsed, sErr := s.emailUsedByOtherInbounds(oldEmail, data.Id)
  1367. if sErr != nil {
  1368. return false, sErr
  1369. }
  1370. if !stillUsed {
  1371. if err = s.DelClientStat(tx, oldEmail); err != nil {
  1372. return false, err
  1373. }
  1374. if err = s.DelClientIPs(tx, oldEmail); err != nil {
  1375. return false, err
  1376. }
  1377. }
  1378. // Refresh the surviving row with the new client's limits/expiry.
  1379. if err = s.UpdateClientStat(tx, clients[0].Email, &clients[0]); err != nil {
  1380. return false, err
  1381. }
  1382. }
  1383. } else {
  1384. s.AddClientStat(tx, data.Id, &clients[0])
  1385. }
  1386. } else {
  1387. stillUsed, err := s.emailUsedByOtherInbounds(oldEmail, data.Id)
  1388. if err != nil {
  1389. return false, err
  1390. }
  1391. if !stillUsed {
  1392. err = s.DelClientStat(tx, oldEmail)
  1393. if err != nil {
  1394. return false, err
  1395. }
  1396. err = s.DelClientIPs(tx, oldEmail)
  1397. if err != nil {
  1398. return false, err
  1399. }
  1400. }
  1401. }
  1402. needRestart := false
  1403. if len(oldEmail) > 0 {
  1404. rt, rterr := s.runtimeFor(oldInbound)
  1405. if rterr != nil {
  1406. if oldInbound.NodeID != nil {
  1407. err = rterr
  1408. return false, err
  1409. }
  1410. needRestart = true
  1411. } else if oldInbound.NodeID == nil {
  1412. // Local: paired Remove+Add on the live xray, keeping other
  1413. // clients online (full-restart fallback on partial failure).
  1414. if oldClients[clientIndex].Enable {
  1415. err1 := rt.RemoveUser(context.Background(), oldInbound, oldEmail)
  1416. if err1 == nil {
  1417. logger.Debug("Old client deleted on", rt.Name(), ":", oldEmail)
  1418. } else if strings.Contains(err1.Error(), fmt.Sprintf("User %s not found.", oldEmail)) {
  1419. logger.Debug("User is already deleted. Nothing to do more...")
  1420. } else {
  1421. logger.Debug("Error in deleting client on", rt.Name(), ":", err1)
  1422. needRestart = true
  1423. }
  1424. }
  1425. if clients[0].Enable {
  1426. cipher := ""
  1427. if oldInbound.Protocol == "shadowsocks" {
  1428. cipher = oldSettings["method"].(string)
  1429. }
  1430. err1 := rt.AddUser(context.Background(), oldInbound, map[string]any{
  1431. "email": clients[0].Email,
  1432. "id": clients[0].ID,
  1433. "security": clients[0].Security,
  1434. "flow": clients[0].Flow,
  1435. "auth": clients[0].Auth,
  1436. "password": clients[0].Password,
  1437. "cipher": cipher,
  1438. })
  1439. if err1 == nil {
  1440. logger.Debug("Client edited on", rt.Name(), ":", clients[0].Email)
  1441. } else {
  1442. logger.Debug("Error in adding client on", rt.Name(), ":", err1)
  1443. needRestart = true
  1444. }
  1445. }
  1446. } else {
  1447. // Remote: settings already mutated; one UpdateInbound suffices.
  1448. if err1 := rt.UpdateInbound(context.Background(), oldInbound, oldInbound); err1 != nil {
  1449. err = err1
  1450. return false, err
  1451. }
  1452. }
  1453. } else {
  1454. logger.Debug("Client old email not found")
  1455. needRestart = true
  1456. }
  1457. return needRestart, tx.Save(oldInbound).Error
  1458. }
  1459. // resetGracePeriodMs is the window after a reset during which incoming
  1460. // traffic snapshots from the node are ignored if they would resurrect
  1461. // non-zero counters. Three sync ticks (10s each) is enough headroom for
  1462. // the central → node reset HTTP call to land before the next pull.
  1463. const resetGracePeriodMs int64 = 30000
  1464. // SetRemoteTraffic merges absolute counters from a remote node into the
  1465. // central DB. Unlike AddTraffic, which adds deltas pulled from the local
  1466. // xray gRPC stats endpoint, this SETs the values — the node already has
  1467. // the canonical absolute value and we just mirror it.
  1468. //
  1469. // Rows in the post-reset grace window are skipped if the snapshot would
  1470. // regress them, so a user-initiated reset survives until the propagation
  1471. // HTTP call has completed on the node. After the grace window expires
  1472. // the snapshot wins regardless (the node is authoritative for the
  1473. // inbounds it hosts).
  1474. func (s *InboundService) SetRemoteTraffic(nodeID int, snap *runtime.TrafficSnapshot) error {
  1475. if snap == nil || nodeID <= 0 {
  1476. return nil
  1477. }
  1478. db := database.GetDB()
  1479. now := time.Now().UnixMilli()
  1480. // Load central inbounds for this node so we can resolve tag→id and
  1481. // honour the per-inbound grace window. One query covers every row
  1482. // touched in this tick.
  1483. var central []model.Inbound
  1484. if err := db.Model(model.Inbound{}).
  1485. Where("node_id = ?", nodeID).
  1486. Find(&central).Error; err != nil {
  1487. return err
  1488. }
  1489. tagToCentral := make(map[string]*model.Inbound, len(central))
  1490. for i := range central {
  1491. tagToCentral[central[i].Tag] = &central[i]
  1492. }
  1493. tx := db.Begin()
  1494. committed := false
  1495. defer func() {
  1496. if !committed {
  1497. tx.Rollback()
  1498. }
  1499. }()
  1500. // Per-inbound counter merge. Skip rows whose central allTime is
  1501. // suspiciously lower than the snapshot AND we're inside the grace
  1502. // window — that's the "reset hit central but not the node yet"
  1503. // pattern we want to defer until next tick.
  1504. for _, snapIb := range snap.Inbounds {
  1505. if snapIb == nil {
  1506. continue
  1507. }
  1508. c, ok := tagToCentral[snapIb.Tag]
  1509. if !ok {
  1510. continue // node has an inbound the central doesn't know about — ignore
  1511. }
  1512. snapAllTime := snapIb.AllTime
  1513. if snapAllTime == 0 {
  1514. snapAllTime = snapIb.Up + snapIb.Down
  1515. }
  1516. inGrace := c.LastTrafficResetTime > 0 && now-c.LastTrafficResetTime < resetGracePeriodMs
  1517. if inGrace && snapAllTime > c.AllTime {
  1518. logger.Debug("SetRemoteTraffic: skipping inbound", c.Id, "in reset grace window")
  1519. continue
  1520. }
  1521. if err := tx.Model(model.Inbound{}).
  1522. Where("id = ?", c.Id).
  1523. Updates(map[string]any{
  1524. "up": snapIb.Up,
  1525. "down": snapIb.Down,
  1526. "all_time": snapAllTime,
  1527. }).Error; err != nil {
  1528. return err
  1529. }
  1530. }
  1531. // Per-client merge. The snapshot's ClientStats are nested under
  1532. // each Inbound, so flatten before walking. Each client_traffics row
  1533. // is keyed by (inbound_id, email) — we resolve inbound_id from the
  1534. // central inbound row matched above.
  1535. for _, snapIb := range snap.Inbounds {
  1536. if snapIb == nil {
  1537. continue
  1538. }
  1539. c, ok := tagToCentral[snapIb.Tag]
  1540. if !ok {
  1541. continue
  1542. }
  1543. // Honour the same grace window for client rows: if the parent
  1544. // inbound was just reset, leave its clients alone too.
  1545. inGrace := c.LastTrafficResetTime > 0 && now-c.LastTrafficResetTime < resetGracePeriodMs
  1546. for _, cs := range snapIb.ClientStats {
  1547. snapAllTime := cs.AllTime
  1548. if snapAllTime == 0 {
  1549. snapAllTime = cs.Up + cs.Down
  1550. }
  1551. if inGrace {
  1552. // Skip client rows whose snapshot would push counters
  1553. // back up; allow rows that are zero on the node side
  1554. // (those are normal — node was reset alongside central).
  1555. if snapAllTime > 0 {
  1556. continue
  1557. }
  1558. }
  1559. // MAX(last_online, ?) so a momentary clock skew on the node
  1560. // can't regress the central row's last-seen timestamp.
  1561. if err := tx.Exec(
  1562. `UPDATE client_traffics
  1563. SET up = ?, down = ?, all_time = ?, last_online = MAX(last_online, ?)
  1564. WHERE inbound_id = ? AND email = ?`,
  1565. cs.Up, cs.Down, snapAllTime, cs.LastOnline, c.Id, cs.Email,
  1566. ).Error; err != nil {
  1567. return err
  1568. }
  1569. }
  1570. }
  1571. if err := tx.Commit().Error; err != nil {
  1572. return err
  1573. }
  1574. committed = true
  1575. // Push the node's online-clients contribution into xray.Process so
  1576. // GetOnlineClients returns the union of local + every node. Empty
  1577. // list still calls Set so a node that just had everyone disconnect
  1578. // updates promptly.
  1579. if p != nil {
  1580. p.SetNodeOnlineClients(nodeID, snap.OnlineEmails)
  1581. }
  1582. return nil
  1583. }
  1584. func (s *InboundService) AddTraffic(inboundTraffics []*xray.Traffic, clientTraffics []*xray.ClientTraffic) (bool, bool, error) {
  1585. var err error
  1586. db := database.GetDB()
  1587. tx := db.Begin()
  1588. defer func() {
  1589. if err != nil {
  1590. tx.Rollback()
  1591. } else {
  1592. tx.Commit()
  1593. }
  1594. }()
  1595. err = s.addInboundTraffic(tx, inboundTraffics)
  1596. if err != nil {
  1597. return false, false, err
  1598. }
  1599. err = s.addClientTraffic(tx, clientTraffics)
  1600. if err != nil {
  1601. return false, false, err
  1602. }
  1603. needRestart0, count, err := s.autoRenewClients(tx)
  1604. if err != nil {
  1605. logger.Warning("Error in renew clients:", err)
  1606. } else if count > 0 {
  1607. logger.Debugf("%v clients renewed", count)
  1608. }
  1609. disabledClientsCount := int64(0)
  1610. needRestart1, count, err := s.disableInvalidClients(tx)
  1611. if err != nil {
  1612. logger.Warning("Error in disabling invalid clients:", err)
  1613. } else if count > 0 {
  1614. logger.Debugf("%v clients disabled", count)
  1615. disabledClientsCount = count
  1616. }
  1617. needRestart2, count, err := s.disableInvalidInbounds(tx)
  1618. if err != nil {
  1619. logger.Warning("Error in disabling invalid inbounds:", err)
  1620. } else if count > 0 {
  1621. logger.Debugf("%v inbounds disabled", count)
  1622. }
  1623. return needRestart0 || needRestart1 || needRestart2, disabledClientsCount > 0, nil
  1624. }
  1625. func (s *InboundService) addInboundTraffic(tx *gorm.DB, traffics []*xray.Traffic) error {
  1626. if len(traffics) == 0 {
  1627. return nil
  1628. }
  1629. var err error
  1630. for _, traffic := range traffics {
  1631. if traffic.IsInbound {
  1632. err = tx.Model(&model.Inbound{}).Where("tag = ?", traffic.Tag).
  1633. Updates(map[string]any{
  1634. "up": gorm.Expr("up + ?", traffic.Up),
  1635. "down": gorm.Expr("down + ?", traffic.Down),
  1636. "all_time": gorm.Expr("COALESCE(all_time, 0) + ?", traffic.Up+traffic.Down),
  1637. }).Error
  1638. if err != nil {
  1639. return err
  1640. }
  1641. }
  1642. }
  1643. return nil
  1644. }
  1645. func (s *InboundService) addClientTraffic(tx *gorm.DB, traffics []*xray.ClientTraffic) (err error) {
  1646. if len(traffics) == 0 {
  1647. // Empty onlineUsers
  1648. if p != nil {
  1649. p.SetOnlineClients(make([]string, 0))
  1650. }
  1651. return nil
  1652. }
  1653. onlineClients := make([]string, 0)
  1654. emails := make([]string, 0, len(traffics))
  1655. for _, traffic := range traffics {
  1656. emails = append(emails, traffic.Email)
  1657. }
  1658. dbClientTraffics := make([]*xray.ClientTraffic, 0, len(traffics))
  1659. err = tx.Model(xray.ClientTraffic{}).Where("email IN (?)", emails).Find(&dbClientTraffics).Error
  1660. if err != nil {
  1661. return err
  1662. }
  1663. // Avoid empty slice error
  1664. if len(dbClientTraffics) == 0 {
  1665. return nil
  1666. }
  1667. dbClientTraffics, err = s.adjustTraffics(tx, dbClientTraffics)
  1668. if err != nil {
  1669. return err
  1670. }
  1671. // Index by email for O(N) merge — the previous nested loop was O(N²)
  1672. // and dominated each cron tick on inbounds with thousands of active
  1673. // clients (7500 × 7500 = 56M string comparisons every 10 seconds).
  1674. trafficByEmail := make(map[string]*xray.ClientTraffic, len(traffics))
  1675. for i := range traffics {
  1676. if traffics[i] != nil {
  1677. trafficByEmail[traffics[i].Email] = traffics[i]
  1678. }
  1679. }
  1680. now := time.Now().UnixMilli()
  1681. for dbTraffic_index := range dbClientTraffics {
  1682. t, ok := trafficByEmail[dbClientTraffics[dbTraffic_index].Email]
  1683. if !ok {
  1684. continue
  1685. }
  1686. dbClientTraffics[dbTraffic_index].Up += t.Up
  1687. dbClientTraffics[dbTraffic_index].Down += t.Down
  1688. dbClientTraffics[dbTraffic_index].AllTime += t.Up + t.Down
  1689. if t.Up+t.Down > 0 {
  1690. onlineClients = append(onlineClients, t.Email)
  1691. dbClientTraffics[dbTraffic_index].LastOnline = now
  1692. }
  1693. }
  1694. // Set onlineUsers
  1695. p.SetOnlineClients(onlineClients)
  1696. err = tx.Save(dbClientTraffics).Error
  1697. if err != nil {
  1698. logger.Warning("AddClientTraffic update data ", err)
  1699. }
  1700. return nil
  1701. }
  1702. func (s *InboundService) adjustTraffics(tx *gorm.DB, dbClientTraffics []*xray.ClientTraffic) ([]*xray.ClientTraffic, error) {
  1703. inboundIds := make([]int, 0, len(dbClientTraffics))
  1704. for _, dbClientTraffic := range dbClientTraffics {
  1705. if dbClientTraffic.ExpiryTime < 0 {
  1706. inboundIds = append(inboundIds, dbClientTraffic.InboundId)
  1707. }
  1708. }
  1709. if len(inboundIds) > 0 {
  1710. var inbounds []*model.Inbound
  1711. err := tx.Model(model.Inbound{}).Where("id IN (?)", inboundIds).Find(&inbounds).Error
  1712. if err != nil {
  1713. return nil, err
  1714. }
  1715. for inbound_index := range inbounds {
  1716. settings := map[string]any{}
  1717. json.Unmarshal([]byte(inbounds[inbound_index].Settings), &settings)
  1718. clients, ok := settings["clients"].([]any)
  1719. if ok {
  1720. var newClients []any
  1721. for client_index := range clients {
  1722. c := clients[client_index].(map[string]any)
  1723. for traffic_index := range dbClientTraffics {
  1724. if dbClientTraffics[traffic_index].ExpiryTime < 0 && c["email"] == dbClientTraffics[traffic_index].Email {
  1725. oldExpiryTime := c["expiryTime"].(float64)
  1726. newExpiryTime := (time.Now().Unix() * 1000) - int64(oldExpiryTime)
  1727. c["expiryTime"] = newExpiryTime
  1728. c["updated_at"] = time.Now().Unix() * 1000
  1729. dbClientTraffics[traffic_index].ExpiryTime = newExpiryTime
  1730. break
  1731. }
  1732. }
  1733. // Backfill created_at and updated_at
  1734. if _, ok := c["created_at"]; !ok {
  1735. c["created_at"] = time.Now().Unix() * 1000
  1736. }
  1737. c["updated_at"] = time.Now().Unix() * 1000
  1738. newClients = append(newClients, any(c))
  1739. }
  1740. settings["clients"] = newClients
  1741. modifiedSettings, err := json.MarshalIndent(settings, "", " ")
  1742. if err != nil {
  1743. return nil, err
  1744. }
  1745. inbounds[inbound_index].Settings = string(modifiedSettings)
  1746. }
  1747. }
  1748. err = tx.Save(inbounds).Error
  1749. if err != nil {
  1750. logger.Warning("AddClientTraffic update inbounds ", err)
  1751. logger.Error(inbounds)
  1752. }
  1753. }
  1754. return dbClientTraffics, nil
  1755. }
  1756. func (s *InboundService) autoRenewClients(tx *gorm.DB) (bool, int64, error) {
  1757. // check for time expired
  1758. var traffics []*xray.ClientTraffic
  1759. now := time.Now().Unix() * 1000
  1760. var err, err1 error
  1761. err = tx.Model(xray.ClientTraffic{}).Where("reset > 0 and expiry_time > 0 and expiry_time <= ?", now).Find(&traffics).Error
  1762. if err != nil {
  1763. return false, 0, err
  1764. }
  1765. // return if there is no client to renew
  1766. if len(traffics) == 0 {
  1767. return false, 0, nil
  1768. }
  1769. var inbound_ids []int
  1770. var inbounds []*model.Inbound
  1771. needRestart := false
  1772. var clientsToAdd []struct {
  1773. protocol string
  1774. tag string
  1775. client map[string]any
  1776. }
  1777. for _, traffic := range traffics {
  1778. inbound_ids = append(inbound_ids, traffic.InboundId)
  1779. }
  1780. // Dedupe so an inbound hosting N expired clients is fetched and saved once
  1781. // per tick instead of N times across chunk boundaries.
  1782. inbound_ids = uniqueInts(inbound_ids)
  1783. // Chunked to stay under SQLite's bind-variable limit when many inbounds
  1784. // are touched in a single tick.
  1785. for _, batch := range chunkInts(inbound_ids, sqliteMaxVars) {
  1786. var page []*model.Inbound
  1787. if err = tx.Model(model.Inbound{}).Where("id IN ?", batch).Find(&page).Error; err != nil {
  1788. return false, 0, err
  1789. }
  1790. inbounds = append(inbounds, page...)
  1791. }
  1792. for inbound_index := range inbounds {
  1793. settings := map[string]any{}
  1794. json.Unmarshal([]byte(inbounds[inbound_index].Settings), &settings)
  1795. clients := settings["clients"].([]any)
  1796. for client_index := range clients {
  1797. c := clients[client_index].(map[string]any)
  1798. for traffic_index, traffic := range traffics {
  1799. if traffic.Email == c["email"].(string) {
  1800. newExpiryTime := traffic.ExpiryTime
  1801. for newExpiryTime < now {
  1802. newExpiryTime += (int64(traffic.Reset) * 86400000)
  1803. }
  1804. c["expiryTime"] = newExpiryTime
  1805. traffics[traffic_index].ExpiryTime = newExpiryTime
  1806. traffics[traffic_index].Down = 0
  1807. traffics[traffic_index].Up = 0
  1808. if !traffic.Enable {
  1809. traffics[traffic_index].Enable = true
  1810. clientsToAdd = append(clientsToAdd,
  1811. struct {
  1812. protocol string
  1813. tag string
  1814. client map[string]any
  1815. }{
  1816. protocol: string(inbounds[inbound_index].Protocol),
  1817. tag: inbounds[inbound_index].Tag,
  1818. client: c,
  1819. })
  1820. }
  1821. clients[client_index] = any(c)
  1822. break
  1823. }
  1824. }
  1825. }
  1826. settings["clients"] = clients
  1827. newSettings, err := json.MarshalIndent(settings, "", " ")
  1828. if err != nil {
  1829. return false, 0, err
  1830. }
  1831. inbounds[inbound_index].Settings = string(newSettings)
  1832. }
  1833. err = tx.Save(inbounds).Error
  1834. if err != nil {
  1835. return false, 0, err
  1836. }
  1837. err = tx.Save(traffics).Error
  1838. if err != nil {
  1839. return false, 0, err
  1840. }
  1841. if p != nil {
  1842. err1 = s.xrayApi.Init(p.GetAPIPort())
  1843. if err1 != nil {
  1844. return true, int64(len(traffics)), nil
  1845. }
  1846. for _, clientToAdd := range clientsToAdd {
  1847. err1 = s.xrayApi.AddUser(clientToAdd.protocol, clientToAdd.tag, clientToAdd.client)
  1848. if err1 != nil {
  1849. needRestart = true
  1850. }
  1851. }
  1852. s.xrayApi.Close()
  1853. }
  1854. return needRestart, int64(len(traffics)), nil
  1855. }
  1856. func (s *InboundService) disableInvalidInbounds(tx *gorm.DB) (bool, int64, error) {
  1857. now := time.Now().Unix() * 1000
  1858. needRestart := false
  1859. if p != nil {
  1860. var tags []string
  1861. err := tx.Table("inbounds").
  1862. Select("inbounds.tag").
  1863. Where("((total > 0 and up + down >= total) or (expiry_time > 0 and expiry_time <= ?)) and enable = ?", now, true).
  1864. Scan(&tags).Error
  1865. if err != nil {
  1866. return false, 0, err
  1867. }
  1868. s.xrayApi.Init(p.GetAPIPort())
  1869. for _, tag := range tags {
  1870. err1 := s.xrayApi.DelInbound(tag)
  1871. if err1 == nil {
  1872. logger.Debug("Inbound disabled by api:", tag)
  1873. } else {
  1874. logger.Debug("Error in disabling inbound by api:", err1)
  1875. needRestart = true
  1876. }
  1877. }
  1878. s.xrayApi.Close()
  1879. }
  1880. result := tx.Model(model.Inbound{}).
  1881. Where("((total > 0 and up + down >= total) or (expiry_time > 0 and expiry_time <= ?)) and enable = ?", now, true).
  1882. Update("enable", false)
  1883. err := result.Error
  1884. count := result.RowsAffected
  1885. return needRestart, count, err
  1886. }
  1887. func (s *InboundService) disableInvalidClients(tx *gorm.DB) (bool, int64, error) {
  1888. now := time.Now().Unix() * 1000
  1889. needRestart := false
  1890. var depletedRows []xray.ClientTraffic
  1891. err := tx.Model(xray.ClientTraffic{}).
  1892. Where("((total > 0 AND up + down >= total) OR (expiry_time > 0 AND expiry_time <= ?)) AND enable = ?", now, true).
  1893. Find(&depletedRows).Error
  1894. if err != nil {
  1895. return false, 0, err
  1896. }
  1897. if len(depletedRows) == 0 {
  1898. return false, 0, nil
  1899. }
  1900. rowByEmail := make(map[string]*xray.ClientTraffic, len(depletedRows))
  1901. depletedEmails := make([]string, 0, len(depletedRows))
  1902. for i := range depletedRows {
  1903. if depletedRows[i].Email == "" {
  1904. continue
  1905. }
  1906. rowByEmail[strings.ToLower(depletedRows[i].Email)] = &depletedRows[i]
  1907. depletedEmails = append(depletedEmails, depletedRows[i].Email)
  1908. }
  1909. // Resolve inbound membership only for the depleted emails — pushing the
  1910. // filter into SQLite avoids dragging every panel client through Go for
  1911. // the common case where most clients are healthy.
  1912. var memberships []struct {
  1913. InboundId int
  1914. Tag string
  1915. Email string
  1916. SubID string `gorm:"column:sub_id"`
  1917. }
  1918. if len(depletedEmails) > 0 {
  1919. err = tx.Raw(`
  1920. SELECT inbounds.id AS inbound_id,
  1921. inbounds.tag AS tag,
  1922. JSON_EXTRACT(client.value, '$.email') AS email,
  1923. JSON_EXTRACT(client.value, '$.subId') AS sub_id
  1924. FROM inbounds,
  1925. JSON_EACH(JSON_EXTRACT(inbounds.settings, '$.clients')) AS client
  1926. WHERE LOWER(JSON_EXTRACT(client.value, '$.email')) IN ?
  1927. `, lowerAll(depletedEmails)).Scan(&memberships).Error
  1928. if err != nil {
  1929. return false, 0, err
  1930. }
  1931. }
  1932. // Discover the row holder's subId per email. Only siblings sharing it
  1933. // get cascaded; legacy data where two identities reuse the same email
  1934. // stays isolated to the row owner.
  1935. holderSub := make(map[string]string, len(rowByEmail))
  1936. for _, m := range memberships {
  1937. email := strings.ToLower(strings.Trim(m.Email, "\""))
  1938. row, ok := rowByEmail[email]
  1939. if !ok || m.InboundId != row.InboundId {
  1940. continue
  1941. }
  1942. holderSub[email] = strings.Trim(m.SubID, "\"")
  1943. }
  1944. type target struct {
  1945. InboundId int
  1946. Tag string
  1947. Email string
  1948. }
  1949. var targets []target
  1950. for _, m := range memberships {
  1951. email := strings.ToLower(strings.Trim(m.Email, "\""))
  1952. row, ok := rowByEmail[email]
  1953. if !ok {
  1954. continue
  1955. }
  1956. expected, hasSub := holderSub[email]
  1957. mSub := strings.Trim(m.SubID, "\"")
  1958. switch {
  1959. case !hasSub || expected == "":
  1960. if m.InboundId != row.InboundId {
  1961. continue
  1962. }
  1963. case mSub != expected:
  1964. continue
  1965. }
  1966. targets = append(targets, target{
  1967. InboundId: m.InboundId,
  1968. Tag: m.Tag,
  1969. Email: strings.Trim(m.Email, "\""),
  1970. })
  1971. }
  1972. if p != nil && len(targets) > 0 {
  1973. s.xrayApi.Init(p.GetAPIPort())
  1974. for _, t := range targets {
  1975. err1 := s.xrayApi.RemoveUser(t.Tag, t.Email)
  1976. if err1 == nil {
  1977. logger.Debug("Client disabled by api:", t.Email)
  1978. } else if strings.Contains(err1.Error(), fmt.Sprintf("User %s not found.", t.Email)) {
  1979. logger.Debug("User is already disabled. Nothing to do more...")
  1980. } else {
  1981. logger.Debug("Error in disabling client by api:", err1)
  1982. needRestart = true
  1983. }
  1984. }
  1985. s.xrayApi.Close()
  1986. }
  1987. result := tx.Model(xray.ClientTraffic{}).
  1988. Where("((total > 0 and up + down >= total) or (expiry_time > 0 and expiry_time <= ?)) and enable = ?", now, true).
  1989. Update("enable", false)
  1990. err = result.Error
  1991. count := result.RowsAffected
  1992. if err != nil {
  1993. return needRestart, count, err
  1994. }
  1995. if len(targets) == 0 {
  1996. return needRestart, count, nil
  1997. }
  1998. // Mirror enable=false + the row's authoritative quota/expiry into every
  1999. // (inbound, email) we just removed via the API.
  2000. inboundEmailMap := make(map[int]map[string]struct{})
  2001. for _, t := range targets {
  2002. if inboundEmailMap[t.InboundId] == nil {
  2003. inboundEmailMap[t.InboundId] = make(map[string]struct{})
  2004. }
  2005. inboundEmailMap[t.InboundId][t.Email] = struct{}{}
  2006. }
  2007. inboundIds := make([]int, 0, len(inboundEmailMap))
  2008. for id := range inboundEmailMap {
  2009. inboundIds = append(inboundIds, id)
  2010. }
  2011. var inbounds []*model.Inbound
  2012. if err = tx.Model(model.Inbound{}).Where("id IN ?", inboundIds).Find(&inbounds).Error; err != nil {
  2013. logger.Warning("disableInvalidClients fetch inbounds:", err)
  2014. return needRestart, count, nil
  2015. }
  2016. dirty := make([]*model.Inbound, 0, len(inbounds))
  2017. for _, inbound := range inbounds {
  2018. settings := map[string]any{}
  2019. if jsonErr := json.Unmarshal([]byte(inbound.Settings), &settings); jsonErr != nil {
  2020. continue
  2021. }
  2022. clientsRaw, ok := settings["clients"].([]any)
  2023. if !ok {
  2024. continue
  2025. }
  2026. emailSet := inboundEmailMap[inbound.Id]
  2027. changed := false
  2028. for i := range clientsRaw {
  2029. c, ok := clientsRaw[i].(map[string]any)
  2030. if !ok {
  2031. continue
  2032. }
  2033. email, _ := c["email"].(string)
  2034. if _, shouldDisable := emailSet[email]; !shouldDisable {
  2035. continue
  2036. }
  2037. c["enable"] = false
  2038. if row, ok := rowByEmail[strings.ToLower(email)]; ok {
  2039. c["totalGB"] = row.Total
  2040. c["expiryTime"] = row.ExpiryTime
  2041. }
  2042. c["updated_at"] = now
  2043. clientsRaw[i] = c
  2044. changed = true
  2045. }
  2046. if !changed {
  2047. continue
  2048. }
  2049. settings["clients"] = clientsRaw
  2050. modifiedSettings, jsonErr := json.MarshalIndent(settings, "", " ")
  2051. if jsonErr != nil {
  2052. continue
  2053. }
  2054. inbound.Settings = string(modifiedSettings)
  2055. dirty = append(dirty, inbound)
  2056. }
  2057. if len(dirty) > 0 {
  2058. if err = tx.Save(dirty).Error; err != nil {
  2059. logger.Warning("disableInvalidClients update inbound settings:", err)
  2060. }
  2061. }
  2062. return needRestart, count, nil
  2063. }
  2064. func (s *InboundService) GetInboundTags() (string, error) {
  2065. db := database.GetDB()
  2066. var inboundTags []string
  2067. err := db.Model(model.Inbound{}).Select("tag").Find(&inboundTags).Error
  2068. if err != nil && err != gorm.ErrRecordNotFound {
  2069. return "", err
  2070. }
  2071. tags, _ := json.Marshal(inboundTags)
  2072. return string(tags), nil
  2073. }
  2074. func (s *InboundService) GetClientReverseTags() (string, error) {
  2075. db := database.GetDB()
  2076. var inbounds []model.Inbound
  2077. err := db.Model(model.Inbound{}).Select("settings").Where("protocol = ?", "vless").Find(&inbounds).Error
  2078. if err != nil && err != gorm.ErrRecordNotFound {
  2079. return "[]", err
  2080. }
  2081. tagSet := make(map[string]struct{})
  2082. for _, inbound := range inbounds {
  2083. var settings map[string]any
  2084. if err := json.Unmarshal([]byte(inbound.Settings), &settings); err != nil {
  2085. continue
  2086. }
  2087. clients, ok := settings["clients"].([]any)
  2088. if !ok {
  2089. continue
  2090. }
  2091. for _, client := range clients {
  2092. clientMap, ok := client.(map[string]any)
  2093. if !ok {
  2094. continue
  2095. }
  2096. reverse, ok := clientMap["reverse"].(map[string]any)
  2097. if !ok {
  2098. continue
  2099. }
  2100. tag, _ := reverse["tag"].(string)
  2101. tag = strings.TrimSpace(tag)
  2102. if tag != "" {
  2103. tagSet[tag] = struct{}{}
  2104. }
  2105. }
  2106. }
  2107. rawTags := make([]string, 0, len(tagSet))
  2108. for tag := range tagSet {
  2109. rawTags = append(rawTags, tag)
  2110. }
  2111. sort.Strings(rawTags)
  2112. result, _ := json.Marshal(rawTags)
  2113. return string(result), nil
  2114. }
  2115. func (s *InboundService) MigrationRemoveOrphanedTraffics() {
  2116. db := database.GetDB()
  2117. db.Exec(`
  2118. DELETE FROM client_traffics
  2119. WHERE email NOT IN (
  2120. SELECT JSON_EXTRACT(client.value, '$.email')
  2121. FROM inbounds,
  2122. JSON_EACH(JSON_EXTRACT(inbounds.settings, '$.clients')) AS client
  2123. )
  2124. `)
  2125. }
  2126. // AddClientStat inserts a per-client accounting row, no-op on email
  2127. // conflict. Xray reports traffic per email, so the surviving row acts as
  2128. // the shared accumulator for inbounds that re-use the same identity.
  2129. func (s *InboundService) AddClientStat(tx *gorm.DB, inboundId int, client *model.Client) error {
  2130. clientTraffic := xray.ClientTraffic{
  2131. InboundId: inboundId,
  2132. Email: client.Email,
  2133. Total: client.TotalGB,
  2134. ExpiryTime: client.ExpiryTime,
  2135. Enable: client.Enable,
  2136. Reset: client.Reset,
  2137. }
  2138. return tx.Clauses(clause.OnConflict{Columns: []clause.Column{{Name: "email"}}, DoNothing: true}).
  2139. Create(&clientTraffic).Error
  2140. }
  2141. func (s *InboundService) UpdateClientStat(tx *gorm.DB, email string, client *model.Client) error {
  2142. result := tx.Model(xray.ClientTraffic{}).
  2143. Where("email = ?", email).
  2144. Updates(map[string]any{
  2145. "enable": client.Enable,
  2146. "email": client.Email,
  2147. "total": client.TotalGB,
  2148. "expiry_time": client.ExpiryTime,
  2149. "reset": client.Reset,
  2150. })
  2151. err := result.Error
  2152. return err
  2153. }
  2154. func (s *InboundService) UpdateClientIPs(tx *gorm.DB, oldEmail string, newEmail string) error {
  2155. return tx.Model(model.InboundClientIps{}).Where("client_email = ?", oldEmail).Update("client_email", newEmail).Error
  2156. }
  2157. func (s *InboundService) DelClientStat(tx *gorm.DB, email string) error {
  2158. return tx.Where("email = ?", email).Delete(xray.ClientTraffic{}).Error
  2159. }
  2160. func (s *InboundService) DelClientIPs(tx *gorm.DB, email string) error {
  2161. return tx.Where("client_email = ?", email).Delete(model.InboundClientIps{}).Error
  2162. }
  2163. func (s *InboundService) GetClientInboundByTrafficID(trafficId int) (traffic *xray.ClientTraffic, inbound *model.Inbound, err error) {
  2164. db := database.GetDB()
  2165. var traffics []*xray.ClientTraffic
  2166. err = db.Model(xray.ClientTraffic{}).Where("id = ?", trafficId).Find(&traffics).Error
  2167. if err != nil {
  2168. logger.Warningf("Error retrieving ClientTraffic with trafficId %d: %v", trafficId, err)
  2169. return nil, nil, err
  2170. }
  2171. if len(traffics) > 0 {
  2172. inbound, err = s.GetInbound(traffics[0].InboundId)
  2173. return traffics[0], inbound, err
  2174. }
  2175. return nil, nil, nil
  2176. }
  2177. func (s *InboundService) GetClientInboundByEmail(email string) (traffic *xray.ClientTraffic, inbound *model.Inbound, err error) {
  2178. db := database.GetDB()
  2179. var traffics []*xray.ClientTraffic
  2180. err = db.Model(xray.ClientTraffic{}).Where("email = ?", email).Find(&traffics).Error
  2181. if err != nil {
  2182. logger.Warningf("Error retrieving ClientTraffic with email %s: %v", email, err)
  2183. return nil, nil, err
  2184. }
  2185. if len(traffics) > 0 {
  2186. inbound, err = s.GetInbound(traffics[0].InboundId)
  2187. return traffics[0], inbound, err
  2188. }
  2189. return nil, nil, nil
  2190. }
  2191. func (s *InboundService) GetClientByEmail(clientEmail string) (*xray.ClientTraffic, *model.Client, error) {
  2192. traffic, inbound, err := s.GetClientInboundByEmail(clientEmail)
  2193. if err != nil {
  2194. return nil, nil, err
  2195. }
  2196. if inbound == nil {
  2197. return nil, nil, common.NewError("Inbound Not Found For Email:", clientEmail)
  2198. }
  2199. clients, err := s.GetClients(inbound)
  2200. if err != nil {
  2201. return nil, nil, err
  2202. }
  2203. for _, client := range clients {
  2204. if client.Email == clientEmail {
  2205. return traffic, &client, nil
  2206. }
  2207. }
  2208. return nil, nil, common.NewError("Client Not Found In Inbound For Email:", clientEmail)
  2209. }
  2210. func (s *InboundService) SetClientTelegramUserID(trafficId int, tgId int64) (bool, error) {
  2211. traffic, inbound, err := s.GetClientInboundByTrafficID(trafficId)
  2212. if err != nil {
  2213. return false, err
  2214. }
  2215. if inbound == nil {
  2216. return false, common.NewError("Inbound Not Found For Traffic ID:", trafficId)
  2217. }
  2218. clientEmail := traffic.Email
  2219. oldClients, err := s.GetClients(inbound)
  2220. if err != nil {
  2221. return false, err
  2222. }
  2223. clientId := ""
  2224. for _, oldClient := range oldClients {
  2225. if oldClient.Email == clientEmail {
  2226. switch inbound.Protocol {
  2227. case "trojan":
  2228. clientId = oldClient.Password
  2229. case "shadowsocks":
  2230. clientId = oldClient.Email
  2231. default:
  2232. clientId = oldClient.ID
  2233. }
  2234. break
  2235. }
  2236. }
  2237. if len(clientId) == 0 {
  2238. return false, common.NewError("Client Not Found For Email:", clientEmail)
  2239. }
  2240. var settings map[string]any
  2241. err = json.Unmarshal([]byte(inbound.Settings), &settings)
  2242. if err != nil {
  2243. return false, err
  2244. }
  2245. clients := settings["clients"].([]any)
  2246. var newClients []any
  2247. for client_index := range clients {
  2248. c := clients[client_index].(map[string]any)
  2249. if c["email"] == clientEmail {
  2250. c["tgId"] = tgId
  2251. c["updated_at"] = time.Now().Unix() * 1000
  2252. newClients = append(newClients, any(c))
  2253. }
  2254. }
  2255. settings["clients"] = newClients
  2256. modifiedSettings, err := json.MarshalIndent(settings, "", " ")
  2257. if err != nil {
  2258. return false, err
  2259. }
  2260. inbound.Settings = string(modifiedSettings)
  2261. needRestart, err := s.UpdateInboundClient(inbound, clientId)
  2262. return needRestart, err
  2263. }
  2264. func (s *InboundService) checkIsEnabledByEmail(clientEmail string) (bool, error) {
  2265. _, inbound, err := s.GetClientInboundByEmail(clientEmail)
  2266. if err != nil {
  2267. return false, err
  2268. }
  2269. if inbound == nil {
  2270. return false, common.NewError("Inbound Not Found For Email:", clientEmail)
  2271. }
  2272. clients, err := s.GetClients(inbound)
  2273. if err != nil {
  2274. return false, err
  2275. }
  2276. isEnable := false
  2277. for _, client := range clients {
  2278. if client.Email == clientEmail {
  2279. isEnable = client.Enable
  2280. break
  2281. }
  2282. }
  2283. return isEnable, err
  2284. }
  2285. func (s *InboundService) ToggleClientEnableByEmail(clientEmail string) (bool, bool, error) {
  2286. _, inbound, err := s.GetClientInboundByEmail(clientEmail)
  2287. if err != nil {
  2288. return false, false, err
  2289. }
  2290. if inbound == nil {
  2291. return false, false, common.NewError("Inbound Not Found For Email:", clientEmail)
  2292. }
  2293. oldClients, err := s.GetClients(inbound)
  2294. if err != nil {
  2295. return false, false, err
  2296. }
  2297. clientId := ""
  2298. clientOldEnabled := false
  2299. for _, oldClient := range oldClients {
  2300. if oldClient.Email == clientEmail {
  2301. switch inbound.Protocol {
  2302. case "trojan":
  2303. clientId = oldClient.Password
  2304. case "shadowsocks":
  2305. clientId = oldClient.Email
  2306. default:
  2307. clientId = oldClient.ID
  2308. }
  2309. clientOldEnabled = oldClient.Enable
  2310. break
  2311. }
  2312. }
  2313. if len(clientId) == 0 {
  2314. return false, false, common.NewError("Client Not Found For Email:", clientEmail)
  2315. }
  2316. var settings map[string]any
  2317. err = json.Unmarshal([]byte(inbound.Settings), &settings)
  2318. if err != nil {
  2319. return false, false, err
  2320. }
  2321. clients := settings["clients"].([]any)
  2322. var newClients []any
  2323. for client_index := range clients {
  2324. c := clients[client_index].(map[string]any)
  2325. if c["email"] == clientEmail {
  2326. c["enable"] = !clientOldEnabled
  2327. c["updated_at"] = time.Now().Unix() * 1000
  2328. newClients = append(newClients, any(c))
  2329. }
  2330. }
  2331. settings["clients"] = newClients
  2332. modifiedSettings, err := json.MarshalIndent(settings, "", " ")
  2333. if err != nil {
  2334. return false, false, err
  2335. }
  2336. inbound.Settings = string(modifiedSettings)
  2337. needRestart, err := s.UpdateInboundClient(inbound, clientId)
  2338. if err != nil {
  2339. return false, needRestart, err
  2340. }
  2341. return !clientOldEnabled, needRestart, nil
  2342. }
  2343. // SetClientEnableByEmail sets client enable state to desired value; returns (changed, needRestart, error)
  2344. func (s *InboundService) SetClientEnableByEmail(clientEmail string, enable bool) (bool, bool, error) {
  2345. current, err := s.checkIsEnabledByEmail(clientEmail)
  2346. if err != nil {
  2347. return false, false, err
  2348. }
  2349. if current == enable {
  2350. return false, false, nil
  2351. }
  2352. newEnabled, needRestart, err := s.ToggleClientEnableByEmail(clientEmail)
  2353. if err != nil {
  2354. return false, needRestart, err
  2355. }
  2356. return newEnabled == enable, needRestart, nil
  2357. }
  2358. func (s *InboundService) ResetClientIpLimitByEmail(clientEmail string, count int) (bool, error) {
  2359. _, inbound, err := s.GetClientInboundByEmail(clientEmail)
  2360. if err != nil {
  2361. return false, err
  2362. }
  2363. if inbound == nil {
  2364. return false, common.NewError("Inbound Not Found For Email:", clientEmail)
  2365. }
  2366. oldClients, err := s.GetClients(inbound)
  2367. if err != nil {
  2368. return false, err
  2369. }
  2370. clientId := ""
  2371. for _, oldClient := range oldClients {
  2372. if oldClient.Email == clientEmail {
  2373. switch inbound.Protocol {
  2374. case "trojan":
  2375. clientId = oldClient.Password
  2376. case "shadowsocks":
  2377. clientId = oldClient.Email
  2378. default:
  2379. clientId = oldClient.ID
  2380. }
  2381. break
  2382. }
  2383. }
  2384. if len(clientId) == 0 {
  2385. return false, common.NewError("Client Not Found For Email:", clientEmail)
  2386. }
  2387. var settings map[string]any
  2388. err = json.Unmarshal([]byte(inbound.Settings), &settings)
  2389. if err != nil {
  2390. return false, err
  2391. }
  2392. clients := settings["clients"].([]any)
  2393. var newClients []any
  2394. for client_index := range clients {
  2395. c := clients[client_index].(map[string]any)
  2396. if c["email"] == clientEmail {
  2397. c["limitIp"] = count
  2398. c["updated_at"] = time.Now().Unix() * 1000
  2399. newClients = append(newClients, any(c))
  2400. }
  2401. }
  2402. settings["clients"] = newClients
  2403. modifiedSettings, err := json.MarshalIndent(settings, "", " ")
  2404. if err != nil {
  2405. return false, err
  2406. }
  2407. inbound.Settings = string(modifiedSettings)
  2408. needRestart, err := s.UpdateInboundClient(inbound, clientId)
  2409. return needRestart, err
  2410. }
  2411. func (s *InboundService) ResetClientExpiryTimeByEmail(clientEmail string, expiry_time int64) (bool, error) {
  2412. _, inbound, err := s.GetClientInboundByEmail(clientEmail)
  2413. if err != nil {
  2414. return false, err
  2415. }
  2416. if inbound == nil {
  2417. return false, common.NewError("Inbound Not Found For Email:", clientEmail)
  2418. }
  2419. oldClients, err := s.GetClients(inbound)
  2420. if err != nil {
  2421. return false, err
  2422. }
  2423. clientId := ""
  2424. for _, oldClient := range oldClients {
  2425. if oldClient.Email == clientEmail {
  2426. switch inbound.Protocol {
  2427. case "trojan":
  2428. clientId = oldClient.Password
  2429. case "shadowsocks":
  2430. clientId = oldClient.Email
  2431. default:
  2432. clientId = oldClient.ID
  2433. }
  2434. break
  2435. }
  2436. }
  2437. if len(clientId) == 0 {
  2438. return false, common.NewError("Client Not Found For Email:", clientEmail)
  2439. }
  2440. var settings map[string]any
  2441. err = json.Unmarshal([]byte(inbound.Settings), &settings)
  2442. if err != nil {
  2443. return false, err
  2444. }
  2445. clients := settings["clients"].([]any)
  2446. var newClients []any
  2447. for client_index := range clients {
  2448. c := clients[client_index].(map[string]any)
  2449. if c["email"] == clientEmail {
  2450. c["expiryTime"] = expiry_time
  2451. c["updated_at"] = time.Now().Unix() * 1000
  2452. newClients = append(newClients, any(c))
  2453. }
  2454. }
  2455. settings["clients"] = newClients
  2456. modifiedSettings, err := json.MarshalIndent(settings, "", " ")
  2457. if err != nil {
  2458. return false, err
  2459. }
  2460. inbound.Settings = string(modifiedSettings)
  2461. needRestart, err := s.UpdateInboundClient(inbound, clientId)
  2462. return needRestart, err
  2463. }
  2464. func (s *InboundService) ResetClientTrafficLimitByEmail(clientEmail string, totalGB int) (bool, error) {
  2465. if totalGB < 0 {
  2466. return false, common.NewError("totalGB must be >= 0")
  2467. }
  2468. _, inbound, err := s.GetClientInboundByEmail(clientEmail)
  2469. if err != nil {
  2470. return false, err
  2471. }
  2472. if inbound == nil {
  2473. return false, common.NewError("Inbound Not Found For Email:", clientEmail)
  2474. }
  2475. oldClients, err := s.GetClients(inbound)
  2476. if err != nil {
  2477. return false, err
  2478. }
  2479. clientId := ""
  2480. for _, oldClient := range oldClients {
  2481. if oldClient.Email == clientEmail {
  2482. switch inbound.Protocol {
  2483. case "trojan":
  2484. clientId = oldClient.Password
  2485. case "shadowsocks":
  2486. clientId = oldClient.Email
  2487. default:
  2488. clientId = oldClient.ID
  2489. }
  2490. break
  2491. }
  2492. }
  2493. if len(clientId) == 0 {
  2494. return false, common.NewError("Client Not Found For Email:", clientEmail)
  2495. }
  2496. var settings map[string]any
  2497. err = json.Unmarshal([]byte(inbound.Settings), &settings)
  2498. if err != nil {
  2499. return false, err
  2500. }
  2501. clients := settings["clients"].([]any)
  2502. var newClients []any
  2503. for client_index := range clients {
  2504. c := clients[client_index].(map[string]any)
  2505. if c["email"] == clientEmail {
  2506. c["totalGB"] = totalGB * 1024 * 1024 * 1024
  2507. c["updated_at"] = time.Now().Unix() * 1000
  2508. newClients = append(newClients, any(c))
  2509. }
  2510. }
  2511. settings["clients"] = newClients
  2512. modifiedSettings, err := json.MarshalIndent(settings, "", " ")
  2513. if err != nil {
  2514. return false, err
  2515. }
  2516. inbound.Settings = string(modifiedSettings)
  2517. needRestart, err := s.UpdateInboundClient(inbound, clientId)
  2518. return needRestart, err
  2519. }
  2520. func (s *InboundService) ResetClientTrafficByEmail(clientEmail string) error {
  2521. db := database.GetDB()
  2522. // Reset traffic stats in ClientTraffic table
  2523. result := db.Model(xray.ClientTraffic{}).
  2524. Where("email = ?", clientEmail).
  2525. Updates(map[string]any{"enable": true, "up": 0, "down": 0})
  2526. err := result.Error
  2527. if err != nil {
  2528. return err
  2529. }
  2530. return nil
  2531. }
  2532. func (s *InboundService) ResetClientTraffic(id int, clientEmail string) (bool, error) {
  2533. needRestart := false
  2534. traffic, err := s.GetClientTrafficByEmail(clientEmail)
  2535. if err != nil {
  2536. return false, err
  2537. }
  2538. if !traffic.Enable {
  2539. inbound, err := s.GetInbound(id)
  2540. if err != nil {
  2541. return false, err
  2542. }
  2543. clients, err := s.GetClients(inbound)
  2544. if err != nil {
  2545. return false, err
  2546. }
  2547. for _, client := range clients {
  2548. if client.Email == clientEmail && client.Enable {
  2549. rt, rterr := s.runtimeFor(inbound)
  2550. if rterr != nil {
  2551. if inbound.NodeID != nil {
  2552. return false, rterr
  2553. }
  2554. needRestart = true
  2555. break
  2556. }
  2557. cipher := ""
  2558. if string(inbound.Protocol) == "shadowsocks" {
  2559. var oldSettings map[string]any
  2560. err = json.Unmarshal([]byte(inbound.Settings), &oldSettings)
  2561. if err != nil {
  2562. return false, err
  2563. }
  2564. cipher = oldSettings["method"].(string)
  2565. }
  2566. err1 := rt.AddUser(context.Background(), inbound, map[string]any{
  2567. "email": client.Email,
  2568. "id": client.ID,
  2569. "auth": client.Auth,
  2570. "security": client.Security,
  2571. "flow": client.Flow,
  2572. "password": client.Password,
  2573. "cipher": cipher,
  2574. })
  2575. if err1 == nil {
  2576. logger.Debug("Client enabled on", rt.Name(), "due to reset traffic:", clientEmail)
  2577. } else {
  2578. logger.Debug("Error in enabling client on", rt.Name(), ":", err1)
  2579. needRestart = true
  2580. }
  2581. break
  2582. }
  2583. }
  2584. }
  2585. traffic.Up = 0
  2586. traffic.Down = 0
  2587. traffic.Enable = true
  2588. db := database.GetDB()
  2589. err = db.Save(traffic).Error
  2590. if err != nil {
  2591. return false, err
  2592. }
  2593. // Stamp last_traffic_reset_time on the parent inbound so the next
  2594. // NodeTrafficSyncJob tick honours the grace window and doesn't pull
  2595. // the pre-reset absolute back from the node.
  2596. now := time.Now().UnixMilli()
  2597. _ = db.Model(model.Inbound{}).
  2598. Where("id = ?", id).
  2599. Update("last_traffic_reset_time", now).Error
  2600. // Propagate to the remote node if this inbound is node-managed.
  2601. // Best-effort: an offline node shouldn't block a user-driven reset
  2602. // — the central DB is already zeroed and the next successful sync
  2603. // (within the grace window) will re-pull whatever the node has.
  2604. inbound, err := s.GetInbound(id)
  2605. if err == nil && inbound != nil && inbound.NodeID != nil {
  2606. if rt, rterr := s.runtimeFor(inbound); rterr == nil {
  2607. if e := rt.ResetClientTraffic(context.Background(), inbound, clientEmail); e != nil {
  2608. logger.Warning("ResetClientTraffic: remote propagation to", rt.Name(), "failed:", e)
  2609. }
  2610. } else {
  2611. logger.Warning("ResetClientTraffic: runtime lookup failed:", rterr)
  2612. }
  2613. }
  2614. return needRestart, nil
  2615. }
  2616. func (s *InboundService) ResetAllClientTraffics(id int) error {
  2617. db := database.GetDB()
  2618. now := time.Now().Unix() * 1000
  2619. if err := db.Transaction(func(tx *gorm.DB) error {
  2620. whereText := "inbound_id "
  2621. if id == -1 {
  2622. whereText += " > ?"
  2623. } else {
  2624. whereText += " = ?"
  2625. }
  2626. // Reset client traffics
  2627. result := tx.Model(xray.ClientTraffic{}).
  2628. Where(whereText, id).
  2629. Updates(map[string]any{"enable": true, "up": 0, "down": 0})
  2630. if result.Error != nil {
  2631. return result.Error
  2632. }
  2633. // Update lastTrafficResetTime for the inbound(s)
  2634. inboundWhereText := "id "
  2635. if id == -1 {
  2636. inboundWhereText += " > ?"
  2637. } else {
  2638. inboundWhereText += " = ?"
  2639. }
  2640. result = tx.Model(model.Inbound{}).
  2641. Where(inboundWhereText, id).
  2642. Update("last_traffic_reset_time", now)
  2643. return result.Error
  2644. }); err != nil {
  2645. return err
  2646. }
  2647. // Propagate to remote nodes after the central DB is settled. Single
  2648. // inbound: one rt.ResetInboundClientTraffics call. id == -1 (all
  2649. // inbounds across panel): walk every node-managed inbound and call
  2650. // the per-inbound endpoint — there's no panel-wide endpoint that
  2651. // only resets clients without zeroing inbound counters.
  2652. var inbounds []model.Inbound
  2653. q := db.Model(model.Inbound{}).Where("node_id IS NOT NULL")
  2654. if id != -1 {
  2655. q = q.Where("id = ?", id)
  2656. }
  2657. if err := q.Find(&inbounds).Error; err != nil {
  2658. // Failed to discover which inbounds to propagate to — central
  2659. // DB is already correct, log and move on.
  2660. logger.Warning("ResetAllClientTraffics: discover node inbounds failed:", err)
  2661. return nil
  2662. }
  2663. for i := range inbounds {
  2664. ib := &inbounds[i]
  2665. rt, rterr := s.runtimeFor(ib)
  2666. if rterr != nil {
  2667. logger.Warning("ResetAllClientTraffics: runtime lookup for inbound", ib.Id, "failed:", rterr)
  2668. continue
  2669. }
  2670. if e := rt.ResetInboundClientTraffics(context.Background(), ib); e != nil {
  2671. logger.Warning("ResetAllClientTraffics: remote propagation to", rt.Name(), "failed:", e)
  2672. }
  2673. }
  2674. return nil
  2675. }
  2676. func (s *InboundService) ResetAllTraffics() error {
  2677. db := database.GetDB()
  2678. now := time.Now().UnixMilli()
  2679. if err := db.Model(model.Inbound{}).
  2680. Where("user_id > ?", 0).
  2681. Updates(map[string]any{
  2682. "up": 0,
  2683. "down": 0,
  2684. "last_traffic_reset_time": now,
  2685. }).Error; err != nil {
  2686. return err
  2687. }
  2688. // Propagate to every node that has at least one inbound on this
  2689. // panel. We can't blanket-call rt.ResetAllTraffics because that
  2690. // would also zero traffic for inbounds the node hosts but the
  2691. // central panel doesn't know about — instead reset per inbound.
  2692. var inbounds []model.Inbound
  2693. if err := db.Model(model.Inbound{}).
  2694. Where("node_id IS NOT NULL").
  2695. Find(&inbounds).Error; err != nil {
  2696. logger.Warning("ResetAllTraffics: discover node inbounds failed:", err)
  2697. return nil
  2698. }
  2699. for i := range inbounds {
  2700. ib := &inbounds[i]
  2701. rt, rterr := s.runtimeFor(ib)
  2702. if rterr != nil {
  2703. logger.Warning("ResetAllTraffics: runtime lookup for inbound", ib.Id, "failed:", rterr)
  2704. continue
  2705. }
  2706. if e := rt.ResetInboundClientTraffics(context.Background(), ib); e != nil {
  2707. logger.Warning("ResetAllTraffics: remote propagation to", rt.Name(), "failed:", e)
  2708. }
  2709. }
  2710. return nil
  2711. }
  2712. func (s *InboundService) ResetInboundTraffic(id int) error {
  2713. db := database.GetDB()
  2714. result := db.Model(model.Inbound{}).
  2715. Where("id = ?", id).
  2716. Updates(map[string]any{"up": 0, "down": 0})
  2717. return result.Error
  2718. }
  2719. func (s *InboundService) DelDepletedClients(id int) (err error) {
  2720. db := database.GetDB()
  2721. tx := db.Begin()
  2722. defer func() {
  2723. if err == nil {
  2724. tx.Commit()
  2725. } else {
  2726. tx.Rollback()
  2727. }
  2728. }()
  2729. // Collect depleted emails globally — a shared-email row owned by one
  2730. // inbound depletes every sibling that lists the email.
  2731. now := time.Now().Unix() * 1000
  2732. depletedClause := "reset = 0 and ((total > 0 and up + down >= total) or (expiry_time > 0 and expiry_time <= ?))"
  2733. var depletedRows []xray.ClientTraffic
  2734. err = db.Model(xray.ClientTraffic{}).
  2735. Where(depletedClause, now).
  2736. Find(&depletedRows).Error
  2737. if err != nil {
  2738. return err
  2739. }
  2740. if len(depletedRows) == 0 {
  2741. return nil
  2742. }
  2743. depletedEmails := make(map[string]struct{}, len(depletedRows))
  2744. for _, r := range depletedRows {
  2745. if r.Email == "" {
  2746. continue
  2747. }
  2748. depletedEmails[strings.ToLower(r.Email)] = struct{}{}
  2749. }
  2750. if len(depletedEmails) == 0 {
  2751. return nil
  2752. }
  2753. var inbounds []*model.Inbound
  2754. inboundQuery := db.Model(model.Inbound{})
  2755. if id >= 0 {
  2756. inboundQuery = inboundQuery.Where("id = ?", id)
  2757. }
  2758. if err = inboundQuery.Find(&inbounds).Error; err != nil {
  2759. return err
  2760. }
  2761. for _, inbound := range inbounds {
  2762. var settings map[string]any
  2763. if err = json.Unmarshal([]byte(inbound.Settings), &settings); err != nil {
  2764. return err
  2765. }
  2766. rawClients, ok := settings["clients"].([]any)
  2767. if !ok {
  2768. continue
  2769. }
  2770. newClients := make([]any, 0, len(rawClients))
  2771. removed := 0
  2772. for _, client := range rawClients {
  2773. c, ok := client.(map[string]any)
  2774. if !ok {
  2775. newClients = append(newClients, client)
  2776. continue
  2777. }
  2778. email, _ := c["email"].(string)
  2779. if _, isDepleted := depletedEmails[strings.ToLower(email)]; isDepleted {
  2780. removed++
  2781. continue
  2782. }
  2783. newClients = append(newClients, client)
  2784. }
  2785. if removed == 0 {
  2786. continue
  2787. }
  2788. if len(newClients) == 0 {
  2789. s.DelInbound(inbound.Id)
  2790. continue
  2791. }
  2792. settings["clients"] = newClients
  2793. ns, mErr := json.MarshalIndent(settings, "", " ")
  2794. if mErr != nil {
  2795. return mErr
  2796. }
  2797. inbound.Settings = string(ns)
  2798. if err = tx.Save(inbound).Error; err != nil {
  2799. return err
  2800. }
  2801. }
  2802. // Drop now-orphaned rows. With id >= 0, a row is safe to drop only when
  2803. // no out-of-scope inbound still references the email.
  2804. if id < 0 {
  2805. err = tx.Where(depletedClause, now).Delete(xray.ClientTraffic{}).Error
  2806. return err
  2807. }
  2808. emails := make([]string, 0, len(depletedEmails))
  2809. for e := range depletedEmails {
  2810. emails = append(emails, e)
  2811. }
  2812. var stillReferenced []string
  2813. if err = tx.Raw(`
  2814. SELECT DISTINCT LOWER(JSON_EXTRACT(client.value, '$.email'))
  2815. FROM inbounds,
  2816. JSON_EACH(JSON_EXTRACT(inbounds.settings, '$.clients')) AS client
  2817. WHERE LOWER(JSON_EXTRACT(client.value, '$.email')) IN ?
  2818. `, emails).Scan(&stillReferenced).Error; err != nil {
  2819. return err
  2820. }
  2821. stillSet := make(map[string]struct{}, len(stillReferenced))
  2822. for _, e := range stillReferenced {
  2823. stillSet[e] = struct{}{}
  2824. }
  2825. toDelete := make([]string, 0, len(emails))
  2826. for _, e := range emails {
  2827. if _, kept := stillSet[e]; !kept {
  2828. toDelete = append(toDelete, e)
  2829. }
  2830. }
  2831. if len(toDelete) > 0 {
  2832. if err = tx.Where("LOWER(email) IN ?", toDelete).Delete(xray.ClientTraffic{}).Error; err != nil {
  2833. return err
  2834. }
  2835. }
  2836. return nil
  2837. }
  2838. func (s *InboundService) GetClientTrafficTgBot(tgId int64) ([]*xray.ClientTraffic, error) {
  2839. db := database.GetDB()
  2840. var inbounds []*model.Inbound
  2841. // Retrieve inbounds where settings contain the given tgId
  2842. err := db.Model(model.Inbound{}).Where("settings LIKE ?", fmt.Sprintf(`%%"tgId": %d%%`, tgId)).Find(&inbounds).Error
  2843. if err != nil && err != gorm.ErrRecordNotFound {
  2844. logger.Errorf("Error retrieving inbounds with tgId %d: %v", tgId, err)
  2845. return nil, err
  2846. }
  2847. var emails []string
  2848. for _, inbound := range inbounds {
  2849. clients, err := s.GetClients(inbound)
  2850. if err != nil {
  2851. logger.Errorf("Error retrieving clients for inbound %d: %v", inbound.Id, err)
  2852. continue
  2853. }
  2854. for _, client := range clients {
  2855. if client.TgID == tgId {
  2856. emails = append(emails, client.Email)
  2857. }
  2858. }
  2859. }
  2860. // Chunked to stay under SQLite's bind-variable limit when a single Telegram
  2861. // account owns thousands of clients across inbounds.
  2862. uniqEmails := uniqueNonEmptyStrings(emails)
  2863. traffics := make([]*xray.ClientTraffic, 0, len(uniqEmails))
  2864. for _, batch := range chunkStrings(uniqEmails, sqliteMaxVars) {
  2865. var page []*xray.ClientTraffic
  2866. if err = db.Model(xray.ClientTraffic{}).Where("email IN ?", batch).Find(&page).Error; err != nil {
  2867. if err == gorm.ErrRecordNotFound {
  2868. continue
  2869. }
  2870. logger.Errorf("Error retrieving ClientTraffic for emails %v: %v", batch, err)
  2871. return nil, err
  2872. }
  2873. traffics = append(traffics, page...)
  2874. }
  2875. if len(traffics) == 0 {
  2876. logger.Warning("No ClientTraffic records found for emails:", emails)
  2877. return nil, nil
  2878. }
  2879. // Populate UUID and other client data for each traffic record
  2880. for i := range traffics {
  2881. if ct, client, e := s.GetClientByEmail(traffics[i].Email); e == nil && ct != nil && client != nil {
  2882. traffics[i].Enable = client.Enable
  2883. traffics[i].UUID = client.ID
  2884. traffics[i].SubId = client.SubID
  2885. }
  2886. }
  2887. return traffics, nil
  2888. }
  2889. // sqliteMaxVars is a safe ceiling for the number of bind parameters in a
  2890. // single SQL statement. SQLite's SQLITE_MAX_VARIABLE_NUMBER is 999 on builds
  2891. // before 3.32 and 32766 after; staying under 999 keeps queries portable
  2892. // across forks/old binaries and also bounds per-query memory on truly large
  2893. // installs (>32k clients) where even modern SQLite would refuse a single IN.
  2894. const sqliteMaxVars = 900
  2895. // uniqueNonEmptyStrings returns a deduplicated copy of in with empty strings
  2896. // removed, preserving the order of first occurrence.
  2897. func uniqueNonEmptyStrings(in []string) []string {
  2898. if len(in) == 0 {
  2899. return nil
  2900. }
  2901. seen := make(map[string]struct{}, len(in))
  2902. out := make([]string, 0, len(in))
  2903. for _, v := range in {
  2904. if v == "" {
  2905. continue
  2906. }
  2907. if _, ok := seen[v]; ok {
  2908. continue
  2909. }
  2910. seen[v] = struct{}{}
  2911. out = append(out, v)
  2912. }
  2913. return out
  2914. }
  2915. // uniqueInts returns a deduplicated copy of in, preserving order of first occurrence.
  2916. func uniqueInts(in []int) []int {
  2917. if len(in) == 0 {
  2918. return nil
  2919. }
  2920. seen := make(map[int]struct{}, len(in))
  2921. out := make([]int, 0, len(in))
  2922. for _, v := range in {
  2923. if _, ok := seen[v]; ok {
  2924. continue
  2925. }
  2926. seen[v] = struct{}{}
  2927. out = append(out, v)
  2928. }
  2929. return out
  2930. }
  2931. // chunkStrings splits s into consecutive sub-slices of at most size elements.
  2932. // Returns nil for an empty input or non-positive size.
  2933. func chunkStrings(s []string, size int) [][]string {
  2934. if size <= 0 || len(s) == 0 {
  2935. return nil
  2936. }
  2937. out := make([][]string, 0, (len(s)+size-1)/size)
  2938. for i := 0; i < len(s); i += size {
  2939. end := i + size
  2940. if end > len(s) {
  2941. end = len(s)
  2942. }
  2943. out = append(out, s[i:end])
  2944. }
  2945. return out
  2946. }
  2947. // chunkInts splits s into consecutive sub-slices of at most size elements.
  2948. // Returns nil for an empty input or non-positive size.
  2949. func chunkInts(s []int, size int) [][]int {
  2950. if size <= 0 || len(s) == 0 {
  2951. return nil
  2952. }
  2953. out := make([][]int, 0, (len(s)+size-1)/size)
  2954. for i := 0; i < len(s); i += size {
  2955. end := i + size
  2956. if end > len(s) {
  2957. end = len(s)
  2958. }
  2959. out = append(out, s[i:end])
  2960. }
  2961. return out
  2962. }
  2963. // GetActiveClientTraffics returns the absolute ClientTraffic rows for the given
  2964. // emails. Used by the WebSocket delta path to push per-client absolute
  2965. // counters without re-serializing the full inbound list. The query is chunked
  2966. // to stay under SQLite's bind-variable limit on very large active sets.
  2967. // Empty input returns (nil, nil).
  2968. func (s *InboundService) GetActiveClientTraffics(emails []string) ([]*xray.ClientTraffic, error) {
  2969. uniq := uniqueNonEmptyStrings(emails)
  2970. if len(uniq) == 0 {
  2971. return nil, nil
  2972. }
  2973. db := database.GetDB()
  2974. traffics := make([]*xray.ClientTraffic, 0, len(uniq))
  2975. for _, batch := range chunkStrings(uniq, sqliteMaxVars) {
  2976. var page []*xray.ClientTraffic
  2977. if err := db.Model(xray.ClientTraffic{}).Where("email IN ?", batch).Find(&page).Error; err != nil {
  2978. return nil, err
  2979. }
  2980. traffics = append(traffics, page...)
  2981. }
  2982. return traffics, nil
  2983. }
  2984. // InboundTrafficSummary is the minimal projection of an inbound's traffic
  2985. // counters used by the WebSocket delta path. Excludes Settings/StreamSettings
  2986. // blobs so the broadcast stays compact even with many inbounds.
  2987. type InboundTrafficSummary struct {
  2988. Id int `json:"id"`
  2989. Up int64 `json:"up"`
  2990. Down int64 `json:"down"`
  2991. Total int64 `json:"total"`
  2992. AllTime int64 `json:"allTime"`
  2993. Enable bool `json:"enable"`
  2994. }
  2995. // GetInboundsTrafficSummary returns inbound-level absolute traffic counters
  2996. // (no per-client expansion). Companion to GetActiveClientTraffics — together
  2997. // they replace the heavy "full inbound list" broadcast on each cron tick.
  2998. func (s *InboundService) GetInboundsTrafficSummary() ([]InboundTrafficSummary, error) {
  2999. db := database.GetDB()
  3000. var summaries []InboundTrafficSummary
  3001. if err := db.Model(&model.Inbound{}).
  3002. Select("id, up, down, total, all_time, enable").
  3003. Find(&summaries).Error; err != nil {
  3004. return nil, err
  3005. }
  3006. return summaries, nil
  3007. }
  3008. func (s *InboundService) GetClientTrafficByEmail(email string) (traffic *xray.ClientTraffic, err error) {
  3009. // Prefer retrieving along with client to reflect actual enabled state from inbound settings
  3010. t, client, err := s.GetClientByEmail(email)
  3011. if err != nil {
  3012. logger.Warningf("Error retrieving ClientTraffic with email %s: %v", email, err)
  3013. return nil, err
  3014. }
  3015. if t != nil && client != nil {
  3016. t.UUID = client.ID
  3017. t.SubId = client.SubID
  3018. return t, nil
  3019. }
  3020. return nil, nil
  3021. }
  3022. func (s *InboundService) UpdateClientTrafficByEmail(email string, upload int64, download int64) error {
  3023. db := database.GetDB()
  3024. // Keep all_time monotonic: it represents historical cumulative usage and
  3025. // must never be less than the currently-tracked up+down. Without this,
  3026. // the UI showed "Общий трафик" (allTime) below the live consumed value
  3027. // after admins manually edited a client's counters.
  3028. result := db.Model(xray.ClientTraffic{}).
  3029. Where("email = ?", email).
  3030. Updates(map[string]any{
  3031. "up": upload,
  3032. "down": download,
  3033. "all_time": gorm.Expr("CASE WHEN COALESCE(all_time, 0) < ? THEN ? ELSE all_time END", upload+download, upload+download),
  3034. })
  3035. err := result.Error
  3036. if err != nil {
  3037. logger.Warningf("Error updating ClientTraffic with email %s: %v", email, err)
  3038. return err
  3039. }
  3040. return nil
  3041. }
  3042. func (s *InboundService) GetClientTrafficByID(id string) ([]xray.ClientTraffic, error) {
  3043. db := database.GetDB()
  3044. var traffics []xray.ClientTraffic
  3045. err := db.Model(xray.ClientTraffic{}).Where(`email IN(
  3046. SELECT JSON_EXTRACT(client.value, '$.email') as email
  3047. FROM inbounds,
  3048. JSON_EACH(JSON_EXTRACT(inbounds.settings, '$.clients')) AS client
  3049. WHERE
  3050. JSON_EXTRACT(client.value, '$.id') in (?)
  3051. )`, id).Find(&traffics).Error
  3052. if err != nil {
  3053. logger.Debug(err)
  3054. return nil, err
  3055. }
  3056. // Reconcile enable flag with client settings per email to avoid stale DB value
  3057. for i := range traffics {
  3058. if ct, client, e := s.GetClientByEmail(traffics[i].Email); e == nil && ct != nil && client != nil {
  3059. traffics[i].Enable = client.Enable
  3060. traffics[i].UUID = client.ID
  3061. traffics[i].SubId = client.SubID
  3062. }
  3063. }
  3064. return traffics, err
  3065. }
  3066. func (s *InboundService) SearchClientTraffic(query string) (traffic *xray.ClientTraffic, err error) {
  3067. db := database.GetDB()
  3068. inbound := &model.Inbound{}
  3069. traffic = &xray.ClientTraffic{}
  3070. // Search for inbound settings that contain the query
  3071. err = db.Model(model.Inbound{}).Where("settings LIKE ?", "%\""+query+"\"%").First(inbound).Error
  3072. if err != nil {
  3073. if err == gorm.ErrRecordNotFound {
  3074. logger.Warningf("Inbound settings containing query %s not found: %v", query, err)
  3075. return nil, err
  3076. }
  3077. logger.Errorf("Error searching for inbound settings with query %s: %v", query, err)
  3078. return nil, err
  3079. }
  3080. traffic.InboundId = inbound.Id
  3081. // Unmarshal settings to get clients
  3082. settings := map[string][]model.Client{}
  3083. if err := json.Unmarshal([]byte(inbound.Settings), &settings); err != nil {
  3084. logger.Errorf("Error unmarshalling inbound settings for inbound ID %d: %v", inbound.Id, err)
  3085. return nil, err
  3086. }
  3087. clients := settings["clients"]
  3088. for _, client := range clients {
  3089. if (client.ID == query || client.Password == query) && client.Email != "" {
  3090. traffic.Email = client.Email
  3091. break
  3092. }
  3093. }
  3094. if traffic.Email == "" {
  3095. logger.Warningf("No client found with query %s in inbound ID %d", query, inbound.Id)
  3096. return nil, gorm.ErrRecordNotFound
  3097. }
  3098. // Retrieve ClientTraffic based on the found email
  3099. err = db.Model(xray.ClientTraffic{}).Where("email = ?", traffic.Email).First(traffic).Error
  3100. if err != nil {
  3101. if err == gorm.ErrRecordNotFound {
  3102. logger.Warningf("ClientTraffic for email %s not found: %v", traffic.Email, err)
  3103. return nil, err
  3104. }
  3105. logger.Errorf("Error retrieving ClientTraffic for email %s: %v", traffic.Email, err)
  3106. return nil, err
  3107. }
  3108. return traffic, nil
  3109. }
  3110. func (s *InboundService) GetInboundClientIps(clientEmail string) (string, error) {
  3111. db := database.GetDB()
  3112. InboundClientIps := &model.InboundClientIps{}
  3113. err := db.Model(model.InboundClientIps{}).Where("client_email = ?", clientEmail).First(InboundClientIps).Error
  3114. if err != nil {
  3115. return "", err
  3116. }
  3117. if InboundClientIps.Ips == "" {
  3118. return "", nil
  3119. }
  3120. // Try to parse as new format (with timestamps)
  3121. type IPWithTimestamp struct {
  3122. IP string `json:"ip"`
  3123. Timestamp int64 `json:"timestamp"`
  3124. }
  3125. var ipsWithTime []IPWithTimestamp
  3126. err = json.Unmarshal([]byte(InboundClientIps.Ips), &ipsWithTime)
  3127. // If successfully parsed as new format, return with timestamps
  3128. if err == nil && len(ipsWithTime) > 0 {
  3129. return InboundClientIps.Ips, nil
  3130. }
  3131. // Otherwise, assume it's old format (simple string array)
  3132. // Try to parse as simple array and convert to new format
  3133. var oldIps []string
  3134. err = json.Unmarshal([]byte(InboundClientIps.Ips), &oldIps)
  3135. if err == nil && len(oldIps) > 0 {
  3136. // Convert old format to new format with current timestamp
  3137. newIpsWithTime := make([]IPWithTimestamp, len(oldIps))
  3138. for i, ip := range oldIps {
  3139. newIpsWithTime[i] = IPWithTimestamp{
  3140. IP: ip,
  3141. Timestamp: time.Now().Unix(),
  3142. }
  3143. }
  3144. result, _ := json.Marshal(newIpsWithTime)
  3145. return string(result), nil
  3146. }
  3147. // Return as-is if parsing fails
  3148. return InboundClientIps.Ips, nil
  3149. }
  3150. func (s *InboundService) ClearClientIps(clientEmail string) error {
  3151. db := database.GetDB()
  3152. result := db.Model(model.InboundClientIps{}).
  3153. Where("client_email = ?", clientEmail).
  3154. Update("ips", "")
  3155. err := result.Error
  3156. if err != nil {
  3157. return err
  3158. }
  3159. return nil
  3160. }
  3161. func (s *InboundService) SearchInbounds(query string) ([]*model.Inbound, error) {
  3162. db := database.GetDB()
  3163. var inbounds []*model.Inbound
  3164. err := db.Model(model.Inbound{}).Preload("ClientStats").Where("remark like ?", "%"+query+"%").Find(&inbounds).Error
  3165. if err != nil && err != gorm.ErrRecordNotFound {
  3166. return nil, err
  3167. }
  3168. return inbounds, nil
  3169. }
  3170. func (s *InboundService) MigrationRequirements() {
  3171. db := database.GetDB()
  3172. tx := db.Begin()
  3173. var err error
  3174. defer func() {
  3175. if err == nil {
  3176. tx.Commit()
  3177. if dbErr := db.Exec(`VACUUM "main"`).Error; dbErr != nil {
  3178. logger.Warningf("VACUUM failed: %v", dbErr)
  3179. }
  3180. } else {
  3181. tx.Rollback()
  3182. }
  3183. }()
  3184. // Calculate and backfill all_time from up+down for inbounds and clients
  3185. err = tx.Exec(`
  3186. UPDATE inbounds
  3187. SET all_time = IFNULL(up, 0) + IFNULL(down, 0)
  3188. WHERE IFNULL(all_time, 0) = 0 AND (IFNULL(up, 0) + IFNULL(down, 0)) > 0
  3189. `).Error
  3190. if err != nil {
  3191. return
  3192. }
  3193. err = tx.Exec(`
  3194. UPDATE client_traffics
  3195. SET all_time = IFNULL(up, 0) + IFNULL(down, 0)
  3196. WHERE IFNULL(all_time, 0) = 0 AND (IFNULL(up, 0) + IFNULL(down, 0)) > 0
  3197. `).Error
  3198. if err != nil {
  3199. return
  3200. }
  3201. // Fix inbounds based problems
  3202. var inbounds []*model.Inbound
  3203. err = tx.Model(model.Inbound{}).Where("protocol IN (?)", []string{"vmess", "vless", "trojan"}).Find(&inbounds).Error
  3204. if err != nil && err != gorm.ErrRecordNotFound {
  3205. return
  3206. }
  3207. for inbound_index := range inbounds {
  3208. settings := map[string]any{}
  3209. json.Unmarshal([]byte(inbounds[inbound_index].Settings), &settings)
  3210. clients, ok := settings["clients"].([]any)
  3211. if ok {
  3212. // Fix Client configuration problems
  3213. var newClients []any
  3214. hasVisionFlow := false
  3215. for client_index := range clients {
  3216. c := clients[client_index].(map[string]any)
  3217. // Add email='' if it is not exists
  3218. if _, ok := c["email"]; !ok {
  3219. c["email"] = ""
  3220. }
  3221. // Convert string tgId to int64
  3222. if _, ok := c["tgId"]; ok {
  3223. var tgId any = c["tgId"]
  3224. if tgIdStr, ok2 := tgId.(string); ok2 {
  3225. tgIdInt64, err := strconv.ParseInt(strings.ReplaceAll(tgIdStr, " ", ""), 10, 64)
  3226. if err == nil {
  3227. c["tgId"] = tgIdInt64
  3228. }
  3229. }
  3230. }
  3231. // Remove "flow": "xtls-rprx-direct"
  3232. if _, ok := c["flow"]; ok {
  3233. if c["flow"] == "xtls-rprx-direct" {
  3234. c["flow"] = ""
  3235. }
  3236. }
  3237. if flow, _ := c["flow"].(string); flow == "xtls-rprx-vision" {
  3238. hasVisionFlow = true
  3239. }
  3240. // Backfill created_at and updated_at
  3241. if _, ok := c["created_at"]; !ok {
  3242. c["created_at"] = time.Now().Unix() * 1000
  3243. }
  3244. c["updated_at"] = time.Now().Unix() * 1000
  3245. newClients = append(newClients, any(c))
  3246. }
  3247. settings["clients"] = newClients
  3248. // Drop orphaned testseed: VLESS-only field, only meaningful when at least
  3249. // one client uses the exact xtls-rprx-vision flow. Older versions saved it
  3250. // for any non-empty flow (including the UDP variant) or kept it after the
  3251. // flow was cleared from the client modal — clean those up here.
  3252. if inbounds[inbound_index].Protocol == model.VLESS && !hasVisionFlow {
  3253. delete(settings, "testseed")
  3254. }
  3255. modifiedSettings, err := json.MarshalIndent(settings, "", " ")
  3256. if err != nil {
  3257. return
  3258. }
  3259. inbounds[inbound_index].Settings = string(modifiedSettings)
  3260. }
  3261. // Add client traffic row for all clients which has email
  3262. modelClients, err := s.GetClients(inbounds[inbound_index])
  3263. if err != nil {
  3264. return
  3265. }
  3266. for _, modelClient := range modelClients {
  3267. if len(modelClient.Email) > 0 {
  3268. var count int64
  3269. tx.Model(xray.ClientTraffic{}).Where("email = ?", modelClient.Email).Count(&count)
  3270. if count == 0 {
  3271. s.AddClientStat(tx, inbounds[inbound_index].Id, &modelClient)
  3272. }
  3273. }
  3274. }
  3275. }
  3276. tx.Save(inbounds)
  3277. // Remove orphaned traffics
  3278. tx.Where("inbound_id = 0").Delete(xray.ClientTraffic{})
  3279. // Migrate old MultiDomain to External Proxy
  3280. var externalProxy []struct {
  3281. Id int
  3282. Port int
  3283. StreamSettings []byte
  3284. }
  3285. err = tx.Raw(`select id, port, stream_settings
  3286. from inbounds
  3287. WHERE protocol in ('vmess','vless','trojan')
  3288. AND json_extract(stream_settings, '$.security') = 'tls'
  3289. AND json_extract(stream_settings, '$.tlsSettings.settings.domains') IS NOT NULL`).Scan(&externalProxy).Error
  3290. if err != nil || len(externalProxy) == 0 {
  3291. return
  3292. }
  3293. for _, ep := range externalProxy {
  3294. var reverses any
  3295. var stream map[string]any
  3296. json.Unmarshal(ep.StreamSettings, &stream)
  3297. if tlsSettings, ok := stream["tlsSettings"].(map[string]any); ok {
  3298. if settings, ok := tlsSettings["settings"].(map[string]any); ok {
  3299. if domains, ok := settings["domains"].([]any); ok {
  3300. for _, domain := range domains {
  3301. if domainMap, ok := domain.(map[string]any); ok {
  3302. domainMap["forceTls"] = "same"
  3303. domainMap["port"] = ep.Port
  3304. domainMap["dest"] = domainMap["domain"].(string)
  3305. delete(domainMap, "domain")
  3306. }
  3307. }
  3308. }
  3309. reverses = settings["domains"]
  3310. delete(settings, "domains")
  3311. }
  3312. }
  3313. stream["externalProxy"] = reverses
  3314. newStream, _ := json.MarshalIndent(stream, " ", " ")
  3315. tx.Model(model.Inbound{}).Where("id = ?", ep.Id).Update("stream_settings", newStream)
  3316. }
  3317. err = tx.Raw(`UPDATE inbounds
  3318. SET tag = REPLACE(tag, '0.0.0.0:', '')
  3319. WHERE INSTR(tag, '0.0.0.0:') > 0;`).Error
  3320. if err != nil {
  3321. return
  3322. }
  3323. }
  3324. func (s *InboundService) MigrateDB() {
  3325. s.MigrationRequirements()
  3326. s.MigrationRemoveOrphanedTraffics()
  3327. }
  3328. func (s *InboundService) GetOnlineClients() []string {
  3329. return p.GetOnlineClients()
  3330. }
  3331. // SetNodeOnlineClients records a remote node's online-clients list on
  3332. // the panel-wide xray.Process so GetOnlineClients returns the union of
  3333. // local + every node's contribution. Called by NodeTrafficSyncJob.
  3334. func (s *InboundService) SetNodeOnlineClients(nodeID int, emails []string) {
  3335. if p != nil {
  3336. p.SetNodeOnlineClients(nodeID, emails)
  3337. }
  3338. }
  3339. // ClearNodeOnlineClients drops one node's contribution to the online
  3340. // set. Used when the per-node sync probe fails so a downed node
  3341. // doesn't keep its clients listed as online forever.
  3342. func (s *InboundService) ClearNodeOnlineClients(nodeID int) {
  3343. if p != nil {
  3344. p.ClearNodeOnlineClients(nodeID)
  3345. }
  3346. }
  3347. func (s *InboundService) GetClientsLastOnline() (map[string]int64, error) {
  3348. db := database.GetDB()
  3349. var rows []xray.ClientTraffic
  3350. err := db.Model(&xray.ClientTraffic{}).Select("email, last_online").Find(&rows).Error
  3351. if err != nil && err != gorm.ErrRecordNotFound {
  3352. return nil, err
  3353. }
  3354. result := make(map[string]int64, len(rows))
  3355. for _, r := range rows {
  3356. result[r.Email] = r.LastOnline
  3357. }
  3358. return result, nil
  3359. }
  3360. func (s *InboundService) FilterAndSortClientEmails(emails []string) ([]string, []string, error) {
  3361. db := database.GetDB()
  3362. // Step 1: Get ClientTraffic records for emails in the input list.
  3363. // Chunked to stay under SQLite's bind-variable limit on huge inputs.
  3364. uniqEmails := uniqueNonEmptyStrings(emails)
  3365. clients := make([]xray.ClientTraffic, 0, len(uniqEmails))
  3366. for _, batch := range chunkStrings(uniqEmails, sqliteMaxVars) {
  3367. var page []xray.ClientTraffic
  3368. if err := db.Where("email IN ?", batch).Find(&page).Error; err != nil && err != gorm.ErrRecordNotFound {
  3369. return nil, nil, err
  3370. }
  3371. clients = append(clients, page...)
  3372. }
  3373. // Step 2: Sort clients by (Up + Down) descending
  3374. sort.Slice(clients, func(i, j int) bool {
  3375. return (clients[i].Up + clients[i].Down) > (clients[j].Up + clients[j].Down)
  3376. })
  3377. // Step 3: Extract sorted valid emails and track found ones
  3378. validEmails := make([]string, 0, len(clients))
  3379. found := make(map[string]bool)
  3380. for _, client := range clients {
  3381. validEmails = append(validEmails, client.Email)
  3382. found[client.Email] = true
  3383. }
  3384. // Step 4: Identify emails that were not found in the database
  3385. extraEmails := make([]string, 0)
  3386. for _, email := range emails {
  3387. if !found[email] {
  3388. extraEmails = append(extraEmails, email)
  3389. }
  3390. }
  3391. return validEmails, extraEmails, nil
  3392. }
  3393. func (s *InboundService) DelInboundClientByEmail(inboundId int, email string) (bool, error) {
  3394. oldInbound, err := s.GetInbound(inboundId)
  3395. if err != nil {
  3396. logger.Error("Load Old Data Error")
  3397. return false, err
  3398. }
  3399. var settings map[string]any
  3400. if err := json.Unmarshal([]byte(oldInbound.Settings), &settings); err != nil {
  3401. return false, err
  3402. }
  3403. interfaceClients, ok := settings["clients"].([]any)
  3404. if !ok {
  3405. return false, common.NewError("invalid clients format in inbound settings")
  3406. }
  3407. var newClients []any
  3408. needApiDel := false
  3409. found := false
  3410. for _, client := range interfaceClients {
  3411. c, ok := client.(map[string]any)
  3412. if !ok {
  3413. continue
  3414. }
  3415. if cEmail, ok := c["email"].(string); ok && cEmail == email {
  3416. // matched client, drop it
  3417. found = true
  3418. needApiDel, _ = c["enable"].(bool)
  3419. } else {
  3420. newClients = append(newClients, client)
  3421. }
  3422. }
  3423. if !found {
  3424. return false, common.NewError(fmt.Sprintf("client with email %s not found", email))
  3425. }
  3426. if len(newClients) == 0 {
  3427. return false, common.NewError("no client remained in Inbound")
  3428. }
  3429. settings["clients"] = newClients
  3430. newSettings, err := json.MarshalIndent(settings, "", " ")
  3431. if err != nil {
  3432. return false, err
  3433. }
  3434. oldInbound.Settings = string(newSettings)
  3435. db := database.GetDB()
  3436. // Drop the row and IPs only when this was the last inbound referencing
  3437. // the email — siblings still need the shared accounting state.
  3438. emailShared, err := s.emailUsedByOtherInbounds(email, inboundId)
  3439. if err != nil {
  3440. return false, err
  3441. }
  3442. if !emailShared {
  3443. if err := s.DelClientIPs(db, email); err != nil {
  3444. logger.Error("Error in delete client IPs")
  3445. return false, err
  3446. }
  3447. }
  3448. needRestart := false
  3449. // remove stats too
  3450. if len(email) > 0 && !emailShared {
  3451. traffic, err := s.GetClientTrafficByEmail(email)
  3452. if err != nil {
  3453. return false, err
  3454. }
  3455. if traffic != nil {
  3456. if err := s.DelClientStat(db, email); err != nil {
  3457. logger.Error("Delete stats Data Error")
  3458. return false, err
  3459. }
  3460. }
  3461. if needApiDel {
  3462. rt, rterr := s.runtimeFor(oldInbound)
  3463. if rterr != nil {
  3464. if oldInbound.NodeID != nil {
  3465. return false, rterr
  3466. }
  3467. needRestart = true
  3468. } else if oldInbound.NodeID == nil {
  3469. if err1 := rt.RemoveUser(context.Background(), oldInbound, email); err1 == nil {
  3470. logger.Debug("Client deleted on", rt.Name(), ":", email)
  3471. needRestart = false
  3472. } else if strings.Contains(err1.Error(), fmt.Sprintf("User %s not found.", email)) {
  3473. logger.Debug("User is already deleted. Nothing to do more...")
  3474. } else {
  3475. logger.Debug("Error in deleting client on", rt.Name(), ":", err1)
  3476. needRestart = true
  3477. }
  3478. } else {
  3479. if err1 := rt.UpdateInbound(context.Background(), oldInbound, oldInbound); err1 != nil {
  3480. return false, err1
  3481. }
  3482. }
  3483. }
  3484. }
  3485. return needRestart, db.Save(oldInbound).Error
  3486. }