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