inbound.go 49 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953
  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. logger.Warning(email)
  1025. return tx.Where("client_email = ?", email).Delete(model.InboundClientIps{}).Error
  1026. }
  1027. func (s *InboundService) GetClientInboundByTrafficID(trafficId int) (traffic *xray.ClientTraffic, inbound *model.Inbound, err error) {
  1028. db := database.GetDB()
  1029. var traffics []*xray.ClientTraffic
  1030. err = db.Model(xray.ClientTraffic{}).Where("id = ?", trafficId).Find(&traffics).Error
  1031. if err != nil {
  1032. logger.Warning(err)
  1033. return nil, nil, err
  1034. }
  1035. if len(traffics) > 0 {
  1036. inbound, err = s.GetInbound(traffics[0].InboundId)
  1037. return traffics[0], inbound, err
  1038. }
  1039. return nil, nil, nil
  1040. }
  1041. func (s *InboundService) GetClientInboundByEmail(email string) (traffic *xray.ClientTraffic, inbound *model.Inbound, err error) {
  1042. db := database.GetDB()
  1043. var traffics []*xray.ClientTraffic
  1044. err = db.Model(xray.ClientTraffic{}).Where("email = ?", email).Find(&traffics).Error
  1045. if err != nil {
  1046. logger.Warning(err)
  1047. return nil, nil, err
  1048. }
  1049. if len(traffics) > 0 {
  1050. inbound, err = s.GetInbound(traffics[0].InboundId)
  1051. return traffics[0], inbound, err
  1052. }
  1053. return nil, nil, nil
  1054. }
  1055. func (s *InboundService) GetClientByEmail(clientEmail string) (*xray.ClientTraffic, *model.Client, error) {
  1056. traffic, inbound, err := s.GetClientInboundByEmail(clientEmail)
  1057. if err != nil {
  1058. return nil, nil, err
  1059. }
  1060. if inbound == nil {
  1061. return nil, nil, common.NewError("Inbound Not Found For Email:", clientEmail)
  1062. }
  1063. clients, err := s.GetClients(inbound)
  1064. if err != nil {
  1065. return nil, nil, err
  1066. }
  1067. for _, client := range clients {
  1068. if client.Email == clientEmail {
  1069. return traffic, &client, nil
  1070. }
  1071. }
  1072. return nil, nil, common.NewError("Client Not Found In Inbound For Email:", clientEmail)
  1073. }
  1074. func (s *InboundService) SetClientTelegramUserID(trafficId int, tgId int64) (bool, error) {
  1075. traffic, inbound, err := s.GetClientInboundByTrafficID(trafficId)
  1076. if err != nil {
  1077. return false, err
  1078. }
  1079. if inbound == nil {
  1080. return false, common.NewError("Inbound Not Found For Traffic ID:", trafficId)
  1081. }
  1082. clientEmail := traffic.Email
  1083. oldClients, err := s.GetClients(inbound)
  1084. if err != nil {
  1085. return false, err
  1086. }
  1087. clientId := ""
  1088. for _, oldClient := range oldClients {
  1089. if oldClient.Email == clientEmail {
  1090. if inbound.Protocol == "trojan" {
  1091. clientId = oldClient.Password
  1092. } else if inbound.Protocol == "shadowsocks" {
  1093. clientId = oldClient.Email
  1094. } else {
  1095. clientId = oldClient.ID
  1096. }
  1097. break
  1098. }
  1099. }
  1100. if len(clientId) == 0 {
  1101. return false, common.NewError("Client Not Found For Email:", clientEmail)
  1102. }
  1103. var settings map[string]interface{}
  1104. err = json.Unmarshal([]byte(inbound.Settings), &settings)
  1105. if err != nil {
  1106. return false, err
  1107. }
  1108. clients := settings["clients"].([]interface{})
  1109. var newClients []interface{}
  1110. for client_index := range clients {
  1111. c := clients[client_index].(map[string]interface{})
  1112. if c["email"] == clientEmail {
  1113. c["tgId"] = tgId
  1114. newClients = append(newClients, interface{}(c))
  1115. }
  1116. }
  1117. settings["clients"] = newClients
  1118. modifiedSettings, err := json.MarshalIndent(settings, "", " ")
  1119. if err != nil {
  1120. return false, err
  1121. }
  1122. inbound.Settings = string(modifiedSettings)
  1123. needRestart, err := s.UpdateInboundClient(inbound, clientId)
  1124. return needRestart, err
  1125. }
  1126. func (s *InboundService) checkIsEnabledByEmail(clientEmail string) (bool, error) {
  1127. _, inbound, err := s.GetClientInboundByEmail(clientEmail)
  1128. if err != nil {
  1129. return false, err
  1130. }
  1131. if inbound == nil {
  1132. return false, common.NewError("Inbound Not Found For Email:", clientEmail)
  1133. }
  1134. clients, err := s.GetClients(inbound)
  1135. if err != nil {
  1136. return false, err
  1137. }
  1138. isEnable := false
  1139. for _, client := range clients {
  1140. if client.Email == clientEmail {
  1141. isEnable = client.Enable
  1142. break
  1143. }
  1144. }
  1145. return isEnable, err
  1146. }
  1147. func (s *InboundService) ToggleClientEnableByEmail(clientEmail string) (bool, bool, error) {
  1148. _, inbound, err := s.GetClientInboundByEmail(clientEmail)
  1149. if err != nil {
  1150. return false, false, err
  1151. }
  1152. if inbound == nil {
  1153. return false, false, common.NewError("Inbound Not Found For Email:", clientEmail)
  1154. }
  1155. oldClients, err := s.GetClients(inbound)
  1156. if err != nil {
  1157. return false, false, err
  1158. }
  1159. clientId := ""
  1160. clientOldEnabled := false
  1161. for _, oldClient := range oldClients {
  1162. if oldClient.Email == clientEmail {
  1163. if inbound.Protocol == "trojan" {
  1164. clientId = oldClient.Password
  1165. } else if inbound.Protocol == "shadowsocks" {
  1166. clientId = oldClient.Email
  1167. } else {
  1168. clientId = oldClient.ID
  1169. }
  1170. clientOldEnabled = oldClient.Enable
  1171. break
  1172. }
  1173. }
  1174. if len(clientId) == 0 {
  1175. return false, false, common.NewError("Client Not Found For Email:", clientEmail)
  1176. }
  1177. var settings map[string]interface{}
  1178. err = json.Unmarshal([]byte(inbound.Settings), &settings)
  1179. if err != nil {
  1180. return false, false, err
  1181. }
  1182. clients := settings["clients"].([]interface{})
  1183. var newClients []interface{}
  1184. for client_index := range clients {
  1185. c := clients[client_index].(map[string]interface{})
  1186. if c["email"] == clientEmail {
  1187. c["enable"] = !clientOldEnabled
  1188. newClients = append(newClients, interface{}(c))
  1189. }
  1190. }
  1191. settings["clients"] = newClients
  1192. modifiedSettings, err := json.MarshalIndent(settings, "", " ")
  1193. if err != nil {
  1194. return false, false, err
  1195. }
  1196. inbound.Settings = string(modifiedSettings)
  1197. needRestart, err := s.UpdateInboundClient(inbound, clientId)
  1198. if err != nil {
  1199. return false, needRestart, err
  1200. }
  1201. return !clientOldEnabled, needRestart, nil
  1202. }
  1203. func (s *InboundService) ResetClientIpLimitByEmail(clientEmail string, count int) (bool, error) {
  1204. _, inbound, err := s.GetClientInboundByEmail(clientEmail)
  1205. if err != nil {
  1206. return false, err
  1207. }
  1208. if inbound == nil {
  1209. return false, common.NewError("Inbound Not Found For Email:", clientEmail)
  1210. }
  1211. oldClients, err := s.GetClients(inbound)
  1212. if err != nil {
  1213. return false, err
  1214. }
  1215. clientId := ""
  1216. for _, oldClient := range oldClients {
  1217. if oldClient.Email == clientEmail {
  1218. if inbound.Protocol == "trojan" {
  1219. clientId = oldClient.Password
  1220. } else if inbound.Protocol == "shadowsocks" {
  1221. clientId = oldClient.Email
  1222. } else {
  1223. clientId = oldClient.ID
  1224. }
  1225. break
  1226. }
  1227. }
  1228. if len(clientId) == 0 {
  1229. return false, common.NewError("Client Not Found For Email:", clientEmail)
  1230. }
  1231. var settings map[string]interface{}
  1232. err = json.Unmarshal([]byte(inbound.Settings), &settings)
  1233. if err != nil {
  1234. return false, err
  1235. }
  1236. clients := settings["clients"].([]interface{})
  1237. var newClients []interface{}
  1238. for client_index := range clients {
  1239. c := clients[client_index].(map[string]interface{})
  1240. if c["email"] == clientEmail {
  1241. c["limitIp"] = count
  1242. newClients = append(newClients, interface{}(c))
  1243. }
  1244. }
  1245. settings["clients"] = newClients
  1246. modifiedSettings, err := json.MarshalIndent(settings, "", " ")
  1247. if err != nil {
  1248. return false, err
  1249. }
  1250. inbound.Settings = string(modifiedSettings)
  1251. needRestart, err := s.UpdateInboundClient(inbound, clientId)
  1252. return needRestart, err
  1253. }
  1254. func (s *InboundService) ResetClientExpiryTimeByEmail(clientEmail string, expiry_time int64) (bool, error) {
  1255. _, inbound, err := s.GetClientInboundByEmail(clientEmail)
  1256. if err != nil {
  1257. return false, err
  1258. }
  1259. if inbound == nil {
  1260. return false, common.NewError("Inbound Not Found For Email:", clientEmail)
  1261. }
  1262. oldClients, err := s.GetClients(inbound)
  1263. if err != nil {
  1264. return false, err
  1265. }
  1266. clientId := ""
  1267. for _, oldClient := range oldClients {
  1268. if oldClient.Email == clientEmail {
  1269. if inbound.Protocol == "trojan" {
  1270. clientId = oldClient.Password
  1271. } else if inbound.Protocol == "shadowsocks" {
  1272. clientId = oldClient.Email
  1273. } else {
  1274. clientId = oldClient.ID
  1275. }
  1276. break
  1277. }
  1278. }
  1279. if len(clientId) == 0 {
  1280. return false, common.NewError("Client Not Found For Email:", clientEmail)
  1281. }
  1282. var settings map[string]interface{}
  1283. err = json.Unmarshal([]byte(inbound.Settings), &settings)
  1284. if err != nil {
  1285. return false, err
  1286. }
  1287. clients := settings["clients"].([]interface{})
  1288. var newClients []interface{}
  1289. for client_index := range clients {
  1290. c := clients[client_index].(map[string]interface{})
  1291. if c["email"] == clientEmail {
  1292. c["expiryTime"] = expiry_time
  1293. newClients = append(newClients, interface{}(c))
  1294. }
  1295. }
  1296. settings["clients"] = newClients
  1297. modifiedSettings, err := json.MarshalIndent(settings, "", " ")
  1298. if err != nil {
  1299. return false, err
  1300. }
  1301. inbound.Settings = string(modifiedSettings)
  1302. needRestart, err := s.UpdateInboundClient(inbound, clientId)
  1303. return needRestart, err
  1304. }
  1305. func (s *InboundService) ResetClientTrafficLimitByEmail(clientEmail string, totalGB int) (bool, error) {
  1306. if totalGB < 0 {
  1307. return false, common.NewError("totalGB must be >= 0")
  1308. }
  1309. _, inbound, err := s.GetClientInboundByEmail(clientEmail)
  1310. if err != nil {
  1311. return false, err
  1312. }
  1313. if inbound == nil {
  1314. return false, common.NewError("Inbound Not Found For Email:", clientEmail)
  1315. }
  1316. oldClients, err := s.GetClients(inbound)
  1317. if err != nil {
  1318. return false, err
  1319. }
  1320. clientId := ""
  1321. for _, oldClient := range oldClients {
  1322. if oldClient.Email == clientEmail {
  1323. if inbound.Protocol == "trojan" {
  1324. clientId = oldClient.Password
  1325. } else if inbound.Protocol == "shadowsocks" {
  1326. clientId = oldClient.Email
  1327. } else {
  1328. clientId = oldClient.ID
  1329. }
  1330. break
  1331. }
  1332. }
  1333. if len(clientId) == 0 {
  1334. return false, common.NewError("Client Not Found For Email:", clientEmail)
  1335. }
  1336. var settings map[string]interface{}
  1337. err = json.Unmarshal([]byte(inbound.Settings), &settings)
  1338. if err != nil {
  1339. return false, err
  1340. }
  1341. clients := settings["clients"].([]interface{})
  1342. var newClients []interface{}
  1343. for client_index := range clients {
  1344. c := clients[client_index].(map[string]interface{})
  1345. if c["email"] == clientEmail {
  1346. c["totalGB"] = totalGB * 1024 * 1024 * 1024
  1347. newClients = append(newClients, interface{}(c))
  1348. }
  1349. }
  1350. settings["clients"] = newClients
  1351. modifiedSettings, err := json.MarshalIndent(settings, "", " ")
  1352. if err != nil {
  1353. return false, err
  1354. }
  1355. inbound.Settings = string(modifiedSettings)
  1356. needRestart, err := s.UpdateInboundClient(inbound, clientId)
  1357. return needRestart, err
  1358. }
  1359. func (s *InboundService) ResetClientTrafficByEmail(clientEmail string) error {
  1360. db := database.GetDB()
  1361. result := db.Model(xray.ClientTraffic{}).
  1362. Where("email = ?", clientEmail).
  1363. Updates(map[string]interface{}{"enable": true, "up": 0, "down": 0})
  1364. err := result.Error
  1365. if err != nil {
  1366. return err
  1367. }
  1368. return nil
  1369. }
  1370. func (s *InboundService) ResetClientTraffic(id int, clientEmail string) (bool, error) {
  1371. needRestart := false
  1372. traffic, err := s.GetClientTrafficByEmail(clientEmail)
  1373. if err != nil {
  1374. return false, err
  1375. }
  1376. if !traffic.Enable {
  1377. inbound, err := s.GetInbound(id)
  1378. if err != nil {
  1379. return false, err
  1380. }
  1381. clients, err := s.GetClients(inbound)
  1382. if err != nil {
  1383. return false, err
  1384. }
  1385. for _, client := range clients {
  1386. if client.Email == clientEmail {
  1387. s.xrayApi.Init(p.GetAPIPort())
  1388. cipher := ""
  1389. if string(inbound.Protocol) == "shadowsocks" {
  1390. var oldSettings map[string]interface{}
  1391. err = json.Unmarshal([]byte(inbound.Settings), &oldSettings)
  1392. if err != nil {
  1393. return false, err
  1394. }
  1395. cipher = oldSettings["method"].(string)
  1396. }
  1397. err1 := s.xrayApi.AddUser(string(inbound.Protocol), inbound.Tag, map[string]interface{}{
  1398. "email": client.Email,
  1399. "id": client.ID,
  1400. "flow": client.Flow,
  1401. "password": client.Password,
  1402. "cipher": cipher,
  1403. })
  1404. if err1 == nil {
  1405. logger.Debug("Client enabled due to reset traffic:", clientEmail)
  1406. } else {
  1407. logger.Debug("Error in enabling client by api:", err1)
  1408. needRestart = true
  1409. }
  1410. s.xrayApi.Close()
  1411. break
  1412. }
  1413. }
  1414. }
  1415. traffic.Up = 0
  1416. traffic.Down = 0
  1417. traffic.Enable = true
  1418. db := database.GetDB()
  1419. err = db.Save(traffic).Error
  1420. if err != nil {
  1421. return false, err
  1422. }
  1423. return needRestart, nil
  1424. }
  1425. func (s *InboundService) ResetAllClientTraffics(id int) error {
  1426. db := database.GetDB()
  1427. whereText := "inbound_id "
  1428. if id == -1 {
  1429. whereText += " > ?"
  1430. } else {
  1431. whereText += " = ?"
  1432. }
  1433. result := db.Model(xray.ClientTraffic{}).
  1434. Where(whereText, id).
  1435. Updates(map[string]interface{}{"enable": true, "up": 0, "down": 0})
  1436. err := result.Error
  1437. return err
  1438. }
  1439. func (s *InboundService) ResetAllTraffics() error {
  1440. db := database.GetDB()
  1441. result := db.Model(model.Inbound{}).
  1442. Where("user_id > ?", 0).
  1443. Updates(map[string]interface{}{"up": 0, "down": 0})
  1444. err := result.Error
  1445. return err
  1446. }
  1447. func (s *InboundService) DelDepletedClients(id int) (err error) {
  1448. db := database.GetDB()
  1449. tx := db.Begin()
  1450. defer func() {
  1451. if err == nil {
  1452. tx.Commit()
  1453. } else {
  1454. tx.Rollback()
  1455. }
  1456. }()
  1457. whereText := "reset = 0 and inbound_id "
  1458. if id < 0 {
  1459. whereText += "> ?"
  1460. } else {
  1461. whereText += "= ?"
  1462. }
  1463. depletedClients := []xray.ClientTraffic{}
  1464. 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
  1465. if err != nil {
  1466. return err
  1467. }
  1468. for _, depletedClient := range depletedClients {
  1469. emails := strings.Split(depletedClient.Email, ",")
  1470. oldInbound, err := s.GetInbound(depletedClient.InboundId)
  1471. if err != nil {
  1472. return err
  1473. }
  1474. var oldSettings map[string]interface{}
  1475. err = json.Unmarshal([]byte(oldInbound.Settings), &oldSettings)
  1476. if err != nil {
  1477. return err
  1478. }
  1479. oldClients := oldSettings["clients"].([]interface{})
  1480. var newClients []interface{}
  1481. for _, client := range oldClients {
  1482. deplete := false
  1483. c := client.(map[string]interface{})
  1484. for _, email := range emails {
  1485. if email == c["email"].(string) {
  1486. deplete = true
  1487. break
  1488. }
  1489. }
  1490. if !deplete {
  1491. newClients = append(newClients, client)
  1492. }
  1493. }
  1494. if len(newClients) > 0 {
  1495. oldSettings["clients"] = newClients
  1496. newSettings, err := json.MarshalIndent(oldSettings, "", " ")
  1497. if err != nil {
  1498. return err
  1499. }
  1500. oldInbound.Settings = string(newSettings)
  1501. err = tx.Save(oldInbound).Error
  1502. if err != nil {
  1503. return err
  1504. }
  1505. } else {
  1506. // Delete inbound if no client remains
  1507. s.DelInbound(depletedClient.InboundId)
  1508. }
  1509. }
  1510. err = tx.Where(whereText+" and enable = ?", id, false).Delete(xray.ClientTraffic{}).Error
  1511. if err != nil {
  1512. return err
  1513. }
  1514. return nil
  1515. }
  1516. func (s *InboundService) GetClientTrafficTgBot(tgId int64) ([]*xray.ClientTraffic, error) {
  1517. db := database.GetDB()
  1518. var inbounds []*model.Inbound
  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. return nil, err
  1522. }
  1523. var emails []string
  1524. for _, inbound := range inbounds {
  1525. clients, err := s.GetClients(inbound)
  1526. if err != nil {
  1527. logger.Error("Unable to get clients from inbound")
  1528. }
  1529. for _, client := range clients {
  1530. if client.TgID == tgId {
  1531. emails = append(emails, client.Email)
  1532. }
  1533. }
  1534. }
  1535. var traffics []*xray.ClientTraffic
  1536. err = db.Model(xray.ClientTraffic{}).Where("email IN ?", emails).Find(&traffics).Error
  1537. if err != nil {
  1538. if err == gorm.ErrRecordNotFound {
  1539. logger.Warning(err)
  1540. return nil, err
  1541. }
  1542. }
  1543. return traffics, err
  1544. }
  1545. func (s *InboundService) GetClientTrafficByEmail(email string) (traffic *xray.ClientTraffic, err error) {
  1546. db := database.GetDB()
  1547. var traffics []*xray.ClientTraffic
  1548. err = db.Model(xray.ClientTraffic{}).Where("email = ?", email).Find(&traffics).Error
  1549. if err != nil {
  1550. logger.Warning(err)
  1551. return nil, err
  1552. }
  1553. if len(traffics) > 0 {
  1554. return traffics[0], nil
  1555. }
  1556. return nil, nil
  1557. }
  1558. func (s *InboundService) SearchClientTraffic(query string) (traffic *xray.ClientTraffic, err error) {
  1559. db := database.GetDB()
  1560. inbound := &model.Inbound{}
  1561. traffic = &xray.ClientTraffic{}
  1562. err = db.Model(model.Inbound{}).Where("settings like ?", "%\""+query+"\"%").First(inbound).Error
  1563. if err != nil {
  1564. if err == gorm.ErrRecordNotFound {
  1565. logger.Warning(err)
  1566. return nil, err
  1567. }
  1568. }
  1569. traffic.InboundId = inbound.Id
  1570. // get settings clients
  1571. settings := map[string][]model.Client{}
  1572. json.Unmarshal([]byte(inbound.Settings), &settings)
  1573. clients := settings["clients"]
  1574. for _, client := range clients {
  1575. if client.ID == query && client.Email != "" {
  1576. traffic.Email = client.Email
  1577. break
  1578. }
  1579. if client.Password == query && client.Email != "" {
  1580. traffic.Email = client.Email
  1581. break
  1582. }
  1583. }
  1584. if traffic.Email == "" {
  1585. return nil, err
  1586. }
  1587. err = db.Model(xray.ClientTraffic{}).Where("email = ?", traffic.Email).First(traffic).Error
  1588. if err != nil {
  1589. logger.Warning(err)
  1590. return nil, err
  1591. }
  1592. return traffic, err
  1593. }
  1594. func (s *InboundService) GetInboundClientIps(clientEmail string) (string, error) {
  1595. db := database.GetDB()
  1596. InboundClientIps := &model.InboundClientIps{}
  1597. err := db.Model(model.InboundClientIps{}).Where("client_email = ?", clientEmail).First(InboundClientIps).Error
  1598. if err != nil {
  1599. return "", err
  1600. }
  1601. return InboundClientIps.Ips, nil
  1602. }
  1603. func (s *InboundService) ClearClientIps(clientEmail string) error {
  1604. db := database.GetDB()
  1605. result := db.Model(model.InboundClientIps{}).
  1606. Where("client_email = ?", clientEmail).
  1607. Update("ips", "")
  1608. err := result.Error
  1609. if err != nil {
  1610. return err
  1611. }
  1612. return nil
  1613. }
  1614. func (s *InboundService) SearchInbounds(query string) ([]*model.Inbound, error) {
  1615. db := database.GetDB()
  1616. var inbounds []*model.Inbound
  1617. err := db.Model(model.Inbound{}).Preload("ClientStats").Where("remark like ?", "%"+query+"%").Find(&inbounds).Error
  1618. if err != nil && err != gorm.ErrRecordNotFound {
  1619. return nil, err
  1620. }
  1621. return inbounds, nil
  1622. }
  1623. func (s *InboundService) MigrationRequirements() {
  1624. db := database.GetDB()
  1625. tx := db.Begin()
  1626. var err error
  1627. defer func() {
  1628. if err == nil {
  1629. tx.Commit()
  1630. } else {
  1631. tx.Rollback()
  1632. }
  1633. }()
  1634. // Fix inbounds based problems
  1635. var inbounds []*model.Inbound
  1636. err = tx.Model(model.Inbound{}).Where("protocol IN (?)", []string{"vmess", "vless", "trojan"}).Find(&inbounds).Error
  1637. if err != nil && err != gorm.ErrRecordNotFound {
  1638. return
  1639. }
  1640. for inbound_index := range inbounds {
  1641. settings := map[string]interface{}{}
  1642. json.Unmarshal([]byte(inbounds[inbound_index].Settings), &settings)
  1643. clients, ok := settings["clients"].([]interface{})
  1644. if ok {
  1645. // Fix Client configuration problems
  1646. var newClients []interface{}
  1647. for client_index := range clients {
  1648. c := clients[client_index].(map[string]interface{})
  1649. // Add email='' if it is not exists
  1650. if _, ok := c["email"]; !ok {
  1651. c["email"] = ""
  1652. }
  1653. // Convert string tgId to int64
  1654. if _, ok := c["tgId"]; ok {
  1655. var tgId interface{} = c["tgId"]
  1656. if tgIdStr, ok2 := tgId.(string); ok2 {
  1657. tgIdInt64, err := strconv.ParseInt(strings.ReplaceAll(tgIdStr, " ", ""), 10, 64)
  1658. if err == nil {
  1659. c["tgId"] = tgIdInt64
  1660. }
  1661. }
  1662. }
  1663. // Remove "flow": "xtls-rprx-direct"
  1664. if _, ok := c["flow"]; ok {
  1665. if c["flow"] == "xtls-rprx-direct" {
  1666. c["flow"] = ""
  1667. }
  1668. }
  1669. newClients = append(newClients, interface{}(c))
  1670. }
  1671. settings["clients"] = newClients
  1672. modifiedSettings, err := json.MarshalIndent(settings, "", " ")
  1673. if err != nil {
  1674. return
  1675. }
  1676. inbounds[inbound_index].Settings = string(modifiedSettings)
  1677. }
  1678. // Add client traffic row for all clients which has email
  1679. modelClients, err := s.GetClients(inbounds[inbound_index])
  1680. if err != nil {
  1681. return
  1682. }
  1683. for _, modelClient := range modelClients {
  1684. if len(modelClient.Email) > 0 {
  1685. var count int64
  1686. tx.Model(xray.ClientTraffic{}).Where("email = ?", modelClient.Email).Count(&count)
  1687. if count == 0 {
  1688. s.AddClientStat(tx, inbounds[inbound_index].Id, &modelClient)
  1689. }
  1690. }
  1691. }
  1692. }
  1693. tx.Save(inbounds)
  1694. // Remove orphaned traffics
  1695. tx.Where("inbound_id = 0").Delete(xray.ClientTraffic{})
  1696. // Migrate old MultiDomain to External Proxy
  1697. var externalProxy []struct {
  1698. Id int
  1699. Port int
  1700. StreamSettings []byte
  1701. }
  1702. err = tx.Raw(`select id, port, stream_settings
  1703. from inbounds
  1704. WHERE protocol in ('vmess','vless','trojan')
  1705. AND json_extract(stream_settings, '$.security') = 'tls'
  1706. AND json_extract(stream_settings, '$.tlsSettings.settings.domains') IS NOT NULL`).Scan(&externalProxy).Error
  1707. if err != nil || len(externalProxy) == 0 {
  1708. return
  1709. }
  1710. for _, ep := range externalProxy {
  1711. var reverses interface{}
  1712. var stream map[string]interface{}
  1713. json.Unmarshal(ep.StreamSettings, &stream)
  1714. if tlsSettings, ok := stream["tlsSettings"].(map[string]interface{}); ok {
  1715. if settings, ok := tlsSettings["settings"].(map[string]interface{}); ok {
  1716. if domains, ok := settings["domains"].([]interface{}); ok {
  1717. for _, domain := range domains {
  1718. if domainMap, ok := domain.(map[string]interface{}); ok {
  1719. domainMap["forceTls"] = "same"
  1720. domainMap["port"] = ep.Port
  1721. domainMap["dest"] = domainMap["domain"].(string)
  1722. delete(domainMap, "domain")
  1723. }
  1724. }
  1725. }
  1726. reverses = settings["domains"]
  1727. delete(settings, "domains")
  1728. }
  1729. }
  1730. stream["externalProxy"] = reverses
  1731. newStream, _ := json.MarshalIndent(stream, " ", " ")
  1732. tx.Model(model.Inbound{}).Where("id = ?", ep.Id).Update("stream_settings", newStream)
  1733. }
  1734. err = tx.Raw(`UPDATE inbounds
  1735. SET tag = REPLACE(tag, '0.0.0.0:', '')
  1736. WHERE INSTR(tag, '0.0.0.0:') > 0;`).Error
  1737. if err != nil {
  1738. return
  1739. }
  1740. }
  1741. func (s *InboundService) MigrateDB() {
  1742. s.MigrationRequirements()
  1743. s.MigrationRemoveOrphanedTraffics()
  1744. }
  1745. func (s *InboundService) GetOnlineClinets() []string {
  1746. return p.GetOnlineClients()
  1747. }