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