check_client_ip_job.go 19 KB

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