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