inbound.go 50 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974
  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) SearchClientTraffic(query string) (traffic *xray.ClientTraffic, err error) {
  1563. db := database.GetDB()
  1564. inbound := &model.Inbound{}
  1565. traffic = &xray.ClientTraffic{}
  1566. // Search for inbound settings that contain the query
  1567. err = db.Model(model.Inbound{}).Where("settings LIKE ?", "%\""+query+"\"%").First(inbound).Error
  1568. if err != nil {
  1569. if err == gorm.ErrRecordNotFound {
  1570. logger.Warningf("Inbound settings containing query %s not found: %v", query, err)
  1571. return nil, err
  1572. }
  1573. logger.Errorf("Error searching for inbound settings with query %s: %v", query, err)
  1574. return nil, err
  1575. }
  1576. traffic.InboundId = inbound.Id
  1577. // Unmarshal settings to get clients
  1578. settings := map[string][]model.Client{}
  1579. if err := json.Unmarshal([]byte(inbound.Settings), &settings); err != nil {
  1580. logger.Errorf("Error unmarshalling inbound settings for inbound ID %d: %v", inbound.Id, err)
  1581. return nil, err
  1582. }
  1583. clients := settings["clients"]
  1584. for _, client := range clients {
  1585. if (client.ID == query || client.Password == query) && client.Email != "" {
  1586. traffic.Email = client.Email
  1587. break
  1588. }
  1589. }
  1590. if traffic.Email == "" {
  1591. logger.Warningf("No client found with query %s in inbound ID %d", query, inbound.Id)
  1592. return nil, gorm.ErrRecordNotFound
  1593. }
  1594. // Retrieve ClientTraffic based on the found email
  1595. err = db.Model(xray.ClientTraffic{}).Where("email = ?", traffic.Email).First(traffic).Error
  1596. if err != nil {
  1597. if err == gorm.ErrRecordNotFound {
  1598. logger.Warningf("ClientTraffic for email %s not found: %v", traffic.Email, err)
  1599. return nil, err
  1600. }
  1601. logger.Errorf("Error retrieving ClientTraffic for email %s: %v", traffic.Email, err)
  1602. return nil, err
  1603. }
  1604. return traffic, nil
  1605. }
  1606. func (s *InboundService) GetInboundClientIps(clientEmail string) (string, error) {
  1607. db := database.GetDB()
  1608. InboundClientIps := &model.InboundClientIps{}
  1609. err := db.Model(model.InboundClientIps{}).Where("client_email = ?", clientEmail).First(InboundClientIps).Error
  1610. if err != nil {
  1611. return "", err
  1612. }
  1613. return InboundClientIps.Ips, nil
  1614. }
  1615. func (s *InboundService) ClearClientIps(clientEmail string) error {
  1616. db := database.GetDB()
  1617. result := db.Model(model.InboundClientIps{}).
  1618. Where("client_email = ?", clientEmail).
  1619. Update("ips", "")
  1620. err := result.Error
  1621. if err != nil {
  1622. return err
  1623. }
  1624. return nil
  1625. }
  1626. func (s *InboundService) SearchInbounds(query string) ([]*model.Inbound, error) {
  1627. db := database.GetDB()
  1628. var inbounds []*model.Inbound
  1629. err := db.Model(model.Inbound{}).Preload("ClientStats").Where("remark like ?", "%"+query+"%").Find(&inbounds).Error
  1630. if err != nil && err != gorm.ErrRecordNotFound {
  1631. return nil, err
  1632. }
  1633. return inbounds, nil
  1634. }
  1635. func (s *InboundService) MigrationRequirements() {
  1636. db := database.GetDB()
  1637. tx := db.Begin()
  1638. var err error
  1639. defer func() {
  1640. if err == nil {
  1641. tx.Commit()
  1642. } else {
  1643. tx.Rollback()
  1644. }
  1645. }()
  1646. // Fix inbounds based problems
  1647. var inbounds []*model.Inbound
  1648. err = tx.Model(model.Inbound{}).Where("protocol IN (?)", []string{"vmess", "vless", "trojan"}).Find(&inbounds).Error
  1649. if err != nil && err != gorm.ErrRecordNotFound {
  1650. return
  1651. }
  1652. for inbound_index := range inbounds {
  1653. settings := map[string]interface{}{}
  1654. json.Unmarshal([]byte(inbounds[inbound_index].Settings), &settings)
  1655. clients, ok := settings["clients"].([]interface{})
  1656. if ok {
  1657. // Fix Client configuration problems
  1658. var newClients []interface{}
  1659. for client_index := range clients {
  1660. c := clients[client_index].(map[string]interface{})
  1661. // Add email='' if it is not exists
  1662. if _, ok := c["email"]; !ok {
  1663. c["email"] = ""
  1664. }
  1665. // Convert string tgId to int64
  1666. if _, ok := c["tgId"]; ok {
  1667. var tgId interface{} = c["tgId"]
  1668. if tgIdStr, ok2 := tgId.(string); ok2 {
  1669. tgIdInt64, err := strconv.ParseInt(strings.ReplaceAll(tgIdStr, " ", ""), 10, 64)
  1670. if err == nil {
  1671. c["tgId"] = tgIdInt64
  1672. }
  1673. }
  1674. }
  1675. // Remove "flow": "xtls-rprx-direct"
  1676. if _, ok := c["flow"]; ok {
  1677. if c["flow"] == "xtls-rprx-direct" {
  1678. c["flow"] = ""
  1679. }
  1680. }
  1681. newClients = append(newClients, interface{}(c))
  1682. }
  1683. settings["clients"] = newClients
  1684. modifiedSettings, err := json.MarshalIndent(settings, "", " ")
  1685. if err != nil {
  1686. return
  1687. }
  1688. inbounds[inbound_index].Settings = string(modifiedSettings)
  1689. }
  1690. // Add client traffic row for all clients which has email
  1691. modelClients, err := s.GetClients(inbounds[inbound_index])
  1692. if err != nil {
  1693. return
  1694. }
  1695. for _, modelClient := range modelClients {
  1696. if len(modelClient.Email) > 0 {
  1697. var count int64
  1698. tx.Model(xray.ClientTraffic{}).Where("email = ?", modelClient.Email).Count(&count)
  1699. if count == 0 {
  1700. s.AddClientStat(tx, inbounds[inbound_index].Id, &modelClient)
  1701. }
  1702. }
  1703. }
  1704. }
  1705. tx.Save(inbounds)
  1706. // Remove orphaned traffics
  1707. tx.Where("inbound_id = 0").Delete(xray.ClientTraffic{})
  1708. // Migrate old MultiDomain to External Proxy
  1709. var externalProxy []struct {
  1710. Id int
  1711. Port int
  1712. StreamSettings []byte
  1713. }
  1714. err = tx.Raw(`select id, port, stream_settings
  1715. from inbounds
  1716. WHERE protocol in ('vmess','vless','trojan')
  1717. AND json_extract(stream_settings, '$.security') = 'tls'
  1718. AND json_extract(stream_settings, '$.tlsSettings.settings.domains') IS NOT NULL`).Scan(&externalProxy).Error
  1719. if err != nil || len(externalProxy) == 0 {
  1720. return
  1721. }
  1722. for _, ep := range externalProxy {
  1723. var reverses interface{}
  1724. var stream map[string]interface{}
  1725. json.Unmarshal(ep.StreamSettings, &stream)
  1726. if tlsSettings, ok := stream["tlsSettings"].(map[string]interface{}); ok {
  1727. if settings, ok := tlsSettings["settings"].(map[string]interface{}); ok {
  1728. if domains, ok := settings["domains"].([]interface{}); ok {
  1729. for _, domain := range domains {
  1730. if domainMap, ok := domain.(map[string]interface{}); ok {
  1731. domainMap["forceTls"] = "same"
  1732. domainMap["port"] = ep.Port
  1733. domainMap["dest"] = domainMap["domain"].(string)
  1734. delete(domainMap, "domain")
  1735. }
  1736. }
  1737. }
  1738. reverses = settings["domains"]
  1739. delete(settings, "domains")
  1740. }
  1741. }
  1742. stream["externalProxy"] = reverses
  1743. newStream, _ := json.MarshalIndent(stream, " ", " ")
  1744. tx.Model(model.Inbound{}).Where("id = ?", ep.Id).Update("stream_settings", newStream)
  1745. }
  1746. err = tx.Raw(`UPDATE inbounds
  1747. SET tag = REPLACE(tag, '0.0.0.0:', '')
  1748. WHERE INSTR(tag, '0.0.0.0:') > 0;`).Error
  1749. if err != nil {
  1750. return
  1751. }
  1752. }
  1753. func (s *InboundService) MigrateDB() {
  1754. s.MigrationRequirements()
  1755. s.MigrationRemoveOrphanedTraffics()
  1756. }
  1757. func (s *InboundService) GetOnlineClients() []string {
  1758. return p.GetOnlineClients()
  1759. }