]> The Tcpdump Group git mirrors - libpcap/blob - pcap-linux.c
With a timeout of zero, specify a maximum-size retire timeout.
[libpcap] / pcap-linux.c
1 /*
2 * pcap-linux.c: Packet capture interface to the Linux kernel
3 *
4 * Copyright (c) 2000 Torsten Landschoff <torsten@debian.org>
5 * Sebastian Krahmer <krahmer@cs.uni-potsdam.de>
6 *
7 * License: BSD
8 *
9 * Redistribution and use in source and binary forms, with or without
10 * modification, are permitted provided that the following conditions
11 * are met:
12 *
13 * 1. Redistributions of source code must retain the above copyright
14 * notice, this list of conditions and the following disclaimer.
15 * 2. Redistributions in binary form must reproduce the above copyright
16 * notice, this list of conditions and the following disclaimer in
17 * the documentation and/or other materials provided with the
18 * distribution.
19 * 3. The names of the authors may not be used to endorse or promote
20 * products derived from this software without specific prior
21 * written permission.
22 *
23 * THIS SOFTWARE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR
24 * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
25 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
26 *
27 * Modifications: Added PACKET_MMAP support
28 * Paolo Abeni <paolo.abeni@email.it>
29 * Added TPACKET_V3 support
30 * Gabor Tatarka <gabor.tatarka@ericsson.com>
31 *
32 * based on previous works of:
33 * Simon Patarin <patarin@cs.unibo.it>
34 * Phil Wood <cpw@lanl.gov>
35 *
36 * Monitor-mode support for mac80211 includes code taken from the iw
37 * command; the copyright notice for that code is
38 *
39 * Copyright (c) 2007, 2008 Johannes Berg
40 * Copyright (c) 2007 Andy Lutomirski
41 * Copyright (c) 2007 Mike Kershaw
42 * Copyright (c) 2008 Gábor Stefanik
43 *
44 * All rights reserved.
45 *
46 * Redistribution and use in source and binary forms, with or without
47 * modification, are permitted provided that the following conditions
48 * are met:
49 * 1. Redistributions of source code must retain the above copyright
50 * notice, this list of conditions and the following disclaimer.
51 * 2. Redistributions in binary form must reproduce the above copyright
52 * notice, this list of conditions and the following disclaimer in the
53 * documentation and/or other materials provided with the distribution.
54 * 3. The name of the author may not be used to endorse or promote products
55 * derived from this software without specific prior written permission.
56 *
57 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
58 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
59 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
60 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
61 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
62 * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
63 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
64 * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
65 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
66 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
67 * SUCH DAMAGE.
68 */
69
70 /*
71 * Known problems with 2.0[.x] kernels:
72 *
73 * - The loopback device gives every packet twice; on 2.2[.x] kernels,
74 * if we use PF_PACKET, we can filter out the transmitted version
75 * of the packet by using data in the "sockaddr_ll" returned by
76 * "recvfrom()", but, on 2.0[.x] kernels, we have to use
77 * PF_INET/SOCK_PACKET, which means "recvfrom()" supplies a
78 * "sockaddr_pkt" which doesn't give us enough information to let
79 * us do that.
80 *
81 * - We have to set the interface's IFF_PROMISC flag ourselves, if
82 * we're to run in promiscuous mode, which means we have to turn
83 * it off ourselves when we're done; the kernel doesn't keep track
84 * of how many sockets are listening promiscuously, which means
85 * it won't get turned off automatically when no sockets are
86 * listening promiscuously. We catch "pcap_close()" and, for
87 * interfaces we put into promiscuous mode, take them out of
88 * promiscuous mode - which isn't necessarily the right thing to
89 * do, if another socket also requested promiscuous mode between
90 * the time when we opened the socket and the time when we close
91 * the socket.
92 *
93 * - MSG_TRUNC isn't supported, so you can't specify that "recvfrom()"
94 * return the amount of data that you could have read, rather than
95 * the amount that was returned, so we can't just allocate a buffer
96 * whose size is the snapshot length and pass the snapshot length
97 * as the byte count, and also pass MSG_TRUNC, so that the return
98 * value tells us how long the packet was on the wire.
99 *
100 * This means that, if we want to get the actual size of the packet,
101 * so we can return it in the "len" field of the packet header,
102 * we have to read the entire packet, not just the part that fits
103 * within the snapshot length, and thus waste CPU time copying data
104 * from the kernel that our caller won't see.
105 *
106 * We have to get the actual size, and supply it in "len", because
107 * otherwise, the IP dissector in tcpdump, for example, will complain
108 * about "truncated-ip", as the packet will appear to have been
109 * shorter, on the wire, than the IP header said it should have been.
110 */
111
112
113 #define _GNU_SOURCE
114
115 #ifdef HAVE_CONFIG_H
116 #include <config.h>
117 #endif
118
119 #include <errno.h>
120 #include <stdio.h>
121 #include <stdlib.h>
122 #include <unistd.h>
123 #include <fcntl.h>
124 #include <string.h>
125 #include <limits.h>
126 #include <sys/stat.h>
127 #include <sys/socket.h>
128 #include <sys/ioctl.h>
129 #include <sys/utsname.h>
130 #include <sys/mman.h>
131 #include <linux/if.h>
132 #include <linux/if_packet.h>
133 #include <linux/sockios.h>
134 #include <netinet/in.h>
135 #include <linux/if_ether.h>
136 #include <linux/if_arp.h>
137 #include <poll.h>
138 #include <dirent.h>
139 #ifdef HAVE_SYS_EVENTFD_H
140 #include <sys/eventfd.h>
141 #endif
142
143 #include "pcap-int.h"
144 #include "pcap/sll.h"
145 #include "pcap/vlan.h"
146
147 #include "diag-control.h"
148
149 /*
150 * If PF_PACKET is defined, we can use {SOCK_RAW,SOCK_DGRAM}/PF_PACKET
151 * sockets rather than SOCK_PACKET sockets.
152 *
153 * To use them, we include <linux/if_packet.h> rather than
154 * <netpacket/packet.h>; we do so because
155 *
156 * some Linux distributions (e.g., Slackware 4.0) have 2.2 or
157 * later kernels and libc5, and don't provide a <netpacket/packet.h>
158 * file;
159 *
160 * not all versions of glibc2 have a <netpacket/packet.h> file
161 * that defines stuff needed for some of the 2.4-or-later-kernel
162 * features, so if the system has a 2.4 or later kernel, we
163 * still can't use those features.
164 *
165 * We're already including a number of other <linux/XXX.h> headers, and
166 * this code is Linux-specific (no other OS has PF_PACKET sockets as
167 * a raw packet capture mechanism), so it's not as if you gain any
168 * useful portability by using <netpacket/packet.h>
169 *
170 * XXX - should we just include <linux/if_packet.h> even if PF_PACKET
171 * isn't defined? It only defines one data structure in 2.0.x, so
172 * it shouldn't cause any problems.
173 */
174 #ifdef PF_PACKET
175 # include <linux/if_packet.h>
176
177 /*
178 * On at least some Linux distributions (for example, Red Hat 5.2),
179 * there's no <netpacket/packet.h> file, but PF_PACKET is defined if
180 * you include <sys/socket.h>, but <linux/if_packet.h> doesn't define
181 * any of the PF_PACKET stuff such as "struct sockaddr_ll" or any of
182 * the PACKET_xxx stuff.
183 *
184 * So we check whether PACKET_HOST is defined, and assume that we have
185 * PF_PACKET sockets only if it is defined.
186 */
187 # ifdef PACKET_HOST
188 # define HAVE_PF_PACKET_SOCKETS
189 # ifdef PACKET_AUXDATA
190 # define HAVE_PACKET_AUXDATA
191 # endif /* PACKET_AUXDATA */
192 # endif /* PACKET_HOST */
193
194
195 /* check for memory mapped access avaibility. We assume every needed
196 * struct is defined if the macro TPACKET_HDRLEN is defined, because it
197 * uses many ring related structs and macros */
198 # ifdef PCAP_SUPPORT_PACKET_RING
199 # ifdef TPACKET_HDRLEN
200 # define HAVE_PACKET_RING
201 # ifdef TPACKET3_HDRLEN
202 # define HAVE_TPACKET3
203 # endif /* TPACKET3_HDRLEN */
204 # ifdef TPACKET2_HDRLEN
205 # define HAVE_TPACKET2
206 # else /* TPACKET2_HDRLEN */
207 # define TPACKET_V1 0 /* Old kernel with only V1, so no TPACKET_Vn defined */
208 # endif /* TPACKET2_HDRLEN */
209 # endif /* TPACKET_HDRLEN */
210 # endif /* PCAP_SUPPORT_PACKET_RING */
211 #endif /* PF_PACKET */
212
213 #ifdef SO_ATTACH_FILTER
214 #include <linux/types.h>
215 #include <linux/filter.h>
216 #endif
217
218 #ifdef HAVE_LINUX_NET_TSTAMP_H
219 #include <linux/net_tstamp.h>
220 #endif
221
222 #ifdef HAVE_LINUX_SOCKIOS_H
223 #include <linux/sockios.h>
224 #endif
225
226 #ifdef HAVE_LINUX_IF_BONDING_H
227 #include <linux/if_bonding.h>
228
229 /*
230 * The ioctl code to use to check whether a device is a bonding device.
231 */
232 #if defined(SIOCBONDINFOQUERY)
233 #define BOND_INFO_QUERY_IOCTL SIOCBONDINFOQUERY
234 #elif defined(BOND_INFO_QUERY_OLD)
235 #define BOND_INFO_QUERY_IOCTL BOND_INFO_QUERY_OLD
236 #endif
237 #endif /* HAVE_LINUX_IF_BONDING_H */
238
239 /*
240 * Got Wireless Extensions?
241 */
242 #ifdef HAVE_LINUX_WIRELESS_H
243 #include <linux/wireless.h>
244 #endif /* HAVE_LINUX_WIRELESS_H */
245
246 /*
247 * Got libnl?
248 */
249 #ifdef HAVE_LIBNL
250 #include <linux/nl80211.h>
251
252 #include <netlink/genl/genl.h>
253 #include <netlink/genl/family.h>
254 #include <netlink/genl/ctrl.h>
255 #include <netlink/msg.h>
256 #include <netlink/attr.h>
257 #endif /* HAVE_LIBNL */
258
259 /*
260 * Got ethtool support?
261 */
262 #ifdef HAVE_LINUX_ETHTOOL_H
263 #include <linux/ethtool.h>
264 #endif
265
266 #ifndef HAVE_SOCKLEN_T
267 typedef int socklen_t;
268 #endif
269
270 #ifndef MSG_TRUNC
271 /*
272 * This is being compiled on a system that lacks MSG_TRUNC; define it
273 * with the value it has in the 2.2 and later kernels, so that, on
274 * those kernels, when we pass it in the flags argument to "recvfrom()"
275 * we're passing the right value and thus get the MSG_TRUNC behavior
276 * we want. (We don't get that behavior on 2.0[.x] kernels, because
277 * they didn't support MSG_TRUNC.)
278 */
279 #define MSG_TRUNC 0x20
280 #endif
281
282 #ifndef SOL_PACKET
283 /*
284 * This is being compiled on a system that lacks SOL_PACKET; define it
285 * with the value it has in the 2.2 and later kernels, so that we can
286 * set promiscuous mode in the good modern way rather than the old
287 * 2.0-kernel crappy way.
288 */
289 #define SOL_PACKET 263
290 #endif
291
292 #define MAX_LINKHEADER_SIZE 256
293
294 /*
295 * When capturing on all interfaces we use this as the buffer size.
296 * Should be bigger then all MTUs that occur in real life.
297 * 64kB should be enough for now.
298 */
299 #define BIGGER_THAN_ALL_MTUS (64*1024)
300
301 /*
302 * Private data for capturing on Linux SOCK_PACKET or PF_PACKET sockets.
303 */
304 struct pcap_linux {
305 u_int packets_read; /* count of packets read with recvfrom() */
306 long proc_dropped; /* packets reported dropped by /proc/net/dev */
307 struct pcap_stat stat;
308
309 char *device; /* device name */
310 int filter_in_userland; /* must filter in userland */
311 int blocks_to_filter_in_userland;
312 int must_do_on_close; /* stuff we must do when we close */
313 int timeout; /* timeout for buffering */
314 int sock_packet; /* using Linux 2.0 compatible interface */
315 int cooked; /* using SOCK_DGRAM rather than SOCK_RAW */
316 int ifindex; /* interface index of device we're bound to */
317 int lo_ifindex; /* interface index of the loopback device */
318 bpf_u_int32 oldmode; /* mode to restore when turning monitor mode off */
319 char *mondevice; /* mac80211 monitor device we created */
320 u_char *mmapbuf; /* memory-mapped region pointer */
321 size_t mmapbuflen; /* size of region */
322 int vlan_offset; /* offset at which to insert vlan tags; if -1, don't insert */
323 u_int tp_version; /* version of tpacket_hdr for mmaped ring */
324 u_int tp_hdrlen; /* hdrlen of tpacket_hdr for mmaped ring */
325 u_char *oneshot_buffer; /* buffer for copy of packet */
326 int poll_timeout; /* timeout to use in poll() */
327 #ifdef HAVE_TPACKET3
328 unsigned char *current_packet; /* Current packet within the TPACKET_V3 block. Move to next block if NULL. */
329 int packets_left; /* Unhandled packets left within the block from previous call to pcap_read_linux_mmap_v3 in case of TPACKET_V3. */
330 #endif
331 #ifdef HAVE_SYS_EVENTFD_H
332 int poll_breakloop_fd; /* fd to an eventfd to break from blocking operations */
333 #endif
334 };
335
336 /*
337 * Stuff to do when we close.
338 */
339 #define MUST_CLEAR_PROMISC 0x00000001 /* clear promiscuous mode */
340 #define MUST_CLEAR_RFMON 0x00000002 /* clear rfmon (monitor) mode */
341 #define MUST_DELETE_MONIF 0x00000004 /* delete monitor-mode interface */
342
343 /*
344 * Prototypes for internal functions and methods.
345 */
346 static int get_if_flags(const char *, bpf_u_int32 *, char *);
347 static int is_wifi(int, const char *);
348 static void map_arphrd_to_dlt(pcap_t *, int, int, const char *, int);
349 static int pcap_activate_linux(pcap_t *);
350 static int activate_old(pcap_t *, int);
351 #ifdef HAVE_PF_PACKET_SOCKETS
352 static int activate_new(pcap_t *, int);
353 #ifdef HAVE_PACKET_RING
354 static int activate_mmap(pcap_t *, int *);
355 #endif
356 #endif /* HAVE_PF_PACKET_SOCKETS */
357 static int pcap_can_set_rfmon_linux(pcap_t *);
358 static int pcap_read_linux(pcap_t *, int, pcap_handler, u_char *);
359 static int pcap_read_packet(pcap_t *, pcap_handler, u_char *);
360 static int pcap_inject_linux(pcap_t *, const void *, int);
361 static int pcap_stats_linux(pcap_t *, struct pcap_stat *);
362 static int pcap_setfilter_linux(pcap_t *, struct bpf_program *);
363 static int pcap_setdirection_linux(pcap_t *, pcap_direction_t);
364 static int pcap_set_datalink_linux(pcap_t *, int);
365 static void pcap_cleanup_linux(pcap_t *);
366
367 /*
368 * This is what the header structure looks like in a 64-bit kernel;
369 * we use this, rather than struct tpacket_hdr, if we're using
370 * TPACKET_V1 in 32-bit code running on a 64-bit kernel.
371 */
372 struct tpacket_hdr_64 {
373 uint64_t tp_status;
374 unsigned int tp_len;
375 unsigned int tp_snaplen;
376 unsigned short tp_mac;
377 unsigned short tp_net;
378 unsigned int tp_sec;
379 unsigned int tp_usec;
380 };
381
382 /*
383 * We use this internally as the tpacket version for TPACKET_V1 in
384 * 32-bit code on a 64-bit kernel.
385 */
386 #define TPACKET_V1_64 99
387
388 union thdr {
389 struct tpacket_hdr *h1;
390 struct tpacket_hdr_64 *h1_64;
391 #ifdef HAVE_TPACKET2
392 struct tpacket2_hdr *h2;
393 #endif
394 #ifdef HAVE_TPACKET3
395 struct tpacket_block_desc *h3;
396 #endif
397 void *raw;
398 };
399
400 #ifdef HAVE_PACKET_RING
401 #define RING_GET_FRAME_AT(h, offset) (((union thdr **)h->buffer)[(offset)])
402 #define RING_GET_CURRENT_FRAME(h) RING_GET_FRAME_AT(h, h->offset)
403
404 static void destroy_ring(pcap_t *handle);
405 static int create_ring(pcap_t *handle, int *status);
406 static int prepare_tpacket_socket(pcap_t *handle);
407 static void pcap_cleanup_linux_mmap(pcap_t *);
408 static int pcap_read_linux_mmap_v1(pcap_t *, int, pcap_handler , u_char *);
409 static int pcap_read_linux_mmap_v1_64(pcap_t *, int, pcap_handler , u_char *);
410 #ifdef HAVE_TPACKET2
411 static int pcap_read_linux_mmap_v2(pcap_t *, int, pcap_handler , u_char *);
412 #endif
413 #ifdef HAVE_TPACKET3
414 static int pcap_read_linux_mmap_v3(pcap_t *, int, pcap_handler , u_char *);
415 #endif
416 static int pcap_setfilter_linux_mmap(pcap_t *, struct bpf_program *);
417 static int pcap_setnonblock_mmap(pcap_t *p, int nonblock);
418 static int pcap_getnonblock_mmap(pcap_t *p);
419 static void pcap_oneshot_mmap(u_char *user, const struct pcap_pkthdr *h,
420 const u_char *bytes);
421 #endif
422
423 /*
424 * In pre-3.0 kernels, the tp_vlan_tci field is set to whatever the
425 * vlan_tci field in the skbuff is. 0 can either mean "not on a VLAN"
426 * or "on VLAN 0". There is no flag set in the tp_status field to
427 * distinguish between them.
428 *
429 * In 3.0 and later kernels, if there's a VLAN tag present, the tp_vlan_tci
430 * field is set to the VLAN tag, and the TP_STATUS_VLAN_VALID flag is set
431 * in the tp_status field, otherwise the tp_vlan_tci field is set to 0 and
432 * the TP_STATUS_VLAN_VALID flag isn't set in the tp_status field.
433 *
434 * With a pre-3.0 kernel, we cannot distinguish between packets with no
435 * VLAN tag and packets on VLAN 0, so we will mishandle some packets, and
436 * there's nothing we can do about that.
437 *
438 * So, on those systems, which never set the TP_STATUS_VLAN_VALID flag, we
439 * continue the behavior of earlier libpcaps, wherein we treated packets
440 * with a VLAN tag of 0 as being packets without a VLAN tag rather than packets
441 * on VLAN 0. We do this by treating packets with a tp_vlan_tci of 0 and
442 * with the TP_STATUS_VLAN_VALID flag not set in tp_status as not having
443 * VLAN tags. This does the right thing on 3.0 and later kernels, and
444 * continues the old unfixably-imperfect behavior on pre-3.0 kernels.
445 *
446 * If TP_STATUS_VLAN_VALID isn't defined, we test it as the 0x10 bit; it
447 * has that value in 3.0 and later kernels.
448 */
449 #ifdef TP_STATUS_VLAN_VALID
450 #define VLAN_VALID(hdr, hv) ((hv)->tp_vlan_tci != 0 || ((hdr)->tp_status & TP_STATUS_VLAN_VALID))
451 #else
452 /*
453 * This is being compiled on a system that lacks TP_STATUS_VLAN_VALID,
454 * so we testwith the value it has in the 3.0 and later kernels, so
455 * we can test it if we're running on a system that has it. (If we're
456 * running on a system that doesn't have it, it won't be set in the
457 * tp_status field, so the tests of it will always fail; that means
458 * we behave the way we did before we introduced this macro.)
459 */
460 #define VLAN_VALID(hdr, hv) ((hv)->tp_vlan_tci != 0 || ((hdr)->tp_status & 0x10))
461 #endif
462
463 #ifdef TP_STATUS_VLAN_TPID_VALID
464 # define VLAN_TPID(hdr, hv) (((hv)->tp_vlan_tpid || ((hdr)->tp_status & TP_STATUS_VLAN_TPID_VALID)) ? (hv)->tp_vlan_tpid : ETH_P_8021Q)
465 #else
466 # define VLAN_TPID(hdr, hv) ETH_P_8021Q
467 #endif
468
469 /*
470 * Wrap some ioctl calls
471 */
472 #ifdef HAVE_PF_PACKET_SOCKETS
473 static int iface_get_id(int fd, const char *device, char *ebuf);
474 #endif /* HAVE_PF_PACKET_SOCKETS */
475 static int iface_get_mtu(int fd, const char *device, char *ebuf);
476 static int iface_get_arptype(int fd, const char *device, char *ebuf);
477 #ifdef HAVE_PF_PACKET_SOCKETS
478 static int iface_bind(int fd, int ifindex, char *ebuf, int protocol);
479 #ifdef IW_MODE_MONITOR
480 static int has_wext(int sock_fd, const char *device, char *ebuf);
481 #endif /* IW_MODE_MONITOR */
482 static int enter_rfmon_mode(pcap_t *handle, int sock_fd,
483 const char *device);
484 #endif /* HAVE_PF_PACKET_SOCKETS */
485 #if defined(HAVE_LINUX_NET_TSTAMP_H) && defined(PACKET_TIMESTAMP)
486 static int iface_ethtool_get_ts_info(const char *device, pcap_t *handle,
487 char *ebuf);
488 #endif
489 #ifdef HAVE_PACKET_RING
490 static int iface_get_offload(pcap_t *handle);
491 #endif
492 static int iface_bind_old(int fd, const char *device, char *ebuf);
493
494 #ifdef SO_ATTACH_FILTER
495 static int fix_program(pcap_t *handle, struct sock_fprog *fcode,
496 int is_mapped);
497 static int fix_offset(pcap_t *handle, struct bpf_insn *p);
498 static int set_kernel_filter(pcap_t *handle, struct sock_fprog *fcode);
499 static int reset_kernel_filter(pcap_t *handle);
500
501 static struct sock_filter total_insn
502 = BPF_STMT(BPF_RET | BPF_K, 0);
503 static struct sock_fprog total_fcode
504 = { 1, &total_insn };
505 #endif /* SO_ATTACH_FILTER */
506
507 static int iface_dsa_get_proto_info(const char *device, pcap_t *handle);
508
509 pcap_t *
510 pcap_create_interface(const char *device, char *ebuf)
511 {
512 pcap_t *handle;
513
514 handle = pcap_create_common(ebuf, sizeof (struct pcap_linux));
515 if (handle == NULL)
516 return NULL;
517
518 handle->activate_op = pcap_activate_linux;
519 handle->can_set_rfmon_op = pcap_can_set_rfmon_linux;
520
521 #if defined(HAVE_LINUX_NET_TSTAMP_H) && defined(PACKET_TIMESTAMP)
522 /*
523 * See what time stamp types we support.
524 */
525 if (iface_ethtool_get_ts_info(device, handle, ebuf) == -1) {
526 pcap_close(handle);
527 return NULL;
528 }
529 #endif
530
531 #if defined(SIOCGSTAMPNS) && defined(SO_TIMESTAMPNS)
532 /*
533 * We claim that we support microsecond and nanosecond time
534 * stamps.
535 *
536 * XXX - with adapter-supplied time stamps, can we choose
537 * microsecond or nanosecond time stamps on arbitrary
538 * adapters?
539 */
540 handle->tstamp_precision_count = 2;
541 handle->tstamp_precision_list = malloc(2 * sizeof(u_int));
542 if (handle->tstamp_precision_list == NULL) {
543 pcap_fmt_errmsg_for_errno(ebuf, PCAP_ERRBUF_SIZE,
544 errno, "malloc");
545 pcap_close(handle);
546 return NULL;
547 }
548 handle->tstamp_precision_list[0] = PCAP_TSTAMP_PRECISION_MICRO;
549 handle->tstamp_precision_list[1] = PCAP_TSTAMP_PRECISION_NANO;
550 #endif /* defined(SIOCGSTAMPNS) && defined(SO_TIMESTAMPNS) */
551
552 #ifdef HAVE_SYS_EVENTFD_H
553 struct pcap_linux *handlep = handle->priv;
554 handlep->poll_breakloop_fd = eventfd(0, EFD_NONBLOCK);
555 #endif
556
557 return handle;
558 }
559
560 #ifdef HAVE_LIBNL
561 /*
562 * If interface {if} is a mac80211 driver, the file
563 * /sys/class/net/{if}/phy80211 is a symlink to
564 * /sys/class/ieee80211/{phydev}, for some {phydev}.
565 *
566 * On Fedora 9, with a 2.6.26.3-29 kernel, my Zydas stick, at
567 * least, has a "wmaster0" device and a "wlan0" device; the
568 * latter is the one with the IP address. Both show up in
569 * "tcpdump -D" output. Capturing on the wmaster0 device
570 * captures with 802.11 headers.
571 *
572 * airmon-ng searches through /sys/class/net for devices named
573 * monN, starting with mon0; as soon as one *doesn't* exist,
574 * it chooses that as the monitor device name. If the "iw"
575 * command exists, it does "iw dev {if} interface add {monif}
576 * type monitor", where {monif} is the monitor device. It
577 * then (sigh) sleeps .1 second, and then configures the
578 * device up. Otherwise, if /sys/class/ieee80211/{phydev}/add_iface
579 * is a file, it writes {mondev}, without a newline, to that file,
580 * and again (sigh) sleeps .1 second, and then iwconfig's that
581 * device into monitor mode and configures it up. Otherwise,
582 * you can't do monitor mode.
583 *
584 * All these devices are "glued" together by having the
585 * /sys/class/net/{device}/phy80211 links pointing to the same
586 * place, so, given a wmaster, wlan, or mon device, you can
587 * find the other devices by looking for devices with
588 * the same phy80211 link.
589 *
590 * To turn monitor mode off, delete the monitor interface,
591 * either with "iw dev {monif} interface del" or by sending
592 * {monif}, with no NL, down /sys/class/ieee80211/{phydev}/remove_iface
593 *
594 * Note: if you try to create a monitor device named "monN", and
595 * there's already a "monN" device, it fails, as least with
596 * the netlink interface (which is what iw uses), with a return
597 * value of -ENFILE. (Return values are negative errnos.) We
598 * could probably use that to find an unused device.
599 *
600 * Yes, you can have multiple monitor devices for a given
601 * physical device.
602 */
603
604 /*
605 * Is this a mac80211 device? If so, fill in the physical device path and
606 * return 1; if not, return 0. On an error, fill in handle->errbuf and
607 * return PCAP_ERROR.
608 */
609 static int
610 get_mac80211_phydev(pcap_t *handle, const char *device, char *phydev_path,
611 size_t phydev_max_pathlen)
612 {
613 char *pathstr;
614 ssize_t bytes_read;
615
616 /*
617 * Generate the path string for the symlink to the physical device.
618 */
619 if (asprintf(&pathstr, "/sys/class/net/%s/phy80211", device) == -1) {
620 snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
621 "%s: Can't generate path name string for /sys/class/net device",
622 device);
623 return PCAP_ERROR;
624 }
625 bytes_read = readlink(pathstr, phydev_path, phydev_max_pathlen);
626 if (bytes_read == -1) {
627 if (errno == ENOENT || errno == EINVAL) {
628 /*
629 * Doesn't exist, or not a symlink; assume that
630 * means it's not a mac80211 device.
631 */
632 free(pathstr);
633 return 0;
634 }
635 pcap_fmt_errmsg_for_errno(handle->errbuf, PCAP_ERRBUF_SIZE,
636 errno, "%s: Can't readlink %s", device, pathstr);
637 free(pathstr);
638 return PCAP_ERROR;
639 }
640 free(pathstr);
641 phydev_path[bytes_read] = '\0';
642 return 1;
643 }
644
645 #ifdef HAVE_LIBNL_SOCKETS
646 #define get_nl_errmsg nl_geterror
647 #else
648 /* libnl 2.x compatibility code */
649
650 #define nl_sock nl_handle
651
652 static inline struct nl_handle *
653 nl_socket_alloc(void)
654 {
655 return nl_handle_alloc();
656 }
657
658 static inline void
659 nl_socket_free(struct nl_handle *h)
660 {
661 nl_handle_destroy(h);
662 }
663
664 #define get_nl_errmsg strerror
665
666 static inline int
667 __genl_ctrl_alloc_cache(struct nl_handle *h, struct nl_cache **cache)
668 {
669 struct nl_cache *tmp = genl_ctrl_alloc_cache(h);
670 if (!tmp)
671 return -ENOMEM;
672 *cache = tmp;
673 return 0;
674 }
675 #define genl_ctrl_alloc_cache __genl_ctrl_alloc_cache
676 #endif /* !HAVE_LIBNL_SOCKETS */
677
678 struct nl80211_state {
679 struct nl_sock *nl_sock;
680 struct nl_cache *nl_cache;
681 struct genl_family *nl80211;
682 };
683
684 static int
685 nl80211_init(pcap_t *handle, struct nl80211_state *state, const char *device)
686 {
687 int err;
688
689 state->nl_sock = nl_socket_alloc();
690 if (!state->nl_sock) {
691 snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
692 "%s: failed to allocate netlink handle", device);
693 return PCAP_ERROR;
694 }
695
696 if (genl_connect(state->nl_sock)) {
697 snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
698 "%s: failed to connect to generic netlink", device);
699 goto out_handle_destroy;
700 }
701
702 err = genl_ctrl_alloc_cache(state->nl_sock, &state->nl_cache);
703 if (err < 0) {
704 snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
705 "%s: failed to allocate generic netlink cache: %s",
706 device, get_nl_errmsg(-err));
707 goto out_handle_destroy;
708 }
709
710 state->nl80211 = genl_ctrl_search_by_name(state->nl_cache, "nl80211");
711 if (!state->nl80211) {
712 snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
713 "%s: nl80211 not found", device);
714 goto out_cache_free;
715 }
716
717 return 0;
718
719 out_cache_free:
720 nl_cache_free(state->nl_cache);
721 out_handle_destroy:
722 nl_socket_free(state->nl_sock);
723 return PCAP_ERROR;
724 }
725
726 static void
727 nl80211_cleanup(struct nl80211_state *state)
728 {
729 genl_family_put(state->nl80211);
730 nl_cache_free(state->nl_cache);
731 nl_socket_free(state->nl_sock);
732 }
733
734 static int
735 del_mon_if(pcap_t *handle, int sock_fd, struct nl80211_state *state,
736 const char *device, const char *mondevice);
737
738 static int
739 add_mon_if(pcap_t *handle, int sock_fd, struct nl80211_state *state,
740 const char *device, const char *mondevice)
741 {
742 struct pcap_linux *handlep = handle->priv;
743 int ifindex;
744 struct nl_msg *msg;
745 int err;
746
747 ifindex = iface_get_id(sock_fd, device, handle->errbuf);
748 if (ifindex == -1)
749 return PCAP_ERROR;
750
751 msg = nlmsg_alloc();
752 if (!msg) {
753 snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
754 "%s: failed to allocate netlink msg", device);
755 return PCAP_ERROR;
756 }
757
758 genlmsg_put(msg, 0, 0, genl_family_get_id(state->nl80211), 0,
759 0, NL80211_CMD_NEW_INTERFACE, 0);
760 NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, ifindex);
761 DIAG_OFF_NARROWING
762 NLA_PUT_STRING(msg, NL80211_ATTR_IFNAME, mondevice);
763 DIAG_ON_NARROWING
764 NLA_PUT_U32(msg, NL80211_ATTR_IFTYPE, NL80211_IFTYPE_MONITOR);
765
766 err = nl_send_auto_complete(state->nl_sock, msg);
767 if (err < 0) {
768 #if defined HAVE_LIBNL_NLE
769 if (err == -NLE_FAILURE) {
770 #else
771 if (err == -ENFILE) {
772 #endif
773 /*
774 * Device not available; our caller should just
775 * keep trying. (libnl 2.x maps ENFILE to
776 * NLE_FAILURE; it can also map other errors
777 * to that, but there's not much we can do
778 * about that.)
779 */
780 nlmsg_free(msg);
781 return 0;
782 } else {
783 /*
784 * Real failure, not just "that device is not
785 * available.
786 */
787 snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
788 "%s: nl_send_auto_complete failed adding %s interface: %s",
789 device, mondevice, get_nl_errmsg(-err));
790 nlmsg_free(msg);
791 return PCAP_ERROR;
792 }
793 }
794 err = nl_wait_for_ack(state->nl_sock);
795 if (err < 0) {
796 #if defined HAVE_LIBNL_NLE
797 if (err == -NLE_FAILURE) {
798 #else
799 if (err == -ENFILE) {
800 #endif
801 /*
802 * Device not available; our caller should just
803 * keep trying. (libnl 2.x maps ENFILE to
804 * NLE_FAILURE; it can also map other errors
805 * to that, but there's not much we can do
806 * about that.)
807 */
808 nlmsg_free(msg);
809 return 0;
810 } else {
811 /*
812 * Real failure, not just "that device is not
813 * available.
814 */
815 snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
816 "%s: nl_wait_for_ack failed adding %s interface: %s",
817 device, mondevice, get_nl_errmsg(-err));
818 nlmsg_free(msg);
819 return PCAP_ERROR;
820 }
821 }
822
823 /*
824 * Success.
825 */
826 nlmsg_free(msg);
827
828 /*
829 * Try to remember the monitor device.
830 */
831 handlep->mondevice = strdup(mondevice);
832 if (handlep->mondevice == NULL) {
833 pcap_fmt_errmsg_for_errno(handle->errbuf, PCAP_ERRBUF_SIZE,
834 errno, "strdup");
835 /*
836 * Get rid of the monitor device.
837 */
838 del_mon_if(handle, sock_fd, state, device, mondevice);
839 return PCAP_ERROR;
840 }
841 return 1;
842
843 nla_put_failure:
844 snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
845 "%s: nl_put failed adding %s interface",
846 device, mondevice);
847 nlmsg_free(msg);
848 return PCAP_ERROR;
849 }
850
851 static int
852 del_mon_if(pcap_t *handle, int sock_fd, struct nl80211_state *state,
853 const char *device, const char *mondevice)
854 {
855 int ifindex;
856 struct nl_msg *msg;
857 int err;
858
859 ifindex = iface_get_id(sock_fd, mondevice, handle->errbuf);
860 if (ifindex == -1)
861 return PCAP_ERROR;
862
863 msg = nlmsg_alloc();
864 if (!msg) {
865 snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
866 "%s: failed to allocate netlink msg", device);
867 return PCAP_ERROR;
868 }
869
870 genlmsg_put(msg, 0, 0, genl_family_get_id(state->nl80211), 0,
871 0, NL80211_CMD_DEL_INTERFACE, 0);
872 NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, ifindex);
873
874 err = nl_send_auto_complete(state->nl_sock, msg);
875 if (err < 0) {
876 snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
877 "%s: nl_send_auto_complete failed deleting %s interface: %s",
878 device, mondevice, get_nl_errmsg(-err));
879 nlmsg_free(msg);
880 return PCAP_ERROR;
881 }
882 err = nl_wait_for_ack(state->nl_sock);
883 if (err < 0) {
884 snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
885 "%s: nl_wait_for_ack failed adding %s interface: %s",
886 device, mondevice, get_nl_errmsg(-err));
887 nlmsg_free(msg);
888 return PCAP_ERROR;
889 }
890
891 /*
892 * Success.
893 */
894 nlmsg_free(msg);
895 return 1;
896
897 nla_put_failure:
898 snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
899 "%s: nl_put failed deleting %s interface",
900 device, mondevice);
901 nlmsg_free(msg);
902 return PCAP_ERROR;
903 }
904
905 static int
906 enter_rfmon_mode_mac80211(pcap_t *handle, int sock_fd, const char *device)
907 {
908 struct pcap_linux *handlep = handle->priv;
909 int ret;
910 char phydev_path[PATH_MAX+1];
911 struct nl80211_state nlstate;
912 struct ifreq ifr;
913 u_int n;
914
915 /*
916 * Is this a mac80211 device?
917 */
918 ret = get_mac80211_phydev(handle, device, phydev_path, PATH_MAX);
919 if (ret < 0)
920 return ret; /* error */
921 if (ret == 0)
922 return 0; /* no error, but not mac80211 device */
923
924 /*
925 * XXX - is this already a monN device?
926 * If so, we're done.
927 * Is that determined by old Wireless Extensions ioctls?
928 */
929
930 /*
931 * OK, it's apparently a mac80211 device.
932 * Try to find an unused monN device for it.
933 */
934 ret = nl80211_init(handle, &nlstate, device);
935 if (ret != 0)
936 return ret;
937 for (n = 0; n < UINT_MAX; n++) {
938 /*
939 * Try mon{n}.
940 */
941 char mondevice[3+10+1]; /* mon{UINT_MAX}\0 */
942
943 snprintf(mondevice, sizeof mondevice, "mon%u", n);
944 ret = add_mon_if(handle, sock_fd, &nlstate, device, mondevice);
945 if (ret == 1) {
946 /*
947 * Success. We don't clean up the libnl state
948 * yet, as we'll be using it later.
949 */
950 goto added;
951 }
952 if (ret < 0) {
953 /*
954 * Hard failure. Just return ret; handle->errbuf
955 * has already been set.
956 */
957 nl80211_cleanup(&nlstate);
958 return ret;
959 }
960 }
961
962 snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
963 "%s: No free monN interfaces", device);
964 nl80211_cleanup(&nlstate);
965 return PCAP_ERROR;
966
967 added:
968
969 #if 0
970 /*
971 * Sleep for .1 seconds.
972 */
973 delay.tv_sec = 0;
974 delay.tv_nsec = 500000000;
975 nanosleep(&delay, NULL);
976 #endif
977
978 /*
979 * If we haven't already done so, arrange to have
980 * "pcap_close_all()" called when we exit.
981 */
982 if (!pcap_do_addexit(handle)) {
983 /*
984 * "atexit()" failed; don't put the interface
985 * in rfmon mode, just give up.
986 */
987 del_mon_if(handle, sock_fd, &nlstate, device,
988 handlep->mondevice);
989 nl80211_cleanup(&nlstate);
990 return PCAP_ERROR;
991 }
992
993 /*
994 * Now configure the monitor interface up.
995 */
996 memset(&ifr, 0, sizeof(ifr));
997 pcap_strlcpy(ifr.ifr_name, handlep->mondevice, sizeof(ifr.ifr_name));
998 if (ioctl(sock_fd, SIOCGIFFLAGS, &ifr) == -1) {
999 pcap_fmt_errmsg_for_errno(handle->errbuf, PCAP_ERRBUF_SIZE,
1000 errno, "%s: Can't get flags for %s", device,
1001 handlep->mondevice);
1002 del_mon_if(handle, sock_fd, &nlstate, device,
1003 handlep->mondevice);
1004 nl80211_cleanup(&nlstate);
1005 return PCAP_ERROR;
1006 }
1007 ifr.ifr_flags |= IFF_UP|IFF_RUNNING;
1008 if (ioctl(sock_fd, SIOCSIFFLAGS, &ifr) == -1) {
1009 pcap_fmt_errmsg_for_errno(handle->errbuf, PCAP_ERRBUF_SIZE,
1010 errno, "%s: Can't set flags for %s", device,
1011 handlep->mondevice);
1012 del_mon_if(handle, sock_fd, &nlstate, device,
1013 handlep->mondevice);
1014 nl80211_cleanup(&nlstate);
1015 return PCAP_ERROR;
1016 }
1017
1018 /*
1019 * Success. Clean up the libnl state.
1020 */
1021 nl80211_cleanup(&nlstate);
1022
1023 /*
1024 * Note that we have to delete the monitor device when we close
1025 * the handle.
1026 */
1027 handlep->must_do_on_close |= MUST_DELETE_MONIF;
1028
1029 /*
1030 * Add this to the list of pcaps to close when we exit.
1031 */
1032 pcap_add_to_pcaps_to_close(handle);
1033
1034 return 1;
1035 }
1036 #endif /* HAVE_LIBNL */
1037
1038 #ifdef IW_MODE_MONITOR
1039 /*
1040 * Bonding devices mishandle unknown ioctls; they fail with ENODEV
1041 * rather than ENOTSUP, EOPNOTSUPP, or ENOTTY, so Wireless Extensions
1042 * will fail with ENODEV if we try to do them on a bonding device,
1043 * making us return a "no such device" indication rather than just
1044 * saying "no Wireless Extensions".
1045 *
1046 * So we check for bonding devices, if we can, before trying those
1047 * ioctls, by trying a bonding device information query ioctl to see
1048 * whether it succeeds.
1049 */
1050 static int
1051 is_bonding_device(int fd, const char *device)
1052 {
1053 #ifdef BOND_INFO_QUERY_IOCTL
1054 struct ifreq ifr;
1055 ifbond ifb;
1056
1057 memset(&ifr, 0, sizeof ifr);
1058 pcap_strlcpy(ifr.ifr_name, device, sizeof ifr.ifr_name);
1059 memset(&ifb, 0, sizeof ifb);
1060 ifr.ifr_data = (caddr_t)&ifb;
1061 if (ioctl(fd, BOND_INFO_QUERY_IOCTL, &ifr) == 0)
1062 return 1; /* success, so it's a bonding device */
1063 #endif /* BOND_INFO_QUERY_IOCTL */
1064
1065 return 0; /* no, it's not a bonding device */
1066 }
1067 #endif /* IW_MODE_MONITOR */
1068
1069 static int pcap_protocol(pcap_t *handle)
1070 {
1071 int protocol;
1072
1073 protocol = handle->opt.protocol;
1074 if (protocol == 0)
1075 protocol = ETH_P_ALL;
1076
1077 return htons(protocol);
1078 }
1079
1080 static int
1081 pcap_can_set_rfmon_linux(pcap_t *handle)
1082 {
1083 #ifdef HAVE_LIBNL
1084 char phydev_path[PATH_MAX+1];
1085 int ret;
1086 #endif
1087 #ifdef IW_MODE_MONITOR
1088 int sock_fd;
1089 struct iwreq ireq;
1090 #endif
1091
1092 if (strcmp(handle->opt.device, "any") == 0) {
1093 /*
1094 * Monitor mode makes no sense on the "any" device.
1095 */
1096 return 0;
1097 }
1098
1099 #ifdef HAVE_LIBNL
1100 /*
1101 * Bleah. There doesn't seem to be a way to ask a mac80211
1102 * device, through libnl, whether it supports monitor mode;
1103 * we'll just check whether the device appears to be a
1104 * mac80211 device and, if so, assume the device supports
1105 * monitor mode.
1106 *
1107 * wmaster devices don't appear to support the Wireless
1108 * Extensions, but we can create a mon device for a
1109 * wmaster device, so we don't bother checking whether
1110 * a mac80211 device supports the Wireless Extensions.
1111 */
1112 ret = get_mac80211_phydev(handle, handle->opt.device, phydev_path,
1113 PATH_MAX);
1114 if (ret < 0)
1115 return ret; /* error */
1116 if (ret == 1)
1117 return 1; /* mac80211 device */
1118 #endif
1119
1120 #ifdef IW_MODE_MONITOR
1121 /*
1122 * Bleah. There doesn't appear to be an ioctl to use to ask
1123 * whether a device supports monitor mode; we'll just do
1124 * SIOCGIWMODE and, if it succeeds, assume the device supports
1125 * monitor mode.
1126 *
1127 * Open a socket on which to attempt to get the mode.
1128 * (We assume that if we have Wireless Extensions support
1129 * we also have PF_PACKET support.)
1130 */
1131 sock_fd = socket(PF_PACKET, SOCK_RAW, pcap_protocol(handle));
1132 if (sock_fd == -1) {
1133 pcap_fmt_errmsg_for_errno(handle->errbuf, PCAP_ERRBUF_SIZE,
1134 errno, "socket");
1135 return PCAP_ERROR;
1136 }
1137
1138 if (is_bonding_device(sock_fd, handle->opt.device)) {
1139 /* It's a bonding device, so don't even try. */
1140 close(sock_fd);
1141 return 0;
1142 }
1143
1144 /*
1145 * Attempt to get the current mode.
1146 */
1147 pcap_strlcpy(ireq.ifr_ifrn.ifrn_name, handle->opt.device,
1148 sizeof ireq.ifr_ifrn.ifrn_name);
1149 if (ioctl(sock_fd, SIOCGIWMODE, &ireq) != -1) {
1150 /*
1151 * Well, we got the mode; assume we can set it.
1152 */
1153 close(sock_fd);
1154 return 1;
1155 }
1156 if (errno == ENODEV) {
1157 /* The device doesn't even exist. */
1158 pcap_fmt_errmsg_for_errno(handle->errbuf, PCAP_ERRBUF_SIZE,
1159 errno, "SIOCGIWMODE failed");
1160 close(sock_fd);
1161 return PCAP_ERROR_NO_SUCH_DEVICE;
1162 }
1163 close(sock_fd);
1164 #endif
1165 return 0;
1166 }
1167
1168 /*
1169 * Grabs the number of dropped packets by the interface from /proc/net/dev.
1170 *
1171 * XXX - what about /sys/class/net/{interface name}/rx_*? There are
1172 * individual devices giving, in ASCII, various rx_ and tx_ statistics.
1173 *
1174 * Or can we get them in binary form from netlink?
1175 */
1176 static long int
1177 linux_if_drops(const char * if_name)
1178 {
1179 char buffer[512];
1180 FILE *file;
1181 char *bufptr, *nameptr, *colonptr;
1182 int field_to_convert = 3;
1183 long int dropped_pkts = 0;
1184
1185 file = fopen("/proc/net/dev", "r");
1186 if (!file)
1187 return 0;
1188
1189 while (fgets(buffer, sizeof(buffer), file) != NULL)
1190 {
1191 /* search for 'bytes' -- if its in there, then
1192 that means we need to grab the fourth field. otherwise
1193 grab the third field. */
1194 if (field_to_convert != 4 && strstr(buffer, "bytes"))
1195 {
1196 field_to_convert = 4;
1197 continue;
1198 }
1199
1200 /*
1201 * See whether this line corresponds to this device.
1202 * The line should have zero or more leading blanks,
1203 * followed by a device name, followed by a colon,
1204 * followed by the statistics.
1205 */
1206 bufptr = buffer;
1207 /* Skip leading blanks */
1208 while (*bufptr == ' ')
1209 bufptr++;
1210 nameptr = bufptr;
1211 /* Look for the colon */
1212 colonptr = strchr(nameptr, ':');
1213 if (colonptr == NULL)
1214 {
1215 /*
1216 * Not found; this could, for example, be the
1217 * header line.
1218 */
1219 continue;
1220 }
1221 /* Null-terminate the interface name. */
1222 *colonptr = '\0';
1223 if (strcmp(if_name, nameptr) == 0)
1224 {
1225 /*
1226 * OK, this line has the statistics for the interface.
1227 * Skip past the interface name.
1228 */
1229 bufptr = colonptr + 1;
1230
1231 /* grab the nth field from it */
1232 while (--field_to_convert && *bufptr != '\0')
1233 {
1234 /*
1235 * This isn't the field we want.
1236 * First, skip any leading blanks before
1237 * the field.
1238 */
1239 while (*bufptr == ' ')
1240 bufptr++;
1241
1242 /*
1243 * Now skip the non-blank characters of
1244 * the field.
1245 */
1246 while (*bufptr != '\0' && *bufptr != ' ')
1247 bufptr++;
1248 }
1249
1250 if (field_to_convert == 0)
1251 {
1252 /*
1253 * We've found the field we want.
1254 * Skip any leading blanks before it.
1255 */
1256 while (*bufptr == ' ')
1257 bufptr++;
1258
1259 /*
1260 * Now extract the value, if we have one.
1261 */
1262 if (*bufptr != '\0')
1263 dropped_pkts = strtol(bufptr, NULL, 10);
1264 }
1265 break;
1266 }
1267 }
1268
1269 fclose(file);
1270 return dropped_pkts;
1271 }
1272
1273
1274 /*
1275 * With older kernels promiscuous mode is kind of interesting because we
1276 * have to reset the interface before exiting. The problem can't really
1277 * be solved without some daemon taking care of managing usage counts.
1278 * If we put the interface into promiscuous mode, we set a flag indicating
1279 * that we must take it out of that mode when the interface is closed,
1280 * and, when closing the interface, if that flag is set we take it out
1281 * of promiscuous mode.
1282 *
1283 * Even with newer kernels, we have the same issue with rfmon mode.
1284 */
1285
1286 static void pcap_cleanup_linux( pcap_t *handle )
1287 {
1288 struct pcap_linux *handlep = handle->priv;
1289 struct ifreq ifr;
1290 #ifdef HAVE_LIBNL
1291 struct nl80211_state nlstate;
1292 int ret;
1293 #endif /* HAVE_LIBNL */
1294 #ifdef IW_MODE_MONITOR
1295 int oldflags;
1296 struct iwreq ireq;
1297 #endif /* IW_MODE_MONITOR */
1298
1299 if (handlep->must_do_on_close != 0) {
1300 /*
1301 * There's something we have to do when closing this
1302 * pcap_t.
1303 */
1304 if (handlep->must_do_on_close & MUST_CLEAR_PROMISC) {
1305 /*
1306 * We put the interface into promiscuous mode;
1307 * take it out of promiscuous mode.
1308 *
1309 * XXX - if somebody else wants it in promiscuous
1310 * mode, this code cannot know that, so it'll take
1311 * it out of promiscuous mode. That's not fixable
1312 * in 2.0[.x] kernels.
1313 */
1314 memset(&ifr, 0, sizeof(ifr));
1315 pcap_strlcpy(ifr.ifr_name, handlep->device,
1316 sizeof(ifr.ifr_name));
1317 if (ioctl(handle->fd, SIOCGIFFLAGS, &ifr) == -1) {
1318 fprintf(stderr,
1319 "Can't restore interface %s flags (SIOCGIFFLAGS failed: %s).\n"
1320 "Please adjust manually.\n"
1321 "Hint: This can't happen with Linux >= 2.2.0.\n",
1322 handlep->device, strerror(errno));
1323 } else {
1324 if (ifr.ifr_flags & IFF_PROMISC) {
1325 /*
1326 * Promiscuous mode is currently on;
1327 * turn it off.
1328 */
1329 ifr.ifr_flags &= ~IFF_PROMISC;
1330 if (ioctl(handle->fd, SIOCSIFFLAGS,
1331 &ifr) == -1) {
1332 fprintf(stderr,
1333 "Can't restore interface %s flags (SIOCSIFFLAGS failed: %s).\n"
1334 "Please adjust manually.\n"
1335 "Hint: This can't happen with Linux >= 2.2.0.\n",
1336 handlep->device,
1337 strerror(errno));
1338 }
1339 }
1340 }
1341 }
1342
1343 #ifdef HAVE_LIBNL
1344 if (handlep->must_do_on_close & MUST_DELETE_MONIF) {
1345 ret = nl80211_init(handle, &nlstate, handlep->device);
1346 if (ret >= 0) {
1347 ret = del_mon_if(handle, handle->fd, &nlstate,
1348 handlep->device, handlep->mondevice);
1349 nl80211_cleanup(&nlstate);
1350 }
1351 if (ret < 0) {
1352 fprintf(stderr,
1353 "Can't delete monitor interface %s (%s).\n"
1354 "Please delete manually.\n",
1355 handlep->mondevice, handle->errbuf);
1356 }
1357 }
1358 #endif /* HAVE_LIBNL */
1359
1360 #ifdef IW_MODE_MONITOR
1361 if (handlep->must_do_on_close & MUST_CLEAR_RFMON) {
1362 /*
1363 * We put the interface into rfmon mode;
1364 * take it out of rfmon mode.
1365 *
1366 * XXX - if somebody else wants it in rfmon
1367 * mode, this code cannot know that, so it'll take
1368 * it out of rfmon mode.
1369 */
1370
1371 /*
1372 * First, take the interface down if it's up;
1373 * otherwise, we might get EBUSY.
1374 * If we get errors, just drive on and print
1375 * a warning if we can't restore the mode.
1376 */
1377 oldflags = 0;
1378 memset(&ifr, 0, sizeof(ifr));
1379 pcap_strlcpy(ifr.ifr_name, handlep->device,
1380 sizeof(ifr.ifr_name));
1381 if (ioctl(handle->fd, SIOCGIFFLAGS, &ifr) != -1) {
1382 if (ifr.ifr_flags & IFF_UP) {
1383 oldflags = ifr.ifr_flags;
1384 ifr.ifr_flags &= ~IFF_UP;
1385 if (ioctl(handle->fd, SIOCSIFFLAGS, &ifr) == -1)
1386 oldflags = 0; /* didn't set, don't restore */
1387 }
1388 }
1389
1390 /*
1391 * Now restore the mode.
1392 */
1393 pcap_strlcpy(ireq.ifr_ifrn.ifrn_name, handlep->device,
1394 sizeof ireq.ifr_ifrn.ifrn_name);
1395 ireq.u.mode = handlep->oldmode;
1396 if (ioctl(handle->fd, SIOCSIWMODE, &ireq) == -1) {
1397 /*
1398 * Scientist, you've failed.
1399 */
1400 fprintf(stderr,
1401 "Can't restore interface %s wireless mode (SIOCSIWMODE failed: %s).\n"
1402 "Please adjust manually.\n",
1403 handlep->device, strerror(errno));
1404 }
1405
1406 /*
1407 * Now bring the interface back up if we brought
1408 * it down.
1409 */
1410 if (oldflags != 0) {
1411 ifr.ifr_flags = oldflags;
1412 if (ioctl(handle->fd, SIOCSIFFLAGS, &ifr) == -1) {
1413 fprintf(stderr,
1414 "Can't bring interface %s back up (SIOCSIFFLAGS failed: %s).\n"
1415 "Please adjust manually.\n",
1416 handlep->device, strerror(errno));
1417 }
1418 }
1419 }
1420 #endif /* IW_MODE_MONITOR */
1421
1422 /*
1423 * Take this pcap out of the list of pcaps for which we
1424 * have to take the interface out of some mode.
1425 */
1426 pcap_remove_from_pcaps_to_close(handle);
1427 }
1428
1429 if (handlep->mondevice != NULL) {
1430 free(handlep->mondevice);
1431 handlep->mondevice = NULL;
1432 }
1433 if (handlep->device != NULL) {
1434 free(handlep->device);
1435 handlep->device = NULL;
1436 }
1437
1438 #ifdef HAVE_SYS_EVENTFD_H
1439 close(handlep->poll_breakloop_fd);
1440 #endif
1441 pcap_cleanup_live_common(handle);
1442 }
1443
1444 /*
1445 * Set the timeout to be used in poll() with memory-mapped packet capture.
1446 */
1447 static void
1448 set_poll_timeout(struct pcap_linux *handlep)
1449 {
1450 #ifdef HAVE_TPACKET3
1451 struct utsname utsname;
1452 char *version_component, *endp;
1453 long major, minor;
1454 int broken_tpacket_v3 = 1;
1455
1456 /*
1457 * Some versions of TPACKET_V3 have annoying bugs/misfeatures
1458 * around which we have to work. Determine if we have those
1459 * problems or not.
1460 */
1461 if (uname(&utsname) == 0) {
1462 /*
1463 * 3.19 is the first release with a fixed version of
1464 * TPACKET_V3. We treat anything before that as
1465 * not haveing a fixed version; that may really mean
1466 * it has *no* version.
1467 */
1468 version_component = utsname.release;
1469 major = strtol(version_component, &endp, 10);
1470 if (endp != version_component && *endp == '.') {
1471 /*
1472 * OK, that was a valid major version.
1473 * Get the minor version.
1474 */
1475 version_component = endp + 1;
1476 minor = strtol(version_component, &endp, 10);
1477 if (endp != version_component &&
1478 (*endp == '.' || *endp == '\0')) {
1479 /*
1480 * OK, that was a valid minor version.
1481 * Is this 3.19 or newer?
1482 */
1483 if (major >= 4 || (major == 3 && minor >= 19)) {
1484 /* Yes. TPACKET_V3 works correctly. */
1485 broken_tpacket_v3 = 0;
1486 }
1487 }
1488 }
1489 }
1490 #endif
1491 if (handlep->timeout == 0) {
1492 #ifdef HAVE_TPACKET3
1493 /*
1494 * XXX - due to a set of (mis)features in the TPACKET_V3
1495 * kernel code prior to the 3.19 kernel, blocking forever
1496 * with a TPACKET_V3 socket can, if few packets are
1497 * arriving and passing the socket filter, cause most
1498 * packets to be dropped. See libpcap issue #335 for the
1499 * full painful story.
1500 *
1501 * The workaround is to have poll() time out very quickly,
1502 * so we grab the frames handed to us, and return them to
1503 * the kernel, ASAP.
1504 */
1505 if (handlep->tp_version == TPACKET_V3 && broken_tpacket_v3)
1506 handlep->poll_timeout = 1; /* don't block for very long */
1507 else
1508 #endif
1509 handlep->poll_timeout = -1; /* block forever */
1510 } else if (handlep->timeout > 0) {
1511 #ifdef HAVE_TPACKET3
1512 /*
1513 * For TPACKET_V3, the timeout is handled by the kernel,
1514 * so block forever; that way, we don't get extra timeouts.
1515 * Don't do that if we have a broken TPACKET_V3, though.
1516 */
1517 if (handlep->tp_version == TPACKET_V3 && !broken_tpacket_v3)
1518 handlep->poll_timeout = -1; /* block forever, let TPACKET_V3 wake us up */
1519 else
1520 #endif
1521 handlep->poll_timeout = handlep->timeout; /* block for that amount of time */
1522 } else {
1523 /*
1524 * Non-blocking mode; we call poll() to pick up error
1525 * indications, but we don't want it to wait for
1526 * anything.
1527 */
1528 handlep->poll_timeout = 0;
1529 }
1530 }
1531
1532 #ifdef HAVE_SYS_EVENTFD_H
1533 static void pcap_breakloop_linux(pcap_t *handle)
1534 {
1535 pcap_breakloop_common(handle);
1536 struct pcap_linux *handlep = handle->priv;
1537
1538 uint64_t value = 1;
1539 /* XXX - what if this fails? */
1540 (void)write(handlep->poll_breakloop_fd, &value, sizeof(value));
1541 }
1542 #endif
1543
1544 #ifdef HAVE_PF_PACKET_SOCKETS
1545 /*
1546 * We need a special error return to indicate that PF_PACKET sockets
1547 * aren't supported; that's not a fatal error, it's just an indication
1548 * that we have a pre-2.2 kernel, and must fall back on PF_INET/SOCK_PACKET
1549 * sockets.
1550 *
1551 * We assume, for now, that we won't have so many PCAP_ERROR_ values that
1552 * -128 will be used, and use that as the error (it fits into a byte,
1553 * so comparison against it should be doable without too big an immediate
1554 * value - yeah, I know, premature optimization is the root of all evil...).
1555 */
1556 #define PCAP_ERROR_NO_PF_PACKET_SOCKETS -128
1557
1558 /*
1559 * Open a PF_PACKET socket.
1560 */
1561 static int
1562 open_pf_packet_socket(pcap_t *handle, int cooked)
1563 {
1564 int protocol = pcap_protocol(handle);
1565 int sock_fd, ret;
1566
1567 /*
1568 * Open a socket with protocol family packet. If cooked is true,
1569 * we open a SOCK_DGRAM socket for the cooked interface, otherwise
1570 * we open a SOCK_RAW socket for the raw interface.
1571 */
1572 sock_fd = cooked ?
1573 socket(PF_PACKET, SOCK_DGRAM, protocol) :
1574 socket(PF_PACKET, SOCK_RAW, protocol);
1575
1576 if (sock_fd == -1) {
1577 if (errno == EINVAL || errno == EAFNOSUPPORT) {
1578 /*
1579 * PF_PACKET sockets aren't supported.
1580 *
1581 * If this is the first attempt to open a PF_PACKET
1582 * socket, our caller will just want to try a
1583 * PF_INET/SOCK_PACKET socket; in other cases, we
1584 * already succeeded opening a PF_PACKET socket,
1585 * but are just switching to cooked from raw, in
1586 * which case this is a fatal error (and "can't
1587 * happen", because the kernel isn't going to
1588 * spontaneously drop its support for PF_PACKET
1589 * sockets).
1590 */
1591 snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
1592 "PF_PACKET sockets not supported (this \"can't happen\"!");
1593 return PCAP_ERROR_NO_PF_PACKET_SOCKETS;
1594 }
1595 if (errno == EPERM || errno == EACCES) {
1596 /*
1597 * You don't have permission to open the
1598 * socket.
1599 */
1600 ret = PCAP_ERROR_PERM_DENIED;
1601 } else {
1602 /*
1603 * Other error.
1604 */
1605 ret = PCAP_ERROR;
1606 }
1607 pcap_fmt_errmsg_for_errno(handle->errbuf, PCAP_ERRBUF_SIZE,
1608 errno, "socket");
1609 return ret;
1610 }
1611 return sock_fd;
1612 }
1613 #endif
1614
1615 /*
1616 * Get a handle for a live capture from the given device. You can
1617 * pass NULL as device to get all packages (without link level
1618 * information of course). If you pass 1 as promisc the interface
1619 * will be set to promiscous mode (XXX: I think this usage should
1620 * be deprecated and functions be added to select that later allow
1621 * modification of that values -- Torsten).
1622 */
1623 static int
1624 pcap_activate_linux(pcap_t *handle)
1625 {
1626 struct pcap_linux *handlep = handle->priv;
1627 const char *device;
1628 int is_any_device;
1629 struct ifreq ifr;
1630 int status = 0;
1631 int ret;
1632
1633 device = handle->opt.device;
1634
1635 /*
1636 * Make sure the name we were handed will fit into the ioctls we
1637 * might perform on the device; if not, return a "No such device"
1638 * indication, as the Linux kernel shouldn't support creating
1639 * a device whose name won't fit into those ioctls.
1640 *
1641 * "Will fit" means "will fit, complete with a null terminator",
1642 * so if the length, which does *not* include the null terminator,
1643 * is greater than *or equal to* the size of the field into which
1644 * we'll be copying it, that won't fit.
1645 */
1646 if (strlen(device) >= sizeof(ifr.ifr_name)) {
1647 status = PCAP_ERROR_NO_SUCH_DEVICE;
1648 goto fail;
1649 }
1650
1651 /*
1652 * Turn a negative snapshot value (invalid), a snapshot value of
1653 * 0 (unspecified), or a value bigger than the normal maximum
1654 * value, into the maximum allowed value.
1655 *
1656 * If some application really *needs* a bigger snapshot
1657 * length, we should just increase MAXIMUM_SNAPLEN.
1658 */
1659 if (handle->snapshot <= 0 || handle->snapshot > MAXIMUM_SNAPLEN)
1660 handle->snapshot = MAXIMUM_SNAPLEN;
1661
1662 handle->inject_op = pcap_inject_linux;
1663 handle->setfilter_op = pcap_setfilter_linux;
1664 handle->setdirection_op = pcap_setdirection_linux;
1665 handle->set_datalink_op = pcap_set_datalink_linux;
1666 handle->getnonblock_op = pcap_getnonblock_fd;
1667 handle->setnonblock_op = pcap_setnonblock_fd;
1668 handle->cleanup_op = pcap_cleanup_linux;
1669 handle->read_op = pcap_read_linux;
1670 handle->stats_op = pcap_stats_linux;
1671 #ifdef HAVE_SYS_EVENTFD_H
1672 handle->breakloop_op = pcap_breakloop_linux;
1673 #endif
1674
1675 handlep->device = strdup(device);
1676 if (handlep->device == NULL) {
1677 pcap_fmt_errmsg_for_errno(handle->errbuf, PCAP_ERRBUF_SIZE,
1678 errno, "strdup");
1679 status = PCAP_ERROR;
1680 goto fail;
1681 }
1682
1683 /*
1684 * The "any" device is a special device which causes us not
1685 * to bind to a particular device and thus to look at all
1686 * devices.
1687 */
1688 is_any_device = (strcmp(device, "any") == 0);
1689 if (is_any_device) {
1690 if (handle->opt.promisc) {
1691 handle->opt.promisc = 0;
1692 /* Just a warning. */
1693 snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
1694 "Promiscuous mode not supported on the \"any\" device");
1695 status = PCAP_WARNING_PROMISC_NOTSUP;
1696 }
1697 }
1698
1699 /* copy timeout value */
1700 handlep->timeout = handle->opt.timeout;
1701
1702 /*
1703 * If we're in promiscuous mode, then we probably want
1704 * to see when the interface drops packets too, so get an
1705 * initial count from /proc/net/dev
1706 */
1707 if (handle->opt.promisc)
1708 handlep->proc_dropped = linux_if_drops(handlep->device);
1709
1710 #ifdef HAVE_PF_PACKET_SOCKETS
1711 /*
1712 * Current Linux kernels use the protocol family PF_PACKET to
1713 * allow direct access to all packets on the network while
1714 * older kernels had a special socket type SOCK_PACKET to
1715 * implement this feature.
1716 * While this old implementation is kind of obsolete we need
1717 * to be compatible with older kernels for a while so we are
1718 * trying both methods with the newer method preferred.
1719 *
1720 * Try to activate with a PF_PACKET socket. If the "any" device
1721 * was specified, we open a SOCK_DGRAM socket for the cooked
1722 * interface, otherwise we first try a SOCK_RAW socket for
1723 * the raw interface.
1724 */
1725 ret = activate_new(handle, is_any_device);
1726 if (ret < 0) {
1727 if (ret != PCAP_ERROR_NO_PF_PACKET_SOCKETS) {
1728 /*
1729 * Fatal error; the return value is the error code,
1730 * and handle->errbuf has been set to an appropriate
1731 * error message.
1732 */
1733 return ret;
1734 }
1735
1736 /*
1737 * We don't support PF_PACKET/SOCK_whatever
1738 * sockets; try the old mechanism.
1739 */
1740 ret = activate_old(handle, is_any_device);
1741 if (ret != 0) {
1742 /*
1743 * Both methods to open the packet socket
1744 * failed.
1745 *
1746 * Tidy up and report our failure
1747 * (handle->errbuf is expected to be set
1748 * by the functions above).
1749 */
1750 status = ret;
1751 goto fail;
1752 }
1753 } else {
1754 #ifdef HAVE_PACKET_RING
1755 /*
1756 * Success.
1757 * Try to use memory-mapped access.
1758 */
1759 switch (activate_mmap(handle, &status)) {
1760
1761 case 1:
1762 /*
1763 * We succeeded. status has been
1764 * set to the status to return,
1765 * which might be 0, or might be
1766 * a PCAP_WARNING_ value.
1767 *
1768 * Set the timeout to use in poll() before
1769 * returning.
1770 */
1771 set_poll_timeout(handlep);
1772 return status;
1773
1774 case 0:
1775 /*
1776 * Kernel doesn't support it - just continue
1777 * with non-memory-mapped access.
1778 */
1779 break;
1780
1781 case -1:
1782 /*
1783 * We failed to set up to use it, or the
1784 * kernel supports it, but we failed to
1785 * enable it. status has been set to the
1786 * error status to return and, if it's
1787 * PCAP_ERROR, handle->errbuf contains
1788 * the error message.
1789 */
1790 goto fail;
1791 }
1792 #endif /* HAVE_PACKET_RING */
1793 }
1794 #else /* HAVE_PF_PACKET_SOCKETS */
1795 /*
1796 * We don't support PF_PACKET/SOCK_whatever sockets, so we must
1797 * try the old mechanism.
1798 */
1799 ret = activate_old(handle, is_any_device);
1800 if (ret != 0) {
1801 /*
1802 * That failed.
1803 *
1804 * Tidy up and report our failure
1805 * (handle->errbuf is expected to be set
1806 * by the functions above).
1807 */
1808 status = ret;
1809 goto fail;
1810 }
1811 #endif /* HAVE_PF_PACKET_SOCKETS */
1812
1813 /*
1814 * We set up the socket, but not with memory-mapped access.
1815 */
1816 if (handle->opt.buffer_size != 0) {
1817 /*
1818 * Set the socket buffer size to the specified value.
1819 */
1820 if (setsockopt(handle->fd, SOL_SOCKET, SO_RCVBUF,
1821 &handle->opt.buffer_size,
1822 sizeof(handle->opt.buffer_size)) == -1) {
1823 pcap_fmt_errmsg_for_errno(handle->errbuf,
1824 PCAP_ERRBUF_SIZE, errno, "SO_RCVBUF");
1825 status = PCAP_ERROR;
1826 goto fail;
1827 }
1828 }
1829
1830 /* Allocate the buffer */
1831
1832 handle->buffer = malloc(handle->bufsize + handle->offset);
1833 if (!handle->buffer) {
1834 pcap_fmt_errmsg_for_errno(handle->errbuf, PCAP_ERRBUF_SIZE,
1835 errno, "malloc");
1836 status = PCAP_ERROR;
1837 goto fail;
1838 }
1839
1840 /*
1841 * "handle->fd" is a socket, so "select()" and "poll()"
1842 * should work on it.
1843 */
1844 handle->selectable_fd = handle->fd;
1845
1846 return status;
1847
1848 fail:
1849 pcap_cleanup_linux(handle);
1850 return status;
1851 }
1852
1853 /*
1854 * Read at most max_packets from the capture stream and call the callback
1855 * for each of them. Returns the number of packets handled or -1 if an
1856 * error occured.
1857 */
1858 static int
1859 pcap_read_linux(pcap_t *handle, int max_packets _U_, pcap_handler callback, u_char *user)
1860 {
1861 /*
1862 * Currently, on Linux only one packet is delivered per read,
1863 * so we don't loop.
1864 */
1865 return pcap_read_packet(handle, callback, user);
1866 }
1867
1868 static int
1869 pcap_set_datalink_linux(pcap_t *handle, int dlt)
1870 {
1871 handle->linktype = dlt;
1872 return 0;
1873 }
1874
1875 /*
1876 * linux_check_direction()
1877 *
1878 * Do checks based on packet direction.
1879 */
1880 static inline int
1881 linux_check_direction(const pcap_t *handle, const struct sockaddr_ll *sll)
1882 {
1883 struct pcap_linux *handlep = handle->priv;
1884
1885 if (sll->sll_pkttype == PACKET_OUTGOING) {
1886 /*
1887 * Outgoing packet.
1888 * If this is from the loopback device, reject it;
1889 * we'll see the packet as an incoming packet as well,
1890 * and we don't want to see it twice.
1891 */
1892 if (sll->sll_ifindex == handlep->lo_ifindex)
1893 return 0;
1894
1895 /*
1896 * If this is an outgoing CAN or CAN FD frame, and
1897 * the user doesn't only want outgoing packets,
1898 * reject it; CAN devices and drivers, and the CAN
1899 * stack, always arrange to loop back transmitted
1900 * packets, so they also appear as incoming packets.
1901 * We don't want duplicate packets, and we can't
1902 * easily distinguish packets looped back by the CAN
1903 * layer than those received by the CAN layer, so we
1904 * eliminate this packet instead.
1905 */
1906 if ((sll->sll_protocol == LINUX_SLL_P_CAN ||
1907 sll->sll_protocol == LINUX_SLL_P_CANFD) &&
1908 handle->direction != PCAP_D_OUT)
1909 return 0;
1910
1911 /*
1912 * If the user only wants incoming packets, reject it.
1913 */
1914 if (handle->direction == PCAP_D_IN)
1915 return 0;
1916 } else {
1917 /*
1918 * Incoming packet.
1919 * If the user only wants outgoing packets, reject it.
1920 */
1921 if (handle->direction == PCAP_D_OUT)
1922 return 0;
1923 }
1924 return 1;
1925 }
1926
1927 /*
1928 * Read a packet from the socket calling the handler provided by
1929 * the user. Returns the number of packets received or -1 if an
1930 * error occured.
1931 */
1932 static int
1933 pcap_read_packet(pcap_t *handle, pcap_handler callback, u_char *userdata)
1934 {
1935 struct pcap_linux *handlep = handle->priv;
1936 u_char *bp;
1937 int offset;
1938 #ifdef HAVE_PF_PACKET_SOCKETS
1939 struct sockaddr_ll from;
1940 #else
1941 struct sockaddr from;
1942 #endif
1943 #if defined(HAVE_PACKET_AUXDATA) && defined(HAVE_STRUCT_TPACKET_AUXDATA_TP_VLAN_TCI)
1944 struct iovec iov;
1945 struct msghdr msg;
1946 struct cmsghdr *cmsg;
1947 union {
1948 struct cmsghdr cmsg;
1949 char buf[CMSG_SPACE(sizeof(struct tpacket_auxdata))];
1950 } cmsg_buf;
1951 #else /* defined(HAVE_PACKET_AUXDATA) && defined(HAVE_STRUCT_TPACKET_AUXDATA_TP_VLAN_TCI) */
1952 socklen_t fromlen;
1953 #endif /* defined(HAVE_PACKET_AUXDATA) && defined(HAVE_STRUCT_TPACKET_AUXDATA_TP_VLAN_TCI) */
1954 ssize_t packet_len;
1955 int caplen;
1956 struct pcap_pkthdr pcap_header;
1957
1958 struct bpf_aux_data aux_data;
1959 #ifdef HAVE_PF_PACKET_SOCKETS
1960 /*
1961 * If this is a cooked device, leave extra room for a
1962 * fake packet header.
1963 */
1964 if (handlep->cooked) {
1965 if (handle->linktype == DLT_LINUX_SLL2)
1966 offset = SLL2_HDR_LEN;
1967 else
1968 offset = SLL_HDR_LEN;
1969 } else
1970 offset = 0;
1971 #else
1972 /*
1973 * This system doesn't have PF_PACKET sockets, so it doesn't
1974 * support cooked devices.
1975 */
1976 offset = 0;
1977 #endif
1978
1979 /*
1980 * Receive a single packet from the kernel.
1981 * We ignore EINTR, as that might just be due to a signal
1982 * being delivered - if the signal should interrupt the
1983 * loop, the signal handler should call pcap_breakloop()
1984 * to set handle->break_loop (we ignore it on other
1985 * platforms as well).
1986 * We also ignore ENETDOWN, so that we can continue to
1987 * capture traffic if the interface goes down and comes
1988 * back up again; comments in the kernel indicate that
1989 * we'll just block waiting for packets if we try to
1990 * receive from a socket that delivered ENETDOWN, and,
1991 * if we're using a memory-mapped buffer, we won't even
1992 * get notified of "network down" events.
1993 */
1994 bp = (u_char *)handle->buffer + handle->offset;
1995
1996 #if defined(HAVE_PACKET_AUXDATA) && defined(HAVE_STRUCT_TPACKET_AUXDATA_TP_VLAN_TCI)
1997 msg.msg_name = &from;
1998 msg.msg_namelen = sizeof(from);
1999 msg.msg_iov = &iov;
2000 msg.msg_iovlen = 1;
2001 msg.msg_control = &cmsg_buf;
2002 msg.msg_controllen = sizeof(cmsg_buf);
2003 msg.msg_flags = 0;
2004
2005 iov.iov_len = handle->bufsize - offset;
2006 iov.iov_base = bp + offset;
2007 #endif /* defined(HAVE_PACKET_AUXDATA) && defined(HAVE_STRUCT_TPACKET_AUXDATA_TP_VLAN_TCI) */
2008
2009 do {
2010 /*
2011 * Has "pcap_breakloop()" been called?
2012 */
2013 if (handle->break_loop) {
2014 /*
2015 * Yes - clear the flag that indicates that it has,
2016 * and return PCAP_ERROR_BREAK as an indication that
2017 * we were told to break out of the loop.
2018 */
2019 handle->break_loop = 0;
2020 return PCAP_ERROR_BREAK;
2021 }
2022
2023 #if defined(HAVE_PACKET_AUXDATA) && defined(HAVE_STRUCT_TPACKET_AUXDATA_TP_VLAN_TCI)
2024 packet_len = recvmsg(handle->fd, &msg, MSG_TRUNC);
2025 #else /* defined(HAVE_PACKET_AUXDATA) && defined(HAVE_STRUCT_TPACKET_AUXDATA_TP_VLAN_TCI) */
2026 fromlen = sizeof(from);
2027 packet_len = recvfrom(
2028 handle->fd, bp + offset,
2029 handle->bufsize - offset, MSG_TRUNC,
2030 (struct sockaddr *) &from, &fromlen);
2031 #endif /* defined(HAVE_PACKET_AUXDATA) && defined(HAVE_STRUCT_TPACKET_AUXDATA_TP_VLAN_TCI) */
2032 } while (packet_len == -1 && errno == EINTR);
2033
2034 /* Check if an error occured */
2035
2036 if (packet_len == -1) {
2037 switch (errno) {
2038
2039 case EAGAIN:
2040 return 0; /* no packet there */
2041
2042 case ENETDOWN:
2043 /*
2044 * The device on which we're capturing went away.
2045 *
2046 * XXX - we should really return
2047 * PCAP_ERROR_IFACE_NOT_UP, but pcap_dispatch()
2048 * etc. aren't defined to return that.
2049 */
2050 snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
2051 "The interface went down");
2052 return PCAP_ERROR;
2053
2054 default:
2055 pcap_fmt_errmsg_for_errno(handle->errbuf,
2056 PCAP_ERRBUF_SIZE, errno, "recvfrom");
2057 return PCAP_ERROR;
2058 }
2059 }
2060
2061 #ifdef HAVE_PF_PACKET_SOCKETS
2062 if (!handlep->sock_packet) {
2063 /*
2064 * Unfortunately, there is a window between socket() and
2065 * bind() where the kernel may queue packets from any
2066 * interface. If we're bound to a particular interface,
2067 * discard packets not from that interface.
2068 *
2069 * (If socket filters are supported, we could do the
2070 * same thing we do when changing the filter; however,
2071 * that won't handle packet sockets without socket
2072 * filter support, and it's a bit more complicated.
2073 * It would save some instructions per packet, however.)
2074 */
2075 if (handlep->ifindex != -1 &&
2076 from.sll_ifindex != handlep->ifindex)
2077 return 0;
2078
2079 /*
2080 * Do checks based on packet direction.
2081 * We can only do this if we're using PF_PACKET; the
2082 * address returned for SOCK_PACKET is a "sockaddr_pkt"
2083 * which lacks the relevant packet type information.
2084 */
2085 if (!linux_check_direction(handle, &from))
2086 return 0;
2087 }
2088 #endif
2089
2090 #ifdef HAVE_PF_PACKET_SOCKETS
2091 /*
2092 * If this is a cooked device, fill in the fake packet header.
2093 */
2094 if (handlep->cooked) {
2095 /*
2096 * Add the length of the fake header to the length
2097 * of packet data we read.
2098 */
2099 if (handle->linktype == DLT_LINUX_SLL2) {
2100 struct sll2_header *hdrp;
2101
2102 packet_len += SLL2_HDR_LEN;
2103
2104 hdrp = (struct sll2_header *)bp;
2105 hdrp->sll2_protocol = from.sll_protocol;
2106 hdrp->sll2_reserved_mbz = 0;
2107 hdrp->sll2_if_index = htonl(from.sll_ifindex);
2108 hdrp->sll2_hatype = htons(from.sll_hatype);
2109 hdrp->sll2_pkttype = from.sll_pkttype;
2110 hdrp->sll2_halen = from.sll_halen;
2111 memcpy(hdrp->sll2_addr, from.sll_addr,
2112 (from.sll_halen > SLL_ADDRLEN) ?
2113 SLL_ADDRLEN :
2114 from.sll_halen);
2115 } else {
2116 struct sll_header *hdrp;
2117
2118 packet_len += SLL_HDR_LEN;
2119
2120 hdrp = (struct sll_header *)bp;
2121 hdrp->sll_pkttype = htons(from.sll_pkttype);
2122 hdrp->sll_hatype = htons(from.sll_hatype);
2123 hdrp->sll_halen = htons(from.sll_halen);
2124 memcpy(hdrp->sll_addr, from.sll_addr,
2125 (from.sll_halen > SLL_ADDRLEN) ?
2126 SLL_ADDRLEN :
2127 from.sll_halen);
2128 hdrp->sll_protocol = from.sll_protocol;
2129 }
2130 }
2131
2132 /*
2133 * Start out with no VLAN information.
2134 */
2135 aux_data.vlan_tag_present = 0;
2136 aux_data.vlan_tag = 0;
2137 #if defined(HAVE_PACKET_AUXDATA) && defined(HAVE_STRUCT_TPACKET_AUXDATA_TP_VLAN_TCI)
2138 if (handlep->vlan_offset != -1) {
2139 for (cmsg = CMSG_FIRSTHDR(&msg); cmsg; cmsg = CMSG_NXTHDR(&msg, cmsg)) {
2140 struct tpacket_auxdata *aux;
2141 size_t len;
2142 struct vlan_tag *tag;
2143
2144 if (cmsg->cmsg_len < CMSG_LEN(sizeof(struct tpacket_auxdata)) ||
2145 cmsg->cmsg_level != SOL_PACKET ||
2146 cmsg->cmsg_type != PACKET_AUXDATA) {
2147 /*
2148 * This isn't a PACKET_AUXDATA auxiliary
2149 * data item.
2150 */
2151 continue;
2152 }
2153
2154 aux = (struct tpacket_auxdata *)CMSG_DATA(cmsg);
2155 if (!VLAN_VALID(aux, aux)) {
2156 /*
2157 * There is no VLAN information in the
2158 * auxiliary data.
2159 */
2160 continue;
2161 }
2162
2163 len = (size_t)packet_len > iov.iov_len ? iov.iov_len : (u_int)packet_len;
2164 if (len < (size_t)handlep->vlan_offset)
2165 break;
2166
2167 /*
2168 * Move everything in the header, except the
2169 * type field, down VLAN_TAG_LEN bytes, to
2170 * allow us to insert the VLAN tag between
2171 * that stuff and the type field.
2172 */
2173 bp -= VLAN_TAG_LEN;
2174 memmove(bp, bp + VLAN_TAG_LEN, handlep->vlan_offset);
2175
2176 /*
2177 * Now insert the tag.
2178 */
2179 tag = (struct vlan_tag *)(bp + handlep->vlan_offset);
2180 tag->vlan_tpid = htons(VLAN_TPID(aux, aux));
2181 tag->vlan_tci = htons(aux->tp_vlan_tci);
2182
2183 /*
2184 * Save a flag indicating that we have a VLAN tag,
2185 * and the VLAN TCI, to bpf_aux_data struct for
2186 * use by the BPF filter if we're doing the
2187 * filtering in userland.
2188 */
2189 aux_data.vlan_tag_present = 1;
2190 aux_data.vlan_tag = htons(aux->tp_vlan_tci) & 0x0fff;
2191
2192 /*
2193 * Add the tag to the packet lengths.
2194 */
2195 packet_len += VLAN_TAG_LEN;
2196 }
2197 }
2198 #endif /* defined(HAVE_PACKET_AUXDATA) && defined(HAVE_STRUCT_TPACKET_AUXDATA_TP_VLAN_TCI) */
2199 #endif /* HAVE_PF_PACKET_SOCKETS */
2200
2201 /*
2202 * XXX: According to the kernel source we should get the real
2203 * packet len if calling recvfrom with MSG_TRUNC set. It does
2204 * not seem to work here :(, but it is supported by this code
2205 * anyway.
2206 * To be honest the code RELIES on that feature so this is really
2207 * broken with 2.2.x kernels.
2208 * I spend a day to figure out what's going on and I found out
2209 * that the following is happening:
2210 *
2211 * The packet comes from a random interface and the packet_rcv
2212 * hook is called with a clone of the packet. That code inserts
2213 * the packet into the receive queue of the packet socket.
2214 * If a filter is attached to that socket that filter is run
2215 * first - and there lies the problem. The default filter always
2216 * cuts the packet at the snaplen:
2217 *
2218 * # tcpdump -d
2219 * (000) ret #68
2220 *
2221 * So the packet filter cuts down the packet. The recvfrom call
2222 * says "hey, it's only 68 bytes, it fits into the buffer" with
2223 * the result that we don't get the real packet length. This
2224 * is valid at least until kernel 2.2.17pre6.
2225 *
2226 * We currently handle this by making a copy of the filter
2227 * program, fixing all "ret" instructions with non-zero
2228 * operands to have an operand of MAXIMUM_SNAPLEN so that the
2229 * filter doesn't truncate the packet, and supplying that modified
2230 * filter to the kernel.
2231 */
2232
2233 caplen = (int)packet_len;
2234 if (caplen > handle->snapshot)
2235 caplen = handle->snapshot;
2236
2237 /* Run the packet filter if not using kernel filter */
2238 if (handlep->filter_in_userland && handle->fcode.bf_insns) {
2239 if (pcap_filter_with_aux_data(handle->fcode.bf_insns, bp,
2240 (int)packet_len, caplen, &aux_data) == 0) {
2241 /* rejected by filter */
2242 return 0;
2243 }
2244 }
2245
2246 /* Fill in our own header data */
2247
2248 /* get timestamp for this packet */
2249 #if defined(SIOCGSTAMPNS) && defined(SO_TIMESTAMPNS)
2250 if (handle->opt.tstamp_precision == PCAP_TSTAMP_PRECISION_NANO) {
2251 if (ioctl(handle->fd, SIOCGSTAMPNS, &pcap_header.ts) == -1) {
2252 pcap_fmt_errmsg_for_errno(handle->errbuf,
2253 PCAP_ERRBUF_SIZE, errno, "SIOCGSTAMPNS");
2254 return PCAP_ERROR;
2255 }
2256 } else
2257 #endif
2258 {
2259 if (ioctl(handle->fd, SIOCGSTAMP, &pcap_header.ts) == -1) {
2260 pcap_fmt_errmsg_for_errno(handle->errbuf,
2261 PCAP_ERRBUF_SIZE, errno, "SIOCGSTAMP");
2262 return PCAP_ERROR;
2263 }
2264 }
2265
2266 pcap_header.caplen = caplen;
2267 pcap_header.len = (bpf_u_int32)packet_len;
2268
2269 /*
2270 * Count the packet.
2271 *
2272 * Arguably, we should count them before we check the filter,
2273 * as on many other platforms "ps_recv" counts packets
2274 * handed to the filter rather than packets that passed
2275 * the filter, but if filtering is done in the kernel, we
2276 * can't get a count of packets that passed the filter,
2277 * and that would mean the meaning of "ps_recv" wouldn't
2278 * be the same on all Linux systems.
2279 *
2280 * XXX - it's not the same on all systems in any case;
2281 * ideally, we should have a "get the statistics" call
2282 * that supplies more counts and indicates which of them
2283 * it supplies, so that we supply a count of packets
2284 * handed to the filter only on platforms where that
2285 * information is available.
2286 *
2287 * We count them here even if we can get the packet count
2288 * from the kernel, as we can only determine at run time
2289 * whether we'll be able to get it from the kernel (if
2290 * HAVE_STRUCT_TPACKET_STATS isn't defined, we can't get it from
2291 * the kernel, but if it is defined, the library might
2292 * have been built with a 2.4 or later kernel, but we
2293 * might be running on a 2.2[.x] kernel without Alexey
2294 * Kuznetzov's turbopacket patches, and thus the kernel
2295 * might not be able to supply those statistics). We
2296 * could, I guess, try, when opening the socket, to get
2297 * the statistics, and if we can not increment the count
2298 * here, but it's not clear that always incrementing
2299 * the count is more expensive than always testing a flag
2300 * in memory.
2301 *
2302 * We keep the count in "handlep->packets_read", and use that
2303 * for "ps_recv" if we can't get the statistics from the kernel.
2304 * We do that because, if we *can* get the statistics from
2305 * the kernel, we use "handlep->stat.ps_recv" and
2306 * "handlep->stat.ps_drop" as running counts, as reading the
2307 * statistics from the kernel resets the kernel statistics,
2308 * and if we directly increment "handlep->stat.ps_recv" here,
2309 * that means it will count packets *twice* on systems where
2310 * we can get kernel statistics - once here, and once in
2311 * pcap_stats_linux().
2312 */
2313 handlep->packets_read++;
2314
2315 /* Call the user supplied callback function */
2316 callback(userdata, &pcap_header, bp);
2317
2318 return 1;
2319 }
2320
2321 static int
2322 pcap_inject_linux(pcap_t *handle, const void *buf, int size)
2323 {
2324 struct pcap_linux *handlep = handle->priv;
2325 int ret;
2326
2327 #ifdef HAVE_PF_PACKET_SOCKETS
2328 if (!handlep->sock_packet) {
2329 /* PF_PACKET socket */
2330 if (handlep->ifindex == -1) {
2331 /*
2332 * We don't support sending on the "any" device.
2333 */
2334 pcap_strlcpy(handle->errbuf,
2335 "Sending packets isn't supported on the \"any\" device",
2336 PCAP_ERRBUF_SIZE);
2337 return (-1);
2338 }
2339
2340 if (handlep->cooked) {
2341 /*
2342 * We don't support sending on cooked-mode sockets.
2343 *
2344 * XXX - how do you send on a bound cooked-mode
2345 * socket?
2346 * Is a "sendto()" required there?
2347 */
2348 pcap_strlcpy(handle->errbuf,
2349 "Sending packets isn't supported in cooked mode",
2350 PCAP_ERRBUF_SIZE);
2351 return (-1);
2352 }
2353 }
2354 #endif
2355
2356 ret = (int)send(handle->fd, buf, size, 0);
2357 if (ret == -1) {
2358 pcap_fmt_errmsg_for_errno(handle->errbuf, PCAP_ERRBUF_SIZE,
2359 errno, "send");
2360 return (-1);
2361 }
2362 return (ret);
2363 }
2364
2365 /*
2366 * Get the statistics for the given packet capture handle.
2367 * Reports the number of dropped packets iff the kernel supports
2368 * the PACKET_STATISTICS "getsockopt()" argument (2.4 and later
2369 * kernels, and 2.2[.x] kernels with Alexey Kuznetzov's turbopacket
2370 * patches); otherwise, that information isn't available, and we lie
2371 * and report 0 as the count of dropped packets.
2372 */
2373 static int
2374 pcap_stats_linux(pcap_t *handle, struct pcap_stat *stats)
2375 {
2376 struct pcap_linux *handlep = handle->priv;
2377 #ifdef HAVE_STRUCT_TPACKET_STATS
2378 #ifdef HAVE_TPACKET3
2379 /*
2380 * For sockets using TPACKET_V1 or TPACKET_V2, the extra
2381 * stuff at the end of a struct tpacket_stats_v3 will not
2382 * be filled in, and we don't look at it so this is OK even
2383 * for those sockets. In addition, the PF_PACKET socket
2384 * code in the kernel only uses the length parameter to
2385 * compute how much data to copy out and to indicate how
2386 * much data was copied out, so it's OK to base it on the
2387 * size of a struct tpacket_stats.
2388 *
2389 * XXX - it's probably OK, in fact, to just use a
2390 * struct tpacket_stats for V3 sockets, as we don't
2391 * care about the tp_freeze_q_cnt stat.
2392 */
2393 struct tpacket_stats_v3 kstats;
2394 #else /* HAVE_TPACKET3 */
2395 struct tpacket_stats kstats;
2396 #endif /* HAVE_TPACKET3 */
2397 socklen_t len = sizeof (struct tpacket_stats);
2398 #endif /* HAVE_STRUCT_TPACKET_STATS */
2399
2400 long if_dropped = 0;
2401
2402 /*
2403 * To fill in ps_ifdrop, we parse /proc/net/dev for the number
2404 */
2405 if (handle->opt.promisc)
2406 {
2407 if_dropped = handlep->proc_dropped;
2408 handlep->proc_dropped = linux_if_drops(handlep->device);
2409 handlep->stat.ps_ifdrop += (handlep->proc_dropped - if_dropped);
2410 }
2411
2412 #ifdef HAVE_STRUCT_TPACKET_STATS
2413 /*
2414 * Try to get the packet counts from the kernel.
2415 */
2416 if (getsockopt(handle->fd, SOL_PACKET, PACKET_STATISTICS,
2417 &kstats, &len) > -1) {
2418 /*
2419 * On systems where the PACKET_STATISTICS "getsockopt()"
2420 * argument is supported on PF_PACKET sockets:
2421 *
2422 * "ps_recv" counts only packets that *passed* the
2423 * filter, not packets that didn't pass the filter.
2424 * This includes packets later dropped because we
2425 * ran out of buffer space.
2426 *
2427 * "ps_drop" counts packets dropped because we ran
2428 * out of buffer space. It doesn't count packets
2429 * dropped by the interface driver. It counts only
2430 * packets that passed the filter.
2431 *
2432 * See above for ps_ifdrop.
2433 *
2434 * Both statistics include packets not yet read from
2435 * the kernel by libpcap, and thus not yet seen by
2436 * the application.
2437 *
2438 * In "linux/net/packet/af_packet.c", at least in the
2439 * 2.4.9 kernel, "tp_packets" is incremented for every
2440 * packet that passes the packet filter *and* is
2441 * successfully queued on the socket; "tp_drops" is
2442 * incremented for every packet dropped because there's
2443 * not enough free space in the socket buffer.
2444 *
2445 * When the statistics are returned for a PACKET_STATISTICS
2446 * "getsockopt()" call, "tp_drops" is added to "tp_packets",
2447 * so that "tp_packets" counts all packets handed to
2448 * the PF_PACKET socket, including packets dropped because
2449 * there wasn't room on the socket buffer - but not
2450 * including packets that didn't pass the filter.
2451 *
2452 * In the BSD BPF, the count of received packets is
2453 * incremented for every packet handed to BPF, regardless
2454 * of whether it passed the filter.
2455 *
2456 * We can't make "pcap_stats()" work the same on both
2457 * platforms, but the best approximation is to return
2458 * "tp_packets" as the count of packets and "tp_drops"
2459 * as the count of drops.
2460 *
2461 * Keep a running total because each call to
2462 * getsockopt(handle->fd, SOL_PACKET, PACKET_STATISTICS, ....
2463 * resets the counters to zero.
2464 */
2465 handlep->stat.ps_recv += kstats.tp_packets;
2466 handlep->stat.ps_drop += kstats.tp_drops;
2467 *stats = handlep->stat;
2468 return 0;
2469 }
2470 else
2471 {
2472 /*
2473 * If the error was EOPNOTSUPP, fall through, so that
2474 * if you build the library on a system with
2475 * "struct tpacket_stats" and run it on a system
2476 * that doesn't, it works as it does if the library
2477 * is built on a system without "struct tpacket_stats".
2478 */
2479 if (errno != EOPNOTSUPP) {
2480 pcap_fmt_errmsg_for_errno(handle->errbuf,
2481 PCAP_ERRBUF_SIZE, errno, "pcap_stats");
2482 return -1;
2483 }
2484 }
2485 #endif
2486 /*
2487 * On systems where the PACKET_STATISTICS "getsockopt()" argument
2488 * is not supported on PF_PACKET sockets:
2489 *
2490 * "ps_recv" counts only packets that *passed* the filter,
2491 * not packets that didn't pass the filter. It does not
2492 * count packets dropped because we ran out of buffer
2493 * space.
2494 *
2495 * "ps_drop" is not supported.
2496 *
2497 * "ps_ifdrop" is supported. It will return the number
2498 * of drops the interface reports in /proc/net/dev,
2499 * if that is available.
2500 *
2501 * "ps_recv" doesn't include packets not yet read from
2502 * the kernel by libpcap.
2503 *
2504 * We maintain the count of packets processed by libpcap in
2505 * "handlep->packets_read", for reasons described in the comment
2506 * at the end of pcap_read_packet(). We have no idea how many
2507 * packets were dropped by the kernel buffers -- but we know
2508 * how many the interface dropped, so we can return that.
2509 */
2510
2511 stats->ps_recv = handlep->packets_read;
2512 stats->ps_drop = 0;
2513 stats->ps_ifdrop = handlep->stat.ps_ifdrop;
2514 return 0;
2515 }
2516
2517 static int
2518 add_linux_if(pcap_if_list_t *devlistp, const char *ifname, int fd, char *errbuf)
2519 {
2520 const char *p;
2521 char name[512]; /* XXX - pick a size */
2522 char *q, *saveq;
2523 struct ifreq ifrflags;
2524
2525 /*
2526 * Get the interface name.
2527 */
2528 p = ifname;
2529 q = &name[0];
2530 while (*p != '\0' && *p != ' ' && *p != '\t' && *p != '\n') {
2531 if (*p == ':') {
2532 /*
2533 * This could be the separator between a
2534 * name and an alias number, or it could be
2535 * the separator between a name with no
2536 * alias number and the next field.
2537 *
2538 * If there's a colon after digits, it
2539 * separates the name and the alias number,
2540 * otherwise it separates the name and the
2541 * next field.
2542 */
2543 saveq = q;
2544 while (PCAP_ISDIGIT(*p))
2545 *q++ = *p++;
2546 if (*p != ':') {
2547 /*
2548 * That was the next field,
2549 * not the alias number.
2550 */
2551 q = saveq;
2552 }
2553 break;
2554 } else
2555 *q++ = *p++;
2556 }
2557 *q = '\0';
2558
2559 /*
2560 * Get the flags for this interface.
2561 */
2562 pcap_strlcpy(ifrflags.ifr_name, name, sizeof(ifrflags.ifr_name));
2563 if (ioctl(fd, SIOCGIFFLAGS, (char *)&ifrflags) < 0) {
2564 if (errno == ENXIO || errno == ENODEV)
2565 return (0); /* device doesn't actually exist - ignore it */
2566 pcap_fmt_errmsg_for_errno(errbuf, PCAP_ERRBUF_SIZE,
2567 errno, "SIOCGIFFLAGS: %.*s",
2568 (int)sizeof(ifrflags.ifr_name),
2569 ifrflags.ifr_name);
2570 return (-1);
2571 }
2572
2573 /*
2574 * Add an entry for this interface, with no addresses, if it's
2575 * not already in the list.
2576 */
2577 if (find_or_add_if(devlistp, name, ifrflags.ifr_flags,
2578 get_if_flags, errbuf) == NULL) {
2579 /*
2580 * Failure.
2581 */
2582 return (-1);
2583 }
2584
2585 return (0);
2586 }
2587
2588 /*
2589 * Get from "/sys/class/net" all interfaces listed there; if they're
2590 * already in the list of interfaces we have, that won't add another
2591 * instance, but if they're not, that'll add them.
2592 *
2593 * We don't bother getting any addresses for them; it appears you can't
2594 * use SIOCGIFADDR on Linux to get IPv6 addresses for interfaces, and,
2595 * although some other types of addresses can be fetched with SIOCGIFADDR,
2596 * we don't bother with them for now.
2597 *
2598 * We also don't fail if we couldn't open "/sys/class/net"; we just leave
2599 * the list of interfaces as is, and return 0, so that we can try
2600 * scanning /proc/net/dev.
2601 *
2602 * Otherwise, we return 1 if we don't get an error and -1 if we do.
2603 */
2604 static int
2605 scan_sys_class_net(pcap_if_list_t *devlistp, char *errbuf)
2606 {
2607 DIR *sys_class_net_d;
2608 int fd;
2609 struct dirent *ent;
2610 char subsystem_path[PATH_MAX+1];
2611 struct stat statb;
2612 int ret = 1;
2613
2614 sys_class_net_d = opendir("/sys/class/net");
2615 if (sys_class_net_d == NULL) {
2616 /*
2617 * Don't fail if it doesn't exist at all.
2618 */
2619 if (errno == ENOENT)
2620 return (0);
2621
2622 /*
2623 * Fail if we got some other error.
2624 */
2625 pcap_fmt_errmsg_for_errno(errbuf, PCAP_ERRBUF_SIZE,
2626 errno, "Can't open /sys/class/net");
2627 return (-1);
2628 }
2629
2630 /*
2631 * Create a socket from which to fetch interface information.
2632 */
2633 fd = socket(PF_UNIX, SOCK_RAW, 0);
2634 if (fd < 0) {
2635 pcap_fmt_errmsg_for_errno(errbuf, PCAP_ERRBUF_SIZE,
2636 errno, "socket");
2637 (void)closedir(sys_class_net_d);
2638 return (-1);
2639 }
2640
2641 for (;;) {
2642 errno = 0;
2643 ent = readdir(sys_class_net_d);
2644 if (ent == NULL) {
2645 /*
2646 * Error or EOF; if errno != 0, it's an error.
2647 */
2648 break;
2649 }
2650
2651 /*
2652 * Ignore "." and "..".
2653 */
2654 if (strcmp(ent->d_name, ".") == 0 ||
2655 strcmp(ent->d_name, "..") == 0)
2656 continue;
2657
2658 /*
2659 * Ignore plain files; they do not have subdirectories
2660 * and thus have no attributes.
2661 */
2662 if (ent->d_type == DT_REG)
2663 continue;
2664
2665 /*
2666 * Is there an "ifindex" file under that name?
2667 * (We don't care whether it's a directory or
2668 * a symlink; older kernels have directories
2669 * for devices, newer kernels have symlinks to
2670 * directories.)
2671 */
2672 snprintf(subsystem_path, sizeof subsystem_path,
2673 "/sys/class/net/%s/ifindex", ent->d_name);
2674 if (lstat(subsystem_path, &statb) != 0) {
2675 /*
2676 * Stat failed. Either there was an error
2677 * other than ENOENT, and we don't know if
2678 * this is an interface, or it's ENOENT,
2679 * and either some part of "/sys/class/net/{if}"
2680 * disappeared, in which case it probably means
2681 * the interface disappeared, or there's no
2682 * "ifindex" file, which means it's not a
2683 * network interface.
2684 */
2685 continue;
2686 }
2687
2688 /*
2689 * Attempt to add the interface.
2690 */
2691 if (add_linux_if(devlistp, &ent->d_name[0], fd, errbuf) == -1) {
2692 /* Fail. */
2693 ret = -1;
2694 break;
2695 }
2696 }
2697 if (ret != -1) {
2698 /*
2699 * Well, we didn't fail for any other reason; did we
2700 * fail due to an error reading the directory?
2701 */
2702 if (errno != 0) {
2703 pcap_fmt_errmsg_for_errno(errbuf, PCAP_ERRBUF_SIZE,
2704 errno, "Error reading /sys/class/net");
2705 ret = -1;
2706 }
2707 }
2708
2709 (void)close(fd);
2710 (void)closedir(sys_class_net_d);
2711 return (ret);
2712 }
2713
2714 /*
2715 * Get from "/proc/net/dev" all interfaces listed there; if they're
2716 * already in the list of interfaces we have, that won't add another
2717 * instance, but if they're not, that'll add them.
2718 *
2719 * See comments from scan_sys_class_net().
2720 */
2721 static int
2722 scan_proc_net_dev(pcap_if_list_t *devlistp, char *errbuf)
2723 {
2724 FILE *proc_net_f;
2725 int fd;
2726 char linebuf[512];
2727 int linenum;
2728 char *p;
2729 int ret = 0;
2730
2731 proc_net_f = fopen("/proc/net/dev", "r");
2732 if (proc_net_f == NULL) {
2733 /*
2734 * Don't fail if it doesn't exist at all.
2735 */
2736 if (errno == ENOENT)
2737 return (0);
2738
2739 /*
2740 * Fail if we got some other error.
2741 */
2742 pcap_fmt_errmsg_for_errno(errbuf, PCAP_ERRBUF_SIZE,
2743 errno, "Can't open /proc/net/dev");
2744 return (-1);
2745 }
2746
2747 /*
2748 * Create a socket from which to fetch interface information.
2749 */
2750 fd = socket(PF_UNIX, SOCK_RAW, 0);
2751 if (fd < 0) {
2752 pcap_fmt_errmsg_for_errno(errbuf, PCAP_ERRBUF_SIZE,
2753 errno, "socket");
2754 (void)fclose(proc_net_f);
2755 return (-1);
2756 }
2757
2758 for (linenum = 1;
2759 fgets(linebuf, sizeof linebuf, proc_net_f) != NULL; linenum++) {
2760 /*
2761 * Skip the first two lines - they're headers.
2762 */
2763 if (linenum <= 2)
2764 continue;
2765
2766 p = &linebuf[0];
2767
2768 /*
2769 * Skip leading white space.
2770 */
2771 while (*p == ' ' || *p == '\t')
2772 p++;
2773 if (*p == '\0' || *p == '\n')
2774 continue; /* blank line */
2775
2776 /*
2777 * Attempt to add the interface.
2778 */
2779 if (add_linux_if(devlistp, p, fd, errbuf) == -1) {
2780 /* Fail. */
2781 ret = -1;
2782 break;
2783 }
2784 }
2785 if (ret != -1) {
2786 /*
2787 * Well, we didn't fail for any other reason; did we
2788 * fail due to an error reading the file?
2789 */
2790 if (ferror(proc_net_f)) {
2791 pcap_fmt_errmsg_for_errno(errbuf, PCAP_ERRBUF_SIZE,
2792 errno, "Error reading /proc/net/dev");
2793 ret = -1;
2794 }
2795 }
2796
2797 (void)close(fd);
2798 (void)fclose(proc_net_f);
2799 return (ret);
2800 }
2801
2802 /*
2803 * Description string for the "any" device.
2804 */
2805 static const char any_descr[] = "Pseudo-device that captures on all interfaces";
2806
2807 /*
2808 * A SOCK_PACKET or PF_PACKET socket can be bound to any network interface.
2809 */
2810 static int
2811 can_be_bound(const char *name _U_)
2812 {
2813 return (1);
2814 }
2815
2816 /*
2817 * Get additional flags for a device, using SIOCGIFMEDIA.
2818 */
2819 static int
2820 get_if_flags(const char *name, bpf_u_int32 *flags, char *errbuf)
2821 {
2822 int sock;
2823 FILE *fh;
2824 unsigned int arptype;
2825 struct ifreq ifr;
2826 struct ethtool_value info;
2827
2828 if (*flags & PCAP_IF_LOOPBACK) {
2829 /*
2830 * Loopback devices aren't wireless, and "connected"/
2831 * "disconnected" doesn't apply to them.
2832 */
2833 *flags |= PCAP_IF_CONNECTION_STATUS_NOT_APPLICABLE;
2834 return 0;
2835 }
2836
2837 sock = socket(AF_INET, SOCK_DGRAM, 0);
2838 if (sock == -1) {
2839 pcap_fmt_errmsg_for_errno(errbuf, PCAP_ERRBUF_SIZE, errno,
2840 "Can't create socket to get ethtool information for %s",
2841 name);
2842 return -1;
2843 }
2844
2845 /*
2846 * OK, what type of network is this?
2847 * In particular, is it wired or wireless?
2848 */
2849 if (is_wifi(sock, name)) {
2850 /*
2851 * Wi-Fi, hence wireless.
2852 */
2853 *flags |= PCAP_IF_WIRELESS;
2854 } else {
2855 /*
2856 * OK, what does /sys/class/net/{if}/type contain?
2857 * (We don't use that for Wi-Fi, as it'll report
2858 * "Ethernet", i.e. ARPHRD_ETHER, for non-monitor-
2859 * mode devices.)
2860 */
2861 char *pathstr;
2862
2863 if (asprintf(&pathstr, "/sys/class/net/%s/type", name) == -1) {
2864 snprintf(errbuf, PCAP_ERRBUF_SIZE,
2865 "%s: Can't generate path name string for /sys/class/net device",
2866 name);
2867 close(sock);
2868 return -1;
2869 }
2870 fh = fopen(pathstr, "r");
2871 if (fh != NULL) {
2872 if (fscanf(fh, "%u", &arptype) == 1) {
2873 /*
2874 * OK, we got an ARPHRD_ type; what is it?
2875 */
2876 switch (arptype) {
2877
2878 #ifdef ARPHRD_LOOPBACK
2879 case ARPHRD_LOOPBACK:
2880 /*
2881 * These are types to which
2882 * "connected" and "disconnected"
2883 * don't apply, so don't bother
2884 * asking about it.
2885 *
2886 * XXX - add other types?
2887 */
2888 close(sock);
2889 fclose(fh);
2890 free(pathstr);
2891 return 0;
2892 #endif
2893
2894 case ARPHRD_IRDA:
2895 case ARPHRD_IEEE80211:
2896 case ARPHRD_IEEE80211_PRISM:
2897 case ARPHRD_IEEE80211_RADIOTAP:
2898 #ifdef ARPHRD_IEEE802154
2899 case ARPHRD_IEEE802154:
2900 #endif
2901 #ifdef ARPHRD_IEEE802154_MONITOR
2902 case ARPHRD_IEEE802154_MONITOR:
2903 #endif
2904 #ifdef ARPHRD_6LOWPAN
2905 case ARPHRD_6LOWPAN:
2906 #endif
2907 /*
2908 * Various wireless types.
2909 */
2910 *flags |= PCAP_IF_WIRELESS;
2911 break;
2912 }
2913 }
2914 fclose(fh);
2915 free(pathstr);
2916 }
2917 }
2918
2919 #ifdef ETHTOOL_GLINK
2920 memset(&ifr, 0, sizeof(ifr));
2921 pcap_strlcpy(ifr.ifr_name, name, sizeof(ifr.ifr_name));
2922 info.cmd = ETHTOOL_GLINK;
2923 ifr.ifr_data = (caddr_t)&info;
2924 if (ioctl(sock, SIOCETHTOOL, &ifr) == -1) {
2925 int save_errno = errno;
2926
2927 switch (save_errno) {
2928
2929 case EOPNOTSUPP:
2930 case EINVAL:
2931 /*
2932 * OK, this OS version or driver doesn't support
2933 * asking for this information.
2934 * XXX - distinguish between "this doesn't
2935 * support ethtool at all because it's not
2936 * that type of device" vs. "this doesn't
2937 * support ethtool even though it's that
2938 * type of device", and return "unknown".
2939 */
2940 *flags |= PCAP_IF_CONNECTION_STATUS_NOT_APPLICABLE;
2941 close(sock);
2942 return 0;
2943
2944 case ENODEV:
2945 /*
2946 * OK, no such device.
2947 * The user will find that out when they try to
2948 * activate the device; just say "OK" and
2949 * don't set anything.
2950 */
2951 close(sock);
2952 return 0;
2953
2954 default:
2955 /*
2956 * Other error.
2957 */
2958 pcap_fmt_errmsg_for_errno(errbuf, PCAP_ERRBUF_SIZE,
2959 save_errno,
2960 "%s: SIOCETHTOOL(ETHTOOL_GLINK) ioctl failed",
2961 name);
2962 close(sock);
2963 return -1;
2964 }
2965 }
2966
2967 /*
2968 * Is it connected?
2969 */
2970 if (info.data) {
2971 /*
2972 * It's connected.
2973 */
2974 *flags |= PCAP_IF_CONNECTION_STATUS_CONNECTED;
2975 } else {
2976 /*
2977 * It's disconnected.
2978 */
2979 *flags |= PCAP_IF_CONNECTION_STATUS_DISCONNECTED;
2980 }
2981 #endif
2982
2983 close(sock);
2984 return 0;
2985 }
2986
2987 int
2988 pcap_platform_finddevs(pcap_if_list_t *devlistp, char *errbuf)
2989 {
2990 int ret;
2991
2992 /*
2993 * Get the list of regular interfaces first.
2994 */
2995 if (pcap_findalldevs_interfaces(devlistp, errbuf, can_be_bound,
2996 get_if_flags) == -1)
2997 return (-1); /* failure */
2998
2999 /*
3000 * Read "/sys/class/net", and add to the list of interfaces all
3001 * interfaces listed there that we don't already have, because,
3002 * on Linux, SIOCGIFCONF reports only interfaces with IPv4 addresses,
3003 * and even getifaddrs() won't return information about
3004 * interfaces with no addresses, so you need to read "/sys/class/net"
3005 * to get the names of the rest of the interfaces.
3006 */
3007 ret = scan_sys_class_net(devlistp, errbuf);
3008 if (ret == -1)
3009 return (-1); /* failed */
3010 if (ret == 0) {
3011 /*
3012 * No /sys/class/net; try reading /proc/net/dev instead.
3013 */
3014 if (scan_proc_net_dev(devlistp, errbuf) == -1)
3015 return (-1);
3016 }
3017
3018 /*
3019 * Add the "any" device.
3020 * As it refers to all network devices, not to any particular
3021 * network device, the notion of "connected" vs. "disconnected"
3022 * doesn't apply.
3023 */
3024 if (add_dev(devlistp, "any",
3025 PCAP_IF_UP|PCAP_IF_RUNNING|PCAP_IF_CONNECTION_STATUS_NOT_APPLICABLE,
3026 any_descr, errbuf) == NULL)
3027 return (-1);
3028
3029 return (0);
3030 }
3031
3032 /*
3033 * Attach the given BPF code to the packet capture device.
3034 */
3035 static int
3036 pcap_setfilter_linux_common(pcap_t *handle, struct bpf_program *filter,
3037 int is_mmapped)
3038 {
3039 struct pcap_linux *handlep;
3040 #ifdef SO_ATTACH_FILTER
3041 struct sock_fprog fcode;
3042 int can_filter_in_kernel;
3043 int err = 0;
3044 #endif
3045
3046 if (!handle)
3047 return -1;
3048 if (!filter) {
3049 pcap_strlcpy(handle->errbuf, "setfilter: No filter specified",
3050 PCAP_ERRBUF_SIZE);
3051 return -1;
3052 }
3053
3054 handlep = handle->priv;
3055
3056 /* Make our private copy of the filter */
3057
3058 if (install_bpf_program(handle, filter) < 0)
3059 /* install_bpf_program() filled in errbuf */
3060 return -1;
3061
3062 /*
3063 * Run user level packet filter by default. Will be overriden if
3064 * installing a kernel filter succeeds.
3065 */
3066 handlep->filter_in_userland = 1;
3067
3068 /* Install kernel level filter if possible */
3069
3070 #ifdef SO_ATTACH_FILTER
3071 #ifdef USHRT_MAX
3072 if (handle->fcode.bf_len > USHRT_MAX) {
3073 /*
3074 * fcode.len is an unsigned short for current kernel.
3075 * I have yet to see BPF-Code with that much
3076 * instructions but still it is possible. So for the
3077 * sake of correctness I added this check.
3078 */
3079 fprintf(stderr, "Warning: Filter too complex for kernel\n");
3080 fcode.len = 0;
3081 fcode.filter = NULL;
3082 can_filter_in_kernel = 0;
3083 } else
3084 #endif /* USHRT_MAX */
3085 {
3086 /*
3087 * Oh joy, the Linux kernel uses struct sock_fprog instead
3088 * of struct bpf_program and of course the length field is
3089 * of different size. Pointed out by Sebastian
3090 *
3091 * Oh, and we also need to fix it up so that all "ret"
3092 * instructions with non-zero operands have MAXIMUM_SNAPLEN
3093 * as the operand if we're not capturing in memory-mapped
3094 * mode, and so that, if we're in cooked mode, all memory-
3095 * reference instructions use special magic offsets in
3096 * references to the link-layer header and assume that the
3097 * link-layer payload begins at 0; "fix_program()" will do
3098 * that.
3099 */
3100 switch (fix_program(handle, &fcode, is_mmapped)) {
3101
3102 case -1:
3103 default:
3104 /*
3105 * Fatal error; just quit.
3106 * (The "default" case shouldn't happen; we
3107 * return -1 for that reason.)
3108 */
3109 return -1;
3110
3111 case 0:
3112 /*
3113 * The program performed checks that we can't make
3114 * work in the kernel.
3115 */
3116 can_filter_in_kernel = 0;
3117 break;
3118
3119 case 1:
3120 /*
3121 * We have a filter that'll work in the kernel.
3122 */
3123 can_filter_in_kernel = 1;
3124 break;
3125 }
3126 }
3127
3128 /*
3129 * NOTE: at this point, we've set both the "len" and "filter"
3130 * fields of "fcode". As of the 2.6.32.4 kernel, at least,
3131 * those are the only members of the "sock_fprog" structure,
3132 * so we initialize every member of that structure.
3133 *
3134 * If there is anything in "fcode" that is not initialized,
3135 * it is either a field added in a later kernel, or it's
3136 * padding.
3137 *
3138 * If a new field is added, this code needs to be updated
3139 * to set it correctly.
3140 *
3141 * If there are no other fields, then:
3142 *
3143 * if the Linux kernel looks at the padding, it's
3144 * buggy;
3145 *
3146 * if the Linux kernel doesn't look at the padding,
3147 * then if some tool complains that we're passing
3148 * uninitialized data to the kernel, then the tool
3149 * is buggy and needs to understand that it's just
3150 * padding.
3151 */
3152 if (can_filter_in_kernel) {
3153 if ((err = set_kernel_filter(handle, &fcode)) == 0)
3154 {
3155 /*
3156 * Installation succeded - using kernel filter,
3157 * so userland filtering not needed.
3158 */
3159 handlep->filter_in_userland = 0;
3160 }
3161 else if (err == -1) /* Non-fatal error */
3162 {
3163 /*
3164 * Print a warning if we weren't able to install
3165 * the filter for a reason other than "this kernel
3166 * isn't configured to support socket filters.
3167 */
3168 if (errno != ENOPROTOOPT && errno != EOPNOTSUPP) {
3169 fprintf(stderr,
3170 "Warning: Kernel filter failed: %s\n",
3171 pcap_strerror(errno));
3172 }
3173 }
3174 }
3175
3176 /*
3177 * If we're not using the kernel filter, get rid of any kernel
3178 * filter that might've been there before, e.g. because the
3179 * previous filter could work in the kernel, or because some other
3180 * code attached a filter to the socket by some means other than
3181 * calling "pcap_setfilter()". Otherwise, the kernel filter may
3182 * filter out packets that would pass the new userland filter.
3183 */
3184 if (handlep->filter_in_userland) {
3185 if (reset_kernel_filter(handle) == -1) {
3186 pcap_fmt_errmsg_for_errno(handle->errbuf,
3187 PCAP_ERRBUF_SIZE, errno,
3188 "can't remove kernel filter");
3189 err = -2; /* fatal error */
3190 }
3191 }
3192
3193 /*
3194 * Free up the copy of the filter that was made by "fix_program()".
3195 */
3196 if (fcode.filter != NULL)
3197 free(fcode.filter);
3198
3199 if (err == -2)
3200 /* Fatal error */
3201 return -1;
3202 #endif /* SO_ATTACH_FILTER */
3203
3204 return 0;
3205 }
3206
3207 static int
3208 pcap_setfilter_linux(pcap_t *handle, struct bpf_program *filter)
3209 {
3210 return pcap_setfilter_linux_common(handle, filter, 0);
3211 }
3212
3213
3214 /*
3215 * Set direction flag: Which packets do we accept on a forwarding
3216 * single device? IN, OUT or both?
3217 */
3218 static int
3219 pcap_setdirection_linux(pcap_t *handle, pcap_direction_t d)
3220 {
3221 #ifdef HAVE_PF_PACKET_SOCKETS
3222 struct pcap_linux *handlep = handle->priv;
3223
3224 if (!handlep->sock_packet) {
3225 handle->direction = d;
3226 return 0;
3227 }
3228 #endif
3229 /*
3230 * We're not using PF_PACKET sockets, so we can't determine
3231 * the direction of the packet.
3232 */
3233 snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
3234 "Setting direction is not supported on SOCK_PACKET sockets");
3235 return -1;
3236 }
3237
3238 static int
3239 is_wifi(int sock_fd
3240 #ifndef IW_MODE_MONITOR
3241 _U_
3242 #endif
3243 , const char *device)
3244 {
3245 char *pathstr;
3246 struct stat statb;
3247 #ifdef IW_MODE_MONITOR
3248 char errbuf[PCAP_ERRBUF_SIZE];
3249 #endif
3250
3251 /*
3252 * See if there's a sysfs wireless directory for it.
3253 * If so, it's a wireless interface.
3254 */
3255 if (asprintf(&pathstr, "/sys/class/net/%s/wireless", device) == -1) {
3256 /*
3257 * Just give up here.
3258 */
3259 return 0;
3260 }
3261 if (stat(pathstr, &statb) == 0) {
3262 free(pathstr);
3263 return 1;
3264 }
3265 free(pathstr);
3266
3267 #ifdef IW_MODE_MONITOR
3268 /*
3269 * OK, maybe it's not wireless, or maybe this kernel doesn't
3270 * support sysfs. Try the wireless extensions.
3271 */
3272 if (has_wext(sock_fd, device, errbuf) == 1) {
3273 /*
3274 * It supports the wireless extensions, so it's a Wi-Fi
3275 * device.
3276 */
3277 return 1;
3278 }
3279 #endif
3280 return 0;
3281 }
3282
3283 /*
3284 * Linux uses the ARP hardware type to identify the type of an
3285 * interface. pcap uses the DLT_xxx constants for this. This
3286 * function takes a pointer to a "pcap_t", and an ARPHRD_xxx
3287 * constant, as arguments, and sets "handle->linktype" to the
3288 * appropriate DLT_XXX constant and sets "handle->offset" to
3289 * the appropriate value (to make "handle->offset" plus link-layer
3290 * header length be a multiple of 4, so that the link-layer payload
3291 * will be aligned on a 4-byte boundary when capturing packets).
3292 * (If the offset isn't set here, it'll be 0; add code as appropriate
3293 * for cases where it shouldn't be 0.)
3294 *
3295 * If "cooked_ok" is non-zero, we can use DLT_LINUX_SLL and capture
3296 * in cooked mode; otherwise, we can't use cooked mode, so we have
3297 * to pick some type that works in raw mode, or fail.
3298 *
3299 * Sets the link type to -1 if unable to map the type.
3300 */
3301 static void map_arphrd_to_dlt(pcap_t *handle, int sock_fd, int arptype,
3302 const char *device, int cooked_ok)
3303 {
3304 static const char cdma_rmnet[] = "cdma_rmnet";
3305
3306 switch (arptype) {
3307
3308 case ARPHRD_ETHER:
3309 /*
3310 * For various annoying reasons having to do with DHCP
3311 * software, some versions of Android give the mobile-
3312 * phone-network interface an ARPHRD_ value of
3313 * ARPHRD_ETHER, even though the packets supplied by
3314 * that interface have no link-layer header, and begin
3315 * with an IP header, so that the ARPHRD_ value should
3316 * be ARPHRD_NONE.
3317 *
3318 * Detect those devices by checking the device name, and
3319 * use DLT_RAW for them.
3320 */
3321 if (strncmp(device, cdma_rmnet, sizeof cdma_rmnet - 1) == 0) {
3322 handle->linktype = DLT_RAW;
3323 return;
3324 }
3325
3326 /*
3327 * Is this a real Ethernet device? If so, give it a
3328 * link-layer-type list with DLT_EN10MB and DLT_DOCSIS, so
3329 * that an application can let you choose it, in case you're
3330 * capturing DOCSIS traffic that a Cisco Cable Modem
3331 * Termination System is putting out onto an Ethernet (it
3332 * doesn't put an Ethernet header onto the wire, it puts raw
3333 * DOCSIS frames out on the wire inside the low-level
3334 * Ethernet framing).
3335 *
3336 * XXX - are there any other sorts of "fake Ethernet" that
3337 * have ARPHRD_ETHER but that shouldn't offer DLT_DOCSIS as
3338 * a Cisco CMTS won't put traffic onto it or get traffic
3339 * bridged onto it? ISDN is handled in "activate_new()",
3340 * as we fall back on cooked mode there, and we use
3341 * is_wifi() to check for 802.11 devices; are there any
3342 * others?
3343 */
3344 if (!is_wifi(sock_fd, device)) {
3345 int ret;
3346
3347 /*
3348 * This is not a Wi-Fi device but it could be
3349 * a DSA master/management network device.
3350 */
3351 ret = iface_dsa_get_proto_info(device, handle);
3352 if (ret < 0)
3353 return;
3354
3355 if (ret == 1) {
3356 /*
3357 * This is a DSA master/management network
3358 * device linktype is already set by
3359 * iface_dsa_get_proto_info() set an
3360 * appropriate offset here.
3361 */
3362 handle->offset = 2;
3363 break;
3364 }
3365
3366 /*
3367 * It's not a Wi-Fi device; offer DOCSIS.
3368 */
3369 handle->dlt_list = (u_int *) malloc(sizeof(u_int) * 2);
3370 /*
3371 * If that fails, just leave the list empty.
3372 */
3373 if (handle->dlt_list != NULL) {
3374 handle->dlt_list[0] = DLT_EN10MB;
3375 handle->dlt_list[1] = DLT_DOCSIS;
3376 handle->dlt_count = 2;
3377 }
3378 }
3379 /* FALLTHROUGH */
3380
3381 case ARPHRD_METRICOM:
3382 case ARPHRD_LOOPBACK:
3383 handle->linktype = DLT_EN10MB;
3384 handle->offset = 2;
3385 break;
3386
3387 case ARPHRD_EETHER:
3388 handle->linktype = DLT_EN3MB;
3389 break;
3390
3391 case ARPHRD_AX25:
3392 handle->linktype = DLT_AX25_KISS;
3393 break;
3394
3395 case ARPHRD_PRONET:
3396 handle->linktype = DLT_PRONET;
3397 break;
3398
3399 case ARPHRD_CHAOS:
3400 handle->linktype = DLT_CHAOS;
3401 break;
3402 #ifndef ARPHRD_CAN
3403 #define ARPHRD_CAN 280
3404 #endif
3405 case ARPHRD_CAN:
3406 /*
3407 * Map this to DLT_LINUX_SLL; that way, CAN frames will
3408 * have ETH_P_CAN/LINUX_SLL_P_CAN as the protocol and
3409 * CAN FD frames will have ETH_P_CANFD/LINUX_SLL_P_CANFD
3410 * as the protocol, so they can be distinguished by the
3411 * protocol in the SLL header.
3412 */
3413 handle->linktype = DLT_LINUX_SLL;
3414 break;
3415
3416 #ifndef ARPHRD_IEEE802_TR
3417 #define ARPHRD_IEEE802_TR 800 /* From Linux 2.4 */
3418 #endif
3419 case ARPHRD_IEEE802_TR:
3420 case ARPHRD_IEEE802:
3421 handle->linktype = DLT_IEEE802;
3422 handle->offset = 2;
3423 break;
3424
3425 case ARPHRD_ARCNET:
3426 handle->linktype = DLT_ARCNET_LINUX;
3427 break;
3428
3429 #ifndef ARPHRD_FDDI /* From Linux 2.2.13 */
3430 #define ARPHRD_FDDI 774
3431 #endif
3432 case ARPHRD_FDDI:
3433 handle->linktype = DLT_FDDI;
3434 handle->offset = 3;
3435 break;
3436
3437 #ifndef ARPHRD_ATM /* FIXME: How to #include this? */
3438 #define ARPHRD_ATM 19
3439 #endif
3440 case ARPHRD_ATM:
3441 /*
3442 * The Classical IP implementation in ATM for Linux
3443 * supports both what RFC 1483 calls "LLC Encapsulation",
3444 * in which each packet has an LLC header, possibly
3445 * with a SNAP header as well, prepended to it, and
3446 * what RFC 1483 calls "VC Based Multiplexing", in which
3447 * different virtual circuits carry different network
3448 * layer protocols, and no header is prepended to packets.
3449 *
3450 * They both have an ARPHRD_ type of ARPHRD_ATM, so
3451 * you can't use the ARPHRD_ type to find out whether
3452 * captured packets will have an LLC header, and,
3453 * while there's a socket ioctl to *set* the encapsulation
3454 * type, there's no ioctl to *get* the encapsulation type.
3455 *
3456 * This means that
3457 *
3458 * programs that dissect Linux Classical IP frames
3459 * would have to check for an LLC header and,
3460 * depending on whether they see one or not, dissect
3461 * the frame as LLC-encapsulated or as raw IP (I
3462 * don't know whether there's any traffic other than
3463 * IP that would show up on the socket, or whether
3464 * there's any support for IPv6 in the Linux
3465 * Classical IP code);
3466 *
3467 * filter expressions would have to compile into
3468 * code that checks for an LLC header and does
3469 * the right thing.
3470 *
3471 * Both of those are a nuisance - and, at least on systems
3472 * that support PF_PACKET sockets, we don't have to put
3473 * up with those nuisances; instead, we can just capture
3474 * in cooked mode. That's what we'll do, if we can.
3475 * Otherwise, we'll just fail.
3476 */
3477 if (cooked_ok)
3478 handle->linktype = DLT_LINUX_SLL;
3479 else
3480 handle->linktype = -1;
3481 break;
3482
3483 #ifndef ARPHRD_IEEE80211 /* From Linux 2.4.6 */
3484 #define ARPHRD_IEEE80211 801
3485 #endif
3486 case ARPHRD_IEEE80211:
3487 handle->linktype = DLT_IEEE802_11;
3488 break;
3489
3490 #ifndef ARPHRD_IEEE80211_PRISM /* From Linux 2.4.18 */
3491 #define ARPHRD_IEEE80211_PRISM 802
3492 #endif
3493 case ARPHRD_IEEE80211_PRISM:
3494 handle->linktype = DLT_PRISM_HEADER;
3495 break;
3496
3497 #ifndef ARPHRD_IEEE80211_RADIOTAP /* new */
3498 #define ARPHRD_IEEE80211_RADIOTAP 803
3499 #endif
3500 case ARPHRD_IEEE80211_RADIOTAP:
3501 handle->linktype = DLT_IEEE802_11_RADIO;
3502 break;
3503
3504 case ARPHRD_PPP:
3505 /*
3506 * Some PPP code in the kernel supplies no link-layer
3507 * header whatsoever to PF_PACKET sockets; other PPP
3508 * code supplies PPP link-layer headers ("syncppp.c");
3509 * some PPP code might supply random link-layer
3510 * headers (PPP over ISDN - there's code in Ethereal,
3511 * for example, to cope with PPP-over-ISDN captures
3512 * with which the Ethereal developers have had to cope,
3513 * heuristically trying to determine which of the
3514 * oddball link-layer headers particular packets have).
3515 *
3516 * As such, we just punt, and run all PPP interfaces
3517 * in cooked mode, if we can; otherwise, we just treat
3518 * it as DLT_RAW, for now - if somebody needs to capture,
3519 * on a 2.0[.x] kernel, on PPP devices that supply a
3520 * link-layer header, they'll have to add code here to
3521 * map to the appropriate DLT_ type (possibly adding a
3522 * new DLT_ type, if necessary).
3523 */
3524 if (cooked_ok)
3525 handle->linktype = DLT_LINUX_SLL;
3526 else {
3527 /*
3528 * XXX - handle ISDN types here? We can't fall
3529 * back on cooked sockets, so we'd have to
3530 * figure out from the device name what type of
3531 * link-layer encapsulation it's using, and map
3532 * that to an appropriate DLT_ value, meaning
3533 * we'd map "isdnN" devices to DLT_RAW (they
3534 * supply raw IP packets with no link-layer
3535 * header) and "isdY" devices to a new DLT_I4L_IP
3536 * type that has only an Ethernet packet type as
3537 * a link-layer header.
3538 *
3539 * But sometimes we seem to get random crap
3540 * in the link-layer header when capturing on
3541 * ISDN devices....
3542 */
3543 handle->linktype = DLT_RAW;
3544 }
3545 break;
3546
3547 #ifndef ARPHRD_CISCO
3548 #define ARPHRD_CISCO 513 /* previously ARPHRD_HDLC */
3549 #endif
3550 case ARPHRD_CISCO:
3551 handle->linktype = DLT_C_HDLC;
3552 break;
3553
3554 /* Not sure if this is correct for all tunnels, but it
3555 * works for CIPE */
3556 case ARPHRD_TUNNEL:
3557 #ifndef ARPHRD_SIT
3558 #define ARPHRD_SIT 776 /* From Linux 2.2.13 */
3559 #endif
3560 case ARPHRD_SIT:
3561 case ARPHRD_CSLIP:
3562 case ARPHRD_SLIP6:
3563 case ARPHRD_CSLIP6:
3564 case ARPHRD_ADAPT:
3565 case ARPHRD_SLIP:
3566 #ifndef ARPHRD_RAWHDLC
3567 #define ARPHRD_RAWHDLC 518
3568 #endif
3569 case ARPHRD_RAWHDLC:
3570 #ifndef ARPHRD_DLCI
3571 #define ARPHRD_DLCI 15
3572 #endif
3573 case ARPHRD_DLCI:
3574 /*
3575 * XXX - should some of those be mapped to DLT_LINUX_SLL
3576 * instead? Should we just map all of them to DLT_LINUX_SLL?
3577 */
3578 handle->linktype = DLT_RAW;
3579 break;
3580
3581 #ifndef ARPHRD_FRAD
3582 #define ARPHRD_FRAD 770
3583 #endif
3584 case ARPHRD_FRAD:
3585 handle->linktype = DLT_FRELAY;
3586 break;
3587
3588 case ARPHRD_LOCALTLK:
3589 handle->linktype = DLT_LTALK;
3590 break;
3591
3592 case 18:
3593 /*
3594 * RFC 4338 defines an encapsulation for IP and ARP
3595 * packets that's compatible with the RFC 2625
3596 * encapsulation, but that uses a different ARP
3597 * hardware type and hardware addresses. That
3598 * ARP hardware type is 18; Linux doesn't define
3599 * any ARPHRD_ value as 18, but if it ever officially
3600 * supports RFC 4338-style IP-over-FC, it should define
3601 * one.
3602 *
3603 * For now, we map it to DLT_IP_OVER_FC, in the hopes
3604 * that this will encourage its use in the future,
3605 * should Linux ever officially support RFC 4338-style
3606 * IP-over-FC.
3607 */
3608 handle->linktype = DLT_IP_OVER_FC;
3609 break;
3610
3611 #ifndef ARPHRD_FCPP
3612 #define ARPHRD_FCPP 784
3613 #endif
3614 case ARPHRD_FCPP:
3615 #ifndef ARPHRD_FCAL
3616 #define ARPHRD_FCAL 785
3617 #endif
3618 case ARPHRD_FCAL:
3619 #ifndef ARPHRD_FCPL
3620 #define ARPHRD_FCPL 786
3621 #endif
3622 case ARPHRD_FCPL:
3623 #ifndef ARPHRD_FCFABRIC
3624 #define ARPHRD_FCFABRIC 787
3625 #endif
3626 case ARPHRD_FCFABRIC:
3627 /*
3628 * Back in 2002, Donald Lee at Cray wanted a DLT_ for
3629 * IP-over-FC:
3630 *
3631 * http://www.mail-archive.com/tcpdump-workers@sandelman.ottawa.on.ca/msg01043.html
3632 *
3633 * and one was assigned.
3634 *
3635 * In a later private discussion (spun off from a message
3636 * on the ethereal-users list) on how to get that DLT_
3637 * value in libpcap on Linux, I ended up deciding that
3638 * the best thing to do would be to have him tweak the
3639 * driver to set the ARPHRD_ value to some ARPHRD_FCxx
3640 * type, and map all those types to DLT_IP_OVER_FC:
3641 *
3642 * I've checked into the libpcap and tcpdump CVS tree
3643 * support for DLT_IP_OVER_FC. In order to use that,
3644 * you'd have to modify your modified driver to return
3645 * one of the ARPHRD_FCxxx types, in "fcLINUXfcp.c" -
3646 * change it to set "dev->type" to ARPHRD_FCFABRIC, for
3647 * example (the exact value doesn't matter, it can be
3648 * any of ARPHRD_FCPP, ARPHRD_FCAL, ARPHRD_FCPL, or
3649 * ARPHRD_FCFABRIC).
3650 *
3651 * 11 years later, Christian Svensson wanted to map
3652 * various ARPHRD_ values to DLT_FC_2 and
3653 * DLT_FC_2_WITH_FRAME_DELIMS for raw Fibre Channel
3654 * frames:
3655 *
3656 * https://github.com/mcr/libpcap/pull/29
3657 *
3658 * There doesn't seem to be any network drivers that uses
3659 * any of the ARPHRD_FC* values for IP-over-FC, and
3660 * it's not exactly clear what the "Dummy types for non
3661 * ARP hardware" are supposed to mean (link-layer
3662 * header type? Physical network type?), so it's
3663 * not exactly clear why the ARPHRD_FC* types exist
3664 * in the first place.
3665 *
3666 * For now, we map them to DLT_FC_2, and provide an
3667 * option of DLT_FC_2_WITH_FRAME_DELIMS, as well as
3668 * DLT_IP_OVER_FC just in case there's some old
3669 * driver out there that uses one of those types for
3670 * IP-over-FC on which somebody wants to capture
3671 * packets.
3672 */
3673 handle->dlt_list = (u_int *) malloc(sizeof(u_int) * 3);
3674 /*
3675 * If that fails, just leave the list empty.
3676 */
3677 if (handle->dlt_list != NULL) {
3678 handle->dlt_list[0] = DLT_FC_2;
3679 handle->dlt_list[1] = DLT_FC_2_WITH_FRAME_DELIMS;
3680 handle->dlt_list[2] = DLT_IP_OVER_FC;
3681 handle->dlt_count = 3;
3682 }
3683 handle->linktype = DLT_FC_2;
3684 break;
3685
3686 #ifndef ARPHRD_IRDA
3687 #define ARPHRD_IRDA 783
3688 #endif
3689 case ARPHRD_IRDA:
3690 /* Don't expect IP packet out of this interfaces... */
3691 handle->linktype = DLT_LINUX_IRDA;
3692 /* We need to save packet direction for IrDA decoding,
3693 * so let's use "Linux-cooked" mode. Jean II
3694 *
3695 * XXX - this is handled in activate_new(). */
3696 /* handlep->cooked = 1; */
3697 break;
3698
3699 /* ARPHRD_LAPD is unofficial and randomly allocated, if reallocation
3700 * is needed, please report it to <daniele@orlandi.com> */
3701 #ifndef ARPHRD_LAPD
3702 #define ARPHRD_LAPD 8445
3703 #endif
3704 case ARPHRD_LAPD:
3705 /* Don't expect IP packet out of this interfaces... */
3706 handle->linktype = DLT_LINUX_LAPD;
3707 break;
3708
3709 #ifndef ARPHRD_NONE
3710 #define ARPHRD_NONE 0xFFFE
3711 #endif
3712 case ARPHRD_NONE:
3713 /*
3714 * No link-layer header; packets are just IP
3715 * packets, so use DLT_RAW.
3716 */
3717 handle->linktype = DLT_RAW;
3718 break;
3719
3720 #ifndef ARPHRD_IEEE802154
3721 #define ARPHRD_IEEE802154 804
3722 #endif
3723 case ARPHRD_IEEE802154:
3724 handle->linktype = DLT_IEEE802_15_4_NOFCS;
3725 break;
3726
3727 #ifndef ARPHRD_NETLINK
3728 #define ARPHRD_NETLINK 824
3729 #endif
3730 case ARPHRD_NETLINK:
3731 handle->linktype = DLT_NETLINK;
3732 /*
3733 * We need to use cooked mode, so that in sll_protocol we
3734 * pick up the netlink protocol type such as NETLINK_ROUTE,
3735 * NETLINK_GENERIC, NETLINK_FIB_LOOKUP, etc.
3736 *
3737 * XXX - this is handled in activate_new().
3738 */
3739 /* handlep->cooked = 1; */
3740 break;
3741
3742 #ifndef ARPHRD_VSOCKMON
3743 #define ARPHRD_VSOCKMON 826
3744 #endif
3745 case ARPHRD_VSOCKMON:
3746 handle->linktype = DLT_VSOCK;
3747 break;
3748
3749 default:
3750 handle->linktype = -1;
3751 break;
3752 }
3753 }
3754
3755 #ifdef HAVE_PF_PACKET_SOCKETS
3756 /* ===== Functions to interface to the newer kernels ================== */
3757
3758 #ifdef PACKET_RESERVE
3759 static void
3760 set_dlt_list_cooked(pcap_t *handle, int sock_fd)
3761 {
3762 socklen_t len;
3763 unsigned int tp_reserve;
3764
3765 /*
3766 * If we can't do PACKET_RESERVE, we can't reserve extra space
3767 * for a DLL_LINUX_SLL2 header, so we can't support DLT_LINUX_SLL2.
3768 */
3769 len = sizeof(tp_reserve);
3770 if (getsockopt(sock_fd, SOL_PACKET, PACKET_RESERVE, &tp_reserve,
3771 &len) == 0) {
3772 /*
3773 * Yes, we can do DLL_LINUX_SLL2.
3774 */
3775 handle->dlt_list = (u_int *) malloc(sizeof(u_int) * 2);
3776 /*
3777 * If that fails, just leave the list empty.
3778 */
3779 if (handle->dlt_list != NULL) {
3780 handle->dlt_list[0] = DLT_LINUX_SLL;
3781 handle->dlt_list[1] = DLT_LINUX_SLL2;
3782 handle->dlt_count = 2;
3783 }
3784 }
3785 }
3786 #else/* PACKET_RESERVE */
3787 /*
3788 * The build environment doesn't define PACKET_RESERVE, so we can't reserve
3789 * extra space for a DLL_LINUX_SLL2 header, so we can't support DLT_LINUX_SLL2.
3790 */
3791 static void
3792 set_dlt_list_cooked(pcap_t *handle _U_, int sock_fd _U_)
3793 {
3794 }
3795 #endif /* PACKET_RESERVE */
3796
3797 /*
3798 * Try to set up a PF_PACKET socket.
3799 * Returns 0 on success and a PCAP_ERROR_ value on failure.
3800 */
3801 static int
3802 activate_new(pcap_t *handle, int is_any_device)
3803 {
3804 struct pcap_linux *handlep = handle->priv;
3805 const char *device = handle->opt.device;
3806 int status = 0;
3807 int sock_fd, arptype;
3808 #ifdef HAVE_PACKET_AUXDATA
3809 int val;
3810 #endif
3811 int err = 0;
3812 struct packet_mreq mr;
3813 #if defined(SO_BPF_EXTENSIONS) && defined(SKF_AD_VLAN_TAG_PRESENT)
3814 int bpf_extensions;
3815 socklen_t len = sizeof(bpf_extensions);
3816 #endif
3817
3818 sock_fd = open_pf_packet_socket(handle, is_any_device);
3819 if (sock_fd < 0) {
3820 /*
3821 * Failed; return its return value.
3822 */
3823 return sock_fd;
3824 }
3825
3826 /* It seems the kernel supports the new interface. */
3827 handlep->sock_packet = 0;
3828
3829 /*
3830 * Get the interface index of the loopback device.
3831 * If the attempt fails, don't fail, just set the
3832 * "handlep->lo_ifindex" to -1.
3833 *
3834 * XXX - can there be more than one device that loops
3835 * packets back, i.e. devices other than "lo"? If so,
3836 * we'd need to find them all, and have an array of
3837 * indices for them, and check all of them in
3838 * "pcap_read_packet()".
3839 */
3840 handlep->lo_ifindex = iface_get_id(sock_fd, "lo", handle->errbuf);
3841
3842 /*
3843 * Default value for offset to align link-layer payload
3844 * on a 4-byte boundary.
3845 */
3846 handle->offset = 0;
3847
3848 /*
3849 * What kind of frames do we have to deal with? Fall back
3850 * to cooked mode if we have an unknown interface type
3851 * or a type we know doesn't work well in raw mode.
3852 */
3853 if (!is_any_device) {
3854 /* Assume for now we don't need cooked mode. */
3855 handlep->cooked = 0;
3856
3857 if (handle->opt.rfmon) {
3858 /*
3859 * We were asked to turn on monitor mode.
3860 * Do so before we get the link-layer type,
3861 * because entering monitor mode could change
3862 * the link-layer type.
3863 */
3864 err = enter_rfmon_mode(handle, sock_fd, device);
3865 if (err < 0) {
3866 /* Hard failure */
3867 close(sock_fd);
3868 return err;
3869 }
3870 if (err == 0) {
3871 /*
3872 * Nothing worked for turning monitor mode
3873 * on.
3874 */
3875 close(sock_fd);
3876 return PCAP_ERROR_RFMON_NOTSUP;
3877 }
3878
3879 /*
3880 * Either monitor mode has been turned on for
3881 * the device, or we've been given a different
3882 * device to open for monitor mode. If we've
3883 * been given a different device, use it.
3884 */
3885 if (handlep->mondevice != NULL)
3886 device = handlep->mondevice;
3887 }
3888 arptype = iface_get_arptype(sock_fd, device, handle->errbuf);
3889 if (arptype < 0) {
3890 close(sock_fd);
3891 return arptype;
3892 }
3893 map_arphrd_to_dlt(handle, sock_fd, arptype, device, 1);
3894 if (handle->linktype == -1 ||
3895 handle->linktype == DLT_LINUX_SLL ||
3896 handle->linktype == DLT_LINUX_IRDA ||
3897 handle->linktype == DLT_LINUX_LAPD ||
3898 handle->linktype == DLT_NETLINK ||
3899 (handle->linktype == DLT_EN10MB &&
3900 (strncmp("isdn", device, 4) == 0 ||
3901 strncmp("isdY", device, 4) == 0))) {
3902 /*
3903 * Unknown interface type (-1), or a
3904 * device we explicitly chose to run
3905 * in cooked mode (e.g., PPP devices),
3906 * or an ISDN device (whose link-layer
3907 * type we can only determine by using
3908 * APIs that may be different on different
3909 * kernels) - reopen in cooked mode.
3910 *
3911 * If the type is unknown, return a warning;
3912 * map_arphrd_to_dlt() has already set the
3913 * warning message.
3914 */
3915 if (close(sock_fd) == -1) {
3916 pcap_fmt_errmsg_for_errno(handle->errbuf,
3917 PCAP_ERRBUF_SIZE, errno, "close");
3918 return PCAP_ERROR;
3919 }
3920 sock_fd = open_pf_packet_socket(handle, 1);
3921 if (sock_fd < 0) {
3922 if (sock_fd == PCAP_ERROR_NO_PF_PACKET_SOCKETS) {
3923 /*
3924 * We don't support PF_PACKET/SOCK_whatever
3925 * sockets. This should never happen,
3926 * because we don't support cooked mode
3927 * without those sockets, so we
3928 * shouldn't get called if we're
3929 * running on a kernel old enough
3930 * not to support them.
3931 *
3932 * The error message has already been
3933 * filled in appropriately.
3934 */
3935 sock_fd = PCAP_ERROR;
3936 }
3937 /*
3938 * Fatal error; the return value is the
3939 * error code, and handle->errbuf has
3940 * been set to an appropriate error
3941 * message.
3942 */
3943 return sock_fd;
3944 }
3945 handlep->cooked = 1;
3946
3947 /*
3948 * Get rid of any link-layer type list
3949 * we allocated - this only supports cooked
3950 * capture.
3951 */
3952 if (handle->dlt_list != NULL) {
3953 free(handle->dlt_list);
3954 handle->dlt_list = NULL;
3955 handle->dlt_count = 0;
3956 set_dlt_list_cooked(handle, sock_fd);
3957 }
3958
3959 if (handle->linktype == -1) {
3960 /*
3961 * Warn that we're falling back on
3962 * cooked mode; we may want to
3963 * update "map_arphrd_to_dlt()"
3964 * to handle the new type.
3965 */
3966 snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
3967 "arptype %d not "
3968 "supported by libpcap - "
3969 "falling back to cooked "
3970 "socket",
3971 arptype);
3972 }
3973
3974 /*
3975 * IrDA capture is not a real "cooked" capture,
3976 * it's IrLAP frames, not IP packets. The
3977 * same applies to LAPD capture.
3978 */
3979 if (handle->linktype != DLT_LINUX_IRDA &&
3980 handle->linktype != DLT_LINUX_LAPD &&
3981 handle->linktype != DLT_NETLINK)
3982 handle->linktype = DLT_LINUX_SLL;
3983 if (handle->linktype == -1) {
3984 snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
3985 "unknown arptype %d, defaulting to cooked mode",
3986 arptype);
3987 status = PCAP_WARNING;
3988 }
3989 }
3990
3991 handlep->ifindex = iface_get_id(sock_fd, device,
3992 handle->errbuf);
3993 if (handlep->ifindex == -1) {
3994 close(sock_fd);
3995 return PCAP_ERROR;
3996 }
3997
3998 if ((err = iface_bind(sock_fd, handlep->ifindex,
3999 handle->errbuf, pcap_protocol(handle))) != 0) {
4000 close(sock_fd);
4001 return err;
4002 }
4003 } else {
4004 /*
4005 * The "any" device.
4006 */
4007 if (handle->opt.rfmon) {
4008 /*
4009 * It doesn't support monitor mode.
4010 */
4011 close(sock_fd);
4012 return PCAP_ERROR_RFMON_NOTSUP;
4013 }
4014
4015 /*
4016 * It uses cooked mode.
4017 */
4018 handlep->cooked = 1;
4019 handle->linktype = DLT_LINUX_SLL;
4020 handle->dlt_list = NULL;
4021 handle->dlt_count = 0;
4022 set_dlt_list_cooked(handle, sock_fd);
4023
4024 /*
4025 * We're not bound to a device.
4026 * For now, we're using this as an indication
4027 * that we can't transmit; stop doing that only
4028 * if we figure out how to transmit in cooked
4029 * mode.
4030 */
4031 handlep->ifindex = -1;
4032 }
4033
4034 /*
4035 * Select promiscuous mode on if "promisc" is set.
4036 *
4037 * Do not turn allmulti mode on if we don't select
4038 * promiscuous mode - on some devices (e.g., Orinoco
4039 * wireless interfaces), allmulti mode isn't supported
4040 * and the driver implements it by turning promiscuous
4041 * mode on, and that screws up the operation of the
4042 * card as a normal networking interface, and on no
4043 * other platform I know of does starting a non-
4044 * promiscuous capture affect which multicast packets
4045 * are received by the interface.
4046 */
4047
4048 /*
4049 * Hmm, how can we set promiscuous mode on all interfaces?
4050 * I am not sure if that is possible at all. For now, we
4051 * silently ignore attempts to turn promiscuous mode on
4052 * for the "any" device (so you don't have to explicitly
4053 * disable it in programs such as tcpdump).
4054 */
4055
4056 if (!is_any_device && handle->opt.promisc) {
4057 memset(&mr, 0, sizeof(mr));
4058 mr.mr_ifindex = handlep->ifindex;
4059 mr.mr_type = PACKET_MR_PROMISC;
4060 if (setsockopt(sock_fd, SOL_PACKET, PACKET_ADD_MEMBERSHIP,
4061 &mr, sizeof(mr)) == -1) {
4062 pcap_fmt_errmsg_for_errno(handle->errbuf,
4063 PCAP_ERRBUF_SIZE, errno, "setsockopt (PACKET_ADD_MEMBERSHIP)");
4064 close(sock_fd);
4065 return PCAP_ERROR;
4066 }
4067 }
4068
4069 /* Enable auxillary data if supported and reserve room for
4070 * reconstructing VLAN headers. */
4071 #ifdef HAVE_PACKET_AUXDATA
4072 val = 1;
4073 if (setsockopt(sock_fd, SOL_PACKET, PACKET_AUXDATA, &val,
4074 sizeof(val)) == -1 && errno != ENOPROTOOPT) {
4075 pcap_fmt_errmsg_for_errno(handle->errbuf, PCAP_ERRBUF_SIZE,
4076 errno, "setsockopt (PACKET_AUXDATA)");
4077 close(sock_fd);
4078 return PCAP_ERROR;
4079 }
4080 handle->offset += VLAN_TAG_LEN;
4081 #endif /* HAVE_PACKET_AUXDATA */
4082
4083 /*
4084 * This is a 2.2[.x] or later kernel (we know that
4085 * because we're not using a SOCK_PACKET socket -
4086 * PF_PACKET is supported only in 2.2 and later
4087 * kernels).
4088 *
4089 * We can safely pass "recvfrom()" a byte count
4090 * based on the snapshot length.
4091 *
4092 * If we're in cooked mode, make the snapshot length
4093 * large enough to hold a "cooked mode" header plus
4094 * 1 byte of packet data (so we don't pass a byte
4095 * count of 0 to "recvfrom()").
4096 * XXX - we don't know whether this will be DLT_LINUX_SLL
4097 * or DLT_LINUX_SLL2, so make sure it's big enough for
4098 * a DLT_LINUX_SLL2 "cooked mode" header; a snapshot length
4099 * that small is silly anyway.
4100 */
4101 if (handlep->cooked) {
4102 if (handle->snapshot < SLL2_HDR_LEN + 1)
4103 handle->snapshot = SLL2_HDR_LEN + 1;
4104 }
4105 handle->bufsize = handle->snapshot;
4106
4107 /*
4108 * Set the offset at which to insert VLAN tags.
4109 * That should be the offset of the type field.
4110 */
4111 switch (handle->linktype) {
4112
4113 case DLT_EN10MB:
4114 /*
4115 * The type field is after the destination and source
4116 * MAC address.
4117 */
4118 handlep->vlan_offset = 2 * ETH_ALEN;
4119 break;
4120
4121 case DLT_LINUX_SLL:
4122 /*
4123 * The type field is in the last 2 bytes of the
4124 * DLT_LINUX_SLL header.
4125 */
4126 handlep->vlan_offset = SLL_HDR_LEN - 2;
4127 break;
4128
4129 default:
4130 handlep->vlan_offset = -1; /* unknown */
4131 break;
4132 }
4133
4134 #if defined(SIOCGSTAMPNS) && defined(SO_TIMESTAMPNS)
4135 if (handle->opt.tstamp_precision == PCAP_TSTAMP_PRECISION_NANO) {
4136 int nsec_tstamps = 1;
4137
4138 if (setsockopt(sock_fd, SOL_SOCKET, SO_TIMESTAMPNS, &nsec_tstamps, sizeof(nsec_tstamps)) < 0) {
4139 snprintf(handle->errbuf, PCAP_ERRBUF_SIZE, "setsockopt: unable to set SO_TIMESTAMPNS");
4140 close(sock_fd);
4141 return PCAP_ERROR;
4142 }
4143 }
4144 #endif /* defined(SIOCGSTAMPNS) && defined(SO_TIMESTAMPNS) */
4145
4146 /*
4147 * We've succeeded. Save the socket FD in the pcap structure.
4148 */
4149 handle->fd = sock_fd;
4150
4151 #if defined(SO_BPF_EXTENSIONS) && defined(SKF_AD_VLAN_TAG_PRESENT)
4152 /*
4153 * Can we generate special code for VLAN checks?
4154 * (XXX - what if we need the special code but it's not supported
4155 * by the OS? Is that possible?)
4156 */
4157 if (getsockopt(sock_fd, SOL_SOCKET, SO_BPF_EXTENSIONS,
4158 &bpf_extensions, &len) == 0) {
4159 if (bpf_extensions >= SKF_AD_VLAN_TAG_PRESENT) {
4160 /*
4161 * Yes, we can. Request that we do so.
4162 */
4163 handle->bpf_codegen_flags |= BPF_SPECIAL_VLAN_HANDLING;
4164 }
4165 }
4166 #endif /* defined(SO_BPF_EXTENSIONS) && defined(SKF_AD_VLAN_TAG_PRESENT) */
4167
4168 return status;
4169 }
4170
4171 #ifdef HAVE_PACKET_RING
4172 /*
4173 * Attempt to activate with memory-mapped access.
4174 *
4175 * On success, returns 1, and sets *status to 0 if there are no warnings
4176 * or to a PCAP_WARNING_ code if there is a warning.
4177 *
4178 * On failure due to lack of support for memory-mapped capture, returns
4179 * 0.
4180 *
4181 * On error, returns -1, and sets *status to the appropriate error code;
4182 * if that is PCAP_ERROR, sets handle->errbuf to the appropriate message.
4183 */
4184 static int
4185 activate_mmap(pcap_t *handle, int *status)
4186 {
4187 struct pcap_linux *handlep = handle->priv;
4188 int ret;
4189
4190 /*
4191 * Attempt to allocate a buffer to hold the contents of one
4192 * packet, for use by the oneshot callback.
4193 */
4194 handlep->oneshot_buffer = malloc(handle->snapshot);
4195 if (handlep->oneshot_buffer == NULL) {
4196 pcap_fmt_errmsg_for_errno(handle->errbuf, PCAP_ERRBUF_SIZE,
4197 errno, "can't allocate oneshot buffer");
4198 *status = PCAP_ERROR;
4199 return -1;
4200 }
4201
4202 if (handle->opt.buffer_size == 0) {
4203 /* by default request 2M for the ring buffer */
4204 handle->opt.buffer_size = 2*1024*1024;
4205 }
4206 ret = prepare_tpacket_socket(handle);
4207 if (ret == -1) {
4208 free(handlep->oneshot_buffer);
4209 *status = PCAP_ERROR;
4210 return ret;
4211 }
4212 ret = create_ring(handle, status);
4213 if (ret == 0) {
4214 /*
4215 * We don't support memory-mapped capture; our caller
4216 * will fall back on reading from the socket.
4217 */
4218 free(handlep->oneshot_buffer);
4219 return 0;
4220 }
4221 if (ret == -1) {
4222 /*
4223 * Error attempting to enable memory-mapped capture;
4224 * fail. create_ring() has set *status.
4225 */
4226 free(handlep->oneshot_buffer);
4227 return -1;
4228 }
4229
4230 /*
4231 * Success. *status has been set either to 0 if there are no
4232 * warnings or to a PCAP_WARNING_ value if there is a warning.
4233 *
4234 * Override some defaults and inherit the other fields from
4235 * activate_new.
4236 * handle->offset is used to get the current position into the rx ring.
4237 * handle->cc is used to store the ring size.
4238 */
4239
4240 switch (handlep->tp_version) {
4241 case TPACKET_V1:
4242 handle->read_op = pcap_read_linux_mmap_v1;
4243 break;
4244 case TPACKET_V1_64:
4245 handle->read_op = pcap_read_linux_mmap_v1_64;
4246 break;
4247 #ifdef HAVE_TPACKET2
4248 case TPACKET_V2:
4249 handle->read_op = pcap_read_linux_mmap_v2;
4250 break;
4251 #endif
4252 #ifdef HAVE_TPACKET3
4253 case TPACKET_V3:
4254 handle->read_op = pcap_read_linux_mmap_v3;
4255 break;
4256 #endif
4257 }
4258 handle->cleanup_op = pcap_cleanup_linux_mmap;
4259 handle->setfilter_op = pcap_setfilter_linux_mmap;
4260 handle->setnonblock_op = pcap_setnonblock_mmap;
4261 handle->getnonblock_op = pcap_getnonblock_mmap;
4262 handle->oneshot_callback = pcap_oneshot_mmap;
4263 handle->selectable_fd = handle->fd;
4264 return 1;
4265 }
4266
4267 #if defined(HAVE_TPACKET2) || defined(HAVE_TPACKET3)
4268 /*
4269 * Attempt to set the socket to the specified version of the memory-mapped
4270 * header.
4271 *
4272 * Return 0 if we succeed; return 1 if we fail because that version isn't
4273 * supported; return -1 on any other error, and set handle->errbuf.
4274 */
4275 static int
4276 init_tpacket(pcap_t *handle, int version, const char *version_str)
4277 {
4278 struct pcap_linux *handlep = handle->priv;
4279 int val = version;
4280 socklen_t len = sizeof(val);
4281
4282 /*
4283 * Probe whether kernel supports the specified TPACKET version;
4284 * this also gets the length of the header for that version.
4285 *
4286 * This socket option was introduced in 2.6.27, which was
4287 * also the first release with TPACKET_V2 support.
4288 */
4289 if (getsockopt(handle->fd, SOL_PACKET, PACKET_HDRLEN, &val, &len) < 0) {
4290 if (errno == ENOPROTOOPT || errno == EINVAL) {
4291 /*
4292 * ENOPROTOOPT means the kernel is too old to
4293 * support PACKET_HDRLEN at all, which means
4294 * it either doesn't support TPACKET at all
4295 * or supports only TPACKET_V1.
4296 */
4297 return 1; /* no */
4298 }
4299
4300 /* Failed to even find out; this is a fatal error. */
4301 pcap_fmt_errmsg_for_errno(handle->errbuf, PCAP_ERRBUF_SIZE,
4302 errno, "can't get %s header len on packet socket",
4303 version_str);
4304 return -1;
4305 }
4306 handlep->tp_hdrlen = val;
4307
4308 val = version;
4309 if (setsockopt(handle->fd, SOL_PACKET, PACKET_VERSION, &val,
4310 sizeof(val)) < 0) {
4311 pcap_fmt_errmsg_for_errno(handle->errbuf, PCAP_ERRBUF_SIZE,
4312 errno, "can't activate %s on packet socket", version_str);
4313 return -1;
4314 }
4315 handlep->tp_version = version;
4316
4317 return 0;
4318 }
4319 #endif /* defined HAVE_TPACKET2 || defined HAVE_TPACKET3 */
4320
4321 /*
4322 * If the instruction set for which we're compiling has both 32-bit
4323 * and 64-bit versions, and Linux support for the 64-bit version
4324 * predates TPACKET_V2, define ISA_64_BIT as the .machine value
4325 * you get from uname() for the 64-bit version. Otherwise, leave
4326 * it undefined. (This includes ARM, which has a 64-bit version,
4327 * but Linux support for it appeared well after TPACKET_V2 support
4328 * did, so there should never be a case where 32-bit ARM code is
4329 * running o a 64-bit kernel that only supports TPACKET_V1.)
4330 *
4331 * If we've omitted your favorite such architecture, please contribute
4332 * a patch. (No patch is needed for architectures that are 32-bit-only
4333 * or for which Linux has no support for 32-bit userland - or for which,
4334 * as noted, 64-bit support appeared in Linux after TPACKET_V2 support
4335 * did.)
4336 */
4337 #if defined(__i386__)
4338 #define ISA_64_BIT "x86_64"
4339 #elif defined(__ppc__)
4340 #define ISA_64_BIT "ppc64"
4341 #elif defined(__sparc__)
4342 #define ISA_64_BIT "sparc64"
4343 #elif defined(__s390__)
4344 #define ISA_64_BIT "s390x"
4345 #elif defined(__mips__)
4346 #define ISA_64_BIT "mips64"
4347 #elif defined(__hppa__)
4348 #define ISA_64_BIT "parisc64"
4349 #endif
4350
4351 /*
4352 * Attempt to set the socket to version 3 of the memory-mapped header and,
4353 * if that fails because version 3 isn't supported, attempt to fall
4354 * back to version 2. If version 2 isn't supported, just leave it at
4355 * version 1.
4356 *
4357 * Return 1 if we succeed or if we fail because neither version 2 nor 3 is
4358 * supported; return -1 on any other error, and set handle->errbuf.
4359 */
4360 static int
4361 prepare_tpacket_socket(pcap_t *handle)
4362 {
4363 struct pcap_linux *handlep = handle->priv;
4364 #if defined(HAVE_TPACKET2) || defined(HAVE_TPACKET3)
4365 int ret;
4366 #endif
4367
4368 #ifdef HAVE_TPACKET3
4369 /*
4370 * Try setting the version to TPACKET_V3.
4371 *
4372 * The only mode in which buffering is done on PF_PACKET
4373 * sockets, so that packets might not be delivered
4374 * immediately, is TPACKET_V3 mode.
4375 *
4376 * The buffering cannot be disabled in that mode, so
4377 * if the user has requested immediate mode, we don't
4378 * use TPACKET_V3.
4379 */
4380 if (!handle->opt.immediate) {
4381 ret = init_tpacket(handle, TPACKET_V3, "TPACKET_V3");
4382 if (ret == 0) {
4383 /*
4384 * Success.
4385 */
4386 return 1;
4387 }
4388 if (ret == -1) {
4389 /*
4390 * We failed for some reason other than "the
4391 * kernel doesn't support TPACKET_V3".
4392 */
4393 return -1;
4394 }
4395 }
4396 #endif /* HAVE_TPACKET3 */
4397
4398 #ifdef HAVE_TPACKET2
4399 /*
4400 * Try setting the version to TPACKET_V2.
4401 */
4402 ret = init_tpacket(handle, TPACKET_V2, "TPACKET_V2");
4403 if (ret == 0) {
4404 /*
4405 * Success.
4406 */
4407 return 1;
4408 }
4409 if (ret == -1) {
4410 /*
4411 * We failed for some reason other than "the
4412 * kernel doesn't support TPACKET_V2".
4413 */
4414 return -1;
4415 }
4416 #endif /* HAVE_TPACKET2 */
4417
4418 /*
4419 * OK, we're using TPACKET_V1, as either that's all the kernel
4420 * supports or it doesn't support TPACKET at all. In the latter
4421 * case, create_ring() will fail, and we'll fall back on non-
4422 * memory-mapped capture.
4423 */
4424 handlep->tp_version = TPACKET_V1;
4425 handlep->tp_hdrlen = sizeof(struct tpacket_hdr);
4426
4427 #ifdef ISA_64_BIT
4428 /*
4429 * 32-bit userspace + 64-bit kernel + TPACKET_V1 are not compatible with
4430 * each other due to platform-dependent data type size differences.
4431 *
4432 * If we have a 32-bit userland and a 64-bit kernel, use an
4433 * internally-defined TPACKET_V1_64, with which we use a 64-bit
4434 * version of the data structures.
4435 */
4436 if (sizeof(long) == 4) {
4437 /*
4438 * This is 32-bit code.
4439 */
4440 struct utsname utsname;
4441
4442 if (uname(&utsname) == -1) {
4443 /*
4444 * Failed.
4445 */
4446 pcap_fmt_errmsg_for_errno(handle->errbuf,
4447 PCAP_ERRBUF_SIZE, errno, "uname failed");
4448 return -1;
4449 }
4450 if (strcmp(utsname.machine, ISA_64_BIT) == 0) {
4451 /*
4452 * uname() tells us the machine is 64-bit,
4453 * so we presumably have a 64-bit kernel.
4454 *
4455 * XXX - this presumes that uname() won't lie
4456 * in 32-bit code and claim that the machine
4457 * has the 32-bit version of the ISA.
4458 */
4459 handlep->tp_version = TPACKET_V1_64;
4460 handlep->tp_hdrlen = sizeof(struct tpacket_hdr_64);
4461 }
4462 }
4463 #endif
4464
4465 return 1;
4466 }
4467
4468 #define MAX(a,b) ((a)>(b)?(a):(b))
4469
4470 /*
4471 * Attempt to set up memory-mapped access.
4472 *
4473 * On success, returns 1, and sets *status to 0 if there are no warnings
4474 * or to a PCAP_WARNING_ code if there is a warning.
4475 *
4476 * On failure due to lack of support for memory-mapped capture, returns
4477 * 0.
4478 *
4479 * On error, returns -1, and sets *status to the appropriate error code;
4480 * if that is PCAP_ERROR, sets handle->errbuf to the appropriate message.
4481 */
4482 static int
4483 create_ring(pcap_t *handle, int *status)
4484 {
4485 struct pcap_linux *handlep = handle->priv;
4486 unsigned i, j, frames_per_block;
4487 #ifdef HAVE_TPACKET3
4488 /*
4489 * For sockets using TPACKET_V1 or TPACKET_V2, the extra
4490 * stuff at the end of a struct tpacket_req3 will be
4491 * ignored, so this is OK even for those sockets.
4492 */
4493 struct tpacket_req3 req;
4494 #else
4495 struct tpacket_req req;
4496 #endif
4497 socklen_t len;
4498 unsigned int sk_type, tp_reserve, maclen, tp_hdrlen, netoff, macoff;
4499 unsigned int frame_size;
4500
4501 /*
4502 * Start out assuming no warnings or errors.
4503 */
4504 *status = 0;
4505
4506 #ifdef TPACKET_RESERVE
4507 /*
4508 * TPACKET_V2 and PACKET_RESERVE were both introduced in
4509 * 2.6.27. If tp_version is for TPACKET_V1, that means
4510 * the kernel doesn't support TPACKET_V2, so it won't
4511 * support PACKET_RESERVE, either.
4512 */
4513 if (handle->tp_version != TPACKET_V1 &&
4514 handle->tp_version != TPACKET_V1_64) {
4515 /*
4516 * Reserve space for VLAN tag reconstruction.
4517 */
4518 tp_reserve = VLAN_TAG_LEN;
4519
4520 /*
4521 * If we're using DLT_LINUX_SLL2, reserve space for a
4522 * DLT_LINUX_SLL2 header.
4523 *
4524 * XXX - we assume that the kernel is still adding
4525 * 16 bytes of extra space; that happens to
4526 * correspond to SLL_HDR_LEN (whether intentionally
4527 * or not - the kernel code has a raw "16" in
4528 * the expression), so we subtract SLL_HDR_LEN
4529 * from SLL2_HDR_LEN to get the additional space
4530 * needed. That also means we don't bother reserving
4531 * any additional space if we're using DLT_LINUX_SLL.
4532 *
4533 * XXX - should we use TPACKET_ALIGN(SLL2_HDR_LEN - SLL_HDR_LEN)?
4534 */
4535 if (handle->linktype == DLT_LINUX_SLL2)
4536 tp_reserve += SLL2_HDR_LEN - SLL_HDR_LEN;
4537
4538 /*
4539 * Try to request that amount of reserve space.
4540 * This must be done before creating the ring buffer.
4541 * If PACKET_RESERVE is supported, creating the ring
4542 * buffer should be, although if creating the ring
4543 * buffer fails, the PACKET_RESERVE call has no effect,
4544 * so falling back on read-from-the-socket capturing
4545 * won't be affected.
4546 */
4547 len = sizeof(tp_reserve);
4548 if (setsockopt(handle->fd, SOL_PACKET, PACKET_RESERVE,
4549 &tp_reserve, len) < 0) {
4550 /*
4551 * We treat ENOPROTOOPT as an error, as we
4552 * already determined that we support
4553 * TPACKET_V2 and later; see above.
4554 */
4555 pcap_fmt_errmsg_for_errno(handle->errbuf,
4556 PCAP_ERRBUF_SIZE, errno,
4557 "setsockopt (PACKET_RESERVE)");
4558 *status = PCAP_ERROR;
4559 return -1;
4560 }
4561 } else {
4562 /*
4563 * Older kernel, so we can't use PACKET_RESERVE;
4564 * this means we can't reserver extra space
4565 * for a DLT_LINUX_SLL2 header.
4566 *
4567 * Those kernels don't supply the information
4568 * necessary to reconstruct the VLAN tag, so
4569 * that's not an issue here, and we don't allow
4570 * DLT_LINUX_SLL2 if we can't use PACKET_RESERVE,
4571 * so that shouldn't be an issue.
4572 */
4573 tp_reserve = 0; /* nothing reserved */
4574 }
4575 #else
4576 /*
4577 * Build environment for an older kernel, so we can't use
4578 * PACKET_RESERVE.
4579 *
4580 * Those kernels don't supply the information necessary
4581 * to reconstruct the VLAN tag, so that's not an issue
4582 * here, and we don't allow DLT_LINUX_SLL2 if we can't
4583 * use PACKET_RESERVE, so that shouldn't be an issue.
4584 */
4585 tp_reserve = 0; /* nothing reserved */
4586 #endif
4587
4588 switch (handlep->tp_version) {
4589
4590 case TPACKET_V1:
4591 case TPACKET_V1_64:
4592 #ifdef HAVE_TPACKET2
4593 case TPACKET_V2:
4594 #endif
4595 /* Note that with large snapshot length (say 256K, which is
4596 * the default for recent versions of tcpdump, Wireshark,
4597 * TShark, dumpcap or 64K, the value that "-s 0" has given for
4598 * a long time with tcpdump), if we use the snapshot
4599 * length to calculate the frame length, only a few frames
4600 * will be available in the ring even with pretty
4601 * large ring size (and a lot of memory will be unused).
4602 *
4603 * Ideally, we should choose a frame length based on the
4604 * minimum of the specified snapshot length and the maximum
4605 * packet size. That's not as easy as it sounds; consider,
4606 * for example, an 802.11 interface in monitor mode, where
4607 * the frame would include a radiotap header, where the
4608 * maximum radiotap header length is device-dependent.
4609 *
4610 * So, for now, we just do this for Ethernet devices, where
4611 * there's no metadata header, and the link-layer header is
4612 * fixed length. We can get the maximum packet size by
4613 * adding 18, the Ethernet header length plus the CRC length
4614 * (just in case we happen to get the CRC in the packet), to
4615 * the MTU of the interface; we fetch the MTU in the hopes
4616 * that it reflects support for jumbo frames. (Even if the
4617 * interface is just being used for passive snooping, the
4618 * driver might set the size of buffers in the receive ring
4619 * based on the MTU, so that the MTU limits the maximum size
4620 * of packets that we can receive.)
4621 *
4622 * If segmentation/fragmentation or receive offload are
4623 * enabled, we can get reassembled/aggregated packets larger
4624 * than MTU, but bounded to 65535 plus the Ethernet overhead,
4625 * due to kernel and protocol constraints */
4626 frame_size = handle->snapshot;
4627 if (handle->linktype == DLT_EN10MB) {
4628 unsigned int max_frame_len;
4629 int mtu;
4630 int offload;
4631
4632 mtu = iface_get_mtu(handle->fd, handle->opt.device,
4633 handle->errbuf);
4634 if (mtu == -1) {
4635 *status = PCAP_ERROR;
4636 return -1;
4637 }
4638 offload = iface_get_offload(handle);
4639 if (offload == -1) {
4640 *status = PCAP_ERROR;
4641 return -1;
4642 }
4643 if (offload)
4644 max_frame_len = MAX(mtu, 65535);
4645 else
4646 max_frame_len = mtu;
4647 max_frame_len += 18;
4648
4649 if (frame_size > max_frame_len)
4650 frame_size = max_frame_len;
4651 }
4652
4653 /* NOTE: calculus matching those in tpacket_rcv()
4654 * in linux-2.6/net/packet/af_packet.c
4655 */
4656 len = sizeof(sk_type);
4657 if (getsockopt(handle->fd, SOL_SOCKET, SO_TYPE, &sk_type,
4658 &len) < 0) {
4659 pcap_fmt_errmsg_for_errno(handle->errbuf,
4660 PCAP_ERRBUF_SIZE, errno, "getsockopt (SO_TYPE)");
4661 *status = PCAP_ERROR;
4662 return -1;
4663 }
4664 maclen = (sk_type == SOCK_DGRAM) ? 0 : MAX_LINKHEADER_SIZE;
4665 /* XXX: in the kernel maclen is calculated from
4666 * LL_ALLOCATED_SPACE(dev) and vnet_hdr.hdr_len
4667 * in: packet_snd() in linux-2.6/net/packet/af_packet.c
4668 * then packet_alloc_skb() in linux-2.6/net/packet/af_packet.c
4669 * then sock_alloc_send_pskb() in linux-2.6/net/core/sock.c
4670 * but I see no way to get those sizes in userspace,
4671 * like for instance with an ifreq ioctl();
4672 * the best thing I've found so far is MAX_HEADER in
4673 * the kernel part of linux-2.6/include/linux/netdevice.h
4674 * which goes up to 128+48=176; since pcap-linux.c
4675 * defines a MAX_LINKHEADER_SIZE of 256 which is
4676 * greater than that, let's use it.. maybe is it even
4677 * large enough to directly replace macoff..
4678 */
4679 tp_hdrlen = TPACKET_ALIGN(handlep->tp_hdrlen) + sizeof(struct sockaddr_ll) ;
4680 netoff = TPACKET_ALIGN(tp_hdrlen + (maclen < 16 ? 16 : maclen)) + tp_reserve;
4681 /* NOTE: AFAICS tp_reserve may break the TPACKET_ALIGN
4682 * of netoff, which contradicts
4683 * linux-2.6/Documentation/networking/packet_mmap.txt
4684 * documenting that:
4685 * "- Gap, chosen so that packet data (Start+tp_net)
4686 * aligns to TPACKET_ALIGNMENT=16"
4687 */
4688 /* NOTE: in linux-2.6/include/linux/skbuff.h:
4689 * "CPUs often take a performance hit
4690 * when accessing unaligned memory locations"
4691 */
4692 macoff = netoff - maclen;
4693 req.tp_frame_size = TPACKET_ALIGN(macoff + frame_size);
4694 /*
4695 * Round the buffer size up to a multiple of the
4696 * frame size (rather than rounding down, which
4697 * would give a buffer smaller than our caller asked
4698 * for, and possibly give zero frames if the requested
4699 * buffer size is too small for one frame).
4700 */
4701 req.tp_frame_nr = (handle->opt.buffer_size + req.tp_frame_size - 1)/req.tp_frame_size;
4702 break;
4703
4704 #ifdef HAVE_TPACKET3
4705 case TPACKET_V3:
4706 /* The "frames" for this are actually buffers that
4707 * contain multiple variable-sized frames.
4708 *
4709 * We pick a "frame" size of MAXIMUM_SNAPLEN to leave
4710 * enough room for at least one reasonably-sized packet
4711 * in the "frame". */
4712 req.tp_frame_size = MAXIMUM_SNAPLEN;
4713 /*
4714 * Round the buffer size up to a multiple of the
4715 * "frame" size (rather than rounding down, which
4716 * would give a buffer smaller than our caller asked
4717 * for, and possibly give zero "frames" if the requested
4718 * buffer size is too small for one "frame").
4719 */
4720 req.tp_frame_nr = (handle->opt.buffer_size + req.tp_frame_size - 1)/req.tp_frame_size;
4721 break;
4722 #endif
4723 default:
4724 snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
4725 "Internal error: unknown TPACKET_ value %u",
4726 handlep->tp_version);
4727 *status = PCAP_ERROR;
4728 return -1;
4729 }
4730
4731 /* compute the minumum block size that will handle this frame.
4732 * The block has to be page size aligned.
4733 * The max block size allowed by the kernel is arch-dependent and
4734 * it's not explicitly checked here. */
4735 req.tp_block_size = getpagesize();
4736 while (req.tp_block_size < req.tp_frame_size)
4737 req.tp_block_size <<= 1;
4738
4739 frames_per_block = req.tp_block_size/req.tp_frame_size;
4740
4741 /*
4742 * PACKET_TIMESTAMP was added after linux/net_tstamp.h was,
4743 * so we check for PACKET_TIMESTAMP. We check for
4744 * linux/net_tstamp.h just in case a system somehow has
4745 * PACKET_TIMESTAMP but not linux/net_tstamp.h; that might
4746 * be unnecessary.
4747 *
4748 * SIOCSHWTSTAMP was introduced in the patch that introduced
4749 * linux/net_tstamp.h, so we don't bother checking whether
4750 * SIOCSHWTSTAMP is defined (if your Linux system has
4751 * linux/net_tstamp.h but doesn't define SIOCSHWTSTAMP, your
4752 * Linux system is badly broken).
4753 */
4754 #if defined(HAVE_LINUX_NET_TSTAMP_H) && defined(PACKET_TIMESTAMP)
4755 /*
4756 * If we were told to do so, ask the kernel and the driver
4757 * to use hardware timestamps.
4758 *
4759 * Hardware timestamps are only supported with mmapped
4760 * captures.
4761 */
4762 if (handle->opt.tstamp_type == PCAP_TSTAMP_ADAPTER ||
4763 handle->opt.tstamp_type == PCAP_TSTAMP_ADAPTER_UNSYNCED) {
4764 struct hwtstamp_config hwconfig;
4765 struct ifreq ifr;
4766 int timesource;
4767
4768 /*
4769 * Ask for hardware time stamps on all packets,
4770 * including transmitted packets.
4771 */
4772 memset(&hwconfig, 0, sizeof(hwconfig));
4773 hwconfig.tx_type = HWTSTAMP_TX_ON;
4774 hwconfig.rx_filter = HWTSTAMP_FILTER_ALL;
4775
4776 memset(&ifr, 0, sizeof(ifr));
4777 pcap_strlcpy(ifr.ifr_name, handle->opt.device, sizeof(ifr.ifr_name));
4778 ifr.ifr_data = (void *)&hwconfig;
4779
4780 if (ioctl(handle->fd, SIOCSHWTSTAMP, &ifr) < 0) {
4781 switch (errno) {
4782
4783 case EPERM:
4784 /*
4785 * Treat this as an error, as the
4786 * user should try to run this
4787 * with the appropriate privileges -
4788 * and, if they can't, shouldn't
4789 * try requesting hardware time stamps.
4790 */
4791 *status = PCAP_ERROR_PERM_DENIED;
4792 return -1;
4793
4794 case EOPNOTSUPP:
4795 case ERANGE:
4796 /*
4797 * Treat this as a warning, as the
4798 * only way to fix the warning is to
4799 * get an adapter that supports hardware
4800 * time stamps for *all* packets.
4801 * (ERANGE means "we support hardware
4802 * time stamps, but for packets matching
4803 * that particular filter", so it means
4804 * "we don't support hardware time stamps
4805 * for all incoming packets" here.)
4806 *
4807 * We'll just fall back on the standard
4808 * host time stamps.
4809 */
4810 *status = PCAP_WARNING_TSTAMP_TYPE_NOTSUP;
4811 break;
4812
4813 default:
4814 pcap_fmt_errmsg_for_errno(handle->errbuf,
4815 PCAP_ERRBUF_SIZE, errno,
4816 "SIOCSHWTSTAMP failed");
4817 *status = PCAP_ERROR;
4818 return -1;
4819 }
4820 } else {
4821 /*
4822 * Well, that worked. Now specify the type of
4823 * hardware time stamp we want for this
4824 * socket.
4825 */
4826 if (handle->opt.tstamp_type == PCAP_TSTAMP_ADAPTER) {
4827 /*
4828 * Hardware timestamp, synchronized
4829 * with the system clock.
4830 */
4831 timesource = SOF_TIMESTAMPING_SYS_HARDWARE;
4832 } else {
4833 /*
4834 * PCAP_TSTAMP_ADAPTER_UNSYNCED - hardware
4835 * timestamp, not synchronized with the
4836 * system clock.
4837 */
4838 timesource = SOF_TIMESTAMPING_RAW_HARDWARE;
4839 }
4840 if (setsockopt(handle->fd, SOL_PACKET, PACKET_TIMESTAMP,
4841 (void *)&timesource, sizeof(timesource))) {
4842 pcap_fmt_errmsg_for_errno(handle->errbuf,
4843 PCAP_ERRBUF_SIZE, errno,
4844 "can't set PACKET_TIMESTAMP");
4845 *status = PCAP_ERROR;
4846 return -1;
4847 }
4848 }
4849 }
4850 #endif /* HAVE_LINUX_NET_TSTAMP_H && PACKET_TIMESTAMP */
4851
4852 /* ask the kernel to create the ring */
4853 retry:
4854 req.tp_block_nr = req.tp_frame_nr / frames_per_block;
4855
4856 /* req.tp_frame_nr is requested to match frames_per_block*req.tp_block_nr */
4857 req.tp_frame_nr = req.tp_block_nr * frames_per_block;
4858
4859 #ifdef HAVE_TPACKET3
4860 /* timeout value to retire block - use the configured buffering timeout, or default if <0. */
4861 if (handlep->timeout > 0) {
4862 /* Use the user specified timeout as the block timeout */
4863 req.tp_retire_blk_tov = handlep->timeout;
4864 } else if (handlep->timeout == 0) {
4865 /*
4866 * In pcap, this means "infinite timeout"; TPACKET_V3
4867 * doesn't support that, so just set it to UINT_MAX
4868 * milliseconds. In the TPACKET_V3 loop, if the
4869 * timeout is 0, and we haven't yet seen any packets,
4870 * and we block and still don't have any packets, we
4871 * keep blocking until we do.
4872 */
4873 req.tp_retire_blk_tov = UINT_MAX;
4874 } else {
4875 /*
4876 * XXX - this is not valid; use 0, meaning "have the
4877 * kernel pick a default", for now.
4878 */
4879 req.tp_retire_blk_tov = 0;
4880 }
4881 /* private data not used */
4882 req.tp_sizeof_priv = 0;
4883 /* Rx ring - feature request bits - none (rxhash will not be filled) */
4884 req.tp_feature_req_word = 0;
4885 #endif
4886
4887 if (setsockopt(handle->fd, SOL_PACKET, PACKET_RX_RING,
4888 (void *) &req, sizeof(req))) {
4889 if ((errno == ENOMEM) && (req.tp_block_nr > 1)) {
4890 /*
4891 * Memory failure; try to reduce the requested ring
4892 * size.
4893 *
4894 * We used to reduce this by half -- do 5% instead.
4895 * That may result in more iterations and a longer
4896 * startup, but the user will be much happier with
4897 * the resulting buffer size.
4898 */
4899 if (req.tp_frame_nr < 20)
4900 req.tp_frame_nr -= 1;
4901 else
4902 req.tp_frame_nr -= req.tp_frame_nr/20;
4903 goto retry;
4904 }
4905 if (errno == ENOPROTOOPT) {
4906 /*
4907 * We don't have ring buffer support in this kernel.
4908 */
4909 return 0;
4910 }
4911 pcap_fmt_errmsg_for_errno(handle->errbuf, PCAP_ERRBUF_SIZE,
4912 errno, "can't create rx ring on packet socket");
4913 *status = PCAP_ERROR;
4914 return -1;
4915 }
4916
4917 /* memory map the rx ring */
4918 handlep->mmapbuflen = req.tp_block_nr * req.tp_block_size;
4919 handlep->mmapbuf = mmap(0, handlep->mmapbuflen,
4920 PROT_READ|PROT_WRITE, MAP_SHARED, handle->fd, 0);
4921 if (handlep->mmapbuf == MAP_FAILED) {
4922 pcap_fmt_errmsg_for_errno(handle->errbuf, PCAP_ERRBUF_SIZE,
4923 errno, "can't mmap rx ring");
4924
4925 /* clear the allocated ring on error*/
4926 destroy_ring(handle);
4927 *status = PCAP_ERROR;
4928 return -1;
4929 }
4930
4931 /* allocate a ring for each frame header pointer*/
4932 handle->cc = req.tp_frame_nr;
4933 handle->buffer = malloc(handle->cc * sizeof(union thdr *));
4934 if (!handle->buffer) {
4935 pcap_fmt_errmsg_for_errno(handle->errbuf, PCAP_ERRBUF_SIZE,
4936 errno, "can't allocate ring of frame headers");
4937
4938 destroy_ring(handle);
4939 *status = PCAP_ERROR;
4940 return -1;
4941 }
4942
4943 /* fill the header ring with proper frame ptr*/
4944 handle->offset = 0;
4945 for (i=0; i<req.tp_block_nr; ++i) {
4946 void *base = &handlep->mmapbuf[i*req.tp_block_size];
4947 for (j=0; j<frames_per_block; ++j, ++handle->offset) {
4948 RING_GET_CURRENT_FRAME(handle) = base;
4949 base += req.tp_frame_size;
4950 }
4951 }
4952
4953 handle->bufsize = req.tp_frame_size;
4954 handle->offset = 0;
4955 return 1;
4956 }
4957
4958 /* free all ring related resources*/
4959 static void
4960 destroy_ring(pcap_t *handle)
4961 {
4962 struct pcap_linux *handlep = handle->priv;
4963
4964 /* tell the kernel to destroy the ring*/
4965 struct tpacket_req req;
4966 memset(&req, 0, sizeof(req));
4967 /* do not test for setsockopt failure, as we can't recover from any error */
4968 (void)setsockopt(handle->fd, SOL_PACKET, PACKET_RX_RING,
4969 (void *) &req, sizeof(req));
4970
4971 /* if ring is mapped, unmap it*/
4972 if (handlep->mmapbuf) {
4973 /* do not test for mmap failure, as we can't recover from any error */
4974 (void)munmap(handlep->mmapbuf, handlep->mmapbuflen);
4975 handlep->mmapbuf = NULL;
4976 }
4977 }
4978
4979 /*
4980 * Special one-shot callback, used for pcap_next() and pcap_next_ex(),
4981 * for Linux mmapped capture.
4982 *
4983 * The problem is that pcap_next() and pcap_next_ex() expect the packet
4984 * data handed to the callback to be valid after the callback returns,
4985 * but pcap_read_linux_mmap() has to release that packet as soon as
4986 * the callback returns (otherwise, the kernel thinks there's still
4987 * at least one unprocessed packet available in the ring, so a select()
4988 * will immediately return indicating that there's data to process), so,
4989 * in the callback, we have to make a copy of the packet.
4990 *
4991 * Yes, this means that, if the capture is using the ring buffer, using
4992 * pcap_next() or pcap_next_ex() requires more copies than using
4993 * pcap_loop() or pcap_dispatch(). If that bothers you, don't use
4994 * pcap_next() or pcap_next_ex().
4995 */
4996 static void
4997 pcap_oneshot_mmap(u_char *user, const struct pcap_pkthdr *h,
4998 const u_char *bytes)
4999 {
5000 struct oneshot_userdata *sp = (struct oneshot_userdata *)user;
5001 pcap_t *handle = sp->pd;
5002 struct pcap_linux *handlep = handle->priv;
5003
5004 *sp->hdr = *h;
5005 memcpy(handlep->oneshot_buffer, bytes, h->caplen);
5006 *sp->pkt = handlep->oneshot_buffer;
5007 }
5008
5009 static void
5010 pcap_cleanup_linux_mmap( pcap_t *handle )
5011 {
5012 struct pcap_linux *handlep = handle->priv;
5013
5014 destroy_ring(handle);
5015 if (handlep->oneshot_buffer != NULL) {
5016 free(handlep->oneshot_buffer);
5017 handlep->oneshot_buffer = NULL;
5018 }
5019 pcap_cleanup_linux(handle);
5020 }
5021
5022
5023 static int
5024 pcap_getnonblock_mmap(pcap_t *handle)
5025 {
5026 struct pcap_linux *handlep = handle->priv;
5027
5028 /* use negative value of timeout to indicate non blocking ops */
5029 return (handlep->timeout<0);
5030 }
5031
5032 static int
5033 pcap_setnonblock_mmap(pcap_t *handle, int nonblock)
5034 {
5035 struct pcap_linux *handlep = handle->priv;
5036
5037 /*
5038 * Set the file descriptor to non-blocking mode, as we use
5039 * it for sending packets.
5040 */
5041 if (pcap_setnonblock_fd(handle, nonblock) == -1)
5042 return -1;
5043
5044 /*
5045 * Map each value to their corresponding negation to
5046 * preserve the timeout value provided with pcap_set_timeout.
5047 */
5048 if (nonblock) {
5049 if (handlep->timeout >= 0) {
5050 /*
5051 * Indicate that we're switching to
5052 * non-blocking mode.
5053 */
5054 handlep->timeout = ~handlep->timeout;
5055 }
5056 } else {
5057 if (handlep->timeout < 0) {
5058 handlep->timeout = ~handlep->timeout;
5059 }
5060 }
5061 /* Update the timeout to use in poll(). */
5062 set_poll_timeout(handlep);
5063 return 0;
5064 }
5065
5066 /*
5067 * Get the status field of the ring buffer frame at a specified offset.
5068 */
5069 static inline u_int
5070 pcap_get_ring_frame_status(pcap_t *handle, int offset)
5071 {
5072 struct pcap_linux *handlep = handle->priv;
5073 union thdr h;
5074
5075 h.raw = RING_GET_FRAME_AT(handle, offset);
5076 switch (handlep->tp_version) {
5077 case TPACKET_V1:
5078 /*
5079 * This is an unsigned long, but only the lower 32
5080 * bits are used.
5081 */
5082 return (u_int)(h.h1->tp_status);
5083 break;
5084 case TPACKET_V1_64:
5085 /*
5086 * This is an unsigned long in the kernel, which is 64-bit,
5087 * but only the lower 32 bits are used.
5088 */
5089 return (u_int)(h.h1_64->tp_status);
5090 break;
5091 #ifdef HAVE_TPACKET2
5092 case TPACKET_V2:
5093 return (h.h2->tp_status);
5094 break;
5095 #endif
5096 #ifdef HAVE_TPACKET3
5097 case TPACKET_V3:
5098 return (h.h3->hdr.bh1.block_status);
5099 break;
5100 #endif
5101 }
5102 /* This should not happen. */
5103 return 0;
5104 }
5105
5106 #ifndef POLLRDHUP
5107 #define POLLRDHUP 0
5108 #endif
5109
5110 /*
5111 * Block waiting for frames to be available.
5112 */
5113 static int pcap_wait_for_frames_mmap(pcap_t *handle)
5114 {
5115 struct pcap_linux *handlep = handle->priv;
5116 char c;
5117 int ret;
5118 #ifdef HAVE_SYS_EVENTFD_H
5119 struct pollfd pollinfo[2];
5120 pollinfo[1].fd = handlep->poll_breakloop_fd;
5121 pollinfo[1].events = POLLIN;
5122 #else
5123 struct pollfd pollinfo[1];
5124 #endif
5125 pollinfo[0].fd = handle->fd;
5126 pollinfo[0].events = POLLIN;
5127
5128 do {
5129 /*
5130 * Yes, we do this even in non-blocking mode, as it's
5131 * the only way to get error indications from a
5132 * tpacket socket.
5133 *
5134 * The timeout is 0 in non-blocking mode, so poll()
5135 * returns immediately.
5136 */
5137
5138 #ifdef HAVE_SYS_EVENTFD_H
5139 ret = poll(pollinfo, 2, handlep->poll_timeout);
5140 #else
5141 ret = poll(pollinfo, 1, handlep->poll_timeout);
5142 #endif
5143 if (ret < 0 && errno != EINTR) {
5144 pcap_fmt_errmsg_for_errno(handle->errbuf,
5145 PCAP_ERRBUF_SIZE, errno,
5146 "can't poll on packet socket");
5147 return PCAP_ERROR;
5148 } else if (ret > 0 && pollinfo[0].revents &&
5149 (pollinfo[0].revents & (POLLHUP|POLLRDHUP|POLLERR|POLLNVAL))) {
5150 /*
5151 * There's some indication other than
5152 * "you can read on this descriptor" on
5153 * the descriptor.
5154 */
5155 if (pollinfo[0].revents & (POLLHUP | POLLRDHUP)) {
5156 snprintf(handle->errbuf,
5157 PCAP_ERRBUF_SIZE,
5158 "Hangup on packet socket");
5159 return PCAP_ERROR;
5160 }
5161 if (pollinfo[0].revents & POLLERR) {
5162 /*
5163 * A recv() will give us the actual error code.
5164 *
5165 * XXX - make the socket non-blocking?
5166 */
5167 if (recv(handle->fd, &c, sizeof c,
5168 MSG_PEEK) != -1)
5169 continue; /* what, no error? */
5170 if (errno == ENETDOWN) {
5171 /*
5172 * The device on which we're
5173 * capturing went away.
5174 *
5175 * XXX - we should really return
5176 * PCAP_ERROR_IFACE_NOT_UP, but
5177 * pcap_dispatch() etc. aren't
5178 * defined to return that.
5179 */
5180 snprintf(handle->errbuf,
5181 PCAP_ERRBUF_SIZE,
5182 "The interface went down");
5183 } else {
5184 pcap_fmt_errmsg_for_errno(handle->errbuf,
5185 PCAP_ERRBUF_SIZE, errno,
5186 "Error condition on packet socket");
5187 }
5188 return PCAP_ERROR;
5189 }
5190 if (pollinfo[0].revents & POLLNVAL) {
5191 snprintf(handle->errbuf,
5192 PCAP_ERRBUF_SIZE,
5193 "Invalid polling request on packet socket");
5194 return PCAP_ERROR;
5195 }
5196 }
5197
5198 #ifdef HAVE_SYS_EVENTFD_H
5199 if (pollinfo[1].revents & POLLIN) {
5200 uint64_t value;
5201 (void)read(handlep->poll_breakloop_fd, &value, sizeof(value));
5202 }
5203 #endif
5204
5205 /* check for break loop condition on interrupted syscall*/
5206 if (handle->break_loop) {
5207 handle->break_loop = 0;
5208 return PCAP_ERROR_BREAK;
5209 }
5210 } while (ret < 0);
5211 return 0;
5212 }
5213
5214 /* handle a single memory mapped packet */
5215 static int pcap_handle_packet_mmap(
5216 pcap_t *handle,
5217 pcap_handler callback,
5218 u_char *user,
5219 unsigned char *frame,
5220 unsigned int tp_len,
5221 unsigned int tp_mac,
5222 unsigned int tp_snaplen,
5223 unsigned int tp_sec,
5224 unsigned int tp_usec,
5225 int tp_vlan_tci_valid,
5226 __u16 tp_vlan_tci,
5227 __u16 tp_vlan_tpid)
5228 {
5229 struct pcap_linux *handlep = handle->priv;
5230 unsigned char *bp;
5231 struct sockaddr_ll *sll;
5232 struct pcap_pkthdr pcaphdr;
5233 unsigned int snaplen = tp_snaplen;
5234 struct utsname utsname;
5235
5236 /* perform sanity check on internal offset. */
5237 if (tp_mac + tp_snaplen > handle->bufsize) {
5238 /*
5239 * Report some system information as a debugging aid.
5240 */
5241 if (uname(&utsname) != -1) {
5242 snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
5243 "corrupted frame on kernel ring mac "
5244 "offset %u + caplen %u > frame len %d "
5245 "(kernel %.32s version %s, machine %.16s)",
5246 tp_mac, tp_snaplen, handle->bufsize,
5247 utsname.release, utsname.version,
5248 utsname.machine);
5249 } else {
5250 snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
5251 "corrupted frame on kernel ring mac "
5252 "offset %u + caplen %u > frame len %d",
5253 tp_mac, tp_snaplen, handle->bufsize);
5254 }
5255 return -1;
5256 }
5257
5258 /* run filter on received packet
5259 * If the kernel filtering is enabled we need to run the
5260 * filter until all the frames present into the ring
5261 * at filter creation time are processed.
5262 * In this case, blocks_to_filter_in_userland is used
5263 * as a counter for the packet we need to filter.
5264 * Note: alternatively it could be possible to stop applying
5265 * the filter when the ring became empty, but it can possibly
5266 * happen a lot later... */
5267 bp = frame + tp_mac;
5268
5269 /* if required build in place the sll header*/
5270 sll = (void *)frame + TPACKET_ALIGN(handlep->tp_hdrlen);
5271 if (handlep->cooked) {
5272 if (handle->linktype == DLT_LINUX_SLL2) {
5273 struct sll2_header *hdrp;
5274
5275 /*
5276 * The kernel should have left us with enough
5277 * space for an sll header; back up the packet
5278 * data pointer into that space, as that'll be
5279 * the beginning of the packet we pass to the
5280 * callback.
5281 */
5282 bp -= SLL2_HDR_LEN;
5283
5284 /*
5285 * Let's make sure that's past the end of
5286 * the tpacket header, i.e. >=
5287 * ((u_char *)thdr + TPACKET_HDRLEN), so we
5288 * don't step on the header when we construct
5289 * the sll header.
5290 */
5291 if (bp < (u_char *)frame +
5292 TPACKET_ALIGN(handlep->tp_hdrlen) +
5293 sizeof(struct sockaddr_ll)) {
5294 snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
5295 "cooked-mode frame doesn't have room for sll header");
5296 return -1;
5297 }
5298
5299 /*
5300 * OK, that worked; construct the sll header.
5301 */
5302 hdrp = (struct sll2_header *)bp;
5303 hdrp->sll2_protocol = sll->sll_protocol;
5304 hdrp->sll2_reserved_mbz = 0;
5305 hdrp->sll2_if_index = htonl(sll->sll_ifindex);
5306 hdrp->sll2_hatype = htons(sll->sll_hatype);
5307 hdrp->sll2_pkttype = sll->sll_pkttype;
5308 hdrp->sll2_halen = sll->sll_halen;
5309 memcpy(hdrp->sll2_addr, sll->sll_addr, SLL_ADDRLEN);
5310
5311 snaplen += sizeof(struct sll2_header);
5312 } else {
5313 struct sll_header *hdrp;
5314
5315 /*
5316 * The kernel should have left us with enough
5317 * space for an sll header; back up the packet
5318 * data pointer into that space, as that'll be
5319 * the beginning of the packet we pass to the
5320 * callback.
5321 */
5322 bp -= SLL_HDR_LEN;
5323
5324 /*
5325 * Let's make sure that's past the end of
5326 * the tpacket header, i.e. >=
5327 * ((u_char *)thdr + TPACKET_HDRLEN), so we
5328 * don't step on the header when we construct
5329 * the sll header.
5330 */
5331 if (bp < (u_char *)frame +
5332 TPACKET_ALIGN(handlep->tp_hdrlen) +
5333 sizeof(struct sockaddr_ll)) {
5334 snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
5335 "cooked-mode frame doesn't have room for sll header");
5336 return -1;
5337 }
5338
5339 /*
5340 * OK, that worked; construct the sll header.
5341 */
5342 hdrp = (struct sll_header *)bp;
5343 hdrp->sll_pkttype = htons(sll->sll_pkttype);
5344 hdrp->sll_hatype = htons(sll->sll_hatype);
5345 hdrp->sll_halen = htons(sll->sll_halen);
5346 memcpy(hdrp->sll_addr, sll->sll_addr, SLL_ADDRLEN);
5347 hdrp->sll_protocol = sll->sll_protocol;
5348
5349 snaplen += sizeof(struct sll_header);
5350 }
5351 }
5352
5353 if (handlep->filter_in_userland && handle->fcode.bf_insns) {
5354 struct bpf_aux_data aux_data;
5355
5356 aux_data.vlan_tag_present = tp_vlan_tci_valid;
5357 aux_data.vlan_tag = tp_vlan_tci & 0x0fff;
5358
5359 if (pcap_filter_with_aux_data(handle->fcode.bf_insns,
5360 bp,
5361 tp_len,
5362 snaplen,
5363 &aux_data) == 0)
5364 return 0;
5365 }
5366
5367 if (!linux_check_direction(handle, sll))
5368 return 0;
5369
5370 /* get required packet info from ring header */
5371 pcaphdr.ts.tv_sec = tp_sec;
5372 pcaphdr.ts.tv_usec = tp_usec;
5373 pcaphdr.caplen = tp_snaplen;
5374 pcaphdr.len = tp_len;
5375
5376 /* if required build in place the sll header*/
5377 if (handlep->cooked) {
5378 /* update packet len */
5379 if (handle->linktype == DLT_LINUX_SLL2) {
5380 pcaphdr.caplen += SLL2_HDR_LEN;
5381 pcaphdr.len += SLL2_HDR_LEN;
5382 } else {
5383 pcaphdr.caplen += SLL_HDR_LEN;
5384 pcaphdr.len += SLL_HDR_LEN;
5385 }
5386 }
5387
5388 #if defined(HAVE_TPACKET2) || defined(HAVE_TPACKET3)
5389 if (tp_vlan_tci_valid &&
5390 handlep->vlan_offset != -1 &&
5391 tp_snaplen >= (unsigned int) handlep->vlan_offset)
5392 {
5393 struct vlan_tag *tag;
5394
5395 /*
5396 * Move everything in the header, except the type field,
5397 * down VLAN_TAG_LEN bytes, to allow us to insert the
5398 * VLAN tag between that stuff and the type field.
5399 */
5400 bp -= VLAN_TAG_LEN;
5401 memmove(bp, bp + VLAN_TAG_LEN, handlep->vlan_offset);
5402
5403 /*
5404 * Now insert the tag.
5405 */
5406 tag = (struct vlan_tag *)(bp + handlep->vlan_offset);
5407 tag->vlan_tpid = htons(tp_vlan_tpid);
5408 tag->vlan_tci = htons(tp_vlan_tci);
5409
5410 /*
5411 * Add the tag to the packet lengths.
5412 */
5413 pcaphdr.caplen += VLAN_TAG_LEN;
5414 pcaphdr.len += VLAN_TAG_LEN;
5415 }
5416 #endif
5417
5418 /*
5419 * The only way to tell the kernel to cut off the
5420 * packet at a snapshot length is with a filter program;
5421 * if there's no filter program, the kernel won't cut
5422 * the packet off.
5423 *
5424 * Trim the snapshot length to be no longer than the
5425 * specified snapshot length.
5426 */
5427 if (pcaphdr.caplen > (bpf_u_int32)handle->snapshot)
5428 pcaphdr.caplen = handle->snapshot;
5429
5430 /* pass the packet to the user */
5431 callback(user, &pcaphdr, bp);
5432
5433 return 1;
5434 }
5435
5436 static int
5437 pcap_read_linux_mmap_v1(pcap_t *handle, int max_packets, pcap_handler callback,
5438 u_char *user)
5439 {
5440 struct pcap_linux *handlep = handle->priv;
5441 union thdr h;
5442 int pkts = 0;
5443 int ret;
5444
5445 /* wait for frames availability.*/
5446 h.raw = RING_GET_CURRENT_FRAME(handle);
5447 if (h.h1->tp_status == TP_STATUS_KERNEL) {
5448 /*
5449 * The current frame is owned by the kernel; wait for
5450 * a frame to be handed to us.
5451 */
5452 ret = pcap_wait_for_frames_mmap(handle);
5453 if (ret) {
5454 return ret;
5455 }
5456 }
5457
5458 /* non-positive values of max_packets are used to require all
5459 * packets currently available in the ring */
5460 while ((pkts < max_packets) || PACKET_COUNT_IS_UNLIMITED(max_packets)) {
5461 /*
5462 * Get the current ring buffer frame, and break if
5463 * it's still owned by the kernel.
5464 */
5465 h.raw = RING_GET_CURRENT_FRAME(handle);
5466 if (h.h1->tp_status == TP_STATUS_KERNEL)
5467 break;
5468
5469 ret = pcap_handle_packet_mmap(
5470 handle,
5471 callback,
5472 user,
5473 h.raw,
5474 h.h1->tp_len,
5475 h.h1->tp_mac,
5476 h.h1->tp_snaplen,
5477 h.h1->tp_sec,
5478 h.h1->tp_usec,
5479 0,
5480 0,
5481 0);
5482 if (ret == 1) {
5483 pkts++;
5484 handlep->packets_read++;
5485 } else if (ret < 0) {
5486 return ret;
5487 }
5488
5489 /*
5490 * Hand this block back to the kernel, and, if we're
5491 * counting blocks that need to be filtered in userland
5492 * after having been filtered by the kernel, count
5493 * the one we've just processed.
5494 */
5495 h.h1->tp_status = TP_STATUS_KERNEL;
5496 if (handlep->blocks_to_filter_in_userland > 0) {
5497 handlep->blocks_to_filter_in_userland--;
5498 if (handlep->blocks_to_filter_in_userland == 0) {
5499 /*
5500 * No more blocks need to be filtered
5501 * in userland.
5502 */
5503 handlep->filter_in_userland = 0;
5504 }
5505 }
5506
5507 /* next block */
5508 if (++handle->offset >= handle->cc)
5509 handle->offset = 0;
5510
5511 /* check for break loop condition*/
5512 if (handle->break_loop) {
5513 handle->break_loop = 0;
5514 return PCAP_ERROR_BREAK;
5515 }
5516 }
5517 return pkts;
5518 }
5519
5520 static int
5521 pcap_read_linux_mmap_v1_64(pcap_t *handle, int max_packets, pcap_handler callback,
5522 u_char *user)
5523 {
5524 struct pcap_linux *handlep = handle->priv;
5525 union thdr h;
5526 int pkts = 0;
5527 int ret;
5528
5529 /* wait for frames availability.*/
5530 h.raw = RING_GET_CURRENT_FRAME(handle);
5531 if (h.h1_64->tp_status == TP_STATUS_KERNEL) {
5532 /*
5533 * The current frame is owned by the kernel; wait for
5534 * a frame to be handed to us.
5535 */
5536 ret = pcap_wait_for_frames_mmap(handle);
5537 if (ret) {
5538 return ret;
5539 }
5540 }
5541
5542 /* non-positive values of max_packets are used to require all
5543 * packets currently available in the ring */
5544 while ((pkts < max_packets) || PACKET_COUNT_IS_UNLIMITED(max_packets)) {
5545 /*
5546 * Get the current ring buffer frame, and break if
5547 * it's still owned by the kernel.
5548 */
5549 h.raw = RING_GET_CURRENT_FRAME(handle);
5550 if (h.h1_64->tp_status == TP_STATUS_KERNEL)
5551 break;
5552
5553 ret = pcap_handle_packet_mmap(
5554 handle,
5555 callback,
5556 user,
5557 h.raw,
5558 h.h1_64->tp_len,
5559 h.h1_64->tp_mac,
5560 h.h1_64->tp_snaplen,
5561 h.h1_64->tp_sec,
5562 h.h1_64->tp_usec,
5563 0,
5564 0,
5565 0);
5566 if (ret == 1) {
5567 pkts++;
5568 handlep->packets_read++;
5569 } else if (ret < 0) {
5570 return ret;
5571 }
5572
5573 /*
5574 * Hand this block back to the kernel, and, if we're
5575 * counting blocks that need to be filtered in userland
5576 * after having been filtered by the kernel, count
5577 * the one we've just processed.
5578 */
5579 h.h1_64->tp_status = TP_STATUS_KERNEL;
5580 if (handlep->blocks_to_filter_in_userland > 0) {
5581 handlep->blocks_to_filter_in_userland--;
5582 if (handlep->blocks_to_filter_in_userland == 0) {
5583 /*
5584 * No more blocks need to be filtered
5585 * in userland.
5586 */
5587 handlep->filter_in_userland = 0;
5588 }
5589 }
5590
5591 /* next block */
5592 if (++handle->offset >= handle->cc)
5593 handle->offset = 0;
5594
5595 /* check for break loop condition*/
5596 if (handle->break_loop) {
5597 handle->break_loop = 0;
5598 return PCAP_ERROR_BREAK;
5599 }
5600 }
5601 return pkts;
5602 }
5603
5604 #ifdef HAVE_TPACKET2
5605 static int
5606 pcap_read_linux_mmap_v2(pcap_t *handle, int max_packets, pcap_handler callback,
5607 u_char *user)
5608 {
5609 struct pcap_linux *handlep = handle->priv;
5610 union thdr h;
5611 int pkts = 0;
5612 int ret;
5613
5614 /* wait for frames availability.*/
5615 h.raw = RING_GET_CURRENT_FRAME(handle);
5616 if (h.h2->tp_status == TP_STATUS_KERNEL) {
5617 /*
5618 * The current frame is owned by the kernel; wait for
5619 * a frame to be handed to us.
5620 */
5621 ret = pcap_wait_for_frames_mmap(handle);
5622 if (ret) {
5623 return ret;
5624 }
5625 }
5626
5627 /* non-positive values of max_packets are used to require all
5628 * packets currently available in the ring */
5629 while ((pkts < max_packets) || PACKET_COUNT_IS_UNLIMITED(max_packets)) {
5630 /*
5631 * Get the current ring buffer frame, and break if
5632 * it's still owned by the kernel.
5633 */
5634 h.raw = RING_GET_CURRENT_FRAME(handle);
5635 if (h.h2->tp_status == TP_STATUS_KERNEL)
5636 break;
5637
5638 ret = pcap_handle_packet_mmap(
5639 handle,
5640 callback,
5641 user,
5642 h.raw,
5643 h.h2->tp_len,
5644 h.h2->tp_mac,
5645 h.h2->tp_snaplen,
5646 h.h2->tp_sec,
5647 handle->opt.tstamp_precision == PCAP_TSTAMP_PRECISION_NANO ? h.h2->tp_nsec : h.h2->tp_nsec / 1000,
5648 VLAN_VALID(h.h2, h.h2),
5649 h.h2->tp_vlan_tci,
5650 VLAN_TPID(h.h2, h.h2));
5651 if (ret == 1) {
5652 pkts++;
5653 handlep->packets_read++;
5654 } else if (ret < 0) {
5655 return ret;
5656 }
5657
5658 /*
5659 * Hand this block back to the kernel, and, if we're
5660 * counting blocks that need to be filtered in userland
5661 * after having been filtered by the kernel, count
5662 * the one we've just processed.
5663 */
5664 h.h2->tp_status = TP_STATUS_KERNEL;
5665 if (handlep->blocks_to_filter_in_userland > 0) {
5666 handlep->blocks_to_filter_in_userland--;
5667 if (handlep->blocks_to_filter_in_userland == 0) {
5668 /*
5669 * No more blocks need to be filtered
5670 * in userland.
5671 */
5672 handlep->filter_in_userland = 0;
5673 }
5674 }
5675
5676 /* next block */
5677 if (++handle->offset >= handle->cc)
5678 handle->offset = 0;
5679
5680 /* check for break loop condition*/
5681 if (handle->break_loop) {
5682 handle->break_loop = 0;
5683 return PCAP_ERROR_BREAK;
5684 }
5685 }
5686 return pkts;
5687 }
5688 #endif /* HAVE_TPACKET2 */
5689
5690 #ifdef HAVE_TPACKET3
5691 static int
5692 pcap_read_linux_mmap_v3(pcap_t *handle, int max_packets, pcap_handler callback,
5693 u_char *user)
5694 {
5695 struct pcap_linux *handlep = handle->priv;
5696 union thdr h;
5697 int pkts = 0;
5698 int ret;
5699
5700 again:
5701 if (handlep->current_packet == NULL) {
5702 /* wait for frames availability.*/
5703 h.raw = RING_GET_CURRENT_FRAME(handle);
5704 if (h.h3->hdr.bh1.block_status == TP_STATUS_KERNEL) {
5705 /*
5706 * The current frame is owned by the kernel; wait
5707 * for a frame to be handed to us.
5708 */
5709 ret = pcap_wait_for_frames_mmap(handle);
5710 if (ret) {
5711 return ret;
5712 }
5713 }
5714 }
5715 h.raw = RING_GET_CURRENT_FRAME(handle);
5716 if (h.h3->hdr.bh1.block_status == TP_STATUS_KERNEL) {
5717 if (pkts == 0 && handlep->timeout == 0) {
5718 /* Block until we see a packet. */
5719 goto again;
5720 }
5721 return pkts;
5722 }
5723
5724 /* non-positive values of max_packets are used to require all
5725 * packets currently available in the ring */
5726 while ((pkts < max_packets) || PACKET_COUNT_IS_UNLIMITED(max_packets)) {
5727 int packets_to_read;
5728
5729 if (handlep->current_packet == NULL) {
5730 h.raw = RING_GET_CURRENT_FRAME(handle);
5731 if (h.h3->hdr.bh1.block_status == TP_STATUS_KERNEL)
5732 break;
5733
5734 handlep->current_packet = h.raw + h.h3->hdr.bh1.offset_to_first_pkt;
5735 handlep->packets_left = h.h3->hdr.bh1.num_pkts;
5736 }
5737 packets_to_read = handlep->packets_left;
5738
5739 if (!PACKET_COUNT_IS_UNLIMITED(max_packets) &&
5740 packets_to_read > (max_packets - pkts)) {
5741 /*
5742 * We've been given a maximum number of packets
5743 * to process, and there are more packets in
5744 * this buffer than that. Only process enough
5745 * of them to get us up to that maximum.
5746 */
5747 packets_to_read = max_packets - pkts;
5748 }
5749
5750 while (packets_to_read-- && !handle->break_loop) {
5751 struct tpacket3_hdr* tp3_hdr = (struct tpacket3_hdr*) handlep->current_packet;
5752 ret = pcap_handle_packet_mmap(
5753 handle,
5754 callback,
5755 user,
5756 handlep->current_packet,
5757 tp3_hdr->tp_len,
5758 tp3_hdr->tp_mac,
5759 tp3_hdr->tp_snaplen,
5760 tp3_hdr->tp_sec,
5761 handle->opt.tstamp_precision == PCAP_TSTAMP_PRECISION_NANO ? tp3_hdr->tp_nsec : tp3_hdr->tp_nsec / 1000,
5762 VLAN_VALID(tp3_hdr, &tp3_hdr->hv1),
5763 tp3_hdr->hv1.tp_vlan_tci,
5764 VLAN_TPID(tp3_hdr, &tp3_hdr->hv1));
5765 if (ret == 1) {
5766 pkts++;
5767 handlep->packets_read++;
5768 } else if (ret < 0) {
5769 handlep->current_packet = NULL;
5770 return ret;
5771 }
5772 handlep->current_packet += tp3_hdr->tp_next_offset;
5773 handlep->packets_left--;
5774 }
5775
5776 if (handlep->packets_left <= 0) {
5777 /*
5778 * Hand this block back to the kernel, and, if
5779 * we're counting blocks that need to be
5780 * filtered in userland after having been
5781 * filtered by the kernel, count the one we've
5782 * just processed.
5783 */
5784 h.h3->hdr.bh1.block_status = TP_STATUS_KERNEL;
5785 if (handlep->blocks_to_filter_in_userland > 0) {
5786 handlep->blocks_to_filter_in_userland--;
5787 if (handlep->blocks_to_filter_in_userland == 0) {
5788 /*
5789 * No more blocks need to be filtered
5790 * in userland.
5791 */
5792 handlep->filter_in_userland = 0;
5793 }
5794 }
5795
5796 /* next block */
5797 if (++handle->offset >= handle->cc)
5798 handle->offset = 0;
5799
5800 handlep->current_packet = NULL;
5801 }
5802
5803 /* check for break loop condition*/
5804 if (handle->break_loop) {
5805 handle->break_loop = 0;
5806 return PCAP_ERROR_BREAK;
5807 }
5808 }
5809 if (pkts == 0 && handlep->timeout == 0) {
5810 /* Block until we see a packet. */
5811 goto again;
5812 }
5813 return pkts;
5814 }
5815 #endif /* HAVE_TPACKET3 */
5816
5817 static int
5818 pcap_setfilter_linux_mmap(pcap_t *handle, struct bpf_program *filter)
5819 {
5820 struct pcap_linux *handlep = handle->priv;
5821 int n, offset;
5822 int ret;
5823
5824 /*
5825 * Don't rewrite "ret" instructions; we don't need to, as
5826 * we're not reading packets with recvmsg(), and we don't
5827 * want to, as, by not rewriting them, the kernel can avoid
5828 * copying extra data.
5829 */
5830 ret = pcap_setfilter_linux_common(handle, filter, 1);
5831 if (ret < 0)
5832 return ret;
5833
5834 /*
5835 * If we're filtering in userland, there's nothing to do;
5836 * the new filter will be used for the next packet.
5837 */
5838 if (handlep->filter_in_userland)
5839 return ret;
5840
5841 /*
5842 * We're filtering in the kernel; the packets present in
5843 * all blocks currently in the ring were already filtered
5844 * by the old filter, and so will need to be filtered in
5845 * userland by the new filter.
5846 *
5847 * Get an upper bound for the number of such blocks; first,
5848 * walk the ring backward and count the free blocks.
5849 */
5850 offset = handle->offset;
5851 if (--offset < 0)
5852 offset = handle->cc - 1;
5853 for (n=0; n < handle->cc; ++n) {
5854 if (--offset < 0)
5855 offset = handle->cc - 1;
5856 if (pcap_get_ring_frame_status(handle, offset) != TP_STATUS_KERNEL)
5857 break;
5858 }
5859
5860 /*
5861 * If we found free blocks, decrement the count of free
5862 * blocks by 1, just in case we lost a race with another
5863 * thread of control that was adding a packet while
5864 * we were counting and that had run the filter before
5865 * we changed it.
5866 *
5867 * XXX - could there be more than one block added in
5868 * this fashion?
5869 *
5870 * XXX - is there a way to avoid that race, e.g. somehow
5871 * wait for all packets that passed the old filter to
5872 * be added to the ring?
5873 */
5874 if (n != 0)
5875 n--;
5876
5877 /*
5878 * Set the count of blocks worth of packets to filter
5879 * in userland to the total number of blocks in the
5880 * ring minus the number of free blocks we found, and
5881 * turn on userland filtering. (The count of blocks
5882 * worth of packets to filter in userland is guaranteed
5883 * not to be zero - n, above, couldn't be set to a
5884 * value > handle->cc, and if it were equal to
5885 * handle->cc, it wouldn't be zero, and thus would
5886 * be decremented to handle->cc - 1.)
5887 */
5888 handlep->blocks_to_filter_in_userland = handle->cc - n;
5889 handlep->filter_in_userland = 1;
5890 return ret;
5891 }
5892 #endif /* HAVE_PACKET_RING */
5893
5894 /*
5895 * Return the index of the given device name. Fill ebuf and return
5896 * -1 on failure.
5897 */
5898 static int
5899 iface_get_id(int fd, const char *device, char *ebuf)
5900 {
5901 struct ifreq ifr;
5902
5903 memset(&ifr, 0, sizeof(ifr));
5904 pcap_strlcpy(ifr.ifr_name, device, sizeof(ifr.ifr_name));
5905
5906 if (ioctl(fd, SIOCGIFINDEX, &ifr) == -1) {
5907 pcap_fmt_errmsg_for_errno(ebuf, PCAP_ERRBUF_SIZE,
5908 errno, "SIOCGIFINDEX");
5909 return -1;
5910 }
5911
5912 return ifr.ifr_ifindex;
5913 }
5914
5915 /*
5916 * Bind the socket associated with FD to the given device.
5917 * Return 0 on success or a PCAP_ERROR_ value on a hard error.
5918 */
5919 static int
5920 iface_bind(int fd, int ifindex, char *ebuf, int protocol)
5921 {
5922 struct sockaddr_ll sll;
5923 int ret, err;
5924 socklen_t errlen = sizeof(err);
5925
5926 memset(&sll, 0, sizeof(sll));
5927 sll.sll_family = AF_PACKET;
5928 sll.sll_ifindex = ifindex;
5929 sll.sll_protocol = protocol;
5930
5931 if (bind(fd, (struct sockaddr *) &sll, sizeof(sll)) == -1) {
5932 if (errno == ENETDOWN) {
5933 /*
5934 * Return a "network down" indication, so that
5935 * the application can report that rather than
5936 * saying we had a mysterious failure and
5937 * suggest that they report a problem to the
5938 * libpcap developers.
5939 */
5940 return PCAP_ERROR_IFACE_NOT_UP;
5941 }
5942 if (errno == ENODEV)
5943 ret = PCAP_ERROR_NO_SUCH_DEVICE;
5944 else
5945 ret = PCAP_ERROR;
5946 pcap_fmt_errmsg_for_errno(ebuf, PCAP_ERRBUF_SIZE,
5947 errno, "bind");
5948 return ret;
5949 }
5950
5951 /* Any pending errors, e.g., network is down? */
5952
5953 if (getsockopt(fd, SOL_SOCKET, SO_ERROR, &err, &errlen) == -1) {
5954 pcap_fmt_errmsg_for_errno(ebuf, PCAP_ERRBUF_SIZE,
5955 errno, "getsockopt (SO_ERROR)");
5956 return PCAP_ERROR;
5957 }
5958
5959 if (err == ENETDOWN) {
5960 /*
5961 * Return a "network down" indication, so that
5962 * the application can report that rather than
5963 * saying we had a mysterious failure and
5964 * suggest that they report a problem to the
5965 * libpcap developers.
5966 */
5967 return PCAP_ERROR_IFACE_NOT_UP;
5968 } else if (err > 0) {
5969 pcap_fmt_errmsg_for_errno(ebuf, PCAP_ERRBUF_SIZE,
5970 err, "bind");
5971 return PCAP_ERROR;
5972 }
5973
5974 return 0;
5975 }
5976
5977 #ifdef IW_MODE_MONITOR
5978 /*
5979 * Check whether the device supports the Wireless Extensions.
5980 * Returns 1 if it does, 0 if it doesn't, PCAP_ERROR_NO_SUCH_DEVICE
5981 * if the device doesn't even exist.
5982 */
5983 static int
5984 has_wext(int sock_fd, const char *device, char *ebuf)
5985 {
5986 struct iwreq ireq;
5987 int ret;
5988
5989 if (is_bonding_device(sock_fd, device))
5990 return 0; /* bonding device, so don't even try */
5991
5992 pcap_strlcpy(ireq.ifr_ifrn.ifrn_name, device,
5993 sizeof ireq.ifr_ifrn.ifrn_name);
5994 if (ioctl(sock_fd, SIOCGIWNAME, &ireq) >= 0)
5995 return 1; /* yes */
5996 if (errno == ENODEV)
5997 ret = PCAP_ERROR_NO_SUCH_DEVICE;
5998 else
5999 ret = 0;
6000 pcap_fmt_errmsg_for_errno(ebuf, PCAP_ERRBUF_SIZE, errno,
6001 "%s: SIOCGIWNAME", device);
6002 return ret;
6003 }
6004
6005 /*
6006 * Per me si va ne la citta dolente,
6007 * Per me si va ne l'etterno dolore,
6008 * ...
6009 * Lasciate ogne speranza, voi ch'intrate.
6010 *
6011 * XXX - airmon-ng does special stuff with the Orinoco driver and the
6012 * wlan-ng driver.
6013 */
6014 typedef enum {
6015 MONITOR_WEXT,
6016 MONITOR_HOSTAP,
6017 MONITOR_PRISM,
6018 MONITOR_PRISM54,
6019 MONITOR_ACX100,
6020 MONITOR_RT2500,
6021 MONITOR_RT2570,
6022 MONITOR_RT73,
6023 MONITOR_RTL8XXX
6024 } monitor_type;
6025
6026 /*
6027 * Use the Wireless Extensions, if we have them, to try to turn monitor mode
6028 * on if it's not already on.
6029 *
6030 * Returns 1 on success, 0 if we don't support the Wireless Extensions
6031 * on this device, or a PCAP_ERROR_ value if we do support them but
6032 * we weren't able to turn monitor mode on.
6033 */
6034 static int
6035 enter_rfmon_mode_wext(pcap_t *handle, int sock_fd, const char *device)
6036 {
6037 /*
6038 * XXX - at least some adapters require non-Wireless Extensions
6039 * mechanisms to turn monitor mode on.
6040 *
6041 * Atheros cards might require that a separate "monitor virtual access
6042 * point" be created, with later versions of the madwifi driver.
6043 * airmon-ng does "wlanconfig ath create wlandev {if} wlanmode
6044 * monitor -bssid", which apparently spits out a line "athN"
6045 * where "athN" is the monitor mode device. To leave monitor
6046 * mode, it destroys the monitor mode device.
6047 *
6048 * Some Intel Centrino adapters might require private ioctls to get
6049 * radio headers; the ipw2200 and ipw3945 drivers allow you to
6050 * configure a separate "rtapN" interface to capture in monitor
6051 * mode without preventing the adapter from operating normally.
6052 * (airmon-ng doesn't appear to use that, though.)
6053 *
6054 * It would be Truly Wonderful if mac80211 and nl80211 cleaned this
6055 * up, and if all drivers were converted to mac80211 drivers.
6056 *
6057 * If interface {if} is a mac80211 driver, the file
6058 * /sys/class/net/{if}/phy80211 is a symlink to
6059 * /sys/class/ieee80211/{phydev}, for some {phydev}.
6060 *
6061 * On Fedora 9, with a 2.6.26.3-29 kernel, my Zydas stick, at
6062 * least, has a "wmaster0" device and a "wlan0" device; the
6063 * latter is the one with the IP address. Both show up in
6064 * "tcpdump -D" output. Capturing on the wmaster0 device
6065 * captures with 802.11 headers.
6066 *
6067 * airmon-ng searches through /sys/class/net for devices named
6068 * monN, starting with mon0; as soon as one *doesn't* exist,
6069 * it chooses that as the monitor device name. If the "iw"
6070 * command exists, it does "iw dev {if} interface add {monif}
6071 * type monitor", where {monif} is the monitor device. It
6072 * then (sigh) sleeps .1 second, and then configures the
6073 * device up. Otherwise, if /sys/class/ieee80211/{phydev}/add_iface
6074 * is a file, it writes {mondev}, without a newline, to that file,
6075 * and again (sigh) sleeps .1 second, and then iwconfig's that
6076 * device into monitor mode and configures it up. Otherwise,
6077 * you can't do monitor mode.
6078 *
6079 * All these devices are "glued" together by having the
6080 * /sys/class/net/{device}/phy80211 links pointing to the same
6081 * place, so, given a wmaster, wlan, or mon device, you can
6082 * find the other devices by looking for devices with
6083 * the same phy80211 link.
6084 *
6085 * To turn monitor mode off, delete the monitor interface,
6086 * either with "iw dev {monif} interface del" or by sending
6087 * {monif}, with no NL, down /sys/class/ieee80211/{phydev}/remove_iface
6088 *
6089 * Note: if you try to create a monitor device named "monN", and
6090 * there's already a "monN" device, it fails, as least with
6091 * the netlink interface (which is what iw uses), with a return
6092 * value of -ENFILE. (Return values are negative errnos.) We
6093 * could probably use that to find an unused device.
6094 */
6095 struct pcap_linux *handlep = handle->priv;
6096 int err;
6097 struct iwreq ireq;
6098 struct iw_priv_args *priv;
6099 monitor_type montype;
6100 int i;
6101 __u32 cmd;
6102 struct ifreq ifr;
6103 int oldflags;
6104 int args[2];
6105 int channel;
6106
6107 /*
6108 * Does this device *support* the Wireless Extensions?
6109 */
6110 err = has_wext(sock_fd, device, handle->errbuf);
6111 if (err <= 0)
6112 return err; /* either it doesn't or the device doesn't even exist */
6113 /*
6114 * Start out assuming we have no private extensions to control
6115 * radio metadata.
6116 */
6117 montype = MONITOR_WEXT;
6118 cmd = 0;
6119
6120 /*
6121 * Try to get all the Wireless Extensions private ioctls
6122 * supported by this device.
6123 *
6124 * First, get the size of the buffer we need, by supplying no
6125 * buffer and a length of 0. If the device supports private
6126 * ioctls, it should return E2BIG, with ireq.u.data.length set
6127 * to the length we need. If it doesn't support them, it should
6128 * return EOPNOTSUPP.
6129 */
6130 memset(&ireq, 0, sizeof ireq);
6131 pcap_strlcpy(ireq.ifr_ifrn.ifrn_name, device,
6132 sizeof ireq.ifr_ifrn.ifrn_name);
6133 ireq.u.data.pointer = (void *)args;
6134 ireq.u.data.length = 0;
6135 ireq.u.data.flags = 0;
6136 if (ioctl(sock_fd, SIOCGIWPRIV, &ireq) != -1) {
6137 snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
6138 "%s: SIOCGIWPRIV with a zero-length buffer didn't fail!",
6139 device);
6140 return PCAP_ERROR;
6141 }
6142 if (errno != EOPNOTSUPP) {
6143 /*
6144 * OK, it's not as if there are no private ioctls.
6145 */
6146 if (errno != E2BIG) {
6147 /*
6148 * Failed.
6149 */
6150 pcap_fmt_errmsg_for_errno(handle->errbuf,
6151 PCAP_ERRBUF_SIZE, errno, "%s: SIOCGIWPRIV", device);
6152 return PCAP_ERROR;
6153 }
6154
6155 /*
6156 * OK, try to get the list of private ioctls.
6157 */
6158 priv = malloc(ireq.u.data.length * sizeof (struct iw_priv_args));
6159 if (priv == NULL) {
6160 pcap_fmt_errmsg_for_errno(handle->errbuf,
6161 PCAP_ERRBUF_SIZE, errno, "malloc");
6162 return PCAP_ERROR;
6163 }
6164 ireq.u.data.pointer = (void *)priv;
6165 if (ioctl(sock_fd, SIOCGIWPRIV, &ireq) == -1) {
6166 pcap_fmt_errmsg_for_errno(handle->errbuf,
6167 PCAP_ERRBUF_SIZE, errno, "%s: SIOCGIWPRIV", device);
6168 free(priv);
6169 return PCAP_ERROR;
6170 }
6171
6172 /*
6173 * Look for private ioctls to turn monitor mode on or, if
6174 * monitor mode is on, to set the header type.
6175 */
6176 for (i = 0; i < ireq.u.data.length; i++) {
6177 if (strcmp(priv[i].name, "monitor_type") == 0) {
6178 /*
6179 * Hostap driver, use this one.
6180 * Set monitor mode first.
6181 * You can set it to 0 to get DLT_IEEE80211,
6182 * 1 to get DLT_PRISM, 2 to get
6183 * DLT_IEEE80211_RADIO_AVS, and, with more
6184 * recent versions of the driver, 3 to get
6185 * DLT_IEEE80211_RADIO.
6186 */
6187 if ((priv[i].set_args & IW_PRIV_TYPE_MASK) != IW_PRIV_TYPE_INT)
6188 break;
6189 if (!(priv[i].set_args & IW_PRIV_SIZE_FIXED))
6190 break;
6191 if ((priv[i].set_args & IW_PRIV_SIZE_MASK) != 1)
6192 break;
6193 montype = MONITOR_HOSTAP;
6194 cmd = priv[i].cmd;
6195 break;
6196 }
6197 if (strcmp(priv[i].name, "set_prismhdr") == 0) {
6198 /*
6199 * Prism54 driver, use this one.
6200 * Set monitor mode first.
6201 * You can set it to 2 to get DLT_IEEE80211
6202 * or 3 or get DLT_PRISM.
6203 */
6204 if ((priv[i].set_args & IW_PRIV_TYPE_MASK) != IW_PRIV_TYPE_INT)
6205 break;
6206 if (!(priv[i].set_args & IW_PRIV_SIZE_FIXED))
6207 break;
6208 if ((priv[i].set_args & IW_PRIV_SIZE_MASK) != 1)
6209 break;
6210 montype = MONITOR_PRISM54;
6211 cmd = priv[i].cmd;
6212 break;
6213 }
6214 if (strcmp(priv[i].name, "forceprismheader") == 0) {
6215 /*
6216 * RT2570 driver, use this one.
6217 * Do this after turning monitor mode on.
6218 * You can set it to 1 to get DLT_PRISM or 2
6219 * to get DLT_IEEE80211.
6220 */
6221 if ((priv[i].set_args & IW_PRIV_TYPE_MASK) != IW_PRIV_TYPE_INT)
6222 break;
6223 if (!(priv[i].set_args & IW_PRIV_SIZE_FIXED))
6224 break;
6225 if ((priv[i].set_args & IW_PRIV_SIZE_MASK) != 1)
6226 break;
6227 montype = MONITOR_RT2570;
6228 cmd = priv[i].cmd;
6229 break;
6230 }
6231 if (strcmp(priv[i].name, "forceprism") == 0) {
6232 /*
6233 * RT73 driver, use this one.
6234 * Do this after turning monitor mode on.
6235 * Its argument is a *string*; you can
6236 * set it to "1" to get DLT_PRISM or "2"
6237 * to get DLT_IEEE80211.
6238 */
6239 if ((priv[i].set_args & IW_PRIV_TYPE_MASK) != IW_PRIV_TYPE_CHAR)
6240 break;
6241 if (priv[i].set_args & IW_PRIV_SIZE_FIXED)
6242 break;
6243 montype = MONITOR_RT73;
6244 cmd = priv[i].cmd;
6245 break;
6246 }
6247 if (strcmp(priv[i].name, "prismhdr") == 0) {
6248 /*
6249 * One of the RTL8xxx drivers, use this one.
6250 * It can only be done after monitor mode
6251 * has been turned on. You can set it to 1
6252 * to get DLT_PRISM or 0 to get DLT_IEEE80211.
6253 */
6254 if ((priv[i].set_args & IW_PRIV_TYPE_MASK) != IW_PRIV_TYPE_INT)
6255 break;
6256 if (!(priv[i].set_args & IW_PRIV_SIZE_FIXED))
6257 break;
6258 if ((priv[i].set_args & IW_PRIV_SIZE_MASK) != 1)
6259 break;
6260 montype = MONITOR_RTL8XXX;
6261 cmd = priv[i].cmd;
6262 break;
6263 }
6264 if (strcmp(priv[i].name, "rfmontx") == 0) {
6265 /*
6266 * RT2500 or RT61 driver, use this one.
6267 * It has one one-byte parameter; set
6268 * u.data.length to 1 and u.data.pointer to
6269 * point to the parameter.
6270 * It doesn't itself turn monitor mode on.
6271 * You can set it to 1 to allow transmitting
6272 * in monitor mode(?) and get DLT_IEEE80211,
6273 * or set it to 0 to disallow transmitting in
6274 * monitor mode(?) and get DLT_PRISM.
6275 */
6276 if ((priv[i].set_args & IW_PRIV_TYPE_MASK) != IW_PRIV_TYPE_INT)
6277 break;
6278 if ((priv[i].set_args & IW_PRIV_SIZE_MASK) != 2)
6279 break;
6280 montype = MONITOR_RT2500;
6281 cmd = priv[i].cmd;
6282 break;
6283 }
6284 if (strcmp(priv[i].name, "monitor") == 0) {
6285 /*
6286 * Either ACX100 or hostap, use this one.
6287 * It turns monitor mode on.
6288 * If it takes two arguments, it's ACX100;
6289 * the first argument is 1 for DLT_PRISM
6290 * or 2 for DLT_IEEE80211, and the second
6291 * argument is the channel on which to
6292 * run. If it takes one argument, it's
6293 * HostAP, and the argument is 2 for
6294 * DLT_IEEE80211 and 3 for DLT_PRISM.
6295 *
6296 * If we see this, we don't quit, as this
6297 * might be a version of the hostap driver
6298 * that also supports "monitor_type".
6299 */
6300 if ((priv[i].set_args & IW_PRIV_TYPE_MASK) != IW_PRIV_TYPE_INT)
6301 break;
6302 if (!(priv[i].set_args & IW_PRIV_SIZE_FIXED))
6303 break;
6304 switch (priv[i].set_args & IW_PRIV_SIZE_MASK) {
6305
6306 case 1:
6307 montype = MONITOR_PRISM;
6308 cmd = priv[i].cmd;
6309 break;
6310
6311 case 2:
6312 montype = MONITOR_ACX100;
6313 cmd = priv[i].cmd;
6314 break;
6315
6316 default:
6317 break;
6318 }
6319 }
6320 }
6321 free(priv);
6322 }
6323
6324 /*
6325 * XXX - ipw3945? islism?
6326 */
6327
6328 /*
6329 * Get the old mode.
6330 */
6331 pcap_strlcpy(ireq.ifr_ifrn.ifrn_name, device,
6332 sizeof ireq.ifr_ifrn.ifrn_name);
6333 if (ioctl(sock_fd, SIOCGIWMODE, &ireq) == -1) {
6334 /*
6335 * We probably won't be able to set the mode, either.
6336 */
6337 return PCAP_ERROR_RFMON_NOTSUP;
6338 }
6339
6340 /*
6341 * Is it currently in monitor mode?
6342 */
6343 if (ireq.u.mode == IW_MODE_MONITOR) {
6344 /*
6345 * Yes. Just leave things as they are.
6346 * We don't offer multiple link-layer types, as
6347 * changing the link-layer type out from under
6348 * somebody else capturing in monitor mode would
6349 * be considered rude.
6350 */
6351 return 1;
6352 }
6353 /*
6354 * No. We have to put the adapter into rfmon mode.
6355 */
6356
6357 /*
6358 * If we haven't already done so, arrange to have
6359 * "pcap_close_all()" called when we exit.
6360 */
6361 if (!pcap_do_addexit(handle)) {
6362 /*
6363 * "atexit()" failed; don't put the interface
6364 * in rfmon mode, just give up.
6365 */
6366 return PCAP_ERROR_RFMON_NOTSUP;
6367 }
6368
6369 /*
6370 * Save the old mode.
6371 */
6372 handlep->oldmode = ireq.u.mode;
6373
6374 /*
6375 * Put the adapter in rfmon mode. How we do this depends
6376 * on whether we have a special private ioctl or not.
6377 */
6378 if (montype == MONITOR_PRISM) {
6379 /*
6380 * We have the "monitor" private ioctl, but none of
6381 * the other private ioctls. Use this, and select
6382 * the Prism header.
6383 *
6384 * If it fails, just fall back on SIOCSIWMODE.
6385 */
6386 memset(&ireq, 0, sizeof ireq);
6387 pcap_strlcpy(ireq.ifr_ifrn.ifrn_name, device,
6388 sizeof ireq.ifr_ifrn.ifrn_name);
6389 ireq.u.data.length = 1; /* 1 argument */
6390 args[0] = 3; /* request Prism header */
6391 memcpy(ireq.u.name, args, sizeof (int));
6392 if (ioctl(sock_fd, cmd, &ireq) != -1) {
6393 /*
6394 * Success.
6395 * Note that we have to put the old mode back
6396 * when we close the device.
6397 */
6398 handlep->must_do_on_close |= MUST_CLEAR_RFMON;
6399
6400 /*
6401 * Add this to the list of pcaps to close
6402 * when we exit.
6403 */
6404 pcap_add_to_pcaps_to_close(handle);
6405
6406 return 1;
6407 }
6408
6409 /*
6410 * Failure. Fall back on SIOCSIWMODE.
6411 */
6412 }
6413
6414 /*
6415 * First, take the interface down if it's up; otherwise, we
6416 * might get EBUSY.
6417 */
6418 memset(&ifr, 0, sizeof(ifr));
6419 pcap_strlcpy(ifr.ifr_name, device, sizeof(ifr.ifr_name));
6420 if (ioctl(sock_fd, SIOCGIFFLAGS, &ifr) == -1) {
6421 pcap_fmt_errmsg_for_errno(handle->errbuf, PCAP_ERRBUF_SIZE,
6422 errno, "%s: Can't get flags", device);
6423 return PCAP_ERROR;
6424 }
6425 oldflags = 0;
6426 if (ifr.ifr_flags & IFF_UP) {
6427 oldflags = ifr.ifr_flags;
6428 ifr.ifr_flags &= ~IFF_UP;
6429 if (ioctl(sock_fd, SIOCSIFFLAGS, &ifr) == -1) {
6430 pcap_fmt_errmsg_for_errno(handle->errbuf,
6431 PCAP_ERRBUF_SIZE, errno, "%s: Can't set flags",
6432 device);
6433 return PCAP_ERROR;
6434 }
6435 }
6436
6437 /*
6438 * Then turn monitor mode on.
6439 */
6440 pcap_strlcpy(ireq.ifr_ifrn.ifrn_name, device,
6441 sizeof ireq.ifr_ifrn.ifrn_name);
6442 ireq.u.mode = IW_MODE_MONITOR;
6443 if (ioctl(sock_fd, SIOCSIWMODE, &ireq) == -1) {
6444 /*
6445 * Scientist, you've failed.
6446 * Bring the interface back up if we shut it down.
6447 */
6448 ifr.ifr_flags = oldflags;
6449 if (ioctl(sock_fd, SIOCSIFFLAGS, &ifr) == -1) {
6450 pcap_fmt_errmsg_for_errno(handle->errbuf,
6451 PCAP_ERRBUF_SIZE, errno, "%s: Can't set flags",
6452 device);
6453 return PCAP_ERROR;
6454 }
6455 return PCAP_ERROR_RFMON_NOTSUP;
6456 }
6457
6458 /*
6459 * XXX - airmon-ng does "iwconfig {if} key off" after setting
6460 * monitor mode and setting the channel, and then does
6461 * "iwconfig up".
6462 */
6463
6464 /*
6465 * Now select the appropriate radio header.
6466 */
6467 switch (montype) {
6468
6469 case MONITOR_WEXT:
6470 /*
6471 * We don't have any private ioctl to set the header.
6472 */
6473 break;
6474
6475 case MONITOR_HOSTAP:
6476 /*
6477 * Try to select the radiotap header.
6478 */
6479 memset(&ireq, 0, sizeof ireq);
6480 pcap_strlcpy(ireq.ifr_ifrn.ifrn_name, device,
6481 sizeof ireq.ifr_ifrn.ifrn_name);
6482 args[0] = 3; /* request radiotap header */
6483 memcpy(ireq.u.name, args, sizeof (int));
6484 if (ioctl(sock_fd, cmd, &ireq) != -1)
6485 break; /* success */
6486
6487 /*
6488 * That failed. Try to select the AVS header.
6489 */
6490 memset(&ireq, 0, sizeof ireq);
6491 pcap_strlcpy(ireq.ifr_ifrn.ifrn_name, device,
6492 sizeof ireq.ifr_ifrn.ifrn_name);
6493 args[0] = 2; /* request AVS header */
6494 memcpy(ireq.u.name, args, sizeof (int));
6495 if (ioctl(sock_fd, cmd, &ireq) != -1)
6496 break; /* success */
6497
6498 /*
6499 * That failed. Try to select the Prism header.
6500 */
6501 memset(&ireq, 0, sizeof ireq);
6502 pcap_strlcpy(ireq.ifr_ifrn.ifrn_name, device,
6503 sizeof ireq.ifr_ifrn.ifrn_name);
6504 args[0] = 1; /* request Prism header */
6505 memcpy(ireq.u.name, args, sizeof (int));
6506 ioctl(sock_fd, cmd, &ireq);
6507 break;
6508
6509 case MONITOR_PRISM:
6510 /*
6511 * The private ioctl failed.
6512 */
6513 break;
6514
6515 case MONITOR_PRISM54:
6516 /*
6517 * Select the Prism header.
6518 */
6519 memset(&ireq, 0, sizeof ireq);
6520 pcap_strlcpy(ireq.ifr_ifrn.ifrn_name, device,
6521 sizeof ireq.ifr_ifrn.ifrn_name);
6522 args[0] = 3; /* request Prism header */
6523 memcpy(ireq.u.name, args, sizeof (int));
6524 ioctl(sock_fd, cmd, &ireq);
6525 break;
6526
6527 case MONITOR_ACX100:
6528 /*
6529 * Get the current channel.
6530 */
6531 memset(&ireq, 0, sizeof ireq);
6532 pcap_strlcpy(ireq.ifr_ifrn.ifrn_name, device,
6533 sizeof ireq.ifr_ifrn.ifrn_name);
6534 if (ioctl(sock_fd, SIOCGIWFREQ, &ireq) == -1) {
6535 pcap_fmt_errmsg_for_errno(handle->errbuf,
6536 PCAP_ERRBUF_SIZE, errno, "%s: SIOCGIWFREQ", device);
6537 return PCAP_ERROR;
6538 }
6539 channel = ireq.u.freq.m;
6540
6541 /*
6542 * Select the Prism header, and set the channel to the
6543 * current value.
6544 */
6545 memset(&ireq, 0, sizeof ireq);
6546 pcap_strlcpy(ireq.ifr_ifrn.ifrn_name, device,
6547 sizeof ireq.ifr_ifrn.ifrn_name);
6548 args[0] = 1; /* request Prism header */
6549 args[1] = channel; /* set channel */
6550 memcpy(ireq.u.name, args, 2*sizeof (int));
6551 ioctl(sock_fd, cmd, &ireq);
6552 break;
6553
6554 case MONITOR_RT2500:
6555 /*
6556 * Disallow transmission - that turns on the
6557 * Prism header.
6558 */
6559 memset(&ireq, 0, sizeof ireq);
6560 pcap_strlcpy(ireq.ifr_ifrn.ifrn_name, device,
6561 sizeof ireq.ifr_ifrn.ifrn_name);
6562 args[0] = 0; /* disallow transmitting */
6563 memcpy(ireq.u.name, args, sizeof (int));
6564 ioctl(sock_fd, cmd, &ireq);
6565 break;
6566
6567 case MONITOR_RT2570:
6568 /*
6569 * Force the Prism header.
6570 */
6571 memset(&ireq, 0, sizeof ireq);
6572 pcap_strlcpy(ireq.ifr_ifrn.ifrn_name, device,
6573 sizeof ireq.ifr_ifrn.ifrn_name);
6574 args[0] = 1; /* request Prism header */
6575 memcpy(ireq.u.name, args, sizeof (int));
6576 ioctl(sock_fd, cmd, &ireq);
6577 break;
6578
6579 case MONITOR_RT73:
6580 /*
6581 * Force the Prism header.
6582 */
6583 memset(&ireq, 0, sizeof ireq);
6584 pcap_strlcpy(ireq.ifr_ifrn.ifrn_name, device,
6585 sizeof ireq.ifr_ifrn.ifrn_name);
6586 ireq.u.data.length = 1; /* 1 argument */
6587 ireq.u.data.pointer = "1";
6588 ireq.u.data.flags = 0;
6589 ioctl(sock_fd, cmd, &ireq);
6590 break;
6591
6592 case MONITOR_RTL8XXX:
6593 /*
6594 * Force the Prism header.
6595 */
6596 memset(&ireq, 0, sizeof ireq);
6597 pcap_strlcpy(ireq.ifr_ifrn.ifrn_name, device,
6598 sizeof ireq.ifr_ifrn.ifrn_name);
6599 args[0] = 1; /* request Prism header */
6600 memcpy(ireq.u.name, args, sizeof (int));
6601 ioctl(sock_fd, cmd, &ireq);
6602 break;
6603 }
6604
6605 /*
6606 * Now bring the interface back up if we brought it down.
6607 */
6608 if (oldflags != 0) {
6609 ifr.ifr_flags = oldflags;
6610 if (ioctl(sock_fd, SIOCSIFFLAGS, &ifr) == -1) {
6611 pcap_fmt_errmsg_for_errno(handle->errbuf,
6612 PCAP_ERRBUF_SIZE, errno, "%s: Can't set flags",
6613 device);
6614
6615 /*
6616 * At least try to restore the old mode on the
6617 * interface.
6618 */
6619 if (ioctl(handle->fd, SIOCSIWMODE, &ireq) == -1) {
6620 /*
6621 * Scientist, you've failed.
6622 */
6623 fprintf(stderr,
6624 "Can't restore interface wireless mode (SIOCSIWMODE failed: %s).\n"
6625 "Please adjust manually.\n",
6626 strerror(errno));
6627 }
6628 return PCAP_ERROR;
6629 }
6630 }
6631
6632 /*
6633 * Note that we have to put the old mode back when we
6634 * close the device.
6635 */
6636 handlep->must_do_on_close |= MUST_CLEAR_RFMON;
6637
6638 /*
6639 * Add this to the list of pcaps to close when we exit.
6640 */
6641 pcap_add_to_pcaps_to_close(handle);
6642
6643 return 1;
6644 }
6645 #endif /* IW_MODE_MONITOR */
6646
6647 /*
6648 * Try various mechanisms to enter monitor mode.
6649 */
6650 static int
6651 enter_rfmon_mode(pcap_t *handle, int sock_fd, const char *device)
6652 {
6653 #if defined(HAVE_LIBNL) || defined(IW_MODE_MONITOR)
6654 int ret;
6655 #endif
6656
6657 #ifdef HAVE_LIBNL
6658 ret = enter_rfmon_mode_mac80211(handle, sock_fd, device);
6659 if (ret < 0)
6660 return ret; /* error attempting to do so */
6661 if (ret == 1)
6662 return 1; /* success */
6663 #endif /* HAVE_LIBNL */
6664
6665 #ifdef IW_MODE_MONITOR
6666 ret = enter_rfmon_mode_wext(handle, sock_fd, device);
6667 if (ret < 0)
6668 return ret; /* error attempting to do so */
6669 if (ret == 1)
6670 return 1; /* success */
6671 #endif /* IW_MODE_MONITOR */
6672
6673 /*
6674 * Either none of the mechanisms we know about work or none
6675 * of those mechanisms are available, so we can't do monitor
6676 * mode.
6677 */
6678 return 0;
6679 }
6680
6681 #if defined(HAVE_LINUX_NET_TSTAMP_H) && defined(PACKET_TIMESTAMP)
6682 /*
6683 * Map SOF_TIMESTAMPING_ values to PCAP_TSTAMP_ values.
6684 */
6685 static const struct {
6686 int soft_timestamping_val;
6687 int pcap_tstamp_val;
6688 } sof_ts_type_map[3] = {
6689 { SOF_TIMESTAMPING_SOFTWARE, PCAP_TSTAMP_HOST },
6690 { SOF_TIMESTAMPING_SYS_HARDWARE, PCAP_TSTAMP_ADAPTER },
6691 { SOF_TIMESTAMPING_RAW_HARDWARE, PCAP_TSTAMP_ADAPTER_UNSYNCED }
6692 };
6693 #define NUM_SOF_TIMESTAMPING_TYPES (sizeof sof_ts_type_map / sizeof sof_ts_type_map[0])
6694
6695 /*
6696 * Set the list of time stamping types to include all types.
6697 */
6698 static void
6699 iface_set_all_ts_types(pcap_t *handle)
6700 {
6701 u_int i;
6702
6703 handle->tstamp_type_count = NUM_SOF_TIMESTAMPING_TYPES;
6704 handle->tstamp_type_list = malloc(NUM_SOF_TIMESTAMPING_TYPES * sizeof(u_int));
6705 for (i = 0; i < NUM_SOF_TIMESTAMPING_TYPES; i++)
6706 handle->tstamp_type_list[i] = sof_ts_type_map[i].pcap_tstamp_val;
6707 }
6708
6709 #ifdef ETHTOOL_GET_TS_INFO
6710 /*
6711 * Get a list of time stamping capabilities.
6712 */
6713 static int
6714 iface_ethtool_get_ts_info(const char *device, pcap_t *handle, char *ebuf)
6715 {
6716 int fd;
6717 struct ifreq ifr;
6718 struct ethtool_ts_info info;
6719 int num_ts_types;
6720 u_int i, j;
6721
6722 /*
6723 * This doesn't apply to the "any" device; you can't say "turn on
6724 * hardware time stamping for all devices that exist now and arrange
6725 * that it be turned on for any device that appears in the future",
6726 * and not all devices even necessarily *support* hardware time
6727 * stamping, so don't report any time stamp types.
6728 */
6729 if (strcmp(device, "any") == 0) {
6730 handle->tstamp_type_list = NULL;
6731 return 0;
6732 }
6733
6734 /*
6735 * Create a socket from which to fetch time stamping capabilities.
6736 */
6737 fd = socket(PF_UNIX, SOCK_RAW, 0);
6738 if (fd < 0) {
6739 pcap_fmt_errmsg_for_errno(ebuf, PCAP_ERRBUF_SIZE,
6740 errno, "socket for SIOCETHTOOL(ETHTOOL_GET_TS_INFO)");
6741 return -1;
6742 }
6743
6744 memset(&ifr, 0, sizeof(ifr));
6745 pcap_strlcpy(ifr.ifr_name, device, sizeof(ifr.ifr_name));
6746 memset(&info, 0, sizeof(info));
6747 info.cmd = ETHTOOL_GET_TS_INFO;
6748 ifr.ifr_data = (caddr_t)&info;
6749 if (ioctl(fd, SIOCETHTOOL, &ifr) == -1) {
6750 int save_errno = errno;
6751
6752 close(fd);
6753 switch (save_errno) {
6754
6755 case EOPNOTSUPP:
6756 case EINVAL:
6757 /*
6758 * OK, this OS version or driver doesn't support
6759 * asking for the time stamping types, so let's
6760 * just return all the possible types.
6761 */
6762 iface_set_all_ts_types(handle);
6763 return 0;
6764
6765 case ENODEV:
6766 /*
6767 * OK, no such device.
6768 * The user will find that out when they try to
6769 * activate the device; just return an empty
6770 * list of time stamp types.
6771 */
6772 handle->tstamp_type_list = NULL;
6773 return 0;
6774
6775 default:
6776 /*
6777 * Other error.
6778 */
6779 pcap_fmt_errmsg_for_errno(ebuf, PCAP_ERRBUF_SIZE,
6780 save_errno,
6781 "%s: SIOCETHTOOL(ETHTOOL_GET_TS_INFO) ioctl failed",
6782 device);
6783 return -1;
6784 }
6785 }
6786 close(fd);
6787
6788 /*
6789 * Do we support hardware time stamping of *all* packets?
6790 */
6791 if (!(info.rx_filters & (1 << HWTSTAMP_FILTER_ALL))) {
6792 /*
6793 * No, so don't report any time stamp types.
6794 *
6795 * XXX - some devices either don't report
6796 * HWTSTAMP_FILTER_ALL when they do support it, or
6797 * report HWTSTAMP_FILTER_ALL but map it to only
6798 * time stamping a few PTP packets. See
6799 * http://marc.info/?l=linux-netdev&m=146318183529571&w=2
6800 */
6801 handle->tstamp_type_list = NULL;
6802 return 0;
6803 }
6804
6805 num_ts_types = 0;
6806 for (i = 0; i < NUM_SOF_TIMESTAMPING_TYPES; i++) {
6807 if (info.so_timestamping & sof_ts_type_map[i].soft_timestamping_val)
6808 num_ts_types++;
6809 }
6810 handle->tstamp_type_count = num_ts_types;
6811 if (num_ts_types != 0) {
6812 handle->tstamp_type_list = malloc(num_ts_types * sizeof(u_int));
6813 for (i = 0, j = 0; i < NUM_SOF_TIMESTAMPING_TYPES; i++) {
6814 if (info.so_timestamping & sof_ts_type_map[i].soft_timestamping_val) {
6815 handle->tstamp_type_list[j] = sof_ts_type_map[i].pcap_tstamp_val;
6816 j++;
6817 }
6818 }
6819 } else
6820 handle->tstamp_type_list = NULL;
6821
6822 return 0;
6823 }
6824 #else /* ETHTOOL_GET_TS_INFO */
6825 static int
6826 iface_ethtool_get_ts_info(const char *device, pcap_t *handle, char *ebuf _U_)
6827 {
6828 /*
6829 * This doesn't apply to the "any" device; you can't say "turn on
6830 * hardware time stamping for all devices that exist now and arrange
6831 * that it be turned on for any device that appears in the future",
6832 * and not all devices even necessarily *support* hardware time
6833 * stamping, so don't report any time stamp types.
6834 */
6835 if (strcmp(device, "any") == 0) {
6836 handle->tstamp_type_list = NULL;
6837 return 0;
6838 }
6839
6840 /*
6841 * We don't have an ioctl to use to ask what's supported,
6842 * so say we support everything.
6843 */
6844 iface_set_all_ts_types(handle);
6845 return 0;
6846 }
6847 #endif /* ETHTOOL_GET_TS_INFO */
6848
6849 #endif /* defined(HAVE_LINUX_NET_TSTAMP_H) && defined(PACKET_TIMESTAMP) */
6850
6851 #ifdef HAVE_PACKET_RING
6852 /*
6853 * Find out if we have any form of fragmentation/reassembly offloading.
6854 *
6855 * We do so using SIOCETHTOOL checking for various types of offloading;
6856 * if SIOCETHTOOL isn't defined, or we don't have any #defines for any
6857 * of the types of offloading, there's nothing we can do to check, so
6858 * we just say "no, we don't".
6859 *
6860 * We treat EOPNOTSUPP, EINVAL and, if eperm_ok is true, EPERM as
6861 * indications that the operation isn't supported. We do EPERM
6862 * weirdly because the SIOCETHTOOL code in later kernels 1) doesn't
6863 * support ETHTOOL_GUFO, 2) also doesn't include it in the list
6864 * of ethtool operations that don't require CAP_NET_ADMIN privileges,
6865 * and 3) does the "is this permitted" check before doing the "is
6866 * this even supported" check, so it fails with "this is not permitted"
6867 * rather than "this is not even supported". To work around this
6868 * annoyance, we only treat EPERM as an error for the first feature,
6869 * and assume that they all do the same permission checks, so if the
6870 * first one is allowed all the others are allowed if supported.
6871 */
6872 #if defined(SIOCETHTOOL) && (defined(ETHTOOL_GTSO) || defined(ETHTOOL_GUFO) || defined(ETHTOOL_GGSO) || defined(ETHTOOL_GFLAGS) || defined(ETHTOOL_GGRO))
6873 static int
6874 iface_ethtool_flag_ioctl(pcap_t *handle, int cmd, const char *cmdname,
6875 int eperm_ok)
6876 {
6877 struct ifreq ifr;
6878 struct ethtool_value eval;
6879
6880 memset(&ifr, 0, sizeof(ifr));
6881 pcap_strlcpy(ifr.ifr_name, handle->opt.device, sizeof(ifr.ifr_name));
6882 eval.cmd = cmd;
6883 eval.data = 0;
6884 ifr.ifr_data = (caddr_t)&eval;
6885 if (ioctl(handle->fd, SIOCETHTOOL, &ifr) == -1) {
6886 if (errno == EOPNOTSUPP || errno == EINVAL ||
6887 (errno == EPERM && eperm_ok)) {
6888 /*
6889 * OK, let's just return 0, which, in our
6890 * case, either means "no, what we're asking
6891 * about is not enabled" or "all the flags
6892 * are clear (i.e., nothing is enabled)".
6893 */
6894 return 0;
6895 }
6896 pcap_fmt_errmsg_for_errno(handle->errbuf, PCAP_ERRBUF_SIZE,
6897 errno, "%s: SIOCETHTOOL(%s) ioctl failed",
6898 handle->opt.device, cmdname);
6899 return -1;
6900 }
6901 return eval.data;
6902 }
6903
6904 /*
6905 * XXX - it's annoying that we have to check for offloading at all, but,
6906 * given that we have to, it's still annoying that we have to check for
6907 * particular types of offloading, especially that shiny new types of
6908 * offloading may be added - and, worse, may not be checkable with
6909 * a particular ETHTOOL_ operation; ETHTOOL_GFEATURES would, in
6910 * theory, give those to you, but the actual flags being used are
6911 * opaque (defined in a non-uapi header), and there doesn't seem to
6912 * be any obvious way to ask the kernel what all the offloading flags
6913 * are - at best, you can ask for a set of strings(!) to get *names*
6914 * for various flags. (That whole mechanism appears to have been
6915 * designed for the sole purpose of letting ethtool report flags
6916 * by name and set flags by name, with the names having no semantics
6917 * ethtool understands.)
6918 */
6919 static int
6920 iface_get_offload(pcap_t *handle)
6921 {
6922 int ret;
6923
6924 #ifdef ETHTOOL_GTSO
6925 ret = iface_ethtool_flag_ioctl(handle, ETHTOOL_GTSO, "ETHTOOL_GTSO", 0);
6926 if (ret == -1)
6927 return -1;
6928 if (ret)
6929 return 1; /* TCP segmentation offloading on */
6930 #endif
6931
6932 #ifdef ETHTOOL_GGSO
6933 /*
6934 * XXX - will this cause large unsegmented packets to be
6935 * handed to PF_PACKET sockets on transmission? If not,
6936 * this need not be checked.
6937 */
6938 ret = iface_ethtool_flag_ioctl(handle, ETHTOOL_GGSO, "ETHTOOL_GGSO", 0);
6939 if (ret == -1)
6940 return -1;
6941 if (ret)
6942 return 1; /* generic segmentation offloading on */
6943 #endif
6944
6945 #ifdef ETHTOOL_GFLAGS
6946 ret = iface_ethtool_flag_ioctl(handle, ETHTOOL_GFLAGS, "ETHTOOL_GFLAGS", 0);
6947 if (ret == -1)
6948 return -1;
6949 if (ret & ETH_FLAG_LRO)
6950 return 1; /* large receive offloading on */
6951 #endif
6952
6953 #ifdef ETHTOOL_GGRO
6954 /*
6955 * XXX - will this cause large reassembled packets to be
6956 * handed to PF_PACKET sockets on receipt? If not,
6957 * this need not be checked.
6958 */
6959 ret = iface_ethtool_flag_ioctl(handle, ETHTOOL_GGRO, "ETHTOOL_GGRO", 0);
6960 if (ret == -1)
6961 return -1;
6962 if (ret)
6963 return 1; /* generic (large) receive offloading on */
6964 #endif
6965
6966 #ifdef ETHTOOL_GUFO
6967 /*
6968 * Do this one last, as support for it was removed in later
6969 * kernels, and it fails with EPERM on those kernels rather
6970 * than with EOPNOTSUPP (see explanation in comment for
6971 * iface_ethtool_flag_ioctl()).
6972 */
6973 ret = iface_ethtool_flag_ioctl(handle, ETHTOOL_GUFO, "ETHTOOL_GUFO", 1);
6974 if (ret == -1)
6975 return -1;
6976 if (ret)
6977 return 1; /* UDP fragmentation offloading on */
6978 #endif
6979
6980 return 0;
6981 }
6982 #else /* SIOCETHTOOL */
6983 static int
6984 iface_get_offload(pcap_t *handle _U_)
6985 {
6986 /*
6987 * XXX - do we need to get this information if we don't
6988 * have the ethtool ioctls? If so, how do we do that?
6989 */
6990 return 0;
6991 }
6992 #endif /* SIOCETHTOOL */
6993
6994 #endif /* HAVE_PACKET_RING */
6995
6996 #endif /* HAVE_PF_PACKET_SOCKETS */
6997
6998 static struct dsa_proto {
6999 const char *name;
7000 bpf_u_int32 linktype;
7001 } dsa_protos[] = {
7002 /*
7003 * None is special and indicates that the interface does not have
7004 * any tagging protocol configured, and is therefore a standard
7005 * Ethernet interface.
7006 */
7007 { "none", DLT_EN10MB },
7008 { "brcm", DLT_DSA_TAG_BRCM },
7009 { "brcm-prepend", DLT_DSA_TAG_BRCM_PREPEND },
7010 { "dsa", DLT_DSA_TAG_DSA },
7011 { "edsa", DLT_DSA_TAG_EDSA },
7012 };
7013
7014 static int
7015 iface_dsa_get_proto_info(const char *device, pcap_t *handle)
7016 {
7017 char *pathstr;
7018 unsigned int i;
7019 /*
7020 * Make this significantly smaller than PCAP_ERRBUF_SIZE;
7021 * the tag *shouldn't* have some huge long name, and making
7022 * it smaller keeps newer versions of GCC from whining that
7023 * the error message if we don't support the tag could
7024 * overflow the error message buffer.
7025 */
7026 char buf[128];
7027 ssize_t r;
7028 int fd;
7029
7030 fd = asprintf(&pathstr, "/sys/class/net/%s/dsa/tagging", device);
7031 if (fd < 0) {
7032 pcap_fmt_errmsg_for_errno(handle->errbuf, PCAP_ERRBUF_SIZE,
7033 fd, "asprintf");
7034 return PCAP_ERROR;
7035 }
7036
7037 fd = open(pathstr, O_RDONLY);
7038 free(pathstr);
7039 /*
7040 * This is not fatal, kernel >= 4.20 *might* expose this attribute
7041 */
7042 if (fd < 0)
7043 return 0;
7044
7045 r = read(fd, buf, sizeof(buf) - 1);
7046 if (r <= 0) {
7047 pcap_fmt_errmsg_for_errno(handle->errbuf, PCAP_ERRBUF_SIZE,
7048 errno, "read");
7049 close(fd);
7050 return PCAP_ERROR;
7051 }
7052 close(fd);
7053
7054 /*
7055 * Buffer should be LF terminated.
7056 */
7057 if (buf[r - 1] == '\n')
7058 r--;
7059 buf[r] = '\0';
7060
7061 for (i = 0; i < sizeof(dsa_protos) / sizeof(dsa_protos[0]); i++) {
7062 if (strlen(dsa_protos[i].name) == (size_t)r &&
7063 strcmp(buf, dsa_protos[i].name) == 0) {
7064 handle->linktype = dsa_protos[i].linktype;
7065 switch (dsa_protos[i].linktype) {
7066 case DLT_EN10MB:
7067 return 0;
7068 default:
7069 return 1;
7070 }
7071 }
7072 }
7073
7074 snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
7075 "unsupported DSA tag: %s", buf);
7076
7077 return PCAP_ERROR;
7078 }
7079
7080 /* ===== Functions to interface to the older kernels ================== */
7081
7082 /*
7083 * Try to open a packet socket using the old kernel interface.
7084 * Returns 0 on success and a PCAP_ERROR_ value on an error.
7085 */
7086 static int
7087 activate_old(pcap_t *handle, int is_any_device)
7088 {
7089 struct pcap_linux *handlep = handle->priv;
7090 int err;
7091 int arptype;
7092 struct ifreq ifr;
7093 const char *device = handle->opt.device;
7094 struct utsname utsname;
7095 int mtu;
7096
7097 /*
7098 * PF_INET/SOCK_PACKET sockets must be bound to a device, so we
7099 * can't support the "any" device.
7100 */
7101 if (is_any_device) {
7102 pcap_strlcpy(handle->errbuf, "pcap_activate: The \"any\" device isn't supported on 2.0[.x]-kernel systems",
7103 PCAP_ERRBUF_SIZE);
7104 return PCAP_ERROR;
7105 }
7106
7107 /* Open the socket */
7108 handle->fd = socket(PF_INET, SOCK_PACKET, htons(ETH_P_ALL));
7109 if (handle->fd == -1) {
7110 err = errno;
7111 pcap_fmt_errmsg_for_errno(handle->errbuf, PCAP_ERRBUF_SIZE,
7112 err, "socket");
7113 if (err == EPERM || err == EACCES) {
7114 /*
7115 * You don't have permission to open the
7116 * socket.
7117 */
7118 return PCAP_ERROR_PERM_DENIED;
7119 } else {
7120 /*
7121 * Other error.
7122 */
7123 return PCAP_ERROR;
7124 }
7125 }
7126
7127 /* It worked - we are using the old interface */
7128 handlep->sock_packet = 1;
7129
7130 /* ...which means we get the link-layer header. */
7131 handlep->cooked = 0;
7132
7133 /* Bind to the given device */
7134 if (iface_bind_old(handle->fd, device, handle->errbuf) == -1) {
7135 close(handle->fd);
7136 return PCAP_ERROR;
7137 }
7138
7139 /*
7140 * Try to get the link-layer type.
7141 */
7142 arptype = iface_get_arptype(handle->fd, device, handle->errbuf);
7143 if (arptype < 0) {
7144 close(handle->fd);
7145 return arptype;
7146 }
7147
7148 /*
7149 * Try to find the DLT_ type corresponding to that
7150 * link-layer type.
7151 */
7152 map_arphrd_to_dlt(handle, handle->fd, arptype, device, 0);
7153 if (handle->linktype == -1) {
7154 snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
7155 "unknown arptype %d", arptype);
7156 return PCAP_ERROR;
7157 }
7158
7159 /* Go to promisc mode if requested */
7160
7161 if (handle->opt.promisc) {
7162 memset(&ifr, 0, sizeof(ifr));
7163 pcap_strlcpy(ifr.ifr_name, device, sizeof(ifr.ifr_name));
7164 if (ioctl(handle->fd, SIOCGIFFLAGS, &ifr) == -1) {
7165 pcap_fmt_errmsg_for_errno(handle->errbuf,
7166 PCAP_ERRBUF_SIZE, errno, "SIOCGIFFLAGS");
7167 close(handle->fd);
7168 return PCAP_ERROR;
7169 }
7170 if ((ifr.ifr_flags & IFF_PROMISC) == 0) {
7171 /*
7172 * Promiscuous mode isn't currently on,
7173 * so turn it on, and remember that
7174 * we should turn it off when the
7175 * pcap_t is closed.
7176 */
7177
7178 /*
7179 * If we haven't already done so, arrange
7180 * to have "pcap_close_all()" called when
7181 * we exit.
7182 */
7183 if (!pcap_do_addexit(handle)) {
7184 /*
7185 * "atexit()" failed; don't put
7186 * the interface in promiscuous
7187 * mode, just give up.
7188 */
7189 close(handle->fd);
7190 return PCAP_ERROR;
7191 }
7192
7193 ifr.ifr_flags |= IFF_PROMISC;
7194 if (ioctl(handle->fd, SIOCSIFFLAGS, &ifr) == -1) {
7195 pcap_fmt_errmsg_for_errno(handle->errbuf,
7196 PCAP_ERRBUF_SIZE, errno, "SIOCSIFFLAGS");
7197 return PCAP_ERROR;
7198 }
7199 handlep->must_do_on_close |= MUST_CLEAR_PROMISC;
7200
7201 /*
7202 * Add this to the list of pcaps
7203 * to close when we exit.
7204 */
7205 pcap_add_to_pcaps_to_close(handle);
7206 }
7207 }
7208
7209 /*
7210 * Compute the buffer size.
7211 *
7212 * We're using SOCK_PACKET, so this might be a 2.0[.x]
7213 * kernel, and might require special handling - check.
7214 */
7215 if (uname(&utsname) < 0 ||
7216 strncmp(utsname.release, "2.0", 3) == 0) {
7217 /*
7218 * Either we couldn't find out what kernel release
7219 * this is, or it's a 2.0[.x] kernel.
7220 *
7221 * In the 2.0[.x] kernel, a "recvfrom()" on
7222 * a SOCK_PACKET socket, with MSG_TRUNC set, will
7223 * return the number of bytes read, so if we pass
7224 * a length based on the snapshot length, it'll
7225 * return the number of bytes from the packet
7226 * copied to userland, not the actual length
7227 * of the packet.
7228 *
7229 * This means that, for example, the IP dissector
7230 * in tcpdump will get handed a packet length less
7231 * than the length in the IP header, and will
7232 * complain about "truncated-ip".
7233 *
7234 * So we don't bother trying to copy from the
7235 * kernel only the bytes in which we're interested,
7236 * but instead copy them all, just as the older
7237 * versions of libpcap for Linux did.
7238 *
7239 * The buffer therefore needs to be big enough to
7240 * hold the largest packet we can get from this
7241 * device. Unfortunately, we can't get the MRU
7242 * of the network; we can only get the MTU. The
7243 * MTU may be too small, in which case a packet larger
7244 * than the buffer size will be truncated *and* we
7245 * won't get the actual packet size.
7246 *
7247 * However, if the snapshot length is larger than
7248 * the buffer size based on the MTU, we use the
7249 * snapshot length as the buffer size, instead;
7250 * this means that with a sufficiently large snapshot
7251 * length we won't artificially truncate packets
7252 * to the MTU-based size.
7253 *
7254 * This mess just one of many problems with packet
7255 * capture on 2.0[.x] kernels; you really want a
7256 * 2.2[.x] or later kernel if you want packet capture
7257 * to work well.
7258 */
7259 mtu = iface_get_mtu(handle->fd, device, handle->errbuf);
7260 if (mtu == -1) {
7261 close(handle->fd);
7262 return PCAP_ERROR;
7263 }
7264 handle->bufsize = MAX_LINKHEADER_SIZE + mtu;
7265 if (handle->bufsize < (u_int)handle->snapshot)
7266 handle->bufsize = (u_int)handle->snapshot;
7267 } else {
7268 /*
7269 * This is a 2.2[.x] or later kernel.
7270 *
7271 * We can safely pass "recvfrom()" a byte count
7272 * based on the snapshot length.
7273 *
7274 * XXX - this "should not happen", as 2.2[.x]
7275 * kernels all have PF_PACKET sockets, and there's
7276 * no configuration option to disable them without
7277 * disabling SOCK_PACKET sockets, because
7278 * SOCK_PACKET sockets are implemented in the same
7279 * source file, net/packet/af_packet.c. There *is*
7280 * an option to disable SOCK_PACKET sockets so that
7281 * you only have PF_PACKET sockets, and the kernel
7282 * will log warning messages for code that uses
7283 * "obsolete (PF_INET,SOCK_PACKET)".
7284 */
7285 handle->bufsize = (u_int)handle->snapshot;
7286 }
7287
7288 /*
7289 * Default value for offset to align link-layer payload
7290 * on a 4-byte boundary.
7291 */
7292 handle->offset = 0;
7293
7294 /*
7295 * SOCK_PACKET sockets don't supply information from
7296 * stripped VLAN tags.
7297 */
7298 handlep->vlan_offset = -1; /* unknown */
7299
7300 return 0;
7301 }
7302
7303 /*
7304 * Bind the socket associated with FD to the given device using the
7305 * interface of the old kernels.
7306 */
7307 static int
7308 iface_bind_old(int fd, const char *device, char *ebuf)
7309 {
7310 struct sockaddr saddr;
7311 int err;
7312 socklen_t errlen = sizeof(err);
7313
7314 memset(&saddr, 0, sizeof(saddr));
7315 pcap_strlcpy(saddr.sa_data, device, sizeof(saddr.sa_data));
7316 if (bind(fd, &saddr, sizeof(saddr)) == -1) {
7317 pcap_fmt_errmsg_for_errno(ebuf, PCAP_ERRBUF_SIZE,
7318 errno, "bind");
7319 return -1;
7320 }
7321
7322 /* Any pending errors, e.g., network is down? */
7323
7324 if (getsockopt(fd, SOL_SOCKET, SO_ERROR, &err, &errlen) == -1) {
7325 pcap_fmt_errmsg_for_errno(ebuf, PCAP_ERRBUF_SIZE,
7326 errno, "getsockopt (SO_ERROR)");
7327 return -1;
7328 }
7329
7330 if (err > 0) {
7331 pcap_fmt_errmsg_for_errno(ebuf, PCAP_ERRBUF_SIZE,
7332 err, "bind");
7333 return -1;
7334 }
7335
7336 return 0;
7337 }
7338
7339
7340 /* ===== System calls available on all supported kernels ============== */
7341
7342 /*
7343 * Query the kernel for the MTU of the given interface.
7344 */
7345 static int
7346 iface_get_mtu(int fd, const char *device, char *ebuf)
7347 {
7348 struct ifreq ifr;
7349
7350 if (!device)
7351 return BIGGER_THAN_ALL_MTUS;
7352
7353 memset(&ifr, 0, sizeof(ifr));
7354 pcap_strlcpy(ifr.ifr_name, device, sizeof(ifr.ifr_name));
7355
7356 if (ioctl(fd, SIOCGIFMTU, &ifr) == -1) {
7357 pcap_fmt_errmsg_for_errno(ebuf, PCAP_ERRBUF_SIZE,
7358 errno, "SIOCGIFMTU");
7359 return -1;
7360 }
7361
7362 return ifr.ifr_mtu;
7363 }
7364
7365 /*
7366 * Get the hardware type of the given interface as ARPHRD_xxx constant.
7367 */
7368 static int
7369 iface_get_arptype(int fd, const char *device, char *ebuf)
7370 {
7371 struct ifreq ifr;
7372 int ret;
7373
7374 memset(&ifr, 0, sizeof(ifr));
7375 pcap_strlcpy(ifr.ifr_name, device, sizeof(ifr.ifr_name));
7376
7377 if (ioctl(fd, SIOCGIFHWADDR, &ifr) == -1) {
7378 if (errno == ENODEV) {
7379 /*
7380 * No such device.
7381 */
7382 ret = PCAP_ERROR_NO_SUCH_DEVICE;
7383 } else
7384 ret = PCAP_ERROR;
7385 pcap_fmt_errmsg_for_errno(ebuf, PCAP_ERRBUF_SIZE,
7386 errno, "SIOCGIFHWADDR");
7387 return ret;
7388 }
7389
7390 return ifr.ifr_hwaddr.sa_family;
7391 }
7392
7393 #ifdef SO_ATTACH_FILTER
7394 static int
7395 fix_program(pcap_t *handle, struct sock_fprog *fcode, int is_mmapped)
7396 {
7397 struct pcap_linux *handlep = handle->priv;
7398 size_t prog_size;
7399 register int i;
7400 register struct bpf_insn *p;
7401 struct bpf_insn *f;
7402 int len;
7403
7404 /*
7405 * Make a copy of the filter, and modify that copy if
7406 * necessary.
7407 */
7408 prog_size = sizeof(*handle->fcode.bf_insns) * handle->fcode.bf_len;
7409 len = handle->fcode.bf_len;
7410 f = (struct bpf_insn *)malloc(prog_size);
7411 if (f == NULL) {
7412 pcap_fmt_errmsg_for_errno(handle->errbuf, PCAP_ERRBUF_SIZE,
7413 errno, "malloc");
7414 return -1;
7415 }
7416 memcpy(f, handle->fcode.bf_insns, prog_size);
7417 fcode->len = len;
7418 fcode->filter = (struct sock_filter *) f;
7419
7420 for (i = 0; i < len; ++i) {
7421 p = &f[i];
7422 /*
7423 * What type of instruction is this?
7424 */
7425 switch (BPF_CLASS(p->code)) {
7426
7427 case BPF_RET:
7428 /*
7429 * It's a return instruction; are we capturing
7430 * in memory-mapped mode?
7431 */
7432 if (!is_mmapped) {
7433 /*
7434 * No; is the snapshot length a constant,
7435 * rather than the contents of the
7436 * accumulator?
7437 */
7438 if (BPF_MODE(p->code) == BPF_K) {
7439 /*
7440 * Yes - if the value to be returned,
7441 * i.e. the snapshot length, is
7442 * anything other than 0, make it
7443 * MAXIMUM_SNAPLEN, so that the packet
7444 * is truncated by "recvfrom()",
7445 * not by the filter.
7446 *
7447 * XXX - there's nothing we can
7448 * easily do if it's getting the
7449 * value from the accumulator; we'd
7450 * have to insert code to force
7451 * non-zero values to be
7452 * MAXIMUM_SNAPLEN.
7453 */
7454 if (p->k != 0)
7455 p->k = MAXIMUM_SNAPLEN;
7456 }
7457 }
7458 break;
7459
7460 case BPF_LD:
7461 case BPF_LDX:
7462 /*
7463 * It's a load instruction; is it loading
7464 * from the packet?
7465 */
7466 switch (BPF_MODE(p->code)) {
7467
7468 case BPF_ABS:
7469 case BPF_IND:
7470 case BPF_MSH:
7471 /*
7472 * Yes; are we in cooked mode?
7473 */
7474 if (handlep->cooked) {
7475 /*
7476 * Yes, so we need to fix this
7477 * instruction.
7478 */
7479 if (fix_offset(handle, p) < 0) {
7480 /*
7481 * We failed to do so.
7482 * Return 0, so our caller
7483 * knows to punt to userland.
7484 */
7485 return 0;
7486 }
7487 }
7488 break;
7489 }
7490 break;
7491 }
7492 }
7493 return 1; /* we succeeded */
7494 }
7495
7496 static int
7497 fix_offset(pcap_t *handle, struct bpf_insn *p)
7498 {
7499 if (handle->linktype == DLT_LINUX_SLL2) {
7500 /*
7501 * What's the offset?
7502 */
7503 if (p->k >= SLL2_HDR_LEN) {
7504 /*
7505 * It's within the link-layer payload; that starts
7506 * at an offset of 0, as far as the kernel packet
7507 * filter is concerned, so subtract the length of
7508 * the link-layer header.
7509 */
7510 p->k -= SLL2_HDR_LEN;
7511 } else if (p->k == 0) {
7512 /*
7513 * It's the protocol field; map it to the
7514 * special magic kernel offset for that field.
7515 */
7516 p->k = SKF_AD_OFF + SKF_AD_PROTOCOL;
7517 } else if (p->k == 10) {
7518 /*
7519 * It's the packet type field; map it to the
7520 * special magic kernel offset for that field.
7521 */
7522 p->k = SKF_AD_OFF + SKF_AD_PKTTYPE;
7523 } else if ((bpf_int32)(p->k) > 0) {
7524 /*
7525 * It's within the header, but it's not one of
7526 * those fields; we can't do that in the kernel,
7527 * so punt to userland.
7528 */
7529 return -1;
7530 }
7531 } else {
7532 /*
7533 * What's the offset?
7534 */
7535 if (p->k >= SLL_HDR_LEN) {
7536 /*
7537 * It's within the link-layer payload; that starts
7538 * at an offset of 0, as far as the kernel packet
7539 * filter is concerned, so subtract the length of
7540 * the link-layer header.
7541 */
7542 p->k -= SLL_HDR_LEN;
7543 } else if (p->k == 0) {
7544 /*
7545 * It's the packet type field; map it to the
7546 * special magic kernel offset for that field.
7547 */
7548 p->k = SKF_AD_OFF + SKF_AD_PKTTYPE;
7549 } else if (p->k == 14) {
7550 /*
7551 * It's the protocol field; map it to the
7552 * special magic kernel offset for that field.
7553 */
7554 p->k = SKF_AD_OFF + SKF_AD_PROTOCOL;
7555 } else if ((bpf_int32)(p->k) > 0) {
7556 /*
7557 * It's within the header, but it's not one of
7558 * those fields; we can't do that in the kernel,
7559 * so punt to userland.
7560 */
7561 return -1;
7562 }
7563 }
7564 return 0;
7565 }
7566
7567 static int
7568 set_kernel_filter(pcap_t *handle, struct sock_fprog *fcode)
7569 {
7570 int total_filter_on = 0;
7571 int save_mode;
7572 int ret;
7573 int save_errno;
7574
7575 /*
7576 * The socket filter code doesn't discard all packets queued
7577 * up on the socket when the filter is changed; this means
7578 * that packets that don't match the new filter may show up
7579 * after the new filter is put onto the socket, if those
7580 * packets haven't yet been read.
7581 *
7582 * This means, for example, that if you do a tcpdump capture
7583 * with a filter, the first few packets in the capture might
7584 * be packets that wouldn't have passed the filter.
7585 *
7586 * We therefore discard all packets queued up on the socket
7587 * when setting a kernel filter. (This isn't an issue for
7588 * userland filters, as the userland filtering is done after
7589 * packets are queued up.)
7590 *
7591 * To flush those packets, we put the socket in read-only mode,
7592 * and read packets from the socket until there are no more to
7593 * read.
7594 *
7595 * In order to keep that from being an infinite loop - i.e.,
7596 * to keep more packets from arriving while we're draining
7597 * the queue - we put the "total filter", which is a filter
7598 * that rejects all packets, onto the socket before draining
7599 * the queue.
7600 *
7601 * This code deliberately ignores any errors, so that you may
7602 * get bogus packets if an error occurs, rather than having
7603 * the filtering done in userland even if it could have been
7604 * done in the kernel.
7605 */
7606 if (setsockopt(handle->fd, SOL_SOCKET, SO_ATTACH_FILTER,
7607 &total_fcode, sizeof(total_fcode)) == 0) {
7608 char drain[1];
7609
7610 /*
7611 * Note that we've put the total filter onto the socket.
7612 */
7613 total_filter_on = 1;
7614
7615 /*
7616 * Save the socket's current mode, and put it in
7617 * non-blocking mode; we drain it by reading packets
7618 * until we get an error (which is normally a
7619 * "nothing more to be read" error).
7620 */
7621 save_mode = fcntl(handle->fd, F_GETFL, 0);
7622 if (save_mode == -1) {
7623 pcap_fmt_errmsg_for_errno(handle->errbuf,
7624 PCAP_ERRBUF_SIZE, errno,
7625 "can't get FD flags when changing filter");
7626 return -2;
7627 }
7628 if (fcntl(handle->fd, F_SETFL, save_mode | O_NONBLOCK) < 0) {
7629 pcap_fmt_errmsg_for_errno(handle->errbuf,
7630 PCAP_ERRBUF_SIZE, errno,
7631 "can't set nonblocking mode when changing filter");
7632 return -2;
7633 }
7634 while (recv(handle->fd, &drain, sizeof drain, MSG_TRUNC) >= 0)
7635 ;
7636 save_errno = errno;
7637 if (save_errno != EAGAIN) {
7638 /*
7639 * Fatal error.
7640 *
7641 * If we can't restore the mode or reset the
7642 * kernel filter, there's nothing we can do.
7643 */
7644 (void)fcntl(handle->fd, F_SETFL, save_mode);
7645 (void)reset_kernel_filter(handle);
7646 pcap_fmt_errmsg_for_errno(handle->errbuf,
7647 PCAP_ERRBUF_SIZE, save_errno,
7648 "recv failed when changing filter");
7649 return -2;
7650 }
7651 if (fcntl(handle->fd, F_SETFL, save_mode) == -1) {
7652 pcap_fmt_errmsg_for_errno(handle->errbuf,
7653 PCAP_ERRBUF_SIZE, errno,
7654 "can't restore FD flags when changing filter");
7655 return -2;
7656 }
7657 }
7658
7659 /*
7660 * Now attach the new filter.
7661 */
7662 ret = setsockopt(handle->fd, SOL_SOCKET, SO_ATTACH_FILTER,
7663 fcode, sizeof(*fcode));
7664 if (ret == -1 && total_filter_on) {
7665 /*
7666 * Well, we couldn't set that filter on the socket,
7667 * but we could set the total filter on the socket.
7668 *
7669 * This could, for example, mean that the filter was
7670 * too big to put into the kernel, so we'll have to
7671 * filter in userland; in any case, we'll be doing
7672 * filtering in userland, so we need to remove the
7673 * total filter so we see packets.
7674 */
7675 save_errno = errno;
7676
7677 /*
7678 * If this fails, we're really screwed; we have the
7679 * total filter on the socket, and it won't come off.
7680 * Report it as a fatal error.
7681 */
7682 if (reset_kernel_filter(handle) == -1) {
7683 pcap_fmt_errmsg_for_errno(handle->errbuf,
7684 PCAP_ERRBUF_SIZE, errno,
7685 "can't remove kernel total filter");
7686 return -2; /* fatal error */
7687 }
7688
7689 errno = save_errno;
7690 }
7691 return ret;
7692 }
7693
7694 static int
7695 reset_kernel_filter(pcap_t *handle)
7696 {
7697 int ret;
7698 /*
7699 * setsockopt() barfs unless it get a dummy parameter.
7700 * valgrind whines unless the value is initialized,
7701 * as it has no idea that setsockopt() ignores its
7702 * parameter.
7703 */
7704 int dummy = 0;
7705
7706 ret = setsockopt(handle->fd, SOL_SOCKET, SO_DETACH_FILTER,
7707 &dummy, sizeof(dummy));
7708 /*
7709 * Ignore ENOENT - it means "we don't have a filter", so there
7710 * was no filter to remove, and there's still no filter.
7711 *
7712 * Also ignore ENONET, as a lot of kernel versions had a
7713 * typo where ENONET, rather than ENOENT, was returned.
7714 */
7715 if (ret == -1 && errno != ENOENT && errno != ENONET)
7716 return -1;
7717 return 0;
7718 }
7719 #endif
7720
7721 int
7722 pcap_set_protocol_linux(pcap_t *p, int protocol)
7723 {
7724 if (pcap_check_activated(p))
7725 return (PCAP_ERROR_ACTIVATED);
7726 p->opt.protocol = protocol;
7727 return (0);
7728 }
7729
7730 /*
7731 * Libpcap version string.
7732 */
7733 const char *
7734 pcap_lib_version(void)
7735 {
7736 #ifdef HAVE_PACKET_RING
7737 #if defined(HAVE_TPACKET3)
7738 return (PCAP_VERSION_STRING " (with TPACKET_V3)");
7739 #elif defined(HAVE_TPACKET2)
7740 return (PCAP_VERSION_STRING " (with TPACKET_V2)");
7741 #else
7742 return (PCAP_VERSION_STRING " (with TPACKET_V1)");
7743 #endif
7744 #else
7745 return (PCAP_VERSION_STRING " (without TPACKET)");
7746 #endif
7747 }