client.go 73 KB

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