1
0

inbound_traffic.go 36 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149
  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. // apiUserFromClient prepares a stored client object for the runtime AddUser
  262. // call. The copy matters twice over: the stored object keeps being mutated and
  263. // marshalled back into the inbound's settings, which must not gain an API-only
  264. // key, and shadowsocks clients carry no cipher of their own — it lives on the
  265. // inbound, and without it the API cannot tell which of xray's two shadowsocks
  266. // account types the running inbound expects.
  267. func apiUserFromClient(client map[string]any, cipher string) map[string]any {
  268. user := maps.Clone(client)
  269. if user == nil {
  270. user = map[string]any{}
  271. }
  272. if cipher != "" {
  273. user["cipher"] = cipher
  274. }
  275. return user
  276. }
  277. func (s *InboundService) autoRenewClients(tx *gorm.DB) (bool, int64, error) {
  278. // check for time expired
  279. var traffics []*xray.ClientTraffic
  280. now := time.Now().Unix() * 1000
  281. var err, err1 error
  282. // Filter to clients that have at least one local inbound. Using
  283. // client_traffics.inbound_id is wrong: it goes stale after an inbound is
  284. // deleted/recreated and always points to the first inbound the client was
  285. // attached to, so it could be a node inbound even when the client also has
  286. // local inbounds. The email-based join through client_inbounds is authoritative.
  287. err = tx.Model(xray.ClientTraffic{}).
  288. Where("reset > 0 and expiry_time > 0 and expiry_time <= ?", now).
  289. Where("email IN (?)", tx.Table("client_inbounds ci").
  290. Select("c.email").
  291. Joins("JOIN clients c ON c.id = ci.client_id").
  292. Joins("JOIN inbounds i ON i.id = ci.inbound_id").
  293. Where("i.node_id IS NULL")).
  294. Find(&traffics).Error
  295. if err != nil {
  296. return false, 0, err
  297. }
  298. // return if there is no client to renew
  299. if len(traffics) == 0 {
  300. return false, 0, nil
  301. }
  302. var inbound_ids []int
  303. var inbounds []*model.Inbound
  304. needRestart := false
  305. var clientsToAdd []struct {
  306. protocol string
  307. tag string
  308. client map[string]any
  309. }
  310. // Resolve the inbounds to renew through the client_inbounds link rather than
  311. // client_traffics.inbound_id, which goes stale after an inbound is deleted and
  312. // recreated and would otherwise skip the renew entirely.
  313. renewEmails := make([]string, 0, len(traffics))
  314. for _, traffic := range traffics {
  315. renewEmails = append(renewEmails, traffic.Email)
  316. }
  317. for _, batch := range chunkStrings(renewEmails, sqliteMaxVars) {
  318. var ids []int
  319. if err = tx.Table("client_inbounds").
  320. Joins("JOIN clients ON clients.id = client_inbounds.client_id").
  321. Where("clients.email IN ?", batch).
  322. Distinct().
  323. Pluck("client_inbounds.inbound_id", &ids).Error; err != nil {
  324. return false, 0, err
  325. }
  326. inbound_ids = append(inbound_ids, ids...)
  327. }
  328. // Dedupe so an inbound hosting N expired clients is fetched and saved once
  329. // per tick instead of N times across chunk boundaries.
  330. inbound_ids = uniqueInts(inbound_ids)
  331. // Chunked to stay under SQLite's bind-variable limit when many inbounds
  332. // are touched in a single tick.
  333. for _, batch := range chunkInts(inbound_ids, sqliteMaxVars) {
  334. var page []*model.Inbound
  335. if err = tx.Model(model.Inbound{}).Where("id IN ?", batch).Find(&page).Error; err != nil {
  336. return false, 0, err
  337. }
  338. inbounds = append(inbounds, page...)
  339. }
  340. // Index the expired traffics by email so each client is an O(1) lookup
  341. // instead of a linear scan of every expired row (O(clients × expired) per
  342. // inbound, quadratic at scale). Pointers keep the in-place mutation below.
  343. trafficByEmail := make(map[string]*xray.ClientTraffic, len(traffics))
  344. for i := range traffics {
  345. trafficByEmail[traffics[i].Email] = traffics[i]
  346. }
  347. for inbound_index := range inbounds {
  348. settings := map[string]any{}
  349. _ = json.Unmarshal([]byte(inbounds[inbound_index].Settings), &settings)
  350. clients, _ := settings["clients"].([]any)
  351. if len(clients) == 0 {
  352. continue
  353. }
  354. cipher := ""
  355. if inbounds[inbound_index].Protocol == model.Shadowsocks {
  356. cipher, _ = settings["method"].(string)
  357. }
  358. for client_index := range clients {
  359. c := clients[client_index].(map[string]any)
  360. email, _ := c["email"].(string)
  361. traffic, ok := trafficByEmail[email]
  362. if !ok {
  363. continue
  364. }
  365. newExpiryTime := traffic.ExpiryTime
  366. for newExpiryTime < now {
  367. newExpiryTime += (int64(traffic.Reset) * 86400000)
  368. }
  369. c["expiryTime"] = newExpiryTime
  370. traffic.ExpiryTime = newExpiryTime
  371. traffic.Down = 0
  372. traffic.Up = 0
  373. if !traffic.Enable {
  374. traffic.Enable = true
  375. c["enable"] = true
  376. clientsToAdd = append(clientsToAdd,
  377. struct {
  378. protocol string
  379. tag string
  380. client map[string]any
  381. }{
  382. protocol: string(inbounds[inbound_index].Protocol),
  383. tag: inbounds[inbound_index].Tag,
  384. client: apiUserFromClient(c, cipher),
  385. })
  386. }
  387. clients[client_index] = any(c)
  388. }
  389. settings["clients"] = clients
  390. newSettings, err := json.MarshalIndent(settings, "", " ")
  391. if err != nil {
  392. return false, 0, err
  393. }
  394. inbounds[inbound_index].Settings = string(newSettings)
  395. }
  396. err = tx.Save(inbounds).Error
  397. if err != nil {
  398. return false, 0, err
  399. }
  400. for _, ib := range inbounds {
  401. if ib == nil {
  402. continue
  403. }
  404. cs, gcErr := s.GetClients(ib)
  405. if gcErr != nil {
  406. logger.Warning("autoRenewClients sync clients: GetClients failed", gcErr)
  407. continue
  408. }
  409. if syncErr := s.clientService.SyncInbound(tx, ib.Id, cs); syncErr != nil {
  410. logger.Warning("autoRenewClients sync clients: SyncInbound failed", syncErr)
  411. }
  412. }
  413. err = tx.Save(traffics).Error
  414. if err != nil {
  415. return false, 0, err
  416. }
  417. // A renewed client starts a fresh quota window: drop the cross-panel rows
  418. // too, or the stale pushed totals would re-deplete it immediately.
  419. if err = clearGlobalTraffic(tx, renewEmails...); err != nil {
  420. return false, 0, err
  421. }
  422. if p != nil {
  423. err1 = s.xrayApi.Init(p.GetAPIPort())
  424. if err1 != nil {
  425. return true, int64(len(traffics)), nil
  426. }
  427. for _, clientToAdd := range clientsToAdd {
  428. err1 = s.xrayApi.AddUser(clientToAdd.protocol, clientToAdd.tag, clientToAdd.client)
  429. if err1 != nil {
  430. needRestart = true
  431. }
  432. }
  433. s.xrayApi.Close()
  434. }
  435. return needRestart, int64(len(traffics)), nil
  436. }
  437. // AddClientStat inserts a per-client accounting row, or refreshes the
  438. // config-derived columns on an email conflict. Xray reports traffic per
  439. // email, so the surviving row also acts as the shared accumulator for
  440. // inbounds that re-use the same identity — every call for that identity
  441. // (one per attached inbound) carries the same enable/expiry/reset/total,
  442. // so re-asserting them here is idempotent for that legitimate case.
  443. //
  444. // The conflict path matters on its own for a second reason: an inbound
  445. // delete detaches its clients (InboundService.DelInbound) without deleting
  446. // their client_traffics row, by design — mirroring ClientService.Detach,
  447. // which intentionally leaves a fully-detached client's row in place so a
  448. // later Attach can resume it with its accumulated traffic intact. If that
  449. // same email is instead reused for a freshly (re)created client, the new
  450. // config's enable/expiry/reset/total must win over whatever the orphaned
  451. // row still holds; DoNothing left them stale indefinitely (#5958).
  452. //
  453. // up/down are deliberately excluded from the refresh: they are the
  454. // accumulated traffic totals, and zeroing them here would erase real usage
  455. // every time an existing, actively-used client is attached to one more
  456. // inbound. One tradeoff this does not resolve: a genuinely new client that
  457. // happens to reuse an orphaned email still inherits that row's leftover
  458. // up/down, since nothing at this call site can tell the two cases apart.
  459. func (s *InboundService) AddClientStat(tx *gorm.DB, inboundId int, client *model.Client) error {
  460. clientTraffic := xray.ClientTraffic{
  461. InboundId: inboundId,
  462. Email: client.Email,
  463. Total: client.TotalGB,
  464. ExpiryTime: client.ExpiryTime,
  465. Enable: client.Enable,
  466. Reset: client.Reset,
  467. }
  468. return tx.Clauses(clause.OnConflict{
  469. Columns: []clause.Column{{Name: "email"}},
  470. DoUpdates: clause.AssignmentColumns([]string{"inbound_id", "total", "expiry_time", "enable", "reset"}),
  471. }).Create(&clientTraffic).Error
  472. }
  473. func (s *InboundService) UpdateClientStat(tx *gorm.DB, email string, client *model.Client) error {
  474. result := tx.Model(xray.ClientTraffic{}).
  475. Where("email = ?", email).
  476. Updates(map[string]any{
  477. "enable": client.Enable,
  478. "email": client.Email,
  479. "total": client.TotalGB,
  480. "expiry_time": client.ExpiryTime,
  481. "reset": client.Reset,
  482. })
  483. err := result.Error
  484. return err
  485. }
  486. func (s *InboundService) DelClientStat(tx *gorm.DB, email string) error {
  487. if err := adjustGroupBaselinesForRemovedTraffic(tx, []string{email}); err != nil {
  488. return err
  489. }
  490. if err := tx.Where("email = ?", email).Delete(xray.ClientTraffic{}).Error; err != nil {
  491. return err
  492. }
  493. if err := clearGlobalTraffic(tx, email); err != nil {
  494. return err
  495. }
  496. return tx.Where("email = ?", email).Delete(&model.NodeClientTraffic{}).Error
  497. }
  498. func (s *InboundService) delClientStatsByEmails(tx *gorm.DB, emails []string) error {
  499. if err := adjustGroupBaselinesForRemovedTraffic(tx, emails); err != nil {
  500. return err
  501. }
  502. const chunk = 400
  503. for start := 0; start < len(emails); start += chunk {
  504. end := min(start+chunk, len(emails))
  505. batch := emails[start:end]
  506. if err := tx.Where("email IN ?", batch).Delete(xray.ClientTraffic{}).Error; err != nil {
  507. return err
  508. }
  509. if err := tx.Where("email IN ?", batch).Delete(&model.ClientGlobalTraffic{}).Error; err != nil {
  510. return err
  511. }
  512. if err := tx.Where("email IN ?", batch).Delete(&model.NodeClientTraffic{}).Error; err != nil {
  513. return err
  514. }
  515. }
  516. return nil
  517. }
  518. func (s *InboundService) ResetClientTrafficByEmail(clientEmail string) error {
  519. err := submitTrafficWrite(func() error {
  520. return database.GetDB().Transaction(func(tx *gorm.DB) error {
  521. if err := adjustGroupBaselinesForRemovedTraffic(tx, []string{clientEmail}); err != nil {
  522. return err
  523. }
  524. if err := clearGlobalTraffic(tx, clientEmail); err != nil {
  525. return err
  526. }
  527. if err := tx.Model(xray.ClientTraffic{}).
  528. Where("email = ?", clientEmail).
  529. Updates(map[string]any{"enable": true, "up": 0, "down": 0}).Error; err != nil {
  530. return err
  531. }
  532. return tx.Where("email = ?", clientEmail).Delete(&model.NodeClientTraffic{}).Error
  533. })
  534. })
  535. if err == nil {
  536. s.resetMtprotoClientQuota(clientEmail)
  537. }
  538. return err
  539. }
  540. func (s *InboundService) ResetClientTraffic(id int, clientEmail string) (needRestart bool, err error) {
  541. err = submitTrafficWrite(func() error {
  542. var inner error
  543. needRestart, inner = s.resetClientTrafficLocked(id, clientEmail)
  544. return inner
  545. })
  546. if err == nil {
  547. s.resetMtprotoClientQuota(clientEmail)
  548. }
  549. return
  550. }
  551. func (s *InboundService) resetClientTrafficLocked(id int, clientEmail string) (bool, error) {
  552. needRestart := false
  553. traffic, err := s.GetClientTrafficByEmail(clientEmail)
  554. if err != nil {
  555. return false, err
  556. }
  557. if !traffic.Enable {
  558. inbound, err := s.GetInbound(id)
  559. if err != nil {
  560. return false, err
  561. }
  562. clients, err := s.GetClients(inbound)
  563. if err != nil {
  564. return false, err
  565. }
  566. for _, client := range clients {
  567. if client.Email == clientEmail && client.Enable {
  568. rt, push, _, perr := s.nodePushPlan(inbound)
  569. if perr != nil {
  570. return false, perr
  571. }
  572. if !push {
  573. if inbound.NodeID == nil {
  574. needRestart = true
  575. }
  576. break
  577. }
  578. cipher := ""
  579. if string(inbound.Protocol) == "shadowsocks" {
  580. var oldSettings map[string]any
  581. err = json.Unmarshal([]byte(inbound.Settings), &oldSettings)
  582. if err != nil {
  583. return false, err
  584. }
  585. cipher, _ = oldSettings["method"].(string)
  586. }
  587. err1 := rt.AddUser(context.Background(), inbound, map[string]any{
  588. "email": client.Email,
  589. "id": client.ID,
  590. "auth": client.Auth,
  591. "security": client.Security,
  592. "flow": client.Flow,
  593. "password": client.Password,
  594. "cipher": cipher,
  595. })
  596. if err1 == nil {
  597. logger.Debug("Client enabled on", rt.Name(), "due to reset traffic:", clientEmail)
  598. } else if inbound.NodeID != nil {
  599. logger.Warning("Error in enabling client on", rt.Name(), ":", err1)
  600. } else {
  601. logger.Debug("Error in enabling client on", rt.Name(), ":", err1)
  602. needRestart = true
  603. }
  604. break
  605. }
  606. }
  607. }
  608. traffic.Up = 0
  609. traffic.Down = 0
  610. traffic.Enable = true
  611. db := database.GetDB()
  612. now := time.Now().UnixMilli()
  613. inbound, err := s.GetInbound(id)
  614. if err != nil {
  615. return false, err
  616. }
  617. if err := db.Transaction(func(tx *gorm.DB) error {
  618. if err := adjustGroupBaselinesForRemovedTraffic(tx, []string{clientEmail}); err != nil {
  619. return err
  620. }
  621. if err := tx.Save(traffic).Error; err != nil {
  622. return err
  623. }
  624. if err := clearGlobalTraffic(tx, clientEmail); err != nil {
  625. return err
  626. }
  627. if err := tx.Where("email = ?", clientEmail).Delete(&model.NodeClientTraffic{}).Error; err != nil {
  628. return err
  629. }
  630. if err := tx.Model(model.Inbound{}).
  631. Where("id = ?", id).
  632. Update("last_traffic_reset_time", now).Error; err != nil {
  633. return err
  634. }
  635. if inbound != nil && inbound.NodeID != nil {
  636. return (&NodeService{}).MarkNodeDirtyTx(tx, *inbound.NodeID)
  637. }
  638. return nil
  639. }); err != nil {
  640. return false, err
  641. }
  642. if inbound != nil && inbound.NodeID != nil {
  643. if rt, rterr := s.runtimeFor(inbound); rterr == nil {
  644. if e := rt.ResetClientTraffic(context.Background(), inbound, clientEmail); e != nil {
  645. logger.Warning("ResetClientTraffic: remote propagation to", rt.Name(), "failed:", e)
  646. }
  647. } else {
  648. logger.Warning("ResetClientTraffic: runtime lookup failed:", rterr)
  649. }
  650. }
  651. return needRestart, nil
  652. }
  653. func (s *InboundService) ResetAllTraffics() error {
  654. err := submitTrafficWrite(func() error {
  655. return s.resetAllTrafficsLocked()
  656. })
  657. if err == nil {
  658. s.propagateResetAllTrafficsToNodes()
  659. s.resetAllMtprotoQuotas()
  660. }
  661. return err
  662. }
  663. func (s *InboundService) resetAllTrafficsLocked() error {
  664. db := database.GetDB()
  665. now := time.Now().UnixMilli()
  666. return db.Model(model.Inbound{}).
  667. Where("user_id > ?", 0).
  668. Updates(map[string]any{
  669. "up": 0,
  670. "down": 0,
  671. "last_traffic_reset_time": now,
  672. }).Error
  673. }
  674. // propagateResetAllTrafficsToNodes tells every node to zero its own counters.
  675. // Kept OUT of the traffic-writer transaction: each remote call can block up to
  676. // remoteHTTPTimeout, and holding the single serial writer across N such calls
  677. // stalls traffic accounting and drops the deltas of every concurrent poll.
  678. func (s *InboundService) propagateResetAllTrafficsToNodes() {
  679. nodes, err := (&NodeService{}).GetAll()
  680. if err != nil {
  681. return
  682. }
  683. for _, node := range nodes {
  684. if rt, err := runtime.GetManager().RuntimeFor(&node.Id); err == nil {
  685. if e := rt.ResetAllTraffics(context.Background()); e != nil {
  686. logger.Warning("ResetAllTraffics: remote propagation to", rt.Name(), "failed:", e)
  687. }
  688. }
  689. }
  690. }
  691. func (s *InboundService) ResetInboundTraffic(id int) error {
  692. if err := submitTrafficWrite(func() error {
  693. return database.GetDB().Model(model.Inbound{}).
  694. Where("id = ?", id).
  695. Updates(map[string]any{"up": 0, "down": 0}).Error
  696. }); err != nil {
  697. return err
  698. }
  699. inbound, err := s.GetInbound(id)
  700. if err == nil && inbound != nil && inbound.NodeID != nil {
  701. if rt, rterr := s.runtimeFor(inbound); rterr == nil {
  702. if e := rt.ResetInboundTraffic(context.Background(), inbound); e != nil {
  703. logger.Warning("ResetInboundTraffic: remote propagation to", rt.Name(), "failed:", e)
  704. }
  705. } else {
  706. logger.Warning("ResetInboundTraffic: runtime lookup failed:", rterr)
  707. }
  708. }
  709. return nil
  710. }
  711. func (s *InboundService) DelDepletedClients(id int) (err error) {
  712. db := database.GetDB()
  713. tx := db.Begin()
  714. defer func() {
  715. if err == nil {
  716. tx.Commit()
  717. } else {
  718. tx.Rollback()
  719. }
  720. }()
  721. // Collect depleted emails globally — a shared-email row owned by one
  722. // inbound depletes every sibling that lists the email.
  723. now := time.Now().Unix() * 1000
  724. depletedClause := "reset = 0 and ((total > 0 and up + down >= total) or (expiry_time > 0 and expiry_time <= ?))"
  725. var depletedRows []xray.ClientTraffic
  726. err = db.Model(xray.ClientTraffic{}).
  727. Where(depletedClause, now).
  728. Find(&depletedRows).Error
  729. if err != nil {
  730. return err
  731. }
  732. if len(depletedRows) == 0 {
  733. return nil
  734. }
  735. depletedEmails := make(map[string]struct{}, len(depletedRows))
  736. for _, r := range depletedRows {
  737. if r.Email == "" {
  738. continue
  739. }
  740. depletedEmails[strings.ToLower(r.Email)] = struct{}{}
  741. }
  742. if len(depletedEmails) == 0 {
  743. return nil
  744. }
  745. var inbounds []*model.Inbound
  746. inboundQuery := db.Model(model.Inbound{})
  747. if id >= 0 {
  748. inboundQuery = inboundQuery.Where("id = ?", id)
  749. }
  750. if err = inboundQuery.Find(&inbounds).Error; err != nil {
  751. return err
  752. }
  753. for _, inbound := range inbounds {
  754. var settings map[string]any
  755. if err = json.Unmarshal([]byte(inbound.Settings), &settings); err != nil {
  756. return err
  757. }
  758. rawClients, ok := settings["clients"].([]any)
  759. if !ok {
  760. continue
  761. }
  762. newClients := make([]any, 0, len(rawClients))
  763. removed := 0
  764. for _, client := range rawClients {
  765. c, ok := client.(map[string]any)
  766. if !ok {
  767. newClients = append(newClients, client)
  768. continue
  769. }
  770. email, _ := c["email"].(string)
  771. if _, isDepleted := depletedEmails[strings.ToLower(email)]; isDepleted {
  772. removed++
  773. continue
  774. }
  775. newClients = append(newClients, client)
  776. }
  777. if removed == 0 {
  778. continue
  779. }
  780. if len(newClients) == 0 {
  781. _, _ = s.DelInbound(inbound.Id)
  782. continue
  783. }
  784. settings["clients"] = newClients
  785. ns, mErr := json.MarshalIndent(settings, "", " ")
  786. if mErr != nil {
  787. return mErr
  788. }
  789. inbound.Settings = string(ns)
  790. if err = tx.Save(inbound).Error; err != nil {
  791. return err
  792. }
  793. survivingClients, gcErr := s.GetClients(inbound)
  794. if gcErr != nil {
  795. err = gcErr
  796. return err
  797. }
  798. if err = s.clientService.SyncInbound(tx, inbound.Id, survivingClients); err != nil {
  799. return err
  800. }
  801. }
  802. // Drop now-orphaned rows. With id >= 0, a row is safe to drop only when
  803. // no out-of-scope inbound still references the email.
  804. if id < 0 {
  805. err = tx.Where(depletedClause, now).Delete(xray.ClientTraffic{}).Error
  806. return err
  807. }
  808. emails := make([]string, 0, len(depletedEmails))
  809. for e := range depletedEmails {
  810. emails = append(emails, e)
  811. }
  812. var stillReferenced []string
  813. emailExpr := database.JSONFieldText("client.value", "email")
  814. stillQuery := fmt.Sprintf(
  815. "SELECT DISTINCT LOWER(%s) %s WHERE LOWER(%s) IN ?",
  816. emailExpr,
  817. database.JSONClientsFromInbound(),
  818. emailExpr,
  819. )
  820. if err = tx.Raw(stillQuery, emails).Scan(&stillReferenced).Error; err != nil {
  821. return err
  822. }
  823. stillSet := make(map[string]struct{}, len(stillReferenced))
  824. for _, e := range stillReferenced {
  825. stillSet[e] = struct{}{}
  826. }
  827. toDelete := make([]string, 0, len(emails))
  828. for _, e := range emails {
  829. if _, kept := stillSet[e]; !kept {
  830. toDelete = append(toDelete, e)
  831. }
  832. }
  833. if len(toDelete) > 0 {
  834. if err = tx.Where("LOWER(email) IN ?", toDelete).Delete(xray.ClientTraffic{}).Error; err != nil {
  835. return err
  836. }
  837. }
  838. return nil
  839. }
  840. func (s *InboundService) GetClientTrafficTgBot(tgId int64) ([]*xray.ClientTraffic, error) {
  841. db := database.GetDB()
  842. idQuery := fmt.Sprintf(
  843. "SELECT DISTINCT inbounds.id %s WHERE %s = ?",
  844. database.JSONClientsFromInbound(),
  845. database.JSONFieldText("client.value", "tgId"),
  846. )
  847. var inboundIds []int
  848. if err := db.Raw(idQuery, strconv.FormatInt(tgId, 10)).Scan(&inboundIds).Error; err != nil {
  849. logger.Errorf("Error retrieving inbounds with tgId %d: %v", tgId, err)
  850. return nil, err
  851. }
  852. var inbounds []*model.Inbound
  853. if len(inboundIds) > 0 {
  854. err := db.Model(model.Inbound{}).Where("id IN ?", inboundIds).Find(&inbounds).Error
  855. if err != nil && !errors.Is(err, gorm.ErrRecordNotFound) {
  856. logger.Errorf("Error retrieving inbounds with tgId %d: %v", tgId, err)
  857. return nil, err
  858. }
  859. }
  860. var emails []string
  861. for _, inbound := range inbounds {
  862. clients, err := s.GetClients(inbound)
  863. if err != nil {
  864. logger.Errorf("Error retrieving clients for inbound %d: %v", inbound.Id, err)
  865. continue
  866. }
  867. for _, client := range clients {
  868. if client.TgID == tgId {
  869. emails = append(emails, client.Email)
  870. }
  871. }
  872. }
  873. // Chunked to stay under SQLite's bind-variable limit when a single Telegram
  874. // account owns thousands of clients across inbounds.
  875. uniqEmails := uniqueNonEmptyStrings(emails)
  876. traffics := make([]*xray.ClientTraffic, 0, len(uniqEmails))
  877. for _, batch := range chunkStrings(uniqEmails, sqliteMaxVars) {
  878. var page []*xray.ClientTraffic
  879. if err := db.Model(xray.ClientTraffic{}).Where("email IN ?", batch).Find(&page).Error; err != nil {
  880. if errors.Is(err, gorm.ErrRecordNotFound) {
  881. continue
  882. }
  883. logger.Errorf("Error retrieving ClientTraffic for emails %v: %v", batch, err)
  884. return nil, err
  885. }
  886. traffics = append(traffics, page...)
  887. }
  888. if len(traffics) == 0 {
  889. logger.Warning("No ClientTraffic records found for emails:", emails)
  890. return nil, nil
  891. }
  892. // Populate UUID and other client data for each traffic record
  893. for i := range traffics {
  894. if ct, client, e := s.GetClientByEmail(traffics[i].Email); e == nil && ct != nil && client != nil {
  895. traffics[i].Enable = client.Enable
  896. traffics[i].UUID = client.ID
  897. traffics[i].SubId = client.SubID
  898. }
  899. }
  900. return traffics, nil
  901. }
  902. // BumpClientsLastOnline sets client_traffics.last_online to now for the given
  903. // emails. Used in online-API mode for clients that hold a live connection but
  904. // moved no bytes this poll — the traffic path (addClientTraffic) only bumps
  905. // last_online on a non-zero delta, so idle-but-connected clients would
  906. // otherwise show a stale "last online" while being reported online.
  907. func (s *InboundService) BumpClientsLastOnline(emails []string) error {
  908. uniq := uniqueNonEmptyStrings(emails)
  909. if len(uniq) == 0 {
  910. return nil
  911. }
  912. now := time.Now().UnixMilli()
  913. return submitTrafficWrite(func() error {
  914. db := database.GetDB()
  915. for _, batch := range chunkStrings(uniq, sqliteMaxVars) {
  916. if err := db.Model(xray.ClientTraffic{}).Where("email IN ?", batch).Update("last_online", now).Error; err != nil {
  917. return err
  918. }
  919. }
  920. return nil
  921. })
  922. }
  923. func (s *InboundService) GetActiveClientTraffics(emails []string) ([]*xray.ClientTraffic, error) {
  924. uniq := uniqueNonEmptyStrings(emails)
  925. if len(uniq) == 0 {
  926. return nil, nil
  927. }
  928. db := database.GetDB()
  929. traffics := make([]*xray.ClientTraffic, 0, len(uniq))
  930. for _, batch := range chunkStrings(uniq, sqliteMaxVars) {
  931. var page []*xray.ClientTraffic
  932. if err := db.Model(xray.ClientTraffic{}).Where("email IN ?", batch).Find(&page).Error; err != nil {
  933. return nil, err
  934. }
  935. traffics = append(traffics, page...)
  936. }
  937. overlayGlobalTraffic(db, traffics)
  938. return traffics, nil
  939. }
  940. // GetAllClientTraffics returns the full set of client_traffics rows so the
  941. // websocket broadcasters can ship a complete snapshot every cycle. A pure
  942. // delta path silently dropped the per-client section whenever no client moved
  943. // bytes in the cycle or a node sync failed, leaving client rows in the UI
  944. // stuck at stale numbers — so small installs broadcast this snapshot, and only
  945. // above the traffic job's snapshot threshold (where the marshaled snapshot
  946. // would exceed the hub's payload cap and be dropped wholesale) does the job
  947. // fall back to active-row deltas.
  948. func (s *InboundService) GetAllClientTraffics() ([]*xray.ClientTraffic, error) {
  949. db := database.GetDB()
  950. var traffics []*xray.ClientTraffic
  951. if err := db.Model(xray.ClientTraffic{}).Find(&traffics).Error; err != nil {
  952. return nil, err
  953. }
  954. overlayGlobalTraffic(db, traffics)
  955. return traffics, nil
  956. }
  957. func (s *InboundService) CountClientTraffics() (int64, error) {
  958. db := database.GetDB()
  959. var count int64
  960. err := db.Model(xray.ClientTraffic{}).Count(&count).Error
  961. return count, err
  962. }
  963. type InboundTrafficSummary struct {
  964. Id int `json:"id"`
  965. Up int64 `json:"up"`
  966. Down int64 `json:"down"`
  967. Total int64 `json:"total"`
  968. Enable bool `json:"enable"`
  969. }
  970. func (s *InboundService) GetInboundsTrafficSummary() ([]InboundTrafficSummary, error) {
  971. db := database.GetDB()
  972. var summaries []InboundTrafficSummary
  973. if err := db.Model(&model.Inbound{}).
  974. Select("id, up, down, total, enable").
  975. Find(&summaries).Error; err != nil {
  976. return nil, err
  977. }
  978. return summaries, nil
  979. }
  980. func (s *InboundService) GetClientTrafficByEmail(email string) (traffic *xray.ClientTraffic, err error) {
  981. db := database.GetDB()
  982. var traffics []*xray.ClientTraffic
  983. if err := db.Model(xray.ClientTraffic{}).Where("email = ?", email).Find(&traffics).Error; err != nil {
  984. logger.Warningf("Error retrieving ClientTraffic with email %s: %v", email, err)
  985. return nil, err
  986. }
  987. if len(traffics) == 0 {
  988. return nil, nil
  989. }
  990. overlayGlobalTraffic(db, traffics)
  991. t := traffics[0]
  992. if rec, rErr := s.clientService.GetRecordByEmail(db, email); rErr == nil && rec != nil {
  993. c := rec.ToClient()
  994. t.UUID = c.ID
  995. t.SubId = c.SubID
  996. return t, nil
  997. }
  998. t2, client, err := s.GetClientByEmail(email)
  999. if err != nil {
  1000. logger.Warningf("Error retrieving ClientTraffic with email %s: %v", email, err)
  1001. return nil, err
  1002. }
  1003. if t2 != nil && client != nil {
  1004. t2.UUID = client.ID
  1005. t2.SubId = client.SubID
  1006. return t2, nil
  1007. }
  1008. return nil, nil
  1009. }
  1010. func (s *InboundService) UpdateClientTrafficByEmail(email string, upload int64, download int64) error {
  1011. return submitTrafficWrite(func() error {
  1012. db := database.GetDB()
  1013. err := db.Model(xray.ClientTraffic{}).
  1014. Where("email = ?", email).
  1015. Updates(map[string]any{
  1016. "up": upload,
  1017. "down": download,
  1018. }).Error
  1019. if err != nil {
  1020. logger.Warningf("Error updating ClientTraffic with email %s: %v", email, err)
  1021. }
  1022. return err
  1023. })
  1024. }
  1025. func (s *InboundService) SearchClientTraffic(query string) (traffic *xray.ClientTraffic, err error) {
  1026. db := database.GetDB()
  1027. inbound := &model.Inbound{}
  1028. traffic = &xray.ClientTraffic{}
  1029. // Search for inbound settings that contain the query
  1030. err = db.Model(model.Inbound{}).Where("settings LIKE ?", "%\""+query+"\"%").First(inbound).Error
  1031. if err != nil {
  1032. if errors.Is(err, gorm.ErrRecordNotFound) {
  1033. logger.Warningf("Inbound settings containing query %s not found: %v", query, err)
  1034. return nil, err
  1035. }
  1036. logger.Errorf("Error searching for inbound settings with query %s: %v", query, err)
  1037. return nil, err
  1038. }
  1039. traffic.InboundId = inbound.Id
  1040. clients, err := ParseInboundSettingsClients(inbound.Settings)
  1041. if err != nil {
  1042. logger.Errorf("Error unmarshalling inbound settings for inbound ID %d: %v", inbound.Id, err)
  1043. return nil, err
  1044. }
  1045. for _, client := range clients {
  1046. if (client.ID == query || client.Password == query) && client.Email != "" {
  1047. traffic.Email = client.Email
  1048. break
  1049. }
  1050. }
  1051. if traffic.Email == "" {
  1052. logger.Warningf("No client found with query %s in inbound ID %d", query, inbound.Id)
  1053. return nil, gorm.ErrRecordNotFound
  1054. }
  1055. // Retrieve ClientTraffic based on the found email
  1056. err = db.Model(xray.ClientTraffic{}).Where("email = ?", traffic.Email).First(traffic).Error
  1057. if err != nil {
  1058. if errors.Is(err, gorm.ErrRecordNotFound) {
  1059. logger.Warningf("ClientTraffic for email %s not found: %v", traffic.Email, err)
  1060. return nil, err
  1061. }
  1062. logger.Errorf("Error retrieving ClientTraffic for email %s: %v", traffic.Email, err)
  1063. return nil, err
  1064. }
  1065. return traffic, nil
  1066. }