client.go 81 KB

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