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