inbound_disable.go 9.1 KB

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