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