func (self RedisDB) UnbanAddr(addr string) (err error) { _, err = self.client.Del(IP_BAN_PREFIX + addr).Result() isnet, ipnet := util.IsSubnet(addr) var start string var range_start string if isnet { min, max := util.IPNet2MinMax(ipnet) range_start = util.ZeroIPString(min) start = util.ZeroIPString(max) } else { _, err = self.client.Del(IP_BAN_PREFIX + addr).Result() return } res, err := self.client.ZRangeByLex(IP_RANGE_BAN_KR, redis.ZRangeByScore{Min: "[" + start, Max: "+", Count: 1}).Result() if err == nil && len(res) > 0 { var range_min string range_max := res[0] range_min, err = self.client.HGet(IP_RANGE_BAN_PREFIX+range_max, "start").Result() if err != nil { return } banned := strings.Compare(range_start, range_min) >= 0 if banned { self.client.ZRem(IP_RANGE_BAN_KR, range_max) self.client.Del(IP_RANGE_BAN_PREFIX + range_max) } } return }
func (self RedisDB) CheckIPBanned(addr string) (banned bool, err error) { banned, err = self.client.Exists(IP_BAN_PREFIX + addr).Result() if banned { return } isnet, ipnet := util.IsSubnet(addr) var start string var range_start string if isnet { min, max := util.IPNet2MinMax(ipnet) range_start = util.ZeroIPString(min) start = util.ZeroIPString(max) } else { ip := net.ParseIP(addr) if ip == nil { return false, errors.New("Couldn't parse IP") } start = util.ZeroIPString(ip) range_start = start } res, err := self.client.ZRangeByLex(IP_RANGE_BAN_KR, redis.ZRangeByScore{Min: "[" + start, Max: "+", Count: 1}).Result() if err == nil && len(res) > 0 { var range_min string range_max := res[0] range_min, err = self.client.HGet(IP_RANGE_BAN_PREFIX+range_max, "start").Result() if err != nil { return } banned = strings.Compare(range_start, range_min) >= 0 } return }
func (self RedisDB) GetMessageIDByCIDR(cidr *net.IPNet) (msgids []string, err error) { min, max := util.IPNet2MinMax(cidr) start := util.ZeroIPString(min) stop := util.ZeroIPString(max) res, err := self.client.ZRangeByLex(IP_WKR, redis.ZRangeByScore{Min: "[" + start, Max: "[" + stop}).Result() if err == nil && len(res) > 0 { for _, ip := range res { posts, _ := self.client.SMembers(IP_ARTICLE_KR_PREFIX + ip).Result() msgids = append(msgids, posts...) } } return }
func (self RedisDB) BanAddr(addr string) (err error) { isnet, ipnet := util.IsSubnet(addr) if !isnet { _, err = self.client.HMSet(IP_BAN_PREFIX+addr, "addr", addr, "made", strconv.Itoa(int(util.TimeNow()))).Result() return } isBanned, err := self.CheckIPBanned(addr) if !isBanned && err == nil { //make sure this range isn't banned already min, max := util.IPNet2MinMax(ipnet) start := util.ZeroIPString(min) end := util.ZeroIPString(max) self.clearIPRange(start, end) //delete all banned ranges that are contained within this range _, err = self.client.ZAdd(IP_RANGE_BAN_KR, redis.Z{Score: 0.0, Member: end}).Result() if err != nil { return } _, err = self.client.HMSet(IP_RANGE_BAN_PREFIX+end, "start", start, "end", end, "made", strconv.Itoa(int(util.TimeNow()))).Result() } return }