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