client.go 49 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959
  1. package service
  2. import (
  3. "context"
  4. "encoding/base64"
  5. "encoding/json"
  6. "errors"
  7. "fmt"
  8. "strings"
  9. "sync"
  10. "time"
  11. "github.com/google/uuid"
  12. "github.com/mhsanaei/3x-ui/v3/database"
  13. "github.com/mhsanaei/3x-ui/v3/database/model"
  14. "github.com/mhsanaei/3x-ui/v3/logger"
  15. "github.com/mhsanaei/3x-ui/v3/util/common"
  16. "github.com/mhsanaei/3x-ui/v3/util/random"
  17. "github.com/mhsanaei/3x-ui/v3/xray"
  18. "gorm.io/gorm"
  19. )
  20. type ClientWithAttachments struct {
  21. model.ClientRecord
  22. InboundIds []int `json:"inboundIds"`
  23. Traffic *xray.ClientTraffic `json:"traffic,omitempty"`
  24. }
  25. // MarshalJSON is required because model.ClientRecord defines its own
  26. // MarshalJSON. Go promotes the embedded method to the outer struct, so without
  27. // this the encoder would call ClientRecord.MarshalJSON for the whole value and
  28. // silently drop InboundIds and Traffic from the API response.
  29. func (c ClientWithAttachments) MarshalJSON() ([]byte, error) {
  30. rec, err := json.Marshal(c.ClientRecord)
  31. if err != nil {
  32. return nil, err
  33. }
  34. extras := struct {
  35. InboundIds []int `json:"inboundIds"`
  36. Traffic *xray.ClientTraffic `json:"traffic,omitempty"`
  37. }{InboundIds: c.InboundIds, Traffic: c.Traffic}
  38. extra, err := json.Marshal(extras)
  39. if err != nil {
  40. return nil, err
  41. }
  42. if len(rec) < 2 || rec[len(rec)-1] != '}' || len(extra) <= 2 {
  43. return rec, nil
  44. }
  45. out := make([]byte, 0, len(rec)+len(extra))
  46. out = append(out, rec[:len(rec)-1]...)
  47. if len(rec) > 2 {
  48. out = append(out, ',')
  49. }
  50. out = append(out, extra[1:]...)
  51. return out, nil
  52. }
  53. func clientKeyForProtocol(p model.Protocol, rec *model.ClientRecord) string {
  54. if rec == nil {
  55. return ""
  56. }
  57. switch p {
  58. case model.Trojan:
  59. return rec.Password
  60. case model.Shadowsocks:
  61. return rec.Email
  62. case model.Hysteria, model.Hysteria2:
  63. return rec.Auth
  64. default:
  65. return rec.UUID
  66. }
  67. }
  68. type ClientService struct{}
  69. // Short-lived tombstone of just-deleted client emails so that a node snapshot
  70. // arriving between delete and node-side processing doesn't resurrect them.
  71. var (
  72. recentlyDeletedMu sync.Mutex
  73. recentlyDeleted = map[string]time.Time{}
  74. )
  75. const deleteTombstoneTTL = 90 * time.Second
  76. var (
  77. inboundMutationLocksMu sync.Mutex
  78. inboundMutationLocks = map[int]*sync.Mutex{}
  79. )
  80. func lockInbound(inboundId int) *sync.Mutex {
  81. inboundMutationLocksMu.Lock()
  82. defer inboundMutationLocksMu.Unlock()
  83. m, ok := inboundMutationLocks[inboundId]
  84. if !ok {
  85. m = &sync.Mutex{}
  86. inboundMutationLocks[inboundId] = m
  87. }
  88. m.Lock()
  89. return m
  90. }
  91. func compactOrphans(db *gorm.DB, clients []any) []any {
  92. if len(clients) == 0 {
  93. return clients
  94. }
  95. emails := make([]string, 0, len(clients))
  96. for _, c := range clients {
  97. cm, ok := c.(map[string]any)
  98. if !ok {
  99. continue
  100. }
  101. if e, _ := cm["email"].(string); e != "" {
  102. emails = append(emails, e)
  103. }
  104. }
  105. if len(emails) == 0 {
  106. return clients
  107. }
  108. var existingEmails []string
  109. if err := db.Model(&model.ClientRecord{}).Where("email IN ?", emails).Pluck("email", &existingEmails).Error; err != nil {
  110. logger.Warning("compactOrphans pluck:", err)
  111. return clients
  112. }
  113. if len(existingEmails) == len(emails) {
  114. return clients
  115. }
  116. existing := make(map[string]struct{}, len(existingEmails))
  117. for _, e := range existingEmails {
  118. existing[e] = struct{}{}
  119. }
  120. out := make([]any, 0, len(existingEmails))
  121. for _, c := range clients {
  122. cm, ok := c.(map[string]any)
  123. if !ok {
  124. out = append(out, c)
  125. continue
  126. }
  127. e, _ := cm["email"].(string)
  128. if e == "" {
  129. out = append(out, c)
  130. continue
  131. }
  132. if _, ok := existing[e]; ok {
  133. out = append(out, c)
  134. }
  135. }
  136. return out
  137. }
  138. func tombstoneClientEmail(email string) {
  139. if email == "" {
  140. return
  141. }
  142. recentlyDeletedMu.Lock()
  143. defer recentlyDeletedMu.Unlock()
  144. recentlyDeleted[email] = time.Now()
  145. cutoff := time.Now().Add(-deleteTombstoneTTL)
  146. for e, ts := range recentlyDeleted {
  147. if ts.Before(cutoff) {
  148. delete(recentlyDeleted, e)
  149. }
  150. }
  151. }
  152. func isClientEmailTombstoned(email string) bool {
  153. if email == "" {
  154. return false
  155. }
  156. recentlyDeletedMu.Lock()
  157. defer recentlyDeletedMu.Unlock()
  158. ts, ok := recentlyDeleted[email]
  159. if !ok {
  160. return false
  161. }
  162. if time.Since(ts) > deleteTombstoneTTL {
  163. delete(recentlyDeleted, email)
  164. return false
  165. }
  166. return true
  167. }
  168. func (s *ClientService) SyncInbound(tx *gorm.DB, inboundId int, clients []model.Client) error {
  169. if tx == nil {
  170. tx = database.GetDB()
  171. }
  172. if err := tx.Where("inbound_id = ?", inboundId).Delete(&model.ClientInbound{}).Error; err != nil {
  173. return err
  174. }
  175. for i := range clients {
  176. c := clients[i]
  177. email := strings.TrimSpace(c.Email)
  178. if email == "" {
  179. continue
  180. }
  181. incoming := c.ToRecord()
  182. row := &model.ClientRecord{}
  183. err := tx.Where("email = ?", email).First(row).Error
  184. if err != nil && !errors.Is(err, gorm.ErrRecordNotFound) {
  185. return err
  186. }
  187. if errors.Is(err, gorm.ErrRecordNotFound) {
  188. if isClientEmailTombstoned(email) {
  189. continue
  190. }
  191. if err := tx.Create(incoming).Error; err != nil {
  192. return err
  193. }
  194. row = incoming
  195. } else {
  196. row.UUID = incoming.UUID
  197. row.Password = incoming.Password
  198. row.Auth = incoming.Auth
  199. row.Flow = incoming.Flow
  200. row.Security = incoming.Security
  201. row.Reverse = incoming.Reverse
  202. row.SubID = incoming.SubID
  203. row.LimitIP = incoming.LimitIP
  204. row.TotalGB = incoming.TotalGB
  205. row.ExpiryTime = incoming.ExpiryTime
  206. row.Enable = incoming.Enable
  207. row.TgID = incoming.TgID
  208. row.Comment = incoming.Comment
  209. row.Reset = incoming.Reset
  210. if incoming.CreatedAt > 0 && (row.CreatedAt == 0 || incoming.CreatedAt < row.CreatedAt) {
  211. row.CreatedAt = incoming.CreatedAt
  212. }
  213. if incoming.UpdatedAt > row.UpdatedAt {
  214. row.UpdatedAt = incoming.UpdatedAt
  215. }
  216. if err := tx.Save(row).Error; err != nil {
  217. return err
  218. }
  219. }
  220. link := model.ClientInbound{
  221. ClientId: row.Id,
  222. InboundId: inboundId,
  223. FlowOverride: c.Flow,
  224. }
  225. if err := tx.Create(&link).Error; err != nil {
  226. return err
  227. }
  228. }
  229. return nil
  230. }
  231. func (s *ClientService) DetachInbound(tx *gorm.DB, inboundId int) error {
  232. if tx == nil {
  233. tx = database.GetDB()
  234. }
  235. return tx.Where("inbound_id = ?", inboundId).Delete(&model.ClientInbound{}).Error
  236. }
  237. func (s *ClientService) ListForInbound(tx *gorm.DB, inboundId int) ([]model.Client, error) {
  238. if tx == nil {
  239. tx = database.GetDB()
  240. }
  241. type joinedRow struct {
  242. model.ClientRecord
  243. FlowOverride string
  244. }
  245. var rows []joinedRow
  246. err := tx.Table("clients").
  247. Select("clients.*, client_inbounds.flow_override AS flow_override").
  248. Joins("JOIN client_inbounds ON client_inbounds.client_id = clients.id").
  249. Where("client_inbounds.inbound_id = ?", inboundId).
  250. Order("clients.id ASC").
  251. Find(&rows).Error
  252. if err != nil {
  253. return nil, err
  254. }
  255. out := make([]model.Client, 0, len(rows))
  256. for i := range rows {
  257. c := rows[i].ToClient()
  258. if rows[i].FlowOverride != "" {
  259. c.Flow = rows[i].FlowOverride
  260. }
  261. out = append(out, *c)
  262. }
  263. return out, nil
  264. }
  265. func (s *ClientService) GetRecordByEmail(tx *gorm.DB, email string) (*model.ClientRecord, error) {
  266. if tx == nil {
  267. tx = database.GetDB()
  268. }
  269. row := &model.ClientRecord{}
  270. err := tx.Where("email = ?", email).First(row).Error
  271. if err != nil {
  272. return nil, err
  273. }
  274. return row, nil
  275. }
  276. func (s *ClientService) GetInboundIdsForEmail(tx *gorm.DB, email string) ([]int, error) {
  277. if tx == nil {
  278. tx = database.GetDB()
  279. }
  280. var ids []int
  281. err := tx.Table("client_inbounds").
  282. Select("client_inbounds.inbound_id").
  283. Joins("JOIN clients ON clients.id = client_inbounds.client_id").
  284. Where("clients.email = ?", email).
  285. Scan(&ids).Error
  286. if err != nil {
  287. return nil, err
  288. }
  289. return ids, nil
  290. }
  291. func (s *ClientService) GetByID(id int) (*model.ClientRecord, error) {
  292. row := &model.ClientRecord{}
  293. if err := database.GetDB().Where("id = ?", id).First(row).Error; err != nil {
  294. return nil, err
  295. }
  296. return row, nil
  297. }
  298. func (s *ClientService) GetInboundIdsForRecord(id int) ([]int, error) {
  299. var ids []int
  300. err := database.GetDB().Table("client_inbounds").
  301. Where("client_id = ?", id).
  302. Order("inbound_id ASC").
  303. Pluck("inbound_id", &ids).Error
  304. if err != nil {
  305. return nil, err
  306. }
  307. return ids, nil
  308. }
  309. func (s *ClientService) List() ([]ClientWithAttachments, error) {
  310. db := database.GetDB()
  311. var rows []model.ClientRecord
  312. if err := db.Order("id ASC").Find(&rows).Error; err != nil {
  313. return nil, err
  314. }
  315. if len(rows) == 0 {
  316. return []ClientWithAttachments{}, nil
  317. }
  318. clientIds := make([]int, 0, len(rows))
  319. emails := make([]string, 0, len(rows))
  320. for i := range rows {
  321. clientIds = append(clientIds, rows[i].Id)
  322. if rows[i].Email != "" {
  323. emails = append(emails, rows[i].Email)
  324. }
  325. }
  326. var links []model.ClientInbound
  327. if err := db.Where("client_id IN ?", clientIds).Find(&links).Error; err != nil {
  328. return nil, err
  329. }
  330. attachments := make(map[int][]int, len(rows))
  331. for _, l := range links {
  332. attachments[l.ClientId] = append(attachments[l.ClientId], l.InboundId)
  333. }
  334. trafficByEmail := make(map[string]*xray.ClientTraffic, len(emails))
  335. if len(emails) > 0 {
  336. var stats []xray.ClientTraffic
  337. if err := db.Where("email IN ?", emails).Find(&stats).Error; err != nil {
  338. return nil, err
  339. }
  340. for i := range stats {
  341. trafficByEmail[stats[i].Email] = &stats[i]
  342. }
  343. }
  344. out := make([]ClientWithAttachments, 0, len(rows))
  345. for i := range rows {
  346. out = append(out, ClientWithAttachments{
  347. ClientRecord: rows[i],
  348. InboundIds: attachments[rows[i].Id],
  349. Traffic: trafficByEmail[rows[i].Email],
  350. })
  351. }
  352. return out, nil
  353. }
  354. type ClientCreatePayload struct {
  355. Client model.Client `json:"client"`
  356. InboundIds []int `json:"inboundIds"`
  357. }
  358. func (s *ClientService) Create(inboundSvc *InboundService, payload *ClientCreatePayload) (bool, error) {
  359. if payload == nil {
  360. return false, common.NewError("empty payload")
  361. }
  362. client := payload.Client
  363. if strings.TrimSpace(client.Email) == "" {
  364. return false, common.NewError("client email is required")
  365. }
  366. if len(payload.InboundIds) == 0 {
  367. return false, common.NewError("at least one inbound is required")
  368. }
  369. if client.SubID == "" {
  370. client.SubID = uuid.NewString()
  371. }
  372. if !client.Enable {
  373. client.Enable = true
  374. }
  375. now := time.Now().UnixMilli()
  376. if client.CreatedAt == 0 {
  377. client.CreatedAt = now
  378. }
  379. client.UpdatedAt = now
  380. existing := &model.ClientRecord{}
  381. err := database.GetDB().Where("email = ?", client.Email).First(existing).Error
  382. if err != nil && !errors.Is(err, gorm.ErrRecordNotFound) {
  383. return false, err
  384. }
  385. emailTaken := !errors.Is(err, gorm.ErrRecordNotFound)
  386. if emailTaken {
  387. if existing.SubID == "" || existing.SubID != client.SubID {
  388. return false, common.NewError("email already in use:", client.Email)
  389. }
  390. }
  391. needRestart := false
  392. for _, ibId := range payload.InboundIds {
  393. inbound, getErr := inboundSvc.GetInbound(ibId)
  394. if getErr != nil {
  395. return needRestart, getErr
  396. }
  397. if err := s.fillProtocolDefaults(&client, inbound); err != nil {
  398. return needRestart, err
  399. }
  400. settingsPayload, mErr := json.Marshal(map[string][]model.Client{"clients": {client}})
  401. if mErr != nil {
  402. return needRestart, mErr
  403. }
  404. nr, addErr := s.AddInboundClient(inboundSvc, &model.Inbound{
  405. Id: ibId,
  406. Settings: string(settingsPayload),
  407. })
  408. if addErr != nil {
  409. return needRestart, addErr
  410. }
  411. if nr {
  412. needRestart = true
  413. }
  414. }
  415. return needRestart, nil
  416. }
  417. func (s *ClientService) fillProtocolDefaults(c *model.Client, ib *model.Inbound) error {
  418. switch ib.Protocol {
  419. case model.VMESS, model.VLESS:
  420. if c.ID == "" {
  421. c.ID = uuid.NewString()
  422. }
  423. case model.Trojan:
  424. if c.Password == "" {
  425. c.Password = strings.ReplaceAll(uuid.NewString(), "-", "")
  426. }
  427. case model.Shadowsocks:
  428. method := shadowsocksMethodFromSettings(ib.Settings)
  429. if c.Password == "" || !validShadowsocksClientKey(method, c.Password) {
  430. c.Password = randomShadowsocksClientKey(method)
  431. }
  432. case model.Hysteria, model.Hysteria2:
  433. if c.Auth == "" {
  434. c.Auth = strings.ReplaceAll(uuid.NewString(), "-", "")
  435. }
  436. }
  437. return nil
  438. }
  439. // shadowsocksMethodFromSettings pulls the "method" field out of the inbound's
  440. // settings JSON. Returns "" when the field is missing or settings is invalid.
  441. func shadowsocksMethodFromSettings(settings string) string {
  442. if settings == "" {
  443. return ""
  444. }
  445. var m map[string]any
  446. if err := json.Unmarshal([]byte(settings), &m); err != nil {
  447. return ""
  448. }
  449. method, _ := m["method"].(string)
  450. return method
  451. }
  452. // randomShadowsocksClientKey returns a per-client key sized to the cipher.
  453. // The 2022-blake3 ciphers require a base64-encoded key of an exact byte
  454. // length (16 bytes for aes-128-gcm, 32 bytes for aes-256-gcm and
  455. // chacha20-poly1305) — anything else fails with "bad key" on xray start.
  456. // Older ciphers accept arbitrary passwords, so we keep the uuid-style.
  457. func randomShadowsocksClientKey(method string) string {
  458. if n := shadowsocksKeyBytes(method); n > 0 {
  459. return random.Base64Bytes(n)
  460. }
  461. return strings.ReplaceAll(uuid.NewString(), "-", "")
  462. }
  463. // validShadowsocksClientKey reports whether key is acceptable for the cipher.
  464. // For 2022-blake3 it must decode to the exact byte length the cipher needs;
  465. // any other method accepts any non-empty string.
  466. func validShadowsocksClientKey(method, key string) bool {
  467. n := shadowsocksKeyBytes(method)
  468. if n == 0 {
  469. return key != ""
  470. }
  471. decoded, err := base64.StdEncoding.DecodeString(key)
  472. if err != nil {
  473. return false
  474. }
  475. return len(decoded) == n
  476. }
  477. func shadowsocksKeyBytes(method string) int {
  478. switch method {
  479. case "2022-blake3-aes-128-gcm":
  480. return 16
  481. case "2022-blake3-aes-256-gcm", "2022-blake3-chacha20-poly1305":
  482. return 32
  483. }
  484. return 0
  485. }
  486. // applyShadowsocksClientMethod ensures each client entry carries a "method"
  487. // field for legacy shadowsocks ciphers. xray's multi-user shadowsocks code
  488. // requires a per-client method; an empty/missing field fails with
  489. // "unsupported cipher method:". 2022-blake3 ciphers use the top-level
  490. // method only, so the per-client field must stay absent.
  491. func applyShadowsocksClientMethod(clients []any, settings map[string]any) {
  492. method, _ := settings["method"].(string)
  493. if method == "" || strings.HasPrefix(method, "2022-blake3-") {
  494. return
  495. }
  496. for i := range clients {
  497. cm, ok := clients[i].(map[string]any)
  498. if !ok {
  499. continue
  500. }
  501. if existing, _ := cm["method"].(string); existing != "" {
  502. continue
  503. }
  504. cm["method"] = method
  505. clients[i] = cm
  506. }
  507. }
  508. func (s *ClientService) Update(inboundSvc *InboundService, id int, updated model.Client) (bool, error) {
  509. existing, err := s.GetByID(id)
  510. if err != nil {
  511. return false, err
  512. }
  513. inboundIds, err := s.GetInboundIdsForRecord(id)
  514. if err != nil {
  515. return false, err
  516. }
  517. if strings.TrimSpace(updated.Email) == "" {
  518. return false, common.NewError("client email is required")
  519. }
  520. if updated.SubID == "" {
  521. updated.SubID = existing.SubID
  522. }
  523. if updated.SubID == "" {
  524. updated.SubID = uuid.NewString()
  525. }
  526. updated.UpdatedAt = time.Now().UnixMilli()
  527. if updated.CreatedAt == 0 {
  528. updated.CreatedAt = existing.CreatedAt
  529. }
  530. needRestart := false
  531. for _, ibId := range inboundIds {
  532. inbound, getErr := inboundSvc.GetInbound(ibId)
  533. if getErr != nil {
  534. return needRestart, getErr
  535. }
  536. oldKey := clientKeyForProtocol(inbound.Protocol, existing)
  537. if oldKey == "" {
  538. continue
  539. }
  540. if err := s.fillProtocolDefaults(&updated, inbound); err != nil {
  541. return needRestart, err
  542. }
  543. settingsPayload, mErr := json.Marshal(map[string][]model.Client{"clients": {updated}})
  544. if mErr != nil {
  545. return needRestart, mErr
  546. }
  547. nr, upErr := s.UpdateInboundClient(inboundSvc, &model.Inbound{
  548. Id: ibId,
  549. Settings: string(settingsPayload),
  550. }, oldKey)
  551. if upErr != nil {
  552. return needRestart, upErr
  553. }
  554. if nr {
  555. needRestart = true
  556. }
  557. }
  558. return needRestart, nil
  559. }
  560. func (s *ClientService) Delete(inboundSvc *InboundService, id int, keepTraffic bool) (bool, error) {
  561. existing, err := s.GetByID(id)
  562. if err != nil {
  563. return false, err
  564. }
  565. tombstoneClientEmail(existing.Email)
  566. inboundIds, err := s.GetInboundIdsForRecord(id)
  567. if err != nil {
  568. return false, err
  569. }
  570. needRestart := false
  571. for _, ibId := range inboundIds {
  572. inbound, getErr := inboundSvc.GetInbound(ibId)
  573. if getErr != nil {
  574. return needRestart, getErr
  575. }
  576. key := clientKeyForProtocol(inbound.Protocol, existing)
  577. if key == "" {
  578. continue
  579. }
  580. nr, delErr := s.DelInboundClient(inboundSvc, ibId, key)
  581. if delErr != nil {
  582. return needRestart, delErr
  583. }
  584. if nr {
  585. needRestart = true
  586. }
  587. }
  588. db := database.GetDB()
  589. if err := db.Where("client_id = ?", id).Delete(&model.ClientInbound{}).Error; err != nil {
  590. return needRestart, err
  591. }
  592. if !keepTraffic && existing.Email != "" {
  593. if err := db.Where("email = ?", existing.Email).Delete(&xray.ClientTraffic{}).Error; err != nil {
  594. return needRestart, err
  595. }
  596. if err := db.Where("client_email = ?", existing.Email).Delete(&model.InboundClientIps{}).Error; err != nil {
  597. return needRestart, err
  598. }
  599. }
  600. if err := db.Delete(&model.ClientRecord{}, id).Error; err != nil {
  601. return needRestart, err
  602. }
  603. return needRestart, nil
  604. }
  605. func (s *ClientService) Attach(inboundSvc *InboundService, id int, inboundIds []int) (bool, error) {
  606. existing, err := s.GetByID(id)
  607. if err != nil {
  608. return false, err
  609. }
  610. currentIds, err := s.GetInboundIdsForRecord(id)
  611. if err != nil {
  612. return false, err
  613. }
  614. have := make(map[int]struct{}, len(currentIds))
  615. for _, x := range currentIds {
  616. have[x] = struct{}{}
  617. }
  618. clientWire := existing.ToClient()
  619. clientWire.UpdatedAt = time.Now().UnixMilli()
  620. needRestart := false
  621. for _, ibId := range inboundIds {
  622. if _, attached := have[ibId]; attached {
  623. continue
  624. }
  625. inbound, getErr := inboundSvc.GetInbound(ibId)
  626. if getErr != nil {
  627. return needRestart, getErr
  628. }
  629. copyClient := *clientWire
  630. if err := s.fillProtocolDefaults(&copyClient, inbound); err != nil {
  631. return needRestart, err
  632. }
  633. settingsPayload, mErr := json.Marshal(map[string][]model.Client{"clients": {copyClient}})
  634. if mErr != nil {
  635. return needRestart, mErr
  636. }
  637. nr, addErr := s.AddInboundClient(inboundSvc, &model.Inbound{
  638. Id: ibId,
  639. Settings: string(settingsPayload),
  640. })
  641. if addErr != nil {
  642. return needRestart, addErr
  643. }
  644. if nr {
  645. needRestart = true
  646. }
  647. }
  648. return needRestart, nil
  649. }
  650. func (s *ClientService) CreateOne(inboundSvc *InboundService, inboundId int, client model.Client) (bool, error) {
  651. return s.Create(inboundSvc, &ClientCreatePayload{
  652. Client: client,
  653. InboundIds: []int{inboundId},
  654. })
  655. }
  656. func (s *ClientService) DetachByEmail(inboundSvc *InboundService, inboundId int, email string) (bool, error) {
  657. if email == "" {
  658. return false, common.NewError("client email is required")
  659. }
  660. rec, err := s.GetRecordByEmail(nil, email)
  661. if err != nil {
  662. return false, err
  663. }
  664. return s.Detach(inboundSvc, rec.Id, []int{inboundId})
  665. }
  666. func (s *ClientService) AttachByEmail(inboundSvc *InboundService, email string, inboundIds []int) (bool, error) {
  667. if email == "" {
  668. return false, common.NewError("client email is required")
  669. }
  670. rec, err := s.GetRecordByEmail(nil, email)
  671. if err != nil {
  672. return false, err
  673. }
  674. return s.Attach(inboundSvc, rec.Id, inboundIds)
  675. }
  676. func (s *ClientService) DetachByEmailMany(inboundSvc *InboundService, email string, inboundIds []int) (bool, error) {
  677. if email == "" {
  678. return false, common.NewError("client email is required")
  679. }
  680. rec, err := s.GetRecordByEmail(nil, email)
  681. if err != nil {
  682. return false, err
  683. }
  684. return s.Detach(inboundSvc, rec.Id, inboundIds)
  685. }
  686. func (s *ClientService) DeleteByEmail(inboundSvc *InboundService, email string, keepTraffic bool) (bool, error) {
  687. if email == "" {
  688. return false, common.NewError("client email is required")
  689. }
  690. rec, err := s.GetRecordByEmail(nil, email)
  691. if err != nil {
  692. return false, err
  693. }
  694. return s.Delete(inboundSvc, rec.Id, keepTraffic)
  695. }
  696. func (s *ClientService) UpdateByEmail(inboundSvc *InboundService, email string, updated model.Client) (bool, error) {
  697. if email == "" {
  698. return false, common.NewError("client email is required")
  699. }
  700. rec, err := s.GetRecordByEmail(nil, email)
  701. if err != nil {
  702. return false, err
  703. }
  704. return s.Update(inboundSvc, rec.Id, updated)
  705. }
  706. func (s *ClientService) ResetTrafficByEmail(inboundSvc *InboundService, email string) (bool, error) {
  707. if email == "" {
  708. return false, common.NewError("client email is required")
  709. }
  710. rec, err := s.GetRecordByEmail(nil, email)
  711. if err != nil {
  712. return false, err
  713. }
  714. inboundIds, err := s.GetInboundIdsForRecord(rec.Id)
  715. if err != nil {
  716. return false, err
  717. }
  718. if len(inboundIds) == 0 {
  719. if rErr := inboundSvc.ResetClientTrafficByEmail(email); rErr != nil {
  720. return false, rErr
  721. }
  722. return false, nil
  723. }
  724. needRestart := false
  725. for _, ibId := range inboundIds {
  726. nr, rErr := inboundSvc.ResetClientTraffic(ibId, email)
  727. if rErr != nil {
  728. return needRestart, rErr
  729. }
  730. if nr {
  731. needRestart = true
  732. }
  733. }
  734. return needRestart, nil
  735. }
  736. func (s *ClientService) DelDepleted(inboundSvc *InboundService) (int, bool, error) {
  737. db := database.GetDB()
  738. now := time.Now().UnixMilli()
  739. depletedClause := "reset = 0 and ((total > 0 and up + down >= total) or (expiry_time > 0 and expiry_time <= ?))"
  740. var rows []xray.ClientTraffic
  741. if err := db.Where(depletedClause, now).Find(&rows).Error; err != nil {
  742. return 0, false, err
  743. }
  744. if len(rows) == 0 {
  745. return 0, false, nil
  746. }
  747. emails := make(map[string]struct{}, len(rows))
  748. for _, r := range rows {
  749. if r.Email != "" {
  750. emails[r.Email] = struct{}{}
  751. }
  752. }
  753. needRestart := false
  754. deleted := 0
  755. for email := range emails {
  756. var rec model.ClientRecord
  757. if err := db.Where("email = ?", email).First(&rec).Error; err != nil {
  758. if errors.Is(err, gorm.ErrRecordNotFound) {
  759. continue
  760. }
  761. return deleted, needRestart, err
  762. }
  763. nr, err := s.Delete(inboundSvc, rec.Id, false)
  764. if err != nil {
  765. return deleted, needRestart, err
  766. }
  767. if nr {
  768. needRestart = true
  769. }
  770. deleted++
  771. }
  772. return deleted, needRestart, nil
  773. }
  774. func (s *ClientService) ResetAllClientTraffics(inboundSvc *InboundService, id int) error {
  775. return submitTrafficWrite(func() error {
  776. return s.resetAllClientTrafficsLocked(id)
  777. })
  778. }
  779. func (s *ClientService) resetAllClientTrafficsLocked(id int) error {
  780. db := database.GetDB()
  781. now := time.Now().Unix() * 1000
  782. if err := db.Transaction(func(tx *gorm.DB) error {
  783. whereText := "inbound_id "
  784. if id == -1 {
  785. whereText += " > ?"
  786. } else {
  787. whereText += " = ?"
  788. }
  789. result := tx.Model(xray.ClientTraffic{}).
  790. Where(whereText, id).
  791. Updates(map[string]any{"enable": true, "up": 0, "down": 0})
  792. if result.Error != nil {
  793. return result.Error
  794. }
  795. inboundWhereText := "id "
  796. if id == -1 {
  797. inboundWhereText += " > ?"
  798. } else {
  799. inboundWhereText += " = ?"
  800. }
  801. result = tx.Model(model.Inbound{}).
  802. Where(inboundWhereText, id).
  803. Update("last_traffic_reset_time", now)
  804. return result.Error
  805. }); err != nil {
  806. return err
  807. }
  808. return nil
  809. }
  810. func (s *ClientService) ResetAllTraffics() (bool, error) {
  811. res := database.GetDB().Model(&xray.ClientTraffic{}).
  812. Where("1 = 1").
  813. Updates(map[string]any{"up": 0, "down": 0})
  814. if res.Error != nil {
  815. return false, res.Error
  816. }
  817. return res.RowsAffected > 0, nil
  818. }
  819. func (s *ClientService) Detach(inboundSvc *InboundService, id int, inboundIds []int) (bool, error) {
  820. existing, err := s.GetByID(id)
  821. if err != nil {
  822. return false, err
  823. }
  824. currentIds, err := s.GetInboundIdsForRecord(id)
  825. if err != nil {
  826. return false, err
  827. }
  828. have := make(map[int]struct{}, len(currentIds))
  829. for _, x := range currentIds {
  830. have[x] = struct{}{}
  831. }
  832. needRestart := false
  833. for _, ibId := range inboundIds {
  834. if _, attached := have[ibId]; !attached {
  835. continue
  836. }
  837. inbound, getErr := inboundSvc.GetInbound(ibId)
  838. if getErr != nil {
  839. return needRestart, getErr
  840. }
  841. key := clientKeyForProtocol(inbound.Protocol, existing)
  842. if key == "" {
  843. continue
  844. }
  845. nr, delErr := s.DelInboundClient(inboundSvc, ibId, key)
  846. if delErr != nil {
  847. return needRestart, delErr
  848. }
  849. if nr {
  850. needRestart = true
  851. }
  852. }
  853. return needRestart, nil
  854. }
  855. func (s *ClientService) checkEmailsExistForClients(inboundSvc *InboundService, clients []model.Client) (string, error) {
  856. emailSubIDs, err := inboundSvc.getAllEmailSubIDs()
  857. if err != nil {
  858. return "", err
  859. }
  860. seen := make(map[string]string, len(clients))
  861. for _, client := range clients {
  862. if client.Email == "" {
  863. continue
  864. }
  865. key := strings.ToLower(client.Email)
  866. if prev, ok := seen[key]; ok {
  867. if prev != client.SubID || client.SubID == "" {
  868. return client.Email, nil
  869. }
  870. continue
  871. }
  872. seen[key] = client.SubID
  873. if existingSub, ok := emailSubIDs[key]; ok {
  874. if client.SubID == "" || existingSub == "" || existingSub != client.SubID {
  875. return client.Email, nil
  876. }
  877. }
  878. }
  879. return "", nil
  880. }
  881. func (s *ClientService) AddInboundClient(inboundSvc *InboundService, data *model.Inbound) (bool, error) {
  882. defer lockInbound(data.Id).Unlock()
  883. clients, err := inboundSvc.GetClients(data)
  884. if err != nil {
  885. return false, err
  886. }
  887. var settings map[string]any
  888. err = json.Unmarshal([]byte(data.Settings), &settings)
  889. if err != nil {
  890. return false, err
  891. }
  892. interfaceClients := settings["clients"].([]any)
  893. nowTs := time.Now().Unix() * 1000
  894. for i := range interfaceClients {
  895. if cm, ok := interfaceClients[i].(map[string]any); ok {
  896. if _, ok2 := cm["created_at"]; !ok2 {
  897. cm["created_at"] = nowTs
  898. }
  899. cm["updated_at"] = nowTs
  900. interfaceClients[i] = cm
  901. }
  902. }
  903. existEmail, err := s.checkEmailsExistForClients(inboundSvc, clients)
  904. if err != nil {
  905. return false, err
  906. }
  907. if existEmail != "" {
  908. return false, common.NewError("Duplicate email:", existEmail)
  909. }
  910. oldInbound, err := inboundSvc.GetInbound(data.Id)
  911. if err != nil {
  912. return false, err
  913. }
  914. for _, client := range clients {
  915. if strings.TrimSpace(client.Email) == "" {
  916. return false, common.NewError("client email is required")
  917. }
  918. switch oldInbound.Protocol {
  919. case "trojan":
  920. if client.Password == "" {
  921. return false, common.NewError("empty client ID")
  922. }
  923. case "shadowsocks":
  924. if client.Email == "" {
  925. return false, common.NewError("empty client ID")
  926. }
  927. case "hysteria", "hysteria2":
  928. if client.Auth == "" {
  929. return false, common.NewError("empty client ID")
  930. }
  931. default:
  932. if client.ID == "" {
  933. return false, common.NewError("empty client ID")
  934. }
  935. }
  936. }
  937. var oldSettings map[string]any
  938. err = json.Unmarshal([]byte(oldInbound.Settings), &oldSettings)
  939. if err != nil {
  940. return false, err
  941. }
  942. if oldInbound.Protocol == model.Shadowsocks {
  943. applyShadowsocksClientMethod(interfaceClients, oldSettings)
  944. }
  945. oldClients := oldSettings["clients"].([]any)
  946. oldClients = compactOrphans(database.GetDB(), oldClients)
  947. oldClients = append(oldClients, interfaceClients...)
  948. oldSettings["clients"] = oldClients
  949. newSettings, err := json.MarshalIndent(oldSettings, "", " ")
  950. if err != nil {
  951. return false, err
  952. }
  953. oldInbound.Settings = string(newSettings)
  954. db := database.GetDB()
  955. tx := db.Begin()
  956. defer func() {
  957. if err != nil {
  958. tx.Rollback()
  959. } else {
  960. tx.Commit()
  961. }
  962. }()
  963. needRestart := false
  964. rt, rterr := inboundSvc.runtimeFor(oldInbound)
  965. if rterr != nil {
  966. if oldInbound.NodeID != nil {
  967. err = rterr
  968. return false, err
  969. }
  970. needRestart = true
  971. } else if oldInbound.NodeID == nil {
  972. for _, client := range clients {
  973. if len(client.Email) == 0 {
  974. needRestart = true
  975. continue
  976. }
  977. inboundSvc.AddClientStat(tx, data.Id, &client)
  978. if !client.Enable {
  979. continue
  980. }
  981. cipher := ""
  982. if oldInbound.Protocol == "shadowsocks" {
  983. cipher = oldSettings["method"].(string)
  984. }
  985. err1 := rt.AddUser(context.Background(), oldInbound, map[string]any{
  986. "email": client.Email,
  987. "id": client.ID,
  988. "auth": client.Auth,
  989. "security": client.Security,
  990. "flow": client.Flow,
  991. "password": client.Password,
  992. "cipher": cipher,
  993. })
  994. if err1 == nil {
  995. logger.Debug("Client added on", rt.Name(), ":", client.Email)
  996. } else {
  997. logger.Debug("Error in adding client on", rt.Name(), ":", err1)
  998. needRestart = true
  999. }
  1000. }
  1001. } else {
  1002. for _, client := range clients {
  1003. if len(client.Email) > 0 {
  1004. inboundSvc.AddClientStat(tx, data.Id, &client)
  1005. }
  1006. if err1 := rt.AddClient(context.Background(), oldInbound, client); err1 != nil {
  1007. err = err1
  1008. return false, err
  1009. }
  1010. }
  1011. }
  1012. if err = tx.Save(oldInbound).Error; err != nil {
  1013. return false, err
  1014. }
  1015. finalClients, gcErr := inboundSvc.GetClients(oldInbound)
  1016. if gcErr != nil {
  1017. err = gcErr
  1018. return false, err
  1019. }
  1020. if err = s.SyncInbound(tx, oldInbound.Id, finalClients); err != nil {
  1021. return false, err
  1022. }
  1023. return needRestart, nil
  1024. }
  1025. func (s *ClientService) UpdateInboundClient(inboundSvc *InboundService, data *model.Inbound, clientId string) (bool, error) {
  1026. defer lockInbound(data.Id).Unlock()
  1027. clients, err := inboundSvc.GetClients(data)
  1028. if err != nil {
  1029. return false, err
  1030. }
  1031. var settings map[string]any
  1032. err = json.Unmarshal([]byte(data.Settings), &settings)
  1033. if err != nil {
  1034. return false, err
  1035. }
  1036. interfaceClients := settings["clients"].([]any)
  1037. oldInbound, err := inboundSvc.GetInbound(data.Id)
  1038. if err != nil {
  1039. return false, err
  1040. }
  1041. oldClients, err := inboundSvc.GetClients(oldInbound)
  1042. if err != nil {
  1043. return false, err
  1044. }
  1045. oldEmail := ""
  1046. newClientId := ""
  1047. clientIndex := -1
  1048. for index, oldClient := range oldClients {
  1049. oldClientId := ""
  1050. switch oldInbound.Protocol {
  1051. case "trojan":
  1052. oldClientId = oldClient.Password
  1053. newClientId = clients[0].Password
  1054. case "shadowsocks":
  1055. oldClientId = oldClient.Email
  1056. newClientId = clients[0].Email
  1057. case "hysteria", "hysteria2":
  1058. oldClientId = oldClient.Auth
  1059. newClientId = clients[0].Auth
  1060. default:
  1061. oldClientId = oldClient.ID
  1062. newClientId = clients[0].ID
  1063. }
  1064. if clientId == oldClientId {
  1065. oldEmail = oldClient.Email
  1066. clientIndex = index
  1067. break
  1068. }
  1069. }
  1070. if newClientId == "" || clientIndex == -1 {
  1071. return false, common.NewError("empty client ID")
  1072. }
  1073. if strings.TrimSpace(clients[0].Email) == "" {
  1074. return false, common.NewError("client email is required")
  1075. }
  1076. if clients[0].Email != oldEmail {
  1077. existEmail, err := s.checkEmailsExistForClients(inboundSvc, clients)
  1078. if err != nil {
  1079. return false, err
  1080. }
  1081. if existEmail != "" {
  1082. return false, common.NewError("Duplicate email:", existEmail)
  1083. }
  1084. }
  1085. var oldSettings map[string]any
  1086. err = json.Unmarshal([]byte(oldInbound.Settings), &oldSettings)
  1087. if err != nil {
  1088. return false, err
  1089. }
  1090. settingsClients := oldSettings["clients"].([]any)
  1091. var preservedCreated any
  1092. if clientIndex >= 0 && clientIndex < len(settingsClients) {
  1093. if oldMap, ok := settingsClients[clientIndex].(map[string]any); ok {
  1094. if v, ok2 := oldMap["created_at"]; ok2 {
  1095. preservedCreated = v
  1096. }
  1097. }
  1098. }
  1099. if len(interfaceClients) > 0 {
  1100. if newMap, ok := interfaceClients[0].(map[string]any); ok {
  1101. if preservedCreated == nil {
  1102. preservedCreated = time.Now().Unix() * 1000
  1103. }
  1104. newMap["created_at"] = preservedCreated
  1105. newMap["updated_at"] = time.Now().Unix() * 1000
  1106. interfaceClients[0] = newMap
  1107. }
  1108. }
  1109. if oldInbound.Protocol == model.Shadowsocks {
  1110. applyShadowsocksClientMethod(interfaceClients, oldSettings)
  1111. }
  1112. settingsClients[clientIndex] = interfaceClients[0]
  1113. oldSettings["clients"] = settingsClients
  1114. if oldInbound.Protocol == model.VLESS {
  1115. hasVisionFlow := false
  1116. for _, c := range settingsClients {
  1117. cm, ok := c.(map[string]any)
  1118. if !ok {
  1119. continue
  1120. }
  1121. if flow, _ := cm["flow"].(string); flow == "xtls-rprx-vision" {
  1122. hasVisionFlow = true
  1123. break
  1124. }
  1125. }
  1126. if !hasVisionFlow {
  1127. delete(oldSettings, "testseed")
  1128. }
  1129. }
  1130. newSettings, err := json.MarshalIndent(oldSettings, "", " ")
  1131. if err != nil {
  1132. return false, err
  1133. }
  1134. oldInbound.Settings = string(newSettings)
  1135. db := database.GetDB()
  1136. tx := db.Begin()
  1137. defer func() {
  1138. if err != nil {
  1139. tx.Rollback()
  1140. } else {
  1141. tx.Commit()
  1142. }
  1143. }()
  1144. if len(clients[0].Email) > 0 {
  1145. if len(oldEmail) > 0 {
  1146. emailUnchanged := strings.EqualFold(oldEmail, clients[0].Email)
  1147. targetExists := int64(0)
  1148. if !emailUnchanged {
  1149. if err = tx.Model(xray.ClientTraffic{}).Where("email = ?", clients[0].Email).Count(&targetExists).Error; err != nil {
  1150. return false, err
  1151. }
  1152. }
  1153. if emailUnchanged || targetExists == 0 {
  1154. err = inboundSvc.UpdateClientStat(tx, oldEmail, &clients[0])
  1155. if err != nil {
  1156. return false, err
  1157. }
  1158. err = inboundSvc.UpdateClientIPs(tx, oldEmail, clients[0].Email)
  1159. if err != nil {
  1160. return false, err
  1161. }
  1162. } else {
  1163. stillUsed, sErr := inboundSvc.emailUsedByOtherInbounds(oldEmail, data.Id)
  1164. if sErr != nil {
  1165. return false, sErr
  1166. }
  1167. if !stillUsed {
  1168. if err = inboundSvc.DelClientStat(tx, oldEmail); err != nil {
  1169. return false, err
  1170. }
  1171. if err = inboundSvc.DelClientIPs(tx, oldEmail); err != nil {
  1172. return false, err
  1173. }
  1174. }
  1175. if err = inboundSvc.UpdateClientStat(tx, clients[0].Email, &clients[0]); err != nil {
  1176. return false, err
  1177. }
  1178. }
  1179. } else {
  1180. inboundSvc.AddClientStat(tx, data.Id, &clients[0])
  1181. }
  1182. } else {
  1183. stillUsed, err := inboundSvc.emailUsedByOtherInbounds(oldEmail, data.Id)
  1184. if err != nil {
  1185. return false, err
  1186. }
  1187. if !stillUsed {
  1188. err = inboundSvc.DelClientStat(tx, oldEmail)
  1189. if err != nil {
  1190. return false, err
  1191. }
  1192. err = inboundSvc.DelClientIPs(tx, oldEmail)
  1193. if err != nil {
  1194. return false, err
  1195. }
  1196. }
  1197. }
  1198. needRestart := false
  1199. if len(oldEmail) > 0 {
  1200. rt, rterr := inboundSvc.runtimeFor(oldInbound)
  1201. if rterr != nil {
  1202. if oldInbound.NodeID != nil {
  1203. err = rterr
  1204. return false, err
  1205. }
  1206. needRestart = true
  1207. } else if oldInbound.NodeID == nil {
  1208. if oldClients[clientIndex].Enable {
  1209. err1 := rt.RemoveUser(context.Background(), oldInbound, oldEmail)
  1210. if err1 == nil {
  1211. logger.Debug("Old client deleted on", rt.Name(), ":", oldEmail)
  1212. } else if strings.Contains(err1.Error(), fmt.Sprintf("User %s not found.", oldEmail)) {
  1213. logger.Debug("User is already deleted. Nothing to do more...")
  1214. } else {
  1215. logger.Debug("Error in deleting client on", rt.Name(), ":", err1)
  1216. needRestart = true
  1217. }
  1218. }
  1219. if clients[0].Enable {
  1220. cipher := ""
  1221. if oldInbound.Protocol == "shadowsocks" {
  1222. cipher = oldSettings["method"].(string)
  1223. }
  1224. err1 := rt.AddUser(context.Background(), oldInbound, map[string]any{
  1225. "email": clients[0].Email,
  1226. "id": clients[0].ID,
  1227. "security": clients[0].Security,
  1228. "flow": clients[0].Flow,
  1229. "auth": clients[0].Auth,
  1230. "password": clients[0].Password,
  1231. "cipher": cipher,
  1232. })
  1233. if err1 == nil {
  1234. logger.Debug("Client edited on", rt.Name(), ":", clients[0].Email)
  1235. } else {
  1236. logger.Debug("Error in adding client on", rt.Name(), ":", err1)
  1237. needRestart = true
  1238. }
  1239. }
  1240. } else {
  1241. if err1 := rt.UpdateUser(context.Background(), oldInbound, oldEmail, clients[0]); err1 != nil {
  1242. err = err1
  1243. return false, err
  1244. }
  1245. }
  1246. } else {
  1247. logger.Debug("Client old email not found")
  1248. needRestart = true
  1249. }
  1250. if err = tx.Save(oldInbound).Error; err != nil {
  1251. return false, err
  1252. }
  1253. finalClients, gcErr := inboundSvc.GetClients(oldInbound)
  1254. if gcErr != nil {
  1255. err = gcErr
  1256. return false, err
  1257. }
  1258. if err = s.SyncInbound(tx, oldInbound.Id, finalClients); err != nil {
  1259. return false, err
  1260. }
  1261. return needRestart, nil
  1262. }
  1263. func (s *ClientService) DelInboundClient(inboundSvc *InboundService, inboundId int, clientId string) (bool, error) {
  1264. defer lockInbound(inboundId).Unlock()
  1265. oldInbound, err := inboundSvc.GetInbound(inboundId)
  1266. if err != nil {
  1267. logger.Error("Load Old Data Error")
  1268. return false, err
  1269. }
  1270. var settings map[string]any
  1271. err = json.Unmarshal([]byte(oldInbound.Settings), &settings)
  1272. if err != nil {
  1273. return false, err
  1274. }
  1275. email := ""
  1276. client_key := "id"
  1277. switch oldInbound.Protocol {
  1278. case "trojan":
  1279. client_key = "password"
  1280. case "shadowsocks":
  1281. client_key = "email"
  1282. case "hysteria", "hysteria2":
  1283. client_key = "auth"
  1284. }
  1285. interfaceClients := settings["clients"].([]any)
  1286. var newClients []any
  1287. needApiDel := false
  1288. clientFound := false
  1289. for _, client := range interfaceClients {
  1290. c := client.(map[string]any)
  1291. c_id := c[client_key].(string)
  1292. if c_id == clientId {
  1293. clientFound = true
  1294. email, _ = c["email"].(string)
  1295. needApiDel, _ = c["enable"].(bool)
  1296. } else {
  1297. newClients = append(newClients, client)
  1298. }
  1299. }
  1300. if !clientFound {
  1301. return false, common.NewError("Client Not Found In Inbound For ID:", clientId)
  1302. }
  1303. db := database.GetDB()
  1304. newClients = compactOrphans(db, newClients)
  1305. if newClients == nil {
  1306. newClients = []any{}
  1307. }
  1308. settings["clients"] = newClients
  1309. newSettings, err := json.MarshalIndent(settings, "", " ")
  1310. if err != nil {
  1311. return false, err
  1312. }
  1313. oldInbound.Settings = string(newSettings)
  1314. emailShared, err := inboundSvc.emailUsedByOtherInbounds(email, inboundId)
  1315. if err != nil {
  1316. return false, err
  1317. }
  1318. if !emailShared {
  1319. err = inboundSvc.DelClientIPs(db, email)
  1320. if err != nil {
  1321. logger.Error("Error in delete client IPs")
  1322. return false, err
  1323. }
  1324. }
  1325. needRestart := false
  1326. if len(email) > 0 {
  1327. var enables []bool
  1328. err = db.Model(xray.ClientTraffic{}).Where("email = ?", email).Limit(1).Pluck("enable", &enables).Error
  1329. if err != nil {
  1330. logger.Error("Get stats error")
  1331. return false, err
  1332. }
  1333. notDepleted := len(enables) > 0 && enables[0]
  1334. if !emailShared {
  1335. err = inboundSvc.DelClientStat(db, email)
  1336. if err != nil {
  1337. logger.Error("Delete stats Data Error")
  1338. return false, err
  1339. }
  1340. }
  1341. if needApiDel && notDepleted && oldInbound.NodeID == nil {
  1342. rt, rterr := inboundSvc.runtimeFor(oldInbound)
  1343. if rterr != nil {
  1344. needRestart = true
  1345. } else {
  1346. err1 := rt.RemoveUser(context.Background(), oldInbound, email)
  1347. if err1 == nil {
  1348. logger.Debug("Client deleted on", rt.Name(), ":", email)
  1349. needRestart = false
  1350. } else if strings.Contains(err1.Error(), fmt.Sprintf("User %s not found.", email)) {
  1351. logger.Debug("User is already deleted. Nothing to do more...")
  1352. } else {
  1353. logger.Debug("Error in deleting client on", rt.Name(), ":", err1)
  1354. needRestart = true
  1355. }
  1356. }
  1357. }
  1358. }
  1359. if oldInbound.NodeID != nil && len(email) > 0 {
  1360. rt, rterr := inboundSvc.runtimeFor(oldInbound)
  1361. if rterr != nil {
  1362. return false, rterr
  1363. }
  1364. if err1 := rt.DeleteUser(context.Background(), oldInbound, email); err1 != nil {
  1365. return false, err1
  1366. }
  1367. }
  1368. if err := db.Save(oldInbound).Error; err != nil {
  1369. return false, err
  1370. }
  1371. finalClients, gcErr := inboundSvc.GetClients(oldInbound)
  1372. if gcErr != nil {
  1373. return false, gcErr
  1374. }
  1375. if err := s.SyncInbound(db, inboundId, finalClients); err != nil {
  1376. return false, err
  1377. }
  1378. return needRestart, nil
  1379. }
  1380. func (s *ClientService) DelInboundClientByEmail(inboundSvc *InboundService, inboundId int, email string) (bool, error) {
  1381. defer lockInbound(inboundId).Unlock()
  1382. oldInbound, err := inboundSvc.GetInbound(inboundId)
  1383. if err != nil {
  1384. logger.Error("Load Old Data Error")
  1385. return false, err
  1386. }
  1387. var settings map[string]any
  1388. if err := json.Unmarshal([]byte(oldInbound.Settings), &settings); err != nil {
  1389. return false, err
  1390. }
  1391. interfaceClients, ok := settings["clients"].([]any)
  1392. if !ok {
  1393. return false, common.NewError("invalid clients format in inbound settings")
  1394. }
  1395. var newClients []any
  1396. needApiDel := false
  1397. found := false
  1398. for _, client := range interfaceClients {
  1399. c, ok := client.(map[string]any)
  1400. if !ok {
  1401. continue
  1402. }
  1403. if cEmail, ok := c["email"].(string); ok && cEmail == email {
  1404. found = true
  1405. needApiDel, _ = c["enable"].(bool)
  1406. } else {
  1407. newClients = append(newClients, client)
  1408. }
  1409. }
  1410. if !found {
  1411. return false, common.NewError(fmt.Sprintf("client with email %s not found", email))
  1412. }
  1413. db := database.GetDB()
  1414. newClients = compactOrphans(db, newClients)
  1415. if newClients == nil {
  1416. newClients = []any{}
  1417. }
  1418. settings["clients"] = newClients
  1419. newSettings, err := json.MarshalIndent(settings, "", " ")
  1420. if err != nil {
  1421. return false, err
  1422. }
  1423. oldInbound.Settings = string(newSettings)
  1424. emailShared, err := inboundSvc.emailUsedByOtherInbounds(email, inboundId)
  1425. if err != nil {
  1426. return false, err
  1427. }
  1428. if !emailShared {
  1429. if err := inboundSvc.DelClientIPs(db, email); err != nil {
  1430. logger.Error("Error in delete client IPs")
  1431. return false, err
  1432. }
  1433. }
  1434. needRestart := false
  1435. if len(email) > 0 && !emailShared {
  1436. traffic, err := inboundSvc.GetClientTrafficByEmail(email)
  1437. if err != nil {
  1438. return false, err
  1439. }
  1440. if traffic != nil {
  1441. if err := inboundSvc.DelClientStat(db, email); err != nil {
  1442. logger.Error("Delete stats Data Error")
  1443. return false, err
  1444. }
  1445. }
  1446. if needApiDel {
  1447. rt, rterr := inboundSvc.runtimeFor(oldInbound)
  1448. if rterr != nil {
  1449. if oldInbound.NodeID != nil {
  1450. return false, rterr
  1451. }
  1452. needRestart = true
  1453. } else if oldInbound.NodeID == nil {
  1454. if err1 := rt.RemoveUser(context.Background(), oldInbound, email); err1 == nil {
  1455. logger.Debug("Client deleted on", rt.Name(), ":", email)
  1456. needRestart = false
  1457. } else if strings.Contains(err1.Error(), fmt.Sprintf("User %s not found.", email)) {
  1458. logger.Debug("User is already deleted. Nothing to do more...")
  1459. } else {
  1460. logger.Debug("Error in deleting client on", rt.Name(), ":", err1)
  1461. needRestart = true
  1462. }
  1463. } else {
  1464. if err1 := rt.DeleteUser(context.Background(), oldInbound, email); err1 != nil {
  1465. return false, err1
  1466. }
  1467. }
  1468. }
  1469. }
  1470. if err := db.Save(oldInbound).Error; err != nil {
  1471. return false, err
  1472. }
  1473. finalClients, gcErr := inboundSvc.GetClients(oldInbound)
  1474. if gcErr != nil {
  1475. return false, gcErr
  1476. }
  1477. if err := s.SyncInbound(db, inboundId, finalClients); err != nil {
  1478. return false, err
  1479. }
  1480. return needRestart, nil
  1481. }
  1482. func (s *ClientService) SetClientTelegramUserID(inboundSvc *InboundService, trafficId int, tgId int64) (bool, error) {
  1483. traffic, inbound, err := inboundSvc.GetClientInboundByTrafficID(trafficId)
  1484. if err != nil {
  1485. return false, err
  1486. }
  1487. if inbound == nil {
  1488. return false, common.NewError("Inbound Not Found For Traffic ID:", trafficId)
  1489. }
  1490. clientEmail := traffic.Email
  1491. oldClients, err := inboundSvc.GetClients(inbound)
  1492. if err != nil {
  1493. return false, err
  1494. }
  1495. clientId := ""
  1496. for _, oldClient := range oldClients {
  1497. if oldClient.Email == clientEmail {
  1498. switch inbound.Protocol {
  1499. case "trojan":
  1500. clientId = oldClient.Password
  1501. case "shadowsocks":
  1502. clientId = oldClient.Email
  1503. default:
  1504. clientId = oldClient.ID
  1505. }
  1506. break
  1507. }
  1508. }
  1509. if len(clientId) == 0 {
  1510. return false, common.NewError("Client Not Found For Email:", clientEmail)
  1511. }
  1512. var settings map[string]any
  1513. err = json.Unmarshal([]byte(inbound.Settings), &settings)
  1514. if err != nil {
  1515. return false, err
  1516. }
  1517. clients := settings["clients"].([]any)
  1518. var newClients []any
  1519. for client_index := range clients {
  1520. c := clients[client_index].(map[string]any)
  1521. if c["email"] == clientEmail {
  1522. c["tgId"] = tgId
  1523. c["updated_at"] = time.Now().Unix() * 1000
  1524. newClients = append(newClients, any(c))
  1525. }
  1526. }
  1527. settings["clients"] = newClients
  1528. modifiedSettings, err := json.MarshalIndent(settings, "", " ")
  1529. if err != nil {
  1530. return false, err
  1531. }
  1532. inbound.Settings = string(modifiedSettings)
  1533. needRestart, err := s.UpdateInboundClient(inboundSvc, inbound, clientId)
  1534. return needRestart, err
  1535. }
  1536. func (s *ClientService) checkIsEnabledByEmail(inboundSvc *InboundService, clientEmail string) (bool, error) {
  1537. _, inbound, err := inboundSvc.GetClientInboundByEmail(clientEmail)
  1538. if err != nil {
  1539. return false, err
  1540. }
  1541. if inbound == nil {
  1542. return false, common.NewError("Inbound Not Found For Email:", clientEmail)
  1543. }
  1544. clients, err := inboundSvc.GetClients(inbound)
  1545. if err != nil {
  1546. return false, err
  1547. }
  1548. isEnable := false
  1549. for _, client := range clients {
  1550. if client.Email == clientEmail {
  1551. isEnable = client.Enable
  1552. break
  1553. }
  1554. }
  1555. return isEnable, err
  1556. }
  1557. func (s *ClientService) ToggleClientEnableByEmail(inboundSvc *InboundService, clientEmail string) (bool, bool, error) {
  1558. _, inbound, err := inboundSvc.GetClientInboundByEmail(clientEmail)
  1559. if err != nil {
  1560. return false, false, err
  1561. }
  1562. if inbound == nil {
  1563. return false, false, common.NewError("Inbound Not Found For Email:", clientEmail)
  1564. }
  1565. oldClients, err := inboundSvc.GetClients(inbound)
  1566. if err != nil {
  1567. return false, false, err
  1568. }
  1569. clientId := ""
  1570. clientOldEnabled := false
  1571. for _, oldClient := range oldClients {
  1572. if oldClient.Email == clientEmail {
  1573. switch inbound.Protocol {
  1574. case "trojan":
  1575. clientId = oldClient.Password
  1576. case "shadowsocks":
  1577. clientId = oldClient.Email
  1578. default:
  1579. clientId = oldClient.ID
  1580. }
  1581. clientOldEnabled = oldClient.Enable
  1582. break
  1583. }
  1584. }
  1585. if len(clientId) == 0 {
  1586. return false, false, common.NewError("Client Not Found For Email:", clientEmail)
  1587. }
  1588. var settings map[string]any
  1589. err = json.Unmarshal([]byte(inbound.Settings), &settings)
  1590. if err != nil {
  1591. return false, false, err
  1592. }
  1593. clients := settings["clients"].([]any)
  1594. var newClients []any
  1595. for client_index := range clients {
  1596. c := clients[client_index].(map[string]any)
  1597. if c["email"] == clientEmail {
  1598. c["enable"] = !clientOldEnabled
  1599. c["updated_at"] = time.Now().Unix() * 1000
  1600. newClients = append(newClients, any(c))
  1601. }
  1602. }
  1603. settings["clients"] = newClients
  1604. modifiedSettings, err := json.MarshalIndent(settings, "", " ")
  1605. if err != nil {
  1606. return false, false, err
  1607. }
  1608. inbound.Settings = string(modifiedSettings)
  1609. needRestart, err := s.UpdateInboundClient(inboundSvc, inbound, clientId)
  1610. if err != nil {
  1611. return false, needRestart, err
  1612. }
  1613. return !clientOldEnabled, needRestart, nil
  1614. }
  1615. func (s *ClientService) SetClientEnableByEmail(inboundSvc *InboundService, clientEmail string, enable bool) (bool, bool, error) {
  1616. current, err := s.checkIsEnabledByEmail(inboundSvc, clientEmail)
  1617. if err != nil {
  1618. return false, false, err
  1619. }
  1620. if current == enable {
  1621. return false, false, nil
  1622. }
  1623. newEnabled, needRestart, err := s.ToggleClientEnableByEmail(inboundSvc, clientEmail)
  1624. if err != nil {
  1625. return false, needRestart, err
  1626. }
  1627. return newEnabled == enable, needRestart, nil
  1628. }
  1629. func (s *ClientService) ResetClientIpLimitByEmail(inboundSvc *InboundService, clientEmail string, count int) (bool, error) {
  1630. _, inbound, err := inboundSvc.GetClientInboundByEmail(clientEmail)
  1631. if err != nil {
  1632. return false, err
  1633. }
  1634. if inbound == nil {
  1635. return false, common.NewError("Inbound Not Found For Email:", clientEmail)
  1636. }
  1637. oldClients, err := inboundSvc.GetClients(inbound)
  1638. if err != nil {
  1639. return false, err
  1640. }
  1641. clientId := ""
  1642. for _, oldClient := range oldClients {
  1643. if oldClient.Email == clientEmail {
  1644. switch inbound.Protocol {
  1645. case "trojan":
  1646. clientId = oldClient.Password
  1647. case "shadowsocks":
  1648. clientId = oldClient.Email
  1649. default:
  1650. clientId = oldClient.ID
  1651. }
  1652. break
  1653. }
  1654. }
  1655. if len(clientId) == 0 {
  1656. return false, common.NewError("Client Not Found For Email:", clientEmail)
  1657. }
  1658. var settings map[string]any
  1659. err = json.Unmarshal([]byte(inbound.Settings), &settings)
  1660. if err != nil {
  1661. return false, err
  1662. }
  1663. clients := settings["clients"].([]any)
  1664. var newClients []any
  1665. for client_index := range clients {
  1666. c := clients[client_index].(map[string]any)
  1667. if c["email"] == clientEmail {
  1668. c["limitIp"] = count
  1669. c["updated_at"] = time.Now().Unix() * 1000
  1670. newClients = append(newClients, any(c))
  1671. }
  1672. }
  1673. settings["clients"] = newClients
  1674. modifiedSettings, err := json.MarshalIndent(settings, "", " ")
  1675. if err != nil {
  1676. return false, err
  1677. }
  1678. inbound.Settings = string(modifiedSettings)
  1679. needRestart, err := s.UpdateInboundClient(inboundSvc, inbound, clientId)
  1680. return needRestart, err
  1681. }
  1682. func (s *ClientService) ResetClientExpiryTimeByEmail(inboundSvc *InboundService, clientEmail string, expiry_time int64) (bool, error) {
  1683. _, inbound, err := inboundSvc.GetClientInboundByEmail(clientEmail)
  1684. if err != nil {
  1685. return false, err
  1686. }
  1687. if inbound == nil {
  1688. return false, common.NewError("Inbound Not Found For Email:", clientEmail)
  1689. }
  1690. oldClients, err := inboundSvc.GetClients(inbound)
  1691. if err != nil {
  1692. return false, err
  1693. }
  1694. clientId := ""
  1695. for _, oldClient := range oldClients {
  1696. if oldClient.Email == clientEmail {
  1697. switch inbound.Protocol {
  1698. case "trojan":
  1699. clientId = oldClient.Password
  1700. case "shadowsocks":
  1701. clientId = oldClient.Email
  1702. default:
  1703. clientId = oldClient.ID
  1704. }
  1705. break
  1706. }
  1707. }
  1708. if len(clientId) == 0 {
  1709. return false, common.NewError("Client Not Found For Email:", clientEmail)
  1710. }
  1711. var settings map[string]any
  1712. err = json.Unmarshal([]byte(inbound.Settings), &settings)
  1713. if err != nil {
  1714. return false, err
  1715. }
  1716. clients := settings["clients"].([]any)
  1717. var newClients []any
  1718. for client_index := range clients {
  1719. c := clients[client_index].(map[string]any)
  1720. if c["email"] == clientEmail {
  1721. c["expiryTime"] = expiry_time
  1722. c["updated_at"] = time.Now().Unix() * 1000
  1723. newClients = append(newClients, any(c))
  1724. }
  1725. }
  1726. settings["clients"] = newClients
  1727. modifiedSettings, err := json.MarshalIndent(settings, "", " ")
  1728. if err != nil {
  1729. return false, err
  1730. }
  1731. inbound.Settings = string(modifiedSettings)
  1732. needRestart, err := s.UpdateInboundClient(inboundSvc, inbound, clientId)
  1733. return needRestart, err
  1734. }
  1735. func (s *ClientService) ResetClientTrafficLimitByEmail(inboundSvc *InboundService, clientEmail string, totalGB int) (bool, error) {
  1736. if totalGB < 0 {
  1737. return false, common.NewError("totalGB must be >= 0")
  1738. }
  1739. _, inbound, err := inboundSvc.GetClientInboundByEmail(clientEmail)
  1740. if err != nil {
  1741. return false, err
  1742. }
  1743. if inbound == nil {
  1744. return false, common.NewError("Inbound Not Found For Email:", clientEmail)
  1745. }
  1746. oldClients, err := inboundSvc.GetClients(inbound)
  1747. if err != nil {
  1748. return false, err
  1749. }
  1750. clientId := ""
  1751. for _, oldClient := range oldClients {
  1752. if oldClient.Email == clientEmail {
  1753. switch inbound.Protocol {
  1754. case "trojan":
  1755. clientId = oldClient.Password
  1756. case "shadowsocks":
  1757. clientId = oldClient.Email
  1758. default:
  1759. clientId = oldClient.ID
  1760. }
  1761. break
  1762. }
  1763. }
  1764. if len(clientId) == 0 {
  1765. return false, common.NewError("Client Not Found For Email:", clientEmail)
  1766. }
  1767. var settings map[string]any
  1768. err = json.Unmarshal([]byte(inbound.Settings), &settings)
  1769. if err != nil {
  1770. return false, err
  1771. }
  1772. clients := settings["clients"].([]any)
  1773. var newClients []any
  1774. for client_index := range clients {
  1775. c := clients[client_index].(map[string]any)
  1776. if c["email"] == clientEmail {
  1777. c["totalGB"] = totalGB * 1024 * 1024 * 1024
  1778. c["updated_at"] = time.Now().Unix() * 1000
  1779. newClients = append(newClients, any(c))
  1780. }
  1781. }
  1782. settings["clients"] = newClients
  1783. modifiedSettings, err := json.MarshalIndent(settings, "", " ")
  1784. if err != nil {
  1785. return false, err
  1786. }
  1787. inbound.Settings = string(modifiedSettings)
  1788. needRestart, err := s.UpdateInboundClient(inboundSvc, inbound, clientId)
  1789. return needRestart, err
  1790. }