check_client_ip_job.go 6.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272
  1. package job
  2. import (
  3. "encoding/json"
  4. "log"
  5. "os"
  6. "regexp"
  7. "sort"
  8. "strings"
  9. "time"
  10. "x-ui/database"
  11. "x-ui/database/model"
  12. "x-ui/logger"
  13. "x-ui/xray"
  14. )
  15. type CheckClientIpJob struct{}
  16. var job *CheckClientIpJob
  17. var disAllowedIps []string
  18. var ipFiles = []string{
  19. xray.GetIPLimitLogPath(),
  20. xray.GetIPLimitBannedLogPath(),
  21. xray.GetAccessPersistentLogPath(),
  22. }
  23. func NewCheckClientIpJob() *CheckClientIpJob {
  24. job = new(CheckClientIpJob)
  25. return job
  26. }
  27. func (j *CheckClientIpJob) Run() {
  28. // create files required for iplimit if not exists
  29. for i := 0; i < len(ipFiles); i++ {
  30. file, err := os.OpenFile(ipFiles[i], os.O_CREATE|os.O_APPEND|os.O_RDWR, 0644)
  31. j.checkError(err)
  32. defer file.Close()
  33. }
  34. // check for limit ip
  35. if j.hasLimitIp() {
  36. j.processLogFile()
  37. }
  38. }
  39. func (j *CheckClientIpJob) hasLimitIp() bool {
  40. db := database.GetDB()
  41. var inbounds []*model.Inbound
  42. err := db.Model(model.Inbound{}).Find(&inbounds).Error
  43. if err != nil {
  44. return false
  45. }
  46. for _, inbound := range inbounds {
  47. if inbound.Settings == "" {
  48. continue
  49. }
  50. settings := map[string][]model.Client{}
  51. json.Unmarshal([]byte(inbound.Settings), &settings)
  52. clients := settings["clients"]
  53. for _, client := range clients {
  54. limitIp := client.LimitIP
  55. if limitIp > 0 {
  56. return true
  57. }
  58. }
  59. }
  60. return false
  61. }
  62. func (j *CheckClientIpJob) processLogFile() {
  63. accessLogPath := xray.GetAccessLogPath()
  64. if accessLogPath == "" {
  65. logger.Warning("access.log doesn't exist in your config.json")
  66. return
  67. }
  68. data, err := os.ReadFile(accessLogPath)
  69. InboundClientIps := make(map[string][]string)
  70. j.checkError(err)
  71. lines := strings.Split(string(data), "\n")
  72. for _, line := range lines {
  73. ipRegx, _ := regexp.Compile(`[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+`)
  74. emailRegx, _ := regexp.Compile(`email:.+`)
  75. matchesIp := ipRegx.FindString(line)
  76. if len(matchesIp) > 0 {
  77. ip := string(matchesIp)
  78. if ip == "127.0.0.1" || ip == "1.1.1.1" {
  79. continue
  80. }
  81. matchesEmail := emailRegx.FindString(line)
  82. if matchesEmail == "" {
  83. continue
  84. }
  85. matchesEmail = strings.TrimSpace(strings.Split(matchesEmail, "email: ")[1])
  86. if InboundClientIps[matchesEmail] != nil {
  87. if j.contains(InboundClientIps[matchesEmail], ip) {
  88. continue
  89. }
  90. InboundClientIps[matchesEmail] = append(InboundClientIps[matchesEmail], ip)
  91. } else {
  92. InboundClientIps[matchesEmail] = append(InboundClientIps[matchesEmail], ip)
  93. }
  94. }
  95. }
  96. disAllowedIps = []string{}
  97. shouldCleanLog := false
  98. for clientEmail, ips := range InboundClientIps {
  99. inboundClientIps, err := j.getInboundClientIps(clientEmail)
  100. sort.Strings(ips)
  101. if err != nil {
  102. j.addInboundClientIps(clientEmail, ips)
  103. } else {
  104. shouldCleanLog = j.updateInboundClientIps(inboundClientIps, clientEmail, ips)
  105. }
  106. }
  107. // added delay before cleaning logs to reduce chance of logging IP that already has been banned
  108. time.Sleep(time.Second * 2)
  109. if shouldCleanLog {
  110. // copy access log to persistent file
  111. logAccessP, err := os.OpenFile(xray.GetAccessPersistentLogPath(), os.O_CREATE|os.O_APPEND|os.O_RDWR, 0644)
  112. j.checkError(err)
  113. input, err := os.ReadFile(accessLogPath)
  114. j.checkError(err)
  115. if _, err := logAccessP.Write(input); err != nil {
  116. j.checkError(err)
  117. }
  118. defer logAccessP.Close()
  119. // clean access log
  120. if err := os.Truncate(xray.GetAccessLogPath(), 0); err != nil {
  121. j.checkError(err)
  122. }
  123. }
  124. }
  125. func (j *CheckClientIpJob) checkError(e error) {
  126. if e != nil {
  127. logger.Warning("client ip job err:", e)
  128. }
  129. }
  130. func (j *CheckClientIpJob) contains(s []string, str string) bool {
  131. for _, v := range s {
  132. if v == str {
  133. return true
  134. }
  135. }
  136. return false
  137. }
  138. func (j *CheckClientIpJob) getInboundClientIps(clientEmail string) (*model.InboundClientIps, error) {
  139. db := database.GetDB()
  140. InboundClientIps := &model.InboundClientIps{}
  141. err := db.Model(model.InboundClientIps{}).Where("client_email = ?", clientEmail).First(InboundClientIps).Error
  142. if err != nil {
  143. return nil, err
  144. }
  145. return InboundClientIps, nil
  146. }
  147. func (j *CheckClientIpJob) addInboundClientIps(clientEmail string, ips []string) error {
  148. inboundClientIps := &model.InboundClientIps{}
  149. jsonIps, err := json.Marshal(ips)
  150. j.checkError(err)
  151. inboundClientIps.ClientEmail = clientEmail
  152. inboundClientIps.Ips = string(jsonIps)
  153. db := database.GetDB()
  154. tx := db.Begin()
  155. defer func() {
  156. if err == nil {
  157. tx.Commit()
  158. } else {
  159. tx.Rollback()
  160. }
  161. }()
  162. err = tx.Save(inboundClientIps).Error
  163. if err != nil {
  164. return err
  165. }
  166. return nil
  167. }
  168. func (j *CheckClientIpJob) updateInboundClientIps(inboundClientIps *model.InboundClientIps, clientEmail string, ips []string) bool {
  169. jsonIps, err := json.Marshal(ips)
  170. j.checkError(err)
  171. inboundClientIps.ClientEmail = clientEmail
  172. inboundClientIps.Ips = string(jsonIps)
  173. // check inbound limitation
  174. inbound, err := j.getInboundByEmail(clientEmail)
  175. j.checkError(err)
  176. if inbound.Settings == "" {
  177. logger.Debug("wrong data ", inbound)
  178. return false
  179. }
  180. settings := map[string][]model.Client{}
  181. json.Unmarshal([]byte(inbound.Settings), &settings)
  182. clients := settings["clients"]
  183. shouldCleanLog := false
  184. // create iplimit log file channel
  185. logIpFile, err := os.OpenFile(xray.GetIPLimitLogPath(), os.O_CREATE|os.O_APPEND|os.O_RDWR, 0644)
  186. if err != nil {
  187. logger.Errorf("failed to create or open ip limit log file: %s", err)
  188. }
  189. defer logIpFile.Close()
  190. log.SetOutput(logIpFile)
  191. log.SetFlags(log.LstdFlags)
  192. for _, client := range clients {
  193. if client.Email == clientEmail {
  194. limitIp := client.LimitIP
  195. if limitIp != 0 {
  196. shouldCleanLog = true
  197. if limitIp < len(ips) && inbound.Enable {
  198. disAllowedIps = append(disAllowedIps, ips[limitIp:]...)
  199. for i := limitIp; i < len(ips); i++ {
  200. log.Printf("[LIMIT_IP] Email = %s || SRC = %s", clientEmail, ips[i])
  201. }
  202. }
  203. }
  204. }
  205. }
  206. logger.Debug("disAllowedIps ", disAllowedIps)
  207. sort.Strings(disAllowedIps)
  208. db := database.GetDB()
  209. err = db.Save(inboundClientIps).Error
  210. if err != nil {
  211. return shouldCleanLog
  212. }
  213. return shouldCleanLog
  214. }
  215. func (j *CheckClientIpJob) getInboundByEmail(clientEmail string) (*model.Inbound, error) {
  216. db := database.GetDB()
  217. var inbounds *model.Inbound
  218. err := db.Model(model.Inbound{}).Where("settings LIKE ?", "%"+clientEmail+"%").Find(&inbounds).Error
  219. if err != nil {
  220. return nil, err
  221. }
  222. return inbounds, nil
  223. }