check_client_ip_job.go 6.4 KB

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