client_inbound_apply.go 31 KB

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