check_client_ip_job.go 7.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329
  1. package job
  2. import (
  3. "bufio"
  4. "encoding/json"
  5. "io"
  6. "log"
  7. "os"
  8. "os/exec"
  9. "regexp"
  10. "sort"
  11. "strings"
  12. "time"
  13. "x-ui/database"
  14. "x-ui/database/model"
  15. "x-ui/logger"
  16. "x-ui/xray"
  17. )
  18. type CheckClientIpJob struct {
  19. lastClear int64
  20. disAllowedIps []string
  21. }
  22. var job *CheckClientIpJob
  23. func NewCheckClientIpJob() *CheckClientIpJob {
  24. job = new(CheckClientIpJob)
  25. return job
  26. }
  27. func (j *CheckClientIpJob) Run() {
  28. if j.lastClear == 0 {
  29. j.lastClear = time.Now().Unix()
  30. }
  31. shouldClearAccessLog := false
  32. iplimitActive := j.hasLimitIp()
  33. f2bInstalled := j.checkFail2BanInstalled()
  34. isAccessLogAvailable := j.checkAccessLogAvailable(iplimitActive)
  35. if iplimitActive {
  36. if f2bInstalled && isAccessLogAvailable {
  37. shouldClearAccessLog = j.processLogFile()
  38. } else {
  39. if !f2bInstalled {
  40. logger.Warning("[iplimit] fail2ban is not installed. IP limiting may not work properly.")
  41. }
  42. }
  43. }
  44. if shouldClearAccessLog || (isAccessLogAvailable && time.Now().Unix()-j.lastClear > 3600) {
  45. j.clearAccessLog()
  46. }
  47. }
  48. func (j *CheckClientIpJob) clearAccessLog() {
  49. logAccessP, err := os.OpenFile(xray.GetAccessPersistentLogPath(), os.O_CREATE|os.O_APPEND|os.O_WRONLY, 0o644)
  50. j.checkError(err)
  51. // get access log path to open it
  52. accessLogPath, err := xray.GetAccessLogPath()
  53. j.checkError(err)
  54. // reopen the access log file for reading
  55. file, err := os.Open(accessLogPath)
  56. j.checkError(err)
  57. // copy access log content to persistent file
  58. _, err = io.Copy(logAccessP, file)
  59. j.checkError(err)
  60. // close the file after copying content
  61. logAccessP.Close()
  62. file.Close()
  63. // clean access log
  64. err = os.Truncate(accessLogPath, 0)
  65. j.checkError(err)
  66. j.lastClear = time.Now().Unix()
  67. }
  68. func (j *CheckClientIpJob) hasLimitIp() bool {
  69. db := database.GetDB()
  70. var inbounds []*model.Inbound
  71. err := db.Model(model.Inbound{}).Find(&inbounds).Error
  72. if err != nil {
  73. return false
  74. }
  75. for _, inbound := range inbounds {
  76. if inbound.Settings == "" {
  77. continue
  78. }
  79. settings := map[string][]model.Client{}
  80. json.Unmarshal([]byte(inbound.Settings), &settings)
  81. clients := settings["clients"]
  82. for _, client := range clients {
  83. limitIp := client.LimitIP
  84. if limitIp > 0 {
  85. return true
  86. }
  87. }
  88. }
  89. return false
  90. }
  91. func (j *CheckClientIpJob) processLogFile() bool {
  92. accessLogPath, err := xray.GetAccessLogPath()
  93. j.checkError(err)
  94. file, err := os.Open(accessLogPath)
  95. j.checkError(err)
  96. InboundClientIps := make(map[string][]string)
  97. scanner := bufio.NewScanner(file)
  98. for scanner.Scan() {
  99. line := scanner.Text()
  100. ipRegx, _ := regexp.Compile(`from \[?([0-9a-fA-F:.]+)\]?:\d+ accepted`)
  101. emailRegx, _ := regexp.Compile(`email: (\S+)$`)
  102. matches := ipRegx.FindStringSubmatch(line)
  103. if len(matches) > 1 {
  104. ip := matches[1]
  105. if ip == "127.0.0.1" || ip == "::1" {
  106. continue
  107. }
  108. matchesEmail := emailRegx.FindString(line)
  109. if matchesEmail == "" {
  110. continue
  111. }
  112. matchesEmail = strings.Split(matchesEmail, "email: ")[1]
  113. if InboundClientIps[matchesEmail] != nil {
  114. if j.contains(InboundClientIps[matchesEmail], ip) {
  115. continue
  116. }
  117. InboundClientIps[matchesEmail] = append(InboundClientIps[matchesEmail], ip)
  118. } else {
  119. InboundClientIps[matchesEmail] = append(InboundClientIps[matchesEmail], ip)
  120. }
  121. }
  122. }
  123. j.checkError(scanner.Err())
  124. file.Close()
  125. shouldCleanLog := false
  126. for clientEmail, ips := range InboundClientIps {
  127. inboundClientIps, err := j.getInboundClientIps(clientEmail)
  128. sort.Strings(ips)
  129. if err != nil {
  130. j.addInboundClientIps(clientEmail, ips)
  131. } else {
  132. shouldCleanLog = j.updateInboundClientIps(inboundClientIps, clientEmail, ips)
  133. }
  134. }
  135. return shouldCleanLog
  136. }
  137. func (j *CheckClientIpJob) checkFail2BanInstalled() bool {
  138. cmd := "fail2ban-client"
  139. args := []string{"-h"}
  140. err := exec.Command(cmd, args...).Run()
  141. return err == nil
  142. }
  143. func (j *CheckClientIpJob) checkAccessLogAvailable(iplimitActive bool) bool {
  144. accessLogPath, err := xray.GetAccessLogPath()
  145. if err != nil {
  146. return false
  147. }
  148. if accessLogPath == "none" || accessLogPath == "" {
  149. if iplimitActive {
  150. logger.Warning("Access log path is not set, and IP limit is active. Please configure the access log path.")
  151. }
  152. return false
  153. }
  154. return true
  155. }
  156. func (j *CheckClientIpJob) checkError(e error) {
  157. if e != nil {
  158. logger.Warning("client ip job err:", e)
  159. }
  160. }
  161. func (j *CheckClientIpJob) contains(s []string, str string) bool {
  162. for _, v := range s {
  163. if v == str {
  164. return true
  165. }
  166. }
  167. return false
  168. }
  169. func (j *CheckClientIpJob) getInboundClientIps(clientEmail string) (*model.InboundClientIps, error) {
  170. db := database.GetDB()
  171. InboundClientIps := &model.InboundClientIps{}
  172. err := db.Model(model.InboundClientIps{}).Where("client_email = ?", clientEmail).First(InboundClientIps).Error
  173. if err != nil {
  174. return nil, err
  175. }
  176. return InboundClientIps, nil
  177. }
  178. func (j *CheckClientIpJob) addInboundClientIps(clientEmail string, ips []string) error {
  179. inboundClientIps := &model.InboundClientIps{}
  180. jsonIps, err := json.Marshal(ips)
  181. j.checkError(err)
  182. inboundClientIps.ClientEmail = clientEmail
  183. inboundClientIps.Ips = string(jsonIps)
  184. db := database.GetDB()
  185. tx := db.Begin()
  186. defer func() {
  187. if err == nil {
  188. tx.Commit()
  189. } else {
  190. tx.Rollback()
  191. }
  192. }()
  193. err = tx.Save(inboundClientIps).Error
  194. if err != nil {
  195. return err
  196. }
  197. return nil
  198. }
  199. func (j *CheckClientIpJob) updateInboundClientIps(inboundClientIps *model.InboundClientIps, clientEmail string, ips []string) bool {
  200. jsonIps, err := json.Marshal(ips)
  201. if err != nil {
  202. logger.Error("failed to marshal IPs to JSON:", err)
  203. return false
  204. }
  205. inboundClientIps.ClientEmail = clientEmail
  206. inboundClientIps.Ips = string(jsonIps)
  207. // Fetch inbound settings by client email
  208. inbound, err := j.getInboundByEmail(clientEmail)
  209. if err != nil {
  210. logger.Errorf("failed to fetch inbound settings for email %s: %s", clientEmail, err)
  211. return false
  212. }
  213. if inbound.Settings == "" {
  214. logger.Debug("wrong data:", inbound)
  215. return false
  216. }
  217. // Unmarshal settings to get client limits
  218. settings := map[string][]model.Client{}
  219. json.Unmarshal([]byte(inbound.Settings), &settings)
  220. clients := settings["clients"]
  221. shouldCleanLog := false
  222. j.disAllowedIps = []string{}
  223. // Open log file for IP limits
  224. logIpFile, err := os.OpenFile(xray.GetIPLimitLogPath(), os.O_CREATE|os.O_APPEND|os.O_WRONLY, 0644)
  225. if err != nil {
  226. logger.Errorf("failed to open IP limit log file: %s", err)
  227. return false
  228. }
  229. defer logIpFile.Close()
  230. log.SetOutput(logIpFile)
  231. log.SetFlags(log.LstdFlags)
  232. // Check client IP limits
  233. for _, client := range clients {
  234. if client.Email == clientEmail {
  235. limitIp := client.LimitIP
  236. if limitIp > 0 && inbound.Enable {
  237. shouldCleanLog = true
  238. if limitIp < len(ips) {
  239. j.disAllowedIps = append(j.disAllowedIps, ips[limitIp:]...)
  240. for i := limitIp; i < len(ips); i++ {
  241. log.Printf("[LIMIT_IP] Email = %s || SRC = %s", clientEmail, ips[i])
  242. }
  243. }
  244. }
  245. }
  246. }
  247. sort.Strings(j.disAllowedIps)
  248. if len(j.disAllowedIps) > 0 {
  249. logger.Debug("disAllowedIps:", j.disAllowedIps)
  250. }
  251. db := database.GetDB()
  252. err = db.Save(inboundClientIps).Error
  253. if err != nil {
  254. logger.Error("failed to save inboundClientIps:", err)
  255. return false
  256. }
  257. return shouldCleanLog
  258. }
  259. func (j *CheckClientIpJob) getInboundByEmail(clientEmail string) (*model.Inbound, error) {
  260. db := database.GetDB()
  261. var inbounds *model.Inbound
  262. err := db.Model(model.Inbound{}).Where("settings LIKE ?", "%"+clientEmail+"%").Find(&inbounds).Error
  263. if err != nil {
  264. return nil, err
  265. }
  266. return inbounds, nil
  267. }