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