client.go 100 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870
  1. package service
  2. import (
  3. "context"
  4. "encoding/base64"
  5. "encoding/json"
  6. "errors"
  7. "fmt"
  8. "slices"
  9. "sort"
  10. "strconv"
  11. "strings"
  12. "sync"
  13. "time"
  14. "github.com/google/uuid"
  15. "github.com/mhsanaei/3x-ui/v3/database"
  16. "github.com/mhsanaei/3x-ui/v3/database/model"
  17. "github.com/mhsanaei/3x-ui/v3/logger"
  18. "github.com/mhsanaei/3x-ui/v3/util/common"
  19. "github.com/mhsanaei/3x-ui/v3/util/random"
  20. "github.com/mhsanaei/3x-ui/v3/xray"
  21. "gorm.io/gorm"
  22. )
  23. type ClientWithAttachments struct {
  24. model.ClientRecord
  25. InboundIds []int `json:"inboundIds"`
  26. Traffic *xray.ClientTraffic `json:"traffic,omitempty"`
  27. }
  28. // MarshalJSON is required because model.ClientRecord defines its own
  29. // MarshalJSON. Go promotes the embedded method to the outer struct, so without
  30. // this the encoder would call ClientRecord.MarshalJSON for the whole value and
  31. // silently drop InboundIds and Traffic from the API response.
  32. func (c ClientWithAttachments) MarshalJSON() ([]byte, error) {
  33. rec, err := json.Marshal(c.ClientRecord)
  34. if err != nil {
  35. return nil, err
  36. }
  37. extras := struct {
  38. InboundIds []int `json:"inboundIds"`
  39. Traffic *xray.ClientTraffic `json:"traffic,omitempty"`
  40. }{InboundIds: c.InboundIds, Traffic: c.Traffic}
  41. extra, err := json.Marshal(extras)
  42. if err != nil {
  43. return nil, err
  44. }
  45. if len(rec) < 2 || rec[len(rec)-1] != '}' || len(extra) <= 2 {
  46. return rec, nil
  47. }
  48. const maxMarshalSize = 256 << 20
  49. if len(rec) > maxMarshalSize || len(extra) > maxMarshalSize {
  50. return rec, nil
  51. }
  52. out := make([]byte, 0, len(rec)+len(extra))
  53. out = append(out, rec[:len(rec)-1]...)
  54. if len(rec) > 2 {
  55. out = append(out, ',')
  56. }
  57. out = append(out, extra[1:]...)
  58. return out, nil
  59. }
  60. func clientKeyForProtocol(p model.Protocol, rec *model.ClientRecord) string {
  61. if rec == nil {
  62. return ""
  63. }
  64. switch p {
  65. case model.Trojan:
  66. return rec.Password
  67. case model.Shadowsocks:
  68. return rec.Email
  69. case model.Hysteria:
  70. return rec.Auth
  71. default:
  72. return rec.UUID
  73. }
  74. }
  75. type ClientService struct{}
  76. // Short-lived tombstone of just-deleted client emails so that a node snapshot
  77. // arriving between delete and node-side processing doesn't resurrect them.
  78. var (
  79. recentlyDeletedMu sync.Mutex
  80. recentlyDeleted = map[string]time.Time{}
  81. )
  82. const deleteTombstoneTTL = 90 * time.Second
  83. var (
  84. inboundMutationLocksMu sync.Mutex
  85. inboundMutationLocks = map[int]*sync.Mutex{}
  86. )
  87. func lockInbound(inboundId int) *sync.Mutex {
  88. inboundMutationLocksMu.Lock()
  89. defer inboundMutationLocksMu.Unlock()
  90. m, ok := inboundMutationLocks[inboundId]
  91. if !ok {
  92. m = &sync.Mutex{}
  93. inboundMutationLocks[inboundId] = m
  94. }
  95. m.Lock()
  96. return m
  97. }
  98. func compactOrphans(db *gorm.DB, clients []any) []any {
  99. if len(clients) == 0 {
  100. return clients
  101. }
  102. emails := make([]string, 0, len(clients))
  103. for _, c := range clients {
  104. cm, ok := c.(map[string]any)
  105. if !ok {
  106. continue
  107. }
  108. if e, _ := cm["email"].(string); e != "" {
  109. emails = append(emails, e)
  110. }
  111. }
  112. if len(emails) == 0 {
  113. return clients
  114. }
  115. var existingEmails []string
  116. if err := db.Model(&model.ClientRecord{}).Where("email IN ?", emails).Pluck("email", &existingEmails).Error; err != nil {
  117. logger.Warning("compactOrphans pluck:", err)
  118. return clients
  119. }
  120. if len(existingEmails) == len(emails) {
  121. return clients
  122. }
  123. existing := make(map[string]struct{}, len(existingEmails))
  124. for _, e := range existingEmails {
  125. existing[e] = struct{}{}
  126. }
  127. out := make([]any, 0, len(existingEmails))
  128. for _, c := range clients {
  129. cm, ok := c.(map[string]any)
  130. if !ok {
  131. out = append(out, c)
  132. continue
  133. }
  134. e, _ := cm["email"].(string)
  135. if e == "" {
  136. out = append(out, c)
  137. continue
  138. }
  139. if _, ok := existing[e]; ok {
  140. out = append(out, c)
  141. }
  142. }
  143. return out
  144. }
  145. func tombstoneClientEmail(email string) {
  146. if email == "" {
  147. return
  148. }
  149. recentlyDeletedMu.Lock()
  150. defer recentlyDeletedMu.Unlock()
  151. recentlyDeleted[email] = time.Now()
  152. cutoff := time.Now().Add(-deleteTombstoneTTL)
  153. for e, ts := range recentlyDeleted {
  154. if ts.Before(cutoff) {
  155. delete(recentlyDeleted, e)
  156. }
  157. }
  158. }
  159. func isClientEmailTombstoned(email string) bool {
  160. if email == "" {
  161. return false
  162. }
  163. recentlyDeletedMu.Lock()
  164. defer recentlyDeletedMu.Unlock()
  165. ts, ok := recentlyDeleted[email]
  166. if !ok {
  167. return false
  168. }
  169. if time.Since(ts) > deleteTombstoneTTL {
  170. delete(recentlyDeleted, email)
  171. return false
  172. }
  173. return true
  174. }
  175. func (s *ClientService) SyncInbound(tx *gorm.DB, inboundId int, clients []model.Client) error {
  176. if tx == nil {
  177. tx = database.GetDB()
  178. }
  179. if err := tx.Where("inbound_id = ?", inboundId).Delete(&model.ClientInbound{}).Error; err != nil {
  180. return err
  181. }
  182. for i := range clients {
  183. c := clients[i]
  184. email := strings.TrimSpace(c.Email)
  185. if email == "" {
  186. continue
  187. }
  188. incoming := c.ToRecord()
  189. row := &model.ClientRecord{}
  190. err := tx.Where("email = ?", email).First(row).Error
  191. if err != nil && !errors.Is(err, gorm.ErrRecordNotFound) {
  192. return err
  193. }
  194. if errors.Is(err, gorm.ErrRecordNotFound) {
  195. if err := tx.Create(incoming).Error; err != nil {
  196. return err
  197. }
  198. row = incoming
  199. } else {
  200. if incoming.UUID != "" {
  201. row.UUID = incoming.UUID
  202. }
  203. if incoming.Password != "" {
  204. row.Password = incoming.Password
  205. }
  206. if incoming.Auth != "" {
  207. row.Auth = incoming.Auth
  208. }
  209. row.Flow = incoming.Flow
  210. if incoming.Security != "" {
  211. row.Security = incoming.Security
  212. }
  213. if incoming.Reverse != "" {
  214. row.Reverse = incoming.Reverse
  215. }
  216. row.SubID = incoming.SubID
  217. row.LimitIP = incoming.LimitIP
  218. row.TotalGB = incoming.TotalGB
  219. row.ExpiryTime = incoming.ExpiryTime
  220. row.Enable = incoming.Enable
  221. row.TgID = incoming.TgID
  222. row.Group = incoming.Group
  223. row.Comment = incoming.Comment
  224. row.Reset = incoming.Reset
  225. if incoming.CreatedAt > 0 && (row.CreatedAt == 0 || incoming.CreatedAt < row.CreatedAt) {
  226. row.CreatedAt = incoming.CreatedAt
  227. }
  228. preservedUpdatedAt := row.UpdatedAt
  229. if incoming.UpdatedAt > preservedUpdatedAt {
  230. preservedUpdatedAt = incoming.UpdatedAt
  231. }
  232. row.UpdatedAt = preservedUpdatedAt
  233. if err := tx.Save(row).Error; err != nil {
  234. return err
  235. }
  236. if err := tx.Model(&model.ClientRecord{}).
  237. Where("id = ?", row.Id).
  238. UpdateColumn("updated_at", preservedUpdatedAt).Error; err != nil {
  239. return err
  240. }
  241. }
  242. link := model.ClientInbound{
  243. ClientId: row.Id,
  244. InboundId: inboundId,
  245. FlowOverride: c.Flow,
  246. }
  247. if err := tx.Create(&link).Error; err != nil {
  248. return err
  249. }
  250. }
  251. return nil
  252. }
  253. func (s *ClientService) DetachInbound(tx *gorm.DB, inboundId int) error {
  254. if tx == nil {
  255. tx = database.GetDB()
  256. }
  257. return tx.Where("inbound_id = ?", inboundId).Delete(&model.ClientInbound{}).Error
  258. }
  259. func (s *ClientService) ListForInbound(tx *gorm.DB, inboundId int) ([]model.Client, error) {
  260. if tx == nil {
  261. tx = database.GetDB()
  262. }
  263. type joinedRow struct {
  264. model.ClientRecord
  265. FlowOverride string
  266. }
  267. var rows []joinedRow
  268. err := tx.Table("clients").
  269. Select("clients.*, client_inbounds.flow_override AS flow_override").
  270. Joins("JOIN client_inbounds ON client_inbounds.client_id = clients.id").
  271. Where("client_inbounds.inbound_id = ?", inboundId).
  272. Order("clients.id ASC").
  273. Find(&rows).Error
  274. if err != nil {
  275. return nil, err
  276. }
  277. out := make([]model.Client, 0, len(rows))
  278. for i := range rows {
  279. c := rows[i].ToClient()
  280. if rows[i].FlowOverride != "" {
  281. c.Flow = rows[i].FlowOverride
  282. }
  283. out = append(out, *c)
  284. }
  285. return out, nil
  286. }
  287. func (s *ClientService) GetRecordByEmail(tx *gorm.DB, email string) (*model.ClientRecord, error) {
  288. if tx == nil {
  289. tx = database.GetDB()
  290. }
  291. row := &model.ClientRecord{}
  292. err := tx.Where("email = ?", email).First(row).Error
  293. if err != nil {
  294. return nil, err
  295. }
  296. return row, nil
  297. }
  298. func (s *ClientService) GetInboundIdsForEmail(tx *gorm.DB, email string) ([]int, error) {
  299. if tx == nil {
  300. tx = database.GetDB()
  301. }
  302. var ids []int
  303. err := tx.Table("client_inbounds").
  304. Select("client_inbounds.inbound_id").
  305. Joins("JOIN clients ON clients.id = client_inbounds.client_id").
  306. Where("clients.email = ?", email).
  307. Scan(&ids).Error
  308. if err != nil {
  309. return nil, err
  310. }
  311. return ids, nil
  312. }
  313. func (s *ClientService) GetByID(id int) (*model.ClientRecord, error) {
  314. row := &model.ClientRecord{}
  315. if err := database.GetDB().Where("id = ?", id).First(row).Error; err != nil {
  316. return nil, err
  317. }
  318. return row, nil
  319. }
  320. func (s *ClientService) GetInboundIdsForRecord(id int) ([]int, error) {
  321. var ids []int
  322. err := database.GetDB().Table("client_inbounds").
  323. Where("client_id = ?", id).
  324. Order("inbound_id ASC").
  325. Pluck("inbound_id", &ids).Error
  326. if err != nil {
  327. return nil, err
  328. }
  329. return ids, nil
  330. }
  331. func (s *ClientService) List() ([]ClientWithAttachments, error) {
  332. db := database.GetDB()
  333. var rows []model.ClientRecord
  334. if err := db.Order("id ASC").Find(&rows).Error; err != nil {
  335. return nil, err
  336. }
  337. if len(rows) == 0 {
  338. return []ClientWithAttachments{}, nil
  339. }
  340. clientIds := make([]int, 0, len(rows))
  341. emails := make([]string, 0, len(rows))
  342. for i := range rows {
  343. clientIds = append(clientIds, rows[i].Id)
  344. if rows[i].Email != "" {
  345. emails = append(emails, rows[i].Email)
  346. }
  347. }
  348. var links []model.ClientInbound
  349. if err := db.Where("client_id IN ?", clientIds).Find(&links).Error; err != nil {
  350. return nil, err
  351. }
  352. attachments := make(map[int][]int, len(rows))
  353. for _, l := range links {
  354. attachments[l.ClientId] = append(attachments[l.ClientId], l.InboundId)
  355. }
  356. trafficByEmail := make(map[string]*xray.ClientTraffic, len(emails))
  357. if len(emails) > 0 {
  358. var stats []xray.ClientTraffic
  359. if err := db.Where("email IN ?", emails).Find(&stats).Error; err != nil {
  360. return nil, err
  361. }
  362. for i := range stats {
  363. trafficByEmail[stats[i].Email] = &stats[i]
  364. }
  365. }
  366. out := make([]ClientWithAttachments, 0, len(rows))
  367. for i := range rows {
  368. out = append(out, ClientWithAttachments{
  369. ClientRecord: rows[i],
  370. InboundIds: attachments[rows[i].Id],
  371. Traffic: trafficByEmail[rows[i].Email],
  372. })
  373. }
  374. return out, nil
  375. }
  376. type ClientCreatePayload struct {
  377. Client model.Client `json:"client"`
  378. InboundIds []int `json:"inboundIds"`
  379. }
  380. func (s *ClientService) Create(inboundSvc *InboundService, payload *ClientCreatePayload) (bool, error) {
  381. if payload == nil {
  382. return false, common.NewError("empty payload")
  383. }
  384. client := payload.Client
  385. if strings.TrimSpace(client.Email) == "" {
  386. return false, common.NewError("client email is required")
  387. }
  388. if len(payload.InboundIds) == 0 {
  389. return false, common.NewError("at least one inbound is required")
  390. }
  391. if client.SubID == "" {
  392. client.SubID = uuid.NewString()
  393. }
  394. if !client.Enable {
  395. client.Enable = true
  396. }
  397. now := time.Now().UnixMilli()
  398. if client.CreatedAt == 0 {
  399. client.CreatedAt = now
  400. }
  401. client.UpdatedAt = now
  402. existing := &model.ClientRecord{}
  403. err := database.GetDB().Where("email = ?", client.Email).First(existing).Error
  404. if err != nil && !errors.Is(err, gorm.ErrRecordNotFound) {
  405. return false, err
  406. }
  407. emailTaken := !errors.Is(err, gorm.ErrRecordNotFound)
  408. if emailTaken {
  409. if existing.SubID == "" || existing.SubID != client.SubID {
  410. return false, common.NewError("email already in use:", client.Email)
  411. }
  412. }
  413. needRestart := false
  414. for _, ibId := range payload.InboundIds {
  415. inbound, getErr := inboundSvc.GetInbound(ibId)
  416. if getErr != nil {
  417. return needRestart, getErr
  418. }
  419. if err := s.fillProtocolDefaults(&client, inbound); err != nil {
  420. return needRestart, err
  421. }
  422. settingsPayload, mErr := json.Marshal(map[string][]model.Client{"clients": {client}})
  423. if mErr != nil {
  424. return needRestart, mErr
  425. }
  426. nr, addErr := s.AddInboundClient(inboundSvc, &model.Inbound{
  427. Id: ibId,
  428. Settings: string(settingsPayload),
  429. })
  430. if addErr != nil {
  431. return needRestart, addErr
  432. }
  433. if nr {
  434. needRestart = true
  435. }
  436. }
  437. return needRestart, nil
  438. }
  439. func (s *ClientService) fillProtocolDefaults(c *model.Client, ib *model.Inbound) error {
  440. switch ib.Protocol {
  441. case model.VMESS, model.VLESS:
  442. if c.ID == "" {
  443. c.ID = uuid.NewString()
  444. }
  445. case model.Trojan:
  446. if c.Password == "" {
  447. c.Password = strings.ReplaceAll(uuid.NewString(), "-", "")
  448. }
  449. case model.Shadowsocks:
  450. method := shadowsocksMethodFromSettings(ib.Settings)
  451. if c.Password == "" || !validShadowsocksClientKey(method, c.Password) {
  452. c.Password = randomShadowsocksClientKey(method)
  453. }
  454. case model.Hysteria:
  455. if c.Auth == "" {
  456. c.Auth = strings.ReplaceAll(uuid.NewString(), "-", "")
  457. }
  458. }
  459. return nil
  460. }
  461. // shadowsocksMethodFromSettings pulls the "method" field out of the inbound's
  462. // settings JSON. Returns "" when the field is missing or settings is invalid.
  463. func shadowsocksMethodFromSettings(settings string) string {
  464. if settings == "" {
  465. return ""
  466. }
  467. var m map[string]any
  468. if err := json.Unmarshal([]byte(settings), &m); err != nil {
  469. return ""
  470. }
  471. method, _ := m["method"].(string)
  472. return method
  473. }
  474. // randomShadowsocksClientKey returns a per-client key sized to the cipher.
  475. // The 2022-blake3 ciphers require a base64-encoded key of an exact byte
  476. // length (16 bytes for aes-128-gcm, 32 bytes for aes-256-gcm and
  477. // chacha20-poly1305) — anything else fails with "bad key" on xray start.
  478. // Older ciphers accept arbitrary passwords, so we keep the uuid-style.
  479. func randomShadowsocksClientKey(method string) string {
  480. if n := shadowsocksKeyBytes(method); n > 0 {
  481. return random.Base64Bytes(n)
  482. }
  483. return strings.ReplaceAll(uuid.NewString(), "-", "")
  484. }
  485. // validShadowsocksClientKey reports whether key is acceptable for the cipher.
  486. // For 2022-blake3 it must decode to the exact byte length the cipher needs;
  487. // any other method accepts any non-empty string.
  488. func validShadowsocksClientKey(method, key string) bool {
  489. n := shadowsocksKeyBytes(method)
  490. if n == 0 {
  491. return key != ""
  492. }
  493. decoded, err := base64.StdEncoding.DecodeString(key)
  494. if err != nil {
  495. return false
  496. }
  497. return len(decoded) == n
  498. }
  499. func shadowsocksKeyBytes(method string) int {
  500. switch method {
  501. case "2022-blake3-aes-128-gcm":
  502. return 16
  503. case "2022-blake3-aes-256-gcm", "2022-blake3-chacha20-poly1305":
  504. return 32
  505. }
  506. return 0
  507. }
  508. // applyShadowsocksClientMethod normalises the per-client "method" field
  509. // when an inbound is created or updated:
  510. // - Legacy ciphers: backfill `method` so xray's multi-user code is happy.
  511. // "unsupported cipher method:" otherwise.
  512. // - 2022-blake3-*: strip the per-client `method` because xray rejects
  513. // it with "users must have empty method". This matters after an admin
  514. // switches an existing inbound from a legacy cipher to a 2022 one.
  515. func applyShadowsocksClientMethod(clients []any, settings map[string]any) {
  516. method, _ := settings["method"].(string)
  517. is2022 := strings.HasPrefix(method, "2022-blake3-")
  518. for i := range clients {
  519. cm, ok := clients[i].(map[string]any)
  520. if !ok {
  521. continue
  522. }
  523. if is2022 {
  524. if _, hasKey := cm["method"]; hasKey {
  525. delete(cm, "method")
  526. clients[i] = cm
  527. }
  528. continue
  529. }
  530. if method == "" {
  531. continue
  532. }
  533. if existing, _ := cm["method"].(string); existing != "" {
  534. continue
  535. }
  536. cm["method"] = method
  537. clients[i] = cm
  538. }
  539. }
  540. func (s *ClientService) Update(inboundSvc *InboundService, id int, updated model.Client) (bool, error) {
  541. existing, err := s.GetByID(id)
  542. if err != nil {
  543. return false, err
  544. }
  545. inboundIds, err := s.GetInboundIdsForRecord(id)
  546. if err != nil {
  547. return false, err
  548. }
  549. if strings.TrimSpace(updated.Email) == "" {
  550. return false, common.NewError("client email is required")
  551. }
  552. if updated.SubID == "" {
  553. updated.SubID = existing.SubID
  554. }
  555. if updated.SubID == "" {
  556. updated.SubID = uuid.NewString()
  557. }
  558. updated.UpdatedAt = time.Now().UnixMilli()
  559. if updated.CreatedAt == 0 {
  560. updated.CreatedAt = existing.CreatedAt
  561. }
  562. // Rename the ClientRecord row up front when the email changes. SyncInbound
  563. // (invoked from UpdateInboundClient below) looks up by email — without
  564. // renaming first it would treat the new email as a brand-new client,
  565. // insert a duplicate ClientRecord, and leave the original orphaned.
  566. if updated.Email != existing.Email {
  567. var collisionCount int64
  568. if err := database.GetDB().Model(&model.ClientRecord{}).
  569. Where("email = ? AND id <> ?", updated.Email, id).
  570. Count(&collisionCount).Error; err != nil {
  571. return false, err
  572. }
  573. if collisionCount > 0 {
  574. return false, common.NewError("Duplicate email:", updated.Email)
  575. }
  576. if err := database.GetDB().Model(&model.ClientRecord{}).
  577. Where("id = ?", id).
  578. Update("email", updated.Email).Error; err != nil {
  579. return false, err
  580. }
  581. }
  582. needRestart := false
  583. for _, ibId := range inboundIds {
  584. inbound, getErr := inboundSvc.GetInbound(ibId)
  585. if getErr != nil {
  586. return needRestart, getErr
  587. }
  588. oldKey := clientKeyForProtocol(inbound.Protocol, existing)
  589. if oldKey == "" {
  590. continue
  591. }
  592. if err := s.fillProtocolDefaults(&updated, inbound); err != nil {
  593. return needRestart, err
  594. }
  595. settingsPayload, mErr := json.Marshal(map[string][]model.Client{"clients": {updated}})
  596. if mErr != nil {
  597. return needRestart, mErr
  598. }
  599. nr, upErr := s.UpdateInboundClient(inboundSvc, &model.Inbound{
  600. Id: ibId,
  601. Settings: string(settingsPayload),
  602. }, oldKey)
  603. if upErr != nil {
  604. return needRestart, upErr
  605. }
  606. if nr {
  607. needRestart = true
  608. }
  609. }
  610. if err := database.GetDB().Model(&model.ClientRecord{}).
  611. Where("id = ?", id).
  612. UpdateColumn("updated_at", time.Now().UnixMilli()).Error; err != nil {
  613. return needRestart, err
  614. }
  615. return needRestart, nil
  616. }
  617. func (s *ClientService) Delete(inboundSvc *InboundService, id int, keepTraffic bool) (bool, error) {
  618. existing, err := s.GetByID(id)
  619. if err != nil {
  620. return false, err
  621. }
  622. tombstoneClientEmail(existing.Email)
  623. inboundIds, err := s.GetInboundIdsForRecord(id)
  624. if err != nil {
  625. return false, err
  626. }
  627. needRestart := false
  628. for _, ibId := range inboundIds {
  629. inbound, getErr := inboundSvc.GetInbound(ibId)
  630. if getErr != nil {
  631. if errors.Is(getErr, gorm.ErrRecordNotFound) {
  632. continue
  633. }
  634. return needRestart, getErr
  635. }
  636. key := clientKeyForProtocol(inbound.Protocol, existing)
  637. if key == "" {
  638. continue
  639. }
  640. nr, delErr := s.DelInboundClient(inboundSvc, ibId, key)
  641. if delErr != nil {
  642. return needRestart, delErr
  643. }
  644. if nr {
  645. needRestart = true
  646. }
  647. }
  648. db := database.GetDB()
  649. if err := db.Where("client_id = ?", id).Delete(&model.ClientInbound{}).Error; err != nil {
  650. return needRestart, err
  651. }
  652. if !keepTraffic && existing.Email != "" {
  653. if err := db.Where("email = ?", existing.Email).Delete(&xray.ClientTraffic{}).Error; err != nil {
  654. return needRestart, err
  655. }
  656. if err := db.Where("client_email = ?", existing.Email).Delete(&model.InboundClientIps{}).Error; err != nil {
  657. return needRestart, err
  658. }
  659. }
  660. if err := db.Delete(&model.ClientRecord{}, id).Error; err != nil {
  661. return needRestart, err
  662. }
  663. return needRestart, nil
  664. }
  665. func (s *ClientService) Attach(inboundSvc *InboundService, id int, inboundIds []int) (bool, error) {
  666. existing, err := s.GetByID(id)
  667. if err != nil {
  668. return false, err
  669. }
  670. currentIds, err := s.GetInboundIdsForRecord(id)
  671. if err != nil {
  672. return false, err
  673. }
  674. have := make(map[int]struct{}, len(currentIds))
  675. for _, x := range currentIds {
  676. have[x] = struct{}{}
  677. }
  678. clientWire := existing.ToClient()
  679. clientWire.UpdatedAt = time.Now().UnixMilli()
  680. needRestart := false
  681. for _, ibId := range inboundIds {
  682. if _, attached := have[ibId]; attached {
  683. continue
  684. }
  685. inbound, getErr := inboundSvc.GetInbound(ibId)
  686. if getErr != nil {
  687. return needRestart, getErr
  688. }
  689. copyClient := *clientWire
  690. if err := s.fillProtocolDefaults(&copyClient, inbound); err != nil {
  691. return needRestart, err
  692. }
  693. settingsPayload, mErr := json.Marshal(map[string][]model.Client{"clients": {copyClient}})
  694. if mErr != nil {
  695. return needRestart, mErr
  696. }
  697. nr, addErr := s.AddInboundClient(inboundSvc, &model.Inbound{
  698. Id: ibId,
  699. Settings: string(settingsPayload),
  700. })
  701. if addErr != nil {
  702. return needRestart, addErr
  703. }
  704. if nr {
  705. needRestart = true
  706. }
  707. }
  708. return needRestart, nil
  709. }
  710. func (s *ClientService) CreateOne(inboundSvc *InboundService, inboundId int, client model.Client) (bool, error) {
  711. return s.Create(inboundSvc, &ClientCreatePayload{
  712. Client: client,
  713. InboundIds: []int{inboundId},
  714. })
  715. }
  716. func (s *ClientService) DetachByEmail(inboundSvc *InboundService, inboundId int, email string) (bool, error) {
  717. if email == "" {
  718. return false, common.NewError("client email is required")
  719. }
  720. rec, err := s.GetRecordByEmail(nil, email)
  721. if err != nil {
  722. return false, err
  723. }
  724. return s.Detach(inboundSvc, rec.Id, []int{inboundId})
  725. }
  726. func (s *ClientService) AttachByEmail(inboundSvc *InboundService, email string, inboundIds []int) (bool, error) {
  727. if email == "" {
  728. return false, common.NewError("client email is required")
  729. }
  730. rec, err := s.GetRecordByEmail(nil, email)
  731. if err != nil {
  732. return false, err
  733. }
  734. return s.Attach(inboundSvc, rec.Id, inboundIds)
  735. }
  736. // BulkAttachResult reports the outcome of a bulk attach across target inbounds.
  737. type BulkAttachResult struct {
  738. Attached []string `json:"attached"`
  739. Skipped []string `json:"skipped"`
  740. Errors []string `json:"errors"`
  741. }
  742. // BulkAttach attaches the given existing clients (by email) to each target inbound,
  743. // reusing their identity (email/UUID/password/subId) and a shared traffic row. It adds
  744. // all clients to a target in a single AddInboundClient call, and reports clients already
  745. // present on a target as skipped.
  746. func (s *ClientService) BulkAttach(inboundSvc *InboundService, emails []string, inboundIds []int) (*BulkAttachResult, bool, error) {
  747. result := &BulkAttachResult{}
  748. if len(emails) == 0 || len(inboundIds) == 0 {
  749. return result, false, nil
  750. }
  751. records := make([]*model.ClientRecord, 0, len(emails))
  752. seenEmail := make(map[string]struct{}, len(emails))
  753. for _, email := range emails {
  754. if email == "" {
  755. continue
  756. }
  757. key := strings.ToLower(email)
  758. if _, ok := seenEmail[key]; ok {
  759. continue
  760. }
  761. seenEmail[key] = struct{}{}
  762. rec, err := s.GetRecordByEmail(nil, email)
  763. if err != nil {
  764. result.Errors = append(result.Errors, fmt.Sprintf("%s: %v", email, err))
  765. continue
  766. }
  767. records = append(records, rec)
  768. }
  769. needRestart := false
  770. for _, ibId := range inboundIds {
  771. inbound, err := inboundSvc.GetInbound(ibId)
  772. if err != nil {
  773. result.Errors = append(result.Errors, fmt.Sprintf("inbound %d: %v", ibId, err))
  774. continue
  775. }
  776. existingClients, err := inboundSvc.GetClients(inbound)
  777. if err != nil {
  778. result.Errors = append(result.Errors, fmt.Sprintf("inbound %d: %v", ibId, err))
  779. continue
  780. }
  781. have := make(map[string]struct{}, len(existingClients))
  782. for _, c := range existingClients {
  783. have[strings.ToLower(c.Email)] = struct{}{}
  784. }
  785. clientsToAdd := make([]model.Client, 0, len(records))
  786. for _, rec := range records {
  787. if _, attached := have[strings.ToLower(rec.Email)]; attached {
  788. result.Skipped = append(result.Skipped, rec.Email)
  789. continue
  790. }
  791. client := *rec.ToClient()
  792. client.UpdatedAt = time.Now().UnixMilli()
  793. if err := s.fillProtocolDefaults(&client, inbound); err != nil {
  794. result.Errors = append(result.Errors, fmt.Sprintf("%s -> inbound %d: %v", rec.Email, ibId, err))
  795. continue
  796. }
  797. clientsToAdd = append(clientsToAdd, client)
  798. }
  799. if len(clientsToAdd) == 0 {
  800. continue
  801. }
  802. payload, err := json.Marshal(map[string][]model.Client{"clients": clientsToAdd})
  803. if err != nil {
  804. result.Errors = append(result.Errors, fmt.Sprintf("inbound %d: %v", ibId, err))
  805. continue
  806. }
  807. nr, err := s.AddInboundClient(inboundSvc, &model.Inbound{Id: ibId, Settings: string(payload)})
  808. if err != nil {
  809. result.Errors = append(result.Errors, fmt.Sprintf("inbound %d: %v", ibId, err))
  810. continue
  811. }
  812. if nr {
  813. needRestart = true
  814. }
  815. for _, c := range clientsToAdd {
  816. result.Attached = append(result.Attached, c.Email)
  817. }
  818. }
  819. return result, needRestart, nil
  820. }
  821. // BulkDetachResult reports the outcome of a bulk detach across target inbounds.
  822. type BulkDetachResult struct {
  823. Detached []string `json:"detached"`
  824. Skipped []string `json:"skipped"`
  825. Errors []string `json:"errors"`
  826. }
  827. // BulkDetach detaches the given existing clients (by email) from each target inbound.
  828. // (email, inbound) pairs where the client is not currently attached are silently skipped
  829. // at the inbound level; emails that aren't attached to any of the requested inbounds
  830. // are reported under skipped. ClientRecord rows are kept even when they become orphaned
  831. // (matches single-client detach semantics); callers should use bulkDelete for full removal.
  832. func (s *ClientService) BulkDetach(inboundSvc *InboundService, emails []string, inboundIds []int) (*BulkDetachResult, bool, error) {
  833. result := &BulkDetachResult{}
  834. if len(emails) == 0 || len(inboundIds) == 0 {
  835. return result, false, nil
  836. }
  837. requested := make(map[int]struct{}, len(inboundIds))
  838. for _, id := range inboundIds {
  839. requested[id] = struct{}{}
  840. }
  841. needRestart := false
  842. seenEmail := make(map[string]struct{}, len(emails))
  843. for _, email := range emails {
  844. if email == "" {
  845. continue
  846. }
  847. key := strings.ToLower(email)
  848. if _, ok := seenEmail[key]; ok {
  849. continue
  850. }
  851. seenEmail[key] = struct{}{}
  852. rec, err := s.GetRecordByEmail(nil, email)
  853. if err != nil {
  854. result.Errors = append(result.Errors, fmt.Sprintf("%s: %v", email, err))
  855. continue
  856. }
  857. currentIds, err := s.GetInboundIdsForRecord(rec.Id)
  858. if err != nil {
  859. result.Errors = append(result.Errors, fmt.Sprintf("%s: %v", email, err))
  860. continue
  861. }
  862. intersection := make([]int, 0, len(currentIds))
  863. for _, id := range currentIds {
  864. if _, ok := requested[id]; ok {
  865. intersection = append(intersection, id)
  866. }
  867. }
  868. if len(intersection) == 0 {
  869. result.Skipped = append(result.Skipped, rec.Email)
  870. continue
  871. }
  872. nr, err := s.Detach(inboundSvc, rec.Id, intersection)
  873. if err != nil {
  874. result.Errors = append(result.Errors, fmt.Sprintf("%s: %v", rec.Email, err))
  875. continue
  876. }
  877. if nr {
  878. needRestart = true
  879. }
  880. result.Detached = append(result.Detached, rec.Email)
  881. }
  882. return result, needRestart, nil
  883. }
  884. func (s *ClientService) DetachByEmailMany(inboundSvc *InboundService, email string, inboundIds []int) (bool, error) {
  885. if email == "" {
  886. return false, common.NewError("client email is required")
  887. }
  888. rec, err := s.GetRecordByEmail(nil, email)
  889. if err != nil {
  890. return false, err
  891. }
  892. return s.Detach(inboundSvc, rec.Id, inboundIds)
  893. }
  894. func (s *ClientService) DeleteByEmail(inboundSvc *InboundService, email string, keepTraffic bool) (bool, error) {
  895. if email == "" {
  896. return false, common.NewError("client email is required")
  897. }
  898. rec, err := s.GetRecordByEmail(nil, email)
  899. if err == nil {
  900. return s.Delete(inboundSvc, rec.Id, keepTraffic)
  901. }
  902. if !errors.Is(err, gorm.ErrRecordNotFound) {
  903. return false, err
  904. }
  905. inboundIds, idsErr := s.findInboundIdsByClientEmail(email)
  906. if idsErr != nil {
  907. return false, idsErr
  908. }
  909. if len(inboundIds) == 0 {
  910. return false, common.NewError(fmt.Sprintf("client %q not found in any inbound or client record", email))
  911. }
  912. needRestart := false
  913. for _, ibId := range inboundIds {
  914. nr, delErr := s.DelInboundClientByEmail(inboundSvc, ibId, email)
  915. if delErr != nil {
  916. return needRestart, delErr
  917. }
  918. if nr {
  919. needRestart = true
  920. }
  921. }
  922. if !keepTraffic {
  923. db := database.GetDB()
  924. if err := db.Where("email = ?", email).Delete(&xray.ClientTraffic{}).Error; err != nil {
  925. return needRestart, err
  926. }
  927. if err := db.Where("client_email = ?", email).Delete(&model.InboundClientIps{}).Error; err != nil {
  928. return needRestart, err
  929. }
  930. }
  931. return needRestart, nil
  932. }
  933. // findInboundIdsByClientEmail returns every inbound whose settings.clients[]
  934. // JSON contains an entry with the given email. Driver-portable (no JSON
  935. // operators) by parsing in Go — fine for the rare fallback path.
  936. func (s *ClientService) findInboundIdsByClientEmail(email string) ([]int, error) {
  937. var inbounds []model.Inbound
  938. if err := database.GetDB().
  939. Select("id, settings").
  940. Where("settings LIKE ?", "%"+email+"%").
  941. Find(&inbounds).Error; err != nil {
  942. return nil, err
  943. }
  944. out := make([]int, 0, len(inbounds))
  945. for _, ib := range inbounds {
  946. var settings map[string]any
  947. if err := json.Unmarshal([]byte(ib.Settings), &settings); err != nil {
  948. continue
  949. }
  950. clients, ok := settings["clients"].([]any)
  951. if !ok {
  952. continue
  953. }
  954. for _, c := range clients {
  955. cm, ok := c.(map[string]any)
  956. if !ok {
  957. continue
  958. }
  959. if cEmail, _ := cm["email"].(string); cEmail == email {
  960. out = append(out, ib.Id)
  961. break
  962. }
  963. }
  964. }
  965. return out, nil
  966. }
  967. func (s *ClientService) UpdateByEmail(inboundSvc *InboundService, email string, updated model.Client) (bool, error) {
  968. if email == "" {
  969. return false, common.NewError("client email is required")
  970. }
  971. rec, err := s.GetRecordByEmail(nil, email)
  972. if err != nil {
  973. return false, err
  974. }
  975. return s.Update(inboundSvc, rec.Id, updated)
  976. }
  977. func (s *ClientService) ResetTrafficByEmail(inboundSvc *InboundService, email string) (bool, error) {
  978. if email == "" {
  979. return false, common.NewError("client email is required")
  980. }
  981. rec, err := s.GetRecordByEmail(nil, email)
  982. if err != nil {
  983. return false, err
  984. }
  985. inboundIds, err := s.GetInboundIdsForRecord(rec.Id)
  986. if err != nil {
  987. return false, err
  988. }
  989. if len(inboundIds) == 0 {
  990. if rErr := inboundSvc.ResetClientTrafficByEmail(email); rErr != nil {
  991. return false, rErr
  992. }
  993. return false, nil
  994. }
  995. needRestart := false
  996. for _, ibId := range inboundIds {
  997. nr, rErr := inboundSvc.ResetClientTraffic(ibId, email)
  998. if rErr != nil {
  999. return needRestart, rErr
  1000. }
  1001. if nr {
  1002. needRestart = true
  1003. }
  1004. }
  1005. return needRestart, nil
  1006. }
  1007. // ClientSlim is the row-shape used by the clients page. It drops fields the
  1008. // table never reads (UUID, password, auth, flow, security, reverse, tgId)
  1009. // so the list payload stays compact even when the panel manages thousands
  1010. // of clients. Modals that need the full record still call /get/:email.
  1011. type ClientSlim struct {
  1012. Email string `json:"email"`
  1013. SubID string `json:"subId"`
  1014. Enable bool `json:"enable"`
  1015. TotalGB int64 `json:"totalGB"`
  1016. ExpiryTime int64 `json:"expiryTime"`
  1017. LimitIP int `json:"limitIp"`
  1018. Reset int `json:"reset"`
  1019. Group string `json:"group,omitempty"`
  1020. Comment string `json:"comment,omitempty"`
  1021. InboundIds []int `json:"inboundIds"`
  1022. Traffic *xray.ClientTraffic `json:"traffic,omitempty"`
  1023. CreatedAt int64 `json:"createdAt"`
  1024. UpdatedAt int64 `json:"updatedAt"`
  1025. }
  1026. // ClientPageParams are the query params accepted by /panel/api/clients/list/paged.
  1027. // All fields are optional — the empty value means "no filter" / defaults.
  1028. //
  1029. // Filter / Protocol / Inbound accept either a single value or a comma-separated
  1030. // list; matching is OR within a field and AND across fields. The numeric range
  1031. // fields treat 0 as "unset" on the lower bound and 0 (or negative) as
  1032. // "unbounded" on the upper bound.
  1033. type ClientPageParams struct {
  1034. Page int `form:"page"`
  1035. PageSize int `form:"pageSize"`
  1036. Search string `form:"search"`
  1037. Filter string `form:"filter"`
  1038. Protocol string `form:"protocol"`
  1039. Inbound string `form:"inbound"`
  1040. Sort string `form:"sort"`
  1041. Order string `form:"order"`
  1042. ExpiryFrom int64 `form:"expiryFrom"`
  1043. ExpiryTo int64 `form:"expiryTo"`
  1044. UsageFrom int64 `form:"usageFrom"`
  1045. UsageTo int64 `form:"usageTo"`
  1046. AutoRenew string `form:"autoRenew"`
  1047. HasTgID string `form:"hasTgId"`
  1048. HasComment string `form:"hasComment"`
  1049. Group string `form:"group"`
  1050. }
  1051. // ClientPageResponse is the shape returned by ListPaged. `Total` is the
  1052. // row count in the DB; `Filtered` is the count after Search/Filter/Protocol
  1053. // were applied, before pagination. The page contains at most PageSize items.
  1054. // Summary is computed across the full DB row set so dashboard counters
  1055. // on the clients page stay stable as the user paginates/filters.
  1056. type ClientPageResponse struct {
  1057. Items []ClientSlim `json:"items"`
  1058. Total int `json:"total"`
  1059. Filtered int `json:"filtered"`
  1060. Page int `json:"page"`
  1061. PageSize int `json:"pageSize"`
  1062. Summary ClientsSummary `json:"summary"`
  1063. Groups []string `json:"groups"`
  1064. }
  1065. // ClientsSummary collects per-bucket counts plus the matching email lists so
  1066. // the clients page can render the dashboard stat cards and their hover
  1067. // popovers without shipping the full client array.
  1068. type ClientsSummary struct {
  1069. Total int `json:"total"`
  1070. Active int `json:"active"`
  1071. Online []string `json:"online"`
  1072. Depleted []string `json:"depleted"`
  1073. Expiring []string `json:"expiring"`
  1074. Deactive []string `json:"deactive"`
  1075. }
  1076. const (
  1077. clientPageDefaultSize = 25
  1078. clientPageMaxSize = 200
  1079. )
  1080. // ListPaged loads every client (with traffic + attachments) into memory,
  1081. // applies the requested filter / search / protocol predicates, sorts, and
  1082. // returns the requested page along with total and filtered counts. The DB
  1083. // query itself is unchanged from List(); the win is that the response
  1084. // only carries 25-ish slim rows over the wire instead of all 2000 full
  1085. // records, which on real panels was the dominant cost.
  1086. func (s *ClientService) ListPaged(inboundSvc *InboundService, settingSvc *SettingService, params ClientPageParams) (*ClientPageResponse, error) {
  1087. all, err := s.List()
  1088. if err != nil {
  1089. return nil, err
  1090. }
  1091. total := len(all)
  1092. pageSize := params.PageSize
  1093. if pageSize <= 0 {
  1094. pageSize = clientPageDefaultSize
  1095. }
  1096. if pageSize > clientPageMaxSize {
  1097. pageSize = clientPageMaxSize
  1098. }
  1099. page := params.Page
  1100. if page <= 0 {
  1101. page = 1
  1102. }
  1103. protocols := parseCSVStrings(params.Protocol)
  1104. inboundIDs := parseCSVInts(params.Inbound)
  1105. buckets := parseCSVStrings(params.Filter)
  1106. var protocolByInbound map[int]string
  1107. if len(protocols) > 0 {
  1108. inbounds, err := inboundSvc.GetAllInbounds()
  1109. if err == nil {
  1110. protocolByInbound = make(map[int]string, len(inbounds))
  1111. for _, ib := range inbounds {
  1112. protocolByInbound[ib.Id] = string(ib.Protocol)
  1113. }
  1114. }
  1115. }
  1116. onlines := inboundSvc.GetOnlineClients()
  1117. onlineSet := make(map[string]struct{}, len(onlines))
  1118. for _, e := range onlines {
  1119. onlineSet[e] = struct{}{}
  1120. }
  1121. var expireDiffMs, trafficDiffBytes int64
  1122. if settingSvc != nil {
  1123. if v, err := settingSvc.GetExpireDiff(); err == nil {
  1124. expireDiffMs = int64(v) * 86400000
  1125. }
  1126. if v, err := settingSvc.GetTrafficDiff(); err == nil {
  1127. trafficDiffBytes = int64(v) * 1073741824
  1128. }
  1129. }
  1130. nowMs := time.Now().UnixMilli()
  1131. summary := buildClientsSummary(all, onlineSet, nowMs, expireDiffMs, trafficDiffBytes)
  1132. needle := strings.ToLower(strings.TrimSpace(params.Search))
  1133. filtered := make([]ClientWithAttachments, 0, len(all))
  1134. for _, c := range all {
  1135. if needle != "" && !clientMatchesSearch(c, needle) {
  1136. continue
  1137. }
  1138. if len(protocols) > 0 && !clientMatchesAnyProtocol(c, protocols, protocolByInbound) {
  1139. continue
  1140. }
  1141. if len(inboundIDs) > 0 && !clientMatchesAnyInbound(c, inboundIDs) {
  1142. continue
  1143. }
  1144. if len(buckets) > 0 && !clientMatchesAnyBucket(c, buckets, onlineSet, nowMs, expireDiffMs, trafficDiffBytes) {
  1145. continue
  1146. }
  1147. if !clientMatchesExpiryRange(c, params.ExpiryFrom, params.ExpiryTo) {
  1148. continue
  1149. }
  1150. if !clientMatchesUsageRange(c, params.UsageFrom, params.UsageTo) {
  1151. continue
  1152. }
  1153. if !clientMatchesAutoRenew(c, params.AutoRenew) {
  1154. continue
  1155. }
  1156. if !clientMatchesHasTgID(c, params.HasTgID) {
  1157. continue
  1158. }
  1159. if !clientMatchesHasComment(c, params.HasComment) {
  1160. continue
  1161. }
  1162. if !clientMatchesAnyGroup(c, params.Group) {
  1163. continue
  1164. }
  1165. filtered = append(filtered, c)
  1166. }
  1167. sortClients(filtered, params.Sort, params.Order)
  1168. filteredCount := len(filtered)
  1169. start := (page - 1) * pageSize
  1170. end := start + pageSize
  1171. if start > filteredCount {
  1172. start = filteredCount
  1173. }
  1174. if end > filteredCount {
  1175. end = filteredCount
  1176. }
  1177. pageRows := filtered[start:end]
  1178. items := make([]ClientSlim, 0, len(pageRows))
  1179. for _, c := range pageRows {
  1180. items = append(items, toClientSlim(c))
  1181. }
  1182. groupRows, gErr := s.ListGroups()
  1183. if gErr != nil {
  1184. return nil, gErr
  1185. }
  1186. groups := make([]string, 0, len(groupRows))
  1187. for _, g := range groupRows {
  1188. groups = append(groups, g.Name)
  1189. }
  1190. return &ClientPageResponse{
  1191. Items: items,
  1192. Total: total,
  1193. Filtered: filteredCount,
  1194. Page: page,
  1195. PageSize: pageSize,
  1196. Summary: summary,
  1197. Groups: groups,
  1198. }, nil
  1199. }
  1200. type GroupSummary struct {
  1201. Name string `json:"name"`
  1202. ClientCount int `json:"clientCount"`
  1203. }
  1204. func (s *ClientService) ListGroups() ([]GroupSummary, error) {
  1205. db := database.GetDB()
  1206. var derived []GroupSummary
  1207. if err := db.Model(&model.ClientRecord{}).
  1208. Select("group_name AS name, COUNT(*) AS client_count").
  1209. Where("group_name <> ''").
  1210. Group("group_name").
  1211. Scan(&derived).Error; err != nil {
  1212. return nil, err
  1213. }
  1214. var stored []model.ClientGroup
  1215. if err := db.Find(&stored).Error; err != nil {
  1216. return nil, err
  1217. }
  1218. merged := make(map[string]int, len(derived)+len(stored))
  1219. for _, g := range stored {
  1220. merged[g.Name] = 0
  1221. }
  1222. for _, g := range derived {
  1223. merged[g.Name] = g.ClientCount
  1224. }
  1225. out := make([]GroupSummary, 0, len(merged))
  1226. for name, count := range merged {
  1227. out = append(out, GroupSummary{Name: name, ClientCount: count})
  1228. }
  1229. sort.Slice(out, func(i, j int) bool {
  1230. return strings.ToLower(out[i].Name) < strings.ToLower(out[j].Name)
  1231. })
  1232. return out, nil
  1233. }
  1234. func (s *ClientService) EmailsByGroup(name string) ([]string, error) {
  1235. name = strings.TrimSpace(name)
  1236. if name == "" {
  1237. return []string{}, nil
  1238. }
  1239. db := database.GetDB()
  1240. var emails []string
  1241. if err := db.Model(&model.ClientRecord{}).
  1242. Where("group_name = ?", name).
  1243. Order("email ASC").
  1244. Pluck("email", &emails).Error; err != nil {
  1245. return nil, err
  1246. }
  1247. if emails == nil {
  1248. emails = []string{}
  1249. }
  1250. return emails, nil
  1251. }
  1252. func (s *ClientService) BulkResetTraffic(inboundSvc *InboundService, emails []string) (int, error) {
  1253. if len(emails) == 0 {
  1254. return 0, nil
  1255. }
  1256. count := 0
  1257. for _, email := range emails {
  1258. if _, err := s.ResetTrafficByEmail(inboundSvc, email); err != nil {
  1259. return count, err
  1260. }
  1261. count++
  1262. }
  1263. return count, nil
  1264. }
  1265. func (s *ClientService) CreateGroup(name string) error {
  1266. name = strings.TrimSpace(name)
  1267. if name == "" {
  1268. return common.NewError("group name is required")
  1269. }
  1270. db := database.GetDB()
  1271. var count int64
  1272. if err := db.Model(&model.ClientGroup{}).Where("name = ?", name).Count(&count).Error; err != nil {
  1273. return err
  1274. }
  1275. if count > 0 {
  1276. return common.NewError("group already exists")
  1277. }
  1278. return db.Create(&model.ClientGroup{Name: name}).Error
  1279. }
  1280. func (s *ClientService) RenameGroup(oldName, newName string) (int, error) {
  1281. oldName = strings.TrimSpace(oldName)
  1282. newName = strings.TrimSpace(newName)
  1283. if oldName == "" {
  1284. return 0, common.NewError("old group name is required")
  1285. }
  1286. if newName == "" {
  1287. return 0, common.NewError("new group name is required")
  1288. }
  1289. if oldName == newName {
  1290. return 0, nil
  1291. }
  1292. return s.replaceGroupValue(oldName, newName)
  1293. }
  1294. func (s *ClientService) DeleteGroup(name string) (int, error) {
  1295. name = strings.TrimSpace(name)
  1296. if name == "" {
  1297. return 0, common.NewError("group name is required")
  1298. }
  1299. return s.replaceGroupValue(name, "")
  1300. }
  1301. func (s *ClientService) AssignGroup(emails []string, group string) (int, error) {
  1302. group = strings.TrimSpace(group)
  1303. if len(emails) == 0 {
  1304. return 0, nil
  1305. }
  1306. db := database.GetDB()
  1307. if group != "" {
  1308. var exists int64
  1309. if err := db.Model(&model.ClientGroup{}).Where("name = ?", group).Count(&exists).Error; err != nil {
  1310. return 0, err
  1311. }
  1312. if exists == 0 {
  1313. var derived int64
  1314. if err := db.Model(&model.ClientRecord{}).Where("group_name = ?", group).Count(&derived).Error; err != nil {
  1315. return 0, err
  1316. }
  1317. if derived == 0 {
  1318. if err := db.Create(&model.ClientGroup{Name: group}).Error; err != nil {
  1319. return 0, err
  1320. }
  1321. }
  1322. }
  1323. }
  1324. var records []model.ClientRecord
  1325. if err := db.Where("email IN ?", emails).Find(&records).Error; err != nil {
  1326. return 0, err
  1327. }
  1328. if len(records) == 0 {
  1329. return 0, nil
  1330. }
  1331. affectedEmails := make([]string, 0, len(records))
  1332. for _, r := range records {
  1333. affectedEmails = append(affectedEmails, r.Email)
  1334. }
  1335. tx := db.Begin()
  1336. if err := tx.Model(&model.ClientRecord{}).
  1337. Where("email IN ?", affectedEmails).
  1338. UpdateColumn("group_name", group).Error; err != nil {
  1339. tx.Rollback()
  1340. return 0, err
  1341. }
  1342. var inboundIDs []int
  1343. if err := tx.Table("client_inbounds").
  1344. Joins("JOIN clients ON clients.id = client_inbounds.client_id").
  1345. Where("clients.email IN ?", affectedEmails).
  1346. Distinct("client_inbounds.inbound_id").
  1347. Pluck("inbound_id", &inboundIDs).Error; err != nil {
  1348. tx.Rollback()
  1349. return 0, err
  1350. }
  1351. emailSet := make(map[string]struct{}, len(affectedEmails))
  1352. for _, e := range affectedEmails {
  1353. emailSet[e] = struct{}{}
  1354. }
  1355. for _, ibID := range inboundIDs {
  1356. var ib model.Inbound
  1357. if err := tx.First(&ib, ibID).Error; err != nil {
  1358. tx.Rollback()
  1359. return 0, err
  1360. }
  1361. var settings map[string]any
  1362. if err := json.Unmarshal([]byte(ib.Settings), &settings); err != nil {
  1363. continue
  1364. }
  1365. clients, ok := settings["clients"].([]any)
  1366. if !ok {
  1367. continue
  1368. }
  1369. modified := false
  1370. for i := range clients {
  1371. cm, ok := clients[i].(map[string]any)
  1372. if !ok {
  1373. continue
  1374. }
  1375. email, _ := cm["email"].(string)
  1376. if _, hit := emailSet[email]; !hit {
  1377. continue
  1378. }
  1379. if group == "" {
  1380. delete(cm, "group")
  1381. } else {
  1382. cm["group"] = group
  1383. }
  1384. clients[i] = cm
  1385. modified = true
  1386. }
  1387. if modified {
  1388. settings["clients"] = clients
  1389. newSettings, err := json.Marshal(settings)
  1390. if err != nil {
  1391. continue
  1392. }
  1393. ib.Settings = string(newSettings)
  1394. if err := tx.Save(&ib).Error; err != nil {
  1395. tx.Rollback()
  1396. return 0, err
  1397. }
  1398. }
  1399. }
  1400. if err := tx.Commit().Error; err != nil {
  1401. return 0, err
  1402. }
  1403. return len(records), nil
  1404. }
  1405. func (s *ClientService) replaceGroupValue(oldName, newName string) (int, error) {
  1406. db := database.GetDB()
  1407. if newName == "" {
  1408. if err := db.Where("name = ?", oldName).Delete(&model.ClientGroup{}).Error; err != nil {
  1409. return 0, err
  1410. }
  1411. } else {
  1412. if err := db.Model(&model.ClientGroup{}).Where("name = ?", oldName).Update("name", newName).Error; err != nil {
  1413. return 0, err
  1414. }
  1415. }
  1416. var records []model.ClientRecord
  1417. if err := db.Where("group_name = ?", oldName).Find(&records).Error; err != nil {
  1418. return 0, err
  1419. }
  1420. if len(records) == 0 {
  1421. return 0, nil
  1422. }
  1423. affectedEmails := make([]string, 0, len(records))
  1424. for _, r := range records {
  1425. affectedEmails = append(affectedEmails, r.Email)
  1426. }
  1427. tx := db.Begin()
  1428. if err := tx.Model(&model.ClientRecord{}).
  1429. Where("group_name = ?", oldName).
  1430. UpdateColumn("group_name", newName).Error; err != nil {
  1431. tx.Rollback()
  1432. return 0, err
  1433. }
  1434. var inboundIDs []int
  1435. if err := tx.Table("client_inbounds").
  1436. Joins("JOIN clients ON clients.id = client_inbounds.client_id").
  1437. Where("clients.email IN ?", affectedEmails).
  1438. Distinct("client_inbounds.inbound_id").
  1439. Pluck("inbound_id", &inboundIDs).Error; err != nil {
  1440. tx.Rollback()
  1441. return 0, err
  1442. }
  1443. for _, ibID := range inboundIDs {
  1444. var ib model.Inbound
  1445. if err := tx.First(&ib, ibID).Error; err != nil {
  1446. tx.Rollback()
  1447. return 0, err
  1448. }
  1449. var settings map[string]any
  1450. if err := json.Unmarshal([]byte(ib.Settings), &settings); err != nil {
  1451. continue
  1452. }
  1453. clients, ok := settings["clients"].([]any)
  1454. if !ok {
  1455. continue
  1456. }
  1457. modified := false
  1458. for i := range clients {
  1459. cm, ok := clients[i].(map[string]any)
  1460. if !ok {
  1461. continue
  1462. }
  1463. if g, ok := cm["group"].(string); ok && g == oldName {
  1464. if newName == "" {
  1465. delete(cm, "group")
  1466. } else {
  1467. cm["group"] = newName
  1468. }
  1469. clients[i] = cm
  1470. modified = true
  1471. }
  1472. }
  1473. if modified {
  1474. settings["clients"] = clients
  1475. newSettings, err := json.Marshal(settings)
  1476. if err != nil {
  1477. continue
  1478. }
  1479. ib.Settings = string(newSettings)
  1480. if err := tx.Save(&ib).Error; err != nil {
  1481. tx.Rollback()
  1482. return 0, err
  1483. }
  1484. }
  1485. }
  1486. if err := tx.Commit().Error; err != nil {
  1487. return 0, err
  1488. }
  1489. return len(records), nil
  1490. }
  1491. func buildClientsSummary(all []ClientWithAttachments, onlineSet map[string]struct{}, nowMs, expireDiffMs, trafficDiffBytes int64) ClientsSummary {
  1492. s := ClientsSummary{
  1493. Total: len(all),
  1494. Online: []string{},
  1495. Depleted: []string{},
  1496. Expiring: []string{},
  1497. Deactive: []string{},
  1498. }
  1499. for _, c := range all {
  1500. used := int64(0)
  1501. if c.Traffic != nil {
  1502. used = c.Traffic.Up + c.Traffic.Down
  1503. }
  1504. exhausted := c.TotalGB > 0 && used >= c.TotalGB
  1505. expired := c.ExpiryTime > 0 && c.ExpiryTime <= nowMs
  1506. if c.Enable {
  1507. if _, ok := onlineSet[c.Email]; ok {
  1508. s.Online = append(s.Online, c.Email)
  1509. }
  1510. }
  1511. if exhausted || expired {
  1512. s.Depleted = append(s.Depleted, c.Email)
  1513. continue
  1514. }
  1515. if !c.Enable {
  1516. s.Deactive = append(s.Deactive, c.Email)
  1517. continue
  1518. }
  1519. nearExpiry := c.ExpiryTime > 0 && c.ExpiryTime-nowMs < expireDiffMs
  1520. nearLimit := c.TotalGB > 0 && c.TotalGB-used < trafficDiffBytes
  1521. if nearExpiry || nearLimit {
  1522. s.Expiring = append(s.Expiring, c.Email)
  1523. } else {
  1524. s.Active++
  1525. }
  1526. }
  1527. return s
  1528. }
  1529. func toClientSlim(c ClientWithAttachments) ClientSlim {
  1530. return ClientSlim{
  1531. Email: c.Email,
  1532. SubID: c.SubID,
  1533. Enable: c.Enable,
  1534. TotalGB: c.TotalGB,
  1535. ExpiryTime: c.ExpiryTime,
  1536. LimitIP: c.LimitIP,
  1537. Reset: c.Reset,
  1538. Group: c.Group,
  1539. Comment: c.Comment,
  1540. InboundIds: c.InboundIds,
  1541. Traffic: c.Traffic,
  1542. CreatedAt: c.CreatedAt,
  1543. UpdatedAt: c.UpdatedAt,
  1544. }
  1545. }
  1546. func clientMatchesSearch(c ClientWithAttachments, needle string) bool {
  1547. if needle == "" {
  1548. return true
  1549. }
  1550. candidates := [...]string{c.Email, c.SubID, c.Comment, c.UUID, c.Password, c.Auth}
  1551. for _, v := range candidates {
  1552. if v != "" && strings.Contains(strings.ToLower(v), needle) {
  1553. return true
  1554. }
  1555. }
  1556. return false
  1557. }
  1558. // parseCSVStrings splits a comma-separated list, trims/lower-cases each item,
  1559. // and drops blanks. Returns nil when the input has no usable entries — the
  1560. // caller can then skip the predicate entirely.
  1561. func parseCSVStrings(raw string) []string {
  1562. if raw == "" {
  1563. return nil
  1564. }
  1565. parts := strings.Split(raw, ",")
  1566. out := make([]string, 0, len(parts))
  1567. for _, p := range parts {
  1568. s := strings.ToLower(strings.TrimSpace(p))
  1569. if s != "" {
  1570. out = append(out, s)
  1571. }
  1572. }
  1573. if len(out) == 0 {
  1574. return nil
  1575. }
  1576. return out
  1577. }
  1578. // parseCSVInts is parseCSVStrings for positive integer IDs; non-numeric or
  1579. // non-positive entries are silently dropped.
  1580. func parseCSVInts(raw string) []int {
  1581. if raw == "" {
  1582. return nil
  1583. }
  1584. parts := strings.Split(raw, ",")
  1585. out := make([]int, 0, len(parts))
  1586. for _, p := range parts {
  1587. s := strings.TrimSpace(p)
  1588. if s == "" {
  1589. continue
  1590. }
  1591. if n, err := strconv.Atoi(s); err == nil && n > 0 {
  1592. out = append(out, n)
  1593. }
  1594. }
  1595. if len(out) == 0 {
  1596. return nil
  1597. }
  1598. return out
  1599. }
  1600. func clientMatchesAnyProtocol(c ClientWithAttachments, protocols []string, byInbound map[int]string) bool {
  1601. for _, id := range c.InboundIds {
  1602. p := byInbound[id]
  1603. if p == "" {
  1604. continue
  1605. }
  1606. if slices.Contains(protocols, strings.ToLower(p)) {
  1607. return true
  1608. }
  1609. }
  1610. return false
  1611. }
  1612. func clientMatchesAnyInbound(c ClientWithAttachments, inboundIds []int) bool {
  1613. for _, id := range c.InboundIds {
  1614. if slices.Contains(inboundIds, id) {
  1615. return true
  1616. }
  1617. }
  1618. return false
  1619. }
  1620. func clientMatchesAnyBucket(c ClientWithAttachments, buckets []string, onlineSet map[string]struct{}, nowMs, expireDiffMs, trafficDiffBytes int64) bool {
  1621. for _, b := range buckets {
  1622. if clientMatchesBucket(c, b, onlineSet, nowMs, expireDiffMs, trafficDiffBytes) {
  1623. return true
  1624. }
  1625. }
  1626. return false
  1627. }
  1628. func clientMatchesExpiryRange(c ClientWithAttachments, fromMs, toMs int64) bool {
  1629. if fromMs <= 0 && toMs <= 0 {
  1630. return true
  1631. }
  1632. // expiryTime of 0 means "never expires"; treat it as outside any bounded
  1633. // range so users filtering by date see only clients with concrete expiries.
  1634. if c.ExpiryTime == 0 {
  1635. return false
  1636. }
  1637. // Negative expiry is the "delayed start" sentinel; same treatment as never.
  1638. if c.ExpiryTime < 0 {
  1639. return false
  1640. }
  1641. if fromMs > 0 && c.ExpiryTime < fromMs {
  1642. return false
  1643. }
  1644. if toMs > 0 && c.ExpiryTime > toMs {
  1645. return false
  1646. }
  1647. return true
  1648. }
  1649. func clientMatchesUsageRange(c ClientWithAttachments, fromBytes, toBytes int64) bool {
  1650. if fromBytes <= 0 && toBytes <= 0 {
  1651. return true
  1652. }
  1653. used := int64(0)
  1654. if c.Traffic != nil {
  1655. used = c.Traffic.Up + c.Traffic.Down
  1656. }
  1657. if fromBytes > 0 && used < fromBytes {
  1658. return false
  1659. }
  1660. if toBytes > 0 && used > toBytes {
  1661. return false
  1662. }
  1663. return true
  1664. }
  1665. func clientMatchesAutoRenew(c ClientWithAttachments, mode string) bool {
  1666. switch strings.ToLower(strings.TrimSpace(mode)) {
  1667. case "on":
  1668. return c.Reset > 0
  1669. case "off":
  1670. return c.Reset <= 0
  1671. }
  1672. return true
  1673. }
  1674. func clientMatchesHasTgID(c ClientWithAttachments, mode string) bool {
  1675. switch strings.ToLower(strings.TrimSpace(mode)) {
  1676. case "yes":
  1677. return c.TgID != 0
  1678. case "no":
  1679. return c.TgID == 0
  1680. }
  1681. return true
  1682. }
  1683. func clientMatchesHasComment(c ClientWithAttachments, mode string) bool {
  1684. switch strings.ToLower(strings.TrimSpace(mode)) {
  1685. case "yes":
  1686. return strings.TrimSpace(c.Comment) != ""
  1687. case "no":
  1688. return strings.TrimSpace(c.Comment) == ""
  1689. }
  1690. return true
  1691. }
  1692. func clientMatchesAnyGroup(c ClientWithAttachments, csv string) bool {
  1693. groups := parseCSVStrings(csv)
  1694. if len(groups) == 0 {
  1695. return true
  1696. }
  1697. current := strings.TrimSpace(c.Group)
  1698. for _, g := range groups {
  1699. if g == "" {
  1700. if current == "" {
  1701. return true
  1702. }
  1703. continue
  1704. }
  1705. if strings.EqualFold(g, current) {
  1706. return true
  1707. }
  1708. }
  1709. return false
  1710. }
  1711. func clientMatchesBucket(c ClientWithAttachments, bucket string, onlineSet map[string]struct{}, nowMs, expireDiffMs, trafficDiffBytes int64) bool {
  1712. if bucket == "" {
  1713. return true
  1714. }
  1715. used := int64(0)
  1716. if c.Traffic != nil {
  1717. used = c.Traffic.Up + c.Traffic.Down
  1718. }
  1719. exhausted := c.TotalGB > 0 && used >= c.TotalGB
  1720. expired := c.ExpiryTime > 0 && c.ExpiryTime <= nowMs
  1721. switch bucket {
  1722. case "online":
  1723. if onlineSet == nil {
  1724. return false
  1725. }
  1726. _, ok := onlineSet[c.Email]
  1727. return ok && c.Enable
  1728. case "depleted":
  1729. return exhausted || expired
  1730. case "deactive":
  1731. return !c.Enable
  1732. case "active":
  1733. return c.Enable && !exhausted && !expired
  1734. case "expiring":
  1735. if !c.Enable || exhausted || expired {
  1736. return false
  1737. }
  1738. nearExpiry := c.ExpiryTime > 0 && c.ExpiryTime-nowMs < expireDiffMs
  1739. nearLimit := c.TotalGB > 0 && c.TotalGB-used < trafficDiffBytes
  1740. return nearExpiry || nearLimit
  1741. }
  1742. return true
  1743. }
  1744. func sortClients(rows []ClientWithAttachments, sortKey, order string) {
  1745. if sortKey == "" {
  1746. return
  1747. }
  1748. desc := order == "descend"
  1749. less := func(i, j int) bool {
  1750. a, b := rows[i], rows[j]
  1751. switch sortKey {
  1752. case "enable":
  1753. if a.Enable == b.Enable {
  1754. return false
  1755. }
  1756. return !a.Enable && b.Enable
  1757. case "email":
  1758. return strings.ToLower(a.Email) < strings.ToLower(b.Email)
  1759. case "inboundIds":
  1760. return len(a.InboundIds) < len(b.InboundIds)
  1761. case "traffic":
  1762. ua := int64(0)
  1763. if a.Traffic != nil {
  1764. ua = a.Traffic.Up + a.Traffic.Down
  1765. }
  1766. ub := int64(0)
  1767. if b.Traffic != nil {
  1768. ub = b.Traffic.Up + b.Traffic.Down
  1769. }
  1770. return ua < ub
  1771. case "remaining":
  1772. ra := int64(1<<62 - 1)
  1773. if a.TotalGB > 0 {
  1774. used := int64(0)
  1775. if a.Traffic != nil {
  1776. used = a.Traffic.Up + a.Traffic.Down
  1777. }
  1778. ra = a.TotalGB - used
  1779. }
  1780. rb := int64(1<<62 - 1)
  1781. if b.TotalGB > 0 {
  1782. used := int64(0)
  1783. if b.Traffic != nil {
  1784. used = b.Traffic.Up + b.Traffic.Down
  1785. }
  1786. rb = b.TotalGB - used
  1787. }
  1788. return ra < rb
  1789. case "expiryTime":
  1790. ea := int64(1<<62 - 1)
  1791. if a.ExpiryTime > 0 {
  1792. ea = a.ExpiryTime
  1793. }
  1794. eb := int64(1<<62 - 1)
  1795. if b.ExpiryTime > 0 {
  1796. eb = b.ExpiryTime
  1797. }
  1798. return ea < eb
  1799. case "createdAt":
  1800. if a.CreatedAt == b.CreatedAt {
  1801. return a.Id < b.Id
  1802. }
  1803. return a.CreatedAt < b.CreatedAt
  1804. case "updatedAt":
  1805. if a.UpdatedAt == b.UpdatedAt {
  1806. return a.Id < b.Id
  1807. }
  1808. return a.UpdatedAt < b.UpdatedAt
  1809. case "lastOnline":
  1810. la := int64(0)
  1811. if a.Traffic != nil {
  1812. la = a.Traffic.LastOnline
  1813. }
  1814. lb := int64(0)
  1815. if b.Traffic != nil {
  1816. lb = b.Traffic.LastOnline
  1817. }
  1818. if la == lb {
  1819. return a.Id < b.Id
  1820. }
  1821. return la < lb
  1822. }
  1823. return false
  1824. }
  1825. sort.SliceStable(rows, func(i, j int) bool {
  1826. if desc {
  1827. return less(j, i)
  1828. }
  1829. return less(i, j)
  1830. })
  1831. }
  1832. // BulkAdjustResult is returned by BulkAdjust to report how many clients were
  1833. // successfully updated and which were skipped (typically because the field
  1834. // being adjusted was unlimited for that client) or failed.
  1835. type BulkAdjustResult struct {
  1836. Adjusted int `json:"adjusted"`
  1837. Skipped []BulkAdjustReport `json:"skipped,omitempty"`
  1838. }
  1839. type BulkAdjustReport struct {
  1840. Email string `json:"email"`
  1841. Reason string `json:"reason"`
  1842. }
  1843. type bulkAdjustEntry struct {
  1844. record *model.ClientRecord
  1845. applyExpiry bool
  1846. newExpiry int64
  1847. applyTotal bool
  1848. newTotal int64
  1849. }
  1850. // BulkAdjust shifts ExpiryTime by addDays (days) and TotalGB by addBytes
  1851. // for every email in the list. Clients whose corresponding field is
  1852. // unlimited (0) are skipped — bulk extend should not accidentally
  1853. // limit an unlimited client. addDays and addBytes may be negative.
  1854. //
  1855. // Like BulkDelete, the work is grouped by inbound so each inbound's
  1856. // settings JSON is parsed and written exactly once regardless of how
  1857. // many target emails it contains.
  1858. func (s *ClientService) BulkAdjust(inboundSvc *InboundService, emails []string, addDays int, addBytes int64) (BulkAdjustResult, bool, error) {
  1859. result := BulkAdjustResult{}
  1860. if len(emails) == 0 {
  1861. return result, false, nil
  1862. }
  1863. if addDays == 0 && addBytes == 0 {
  1864. return result, false, common.NewError("no adjustment specified")
  1865. }
  1866. addExpiryMs := int64(addDays) * 24 * 60 * 60 * 1000
  1867. seen := map[string]struct{}{}
  1868. cleanEmails := make([]string, 0, len(emails))
  1869. for _, e := range emails {
  1870. e = strings.TrimSpace(e)
  1871. if e == "" {
  1872. continue
  1873. }
  1874. if _, ok := seen[e]; ok {
  1875. continue
  1876. }
  1877. seen[e] = struct{}{}
  1878. cleanEmails = append(cleanEmails, e)
  1879. }
  1880. if len(cleanEmails) == 0 {
  1881. return result, false, nil
  1882. }
  1883. db := database.GetDB()
  1884. var records []model.ClientRecord
  1885. if err := db.Where("email IN ?", cleanEmails).Find(&records).Error; err != nil {
  1886. return result, false, err
  1887. }
  1888. recordsByEmail := make(map[string]*model.ClientRecord, len(records))
  1889. for i := range records {
  1890. recordsByEmail[records[i].Email] = &records[i]
  1891. }
  1892. skippedReasons := map[string]string{}
  1893. for _, email := range cleanEmails {
  1894. if _, ok := recordsByEmail[email]; !ok {
  1895. skippedReasons[email] = "client not found"
  1896. }
  1897. }
  1898. plan := map[string]*bulkAdjustEntry{}
  1899. for email, rec := range recordsByEmail {
  1900. entry := &bulkAdjustEntry{record: rec}
  1901. if addDays != 0 {
  1902. switch {
  1903. case rec.ExpiryTime == 0:
  1904. if _, exists := skippedReasons[email]; !exists {
  1905. skippedReasons[email] = "unlimited expiry"
  1906. }
  1907. case rec.ExpiryTime > 0:
  1908. next := rec.ExpiryTime + addExpiryMs
  1909. if next <= 0 {
  1910. if _, exists := skippedReasons[email]; !exists {
  1911. skippedReasons[email] = "reduction exceeds remaining time"
  1912. }
  1913. } else {
  1914. entry.applyExpiry = true
  1915. entry.newExpiry = next
  1916. }
  1917. default:
  1918. next := rec.ExpiryTime - addExpiryMs
  1919. if next >= 0 {
  1920. if _, exists := skippedReasons[email]; !exists {
  1921. skippedReasons[email] = "reduction exceeds delay window"
  1922. }
  1923. } else {
  1924. entry.applyExpiry = true
  1925. entry.newExpiry = next
  1926. }
  1927. }
  1928. }
  1929. if addBytes != 0 {
  1930. if rec.TotalGB == 0 {
  1931. if _, exists := skippedReasons[email]; !exists {
  1932. skippedReasons[email] = "unlimited traffic"
  1933. }
  1934. } else {
  1935. next := max(rec.TotalGB+addBytes, 0)
  1936. entry.applyTotal = true
  1937. entry.newTotal = next
  1938. }
  1939. }
  1940. if entry.applyExpiry || entry.applyTotal {
  1941. plan[email] = entry
  1942. }
  1943. }
  1944. if len(plan) == 0 {
  1945. for email, reason := range skippedReasons {
  1946. result.Skipped = append(result.Skipped, BulkAdjustReport{Email: email, Reason: reason})
  1947. }
  1948. return result, false, nil
  1949. }
  1950. plannedIds := make([]int, 0, len(plan))
  1951. recordIdToEmail := make(map[int]string, len(plan))
  1952. for email, entry := range plan {
  1953. plannedIds = append(plannedIds, entry.record.Id)
  1954. recordIdToEmail[entry.record.Id] = email
  1955. }
  1956. var mappings []model.ClientInbound
  1957. if err := db.Where("client_id IN ?", plannedIds).Find(&mappings).Error; err != nil {
  1958. return result, false, err
  1959. }
  1960. emailsByInbound := map[int][]string{}
  1961. for _, m := range mappings {
  1962. email, ok := recordIdToEmail[m.ClientId]
  1963. if !ok {
  1964. continue
  1965. }
  1966. emailsByInbound[m.InboundId] = append(emailsByInbound[m.InboundId], email)
  1967. }
  1968. needRestart := false
  1969. for inboundId, ibEmails := range emailsByInbound {
  1970. ibRes := s.bulkAdjustInboundClients(inboundSvc, inboundId, ibEmails, plan)
  1971. if ibRes.needRestart {
  1972. needRestart = true
  1973. }
  1974. for email, reason := range ibRes.perEmailSkipped {
  1975. if _, already := skippedReasons[email]; !already {
  1976. skippedReasons[email] = reason
  1977. }
  1978. }
  1979. }
  1980. for email, entry := range plan {
  1981. if _, skipped := skippedReasons[email]; skipped {
  1982. continue
  1983. }
  1984. updates := map[string]any{}
  1985. if entry.applyExpiry {
  1986. updates["expiry_time"] = entry.newExpiry
  1987. }
  1988. if entry.applyTotal {
  1989. updates["total"] = entry.newTotal
  1990. }
  1991. if len(updates) == 0 {
  1992. continue
  1993. }
  1994. if err := db.Model(xray.ClientTraffic{}).Where("email = ?", email).Updates(updates).Error; err != nil {
  1995. if _, already := skippedReasons[email]; !already {
  1996. skippedReasons[email] = err.Error()
  1997. }
  1998. continue
  1999. }
  2000. result.Adjusted++
  2001. }
  2002. for email, reason := range skippedReasons {
  2003. result.Skipped = append(result.Skipped, BulkAdjustReport{Email: email, Reason: reason})
  2004. }
  2005. return result, needRestart, nil
  2006. }
  2007. type bulkInboundAdjustResult struct {
  2008. perEmailSkipped map[string]string
  2009. needRestart bool
  2010. }
  2011. // bulkAdjustInboundClients applies expiry/total deltas to multiple clients
  2012. // inside a single inbound's settings JSON. The xray runtime is updated
  2013. // only for remote-node inbounds; local nodes do not need a notification
  2014. // because the AddUser payload does not include totalGB/expiryTime —
  2015. // changing those fields is identity-preserving and the panel's traffic
  2016. // enforcement loop picks up the new limits from ClientTraffic directly.
  2017. func (s *ClientService) bulkAdjustInboundClients(
  2018. inboundSvc *InboundService,
  2019. inboundId int,
  2020. emails []string,
  2021. plan map[string]*bulkAdjustEntry,
  2022. ) bulkInboundAdjustResult {
  2023. res := bulkInboundAdjustResult{perEmailSkipped: map[string]string{}}
  2024. defer lockInbound(inboundId).Unlock()
  2025. oldInbound, err := inboundSvc.GetInbound(inboundId)
  2026. if err != nil {
  2027. logger.Error("Load Old Data Error")
  2028. for _, e := range emails {
  2029. res.perEmailSkipped[e] = err.Error()
  2030. }
  2031. return res
  2032. }
  2033. var settings map[string]any
  2034. if err := json.Unmarshal([]byte(oldInbound.Settings), &settings); err != nil {
  2035. for _, e := range emails {
  2036. res.perEmailSkipped[e] = err.Error()
  2037. }
  2038. return res
  2039. }
  2040. clientKey := "id"
  2041. switch oldInbound.Protocol {
  2042. case model.Trojan:
  2043. clientKey = "password"
  2044. case model.Shadowsocks:
  2045. clientKey = "email"
  2046. case model.Hysteria:
  2047. clientKey = "auth"
  2048. }
  2049. keyToEmail := make(map[string]string, len(emails))
  2050. for _, email := range emails {
  2051. entry := plan[email]
  2052. if entry == nil {
  2053. res.perEmailSkipped[email] = "client not found"
  2054. continue
  2055. }
  2056. key := clientKeyForProtocol(oldInbound.Protocol, entry.record)
  2057. if key == "" {
  2058. res.perEmailSkipped[email] = "missing client key for protocol"
  2059. continue
  2060. }
  2061. keyToEmail[key] = email
  2062. }
  2063. interfaceClients, _ := settings["clients"].([]any)
  2064. foundEmails := map[string]bool{}
  2065. nowMs := time.Now().Unix() * 1000
  2066. for i, client := range interfaceClients {
  2067. c, ok := client.(map[string]any)
  2068. if !ok {
  2069. continue
  2070. }
  2071. cKey, _ := c[clientKey].(string)
  2072. targetEmail, found := keyToEmail[cKey]
  2073. if !found {
  2074. continue
  2075. }
  2076. entry := plan[targetEmail]
  2077. if entry.applyExpiry {
  2078. c["expiryTime"] = entry.newExpiry
  2079. }
  2080. if entry.applyTotal {
  2081. c["totalGB"] = entry.newTotal
  2082. }
  2083. c["updated_at"] = nowMs
  2084. interfaceClients[i] = c
  2085. foundEmails[targetEmail] = true
  2086. }
  2087. for _, email := range keyToEmail {
  2088. if !foundEmails[email] {
  2089. res.perEmailSkipped[email] = "Client Not Found In Inbound"
  2090. }
  2091. }
  2092. if len(foundEmails) == 0 {
  2093. return res
  2094. }
  2095. settings["clients"] = interfaceClients
  2096. newSettings, err := json.MarshalIndent(settings, "", " ")
  2097. if err != nil {
  2098. for email := range foundEmails {
  2099. res.perEmailSkipped[email] = err.Error()
  2100. }
  2101. return res
  2102. }
  2103. oldInbound.Settings = string(newSettings)
  2104. if oldInbound.NodeID != nil {
  2105. rt, rterr := inboundSvc.runtimeFor(oldInbound)
  2106. if rterr != nil {
  2107. for email := range foundEmails {
  2108. res.perEmailSkipped[email] = rterr.Error()
  2109. delete(foundEmails, email)
  2110. }
  2111. } else {
  2112. for email := range foundEmails {
  2113. entry := plan[email]
  2114. updated := *entry.record.ToClient()
  2115. if entry.applyExpiry {
  2116. updated.ExpiryTime = entry.newExpiry
  2117. }
  2118. if entry.applyTotal {
  2119. updated.TotalGB = entry.newTotal
  2120. }
  2121. updated.UpdatedAt = nowMs
  2122. if err1 := rt.UpdateUser(context.Background(), oldInbound, email, updated); err1 != nil {
  2123. res.perEmailSkipped[email] = err1.Error()
  2124. delete(foundEmails, email)
  2125. }
  2126. }
  2127. }
  2128. }
  2129. db := database.GetDB()
  2130. if err := db.Save(oldInbound).Error; err != nil {
  2131. for email := range foundEmails {
  2132. if _, skip := res.perEmailSkipped[email]; !skip {
  2133. res.perEmailSkipped[email] = err.Error()
  2134. }
  2135. }
  2136. return res
  2137. }
  2138. finalClients, gcErr := inboundSvc.GetClients(oldInbound)
  2139. if gcErr == nil {
  2140. if syncErr := s.SyncInbound(db, inboundId, finalClients); syncErr != nil {
  2141. logger.Warning("bulkAdjust SyncInbound:", syncErr)
  2142. }
  2143. }
  2144. return res
  2145. }
  2146. // BulkDeleteResult mirrors BulkAdjustResult: total deleted plus per-email
  2147. // skip reasons when an email could not be processed.
  2148. type BulkDeleteResult struct {
  2149. Deleted int `json:"deleted"`
  2150. Skipped []BulkDeleteReport `json:"skipped,omitempty"`
  2151. }
  2152. type BulkDeleteReport struct {
  2153. Email string `json:"email"`
  2154. Reason string `json:"reason"`
  2155. }
  2156. // BulkDelete removes every client in the list in one optimized pass.
  2157. // Instead of running the full single-delete pipeline N times (which would
  2158. // re-read, re-parse, and re-write each inbound's settings JSON for every
  2159. // email), it groups emails by inbound and performs a single
  2160. // read-modify-write per inbound. Per-row DB cleanups are also batched with
  2161. // IN-clause queries at the end. Errors on a particular email are recorded
  2162. // in the Skipped list and processing continues for the rest.
  2163. func (s *ClientService) BulkDelete(inboundSvc *InboundService, emails []string, keepTraffic bool) (BulkDeleteResult, bool, error) {
  2164. result := BulkDeleteResult{}
  2165. seen := map[string]struct{}{}
  2166. cleanEmails := make([]string, 0, len(emails))
  2167. for _, e := range emails {
  2168. e = strings.TrimSpace(e)
  2169. if e == "" {
  2170. continue
  2171. }
  2172. if _, ok := seen[e]; ok {
  2173. continue
  2174. }
  2175. seen[e] = struct{}{}
  2176. cleanEmails = append(cleanEmails, e)
  2177. }
  2178. if len(cleanEmails) == 0 {
  2179. return result, false, nil
  2180. }
  2181. db := database.GetDB()
  2182. var records []model.ClientRecord
  2183. if err := db.Where("email IN ?", cleanEmails).Find(&records).Error; err != nil {
  2184. return result, false, err
  2185. }
  2186. recordsByEmail := make(map[string]*model.ClientRecord, len(records))
  2187. for i := range records {
  2188. recordsByEmail[records[i].Email] = &records[i]
  2189. tombstoneClientEmail(records[i].Email)
  2190. }
  2191. skippedReasons := map[string]string{}
  2192. for _, email := range cleanEmails {
  2193. if _, ok := recordsByEmail[email]; !ok {
  2194. skippedReasons[email] = "client not found"
  2195. }
  2196. }
  2197. clientIds := make([]int, 0, len(recordsByEmail))
  2198. recordIdToEmail := make(map[int]string, len(recordsByEmail))
  2199. for _, r := range recordsByEmail {
  2200. clientIds = append(clientIds, r.Id)
  2201. recordIdToEmail[r.Id] = r.Email
  2202. }
  2203. emailsByInbound := map[int][]string{}
  2204. if len(clientIds) > 0 {
  2205. var mappings []model.ClientInbound
  2206. if err := db.Where("client_id IN ?", clientIds).Find(&mappings).Error; err != nil {
  2207. return result, false, err
  2208. }
  2209. for _, m := range mappings {
  2210. email, ok := recordIdToEmail[m.ClientId]
  2211. if !ok {
  2212. continue
  2213. }
  2214. emailsByInbound[m.InboundId] = append(emailsByInbound[m.InboundId], email)
  2215. }
  2216. }
  2217. needRestart := false
  2218. for inboundId, ibEmails := range emailsByInbound {
  2219. ibResult := s.bulkDelInboundClients(inboundSvc, inboundId, ibEmails, recordsByEmail)
  2220. if ibResult.needRestart {
  2221. needRestart = true
  2222. }
  2223. for email, reason := range ibResult.perEmailSkipped {
  2224. if _, already := skippedReasons[email]; !already {
  2225. skippedReasons[email] = reason
  2226. }
  2227. }
  2228. }
  2229. successEmails := make([]string, 0, len(recordsByEmail))
  2230. successIds := make([]int, 0, len(recordsByEmail))
  2231. for email, rec := range recordsByEmail {
  2232. if _, skipped := skippedReasons[email]; skipped {
  2233. continue
  2234. }
  2235. successEmails = append(successEmails, email)
  2236. successIds = append(successIds, rec.Id)
  2237. }
  2238. if len(successIds) > 0 {
  2239. if err := db.Where("client_id IN ?", successIds).Delete(&model.ClientInbound{}).Error; err != nil {
  2240. return result, needRestart, err
  2241. }
  2242. if !keepTraffic && len(successEmails) > 0 {
  2243. if err := db.Where("email IN ?", successEmails).Delete(&xray.ClientTraffic{}).Error; err != nil {
  2244. return result, needRestart, err
  2245. }
  2246. if err := db.Where("client_email IN ?", successEmails).Delete(&model.InboundClientIps{}).Error; err != nil {
  2247. return result, needRestart, err
  2248. }
  2249. }
  2250. if err := db.Where("id IN ?", successIds).Delete(&model.ClientRecord{}).Error; err != nil {
  2251. return result, needRestart, err
  2252. }
  2253. }
  2254. result.Deleted = len(successEmails)
  2255. for email, reason := range skippedReasons {
  2256. result.Skipped = append(result.Skipped, BulkDeleteReport{Email: email, Reason: reason})
  2257. }
  2258. return result, needRestart, nil
  2259. }
  2260. type bulkInboundDeleteResult struct {
  2261. perEmailSkipped map[string]string
  2262. needRestart bool
  2263. }
  2264. // bulkDelInboundClients removes multiple clients from a single inbound's
  2265. // settings JSON in one read-modify-write cycle, runs the xray runtime
  2266. // RemoveUser/DeleteUser calls, and persists the inbound. The returned map
  2267. // holds per-email failure reasons; emails not present in the map are
  2268. // considered successful for this inbound.
  2269. func (s *ClientService) bulkDelInboundClients(
  2270. inboundSvc *InboundService,
  2271. inboundId int,
  2272. emails []string,
  2273. records map[string]*model.ClientRecord,
  2274. ) bulkInboundDeleteResult {
  2275. res := bulkInboundDeleteResult{perEmailSkipped: map[string]string{}}
  2276. defer lockInbound(inboundId).Unlock()
  2277. oldInbound, err := inboundSvc.GetInbound(inboundId)
  2278. if err != nil {
  2279. logger.Error("Load Old Data Error")
  2280. for _, e := range emails {
  2281. res.perEmailSkipped[e] = err.Error()
  2282. }
  2283. return res
  2284. }
  2285. var settings map[string]any
  2286. if err := json.Unmarshal([]byte(oldInbound.Settings), &settings); err != nil {
  2287. for _, e := range emails {
  2288. res.perEmailSkipped[e] = err.Error()
  2289. }
  2290. return res
  2291. }
  2292. clientKey := "id"
  2293. switch oldInbound.Protocol {
  2294. case model.Trojan:
  2295. clientKey = "password"
  2296. case model.Shadowsocks:
  2297. clientKey = "email"
  2298. case model.Hysteria:
  2299. clientKey = "auth"
  2300. }
  2301. keyToEmail := make(map[string]string, len(emails))
  2302. for _, email := range emails {
  2303. rec := records[email]
  2304. if rec == nil {
  2305. res.perEmailSkipped[email] = "client not found"
  2306. continue
  2307. }
  2308. key := clientKeyForProtocol(oldInbound.Protocol, rec)
  2309. if key == "" {
  2310. res.perEmailSkipped[email] = "missing client key for protocol"
  2311. continue
  2312. }
  2313. keyToEmail[key] = email
  2314. }
  2315. interfaceClients, _ := settings["clients"].([]any)
  2316. newClients := make([]any, 0, len(interfaceClients))
  2317. foundEmails := map[string]bool{}
  2318. enableByEmail := map[string]bool{}
  2319. for _, client := range interfaceClients {
  2320. c, ok := client.(map[string]any)
  2321. if !ok {
  2322. newClients = append(newClients, client)
  2323. continue
  2324. }
  2325. cKey, _ := c[clientKey].(string)
  2326. if targetEmail, found := keyToEmail[cKey]; found {
  2327. foundEmails[targetEmail] = true
  2328. if em, _ := c["email"].(string); em != "" {
  2329. en, _ := c["enable"].(bool)
  2330. enableByEmail[em] = en
  2331. }
  2332. continue
  2333. }
  2334. newClients = append(newClients, client)
  2335. }
  2336. for _, email := range keyToEmail {
  2337. if !foundEmails[email] {
  2338. res.perEmailSkipped[email] = "Client Not Found In Inbound"
  2339. }
  2340. }
  2341. db := database.GetDB()
  2342. newClients = compactOrphans(db, newClients)
  2343. if newClients == nil {
  2344. newClients = []any{}
  2345. }
  2346. settings["clients"] = newClients
  2347. newSettings, err := json.MarshalIndent(settings, "", " ")
  2348. if err != nil {
  2349. for email := range foundEmails {
  2350. if _, skip := res.perEmailSkipped[email]; !skip {
  2351. res.perEmailSkipped[email] = err.Error()
  2352. }
  2353. }
  2354. return res
  2355. }
  2356. oldInbound.Settings = string(newSettings)
  2357. foundList := make([]string, 0, len(foundEmails))
  2358. for email := range foundEmails {
  2359. foundList = append(foundList, email)
  2360. }
  2361. notDepletedByEmail := map[string]bool{}
  2362. if len(foundList) > 0 {
  2363. type trafficRow struct {
  2364. Email string
  2365. Enable bool
  2366. }
  2367. var rows []trafficRow
  2368. if err := db.Model(xray.ClientTraffic{}).
  2369. Where("email IN ?", foundList).
  2370. Select("email, enable").
  2371. Scan(&rows).Error; err == nil {
  2372. for _, r := range rows {
  2373. notDepletedByEmail[r.Email] = r.Enable
  2374. }
  2375. }
  2376. }
  2377. for email := range foundEmails {
  2378. shared, sharedErr := inboundSvc.emailUsedByOtherInbounds(email, inboundId)
  2379. if sharedErr != nil {
  2380. res.perEmailSkipped[email] = sharedErr.Error()
  2381. delete(foundEmails, email)
  2382. continue
  2383. }
  2384. if shared {
  2385. continue
  2386. }
  2387. if delErr := inboundSvc.DelClientIPs(db, email); delErr != nil {
  2388. logger.Error("Error in delete client IPs")
  2389. res.perEmailSkipped[email] = delErr.Error()
  2390. delete(foundEmails, email)
  2391. continue
  2392. }
  2393. if delErr := inboundSvc.DelClientStat(db, email); delErr != nil {
  2394. logger.Error("Delete stats Data Error")
  2395. res.perEmailSkipped[email] = delErr.Error()
  2396. delete(foundEmails, email)
  2397. continue
  2398. }
  2399. }
  2400. if oldInbound.NodeID == nil {
  2401. rt, rterr := inboundSvc.runtimeFor(oldInbound)
  2402. if rterr != nil {
  2403. res.needRestart = true
  2404. } else {
  2405. for email := range foundEmails {
  2406. if !enableByEmail[email] || !notDepletedByEmail[email] {
  2407. continue
  2408. }
  2409. err1 := rt.RemoveUser(context.Background(), oldInbound, email)
  2410. if err1 == nil {
  2411. logger.Debug("Client deleted on", rt.Name(), ":", email)
  2412. } else if strings.Contains(err1.Error(), fmt.Sprintf("User %s not found.", email)) {
  2413. logger.Debug("User is already deleted. Nothing to do more...")
  2414. } else {
  2415. logger.Debug("Error in deleting client on", rt.Name(), ":", err1)
  2416. res.needRestart = true
  2417. }
  2418. }
  2419. }
  2420. } else {
  2421. rt, rterr := inboundSvc.runtimeFor(oldInbound)
  2422. if rterr != nil {
  2423. for email := range foundEmails {
  2424. res.perEmailSkipped[email] = rterr.Error()
  2425. delete(foundEmails, email)
  2426. }
  2427. } else {
  2428. for email := range foundEmails {
  2429. if err1 := rt.DeleteUser(context.Background(), oldInbound, email); err1 != nil {
  2430. res.perEmailSkipped[email] = err1.Error()
  2431. delete(foundEmails, email)
  2432. }
  2433. }
  2434. }
  2435. }
  2436. if err := db.Save(oldInbound).Error; err != nil {
  2437. for email := range foundEmails {
  2438. if _, skip := res.perEmailSkipped[email]; !skip {
  2439. res.perEmailSkipped[email] = err.Error()
  2440. }
  2441. }
  2442. return res
  2443. }
  2444. finalClients, err := inboundSvc.GetClients(oldInbound)
  2445. if err != nil {
  2446. return res
  2447. }
  2448. if err := s.SyncInbound(db, inboundId, finalClients); err != nil {
  2449. return res
  2450. }
  2451. return res
  2452. }
  2453. // BulkCreateResult mirrors BulkAdjustResult for the create flow.
  2454. type BulkCreateResult struct {
  2455. Created int `json:"created"`
  2456. Skipped []BulkCreateReport `json:"skipped,omitempty"`
  2457. }
  2458. type BulkCreateReport struct {
  2459. Email string `json:"email"`
  2460. Reason string `json:"reason"`
  2461. }
  2462. // BulkCreate iterates payloads sequentially. Each item is the same shape
  2463. // the single-create endpoint accepts, so callers can submit a heterogeneous
  2464. // list (different inboundIds, plans, etc.) in one round-trip.
  2465. func (s *ClientService) BulkCreate(inboundSvc *InboundService, payloads []ClientCreatePayload) (BulkCreateResult, bool, error) {
  2466. result := BulkCreateResult{}
  2467. needRestart := false
  2468. for i := range payloads {
  2469. p := payloads[i]
  2470. email := strings.TrimSpace(p.Client.Email)
  2471. nr, err := s.Create(inboundSvc, &p)
  2472. if err != nil {
  2473. if email == "" {
  2474. email = "(missing email)"
  2475. }
  2476. result.Skipped = append(result.Skipped, BulkCreateReport{Email: email, Reason: err.Error()})
  2477. continue
  2478. }
  2479. if nr {
  2480. needRestart = true
  2481. }
  2482. result.Created++
  2483. }
  2484. return result, needRestart, nil
  2485. }
  2486. func (s *ClientService) DelDepleted(inboundSvc *InboundService) (int, bool, error) {
  2487. db := database.GetDB()
  2488. now := time.Now().UnixMilli()
  2489. depletedClause := "reset = 0 and ((total > 0 and up + down >= total) or (expiry_time > 0 and expiry_time <= ?))"
  2490. var rows []xray.ClientTraffic
  2491. if err := db.Where(depletedClause, now).Find(&rows).Error; err != nil {
  2492. return 0, false, err
  2493. }
  2494. if len(rows) == 0 {
  2495. return 0, false, nil
  2496. }
  2497. emails := make(map[string]struct{}, len(rows))
  2498. for _, r := range rows {
  2499. if r.Email != "" {
  2500. emails[r.Email] = struct{}{}
  2501. }
  2502. }
  2503. needRestart := false
  2504. deleted := 0
  2505. for email := range emails {
  2506. var rec model.ClientRecord
  2507. if err := db.Where("email = ?", email).First(&rec).Error; err != nil {
  2508. if errors.Is(err, gorm.ErrRecordNotFound) {
  2509. continue
  2510. }
  2511. return deleted, needRestart, err
  2512. }
  2513. nr, err := s.Delete(inboundSvc, rec.Id, false)
  2514. if err != nil {
  2515. return deleted, needRestart, err
  2516. }
  2517. if nr {
  2518. needRestart = true
  2519. }
  2520. deleted++
  2521. }
  2522. return deleted, needRestart, nil
  2523. }
  2524. func (s *ClientService) ResetAllClientTraffics(inboundSvc *InboundService, id int) error {
  2525. return submitTrafficWrite(func() error {
  2526. return s.resetAllClientTrafficsLocked(id)
  2527. })
  2528. }
  2529. func (s *ClientService) resetAllClientTrafficsLocked(id int) error {
  2530. db := database.GetDB()
  2531. now := time.Now().Unix() * 1000
  2532. if err := db.Transaction(func(tx *gorm.DB) error {
  2533. whereText := "inbound_id "
  2534. if id == -1 {
  2535. whereText += " > ?"
  2536. } else {
  2537. whereText += " = ?"
  2538. }
  2539. result := tx.Model(xray.ClientTraffic{}).
  2540. Where(whereText, id).
  2541. Updates(map[string]any{"enable": true, "up": 0, "down": 0})
  2542. if result.Error != nil {
  2543. return result.Error
  2544. }
  2545. inboundWhereText := "id "
  2546. if id == -1 {
  2547. inboundWhereText += " > ?"
  2548. } else {
  2549. inboundWhereText += " = ?"
  2550. }
  2551. result = tx.Model(model.Inbound{}).
  2552. Where(inboundWhereText, id).
  2553. Update("last_traffic_reset_time", now)
  2554. return result.Error
  2555. }); err != nil {
  2556. return err
  2557. }
  2558. return nil
  2559. }
  2560. func (s *ClientService) ResetAllTraffics() (bool, error) {
  2561. res := database.GetDB().Model(&xray.ClientTraffic{}).
  2562. Where("1 = 1").
  2563. Updates(map[string]any{"up": 0, "down": 0})
  2564. if res.Error != nil {
  2565. return false, res.Error
  2566. }
  2567. return res.RowsAffected > 0, nil
  2568. }
  2569. func (s *ClientService) Detach(inboundSvc *InboundService, id int, inboundIds []int) (bool, error) {
  2570. existing, err := s.GetByID(id)
  2571. if err != nil {
  2572. return false, err
  2573. }
  2574. currentIds, err := s.GetInboundIdsForRecord(id)
  2575. if err != nil {
  2576. return false, err
  2577. }
  2578. have := make(map[int]struct{}, len(currentIds))
  2579. for _, x := range currentIds {
  2580. have[x] = struct{}{}
  2581. }
  2582. needRestart := false
  2583. for _, ibId := range inboundIds {
  2584. if _, attached := have[ibId]; !attached {
  2585. continue
  2586. }
  2587. inbound, getErr := inboundSvc.GetInbound(ibId)
  2588. if getErr != nil {
  2589. return needRestart, getErr
  2590. }
  2591. key := clientKeyForProtocol(inbound.Protocol, existing)
  2592. if key == "" {
  2593. continue
  2594. }
  2595. nr, delErr := s.DelInboundClient(inboundSvc, ibId, key)
  2596. if delErr != nil {
  2597. return needRestart, delErr
  2598. }
  2599. if nr {
  2600. needRestart = true
  2601. }
  2602. }
  2603. return needRestart, nil
  2604. }
  2605. func (s *ClientService) checkEmailsExistForClients(inboundSvc *InboundService, clients []model.Client) (string, error) {
  2606. emailSubIDs, err := inboundSvc.getAllEmailSubIDs()
  2607. if err != nil {
  2608. return "", err
  2609. }
  2610. seen := make(map[string]string, len(clients))
  2611. for _, client := range clients {
  2612. if client.Email == "" {
  2613. continue
  2614. }
  2615. key := strings.ToLower(client.Email)
  2616. if prev, ok := seen[key]; ok {
  2617. if prev != client.SubID || client.SubID == "" {
  2618. return client.Email, nil
  2619. }
  2620. continue
  2621. }
  2622. seen[key] = client.SubID
  2623. if existingSub, ok := emailSubIDs[key]; ok {
  2624. if client.SubID == "" || existingSub == "" || existingSub != client.SubID {
  2625. return client.Email, nil
  2626. }
  2627. }
  2628. }
  2629. return "", nil
  2630. }
  2631. func (s *ClientService) AddInboundClient(inboundSvc *InboundService, data *model.Inbound) (bool, error) {
  2632. defer lockInbound(data.Id).Unlock()
  2633. clients, err := inboundSvc.GetClients(data)
  2634. if err != nil {
  2635. return false, err
  2636. }
  2637. var settings map[string]any
  2638. err = json.Unmarshal([]byte(data.Settings), &settings)
  2639. if err != nil {
  2640. return false, err
  2641. }
  2642. interfaceClients := settings["clients"].([]any)
  2643. nowTs := time.Now().Unix() * 1000
  2644. for i := range interfaceClients {
  2645. if cm, ok := interfaceClients[i].(map[string]any); ok {
  2646. if _, ok2 := cm["created_at"]; !ok2 {
  2647. cm["created_at"] = nowTs
  2648. }
  2649. cm["updated_at"] = nowTs
  2650. interfaceClients[i] = cm
  2651. }
  2652. }
  2653. existEmail, err := s.checkEmailsExistForClients(inboundSvc, clients)
  2654. if err != nil {
  2655. return false, err
  2656. }
  2657. if existEmail != "" {
  2658. return false, common.NewError("Duplicate email:", existEmail)
  2659. }
  2660. oldInbound, err := inboundSvc.GetInbound(data.Id)
  2661. if err != nil {
  2662. return false, err
  2663. }
  2664. for _, client := range clients {
  2665. if strings.TrimSpace(client.Email) == "" {
  2666. return false, common.NewError("client email is required")
  2667. }
  2668. switch oldInbound.Protocol {
  2669. case "trojan":
  2670. if client.Password == "" {
  2671. return false, common.NewError("empty client ID")
  2672. }
  2673. case "shadowsocks":
  2674. if client.Email == "" {
  2675. return false, common.NewError("empty client ID")
  2676. }
  2677. case "hysteria":
  2678. if client.Auth == "" {
  2679. return false, common.NewError("empty client ID")
  2680. }
  2681. default:
  2682. if client.ID == "" {
  2683. return false, common.NewError("empty client ID")
  2684. }
  2685. }
  2686. }
  2687. var oldSettings map[string]any
  2688. err = json.Unmarshal([]byte(oldInbound.Settings), &oldSettings)
  2689. if err != nil {
  2690. return false, err
  2691. }
  2692. if oldInbound.Protocol == model.Shadowsocks {
  2693. applyShadowsocksClientMethod(interfaceClients, oldSettings)
  2694. }
  2695. oldClients := oldSettings["clients"].([]any)
  2696. oldClients = compactOrphans(database.GetDB(), oldClients)
  2697. oldClients = append(oldClients, interfaceClients...)
  2698. oldSettings["clients"] = oldClients
  2699. newSettings, err := json.MarshalIndent(oldSettings, "", " ")
  2700. if err != nil {
  2701. return false, err
  2702. }
  2703. oldInbound.Settings = string(newSettings)
  2704. db := database.GetDB()
  2705. tx := db.Begin()
  2706. defer func() {
  2707. if err != nil {
  2708. tx.Rollback()
  2709. } else {
  2710. tx.Commit()
  2711. }
  2712. }()
  2713. needRestart := false
  2714. rt, rterr := inboundSvc.runtimeFor(oldInbound)
  2715. if rterr != nil {
  2716. if oldInbound.NodeID != nil {
  2717. err = rterr
  2718. return false, err
  2719. }
  2720. needRestart = true
  2721. } else if oldInbound.NodeID == nil {
  2722. for _, client := range clients {
  2723. if len(client.Email) == 0 {
  2724. needRestart = true
  2725. continue
  2726. }
  2727. inboundSvc.AddClientStat(tx, data.Id, &client)
  2728. if !client.Enable {
  2729. continue
  2730. }
  2731. cipher := ""
  2732. if oldInbound.Protocol == "shadowsocks" {
  2733. cipher = oldSettings["method"].(string)
  2734. }
  2735. err1 := rt.AddUser(context.Background(), oldInbound, map[string]any{
  2736. "email": client.Email,
  2737. "id": client.ID,
  2738. "auth": client.Auth,
  2739. "security": client.Security,
  2740. "flow": client.Flow,
  2741. "password": client.Password,
  2742. "cipher": cipher,
  2743. })
  2744. if err1 == nil {
  2745. logger.Debug("Client added on", rt.Name(), ":", client.Email)
  2746. } else {
  2747. logger.Debug("Error in adding client on", rt.Name(), ":", err1)
  2748. needRestart = true
  2749. }
  2750. }
  2751. } else {
  2752. for _, client := range clients {
  2753. if len(client.Email) > 0 {
  2754. inboundSvc.AddClientStat(tx, data.Id, &client)
  2755. }
  2756. if err1 := rt.AddClient(context.Background(), oldInbound, client); err1 != nil {
  2757. err = err1
  2758. return false, err
  2759. }
  2760. }
  2761. }
  2762. if err = tx.Save(oldInbound).Error; err != nil {
  2763. return false, err
  2764. }
  2765. finalClients, gcErr := inboundSvc.GetClients(oldInbound)
  2766. if gcErr != nil {
  2767. err = gcErr
  2768. return false, err
  2769. }
  2770. if err = s.SyncInbound(tx, oldInbound.Id, finalClients); err != nil {
  2771. return false, err
  2772. }
  2773. return needRestart, nil
  2774. }
  2775. func (s *ClientService) UpdateInboundClient(inboundSvc *InboundService, data *model.Inbound, clientId string) (bool, error) {
  2776. defer lockInbound(data.Id).Unlock()
  2777. clients, err := inboundSvc.GetClients(data)
  2778. if err != nil {
  2779. return false, err
  2780. }
  2781. var settings map[string]any
  2782. err = json.Unmarshal([]byte(data.Settings), &settings)
  2783. if err != nil {
  2784. return false, err
  2785. }
  2786. interfaceClients := settings["clients"].([]any)
  2787. oldInbound, err := inboundSvc.GetInbound(data.Id)
  2788. if err != nil {
  2789. return false, err
  2790. }
  2791. oldClients, err := inboundSvc.GetClients(oldInbound)
  2792. if err != nil {
  2793. return false, err
  2794. }
  2795. oldEmail := ""
  2796. newClientId := ""
  2797. clientIndex := -1
  2798. for index, oldClient := range oldClients {
  2799. oldClientId := ""
  2800. switch oldInbound.Protocol {
  2801. case "trojan":
  2802. oldClientId = oldClient.Password
  2803. newClientId = clients[0].Password
  2804. case "shadowsocks":
  2805. oldClientId = oldClient.Email
  2806. newClientId = clients[0].Email
  2807. case "hysteria":
  2808. oldClientId = oldClient.Auth
  2809. newClientId = clients[0].Auth
  2810. default:
  2811. oldClientId = oldClient.ID
  2812. newClientId = clients[0].ID
  2813. }
  2814. if clientId == oldClientId {
  2815. oldEmail = oldClient.Email
  2816. clientIndex = index
  2817. break
  2818. }
  2819. }
  2820. if clientIndex == -1 {
  2821. var rec model.ClientRecord
  2822. var lookupErr error
  2823. switch oldInbound.Protocol {
  2824. case "trojan":
  2825. lookupErr = database.GetDB().Where("password = ?", clientId).First(&rec).Error
  2826. case "shadowsocks":
  2827. lookupErr = database.GetDB().Where("email = ?", clientId).First(&rec).Error
  2828. case "hysteria":
  2829. lookupErr = database.GetDB().Where("auth = ?", clientId).First(&rec).Error
  2830. default:
  2831. lookupErr = database.GetDB().Where("uuid = ?", clientId).First(&rec).Error
  2832. }
  2833. if lookupErr == nil && rec.Email != "" {
  2834. for index, oldClient := range oldClients {
  2835. if oldClient.Email == rec.Email {
  2836. oldEmail = oldClient.Email
  2837. clientIndex = index
  2838. break
  2839. }
  2840. }
  2841. }
  2842. }
  2843. if newClientId == "" || clientIndex == -1 {
  2844. return false, common.NewError("empty client ID")
  2845. }
  2846. if strings.TrimSpace(clients[0].Email) == "" {
  2847. return false, common.NewError("client email is required")
  2848. }
  2849. if clients[0].Email != oldEmail {
  2850. existEmail, err := s.checkEmailsExistForClients(inboundSvc, clients)
  2851. if err != nil {
  2852. return false, err
  2853. }
  2854. if existEmail != "" {
  2855. return false, common.NewError("Duplicate email:", existEmail)
  2856. }
  2857. }
  2858. var oldSettings map[string]any
  2859. err = json.Unmarshal([]byte(oldInbound.Settings), &oldSettings)
  2860. if err != nil {
  2861. return false, err
  2862. }
  2863. settingsClients := oldSettings["clients"].([]any)
  2864. var preservedCreated any
  2865. if clientIndex >= 0 && clientIndex < len(settingsClients) {
  2866. if oldMap, ok := settingsClients[clientIndex].(map[string]any); ok {
  2867. if v, ok2 := oldMap["created_at"]; ok2 {
  2868. preservedCreated = v
  2869. }
  2870. }
  2871. }
  2872. if len(interfaceClients) > 0 {
  2873. if newMap, ok := interfaceClients[0].(map[string]any); ok {
  2874. if preservedCreated == nil {
  2875. preservedCreated = time.Now().Unix() * 1000
  2876. }
  2877. newMap["created_at"] = preservedCreated
  2878. newMap["updated_at"] = time.Now().Unix() * 1000
  2879. interfaceClients[0] = newMap
  2880. }
  2881. }
  2882. if oldInbound.Protocol == model.Shadowsocks {
  2883. applyShadowsocksClientMethod(interfaceClients, oldSettings)
  2884. }
  2885. settingsClients[clientIndex] = interfaceClients[0]
  2886. oldSettings["clients"] = settingsClients
  2887. if oldInbound.Protocol == model.VLESS {
  2888. hasVisionFlow := false
  2889. for _, c := range settingsClients {
  2890. cm, ok := c.(map[string]any)
  2891. if !ok {
  2892. continue
  2893. }
  2894. if flow, _ := cm["flow"].(string); flow == "xtls-rprx-vision" {
  2895. hasVisionFlow = true
  2896. break
  2897. }
  2898. }
  2899. if !hasVisionFlow {
  2900. delete(oldSettings, "testseed")
  2901. }
  2902. }
  2903. newSettings, err := json.MarshalIndent(oldSettings, "", " ")
  2904. if err != nil {
  2905. return false, err
  2906. }
  2907. oldInbound.Settings = string(newSettings)
  2908. db := database.GetDB()
  2909. tx := db.Begin()
  2910. defer func() {
  2911. if err != nil {
  2912. tx.Rollback()
  2913. } else {
  2914. tx.Commit()
  2915. }
  2916. }()
  2917. if len(clients[0].Email) > 0 {
  2918. if len(oldEmail) > 0 {
  2919. emailUnchanged := strings.EqualFold(oldEmail, clients[0].Email)
  2920. targetExists := int64(0)
  2921. if !emailUnchanged {
  2922. if err = tx.Model(xray.ClientTraffic{}).Where("email = ?", clients[0].Email).Count(&targetExists).Error; err != nil {
  2923. return false, err
  2924. }
  2925. }
  2926. if emailUnchanged || targetExists == 0 {
  2927. err = inboundSvc.UpdateClientStat(tx, oldEmail, &clients[0])
  2928. if err != nil {
  2929. return false, err
  2930. }
  2931. err = inboundSvc.UpdateClientIPs(tx, oldEmail, clients[0].Email)
  2932. if err != nil {
  2933. return false, err
  2934. }
  2935. } else {
  2936. stillUsed, sErr := inboundSvc.emailUsedByOtherInbounds(oldEmail, data.Id)
  2937. if sErr != nil {
  2938. return false, sErr
  2939. }
  2940. if !stillUsed {
  2941. if err = inboundSvc.DelClientStat(tx, oldEmail); err != nil {
  2942. return false, err
  2943. }
  2944. if err = inboundSvc.DelClientIPs(tx, oldEmail); err != nil {
  2945. return false, err
  2946. }
  2947. }
  2948. if err = inboundSvc.UpdateClientStat(tx, clients[0].Email, &clients[0]); err != nil {
  2949. return false, err
  2950. }
  2951. }
  2952. } else {
  2953. inboundSvc.AddClientStat(tx, data.Id, &clients[0])
  2954. }
  2955. } else {
  2956. stillUsed, err := inboundSvc.emailUsedByOtherInbounds(oldEmail, data.Id)
  2957. if err != nil {
  2958. return false, err
  2959. }
  2960. if !stillUsed {
  2961. err = inboundSvc.DelClientStat(tx, oldEmail)
  2962. if err != nil {
  2963. return false, err
  2964. }
  2965. err = inboundSvc.DelClientIPs(tx, oldEmail)
  2966. if err != nil {
  2967. return false, err
  2968. }
  2969. }
  2970. }
  2971. needRestart := false
  2972. if len(oldEmail) > 0 {
  2973. rt, rterr := inboundSvc.runtimeFor(oldInbound)
  2974. if rterr != nil {
  2975. if oldInbound.NodeID != nil {
  2976. err = rterr
  2977. return false, err
  2978. }
  2979. needRestart = true
  2980. } else if oldInbound.NodeID == nil {
  2981. if oldClients[clientIndex].Enable {
  2982. err1 := rt.RemoveUser(context.Background(), oldInbound, oldEmail)
  2983. if err1 == nil {
  2984. logger.Debug("Old client deleted on", rt.Name(), ":", oldEmail)
  2985. } else if strings.Contains(err1.Error(), fmt.Sprintf("User %s not found.", oldEmail)) {
  2986. logger.Debug("User is already deleted. Nothing to do more...")
  2987. } else {
  2988. logger.Debug("Error in deleting client on", rt.Name(), ":", err1)
  2989. needRestart = true
  2990. }
  2991. }
  2992. if clients[0].Enable {
  2993. cipher := ""
  2994. if oldInbound.Protocol == "shadowsocks" {
  2995. cipher = oldSettings["method"].(string)
  2996. }
  2997. err1 := rt.AddUser(context.Background(), oldInbound, map[string]any{
  2998. "email": clients[0].Email,
  2999. "id": clients[0].ID,
  3000. "security": clients[0].Security,
  3001. "flow": clients[0].Flow,
  3002. "auth": clients[0].Auth,
  3003. "password": clients[0].Password,
  3004. "cipher": cipher,
  3005. })
  3006. if err1 == nil {
  3007. logger.Debug("Client edited on", rt.Name(), ":", clients[0].Email)
  3008. } else {
  3009. logger.Debug("Error in adding client on", rt.Name(), ":", err1)
  3010. needRestart = true
  3011. }
  3012. }
  3013. } else {
  3014. if err1 := rt.UpdateUser(context.Background(), oldInbound, oldEmail, clients[0]); err1 != nil {
  3015. err = err1
  3016. return false, err
  3017. }
  3018. }
  3019. } else {
  3020. logger.Debug("Client old email not found")
  3021. needRestart = true
  3022. }
  3023. if err = tx.Save(oldInbound).Error; err != nil {
  3024. return false, err
  3025. }
  3026. finalClients, gcErr := inboundSvc.GetClients(oldInbound)
  3027. if gcErr != nil {
  3028. err = gcErr
  3029. return false, err
  3030. }
  3031. if err = s.SyncInbound(tx, oldInbound.Id, finalClients); err != nil {
  3032. return false, err
  3033. }
  3034. return needRestart, nil
  3035. }
  3036. func (s *ClientService) DelInboundClient(inboundSvc *InboundService, inboundId int, clientId string) (bool, error) {
  3037. defer lockInbound(inboundId).Unlock()
  3038. oldInbound, err := inboundSvc.GetInbound(inboundId)
  3039. if err != nil {
  3040. logger.Error("Load Old Data Error")
  3041. return false, err
  3042. }
  3043. var settings map[string]any
  3044. err = json.Unmarshal([]byte(oldInbound.Settings), &settings)
  3045. if err != nil {
  3046. return false, err
  3047. }
  3048. email := ""
  3049. client_key := "id"
  3050. switch oldInbound.Protocol {
  3051. case "trojan":
  3052. client_key = "password"
  3053. case "shadowsocks":
  3054. client_key = "email"
  3055. case "hysteria":
  3056. client_key = "auth"
  3057. }
  3058. interfaceClients := settings["clients"].([]any)
  3059. var newClients []any
  3060. needApiDel := false
  3061. clientFound := false
  3062. for _, client := range interfaceClients {
  3063. c := client.(map[string]any)
  3064. c_id := c[client_key].(string)
  3065. if c_id == clientId {
  3066. clientFound = true
  3067. email, _ = c["email"].(string)
  3068. needApiDel, _ = c["enable"].(bool)
  3069. } else {
  3070. newClients = append(newClients, client)
  3071. }
  3072. }
  3073. if !clientFound {
  3074. return false, common.NewError("Client Not Found In Inbound For ID:", clientId)
  3075. }
  3076. db := database.GetDB()
  3077. newClients = compactOrphans(db, newClients)
  3078. if newClients == nil {
  3079. newClients = []any{}
  3080. }
  3081. settings["clients"] = newClients
  3082. newSettings, err := json.MarshalIndent(settings, "", " ")
  3083. if err != nil {
  3084. return false, err
  3085. }
  3086. oldInbound.Settings = string(newSettings)
  3087. emailShared, err := inboundSvc.emailUsedByOtherInbounds(email, inboundId)
  3088. if err != nil {
  3089. return false, err
  3090. }
  3091. if !emailShared {
  3092. err = inboundSvc.DelClientIPs(db, email)
  3093. if err != nil {
  3094. logger.Error("Error in delete client IPs")
  3095. return false, err
  3096. }
  3097. }
  3098. needRestart := false
  3099. if len(email) > 0 {
  3100. var enables []bool
  3101. err = db.Model(xray.ClientTraffic{}).Where("email = ?", email).Limit(1).Pluck("enable", &enables).Error
  3102. if err != nil {
  3103. logger.Error("Get stats error")
  3104. return false, err
  3105. }
  3106. notDepleted := len(enables) > 0 && enables[0]
  3107. if !emailShared {
  3108. err = inboundSvc.DelClientStat(db, email)
  3109. if err != nil {
  3110. logger.Error("Delete stats Data Error")
  3111. return false, err
  3112. }
  3113. }
  3114. if needApiDel && notDepleted && oldInbound.NodeID == nil {
  3115. rt, rterr := inboundSvc.runtimeFor(oldInbound)
  3116. if rterr != nil {
  3117. needRestart = true
  3118. } else {
  3119. err1 := rt.RemoveUser(context.Background(), oldInbound, email)
  3120. if err1 == nil {
  3121. logger.Debug("Client deleted on", rt.Name(), ":", email)
  3122. needRestart = false
  3123. } else if strings.Contains(err1.Error(), fmt.Sprintf("User %s not found.", email)) {
  3124. logger.Debug("User is already deleted. Nothing to do more...")
  3125. } else {
  3126. logger.Debug("Error in deleting client on", rt.Name(), ":", err1)
  3127. needRestart = true
  3128. }
  3129. }
  3130. }
  3131. }
  3132. if oldInbound.NodeID != nil && len(email) > 0 {
  3133. rt, rterr := inboundSvc.runtimeFor(oldInbound)
  3134. if rterr != nil {
  3135. return false, rterr
  3136. }
  3137. if err1 := rt.DeleteUser(context.Background(), oldInbound, email); err1 != nil {
  3138. return false, err1
  3139. }
  3140. }
  3141. if err := db.Save(oldInbound).Error; err != nil {
  3142. return false, err
  3143. }
  3144. finalClients, gcErr := inboundSvc.GetClients(oldInbound)
  3145. if gcErr != nil {
  3146. return false, gcErr
  3147. }
  3148. if err := s.SyncInbound(db, inboundId, finalClients); err != nil {
  3149. return false, err
  3150. }
  3151. return needRestart, nil
  3152. }
  3153. func (s *ClientService) DelInboundClientByEmail(inboundSvc *InboundService, inboundId int, email string) (bool, error) {
  3154. defer lockInbound(inboundId).Unlock()
  3155. oldInbound, err := inboundSvc.GetInbound(inboundId)
  3156. if err != nil {
  3157. logger.Error("Load Old Data Error")
  3158. return false, err
  3159. }
  3160. var settings map[string]any
  3161. if err := json.Unmarshal([]byte(oldInbound.Settings), &settings); err != nil {
  3162. return false, err
  3163. }
  3164. interfaceClients, ok := settings["clients"].([]any)
  3165. if !ok {
  3166. return false, common.NewError("invalid clients format in inbound settings")
  3167. }
  3168. var newClients []any
  3169. needApiDel := false
  3170. found := false
  3171. for _, client := range interfaceClients {
  3172. c, ok := client.(map[string]any)
  3173. if !ok {
  3174. continue
  3175. }
  3176. if cEmail, ok := c["email"].(string); ok && cEmail == email {
  3177. found = true
  3178. needApiDel, _ = c["enable"].(bool)
  3179. } else {
  3180. newClients = append(newClients, client)
  3181. }
  3182. }
  3183. if !found {
  3184. return false, common.NewError(fmt.Sprintf("client with email %s not found", email))
  3185. }
  3186. db := database.GetDB()
  3187. newClients = compactOrphans(db, newClients)
  3188. if newClients == nil {
  3189. newClients = []any{}
  3190. }
  3191. settings["clients"] = newClients
  3192. newSettings, err := json.MarshalIndent(settings, "", " ")
  3193. if err != nil {
  3194. return false, err
  3195. }
  3196. oldInbound.Settings = string(newSettings)
  3197. emailShared, err := inboundSvc.emailUsedByOtherInbounds(email, inboundId)
  3198. if err != nil {
  3199. return false, err
  3200. }
  3201. if !emailShared {
  3202. if err := inboundSvc.DelClientIPs(db, email); err != nil {
  3203. logger.Error("Error in delete client IPs")
  3204. return false, err
  3205. }
  3206. }
  3207. needRestart := false
  3208. if len(email) > 0 && !emailShared {
  3209. traffic, err := inboundSvc.GetClientTrafficByEmail(email)
  3210. if err != nil {
  3211. return false, err
  3212. }
  3213. if traffic != nil {
  3214. if err := inboundSvc.DelClientStat(db, email); err != nil {
  3215. logger.Error("Delete stats Data Error")
  3216. return false, err
  3217. }
  3218. }
  3219. if needApiDel {
  3220. rt, rterr := inboundSvc.runtimeFor(oldInbound)
  3221. if rterr != nil {
  3222. if oldInbound.NodeID != nil {
  3223. return false, rterr
  3224. }
  3225. needRestart = true
  3226. } else if oldInbound.NodeID == nil {
  3227. if err1 := rt.RemoveUser(context.Background(), oldInbound, email); err1 == nil {
  3228. logger.Debug("Client deleted on", rt.Name(), ":", email)
  3229. needRestart = false
  3230. } else if strings.Contains(err1.Error(), fmt.Sprintf("User %s not found.", email)) {
  3231. logger.Debug("User is already deleted. Nothing to do more...")
  3232. } else {
  3233. logger.Debug("Error in deleting client on", rt.Name(), ":", err1)
  3234. needRestart = true
  3235. }
  3236. } else {
  3237. if err1 := rt.DeleteUser(context.Background(), oldInbound, email); err1 != nil {
  3238. return false, err1
  3239. }
  3240. }
  3241. }
  3242. }
  3243. if err := db.Save(oldInbound).Error; err != nil {
  3244. return false, err
  3245. }
  3246. finalClients, gcErr := inboundSvc.GetClients(oldInbound)
  3247. if gcErr != nil {
  3248. return false, gcErr
  3249. }
  3250. if err := s.SyncInbound(db, inboundId, finalClients); err != nil {
  3251. return false, err
  3252. }
  3253. return needRestart, nil
  3254. }
  3255. func (s *ClientService) SetClientTelegramUserID(inboundSvc *InboundService, trafficId int, tgId int64) (bool, error) {
  3256. traffic, inbound, err := inboundSvc.GetClientInboundByTrafficID(trafficId)
  3257. if err != nil {
  3258. return false, err
  3259. }
  3260. if inbound == nil {
  3261. return false, common.NewError("Inbound Not Found For Traffic ID:", trafficId)
  3262. }
  3263. clientEmail := traffic.Email
  3264. oldClients, err := inboundSvc.GetClients(inbound)
  3265. if err != nil {
  3266. return false, err
  3267. }
  3268. clientId := ""
  3269. for _, oldClient := range oldClients {
  3270. if oldClient.Email == clientEmail {
  3271. switch inbound.Protocol {
  3272. case "trojan":
  3273. clientId = oldClient.Password
  3274. case "shadowsocks":
  3275. clientId = oldClient.Email
  3276. default:
  3277. clientId = oldClient.ID
  3278. }
  3279. break
  3280. }
  3281. }
  3282. if len(clientId) == 0 {
  3283. return false, common.NewError("Client Not Found For Email:", clientEmail)
  3284. }
  3285. var settings map[string]any
  3286. err = json.Unmarshal([]byte(inbound.Settings), &settings)
  3287. if err != nil {
  3288. return false, err
  3289. }
  3290. clients := settings["clients"].([]any)
  3291. var newClients []any
  3292. for client_index := range clients {
  3293. c := clients[client_index].(map[string]any)
  3294. if c["email"] == clientEmail {
  3295. c["tgId"] = tgId
  3296. c["updated_at"] = time.Now().Unix() * 1000
  3297. newClients = append(newClients, any(c))
  3298. }
  3299. }
  3300. settings["clients"] = newClients
  3301. modifiedSettings, err := json.MarshalIndent(settings, "", " ")
  3302. if err != nil {
  3303. return false, err
  3304. }
  3305. inbound.Settings = string(modifiedSettings)
  3306. needRestart, err := s.UpdateInboundClient(inboundSvc, inbound, clientId)
  3307. return needRestart, err
  3308. }
  3309. func (s *ClientService) checkIsEnabledByEmail(inboundSvc *InboundService, clientEmail string) (bool, error) {
  3310. _, inbound, err := inboundSvc.GetClientInboundByEmail(clientEmail)
  3311. if err != nil {
  3312. return false, err
  3313. }
  3314. if inbound == nil {
  3315. return false, common.NewError("Inbound Not Found For Email:", clientEmail)
  3316. }
  3317. clients, err := inboundSvc.GetClients(inbound)
  3318. if err != nil {
  3319. return false, err
  3320. }
  3321. isEnable := false
  3322. for _, client := range clients {
  3323. if client.Email == clientEmail {
  3324. isEnable = client.Enable
  3325. break
  3326. }
  3327. }
  3328. return isEnable, err
  3329. }
  3330. func (s *ClientService) ToggleClientEnableByEmail(inboundSvc *InboundService, clientEmail string) (bool, bool, error) {
  3331. _, inbound, err := inboundSvc.GetClientInboundByEmail(clientEmail)
  3332. if err != nil {
  3333. return false, false, err
  3334. }
  3335. if inbound == nil {
  3336. return false, false, common.NewError("Inbound Not Found For Email:", clientEmail)
  3337. }
  3338. oldClients, err := inboundSvc.GetClients(inbound)
  3339. if err != nil {
  3340. return false, false, err
  3341. }
  3342. clientId := ""
  3343. clientOldEnabled := false
  3344. for _, oldClient := range oldClients {
  3345. if oldClient.Email == clientEmail {
  3346. switch inbound.Protocol {
  3347. case "trojan":
  3348. clientId = oldClient.Password
  3349. case "shadowsocks":
  3350. clientId = oldClient.Email
  3351. default:
  3352. clientId = oldClient.ID
  3353. }
  3354. clientOldEnabled = oldClient.Enable
  3355. break
  3356. }
  3357. }
  3358. if len(clientId) == 0 {
  3359. return false, false, common.NewError("Client Not Found For Email:", clientEmail)
  3360. }
  3361. var settings map[string]any
  3362. err = json.Unmarshal([]byte(inbound.Settings), &settings)
  3363. if err != nil {
  3364. return false, false, err
  3365. }
  3366. clients := settings["clients"].([]any)
  3367. var newClients []any
  3368. for client_index := range clients {
  3369. c := clients[client_index].(map[string]any)
  3370. if c["email"] == clientEmail {
  3371. c["enable"] = !clientOldEnabled
  3372. c["updated_at"] = time.Now().Unix() * 1000
  3373. newClients = append(newClients, any(c))
  3374. }
  3375. }
  3376. settings["clients"] = newClients
  3377. modifiedSettings, err := json.MarshalIndent(settings, "", " ")
  3378. if err != nil {
  3379. return false, false, err
  3380. }
  3381. inbound.Settings = string(modifiedSettings)
  3382. needRestart, err := s.UpdateInboundClient(inboundSvc, inbound, clientId)
  3383. if err != nil {
  3384. return false, needRestart, err
  3385. }
  3386. return !clientOldEnabled, needRestart, nil
  3387. }
  3388. func (s *ClientService) SetClientEnableByEmail(inboundSvc *InboundService, clientEmail string, enable bool) (bool, bool, error) {
  3389. current, err := s.checkIsEnabledByEmail(inboundSvc, clientEmail)
  3390. if err != nil {
  3391. return false, false, err
  3392. }
  3393. if current == enable {
  3394. return false, false, nil
  3395. }
  3396. newEnabled, needRestart, err := s.ToggleClientEnableByEmail(inboundSvc, clientEmail)
  3397. if err != nil {
  3398. return false, needRestart, err
  3399. }
  3400. return newEnabled == enable, needRestart, nil
  3401. }
  3402. func (s *ClientService) ResetClientIpLimitByEmail(inboundSvc *InboundService, clientEmail string, count int) (bool, error) {
  3403. _, inbound, err := inboundSvc.GetClientInboundByEmail(clientEmail)
  3404. if err != nil {
  3405. return false, err
  3406. }
  3407. if inbound == nil {
  3408. return false, common.NewError("Inbound Not Found For Email:", clientEmail)
  3409. }
  3410. oldClients, err := inboundSvc.GetClients(inbound)
  3411. if err != nil {
  3412. return false, err
  3413. }
  3414. clientId := ""
  3415. for _, oldClient := range oldClients {
  3416. if oldClient.Email == clientEmail {
  3417. switch inbound.Protocol {
  3418. case "trojan":
  3419. clientId = oldClient.Password
  3420. case "shadowsocks":
  3421. clientId = oldClient.Email
  3422. default:
  3423. clientId = oldClient.ID
  3424. }
  3425. break
  3426. }
  3427. }
  3428. if len(clientId) == 0 {
  3429. return false, common.NewError("Client Not Found For Email:", clientEmail)
  3430. }
  3431. var settings map[string]any
  3432. err = json.Unmarshal([]byte(inbound.Settings), &settings)
  3433. if err != nil {
  3434. return false, err
  3435. }
  3436. clients := settings["clients"].([]any)
  3437. var newClients []any
  3438. for client_index := range clients {
  3439. c := clients[client_index].(map[string]any)
  3440. if c["email"] == clientEmail {
  3441. c["limitIp"] = count
  3442. c["updated_at"] = time.Now().Unix() * 1000
  3443. newClients = append(newClients, any(c))
  3444. }
  3445. }
  3446. settings["clients"] = newClients
  3447. modifiedSettings, err := json.MarshalIndent(settings, "", " ")
  3448. if err != nil {
  3449. return false, err
  3450. }
  3451. inbound.Settings = string(modifiedSettings)
  3452. needRestart, err := s.UpdateInboundClient(inboundSvc, inbound, clientId)
  3453. return needRestart, err
  3454. }
  3455. func (s *ClientService) ResetClientExpiryTimeByEmail(inboundSvc *InboundService, clientEmail string, expiry_time int64) (bool, error) {
  3456. _, inbound, err := inboundSvc.GetClientInboundByEmail(clientEmail)
  3457. if err != nil {
  3458. return false, err
  3459. }
  3460. if inbound == nil {
  3461. return false, common.NewError("Inbound Not Found For Email:", clientEmail)
  3462. }
  3463. oldClients, err := inboundSvc.GetClients(inbound)
  3464. if err != nil {
  3465. return false, err
  3466. }
  3467. clientId := ""
  3468. for _, oldClient := range oldClients {
  3469. if oldClient.Email == clientEmail {
  3470. switch inbound.Protocol {
  3471. case "trojan":
  3472. clientId = oldClient.Password
  3473. case "shadowsocks":
  3474. clientId = oldClient.Email
  3475. default:
  3476. clientId = oldClient.ID
  3477. }
  3478. break
  3479. }
  3480. }
  3481. if len(clientId) == 0 {
  3482. return false, common.NewError("Client Not Found For Email:", clientEmail)
  3483. }
  3484. var settings map[string]any
  3485. err = json.Unmarshal([]byte(inbound.Settings), &settings)
  3486. if err != nil {
  3487. return false, err
  3488. }
  3489. clients := settings["clients"].([]any)
  3490. var newClients []any
  3491. for client_index := range clients {
  3492. c := clients[client_index].(map[string]any)
  3493. if c["email"] == clientEmail {
  3494. c["expiryTime"] = expiry_time
  3495. c["updated_at"] = time.Now().Unix() * 1000
  3496. newClients = append(newClients, any(c))
  3497. }
  3498. }
  3499. settings["clients"] = newClients
  3500. modifiedSettings, err := json.MarshalIndent(settings, "", " ")
  3501. if err != nil {
  3502. return false, err
  3503. }
  3504. inbound.Settings = string(modifiedSettings)
  3505. needRestart, err := s.UpdateInboundClient(inboundSvc, inbound, clientId)
  3506. return needRestart, err
  3507. }
  3508. func (s *ClientService) ResetClientTrafficLimitByEmail(inboundSvc *InboundService, clientEmail string, totalGB int) (bool, error) {
  3509. if totalGB < 0 {
  3510. return false, common.NewError("totalGB must be >= 0")
  3511. }
  3512. _, inbound, err := inboundSvc.GetClientInboundByEmail(clientEmail)
  3513. if err != nil {
  3514. return false, err
  3515. }
  3516. if inbound == nil {
  3517. return false, common.NewError("Inbound Not Found For Email:", clientEmail)
  3518. }
  3519. oldClients, err := inboundSvc.GetClients(inbound)
  3520. if err != nil {
  3521. return false, err
  3522. }
  3523. clientId := ""
  3524. for _, oldClient := range oldClients {
  3525. if oldClient.Email == clientEmail {
  3526. switch inbound.Protocol {
  3527. case "trojan":
  3528. clientId = oldClient.Password
  3529. case "shadowsocks":
  3530. clientId = oldClient.Email
  3531. default:
  3532. clientId = oldClient.ID
  3533. }
  3534. break
  3535. }
  3536. }
  3537. if len(clientId) == 0 {
  3538. return false, common.NewError("Client Not Found For Email:", clientEmail)
  3539. }
  3540. var settings map[string]any
  3541. err = json.Unmarshal([]byte(inbound.Settings), &settings)
  3542. if err != nil {
  3543. return false, err
  3544. }
  3545. clients := settings["clients"].([]any)
  3546. var newClients []any
  3547. for client_index := range clients {
  3548. c := clients[client_index].(map[string]any)
  3549. if c["email"] == clientEmail {
  3550. c["totalGB"] = totalGB * 1024 * 1024 * 1024
  3551. c["updated_at"] = time.Now().Unix() * 1000
  3552. newClients = append(newClients, any(c))
  3553. }
  3554. }
  3555. settings["clients"] = newClients
  3556. modifiedSettings, err := json.MarshalIndent(settings, "", " ")
  3557. if err != nil {
  3558. return false, err
  3559. }
  3560. inbound.Settings = string(modifiedSettings)
  3561. needRestart, err := s.UpdateInboundClient(inboundSvc, inbound, clientId)
  3562. return needRestart, err
  3563. }