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