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