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