client_inbound_apply.go 45 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466
  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. // droppedClientNeedsRestart is what restartXrayOnClientDisable asks for: the core
  19. // API drops the credential only, so a live session needs the process replaced.
  20. func droppedClientNeedsRestart() bool {
  21. on, err := (&SettingService{}).GetRestartXrayOnClientDisable()
  22. if err != nil {
  23. logger.Warning("get RestartXrayOnClientDisable failed:", err)
  24. }
  25. return on
  26. }
  27. func sameClientConfigExceptUpdatedAt(a, b map[string]any) bool {
  28. aa := maps.Clone(a)
  29. bb := maps.Clone(b)
  30. delete(aa, "updated_at")
  31. delete(bb, "updated_at")
  32. an, aerr := json.Marshal(aa)
  33. bn, berr := json.Marshal(bb)
  34. return aerr == nil && berr == nil && string(an) == string(bn)
  35. }
  36. // advancePushedInbound advances the node's reconcile-skip fingerprint from the
  37. // pre-edit settings to the saved ones after every per-client push succeeded.
  38. func advancePushedInbound(rt runtime.Runtime, prevSettings string, ib *model.Inbound) {
  39. rem, ok := rt.(*runtime.Remote)
  40. if !ok {
  41. return
  42. }
  43. prev := *ib
  44. prev.Settings = prevSettings
  45. rem.AdvancePushedInbound(&prev, ib)
  46. }
  47. // delInboundClients removes several clients from a single inbound in one pass:
  48. // one settings rewrite, one runtime sweep, one Save and one link delta for the
  49. // whole batch, instead of repeating the full per-client cycle. It mirrors the
  50. // semantics of DelInboundClientByEmail for each removed client. needRestart is
  51. // the OR across all removals.
  52. func (s *ClientService) delInboundClients(inboundSvc *InboundService, inboundId int, recs []*model.ClientRecord, keepTraffic bool) (bool, error) {
  53. if len(recs) == 0 {
  54. return false, nil
  55. }
  56. defer lockInbound(inboundId).Unlock()
  57. oldInbound, err := inboundSvc.GetInbound(inboundId)
  58. if err != nil {
  59. logger.Error("Load Old Data Error")
  60. return false, err
  61. }
  62. var settings map[string]any
  63. if err := json.Unmarshal([]byte(oldInbound.Settings), &settings); err != nil {
  64. return false, err
  65. }
  66. // Match by email — the client's stable identity (see Delete). Removes every
  67. // entry carrying a wanted email, independent of credential drift.
  68. wanted := make(map[string]struct{}, len(recs))
  69. for _, rec := range recs {
  70. if rec.Email != "" {
  71. wanted[rec.Email] = struct{}{}
  72. }
  73. }
  74. interfaceClients, ok := settings["clients"].([]any)
  75. if !ok {
  76. return false, common.NewError("invalid clients format in inbound settings")
  77. }
  78. type removedClient struct {
  79. email string
  80. needApiDel bool
  81. }
  82. removed := make([]removedClient, 0, len(wanted))
  83. newClients := make([]any, 0, len(interfaceClients))
  84. for _, client := range interfaceClients {
  85. c, ok := client.(map[string]any)
  86. if !ok {
  87. newClients = append(newClients, client)
  88. continue
  89. }
  90. email, _ := c["email"].(string)
  91. if _, hit := wanted[email]; hit && email != "" {
  92. enable, _ := c["enable"].(bool)
  93. removed = append(removed, removedClient{email: email, needApiDel: enable})
  94. continue
  95. }
  96. newClients = append(newClients, client)
  97. }
  98. if len(removed) == 0 {
  99. return false, nil
  100. }
  101. db := database.GetDB()
  102. newClients = compactOrphans(db, newClients)
  103. if newClients == nil {
  104. newClients = []any{}
  105. }
  106. settings["clients"] = newClients
  107. newSettings, err := json.MarshalIndent(settings, "", " ")
  108. if err != nil {
  109. return false, err
  110. }
  111. prevSettings := oldInbound.Settings
  112. oldInbound.Settings = string(newSettings)
  113. var sharedSet map[string]bool
  114. if !keepTraffic {
  115. removedEmails := make([]string, 0, len(removed))
  116. for _, r := range removed {
  117. if r.email != "" {
  118. removedEmails = append(removedEmails, r.email)
  119. }
  120. }
  121. var sharedErr error
  122. sharedSet, sharedErr = inboundSvc.emailsUsedByOtherInbounds(removedEmails, inboundId)
  123. if sharedErr != nil {
  124. return false, sharedErr
  125. }
  126. }
  127. needRestart := false
  128. // Read each client's live state before the DB write (DelClientStat would
  129. // erase the enable flag we need to decide on a runtime removal).
  130. type delTarget struct {
  131. email string
  132. emailShared bool
  133. notDepleted bool
  134. needApiDel bool
  135. }
  136. targets := make([]delTarget, 0, len(removed))
  137. for _, r := range removed {
  138. email := r.email
  139. emailShared := sharedSet[strings.ToLower(strings.TrimSpace(email))]
  140. notDepleted := false
  141. if len(email) > 0 {
  142. var enables []bool
  143. if err := db.Model(xray.ClientTraffic{}).Where("email = ?", email).Limit(1).Pluck("enable", &enables).Error; err != nil {
  144. logger.Error("Get stats error")
  145. return needRestart, err
  146. }
  147. notDepleted = len(enables) > 0 && enables[0]
  148. }
  149. targets = append(targets, delTarget{email: email, emailShared: emailShared, notDepleted: notDepleted, needApiDel: r.needApiDel})
  150. }
  151. // Persist the batch deletion atomically, serialized against the traffic poll
  152. // to avoid the cross-transaction lock-order deadlock (runSerializedTx).
  153. if txErr := runSerializedTx(func(tx *gorm.DB) error {
  154. for _, t := range targets {
  155. if t.emailShared || keepTraffic {
  156. continue
  157. }
  158. if e := inboundSvc.DelClientIPs(tx, t.email); e != nil {
  159. logger.Error("Error in delete client IPs")
  160. return e
  161. }
  162. if len(t.email) > 0 {
  163. if e := inboundSvc.DelClientStat(tx, t.email); e != nil {
  164. logger.Error("Delete stats Data Error")
  165. return e
  166. }
  167. }
  168. }
  169. if e := tx.Save(oldInbound).Error; e != nil {
  170. return e
  171. }
  172. detached := make([]string, 0, len(targets))
  173. for _, t := range targets {
  174. if t.email != "" {
  175. detached = append(detached, t.email)
  176. }
  177. }
  178. if err := s.ApplyInboundClientDelta(tx, inboundId, nil, detached); err != nil {
  179. return err
  180. }
  181. if oldInbound.NodeID != nil {
  182. return (&NodeService{}).MarkNodeDirtyTx(tx, *oldInbound.NodeID)
  183. }
  184. return nil
  185. }); txErr != nil {
  186. return needRestart, txErr
  187. }
  188. // Resolve the node push plan once for the whole batch instead of per email.
  189. var nodeRt runtime.Runtime
  190. nodePush := false
  191. if oldInbound.NodeID != nil {
  192. rt, push, _, perr := inboundSvc.nodePushPlan(oldInbound)
  193. if perr != nil {
  194. return needRestart, perr
  195. }
  196. nodeRt, nodePush = rt, push
  197. // Large batches collapse into one reconcile push rather than M deletes.
  198. if nodePush && len(targets) > nodeBulkPushThreshold {
  199. nodePush = false
  200. }
  201. }
  202. // Apply runtime deletes after commit — outside the serialized writer so a
  203. // slow node call can't stall traffic accounting.
  204. nodePushFailed := false
  205. for _, t := range targets {
  206. if len(t.email) == 0 {
  207. continue
  208. }
  209. if oldInbound.NodeID == nil {
  210. if t.needApiDel && t.notDepleted {
  211. rt, rterr := inboundSvc.runtimeFor(oldInbound)
  212. if rterr != nil {
  213. needRestart = true
  214. } else if err1 := rt.RemoveUser(context.Background(), oldInbound, t.email); err1 != nil {
  215. if !strings.Contains(err1.Error(), fmt.Sprintf("User %s not found.", t.email)) {
  216. needRestart = true
  217. }
  218. }
  219. }
  220. } else if nodePush && !nodePushFailed {
  221. // First failure ends the batch push; the reconcile converges the rest.
  222. ctx, cancel := nodePushContext()
  223. err1 := nodeRt.DeleteUser(ctx, oldInbound, t.email)
  224. cancel()
  225. if err1 != nil {
  226. logger.Warning("Error in deleting client on", nodeRt.Name(), ":", err1)
  227. nodePushFailed = true
  228. }
  229. }
  230. }
  231. if nodePush && !nodePushFailed {
  232. advancePushedInbound(nodeRt, prevSettings, oldInbound)
  233. }
  234. return needRestart, nil
  235. }
  236. // otherTunnelAllowedIPs maps every AllowedIPs entry claimed on another
  237. // WireGuard/AmneziaWG inbound to a description of which one holds it: the
  238. // per-inbound defaulters only check their own client list, so two inbounds
  239. // sharing a subnet could otherwise hand out the same address. Disabled
  240. // siblings count too, keeping their addresses reserved for a later re-enable.
  241. //
  242. // selfEmails skips this identity's own entries. Email is globally unique, so a
  243. // match there is never a real collision -- and Attach deliberately reuses one
  244. // address across every inbound it attaches the identity to.
  245. func (s *ClientService) otherTunnelAllowedIPs(db *gorm.DB, inboundSvc *InboundService, excludeID int, selfEmails map[string]struct{}) (map[string]string, error) {
  246. var inbounds []*model.Inbound
  247. err := db.Model(model.Inbound{}).
  248. Where("protocol IN ? AND id != ?", []model.Protocol{model.WireGuard, model.AmneziaWG}, excludeID).
  249. Find(&inbounds).Error
  250. if err != nil {
  251. return nil, err
  252. }
  253. used := make(map[string]string)
  254. for _, ib := range inbounds {
  255. clients, cErr := inboundSvc.GetClients(ib)
  256. if cErr != nil {
  257. continue
  258. }
  259. name := ib.Remark
  260. if name == "" {
  261. name = ib.Tag
  262. }
  263. label := fmt.Sprintf("inbound '%s' (#%d)", name, ib.Id)
  264. for _, c := range clients {
  265. if _, self := selfEmails[strings.ToLower(c.Email)]; self {
  266. continue
  267. }
  268. for _, addr := range c.AllowedIPs {
  269. used[addr] = label
  270. }
  271. }
  272. }
  273. return used, nil
  274. }
  275. func (s *ClientService) checkEmailsExistForClients(inboundSvc *InboundService, clients []model.Client) (string, error) {
  276. emailSubIDs, err := inboundSvc.emailSubIDsForClients(clients)
  277. if err != nil {
  278. return "", err
  279. }
  280. seen := make(map[string]string, len(clients))
  281. for _, client := range clients {
  282. if client.Email == "" {
  283. continue
  284. }
  285. key := strings.ToLower(client.Email)
  286. if prev, ok := seen[key]; ok {
  287. if prev != client.SubID || client.SubID == "" {
  288. return client.Email, nil
  289. }
  290. continue
  291. }
  292. seen[key] = client.SubID
  293. if existingSub, ok := emailSubIDs[key]; ok {
  294. if client.SubID == "" || existingSub == "" || existingSub != client.SubID {
  295. return client.Email, nil
  296. }
  297. }
  298. }
  299. return "", nil
  300. }
  301. func (s *ClientService) AddInboundClient(inboundSvc *InboundService, data *model.Inbound) (bool, error) {
  302. defer lockInbound(data.Id).Unlock()
  303. clients, err := inboundSvc.GetClients(data)
  304. if err != nil {
  305. return false, err
  306. }
  307. var settings map[string]any
  308. err = json.Unmarshal([]byte(data.Settings), &settings)
  309. if err != nil {
  310. return false, err
  311. }
  312. interfaceClients := settings["clients"].([]any)
  313. nowTs := time.Now().Unix() * 1000
  314. for i := range interfaceClients {
  315. if cm, ok := interfaceClients[i].(map[string]any); ok {
  316. if _, ok2 := cm["created_at"]; !ok2 {
  317. cm["created_at"] = nowTs
  318. }
  319. cm["updated_at"] = nowTs
  320. existingSub, _ := cm["subId"].(string)
  321. if strings.TrimSpace(existingSub) == "" {
  322. cm["subId"] = random.NumLower(16)
  323. }
  324. interfaceClients[i] = cm
  325. }
  326. }
  327. existEmail, err := s.checkEmailsExistForClients(inboundSvc, clients)
  328. if err != nil {
  329. return false, err
  330. }
  331. if existEmail != "" {
  332. return false, common.NewError("Duplicate email:", existEmail)
  333. }
  334. oldInbound, err := inboundSvc.GetInbound(data.Id)
  335. if err != nil {
  336. return false, err
  337. }
  338. existingClients, err := inboundSvc.GetClients(oldInbound)
  339. if err != nil {
  340. return false, err
  341. }
  342. // A client already on this inbound is skipped instead of appended again:
  343. // checkEmailsExistForClients exempts a matching subId so one identity can
  344. // live on several inbounds, which let retried or raced adds duplicate the
  345. // same email inside a single settings array (#5770). clients and
  346. // interfaceClients are parsed from the same data.Settings array, so they
  347. // stay index-aligned while filtering.
  348. if len(existingClients) > 0 && len(clients) > 0 {
  349. existingEmails := make(map[string]struct{}, len(existingClients))
  350. for _, c := range existingClients {
  351. if c.Email != "" {
  352. existingEmails[strings.ToLower(c.Email)] = struct{}{}
  353. }
  354. }
  355. keptClients := make([]model.Client, 0, len(clients))
  356. keptWire := make([]any, 0, len(interfaceClients))
  357. for i, c := range clients {
  358. if c.Email != "" {
  359. if _, dup := existingEmails[strings.ToLower(c.Email)]; dup {
  360. continue
  361. }
  362. }
  363. keptClients = append(keptClients, c)
  364. if i < len(interfaceClients) {
  365. keptWire = append(keptWire, interfaceClients[i])
  366. }
  367. }
  368. if len(keptClients) == 0 {
  369. return false, nil
  370. }
  371. clients = keptClients
  372. interfaceClients = keptWire
  373. }
  374. var selfEmails map[string]struct{}
  375. if oldInbound.Protocol == model.WireGuard || oldInbound.Protocol == model.AmneziaWG {
  376. selfEmails = make(map[string]struct{}, len(clients))
  377. for _, c := range clients {
  378. if c.Email != "" {
  379. selfEmails[strings.ToLower(c.Email)] = struct{}{}
  380. }
  381. }
  382. crossUsed, cErr := s.otherTunnelAllowedIPs(database.GetDB(), inboundSvc, oldInbound.Id, selfEmails)
  383. if cErr != nil {
  384. return false, cErr
  385. }
  386. if oldInbound.Protocol == model.WireGuard {
  387. if dErr := defaultWireguardClients(oldInbound.Settings, existingClients, clients, interfaceClients, crossUsed); dErr != nil {
  388. return false, dErr
  389. }
  390. }
  391. if oldInbound.Protocol == model.AmneziaWG {
  392. if dErr := defaultAmneziaWGClients(oldInbound.Settings, existingClients, clients, interfaceClients, crossUsed); dErr != nil {
  393. return false, dErr
  394. }
  395. }
  396. }
  397. var portCtx portConflictContext
  398. if oldInbound.Protocol == model.AmneziaWG {
  399. portCtx, err = inboundSvc.loadPortConflictContext(database.GetDB())
  400. if err != nil {
  401. return false, err
  402. }
  403. }
  404. for _, client := range clients {
  405. if strings.TrimSpace(client.Email) == "" {
  406. return false, common.NewError("client email is required")
  407. }
  408. switch oldInbound.Protocol {
  409. case "trojan":
  410. if client.Password == "" {
  411. return false, common.NewError("empty client ID")
  412. }
  413. case "shadowsocks":
  414. if client.Email == "" {
  415. return false, common.NewError("empty client ID")
  416. }
  417. case "hysteria":
  418. if client.Auth == "" {
  419. return false, common.NewError("empty client ID")
  420. }
  421. case "wireguard", "amneziawg":
  422. if client.PublicKey == "" {
  423. return false, common.NewError("wireguard client requires a key")
  424. }
  425. case "mtproto":
  426. if client.Secret == "" {
  427. return false, common.NewError("mtproto client requires a secret")
  428. }
  429. if client.AdTag != "" && !model.ValidMtprotoAdTag(client.AdTag) {
  430. return false, common.NewError("mtproto client ad tag must be 32 hex characters")
  431. }
  432. case "tuic":
  433. if client.ID == "" {
  434. return false, common.NewError("empty client ID")
  435. }
  436. if client.Password == "" {
  437. return false, common.NewError("tuic client requires a password")
  438. }
  439. if client.Email == "" {
  440. return false, common.NewError("empty client email")
  441. }
  442. default:
  443. if client.ID == "" {
  444. return false, common.NewError("empty client ID")
  445. }
  446. }
  447. if oldInbound.Protocol == model.AmneziaWG {
  448. if hit := inboundSvc.checkForwardedPortsConflict(portCtx, client.ForwardedPorts); hit != "" {
  449. return false, common.NewError("amneziawg: forwardedPorts collides with", hit)
  450. }
  451. }
  452. }
  453. var oldSettings map[string]any
  454. err = json.Unmarshal([]byte(oldInbound.Settings), &oldSettings)
  455. if err != nil {
  456. return false, err
  457. }
  458. if oldInbound.Protocol == model.Shadowsocks {
  459. applyShadowsocksClientMethod(interfaceClients, oldSettings)
  460. }
  461. oldClients, _ := oldSettings["clients"].([]any)
  462. oldClients = compactOrphans(database.GetDB(), oldClients)
  463. oldClients = append(oldClients, interfaceClients...)
  464. oldSettings["clients"] = oldClients
  465. newSettings, err := json.MarshalIndent(oldSettings, "", " ")
  466. if err != nil {
  467. return false, err
  468. }
  469. prevSettings := oldInbound.Settings
  470. oldInbound.Settings = string(newSettings)
  471. // From the stamped wire entries, not from clients: created_at / updated_at /
  472. // subId are written onto interfaceClients above, after clients was parsed.
  473. addedClients, err := settingsEntriesToClients(interfaceClients)
  474. if err != nil {
  475. return false, err
  476. }
  477. needRestart := false
  478. rt, push, _, perr := inboundSvc.nodePushPlan(oldInbound)
  479. if perr != nil {
  480. return false, perr
  481. }
  482. // Persist client stats + inbound atomically, serialized against the traffic
  483. // poll to avoid the cross-transaction lock-order deadlock (runSerializedTx).
  484. if txErr := runSerializedTx(func(tx *gorm.DB) error {
  485. // lockInbound is per-inbound, so the pre-tx cross-inbound checks race
  486. // concurrent writers on other inbounds — re-run them in here (#6225).
  487. if oldInbound.Protocol == model.WireGuard || oldInbound.Protocol == model.AmneziaWG {
  488. crossUsed, cErr := s.otherTunnelAllowedIPs(tx, inboundSvc, oldInbound.Id, selfEmails)
  489. if cErr != nil {
  490. return cErr
  491. }
  492. crossAddrs := make([]string, 0, len(crossUsed))
  493. for addr := range crossUsed {
  494. crossAddrs = append(crossAddrs, addr)
  495. }
  496. for i := range clients {
  497. if hit := wireguardAllowedIPsCollision(clients[i].AllowedIPs, crossAddrs); hit != "" {
  498. return common.NewError("allowedIPs entry", hit, "is already used by a client on", crossUsed[hit])
  499. }
  500. }
  501. }
  502. if oldInbound.Protocol == model.AmneziaWG {
  503. txPortCtx, pErr := inboundSvc.loadPortConflictContext(tx)
  504. if pErr != nil {
  505. return pErr
  506. }
  507. for i := range clients {
  508. if hit := inboundSvc.checkForwardedPortsConflict(txPortCtx, clients[i].ForwardedPorts); hit != "" {
  509. return common.NewError("amneziawg: forwardedPorts collides with", hit)
  510. }
  511. }
  512. }
  513. for i := range clients {
  514. if len(clients[i].Email) == 0 {
  515. continue
  516. }
  517. if e := inboundSvc.AddClientStat(tx, data.Id, &clients[i]); e != nil {
  518. return e
  519. }
  520. }
  521. if e := tx.Save(oldInbound).Error; e != nil {
  522. return e
  523. }
  524. if err := s.ApplyInboundClientDelta(tx, oldInbound.Id, addedClients, nil); err != nil {
  525. return err
  526. }
  527. if oldInbound.NodeID != nil {
  528. return (&NodeService{}).MarkNodeDirtyTx(tx, *oldInbound.NodeID)
  529. }
  530. return nil
  531. }); txErr != nil {
  532. return false, txErr
  533. }
  534. // Apply to the running runtime after commit — outside the serialized writer
  535. // so a slow node call can't stall traffic accounting.
  536. if oldInbound.NodeID == nil {
  537. if !push {
  538. needRestart = true
  539. } else if oldInbound.Protocol == model.MTProto {
  540. inboundSvc.applyLocalMtproto(oldInbound.Id)
  541. } else if oldInbound.Protocol == model.AmneziaWG {
  542. inboundSvc.applyLocalAmneziaWG(oldInbound.Id)
  543. } else if oldInbound.Protocol == model.TUIC {
  544. inboundSvc.applyLocalTuic(oldInbound.Id)
  545. } else {
  546. for _, client := range clients {
  547. if len(client.Email) == 0 {
  548. needRestart = true
  549. continue
  550. }
  551. if !client.Enable {
  552. continue
  553. }
  554. cipher := ""
  555. if oldInbound.Protocol == "shadowsocks" {
  556. cipher, _ = oldSettings["method"].(string)
  557. }
  558. err1 := rt.AddUser(context.Background(), oldInbound, map[string]any{
  559. "email": client.Email,
  560. "id": client.ID,
  561. "auth": client.Auth,
  562. "security": client.Security,
  563. "flow": client.Flow,
  564. "password": client.Password,
  565. "cipher": cipher,
  566. "publicKey": client.PublicKey,
  567. "allowedIPs": client.AllowedIPs,
  568. "preSharedKey": client.PreSharedKey,
  569. "keepAlive": keepAliveStr(client.KeepAliveSeconds()),
  570. })
  571. if err1 == nil {
  572. logger.Debug("Client added on", rt.Name(), ":", client.Email)
  573. } else {
  574. logger.Debug("Error in adding client on", rt.Name(), ":", err1)
  575. needRestart = true
  576. }
  577. }
  578. }
  579. } else {
  580. // Large batches would be M sequential per-client RPCs; the inbound's saved
  581. // settings already hold the final set, so mark dirty and let one reconcile
  582. // push converge the node instead.
  583. if push && len(clients) > nodeBulkPushThreshold {
  584. push = false
  585. }
  586. for _, client := range clients {
  587. // /clients/add on the node historically coerced enable=true; skip live
  588. // push for disabled clients and leave dirty so reconcile converges.
  589. if !client.Enable {
  590. push = false
  591. continue
  592. }
  593. if push {
  594. ctx, cancel := nodePushContext()
  595. err1 := rt.AddClient(ctx, oldInbound, client)
  596. cancel()
  597. if err1 != nil {
  598. logger.Warning("Error in adding client on", rt.Name(), ":", err1)
  599. push = false
  600. }
  601. }
  602. }
  603. if push {
  604. advancePushedInbound(rt, prevSettings, oldInbound)
  605. }
  606. }
  607. return needRestart, nil
  608. }
  609. func (s *ClientService) UpdateInboundClient(inboundSvc *InboundService, data *model.Inbound, oldEmail string) (bool, error) {
  610. defer lockInbound(data.Id).Unlock()
  611. clients, err := inboundSvc.GetClients(data)
  612. if err != nil {
  613. return false, err
  614. }
  615. var settings map[string]any
  616. err = json.Unmarshal([]byte(data.Settings), &settings)
  617. if err != nil {
  618. return false, err
  619. }
  620. interfaceClients := settings["clients"].([]any)
  621. oldInbound, err := inboundSvc.GetInbound(data.Id)
  622. if err != nil {
  623. return false, err
  624. }
  625. oldClients, err := inboundSvc.GetClients(oldInbound)
  626. if err != nil {
  627. return false, err
  628. }
  629. newClientId := ""
  630. switch oldInbound.Protocol {
  631. case "trojan":
  632. newClientId = clients[0].Password
  633. case "shadowsocks":
  634. newClientId = clients[0].Email
  635. case "hysteria":
  636. newClientId = clients[0].Auth
  637. case "wireguard", "amneziawg":
  638. newClientId = clients[0].Email
  639. case "mtproto":
  640. newClientId = clients[0].Email
  641. default:
  642. newClientId = clients[0].ID
  643. }
  644. // Locate the client to replace by email — the client's stable identity.
  645. // Credentials (uuid/password/auth) can drift from the inbound JSON, so they
  646. // are never used for matching.
  647. clientIndex := -1
  648. for index, oldClient := range oldClients {
  649. if strings.EqualFold(oldClient.Email, oldEmail) {
  650. oldEmail = oldClient.Email
  651. clientIndex = index
  652. break
  653. }
  654. }
  655. if newClientId == "" || clientIndex == -1 {
  656. return false, common.NewError("empty client ID")
  657. }
  658. if strings.TrimSpace(clients[0].Email) == "" {
  659. return false, common.NewError("client email is required")
  660. }
  661. if oldInbound.Protocol == model.MTProto && clients[0].AdTag != "" && !model.ValidMtprotoAdTag(clients[0].AdTag) {
  662. return false, common.NewError("mtproto client ad tag must be 32 hex characters")
  663. }
  664. if clients[0].Email != oldEmail {
  665. existEmail, err := s.checkEmailsExistForClients(inboundSvc, clients)
  666. if err != nil {
  667. return false, err
  668. }
  669. if existEmail != "" {
  670. return false, common.NewError("Duplicate email:", existEmail)
  671. }
  672. }
  673. // WireGuard/AmneziaWG keys are never rotated by an edit: when the incoming
  674. // payload omits them (a metadata-only change), carry the stored credentials
  675. // forward so the settings JSON and the running peer keep the client's identity.
  676. if (oldInbound.Protocol == model.WireGuard || oldInbound.Protocol == model.AmneziaWG) && clientIndex >= 0 && clientIndex < len(oldClients) {
  677. old := oldClients[clientIndex]
  678. if clients[0].PrivateKey == "" {
  679. clients[0].PrivateKey = old.PrivateKey
  680. }
  681. if clients[0].PublicKey == "" {
  682. clients[0].PublicKey = old.PublicKey
  683. }
  684. if len(clients[0].AllowedIPs) == 0 {
  685. clients[0].AllowedIPs = old.AllowedIPs
  686. } else {
  687. normalized, nErr := normalizeWireguardAllowedIPs(clients[0].AllowedIPs)
  688. if nErr != nil {
  689. return false, nErr
  690. }
  691. if len(normalized) == 0 {
  692. clients[0].AllowedIPs = old.AllowedIPs
  693. } else {
  694. peers := make([]string, 0, len(oldClients))
  695. for i := range oldClients {
  696. if i == clientIndex {
  697. continue
  698. }
  699. peers = append(peers, oldClients[i].AllowedIPs...)
  700. }
  701. if hit := wireguardAllowedIPsCollision(normalized, peers); hit != "" {
  702. return false, common.NewError("wireguard: allowedIPs entry already used by another client:", hit)
  703. }
  704. clients[0].AllowedIPs = normalized
  705. }
  706. }
  707. if clients[0].PreSharedKey == "" {
  708. clients[0].PreSharedKey = old.PreSharedKey
  709. }
  710. if clients[0].KeepAlive == nil {
  711. clients[0].KeepAlive = old.KeepAlive
  712. }
  713. // ForwardedPorts is AmneziaWG-only (WireGuard's own inbound never
  714. // reads it), same carry-forward reasoning as the fields above: a
  715. // partial edit (e.g. a Telegram-bot enable/expiry toggle, or an API
  716. // call that omits the field) must not silently drop a client's
  717. // existing port-forwarding spec.
  718. if oldInbound.Protocol == model.AmneziaWG && clients[0].ForwardedPorts == "" {
  719. clients[0].ForwardedPorts = old.ForwardedPorts
  720. }
  721. }
  722. if oldInbound.Protocol == model.AmneziaWG {
  723. portCtx, err := inboundSvc.loadPortConflictContext(database.GetDB())
  724. if err != nil {
  725. return false, err
  726. }
  727. if hit := inboundSvc.checkForwardedPortsConflict(portCtx, clients[0].ForwardedPorts); hit != "" {
  728. return false, common.NewError("amneziawg: forwardedPorts collides with", hit)
  729. }
  730. }
  731. var oldSettings map[string]any
  732. err = json.Unmarshal([]byte(oldInbound.Settings), &oldSettings)
  733. if err != nil {
  734. return false, err
  735. }
  736. settingsClients, _ := oldSettings["clients"].([]any)
  737. var preservedCreated any
  738. var preservedSubID string
  739. var oldClientMap map[string]any
  740. if clientIndex >= 0 && clientIndex < len(settingsClients) {
  741. if oldMap, ok := settingsClients[clientIndex].(map[string]any); ok {
  742. oldClientMap = oldMap
  743. if v, ok2 := oldMap["created_at"]; ok2 {
  744. preservedCreated = v
  745. }
  746. preservedSubID, _ = oldMap["subId"].(string)
  747. }
  748. }
  749. if oldInbound.Protocol == model.Shadowsocks {
  750. applyShadowsocksClientMethod(interfaceClients, oldSettings)
  751. }
  752. if len(interfaceClients) > 0 {
  753. if newMap, ok := interfaceClients[0].(map[string]any); ok {
  754. if preservedCreated == nil {
  755. preservedCreated = time.Now().Unix() * 1000
  756. }
  757. newMap["created_at"] = preservedCreated
  758. newSub, _ := newMap["subId"].(string)
  759. if strings.TrimSpace(newSub) == "" {
  760. if strings.TrimSpace(preservedSubID) != "" {
  761. newMap["subId"] = preservedSubID
  762. } else {
  763. newMap["subId"] = random.NumLower(16)
  764. }
  765. }
  766. if v, ok2 := newMap["subId"].(string); ok2 {
  767. clients[0].SubID = v
  768. }
  769. if oldInbound.Protocol == model.WireGuard || oldInbound.Protocol == model.AmneziaWG {
  770. newMap["privateKey"] = clients[0].PrivateKey
  771. newMap["publicKey"] = clients[0].PublicKey
  772. newMap["allowedIPs"] = clients[0].AllowedIPs
  773. if clients[0].PreSharedKey != "" {
  774. newMap["preSharedKey"] = clients[0].PreSharedKey
  775. }
  776. if ka := clients[0].KeepAliveSeconds(); ka > 0 {
  777. newMap["keepAlive"] = ka
  778. }
  779. if oldInbound.Protocol == model.AmneziaWG && clients[0].ForwardedPorts != "" {
  780. newMap["forwardedPorts"] = clients[0].ForwardedPorts
  781. }
  782. }
  783. if oldClientMap != nil && sameClientConfigExceptUpdatedAt(oldClientMap, newMap) {
  784. if v, ok2 := oldClientMap["updated_at"]; ok2 {
  785. newMap["updated_at"] = v
  786. } else {
  787. delete(newMap, "updated_at")
  788. }
  789. } else {
  790. newMap["updated_at"] = time.Now().Unix() * 1000
  791. }
  792. interfaceClients[0] = newMap
  793. }
  794. }
  795. settingsClients[clientIndex] = interfaceClients[0]
  796. oldSettings["clients"] = settingsClients
  797. if oldInbound.Protocol == model.VLESS {
  798. hasVisionFlow := false
  799. for _, c := range settingsClients {
  800. cm, ok := c.(map[string]any)
  801. if !ok {
  802. continue
  803. }
  804. if flow, _ := cm["flow"].(string); flow == "xtls-rprx-vision" {
  805. hasVisionFlow = true
  806. break
  807. }
  808. }
  809. if !hasVisionFlow {
  810. delete(oldSettings, "testseed")
  811. }
  812. }
  813. newSettings, err := json.MarshalIndent(oldSettings, "", " ")
  814. if err != nil {
  815. return false, err
  816. }
  817. if string(newSettings) == oldInbound.Settings {
  818. return false, nil
  819. }
  820. prevSettings := oldInbound.Settings
  821. oldInbound.Settings = string(newSettings)
  822. // From the stamped wire entry, not from clients[0]: created_at, the
  823. // preserved subId and the WireGuard carry-forward land on interfaceClients.
  824. changedClients, err := settingsEntriesToClients(interfaceClients[:1])
  825. if err != nil {
  826. return false, err
  827. }
  828. var detachEmails []string
  829. if len(oldEmail) > 0 && oldEmail != clients[0].Email {
  830. detachEmails = []string{oldEmail}
  831. }
  832. needRestart := false
  833. // Resolve the push plan before the DB write so a node-state lookup failure
  834. // still aborts the whole update without committing anything (it used to roll
  835. // the transaction back). nodePushPlan only reads, so order doesn't matter.
  836. var rt runtime.Runtime
  837. var push bool
  838. if len(oldEmail) > 0 {
  839. var perr error
  840. rt, push, _, perr = inboundSvc.nodePushPlan(oldInbound)
  841. if perr != nil {
  842. return false, perr
  843. }
  844. }
  845. // Persist client stats + inbound atomically, serialized against the traffic
  846. // poll to avoid the cross-transaction lock-order deadlock (runSerializedTx).
  847. if txErr := runSerializedTx(func(tx *gorm.DB) error {
  848. // Same re-check-inside-the-writer rule as AddInboundClient (#6225):
  849. // the pre-tx pass can race a concurrent writer on another inbound.
  850. if oldInbound.Protocol == model.AmneziaWG {
  851. txPortCtx, pErr := inboundSvc.loadPortConflictContext(tx)
  852. if pErr != nil {
  853. return pErr
  854. }
  855. if hit := inboundSvc.checkForwardedPortsConflict(txPortCtx, clients[0].ForwardedPorts); hit != "" {
  856. return common.NewError("amneziawg: forwardedPorts collides with", hit)
  857. }
  858. }
  859. if len(clients[0].Email) > 0 {
  860. if len(oldEmail) > 0 {
  861. emailUnchanged := strings.EqualFold(oldEmail, clients[0].Email)
  862. targetExists := int64(0)
  863. if !emailUnchanged {
  864. if e := tx.Model(xray.ClientTraffic{}).Where("email = ?", clients[0].Email).Count(&targetExists).Error; e != nil {
  865. return e
  866. }
  867. }
  868. if emailUnchanged || targetExists == 0 {
  869. if e := inboundSvc.UpdateClientStat(tx, oldEmail, &clients[0]); e != nil {
  870. return e
  871. }
  872. if e := inboundSvc.UpdateClientIPs(tx, oldEmail, clients[0].Email); e != nil {
  873. return e
  874. }
  875. } else {
  876. stillUsed, sErr := inboundSvc.emailUsedByOtherInbounds(oldEmail, data.Id)
  877. if sErr != nil {
  878. return sErr
  879. }
  880. if !stillUsed {
  881. if e := inboundSvc.DelClientStat(tx, oldEmail); e != nil {
  882. return e
  883. }
  884. if e := inboundSvc.DelClientIPs(tx, oldEmail); e != nil {
  885. return e
  886. }
  887. }
  888. if e := inboundSvc.UpdateClientStat(tx, clients[0].Email, &clients[0]); e != nil {
  889. return e
  890. }
  891. }
  892. } else {
  893. if e := inboundSvc.AddClientStat(tx, data.Id, &clients[0]); e != nil {
  894. return e
  895. }
  896. }
  897. } else {
  898. stillUsed, sErr := inboundSvc.emailUsedByOtherInbounds(oldEmail, data.Id)
  899. if sErr != nil {
  900. return sErr
  901. }
  902. if !stillUsed {
  903. if e := inboundSvc.DelClientStat(tx, oldEmail); e != nil {
  904. return e
  905. }
  906. if e := inboundSvc.DelClientIPs(tx, oldEmail); e != nil {
  907. return e
  908. }
  909. }
  910. }
  911. if e := tx.Save(oldInbound).Error; e != nil {
  912. return e
  913. }
  914. // Rename the client record in the same transaction as the settings JSON
  915. // so no concurrent SyncInbound can see one renamed without the other.
  916. // Byte-level compare (not EqualFold): case-only edits must rename too,
  917. // otherwise SyncInbound's case-sensitive lookup creates a duplicate row.
  918. if len(oldEmail) > 0 && oldEmail != clients[0].Email {
  919. var renameTaken int64
  920. if e := tx.Model(&model.ClientRecord{}).Where("email = ?", clients[0].Email).Count(&renameTaken).Error; e != nil {
  921. return e
  922. }
  923. if renameTaken == 0 {
  924. if e := tx.Model(&model.ClientRecord{}).Where("email = ?", oldEmail).Update("email", clients[0].Email).Error; e != nil {
  925. return e
  926. }
  927. }
  928. }
  929. // detachEmails covers the rename the guard above refused: the old record
  930. // keeps this inbound's link otherwise, which the full sync used to drop.
  931. if err := s.ApplyInboundClientDelta(tx, oldInbound.Id, changedClients, detachEmails); err != nil {
  932. return err
  933. }
  934. if oldInbound.NodeID != nil {
  935. return (&NodeService{}).MarkNodeDirtyTx(tx, *oldInbound.NodeID)
  936. }
  937. return nil
  938. }); txErr != nil {
  939. return false, txErr
  940. }
  941. // Apply to the running runtime after the DB is committed — outside the
  942. // serialized writer so a slow node call can't stall traffic accounting.
  943. if len(oldEmail) > 0 {
  944. if oldInbound.NodeID == nil {
  945. if !push {
  946. needRestart = true
  947. } else if oldInbound.Protocol == model.MTProto {
  948. inboundSvc.applyLocalMtproto(oldInbound.Id)
  949. } else if oldInbound.Protocol == model.AmneziaWG {
  950. inboundSvc.applyLocalAmneziaWG(oldInbound.Id)
  951. } else if oldInbound.Protocol == model.TUIC {
  952. inboundSvc.applyLocalTuic(oldInbound.Id)
  953. } else {
  954. if oldClients[clientIndex].Enable {
  955. err1 := rt.RemoveUser(context.Background(), oldInbound, oldEmail)
  956. if err1 == nil {
  957. logger.Debug("Old client deleted on", rt.Name(), ":", oldEmail)
  958. // The API removal is enough only while the client is re-added; a
  959. // dropped one ends its session only through a restart.
  960. if !clients[0].Enable && droppedClientNeedsRestart() {
  961. needRestart = true
  962. }
  963. } else if strings.Contains(err1.Error(), fmt.Sprintf("User %s not found.", oldEmail)) {
  964. logger.Debug("User is already deleted. Nothing to do more...")
  965. } else {
  966. logger.Debug("Error in deleting client on", rt.Name(), ":", err1)
  967. needRestart = true
  968. }
  969. }
  970. if clients[0].Enable {
  971. cipher := ""
  972. if oldInbound.Protocol == "shadowsocks" {
  973. cipher, _ = oldSettings["method"].(string)
  974. }
  975. err1 := rt.AddUser(context.Background(), oldInbound, map[string]any{
  976. "email": clients[0].Email,
  977. "id": clients[0].ID,
  978. "security": clients[0].Security,
  979. "flow": clients[0].Flow,
  980. "auth": clients[0].Auth,
  981. "password": clients[0].Password,
  982. "cipher": cipher,
  983. "publicKey": clients[0].PublicKey,
  984. "allowedIPs": clients[0].AllowedIPs,
  985. "preSharedKey": clients[0].PreSharedKey,
  986. "keepAlive": keepAliveStr(clients[0].KeepAliveSeconds()),
  987. })
  988. if err1 == nil {
  989. logger.Debug("Client edited on", rt.Name(), ":", clients[0].Email)
  990. } else {
  991. logger.Debug("Error in adding client on", rt.Name(), ":", err1)
  992. needRestart = true
  993. }
  994. }
  995. }
  996. } else if push {
  997. ctx, cancel := nodePushContext()
  998. err1 := rt.UpdateUser(ctx, oldInbound, oldEmail, clients[0])
  999. cancel()
  1000. if err1 != nil {
  1001. logger.Warning("Error in updating client on", rt.Name(), ":", err1)
  1002. } else {
  1003. advancePushedInbound(rt, prevSettings, oldInbound)
  1004. }
  1005. }
  1006. } else {
  1007. logger.Debug("Client old email not found")
  1008. needRestart = true
  1009. }
  1010. return needRestart, nil
  1011. }
  1012. func (s *ClientService) DelInboundClientByEmail(inboundSvc *InboundService, inboundId int, email string, keepTraffic bool, fullDelete bool) (bool, error) {
  1013. defer lockInbound(inboundId).Unlock()
  1014. oldInbound, err := inboundSvc.GetInbound(inboundId)
  1015. if err != nil {
  1016. logger.Error("Load Old Data Error")
  1017. return false, err
  1018. }
  1019. var settings map[string]any
  1020. if err := json.Unmarshal([]byte(oldInbound.Settings), &settings); err != nil {
  1021. return false, err
  1022. }
  1023. interfaceClients, ok := settings["clients"].([]any)
  1024. if !ok {
  1025. return false, common.NewError("invalid clients format in inbound settings")
  1026. }
  1027. var newClients []any
  1028. needApiDel := false
  1029. found := false
  1030. for _, client := range interfaceClients {
  1031. c, ok := client.(map[string]any)
  1032. if !ok {
  1033. continue
  1034. }
  1035. if cEmail, ok := c["email"].(string); ok && cEmail == email {
  1036. found = true
  1037. needApiDel, _ = c["enable"].(bool)
  1038. } else {
  1039. newClients = append(newClients, client)
  1040. }
  1041. }
  1042. if !found {
  1043. return false, fmt.Errorf("%w for email: %s", ErrClientNotInInbound, email)
  1044. }
  1045. db := database.GetDB()
  1046. newClients = compactOrphans(db, newClients)
  1047. if newClients == nil {
  1048. newClients = []any{}
  1049. }
  1050. settings["clients"] = newClients
  1051. newSettings, err := json.MarshalIndent(settings, "", " ")
  1052. if err != nil {
  1053. return false, err
  1054. }
  1055. prevSettings := oldInbound.Settings
  1056. oldInbound.Settings = string(newSettings)
  1057. emailShared, err := inboundSvc.emailUsedByOtherInbounds(email, inboundId)
  1058. if err != nil {
  1059. return false, err
  1060. }
  1061. needRestart := false
  1062. // Decide what to delete and the push plan before the serialized DB write —
  1063. // these are reads, and nodePushPlan failing should abort before committing.
  1064. delStat := false
  1065. if len(email) > 0 && !emailShared && !keepTraffic {
  1066. traffic, tErr := inboundSvc.GetClientTrafficByEmail(email)
  1067. if tErr != nil {
  1068. return false, tErr
  1069. }
  1070. delStat = traffic != nil
  1071. }
  1072. // The runtime user is scoped to this inbound's tag + email, so the push plan
  1073. // is resolved independently of emailShared — a sibling inbound still carrying
  1074. // the email must not suppress removing the user from this inbound's Xray.
  1075. var rt runtime.Runtime
  1076. var push bool
  1077. if len(email) > 0 && (oldInbound.NodeID != nil || needApiDel) {
  1078. r, p, _, perr := inboundSvc.nodePushPlan(oldInbound)
  1079. if perr != nil {
  1080. return false, perr
  1081. }
  1082. rt, push = r, p
  1083. }
  1084. // Persist the deletion atomically, serialized against the traffic poll to
  1085. // avoid the cross-transaction lock-order deadlock (runSerializedTx).
  1086. if txErr := runSerializedTx(func(tx *gorm.DB) error {
  1087. if !emailShared && !keepTraffic {
  1088. if e := inboundSvc.DelClientIPs(tx, email); e != nil {
  1089. logger.Error("Error in delete client IPs")
  1090. return e
  1091. }
  1092. }
  1093. if delStat {
  1094. if e := inboundSvc.DelClientStat(tx, email); e != nil {
  1095. logger.Error("Delete stats Data Error")
  1096. return e
  1097. }
  1098. }
  1099. if e := tx.Save(oldInbound).Error; e != nil {
  1100. return e
  1101. }
  1102. if err := s.ApplyInboundClientDelta(tx, inboundId, nil, []string{email}); err != nil {
  1103. return err
  1104. }
  1105. if oldInbound.NodeID != nil {
  1106. return (&NodeService{}).MarkNodeDirtyTx(tx, *oldInbound.NodeID)
  1107. }
  1108. return nil
  1109. }); txErr != nil {
  1110. return false, txErr
  1111. }
  1112. // Apply the runtime delete after commit — outside the serialized writer so a
  1113. // slow node call can't stall traffic accounting. Independent of emailShared:
  1114. // Xray users are keyed by inbound tag, so the user must be removed from this
  1115. // inbound's runtime even when the same email survives in another inbound.
  1116. if len(email) > 0 {
  1117. if oldInbound.NodeID == nil {
  1118. if oldInbound.Protocol == model.MTProto {
  1119. // mtg serves the full secret set, so any client delete re-applies
  1120. // it (removing the last client stops the sidecar) regardless of the
  1121. // client's enable state.
  1122. inboundSvc.applyLocalMtproto(oldInbound.Id)
  1123. } else if oldInbound.Protocol == model.AmneziaWG {
  1124. // Same reasoning as MTProto above: the interface config is
  1125. // regenerated from the full peer set, so any delete re-applies it.
  1126. inboundSvc.applyLocalAmneziaWG(oldInbound.Id)
  1127. } else if oldInbound.Protocol == model.TUIC {
  1128. inboundSvc.applyLocalTuic(oldInbound.Id)
  1129. } else if needApiDel {
  1130. // Local inbound: a disabled client isn't in the running Xray, so only
  1131. // a live one (needApiDel) needs an API removal.
  1132. if !push {
  1133. needRestart = true
  1134. } else if err1 := rt.RemoveUser(context.Background(), oldInbound, email); err1 == nil {
  1135. logger.Debug("Client deleted on", rt.Name(), ":", email)
  1136. needRestart = droppedClientNeedsRestart()
  1137. } else if strings.Contains(err1.Error(), fmt.Sprintf("User %s not found.", email)) {
  1138. logger.Debug("User is already deleted. Nothing to do more...")
  1139. } else {
  1140. logger.Debug("Error in deleting client on", rt.Name(), ":", email)
  1141. needRestart = true
  1142. }
  1143. }
  1144. } else {
  1145. // Node inbound: propagate the delete regardless of the enable flag —
  1146. // the node's own DB still carries a disabled client and would
  1147. // resurrect it on the next snapshot otherwise. A full client delete
  1148. // must remove the node's client record too, not just detach it from
  1149. // this inbound (#5797).
  1150. if push {
  1151. ctx, cancel := nodePushContext()
  1152. var err1 error
  1153. if fullDelete {
  1154. err1 = rt.DeleteClient(ctx, email)
  1155. } else {
  1156. err1 = rt.DeleteUser(ctx, oldInbound, email)
  1157. }
  1158. cancel()
  1159. if err1 != nil {
  1160. logger.Warning("Error in deleting client on", rt.Name(), ":", err1)
  1161. } else {
  1162. advancePushedInbound(rt, prevSettings, oldInbound)
  1163. }
  1164. }
  1165. }
  1166. }
  1167. return needRestart, nil
  1168. }
  1169. func (s *ClientService) SetClientTelegramUserID(inboundSvc *InboundService, trafficId int, tgId int64) (bool, error) {
  1170. traffic, inbound, err := inboundSvc.GetClientInboundByTrafficID(trafficId)
  1171. if err != nil {
  1172. return false, err
  1173. }
  1174. if inbound == nil {
  1175. return false, common.NewError("Inbound Not Found For Traffic ID:", trafficId)
  1176. }
  1177. clientEmail := traffic.Email
  1178. oldClients, err := inboundSvc.GetClients(inbound)
  1179. if err != nil {
  1180. return false, err
  1181. }
  1182. found := false
  1183. for _, oldClient := range oldClients {
  1184. if oldClient.Email == clientEmail {
  1185. found = true
  1186. break
  1187. }
  1188. }
  1189. if !found {
  1190. return false, common.NewError("Client Not Found For Email:", clientEmail)
  1191. }
  1192. var settings map[string]any
  1193. err = json.Unmarshal([]byte(inbound.Settings), &settings)
  1194. if err != nil {
  1195. return false, err
  1196. }
  1197. clients := settings["clients"].([]any)
  1198. var newClients []any
  1199. for client_index := range clients {
  1200. c := clients[client_index].(map[string]any)
  1201. if c["email"] == clientEmail {
  1202. c["tgId"] = tgId
  1203. c["updated_at"] = time.Now().Unix() * 1000
  1204. newClients = append(newClients, any(c))
  1205. }
  1206. }
  1207. settings["clients"] = newClients
  1208. modifiedSettings, err := json.MarshalIndent(settings, "", " ")
  1209. if err != nil {
  1210. return false, err
  1211. }
  1212. inbound.Settings = string(modifiedSettings)
  1213. needRestart, err := s.UpdateInboundClient(inboundSvc, inbound, clientEmail)
  1214. return needRestart, err
  1215. }
  1216. func (s *ClientService) CheckIsEnabledByEmail(inboundSvc *InboundService, clientEmail string) (bool, error) {
  1217. _, inbound, err := inboundSvc.GetClientInboundByEmail(clientEmail)
  1218. if err != nil {
  1219. return false, err
  1220. }
  1221. if inbound == nil {
  1222. return false, common.NewError("Inbound Not Found For Email:", clientEmail)
  1223. }
  1224. clients, err := inboundSvc.GetClients(inbound)
  1225. if err != nil {
  1226. return false, err
  1227. }
  1228. isEnable := false
  1229. for _, client := range clients {
  1230. if client.Email == clientEmail {
  1231. isEnable = client.Enable
  1232. break
  1233. }
  1234. }
  1235. return isEnable, err
  1236. }
  1237. func (s *ClientService) ToggleClientEnableByEmail(inboundSvc *InboundService, clientEmail string) (bool, bool, error) {
  1238. current, err := s.CheckIsEnabledByEmail(inboundSvc, clientEmail)
  1239. if err != nil {
  1240. return false, false, err
  1241. }
  1242. target := !current
  1243. needRestart, err := s.applyClientFieldByEmail(inboundSvc, clientEmail, func(c map[string]any) {
  1244. c["enable"] = target
  1245. })
  1246. if err != nil {
  1247. return false, needRestart, err
  1248. }
  1249. return target, needRestart, nil
  1250. }
  1251. func (s *ClientService) SetClientEnableByEmail(inboundSvc *InboundService, clientEmail string, enable bool) (bool, bool, error) {
  1252. current, err := s.CheckIsEnabledByEmail(inboundSvc, clientEmail)
  1253. if err != nil {
  1254. return false, false, err
  1255. }
  1256. if current == enable {
  1257. return false, false, nil
  1258. }
  1259. needRestart, err := s.applyClientFieldByEmail(inboundSvc, clientEmail, func(c map[string]any) {
  1260. c["enable"] = enable
  1261. })
  1262. if err != nil {
  1263. return false, needRestart, err
  1264. }
  1265. return true, needRestart, nil
  1266. }
  1267. // applyClientFieldByEmail loads the inbound currently hosting clientEmail,
  1268. // confirms the client exists, applies mutate to the matching client (plus a
  1269. // refreshed updated_at), and hands a single-client update payload to
  1270. // UpdateInboundClient. The rebuilt clients array intentionally contains only
  1271. // the matched client — that is the input contract UpdateInboundClient expects
  1272. // (clients[0] is the new data; clientEmail locates the row to replace). It
  1273. // backs the single-field by-email setters below.
  1274. // applyClientFieldByEmail mutates a client field on every inbound the email is
  1275. // attached to. A multi-inbound client is one logical identity: patching only
  1276. // the first inbound's JSON would leave the siblings stale, and the next
  1277. // SyncInbound over a stale sibling would revert the edit in the normalized
  1278. // records (#5039).
  1279. func (s *ClientService) applyClientFieldByEmail(inboundSvc *InboundService, clientEmail string, mutate func(c map[string]any)) (bool, error) {
  1280. inboundIds, err := s.GetInboundIdsForEmail(database.GetDB(), clientEmail)
  1281. if err != nil {
  1282. return false, err
  1283. }
  1284. if len(inboundIds) == 0 {
  1285. // Legacy fallback for clients that only live in the inbound JSON and
  1286. // were never normalized into client_inbounds.
  1287. _, inbound, gErr := inboundSvc.GetClientInboundByEmail(clientEmail)
  1288. if gErr != nil {
  1289. return false, gErr
  1290. }
  1291. if inbound == nil {
  1292. return false, common.NewError("Inbound Not Found For Email:", clientEmail)
  1293. }
  1294. inboundIds = []int{inbound.Id}
  1295. }
  1296. needRestart := false
  1297. found := false
  1298. // Built before any inbound is written, as in Update: only the applies
  1299. // overlap, so one node's round-trip no longer waits on the previous one.
  1300. applies := make([]inboundApply, 0, len(inboundIds))
  1301. for _, ibId := range inboundIds {
  1302. inbound, gErr := inboundSvc.GetInbound(ibId)
  1303. if gErr != nil {
  1304. return needRestart, gErr
  1305. }
  1306. var settings map[string]any
  1307. if uErr := json.Unmarshal([]byte(inbound.Settings), &settings); uErr != nil {
  1308. return needRestart, uErr
  1309. }
  1310. clients, _ := settings["clients"].([]any)
  1311. // UpdateInboundClient expects a single-client payload, so keep only the
  1312. // matching entry in the scratch copy; it splices the result back into
  1313. // the inbound's full client list itself.
  1314. var newClients []any
  1315. for client_index := range clients {
  1316. c, ok := clients[client_index].(map[string]any)
  1317. if !ok {
  1318. continue
  1319. }
  1320. if c["email"] == clientEmail {
  1321. mutate(c)
  1322. c["updated_at"] = time.Now().Unix() * 1000
  1323. newClients = append(newClients, any(c))
  1324. }
  1325. }
  1326. if len(newClients) == 0 {
  1327. continue
  1328. }
  1329. found = true
  1330. settings["clients"] = newClients
  1331. modifiedSettings, mErr := json.MarshalIndent(settings, "", " ")
  1332. if mErr != nil {
  1333. return needRestart, mErr
  1334. }
  1335. inbound.Settings = string(modifiedSettings)
  1336. data := inbound
  1337. applies = append(applies, inboundApply{id: ibId, run: func() (bool, error) {
  1338. return s.UpdateInboundClient(inboundSvc, data, clientEmail)
  1339. }})
  1340. }
  1341. if !found {
  1342. return needRestart, common.NewError("Client Not Found For Email:", clientEmail)
  1343. }
  1344. nr, applyErr := fanoutInboundApplies(applies)
  1345. return needRestart || nr, applyErr
  1346. }
  1347. func (s *ClientService) ResetClientIpLimitByEmail(inboundSvc *InboundService, clientEmail string, count int) (bool, error) {
  1348. return s.applyClientFieldByEmail(inboundSvc, clientEmail, func(c map[string]any) {
  1349. c["limitIp"] = count
  1350. })
  1351. }
  1352. func (s *ClientService) ResetClientExpiryTimeByEmail(inboundSvc *InboundService, clientEmail string, expiry_time int64) (bool, error) {
  1353. return s.applyClientFieldByEmail(inboundSvc, clientEmail, func(c map[string]any) {
  1354. c["expiryTime"] = expiry_time
  1355. })
  1356. }
  1357. func (s *ClientService) ResetClientTrafficLimitByEmail(inboundSvc *InboundService, clientEmail string, totalGB int) (bool, error) {
  1358. if totalGB < 0 {
  1359. return false, common.NewError("totalGB must be >= 0")
  1360. }
  1361. return s.applyClientFieldByEmail(inboundSvc, clientEmail, func(c map[string]any) {
  1362. c["totalGB"] = totalGB * 1024 * 1024 * 1024
  1363. })
  1364. }