check_client_ip_job.go 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694
  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. now := time.Now().Unix()
  214. // attribution accumulates this scan's local observations per email so they can
  215. // be recorded under this panel's own guid for cross-node IP attribution.
  216. attribution := make(map[string][]model.ClientIpEntry, len(observed))
  217. for email, ipTimestamps := range observed {
  218. // The observations can still reference a client that was just renamed
  219. // or deleted; its email no longer matches any inbound. Skip it (and
  220. // drop any orphaned tracking row) instead of recreating a row and
  221. // logging an ERROR every run (#4963).
  222. inbound, err := j.getInboundByEmail(email)
  223. if err != nil {
  224. if errors.Is(err, gorm.ErrRecordNotFound) {
  225. logger.Debugf("[LimitIP] skipping stale observed email %q (renamed or deleted)", email)
  226. j.delInboundClientIps(email)
  227. } else {
  228. j.checkError(err)
  229. }
  230. continue
  231. }
  232. // Convert to IPWithTimestamp slice
  233. ipsWithTime := make([]IPWithTimestamp, 0, len(ipTimestamps))
  234. attrEntries := make([]model.ClientIpEntry, 0, len(ipTimestamps))
  235. for ip, timestamp := range ipTimestamps {
  236. ipsWithTime = append(ipsWithTime, IPWithTimestamp{IP: ip, Timestamp: timestamp})
  237. // Live API observations may carry an old lastSeen (connection start),
  238. // so stamp attribution with now; otherwise the stale cutoff would evict
  239. // an IP that is connected right now.
  240. attrTs := timestamp
  241. if observedAreLive {
  242. attrTs = now
  243. }
  244. attrEntries = append(attrEntries, model.ClientIpEntry{IP: ip, Timestamp: attrTs})
  245. }
  246. if len(attrEntries) > 0 {
  247. attribution[email] = attrEntries
  248. }
  249. clientIpsRecord, err := j.getInboundClientIps(email)
  250. if err != nil {
  251. j.addInboundClientIps(email, ipsWithTime)
  252. continue
  253. }
  254. shouldCleanLog = j.updateInboundClientIps(clientIpsRecord, inbound, email, ipsWithTime, enforce, observedAreLive) || shouldCleanLog
  255. }
  256. j.recordLocalAttribution(attribution)
  257. return shouldCleanLog
  258. }
  259. // recordLocalAttribution stores this scan's local observations under this panel's
  260. // own guid so a parent panel can attribute each IP to the node it is on.
  261. // Best-effort: attribution is advisory and must never block IP-limit enforcement.
  262. func (j *CheckClientIpJob) recordLocalAttribution(attribution map[string][]model.ClientIpEntry) {
  263. if len(attribution) == 0 {
  264. return
  265. }
  266. guid, err := (&service.SettingService{}).GetPanelGuid()
  267. if err != nil || guid == "" {
  268. return
  269. }
  270. if err := (&service.InboundService{}).RecordLocalClientIps(guid, attribution); err != nil {
  271. logger.Debug("[LimitIP] record local ip attribution failed:", err)
  272. }
  273. }
  274. // mergeClientIps folds this scan's observations into the persisted set,
  275. // dropping entries older than staleCutoff. newAlwaysLive exempts the new
  276. // entries from that cutoff: an API-observed IP is a live connection by
  277. // definition, even when its lastSeen (set at dispatch time) is hours old.
  278. func mergeClientIps(old, new []IPWithTimestamp, staleCutoff int64, newAlwaysLive bool) map[string]int64 {
  279. ipMap := make(map[string]int64, len(old)+len(new))
  280. for _, ipTime := range old {
  281. if ipTime.Timestamp < staleCutoff {
  282. continue
  283. }
  284. ipMap[ipTime.IP] = ipTime.Timestamp
  285. }
  286. for _, ipTime := range new {
  287. if !newAlwaysLive && ipTime.Timestamp < staleCutoff {
  288. continue
  289. }
  290. if existingTime, ok := ipMap[ipTime.IP]; !ok || ipTime.Timestamp > existingTime {
  291. ipMap[ipTime.IP] = ipTime.Timestamp
  292. }
  293. }
  294. return ipMap
  295. }
  296. // selectIpsToBan splits the live IPs (sorted oldest-first by partitionLiveIps)
  297. // into the newest `limit` entries to keep and the older remainder to ban.
  298. func selectIpsToBan(live []IPWithTimestamp, limit int) (kept, banned []IPWithTimestamp) {
  299. if limit <= 0 || len(live) <= limit {
  300. return live, nil
  301. }
  302. cutoff := len(live) - limit
  303. return live[cutoff:], live[:cutoff]
  304. }
  305. func partitionLiveIps(ipMap map[string]int64, observedThisScan map[string]bool) (live, historical []IPWithTimestamp) {
  306. live = make([]IPWithTimestamp, 0, len(observedThisScan))
  307. historical = make([]IPWithTimestamp, 0, len(ipMap))
  308. now := time.Now().Unix()
  309. for ip, ts := range ipMap {
  310. entry := IPWithTimestamp{IP: ip, Timestamp: ts}
  311. // Consider an IP "live" if it was seen locally in this scan, OR if its
  312. // timestamp from the synced database is very recent (e.g. within 2 minutes).
  313. // This ensures cluster-wide limits work even if the IP was seen on another node.
  314. if observedThisScan[ip] || now-ts < 120 {
  315. live = append(live, entry)
  316. } else {
  317. historical = append(historical, entry)
  318. }
  319. }
  320. sort.Slice(live, func(i, j int) bool { return live[i].Timestamp < live[j].Timestamp })
  321. sort.Slice(historical, func(i, j int) bool { return historical[i].Timestamp < historical[j].Timestamp })
  322. return live, historical
  323. }
  324. func (j *CheckClientIpJob) checkFail2BanInstalled() bool {
  325. if !isFail2BanEnabled() {
  326. return false
  327. }
  328. cmd := "fail2ban-client"
  329. args := []string{"-h"}
  330. err := exec.Command(cmd, args...).Run()
  331. return err == nil
  332. }
  333. func isFail2BanEnabled() bool {
  334. value, ok := os.LookupEnv("XUI_ENABLE_FAIL2BAN")
  335. return !ok || value == "true"
  336. }
  337. func (j *CheckClientIpJob) checkAccessLogAvailable(iplimitActive bool) bool {
  338. accessLogPath, err := xray.GetAccessLogPath()
  339. if err != nil {
  340. return false
  341. }
  342. if accessLogPath == "none" || accessLogPath == "" {
  343. if iplimitActive {
  344. logger.Warning("[LimitIP] Access log path is not set, Please configure the access log path in Xray configs.")
  345. }
  346. return false
  347. }
  348. return true
  349. }
  350. func (j *CheckClientIpJob) checkError(e error) {
  351. if e != nil {
  352. logger.Warning("client ip job err:", e)
  353. }
  354. }
  355. func (j *CheckClientIpJob) getInboundClientIps(clientEmail string) (*model.InboundClientIps, error) {
  356. db := database.GetDB()
  357. InboundClientIps := &model.InboundClientIps{}
  358. err := db.Model(model.InboundClientIps{}).Where("client_email = ?", clientEmail).First(InboundClientIps).Error
  359. if err != nil {
  360. return nil, err
  361. }
  362. return InboundClientIps, nil
  363. }
  364. func (j *CheckClientIpJob) addInboundClientIps(clientEmail string, ipsWithTime []IPWithTimestamp) error {
  365. inboundClientIps := &model.InboundClientIps{}
  366. jsonIps, err := json.Marshal(ipsWithTime)
  367. j.checkError(err)
  368. inboundClientIps.ClientEmail = clientEmail
  369. inboundClientIps.Ips = string(jsonIps)
  370. db := database.GetDB()
  371. tx := db.Begin()
  372. defer func() {
  373. if err == nil {
  374. tx.Commit()
  375. } else {
  376. tx.Rollback()
  377. }
  378. }()
  379. err = tx.Save(inboundClientIps).Error
  380. if err != nil {
  381. return err
  382. }
  383. return nil
  384. }
  385. // delInboundClientIps drops the inbound_client_ips tracking row for an email
  386. // that no longer maps to any inbound (a renamed or deleted client), so stale
  387. // access-log entries don't keep a ghost row alive (#4963).
  388. func (j *CheckClientIpJob) delInboundClientIps(clientEmail string) {
  389. db := database.GetDB()
  390. if err := db.Where("client_email = ?", clientEmail).Delete(&model.InboundClientIps{}).Error; err != nil {
  391. j.checkError(err)
  392. }
  393. }
  394. func (j *CheckClientIpJob) updateInboundClientIps(inboundClientIps *model.InboundClientIps, inbound *model.Inbound, clientEmail string, newIpsWithTime []IPWithTimestamp, enforce, observedAreLive bool) bool {
  395. if inbound.Settings == "" {
  396. logger.Debug("wrong data:", inbound)
  397. return false
  398. }
  399. settings := map[string][]model.Client{}
  400. json.Unmarshal([]byte(inbound.Settings), &settings)
  401. clients := settings["clients"]
  402. // Find the client's IP limit
  403. var limitIp int
  404. var clientFound bool
  405. for _, client := range clients {
  406. if client.Email == clientEmail {
  407. limitIp = client.LimitIP
  408. clientFound = true
  409. break
  410. }
  411. }
  412. if !enforce || !clientFound || limitIp <= 0 || !inbound.Enable {
  413. // Nothing to enforce (collection-only run, no limit, client missing, or
  414. // inbound disabled): record the observed IPs for the panel and return.
  415. jsonIps, _ := json.Marshal(newIpsWithTime)
  416. inboundClientIps.Ips = string(jsonIps)
  417. db := database.GetDB()
  418. db.Save(inboundClientIps)
  419. return false
  420. }
  421. // Parse old IPs from database
  422. var oldIpsWithTime []IPWithTimestamp
  423. if inboundClientIps.Ips != "" {
  424. json.Unmarshal([]byte(inboundClientIps.Ips), &oldIpsWithTime)
  425. }
  426. ipMap := mergeClientIps(oldIpsWithTime, newIpsWithTime, time.Now().Unix()-ipStaleAfterSeconds, observedAreLive)
  427. // only ips seen in this scan count toward the limit. see
  428. // partitionLiveIps.
  429. observedThisScan := make(map[string]bool, len(newIpsWithTime))
  430. for _, ipTime := range newIpsWithTime {
  431. observedThisScan[ipTime.IP] = true
  432. }
  433. liveIps, historicalIps := partitionLiveIps(ipMap, observedThisScan)
  434. shouldCleanLog := false
  435. j.disAllowedIps = []string{}
  436. // historical db-only ips are excluded from this count on purpose.
  437. keptLive, bannedLive := selectIpsToBan(liveIps, limitIp)
  438. if len(bannedLive) > 0 {
  439. shouldCleanLog = true
  440. logIpFile, err := os.OpenFile(xray.GetIPLimitLogPath(), os.O_CREATE|os.O_APPEND|os.O_WRONLY, 0644)
  441. if err != nil {
  442. logger.Errorf("failed to open IP limit log file: %s", err)
  443. return false
  444. }
  445. defer logIpFile.Close()
  446. ipLogger := log.New(logIpFile, "", log.LstdFlags)
  447. // log format is load-bearing: x-ui.sh create_iplimit_jails builds
  448. // filter.d/3x-ipl.conf with
  449. // 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+
  450. // don't change the wording.
  451. for _, ipTime := range bannedLive {
  452. j.disAllowedIps = append(j.disAllowedIps, ipTime.IP)
  453. ipLogger.Printf("[LIMIT_IP] Email = %s || Disconnecting OLD IP = %s || Timestamp = %d", clientEmail, ipTime.IP, ipTime.Timestamp)
  454. }
  455. // force xray to drop existing connections from banned ips
  456. j.disconnectClientTemporarily(inbound, clientEmail, clients)
  457. }
  458. // keep kept-live + historical in the blob so the panel keeps showing
  459. // recently seen ips. banned live ips are already in the fail2ban log
  460. // and will reappear in the next scan if they reconnect.
  461. dbIps := make([]IPWithTimestamp, 0, len(keptLive)+len(historicalIps))
  462. dbIps = append(dbIps, keptLive...)
  463. dbIps = append(dbIps, historicalIps...)
  464. jsonIps, _ := json.Marshal(dbIps)
  465. inboundClientIps.Ips = string(jsonIps)
  466. db := database.GetDB()
  467. err := db.Save(inboundClientIps).Error
  468. if err != nil {
  469. logger.Error("failed to save inboundClientIps:", err)
  470. return false
  471. }
  472. if len(j.disAllowedIps) > 0 {
  473. logger.Infof("[LIMIT_IP] Client %s: Kept %d live IPs, queued %d old IPs for fail2ban", clientEmail, len(keptLive), len(j.disAllowedIps))
  474. }
  475. return shouldCleanLog
  476. }
  477. // disconnectClientTemporarily removes and re-adds a client to force disconnect banned connections
  478. func (j *CheckClientIpJob) disconnectClientTemporarily(inbound *model.Inbound, clientEmail string, clients []model.Client) {
  479. var xrayAPI xray.XrayAPI
  480. apiPort := j.resolveXrayAPIPort()
  481. err := xrayAPI.Init(apiPort)
  482. if err != nil {
  483. logger.Warningf("[LIMIT_IP] Failed to init Xray API for disconnection: %v", err)
  484. return
  485. }
  486. defer xrayAPI.Close()
  487. // Find the client config
  488. var clientConfig map[string]any
  489. for _, client := range clients {
  490. if client.Email == clientEmail {
  491. // Convert client to map for API
  492. clientBytes, _ := json.Marshal(client)
  493. json.Unmarshal(clientBytes, &clientConfig)
  494. break
  495. }
  496. }
  497. if clientConfig == nil {
  498. return
  499. }
  500. // Only perform remove/re-add for protocols supported by XrayAPI.AddUser
  501. protocol := string(inbound.Protocol)
  502. switch protocol {
  503. case "vmess", "vless", "trojan", "shadowsocks":
  504. // supported protocols, continue
  505. default:
  506. logger.Warningf("[LIMIT_IP] Temporary disconnect is not supported for protocol %s on inbound %s", protocol, inbound.Tag)
  507. return
  508. }
  509. // For Shadowsocks, ensure the required "cipher" field is present by
  510. // reading it from the inbound settings (e.g., settings["method"]).
  511. if string(inbound.Protocol) == "shadowsocks" {
  512. var inboundSettings map[string]any
  513. if err := json.Unmarshal([]byte(inbound.Settings), &inboundSettings); err != nil {
  514. logger.Warningf("[LIMIT_IP] Failed to parse inbound settings for shadowsocks cipher: %v", err)
  515. } else {
  516. if method, ok := inboundSettings["method"].(string); ok && method != "" {
  517. clientConfig["cipher"] = method
  518. }
  519. }
  520. }
  521. // Remove user to disconnect all connections
  522. err = xrayAPI.RemoveUser(inbound.Tag, clientEmail)
  523. if err != nil {
  524. logger.Warningf("[LIMIT_IP] Failed to remove user %s: %v", clientEmail, err)
  525. return
  526. }
  527. // Wait a moment for disconnection to take effect
  528. time.Sleep(100 * time.Millisecond)
  529. // Re-add user to allow new connections
  530. err = xrayAPI.AddUser(protocol, inbound.Tag, clientConfig)
  531. if err != nil {
  532. logger.Warningf("[LIMIT_IP] Failed to re-add user %s: %v", clientEmail, err)
  533. }
  534. }
  535. // resolveXrayAPIPort returns the API inbound port from running config, then template config, then default.
  536. func (j *CheckClientIpJob) resolveXrayAPIPort() int {
  537. var configErr error
  538. var templateErr error
  539. if port, err := getAPIPortFromConfigPath(xray.GetConfigPath()); err == nil {
  540. return port
  541. } else {
  542. configErr = err
  543. }
  544. db := database.GetDB()
  545. var template model.Setting
  546. if err := db.Where("key = ?", "xrayTemplateConfig").First(&template).Error; err == nil {
  547. if port, parseErr := getAPIPortFromConfigData([]byte(template.Value)); parseErr == nil {
  548. return port
  549. } else {
  550. templateErr = parseErr
  551. }
  552. } else {
  553. templateErr = err
  554. }
  555. logger.Warningf(
  556. "[LIMIT_IP] Could not determine Xray API port from config or template; falling back to default port %d (config error: %v, template error: %v)",
  557. defaultXrayAPIPort,
  558. configErr,
  559. templateErr,
  560. )
  561. return defaultXrayAPIPort
  562. }
  563. func getAPIPortFromConfigPath(configPath string) (int, error) {
  564. configData, err := os.ReadFile(configPath)
  565. if err != nil {
  566. return 0, err
  567. }
  568. return getAPIPortFromConfigData(configData)
  569. }
  570. func getAPIPortFromConfigData(configData []byte) (int, error) {
  571. xrayConfig := &xray.Config{}
  572. if err := json.Unmarshal(configData, xrayConfig); err != nil {
  573. return 0, err
  574. }
  575. for _, inboundConfig := range xrayConfig.InboundConfigs {
  576. if inboundConfig.Tag == "api" && inboundConfig.Port > 0 {
  577. return inboundConfig.Port, nil
  578. }
  579. }
  580. return 0, errors.New("api inbound port not found")
  581. }
  582. func (j *CheckClientIpJob) getInboundByEmail(clientEmail string) (*model.Inbound, error) {
  583. db := database.GetDB()
  584. inbound := &model.Inbound{}
  585. err := db.Model(&model.Inbound{}).Where("settings LIKE ?", "%"+clientEmail+"%").First(inbound).Error
  586. if err != nil {
  587. return nil, err
  588. }
  589. return inbound, nil
  590. }