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