summaryrefslogtreecommitdiffstats
path: root/features/support/helpers/net_helper.rb
blob: 29119195da5a94610aeae65b432e3bf1a071b889 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
#
# Sniffer is a very dumb wrapper to start and stop tcpdumps instances, possibly
# with customized filters. Captured traffic is stored in files whose name
# depends on the sniffer name. The resulting captured packets for each sniffers
# can be accessed as an array through its `packets` method.
#
# Use of more rubyish internal ways to sniff a network like with pcap-able gems
# is waaay to much resource consumming, notmuch reliable and soooo slow. Let's
# not bother too much with that. :)
#
# Should put all that in a Module.

class Sniffer

  attr_reader :name, :pcap_file, :pid

  def initialize(name, bridge_name)
    @name = name
    @bridge_name = bridge_name
    @bridge_mac = File.open("/sys/class/net/#{@bridge_name}/address", "rb").read.chomp
    @pcap_file = "#{$tmp_dir}/#{name}.pcap"
  end

  def capture(filter="not ether src host #{@bridge_mac} and not ether proto \\arp and not ether proto \\rarp")
    job = IO.popen("/usr/sbin/tcpdump -n -i #{@bridge_name} -w #{@pcap_file} -U '#{filter}' >/dev/null 2>&1")
    @pid = job.pid
  end

  def stop
    begin
      Process.kill("TERM", @pid)
    rescue
      # noop
    end
  end

  def clear
    if File.exist?(@pcap_file)
      File.delete(@pcap_file)
    end
  end
end