1
0

inbound_traffic.go 33 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093
  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. return 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. }
  492. func (s *InboundService) ResetClientTraffic(id int, clientEmail string) (needRestart bool, err error) {
  493. err = submitTrafficWrite(func() error {
  494. var inner error
  495. needRestart, inner = s.resetClientTrafficLocked(id, clientEmail)
  496. return inner
  497. })
  498. return
  499. }
  500. func (s *InboundService) resetClientTrafficLocked(id int, clientEmail string) (bool, error) {
  501. needRestart := false
  502. traffic, err := s.GetClientTrafficByEmail(clientEmail)
  503. if err != nil {
  504. return false, err
  505. }
  506. if !traffic.Enable {
  507. inbound, err := s.GetInbound(id)
  508. if err != nil {
  509. return false, err
  510. }
  511. clients, err := s.GetClients(inbound)
  512. if err != nil {
  513. return false, err
  514. }
  515. for _, client := range clients {
  516. if client.Email == clientEmail && client.Enable {
  517. rt, push, _, perr := s.nodePushPlan(inbound)
  518. if perr != nil {
  519. return false, perr
  520. }
  521. if !push {
  522. if inbound.NodeID == nil {
  523. needRestart = true
  524. }
  525. break
  526. }
  527. cipher := ""
  528. if string(inbound.Protocol) == "shadowsocks" {
  529. var oldSettings map[string]any
  530. err = json.Unmarshal([]byte(inbound.Settings), &oldSettings)
  531. if err != nil {
  532. return false, err
  533. }
  534. cipher = oldSettings["method"].(string)
  535. }
  536. err1 := rt.AddUser(context.Background(), inbound, map[string]any{
  537. "email": client.Email,
  538. "id": client.ID,
  539. "auth": client.Auth,
  540. "security": client.Security,
  541. "flow": client.Flow,
  542. "password": client.Password,
  543. "cipher": cipher,
  544. })
  545. if err1 == nil {
  546. logger.Debug("Client enabled on", rt.Name(), "due to reset traffic:", clientEmail)
  547. } else if inbound.NodeID != nil {
  548. logger.Warning("Error in enabling client on", rt.Name(), ":", err1)
  549. } else {
  550. logger.Debug("Error in enabling client on", rt.Name(), ":", err1)
  551. needRestart = true
  552. }
  553. break
  554. }
  555. }
  556. }
  557. traffic.Up = 0
  558. traffic.Down = 0
  559. traffic.Enable = true
  560. db := database.GetDB()
  561. now := time.Now().UnixMilli()
  562. inbound, err := s.GetInbound(id)
  563. if err != nil {
  564. return false, err
  565. }
  566. if err := db.Transaction(func(tx *gorm.DB) error {
  567. if err := adjustGroupBaselinesForRemovedTraffic(tx, []string{clientEmail}); err != nil {
  568. return err
  569. }
  570. if err := tx.Save(traffic).Error; err != nil {
  571. return err
  572. }
  573. if err := clearGlobalTraffic(tx, clientEmail); err != nil {
  574. return err
  575. }
  576. if err := tx.Where("email = ?", clientEmail).Delete(&model.NodeClientTraffic{}).Error; err != nil {
  577. return err
  578. }
  579. if err := tx.Model(model.Inbound{}).
  580. Where("id = ?", id).
  581. Update("last_traffic_reset_time", now).Error; err != nil {
  582. return err
  583. }
  584. if inbound != nil && inbound.NodeID != nil {
  585. return (&NodeService{}).MarkNodeDirtyTx(tx, *inbound.NodeID)
  586. }
  587. return nil
  588. }); err != nil {
  589. return false, err
  590. }
  591. if inbound != nil && inbound.NodeID != nil {
  592. if rt, rterr := s.runtimeFor(inbound); rterr == nil {
  593. if e := rt.ResetClientTraffic(context.Background(), inbound, clientEmail); e != nil {
  594. logger.Warning("ResetClientTraffic: remote propagation to", rt.Name(), "failed:", e)
  595. }
  596. } else {
  597. logger.Warning("ResetClientTraffic: runtime lookup failed:", rterr)
  598. }
  599. }
  600. return needRestart, nil
  601. }
  602. func (s *InboundService) ResetAllTraffics() error {
  603. return submitTrafficWrite(func() error {
  604. return s.resetAllTrafficsLocked()
  605. })
  606. }
  607. func (s *InboundService) resetAllTrafficsLocked() error {
  608. db := database.GetDB()
  609. now := time.Now().UnixMilli()
  610. if err := db.Model(model.Inbound{}).
  611. Where("user_id > ?", 0).
  612. Updates(map[string]any{
  613. "up": 0,
  614. "down": 0,
  615. "last_traffic_reset_time": now,
  616. }).Error; err != nil {
  617. return err
  618. }
  619. nodes, err := (&NodeService{}).GetAll()
  620. if err == nil {
  621. for _, node := range nodes {
  622. if rt, err := runtime.GetManager().RuntimeFor(&node.Id); err == nil {
  623. if e := rt.ResetAllTraffics(context.Background()); e != nil {
  624. logger.Warning("ResetAllTraffics: remote propagation to", rt.Name(), "failed:", e)
  625. }
  626. }
  627. }
  628. }
  629. return nil
  630. }
  631. func (s *InboundService) ResetInboundTraffic(id int) error {
  632. return submitTrafficWrite(func() error {
  633. db := database.GetDB()
  634. if err := db.Model(model.Inbound{}).
  635. Where("id = ?", id).
  636. Updates(map[string]any{"up": 0, "down": 0}).Error; err != nil {
  637. return err
  638. }
  639. inbound, err := s.GetInbound(id)
  640. if err == nil && inbound != nil && inbound.NodeID != nil {
  641. if rt, rterr := s.runtimeFor(inbound); rterr == nil {
  642. if e := rt.ResetInboundTraffic(context.Background(), inbound); e != nil {
  643. logger.Warning("ResetInboundTraffic: remote propagation to", rt.Name(), "failed:", e)
  644. }
  645. } else {
  646. logger.Warning("ResetInboundTraffic: runtime lookup failed:", rterr)
  647. }
  648. }
  649. return nil
  650. })
  651. }
  652. func (s *InboundService) DelDepletedClients(id int) (err error) {
  653. db := database.GetDB()
  654. tx := db.Begin()
  655. defer func() {
  656. if err == nil {
  657. tx.Commit()
  658. } else {
  659. tx.Rollback()
  660. }
  661. }()
  662. // Collect depleted emails globally — a shared-email row owned by one
  663. // inbound depletes every sibling that lists the email.
  664. now := time.Now().Unix() * 1000
  665. depletedClause := "reset = 0 and ((total > 0 and up + down >= total) or (expiry_time > 0 and expiry_time <= ?))"
  666. var depletedRows []xray.ClientTraffic
  667. err = db.Model(xray.ClientTraffic{}).
  668. Where(depletedClause, now).
  669. Find(&depletedRows).Error
  670. if err != nil {
  671. return err
  672. }
  673. if len(depletedRows) == 0 {
  674. return nil
  675. }
  676. depletedEmails := make(map[string]struct{}, len(depletedRows))
  677. for _, r := range depletedRows {
  678. if r.Email == "" {
  679. continue
  680. }
  681. depletedEmails[strings.ToLower(r.Email)] = struct{}{}
  682. }
  683. if len(depletedEmails) == 0 {
  684. return nil
  685. }
  686. var inbounds []*model.Inbound
  687. inboundQuery := db.Model(model.Inbound{})
  688. if id >= 0 {
  689. inboundQuery = inboundQuery.Where("id = ?", id)
  690. }
  691. if err = inboundQuery.Find(&inbounds).Error; err != nil {
  692. return err
  693. }
  694. for _, inbound := range inbounds {
  695. var settings map[string]any
  696. if err = json.Unmarshal([]byte(inbound.Settings), &settings); err != nil {
  697. return err
  698. }
  699. rawClients, ok := settings["clients"].([]any)
  700. if !ok {
  701. continue
  702. }
  703. newClients := make([]any, 0, len(rawClients))
  704. removed := 0
  705. for _, client := range rawClients {
  706. c, ok := client.(map[string]any)
  707. if !ok {
  708. newClients = append(newClients, client)
  709. continue
  710. }
  711. email, _ := c["email"].(string)
  712. if _, isDepleted := depletedEmails[strings.ToLower(email)]; isDepleted {
  713. removed++
  714. continue
  715. }
  716. newClients = append(newClients, client)
  717. }
  718. if removed == 0 {
  719. continue
  720. }
  721. if len(newClients) == 0 {
  722. _, _ = s.DelInbound(inbound.Id)
  723. continue
  724. }
  725. settings["clients"] = newClients
  726. ns, mErr := json.MarshalIndent(settings, "", " ")
  727. if mErr != nil {
  728. return mErr
  729. }
  730. inbound.Settings = string(ns)
  731. if err = tx.Save(inbound).Error; err != nil {
  732. return err
  733. }
  734. survivingClients, gcErr := s.GetClients(inbound)
  735. if gcErr != nil {
  736. err = gcErr
  737. return err
  738. }
  739. if err = s.clientService.SyncInbound(tx, inbound.Id, survivingClients); err != nil {
  740. return err
  741. }
  742. }
  743. // Drop now-orphaned rows. With id >= 0, a row is safe to drop only when
  744. // no out-of-scope inbound still references the email.
  745. if id < 0 {
  746. err = tx.Where(depletedClause, now).Delete(xray.ClientTraffic{}).Error
  747. return err
  748. }
  749. emails := make([]string, 0, len(depletedEmails))
  750. for e := range depletedEmails {
  751. emails = append(emails, e)
  752. }
  753. var stillReferenced []string
  754. emailExpr := database.JSONFieldText("client.value", "email")
  755. stillQuery := fmt.Sprintf(
  756. "SELECT DISTINCT LOWER(%s) %s WHERE LOWER(%s) IN ?",
  757. emailExpr,
  758. database.JSONClientsFromInbound(),
  759. emailExpr,
  760. )
  761. if err = tx.Raw(stillQuery, emails).Scan(&stillReferenced).Error; err != nil {
  762. return err
  763. }
  764. stillSet := make(map[string]struct{}, len(stillReferenced))
  765. for _, e := range stillReferenced {
  766. stillSet[e] = struct{}{}
  767. }
  768. toDelete := make([]string, 0, len(emails))
  769. for _, e := range emails {
  770. if _, kept := stillSet[e]; !kept {
  771. toDelete = append(toDelete, e)
  772. }
  773. }
  774. if len(toDelete) > 0 {
  775. if err = tx.Where("LOWER(email) IN ?", toDelete).Delete(xray.ClientTraffic{}).Error; err != nil {
  776. return err
  777. }
  778. }
  779. return nil
  780. }
  781. func (s *InboundService) GetClientTrafficTgBot(tgId int64) ([]*xray.ClientTraffic, error) {
  782. db := database.GetDB()
  783. idQuery := fmt.Sprintf(
  784. "SELECT DISTINCT inbounds.id %s WHERE %s = ?",
  785. database.JSONClientsFromInbound(),
  786. database.JSONFieldText("client.value", "tgId"),
  787. )
  788. var inboundIds []int
  789. if err := db.Raw(idQuery, strconv.FormatInt(tgId, 10)).Scan(&inboundIds).Error; err != nil {
  790. logger.Errorf("Error retrieving inbounds with tgId %d: %v", tgId, err)
  791. return nil, err
  792. }
  793. var inbounds []*model.Inbound
  794. if len(inboundIds) > 0 {
  795. err := db.Model(model.Inbound{}).Where("id IN ?", inboundIds).Find(&inbounds).Error
  796. if err != nil && !errors.Is(err, gorm.ErrRecordNotFound) {
  797. logger.Errorf("Error retrieving inbounds with tgId %d: %v", tgId, err)
  798. return nil, err
  799. }
  800. }
  801. var emails []string
  802. for _, inbound := range inbounds {
  803. clients, err := s.GetClients(inbound)
  804. if err != nil {
  805. logger.Errorf("Error retrieving clients for inbound %d: %v", inbound.Id, err)
  806. continue
  807. }
  808. for _, client := range clients {
  809. if client.TgID == tgId {
  810. emails = append(emails, client.Email)
  811. }
  812. }
  813. }
  814. // Chunked to stay under SQLite's bind-variable limit when a single Telegram
  815. // account owns thousands of clients across inbounds.
  816. uniqEmails := uniqueNonEmptyStrings(emails)
  817. traffics := make([]*xray.ClientTraffic, 0, len(uniqEmails))
  818. for _, batch := range chunkStrings(uniqEmails, sqliteMaxVars) {
  819. var page []*xray.ClientTraffic
  820. if err := db.Model(xray.ClientTraffic{}).Where("email IN ?", batch).Find(&page).Error; err != nil {
  821. if errors.Is(err, gorm.ErrRecordNotFound) {
  822. continue
  823. }
  824. logger.Errorf("Error retrieving ClientTraffic for emails %v: %v", batch, err)
  825. return nil, err
  826. }
  827. traffics = append(traffics, page...)
  828. }
  829. if len(traffics) == 0 {
  830. logger.Warning("No ClientTraffic records found for emails:", emails)
  831. return nil, nil
  832. }
  833. // Populate UUID and other client data for each traffic record
  834. for i := range traffics {
  835. if ct, client, e := s.GetClientByEmail(traffics[i].Email); e == nil && ct != nil && client != nil {
  836. traffics[i].Enable = client.Enable
  837. traffics[i].UUID = client.ID
  838. traffics[i].SubId = client.SubID
  839. }
  840. }
  841. return traffics, nil
  842. }
  843. // BumpClientsLastOnline sets client_traffics.last_online to now for the given
  844. // emails. Used in online-API mode for clients that hold a live connection but
  845. // moved no bytes this poll — the traffic path (addClientTraffic) only bumps
  846. // last_online on a non-zero delta, so idle-but-connected clients would
  847. // otherwise show a stale "last online" while being reported online.
  848. func (s *InboundService) BumpClientsLastOnline(emails []string) error {
  849. uniq := uniqueNonEmptyStrings(emails)
  850. if len(uniq) == 0 {
  851. return nil
  852. }
  853. now := time.Now().UnixMilli()
  854. return submitTrafficWrite(func() error {
  855. db := database.GetDB()
  856. for _, batch := range chunkStrings(uniq, sqliteMaxVars) {
  857. if err := db.Model(xray.ClientTraffic{}).Where("email IN ?", batch).Update("last_online", now).Error; err != nil {
  858. return err
  859. }
  860. }
  861. return nil
  862. })
  863. }
  864. func (s *InboundService) GetActiveClientTraffics(emails []string) ([]*xray.ClientTraffic, error) {
  865. uniq := uniqueNonEmptyStrings(emails)
  866. if len(uniq) == 0 {
  867. return nil, nil
  868. }
  869. db := database.GetDB()
  870. traffics := make([]*xray.ClientTraffic, 0, len(uniq))
  871. for _, batch := range chunkStrings(uniq, sqliteMaxVars) {
  872. var page []*xray.ClientTraffic
  873. if err := db.Model(xray.ClientTraffic{}).Where("email IN ?", batch).Find(&page).Error; err != nil {
  874. return nil, err
  875. }
  876. traffics = append(traffics, page...)
  877. }
  878. overlayGlobalTraffic(db, traffics)
  879. return traffics, nil
  880. }
  881. // GetAllClientTraffics returns the full set of client_traffics rows so the
  882. // websocket broadcasters can ship a complete snapshot every cycle. A pure
  883. // delta path silently dropped the per-client section whenever no client moved
  884. // bytes in the cycle or a node sync failed, leaving client rows in the UI
  885. // stuck at stale numbers — so small installs broadcast this snapshot, and only
  886. // above the traffic job's snapshot threshold (where the marshaled snapshot
  887. // would exceed the hub's payload cap and be dropped wholesale) does the job
  888. // fall back to active-row deltas.
  889. func (s *InboundService) GetAllClientTraffics() ([]*xray.ClientTraffic, error) {
  890. db := database.GetDB()
  891. var traffics []*xray.ClientTraffic
  892. if err := db.Model(xray.ClientTraffic{}).Find(&traffics).Error; err != nil {
  893. return nil, err
  894. }
  895. overlayGlobalTraffic(db, traffics)
  896. return traffics, nil
  897. }
  898. func (s *InboundService) CountClientTraffics() (int64, error) {
  899. db := database.GetDB()
  900. var count int64
  901. err := db.Model(xray.ClientTraffic{}).Count(&count).Error
  902. return count, err
  903. }
  904. type InboundTrafficSummary struct {
  905. Id int `json:"id"`
  906. Up int64 `json:"up"`
  907. Down int64 `json:"down"`
  908. Total int64 `json:"total"`
  909. Enable bool `json:"enable"`
  910. }
  911. func (s *InboundService) GetInboundsTrafficSummary() ([]InboundTrafficSummary, error) {
  912. db := database.GetDB()
  913. var summaries []InboundTrafficSummary
  914. if err := db.Model(&model.Inbound{}).
  915. Select("id, up, down, total, enable").
  916. Find(&summaries).Error; err != nil {
  917. return nil, err
  918. }
  919. return summaries, nil
  920. }
  921. func (s *InboundService) GetClientTrafficByEmail(email string) (traffic *xray.ClientTraffic, err error) {
  922. db := database.GetDB()
  923. var traffics []*xray.ClientTraffic
  924. if err := db.Model(xray.ClientTraffic{}).Where("email = ?", email).Find(&traffics).Error; err != nil {
  925. logger.Warningf("Error retrieving ClientTraffic with email %s: %v", email, err)
  926. return nil, err
  927. }
  928. if len(traffics) == 0 {
  929. return nil, nil
  930. }
  931. overlayGlobalTraffic(db, traffics)
  932. t := traffics[0]
  933. if rec, rErr := s.clientService.GetRecordByEmail(db, email); rErr == nil && rec != nil {
  934. c := rec.ToClient()
  935. t.UUID = c.ID
  936. t.SubId = c.SubID
  937. return t, nil
  938. }
  939. t2, client, err := s.GetClientByEmail(email)
  940. if err != nil {
  941. logger.Warningf("Error retrieving ClientTraffic with email %s: %v", email, err)
  942. return nil, err
  943. }
  944. if t2 != nil && client != nil {
  945. t2.UUID = client.ID
  946. t2.SubId = client.SubID
  947. return t2, nil
  948. }
  949. return nil, nil
  950. }
  951. func (s *InboundService) UpdateClientTrafficByEmail(email string, upload int64, download int64) error {
  952. return submitTrafficWrite(func() error {
  953. db := database.GetDB()
  954. err := db.Model(xray.ClientTraffic{}).
  955. Where("email = ?", email).
  956. Updates(map[string]any{
  957. "up": upload,
  958. "down": download,
  959. }).Error
  960. if err != nil {
  961. logger.Warningf("Error updating ClientTraffic with email %s: %v", email, err)
  962. }
  963. return err
  964. })
  965. }
  966. func (s *InboundService) SearchClientTraffic(query string) (traffic *xray.ClientTraffic, err error) {
  967. db := database.GetDB()
  968. inbound := &model.Inbound{}
  969. traffic = &xray.ClientTraffic{}
  970. // Search for inbound settings that contain the query
  971. err = db.Model(model.Inbound{}).Where("settings LIKE ?", "%\""+query+"\"%").First(inbound).Error
  972. if err != nil {
  973. if errors.Is(err, gorm.ErrRecordNotFound) {
  974. logger.Warningf("Inbound settings containing query %s not found: %v", query, err)
  975. return nil, err
  976. }
  977. logger.Errorf("Error searching for inbound settings with query %s: %v", query, err)
  978. return nil, err
  979. }
  980. traffic.InboundId = inbound.Id
  981. // Unmarshal settings to get clients
  982. settings := map[string][]model.Client{}
  983. if err := json.Unmarshal([]byte(inbound.Settings), &settings); err != nil {
  984. logger.Errorf("Error unmarshalling inbound settings for inbound ID %d: %v", inbound.Id, err)
  985. return nil, err
  986. }
  987. clients := settings["clients"]
  988. for _, client := range clients {
  989. if (client.ID == query || client.Password == query) && client.Email != "" {
  990. traffic.Email = client.Email
  991. break
  992. }
  993. }
  994. if traffic.Email == "" {
  995. logger.Warningf("No client found with query %s in inbound ID %d", query, inbound.Id)
  996. return nil, gorm.ErrRecordNotFound
  997. }
  998. // Retrieve ClientTraffic based on the found email
  999. err = db.Model(xray.ClientTraffic{}).Where("email = ?", traffic.Email).First(traffic).Error
  1000. if err != nil {
  1001. if errors.Is(err, gorm.ErrRecordNotFound) {
  1002. logger.Warningf("ClientTraffic for email %s not found: %v", traffic.Email, err)
  1003. return nil, err
  1004. }
  1005. logger.Errorf("Error retrieving ClientTraffic for email %s: %v", traffic.Email, err)
  1006. return nil, err
  1007. }
  1008. return traffic, nil
  1009. }