+ default:
+ snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
+ "recvfrom: %s", pcap_strerror(errno));
+ return PCAP_ERROR;
+ }
+ }
+
+#ifdef HAVE_PF_PACKET_SOCKETS
+ if (!handle->md.sock_packet) {
+ /*
+ * Unfortunately, there is a window between socket() and
+ * bind() where the kernel may queue packets from any
+ * interface. If we're bound to a particular interface,
+ * discard packets not from that interface.
+ *
+ * (If socket filters are supported, we could do the
+ * same thing we do when changing the filter; however,
+ * that won't handle packet sockets without socket
+ * filter support, and it's a bit more complicated.
+ * It would save some instructions per packet, however.)
+ */
+ if (handle->md.ifindex != -1 &&
+ from.sll_ifindex != handle->md.ifindex)
+ return 0;
+
+ /*
+ * Do checks based on packet direction.
+ * We can only do this if we're using PF_PACKET; the
+ * address returned for SOCK_PACKET is a "sockaddr_pkt"
+ * which lacks the relevant packet type information.
+ */
+ if (from.sll_pkttype == PACKET_OUTGOING) {
+ /*
+ * Outgoing packet.
+ * If this is from the loopback device, reject it;
+ * we'll see the packet as an incoming packet as well,
+ * and we don't want to see it twice.
+ */
+ if (from.sll_ifindex == handle->md.lo_ifindex)
+ return 0;
+
+ /*
+ * If the user only wants incoming packets, reject it.
+ */
+ if (handle->direction == PCAP_D_IN)
+ return 0;
+ } else {
+ /*
+ * Incoming packet.
+ * If the user only wants outgoing packets, reject it.
+ */
+ if (handle->direction == PCAP_D_OUT)
+ return 0;
+ }
+ }
+#endif
+
+#ifdef HAVE_PF_PACKET_SOCKETS
+ /*
+ * If this is a cooked device, fill in the fake packet header.
+ */
+ if (handle->md.cooked) {
+ /*
+ * Add the length of the fake header to the length
+ * of packet data we read.
+ */
+ packet_len += SLL_HDR_LEN;
+
+ hdrp = (struct sll_header *)bp;
+ hdrp->sll_pkttype = map_packet_type_to_sll_type(from.sll_pkttype);
+ hdrp->sll_hatype = htons(from.sll_hatype);
+ hdrp->sll_halen = htons(from.sll_halen);
+ memcpy(hdrp->sll_addr, from.sll_addr,
+ (from.sll_halen > SLL_ADDRLEN) ?
+ SLL_ADDRLEN :
+ from.sll_halen);
+ hdrp->sll_protocol = from.sll_protocol;
+ }
+
+#if defined(HAVE_PACKET_AUXDATA) && defined(HAVE_LINUX_TPACKET_AUXDATA_TP_VLAN_TCI)
+ if (handle->md.vlan_offset != -1) {
+ for (cmsg = CMSG_FIRSTHDR(&msg); cmsg; cmsg = CMSG_NXTHDR(&msg, cmsg)) {
+ struct tpacket_auxdata *aux;
+ unsigned int len;
+ struct vlan_tag *tag;
+
+ if (cmsg->cmsg_len < CMSG_LEN(sizeof(struct tpacket_auxdata)) ||
+ cmsg->cmsg_level != SOL_PACKET ||
+ cmsg->cmsg_type != PACKET_AUXDATA)
+ continue;
+
+ aux = (struct tpacket_auxdata *)CMSG_DATA(cmsg);
+#if defined(TP_STATUS_VLAN_VALID)
+ if ((aux->tp_vlan_tci == 0) && !(aux->tp_status & TP_STATUS_VLAN_VALID))
+#else
+ if (aux->tp_vlan_tci == 0) /* this is ambigious but without the
+ TP_STATUS_VLAN_VALID flag, there is
+ nothing that we can do */
+#endif
+ continue;
+
+ len = packet_len > iov.iov_len ? iov.iov_len : packet_len;
+ if (len < (unsigned int) handle->md.vlan_offset)
+ break;
+
+ bp -= VLAN_TAG_LEN;
+ memmove(bp, bp + VLAN_TAG_LEN, handle->md.vlan_offset);
+
+ tag = (struct vlan_tag *)(bp + handle->md.vlan_offset);
+ tag->vlan_tpid = htons(ETH_P_8021Q);
+ tag->vlan_tci = htons(aux->tp_vlan_tci);
+
+ packet_len += VLAN_TAG_LEN;
+ }
+ }
+#endif /* defined(HAVE_PACKET_AUXDATA) && defined(HAVE_LINUX_TPACKET_AUXDATA_TP_VLAN_TCI) */
+#endif /* HAVE_PF_PACKET_SOCKETS */
+
+ /*
+ * XXX: According to the kernel source we should get the real
+ * packet len if calling recvfrom with MSG_TRUNC set. It does
+ * not seem to work here :(, but it is supported by this code
+ * anyway.
+ * To be honest the code RELIES on that feature so this is really
+ * broken with 2.2.x kernels.
+ * I spend a day to figure out what's going on and I found out
+ * that the following is happening:
+ *
+ * The packet comes from a random interface and the packet_rcv
+ * hook is called with a clone of the packet. That code inserts
+ * the packet into the receive queue of the packet socket.
+ * If a filter is attached to that socket that filter is run
+ * first - and there lies the problem. The default filter always
+ * cuts the packet at the snaplen:
+ *
+ * # tcpdump -d
+ * (000) ret #68
+ *
+ * So the packet filter cuts down the packet. The recvfrom call
+ * says "hey, it's only 68 bytes, it fits into the buffer" with
+ * the result that we don't get the real packet length. This
+ * is valid at least until kernel 2.2.17pre6.
+ *
+ * We currently handle this by making a copy of the filter
+ * program, fixing all "ret" instructions with non-zero
+ * operands to have an operand of 65535 so that the filter
+ * doesn't truncate the packet, and supplying that modified
+ * filter to the kernel.
+ */
+
+ caplen = packet_len;
+ if (caplen > handle->snapshot)
+ caplen = handle->snapshot;
+
+ /* Run the packet filter if not using kernel filter */
+ if (!handle->md.use_bpf && handle->fcode.bf_insns) {
+ if (bpf_filter(handle->fcode.bf_insns, bp,
+ packet_len, caplen) == 0)
+ {
+ /* rejected by filter */
+ return 0;
+ }
+ }
+
+ /* Fill in our own header data */
+
+ if (ioctl(handle->fd, SIOCGSTAMP, &pcap_header.ts) == -1) {
+ snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
+ "SIOCGSTAMP: %s", pcap_strerror(errno));
+ return PCAP_ERROR;
+ }
+ pcap_header.caplen = caplen;
+ pcap_header.len = packet_len;
+
+ /*
+ * Count the packet.
+ *
+ * Arguably, we should count them before we check the filter,
+ * as on many other platforms "ps_recv" counts packets
+ * handed to the filter rather than packets that passed
+ * the filter, but if filtering is done in the kernel, we
+ * can't get a count of packets that passed the filter,
+ * and that would mean the meaning of "ps_recv" wouldn't
+ * be the same on all Linux systems.
+ *
+ * XXX - it's not the same on all systems in any case;
+ * ideally, we should have a "get the statistics" call
+ * that supplies more counts and indicates which of them
+ * it supplies, so that we supply a count of packets
+ * handed to the filter only on platforms where that
+ * information is available.
+ *
+ * We count them here even if we can get the packet count
+ * from the kernel, as we can only determine at run time
+ * whether we'll be able to get it from the kernel (if
+ * HAVE_TPACKET_STATS isn't defined, we can't get it from
+ * the kernel, but if it is defined, the library might
+ * have been built with a 2.4 or later kernel, but we
+ * might be running on a 2.2[.x] kernel without Alexey
+ * Kuznetzov's turbopacket patches, and thus the kernel
+ * might not be able to supply those statistics). We
+ * could, I guess, try, when opening the socket, to get
+ * the statistics, and if we can not increment the count
+ * here, but it's not clear that always incrementing
+ * the count is more expensive than always testing a flag
+ * in memory.
+ *
+ * We keep the count in "md.packets_read", and use that for
+ * "ps_recv" if we can't get the statistics from the kernel.
+ * We do that because, if we *can* get the statistics from
+ * the kernel, we use "md.stat.ps_recv" and "md.stat.ps_drop"
+ * as running counts, as reading the statistics from the
+ * kernel resets the kernel statistics, and if we directly
+ * increment "md.stat.ps_recv" here, that means it will
+ * count packets *twice* on systems where we can get kernel
+ * statistics - once here, and once in pcap_stats_linux().
+ */
+ handle->md.packets_read++;
+
+ /* Call the user supplied callback function */
+ callback(userdata, &pcap_header, bp);
+
+ return 1;
+}
+
+static int
+pcap_inject_linux(pcap_t *handle, const void *buf, size_t size)
+{
+ int ret;
+
+#ifdef HAVE_PF_PACKET_SOCKETS
+ if (!handle->md.sock_packet) {
+ /* PF_PACKET socket */
+ if (handle->md.ifindex == -1) {
+ /*
+ * We don't support sending on the "any" device.
+ */
+ strlcpy(handle->errbuf,
+ "Sending packets isn't supported on the \"any\" device",
+ PCAP_ERRBUF_SIZE);
+ return (-1);
+ }
+
+ if (handle->md.cooked) {
+ /*
+ * We don't support sending on the "any" device.
+ *
+ * XXX - how do you send on a bound cooked-mode
+ * socket?
+ * Is a "sendto()" required there?
+ */
+ strlcpy(handle->errbuf,
+ "Sending packets isn't supported in cooked mode",
+ PCAP_ERRBUF_SIZE);
+ return (-1);
+ }
+ }
+#endif
+
+ ret = send(handle->fd, buf, size, 0);
+ if (ret == -1) {
+ snprintf(handle->errbuf, PCAP_ERRBUF_SIZE, "send: %s",
+ pcap_strerror(errno));
+ return (-1);
+ }
+ return (ret);
+}
+
+/*
+ * Get the statistics for the given packet capture handle.
+ * Reports the number of dropped packets iff the kernel supports
+ * the PACKET_STATISTICS "getsockopt()" argument (2.4 and later
+ * kernels, and 2.2[.x] kernels with Alexey Kuznetzov's turbopacket
+ * patches); otherwise, that information isn't available, and we lie
+ * and report 0 as the count of dropped packets.
+ */
+static int
+pcap_stats_linux(pcap_t *handle, struct pcap_stat *stats)
+{
+#ifdef HAVE_TPACKET_STATS
+ struct tpacket_stats kstats;
+ socklen_t len = sizeof (struct tpacket_stats);
+#endif
+
+ long if_dropped = 0;
+
+ /*
+ * To fill in ps_ifdrop, we parse /proc/net/dev for the number
+ */
+ if (handle->opt.promisc)
+ {
+ if_dropped = handle->md.proc_dropped;
+ handle->md.proc_dropped = linux_if_drops(handle->md.device);
+ handle->md.stat.ps_ifdrop += (handle->md.proc_dropped - if_dropped);
+ }
+
+#ifdef HAVE_TPACKET_STATS
+ /*
+ * Try to get the packet counts from the kernel.
+ */
+ if (getsockopt(handle->fd, SOL_PACKET, PACKET_STATISTICS,
+ &kstats, &len) > -1) {
+ /*
+ * On systems where the PACKET_STATISTICS "getsockopt()"
+ * argument is supported on PF_PACKET sockets:
+ *
+ * "ps_recv" counts only packets that *passed* the
+ * filter, not packets that didn't pass the filter.
+ * This includes packets later dropped because we
+ * ran out of buffer space.
+ *
+ * "ps_drop" counts packets dropped because we ran
+ * out of buffer space. It doesn't count packets
+ * dropped by the interface driver. It counts only
+ * packets that passed the filter.
+ *
+ * See above for ps_ifdrop.
+ *
+ * Both statistics include packets not yet read from
+ * the kernel by libpcap, and thus not yet seen by
+ * the application.
+ *
+ * In "linux/net/packet/af_packet.c", at least in the
+ * 2.4.9 kernel, "tp_packets" is incremented for every
+ * packet that passes the packet filter *and* is
+ * successfully queued on the socket; "tp_drops" is
+ * incremented for every packet dropped because there's
+ * not enough free space in the socket buffer.
+ *
+ * When the statistics are returned for a PACKET_STATISTICS
+ * "getsockopt()" call, "tp_drops" is added to "tp_packets",
+ * so that "tp_packets" counts all packets handed to
+ * the PF_PACKET socket, including packets dropped because
+ * there wasn't room on the socket buffer - but not
+ * including packets that didn't pass the filter.
+ *
+ * In the BSD BPF, the count of received packets is
+ * incremented for every packet handed to BPF, regardless
+ * of whether it passed the filter.
+ *
+ * We can't make "pcap_stats()" work the same on both
+ * platforms, but the best approximation is to return
+ * "tp_packets" as the count of packets and "tp_drops"
+ * as the count of drops.
+ *
+ * Keep a running total because each call to
+ * getsockopt(handle->fd, SOL_PACKET, PACKET_STATISTICS, ....
+ * resets the counters to zero.
+ */
+ handle->md.stat.ps_recv += kstats.tp_packets;
+ handle->md.stat.ps_drop += kstats.tp_drops;
+ *stats = handle->md.stat;
+ return 0;
+ }
+ else
+ {
+ /*
+ * If the error was EOPNOTSUPP, fall through, so that
+ * if you build the library on a system with
+ * "struct tpacket_stats" and run it on a system
+ * that doesn't, it works as it does if the library
+ * is built on a system without "struct tpacket_stats".
+ */
+ if (errno != EOPNOTSUPP) {
+ snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
+ "pcap_stats: %s", pcap_strerror(errno));
+ return -1;
+ }
+ }
+#endif
+ /*
+ * On systems where the PACKET_STATISTICS "getsockopt()" argument
+ * is not supported on PF_PACKET sockets:
+ *
+ * "ps_recv" counts only packets that *passed* the filter,
+ * not packets that didn't pass the filter. It does not
+ * count packets dropped because we ran out of buffer
+ * space.
+ *
+ * "ps_drop" is not supported.
+ *
+ * "ps_ifdrop" is supported. It will return the number
+ * of drops the interface reports in /proc/net/dev,
+ * if that is available.
+ *
+ * "ps_recv" doesn't include packets not yet read from
+ * the kernel by libpcap.
+ *
+ * We maintain the count of packets processed by libpcap in
+ * "md.packets_read", for reasons described in the comment
+ * at the end of pcap_read_packet(). We have no idea how many
+ * packets were dropped by the kernel buffers -- but we know
+ * how many the interface dropped, so we can return that.
+ */
+
+ stats->ps_recv = handle->md.packets_read;
+ stats->ps_drop = 0;
+ stats->ps_ifdrop = handle->md.stat.ps_ifdrop;
+ return 0;
+}
+
+/*
+ * Get from "/sys/class/net" all interfaces listed there; if they're
+ * already in the list of interfaces we have, that won't add another
+ * instance, but if they're not, that'll add them.
+ *
+ * We don't bother getting any addresses for them; it appears you can't
+ * use SIOCGIFADDR on Linux to get IPv6 addresses for interfaces, and,
+ * although some other types of addresses can be fetched with SIOCGIFADDR,
+ * we don't bother with them for now.
+ *
+ * We also don't fail if we couldn't open "/sys/class/net"; we just leave
+ * the list of interfaces as is, and return 0, so that we can try
+ * scanning /proc/net/dev.
+ */
+static int
+scan_sys_class_net(pcap_if_t **devlistp, char *errbuf)
+{
+ DIR *sys_class_net_d;
+ int fd;
+ struct dirent *ent;
+ char subsystem_path[PATH_MAX+1];
+ struct stat statb;
+ char *p;
+ char name[512]; /* XXX - pick a size */
+ char *q, *saveq;
+ struct ifreq ifrflags;
+ int ret = 1;
+
+ sys_class_net_d = opendir("/sys/class/net");
+ if (sys_class_net_d == NULL) {
+ /*
+ * Don't fail if it doesn't exist at all.
+ */
+ if (errno == ENOENT)
+ return (0);
+
+ /*
+ * Fail if we got some other error.
+ */
+ (void)snprintf(errbuf, PCAP_ERRBUF_SIZE,
+ "Can't open /sys/class/net: %s", pcap_strerror(errno));
+ return (-1);
+ }
+
+ /*
+ * Create a socket from which to fetch interface information.
+ */
+ fd = socket(AF_INET, SOCK_DGRAM, 0);
+ if (fd < 0) {
+ (void)snprintf(errbuf, PCAP_ERRBUF_SIZE,
+ "socket: %s", pcap_strerror(errno));
+ (void)closedir(sys_class_net_d);
+ return (-1);
+ }
+
+ for (;;) {
+ errno = 0;
+ ent = readdir(sys_class_net_d);
+ if (ent == NULL) {
+ /*
+ * Error or EOF; if errno != 0, it's an error.
+ */
+ break;
+ }
+
+ /*
+ * Ignore "." and "..".
+ */
+ if (strcmp(ent->d_name, ".") == 0 ||
+ strcmp(ent->d_name, "..") == 0)
+ continue;
+
+ /*
+ * Ignore plain files; they do not have subdirectories
+ * and thus have no attributes.
+ */
+ if (ent->d_type == DT_REG)
+ continue;
+
+ /*
+ * Is there an "ifindex" file under that name?
+ * (We don't care whether it's a directory or
+ * a symlink; older kernels have directories
+ * for devices, newer kernels have symlinks to
+ * directories.)
+ */
+ snprintf(subsystem_path, sizeof subsystem_path,
+ "/sys/class/net/%s/ifindex", ent->d_name);
+ if (lstat(subsystem_path, &statb) != 0) {
+ /*
+ * Stat failed. Either there was an error
+ * other than ENOENT, and we don't know if
+ * this is an interface, or it's ENOENT,
+ * and either some part of "/sys/class/net/{if}"
+ * disappeared, in which case it probably means
+ * the interface disappeared, or there's no
+ * "ifindex" file, which means it's not a
+ * network interface.
+ */
+ continue;
+ }
+
+ /*
+ * Get the interface name.
+ */
+ p = &ent->d_name[0];
+ q = &name[0];
+ while (*p != '\0' && isascii(*p) && !isspace(*p)) {
+ if (*p == ':') {
+ /*
+ * This could be the separator between a
+ * name and an alias number, or it could be
+ * the separator between a name with no
+ * alias number and the next field.
+ *
+ * If there's a colon after digits, it
+ * separates the name and the alias number,
+ * otherwise it separates the name and the
+ * next field.
+ */
+ saveq = q;
+ while (isascii(*p) && isdigit(*p))
+ *q++ = *p++;
+ if (*p != ':') {
+ /*
+ * That was the next field,
+ * not the alias number.
+ */
+ q = saveq;
+ }
+ break;
+ } else
+ *q++ = *p++;
+ }
+ *q = '\0';
+
+ /*
+ * Get the flags for this interface, and skip it if
+ * it's not up.
+ */
+ strncpy(ifrflags.ifr_name, name, sizeof(ifrflags.ifr_name));
+ if (ioctl(fd, SIOCGIFFLAGS, (char *)&ifrflags) < 0) {
+ if (errno == ENXIO || errno == ENODEV)
+ continue;
+ (void)snprintf(errbuf, PCAP_ERRBUF_SIZE,
+ "SIOCGIFFLAGS: %.*s: %s",
+ (int)sizeof(ifrflags.ifr_name),
+ ifrflags.ifr_name,
+ pcap_strerror(errno));
+ ret = -1;
+ break;
+ }
+ if (!(ifrflags.ifr_flags & IFF_UP))
+ continue;
+
+ /*
+ * Add an entry for this interface, with no addresses.
+ */
+ if (pcap_add_if(devlistp, name, ifrflags.ifr_flags, NULL,
+ errbuf) == -1) {
+ /*
+ * Failure.
+ */
+ ret = -1;
+ break;
+ }
+ }
+ if (ret != -1) {
+ /*
+ * Well, we didn't fail for any other reason; did we
+ * fail due to an error reading the directory?
+ */
+ if (errno != 0) {
+ (void)snprintf(errbuf, PCAP_ERRBUF_SIZE,
+ "Error reading /sys/class/net: %s",
+ pcap_strerror(errno));
+ ret = -1;
+ }
+ }
+
+ (void)close(fd);
+ (void)closedir(sys_class_net_d);
+ return (ret);
+}
+
+/*
+ * Get from "/proc/net/dev" all interfaces listed there; if they're
+ * already in the list of interfaces we have, that won't add another
+ * instance, but if they're not, that'll add them.
+ *
+ * See comments from scan_sys_class_net().
+ */
+static int
+scan_proc_net_dev(pcap_if_t **devlistp, char *errbuf)
+{
+ FILE *proc_net_f;
+ int fd;
+ char linebuf[512];
+ int linenum;
+ char *p;
+ char name[512]; /* XXX - pick a size */
+ char *q, *saveq;
+ struct ifreq ifrflags;
+ int ret = 0;
+
+ proc_net_f = fopen("/proc/net/dev", "r");
+ if (proc_net_f == NULL) {
+ /*
+ * Don't fail if it doesn't exist at all.
+ */
+ if (errno == ENOENT)
+ return (0);
+
+ /*
+ * Fail if we got some other error.
+ */
+ (void)snprintf(errbuf, PCAP_ERRBUF_SIZE,
+ "Can't open /proc/net/dev: %s", pcap_strerror(errno));
+ return (-1);
+ }
+
+ /*
+ * Create a socket from which to fetch interface information.
+ */
+ fd = socket(AF_INET, SOCK_DGRAM, 0);
+ if (fd < 0) {
+ (void)snprintf(errbuf, PCAP_ERRBUF_SIZE,
+ "socket: %s", pcap_strerror(errno));
+ (void)fclose(proc_net_f);
+ return (-1);
+ }
+
+ for (linenum = 1;
+ fgets(linebuf, sizeof linebuf, proc_net_f) != NULL; linenum++) {
+ /*
+ * Skip the first two lines - they're headers.
+ */
+ if (linenum <= 2)
+ continue;
+
+ p = &linebuf[0];
+
+ /*
+ * Skip leading white space.
+ */
+ while (*p != '\0' && isascii(*p) && isspace(*p))
+ p++;
+ if (*p == '\0' || *p == '\n')
+ continue; /* blank line */
+
+ /*
+ * Get the interface name.
+ */
+ q = &name[0];
+ while (*p != '\0' && isascii(*p) && !isspace(*p)) {
+ if (*p == ':') {
+ /*
+ * This could be the separator between a
+ * name and an alias number, or it could be
+ * the separator between a name with no
+ * alias number and the next field.
+ *
+ * If there's a colon after digits, it
+ * separates the name and the alias number,
+ * otherwise it separates the name and the
+ * next field.
+ */
+ saveq = q;
+ while (isascii(*p) && isdigit(*p))
+ *q++ = *p++;
+ if (*p != ':') {
+ /*
+ * That was the next field,
+ * not the alias number.
+ */
+ q = saveq;
+ }
+ break;
+ } else
+ *q++ = *p++;
+ }
+ *q = '\0';
+
+ /*
+ * Get the flags for this interface, and skip it if
+ * it's not up.
+ */
+ strncpy(ifrflags.ifr_name, name, sizeof(ifrflags.ifr_name));
+ if (ioctl(fd, SIOCGIFFLAGS, (char *)&ifrflags) < 0) {
+ if (errno == ENXIO)
+ continue;
+ (void)snprintf(errbuf, PCAP_ERRBUF_SIZE,
+ "SIOCGIFFLAGS: %.*s: %s",
+ (int)sizeof(ifrflags.ifr_name),
+ ifrflags.ifr_name,
+ pcap_strerror(errno));
+ ret = -1;
+ break;
+ }
+ if (!(ifrflags.ifr_flags & IFF_UP))
+ continue;
+
+ /*
+ * Add an entry for this interface, with no addresses.
+ */
+ if (pcap_add_if(devlistp, name, ifrflags.ifr_flags, NULL,
+ errbuf) == -1) {
+ /*
+ * Failure.
+ */
+ ret = -1;
+ break;
+ }
+ }
+ if (ret != -1) {
+ /*
+ * Well, we didn't fail for any other reason; did we
+ * fail due to an error reading the file?
+ */
+ if (ferror(proc_net_f)) {
+ (void)snprintf(errbuf, PCAP_ERRBUF_SIZE,
+ "Error reading /proc/net/dev: %s",
+ pcap_strerror(errno));
+ ret = -1;
+ }
+ }
+
+ (void)close(fd);
+ (void)fclose(proc_net_f);
+ return (ret);
+}
+
+/*
+ * Description string for the "any" device.
+ */
+static const char any_descr[] = "Pseudo-device that captures on all interfaces";
+
+int
+pcap_platform_finddevs(pcap_if_t **alldevsp, char *errbuf)
+{
+ int ret;
+
+ /*
+ * Read "/sys/class/net", and add to the list of interfaces all
+ * interfaces listed there that we don't already have, because,
+ * on Linux, SIOCGIFCONF reports only interfaces with IPv4 addresses,
+ * and even getifaddrs() won't return information about
+ * interfaces with no addresses, so you need to read "/sys/class/net"
+ * to get the names of the rest of the interfaces.
+ */
+ ret = scan_sys_class_net(alldevsp, errbuf);
+ if (ret == -1)
+ return (-1); /* failed */
+ if (ret == 0) {
+ /*
+ * No /sys/class/net; try reading /proc/net/dev instead.
+ */
+ if (scan_proc_net_dev(alldevsp, errbuf) == -1)
+ return (-1);
+ }
+
+ /*
+ * Add the "any" device.
+ */
+ if (pcap_add_if(alldevsp, "any", 0, any_descr, errbuf) < 0)
+ return (-1);
+
+#ifdef HAVE_DAG_API
+ /*
+ * Add DAG devices.
+ */
+ if (dag_platform_finddevs(alldevsp, errbuf) < 0)
+ return (-1);
+#endif /* HAVE_DAG_API */
+
+#ifdef HAVE_SEPTEL_API
+ /*
+ * Add Septel devices.
+ */
+ if (septel_platform_finddevs(alldevsp, errbuf) < 0)
+ return (-1);
+#endif /* HAVE_SEPTEL_API */
+
+#ifdef HAVE_SNF_API
+ if (snf_platform_finddevs(alldevsp, errbuf) < 0)
+ return (-1);
+#endif /* HAVE_SNF_API */
+
+#ifdef PCAP_SUPPORT_BT
+ /*
+ * Add Bluetooth devices.
+ */
+ if (bt_platform_finddevs(alldevsp, errbuf) < 0)
+ return (-1);
+#endif
+
+#ifdef PCAP_SUPPORT_USB
+ /*
+ * Add USB devices.
+ */
+ if (usb_platform_finddevs(alldevsp, errbuf) < 0)
+ return (-1);
+#endif
+
+#ifdef PCAP_SUPPORT_NETFILTER
+ /*
+ * Add netfilter devices.
+ */
+ if (netfilter_platform_finddevs(alldevsp, errbuf) < 0)
+ return (-1);
+#endif
+
+#if PCAP_SUPPORT_CANUSB
+ if (canusb_platform_finddevs(alldevsp, errbuf) < 0)
+ return (-1);
+#endif
+
+ return (0);
+}
+
+/*
+ * Attach the given BPF code to the packet capture device.
+ */
+static int
+pcap_setfilter_linux_common(pcap_t *handle, struct bpf_program *filter,
+ int is_mmapped)
+{
+#ifdef SO_ATTACH_FILTER
+ struct sock_fprog fcode;
+ int can_filter_in_kernel;
+ int err = 0;
+#endif
+
+ if (!handle)
+ return -1;
+ if (!filter) {
+ strncpy(handle->errbuf, "setfilter: No filter specified",
+ PCAP_ERRBUF_SIZE);
+ return -1;
+ }
+
+ /* Make our private copy of the filter */
+
+ if (install_bpf_program(handle, filter) < 0)
+ /* install_bpf_program() filled in errbuf */
+ return -1;
+
+ /*
+ * Run user level packet filter by default. Will be overriden if
+ * installing a kernel filter succeeds.
+ */
+ handle->md.use_bpf = 0;
+
+ /* Install kernel level filter if possible */
+
+#ifdef SO_ATTACH_FILTER
+#ifdef USHRT_MAX
+ if (handle->fcode.bf_len > USHRT_MAX) {
+ /*
+ * fcode.len is an unsigned short for current kernel.
+ * I have yet to see BPF-Code with that much
+ * instructions but still it is possible. So for the
+ * sake of correctness I added this check.
+ */
+ fprintf(stderr, "Warning: Filter too complex for kernel\n");
+ fcode.len = 0;
+ fcode.filter = NULL;
+ can_filter_in_kernel = 0;
+ } else
+#endif /* USHRT_MAX */
+ {
+ /*
+ * Oh joy, the Linux kernel uses struct sock_fprog instead
+ * of struct bpf_program and of course the length field is
+ * of different size. Pointed out by Sebastian
+ *
+ * Oh, and we also need to fix it up so that all "ret"
+ * instructions with non-zero operands have 65535 as the
+ * operand if we're not capturing in memory-mapped modee,
+ * and so that, if we're in cooked mode, all memory-reference
+ * instructions use special magic offsets in references to
+ * the link-layer header and assume that the link-layer
+ * payload begins at 0; "fix_program()" will do that.
+ */
+ switch (fix_program(handle, &fcode, is_mmapped)) {
+
+ case -1:
+ default:
+ /*
+ * Fatal error; just quit.
+ * (The "default" case shouldn't happen; we
+ * return -1 for that reason.)
+ */
+ return -1;
+
+ case 0:
+ /*
+ * The program performed checks that we can't make
+ * work in the kernel.
+ */
+ can_filter_in_kernel = 0;
+ break;
+
+ case 1:
+ /*
+ * We have a filter that'll work in the kernel.
+ */
+ can_filter_in_kernel = 1;
+ break;
+ }
+ }
+
+ /*
+ * NOTE: at this point, we've set both the "len" and "filter"
+ * fields of "fcode". As of the 2.6.32.4 kernel, at least,
+ * those are the only members of the "sock_fprog" structure,
+ * so we initialize every member of that structure.
+ *
+ * If there is anything in "fcode" that is not initialized,
+ * it is either a field added in a later kernel, or it's
+ * padding.
+ *
+ * If a new field is added, this code needs to be updated
+ * to set it correctly.
+ *
+ * If there are no other fields, then:
+ *
+ * if the Linux kernel looks at the padding, it's
+ * buggy;
+ *
+ * if the Linux kernel doesn't look at the padding,
+ * then if some tool complains that we're passing
+ * uninitialized data to the kernel, then the tool
+ * is buggy and needs to understand that it's just
+ * padding.
+ */
+ if (can_filter_in_kernel) {
+ if ((err = set_kernel_filter(handle, &fcode)) == 0)
+ {
+ /* Installation succeded - using kernel filter. */
+ handle->md.use_bpf = 1;
+ }
+ else if (err == -1) /* Non-fatal error */
+ {
+ /*
+ * Print a warning if we weren't able to install
+ * the filter for a reason other than "this kernel
+ * isn't configured to support socket filters.
+ */
+ if (errno != ENOPROTOOPT && errno != EOPNOTSUPP) {
+ fprintf(stderr,
+ "Warning: Kernel filter failed: %s\n",
+ pcap_strerror(errno));
+ }
+ }
+ }
+
+ /*
+ * If we're not using the kernel filter, get rid of any kernel
+ * filter that might've been there before, e.g. because the
+ * previous filter could work in the kernel, or because some other
+ * code attached a filter to the socket by some means other than
+ * calling "pcap_setfilter()". Otherwise, the kernel filter may
+ * filter out packets that would pass the new userland filter.
+ */
+ if (!handle->md.use_bpf)
+ reset_kernel_filter(handle);
+
+ /*
+ * Free up the copy of the filter that was made by "fix_program()".
+ */
+ if (fcode.filter != NULL)
+ free(fcode.filter);
+
+ if (err == -2)
+ /* Fatal error */
+ return -1;
+#endif /* SO_ATTACH_FILTER */
+
+ return 0;
+}
+
+static int
+pcap_setfilter_linux(pcap_t *handle, struct bpf_program *filter)
+{
+ return pcap_setfilter_linux_common(handle, filter, 0);
+}
+
+
+/*
+ * Set direction flag: Which packets do we accept on a forwarding
+ * single device? IN, OUT or both?
+ */
+static int
+pcap_setdirection_linux(pcap_t *handle, pcap_direction_t d)
+{
+#ifdef HAVE_PF_PACKET_SOCKETS
+ if (!handle->md.sock_packet) {
+ handle->direction = d;
+ return 0;
+ }
+#endif
+ /*
+ * We're not using PF_PACKET sockets, so we can't determine
+ * the direction of the packet.
+ */
+ snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
+ "Setting direction is not supported on SOCK_PACKET sockets");
+ return -1;
+}
+
+#ifdef HAVE_PF_PACKET_SOCKETS
+/*
+ * Map the PACKET_ value to a LINUX_SLL_ value; we
+ * want the same numerical value to be used in
+ * the link-layer header even if the numerical values
+ * for the PACKET_ #defines change, so that programs
+ * that look at the packet type field will always be
+ * able to handle DLT_LINUX_SLL captures.
+ */
+static short int
+map_packet_type_to_sll_type(short int sll_pkttype)
+{
+ switch (sll_pkttype) {
+
+ case PACKET_HOST:
+ return htons(LINUX_SLL_HOST);
+
+ case PACKET_BROADCAST:
+ return htons(LINUX_SLL_BROADCAST);
+
+ case PACKET_MULTICAST:
+ return htons(LINUX_SLL_MULTICAST);
+
+ case PACKET_OTHERHOST:
+ return htons(LINUX_SLL_OTHERHOST);
+
+ case PACKET_OUTGOING:
+ return htons(LINUX_SLL_OUTGOING);
+
+ default:
+ return -1;
+ }
+}
+#endif
+
+static int
+is_wifi(int sock_fd
+#ifndef IW_MODE_MONITOR
+_U_
+#endif
+, const char *device)
+{
+ char *pathstr;
+ struct stat statb;
+#ifdef IW_MODE_MONITOR
+ char errbuf[PCAP_ERRBUF_SIZE];
+#endif
+
+ /*
+ * See if there's a sysfs wireless directory for it.
+ * If so, it's a wireless interface.
+ */
+ if (asprintf(&pathstr, "/sys/class/net/%s/wireless", device) == -1) {
+ /*
+ * Just give up here.
+ */
+ return 0;
+ }
+ if (stat(pathstr, &statb) == 0) {
+ free(pathstr);
+ return 1;
+ }
+ free(pathstr);
+
+#ifdef IW_MODE_MONITOR
+ /*
+ * OK, maybe it's not wireless, or maybe this kernel doesn't
+ * support sysfs. Try the wireless extensions.
+ */
+ if (has_wext(sock_fd, device, errbuf) == 1) {
+ /*
+ * It supports the wireless extensions, so it's a Wi-Fi
+ * device.
+ */
+ return 1;
+ }
+#endif
+ return 0;
+}
+
+/*
+ * Linux uses the ARP hardware type to identify the type of an
+ * interface. pcap uses the DLT_xxx constants for this. This
+ * function takes a pointer to a "pcap_t", and an ARPHRD_xxx
+ * constant, as arguments, and sets "handle->linktype" to the
+ * appropriate DLT_XXX constant and sets "handle->offset" to
+ * the appropriate value (to make "handle->offset" plus link-layer
+ * header length be a multiple of 4, so that the link-layer payload
+ * will be aligned on a 4-byte boundary when capturing packets).
+ * (If the offset isn't set here, it'll be 0; add code as appropriate
+ * for cases where it shouldn't be 0.)
+ *
+ * If "cooked_ok" is non-zero, we can use DLT_LINUX_SLL and capture
+ * in cooked mode; otherwise, we can't use cooked mode, so we have
+ * to pick some type that works in raw mode, or fail.
+ *
+ * Sets the link type to -1 if unable to map the type.
+ */
+static void map_arphrd_to_dlt(pcap_t *handle, int sock_fd, int arptype,
+ const char *device, int cooked_ok)
+{
+ static const char cdma_rmnet[] = "cdma_rmnet";
+
+ switch (arptype) {
+
+ case ARPHRD_ETHER:
+ /*
+ * For various annoying reasons having to do with DHCP
+ * software, some versions of Android give the mobile-
+ * phone-network interface an ARPHRD_ value of
+ * ARPHRD_ETHER, even though the packets supplied by
+ * that interface have no link-layer header, and begin
+ * with an IP header, so that the ARPHRD_ value should
+ * be ARPHRD_NONE.
+ *
+ * Detect those devices by checking the device name, and
+ * use DLT_RAW for them.
+ */
+ if (strncmp(device, cdma_rmnet, sizeof cdma_rmnet - 1) == 0) {
+ handle->linktype = DLT_RAW;
+ return;
+ }
+
+ /*
+ * Is this a real Ethernet device? If so, give it a
+ * link-layer-type list with DLT_EN10MB and DLT_DOCSIS, so
+ * that an application can let you choose it, in case you're
+ * capturing DOCSIS traffic that a Cisco Cable Modem
+ * Termination System is putting out onto an Ethernet (it
+ * doesn't put an Ethernet header onto the wire, it puts raw
+ * DOCSIS frames out on the wire inside the low-level
+ * Ethernet framing).
+ *
+ * XXX - are there any other sorts of "fake Ethernet" that
+ * have ARPHRD_ETHER but that shouldn't offer DLT_DOCSIS as
+ * a Cisco CMTS won't put traffic onto it or get traffic
+ * bridged onto it? ISDN is handled in "activate_new()",
+ * as we fall back on cooked mode there, and we use
+ * is_wifi() to check for 802.11 devices; are there any
+ * others?
+ */
+ if (!is_wifi(sock_fd, device)) {
+ /*
+ * It's not a Wi-Fi device; offer DOCSIS.
+ */
+ handle->dlt_list = (u_int *) malloc(sizeof(u_int) * 2);
+ /*
+ * If that fails, just leave the list empty.
+ */
+ if (handle->dlt_list != NULL) {
+ handle->dlt_list[0] = DLT_EN10MB;
+ handle->dlt_list[1] = DLT_DOCSIS;
+ handle->dlt_count = 2;
+ }
+ }
+ /* FALLTHROUGH */
+
+ case ARPHRD_METRICOM:
+ case ARPHRD_LOOPBACK:
+ handle->linktype = DLT_EN10MB;
+ handle->offset = 2;
+ break;
+
+ case ARPHRD_EETHER:
+ handle->linktype = DLT_EN3MB;
+ break;
+
+ case ARPHRD_AX25:
+ handle->linktype = DLT_AX25_KISS;
+ break;
+
+ case ARPHRD_PRONET:
+ handle->linktype = DLT_PRONET;
+ break;
+
+ case ARPHRD_CHAOS:
+ handle->linktype = DLT_CHAOS;
+ break;
+#ifndef ARPHRD_CAN
+#define ARPHRD_CAN 280
+#endif
+ case ARPHRD_CAN:
+ handle->linktype = DLT_CAN_SOCKETCAN;
+ break;
+
+#ifndef ARPHRD_IEEE802_TR
+#define ARPHRD_IEEE802_TR 800 /* From Linux 2.4 */
+#endif