]> The Tcpdump Group git mirrors - libpcap/blob - pcap-linux.c
Improve the error message printed if you try to use the "any" device on
[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 #ifndef lint
28 static const char rcsid[] =
29 "@(#) $Header: /tcpdump/master/libpcap/pcap-linux.c,v 1.43 2000-12-18 00:20:51 guy Exp $ (LBL)";
30 #endif
31
32 /*
33 * Known problems with 2.0[.x] kernels:
34 *
35 * - The loopback device gives every packet twice; on 2.2[.x] kernels,
36 * if we use PF_PACKET, we can filter out the transmitted version
37 * of the packet by using data in the "sockaddr_ll" returned by
38 * "recvfrom()", but, on 2.0[.x] kernels, we have to use
39 * PF_INET/SOCK_PACKET, which means "recvfrom()" supplies a
40 * "sockaddr_pkt" which doesn't give us enough information to let
41 * us do that.
42 *
43 * - We have to set the interface's IFF_PROMISC flag ourselves, if
44 * we're to run in promiscuous mode, which means we have to turn
45 * it off ourselves when we're done; the kernel doesn't keep track
46 * of how many sockets are listening promiscuously, which means
47 * it won't get turned off automatically when no sockets are
48 * listening promiscuously. We catch "pcap_close()" and, for
49 * interfaces we put into promiscuous mode, take them out of
50 * promiscuous mode - which isn't necessarily the right thing to
51 * do, if another socket also requested promiscuous mode between
52 * the time when we opened the socket and the time when we close
53 * the socket.
54 */
55
56
57 #ifdef HAVE_CONFIG_H
58 #include "config.h"
59 #endif
60
61 #include "pcap-int.h"
62
63 #include <errno.h>
64 #include <stdlib.h>
65 #include <unistd.h>
66 #include <fcntl.h>
67 #include <string.h>
68 #include <sys/socket.h>
69 #include <sys/ioctl.h>
70 #include <sys/utsname.h>
71 #include <net/if.h>
72 #include <netinet/in.h>
73 #include <linux/if_ether.h>
74 #include <netinet/if_ether.h>
75
76 #ifdef HAVE_NETPACKET_PACKET_H
77 #include <netpacket/packet.h>
78 #endif
79 #ifdef SO_ATTACH_FILTER
80 #include <linux/types.h>
81 #include <linux/filter.h>
82 #endif
83
84 #ifndef __GLIBC__
85 typedef int socklen_t;
86 #endif
87
88 #ifndef MSG_TRUNC
89 #define MSG_TRUNC 0
90 #endif
91
92 #define MAX_LINKHEADER_SIZE 256
93
94 /*
95 * When capturing on all interfaces we use this as the buffer size.
96 * Should be bigger then all MTUs that occur in real life.
97 * 64kB should be enough for now.
98 */
99 #define BIGGER_THAN_ALL_MTUS (64*1024)
100
101 /*
102 * Prototypes for internal functions
103 */
104 static int map_arphrd_to_dlt(int arptype );
105 static int live_open_old(pcap_t *, char *, int, int, char *);
106 static int live_open_new(pcap_t *, char *, int, int, char *);
107 static int pcap_read_packet(pcap_t *, pcap_handler, u_char *);
108
109 /*
110 * Wrap some ioctl calls
111 */
112 #ifdef HAVE_NETPACKET_PACKET_H
113 static int iface_get_id(int fd, const char *device, char *ebuf);
114 #endif
115 static int iface_get_mtu(int fd, const char *device, char *ebuf);
116 static int iface_get_arptype(int fd, const char *device, char *ebuf);
117 #ifdef HAVE_NETPACKET_PACKET_H
118 static int iface_bind(int fd, int ifindex, char *ebuf);
119 #endif
120 static int iface_bind_old(int fd, const char *device, char *ebuf);
121
122 /*
123 * Get a handle for a live capture from the given device. You can
124 * pass NULL as device to get all packages (without link level
125 * information of course). If you pass 1 as promisc the interface
126 * will be set to promiscous mode (XXX: I think this usage should
127 * be deprecated and functions be added to select that later allow
128 * modification of that values -- Torsten).
129 *
130 * See also pcap(3).
131 */
132 pcap_t *
133 pcap_open_live(char *device, int snaplen, int promisc, int to_ms, char *ebuf)
134 {
135 /* Allocate a handle for this session. */
136
137 pcap_t *handle = malloc(sizeof(*handle));
138 if (handle == NULL) {
139 snprintf(ebuf, PCAP_ERRBUF_SIZE, "malloc: %s",
140 pcap_strerror(errno));
141 return NULL;
142 }
143
144 /* Initialize some components of the pcap structure. */
145
146 memset(handle, 0, sizeof(*handle));
147 handle->snapshot = snaplen;
148 handle->md.timeout = to_ms;
149
150 /*
151 * NULL and "any" are special devices which give us the hint to
152 * monitor all devices.
153 */
154 if (!device || strcmp(device, "any") == 0) {
155 device = NULL;
156 handle->md.device = strdup("any");
157 } else
158 handle->md.device = strdup(device);
159
160 if (handle->md.device == NULL) {
161 snprintf(ebuf, PCAP_ERRBUF_SIZE, "strdup: %s",
162 pcap_strerror(errno) );
163 free(handle);
164 return NULL;
165 }
166
167 /*
168 * Current Linux kernels use the protocol family PF_PACKET to
169 * allow direct access to all packets on the network while
170 * older kernels had a special socket type SOCK_PACKET to
171 * implement this feature.
172 * While this old implementation is kind of obsolete we need
173 * to be compatible with older kernels for a while so we are
174 * trying both methods with the newer method preferred.
175 */
176
177 if (! (live_open_new(handle, device, promisc, to_ms, ebuf) ||
178 live_open_old(handle, device, promisc, to_ms, ebuf)) )
179 {
180 /*
181 * Both methods to open the packet socket failed. Tidy
182 * up and report our failure (ebuf is expected to be
183 * set by the functions above).
184 */
185
186 free(handle->md.device);
187 free(handle);
188 return NULL;
189 }
190
191 /*
192 * Okay, now we have a packet stream open. Maybe we need to handle
193 * a timeout? In that case we set the filehandle to nonblocking
194 * so pcap_read can try reading the fd and call select if no data
195 * is available at first.
196 */
197
198 if (to_ms > 0) {
199 int flags = fcntl(handle->fd, F_GETFL);
200 if (flags != -1) {
201 flags |= O_NONBLOCK;
202 flags = fcntl(handle->fd, F_SETFL, flags);
203 }
204 if (flags == -1) {
205 snprintf(ebuf, PCAP_ERRBUF_SIZE, "fcntl: %s",
206 pcap_strerror(errno));
207 pcap_close(handle);
208 return NULL;
209 }
210 }
211
212 return handle;
213 }
214
215 /*
216 * Read at most max_packets from the capture stream and call the callback
217 * for each of them. Returns the number of packets handled or -1 if an
218 * error occured.
219 *
220 * XXX: Can I rely on the Linux-specified behaviour of select (returning
221 * the time left in the timeval structure)? I really don't want to query
222 * the system time before each select call...
223 *
224 * pcap_read currently gets not only a packet from the kernel but also
225 * the sockaddr_ll returned as source of the packet. This way we can at
226 * some time extend tcpdump and libpcap to sniff on all devices at a time
227 * and find the right printing routine by using the information in the
228 * sockaddr_ll structure.
229 */
230 int
231 pcap_read(pcap_t *handle, int max_packets, pcap_handler callback, u_char *user)
232 {
233 int status, packets;
234 fd_set read_fds;
235 struct timeval tv;
236
237 /*
238 * Fill in a timeval structure for select if we need to obeye a
239 * timeout.
240 */
241 if (handle->md.timeout > 0) {
242 tv.tv_usec = (handle->md.timeout % 1000) * 1000;
243 tv.tv_sec = (handle->md.timeout / 1000);
244 }
245
246 /*
247 * Read packets until the packet limit has been reached or
248 * an error occured while reading. Call the user function
249 * for each received packet.
250 */
251 for (packets = 0; max_packets == -1 || packets < max_packets;)
252 {
253 status = pcap_read_packet(handle, callback, user);
254
255 if (status > 0) {
256 packets += status;
257 continue;
258 } else if (status == -1)
259 return -1;
260
261 /*
262 * If no packet is available we go to sleep. FIXME: This
263 * might be better implemented using poll(?)
264 */
265 FD_ZERO(&read_fds);
266 FD_SET(handle->fd, &read_fds);
267 status = select(handle->fd + 1,
268 &read_fds, NULL, NULL, &tv);
269
270 if (status == -1) {
271 if (errno == EINTR)
272 return packets;
273 snprintf(handle->errbuf, sizeof(handle->errbuf),
274 "select: %s", pcap_strerror(errno));
275 return -1;
276 }
277 else if (status == 0 ||
278 (tv.tv_usec == 0 && tv.tv_sec == 0))
279 return packets;
280 }
281
282 return packets;
283 }
284
285 /*
286 * Read a packet from the socket calling the handler provided by
287 * the user. Returns the number of packets received or -1 if an
288 * error occured.
289 */
290 static int
291 pcap_read_packet(pcap_t *handle, pcap_handler callback, u_char *userdata)
292 {
293 #ifdef HAVE_NETPACKET_PACKET_H
294 struct sockaddr_ll from;
295 #else
296 struct sockaddr from;
297 #endif
298 socklen_t fromlen;
299 int packet_len, caplen;
300 struct pcap_pkthdr pcap_header;
301
302 /*
303 * We don't currently use the from return value of recvfrom but
304 * this will probably be implemented in the future.
305 */
306
307 /* Receive a single packet from the kernel */
308
309 do {
310 fromlen = sizeof(from);
311 packet_len = recvfrom(
312 handle->fd, handle->buffer + handle->offset,
313 handle->md.readlen, MSG_TRUNC,
314 (struct sockaddr *) &from, &fromlen);
315 } while (packet_len == -1 && errno == EINTR);
316
317 /* Check if an error occured */
318
319 if (packet_len == -1) {
320 if (errno == EAGAIN)
321 return 0; /* no packet there */
322 else {
323 snprintf(handle->errbuf, sizeof(handle->errbuf),
324 "recvfrom: %s", pcap_strerror(errno));
325 return -1;
326 }
327 }
328
329 #ifdef HAVE_NETPACKET_PACKET_H
330 /*
331 * If this is from the loopback device, reject outgoing packets;
332 * we'll see the packet as an incoming packet as well, and
333 * we don't want to see it twice.
334 *
335 * We can only do this if we're using PF_PACKET; the address
336 * returned for SOCK_PACKET is a "sockaddr_pkt" which lacks
337 * the relevant packet type information.
338 */
339 if (!handle->md.sock_packet &&
340 from.sll_ifindex == handle->md.lo_ifindex &&
341 from.sll_pkttype == PACKET_OUTGOING)
342 return 0;
343 #endif
344
345 /*
346 * XXX: According to the kernel source we should get the real
347 * packet len if calling recvfrom with MSG_TRUNC set. It does
348 * not seem to work here :(, but it is supported by this code
349 * anyway.
350 * To be honest the code RELIES on that feature so this is really
351 * broken with 2.2.x kernels.
352 * I spend a day to figure out what's going on and I found out
353 * that the following is happening:
354 *
355 * The packet comes from a random interface and the packet_rcv
356 * hook is called with a clone of the packet. That code inserts
357 * the packet into the receive queue of the packet socket.
358 * If a filter is attached to that socket that filter is run
359 * first - and there lies the problem. The default filter always
360 * cuts the packet at the snaplen:
361 *
362 * # tcpdump -d
363 * (000) ret #68
364 *
365 * So the packet filter cuts down the packet. The recvfrom call
366 * says "hey, it's only 68 bytes, it fits into the buffer" with
367 * the result that we don't get the real packet length. This
368 * is valid at least until kernel 2.2.17pre6.
369 *
370 * tcpdump is currently fixed by changing the BPF code generator
371 * to not truncate the received packet.
372 */
373
374 caplen = packet_len;
375 if (caplen > handle->snapshot)
376 caplen = handle->snapshot;
377
378 /* Run the packet filter if not using kernel filter */
379 if (!handle->md.use_bpf && handle->fcode.bf_insns) {
380 if (bpf_filter(handle->fcode.bf_insns, handle->buffer,
381 packet_len, caplen) == 0)
382 {
383 /* rejected by filter */
384 return 0;
385 }
386 }
387
388 /* Fill in our own header data */
389
390 if (ioctl(handle->fd, SIOCGSTAMP, &pcap_header.ts) == -1) {
391 snprintf(handle->errbuf, sizeof(handle->errbuf),
392 "ioctl: %s", pcap_strerror(errno));
393 return -1;
394 }
395 pcap_header.caplen = caplen;
396 pcap_header.len = packet_len;
397
398 /* Call the user supplied callback function */
399 handle->md.stat.ps_recv++;
400 callback(userdata, &pcap_header, handle->buffer + handle->offset);
401
402 return 1;
403 }
404
405 /*
406 * Get the statistics for the given packet capture handle.
407 * FIXME: Currently does not report the number of dropped packets.
408 */
409 int
410 pcap_stats(pcap_t *handle, struct pcap_stat *stats)
411 {
412 *stats = handle->md.stat;
413 return 0;
414 }
415
416 /*
417 * Attach the given BPF code to the packet capture device.
418 */
419 int
420 pcap_setfilter(pcap_t *handle, struct bpf_program *filter)
421 {
422 #ifdef SO_ATTACH_FILTER
423 struct sock_fprog fcode;
424 #endif
425
426 if (!handle)
427 return -1;
428 if (!filter) {
429 strncpy(handle->errbuf, "setfilter: No filter specified",
430 sizeof(handle->errbuf));
431 return -1;
432 }
433
434 /* Make our private copy of the filter */
435
436 if (install_bpf_program(handle, filter) < 0) {
437 snprintf(handle->errbuf, sizeof(handle->errbuf),
438 "malloc: %s", pcap_strerror(errno));
439 return -1;
440 }
441
442 /*
443 * Run user level packet filter by default. Will be overriden if
444 * installing a kernel filter succeeds.
445 */
446 handle->md.use_bpf = 0;
447
448 /*
449 * If we're reading from a savefile, don't try to install
450 * a kernel filter.
451 */
452 if (handle->sf.rfile != NULL)
453 return 0;
454
455 /* Install kernel level filter if possible */
456
457 #ifdef SO_ATTACH_FILTER
458 /*
459 * Oh joy, the Linux kernel uses struct sock_fprog instead of
460 * struct bpf_program and of course the length field is of
461 * different size. Pointed out by Sebastian
462 */
463
464 fcode.filter = (struct sock_filter *) handle->fcode.bf_insns;
465 fcode.len = filter->bf_len;
466 #ifdef USHRT_MAX
467 if (filter->bf_len > USHRT_MAX) {
468 /*
469 * fcode.len is an unsigned short for current kernel.
470 * I have yet to see BPF-Code with that much instructions
471 * but still it is possible. So for the sake of
472 * correctness I added this check.
473 */
474 fprintf(stderr, "Warning: Filter to complex for kernel\n");
475 }
476 else
477 #endif
478 if (setsockopt(handle->fd, SOL_SOCKET, SO_ATTACH_FILTER,
479 &fcode, sizeof(fcode)) == 0)
480 {
481 /* Installation succeded - using kernel filter. */
482 handle->md.use_bpf = 1;
483 }
484 else
485 {
486 /*
487 * Print a warning if kernel filter available but a problem
488 * occured using it.
489 */
490 if (errno != ENOPROTOOPT && errno != EOPNOTSUPP) {
491 fprintf(stderr, "Warning: Kernel filter failed: %s\n",
492 pcap_strerror(errno));
493 }
494 }
495 #endif
496
497 return 0;
498 }
499
500 /*
501 * Linux uses the ARP hardware type to identify the type of an
502 * interface. pcap uses the DLT_xxx constants for this. This
503 * function maps the ARPHRD_xxx constant to an appropriate
504 * DLT_xxx constant.
505 *
506 * Returns -1 if unable to map the type.
507 */
508 static int map_arphrd_to_dlt(int arptype)
509 {
510 switch (arptype) {
511 case ARPHRD_ETHER:
512 case ARPHRD_METRICOM:
513 case ARPHRD_LOOPBACK: return DLT_EN10MB;
514 case ARPHRD_EETHER: return DLT_EN3MB;
515 case ARPHRD_AX25: return DLT_AX25;
516 case ARPHRD_PRONET: return DLT_PRONET;
517 case ARPHRD_CHAOS: return DLT_CHAOS;
518 #ifndef ARPHRD_IEEE802_TR
519 #define ARPHRD_IEEE802_TR 800 /* From Linux 2.4 */
520 #endif
521 case ARPHRD_IEEE802_TR:
522 case ARPHRD_IEEE802: return DLT_IEEE802;
523 case ARPHRD_ARCNET: return DLT_ARCNET;
524 case ARPHRD_FDDI: return DLT_FDDI;
525
526 #ifndef ARPHRD_ATM /* FIXME: How to #include this? */
527 #define ARPHRD_ATM 19
528 #endif
529 case ARPHRD_ATM: return DLT_ATM_CLIP;
530
531 case ARPHRD_SIT:
532 case ARPHRD_PPP:
533 case ARPHRD_CSLIP:
534 case ARPHRD_SLIP6:
535 case ARPHRD_CSLIP6:
536 case ARPHRD_SLIP: return DLT_RAW;
537 }
538
539 return -1;
540 }
541
542 /* ===== Functions to interface to the newer kernels ================== */
543
544 /*
545 * Try to open a packet socket using the new kernel interface.
546 * Returns 0 on failure.
547 * FIXME: 0 uses to mean success (Sebastian)
548 */
549 static int
550 live_open_new(pcap_t *handle, char *device, int promisc,
551 int to_ms, char *ebuf)
552 {
553 #ifdef HAVE_NETPACKET_PACKET_H
554 int sock_fd = -1, device_id, mtu, arptype;
555 struct packet_mreq mr;
556
557 /* One shot loop used for error handling - bail out with break */
558
559 do {
560 /*
561 * Open a socket with protocol family packet. If a device is
562 * given we try to open it in raw mode otherwise we use
563 * the cooked interface.
564 */
565 sock_fd = device ?
566 socket(PF_PACKET, SOCK_RAW, htons(ETH_P_ALL))
567 : socket(PF_PACKET, SOCK_DGRAM, htons(ETH_P_ALL));
568
569 if (sock_fd == -1) {
570 snprintf(ebuf, PCAP_ERRBUF_SIZE, "socket: %s",
571 pcap_strerror(errno) );
572 break;
573 }
574
575 /* It seems the kernel supports the new interface. */
576 handle->md.sock_packet = 0;
577
578 /*
579 * Get the interface index of the loopback device.
580 * If the attempt fails, don't fail, just set the
581 * "md.lo_ifindex" to -1.
582 *
583 * XXX - can there be more than one device that loops
584 * packets back, i.e. devices other than "lo"? If so,
585 * we'd need to find them all, and have an array of
586 * indices for them, and check all of them in
587 * "pcap_read_packet()".
588 */
589 handle->md.lo_ifindex = iface_get_id(sock_fd, "lo", ebuf);
590
591 /*
592 * What kind of frames do we have to deal with? Fall back
593 * to cooked mode if we have an unknown interface type.
594 */
595
596 if (device) {
597 arptype = iface_get_arptype(sock_fd, device, ebuf);
598 if (arptype == -1)
599 break;
600 handle->linktype = map_arphrd_to_dlt(arptype);
601 if (handle->linktype == -1) {
602 /*
603 * Unknown interface type - reopen in cooked
604 * mode.
605 */
606 if (close(sock_fd) == -1) {
607 snprintf(ebuf, PCAP_ERRBUF_SIZE,
608 "close: %s", pcap_strerror(errno));
609 break;
610 }
611 sock_fd = socket(PF_PACKET, SOCK_DGRAM,
612 htons(ETH_P_ALL));
613 if (sock_fd == -1) {
614 snprintf(ebuf, PCAP_ERRBUF_SIZE,
615 "socket: %s", pcap_strerror(errno));
616 break;
617 }
618
619 fprintf(stderr,
620 "Warning: arptype %d not supported by "
621 "libpcap - falling back to cooked "
622 "socket\n",
623 arptype);
624 handle->linktype = DLT_RAW;
625 }
626
627 device_id = iface_get_id(sock_fd, device, ebuf);
628 if (device_id == -1)
629 break;
630
631 if (iface_bind(sock_fd, device_id, ebuf) == -1)
632 break;
633 } else {
634 handle->linktype = DLT_RAW;
635
636 /*
637 * XXX - squelch GCC complaints about
638 * uninitialized variables; if we can't
639 * select promiscuous mode on all interfaces,
640 * we should move the code below into the
641 * "if (device)" branch of the "if" and
642 * get rid of the next statement.
643 */
644 device_id = -1;
645 }
646
647 /* Select promiscuous mode on/off */
648
649 #ifdef SOL_PACKET
650 /*
651 * Hmm, how can we set promiscuous mode on all interfaces?
652 * I am not sure if that is possible at all.
653 */
654
655 if (device) {
656 memset(&mr, 0, sizeof(mr));
657 mr.mr_ifindex = device_id;
658 mr.mr_type = promisc ?
659 PACKET_MR_PROMISC : PACKET_MR_ALLMULTI;
660 if (setsockopt(sock_fd, SOL_PACKET,
661 PACKET_ADD_MEMBERSHIP, &mr, sizeof(mr)) == -1)
662 {
663 snprintf(ebuf, PCAP_ERRBUF_SIZE,
664 "setsockopt: %s", pcap_strerror(errno));
665 break;
666 }
667 }
668 #endif
669
670 /* Compute the buffersize */
671
672 mtu = iface_get_mtu(sock_fd, device, ebuf);
673 if (mtu == -1)
674 break;
675 handle->bufsize = MAX_LINKHEADER_SIZE + mtu;
676
677 /* Fill in the pcap structure */
678
679 handle->fd = sock_fd;
680 handle->offset = 0;
681
682 handle->buffer = malloc(handle->bufsize);
683 if (!handle->buffer) {
684 snprintf(ebuf, PCAP_ERRBUF_SIZE,
685 "malloc: %s", pcap_strerror(errno));
686 break;
687 }
688
689 /*
690 * This is a 2.2 or later kernel, as it has PF_PACKET;
691 * "recvfrom()", when passed the MSG_TRUNC flag, will
692 * return the actual length of the packet, not the
693 * number of bytes from the packet copied to userland,
694 * so we can safely pass it a byte count based on the
695 * snapshot length.
696 */
697 handle->md.readlen = handle->snapshot;
698 return 1;
699
700 } while(0);
701
702 if (sock_fd != -1)
703 close(sock_fd);
704 return 0;
705 #else
706 strncpy(ebuf,
707 "New packet capturing interface not supported by build "
708 "environment", PCAP_ERRBUF_SIZE);
709 return 0;
710 #endif
711 }
712
713 #ifdef HAVE_NETPACKET_PACKET_H
714 /*
715 * Return the index of the given device name. Fill ebuf and return
716 * -1 on failure.
717 */
718 static int
719 iface_get_id(int fd, const char *device, char *ebuf)
720 {
721 struct ifreq ifr;
722
723 memset(&ifr, 0, sizeof(ifr));
724 strncpy(ifr.ifr_name, device, sizeof(ifr.ifr_name));
725
726 if (ioctl(fd, SIOCGIFINDEX, &ifr) == -1) {
727 snprintf(ebuf, PCAP_ERRBUF_SIZE,
728 "ioctl: %s", pcap_strerror(errno));
729 return -1;
730 }
731
732 return ifr.ifr_ifindex;
733 }
734
735 /*
736 * Bind the socket associated with FD to the given device.
737 */
738 static int
739 iface_bind(int fd, int ifindex, char *ebuf)
740 {
741 struct sockaddr_ll sll;
742
743 memset(&sll, 0, sizeof(sll));
744 sll.sll_family = AF_PACKET;
745 sll.sll_ifindex = ifindex;
746 sll.sll_protocol = htons(ETH_P_ALL);
747
748 if (bind(fd, (struct sockaddr *) &sll, sizeof(sll)) == -1) {
749 snprintf(ebuf, PCAP_ERRBUF_SIZE,
750 "bind: %s", pcap_strerror(errno));
751 return -1;
752 }
753
754 return 0;
755 }
756
757 #endif
758
759
760 /* ===== Functions to interface to the older kernels ================== */
761
762 /*
763 * With older kernels promiscuous mode is kind of interesting because we
764 * have to reset the interface before exiting. The problem can't really
765 * be solved without some daemon taking care of managing usage counts.
766 * If we put the interface into promiscuous mode, we set a flag indicating
767 * that we must take it out of that mode when the interface is closed,
768 * and, when closing the interface, if that flag is set we take it out
769 * of promiscuous mode.
770 */
771
772 /*
773 * List of pcaps for which we turned promiscuous mode on by hand.
774 * If there are any such pcaps, we arrange to call "pcap_close_all()"
775 * when we exit, and have it close all of them to turn promiscuous mode
776 * off.
777 */
778 static struct pcap *pcaps_to_close;
779
780 /*
781 * TRUE if we've already called "atexit()" to cause "pcap_close_all()" to
782 * be called on exit.
783 */
784 static int did_atexit;
785
786 static void pcap_close_all(void)
787 {
788 struct pcap *handle;
789
790 while ((handle = pcaps_to_close) != NULL)
791 pcap_close(handle);
792 }
793
794 void pcap_close_linux( pcap_t *handle )
795 {
796 struct pcap *p, *prevp;
797 struct ifreq ifr;
798
799 if (handle->md.clear_promisc) {
800 /*
801 * We put the interface into promiscuous mode; take
802 * it out of promiscuous mode.
803 *
804 * XXX - if somebody else wants it in promiscuous mode,
805 * this code cannot know that, so it'll take it out
806 * of promiscuous mode. That's not fixable in 2.0[.x]
807 * kernels.
808 */
809 memset(&ifr, 0, sizeof(ifr));
810 strncpy(ifr.ifr_name, handle->md.device, sizeof(ifr.ifr_name));
811 if (ioctl(handle->fd, SIOCGIFFLAGS, &ifr) == -1) {
812 fprintf(stderr,
813 "Can't restore interface flags (SIOCGIFFLAGS failed: %s).\n"
814 "Please adjust manually.\n"
815 "Hint: This can't happen with Linux >= 2.2.0.\n",
816 strerror(errno));
817 } else {
818 if (ifr.ifr_flags & IFF_PROMISC) {
819 /*
820 * Promiscuous mode is currently on; turn it
821 * off.
822 */
823 ifr.ifr_flags &= ~IFF_PROMISC;
824 if (ioctl(handle->fd, SIOCSIFFLAGS, &ifr) == -1) {
825 fprintf(stderr,
826 "Can't restore interface flags (SIOCSIFFLAGS failed: %s).\n"
827 "Please adjust manually.\n"
828 "Hint: This can't happen with Linux >= 2.2.0.\n",
829 strerror(errno));
830 }
831 }
832 }
833
834 /*
835 * Take this pcap out of the list of pcaps for which we
836 * have to take the interface out of promiscuous mode.
837 */
838 for (p = pcaps_to_close, prevp = NULL; p != NULL;
839 prevp = p, p = p->md.next) {
840 if (p == handle) {
841 /*
842 * Found it. Remove it from the list.
843 */
844 if (prevp == NULL) {
845 /*
846 * It was at the head of the list.
847 */
848 pcaps_to_close = p->md.next;
849 } else {
850 /*
851 * It was in the middle of the list.
852 */
853 prevp->md.next = p->md.next;
854 }
855 break;
856 }
857 }
858 }
859 if (handle->md.device != NULL)
860 free(handle->md.device);
861 }
862
863 /*
864 * Try to open a packet socket using the old kernel interface.
865 * Returns 0 on failure.
866 * FIXME: 0 uses to mean success (Sebastian)
867 */
868 static int
869 live_open_old(pcap_t *handle, char *device, int promisc,
870 int to_ms, char *ebuf)
871 {
872 int sock_fd = -1, mtu, arptype;
873 struct utsname utsname;
874 struct ifreq ifr;
875
876 do {
877 /* Open the socket */
878
879 sock_fd = socket(PF_INET, SOCK_PACKET, htons(ETH_P_ALL));
880 if (sock_fd == -1) {
881 snprintf(ebuf, PCAP_ERRBUF_SIZE,
882 "socket: %s", pcap_strerror(errno));
883 break;
884 }
885
886 /* It worked - we are using the old interface */
887 handle->md.sock_packet = 1;
888
889 /* Bind to the given device */
890
891 if (!device) {
892 strncpy(ebuf, "pcap_open_live: The \"any\" device isn't supported on 2.0[.x]-kernel systems",
893 PCAP_ERRBUF_SIZE);
894 break;
895 }
896 if (iface_bind_old(sock_fd, device, ebuf) == -1)
897 break;
898
899 /* Go to promisc mode */
900 if (promisc) {
901 memset(&ifr, 0, sizeof(ifr));
902 strncpy(ifr.ifr_name, device, sizeof(ifr.ifr_name));
903 if (ioctl(sock_fd, SIOCGIFFLAGS, &ifr) == -1) {
904 snprintf(ebuf, PCAP_ERRBUF_SIZE,
905 "ioctl: %s", pcap_strerror(errno));
906 break;
907 }
908 if ((ifr.ifr_flags & IFF_PROMISC) == 0) {
909 /*
910 * Promiscuous mode isn't currently on,
911 * so turn it on, and remember that
912 * we should turn it off when the
913 * pcap_t is closed.
914 */
915
916 /*
917 * If we haven't already done so, arrange
918 * to have "pcap_close_all()" called when
919 * we exit.
920 */
921 if (!did_atexit) {
922 if (atexit(pcap_close_all) == -1) {
923 /*
924 * "atexit()" failed; don't
925 * put the interface in
926 * promiscuous mode, just
927 * give up.
928 */
929 strncpy(ebuf, "atexit failed",
930 PCAP_ERRBUF_SIZE);
931 break;
932 }
933 }
934
935 ifr.ifr_flags |= IFF_PROMISC;
936 if (ioctl(sock_fd, SIOCSIFFLAGS, &ifr) == -1) {
937 snprintf(ebuf, PCAP_ERRBUF_SIZE,
938 "ioctl: %s",
939 pcap_strerror(errno));
940 break;
941 }
942 handle->md.clear_promisc = 1;
943
944 /*
945 * Add this to the list of pcaps
946 * to close when we exit.
947 */
948 handle->md.next = pcaps_to_close;
949 pcaps_to_close = handle;
950 }
951 }
952
953 /* Compute the buffersize */
954
955 mtu = iface_get_mtu(sock_fd, device, ebuf);
956 if (mtu == -1)
957 break;
958 handle->bufsize = MAX_LINKHEADER_SIZE + mtu;
959 if (handle->bufsize < handle->snapshot)
960 handle->bufsize = handle->snapshot;
961
962 /* All done - fill in the pcap handle */
963
964 arptype = iface_get_arptype(sock_fd, device, ebuf);
965 if (arptype == -1)
966 break;
967
968 handle->fd = sock_fd;
969 handle->offset = 0;
970 handle->linktype = map_arphrd_to_dlt(arptype);
971 if (handle->linktype == -1) {
972 snprintf(ebuf, PCAP_ERRBUF_SIZE,
973 "interface type of %s not supported", device);
974 break;
975 }
976 handle->buffer = malloc(handle->bufsize);
977 if (!handle->buffer) {
978 snprintf(ebuf, PCAP_ERRBUF_SIZE,
979 "malloc: %s", pcap_strerror(errno));
980 break;
981 }
982
983 /*
984 * This might be a 2.0[.x] kernel - check.
985 */
986 if (uname(&utsname) < 0 ||
987 strncmp(utsname.release, "2.0", 3) == 0) {
988 /*
989 * Either we couldn't find out what kernel release
990 * this is, or it's a 2.0[.x] kernel.
991 *
992 * In the 2.0[.x] kernel, a "recvfrom()" on
993 * a SOCK_PACKET socket, with MSG_TRUNC set, will
994 * return the number of bytes read, so if we pass
995 * a length based on the snapshot length, it'll
996 * return the number of bytes from the packet
997 * copied to userland, not the actual length
998 * of the packet.
999 *
1000 * This means that, for example, the IP dissector
1001 * in tcpdump will get handed a packet length less
1002 * than the length in the IP header, and will
1003 * complain about "truncated-ip".
1004 *
1005 * So we don't bother trying to copy from the
1006 * kernel only the bytes in which we're interested,
1007 * but instead copy them all, just as the older
1008 * versions of libpcap for Linux did.
1009 *
1010 * Just one of many problems with packet capture
1011 * on 2.0[.x] kernels; you really want a 2.2[.x]
1012 * or later kernel if you want packet capture to
1013 * work well.
1014 */
1015 handle->md.readlen = handle->bufsize;
1016 } else {
1017 /*
1018 * This is a 2.2[.x] or later kernel (although
1019 * why we're using SOCK_PACKET on such a system
1020 * is unknown to me).
1021 *
1022 * We can safely pass "recvfrom()" a byte count
1023 * based on the snapshot length.
1024 */
1025 handle->md.readlen = handle->snapshot;
1026 }
1027 return 1;
1028
1029 } while (0);
1030
1031 if (sock_fd != -1)
1032 close(sock_fd);
1033 return 0;
1034 }
1035
1036 /*
1037 * Bind the socket associated with FD to the given device using the
1038 * interface of the old kernels.
1039 */
1040 static int
1041 iface_bind_old(int fd, const char *device, char *ebuf)
1042 {
1043 struct sockaddr saddr;
1044
1045 memset(&saddr, 0, sizeof(saddr));
1046 strncpy(saddr.sa_data, device, sizeof(saddr.sa_data));
1047 if (bind(fd, &saddr, sizeof(saddr)) == -1) {
1048 snprintf(ebuf, PCAP_ERRBUF_SIZE,
1049 "bind: %s", pcap_strerror(errno));
1050 return -1;
1051 }
1052
1053 return 0;
1054 }
1055
1056
1057 /* ===== System calls available on all supported kernels ============== */
1058
1059 /*
1060 * Query the kernel for the MTU of the given interface.
1061 */
1062 static int
1063 iface_get_mtu(int fd, const char *device, char *ebuf)
1064 {
1065 struct ifreq ifr;
1066
1067 if (!device)
1068 return BIGGER_THAN_ALL_MTUS;
1069
1070 memset(&ifr, 0, sizeof(ifr));
1071 strncpy(ifr.ifr_name, device, sizeof(ifr.ifr_name));
1072
1073 if (ioctl(fd, SIOCGIFMTU, &ifr) == -1) {
1074 snprintf(ebuf, PCAP_ERRBUF_SIZE,
1075 "ioctl: %s", pcap_strerror(errno));
1076 return -1;
1077 }
1078
1079 return ifr.ifr_mtu;
1080 }
1081
1082 /*
1083 * Get the hardware type of the given interface as ARPHRD_xxx constant.
1084 */
1085 static int
1086 iface_get_arptype(int fd, const char *device, char *ebuf)
1087 {
1088 struct ifreq ifr;
1089
1090 memset(&ifr, 0, sizeof(ifr));
1091 strncpy(ifr.ifr_name, device, sizeof(ifr.ifr_name));
1092
1093 if (ioctl(fd, SIOCGIFHWADDR, &ifr) == -1) {
1094 snprintf(ebuf, PCAP_ERRBUF_SIZE,
1095 "ioctl: %s", pcap_strerror(errno));
1096 return -1;
1097 }
1098
1099 return ifr.ifr_hwaddr.sa_family;
1100 }