inbound_traffic.go 32 KB

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