inbound_traffic.go 33 KB

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