client.go 80 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086
  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. needRestart := false
  554. for _, ibId := range inboundIds {
  555. inbound, getErr := inboundSvc.GetInbound(ibId)
  556. if getErr != nil {
  557. return needRestart, getErr
  558. }
  559. oldKey := clientKeyForProtocol(inbound.Protocol, existing)
  560. if oldKey == "" {
  561. continue
  562. }
  563. if err := s.fillProtocolDefaults(&updated, inbound); err != nil {
  564. return needRestart, err
  565. }
  566. settingsPayload, mErr := json.Marshal(map[string][]model.Client{"clients": {updated}})
  567. if mErr != nil {
  568. return needRestart, mErr
  569. }
  570. nr, upErr := s.UpdateInboundClient(inboundSvc, &model.Inbound{
  571. Id: ibId,
  572. Settings: string(settingsPayload),
  573. }, oldKey)
  574. if upErr != nil {
  575. return needRestart, upErr
  576. }
  577. if nr {
  578. needRestart = true
  579. }
  580. }
  581. if err := database.GetDB().Model(&model.ClientRecord{}).
  582. Where("id = ?", id).
  583. Update("updated_at", updated.UpdatedAt).Error; err != nil {
  584. return needRestart, err
  585. }
  586. return needRestart, nil
  587. }
  588. func (s *ClientService) Delete(inboundSvc *InboundService, id int, keepTraffic bool) (bool, error) {
  589. existing, err := s.GetByID(id)
  590. if err != nil {
  591. return false, err
  592. }
  593. tombstoneClientEmail(existing.Email)
  594. inboundIds, err := s.GetInboundIdsForRecord(id)
  595. if err != nil {
  596. return false, err
  597. }
  598. needRestart := false
  599. for _, ibId := range inboundIds {
  600. inbound, getErr := inboundSvc.GetInbound(ibId)
  601. if getErr != nil {
  602. return needRestart, getErr
  603. }
  604. key := clientKeyForProtocol(inbound.Protocol, existing)
  605. if key == "" {
  606. continue
  607. }
  608. nr, delErr := s.DelInboundClient(inboundSvc, ibId, key)
  609. if delErr != nil {
  610. return needRestart, delErr
  611. }
  612. if nr {
  613. needRestart = true
  614. }
  615. }
  616. db := database.GetDB()
  617. if err := db.Where("client_id = ?", id).Delete(&model.ClientInbound{}).Error; err != nil {
  618. return needRestart, err
  619. }
  620. if !keepTraffic && existing.Email != "" {
  621. if err := db.Where("email = ?", existing.Email).Delete(&xray.ClientTraffic{}).Error; err != nil {
  622. return needRestart, err
  623. }
  624. if err := db.Where("client_email = ?", existing.Email).Delete(&model.InboundClientIps{}).Error; err != nil {
  625. return needRestart, err
  626. }
  627. }
  628. if err := db.Delete(&model.ClientRecord{}, id).Error; err != nil {
  629. return needRestart, err
  630. }
  631. return needRestart, nil
  632. }
  633. func (s *ClientService) Attach(inboundSvc *InboundService, id int, inboundIds []int) (bool, error) {
  634. existing, err := s.GetByID(id)
  635. if err != nil {
  636. return false, err
  637. }
  638. currentIds, err := s.GetInboundIdsForRecord(id)
  639. if err != nil {
  640. return false, err
  641. }
  642. have := make(map[int]struct{}, len(currentIds))
  643. for _, x := range currentIds {
  644. have[x] = struct{}{}
  645. }
  646. clientWire := existing.ToClient()
  647. clientWire.UpdatedAt = time.Now().UnixMilli()
  648. needRestart := false
  649. for _, ibId := range inboundIds {
  650. if _, attached := have[ibId]; attached {
  651. continue
  652. }
  653. inbound, getErr := inboundSvc.GetInbound(ibId)
  654. if getErr != nil {
  655. return needRestart, getErr
  656. }
  657. copyClient := *clientWire
  658. if err := s.fillProtocolDefaults(&copyClient, inbound); err != nil {
  659. return needRestart, err
  660. }
  661. settingsPayload, mErr := json.Marshal(map[string][]model.Client{"clients": {copyClient}})
  662. if mErr != nil {
  663. return needRestart, mErr
  664. }
  665. nr, addErr := s.AddInboundClient(inboundSvc, &model.Inbound{
  666. Id: ibId,
  667. Settings: string(settingsPayload),
  668. })
  669. if addErr != nil {
  670. return needRestart, addErr
  671. }
  672. if nr {
  673. needRestart = true
  674. }
  675. }
  676. return needRestart, nil
  677. }
  678. func (s *ClientService) CreateOne(inboundSvc *InboundService, inboundId int, client model.Client) (bool, error) {
  679. return s.Create(inboundSvc, &ClientCreatePayload{
  680. Client: client,
  681. InboundIds: []int{inboundId},
  682. })
  683. }
  684. func (s *ClientService) DetachByEmail(inboundSvc *InboundService, inboundId int, email string) (bool, error) {
  685. if email == "" {
  686. return false, common.NewError("client email is required")
  687. }
  688. rec, err := s.GetRecordByEmail(nil, email)
  689. if err != nil {
  690. return false, err
  691. }
  692. return s.Detach(inboundSvc, rec.Id, []int{inboundId})
  693. }
  694. func (s *ClientService) AttachByEmail(inboundSvc *InboundService, email string, inboundIds []int) (bool, error) {
  695. if email == "" {
  696. return false, common.NewError("client email is required")
  697. }
  698. rec, err := s.GetRecordByEmail(nil, email)
  699. if err != nil {
  700. return false, err
  701. }
  702. return s.Attach(inboundSvc, rec.Id, inboundIds)
  703. }
  704. func (s *ClientService) DetachByEmailMany(inboundSvc *InboundService, email string, inboundIds []int) (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, inboundIds)
  713. }
  714. func (s *ClientService) DeleteByEmail(inboundSvc *InboundService, email string, keepTraffic bool) (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.Delete(inboundSvc, rec.Id, keepTraffic)
  723. }
  724. func (s *ClientService) UpdateByEmail(inboundSvc *InboundService, email string, updated model.Client) (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.Update(inboundSvc, rec.Id, updated)
  733. }
  734. func (s *ClientService) ResetTrafficByEmail(inboundSvc *InboundService, email string) (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. inboundIds, err := s.GetInboundIdsForRecord(rec.Id)
  743. if err != nil {
  744. return false, err
  745. }
  746. if len(inboundIds) == 0 {
  747. if rErr := inboundSvc.ResetClientTrafficByEmail(email); rErr != nil {
  748. return false, rErr
  749. }
  750. return false, nil
  751. }
  752. needRestart := false
  753. for _, ibId := range inboundIds {
  754. nr, rErr := inboundSvc.ResetClientTraffic(ibId, email)
  755. if rErr != nil {
  756. return needRestart, rErr
  757. }
  758. if nr {
  759. needRestart = true
  760. }
  761. }
  762. return needRestart, nil
  763. }
  764. // ClientSlim is the row-shape used by the clients page. It drops fields the
  765. // table never reads (UUID, password, auth, flow, security, reverse, tgId)
  766. // so the list payload stays compact even when the panel manages thousands
  767. // of clients. Modals that need the full record still call /get/:email.
  768. type ClientSlim struct {
  769. Email string `json:"email"`
  770. SubID string `json:"subId"`
  771. Enable bool `json:"enable"`
  772. TotalGB int64 `json:"totalGB"`
  773. ExpiryTime int64 `json:"expiryTime"`
  774. LimitIP int `json:"limitIp"`
  775. Reset int `json:"reset"`
  776. Comment string `json:"comment,omitempty"`
  777. InboundIds []int `json:"inboundIds"`
  778. Traffic *xray.ClientTraffic `json:"traffic,omitempty"`
  779. CreatedAt int64 `json:"createdAt"`
  780. UpdatedAt int64 `json:"updatedAt"`
  781. }
  782. // ClientPageParams are the query params accepted by /panel/api/clients/list/paged.
  783. // All fields are optional — the empty value means "no filter" / defaults.
  784. type ClientPageParams struct {
  785. Page int `form:"page"`
  786. PageSize int `form:"pageSize"`
  787. Search string `form:"search"`
  788. Filter string `form:"filter"`
  789. Protocol string `form:"protocol"`
  790. Inbound int `form:"inbound"`
  791. Sort string `form:"sort"`
  792. Order string `form:"order"`
  793. }
  794. // ClientPageResponse is the shape returned by ListPaged. `Total` is the
  795. // row count in the DB; `Filtered` is the count after Search/Filter/Protocol
  796. // were applied, before pagination. The page contains at most PageSize items.
  797. // Summary is computed across the full DB row set so dashboard counters
  798. // on the clients page stay stable as the user paginates/filters.
  799. type ClientPageResponse struct {
  800. Items []ClientSlim `json:"items"`
  801. Total int `json:"total"`
  802. Filtered int `json:"filtered"`
  803. Page int `json:"page"`
  804. PageSize int `json:"pageSize"`
  805. Summary ClientsSummary `json:"summary"`
  806. }
  807. // ClientsSummary collects per-bucket counts plus the matching email lists so
  808. // the clients page can render the dashboard stat cards and their hover
  809. // popovers without shipping the full client array.
  810. type ClientsSummary struct {
  811. Total int `json:"total"`
  812. Active int `json:"active"`
  813. Online []string `json:"online"`
  814. Depleted []string `json:"depleted"`
  815. Expiring []string `json:"expiring"`
  816. Deactive []string `json:"deactive"`
  817. }
  818. const (
  819. clientPageDefaultSize = 25
  820. clientPageMaxSize = 200
  821. )
  822. // ListPaged loads every client (with traffic + attachments) into memory,
  823. // applies the requested filter / search / protocol predicates, sorts, and
  824. // returns the requested page along with total and filtered counts. The DB
  825. // query itself is unchanged from List(); the win is that the response
  826. // only carries 25-ish slim rows over the wire instead of all 2000 full
  827. // records, which on real panels was the dominant cost.
  828. func (s *ClientService) ListPaged(inboundSvc *InboundService, settingSvc *SettingService, params ClientPageParams) (*ClientPageResponse, error) {
  829. all, err := s.List()
  830. if err != nil {
  831. return nil, err
  832. }
  833. total := len(all)
  834. pageSize := params.PageSize
  835. if pageSize <= 0 {
  836. pageSize = clientPageDefaultSize
  837. }
  838. if pageSize > clientPageMaxSize {
  839. pageSize = clientPageMaxSize
  840. }
  841. page := params.Page
  842. if page <= 0 {
  843. page = 1
  844. }
  845. var protocolByInbound map[int]string
  846. if params.Protocol != "" {
  847. inbounds, err := inboundSvc.GetAllInbounds()
  848. if err == nil {
  849. protocolByInbound = make(map[int]string, len(inbounds))
  850. for _, ib := range inbounds {
  851. protocolByInbound[ib.Id] = string(ib.Protocol)
  852. }
  853. }
  854. }
  855. onlines := inboundSvc.GetOnlineClients()
  856. onlineSet := make(map[string]struct{}, len(onlines))
  857. for _, e := range onlines {
  858. onlineSet[e] = struct{}{}
  859. }
  860. var expireDiffMs, trafficDiffBytes int64
  861. if settingSvc != nil {
  862. if v, err := settingSvc.GetExpireDiff(); err == nil {
  863. expireDiffMs = int64(v) * 86400000
  864. }
  865. if v, err := settingSvc.GetTrafficDiff(); err == nil {
  866. trafficDiffBytes = int64(v) * 1073741824
  867. }
  868. }
  869. nowMs := time.Now().UnixMilli()
  870. summary := buildClientsSummary(all, onlineSet, nowMs, expireDiffMs, trafficDiffBytes)
  871. needle := strings.ToLower(strings.TrimSpace(params.Search))
  872. filtered := make([]ClientWithAttachments, 0, len(all))
  873. for _, c := range all {
  874. if needle != "" && !clientMatchesSearch(c, needle) {
  875. continue
  876. }
  877. if params.Protocol != "" && !clientMatchesProtocol(c, params.Protocol, protocolByInbound) {
  878. continue
  879. }
  880. if params.Inbound > 0 && !clientMatchesInbound(c, params.Inbound) {
  881. continue
  882. }
  883. if params.Filter != "" && !clientMatchesBucket(c, params.Filter, onlineSet, nowMs, expireDiffMs, trafficDiffBytes) {
  884. continue
  885. }
  886. filtered = append(filtered, c)
  887. }
  888. sortClients(filtered, params.Sort, params.Order)
  889. filteredCount := len(filtered)
  890. start := (page - 1) * pageSize
  891. end := start + pageSize
  892. if start > filteredCount {
  893. start = filteredCount
  894. }
  895. if end > filteredCount {
  896. end = filteredCount
  897. }
  898. pageRows := filtered[start:end]
  899. items := make([]ClientSlim, 0, len(pageRows))
  900. for _, c := range pageRows {
  901. items = append(items, toClientSlim(c))
  902. }
  903. return &ClientPageResponse{
  904. Items: items,
  905. Total: total,
  906. Filtered: filteredCount,
  907. Page: page,
  908. PageSize: pageSize,
  909. Summary: summary,
  910. }, nil
  911. }
  912. func buildClientsSummary(all []ClientWithAttachments, onlineSet map[string]struct{}, nowMs, expireDiffMs, trafficDiffBytes int64) ClientsSummary {
  913. s := ClientsSummary{
  914. Total: len(all),
  915. Online: []string{},
  916. Depleted: []string{},
  917. Expiring: []string{},
  918. Deactive: []string{},
  919. }
  920. for _, c := range all {
  921. used := int64(0)
  922. if c.Traffic != nil {
  923. used = c.Traffic.Up + c.Traffic.Down
  924. }
  925. exhausted := c.TotalGB > 0 && used >= c.TotalGB
  926. expired := c.ExpiryTime > 0 && c.ExpiryTime <= nowMs
  927. if c.Enable {
  928. if _, ok := onlineSet[c.Email]; ok {
  929. s.Online = append(s.Online, c.Email)
  930. }
  931. }
  932. if exhausted || expired {
  933. s.Depleted = append(s.Depleted, c.Email)
  934. continue
  935. }
  936. if !c.Enable {
  937. s.Deactive = append(s.Deactive, c.Email)
  938. continue
  939. }
  940. nearExpiry := c.ExpiryTime > 0 && c.ExpiryTime-nowMs < expireDiffMs
  941. nearLimit := c.TotalGB > 0 && c.TotalGB-used < trafficDiffBytes
  942. if nearExpiry || nearLimit {
  943. s.Expiring = append(s.Expiring, c.Email)
  944. } else {
  945. s.Active++
  946. }
  947. }
  948. return s
  949. }
  950. func toClientSlim(c ClientWithAttachments) ClientSlim {
  951. return ClientSlim{
  952. Email: c.Email,
  953. SubID: c.SubID,
  954. Enable: c.Enable,
  955. TotalGB: c.TotalGB,
  956. ExpiryTime: c.ExpiryTime,
  957. LimitIP: c.LimitIP,
  958. Reset: c.Reset,
  959. Comment: c.Comment,
  960. InboundIds: c.InboundIds,
  961. Traffic: c.Traffic,
  962. CreatedAt: c.CreatedAt,
  963. UpdatedAt: c.UpdatedAt,
  964. }
  965. }
  966. func clientMatchesSearch(c ClientWithAttachments, needle string) bool {
  967. if needle == "" {
  968. return true
  969. }
  970. if strings.Contains(strings.ToLower(c.Email), needle) {
  971. return true
  972. }
  973. if strings.Contains(strings.ToLower(c.SubID), needle) {
  974. return true
  975. }
  976. if strings.Contains(strings.ToLower(c.Comment), needle) {
  977. return true
  978. }
  979. return false
  980. }
  981. func clientMatchesProtocol(c ClientWithAttachments, protocol string, byInbound map[int]string) bool {
  982. if protocol == "" {
  983. return true
  984. }
  985. for _, id := range c.InboundIds {
  986. if byInbound[id] == protocol {
  987. return true
  988. }
  989. }
  990. return false
  991. }
  992. func clientMatchesInbound(c ClientWithAttachments, inboundId int) bool {
  993. if inboundId <= 0 {
  994. return true
  995. }
  996. return slices.Contains(c.InboundIds, inboundId)
  997. }
  998. func clientMatchesBucket(c ClientWithAttachments, bucket string, onlineSet map[string]struct{}, nowMs, expireDiffMs, trafficDiffBytes int64) bool {
  999. if bucket == "" {
  1000. return true
  1001. }
  1002. used := int64(0)
  1003. if c.Traffic != nil {
  1004. used = c.Traffic.Up + c.Traffic.Down
  1005. }
  1006. exhausted := c.TotalGB > 0 && used >= c.TotalGB
  1007. expired := c.ExpiryTime > 0 && c.ExpiryTime <= nowMs
  1008. switch bucket {
  1009. case "online":
  1010. if onlineSet == nil {
  1011. return false
  1012. }
  1013. _, ok := onlineSet[c.Email]
  1014. return ok && c.Enable
  1015. case "depleted":
  1016. return exhausted || expired
  1017. case "deactive":
  1018. return !c.Enable
  1019. case "active":
  1020. return c.Enable && !exhausted && !expired
  1021. case "expiring":
  1022. if !c.Enable || exhausted || expired {
  1023. return false
  1024. }
  1025. nearExpiry := c.ExpiryTime > 0 && c.ExpiryTime-nowMs < expireDiffMs
  1026. nearLimit := c.TotalGB > 0 && c.TotalGB-used < trafficDiffBytes
  1027. return nearExpiry || nearLimit
  1028. }
  1029. return true
  1030. }
  1031. func sortClients(rows []ClientWithAttachments, sortKey, order string) {
  1032. if sortKey == "" {
  1033. return
  1034. }
  1035. desc := order == "descend"
  1036. less := func(i, j int) bool {
  1037. a, b := rows[i], rows[j]
  1038. switch sortKey {
  1039. case "enable":
  1040. if a.Enable == b.Enable {
  1041. return false
  1042. }
  1043. return !a.Enable && b.Enable
  1044. case "email":
  1045. return strings.ToLower(a.Email) < strings.ToLower(b.Email)
  1046. case "inboundIds":
  1047. return len(a.InboundIds) < len(b.InboundIds)
  1048. case "traffic":
  1049. ua := int64(0)
  1050. if a.Traffic != nil {
  1051. ua = a.Traffic.Up + a.Traffic.Down
  1052. }
  1053. ub := int64(0)
  1054. if b.Traffic != nil {
  1055. ub = b.Traffic.Up + b.Traffic.Down
  1056. }
  1057. return ua < ub
  1058. case "remaining":
  1059. ra := int64(1<<62 - 1)
  1060. if a.TotalGB > 0 {
  1061. used := int64(0)
  1062. if a.Traffic != nil {
  1063. used = a.Traffic.Up + a.Traffic.Down
  1064. }
  1065. ra = a.TotalGB - used
  1066. }
  1067. rb := int64(1<<62 - 1)
  1068. if b.TotalGB > 0 {
  1069. used := int64(0)
  1070. if b.Traffic != nil {
  1071. used = b.Traffic.Up + b.Traffic.Down
  1072. }
  1073. rb = b.TotalGB - used
  1074. }
  1075. return ra < rb
  1076. case "expiryTime":
  1077. ea := int64(1<<62 - 1)
  1078. if a.ExpiryTime > 0 {
  1079. ea = a.ExpiryTime
  1080. }
  1081. eb := int64(1<<62 - 1)
  1082. if b.ExpiryTime > 0 {
  1083. eb = b.ExpiryTime
  1084. }
  1085. return ea < eb
  1086. }
  1087. return false
  1088. }
  1089. sort.SliceStable(rows, func(i, j int) bool {
  1090. if desc {
  1091. return less(j, i)
  1092. }
  1093. return less(i, j)
  1094. })
  1095. }
  1096. // BulkAdjustResult is returned by BulkAdjust to report how many clients were
  1097. // successfully updated and which were skipped (typically because the field
  1098. // being adjusted was unlimited for that client) or failed.
  1099. type BulkAdjustResult struct {
  1100. Adjusted int `json:"adjusted"`
  1101. Skipped []BulkAdjustReport `json:"skipped,omitempty"`
  1102. }
  1103. type BulkAdjustReport struct {
  1104. Email string `json:"email"`
  1105. Reason string `json:"reason"`
  1106. }
  1107. type bulkAdjustEntry struct {
  1108. record *model.ClientRecord
  1109. applyExpiry bool
  1110. newExpiry int64
  1111. applyTotal bool
  1112. newTotal int64
  1113. }
  1114. // BulkAdjust shifts ExpiryTime by addDays (days) and TotalGB by addBytes
  1115. // for every email in the list. Clients whose corresponding field is
  1116. // unlimited (0) are skipped — bulk extend should not accidentally
  1117. // limit an unlimited client. addDays and addBytes may be negative.
  1118. //
  1119. // Like BulkDelete, the work is grouped by inbound so each inbound's
  1120. // settings JSON is parsed and written exactly once regardless of how
  1121. // many target emails it contains.
  1122. func (s *ClientService) BulkAdjust(inboundSvc *InboundService, emails []string, addDays int, addBytes int64) (BulkAdjustResult, bool, error) {
  1123. result := BulkAdjustResult{}
  1124. if len(emails) == 0 {
  1125. return result, false, nil
  1126. }
  1127. if addDays == 0 && addBytes == 0 {
  1128. return result, false, common.NewError("no adjustment specified")
  1129. }
  1130. addExpiryMs := int64(addDays) * 24 * 60 * 60 * 1000
  1131. seen := map[string]struct{}{}
  1132. cleanEmails := make([]string, 0, len(emails))
  1133. for _, e := range emails {
  1134. e = strings.TrimSpace(e)
  1135. if e == "" {
  1136. continue
  1137. }
  1138. if _, ok := seen[e]; ok {
  1139. continue
  1140. }
  1141. seen[e] = struct{}{}
  1142. cleanEmails = append(cleanEmails, e)
  1143. }
  1144. if len(cleanEmails) == 0 {
  1145. return result, false, nil
  1146. }
  1147. db := database.GetDB()
  1148. var records []model.ClientRecord
  1149. if err := db.Where("email IN ?", cleanEmails).Find(&records).Error; err != nil {
  1150. return result, false, err
  1151. }
  1152. recordsByEmail := make(map[string]*model.ClientRecord, len(records))
  1153. for i := range records {
  1154. recordsByEmail[records[i].Email] = &records[i]
  1155. }
  1156. skippedReasons := map[string]string{}
  1157. for _, email := range cleanEmails {
  1158. if _, ok := recordsByEmail[email]; !ok {
  1159. skippedReasons[email] = "client not found"
  1160. }
  1161. }
  1162. plan := map[string]*bulkAdjustEntry{}
  1163. for email, rec := range recordsByEmail {
  1164. entry := &bulkAdjustEntry{record: rec}
  1165. if addDays != 0 {
  1166. switch {
  1167. case rec.ExpiryTime == 0:
  1168. if _, exists := skippedReasons[email]; !exists {
  1169. skippedReasons[email] = "unlimited expiry"
  1170. }
  1171. case rec.ExpiryTime > 0:
  1172. next := rec.ExpiryTime + addExpiryMs
  1173. if next <= 0 {
  1174. if _, exists := skippedReasons[email]; !exists {
  1175. skippedReasons[email] = "reduction exceeds remaining time"
  1176. }
  1177. } else {
  1178. entry.applyExpiry = true
  1179. entry.newExpiry = next
  1180. }
  1181. default:
  1182. next := rec.ExpiryTime - addExpiryMs
  1183. if next >= 0 {
  1184. if _, exists := skippedReasons[email]; !exists {
  1185. skippedReasons[email] = "reduction exceeds delay window"
  1186. }
  1187. } else {
  1188. entry.applyExpiry = true
  1189. entry.newExpiry = next
  1190. }
  1191. }
  1192. }
  1193. if addBytes != 0 {
  1194. if rec.TotalGB == 0 {
  1195. if _, exists := skippedReasons[email]; !exists {
  1196. skippedReasons[email] = "unlimited traffic"
  1197. }
  1198. } else {
  1199. next := max(rec.TotalGB+addBytes, 0)
  1200. entry.applyTotal = true
  1201. entry.newTotal = next
  1202. }
  1203. }
  1204. if entry.applyExpiry || entry.applyTotal {
  1205. plan[email] = entry
  1206. }
  1207. }
  1208. if len(plan) == 0 {
  1209. for email, reason := range skippedReasons {
  1210. result.Skipped = append(result.Skipped, BulkAdjustReport{Email: email, Reason: reason})
  1211. }
  1212. return result, false, nil
  1213. }
  1214. plannedIds := make([]int, 0, len(plan))
  1215. recordIdToEmail := make(map[int]string, len(plan))
  1216. for email, entry := range plan {
  1217. plannedIds = append(plannedIds, entry.record.Id)
  1218. recordIdToEmail[entry.record.Id] = email
  1219. }
  1220. var mappings []model.ClientInbound
  1221. if err := db.Where("client_id IN ?", plannedIds).Find(&mappings).Error; err != nil {
  1222. return result, false, err
  1223. }
  1224. emailsByInbound := map[int][]string{}
  1225. for _, m := range mappings {
  1226. email, ok := recordIdToEmail[m.ClientId]
  1227. if !ok {
  1228. continue
  1229. }
  1230. emailsByInbound[m.InboundId] = append(emailsByInbound[m.InboundId], email)
  1231. }
  1232. needRestart := false
  1233. for inboundId, ibEmails := range emailsByInbound {
  1234. ibRes := s.bulkAdjustInboundClients(inboundSvc, inboundId, ibEmails, plan)
  1235. if ibRes.needRestart {
  1236. needRestart = true
  1237. }
  1238. for email, reason := range ibRes.perEmailSkipped {
  1239. if _, already := skippedReasons[email]; !already {
  1240. skippedReasons[email] = reason
  1241. }
  1242. }
  1243. }
  1244. for email, entry := range plan {
  1245. if _, skipped := skippedReasons[email]; skipped {
  1246. continue
  1247. }
  1248. updates := map[string]any{}
  1249. if entry.applyExpiry {
  1250. updates["expiry_time"] = entry.newExpiry
  1251. }
  1252. if entry.applyTotal {
  1253. updates["total"] = entry.newTotal
  1254. }
  1255. if len(updates) == 0 {
  1256. continue
  1257. }
  1258. if err := db.Model(xray.ClientTraffic{}).Where("email = ?", email).Updates(updates).Error; err != nil {
  1259. if _, already := skippedReasons[email]; !already {
  1260. skippedReasons[email] = err.Error()
  1261. }
  1262. continue
  1263. }
  1264. result.Adjusted++
  1265. }
  1266. for email, reason := range skippedReasons {
  1267. result.Skipped = append(result.Skipped, BulkAdjustReport{Email: email, Reason: reason})
  1268. }
  1269. return result, needRestart, nil
  1270. }
  1271. type bulkInboundAdjustResult struct {
  1272. perEmailSkipped map[string]string
  1273. needRestart bool
  1274. }
  1275. // bulkAdjustInboundClients applies expiry/total deltas to multiple clients
  1276. // inside a single inbound's settings JSON. The xray runtime is updated
  1277. // only for remote-node inbounds; local nodes do not need a notification
  1278. // because the AddUser payload does not include totalGB/expiryTime —
  1279. // changing those fields is identity-preserving and the panel's traffic
  1280. // enforcement loop picks up the new limits from ClientTraffic directly.
  1281. func (s *ClientService) bulkAdjustInboundClients(
  1282. inboundSvc *InboundService,
  1283. inboundId int,
  1284. emails []string,
  1285. plan map[string]*bulkAdjustEntry,
  1286. ) bulkInboundAdjustResult {
  1287. res := bulkInboundAdjustResult{perEmailSkipped: map[string]string{}}
  1288. defer lockInbound(inboundId).Unlock()
  1289. oldInbound, err := inboundSvc.GetInbound(inboundId)
  1290. if err != nil {
  1291. logger.Error("Load Old Data Error")
  1292. for _, e := range emails {
  1293. res.perEmailSkipped[e] = err.Error()
  1294. }
  1295. return res
  1296. }
  1297. var settings map[string]any
  1298. if err := json.Unmarshal([]byte(oldInbound.Settings), &settings); err != nil {
  1299. for _, e := range emails {
  1300. res.perEmailSkipped[e] = err.Error()
  1301. }
  1302. return res
  1303. }
  1304. clientKey := "id"
  1305. switch oldInbound.Protocol {
  1306. case model.Trojan:
  1307. clientKey = "password"
  1308. case model.Shadowsocks:
  1309. clientKey = "email"
  1310. case model.Hysteria:
  1311. clientKey = "auth"
  1312. }
  1313. keyToEmail := make(map[string]string, len(emails))
  1314. for _, email := range emails {
  1315. entry := plan[email]
  1316. if entry == nil {
  1317. res.perEmailSkipped[email] = "client not found"
  1318. continue
  1319. }
  1320. key := clientKeyForProtocol(oldInbound.Protocol, entry.record)
  1321. if key == "" {
  1322. res.perEmailSkipped[email] = "missing client key for protocol"
  1323. continue
  1324. }
  1325. keyToEmail[key] = email
  1326. }
  1327. interfaceClients, _ := settings["clients"].([]any)
  1328. foundEmails := map[string]bool{}
  1329. nowMs := time.Now().Unix() * 1000
  1330. for i, client := range interfaceClients {
  1331. c, ok := client.(map[string]any)
  1332. if !ok {
  1333. continue
  1334. }
  1335. cKey, _ := c[clientKey].(string)
  1336. targetEmail, found := keyToEmail[cKey]
  1337. if !found {
  1338. continue
  1339. }
  1340. entry := plan[targetEmail]
  1341. if entry.applyExpiry {
  1342. c["expiryTime"] = entry.newExpiry
  1343. }
  1344. if entry.applyTotal {
  1345. c["totalGB"] = entry.newTotal
  1346. }
  1347. c["updated_at"] = nowMs
  1348. interfaceClients[i] = c
  1349. foundEmails[targetEmail] = true
  1350. }
  1351. for _, email := range keyToEmail {
  1352. if !foundEmails[email] {
  1353. res.perEmailSkipped[email] = "Client Not Found In Inbound"
  1354. }
  1355. }
  1356. if len(foundEmails) == 0 {
  1357. return res
  1358. }
  1359. settings["clients"] = interfaceClients
  1360. newSettings, err := json.MarshalIndent(settings, "", " ")
  1361. if err != nil {
  1362. for email := range foundEmails {
  1363. res.perEmailSkipped[email] = err.Error()
  1364. }
  1365. return res
  1366. }
  1367. oldInbound.Settings = string(newSettings)
  1368. if oldInbound.NodeID != nil {
  1369. rt, rterr := inboundSvc.runtimeFor(oldInbound)
  1370. if rterr != nil {
  1371. for email := range foundEmails {
  1372. res.perEmailSkipped[email] = rterr.Error()
  1373. delete(foundEmails, email)
  1374. }
  1375. } else {
  1376. for email := range foundEmails {
  1377. entry := plan[email]
  1378. updated := *entry.record.ToClient()
  1379. if entry.applyExpiry {
  1380. updated.ExpiryTime = entry.newExpiry
  1381. }
  1382. if entry.applyTotal {
  1383. updated.TotalGB = entry.newTotal
  1384. }
  1385. updated.UpdatedAt = nowMs
  1386. if err1 := rt.UpdateUser(context.Background(), oldInbound, email, updated); err1 != nil {
  1387. res.perEmailSkipped[email] = err1.Error()
  1388. delete(foundEmails, email)
  1389. }
  1390. }
  1391. }
  1392. }
  1393. db := database.GetDB()
  1394. if err := db.Save(oldInbound).Error; err != nil {
  1395. for email := range foundEmails {
  1396. if _, skip := res.perEmailSkipped[email]; !skip {
  1397. res.perEmailSkipped[email] = err.Error()
  1398. }
  1399. }
  1400. return res
  1401. }
  1402. finalClients, gcErr := inboundSvc.GetClients(oldInbound)
  1403. if gcErr == nil {
  1404. if syncErr := s.SyncInbound(db, inboundId, finalClients); syncErr != nil {
  1405. logger.Warning("bulkAdjust SyncInbound:", syncErr)
  1406. }
  1407. }
  1408. return res
  1409. }
  1410. // BulkDeleteResult mirrors BulkAdjustResult: total deleted plus per-email
  1411. // skip reasons when an email could not be processed.
  1412. type BulkDeleteResult struct {
  1413. Deleted int `json:"deleted"`
  1414. Skipped []BulkDeleteReport `json:"skipped,omitempty"`
  1415. }
  1416. type BulkDeleteReport struct {
  1417. Email string `json:"email"`
  1418. Reason string `json:"reason"`
  1419. }
  1420. // BulkDelete removes every client in the list in one optimized pass.
  1421. // Instead of running the full single-delete pipeline N times (which would
  1422. // re-read, re-parse, and re-write each inbound's settings JSON for every
  1423. // email), it groups emails by inbound and performs a single
  1424. // read-modify-write per inbound. Per-row DB cleanups are also batched with
  1425. // IN-clause queries at the end. Errors on a particular email are recorded
  1426. // in the Skipped list and processing continues for the rest.
  1427. func (s *ClientService) BulkDelete(inboundSvc *InboundService, emails []string, keepTraffic bool) (BulkDeleteResult, bool, error) {
  1428. result := BulkDeleteResult{}
  1429. seen := map[string]struct{}{}
  1430. cleanEmails := make([]string, 0, len(emails))
  1431. for _, e := range emails {
  1432. e = strings.TrimSpace(e)
  1433. if e == "" {
  1434. continue
  1435. }
  1436. if _, ok := seen[e]; ok {
  1437. continue
  1438. }
  1439. seen[e] = struct{}{}
  1440. cleanEmails = append(cleanEmails, e)
  1441. }
  1442. if len(cleanEmails) == 0 {
  1443. return result, false, nil
  1444. }
  1445. db := database.GetDB()
  1446. var records []model.ClientRecord
  1447. if err := db.Where("email IN ?", cleanEmails).Find(&records).Error; err != nil {
  1448. return result, false, err
  1449. }
  1450. recordsByEmail := make(map[string]*model.ClientRecord, len(records))
  1451. for i := range records {
  1452. recordsByEmail[records[i].Email] = &records[i]
  1453. tombstoneClientEmail(records[i].Email)
  1454. }
  1455. skippedReasons := map[string]string{}
  1456. for _, email := range cleanEmails {
  1457. if _, ok := recordsByEmail[email]; !ok {
  1458. skippedReasons[email] = "client not found"
  1459. }
  1460. }
  1461. clientIds := make([]int, 0, len(recordsByEmail))
  1462. recordIdToEmail := make(map[int]string, len(recordsByEmail))
  1463. for _, r := range recordsByEmail {
  1464. clientIds = append(clientIds, r.Id)
  1465. recordIdToEmail[r.Id] = r.Email
  1466. }
  1467. emailsByInbound := map[int][]string{}
  1468. if len(clientIds) > 0 {
  1469. var mappings []model.ClientInbound
  1470. if err := db.Where("client_id IN ?", clientIds).Find(&mappings).Error; err != nil {
  1471. return result, false, err
  1472. }
  1473. for _, m := range mappings {
  1474. email, ok := recordIdToEmail[m.ClientId]
  1475. if !ok {
  1476. continue
  1477. }
  1478. emailsByInbound[m.InboundId] = append(emailsByInbound[m.InboundId], email)
  1479. }
  1480. }
  1481. needRestart := false
  1482. for inboundId, ibEmails := range emailsByInbound {
  1483. ibResult := s.bulkDelInboundClients(inboundSvc, inboundId, ibEmails, recordsByEmail)
  1484. if ibResult.needRestart {
  1485. needRestart = true
  1486. }
  1487. for email, reason := range ibResult.perEmailSkipped {
  1488. if _, already := skippedReasons[email]; !already {
  1489. skippedReasons[email] = reason
  1490. }
  1491. }
  1492. }
  1493. successEmails := make([]string, 0, len(recordsByEmail))
  1494. successIds := make([]int, 0, len(recordsByEmail))
  1495. for email, rec := range recordsByEmail {
  1496. if _, skipped := skippedReasons[email]; skipped {
  1497. continue
  1498. }
  1499. successEmails = append(successEmails, email)
  1500. successIds = append(successIds, rec.Id)
  1501. }
  1502. if len(successIds) > 0 {
  1503. if err := db.Where("client_id IN ?", successIds).Delete(&model.ClientInbound{}).Error; err != nil {
  1504. return result, needRestart, err
  1505. }
  1506. if !keepTraffic && len(successEmails) > 0 {
  1507. if err := db.Where("email IN ?", successEmails).Delete(&xray.ClientTraffic{}).Error; err != nil {
  1508. return result, needRestart, err
  1509. }
  1510. if err := db.Where("client_email IN ?", successEmails).Delete(&model.InboundClientIps{}).Error; err != nil {
  1511. return result, needRestart, err
  1512. }
  1513. }
  1514. if err := db.Where("id IN ?", successIds).Delete(&model.ClientRecord{}).Error; err != nil {
  1515. return result, needRestart, err
  1516. }
  1517. }
  1518. result.Deleted = len(successEmails)
  1519. for email, reason := range skippedReasons {
  1520. result.Skipped = append(result.Skipped, BulkDeleteReport{Email: email, Reason: reason})
  1521. }
  1522. return result, needRestart, nil
  1523. }
  1524. type bulkInboundDeleteResult struct {
  1525. perEmailSkipped map[string]string
  1526. needRestart bool
  1527. }
  1528. // bulkDelInboundClients removes multiple clients from a single inbound's
  1529. // settings JSON in one read-modify-write cycle, runs the xray runtime
  1530. // RemoveUser/DeleteUser calls, and persists the inbound. The returned map
  1531. // holds per-email failure reasons; emails not present in the map are
  1532. // considered successful for this inbound.
  1533. func (s *ClientService) bulkDelInboundClients(
  1534. inboundSvc *InboundService,
  1535. inboundId int,
  1536. emails []string,
  1537. records map[string]*model.ClientRecord,
  1538. ) bulkInboundDeleteResult {
  1539. res := bulkInboundDeleteResult{perEmailSkipped: map[string]string{}}
  1540. defer lockInbound(inboundId).Unlock()
  1541. oldInbound, err := inboundSvc.GetInbound(inboundId)
  1542. if err != nil {
  1543. logger.Error("Load Old Data Error")
  1544. for _, e := range emails {
  1545. res.perEmailSkipped[e] = err.Error()
  1546. }
  1547. return res
  1548. }
  1549. var settings map[string]any
  1550. if err := json.Unmarshal([]byte(oldInbound.Settings), &settings); err != nil {
  1551. for _, e := range emails {
  1552. res.perEmailSkipped[e] = err.Error()
  1553. }
  1554. return res
  1555. }
  1556. clientKey := "id"
  1557. switch oldInbound.Protocol {
  1558. case model.Trojan:
  1559. clientKey = "password"
  1560. case model.Shadowsocks:
  1561. clientKey = "email"
  1562. case model.Hysteria:
  1563. clientKey = "auth"
  1564. }
  1565. keyToEmail := make(map[string]string, len(emails))
  1566. for _, email := range emails {
  1567. rec := records[email]
  1568. if rec == nil {
  1569. res.perEmailSkipped[email] = "client not found"
  1570. continue
  1571. }
  1572. key := clientKeyForProtocol(oldInbound.Protocol, rec)
  1573. if key == "" {
  1574. res.perEmailSkipped[email] = "missing client key for protocol"
  1575. continue
  1576. }
  1577. keyToEmail[key] = email
  1578. }
  1579. interfaceClients, _ := settings["clients"].([]any)
  1580. newClients := make([]any, 0, len(interfaceClients))
  1581. foundEmails := map[string]bool{}
  1582. enableByEmail := map[string]bool{}
  1583. for _, client := range interfaceClients {
  1584. c, ok := client.(map[string]any)
  1585. if !ok {
  1586. newClients = append(newClients, client)
  1587. continue
  1588. }
  1589. cKey, _ := c[clientKey].(string)
  1590. if targetEmail, found := keyToEmail[cKey]; found {
  1591. foundEmails[targetEmail] = true
  1592. if em, _ := c["email"].(string); em != "" {
  1593. en, _ := c["enable"].(bool)
  1594. enableByEmail[em] = en
  1595. }
  1596. continue
  1597. }
  1598. newClients = append(newClients, client)
  1599. }
  1600. for _, email := range keyToEmail {
  1601. if !foundEmails[email] {
  1602. res.perEmailSkipped[email] = "Client Not Found In Inbound"
  1603. }
  1604. }
  1605. db := database.GetDB()
  1606. newClients = compactOrphans(db, newClients)
  1607. if newClients == nil {
  1608. newClients = []any{}
  1609. }
  1610. settings["clients"] = newClients
  1611. newSettings, err := json.MarshalIndent(settings, "", " ")
  1612. if err != nil {
  1613. for email := range foundEmails {
  1614. if _, skip := res.perEmailSkipped[email]; !skip {
  1615. res.perEmailSkipped[email] = err.Error()
  1616. }
  1617. }
  1618. return res
  1619. }
  1620. oldInbound.Settings = string(newSettings)
  1621. foundList := make([]string, 0, len(foundEmails))
  1622. for email := range foundEmails {
  1623. foundList = append(foundList, email)
  1624. }
  1625. notDepletedByEmail := map[string]bool{}
  1626. if len(foundList) > 0 {
  1627. type trafficRow struct {
  1628. Email string
  1629. Enable bool
  1630. }
  1631. var rows []trafficRow
  1632. if err := db.Model(xray.ClientTraffic{}).
  1633. Where("email IN ?", foundList).
  1634. Select("email, enable").
  1635. Scan(&rows).Error; err == nil {
  1636. for _, r := range rows {
  1637. notDepletedByEmail[r.Email] = r.Enable
  1638. }
  1639. }
  1640. }
  1641. for email := range foundEmails {
  1642. shared, sharedErr := inboundSvc.emailUsedByOtherInbounds(email, inboundId)
  1643. if sharedErr != nil {
  1644. res.perEmailSkipped[email] = sharedErr.Error()
  1645. delete(foundEmails, email)
  1646. continue
  1647. }
  1648. if shared {
  1649. continue
  1650. }
  1651. if delErr := inboundSvc.DelClientIPs(db, email); delErr != nil {
  1652. logger.Error("Error in delete client IPs")
  1653. res.perEmailSkipped[email] = delErr.Error()
  1654. delete(foundEmails, email)
  1655. continue
  1656. }
  1657. if delErr := inboundSvc.DelClientStat(db, email); delErr != nil {
  1658. logger.Error("Delete stats Data Error")
  1659. res.perEmailSkipped[email] = delErr.Error()
  1660. delete(foundEmails, email)
  1661. continue
  1662. }
  1663. }
  1664. if oldInbound.NodeID == nil {
  1665. rt, rterr := inboundSvc.runtimeFor(oldInbound)
  1666. if rterr != nil {
  1667. res.needRestart = true
  1668. } else {
  1669. for email := range foundEmails {
  1670. if !enableByEmail[email] || !notDepletedByEmail[email] {
  1671. continue
  1672. }
  1673. err1 := rt.RemoveUser(context.Background(), oldInbound, email)
  1674. if err1 == nil {
  1675. logger.Debug("Client deleted on", rt.Name(), ":", email)
  1676. } else if strings.Contains(err1.Error(), fmt.Sprintf("User %s not found.", email)) {
  1677. logger.Debug("User is already deleted. Nothing to do more...")
  1678. } else {
  1679. logger.Debug("Error in deleting client on", rt.Name(), ":", err1)
  1680. res.needRestart = true
  1681. }
  1682. }
  1683. }
  1684. } else {
  1685. rt, rterr := inboundSvc.runtimeFor(oldInbound)
  1686. if rterr != nil {
  1687. for email := range foundEmails {
  1688. res.perEmailSkipped[email] = rterr.Error()
  1689. delete(foundEmails, email)
  1690. }
  1691. } else {
  1692. for email := range foundEmails {
  1693. if err1 := rt.DeleteUser(context.Background(), oldInbound, email); err1 != nil {
  1694. res.perEmailSkipped[email] = err1.Error()
  1695. delete(foundEmails, email)
  1696. }
  1697. }
  1698. }
  1699. }
  1700. if err := db.Save(oldInbound).Error; err != nil {
  1701. for email := range foundEmails {
  1702. if _, skip := res.perEmailSkipped[email]; !skip {
  1703. res.perEmailSkipped[email] = err.Error()
  1704. }
  1705. }
  1706. return res
  1707. }
  1708. finalClients, err := inboundSvc.GetClients(oldInbound)
  1709. if err != nil {
  1710. return res
  1711. }
  1712. if err := s.SyncInbound(db, inboundId, finalClients); err != nil {
  1713. return res
  1714. }
  1715. return res
  1716. }
  1717. // BulkCreateResult mirrors BulkAdjustResult for the create flow.
  1718. type BulkCreateResult struct {
  1719. Created int `json:"created"`
  1720. Skipped []BulkCreateReport `json:"skipped,omitempty"`
  1721. }
  1722. type BulkCreateReport struct {
  1723. Email string `json:"email"`
  1724. Reason string `json:"reason"`
  1725. }
  1726. // BulkCreate iterates payloads sequentially. Each item is the same shape
  1727. // the single-create endpoint accepts, so callers can submit a heterogeneous
  1728. // list (different inboundIds, plans, etc.) in one round-trip.
  1729. func (s *ClientService) BulkCreate(inboundSvc *InboundService, payloads []ClientCreatePayload) (BulkCreateResult, bool, error) {
  1730. result := BulkCreateResult{}
  1731. needRestart := false
  1732. for i := range payloads {
  1733. p := payloads[i]
  1734. email := strings.TrimSpace(p.Client.Email)
  1735. nr, err := s.Create(inboundSvc, &p)
  1736. if err != nil {
  1737. if email == "" {
  1738. email = "(missing email)"
  1739. }
  1740. result.Skipped = append(result.Skipped, BulkCreateReport{Email: email, Reason: err.Error()})
  1741. continue
  1742. }
  1743. if nr {
  1744. needRestart = true
  1745. }
  1746. result.Created++
  1747. }
  1748. return result, needRestart, nil
  1749. }
  1750. func (s *ClientService) DelDepleted(inboundSvc *InboundService) (int, bool, error) {
  1751. db := database.GetDB()
  1752. now := time.Now().UnixMilli()
  1753. depletedClause := "reset = 0 and ((total > 0 and up + down >= total) or (expiry_time > 0 and expiry_time <= ?))"
  1754. var rows []xray.ClientTraffic
  1755. if err := db.Where(depletedClause, now).Find(&rows).Error; err != nil {
  1756. return 0, false, err
  1757. }
  1758. if len(rows) == 0 {
  1759. return 0, false, nil
  1760. }
  1761. emails := make(map[string]struct{}, len(rows))
  1762. for _, r := range rows {
  1763. if r.Email != "" {
  1764. emails[r.Email] = struct{}{}
  1765. }
  1766. }
  1767. needRestart := false
  1768. deleted := 0
  1769. for email := range emails {
  1770. var rec model.ClientRecord
  1771. if err := db.Where("email = ?", email).First(&rec).Error; err != nil {
  1772. if errors.Is(err, gorm.ErrRecordNotFound) {
  1773. continue
  1774. }
  1775. return deleted, needRestart, err
  1776. }
  1777. nr, err := s.Delete(inboundSvc, rec.Id, false)
  1778. if err != nil {
  1779. return deleted, needRestart, err
  1780. }
  1781. if nr {
  1782. needRestart = true
  1783. }
  1784. deleted++
  1785. }
  1786. return deleted, needRestart, nil
  1787. }
  1788. func (s *ClientService) ResetAllClientTraffics(inboundSvc *InboundService, id int) error {
  1789. return submitTrafficWrite(func() error {
  1790. return s.resetAllClientTrafficsLocked(id)
  1791. })
  1792. }
  1793. func (s *ClientService) resetAllClientTrafficsLocked(id int) error {
  1794. db := database.GetDB()
  1795. now := time.Now().Unix() * 1000
  1796. if err := db.Transaction(func(tx *gorm.DB) error {
  1797. whereText := "inbound_id "
  1798. if id == -1 {
  1799. whereText += " > ?"
  1800. } else {
  1801. whereText += " = ?"
  1802. }
  1803. result := tx.Model(xray.ClientTraffic{}).
  1804. Where(whereText, id).
  1805. Updates(map[string]any{"enable": true, "up": 0, "down": 0})
  1806. if result.Error != nil {
  1807. return result.Error
  1808. }
  1809. inboundWhereText := "id "
  1810. if id == -1 {
  1811. inboundWhereText += " > ?"
  1812. } else {
  1813. inboundWhereText += " = ?"
  1814. }
  1815. result = tx.Model(model.Inbound{}).
  1816. Where(inboundWhereText, id).
  1817. Update("last_traffic_reset_time", now)
  1818. return result.Error
  1819. }); err != nil {
  1820. return err
  1821. }
  1822. return nil
  1823. }
  1824. func (s *ClientService) ResetAllTraffics() (bool, error) {
  1825. res := database.GetDB().Model(&xray.ClientTraffic{}).
  1826. Where("1 = 1").
  1827. Updates(map[string]any{"up": 0, "down": 0})
  1828. if res.Error != nil {
  1829. return false, res.Error
  1830. }
  1831. return res.RowsAffected > 0, nil
  1832. }
  1833. func (s *ClientService) Detach(inboundSvc *InboundService, id int, inboundIds []int) (bool, error) {
  1834. existing, err := s.GetByID(id)
  1835. if err != nil {
  1836. return false, err
  1837. }
  1838. currentIds, err := s.GetInboundIdsForRecord(id)
  1839. if err != nil {
  1840. return false, err
  1841. }
  1842. have := make(map[int]struct{}, len(currentIds))
  1843. for _, x := range currentIds {
  1844. have[x] = struct{}{}
  1845. }
  1846. needRestart := false
  1847. for _, ibId := range inboundIds {
  1848. if _, attached := have[ibId]; !attached {
  1849. continue
  1850. }
  1851. inbound, getErr := inboundSvc.GetInbound(ibId)
  1852. if getErr != nil {
  1853. return needRestart, getErr
  1854. }
  1855. key := clientKeyForProtocol(inbound.Protocol, existing)
  1856. if key == "" {
  1857. continue
  1858. }
  1859. nr, delErr := s.DelInboundClient(inboundSvc, ibId, key)
  1860. if delErr != nil {
  1861. return needRestart, delErr
  1862. }
  1863. if nr {
  1864. needRestart = true
  1865. }
  1866. }
  1867. return needRestart, nil
  1868. }
  1869. func (s *ClientService) checkEmailsExistForClients(inboundSvc *InboundService, clients []model.Client) (string, error) {
  1870. emailSubIDs, err := inboundSvc.getAllEmailSubIDs()
  1871. if err != nil {
  1872. return "", err
  1873. }
  1874. seen := make(map[string]string, len(clients))
  1875. for _, client := range clients {
  1876. if client.Email == "" {
  1877. continue
  1878. }
  1879. key := strings.ToLower(client.Email)
  1880. if prev, ok := seen[key]; ok {
  1881. if prev != client.SubID || client.SubID == "" {
  1882. return client.Email, nil
  1883. }
  1884. continue
  1885. }
  1886. seen[key] = client.SubID
  1887. if existingSub, ok := emailSubIDs[key]; ok {
  1888. if client.SubID == "" || existingSub == "" || existingSub != client.SubID {
  1889. return client.Email, nil
  1890. }
  1891. }
  1892. }
  1893. return "", nil
  1894. }
  1895. func (s *ClientService) AddInboundClient(inboundSvc *InboundService, data *model.Inbound) (bool, error) {
  1896. defer lockInbound(data.Id).Unlock()
  1897. clients, err := inboundSvc.GetClients(data)
  1898. if err != nil {
  1899. return false, err
  1900. }
  1901. var settings map[string]any
  1902. err = json.Unmarshal([]byte(data.Settings), &settings)
  1903. if err != nil {
  1904. return false, err
  1905. }
  1906. interfaceClients := settings["clients"].([]any)
  1907. nowTs := time.Now().Unix() * 1000
  1908. for i := range interfaceClients {
  1909. if cm, ok := interfaceClients[i].(map[string]any); ok {
  1910. if _, ok2 := cm["created_at"]; !ok2 {
  1911. cm["created_at"] = nowTs
  1912. }
  1913. cm["updated_at"] = nowTs
  1914. interfaceClients[i] = cm
  1915. }
  1916. }
  1917. existEmail, err := s.checkEmailsExistForClients(inboundSvc, clients)
  1918. if err != nil {
  1919. return false, err
  1920. }
  1921. if existEmail != "" {
  1922. return false, common.NewError("Duplicate email:", existEmail)
  1923. }
  1924. oldInbound, err := inboundSvc.GetInbound(data.Id)
  1925. if err != nil {
  1926. return false, err
  1927. }
  1928. for _, client := range clients {
  1929. if strings.TrimSpace(client.Email) == "" {
  1930. return false, common.NewError("client email is required")
  1931. }
  1932. switch oldInbound.Protocol {
  1933. case "trojan":
  1934. if client.Password == "" {
  1935. return false, common.NewError("empty client ID")
  1936. }
  1937. case "shadowsocks":
  1938. if client.Email == "" {
  1939. return false, common.NewError("empty client ID")
  1940. }
  1941. case "hysteria":
  1942. if client.Auth == "" {
  1943. return false, common.NewError("empty client ID")
  1944. }
  1945. default:
  1946. if client.ID == "" {
  1947. return false, common.NewError("empty client ID")
  1948. }
  1949. }
  1950. }
  1951. var oldSettings map[string]any
  1952. err = json.Unmarshal([]byte(oldInbound.Settings), &oldSettings)
  1953. if err != nil {
  1954. return false, err
  1955. }
  1956. if oldInbound.Protocol == model.Shadowsocks {
  1957. applyShadowsocksClientMethod(interfaceClients, oldSettings)
  1958. }
  1959. oldClients := oldSettings["clients"].([]any)
  1960. oldClients = compactOrphans(database.GetDB(), oldClients)
  1961. oldClients = append(oldClients, interfaceClients...)
  1962. oldSettings["clients"] = oldClients
  1963. newSettings, err := json.MarshalIndent(oldSettings, "", " ")
  1964. if err != nil {
  1965. return false, err
  1966. }
  1967. oldInbound.Settings = string(newSettings)
  1968. db := database.GetDB()
  1969. tx := db.Begin()
  1970. defer func() {
  1971. if err != nil {
  1972. tx.Rollback()
  1973. } else {
  1974. tx.Commit()
  1975. }
  1976. }()
  1977. needRestart := false
  1978. rt, rterr := inboundSvc.runtimeFor(oldInbound)
  1979. if rterr != nil {
  1980. if oldInbound.NodeID != nil {
  1981. err = rterr
  1982. return false, err
  1983. }
  1984. needRestart = true
  1985. } else if oldInbound.NodeID == nil {
  1986. for _, client := range clients {
  1987. if len(client.Email) == 0 {
  1988. needRestart = true
  1989. continue
  1990. }
  1991. inboundSvc.AddClientStat(tx, data.Id, &client)
  1992. if !client.Enable {
  1993. continue
  1994. }
  1995. cipher := ""
  1996. if oldInbound.Protocol == "shadowsocks" {
  1997. cipher = oldSettings["method"].(string)
  1998. }
  1999. err1 := rt.AddUser(context.Background(), oldInbound, map[string]any{
  2000. "email": client.Email,
  2001. "id": client.ID,
  2002. "auth": client.Auth,
  2003. "security": client.Security,
  2004. "flow": client.Flow,
  2005. "password": client.Password,
  2006. "cipher": cipher,
  2007. })
  2008. if err1 == nil {
  2009. logger.Debug("Client added on", rt.Name(), ":", client.Email)
  2010. } else {
  2011. logger.Debug("Error in adding client on", rt.Name(), ":", err1)
  2012. needRestart = true
  2013. }
  2014. }
  2015. } else {
  2016. for _, client := range clients {
  2017. if len(client.Email) > 0 {
  2018. inboundSvc.AddClientStat(tx, data.Id, &client)
  2019. }
  2020. if err1 := rt.AddClient(context.Background(), oldInbound, client); err1 != nil {
  2021. err = err1
  2022. return false, err
  2023. }
  2024. }
  2025. }
  2026. if err = tx.Save(oldInbound).Error; err != nil {
  2027. return false, err
  2028. }
  2029. finalClients, gcErr := inboundSvc.GetClients(oldInbound)
  2030. if gcErr != nil {
  2031. err = gcErr
  2032. return false, err
  2033. }
  2034. if err = s.SyncInbound(tx, oldInbound.Id, finalClients); err != nil {
  2035. return false, err
  2036. }
  2037. return needRestart, nil
  2038. }
  2039. func (s *ClientService) UpdateInboundClient(inboundSvc *InboundService, data *model.Inbound, clientId string) (bool, error) {
  2040. defer lockInbound(data.Id).Unlock()
  2041. clients, err := inboundSvc.GetClients(data)
  2042. if err != nil {
  2043. return false, err
  2044. }
  2045. var settings map[string]any
  2046. err = json.Unmarshal([]byte(data.Settings), &settings)
  2047. if err != nil {
  2048. return false, err
  2049. }
  2050. interfaceClients := settings["clients"].([]any)
  2051. oldInbound, err := inboundSvc.GetInbound(data.Id)
  2052. if err != nil {
  2053. return false, err
  2054. }
  2055. oldClients, err := inboundSvc.GetClients(oldInbound)
  2056. if err != nil {
  2057. return false, err
  2058. }
  2059. oldEmail := ""
  2060. newClientId := ""
  2061. clientIndex := -1
  2062. for index, oldClient := range oldClients {
  2063. oldClientId := ""
  2064. switch oldInbound.Protocol {
  2065. case "trojan":
  2066. oldClientId = oldClient.Password
  2067. newClientId = clients[0].Password
  2068. case "shadowsocks":
  2069. oldClientId = oldClient.Email
  2070. newClientId = clients[0].Email
  2071. case "hysteria":
  2072. oldClientId = oldClient.Auth
  2073. newClientId = clients[0].Auth
  2074. default:
  2075. oldClientId = oldClient.ID
  2076. newClientId = clients[0].ID
  2077. }
  2078. if clientId == oldClientId {
  2079. oldEmail = oldClient.Email
  2080. clientIndex = index
  2081. break
  2082. }
  2083. }
  2084. if clientIndex == -1 {
  2085. var rec model.ClientRecord
  2086. var lookupErr error
  2087. switch oldInbound.Protocol {
  2088. case "trojan":
  2089. lookupErr = database.GetDB().Where("password = ?", clientId).First(&rec).Error
  2090. case "shadowsocks":
  2091. lookupErr = database.GetDB().Where("email = ?", clientId).First(&rec).Error
  2092. case "hysteria":
  2093. lookupErr = database.GetDB().Where("auth = ?", clientId).First(&rec).Error
  2094. default:
  2095. lookupErr = database.GetDB().Where("uuid = ?", clientId).First(&rec).Error
  2096. }
  2097. if lookupErr == nil && rec.Email != "" {
  2098. for index, oldClient := range oldClients {
  2099. if oldClient.Email == rec.Email {
  2100. oldEmail = oldClient.Email
  2101. clientIndex = index
  2102. break
  2103. }
  2104. }
  2105. }
  2106. }
  2107. if newClientId == "" || clientIndex == -1 {
  2108. return false, common.NewError("empty client ID")
  2109. }
  2110. if strings.TrimSpace(clients[0].Email) == "" {
  2111. return false, common.NewError("client email is required")
  2112. }
  2113. if clients[0].Email != oldEmail {
  2114. existEmail, err := s.checkEmailsExistForClients(inboundSvc, clients)
  2115. if err != nil {
  2116. return false, err
  2117. }
  2118. if existEmail != "" {
  2119. return false, common.NewError("Duplicate email:", existEmail)
  2120. }
  2121. }
  2122. var oldSettings map[string]any
  2123. err = json.Unmarshal([]byte(oldInbound.Settings), &oldSettings)
  2124. if err != nil {
  2125. return false, err
  2126. }
  2127. settingsClients := oldSettings["clients"].([]any)
  2128. var preservedCreated any
  2129. if clientIndex >= 0 && clientIndex < len(settingsClients) {
  2130. if oldMap, ok := settingsClients[clientIndex].(map[string]any); ok {
  2131. if v, ok2 := oldMap["created_at"]; ok2 {
  2132. preservedCreated = v
  2133. }
  2134. }
  2135. }
  2136. if len(interfaceClients) > 0 {
  2137. if newMap, ok := interfaceClients[0].(map[string]any); ok {
  2138. if preservedCreated == nil {
  2139. preservedCreated = time.Now().Unix() * 1000
  2140. }
  2141. newMap["created_at"] = preservedCreated
  2142. newMap["updated_at"] = time.Now().Unix() * 1000
  2143. interfaceClients[0] = newMap
  2144. }
  2145. }
  2146. if oldInbound.Protocol == model.Shadowsocks {
  2147. applyShadowsocksClientMethod(interfaceClients, oldSettings)
  2148. }
  2149. settingsClients[clientIndex] = interfaceClients[0]
  2150. oldSettings["clients"] = settingsClients
  2151. if oldInbound.Protocol == model.VLESS {
  2152. hasVisionFlow := false
  2153. for _, c := range settingsClients {
  2154. cm, ok := c.(map[string]any)
  2155. if !ok {
  2156. continue
  2157. }
  2158. if flow, _ := cm["flow"].(string); flow == "xtls-rprx-vision" {
  2159. hasVisionFlow = true
  2160. break
  2161. }
  2162. }
  2163. if !hasVisionFlow {
  2164. delete(oldSettings, "testseed")
  2165. }
  2166. }
  2167. newSettings, err := json.MarshalIndent(oldSettings, "", " ")
  2168. if err != nil {
  2169. return false, err
  2170. }
  2171. oldInbound.Settings = string(newSettings)
  2172. db := database.GetDB()
  2173. tx := db.Begin()
  2174. defer func() {
  2175. if err != nil {
  2176. tx.Rollback()
  2177. } else {
  2178. tx.Commit()
  2179. }
  2180. }()
  2181. if len(clients[0].Email) > 0 {
  2182. if len(oldEmail) > 0 {
  2183. emailUnchanged := strings.EqualFold(oldEmail, clients[0].Email)
  2184. targetExists := int64(0)
  2185. if !emailUnchanged {
  2186. if err = tx.Model(xray.ClientTraffic{}).Where("email = ?", clients[0].Email).Count(&targetExists).Error; err != nil {
  2187. return false, err
  2188. }
  2189. }
  2190. if emailUnchanged || targetExists == 0 {
  2191. err = inboundSvc.UpdateClientStat(tx, oldEmail, &clients[0])
  2192. if err != nil {
  2193. return false, err
  2194. }
  2195. err = inboundSvc.UpdateClientIPs(tx, oldEmail, clients[0].Email)
  2196. if err != nil {
  2197. return false, err
  2198. }
  2199. } else {
  2200. stillUsed, sErr := inboundSvc.emailUsedByOtherInbounds(oldEmail, data.Id)
  2201. if sErr != nil {
  2202. return false, sErr
  2203. }
  2204. if !stillUsed {
  2205. if err = inboundSvc.DelClientStat(tx, oldEmail); err != nil {
  2206. return false, err
  2207. }
  2208. if err = inboundSvc.DelClientIPs(tx, oldEmail); err != nil {
  2209. return false, err
  2210. }
  2211. }
  2212. if err = inboundSvc.UpdateClientStat(tx, clients[0].Email, &clients[0]); err != nil {
  2213. return false, err
  2214. }
  2215. }
  2216. } else {
  2217. inboundSvc.AddClientStat(tx, data.Id, &clients[0])
  2218. }
  2219. } else {
  2220. stillUsed, err := inboundSvc.emailUsedByOtherInbounds(oldEmail, data.Id)
  2221. if err != nil {
  2222. return false, err
  2223. }
  2224. if !stillUsed {
  2225. err = inboundSvc.DelClientStat(tx, oldEmail)
  2226. if err != nil {
  2227. return false, err
  2228. }
  2229. err = inboundSvc.DelClientIPs(tx, oldEmail)
  2230. if err != nil {
  2231. return false, err
  2232. }
  2233. }
  2234. }
  2235. needRestart := false
  2236. if len(oldEmail) > 0 {
  2237. rt, rterr := inboundSvc.runtimeFor(oldInbound)
  2238. if rterr != nil {
  2239. if oldInbound.NodeID != nil {
  2240. err = rterr
  2241. return false, err
  2242. }
  2243. needRestart = true
  2244. } else if oldInbound.NodeID == nil {
  2245. if oldClients[clientIndex].Enable {
  2246. err1 := rt.RemoveUser(context.Background(), oldInbound, oldEmail)
  2247. if err1 == nil {
  2248. logger.Debug("Old client deleted on", rt.Name(), ":", oldEmail)
  2249. } else if strings.Contains(err1.Error(), fmt.Sprintf("User %s not found.", oldEmail)) {
  2250. logger.Debug("User is already deleted. Nothing to do more...")
  2251. } else {
  2252. logger.Debug("Error in deleting client on", rt.Name(), ":", err1)
  2253. needRestart = true
  2254. }
  2255. }
  2256. if clients[0].Enable {
  2257. cipher := ""
  2258. if oldInbound.Protocol == "shadowsocks" {
  2259. cipher = oldSettings["method"].(string)
  2260. }
  2261. err1 := rt.AddUser(context.Background(), oldInbound, map[string]any{
  2262. "email": clients[0].Email,
  2263. "id": clients[0].ID,
  2264. "security": clients[0].Security,
  2265. "flow": clients[0].Flow,
  2266. "auth": clients[0].Auth,
  2267. "password": clients[0].Password,
  2268. "cipher": cipher,
  2269. })
  2270. if err1 == nil {
  2271. logger.Debug("Client edited on", rt.Name(), ":", clients[0].Email)
  2272. } else {
  2273. logger.Debug("Error in adding client on", rt.Name(), ":", err1)
  2274. needRestart = true
  2275. }
  2276. }
  2277. } else {
  2278. if err1 := rt.UpdateUser(context.Background(), oldInbound, oldEmail, clients[0]); err1 != nil {
  2279. err = err1
  2280. return false, err
  2281. }
  2282. }
  2283. } else {
  2284. logger.Debug("Client old email not found")
  2285. needRestart = true
  2286. }
  2287. if err = tx.Save(oldInbound).Error; err != nil {
  2288. return false, err
  2289. }
  2290. finalClients, gcErr := inboundSvc.GetClients(oldInbound)
  2291. if gcErr != nil {
  2292. err = gcErr
  2293. return false, err
  2294. }
  2295. if err = s.SyncInbound(tx, oldInbound.Id, finalClients); err != nil {
  2296. return false, err
  2297. }
  2298. return needRestart, nil
  2299. }
  2300. func (s *ClientService) DelInboundClient(inboundSvc *InboundService, inboundId int, clientId string) (bool, error) {
  2301. defer lockInbound(inboundId).Unlock()
  2302. oldInbound, err := inboundSvc.GetInbound(inboundId)
  2303. if err != nil {
  2304. logger.Error("Load Old Data Error")
  2305. return false, err
  2306. }
  2307. var settings map[string]any
  2308. err = json.Unmarshal([]byte(oldInbound.Settings), &settings)
  2309. if err != nil {
  2310. return false, err
  2311. }
  2312. email := ""
  2313. client_key := "id"
  2314. switch oldInbound.Protocol {
  2315. case "trojan":
  2316. client_key = "password"
  2317. case "shadowsocks":
  2318. client_key = "email"
  2319. case "hysteria":
  2320. client_key = "auth"
  2321. }
  2322. interfaceClients := settings["clients"].([]any)
  2323. var newClients []any
  2324. needApiDel := false
  2325. clientFound := false
  2326. for _, client := range interfaceClients {
  2327. c := client.(map[string]any)
  2328. c_id := c[client_key].(string)
  2329. if c_id == clientId {
  2330. clientFound = true
  2331. email, _ = c["email"].(string)
  2332. needApiDel, _ = c["enable"].(bool)
  2333. } else {
  2334. newClients = append(newClients, client)
  2335. }
  2336. }
  2337. if !clientFound {
  2338. return false, common.NewError("Client Not Found In Inbound For ID:", clientId)
  2339. }
  2340. db := database.GetDB()
  2341. newClients = compactOrphans(db, newClients)
  2342. if newClients == nil {
  2343. newClients = []any{}
  2344. }
  2345. settings["clients"] = newClients
  2346. newSettings, err := json.MarshalIndent(settings, "", " ")
  2347. if err != nil {
  2348. return false, err
  2349. }
  2350. oldInbound.Settings = string(newSettings)
  2351. emailShared, err := inboundSvc.emailUsedByOtherInbounds(email, inboundId)
  2352. if err != nil {
  2353. return false, err
  2354. }
  2355. if !emailShared {
  2356. err = inboundSvc.DelClientIPs(db, email)
  2357. if err != nil {
  2358. logger.Error("Error in delete client IPs")
  2359. return false, err
  2360. }
  2361. }
  2362. needRestart := false
  2363. if len(email) > 0 {
  2364. var enables []bool
  2365. err = db.Model(xray.ClientTraffic{}).Where("email = ?", email).Limit(1).Pluck("enable", &enables).Error
  2366. if err != nil {
  2367. logger.Error("Get stats error")
  2368. return false, err
  2369. }
  2370. notDepleted := len(enables) > 0 && enables[0]
  2371. if !emailShared {
  2372. err = inboundSvc.DelClientStat(db, email)
  2373. if err != nil {
  2374. logger.Error("Delete stats Data Error")
  2375. return false, err
  2376. }
  2377. }
  2378. if needApiDel && notDepleted && oldInbound.NodeID == nil {
  2379. rt, rterr := inboundSvc.runtimeFor(oldInbound)
  2380. if rterr != nil {
  2381. needRestart = true
  2382. } else {
  2383. err1 := rt.RemoveUser(context.Background(), oldInbound, email)
  2384. if err1 == nil {
  2385. logger.Debug("Client deleted on", rt.Name(), ":", email)
  2386. needRestart = false
  2387. } else if strings.Contains(err1.Error(), fmt.Sprintf("User %s not found.", email)) {
  2388. logger.Debug("User is already deleted. Nothing to do more...")
  2389. } else {
  2390. logger.Debug("Error in deleting client on", rt.Name(), ":", err1)
  2391. needRestart = true
  2392. }
  2393. }
  2394. }
  2395. }
  2396. if oldInbound.NodeID != nil && len(email) > 0 {
  2397. rt, rterr := inboundSvc.runtimeFor(oldInbound)
  2398. if rterr != nil {
  2399. return false, rterr
  2400. }
  2401. if err1 := rt.DeleteUser(context.Background(), oldInbound, email); err1 != nil {
  2402. return false, err1
  2403. }
  2404. }
  2405. if err := db.Save(oldInbound).Error; err != nil {
  2406. return false, err
  2407. }
  2408. finalClients, gcErr := inboundSvc.GetClients(oldInbound)
  2409. if gcErr != nil {
  2410. return false, gcErr
  2411. }
  2412. if err := s.SyncInbound(db, inboundId, finalClients); err != nil {
  2413. return false, err
  2414. }
  2415. return needRestart, nil
  2416. }
  2417. func (s *ClientService) DelInboundClientByEmail(inboundSvc *InboundService, inboundId int, email string) (bool, error) {
  2418. defer lockInbound(inboundId).Unlock()
  2419. oldInbound, err := inboundSvc.GetInbound(inboundId)
  2420. if err != nil {
  2421. logger.Error("Load Old Data Error")
  2422. return false, err
  2423. }
  2424. var settings map[string]any
  2425. if err := json.Unmarshal([]byte(oldInbound.Settings), &settings); err != nil {
  2426. return false, err
  2427. }
  2428. interfaceClients, ok := settings["clients"].([]any)
  2429. if !ok {
  2430. return false, common.NewError("invalid clients format in inbound settings")
  2431. }
  2432. var newClients []any
  2433. needApiDel := false
  2434. found := false
  2435. for _, client := range interfaceClients {
  2436. c, ok := client.(map[string]any)
  2437. if !ok {
  2438. continue
  2439. }
  2440. if cEmail, ok := c["email"].(string); ok && cEmail == email {
  2441. found = true
  2442. needApiDel, _ = c["enable"].(bool)
  2443. } else {
  2444. newClients = append(newClients, client)
  2445. }
  2446. }
  2447. if !found {
  2448. return false, common.NewError(fmt.Sprintf("client with email %s not found", email))
  2449. }
  2450. db := database.GetDB()
  2451. newClients = compactOrphans(db, newClients)
  2452. if newClients == nil {
  2453. newClients = []any{}
  2454. }
  2455. settings["clients"] = newClients
  2456. newSettings, err := json.MarshalIndent(settings, "", " ")
  2457. if err != nil {
  2458. return false, err
  2459. }
  2460. oldInbound.Settings = string(newSettings)
  2461. emailShared, err := inboundSvc.emailUsedByOtherInbounds(email, inboundId)
  2462. if err != nil {
  2463. return false, err
  2464. }
  2465. if !emailShared {
  2466. if err := inboundSvc.DelClientIPs(db, email); err != nil {
  2467. logger.Error("Error in delete client IPs")
  2468. return false, err
  2469. }
  2470. }
  2471. needRestart := false
  2472. if len(email) > 0 && !emailShared {
  2473. traffic, err := inboundSvc.GetClientTrafficByEmail(email)
  2474. if err != nil {
  2475. return false, err
  2476. }
  2477. if traffic != nil {
  2478. if err := inboundSvc.DelClientStat(db, email); err != nil {
  2479. logger.Error("Delete stats Data Error")
  2480. return false, err
  2481. }
  2482. }
  2483. if needApiDel {
  2484. rt, rterr := inboundSvc.runtimeFor(oldInbound)
  2485. if rterr != nil {
  2486. if oldInbound.NodeID != nil {
  2487. return false, rterr
  2488. }
  2489. needRestart = true
  2490. } else if oldInbound.NodeID == nil {
  2491. if err1 := rt.RemoveUser(context.Background(), oldInbound, email); err1 == nil {
  2492. logger.Debug("Client deleted on", rt.Name(), ":", email)
  2493. needRestart = false
  2494. } else if strings.Contains(err1.Error(), fmt.Sprintf("User %s not found.", email)) {
  2495. logger.Debug("User is already deleted. Nothing to do more...")
  2496. } else {
  2497. logger.Debug("Error in deleting client on", rt.Name(), ":", err1)
  2498. needRestart = true
  2499. }
  2500. } else {
  2501. if err1 := rt.DeleteUser(context.Background(), oldInbound, email); err1 != nil {
  2502. return false, err1
  2503. }
  2504. }
  2505. }
  2506. }
  2507. if err := db.Save(oldInbound).Error; err != nil {
  2508. return false, err
  2509. }
  2510. finalClients, gcErr := inboundSvc.GetClients(oldInbound)
  2511. if gcErr != nil {
  2512. return false, gcErr
  2513. }
  2514. if err := s.SyncInbound(db, inboundId, finalClients); err != nil {
  2515. return false, err
  2516. }
  2517. return needRestart, nil
  2518. }
  2519. func (s *ClientService) SetClientTelegramUserID(inboundSvc *InboundService, trafficId int, tgId int64) (bool, error) {
  2520. traffic, inbound, err := inboundSvc.GetClientInboundByTrafficID(trafficId)
  2521. if err != nil {
  2522. return false, err
  2523. }
  2524. if inbound == nil {
  2525. return false, common.NewError("Inbound Not Found For Traffic ID:", trafficId)
  2526. }
  2527. clientEmail := traffic.Email
  2528. oldClients, err := inboundSvc.GetClients(inbound)
  2529. if err != nil {
  2530. return false, err
  2531. }
  2532. clientId := ""
  2533. for _, oldClient := range oldClients {
  2534. if oldClient.Email == clientEmail {
  2535. switch inbound.Protocol {
  2536. case "trojan":
  2537. clientId = oldClient.Password
  2538. case "shadowsocks":
  2539. clientId = oldClient.Email
  2540. default:
  2541. clientId = oldClient.ID
  2542. }
  2543. break
  2544. }
  2545. }
  2546. if len(clientId) == 0 {
  2547. return false, common.NewError("Client Not Found For Email:", clientEmail)
  2548. }
  2549. var settings map[string]any
  2550. err = json.Unmarshal([]byte(inbound.Settings), &settings)
  2551. if err != nil {
  2552. return false, err
  2553. }
  2554. clients := settings["clients"].([]any)
  2555. var newClients []any
  2556. for client_index := range clients {
  2557. c := clients[client_index].(map[string]any)
  2558. if c["email"] == clientEmail {
  2559. c["tgId"] = tgId
  2560. c["updated_at"] = time.Now().Unix() * 1000
  2561. newClients = append(newClients, any(c))
  2562. }
  2563. }
  2564. settings["clients"] = newClients
  2565. modifiedSettings, err := json.MarshalIndent(settings, "", " ")
  2566. if err != nil {
  2567. return false, err
  2568. }
  2569. inbound.Settings = string(modifiedSettings)
  2570. needRestart, err := s.UpdateInboundClient(inboundSvc, inbound, clientId)
  2571. return needRestart, err
  2572. }
  2573. func (s *ClientService) checkIsEnabledByEmail(inboundSvc *InboundService, clientEmail string) (bool, error) {
  2574. _, inbound, err := inboundSvc.GetClientInboundByEmail(clientEmail)
  2575. if err != nil {
  2576. return false, err
  2577. }
  2578. if inbound == nil {
  2579. return false, common.NewError("Inbound Not Found For Email:", clientEmail)
  2580. }
  2581. clients, err := inboundSvc.GetClients(inbound)
  2582. if err != nil {
  2583. return false, err
  2584. }
  2585. isEnable := false
  2586. for _, client := range clients {
  2587. if client.Email == clientEmail {
  2588. isEnable = client.Enable
  2589. break
  2590. }
  2591. }
  2592. return isEnable, err
  2593. }
  2594. func (s *ClientService) ToggleClientEnableByEmail(inboundSvc *InboundService, clientEmail string) (bool, bool, error) {
  2595. _, inbound, err := inboundSvc.GetClientInboundByEmail(clientEmail)
  2596. if err != nil {
  2597. return false, false, err
  2598. }
  2599. if inbound == nil {
  2600. return false, false, common.NewError("Inbound Not Found For Email:", clientEmail)
  2601. }
  2602. oldClients, err := inboundSvc.GetClients(inbound)
  2603. if err != nil {
  2604. return false, false, err
  2605. }
  2606. clientId := ""
  2607. clientOldEnabled := false
  2608. for _, oldClient := range oldClients {
  2609. if oldClient.Email == clientEmail {
  2610. switch inbound.Protocol {
  2611. case "trojan":
  2612. clientId = oldClient.Password
  2613. case "shadowsocks":
  2614. clientId = oldClient.Email
  2615. default:
  2616. clientId = oldClient.ID
  2617. }
  2618. clientOldEnabled = oldClient.Enable
  2619. break
  2620. }
  2621. }
  2622. if len(clientId) == 0 {
  2623. return false, false, common.NewError("Client Not Found For Email:", clientEmail)
  2624. }
  2625. var settings map[string]any
  2626. err = json.Unmarshal([]byte(inbound.Settings), &settings)
  2627. if err != nil {
  2628. return false, false, err
  2629. }
  2630. clients := settings["clients"].([]any)
  2631. var newClients []any
  2632. for client_index := range clients {
  2633. c := clients[client_index].(map[string]any)
  2634. if c["email"] == clientEmail {
  2635. c["enable"] = !clientOldEnabled
  2636. c["updated_at"] = time.Now().Unix() * 1000
  2637. newClients = append(newClients, any(c))
  2638. }
  2639. }
  2640. settings["clients"] = newClients
  2641. modifiedSettings, err := json.MarshalIndent(settings, "", " ")
  2642. if err != nil {
  2643. return false, false, err
  2644. }
  2645. inbound.Settings = string(modifiedSettings)
  2646. needRestart, err := s.UpdateInboundClient(inboundSvc, inbound, clientId)
  2647. if err != nil {
  2648. return false, needRestart, err
  2649. }
  2650. return !clientOldEnabled, needRestart, nil
  2651. }
  2652. func (s *ClientService) SetClientEnableByEmail(inboundSvc *InboundService, clientEmail string, enable bool) (bool, bool, error) {
  2653. current, err := s.checkIsEnabledByEmail(inboundSvc, clientEmail)
  2654. if err != nil {
  2655. return false, false, err
  2656. }
  2657. if current == enable {
  2658. return false, false, nil
  2659. }
  2660. newEnabled, needRestart, err := s.ToggleClientEnableByEmail(inboundSvc, clientEmail)
  2661. if err != nil {
  2662. return false, needRestart, err
  2663. }
  2664. return newEnabled == enable, needRestart, nil
  2665. }
  2666. func (s *ClientService) ResetClientIpLimitByEmail(inboundSvc *InboundService, clientEmail string, count int) (bool, error) {
  2667. _, inbound, err := inboundSvc.GetClientInboundByEmail(clientEmail)
  2668. if err != nil {
  2669. return false, err
  2670. }
  2671. if inbound == nil {
  2672. return false, common.NewError("Inbound Not Found For Email:", clientEmail)
  2673. }
  2674. oldClients, err := inboundSvc.GetClients(inbound)
  2675. if err != nil {
  2676. return false, err
  2677. }
  2678. clientId := ""
  2679. for _, oldClient := range oldClients {
  2680. if oldClient.Email == clientEmail {
  2681. switch inbound.Protocol {
  2682. case "trojan":
  2683. clientId = oldClient.Password
  2684. case "shadowsocks":
  2685. clientId = oldClient.Email
  2686. default:
  2687. clientId = oldClient.ID
  2688. }
  2689. break
  2690. }
  2691. }
  2692. if len(clientId) == 0 {
  2693. return false, common.NewError("Client Not Found For Email:", clientEmail)
  2694. }
  2695. var settings map[string]any
  2696. err = json.Unmarshal([]byte(inbound.Settings), &settings)
  2697. if err != nil {
  2698. return false, err
  2699. }
  2700. clients := settings["clients"].([]any)
  2701. var newClients []any
  2702. for client_index := range clients {
  2703. c := clients[client_index].(map[string]any)
  2704. if c["email"] == clientEmail {
  2705. c["limitIp"] = count
  2706. c["updated_at"] = time.Now().Unix() * 1000
  2707. newClients = append(newClients, any(c))
  2708. }
  2709. }
  2710. settings["clients"] = newClients
  2711. modifiedSettings, err := json.MarshalIndent(settings, "", " ")
  2712. if err != nil {
  2713. return false, err
  2714. }
  2715. inbound.Settings = string(modifiedSettings)
  2716. needRestart, err := s.UpdateInboundClient(inboundSvc, inbound, clientId)
  2717. return needRestart, err
  2718. }
  2719. func (s *ClientService) ResetClientExpiryTimeByEmail(inboundSvc *InboundService, clientEmail string, expiry_time int64) (bool, error) {
  2720. _, inbound, err := inboundSvc.GetClientInboundByEmail(clientEmail)
  2721. if err != nil {
  2722. return false, err
  2723. }
  2724. if inbound == nil {
  2725. return false, common.NewError("Inbound Not Found For Email:", clientEmail)
  2726. }
  2727. oldClients, err := inboundSvc.GetClients(inbound)
  2728. if err != nil {
  2729. return false, err
  2730. }
  2731. clientId := ""
  2732. for _, oldClient := range oldClients {
  2733. if oldClient.Email == clientEmail {
  2734. switch inbound.Protocol {
  2735. case "trojan":
  2736. clientId = oldClient.Password
  2737. case "shadowsocks":
  2738. clientId = oldClient.Email
  2739. default:
  2740. clientId = oldClient.ID
  2741. }
  2742. break
  2743. }
  2744. }
  2745. if len(clientId) == 0 {
  2746. return false, common.NewError("Client Not Found For Email:", clientEmail)
  2747. }
  2748. var settings map[string]any
  2749. err = json.Unmarshal([]byte(inbound.Settings), &settings)
  2750. if err != nil {
  2751. return false, err
  2752. }
  2753. clients := settings["clients"].([]any)
  2754. var newClients []any
  2755. for client_index := range clients {
  2756. c := clients[client_index].(map[string]any)
  2757. if c["email"] == clientEmail {
  2758. c["expiryTime"] = expiry_time
  2759. c["updated_at"] = time.Now().Unix() * 1000
  2760. newClients = append(newClients, any(c))
  2761. }
  2762. }
  2763. settings["clients"] = newClients
  2764. modifiedSettings, err := json.MarshalIndent(settings, "", " ")
  2765. if err != nil {
  2766. return false, err
  2767. }
  2768. inbound.Settings = string(modifiedSettings)
  2769. needRestart, err := s.UpdateInboundClient(inboundSvc, inbound, clientId)
  2770. return needRestart, err
  2771. }
  2772. func (s *ClientService) ResetClientTrafficLimitByEmail(inboundSvc *InboundService, clientEmail string, totalGB int) (bool, error) {
  2773. if totalGB < 0 {
  2774. return false, common.NewError("totalGB must be >= 0")
  2775. }
  2776. _, inbound, err := inboundSvc.GetClientInboundByEmail(clientEmail)
  2777. if err != nil {
  2778. return false, err
  2779. }
  2780. if inbound == nil {
  2781. return false, common.NewError("Inbound Not Found For Email:", clientEmail)
  2782. }
  2783. oldClients, err := inboundSvc.GetClients(inbound)
  2784. if err != nil {
  2785. return false, err
  2786. }
  2787. clientId := ""
  2788. for _, oldClient := range oldClients {
  2789. if oldClient.Email == clientEmail {
  2790. switch inbound.Protocol {
  2791. case "trojan":
  2792. clientId = oldClient.Password
  2793. case "shadowsocks":
  2794. clientId = oldClient.Email
  2795. default:
  2796. clientId = oldClient.ID
  2797. }
  2798. break
  2799. }
  2800. }
  2801. if len(clientId) == 0 {
  2802. return false, common.NewError("Client Not Found For Email:", clientEmail)
  2803. }
  2804. var settings map[string]any
  2805. err = json.Unmarshal([]byte(inbound.Settings), &settings)
  2806. if err != nil {
  2807. return false, err
  2808. }
  2809. clients := settings["clients"].([]any)
  2810. var newClients []any
  2811. for client_index := range clients {
  2812. c := clients[client_index].(map[string]any)
  2813. if c["email"] == clientEmail {
  2814. c["totalGB"] = totalGB * 1024 * 1024 * 1024
  2815. c["updated_at"] = time.Now().Unix() * 1000
  2816. newClients = append(newClients, any(c))
  2817. }
  2818. }
  2819. settings["clients"] = newClients
  2820. modifiedSettings, err := json.MarshalIndent(settings, "", " ")
  2821. if err != nil {
  2822. return false, err
  2823. }
  2824. inbound.Settings = string(modifiedSettings)
  2825. needRestart, err := s.UpdateInboundClient(inboundSvc, inbound, clientId)
  2826. return needRestart, err
  2827. }