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