inbound.go 67 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535
  1. // Package service provides business logic services for the 3x-ui web panel,
  2. // including inbound/outbound management, user administration, settings, and Xray integration.
  3. package service
  4. import (
  5. "encoding/json"
  6. "fmt"
  7. "sort"
  8. "strconv"
  9. "strings"
  10. "time"
  11. "github.com/mhsanaei/3x-ui/v2/database"
  12. "github.com/mhsanaei/3x-ui/v2/database/model"
  13. "github.com/mhsanaei/3x-ui/v2/logger"
  14. "github.com/mhsanaei/3x-ui/v2/util/common"
  15. "github.com/mhsanaei/3x-ui/v2/xray"
  16. "gorm.io/gorm"
  17. )
  18. // InboundService provides business logic for managing Xray inbound configurations.
  19. // It handles CRUD operations for inbounds, client management, traffic monitoring,
  20. // and integration with the Xray API for real-time updates.
  21. type InboundService struct {
  22. xrayApi xray.XrayAPI
  23. }
  24. // GetInbounds retrieves all inbounds for a specific user.
  25. // Returns a slice of inbound models with their associated client statistics.
  26. func (s *InboundService) GetInbounds(userId int) ([]*model.Inbound, error) {
  27. db := database.GetDB()
  28. var inbounds []*model.Inbound
  29. err := db.Model(model.Inbound{}).Preload("ClientStats").Where("user_id = ?", userId).Find(&inbounds).Error
  30. if err != nil && err != gorm.ErrRecordNotFound {
  31. return nil, err
  32. }
  33. // Enrich client stats with UUID/SubId from inbound settings
  34. for _, inbound := range inbounds {
  35. clients, _ := s.GetClients(inbound)
  36. if len(clients) == 0 || len(inbound.ClientStats) == 0 {
  37. continue
  38. }
  39. // Build a map email -> client
  40. cMap := make(map[string]model.Client, len(clients))
  41. for _, c := range clients {
  42. cMap[strings.ToLower(c.Email)] = c
  43. }
  44. for i := range inbound.ClientStats {
  45. email := strings.ToLower(inbound.ClientStats[i].Email)
  46. if c, ok := cMap[email]; ok {
  47. inbound.ClientStats[i].UUID = c.ID
  48. inbound.ClientStats[i].SubId = c.SubID
  49. }
  50. }
  51. }
  52. return inbounds, nil
  53. }
  54. // GetAllInbounds retrieves all inbounds from the database.
  55. // Returns a slice of all inbound models with their associated client statistics.
  56. func (s *InboundService) GetAllInbounds() ([]*model.Inbound, error) {
  57. db := database.GetDB()
  58. var inbounds []*model.Inbound
  59. err := db.Model(model.Inbound{}).Preload("ClientStats").Find(&inbounds).Error
  60. if err != nil && err != gorm.ErrRecordNotFound {
  61. return nil, err
  62. }
  63. // Enrich client stats with UUID/SubId from inbound settings
  64. for _, inbound := range inbounds {
  65. clients, _ := s.GetClients(inbound)
  66. if len(clients) == 0 || len(inbound.ClientStats) == 0 {
  67. continue
  68. }
  69. cMap := make(map[string]model.Client, len(clients))
  70. for _, c := range clients {
  71. cMap[strings.ToLower(c.Email)] = c
  72. }
  73. for i := range inbound.ClientStats {
  74. email := strings.ToLower(inbound.ClientStats[i].Email)
  75. if c, ok := cMap[email]; ok {
  76. inbound.ClientStats[i].UUID = c.ID
  77. inbound.ClientStats[i].SubId = c.SubID
  78. }
  79. }
  80. }
  81. return inbounds, nil
  82. }
  83. func (s *InboundService) GetInboundsByTrafficReset(period string) ([]*model.Inbound, error) {
  84. db := database.GetDB()
  85. var inbounds []*model.Inbound
  86. err := db.Model(model.Inbound{}).Where("traffic_reset = ?", period).Find(&inbounds).Error
  87. if err != nil && err != gorm.ErrRecordNotFound {
  88. return nil, err
  89. }
  90. return inbounds, nil
  91. }
  92. func (s *InboundService) checkPortExist(listen string, port int, ignoreId int) (bool, error) {
  93. db := database.GetDB()
  94. if listen == "" || listen == "0.0.0.0" || listen == "::" || listen == "::0" {
  95. db = db.Model(model.Inbound{}).Where("port = ?", port)
  96. } else {
  97. db = db.Model(model.Inbound{}).
  98. Where("port = ?", port).
  99. Where(
  100. db.Model(model.Inbound{}).Where(
  101. "listen = ?", listen,
  102. ).Or(
  103. "listen = \"\"",
  104. ).Or(
  105. "listen = \"0.0.0.0\"",
  106. ).Or(
  107. "listen = \"::\"",
  108. ).Or(
  109. "listen = \"::0\""))
  110. }
  111. if ignoreId > 0 {
  112. db = db.Where("id != ?", ignoreId)
  113. }
  114. var count int64
  115. err := db.Count(&count).Error
  116. if err != nil {
  117. return false, err
  118. }
  119. return count > 0, nil
  120. }
  121. func (s *InboundService) GetClients(inbound *model.Inbound) ([]model.Client, error) {
  122. settings := map[string][]model.Client{}
  123. json.Unmarshal([]byte(inbound.Settings), &settings)
  124. if settings == nil {
  125. return nil, fmt.Errorf("setting is null")
  126. }
  127. clients := settings["clients"]
  128. if clients == nil {
  129. return nil, nil
  130. }
  131. return clients, nil
  132. }
  133. func (s *InboundService) getAllEmails() ([]string, error) {
  134. db := database.GetDB()
  135. var emails []string
  136. err := db.Raw(`
  137. SELECT JSON_EXTRACT(client.value, '$.email')
  138. FROM inbounds,
  139. JSON_EACH(JSON_EXTRACT(inbounds.settings, '$.clients')) AS client
  140. `).Scan(&emails).Error
  141. if err != nil {
  142. return nil, err
  143. }
  144. return emails, nil
  145. }
  146. func (s *InboundService) contains(slice []string, str string) bool {
  147. lowerStr := strings.ToLower(str)
  148. for _, s := range slice {
  149. if strings.ToLower(s) == lowerStr {
  150. return true
  151. }
  152. }
  153. return false
  154. }
  155. func (s *InboundService) checkEmailsExistForClients(clients []model.Client) (string, error) {
  156. allEmails, err := s.getAllEmails()
  157. if err != nil {
  158. return "", err
  159. }
  160. var emails []string
  161. for _, client := range clients {
  162. if client.Email != "" {
  163. if s.contains(emails, client.Email) {
  164. return client.Email, nil
  165. }
  166. if s.contains(allEmails, client.Email) {
  167. return client.Email, nil
  168. }
  169. emails = append(emails, client.Email)
  170. }
  171. }
  172. return "", nil
  173. }
  174. func (s *InboundService) checkEmailExistForInbound(inbound *model.Inbound) (string, error) {
  175. clients, err := s.GetClients(inbound)
  176. if err != nil {
  177. return "", err
  178. }
  179. allEmails, err := s.getAllEmails()
  180. if err != nil {
  181. return "", err
  182. }
  183. var emails []string
  184. for _, client := range clients {
  185. if client.Email != "" {
  186. if s.contains(emails, client.Email) {
  187. return client.Email, nil
  188. }
  189. if s.contains(allEmails, client.Email) {
  190. return client.Email, nil
  191. }
  192. emails = append(emails, client.Email)
  193. }
  194. }
  195. return "", nil
  196. }
  197. // AddInbound creates a new inbound configuration.
  198. // It validates port uniqueness, client email uniqueness, and required fields,
  199. // then saves the inbound to the database and optionally adds it to the running Xray instance.
  200. // Returns the created inbound, whether Xray needs restart, and any error.
  201. func (s *InboundService) AddInbound(inbound *model.Inbound) (*model.Inbound, bool, error) {
  202. exist, err := s.checkPortExist(inbound.Listen, inbound.Port, 0)
  203. if err != nil {
  204. return inbound, false, err
  205. }
  206. if exist {
  207. return inbound, false, common.NewError("Port already exists:", inbound.Port)
  208. }
  209. existEmail, err := s.checkEmailExistForInbound(inbound)
  210. if err != nil {
  211. return inbound, false, err
  212. }
  213. if existEmail != "" {
  214. return inbound, false, common.NewError("Duplicate email:", existEmail)
  215. }
  216. clients, err := s.GetClients(inbound)
  217. if err != nil {
  218. return inbound, false, err
  219. }
  220. // Ensure created_at and updated_at on clients in settings
  221. if len(clients) > 0 {
  222. var settings map[string]any
  223. if err2 := json.Unmarshal([]byte(inbound.Settings), &settings); err2 == nil && settings != nil {
  224. now := time.Now().Unix() * 1000
  225. updatedClients := make([]model.Client, 0, len(clients))
  226. for _, c := range clients {
  227. if c.CreatedAt == 0 {
  228. c.CreatedAt = now
  229. }
  230. c.UpdatedAt = now
  231. updatedClients = append(updatedClients, c)
  232. }
  233. settings["clients"] = updatedClients
  234. if bs, err3 := json.MarshalIndent(settings, "", " "); err3 == nil {
  235. inbound.Settings = string(bs)
  236. } else {
  237. logger.Debug("Unable to marshal inbound settings with timestamps:", err3)
  238. }
  239. } else if err2 != nil {
  240. logger.Debug("Unable to parse inbound settings for timestamps:", err2)
  241. }
  242. }
  243. // Secure client ID
  244. for _, client := range clients {
  245. switch inbound.Protocol {
  246. case "trojan":
  247. if client.Password == "" {
  248. return inbound, false, common.NewError("empty client ID")
  249. }
  250. case "shadowsocks":
  251. if client.Email == "" {
  252. return inbound, false, common.NewError("empty client ID")
  253. }
  254. case "hysteria":
  255. if client.Auth == "" {
  256. return inbound, false, common.NewError("empty client ID")
  257. }
  258. default:
  259. if client.ID == "" {
  260. return inbound, false, common.NewError("empty client ID")
  261. }
  262. }
  263. }
  264. db := database.GetDB()
  265. tx := db.Begin()
  266. defer func() {
  267. if err == nil {
  268. tx.Commit()
  269. } else {
  270. tx.Rollback()
  271. }
  272. }()
  273. err = tx.Save(inbound).Error
  274. if err == nil {
  275. if len(inbound.ClientStats) == 0 {
  276. for _, client := range clients {
  277. s.AddClientStat(tx, inbound.Id, &client)
  278. }
  279. }
  280. } else {
  281. return inbound, false, err
  282. }
  283. needRestart := false
  284. if inbound.Enable {
  285. s.xrayApi.Init(p.GetAPIPort())
  286. inboundJson, err1 := json.MarshalIndent(inbound.GenXrayInboundConfig(), "", " ")
  287. if err1 != nil {
  288. logger.Debug("Unable to marshal inbound config:", err1)
  289. }
  290. err1 = s.xrayApi.AddInbound(inboundJson)
  291. if err1 == nil {
  292. logger.Debug("New inbound added by api:", inbound.Tag)
  293. } else {
  294. logger.Debug("Unable to add inbound by api:", err1)
  295. needRestart = true
  296. }
  297. s.xrayApi.Close()
  298. }
  299. return inbound, needRestart, err
  300. }
  301. // DelInbound deletes an inbound configuration by ID.
  302. // It removes the inbound from the database and the running Xray instance if active.
  303. // Returns whether Xray needs restart and any error.
  304. func (s *InboundService) DelInbound(id int) (bool, error) {
  305. db := database.GetDB()
  306. var tag string
  307. needRestart := false
  308. result := db.Model(model.Inbound{}).Select("tag").Where("id = ? and enable = ?", id, true).First(&tag)
  309. if result.Error == nil {
  310. s.xrayApi.Init(p.GetAPIPort())
  311. err1 := s.xrayApi.DelInbound(tag)
  312. if err1 == nil {
  313. logger.Debug("Inbound deleted by api:", tag)
  314. } else {
  315. logger.Debug("Unable to delete inbound by api:", err1)
  316. needRestart = true
  317. }
  318. s.xrayApi.Close()
  319. } else {
  320. logger.Debug("No enabled inbound founded to removing by api", tag)
  321. }
  322. // Delete client traffics of inbounds
  323. err := db.Where("inbound_id = ?", id).Delete(xray.ClientTraffic{}).Error
  324. if err != nil {
  325. return false, err
  326. }
  327. inbound, err := s.GetInbound(id)
  328. if err != nil {
  329. return false, err
  330. }
  331. clients, err := s.GetClients(inbound)
  332. if err != nil {
  333. return false, err
  334. }
  335. for _, client := range clients {
  336. err := s.DelClientIPs(db, client.Email)
  337. if err != nil {
  338. return false, err
  339. }
  340. }
  341. return needRestart, db.Delete(model.Inbound{}, id).Error
  342. }
  343. func (s *InboundService) GetInbound(id int) (*model.Inbound, error) {
  344. db := database.GetDB()
  345. inbound := &model.Inbound{}
  346. err := db.Model(model.Inbound{}).First(inbound, id).Error
  347. if err != nil {
  348. return nil, err
  349. }
  350. return inbound, nil
  351. }
  352. // UpdateInbound modifies an existing inbound configuration.
  353. // It validates changes, updates the database, and syncs with the running Xray instance.
  354. // Returns the updated inbound, whether Xray needs restart, and any error.
  355. func (s *InboundService) UpdateInbound(inbound *model.Inbound) (*model.Inbound, bool, error) {
  356. exist, err := s.checkPortExist(inbound.Listen, inbound.Port, inbound.Id)
  357. if err != nil {
  358. return inbound, false, err
  359. }
  360. if exist {
  361. return inbound, false, common.NewError("Port already exists:", inbound.Port)
  362. }
  363. oldInbound, err := s.GetInbound(inbound.Id)
  364. if err != nil {
  365. return inbound, false, err
  366. }
  367. tag := oldInbound.Tag
  368. db := database.GetDB()
  369. tx := db.Begin()
  370. defer func() {
  371. if err != nil {
  372. tx.Rollback()
  373. } else {
  374. tx.Commit()
  375. }
  376. }()
  377. err = s.updateClientTraffics(tx, oldInbound, inbound)
  378. if err != nil {
  379. return inbound, false, err
  380. }
  381. // Ensure created_at and updated_at exist in inbound.Settings clients
  382. {
  383. var oldSettings map[string]any
  384. _ = json.Unmarshal([]byte(oldInbound.Settings), &oldSettings)
  385. emailToCreated := map[string]int64{}
  386. emailToUpdated := map[string]int64{}
  387. if oldSettings != nil {
  388. if oc, ok := oldSettings["clients"].([]any); ok {
  389. for _, it := range oc {
  390. if m, ok2 := it.(map[string]any); ok2 {
  391. if email, ok3 := m["email"].(string); ok3 {
  392. switch v := m["created_at"].(type) {
  393. case float64:
  394. emailToCreated[email] = int64(v)
  395. case int64:
  396. emailToCreated[email] = v
  397. }
  398. switch v := m["updated_at"].(type) {
  399. case float64:
  400. emailToUpdated[email] = int64(v)
  401. case int64:
  402. emailToUpdated[email] = v
  403. }
  404. }
  405. }
  406. }
  407. }
  408. }
  409. var newSettings map[string]any
  410. if err2 := json.Unmarshal([]byte(inbound.Settings), &newSettings); err2 == nil && newSettings != nil {
  411. now := time.Now().Unix() * 1000
  412. if nSlice, ok := newSettings["clients"].([]any); ok {
  413. for i := range nSlice {
  414. if m, ok2 := nSlice[i].(map[string]any); ok2 {
  415. email, _ := m["email"].(string)
  416. if _, ok3 := m["created_at"]; !ok3 {
  417. if v, ok4 := emailToCreated[email]; ok4 && v > 0 {
  418. m["created_at"] = v
  419. } else {
  420. m["created_at"] = now
  421. }
  422. }
  423. // Preserve client's updated_at if present; do not bump on parent inbound update
  424. if _, hasUpdated := m["updated_at"]; !hasUpdated {
  425. if v, ok4 := emailToUpdated[email]; ok4 && v > 0 {
  426. m["updated_at"] = v
  427. }
  428. }
  429. nSlice[i] = m
  430. }
  431. }
  432. newSettings["clients"] = nSlice
  433. if bs, err3 := json.MarshalIndent(newSettings, "", " "); err3 == nil {
  434. inbound.Settings = string(bs)
  435. }
  436. }
  437. }
  438. }
  439. oldInbound.Up = inbound.Up
  440. oldInbound.Down = inbound.Down
  441. oldInbound.Total = inbound.Total
  442. oldInbound.Remark = inbound.Remark
  443. oldInbound.Enable = inbound.Enable
  444. oldInbound.ExpiryTime = inbound.ExpiryTime
  445. oldInbound.TrafficReset = inbound.TrafficReset
  446. oldInbound.Listen = inbound.Listen
  447. oldInbound.Port = inbound.Port
  448. oldInbound.Protocol = inbound.Protocol
  449. oldInbound.Settings = inbound.Settings
  450. oldInbound.StreamSettings = inbound.StreamSettings
  451. oldInbound.Sniffing = inbound.Sniffing
  452. if inbound.Listen == "" || inbound.Listen == "0.0.0.0" || inbound.Listen == "::" || inbound.Listen == "::0" {
  453. oldInbound.Tag = fmt.Sprintf("inbound-%v", inbound.Port)
  454. } else {
  455. oldInbound.Tag = fmt.Sprintf("inbound-%v:%v", inbound.Listen, inbound.Port)
  456. }
  457. needRestart := false
  458. s.xrayApi.Init(p.GetAPIPort())
  459. if s.xrayApi.DelInbound(tag) == nil {
  460. logger.Debug("Old inbound deleted by api:", tag)
  461. }
  462. if inbound.Enable {
  463. inboundJson, err2 := json.MarshalIndent(oldInbound.GenXrayInboundConfig(), "", " ")
  464. if err2 != nil {
  465. logger.Debug("Unable to marshal updated inbound config:", err2)
  466. needRestart = true
  467. } else {
  468. err2 = s.xrayApi.AddInbound(inboundJson)
  469. if err2 == nil {
  470. logger.Debug("Updated inbound added by api:", oldInbound.Tag)
  471. } else {
  472. logger.Debug("Unable to update inbound by api:", err2)
  473. needRestart = true
  474. }
  475. }
  476. }
  477. s.xrayApi.Close()
  478. return inbound, needRestart, tx.Save(oldInbound).Error
  479. }
  480. func (s *InboundService) updateClientTraffics(tx *gorm.DB, oldInbound *model.Inbound, newInbound *model.Inbound) error {
  481. oldClients, err := s.GetClients(oldInbound)
  482. if err != nil {
  483. return err
  484. }
  485. newClients, err := s.GetClients(newInbound)
  486. if err != nil {
  487. return err
  488. }
  489. var emailExists bool
  490. for _, oldClient := range oldClients {
  491. emailExists = false
  492. for _, newClient := range newClients {
  493. if oldClient.Email == newClient.Email {
  494. emailExists = true
  495. break
  496. }
  497. }
  498. if !emailExists {
  499. err = s.DelClientStat(tx, oldClient.Email)
  500. if err != nil {
  501. return err
  502. }
  503. }
  504. }
  505. for _, newClient := range newClients {
  506. emailExists = false
  507. for _, oldClient := range oldClients {
  508. if newClient.Email == oldClient.Email {
  509. emailExists = true
  510. break
  511. }
  512. }
  513. if !emailExists {
  514. err = s.AddClientStat(tx, oldInbound.Id, &newClient)
  515. if err != nil {
  516. return err
  517. }
  518. }
  519. }
  520. return nil
  521. }
  522. func (s *InboundService) AddInboundClient(data *model.Inbound) (bool, error) {
  523. clients, err := s.GetClients(data)
  524. if err != nil {
  525. return false, err
  526. }
  527. var settings map[string]any
  528. err = json.Unmarshal([]byte(data.Settings), &settings)
  529. if err != nil {
  530. return false, err
  531. }
  532. interfaceClients := settings["clients"].([]any)
  533. // Add timestamps for new clients being appended
  534. nowTs := time.Now().Unix() * 1000
  535. for i := range interfaceClients {
  536. if cm, ok := interfaceClients[i].(map[string]any); ok {
  537. if _, ok2 := cm["created_at"]; !ok2 {
  538. cm["created_at"] = nowTs
  539. }
  540. cm["updated_at"] = nowTs
  541. interfaceClients[i] = cm
  542. }
  543. }
  544. existEmail, err := s.checkEmailsExistForClients(clients)
  545. if err != nil {
  546. return false, err
  547. }
  548. if existEmail != "" {
  549. return false, common.NewError("Duplicate email:", existEmail)
  550. }
  551. oldInbound, err := s.GetInbound(data.Id)
  552. if err != nil {
  553. return false, err
  554. }
  555. // Secure client ID
  556. for _, client := range clients {
  557. switch oldInbound.Protocol {
  558. case "trojan":
  559. if client.Password == "" {
  560. return false, common.NewError("empty client ID")
  561. }
  562. case "shadowsocks":
  563. if client.Email == "" {
  564. return false, common.NewError("empty client ID")
  565. }
  566. case "hysteria":
  567. if client.Auth == "" {
  568. return false, common.NewError("empty client ID")
  569. }
  570. default:
  571. if client.ID == "" {
  572. return false, common.NewError("empty client ID")
  573. }
  574. }
  575. }
  576. var oldSettings map[string]any
  577. err = json.Unmarshal([]byte(oldInbound.Settings), &oldSettings)
  578. if err != nil {
  579. return false, err
  580. }
  581. oldClients := oldSettings["clients"].([]any)
  582. oldClients = append(oldClients, interfaceClients...)
  583. oldSettings["clients"] = oldClients
  584. newSettings, err := json.MarshalIndent(oldSettings, "", " ")
  585. if err != nil {
  586. return false, err
  587. }
  588. oldInbound.Settings = string(newSettings)
  589. db := database.GetDB()
  590. tx := db.Begin()
  591. defer func() {
  592. if err != nil {
  593. tx.Rollback()
  594. } else {
  595. tx.Commit()
  596. }
  597. }()
  598. needRestart := false
  599. s.xrayApi.Init(p.GetAPIPort())
  600. for _, client := range clients {
  601. if len(client.Email) > 0 {
  602. s.AddClientStat(tx, data.Id, &client)
  603. if client.Enable {
  604. cipher := ""
  605. if oldInbound.Protocol == "shadowsocks" {
  606. cipher = oldSettings["method"].(string)
  607. }
  608. err1 := s.xrayApi.AddUser(string(oldInbound.Protocol), oldInbound.Tag, map[string]any{
  609. "email": client.Email,
  610. "id": client.ID,
  611. "auth": client.Auth,
  612. "security": client.Security,
  613. "flow": client.Flow,
  614. "password": client.Password,
  615. "cipher": cipher,
  616. })
  617. if err1 == nil {
  618. logger.Debug("Client added by api:", client.Email)
  619. } else {
  620. logger.Debug("Error in adding client by api:", err1)
  621. needRestart = true
  622. }
  623. }
  624. } else {
  625. needRestart = true
  626. }
  627. }
  628. s.xrayApi.Close()
  629. return needRestart, tx.Save(oldInbound).Error
  630. }
  631. func (s *InboundService) DelInboundClient(inboundId int, clientId string) (bool, error) {
  632. oldInbound, err := s.GetInbound(inboundId)
  633. if err != nil {
  634. logger.Error("Load Old Data Error")
  635. return false, err
  636. }
  637. var settings map[string]any
  638. err = json.Unmarshal([]byte(oldInbound.Settings), &settings)
  639. if err != nil {
  640. return false, err
  641. }
  642. email := ""
  643. client_key := "id"
  644. switch oldInbound.Protocol {
  645. case "trojan":
  646. client_key = "password"
  647. case "shadowsocks":
  648. client_key = "email"
  649. case "hysteria":
  650. client_key = "auth"
  651. }
  652. interfaceClients := settings["clients"].([]any)
  653. var newClients []any
  654. needApiDel := false
  655. for _, client := range interfaceClients {
  656. c := client.(map[string]any)
  657. c_id := c[client_key].(string)
  658. if c_id == clientId {
  659. email, _ = c["email"].(string)
  660. needApiDel, _ = c["enable"].(bool)
  661. } else {
  662. newClients = append(newClients, client)
  663. }
  664. }
  665. if len(newClients) == 0 {
  666. return false, common.NewError("no client remained in Inbound")
  667. }
  668. settings["clients"] = newClients
  669. newSettings, err := json.MarshalIndent(settings, "", " ")
  670. if err != nil {
  671. return false, err
  672. }
  673. oldInbound.Settings = string(newSettings)
  674. db := database.GetDB()
  675. err = s.DelClientIPs(db, email)
  676. if err != nil {
  677. logger.Error("Error in delete client IPs")
  678. return false, err
  679. }
  680. needRestart := false
  681. if len(email) > 0 {
  682. notDepleted := true
  683. err = db.Model(xray.ClientTraffic{}).Select("enable").Where("email = ?", email).First(&notDepleted).Error
  684. if err != nil {
  685. logger.Error("Get stats error")
  686. return false, err
  687. }
  688. err = s.DelClientStat(db, email)
  689. if err != nil {
  690. logger.Error("Delete stats Data Error")
  691. return false, err
  692. }
  693. if needApiDel && notDepleted {
  694. s.xrayApi.Init(p.GetAPIPort())
  695. err1 := s.xrayApi.RemoveUser(oldInbound.Tag, email)
  696. if err1 == nil {
  697. logger.Debug("Client deleted by api:", email)
  698. needRestart = false
  699. } else {
  700. if strings.Contains(err1.Error(), fmt.Sprintf("User %s not found.", email)) {
  701. logger.Debug("User is already deleted. Nothing to do more...")
  702. } else {
  703. logger.Debug("Error in deleting client by api:", err1)
  704. needRestart = true
  705. }
  706. }
  707. s.xrayApi.Close()
  708. }
  709. }
  710. return needRestart, db.Save(oldInbound).Error
  711. }
  712. func (s *InboundService) UpdateInboundClient(data *model.Inbound, clientId string) (bool, error) {
  713. // TODO: check if TrafficReset field is updating
  714. clients, err := s.GetClients(data)
  715. if err != nil {
  716. return false, err
  717. }
  718. var settings map[string]any
  719. err = json.Unmarshal([]byte(data.Settings), &settings)
  720. if err != nil {
  721. return false, err
  722. }
  723. interfaceClients := settings["clients"].([]any)
  724. oldInbound, err := s.GetInbound(data.Id)
  725. if err != nil {
  726. return false, err
  727. }
  728. oldClients, err := s.GetClients(oldInbound)
  729. if err != nil {
  730. return false, err
  731. }
  732. oldEmail := ""
  733. newClientId := ""
  734. clientIndex := -1
  735. for index, oldClient := range oldClients {
  736. oldClientId := ""
  737. switch oldInbound.Protocol {
  738. case "trojan":
  739. oldClientId = oldClient.Password
  740. newClientId = clients[0].Password
  741. case "shadowsocks":
  742. oldClientId = oldClient.Email
  743. newClientId = clients[0].Email
  744. case "hysteria":
  745. oldClientId = oldClient.Auth
  746. newClientId = clients[0].Auth
  747. default:
  748. oldClientId = oldClient.ID
  749. newClientId = clients[0].ID
  750. }
  751. if clientId == oldClientId {
  752. oldEmail = oldClient.Email
  753. clientIndex = index
  754. break
  755. }
  756. }
  757. // Validate new client ID
  758. if newClientId == "" || clientIndex == -1 {
  759. return false, common.NewError("empty client ID")
  760. }
  761. if len(clients[0].Email) > 0 && clients[0].Email != oldEmail {
  762. existEmail, err := s.checkEmailsExistForClients(clients)
  763. if err != nil {
  764. return false, err
  765. }
  766. if existEmail != "" {
  767. return false, common.NewError("Duplicate email:", existEmail)
  768. }
  769. }
  770. var oldSettings map[string]any
  771. err = json.Unmarshal([]byte(oldInbound.Settings), &oldSettings)
  772. if err != nil {
  773. return false, err
  774. }
  775. settingsClients := oldSettings["clients"].([]any)
  776. // Preserve created_at and set updated_at for the replacing client
  777. var preservedCreated any
  778. if clientIndex >= 0 && clientIndex < len(settingsClients) {
  779. if oldMap, ok := settingsClients[clientIndex].(map[string]any); ok {
  780. if v, ok2 := oldMap["created_at"]; ok2 {
  781. preservedCreated = v
  782. }
  783. }
  784. }
  785. if len(interfaceClients) > 0 {
  786. if newMap, ok := interfaceClients[0].(map[string]any); ok {
  787. if preservedCreated == nil {
  788. preservedCreated = time.Now().Unix() * 1000
  789. }
  790. newMap["created_at"] = preservedCreated
  791. newMap["updated_at"] = time.Now().Unix() * 1000
  792. interfaceClients[0] = newMap
  793. }
  794. }
  795. settingsClients[clientIndex] = interfaceClients[0]
  796. oldSettings["clients"] = settingsClients
  797. newSettings, err := json.MarshalIndent(oldSettings, "", " ")
  798. if err != nil {
  799. return false, err
  800. }
  801. oldInbound.Settings = string(newSettings)
  802. db := database.GetDB()
  803. tx := db.Begin()
  804. defer func() {
  805. if err != nil {
  806. tx.Rollback()
  807. } else {
  808. tx.Commit()
  809. }
  810. }()
  811. if len(clients[0].Email) > 0 {
  812. if len(oldEmail) > 0 {
  813. err = s.UpdateClientStat(tx, oldEmail, &clients[0])
  814. if err != nil {
  815. return false, err
  816. }
  817. err = s.UpdateClientIPs(tx, oldEmail, clients[0].Email)
  818. if err != nil {
  819. return false, err
  820. }
  821. } else {
  822. s.AddClientStat(tx, data.Id, &clients[0])
  823. }
  824. } else {
  825. err = s.DelClientStat(tx, oldEmail)
  826. if err != nil {
  827. return false, err
  828. }
  829. err = s.DelClientIPs(tx, oldEmail)
  830. if err != nil {
  831. return false, err
  832. }
  833. }
  834. needRestart := false
  835. if len(oldEmail) > 0 {
  836. s.xrayApi.Init(p.GetAPIPort())
  837. if oldClients[clientIndex].Enable {
  838. err1 := s.xrayApi.RemoveUser(oldInbound.Tag, oldEmail)
  839. if err1 == nil {
  840. logger.Debug("Old client deleted by api:", oldEmail)
  841. } else {
  842. if strings.Contains(err1.Error(), fmt.Sprintf("User %s not found.", oldEmail)) {
  843. logger.Debug("User is already deleted. Nothing to do more...")
  844. } else {
  845. logger.Debug("Error in deleting client by api:", err1)
  846. needRestart = true
  847. }
  848. }
  849. }
  850. if clients[0].Enable {
  851. cipher := ""
  852. if oldInbound.Protocol == "shadowsocks" {
  853. cipher = oldSettings["method"].(string)
  854. }
  855. err1 := s.xrayApi.AddUser(string(oldInbound.Protocol), oldInbound.Tag, map[string]any{
  856. "email": clients[0].Email,
  857. "id": clients[0].ID,
  858. "security": clients[0].Security,
  859. "flow": clients[0].Flow,
  860. "auth": clients[0].Auth,
  861. "password": clients[0].Password,
  862. "cipher": cipher,
  863. })
  864. if err1 == nil {
  865. logger.Debug("Client edited by api:", clients[0].Email)
  866. } else {
  867. logger.Debug("Error in adding client by api:", err1)
  868. needRestart = true
  869. }
  870. }
  871. s.xrayApi.Close()
  872. } else {
  873. logger.Debug("Client old email not found")
  874. needRestart = true
  875. }
  876. return needRestart, tx.Save(oldInbound).Error
  877. }
  878. func (s *InboundService) AddTraffic(inboundTraffics []*xray.Traffic, clientTraffics []*xray.ClientTraffic) (error, bool) {
  879. var err error
  880. db := database.GetDB()
  881. tx := db.Begin()
  882. defer func() {
  883. if err != nil {
  884. tx.Rollback()
  885. } else {
  886. tx.Commit()
  887. }
  888. }()
  889. err = s.addInboundTraffic(tx, inboundTraffics)
  890. if err != nil {
  891. return err, false
  892. }
  893. err = s.addClientTraffic(tx, clientTraffics)
  894. if err != nil {
  895. return err, false
  896. }
  897. needRestart0, count, err := s.autoRenewClients(tx)
  898. if err != nil {
  899. logger.Warning("Error in renew clients:", err)
  900. } else if count > 0 {
  901. logger.Debugf("%v clients renewed", count)
  902. }
  903. needRestart1, count, err := s.disableInvalidClients(tx)
  904. if err != nil {
  905. logger.Warning("Error in disabling invalid clients:", err)
  906. } else if count > 0 {
  907. logger.Debugf("%v clients disabled", count)
  908. }
  909. needRestart2, count, err := s.disableInvalidInbounds(tx)
  910. if err != nil {
  911. logger.Warning("Error in disabling invalid inbounds:", err)
  912. } else if count > 0 {
  913. logger.Debugf("%v inbounds disabled", count)
  914. }
  915. return nil, (needRestart0 || needRestart1 || needRestart2)
  916. }
  917. func (s *InboundService) addInboundTraffic(tx *gorm.DB, traffics []*xray.Traffic) error {
  918. if len(traffics) == 0 {
  919. return nil
  920. }
  921. var err error
  922. for _, traffic := range traffics {
  923. if traffic.IsInbound {
  924. err = tx.Model(&model.Inbound{}).Where("tag = ?", traffic.Tag).
  925. Updates(map[string]any{
  926. "up": gorm.Expr("up + ?", traffic.Up),
  927. "down": gorm.Expr("down + ?", traffic.Down),
  928. "all_time": gorm.Expr("COALESCE(all_time, 0) + ?", traffic.Up+traffic.Down),
  929. }).Error
  930. if err != nil {
  931. return err
  932. }
  933. }
  934. }
  935. return nil
  936. }
  937. func (s *InboundService) addClientTraffic(tx *gorm.DB, traffics []*xray.ClientTraffic) (err error) {
  938. if len(traffics) == 0 {
  939. // Empty onlineUsers
  940. if p != nil {
  941. p.SetOnlineClients(make([]string, 0))
  942. }
  943. return nil
  944. }
  945. onlineClients := make([]string, 0)
  946. emails := make([]string, 0, len(traffics))
  947. for _, traffic := range traffics {
  948. emails = append(emails, traffic.Email)
  949. }
  950. dbClientTraffics := make([]*xray.ClientTraffic, 0, len(traffics))
  951. err = tx.Model(xray.ClientTraffic{}).Where("email IN (?)", emails).Find(&dbClientTraffics).Error
  952. if err != nil {
  953. return err
  954. }
  955. // Avoid empty slice error
  956. if len(dbClientTraffics) == 0 {
  957. return nil
  958. }
  959. dbClientTraffics, err = s.adjustTraffics(tx, dbClientTraffics)
  960. if err != nil {
  961. return err
  962. }
  963. for dbTraffic_index := range dbClientTraffics {
  964. for traffic_index := range traffics {
  965. if dbClientTraffics[dbTraffic_index].Email == traffics[traffic_index].Email {
  966. dbClientTraffics[dbTraffic_index].Up += traffics[traffic_index].Up
  967. dbClientTraffics[dbTraffic_index].Down += traffics[traffic_index].Down
  968. dbClientTraffics[dbTraffic_index].AllTime += (traffics[traffic_index].Up + traffics[traffic_index].Down)
  969. // Add user in onlineUsers array on traffic
  970. if traffics[traffic_index].Up+traffics[traffic_index].Down > 0 {
  971. onlineClients = append(onlineClients, traffics[traffic_index].Email)
  972. dbClientTraffics[dbTraffic_index].LastOnline = time.Now().UnixMilli()
  973. }
  974. break
  975. }
  976. }
  977. }
  978. // Set onlineUsers
  979. p.SetOnlineClients(onlineClients)
  980. err = tx.Save(dbClientTraffics).Error
  981. if err != nil {
  982. logger.Warning("AddClientTraffic update data ", err)
  983. }
  984. return nil
  985. }
  986. func (s *InboundService) adjustTraffics(tx *gorm.DB, dbClientTraffics []*xray.ClientTraffic) ([]*xray.ClientTraffic, error) {
  987. inboundIds := make([]int, 0, len(dbClientTraffics))
  988. for _, dbClientTraffic := range dbClientTraffics {
  989. if dbClientTraffic.ExpiryTime < 0 {
  990. inboundIds = append(inboundIds, dbClientTraffic.InboundId)
  991. }
  992. }
  993. if len(inboundIds) > 0 {
  994. var inbounds []*model.Inbound
  995. err := tx.Model(model.Inbound{}).Where("id IN (?)", inboundIds).Find(&inbounds).Error
  996. if err != nil {
  997. return nil, err
  998. }
  999. for inbound_index := range inbounds {
  1000. settings := map[string]any{}
  1001. json.Unmarshal([]byte(inbounds[inbound_index].Settings), &settings)
  1002. clients, ok := settings["clients"].([]any)
  1003. if ok {
  1004. var newClients []any
  1005. for client_index := range clients {
  1006. c := clients[client_index].(map[string]any)
  1007. for traffic_index := range dbClientTraffics {
  1008. if dbClientTraffics[traffic_index].ExpiryTime < 0 && c["email"] == dbClientTraffics[traffic_index].Email {
  1009. oldExpiryTime := c["expiryTime"].(float64)
  1010. newExpiryTime := (time.Now().Unix() * 1000) - int64(oldExpiryTime)
  1011. c["expiryTime"] = newExpiryTime
  1012. c["updated_at"] = time.Now().Unix() * 1000
  1013. dbClientTraffics[traffic_index].ExpiryTime = newExpiryTime
  1014. break
  1015. }
  1016. }
  1017. // Backfill created_at and updated_at
  1018. if _, ok := c["created_at"]; !ok {
  1019. c["created_at"] = time.Now().Unix() * 1000
  1020. }
  1021. c["updated_at"] = time.Now().Unix() * 1000
  1022. newClients = append(newClients, any(c))
  1023. }
  1024. settings["clients"] = newClients
  1025. modifiedSettings, err := json.MarshalIndent(settings, "", " ")
  1026. if err != nil {
  1027. return nil, err
  1028. }
  1029. inbounds[inbound_index].Settings = string(modifiedSettings)
  1030. }
  1031. }
  1032. err = tx.Save(inbounds).Error
  1033. if err != nil {
  1034. logger.Warning("AddClientTraffic update inbounds ", err)
  1035. logger.Error(inbounds)
  1036. }
  1037. }
  1038. return dbClientTraffics, nil
  1039. }
  1040. func (s *InboundService) autoRenewClients(tx *gorm.DB) (bool, int64, error) {
  1041. // check for time expired
  1042. var traffics []*xray.ClientTraffic
  1043. now := time.Now().Unix() * 1000
  1044. var err, err1 error
  1045. err = tx.Model(xray.ClientTraffic{}).Where("reset > 0 and expiry_time > 0 and expiry_time <= ?", now).Find(&traffics).Error
  1046. if err != nil {
  1047. return false, 0, err
  1048. }
  1049. // return if there is no client to renew
  1050. if len(traffics) == 0 {
  1051. return false, 0, nil
  1052. }
  1053. var inbound_ids []int
  1054. var inbounds []*model.Inbound
  1055. needRestart := false
  1056. var clientsToAdd []struct {
  1057. protocol string
  1058. tag string
  1059. client map[string]any
  1060. }
  1061. for _, traffic := range traffics {
  1062. inbound_ids = append(inbound_ids, traffic.InboundId)
  1063. }
  1064. err = tx.Model(model.Inbound{}).Where("id IN ?", inbound_ids).Find(&inbounds).Error
  1065. if err != nil {
  1066. return false, 0, err
  1067. }
  1068. for inbound_index := range inbounds {
  1069. settings := map[string]any{}
  1070. json.Unmarshal([]byte(inbounds[inbound_index].Settings), &settings)
  1071. clients := settings["clients"].([]any)
  1072. for client_index := range clients {
  1073. c := clients[client_index].(map[string]any)
  1074. for traffic_index, traffic := range traffics {
  1075. if traffic.Email == c["email"].(string) {
  1076. newExpiryTime := traffic.ExpiryTime
  1077. for newExpiryTime < now {
  1078. newExpiryTime += (int64(traffic.Reset) * 86400000)
  1079. }
  1080. c["expiryTime"] = newExpiryTime
  1081. traffics[traffic_index].ExpiryTime = newExpiryTime
  1082. traffics[traffic_index].Down = 0
  1083. traffics[traffic_index].Up = 0
  1084. if !traffic.Enable {
  1085. traffics[traffic_index].Enable = true
  1086. clientsToAdd = append(clientsToAdd,
  1087. struct {
  1088. protocol string
  1089. tag string
  1090. client map[string]any
  1091. }{
  1092. protocol: string(inbounds[inbound_index].Protocol),
  1093. tag: inbounds[inbound_index].Tag,
  1094. client: c,
  1095. })
  1096. }
  1097. clients[client_index] = any(c)
  1098. break
  1099. }
  1100. }
  1101. }
  1102. settings["clients"] = clients
  1103. newSettings, err := json.MarshalIndent(settings, "", " ")
  1104. if err != nil {
  1105. return false, 0, err
  1106. }
  1107. inbounds[inbound_index].Settings = string(newSettings)
  1108. }
  1109. err = tx.Save(inbounds).Error
  1110. if err != nil {
  1111. return false, 0, err
  1112. }
  1113. err = tx.Save(traffics).Error
  1114. if err != nil {
  1115. return false, 0, err
  1116. }
  1117. if p != nil {
  1118. err1 = s.xrayApi.Init(p.GetAPIPort())
  1119. if err1 != nil {
  1120. return true, int64(len(traffics)), nil
  1121. }
  1122. for _, clientToAdd := range clientsToAdd {
  1123. err1 = s.xrayApi.AddUser(clientToAdd.protocol, clientToAdd.tag, clientToAdd.client)
  1124. if err1 != nil {
  1125. needRestart = true
  1126. }
  1127. }
  1128. s.xrayApi.Close()
  1129. }
  1130. return needRestart, int64(len(traffics)), nil
  1131. }
  1132. func (s *InboundService) disableInvalidInbounds(tx *gorm.DB) (bool, int64, error) {
  1133. now := time.Now().Unix() * 1000
  1134. needRestart := false
  1135. if p != nil {
  1136. var tags []string
  1137. err := tx.Table("inbounds").
  1138. Select("inbounds.tag").
  1139. Where("((total > 0 and up + down >= total) or (expiry_time > 0 and expiry_time <= ?)) and enable = ?", now, true).
  1140. Scan(&tags).Error
  1141. if err != nil {
  1142. return false, 0, err
  1143. }
  1144. s.xrayApi.Init(p.GetAPIPort())
  1145. for _, tag := range tags {
  1146. err1 := s.xrayApi.DelInbound(tag)
  1147. if err1 == nil {
  1148. logger.Debug("Inbound disabled by api:", tag)
  1149. } else {
  1150. logger.Debug("Error in disabling inbound by api:", err1)
  1151. needRestart = true
  1152. }
  1153. }
  1154. s.xrayApi.Close()
  1155. }
  1156. result := tx.Model(model.Inbound{}).
  1157. Where("((total > 0 and up + down >= total) or (expiry_time > 0 and expiry_time <= ?)) and enable = ?", now, true).
  1158. Update("enable", false)
  1159. err := result.Error
  1160. count := result.RowsAffected
  1161. return needRestart, count, err
  1162. }
  1163. func (s *InboundService) disableInvalidClients(tx *gorm.DB) (bool, int64, error) {
  1164. now := time.Now().Unix() * 1000
  1165. needRestart := false
  1166. if p != nil {
  1167. var results []struct {
  1168. Tag string
  1169. Email string
  1170. }
  1171. err := tx.Table("inbounds").
  1172. Select("inbounds.tag, client_traffics.email").
  1173. Joins("JOIN client_traffics ON inbounds.id = client_traffics.inbound_id").
  1174. 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).
  1175. Scan(&results).Error
  1176. if err != nil {
  1177. return false, 0, err
  1178. }
  1179. s.xrayApi.Init(p.GetAPIPort())
  1180. for _, result := range results {
  1181. err1 := s.xrayApi.RemoveUser(result.Tag, result.Email)
  1182. if err1 == nil {
  1183. logger.Debug("Client disabled by api:", result.Email)
  1184. } else {
  1185. if strings.Contains(err1.Error(), fmt.Sprintf("User %s not found.", result.Email)) {
  1186. logger.Debug("User is already disabled. Nothing to do more...")
  1187. } else {
  1188. if strings.Contains(err1.Error(), fmt.Sprintf("User %s not found.", result.Email)) {
  1189. logger.Debug("User is already disabled. Nothing to do more...")
  1190. } else {
  1191. logger.Debug("Error in disabling client by api:", err1)
  1192. needRestart = true
  1193. }
  1194. }
  1195. }
  1196. }
  1197. s.xrayApi.Close()
  1198. }
  1199. result := tx.Model(xray.ClientTraffic{}).
  1200. Where("((total > 0 and up + down >= total) or (expiry_time > 0 and expiry_time <= ?)) and enable = ?", now, true).
  1201. Update("enable", false)
  1202. err := result.Error
  1203. count := result.RowsAffected
  1204. return needRestart, count, err
  1205. }
  1206. func (s *InboundService) GetInboundTags() (string, error) {
  1207. db := database.GetDB()
  1208. var inboundTags []string
  1209. err := db.Model(model.Inbound{}).Select("tag").Find(&inboundTags).Error
  1210. if err != nil && err != gorm.ErrRecordNotFound {
  1211. return "", err
  1212. }
  1213. tags, _ := json.Marshal(inboundTags)
  1214. return string(tags), nil
  1215. }
  1216. func (s *InboundService) MigrationRemoveOrphanedTraffics() {
  1217. db := database.GetDB()
  1218. db.Exec(`
  1219. DELETE FROM client_traffics
  1220. WHERE email NOT IN (
  1221. SELECT JSON_EXTRACT(client.value, '$.email')
  1222. FROM inbounds,
  1223. JSON_EACH(JSON_EXTRACT(inbounds.settings, '$.clients')) AS client
  1224. )
  1225. `)
  1226. }
  1227. func (s *InboundService) AddClientStat(tx *gorm.DB, inboundId int, client *model.Client) error {
  1228. clientTraffic := xray.ClientTraffic{}
  1229. clientTraffic.InboundId = inboundId
  1230. clientTraffic.Email = client.Email
  1231. clientTraffic.Total = client.TotalGB
  1232. clientTraffic.ExpiryTime = client.ExpiryTime
  1233. clientTraffic.Enable = client.Enable
  1234. clientTraffic.Up = 0
  1235. clientTraffic.Down = 0
  1236. clientTraffic.Reset = client.Reset
  1237. result := tx.Create(&clientTraffic)
  1238. err := result.Error
  1239. return err
  1240. }
  1241. func (s *InboundService) UpdateClientStat(tx *gorm.DB, email string, client *model.Client) error {
  1242. result := tx.Model(xray.ClientTraffic{}).
  1243. Where("email = ?", email).
  1244. Updates(map[string]any{
  1245. "enable": client.Enable,
  1246. "email": client.Email,
  1247. "total": client.TotalGB,
  1248. "expiry_time": client.ExpiryTime,
  1249. "reset": client.Reset,
  1250. })
  1251. err := result.Error
  1252. return err
  1253. }
  1254. func (s *InboundService) UpdateClientIPs(tx *gorm.DB, oldEmail string, newEmail string) error {
  1255. return tx.Model(model.InboundClientIps{}).Where("client_email = ?", oldEmail).Update("client_email", newEmail).Error
  1256. }
  1257. func (s *InboundService) DelClientStat(tx *gorm.DB, email string) error {
  1258. return tx.Where("email = ?", email).Delete(xray.ClientTraffic{}).Error
  1259. }
  1260. func (s *InboundService) DelClientIPs(tx *gorm.DB, email string) error {
  1261. return tx.Where("client_email = ?", email).Delete(model.InboundClientIps{}).Error
  1262. }
  1263. func (s *InboundService) GetClientInboundByTrafficID(trafficId int) (traffic *xray.ClientTraffic, inbound *model.Inbound, err error) {
  1264. db := database.GetDB()
  1265. var traffics []*xray.ClientTraffic
  1266. err = db.Model(xray.ClientTraffic{}).Where("id = ?", trafficId).Find(&traffics).Error
  1267. if err != nil {
  1268. logger.Warningf("Error retrieving ClientTraffic with trafficId %d: %v", trafficId, err)
  1269. return nil, nil, err
  1270. }
  1271. if len(traffics) > 0 {
  1272. inbound, err = s.GetInbound(traffics[0].InboundId)
  1273. return traffics[0], inbound, err
  1274. }
  1275. return nil, nil, nil
  1276. }
  1277. func (s *InboundService) GetClientInboundByEmail(email string) (traffic *xray.ClientTraffic, inbound *model.Inbound, err error) {
  1278. db := database.GetDB()
  1279. var traffics []*xray.ClientTraffic
  1280. err = db.Model(xray.ClientTraffic{}).Where("email = ?", email).Find(&traffics).Error
  1281. if err != nil {
  1282. logger.Warningf("Error retrieving ClientTraffic with email %s: %v", email, err)
  1283. return nil, nil, err
  1284. }
  1285. if len(traffics) > 0 {
  1286. inbound, err = s.GetInbound(traffics[0].InboundId)
  1287. return traffics[0], inbound, err
  1288. }
  1289. return nil, nil, nil
  1290. }
  1291. func (s *InboundService) GetClientByEmail(clientEmail string) (*xray.ClientTraffic, *model.Client, error) {
  1292. traffic, inbound, err := s.GetClientInboundByEmail(clientEmail)
  1293. if err != nil {
  1294. return nil, nil, err
  1295. }
  1296. if inbound == nil {
  1297. return nil, nil, common.NewError("Inbound Not Found For Email:", clientEmail)
  1298. }
  1299. clients, err := s.GetClients(inbound)
  1300. if err != nil {
  1301. return nil, nil, err
  1302. }
  1303. for _, client := range clients {
  1304. if client.Email == clientEmail {
  1305. return traffic, &client, nil
  1306. }
  1307. }
  1308. return nil, nil, common.NewError("Client Not Found In Inbound For Email:", clientEmail)
  1309. }
  1310. func (s *InboundService) SetClientTelegramUserID(trafficId int, tgId int64) (bool, error) {
  1311. traffic, inbound, err := s.GetClientInboundByTrafficID(trafficId)
  1312. if err != nil {
  1313. return false, err
  1314. }
  1315. if inbound == nil {
  1316. return false, common.NewError("Inbound Not Found For Traffic ID:", trafficId)
  1317. }
  1318. clientEmail := traffic.Email
  1319. oldClients, err := s.GetClients(inbound)
  1320. if err != nil {
  1321. return false, err
  1322. }
  1323. clientId := ""
  1324. for _, oldClient := range oldClients {
  1325. if oldClient.Email == clientEmail {
  1326. switch inbound.Protocol {
  1327. case "trojan":
  1328. clientId = oldClient.Password
  1329. case "shadowsocks":
  1330. clientId = oldClient.Email
  1331. default:
  1332. clientId = oldClient.ID
  1333. }
  1334. break
  1335. }
  1336. }
  1337. if len(clientId) == 0 {
  1338. return false, common.NewError("Client Not Found For Email:", clientEmail)
  1339. }
  1340. var settings map[string]any
  1341. err = json.Unmarshal([]byte(inbound.Settings), &settings)
  1342. if err != nil {
  1343. return false, err
  1344. }
  1345. clients := settings["clients"].([]any)
  1346. var newClients []any
  1347. for client_index := range clients {
  1348. c := clients[client_index].(map[string]any)
  1349. if c["email"] == clientEmail {
  1350. c["tgId"] = tgId
  1351. c["updated_at"] = time.Now().Unix() * 1000
  1352. newClients = append(newClients, any(c))
  1353. }
  1354. }
  1355. settings["clients"] = newClients
  1356. modifiedSettings, err := json.MarshalIndent(settings, "", " ")
  1357. if err != nil {
  1358. return false, err
  1359. }
  1360. inbound.Settings = string(modifiedSettings)
  1361. needRestart, err := s.UpdateInboundClient(inbound, clientId)
  1362. return needRestart, err
  1363. }
  1364. func (s *InboundService) checkIsEnabledByEmail(clientEmail string) (bool, error) {
  1365. _, inbound, err := s.GetClientInboundByEmail(clientEmail)
  1366. if err != nil {
  1367. return false, err
  1368. }
  1369. if inbound == nil {
  1370. return false, common.NewError("Inbound Not Found For Email:", clientEmail)
  1371. }
  1372. clients, err := s.GetClients(inbound)
  1373. if err != nil {
  1374. return false, err
  1375. }
  1376. isEnable := false
  1377. for _, client := range clients {
  1378. if client.Email == clientEmail {
  1379. isEnable = client.Enable
  1380. break
  1381. }
  1382. }
  1383. return isEnable, err
  1384. }
  1385. func (s *InboundService) ToggleClientEnableByEmail(clientEmail string) (bool, bool, error) {
  1386. _, inbound, err := s.GetClientInboundByEmail(clientEmail)
  1387. if err != nil {
  1388. return false, false, err
  1389. }
  1390. if inbound == nil {
  1391. return false, false, common.NewError("Inbound Not Found For Email:", clientEmail)
  1392. }
  1393. oldClients, err := s.GetClients(inbound)
  1394. if err != nil {
  1395. return false, false, err
  1396. }
  1397. clientId := ""
  1398. clientOldEnabled := false
  1399. for _, oldClient := range oldClients {
  1400. if oldClient.Email == clientEmail {
  1401. switch inbound.Protocol {
  1402. case "trojan":
  1403. clientId = oldClient.Password
  1404. case "shadowsocks":
  1405. clientId = oldClient.Email
  1406. default:
  1407. clientId = oldClient.ID
  1408. }
  1409. clientOldEnabled = oldClient.Enable
  1410. break
  1411. }
  1412. }
  1413. if len(clientId) == 0 {
  1414. return false, false, common.NewError("Client Not Found For Email:", clientEmail)
  1415. }
  1416. var settings map[string]any
  1417. err = json.Unmarshal([]byte(inbound.Settings), &settings)
  1418. if err != nil {
  1419. return false, false, err
  1420. }
  1421. clients := settings["clients"].([]any)
  1422. var newClients []any
  1423. for client_index := range clients {
  1424. c := clients[client_index].(map[string]any)
  1425. if c["email"] == clientEmail {
  1426. c["enable"] = !clientOldEnabled
  1427. c["updated_at"] = time.Now().Unix() * 1000
  1428. newClients = append(newClients, any(c))
  1429. }
  1430. }
  1431. settings["clients"] = newClients
  1432. modifiedSettings, err := json.MarshalIndent(settings, "", " ")
  1433. if err != nil {
  1434. return false, false, err
  1435. }
  1436. inbound.Settings = string(modifiedSettings)
  1437. needRestart, err := s.UpdateInboundClient(inbound, clientId)
  1438. if err != nil {
  1439. return false, needRestart, err
  1440. }
  1441. return !clientOldEnabled, needRestart, nil
  1442. }
  1443. // SetClientEnableByEmail sets client enable state to desired value; returns (changed, needRestart, error)
  1444. func (s *InboundService) SetClientEnableByEmail(clientEmail string, enable bool) (bool, bool, error) {
  1445. current, err := s.checkIsEnabledByEmail(clientEmail)
  1446. if err != nil {
  1447. return false, false, err
  1448. }
  1449. if current == enable {
  1450. return false, false, nil
  1451. }
  1452. newEnabled, needRestart, err := s.ToggleClientEnableByEmail(clientEmail)
  1453. if err != nil {
  1454. return false, needRestart, err
  1455. }
  1456. return newEnabled == enable, needRestart, nil
  1457. }
  1458. func (s *InboundService) ResetClientIpLimitByEmail(clientEmail string, count int) (bool, error) {
  1459. _, inbound, err := s.GetClientInboundByEmail(clientEmail)
  1460. if err != nil {
  1461. return false, err
  1462. }
  1463. if inbound == nil {
  1464. return false, common.NewError("Inbound Not Found For Email:", clientEmail)
  1465. }
  1466. oldClients, err := s.GetClients(inbound)
  1467. if err != nil {
  1468. return false, err
  1469. }
  1470. clientId := ""
  1471. for _, oldClient := range oldClients {
  1472. if oldClient.Email == clientEmail {
  1473. switch inbound.Protocol {
  1474. case "trojan":
  1475. clientId = oldClient.Password
  1476. case "shadowsocks":
  1477. clientId = oldClient.Email
  1478. default:
  1479. clientId = oldClient.ID
  1480. }
  1481. break
  1482. }
  1483. }
  1484. if len(clientId) == 0 {
  1485. return false, common.NewError("Client Not Found For Email:", clientEmail)
  1486. }
  1487. var settings map[string]any
  1488. err = json.Unmarshal([]byte(inbound.Settings), &settings)
  1489. if err != nil {
  1490. return false, err
  1491. }
  1492. clients := settings["clients"].([]any)
  1493. var newClients []any
  1494. for client_index := range clients {
  1495. c := clients[client_index].(map[string]any)
  1496. if c["email"] == clientEmail {
  1497. c["limitIp"] = count
  1498. c["updated_at"] = time.Now().Unix() * 1000
  1499. newClients = append(newClients, any(c))
  1500. }
  1501. }
  1502. settings["clients"] = newClients
  1503. modifiedSettings, err := json.MarshalIndent(settings, "", " ")
  1504. if err != nil {
  1505. return false, err
  1506. }
  1507. inbound.Settings = string(modifiedSettings)
  1508. needRestart, err := s.UpdateInboundClient(inbound, clientId)
  1509. return needRestart, err
  1510. }
  1511. func (s *InboundService) ResetClientExpiryTimeByEmail(clientEmail string, expiry_time int64) (bool, error) {
  1512. _, inbound, err := s.GetClientInboundByEmail(clientEmail)
  1513. if err != nil {
  1514. return false, err
  1515. }
  1516. if inbound == nil {
  1517. return false, common.NewError("Inbound Not Found For Email:", clientEmail)
  1518. }
  1519. oldClients, err := s.GetClients(inbound)
  1520. if err != nil {
  1521. return false, err
  1522. }
  1523. clientId := ""
  1524. for _, oldClient := range oldClients {
  1525. if oldClient.Email == clientEmail {
  1526. switch inbound.Protocol {
  1527. case "trojan":
  1528. clientId = oldClient.Password
  1529. case "shadowsocks":
  1530. clientId = oldClient.Email
  1531. default:
  1532. clientId = oldClient.ID
  1533. }
  1534. break
  1535. }
  1536. }
  1537. if len(clientId) == 0 {
  1538. return false, common.NewError("Client Not Found For Email:", clientEmail)
  1539. }
  1540. var settings map[string]any
  1541. err = json.Unmarshal([]byte(inbound.Settings), &settings)
  1542. if err != nil {
  1543. return false, err
  1544. }
  1545. clients := settings["clients"].([]any)
  1546. var newClients []any
  1547. for client_index := range clients {
  1548. c := clients[client_index].(map[string]any)
  1549. if c["email"] == clientEmail {
  1550. c["expiryTime"] = expiry_time
  1551. c["updated_at"] = time.Now().Unix() * 1000
  1552. newClients = append(newClients, any(c))
  1553. }
  1554. }
  1555. settings["clients"] = newClients
  1556. modifiedSettings, err := json.MarshalIndent(settings, "", " ")
  1557. if err != nil {
  1558. return false, err
  1559. }
  1560. inbound.Settings = string(modifiedSettings)
  1561. needRestart, err := s.UpdateInboundClient(inbound, clientId)
  1562. return needRestart, err
  1563. }
  1564. func (s *InboundService) ResetClientTrafficLimitByEmail(clientEmail string, totalGB int) (bool, error) {
  1565. if totalGB < 0 {
  1566. return false, common.NewError("totalGB must be >= 0")
  1567. }
  1568. _, inbound, err := s.GetClientInboundByEmail(clientEmail)
  1569. if err != nil {
  1570. return false, err
  1571. }
  1572. if inbound == nil {
  1573. return false, common.NewError("Inbound Not Found For Email:", clientEmail)
  1574. }
  1575. oldClients, err := s.GetClients(inbound)
  1576. if err != nil {
  1577. return false, err
  1578. }
  1579. clientId := ""
  1580. for _, oldClient := range oldClients {
  1581. if oldClient.Email == clientEmail {
  1582. switch inbound.Protocol {
  1583. case "trojan":
  1584. clientId = oldClient.Password
  1585. case "shadowsocks":
  1586. clientId = oldClient.Email
  1587. default:
  1588. clientId = oldClient.ID
  1589. }
  1590. break
  1591. }
  1592. }
  1593. if len(clientId) == 0 {
  1594. return false, common.NewError("Client Not Found For Email:", clientEmail)
  1595. }
  1596. var settings map[string]any
  1597. err = json.Unmarshal([]byte(inbound.Settings), &settings)
  1598. if err != nil {
  1599. return false, err
  1600. }
  1601. clients := settings["clients"].([]any)
  1602. var newClients []any
  1603. for client_index := range clients {
  1604. c := clients[client_index].(map[string]any)
  1605. if c["email"] == clientEmail {
  1606. c["totalGB"] = totalGB * 1024 * 1024 * 1024
  1607. c["updated_at"] = time.Now().Unix() * 1000
  1608. newClients = append(newClients, any(c))
  1609. }
  1610. }
  1611. settings["clients"] = newClients
  1612. modifiedSettings, err := json.MarshalIndent(settings, "", " ")
  1613. if err != nil {
  1614. return false, err
  1615. }
  1616. inbound.Settings = string(modifiedSettings)
  1617. needRestart, err := s.UpdateInboundClient(inbound, clientId)
  1618. return needRestart, err
  1619. }
  1620. func (s *InboundService) ResetClientTrafficByEmail(clientEmail string) error {
  1621. db := database.GetDB()
  1622. // Reset traffic stats in ClientTraffic table
  1623. result := db.Model(xray.ClientTraffic{}).
  1624. Where("email = ?", clientEmail).
  1625. Updates(map[string]any{"enable": true, "up": 0, "down": 0})
  1626. err := result.Error
  1627. if err != nil {
  1628. return err
  1629. }
  1630. return nil
  1631. }
  1632. func (s *InboundService) ResetClientTraffic(id int, clientEmail string) (bool, error) {
  1633. needRestart := false
  1634. traffic, err := s.GetClientTrafficByEmail(clientEmail)
  1635. if err != nil {
  1636. return false, err
  1637. }
  1638. if !traffic.Enable {
  1639. inbound, err := s.GetInbound(id)
  1640. if err != nil {
  1641. return false, err
  1642. }
  1643. clients, err := s.GetClients(inbound)
  1644. if err != nil {
  1645. return false, err
  1646. }
  1647. for _, client := range clients {
  1648. if client.Email == clientEmail && client.Enable {
  1649. s.xrayApi.Init(p.GetAPIPort())
  1650. cipher := ""
  1651. if string(inbound.Protocol) == "shadowsocks" {
  1652. var oldSettings map[string]any
  1653. err = json.Unmarshal([]byte(inbound.Settings), &oldSettings)
  1654. if err != nil {
  1655. return false, err
  1656. }
  1657. cipher = oldSettings["method"].(string)
  1658. }
  1659. err1 := s.xrayApi.AddUser(string(inbound.Protocol), inbound.Tag, map[string]any{
  1660. "email": client.Email,
  1661. "id": client.ID,
  1662. "auth": client.Auth,
  1663. "security": client.Security,
  1664. "flow": client.Flow,
  1665. "password": client.Password,
  1666. "cipher": cipher,
  1667. })
  1668. if err1 == nil {
  1669. logger.Debug("Client enabled due to reset traffic:", clientEmail)
  1670. } else {
  1671. logger.Debug("Error in enabling client by api:", err1)
  1672. needRestart = true
  1673. }
  1674. s.xrayApi.Close()
  1675. break
  1676. }
  1677. }
  1678. }
  1679. traffic.Up = 0
  1680. traffic.Down = 0
  1681. traffic.Enable = true
  1682. db := database.GetDB()
  1683. err = db.Save(traffic).Error
  1684. if err != nil {
  1685. return false, err
  1686. }
  1687. return needRestart, nil
  1688. }
  1689. func (s *InboundService) ResetAllClientTraffics(id int) error {
  1690. db := database.GetDB()
  1691. now := time.Now().Unix() * 1000
  1692. return db.Transaction(func(tx *gorm.DB) error {
  1693. whereText := "inbound_id "
  1694. if id == -1 {
  1695. whereText += " > ?"
  1696. } else {
  1697. whereText += " = ?"
  1698. }
  1699. // Reset client traffics
  1700. result := tx.Model(xray.ClientTraffic{}).
  1701. Where(whereText, id).
  1702. Updates(map[string]any{"enable": true, "up": 0, "down": 0})
  1703. if result.Error != nil {
  1704. return result.Error
  1705. }
  1706. // Update lastTrafficResetTime for the inbound(s)
  1707. inboundWhereText := "id "
  1708. if id == -1 {
  1709. inboundWhereText += " > ?"
  1710. } else {
  1711. inboundWhereText += " = ?"
  1712. }
  1713. result = tx.Model(model.Inbound{}).
  1714. Where(inboundWhereText, id).
  1715. Update("last_traffic_reset_time", now)
  1716. return result.Error
  1717. })
  1718. }
  1719. func (s *InboundService) ResetAllTraffics() error {
  1720. db := database.GetDB()
  1721. result := db.Model(model.Inbound{}).
  1722. Where("user_id > ?", 0).
  1723. Updates(map[string]any{"up": 0, "down": 0})
  1724. err := result.Error
  1725. return err
  1726. }
  1727. func (s *InboundService) ResetInboundTraffic(id int) error {
  1728. db := database.GetDB()
  1729. result := db.Model(model.Inbound{}).
  1730. Where("id = ?", id).
  1731. Updates(map[string]any{"up": 0, "down": 0})
  1732. return result.Error
  1733. }
  1734. func (s *InboundService) DelDepletedClients(id int) (err error) {
  1735. db := database.GetDB()
  1736. tx := db.Begin()
  1737. defer func() {
  1738. if err == nil {
  1739. tx.Commit()
  1740. } else {
  1741. tx.Rollback()
  1742. }
  1743. }()
  1744. whereText := "reset = 0 and inbound_id "
  1745. if id < 0 {
  1746. whereText += "> ?"
  1747. } else {
  1748. whereText += "= ?"
  1749. }
  1750. // Only consider truly depleted clients: expired OR traffic exhausted
  1751. now := time.Now().Unix() * 1000
  1752. depletedClients := []xray.ClientTraffic{}
  1753. err = db.Model(xray.ClientTraffic{}).
  1754. Where(whereText+" and ((total > 0 and up + down >= total) or (expiry_time > 0 and expiry_time <= ?))", id, now).
  1755. Select("inbound_id, GROUP_CONCAT(email) as email").
  1756. Group("inbound_id").
  1757. Find(&depletedClients).Error
  1758. if err != nil {
  1759. return err
  1760. }
  1761. for _, depletedClient := range depletedClients {
  1762. emails := strings.Split(depletedClient.Email, ",")
  1763. oldInbound, err := s.GetInbound(depletedClient.InboundId)
  1764. if err != nil {
  1765. return err
  1766. }
  1767. var oldSettings map[string]any
  1768. err = json.Unmarshal([]byte(oldInbound.Settings), &oldSettings)
  1769. if err != nil {
  1770. return err
  1771. }
  1772. oldClients := oldSettings["clients"].([]any)
  1773. var newClients []any
  1774. for _, client := range oldClients {
  1775. deplete := false
  1776. c := client.(map[string]any)
  1777. for _, email := range emails {
  1778. if email == c["email"].(string) {
  1779. deplete = true
  1780. break
  1781. }
  1782. }
  1783. if !deplete {
  1784. newClients = append(newClients, client)
  1785. }
  1786. }
  1787. if len(newClients) > 0 {
  1788. oldSettings["clients"] = newClients
  1789. newSettings, err := json.MarshalIndent(oldSettings, "", " ")
  1790. if err != nil {
  1791. return err
  1792. }
  1793. oldInbound.Settings = string(newSettings)
  1794. err = tx.Save(oldInbound).Error
  1795. if err != nil {
  1796. return err
  1797. }
  1798. } else {
  1799. // Delete inbound if no client remains
  1800. s.DelInbound(depletedClient.InboundId)
  1801. }
  1802. }
  1803. // Delete stats only for truly depleted clients
  1804. err = tx.Where(whereText+" and ((total > 0 and up + down >= total) or (expiry_time > 0 and expiry_time <= ?))", id, now).Delete(xray.ClientTraffic{}).Error
  1805. if err != nil {
  1806. return err
  1807. }
  1808. return nil
  1809. }
  1810. func (s *InboundService) GetClientTrafficTgBot(tgId int64) ([]*xray.ClientTraffic, error) {
  1811. db := database.GetDB()
  1812. var inbounds []*model.Inbound
  1813. // Retrieve inbounds where settings contain the given tgId
  1814. err := db.Model(model.Inbound{}).Where("settings LIKE ?", fmt.Sprintf(`%%"tgId": %d%%`, tgId)).Find(&inbounds).Error
  1815. if err != nil && err != gorm.ErrRecordNotFound {
  1816. logger.Errorf("Error retrieving inbounds with tgId %d: %v", tgId, err)
  1817. return nil, err
  1818. }
  1819. var emails []string
  1820. for _, inbound := range inbounds {
  1821. clients, err := s.GetClients(inbound)
  1822. if err != nil {
  1823. logger.Errorf("Error retrieving clients for inbound %d: %v", inbound.Id, err)
  1824. continue
  1825. }
  1826. for _, client := range clients {
  1827. if client.TgID == tgId {
  1828. emails = append(emails, client.Email)
  1829. }
  1830. }
  1831. }
  1832. var traffics []*xray.ClientTraffic
  1833. err = db.Model(xray.ClientTraffic{}).Where("email IN ?", emails).Find(&traffics).Error
  1834. if err != nil {
  1835. if err == gorm.ErrRecordNotFound {
  1836. logger.Warning("No ClientTraffic records found for emails:", emails)
  1837. return nil, nil
  1838. }
  1839. logger.Errorf("Error retrieving ClientTraffic for emails %v: %v", emails, err)
  1840. return nil, err
  1841. }
  1842. // Populate UUID and other client data for each traffic record
  1843. for i := range traffics {
  1844. if ct, client, e := s.GetClientByEmail(traffics[i].Email); e == nil && ct != nil && client != nil {
  1845. traffics[i].Enable = client.Enable
  1846. traffics[i].UUID = client.ID
  1847. traffics[i].SubId = client.SubID
  1848. }
  1849. }
  1850. return traffics, nil
  1851. }
  1852. func (s *InboundService) GetClientTrafficByEmail(email string) (traffic *xray.ClientTraffic, err error) {
  1853. // Prefer retrieving along with client to reflect actual enabled state from inbound settings
  1854. t, client, err := s.GetClientByEmail(email)
  1855. if err != nil {
  1856. logger.Warningf("Error retrieving ClientTraffic with email %s: %v", email, err)
  1857. return nil, err
  1858. }
  1859. if t != nil && client != nil {
  1860. t.UUID = client.ID
  1861. t.SubId = client.SubID
  1862. return t, nil
  1863. }
  1864. return nil, nil
  1865. }
  1866. func (s *InboundService) UpdateClientTrafficByEmail(email string, upload int64, download int64) error {
  1867. db := database.GetDB()
  1868. result := db.Model(xray.ClientTraffic{}).
  1869. Where("email = ?", email).
  1870. Updates(map[string]any{"up": upload, "down": download})
  1871. err := result.Error
  1872. if err != nil {
  1873. logger.Warningf("Error updating ClientTraffic with email %s: %v", email, err)
  1874. return err
  1875. }
  1876. return nil
  1877. }
  1878. func (s *InboundService) GetClientTrafficByID(id string) ([]xray.ClientTraffic, error) {
  1879. db := database.GetDB()
  1880. var traffics []xray.ClientTraffic
  1881. err := db.Model(xray.ClientTraffic{}).Where(`email IN(
  1882. SELECT JSON_EXTRACT(client.value, '$.email') as email
  1883. FROM inbounds,
  1884. JSON_EACH(JSON_EXTRACT(inbounds.settings, '$.clients')) AS client
  1885. WHERE
  1886. JSON_EXTRACT(client.value, '$.id') in (?)
  1887. )`, id).Find(&traffics).Error
  1888. if err != nil {
  1889. logger.Debug(err)
  1890. return nil, err
  1891. }
  1892. // Reconcile enable flag with client settings per email to avoid stale DB value
  1893. for i := range traffics {
  1894. if ct, client, e := s.GetClientByEmail(traffics[i].Email); e == nil && ct != nil && client != nil {
  1895. traffics[i].Enable = client.Enable
  1896. traffics[i].UUID = client.ID
  1897. traffics[i].SubId = client.SubID
  1898. }
  1899. }
  1900. return traffics, err
  1901. }
  1902. func (s *InboundService) SearchClientTraffic(query string) (traffic *xray.ClientTraffic, err error) {
  1903. db := database.GetDB()
  1904. inbound := &model.Inbound{}
  1905. traffic = &xray.ClientTraffic{}
  1906. // Search for inbound settings that contain the query
  1907. err = db.Model(model.Inbound{}).Where("settings LIKE ?", "%\""+query+"\"%").First(inbound).Error
  1908. if err != nil {
  1909. if err == gorm.ErrRecordNotFound {
  1910. logger.Warningf("Inbound settings containing query %s not found: %v", query, err)
  1911. return nil, err
  1912. }
  1913. logger.Errorf("Error searching for inbound settings with query %s: %v", query, err)
  1914. return nil, err
  1915. }
  1916. traffic.InboundId = inbound.Id
  1917. // Unmarshal settings to get clients
  1918. settings := map[string][]model.Client{}
  1919. if err := json.Unmarshal([]byte(inbound.Settings), &settings); err != nil {
  1920. logger.Errorf("Error unmarshalling inbound settings for inbound ID %d: %v", inbound.Id, err)
  1921. return nil, err
  1922. }
  1923. clients := settings["clients"]
  1924. for _, client := range clients {
  1925. if (client.ID == query || client.Password == query) && client.Email != "" {
  1926. traffic.Email = client.Email
  1927. break
  1928. }
  1929. }
  1930. if traffic.Email == "" {
  1931. logger.Warningf("No client found with query %s in inbound ID %d", query, inbound.Id)
  1932. return nil, gorm.ErrRecordNotFound
  1933. }
  1934. // Retrieve ClientTraffic based on the found email
  1935. err = db.Model(xray.ClientTraffic{}).Where("email = ?", traffic.Email).First(traffic).Error
  1936. if err != nil {
  1937. if err == gorm.ErrRecordNotFound {
  1938. logger.Warningf("ClientTraffic for email %s not found: %v", traffic.Email, err)
  1939. return nil, err
  1940. }
  1941. logger.Errorf("Error retrieving ClientTraffic for email %s: %v", traffic.Email, err)
  1942. return nil, err
  1943. }
  1944. return traffic, nil
  1945. }
  1946. func (s *InboundService) GetInboundClientIps(clientEmail string) (string, error) {
  1947. db := database.GetDB()
  1948. InboundClientIps := &model.InboundClientIps{}
  1949. err := db.Model(model.InboundClientIps{}).Where("client_email = ?", clientEmail).First(InboundClientIps).Error
  1950. if err != nil {
  1951. return "", err
  1952. }
  1953. if InboundClientIps.Ips == "" {
  1954. return "", nil
  1955. }
  1956. // Try to parse as new format (with timestamps)
  1957. type IPWithTimestamp struct {
  1958. IP string `json:"ip"`
  1959. Timestamp int64 `json:"timestamp"`
  1960. }
  1961. var ipsWithTime []IPWithTimestamp
  1962. err = json.Unmarshal([]byte(InboundClientIps.Ips), &ipsWithTime)
  1963. // If successfully parsed as new format, return with timestamps
  1964. if err == nil && len(ipsWithTime) > 0 {
  1965. return InboundClientIps.Ips, nil
  1966. }
  1967. // Otherwise, assume it's old format (simple string array)
  1968. // Try to parse as simple array and convert to new format
  1969. var oldIps []string
  1970. err = json.Unmarshal([]byte(InboundClientIps.Ips), &oldIps)
  1971. if err == nil && len(oldIps) > 0 {
  1972. // Convert old format to new format with current timestamp
  1973. newIpsWithTime := make([]IPWithTimestamp, len(oldIps))
  1974. for i, ip := range oldIps {
  1975. newIpsWithTime[i] = IPWithTimestamp{
  1976. IP: ip,
  1977. Timestamp: time.Now().Unix(),
  1978. }
  1979. }
  1980. result, _ := json.Marshal(newIpsWithTime)
  1981. return string(result), nil
  1982. }
  1983. // Return as-is if parsing fails
  1984. return InboundClientIps.Ips, nil
  1985. }
  1986. func (s *InboundService) ClearClientIps(clientEmail string) error {
  1987. db := database.GetDB()
  1988. result := db.Model(model.InboundClientIps{}).
  1989. Where("client_email = ?", clientEmail).
  1990. Update("ips", "")
  1991. err := result.Error
  1992. if err != nil {
  1993. return err
  1994. }
  1995. return nil
  1996. }
  1997. func (s *InboundService) SearchInbounds(query string) ([]*model.Inbound, error) {
  1998. db := database.GetDB()
  1999. var inbounds []*model.Inbound
  2000. err := db.Model(model.Inbound{}).Preload("ClientStats").Where("remark like ?", "%"+query+"%").Find(&inbounds).Error
  2001. if err != nil && err != gorm.ErrRecordNotFound {
  2002. return nil, err
  2003. }
  2004. return inbounds, nil
  2005. }
  2006. func (s *InboundService) MigrationRequirements() {
  2007. db := database.GetDB()
  2008. tx := db.Begin()
  2009. var err error
  2010. defer func() {
  2011. if err == nil {
  2012. tx.Commit()
  2013. if dbErr := db.Exec(`VACUUM "main"`).Error; dbErr != nil {
  2014. logger.Warningf("VACUUM failed: %v", dbErr)
  2015. }
  2016. } else {
  2017. tx.Rollback()
  2018. }
  2019. }()
  2020. // Calculate and backfill all_time from up+down for inbounds and clients
  2021. err = tx.Exec(`
  2022. UPDATE inbounds
  2023. SET all_time = IFNULL(up, 0) + IFNULL(down, 0)
  2024. WHERE IFNULL(all_time, 0) = 0 AND (IFNULL(up, 0) + IFNULL(down, 0)) > 0
  2025. `).Error
  2026. if err != nil {
  2027. return
  2028. }
  2029. err = tx.Exec(`
  2030. UPDATE client_traffics
  2031. SET all_time = IFNULL(up, 0) + IFNULL(down, 0)
  2032. WHERE IFNULL(all_time, 0) = 0 AND (IFNULL(up, 0) + IFNULL(down, 0)) > 0
  2033. `).Error
  2034. if err != nil {
  2035. return
  2036. }
  2037. // Fix inbounds based problems
  2038. var inbounds []*model.Inbound
  2039. err = tx.Model(model.Inbound{}).Where("protocol IN (?)", []string{"vmess", "vless", "trojan"}).Find(&inbounds).Error
  2040. if err != nil && err != gorm.ErrRecordNotFound {
  2041. return
  2042. }
  2043. for inbound_index := range inbounds {
  2044. settings := map[string]any{}
  2045. json.Unmarshal([]byte(inbounds[inbound_index].Settings), &settings)
  2046. clients, ok := settings["clients"].([]any)
  2047. if ok {
  2048. // Fix Client configuration problems
  2049. var newClients []any
  2050. for client_index := range clients {
  2051. c := clients[client_index].(map[string]any)
  2052. // Add email='' if it is not exists
  2053. if _, ok := c["email"]; !ok {
  2054. c["email"] = ""
  2055. }
  2056. // Convert string tgId to int64
  2057. if _, ok := c["tgId"]; ok {
  2058. var tgId any = c["tgId"]
  2059. if tgIdStr, ok2 := tgId.(string); ok2 {
  2060. tgIdInt64, err := strconv.ParseInt(strings.ReplaceAll(tgIdStr, " ", ""), 10, 64)
  2061. if err == nil {
  2062. c["tgId"] = tgIdInt64
  2063. }
  2064. }
  2065. }
  2066. // Remove "flow": "xtls-rprx-direct"
  2067. if _, ok := c["flow"]; ok {
  2068. if c["flow"] == "xtls-rprx-direct" {
  2069. c["flow"] = ""
  2070. }
  2071. }
  2072. // Backfill created_at and updated_at
  2073. if _, ok := c["created_at"]; !ok {
  2074. c["created_at"] = time.Now().Unix() * 1000
  2075. }
  2076. c["updated_at"] = time.Now().Unix() * 1000
  2077. newClients = append(newClients, any(c))
  2078. }
  2079. settings["clients"] = newClients
  2080. modifiedSettings, err := json.MarshalIndent(settings, "", " ")
  2081. if err != nil {
  2082. return
  2083. }
  2084. inbounds[inbound_index].Settings = string(modifiedSettings)
  2085. }
  2086. // Add client traffic row for all clients which has email
  2087. modelClients, err := s.GetClients(inbounds[inbound_index])
  2088. if err != nil {
  2089. return
  2090. }
  2091. for _, modelClient := range modelClients {
  2092. if len(modelClient.Email) > 0 {
  2093. var count int64
  2094. tx.Model(xray.ClientTraffic{}).Where("email = ?", modelClient.Email).Count(&count)
  2095. if count == 0 {
  2096. s.AddClientStat(tx, inbounds[inbound_index].Id, &modelClient)
  2097. }
  2098. }
  2099. }
  2100. }
  2101. tx.Save(inbounds)
  2102. // Remove orphaned traffics
  2103. tx.Where("inbound_id = 0").Delete(xray.ClientTraffic{})
  2104. // Migrate old MultiDomain to External Proxy
  2105. var externalProxy []struct {
  2106. Id int
  2107. Port int
  2108. StreamSettings []byte
  2109. }
  2110. err = tx.Raw(`select id, port, stream_settings
  2111. from inbounds
  2112. WHERE protocol in ('vmess','vless','trojan')
  2113. AND json_extract(stream_settings, '$.security') = 'tls'
  2114. AND json_extract(stream_settings, '$.tlsSettings.settings.domains') IS NOT NULL`).Scan(&externalProxy).Error
  2115. if err != nil || len(externalProxy) == 0 {
  2116. return
  2117. }
  2118. for _, ep := range externalProxy {
  2119. var reverses any
  2120. var stream map[string]any
  2121. json.Unmarshal(ep.StreamSettings, &stream)
  2122. if tlsSettings, ok := stream["tlsSettings"].(map[string]any); ok {
  2123. if settings, ok := tlsSettings["settings"].(map[string]any); ok {
  2124. if domains, ok := settings["domains"].([]any); ok {
  2125. for _, domain := range domains {
  2126. if domainMap, ok := domain.(map[string]any); ok {
  2127. domainMap["forceTls"] = "same"
  2128. domainMap["port"] = ep.Port
  2129. domainMap["dest"] = domainMap["domain"].(string)
  2130. delete(domainMap, "domain")
  2131. }
  2132. }
  2133. }
  2134. reverses = settings["domains"]
  2135. delete(settings, "domains")
  2136. }
  2137. }
  2138. stream["externalProxy"] = reverses
  2139. newStream, _ := json.MarshalIndent(stream, " ", " ")
  2140. tx.Model(model.Inbound{}).Where("id = ?", ep.Id).Update("stream_settings", newStream)
  2141. }
  2142. err = tx.Raw(`UPDATE inbounds
  2143. SET tag = REPLACE(tag, '0.0.0.0:', '')
  2144. WHERE INSTR(tag, '0.0.0.0:') > 0;`).Error
  2145. if err != nil {
  2146. return
  2147. }
  2148. }
  2149. func (s *InboundService) MigrateDB() {
  2150. s.MigrationRequirements()
  2151. s.MigrationRemoveOrphanedTraffics()
  2152. }
  2153. func (s *InboundService) GetOnlineClients() []string {
  2154. return p.GetOnlineClients()
  2155. }
  2156. func (s *InboundService) GetClientsLastOnline() (map[string]int64, error) {
  2157. db := database.GetDB()
  2158. var rows []xray.ClientTraffic
  2159. err := db.Model(&xray.ClientTraffic{}).Select("email, last_online").Find(&rows).Error
  2160. if err != nil && err != gorm.ErrRecordNotFound {
  2161. return nil, err
  2162. }
  2163. result := make(map[string]int64, len(rows))
  2164. for _, r := range rows {
  2165. result[r.Email] = r.LastOnline
  2166. }
  2167. return result, nil
  2168. }
  2169. func (s *InboundService) FilterAndSortClientEmails(emails []string) ([]string, []string, error) {
  2170. db := database.GetDB()
  2171. // Step 1: Get ClientTraffic records for emails in the input list
  2172. var clients []xray.ClientTraffic
  2173. err := db.Where("email IN ?", emails).Find(&clients).Error
  2174. if err != nil && err != gorm.ErrRecordNotFound {
  2175. return nil, nil, err
  2176. }
  2177. // Step 2: Sort clients by (Up + Down) descending
  2178. sort.Slice(clients, func(i, j int) bool {
  2179. return (clients[i].Up + clients[i].Down) > (clients[j].Up + clients[j].Down)
  2180. })
  2181. // Step 3: Extract sorted valid emails and track found ones
  2182. validEmails := make([]string, 0, len(clients))
  2183. found := make(map[string]bool)
  2184. for _, client := range clients {
  2185. validEmails = append(validEmails, client.Email)
  2186. found[client.Email] = true
  2187. }
  2188. // Step 4: Identify emails that were not found in the database
  2189. extraEmails := make([]string, 0)
  2190. for _, email := range emails {
  2191. if !found[email] {
  2192. extraEmails = append(extraEmails, email)
  2193. }
  2194. }
  2195. return validEmails, extraEmails, nil
  2196. }
  2197. func (s *InboundService) DelInboundClientByEmail(inboundId int, email string) (bool, error) {
  2198. oldInbound, err := s.GetInbound(inboundId)
  2199. if err != nil {
  2200. logger.Error("Load Old Data Error")
  2201. return false, err
  2202. }
  2203. var settings map[string]any
  2204. if err := json.Unmarshal([]byte(oldInbound.Settings), &settings); err != nil {
  2205. return false, err
  2206. }
  2207. interfaceClients, ok := settings["clients"].([]any)
  2208. if !ok {
  2209. return false, common.NewError("invalid clients format in inbound settings")
  2210. }
  2211. var newClients []any
  2212. needApiDel := false
  2213. found := false
  2214. for _, client := range interfaceClients {
  2215. c, ok := client.(map[string]any)
  2216. if !ok {
  2217. continue
  2218. }
  2219. if cEmail, ok := c["email"].(string); ok && cEmail == email {
  2220. // matched client, drop it
  2221. found = true
  2222. needApiDel, _ = c["enable"].(bool)
  2223. } else {
  2224. newClients = append(newClients, client)
  2225. }
  2226. }
  2227. if !found {
  2228. return false, common.NewError(fmt.Sprintf("client with email %s not found", email))
  2229. }
  2230. if len(newClients) == 0 {
  2231. return false, common.NewError("no client remained in Inbound")
  2232. }
  2233. settings["clients"] = newClients
  2234. newSettings, err := json.MarshalIndent(settings, "", " ")
  2235. if err != nil {
  2236. return false, err
  2237. }
  2238. oldInbound.Settings = string(newSettings)
  2239. db := database.GetDB()
  2240. // remove IP bindings
  2241. if err := s.DelClientIPs(db, email); err != nil {
  2242. logger.Error("Error in delete client IPs")
  2243. return false, err
  2244. }
  2245. needRestart := false
  2246. // remove stats too
  2247. if len(email) > 0 {
  2248. traffic, err := s.GetClientTrafficByEmail(email)
  2249. if err != nil {
  2250. return false, err
  2251. }
  2252. if traffic != nil {
  2253. if err := s.DelClientStat(db, email); err != nil {
  2254. logger.Error("Delete stats Data Error")
  2255. return false, err
  2256. }
  2257. }
  2258. if needApiDel {
  2259. s.xrayApi.Init(p.GetAPIPort())
  2260. if err1 := s.xrayApi.RemoveUser(oldInbound.Tag, email); err1 == nil {
  2261. logger.Debug("Client deleted by api:", email)
  2262. needRestart = false
  2263. } else {
  2264. if strings.Contains(err1.Error(), fmt.Sprintf("User %s not found.", email)) {
  2265. logger.Debug("User is already deleted. Nothing to do more...")
  2266. } else {
  2267. logger.Debug("Error in deleting client by api:", err1)
  2268. needRestart = true
  2269. }
  2270. }
  2271. s.xrayApi.Close()
  2272. }
  2273. }
  2274. return needRestart, db.Save(oldInbound).Error
  2275. }