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