check_client_ip_job.go 7.2 KB

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