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