client_inbound_apply.go 34 KB

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