1
0

inbound.go 51 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996
  1. package service
  2. import (
  3. "encoding/json"
  4. "fmt"
  5. "strconv"
  6. "strings"
  7. "time"
  8. "x-ui/database"
  9. "x-ui/database/model"
  10. "x-ui/logger"
  11. "x-ui/util/common"
  12. "x-ui/xray"
  13. "gorm.io/gorm"
  14. )
  15. type InboundService struct {
  16. xrayApi xray.XrayAPI
  17. }
  18. func (s *InboundService) GetInbounds(userId int) ([]*model.Inbound, error) {
  19. db := database.GetDB()
  20. var inbounds []*model.Inbound
  21. err := db.Model(model.Inbound{}).Preload("ClientStats").Where("user_id = ?", userId).Find(&inbounds).Error
  22. if err != nil && err != gorm.ErrRecordNotFound {
  23. return nil, err
  24. }
  25. return inbounds, nil
  26. }
  27. func (s *InboundService) GetAllInbounds() ([]*model.Inbound, error) {
  28. db := database.GetDB()
  29. var inbounds []*model.Inbound
  30. err := db.Model(model.Inbound{}).Preload("ClientStats").Find(&inbounds).Error
  31. if err != nil && err != gorm.ErrRecordNotFound {
  32. return nil, err
  33. }
  34. return inbounds, nil
  35. }
  36. func (s *InboundService) checkPortExist(listen string, port int, ignoreId int) (bool, error) {
  37. db := database.GetDB()
  38. if listen == "" || listen == "0.0.0.0" || listen == "::" || listen == "::0" {
  39. db = db.Model(model.Inbound{}).Where("port = ?", port)
  40. } else {
  41. db = db.Model(model.Inbound{}).
  42. Where("port = ?", port).
  43. Where(
  44. db.Model(model.Inbound{}).Where(
  45. "listen = ?", listen,
  46. ).Or(
  47. "listen = \"\"",
  48. ).Or(
  49. "listen = \"0.0.0.0\"",
  50. ).Or(
  51. "listen = \"::\"",
  52. ).Or(
  53. "listen = \"::0\""))
  54. }
  55. if ignoreId > 0 {
  56. db = db.Where("id != ?", ignoreId)
  57. }
  58. var count int64
  59. err := db.Count(&count).Error
  60. if err != nil {
  61. return false, err
  62. }
  63. return count > 0, nil
  64. }
  65. func (s *InboundService) GetClients(inbound *model.Inbound) ([]model.Client, error) {
  66. settings := map[string][]model.Client{}
  67. json.Unmarshal([]byte(inbound.Settings), &settings)
  68. if settings == nil {
  69. return nil, fmt.Errorf("setting is null")
  70. }
  71. clients := settings["clients"]
  72. if clients == nil {
  73. return nil, nil
  74. }
  75. return clients, nil
  76. }
  77. func (s *InboundService) getAllEmails() ([]string, error) {
  78. db := database.GetDB()
  79. var emails []string
  80. err := db.Raw(`
  81. SELECT JSON_EXTRACT(client.value, '$.email')
  82. FROM inbounds,
  83. JSON_EACH(JSON_EXTRACT(inbounds.settings, '$.clients')) AS client
  84. `).Scan(&emails).Error
  85. if err != nil {
  86. return nil, err
  87. }
  88. return emails, nil
  89. }
  90. func (s *InboundService) contains(slice []string, str string) bool {
  91. for _, s := range slice {
  92. if s == str {
  93. return true
  94. }
  95. }
  96. return false
  97. }
  98. func (s *InboundService) checkEmailsExistForClients(clients []model.Client) (string, error) {
  99. allEmails, err := s.getAllEmails()
  100. if err != nil {
  101. return "", err
  102. }
  103. var emails []string
  104. for _, client := range clients {
  105. if client.Email != "" {
  106. if s.contains(emails, client.Email) {
  107. return client.Email, nil
  108. }
  109. if s.contains(allEmails, client.Email) {
  110. return client.Email, nil
  111. }
  112. emails = append(emails, client.Email)
  113. }
  114. }
  115. return "", nil
  116. }
  117. func (s *InboundService) checkEmailExistForInbound(inbound *model.Inbound) (string, error) {
  118. clients, err := s.GetClients(inbound)
  119. if err != nil {
  120. return "", err
  121. }
  122. allEmails, err := s.getAllEmails()
  123. if err != nil {
  124. return "", err
  125. }
  126. var emails []string
  127. for _, client := range clients {
  128. if client.Email != "" {
  129. if s.contains(emails, client.Email) {
  130. return client.Email, nil
  131. }
  132. if s.contains(allEmails, client.Email) {
  133. return client.Email, nil
  134. }
  135. emails = append(emails, client.Email)
  136. }
  137. }
  138. return "", nil
  139. }
  140. func (s *InboundService) AddInbound(inbound *model.Inbound) (*model.Inbound, bool, error) {
  141. exist, err := s.checkPortExist(inbound.Listen, inbound.Port, 0)
  142. if err != nil {
  143. return inbound, false, err
  144. }
  145. if exist {
  146. return inbound, false, common.NewError("Port already exists:", inbound.Port)
  147. }
  148. existEmail, err := s.checkEmailExistForInbound(inbound)
  149. if err != nil {
  150. return inbound, false, err
  151. }
  152. if existEmail != "" {
  153. return inbound, false, common.NewError("Duplicate email:", existEmail)
  154. }
  155. clients, err := s.GetClients(inbound)
  156. if err != nil {
  157. return inbound, false, err
  158. }
  159. // Secure client ID
  160. for _, client := range clients {
  161. if inbound.Protocol == "trojan" {
  162. if client.Password == "" {
  163. return inbound, false, common.NewError("empty client ID")
  164. }
  165. } else if inbound.Protocol == "shadowsocks" {
  166. if client.Email == "" {
  167. return inbound, false, common.NewError("empty client ID")
  168. }
  169. } else {
  170. if client.ID == "" {
  171. return inbound, false, common.NewError("empty client ID")
  172. }
  173. }
  174. }
  175. db := database.GetDB()
  176. tx := db.Begin()
  177. defer func() {
  178. if err == nil {
  179. tx.Commit()
  180. } else {
  181. tx.Rollback()
  182. }
  183. }()
  184. err = tx.Save(inbound).Error
  185. if err == nil {
  186. if len(inbound.ClientStats) == 0 {
  187. for _, client := range clients {
  188. s.AddClientStat(tx, inbound.Id, &client)
  189. }
  190. }
  191. } else {
  192. return inbound, false, err
  193. }
  194. needRestart := false
  195. if inbound.Enable {
  196. s.xrayApi.Init(p.GetAPIPort())
  197. inboundJson, err1 := json.MarshalIndent(inbound.GenXrayInboundConfig(), "", " ")
  198. if err1 != nil {
  199. logger.Debug("Unable to marshal inbound config:", err1)
  200. }
  201. err1 = s.xrayApi.AddInbound(inboundJson)
  202. if err1 == nil {
  203. logger.Debug("New inbound added by api:", inbound.Tag)
  204. } else {
  205. logger.Debug("Unable to add inbound by api:", err1)
  206. needRestart = true
  207. }
  208. s.xrayApi.Close()
  209. }
  210. return inbound, needRestart, err
  211. }
  212. func (s *InboundService) DelInbound(id int) (bool, error) {
  213. db := database.GetDB()
  214. var tag string
  215. needRestart := false
  216. result := db.Model(model.Inbound{}).Select("tag").Where("id = ? and enable = ?", id, true).First(&tag)
  217. if result.Error == nil {
  218. s.xrayApi.Init(p.GetAPIPort())
  219. err1 := s.xrayApi.DelInbound(tag)
  220. if err1 == nil {
  221. logger.Debug("Inbound deleted by api:", tag)
  222. } else {
  223. logger.Debug("Unable to delete inbound by api:", err1)
  224. needRestart = true
  225. }
  226. s.xrayApi.Close()
  227. } else {
  228. logger.Debug("No enabled inbound founded to removing by api", tag)
  229. }
  230. // Delete client traffics of inbounds
  231. err := db.Where("inbound_id = ?", id).Delete(xray.ClientTraffic{}).Error
  232. if err != nil {
  233. return false, err
  234. }
  235. inbound, err := s.GetInbound(id)
  236. if err != nil {
  237. return false, err
  238. }
  239. clients, err := s.GetClients(inbound)
  240. if err != nil {
  241. return false, err
  242. }
  243. for _, client := range clients {
  244. err := s.DelClientIPs(db, client.Email)
  245. if err != nil {
  246. return false, err
  247. }
  248. }
  249. return needRestart, db.Delete(model.Inbound{}, id).Error
  250. }
  251. func (s *InboundService) GetInbound(id int) (*model.Inbound, error) {
  252. db := database.GetDB()
  253. inbound := &model.Inbound{}
  254. err := db.Model(model.Inbound{}).First(inbound, id).Error
  255. if err != nil {
  256. return nil, err
  257. }
  258. return inbound, nil
  259. }
  260. func (s *InboundService) UpdateInbound(inbound *model.Inbound) (*model.Inbound, bool, error) {
  261. exist, err := s.checkPortExist(inbound.Listen, inbound.Port, inbound.Id)
  262. if err != nil {
  263. return inbound, false, err
  264. }
  265. if exist {
  266. return inbound, false, common.NewError("Port already exists:", inbound.Port)
  267. }
  268. oldInbound, err := s.GetInbound(inbound.Id)
  269. if err != nil {
  270. return inbound, false, err
  271. }
  272. tag := oldInbound.Tag
  273. db := database.GetDB()
  274. tx := db.Begin()
  275. defer func() {
  276. if err != nil {
  277. tx.Rollback()
  278. } else {
  279. tx.Commit()
  280. }
  281. }()
  282. err = s.updateClientTraffics(tx, oldInbound, inbound)
  283. if err != nil {
  284. return inbound, false, err
  285. }
  286. oldInbound.Up = inbound.Up
  287. oldInbound.Down = inbound.Down
  288. oldInbound.Total = inbound.Total
  289. oldInbound.Remark = inbound.Remark
  290. oldInbound.Enable = inbound.Enable
  291. oldInbound.ExpiryTime = inbound.ExpiryTime
  292. oldInbound.Listen = inbound.Listen
  293. oldInbound.Port = inbound.Port
  294. oldInbound.Protocol = inbound.Protocol
  295. oldInbound.Settings = inbound.Settings
  296. oldInbound.StreamSettings = inbound.StreamSettings
  297. oldInbound.Sniffing = inbound.Sniffing
  298. if inbound.Listen == "" || inbound.Listen == "0.0.0.0" || inbound.Listen == "::" || inbound.Listen == "::0" {
  299. oldInbound.Tag = fmt.Sprintf("inbound-%v", inbound.Port)
  300. } else {
  301. oldInbound.Tag = fmt.Sprintf("inbound-%v:%v", inbound.Listen, inbound.Port)
  302. }
  303. needRestart := false
  304. s.xrayApi.Init(p.GetAPIPort())
  305. if s.xrayApi.DelInbound(tag) == nil {
  306. logger.Debug("Old inbound deleted by api:", tag)
  307. }
  308. if inbound.Enable {
  309. inboundJson, err2 := json.MarshalIndent(oldInbound.GenXrayInboundConfig(), "", " ")
  310. if err2 != nil {
  311. logger.Debug("Unable to marshal updated inbound config:", err2)
  312. needRestart = true
  313. } else {
  314. err2 = s.xrayApi.AddInbound(inboundJson)
  315. if err2 == nil {
  316. logger.Debug("Updated inbound added by api:", oldInbound.Tag)
  317. } else {
  318. logger.Debug("Unable to update inbound by api:", err2)
  319. needRestart = true
  320. }
  321. }
  322. }
  323. s.xrayApi.Close()
  324. return inbound, needRestart, tx.Save(oldInbound).Error
  325. }
  326. func (s *InboundService) updateClientTraffics(tx *gorm.DB, oldInbound *model.Inbound, newInbound *model.Inbound) error {
  327. oldClients, err := s.GetClients(oldInbound)
  328. if err != nil {
  329. return err
  330. }
  331. newClients, err := s.GetClients(newInbound)
  332. if err != nil {
  333. return err
  334. }
  335. var emailExists bool
  336. for _, oldClient := range oldClients {
  337. emailExists = false
  338. for _, newClient := range newClients {
  339. if oldClient.Email == newClient.Email {
  340. emailExists = true
  341. break
  342. }
  343. }
  344. if !emailExists {
  345. err = s.DelClientStat(tx, oldClient.Email)
  346. if err != nil {
  347. return err
  348. }
  349. }
  350. }
  351. for _, newClient := range newClients {
  352. emailExists = false
  353. for _, oldClient := range oldClients {
  354. if newClient.Email == oldClient.Email {
  355. emailExists = true
  356. break
  357. }
  358. }
  359. if !emailExists {
  360. err = s.AddClientStat(tx, oldInbound.Id, &newClient)
  361. if err != nil {
  362. return err
  363. }
  364. }
  365. }
  366. return nil
  367. }
  368. func (s *InboundService) AddInboundClient(data *model.Inbound) (bool, error) {
  369. clients, err := s.GetClients(data)
  370. if err != nil {
  371. return false, err
  372. }
  373. var settings map[string]interface{}
  374. err = json.Unmarshal([]byte(data.Settings), &settings)
  375. if err != nil {
  376. return false, err
  377. }
  378. interfaceClients := settings["clients"].([]interface{})
  379. existEmail, err := s.checkEmailsExistForClients(clients)
  380. if err != nil {
  381. return false, err
  382. }
  383. if existEmail != "" {
  384. return false, common.NewError("Duplicate email:", existEmail)
  385. }
  386. oldInbound, err := s.GetInbound(data.Id)
  387. if err != nil {
  388. return false, err
  389. }
  390. // Secure client ID
  391. for _, client := range clients {
  392. if oldInbound.Protocol == "trojan" {
  393. if client.Password == "" {
  394. return false, common.NewError("empty client ID")
  395. }
  396. } else if oldInbound.Protocol == "shadowsocks" {
  397. if client.Email == "" {
  398. return false, common.NewError("empty client ID")
  399. }
  400. } else {
  401. if client.ID == "" {
  402. return false, common.NewError("empty client ID")
  403. }
  404. }
  405. }
  406. var oldSettings map[string]interface{}
  407. err = json.Unmarshal([]byte(oldInbound.Settings), &oldSettings)
  408. if err != nil {
  409. return false, err
  410. }
  411. oldClients := oldSettings["clients"].([]interface{})
  412. oldClients = append(oldClients, interfaceClients...)
  413. oldSettings["clients"] = oldClients
  414. newSettings, err := json.MarshalIndent(oldSettings, "", " ")
  415. if err != nil {
  416. return false, err
  417. }
  418. oldInbound.Settings = string(newSettings)
  419. db := database.GetDB()
  420. tx := db.Begin()
  421. defer func() {
  422. if err != nil {
  423. tx.Rollback()
  424. } else {
  425. tx.Commit()
  426. }
  427. }()
  428. needRestart := false
  429. s.xrayApi.Init(p.GetAPIPort())
  430. for _, client := range clients {
  431. if len(client.Email) > 0 {
  432. s.AddClientStat(tx, data.Id, &client)
  433. if client.Enable {
  434. cipher := ""
  435. if oldInbound.Protocol == "shadowsocks" {
  436. cipher = oldSettings["method"].(string)
  437. }
  438. err1 := s.xrayApi.AddUser(string(oldInbound.Protocol), oldInbound.Tag, map[string]interface{}{
  439. "email": client.Email,
  440. "id": client.ID,
  441. "security": client.Security,
  442. "flow": client.Flow,
  443. "password": client.Password,
  444. "cipher": cipher,
  445. })
  446. if err1 == nil {
  447. logger.Debug("Client added by api:", client.Email)
  448. } else {
  449. logger.Debug("Error in adding client by api:", err1)
  450. needRestart = true
  451. }
  452. }
  453. } else {
  454. needRestart = true
  455. }
  456. }
  457. s.xrayApi.Close()
  458. return needRestart, tx.Save(oldInbound).Error
  459. }
  460. func (s *InboundService) DelInboundClient(inboundId int, clientId string) (bool, error) {
  461. oldInbound, err := s.GetInbound(inboundId)
  462. if err != nil {
  463. logger.Error("Load Old Data Error")
  464. return false, err
  465. }
  466. var settings map[string]interface{}
  467. err = json.Unmarshal([]byte(oldInbound.Settings), &settings)
  468. if err != nil {
  469. return false, err
  470. }
  471. email := ""
  472. client_key := "id"
  473. if oldInbound.Protocol == "trojan" {
  474. client_key = "password"
  475. }
  476. if oldInbound.Protocol == "shadowsocks" {
  477. client_key = "email"
  478. }
  479. interfaceClients := settings["clients"].([]interface{})
  480. var newClients []interface{}
  481. for _, client := range interfaceClients {
  482. c := client.(map[string]interface{})
  483. c_id := c[client_key].(string)
  484. if c_id == clientId {
  485. email = c["email"].(string)
  486. } else {
  487. newClients = append(newClients, client)
  488. }
  489. }
  490. if len(newClients) == 0 {
  491. return false, common.NewError("no client remained in Inbound")
  492. }
  493. settings["clients"] = newClients
  494. newSettings, err := json.MarshalIndent(settings, "", " ")
  495. if err != nil {
  496. return false, err
  497. }
  498. oldInbound.Settings = string(newSettings)
  499. db := database.GetDB()
  500. err = s.DelClientStat(db, email)
  501. if err != nil {
  502. logger.Error("Delete stats Data Error")
  503. return false, err
  504. }
  505. err = s.DelClientIPs(db, email)
  506. if err != nil {
  507. logger.Error("Error in delete client IPs")
  508. return false, err
  509. }
  510. needRestart := false
  511. if len(email) > 0 {
  512. s.xrayApi.Init(p.GetAPIPort())
  513. err1 := s.xrayApi.RemoveUser(oldInbound.Tag, email)
  514. if err1 == nil {
  515. logger.Debug("Client deleted by api:", email)
  516. needRestart = false
  517. } else {
  518. logger.Debug("Unable to del client by api:", err1)
  519. needRestart = true
  520. }
  521. s.xrayApi.Close()
  522. }
  523. return needRestart, db.Save(oldInbound).Error
  524. }
  525. func (s *InboundService) UpdateInboundClient(data *model.Inbound, clientId string) (bool, error) {
  526. clients, err := s.GetClients(data)
  527. if err != nil {
  528. return false, err
  529. }
  530. var settings map[string]interface{}
  531. err = json.Unmarshal([]byte(data.Settings), &settings)
  532. if err != nil {
  533. return false, err
  534. }
  535. interfaceClients := settings["clients"].([]interface{})
  536. oldInbound, err := s.GetInbound(data.Id)
  537. if err != nil {
  538. return false, err
  539. }
  540. oldClients, err := s.GetClients(oldInbound)
  541. if err != nil {
  542. return false, err
  543. }
  544. oldEmail := ""
  545. newClientId := ""
  546. clientIndex := -1
  547. for index, oldClient := range oldClients {
  548. oldClientId := ""
  549. if oldInbound.Protocol == "trojan" {
  550. oldClientId = oldClient.Password
  551. newClientId = clients[0].Password
  552. } else if oldInbound.Protocol == "shadowsocks" {
  553. oldClientId = oldClient.Email
  554. newClientId = clients[0].Email
  555. } else {
  556. oldClientId = oldClient.ID
  557. newClientId = clients[0].ID
  558. }
  559. if clientId == oldClientId {
  560. oldEmail = oldClient.Email
  561. clientIndex = index
  562. break
  563. }
  564. }
  565. // Validate new client ID
  566. if newClientId == "" || clientIndex == -1 {
  567. return false, common.NewError("empty client ID")
  568. }
  569. if len(clients[0].Email) > 0 && clients[0].Email != oldEmail {
  570. existEmail, err := s.checkEmailsExistForClients(clients)
  571. if err != nil {
  572. return false, err
  573. }
  574. if existEmail != "" {
  575. return false, common.NewError("Duplicate email:", existEmail)
  576. }
  577. }
  578. var oldSettings map[string]interface{}
  579. err = json.Unmarshal([]byte(oldInbound.Settings), &oldSettings)
  580. if err != nil {
  581. return false, err
  582. }
  583. settingsClients := oldSettings["clients"].([]interface{})
  584. settingsClients[clientIndex] = interfaceClients[0]
  585. oldSettings["clients"] = settingsClients
  586. newSettings, err := json.MarshalIndent(oldSettings, "", " ")
  587. if err != nil {
  588. return false, err
  589. }
  590. oldInbound.Settings = string(newSettings)
  591. db := database.GetDB()
  592. tx := db.Begin()
  593. defer func() {
  594. if err != nil {
  595. tx.Rollback()
  596. } else {
  597. tx.Commit()
  598. }
  599. }()
  600. if len(clients[0].Email) > 0 {
  601. if len(oldEmail) > 0 {
  602. err = s.UpdateClientStat(tx, oldEmail, &clients[0])
  603. if err != nil {
  604. return false, err
  605. }
  606. err = s.UpdateClientIPs(tx, oldEmail, clients[0].Email)
  607. if err != nil {
  608. return false, err
  609. }
  610. } else {
  611. s.AddClientStat(tx, data.Id, &clients[0])
  612. }
  613. } else {
  614. err = s.DelClientStat(tx, oldEmail)
  615. if err != nil {
  616. return false, err
  617. }
  618. err = s.DelClientIPs(tx, oldEmail)
  619. if err != nil {
  620. return false, err
  621. }
  622. }
  623. needRestart := false
  624. if len(oldEmail) > 0 {
  625. s.xrayApi.Init(p.GetAPIPort())
  626. err1 := s.xrayApi.RemoveUser(oldInbound.Tag, oldEmail)
  627. if err1 == nil {
  628. logger.Debug("Old client deleted by api:", clients[0].Email)
  629. } else {
  630. logger.Debug("Error in deleting client by api:", err1)
  631. needRestart = true
  632. }
  633. if clients[0].Enable {
  634. cipher := ""
  635. if oldInbound.Protocol == "shadowsocks" {
  636. cipher = oldSettings["method"].(string)
  637. }
  638. err1 := s.xrayApi.AddUser(string(oldInbound.Protocol), oldInbound.Tag, map[string]interface{}{
  639. "email": clients[0].Email,
  640. "id": clients[0].ID,
  641. "security": clients[0].Security,
  642. "flow": clients[0].Flow,
  643. "password": clients[0].Password,
  644. "cipher": cipher,
  645. })
  646. if err1 == nil {
  647. logger.Debug("Client edited by api:", clients[0].Email)
  648. } else {
  649. logger.Debug("Error in adding client by api:", err1)
  650. needRestart = true
  651. }
  652. }
  653. s.xrayApi.Close()
  654. } else {
  655. logger.Debug("Client old email not found")
  656. needRestart = true
  657. }
  658. return needRestart, tx.Save(oldInbound).Error
  659. }
  660. func (s *InboundService) AddTraffic(inboundTraffics []*xray.Traffic, clientTraffics []*xray.ClientTraffic) (error, bool) {
  661. var err error
  662. db := database.GetDB()
  663. tx := db.Begin()
  664. defer func() {
  665. if err != nil {
  666. tx.Rollback()
  667. } else {
  668. tx.Commit()
  669. }
  670. }()
  671. err = s.addInboundTraffic(tx, inboundTraffics)
  672. if err != nil {
  673. return err, false
  674. }
  675. err = s.addClientTraffic(tx, clientTraffics)
  676. if err != nil {
  677. return err, false
  678. }
  679. needRestart0, count, err := s.autoRenewClients(tx)
  680. if err != nil {
  681. logger.Warning("Error in renew clients:", err)
  682. } else if count > 0 {
  683. logger.Debugf("%v clients renewed", count)
  684. }
  685. needRestart1, count, err := s.disableInvalidClients(tx)
  686. if err != nil {
  687. logger.Warning("Error in disabling invalid clients:", err)
  688. } else if count > 0 {
  689. logger.Debugf("%v clients disabled", count)
  690. }
  691. needRestart2, count, err := s.disableInvalidInbounds(tx)
  692. if err != nil {
  693. logger.Warning("Error in disabling invalid inbounds:", err)
  694. } else if count > 0 {
  695. logger.Debugf("%v inbounds disabled", count)
  696. }
  697. return nil, (needRestart0 || needRestart1 || needRestart2)
  698. }
  699. func (s *InboundService) addInboundTraffic(tx *gorm.DB, traffics []*xray.Traffic) error {
  700. if len(traffics) == 0 {
  701. return nil
  702. }
  703. var err error
  704. for _, traffic := range traffics {
  705. if traffic.IsInbound {
  706. err = tx.Model(&model.Inbound{}).Where("tag = ?", traffic.Tag).
  707. Updates(map[string]interface{}{
  708. "up": gorm.Expr("up + ?", traffic.Up),
  709. "down": gorm.Expr("down + ?", traffic.Down),
  710. }).Error
  711. if err != nil {
  712. return err
  713. }
  714. }
  715. }
  716. return nil
  717. }
  718. func (s *InboundService) addClientTraffic(tx *gorm.DB, traffics []*xray.ClientTraffic) (err error) {
  719. if len(traffics) == 0 {
  720. // Empty onlineUsers
  721. if p != nil {
  722. p.SetOnlineClients(nil)
  723. }
  724. return nil
  725. }
  726. var onlineClients []string
  727. emails := make([]string, 0, len(traffics))
  728. for _, traffic := range traffics {
  729. emails = append(emails, traffic.Email)
  730. }
  731. dbClientTraffics := make([]*xray.ClientTraffic, 0, len(traffics))
  732. err = tx.Model(xray.ClientTraffic{}).Where("email IN (?)", emails).Find(&dbClientTraffics).Error
  733. if err != nil {
  734. return err
  735. }
  736. // Avoid empty slice error
  737. if len(dbClientTraffics) == 0 {
  738. return nil
  739. }
  740. dbClientTraffics, err = s.adjustTraffics(tx, dbClientTraffics)
  741. if err != nil {
  742. return err
  743. }
  744. for dbTraffic_index := range dbClientTraffics {
  745. for traffic_index := range traffics {
  746. if dbClientTraffics[dbTraffic_index].Email == traffics[traffic_index].Email {
  747. dbClientTraffics[dbTraffic_index].Up += traffics[traffic_index].Up
  748. dbClientTraffics[dbTraffic_index].Down += traffics[traffic_index].Down
  749. // Add user in onlineUsers array on traffic
  750. if traffics[traffic_index].Up+traffics[traffic_index].Down > 0 {
  751. onlineClients = append(onlineClients, traffics[traffic_index].Email)
  752. }
  753. break
  754. }
  755. }
  756. }
  757. // Set onlineUsers
  758. p.SetOnlineClients(onlineClients)
  759. err = tx.Save(dbClientTraffics).Error
  760. if err != nil {
  761. logger.Warning("AddClientTraffic update data ", err)
  762. }
  763. return nil
  764. }
  765. func (s *InboundService) adjustTraffics(tx *gorm.DB, dbClientTraffics []*xray.ClientTraffic) ([]*xray.ClientTraffic, error) {
  766. inboundIds := make([]int, 0, len(dbClientTraffics))
  767. for _, dbClientTraffic := range dbClientTraffics {
  768. if dbClientTraffic.ExpiryTime < 0 {
  769. inboundIds = append(inboundIds, dbClientTraffic.InboundId)
  770. }
  771. }
  772. if len(inboundIds) > 0 {
  773. var inbounds []*model.Inbound
  774. err := tx.Model(model.Inbound{}).Where("id IN (?)", inboundIds).Find(&inbounds).Error
  775. if err != nil {
  776. return nil, err
  777. }
  778. for inbound_index := range inbounds {
  779. settings := map[string]interface{}{}
  780. json.Unmarshal([]byte(inbounds[inbound_index].Settings), &settings)
  781. clients, ok := settings["clients"].([]interface{})
  782. if ok {
  783. var newClients []interface{}
  784. for client_index := range clients {
  785. c := clients[client_index].(map[string]interface{})
  786. for traffic_index := range dbClientTraffics {
  787. if dbClientTraffics[traffic_index].ExpiryTime < 0 && c["email"] == dbClientTraffics[traffic_index].Email {
  788. oldExpiryTime := c["expiryTime"].(float64)
  789. newExpiryTime := (time.Now().Unix() * 1000) - int64(oldExpiryTime)
  790. c["expiryTime"] = newExpiryTime
  791. dbClientTraffics[traffic_index].ExpiryTime = newExpiryTime
  792. break
  793. }
  794. }
  795. newClients = append(newClients, interface{}(c))
  796. }
  797. settings["clients"] = newClients
  798. modifiedSettings, err := json.MarshalIndent(settings, "", " ")
  799. if err != nil {
  800. return nil, err
  801. }
  802. inbounds[inbound_index].Settings = string(modifiedSettings)
  803. }
  804. }
  805. err = tx.Save(inbounds).Error
  806. if err != nil {
  807. logger.Warning("AddClientTraffic update inbounds ", err)
  808. logger.Error(inbounds)
  809. }
  810. }
  811. return dbClientTraffics, nil
  812. }
  813. func (s *InboundService) autoRenewClients(tx *gorm.DB) (bool, int64, error) {
  814. // check for time expired
  815. var traffics []*xray.ClientTraffic
  816. now := time.Now().Unix() * 1000
  817. var err, err1 error
  818. err = tx.Model(xray.ClientTraffic{}).Where("reset > 0 and expiry_time > 0 and expiry_time <= ?", now).Find(&traffics).Error
  819. if err != nil {
  820. return false, 0, err
  821. }
  822. // return if there is no client to renew
  823. if len(traffics) == 0 {
  824. return false, 0, nil
  825. }
  826. var inbound_ids []int
  827. var inbounds []*model.Inbound
  828. needRestart := false
  829. var clientsToAdd []struct {
  830. protocol string
  831. tag string
  832. client map[string]interface{}
  833. }
  834. for _, traffic := range traffics {
  835. inbound_ids = append(inbound_ids, traffic.InboundId)
  836. }
  837. err = tx.Model(model.Inbound{}).Where("id IN ?", inbound_ids).Find(&inbounds).Error
  838. if err != nil {
  839. return false, 0, err
  840. }
  841. for inbound_index := range inbounds {
  842. settings := map[string]interface{}{}
  843. json.Unmarshal([]byte(inbounds[inbound_index].Settings), &settings)
  844. clients := settings["clients"].([]interface{})
  845. for client_index := range clients {
  846. c := clients[client_index].(map[string]interface{})
  847. for traffic_index, traffic := range traffics {
  848. if traffic.Email == c["email"].(string) {
  849. newExpiryTime := traffic.ExpiryTime
  850. for newExpiryTime < now {
  851. newExpiryTime += (int64(traffic.Reset) * 86400000)
  852. }
  853. c["expiryTime"] = newExpiryTime
  854. traffics[traffic_index].ExpiryTime = newExpiryTime
  855. traffics[traffic_index].Down = 0
  856. traffics[traffic_index].Up = 0
  857. if !traffic.Enable {
  858. traffics[traffic_index].Enable = true
  859. clientsToAdd = append(clientsToAdd,
  860. struct {
  861. protocol string
  862. tag string
  863. client map[string]interface{}
  864. }{
  865. protocol: string(inbounds[inbound_index].Protocol),
  866. tag: inbounds[inbound_index].Tag,
  867. client: c,
  868. })
  869. }
  870. clients[client_index] = interface{}(c)
  871. break
  872. }
  873. }
  874. }
  875. settings["clients"] = clients
  876. newSettings, err := json.MarshalIndent(settings, "", " ")
  877. if err != nil {
  878. return false, 0, err
  879. }
  880. inbounds[inbound_index].Settings = string(newSettings)
  881. }
  882. err = tx.Save(inbounds).Error
  883. if err != nil {
  884. return false, 0, err
  885. }
  886. err = tx.Save(traffics).Error
  887. if err != nil {
  888. return false, 0, err
  889. }
  890. if p != nil {
  891. err1 = s.xrayApi.Init(p.GetAPIPort())
  892. if err1 != nil {
  893. return true, int64(len(traffics)), nil
  894. }
  895. for _, clientToAdd := range clientsToAdd {
  896. err1 = s.xrayApi.AddUser(clientToAdd.protocol, clientToAdd.tag, clientToAdd.client)
  897. if err1 != nil {
  898. needRestart = true
  899. }
  900. }
  901. s.xrayApi.Close()
  902. }
  903. return needRestart, int64(len(traffics)), nil
  904. }
  905. func (s *InboundService) disableInvalidInbounds(tx *gorm.DB) (bool, int64, error) {
  906. now := time.Now().Unix() * 1000
  907. needRestart := false
  908. if p != nil {
  909. var tags []string
  910. err := tx.Table("inbounds").
  911. Select("inbounds.tag").
  912. Where("((total > 0 and up + down >= total) or (expiry_time > 0 and expiry_time <= ?)) and enable = ?", now, true).
  913. Scan(&tags).Error
  914. if err != nil {
  915. return false, 0, err
  916. }
  917. s.xrayApi.Init(p.GetAPIPort())
  918. for _, tag := range tags {
  919. err1 := s.xrayApi.DelInbound(tag)
  920. if err1 == nil {
  921. logger.Debug("Inbound disabled by api:", tag)
  922. } else {
  923. logger.Debug("Error in disabling inbound by api:", err1)
  924. needRestart = true
  925. }
  926. }
  927. s.xrayApi.Close()
  928. }
  929. result := tx.Model(model.Inbound{}).
  930. Where("((total > 0 and up + down >= total) or (expiry_time > 0 and expiry_time <= ?)) and enable = ?", now, true).
  931. Update("enable", false)
  932. err := result.Error
  933. count := result.RowsAffected
  934. return needRestart, count, err
  935. }
  936. func (s *InboundService) disableInvalidClients(tx *gorm.DB) (bool, int64, error) {
  937. now := time.Now().Unix() * 1000
  938. needRestart := false
  939. if p != nil {
  940. var results []struct {
  941. Tag string
  942. Email string
  943. }
  944. err := tx.Table("inbounds").
  945. Select("inbounds.tag, client_traffics.email").
  946. Joins("JOIN client_traffics ON inbounds.id = client_traffics.inbound_id").
  947. 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).
  948. Scan(&results).Error
  949. if err != nil {
  950. return false, 0, err
  951. }
  952. s.xrayApi.Init(p.GetAPIPort())
  953. for _, result := range results {
  954. err1 := s.xrayApi.RemoveUser(result.Tag, result.Email)
  955. if err1 == nil {
  956. logger.Debug("Client disabled by api:", result.Email)
  957. } else {
  958. logger.Debug("Error in disabling client by api:", err1)
  959. needRestart = true
  960. }
  961. }
  962. s.xrayApi.Close()
  963. }
  964. result := tx.Model(xray.ClientTraffic{}).
  965. Where("((total > 0 and up + down >= total) or (expiry_time > 0 and expiry_time <= ?)) and enable = ?", now, true).
  966. Update("enable", false)
  967. err := result.Error
  968. count := result.RowsAffected
  969. return needRestart, count, err
  970. }
  971. func (s *InboundService) GetInboundTags() (string, error) {
  972. db := database.GetDB()
  973. var inboundTags []string
  974. err := db.Model(model.Inbound{}).Select("tag").Find(&inboundTags).Error
  975. if err != nil && err != gorm.ErrRecordNotFound {
  976. return "", err
  977. }
  978. tags, _ := json.Marshal(inboundTags)
  979. return string(tags), nil
  980. }
  981. func (s *InboundService) MigrationRemoveOrphanedTraffics() {
  982. db := database.GetDB()
  983. db.Exec(`
  984. DELETE FROM client_traffics
  985. WHERE email NOT IN (
  986. SELECT JSON_EXTRACT(client.value, '$.email')
  987. FROM inbounds,
  988. JSON_EACH(JSON_EXTRACT(inbounds.settings, '$.clients')) AS client
  989. )
  990. `)
  991. }
  992. func (s *InboundService) AddClientStat(tx *gorm.DB, inboundId int, client *model.Client) error {
  993. clientTraffic := xray.ClientTraffic{}
  994. clientTraffic.InboundId = inboundId
  995. clientTraffic.Email = client.Email
  996. clientTraffic.Total = client.TotalGB
  997. clientTraffic.ExpiryTime = client.ExpiryTime
  998. clientTraffic.Enable = true
  999. clientTraffic.Up = 0
  1000. clientTraffic.Down = 0
  1001. clientTraffic.Reset = client.Reset
  1002. result := tx.Create(&clientTraffic)
  1003. err := result.Error
  1004. return err
  1005. }
  1006. func (s *InboundService) UpdateClientStat(tx *gorm.DB, email string, client *model.Client) error {
  1007. result := tx.Model(xray.ClientTraffic{}).
  1008. Where("email = ?", email).
  1009. Updates(map[string]interface{}{
  1010. "enable": true,
  1011. "email": client.Email,
  1012. "total": client.TotalGB,
  1013. "expiry_time": client.ExpiryTime,
  1014. "reset": client.Reset,
  1015. })
  1016. err := result.Error
  1017. return err
  1018. }
  1019. func (s *InboundService) UpdateClientIPs(tx *gorm.DB, oldEmail string, newEmail string) error {
  1020. return tx.Model(model.InboundClientIps{}).Where("client_email = ?", oldEmail).Update("client_email", newEmail).Error
  1021. }
  1022. func (s *InboundService) DelClientStat(tx *gorm.DB, email string) error {
  1023. return tx.Where("email = ?", email).Delete(xray.ClientTraffic{}).Error
  1024. }
  1025. func (s *InboundService) DelClientIPs(tx *gorm.DB, email string) error {
  1026. return tx.Where("client_email = ?", email).Delete(model.InboundClientIps{}).Error
  1027. }
  1028. func (s *InboundService) GetClientInboundByTrafficID(trafficId int) (traffic *xray.ClientTraffic, inbound *model.Inbound, err error) {
  1029. db := database.GetDB()
  1030. var traffics []*xray.ClientTraffic
  1031. err = db.Model(xray.ClientTraffic{}).Where("id = ?", trafficId).Find(&traffics).Error
  1032. if err != nil {
  1033. logger.Warningf("Error retrieving ClientTraffic with trafficId %d: %v", trafficId, err)
  1034. return nil, nil, err
  1035. }
  1036. if len(traffics) > 0 {
  1037. inbound, err = s.GetInbound(traffics[0].InboundId)
  1038. return traffics[0], inbound, err
  1039. }
  1040. return nil, nil, nil
  1041. }
  1042. func (s *InboundService) GetClientInboundByEmail(email string) (traffic *xray.ClientTraffic, inbound *model.Inbound, err error) {
  1043. db := database.GetDB()
  1044. var traffics []*xray.ClientTraffic
  1045. err = db.Model(xray.ClientTraffic{}).Where("email = ?", email).Find(&traffics).Error
  1046. if err != nil {
  1047. logger.Warningf("Error retrieving ClientTraffic with email %s: %v", email, err)
  1048. return nil, nil, err
  1049. }
  1050. if len(traffics) > 0 {
  1051. inbound, err = s.GetInbound(traffics[0].InboundId)
  1052. return traffics[0], inbound, err
  1053. }
  1054. return nil, nil, nil
  1055. }
  1056. func (s *InboundService) GetClientByEmail(clientEmail string) (*xray.ClientTraffic, *model.Client, error) {
  1057. traffic, inbound, err := s.GetClientInboundByEmail(clientEmail)
  1058. if err != nil {
  1059. return nil, nil, err
  1060. }
  1061. if inbound == nil {
  1062. return nil, nil, common.NewError("Inbound Not Found For Email:", clientEmail)
  1063. }
  1064. clients, err := s.GetClients(inbound)
  1065. if err != nil {
  1066. return nil, nil, err
  1067. }
  1068. for _, client := range clients {
  1069. if client.Email == clientEmail {
  1070. return traffic, &client, nil
  1071. }
  1072. }
  1073. return nil, nil, common.NewError("Client Not Found In Inbound For Email:", clientEmail)
  1074. }
  1075. func (s *InboundService) SetClientTelegramUserID(trafficId int, tgId int64) (bool, error) {
  1076. traffic, inbound, err := s.GetClientInboundByTrafficID(trafficId)
  1077. if err != nil {
  1078. return false, err
  1079. }
  1080. if inbound == nil {
  1081. return false, common.NewError("Inbound Not Found For Traffic ID:", trafficId)
  1082. }
  1083. clientEmail := traffic.Email
  1084. oldClients, err := s.GetClients(inbound)
  1085. if err != nil {
  1086. return false, err
  1087. }
  1088. clientId := ""
  1089. for _, oldClient := range oldClients {
  1090. if oldClient.Email == clientEmail {
  1091. if inbound.Protocol == "trojan" {
  1092. clientId = oldClient.Password
  1093. } else if inbound.Protocol == "shadowsocks" {
  1094. clientId = oldClient.Email
  1095. } else {
  1096. clientId = oldClient.ID
  1097. }
  1098. break
  1099. }
  1100. }
  1101. if len(clientId) == 0 {
  1102. return false, common.NewError("Client Not Found For Email:", clientEmail)
  1103. }
  1104. var settings map[string]interface{}
  1105. err = json.Unmarshal([]byte(inbound.Settings), &settings)
  1106. if err != nil {
  1107. return false, err
  1108. }
  1109. clients := settings["clients"].([]interface{})
  1110. var newClients []interface{}
  1111. for client_index := range clients {
  1112. c := clients[client_index].(map[string]interface{})
  1113. if c["email"] == clientEmail {
  1114. c["tgId"] = tgId
  1115. newClients = append(newClients, interface{}(c))
  1116. }
  1117. }
  1118. settings["clients"] = newClients
  1119. modifiedSettings, err := json.MarshalIndent(settings, "", " ")
  1120. if err != nil {
  1121. return false, err
  1122. }
  1123. inbound.Settings = string(modifiedSettings)
  1124. needRestart, err := s.UpdateInboundClient(inbound, clientId)
  1125. return needRestart, err
  1126. }
  1127. func (s *InboundService) checkIsEnabledByEmail(clientEmail string) (bool, error) {
  1128. _, inbound, err := s.GetClientInboundByEmail(clientEmail)
  1129. if err != nil {
  1130. return false, err
  1131. }
  1132. if inbound == nil {
  1133. return false, common.NewError("Inbound Not Found For Email:", clientEmail)
  1134. }
  1135. clients, err := s.GetClients(inbound)
  1136. if err != nil {
  1137. return false, err
  1138. }
  1139. isEnable := false
  1140. for _, client := range clients {
  1141. if client.Email == clientEmail {
  1142. isEnable = client.Enable
  1143. break
  1144. }
  1145. }
  1146. return isEnable, err
  1147. }
  1148. func (s *InboundService) ToggleClientEnableByEmail(clientEmail string) (bool, bool, error) {
  1149. _, inbound, err := s.GetClientInboundByEmail(clientEmail)
  1150. if err != nil {
  1151. return false, false, err
  1152. }
  1153. if inbound == nil {
  1154. return false, false, common.NewError("Inbound Not Found For Email:", clientEmail)
  1155. }
  1156. oldClients, err := s.GetClients(inbound)
  1157. if err != nil {
  1158. return false, false, err
  1159. }
  1160. clientId := ""
  1161. clientOldEnabled := false
  1162. for _, oldClient := range oldClients {
  1163. if oldClient.Email == clientEmail {
  1164. if inbound.Protocol == "trojan" {
  1165. clientId = oldClient.Password
  1166. } else if inbound.Protocol == "shadowsocks" {
  1167. clientId = oldClient.Email
  1168. } else {
  1169. clientId = oldClient.ID
  1170. }
  1171. clientOldEnabled = oldClient.Enable
  1172. break
  1173. }
  1174. }
  1175. if len(clientId) == 0 {
  1176. return false, false, common.NewError("Client Not Found For Email:", clientEmail)
  1177. }
  1178. var settings map[string]interface{}
  1179. err = json.Unmarshal([]byte(inbound.Settings), &settings)
  1180. if err != nil {
  1181. return false, false, err
  1182. }
  1183. clients := settings["clients"].([]interface{})
  1184. var newClients []interface{}
  1185. for client_index := range clients {
  1186. c := clients[client_index].(map[string]interface{})
  1187. if c["email"] == clientEmail {
  1188. c["enable"] = !clientOldEnabled
  1189. newClients = append(newClients, interface{}(c))
  1190. }
  1191. }
  1192. settings["clients"] = newClients
  1193. modifiedSettings, err := json.MarshalIndent(settings, "", " ")
  1194. if err != nil {
  1195. return false, false, err
  1196. }
  1197. inbound.Settings = string(modifiedSettings)
  1198. needRestart, err := s.UpdateInboundClient(inbound, clientId)
  1199. if err != nil {
  1200. return false, needRestart, err
  1201. }
  1202. return !clientOldEnabled, needRestart, nil
  1203. }
  1204. func (s *InboundService) ResetClientIpLimitByEmail(clientEmail string, count int) (bool, error) {
  1205. _, inbound, err := s.GetClientInboundByEmail(clientEmail)
  1206. if err != nil {
  1207. return false, err
  1208. }
  1209. if inbound == nil {
  1210. return false, common.NewError("Inbound Not Found For Email:", clientEmail)
  1211. }
  1212. oldClients, err := s.GetClients(inbound)
  1213. if err != nil {
  1214. return false, err
  1215. }
  1216. clientId := ""
  1217. for _, oldClient := range oldClients {
  1218. if oldClient.Email == clientEmail {
  1219. if inbound.Protocol == "trojan" {
  1220. clientId = oldClient.Password
  1221. } else if inbound.Protocol == "shadowsocks" {
  1222. clientId = oldClient.Email
  1223. } else {
  1224. clientId = oldClient.ID
  1225. }
  1226. break
  1227. }
  1228. }
  1229. if len(clientId) == 0 {
  1230. return false, common.NewError("Client Not Found For Email:", clientEmail)
  1231. }
  1232. var settings map[string]interface{}
  1233. err = json.Unmarshal([]byte(inbound.Settings), &settings)
  1234. if err != nil {
  1235. return false, err
  1236. }
  1237. clients := settings["clients"].([]interface{})
  1238. var newClients []interface{}
  1239. for client_index := range clients {
  1240. c := clients[client_index].(map[string]interface{})
  1241. if c["email"] == clientEmail {
  1242. c["limitIp"] = count
  1243. newClients = append(newClients, interface{}(c))
  1244. }
  1245. }
  1246. settings["clients"] = newClients
  1247. modifiedSettings, err := json.MarshalIndent(settings, "", " ")
  1248. if err != nil {
  1249. return false, err
  1250. }
  1251. inbound.Settings = string(modifiedSettings)
  1252. needRestart, err := s.UpdateInboundClient(inbound, clientId)
  1253. return needRestart, err
  1254. }
  1255. func (s *InboundService) ResetClientExpiryTimeByEmail(clientEmail string, expiry_time int64) (bool, error) {
  1256. _, inbound, err := s.GetClientInboundByEmail(clientEmail)
  1257. if err != nil {
  1258. return false, err
  1259. }
  1260. if inbound == nil {
  1261. return false, common.NewError("Inbound Not Found For Email:", clientEmail)
  1262. }
  1263. oldClients, err := s.GetClients(inbound)
  1264. if err != nil {
  1265. return false, err
  1266. }
  1267. clientId := ""
  1268. for _, oldClient := range oldClients {
  1269. if oldClient.Email == clientEmail {
  1270. if inbound.Protocol == "trojan" {
  1271. clientId = oldClient.Password
  1272. } else if inbound.Protocol == "shadowsocks" {
  1273. clientId = oldClient.Email
  1274. } else {
  1275. clientId = oldClient.ID
  1276. }
  1277. break
  1278. }
  1279. }
  1280. if len(clientId) == 0 {
  1281. return false, common.NewError("Client Not Found For Email:", clientEmail)
  1282. }
  1283. var settings map[string]interface{}
  1284. err = json.Unmarshal([]byte(inbound.Settings), &settings)
  1285. if err != nil {
  1286. return false, err
  1287. }
  1288. clients := settings["clients"].([]interface{})
  1289. var newClients []interface{}
  1290. for client_index := range clients {
  1291. c := clients[client_index].(map[string]interface{})
  1292. if c["email"] == clientEmail {
  1293. c["expiryTime"] = expiry_time
  1294. newClients = append(newClients, interface{}(c))
  1295. }
  1296. }
  1297. settings["clients"] = newClients
  1298. modifiedSettings, err := json.MarshalIndent(settings, "", " ")
  1299. if err != nil {
  1300. return false, err
  1301. }
  1302. inbound.Settings = string(modifiedSettings)
  1303. needRestart, err := s.UpdateInboundClient(inbound, clientId)
  1304. return needRestart, err
  1305. }
  1306. func (s *InboundService) ResetClientTrafficLimitByEmail(clientEmail string, totalGB int) (bool, error) {
  1307. if totalGB < 0 {
  1308. return false, common.NewError("totalGB must be >= 0")
  1309. }
  1310. _, inbound, err := s.GetClientInboundByEmail(clientEmail)
  1311. if err != nil {
  1312. return false, err
  1313. }
  1314. if inbound == nil {
  1315. return false, common.NewError("Inbound Not Found For Email:", clientEmail)
  1316. }
  1317. oldClients, err := s.GetClients(inbound)
  1318. if err != nil {
  1319. return false, err
  1320. }
  1321. clientId := ""
  1322. for _, oldClient := range oldClients {
  1323. if oldClient.Email == clientEmail {
  1324. if inbound.Protocol == "trojan" {
  1325. clientId = oldClient.Password
  1326. } else if inbound.Protocol == "shadowsocks" {
  1327. clientId = oldClient.Email
  1328. } else {
  1329. clientId = oldClient.ID
  1330. }
  1331. break
  1332. }
  1333. }
  1334. if len(clientId) == 0 {
  1335. return false, common.NewError("Client Not Found For Email:", clientEmail)
  1336. }
  1337. var settings map[string]interface{}
  1338. err = json.Unmarshal([]byte(inbound.Settings), &settings)
  1339. if err != nil {
  1340. return false, err
  1341. }
  1342. clients := settings["clients"].([]interface{})
  1343. var newClients []interface{}
  1344. for client_index := range clients {
  1345. c := clients[client_index].(map[string]interface{})
  1346. if c["email"] == clientEmail {
  1347. c["totalGB"] = totalGB * 1024 * 1024 * 1024
  1348. newClients = append(newClients, interface{}(c))
  1349. }
  1350. }
  1351. settings["clients"] = newClients
  1352. modifiedSettings, err := json.MarshalIndent(settings, "", " ")
  1353. if err != nil {
  1354. return false, err
  1355. }
  1356. inbound.Settings = string(modifiedSettings)
  1357. needRestart, err := s.UpdateInboundClient(inbound, clientId)
  1358. return needRestart, err
  1359. }
  1360. func (s *InboundService) ResetClientTrafficByEmail(clientEmail string) error {
  1361. db := database.GetDB()
  1362. result := db.Model(xray.ClientTraffic{}).
  1363. Where("email = ?", clientEmail).
  1364. Updates(map[string]interface{}{"enable": true, "up": 0, "down": 0})
  1365. err := result.Error
  1366. if err != nil {
  1367. return err
  1368. }
  1369. return nil
  1370. }
  1371. func (s *InboundService) ResetClientTraffic(id int, clientEmail string) (bool, error) {
  1372. needRestart := false
  1373. traffic, err := s.GetClientTrafficByEmail(clientEmail)
  1374. if err != nil {
  1375. return false, err
  1376. }
  1377. if !traffic.Enable {
  1378. inbound, err := s.GetInbound(id)
  1379. if err != nil {
  1380. return false, err
  1381. }
  1382. clients, err := s.GetClients(inbound)
  1383. if err != nil {
  1384. return false, err
  1385. }
  1386. for _, client := range clients {
  1387. if client.Email == clientEmail {
  1388. s.xrayApi.Init(p.GetAPIPort())
  1389. cipher := ""
  1390. if string(inbound.Protocol) == "shadowsocks" {
  1391. var oldSettings map[string]interface{}
  1392. err = json.Unmarshal([]byte(inbound.Settings), &oldSettings)
  1393. if err != nil {
  1394. return false, err
  1395. }
  1396. cipher = oldSettings["method"].(string)
  1397. }
  1398. err1 := s.xrayApi.AddUser(string(inbound.Protocol), inbound.Tag, map[string]interface{}{
  1399. "email": client.Email,
  1400. "id": client.ID,
  1401. "security": client.Security,
  1402. "flow": client.Flow,
  1403. "password": client.Password,
  1404. "cipher": cipher,
  1405. })
  1406. if err1 == nil {
  1407. logger.Debug("Client enabled due to reset traffic:", clientEmail)
  1408. } else {
  1409. logger.Debug("Error in enabling client by api:", err1)
  1410. needRestart = true
  1411. }
  1412. s.xrayApi.Close()
  1413. break
  1414. }
  1415. }
  1416. }
  1417. traffic.Up = 0
  1418. traffic.Down = 0
  1419. traffic.Enable = true
  1420. db := database.GetDB()
  1421. err = db.Save(traffic).Error
  1422. if err != nil {
  1423. return false, err
  1424. }
  1425. return needRestart, nil
  1426. }
  1427. func (s *InboundService) ResetAllClientTraffics(id int) error {
  1428. db := database.GetDB()
  1429. whereText := "inbound_id "
  1430. if id == -1 {
  1431. whereText += " > ?"
  1432. } else {
  1433. whereText += " = ?"
  1434. }
  1435. result := db.Model(xray.ClientTraffic{}).
  1436. Where(whereText, id).
  1437. Updates(map[string]interface{}{"enable": true, "up": 0, "down": 0})
  1438. err := result.Error
  1439. return err
  1440. }
  1441. func (s *InboundService) ResetAllTraffics() error {
  1442. db := database.GetDB()
  1443. result := db.Model(model.Inbound{}).
  1444. Where("user_id > ?", 0).
  1445. Updates(map[string]interface{}{"up": 0, "down": 0})
  1446. err := result.Error
  1447. return err
  1448. }
  1449. func (s *InboundService) DelDepletedClients(id int) (err error) {
  1450. db := database.GetDB()
  1451. tx := db.Begin()
  1452. defer func() {
  1453. if err == nil {
  1454. tx.Commit()
  1455. } else {
  1456. tx.Rollback()
  1457. }
  1458. }()
  1459. whereText := "reset = 0 and inbound_id "
  1460. if id < 0 {
  1461. whereText += "> ?"
  1462. } else {
  1463. whereText += "= ?"
  1464. }
  1465. depletedClients := []xray.ClientTraffic{}
  1466. err = db.Model(xray.ClientTraffic{}).Where(whereText+" and enable = ?", id, false).Select("inbound_id, GROUP_CONCAT(email) as email").Group("inbound_id").Find(&depletedClients).Error
  1467. if err != nil {
  1468. return err
  1469. }
  1470. for _, depletedClient := range depletedClients {
  1471. emails := strings.Split(depletedClient.Email, ",")
  1472. oldInbound, err := s.GetInbound(depletedClient.InboundId)
  1473. if err != nil {
  1474. return err
  1475. }
  1476. var oldSettings map[string]interface{}
  1477. err = json.Unmarshal([]byte(oldInbound.Settings), &oldSettings)
  1478. if err != nil {
  1479. return err
  1480. }
  1481. oldClients := oldSettings["clients"].([]interface{})
  1482. var newClients []interface{}
  1483. for _, client := range oldClients {
  1484. deplete := false
  1485. c := client.(map[string]interface{})
  1486. for _, email := range emails {
  1487. if email == c["email"].(string) {
  1488. deplete = true
  1489. break
  1490. }
  1491. }
  1492. if !deplete {
  1493. newClients = append(newClients, client)
  1494. }
  1495. }
  1496. if len(newClients) > 0 {
  1497. oldSettings["clients"] = newClients
  1498. newSettings, err := json.MarshalIndent(oldSettings, "", " ")
  1499. if err != nil {
  1500. return err
  1501. }
  1502. oldInbound.Settings = string(newSettings)
  1503. err = tx.Save(oldInbound).Error
  1504. if err != nil {
  1505. return err
  1506. }
  1507. } else {
  1508. // Delete inbound if no client remains
  1509. s.DelInbound(depletedClient.InboundId)
  1510. }
  1511. }
  1512. err = tx.Where(whereText+" and enable = ?", id, false).Delete(xray.ClientTraffic{}).Error
  1513. if err != nil {
  1514. return err
  1515. }
  1516. return nil
  1517. }
  1518. func (s *InboundService) GetClientTrafficTgBot(tgId int64) ([]*xray.ClientTraffic, error) {
  1519. db := database.GetDB()
  1520. var inbounds []*model.Inbound
  1521. // Retrieve inbounds where settings contain the given tgId
  1522. err := db.Model(model.Inbound{}).Where("settings LIKE ?", fmt.Sprintf(`%%"tgId": %d%%`, tgId)).Find(&inbounds).Error
  1523. if err != nil && err != gorm.ErrRecordNotFound {
  1524. logger.Errorf("Error retrieving inbounds with tgId %d: %v", tgId, err)
  1525. return nil, err
  1526. }
  1527. var emails []string
  1528. for _, inbound := range inbounds {
  1529. clients, err := s.GetClients(inbound)
  1530. if err != nil {
  1531. logger.Errorf("Error retrieving clients for inbound %d: %v", inbound.Id, err)
  1532. continue
  1533. }
  1534. for _, client := range clients {
  1535. if client.TgID == tgId {
  1536. emails = append(emails, client.Email)
  1537. }
  1538. }
  1539. }
  1540. var traffics []*xray.ClientTraffic
  1541. err = db.Model(xray.ClientTraffic{}).Where("email IN ?", emails).Find(&traffics).Error
  1542. if err != nil {
  1543. if err == gorm.ErrRecordNotFound {
  1544. logger.Warning("No ClientTraffic records found for emails:", emails)
  1545. return nil, nil
  1546. }
  1547. logger.Errorf("Error retrieving ClientTraffic for emails %v: %v", emails, err)
  1548. return nil, err
  1549. }
  1550. return traffics, nil
  1551. }
  1552. func (s *InboundService) GetClientTrafficByEmail(email string) (traffic *xray.ClientTraffic, err error) {
  1553. db := database.GetDB()
  1554. var traffics []*xray.ClientTraffic
  1555. err = db.Model(xray.ClientTraffic{}).Where("email = ?", email).Find(&traffics).Error
  1556. if err != nil {
  1557. logger.Warningf("Error retrieving ClientTraffic with email %s: %v", email, err)
  1558. return nil, err
  1559. }
  1560. if len(traffics) > 0 {
  1561. return traffics[0], nil
  1562. }
  1563. return nil, nil
  1564. }
  1565. func (s *InboundService) GetClientTrafficByID(id string) ([]xray.ClientTraffic, error) {
  1566. db := database.GetDB()
  1567. var traffics []xray.ClientTraffic
  1568. err := db.Model(xray.ClientTraffic{}).Where(`email IN(
  1569. SELECT JSON_EXTRACT(client.value, '$.email') as email
  1570. FROM inbounds,
  1571. JSON_EACH(JSON_EXTRACT(inbounds.settings, '$.clients')) AS client
  1572. WHERE
  1573. JSON_EXTRACT(client.value, '$.id') in (?)
  1574. )`, id).Find(&traffics).Error
  1575. if err != nil {
  1576. logger.Debug(err)
  1577. return nil, err
  1578. }
  1579. return traffics, err
  1580. }
  1581. func (s *InboundService) SearchClientTraffic(query string) (traffic *xray.ClientTraffic, err error) {
  1582. db := database.GetDB()
  1583. inbound := &model.Inbound{}
  1584. traffic = &xray.ClientTraffic{}
  1585. // Search for inbound settings that contain the query
  1586. err = db.Model(model.Inbound{}).Where("settings LIKE ?", "%\""+query+"\"%").First(inbound).Error
  1587. if err != nil {
  1588. if err == gorm.ErrRecordNotFound {
  1589. logger.Warningf("Inbound settings containing query %s not found: %v", query, err)
  1590. return nil, err
  1591. }
  1592. logger.Errorf("Error searching for inbound settings with query %s: %v", query, err)
  1593. return nil, err
  1594. }
  1595. traffic.InboundId = inbound.Id
  1596. // Unmarshal settings to get clients
  1597. settings := map[string][]model.Client{}
  1598. if err := json.Unmarshal([]byte(inbound.Settings), &settings); err != nil {
  1599. logger.Errorf("Error unmarshalling inbound settings for inbound ID %d: %v", inbound.Id, err)
  1600. return nil, err
  1601. }
  1602. clients := settings["clients"]
  1603. for _, client := range clients {
  1604. if (client.ID == query || client.Password == query) && client.Email != "" {
  1605. traffic.Email = client.Email
  1606. break
  1607. }
  1608. }
  1609. if traffic.Email == "" {
  1610. logger.Warningf("No client found with query %s in inbound ID %d", query, inbound.Id)
  1611. return nil, gorm.ErrRecordNotFound
  1612. }
  1613. // Retrieve ClientTraffic based on the found email
  1614. err = db.Model(xray.ClientTraffic{}).Where("email = ?", traffic.Email).First(traffic).Error
  1615. if err != nil {
  1616. if err == gorm.ErrRecordNotFound {
  1617. logger.Warningf("ClientTraffic for email %s not found: %v", traffic.Email, err)
  1618. return nil, err
  1619. }
  1620. logger.Errorf("Error retrieving ClientTraffic for email %s: %v", traffic.Email, err)
  1621. return nil, err
  1622. }
  1623. return traffic, nil
  1624. }
  1625. func (s *InboundService) GetInboundClientIps(clientEmail string) (string, error) {
  1626. db := database.GetDB()
  1627. InboundClientIps := &model.InboundClientIps{}
  1628. err := db.Model(model.InboundClientIps{}).Where("client_email = ?", clientEmail).First(InboundClientIps).Error
  1629. if err != nil {
  1630. return "", err
  1631. }
  1632. return InboundClientIps.Ips, nil
  1633. }
  1634. func (s *InboundService) ClearClientIps(clientEmail string) error {
  1635. db := database.GetDB()
  1636. result := db.Model(model.InboundClientIps{}).
  1637. Where("client_email = ?", clientEmail).
  1638. Update("ips", "")
  1639. err := result.Error
  1640. if err != nil {
  1641. return err
  1642. }
  1643. return nil
  1644. }
  1645. func (s *InboundService) SearchInbounds(query string) ([]*model.Inbound, error) {
  1646. db := database.GetDB()
  1647. var inbounds []*model.Inbound
  1648. err := db.Model(model.Inbound{}).Preload("ClientStats").Where("remark like ?", "%"+query+"%").Find(&inbounds).Error
  1649. if err != nil && err != gorm.ErrRecordNotFound {
  1650. return nil, err
  1651. }
  1652. return inbounds, nil
  1653. }
  1654. func (s *InboundService) MigrationRequirements() {
  1655. db := database.GetDB()
  1656. tx := db.Begin()
  1657. var err error
  1658. defer func() {
  1659. if err == nil {
  1660. tx.Commit()
  1661. } else {
  1662. tx.Rollback()
  1663. }
  1664. }()
  1665. // Fix inbounds based problems
  1666. var inbounds []*model.Inbound
  1667. err = tx.Model(model.Inbound{}).Where("protocol IN (?)", []string{"vmess", "vless", "trojan"}).Find(&inbounds).Error
  1668. if err != nil && err != gorm.ErrRecordNotFound {
  1669. return
  1670. }
  1671. for inbound_index := range inbounds {
  1672. settings := map[string]interface{}{}
  1673. json.Unmarshal([]byte(inbounds[inbound_index].Settings), &settings)
  1674. clients, ok := settings["clients"].([]interface{})
  1675. if ok {
  1676. // Fix Client configuration problems
  1677. var newClients []interface{}
  1678. for client_index := range clients {
  1679. c := clients[client_index].(map[string]interface{})
  1680. // Add email='' if it is not exists
  1681. if _, ok := c["email"]; !ok {
  1682. c["email"] = ""
  1683. }
  1684. // Convert string tgId to int64
  1685. if _, ok := c["tgId"]; ok {
  1686. var tgId interface{} = c["tgId"]
  1687. if tgIdStr, ok2 := tgId.(string); ok2 {
  1688. tgIdInt64, err := strconv.ParseInt(strings.ReplaceAll(tgIdStr, " ", ""), 10, 64)
  1689. if err == nil {
  1690. c["tgId"] = tgIdInt64
  1691. }
  1692. }
  1693. }
  1694. // Remove "flow": "xtls-rprx-direct"
  1695. if _, ok := c["flow"]; ok {
  1696. if c["flow"] == "xtls-rprx-direct" {
  1697. c["flow"] = ""
  1698. }
  1699. }
  1700. newClients = append(newClients, interface{}(c))
  1701. }
  1702. settings["clients"] = newClients
  1703. modifiedSettings, err := json.MarshalIndent(settings, "", " ")
  1704. if err != nil {
  1705. return
  1706. }
  1707. inbounds[inbound_index].Settings = string(modifiedSettings)
  1708. }
  1709. // Add client traffic row for all clients which has email
  1710. modelClients, err := s.GetClients(inbounds[inbound_index])
  1711. if err != nil {
  1712. return
  1713. }
  1714. for _, modelClient := range modelClients {
  1715. if len(modelClient.Email) > 0 {
  1716. var count int64
  1717. tx.Model(xray.ClientTraffic{}).Where("email = ?", modelClient.Email).Count(&count)
  1718. if count == 0 {
  1719. s.AddClientStat(tx, inbounds[inbound_index].Id, &modelClient)
  1720. }
  1721. }
  1722. }
  1723. }
  1724. tx.Save(inbounds)
  1725. // Remove orphaned traffics
  1726. tx.Where("inbound_id = 0").Delete(xray.ClientTraffic{})
  1727. // Migrate old MultiDomain to External Proxy
  1728. var externalProxy []struct {
  1729. Id int
  1730. Port int
  1731. StreamSettings []byte
  1732. }
  1733. err = tx.Raw(`select id, port, stream_settings
  1734. from inbounds
  1735. WHERE protocol in ('vmess','vless','trojan')
  1736. AND json_extract(stream_settings, '$.security') = 'tls'
  1737. AND json_extract(stream_settings, '$.tlsSettings.settings.domains') IS NOT NULL`).Scan(&externalProxy).Error
  1738. if err != nil || len(externalProxy) == 0 {
  1739. return
  1740. }
  1741. for _, ep := range externalProxy {
  1742. var reverses interface{}
  1743. var stream map[string]interface{}
  1744. json.Unmarshal(ep.StreamSettings, &stream)
  1745. if tlsSettings, ok := stream["tlsSettings"].(map[string]interface{}); ok {
  1746. if settings, ok := tlsSettings["settings"].(map[string]interface{}); ok {
  1747. if domains, ok := settings["domains"].([]interface{}); ok {
  1748. for _, domain := range domains {
  1749. if domainMap, ok := domain.(map[string]interface{}); ok {
  1750. domainMap["forceTls"] = "same"
  1751. domainMap["port"] = ep.Port
  1752. domainMap["dest"] = domainMap["domain"].(string)
  1753. delete(domainMap, "domain")
  1754. }
  1755. }
  1756. }
  1757. reverses = settings["domains"]
  1758. delete(settings, "domains")
  1759. }
  1760. }
  1761. stream["externalProxy"] = reverses
  1762. newStream, _ := json.MarshalIndent(stream, " ", " ")
  1763. tx.Model(model.Inbound{}).Where("id = ?", ep.Id).Update("stream_settings", newStream)
  1764. }
  1765. err = tx.Raw(`UPDATE inbounds
  1766. SET tag = REPLACE(tag, '0.0.0.0:', '')
  1767. WHERE INSTR(tag, '0.0.0.0:') > 0;`).Error
  1768. if err != nil {
  1769. return
  1770. }
  1771. }
  1772. func (s *InboundService) MigrateDB() {
  1773. s.MigrationRequirements()
  1774. s.MigrationRemoveOrphanedTraffics()
  1775. }
  1776. func (s *InboundService) GetOnlineClients() []string {
  1777. return p.GetOnlineClients()
  1778. }