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