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