inbound.go 49 KB

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