check_client_ip_job.go 7.0 KB

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