client.go 80 KB

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