File Coverage

blib/lib/Socket/Packet.pm
Criterion Covered Total %
statement 11 11 100.0
branch n/a
condition n/a
subroutine 4 4 100.0
pod n/a
total 15 15 100.0


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-2025 -- leonerd@leonerd.org.uk
5              
6             package Socket::Packet 0.12;
7              
8 8     8   1569025 use v5.14;
  8         32  
9 8     8   49 use warnings;
  8         72  
  8         489  
10              
11 8     8   46 use Carp;
  8         13  
  8         595  
12              
13 8     8   46 use Exporter 'import';
  8         19  
  8         1474  
14             our @EXPORT_OK = qw(
15             pack_sockaddr_ll unpack_sockaddr_ll
16             pack_packet_mreq unpack_packet_mreq
17             unpack_tpacket_stats
18             siocgstamp
19             siocgstampns
20             siocgifindex
21             siocgifname
22             recv_len
23              
24             setup_rx_ring
25             get_ring_frame_status
26             get_ring_frame
27             done_ring_frame
28             );
29              
30             require XSLoader;
31             XSLoader::load( __PACKAGE__, our $VERSION );
32              
33             =head1 NAME
34              
35             C - interface to Linux's C socket family
36              
37             =head1 SYNOPSIS
38              
39             use Socket qw( SOCK_RAW );
40             use Socket::Packet qw(
41             PF_PACKET
42             ETH_P_ALL
43             pack_sockaddr_ll unpack_sockaddr_ll
44             );
45              
46             socket( my $sock, PF_PACKET, SOCK_RAW, 0 )
47             or die "Cannot socket() - $!\n";
48              
49             bind( $sock, pack_sockaddr_ll( ETH_P_ALL, 0, 0, 0, "" ) )
50             or die "Cannot bind() - $!\n";
51              
52             while( my $addr = recv( $sock, my $packet, 8192, 0 ) ) {
53             my ( $proto, $ifindex, $hatype, $pkttype, $addr )
54             = unpack_sockaddr_ll( $addr );
55              
56             ...
57             }
58              
59             =head1 DESCRIPTION
60              
61             To quote C:
62              
63             Packet sockets are used to receive or send raw packets at the device driver
64             (OSI Layer 2) level. They allow the user to implement protocol modules in
65             user space on top of the physical layer.
66              
67             Sockets in the C family get direct link-level access to the
68             underlying hardware (i.e. Ethernet or similar). They are usually used to
69             implement packet capturing, or sending of specially-constructed packets
70             or to implement protocols the underlying kernel does not recognise.
71              
72             The use of C sockets is usually restricted to privileged users
73             only.
74              
75             This module also provides various other support functions which wrap
76             Cs or socket options. This includes support for C,
77             the high-performance zero-copy packet receive buffering, if the underlying
78             platform supports it.
79              
80             =cut
81              
82             =head1 CONSTANTS
83              
84             The following constants are exported
85              
86             =over 8
87              
88             =item PF_PACKET
89              
90             The packet family (for C calls)
91              
92             =item AF_PACKET
93              
94             The address family
95              
96             =item PACKET_HOST
97              
98             This packet is inbound unicast for this host.
99              
100             =item PACKET_BROADCAST
101              
102             This packet is inbound broadcast.
103              
104             =item PACKET_MULTICAST
105              
106             This packet is inbound multicast.
107              
108             =item PACKET_OTHERHOST
109              
110             This packet is inbound unicast for another host.
111              
112             =item PACKET_OUTGOING
113              
114             This packet is outbound.
115              
116             =item ETH_P_ALL
117              
118             Pseudo-protocol number to capture all protocols.
119              
120             =item SOL_PACKET
121              
122             Socket option level for C and C.
123              
124             =back
125              
126             =cut
127              
128             =head1 SOCKET OPTIONS
129              
130             The following constants define socket options
131              
132             =over 8
133              
134             =item PACKET_STATISTICS (get; struct tpacket_stats)
135              
136             Packet received and drop counters.
137              
138             =item PACKET_ORIGDEV (get or set; int)
139              
140             Received packets will indicate the originally-received device, rather than the
141             apparent one. This mainly relates to Ethernet bonding or VLANs.
142              
143             This socket option is optional, and may not be provided on all platforms.
144              
145             =item PACKET_ADD_MEMBERSHIP (set; struct packet_mreq)
146              
147             =item PACKET_DROP_MEMBERSHIP (set; struct packet_mreq)
148              
149             Membership of multicast or broadcast groups, or set promiscuous mode.
150              
151             The C C field should be one of the following:
152              
153             =over 4
154              
155             =item PACKET_MR_MULTICAST
156              
157             A multicast group
158              
159             =item PACKET_MR_PROMISC
160              
161             Set or clear the promiscuous flag; the address is ignored
162              
163             =item PACKET_MR_ALLMULTI
164              
165             Set or clear the allmulti flag; the address is ignored
166              
167             =back
168              
169             =back
170              
171             =cut
172              
173             =head1 FUNCTIONS
174              
175             The following pair of functions operate on C address structures.
176             The meanings of the parameters are:
177              
178             =over 8
179              
180             =item protocol
181              
182             An ethertype protocol number. When using an address with C, the
183             constant C can be used instead, to capture any protocol. The
184             C and C functions byte-swap this
185             value to or from network endian order.
186              
187             =item ifindex
188              
189             The index number of the interface on which the packet was sent or received.
190             When using an address with C, the value C<0> can be used instead, to
191             watch all interfaces.
192              
193             =item hatype
194              
195             The hardware ARP type of hardware address.
196              
197             =item pkttype
198              
199             The type of the packet; indicates if it was sent or received. Will be one of
200             the C values.
201              
202             =item addr
203              
204             The underlying hardware address, in the type given by C.
205              
206             =back
207              
208             =head2 pack_sockaddr_ll
209              
210             $a = pack_sockaddr_ll( $protocol, $ifindex, $hatype, $pkttype, $addr );
211              
212             Returns a C structure with the fields packed into it.
213              
214             =head2 unpack_sockaddr_ll
215              
216             ( $protocol, $ifindex, $hatype, $pkttype, $addr ) = unpack_sockaddr_ll( $a );
217              
218             Takes a C structure and returns the unpacked fields from it.
219              
220             =head2 pack_packet_mreq
221              
222             $mreq = pack_packet_mreq( $ifindex, $type, $addr );
223              
224             Returns a C structure with the fields packed into it.
225              
226             =head2 unpack_packet_mreq
227              
228             ( $ifindex, $type, $addr ) = unpack_packet_mreq( $mreq );
229              
230             Takes a C structure and returns the unpacked fields from it.
231              
232             =head2 unpack_tpacket_stats
233              
234             ( $packets, $drops ) = unpack_tpacket_stats( $stats );
235              
236             Takes a C structure from the C sockopt and
237             returns the unpacked fields from it.
238              
239             =head2 siocgstamp
240              
241             $time = siocgstamp( $sock );
242              
243             ( $sec, $usec ) = siocgstamp( $sock );
244              
245             Returns the timestamp of the last received packet on the socket (as obtained
246             by the C C). In scalar context, returns a single
247             floating-point value in UNIX epoch seconds. In list context, returns the
248             number of seconds, and the number of microseconds.
249              
250             =head2 siocgstampns
251              
252             $time = siocgstampns( $sock );
253              
254             ( $sec, $nsec ) = siocgstampns( $sock );
255              
256             Returns the nanosecond-precise timestamp of the last received packet on the
257             socket (as obtained by the C C). In scalar context,
258             returns a single floating-point value in UNIX epoch seconds. In list context,
259             returns the number of seconds, and the number of nanoseconds.
260              
261             =head2 siocgifindex
262              
263             $ifindex = siocgifindex( $sock, $ifname );
264              
265             Returns the C of the interface with the given name if one exists, or
266             C if not. C<$sock> does not need to be a C socket, any
267             socket handle will do.
268              
269             =head2 siocgifname
270              
271             $ifname = siocgifname( $sock, $ifindex );
272              
273             Returns the C of the interface at the given index if one exists, or
274             C if not. C<$sock> does not need to be a C socket, any
275             socket handle will do.
276              
277             =head2 recv_len
278              
279             ( $addr, $len ) = recv_len( $sock, $buffer, $maxlen, $flags );
280              
281             Similar to Perl's C builtin, except it returns the packet length as an
282             explict return value. This may be useful if C<$flags> contains the
283             C flag, obtaining the true length of the packet on the wire, even
284             if this is longer than the data written in the buffer.
285              
286             =cut
287              
288             =head1 RING-BUFFER FUNCTIONS
289              
290             The following functions operate on the high-performance memory-mapped buffer
291             feature of C, allowing efficient packet-capture applications to
292             share a buffer with the kernel directly, avoiding the need for per-packet
293             system calls to C (and possibly C to obtain the timestamp).
294              
295             The ring-buffer is optional, and may not be implemented on all platforms. If
296             it is not implemented, then all the following functions will die with an error
297             message.
298              
299             =cut
300              
301             =head2 setup_rx_ring
302              
303             $size = setup_rx_ring( $sock, $frame_size, $frame_nr, $block_size );
304              
305             Sets up the ring-buffer on the socket. The buffer will store C<$frame_nr>
306             frames of up to C<$frame_size> bytes each (including metadata headers), and
307             will be split in the kernel in blocks of C<$block_size> bytes. C<$block_size>
308             should be a power of 2, at minimum, 4KiB.
309              
310             If successful, the overall size of the buffer in bytes is returned. If not,
311             C is returned, and C<$!> will hold the error value.
312              
313             =head2 get_ring_frame_status
314              
315             $status = get_ring_frame_status( $sock );
316              
317             Returns the frame status of the next frame in the ring.
318              
319             The following constants are defined for the status:
320              
321             =over 8
322              
323             =item TP_STATUS_KERNEL
324              
325             This frame belongs to the kernel and userland should not touch it.
326              
327             =item TP_STATUS_USER
328              
329             This frame belongs to userland and the kernel will not modify it.
330              
331             =item TP_STATUS_LOSING
332              
333             Bitwise-or'ed with the status if packet loss has occurred since the previous
334             frame.
335              
336             =back
337              
338             =head2 get_ring_frame
339              
340             $len = get_ring_frame( $sock, $buffer, \%info );
341              
342             If the next frame is ready for userland, fills in keys of the C<%info> hash
343             with its metadata, sets C<$buffer> to its contents, and return the length of
344             the data. The C<$buffer> variable has its string backing buffer aliased,
345             rather than the buffer copied into, for performance. The caller should not
346             modify the variable, nor attempt to access it after the socket has been
347             closed.
348              
349             If the frame is not yet ready, this function returns undef.
350              
351             The following fields are returned:
352              
353             =over 8
354              
355             =item tp_status
356              
357             The status of the frame; see C
358              
359             =item tp_len
360              
361             The length of the packet on the wire, in bytes
362              
363             =item tp_snaplen
364              
365             The length of the packet captured and stored in the buffer, in bytes. This may
366             be shorter than C if, for example, a filter is set on the socket that
367             truncated the packet.
368              
369             =item tp_sec
370              
371             =item tp_nsec
372              
373             The seconds and nanoseconds fields of the timestamp. If the underlying
374             platform does not support C, then this field will only have a
375             resolution of microseconds; i.e. it will be a whole multiple of 1000.
376              
377             =item tp_vlan_tci
378              
379             VLAN information about the packet, if the underlying platform supports
380             C. If this is not supported, the key will not be present in the
381             hash
382              
383             =item sll_protocol
384              
385             =item sll_ifindex
386              
387             =item sll_hatype
388              
389             =item sll_pkttype
390              
391             =item sll_addr
392              
393             Fields from the C; see above for more detail
394              
395             =back
396              
397             =head2 clear_ring_frame
398              
399             clear_ring_frame( $sock );
400              
401             Clears the status of current frame to hand it back to the kernel and moves on
402             to the next.
403              
404             =cut
405              
406             =head1 SEE ALSO
407              
408             =over 4
409              
410             =item *
411              
412             L - Object interface to C domain sockets
413              
414             =item *
415              
416             L - interface to Linux's socket packet filtering
417              
418             =item *
419              
420             C - packet, AF_PACKET - packet interface on device level
421              
422             =back
423              
424             =head1 AUTHOR
425              
426             Paul Evans
427              
428             =cut
429              
430             0x55AA;