inbound_traffic.go 31 KB

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