check_client_ip_job.go 6.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285
  1. package job
  2. import (
  3. "encoding/json"
  4. "os"
  5. "regexp"
  6. "x-ui/database"
  7. "x-ui/database/model"
  8. "x-ui/logger"
  9. "x-ui/web/service"
  10. "x-ui/xray"
  11. "sort"
  12. "strings"
  13. "time"
  14. )
  15. type CheckClientIpJob struct {
  16. xrayService service.XrayService
  17. }
  18. var job *CheckClientIpJob
  19. var disAllowedIps []string
  20. func NewCheckClientIpJob() *CheckClientIpJob {
  21. job = new(CheckClientIpJob)
  22. return job
  23. }
  24. func (j *CheckClientIpJob) Run() {
  25. logger.Debug("Check Client IP Job...")
  26. if hasLimitIp() {
  27. processLogFile()
  28. }
  29. blockedIps := []byte(strings.Join(disAllowedIps, ","))
  30. // check if file exists, if not create one
  31. _, err := os.Stat(xray.GetBlockedIPsPath())
  32. if os.IsNotExist(err) {
  33. _, err = os.OpenFile(xray.GetBlockedIPsPath(), os.O_RDWR|os.O_CREATE, 0755)
  34. checkError(err)
  35. }
  36. err = os.WriteFile(xray.GetBlockedIPsPath(), blockedIps, 0755)
  37. checkError(err)
  38. }
  39. func 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 processLogFile() {
  63. accessLogPath := 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. 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 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 := GetInboundClientIps(clientEmail)
  100. sort.Strings(ips)
  101. if err != nil {
  102. addInboundClientIps(clientEmail, ips)
  103. } else {
  104. shouldCleanLog = updateInboundClientIps(inboundClientIps, clientEmail, ips)
  105. }
  106. }
  107. time.Sleep(time.Second * 5)
  108. //added 5 seconds delay before cleaning logs to reduce chance of logging IP that already has been banned
  109. if shouldCleanLog {
  110. // clean log
  111. if err := os.Truncate(GetAccessLogPath(), 0); err != nil {
  112. checkError(err)
  113. }
  114. }
  115. }
  116. func GetAccessLogPath() string {
  117. config, err := os.ReadFile(xray.GetConfigPath())
  118. checkError(err)
  119. jsonConfig := map[string]interface{}{}
  120. err = json.Unmarshal([]byte(config), &jsonConfig)
  121. checkError(err)
  122. if jsonConfig["log"] != nil {
  123. jsonLog := jsonConfig["log"].(map[string]interface{})
  124. if jsonLog["access"] != nil {
  125. accessLogPath := jsonLog["access"].(string)
  126. return accessLogPath
  127. }
  128. }
  129. return ""
  130. }
  131. func checkError(e error) {
  132. if e != nil {
  133. logger.Warning("client ip job err:", e)
  134. }
  135. }
  136. func 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 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 addInboundClientIps(clientEmail string, ips []string) error {
  154. inboundClientIps := &model.InboundClientIps{}
  155. jsonIps, err := json.Marshal(ips)
  156. 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 updateInboundClientIps(inboundClientIps *model.InboundClientIps, clientEmail string, ips []string) bool {
  175. jsonIps, err := json.Marshal(ips)
  176. checkError(err)
  177. inboundClientIps.ClientEmail = clientEmail
  178. inboundClientIps.Ips = string(jsonIps)
  179. // check inbound limitation
  180. inbound, err := GetInboundByEmail(clientEmail)
  181. 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. for _, client := range clients {
  191. if client.Email == clientEmail {
  192. limitIp := client.LimitIP
  193. if limitIp != 0 {
  194. shouldCleanLog = true
  195. if limitIp < len(ips) && inbound.Enable {
  196. disAllowedIps = append(disAllowedIps, ips[limitIp:]...)
  197. for i := limitIp; i < len(ips); i++ {
  198. logger.Notice("[LIMIT_IP] Email=", clientEmail, " SRC=", ips[i])
  199. }
  200. }
  201. }
  202. }
  203. }
  204. logger.Debug("disAllowedIps ", disAllowedIps)
  205. sort.Strings(disAllowedIps)
  206. db := database.GetDB()
  207. err = db.Save(inboundClientIps).Error
  208. if err != nil {
  209. return shouldCleanLog
  210. }
  211. return shouldCleanLog
  212. }
  213. func DisableInbound(id int) error {
  214. db := database.GetDB()
  215. result := db.Model(model.Inbound{}).
  216. Where("id = ? and enable = ?", id, true).
  217. Update("enable", false)
  218. err := result.Error
  219. logger.Warning("disable inbound with id:", id)
  220. if err == nil {
  221. job.xrayService.SetToNeedRestart()
  222. }
  223. return err
  224. }
  225. func GetInboundByEmail(clientEmail string) (*model.Inbound, error) {
  226. db := database.GetDB()
  227. var inbounds *model.Inbound
  228. err := db.Model(model.Inbound{}).Where("settings LIKE ?", "%"+clientEmail+"%").Find(&inbounds).Error
  229. if err != nil {
  230. return nil, err
  231. }
  232. return inbounds, nil
  233. }