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