]> The Tcpdump Group git mirrors - libpcap/blob - pcap-linux.c
Return -1 for all failures to create a packet ring other than "this
[libpcap] / pcap-linux.c
1 /*
2 * pcap-linux.c: Packet capture interface to the Linux kernel
3 *
4 * Copyright (c) 2000 Torsten Landschoff <torsten@debian.org>
5 * Sebastian Krahmer <krahmer@cs.uni-potsdam.de>
6 *
7 * License: BSD
8 *
9 * Redistribution and use in source and binary forms, with or without
10 * modification, are permitted provided that the following conditions
11 * are met:
12 *
13 * 1. Redistributions of source code must retain the above copyright
14 * notice, this list of conditions and the following disclaimer.
15 * 2. Redistributions in binary form must reproduce the above copyright
16 * notice, this list of conditions and the following disclaimer in
17 * the documentation and/or other materials provided with the
18 * distribution.
19 * 3. The names of the authors may not be used to endorse or promote
20 * products derived from this software without specific prior
21 * written permission.
22 *
23 * THIS SOFTWARE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR
24 * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
25 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
26 *
27 * Modifications: Added PACKET_MMAP support
28 * Paolo Abeni <paolo.abeni@email.it>
29 *
30 * based on previous works of:
31 * Simon Patarin <patarin@cs.unibo.it>
32 * Phil Wood <cpw@lanl.gov>
33 */
34
35 #ifndef lint
36 static const char rcsid[] _U_ =
37 "@(#) $Header: /tcpdump/master/libpcap/pcap-linux.c,v 1.129.2.32 2008-11-19 17:37:14 guy Exp $ (LBL)";
38 #endif
39
40 /*
41 * Known problems with 2.0[.x] kernels:
42 *
43 * - The loopback device gives every packet twice; on 2.2[.x] kernels,
44 * if we use PF_PACKET, we can filter out the transmitted version
45 * of the packet by using data in the "sockaddr_ll" returned by
46 * "recvfrom()", but, on 2.0[.x] kernels, we have to use
47 * PF_INET/SOCK_PACKET, which means "recvfrom()" supplies a
48 * "sockaddr_pkt" which doesn't give us enough information to let
49 * us do that.
50 *
51 * - We have to set the interface's IFF_PROMISC flag ourselves, if
52 * we're to run in promiscuous mode, which means we have to turn
53 * it off ourselves when we're done; the kernel doesn't keep track
54 * of how many sockets are listening promiscuously, which means
55 * it won't get turned off automatically when no sockets are
56 * listening promiscuously. We catch "pcap_close()" and, for
57 * interfaces we put into promiscuous mode, take them out of
58 * promiscuous mode - which isn't necessarily the right thing to
59 * do, if another socket also requested promiscuous mode between
60 * the time when we opened the socket and the time when we close
61 * the socket.
62 *
63 * - MSG_TRUNC isn't supported, so you can't specify that "recvfrom()"
64 * return the amount of data that you could have read, rather than
65 * the amount that was returned, so we can't just allocate a buffer
66 * whose size is the snapshot length and pass the snapshot length
67 * as the byte count, and also pass MSG_TRUNC, so that the return
68 * value tells us how long the packet was on the wire.
69 *
70 * This means that, if we want to get the actual size of the packet,
71 * so we can return it in the "len" field of the packet header,
72 * we have to read the entire packet, not just the part that fits
73 * within the snapshot length, and thus waste CPU time copying data
74 * from the kernel that our caller won't see.
75 *
76 * We have to get the actual size, and supply it in "len", because
77 * otherwise, the IP dissector in tcpdump, for example, will complain
78 * about "truncated-ip", as the packet will appear to have been
79 * shorter, on the wire, than the IP header said it should have been.
80 */
81
82
83 #ifdef HAVE_CONFIG_H
84 #include "config.h"
85 #endif
86
87 #include <errno.h>
88 #include <stdlib.h>
89 #include <unistd.h>
90 #include <fcntl.h>
91 #include <string.h>
92 #include <sys/socket.h>
93 #include <sys/ioctl.h>
94 #include <sys/utsname.h>
95 #include <sys/mman.h>
96 #include <net/if.h>
97 #include <netinet/in.h>
98 #include <linux/if_ether.h>
99 #include <net/if_arp.h>
100 #include <poll.h>
101
102 /*
103 * Got Wireless Extensions?
104 */
105 #ifdef HAVE_LINUX_WIRELESS_H
106 #include <linux/wireless.h>
107 #endif
108
109 #include "pcap-int.h"
110 #include "pcap/sll.h"
111 #include "pcap/vlan.h"
112
113 #ifdef HAVE_DAG_API
114 #include "pcap-dag.h"
115 #endif /* HAVE_DAG_API */
116
117 #ifdef HAVE_SEPTEL_API
118 #include "pcap-septel.h"
119 #endif /* HAVE_SEPTEL_API */
120
121 #ifdef PCAP_SUPPORT_USB
122 #include "pcap-usb-linux.h"
123 #endif
124
125 #ifdef PCAP_SUPPORT_BT
126 #include "pcap-bt-linux.h"
127 #endif
128
129 /*
130 * If PF_PACKET is defined, we can use {SOCK_RAW,SOCK_DGRAM}/PF_PACKET
131 * sockets rather than SOCK_PACKET sockets.
132 *
133 * To use them, we include <linux/if_packet.h> rather than
134 * <netpacket/packet.h>; we do so because
135 *
136 * some Linux distributions (e.g., Slackware 4.0) have 2.2 or
137 * later kernels and libc5, and don't provide a <netpacket/packet.h>
138 * file;
139 *
140 * not all versions of glibc2 have a <netpacket/packet.h> file
141 * that defines stuff needed for some of the 2.4-or-later-kernel
142 * features, so if the system has a 2.4 or later kernel, we
143 * still can't use those features.
144 *
145 * We're already including a number of other <linux/XXX.h> headers, and
146 * this code is Linux-specific (no other OS has PF_PACKET sockets as
147 * a raw packet capture mechanism), so it's not as if you gain any
148 * useful portability by using <netpacket/packet.h>
149 *
150 * XXX - should we just include <linux/if_packet.h> even if PF_PACKET
151 * isn't defined? It only defines one data structure in 2.0.x, so
152 * it shouldn't cause any problems.
153 */
154 #ifdef PF_PACKET
155 # include <linux/if_packet.h>
156
157 /*
158 * On at least some Linux distributions (for example, Red Hat 5.2),
159 * there's no <netpacket/packet.h> file, but PF_PACKET is defined if
160 * you include <sys/socket.h>, but <linux/if_packet.h> doesn't define
161 * any of the PF_PACKET stuff such as "struct sockaddr_ll" or any of
162 * the PACKET_xxx stuff.
163 *
164 * So we check whether PACKET_HOST is defined, and assume that we have
165 * PF_PACKET sockets only if it is defined.
166 */
167 # ifdef PACKET_HOST
168 # define HAVE_PF_PACKET_SOCKETS
169 # ifdef PACKET_AUXDATA
170 # define HAVE_PACKET_AUXDATA
171 # endif /* PACKET_AUXDATA */
172 # endif /* PACKET_HOST */
173
174
175 /* check for memory mapped access avaibility. We assume every needed
176 * struct is defined if the macro TPACKET_HDRLEN is defined, because it
177 * uses many ring related structs and macros */
178 # ifdef TPACKET_HDRLEN
179 # define HAVE_PACKET_RING
180 # ifdef TPACKET2_HDRLEN
181 # define HAVE_TPACKET2
182 # else
183 # define TPACKET_V1 0
184 # endif /* TPACKET2_HDRLEN */
185 # endif /* TPACKET_HDRLEN */
186 #endif /* PF_PACKET */
187
188 #ifdef SO_ATTACH_FILTER
189 #include <linux/types.h>
190 #include <linux/filter.h>
191 #endif
192
193 #ifndef HAVE_SOCKLEN_T
194 typedef int socklen_t;
195 #endif
196
197 #ifndef MSG_TRUNC
198 /*
199 * This is being compiled on a system that lacks MSG_TRUNC; define it
200 * with the value it has in the 2.2 and later kernels, so that, on
201 * those kernels, when we pass it in the flags argument to "recvfrom()"
202 * we're passing the right value and thus get the MSG_TRUNC behavior
203 * we want. (We don't get that behavior on 2.0[.x] kernels, because
204 * they didn't support MSG_TRUNC.)
205 */
206 #define MSG_TRUNC 0x20
207 #endif
208
209 #ifndef SOL_PACKET
210 /*
211 * This is being compiled on a system that lacks SOL_PACKET; define it
212 * with the value it has in the 2.2 and later kernels, so that we can
213 * set promiscuous mode in the good modern way rather than the old
214 * 2.0-kernel crappy way.
215 */
216 #define SOL_PACKET 263
217 #endif
218
219 #define MAX_LINKHEADER_SIZE 256
220
221 /*
222 * When capturing on all interfaces we use this as the buffer size.
223 * Should be bigger then all MTUs that occur in real life.
224 * 64kB should be enough for now.
225 */
226 #define BIGGER_THAN_ALL_MTUS (64*1024)
227
228 /*
229 * Prototypes for internal functions and methods.
230 */
231 static void map_arphrd_to_dlt(pcap_t *, int, int);
232 #ifdef HAVE_PF_PACKET_SOCKETS
233 static short int map_packet_type_to_sll_type(short int);
234 #endif
235 static int pcap_activate_linux(pcap_t *);
236 static int activate_old(pcap_t *);
237 static int activate_new(pcap_t *);
238 static int activate_mmap(pcap_t *);
239 static int pcap_can_set_rfmon_linux(pcap_t *);
240 static int pcap_read_linux(pcap_t *, int, pcap_handler, u_char *);
241 static int pcap_read_packet(pcap_t *, pcap_handler, u_char *);
242 static int pcap_inject_linux(pcap_t *, const void *, size_t);
243 static int pcap_stats_linux(pcap_t *, struct pcap_stat *);
244 static int pcap_setfilter_linux(pcap_t *, struct bpf_program *);
245 static int pcap_setdirection_linux(pcap_t *, pcap_direction_t);
246 static void pcap_cleanup_linux(pcap_t *);
247
248 union thdr {
249 struct tpacket_hdr *h1;
250 struct tpacket2_hdr *h2;
251 void *raw;
252 };
253
254 #ifdef HAVE_PACKET_RING
255 #define RING_GET_FRAME(h) (((union thdr **)h->buffer)[h->offset])
256
257 static void destroy_ring(pcap_t *handle);
258 static int create_ring(pcap_t *handle);
259 static int prepare_tpacket_socket(pcap_t *handle);
260 static void pcap_cleanup_linux_mmap(pcap_t *);
261 static int pcap_read_linux_mmap(pcap_t *, int, pcap_handler , u_char *);
262 static int pcap_setfilter_linux_mmap(pcap_t *, struct bpf_program *);
263 static int pcap_setnonblock_mmap(pcap_t *p, int nonblock, char *errbuf);
264 static int pcap_getnonblock_mmap(pcap_t *p, char *errbuf);
265 #endif
266
267 /*
268 * Wrap some ioctl calls
269 */
270 #ifdef HAVE_PF_PACKET_SOCKETS
271 static int iface_get_id(int fd, const char *device, char *ebuf);
272 #endif
273 static int iface_get_mtu(int fd, const char *device, char *ebuf);
274 static int iface_get_arptype(int fd, const char *device, char *ebuf);
275 #ifdef HAVE_PF_PACKET_SOCKETS
276 static int iface_bind(int fd, int ifindex, char *ebuf);
277 static int has_wext(int sock_fd, const char *device, char *ebuf);
278 static int enter_rfmon_mode_wext(pcap_t *handle, int sock_fd,
279 const char *device);
280 #endif
281 static int iface_bind_old(int fd, const char *device, char *ebuf);
282
283 #ifdef SO_ATTACH_FILTER
284 static int fix_program(pcap_t *handle, struct sock_fprog *fcode);
285 static int fix_offset(struct bpf_insn *p);
286 static int set_kernel_filter(pcap_t *handle, struct sock_fprog *fcode);
287 static int reset_kernel_filter(pcap_t *handle);
288
289 static struct sock_filter total_insn
290 = BPF_STMT(BPF_RET | BPF_K, 0);
291 static struct sock_fprog total_fcode
292 = { 1, &total_insn };
293 #endif
294
295 pcap_t *
296 pcap_create(const char *device, char *ebuf)
297 {
298 pcap_t *handle;
299
300 /*
301 * A null device name is equivalent to the "any" device.
302 */
303 if (device == NULL)
304 device = "any";
305
306 #ifdef HAVE_DAG_API
307 if (strstr(device, "dag")) {
308 return dag_create(device, ebuf);
309 }
310 #endif /* HAVE_DAG_API */
311
312 #ifdef HAVE_SEPTEL_API
313 if (strstr(device, "septel")) {
314 return septel_create(device, ebuf);
315 }
316 #endif /* HAVE_SEPTEL_API */
317
318 #ifdef PCAP_SUPPORT_BT
319 if (strstr(device, "bluetooth")) {
320 return bt_create(device, ebuf);
321 }
322 #endif
323
324 #ifdef PCAP_SUPPORT_USB
325 if (strstr(device, "usb")) {
326 return usb_create(device, ebuf);
327 }
328 #endif
329
330 handle = pcap_create_common(device, ebuf);
331 if (handle == NULL)
332 return NULL;
333
334 handle->activate_op = pcap_activate_linux;
335 handle->can_set_rfmon_op = pcap_can_set_rfmon_linux;
336 return handle;
337 }
338
339 static int
340 pcap_can_set_rfmon_linux(pcap_t *p)
341 {
342 #ifdef IW_MODE_MONITOR
343 int sock_fd;
344 struct iwreq ireq;
345 #endif
346
347 if (strcmp(p->opt.source, "any") == 0) {
348 /*
349 * Monitor mode makes no sense on the "any" device.
350 */
351 return 0;
352 }
353
354 #ifdef IW_MODE_MONITOR
355 /*
356 * Bleah. There doesn't appear to be an ioctl to use to ask
357 * whether a device supports monitor mode; we'll just do
358 * SIOCGIWMODE and, if it succeeds, assume the device supports
359 * monitor mode.
360 *
361 * Open a socket on which to attempt to get the mode.
362 * (We assume that if we have Wireless Extensions support
363 * we also have PF_PACKET support.)
364 */
365 sock_fd = socket(PF_PACKET, SOCK_RAW, htons(ETH_P_ALL));
366 if (sock_fd == -1) {
367 (void)snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
368 "socket: %s", pcap_strerror(errno));
369 return PCAP_ERROR;
370 }
371
372 /*
373 * Attempt to get the current mode.
374 */
375 strncpy(ireq.ifr_ifrn.ifrn_name, p->opt.source,
376 sizeof ireq.ifr_ifrn.ifrn_name);
377 ireq.ifr_ifrn.ifrn_name[sizeof ireq.ifr_ifrn.ifrn_name - 1] = 0;
378 if (ioctl(sock_fd, SIOCGIWMODE, &ireq) != -1) {
379 /*
380 * Well, we got the mode; assume we can set it.
381 */
382 close(sock_fd);
383 return 1;
384 }
385 if (errno == ENODEV) {
386 /* The device doesn't even exist. */
387 close(sock_fd);
388 return PCAP_ERROR_NO_SUCH_DEVICE;
389 }
390 close(sock_fd);
391 #endif
392 return 0;
393 }
394
395 /*
396 * With older kernels promiscuous mode is kind of interesting because we
397 * have to reset the interface before exiting. The problem can't really
398 * be solved without some daemon taking care of managing usage counts.
399 * If we put the interface into promiscuous mode, we set a flag indicating
400 * that we must take it out of that mode when the interface is closed,
401 * and, when closing the interface, if that flag is set we take it out
402 * of promiscuous mode.
403 *
404 * Even with newer kernels, we have the same issue with rfmon mode.
405 */
406
407 static void pcap_cleanup_linux( pcap_t *handle )
408 {
409 struct ifreq ifr;
410 #ifdef IW_MODE_MONITOR
411 struct iwreq ireq;
412 #endif
413
414 if (handle->md.must_clear != 0) {
415 /*
416 * There's something we have to do when closing this
417 * pcap_t.
418 */
419 if (handle->md.must_clear & MUST_CLEAR_PROMISC) {
420 /*
421 * We put the interface into promiscuous mode;
422 * take it out of promiscuous mode.
423 *
424 * XXX - if somebody else wants it in promiscuous
425 * mode, this code cannot know that, so it'll take
426 * it out of promiscuous mode. That's not fixable
427 * in 2.0[.x] kernels.
428 */
429 memset(&ifr, 0, sizeof(ifr));
430 strncpy(ifr.ifr_name, handle->md.device,
431 sizeof(ifr.ifr_name));
432 if (ioctl(handle->fd, SIOCGIFFLAGS, &ifr) == -1) {
433 fprintf(stderr,
434 "Can't restore interface flags (SIOCGIFFLAGS failed: %s).\n"
435 "Please adjust manually.\n"
436 "Hint: This can't happen with Linux >= 2.2.0.\n",
437 strerror(errno));
438 } else {
439 if (ifr.ifr_flags & IFF_PROMISC) {
440 /*
441 * Promiscuous mode is currently on;
442 * turn it off.
443 */
444 ifr.ifr_flags &= ~IFF_PROMISC;
445 if (ioctl(handle->fd, SIOCSIFFLAGS,
446 &ifr) == -1) {
447 fprintf(stderr,
448 "Can't restore interface flags (SIOCSIFFLAGS failed: %s).\n"
449 "Please adjust manually.\n"
450 "Hint: This can't happen with Linux >= 2.2.0.\n",
451 strerror(errno));
452 }
453 }
454 }
455 }
456
457 #ifdef IW_MODE_MONITOR
458 if (handle->md.must_clear & MUST_CLEAR_RFMON) {
459 /*
460 * We put the interface into rfmon mode;
461 * take it out of rfmon mode.
462 *
463 * XXX - if somebody else wants it in rfmon
464 * mode, this code cannot know that, so it'll take
465 * it out of rfmon mode.
466 */
467 strncpy(ireq.ifr_ifrn.ifrn_name, handle->md.device,
468 sizeof ireq.ifr_ifrn.ifrn_name);
469 ireq.ifr_ifrn.ifrn_name[sizeof ireq.ifr_ifrn.ifrn_name - 1]
470 = 0;
471 ireq.u.mode = handle->md.oldmode;
472 if (ioctl(handle->fd, SIOCSIWMODE, &ireq) == -1) {
473 /*
474 * Scientist, you've failed.
475 */
476 fprintf(stderr,
477 "Can't restore interface wireless mode (SIOCSIWMODE failed: %s).\n"
478 "Please adjust manually.\n",
479 strerror(errno));
480 }
481 }
482 #endif
483
484 /*
485 * Take this pcap out of the list of pcaps for which we
486 * have to take the interface out of some mode.
487 */
488 pcap_remove_from_pcaps_to_close(handle);
489 }
490
491 if (handle->md.device != NULL) {
492 free(handle->md.device);
493 handle->md.device = NULL;
494 }
495 pcap_cleanup_live_common(handle);
496 }
497
498 /*
499 * Get a handle for a live capture from the given device. You can
500 * pass NULL as device to get all packages (without link level
501 * information of course). If you pass 1 as promisc the interface
502 * will be set to promiscous mode (XXX: I think this usage should
503 * be deprecated and functions be added to select that later allow
504 * modification of that values -- Torsten).
505 */
506 static int
507 pcap_activate_linux(pcap_t *handle)
508 {
509 const char *device;
510 int status = 0;
511
512 device = handle->opt.source;
513
514 handle->inject_op = pcap_inject_linux;
515 handle->setfilter_op = pcap_setfilter_linux;
516 handle->setdirection_op = pcap_setdirection_linux;
517 handle->set_datalink_op = NULL; /* can't change data link type */
518 handle->getnonblock_op = pcap_getnonblock_fd;
519 handle->setnonblock_op = pcap_setnonblock_fd;
520 handle->cleanup_op = pcap_cleanup_linux;
521 handle->read_op = pcap_read_linux;
522 handle->stats_op = pcap_stats_linux;
523
524 /*
525 * The "any" device is a special device which causes us not
526 * to bind to a particular device and thus to look at all
527 * devices.
528 */
529 if (strcmp(device, "any") == 0) {
530 if (handle->opt.promisc) {
531 handle->opt.promisc = 0;
532 /* Just a warning. */
533 snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
534 "Promiscuous mode not supported on the \"any\" device");
535 status = PCAP_WARNING_PROMISC_NOTSUP;
536 }
537 }
538
539 handle->md.device = strdup(device);
540 if (handle->md.device == NULL) {
541 snprintf(handle->errbuf, PCAP_ERRBUF_SIZE, "strdup: %s",
542 pcap_strerror(errno) );
543 return PCAP_ERROR;
544 }
545
546 /*
547 * Current Linux kernels use the protocol family PF_PACKET to
548 * allow direct access to all packets on the network while
549 * older kernels had a special socket type SOCK_PACKET to
550 * implement this feature.
551 * While this old implementation is kind of obsolete we need
552 * to be compatible with older kernels for a while so we are
553 * trying both methods with the newer method preferred.
554 */
555
556 if ((status = activate_new(handle)) == 1) {
557 /*
558 * Success.
559 * Try to use memory-mapped access.
560 */
561 switch (activate_mmap(handle)) {
562
563 case 1:
564 /* we succeeded; nothing more to do */
565 return 0;
566
567 case 0:
568 /*
569 * Kernel doesn't support it - just continue
570 * with non-memory-mapped access.
571 */
572 break;
573
574 case -1:
575 /*
576 * We failed to set up to use it, or kernel
577 * supports it, but we failed to enable it;
578 * return an error. handle->errbuf contains
579 * an error message.
580 */
581 status = PCAP_ERROR;
582 goto fail;
583 }
584 }
585 else if (status == 0) {
586 /* Non-fatal error; try old way */
587 if ((status = activate_old(handle)) != 1) {
588 /*
589 * Both methods to open the packet socket failed.
590 * Tidy up and report our failure (handle->errbuf
591 * is expected to be set by the functions above).
592 */
593 goto fail;
594 }
595 } else {
596 /*
597 * Fatal error with the new way; just fail.
598 * status has the error return; if it's PCAP_ERROR,
599 * handle->errbuf has been set appropriately.
600 */
601 goto fail;
602 }
603
604 /*
605 * We set up the socket, but not with memory-mapped access.
606 */
607 if (handle->opt.buffer_size != 0) {
608 /*
609 * Set the socket buffer size to the specified value.
610 */
611 if (setsockopt(handle->fd, SOL_SOCKET, SO_RCVBUF,
612 &handle->opt.buffer_size,
613 sizeof(handle->opt.buffer_size)) == -1) {
614 snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
615 "SO_RCVBUF: %s", pcap_strerror(errno));
616 status = PCAP_ERROR;
617 goto fail;
618 }
619 }
620
621 /* Allocate the buffer */
622
623 handle->buffer = malloc(handle->bufsize + handle->offset);
624 if (!handle->buffer) {
625 snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
626 "malloc: %s", pcap_strerror(errno));
627 status = PCAP_ERROR;
628 goto fail;
629 }
630
631 /*
632 * "handle->fd" is a socket, so "select()" and "poll()"
633 * should work on it.
634 */
635 handle->selectable_fd = handle->fd;
636
637 return status;
638
639 fail:
640 pcap_cleanup_linux(handle);
641 return status;
642 }
643
644 /*
645 * Read at most max_packets from the capture stream and call the callback
646 * for each of them. Returns the number of packets handled or -1 if an
647 * error occured.
648 */
649 static int
650 pcap_read_linux(pcap_t *handle, int max_packets, pcap_handler callback, u_char *user)
651 {
652 /*
653 * Currently, on Linux only one packet is delivered per read,
654 * so we don't loop.
655 */
656 return pcap_read_packet(handle, callback, user);
657 }
658
659 /*
660 * Read a packet from the socket calling the handler provided by
661 * the user. Returns the number of packets received or -1 if an
662 * error occured.
663 */
664 static int
665 pcap_read_packet(pcap_t *handle, pcap_handler callback, u_char *userdata)
666 {
667 u_char *bp;
668 int offset;
669 #ifdef HAVE_PF_PACKET_SOCKETS
670 struct sockaddr_ll from;
671 struct sll_header *hdrp;
672 #else
673 struct sockaddr from;
674 #endif
675 #if defined(HAVE_PACKET_AUXDATA) && defined(HAVE_LINUX_TPACKET_AUXDATA_TP_VLAN_TCI)
676 struct iovec iov;
677 struct msghdr msg;
678 struct cmsghdr *cmsg;
679 union {
680 struct cmsghdr cmsg;
681 char buf[CMSG_SPACE(sizeof(struct tpacket_auxdata))];
682 } cmsg_buf;
683 #else /* defined(HAVE_PACKET_AUXDATA) && defined(HAVE_LINUX_TPACKET_AUXDATA_TP_VLAN_TCI) */
684 socklen_t fromlen;
685 #endif /* defined(HAVE_PACKET_AUXDATA) && defined(HAVE_LINUX_TPACKET_AUXDATA_TP_VLAN_TCI) */
686 int packet_len, caplen;
687 struct pcap_pkthdr pcap_header;
688
689 #ifdef HAVE_PF_PACKET_SOCKETS
690 /*
691 * If this is a cooked device, leave extra room for a
692 * fake packet header.
693 */
694 if (handle->md.cooked)
695 offset = SLL_HDR_LEN;
696 else
697 offset = 0;
698 #else
699 /*
700 * This system doesn't have PF_PACKET sockets, so it doesn't
701 * support cooked devices.
702 */
703 offset = 0;
704 #endif
705
706 /*
707 * Receive a single packet from the kernel.
708 * We ignore EINTR, as that might just be due to a signal
709 * being delivered - if the signal should interrupt the
710 * loop, the signal handler should call pcap_breakloop()
711 * to set handle->break_loop (we ignore it on other
712 * platforms as well).
713 * We also ignore ENETDOWN, so that we can continue to
714 * capture traffic if the interface goes down and comes
715 * back up again; comments in the kernel indicate that
716 * we'll just block waiting for packets if we try to
717 * receive from a socket that delivered ENETDOWN, and,
718 * if we're using a memory-mapped buffer, we won't even
719 * get notified of "network down" events.
720 */
721 bp = handle->buffer + handle->offset;
722
723 #if defined(HAVE_PACKET_AUXDATA) && defined(HAVE_LINUX_TPACKET_AUXDATA_TP_VLAN_TCI)
724 msg.msg_name = &from;
725 msg.msg_namelen = sizeof(from);
726 msg.msg_iov = &iov;
727 msg.msg_iovlen = 1;
728 msg.msg_control = &cmsg_buf;
729 msg.msg_controllen = sizeof(cmsg_buf);
730 msg.msg_flags = 0;
731
732 iov.iov_len = handle->bufsize - offset;
733 iov.iov_base = bp + offset;
734 #endif /* defined(HAVE_PACKET_AUXDATA) && defined(HAVE_LINUX_TPACKET_AUXDATA_TP_VLAN_TCI) */
735
736 do {
737 /*
738 * Has "pcap_breakloop()" been called?
739 */
740 if (handle->break_loop) {
741 /*
742 * Yes - clear the flag that indicates that it
743 * has, and return -2 as an indication that we
744 * were told to break out of the loop.
745 */
746 handle->break_loop = 0;
747 return -2;
748 }
749
750 #if defined(HAVE_PACKET_AUXDATA) && defined(HAVE_LINUX_TPACKET_AUXDATA_TP_VLAN_TCI)
751 packet_len = recvmsg(handle->fd, &msg, MSG_TRUNC);
752 #else /* defined(HAVE_PACKET_AUXDATA) && defined(HAVE_LINUX_TPACKET_AUXDATA_TP_VLAN_TCI) */
753 fromlen = sizeof(from);
754 packet_len = recvfrom(
755 handle->fd, bp + offset,
756 handle->bufsize - offset, MSG_TRUNC,
757 (struct sockaddr *) &from, &fromlen);
758 #endif /* defined(HAVE_PACKET_AUXDATA) && defined(HAVE_LINUX_TPACKET_AUXDATA_TP_VLAN_TCI) */
759 } while (packet_len == -1 && (errno == EINTR || errno == ENETDOWN));
760
761 /* Check if an error occured */
762
763 if (packet_len == -1) {
764 if (errno == EAGAIN)
765 return 0; /* no packet there */
766 else {
767 snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
768 "recvfrom: %s", pcap_strerror(errno));
769 return -1;
770 }
771 }
772
773 #ifdef HAVE_PF_PACKET_SOCKETS
774 if (!handle->md.sock_packet) {
775 /*
776 * Unfortunately, there is a window between socket() and
777 * bind() where the kernel may queue packets from any
778 * interface. If we're bound to a particular interface,
779 * discard packets not from that interface.
780 *
781 * (If socket filters are supported, we could do the
782 * same thing we do when changing the filter; however,
783 * that won't handle packet sockets without socket
784 * filter support, and it's a bit more complicated.
785 * It would save some instructions per packet, however.)
786 */
787 if (handle->md.ifindex != -1 &&
788 from.sll_ifindex != handle->md.ifindex)
789 return 0;
790
791 /*
792 * Do checks based on packet direction.
793 * We can only do this if we're using PF_PACKET; the
794 * address returned for SOCK_PACKET is a "sockaddr_pkt"
795 * which lacks the relevant packet type information.
796 */
797 if (from.sll_pkttype == PACKET_OUTGOING) {
798 /*
799 * Outgoing packet.
800 * If this is from the loopback device, reject it;
801 * we'll see the packet as an incoming packet as well,
802 * and we don't want to see it twice.
803 */
804 if (from.sll_ifindex == handle->md.lo_ifindex)
805 return 0;
806
807 /*
808 * If the user only wants incoming packets, reject it.
809 */
810 if (handle->direction == PCAP_D_IN)
811 return 0;
812 } else {
813 /*
814 * Incoming packet.
815 * If the user only wants outgoing packets, reject it.
816 */
817 if (handle->direction == PCAP_D_OUT)
818 return 0;
819 }
820 }
821 #endif
822
823 #ifdef HAVE_PF_PACKET_SOCKETS
824 /*
825 * If this is a cooked device, fill in the fake packet header.
826 */
827 if (handle->md.cooked) {
828 /*
829 * Add the length of the fake header to the length
830 * of packet data we read.
831 */
832 packet_len += SLL_HDR_LEN;
833
834 hdrp = (struct sll_header *)bp;
835 hdrp->sll_pkttype = map_packet_type_to_sll_type(from.sll_pkttype);
836 hdrp->sll_hatype = htons(from.sll_hatype);
837 hdrp->sll_halen = htons(from.sll_halen);
838 memcpy(hdrp->sll_addr, from.sll_addr,
839 (from.sll_halen > SLL_ADDRLEN) ?
840 SLL_ADDRLEN :
841 from.sll_halen);
842 hdrp->sll_protocol = from.sll_protocol;
843 }
844
845 #if defined(HAVE_PACKET_AUXDATA) && defined(HAVE_LINUX_TPACKET_AUXDATA_TP_VLAN_TCI)
846 for (cmsg = CMSG_FIRSTHDR(&msg); cmsg; cmsg = CMSG_NXTHDR(&msg, cmsg)) {
847 struct tpacket_auxdata *aux;
848 unsigned int len;
849 struct vlan_tag *tag;
850
851 if (cmsg->cmsg_len < CMSG_LEN(sizeof(struct tpacket_auxdata)) ||
852 cmsg->cmsg_level != SOL_PACKET ||
853 cmsg->cmsg_type != PACKET_AUXDATA)
854 continue;
855
856 aux = (struct tpacket_auxdata *)CMSG_DATA(cmsg);
857 if (aux->tp_vlan_tci == 0)
858 continue;
859
860 len = packet_len > iov.iov_len ? iov.iov_len : packet_len;
861 if (len < 2 * ETH_ALEN)
862 break;
863
864 bp -= VLAN_TAG_LEN;
865 memmove(bp, bp + VLAN_TAG_LEN, 2 * ETH_ALEN);
866
867 tag = (struct vlan_tag *)(bp + 2 * ETH_ALEN);
868 tag->vlan_tpid = htons(ETH_P_8021Q);
869 tag->vlan_tci = htons(aux->tp_vlan_tci);
870
871 packet_len += VLAN_TAG_LEN;
872 }
873 #endif /* defined(HAVE_PACKET_AUXDATA) && defined(HAVE_LINUX_TPACKET_AUXDATA_TP_VLAN_TCI) */
874 #endif /* HAVE_PF_PACKET_SOCKETS */
875
876 /*
877 * XXX: According to the kernel source we should get the real
878 * packet len if calling recvfrom with MSG_TRUNC set. It does
879 * not seem to work here :(, but it is supported by this code
880 * anyway.
881 * To be honest the code RELIES on that feature so this is really
882 * broken with 2.2.x kernels.
883 * I spend a day to figure out what's going on and I found out
884 * that the following is happening:
885 *
886 * The packet comes from a random interface and the packet_rcv
887 * hook is called with a clone of the packet. That code inserts
888 * the packet into the receive queue of the packet socket.
889 * If a filter is attached to that socket that filter is run
890 * first - and there lies the problem. The default filter always
891 * cuts the packet at the snaplen:
892 *
893 * # tcpdump -d
894 * (000) ret #68
895 *
896 * So the packet filter cuts down the packet. The recvfrom call
897 * says "hey, it's only 68 bytes, it fits into the buffer" with
898 * the result that we don't get the real packet length. This
899 * is valid at least until kernel 2.2.17pre6.
900 *
901 * We currently handle this by making a copy of the filter
902 * program, fixing all "ret" instructions with non-zero
903 * operands to have an operand of 65535 so that the filter
904 * doesn't truncate the packet, and supplying that modified
905 * filter to the kernel.
906 */
907
908 caplen = packet_len;
909 if (caplen > handle->snapshot)
910 caplen = handle->snapshot;
911
912 /* Run the packet filter if not using kernel filter */
913 if (!handle->md.use_bpf && handle->fcode.bf_insns) {
914 if (bpf_filter(handle->fcode.bf_insns, bp,
915 packet_len, caplen) == 0)
916 {
917 /* rejected by filter */
918 return 0;
919 }
920 }
921
922 /* Fill in our own header data */
923
924 if (ioctl(handle->fd, SIOCGSTAMP, &pcap_header.ts) == -1) {
925 snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
926 "SIOCGSTAMP: %s", pcap_strerror(errno));
927 return -1;
928 }
929 pcap_header.caplen = caplen;
930 pcap_header.len = packet_len;
931
932 /*
933 * Count the packet.
934 *
935 * Arguably, we should count them before we check the filter,
936 * as on many other platforms "ps_recv" counts packets
937 * handed to the filter rather than packets that passed
938 * the filter, but if filtering is done in the kernel, we
939 * can't get a count of packets that passed the filter,
940 * and that would mean the meaning of "ps_recv" wouldn't
941 * be the same on all Linux systems.
942 *
943 * XXX - it's not the same on all systems in any case;
944 * ideally, we should have a "get the statistics" call
945 * that supplies more counts and indicates which of them
946 * it supplies, so that we supply a count of packets
947 * handed to the filter only on platforms where that
948 * information is available.
949 *
950 * We count them here even if we can get the packet count
951 * from the kernel, as we can only determine at run time
952 * whether we'll be able to get it from the kernel (if
953 * HAVE_TPACKET_STATS isn't defined, we can't get it from
954 * the kernel, but if it is defined, the library might
955 * have been built with a 2.4 or later kernel, but we
956 * might be running on a 2.2[.x] kernel without Alexey
957 * Kuznetzov's turbopacket patches, and thus the kernel
958 * might not be able to supply those statistics). We
959 * could, I guess, try, when opening the socket, to get
960 * the statistics, and if we can not increment the count
961 * here, but it's not clear that always incrementing
962 * the count is more expensive than always testing a flag
963 * in memory.
964 *
965 * We keep the count in "md.packets_read", and use that for
966 * "ps_recv" if we can't get the statistics from the kernel.
967 * We do that because, if we *can* get the statistics from
968 * the kernel, we use "md.stat.ps_recv" and "md.stat.ps_drop"
969 * as running counts, as reading the statistics from the
970 * kernel resets the kernel statistics, and if we directly
971 * increment "md.stat.ps_recv" here, that means it will
972 * count packets *twice* on systems where we can get kernel
973 * statistics - once here, and once in pcap_stats_linux().
974 */
975 handle->md.packets_read++;
976
977 /* Call the user supplied callback function */
978 callback(userdata, &pcap_header, bp);
979
980 return 1;
981 }
982
983 static int
984 pcap_inject_linux(pcap_t *handle, const void *buf, size_t size)
985 {
986 int ret;
987
988 #ifdef HAVE_PF_PACKET_SOCKETS
989 if (!handle->md.sock_packet) {
990 /* PF_PACKET socket */
991 if (handle->md.ifindex == -1) {
992 /*
993 * We don't support sending on the "any" device.
994 */
995 strlcpy(handle->errbuf,
996 "Sending packets isn't supported on the \"any\" device",
997 PCAP_ERRBUF_SIZE);
998 return (-1);
999 }
1000
1001 if (handle->md.cooked) {
1002 /*
1003 * We don't support sending on the "any" device.
1004 *
1005 * XXX - how do you send on a bound cooked-mode
1006 * socket?
1007 * Is a "sendto()" required there?
1008 */
1009 strlcpy(handle->errbuf,
1010 "Sending packets isn't supported in cooked mode",
1011 PCAP_ERRBUF_SIZE);
1012 return (-1);
1013 }
1014 }
1015 #endif
1016
1017 ret = send(handle->fd, buf, size, 0);
1018 if (ret == -1) {
1019 snprintf(handle->errbuf, PCAP_ERRBUF_SIZE, "send: %s",
1020 pcap_strerror(errno));
1021 return (-1);
1022 }
1023 return (ret);
1024 }
1025
1026 /*
1027 * Get the statistics for the given packet capture handle.
1028 * Reports the number of dropped packets iff the kernel supports
1029 * the PACKET_STATISTICS "getsockopt()" argument (2.4 and later
1030 * kernels, and 2.2[.x] kernels with Alexey Kuznetzov's turbopacket
1031 * patches); otherwise, that information isn't available, and we lie
1032 * and report 0 as the count of dropped packets.
1033 */
1034 static int
1035 pcap_stats_linux(pcap_t *handle, struct pcap_stat *stats)
1036 {
1037 #ifdef HAVE_TPACKET_STATS
1038 struct tpacket_stats kstats;
1039 socklen_t len = sizeof (struct tpacket_stats);
1040 #endif
1041
1042 #ifdef HAVE_TPACKET_STATS
1043 /*
1044 * Try to get the packet counts from the kernel.
1045 */
1046 if (getsockopt(handle->fd, SOL_PACKET, PACKET_STATISTICS,
1047 &kstats, &len) > -1) {
1048 /*
1049 * On systems where the PACKET_STATISTICS "getsockopt()"
1050 * argument is supported on PF_PACKET sockets:
1051 *
1052 * "ps_recv" counts only packets that *passed* the
1053 * filter, not packets that didn't pass the filter.
1054 * This includes packets later dropped because we
1055 * ran out of buffer space.
1056 *
1057 * "ps_drop" counts packets dropped because we ran
1058 * out of buffer space. It doesn't count packets
1059 * dropped by the interface driver. It counts only
1060 * packets that passed the filter.
1061 *
1062 * Both statistics include packets not yet read from
1063 * the kernel by libpcap, and thus not yet seen by
1064 * the application.
1065 *
1066 * In "linux/net/packet/af_packet.c", at least in the
1067 * 2.4.9 kernel, "tp_packets" is incremented for every
1068 * packet that passes the packet filter *and* is
1069 * successfully queued on the socket; "tp_drops" is
1070 * incremented for every packet dropped because there's
1071 * not enough free space in the socket buffer.
1072 *
1073 * When the statistics are returned for a PACKET_STATISTICS
1074 * "getsockopt()" call, "tp_drops" is added to "tp_packets",
1075 * so that "tp_packets" counts all packets handed to
1076 * the PF_PACKET socket, including packets dropped because
1077 * there wasn't room on the socket buffer - but not
1078 * including packets that didn't pass the filter.
1079 *
1080 * In the BSD BPF, the count of received packets is
1081 * incremented for every packet handed to BPF, regardless
1082 * of whether it passed the filter.
1083 *
1084 * We can't make "pcap_stats()" work the same on both
1085 * platforms, but the best approximation is to return
1086 * "tp_packets" as the count of packets and "tp_drops"
1087 * as the count of drops.
1088 *
1089 * Keep a running total because each call to
1090 * getsockopt(handle->fd, SOL_PACKET, PACKET_STATISTICS, ....
1091 * resets the counters to zero.
1092 */
1093 handle->md.stat.ps_recv += kstats.tp_packets;
1094 handle->md.stat.ps_drop += kstats.tp_drops;
1095 *stats = handle->md.stat;
1096 return 0;
1097 }
1098 else
1099 {
1100 /*
1101 * If the error was EOPNOTSUPP, fall through, so that
1102 * if you build the library on a system with
1103 * "struct tpacket_stats" and run it on a system
1104 * that doesn't, it works as it does if the library
1105 * is built on a system without "struct tpacket_stats".
1106 */
1107 if (errno != EOPNOTSUPP) {
1108 snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
1109 "pcap_stats: %s", pcap_strerror(errno));
1110 return -1;
1111 }
1112 }
1113 #endif
1114 /*
1115 * On systems where the PACKET_STATISTICS "getsockopt()" argument
1116 * is not supported on PF_PACKET sockets:
1117 *
1118 * "ps_recv" counts only packets that *passed* the filter,
1119 * not packets that didn't pass the filter. It does not
1120 * count packets dropped because we ran out of buffer
1121 * space.
1122 *
1123 * "ps_drop" is not supported.
1124 *
1125 * "ps_recv" doesn't include packets not yet read from
1126 * the kernel by libpcap.
1127 *
1128 * We maintain the count of packets processed by libpcap in
1129 * "md.packets_read", for reasons described in the comment
1130 * at the end of pcap_read_packet(). We have no idea how many
1131 * packets were dropped.
1132 */
1133 stats->ps_recv = handle->md.packets_read;
1134 stats->ps_drop = 0;
1135 return 0;
1136 }
1137
1138 /*
1139 * Description string for the "any" device.
1140 */
1141 static const char any_descr[] = "Pseudo-device that captures on all interfaces";
1142
1143 int
1144 pcap_platform_finddevs(pcap_if_t **alldevsp, char *errbuf)
1145 {
1146 if (pcap_add_if(alldevsp, "any", 0, any_descr, errbuf) < 0)
1147 return (-1);
1148
1149 #ifdef HAVE_DAG_API
1150 if (dag_platform_finddevs(alldevsp, errbuf) < 0)
1151 return (-1);
1152 #endif /* HAVE_DAG_API */
1153
1154 #ifdef HAVE_SEPTEL_API
1155 if (septel_platform_finddevs(alldevsp, errbuf) < 0)
1156 return (-1);
1157 #endif /* HAVE_SEPTEL_API */
1158
1159 #ifdef PCAP_SUPPORT_BT
1160 if (bt_platform_finddevs(alldevsp, errbuf) < 0)
1161 return (-1);
1162 #endif
1163
1164 #ifdef PCAP_SUPPORT_USB
1165 if (usb_platform_finddevs(alldevsp, errbuf) < 0)
1166 return (-1);
1167 #endif
1168
1169 return (0);
1170 }
1171
1172 /*
1173 * Attach the given BPF code to the packet capture device.
1174 */
1175 static int
1176 pcap_setfilter_linux(pcap_t *handle, struct bpf_program *filter)
1177 {
1178 #ifdef SO_ATTACH_FILTER
1179 struct sock_fprog fcode;
1180 int can_filter_in_kernel;
1181 int err = 0;
1182 #endif
1183
1184 if (!handle)
1185 return -1;
1186 if (!filter) {
1187 strncpy(handle->errbuf, "setfilter: No filter specified",
1188 PCAP_ERRBUF_SIZE);
1189 return -1;
1190 }
1191
1192 /* Make our private copy of the filter */
1193
1194 if (install_bpf_program(handle, filter) < 0)
1195 /* install_bpf_program() filled in errbuf */
1196 return -1;
1197
1198 /*
1199 * Run user level packet filter by default. Will be overriden if
1200 * installing a kernel filter succeeds.
1201 */
1202 handle->md.use_bpf = 0;
1203
1204 /* Install kernel level filter if possible */
1205
1206 #ifdef SO_ATTACH_FILTER
1207 #ifdef USHRT_MAX
1208 if (handle->fcode.bf_len > USHRT_MAX) {
1209 /*
1210 * fcode.len is an unsigned short for current kernel.
1211 * I have yet to see BPF-Code with that much
1212 * instructions but still it is possible. So for the
1213 * sake of correctness I added this check.
1214 */
1215 fprintf(stderr, "Warning: Filter too complex for kernel\n");
1216 fcode.len = 0;
1217 fcode.filter = NULL;
1218 can_filter_in_kernel = 0;
1219 } else
1220 #endif /* USHRT_MAX */
1221 {
1222 /*
1223 * Oh joy, the Linux kernel uses struct sock_fprog instead
1224 * of struct bpf_program and of course the length field is
1225 * of different size. Pointed out by Sebastian
1226 *
1227 * Oh, and we also need to fix it up so that all "ret"
1228 * instructions with non-zero operands have 65535 as the
1229 * operand, and so that, if we're in cooked mode, all
1230 * memory-reference instructions use special magic offsets
1231 * in references to the link-layer header and assume that
1232 * the link-layer payload begins at 0; "fix_program()"
1233 * will do that.
1234 */
1235 switch (fix_program(handle, &fcode)) {
1236
1237 case -1:
1238 default:
1239 /*
1240 * Fatal error; just quit.
1241 * (The "default" case shouldn't happen; we
1242 * return -1 for that reason.)
1243 */
1244 return -1;
1245
1246 case 0:
1247 /*
1248 * The program performed checks that we can't make
1249 * work in the kernel.
1250 */
1251 can_filter_in_kernel = 0;
1252 break;
1253
1254 case 1:
1255 /*
1256 * We have a filter that'll work in the kernel.
1257 */
1258 can_filter_in_kernel = 1;
1259 break;
1260 }
1261 }
1262
1263 if (can_filter_in_kernel) {
1264 if ((err = set_kernel_filter(handle, &fcode)) == 0)
1265 {
1266 /* Installation succeded - using kernel filter. */
1267 handle->md.use_bpf = 1;
1268 }
1269 else if (err == -1) /* Non-fatal error */
1270 {
1271 /*
1272 * Print a warning if we weren't able to install
1273 * the filter for a reason other than "this kernel
1274 * isn't configured to support socket filters.
1275 */
1276 if (errno != ENOPROTOOPT && errno != EOPNOTSUPP) {
1277 fprintf(stderr,
1278 "Warning: Kernel filter failed: %s\n",
1279 pcap_strerror(errno));
1280 }
1281 }
1282 }
1283
1284 /*
1285 * If we're not using the kernel filter, get rid of any kernel
1286 * filter that might've been there before, e.g. because the
1287 * previous filter could work in the kernel, or because some other
1288 * code attached a filter to the socket by some means other than
1289 * calling "pcap_setfilter()". Otherwise, the kernel filter may
1290 * filter out packets that would pass the new userland filter.
1291 */
1292 if (!handle->md.use_bpf)
1293 reset_kernel_filter(handle);
1294
1295 /*
1296 * Free up the copy of the filter that was made by "fix_program()".
1297 */
1298 if (fcode.filter != NULL)
1299 free(fcode.filter);
1300
1301 if (err == -2)
1302 /* Fatal error */
1303 return -1;
1304 #endif /* SO_ATTACH_FILTER */
1305
1306 return 0;
1307 }
1308
1309 /*
1310 * Set direction flag: Which packets do we accept on a forwarding
1311 * single device? IN, OUT or both?
1312 */
1313 static int
1314 pcap_setdirection_linux(pcap_t *handle, pcap_direction_t d)
1315 {
1316 #ifdef HAVE_PF_PACKET_SOCKETS
1317 if (!handle->md.sock_packet) {
1318 handle->direction = d;
1319 return 0;
1320 }
1321 #endif
1322 /*
1323 * We're not using PF_PACKET sockets, so we can't determine
1324 * the direction of the packet.
1325 */
1326 snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
1327 "Setting direction is not supported on SOCK_PACKET sockets");
1328 return -1;
1329 }
1330
1331
1332 #ifdef HAVE_PF_PACKET_SOCKETS
1333 /*
1334 * Map the PACKET_ value to a LINUX_SLL_ value; we
1335 * want the same numerical value to be used in
1336 * the link-layer header even if the numerical values
1337 * for the PACKET_ #defines change, so that programs
1338 * that look at the packet type field will always be
1339 * able to handle DLT_LINUX_SLL captures.
1340 */
1341 static short int
1342 map_packet_type_to_sll_type(short int sll_pkttype)
1343 {
1344 switch (sll_pkttype) {
1345
1346 case PACKET_HOST:
1347 return htons(LINUX_SLL_HOST);
1348
1349 case PACKET_BROADCAST:
1350 return htons(LINUX_SLL_BROADCAST);
1351
1352 case PACKET_MULTICAST:
1353 return htons(LINUX_SLL_MULTICAST);
1354
1355 case PACKET_OTHERHOST:
1356 return htons(LINUX_SLL_OTHERHOST);
1357
1358 case PACKET_OUTGOING:
1359 return htons(LINUX_SLL_OUTGOING);
1360
1361 default:
1362 return -1;
1363 }
1364 }
1365 #endif
1366
1367 /*
1368 * Linux uses the ARP hardware type to identify the type of an
1369 * interface. pcap uses the DLT_xxx constants for this. This
1370 * function takes a pointer to a "pcap_t", and an ARPHRD_xxx
1371 * constant, as arguments, and sets "handle->linktype" to the
1372 * appropriate DLT_XXX constant and sets "handle->offset" to
1373 * the appropriate value (to make "handle->offset" plus link-layer
1374 * header length be a multiple of 4, so that the link-layer payload
1375 * will be aligned on a 4-byte boundary when capturing packets).
1376 * (If the offset isn't set here, it'll be 0; add code as appropriate
1377 * for cases where it shouldn't be 0.)
1378 *
1379 * If "cooked_ok" is non-zero, we can use DLT_LINUX_SLL and capture
1380 * in cooked mode; otherwise, we can't use cooked mode, so we have
1381 * to pick some type that works in raw mode, or fail.
1382 *
1383 * Sets the link type to -1 if unable to map the type.
1384 */
1385 static void map_arphrd_to_dlt(pcap_t *handle, int arptype, int cooked_ok)
1386 {
1387 switch (arptype) {
1388
1389 case ARPHRD_ETHER:
1390 /*
1391 * This is (presumably) a real Ethernet capture; give it a
1392 * link-layer-type list with DLT_EN10MB and DLT_DOCSIS, so
1393 * that an application can let you choose it, in case you're
1394 * capturing DOCSIS traffic that a Cisco Cable Modem
1395 * Termination System is putting out onto an Ethernet (it
1396 * doesn't put an Ethernet header onto the wire, it puts raw
1397 * DOCSIS frames out on the wire inside the low-level
1398 * Ethernet framing).
1399 *
1400 * XXX - are there any sorts of "fake Ethernet" that have
1401 * ARPHRD_ETHER but that *shouldn't offer DLT_DOCSIS as
1402 * a Cisco CMTS won't put traffic onto it or get traffic
1403 * bridged onto it? ISDN is handled in "activate_new()",
1404 * as we fall back on cooked mode there; are there any
1405 * others?
1406 */
1407 handle->dlt_list = (u_int *) malloc(sizeof(u_int) * 2);
1408 /*
1409 * If that fails, just leave the list empty.
1410 */
1411 if (handle->dlt_list != NULL) {
1412 handle->dlt_list[0] = DLT_EN10MB;
1413 handle->dlt_list[1] = DLT_DOCSIS;
1414 handle->dlt_count = 2;
1415 }
1416 /* FALLTHROUGH */
1417
1418 case ARPHRD_METRICOM:
1419 case ARPHRD_LOOPBACK:
1420 handle->linktype = DLT_EN10MB;
1421 handle->offset = 2;
1422 break;
1423
1424 case ARPHRD_EETHER:
1425 handle->linktype = DLT_EN3MB;
1426 break;
1427
1428 case ARPHRD_AX25:
1429 handle->linktype = DLT_AX25_KISS;
1430 break;
1431
1432 case ARPHRD_PRONET:
1433 handle->linktype = DLT_PRONET;
1434 break;
1435
1436 case ARPHRD_CHAOS:
1437 handle->linktype = DLT_CHAOS;
1438 break;
1439
1440 #ifndef ARPHRD_IEEE802_TR
1441 #define ARPHRD_IEEE802_TR 800 /* From Linux 2.4 */
1442 #endif
1443 case ARPHRD_IEEE802_TR:
1444 case ARPHRD_IEEE802:
1445 handle->linktype = DLT_IEEE802;
1446 handle->offset = 2;
1447 break;
1448
1449 case ARPHRD_ARCNET:
1450 handle->linktype = DLT_ARCNET_LINUX;
1451 break;
1452
1453 #ifndef ARPHRD_FDDI /* From Linux 2.2.13 */
1454 #define ARPHRD_FDDI 774
1455 #endif
1456 case ARPHRD_FDDI:
1457 handle->linktype = DLT_FDDI;
1458 handle->offset = 3;
1459 break;
1460
1461 #ifndef ARPHRD_ATM /* FIXME: How to #include this? */
1462 #define ARPHRD_ATM 19
1463 #endif
1464 case ARPHRD_ATM:
1465 /*
1466 * The Classical IP implementation in ATM for Linux
1467 * supports both what RFC 1483 calls "LLC Encapsulation",
1468 * in which each packet has an LLC header, possibly
1469 * with a SNAP header as well, prepended to it, and
1470 * what RFC 1483 calls "VC Based Multiplexing", in which
1471 * different virtual circuits carry different network
1472 * layer protocols, and no header is prepended to packets.
1473 *
1474 * They both have an ARPHRD_ type of ARPHRD_ATM, so
1475 * you can't use the ARPHRD_ type to find out whether
1476 * captured packets will have an LLC header, and,
1477 * while there's a socket ioctl to *set* the encapsulation
1478 * type, there's no ioctl to *get* the encapsulation type.
1479 *
1480 * This means that
1481 *
1482 * programs that dissect Linux Classical IP frames
1483 * would have to check for an LLC header and,
1484 * depending on whether they see one or not, dissect
1485 * the frame as LLC-encapsulated or as raw IP (I
1486 * don't know whether there's any traffic other than
1487 * IP that would show up on the socket, or whether
1488 * there's any support for IPv6 in the Linux
1489 * Classical IP code);
1490 *
1491 * filter expressions would have to compile into
1492 * code that checks for an LLC header and does
1493 * the right thing.
1494 *
1495 * Both of those are a nuisance - and, at least on systems
1496 * that support PF_PACKET sockets, we don't have to put
1497 * up with those nuisances; instead, we can just capture
1498 * in cooked mode. That's what we'll do, if we can.
1499 * Otherwise, we'll just fail.
1500 */
1501 if (cooked_ok)
1502 handle->linktype = DLT_LINUX_SLL;
1503 else
1504 handle->linktype = -1;
1505 break;
1506
1507 #ifndef ARPHRD_IEEE80211 /* From Linux 2.4.6 */
1508 #define ARPHRD_IEEE80211 801
1509 #endif
1510 case ARPHRD_IEEE80211:
1511 handle->linktype = DLT_IEEE802_11;
1512 break;
1513
1514 #ifndef ARPHRD_IEEE80211_PRISM /* From Linux 2.4.18 */
1515 #define ARPHRD_IEEE80211_PRISM 802
1516 #endif
1517 case ARPHRD_IEEE80211_PRISM:
1518 handle->linktype = DLT_PRISM_HEADER;
1519 break;
1520
1521 #ifndef ARPHRD_IEEE80211_RADIOTAP /* new */
1522 #define ARPHRD_IEEE80211_RADIOTAP 803
1523 #endif
1524 case ARPHRD_IEEE80211_RADIOTAP:
1525 handle->linktype = DLT_IEEE802_11_RADIO;
1526 break;
1527
1528 case ARPHRD_PPP:
1529 /*
1530 * Some PPP code in the kernel supplies no link-layer
1531 * header whatsoever to PF_PACKET sockets; other PPP
1532 * code supplies PPP link-layer headers ("syncppp.c");
1533 * some PPP code might supply random link-layer
1534 * headers (PPP over ISDN - there's code in Ethereal,
1535 * for example, to cope with PPP-over-ISDN captures
1536 * with which the Ethereal developers have had to cope,
1537 * heuristically trying to determine which of the
1538 * oddball link-layer headers particular packets have).
1539 *
1540 * As such, we just punt, and run all PPP interfaces
1541 * in cooked mode, if we can; otherwise, we just treat
1542 * it as DLT_RAW, for now - if somebody needs to capture,
1543 * on a 2.0[.x] kernel, on PPP devices that supply a
1544 * link-layer header, they'll have to add code here to
1545 * map to the appropriate DLT_ type (possibly adding a
1546 * new DLT_ type, if necessary).
1547 */
1548 if (cooked_ok)
1549 handle->linktype = DLT_LINUX_SLL;
1550 else {
1551 /*
1552 * XXX - handle ISDN types here? We can't fall
1553 * back on cooked sockets, so we'd have to
1554 * figure out from the device name what type of
1555 * link-layer encapsulation it's using, and map
1556 * that to an appropriate DLT_ value, meaning
1557 * we'd map "isdnN" devices to DLT_RAW (they
1558 * supply raw IP packets with no link-layer
1559 * header) and "isdY" devices to a new DLT_I4L_IP
1560 * type that has only an Ethernet packet type as
1561 * a link-layer header.
1562 *
1563 * But sometimes we seem to get random crap
1564 * in the link-layer header when capturing on
1565 * ISDN devices....
1566 */
1567 handle->linktype = DLT_RAW;
1568 }
1569 break;
1570
1571 #ifndef ARPHRD_CISCO
1572 #define ARPHRD_CISCO 513 /* previously ARPHRD_HDLC */
1573 #endif
1574 case ARPHRD_CISCO:
1575 handle->linktype = DLT_C_HDLC;
1576 break;
1577
1578 /* Not sure if this is correct for all tunnels, but it
1579 * works for CIPE */
1580 case ARPHRD_TUNNEL:
1581 #ifndef ARPHRD_SIT
1582 #define ARPHRD_SIT 776 /* From Linux 2.2.13 */
1583 #endif
1584 case ARPHRD_SIT:
1585 case ARPHRD_CSLIP:
1586 case ARPHRD_SLIP6:
1587 case ARPHRD_CSLIP6:
1588 case ARPHRD_ADAPT:
1589 case ARPHRD_SLIP:
1590 #ifndef ARPHRD_RAWHDLC
1591 #define ARPHRD_RAWHDLC 518
1592 #endif
1593 case ARPHRD_RAWHDLC:
1594 #ifndef ARPHRD_DLCI
1595 #define ARPHRD_DLCI 15
1596 #endif
1597 case ARPHRD_DLCI:
1598 /*
1599 * XXX - should some of those be mapped to DLT_LINUX_SLL
1600 * instead? Should we just map all of them to DLT_LINUX_SLL?
1601 */
1602 handle->linktype = DLT_RAW;
1603 break;
1604
1605 #ifndef ARPHRD_FRAD
1606 #define ARPHRD_FRAD 770
1607 #endif
1608 case ARPHRD_FRAD:
1609 handle->linktype = DLT_FRELAY;
1610 break;
1611
1612 case ARPHRD_LOCALTLK:
1613 handle->linktype = DLT_LTALK;
1614 break;
1615
1616 #ifndef ARPHRD_FCPP
1617 #define ARPHRD_FCPP 784
1618 #endif
1619 case ARPHRD_FCPP:
1620 #ifndef ARPHRD_FCAL
1621 #define ARPHRD_FCAL 785
1622 #endif
1623 case ARPHRD_FCAL:
1624 #ifndef ARPHRD_FCPL
1625 #define ARPHRD_FCPL 786
1626 #endif
1627 case ARPHRD_FCPL:
1628 #ifndef ARPHRD_FCFABRIC
1629 #define ARPHRD_FCFABRIC 787
1630 #endif
1631 case ARPHRD_FCFABRIC:
1632 /*
1633 * We assume that those all mean RFC 2625 IP-over-
1634 * Fibre Channel, with the RFC 2625 header at
1635 * the beginning of the packet.
1636 */
1637 handle->linktype = DLT_IP_OVER_FC;
1638 break;
1639
1640 #ifndef ARPHRD_IRDA
1641 #define ARPHRD_IRDA 783
1642 #endif
1643 case ARPHRD_IRDA:
1644 /* Don't expect IP packet out of this interfaces... */
1645 handle->linktype = DLT_LINUX_IRDA;
1646 /* We need to save packet direction for IrDA decoding,
1647 * so let's use "Linux-cooked" mode. Jean II */
1648 //handle->md.cooked = 1;
1649 break;
1650
1651 /* ARPHRD_LAPD is unofficial and randomly allocated, if reallocation
1652 * is needed, please report it to <daniele@orlandi.com> */
1653 #ifndef ARPHRD_LAPD
1654 #define ARPHRD_LAPD 8445
1655 #endif
1656 case ARPHRD_LAPD:
1657 /* Don't expect IP packet out of this interfaces... */
1658 handle->linktype = DLT_LINUX_LAPD;
1659 break;
1660
1661 #ifndef ARPHRD_NONE
1662 #define ARPHRD_NONE 0xFFFE
1663 #endif
1664 case ARPHRD_NONE:
1665 /*
1666 * No link-layer header; packets are just IP
1667 * packets, so use DLT_RAW.
1668 */
1669 handle->linktype = DLT_RAW;
1670 break;
1671
1672 default:
1673 handle->linktype = -1;
1674 break;
1675 }
1676 }
1677
1678 /* ===== Functions to interface to the newer kernels ================== */
1679
1680 /*
1681 * Try to open a packet socket using the new kernel PF_PACKET interface.
1682 * Returns 1 on success, 0 on an error that means the new interface isn't
1683 * present (so the old SOCK_PACKET interface should be tried), and a
1684 * PCAP_ERROR_ value on an error that means that the old mechanism won't
1685 * work either (so it shouldn't be tried).
1686 */
1687 static int
1688 activate_new(pcap_t *handle)
1689 {
1690 #ifdef HAVE_PF_PACKET_SOCKETS
1691 const char *device = handle->opt.source;
1692 int is_any_device = (strcmp(device, "any") == 0);
1693 int sock_fd = -1, arptype, val;
1694 int err = 0;
1695 struct packet_mreq mr;
1696
1697 /*
1698 * Open a socket with protocol family packet. If the
1699 * "any" device was specified, we open a SOCK_DGRAM
1700 * socket for the cooked interface, otherwise we first
1701 * try a SOCK_RAW socket for the raw interface.
1702 */
1703 sock_fd = is_any_device ?
1704 socket(PF_PACKET, SOCK_DGRAM, htons(ETH_P_ALL)) :
1705 socket(PF_PACKET, SOCK_RAW, htons(ETH_P_ALL));
1706
1707 if (sock_fd == -1) {
1708 snprintf(handle->errbuf, PCAP_ERRBUF_SIZE, "socket: %s",
1709 pcap_strerror(errno) );
1710 return 0; /* try old mechanism */
1711 }
1712
1713 /* It seems the kernel supports the new interface. */
1714 handle->md.sock_packet = 0;
1715
1716 /*
1717 * Get the interface index of the loopback device.
1718 * If the attempt fails, don't fail, just set the
1719 * "md.lo_ifindex" to -1.
1720 *
1721 * XXX - can there be more than one device that loops
1722 * packets back, i.e. devices other than "lo"? If so,
1723 * we'd need to find them all, and have an array of
1724 * indices for them, and check all of them in
1725 * "pcap_read_packet()".
1726 */
1727 handle->md.lo_ifindex = iface_get_id(sock_fd, "lo", handle->errbuf);
1728
1729 /*
1730 * Default value for offset to align link-layer payload
1731 * on a 4-byte boundary.
1732 */
1733 handle->offset = 0;
1734
1735 /*
1736 * What kind of frames do we have to deal with? Fall back
1737 * to cooked mode if we have an unknown interface type
1738 * or a type we know doesn't work well in raw mode.
1739 */
1740 if (!is_any_device) {
1741 /* Assume for now we don't need cooked mode. */
1742 handle->md.cooked = 0;
1743
1744 if (handle->opt.rfmon) {
1745 /*
1746 * We were asked to turn on monitor mode.
1747 * Do so before we get the link-layer type,
1748 * because entering monitor mode could change
1749 * the link-layer type.
1750 */
1751 err = enter_rfmon_mode_wext(handle, sock_fd, device);
1752 if (err < 0) {
1753 /* Hard failure */
1754 close(sock_fd);
1755 return err;
1756 }
1757 if (err == 0) {
1758 /*
1759 * Nothing worked for turning monitor mode
1760 * on.
1761 */
1762 close(sock_fd);
1763 return PCAP_ERROR_RFMON_NOTSUP;
1764 }
1765 }
1766 arptype = iface_get_arptype(sock_fd, device, handle->errbuf);
1767 if (arptype < 0) {
1768 close(sock_fd);
1769 return arptype;
1770 }
1771 map_arphrd_to_dlt(handle, arptype, 1);
1772 if (handle->linktype == -1 ||
1773 handle->linktype == DLT_LINUX_SLL ||
1774 handle->linktype == DLT_LINUX_IRDA ||
1775 handle->linktype == DLT_LINUX_LAPD ||
1776 (handle->linktype == DLT_EN10MB &&
1777 (strncmp("isdn", device, 4) == 0 ||
1778 strncmp("isdY", device, 4) == 0))) {
1779 /*
1780 * Unknown interface type (-1), or a
1781 * device we explicitly chose to run
1782 * in cooked mode (e.g., PPP devices),
1783 * or an ISDN device (whose link-layer
1784 * type we can only determine by using
1785 * APIs that may be different on different
1786 * kernels) - reopen in cooked mode.
1787 */
1788 if (close(sock_fd) == -1) {
1789 snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
1790 "close: %s", pcap_strerror(errno));
1791 return PCAP_ERROR;
1792 }
1793 sock_fd = socket(PF_PACKET, SOCK_DGRAM,
1794 htons(ETH_P_ALL));
1795 if (sock_fd == -1) {
1796 snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
1797 "socket: %s", pcap_strerror(errno));
1798 return PCAP_ERROR;
1799 }
1800 handle->md.cooked = 1;
1801
1802 /*
1803 * Get rid of any link-layer type list
1804 * we allocated - this only supports cooked
1805 * capture.
1806 */
1807 if (handle->dlt_list != NULL) {
1808 free(handle->dlt_list);
1809 handle->dlt_list = NULL;
1810 handle->dlt_count = 0;
1811 }
1812
1813 if (handle->linktype == -1) {
1814 /*
1815 * Warn that we're falling back on
1816 * cooked mode; we may want to
1817 * update "map_arphrd_to_dlt()"
1818 * to handle the new type.
1819 */
1820 snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
1821 "arptype %d not "
1822 "supported by libpcap - "
1823 "falling back to cooked "
1824 "socket",
1825 arptype);
1826 }
1827
1828 /*
1829 * IrDA capture is not a real "cooked" capture,
1830 * it's IrLAP frames, not IP packets. The
1831 * same applies to LAPD capture.
1832 */
1833 if (handle->linktype != DLT_LINUX_IRDA &&
1834 handle->linktype != DLT_LINUX_LAPD)
1835 handle->linktype = DLT_LINUX_SLL;
1836 }
1837
1838 handle->md.ifindex = iface_get_id(sock_fd, device,
1839 handle->errbuf);
1840 if (handle->md.ifindex == -1) {
1841 close(sock_fd);
1842 return PCAP_ERROR;
1843 }
1844
1845 if ((err = iface_bind(sock_fd, handle->md.ifindex,
1846 handle->errbuf)) != 1) {
1847 close(sock_fd);
1848 if (err < 0)
1849 return err;
1850 else
1851 return 0; /* try old mechanism */
1852 }
1853 } else {
1854 /*
1855 * The "any" device.
1856 */
1857 if (handle->opt.rfmon) {
1858 /*
1859 * It doesn't support monitor mode.
1860 */
1861 return PCAP_ERROR_RFMON_NOTSUP;
1862 }
1863
1864 /*
1865 * It uses cooked mode.
1866 */
1867 handle->md.cooked = 1;
1868 handle->linktype = DLT_LINUX_SLL;
1869
1870 /*
1871 * We're not bound to a device.
1872 * For now, we're using this as an indication
1873 * that we can't transmit; stop doing that only
1874 * if we figure out how to transmit in cooked
1875 * mode.
1876 */
1877 handle->md.ifindex = -1;
1878 }
1879
1880 /*
1881 * Select promiscuous mode on if "promisc" is set.
1882 *
1883 * Do not turn allmulti mode on if we don't select
1884 * promiscuous mode - on some devices (e.g., Orinoco
1885 * wireless interfaces), allmulti mode isn't supported
1886 * and the driver implements it by turning promiscuous
1887 * mode on, and that screws up the operation of the
1888 * card as a normal networking interface, and on no
1889 * other platform I know of does starting a non-
1890 * promiscuous capture affect which multicast packets
1891 * are received by the interface.
1892 */
1893
1894 /*
1895 * Hmm, how can we set promiscuous mode on all interfaces?
1896 * I am not sure if that is possible at all. For now, we
1897 * silently ignore attempts to turn promiscuous mode on
1898 * for the "any" device (so you don't have to explicitly
1899 * disable it in programs such as tcpdump).
1900 */
1901
1902 if (!is_any_device && handle->opt.promisc) {
1903 memset(&mr, 0, sizeof(mr));
1904 mr.mr_ifindex = handle->md.ifindex;
1905 mr.mr_type = PACKET_MR_PROMISC;
1906 if (setsockopt(sock_fd, SOL_PACKET, PACKET_ADD_MEMBERSHIP,
1907 &mr, sizeof(mr)) == -1) {
1908 snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
1909 "setsockopt: %s", pcap_strerror(errno));
1910 close(sock_fd);
1911 return PCAP_ERROR;
1912 }
1913 }
1914
1915 /* Enable auxillary data if supported and reserve room for
1916 * reconstructing VLAN headers. */
1917 #ifdef HAVE_PACKET_AUXDATA
1918 val = 1;
1919 if (setsockopt(sock_fd, SOL_PACKET, PACKET_AUXDATA, &val,
1920 sizeof(val)) == -1 && errno != ENOPROTOOPT) {
1921 snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
1922 "setsockopt: %s", pcap_strerror(errno));
1923 close(sock_fd);
1924 return PCAP_ERROR;
1925 }
1926 handle->offset += VLAN_TAG_LEN;
1927 #endif /* HAVE_PACKET_AUXDATA */
1928
1929 /*
1930 * This is a 2.2[.x] or later kernel (we know that
1931 * because we're not using a SOCK_PACKET socket -
1932 * PF_PACKET is supported only in 2.2 and later
1933 * kernels).
1934 *
1935 * We can safely pass "recvfrom()" a byte count
1936 * based on the snapshot length.
1937 *
1938 * If we're in cooked mode, make the snapshot length
1939 * large enough to hold a "cooked mode" header plus
1940 * 1 byte of packet data (so we don't pass a byte
1941 * count of 0 to "recvfrom()").
1942 */
1943 if (handle->md.cooked) {
1944 if (handle->snapshot < SLL_HDR_LEN + 1)
1945 handle->snapshot = SLL_HDR_LEN + 1;
1946 }
1947 handle->bufsize = handle->snapshot;
1948
1949 /* Save the socket FD in the pcap structure */
1950 handle->fd = sock_fd;
1951
1952 return 1;
1953 #else
1954 strncpy(ebuf,
1955 "New packet capturing interface not supported by build "
1956 "environment", PCAP_ERRBUF_SIZE);
1957 return 0;
1958 #endif
1959 }
1960
1961 static int
1962 activate_mmap(pcap_t *handle)
1963 {
1964 #ifdef HAVE_PACKET_RING
1965 int ret;
1966
1967 if (handle->opt.buffer_size == 0) {
1968 /* by default request 2M for the ring buffer */
1969 handle->opt.buffer_size = 2*1024*1024;
1970 }
1971 ret = prepare_tpacket_socket(handle);
1972 if (ret != 1)
1973 return ret;
1974 ret = create_ring(handle);
1975 if (ret != 1)
1976 return ret;
1977
1978 /* override some defaults and inherit the other fields from
1979 * activate_new
1980 * handle->offset is used to get the current position into the rx ring
1981 * handle->cc is used to store the ring size */
1982 handle->read_op = pcap_read_linux_mmap;
1983 handle->cleanup_op = pcap_cleanup_linux_mmap;
1984 handle->setfilter_op = pcap_setfilter_linux_mmap;
1985 handle->setnonblock_op = pcap_setnonblock_mmap;
1986 handle->getnonblock_op = pcap_getnonblock_mmap;
1987 handle->selectable_fd = handle->fd;
1988 return 1;
1989 #else /* HAVE_PACKET_RING */
1990 return 0;
1991 #endif /* HAVE_PACKET_RING */
1992 }
1993
1994 #ifdef HAVE_PACKET_RING
1995 static int
1996 prepare_tpacket_socket(pcap_t *handle)
1997 {
1998 #ifdef HAVE_TPACKET2
1999 socklen_t len;
2000 int val;
2001 #endif
2002
2003 handle->md.tp_version = TPACKET_V1;
2004 handle->md.tp_hdrlen = sizeof(struct tpacket_hdr);
2005
2006 #ifdef HAVE_TPACKET2
2007 /* Probe whether kernel supports TPACKET_V2 */
2008 val = TPACKET_V2;
2009 len = sizeof(val);
2010 if (getsockopt(handle->fd, SOL_PACKET, PACKET_HDRLEN, &val, &len) < 0) {
2011 if (errno == ENOPROTOOPT)
2012 return 1; /* no - just drive on */
2013
2014 /* Yes - treat as a failure. */
2015 snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
2016 "can't get TPACKET_V2 header len on packet socket: %s",
2017 pcap_strerror(errno));
2018 return -1;
2019 }
2020 handle->md.tp_hdrlen = val;
2021
2022 val = TPACKET_V2;
2023 if (setsockopt(handle->fd, SOL_PACKET, PACKET_VERSION, &val,
2024 sizeof(val)) < 0) {
2025 snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
2026 "can't activate TPACKET_V2 on packet socket: %s",
2027 pcap_strerror(errno));
2028 return -1;
2029 }
2030 handle->md.tp_version = TPACKET_V2;
2031
2032 /* Reserve space for VLAN tag reconstruction */
2033 val = VLAN_TAG_LEN;
2034 if (setsockopt(handle->fd, SOL_PACKET, PACKET_RESERVE, &val,
2035 sizeof(val)) < 0) {
2036 snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
2037 "can't set up reserve on packet socket: %s",
2038 pcap_strerror(errno));
2039 return -1;
2040 }
2041
2042 #endif /* HAVE_TPACKET2 */
2043 return 1;
2044 }
2045
2046 static void
2047 compute_ring_block(int frame_size, unsigned *block_size, unsigned *frames_per_block)
2048 {
2049 /* compute the minumum block size that will handle this frame.
2050 * The block has to be page size aligned.
2051 * The max block size allowed by the kernel is arch-dependent and
2052 * it's not explicitly checked here. */
2053 *block_size = getpagesize();
2054 while (*block_size < frame_size)
2055 *block_size <<= 1;
2056
2057 *frames_per_block = *block_size/frame_size;
2058 }
2059
2060 static int
2061 create_ring(pcap_t *handle)
2062 {
2063 unsigned i, j, ringsize, frames_per_block;
2064 struct tpacket_req req;
2065
2066 /* Note that with large snapshot (say 64K) only a few frames
2067 * will be available in the ring even with pretty large ring size
2068 * (and a lot of memory will be unused).
2069 * The snap len should be carefully chosen to achive best
2070 * performance */
2071 req.tp_frame_size = TPACKET_ALIGN(handle->snapshot +
2072 TPACKET_ALIGN(handle->md.tp_hdrlen) +
2073 sizeof(struct sockaddr_ll));
2074 req.tp_frame_nr = handle->opt.buffer_size/req.tp_frame_size;
2075 compute_ring_block(req.tp_frame_size, &req.tp_block_size, &frames_per_block);
2076 req.tp_block_nr = req.tp_frame_nr / frames_per_block;
2077
2078 /* req.tp_frame_nr is requested to match frames_per_block*req.tp_block_nr */
2079 req.tp_frame_nr = req.tp_block_nr * frames_per_block;
2080
2081 /* ask the kernel to create the ring */
2082 retry:
2083 if (setsockopt(handle->fd, SOL_PACKET, PACKET_RX_RING,
2084 (void *) &req, sizeof(req))) {
2085 /* try to reduce requested ring size to prevent memory failure */
2086 if ((errno == ENOMEM) && (req.tp_block_nr > 1)) {
2087 req.tp_frame_nr >>= 1;
2088 req.tp_block_nr = req.tp_frame_nr/frames_per_block;
2089 goto retry;
2090 }
2091 if (errno == ENOPROTOOPT) {
2092 /*
2093 * We don't have ring buffer support in this kernel.
2094 */
2095 return 0;
2096 }
2097 snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
2098 "can't create rx ring on packet socket: %s",
2099 pcap_strerror(errno));
2100 return -1;
2101 }
2102
2103 /* memory map the rx ring */
2104 ringsize = req.tp_block_nr * req.tp_block_size;
2105 handle->bp = mmap(0, ringsize, PROT_READ| PROT_WRITE, MAP_SHARED,
2106 handle->fd, 0);
2107 if (handle->bp == MAP_FAILED) {
2108 snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
2109 "can't mmap rx ring: %s", pcap_strerror(errno));
2110
2111 /* clear the allocated ring on error*/
2112 destroy_ring(handle);
2113 return -1;
2114 }
2115
2116 /* allocate a ring for each frame header pointer*/
2117 handle->cc = req.tp_frame_nr;
2118 handle->buffer = malloc(handle->cc * sizeof(union thdr *));
2119 if (!handle->buffer) {
2120 snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
2121 "can't allocate ring of frame headers: %s",
2122 pcap_strerror(errno));
2123
2124 destroy_ring(handle);
2125 return -1;
2126 }
2127
2128 /* fill the header ring with proper frame ptr*/
2129 handle->offset = 0;
2130 for (i=0; i<req.tp_block_nr; ++i) {
2131 void *base = &handle->bp[i*req.tp_block_size];
2132 for (j=0; j<frames_per_block; ++j, ++handle->offset) {
2133 RING_GET_FRAME(handle) = base;
2134 base += req.tp_frame_size;
2135 }
2136 }
2137
2138 handle->bufsize = req.tp_frame_size;
2139 handle->offset = 0;
2140 return 1;
2141 }
2142
2143 /* free all ring related resources*/
2144 static void
2145 destroy_ring(pcap_t *handle)
2146 {
2147 /* tell the kernel to destroy the ring*/
2148 struct tpacket_req req;
2149 memset(&req, 0, sizeof(req));
2150 setsockopt(handle->fd, SOL_PACKET, PACKET_RX_RING,
2151 (void *) &req, sizeof(req));
2152
2153 /* if ring is mapped, unmap it*/
2154 if (handle->bp) {
2155 /* need to re-compute the ring size */
2156 unsigned frames_per_block, block_size;
2157 compute_ring_block(handle->bufsize, &block_size, &frames_per_block);
2158
2159 /* do not perform sanity check here: we can't recover any error */
2160 munmap(handle->bp, block_size * handle->cc / frames_per_block);
2161 handle->bp = 0;
2162 }
2163 }
2164
2165 static void
2166 pcap_cleanup_linux_mmap( pcap_t *handle )
2167 {
2168 destroy_ring(handle);
2169 pcap_cleanup_linux(handle);
2170 }
2171
2172
2173 static int
2174 pcap_getnonblock_mmap(pcap_t *p, char *errbuf)
2175 {
2176 /* use negative value of timeout to indicate non blocking ops */
2177 return (p->md.timeout<0);
2178 }
2179
2180 static int
2181 pcap_setnonblock_mmap(pcap_t *p, int nonblock, char *errbuf)
2182 {
2183 /* map each value to the corresponding 2's complement, to
2184 * preserve the timeout value provided with pcap_set_timeout */
2185 if (nonblock) {
2186 if (p->md.timeout > 0)
2187 p->md.timeout = p->md.timeout*-1 - 1;
2188 } else
2189 if (p->md.timeout < 0)
2190 p->md.timeout = (p->md.timeout+1)*-1;
2191 return 0;
2192 }
2193
2194 static inline union thdr *
2195 pcap_get_ring_frame(pcap_t *handle, int status)
2196 {
2197 union thdr h;
2198
2199 h.raw = RING_GET_FRAME(handle);
2200 switch (handle->md.tp_version) {
2201 case TPACKET_V1:
2202 if (status != (h.h1->tp_status ? TP_STATUS_USER :
2203 TP_STATUS_KERNEL))
2204 return NULL;
2205 break;
2206 #ifdef HAVE_TPACKET2
2207 case TPACKET_V2:
2208 if (status != (h.h2->tp_status ? TP_STATUS_USER :
2209 TP_STATUS_KERNEL))
2210 return NULL;
2211 break;
2212 #endif
2213 }
2214 return h.raw;
2215 }
2216
2217 static int
2218 pcap_read_linux_mmap(pcap_t *handle, int max_packets, pcap_handler callback,
2219 u_char *user)
2220 {
2221 int pkts = 0;
2222
2223 /* wait for frames availability.*/
2224 if ((handle->md.timeout >= 0) &&
2225 !pcap_get_ring_frame(handle, TP_STATUS_USER)) {
2226 struct pollfd pollinfo;
2227 int ret;
2228
2229 pollinfo.fd = handle->fd;
2230 pollinfo.events = POLLIN;
2231
2232 do {
2233 /* poll() requires a negative timeout to wait forever */
2234 ret = poll(&pollinfo, 1, (handle->md.timeout > 0)?
2235 handle->md.timeout: -1);
2236 if ((ret < 0) && (errno != EINTR)) {
2237 snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
2238 "can't poll on packet socket fd %d: %d-%s",
2239 handle->fd, errno, pcap_strerror(errno));
2240 return -1;
2241 }
2242 /* check for break loop condition on interrupted syscall*/
2243 if (handle->break_loop) {
2244 handle->break_loop = 0;
2245 return -2;
2246 }
2247 } while (ret < 0);
2248 }
2249
2250 /* non-positive values of max_packets are used to require all
2251 * packets currently available in the ring */
2252 while ((pkts < max_packets) || (max_packets <= 0)) {
2253 int run_bpf;
2254 struct sockaddr_ll *sll;
2255 struct pcap_pkthdr pcaphdr;
2256 unsigned char *bp;
2257 union thdr h;
2258 unsigned int tp_len;
2259 unsigned int tp_mac;
2260 unsigned int tp_snaplen;
2261 unsigned int tp_sec;
2262 unsigned int tp_usec;
2263
2264 h.raw = pcap_get_ring_frame(handle, TP_STATUS_USER);
2265 if (!h.raw)
2266 break;
2267
2268 switch (handle->md.tp_version) {
2269 case TPACKET_V1:
2270 tp_len = h.h1->tp_len;
2271 tp_mac = h.h1->tp_mac;
2272 tp_snaplen = h.h1->tp_snaplen;
2273 tp_sec = h.h1->tp_sec;
2274 tp_usec = h.h1->tp_usec;
2275 break;
2276 #ifdef HAVE_TPACKET2
2277 case TPACKET_V2:
2278 tp_len = h.h2->tp_len;
2279 tp_mac = h.h2->tp_mac;
2280 tp_snaplen = h.h2->tp_snaplen;
2281 tp_sec = h.h2->tp_sec;
2282 tp_usec = h.h2->tp_nsec / 1000;
2283 break;
2284 #endif
2285 default:
2286 snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
2287 "unsupported tpacket version %d",
2288 handle->md.tp_version);
2289 return -1;
2290 }
2291 /* perform sanity check on internal offset. */
2292 if (tp_mac + tp_snaplen > handle->bufsize) {
2293 snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
2294 "corrupted frame on kernel ring mac "
2295 "offset %d + caplen %d > frame len %d",
2296 tp_mac, tp_snaplen, handle->bufsize);
2297 return -1;
2298 }
2299
2300 /* run filter on received packet
2301 * If the kernel filtering is enabled we need to run the
2302 * filter until all the frames present into the ring
2303 * at filter creation time are processed.
2304 * In such case md.use_bpf is used as a counter for the
2305 * packet we need to filter.
2306 * Note: alternatively it could be possible to stop applying
2307 * the filter when the ring became empty, but it can possibly
2308 * happen a lot later... */
2309 bp = (unsigned char*)h.raw + tp_mac;
2310 run_bpf = (!handle->md.use_bpf) ||
2311 ((handle->md.use_bpf>1) && handle->md.use_bpf--);
2312 if (run_bpf && handle->fcode.bf_insns &&
2313 (bpf_filter(handle->fcode.bf_insns, bp,
2314 tp_len, tp_snaplen) == 0))
2315 goto skip;
2316
2317 /* check direction and interface index */
2318 sll = (void *)h.raw + TPACKET_ALIGN(handle->md.tp_hdrlen);
2319 if ((sll->sll_ifindex == handle->md.lo_ifindex) &&
2320 (sll->sll_pkttype == PACKET_OUTGOING))
2321 goto skip;
2322
2323 /* get required packet info from ring header */
2324 pcaphdr.ts.tv_sec = tp_sec;
2325 pcaphdr.ts.tv_usec = tp_usec;
2326 pcaphdr.caplen = tp_snaplen;
2327 pcaphdr.len = tp_len;
2328
2329 /* if required build in place the sll header*/
2330 if (handle->md.cooked) {
2331 struct sll_header *hdrp;
2332
2333 /*
2334 * The kernel should have left us with enough
2335 * space for an sll header; back up the packet
2336 * data pointer into that space, as that'll be
2337 * the beginning of the packet we pass to the
2338 * callback.
2339 */
2340 bp -= SLL_HDR_LEN;
2341
2342 /*
2343 * Let's make sure that's past the end of
2344 * the tpacket header, i.e. >=
2345 * ((u_char *)thdr + TPACKET_HDRLEN), so we
2346 * don't step on the header when we construct
2347 * the sll header.
2348 */
2349 if (bp < (u_char *)h.raw +
2350 TPACKET_ALIGN(handle->md.tp_hdrlen) +
2351 sizeof(struct sockaddr_ll)) {
2352 snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
2353 "cooked-mode frame doesn't have room for sll header");
2354 return -1;
2355 }
2356
2357 /*
2358 * OK, that worked; construct the sll header.
2359 */
2360 hdrp = (struct sll_header *)bp;
2361 hdrp->sll_pkttype = map_packet_type_to_sll_type(
2362 sll->sll_pkttype);
2363 hdrp->sll_hatype = htons(sll->sll_hatype);
2364 hdrp->sll_halen = htons(sll->sll_halen);
2365 memcpy(hdrp->sll_addr, sll->sll_addr, SLL_ADDRLEN);
2366 hdrp->sll_protocol = sll->sll_protocol;
2367
2368 /* update packet len */
2369 pcaphdr.caplen += SLL_HDR_LEN;
2370 pcaphdr.len += SLL_HDR_LEN;
2371 }
2372
2373 #ifdef HAVE_TPACKET2
2374 if (handle->md.tp_version == TPACKET_V2 && h.h2->tp_vlan_tci &&
2375 tp_snaplen >= 2 * ETH_ALEN) {
2376 struct vlan_tag *tag;
2377
2378 bp -= VLAN_TAG_LEN;
2379 memmove(bp, bp + VLAN_TAG_LEN, 2 * ETH_ALEN);
2380
2381 tag = (struct vlan_tag *)(bp + 2 * ETH_ALEN);
2382 tag->vlan_tpid = htons(ETH_P_8021Q);
2383 tag->vlan_tci = htons(h.h2->tp_vlan_tci);
2384
2385 pcaphdr.caplen += VLAN_TAG_LEN;
2386 pcaphdr.len += VLAN_TAG_LEN;
2387 }
2388 #endif
2389
2390 /* pass the packet to the user */
2391 pkts++;
2392 callback(user, &pcaphdr, bp);
2393 handle->md.packets_read++;
2394
2395 skip:
2396 /* next packet */
2397 switch (handle->md.tp_version) {
2398 case TPACKET_V1:
2399 h.h1->tp_status = TP_STATUS_KERNEL;
2400 break;
2401 #ifdef HAVE_TPACKET2
2402 case TPACKET_V2:
2403 h.h2->tp_status = TP_STATUS_KERNEL;
2404 break;
2405 #endif
2406 }
2407 if (++handle->offset >= handle->cc)
2408 handle->offset = 0;
2409
2410 /* check for break loop condition*/
2411 if (handle->break_loop) {
2412 handle->break_loop = 0;
2413 return -2;
2414 }
2415 }
2416 return pkts;
2417 }
2418
2419 static int
2420 pcap_setfilter_linux_mmap(pcap_t *handle, struct bpf_program *filter)
2421 {
2422 int n, offset;
2423 int ret = pcap_setfilter_linux(handle, filter);
2424 if (ret < 0)
2425 return ret;
2426
2427 /* if the kernel filter is enabled, we need to apply the filter on
2428 * all packets present into the ring. Get an upper bound of their number
2429 */
2430 if (!handle->md.use_bpf)
2431 return ret;
2432
2433 /* walk the ring backward and count the free slot */
2434 offset = handle->offset;
2435 if (--handle->offset < 0)
2436 handle->offset = handle->cc - 1;
2437 for (n=0; n < handle->cc; ++n) {
2438 if (--handle->offset < 0)
2439 handle->offset = handle->cc - 1;
2440 if (!pcap_get_ring_frame(handle, TP_STATUS_KERNEL))
2441 break;
2442 }
2443
2444 /* be careful to not change current ring position */
2445 handle->offset = offset;
2446
2447 /* store the number of packets currently present in the ring */
2448 handle->md.use_bpf = 1 + (handle->cc - n);
2449 return ret;
2450 }
2451
2452 #endif /* HAVE_PACKET_RING */
2453
2454
2455 #ifdef HAVE_PF_PACKET_SOCKETS
2456 /*
2457 * Return the index of the given device name. Fill ebuf and return
2458 * -1 on failure.
2459 */
2460 static int
2461 iface_get_id(int fd, const char *device, char *ebuf)
2462 {
2463 struct ifreq ifr;
2464
2465 memset(&ifr, 0, sizeof(ifr));
2466 strncpy(ifr.ifr_name, device, sizeof(ifr.ifr_name));
2467
2468 if (ioctl(fd, SIOCGIFINDEX, &ifr) == -1) {
2469 snprintf(ebuf, PCAP_ERRBUF_SIZE,
2470 "SIOCGIFINDEX: %s", pcap_strerror(errno));
2471 return -1;
2472 }
2473
2474 return ifr.ifr_ifindex;
2475 }
2476
2477 /*
2478 * Bind the socket associated with FD to the given device.
2479 * Return 1 on success, 0 if we should try a SOCK_PACKET socket,
2480 * or a PCAP_ERROR_ value on a hard error.
2481 */
2482 static int
2483 iface_bind(int fd, int ifindex, char *ebuf)
2484 {
2485 struct sockaddr_ll sll;
2486 int err;
2487 socklen_t errlen = sizeof(err);
2488
2489 memset(&sll, 0, sizeof(sll));
2490 sll.sll_family = AF_PACKET;
2491 sll.sll_ifindex = ifindex;
2492 sll.sll_protocol = htons(ETH_P_ALL);
2493
2494 if (bind(fd, (struct sockaddr *) &sll, sizeof(sll)) == -1) {
2495 if (errno == ENETDOWN) {
2496 /*
2497 * Return a "network down" indication, so that
2498 * the application can report that rather than
2499 * saying we had a mysterious failure and
2500 * suggest that they report a problem to the
2501 * libpcap developers.
2502 */
2503 return PCAP_ERROR_IFACE_NOT_UP;
2504 } else {
2505 snprintf(ebuf, PCAP_ERRBUF_SIZE,
2506 "bind: %s", pcap_strerror(errno));
2507 return PCAP_ERROR;
2508 }
2509 }
2510
2511 /* Any pending errors, e.g., network is down? */
2512
2513 if (getsockopt(fd, SOL_SOCKET, SO_ERROR, &err, &errlen) == -1) {
2514 snprintf(ebuf, PCAP_ERRBUF_SIZE,
2515 "getsockopt: %s", pcap_strerror(errno));
2516 return 0;
2517 }
2518
2519 if (err == ENETDOWN) {
2520 /*
2521 * Return a "network down" indication, so that
2522 * the application can report that rather than
2523 * saying we had a mysterious failure and
2524 * suggest that they report a problem to the
2525 * libpcap developers.
2526 */
2527 return PCAP_ERROR_IFACE_NOT_UP;
2528 } else if (err > 0) {
2529 snprintf(ebuf, PCAP_ERRBUF_SIZE,
2530 "bind: %s", pcap_strerror(err));
2531 return 0;
2532 }
2533
2534 return 1;
2535 }
2536
2537 /*
2538 * Check whether the device supports the Wireless Extensions.
2539 * Returns 1 if it does, 0 if it doesn't, PCAP_ERROR_NO_SUCH_DEVICE
2540 * if the device doesn't even exist.
2541 */
2542 static int
2543 has_wext(int sock_fd, const char *device, char *ebuf)
2544 {
2545 #ifdef IW_MODE_MONITOR
2546 struct iwreq ireq;
2547
2548 strncpy(ireq.ifr_ifrn.ifrn_name, device,
2549 sizeof ireq.ifr_ifrn.ifrn_name);
2550 ireq.ifr_ifrn.ifrn_name[sizeof ireq.ifr_ifrn.ifrn_name - 1] = 0;
2551 if (ioctl(sock_fd, SIOCGIWNAME, &ireq) >= 0)
2552 return 1; /* yes */
2553 snprintf(ebuf, PCAP_ERRBUF_SIZE,
2554 "%s: SIOCGIWPRIV: %s", device, pcap_strerror(errno));
2555 if (errno == ENODEV)
2556 return PCAP_ERROR_NO_SUCH_DEVICE;
2557 #endif
2558 return 0;
2559 }
2560
2561 /*
2562 * Per me si va ne la citta dolente,
2563 * Per me si va ne l'etterno dolore,
2564 * ...
2565 * Lasciate ogne speranza, voi ch'intrate.
2566 *
2567 * XXX - airmon-ng does special stuff with the Orinoco driver and the
2568 * wlan-ng driver.
2569 */
2570 typedef enum {
2571 MONITOR_WEXT,
2572 MONITOR_HOSTAP,
2573 MONITOR_PRISM,
2574 MONITOR_PRISM54,
2575 MONITOR_ACX100,
2576 MONITOR_RT2500,
2577 MONITOR_RT2570,
2578 MONITOR_RT73,
2579 MONITOR_RTL8XXX
2580 } monitor_type;
2581
2582 /*
2583 * Use the Wireless Extensions, if we have them, to try to turn monitor mode
2584 * on if it's not already on.
2585 *
2586 * Returns 1 on success, 0 if we don't support the Wireless Extensions
2587 * on this device, or a PCAP_ERROR_ value if we do support them but
2588 * we weren't able to turn monitor mode on.
2589 */
2590 static int
2591 enter_rfmon_mode_wext(pcap_t *handle, int sock_fd, const char *device)
2592 {
2593 #ifdef IW_MODE_MONITOR
2594 /*
2595 * XXX - at least some adapters require non-Wireless Extensions
2596 * mechanisms to turn monitor mode on.
2597 *
2598 * Atheros cards might require that a separate "monitor virtual access
2599 * point" be created, with later versions of the madwifi driver.
2600 * airmon-ng does "wlanconfig ath create wlandev {if} wlanmode
2601 * monitor -bssid", which apparently spits out a line "athN"
2602 * where "athN" is the monitor mode device. To leave monitor
2603 * mode, it destroys the monitor mode device.
2604 *
2605 * Some Intel Centrino adapters might require private ioctls to get
2606 * radio headers; the ipw2200 and ipw3945 drivers allow you to
2607 * configure a separate "rtapN" interface to capture in monitor
2608 * mode without preventing the adapter from operating normally.
2609 * (airmon-ng doesn't appear to use that, though.)
2610 *
2611 * It would be Truly Wonderful if mac80211 and nl80211 cleaned this
2612 * up, and if all drivers were converted to mac80211 drivers.
2613 *
2614 * If interface {if} is a mac80211 driver, the file
2615 * /sys/class/net/{if}/phy80211 is a symlink to
2616 * /sys/class/ieee80211/{phydev}, for some {phydev}.
2617 *
2618 * On Fedora 9, with a 2.6.26.3-29 kernel, my Zydas stick, at
2619 * least, has a "wmaster0" device and a "wlan0" device; the
2620 * latter is the one with the IP address. Both show up in
2621 * "tcpdump -D" output. Capturing on the wmaster0 device
2622 * captures with 802.11 headers.
2623 *
2624 * airmon-ng searches through /sys/class/net for devices named
2625 * monN, starting with mon0; as soon as one *doesn't* exist,
2626 * it chooses that as the monitor device name. If the "iw"
2627 * command exists, it does "iw dev {if} interface add {monif}
2628 * type monitor", where {monif} is the monitor device. It
2629 * then (sigh) sleeps .1 second, and then configures the
2630 * device up. Otherwise, if /sys/class/ieee80211/{phydev}/add_iface
2631 * is a file, it writes {mondev}, without a newline, to that file,
2632 * and again (sigh) sleeps .1 second, and then iwconfig's that
2633 * device into monitor mode and configures it up. Otherwise,
2634 * you can't do monitor mode.
2635 *
2636 * All these devices are "glued" together by having the
2637 * /sys/class/net/{device}/phy80211 links pointing to the same
2638 * place, so, given a wmaster, wlan, or mon device, you can
2639 * find the other devices by looking for devices with
2640 * the same phy80211 link.
2641 *
2642 * To turn monitor mode off, delete the monitor interface,
2643 * either with "iw dev {monif} interface del" or by sending
2644 * {monif}, with no NL, down /sys/class/ieee80211/{phydev}/remove_iface
2645 *
2646 * Note: if you try to create a monitor device named "monN", and
2647 * there's already a "monN" device, it fails, as least with
2648 * the netlink interface (which is what iw uses), with a return
2649 * value of -ENFILE. (Return values are negative errnos.) We
2650 * could probably use that to find an unused device.
2651 */
2652 int err;
2653 struct iwreq ireq;
2654 struct iw_priv_args *priv;
2655 monitor_type montype;
2656 int i;
2657 __u32 cmd;
2658 int args[2];
2659 int channel;
2660
2661 /*
2662 * Does this device *support* the Wireless Extensions?
2663 */
2664 err = has_wext(sock_fd, device, handle->errbuf);
2665 if (err <= 0)
2666 return err; /* either it doesn't or the device doesn't even exist */
2667 /*
2668 * Try to get all the Wireless Extensions private ioctls
2669 * supported by this device.
2670 *
2671 * First, get the size of the buffer we need, by supplying no
2672 * buffer and a length of 0. If the device supports private
2673 * ioctls, it should return E2BIG, with ireq.u.data.length set
2674 * to the length we need. If it doesn't support them, it should
2675 * return EOPNOTSUPP.
2676 */
2677 memset(&ireq, 0, sizeof ireq);
2678 strncpy(ireq.ifr_ifrn.ifrn_name, device,
2679 sizeof ireq.ifr_ifrn.ifrn_name);
2680 ireq.ifr_ifrn.ifrn_name[sizeof ireq.ifr_ifrn.ifrn_name - 1] = 0;
2681 ireq.u.data.pointer = args;
2682 ireq.u.data.length = 0;
2683 ireq.u.data.flags = 0;
2684 if (ioctl(sock_fd, SIOCGIWPRIV, &ireq) != -1) {
2685 snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
2686 "%s: SIOCGIWPRIV with a zero-length buffer didn't fail!",
2687 device);
2688 return PCAP_ERROR;
2689 }
2690 if (errno == EOPNOTSUPP) {
2691 /*
2692 * No private ioctls, so we assume that there's only one
2693 * DLT_ for monitor mode.
2694 */
2695 return 0;
2696 }
2697 if (errno != E2BIG) {
2698 /*
2699 * Failed.
2700 */
2701 snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
2702 "%s: SIOCGIWPRIV: %s", device, pcap_strerror(errno));
2703 return PCAP_ERROR;
2704 }
2705 priv = malloc(ireq.u.data.length * sizeof (struct iw_priv_args));
2706 if (priv == NULL) {
2707 snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
2708 "malloc: %s", pcap_strerror(errno));
2709 return PCAP_ERROR;
2710 }
2711 ireq.u.data.pointer = priv;
2712 if (ioctl(sock_fd, SIOCGIWPRIV, &ireq) == -1) {
2713 snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
2714 "%s: SIOCGIWPRIV: %s", device, pcap_strerror(errno));
2715 free(priv);
2716 return PCAP_ERROR;
2717 }
2718
2719 /*
2720 * Look for private ioctls to turn monitor mode on or, if
2721 * monitor mode is on, to set the header type.
2722 */
2723 montype = MONITOR_WEXT;
2724 cmd = 0;
2725 for (i = 0; i < ireq.u.data.length; i++) {
2726 if (strcmp(priv[i].name, "monitor_type") == 0) {
2727 /*
2728 * Hostap driver, use this one.
2729 * Set monitor mode first.
2730 * You can set it to 0 to get DLT_IEEE80211,
2731 * 1 to get DLT_PRISM, or 2 to get
2732 * DLT_IEEE80211_RADIO_AVS.
2733 */
2734 if ((priv[i].set_args & IW_PRIV_TYPE_MASK) != IW_PRIV_TYPE_INT)
2735 break;
2736 if (!(priv[i].set_args & IW_PRIV_SIZE_FIXED))
2737 break;
2738 if ((priv[i].set_args & IW_PRIV_SIZE_MASK) != 1)
2739 break;
2740 montype = MONITOR_HOSTAP;
2741 cmd = priv[i].cmd;
2742 break;
2743 }
2744 if (strcmp(priv[i].name, "set_prismhdr") == 0) {
2745 /*
2746 * Prism54 driver, use this one.
2747 * Set monitor mode first.
2748 * You can set it to 2 to get DLT_IEEE80211
2749 * or 3 or get DLT_PRISM.
2750 */
2751 if ((priv[i].set_args & IW_PRIV_TYPE_MASK) != IW_PRIV_TYPE_INT)
2752 break;
2753 if (!(priv[i].set_args & IW_PRIV_SIZE_FIXED))
2754 break;
2755 if ((priv[i].set_args & IW_PRIV_SIZE_MASK) != 1)
2756 break;
2757 montype = MONITOR_PRISM54;
2758 cmd = priv[i].cmd;
2759 break;
2760 }
2761 if (strcmp(priv[i].name, "forceprismheader") == 0) {
2762 /*
2763 * RT2570 driver, use this one.
2764 * Do this after turning monitor mode on.
2765 * You can set it to 1 to get DLT_PRISM or 2
2766 * to get DLT_IEEE80211.
2767 */
2768 if ((priv[i].set_args & IW_PRIV_TYPE_MASK) != IW_PRIV_TYPE_INT)
2769 break;
2770 if (!(priv[i].set_args & IW_PRIV_SIZE_FIXED))
2771 break;
2772 if ((priv[i].set_args & IW_PRIV_SIZE_MASK) != 1)
2773 break;
2774 montype = MONITOR_RT2570;
2775 cmd = priv[i].cmd;
2776 break;
2777 }
2778 if (strcmp(priv[i].name, "forceprism") == 0) {
2779 /*
2780 * RT73 driver, use this one.
2781 * Do this after turning monitor mode on.
2782 * Its argument is a *string*; you can
2783 * set it to "1" to get DLT_PRISM or "2"
2784 * to get DLT_IEEE80211.
2785 */
2786 if ((priv[i].set_args & IW_PRIV_TYPE_MASK) != IW_PRIV_TYPE_CHAR)
2787 break;
2788 if (priv[i].set_args & IW_PRIV_SIZE_FIXED)
2789 break;
2790 montype = MONITOR_RT73;
2791 cmd = priv[i].cmd;
2792 break;
2793 }
2794 if (strcmp(priv[i].name, "prismhdr") == 0) {
2795 /*
2796 * One of the RTL8xxx drivers, use this one.
2797 * It can only be done after monitor mode
2798 * has been turned on. You can set it to 1
2799 * to get DLT_PRISM or 0 to get DLT_IEEE80211.
2800 */
2801 if ((priv[i].set_args & IW_PRIV_TYPE_MASK) != IW_PRIV_TYPE_INT)
2802 break;
2803 if (!(priv[i].set_args & IW_PRIV_SIZE_FIXED))
2804 break;
2805 if ((priv[i].set_args & IW_PRIV_SIZE_MASK) != 1)
2806 break;
2807 montype = MONITOR_RTL8XXX;
2808 cmd = priv[i].cmd;
2809 break;
2810 }
2811 if (strcmp(priv[i].name, "rfmontx") == 0) {
2812 /*
2813 * RT2500 or RT61 driver, use this one.
2814 * It has one one-byte parameter; set
2815 * u.data.length to 1 and u.data.pointer to
2816 * point to the parameter.
2817 * It doesn't itself turn monitor mode on.
2818 * You can set it to 1 to allow transmitting
2819 * in monitor mode(?) and get DLT_IEEE80211,
2820 * or set it to 0 to disallow transmitting in
2821 * monitor mode(?) and get DLT_PRISM.
2822 */
2823 if ((priv[i].set_args & IW_PRIV_TYPE_MASK) != IW_PRIV_TYPE_INT)
2824 break;
2825 if ((priv[i].set_args & IW_PRIV_SIZE_MASK) != 2)
2826 break;
2827 montype = MONITOR_RT2500;
2828 cmd = priv[i].cmd;
2829 break;
2830 }
2831 if (strcmp(priv[i].name, "monitor") == 0) {
2832 /*
2833 * Either ACX100 or hostap, use this one.
2834 * It turns monitor mode on.
2835 * If it takes two arguments, it's ACX100;
2836 * the first argument is 1 for DLT_PRISM
2837 * or 2 for DLT_IEEE80211, and the second
2838 * argument is the channel on which to
2839 * run. If it takes one argument, it's
2840 * HostAP, and the argument is 2 for
2841 * DLT_IEEE80211 and 3 for DLT_PRISM.
2842 *
2843 * If we see this, we don't quit, as this
2844 * might be a version of the hostap driver
2845 * that also supports "monitor_type".
2846 */
2847 if ((priv[i].set_args & IW_PRIV_TYPE_MASK) != IW_PRIV_TYPE_INT)
2848 break;
2849 if (!(priv[i].set_args & IW_PRIV_SIZE_FIXED))
2850 break;
2851 switch (priv[i].set_args & IW_PRIV_SIZE_MASK) {
2852
2853 case 1:
2854 montype = MONITOR_PRISM;
2855 cmd = priv[i].cmd;
2856 break;
2857
2858 case 2:
2859 montype = MONITOR_ACX100;
2860 cmd = priv[i].cmd;
2861 break;
2862
2863 default:
2864 break;
2865 }
2866 }
2867 }
2868 free(priv);
2869
2870 /*
2871 * XXX - ipw3945? islism?
2872 */
2873
2874 /*
2875 * Get the old mode.
2876 */
2877 strncpy(ireq.ifr_ifrn.ifrn_name, device,
2878 sizeof ireq.ifr_ifrn.ifrn_name);
2879 ireq.ifr_ifrn.ifrn_name[sizeof ireq.ifr_ifrn.ifrn_name - 1] = 0;
2880 if (ioctl(sock_fd, SIOCGIWMODE, &ireq) == -1) {
2881 /*
2882 * We probably won't be able to set the mode, either.
2883 */
2884 return PCAP_ERROR_RFMON_NOTSUP;
2885 }
2886
2887 /*
2888 * Is it currently in monitor mode?
2889 */
2890 if (ireq.u.mode == IW_MODE_MONITOR) {
2891 /*
2892 * Yes. Just leave things as they are.
2893 * We don't offer multiple link-layer types, as
2894 * changing the link-layer type out from under
2895 * somebody else capturing in monitor mode would
2896 * be considered rude.
2897 */
2898 return 1;
2899 }
2900 /*
2901 * No. We have to put the adapter into rfmon mode.
2902 */
2903
2904 /*
2905 * If we haven't already done so, arrange to have
2906 * "pcap_close_all()" called when we exit.
2907 */
2908 if (!pcap_do_addexit(handle)) {
2909 /*
2910 * "atexit()" failed; don't put the interface
2911 * in rfmon mode, just give up.
2912 */
2913 return PCAP_ERROR_RFMON_NOTSUP;
2914 }
2915
2916 /*
2917 * Save the old mode.
2918 */
2919 handle->md.oldmode = ireq.u.mode;
2920
2921 /*
2922 * Put the adapter in rfmon mode. How we do this depends
2923 * on whether we have a special private ioctl or not.
2924 */
2925 if (montype == MONITOR_PRISM) {
2926 /*
2927 * We have the "monitor" private ioctl, but none of
2928 * the other private ioctls. Use this, and select
2929 * the Prism header.
2930 *
2931 * If it fails, just fall back on SIOCSIWMODE.
2932 */
2933 memset(&ireq, 0, sizeof ireq);
2934 strncpy(ireq.ifr_ifrn.ifrn_name, device,
2935 sizeof ireq.ifr_ifrn.ifrn_name);
2936 ireq.ifr_ifrn.ifrn_name[sizeof ireq.ifr_ifrn.ifrn_name - 1] = 0;
2937 ireq.u.data.length = 1; /* 1 argument */
2938 args[0] = 3; /* request Prism header */
2939 memcpy(ireq.u.name, args, IFNAMSIZ);
2940 if (ioctl(sock_fd, cmd, &ireq) != -1) {
2941 /*
2942 * Success.
2943 * Note that we have to put the old mode back
2944 * when we close the device.
2945 */
2946 handle->md.must_clear |= MUST_CLEAR_RFMON;
2947
2948 /*
2949 * Add this to the list of pcaps to close
2950 * when we exit.
2951 */
2952 pcap_add_to_pcaps_to_close(handle);
2953
2954 return 1;
2955 }
2956
2957 /*
2958 * Failure. Fall back on SIOCSIWMODE.
2959 */
2960 }
2961
2962 /*
2963 * First, turn monitor mode on.
2964 */
2965 strncpy(ireq.ifr_ifrn.ifrn_name, device,
2966 sizeof ireq.ifr_ifrn.ifrn_name);
2967 ireq.ifr_ifrn.ifrn_name[sizeof ireq.ifr_ifrn.ifrn_name - 1] = 0;
2968 ireq.u.mode = IW_MODE_MONITOR;
2969 if (ioctl(sock_fd, SIOCSIWMODE, &ireq) == -1) {
2970 /*
2971 * Scientist, you've failed.
2972 */
2973 return PCAP_ERROR_RFMON_NOTSUP;
2974 }
2975
2976 /*
2977 * XXX - airmon-ng does "iwconfig {if} key off" after setting
2978 * monitor mode and setting the channel, and then does
2979 * "iwconfig up".
2980 */
2981
2982 /*
2983 * Now select the appropriate radio header.
2984 */
2985 switch (montype) {
2986
2987 case MONITOR_WEXT:
2988 /*
2989 * We don't have any private ioctl to set the header.
2990 */
2991 break;
2992
2993 case MONITOR_HOSTAP:
2994 /*
2995 * Select the AVS header if we can, otherwise
2996 * select the Prism header.
2997 */
2998 memset(&ireq, 0, sizeof ireq);
2999 strncpy(ireq.ifr_ifrn.ifrn_name, device,
3000 sizeof ireq.ifr_ifrn.ifrn_name);
3001 ireq.ifr_ifrn.ifrn_name[sizeof ireq.ifr_ifrn.ifrn_name - 1] = 0;
3002 args[0] = 2; /* request AVS header */
3003 memcpy(ireq.u.name, args, sizeof (int));
3004 if (ioctl(sock_fd, cmd, &ireq) == -1) {
3005 /*
3006 * Failure - try the Prism header.
3007 */
3008 memset(&ireq, 0, sizeof ireq);
3009 strncpy(ireq.ifr_ifrn.ifrn_name, device,
3010 sizeof ireq.ifr_ifrn.ifrn_name);
3011 ireq.ifr_ifrn.ifrn_name[sizeof ireq.ifr_ifrn.ifrn_name - 1] = 0;
3012 args[0] = 1; /* request Prism header */
3013 memcpy(ireq.u.name, args, sizeof (int));
3014 ioctl(sock_fd, cmd, &ireq);
3015 }
3016 break;
3017
3018 case MONITOR_PRISM:
3019 /*
3020 * The private ioctl failed.
3021 */
3022 break;
3023
3024 case MONITOR_PRISM54:
3025 /*
3026 * Select the Prism header.
3027 */
3028 memset(&ireq, 0, sizeof ireq);
3029 strncpy(ireq.ifr_ifrn.ifrn_name, device,
3030 sizeof ireq.ifr_ifrn.ifrn_name);
3031 ireq.ifr_ifrn.ifrn_name[sizeof ireq.ifr_ifrn.ifrn_name - 1] = 0;
3032 args[0] = 3; /* request Prism header */
3033 memcpy(ireq.u.name, args, sizeof (int));
3034 ioctl(sock_fd, cmd, &ireq);
3035 break;
3036
3037 case MONITOR_ACX100:
3038 /*
3039 * Get the current channel.
3040 */
3041 memset(&ireq, 0, sizeof ireq);
3042 strncpy(ireq.ifr_ifrn.ifrn_name, device,
3043 sizeof ireq.ifr_ifrn.ifrn_name);
3044 ireq.ifr_ifrn.ifrn_name[sizeof ireq.ifr_ifrn.ifrn_name - 1] = 0;
3045 if (ioctl(sock_fd, SIOCGIWFREQ, &ireq) == -1) {
3046 snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
3047 "%s: SIOCGIWFREQ: %s", device,
3048 pcap_strerror(errno));
3049 return PCAP_ERROR;
3050 }
3051 channel = ireq.u.freq.m;
3052
3053 /*
3054 * Select the Prism header, and set the channel to the
3055 * current value.
3056 */
3057 memset(&ireq, 0, sizeof ireq);
3058 strncpy(ireq.ifr_ifrn.ifrn_name, device,
3059 sizeof ireq.ifr_ifrn.ifrn_name);
3060 ireq.ifr_ifrn.ifrn_name[sizeof ireq.ifr_ifrn.ifrn_name - 1] = 0;
3061 args[0] = 1; /* request Prism header */
3062 args[1] = channel; /* set channel */
3063 memcpy(ireq.u.name, args, 2*sizeof (int));
3064 ioctl(sock_fd, cmd, &ireq);
3065 break;
3066
3067 case MONITOR_RT2500:
3068 /*
3069 * Disallow transmission - that turns on the
3070 * Prism header.
3071 */
3072 memset(&ireq, 0, sizeof ireq);
3073 strncpy(ireq.ifr_ifrn.ifrn_name, device,
3074 sizeof ireq.ifr_ifrn.ifrn_name);
3075 ireq.ifr_ifrn.ifrn_name[sizeof ireq.ifr_ifrn.ifrn_name - 1] = 0;
3076 args[0] = 0; /* disallow transmitting */
3077 memcpy(ireq.u.name, args, sizeof (int));
3078 ioctl(sock_fd, cmd, &ireq);
3079 break;
3080
3081 case MONITOR_RT2570:
3082 /*
3083 * Force the Prism header.
3084 */
3085 memset(&ireq, 0, sizeof ireq);
3086 strncpy(ireq.ifr_ifrn.ifrn_name, device,
3087 sizeof ireq.ifr_ifrn.ifrn_name);
3088 ireq.ifr_ifrn.ifrn_name[sizeof ireq.ifr_ifrn.ifrn_name - 1] = 0;
3089 args[0] = 1; /* request Prism header */
3090 memcpy(ireq.u.name, args, sizeof (int));
3091 ioctl(sock_fd, cmd, &ireq);
3092 break;
3093
3094 case MONITOR_RT73:
3095 /*
3096 * Force the Prism header.
3097 */
3098 memset(&ireq, 0, sizeof ireq);
3099 strncpy(ireq.ifr_ifrn.ifrn_name, device,
3100 sizeof ireq.ifr_ifrn.ifrn_name);
3101 ireq.ifr_ifrn.ifrn_name[sizeof ireq.ifr_ifrn.ifrn_name - 1] = 0;
3102 ireq.u.data.length = 1; /* 1 argument */
3103 ireq.u.data.pointer = "1";
3104 ireq.u.data.flags = 0;
3105 ioctl(sock_fd, cmd, &ireq);
3106 break;
3107
3108 case MONITOR_RTL8XXX:
3109 /*
3110 * Force the Prism header.
3111 */
3112 memset(&ireq, 0, sizeof ireq);
3113 strncpy(ireq.ifr_ifrn.ifrn_name, device,
3114 sizeof ireq.ifr_ifrn.ifrn_name);
3115 ireq.ifr_ifrn.ifrn_name[sizeof ireq.ifr_ifrn.ifrn_name - 1] = 0;
3116 args[0] = 1; /* request Prism header */
3117 memcpy(ireq.u.name, args, sizeof (int));
3118 ioctl(sock_fd, cmd, &ireq);
3119 break;
3120 }
3121
3122 /*
3123 * Note that we have to put the old mode back when we
3124 * close the device.
3125 */
3126 handle->md.must_clear |= MUST_CLEAR_RFMON;
3127
3128 /*
3129 * Add this to the list of pcaps to close when we exit.
3130 */
3131 pcap_add_to_pcaps_to_close(handle);
3132
3133 return 1;
3134 #else
3135 /*
3136 * We don't have the Wireless Extensions available, so we can't
3137 * do monitor mode.
3138 */
3139 return 0;
3140 #endif
3141 }
3142
3143 #endif /* HAVE_PF_PACKET_SOCKETS */
3144
3145 /* ===== Functions to interface to the older kernels ================== */
3146
3147 /*
3148 * Try to open a packet socket using the old kernel interface.
3149 * Returns 1 on success and a PCAP_ERROR_ value on an error.
3150 */
3151 static int
3152 activate_old(pcap_t *handle)
3153 {
3154 int arptype;
3155 struct ifreq ifr;
3156 const char *device = handle->opt.source;
3157 struct utsname utsname;
3158 int mtu;
3159
3160 /* Open the socket */
3161
3162 handle->fd = socket(PF_INET, SOCK_PACKET, htons(ETH_P_ALL));
3163 if (handle->fd == -1) {
3164 snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
3165 "socket: %s", pcap_strerror(errno));
3166 return PCAP_ERROR_PERM_DENIED;
3167 }
3168
3169 /* It worked - we are using the old interface */
3170 handle->md.sock_packet = 1;
3171
3172 /* ...which means we get the link-layer header. */
3173 handle->md.cooked = 0;
3174
3175 /* Bind to the given device */
3176
3177 if (strcmp(device, "any") == 0) {
3178 strncpy(handle->errbuf, "pcap_activate: The \"any\" device isn't supported on 2.0[.x]-kernel systems",
3179 PCAP_ERRBUF_SIZE);
3180 return PCAP_ERROR;
3181 }
3182 if (iface_bind_old(handle->fd, device, handle->errbuf) == -1)
3183 return PCAP_ERROR;
3184
3185 /*
3186 * Try to get the link-layer type.
3187 */
3188 arptype = iface_get_arptype(handle->fd, device, handle->errbuf);
3189 if (arptype < 0)
3190 return PCAP_ERROR;
3191
3192 /*
3193 * Try to find the DLT_ type corresponding to that
3194 * link-layer type.
3195 */
3196 map_arphrd_to_dlt(handle, arptype, 0);
3197 if (handle->linktype == -1) {
3198 snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
3199 "unknown arptype %d", arptype);
3200 return PCAP_ERROR;
3201 }
3202
3203 /* Go to promisc mode if requested */
3204
3205 if (handle->opt.promisc) {
3206 memset(&ifr, 0, sizeof(ifr));
3207 strncpy(ifr.ifr_name, device, sizeof(ifr.ifr_name));
3208 if (ioctl(handle->fd, SIOCGIFFLAGS, &ifr) == -1) {
3209 snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
3210 "SIOCGIFFLAGS: %s", pcap_strerror(errno));
3211 return PCAP_ERROR;
3212 }
3213 if ((ifr.ifr_flags & IFF_PROMISC) == 0) {
3214 /*
3215 * Promiscuous mode isn't currently on,
3216 * so turn it on, and remember that
3217 * we should turn it off when the
3218 * pcap_t is closed.
3219 */
3220
3221 /*
3222 * If we haven't already done so, arrange
3223 * to have "pcap_close_all()" called when
3224 * we exit.
3225 */
3226 if (!pcap_do_addexit(handle)) {
3227 /*
3228 * "atexit()" failed; don't put
3229 * the interface in promiscuous
3230 * mode, just give up.
3231 */
3232 return PCAP_ERROR;
3233 }
3234
3235 ifr.ifr_flags |= IFF_PROMISC;
3236 if (ioctl(handle->fd, SIOCSIFFLAGS, &ifr) == -1) {
3237 snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
3238 "SIOCSIFFLAGS: %s",
3239 pcap_strerror(errno));
3240 return PCAP_ERROR;
3241 }
3242 handle->md.must_clear |= MUST_CLEAR_PROMISC;
3243
3244 /*
3245 * Add this to the list of pcaps
3246 * to close when we exit.
3247 */
3248 pcap_add_to_pcaps_to_close(handle);
3249 }
3250 }
3251
3252 /*
3253 * Compute the buffer size.
3254 *
3255 * We're using SOCK_PACKET, so this might be a 2.0[.x]
3256 * kernel, and might require special handling - check.
3257 */
3258 if (uname(&utsname) < 0 ||
3259 strncmp(utsname.release, "2.0", 3) == 0) {
3260 /*
3261 * Either we couldn't find out what kernel release
3262 * this is, or it's a 2.0[.x] kernel.
3263 *
3264 * In the 2.0[.x] kernel, a "recvfrom()" on
3265 * a SOCK_PACKET socket, with MSG_TRUNC set, will
3266 * return the number of bytes read, so if we pass
3267 * a length based on the snapshot length, it'll
3268 * return the number of bytes from the packet
3269 * copied to userland, not the actual length
3270 * of the packet.
3271 *
3272 * This means that, for example, the IP dissector
3273 * in tcpdump will get handed a packet length less
3274 * than the length in the IP header, and will
3275 * complain about "truncated-ip".
3276 *
3277 * So we don't bother trying to copy from the
3278 * kernel only the bytes in which we're interested,
3279 * but instead copy them all, just as the older
3280 * versions of libpcap for Linux did.
3281 *
3282 * The buffer therefore needs to be big enough to
3283 * hold the largest packet we can get from this
3284 * device. Unfortunately, we can't get the MRU
3285 * of the network; we can only get the MTU. The
3286 * MTU may be too small, in which case a packet larger
3287 * than the buffer size will be truncated *and* we
3288 * won't get the actual packet size.
3289 *
3290 * However, if the snapshot length is larger than
3291 * the buffer size based on the MTU, we use the
3292 * snapshot length as the buffer size, instead;
3293 * this means that with a sufficiently large snapshot
3294 * length we won't artificially truncate packets
3295 * to the MTU-based size.
3296 *
3297 * This mess just one of many problems with packet
3298 * capture on 2.0[.x] kernels; you really want a
3299 * 2.2[.x] or later kernel if you want packet capture
3300 * to work well.
3301 */
3302 mtu = iface_get_mtu(handle->fd, device, handle->errbuf);
3303 if (mtu == -1)
3304 return PCAP_ERROR;
3305 handle->bufsize = MAX_LINKHEADER_SIZE + mtu;
3306 if (handle->bufsize < handle->snapshot)
3307 handle->bufsize = handle->snapshot;
3308 } else {
3309 /*
3310 * This is a 2.2[.x] or later kernel.
3311 *
3312 * We can safely pass "recvfrom()" a byte count
3313 * based on the snapshot length.
3314 */
3315 handle->bufsize = handle->snapshot;
3316 }
3317
3318 /*
3319 * Default value for offset to align link-layer payload
3320 * on a 4-byte boundary.
3321 */
3322 handle->offset = 0;
3323
3324 return 1;
3325 }
3326
3327 /*
3328 * Bind the socket associated with FD to the given device using the
3329 * interface of the old kernels.
3330 */
3331 static int
3332 iface_bind_old(int fd, const char *device, char *ebuf)
3333 {
3334 struct sockaddr saddr;
3335 int err;
3336 socklen_t errlen = sizeof(err);
3337
3338 memset(&saddr, 0, sizeof(saddr));
3339 strncpy(saddr.sa_data, device, sizeof(saddr.sa_data));
3340 if (bind(fd, &saddr, sizeof(saddr)) == -1) {
3341 snprintf(ebuf, PCAP_ERRBUF_SIZE,
3342 "bind: %s", pcap_strerror(errno));
3343 return -1;
3344 }
3345
3346 /* Any pending errors, e.g., network is down? */
3347
3348 if (getsockopt(fd, SOL_SOCKET, SO_ERROR, &err, &errlen) == -1) {
3349 snprintf(ebuf, PCAP_ERRBUF_SIZE,
3350 "getsockopt: %s", pcap_strerror(errno));
3351 return -1;
3352 }
3353
3354 if (err > 0) {
3355 snprintf(ebuf, PCAP_ERRBUF_SIZE,
3356 "bind: %s", pcap_strerror(err));
3357 return -1;
3358 }
3359
3360 return 0;
3361 }
3362
3363
3364 /* ===== System calls available on all supported kernels ============== */
3365
3366 /*
3367 * Query the kernel for the MTU of the given interface.
3368 */
3369 static int
3370 iface_get_mtu(int fd, const char *device, char *ebuf)
3371 {
3372 struct ifreq ifr;
3373
3374 if (!device)
3375 return BIGGER_THAN_ALL_MTUS;
3376
3377 memset(&ifr, 0, sizeof(ifr));
3378 strncpy(ifr.ifr_name, device, sizeof(ifr.ifr_name));
3379
3380 if (ioctl(fd, SIOCGIFMTU, &ifr) == -1) {
3381 snprintf(ebuf, PCAP_ERRBUF_SIZE,
3382 "SIOCGIFMTU: %s", pcap_strerror(errno));
3383 return -1;
3384 }
3385
3386 return ifr.ifr_mtu;
3387 }
3388
3389 /*
3390 * Get the hardware type of the given interface as ARPHRD_xxx constant.
3391 */
3392 static int
3393 iface_get_arptype(int fd, const char *device, char *ebuf)
3394 {
3395 struct ifreq ifr;
3396
3397 memset(&ifr, 0, sizeof(ifr));
3398 strncpy(ifr.ifr_name, device, sizeof(ifr.ifr_name));
3399
3400 if (ioctl(fd, SIOCGIFHWADDR, &ifr) == -1) {
3401 snprintf(ebuf, PCAP_ERRBUF_SIZE,
3402 "SIOCGIFHWADDR: %s", pcap_strerror(errno));
3403 if (errno == ENODEV) {
3404 /*
3405 * No such device.
3406 */
3407 return PCAP_ERROR_NO_SUCH_DEVICE;
3408 }
3409 return PCAP_ERROR;
3410 }
3411
3412 return ifr.ifr_hwaddr.sa_family;
3413 }
3414
3415 #ifdef SO_ATTACH_FILTER
3416 static int
3417 fix_program(pcap_t *handle, struct sock_fprog *fcode)
3418 {
3419 size_t prog_size;
3420 register int i;
3421 register struct bpf_insn *p;
3422 struct bpf_insn *f;
3423 int len;
3424
3425 /*
3426 * Make a copy of the filter, and modify that copy if
3427 * necessary.
3428 */
3429 prog_size = sizeof(*handle->fcode.bf_insns) * handle->fcode.bf_len;
3430 len = handle->fcode.bf_len;
3431 f = (struct bpf_insn *)malloc(prog_size);
3432 if (f == NULL) {
3433 snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
3434 "malloc: %s", pcap_strerror(errno));
3435 return -1;
3436 }
3437 memcpy(f, handle->fcode.bf_insns, prog_size);
3438 fcode->len = len;
3439 fcode->filter = (struct sock_filter *) f;
3440
3441 for (i = 0; i < len; ++i) {
3442 p = &f[i];
3443 /*
3444 * What type of instruction is this?
3445 */
3446 switch (BPF_CLASS(p->code)) {
3447
3448 case BPF_RET:
3449 /*
3450 * It's a return instruction; is the snapshot
3451 * length a constant, rather than the contents
3452 * of the accumulator?
3453 */
3454 if (BPF_MODE(p->code) == BPF_K) {
3455 /*
3456 * Yes - if the value to be returned,
3457 * i.e. the snapshot length, is anything
3458 * other than 0, make it 65535, so that
3459 * the packet is truncated by "recvfrom()",
3460 * not by the filter.
3461 *
3462 * XXX - there's nothing we can easily do
3463 * if it's getting the value from the
3464 * accumulator; we'd have to insert
3465 * code to force non-zero values to be
3466 * 65535.
3467 */
3468 if (p->k != 0)
3469 p->k = 65535;
3470 }
3471 break;
3472
3473 case BPF_LD:
3474 case BPF_LDX:
3475 /*
3476 * It's a load instruction; is it loading
3477 * from the packet?
3478 */
3479 switch (BPF_MODE(p->code)) {
3480
3481 case BPF_ABS:
3482 case BPF_IND:
3483 case BPF_MSH:
3484 /*
3485 * Yes; are we in cooked mode?
3486 */
3487 if (handle->md.cooked) {
3488 /*
3489 * Yes, so we need to fix this
3490 * instruction.
3491 */
3492 if (fix_offset(p) < 0) {
3493 /*
3494 * We failed to do so.
3495 * Return 0, so our caller
3496 * knows to punt to userland.
3497 */
3498 return 0;
3499 }
3500 }
3501 break;
3502 }
3503 break;
3504 }
3505 }
3506 return 1; /* we succeeded */
3507 }
3508
3509 static int
3510 fix_offset(struct bpf_insn *p)
3511 {
3512 /*
3513 * What's the offset?
3514 */
3515 if (p->k >= SLL_HDR_LEN) {
3516 /*
3517 * It's within the link-layer payload; that starts at an
3518 * offset of 0, as far as the kernel packet filter is
3519 * concerned, so subtract the length of the link-layer
3520 * header.
3521 */
3522 p->k -= SLL_HDR_LEN;
3523 } else if (p->k == 14) {
3524 /*
3525 * It's the protocol field; map it to the special magic
3526 * kernel offset for that field.
3527 */
3528 p->k = SKF_AD_OFF + SKF_AD_PROTOCOL;
3529 } else {
3530 /*
3531 * It's within the header, but it's not one of those
3532 * fields; we can't do that in the kernel, so punt
3533 * to userland.
3534 */
3535 return -1;
3536 }
3537 return 0;
3538 }
3539
3540 static int
3541 set_kernel_filter(pcap_t *handle, struct sock_fprog *fcode)
3542 {
3543 int total_filter_on = 0;
3544 int save_mode;
3545 int ret;
3546 int save_errno;
3547
3548 /*
3549 * The socket filter code doesn't discard all packets queued
3550 * up on the socket when the filter is changed; this means
3551 * that packets that don't match the new filter may show up
3552 * after the new filter is put onto the socket, if those
3553 * packets haven't yet been read.
3554 *
3555 * This means, for example, that if you do a tcpdump capture
3556 * with a filter, the first few packets in the capture might
3557 * be packets that wouldn't have passed the filter.
3558 *
3559 * We therefore discard all packets queued up on the socket
3560 * when setting a kernel filter. (This isn't an issue for
3561 * userland filters, as the userland filtering is done after
3562 * packets are queued up.)
3563 *
3564 * To flush those packets, we put the socket in read-only mode,
3565 * and read packets from the socket until there are no more to
3566 * read.
3567 *
3568 * In order to keep that from being an infinite loop - i.e.,
3569 * to keep more packets from arriving while we're draining
3570 * the queue - we put the "total filter", which is a filter
3571 * that rejects all packets, onto the socket before draining
3572 * the queue.
3573 *
3574 * This code deliberately ignores any errors, so that you may
3575 * get bogus packets if an error occurs, rather than having
3576 * the filtering done in userland even if it could have been
3577 * done in the kernel.
3578 */
3579 if (setsockopt(handle->fd, SOL_SOCKET, SO_ATTACH_FILTER,
3580 &total_fcode, sizeof(total_fcode)) == 0) {
3581 char drain[1];
3582
3583 /*
3584 * Note that we've put the total filter onto the socket.
3585 */
3586 total_filter_on = 1;
3587
3588 /*
3589 * Save the socket's current mode, and put it in
3590 * non-blocking mode; we drain it by reading packets
3591 * until we get an error (which is normally a
3592 * "nothing more to be read" error).
3593 */
3594 save_mode = fcntl(handle->fd, F_GETFL, 0);
3595 if (save_mode != -1 &&
3596 fcntl(handle->fd, F_SETFL, save_mode | O_NONBLOCK) >= 0) {
3597 while (recv(handle->fd, &drain, sizeof drain,
3598 MSG_TRUNC) >= 0)
3599 ;
3600 save_errno = errno;
3601 fcntl(handle->fd, F_SETFL, save_mode);
3602 if (save_errno != EAGAIN) {
3603 /* Fatal error */
3604 reset_kernel_filter(handle);
3605 snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
3606 "recv: %s", pcap_strerror(save_errno));
3607 return -2;
3608 }
3609 }
3610 }
3611
3612 /*
3613 * Now attach the new filter.
3614 */
3615 ret = setsockopt(handle->fd, SOL_SOCKET, SO_ATTACH_FILTER,
3616 fcode, sizeof(*fcode));
3617 if (ret == -1 && total_filter_on) {
3618 /*
3619 * Well, we couldn't set that filter on the socket,
3620 * but we could set the total filter on the socket.
3621 *
3622 * This could, for example, mean that the filter was
3623 * too big to put into the kernel, so we'll have to
3624 * filter in userland; in any case, we'll be doing
3625 * filtering in userland, so we need to remove the
3626 * total filter so we see packets.
3627 */
3628 save_errno = errno;
3629
3630 /*
3631 * XXX - if this fails, we're really screwed;
3632 * we have the total filter on the socket,
3633 * and it won't come off. What do we do then?
3634 */
3635 reset_kernel_filter(handle);
3636
3637 errno = save_errno;
3638 }
3639 return ret;
3640 }
3641
3642 static int
3643 reset_kernel_filter(pcap_t *handle)
3644 {
3645 /*
3646 * setsockopt() barfs unless it get a dummy parameter.
3647 * valgrind whines unless the value is initialized,
3648 * as it has no idea that setsockopt() ignores its
3649 * parameter.
3650 */
3651 int dummy = 0;
3652
3653 return setsockopt(handle->fd, SOL_SOCKET, SO_DETACH_FILTER,
3654 &dummy, sizeof(dummy));
3655 }
3656 #endif