inbound_disable.go 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296
  1. package service
  2. import (
  3. "context"
  4. "encoding/json"
  5. "fmt"
  6. "slices"
  7. "strings"
  8. "time"
  9. "github.com/mhsanaei/3x-ui/v3/internal/database/model"
  10. "github.com/mhsanaei/3x-ui/v3/internal/logger"
  11. "github.com/mhsanaei/3x-ui/v3/internal/xray"
  12. "gorm.io/gorm"
  13. )
  14. func (s *InboundService) disableInvalidInbounds(tx *gorm.DB) (bool, int64, error) {
  15. now := time.Now().Unix() * 1000
  16. needRestart := false
  17. if p != nil {
  18. var tags []string
  19. err := tx.Table("inbounds").
  20. Select("inbounds.tag").
  21. Where("((total > 0 and up + down >= total) or (expiry_time > 0 and expiry_time <= ?)) and enable = ? and node_id IS NULL", now, true).
  22. Scan(&tags).Error
  23. if err != nil {
  24. return false, 0, err
  25. }
  26. _ = s.xrayApi.Init(p.GetAPIPort())
  27. for _, tag := range tags {
  28. err1 := s.xrayApi.DelInbound(tag)
  29. if err1 == nil {
  30. logger.Debug("Inbound disabled by api:", tag)
  31. } else {
  32. logger.Debug("Error in disabling inbound by api:", err1)
  33. needRestart = true
  34. }
  35. }
  36. s.xrayApi.Close()
  37. }
  38. result := tx.Model(model.Inbound{}).
  39. Where("((total > 0 and up + down >= total) or (expiry_time > 0 and expiry_time <= ?)) and enable = ? and node_id IS NULL", now, true).
  40. Update("enable", false)
  41. err := result.Error
  42. count := result.RowsAffected
  43. return needRestart, count, err
  44. }
  45. // globalTrafficFreshWindow bounds how long a pushed client_global_traffics row
  46. // stays authoritative. Masters refresh their rows every nodeGlobalPushInterval
  47. // (30s), so a row older than this belongs to a master that stopped pushing —
  48. // decommissioned, reinstalled under a new GUID, or detached from this node.
  49. // Such a row keeps its last-seen counters forever, and without this bound a
  50. // long-dead master's numbers permanently trip the cross-panel quota check and
  51. // disable clients that are nowhere near their limit (#6113). The window is far
  52. // wider than any real push gap, so a master that is merely unreachable for a
  53. // while keeps enforcing.
  54. const globalTrafficFreshWindow = 24 * time.Hour
  55. func globalTrafficFreshSince() int64 {
  56. return time.Now().Add(-globalTrafficFreshWindow).UnixMilli()
  57. }
  58. // depletedClientsCond matches clients that exhausted their quota or expired.
  59. // Besides the local counters it also trips on the cross-panel usage a master
  60. // pushed into client_global_traffics — that's what lets a node cut a client
  61. // whose combined usage exceeds the quota even though the local share doesn't.
  62. // Only rows a master refreshed recently count (placeholders: now, freshSince).
  63. const depletedClientsCond = `((total > 0 AND up + down >= total)
  64. OR (expiry_time > 0 AND expiry_time <= ?)
  65. OR (total > 0 AND EXISTS (
  66. SELECT 1 FROM client_global_traffics g
  67. WHERE g.email = client_traffics.email
  68. AND g.updated_at >= ?
  69. AND g.up + g.down >= client_traffics.total
  70. )))`
  71. // depletedClientsCondLocal is depletedClientsCond without the cross-panel
  72. // client_global_traffics check. The EXISTS branch is a correlated subquery that
  73. // turns every traffic poll into a full client_traffics scan; on a panel no
  74. // master pushes to (the common case) client_global_traffics is empty, so the
  75. // branch can never match and is pure CPU cost (#5392). Placeholders: now.
  76. const depletedClientsCondLocal = `((total > 0 AND up + down >= total)
  77. OR (expiry_time > 0 AND expiry_time <= ?))`
  78. // depletedCond returns the predicate matching depleted clients together with
  79. // the arguments it binds. The local-only variant is used unless this panel
  80. // holds a global-traffic row a master still refreshes, in which case the
  81. // cross-panel EXISTS check is needed to enforce combined quota.
  82. func depletedCond(tx *gorm.DB) (string, []any) {
  83. now := time.Now().UnixMilli()
  84. freshSince := globalTrafficFreshSince()
  85. var probe int64
  86. err := tx.Model(&model.ClientGlobalTraffic{}).
  87. Where("updated_at >= ?", freshSince).
  88. Limit(1).Count(&probe).Error
  89. if err == nil && probe > 0 {
  90. return depletedClientsCond, []any{now, freshSince}
  91. }
  92. return depletedClientsCondLocal, []any{now}
  93. }
  94. func (s *InboundService) disableInvalidClients(tx *gorm.DB) (bool, int64, error) {
  95. needRestart := false
  96. cond, condArgs := depletedCond(tx)
  97. var depletedRows []xray.ClientTraffic
  98. err := tx.Model(xray.ClientTraffic{}).
  99. Where(cond+" AND enable = ?", append(condArgs, true)...).
  100. Find(&depletedRows).Error
  101. if err != nil {
  102. return false, 0, err
  103. }
  104. if len(depletedRows) == 0 {
  105. return false, 0, nil
  106. }
  107. depletedEmails := make([]string, 0, len(depletedRows))
  108. for i := range depletedRows {
  109. if depletedRows[i].Email == "" {
  110. continue
  111. }
  112. depletedEmails = append(depletedEmails, depletedRows[i].Email)
  113. }
  114. type target struct {
  115. InboundID int `gorm:"column:inbound_id"`
  116. NodeID *int `gorm:"column:node_id"`
  117. Tag string
  118. Email string
  119. }
  120. var targets []target
  121. if len(depletedEmails) > 0 {
  122. err = tx.Raw(`
  123. SELECT inbounds.id AS inbound_id, inbounds.node_id AS node_id,
  124. inbounds.tag AS tag, clients.email AS email
  125. FROM clients
  126. JOIN client_inbounds ON client_inbounds.client_id = clients.id
  127. JOIN inbounds ON inbounds.id = client_inbounds.inbound_id
  128. WHERE clients.email IN ?
  129. `, depletedEmails).Scan(&targets).Error
  130. if err != nil {
  131. return false, 0, err
  132. }
  133. }
  134. var localTargets []target
  135. localByInbound := make(map[int]map[string]struct{})
  136. remoteByInbound := make(map[int][]target)
  137. for _, t := range targets {
  138. if t.NodeID == nil {
  139. localTargets = append(localTargets, t)
  140. if localByInbound[t.InboundID] == nil {
  141. localByInbound[t.InboundID] = make(map[string]struct{})
  142. }
  143. localByInbound[t.InboundID][t.Email] = struct{}{}
  144. } else {
  145. remoteByInbound[t.InboundID] = append(remoteByInbound[t.InboundID], t)
  146. }
  147. }
  148. if p != nil && len(localTargets) > 0 {
  149. _ = s.xrayApi.Init(p.GetAPIPort())
  150. for _, t := range localTargets {
  151. err1 := s.xrayApi.RemoveUser(t.Tag, t.Email)
  152. if err1 == nil {
  153. logger.Debug("Client disabled by api:", t.Email)
  154. } else if strings.Contains(err1.Error(), fmt.Sprintf("User %s not found.", t.Email)) {
  155. logger.Debug("User is already disabled. Nothing to do more...")
  156. } else {
  157. logger.Debug("Error in disabling client by api:", err1)
  158. needRestart = true
  159. }
  160. }
  161. s.xrayApi.Close()
  162. }
  163. for inboundID, emails := range localByInbound {
  164. if _, _, mErr := s.markClientsDisabledInSettings(tx, inboundID, emails); mErr != nil {
  165. logger.Warning("disableInvalidClients: settings.JSON sync failed for inbound", inboundID, ":", mErr)
  166. }
  167. }
  168. // Flip the rows already collected above by primary key instead of
  169. // re-evaluating the depleted predicate, which was a second full scan of
  170. // client_traffics on every poll. Sorted ids keep the lock order stable.
  171. ids := make([]int, 0, len(depletedRows))
  172. for i := range depletedRows {
  173. ids = append(ids, depletedRows[i].Id)
  174. }
  175. slices.Sort(ids)
  176. var count int64
  177. for _, batch := range chunkInts(ids, sqlInChunk) {
  178. result := tx.Model(xray.ClientTraffic{}).
  179. Where("id IN ? AND enable = ?", batch, true).
  180. Update("enable", false)
  181. if result.Error != nil {
  182. return needRestart, count, result.Error
  183. }
  184. count += result.RowsAffected
  185. }
  186. if len(depletedEmails) > 0 {
  187. if err := tx.Model(&model.ClientRecord{}).
  188. Where("email IN ?", depletedEmails).
  189. Updates(map[string]any{"enable": false, "updated_at": time.Now().UnixMilli()}).Error; err != nil {
  190. logger.Warning("disableInvalidClients update clients.enable:", err)
  191. }
  192. }
  193. for inboundID, group := range remoteByInbound {
  194. emails := make(map[string]struct{}, len(group))
  195. for _, t := range group {
  196. emails[t.Email] = struct{}{}
  197. }
  198. if pushErr := s.disableRemoteClients(tx, inboundID, emails); pushErr != nil {
  199. logger.Warning("disableInvalidClients: push to remote failed for inbound", inboundID, ":", pushErr)
  200. needRestart = true
  201. }
  202. }
  203. return needRestart, count, nil
  204. }
  205. // markClientsDisabledInSettings flips client.enable=false in the inbound's
  206. // stored settings JSON for the given emails and returns both the pre and
  207. // post snapshots so a caller pushing to a remote node has the diff to hand.
  208. func (s *InboundService) markClientsDisabledInSettings(tx *gorm.DB, inboundID int, emails map[string]struct{}) (oldIb, newIb *model.Inbound, err error) {
  209. var ib model.Inbound
  210. if err := tx.Model(&model.Inbound{}).Where("id = ?", inboundID).First(&ib).Error; err != nil {
  211. return nil, nil, err
  212. }
  213. snapshot := ib
  214. settings := map[string]any{}
  215. if err := json.Unmarshal([]byte(ib.Settings), &settings); err != nil {
  216. return nil, nil, err
  217. }
  218. clients, _ := settings["clients"].([]any)
  219. now := time.Now().Unix() * 1000
  220. mutated := false
  221. for i := range clients {
  222. entry, ok := clients[i].(map[string]any)
  223. if !ok {
  224. continue
  225. }
  226. email, _ := entry["email"].(string)
  227. if _, hit := emails[email]; !hit {
  228. continue
  229. }
  230. if cur, _ := entry["enable"].(bool); !cur {
  231. continue
  232. }
  233. entry["enable"] = false
  234. entry["updated_at"] = now
  235. clients[i] = entry
  236. mutated = true
  237. }
  238. if !mutated {
  239. return &snapshot, &ib, nil
  240. }
  241. settings["clients"] = clients
  242. bs, marshalErr := json.MarshalIndent(settings, "", " ")
  243. if marshalErr != nil {
  244. return nil, nil, marshalErr
  245. }
  246. ib.Settings = string(bs)
  247. if err := tx.Model(&model.Inbound{}).Where("id = ?", inboundID).
  248. Update("settings", ib.Settings).Error; err != nil {
  249. return nil, nil, err
  250. }
  251. return &snapshot, &ib, nil
  252. }
  253. // disableRemoteClients flips the clients off in the inbound's stored settings
  254. // and pushes the updated inbound to its node, which applies it to its own
  255. // running Xray. That push is the whole reconcile — restarting the node's Xray
  256. // afterwards would drop every live connection on the node for nothing (#5740).
  257. func (s *InboundService) disableRemoteClients(tx *gorm.DB, inboundID int, emails map[string]struct{}) error {
  258. oldSnapshot, ib, err := s.markClientsDisabledInSettings(tx, inboundID, emails)
  259. if err != nil {
  260. return err
  261. }
  262. rt, err := s.runtimeFor(ib)
  263. if err != nil {
  264. return err
  265. }
  266. if err := rt.UpdateInbound(context.Background(), oldSnapshot, ib); err != nil {
  267. return err
  268. }
  269. return nil
  270. }