inbound.go 49 KB

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