1
0

client.go 63 KB

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