inbound_traffic.go 33 KB

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