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