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