client.go 62 KB

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