client_inbound_apply.go 45 KB

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