client.go 62 KB

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