inbound_traffic.go 34 KB

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