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