1
0

inbound.go 51 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993
  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. "flow": client.Flow,
  442. "password": client.Password,
  443. "cipher": cipher,
  444. })
  445. if err1 == nil {
  446. logger.Debug("Client added by api:", client.Email)
  447. } else {
  448. logger.Debug("Error in adding client by api:", err1)
  449. needRestart = true
  450. }
  451. }
  452. } else {
  453. needRestart = true
  454. }
  455. }
  456. s.xrayApi.Close()
  457. return needRestart, tx.Save(oldInbound).Error
  458. }
  459. func (s *InboundService) DelInboundClient(inboundId int, clientId string) (bool, error) {
  460. oldInbound, err := s.GetInbound(inboundId)
  461. if err != nil {
  462. logger.Error("Load Old Data Error")
  463. return false, err
  464. }
  465. var settings map[string]interface{}
  466. err = json.Unmarshal([]byte(oldInbound.Settings), &settings)
  467. if err != nil {
  468. return false, err
  469. }
  470. email := ""
  471. client_key := "id"
  472. if oldInbound.Protocol == "trojan" {
  473. client_key = "password"
  474. }
  475. if oldInbound.Protocol == "shadowsocks" {
  476. client_key = "email"
  477. }
  478. interfaceClients := settings["clients"].([]interface{})
  479. var newClients []interface{}
  480. for _, client := range interfaceClients {
  481. c := client.(map[string]interface{})
  482. c_id := c[client_key].(string)
  483. if c_id == clientId {
  484. email = c["email"].(string)
  485. } else {
  486. newClients = append(newClients, client)
  487. }
  488. }
  489. if len(newClients) == 0 {
  490. return false, common.NewError("no client remained in Inbound")
  491. }
  492. settings["clients"] = newClients
  493. newSettings, err := json.MarshalIndent(settings, "", " ")
  494. if err != nil {
  495. return false, err
  496. }
  497. oldInbound.Settings = string(newSettings)
  498. db := database.GetDB()
  499. err = s.DelClientStat(db, email)
  500. if err != nil {
  501. logger.Error("Delete stats Data Error")
  502. return false, err
  503. }
  504. err = s.DelClientIPs(db, email)
  505. if err != nil {
  506. logger.Error("Error in delete client IPs")
  507. return false, err
  508. }
  509. needRestart := false
  510. if len(email) > 0 {
  511. s.xrayApi.Init(p.GetAPIPort())
  512. err1 := s.xrayApi.RemoveUser(oldInbound.Tag, email)
  513. if err1 == nil {
  514. logger.Debug("Client deleted by api:", email)
  515. needRestart = false
  516. } else {
  517. logger.Debug("Unable to del client by api:", err1)
  518. needRestart = true
  519. }
  520. s.xrayApi.Close()
  521. }
  522. return needRestart, db.Save(oldInbound).Error
  523. }
  524. func (s *InboundService) UpdateInboundClient(data *model.Inbound, clientId string) (bool, error) {
  525. clients, err := s.GetClients(data)
  526. if err != nil {
  527. return false, err
  528. }
  529. var settings map[string]interface{}
  530. err = json.Unmarshal([]byte(data.Settings), &settings)
  531. if err != nil {
  532. return false, err
  533. }
  534. interfaceClients := settings["clients"].([]interface{})
  535. oldInbound, err := s.GetInbound(data.Id)
  536. if err != nil {
  537. return false, err
  538. }
  539. oldClients, err := s.GetClients(oldInbound)
  540. if err != nil {
  541. return false, err
  542. }
  543. oldEmail := ""
  544. newClientId := ""
  545. clientIndex := -1
  546. for index, oldClient := range oldClients {
  547. oldClientId := ""
  548. if oldInbound.Protocol == "trojan" {
  549. oldClientId = oldClient.Password
  550. newClientId = clients[0].Password
  551. } else if oldInbound.Protocol == "shadowsocks" {
  552. oldClientId = oldClient.Email
  553. newClientId = clients[0].Email
  554. } else {
  555. oldClientId = oldClient.ID
  556. newClientId = clients[0].ID
  557. }
  558. if clientId == oldClientId {
  559. oldEmail = oldClient.Email
  560. clientIndex = index
  561. break
  562. }
  563. }
  564. // Validate new client ID
  565. if newClientId == "" || clientIndex == -1 {
  566. return false, common.NewError("empty client ID")
  567. }
  568. if len(clients[0].Email) > 0 && clients[0].Email != oldEmail {
  569. existEmail, err := s.checkEmailsExistForClients(clients)
  570. if err != nil {
  571. return false, err
  572. }
  573. if existEmail != "" {
  574. return false, common.NewError("Duplicate email:", existEmail)
  575. }
  576. }
  577. var oldSettings map[string]interface{}
  578. err = json.Unmarshal([]byte(oldInbound.Settings), &oldSettings)
  579. if err != nil {
  580. return false, err
  581. }
  582. settingsClients := oldSettings["clients"].([]interface{})
  583. settingsClients[clientIndex] = interfaceClients[0]
  584. oldSettings["clients"] = settingsClients
  585. newSettings, err := json.MarshalIndent(oldSettings, "", " ")
  586. if err != nil {
  587. return false, err
  588. }
  589. oldInbound.Settings = string(newSettings)
  590. db := database.GetDB()
  591. tx := db.Begin()
  592. defer func() {
  593. if err != nil {
  594. tx.Rollback()
  595. } else {
  596. tx.Commit()
  597. }
  598. }()
  599. if len(clients[0].Email) > 0 {
  600. if len(oldEmail) > 0 {
  601. err = s.UpdateClientStat(tx, oldEmail, &clients[0])
  602. if err != nil {
  603. return false, err
  604. }
  605. err = s.UpdateClientIPs(tx, oldEmail, clients[0].Email)
  606. if err != nil {
  607. return false, err
  608. }
  609. } else {
  610. s.AddClientStat(tx, data.Id, &clients[0])
  611. }
  612. } else {
  613. err = s.DelClientStat(tx, oldEmail)
  614. if err != nil {
  615. return false, err
  616. }
  617. err = s.DelClientIPs(tx, oldEmail)
  618. if err != nil {
  619. return false, err
  620. }
  621. }
  622. needRestart := false
  623. if len(oldEmail) > 0 {
  624. s.xrayApi.Init(p.GetAPIPort())
  625. err1 := s.xrayApi.RemoveUser(oldInbound.Tag, oldEmail)
  626. if err1 == nil {
  627. logger.Debug("Old client deleted by api:", clients[0].Email)
  628. } else {
  629. logger.Debug("Error in deleting client by api:", err1)
  630. needRestart = true
  631. }
  632. if clients[0].Enable {
  633. cipher := ""
  634. if oldInbound.Protocol == "shadowsocks" {
  635. cipher = oldSettings["method"].(string)
  636. }
  637. err1 := s.xrayApi.AddUser(string(oldInbound.Protocol), oldInbound.Tag, map[string]interface{}{
  638. "email": clients[0].Email,
  639. "id": clients[0].ID,
  640. "flow": clients[0].Flow,
  641. "password": clients[0].Password,
  642. "cipher": cipher,
  643. })
  644. if err1 == nil {
  645. logger.Debug("Client edited by api:", clients[0].Email)
  646. } else {
  647. logger.Debug("Error in adding client by api:", err1)
  648. needRestart = true
  649. }
  650. }
  651. s.xrayApi.Close()
  652. } else {
  653. logger.Debug("Client old email not found")
  654. needRestart = true
  655. }
  656. return needRestart, tx.Save(oldInbound).Error
  657. }
  658. func (s *InboundService) AddTraffic(inboundTraffics []*xray.Traffic, clientTraffics []*xray.ClientTraffic) (error, bool) {
  659. var err error
  660. db := database.GetDB()
  661. tx := db.Begin()
  662. defer func() {
  663. if err != nil {
  664. tx.Rollback()
  665. } else {
  666. tx.Commit()
  667. }
  668. }()
  669. err = s.addInboundTraffic(tx, inboundTraffics)
  670. if err != nil {
  671. return err, false
  672. }
  673. err = s.addClientTraffic(tx, clientTraffics)
  674. if err != nil {
  675. return err, false
  676. }
  677. needRestart0, count, err := s.autoRenewClients(tx)
  678. if err != nil {
  679. logger.Warning("Error in renew clients:", err)
  680. } else if count > 0 {
  681. logger.Debugf("%v clients renewed", count)
  682. }
  683. needRestart1, count, err := s.disableInvalidClients(tx)
  684. if err != nil {
  685. logger.Warning("Error in disabling invalid clients:", err)
  686. } else if count > 0 {
  687. logger.Debugf("%v clients disabled", count)
  688. }
  689. needRestart2, count, err := s.disableInvalidInbounds(tx)
  690. if err != nil {
  691. logger.Warning("Error in disabling invalid inbounds:", err)
  692. } else if count > 0 {
  693. logger.Debugf("%v inbounds disabled", count)
  694. }
  695. return nil, (needRestart0 || needRestart1 || needRestart2)
  696. }
  697. func (s *InboundService) addInboundTraffic(tx *gorm.DB, traffics []*xray.Traffic) error {
  698. if len(traffics) == 0 {
  699. return nil
  700. }
  701. var err error
  702. for _, traffic := range traffics {
  703. if traffic.IsInbound {
  704. err = tx.Model(&model.Inbound{}).Where("tag = ?", traffic.Tag).
  705. Updates(map[string]interface{}{
  706. "up": gorm.Expr("up + ?", traffic.Up),
  707. "down": gorm.Expr("down + ?", traffic.Down),
  708. }).Error
  709. if err != nil {
  710. return err
  711. }
  712. }
  713. }
  714. return nil
  715. }
  716. func (s *InboundService) addClientTraffic(tx *gorm.DB, traffics []*xray.ClientTraffic) (err error) {
  717. if len(traffics) == 0 {
  718. // Empty onlineUsers
  719. if p != nil {
  720. p.SetOnlineClients(nil)
  721. }
  722. return nil
  723. }
  724. var onlineClients []string
  725. emails := make([]string, 0, len(traffics))
  726. for _, traffic := range traffics {
  727. emails = append(emails, traffic.Email)
  728. }
  729. dbClientTraffics := make([]*xray.ClientTraffic, 0, len(traffics))
  730. err = tx.Model(xray.ClientTraffic{}).Where("email IN (?)", emails).Find(&dbClientTraffics).Error
  731. if err != nil {
  732. return err
  733. }
  734. // Avoid empty slice error
  735. if len(dbClientTraffics) == 0 {
  736. return nil
  737. }
  738. dbClientTraffics, err = s.adjustTraffics(tx, dbClientTraffics)
  739. if err != nil {
  740. return err
  741. }
  742. for dbTraffic_index := range dbClientTraffics {
  743. for traffic_index := range traffics {
  744. if dbClientTraffics[dbTraffic_index].Email == traffics[traffic_index].Email {
  745. dbClientTraffics[dbTraffic_index].Up += traffics[traffic_index].Up
  746. dbClientTraffics[dbTraffic_index].Down += traffics[traffic_index].Down
  747. // Add user in onlineUsers array on traffic
  748. if traffics[traffic_index].Up+traffics[traffic_index].Down > 0 {
  749. onlineClients = append(onlineClients, traffics[traffic_index].Email)
  750. }
  751. break
  752. }
  753. }
  754. }
  755. // Set onlineUsers
  756. p.SetOnlineClients(onlineClients)
  757. err = tx.Save(dbClientTraffics).Error
  758. if err != nil {
  759. logger.Warning("AddClientTraffic update data ", err)
  760. }
  761. return nil
  762. }
  763. func (s *InboundService) adjustTraffics(tx *gorm.DB, dbClientTraffics []*xray.ClientTraffic) ([]*xray.ClientTraffic, error) {
  764. inboundIds := make([]int, 0, len(dbClientTraffics))
  765. for _, dbClientTraffic := range dbClientTraffics {
  766. if dbClientTraffic.ExpiryTime < 0 {
  767. inboundIds = append(inboundIds, dbClientTraffic.InboundId)
  768. }
  769. }
  770. if len(inboundIds) > 0 {
  771. var inbounds []*model.Inbound
  772. err := tx.Model(model.Inbound{}).Where("id IN (?)", inboundIds).Find(&inbounds).Error
  773. if err != nil {
  774. return nil, err
  775. }
  776. for inbound_index := range inbounds {
  777. settings := map[string]interface{}{}
  778. json.Unmarshal([]byte(inbounds[inbound_index].Settings), &settings)
  779. clients, ok := settings["clients"].([]interface{})
  780. if ok {
  781. var newClients []interface{}
  782. for client_index := range clients {
  783. c := clients[client_index].(map[string]interface{})
  784. for traffic_index := range dbClientTraffics {
  785. if dbClientTraffics[traffic_index].ExpiryTime < 0 && c["email"] == dbClientTraffics[traffic_index].Email {
  786. oldExpiryTime := c["expiryTime"].(float64)
  787. newExpiryTime := (time.Now().Unix() * 1000) - int64(oldExpiryTime)
  788. c["expiryTime"] = newExpiryTime
  789. dbClientTraffics[traffic_index].ExpiryTime = newExpiryTime
  790. break
  791. }
  792. }
  793. newClients = append(newClients, interface{}(c))
  794. }
  795. settings["clients"] = newClients
  796. modifiedSettings, err := json.MarshalIndent(settings, "", " ")
  797. if err != nil {
  798. return nil, err
  799. }
  800. inbounds[inbound_index].Settings = string(modifiedSettings)
  801. }
  802. }
  803. err = tx.Save(inbounds).Error
  804. if err != nil {
  805. logger.Warning("AddClientTraffic update inbounds ", err)
  806. logger.Error(inbounds)
  807. }
  808. }
  809. return dbClientTraffics, nil
  810. }
  811. func (s *InboundService) autoRenewClients(tx *gorm.DB) (bool, int64, error) {
  812. // check for time expired
  813. var traffics []*xray.ClientTraffic
  814. now := time.Now().Unix() * 1000
  815. var err, err1 error
  816. err = tx.Model(xray.ClientTraffic{}).Where("reset > 0 and expiry_time > 0 and expiry_time <= ?", now).Find(&traffics).Error
  817. if err != nil {
  818. return false, 0, err
  819. }
  820. // return if there is no client to renew
  821. if len(traffics) == 0 {
  822. return false, 0, nil
  823. }
  824. var inbound_ids []int
  825. var inbounds []*model.Inbound
  826. needRestart := false
  827. var clientsToAdd []struct {
  828. protocol string
  829. tag string
  830. client map[string]interface{}
  831. }
  832. for _, traffic := range traffics {
  833. inbound_ids = append(inbound_ids, traffic.InboundId)
  834. }
  835. err = tx.Model(model.Inbound{}).Where("id IN ?", inbound_ids).Find(&inbounds).Error
  836. if err != nil {
  837. return false, 0, err
  838. }
  839. for inbound_index := range inbounds {
  840. settings := map[string]interface{}{}
  841. json.Unmarshal([]byte(inbounds[inbound_index].Settings), &settings)
  842. clients := settings["clients"].([]interface{})
  843. for client_index := range clients {
  844. c := clients[client_index].(map[string]interface{})
  845. for traffic_index, traffic := range traffics {
  846. if traffic.Email == c["email"].(string) {
  847. newExpiryTime := traffic.ExpiryTime
  848. for newExpiryTime < now {
  849. newExpiryTime += (int64(traffic.Reset) * 86400000)
  850. }
  851. c["expiryTime"] = newExpiryTime
  852. traffics[traffic_index].ExpiryTime = newExpiryTime
  853. traffics[traffic_index].Down = 0
  854. traffics[traffic_index].Up = 0
  855. if !traffic.Enable {
  856. traffics[traffic_index].Enable = true
  857. clientsToAdd = append(clientsToAdd,
  858. struct {
  859. protocol string
  860. tag string
  861. client map[string]interface{}
  862. }{
  863. protocol: string(inbounds[inbound_index].Protocol),
  864. tag: inbounds[inbound_index].Tag,
  865. client: c,
  866. })
  867. }
  868. clients[client_index] = interface{}(c)
  869. break
  870. }
  871. }
  872. }
  873. settings["clients"] = clients
  874. newSettings, err := json.MarshalIndent(settings, "", " ")
  875. if err != nil {
  876. return false, 0, err
  877. }
  878. inbounds[inbound_index].Settings = string(newSettings)
  879. }
  880. err = tx.Save(inbounds).Error
  881. if err != nil {
  882. return false, 0, err
  883. }
  884. err = tx.Save(traffics).Error
  885. if err != nil {
  886. return false, 0, err
  887. }
  888. if p != nil {
  889. err1 = s.xrayApi.Init(p.GetAPIPort())
  890. if err1 != nil {
  891. return true, int64(len(traffics)), nil
  892. }
  893. for _, clientToAdd := range clientsToAdd {
  894. err1 = s.xrayApi.AddUser(clientToAdd.protocol, clientToAdd.tag, clientToAdd.client)
  895. if err1 != nil {
  896. needRestart = true
  897. }
  898. }
  899. s.xrayApi.Close()
  900. }
  901. return needRestart, int64(len(traffics)), nil
  902. }
  903. func (s *InboundService) disableInvalidInbounds(tx *gorm.DB) (bool, int64, error) {
  904. now := time.Now().Unix() * 1000
  905. needRestart := false
  906. if p != nil {
  907. var tags []string
  908. err := tx.Table("inbounds").
  909. Select("inbounds.tag").
  910. Where("((total > 0 and up + down >= total) or (expiry_time > 0 and expiry_time <= ?)) and enable = ?", now, true).
  911. Scan(&tags).Error
  912. if err != nil {
  913. return false, 0, err
  914. }
  915. s.xrayApi.Init(p.GetAPIPort())
  916. for _, tag := range tags {
  917. err1 := s.xrayApi.DelInbound(tag)
  918. if err1 == nil {
  919. logger.Debug("Inbound disabled by api:", tag)
  920. } else {
  921. logger.Debug("Error in disabling inbound by api:", err1)
  922. needRestart = true
  923. }
  924. }
  925. s.xrayApi.Close()
  926. }
  927. result := tx.Model(model.Inbound{}).
  928. Where("((total > 0 and up + down >= total) or (expiry_time > 0 and expiry_time <= ?)) and enable = ?", now, true).
  929. Update("enable", false)
  930. err := result.Error
  931. count := result.RowsAffected
  932. return needRestart, count, err
  933. }
  934. func (s *InboundService) disableInvalidClients(tx *gorm.DB) (bool, int64, error) {
  935. now := time.Now().Unix() * 1000
  936. needRestart := false
  937. if p != nil {
  938. var results []struct {
  939. Tag string
  940. Email string
  941. }
  942. err := tx.Table("inbounds").
  943. Select("inbounds.tag, client_traffics.email").
  944. Joins("JOIN client_traffics ON inbounds.id = client_traffics.inbound_id").
  945. 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).
  946. Scan(&results).Error
  947. if err != nil {
  948. return false, 0, err
  949. }
  950. s.xrayApi.Init(p.GetAPIPort())
  951. for _, result := range results {
  952. err1 := s.xrayApi.RemoveUser(result.Tag, result.Email)
  953. if err1 == nil {
  954. logger.Debug("Client disabled by api:", result.Email)
  955. } else {
  956. logger.Debug("Error in disabling client by api:", err1)
  957. needRestart = true
  958. }
  959. }
  960. s.xrayApi.Close()
  961. }
  962. result := tx.Model(xray.ClientTraffic{}).
  963. Where("((total > 0 and up + down >= total) or (expiry_time > 0 and expiry_time <= ?)) and enable = ?", now, true).
  964. Update("enable", false)
  965. err := result.Error
  966. count := result.RowsAffected
  967. return needRestart, count, err
  968. }
  969. func (s *InboundService) GetInboundTags() (string, error) {
  970. db := database.GetDB()
  971. var inboundTags []string
  972. err := db.Model(model.Inbound{}).Select("tag").Find(&inboundTags).Error
  973. if err != nil && err != gorm.ErrRecordNotFound {
  974. return "", err
  975. }
  976. tags, _ := json.Marshal(inboundTags)
  977. return string(tags), nil
  978. }
  979. func (s *InboundService) MigrationRemoveOrphanedTraffics() {
  980. db := database.GetDB()
  981. db.Exec(`
  982. DELETE FROM client_traffics
  983. WHERE email NOT IN (
  984. SELECT JSON_EXTRACT(client.value, '$.email')
  985. FROM inbounds,
  986. JSON_EACH(JSON_EXTRACT(inbounds.settings, '$.clients')) AS client
  987. )
  988. `)
  989. }
  990. func (s *InboundService) AddClientStat(tx *gorm.DB, inboundId int, client *model.Client) error {
  991. clientTraffic := xray.ClientTraffic{}
  992. clientTraffic.InboundId = inboundId
  993. clientTraffic.Email = client.Email
  994. clientTraffic.Total = client.TotalGB
  995. clientTraffic.ExpiryTime = client.ExpiryTime
  996. clientTraffic.Enable = true
  997. clientTraffic.Up = 0
  998. clientTraffic.Down = 0
  999. clientTraffic.Reset = client.Reset
  1000. result := tx.Create(&clientTraffic)
  1001. err := result.Error
  1002. return err
  1003. }
  1004. func (s *InboundService) UpdateClientStat(tx *gorm.DB, email string, client *model.Client) error {
  1005. result := tx.Model(xray.ClientTraffic{}).
  1006. Where("email = ?", email).
  1007. Updates(map[string]interface{}{
  1008. "enable": true,
  1009. "email": client.Email,
  1010. "total": client.TotalGB,
  1011. "expiry_time": client.ExpiryTime,
  1012. "reset": client.Reset,
  1013. })
  1014. err := result.Error
  1015. return err
  1016. }
  1017. func (s *InboundService) UpdateClientIPs(tx *gorm.DB, oldEmail string, newEmail string) error {
  1018. return tx.Model(model.InboundClientIps{}).Where("client_email = ?", oldEmail).Update("client_email", newEmail).Error
  1019. }
  1020. func (s *InboundService) DelClientStat(tx *gorm.DB, email string) error {
  1021. return tx.Where("email = ?", email).Delete(xray.ClientTraffic{}).Error
  1022. }
  1023. func (s *InboundService) DelClientIPs(tx *gorm.DB, email string) error {
  1024. return tx.Where("client_email = ?", email).Delete(model.InboundClientIps{}).Error
  1025. }
  1026. func (s *InboundService) GetClientInboundByTrafficID(trafficId int) (traffic *xray.ClientTraffic, inbound *model.Inbound, err error) {
  1027. db := database.GetDB()
  1028. var traffics []*xray.ClientTraffic
  1029. err = db.Model(xray.ClientTraffic{}).Where("id = ?", trafficId).Find(&traffics).Error
  1030. if err != nil {
  1031. logger.Warningf("Error retrieving ClientTraffic with trafficId %d: %v", trafficId, err)
  1032. return nil, nil, err
  1033. }
  1034. if len(traffics) > 0 {
  1035. inbound, err = s.GetInbound(traffics[0].InboundId)
  1036. return traffics[0], inbound, err
  1037. }
  1038. return nil, nil, nil
  1039. }
  1040. func (s *InboundService) GetClientInboundByEmail(email string) (traffic *xray.ClientTraffic, inbound *model.Inbound, err error) {
  1041. db := database.GetDB()
  1042. var traffics []*xray.ClientTraffic
  1043. err = db.Model(xray.ClientTraffic{}).Where("email = ?", email).Find(&traffics).Error
  1044. if err != nil {
  1045. logger.Warningf("Error retrieving ClientTraffic with email %s: %v", email, err)
  1046. return nil, nil, err
  1047. }
  1048. if len(traffics) > 0 {
  1049. inbound, err = s.GetInbound(traffics[0].InboundId)
  1050. return traffics[0], inbound, err
  1051. }
  1052. return nil, nil, nil
  1053. }
  1054. func (s *InboundService) GetClientByEmail(clientEmail string) (*xray.ClientTraffic, *model.Client, error) {
  1055. traffic, inbound, err := s.GetClientInboundByEmail(clientEmail)
  1056. if err != nil {
  1057. return nil, nil, err
  1058. }
  1059. if inbound == nil {
  1060. return nil, nil, common.NewError("Inbound Not Found For Email:", clientEmail)
  1061. }
  1062. clients, err := s.GetClients(inbound)
  1063. if err != nil {
  1064. return nil, nil, err
  1065. }
  1066. for _, client := range clients {
  1067. if client.Email == clientEmail {
  1068. return traffic, &client, nil
  1069. }
  1070. }
  1071. return nil, nil, common.NewError("Client Not Found In Inbound For Email:", clientEmail)
  1072. }
  1073. func (s *InboundService) SetClientTelegramUserID(trafficId int, tgId int64) (bool, error) {
  1074. traffic, inbound, err := s.GetClientInboundByTrafficID(trafficId)
  1075. if err != nil {
  1076. return false, err
  1077. }
  1078. if inbound == nil {
  1079. return false, common.NewError("Inbound Not Found For Traffic ID:", trafficId)
  1080. }
  1081. clientEmail := traffic.Email
  1082. oldClients, err := s.GetClients(inbound)
  1083. if err != nil {
  1084. return false, err
  1085. }
  1086. clientId := ""
  1087. for _, oldClient := range oldClients {
  1088. if oldClient.Email == clientEmail {
  1089. if inbound.Protocol == "trojan" {
  1090. clientId = oldClient.Password
  1091. } else if inbound.Protocol == "shadowsocks" {
  1092. clientId = oldClient.Email
  1093. } else {
  1094. clientId = oldClient.ID
  1095. }
  1096. break
  1097. }
  1098. }
  1099. if len(clientId) == 0 {
  1100. return false, common.NewError("Client Not Found For Email:", clientEmail)
  1101. }
  1102. var settings map[string]interface{}
  1103. err = json.Unmarshal([]byte(inbound.Settings), &settings)
  1104. if err != nil {
  1105. return false, err
  1106. }
  1107. clients := settings["clients"].([]interface{})
  1108. var newClients []interface{}
  1109. for client_index := range clients {
  1110. c := clients[client_index].(map[string]interface{})
  1111. if c["email"] == clientEmail {
  1112. c["tgId"] = tgId
  1113. newClients = append(newClients, interface{}(c))
  1114. }
  1115. }
  1116. settings["clients"] = newClients
  1117. modifiedSettings, err := json.MarshalIndent(settings, "", " ")
  1118. if err != nil {
  1119. return false, err
  1120. }
  1121. inbound.Settings = string(modifiedSettings)
  1122. needRestart, err := s.UpdateInboundClient(inbound, clientId)
  1123. return needRestart, err
  1124. }
  1125. func (s *InboundService) checkIsEnabledByEmail(clientEmail string) (bool, error) {
  1126. _, inbound, err := s.GetClientInboundByEmail(clientEmail)
  1127. if err != nil {
  1128. return false, err
  1129. }
  1130. if inbound == nil {
  1131. return false, common.NewError("Inbound Not Found For Email:", clientEmail)
  1132. }
  1133. clients, err := s.GetClients(inbound)
  1134. if err != nil {
  1135. return false, err
  1136. }
  1137. isEnable := false
  1138. for _, client := range clients {
  1139. if client.Email == clientEmail {
  1140. isEnable = client.Enable
  1141. break
  1142. }
  1143. }
  1144. return isEnable, err
  1145. }
  1146. func (s *InboundService) ToggleClientEnableByEmail(clientEmail string) (bool, bool, error) {
  1147. _, inbound, err := s.GetClientInboundByEmail(clientEmail)
  1148. if err != nil {
  1149. return false, false, err
  1150. }
  1151. if inbound == nil {
  1152. return false, false, common.NewError("Inbound Not Found For Email:", clientEmail)
  1153. }
  1154. oldClients, err := s.GetClients(inbound)
  1155. if err != nil {
  1156. return false, false, err
  1157. }
  1158. clientId := ""
  1159. clientOldEnabled := false
  1160. for _, oldClient := range oldClients {
  1161. if oldClient.Email == clientEmail {
  1162. if inbound.Protocol == "trojan" {
  1163. clientId = oldClient.Password
  1164. } else if inbound.Protocol == "shadowsocks" {
  1165. clientId = oldClient.Email
  1166. } else {
  1167. clientId = oldClient.ID
  1168. }
  1169. clientOldEnabled = oldClient.Enable
  1170. break
  1171. }
  1172. }
  1173. if len(clientId) == 0 {
  1174. return false, false, common.NewError("Client Not Found For Email:", clientEmail)
  1175. }
  1176. var settings map[string]interface{}
  1177. err = json.Unmarshal([]byte(inbound.Settings), &settings)
  1178. if err != nil {
  1179. return false, false, err
  1180. }
  1181. clients := settings["clients"].([]interface{})
  1182. var newClients []interface{}
  1183. for client_index := range clients {
  1184. c := clients[client_index].(map[string]interface{})
  1185. if c["email"] == clientEmail {
  1186. c["enable"] = !clientOldEnabled
  1187. newClients = append(newClients, interface{}(c))
  1188. }
  1189. }
  1190. settings["clients"] = newClients
  1191. modifiedSettings, err := json.MarshalIndent(settings, "", " ")
  1192. if err != nil {
  1193. return false, false, err
  1194. }
  1195. inbound.Settings = string(modifiedSettings)
  1196. needRestart, err := s.UpdateInboundClient(inbound, clientId)
  1197. if err != nil {
  1198. return false, needRestart, err
  1199. }
  1200. return !clientOldEnabled, needRestart, nil
  1201. }
  1202. func (s *InboundService) ResetClientIpLimitByEmail(clientEmail string, count int) (bool, error) {
  1203. _, inbound, err := s.GetClientInboundByEmail(clientEmail)
  1204. if err != nil {
  1205. return false, err
  1206. }
  1207. if inbound == nil {
  1208. return false, common.NewError("Inbound Not Found For Email:", clientEmail)
  1209. }
  1210. oldClients, err := s.GetClients(inbound)
  1211. if err != nil {
  1212. return false, err
  1213. }
  1214. clientId := ""
  1215. for _, oldClient := range oldClients {
  1216. if oldClient.Email == clientEmail {
  1217. if inbound.Protocol == "trojan" {
  1218. clientId = oldClient.Password
  1219. } else if inbound.Protocol == "shadowsocks" {
  1220. clientId = oldClient.Email
  1221. } else {
  1222. clientId = oldClient.ID
  1223. }
  1224. break
  1225. }
  1226. }
  1227. if len(clientId) == 0 {
  1228. return false, common.NewError("Client Not Found For Email:", clientEmail)
  1229. }
  1230. var settings map[string]interface{}
  1231. err = json.Unmarshal([]byte(inbound.Settings), &settings)
  1232. if err != nil {
  1233. return false, err
  1234. }
  1235. clients := settings["clients"].([]interface{})
  1236. var newClients []interface{}
  1237. for client_index := range clients {
  1238. c := clients[client_index].(map[string]interface{})
  1239. if c["email"] == clientEmail {
  1240. c["limitIp"] = count
  1241. newClients = append(newClients, interface{}(c))
  1242. }
  1243. }
  1244. settings["clients"] = newClients
  1245. modifiedSettings, err := json.MarshalIndent(settings, "", " ")
  1246. if err != nil {
  1247. return false, err
  1248. }
  1249. inbound.Settings = string(modifiedSettings)
  1250. needRestart, err := s.UpdateInboundClient(inbound, clientId)
  1251. return needRestart, err
  1252. }
  1253. func (s *InboundService) ResetClientExpiryTimeByEmail(clientEmail string, expiry_time int64) (bool, error) {
  1254. _, inbound, err := s.GetClientInboundByEmail(clientEmail)
  1255. if err != nil {
  1256. return false, err
  1257. }
  1258. if inbound == nil {
  1259. return false, common.NewError("Inbound Not Found For Email:", clientEmail)
  1260. }
  1261. oldClients, err := s.GetClients(inbound)
  1262. if err != nil {
  1263. return false, err
  1264. }
  1265. clientId := ""
  1266. for _, oldClient := range oldClients {
  1267. if oldClient.Email == clientEmail {
  1268. if inbound.Protocol == "trojan" {
  1269. clientId = oldClient.Password
  1270. } else if inbound.Protocol == "shadowsocks" {
  1271. clientId = oldClient.Email
  1272. } else {
  1273. clientId = oldClient.ID
  1274. }
  1275. break
  1276. }
  1277. }
  1278. if len(clientId) == 0 {
  1279. return false, common.NewError("Client Not Found For Email:", clientEmail)
  1280. }
  1281. var settings map[string]interface{}
  1282. err = json.Unmarshal([]byte(inbound.Settings), &settings)
  1283. if err != nil {
  1284. return false, err
  1285. }
  1286. clients := settings["clients"].([]interface{})
  1287. var newClients []interface{}
  1288. for client_index := range clients {
  1289. c := clients[client_index].(map[string]interface{})
  1290. if c["email"] == clientEmail {
  1291. c["expiryTime"] = expiry_time
  1292. newClients = append(newClients, interface{}(c))
  1293. }
  1294. }
  1295. settings["clients"] = newClients
  1296. modifiedSettings, err := json.MarshalIndent(settings, "", " ")
  1297. if err != nil {
  1298. return false, err
  1299. }
  1300. inbound.Settings = string(modifiedSettings)
  1301. needRestart, err := s.UpdateInboundClient(inbound, clientId)
  1302. return needRestart, err
  1303. }
  1304. func (s *InboundService) ResetClientTrafficLimitByEmail(clientEmail string, totalGB int) (bool, error) {
  1305. if totalGB < 0 {
  1306. return false, common.NewError("totalGB must be >= 0")
  1307. }
  1308. _, inbound, err := s.GetClientInboundByEmail(clientEmail)
  1309. if err != nil {
  1310. return false, err
  1311. }
  1312. if inbound == nil {
  1313. return false, common.NewError("Inbound Not Found For Email:", clientEmail)
  1314. }
  1315. oldClients, err := s.GetClients(inbound)
  1316. if err != nil {
  1317. return false, err
  1318. }
  1319. clientId := ""
  1320. for _, oldClient := range oldClients {
  1321. if oldClient.Email == clientEmail {
  1322. if inbound.Protocol == "trojan" {
  1323. clientId = oldClient.Password
  1324. } else if inbound.Protocol == "shadowsocks" {
  1325. clientId = oldClient.Email
  1326. } else {
  1327. clientId = oldClient.ID
  1328. }
  1329. break
  1330. }
  1331. }
  1332. if len(clientId) == 0 {
  1333. return false, common.NewError("Client Not Found For Email:", clientEmail)
  1334. }
  1335. var settings map[string]interface{}
  1336. err = json.Unmarshal([]byte(inbound.Settings), &settings)
  1337. if err != nil {
  1338. return false, err
  1339. }
  1340. clients := settings["clients"].([]interface{})
  1341. var newClients []interface{}
  1342. for client_index := range clients {
  1343. c := clients[client_index].(map[string]interface{})
  1344. if c["email"] == clientEmail {
  1345. c["totalGB"] = totalGB * 1024 * 1024 * 1024
  1346. newClients = append(newClients, interface{}(c))
  1347. }
  1348. }
  1349. settings["clients"] = newClients
  1350. modifiedSettings, err := json.MarshalIndent(settings, "", " ")
  1351. if err != nil {
  1352. return false, err
  1353. }
  1354. inbound.Settings = string(modifiedSettings)
  1355. needRestart, err := s.UpdateInboundClient(inbound, clientId)
  1356. return needRestart, err
  1357. }
  1358. func (s *InboundService) ResetClientTrafficByEmail(clientEmail string) error {
  1359. db := database.GetDB()
  1360. result := db.Model(xray.ClientTraffic{}).
  1361. Where("email = ?", clientEmail).
  1362. Updates(map[string]interface{}{"enable": true, "up": 0, "down": 0})
  1363. err := result.Error
  1364. if err != nil {
  1365. return err
  1366. }
  1367. return nil
  1368. }
  1369. func (s *InboundService) ResetClientTraffic(id int, clientEmail string) (bool, error) {
  1370. needRestart := false
  1371. traffic, err := s.GetClientTrafficByEmail(clientEmail)
  1372. if err != nil {
  1373. return false, err
  1374. }
  1375. if !traffic.Enable {
  1376. inbound, err := s.GetInbound(id)
  1377. if err != nil {
  1378. return false, err
  1379. }
  1380. clients, err := s.GetClients(inbound)
  1381. if err != nil {
  1382. return false, err
  1383. }
  1384. for _, client := range clients {
  1385. if client.Email == clientEmail {
  1386. s.xrayApi.Init(p.GetAPIPort())
  1387. cipher := ""
  1388. if string(inbound.Protocol) == "shadowsocks" {
  1389. var oldSettings map[string]interface{}
  1390. err = json.Unmarshal([]byte(inbound.Settings), &oldSettings)
  1391. if err != nil {
  1392. return false, err
  1393. }
  1394. cipher = oldSettings["method"].(string)
  1395. }
  1396. err1 := s.xrayApi.AddUser(string(inbound.Protocol), inbound.Tag, map[string]interface{}{
  1397. "email": client.Email,
  1398. "id": client.ID,
  1399. "flow": client.Flow,
  1400. "password": client.Password,
  1401. "cipher": cipher,
  1402. })
  1403. if err1 == nil {
  1404. logger.Debug("Client enabled due to reset traffic:", clientEmail)
  1405. } else {
  1406. logger.Debug("Error in enabling client by api:", err1)
  1407. needRestart = true
  1408. }
  1409. s.xrayApi.Close()
  1410. break
  1411. }
  1412. }
  1413. }
  1414. traffic.Up = 0
  1415. traffic.Down = 0
  1416. traffic.Enable = true
  1417. db := database.GetDB()
  1418. err = db.Save(traffic).Error
  1419. if err != nil {
  1420. return false, err
  1421. }
  1422. return needRestart, nil
  1423. }
  1424. func (s *InboundService) ResetAllClientTraffics(id int) error {
  1425. db := database.GetDB()
  1426. whereText := "inbound_id "
  1427. if id == -1 {
  1428. whereText += " > ?"
  1429. } else {
  1430. whereText += " = ?"
  1431. }
  1432. result := db.Model(xray.ClientTraffic{}).
  1433. Where(whereText, id).
  1434. Updates(map[string]interface{}{"enable": true, "up": 0, "down": 0})
  1435. err := result.Error
  1436. return err
  1437. }
  1438. func (s *InboundService) ResetAllTraffics() error {
  1439. db := database.GetDB()
  1440. result := db.Model(model.Inbound{}).
  1441. Where("user_id > ?", 0).
  1442. Updates(map[string]interface{}{"up": 0, "down": 0})
  1443. err := result.Error
  1444. return err
  1445. }
  1446. func (s *InboundService) DelDepletedClients(id int) (err error) {
  1447. db := database.GetDB()
  1448. tx := db.Begin()
  1449. defer func() {
  1450. if err == nil {
  1451. tx.Commit()
  1452. } else {
  1453. tx.Rollback()
  1454. }
  1455. }()
  1456. whereText := "reset = 0 and inbound_id "
  1457. if id < 0 {
  1458. whereText += "> ?"
  1459. } else {
  1460. whereText += "= ?"
  1461. }
  1462. depletedClients := []xray.ClientTraffic{}
  1463. 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
  1464. if err != nil {
  1465. return err
  1466. }
  1467. for _, depletedClient := range depletedClients {
  1468. emails := strings.Split(depletedClient.Email, ",")
  1469. oldInbound, err := s.GetInbound(depletedClient.InboundId)
  1470. if err != nil {
  1471. return err
  1472. }
  1473. var oldSettings map[string]interface{}
  1474. err = json.Unmarshal([]byte(oldInbound.Settings), &oldSettings)
  1475. if err != nil {
  1476. return err
  1477. }
  1478. oldClients := oldSettings["clients"].([]interface{})
  1479. var newClients []interface{}
  1480. for _, client := range oldClients {
  1481. deplete := false
  1482. c := client.(map[string]interface{})
  1483. for _, email := range emails {
  1484. if email == c["email"].(string) {
  1485. deplete = true
  1486. break
  1487. }
  1488. }
  1489. if !deplete {
  1490. newClients = append(newClients, client)
  1491. }
  1492. }
  1493. if len(newClients) > 0 {
  1494. oldSettings["clients"] = newClients
  1495. newSettings, err := json.MarshalIndent(oldSettings, "", " ")
  1496. if err != nil {
  1497. return err
  1498. }
  1499. oldInbound.Settings = string(newSettings)
  1500. err = tx.Save(oldInbound).Error
  1501. if err != nil {
  1502. return err
  1503. }
  1504. } else {
  1505. // Delete inbound if no client remains
  1506. s.DelInbound(depletedClient.InboundId)
  1507. }
  1508. }
  1509. err = tx.Where(whereText+" and enable = ?", id, false).Delete(xray.ClientTraffic{}).Error
  1510. if err != nil {
  1511. return err
  1512. }
  1513. return nil
  1514. }
  1515. func (s *InboundService) GetClientTrafficTgBot(tgId int64) ([]*xray.ClientTraffic, error) {
  1516. db := database.GetDB()
  1517. var inbounds []*model.Inbound
  1518. // Retrieve inbounds where settings contain the given tgId
  1519. err := db.Model(model.Inbound{}).Where("settings LIKE ?", fmt.Sprintf(`%%"tgId": %d%%`, tgId)).Find(&inbounds).Error
  1520. if err != nil && err != gorm.ErrRecordNotFound {
  1521. logger.Errorf("Error retrieving inbounds with tgId %d: %v", tgId, err)
  1522. return nil, err
  1523. }
  1524. var emails []string
  1525. for _, inbound := range inbounds {
  1526. clients, err := s.GetClients(inbound)
  1527. if err != nil {
  1528. logger.Errorf("Error retrieving clients for inbound %d: %v", inbound.Id, err)
  1529. continue
  1530. }
  1531. for _, client := range clients {
  1532. if client.TgID == tgId {
  1533. emails = append(emails, client.Email)
  1534. }
  1535. }
  1536. }
  1537. var traffics []*xray.ClientTraffic
  1538. err = db.Model(xray.ClientTraffic{}).Where("email IN ?", emails).Find(&traffics).Error
  1539. if err != nil {
  1540. if err == gorm.ErrRecordNotFound {
  1541. logger.Warning("No ClientTraffic records found for emails:", emails)
  1542. return nil, nil
  1543. }
  1544. logger.Errorf("Error retrieving ClientTraffic for emails %v: %v", emails, err)
  1545. return nil, err
  1546. }
  1547. return traffics, nil
  1548. }
  1549. func (s *InboundService) GetClientTrafficByEmail(email string) (traffic *xray.ClientTraffic, err error) {
  1550. db := database.GetDB()
  1551. var traffics []*xray.ClientTraffic
  1552. err = db.Model(xray.ClientTraffic{}).Where("email = ?", email).Find(&traffics).Error
  1553. if err != nil {
  1554. logger.Warningf("Error retrieving ClientTraffic with email %s: %v", email, err)
  1555. return nil, err
  1556. }
  1557. if len(traffics) > 0 {
  1558. return traffics[0], nil
  1559. }
  1560. return nil, nil
  1561. }
  1562. func (s *InboundService) GetClientTrafficByID(id string) ([]xray.ClientTraffic, error) {
  1563. db := database.GetDB()
  1564. var traffics []xray.ClientTraffic
  1565. err := db.Model(xray.ClientTraffic{}).Where(`email IN(
  1566. SELECT JSON_EXTRACT(client.value, '$.email') as email
  1567. FROM inbounds,
  1568. JSON_EACH(JSON_EXTRACT(inbounds.settings, '$.clients')) AS client
  1569. WHERE
  1570. JSON_EXTRACT(client.value, '$.id') in (?)
  1571. )`, id).Find(&traffics).Error
  1572. if err != nil {
  1573. logger.Debug(err)
  1574. return nil, err
  1575. }
  1576. return traffics, err
  1577. }
  1578. func (s *InboundService) SearchClientTraffic(query string) (traffic *xray.ClientTraffic, err error) {
  1579. db := database.GetDB()
  1580. inbound := &model.Inbound{}
  1581. traffic = &xray.ClientTraffic{}
  1582. // Search for inbound settings that contain the query
  1583. err = db.Model(model.Inbound{}).Where("settings LIKE ?", "%\""+query+"\"%").First(inbound).Error
  1584. if err != nil {
  1585. if err == gorm.ErrRecordNotFound {
  1586. logger.Warningf("Inbound settings containing query %s not found: %v", query, err)
  1587. return nil, err
  1588. }
  1589. logger.Errorf("Error searching for inbound settings with query %s: %v", query, err)
  1590. return nil, err
  1591. }
  1592. traffic.InboundId = inbound.Id
  1593. // Unmarshal settings to get clients
  1594. settings := map[string][]model.Client{}
  1595. if err := json.Unmarshal([]byte(inbound.Settings), &settings); err != nil {
  1596. logger.Errorf("Error unmarshalling inbound settings for inbound ID %d: %v", inbound.Id, err)
  1597. return nil, err
  1598. }
  1599. clients := settings["clients"]
  1600. for _, client := range clients {
  1601. if (client.ID == query || client.Password == query) && client.Email != "" {
  1602. traffic.Email = client.Email
  1603. break
  1604. }
  1605. }
  1606. if traffic.Email == "" {
  1607. logger.Warningf("No client found with query %s in inbound ID %d", query, inbound.Id)
  1608. return nil, gorm.ErrRecordNotFound
  1609. }
  1610. // Retrieve ClientTraffic based on the found email
  1611. err = db.Model(xray.ClientTraffic{}).Where("email = ?", traffic.Email).First(traffic).Error
  1612. if err != nil {
  1613. if err == gorm.ErrRecordNotFound {
  1614. logger.Warningf("ClientTraffic for email %s not found: %v", traffic.Email, err)
  1615. return nil, err
  1616. }
  1617. logger.Errorf("Error retrieving ClientTraffic for email %s: %v", traffic.Email, err)
  1618. return nil, err
  1619. }
  1620. return traffic, nil
  1621. }
  1622. func (s *InboundService) GetInboundClientIps(clientEmail string) (string, error) {
  1623. db := database.GetDB()
  1624. InboundClientIps := &model.InboundClientIps{}
  1625. err := db.Model(model.InboundClientIps{}).Where("client_email = ?", clientEmail).First(InboundClientIps).Error
  1626. if err != nil {
  1627. return "", err
  1628. }
  1629. return InboundClientIps.Ips, nil
  1630. }
  1631. func (s *InboundService) ClearClientIps(clientEmail string) error {
  1632. db := database.GetDB()
  1633. result := db.Model(model.InboundClientIps{}).
  1634. Where("client_email = ?", clientEmail).
  1635. Update("ips", "")
  1636. err := result.Error
  1637. if err != nil {
  1638. return err
  1639. }
  1640. return nil
  1641. }
  1642. func (s *InboundService) SearchInbounds(query string) ([]*model.Inbound, error) {
  1643. db := database.GetDB()
  1644. var inbounds []*model.Inbound
  1645. err := db.Model(model.Inbound{}).Preload("ClientStats").Where("remark like ?", "%"+query+"%").Find(&inbounds).Error
  1646. if err != nil && err != gorm.ErrRecordNotFound {
  1647. return nil, err
  1648. }
  1649. return inbounds, nil
  1650. }
  1651. func (s *InboundService) MigrationRequirements() {
  1652. db := database.GetDB()
  1653. tx := db.Begin()
  1654. var err error
  1655. defer func() {
  1656. if err == nil {
  1657. tx.Commit()
  1658. } else {
  1659. tx.Rollback()
  1660. }
  1661. }()
  1662. // Fix inbounds based problems
  1663. var inbounds []*model.Inbound
  1664. err = tx.Model(model.Inbound{}).Where("protocol IN (?)", []string{"vmess", "vless", "trojan"}).Find(&inbounds).Error
  1665. if err != nil && err != gorm.ErrRecordNotFound {
  1666. return
  1667. }
  1668. for inbound_index := range inbounds {
  1669. settings := map[string]interface{}{}
  1670. json.Unmarshal([]byte(inbounds[inbound_index].Settings), &settings)
  1671. clients, ok := settings["clients"].([]interface{})
  1672. if ok {
  1673. // Fix Client configuration problems
  1674. var newClients []interface{}
  1675. for client_index := range clients {
  1676. c := clients[client_index].(map[string]interface{})
  1677. // Add email='' if it is not exists
  1678. if _, ok := c["email"]; !ok {
  1679. c["email"] = ""
  1680. }
  1681. // Convert string tgId to int64
  1682. if _, ok := c["tgId"]; ok {
  1683. var tgId interface{} = c["tgId"]
  1684. if tgIdStr, ok2 := tgId.(string); ok2 {
  1685. tgIdInt64, err := strconv.ParseInt(strings.ReplaceAll(tgIdStr, " ", ""), 10, 64)
  1686. if err == nil {
  1687. c["tgId"] = tgIdInt64
  1688. }
  1689. }
  1690. }
  1691. // Remove "flow": "xtls-rprx-direct"
  1692. if _, ok := c["flow"]; ok {
  1693. if c["flow"] == "xtls-rprx-direct" {
  1694. c["flow"] = ""
  1695. }
  1696. }
  1697. newClients = append(newClients, interface{}(c))
  1698. }
  1699. settings["clients"] = newClients
  1700. modifiedSettings, err := json.MarshalIndent(settings, "", " ")
  1701. if err != nil {
  1702. return
  1703. }
  1704. inbounds[inbound_index].Settings = string(modifiedSettings)
  1705. }
  1706. // Add client traffic row for all clients which has email
  1707. modelClients, err := s.GetClients(inbounds[inbound_index])
  1708. if err != nil {
  1709. return
  1710. }
  1711. for _, modelClient := range modelClients {
  1712. if len(modelClient.Email) > 0 {
  1713. var count int64
  1714. tx.Model(xray.ClientTraffic{}).Where("email = ?", modelClient.Email).Count(&count)
  1715. if count == 0 {
  1716. s.AddClientStat(tx, inbounds[inbound_index].Id, &modelClient)
  1717. }
  1718. }
  1719. }
  1720. }
  1721. tx.Save(inbounds)
  1722. // Remove orphaned traffics
  1723. tx.Where("inbound_id = 0").Delete(xray.ClientTraffic{})
  1724. // Migrate old MultiDomain to External Proxy
  1725. var externalProxy []struct {
  1726. Id int
  1727. Port int
  1728. StreamSettings []byte
  1729. }
  1730. err = tx.Raw(`select id, port, stream_settings
  1731. from inbounds
  1732. WHERE protocol in ('vmess','vless','trojan')
  1733. AND json_extract(stream_settings, '$.security') = 'tls'
  1734. AND json_extract(stream_settings, '$.tlsSettings.settings.domains') IS NOT NULL`).Scan(&externalProxy).Error
  1735. if err != nil || len(externalProxy) == 0 {
  1736. return
  1737. }
  1738. for _, ep := range externalProxy {
  1739. var reverses interface{}
  1740. var stream map[string]interface{}
  1741. json.Unmarshal(ep.StreamSettings, &stream)
  1742. if tlsSettings, ok := stream["tlsSettings"].(map[string]interface{}); ok {
  1743. if settings, ok := tlsSettings["settings"].(map[string]interface{}); ok {
  1744. if domains, ok := settings["domains"].([]interface{}); ok {
  1745. for _, domain := range domains {
  1746. if domainMap, ok := domain.(map[string]interface{}); ok {
  1747. domainMap["forceTls"] = "same"
  1748. domainMap["port"] = ep.Port
  1749. domainMap["dest"] = domainMap["domain"].(string)
  1750. delete(domainMap, "domain")
  1751. }
  1752. }
  1753. }
  1754. reverses = settings["domains"]
  1755. delete(settings, "domains")
  1756. }
  1757. }
  1758. stream["externalProxy"] = reverses
  1759. newStream, _ := json.MarshalIndent(stream, " ", " ")
  1760. tx.Model(model.Inbound{}).Where("id = ?", ep.Id).Update("stream_settings", newStream)
  1761. }
  1762. err = tx.Raw(`UPDATE inbounds
  1763. SET tag = REPLACE(tag, '0.0.0.0:', '')
  1764. WHERE INSTR(tag, '0.0.0.0:') > 0;`).Error
  1765. if err != nil {
  1766. return
  1767. }
  1768. }
  1769. func (s *InboundService) MigrateDB() {
  1770. s.MigrationRequirements()
  1771. s.MigrationRemoveOrphanedTraffics()
  1772. }
  1773. func (s *InboundService) GetOnlineClients() []string {
  1774. return p.GetOnlineClients()
  1775. }