]> The Tcpdump Group git mirrors - libpcap/blob - pcap-linux.c
2.6.0 didn't have "subsystem" links; use "ifindex" instead.
[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; they do not have subdirectories
2011 * and thus have no attributes.
2012 */
2013 if (ent->d_type == DT_REG)
2014 continue;
2015
2016 /*
2017 * Is there an "ifindex" file under that name?
2018 * (We don't care whether it's a directory or
2019 * a symlink; older kernels have directories
2020 * for devices, newer kernels have symlinks to
2021 * directories.)
2022 */
2023 snprintf(subsystem_path, sizeof subsystem_path,
2024 "/sys/class/net/%s/ifindex", ent->d_name);
2025 if (lstat(subsystem_path, &statb) != 0) {
2026 /*
2027 * Stat failed. Either there was an error
2028 * other than ENOENT, and we don't know if
2029 * this is an interface, or it's ENOENT,
2030 * and either some part of "/sys/class/net/{if}"
2031 * disappeared, in which case it probably means
2032 * the interface disappeared, or there's no
2033 * "ifindex" file, which means it's not a
2034 * network interface.
2035 */
2036 continue;
2037 }
2038
2039 /*
2040 * Get the interface name.
2041 */
2042 p = &ent->d_name[0];
2043 q = &name[0];
2044 while (*p != '\0' && isascii(*p) && !isspace(*p)) {
2045 if (*p == ':') {
2046 /*
2047 * This could be the separator between a
2048 * name and an alias number, or it could be
2049 * the separator between a name with no
2050 * alias number and the next field.
2051 *
2052 * If there's a colon after digits, it
2053 * separates the name and the alias number,
2054 * otherwise it separates the name and the
2055 * next field.
2056 */
2057 saveq = q;
2058 while (isascii(*p) && isdigit(*p))
2059 *q++ = *p++;
2060 if (*p != ':') {
2061 /*
2062 * That was the next field,
2063 * not the alias number.
2064 */
2065 q = saveq;
2066 }
2067 break;
2068 } else
2069 *q++ = *p++;
2070 }
2071 *q = '\0';
2072
2073 /*
2074 * Get the flags for this interface, and skip it if
2075 * it's not up.
2076 */
2077 strncpy(ifrflags.ifr_name, name, sizeof(ifrflags.ifr_name));
2078 if (ioctl(fd, SIOCGIFFLAGS, (char *)&ifrflags) < 0) {
2079 if (errno == ENXIO || errno == ENODEV)
2080 continue;
2081 (void)snprintf(errbuf, PCAP_ERRBUF_SIZE,
2082 "SIOCGIFFLAGS: %.*s: %s",
2083 (int)sizeof(ifrflags.ifr_name),
2084 ifrflags.ifr_name,
2085 pcap_strerror(errno));
2086 ret = -1;
2087 break;
2088 }
2089 if (!(ifrflags.ifr_flags & IFF_UP))
2090 continue;
2091
2092 /*
2093 * Add an entry for this interface, with no addresses.
2094 */
2095 if (pcap_add_if(devlistp, name, ifrflags.ifr_flags, NULL,
2096 errbuf) == -1) {
2097 /*
2098 * Failure.
2099 */
2100 ret = -1;
2101 break;
2102 }
2103 }
2104 if (ret != -1) {
2105 /*
2106 * Well, we didn't fail for any other reason; did we
2107 * fail due to an error reading the directory?
2108 */
2109 if (errno != 0) {
2110 (void)snprintf(errbuf, PCAP_ERRBUF_SIZE,
2111 "Error reading /sys/class/net: %s",
2112 pcap_strerror(errno));
2113 ret = -1;
2114 }
2115 }
2116
2117 (void)close(fd);
2118 (void)closedir(sys_class_net_d);
2119 return (ret);
2120 }
2121
2122 /*
2123 * Get from "/proc/net/dev" all interfaces listed there; if they're
2124 * already in the list of interfaces we have, that won't add another
2125 * instance, but if they're not, that'll add them.
2126 *
2127 * See comments from scan_sys_class_net().
2128 */
2129 static int
2130 scan_proc_net_dev(pcap_if_t **devlistp, char *errbuf)
2131 {
2132 FILE *proc_net_f;
2133 int fd;
2134 char linebuf[512];
2135 int linenum;
2136 char *p;
2137 char name[512]; /* XXX - pick a size */
2138 char *q, *saveq;
2139 struct ifreq ifrflags;
2140 int ret = 0;
2141
2142 proc_net_f = fopen("/proc/net/dev", "r");
2143 if (proc_net_f == NULL) {
2144 /*
2145 * Don't fail if it doesn't exist at all.
2146 */
2147 if (errno == ENOENT)
2148 return (0);
2149
2150 /*
2151 * Fail if we got some other error.
2152 */
2153 (void)snprintf(errbuf, PCAP_ERRBUF_SIZE,
2154 "Can't open /proc/net/dev: %s", pcap_strerror(errno));
2155 return (-1);
2156 }
2157
2158 /*
2159 * Create a socket from which to fetch interface information.
2160 */
2161 fd = socket(AF_INET, SOCK_DGRAM, 0);
2162 if (fd < 0) {
2163 (void)snprintf(errbuf, PCAP_ERRBUF_SIZE,
2164 "socket: %s", pcap_strerror(errno));
2165 (void)fclose(proc_net_f);
2166 return (-1);
2167 }
2168
2169 for (linenum = 1;
2170 fgets(linebuf, sizeof linebuf, proc_net_f) != NULL; linenum++) {
2171 /*
2172 * Skip the first two lines - they're headers.
2173 */
2174 if (linenum <= 2)
2175 continue;
2176
2177 p = &linebuf[0];
2178
2179 /*
2180 * Skip leading white space.
2181 */
2182 while (*p != '\0' && isascii(*p) && isspace(*p))
2183 p++;
2184 if (*p == '\0' || *p == '\n')
2185 continue; /* blank line */
2186
2187 /*
2188 * Get the interface name.
2189 */
2190 q = &name[0];
2191 while (*p != '\0' && isascii(*p) && !isspace(*p)) {
2192 if (*p == ':') {
2193 /*
2194 * This could be the separator between a
2195 * name and an alias number, or it could be
2196 * the separator between a name with no
2197 * alias number and the next field.
2198 *
2199 * If there's a colon after digits, it
2200 * separates the name and the alias number,
2201 * otherwise it separates the name and the
2202 * next field.
2203 */
2204 saveq = q;
2205 while (isascii(*p) && isdigit(*p))
2206 *q++ = *p++;
2207 if (*p != ':') {
2208 /*
2209 * That was the next field,
2210 * not the alias number.
2211 */
2212 q = saveq;
2213 }
2214 break;
2215 } else
2216 *q++ = *p++;
2217 }
2218 *q = '\0';
2219
2220 /*
2221 * Get the flags for this interface, and skip it if
2222 * it's not up.
2223 */
2224 strncpy(ifrflags.ifr_name, name, sizeof(ifrflags.ifr_name));
2225 if (ioctl(fd, SIOCGIFFLAGS, (char *)&ifrflags) < 0) {
2226 if (errno == ENXIO)
2227 continue;
2228 (void)snprintf(errbuf, PCAP_ERRBUF_SIZE,
2229 "SIOCGIFFLAGS: %.*s: %s",
2230 (int)sizeof(ifrflags.ifr_name),
2231 ifrflags.ifr_name,
2232 pcap_strerror(errno));
2233 ret = -1;
2234 break;
2235 }
2236 if (!(ifrflags.ifr_flags & IFF_UP))
2237 continue;
2238
2239 /*
2240 * Add an entry for this interface, with no addresses.
2241 */
2242 if (pcap_add_if(devlistp, name, ifrflags.ifr_flags, NULL,
2243 errbuf) == -1) {
2244 /*
2245 * Failure.
2246 */
2247 ret = -1;
2248 break;
2249 }
2250 }
2251 if (ret != -1) {
2252 /*
2253 * Well, we didn't fail for any other reason; did we
2254 * fail due to an error reading the file?
2255 */
2256 if (ferror(proc_net_f)) {
2257 (void)snprintf(errbuf, PCAP_ERRBUF_SIZE,
2258 "Error reading /proc/net/dev: %s",
2259 pcap_strerror(errno));
2260 ret = -1;
2261 }
2262 }
2263
2264 (void)close(fd);
2265 (void)fclose(proc_net_f);
2266 return (ret);
2267 }
2268
2269 /*
2270 * Description string for the "any" device.
2271 */
2272 static const char any_descr[] = "Pseudo-device that captures on all interfaces";
2273
2274 int
2275 pcap_platform_finddevs(pcap_if_t **alldevsp, char *errbuf)
2276 {
2277 int ret;
2278
2279 /*
2280 * Read "/sys/class/net", and add to the list of interfaces all
2281 * interfaces listed there that we don't already have, because,
2282 * on Linux, SIOCGIFCONF reports only interfaces with IPv4 addresses,
2283 * and even getifaddrs() won't return information about
2284 * interfaces with no addresses, so you need to read "/sys/class/net"
2285 * to get the names of the rest of the interfaces.
2286 */
2287 ret = scan_sys_class_net(alldevsp, errbuf);
2288 if (ret == -1)
2289 return (-1); /* failed */
2290 if (ret == 0) {
2291 /*
2292 * No /sys/class/net; try reading /proc/net/dev instead.
2293 */
2294 if (scan_proc_net_dev(alldevsp, errbuf) == -1)
2295 return (-1);
2296 }
2297
2298 /*
2299 * Add the "any" device.
2300 */
2301 if (pcap_add_if(alldevsp, "any", 0, any_descr, errbuf) < 0)
2302 return (-1);
2303
2304 #ifdef HAVE_DAG_API
2305 /*
2306 * Add DAG devices.
2307 */
2308 if (dag_platform_finddevs(alldevsp, errbuf) < 0)
2309 return (-1);
2310 #endif /* HAVE_DAG_API */
2311
2312 #ifdef HAVE_SEPTEL_API
2313 /*
2314 * Add Septel devices.
2315 */
2316 if (septel_platform_finddevs(alldevsp, errbuf) < 0)
2317 return (-1);
2318 #endif /* HAVE_SEPTEL_API */
2319
2320 #ifdef HAVE_SNF_API
2321 if (snf_platform_finddevs(alldevsp, errbuf) < 0)
2322 return (-1);
2323 #endif /* HAVE_SNF_API */
2324
2325 #ifdef PCAP_SUPPORT_BT
2326 /*
2327 * Add Bluetooth devices.
2328 */
2329 if (bt_platform_finddevs(alldevsp, errbuf) < 0)
2330 return (-1);
2331 #endif
2332
2333 #ifdef PCAP_SUPPORT_USB
2334 /*
2335 * Add USB devices.
2336 */
2337 if (usb_platform_finddevs(alldevsp, errbuf) < 0)
2338 return (-1);
2339 #endif
2340
2341 #ifdef PCAP_SUPPORT_NETFILTER
2342 /*
2343 * Add netfilter devices.
2344 */
2345 if (netfilter_platform_finddevs(alldevsp, errbuf) < 0)
2346 return (-1);
2347 #endif
2348
2349 #if PCAP_SUPPORT_CANUSB
2350 if (canusb_platform_finddevs(alldevsp, errbuf) < 0)
2351 return (-1);
2352 #endif
2353
2354 return (0);
2355 }
2356
2357 /*
2358 * Attach the given BPF code to the packet capture device.
2359 */
2360 static int
2361 pcap_setfilter_linux_common(pcap_t *handle, struct bpf_program *filter,
2362 int is_mmapped)
2363 {
2364 #ifdef SO_ATTACH_FILTER
2365 struct sock_fprog fcode;
2366 int can_filter_in_kernel;
2367 int err = 0;
2368 #endif
2369
2370 if (!handle)
2371 return -1;
2372 if (!filter) {
2373 strncpy(handle->errbuf, "setfilter: No filter specified",
2374 PCAP_ERRBUF_SIZE);
2375 return -1;
2376 }
2377
2378 /* Make our private copy of the filter */
2379
2380 if (install_bpf_program(handle, filter) < 0)
2381 /* install_bpf_program() filled in errbuf */
2382 return -1;
2383
2384 /*
2385 * Run user level packet filter by default. Will be overriden if
2386 * installing a kernel filter succeeds.
2387 */
2388 handle->md.use_bpf = 0;
2389
2390 /* Install kernel level filter if possible */
2391
2392 #ifdef SO_ATTACH_FILTER
2393 #ifdef USHRT_MAX
2394 if (handle->fcode.bf_len > USHRT_MAX) {
2395 /*
2396 * fcode.len is an unsigned short for current kernel.
2397 * I have yet to see BPF-Code with that much
2398 * instructions but still it is possible. So for the
2399 * sake of correctness I added this check.
2400 */
2401 fprintf(stderr, "Warning: Filter too complex for kernel\n");
2402 fcode.len = 0;
2403 fcode.filter = NULL;
2404 can_filter_in_kernel = 0;
2405 } else
2406 #endif /* USHRT_MAX */
2407 {
2408 /*
2409 * Oh joy, the Linux kernel uses struct sock_fprog instead
2410 * of struct bpf_program and of course the length field is
2411 * of different size. Pointed out by Sebastian
2412 *
2413 * Oh, and we also need to fix it up so that all "ret"
2414 * instructions with non-zero operands have 65535 as the
2415 * operand if we're not capturing in memory-mapped modee,
2416 * and so that, if we're in cooked mode, all memory-reference
2417 * instructions use special magic offsets in references to
2418 * the link-layer header and assume that the link-layer
2419 * payload begins at 0; "fix_program()" will do that.
2420 */
2421 switch (fix_program(handle, &fcode, is_mmapped)) {
2422
2423 case -1:
2424 default:
2425 /*
2426 * Fatal error; just quit.
2427 * (The "default" case shouldn't happen; we
2428 * return -1 for that reason.)
2429 */
2430 return -1;
2431
2432 case 0:
2433 /*
2434 * The program performed checks that we can't make
2435 * work in the kernel.
2436 */
2437 can_filter_in_kernel = 0;
2438 break;
2439
2440 case 1:
2441 /*
2442 * We have a filter that'll work in the kernel.
2443 */
2444 can_filter_in_kernel = 1;
2445 break;
2446 }
2447 }
2448
2449 /*
2450 * NOTE: at this point, we've set both the "len" and "filter"
2451 * fields of "fcode". As of the 2.6.32.4 kernel, at least,
2452 * those are the only members of the "sock_fprog" structure,
2453 * so we initialize every member of that structure.
2454 *
2455 * If there is anything in "fcode" that is not initialized,
2456 * it is either a field added in a later kernel, or it's
2457 * padding.
2458 *
2459 * If a new field is added, this code needs to be updated
2460 * to set it correctly.
2461 *
2462 * If there are no other fields, then:
2463 *
2464 * if the Linux kernel looks at the padding, it's
2465 * buggy;
2466 *
2467 * if the Linux kernel doesn't look at the padding,
2468 * then if some tool complains that we're passing
2469 * uninitialized data to the kernel, then the tool
2470 * is buggy and needs to understand that it's just
2471 * padding.
2472 */
2473 if (can_filter_in_kernel) {
2474 if ((err = set_kernel_filter(handle, &fcode)) == 0)
2475 {
2476 /* Installation succeded - using kernel filter. */
2477 handle->md.use_bpf = 1;
2478 }
2479 else if (err == -1) /* Non-fatal error */
2480 {
2481 /*
2482 * Print a warning if we weren't able to install
2483 * the filter for a reason other than "this kernel
2484 * isn't configured to support socket filters.
2485 */
2486 if (errno != ENOPROTOOPT && errno != EOPNOTSUPP) {
2487 fprintf(stderr,
2488 "Warning: Kernel filter failed: %s\n",
2489 pcap_strerror(errno));
2490 }
2491 }
2492 }
2493
2494 /*
2495 * If we're not using the kernel filter, get rid of any kernel
2496 * filter that might've been there before, e.g. because the
2497 * previous filter could work in the kernel, or because some other
2498 * code attached a filter to the socket by some means other than
2499 * calling "pcap_setfilter()". Otherwise, the kernel filter may
2500 * filter out packets that would pass the new userland filter.
2501 */
2502 if (!handle->md.use_bpf)
2503 reset_kernel_filter(handle);
2504
2505 /*
2506 * Free up the copy of the filter that was made by "fix_program()".
2507 */
2508 if (fcode.filter != NULL)
2509 free(fcode.filter);
2510
2511 if (err == -2)
2512 /* Fatal error */
2513 return -1;
2514 #endif /* SO_ATTACH_FILTER */
2515
2516 return 0;
2517 }
2518
2519 static int
2520 pcap_setfilter_linux(pcap_t *handle, struct bpf_program *filter)
2521 {
2522 return pcap_setfilter_linux_common(handle, filter, 0);
2523 }
2524
2525
2526 /*
2527 * Set direction flag: Which packets do we accept on a forwarding
2528 * single device? IN, OUT or both?
2529 */
2530 static int
2531 pcap_setdirection_linux(pcap_t *handle, pcap_direction_t d)
2532 {
2533 #ifdef HAVE_PF_PACKET_SOCKETS
2534 if (!handle->md.sock_packet) {
2535 handle->direction = d;
2536 return 0;
2537 }
2538 #endif
2539 /*
2540 * We're not using PF_PACKET sockets, so we can't determine
2541 * the direction of the packet.
2542 */
2543 snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
2544 "Setting direction is not supported on SOCK_PACKET sockets");
2545 return -1;
2546 }
2547
2548 #ifdef HAVE_PF_PACKET_SOCKETS
2549 /*
2550 * Map the PACKET_ value to a LINUX_SLL_ value; we
2551 * want the same numerical value to be used in
2552 * the link-layer header even if the numerical values
2553 * for the PACKET_ #defines change, so that programs
2554 * that look at the packet type field will always be
2555 * able to handle DLT_LINUX_SLL captures.
2556 */
2557 static short int
2558 map_packet_type_to_sll_type(short int sll_pkttype)
2559 {
2560 switch (sll_pkttype) {
2561
2562 case PACKET_HOST:
2563 return htons(LINUX_SLL_HOST);
2564
2565 case PACKET_BROADCAST:
2566 return htons(LINUX_SLL_BROADCAST);
2567
2568 case PACKET_MULTICAST:
2569 return htons(LINUX_SLL_MULTICAST);
2570
2571 case PACKET_OTHERHOST:
2572 return htons(LINUX_SLL_OTHERHOST);
2573
2574 case PACKET_OUTGOING:
2575 return htons(LINUX_SLL_OUTGOING);
2576
2577 default:
2578 return -1;
2579 }
2580 }
2581 #endif
2582
2583 /*
2584 * Linux uses the ARP hardware type to identify the type of an
2585 * interface. pcap uses the DLT_xxx constants for this. This
2586 * function takes a pointer to a "pcap_t", and an ARPHRD_xxx
2587 * constant, as arguments, and sets "handle->linktype" to the
2588 * appropriate DLT_XXX constant and sets "handle->offset" to
2589 * the appropriate value (to make "handle->offset" plus link-layer
2590 * header length be a multiple of 4, so that the link-layer payload
2591 * will be aligned on a 4-byte boundary when capturing packets).
2592 * (If the offset isn't set here, it'll be 0; add code as appropriate
2593 * for cases where it shouldn't be 0.)
2594 *
2595 * If "cooked_ok" is non-zero, we can use DLT_LINUX_SLL and capture
2596 * in cooked mode; otherwise, we can't use cooked mode, so we have
2597 * to pick some type that works in raw mode, or fail.
2598 *
2599 * Sets the link type to -1 if unable to map the type.
2600 */
2601 static void map_arphrd_to_dlt(pcap_t *handle, int arptype, int cooked_ok)
2602 {
2603 switch (arptype) {
2604
2605 case ARPHRD_ETHER:
2606 /*
2607 * This is (presumably) a real Ethernet capture; give it a
2608 * link-layer-type list with DLT_EN10MB and DLT_DOCSIS, so
2609 * that an application can let you choose it, in case you're
2610 * capturing DOCSIS traffic that a Cisco Cable Modem
2611 * Termination System is putting out onto an Ethernet (it
2612 * doesn't put an Ethernet header onto the wire, it puts raw
2613 * DOCSIS frames out on the wire inside the low-level
2614 * Ethernet framing).
2615 *
2616 * XXX - are there any sorts of "fake Ethernet" that have
2617 * ARPHRD_ETHER but that *shouldn't offer DLT_DOCSIS as
2618 * a Cisco CMTS won't put traffic onto it or get traffic
2619 * bridged onto it? ISDN is handled in "activate_new()",
2620 * as we fall back on cooked mode there; are there any
2621 * others?
2622 */
2623 handle->dlt_list = (u_int *) malloc(sizeof(u_int) * 2);
2624 /*
2625 * If that fails, just leave the list empty.
2626 */
2627 if (handle->dlt_list != NULL) {
2628 handle->dlt_list[0] = DLT_EN10MB;
2629 handle->dlt_list[1] = DLT_DOCSIS;
2630 handle->dlt_count = 2;
2631 }
2632 /* FALLTHROUGH */
2633
2634 case ARPHRD_METRICOM:
2635 case ARPHRD_LOOPBACK:
2636 handle->linktype = DLT_EN10MB;
2637 handle->offset = 2;
2638 break;
2639
2640 case ARPHRD_EETHER:
2641 handle->linktype = DLT_EN3MB;
2642 break;
2643
2644 case ARPHRD_AX25:
2645 handle->linktype = DLT_AX25_KISS;
2646 break;
2647
2648 case ARPHRD_PRONET:
2649 handle->linktype = DLT_PRONET;
2650 break;
2651
2652 case ARPHRD_CHAOS:
2653 handle->linktype = DLT_CHAOS;
2654 break;
2655 #ifndef ARPHRD_CAN
2656 #define ARPHRD_CAN 280
2657 #endif
2658 case ARPHRD_CAN:
2659 handle->linktype = DLT_CAN_SOCKETCAN;
2660 break;
2661
2662 #ifndef ARPHRD_IEEE802_TR
2663 #define ARPHRD_IEEE802_TR 800 /* From Linux 2.4 */
2664 #endif
2665 case ARPHRD_IEEE802_TR:
2666 case ARPHRD_IEEE802:
2667 handle->linktype = DLT_IEEE802;
2668 handle->offset = 2;
2669 break;
2670
2671 case ARPHRD_ARCNET:
2672 handle->linktype = DLT_ARCNET_LINUX;
2673 break;
2674
2675 #ifndef ARPHRD_FDDI /* From Linux 2.2.13 */
2676 #define ARPHRD_FDDI 774
2677 #endif
2678 case ARPHRD_FDDI:
2679 handle->linktype = DLT_FDDI;
2680 handle->offset = 3;
2681 break;
2682
2683 #ifndef ARPHRD_ATM /* FIXME: How to #include this? */
2684 #define ARPHRD_ATM 19
2685 #endif
2686 case ARPHRD_ATM:
2687 /*
2688 * The Classical IP implementation in ATM for Linux
2689 * supports both what RFC 1483 calls "LLC Encapsulation",
2690 * in which each packet has an LLC header, possibly
2691 * with a SNAP header as well, prepended to it, and
2692 * what RFC 1483 calls "VC Based Multiplexing", in which
2693 * different virtual circuits carry different network
2694 * layer protocols, and no header is prepended to packets.
2695 *
2696 * They both have an ARPHRD_ type of ARPHRD_ATM, so
2697 * you can't use the ARPHRD_ type to find out whether
2698 * captured packets will have an LLC header, and,
2699 * while there's a socket ioctl to *set* the encapsulation
2700 * type, there's no ioctl to *get* the encapsulation type.
2701 *
2702 * This means that
2703 *
2704 * programs that dissect Linux Classical IP frames
2705 * would have to check for an LLC header and,
2706 * depending on whether they see one or not, dissect
2707 * the frame as LLC-encapsulated or as raw IP (I
2708 * don't know whether there's any traffic other than
2709 * IP that would show up on the socket, or whether
2710 * there's any support for IPv6 in the Linux
2711 * Classical IP code);
2712 *
2713 * filter expressions would have to compile into
2714 * code that checks for an LLC header and does
2715 * the right thing.
2716 *
2717 * Both of those are a nuisance - and, at least on systems
2718 * that support PF_PACKET sockets, we don't have to put
2719 * up with those nuisances; instead, we can just capture
2720 * in cooked mode. That's what we'll do, if we can.
2721 * Otherwise, we'll just fail.
2722 */
2723 if (cooked_ok)
2724 handle->linktype = DLT_LINUX_SLL;
2725 else
2726 handle->linktype = -1;
2727 break;
2728
2729 #ifndef ARPHRD_IEEE80211 /* From Linux 2.4.6 */
2730 #define ARPHRD_IEEE80211 801
2731 #endif
2732 case ARPHRD_IEEE80211:
2733 handle->linktype = DLT_IEEE802_11;
2734 break;
2735
2736 #ifndef ARPHRD_IEEE80211_PRISM /* From Linux 2.4.18 */
2737 #define ARPHRD_IEEE80211_PRISM 802
2738 #endif
2739 case ARPHRD_IEEE80211_PRISM:
2740 handle->linktype = DLT_PRISM_HEADER;
2741 break;
2742
2743 #ifndef ARPHRD_IEEE80211_RADIOTAP /* new */
2744 #define ARPHRD_IEEE80211_RADIOTAP 803
2745 #endif
2746 case ARPHRD_IEEE80211_RADIOTAP:
2747 handle->linktype = DLT_IEEE802_11_RADIO;
2748 break;
2749
2750 case ARPHRD_PPP:
2751 /*
2752 * Some PPP code in the kernel supplies no link-layer
2753 * header whatsoever to PF_PACKET sockets; other PPP
2754 * code supplies PPP link-layer headers ("syncppp.c");
2755 * some PPP code might supply random link-layer
2756 * headers (PPP over ISDN - there's code in Ethereal,
2757 * for example, to cope with PPP-over-ISDN captures
2758 * with which the Ethereal developers have had to cope,
2759 * heuristically trying to determine which of the
2760 * oddball link-layer headers particular packets have).
2761 *
2762 * As such, we just punt, and run all PPP interfaces
2763 * in cooked mode, if we can; otherwise, we just treat
2764 * it as DLT_RAW, for now - if somebody needs to capture,
2765 * on a 2.0[.x] kernel, on PPP devices that supply a
2766 * link-layer header, they'll have to add code here to
2767 * map to the appropriate DLT_ type (possibly adding a
2768 * new DLT_ type, if necessary).
2769 */
2770 if (cooked_ok)
2771 handle->linktype = DLT_LINUX_SLL;
2772 else {
2773 /*
2774 * XXX - handle ISDN types here? We can't fall
2775 * back on cooked sockets, so we'd have to
2776 * figure out from the device name what type of
2777 * link-layer encapsulation it's using, and map
2778 * that to an appropriate DLT_ value, meaning
2779 * we'd map "isdnN" devices to DLT_RAW (they
2780 * supply raw IP packets with no link-layer
2781 * header) and "isdY" devices to a new DLT_I4L_IP
2782 * type that has only an Ethernet packet type as
2783 * a link-layer header.
2784 *
2785 * But sometimes we seem to get random crap
2786 * in the link-layer header when capturing on
2787 * ISDN devices....
2788 */
2789 handle->linktype = DLT_RAW;
2790 }
2791 break;
2792
2793 #ifndef ARPHRD_CISCO
2794 #define ARPHRD_CISCO 513 /* previously ARPHRD_HDLC */
2795 #endif
2796 case ARPHRD_CISCO:
2797 handle->linktype = DLT_C_HDLC;
2798 break;
2799
2800 /* Not sure if this is correct for all tunnels, but it
2801 * works for CIPE */
2802 case ARPHRD_TUNNEL:
2803 #ifndef ARPHRD_SIT
2804 #define ARPHRD_SIT 776 /* From Linux 2.2.13 */
2805 #endif
2806 case ARPHRD_SIT:
2807 case ARPHRD_CSLIP:
2808 case ARPHRD_SLIP6:
2809 case ARPHRD_CSLIP6:
2810 case ARPHRD_ADAPT:
2811 case ARPHRD_SLIP:
2812 #ifndef ARPHRD_RAWHDLC
2813 #define ARPHRD_RAWHDLC 518
2814 #endif
2815 case ARPHRD_RAWHDLC:
2816 #ifndef ARPHRD_DLCI
2817 #define ARPHRD_DLCI 15
2818 #endif
2819 case ARPHRD_DLCI:
2820 /*
2821 * XXX - should some of those be mapped to DLT_LINUX_SLL
2822 * instead? Should we just map all of them to DLT_LINUX_SLL?
2823 */
2824 handle->linktype = DLT_RAW;
2825 break;
2826
2827 #ifndef ARPHRD_FRAD
2828 #define ARPHRD_FRAD 770
2829 #endif
2830 case ARPHRD_FRAD:
2831 handle->linktype = DLT_FRELAY;
2832 break;
2833
2834 case ARPHRD_LOCALTLK:
2835 handle->linktype = DLT_LTALK;
2836 break;
2837
2838 #ifndef ARPHRD_FCPP
2839 #define ARPHRD_FCPP 784
2840 #endif
2841 case ARPHRD_FCPP:
2842 #ifndef ARPHRD_FCAL
2843 #define ARPHRD_FCAL 785
2844 #endif
2845 case ARPHRD_FCAL:
2846 #ifndef ARPHRD_FCPL
2847 #define ARPHRD_FCPL 786
2848 #endif
2849 case ARPHRD_FCPL:
2850 #ifndef ARPHRD_FCFABRIC
2851 #define ARPHRD_FCFABRIC 787
2852 #endif
2853 case ARPHRD_FCFABRIC:
2854 /*
2855 * We assume that those all mean RFC 2625 IP-over-
2856 * Fibre Channel, with the RFC 2625 header at
2857 * the beginning of the packet.
2858 */
2859 handle->linktype = DLT_IP_OVER_FC;
2860 break;
2861
2862 #ifndef ARPHRD_IRDA
2863 #define ARPHRD_IRDA 783
2864 #endif
2865 case ARPHRD_IRDA:
2866 /* Don't expect IP packet out of this interfaces... */
2867 handle->linktype = DLT_LINUX_IRDA;
2868 /* We need to save packet direction for IrDA decoding,
2869 * so let's use "Linux-cooked" mode. Jean II */
2870 //handle->md.cooked = 1;
2871 break;
2872
2873 /* ARPHRD_LAPD is unofficial and randomly allocated, if reallocation
2874 * is needed, please report it to <daniele@orlandi.com> */
2875 #ifndef ARPHRD_LAPD
2876 #define ARPHRD_LAPD 8445
2877 #endif
2878 case ARPHRD_LAPD:
2879 /* Don't expect IP packet out of this interfaces... */
2880 handle->linktype = DLT_LINUX_LAPD;
2881 break;
2882
2883 #ifndef ARPHRD_NONE
2884 #define ARPHRD_NONE 0xFFFE
2885 #endif
2886 case ARPHRD_NONE:
2887 /*
2888 * No link-layer header; packets are just IP
2889 * packets, so use DLT_RAW.
2890 */
2891 handle->linktype = DLT_RAW;
2892 break;
2893
2894 #ifndef ARPHRD_IEEE802154
2895 #define ARPHRD_IEEE802154 804
2896 #endif
2897 case ARPHRD_IEEE802154:
2898 handle->linktype = DLT_IEEE802_15_4_NOFCS;
2899 break;
2900
2901 default:
2902 handle->linktype = -1;
2903 break;
2904 }
2905 }
2906
2907 /* ===== Functions to interface to the newer kernels ================== */
2908
2909 /*
2910 * Try to open a packet socket using the new kernel PF_PACKET interface.
2911 * Returns 1 on success, 0 on an error that means the new interface isn't
2912 * present (so the old SOCK_PACKET interface should be tried), and a
2913 * PCAP_ERROR_ value on an error that means that the old mechanism won't
2914 * work either (so it shouldn't be tried).
2915 */
2916 static int
2917 activate_new(pcap_t *handle)
2918 {
2919 #ifdef HAVE_PF_PACKET_SOCKETS
2920 const char *device = handle->opt.source;
2921 int is_any_device = (strcmp(device, "any") == 0);
2922 int sock_fd = -1, arptype;
2923 #ifdef HAVE_PACKET_AUXDATA
2924 int val;
2925 #endif
2926 int err = 0;
2927 struct packet_mreq mr;
2928
2929 /*
2930 * Open a socket with protocol family packet. If the
2931 * "any" device was specified, we open a SOCK_DGRAM
2932 * socket for the cooked interface, otherwise we first
2933 * try a SOCK_RAW socket for the raw interface.
2934 */
2935 sock_fd = is_any_device ?
2936 socket(PF_PACKET, SOCK_DGRAM, htons(ETH_P_ALL)) :
2937 socket(PF_PACKET, SOCK_RAW, htons(ETH_P_ALL));
2938
2939 if (sock_fd == -1) {
2940 if (errno == EINVAL || errno == EAFNOSUPPORT) {
2941 /*
2942 * We don't support PF_PACKET/SOCK_whatever
2943 * sockets; try the old mechanism.
2944 */
2945 return 0;
2946 }
2947
2948 snprintf(handle->errbuf, PCAP_ERRBUF_SIZE, "socket: %s",
2949 pcap_strerror(errno) );
2950 if (errno == EPERM || errno == EACCES) {
2951 /*
2952 * You don't have permission to open the
2953 * socket.
2954 */
2955 return PCAP_ERROR_PERM_DENIED;
2956 } else {
2957 /*
2958 * Other error.
2959 */
2960 return PCAP_ERROR;
2961 }
2962 }
2963
2964 /* It seems the kernel supports the new interface. */
2965 handle->md.sock_packet = 0;
2966
2967 /*
2968 * Get the interface index of the loopback device.
2969 * If the attempt fails, don't fail, just set the
2970 * "md.lo_ifindex" to -1.
2971 *
2972 * XXX - can there be more than one device that loops
2973 * packets back, i.e. devices other than "lo"? If so,
2974 * we'd need to find them all, and have an array of
2975 * indices for them, and check all of them in
2976 * "pcap_read_packet()".
2977 */
2978 handle->md.lo_ifindex = iface_get_id(sock_fd, "lo", handle->errbuf);
2979
2980 /*
2981 * Default value for offset to align link-layer payload
2982 * on a 4-byte boundary.
2983 */
2984 handle->offset = 0;
2985
2986 /*
2987 * What kind of frames do we have to deal with? Fall back
2988 * to cooked mode if we have an unknown interface type
2989 * or a type we know doesn't work well in raw mode.
2990 */
2991 if (!is_any_device) {
2992 /* Assume for now we don't need cooked mode. */
2993 handle->md.cooked = 0;
2994
2995 if (handle->opt.rfmon) {
2996 /*
2997 * We were asked to turn on monitor mode.
2998 * Do so before we get the link-layer type,
2999 * because entering monitor mode could change
3000 * the link-layer type.
3001 */
3002 err = enter_rfmon_mode(handle, sock_fd, device);
3003 if (err < 0) {
3004 /* Hard failure */
3005 close(sock_fd);
3006 return err;
3007 }
3008 if (err == 0) {
3009 /*
3010 * Nothing worked for turning monitor mode
3011 * on.
3012 */
3013 close(sock_fd);
3014 return PCAP_ERROR_RFMON_NOTSUP;
3015 }
3016
3017 /*
3018 * Either monitor mode has been turned on for
3019 * the device, or we've been given a different
3020 * device to open for monitor mode. If we've
3021 * been given a different device, use it.
3022 */
3023 if (handle->md.mondevice != NULL)
3024 device = handle->md.mondevice;
3025 }
3026 arptype = iface_get_arptype(sock_fd, device, handle->errbuf);
3027 if (arptype < 0) {
3028 close(sock_fd);
3029 return arptype;
3030 }
3031 map_arphrd_to_dlt(handle, arptype, 1);
3032 if (handle->linktype == -1 ||
3033 handle->linktype == DLT_LINUX_SLL ||
3034 handle->linktype == DLT_LINUX_IRDA ||
3035 handle->linktype == DLT_LINUX_LAPD ||
3036 (handle->linktype == DLT_EN10MB &&
3037 (strncmp("isdn", device, 4) == 0 ||
3038 strncmp("isdY", device, 4) == 0))) {
3039 /*
3040 * Unknown interface type (-1), or a
3041 * device we explicitly chose to run
3042 * in cooked mode (e.g., PPP devices),
3043 * or an ISDN device (whose link-layer
3044 * type we can only determine by using
3045 * APIs that may be different on different
3046 * kernels) - reopen in cooked mode.
3047 */
3048 if (close(sock_fd) == -1) {
3049 snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
3050 "close: %s", pcap_strerror(errno));
3051 return PCAP_ERROR;
3052 }
3053 sock_fd = socket(PF_PACKET, SOCK_DGRAM,
3054 htons(ETH_P_ALL));
3055 if (sock_fd == -1) {
3056 snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
3057 "socket: %s", pcap_strerror(errno));
3058 if (errno == EPERM || errno == EACCES) {
3059 /*
3060 * You don't have permission to
3061 * open the socket.
3062 */
3063 return PCAP_ERROR_PERM_DENIED;
3064 } else {
3065 /*
3066 * Other error.
3067 */
3068 return PCAP_ERROR;
3069 }
3070 }
3071 handle->md.cooked = 1;
3072
3073 /*
3074 * Get rid of any link-layer type list
3075 * we allocated - this only supports cooked
3076 * capture.
3077 */
3078 if (handle->dlt_list != NULL) {
3079 free(handle->dlt_list);
3080 handle->dlt_list = NULL;
3081 handle->dlt_count = 0;
3082 }
3083
3084 if (handle->linktype == -1) {
3085 /*
3086 * Warn that we're falling back on
3087 * cooked mode; we may want to
3088 * update "map_arphrd_to_dlt()"
3089 * to handle the new type.
3090 */
3091 snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
3092 "arptype %d not "
3093 "supported by libpcap - "
3094 "falling back to cooked "
3095 "socket",
3096 arptype);
3097 }
3098
3099 /*
3100 * IrDA capture is not a real "cooked" capture,
3101 * it's IrLAP frames, not IP packets. The
3102 * same applies to LAPD capture.
3103 */
3104 if (handle->linktype != DLT_LINUX_IRDA &&
3105 handle->linktype != DLT_LINUX_LAPD)
3106 handle->linktype = DLT_LINUX_SLL;
3107 }
3108
3109 handle->md.ifindex = iface_get_id(sock_fd, device,
3110 handle->errbuf);
3111 if (handle->md.ifindex == -1) {
3112 close(sock_fd);
3113 return PCAP_ERROR;
3114 }
3115
3116 if ((err = iface_bind(sock_fd, handle->md.ifindex,
3117 handle->errbuf)) != 1) {
3118 close(sock_fd);
3119 if (err < 0)
3120 return err;
3121 else
3122 return 0; /* try old mechanism */
3123 }
3124 } else {
3125 /*
3126 * The "any" device.
3127 */
3128 if (handle->opt.rfmon) {
3129 /*
3130 * It doesn't support monitor mode.
3131 */
3132 return PCAP_ERROR_RFMON_NOTSUP;
3133 }
3134
3135 /*
3136 * It uses cooked mode.
3137 */
3138 handle->md.cooked = 1;
3139 handle->linktype = DLT_LINUX_SLL;
3140
3141 /*
3142 * We're not bound to a device.
3143 * For now, we're using this as an indication
3144 * that we can't transmit; stop doing that only
3145 * if we figure out how to transmit in cooked
3146 * mode.
3147 */
3148 handle->md.ifindex = -1;
3149 }
3150
3151 /*
3152 * Select promiscuous mode on if "promisc" is set.
3153 *
3154 * Do not turn allmulti mode on if we don't select
3155 * promiscuous mode - on some devices (e.g., Orinoco
3156 * wireless interfaces), allmulti mode isn't supported
3157 * and the driver implements it by turning promiscuous
3158 * mode on, and that screws up the operation of the
3159 * card as a normal networking interface, and on no
3160 * other platform I know of does starting a non-
3161 * promiscuous capture affect which multicast packets
3162 * are received by the interface.
3163 */
3164
3165 /*
3166 * Hmm, how can we set promiscuous mode on all interfaces?
3167 * I am not sure if that is possible at all. For now, we
3168 * silently ignore attempts to turn promiscuous mode on
3169 * for the "any" device (so you don't have to explicitly
3170 * disable it in programs such as tcpdump).
3171 */
3172
3173 if (!is_any_device && handle->opt.promisc) {
3174 memset(&mr, 0, sizeof(mr));
3175 mr.mr_ifindex = handle->md.ifindex;
3176 mr.mr_type = PACKET_MR_PROMISC;
3177 if (setsockopt(sock_fd, SOL_PACKET, PACKET_ADD_MEMBERSHIP,
3178 &mr, sizeof(mr)) == -1) {
3179 snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
3180 "setsockopt: %s", pcap_strerror(errno));
3181 close(sock_fd);
3182 return PCAP_ERROR;
3183 }
3184 }
3185
3186 /* Enable auxillary data if supported and reserve room for
3187 * reconstructing VLAN headers. */
3188 #ifdef HAVE_PACKET_AUXDATA
3189 val = 1;
3190 if (setsockopt(sock_fd, SOL_PACKET, PACKET_AUXDATA, &val,
3191 sizeof(val)) == -1 && errno != ENOPROTOOPT) {
3192 snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
3193 "setsockopt: %s", pcap_strerror(errno));
3194 close(sock_fd);
3195 return PCAP_ERROR;
3196 }
3197 handle->offset += VLAN_TAG_LEN;
3198 #endif /* HAVE_PACKET_AUXDATA */
3199
3200 /*
3201 * This is a 2.2[.x] or later kernel (we know that
3202 * because we're not using a SOCK_PACKET socket -
3203 * PF_PACKET is supported only in 2.2 and later
3204 * kernels).
3205 *
3206 * We can safely pass "recvfrom()" a byte count
3207 * based on the snapshot length.
3208 *
3209 * If we're in cooked mode, make the snapshot length
3210 * large enough to hold a "cooked mode" header plus
3211 * 1 byte of packet data (so we don't pass a byte
3212 * count of 0 to "recvfrom()").
3213 */
3214 if (handle->md.cooked) {
3215 if (handle->snapshot < SLL_HDR_LEN + 1)
3216 handle->snapshot = SLL_HDR_LEN + 1;
3217 }
3218 handle->bufsize = handle->snapshot;
3219
3220 /*
3221 * Set the offset at which to insert VLAN tags.
3222 */
3223 switch (handle->linktype) {
3224
3225 case DLT_EN10MB:
3226 handle->md.vlan_offset = 2 * ETH_ALEN;
3227 break;
3228
3229 case DLT_LINUX_SLL:
3230 handle->md.vlan_offset = 14;
3231 break;
3232
3233 default:
3234 handle->md.vlan_offset = -1; /* unknown */
3235 break;
3236 }
3237
3238 /* Save the socket FD in the pcap structure */
3239 handle->fd = sock_fd;
3240
3241 return 1;
3242 #else
3243 strncpy(ebuf,
3244 "New packet capturing interface not supported by build "
3245 "environment", PCAP_ERRBUF_SIZE);
3246 return 0;
3247 #endif
3248 }
3249
3250 #ifdef HAVE_PACKET_RING
3251 /*
3252 * Attempt to activate with memory-mapped access.
3253 *
3254 * On success, returns 1, and sets *status to 0 if there are no warnings
3255 * or to a PCAP_WARNING_ code if there is a warning.
3256 *
3257 * On failure due to lack of support for memory-mapped capture, returns
3258 * 0.
3259 *
3260 * On error, returns -1, and sets *status to the appropriate error code;
3261 * if that is PCAP_ERROR, sets handle->errbuf to the appropriate message.
3262 */
3263 static int
3264 activate_mmap(pcap_t *handle, int *status)
3265 {
3266 int ret;
3267
3268 /*
3269 * Attempt to allocate a buffer to hold the contents of one
3270 * packet, for use by the oneshot callback.
3271 */
3272 handle->md.oneshot_buffer = malloc(handle->snapshot);
3273 if (handle->md.oneshot_buffer == NULL) {
3274 snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
3275 "can't allocate oneshot buffer: %s",
3276 pcap_strerror(errno));
3277 *status = PCAP_ERROR;
3278 return -1;
3279 }
3280
3281 if (handle->opt.buffer_size == 0) {
3282 /* by default request 2M for the ring buffer */
3283 handle->opt.buffer_size = 2*1024*1024;
3284 }
3285 ret = prepare_tpacket_socket(handle);
3286 if (ret == -1) {
3287 free(handle->md.oneshot_buffer);
3288 *status = PCAP_ERROR;
3289 return ret;
3290 }
3291 ret = create_ring(handle, status);
3292 if (ret == 0) {
3293 /*
3294 * We don't support memory-mapped capture; our caller
3295 * will fall back on reading from the socket.
3296 */
3297 free(handle->md.oneshot_buffer);
3298 return 0;
3299 }
3300 if (ret == -1) {
3301 /*
3302 * Error attempting to enable memory-mapped capture;
3303 * fail. create_ring() has set *status.
3304 */
3305 free(handle->md.oneshot_buffer);
3306 return -1;
3307 }
3308
3309 /*
3310 * Success. *status has been set either to 0 if there are no
3311 * warnings or to a PCAP_WARNING_ value if there is a warning.
3312 *
3313 * Override some defaults and inherit the other fields from
3314 * activate_new.
3315 * handle->offset is used to get the current position into the rx ring.
3316 * handle->cc is used to store the ring size.
3317 */
3318 handle->read_op = pcap_read_linux_mmap;
3319 handle->cleanup_op = pcap_cleanup_linux_mmap;
3320 handle->setfilter_op = pcap_setfilter_linux_mmap;
3321 handle->setnonblock_op = pcap_setnonblock_mmap;
3322 handle->getnonblock_op = pcap_getnonblock_mmap;
3323 handle->oneshot_callback = pcap_oneshot_mmap;
3324 handle->selectable_fd = handle->fd;
3325 return 1;
3326 }
3327 #else /* HAVE_PACKET_RING */
3328 static int
3329 activate_mmap(pcap_t *handle _U_, int *status _U_)
3330 {
3331 return 0;
3332 }
3333 #endif /* HAVE_PACKET_RING */
3334
3335 #ifdef HAVE_PACKET_RING
3336 /*
3337 * Attempt to set the socket to version 2 of the memory-mapped header.
3338 * Return 1 if we succeed or if we fail because version 2 isn't
3339 * supported; return -1 on any other error, and set handle->errbuf.
3340 */
3341 static int
3342 prepare_tpacket_socket(pcap_t *handle)
3343 {
3344 #ifdef HAVE_TPACKET2
3345 socklen_t len;
3346 int val;
3347 #endif
3348
3349 handle->md.tp_version = TPACKET_V1;
3350 handle->md.tp_hdrlen = sizeof(struct tpacket_hdr);
3351
3352 #ifdef HAVE_TPACKET2
3353 /* Probe whether kernel supports TPACKET_V2 */
3354 val = TPACKET_V2;
3355 len = sizeof(val);
3356 if (getsockopt(handle->fd, SOL_PACKET, PACKET_HDRLEN, &val, &len) < 0) {
3357 if (errno == ENOPROTOOPT)
3358 return 1; /* no - just drive on */
3359
3360 /* Yes - treat as a failure. */
3361 snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
3362 "can't get TPACKET_V2 header len on packet socket: %s",
3363 pcap_strerror(errno));
3364 return -1;
3365 }
3366 handle->md.tp_hdrlen = val;
3367
3368 val = TPACKET_V2;
3369 if (setsockopt(handle->fd, SOL_PACKET, PACKET_VERSION, &val,
3370 sizeof(val)) < 0) {
3371 snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
3372 "can't activate TPACKET_V2 on packet socket: %s",
3373 pcap_strerror(errno));
3374 return -1;
3375 }
3376 handle->md.tp_version = TPACKET_V2;
3377
3378 /* Reserve space for VLAN tag reconstruction */
3379 val = VLAN_TAG_LEN;
3380 if (setsockopt(handle->fd, SOL_PACKET, PACKET_RESERVE, &val,
3381 sizeof(val)) < 0) {
3382 snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
3383 "can't set up reserve on packet socket: %s",
3384 pcap_strerror(errno));
3385 return -1;
3386 }
3387
3388 #endif /* HAVE_TPACKET2 */
3389 return 1;
3390 }
3391
3392 /*
3393 * Attempt to set up memory-mapped access.
3394 *
3395 * On success, returns 1, and sets *status to 0 if there are no warnings
3396 * or to a PCAP_WARNING_ code if there is a warning.
3397 *
3398 * On failure due to lack of support for memory-mapped capture, returns
3399 * 0.
3400 *
3401 * On error, returns -1, and sets *status to the appropriate error code;
3402 * if that is PCAP_ERROR, sets handle->errbuf to the appropriate message.
3403 */
3404 static int
3405 create_ring(pcap_t *handle, int *status)
3406 {
3407 unsigned i, j, frames_per_block;
3408 struct tpacket_req req;
3409 socklen_t len;
3410 unsigned int sk_type, tp_reserve, maclen, tp_hdrlen, netoff, macoff;
3411 unsigned int frame_size;
3412
3413 /*
3414 * Start out assuming no warnings or errors.
3415 */
3416 *status = 0;
3417
3418 /* Note that with large snapshot length (say 64K, which is the default
3419 * for recent versions of tcpdump, the value that "-s 0" has given
3420 * for a long time with tcpdump, and the default in Wireshark/TShark),
3421 * if we use the snapshot length to calculate the frame length,
3422 * only a few frames will be available in the ring even with pretty
3423 * large ring size (and a lot of memory will be unused).
3424 *
3425 * Ideally, we should choose a frame length based on the
3426 * minimum of the specified snapshot length and the maximum
3427 * packet size. That's not as easy as it sounds; consider, for
3428 * example, an 802.11 interface in monitor mode, where the
3429 * frame would include a radiotap header, where the maximum
3430 * radiotap header length is device-dependent.
3431 *
3432 * So, for now, we just do this for Ethernet devices, where
3433 * there's no metadata header, and the link-layer header is
3434 * fixed length. We can get the maximum packet size by
3435 * adding 18, the Ethernet header length plus the CRC length
3436 * (just in case we happen to get the CRC in the packet), to
3437 * the MTU of the interface; we fetch the MTU in the hopes
3438 * that it reflects support for jumbo frames. (Even if the
3439 * interface is just being used for passive snooping, the driver
3440 * might set the size of buffers in the receive ring based on
3441 * the MTU, so that the MTU limits the maximum size of packets
3442 * that we can receive.)
3443 *
3444 * We don't do that if segmentation/fragmentation or receive
3445 * offload are enabled, so we don't get rudely surprised by
3446 * "packets" bigger than the MTU. */
3447 frame_size = handle->snapshot;
3448 if (handle->linktype == DLT_EN10MB) {
3449 int mtu;
3450 int offload;
3451
3452 offload = iface_get_offload(handle);
3453 if (offload == -1) {
3454 *status = PCAP_ERROR;
3455 return -1;
3456 }
3457 if (!offload) {
3458 mtu = iface_get_mtu(handle->fd, handle->opt.source,
3459 handle->errbuf);
3460 if (mtu == -1) {
3461 *status = PCAP_ERROR;
3462 return -1;
3463 }
3464 if (frame_size > mtu + 18)
3465 frame_size = mtu + 18;
3466 }
3467 }
3468
3469 /* NOTE: calculus matching those in tpacket_rcv()
3470 * in linux-2.6/net/packet/af_packet.c
3471 */
3472 len = sizeof(sk_type);
3473 if (getsockopt(handle->fd, SOL_SOCKET, SO_TYPE, &sk_type, &len) < 0) {
3474 snprintf(handle->errbuf, PCAP_ERRBUF_SIZE, "getsockopt: %s", pcap_strerror(errno));
3475 *status = PCAP_ERROR;
3476 return -1;
3477 }
3478 #ifdef PACKET_RESERVE
3479 len = sizeof(tp_reserve);
3480 if (getsockopt(handle->fd, SOL_PACKET, PACKET_RESERVE, &tp_reserve, &len) < 0) {
3481 if (errno != ENOPROTOOPT) {
3482 /*
3483 * ENOPROTOOPT means "kernel doesn't support
3484 * PACKET_RESERVE", in which case we fall back
3485 * as best we can.
3486 */
3487 snprintf(handle->errbuf, PCAP_ERRBUF_SIZE, "getsockopt: %s", pcap_strerror(errno));
3488 *status = PCAP_ERROR;
3489 return -1;
3490 }
3491 tp_reserve = 0; /* older kernel, reserve not supported */
3492 }
3493 #else
3494 tp_reserve = 0; /* older kernel, reserve not supported */
3495 #endif
3496 maclen = (sk_type == SOCK_DGRAM) ? 0 : MAX_LINKHEADER_SIZE;
3497 /* XXX: in the kernel maclen is calculated from
3498 * LL_ALLOCATED_SPACE(dev) and vnet_hdr.hdr_len
3499 * in: packet_snd() in linux-2.6/net/packet/af_packet.c
3500 * then packet_alloc_skb() in linux-2.6/net/packet/af_packet.c
3501 * then sock_alloc_send_pskb() in linux-2.6/net/core/sock.c
3502 * but I see no way to get those sizes in userspace,
3503 * like for instance with an ifreq ioctl();
3504 * the best thing I've found so far is MAX_HEADER in the kernel
3505 * part of linux-2.6/include/linux/netdevice.h
3506 * which goes up to 128+48=176; since pcap-linux.c defines
3507 * a MAX_LINKHEADER_SIZE of 256 which is greater than that,
3508 * let's use it.. maybe is it even large enough to directly
3509 * replace macoff..
3510 */
3511 tp_hdrlen = TPACKET_ALIGN(handle->md.tp_hdrlen) + sizeof(struct sockaddr_ll) ;
3512 netoff = TPACKET_ALIGN(tp_hdrlen + (maclen < 16 ? 16 : maclen)) + tp_reserve;
3513 /* NOTE: AFAICS tp_reserve may break the TPACKET_ALIGN of
3514 * netoff, which contradicts
3515 * linux-2.6/Documentation/networking/packet_mmap.txt
3516 * documenting that:
3517 * "- Gap, chosen so that packet data (Start+tp_net)
3518 * aligns to TPACKET_ALIGNMENT=16"
3519 */
3520 /* NOTE: in linux-2.6/include/linux/skbuff.h:
3521 * "CPUs often take a performance hit
3522 * when accessing unaligned memory locations"
3523 */
3524 macoff = netoff - maclen;
3525 req.tp_frame_size = TPACKET_ALIGN(macoff + frame_size);
3526 req.tp_frame_nr = handle->opt.buffer_size/req.tp_frame_size;
3527
3528 /* compute the minumum block size that will handle this frame.
3529 * The block has to be page size aligned.
3530 * The max block size allowed by the kernel is arch-dependent and
3531 * it's not explicitly checked here. */
3532 req.tp_block_size = getpagesize();
3533 while (req.tp_block_size < req.tp_frame_size)
3534 req.tp_block_size <<= 1;
3535
3536 frames_per_block = req.tp_block_size/req.tp_frame_size;
3537
3538 /*
3539 * PACKET_TIMESTAMP was added after linux/net_tstamp.h was,
3540 * so we check for PACKET_TIMESTAMP. We check for
3541 * linux/net_tstamp.h just in case a system somehow has
3542 * PACKET_TIMESTAMP but not linux/net_tstamp.h; that might
3543 * be unnecessary.
3544 *
3545 * SIOCSHWTSTAMP was introduced in the patch that introduced
3546 * linux/net_tstamp.h, so we don't bother checking whether
3547 * SIOCSHWTSTAMP is defined (if your Linux system has
3548 * linux/net_tstamp.h but doesn't define SIOCSHWTSTAMP, your
3549 * Linux system is badly broken).
3550 */
3551 #if defined(HAVE_LINUX_NET_TSTAMP_H) && defined(PACKET_TIMESTAMP)
3552 /*
3553 * If we were told to do so, ask the kernel and the driver
3554 * to use hardware timestamps.
3555 *
3556 * Hardware timestamps are only supported with mmapped
3557 * captures.
3558 */
3559 if (handle->opt.tstamp_type == PCAP_TSTAMP_ADAPTER ||
3560 handle->opt.tstamp_type == PCAP_TSTAMP_ADAPTER_UNSYNCED) {
3561 struct hwtstamp_config hwconfig;
3562 struct ifreq ifr;
3563 int timesource;
3564
3565 /*
3566 * Ask for hardware time stamps on all packets,
3567 * including transmitted packets.
3568 */
3569 memset(&hwconfig, 0, sizeof(hwconfig));
3570 hwconfig.tx_type = HWTSTAMP_TX_ON;
3571 hwconfig.rx_filter = HWTSTAMP_FILTER_ALL;
3572
3573 memset(&ifr, 0, sizeof(ifr));
3574 strcpy(ifr.ifr_name, handle->opt.source);
3575 ifr.ifr_data = (void *)&hwconfig;
3576
3577 if (ioctl(handle->fd, SIOCSHWTSTAMP, &ifr) < 0) {
3578 switch (errno) {
3579
3580 case EPERM:
3581 /*
3582 * Treat this as an error, as the
3583 * user should try to run this
3584 * with the appropriate privileges -
3585 * and, if they can't, shouldn't
3586 * try requesting hardware time stamps.
3587 */
3588 *status = PCAP_ERROR_PERM_DENIED;
3589 return -1;
3590
3591 case EOPNOTSUPP:
3592 /*
3593 * Treat this as a warning, as the
3594 * only way to fix the warning is to
3595 * get an adapter that supports hardware
3596 * time stamps. We'll just fall back
3597 * on the standard host time stamps.
3598 */
3599 *status = PCAP_WARNING_TSTAMP_TYPE_NOTSUP;
3600 break;
3601
3602 default:
3603 snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
3604 "SIOCSHWTSTAMP failed: %s",
3605 pcap_strerror(errno));
3606 *status = PCAP_ERROR;
3607 return -1;
3608 }
3609 } else {
3610 /*
3611 * Well, that worked. Now specify the type of
3612 * hardware time stamp we want for this
3613 * socket.
3614 */
3615 if (handle->opt.tstamp_type == PCAP_TSTAMP_ADAPTER) {
3616 /*
3617 * Hardware timestamp, synchronized
3618 * with the system clock.
3619 */
3620 timesource = SOF_TIMESTAMPING_SYS_HARDWARE;
3621 } else {
3622 /*
3623 * PCAP_TSTAMP_ADAPTER_UNSYNCED - hardware
3624 * timestamp, not synchronized with the
3625 * system clock.
3626 */
3627 timesource = SOF_TIMESTAMPING_RAW_HARDWARE;
3628 }
3629 if (setsockopt(handle->fd, SOL_PACKET, PACKET_TIMESTAMP,
3630 (void *)&timesource, sizeof(timesource))) {
3631 snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
3632 "can't set PACKET_TIMESTAMP: %s",
3633 pcap_strerror(errno));
3634 *status = PCAP_ERROR;
3635 return -1;
3636 }
3637 }
3638 }
3639 #endif /* HAVE_LINUX_NET_TSTAMP_H && PACKET_TIMESTAMP */
3640
3641 /* ask the kernel to create the ring */
3642 retry:
3643 req.tp_block_nr = req.tp_frame_nr / frames_per_block;
3644
3645 /* req.tp_frame_nr is requested to match frames_per_block*req.tp_block_nr */
3646 req.tp_frame_nr = req.tp_block_nr * frames_per_block;
3647
3648 if (setsockopt(handle->fd, SOL_PACKET, PACKET_RX_RING,
3649 (void *) &req, sizeof(req))) {
3650 if ((errno == ENOMEM) && (req.tp_block_nr > 1)) {
3651 /*
3652 * Memory failure; try to reduce the requested ring
3653 * size.
3654 *
3655 * We used to reduce this by half -- do 5% instead.
3656 * That may result in more iterations and a longer
3657 * startup, but the user will be much happier with
3658 * the resulting buffer size.
3659 */
3660 if (req.tp_frame_nr < 20)
3661 req.tp_frame_nr -= 1;
3662 else
3663 req.tp_frame_nr -= req.tp_frame_nr/20;
3664 goto retry;
3665 }
3666 if (errno == ENOPROTOOPT) {
3667 /*
3668 * We don't have ring buffer support in this kernel.
3669 */
3670 return 0;
3671 }
3672 snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
3673 "can't create rx ring on packet socket: %s",
3674 pcap_strerror(errno));
3675 *status = PCAP_ERROR;
3676 return -1;
3677 }
3678
3679 /* memory map the rx ring */
3680 handle->md.mmapbuflen = req.tp_block_nr * req.tp_block_size;
3681 handle->md.mmapbuf = mmap(0, handle->md.mmapbuflen,
3682 PROT_READ|PROT_WRITE, MAP_SHARED, handle->fd, 0);
3683 if (handle->md.mmapbuf == MAP_FAILED) {
3684 snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
3685 "can't mmap rx ring: %s", pcap_strerror(errno));
3686
3687 /* clear the allocated ring on error*/
3688 destroy_ring(handle);
3689 *status = PCAP_ERROR;
3690 return -1;
3691 }
3692
3693 /* allocate a ring for each frame header pointer*/
3694 handle->cc = req.tp_frame_nr;
3695 handle->buffer = malloc(handle->cc * sizeof(union thdr *));
3696 if (!handle->buffer) {
3697 snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
3698 "can't allocate ring of frame headers: %s",
3699 pcap_strerror(errno));
3700
3701 destroy_ring(handle);
3702 *status = PCAP_ERROR;
3703 return -1;
3704 }
3705
3706 /* fill the header ring with proper frame ptr*/
3707 handle->offset = 0;
3708 for (i=0; i<req.tp_block_nr; ++i) {
3709 void *base = &handle->md.mmapbuf[i*req.tp_block_size];
3710 for (j=0; j<frames_per_block; ++j, ++handle->offset) {
3711 RING_GET_FRAME(handle) = base;
3712 base += req.tp_frame_size;
3713 }
3714 }
3715
3716 handle->bufsize = req.tp_frame_size;
3717 handle->offset = 0;
3718 return 1;
3719 }
3720
3721 /* free all ring related resources*/
3722 static void
3723 destroy_ring(pcap_t *handle)
3724 {
3725 /* tell the kernel to destroy the ring*/
3726 struct tpacket_req req;
3727 memset(&req, 0, sizeof(req));
3728 setsockopt(handle->fd, SOL_PACKET, PACKET_RX_RING,
3729 (void *) &req, sizeof(req));
3730
3731 /* if ring is mapped, unmap it*/
3732 if (handle->md.mmapbuf) {
3733 /* do not test for mmap failure, as we can't recover from any error */
3734 munmap(handle->md.mmapbuf, handle->md.mmapbuflen);
3735 handle->md.mmapbuf = NULL;
3736 }
3737 }
3738
3739 /*
3740 * Special one-shot callback, used for pcap_next() and pcap_next_ex(),
3741 * for Linux mmapped capture.
3742 *
3743 * The problem is that pcap_next() and pcap_next_ex() expect the packet
3744 * data handed to the callback to be valid after the callback returns,
3745 * but pcap_read_linux_mmap() has to release that packet as soon as
3746 * the callback returns (otherwise, the kernel thinks there's still
3747 * at least one unprocessed packet available in the ring, so a select()
3748 * will immediately return indicating that there's data to process), so,
3749 * in the callback, we have to make a copy of the packet.
3750 *
3751 * Yes, this means that, if the capture is using the ring buffer, using
3752 * pcap_next() or pcap_next_ex() requires more copies than using
3753 * pcap_loop() or pcap_dispatch(). If that bothers you, don't use
3754 * pcap_next() or pcap_next_ex().
3755 */
3756 static void
3757 pcap_oneshot_mmap(u_char *user, const struct pcap_pkthdr *h,
3758 const u_char *bytes)
3759 {
3760 struct oneshot_userdata *sp = (struct oneshot_userdata *)user;
3761
3762 *sp->hdr = *h;
3763 memcpy(sp->pd->md.oneshot_buffer, bytes, h->caplen);
3764 *sp->pkt = sp->pd->md.oneshot_buffer;
3765 }
3766
3767 static void
3768 pcap_cleanup_linux_mmap( pcap_t *handle )
3769 {
3770 destroy_ring(handle);
3771 if (handle->md.oneshot_buffer != NULL) {
3772 free(handle->md.oneshot_buffer);
3773 handle->md.oneshot_buffer = NULL;
3774 }
3775 pcap_cleanup_linux(handle);
3776 }
3777
3778
3779 static int
3780 pcap_getnonblock_mmap(pcap_t *p, char *errbuf)
3781 {
3782 /* use negative value of timeout to indicate non blocking ops */
3783 return (p->md.timeout<0);
3784 }
3785
3786 static int
3787 pcap_setnonblock_mmap(pcap_t *p, int nonblock, char *errbuf)
3788 {
3789 /* map each value to the corresponding 2's complement, to
3790 * preserve the timeout value provided with pcap_set_timeout */
3791 if (nonblock) {
3792 if (p->md.timeout >= 0) {
3793 /*
3794 * Timeout is non-negative, so we're not already
3795 * in non-blocking mode; set it to the 2's
3796 * complement, to make it negative, as an
3797 * indication that we're in non-blocking mode.
3798 */
3799 p->md.timeout = p->md.timeout*-1 - 1;
3800 }
3801 } else {
3802 if (p->md.timeout < 0) {
3803 /*
3804 * Timeout is negative, so we're not already
3805 * in blocking mode; reverse the previous
3806 * operation, to make the timeout non-negative
3807 * again.
3808 */
3809 p->md.timeout = (p->md.timeout+1)*-1;
3810 }
3811 }
3812 return 0;
3813 }
3814
3815 static inline union thdr *
3816 pcap_get_ring_frame(pcap_t *handle, int status)
3817 {
3818 union thdr h;
3819
3820 h.raw = RING_GET_FRAME(handle);
3821 switch (handle->md.tp_version) {
3822 case TPACKET_V1:
3823 if (status != (h.h1->tp_status ? TP_STATUS_USER :
3824 TP_STATUS_KERNEL))
3825 return NULL;
3826 break;
3827 #ifdef HAVE_TPACKET2
3828 case TPACKET_V2:
3829 if (status != (h.h2->tp_status ? TP_STATUS_USER :
3830 TP_STATUS_KERNEL))
3831 return NULL;
3832 break;
3833 #endif
3834 }
3835 return h.raw;
3836 }
3837
3838 #ifndef POLLRDHUP
3839 #define POLLRDHUP 0
3840 #endif
3841
3842 static int
3843 pcap_read_linux_mmap(pcap_t *handle, int max_packets, pcap_handler callback,
3844 u_char *user)
3845 {
3846 int timeout;
3847 int pkts = 0;
3848 char c;
3849
3850 /* wait for frames availability.*/
3851 if (!pcap_get_ring_frame(handle, TP_STATUS_USER)) {
3852 struct pollfd pollinfo;
3853 int ret;
3854
3855 pollinfo.fd = handle->fd;
3856 pollinfo.events = POLLIN;
3857
3858 if (handle->md.timeout == 0)
3859 timeout = -1; /* block forever */
3860 else if (handle->md.timeout > 0)
3861 timeout = handle->md.timeout; /* block for that amount of time */
3862 else
3863 timeout = 0; /* non-blocking mode - poll to pick up errors */
3864 do {
3865 ret = poll(&pollinfo, 1, timeout);
3866 if (ret < 0 && errno != EINTR) {
3867 snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
3868 "can't poll on packet socket: %s",
3869 pcap_strerror(errno));
3870 return PCAP_ERROR;
3871 } else if (ret > 0 &&
3872 (pollinfo.revents & (POLLHUP|POLLRDHUP|POLLERR|POLLNVAL))) {
3873 /*
3874 * There's some indication other than
3875 * "you can read on this descriptor" on
3876 * the descriptor.
3877 */
3878 if (pollinfo.revents & (POLLHUP | POLLRDHUP)) {
3879 snprintf(handle->errbuf,
3880 PCAP_ERRBUF_SIZE,
3881 "Hangup on packet socket");
3882 return PCAP_ERROR;
3883 }
3884 if (pollinfo.revents & POLLERR) {
3885 /*
3886 * A recv() will give us the
3887 * actual error code.
3888 *
3889 * XXX - make the socket non-blocking?
3890 */
3891 if (recv(handle->fd, &c, sizeof c,
3892 MSG_PEEK) != -1)
3893 continue; /* what, no error? */
3894 if (errno == ENETDOWN) {
3895 /*
3896 * The device on which we're
3897 * capturing went away.
3898 *
3899 * XXX - we should really return
3900 * PCAP_ERROR_IFACE_NOT_UP,
3901 * but pcap_dispatch() etc.
3902 * aren't defined to return
3903 * that.
3904 */
3905 snprintf(handle->errbuf,
3906 PCAP_ERRBUF_SIZE,
3907 "The interface went down");
3908 } else {
3909 snprintf(handle->errbuf,
3910 PCAP_ERRBUF_SIZE,
3911 "Error condition on packet socket: %s",
3912 strerror(errno));
3913 }
3914 return PCAP_ERROR;
3915 }
3916 if (pollinfo.revents & POLLNVAL) {
3917 snprintf(handle->errbuf,
3918 PCAP_ERRBUF_SIZE,
3919 "Invalid polling request on packet socket");
3920 return PCAP_ERROR;
3921 }
3922 }
3923 /* check for break loop condition on interrupted syscall*/
3924 if (handle->break_loop) {
3925 handle->break_loop = 0;
3926 return PCAP_ERROR_BREAK;
3927 }
3928 } while (ret < 0);
3929 }
3930
3931 /* non-positive values of max_packets are used to require all
3932 * packets currently available in the ring */
3933 while ((pkts < max_packets) || (max_packets <= 0)) {
3934 int run_bpf;
3935 struct sockaddr_ll *sll;
3936 struct pcap_pkthdr pcaphdr;
3937 unsigned char *bp;
3938 union thdr h;
3939 unsigned int tp_len;
3940 unsigned int tp_mac;
3941 unsigned int tp_snaplen;
3942 unsigned int tp_sec;
3943 unsigned int tp_usec;
3944
3945 h.raw = pcap_get_ring_frame(handle, TP_STATUS_USER);
3946 if (!h.raw)
3947 break;
3948
3949 switch (handle->md.tp_version) {
3950 case TPACKET_V1:
3951 tp_len = h.h1->tp_len;
3952 tp_mac = h.h1->tp_mac;
3953 tp_snaplen = h.h1->tp_snaplen;
3954 tp_sec = h.h1->tp_sec;
3955 tp_usec = h.h1->tp_usec;
3956 break;
3957 #ifdef HAVE_TPACKET2
3958 case TPACKET_V2:
3959 tp_len = h.h2->tp_len;
3960 tp_mac = h.h2->tp_mac;
3961 tp_snaplen = h.h2->tp_snaplen;
3962 tp_sec = h.h2->tp_sec;
3963 tp_usec = h.h2->tp_nsec / 1000;
3964 break;
3965 #endif
3966 default:
3967 snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
3968 "unsupported tpacket version %d",
3969 handle->md.tp_version);
3970 return -1;
3971 }
3972 /* perform sanity check on internal offset. */
3973 if (tp_mac + tp_snaplen > handle->bufsize) {
3974 snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
3975 "corrupted frame on kernel ring mac "
3976 "offset %d + caplen %d > frame len %d",
3977 tp_mac, tp_snaplen, handle->bufsize);
3978 return -1;
3979 }
3980
3981 /* run filter on received packet
3982 * If the kernel filtering is enabled we need to run the
3983 * filter until all the frames present into the ring
3984 * at filter creation time are processed.
3985 * In such case md.use_bpf is used as a counter for the
3986 * packet we need to filter.
3987 * Note: alternatively it could be possible to stop applying
3988 * the filter when the ring became empty, but it can possibly
3989 * happen a lot later... */
3990 bp = (unsigned char*)h.raw + tp_mac;
3991 run_bpf = (!handle->md.use_bpf) ||
3992 ((handle->md.use_bpf>1) && handle->md.use_bpf--);
3993 if (run_bpf && handle->fcode.bf_insns &&
3994 (bpf_filter(handle->fcode.bf_insns, bp,
3995 tp_len, tp_snaplen) == 0))
3996 goto skip;
3997
3998 /*
3999 * Do checks based on packet direction.
4000 */
4001 sll = (void *)h.raw + TPACKET_ALIGN(handle->md.tp_hdrlen);
4002 if (sll->sll_pkttype == PACKET_OUTGOING) {
4003 /*
4004 * Outgoing packet.
4005 * If this is from the loopback device, reject it;
4006 * we'll see the packet as an incoming packet as well,
4007 * and we don't want to see it twice.
4008 */
4009 if (sll->sll_ifindex == handle->md.lo_ifindex)
4010 goto skip;
4011
4012 /*
4013 * If the user only wants incoming packets, reject it.
4014 */
4015 if (handle->direction == PCAP_D_IN)
4016 goto skip;
4017 } else {
4018 /*
4019 * Incoming packet.
4020 * If the user only wants outgoing packets, reject it.
4021 */
4022 if (handle->direction == PCAP_D_OUT)
4023 goto skip;
4024 }
4025
4026 /* get required packet info from ring header */
4027 pcaphdr.ts.tv_sec = tp_sec;
4028 pcaphdr.ts.tv_usec = tp_usec;
4029 pcaphdr.caplen = tp_snaplen;
4030 pcaphdr.len = tp_len;
4031
4032 /* if required build in place the sll header*/
4033 if (handle->md.cooked) {
4034 struct sll_header *hdrp;
4035
4036 /*
4037 * The kernel should have left us with enough
4038 * space for an sll header; back up the packet
4039 * data pointer into that space, as that'll be
4040 * the beginning of the packet we pass to the
4041 * callback.
4042 */
4043 bp -= SLL_HDR_LEN;
4044
4045 /*
4046 * Let's make sure that's past the end of
4047 * the tpacket header, i.e. >=
4048 * ((u_char *)thdr + TPACKET_HDRLEN), so we
4049 * don't step on the header when we construct
4050 * the sll header.
4051 */
4052 if (bp < (u_char *)h.raw +
4053 TPACKET_ALIGN(handle->md.tp_hdrlen) +
4054 sizeof(struct sockaddr_ll)) {
4055 snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
4056 "cooked-mode frame doesn't have room for sll header");
4057 return -1;
4058 }
4059
4060 /*
4061 * OK, that worked; construct the sll header.
4062 */
4063 hdrp = (struct sll_header *)bp;
4064 hdrp->sll_pkttype = map_packet_type_to_sll_type(
4065 sll->sll_pkttype);
4066 hdrp->sll_hatype = htons(sll->sll_hatype);
4067 hdrp->sll_halen = htons(sll->sll_halen);
4068 memcpy(hdrp->sll_addr, sll->sll_addr, SLL_ADDRLEN);
4069 hdrp->sll_protocol = sll->sll_protocol;
4070
4071 /* update packet len */
4072 pcaphdr.caplen += SLL_HDR_LEN;
4073 pcaphdr.len += SLL_HDR_LEN;
4074 }
4075
4076 #ifdef HAVE_TPACKET2
4077 if (handle->md.tp_version == TPACKET_V2 && h.h2->tp_vlan_tci &&
4078 handle->md.vlan_offset != -1 &&
4079 tp_snaplen >= (unsigned int) handle->md.vlan_offset) {
4080 struct vlan_tag *tag;
4081
4082 bp -= VLAN_TAG_LEN;
4083 memmove(bp, bp + VLAN_TAG_LEN, handle->md.vlan_offset);
4084
4085 tag = (struct vlan_tag *)(bp + handle->md.vlan_offset);
4086 tag->vlan_tpid = htons(ETH_P_8021Q);
4087 tag->vlan_tci = htons(h.h2->tp_vlan_tci);
4088
4089 pcaphdr.caplen += VLAN_TAG_LEN;
4090 pcaphdr.len += VLAN_TAG_LEN;
4091 }
4092 #endif
4093
4094 /*
4095 * The only way to tell the kernel to cut off the
4096 * packet at a snapshot length is with a filter program;
4097 * if there's no filter program, the kernel won't cut
4098 * the packet off.
4099 *
4100 * Trim the snapshot length to be no longer than the
4101 * specified snapshot length.
4102 */
4103 if (pcaphdr.caplen > handle->snapshot)
4104 pcaphdr.caplen = handle->snapshot;
4105
4106 /* pass the packet to the user */
4107 pkts++;
4108 callback(user, &pcaphdr, bp);
4109 handle->md.packets_read++;
4110
4111 skip:
4112 /* next packet */
4113 switch (handle->md.tp_version) {
4114 case TPACKET_V1:
4115 h.h1->tp_status = TP_STATUS_KERNEL;
4116 break;
4117 #ifdef HAVE_TPACKET2
4118 case TPACKET_V2:
4119 h.h2->tp_status = TP_STATUS_KERNEL;
4120 break;
4121 #endif
4122 }
4123 if (++handle->offset >= handle->cc)
4124 handle->offset = 0;
4125
4126 /* check for break loop condition*/
4127 if (handle->break_loop) {
4128 handle->break_loop = 0;
4129 return PCAP_ERROR_BREAK;
4130 }
4131 }
4132 return pkts;
4133 }
4134
4135 static int
4136 pcap_setfilter_linux_mmap(pcap_t *handle, struct bpf_program *filter)
4137 {
4138 int n, offset;
4139 int ret;
4140
4141 /*
4142 * Don't rewrite "ret" instructions; we don't need to, as
4143 * we're not reading packets with recvmsg(), and we don't
4144 * want to, as, by not rewriting them, the kernel can avoid
4145 * copying extra data.
4146 */
4147 ret = pcap_setfilter_linux_common(handle, filter, 1);
4148 if (ret < 0)
4149 return ret;
4150
4151 /* if the kernel filter is enabled, we need to apply the filter on
4152 * all packets present into the ring. Get an upper bound of their number
4153 */
4154 if (!handle->md.use_bpf)
4155 return ret;
4156
4157 /* walk the ring backward and count the free slot */
4158 offset = handle->offset;
4159 if (--handle->offset < 0)
4160 handle->offset = handle->cc - 1;
4161 for (n=0; n < handle->cc; ++n) {
4162 if (--handle->offset < 0)
4163 handle->offset = handle->cc - 1;
4164 if (!pcap_get_ring_frame(handle, TP_STATUS_KERNEL))
4165 break;
4166 }
4167
4168 /* be careful to not change current ring position */
4169 handle->offset = offset;
4170
4171 /* store the number of packets currently present in the ring */
4172 handle->md.use_bpf = 1 + (handle->cc - n);
4173 return ret;
4174 }
4175
4176 #endif /* HAVE_PACKET_RING */
4177
4178
4179 #ifdef HAVE_PF_PACKET_SOCKETS
4180 /*
4181 * Return the index of the given device name. Fill ebuf and return
4182 * -1 on failure.
4183 */
4184 static int
4185 iface_get_id(int fd, const char *device, char *ebuf)
4186 {
4187 struct ifreq ifr;
4188
4189 memset(&ifr, 0, sizeof(ifr));
4190 strncpy(ifr.ifr_name, device, sizeof(ifr.ifr_name));
4191
4192 if (ioctl(fd, SIOCGIFINDEX, &ifr) == -1) {
4193 snprintf(ebuf, PCAP_ERRBUF_SIZE,
4194 "SIOCGIFINDEX: %s", pcap_strerror(errno));
4195 return -1;
4196 }
4197
4198 return ifr.ifr_ifindex;
4199 }
4200
4201 /*
4202 * Bind the socket associated with FD to the given device.
4203 * Return 1 on success, 0 if we should try a SOCK_PACKET socket,
4204 * or a PCAP_ERROR_ value on a hard error.
4205 */
4206 static int
4207 iface_bind(int fd, int ifindex, char *ebuf)
4208 {
4209 struct sockaddr_ll sll;
4210 int err;
4211 socklen_t errlen = sizeof(err);
4212
4213 memset(&sll, 0, sizeof(sll));
4214 sll.sll_family = AF_PACKET;
4215 sll.sll_ifindex = ifindex;
4216 sll.sll_protocol = htons(ETH_P_ALL);
4217
4218 if (bind(fd, (struct sockaddr *) &sll, sizeof(sll)) == -1) {
4219 if (errno == ENETDOWN) {
4220 /*
4221 * Return a "network down" indication, so that
4222 * the application can report that rather than
4223 * saying we had a mysterious failure and
4224 * suggest that they report a problem to the
4225 * libpcap developers.
4226 */
4227 return PCAP_ERROR_IFACE_NOT_UP;
4228 } else {
4229 snprintf(ebuf, PCAP_ERRBUF_SIZE,
4230 "bind: %s", pcap_strerror(errno));
4231 return PCAP_ERROR;
4232 }
4233 }
4234
4235 /* Any pending errors, e.g., network is down? */
4236
4237 if (getsockopt(fd, SOL_SOCKET, SO_ERROR, &err, &errlen) == -1) {
4238 snprintf(ebuf, PCAP_ERRBUF_SIZE,
4239 "getsockopt: %s", pcap_strerror(errno));
4240 return 0;
4241 }
4242
4243 if (err == ENETDOWN) {
4244 /*
4245 * Return a "network down" indication, so that
4246 * the application can report that rather than
4247 * saying we had a mysterious failure and
4248 * suggest that they report a problem to the
4249 * libpcap developers.
4250 */
4251 return PCAP_ERROR_IFACE_NOT_UP;
4252 } else if (err > 0) {
4253 snprintf(ebuf, PCAP_ERRBUF_SIZE,
4254 "bind: %s", pcap_strerror(err));
4255 return 0;
4256 }
4257
4258 return 1;
4259 }
4260
4261 #ifdef IW_MODE_MONITOR
4262 /*
4263 * Check whether the device supports the Wireless Extensions.
4264 * Returns 1 if it does, 0 if it doesn't, PCAP_ERROR_NO_SUCH_DEVICE
4265 * if the device doesn't even exist.
4266 */
4267 static int
4268 has_wext(int sock_fd, const char *device, char *ebuf)
4269 {
4270 struct iwreq ireq;
4271
4272 strncpy(ireq.ifr_ifrn.ifrn_name, device,
4273 sizeof ireq.ifr_ifrn.ifrn_name);
4274 ireq.ifr_ifrn.ifrn_name[sizeof ireq.ifr_ifrn.ifrn_name - 1] = 0;
4275 if (ioctl(sock_fd, SIOCGIWNAME, &ireq) >= 0)
4276 return 1; /* yes */
4277 snprintf(ebuf, PCAP_ERRBUF_SIZE,
4278 "%s: SIOCGIWPRIV: %s", device, pcap_strerror(errno));
4279 if (errno == ENODEV)
4280 return PCAP_ERROR_NO_SUCH_DEVICE;
4281 return 0;
4282 }
4283
4284 /*
4285 * Per me si va ne la citta dolente,
4286 * Per me si va ne l'etterno dolore,
4287 * ...
4288 * Lasciate ogne speranza, voi ch'intrate.
4289 *
4290 * XXX - airmon-ng does special stuff with the Orinoco driver and the
4291 * wlan-ng driver.
4292 */
4293 typedef enum {
4294 MONITOR_WEXT,
4295 MONITOR_HOSTAP,
4296 MONITOR_PRISM,
4297 MONITOR_PRISM54,
4298 MONITOR_ACX100,
4299 MONITOR_RT2500,
4300 MONITOR_RT2570,
4301 MONITOR_RT73,
4302 MONITOR_RTL8XXX
4303 } monitor_type;
4304
4305 /*
4306 * Use the Wireless Extensions, if we have them, to try to turn monitor mode
4307 * on if it's not already on.
4308 *
4309 * Returns 1 on success, 0 if we don't support the Wireless Extensions
4310 * on this device, or a PCAP_ERROR_ value if we do support them but
4311 * we weren't able to turn monitor mode on.
4312 */
4313 static int
4314 enter_rfmon_mode_wext(pcap_t *handle, int sock_fd, const char *device)
4315 {
4316 /*
4317 * XXX - at least some adapters require non-Wireless Extensions
4318 * mechanisms to turn monitor mode on.
4319 *
4320 * Atheros cards might require that a separate "monitor virtual access
4321 * point" be created, with later versions of the madwifi driver.
4322 * airmon-ng does "wlanconfig ath create wlandev {if} wlanmode
4323 * monitor -bssid", which apparently spits out a line "athN"
4324 * where "athN" is the monitor mode device. To leave monitor
4325 * mode, it destroys the monitor mode device.
4326 *
4327 * Some Intel Centrino adapters might require private ioctls to get
4328 * radio headers; the ipw2200 and ipw3945 drivers allow you to
4329 * configure a separate "rtapN" interface to capture in monitor
4330 * mode without preventing the adapter from operating normally.
4331 * (airmon-ng doesn't appear to use that, though.)
4332 *
4333 * It would be Truly Wonderful if mac80211 and nl80211 cleaned this
4334 * up, and if all drivers were converted to mac80211 drivers.
4335 *
4336 * If interface {if} is a mac80211 driver, the file
4337 * /sys/class/net/{if}/phy80211 is a symlink to
4338 * /sys/class/ieee80211/{phydev}, for some {phydev}.
4339 *
4340 * On Fedora 9, with a 2.6.26.3-29 kernel, my Zydas stick, at
4341 * least, has a "wmaster0" device and a "wlan0" device; the
4342 * latter is the one with the IP address. Both show up in
4343 * "tcpdump -D" output. Capturing on the wmaster0 device
4344 * captures with 802.11 headers.
4345 *
4346 * airmon-ng searches through /sys/class/net for devices named
4347 * monN, starting with mon0; as soon as one *doesn't* exist,
4348 * it chooses that as the monitor device name. If the "iw"
4349 * command exists, it does "iw dev {if} interface add {monif}
4350 * type monitor", where {monif} is the monitor device. It
4351 * then (sigh) sleeps .1 second, and then configures the
4352 * device up. Otherwise, if /sys/class/ieee80211/{phydev}/add_iface
4353 * is a file, it writes {mondev}, without a newline, to that file,
4354 * and again (sigh) sleeps .1 second, and then iwconfig's that
4355 * device into monitor mode and configures it up. Otherwise,
4356 * you can't do monitor mode.
4357 *
4358 * All these devices are "glued" together by having the
4359 * /sys/class/net/{device}/phy80211 links pointing to the same
4360 * place, so, given a wmaster, wlan, or mon device, you can
4361 * find the other devices by looking for devices with
4362 * the same phy80211 link.
4363 *
4364 * To turn monitor mode off, delete the monitor interface,
4365 * either with "iw dev {monif} interface del" or by sending
4366 * {monif}, with no NL, down /sys/class/ieee80211/{phydev}/remove_iface
4367 *
4368 * Note: if you try to create a monitor device named "monN", and
4369 * there's already a "monN" device, it fails, as least with
4370 * the netlink interface (which is what iw uses), with a return
4371 * value of -ENFILE. (Return values are negative errnos.) We
4372 * could probably use that to find an unused device.
4373 */
4374 int err;
4375 struct iwreq ireq;
4376 struct iw_priv_args *priv;
4377 monitor_type montype;
4378 int i;
4379 __u32 cmd;
4380 struct ifreq ifr;
4381 int oldflags;
4382 int args[2];
4383 int channel;
4384
4385 /*
4386 * Does this device *support* the Wireless Extensions?
4387 */
4388 err = has_wext(sock_fd, device, handle->errbuf);
4389 if (err <= 0)
4390 return err; /* either it doesn't or the device doesn't even exist */
4391 /*
4392 * Start out assuming we have no private extensions to control
4393 * radio metadata.
4394 */
4395 montype = MONITOR_WEXT;
4396 cmd = 0;
4397
4398 /*
4399 * Try to get all the Wireless Extensions private ioctls
4400 * supported by this device.
4401 *
4402 * First, get the size of the buffer we need, by supplying no
4403 * buffer and a length of 0. If the device supports private
4404 * ioctls, it should return E2BIG, with ireq.u.data.length set
4405 * to the length we need. If it doesn't support them, it should
4406 * return EOPNOTSUPP.
4407 */
4408 memset(&ireq, 0, sizeof ireq);
4409 strncpy(ireq.ifr_ifrn.ifrn_name, device,
4410 sizeof ireq.ifr_ifrn.ifrn_name);
4411 ireq.ifr_ifrn.ifrn_name[sizeof ireq.ifr_ifrn.ifrn_name - 1] = 0;
4412 ireq.u.data.pointer = (void *)args;
4413 ireq.u.data.length = 0;
4414 ireq.u.data.flags = 0;
4415 if (ioctl(sock_fd, SIOCGIWPRIV, &ireq) != -1) {
4416 snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
4417 "%s: SIOCGIWPRIV with a zero-length buffer didn't fail!",
4418 device);
4419 return PCAP_ERROR;
4420 }
4421 if (errno != EOPNOTSUPP) {
4422 /*
4423 * OK, it's not as if there are no private ioctls.
4424 */
4425 if (errno != E2BIG) {
4426 /*
4427 * Failed.
4428 */
4429 snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
4430 "%s: SIOCGIWPRIV: %s", device,
4431 pcap_strerror(errno));
4432 return PCAP_ERROR;
4433 }
4434
4435 /*
4436 * OK, try to get the list of private ioctls.
4437 */
4438 priv = malloc(ireq.u.data.length * sizeof (struct iw_priv_args));
4439 if (priv == NULL) {
4440 snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
4441 "malloc: %s", pcap_strerror(errno));
4442 return PCAP_ERROR;
4443 }
4444 ireq.u.data.pointer = (void *)priv;
4445 if (ioctl(sock_fd, SIOCGIWPRIV, &ireq) == -1) {
4446 snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
4447 "%s: SIOCGIWPRIV: %s", device,
4448 pcap_strerror(errno));
4449 free(priv);
4450 return PCAP_ERROR;
4451 }
4452
4453 /*
4454 * Look for private ioctls to turn monitor mode on or, if
4455 * monitor mode is on, to set the header type.
4456 */
4457 for (i = 0; i < ireq.u.data.length; i++) {
4458 if (strcmp(priv[i].name, "monitor_type") == 0) {
4459 /*
4460 * Hostap driver, use this one.
4461 * Set monitor mode first.
4462 * You can set it to 0 to get DLT_IEEE80211,
4463 * 1 to get DLT_PRISM, 2 to get
4464 * DLT_IEEE80211_RADIO_AVS, and, with more
4465 * recent versions of the driver, 3 to get
4466 * DLT_IEEE80211_RADIO.
4467 */
4468 if ((priv[i].set_args & IW_PRIV_TYPE_MASK) != IW_PRIV_TYPE_INT)
4469 break;
4470 if (!(priv[i].set_args & IW_PRIV_SIZE_FIXED))
4471 break;
4472 if ((priv[i].set_args & IW_PRIV_SIZE_MASK) != 1)
4473 break;
4474 montype = MONITOR_HOSTAP;
4475 cmd = priv[i].cmd;
4476 break;
4477 }
4478 if (strcmp(priv[i].name, "set_prismhdr") == 0) {
4479 /*
4480 * Prism54 driver, use this one.
4481 * Set monitor mode first.
4482 * You can set it to 2 to get DLT_IEEE80211
4483 * or 3 or get DLT_PRISM.
4484 */
4485 if ((priv[i].set_args & IW_PRIV_TYPE_MASK) != IW_PRIV_TYPE_INT)
4486 break;
4487 if (!(priv[i].set_args & IW_PRIV_SIZE_FIXED))
4488 break;
4489 if ((priv[i].set_args & IW_PRIV_SIZE_MASK) != 1)
4490 break;
4491 montype = MONITOR_PRISM54;
4492 cmd = priv[i].cmd;
4493 break;
4494 }
4495 if (strcmp(priv[i].name, "forceprismheader") == 0) {
4496 /*
4497 * RT2570 driver, use this one.
4498 * Do this after turning monitor mode on.
4499 * You can set it to 1 to get DLT_PRISM or 2
4500 * to get DLT_IEEE80211.
4501 */
4502 if ((priv[i].set_args & IW_PRIV_TYPE_MASK) != IW_PRIV_TYPE_INT)
4503 break;
4504 if (!(priv[i].set_args & IW_PRIV_SIZE_FIXED))
4505 break;
4506 if ((priv[i].set_args & IW_PRIV_SIZE_MASK) != 1)
4507 break;
4508 montype = MONITOR_RT2570;
4509 cmd = priv[i].cmd;
4510 break;
4511 }
4512 if (strcmp(priv[i].name, "forceprism") == 0) {
4513 /*
4514 * RT73 driver, use this one.
4515 * Do this after turning monitor mode on.
4516 * Its argument is a *string*; you can
4517 * set it to "1" to get DLT_PRISM or "2"
4518 * to get DLT_IEEE80211.
4519 */
4520 if ((priv[i].set_args & IW_PRIV_TYPE_MASK) != IW_PRIV_TYPE_CHAR)
4521 break;
4522 if (priv[i].set_args & IW_PRIV_SIZE_FIXED)
4523 break;
4524 montype = MONITOR_RT73;
4525 cmd = priv[i].cmd;
4526 break;
4527 }
4528 if (strcmp(priv[i].name, "prismhdr") == 0) {
4529 /*
4530 * One of the RTL8xxx drivers, use this one.
4531 * It can only be done after monitor mode
4532 * has been turned on. You can set it to 1
4533 * to get DLT_PRISM or 0 to get DLT_IEEE80211.
4534 */
4535 if ((priv[i].set_args & IW_PRIV_TYPE_MASK) != IW_PRIV_TYPE_INT)
4536 break;
4537 if (!(priv[i].set_args & IW_PRIV_SIZE_FIXED))
4538 break;
4539 if ((priv[i].set_args & IW_PRIV_SIZE_MASK) != 1)
4540 break;
4541 montype = MONITOR_RTL8XXX;
4542 cmd = priv[i].cmd;
4543 break;
4544 }
4545 if (strcmp(priv[i].name, "rfmontx") == 0) {
4546 /*
4547 * RT2500 or RT61 driver, use this one.
4548 * It has one one-byte parameter; set
4549 * u.data.length to 1 and u.data.pointer to
4550 * point to the parameter.
4551 * It doesn't itself turn monitor mode on.
4552 * You can set it to 1 to allow transmitting
4553 * in monitor mode(?) and get DLT_IEEE80211,
4554 * or set it to 0 to disallow transmitting in
4555 * monitor mode(?) and get DLT_PRISM.
4556 */
4557 if ((priv[i].set_args & IW_PRIV_TYPE_MASK) != IW_PRIV_TYPE_INT)
4558 break;
4559 if ((priv[i].set_args & IW_PRIV_SIZE_MASK) != 2)
4560 break;
4561 montype = MONITOR_RT2500;
4562 cmd = priv[i].cmd;
4563 break;
4564 }
4565 if (strcmp(priv[i].name, "monitor") == 0) {
4566 /*
4567 * Either ACX100 or hostap, use this one.
4568 * It turns monitor mode on.
4569 * If it takes two arguments, it's ACX100;
4570 * the first argument is 1 for DLT_PRISM
4571 * or 2 for DLT_IEEE80211, and the second
4572 * argument is the channel on which to
4573 * run. If it takes one argument, it's
4574 * HostAP, and the argument is 2 for
4575 * DLT_IEEE80211 and 3 for DLT_PRISM.
4576 *
4577 * If we see this, we don't quit, as this
4578 * might be a version of the hostap driver
4579 * that also supports "monitor_type".
4580 */
4581 if ((priv[i].set_args & IW_PRIV_TYPE_MASK) != IW_PRIV_TYPE_INT)
4582 break;
4583 if (!(priv[i].set_args & IW_PRIV_SIZE_FIXED))
4584 break;
4585 switch (priv[i].set_args & IW_PRIV_SIZE_MASK) {
4586
4587 case 1:
4588 montype = MONITOR_PRISM;
4589 cmd = priv[i].cmd;
4590 break;
4591
4592 case 2:
4593 montype = MONITOR_ACX100;
4594 cmd = priv[i].cmd;
4595 break;
4596
4597 default:
4598 break;
4599 }
4600 }
4601 }
4602 free(priv);
4603 }
4604
4605 /*
4606 * XXX - ipw3945? islism?
4607 */
4608
4609 /*
4610 * Get the old mode.
4611 */
4612 strncpy(ireq.ifr_ifrn.ifrn_name, device,
4613 sizeof ireq.ifr_ifrn.ifrn_name);
4614 ireq.ifr_ifrn.ifrn_name[sizeof ireq.ifr_ifrn.ifrn_name - 1] = 0;
4615 if (ioctl(sock_fd, SIOCGIWMODE, &ireq) == -1) {
4616 /*
4617 * We probably won't be able to set the mode, either.
4618 */
4619 return PCAP_ERROR_RFMON_NOTSUP;
4620 }
4621
4622 /*
4623 * Is it currently in monitor mode?
4624 */
4625 if (ireq.u.mode == IW_MODE_MONITOR) {
4626 /*
4627 * Yes. Just leave things as they are.
4628 * We don't offer multiple link-layer types, as
4629 * changing the link-layer type out from under
4630 * somebody else capturing in monitor mode would
4631 * be considered rude.
4632 */
4633 return 1;
4634 }
4635 /*
4636 * No. We have to put the adapter into rfmon mode.
4637 */
4638
4639 /*
4640 * If we haven't already done so, arrange to have
4641 * "pcap_close_all()" called when we exit.
4642 */
4643 if (!pcap_do_addexit(handle)) {
4644 /*
4645 * "atexit()" failed; don't put the interface
4646 * in rfmon mode, just give up.
4647 */
4648 return PCAP_ERROR_RFMON_NOTSUP;
4649 }
4650
4651 /*
4652 * Save the old mode.
4653 */
4654 handle->md.oldmode = ireq.u.mode;
4655
4656 /*
4657 * Put the adapter in rfmon mode. How we do this depends
4658 * on whether we have a special private ioctl or not.
4659 */
4660 if (montype == MONITOR_PRISM) {
4661 /*
4662 * We have the "monitor" private ioctl, but none of
4663 * the other private ioctls. Use this, and select
4664 * the Prism header.
4665 *
4666 * If it fails, just fall back on SIOCSIWMODE.
4667 */
4668 memset(&ireq, 0, sizeof ireq);
4669 strncpy(ireq.ifr_ifrn.ifrn_name, device,
4670 sizeof ireq.ifr_ifrn.ifrn_name);
4671 ireq.ifr_ifrn.ifrn_name[sizeof ireq.ifr_ifrn.ifrn_name - 1] = 0;
4672 ireq.u.data.length = 1; /* 1 argument */
4673 args[0] = 3; /* request Prism header */
4674 memcpy(ireq.u.name, args, IFNAMSIZ);
4675 if (ioctl(sock_fd, cmd, &ireq) != -1) {
4676 /*
4677 * Success.
4678 * Note that we have to put the old mode back
4679 * when we close the device.
4680 */
4681 handle->md.must_do_on_close |= MUST_CLEAR_RFMON;
4682
4683 /*
4684 * Add this to the list of pcaps to close
4685 * when we exit.
4686 */
4687 pcap_add_to_pcaps_to_close(handle);
4688
4689 return 1;
4690 }
4691
4692 /*
4693 * Failure. Fall back on SIOCSIWMODE.
4694 */
4695 }
4696
4697 /*
4698 * First, take the interface down if it's up; otherwise, we
4699 * might get EBUSY.
4700 */
4701 memset(&ifr, 0, sizeof(ifr));
4702 strncpy(ifr.ifr_name, device, sizeof(ifr.ifr_name));
4703 if (ioctl(sock_fd, SIOCGIFFLAGS, &ifr) == -1) {
4704 snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
4705 "%s: Can't get flags: %s", device, strerror(errno));
4706 return PCAP_ERROR;
4707 }
4708 oldflags = 0;
4709 if (ifr.ifr_flags & IFF_UP) {
4710 oldflags = ifr.ifr_flags;
4711 ifr.ifr_flags &= ~IFF_UP;
4712 if (ioctl(sock_fd, SIOCSIFFLAGS, &ifr) == -1) {
4713 snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
4714 "%s: Can't set flags: %s", device, strerror(errno));
4715 return PCAP_ERROR;
4716 }
4717 }
4718
4719 /*
4720 * Then turn monitor mode on.
4721 */
4722 strncpy(ireq.ifr_ifrn.ifrn_name, device,
4723 sizeof ireq.ifr_ifrn.ifrn_name);
4724 ireq.ifr_ifrn.ifrn_name[sizeof ireq.ifr_ifrn.ifrn_name - 1] = 0;
4725 ireq.u.mode = IW_MODE_MONITOR;
4726 if (ioctl(sock_fd, SIOCSIWMODE, &ireq) == -1) {
4727 /*
4728 * Scientist, you've failed.
4729 * Bring the interface back up if we shut it down.
4730 */
4731 ifr.ifr_flags = oldflags;
4732 if (ioctl(sock_fd, SIOCSIFFLAGS, &ifr) == -1) {
4733 snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
4734 "%s: Can't set flags: %s", device, strerror(errno));
4735 return PCAP_ERROR;
4736 }
4737 return PCAP_ERROR_RFMON_NOTSUP;
4738 }
4739
4740 /*
4741 * XXX - airmon-ng does "iwconfig {if} key off" after setting
4742 * monitor mode and setting the channel, and then does
4743 * "iwconfig up".
4744 */
4745
4746 /*
4747 * Now select the appropriate radio header.
4748 */
4749 switch (montype) {
4750
4751 case MONITOR_WEXT:
4752 /*
4753 * We don't have any private ioctl to set the header.
4754 */
4755 break;
4756
4757 case MONITOR_HOSTAP:
4758 /*
4759 * Try to select the radiotap header.
4760 */
4761 memset(&ireq, 0, sizeof ireq);
4762 strncpy(ireq.ifr_ifrn.ifrn_name, device,
4763 sizeof ireq.ifr_ifrn.ifrn_name);
4764 ireq.ifr_ifrn.ifrn_name[sizeof ireq.ifr_ifrn.ifrn_name - 1] = 0;
4765 args[0] = 3; /* request radiotap header */
4766 memcpy(ireq.u.name, args, sizeof (int));
4767 if (ioctl(sock_fd, cmd, &ireq) != -1)
4768 break; /* success */
4769
4770 /*
4771 * That failed. Try to select the AVS header.
4772 */
4773 memset(&ireq, 0, sizeof ireq);
4774 strncpy(ireq.ifr_ifrn.ifrn_name, device,
4775 sizeof ireq.ifr_ifrn.ifrn_name);
4776 ireq.ifr_ifrn.ifrn_name[sizeof ireq.ifr_ifrn.ifrn_name - 1] = 0;
4777 args[0] = 2; /* request AVS header */
4778 memcpy(ireq.u.name, args, sizeof (int));
4779 if (ioctl(sock_fd, cmd, &ireq) != -1)
4780 break; /* success */
4781
4782 /*
4783 * That failed. Try to select the Prism header.
4784 */
4785 memset(&ireq, 0, sizeof ireq);
4786 strncpy(ireq.ifr_ifrn.ifrn_name, device,
4787 sizeof ireq.ifr_ifrn.ifrn_name);
4788 ireq.ifr_ifrn.ifrn_name[sizeof ireq.ifr_ifrn.ifrn_name - 1] = 0;
4789 args[0] = 1; /* request Prism header */
4790 memcpy(ireq.u.name, args, sizeof (int));
4791 ioctl(sock_fd, cmd, &ireq);
4792 break;
4793
4794 case MONITOR_PRISM:
4795 /*
4796 * The private ioctl failed.
4797 */
4798 break;
4799
4800 case MONITOR_PRISM54:
4801 /*
4802 * Select the Prism header.
4803 */
4804 memset(&ireq, 0, sizeof ireq);
4805 strncpy(ireq.ifr_ifrn.ifrn_name, device,
4806 sizeof ireq.ifr_ifrn.ifrn_name);
4807 ireq.ifr_ifrn.ifrn_name[sizeof ireq.ifr_ifrn.ifrn_name - 1] = 0;
4808 args[0] = 3; /* request Prism header */
4809 memcpy(ireq.u.name, args, sizeof (int));
4810 ioctl(sock_fd, cmd, &ireq);
4811 break;
4812
4813 case MONITOR_ACX100:
4814 /*
4815 * Get the current channel.
4816 */
4817 memset(&ireq, 0, sizeof ireq);
4818 strncpy(ireq.ifr_ifrn.ifrn_name, device,
4819 sizeof ireq.ifr_ifrn.ifrn_name);
4820 ireq.ifr_ifrn.ifrn_name[sizeof ireq.ifr_ifrn.ifrn_name - 1] = 0;
4821 if (ioctl(sock_fd, SIOCGIWFREQ, &ireq) == -1) {
4822 snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
4823 "%s: SIOCGIWFREQ: %s", device,
4824 pcap_strerror(errno));
4825 return PCAP_ERROR;
4826 }
4827 channel = ireq.u.freq.m;
4828
4829 /*
4830 * Select the Prism header, and set the channel to the
4831 * current value.
4832 */
4833 memset(&ireq, 0, sizeof ireq);
4834 strncpy(ireq.ifr_ifrn.ifrn_name, device,
4835 sizeof ireq.ifr_ifrn.ifrn_name);
4836 ireq.ifr_ifrn.ifrn_name[sizeof ireq.ifr_ifrn.ifrn_name - 1] = 0;
4837 args[0] = 1; /* request Prism header */
4838 args[1] = channel; /* set channel */
4839 memcpy(ireq.u.name, args, 2*sizeof (int));
4840 ioctl(sock_fd, cmd, &ireq);
4841 break;
4842
4843 case MONITOR_RT2500:
4844 /*
4845 * Disallow transmission - that turns on the
4846 * Prism header.
4847 */
4848 memset(&ireq, 0, sizeof ireq);
4849 strncpy(ireq.ifr_ifrn.ifrn_name, device,
4850 sizeof ireq.ifr_ifrn.ifrn_name);
4851 ireq.ifr_ifrn.ifrn_name[sizeof ireq.ifr_ifrn.ifrn_name - 1] = 0;
4852 args[0] = 0; /* disallow transmitting */
4853 memcpy(ireq.u.name, args, sizeof (int));
4854 ioctl(sock_fd, cmd, &ireq);
4855 break;
4856
4857 case MONITOR_RT2570:
4858 /*
4859 * Force the Prism header.
4860 */
4861 memset(&ireq, 0, sizeof ireq);
4862 strncpy(ireq.ifr_ifrn.ifrn_name, device,
4863 sizeof ireq.ifr_ifrn.ifrn_name);
4864 ireq.ifr_ifrn.ifrn_name[sizeof ireq.ifr_ifrn.ifrn_name - 1] = 0;
4865 args[0] = 1; /* request Prism header */
4866 memcpy(ireq.u.name, args, sizeof (int));
4867 ioctl(sock_fd, cmd, &ireq);
4868 break;
4869
4870 case MONITOR_RT73:
4871 /*
4872 * Force the Prism header.
4873 */
4874 memset(&ireq, 0, sizeof ireq);
4875 strncpy(ireq.ifr_ifrn.ifrn_name, device,
4876 sizeof ireq.ifr_ifrn.ifrn_name);
4877 ireq.ifr_ifrn.ifrn_name[sizeof ireq.ifr_ifrn.ifrn_name - 1] = 0;
4878 ireq.u.data.length = 1; /* 1 argument */
4879 ireq.u.data.pointer = "1";
4880 ireq.u.data.flags = 0;
4881 ioctl(sock_fd, cmd, &ireq);
4882 break;
4883
4884 case MONITOR_RTL8XXX:
4885 /*
4886 * Force the Prism header.
4887 */
4888 memset(&ireq, 0, sizeof ireq);
4889 strncpy(ireq.ifr_ifrn.ifrn_name, device,
4890 sizeof ireq.ifr_ifrn.ifrn_name);
4891 ireq.ifr_ifrn.ifrn_name[sizeof ireq.ifr_ifrn.ifrn_name - 1] = 0;
4892 args[0] = 1; /* request Prism header */
4893 memcpy(ireq.u.name, args, sizeof (int));
4894 ioctl(sock_fd, cmd, &ireq);
4895 break;
4896 }
4897
4898 /*
4899 * Now bring the interface back up if we brought it down.
4900 */
4901 if (oldflags != 0) {
4902 ifr.ifr_flags = oldflags;
4903 if (ioctl(sock_fd, SIOCSIFFLAGS, &ifr) == -1) {
4904 snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
4905 "%s: Can't set flags: %s", device, strerror(errno));
4906
4907 /*
4908 * At least try to restore the old mode on the
4909 * interface.
4910 */
4911 if (ioctl(handle->fd, SIOCSIWMODE, &ireq) == -1) {
4912 /*
4913 * Scientist, you've failed.
4914 */
4915 fprintf(stderr,
4916 "Can't restore interface wireless mode (SIOCSIWMODE failed: %s).\n"
4917 "Please adjust manually.\n",
4918 strerror(errno));
4919 }
4920 return PCAP_ERROR;
4921 }
4922 }
4923
4924 /*
4925 * Note that we have to put the old mode back when we
4926 * close the device.
4927 */
4928 handle->md.must_do_on_close |= MUST_CLEAR_RFMON;
4929
4930 /*
4931 * Add this to the list of pcaps to close when we exit.
4932 */
4933 pcap_add_to_pcaps_to_close(handle);
4934
4935 return 1;
4936 }
4937 #endif /* IW_MODE_MONITOR */
4938
4939 /*
4940 * Try various mechanisms to enter monitor mode.
4941 */
4942 static int
4943 enter_rfmon_mode(pcap_t *handle, int sock_fd, const char *device)
4944 {
4945 #if defined(HAVE_LIBNL) || defined(IW_MODE_MONITOR)
4946 int ret;
4947 #endif
4948
4949 #ifdef HAVE_LIBNL
4950 ret = enter_rfmon_mode_mac80211(handle, sock_fd, device);
4951 if (ret < 0)
4952 return ret; /* error attempting to do so */
4953 if (ret == 1)
4954 return 1; /* success */
4955 #endif /* HAVE_LIBNL */
4956
4957 #ifdef IW_MODE_MONITOR
4958 ret = enter_rfmon_mode_wext(handle, sock_fd, device);
4959 if (ret < 0)
4960 return ret; /* error attempting to do so */
4961 if (ret == 1)
4962 return 1; /* success */
4963 #endif /* IW_MODE_MONITOR */
4964
4965 /*
4966 * Either none of the mechanisms we know about work or none
4967 * of those mechanisms are available, so we can't do monitor
4968 * mode.
4969 */
4970 return 0;
4971 }
4972
4973 /*
4974 * Find out if we have any form of fragmentation/reassembly offloading.
4975 *
4976 * We do so using SIOCETHTOOL checking for various types of offloading;
4977 * if SIOCETHTOOL isn't defined, or we don't have any #defines for any
4978 * of the types of offloading, there's nothing we can do to check, so
4979 * we just say "no, we don't".
4980 */
4981 #if defined(SIOCETHTOOL) && (defined(ETHTOOL_GTSO) || defined(ETHTOOL_GUFO) || defined(ETHTOOL_GGSO) || defined(ETHTOOL_GFLAGS) || defined(ETHTOOL_GGRO))
4982 static int
4983 iface_ethtool_ioctl(pcap_t *handle, int cmd, const char *cmdname)
4984 {
4985 struct ifreq ifr;
4986 struct ethtool_value eval;
4987
4988 memset(&ifr, 0, sizeof(ifr));
4989 strncpy(ifr.ifr_name, handle->opt.source, sizeof(ifr.ifr_name));
4990 eval.cmd = cmd;
4991 ifr.ifr_data = (caddr_t)&eval;
4992 if (ioctl(handle->fd, SIOCETHTOOL, &ifr) == -1) {
4993 if (errno == EOPNOTSUPP || errno == EINVAL) {
4994 /*
4995 * OK, let's just return 0, which, in our
4996 * case, either means "no, what we're asking
4997 * about is not enabled" or "all the flags
4998 * are clear (i.e., nothing is enabled)".
4999 */
5000 return 0;
5001 }
5002 snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
5003 "%s: SIOETHTOOL(%s) ioctl failed: %s", handle->opt.source,
5004 cmdname, strerror(errno));
5005 return -1;
5006 }
5007 return eval.data;
5008 }
5009
5010 static int
5011 iface_get_offload(pcap_t *handle)
5012 {
5013 int ret;
5014
5015 #ifdef ETHTOOL_GTSO
5016 ret = iface_ethtool_ioctl(handle, ETHTOOL_GTSO, "ETHTOOL_GTSO");
5017 if (ret == -1)
5018 return -1;
5019 if (ret)
5020 return 1; /* TCP segmentation offloading on */
5021 #endif
5022
5023 #ifdef ETHTOOL_GUFO
5024 ret = iface_ethtool_ioctl(handle, ETHTOOL_GUFO, "ETHTOOL_GUFO");
5025 if (ret == -1)
5026 return -1;
5027 if (ret)
5028 return 1; /* UDP fragmentation offloading on */
5029 #endif
5030
5031 #ifdef ETHTOOL_GGSO
5032 /*
5033 * XXX - will this cause large unsegmented packets to be
5034 * handed to PF_PACKET sockets on transmission? If not,
5035 * this need not be checked.
5036 */
5037 ret = iface_ethtool_ioctl(handle, ETHTOOL_GGSO, "ETHTOOL_GGSO");
5038 if (ret == -1)
5039 return -1;
5040 if (ret)
5041 return 1; /* generic segmentation offloading on */
5042 #endif
5043
5044 #ifdef ETHTOOL_GFLAGS
5045 ret = iface_ethtool_ioctl(handle, ETHTOOL_GFLAGS, "ETHTOOL_GFLAGS");
5046 if (ret == -1)
5047 return -1;
5048 if (ret & ETH_FLAG_LRO)
5049 return 1; /* large receive offloading on */
5050 #endif
5051
5052 #ifdef ETHTOOL_GGRO
5053 /*
5054 * XXX - will this cause large reassembled packets to be
5055 * handed to PF_PACKET sockets on receipt? If not,
5056 * this need not be checked.
5057 */
5058 ret = iface_ethtool_ioctl(handle, ETHTOOL_GGRO, "ETHTOOL_GGRO");
5059 if (ret == -1)
5060 return -1;
5061 if (ret)
5062 return 1; /* generic (large) receive offloading on */
5063 #endif
5064
5065 return 0;
5066 }
5067 #else /* SIOCETHTOOL */
5068 static int
5069 iface_get_offload(pcap_t *handle _U_)
5070 {
5071 /*
5072 * XXX - do we need to get this information if we don't
5073 * have the ethtool ioctls? If so, how do we do that?
5074 */
5075 return 0;
5076 }
5077 #endif /* SIOCETHTOOL */
5078
5079 #endif /* HAVE_PF_PACKET_SOCKETS */
5080
5081 /* ===== Functions to interface to the older kernels ================== */
5082
5083 /*
5084 * Try to open a packet socket using the old kernel interface.
5085 * Returns 1 on success and a PCAP_ERROR_ value on an error.
5086 */
5087 static int
5088 activate_old(pcap_t *handle)
5089 {
5090 int arptype;
5091 struct ifreq ifr;
5092 const char *device = handle->opt.source;
5093 struct utsname utsname;
5094 int mtu;
5095
5096 /* Open the socket */
5097
5098 handle->fd = socket(PF_INET, SOCK_PACKET, htons(ETH_P_ALL));
5099 if (handle->fd == -1) {
5100 snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
5101 "socket: %s", pcap_strerror(errno));
5102 if (errno == EPERM || errno == EACCES) {
5103 /*
5104 * You don't have permission to open the
5105 * socket.
5106 */
5107 return PCAP_ERROR_PERM_DENIED;
5108 } else {
5109 /*
5110 * Other error.
5111 */
5112 return PCAP_ERROR;
5113 }
5114 }
5115
5116 /* It worked - we are using the old interface */
5117 handle->md.sock_packet = 1;
5118
5119 /* ...which means we get the link-layer header. */
5120 handle->md.cooked = 0;
5121
5122 /* Bind to the given device */
5123
5124 if (strcmp(device, "any") == 0) {
5125 strncpy(handle->errbuf, "pcap_activate: The \"any\" device isn't supported on 2.0[.x]-kernel systems",
5126 PCAP_ERRBUF_SIZE);
5127 return PCAP_ERROR;
5128 }
5129 if (iface_bind_old(handle->fd, device, handle->errbuf) == -1)
5130 return PCAP_ERROR;
5131
5132 /*
5133 * Try to get the link-layer type.
5134 */
5135 arptype = iface_get_arptype(handle->fd, device, handle->errbuf);
5136 if (arptype < 0)
5137 return PCAP_ERROR;
5138
5139 /*
5140 * Try to find the DLT_ type corresponding to that
5141 * link-layer type.
5142 */
5143 map_arphrd_to_dlt(handle, arptype, 0);
5144 if (handle->linktype == -1) {
5145 snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
5146 "unknown arptype %d", arptype);
5147 return PCAP_ERROR;
5148 }
5149
5150 /* Go to promisc mode if requested */
5151
5152 if (handle->opt.promisc) {
5153 memset(&ifr, 0, sizeof(ifr));
5154 strncpy(ifr.ifr_name, device, sizeof(ifr.ifr_name));
5155 if (ioctl(handle->fd, SIOCGIFFLAGS, &ifr) == -1) {
5156 snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
5157 "SIOCGIFFLAGS: %s", pcap_strerror(errno));
5158 return PCAP_ERROR;
5159 }
5160 if ((ifr.ifr_flags & IFF_PROMISC) == 0) {
5161 /*
5162 * Promiscuous mode isn't currently on,
5163 * so turn it on, and remember that
5164 * we should turn it off when the
5165 * pcap_t is closed.
5166 */
5167
5168 /*
5169 * If we haven't already done so, arrange
5170 * to have "pcap_close_all()" called when
5171 * we exit.
5172 */
5173 if (!pcap_do_addexit(handle)) {
5174 /*
5175 * "atexit()" failed; don't put
5176 * the interface in promiscuous
5177 * mode, just give up.
5178 */
5179 return PCAP_ERROR;
5180 }
5181
5182 ifr.ifr_flags |= IFF_PROMISC;
5183 if (ioctl(handle->fd, SIOCSIFFLAGS, &ifr) == -1) {
5184 snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
5185 "SIOCSIFFLAGS: %s",
5186 pcap_strerror(errno));
5187 return PCAP_ERROR;
5188 }
5189 handle->md.must_do_on_close |= MUST_CLEAR_PROMISC;
5190
5191 /*
5192 * Add this to the list of pcaps
5193 * to close when we exit.
5194 */
5195 pcap_add_to_pcaps_to_close(handle);
5196 }
5197 }
5198
5199 /*
5200 * Compute the buffer size.
5201 *
5202 * We're using SOCK_PACKET, so this might be a 2.0[.x]
5203 * kernel, and might require special handling - check.
5204 */
5205 if (uname(&utsname) < 0 ||
5206 strncmp(utsname.release, "2.0", 3) == 0) {
5207 /*
5208 * Either we couldn't find out what kernel release
5209 * this is, or it's a 2.0[.x] kernel.
5210 *
5211 * In the 2.0[.x] kernel, a "recvfrom()" on
5212 * a SOCK_PACKET socket, with MSG_TRUNC set, will
5213 * return the number of bytes read, so if we pass
5214 * a length based on the snapshot length, it'll
5215 * return the number of bytes from the packet
5216 * copied to userland, not the actual length
5217 * of the packet.
5218 *
5219 * This means that, for example, the IP dissector
5220 * in tcpdump will get handed a packet length less
5221 * than the length in the IP header, and will
5222 * complain about "truncated-ip".
5223 *
5224 * So we don't bother trying to copy from the
5225 * kernel only the bytes in which we're interested,
5226 * but instead copy them all, just as the older
5227 * versions of libpcap for Linux did.
5228 *
5229 * The buffer therefore needs to be big enough to
5230 * hold the largest packet we can get from this
5231 * device. Unfortunately, we can't get the MRU
5232 * of the network; we can only get the MTU. The
5233 * MTU may be too small, in which case a packet larger
5234 * than the buffer size will be truncated *and* we
5235 * won't get the actual packet size.
5236 *
5237 * However, if the snapshot length is larger than
5238 * the buffer size based on the MTU, we use the
5239 * snapshot length as the buffer size, instead;
5240 * this means that with a sufficiently large snapshot
5241 * length we won't artificially truncate packets
5242 * to the MTU-based size.
5243 *
5244 * This mess just one of many problems with packet
5245 * capture on 2.0[.x] kernels; you really want a
5246 * 2.2[.x] or later kernel if you want packet capture
5247 * to work well.
5248 */
5249 mtu = iface_get_mtu(handle->fd, device, handle->errbuf);
5250 if (mtu == -1)
5251 return PCAP_ERROR;
5252 handle->bufsize = MAX_LINKHEADER_SIZE + mtu;
5253 if (handle->bufsize < handle->snapshot)
5254 handle->bufsize = handle->snapshot;
5255 } else {
5256 /*
5257 * This is a 2.2[.x] or later kernel.
5258 *
5259 * We can safely pass "recvfrom()" a byte count
5260 * based on the snapshot length.
5261 */
5262 handle->bufsize = handle->snapshot;
5263 }
5264
5265 /*
5266 * Default value for offset to align link-layer payload
5267 * on a 4-byte boundary.
5268 */
5269 handle->offset = 0;
5270
5271 /*
5272 * SOCK_PACKET sockets don't supply information from
5273 * stripped VLAN tags.
5274 */
5275 handle->md.vlan_offset = -1; /* unknown */
5276
5277 return 1;
5278 }
5279
5280 /*
5281 * Bind the socket associated with FD to the given device using the
5282 * interface of the old kernels.
5283 */
5284 static int
5285 iface_bind_old(int fd, const char *device, char *ebuf)
5286 {
5287 struct sockaddr saddr;
5288 int err;
5289 socklen_t errlen = sizeof(err);
5290
5291 memset(&saddr, 0, sizeof(saddr));
5292 strncpy(saddr.sa_data, device, sizeof(saddr.sa_data));
5293 if (bind(fd, &saddr, sizeof(saddr)) == -1) {
5294 snprintf(ebuf, PCAP_ERRBUF_SIZE,
5295 "bind: %s", pcap_strerror(errno));
5296 return -1;
5297 }
5298
5299 /* Any pending errors, e.g., network is down? */
5300
5301 if (getsockopt(fd, SOL_SOCKET, SO_ERROR, &err, &errlen) == -1) {
5302 snprintf(ebuf, PCAP_ERRBUF_SIZE,
5303 "getsockopt: %s", pcap_strerror(errno));
5304 return -1;
5305 }
5306
5307 if (err > 0) {
5308 snprintf(ebuf, PCAP_ERRBUF_SIZE,
5309 "bind: %s", pcap_strerror(err));
5310 return -1;
5311 }
5312
5313 return 0;
5314 }
5315
5316
5317 /* ===== System calls available on all supported kernels ============== */
5318
5319 /*
5320 * Query the kernel for the MTU of the given interface.
5321 */
5322 static int
5323 iface_get_mtu(int fd, const char *device, char *ebuf)
5324 {
5325 struct ifreq ifr;
5326
5327 if (!device)
5328 return BIGGER_THAN_ALL_MTUS;
5329
5330 memset(&ifr, 0, sizeof(ifr));
5331 strncpy(ifr.ifr_name, device, sizeof(ifr.ifr_name));
5332
5333 if (ioctl(fd, SIOCGIFMTU, &ifr) == -1) {
5334 snprintf(ebuf, PCAP_ERRBUF_SIZE,
5335 "SIOCGIFMTU: %s", pcap_strerror(errno));
5336 return -1;
5337 }
5338
5339 return ifr.ifr_mtu;
5340 }
5341
5342 /*
5343 * Get the hardware type of the given interface as ARPHRD_xxx constant.
5344 */
5345 static int
5346 iface_get_arptype(int fd, const char *device, char *ebuf)
5347 {
5348 struct ifreq ifr;
5349
5350 memset(&ifr, 0, sizeof(ifr));
5351 strncpy(ifr.ifr_name, device, sizeof(ifr.ifr_name));
5352
5353 if (ioctl(fd, SIOCGIFHWADDR, &ifr) == -1) {
5354 snprintf(ebuf, PCAP_ERRBUF_SIZE,
5355 "SIOCGIFHWADDR: %s", pcap_strerror(errno));
5356 if (errno == ENODEV) {
5357 /*
5358 * No such device.
5359 */
5360 return PCAP_ERROR_NO_SUCH_DEVICE;
5361 }
5362 return PCAP_ERROR;
5363 }
5364
5365 return ifr.ifr_hwaddr.sa_family;
5366 }
5367
5368 #ifdef SO_ATTACH_FILTER
5369 static int
5370 fix_program(pcap_t *handle, struct sock_fprog *fcode, int is_mmapped)
5371 {
5372 size_t prog_size;
5373 register int i;
5374 register struct bpf_insn *p;
5375 struct bpf_insn *f;
5376 int len;
5377
5378 /*
5379 * Make a copy of the filter, and modify that copy if
5380 * necessary.
5381 */
5382 prog_size = sizeof(*handle->fcode.bf_insns) * handle->fcode.bf_len;
5383 len = handle->fcode.bf_len;
5384 f = (struct bpf_insn *)malloc(prog_size);
5385 if (f == NULL) {
5386 snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
5387 "malloc: %s", pcap_strerror(errno));
5388 return -1;
5389 }
5390 memcpy(f, handle->fcode.bf_insns, prog_size);
5391 fcode->len = len;
5392 fcode->filter = (struct sock_filter *) f;
5393
5394 for (i = 0; i < len; ++i) {
5395 p = &f[i];
5396 /*
5397 * What type of instruction is this?
5398 */
5399 switch (BPF_CLASS(p->code)) {
5400
5401 case BPF_RET:
5402 /*
5403 * It's a return instruction; are we capturing
5404 * in memory-mapped mode?
5405 */
5406 if (!is_mmapped) {
5407 /*
5408 * No; is the snapshot length a constant,
5409 * rather than the contents of the
5410 * accumulator?
5411 */
5412 if (BPF_MODE(p->code) == BPF_K) {
5413 /*
5414 * Yes - if the value to be returned,
5415 * i.e. the snapshot length, is
5416 * anything other than 0, make it
5417 * 65535, so that the packet is
5418 * truncated by "recvfrom()",
5419 * not by the filter.
5420 *
5421 * XXX - there's nothing we can
5422 * easily do if it's getting the
5423 * value from the accumulator; we'd
5424 * have to insert code to force
5425 * non-zero values to be 65535.
5426 */
5427 if (p->k != 0)
5428 p->k = 65535;
5429 }
5430 }
5431 break;
5432
5433 case BPF_LD:
5434 case BPF_LDX:
5435 /*
5436 * It's a load instruction; is it loading
5437 * from the packet?
5438 */
5439 switch (BPF_MODE(p->code)) {
5440
5441 case BPF_ABS:
5442 case BPF_IND:
5443 case BPF_MSH:
5444 /*
5445 * Yes; are we in cooked mode?
5446 */
5447 if (handle->md.cooked) {
5448 /*
5449 * Yes, so we need to fix this
5450 * instruction.
5451 */
5452 if (fix_offset(p) < 0) {
5453 /*
5454 * We failed to do so.
5455 * Return 0, so our caller
5456 * knows to punt to userland.
5457 */
5458 return 0;
5459 }
5460 }
5461 break;
5462 }
5463 break;
5464 }
5465 }
5466 return 1; /* we succeeded */
5467 }
5468
5469 static int
5470 fix_offset(struct bpf_insn *p)
5471 {
5472 /*
5473 * What's the offset?
5474 */
5475 if (p->k >= SLL_HDR_LEN) {
5476 /*
5477 * It's within the link-layer payload; that starts at an
5478 * offset of 0, as far as the kernel packet filter is
5479 * concerned, so subtract the length of the link-layer
5480 * header.
5481 */
5482 p->k -= SLL_HDR_LEN;
5483 } else if (p->k == 0) {
5484 /*
5485 * It's the packet type field; map it to the special magic
5486 * kernel offset for that field.
5487 */
5488 p->k = SKF_AD_OFF + SKF_AD_PKTTYPE;
5489 } else if (p->k == 14) {
5490 /*
5491 * It's the protocol field; map it to the special magic
5492 * kernel offset for that field.
5493 */
5494 p->k = SKF_AD_OFF + SKF_AD_PROTOCOL;
5495 } else if ((bpf_int32)(p->k) > 0) {
5496 /*
5497 * It's within the header, but it's not one of those
5498 * fields; we can't do that in the kernel, so punt
5499 * to userland.
5500 */
5501 return -1;
5502 }
5503 return 0;
5504 }
5505
5506 static int
5507 set_kernel_filter(pcap_t *handle, struct sock_fprog *fcode)
5508 {
5509 int total_filter_on = 0;
5510 int save_mode;
5511 int ret;
5512 int save_errno;
5513
5514 /*
5515 * The socket filter code doesn't discard all packets queued
5516 * up on the socket when the filter is changed; this means
5517 * that packets that don't match the new filter may show up
5518 * after the new filter is put onto the socket, if those
5519 * packets haven't yet been read.
5520 *
5521 * This means, for example, that if you do a tcpdump capture
5522 * with a filter, the first few packets in the capture might
5523 * be packets that wouldn't have passed the filter.
5524 *
5525 * We therefore discard all packets queued up on the socket
5526 * when setting a kernel filter. (This isn't an issue for
5527 * userland filters, as the userland filtering is done after
5528 * packets are queued up.)
5529 *
5530 * To flush those packets, we put the socket in read-only mode,
5531 * and read packets from the socket until there are no more to
5532 * read.
5533 *
5534 * In order to keep that from being an infinite loop - i.e.,
5535 * to keep more packets from arriving while we're draining
5536 * the queue - we put the "total filter", which is a filter
5537 * that rejects all packets, onto the socket before draining
5538 * the queue.
5539 *
5540 * This code deliberately ignores any errors, so that you may
5541 * get bogus packets if an error occurs, rather than having
5542 * the filtering done in userland even if it could have been
5543 * done in the kernel.
5544 */
5545 if (setsockopt(handle->fd, SOL_SOCKET, SO_ATTACH_FILTER,
5546 &total_fcode, sizeof(total_fcode)) == 0) {
5547 char drain[1];
5548
5549 /*
5550 * Note that we've put the total filter onto the socket.
5551 */
5552 total_filter_on = 1;
5553
5554 /*
5555 * Save the socket's current mode, and put it in
5556 * non-blocking mode; we drain it by reading packets
5557 * until we get an error (which is normally a
5558 * "nothing more to be read" error).
5559 */
5560 save_mode = fcntl(handle->fd, F_GETFL, 0);
5561 if (save_mode != -1 &&
5562 fcntl(handle->fd, F_SETFL, save_mode | O_NONBLOCK) >= 0) {
5563 while (recv(handle->fd, &drain, sizeof drain,
5564 MSG_TRUNC) >= 0)
5565 ;
5566 save_errno = errno;
5567 fcntl(handle->fd, F_SETFL, save_mode);
5568 if (save_errno != EAGAIN) {
5569 /* Fatal error */
5570 reset_kernel_filter(handle);
5571 snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
5572 "recv: %s", pcap_strerror(save_errno));
5573 return -2;
5574 }
5575 }
5576 }
5577
5578 /*
5579 * Now attach the new filter.
5580 */
5581 ret = setsockopt(handle->fd, SOL_SOCKET, SO_ATTACH_FILTER,
5582 fcode, sizeof(*fcode));
5583 if (ret == -1 && total_filter_on) {
5584 /*
5585 * Well, we couldn't set that filter on the socket,
5586 * but we could set the total filter on the socket.
5587 *
5588 * This could, for example, mean that the filter was
5589 * too big to put into the kernel, so we'll have to
5590 * filter in userland; in any case, we'll be doing
5591 * filtering in userland, so we need to remove the
5592 * total filter so we see packets.
5593 */
5594 save_errno = errno;
5595
5596 /*
5597 * XXX - if this fails, we're really screwed;
5598 * we have the total filter on the socket,
5599 * and it won't come off. What do we do then?
5600 */
5601 reset_kernel_filter(handle);
5602
5603 errno = save_errno;
5604 }
5605 return ret;
5606 }
5607
5608 static int
5609 reset_kernel_filter(pcap_t *handle)
5610 {
5611 /*
5612 * setsockopt() barfs unless it get a dummy parameter.
5613 * valgrind whines unless the value is initialized,
5614 * as it has no idea that setsockopt() ignores its
5615 * parameter.
5616 */
5617 int dummy = 0;
5618
5619 return setsockopt(handle->fd, SOL_SOCKET, SO_DETACH_FILTER,
5620 &dummy, sizeof(dummy));
5621 }
5622 #endif