inbound_traffic.go 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128
  1. package service
  2. import (
  3. "context"
  4. "encoding/json"
  5. "errors"
  6. "fmt"
  7. "maps"
  8. "slices"
  9. "strconv"
  10. "strings"
  11. "time"
  12. "github.com/mhsanaei/3x-ui/v3/internal/database"
  13. "github.com/mhsanaei/3x-ui/v3/internal/database/model"
  14. "github.com/mhsanaei/3x-ui/v3/internal/logger"
  15. "github.com/mhsanaei/3x-ui/v3/internal/web/runtime"
  16. "github.com/mhsanaei/3x-ui/v3/internal/xray"
  17. "gorm.io/gorm"
  18. "gorm.io/gorm/clause"
  19. )
  20. func (s *InboundService) AddTraffic(inboundTraffics []*xray.Traffic, clientTraffics []*xray.ClientTraffic) (needRestart bool, clientsDisabled bool, err error) {
  21. err = submitTrafficWrite(func() error {
  22. var inner error
  23. needRestart, clientsDisabled, inner = s.addTrafficLocked(inboundTraffics, clientTraffics)
  24. return inner
  25. })
  26. return
  27. }
  28. func (s *InboundService) addTrafficLocked(inboundTraffics []*xray.Traffic, clientTraffics []*xray.ClientTraffic) (bool, bool, error) {
  29. var err error
  30. db := database.GetDB()
  31. tx := db.Begin()
  32. defer func() {
  33. if err != nil {
  34. if rbErr := tx.Rollback().Error; rbErr != nil {
  35. logger.Warning("Error rolling back traffic tx:", rbErr)
  36. }
  37. } else if cErr := tx.Commit().Error; cErr != nil {
  38. logger.Warning("Error committing traffic tx:", cErr)
  39. }
  40. }()
  41. err = s.addInboundTraffic(tx, inboundTraffics)
  42. if err != nil {
  43. return false, false, err
  44. }
  45. err = s.addClientTraffic(tx, clientTraffics)
  46. if err != nil {
  47. return false, false, err
  48. }
  49. needRestart0, count, renewErr := s.autoRenewClients(tx)
  50. if renewErr != nil {
  51. logger.Warning("Error in renew clients:", renewErr)
  52. } else if count > 0 {
  53. logger.Debugf("%v clients renewed", count)
  54. }
  55. disabledClientsCount := int64(0)
  56. needRestart1, count, disableClientsErr := s.disableInvalidClients(tx)
  57. if disableClientsErr != nil {
  58. logger.Warning("Error in disabling invalid clients:", disableClientsErr)
  59. } else if count > 0 {
  60. logger.Debugf("%v clients disabled", count)
  61. disabledClientsCount = count
  62. }
  63. needRestart2, count, disableInboundsErr := s.disableInvalidInbounds(tx)
  64. if disableInboundsErr != nil {
  65. logger.Warning("Error in disabling invalid inbounds:", disableInboundsErr)
  66. } else if count > 0 {
  67. logger.Debugf("%v inbounds disabled", count)
  68. }
  69. return needRestart0 || needRestart1 || needRestart2, disabledClientsCount > 0, nil
  70. }
  71. func (s *InboundService) addInboundTraffic(tx *gorm.DB, traffics []*xray.Traffic) error {
  72. if len(traffics) == 0 {
  73. return nil
  74. }
  75. var err error
  76. for _, traffic := range traffics {
  77. if traffic.IsInbound {
  78. err = tx.Model(&model.Inbound{}).Where("tag = ? AND node_id IS NULL", traffic.Tag).
  79. Updates(map[string]any{
  80. "up": gorm.Expr(database.ClampedAddExpr("up"), traffic.Up),
  81. "down": gorm.Expr(database.ClampedAddExpr("down"), traffic.Down),
  82. }).Error
  83. if err != nil {
  84. return err
  85. }
  86. }
  87. }
  88. return nil
  89. }
  90. func (s *InboundService) addClientTraffic(tx *gorm.DB, traffics []*xray.ClientTraffic) (err error) {
  91. if len(traffics) == 0 {
  92. return nil
  93. }
  94. emails := make([]string, 0, len(traffics))
  95. for _, traffic := range traffics {
  96. emails = append(emails, traffic.Email)
  97. }
  98. dbClientTraffics := make([]*xray.ClientTraffic, 0, len(traffics))
  99. // Match purely by email. client_traffics is email-keyed (one shared row per
  100. // email regardless of how many inbounds the client is attached to), and these
  101. // emails come from the local xray's report, so they always belong to a client
  102. // attached to a local inbound. The old `inbound_id NOT IN (node inbounds)`
  103. // filter dropped the local traffic of a client attached to both a node and the
  104. // mother inbound whenever the node inbound happened to be attached first — its
  105. // shared row then carried the node inbound's id (AddClientStat used to use
  106. // OnConflict DoNothing and never refreshed it; it now refreshes inbound_id on
  107. // conflict, but this filter was removed rather than relying on that ordering).
  108. err = tx.Model(xray.ClientTraffic{}).
  109. Where("email IN (?)", emails).
  110. Find(&dbClientTraffics).Error
  111. if err != nil {
  112. return err
  113. }
  114. // Avoid empty slice error
  115. if len(dbClientTraffics) == 0 {
  116. return nil
  117. }
  118. dbClientTraffics, convertedExpiryByEmail, err := s.adjustTraffics(tx, dbClientTraffics)
  119. if err != nil {
  120. return err
  121. }
  122. // Index by email for O(N) merge.
  123. trafficByEmail := make(map[string]*xray.ClientTraffic, len(traffics))
  124. for i := range traffics {
  125. if traffics[i] != nil {
  126. trafficByEmail[traffics[i].Email] = traffics[i]
  127. }
  128. }
  129. now := time.Now().UnixMilli()
  130. // Use atomic per-row UPDATE instead of read-modify-write Save. tx.Save
  131. // issues UPDATEs in slice order, which varies between concurrent callers;
  132. // on PostgreSQL two transactions locking the same rows in opposite order
  133. // deadlock. An atomic "SET up = up + ?" never holds a row lock across a
  134. // subsequent lock acquisition, so concurrent writers cannot deadlock.
  135. for _, ct := range dbClientTraffics {
  136. t, ok := trafficByEmail[ct.Email]
  137. if !ok || (t.Up == 0 && t.Down == 0) {
  138. continue
  139. }
  140. if err = tx.Exec(
  141. fmt.Sprintf(
  142. `UPDATE client_traffics SET up = %s, down = %s, last_online = %s WHERE email = ?`,
  143. database.ClampedAddExpr("up"),
  144. database.ClampedAddExpr("down"),
  145. database.GreatestExpr("last_online", "?"),
  146. ),
  147. t.Up, t.Down, now, ct.Email,
  148. ).Error; err != nil {
  149. logger.Warning("AddClientTraffic update data ", err)
  150. }
  151. }
  152. // adjustTraffics converts delayed-start rows (negative ExpiryTime → absolute
  153. // deadline) in-memory. Persist that conversion now since the traffic UPDATE
  154. // above only touches up/down/last_online. Only converted emails are written:
  155. // updating every polled row issued one no-op UPDATE per active client per
  156. // poll. Sorted order keeps concurrent writers lock-compatible on Postgres.
  157. for _, email := range slices.Sorted(maps.Keys(convertedExpiryByEmail)) {
  158. if err = tx.Exec(
  159. `UPDATE client_traffics SET expiry_time = ? WHERE email = ? AND expiry_time < 0`,
  160. convertedExpiryByEmail[email], email,
  161. ).Error; err != nil {
  162. logger.Warning("AddClientTraffic update expiry_time ", err)
  163. }
  164. }
  165. return nil
  166. }
  167. func (s *InboundService) adjustTraffics(tx *gorm.DB, dbClientTraffics []*xray.ClientTraffic) ([]*xray.ClientTraffic, map[string]int64, error) {
  168. now := time.Now().UnixMilli()
  169. // "Start After First Use" stores a negative expiry (the duration). On the
  170. // first traffic tick it becomes an absolute deadline of now+duration. Compute
  171. // it once per email so every inbound the client is attached to lands on the
  172. // same value (recomputing per inbound would skip all but the first one).
  173. newExpiryByEmail := make(map[string]int64, len(dbClientTraffics))
  174. for traffic_index := range dbClientTraffics {
  175. if dbClientTraffics[traffic_index].ExpiryTime < 0 {
  176. newExpiryByEmail[dbClientTraffics[traffic_index].Email] = now - dbClientTraffics[traffic_index].ExpiryTime
  177. }
  178. }
  179. if len(newExpiryByEmail) == 0 {
  180. return dbClientTraffics, nil, nil
  181. }
  182. delayedEmails := make([]string, 0, len(newExpiryByEmail))
  183. for email := range newExpiryByEmail {
  184. delayedEmails = append(delayedEmails, email)
  185. }
  186. // Resolve the owning inbounds through the client_inbounds link, which is
  187. // authoritative. client_traffics.inbound_id goes stale when an inbound is
  188. // deleted and recreated, which would leave the negative expiry unconverted.
  189. var inboundIds []int
  190. err := tx.Table("client_inbounds").
  191. Joins("JOIN clients ON clients.id = client_inbounds.client_id").
  192. Where("clients.email IN (?)", delayedEmails).
  193. Distinct().
  194. Pluck("client_inbounds.inbound_id", &inboundIds).Error
  195. if err != nil {
  196. return nil, nil, err
  197. }
  198. if len(inboundIds) == 0 {
  199. return dbClientTraffics, nil, nil
  200. }
  201. var inbounds []*model.Inbound
  202. err = tx.Model(model.Inbound{}).Where("id IN (?)", inboundIds).Find(&inbounds).Error
  203. if err != nil {
  204. return nil, nil, err
  205. }
  206. for inbound_index := range inbounds {
  207. settings := map[string]any{}
  208. _ = json.Unmarshal([]byte(inbounds[inbound_index].Settings), &settings)
  209. clients, ok := settings["clients"].([]any)
  210. if ok {
  211. var newClients []any
  212. for client_index := range clients {
  213. c := clients[client_index].(map[string]any)
  214. email, _ := c["email"].(string)
  215. if newExpiry, ok := newExpiryByEmail[email]; ok {
  216. c["expiryTime"] = newExpiry
  217. c["updated_at"] = now
  218. }
  219. if _, ok := c["created_at"]; !ok {
  220. c["created_at"] = now
  221. }
  222. if _, ok := c["updated_at"]; !ok {
  223. c["updated_at"] = now
  224. }
  225. newClients = append(newClients, any(c))
  226. }
  227. settings["clients"] = newClients
  228. modifiedSettings, err := json.MarshalIndent(settings, "", " ")
  229. if err != nil {
  230. return nil, nil, err
  231. }
  232. inbounds[inbound_index].Settings = string(modifiedSettings)
  233. }
  234. }
  235. for traffic_index := range dbClientTraffics {
  236. if newExpiry, ok := newExpiryByEmail[dbClientTraffics[traffic_index].Email]; ok {
  237. dbClientTraffics[traffic_index].ExpiryTime = newExpiry
  238. }
  239. }
  240. err = tx.Save(inbounds).Error
  241. if err != nil {
  242. logger.Warning("AddClientTraffic update inbounds ", err)
  243. logger.Error(inbounds)
  244. } else {
  245. for _, ib := range inbounds {
  246. if ib == nil {
  247. continue
  248. }
  249. cs, gcErr := s.GetClients(ib)
  250. if gcErr != nil {
  251. logger.Warning("AddClientTraffic sync clients: GetClients failed", gcErr)
  252. continue
  253. }
  254. if syncErr := s.clientService.SyncInbound(tx, ib.Id, cs); syncErr != nil {
  255. logger.Warning("AddClientTraffic sync clients: SyncInbound failed", syncErr)
  256. }
  257. }
  258. }
  259. return dbClientTraffics, newExpiryByEmail, nil
  260. }
  261. func (s *InboundService) autoRenewClients(tx *gorm.DB) (bool, int64, error) {
  262. // check for time expired
  263. var traffics []*xray.ClientTraffic
  264. now := time.Now().Unix() * 1000
  265. var err, err1 error
  266. // Filter to clients that have at least one local inbound. Using
  267. // client_traffics.inbound_id is wrong: it goes stale after an inbound is
  268. // deleted/recreated and always points to the first inbound the client was
  269. // attached to, so it could be a node inbound even when the client also has
  270. // local inbounds. The email-based join through client_inbounds is authoritative.
  271. err = tx.Model(xray.ClientTraffic{}).
  272. Where("reset > 0 and expiry_time > 0 and expiry_time <= ?", now).
  273. Where("email IN (?)", tx.Table("client_inbounds ci").
  274. Select("c.email").
  275. Joins("JOIN clients c ON c.id = ci.client_id").
  276. Joins("JOIN inbounds i ON i.id = ci.inbound_id").
  277. Where("i.node_id IS NULL")).
  278. Find(&traffics).Error
  279. if err != nil {
  280. return false, 0, err
  281. }
  282. // return if there is no client to renew
  283. if len(traffics) == 0 {
  284. return false, 0, nil
  285. }
  286. var inbound_ids []int
  287. var inbounds []*model.Inbound
  288. needRestart := false
  289. var clientsToAdd []struct {
  290. protocol string
  291. tag string
  292. client map[string]any
  293. }
  294. // Resolve the inbounds to renew through the client_inbounds link rather than
  295. // client_traffics.inbound_id, which goes stale after an inbound is deleted and
  296. // recreated and would otherwise skip the renew entirely.
  297. renewEmails := make([]string, 0, len(traffics))
  298. for _, traffic := range traffics {
  299. renewEmails = append(renewEmails, traffic.Email)
  300. }
  301. for _, batch := range chunkStrings(renewEmails, sqliteMaxVars) {
  302. var ids []int
  303. if err = tx.Table("client_inbounds").
  304. Joins("JOIN clients ON clients.id = client_inbounds.client_id").
  305. Where("clients.email IN ?", batch).
  306. Distinct().
  307. Pluck("client_inbounds.inbound_id", &ids).Error; err != nil {
  308. return false, 0, err
  309. }
  310. inbound_ids = append(inbound_ids, ids...)
  311. }
  312. // Dedupe so an inbound hosting N expired clients is fetched and saved once
  313. // per tick instead of N times across chunk boundaries.
  314. inbound_ids = uniqueInts(inbound_ids)
  315. // Chunked to stay under SQLite's bind-variable limit when many inbounds
  316. // are touched in a single tick.
  317. for _, batch := range chunkInts(inbound_ids, sqliteMaxVars) {
  318. var page []*model.Inbound
  319. if err = tx.Model(model.Inbound{}).Where("id IN ?", batch).Find(&page).Error; err != nil {
  320. return false, 0, err
  321. }
  322. inbounds = append(inbounds, page...)
  323. }
  324. // Index the expired traffics by email so each client is an O(1) lookup
  325. // instead of a linear scan of every expired row (O(clients × expired) per
  326. // inbound, quadratic at scale). Pointers keep the in-place mutation below.
  327. trafficByEmail := make(map[string]*xray.ClientTraffic, len(traffics))
  328. for i := range traffics {
  329. trafficByEmail[traffics[i].Email] = traffics[i]
  330. }
  331. for inbound_index := range inbounds {
  332. settings := map[string]any{}
  333. _ = json.Unmarshal([]byte(inbounds[inbound_index].Settings), &settings)
  334. clients, _ := settings["clients"].([]any)
  335. if len(clients) == 0 {
  336. continue
  337. }
  338. for client_index := range clients {
  339. c := clients[client_index].(map[string]any)
  340. email, _ := c["email"].(string)
  341. traffic, ok := trafficByEmail[email]
  342. if !ok {
  343. continue
  344. }
  345. newExpiryTime := traffic.ExpiryTime
  346. for newExpiryTime < now {
  347. newExpiryTime += (int64(traffic.Reset) * 86400000)
  348. }
  349. c["expiryTime"] = newExpiryTime
  350. traffic.ExpiryTime = newExpiryTime
  351. traffic.Down = 0
  352. traffic.Up = 0
  353. if !traffic.Enable {
  354. traffic.Enable = true
  355. c["enable"] = true
  356. clientsToAdd = append(clientsToAdd,
  357. struct {
  358. protocol string
  359. tag string
  360. client map[string]any
  361. }{
  362. protocol: string(inbounds[inbound_index].Protocol),
  363. tag: inbounds[inbound_index].Tag,
  364. client: c,
  365. })
  366. }
  367. clients[client_index] = any(c)
  368. }
  369. settings["clients"] = clients
  370. newSettings, err := json.MarshalIndent(settings, "", " ")
  371. if err != nil {
  372. return false, 0, err
  373. }
  374. inbounds[inbound_index].Settings = string(newSettings)
  375. }
  376. err = tx.Save(inbounds).Error
  377. if err != nil {
  378. return false, 0, err
  379. }
  380. for _, ib := range inbounds {
  381. if ib == nil {
  382. continue
  383. }
  384. cs, gcErr := s.GetClients(ib)
  385. if gcErr != nil {
  386. logger.Warning("autoRenewClients sync clients: GetClients failed", gcErr)
  387. continue
  388. }
  389. if syncErr := s.clientService.SyncInbound(tx, ib.Id, cs); syncErr != nil {
  390. logger.Warning("autoRenewClients sync clients: SyncInbound failed", syncErr)
  391. }
  392. }
  393. err = tx.Save(traffics).Error
  394. if err != nil {
  395. return false, 0, err
  396. }
  397. // A renewed client starts a fresh quota window: drop the cross-panel rows
  398. // too, or the stale pushed totals would re-deplete it immediately.
  399. if err = clearGlobalTraffic(tx, renewEmails...); err != nil {
  400. return false, 0, err
  401. }
  402. if p != nil {
  403. err1 = s.xrayApi.Init(p.GetAPIPort())
  404. if err1 != nil {
  405. return true, int64(len(traffics)), nil
  406. }
  407. for _, clientToAdd := range clientsToAdd {
  408. err1 = s.xrayApi.AddUser(clientToAdd.protocol, clientToAdd.tag, clientToAdd.client)
  409. if err1 != nil {
  410. needRestart = true
  411. }
  412. }
  413. s.xrayApi.Close()
  414. }
  415. return needRestart, int64(len(traffics)), nil
  416. }
  417. // AddClientStat inserts a per-client accounting row, or refreshes the
  418. // config-derived columns on an email conflict. Xray reports traffic per
  419. // email, so the surviving row also acts as the shared accumulator for
  420. // inbounds that re-use the same identity — every call for that identity
  421. // (one per attached inbound) carries the same enable/expiry/reset/total,
  422. // so re-asserting them here is idempotent for that legitimate case.
  423. //
  424. // The conflict path matters on its own for a second reason: an inbound
  425. // delete detaches its clients (InboundService.DelInbound) without deleting
  426. // their client_traffics row, by design — mirroring ClientService.Detach,
  427. // which intentionally leaves a fully-detached client's row in place so a
  428. // later Attach can resume it with its accumulated traffic intact. If that
  429. // same email is instead reused for a freshly (re)created client, the new
  430. // config's enable/expiry/reset/total must win over whatever the orphaned
  431. // row still holds; DoNothing left them stale indefinitely (#5958).
  432. //
  433. // up/down are deliberately excluded from the refresh: they are the
  434. // accumulated traffic totals, and zeroing them here would erase real usage
  435. // every time an existing, actively-used client is attached to one more
  436. // inbound. One tradeoff this does not resolve: a genuinely new client that
  437. // happens to reuse an orphaned email still inherits that row's leftover
  438. // up/down, since nothing at this call site can tell the two cases apart.
  439. func (s *InboundService) AddClientStat(tx *gorm.DB, inboundId int, client *model.Client) error {
  440. clientTraffic := xray.ClientTraffic{
  441. InboundId: inboundId,
  442. Email: client.Email,
  443. Total: client.TotalGB,
  444. ExpiryTime: client.ExpiryTime,
  445. Enable: client.Enable,
  446. Reset: client.Reset,
  447. }
  448. return tx.Clauses(clause.OnConflict{
  449. Columns: []clause.Column{{Name: "email"}},
  450. DoUpdates: clause.AssignmentColumns([]string{"inbound_id", "total", "expiry_time", "enable", "reset"}),
  451. }).Create(&clientTraffic).Error
  452. }
  453. func (s *InboundService) UpdateClientStat(tx *gorm.DB, email string, client *model.Client) error {
  454. result := tx.Model(xray.ClientTraffic{}).
  455. Where("email = ?", email).
  456. Updates(map[string]any{
  457. "enable": client.Enable,
  458. "email": client.Email,
  459. "total": client.TotalGB,
  460. "expiry_time": client.ExpiryTime,
  461. "reset": client.Reset,
  462. })
  463. err := result.Error
  464. return err
  465. }
  466. func (s *InboundService) DelClientStat(tx *gorm.DB, email string) error {
  467. if err := adjustGroupBaselinesForRemovedTraffic(tx, []string{email}); err != nil {
  468. return err
  469. }
  470. if err := tx.Where("email = ?", email).Delete(xray.ClientTraffic{}).Error; err != nil {
  471. return err
  472. }
  473. if err := clearGlobalTraffic(tx, email); err != nil {
  474. return err
  475. }
  476. return tx.Where("email = ?", email).Delete(&model.NodeClientTraffic{}).Error
  477. }
  478. func (s *InboundService) delClientStatsByEmails(tx *gorm.DB, emails []string) error {
  479. if err := adjustGroupBaselinesForRemovedTraffic(tx, emails); err != nil {
  480. return err
  481. }
  482. const chunk = 400
  483. for start := 0; start < len(emails); start += chunk {
  484. end := min(start+chunk, len(emails))
  485. batch := emails[start:end]
  486. if err := tx.Where("email IN ?", batch).Delete(xray.ClientTraffic{}).Error; err != nil {
  487. return err
  488. }
  489. if err := tx.Where("email IN ?", batch).Delete(&model.ClientGlobalTraffic{}).Error; err != nil {
  490. return err
  491. }
  492. if err := tx.Where("email IN ?", batch).Delete(&model.NodeClientTraffic{}).Error; err != nil {
  493. return err
  494. }
  495. }
  496. return nil
  497. }
  498. func (s *InboundService) ResetClientTrafficByEmail(clientEmail string) error {
  499. err := submitTrafficWrite(func() error {
  500. return database.GetDB().Transaction(func(tx *gorm.DB) error {
  501. if err := adjustGroupBaselinesForRemovedTraffic(tx, []string{clientEmail}); err != nil {
  502. return err
  503. }
  504. if err := clearGlobalTraffic(tx, clientEmail); err != nil {
  505. return err
  506. }
  507. if err := tx.Model(xray.ClientTraffic{}).
  508. Where("email = ?", clientEmail).
  509. Updates(map[string]any{"enable": true, "up": 0, "down": 0}).Error; err != nil {
  510. return err
  511. }
  512. return tx.Where("email = ?", clientEmail).Delete(&model.NodeClientTraffic{}).Error
  513. })
  514. })
  515. if err == nil {
  516. s.resetMtprotoClientQuota(clientEmail)
  517. }
  518. return err
  519. }
  520. func (s *InboundService) ResetClientTraffic(id int, clientEmail string) (needRestart bool, err error) {
  521. err = submitTrafficWrite(func() error {
  522. var inner error
  523. needRestart, inner = s.resetClientTrafficLocked(id, clientEmail)
  524. return inner
  525. })
  526. if err == nil {
  527. s.resetMtprotoClientQuota(clientEmail)
  528. }
  529. return
  530. }
  531. func (s *InboundService) resetClientTrafficLocked(id int, clientEmail string) (bool, error) {
  532. needRestart := false
  533. traffic, err := s.GetClientTrafficByEmail(clientEmail)
  534. if err != nil {
  535. return false, err
  536. }
  537. if !traffic.Enable {
  538. inbound, err := s.GetInbound(id)
  539. if err != nil {
  540. return false, err
  541. }
  542. clients, err := s.GetClients(inbound)
  543. if err != nil {
  544. return false, err
  545. }
  546. for _, client := range clients {
  547. if client.Email == clientEmail && client.Enable {
  548. rt, push, _, perr := s.nodePushPlan(inbound)
  549. if perr != nil {
  550. return false, perr
  551. }
  552. if !push {
  553. if inbound.NodeID == nil {
  554. needRestart = true
  555. }
  556. break
  557. }
  558. cipher := ""
  559. if string(inbound.Protocol) == "shadowsocks" {
  560. var oldSettings map[string]any
  561. err = json.Unmarshal([]byte(inbound.Settings), &oldSettings)
  562. if err != nil {
  563. return false, err
  564. }
  565. cipher = oldSettings["method"].(string)
  566. }
  567. err1 := rt.AddUser(context.Background(), inbound, map[string]any{
  568. "email": client.Email,
  569. "id": client.ID,
  570. "auth": client.Auth,
  571. "security": client.Security,
  572. "flow": client.Flow,
  573. "password": client.Password,
  574. "cipher": cipher,
  575. })
  576. if err1 == nil {
  577. logger.Debug("Client enabled on", rt.Name(), "due to reset traffic:", clientEmail)
  578. } else if inbound.NodeID != nil {
  579. logger.Warning("Error in enabling client on", rt.Name(), ":", err1)
  580. } else {
  581. logger.Debug("Error in enabling client on", rt.Name(), ":", err1)
  582. needRestart = true
  583. }
  584. break
  585. }
  586. }
  587. }
  588. traffic.Up = 0
  589. traffic.Down = 0
  590. traffic.Enable = true
  591. db := database.GetDB()
  592. now := time.Now().UnixMilli()
  593. inbound, err := s.GetInbound(id)
  594. if err != nil {
  595. return false, err
  596. }
  597. if err := db.Transaction(func(tx *gorm.DB) error {
  598. if err := adjustGroupBaselinesForRemovedTraffic(tx, []string{clientEmail}); err != nil {
  599. return err
  600. }
  601. if err := tx.Save(traffic).Error; err != nil {
  602. return err
  603. }
  604. if err := clearGlobalTraffic(tx, clientEmail); err != nil {
  605. return err
  606. }
  607. if err := tx.Where("email = ?", clientEmail).Delete(&model.NodeClientTraffic{}).Error; err != nil {
  608. return err
  609. }
  610. if err := tx.Model(model.Inbound{}).
  611. Where("id = ?", id).
  612. Update("last_traffic_reset_time", now).Error; err != nil {
  613. return err
  614. }
  615. if inbound != nil && inbound.NodeID != nil {
  616. return (&NodeService{}).MarkNodeDirtyTx(tx, *inbound.NodeID)
  617. }
  618. return nil
  619. }); err != nil {
  620. return false, err
  621. }
  622. if inbound != nil && inbound.NodeID != nil {
  623. if rt, rterr := s.runtimeFor(inbound); rterr == nil {
  624. if e := rt.ResetClientTraffic(context.Background(), inbound, clientEmail); e != nil {
  625. logger.Warning("ResetClientTraffic: remote propagation to", rt.Name(), "failed:", e)
  626. }
  627. } else {
  628. logger.Warning("ResetClientTraffic: runtime lookup failed:", rterr)
  629. }
  630. }
  631. return needRestart, nil
  632. }
  633. func (s *InboundService) ResetAllTraffics() error {
  634. err := submitTrafficWrite(func() error {
  635. return s.resetAllTrafficsLocked()
  636. })
  637. if err == nil {
  638. s.propagateResetAllTrafficsToNodes()
  639. s.resetAllMtprotoQuotas()
  640. }
  641. return err
  642. }
  643. func (s *InboundService) resetAllTrafficsLocked() error {
  644. db := database.GetDB()
  645. now := time.Now().UnixMilli()
  646. return db.Model(model.Inbound{}).
  647. Where("user_id > ?", 0).
  648. Updates(map[string]any{
  649. "up": 0,
  650. "down": 0,
  651. "last_traffic_reset_time": now,
  652. }).Error
  653. }
  654. // propagateResetAllTrafficsToNodes tells every node to zero its own counters.
  655. // Kept OUT of the traffic-writer transaction: each remote call can block up to
  656. // remoteHTTPTimeout, and holding the single serial writer across N such calls
  657. // stalls traffic accounting and drops the deltas of every concurrent poll.
  658. func (s *InboundService) propagateResetAllTrafficsToNodes() {
  659. nodes, err := (&NodeService{}).GetAll()
  660. if err != nil {
  661. return
  662. }
  663. for _, node := range nodes {
  664. if rt, err := runtime.GetManager().RuntimeFor(&node.Id); err == nil {
  665. if e := rt.ResetAllTraffics(context.Background()); e != nil {
  666. logger.Warning("ResetAllTraffics: remote propagation to", rt.Name(), "failed:", e)
  667. }
  668. }
  669. }
  670. }
  671. func (s *InboundService) ResetInboundTraffic(id int) error {
  672. if err := submitTrafficWrite(func() error {
  673. return database.GetDB().Model(model.Inbound{}).
  674. Where("id = ?", id).
  675. Updates(map[string]any{"up": 0, "down": 0}).Error
  676. }); err != nil {
  677. return err
  678. }
  679. inbound, err := s.GetInbound(id)
  680. if err == nil && inbound != nil && inbound.NodeID != nil {
  681. if rt, rterr := s.runtimeFor(inbound); rterr == nil {
  682. if e := rt.ResetInboundTraffic(context.Background(), inbound); e != nil {
  683. logger.Warning("ResetInboundTraffic: remote propagation to", rt.Name(), "failed:", e)
  684. }
  685. } else {
  686. logger.Warning("ResetInboundTraffic: runtime lookup failed:", rterr)
  687. }
  688. }
  689. return nil
  690. }
  691. func (s *InboundService) DelDepletedClients(id int) (err error) {
  692. db := database.GetDB()
  693. tx := db.Begin()
  694. defer func() {
  695. if err == nil {
  696. tx.Commit()
  697. } else {
  698. tx.Rollback()
  699. }
  700. }()
  701. // Collect depleted emails globally — a shared-email row owned by one
  702. // inbound depletes every sibling that lists the email.
  703. now := time.Now().Unix() * 1000
  704. depletedClause := "reset = 0 and ((total > 0 and up + down >= total) or (expiry_time > 0 and expiry_time <= ?))"
  705. var depletedRows []xray.ClientTraffic
  706. err = db.Model(xray.ClientTraffic{}).
  707. Where(depletedClause, now).
  708. Find(&depletedRows).Error
  709. if err != nil {
  710. return err
  711. }
  712. if len(depletedRows) == 0 {
  713. return nil
  714. }
  715. depletedEmails := make(map[string]struct{}, len(depletedRows))
  716. for _, r := range depletedRows {
  717. if r.Email == "" {
  718. continue
  719. }
  720. depletedEmails[strings.ToLower(r.Email)] = struct{}{}
  721. }
  722. if len(depletedEmails) == 0 {
  723. return nil
  724. }
  725. var inbounds []*model.Inbound
  726. inboundQuery := db.Model(model.Inbound{})
  727. if id >= 0 {
  728. inboundQuery = inboundQuery.Where("id = ?", id)
  729. }
  730. if err = inboundQuery.Find(&inbounds).Error; err != nil {
  731. return err
  732. }
  733. for _, inbound := range inbounds {
  734. var settings map[string]any
  735. if err = json.Unmarshal([]byte(inbound.Settings), &settings); err != nil {
  736. return err
  737. }
  738. rawClients, ok := settings["clients"].([]any)
  739. if !ok {
  740. continue
  741. }
  742. newClients := make([]any, 0, len(rawClients))
  743. removed := 0
  744. for _, client := range rawClients {
  745. c, ok := client.(map[string]any)
  746. if !ok {
  747. newClients = append(newClients, client)
  748. continue
  749. }
  750. email, _ := c["email"].(string)
  751. if _, isDepleted := depletedEmails[strings.ToLower(email)]; isDepleted {
  752. removed++
  753. continue
  754. }
  755. newClients = append(newClients, client)
  756. }
  757. if removed == 0 {
  758. continue
  759. }
  760. if len(newClients) == 0 {
  761. _, _ = s.DelInbound(inbound.Id)
  762. continue
  763. }
  764. settings["clients"] = newClients
  765. ns, mErr := json.MarshalIndent(settings, "", " ")
  766. if mErr != nil {
  767. return mErr
  768. }
  769. inbound.Settings = string(ns)
  770. if err = tx.Save(inbound).Error; err != nil {
  771. return err
  772. }
  773. survivingClients, gcErr := s.GetClients(inbound)
  774. if gcErr != nil {
  775. err = gcErr
  776. return err
  777. }
  778. if err = s.clientService.SyncInbound(tx, inbound.Id, survivingClients); err != nil {
  779. return err
  780. }
  781. }
  782. // Drop now-orphaned rows. With id >= 0, a row is safe to drop only when
  783. // no out-of-scope inbound still references the email.
  784. if id < 0 {
  785. err = tx.Where(depletedClause, now).Delete(xray.ClientTraffic{}).Error
  786. return err
  787. }
  788. emails := make([]string, 0, len(depletedEmails))
  789. for e := range depletedEmails {
  790. emails = append(emails, e)
  791. }
  792. var stillReferenced []string
  793. emailExpr := database.JSONFieldText("client.value", "email")
  794. stillQuery := fmt.Sprintf(
  795. "SELECT DISTINCT LOWER(%s) %s WHERE LOWER(%s) IN ?",
  796. emailExpr,
  797. database.JSONClientsFromInbound(),
  798. emailExpr,
  799. )
  800. if err = tx.Raw(stillQuery, emails).Scan(&stillReferenced).Error; err != nil {
  801. return err
  802. }
  803. stillSet := make(map[string]struct{}, len(stillReferenced))
  804. for _, e := range stillReferenced {
  805. stillSet[e] = struct{}{}
  806. }
  807. toDelete := make([]string, 0, len(emails))
  808. for _, e := range emails {
  809. if _, kept := stillSet[e]; !kept {
  810. toDelete = append(toDelete, e)
  811. }
  812. }
  813. if len(toDelete) > 0 {
  814. if err = tx.Where("LOWER(email) IN ?", toDelete).Delete(xray.ClientTraffic{}).Error; err != nil {
  815. return err
  816. }
  817. }
  818. return nil
  819. }
  820. func (s *InboundService) GetClientTrafficTgBot(tgId int64) ([]*xray.ClientTraffic, error) {
  821. db := database.GetDB()
  822. idQuery := fmt.Sprintf(
  823. "SELECT DISTINCT inbounds.id %s WHERE %s = ?",
  824. database.JSONClientsFromInbound(),
  825. database.JSONFieldText("client.value", "tgId"),
  826. )
  827. var inboundIds []int
  828. if err := db.Raw(idQuery, strconv.FormatInt(tgId, 10)).Scan(&inboundIds).Error; err != nil {
  829. logger.Errorf("Error retrieving inbounds with tgId %d: %v", tgId, err)
  830. return nil, err
  831. }
  832. var inbounds []*model.Inbound
  833. if len(inboundIds) > 0 {
  834. err := db.Model(model.Inbound{}).Where("id IN ?", inboundIds).Find(&inbounds).Error
  835. if err != nil && !errors.Is(err, gorm.ErrRecordNotFound) {
  836. logger.Errorf("Error retrieving inbounds with tgId %d: %v", tgId, err)
  837. return nil, err
  838. }
  839. }
  840. var emails []string
  841. for _, inbound := range inbounds {
  842. clients, err := s.GetClients(inbound)
  843. if err != nil {
  844. logger.Errorf("Error retrieving clients for inbound %d: %v", inbound.Id, err)
  845. continue
  846. }
  847. for _, client := range clients {
  848. if client.TgID == tgId {
  849. emails = append(emails, client.Email)
  850. }
  851. }
  852. }
  853. // Chunked to stay under SQLite's bind-variable limit when a single Telegram
  854. // account owns thousands of clients across inbounds.
  855. uniqEmails := uniqueNonEmptyStrings(emails)
  856. traffics := make([]*xray.ClientTraffic, 0, len(uniqEmails))
  857. for _, batch := range chunkStrings(uniqEmails, sqliteMaxVars) {
  858. var page []*xray.ClientTraffic
  859. if err := db.Model(xray.ClientTraffic{}).Where("email IN ?", batch).Find(&page).Error; err != nil {
  860. if errors.Is(err, gorm.ErrRecordNotFound) {
  861. continue
  862. }
  863. logger.Errorf("Error retrieving ClientTraffic for emails %v: %v", batch, err)
  864. return nil, err
  865. }
  866. traffics = append(traffics, page...)
  867. }
  868. if len(traffics) == 0 {
  869. logger.Warning("No ClientTraffic records found for emails:", emails)
  870. return nil, nil
  871. }
  872. // Populate UUID and other client data for each traffic record
  873. for i := range traffics {
  874. if ct, client, e := s.GetClientByEmail(traffics[i].Email); e == nil && ct != nil && client != nil {
  875. traffics[i].Enable = client.Enable
  876. traffics[i].UUID = client.ID
  877. traffics[i].SubId = client.SubID
  878. }
  879. }
  880. return traffics, nil
  881. }
  882. // BumpClientsLastOnline sets client_traffics.last_online to now for the given
  883. // emails. Used in online-API mode for clients that hold a live connection but
  884. // moved no bytes this poll — the traffic path (addClientTraffic) only bumps
  885. // last_online on a non-zero delta, so idle-but-connected clients would
  886. // otherwise show a stale "last online" while being reported online.
  887. func (s *InboundService) BumpClientsLastOnline(emails []string) error {
  888. uniq := uniqueNonEmptyStrings(emails)
  889. if len(uniq) == 0 {
  890. return nil
  891. }
  892. now := time.Now().UnixMilli()
  893. return submitTrafficWrite(func() error {
  894. db := database.GetDB()
  895. for _, batch := range chunkStrings(uniq, sqliteMaxVars) {
  896. if err := db.Model(xray.ClientTraffic{}).Where("email IN ?", batch).Update("last_online", now).Error; err != nil {
  897. return err
  898. }
  899. }
  900. return nil
  901. })
  902. }
  903. func (s *InboundService) GetActiveClientTraffics(emails []string) ([]*xray.ClientTraffic, error) {
  904. uniq := uniqueNonEmptyStrings(emails)
  905. if len(uniq) == 0 {
  906. return nil, nil
  907. }
  908. db := database.GetDB()
  909. traffics := make([]*xray.ClientTraffic, 0, len(uniq))
  910. for _, batch := range chunkStrings(uniq, sqliteMaxVars) {
  911. var page []*xray.ClientTraffic
  912. if err := db.Model(xray.ClientTraffic{}).Where("email IN ?", batch).Find(&page).Error; err != nil {
  913. return nil, err
  914. }
  915. traffics = append(traffics, page...)
  916. }
  917. overlayGlobalTraffic(db, traffics)
  918. return traffics, nil
  919. }
  920. // GetAllClientTraffics returns the full set of client_traffics rows so the
  921. // websocket broadcasters can ship a complete snapshot every cycle. A pure
  922. // delta path silently dropped the per-client section whenever no client moved
  923. // bytes in the cycle or a node sync failed, leaving client rows in the UI
  924. // stuck at stale numbers — so small installs broadcast this snapshot, and only
  925. // above the traffic job's snapshot threshold (where the marshaled snapshot
  926. // would exceed the hub's payload cap and be dropped wholesale) does the job
  927. // fall back to active-row deltas.
  928. func (s *InboundService) GetAllClientTraffics() ([]*xray.ClientTraffic, error) {
  929. db := database.GetDB()
  930. var traffics []*xray.ClientTraffic
  931. if err := db.Model(xray.ClientTraffic{}).Find(&traffics).Error; err != nil {
  932. return nil, err
  933. }
  934. overlayGlobalTraffic(db, traffics)
  935. return traffics, nil
  936. }
  937. func (s *InboundService) CountClientTraffics() (int64, error) {
  938. db := database.GetDB()
  939. var count int64
  940. err := db.Model(xray.ClientTraffic{}).Count(&count).Error
  941. return count, err
  942. }
  943. type InboundTrafficSummary struct {
  944. Id int `json:"id"`
  945. Up int64 `json:"up"`
  946. Down int64 `json:"down"`
  947. Total int64 `json:"total"`
  948. Enable bool `json:"enable"`
  949. }
  950. func (s *InboundService) GetInboundsTrafficSummary() ([]InboundTrafficSummary, error) {
  951. db := database.GetDB()
  952. var summaries []InboundTrafficSummary
  953. if err := db.Model(&model.Inbound{}).
  954. Select("id, up, down, total, enable").
  955. Find(&summaries).Error; err != nil {
  956. return nil, err
  957. }
  958. return summaries, nil
  959. }
  960. func (s *InboundService) GetClientTrafficByEmail(email string) (traffic *xray.ClientTraffic, err error) {
  961. db := database.GetDB()
  962. var traffics []*xray.ClientTraffic
  963. if err := db.Model(xray.ClientTraffic{}).Where("email = ?", email).Find(&traffics).Error; err != nil {
  964. logger.Warningf("Error retrieving ClientTraffic with email %s: %v", email, err)
  965. return nil, err
  966. }
  967. if len(traffics) == 0 {
  968. return nil, nil
  969. }
  970. overlayGlobalTraffic(db, traffics)
  971. t := traffics[0]
  972. if rec, rErr := s.clientService.GetRecordByEmail(db, email); rErr == nil && rec != nil {
  973. c := rec.ToClient()
  974. t.UUID = c.ID
  975. t.SubId = c.SubID
  976. return t, nil
  977. }
  978. t2, client, err := s.GetClientByEmail(email)
  979. if err != nil {
  980. logger.Warningf("Error retrieving ClientTraffic with email %s: %v", email, err)
  981. return nil, err
  982. }
  983. if t2 != nil && client != nil {
  984. t2.UUID = client.ID
  985. t2.SubId = client.SubID
  986. return t2, nil
  987. }
  988. return nil, nil
  989. }
  990. func (s *InboundService) UpdateClientTrafficByEmail(email string, upload int64, download int64) error {
  991. return submitTrafficWrite(func() error {
  992. db := database.GetDB()
  993. err := db.Model(xray.ClientTraffic{}).
  994. Where("email = ?", email).
  995. Updates(map[string]any{
  996. "up": upload,
  997. "down": download,
  998. }).Error
  999. if err != nil {
  1000. logger.Warningf("Error updating ClientTraffic with email %s: %v", email, err)
  1001. }
  1002. return err
  1003. })
  1004. }
  1005. func (s *InboundService) SearchClientTraffic(query string) (traffic *xray.ClientTraffic, err error) {
  1006. db := database.GetDB()
  1007. inbound := &model.Inbound{}
  1008. traffic = &xray.ClientTraffic{}
  1009. // Search for inbound settings that contain the query
  1010. err = db.Model(model.Inbound{}).Where("settings LIKE ?", "%\""+query+"\"%").First(inbound).Error
  1011. if err != nil {
  1012. if errors.Is(err, gorm.ErrRecordNotFound) {
  1013. logger.Warningf("Inbound settings containing query %s not found: %v", query, err)
  1014. return nil, err
  1015. }
  1016. logger.Errorf("Error searching for inbound settings with query %s: %v", query, err)
  1017. return nil, err
  1018. }
  1019. traffic.InboundId = inbound.Id
  1020. clients, err := ParseInboundSettingsClients(inbound.Settings)
  1021. if err != nil {
  1022. logger.Errorf("Error unmarshalling inbound settings for inbound ID %d: %v", inbound.Id, err)
  1023. return nil, err
  1024. }
  1025. for _, client := range clients {
  1026. if (client.ID == query || client.Password == query) && client.Email != "" {
  1027. traffic.Email = client.Email
  1028. break
  1029. }
  1030. }
  1031. if traffic.Email == "" {
  1032. logger.Warningf("No client found with query %s in inbound ID %d", query, inbound.Id)
  1033. return nil, gorm.ErrRecordNotFound
  1034. }
  1035. // Retrieve ClientTraffic based on the found email
  1036. err = db.Model(xray.ClientTraffic{}).Where("email = ?", traffic.Email).First(traffic).Error
  1037. if err != nil {
  1038. if errors.Is(err, gorm.ErrRecordNotFound) {
  1039. logger.Warningf("ClientTraffic for email %s not found: %v", traffic.Email, err)
  1040. return nil, err
  1041. }
  1042. logger.Errorf("Error retrieving ClientTraffic for email %s: %v", traffic.Email, err)
  1043. return nil, err
  1044. }
  1045. return traffic, nil
  1046. }