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