client.go 63 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445
  1. package service
  2. import (
  3. "context"
  4. "encoding/base64"
  5. "encoding/json"
  6. "errors"
  7. "fmt"
  8. "sort"
  9. "strings"
  10. "sync"
  11. "time"
  12. "github.com/google/uuid"
  13. "github.com/mhsanaei/3x-ui/v3/database"
  14. "github.com/mhsanaei/3x-ui/v3/database/model"
  15. "github.com/mhsanaei/3x-ui/v3/logger"
  16. "github.com/mhsanaei/3x-ui/v3/util/common"
  17. "github.com/mhsanaei/3x-ui/v3/util/random"
  18. "github.com/mhsanaei/3x-ui/v3/xray"
  19. "gorm.io/gorm"
  20. )
  21. type ClientWithAttachments struct {
  22. model.ClientRecord
  23. InboundIds []int `json:"inboundIds"`
  24. Traffic *xray.ClientTraffic `json:"traffic,omitempty"`
  25. }
  26. // MarshalJSON is required because model.ClientRecord defines its own
  27. // MarshalJSON. Go promotes the embedded method to the outer struct, so without
  28. // this the encoder would call ClientRecord.MarshalJSON for the whole value and
  29. // silently drop InboundIds and Traffic from the API response.
  30. func (c ClientWithAttachments) MarshalJSON() ([]byte, error) {
  31. rec, err := json.Marshal(c.ClientRecord)
  32. if err != nil {
  33. return nil, err
  34. }
  35. extras := struct {
  36. InboundIds []int `json:"inboundIds"`
  37. Traffic *xray.ClientTraffic `json:"traffic,omitempty"`
  38. }{InboundIds: c.InboundIds, Traffic: c.Traffic}
  39. extra, err := json.Marshal(extras)
  40. if err != nil {
  41. return nil, err
  42. }
  43. if len(rec) < 2 || rec[len(rec)-1] != '}' || len(extra) <= 2 {
  44. return rec, nil
  45. }
  46. const maxMarshalSize = 256 << 20
  47. if len(rec) > maxMarshalSize || len(extra) > maxMarshalSize {
  48. return rec, nil
  49. }
  50. out := make([]byte, 0, len(rec)+len(extra))
  51. out = append(out, rec[:len(rec)-1]...)
  52. if len(rec) > 2 {
  53. out = append(out, ',')
  54. }
  55. out = append(out, extra[1:]...)
  56. return out, nil
  57. }
  58. func clientKeyForProtocol(p model.Protocol, rec *model.ClientRecord) string {
  59. if rec == nil {
  60. return ""
  61. }
  62. switch p {
  63. case model.Trojan:
  64. return rec.Password
  65. case model.Shadowsocks:
  66. return rec.Email
  67. case model.Hysteria, model.Hysteria2:
  68. return rec.Auth
  69. default:
  70. return rec.UUID
  71. }
  72. }
  73. type ClientService struct{}
  74. // Short-lived tombstone of just-deleted client emails so that a node snapshot
  75. // arriving between delete and node-side processing doesn't resurrect them.
  76. var (
  77. recentlyDeletedMu sync.Mutex
  78. recentlyDeleted = map[string]time.Time{}
  79. )
  80. const deleteTombstoneTTL = 90 * time.Second
  81. var (
  82. inboundMutationLocksMu sync.Mutex
  83. inboundMutationLocks = map[int]*sync.Mutex{}
  84. )
  85. func lockInbound(inboundId int) *sync.Mutex {
  86. inboundMutationLocksMu.Lock()
  87. defer inboundMutationLocksMu.Unlock()
  88. m, ok := inboundMutationLocks[inboundId]
  89. if !ok {
  90. m = &sync.Mutex{}
  91. inboundMutationLocks[inboundId] = m
  92. }
  93. m.Lock()
  94. return m
  95. }
  96. func compactOrphans(db *gorm.DB, clients []any) []any {
  97. if len(clients) == 0 {
  98. return clients
  99. }
  100. emails := make([]string, 0, len(clients))
  101. for _, c := range clients {
  102. cm, ok := c.(map[string]any)
  103. if !ok {
  104. continue
  105. }
  106. if e, _ := cm["email"].(string); e != "" {
  107. emails = append(emails, e)
  108. }
  109. }
  110. if len(emails) == 0 {
  111. return clients
  112. }
  113. var existingEmails []string
  114. if err := db.Model(&model.ClientRecord{}).Where("email IN ?", emails).Pluck("email", &existingEmails).Error; err != nil {
  115. logger.Warning("compactOrphans pluck:", err)
  116. return clients
  117. }
  118. if len(existingEmails) == len(emails) {
  119. return clients
  120. }
  121. existing := make(map[string]struct{}, len(existingEmails))
  122. for _, e := range existingEmails {
  123. existing[e] = struct{}{}
  124. }
  125. out := make([]any, 0, len(existingEmails))
  126. for _, c := range clients {
  127. cm, ok := c.(map[string]any)
  128. if !ok {
  129. out = append(out, c)
  130. continue
  131. }
  132. e, _ := cm["email"].(string)
  133. if e == "" {
  134. out = append(out, c)
  135. continue
  136. }
  137. if _, ok := existing[e]; ok {
  138. out = append(out, c)
  139. }
  140. }
  141. return out
  142. }
  143. func tombstoneClientEmail(email string) {
  144. if email == "" {
  145. return
  146. }
  147. recentlyDeletedMu.Lock()
  148. defer recentlyDeletedMu.Unlock()
  149. recentlyDeleted[email] = time.Now()
  150. cutoff := time.Now().Add(-deleteTombstoneTTL)
  151. for e, ts := range recentlyDeleted {
  152. if ts.Before(cutoff) {
  153. delete(recentlyDeleted, e)
  154. }
  155. }
  156. }
  157. func isClientEmailTombstoned(email string) bool {
  158. if email == "" {
  159. return false
  160. }
  161. recentlyDeletedMu.Lock()
  162. defer recentlyDeletedMu.Unlock()
  163. ts, ok := recentlyDeleted[email]
  164. if !ok {
  165. return false
  166. }
  167. if time.Since(ts) > deleteTombstoneTTL {
  168. delete(recentlyDeleted, email)
  169. return false
  170. }
  171. return true
  172. }
  173. func (s *ClientService) SyncInbound(tx *gorm.DB, inboundId int, clients []model.Client) error {
  174. if tx == nil {
  175. tx = database.GetDB()
  176. }
  177. if err := tx.Where("inbound_id = ?", inboundId).Delete(&model.ClientInbound{}).Error; err != nil {
  178. return err
  179. }
  180. for i := range clients {
  181. c := clients[i]
  182. email := strings.TrimSpace(c.Email)
  183. if email == "" {
  184. continue
  185. }
  186. incoming := c.ToRecord()
  187. row := &model.ClientRecord{}
  188. err := tx.Where("email = ?", email).First(row).Error
  189. if err != nil && !errors.Is(err, gorm.ErrRecordNotFound) {
  190. return err
  191. }
  192. if errors.Is(err, gorm.ErrRecordNotFound) {
  193. if err := tx.Create(incoming).Error; err != nil {
  194. return err
  195. }
  196. row = incoming
  197. } else {
  198. row.UUID = incoming.UUID
  199. row.Password = incoming.Password
  200. row.Auth = incoming.Auth
  201. row.Flow = incoming.Flow
  202. row.Security = incoming.Security
  203. row.Reverse = incoming.Reverse
  204. row.SubID = incoming.SubID
  205. row.LimitIP = incoming.LimitIP
  206. row.TotalGB = incoming.TotalGB
  207. row.ExpiryTime = incoming.ExpiryTime
  208. row.Enable = incoming.Enable
  209. row.TgID = incoming.TgID
  210. row.Comment = incoming.Comment
  211. row.Reset = incoming.Reset
  212. if incoming.CreatedAt > 0 && (row.CreatedAt == 0 || incoming.CreatedAt < row.CreatedAt) {
  213. row.CreatedAt = incoming.CreatedAt
  214. }
  215. if incoming.UpdatedAt > row.UpdatedAt {
  216. row.UpdatedAt = incoming.UpdatedAt
  217. }
  218. if err := tx.Save(row).Error; err != nil {
  219. return err
  220. }
  221. }
  222. link := model.ClientInbound{
  223. ClientId: row.Id,
  224. InboundId: inboundId,
  225. FlowOverride: c.Flow,
  226. }
  227. if err := tx.Create(&link).Error; err != nil {
  228. return err
  229. }
  230. }
  231. return nil
  232. }
  233. func (s *ClientService) DetachInbound(tx *gorm.DB, inboundId int) error {
  234. if tx == nil {
  235. tx = database.GetDB()
  236. }
  237. return tx.Where("inbound_id = ?", inboundId).Delete(&model.ClientInbound{}).Error
  238. }
  239. func (s *ClientService) ListForInbound(tx *gorm.DB, inboundId int) ([]model.Client, error) {
  240. if tx == nil {
  241. tx = database.GetDB()
  242. }
  243. type joinedRow struct {
  244. model.ClientRecord
  245. FlowOverride string
  246. }
  247. var rows []joinedRow
  248. err := tx.Table("clients").
  249. Select("clients.*, client_inbounds.flow_override AS flow_override").
  250. Joins("JOIN client_inbounds ON client_inbounds.client_id = clients.id").
  251. Where("client_inbounds.inbound_id = ?", inboundId).
  252. Order("clients.id ASC").
  253. Find(&rows).Error
  254. if err != nil {
  255. return nil, err
  256. }
  257. out := make([]model.Client, 0, len(rows))
  258. for i := range rows {
  259. c := rows[i].ToClient()
  260. if rows[i].FlowOverride != "" {
  261. c.Flow = rows[i].FlowOverride
  262. }
  263. out = append(out, *c)
  264. }
  265. return out, nil
  266. }
  267. func (s *ClientService) GetRecordByEmail(tx *gorm.DB, email string) (*model.ClientRecord, error) {
  268. if tx == nil {
  269. tx = database.GetDB()
  270. }
  271. row := &model.ClientRecord{}
  272. err := tx.Where("email = ?", email).First(row).Error
  273. if err != nil {
  274. return nil, err
  275. }
  276. return row, nil
  277. }
  278. func (s *ClientService) GetInboundIdsForEmail(tx *gorm.DB, email string) ([]int, error) {
  279. if tx == nil {
  280. tx = database.GetDB()
  281. }
  282. var ids []int
  283. err := tx.Table("client_inbounds").
  284. Select("client_inbounds.inbound_id").
  285. Joins("JOIN clients ON clients.id = client_inbounds.client_id").
  286. Where("clients.email = ?", email).
  287. Scan(&ids).Error
  288. if err != nil {
  289. return nil, err
  290. }
  291. return ids, nil
  292. }
  293. func (s *ClientService) GetByID(id int) (*model.ClientRecord, error) {
  294. row := &model.ClientRecord{}
  295. if err := database.GetDB().Where("id = ?", id).First(row).Error; err != nil {
  296. return nil, err
  297. }
  298. return row, nil
  299. }
  300. func (s *ClientService) GetInboundIdsForRecord(id int) ([]int, error) {
  301. var ids []int
  302. err := database.GetDB().Table("client_inbounds").
  303. Where("client_id = ?", id).
  304. Order("inbound_id ASC").
  305. Pluck("inbound_id", &ids).Error
  306. if err != nil {
  307. return nil, err
  308. }
  309. return ids, nil
  310. }
  311. func (s *ClientService) List() ([]ClientWithAttachments, error) {
  312. db := database.GetDB()
  313. var rows []model.ClientRecord
  314. if err := db.Order("id ASC").Find(&rows).Error; err != nil {
  315. return nil, err
  316. }
  317. if len(rows) == 0 {
  318. return []ClientWithAttachments{}, nil
  319. }
  320. clientIds := make([]int, 0, len(rows))
  321. emails := make([]string, 0, len(rows))
  322. for i := range rows {
  323. clientIds = append(clientIds, rows[i].Id)
  324. if rows[i].Email != "" {
  325. emails = append(emails, rows[i].Email)
  326. }
  327. }
  328. var links []model.ClientInbound
  329. if err := db.Where("client_id IN ?", clientIds).Find(&links).Error; err != nil {
  330. return nil, err
  331. }
  332. attachments := make(map[int][]int, len(rows))
  333. for _, l := range links {
  334. attachments[l.ClientId] = append(attachments[l.ClientId], l.InboundId)
  335. }
  336. trafficByEmail := make(map[string]*xray.ClientTraffic, len(emails))
  337. if len(emails) > 0 {
  338. var stats []xray.ClientTraffic
  339. if err := db.Where("email IN ?", emails).Find(&stats).Error; err != nil {
  340. return nil, err
  341. }
  342. for i := range stats {
  343. trafficByEmail[stats[i].Email] = &stats[i]
  344. }
  345. }
  346. out := make([]ClientWithAttachments, 0, len(rows))
  347. for i := range rows {
  348. out = append(out, ClientWithAttachments{
  349. ClientRecord: rows[i],
  350. InboundIds: attachments[rows[i].Id],
  351. Traffic: trafficByEmail[rows[i].Email],
  352. })
  353. }
  354. return out, nil
  355. }
  356. type ClientCreatePayload struct {
  357. Client model.Client `json:"client"`
  358. InboundIds []int `json:"inboundIds"`
  359. }
  360. func (s *ClientService) Create(inboundSvc *InboundService, payload *ClientCreatePayload) (bool, error) {
  361. if payload == nil {
  362. return false, common.NewError("empty payload")
  363. }
  364. client := payload.Client
  365. if strings.TrimSpace(client.Email) == "" {
  366. return false, common.NewError("client email is required")
  367. }
  368. if len(payload.InboundIds) == 0 {
  369. return false, common.NewError("at least one inbound is required")
  370. }
  371. if client.SubID == "" {
  372. client.SubID = uuid.NewString()
  373. }
  374. if !client.Enable {
  375. client.Enable = true
  376. }
  377. now := time.Now().UnixMilli()
  378. if client.CreatedAt == 0 {
  379. client.CreatedAt = now
  380. }
  381. client.UpdatedAt = now
  382. existing := &model.ClientRecord{}
  383. err := database.GetDB().Where("email = ?", client.Email).First(existing).Error
  384. if err != nil && !errors.Is(err, gorm.ErrRecordNotFound) {
  385. return false, err
  386. }
  387. emailTaken := !errors.Is(err, gorm.ErrRecordNotFound)
  388. if emailTaken {
  389. if existing.SubID == "" || existing.SubID != client.SubID {
  390. return false, common.NewError("email already in use:", client.Email)
  391. }
  392. }
  393. needRestart := false
  394. for _, ibId := range payload.InboundIds {
  395. inbound, getErr := inboundSvc.GetInbound(ibId)
  396. if getErr != nil {
  397. return needRestart, getErr
  398. }
  399. if err := s.fillProtocolDefaults(&client, inbound); err != nil {
  400. return needRestart, err
  401. }
  402. settingsPayload, mErr := json.Marshal(map[string][]model.Client{"clients": {client}})
  403. if mErr != nil {
  404. return needRestart, mErr
  405. }
  406. nr, addErr := s.AddInboundClient(inboundSvc, &model.Inbound{
  407. Id: ibId,
  408. Settings: string(settingsPayload),
  409. })
  410. if addErr != nil {
  411. return needRestart, addErr
  412. }
  413. if nr {
  414. needRestart = true
  415. }
  416. }
  417. return needRestart, nil
  418. }
  419. func (s *ClientService) fillProtocolDefaults(c *model.Client, ib *model.Inbound) error {
  420. switch ib.Protocol {
  421. case model.VMESS, model.VLESS:
  422. if c.ID == "" {
  423. c.ID = uuid.NewString()
  424. }
  425. case model.Trojan:
  426. if c.Password == "" {
  427. c.Password = strings.ReplaceAll(uuid.NewString(), "-", "")
  428. }
  429. case model.Shadowsocks:
  430. method := shadowsocksMethodFromSettings(ib.Settings)
  431. if c.Password == "" || !validShadowsocksClientKey(method, c.Password) {
  432. c.Password = randomShadowsocksClientKey(method)
  433. }
  434. case model.Hysteria, model.Hysteria2:
  435. if c.Auth == "" {
  436. c.Auth = strings.ReplaceAll(uuid.NewString(), "-", "")
  437. }
  438. }
  439. return nil
  440. }
  441. // shadowsocksMethodFromSettings pulls the "method" field out of the inbound's
  442. // settings JSON. Returns "" when the field is missing or settings is invalid.
  443. func shadowsocksMethodFromSettings(settings string) string {
  444. if settings == "" {
  445. return ""
  446. }
  447. var m map[string]any
  448. if err := json.Unmarshal([]byte(settings), &m); err != nil {
  449. return ""
  450. }
  451. method, _ := m["method"].(string)
  452. return method
  453. }
  454. // randomShadowsocksClientKey returns a per-client key sized to the cipher.
  455. // The 2022-blake3 ciphers require a base64-encoded key of an exact byte
  456. // length (16 bytes for aes-128-gcm, 32 bytes for aes-256-gcm and
  457. // chacha20-poly1305) — anything else fails with "bad key" on xray start.
  458. // Older ciphers accept arbitrary passwords, so we keep the uuid-style.
  459. func randomShadowsocksClientKey(method string) string {
  460. if n := shadowsocksKeyBytes(method); n > 0 {
  461. return random.Base64Bytes(n)
  462. }
  463. return strings.ReplaceAll(uuid.NewString(), "-", "")
  464. }
  465. // validShadowsocksClientKey reports whether key is acceptable for the cipher.
  466. // For 2022-blake3 it must decode to the exact byte length the cipher needs;
  467. // any other method accepts any non-empty string.
  468. func validShadowsocksClientKey(method, key string) bool {
  469. n := shadowsocksKeyBytes(method)
  470. if n == 0 {
  471. return key != ""
  472. }
  473. decoded, err := base64.StdEncoding.DecodeString(key)
  474. if err != nil {
  475. return false
  476. }
  477. return len(decoded) == n
  478. }
  479. func shadowsocksKeyBytes(method string) int {
  480. switch method {
  481. case "2022-blake3-aes-128-gcm":
  482. return 16
  483. case "2022-blake3-aes-256-gcm", "2022-blake3-chacha20-poly1305":
  484. return 32
  485. }
  486. return 0
  487. }
  488. // applyShadowsocksClientMethod ensures each client entry carries a "method"
  489. // field for legacy shadowsocks ciphers. xray's multi-user shadowsocks code
  490. // requires a per-client method; an empty/missing field fails with
  491. // "unsupported cipher method:". 2022-blake3 ciphers use the top-level
  492. // method only, so the per-client field must stay absent.
  493. func applyShadowsocksClientMethod(clients []any, settings map[string]any) {
  494. method, _ := settings["method"].(string)
  495. if method == "" || strings.HasPrefix(method, "2022-blake3-") {
  496. return
  497. }
  498. for i := range clients {
  499. cm, ok := clients[i].(map[string]any)
  500. if !ok {
  501. continue
  502. }
  503. if existing, _ := cm["method"].(string); existing != "" {
  504. continue
  505. }
  506. cm["method"] = method
  507. clients[i] = cm
  508. }
  509. }
  510. func (s *ClientService) Update(inboundSvc *InboundService, id int, updated model.Client) (bool, error) {
  511. existing, err := s.GetByID(id)
  512. if err != nil {
  513. return false, err
  514. }
  515. inboundIds, err := s.GetInboundIdsForRecord(id)
  516. if err != nil {
  517. return false, err
  518. }
  519. if strings.TrimSpace(updated.Email) == "" {
  520. return false, common.NewError("client email is required")
  521. }
  522. if updated.SubID == "" {
  523. updated.SubID = existing.SubID
  524. }
  525. if updated.SubID == "" {
  526. updated.SubID = uuid.NewString()
  527. }
  528. updated.UpdatedAt = time.Now().UnixMilli()
  529. if updated.CreatedAt == 0 {
  530. updated.CreatedAt = existing.CreatedAt
  531. }
  532. needRestart := false
  533. for _, ibId := range inboundIds {
  534. inbound, getErr := inboundSvc.GetInbound(ibId)
  535. if getErr != nil {
  536. return needRestart, getErr
  537. }
  538. oldKey := clientKeyForProtocol(inbound.Protocol, existing)
  539. if oldKey == "" {
  540. continue
  541. }
  542. if err := s.fillProtocolDefaults(&updated, inbound); err != nil {
  543. return needRestart, err
  544. }
  545. settingsPayload, mErr := json.Marshal(map[string][]model.Client{"clients": {updated}})
  546. if mErr != nil {
  547. return needRestart, mErr
  548. }
  549. nr, upErr := s.UpdateInboundClient(inboundSvc, &model.Inbound{
  550. Id: ibId,
  551. Settings: string(settingsPayload),
  552. }, oldKey)
  553. if upErr != nil {
  554. return needRestart, upErr
  555. }
  556. if nr {
  557. needRestart = true
  558. }
  559. }
  560. if err := database.GetDB().Model(&model.ClientRecord{}).
  561. Where("id = ?", id).
  562. Update("updated_at", updated.UpdatedAt).Error; err != nil {
  563. return needRestart, err
  564. }
  565. return needRestart, nil
  566. }
  567. func (s *ClientService) Delete(inboundSvc *InboundService, id int, keepTraffic bool) (bool, error) {
  568. existing, err := s.GetByID(id)
  569. if err != nil {
  570. return false, err
  571. }
  572. tombstoneClientEmail(existing.Email)
  573. inboundIds, err := s.GetInboundIdsForRecord(id)
  574. if err != nil {
  575. return false, err
  576. }
  577. needRestart := false
  578. for _, ibId := range inboundIds {
  579. inbound, getErr := inboundSvc.GetInbound(ibId)
  580. if getErr != nil {
  581. return needRestart, getErr
  582. }
  583. key := clientKeyForProtocol(inbound.Protocol, existing)
  584. if key == "" {
  585. continue
  586. }
  587. nr, delErr := s.DelInboundClient(inboundSvc, ibId, key)
  588. if delErr != nil {
  589. return needRestart, delErr
  590. }
  591. if nr {
  592. needRestart = true
  593. }
  594. }
  595. db := database.GetDB()
  596. if err := db.Where("client_id = ?", id).Delete(&model.ClientInbound{}).Error; err != nil {
  597. return needRestart, err
  598. }
  599. if !keepTraffic && existing.Email != "" {
  600. if err := db.Where("email = ?", existing.Email).Delete(&xray.ClientTraffic{}).Error; err != nil {
  601. return needRestart, err
  602. }
  603. if err := db.Where("client_email = ?", existing.Email).Delete(&model.InboundClientIps{}).Error; err != nil {
  604. return needRestart, err
  605. }
  606. }
  607. if err := db.Delete(&model.ClientRecord{}, id).Error; err != nil {
  608. return needRestart, err
  609. }
  610. return needRestart, nil
  611. }
  612. func (s *ClientService) Attach(inboundSvc *InboundService, id int, inboundIds []int) (bool, error) {
  613. existing, err := s.GetByID(id)
  614. if err != nil {
  615. return false, err
  616. }
  617. currentIds, err := s.GetInboundIdsForRecord(id)
  618. if err != nil {
  619. return false, err
  620. }
  621. have := make(map[int]struct{}, len(currentIds))
  622. for _, x := range currentIds {
  623. have[x] = struct{}{}
  624. }
  625. clientWire := existing.ToClient()
  626. clientWire.UpdatedAt = time.Now().UnixMilli()
  627. needRestart := false
  628. for _, ibId := range inboundIds {
  629. if _, attached := have[ibId]; attached {
  630. continue
  631. }
  632. inbound, getErr := inboundSvc.GetInbound(ibId)
  633. if getErr != nil {
  634. return needRestart, getErr
  635. }
  636. copyClient := *clientWire
  637. if err := s.fillProtocolDefaults(&copyClient, inbound); err != nil {
  638. return needRestart, err
  639. }
  640. settingsPayload, mErr := json.Marshal(map[string][]model.Client{"clients": {copyClient}})
  641. if mErr != nil {
  642. return needRestart, mErr
  643. }
  644. nr, addErr := s.AddInboundClient(inboundSvc, &model.Inbound{
  645. Id: ibId,
  646. Settings: string(settingsPayload),
  647. })
  648. if addErr != nil {
  649. return needRestart, addErr
  650. }
  651. if nr {
  652. needRestart = true
  653. }
  654. }
  655. return needRestart, nil
  656. }
  657. func (s *ClientService) CreateOne(inboundSvc *InboundService, inboundId int, client model.Client) (bool, error) {
  658. return s.Create(inboundSvc, &ClientCreatePayload{
  659. Client: client,
  660. InboundIds: []int{inboundId},
  661. })
  662. }
  663. func (s *ClientService) DetachByEmail(inboundSvc *InboundService, inboundId int, email string) (bool, error) {
  664. if email == "" {
  665. return false, common.NewError("client email is required")
  666. }
  667. rec, err := s.GetRecordByEmail(nil, email)
  668. if err != nil {
  669. return false, err
  670. }
  671. return s.Detach(inboundSvc, rec.Id, []int{inboundId})
  672. }
  673. func (s *ClientService) AttachByEmail(inboundSvc *InboundService, email string, inboundIds []int) (bool, error) {
  674. if email == "" {
  675. return false, common.NewError("client email is required")
  676. }
  677. rec, err := s.GetRecordByEmail(nil, email)
  678. if err != nil {
  679. return false, err
  680. }
  681. return s.Attach(inboundSvc, rec.Id, inboundIds)
  682. }
  683. func (s *ClientService) DetachByEmailMany(inboundSvc *InboundService, email string, inboundIds []int) (bool, error) {
  684. if email == "" {
  685. return false, common.NewError("client email is required")
  686. }
  687. rec, err := s.GetRecordByEmail(nil, email)
  688. if err != nil {
  689. return false, err
  690. }
  691. return s.Detach(inboundSvc, rec.Id, inboundIds)
  692. }
  693. func (s *ClientService) DeleteByEmail(inboundSvc *InboundService, email string, keepTraffic bool) (bool, error) {
  694. if email == "" {
  695. return false, common.NewError("client email is required")
  696. }
  697. rec, err := s.GetRecordByEmail(nil, email)
  698. if err != nil {
  699. return false, err
  700. }
  701. return s.Delete(inboundSvc, rec.Id, keepTraffic)
  702. }
  703. func (s *ClientService) UpdateByEmail(inboundSvc *InboundService, email string, updated model.Client) (bool, error) {
  704. if email == "" {
  705. return false, common.NewError("client email is required")
  706. }
  707. rec, err := s.GetRecordByEmail(nil, email)
  708. if err != nil {
  709. return false, err
  710. }
  711. return s.Update(inboundSvc, rec.Id, updated)
  712. }
  713. func (s *ClientService) ResetTrafficByEmail(inboundSvc *InboundService, email string) (bool, error) {
  714. if email == "" {
  715. return false, common.NewError("client email is required")
  716. }
  717. rec, err := s.GetRecordByEmail(nil, email)
  718. if err != nil {
  719. return false, err
  720. }
  721. inboundIds, err := s.GetInboundIdsForRecord(rec.Id)
  722. if err != nil {
  723. return false, err
  724. }
  725. if len(inboundIds) == 0 {
  726. if rErr := inboundSvc.ResetClientTrafficByEmail(email); rErr != nil {
  727. return false, rErr
  728. }
  729. return false, nil
  730. }
  731. needRestart := false
  732. for _, ibId := range inboundIds {
  733. nr, rErr := inboundSvc.ResetClientTraffic(ibId, email)
  734. if rErr != nil {
  735. return needRestart, rErr
  736. }
  737. if nr {
  738. needRestart = true
  739. }
  740. }
  741. return needRestart, nil
  742. }
  743. // ClientSlim is the row-shape used by the clients page. It drops fields the
  744. // table never reads (UUID, password, auth, flow, security, reverse, tgId)
  745. // so the list payload stays compact even when the panel manages thousands
  746. // of clients. Modals that need the full record still call /get/:email.
  747. type ClientSlim struct {
  748. Email string `json:"email"`
  749. SubID string `json:"subId"`
  750. Enable bool `json:"enable"`
  751. TotalGB int64 `json:"totalGB"`
  752. ExpiryTime int64 `json:"expiryTime"`
  753. LimitIP int `json:"limitIp"`
  754. Reset int `json:"reset"`
  755. Comment string `json:"comment,omitempty"`
  756. InboundIds []int `json:"inboundIds"`
  757. Traffic *xray.ClientTraffic `json:"traffic,omitempty"`
  758. CreatedAt int64 `json:"createdAt"`
  759. UpdatedAt int64 `json:"updatedAt"`
  760. }
  761. // ClientPageParams are the query params accepted by /panel/api/clients/list/paged.
  762. // All fields are optional — the empty value means "no filter" / defaults.
  763. type ClientPageParams struct {
  764. Page int `form:"page"`
  765. PageSize int `form:"pageSize"`
  766. Search string `form:"search"`
  767. Filter string `form:"filter"`
  768. Protocol string `form:"protocol"`
  769. Inbound int `form:"inbound"`
  770. Sort string `form:"sort"`
  771. Order string `form:"order"`
  772. }
  773. // ClientPageResponse is the shape returned by ListPaged. `Total` is the
  774. // row count in the DB; `Filtered` is the count after Search/Filter/Protocol
  775. // were applied, before pagination. The page contains at most PageSize items.
  776. // Summary is computed across the full DB row set so dashboard counters
  777. // on the clients page stay stable as the user paginates/filters.
  778. type ClientPageResponse struct {
  779. Items []ClientSlim `json:"items"`
  780. Total int `json:"total"`
  781. Filtered int `json:"filtered"`
  782. Page int `json:"page"`
  783. PageSize int `json:"pageSize"`
  784. Summary ClientsSummary `json:"summary"`
  785. }
  786. // ClientsSummary collects per-bucket counts plus the matching email lists so
  787. // the clients page can render the dashboard stat cards and their hover
  788. // popovers without shipping the full client array.
  789. type ClientsSummary struct {
  790. Total int `json:"total"`
  791. Active int `json:"active"`
  792. Online []string `json:"online"`
  793. Depleted []string `json:"depleted"`
  794. Expiring []string `json:"expiring"`
  795. Deactive []string `json:"deactive"`
  796. }
  797. const (
  798. clientPageDefaultSize = 25
  799. clientPageMaxSize = 200
  800. )
  801. // ListPaged loads every client (with traffic + attachments) into memory,
  802. // applies the requested filter / search / protocol predicates, sorts, and
  803. // returns the requested page along with total and filtered counts. The DB
  804. // query itself is unchanged from List(); the win is that the response
  805. // only carries 25-ish slim rows over the wire instead of all 2000 full
  806. // records, which on real panels was the dominant cost.
  807. func (s *ClientService) ListPaged(inboundSvc *InboundService, settingSvc *SettingService, params ClientPageParams) (*ClientPageResponse, error) {
  808. all, err := s.List()
  809. if err != nil {
  810. return nil, err
  811. }
  812. total := len(all)
  813. pageSize := params.PageSize
  814. if pageSize <= 0 {
  815. pageSize = clientPageDefaultSize
  816. }
  817. if pageSize > clientPageMaxSize {
  818. pageSize = clientPageMaxSize
  819. }
  820. page := params.Page
  821. if page <= 0 {
  822. page = 1
  823. }
  824. var protocolByInbound map[int]string
  825. if params.Protocol != "" {
  826. inbounds, err := inboundSvc.GetAllInbounds()
  827. if err == nil {
  828. protocolByInbound = make(map[int]string, len(inbounds))
  829. for _, ib := range inbounds {
  830. protocolByInbound[ib.Id] = string(ib.Protocol)
  831. }
  832. }
  833. }
  834. onlines := inboundSvc.GetOnlineClients()
  835. onlineSet := make(map[string]struct{}, len(onlines))
  836. for _, e := range onlines {
  837. onlineSet[e] = struct{}{}
  838. }
  839. var expireDiffMs, trafficDiffBytes int64
  840. if settingSvc != nil {
  841. if v, err := settingSvc.GetExpireDiff(); err == nil {
  842. expireDiffMs = int64(v) * 86400000
  843. }
  844. if v, err := settingSvc.GetTrafficDiff(); err == nil {
  845. trafficDiffBytes = int64(v) * 1073741824
  846. }
  847. }
  848. nowMs := time.Now().UnixMilli()
  849. summary := buildClientsSummary(all, onlineSet, nowMs, expireDiffMs, trafficDiffBytes)
  850. needle := strings.ToLower(strings.TrimSpace(params.Search))
  851. filtered := make([]ClientWithAttachments, 0, len(all))
  852. for _, c := range all {
  853. if needle != "" && !clientMatchesSearch(c, needle) {
  854. continue
  855. }
  856. if params.Protocol != "" && !clientMatchesProtocol(c, params.Protocol, protocolByInbound) {
  857. continue
  858. }
  859. if params.Inbound > 0 && !clientMatchesInbound(c, params.Inbound) {
  860. continue
  861. }
  862. if params.Filter != "" && !clientMatchesBucket(c, params.Filter, onlineSet, nowMs, expireDiffMs, trafficDiffBytes) {
  863. continue
  864. }
  865. filtered = append(filtered, c)
  866. }
  867. sortClients(filtered, params.Sort, params.Order)
  868. filteredCount := len(filtered)
  869. start := (page - 1) * pageSize
  870. end := start + pageSize
  871. if start > filteredCount {
  872. start = filteredCount
  873. }
  874. if end > filteredCount {
  875. end = filteredCount
  876. }
  877. pageRows := filtered[start:end]
  878. items := make([]ClientSlim, 0, len(pageRows))
  879. for _, c := range pageRows {
  880. items = append(items, toClientSlim(c))
  881. }
  882. return &ClientPageResponse{
  883. Items: items,
  884. Total: total,
  885. Filtered: filteredCount,
  886. Page: page,
  887. PageSize: pageSize,
  888. Summary: summary,
  889. }, nil
  890. }
  891. func buildClientsSummary(all []ClientWithAttachments, onlineSet map[string]struct{}, nowMs, expireDiffMs, trafficDiffBytes int64) ClientsSummary {
  892. s := ClientsSummary{
  893. Total: len(all),
  894. Online: []string{},
  895. Depleted: []string{},
  896. Expiring: []string{},
  897. Deactive: []string{},
  898. }
  899. for _, c := range all {
  900. used := int64(0)
  901. if c.Traffic != nil {
  902. used = c.Traffic.Up + c.Traffic.Down
  903. }
  904. exhausted := c.TotalGB > 0 && used >= c.TotalGB
  905. expired := c.ExpiryTime > 0 && c.ExpiryTime <= nowMs
  906. if c.Enable {
  907. if _, ok := onlineSet[c.Email]; ok {
  908. s.Online = append(s.Online, c.Email)
  909. }
  910. }
  911. if exhausted || expired {
  912. s.Depleted = append(s.Depleted, c.Email)
  913. continue
  914. }
  915. if !c.Enable {
  916. s.Deactive = append(s.Deactive, c.Email)
  917. continue
  918. }
  919. nearExpiry := c.ExpiryTime > 0 && c.ExpiryTime-nowMs < expireDiffMs
  920. nearLimit := c.TotalGB > 0 && c.TotalGB-used < trafficDiffBytes
  921. if nearExpiry || nearLimit {
  922. s.Expiring = append(s.Expiring, c.Email)
  923. } else {
  924. s.Active++
  925. }
  926. }
  927. return s
  928. }
  929. func toClientSlim(c ClientWithAttachments) ClientSlim {
  930. return ClientSlim{
  931. Email: c.Email,
  932. SubID: c.SubID,
  933. Enable: c.Enable,
  934. TotalGB: c.TotalGB,
  935. ExpiryTime: c.ExpiryTime,
  936. LimitIP: c.LimitIP,
  937. Reset: c.Reset,
  938. Comment: c.Comment,
  939. InboundIds: c.InboundIds,
  940. Traffic: c.Traffic,
  941. CreatedAt: c.CreatedAt,
  942. UpdatedAt: c.UpdatedAt,
  943. }
  944. }
  945. func clientMatchesSearch(c ClientWithAttachments, needle string) bool {
  946. if needle == "" {
  947. return true
  948. }
  949. if strings.Contains(strings.ToLower(c.Email), needle) {
  950. return true
  951. }
  952. if strings.Contains(strings.ToLower(c.SubID), needle) {
  953. return true
  954. }
  955. if strings.Contains(strings.ToLower(c.Comment), needle) {
  956. return true
  957. }
  958. return false
  959. }
  960. func clientMatchesProtocol(c ClientWithAttachments, protocol string, byInbound map[int]string) bool {
  961. if protocol == "" {
  962. return true
  963. }
  964. for _, id := range c.InboundIds {
  965. if byInbound[id] == protocol {
  966. return true
  967. }
  968. }
  969. return false
  970. }
  971. func clientMatchesInbound(c ClientWithAttachments, inboundId int) bool {
  972. if inboundId <= 0 {
  973. return true
  974. }
  975. for _, id := range c.InboundIds {
  976. if id == inboundId {
  977. return true
  978. }
  979. }
  980. return false
  981. }
  982. func clientMatchesBucket(c ClientWithAttachments, bucket string, onlineSet map[string]struct{}, nowMs, expireDiffMs, trafficDiffBytes int64) bool {
  983. if bucket == "" {
  984. return true
  985. }
  986. used := int64(0)
  987. if c.Traffic != nil {
  988. used = c.Traffic.Up + c.Traffic.Down
  989. }
  990. exhausted := c.TotalGB > 0 && used >= c.TotalGB
  991. expired := c.ExpiryTime > 0 && c.ExpiryTime <= nowMs
  992. switch bucket {
  993. case "online":
  994. if onlineSet == nil {
  995. return false
  996. }
  997. _, ok := onlineSet[c.Email]
  998. return ok && c.Enable
  999. case "depleted":
  1000. return exhausted || expired
  1001. case "deactive":
  1002. return !c.Enable
  1003. case "active":
  1004. return c.Enable && !exhausted && !expired
  1005. case "expiring":
  1006. if !c.Enable || exhausted || expired {
  1007. return false
  1008. }
  1009. nearExpiry := c.ExpiryTime > 0 && c.ExpiryTime-nowMs < expireDiffMs
  1010. nearLimit := c.TotalGB > 0 && c.TotalGB-used < trafficDiffBytes
  1011. return nearExpiry || nearLimit
  1012. }
  1013. return true
  1014. }
  1015. func sortClients(rows []ClientWithAttachments, sortKey, order string) {
  1016. if sortKey == "" {
  1017. return
  1018. }
  1019. desc := order == "descend"
  1020. less := func(i, j int) bool {
  1021. a, b := rows[i], rows[j]
  1022. switch sortKey {
  1023. case "enable":
  1024. if a.Enable == b.Enable {
  1025. return false
  1026. }
  1027. return !a.Enable && b.Enable
  1028. case "email":
  1029. return strings.ToLower(a.Email) < strings.ToLower(b.Email)
  1030. case "inboundIds":
  1031. return len(a.InboundIds) < len(b.InboundIds)
  1032. case "traffic":
  1033. ua := int64(0)
  1034. if a.Traffic != nil {
  1035. ua = a.Traffic.Up + a.Traffic.Down
  1036. }
  1037. ub := int64(0)
  1038. if b.Traffic != nil {
  1039. ub = b.Traffic.Up + b.Traffic.Down
  1040. }
  1041. return ua < ub
  1042. case "remaining":
  1043. ra := int64(1<<62 - 1)
  1044. if a.TotalGB > 0 {
  1045. used := int64(0)
  1046. if a.Traffic != nil {
  1047. used = a.Traffic.Up + a.Traffic.Down
  1048. }
  1049. ra = a.TotalGB - used
  1050. }
  1051. rb := int64(1<<62 - 1)
  1052. if b.TotalGB > 0 {
  1053. used := int64(0)
  1054. if b.Traffic != nil {
  1055. used = b.Traffic.Up + b.Traffic.Down
  1056. }
  1057. rb = b.TotalGB - used
  1058. }
  1059. return ra < rb
  1060. case "expiryTime":
  1061. ea := int64(1<<62 - 1)
  1062. if a.ExpiryTime > 0 {
  1063. ea = a.ExpiryTime
  1064. }
  1065. eb := int64(1<<62 - 1)
  1066. if b.ExpiryTime > 0 {
  1067. eb = b.ExpiryTime
  1068. }
  1069. return ea < eb
  1070. }
  1071. return false
  1072. }
  1073. sort.SliceStable(rows, func(i, j int) bool {
  1074. if desc {
  1075. return less(j, i)
  1076. }
  1077. return less(i, j)
  1078. })
  1079. }
  1080. // BulkAdjustResult is returned by BulkAdjust to report how many clients were
  1081. // successfully updated and which were skipped (typically because the field
  1082. // being adjusted was unlimited for that client) or failed.
  1083. type BulkAdjustResult struct {
  1084. Adjusted int `json:"adjusted"`
  1085. Skipped []BulkAdjustReport `json:"skipped,omitempty"`
  1086. }
  1087. type BulkAdjustReport struct {
  1088. Email string `json:"email"`
  1089. Reason string `json:"reason"`
  1090. }
  1091. // BulkAdjust shifts ExpiryTime by addDays (days) and TotalGB by addBytes
  1092. // for every email in the list. Clients whose corresponding field is
  1093. // unlimited (0) are skipped — bulk extend should not accidentally
  1094. // limit an unlimited client. addDays and addBytes may be negative.
  1095. func (s *ClientService) BulkAdjust(inboundSvc *InboundService, emails []string, addDays int, addBytes int64) (BulkAdjustResult, bool, error) {
  1096. result := BulkAdjustResult{}
  1097. needRestart := false
  1098. if len(emails) == 0 {
  1099. return result, needRestart, nil
  1100. }
  1101. if addDays == 0 && addBytes == 0 {
  1102. return result, needRestart, common.NewError("no adjustment specified")
  1103. }
  1104. addExpiryMs := int64(addDays) * 24 * 60 * 60 * 1000
  1105. for _, email := range emails {
  1106. email = strings.TrimSpace(email)
  1107. if email == "" {
  1108. continue
  1109. }
  1110. rec, err := s.GetRecordByEmail(nil, email)
  1111. if err != nil {
  1112. result.Skipped = append(result.Skipped, BulkAdjustReport{Email: email, Reason: err.Error()})
  1113. continue
  1114. }
  1115. client := rec.ToClient()
  1116. applied := false
  1117. if addDays != 0 {
  1118. switch {
  1119. case rec.ExpiryTime == 0:
  1120. result.Skipped = append(result.Skipped, BulkAdjustReport{Email: email, Reason: "unlimited expiry"})
  1121. case rec.ExpiryTime > 0:
  1122. next := rec.ExpiryTime + addExpiryMs
  1123. if next <= 0 {
  1124. result.Skipped = append(result.Skipped, BulkAdjustReport{Email: email, Reason: "reduction exceeds remaining time"})
  1125. } else {
  1126. client.ExpiryTime = next
  1127. applied = true
  1128. }
  1129. default:
  1130. next := rec.ExpiryTime - addExpiryMs
  1131. if next >= 0 {
  1132. result.Skipped = append(result.Skipped, BulkAdjustReport{Email: email, Reason: "reduction exceeds delay window"})
  1133. } else {
  1134. client.ExpiryTime = next
  1135. applied = true
  1136. }
  1137. }
  1138. }
  1139. if addBytes != 0 {
  1140. if rec.TotalGB == 0 {
  1141. result.Skipped = append(result.Skipped, BulkAdjustReport{Email: email, Reason: "unlimited traffic"})
  1142. } else {
  1143. next := rec.TotalGB + addBytes
  1144. if next < 0 {
  1145. next = 0
  1146. }
  1147. client.TotalGB = next
  1148. applied = true
  1149. }
  1150. }
  1151. if !applied {
  1152. continue
  1153. }
  1154. nr, err := s.Update(inboundSvc, rec.Id, *client)
  1155. if err != nil {
  1156. result.Skipped = append(result.Skipped, BulkAdjustReport{Email: email, Reason: err.Error()})
  1157. continue
  1158. }
  1159. if nr {
  1160. needRestart = true
  1161. }
  1162. result.Adjusted++
  1163. }
  1164. return result, needRestart, nil
  1165. }
  1166. func (s *ClientService) DelDepleted(inboundSvc *InboundService) (int, bool, error) {
  1167. db := database.GetDB()
  1168. now := time.Now().UnixMilli()
  1169. depletedClause := "reset = 0 and ((total > 0 and up + down >= total) or (expiry_time > 0 and expiry_time <= ?))"
  1170. var rows []xray.ClientTraffic
  1171. if err := db.Where(depletedClause, now).Find(&rows).Error; err != nil {
  1172. return 0, false, err
  1173. }
  1174. if len(rows) == 0 {
  1175. return 0, false, nil
  1176. }
  1177. emails := make(map[string]struct{}, len(rows))
  1178. for _, r := range rows {
  1179. if r.Email != "" {
  1180. emails[r.Email] = struct{}{}
  1181. }
  1182. }
  1183. needRestart := false
  1184. deleted := 0
  1185. for email := range emails {
  1186. var rec model.ClientRecord
  1187. if err := db.Where("email = ?", email).First(&rec).Error; err != nil {
  1188. if errors.Is(err, gorm.ErrRecordNotFound) {
  1189. continue
  1190. }
  1191. return deleted, needRestart, err
  1192. }
  1193. nr, err := s.Delete(inboundSvc, rec.Id, false)
  1194. if err != nil {
  1195. return deleted, needRestart, err
  1196. }
  1197. if nr {
  1198. needRestart = true
  1199. }
  1200. deleted++
  1201. }
  1202. return deleted, needRestart, nil
  1203. }
  1204. func (s *ClientService) ResetAllClientTraffics(inboundSvc *InboundService, id int) error {
  1205. return submitTrafficWrite(func() error {
  1206. return s.resetAllClientTrafficsLocked(id)
  1207. })
  1208. }
  1209. func (s *ClientService) resetAllClientTrafficsLocked(id int) error {
  1210. db := database.GetDB()
  1211. now := time.Now().Unix() * 1000
  1212. if err := db.Transaction(func(tx *gorm.DB) error {
  1213. whereText := "inbound_id "
  1214. if id == -1 {
  1215. whereText += " > ?"
  1216. } else {
  1217. whereText += " = ?"
  1218. }
  1219. result := tx.Model(xray.ClientTraffic{}).
  1220. Where(whereText, id).
  1221. Updates(map[string]any{"enable": true, "up": 0, "down": 0})
  1222. if result.Error != nil {
  1223. return result.Error
  1224. }
  1225. inboundWhereText := "id "
  1226. if id == -1 {
  1227. inboundWhereText += " > ?"
  1228. } else {
  1229. inboundWhereText += " = ?"
  1230. }
  1231. result = tx.Model(model.Inbound{}).
  1232. Where(inboundWhereText, id).
  1233. Update("last_traffic_reset_time", now)
  1234. return result.Error
  1235. }); err != nil {
  1236. return err
  1237. }
  1238. return nil
  1239. }
  1240. func (s *ClientService) ResetAllTraffics() (bool, error) {
  1241. res := database.GetDB().Model(&xray.ClientTraffic{}).
  1242. Where("1 = 1").
  1243. Updates(map[string]any{"up": 0, "down": 0})
  1244. if res.Error != nil {
  1245. return false, res.Error
  1246. }
  1247. return res.RowsAffected > 0, nil
  1248. }
  1249. func (s *ClientService) Detach(inboundSvc *InboundService, id int, inboundIds []int) (bool, error) {
  1250. existing, err := s.GetByID(id)
  1251. if err != nil {
  1252. return false, err
  1253. }
  1254. currentIds, err := s.GetInboundIdsForRecord(id)
  1255. if err != nil {
  1256. return false, err
  1257. }
  1258. have := make(map[int]struct{}, len(currentIds))
  1259. for _, x := range currentIds {
  1260. have[x] = struct{}{}
  1261. }
  1262. needRestart := false
  1263. for _, ibId := range inboundIds {
  1264. if _, attached := have[ibId]; !attached {
  1265. continue
  1266. }
  1267. inbound, getErr := inboundSvc.GetInbound(ibId)
  1268. if getErr != nil {
  1269. return needRestart, getErr
  1270. }
  1271. key := clientKeyForProtocol(inbound.Protocol, existing)
  1272. if key == "" {
  1273. continue
  1274. }
  1275. nr, delErr := s.DelInboundClient(inboundSvc, ibId, key)
  1276. if delErr != nil {
  1277. return needRestart, delErr
  1278. }
  1279. if nr {
  1280. needRestart = true
  1281. }
  1282. }
  1283. return needRestart, nil
  1284. }
  1285. func (s *ClientService) checkEmailsExistForClients(inboundSvc *InboundService, clients []model.Client) (string, error) {
  1286. emailSubIDs, err := inboundSvc.getAllEmailSubIDs()
  1287. if err != nil {
  1288. return "", err
  1289. }
  1290. seen := make(map[string]string, len(clients))
  1291. for _, client := range clients {
  1292. if client.Email == "" {
  1293. continue
  1294. }
  1295. key := strings.ToLower(client.Email)
  1296. if prev, ok := seen[key]; ok {
  1297. if prev != client.SubID || client.SubID == "" {
  1298. return client.Email, nil
  1299. }
  1300. continue
  1301. }
  1302. seen[key] = client.SubID
  1303. if existingSub, ok := emailSubIDs[key]; ok {
  1304. if client.SubID == "" || existingSub == "" || existingSub != client.SubID {
  1305. return client.Email, nil
  1306. }
  1307. }
  1308. }
  1309. return "", nil
  1310. }
  1311. func (s *ClientService) AddInboundClient(inboundSvc *InboundService, data *model.Inbound) (bool, error) {
  1312. defer lockInbound(data.Id).Unlock()
  1313. clients, err := inboundSvc.GetClients(data)
  1314. if err != nil {
  1315. return false, err
  1316. }
  1317. var settings map[string]any
  1318. err = json.Unmarshal([]byte(data.Settings), &settings)
  1319. if err != nil {
  1320. return false, err
  1321. }
  1322. interfaceClients := settings["clients"].([]any)
  1323. nowTs := time.Now().Unix() * 1000
  1324. for i := range interfaceClients {
  1325. if cm, ok := interfaceClients[i].(map[string]any); ok {
  1326. if _, ok2 := cm["created_at"]; !ok2 {
  1327. cm["created_at"] = nowTs
  1328. }
  1329. cm["updated_at"] = nowTs
  1330. interfaceClients[i] = cm
  1331. }
  1332. }
  1333. existEmail, err := s.checkEmailsExistForClients(inboundSvc, clients)
  1334. if err != nil {
  1335. return false, err
  1336. }
  1337. if existEmail != "" {
  1338. return false, common.NewError("Duplicate email:", existEmail)
  1339. }
  1340. oldInbound, err := inboundSvc.GetInbound(data.Id)
  1341. if err != nil {
  1342. return false, err
  1343. }
  1344. for _, client := range clients {
  1345. if strings.TrimSpace(client.Email) == "" {
  1346. return false, common.NewError("client email is required")
  1347. }
  1348. switch oldInbound.Protocol {
  1349. case "trojan":
  1350. if client.Password == "" {
  1351. return false, common.NewError("empty client ID")
  1352. }
  1353. case "shadowsocks":
  1354. if client.Email == "" {
  1355. return false, common.NewError("empty client ID")
  1356. }
  1357. case "hysteria", "hysteria2":
  1358. if client.Auth == "" {
  1359. return false, common.NewError("empty client ID")
  1360. }
  1361. default:
  1362. if client.ID == "" {
  1363. return false, common.NewError("empty client ID")
  1364. }
  1365. }
  1366. }
  1367. var oldSettings map[string]any
  1368. err = json.Unmarshal([]byte(oldInbound.Settings), &oldSettings)
  1369. if err != nil {
  1370. return false, err
  1371. }
  1372. if oldInbound.Protocol == model.Shadowsocks {
  1373. applyShadowsocksClientMethod(interfaceClients, oldSettings)
  1374. }
  1375. oldClients := oldSettings["clients"].([]any)
  1376. oldClients = compactOrphans(database.GetDB(), oldClients)
  1377. oldClients = append(oldClients, interfaceClients...)
  1378. oldSettings["clients"] = oldClients
  1379. newSettings, err := json.MarshalIndent(oldSettings, "", " ")
  1380. if err != nil {
  1381. return false, err
  1382. }
  1383. oldInbound.Settings = string(newSettings)
  1384. db := database.GetDB()
  1385. tx := db.Begin()
  1386. defer func() {
  1387. if err != nil {
  1388. tx.Rollback()
  1389. } else {
  1390. tx.Commit()
  1391. }
  1392. }()
  1393. needRestart := false
  1394. rt, rterr := inboundSvc.runtimeFor(oldInbound)
  1395. if rterr != nil {
  1396. if oldInbound.NodeID != nil {
  1397. err = rterr
  1398. return false, err
  1399. }
  1400. needRestart = true
  1401. } else if oldInbound.NodeID == nil {
  1402. for _, client := range clients {
  1403. if len(client.Email) == 0 {
  1404. needRestart = true
  1405. continue
  1406. }
  1407. inboundSvc.AddClientStat(tx, data.Id, &client)
  1408. if !client.Enable {
  1409. continue
  1410. }
  1411. cipher := ""
  1412. if oldInbound.Protocol == "shadowsocks" {
  1413. cipher = oldSettings["method"].(string)
  1414. }
  1415. err1 := rt.AddUser(context.Background(), oldInbound, map[string]any{
  1416. "email": client.Email,
  1417. "id": client.ID,
  1418. "auth": client.Auth,
  1419. "security": client.Security,
  1420. "flow": client.Flow,
  1421. "password": client.Password,
  1422. "cipher": cipher,
  1423. })
  1424. if err1 == nil {
  1425. logger.Debug("Client added on", rt.Name(), ":", client.Email)
  1426. } else {
  1427. logger.Debug("Error in adding client on", rt.Name(), ":", err1)
  1428. needRestart = true
  1429. }
  1430. }
  1431. } else {
  1432. for _, client := range clients {
  1433. if len(client.Email) > 0 {
  1434. inboundSvc.AddClientStat(tx, data.Id, &client)
  1435. }
  1436. if err1 := rt.AddClient(context.Background(), oldInbound, client); err1 != nil {
  1437. err = err1
  1438. return false, err
  1439. }
  1440. }
  1441. }
  1442. if err = tx.Save(oldInbound).Error; err != nil {
  1443. return false, err
  1444. }
  1445. finalClients, gcErr := inboundSvc.GetClients(oldInbound)
  1446. if gcErr != nil {
  1447. err = gcErr
  1448. return false, err
  1449. }
  1450. if err = s.SyncInbound(tx, oldInbound.Id, finalClients); err != nil {
  1451. return false, err
  1452. }
  1453. return needRestart, nil
  1454. }
  1455. func (s *ClientService) UpdateInboundClient(inboundSvc *InboundService, data *model.Inbound, clientId string) (bool, error) {
  1456. defer lockInbound(data.Id).Unlock()
  1457. clients, err := inboundSvc.GetClients(data)
  1458. if err != nil {
  1459. return false, err
  1460. }
  1461. var settings map[string]any
  1462. err = json.Unmarshal([]byte(data.Settings), &settings)
  1463. if err != nil {
  1464. return false, err
  1465. }
  1466. interfaceClients := settings["clients"].([]any)
  1467. oldInbound, err := inboundSvc.GetInbound(data.Id)
  1468. if err != nil {
  1469. return false, err
  1470. }
  1471. oldClients, err := inboundSvc.GetClients(oldInbound)
  1472. if err != nil {
  1473. return false, err
  1474. }
  1475. oldEmail := ""
  1476. newClientId := ""
  1477. clientIndex := -1
  1478. for index, oldClient := range oldClients {
  1479. oldClientId := ""
  1480. switch oldInbound.Protocol {
  1481. case "trojan":
  1482. oldClientId = oldClient.Password
  1483. newClientId = clients[0].Password
  1484. case "shadowsocks":
  1485. oldClientId = oldClient.Email
  1486. newClientId = clients[0].Email
  1487. case "hysteria", "hysteria2":
  1488. oldClientId = oldClient.Auth
  1489. newClientId = clients[0].Auth
  1490. default:
  1491. oldClientId = oldClient.ID
  1492. newClientId = clients[0].ID
  1493. }
  1494. if clientId == oldClientId {
  1495. oldEmail = oldClient.Email
  1496. clientIndex = index
  1497. break
  1498. }
  1499. }
  1500. if clientIndex == -1 {
  1501. var rec model.ClientRecord
  1502. var lookupErr error
  1503. switch oldInbound.Protocol {
  1504. case "trojan":
  1505. lookupErr = database.GetDB().Where("password = ?", clientId).First(&rec).Error
  1506. case "shadowsocks":
  1507. lookupErr = database.GetDB().Where("email = ?", clientId).First(&rec).Error
  1508. case "hysteria", "hysteria2":
  1509. lookupErr = database.GetDB().Where("auth = ?", clientId).First(&rec).Error
  1510. default:
  1511. lookupErr = database.GetDB().Where("uuid = ?", clientId).First(&rec).Error
  1512. }
  1513. if lookupErr == nil && rec.Email != "" {
  1514. for index, oldClient := range oldClients {
  1515. if oldClient.Email == rec.Email {
  1516. oldEmail = oldClient.Email
  1517. clientIndex = index
  1518. break
  1519. }
  1520. }
  1521. }
  1522. }
  1523. if newClientId == "" || clientIndex == -1 {
  1524. return false, common.NewError("empty client ID")
  1525. }
  1526. if strings.TrimSpace(clients[0].Email) == "" {
  1527. return false, common.NewError("client email is required")
  1528. }
  1529. if clients[0].Email != oldEmail {
  1530. existEmail, err := s.checkEmailsExistForClients(inboundSvc, clients)
  1531. if err != nil {
  1532. return false, err
  1533. }
  1534. if existEmail != "" {
  1535. return false, common.NewError("Duplicate email:", existEmail)
  1536. }
  1537. }
  1538. var oldSettings map[string]any
  1539. err = json.Unmarshal([]byte(oldInbound.Settings), &oldSettings)
  1540. if err != nil {
  1541. return false, err
  1542. }
  1543. settingsClients := oldSettings["clients"].([]any)
  1544. var preservedCreated any
  1545. if clientIndex >= 0 && clientIndex < len(settingsClients) {
  1546. if oldMap, ok := settingsClients[clientIndex].(map[string]any); ok {
  1547. if v, ok2 := oldMap["created_at"]; ok2 {
  1548. preservedCreated = v
  1549. }
  1550. }
  1551. }
  1552. if len(interfaceClients) > 0 {
  1553. if newMap, ok := interfaceClients[0].(map[string]any); ok {
  1554. if preservedCreated == nil {
  1555. preservedCreated = time.Now().Unix() * 1000
  1556. }
  1557. newMap["created_at"] = preservedCreated
  1558. newMap["updated_at"] = time.Now().Unix() * 1000
  1559. interfaceClients[0] = newMap
  1560. }
  1561. }
  1562. if oldInbound.Protocol == model.Shadowsocks {
  1563. applyShadowsocksClientMethod(interfaceClients, oldSettings)
  1564. }
  1565. settingsClients[clientIndex] = interfaceClients[0]
  1566. oldSettings["clients"] = settingsClients
  1567. if oldInbound.Protocol == model.VLESS {
  1568. hasVisionFlow := false
  1569. for _, c := range settingsClients {
  1570. cm, ok := c.(map[string]any)
  1571. if !ok {
  1572. continue
  1573. }
  1574. if flow, _ := cm["flow"].(string); flow == "xtls-rprx-vision" {
  1575. hasVisionFlow = true
  1576. break
  1577. }
  1578. }
  1579. if !hasVisionFlow {
  1580. delete(oldSettings, "testseed")
  1581. }
  1582. }
  1583. newSettings, err := json.MarshalIndent(oldSettings, "", " ")
  1584. if err != nil {
  1585. return false, err
  1586. }
  1587. oldInbound.Settings = string(newSettings)
  1588. db := database.GetDB()
  1589. tx := db.Begin()
  1590. defer func() {
  1591. if err != nil {
  1592. tx.Rollback()
  1593. } else {
  1594. tx.Commit()
  1595. }
  1596. }()
  1597. if len(clients[0].Email) > 0 {
  1598. if len(oldEmail) > 0 {
  1599. emailUnchanged := strings.EqualFold(oldEmail, clients[0].Email)
  1600. targetExists := int64(0)
  1601. if !emailUnchanged {
  1602. if err = tx.Model(xray.ClientTraffic{}).Where("email = ?", clients[0].Email).Count(&targetExists).Error; err != nil {
  1603. return false, err
  1604. }
  1605. }
  1606. if emailUnchanged || targetExists == 0 {
  1607. err = inboundSvc.UpdateClientStat(tx, oldEmail, &clients[0])
  1608. if err != nil {
  1609. return false, err
  1610. }
  1611. err = inboundSvc.UpdateClientIPs(tx, oldEmail, clients[0].Email)
  1612. if err != nil {
  1613. return false, err
  1614. }
  1615. } else {
  1616. stillUsed, sErr := inboundSvc.emailUsedByOtherInbounds(oldEmail, data.Id)
  1617. if sErr != nil {
  1618. return false, sErr
  1619. }
  1620. if !stillUsed {
  1621. if err = inboundSvc.DelClientStat(tx, oldEmail); err != nil {
  1622. return false, err
  1623. }
  1624. if err = inboundSvc.DelClientIPs(tx, oldEmail); err != nil {
  1625. return false, err
  1626. }
  1627. }
  1628. if err = inboundSvc.UpdateClientStat(tx, clients[0].Email, &clients[0]); err != nil {
  1629. return false, err
  1630. }
  1631. }
  1632. } else {
  1633. inboundSvc.AddClientStat(tx, data.Id, &clients[0])
  1634. }
  1635. } else {
  1636. stillUsed, err := inboundSvc.emailUsedByOtherInbounds(oldEmail, data.Id)
  1637. if err != nil {
  1638. return false, err
  1639. }
  1640. if !stillUsed {
  1641. err = inboundSvc.DelClientStat(tx, oldEmail)
  1642. if err != nil {
  1643. return false, err
  1644. }
  1645. err = inboundSvc.DelClientIPs(tx, oldEmail)
  1646. if err != nil {
  1647. return false, err
  1648. }
  1649. }
  1650. }
  1651. needRestart := false
  1652. if len(oldEmail) > 0 {
  1653. rt, rterr := inboundSvc.runtimeFor(oldInbound)
  1654. if rterr != nil {
  1655. if oldInbound.NodeID != nil {
  1656. err = rterr
  1657. return false, err
  1658. }
  1659. needRestart = true
  1660. } else if oldInbound.NodeID == nil {
  1661. if oldClients[clientIndex].Enable {
  1662. err1 := rt.RemoveUser(context.Background(), oldInbound, oldEmail)
  1663. if err1 == nil {
  1664. logger.Debug("Old client deleted on", rt.Name(), ":", oldEmail)
  1665. } else if strings.Contains(err1.Error(), fmt.Sprintf("User %s not found.", oldEmail)) {
  1666. logger.Debug("User is already deleted. Nothing to do more...")
  1667. } else {
  1668. logger.Debug("Error in deleting client on", rt.Name(), ":", err1)
  1669. needRestart = true
  1670. }
  1671. }
  1672. if clients[0].Enable {
  1673. cipher := ""
  1674. if oldInbound.Protocol == "shadowsocks" {
  1675. cipher = oldSettings["method"].(string)
  1676. }
  1677. err1 := rt.AddUser(context.Background(), oldInbound, map[string]any{
  1678. "email": clients[0].Email,
  1679. "id": clients[0].ID,
  1680. "security": clients[0].Security,
  1681. "flow": clients[0].Flow,
  1682. "auth": clients[0].Auth,
  1683. "password": clients[0].Password,
  1684. "cipher": cipher,
  1685. })
  1686. if err1 == nil {
  1687. logger.Debug("Client edited on", rt.Name(), ":", clients[0].Email)
  1688. } else {
  1689. logger.Debug("Error in adding client on", rt.Name(), ":", err1)
  1690. needRestart = true
  1691. }
  1692. }
  1693. } else {
  1694. if err1 := rt.UpdateUser(context.Background(), oldInbound, oldEmail, clients[0]); err1 != nil {
  1695. err = err1
  1696. return false, err
  1697. }
  1698. }
  1699. } else {
  1700. logger.Debug("Client old email not found")
  1701. needRestart = true
  1702. }
  1703. if err = tx.Save(oldInbound).Error; err != nil {
  1704. return false, err
  1705. }
  1706. finalClients, gcErr := inboundSvc.GetClients(oldInbound)
  1707. if gcErr != nil {
  1708. err = gcErr
  1709. return false, err
  1710. }
  1711. if err = s.SyncInbound(tx, oldInbound.Id, finalClients); err != nil {
  1712. return false, err
  1713. }
  1714. return needRestart, nil
  1715. }
  1716. func (s *ClientService) DelInboundClient(inboundSvc *InboundService, inboundId int, clientId string) (bool, error) {
  1717. defer lockInbound(inboundId).Unlock()
  1718. oldInbound, err := inboundSvc.GetInbound(inboundId)
  1719. if err != nil {
  1720. logger.Error("Load Old Data Error")
  1721. return false, err
  1722. }
  1723. var settings map[string]any
  1724. err = json.Unmarshal([]byte(oldInbound.Settings), &settings)
  1725. if err != nil {
  1726. return false, err
  1727. }
  1728. email := ""
  1729. client_key := "id"
  1730. switch oldInbound.Protocol {
  1731. case "trojan":
  1732. client_key = "password"
  1733. case "shadowsocks":
  1734. client_key = "email"
  1735. case "hysteria", "hysteria2":
  1736. client_key = "auth"
  1737. }
  1738. interfaceClients := settings["clients"].([]any)
  1739. var newClients []any
  1740. needApiDel := false
  1741. clientFound := false
  1742. for _, client := range interfaceClients {
  1743. c := client.(map[string]any)
  1744. c_id := c[client_key].(string)
  1745. if c_id == clientId {
  1746. clientFound = true
  1747. email, _ = c["email"].(string)
  1748. needApiDel, _ = c["enable"].(bool)
  1749. } else {
  1750. newClients = append(newClients, client)
  1751. }
  1752. }
  1753. if !clientFound {
  1754. return false, common.NewError("Client Not Found In Inbound For ID:", clientId)
  1755. }
  1756. db := database.GetDB()
  1757. newClients = compactOrphans(db, newClients)
  1758. if newClients == nil {
  1759. newClients = []any{}
  1760. }
  1761. settings["clients"] = newClients
  1762. newSettings, err := json.MarshalIndent(settings, "", " ")
  1763. if err != nil {
  1764. return false, err
  1765. }
  1766. oldInbound.Settings = string(newSettings)
  1767. emailShared, err := inboundSvc.emailUsedByOtherInbounds(email, inboundId)
  1768. if err != nil {
  1769. return false, err
  1770. }
  1771. if !emailShared {
  1772. err = inboundSvc.DelClientIPs(db, email)
  1773. if err != nil {
  1774. logger.Error("Error in delete client IPs")
  1775. return false, err
  1776. }
  1777. }
  1778. needRestart := false
  1779. if len(email) > 0 {
  1780. var enables []bool
  1781. err = db.Model(xray.ClientTraffic{}).Where("email = ?", email).Limit(1).Pluck("enable", &enables).Error
  1782. if err != nil {
  1783. logger.Error("Get stats error")
  1784. return false, err
  1785. }
  1786. notDepleted := len(enables) > 0 && enables[0]
  1787. if !emailShared {
  1788. err = inboundSvc.DelClientStat(db, email)
  1789. if err != nil {
  1790. logger.Error("Delete stats Data Error")
  1791. return false, err
  1792. }
  1793. }
  1794. if needApiDel && notDepleted && oldInbound.NodeID == nil {
  1795. rt, rterr := inboundSvc.runtimeFor(oldInbound)
  1796. if rterr != nil {
  1797. needRestart = true
  1798. } else {
  1799. err1 := rt.RemoveUser(context.Background(), oldInbound, email)
  1800. if err1 == nil {
  1801. logger.Debug("Client deleted on", rt.Name(), ":", email)
  1802. needRestart = false
  1803. } else if strings.Contains(err1.Error(), fmt.Sprintf("User %s not found.", email)) {
  1804. logger.Debug("User is already deleted. Nothing to do more...")
  1805. } else {
  1806. logger.Debug("Error in deleting client on", rt.Name(), ":", err1)
  1807. needRestart = true
  1808. }
  1809. }
  1810. }
  1811. }
  1812. if oldInbound.NodeID != nil && len(email) > 0 {
  1813. rt, rterr := inboundSvc.runtimeFor(oldInbound)
  1814. if rterr != nil {
  1815. return false, rterr
  1816. }
  1817. if err1 := rt.DeleteUser(context.Background(), oldInbound, email); err1 != nil {
  1818. return false, err1
  1819. }
  1820. }
  1821. if err := db.Save(oldInbound).Error; err != nil {
  1822. return false, err
  1823. }
  1824. finalClients, gcErr := inboundSvc.GetClients(oldInbound)
  1825. if gcErr != nil {
  1826. return false, gcErr
  1827. }
  1828. if err := s.SyncInbound(db, inboundId, finalClients); err != nil {
  1829. return false, err
  1830. }
  1831. return needRestart, nil
  1832. }
  1833. func (s *ClientService) DelInboundClientByEmail(inboundSvc *InboundService, inboundId int, email string) (bool, error) {
  1834. defer lockInbound(inboundId).Unlock()
  1835. oldInbound, err := inboundSvc.GetInbound(inboundId)
  1836. if err != nil {
  1837. logger.Error("Load Old Data Error")
  1838. return false, err
  1839. }
  1840. var settings map[string]any
  1841. if err := json.Unmarshal([]byte(oldInbound.Settings), &settings); err != nil {
  1842. return false, err
  1843. }
  1844. interfaceClients, ok := settings["clients"].([]any)
  1845. if !ok {
  1846. return false, common.NewError("invalid clients format in inbound settings")
  1847. }
  1848. var newClients []any
  1849. needApiDel := false
  1850. found := false
  1851. for _, client := range interfaceClients {
  1852. c, ok := client.(map[string]any)
  1853. if !ok {
  1854. continue
  1855. }
  1856. if cEmail, ok := c["email"].(string); ok && cEmail == email {
  1857. found = true
  1858. needApiDel, _ = c["enable"].(bool)
  1859. } else {
  1860. newClients = append(newClients, client)
  1861. }
  1862. }
  1863. if !found {
  1864. return false, common.NewError(fmt.Sprintf("client with email %s not found", email))
  1865. }
  1866. db := database.GetDB()
  1867. newClients = compactOrphans(db, newClients)
  1868. if newClients == nil {
  1869. newClients = []any{}
  1870. }
  1871. settings["clients"] = newClients
  1872. newSettings, err := json.MarshalIndent(settings, "", " ")
  1873. if err != nil {
  1874. return false, err
  1875. }
  1876. oldInbound.Settings = string(newSettings)
  1877. emailShared, err := inboundSvc.emailUsedByOtherInbounds(email, inboundId)
  1878. if err != nil {
  1879. return false, err
  1880. }
  1881. if !emailShared {
  1882. if err := inboundSvc.DelClientIPs(db, email); err != nil {
  1883. logger.Error("Error in delete client IPs")
  1884. return false, err
  1885. }
  1886. }
  1887. needRestart := false
  1888. if len(email) > 0 && !emailShared {
  1889. traffic, err := inboundSvc.GetClientTrafficByEmail(email)
  1890. if err != nil {
  1891. return false, err
  1892. }
  1893. if traffic != nil {
  1894. if err := inboundSvc.DelClientStat(db, email); err != nil {
  1895. logger.Error("Delete stats Data Error")
  1896. return false, err
  1897. }
  1898. }
  1899. if needApiDel {
  1900. rt, rterr := inboundSvc.runtimeFor(oldInbound)
  1901. if rterr != nil {
  1902. if oldInbound.NodeID != nil {
  1903. return false, rterr
  1904. }
  1905. needRestart = true
  1906. } else if oldInbound.NodeID == nil {
  1907. if err1 := rt.RemoveUser(context.Background(), oldInbound, email); err1 == nil {
  1908. logger.Debug("Client deleted on", rt.Name(), ":", email)
  1909. needRestart = false
  1910. } else if strings.Contains(err1.Error(), fmt.Sprintf("User %s not found.", email)) {
  1911. logger.Debug("User is already deleted. Nothing to do more...")
  1912. } else {
  1913. logger.Debug("Error in deleting client on", rt.Name(), ":", err1)
  1914. needRestart = true
  1915. }
  1916. } else {
  1917. if err1 := rt.DeleteUser(context.Background(), oldInbound, email); err1 != nil {
  1918. return false, err1
  1919. }
  1920. }
  1921. }
  1922. }
  1923. if err := db.Save(oldInbound).Error; err != nil {
  1924. return false, err
  1925. }
  1926. finalClients, gcErr := inboundSvc.GetClients(oldInbound)
  1927. if gcErr != nil {
  1928. return false, gcErr
  1929. }
  1930. if err := s.SyncInbound(db, inboundId, finalClients); err != nil {
  1931. return false, err
  1932. }
  1933. return needRestart, nil
  1934. }
  1935. func (s *ClientService) SetClientTelegramUserID(inboundSvc *InboundService, trafficId int, tgId int64) (bool, error) {
  1936. traffic, inbound, err := inboundSvc.GetClientInboundByTrafficID(trafficId)
  1937. if err != nil {
  1938. return false, err
  1939. }
  1940. if inbound == nil {
  1941. return false, common.NewError("Inbound Not Found For Traffic ID:", trafficId)
  1942. }
  1943. clientEmail := traffic.Email
  1944. oldClients, err := inboundSvc.GetClients(inbound)
  1945. if err != nil {
  1946. return false, err
  1947. }
  1948. clientId := ""
  1949. for _, oldClient := range oldClients {
  1950. if oldClient.Email == clientEmail {
  1951. switch inbound.Protocol {
  1952. case "trojan":
  1953. clientId = oldClient.Password
  1954. case "shadowsocks":
  1955. clientId = oldClient.Email
  1956. default:
  1957. clientId = oldClient.ID
  1958. }
  1959. break
  1960. }
  1961. }
  1962. if len(clientId) == 0 {
  1963. return false, common.NewError("Client Not Found For Email:", clientEmail)
  1964. }
  1965. var settings map[string]any
  1966. err = json.Unmarshal([]byte(inbound.Settings), &settings)
  1967. if err != nil {
  1968. return false, err
  1969. }
  1970. clients := settings["clients"].([]any)
  1971. var newClients []any
  1972. for client_index := range clients {
  1973. c := clients[client_index].(map[string]any)
  1974. if c["email"] == clientEmail {
  1975. c["tgId"] = tgId
  1976. c["updated_at"] = time.Now().Unix() * 1000
  1977. newClients = append(newClients, any(c))
  1978. }
  1979. }
  1980. settings["clients"] = newClients
  1981. modifiedSettings, err := json.MarshalIndent(settings, "", " ")
  1982. if err != nil {
  1983. return false, err
  1984. }
  1985. inbound.Settings = string(modifiedSettings)
  1986. needRestart, err := s.UpdateInboundClient(inboundSvc, inbound, clientId)
  1987. return needRestart, err
  1988. }
  1989. func (s *ClientService) checkIsEnabledByEmail(inboundSvc *InboundService, clientEmail string) (bool, error) {
  1990. _, inbound, err := inboundSvc.GetClientInboundByEmail(clientEmail)
  1991. if err != nil {
  1992. return false, err
  1993. }
  1994. if inbound == nil {
  1995. return false, common.NewError("Inbound Not Found For Email:", clientEmail)
  1996. }
  1997. clients, err := inboundSvc.GetClients(inbound)
  1998. if err != nil {
  1999. return false, err
  2000. }
  2001. isEnable := false
  2002. for _, client := range clients {
  2003. if client.Email == clientEmail {
  2004. isEnable = client.Enable
  2005. break
  2006. }
  2007. }
  2008. return isEnable, err
  2009. }
  2010. func (s *ClientService) ToggleClientEnableByEmail(inboundSvc *InboundService, clientEmail string) (bool, bool, error) {
  2011. _, inbound, err := inboundSvc.GetClientInboundByEmail(clientEmail)
  2012. if err != nil {
  2013. return false, false, err
  2014. }
  2015. if inbound == nil {
  2016. return false, false, common.NewError("Inbound Not Found For Email:", clientEmail)
  2017. }
  2018. oldClients, err := inboundSvc.GetClients(inbound)
  2019. if err != nil {
  2020. return false, false, err
  2021. }
  2022. clientId := ""
  2023. clientOldEnabled := false
  2024. for _, oldClient := range oldClients {
  2025. if oldClient.Email == clientEmail {
  2026. switch inbound.Protocol {
  2027. case "trojan":
  2028. clientId = oldClient.Password
  2029. case "shadowsocks":
  2030. clientId = oldClient.Email
  2031. default:
  2032. clientId = oldClient.ID
  2033. }
  2034. clientOldEnabled = oldClient.Enable
  2035. break
  2036. }
  2037. }
  2038. if len(clientId) == 0 {
  2039. return false, false, common.NewError("Client Not Found For Email:", clientEmail)
  2040. }
  2041. var settings map[string]any
  2042. err = json.Unmarshal([]byte(inbound.Settings), &settings)
  2043. if err != nil {
  2044. return false, false, err
  2045. }
  2046. clients := settings["clients"].([]any)
  2047. var newClients []any
  2048. for client_index := range clients {
  2049. c := clients[client_index].(map[string]any)
  2050. if c["email"] == clientEmail {
  2051. c["enable"] = !clientOldEnabled
  2052. c["updated_at"] = time.Now().Unix() * 1000
  2053. newClients = append(newClients, any(c))
  2054. }
  2055. }
  2056. settings["clients"] = newClients
  2057. modifiedSettings, err := json.MarshalIndent(settings, "", " ")
  2058. if err != nil {
  2059. return false, false, err
  2060. }
  2061. inbound.Settings = string(modifiedSettings)
  2062. needRestart, err := s.UpdateInboundClient(inboundSvc, inbound, clientId)
  2063. if err != nil {
  2064. return false, needRestart, err
  2065. }
  2066. return !clientOldEnabled, needRestart, nil
  2067. }
  2068. func (s *ClientService) SetClientEnableByEmail(inboundSvc *InboundService, clientEmail string, enable bool) (bool, bool, error) {
  2069. current, err := s.checkIsEnabledByEmail(inboundSvc, clientEmail)
  2070. if err != nil {
  2071. return false, false, err
  2072. }
  2073. if current == enable {
  2074. return false, false, nil
  2075. }
  2076. newEnabled, needRestart, err := s.ToggleClientEnableByEmail(inboundSvc, clientEmail)
  2077. if err != nil {
  2078. return false, needRestart, err
  2079. }
  2080. return newEnabled == enable, needRestart, nil
  2081. }
  2082. func (s *ClientService) ResetClientIpLimitByEmail(inboundSvc *InboundService, clientEmail string, count int) (bool, error) {
  2083. _, inbound, err := inboundSvc.GetClientInboundByEmail(clientEmail)
  2084. if err != nil {
  2085. return false, err
  2086. }
  2087. if inbound == nil {
  2088. return false, common.NewError("Inbound Not Found For Email:", clientEmail)
  2089. }
  2090. oldClients, err := inboundSvc.GetClients(inbound)
  2091. if err != nil {
  2092. return false, err
  2093. }
  2094. clientId := ""
  2095. for _, oldClient := range oldClients {
  2096. if oldClient.Email == clientEmail {
  2097. switch inbound.Protocol {
  2098. case "trojan":
  2099. clientId = oldClient.Password
  2100. case "shadowsocks":
  2101. clientId = oldClient.Email
  2102. default:
  2103. clientId = oldClient.ID
  2104. }
  2105. break
  2106. }
  2107. }
  2108. if len(clientId) == 0 {
  2109. return false, common.NewError("Client Not Found For Email:", clientEmail)
  2110. }
  2111. var settings map[string]any
  2112. err = json.Unmarshal([]byte(inbound.Settings), &settings)
  2113. if err != nil {
  2114. return false, err
  2115. }
  2116. clients := settings["clients"].([]any)
  2117. var newClients []any
  2118. for client_index := range clients {
  2119. c := clients[client_index].(map[string]any)
  2120. if c["email"] == clientEmail {
  2121. c["limitIp"] = count
  2122. c["updated_at"] = time.Now().Unix() * 1000
  2123. newClients = append(newClients, any(c))
  2124. }
  2125. }
  2126. settings["clients"] = newClients
  2127. modifiedSettings, err := json.MarshalIndent(settings, "", " ")
  2128. if err != nil {
  2129. return false, err
  2130. }
  2131. inbound.Settings = string(modifiedSettings)
  2132. needRestart, err := s.UpdateInboundClient(inboundSvc, inbound, clientId)
  2133. return needRestart, err
  2134. }
  2135. func (s *ClientService) ResetClientExpiryTimeByEmail(inboundSvc *InboundService, clientEmail string, expiry_time int64) (bool, error) {
  2136. _, inbound, err := inboundSvc.GetClientInboundByEmail(clientEmail)
  2137. if err != nil {
  2138. return false, err
  2139. }
  2140. if inbound == nil {
  2141. return false, common.NewError("Inbound Not Found For Email:", clientEmail)
  2142. }
  2143. oldClients, err := inboundSvc.GetClients(inbound)
  2144. if err != nil {
  2145. return false, err
  2146. }
  2147. clientId := ""
  2148. for _, oldClient := range oldClients {
  2149. if oldClient.Email == clientEmail {
  2150. switch inbound.Protocol {
  2151. case "trojan":
  2152. clientId = oldClient.Password
  2153. case "shadowsocks":
  2154. clientId = oldClient.Email
  2155. default:
  2156. clientId = oldClient.ID
  2157. }
  2158. break
  2159. }
  2160. }
  2161. if len(clientId) == 0 {
  2162. return false, common.NewError("Client Not Found For Email:", clientEmail)
  2163. }
  2164. var settings map[string]any
  2165. err = json.Unmarshal([]byte(inbound.Settings), &settings)
  2166. if err != nil {
  2167. return false, err
  2168. }
  2169. clients := settings["clients"].([]any)
  2170. var newClients []any
  2171. for client_index := range clients {
  2172. c := clients[client_index].(map[string]any)
  2173. if c["email"] == clientEmail {
  2174. c["expiryTime"] = expiry_time
  2175. c["updated_at"] = time.Now().Unix() * 1000
  2176. newClients = append(newClients, any(c))
  2177. }
  2178. }
  2179. settings["clients"] = newClients
  2180. modifiedSettings, err := json.MarshalIndent(settings, "", " ")
  2181. if err != nil {
  2182. return false, err
  2183. }
  2184. inbound.Settings = string(modifiedSettings)
  2185. needRestart, err := s.UpdateInboundClient(inboundSvc, inbound, clientId)
  2186. return needRestart, err
  2187. }
  2188. func (s *ClientService) ResetClientTrafficLimitByEmail(inboundSvc *InboundService, clientEmail string, totalGB int) (bool, error) {
  2189. if totalGB < 0 {
  2190. return false, common.NewError("totalGB must be >= 0")
  2191. }
  2192. _, inbound, err := inboundSvc.GetClientInboundByEmail(clientEmail)
  2193. if err != nil {
  2194. return false, err
  2195. }
  2196. if inbound == nil {
  2197. return false, common.NewError("Inbound Not Found For Email:", clientEmail)
  2198. }
  2199. oldClients, err := inboundSvc.GetClients(inbound)
  2200. if err != nil {
  2201. return false, err
  2202. }
  2203. clientId := ""
  2204. for _, oldClient := range oldClients {
  2205. if oldClient.Email == clientEmail {
  2206. switch inbound.Protocol {
  2207. case "trojan":
  2208. clientId = oldClient.Password
  2209. case "shadowsocks":
  2210. clientId = oldClient.Email
  2211. default:
  2212. clientId = oldClient.ID
  2213. }
  2214. break
  2215. }
  2216. }
  2217. if len(clientId) == 0 {
  2218. return false, common.NewError("Client Not Found For Email:", clientEmail)
  2219. }
  2220. var settings map[string]any
  2221. err = json.Unmarshal([]byte(inbound.Settings), &settings)
  2222. if err != nil {
  2223. return false, err
  2224. }
  2225. clients := settings["clients"].([]any)
  2226. var newClients []any
  2227. for client_index := range clients {
  2228. c := clients[client_index].(map[string]any)
  2229. if c["email"] == clientEmail {
  2230. c["totalGB"] = totalGB * 1024 * 1024 * 1024
  2231. c["updated_at"] = time.Now().Unix() * 1000
  2232. newClients = append(newClients, any(c))
  2233. }
  2234. }
  2235. settings["clients"] = newClients
  2236. modifiedSettings, err := json.MarshalIndent(settings, "", " ")
  2237. if err != nil {
  2238. return false, err
  2239. }
  2240. inbound.Settings = string(modifiedSettings)
  2241. needRestart, err := s.UpdateInboundClient(inboundSvc, inbound, clientId)
  2242. return needRestart, err
  2243. }