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