File Coverage

blib/lib/IO/Socket/Packet.pm
Criterion Covered Total %
statement 62 131 47.3
branch 15 58 25.8
condition 5 7 71.4
subroutine 16 28 57.1
pod 18 19 94.7
total 116 243 47.7


line stmt bran cond sub pod time code
1             # You may distribute under the terms of either the GNU General Public License
2             # or the Artistic License (the same terms as Perl itself)
3             #
4             # (C) Paul Evans, 2009-2012 -- leonerd@leonerd.org.uk
5              
6             package IO::Socket::Packet;
7              
8 3     3   25929 use strict;
  3         7  
  3         139  
9 3     3   16 use warnings;
  3         5  
  3         123  
10 3     3   21 use base qw( IO::Socket );
  3         6  
  3         3995  
11              
12             our $VERSION = '0.10';
13              
14 3     3   109487 use Carp;
  3         8  
  3         156  
15              
16 3     3   1809 use POSIX qw( EAGAIN );
  3         16214  
  3         28  
17 3     3   2411 use Socket qw( AF_INET SOCK_STREAM SOCK_RAW );
  3         5  
  3         622  
18              
19 3         5601 use Socket::Packet qw(
20             AF_PACKET ETH_P_ALL
21             pack_sockaddr_ll unpack_sockaddr_ll
22             pack_packet_mreq
23             unpack_tpacket_stats
24             siocgstamp siocgstampns
25             siocgifindex siocgifname
26             recv_len
27              
28             SOL_PACKET
29              
30             PACKET_ADD_MEMBERSHIP
31             PACKET_DROP_MEMBERSHIP
32             PACKET_STATISTICS
33              
34             PACKET_MR_MULTICAST
35             PACKET_MR_PROMISC
36             PACKET_MR_ALLMULTI
37 3     3   720 );
  3         12  
