client.go 80 KB

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