client_inbound_apply.go 36 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250
  1. package service
  2. import (
  3. "context"
  4. "encoding/json"
  5. "fmt"
  6. "maps"
  7. "strings"
  8. "time"
  9. "github.com/mhsanaei/3x-ui/v3/internal/database"
  10. "github.com/mhsanaei/3x-ui/v3/internal/database/model"
  11. "github.com/mhsanaei/3x-ui/v3/internal/logger"
  12. "github.com/mhsanaei/3x-ui/v3/internal/util/common"
  13. "github.com/mhsanaei/3x-ui/v3/internal/util/random"
  14. "github.com/mhsanaei/3x-ui/v3/internal/web/runtime"
  15. "github.com/mhsanaei/3x-ui/v3/internal/xray"
  16. "gorm.io/gorm"
  17. )
  18. func sameClientConfigExceptUpdatedAt(a, b map[string]any) bool {
  19. aa := maps.Clone(a)
  20. bb := maps.Clone(b)
  21. delete(aa, "updated_at")
  22. delete(bb, "updated_at")
  23. an, aerr := json.Marshal(aa)
  24. bn, berr := json.Marshal(bb)
  25. return aerr == nil && berr == nil && string(an) == string(bn)
  26. }
  27. // advancePushedInbound advances the node's reconcile-skip fingerprint from the
  28. // pre-edit settings to the saved ones after every per-client push succeeded.
  29. func advancePushedInbound(rt runtime.Runtime, prevSettings string, ib *model.Inbound) {
  30. rem, ok := rt.(*runtime.Remote)
  31. if !ok {
  32. return
  33. }
  34. prev := *ib
  35. prev.Settings = prevSettings
  36. rem.AdvancePushedInbound(&prev, ib)
  37. }
  38. // delInboundClients removes several clients from a single inbound in one pass:
  39. // one settings rewrite, one runtime sweep, one Save and one SyncInbound for the
  40. // whole batch, instead of repeating the full per-client cycle. It mirrors the
  41. // semantics of DelInboundClientByEmail for each removed client. needRestart is
  42. // the OR across all removals.
  43. func (s *ClientService) delInboundClients(inboundSvc *InboundService, inboundId int, recs []*model.ClientRecord, keepTraffic bool) (bool, error) {
  44. if len(recs) == 0 {
  45. return false, nil
  46. }
  47. defer lockInbound(inboundId).Unlock()
  48. oldInbound, err := inboundSvc.GetInbound(inboundId)
  49. if err != nil {
  50. logger.Error("Load Old Data Error")
  51. return false, err
  52. }
  53. var settings map[string]any
  54. if err := json.Unmarshal([]byte(oldInbound.Settings), &settings); err != nil {
  55. return false, err
  56. }
  57. // Match by email — the client's stable identity (see Delete). Removes every
  58. // entry carrying a wanted email, independent of credential drift.
  59. wanted := make(map[string]struct{}, len(recs))
  60. for _, rec := range recs {
  61. if rec.Email != "" {
  62. wanted[rec.Email] = struct{}{}
  63. }
  64. }
  65. interfaceClients, ok := settings["clients"].([]any)
  66. if !ok {
  67. return false, common.NewError("invalid clients format in inbound settings")
  68. }
  69. type removedClient struct {
  70. email string
  71. needApiDel bool
  72. }
  73. removed := make([]removedClient, 0, len(wanted))
  74. newClients := make([]any, 0, len(interfaceClients))
  75. for _, client := range interfaceClients {
  76. c, ok := client.(map[string]any)
  77. if !ok {
  78. newClients = append(newClients, client)
  79. continue
  80. }
  81. email, _ := c["email"].(string)
  82. if _, hit := wanted[email]; hit && email != "" {
  83. enable, _ := c["enable"].(bool)
  84. removed = append(removed, removedClient{email: email, needApiDel: enable})
  85. continue
  86. }
  87. newClients = append(newClients, client)
  88. }
  89. if len(removed) == 0 {
  90. return false, nil
  91. }
  92. db := database.GetDB()
  93. newClients = compactOrphans(db, newClients)
  94. if newClients == nil {
  95. newClients = []any{}
  96. }
  97. settings["clients"] = newClients
  98. newSettings, err := json.MarshalIndent(settings, "", " ")
  99. if err != nil {
  100. return false, err
  101. }
  102. prevSettings := oldInbound.Settings
  103. oldInbound.Settings = string(newSettings)
  104. var sharedSet map[string]bool
  105. if !keepTraffic {
  106. removedEmails := make([]string, 0, len(removed))
  107. for _, r := range removed {
  108. if r.email != "" {
  109. removedEmails = append(removedEmails, r.email)
  110. }
  111. }
  112. var sharedErr error
  113. sharedSet, sharedErr = inboundSvc.emailsUsedByOtherInbounds(removedEmails, inboundId)
  114. if sharedErr != nil {
  115. return false, sharedErr
  116. }
  117. }
  118. needRestart := false
  119. // Read each client's live state before the DB write (DelClientStat would
  120. // erase the enable flag we need to decide on a runtime removal).
  121. type delTarget struct {
  122. email string
  123. emailShared bool
  124. notDepleted bool
  125. needApiDel bool
  126. }
  127. targets := make([]delTarget, 0, len(removed))
  128. for _, r := range removed {
  129. email := r.email
  130. emailShared := sharedSet[strings.ToLower(strings.TrimSpace(email))]
  131. notDepleted := false
  132. if len(email) > 0 {
  133. var enables []bool
  134. if err := db.Model(xray.ClientTraffic{}).Where("email = ?", email).Limit(1).Pluck("enable", &enables).Error; err != nil {
  135. logger.Error("Get stats error")
  136. return needRestart, err
  137. }
  138. notDepleted = len(enables) > 0 && enables[0]
  139. }
  140. targets = append(targets, delTarget{email: email, emailShared: emailShared, notDepleted: notDepleted, needApiDel: r.needApiDel})
  141. }
  142. // Persist the batch deletion atomically, serialized against the traffic poll
  143. // to avoid the cross-transaction lock-order deadlock (runSerializedTx).
  144. if txErr := runSerializedTx(func(tx *gorm.DB) error {
  145. for _, t := range targets {
  146. if t.emailShared || keepTraffic {
  147. continue
  148. }
  149. if e := inboundSvc.DelClientIPs(tx, t.email); e != nil {
  150. logger.Error("Error in delete client IPs")
  151. return e
  152. }
  153. if len(t.email) > 0 {
  154. if e := inboundSvc.DelClientStat(tx, t.email); e != nil {
  155. logger.Error("Delete stats Data Error")
  156. return e
  157. }
  158. }
  159. }
  160. if e := tx.Save(oldInbound).Error; e != nil {
  161. return e
  162. }
  163. finalClients, gcErr := inboundSvc.GetClients(oldInbound)
  164. if gcErr != nil {
  165. return gcErr
  166. }
  167. if err := s.SyncInbound(tx, inboundId, finalClients); err != nil {
  168. return err
  169. }
  170. if oldInbound.NodeID != nil {
  171. return (&NodeService{}).MarkNodeDirtyTx(tx, *oldInbound.NodeID)
  172. }
  173. return nil
  174. }); txErr != nil {
  175. return needRestart, txErr
  176. }
  177. // Resolve the node push plan once for the whole batch instead of per email.
  178. var nodeRt runtime.Runtime
  179. nodePush := false
  180. if oldInbound.NodeID != nil {
  181. rt, push, _, perr := inboundSvc.nodePushPlan(oldInbound)
  182. if perr != nil {
  183. return needRestart, perr
  184. }
  185. nodeRt, nodePush = rt, push
  186. // Large batches collapse into one reconcile push rather than M deletes.
  187. if nodePush && len(targets) > nodeBulkPushThreshold {
  188. nodePush = false
  189. }
  190. }
  191. // Apply runtime deletes after commit — outside the serialized writer so a
  192. // slow node call can't stall traffic accounting.
  193. nodePushFailed := false
  194. for _, t := range targets {
  195. if len(t.email) == 0 {
  196. continue
  197. }
  198. if oldInbound.NodeID == nil {
  199. if t.needApiDel && t.notDepleted {
  200. rt, rterr := inboundSvc.runtimeFor(oldInbound)
  201. if rterr != nil {
  202. needRestart = true
  203. } else if err1 := rt.RemoveUser(context.Background(), oldInbound, t.email); err1 != nil {
  204. if !strings.Contains(err1.Error(), fmt.Sprintf("User %s not found.", t.email)) {
  205. needRestart = true
  206. }
  207. }
  208. }
  209. } else if nodePush {
  210. if err1 := nodeRt.DeleteUser(context.Background(), oldInbound, t.email); err1 != nil {
  211. logger.Warning("Error in deleting client on", nodeRt.Name(), ":", err1)
  212. nodePushFailed = true
  213. }
  214. }
  215. }
  216. if nodePush && !nodePushFailed {
  217. advancePushedInbound(nodeRt, prevSettings, oldInbound)
  218. }
  219. return needRestart, nil
  220. }
  221. func (s *ClientService) checkEmailsExistForClients(inboundSvc *InboundService, clients []model.Client, emailSubIDs map[string]string) (string, error) {
  222. if emailSubIDs == nil {
  223. var err error
  224. emailSubIDs, err = inboundSvc.getAllEmailSubIDs()
  225. if err != nil {
  226. return "", err
  227. }
  228. }
  229. seen := make(map[string]string, len(clients))
  230. for _, client := range clients {
  231. if client.Email == "" {
  232. continue
  233. }
  234. key := strings.ToLower(client.Email)
  235. if prev, ok := seen[key]; ok {
  236. if prev != client.SubID || client.SubID == "" {
  237. return client.Email, nil
  238. }
  239. continue
  240. }
  241. seen[key] = client.SubID
  242. if existingSub, ok := emailSubIDs[key]; ok {
  243. if client.SubID == "" || existingSub == "" || existingSub != client.SubID {
  244. return client.Email, nil
  245. }
  246. }
  247. }
  248. return "", nil
  249. }
  250. func (s *ClientService) AddInboundClient(inboundSvc *InboundService, data *model.Inbound) (bool, error) {
  251. return s.addInboundClient(inboundSvc, data, nil)
  252. }
  253. // addInboundClient is AddInboundClient with an optional precomputed email→subId
  254. // map. Bulk callers pass a single snapshot so the global getAllEmailSubIDs scan
  255. // runs once for the whole batch instead of once per target inbound; a nil map
  256. // makes it compute its own (the single-add path).
  257. func (s *ClientService) addInboundClient(inboundSvc *InboundService, data *model.Inbound, emailSubIDs map[string]string) (bool, error) {
  258. defer lockInbound(data.Id).Unlock()
  259. clients, err := inboundSvc.GetClients(data)
  260. if err != nil {
  261. return false, err
  262. }
  263. var settings map[string]any
  264. err = json.Unmarshal([]byte(data.Settings), &settings)
  265. if err != nil {
  266. return false, err
  267. }
  268. interfaceClients := settings["clients"].([]any)
  269. nowTs := time.Now().Unix() * 1000
  270. for i := range interfaceClients {
  271. if cm, ok := interfaceClients[i].(map[string]any); ok {
  272. if _, ok2 := cm["created_at"]; !ok2 {
  273. cm["created_at"] = nowTs
  274. }
  275. cm["updated_at"] = nowTs
  276. existingSub, _ := cm["subId"].(string)
  277. if strings.TrimSpace(existingSub) == "" {
  278. cm["subId"] = random.NumLower(16)
  279. }
  280. interfaceClients[i] = cm
  281. }
  282. }
  283. existEmail, err := s.checkEmailsExistForClients(inboundSvc, clients, emailSubIDs)
  284. if err != nil {
  285. return false, err
  286. }
  287. if existEmail != "" {
  288. return false, common.NewError("Duplicate email:", existEmail)
  289. }
  290. oldInbound, err := inboundSvc.GetInbound(data.Id)
  291. if err != nil {
  292. return false, err
  293. }
  294. if oldInbound.Protocol == model.WireGuard {
  295. existing, gcErr := inboundSvc.GetClients(oldInbound)
  296. if gcErr != nil {
  297. return false, gcErr
  298. }
  299. if dErr := defaultWireguardClients(existing, clients, interfaceClients); dErr != nil {
  300. return false, dErr
  301. }
  302. }
  303. for _, client := range clients {
  304. if strings.TrimSpace(client.Email) == "" {
  305. return false, common.NewError("client email is required")
  306. }
  307. switch oldInbound.Protocol {
  308. case "trojan":
  309. if client.Password == "" {
  310. return false, common.NewError("empty client ID")
  311. }
  312. case "shadowsocks":
  313. if client.Email == "" {
  314. return false, common.NewError("empty client ID")
  315. }
  316. case "hysteria":
  317. if client.Auth == "" {
  318. return false, common.NewError("empty client ID")
  319. }
  320. case "wireguard":
  321. if client.PublicKey == "" {
  322. return false, common.NewError("wireguard client requires a key")
  323. }
  324. default:
  325. if client.ID == "" {
  326. return false, common.NewError("empty client ID")
  327. }
  328. }
  329. }
  330. var oldSettings map[string]any
  331. err = json.Unmarshal([]byte(oldInbound.Settings), &oldSettings)
  332. if err != nil {
  333. return false, err
  334. }
  335. if oldInbound.Protocol == model.Shadowsocks {
  336. applyShadowsocksClientMethod(interfaceClients, oldSettings)
  337. }
  338. oldClients, _ := oldSettings["clients"].([]any)
  339. oldClients = compactOrphans(database.GetDB(), oldClients)
  340. oldClients = append(oldClients, interfaceClients...)
  341. oldSettings["clients"] = oldClients
  342. newSettings, err := json.MarshalIndent(oldSettings, "", " ")
  343. if err != nil {
  344. return false, err
  345. }
  346. prevSettings := oldInbound.Settings
  347. oldInbound.Settings = string(newSettings)
  348. needRestart := false
  349. rt, push, _, perr := inboundSvc.nodePushPlan(oldInbound)
  350. if perr != nil {
  351. return false, perr
  352. }
  353. // Persist client stats + inbound atomically, serialized against the traffic
  354. // poll to avoid the cross-transaction lock-order deadlock (runSerializedTx).
  355. if txErr := runSerializedTx(func(tx *gorm.DB) error {
  356. for i := range clients {
  357. if len(clients[i].Email) == 0 {
  358. continue
  359. }
  360. if e := inboundSvc.AddClientStat(tx, data.Id, &clients[i]); e != nil {
  361. return e
  362. }
  363. }
  364. if e := tx.Save(oldInbound).Error; e != nil {
  365. return e
  366. }
  367. finalClients, gcErr := inboundSvc.GetClients(oldInbound)
  368. if gcErr != nil {
  369. return gcErr
  370. }
  371. if err := s.SyncInbound(tx, oldInbound.Id, finalClients); err != nil {
  372. return err
  373. }
  374. if oldInbound.NodeID != nil {
  375. return (&NodeService{}).MarkNodeDirtyTx(tx, *oldInbound.NodeID)
  376. }
  377. return nil
  378. }); txErr != nil {
  379. return false, txErr
  380. }
  381. // Apply to the running runtime after commit — outside the serialized writer
  382. // so a slow node call can't stall traffic accounting.
  383. if oldInbound.NodeID == nil {
  384. if !push {
  385. needRestart = true
  386. } else {
  387. for _, client := range clients {
  388. if len(client.Email) == 0 {
  389. needRestart = true
  390. continue
  391. }
  392. if !client.Enable {
  393. continue
  394. }
  395. cipher := ""
  396. if oldInbound.Protocol == "shadowsocks" {
  397. cipher = oldSettings["method"].(string)
  398. }
  399. err1 := rt.AddUser(context.Background(), oldInbound, map[string]any{
  400. "email": client.Email,
  401. "id": client.ID,
  402. "auth": client.Auth,
  403. "security": client.Security,
  404. "flow": client.Flow,
  405. "password": client.Password,
  406. "cipher": cipher,
  407. "publicKey": client.PublicKey,
  408. "allowedIPs": client.AllowedIPs,
  409. "preSharedKey": client.PreSharedKey,
  410. "keepAlive": keepAliveStr(client.KeepAlive),
  411. })
  412. if err1 == nil {
  413. logger.Debug("Client added on", rt.Name(), ":", client.Email)
  414. } else {
  415. logger.Debug("Error in adding client on", rt.Name(), ":", err1)
  416. needRestart = true
  417. }
  418. }
  419. }
  420. } else {
  421. // Large batches would be M sequential per-client RPCs; the inbound's saved
  422. // settings already hold the final set, so mark dirty and let one reconcile
  423. // push converge the node instead.
  424. if push && len(clients) > nodeBulkPushThreshold {
  425. push = false
  426. }
  427. for _, client := range clients {
  428. if push {
  429. if err1 := rt.AddClient(context.Background(), oldInbound, client); err1 != nil {
  430. logger.Warning("Error in adding client on", rt.Name(), ":", err1)
  431. push = false
  432. }
  433. }
  434. }
  435. if push {
  436. advancePushedInbound(rt, prevSettings, oldInbound)
  437. }
  438. }
  439. return needRestart, nil
  440. }
  441. func (s *ClientService) UpdateInboundClient(inboundSvc *InboundService, data *model.Inbound, oldEmail string) (bool, error) {
  442. defer lockInbound(data.Id).Unlock()
  443. clients, err := inboundSvc.GetClients(data)
  444. if err != nil {
  445. return false, err
  446. }
  447. var settings map[string]any
  448. err = json.Unmarshal([]byte(data.Settings), &settings)
  449. if err != nil {
  450. return false, err
  451. }
  452. interfaceClients := settings["clients"].([]any)
  453. oldInbound, err := inboundSvc.GetInbound(data.Id)
  454. if err != nil {
  455. return false, err
  456. }
  457. oldClients, err := inboundSvc.GetClients(oldInbound)
  458. if err != nil {
  459. return false, err
  460. }
  461. newClientId := ""
  462. switch oldInbound.Protocol {
  463. case "trojan":
  464. newClientId = clients[0].Password
  465. case "shadowsocks":
  466. newClientId = clients[0].Email
  467. case "hysteria":
  468. newClientId = clients[0].Auth
  469. case "wireguard":
  470. newClientId = clients[0].Email
  471. default:
  472. newClientId = clients[0].ID
  473. }
  474. // Locate the client to replace by email — the client's stable identity.
  475. // Credentials (uuid/password/auth) can drift from the inbound JSON, so they
  476. // are never used for matching.
  477. clientIndex := -1
  478. for index, oldClient := range oldClients {
  479. if strings.EqualFold(oldClient.Email, oldEmail) {
  480. oldEmail = oldClient.Email
  481. clientIndex = index
  482. break
  483. }
  484. }
  485. if newClientId == "" || clientIndex == -1 {
  486. return false, common.NewError("empty client ID")
  487. }
  488. if strings.TrimSpace(clients[0].Email) == "" {
  489. return false, common.NewError("client email is required")
  490. }
  491. if clients[0].Email != oldEmail {
  492. existEmail, err := s.checkEmailsExistForClients(inboundSvc, clients, nil)
  493. if err != nil {
  494. return false, err
  495. }
  496. if existEmail != "" {
  497. return false, common.NewError("Duplicate email:", existEmail)
  498. }
  499. }
  500. // WireGuard keys are never rotated by an edit: when the incoming payload omits
  501. // them (a metadata-only change), carry the stored credentials forward so the
  502. // settings JSON and the running peer keep the client's identity.
  503. if oldInbound.Protocol == model.WireGuard && clientIndex >= 0 && clientIndex < len(oldClients) {
  504. old := oldClients[clientIndex]
  505. if clients[0].PrivateKey == "" {
  506. clients[0].PrivateKey = old.PrivateKey
  507. }
  508. if clients[0].PublicKey == "" {
  509. clients[0].PublicKey = old.PublicKey
  510. }
  511. if len(clients[0].AllowedIPs) == 0 {
  512. clients[0].AllowedIPs = old.AllowedIPs
  513. } else {
  514. normalized, nErr := normalizeWireguardAllowedIPs(clients[0].AllowedIPs)
  515. if nErr != nil {
  516. return false, nErr
  517. }
  518. if len(normalized) == 0 {
  519. clients[0].AllowedIPs = old.AllowedIPs
  520. } else {
  521. peers := make([]string, 0, len(oldClients))
  522. for i := range oldClients {
  523. if i == clientIndex {
  524. continue
  525. }
  526. peers = append(peers, oldClients[i].AllowedIPs...)
  527. }
  528. if hit := wireguardAllowedIPsCollision(normalized, peers); hit != "" {
  529. return false, common.NewError("wireguard: allowedIPs entry already used by another client:", hit)
  530. }
  531. clients[0].AllowedIPs = normalized
  532. }
  533. }
  534. if clients[0].PreSharedKey == "" {
  535. clients[0].PreSharedKey = old.PreSharedKey
  536. }
  537. if clients[0].KeepAlive == 0 {
  538. clients[0].KeepAlive = old.KeepAlive
  539. }
  540. }
  541. var oldSettings map[string]any
  542. err = json.Unmarshal([]byte(oldInbound.Settings), &oldSettings)
  543. if err != nil {
  544. return false, err
  545. }
  546. settingsClients, _ := oldSettings["clients"].([]any)
  547. var preservedCreated any
  548. var preservedSubID string
  549. var oldClientMap map[string]any
  550. if clientIndex >= 0 && clientIndex < len(settingsClients) {
  551. if oldMap, ok := settingsClients[clientIndex].(map[string]any); ok {
  552. oldClientMap = oldMap
  553. if v, ok2 := oldMap["created_at"]; ok2 {
  554. preservedCreated = v
  555. }
  556. preservedSubID, _ = oldMap["subId"].(string)
  557. }
  558. }
  559. if oldInbound.Protocol == model.Shadowsocks {
  560. applyShadowsocksClientMethod(interfaceClients, oldSettings)
  561. }
  562. if len(interfaceClients) > 0 {
  563. if newMap, ok := interfaceClients[0].(map[string]any); ok {
  564. if preservedCreated == nil {
  565. preservedCreated = time.Now().Unix() * 1000
  566. }
  567. newMap["created_at"] = preservedCreated
  568. newSub, _ := newMap["subId"].(string)
  569. if strings.TrimSpace(newSub) == "" {
  570. if strings.TrimSpace(preservedSubID) != "" {
  571. newMap["subId"] = preservedSubID
  572. } else {
  573. newMap["subId"] = random.NumLower(16)
  574. }
  575. }
  576. if v, ok2 := newMap["subId"].(string); ok2 {
  577. clients[0].SubID = v
  578. }
  579. if oldInbound.Protocol == model.WireGuard {
  580. newMap["privateKey"] = clients[0].PrivateKey
  581. newMap["publicKey"] = clients[0].PublicKey
  582. newMap["allowedIPs"] = clients[0].AllowedIPs
  583. if clients[0].PreSharedKey != "" {
  584. newMap["preSharedKey"] = clients[0].PreSharedKey
  585. }
  586. if clients[0].KeepAlive > 0 {
  587. newMap["keepAlive"] = clients[0].KeepAlive
  588. }
  589. }
  590. if oldClientMap != nil && sameClientConfigExceptUpdatedAt(oldClientMap, newMap) {
  591. if v, ok2 := oldClientMap["updated_at"]; ok2 {
  592. newMap["updated_at"] = v
  593. } else {
  594. delete(newMap, "updated_at")
  595. }
  596. } else {
  597. newMap["updated_at"] = time.Now().Unix() * 1000
  598. }
  599. interfaceClients[0] = newMap
  600. }
  601. }
  602. settingsClients[clientIndex] = interfaceClients[0]
  603. oldSettings["clients"] = settingsClients
  604. if oldInbound.Protocol == model.VLESS {
  605. hasVisionFlow := false
  606. for _, c := range settingsClients {
  607. cm, ok := c.(map[string]any)
  608. if !ok {
  609. continue
  610. }
  611. if flow, _ := cm["flow"].(string); flow == "xtls-rprx-vision" {
  612. hasVisionFlow = true
  613. break
  614. }
  615. }
  616. if !hasVisionFlow {
  617. delete(oldSettings, "testseed")
  618. }
  619. }
  620. newSettings, err := json.MarshalIndent(oldSettings, "", " ")
  621. if err != nil {
  622. return false, err
  623. }
  624. if string(newSettings) == oldInbound.Settings {
  625. return false, nil
  626. }
  627. prevSettings := oldInbound.Settings
  628. oldInbound.Settings = string(newSettings)
  629. needRestart := false
  630. // Resolve the push plan before the DB write so a node-state lookup failure
  631. // still aborts the whole update without committing anything (it used to roll
  632. // the transaction back). nodePushPlan only reads, so order doesn't matter.
  633. var rt runtime.Runtime
  634. var push bool
  635. if len(oldEmail) > 0 {
  636. var perr error
  637. rt, push, _, perr = inboundSvc.nodePushPlan(oldInbound)
  638. if perr != nil {
  639. return false, perr
  640. }
  641. }
  642. // Persist client stats + inbound atomically, serialized against the traffic
  643. // poll to avoid the cross-transaction lock-order deadlock (runSerializedTx).
  644. if txErr := runSerializedTx(func(tx *gorm.DB) error {
  645. if len(clients[0].Email) > 0 {
  646. if len(oldEmail) > 0 {
  647. emailUnchanged := strings.EqualFold(oldEmail, clients[0].Email)
  648. targetExists := int64(0)
  649. if !emailUnchanged {
  650. if e := tx.Model(xray.ClientTraffic{}).Where("email = ?", clients[0].Email).Count(&targetExists).Error; e != nil {
  651. return e
  652. }
  653. }
  654. if emailUnchanged || targetExists == 0 {
  655. if e := inboundSvc.UpdateClientStat(tx, oldEmail, &clients[0]); e != nil {
  656. return e
  657. }
  658. if e := inboundSvc.UpdateClientIPs(tx, oldEmail, clients[0].Email); e != nil {
  659. return e
  660. }
  661. } else {
  662. stillUsed, sErr := inboundSvc.emailUsedByOtherInbounds(oldEmail, data.Id)
  663. if sErr != nil {
  664. return sErr
  665. }
  666. if !stillUsed {
  667. if e := inboundSvc.DelClientStat(tx, oldEmail); e != nil {
  668. return e
  669. }
  670. if e := inboundSvc.DelClientIPs(tx, oldEmail); e != nil {
  671. return e
  672. }
  673. }
  674. if e := inboundSvc.UpdateClientStat(tx, clients[0].Email, &clients[0]); e != nil {
  675. return e
  676. }
  677. }
  678. } else {
  679. if e := inboundSvc.AddClientStat(tx, data.Id, &clients[0]); e != nil {
  680. return e
  681. }
  682. }
  683. } else {
  684. stillUsed, sErr := inboundSvc.emailUsedByOtherInbounds(oldEmail, data.Id)
  685. if sErr != nil {
  686. return sErr
  687. }
  688. if !stillUsed {
  689. if e := inboundSvc.DelClientStat(tx, oldEmail); e != nil {
  690. return e
  691. }
  692. if e := inboundSvc.DelClientIPs(tx, oldEmail); e != nil {
  693. return e
  694. }
  695. }
  696. }
  697. if e := tx.Save(oldInbound).Error; e != nil {
  698. return e
  699. }
  700. finalClients, gcErr := inboundSvc.GetClients(oldInbound)
  701. if gcErr != nil {
  702. return gcErr
  703. }
  704. if err := s.SyncInbound(tx, oldInbound.Id, finalClients); err != nil {
  705. return err
  706. }
  707. if oldInbound.NodeID != nil {
  708. return (&NodeService{}).MarkNodeDirtyTx(tx, *oldInbound.NodeID)
  709. }
  710. return nil
  711. }); txErr != nil {
  712. return false, txErr
  713. }
  714. // Apply to the running runtime after the DB is committed — outside the
  715. // serialized writer so a slow node call can't stall traffic accounting.
  716. if len(oldEmail) > 0 {
  717. if oldInbound.NodeID == nil {
  718. if !push {
  719. needRestart = true
  720. } else {
  721. if oldClients[clientIndex].Enable {
  722. err1 := rt.RemoveUser(context.Background(), oldInbound, oldEmail)
  723. if err1 == nil {
  724. logger.Debug("Old client deleted on", rt.Name(), ":", oldEmail)
  725. } else if strings.Contains(err1.Error(), fmt.Sprintf("User %s not found.", oldEmail)) {
  726. logger.Debug("User is already deleted. Nothing to do more...")
  727. } else {
  728. logger.Debug("Error in deleting client on", rt.Name(), ":", err1)
  729. needRestart = true
  730. }
  731. }
  732. if clients[0].Enable {
  733. cipher := ""
  734. if oldInbound.Protocol == "shadowsocks" {
  735. cipher = oldSettings["method"].(string)
  736. }
  737. err1 := rt.AddUser(context.Background(), oldInbound, map[string]any{
  738. "email": clients[0].Email,
  739. "id": clients[0].ID,
  740. "security": clients[0].Security,
  741. "flow": clients[0].Flow,
  742. "auth": clients[0].Auth,
  743. "password": clients[0].Password,
  744. "cipher": cipher,
  745. "publicKey": clients[0].PublicKey,
  746. "allowedIPs": clients[0].AllowedIPs,
  747. "preSharedKey": clients[0].PreSharedKey,
  748. "keepAlive": keepAliveStr(clients[0].KeepAlive),
  749. })
  750. if err1 == nil {
  751. logger.Debug("Client edited on", rt.Name(), ":", clients[0].Email)
  752. } else {
  753. logger.Debug("Error in adding client on", rt.Name(), ":", err1)
  754. needRestart = true
  755. }
  756. }
  757. }
  758. } else if push {
  759. if err1 := rt.UpdateUser(context.Background(), oldInbound, oldEmail, clients[0]); err1 != nil {
  760. logger.Warning("Error in updating client on", rt.Name(), ":", err1)
  761. } else {
  762. advancePushedInbound(rt, prevSettings, oldInbound)
  763. }
  764. }
  765. } else {
  766. logger.Debug("Client old email not found")
  767. needRestart = true
  768. }
  769. return needRestart, nil
  770. }
  771. func (s *ClientService) DelInboundClientByEmail(inboundSvc *InboundService, inboundId int, email string, keepTraffic bool, fullDelete bool) (bool, error) {
  772. defer lockInbound(inboundId).Unlock()
  773. oldInbound, err := inboundSvc.GetInbound(inboundId)
  774. if err != nil {
  775. logger.Error("Load Old Data Error")
  776. return false, err
  777. }
  778. var settings map[string]any
  779. if err := json.Unmarshal([]byte(oldInbound.Settings), &settings); err != nil {
  780. return false, err
  781. }
  782. interfaceClients, ok := settings["clients"].([]any)
  783. if !ok {
  784. return false, common.NewError("invalid clients format in inbound settings")
  785. }
  786. var newClients []any
  787. needApiDel := false
  788. found := false
  789. for _, client := range interfaceClients {
  790. c, ok := client.(map[string]any)
  791. if !ok {
  792. continue
  793. }
  794. if cEmail, ok := c["email"].(string); ok && cEmail == email {
  795. found = true
  796. needApiDel, _ = c["enable"].(bool)
  797. } else {
  798. newClients = append(newClients, client)
  799. }
  800. }
  801. if !found {
  802. return false, fmt.Errorf("%w for email: %s", ErrClientNotInInbound, email)
  803. }
  804. db := database.GetDB()
  805. newClients = compactOrphans(db, newClients)
  806. if newClients == nil {
  807. newClients = []any{}
  808. }
  809. settings["clients"] = newClients
  810. newSettings, err := json.MarshalIndent(settings, "", " ")
  811. if err != nil {
  812. return false, err
  813. }
  814. prevSettings := oldInbound.Settings
  815. oldInbound.Settings = string(newSettings)
  816. emailShared, err := inboundSvc.emailUsedByOtherInbounds(email, inboundId)
  817. if err != nil {
  818. return false, err
  819. }
  820. needRestart := false
  821. // Decide what to delete and the push plan before the serialized DB write —
  822. // these are reads, and nodePushPlan failing should abort before committing.
  823. delStat := false
  824. if len(email) > 0 && !emailShared && !keepTraffic {
  825. traffic, tErr := inboundSvc.GetClientTrafficByEmail(email)
  826. if tErr != nil {
  827. return false, tErr
  828. }
  829. delStat = traffic != nil
  830. }
  831. // The runtime user is scoped to this inbound's tag + email, so the push plan
  832. // is resolved independently of emailShared — a sibling inbound still carrying
  833. // the email must not suppress removing the user from this inbound's Xray.
  834. var rt runtime.Runtime
  835. var push bool
  836. if len(email) > 0 && (oldInbound.NodeID != nil || needApiDel) {
  837. r, p, _, perr := inboundSvc.nodePushPlan(oldInbound)
  838. if perr != nil {
  839. return false, perr
  840. }
  841. rt, push = r, p
  842. }
  843. // Persist the deletion atomically, serialized against the traffic poll to
  844. // avoid the cross-transaction lock-order deadlock (runSerializedTx).
  845. if txErr := runSerializedTx(func(tx *gorm.DB) error {
  846. if !emailShared && !keepTraffic {
  847. if e := inboundSvc.DelClientIPs(tx, email); e != nil {
  848. logger.Error("Error in delete client IPs")
  849. return e
  850. }
  851. }
  852. if delStat {
  853. if e := inboundSvc.DelClientStat(tx, email); e != nil {
  854. logger.Error("Delete stats Data Error")
  855. return e
  856. }
  857. }
  858. if e := tx.Save(oldInbound).Error; e != nil {
  859. return e
  860. }
  861. finalClients, gcErr := inboundSvc.GetClients(oldInbound)
  862. if gcErr != nil {
  863. return gcErr
  864. }
  865. if err := s.SyncInbound(tx, inboundId, finalClients); err != nil {
  866. return err
  867. }
  868. if oldInbound.NodeID != nil {
  869. return (&NodeService{}).MarkNodeDirtyTx(tx, *oldInbound.NodeID)
  870. }
  871. return nil
  872. }); txErr != nil {
  873. return false, txErr
  874. }
  875. // Apply the runtime delete after commit — outside the serialized writer so a
  876. // slow node call can't stall traffic accounting. Independent of emailShared:
  877. // Xray users are keyed by inbound tag, so the user must be removed from this
  878. // inbound's runtime even when the same email survives in another inbound.
  879. if len(email) > 0 {
  880. if oldInbound.NodeID == nil {
  881. // Local inbound: a disabled client isn't in the running Xray, so only
  882. // a live one (needApiDel) needs an API removal.
  883. if needApiDel {
  884. if !push {
  885. needRestart = true
  886. } else if err1 := rt.RemoveUser(context.Background(), oldInbound, email); err1 == nil {
  887. logger.Debug("Client deleted on", rt.Name(), ":", email)
  888. needRestart = false
  889. } else if strings.Contains(err1.Error(), fmt.Sprintf("User %s not found.", email)) {
  890. logger.Debug("User is already deleted. Nothing to do more...")
  891. } else {
  892. logger.Debug("Error in deleting client on", rt.Name(), ":", email)
  893. needRestart = true
  894. }
  895. }
  896. } else {
  897. // Node inbound: propagate the delete regardless of the enable flag —
  898. // the node's own DB still carries a disabled client and would
  899. // resurrect it on the next snapshot otherwise. A full client delete
  900. // must remove the node's client record too, not just detach it from
  901. // this inbound (#5797).
  902. if push {
  903. var err1 error
  904. if fullDelete {
  905. err1 = rt.DeleteClient(context.Background(), email)
  906. } else {
  907. err1 = rt.DeleteUser(context.Background(), oldInbound, email)
  908. }
  909. if err1 != nil {
  910. logger.Warning("Error in deleting client on", rt.Name(), ":", err1)
  911. } else {
  912. advancePushedInbound(rt, prevSettings, oldInbound)
  913. }
  914. }
  915. }
  916. }
  917. return needRestart, nil
  918. }
  919. func (s *ClientService) SetClientTelegramUserID(inboundSvc *InboundService, trafficId int, tgId int64) (bool, error) {
  920. traffic, inbound, err := inboundSvc.GetClientInboundByTrafficID(trafficId)
  921. if err != nil {
  922. return false, err
  923. }
  924. if inbound == nil {
  925. return false, common.NewError("Inbound Not Found For Traffic ID:", trafficId)
  926. }
  927. clientEmail := traffic.Email
  928. oldClients, err := inboundSvc.GetClients(inbound)
  929. if err != nil {
  930. return false, err
  931. }
  932. found := false
  933. for _, oldClient := range oldClients {
  934. if oldClient.Email == clientEmail {
  935. found = true
  936. break
  937. }
  938. }
  939. if !found {
  940. return false, common.NewError("Client Not Found For Email:", clientEmail)
  941. }
  942. var settings map[string]any
  943. err = json.Unmarshal([]byte(inbound.Settings), &settings)
  944. if err != nil {
  945. return false, err
  946. }
  947. clients := settings["clients"].([]any)
  948. var newClients []any
  949. for client_index := range clients {
  950. c := clients[client_index].(map[string]any)
  951. if c["email"] == clientEmail {
  952. c["tgId"] = tgId
  953. c["updated_at"] = time.Now().Unix() * 1000
  954. newClients = append(newClients, any(c))
  955. }
  956. }
  957. settings["clients"] = newClients
  958. modifiedSettings, err := json.MarshalIndent(settings, "", " ")
  959. if err != nil {
  960. return false, err
  961. }
  962. inbound.Settings = string(modifiedSettings)
  963. needRestart, err := s.UpdateInboundClient(inboundSvc, inbound, clientEmail)
  964. return needRestart, err
  965. }
  966. func (s *ClientService) CheckIsEnabledByEmail(inboundSvc *InboundService, clientEmail string) (bool, error) {
  967. _, inbound, err := inboundSvc.GetClientInboundByEmail(clientEmail)
  968. if err != nil {
  969. return false, err
  970. }
  971. if inbound == nil {
  972. return false, common.NewError("Inbound Not Found For Email:", clientEmail)
  973. }
  974. clients, err := inboundSvc.GetClients(inbound)
  975. if err != nil {
  976. return false, err
  977. }
  978. isEnable := false
  979. for _, client := range clients {
  980. if client.Email == clientEmail {
  981. isEnable = client.Enable
  982. break
  983. }
  984. }
  985. return isEnable, err
  986. }
  987. func (s *ClientService) ToggleClientEnableByEmail(inboundSvc *InboundService, clientEmail string) (bool, bool, error) {
  988. _, inbound, err := inboundSvc.GetClientInboundByEmail(clientEmail)
  989. if err != nil {
  990. return false, false, err
  991. }
  992. if inbound == nil {
  993. return false, false, common.NewError("Inbound Not Found For Email:", clientEmail)
  994. }
  995. oldClients, err := inboundSvc.GetClients(inbound)
  996. if err != nil {
  997. return false, false, err
  998. }
  999. found := false
  1000. clientOldEnabled := false
  1001. for _, oldClient := range oldClients {
  1002. if oldClient.Email == clientEmail {
  1003. found = true
  1004. clientOldEnabled = oldClient.Enable
  1005. break
  1006. }
  1007. }
  1008. if !found {
  1009. return false, false, common.NewError("Client Not Found For Email:", clientEmail)
  1010. }
  1011. var settings map[string]any
  1012. err = json.Unmarshal([]byte(inbound.Settings), &settings)
  1013. if err != nil {
  1014. return false, false, err
  1015. }
  1016. clients := settings["clients"].([]any)
  1017. var newClients []any
  1018. for client_index := range clients {
  1019. c := clients[client_index].(map[string]any)
  1020. if c["email"] == clientEmail {
  1021. c["enable"] = !clientOldEnabled
  1022. c["updated_at"] = time.Now().Unix() * 1000
  1023. newClients = append(newClients, any(c))
  1024. }
  1025. }
  1026. settings["clients"] = newClients
  1027. modifiedSettings, err := json.MarshalIndent(settings, "", " ")
  1028. if err != nil {
  1029. return false, false, err
  1030. }
  1031. inbound.Settings = string(modifiedSettings)
  1032. needRestart, err := s.UpdateInboundClient(inboundSvc, inbound, clientEmail)
  1033. if err != nil {
  1034. return false, needRestart, err
  1035. }
  1036. return !clientOldEnabled, needRestart, nil
  1037. }
  1038. func (s *ClientService) SetClientEnableByEmail(inboundSvc *InboundService, clientEmail string, enable bool) (bool, bool, error) {
  1039. current, err := s.CheckIsEnabledByEmail(inboundSvc, clientEmail)
  1040. if err != nil {
  1041. return false, false, err
  1042. }
  1043. if current == enable {
  1044. return false, false, nil
  1045. }
  1046. newEnabled, needRestart, err := s.ToggleClientEnableByEmail(inboundSvc, clientEmail)
  1047. if err != nil {
  1048. return false, needRestart, err
  1049. }
  1050. return newEnabled == enable, needRestart, nil
  1051. }
  1052. // applyClientFieldByEmail loads the inbound currently hosting clientEmail,
  1053. // confirms the client exists, applies mutate to the matching client (plus a
  1054. // refreshed updated_at), and hands a single-client update payload to
  1055. // UpdateInboundClient. The rebuilt clients array intentionally contains only
  1056. // the matched client — that is the input contract UpdateInboundClient expects
  1057. // (clients[0] is the new data; clientEmail locates the row to replace). It
  1058. // backs the single-field by-email setters below.
  1059. // applyClientFieldByEmail mutates a client field on every inbound the email is
  1060. // attached to. A multi-inbound client is one logical identity: patching only
  1061. // the first inbound's JSON would leave the siblings stale, and the next
  1062. // SyncInbound over a stale sibling would revert the edit in the normalized
  1063. // records (#5039).
  1064. func (s *ClientService) applyClientFieldByEmail(inboundSvc *InboundService, clientEmail string, mutate func(c map[string]any)) (bool, error) {
  1065. inboundIds, err := s.GetInboundIdsForEmail(database.GetDB(), clientEmail)
  1066. if err != nil {
  1067. return false, err
  1068. }
  1069. if len(inboundIds) == 0 {
  1070. // Legacy fallback for clients that only live in the inbound JSON and
  1071. // were never normalized into client_inbounds.
  1072. _, inbound, gErr := inboundSvc.GetClientInboundByEmail(clientEmail)
  1073. if gErr != nil {
  1074. return false, gErr
  1075. }
  1076. if inbound == nil {
  1077. return false, common.NewError("Inbound Not Found For Email:", clientEmail)
  1078. }
  1079. inboundIds = []int{inbound.Id}
  1080. }
  1081. needRestart := false
  1082. found := false
  1083. for _, ibId := range inboundIds {
  1084. inbound, gErr := inboundSvc.GetInbound(ibId)
  1085. if gErr != nil {
  1086. return needRestart, gErr
  1087. }
  1088. var settings map[string]any
  1089. if uErr := json.Unmarshal([]byte(inbound.Settings), &settings); uErr != nil {
  1090. return needRestart, uErr
  1091. }
  1092. clients, _ := settings["clients"].([]any)
  1093. // UpdateInboundClient expects a single-client payload, so keep only the
  1094. // matching entry in the scratch copy; it splices the result back into
  1095. // the inbound's full client list itself.
  1096. var newClients []any
  1097. for client_index := range clients {
  1098. c, ok := clients[client_index].(map[string]any)
  1099. if !ok {
  1100. continue
  1101. }
  1102. if c["email"] == clientEmail {
  1103. mutate(c)
  1104. c["updated_at"] = time.Now().Unix() * 1000
  1105. newClients = append(newClients, any(c))
  1106. }
  1107. }
  1108. if len(newClients) == 0 {
  1109. continue
  1110. }
  1111. found = true
  1112. settings["clients"] = newClients
  1113. modifiedSettings, mErr := json.MarshalIndent(settings, "", " ")
  1114. if mErr != nil {
  1115. return needRestart, mErr
  1116. }
  1117. inbound.Settings = string(modifiedSettings)
  1118. nr, uErr := s.UpdateInboundClient(inboundSvc, inbound, clientEmail)
  1119. if uErr != nil {
  1120. return needRestart, uErr
  1121. }
  1122. needRestart = needRestart || nr
  1123. }
  1124. if !found {
  1125. return needRestart, common.NewError("Client Not Found For Email:", clientEmail)
  1126. }
  1127. return needRestart, nil
  1128. }
  1129. func (s *ClientService) ResetClientIpLimitByEmail(inboundSvc *InboundService, clientEmail string, count int) (bool, error) {
  1130. return s.applyClientFieldByEmail(inboundSvc, clientEmail, func(c map[string]any) {
  1131. c["limitIp"] = count
  1132. })
  1133. }
  1134. func (s *ClientService) ResetClientExpiryTimeByEmail(inboundSvc *InboundService, clientEmail string, expiry_time int64) (bool, error) {
  1135. return s.applyClientFieldByEmail(inboundSvc, clientEmail, func(c map[string]any) {
  1136. c["expiryTime"] = expiry_time
  1137. })
  1138. }
  1139. func (s *ClientService) ResetClientTrafficLimitByEmail(inboundSvc *InboundService, clientEmail string, totalGB int) (bool, error) {
  1140. if totalGB < 0 {
  1141. return false, common.NewError("totalGB must be >= 0")
  1142. }
  1143. return s.applyClientFieldByEmail(inboundSvc, clientEmail, func(c map[string]any) {
  1144. c["totalGB"] = totalGB * 1024 * 1024 * 1024
  1145. })
  1146. }