38              
39             __PACKAGE__->register_domain( AF_PACKET );
40              
41             =head1 NAME
42              
43             C - Object interface to C domain sockets
44              
45             =head1 SYNOPSIS
46              
47             use IO::Socket::Packet;
48             use Socket::Packet qw( unpack_sockaddr_ll );
49              
50             my $sock = IO::Socket::Packet->new( IfIndex => 0 );
51              
52             while( my ( $protocol, $ifindex, $hatype, $pkttype, $addr ) =
53             $sock->recv_unpack( my $packet, 8192, 0 ) ) {
54              
55             ...
56             }
57              
58             =head1 DESCRIPTION
59              
60             This class provides an object interface to C sockets on Linux. It
61             is built upon L and inherits all the methods defined by this base
62             class.
63              
64             =cut
65              
66             =head1 CONSTRUCTOR
67              
68             =cut
69              
70             =head2 $sock = IO::Socket::Packet->new( %args )
71              
72             Creates a new C object. If any arguments are passed it
73             will be configured to contain a newly created socket handle, and be Ced
74             as required by the arguments. The recognised arguments are:
75              
76             =over 8
77              
78             =item Type => INT
79              
80             The socktype to use; should be either C or C. It not
81             supplied a default of C will be used.
82              
83             =item Protocol => INT
84              
85             Ethernet protocol number to bind to. To capture all protocols, use the
86             C constant (or omit this key, which implies that as a default).
87              
88             =item IfIndex => INT
89              
90             If supplied, binds the socket to the specified interface index. To bind to all
91             interfaces, use 0 (or omit this key, which implies that as a default).
92              
93             =item IfName => STRING
94              
95             If supplied, binds the socket to the interface with the specified name.
96              
97             =back
98              
99             =cut
100              
101             sub configure
102             {
103 3     3 0 28189 my $self = shift;
104 3         6 my ( $arg ) = @_;
105              
106 3   50     23 my $type = $arg->{Type} || SOCK_RAW;
107              
108 3 50       18 $self->socket( AF_PACKET, $type, 0 ) or return undef;
109              
110             # bind() arguments
111 3         145 my ( $protocol, $ifindex );
112              
113 3 50       14 $protocol = $arg->{Protocol} if exists $arg->{Protocol};
114 3 100       12 $ifindex = $arg->{IfIndex} if exists $arg->{IfIndex};
115              
116 3 100 66     16 if( !defined $ifindex and exists $arg->{IfName} ) {
117 1         12 $ifindex = siocgifindex( $self, $arg->{IfName} );
118 1 50       6 defined $ifindex or return undef;
119             }
120              
121 3 50 100     40 $self->bind( pack_sockaddr_ll(
    50          
122             defined $protocol ? $protocol : ETH_P_ALL,
123             $ifindex || 0,
124             0, 0, '' ) ) or return undef;
125              
126 3         60 return $self;
127             }
128              
129             =head1 METHODS
130              
131             =cut
132              
133             =head2 ( $addr, $len ) = $sock->recv_len( $buffer, $maxlen, $flags )
134              
135             Similar to Perl's C builtin, except it returns the packet length as an
136             explict return value. This may be useful if C<$flags> contains the
137             C flag, obtaining the true length of the packet on the wire, even
138             if this is longer than the data written in the buffer.
139              
140             =cut
141              
142             # don't actually need to implement it; the imported symbol works fine
143              
144             =head2 ( $protocol, $ifindex, $hatype, $pkttype, $addr, $len ) = $sock->recv_unpack( $buffer, $size, $flags )
145              
146             This method is a combination of C and C. If it
147             successfully receives a packet, it unpacks the address and returns the fields
148             from it, and the length of the received packet. If it fails, it returns an
149             empty list.
150              
151             If the ring-buffer has been set using C, it will automatically
152             be used by this method.
153              
154             =cut
155              
156             sub recv_unpack
157             {
158 0     0 1 0 my $self = shift;
159              
160 0 0       0 if( defined ${*$self}{packet_rx_ring} ) {
  0         0  
161 0 0       0 defined $self->wait_ring_frame( my $buffer, \my %info ) or return;
162              
163             # Copy to caller
164 0         0 $_[0] = $buffer;
165              
166 0         0 $self->done_ring_frame;
167              
168 0         0 ${*$self}{packet_ts_sec} = $info{tp_sec};
  0         0  
169 0         0 ${*$self}{packet_ts_nsec} = $info{tp_nsec};
  0         0  
170              
171 0         0 return ( $info{sll_protocol},
172             $info{sll_ifindex},
173             $info{sll_hatype},
174             $info{sll_pkttype},
175             $info{sll_addr},
176             $info{tp_len} );
177             }
178              
179 0 0       0 my ( $addr, $len ) = $self->recv_len( @_ ) or return;
180 0         0 return unpack_sockaddr_ll( $addr ), $len;
181             }
182              
183             =head2 $protocol = $sock->protocol
184              
185             Returns the ethertype protocol the socket is bound to.
186              
187             =cut
188              
189             sub protocol
190             {
191 2     2 1 2129 my $self = shift;
192 2         12 return (unpack_sockaddr_ll($self->sockname))[0];
193             }
194              
195             =head2 $ifindex = $sock->ifindex
196              
197             Returns the interface index the socket is bound to.
198              
199             =cut
200              
201             sub ifindex
202             {
203 5     5 1 682 my $self = shift;
204 5         16 return (unpack_sockaddr_ll($self->sockname))[1];
205             }
206              
207             =head2 $ifname = $sock->ifname
208              
209             Returns the name of the interface the socket is bound to.
210              
211             =cut
212              
213             sub ifname
214             {
215 3     3 1 916 my $self = shift;
216 3         8 return siocgifname( $self, $self->ifindex );
217             }
218              
219             =head2 $hatype = $sock->hatype
220              
221             Returns the hardware address type for the interface the socket is bound to.
222              
223             =cut
224              
225             sub hatype
226             {
227 2     2 1 620 my $self = shift;
228 2         10 return (unpack_sockaddr_ll($self->sockname))[2];
229             }
230              
231             =head2 $time = $sock->timestamp
232              
233             =head2 ( $sec, $usec ) = $sock->timestamp
234              
235             Returns the timestamp of the last received packet on the socket (as obtained
236             by the C C). In scalar context, returns a single
237             floating-point value in UNIX epoch seconds. In list context, returns the
238             number of seconds, and the number of microseconds.
239              
240             If the ring-buffer has been set using C, this method returns
241             the timestamp of the last packet received from it.
242              
243             =cut
244              
245             sub timestamp
246             {
247 1     1 1 367 my $self = shift;
248              
249 1 50       3 if( defined ${*$self}{packet_ts_sec} ) {
  1         6  
250 0         0 my $sec = delete ${*$self}{packet_ts_sec};
  0         0  
251 0         0 my $nsec = delete ${*$self}{packet_ts_nsec};
  0         0  
252              
253 0 0       0 return wantarray ? ( $sec, int($nsec/1000) ) : $sec + $nsec/1_000_000_000;
254             }
255              
256 1         20 return siocgstamp( $self );
257             }
258              
259             =head2 $time = $sock->timestamp_nano
260              
261             =head2 ( $sec, $nsec ) = $sock->timestamp_nano
262              
263             Returns the nanosecond-precise timestamp of the last received packet on the
264             socket (as obtained by the C C). In scalar context,
265             returns a single floating-point value in UNIX epoch seconds. In list context,
266             returns the number of seconds, and the number of nanoseconds.
267              
268             If the ring-buffer has been set using C, this method returns
269             the timestamp of the last packet received from it.
270              
271             =cut
272              
273             sub timestamp_nano
274             {
275 0     0 1 0 my $self = shift;
276              
277 0 0       0 if( defined ${*$self}{packet_ts_sec} ) {
  0         0  
278 0         0 my $sec = delete ${*$self}{packet_ts_sec};
  0         0  
279 0         0 my $nsec = delete ${*$self}{packet_ts_nsec};
  0         0  
280              
281 0 0       0 return wantarray ? ( $sec, $nsec ) : $sec + $nsec/1_000_000_000;
282             }
283              
284 0         0 return siocgstampns( $self );
285             }
286              
287             =head1 INTERFACE NAME UTILITIES
288              
289             The following methods are utilities around C and C.
290             If called on an object, they use the encapsulated socket. If called as class
291             methods, they will create a temporary socket to pass to the kernel, then close
292             it again.
293              
294             =cut
295              
296             =head2 $ifindex = $sock->ifname2index( $ifname )
297              
298             =head2 $ifindex = IO::Socket::Packet->ifname2index( $ifname )
299              
300             Returns the name for the given interface index, or C if it doesn't
301             exist.
302              
303             =cut
304              
305             sub ifname2index
306             {
307 1     1 1 613 my $self = shift;
308 1         3 my ( $ifname ) = @_;
309              
310 1         2 my $sock;
311 1 50       5 if( ref $self ) {
312 0         0 $sock = $self;
313             }
314             else {
315 1 50       30 socket( $sock, AF_INET, SOCK_STREAM, 0 ) or
316             croak "Cannot socket(AF_INET) - $!";
317             }
318              
319 1         29 return siocgifindex( $sock, $ifname );
320             }
321              
322             =head2 $ifname = $sock->ifindex2name( $ifindex )
323              
324             =head2 $ifname = IO::Socket::Packet->ifindex2name( $ifindex )
325              
326             Returns the index for the given interface name, or C if it doesn't
327             exist.
328              
329             =cut
330              
331             sub ifindex2name
332             {
333 2     2 1 25 my $self = shift;
334 2         5 my ( $ifindex ) = @_;
335              
336 2         25 my $sock;
337 2 50       11 if( ref $self ) {
338 0         0 $sock = $self;
339             }
340             else {
341 2 50       82 socket( $sock, AF_INET, SOCK_STREAM, 0 ) or
342             croak "Cannot socket(AF_INET) - $!";
343             }
344              
345 2         41 return siocgifname( $sock, $ifindex );
346             }
347              
348             sub _make_sockopt_int
349             {
350 0     0   0 my ( $optname ) = @_;
351              
352             # IO::Socket automatically handles the pack/unpack in this case
353              
354             sub {
355 0     0   0 my $sock = shift;
356              
357 0 0       0 if( @_ ) {
358 0         0 $sock->setsockopt( SOL_PACKET, $optname, $_[0] );
359             }
360             else {
361 0         0 return $sock->getsockopt( SOL_PACKET, $optname );
362             }
363 0         0 };
364             }
365              
366             =head1 SOCKET OPTION ACCESSORS
367              
368             =cut
369              
370             =head2 $sock->add_multicast( $addr, $ifindex )
371              
372             Adds the given multicast address on the given interface index. If the
373             interface index is not supplied, C<< $sock->ifindex >> is used.
374              
375             =cut
376              
377             sub add_multicast
378             {
379 0     0 1 0 my $self = shift;
380 0         0 my ( $addr, $ifindex ) = @_;
381 0 0       0 defined $ifindex or $ifindex = $self->ifindex;
382              
383 0         0 $self->setsockopt( SOL_PACKET, PACKET_ADD_MEMBERSHIP,
384             pack_packet_mreq( $ifindex, PACKET_MR_MULTICAST, $addr )
385             );
386             }
387              
388             =head2 $sock->drop_multicast( $addr, $ifindex )
389              
390             Drops the given multicast address on the given interface index. If the
391             interface index is not supplied, C<< $sock->ifindex >> is used.
392              
393             =cut
394              
395             sub drop_multicast
396             {
397 0     0 1 0 my $self = shift;
398 0         0 my ( $addr, $ifindex ) = @_;
399 0 0       0 defined $ifindex or $ifindex = $self->ifindex;
400              
401 0         0 $self->setsockopt( SOL_PACKET, PACKET_DROP_MEMBERSHIP,
402             pack_packet_mreq( $ifindex, PACKET_MR_MULTICAST, $addr )
403             );
404             }
405              
406             =head2 $sock->promisc( $promisc, $ifindex )
407              
408             Sets or clears the PACKET_MR_PROMISC flag on the given interface. If the
409             interface index is not supplied, C<< $sock->ifindex >> is used.
410              
411             =cut
412              
413             sub promisc
414             {
415 0     0 1 0 my $self = shift;
416 0         0 my ( $value, $ifindex ) = @_;
417 0 0       0 defined $ifindex or $ifindex = $self->ifindex;
418              
419 0 0       0 $self->setsockopt( SOL_PACKET, $value ? PACKET_ADD_MEMBERSHIP : PACKET_DROP_MEMBERSHIP,
420             pack_packet_mreq( $ifindex, PACKET_MR_PROMISC, "" )
421             );
422             }
423              
424             =head2 $sock->allmulti( $allmulti, $ifindex )
425              
426             Sets or clears the PACKET_MR_ALLMULTI flag on the given interface. If the
427             interface index is not supplied, C<< $sock->ifindex >> is used.
428              
429             =cut
430              
431             sub allmulti
432             {
433 0     0 1 0 my $self = shift;
434 0         0 my ( $value, $ifindex ) = @_;
435 0 0       0 defined $ifindex or $ifindex = $self->ifindex;
436              
437 0 0       0 $self->setsockopt( SOL_PACKET, $value ? PACKET_ADD_MEMBERSHIP : PACKET_DROP_MEMBERSHIP,
438             pack_packet_mreq( $ifindex, PACKET_MR_ALLMULTI, "" )
439             );
440             }
441              
442             =head2 $stats = $sock->statistics
443              
444             Returns the socket statistics. This will be a two-field hash containing
445             counts C, the total number of packets the socket has seen, and
446             C, the number of packets that could not stored because the buffer was
447             full.
448              
449             =cut
450              
451             sub statistics
452             {
453 1     1 1 22678 my $self = shift;
454              
455 1 50       18 my $stats = $self->getsockopt( SOL_PACKET, PACKET_STATISTICS )
456             or return;
457              
458 1         28 my %stats;
459 1         8 @stats{qw( packets drops)} = unpack_tpacket_stats( $stats );
460              
461 1         14 return \%stats;
462             }
463              
464             =head2 $val = $sock->origdev
465              
466             =head2 $sock->origdev( $val )
467              
468             Return or set the value of the C socket option.
469              
470             =cut
471              
472             if( defined &Socket::Packet::PACKET_ORIGDEV ) {
473             *origdev = _make_sockopt_int( Socket::Packet::PACKET_ORIGDEV() );
474             }
475              
476             =head1 RING-BUFFER METHODS
477              
478             These methods operate on the high-performance memory-mapped capture buffer.
479              
480             An example of how to use these methods for packet capture is included in the
481             module distribution; see F for more detail.
482              
483             =cut
484              
485             =head2 $size = $sock->setup_rx_ring( $frame_size, $frame_nr, $block_size )
486              
487             Sets up the ring-buffer on the object. This method is identical to the
488             C function C, except that the ring-buffer
489             variable is stored transparently within the C<$sock> object; the caller does
490             not need to manage it.
491              
492             Once this buffer is enabled, the C, C and
493             C methods will automatically use it instead of the regular
494             C+C interface.
495              
496             =cut
497              
498             sub setup_rx_ring
499             {
500 0     0 1   my $self = shift;
501 0           my ( $frame_size, $frame_nr, $block_size ) = @_;
502              
503 0           my $ret = Socket::Packet::setup_rx_ring( $self, $frame_size, $frame_nr, $block_size );
504 0 0         ${*$self}{packet_rx_ring} = 1 if defined $ret;
  0            
505              
506 0           return $ret;
507             }
508              
509             =head2 $len = $sock->get_ring_frame( $buffer, \%info )
510              
511             Receives the next packet from the ring-buffer. If there are no packets waiting
512             it will return undef. This method aliases the C<$buffer> variable to the
513             Ced packet buffer.
514              
515             For detail on the C<%info> hash, see L's C
516             function.
517              
518             Once the caller has finished with the C<$buffer> data, the C
519             method should be called to hand the frame buffer back to the kernel.
520              
521             =cut
522              
523             sub get_ring_frame
524             {
525 0     0 1   my $self = shift;
526              
527 0           return Socket::Packet::get_ring_frame( $self, $_[0], $_[1] );
528             }
529              
530             =head2 $len = $sock->wait_ring_frame( $buffer, \%info )
531              
532             If a packet is ready, this method sets C<$buffer> and C<%info> as per the
533             C method. If there are no packets waiting and the socket is
534             in blocking mode, it will C on the socket until a packet is
535             available. If the socket is in non-blocking mode, it will return false with
536             C<$!> set to C.
537              
538             For detail on the C<%info> hash, see L's C
539             function.
540              
541             Once the caller has finished with the C<$buffer> data, the C
542             method should be called to hand the frame buffer back to the kernel.
543              
544             =cut
545              
546             sub wait_ring_frame
547             {
548 0     0 1   my $self = shift;
549              
550 0           my $len;
551 0           while( !defined( $len = $self->get_ring_frame( $_[0], $_[1] ) ) ) {
552 0 0         $! = EAGAIN, return if not $self->blocking;
553              
554 0           my $rvec = '';
555 0           vec( $rvec, fileno $self, 1 ) = 1;
556 0 0         select( $rvec, undef, undef, undef ) or return;
557             }
558              
559 0           return $len;
560             }
561              
562             =head2 $sock->done_ring_frame
563              
564             Hands the current ring-buffer frame back to the kernel.
565              
566             =cut
567              
568             sub done_ring_frame
569             {
570 0     0 1   my $self = shift;
571              
572 0           Socket::Packet::done_ring_frame( $self );
573             }
574              
575             =head1 SEE ALSO
576              
577             =over 4
578              
579             =item *
580              
581             L - interface to Linux's C socket family
582              
583             =back
584              
585             =head1 AUTHOR
586              
587             Paul Evans
588              
589             =cut
590              
591             0x55AA;