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