check_client_ip_job.go 19 KB

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