inbound.go 66 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474
  1. // Package service provides business logic services for the 3x-ui web panel,
  2. // including inbound/outbound management, user administration, settings, and Xray integration.
  3. package service
  4. import (
  5. "encoding/json"
  6. "fmt"
  7. "sort"
  8. "strconv"
  9. "strings"
  10. "time"
  11. "github.com/mhsanaei/3x-ui/v2/database"
  12. "github.com/mhsanaei/3x-ui/v2/database/model"
  13. "github.com/mhsanaei/3x-ui/v2/logger"
  14. "github.com/mhsanaei/3x-ui/v2/util/common"
  15. "github.com/mhsanaei/3x-ui/v2/xray"
  16. "gorm.io/gorm"
  17. )
  18. // InboundService provides business logic for managing Xray inbound configurations.
  19. // It handles CRUD operations for inbounds, client management, traffic monitoring,
  20. // and integration with the Xray API for real-time updates.
  21. type InboundService struct {
  22. xrayApi xray.XrayAPI
  23. }
  24. // GetInbounds retrieves all inbounds for a specific user.
  25. // Returns a slice of inbound models with their associated client statistics.
  26. func (s *InboundService) GetInbounds(userId int) ([]*model.Inbound, error) {
  27. db := database.GetDB()
  28. var inbounds []*model.Inbound
  29. err := db.Model(model.Inbound{}).Preload("ClientStats").Where("user_id = ?", userId).Find(&inbounds).Error
  30. if err != nil && err != gorm.ErrRecordNotFound {
  31. return nil, err
  32. }
  33. // Enrich client stats with UUID/SubId from inbound settings
  34. for _, inbound := range inbounds {
  35. clients, _ := s.GetClients(inbound)
  36. if len(clients) == 0 || len(inbound.ClientStats) == 0 {
  37. continue
  38. }
  39. // Build a map email -> client
  40. cMap := make(map[string]model.Client, len(clients))
  41. for _, c := range clients {
  42. cMap[strings.ToLower(c.Email)] = c
  43. }
  44. for i := range inbound.ClientStats {
  45. email := strings.ToLower(inbound.ClientStats[i].Email)
  46. if c, ok := cMap[email]; ok {
  47. inbound.ClientStats[i].UUID = c.ID
  48. inbound.ClientStats[i].SubId = c.SubID
  49. }
  50. }
  51. }
  52. return inbounds, nil
  53. }
  54. // GetAllInbounds retrieves all inbounds from the database.
  55. // Returns a slice of all inbound models with their associated client statistics.
  56. func (s *InboundService) GetAllInbounds() ([]*model.Inbound, error) {
  57. db := database.GetDB()
  58. var inbounds []*model.Inbound
  59. err := db.Model(model.Inbound{}).Preload("ClientStats").Find(&inbounds).Error
  60. if err != nil && err != gorm.ErrRecordNotFound {
  61. return nil, err
  62. }
  63. // Enrich client stats with UUID/SubId from inbound settings
  64. for _, inbound := range inbounds {
  65. clients, _ := s.GetClients(inbound)
  66. if len(clients) == 0 || len(inbound.ClientStats) == 0 {
  67. continue
  68. }
  69. cMap := make(map[string]model.Client, len(clients))
  70. for _, c := range clients {
  71. cMap[strings.ToLower(c.Email)] = c
  72. }
  73. for i := range inbound.ClientStats {
  74. email := strings.ToLower(inbound.ClientStats[i].Email)
  75. if c, ok := cMap[email]; ok {
  76. inbound.ClientStats[i].UUID = c.ID
  77. inbound.ClientStats[i].SubId = c.SubID
  78. }
  79. }
  80. }
  81. return inbounds, nil
  82. }
  83. func (s *InboundService) GetInboundsByTrafficReset(period string) ([]*model.Inbound, error) {
  84. db := database.GetDB()
  85. var inbounds []*model.Inbound
  86. err := db.Model(model.Inbound{}).Where("traffic_reset = ?", period).Find(&inbounds).Error
  87. if err != nil && err != gorm.ErrRecordNotFound {
  88. return nil, err
  89. }
  90. return inbounds, nil
  91. }
  92. func (s *InboundService) checkPortExist(listen string, port int, ignoreId int) (bool, error) {
  93. db := database.GetDB()
  94. if listen == "" || listen == "0.0.0.0" || listen == "::" || listen == "::0" {
  95. db = db.Model(model.Inbound{}).Where("port = ?", port)
  96. } else {
  97. db = db.Model(model.Inbound{}).
  98. Where("port = ?", port).
  99. Where(
  100. db.Model(model.Inbound{}).Where(
  101. "listen = ?", listen,
  102. ).Or(
  103. "listen = \"\"",
  104. ).Or(
  105. "listen = \"0.0.0.0\"",
  106. ).Or(
  107. "listen = \"::\"",
  108. ).Or(
  109. "listen = \"::0\""))
  110. }
  111. if ignoreId > 0 {
  112. db = db.Where("id != ?", ignoreId)
  113. }
  114. var count int64
  115. err := db.Count(&count).Error
  116. if err != nil {
  117. return false, err
  118. }
  119. return count > 0, nil
  120. }
  121. func (s *InboundService) GetClients(inbound *model.Inbound) ([]model.Client, error) {
  122. settings := map[string][]model.Client{}
  123. json.Unmarshal([]byte(inbound.Settings), &settings)
  124. if settings == nil {
  125. return nil, fmt.Errorf("setting is null")
  126. }
  127. clients := settings["clients"]
  128. if clients == nil {
  129. return nil, nil
  130. }
  131. return clients, nil
  132. }
  133. func (s *InboundService) getAllEmails() ([]string, error) {
  134. db := database.GetDB()
  135. var emails []string
  136. err := db.Raw(`
  137. SELECT JSON_EXTRACT(client.value, '$.email')
  138. FROM inbounds,
  139. JSON_EACH(JSON_EXTRACT(inbounds.settings, '$.clients')) AS client
  140. `).Scan(&emails).Error
  141. if err != nil {
  142. return nil, err
  143. }
  144. return emails, nil
  145. }
  146. func (s *InboundService) contains(slice []string, str string) bool {
  147. lowerStr := strings.ToLower(str)
  148. for _, s := range slice {
  149. if strings.ToLower(s) == lowerStr {
  150. return true
  151. }
  152. }
  153. return false
  154. }
  155. func (s *InboundService) checkEmailsExistForClients(clients []model.Client) (string, error) {
  156. allEmails, err := s.getAllEmails()
  157. if err != nil {
  158. return "", err
  159. }
  160. var emails []string
  161. for _, client := range clients {
  162. if client.Email != "" {
  163. if s.contains(emails, client.Email) {
  164. return client.Email, nil
  165. }
  166. if s.contains(allEmails, client.Email) {
  167. return client.Email, nil
  168. }
  169. emails = append(emails, client.Email)
  170. }
  171. }
  172. return "", nil
  173. }
  174. func (s *InboundService) checkEmailExistForInbound(inbound *model.Inbound) (string, error) {
  175. clients, err := s.GetClients(inbound)
  176. if err != nil {
  177. return "", err
  178. }
  179. allEmails, err := s.getAllEmails()
  180. if err != nil {
  181. return "", err
  182. }
  183. var emails []string
  184. for _, client := range clients {
  185. if client.Email != "" {
  186. if s.contains(emails, client.Email) {
  187. return client.Email, nil
  188. }
  189. if s.contains(allEmails, client.Email) {
  190. return client.Email, nil
  191. }
  192. emails = append(emails, client.Email)
  193. }
  194. }
  195. return "", nil
  196. }
  197. // AddInbound creates a new inbound configuration.
  198. // It validates port uniqueness, client email uniqueness, and required fields,
  199. // then saves the inbound to the database and optionally adds it to the running Xray instance.
  200. // Returns the created inbound, whether Xray needs restart, and any error.
  201. func (s *InboundService) AddInbound(inbound *model.Inbound) (*model.Inbound, bool, error) {
  202. exist, err := s.checkPortExist(inbound.Listen, inbound.Port, 0)
  203. if err != nil {
  204. return inbound, false, err
  205. }
  206. if exist {
  207. return inbound, false, common.NewError("Port already exists:", inbound.Port)
  208. }
  209. existEmail, err := s.checkEmailExistForInbound(inbound)
  210. if err != nil {
  211. return inbound, false, err
  212. }
  213. if existEmail != "" {
  214. return inbound, false, common.NewError("Duplicate email:", existEmail)
  215. }
  216. clients, err := s.GetClients(inbound)
  217. if err != nil {
  218. return inbound, false, err
  219. }
  220. // Ensure created_at and updated_at on clients in settings
  221. if len(clients) > 0 {
  222. var settings map[string]any
  223. if err2 := json.Unmarshal([]byte(inbound.Settings), &settings); err2 == nil && settings != nil {
  224. now := time.Now().Unix() * 1000
  225. updatedClients := make([]model.Client, 0, len(clients))
  226. for _, c := range clients {
  227. if c.CreatedAt == 0 {
  228. c.CreatedAt = now
  229. }
  230. c.UpdatedAt = now
  231. updatedClients = append(updatedClients, c)
  232. }
  233. settings["clients"] = updatedClients
  234. if bs, err3 := json.MarshalIndent(settings, "", " "); err3 == nil {
  235. inbound.Settings = string(bs)
  236. } else {
  237. logger.Debug("Unable to marshal inbound settings with timestamps:", err3)
  238. }
  239. } else if err2 != nil {
  240. logger.Debug("Unable to parse inbound settings for timestamps:", err2)
  241. }
  242. }
  243. // Secure client ID
  244. for _, client := range clients {
  245. switch inbound.Protocol {
  246. case "trojan":
  247. if client.Password == "" {
  248. return inbound, false, common.NewError("empty client ID")
  249. }
  250. case "shadowsocks":
  251. if client.Email == "" {
  252. return inbound, false, common.NewError("empty client ID")
  253. }
  254. default:
  255. if client.ID == "" {
  256. return inbound, false, common.NewError("empty client ID")
  257. }
  258. }
  259. }
  260. db := database.GetDB()
  261. tx := db.Begin()
  262. defer func() {
  263. if err == nil {
  264. tx.Commit()
  265. } else {
  266. tx.Rollback()
  267. }
  268. }()
  269. err = tx.Save(inbound).Error
  270. if err == nil {
  271. if len(inbound.ClientStats) == 0 {
  272. for _, client := range clients {
  273. s.AddClientStat(tx, inbound.Id, &client)
  274. }
  275. }
  276. } else {
  277. return inbound, false, err
  278. }
  279. needRestart := false
  280. if inbound.Enable {
  281. s.xrayApi.Init(p.GetAPIPort())
  282. inboundJson, err1 := json.MarshalIndent(inbound.GenXrayInboundConfig(), "", " ")
  283. if err1 != nil {
  284. logger.Debug("Unable to marshal inbound config:", err1)
  285. }
  286. err1 = s.xrayApi.AddInbound(inboundJson)
  287. if err1 == nil {
  288. logger.Debug("New inbound added by api:", inbound.Tag)
  289. } else {
  290. logger.Debug("Unable to add inbound by api:", err1)
  291. needRestart = true
  292. }
  293. s.xrayApi.Close()
  294. }
  295. return inbound, needRestart, err
  296. }
  297. // DelInbound deletes an inbound configuration by ID.
  298. // It removes the inbound from the database and the running Xray instance if active.
  299. // Returns whether Xray needs restart and any error.
  300. func (s *InboundService) DelInbound(id int) (bool, error) {
  301. db := database.GetDB()
  302. var tag string
  303. needRestart := false
  304. result := db.Model(model.Inbound{}).Select("tag").Where("id = ? and enable = ?", id, true).First(&tag)
  305. if result.Error == nil {
  306. s.xrayApi.Init(p.GetAPIPort())
  307. err1 := s.xrayApi.DelInbound(tag)
  308. if err1 == nil {
  309. logger.Debug("Inbound deleted by api:", tag)
  310. } else {
  311. logger.Debug("Unable to delete inbound by api:", err1)
  312. needRestart = true
  313. }
  314. s.xrayApi.Close()
  315. } else {
  316. logger.Debug("No enabled inbound founded to removing by api", tag)
  317. }
  318. // Delete client traffics of inbounds
  319. err := db.Where("inbound_id = ?", id).Delete(xray.ClientTraffic{}).Error
  320. if err != nil {
  321. return false, err
  322. }
  323. inbound, err := s.GetInbound(id)
  324. if err != nil {
  325. return false, err
  326. }
  327. clients, err := s.GetClients(inbound)
  328. if err != nil {
  329. return false, err
  330. }
  331. for _, client := range clients {
  332. err := s.DelClientIPs(db, client.Email)
  333. if err != nil {
  334. return false, err
  335. }
  336. }
  337. return needRestart, db.Delete(model.Inbound{}, id).Error
  338. }
  339. func (s *InboundService) GetInbound(id int) (*model.Inbound, error) {
  340. db := database.GetDB()
  341. inbound := &model.Inbound{}
  342. err := db.Model(model.Inbound{}).First(inbound, id).Error
  343. if err != nil {
  344. return nil, err
  345. }
  346. return inbound, nil
  347. }
  348. // UpdateInbound modifies an existing inbound configuration.
  349. // It validates changes, updates the database, and syncs with the running Xray instance.
  350. // Returns the updated inbound, whether Xray needs restart, and any error.
  351. func (s *InboundService) UpdateInbound(inbound *model.Inbound) (*model.Inbound, bool, error) {
  352. exist, err := s.checkPortExist(inbound.Listen, inbound.Port, inbound.Id)
  353. if err != nil {
  354. return inbound, false, err
  355. }
  356. if exist {
  357. return inbound, false, common.NewError("Port already exists:", inbound.Port)
  358. }
  359. oldInbound, err := s.GetInbound(inbound.Id)
  360. if err != nil {
  361. return inbound, false, err
  362. }
  363. tag := oldInbound.Tag
  364. db := database.GetDB()
  365. tx := db.Begin()
  366. defer func() {
  367. if err != nil {
  368. tx.Rollback()
  369. } else {
  370. tx.Commit()
  371. }
  372. }()
  373. err = s.updateClientTraffics(tx, oldInbound, inbound)
  374. if err != nil {
  375. return inbound, false, err
  376. }
  377. // Ensure created_at and updated_at exist in inbound.Settings clients
  378. {
  379. var oldSettings map[string]any
  380. _ = json.Unmarshal([]byte(oldInbound.Settings), &oldSettings)
  381. emailToCreated := map[string]int64{}
  382. emailToUpdated := map[string]int64{}
  383. if oldSettings != nil {
  384. if oc, ok := oldSettings["clients"].([]any); ok {
  385. for _, it := range oc {
  386. if m, ok2 := it.(map[string]any); ok2 {
  387. if email, ok3 := m["email"].(string); ok3 {
  388. switch v := m["created_at"].(type) {
  389. case float64:
  390. emailToCreated[email] = int64(v)
  391. case int64:
  392. emailToCreated[email] = v
  393. }
  394. switch v := m["updated_at"].(type) {
  395. case float64:
  396. emailToUpdated[email] = int64(v)
  397. case int64:
  398. emailToUpdated[email] = v
  399. }
  400. }
  401. }
  402. }
  403. }
  404. }
  405. var newSettings map[string]any
  406. if err2 := json.Unmarshal([]byte(inbound.Settings), &newSettings); err2 == nil && newSettings != nil {
  407. now := time.Now().Unix() * 1000
  408. if nSlice, ok := newSettings["clients"].([]any); ok {
  409. for i := range nSlice {
  410. if m, ok2 := nSlice[i].(map[string]any); ok2 {
  411. email, _ := m["email"].(string)
  412. if _, ok3 := m["created_at"]; !ok3 {
  413. if v, ok4 := emailToCreated[email]; ok4 && v > 0 {
  414. m["created_at"] = v
  415. } else {
  416. m["created_at"] = now
  417. }
  418. }
  419. // Preserve client's updated_at if present; do not bump on parent inbound update
  420. if _, hasUpdated := m["updated_at"]; !hasUpdated {
  421. if v, ok4 := emailToUpdated[email]; ok4 && v > 0 {
  422. m["updated_at"] = v
  423. }
  424. }
  425. nSlice[i] = m
  426. }
  427. }
  428. newSettings["clients"] = nSlice
  429. if bs, err3 := json.MarshalIndent(newSettings, "", " "); err3 == nil {
  430. inbound.Settings = string(bs)
  431. }
  432. }
  433. }
  434. }
  435. oldInbound.Up = inbound.Up
  436. oldInbound.Down = inbound.Down
  437. oldInbound.Total = inbound.Total
  438. oldInbound.Remark = inbound.Remark
  439. oldInbound.Enable = inbound.Enable
  440. oldInbound.ExpiryTime = inbound.ExpiryTime
  441. oldInbound.TrafficReset = inbound.TrafficReset
  442. oldInbound.Listen = inbound.Listen
  443. oldInbound.Port = inbound.Port
  444. oldInbound.Protocol = inbound.Protocol
  445. oldInbound.Settings = inbound.Settings
  446. oldInbound.StreamSettings = inbound.StreamSettings
  447. oldInbound.Sniffing = inbound.Sniffing
  448. if inbound.Listen == "" || inbound.Listen == "0.0.0.0" || inbound.Listen == "::" || inbound.Listen == "::0" {
  449. oldInbound.Tag = fmt.Sprintf("inbound-%v", inbound.Port)
  450. } else {
  451. oldInbound.Tag = fmt.Sprintf("inbound-%v:%v", inbound.Listen, inbound.Port)
  452. }
  453. needRestart := false
  454. s.xrayApi.Init(p.GetAPIPort())
  455. if s.xrayApi.DelInbound(tag) == nil {
  456. logger.Debug("Old inbound deleted by api:", tag)
  457. }
  458. if inbound.Enable {
  459. inboundJson, err2 := json.MarshalIndent(oldInbound.GenXrayInboundConfig(), "", " ")
  460. if err2 != nil {
  461. logger.Debug("Unable to marshal updated inbound config:", err2)
  462. needRestart = true
  463. } else {
  464. err2 = s.xrayApi.AddInbound(inboundJson)
  465. if err2 == nil {
  466. logger.Debug("Updated inbound added by api:", oldInbound.Tag)
  467. } else {
  468. logger.Debug("Unable to update inbound by api:", err2)
  469. needRestart = true
  470. }
  471. }
  472. }
  473. s.xrayApi.Close()
  474. return inbound, needRestart, tx.Save(oldInbound).Error
  475. }
  476. func (s *InboundService) updateClientTraffics(tx *gorm.DB, oldInbound *model.Inbound, newInbound *model.Inbound) error {
  477. oldClients, err := s.GetClients(oldInbound)
  478. if err != nil {
  479. return err
  480. }
  481. newClients, err := s.GetClients(newInbound)
  482. if err != nil {
  483. return err
  484. }
  485. var emailExists bool
  486. for _, oldClient := range oldClients {
  487. emailExists = false
  488. for _, newClient := range newClients {
  489. if oldClient.Email == newClient.Email {
  490. emailExists = true
  491. break
  492. }
  493. }
  494. if !emailExists {
  495. err = s.DelClientStat(tx, oldClient.Email)
  496. if err != nil {
  497. return err
  498. }
  499. }
  500. }
  501. for _, newClient := range newClients {
  502. emailExists = false
  503. for _, oldClient := range oldClients {
  504. if newClient.Email == oldClient.Email {
  505. emailExists = true
  506. break
  507. }
  508. }
  509. if !emailExists {
  510. err = s.AddClientStat(tx, oldInbound.Id, &newClient)
  511. if err != nil {
  512. return err
  513. }
  514. }
  515. }
  516. return nil
  517. }
  518. func (s *InboundService) AddInboundClient(data *model.Inbound) (bool, error) {
  519. clients, err := s.GetClients(data)
  520. if err != nil {
  521. return false, err
  522. }
  523. var settings map[string]any
  524. err = json.Unmarshal([]byte(data.Settings), &settings)
  525. if err != nil {
  526. return false, err
  527. }
  528. interfaceClients := settings["clients"].([]any)
  529. // Add timestamps for new clients being appended
  530. nowTs := time.Now().Unix() * 1000
  531. for i := range interfaceClients {
  532. if cm, ok := interfaceClients[i].(map[string]any); ok {
  533. if _, ok2 := cm["created_at"]; !ok2 {
  534. cm["created_at"] = nowTs
  535. }
  536. cm["updated_at"] = nowTs
  537. interfaceClients[i] = cm
  538. }
  539. }
  540. existEmail, err := s.checkEmailsExistForClients(clients)
  541. if err != nil {
  542. return false, err
  543. }
  544. if existEmail != "" {
  545. return false, common.NewError("Duplicate email:", existEmail)
  546. }
  547. oldInbound, err := s.GetInbound(data.Id)
  548. if err != nil {
  549. return false, err
  550. }
  551. // Secure client ID
  552. for _, client := range clients {
  553. switch oldInbound.Protocol {
  554. case "trojan":
  555. if client.Password == "" {
  556. return false, common.NewError("empty client ID")
  557. }
  558. case "shadowsocks":
  559. if client.Email == "" {
  560. return false, common.NewError("empty client ID")
  561. }
  562. default:
  563. if client.ID == "" {
  564. return false, common.NewError("empty client ID")
  565. }
  566. }
  567. }
  568. var oldSettings map[string]any
  569. err = json.Unmarshal([]byte(oldInbound.Settings), &oldSettings)
  570. if err != nil {
  571. return false, err
  572. }
  573. oldClients := oldSettings["clients"].([]any)
  574. oldClients = append(oldClients, interfaceClients...)
  575. oldSettings["clients"] = oldClients
  576. newSettings, err := json.MarshalIndent(oldSettings, "", " ")
  577. if err != nil {
  578. return false, err
  579. }
  580. oldInbound.Settings = string(newSettings)
  581. db := database.GetDB()
  582. tx := db.Begin()
  583. defer func() {
  584. if err != nil {
  585. tx.Rollback()
  586. } else {
  587. tx.Commit()
  588. }
  589. }()
  590. needRestart := false
  591. s.xrayApi.Init(p.GetAPIPort())
  592. for _, client := range clients {
  593. if len(client.Email) > 0 {
  594. s.AddClientStat(tx, data.Id, &client)
  595. if client.Enable {
  596. cipher := ""
  597. if oldInbound.Protocol == "shadowsocks" {
  598. cipher = oldSettings["method"].(string)
  599. }
  600. err1 := s.xrayApi.AddUser(string(oldInbound.Protocol), oldInbound.Tag, map[string]any{
  601. "email": client.Email,
  602. "id": client.ID,
  603. "security": client.Security,
  604. "flow": client.Flow,
  605. "password": client.Password,
  606. "cipher": cipher,
  607. })
  608. if err1 == nil {
  609. logger.Debug("Client added by api:", client.Email)
  610. } else {
  611. logger.Debug("Error in adding client by api:", err1)
  612. needRestart = true
  613. }
  614. }
  615. } else {
  616. needRestart = true
  617. }
  618. }
  619. s.xrayApi.Close()
  620. return needRestart, tx.Save(oldInbound).Error
  621. }
  622. func (s *InboundService) DelInboundClient(inboundId int, clientId string) (bool, error) {
  623. oldInbound, err := s.GetInbound(inboundId)
  624. if err != nil {
  625. logger.Error("Load Old Data Error")
  626. return false, err
  627. }
  628. var settings map[string]any
  629. err = json.Unmarshal([]byte(oldInbound.Settings), &settings)
  630. if err != nil {
  631. return false, err
  632. }
  633. email := ""
  634. client_key := "id"
  635. if oldInbound.Protocol == "trojan" {
  636. client_key = "password"
  637. }
  638. if oldInbound.Protocol == "shadowsocks" {
  639. client_key = "email"
  640. }
  641. interfaceClients := settings["clients"].([]any)
  642. var newClients []any
  643. needApiDel := false
  644. for _, client := range interfaceClients {
  645. c := client.(map[string]any)
  646. c_id := c[client_key].(string)
  647. if c_id == clientId {
  648. email, _ = c["email"].(string)
  649. needApiDel, _ = c["enable"].(bool)
  650. } else {
  651. newClients = append(newClients, client)
  652. }
  653. }
  654. if len(newClients) == 0 {
  655. return false, common.NewError("no client remained in Inbound")
  656. }
  657. settings["clients"] = newClients
  658. newSettings, err := json.MarshalIndent(settings, "", " ")
  659. if err != nil {
  660. return false, err
  661. }
  662. oldInbound.Settings = string(newSettings)
  663. db := database.GetDB()
  664. err = s.DelClientIPs(db, email)
  665. if err != nil {
  666. logger.Error("Error in delete client IPs")
  667. return false, err
  668. }
  669. needRestart := false
  670. if len(email) > 0 {
  671. notDepleted := true
  672. err = db.Model(xray.ClientTraffic{}).Select("enable").Where("email = ?", email).First(&notDepleted).Error
  673. if err != nil {
  674. logger.Error("Get stats error")
  675. return false, err
  676. }
  677. err = s.DelClientStat(db, email)
  678. if err != nil {
  679. logger.Error("Delete stats Data Error")
  680. return false, err
  681. }
  682. if needApiDel && notDepleted {
  683. s.xrayApi.Init(p.GetAPIPort())
  684. err1 := s.xrayApi.RemoveUser(oldInbound.Tag, email)
  685. if err1 == nil {
  686. logger.Debug("Client deleted by api:", email)
  687. needRestart = false
  688. } else {
  689. if strings.Contains(err1.Error(), fmt.Sprintf("User %s not found.", email)) {
  690. logger.Debug("User is already deleted. Nothing to do more...")
  691. } else {
  692. logger.Debug("Error in deleting client by api:", err1)
  693. needRestart = true
  694. }
  695. }
  696. s.xrayApi.Close()
  697. }
  698. }
  699. return needRestart, db.Save(oldInbound).Error
  700. }
  701. func (s *InboundService) UpdateInboundClient(data *model.Inbound, clientId string) (bool, error) {
  702. // TODO: check if TrafficReset field is updating
  703. clients, err := s.GetClients(data)
  704. if err != nil {
  705. return false, err
  706. }
  707. var settings map[string]any
  708. err = json.Unmarshal([]byte(data.Settings), &settings)
  709. if err != nil {
  710. return false, err
  711. }
  712. interfaceClients := settings["clients"].([]any)
  713. oldInbound, err := s.GetInbound(data.Id)
  714. if err != nil {
  715. return false, err
  716. }
  717. oldClients, err := s.GetClients(oldInbound)
  718. if err != nil {
  719. return false, err
  720. }
  721. oldEmail := ""
  722. newClientId := ""
  723. clientIndex := -1
  724. for index, oldClient := range oldClients {
  725. oldClientId := ""
  726. switch oldInbound.Protocol {
  727. case "trojan":
  728. oldClientId = oldClient.Password
  729. newClientId = clients[0].Password
  730. case "shadowsocks":
  731. oldClientId = oldClient.Email
  732. newClientId = clients[0].Email
  733. default:
  734. oldClientId = oldClient.ID
  735. newClientId = clients[0].ID
  736. }
  737. if clientId == oldClientId {
  738. oldEmail = oldClient.Email
  739. clientIndex = index
  740. break
  741. }
  742. }
  743. // Validate new client ID
  744. if newClientId == "" || clientIndex == -1 {
  745. return false, common.NewError("empty client ID")
  746. }
  747. if len(clients[0].Email) > 0 && clients[0].Email != oldEmail {
  748. existEmail, err := s.checkEmailsExistForClients(clients)
  749. if err != nil {
  750. return false, err
  751. }
  752. if existEmail != "" {
  753. return false, common.NewError("Duplicate email:", existEmail)
  754. }
  755. }
  756. var oldSettings map[string]any
  757. err = json.Unmarshal([]byte(oldInbound.Settings), &oldSettings)
  758. if err != nil {
  759. return false, err
  760. }
  761. settingsClients := oldSettings["clients"].([]any)
  762. // Preserve created_at and set updated_at for the replacing client
  763. var preservedCreated any
  764. if clientIndex >= 0 && clientIndex < len(settingsClients) {
  765. if oldMap, ok := settingsClients[clientIndex].(map[string]any); ok {
  766. if v, ok2 := oldMap["created_at"]; ok2 {
  767. preservedCreated = v
  768. }
  769. }
  770. }
  771. if len(interfaceClients) > 0 {
  772. if newMap, ok := interfaceClients[0].(map[string]any); ok {
  773. if preservedCreated == nil {
  774. preservedCreated = time.Now().Unix() * 1000
  775. }
  776. newMap["created_at"] = preservedCreated
  777. newMap["updated_at"] = time.Now().Unix() * 1000
  778. interfaceClients[0] = newMap
  779. }
  780. }
  781. settingsClients[clientIndex] = interfaceClients[0]
  782. oldSettings["clients"] = settingsClients
  783. newSettings, err := json.MarshalIndent(oldSettings, "", " ")
  784. if err != nil {
  785. return false, err
  786. }
  787. oldInbound.Settings = string(newSettings)
  788. db := database.GetDB()
  789. tx := db.Begin()
  790. defer func() {
  791. if err != nil {
  792. tx.Rollback()
  793. } else {
  794. tx.Commit()
  795. }
  796. }()
  797. if len(clients[0].Email) > 0 {
  798. if len(oldEmail) > 0 {
  799. err = s.UpdateClientStat(tx, oldEmail, &clients[0])
  800. if err != nil {
  801. return false, err
  802. }
  803. err = s.UpdateClientIPs(tx, oldEmail, clients[0].Email)
  804. if err != nil {
  805. return false, err
  806. }
  807. } else {
  808. s.AddClientStat(tx, data.Id, &clients[0])
  809. }
  810. } else {
  811. err = s.DelClientStat(tx, oldEmail)
  812. if err != nil {
  813. return false, err
  814. }
  815. err = s.DelClientIPs(tx, oldEmail)
  816. if err != nil {
  817. return false, err
  818. }
  819. }
  820. needRestart := false
  821. if len(oldEmail) > 0 {
  822. s.xrayApi.Init(p.GetAPIPort())
  823. if oldClients[clientIndex].Enable {
  824. err1 := s.xrayApi.RemoveUser(oldInbound.Tag, oldEmail)
  825. if err1 == nil {
  826. logger.Debug("Old client deleted by api:", oldEmail)
  827. } else {
  828. if strings.Contains(err1.Error(), fmt.Sprintf("User %s not found.", oldEmail)) {
  829. logger.Debug("User is already deleted. Nothing to do more...")
  830. } else {
  831. logger.Debug("Error in deleting client by api:", err1)
  832. needRestart = true
  833. }
  834. }
  835. }
  836. if clients[0].Enable {
  837. cipher := ""
  838. if oldInbound.Protocol == "shadowsocks" {
  839. cipher = oldSettings["method"].(string)
  840. }
  841. err1 := s.xrayApi.AddUser(string(oldInbound.Protocol), oldInbound.Tag, map[string]any{
  842. "email": clients[0].Email,
  843. "id": clients[0].ID,
  844. "security": clients[0].Security,
  845. "flow": clients[0].Flow,
  846. "password": clients[0].Password,
  847. "cipher": cipher,
  848. })
  849. if err1 == nil {
  850. logger.Debug("Client edited by api:", clients[0].Email)
  851. } else {
  852. logger.Debug("Error in adding client by api:", err1)
  853. needRestart = true
  854. }
  855. }
  856. s.xrayApi.Close()
  857. } else {
  858. logger.Debug("Client old email not found")
  859. needRestart = true
  860. }
  861. return needRestart, tx.Save(oldInbound).Error
  862. }
  863. func (s *InboundService) AddTraffic(inboundTraffics []*xray.Traffic, clientTraffics []*xray.ClientTraffic) (error, bool) {
  864. var err error
  865. db := database.GetDB()
  866. tx := db.Begin()
  867. defer func() {
  868. if err != nil {
  869. tx.Rollback()
  870. } else {
  871. tx.Commit()
  872. }
  873. }()
  874. err = s.addInboundTraffic(tx, inboundTraffics)
  875. if err != nil {
  876. return err, false
  877. }
  878. err = s.addClientTraffic(tx, clientTraffics)
  879. if err != nil {
  880. return err, false
  881. }
  882. needRestart0, count, err := s.autoRenewClients(tx)
  883. if err != nil {
  884. logger.Warning("Error in renew clients:", err)
  885. } else if count > 0 {
  886. logger.Debugf("%v clients renewed", count)
  887. }
  888. needRestart1, count, err := s.disableInvalidClients(tx)
  889. if err != nil {
  890. logger.Warning("Error in disabling invalid clients:", err)
  891. } else if count > 0 {
  892. logger.Debugf("%v clients disabled", count)
  893. }
  894. needRestart2, count, err := s.disableInvalidInbounds(tx)
  895. if err != nil {
  896. logger.Warning("Error in disabling invalid inbounds:", err)
  897. } else if count > 0 {
  898. logger.Debugf("%v inbounds disabled", count)
  899. }
  900. return nil, (needRestart0 || needRestart1 || needRestart2)
  901. }
  902. func (s *InboundService) addInboundTraffic(tx *gorm.DB, traffics []*xray.Traffic) error {
  903. if len(traffics) == 0 {
  904. return nil
  905. }
  906. var err error
  907. for _, traffic := range traffics {
  908. if traffic.IsInbound {
  909. err = tx.Model(&model.Inbound{}).Where("tag = ?", traffic.Tag).
  910. Updates(map[string]any{
  911. "up": gorm.Expr("up + ?", traffic.Up),
  912. "down": gorm.Expr("down + ?", traffic.Down),
  913. "all_time": gorm.Expr("COALESCE(all_time, 0) + ?", traffic.Up+traffic.Down),
  914. }).Error
  915. if err != nil {
  916. return err
  917. }
  918. }
  919. }
  920. return nil
  921. }
  922. func (s *InboundService) addClientTraffic(tx *gorm.DB, traffics []*xray.ClientTraffic) (err error) {
  923. if len(traffics) == 0 {
  924. // Empty onlineUsers
  925. if p != nil {
  926. p.SetOnlineClients(nil)
  927. }
  928. return nil
  929. }
  930. var onlineClients []string
  931. emails := make([]string, 0, len(traffics))
  932. for _, traffic := range traffics {
  933. emails = append(emails, traffic.Email)
  934. }
  935. dbClientTraffics := make([]*xray.ClientTraffic, 0, len(traffics))
  936. err = tx.Model(xray.ClientTraffic{}).Where("email IN (?)", emails).Find(&dbClientTraffics).Error
  937. if err != nil {
  938. return err
  939. }
  940. // Avoid empty slice error
  941. if len(dbClientTraffics) == 0 {
  942. return nil
  943. }
  944. dbClientTraffics, err = s.adjustTraffics(tx, dbClientTraffics)
  945. if err != nil {
  946. return err
  947. }
  948. for dbTraffic_index := range dbClientTraffics {
  949. for traffic_index := range traffics {
  950. if dbClientTraffics[dbTraffic_index].Email == traffics[traffic_index].Email {
  951. dbClientTraffics[dbTraffic_index].Up += traffics[traffic_index].Up
  952. dbClientTraffics[dbTraffic_index].Down += traffics[traffic_index].Down
  953. dbClientTraffics[dbTraffic_index].AllTime += (traffics[traffic_index].Up + traffics[traffic_index].Down)
  954. // Add user in onlineUsers array on traffic
  955. if traffics[traffic_index].Up+traffics[traffic_index].Down > 0 {
  956. onlineClients = append(onlineClients, traffics[traffic_index].Email)
  957. dbClientTraffics[dbTraffic_index].LastOnline = time.Now().UnixMilli()
  958. }
  959. break
  960. }
  961. }
  962. }
  963. // Set onlineUsers
  964. p.SetOnlineClients(onlineClients)
  965. err = tx.Save(dbClientTraffics).Error
  966. if err != nil {
  967. logger.Warning("AddClientTraffic update data ", err)
  968. }
  969. return nil
  970. }
  971. func (s *InboundService) adjustTraffics(tx *gorm.DB, dbClientTraffics []*xray.ClientTraffic) ([]*xray.ClientTraffic, error) {
  972. inboundIds := make([]int, 0, len(dbClientTraffics))
  973. for _, dbClientTraffic := range dbClientTraffics {
  974. if dbClientTraffic.ExpiryTime < 0 {
  975. inboundIds = append(inboundIds, dbClientTraffic.InboundId)
  976. }
  977. }
  978. if len(inboundIds) > 0 {
  979. var inbounds []*model.Inbound
  980. err := tx.Model(model.Inbound{}).Where("id IN (?)", inboundIds).Find(&inbounds).Error
  981. if err != nil {
  982. return nil, err
  983. }
  984. for inbound_index := range inbounds {
  985. settings := map[string]any{}
  986. json.Unmarshal([]byte(inbounds[inbound_index].Settings), &settings)
  987. clients, ok := settings["clients"].([]any)
  988. if ok {
  989. var newClients []any
  990. for client_index := range clients {
  991. c := clients[client_index].(map[string]any)
  992. for traffic_index := range dbClientTraffics {
  993. if dbClientTraffics[traffic_index].ExpiryTime < 0 && c["email"] == dbClientTraffics[traffic_index].Email {
  994. oldExpiryTime := c["expiryTime"].(float64)
  995. newExpiryTime := (time.Now().Unix() * 1000) - int64(oldExpiryTime)
  996. c["expiryTime"] = newExpiryTime
  997. c["updated_at"] = time.Now().Unix() * 1000
  998. dbClientTraffics[traffic_index].ExpiryTime = newExpiryTime
  999. break
  1000. }
  1001. }
  1002. // Backfill created_at and updated_at
  1003. if _, ok := c["created_at"]; !ok {
  1004. c["created_at"] = time.Now().Unix() * 1000
  1005. }
  1006. c["updated_at"] = time.Now().Unix() * 1000
  1007. newClients = append(newClients, any(c))
  1008. }
  1009. settings["clients"] = newClients
  1010. modifiedSettings, err := json.MarshalIndent(settings, "", " ")
  1011. if err != nil {
  1012. return nil, err
  1013. }
  1014. inbounds[inbound_index].Settings = string(modifiedSettings)
  1015. }
  1016. }
  1017. err = tx.Save(inbounds).Error
  1018. if err != nil {
  1019. logger.Warning("AddClientTraffic update inbounds ", err)
  1020. logger.Error(inbounds)
  1021. }
  1022. }
  1023. return dbClientTraffics, nil
  1024. }
  1025. func (s *InboundService) autoRenewClients(tx *gorm.DB) (bool, int64, error) {
  1026. // check for time expired
  1027. var traffics []*xray.ClientTraffic
  1028. now := time.Now().Unix() * 1000
  1029. var err, err1 error
  1030. err = tx.Model(xray.ClientTraffic{}).Where("reset > 0 and expiry_time > 0 and expiry_time <= ?", now).Find(&traffics).Error
  1031. if err != nil {
  1032. return false, 0, err
  1033. }
  1034. // return if there is no client to renew
  1035. if len(traffics) == 0 {
  1036. return false, 0, nil
  1037. }
  1038. var inbound_ids []int
  1039. var inbounds []*model.Inbound
  1040. needRestart := false
  1041. var clientsToAdd []struct {
  1042. protocol string
  1043. tag string
  1044. client map[string]any
  1045. }
  1046. for _, traffic := range traffics {
  1047. inbound_ids = append(inbound_ids, traffic.InboundId)
  1048. }
  1049. err = tx.Model(model.Inbound{}).Where("id IN ?", inbound_ids).Find(&inbounds).Error
  1050. if err != nil {
  1051. return false, 0, err
  1052. }
  1053. for inbound_index := range inbounds {
  1054. settings := map[string]any{}
  1055. json.Unmarshal([]byte(inbounds[inbound_index].Settings), &settings)
  1056. clients := settings["clients"].([]any)
  1057. for client_index := range clients {
  1058. c := clients[client_index].(map[string]any)
  1059. for traffic_index, traffic := range traffics {
  1060. if traffic.Email == c["email"].(string) {
  1061. newExpiryTime := traffic.ExpiryTime
  1062. for newExpiryTime < now {
  1063. newExpiryTime += (int64(traffic.Reset) * 86400000)
  1064. }
  1065. c["expiryTime"] = newExpiryTime
  1066. traffics[traffic_index].ExpiryTime = newExpiryTime
  1067. traffics[traffic_index].Down = 0
  1068. traffics[traffic_index].Up = 0
  1069. if !traffic.Enable {
  1070. traffics[traffic_index].Enable = true
  1071. clientsToAdd = append(clientsToAdd,
  1072. struct {
  1073. protocol string
  1074. tag string
  1075. client map[string]any
  1076. }{
  1077. protocol: string(inbounds[inbound_index].Protocol),
  1078. tag: inbounds[inbound_index].Tag,
  1079. client: c,
  1080. })
  1081. }
  1082. clients[client_index] = any(c)
  1083. break
  1084. }
  1085. }
  1086. }
  1087. settings["clients"] = clients
  1088. newSettings, err := json.MarshalIndent(settings, "", " ")
  1089. if err != nil {
  1090. return false, 0, err
  1091. }
  1092. inbounds[inbound_index].Settings = string(newSettings)
  1093. }
  1094. err = tx.Save(inbounds).Error
  1095. if err != nil {
  1096. return false, 0, err
  1097. }
  1098. err = tx.Save(traffics).Error
  1099. if err != nil {
  1100. return false, 0, err
  1101. }
  1102. if p != nil {
  1103. err1 = s.xrayApi.Init(p.GetAPIPort())
  1104. if err1 != nil {
  1105. return true, int64(len(traffics)), nil
  1106. }
  1107. for _, clientToAdd := range clientsToAdd {
  1108. err1 = s.xrayApi.AddUser(clientToAdd.protocol, clientToAdd.tag, clientToAdd.client)
  1109. if err1 != nil {
  1110. needRestart = true
  1111. }
  1112. }
  1113. s.xrayApi.Close()
  1114. }
  1115. return needRestart, int64(len(traffics)), nil
  1116. }
  1117. func (s *InboundService) disableInvalidInbounds(tx *gorm.DB) (bool, int64, error) {
  1118. now := time.Now().Unix() * 1000
  1119. needRestart := false
  1120. if p != nil {
  1121. var tags []string
  1122. err := tx.Table("inbounds").
  1123. Select("inbounds.tag").
  1124. Where("((total > 0 and up + down >= total) or (expiry_time > 0 and expiry_time <= ?)) and enable = ?", now, true).
  1125. Scan(&tags).Error
  1126. if err != nil {
  1127. return false, 0, err
  1128. }
  1129. s.xrayApi.Init(p.GetAPIPort())
  1130. for _, tag := range tags {
  1131. err1 := s.xrayApi.DelInbound(tag)
  1132. if err1 == nil {
  1133. logger.Debug("Inbound disabled by api:", tag)
  1134. } else {
  1135. logger.Debug("Error in disabling inbound by api:", err1)
  1136. needRestart = true
  1137. }
  1138. }
  1139. s.xrayApi.Close()
  1140. }
  1141. result := tx.Model(model.Inbound{}).
  1142. Where("((total > 0 and up + down >= total) or (expiry_time > 0 and expiry_time <= ?)) and enable = ?", now, true).
  1143. Update("enable", false)
  1144. err := result.Error
  1145. count := result.RowsAffected
  1146. return needRestart, count, err
  1147. }
  1148. func (s *InboundService) disableInvalidClients(tx *gorm.DB) (bool, int64, error) {
  1149. now := time.Now().Unix() * 1000
  1150. needRestart := false
  1151. if p != nil {
  1152. var results []struct {
  1153. Tag string
  1154. Email string
  1155. }
  1156. err := tx.Table("inbounds").
  1157. Select("inbounds.tag, client_traffics.email").
  1158. Joins("JOIN client_traffics ON inbounds.id = client_traffics.inbound_id").
  1159. Where("((client_traffics.total > 0 AND client_traffics.up + client_traffics.down >= client_traffics.total) OR (client_traffics.expiry_time > 0 AND client_traffics.expiry_time <= ?)) AND client_traffics.enable = ?", now, true).
  1160. Scan(&results).Error
  1161. if err != nil {
  1162. return false, 0, err
  1163. }
  1164. s.xrayApi.Init(p.GetAPIPort())
  1165. for _, result := range results {
  1166. err1 := s.xrayApi.RemoveUser(result.Tag, result.Email)
  1167. if err1 == nil {
  1168. logger.Debug("Client disabled by api:", result.Email)
  1169. } else {
  1170. if strings.Contains(err1.Error(), fmt.Sprintf("User %s not found.", result.Email)) {
  1171. logger.Debug("User is already disabled. Nothing to do more...")
  1172. } else {
  1173. if strings.Contains(err1.Error(), fmt.Sprintf("User %s not found.", result.Email)) {
  1174. logger.Debug("User is already disabled. Nothing to do more...")
  1175. } else {
  1176. logger.Debug("Error in disabling client by api:", err1)
  1177. needRestart = true
  1178. }
  1179. }
  1180. }
  1181. }
  1182. s.xrayApi.Close()
  1183. }
  1184. result := tx.Model(xray.ClientTraffic{}).
  1185. Where("((total > 0 and up + down >= total) or (expiry_time > 0 and expiry_time <= ?)) and enable = ?", now, true).
  1186. Update("enable", false)
  1187. err := result.Error
  1188. count := result.RowsAffected
  1189. return needRestart, count, err
  1190. }
  1191. func (s *InboundService) GetInboundTags() (string, error) {
  1192. db := database.GetDB()
  1193. var inboundTags []string
  1194. err := db.Model(model.Inbound{}).Select("tag").Find(&inboundTags).Error
  1195. if err != nil && err != gorm.ErrRecordNotFound {
  1196. return "", err
  1197. }
  1198. tags, _ := json.Marshal(inboundTags)
  1199. return string(tags), nil
  1200. }
  1201. func (s *InboundService) MigrationRemoveOrphanedTraffics() {
  1202. db := database.GetDB()
  1203. db.Exec(`
  1204. DELETE FROM client_traffics
  1205. WHERE email NOT IN (
  1206. SELECT JSON_EXTRACT(client.value, '$.email')
  1207. FROM inbounds,
  1208. JSON_EACH(JSON_EXTRACT(inbounds.settings, '$.clients')) AS client
  1209. )
  1210. `)
  1211. }
  1212. func (s *InboundService) AddClientStat(tx *gorm.DB, inboundId int, client *model.Client) error {
  1213. clientTraffic := xray.ClientTraffic{}
  1214. clientTraffic.InboundId = inboundId
  1215. clientTraffic.Email = client.Email
  1216. clientTraffic.Total = client.TotalGB
  1217. clientTraffic.ExpiryTime = client.ExpiryTime
  1218. clientTraffic.Enable = client.Enable
  1219. clientTraffic.Up = 0
  1220. clientTraffic.Down = 0
  1221. clientTraffic.Reset = client.Reset
  1222. result := tx.Create(&clientTraffic)
  1223. err := result.Error
  1224. return err
  1225. }
  1226. func (s *InboundService) UpdateClientStat(tx *gorm.DB, email string, client *model.Client) error {
  1227. result := tx.Model(xray.ClientTraffic{}).
  1228. Where("email = ?", email).
  1229. Updates(map[string]any{
  1230. "enable": client.Enable,
  1231. "email": client.Email,
  1232. "total": client.TotalGB,
  1233. "expiry_time": client.ExpiryTime,
  1234. "reset": client.Reset,
  1235. })
  1236. err := result.Error
  1237. return err
  1238. }
  1239. func (s *InboundService) UpdateClientIPs(tx *gorm.DB, oldEmail string, newEmail string) error {
  1240. return tx.Model(model.InboundClientIps{}).Where("client_email = ?", oldEmail).Update("client_email", newEmail).Error
  1241. }
  1242. func (s *InboundService) DelClientStat(tx *gorm.DB, email string) error {
  1243. return tx.Where("email = ?", email).Delete(xray.ClientTraffic{}).Error
  1244. }
  1245. func (s *InboundService) DelClientIPs(tx *gorm.DB, email string) error {
  1246. return tx.Where("client_email = ?", email).Delete(model.InboundClientIps{}).Error
  1247. }
  1248. func (s *InboundService) GetClientInboundByTrafficID(trafficId int) (traffic *xray.ClientTraffic, inbound *model.Inbound, err error) {
  1249. db := database.GetDB()
  1250. var traffics []*xray.ClientTraffic
  1251. err = db.Model(xray.ClientTraffic{}).Where("id = ?", trafficId).Find(&traffics).Error
  1252. if err != nil {
  1253. logger.Warningf("Error retrieving ClientTraffic with trafficId %d: %v", trafficId, err)
  1254. return nil, nil, err
  1255. }
  1256. if len(traffics) > 0 {
  1257. inbound, err = s.GetInbound(traffics[0].InboundId)
  1258. return traffics[0], inbound, err
  1259. }
  1260. return nil, nil, nil
  1261. }
  1262. func (s *InboundService) GetClientInboundByEmail(email string) (traffic *xray.ClientTraffic, inbound *model.Inbound, err error) {
  1263. db := database.GetDB()
  1264. var traffics []*xray.ClientTraffic
  1265. err = db.Model(xray.ClientTraffic{}).Where("email = ?", email).Find(&traffics).Error
  1266. if err != nil {
  1267. logger.Warningf("Error retrieving ClientTraffic with email %s: %v", email, err)
  1268. return nil, nil, err
  1269. }
  1270. if len(traffics) > 0 {
  1271. inbound, err = s.GetInbound(traffics[0].InboundId)
  1272. return traffics[0], inbound, err
  1273. }
  1274. return nil, nil, nil
  1275. }
  1276. func (s *InboundService) GetClientByEmail(clientEmail string) (*xray.ClientTraffic, *model.Client, error) {
  1277. traffic, inbound, err := s.GetClientInboundByEmail(clientEmail)
  1278. if err != nil {
  1279. return nil, nil, err
  1280. }
  1281. if inbound == nil {
  1282. return nil, nil, common.NewError("Inbound Not Found For Email:", clientEmail)
  1283. }
  1284. clients, err := s.GetClients(inbound)
  1285. if err != nil {
  1286. return nil, nil, err
  1287. }
  1288. for _, client := range clients {
  1289. if client.Email == clientEmail {
  1290. return traffic, &client, nil
  1291. }
  1292. }
  1293. return nil, nil, common.NewError("Client Not Found In Inbound For Email:", clientEmail)
  1294. }
  1295. func (s *InboundService) SetClientTelegramUserID(trafficId int, tgId int64) (bool, error) {
  1296. traffic, inbound, err := s.GetClientInboundByTrafficID(trafficId)
  1297. if err != nil {
  1298. return false, err
  1299. }
  1300. if inbound == nil {
  1301. return false, common.NewError("Inbound Not Found For Traffic ID:", trafficId)
  1302. }
  1303. clientEmail := traffic.Email
  1304. oldClients, err := s.GetClients(inbound)
  1305. if err != nil {
  1306. return false, err
  1307. }
  1308. clientId := ""
  1309. for _, oldClient := range oldClients {
  1310. if oldClient.Email == clientEmail {
  1311. switch inbound.Protocol {
  1312. case "trojan":
  1313. clientId = oldClient.Password
  1314. case "shadowsocks":
  1315. clientId = oldClient.Email
  1316. default:
  1317. clientId = oldClient.ID
  1318. }
  1319. break
  1320. }
  1321. }
  1322. if len(clientId) == 0 {
  1323. return false, common.NewError("Client Not Found For Email:", clientEmail)
  1324. }
  1325. var settings map[string]any
  1326. err = json.Unmarshal([]byte(inbound.Settings), &settings)
  1327. if err != nil {
  1328. return false, err
  1329. }
  1330. clients := settings["clients"].([]any)
  1331. var newClients []any
  1332. for client_index := range clients {
  1333. c := clients[client_index].(map[string]any)
  1334. if c["email"] == clientEmail {
  1335. c["tgId"] = tgId
  1336. c["updated_at"] = time.Now().Unix() * 1000
  1337. newClients = append(newClients, any(c))
  1338. }
  1339. }
  1340. settings["clients"] = newClients
  1341. modifiedSettings, err := json.MarshalIndent(settings, "", " ")
  1342. if err != nil {
  1343. return false, err
  1344. }
  1345. inbound.Settings = string(modifiedSettings)
  1346. needRestart, err := s.UpdateInboundClient(inbound, clientId)
  1347. return needRestart, err
  1348. }
  1349. func (s *InboundService) checkIsEnabledByEmail(clientEmail string) (bool, error) {
  1350. _, inbound, err := s.GetClientInboundByEmail(clientEmail)
  1351. if err != nil {
  1352. return false, err
  1353. }
  1354. if inbound == nil {
  1355. return false, common.NewError("Inbound Not Found For Email:", clientEmail)
  1356. }
  1357. clients, err := s.GetClients(inbound)
  1358. if err != nil {
  1359. return false, err
  1360. }
  1361. isEnable := false
  1362. for _, client := range clients {
  1363. if client.Email == clientEmail {
  1364. isEnable = client.Enable
  1365. break
  1366. }
  1367. }
  1368. return isEnable, err
  1369. }
  1370. func (s *InboundService) ToggleClientEnableByEmail(clientEmail string) (bool, bool, error) {
  1371. _, inbound, err := s.GetClientInboundByEmail(clientEmail)
  1372. if err != nil {
  1373. return false, false, err
  1374. }
  1375. if inbound == nil {
  1376. return false, false, common.NewError("Inbound Not Found For Email:", clientEmail)
  1377. }
  1378. oldClients, err := s.GetClients(inbound)
  1379. if err != nil {
  1380. return false, false, err
  1381. }
  1382. clientId := ""
  1383. clientOldEnabled := false
  1384. for _, oldClient := range oldClients {
  1385. if oldClient.Email == clientEmail {
  1386. switch inbound.Protocol {
  1387. case "trojan":
  1388. clientId = oldClient.Password
  1389. case "shadowsocks":
  1390. clientId = oldClient.Email
  1391. default:
  1392. clientId = oldClient.ID
  1393. }
  1394. clientOldEnabled = oldClient.Enable
  1395. break
  1396. }
  1397. }
  1398. if len(clientId) == 0 {
  1399. return false, false, common.NewError("Client Not Found For Email:", clientEmail)
  1400. }
  1401. var settings map[string]any
  1402. err = json.Unmarshal([]byte(inbound.Settings), &settings)
  1403. if err != nil {
  1404. return false, false, err
  1405. }
  1406. clients := settings["clients"].([]any)
  1407. var newClients []any
  1408. for client_index := range clients {
  1409. c := clients[client_index].(map[string]any)
  1410. if c["email"] == clientEmail {
  1411. c["enable"] = !clientOldEnabled
  1412. c["updated_at"] = time.Now().Unix() * 1000
  1413. newClients = append(newClients, any(c))
  1414. }
  1415. }
  1416. settings["clients"] = newClients
  1417. modifiedSettings, err := json.MarshalIndent(settings, "", " ")
  1418. if err != nil {
  1419. return false, false, err
  1420. }
  1421. inbound.Settings = string(modifiedSettings)
  1422. needRestart, err := s.UpdateInboundClient(inbound, clientId)
  1423. if err != nil {
  1424. return false, needRestart, err
  1425. }
  1426. return !clientOldEnabled, needRestart, nil
  1427. }
  1428. // SetClientEnableByEmail sets client enable state to desired value; returns (changed, needRestart, error)
  1429. func (s *InboundService) SetClientEnableByEmail(clientEmail string, enable bool) (bool, bool, error) {
  1430. current, err := s.checkIsEnabledByEmail(clientEmail)
  1431. if err != nil {
  1432. return false, false, err
  1433. }
  1434. if current == enable {
  1435. return false, false, nil
  1436. }
  1437. newEnabled, needRestart, err := s.ToggleClientEnableByEmail(clientEmail)
  1438. if err != nil {
  1439. return false, needRestart, err
  1440. }
  1441. return newEnabled == enable, needRestart, nil
  1442. }
  1443. func (s *InboundService) ResetClientIpLimitByEmail(clientEmail string, count int) (bool, error) {
  1444. _, inbound, err := s.GetClientInboundByEmail(clientEmail)
  1445. if err != nil {
  1446. return false, err
  1447. }
  1448. if inbound == nil {
  1449. return false, common.NewError("Inbound Not Found For Email:", clientEmail)
  1450. }
  1451. oldClients, err := s.GetClients(inbound)
  1452. if err != nil {
  1453. return false, err
  1454. }
  1455. clientId := ""
  1456. for _, oldClient := range oldClients {
  1457. if oldClient.Email == clientEmail {
  1458. switch inbound.Protocol {
  1459. case "trojan":
  1460. clientId = oldClient.Password
  1461. case "shadowsocks":
  1462. clientId = oldClient.Email
  1463. default:
  1464. clientId = oldClient.ID
  1465. }
  1466. break
  1467. }
  1468. }
  1469. if len(clientId) == 0 {
  1470. return false, common.NewError("Client Not Found For Email:", clientEmail)
  1471. }
  1472. var settings map[string]any
  1473. err = json.Unmarshal([]byte(inbound.Settings), &settings)
  1474. if err != nil {
  1475. return false, err
  1476. }
  1477. clients := settings["clients"].([]any)
  1478. var newClients []any
  1479. for client_index := range clients {
  1480. c := clients[client_index].(map[string]any)
  1481. if c["email"] == clientEmail {
  1482. c["limitIp"] = count
  1483. c["updated_at"] = time.Now().Unix() * 1000
  1484. newClients = append(newClients, any(c))
  1485. }
  1486. }
  1487. settings["clients"] = newClients
  1488. modifiedSettings, err := json.MarshalIndent(settings, "", " ")
  1489. if err != nil {
  1490. return false, err
  1491. }
  1492. inbound.Settings = string(modifiedSettings)
  1493. needRestart, err := s.UpdateInboundClient(inbound, clientId)
  1494. return needRestart, err
  1495. }
  1496. func (s *InboundService) ResetClientExpiryTimeByEmail(clientEmail string, expiry_time int64) (bool, error) {
  1497. _, inbound, err := s.GetClientInboundByEmail(clientEmail)
  1498. if err != nil {
  1499. return false, err
  1500. }
  1501. if inbound == nil {
  1502. return false, common.NewError("Inbound Not Found For Email:", clientEmail)
  1503. }
  1504. oldClients, err := s.GetClients(inbound)
  1505. if err != nil {
  1506. return false, err
  1507. }
  1508. clientId := ""
  1509. for _, oldClient := range oldClients {
  1510. if oldClient.Email == clientEmail {
  1511. switch inbound.Protocol {
  1512. case "trojan":
  1513. clientId = oldClient.Password
  1514. case "shadowsocks":
  1515. clientId = oldClient.Email
  1516. default:
  1517. clientId = oldClient.ID
  1518. }
  1519. break
  1520. }
  1521. }
  1522. if len(clientId) == 0 {
  1523. return false, common.NewError("Client Not Found For Email:", clientEmail)
  1524. }
  1525. var settings map[string]any
  1526. err = json.Unmarshal([]byte(inbound.Settings), &settings)
  1527. if err != nil {
  1528. return false, err
  1529. }
  1530. clients := settings["clients"].([]any)
  1531. var newClients []any
  1532. for client_index := range clients {
  1533. c := clients[client_index].(map[string]any)
  1534. if c["email"] == clientEmail {
  1535. c["expiryTime"] = expiry_time
  1536. c["updated_at"] = time.Now().Unix() * 1000
  1537. newClients = append(newClients, any(c))
  1538. }
  1539. }
  1540. settings["clients"] = newClients
  1541. modifiedSettings, err := json.MarshalIndent(settings, "", " ")
  1542. if err != nil {
  1543. return false, err
  1544. }
  1545. inbound.Settings = string(modifiedSettings)
  1546. needRestart, err := s.UpdateInboundClient(inbound, clientId)
  1547. return needRestart, err
  1548. }
  1549. func (s *InboundService) ResetClientTrafficLimitByEmail(clientEmail string, totalGB int) (bool, error) {
  1550. if totalGB < 0 {
  1551. return false, common.NewError("totalGB must be >= 0")
  1552. }
  1553. _, inbound, err := s.GetClientInboundByEmail(clientEmail)
  1554. if err != nil {
  1555. return false, err
  1556. }
  1557. if inbound == nil {
  1558. return false, common.NewError("Inbound Not Found For Email:", clientEmail)
  1559. }
  1560. oldClients, err := s.GetClients(inbound)
  1561. if err != nil {
  1562. return false, err
  1563. }
  1564. clientId := ""
  1565. for _, oldClient := range oldClients {
  1566. if oldClient.Email == clientEmail {
  1567. switch inbound.Protocol {
  1568. case "trojan":
  1569. clientId = oldClient.Password
  1570. case "shadowsocks":
  1571. clientId = oldClient.Email
  1572. default:
  1573. clientId = oldClient.ID
  1574. }
  1575. break
  1576. }
  1577. }
  1578. if len(clientId) == 0 {
  1579. return false, common.NewError("Client Not Found For Email:", clientEmail)
  1580. }
  1581. var settings map[string]any
  1582. err = json.Unmarshal([]byte(inbound.Settings), &settings)
  1583. if err != nil {
  1584. return false, err
  1585. }
  1586. clients := settings["clients"].([]any)
  1587. var newClients []any
  1588. for client_index := range clients {
  1589. c := clients[client_index].(map[string]any)
  1590. if c["email"] == clientEmail {
  1591. c["totalGB"] = totalGB * 1024 * 1024 * 1024
  1592. c["updated_at"] = time.Now().Unix() * 1000
  1593. newClients = append(newClients, any(c))
  1594. }
  1595. }
  1596. settings["clients"] = newClients
  1597. modifiedSettings, err := json.MarshalIndent(settings, "", " ")
  1598. if err != nil {
  1599. return false, err
  1600. }
  1601. inbound.Settings = string(modifiedSettings)
  1602. needRestart, err := s.UpdateInboundClient(inbound, clientId)
  1603. return needRestart, err
  1604. }
  1605. func (s *InboundService) ResetClientTrafficByEmail(clientEmail string) error {
  1606. db := database.GetDB()
  1607. // Reset traffic stats in ClientTraffic table
  1608. result := db.Model(xray.ClientTraffic{}).
  1609. Where("email = ?", clientEmail).
  1610. Updates(map[string]any{"enable": true, "up": 0, "down": 0})
  1611. err := result.Error
  1612. if err != nil {
  1613. return err
  1614. }
  1615. return nil
  1616. }
  1617. func (s *InboundService) ResetClientTraffic(id int, clientEmail string) (bool, error) {
  1618. needRestart := false
  1619. traffic, err := s.GetClientTrafficByEmail(clientEmail)
  1620. if err != nil {
  1621. return false, err
  1622. }
  1623. if !traffic.Enable {
  1624. inbound, err := s.GetInbound(id)
  1625. if err != nil {
  1626. return false, err
  1627. }
  1628. clients, err := s.GetClients(inbound)
  1629. if err != nil {
  1630. return false, err
  1631. }
  1632. for _, client := range clients {
  1633. if client.Email == clientEmail && client.Enable {
  1634. s.xrayApi.Init(p.GetAPIPort())
  1635. cipher := ""
  1636. if string(inbound.Protocol) == "shadowsocks" {
  1637. var oldSettings map[string]any
  1638. err = json.Unmarshal([]byte(inbound.Settings), &oldSettings)
  1639. if err != nil {
  1640. return false, err
  1641. }
  1642. cipher = oldSettings["method"].(string)
  1643. }
  1644. err1 := s.xrayApi.AddUser(string(inbound.Protocol), inbound.Tag, map[string]any{
  1645. "email": client.Email,
  1646. "id": client.ID,
  1647. "security": client.Security,
  1648. "flow": client.Flow,
  1649. "password": client.Password,
  1650. "cipher": cipher,
  1651. })
  1652. if err1 == nil {
  1653. logger.Debug("Client enabled due to reset traffic:", clientEmail)
  1654. } else {
  1655. logger.Debug("Error in enabling client by api:", err1)
  1656. needRestart = true
  1657. }
  1658. s.xrayApi.Close()
  1659. break
  1660. }
  1661. }
  1662. }
  1663. traffic.Up = 0
  1664. traffic.Down = 0
  1665. traffic.Enable = true
  1666. db := database.GetDB()
  1667. err = db.Save(traffic).Error
  1668. if err != nil {
  1669. return false, err
  1670. }
  1671. return needRestart, nil
  1672. }
  1673. func (s *InboundService) ResetAllClientTraffics(id int) error {
  1674. db := database.GetDB()
  1675. now := time.Now().Unix() * 1000
  1676. return db.Transaction(func(tx *gorm.DB) error {
  1677. whereText := "inbound_id "
  1678. if id == -1 {
  1679. whereText += " > ?"
  1680. } else {
  1681. whereText += " = ?"
  1682. }
  1683. // Reset client traffics
  1684. result := tx.Model(xray.ClientTraffic{}).
  1685. Where(whereText, id).
  1686. Updates(map[string]any{"enable": true, "up": 0, "down": 0})
  1687. if result.Error != nil {
  1688. return result.Error
  1689. }
  1690. // Update lastTrafficResetTime for the inbound(s)
  1691. inboundWhereText := "id "
  1692. if id == -1 {
  1693. inboundWhereText += " > ?"
  1694. } else {
  1695. inboundWhereText += " = ?"
  1696. }
  1697. result = tx.Model(model.Inbound{}).
  1698. Where(inboundWhereText, id).
  1699. Update("last_traffic_reset_time", now)
  1700. return result.Error
  1701. })
  1702. }
  1703. func (s *InboundService) ResetAllTraffics() error {
  1704. db := database.GetDB()
  1705. result := db.Model(model.Inbound{}).
  1706. Where("user_id > ?", 0).
  1707. Updates(map[string]any{"up": 0, "down": 0})
  1708. err := result.Error
  1709. return err
  1710. }
  1711. func (s *InboundService) DelDepletedClients(id int) (err error) {
  1712. db := database.GetDB()
  1713. tx := db.Begin()
  1714. defer func() {
  1715. if err == nil {
  1716. tx.Commit()
  1717. } else {
  1718. tx.Rollback()
  1719. }
  1720. }()
  1721. whereText := "reset = 0 and inbound_id "
  1722. if id < 0 {
  1723. whereText += "> ?"
  1724. } else {
  1725. whereText += "= ?"
  1726. }
  1727. // Only consider truly depleted clients: expired OR traffic exhausted
  1728. now := time.Now().Unix() * 1000
  1729. depletedClients := []xray.ClientTraffic{}
  1730. err = db.Model(xray.ClientTraffic{}).
  1731. Where(whereText+" and ((total > 0 and up + down >= total) or (expiry_time > 0 and expiry_time <= ?))", id, now).
  1732. Select("inbound_id, GROUP_CONCAT(email) as email").
  1733. Group("inbound_id").
  1734. Find(&depletedClients).Error
  1735. if err != nil {
  1736. return err
  1737. }
  1738. for _, depletedClient := range depletedClients {
  1739. emails := strings.Split(depletedClient.Email, ",")
  1740. oldInbound, err := s.GetInbound(depletedClient.InboundId)
  1741. if err != nil {
  1742. return err
  1743. }
  1744. var oldSettings map[string]any
  1745. err = json.Unmarshal([]byte(oldInbound.Settings), &oldSettings)
  1746. if err != nil {
  1747. return err
  1748. }
  1749. oldClients := oldSettings["clients"].([]any)
  1750. var newClients []any
  1751. for _, client := range oldClients {
  1752. deplete := false
  1753. c := client.(map[string]any)
  1754. for _, email := range emails {
  1755. if email == c["email"].(string) {
  1756. deplete = true
  1757. break
  1758. }
  1759. }
  1760. if !deplete {
  1761. newClients = append(newClients, client)
  1762. }
  1763. }
  1764. if len(newClients) > 0 {
  1765. oldSettings["clients"] = newClients
  1766. newSettings, err := json.MarshalIndent(oldSettings, "", " ")
  1767. if err != nil {
  1768. return err
  1769. }
  1770. oldInbound.Settings = string(newSettings)
  1771. err = tx.Save(oldInbound).Error
  1772. if err != nil {
  1773. return err
  1774. }
  1775. } else {
  1776. // Delete inbound if no client remains
  1777. s.DelInbound(depletedClient.InboundId)
  1778. }
  1779. }
  1780. // Delete stats only for truly depleted clients
  1781. err = tx.Where(whereText+" and ((total > 0 and up + down >= total) or (expiry_time > 0 and expiry_time <= ?))", id, now).Delete(xray.ClientTraffic{}).Error
  1782. if err != nil {
  1783. return err
  1784. }
  1785. return nil
  1786. }
  1787. func (s *InboundService) GetClientTrafficTgBot(tgId int64) ([]*xray.ClientTraffic, error) {
  1788. db := database.GetDB()
  1789. var inbounds []*model.Inbound
  1790. // Retrieve inbounds where settings contain the given tgId
  1791. err := db.Model(model.Inbound{}).Where("settings LIKE ?", fmt.Sprintf(`%%"tgId": %d%%`, tgId)).Find(&inbounds).Error
  1792. if err != nil && err != gorm.ErrRecordNotFound {
  1793. logger.Errorf("Error retrieving inbounds with tgId %d: %v", tgId, err)
  1794. return nil, err
  1795. }
  1796. var emails []string
  1797. for _, inbound := range inbounds {
  1798. clients, err := s.GetClients(inbound)
  1799. if err != nil {
  1800. logger.Errorf("Error retrieving clients for inbound %d: %v", inbound.Id, err)
  1801. continue
  1802. }
  1803. for _, client := range clients {
  1804. if client.TgID == tgId {
  1805. emails = append(emails, client.Email)
  1806. }
  1807. }
  1808. }
  1809. var traffics []*xray.ClientTraffic
  1810. err = db.Model(xray.ClientTraffic{}).Where("email IN ?", emails).Find(&traffics).Error
  1811. if err != nil {
  1812. if err == gorm.ErrRecordNotFound {
  1813. logger.Warning("No ClientTraffic records found for emails:", emails)
  1814. return nil, nil
  1815. }
  1816. logger.Errorf("Error retrieving ClientTraffic for emails %v: %v", emails, err)
  1817. return nil, err
  1818. }
  1819. // Populate UUID and other client data for each traffic record
  1820. for i := range traffics {
  1821. if ct, client, e := s.GetClientByEmail(traffics[i].Email); e == nil && ct != nil && client != nil {
  1822. traffics[i].Enable = client.Enable
  1823. traffics[i].UUID = client.ID
  1824. traffics[i].SubId = client.SubID
  1825. }
  1826. }
  1827. return traffics, nil
  1828. }
  1829. func (s *InboundService) GetClientTrafficByEmail(email string) (traffic *xray.ClientTraffic, err error) {
  1830. // Prefer retrieving along with client to reflect actual enabled state from inbound settings
  1831. t, client, err := s.GetClientByEmail(email)
  1832. if err != nil {
  1833. logger.Warningf("Error retrieving ClientTraffic with email %s: %v", email, err)
  1834. return nil, err
  1835. }
  1836. if t != nil && client != nil {
  1837. t.Enable = client.Enable
  1838. t.UUID = client.ID
  1839. t.SubId = client.SubID
  1840. return t, nil
  1841. }
  1842. return nil, nil
  1843. }
  1844. func (s *InboundService) UpdateClientTrafficByEmail(email string, upload int64, download int64) error {
  1845. db := database.GetDB()
  1846. result := db.Model(xray.ClientTraffic{}).
  1847. Where("email = ?", email).
  1848. Updates(map[string]any{"up": upload, "down": download})
  1849. err := result.Error
  1850. if err != nil {
  1851. logger.Warningf("Error updating ClientTraffic with email %s: %v", email, err)
  1852. return err
  1853. }
  1854. return nil
  1855. }
  1856. func (s *InboundService) GetClientTrafficByID(id string) ([]xray.ClientTraffic, error) {
  1857. db := database.GetDB()
  1858. var traffics []xray.ClientTraffic
  1859. err := db.Model(xray.ClientTraffic{}).Where(`email IN(
  1860. SELECT JSON_EXTRACT(client.value, '$.email') as email
  1861. FROM inbounds,
  1862. JSON_EACH(JSON_EXTRACT(inbounds.settings, '$.clients')) AS client
  1863. WHERE
  1864. JSON_EXTRACT(client.value, '$.id') in (?)
  1865. )`, id).Find(&traffics).Error
  1866. if err != nil {
  1867. logger.Debug(err)
  1868. return nil, err
  1869. }
  1870. // Reconcile enable flag with client settings per email to avoid stale DB value
  1871. for i := range traffics {
  1872. if ct, client, e := s.GetClientByEmail(traffics[i].Email); e == nil && ct != nil && client != nil {
  1873. traffics[i].Enable = client.Enable
  1874. traffics[i].UUID = client.ID
  1875. traffics[i].SubId = client.SubID
  1876. }
  1877. }
  1878. return traffics, err
  1879. }
  1880. func (s *InboundService) SearchClientTraffic(query string) (traffic *xray.ClientTraffic, err error) {
  1881. db := database.GetDB()
  1882. inbound := &model.Inbound{}
  1883. traffic = &xray.ClientTraffic{}
  1884. // Search for inbound settings that contain the query
  1885. err = db.Model(model.Inbound{}).Where("settings LIKE ?", "%\""+query+"\"%").First(inbound).Error
  1886. if err != nil {
  1887. if err == gorm.ErrRecordNotFound {
  1888. logger.Warningf("Inbound settings containing query %s not found: %v", query, err)
  1889. return nil, err
  1890. }
  1891. logger.Errorf("Error searching for inbound settings with query %s: %v", query, err)
  1892. return nil, err
  1893. }
  1894. traffic.InboundId = inbound.Id
  1895. // Unmarshal settings to get clients
  1896. settings := map[string][]model.Client{}
  1897. if err := json.Unmarshal([]byte(inbound.Settings), &settings); err != nil {
  1898. logger.Errorf("Error unmarshalling inbound settings for inbound ID %d: %v", inbound.Id, err)
  1899. return nil, err
  1900. }
  1901. clients := settings["clients"]
  1902. for _, client := range clients {
  1903. if (client.ID == query || client.Password == query) && client.Email != "" {
  1904. traffic.Email = client.Email
  1905. break
  1906. }
  1907. }
  1908. if traffic.Email == "" {
  1909. logger.Warningf("No client found with query %s in inbound ID %d", query, inbound.Id)
  1910. return nil, gorm.ErrRecordNotFound
  1911. }
  1912. // Retrieve ClientTraffic based on the found email
  1913. err = db.Model(xray.ClientTraffic{}).Where("email = ?", traffic.Email).First(traffic).Error
  1914. if err != nil {
  1915. if err == gorm.ErrRecordNotFound {
  1916. logger.Warningf("ClientTraffic for email %s not found: %v", traffic.Email, err)
  1917. return nil, err
  1918. }
  1919. logger.Errorf("Error retrieving ClientTraffic for email %s: %v", traffic.Email, err)
  1920. return nil, err
  1921. }
  1922. return traffic, nil
  1923. }
  1924. func (s *InboundService) GetInboundClientIps(clientEmail string) (string, error) {
  1925. db := database.GetDB()
  1926. InboundClientIps := &model.InboundClientIps{}
  1927. err := db.Model(model.InboundClientIps{}).Where("client_email = ?", clientEmail).First(InboundClientIps).Error
  1928. if err != nil {
  1929. return "", err
  1930. }
  1931. return InboundClientIps.Ips, nil
  1932. }
  1933. func (s *InboundService) ClearClientIps(clientEmail string) error {
  1934. db := database.GetDB()
  1935. result := db.Model(model.InboundClientIps{}).
  1936. Where("client_email = ?", clientEmail).
  1937. Update("ips", "")
  1938. err := result.Error
  1939. if err != nil {
  1940. return err
  1941. }
  1942. return nil
  1943. }
  1944. func (s *InboundService) SearchInbounds(query string) ([]*model.Inbound, error) {
  1945. db := database.GetDB()
  1946. var inbounds []*model.Inbound
  1947. err := db.Model(model.Inbound{}).Preload("ClientStats").Where("remark like ?", "%"+query+"%").Find(&inbounds).Error
  1948. if err != nil && err != gorm.ErrRecordNotFound {
  1949. return nil, err
  1950. }
  1951. return inbounds, nil
  1952. }
  1953. func (s *InboundService) MigrationRequirements() {
  1954. db := database.GetDB()
  1955. tx := db.Begin()
  1956. var err error
  1957. defer func() {
  1958. if err == nil {
  1959. tx.Commit()
  1960. if dbErr := db.Exec(`VACUUM "main"`).Error; dbErr != nil {
  1961. logger.Warningf("VACUUM failed: %v", dbErr)
  1962. }
  1963. } else {
  1964. tx.Rollback()
  1965. }
  1966. }()
  1967. // Calculate and backfill all_time from up+down for inbounds and clients
  1968. err = tx.Exec(`
  1969. UPDATE inbounds
  1970. SET all_time = IFNULL(up, 0) + IFNULL(down, 0)
  1971. WHERE IFNULL(all_time, 0) = 0 AND (IFNULL(up, 0) + IFNULL(down, 0)) > 0
  1972. `).Error
  1973. if err != nil {
  1974. return
  1975. }
  1976. err = tx.Exec(`
  1977. UPDATE client_traffics
  1978. SET all_time = IFNULL(up, 0) + IFNULL(down, 0)
  1979. WHERE IFNULL(all_time, 0) = 0 AND (IFNULL(up, 0) + IFNULL(down, 0)) > 0
  1980. `).Error
  1981. if err != nil {
  1982. return
  1983. }
  1984. // Fix inbounds based problems
  1985. var inbounds []*model.Inbound
  1986. err = tx.Model(model.Inbound{}).Where("protocol IN (?)", []string{"vmess", "vless", "trojan"}).Find(&inbounds).Error
  1987. if err != nil && err != gorm.ErrRecordNotFound {
  1988. return
  1989. }
  1990. for inbound_index := range inbounds {
  1991. settings := map[string]any{}
  1992. json.Unmarshal([]byte(inbounds[inbound_index].Settings), &settings)
  1993. clients, ok := settings["clients"].([]any)
  1994. if ok {
  1995. // Fix Client configuration problems
  1996. var newClients []any
  1997. for client_index := range clients {
  1998. c := clients[client_index].(map[string]any)
  1999. // Add email='' if it is not exists
  2000. if _, ok := c["email"]; !ok {
  2001. c["email"] = ""
  2002. }
  2003. // Convert string tgId to int64
  2004. if _, ok := c["tgId"]; ok {
  2005. var tgId any = c["tgId"]
  2006. if tgIdStr, ok2 := tgId.(string); ok2 {
  2007. tgIdInt64, err := strconv.ParseInt(strings.ReplaceAll(tgIdStr, " ", ""), 10, 64)
  2008. if err == nil {
  2009. c["tgId"] = tgIdInt64
  2010. }
  2011. }
  2012. }
  2013. // Remove "flow": "xtls-rprx-direct"
  2014. if _, ok := c["flow"]; ok {
  2015. if c["flow"] == "xtls-rprx-direct" {
  2016. c["flow"] = ""
  2017. }
  2018. }
  2019. // Backfill created_at and updated_at
  2020. if _, ok := c["created_at"]; !ok {
  2021. c["created_at"] = time.Now().Unix() * 1000
  2022. }
  2023. c["updated_at"] = time.Now().Unix() * 1000
  2024. newClients = append(newClients, any(c))
  2025. }
  2026. settings["clients"] = newClients
  2027. modifiedSettings, err := json.MarshalIndent(settings, "", " ")
  2028. if err != nil {
  2029. return
  2030. }
  2031. inbounds[inbound_index].Settings = string(modifiedSettings)
  2032. }
  2033. // Add client traffic row for all clients which has email
  2034. modelClients, err := s.GetClients(inbounds[inbound_index])
  2035. if err != nil {
  2036. return
  2037. }
  2038. for _, modelClient := range modelClients {
  2039. if len(modelClient.Email) > 0 {
  2040. var count int64
  2041. tx.Model(xray.ClientTraffic{}).Where("email = ?", modelClient.Email).Count(&count)
  2042. if count == 0 {
  2043. s.AddClientStat(tx, inbounds[inbound_index].Id, &modelClient)
  2044. }
  2045. }
  2046. }
  2047. }
  2048. tx.Save(inbounds)
  2049. // Remove orphaned traffics
  2050. tx.Where("inbound_id = 0").Delete(xray.ClientTraffic{})
  2051. // Migrate old MultiDomain to External Proxy
  2052. var externalProxy []struct {
  2053. Id int
  2054. Port int
  2055. StreamSettings []byte
  2056. }
  2057. err = tx.Raw(`select id, port, stream_settings
  2058. from inbounds
  2059. WHERE protocol in ('vmess','vless','trojan')
  2060. AND json_extract(stream_settings, '$.security') = 'tls'
  2061. AND json_extract(stream_settings, '$.tlsSettings.settings.domains') IS NOT NULL`).Scan(&externalProxy).Error
  2062. if err != nil || len(externalProxy) == 0 {
  2063. return
  2064. }
  2065. for _, ep := range externalProxy {
  2066. var reverses any
  2067. var stream map[string]any
  2068. json.Unmarshal(ep.StreamSettings, &stream)
  2069. if tlsSettings, ok := stream["tlsSettings"].(map[string]any); ok {
  2070. if settings, ok := tlsSettings["settings"].(map[string]any); ok {
  2071. if domains, ok := settings["domains"].([]any); ok {
  2072. for _, domain := range domains {
  2073. if domainMap, ok := domain.(map[string]any); ok {
  2074. domainMap["forceTls"] = "same"
  2075. domainMap["port"] = ep.Port
  2076. domainMap["dest"] = domainMap["domain"].(string)
  2077. delete(domainMap, "domain")
  2078. }
  2079. }
  2080. }
  2081. reverses = settings["domains"]
  2082. delete(settings, "domains")
  2083. }
  2084. }
  2085. stream["externalProxy"] = reverses
  2086. newStream, _ := json.MarshalIndent(stream, " ", " ")
  2087. tx.Model(model.Inbound{}).Where("id = ?", ep.Id).Update("stream_settings", newStream)
  2088. }
  2089. err = tx.Raw(`UPDATE inbounds
  2090. SET tag = REPLACE(tag, '0.0.0.0:', '')
  2091. WHERE INSTR(tag, '0.0.0.0:') > 0;`).Error
  2092. if err != nil {
  2093. return
  2094. }
  2095. }
  2096. func (s *InboundService) MigrateDB() {
  2097. s.MigrationRequirements()
  2098. s.MigrationRemoveOrphanedTraffics()
  2099. }
  2100. func (s *InboundService) GetOnlineClients() []string {
  2101. return p.GetOnlineClients()
  2102. }
  2103. func (s *InboundService) GetClientsLastOnline() (map[string]int64, error) {
  2104. db := database.GetDB()
  2105. var rows []xray.ClientTraffic
  2106. err := db.Model(&xray.ClientTraffic{}).Select("email, last_online").Find(&rows).Error
  2107. if err != nil && err != gorm.ErrRecordNotFound {
  2108. return nil, err
  2109. }
  2110. result := make(map[string]int64, len(rows))
  2111. for _, r := range rows {
  2112. result[r.Email] = r.LastOnline
  2113. }
  2114. return result, nil
  2115. }
  2116. func (s *InboundService) FilterAndSortClientEmails(emails []string) ([]string, []string, error) {
  2117. db := database.GetDB()
  2118. // Step 1: Get ClientTraffic records for emails in the input list
  2119. var clients []xray.ClientTraffic
  2120. err := db.Where("email IN ?", emails).Find(&clients).Error
  2121. if err != nil && err != gorm.ErrRecordNotFound {
  2122. return nil, nil, err
  2123. }
  2124. // Step 2: Sort clients by (Up + Down) descending
  2125. sort.Slice(clients, func(i, j int) bool {
  2126. return (clients[i].Up + clients[i].Down) > (clients[j].Up + clients[j].Down)
  2127. })
  2128. // Step 3: Extract sorted valid emails and track found ones
  2129. validEmails := make([]string, 0, len(clients))
  2130. found := make(map[string]bool)
  2131. for _, client := range clients {
  2132. validEmails = append(validEmails, client.Email)
  2133. found[client.Email] = true
  2134. }
  2135. // Step 4: Identify emails that were not found in the database
  2136. extraEmails := make([]string, 0)
  2137. for _, email := range emails {
  2138. if !found[email] {
  2139. extraEmails = append(extraEmails, email)
  2140. }
  2141. }
  2142. return validEmails, extraEmails, nil
  2143. }
  2144. func (s *InboundService) DelInboundClientByEmail(inboundId int, email string) (bool, error) {
  2145. oldInbound, err := s.GetInbound(inboundId)
  2146. if err != nil {
  2147. logger.Error("Load Old Data Error")
  2148. return false, err
  2149. }
  2150. var settings map[string]any
  2151. if err := json.Unmarshal([]byte(oldInbound.Settings), &settings); err != nil {
  2152. return false, err
  2153. }
  2154. interfaceClients, ok := settings["clients"].([]any)
  2155. if !ok {
  2156. return false, common.NewError("invalid clients format in inbound settings")
  2157. }
  2158. var newClients []any
  2159. needApiDel := false
  2160. found := false
  2161. for _, client := range interfaceClients {
  2162. c, ok := client.(map[string]any)
  2163. if !ok {
  2164. continue
  2165. }
  2166. if cEmail, ok := c["email"].(string); ok && cEmail == email {
  2167. // matched client, drop it
  2168. found = true
  2169. needApiDel, _ = c["enable"].(bool)
  2170. } else {
  2171. newClients = append(newClients, client)
  2172. }
  2173. }
  2174. if !found {
  2175. return false, common.NewError(fmt.Sprintf("client with email %s not found", email))
  2176. }
  2177. if len(newClients) == 0 {
  2178. return false, common.NewError("no client remained in Inbound")
  2179. }
  2180. settings["clients"] = newClients
  2181. newSettings, err := json.MarshalIndent(settings, "", " ")
  2182. if err != nil {
  2183. return false, err
  2184. }
  2185. oldInbound.Settings = string(newSettings)
  2186. db := database.GetDB()
  2187. // remove IP bindings
  2188. if err := s.DelClientIPs(db, email); err != nil {
  2189. logger.Error("Error in delete client IPs")
  2190. return false, err
  2191. }
  2192. needRestart := false
  2193. // remove stats too
  2194. if len(email) > 0 {
  2195. traffic, err := s.GetClientTrafficByEmail(email)
  2196. if err != nil {
  2197. return false, err
  2198. }
  2199. if traffic != nil {
  2200. if err := s.DelClientStat(db, email); err != nil {
  2201. logger.Error("Delete stats Data Error")
  2202. return false, err
  2203. }
  2204. }
  2205. if needApiDel {
  2206. s.xrayApi.Init(p.GetAPIPort())
  2207. if err1 := s.xrayApi.RemoveUser(oldInbound.Tag, email); err1 == nil {
  2208. logger.Debug("Client deleted by api:", email)
  2209. needRestart = false
  2210. } else {
  2211. if strings.Contains(err1.Error(), fmt.Sprintf("User %s not found.", email)) {
  2212. logger.Debug("User is already deleted. Nothing to do more...")
  2213. } else {
  2214. logger.Debug("Error in deleting client by api:", err1)
  2215. needRestart = true
  2216. }
  2217. }
  2218. s.xrayApi.Close()
  2219. }
  2220. }
  2221. return needRestart, db.Save(oldInbound).Error
  2222. }