Class: LogEntries

Inherits:
Object
  • Object
show all
Defined in:
lib/log_entries.rb

Constant Summary collapse

REDIRECT_MAX =

number of permissable redirects

5
REDIRECT_WINDOW =

span of time to check redirects

5

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(log_file, output_file) ⇒ LogEntries

Returns a new instance of LogEntries.



10
11
12
13
# File 'lib/log_entries.rb', line 10

def initialize(log_file, output_file)
  @log_file, @output_file = log_file, output_file
  @entries = {}
end

Instance Attribute Details

#entriesObject (readonly)

Returns the value of attribute entries.



9
10
11
# File 'lib/log_entries.rb', line 9

def entries
  @entries
end

Instance Method Details

#add(log_entry) ⇒ Object



15
16
17
18
# File 'lib/log_entries.rb', line 15

def add(log_entry)
  @entries[log_entry.ip.to_s] ||= []
  @entries[log_entry.ip.to_s] << log_entry
end

#create_blocklistObject



49
50
51
52
53
54
55
56
57
58
59
60
61
# File 'lib/log_entries.rb', line 49

def create_blocklist
  new_blocks  = sketch_ips
  curr_blocks = []

  if(File.file?(@output_file))
    curr_blocks += File.read(@output_file).split("\n")
  end

  results = (curr_blocks + new_blocks).uniq.
              reject(&:empty?).
              sort_by { |ip| IP.new(ip).to_binary }
  File.write(@output_file, results.join("\n"))
end

#exceeds_window(time_arr) ⇒ Object



43
44
45
46
47
# File 'lib/log_entries.rb', line 43

def exceeds_window(time_arr)
  return false if time_arr.count < REDIRECT_MAX
  return true  if (time_arr[REDIRECT_MAX - 1] - time_arr.first) < REDIRECT_WINDOW
  exceeds_window(time_arr[1..-1])
end

#sketch?(ip) ⇒ Boolean

Returns:

  • (Boolean)


20
21
22
23
24
25
26
27
# File 'lib/log_entries.rb', line 20

def sketch?(ip)
  return false unless entries[ip.to_s]
  redirects = entries[ip.to_s].select{ |entry| entry.redirect? }

  ip.sketch? &&
    redirects.count > REDIRECT_MAX &&
    exceeds_window(redirects.map(&:time))
end

#sketch_ipsObject



29
30
31
32
33
34
35
36
37
38
39
40
41
# File 'lib/log_entries.rb', line 29

def sketch_ips
  File.open(@log_file, 'r').each_line do |line|
    if(entry = LogEntry.parse(line))
      self.add(LogEntry.new(entry))
    end
  end

  sketchy = []
  self.entries.values.map(&:first).each do |entry|
    sketchy << entry.ip.to_s if self.sketch?(entry.ip)
  end
  sketchy
end