1
0

inbound_traffic.go 31 KB

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