check_client_ip_job.go 21 KB

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