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