inbound.go 65 KB

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