Sha256: d71a1a6e53147967585adfd43f4db1cdca6f966b1ad2827a954ebd8e46d37a89

Contents?: true

Size: 1.52 KB

Versions: 10

Compression:

Stored size: 1.52 KB

Contents

# typed: ignore

# Copyright (c) 2015 Sqreen. All Rights Reserved.
# Please refer to our terms for more information: https://www.sqreen.com/terms.html

require 'ipaddr'
require 'sqreen/actions/actions_index'
require 'sqreen/trie'
require 'sqreen/prefix'

module Sqreen
  module Actions
    class IpRangesIndex < ActionsIndex
      def initialize
        @trie_v4 = Sqreen::Trie.new
        @trie_v6 = Sqreen::Trie.new(nil, nil, Socket::AF_INET6)
      end

      def index(params, action)
        ranges = parse_ip_ranges params

        ranges.each do |r|
          add_prefix r, action
        end
      end

      def actions_matching(client_ip)
        parsed_ip = IPAddr.new(client_ip.gsub(/%[^%\/]+/, ''))
        trie = parsed_ip.family == Socket::AF_INET6 ? @trie_v6 : @trie_v4
        return [] unless trie
        found = trie.search_matching(parsed_ip.to_i, parsed_ip.family)
        return [] unless found.size > 0

        Sqreen.log.debug("Client ip #{client_ip} matches #{found.inspect}")
        found.map(&:data)
      end

      private

      # returns array of prefixes in string form
      def parse_ip_ranges(params)
        ranges = params['ip_cidr']
        unless ranges && ranges.is_a?(Array) && !ranges.empty?
          raise 'no non-empty ip_cidr array present'
        end

        ranges
      end

      def add_prefix(prefix_str, data)
        prefix = Sqreen::Prefix.from_str(prefix_str, data)
        trie = prefix.family == Socket::AF_INET6 ? @trie_v6 : @trie_v4
        trie.insert prefix
      end
    end
  end
end

Version data entries

10 entries across 10 versions & 1 rubygems

Version Path
sqreen-1.25.1 lib/sqreen/actions/ip_ranges_index.rb
sqreen-1.25.0 lib/sqreen/actions/ip_ranges_index.rb
sqreen-1.24.3 lib/sqreen/actions/ip_ranges_index.rb
sqreen-1.24.2 lib/sqreen/actions/ip_ranges_index.rb
sqreen-1.24.1 lib/sqreen/actions/ip_ranges_index.rb
sqreen-1.24.0 lib/sqreen/actions/ip_ranges_index.rb
sqreen-1.23.2 lib/sqreen/actions/ip_ranges_index.rb
sqreen-1.23.1 lib/sqreen/actions/ip_ranges_index.rb
sqreen-1.23.0 lib/sqreen/actions/ip_ranges_index.rb
sqreen-1.22.1 lib/sqreen/actions/ip_ranges_index.rb