Pcap.pm

filter: Statementstmt 88.8% 16 / 18 Branchbran n/a Conditioncond n/a MC/DCmcdc n/a Subroutinesub 100% 6 / 6 Podpod n/a totaltotal 91.6% 22 / 24 CC 1 SCAR 0.5
CC
1
Cov
89%
BEGIN
1.3
BEGIN
1.0
BEGIN
1.0
CRAP 1.0
« Pcap/Utils.pm ↑ Summary
1 package AnyEvent::Pcap;
2 5 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
3 5 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
4 5 ▶use Carp;
Subroutine BEGIN: called CC=1 SCAR=0.0
5 5 ▶use AnyEvent;
Subroutine BEGIN: called CC=1 SCAR=0.0
6 5 ▶use AnyEvent::Pcap::Utils;
Subroutine BEGIN: called CC=1 SCAR=0.0
7 0 ▶use Net::Pcap;
Subroutine BEGIN: called CC=1 SCAR=2.6
8 use base qw(Class::Accessor::Fast);
9  
10 our $VERSION = '0.00005';
11  
12 __PACKAGE__->mk_accessors($_) for qw(utils device filter packet_handler fd timeout);
13  
14 # be compatible with old versions of Net::Pcap
15 if ($Net::Pcap::VERSION < 0.15) {
16 *Net::Pcap::pcap_lookupdev = \&Net::Pcap::lookupdev;
17 *Net::Pcap::pcap_open_live = \&Net::Pcap::open_live;
18 *Net::Pcap::pcap_open_offline = \&Net::Pcap::open_offline;
19 *Net::Pcap::pcap_file = \&Net::Pcap::file;
20 }
21  
22 sub new {
23 my $class = shift;
24 my $self = bless {@_}, $class;
25 $self->utils( AnyEvent::Pcap::Utils->new );
26 return $self;
27 }
28  
29 sub _setup_pcap {
30 my $self = shift;
31  
32 my $err;
33 my $device = $self->device || sub {
34 $self->device( Net::Pcap::pcap_lookupdev( \$err ) );
35 }
36 ->();
37 croak $err if $err;
38  
39 my $pcap;
40 my $timeout = $self->timeout || 0;
41 my $netmask = 0;
42  
43 if ($device =~ s/^file://) {
44 # open the file
45 $pcap = Net::Pcap::pcap_open_offline( $device, \$err );
46 croak $err if $err;
47  
48 # get its file descriptor
49 my $fd = Net::Pcap::pcap_file($pcap);
50 $self->fd($fd);
51 } else {
52 # open the device
53 $pcap = Net::Pcap::pcap_open_live( $device, 1024, 1, $timeout, \$err );
54 croak $err if $err;
55  
56 # get its file descriptor
57 my $fd = Net::Pcap::fileno($pcap);
58 $self->fd($fd);
59  
60 # get the associated network mask
61 Net::Pcap::lookupnet( $device, \my $address, \$netmask, \$err );
62 croak $err if $err;
63 }
64  
65 my $filter;
66 my $filter_string = $self->filter || sub {
67 $self->filter("");
68 }
69 ->();
70  
71 Net::Pcap::compile( $pcap, \$filter, $filter_string, 0, $netmask );
72 Net::Pcap::setfilter( $pcap, $filter );
73  
74 return $pcap;
75 }
76  
77 sub run {
78 my $self = shift;
79  
80 my $pcap = $self->_setup_pcap();
81  
82 my $packet_handler = $self->packet_handler || sub {
83 $self->packet_handler( sub { } );
84 }
85 ->();
86  
87 my $io;
88 $io = AnyEvent->io(
89 fh => $self->fd,
90 poll => 'r',
91 cb => sub {
92 my @pending;
93 Net::Pcap::dispatch(
94 $pcap, -1,
95 sub {
96 my $header = $_[1];
97 my $packet = $_[2];
98 push @{ $_[0] }, ( $header, $packet );
99 },
100 \@pending
101 );
102 $packet_handler->( @pending, $io );
103 }
104 );
105 }
106  
107 1;
108 __END__
« Pcap/Utils.pm ↑ Summary