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