1
0

check_client_ip_job.go 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660
  1. package job
  2. import (
  3. "bufio"
  4. "encoding/json"
  5. "errors"
  6. "io"
  7. "log"
  8. "os"
  9. "os/exec"
  10. "regexp"
  11. "runtime"
  12. "sort"
  13. "time"
  14. "github.com/mhsanaei/3x-ui/v3/internal/database"
  15. "github.com/mhsanaei/3x-ui/v3/internal/database/model"
  16. "github.com/mhsanaei/3x-ui/v3/internal/logger"
  17. "github.com/mhsanaei/3x-ui/v3/internal/web/service"
  18. "github.com/mhsanaei/3x-ui/v3/internal/xray"
  19. "gorm.io/gorm"
  20. )
  21. // IPWithTimestamp tracks an IP address with its last seen timestamp
  22. type IPWithTimestamp struct {
  23. IP string `json:"ip"`
  24. Timestamp int64 `json:"timestamp"`
  25. }
  26. // CheckClientIpJob monitors client IP addresses and manages IP blocking based
  27. // on configured limits. The per-client IPs come from the core's online-stats
  28. // API when the running core supports it (no access log needed), falling back
  29. // to access-log parsing on older cores.
  30. type CheckClientIpJob struct {
  31. lastClear int64
  32. disAllowedIps []string
  33. xrayService service.XrayService
  34. }
  35. var job *CheckClientIpJob
  36. const defaultXrayAPIPort = 62789
  37. const ipStaleAfterSeconds = int64(30 * 60)
  38. // NewCheckClientIpJob creates a new client IP monitoring job instance.
  39. func NewCheckClientIpJob() *CheckClientIpJob {
  40. job = new(CheckClientIpJob)
  41. return job
  42. }
  43. func (j *CheckClientIpJob) Run() {
  44. if j.lastClear == 0 {
  45. j.lastClear = time.Now().Unix()
  46. }
  47. fail2BanEnabled := isFail2BanEnabled()
  48. hasLimit := fail2BanEnabled && j.hasLimitIp()
  49. f2bInstalled := false
  50. if hasLimit {
  51. f2bInstalled = j.checkFail2BanInstalled()
  52. }
  53. if observed, apiMode := j.collectFromOnlineAPI(); apiMode {
  54. if fail2BanEnabled {
  55. j.processObserved(observed, j.resolveEnforce(hasLimit, f2bInstalled), true)
  56. }
  57. // The core tracks online IPs itself, so no access log is needed in this
  58. // mode; still rotate a user-configured access log hourly so it doesn't
  59. // grow unboundedly. The enforcement-triggered rotation is skipped —
  60. // nothing here reads the log.
  61. if j.checkAccessLogAvailable(false) && time.Now().Unix()-j.lastClear > 3600 {
  62. j.clearAccessLog()
  63. }
  64. return
  65. }
  66. shouldClearAccessLog := false
  67. isAccessLogAvailable := j.checkAccessLogAvailable(hasLimit)
  68. if fail2BanEnabled && isAccessLogAvailable {
  69. shouldClearAccessLog = j.processLogFile(j.resolveEnforce(hasLimit, f2bInstalled))
  70. }
  71. if shouldClearAccessLog || (isAccessLogAvailable && time.Now().Unix()-j.lastClear > 3600) {
  72. j.clearAccessLog()
  73. }
  74. }
  75. // resolveEnforce decides whether limits can actually be enforced this run,
  76. // warning when fail2ban is missing on a platform that needs it.
  77. func (j *CheckClientIpJob) resolveEnforce(hasLimit, f2bInstalled bool) bool {
  78. if hasLimit && runtime.GOOS != "windows" && !f2bInstalled {
  79. logger.Warning("[LimitIP] Fail2Ban is not installed, Please install Fail2Ban from the x-ui bash menu.")
  80. return false
  81. }
  82. return hasLimit
  83. }
  84. // collectFromOnlineAPI builds per-email IP observations (email -> ip ->
  85. // last-seen unix seconds) from the core's online-stats API. ok=false means the
  86. // API is unavailable — xray not running, an older core, or a transient gRPC
  87. // failure — and the caller must fall back to access-log parsing.
  88. func (j *CheckClientIpJob) collectFromOnlineAPI() (map[string]map[string]int64, bool) {
  89. onlineUsers, ok, err := j.xrayService.GetOnlineUsers()
  90. if err != nil {
  91. logger.Debug("[LimitIP] online-stats API unavailable this run:", err)
  92. return nil, false
  93. }
  94. if !ok {
  95. return nil, false
  96. }
  97. now := time.Now().Unix()
  98. observed := make(map[string]map[string]int64, len(onlineUsers))
  99. for _, user := range onlineUsers {
  100. for _, entry := range user.IPs {
  101. // No localhost guard needed here: the core's OnlineMap.AddIP drops
  102. // 127.0.0.1/[::1] itself, so they never reach this list.
  103. ts := entry.LastSeen
  104. if ts <= 0 {
  105. ts = now
  106. }
  107. if _, exists := observed[user.Email]; !exists {
  108. observed[user.Email] = make(map[string]int64)
  109. }
  110. if existing, seen := observed[user.Email][entry.IP]; !seen || ts > existing {
  111. observed[user.Email][entry.IP] = ts
  112. }
  113. }
  114. }
  115. return observed, true
  116. }
  117. func (j *CheckClientIpJob) clearAccessLog() {
  118. logAccessP, err := os.OpenFile(xray.GetAccessPersistentLogPath(), os.O_CREATE|os.O_APPEND|os.O_WRONLY, 0o644)
  119. j.checkError(err)
  120. defer logAccessP.Close()
  121. accessLogPath, err := xray.GetAccessLogPath()
  122. j.checkError(err)
  123. file, err := os.Open(accessLogPath)
  124. j.checkError(err)
  125. defer file.Close()
  126. _, err = io.Copy(logAccessP, file)
  127. j.checkError(err)
  128. err = os.Truncate(accessLogPath, 0)
  129. j.checkError(err)
  130. j.lastClear = time.Now().Unix()
  131. }
  132. func (j *CheckClientIpJob) hasLimitIp() bool {
  133. db := database.GetDB()
  134. var inbounds []*model.Inbound
  135. err := db.Model(model.Inbound{}).Find(&inbounds).Error
  136. if err != nil {
  137. return false
  138. }
  139. for _, inbound := range inbounds {
  140. if inbound.Settings == "" {
  141. continue
  142. }
  143. settings := map[string][]model.Client{}
  144. json.Unmarshal([]byte(inbound.Settings), &settings)
  145. clients := settings["clients"]
  146. for _, client := range clients {
  147. limitIp := client.LimitIP
  148. if limitIp > 0 {
  149. return true
  150. }
  151. }
  152. }
  153. return false
  154. }
  155. func (j *CheckClientIpJob) processLogFile(enforce bool) bool {
  156. ipRegex := regexp.MustCompile(`from (?:tcp:|udp:)?\[?([0-9a-fA-F\.:]+)\]?:\d+ accepted`)
  157. emailRegex := regexp.MustCompile(`email: (.+)$`)
  158. timestampRegex := regexp.MustCompile(`^(\d{4}/\d{2}/\d{2} \d{2}:\d{2}:\d{2})`)
  159. accessLogPath, _ := xray.GetAccessLogPath()
  160. file, _ := os.Open(accessLogPath)
  161. defer file.Close()
  162. // Track IPs with their last seen timestamp
  163. inboundClientIps := make(map[string]map[string]int64, 100)
  164. scanner := bufio.NewScanner(file)
  165. for scanner.Scan() {
  166. line := scanner.Text()
  167. ipMatches := ipRegex.FindStringSubmatch(line)
  168. if len(ipMatches) < 2 {
  169. continue
  170. }
  171. ip := ipMatches[1]
  172. if ip == "127.0.0.1" || ip == "::1" {
  173. continue
  174. }
  175. emailMatches := emailRegex.FindStringSubmatch(line)
  176. if len(emailMatches) < 2 {
  177. continue
  178. }
  179. email := emailMatches[1]
  180. // Extract timestamp from log line
  181. var timestamp int64
  182. timestampMatches := timestampRegex.FindStringSubmatch(line)
  183. if len(timestampMatches) >= 2 {
  184. t, err := time.ParseInLocation("2006/01/02 15:04:05", timestampMatches[1], time.Local)
  185. if err == nil {
  186. timestamp = t.Unix()
  187. } else {
  188. timestamp = time.Now().Unix()
  189. }
  190. } else {
  191. timestamp = time.Now().Unix()
  192. }
  193. if _, exists := inboundClientIps[email]; !exists {
  194. inboundClientIps[email] = make(map[string]int64)
  195. }
  196. // Update timestamp - keep the latest
  197. if existingTime, ok := inboundClientIps[email][ip]; !ok || timestamp > existingTime {
  198. inboundClientIps[email][ip] = timestamp
  199. }
  200. }
  201. if err := scanner.Err(); err != nil {
  202. j.checkError(err)
  203. }
  204. return j.processObserved(inboundClientIps, enforce, false)
  205. }
  206. // processObserved runs collection + enforcement for one scan's observations
  207. // (email -> ip -> last-seen unix seconds). observedAreLive marks the
  208. // observations as live connections (online-stats API) rather than recent log
  209. // lines: live entries bypass the stale cutoff, since a connection that opened
  210. // hours ago is still live even though its timestamp is old.
  211. func (j *CheckClientIpJob) processObserved(observed map[string]map[string]int64, enforce, observedAreLive bool) bool {
  212. shouldCleanLog := false
  213. for email, ipTimestamps := range observed {
  214. // The observations can still reference a client that was just renamed
  215. // or deleted; its email no longer matches any inbound. Skip it (and
  216. // drop any orphaned tracking row) instead of recreating a row and
  217. // logging an ERROR every run (#4963).
  218. inbound, err := j.getInboundByEmail(email)
  219. if err != nil {
  220. if errors.Is(err, gorm.ErrRecordNotFound) {
  221. logger.Debugf("[LimitIP] skipping stale observed email %q (renamed or deleted)", email)
  222. j.delInboundClientIps(email)
  223. } else {
  224. j.checkError(err)
  225. }
  226. continue
  227. }
  228. // Convert to IPWithTimestamp slice
  229. ipsWithTime := make([]IPWithTimestamp, 0, len(ipTimestamps))
  230. for ip, timestamp := range ipTimestamps {
  231. ipsWithTime = append(ipsWithTime, IPWithTimestamp{IP: ip, Timestamp: timestamp})
  232. }
  233. clientIpsRecord, err := j.getInboundClientIps(email)
  234. if err != nil {
  235. j.addInboundClientIps(email, ipsWithTime)
  236. continue
  237. }
  238. shouldCleanLog = j.updateInboundClientIps(clientIpsRecord, inbound, email, ipsWithTime, enforce, observedAreLive) || shouldCleanLog
  239. }
  240. return shouldCleanLog
  241. }
  242. // mergeClientIps folds this scan's observations into the persisted set,
  243. // dropping entries older than staleCutoff. newAlwaysLive exempts the new
  244. // entries from that cutoff: an API-observed IP is a live connection by
  245. // definition, even when its lastSeen (set at dispatch time) is hours old.
  246. func mergeClientIps(old, new []IPWithTimestamp, staleCutoff int64, newAlwaysLive bool) map[string]int64 {
  247. ipMap := make(map[string]int64, len(old)+len(new))
  248. for _, ipTime := range old {
  249. if ipTime.Timestamp < staleCutoff {
  250. continue
  251. }
  252. ipMap[ipTime.IP] = ipTime.Timestamp
  253. }
  254. for _, ipTime := range new {
  255. if !newAlwaysLive && ipTime.Timestamp < staleCutoff {
  256. continue
  257. }
  258. if existingTime, ok := ipMap[ipTime.IP]; !ok || ipTime.Timestamp > existingTime {
  259. ipMap[ipTime.IP] = ipTime.Timestamp
  260. }
  261. }
  262. return ipMap
  263. }
  264. // selectIpsToBan splits the live IPs (sorted oldest-first by partitionLiveIps)
  265. // into the newest `limit` entries to keep and the older remainder to ban.
  266. func selectIpsToBan(live []IPWithTimestamp, limit int) (kept, banned []IPWithTimestamp) {
  267. if limit <= 0 || len(live) <= limit {
  268. return live, nil
  269. }
  270. cutoff := len(live) - limit
  271. return live[cutoff:], live[:cutoff]
  272. }
  273. func partitionLiveIps(ipMap map[string]int64, observedThisScan map[string]bool) (live, historical []IPWithTimestamp) {
  274. live = make([]IPWithTimestamp, 0, len(observedThisScan))
  275. historical = make([]IPWithTimestamp, 0, len(ipMap))
  276. now := time.Now().Unix()
  277. for ip, ts := range ipMap {
  278. entry := IPWithTimestamp{IP: ip, Timestamp: ts}
  279. // Consider an IP "live" if it was seen locally in this scan, OR if its
  280. // timestamp from the synced database is very recent (e.g. within 2 minutes).
  281. // This ensures cluster-wide limits work even if the IP was seen on another node.
  282. if observedThisScan[ip] || now-ts < 120 {
  283. live = append(live, entry)
  284. } else {
  285. historical = append(historical, entry)
  286. }
  287. }
  288. sort.Slice(live, func(i, j int) bool { return live[i].Timestamp < live[j].Timestamp })
  289. sort.Slice(historical, func(i, j int) bool { return historical[i].Timestamp < historical[j].Timestamp })
  290. return live, historical
  291. }
  292. func (j *CheckClientIpJob) checkFail2BanInstalled() bool {
  293. if !isFail2BanEnabled() {
  294. return false
  295. }
  296. cmd := "fail2ban-client"
  297. args := []string{"-h"}
  298. err := exec.Command(cmd, args...).Run()
  299. return err == nil
  300. }
  301. func isFail2BanEnabled() bool {
  302. value, ok := os.LookupEnv("XUI_ENABLE_FAIL2BAN")
  303. return !ok || value == "true"
  304. }
  305. func (j *CheckClientIpJob) checkAccessLogAvailable(iplimitActive bool) bool {
  306. accessLogPath, err := xray.GetAccessLogPath()
  307. if err != nil {
  308. return false
  309. }
  310. if accessLogPath == "none" || accessLogPath == "" {
  311. if iplimitActive {
  312. logger.Warning("[LimitIP] Access log path is not set, Please configure the access log path in Xray configs.")
  313. }
  314. return false
  315. }
  316. return true
  317. }
  318. func (j *CheckClientIpJob) checkError(e error) {
  319. if e != nil {
  320. logger.Warning("client ip job err:", e)
  321. }
  322. }
  323. func (j *CheckClientIpJob) getInboundClientIps(clientEmail string) (*model.InboundClientIps, error) {
  324. db := database.GetDB()
  325. InboundClientIps := &model.InboundClientIps{}
  326. err := db.Model(model.InboundClientIps{}).Where("client_email = ?", clientEmail).First(InboundClientIps).Error
  327. if err != nil {
  328. return nil, err
  329. }
  330. return InboundClientIps, nil
  331. }
  332. func (j *CheckClientIpJob) addInboundClientIps(clientEmail string, ipsWithTime []IPWithTimestamp) error {
  333. inboundClientIps := &model.InboundClientIps{}
  334. jsonIps, err := json.Marshal(ipsWithTime)
  335. j.checkError(err)
  336. inboundClientIps.ClientEmail = clientEmail
  337. inboundClientIps.Ips = string(jsonIps)
  338. db := database.GetDB()
  339. tx := db.Begin()
  340. defer func() {
  341. if err == nil {
  342. tx.Commit()
  343. } else {
  344. tx.Rollback()
  345. }
  346. }()
  347. err = tx.Save(inboundClientIps).Error
  348. if err != nil {
  349. return err
  350. }
  351. return nil
  352. }
  353. // delInboundClientIps drops the inbound_client_ips tracking row for an email
  354. // that no longer maps to any inbound (a renamed or deleted client), so stale
  355. // access-log entries don't keep a ghost row alive (#4963).
  356. func (j *CheckClientIpJob) delInboundClientIps(clientEmail string) {
  357. db := database.GetDB()
  358. if err := db.Where("client_email = ?", clientEmail).Delete(&model.InboundClientIps{}).Error; err != nil {
  359. j.checkError(err)
  360. }
  361. }
  362. func (j *CheckClientIpJob) updateInboundClientIps(inboundClientIps *model.InboundClientIps, inbound *model.Inbound, clientEmail string, newIpsWithTime []IPWithTimestamp, enforce, observedAreLive bool) bool {
  363. if inbound.Settings == "" {
  364. logger.Debug("wrong data:", inbound)
  365. return false
  366. }
  367. settings := map[string][]model.Client{}
  368. json.Unmarshal([]byte(inbound.Settings), &settings)
  369. clients := settings["clients"]
  370. // Find the client's IP limit
  371. var limitIp int
  372. var clientFound bool
  373. for _, client := range clients {
  374. if client.Email == clientEmail {
  375. limitIp = client.LimitIP
  376. clientFound = true
  377. break
  378. }
  379. }
  380. if !enforce || !clientFound || limitIp <= 0 || !inbound.Enable {
  381. // Nothing to enforce (collection-only run, no limit, client missing, or
  382. // inbound disabled): record the observed IPs for the panel and return.
  383. jsonIps, _ := json.Marshal(newIpsWithTime)
  384. inboundClientIps.Ips = string(jsonIps)
  385. db := database.GetDB()
  386. db.Save(inboundClientIps)
  387. return false
  388. }
  389. // Parse old IPs from database
  390. var oldIpsWithTime []IPWithTimestamp
  391. if inboundClientIps.Ips != "" {
  392. json.Unmarshal([]byte(inboundClientIps.Ips), &oldIpsWithTime)
  393. }
  394. ipMap := mergeClientIps(oldIpsWithTime, newIpsWithTime, time.Now().Unix()-ipStaleAfterSeconds, observedAreLive)
  395. // only ips seen in this scan count toward the limit. see
  396. // partitionLiveIps.
  397. observedThisScan := make(map[string]bool, len(newIpsWithTime))
  398. for _, ipTime := range newIpsWithTime {
  399. observedThisScan[ipTime.IP] = true
  400. }
  401. liveIps, historicalIps := partitionLiveIps(ipMap, observedThisScan)
  402. shouldCleanLog := false
  403. j.disAllowedIps = []string{}
  404. // historical db-only ips are excluded from this count on purpose.
  405. keptLive, bannedLive := selectIpsToBan(liveIps, limitIp)
  406. if len(bannedLive) > 0 {
  407. shouldCleanLog = true
  408. logIpFile, err := os.OpenFile(xray.GetIPLimitLogPath(), os.O_CREATE|os.O_APPEND|os.O_WRONLY, 0644)
  409. if err != nil {
  410. logger.Errorf("failed to open IP limit log file: %s", err)
  411. return false
  412. }
  413. defer logIpFile.Close()
  414. ipLogger := log.New(logIpFile, "", log.LstdFlags)
  415. // log format is load-bearing: x-ui.sh create_iplimit_jails builds
  416. // filter.d/3x-ipl.conf with
  417. // failregex = \[LIMIT_IP\]\s*Email\s*=\s*<F-USER>.+</F-USER>\s*\|\|\s*Disconnecting OLD IP\s*=\s*<ADDR>\s*\|\|\s*Timestamp\s*=\s*\d+
  418. // don't change the wording.
  419. for _, ipTime := range bannedLive {
  420. j.disAllowedIps = append(j.disAllowedIps, ipTime.IP)
  421. ipLogger.Printf("[LIMIT_IP] Email = %s || Disconnecting OLD IP = %s || Timestamp = %d", clientEmail, ipTime.IP, ipTime.Timestamp)
  422. }
  423. // force xray to drop existing connections from banned ips
  424. j.disconnectClientTemporarily(inbound, clientEmail, clients)
  425. }
  426. // keep kept-live + historical in the blob so the panel keeps showing
  427. // recently seen ips. banned live ips are already in the fail2ban log
  428. // and will reappear in the next scan if they reconnect.
  429. dbIps := make([]IPWithTimestamp, 0, len(keptLive)+len(historicalIps))
  430. dbIps = append(dbIps, keptLive...)
  431. dbIps = append(dbIps, historicalIps...)
  432. jsonIps, _ := json.Marshal(dbIps)
  433. inboundClientIps.Ips = string(jsonIps)
  434. db := database.GetDB()
  435. err := db.Save(inboundClientIps).Error
  436. if err != nil {
  437. logger.Error("failed to save inboundClientIps:", err)
  438. return false
  439. }
  440. if len(j.disAllowedIps) > 0 {
  441. logger.Infof("[LIMIT_IP] Client %s: Kept %d live IPs, queued %d old IPs for fail2ban", clientEmail, len(keptLive), len(j.disAllowedIps))
  442. }
  443. return shouldCleanLog
  444. }
  445. // disconnectClientTemporarily removes and re-adds a client to force disconnect banned connections
  446. func (j *CheckClientIpJob) disconnectClientTemporarily(inbound *model.Inbound, clientEmail string, clients []model.Client) {
  447. var xrayAPI xray.XrayAPI
  448. apiPort := j.resolveXrayAPIPort()
  449. err := xrayAPI.Init(apiPort)
  450. if err != nil {
  451. logger.Warningf("[LIMIT_IP] Failed to init Xray API for disconnection: %v", err)
  452. return
  453. }
  454. defer xrayAPI.Close()
  455. // Find the client config
  456. var clientConfig map[string]any
  457. for _, client := range clients {
  458. if client.Email == clientEmail {
  459. // Convert client to map for API
  460. clientBytes, _ := json.Marshal(client)
  461. json.Unmarshal(clientBytes, &clientConfig)
  462. break
  463. }
  464. }
  465. if clientConfig == nil {
  466. return
  467. }
  468. // Only perform remove/re-add for protocols supported by XrayAPI.AddUser
  469. protocol := string(inbound.Protocol)
  470. switch protocol {
  471. case "vmess", "vless", "trojan", "shadowsocks":
  472. // supported protocols, continue
  473. default:
  474. logger.Warningf("[LIMIT_IP] Temporary disconnect is not supported for protocol %s on inbound %s", protocol, inbound.Tag)
  475. return
  476. }
  477. // For Shadowsocks, ensure the required "cipher" field is present by
  478. // reading it from the inbound settings (e.g., settings["method"]).
  479. if string(inbound.Protocol) == "shadowsocks" {
  480. var inboundSettings map[string]any
  481. if err := json.Unmarshal([]byte(inbound.Settings), &inboundSettings); err != nil {
  482. logger.Warningf("[LIMIT_IP] Failed to parse inbound settings for shadowsocks cipher: %v", err)
  483. } else {
  484. if method, ok := inboundSettings["method"].(string); ok && method != "" {
  485. clientConfig["cipher"] = method
  486. }
  487. }
  488. }
  489. // Remove user to disconnect all connections
  490. err = xrayAPI.RemoveUser(inbound.Tag, clientEmail)
  491. if err != nil {
  492. logger.Warningf("[LIMIT_IP] Failed to remove user %s: %v", clientEmail, err)
  493. return
  494. }
  495. // Wait a moment for disconnection to take effect
  496. time.Sleep(100 * time.Millisecond)
  497. // Re-add user to allow new connections
  498. err = xrayAPI.AddUser(protocol, inbound.Tag, clientConfig)
  499. if err != nil {
  500. logger.Warningf("[LIMIT_IP] Failed to re-add user %s: %v", clientEmail, err)
  501. }
  502. }
  503. // resolveXrayAPIPort returns the API inbound port from running config, then template config, then default.
  504. func (j *CheckClientIpJob) resolveXrayAPIPort() int {
  505. var configErr error
  506. var templateErr error
  507. if port, err := getAPIPortFromConfigPath(xray.GetConfigPath()); err == nil {
  508. return port
  509. } else {
  510. configErr = err
  511. }
  512. db := database.GetDB()
  513. var template model.Setting
  514. if err := db.Where("key = ?", "xrayTemplateConfig").First(&template).Error; err == nil {
  515. if port, parseErr := getAPIPortFromConfigData([]byte(template.Value)); parseErr == nil {
  516. return port
  517. } else {
  518. templateErr = parseErr
  519. }
  520. } else {
  521. templateErr = err
  522. }
  523. logger.Warningf(
  524. "[LIMIT_IP] Could not determine Xray API port from config or template; falling back to default port %d (config error: %v, template error: %v)",
  525. defaultXrayAPIPort,
  526. configErr,
  527. templateErr,
  528. )
  529. return defaultXrayAPIPort
  530. }
  531. func getAPIPortFromConfigPath(configPath string) (int, error) {
  532. configData, err := os.ReadFile(configPath)
  533. if err != nil {
  534. return 0, err
  535. }
  536. return getAPIPortFromConfigData(configData)
  537. }
  538. func getAPIPortFromConfigData(configData []byte) (int, error) {
  539. xrayConfig := &xray.Config{}
  540. if err := json.Unmarshal(configData, xrayConfig); err != nil {
  541. return 0, err
  542. }
  543. for _, inboundConfig := range xrayConfig.InboundConfigs {
  544. if inboundConfig.Tag == "api" && inboundConfig.Port > 0 {
  545. return inboundConfig.Port, nil
  546. }
  547. }
  548. return 0, errors.New("api inbound port not found")
  549. }
  550. func (j *CheckClientIpJob) getInboundByEmail(clientEmail string) (*model.Inbound, error) {
  551. db := database.GetDB()
  552. inbound := &model.Inbound{}
  553. err := db.Model(&model.Inbound{}).Where("settings LIKE ?", "%"+clientEmail+"%").First(inbound).Error
  554. if err != nil {
  555. return nil, err
  556. }
  557. return inbound, nil
  558. }