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