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