-
libpcap源码分析
2016-01-04 13:45:05今天刚好在写总结,就将之前分析的libpcap文档与大家分享一下。 百度文库的地址:http://wenku.baidu.com/view/1a8fc4baa26925c52cc5bff2# 其中有部分是参考网上资料。 1、Libpcap介绍 Libpcap是Packet...今天刚好在写总结,就将之前分析的libpcap文档与大家分享一下。
百度文库的地址:http://wenku.baidu.com/view/1a8fc4baa26925c52cc5bff2#
其中有部分是参考网上资料。
1、Libpcap介绍
Libpcap是Packet Capture Library的英文缩写,即数据包捕获函数库。该库提供的C函数接口用于捕获及格过指定网络接口的数据包,该接口是被设为混杂模式。大多数网络监控软件都以它为基础,其提供的接口函数实现和封装了与数据包截获相关的过程。Libpcap提供了用户级别的网络数据包捕获接口,并充分考虑到引用程序的可移植性,可以在绝大多数类unix平台下工作。主要功能:
l 数据包捕获:捕获流经网卡的原始数据包
l 自定义数据包发送:构造任何格式的原始数据包
l 流量采集与统计:采集网络中的流量信息
l 规则过滤:提供自带规则过滤功能,按需要选择过滤规则
绝大多数的现代操作系统都提供了对底层网络数据包捕获的机制,在捕获机制之上可以建立网络监控(Network Monitoring)应用软件。网络监控也常简称为sniffer,其最初的目的在于对网络通信情况进行监控,以对网络的一些异常情况进行调试处理。但随着互连网的快速普及和网络攻击行为的频繁出现,保护网络的运行安全也成为监控软件的另一个重要目的。例如,网络监控在路由器,防火墙、入侵检查等方面使用也很广泛。本文分析了Libpcap在linux下的源代码实现,其中重点是linux的底层包捕获机制。
2、Libpcap的安装
Libpcap的下载地址: http://www.tcpdump.org/ 然后切换到下载的目录,解压压缩文件,配置,编译,安装。其命令如下:
cd ****
tar zxvf ****
./configure
Make
Make install
配置中如果出现错误,检查是否安装了所有的依赖包bison、m4、GNU、flex以及libpcap-dev。在运行的时候,是需要root权限的。
3、Libpcap工作原理
作为捕获网络数据包的库,它是一个独立于系统的用户级的API接口,为底层网络检测提供了可移植的框架。从广义的角度上看,一个包捕获机制包含三个主要部分:最底层是针对特定操作系统的包捕获机制,最高层是针对用户程序的接口,第三部分是包过滤机制。不同的操作系统实现的底层包捕获机制可能是不一样的,但从形式上看大同小异。数据包常规的传输路径依次为网卡、设备驱动层、数据链路层、网络层、传输层、应用层。而包捕获机制是在数据链路层增加一个旁路处理,对发送和接收到的数据包做过滤、缓冲等相关处理,最后直接传递到应用程序。值得注意的是,包捕获机制并不影响操作系统对数据包的网络栈处理。对用户程序而言,包捕获机制提供了一个统一的接口,使用户只需要简单的调用若干函数就能获得所期望的数据包。这样一来,针对特定操作系统的捕获机制对用户透明,使用户程序有比较好的可移植性。包过滤机制是对所捕获到的数据包根据用户的要求进行筛选,最终只把满足过滤条件的数据包传递给用户程序。如图1所示:
图1、包捕获机制
Libpcap源代码由20多个C文件构成,但在Linux系统下并不是所有文件都用到。可以通过查看命令make的输出了解实际所用的文件。本文所针对的Libpcap版本号为1.6.2
网络类型为常规以太网。Libpcap应用程序从形式上看很简单,其程序框架如图2所示:
图2、程序框架
在上面的流程中,通过查找网络设备,打开网络设备,获取网络参数,捕获数据包等操作简单的描述了一个抓包的流程。
4、函数功能介绍
4.1查找网络设备
Libpcap程序的第一步通常是在系统中找到合适的网络设备。网络接口在Linux网络体系中式一个很重要的概念,它是对具体网络硬件设备的一个抽象,在它的下面是具体的网卡驱动程序,而其上则是网络协议层。Linux中最常见的接口设备名eth0和lo。Lo称为回路设备,是一种逻辑意义上的设备,其主要目的是为了调试网络程序之间的通讯功能。Eth0对应实际的物理网卡,在真实网络环境下,数据包的发送和接收都要通过eth0。如果计算机有多个网卡,则还可以有更多的网络接口,如eth1,eth2等等。调用命令ifconfig可以列出当前所有活跃的接口及相关信息,注意对eth0的描述中技有物理网卡的MAC地址,也有网络协议的IP地址。查看文件/proc/net/dev也可以获得接口的信息。
Libpcap中检查网络设备中主要使用到的函数如下:
char * pcap_lookupdev(char * errbuf)
//上面这个函数返回第一个合适的网络接口的字符串指针,如果出错,则errbuf存放出错信息字符串,errbuf至少应该是PCAP_ERRBUF_SIZE个字节长度的
char *
pcap_lookupdev(errbuf)
register char *errbuf;
{
pcap_if_t *alldevs;
/* for old BSD systems, including bsdi3 */
#ifndef IF_NAMESIZE
#define IF_NAMESIZE IFNAMSIZ
#endif
static char device[IF_NAMESIZE + 1];
char *ret;
if (pcap_findalldevs(&alldevs, errbuf) == -1)
return (NULL);
if (alldevs == NULL || (alldevs->flags & PCAP_IF_LOOPBACK)) {
/*
* There are no devices on the list, or the first device
* on the list is a loopback device, which means there
* are no non-loopback devices on the list. This means
* we can't return any device.
*
* XXX - why not return a loopback device? If we can't
* capture on it, it won't be on the list, and if it's
* on the list, there aren't any non-loopback devices,
* so why not just supply it as the default device?
*/
(void)strlcpy(errbuf, "no suitable device found",
PCAP_ERRBUF_SIZE);
ret = NULL;
} else {
/*
* Return the name of the first device on the list.
*/
(void)strlcpy(device, alldevs->name, sizeof(device));
ret = device;
}
pcap_freealldevs(alldevs);
return (ret);
}
pcap_findalldevs_interfaces(alldevsp, errbuf)
//获取常规的网络接口
Libpcap调用上面的pcap_lookupdev()函数获得可用网络接口的设备名。首先利用函数pcap_findalldevs_interfaces()查找网络设备接口,其部分源码如下:
/*
* Create a socket from which to fetch the list of interfaces,
* and from which to fetch IPv4 information.
*/
fd4 = socket(AF_INET, SOCK_DGRAM, 0);
if (fd4 < 0) {
(void)snprintf(errbuf, PCAP_ERRBUF_SIZE,
"socket: %s", pcap_strerror(errno));
return (-1);
}
//创建socket套接字,为后面的数据传输。
/*
* How many entries will SIOCGLIFCONF return?
*/
ifn.lifn_family = AF_UNSPEC;
ifn.lifn_flags = 0;
ifn.lifn_count = 0;
if (ioctl(fd4, SIOCGLIFNUM, (char *)&ifn) < 0) {
(void)snprintf(errbuf, PCAP_ERRBUF_SIZE,
"SIOCGLIFNUM: %s", pcap_strerror(errno));
(void)close(fd6);
(void)close(fd4);
return (-1);
}
/*
* Get the entries.
*/
ifc.lifc_len = buf_size;
ifc.lifc_buf = buf;
ifc.lifc_family = AF_UNSPEC;
ifc.lifc_flags = 0;
memset(buf, 0, buf_size);
if (ioctl(fd4, SIOCGLIFCONF, (char *)&ifc) < 0) {
(void)snprintf(errbuf, PCAP_ERRBUF_SIZE,
"SIOCGLIFCONF: %s", pcap_strerror(errno));
(void)close(fd6);
(void)close(fd4);
free(buf);
return (-1);
}
利用ioctl函数,获取所有的设备名。保存到*alldevsp指针的入口参数里面。在pcap_lookupdev函数的最后通过使用函数strlcpy(device, alldevs->name, sizeof(device))将上面找到的设备名复制给device。最后返回给调用程序。
/* libpcap 自定义的接口信息链表 [pcap.h] */
struct pcap_if
{
struct pcap_if *next;
char *name; /* 接口设备名 */
char *description; /* 接口描述 */
/*接口的 IP 地址, 地址掩码, 广播地址,目的地址 */
struct pcap_addr addresses;
bpf_u_int32 flags; /* 接口的参数 */
};网络设备
当设备找到后,下一步工作就是打开设备以准备捕获数据包。Libpcap的包捕获是建立在具体的操作系统所提供的捕获机制上,而Linux系统随着版本的不同,所支持的捕获机制也有所不同。
2.0 及以前的内核版本使用一个特殊的socket类型SOCK_PACKET,调用形式是socket(PF_INET, SOCK_PACKET, int protocol),但 Linux 内核开发者明确指出这种方式已过时。Linux 在 2.2及以后的版本中提供了一种新的协议簇 PF_PACKET 来实现捕获机制。PF_PACKET 的调用形式为 socket(PF_PACKET, int socket_type, int protocol),其中socket类型可以是 SOCK_RAW和SOCK_DGRAM。SOCK_RAW 类型使得数据包从数据链路层取得后,不做任何修改直接传递给用户程序,而 SOCK_DRRAM 则要对数据包进行加工(cooked),把数据包的数据链路层头部去掉,而使用一个通用结构 sockaddr_ll 来保存链路信息。
使 用 2.0 版本内核捕获数据包存在多个问题:首先,SOCK_PACKET 方式使用结构 sockaddr_pkt来保存数据链路层信息,但该结构缺乏包类型信息;其次,如果参数 MSG_TRUNC 传递给读包函数 recvmsg()、recv()、recvfrom() 等,则函数返回的数据包长度是实际读到的包数据长度,而不是数据包真正的长度。Libpcap 的开发者在源代码中明确建议不使用 2.0 版本进行捕获。
相对2.0版本SOCK_PACKET方式,2.2版本的PF_PACKET方式则不存在上述两个问题。在实际应用中,用 户程序显然希望直接得到"原始"的数据包,因此使用 SOCK_RAW 类型最好。但在下面两种情况下,libpcap 不得不使用SOCK_DGRAM类型,从而也必须为数据包合成一个"伪"链路层头部(sockaddr_ll)。打开网络设备的主函数是pcap_open_live,其任务就是通过给定的接口设备名,获得一个捕获句柄:pcap_t。Pcap_t结构体是大多数libpcap函数都要用到的参数,其中最重要的属性就是上面的socket方式的一种,位于pcap_int.h中,下面是pcap_t的结构:
/*
* We put all the stuff used in the read code path at the beginning,
* to try to keep it together in the same cache line or lines.
*/
struct pcap {
/*
* Method to call to read packets on a live capture.
*/
read_op_t read_op; //回调函数,用户获取数据包。
/*
* Method to call to read to read packets from a savefile.
*/
int (*next_packet_op)(pcap_t *, struct pcap_pkthdr *, u_char **);
#ifdef WIN32
ADAPTER *adapter;
LPPACKET Packet;
int nonblock;
#else
int fd; //文件描述符。实际就是socket
int selectable_fd;
#endif /* WIN32 */
/*
* Read buffer.
*/
int bufsize;
u_char *buffer;
u_char *bp;
int cc;
int break_loop; /* flag set to force break from packet-reading loop */强制从读数据包循环中跳出的标志
void *priv; /* private data for methods */
int swapped;
FILE *rfile; /* null if live capture, non-null if savefile */
int fddipad;
struct pcap *next; /* list of open pcaps that need stuff cleared on close */
/*
* File version number; meaningful only for a savefile, but we
* keep it here so that apps that (mistakenly) ask for the
* version numbers will get the same zero values that they
* always did.
*/
int version_major;
int version_minor;
int snapshot; //用户期望捕获数据包的最大长度,自定义的
int linktype; /* Network linktype */设备类型
int linktype_ext; /* Extended information stored in the linktype field of a file */
int tzoff; /* timezone offset */时区位置 偏移
int offset; /* offset for proper alignment */边界对齐偏移量
int activated; /* true if the capture is really started */
int oldstyle; /* if we're opening with pcap_open_live() */
struct pcap_opt opt;
/*
* Place holder for pcap_next().
*/
u_char *pkt;
/* We're accepting only packets in this direction/these directions. */
pcap_direction_t direction;
/*
* Placeholder for filter code if bpf not in kernel.
*/
//如果BPF过滤代码不能在内核中执行,则将其保存并在用户控件执行
struct bpf_program fcode;
//相关的函数指针,最终指向特定操作系统的处理函数。
char errbuf[PCAP_ERRBUF_SIZE + 1];
int dlt_count;
u_int *dlt_list;
int tstamp_type_count;
u_int *tstamp_type_list;
int tstamp_precision_count;
u_int *tstamp_precision_list;
struct pcap_pkthdr pcap_header; /* This is needed for the pcap_next_ex() to work */
/*
* More methods.
*/
activate_op_t activate_op;
can_set_rfmon_op_t can_set_rfmon_op;
inject_op_t inject_op;
setfilter_op_t setfilter_op;
setdirection_op_t setdirection_op;
set_datalink_op_t set_datalink_op;
getnonblock_op_t getnonblock_op;
setnonblock_op_t setnonblock_op;
stats_op_t stats_op;
/*
* Routine to use as callback for pcap_next()/pcap_next_ex().
*/
pcap_handler oneshot_callback;
#ifdef WIN32
/*
* These are, at least currently, specific to the Win32 NPF
* driver.
*/
setbuff_op_t setbuff_op;
setmode_op_t setmode_op;
setmintocopy_op_t setmintocopy_op;
getadapter_op_t getadapter_op;
#endif
cleanup_op_t cleanup_op;
};
函数pcap_open_live调用中,如果device为NULL或any,则对所有接口捕获,snaplen表示用户期望的捕获数据包最大长度,promisc表示设置接口为混杂模式,to_ms表示函数超时返回的时间。在pcap.c文件中找到pcap_open_live()函数,其源码如下:
pcap_t *
pcap_open_live(const char *source, int snaplen, int promisc, int to_ms, char *errbuf)
{
pcap_t *p;
int status;
p = pcap_create(source, errbuf);
if (p == NULL)
return (NULL);
status = pcap_set_snaplen(p, snaplen);
if (status < 0)
goto fail;
status = pcap_set_promisc(p, promisc);
if (status < 0)
goto fail;
status = pcap_set_timeout(p, to_ms);
if (status < 0)
goto fail;
/*
* Mark this as opened with pcap_open_live(), so that, for
* example, we show the full list of DLT_ values, rather
* than just the ones that are compatible with capturing
* when not in monitor mode. That allows existing applications
* to work the way they used to work, but allows new applications
* that know about the new open API to, for example, find out the
* DLT_ values that they can select without changing whether
* the adapter is in monitor mode or not.
*/
p->oldstyle = 1;
status = pcap_activate(p);
if (status < 0)
goto fail;
return (p);
fail:
if (status == PCAP_ERROR)
snprintf(errbuf, PCAP_ERRBUF_SIZE, "%s: %s", source,
p->errbuf);
else if (status == PCAP_ERROR_NO_SUCH_DEVICE ||
status == PCAP_ERROR_PERM_DENIED ||
status == PCAP_ERROR_PROMISC_PERM_DENIED)
snprintf(errbuf, PCAP_ERRBUF_SIZE, "%s: %s (%s)", source,
pcap_statustostr(status), p->errbuf);
else
snprintf(errbuf, PCAP_ERRBUF_SIZE, "%s: %s", source,
pcap_statustostr(status));
pcap_close(p);
return (NULL);
}
从上面的源码可以看到,pcap_open_live函数首先调用pcap_create函数,这个函数里面的内容待会儿在下面进行分析,然后就是调用pcap_set_snaplen(p, snaplen)函数设置最大捕获包的长度,对于以太网数据包,最大长度为1518bytes,默认的可以设置成65535可以捕获所有的数据包。然后就是调用pcap_set_promisc(p, promisc)函数设置数据包的捕获模式,1为混杂模式(只有混杂模式才能接收所有经过该网卡设备的数据包)。pcap_set_timeout(p, to_ms)的作用是设置超时的时间,当应用程序在这个时间内没读到数据就返回。接着就是pcap_activate(p)函数了,这个也将在后面进行讲解。
在Libpcap源码为了支持多个操作系统,代码错综复杂。对于pcap_create函数,在很多地方都定义了该函数,下面是在source insight软件中的列表。
其源码如下:
pcap_t *
pcap_create(const char *source, char *errbuf)
{
size_t i;
int is_theirs;
pcap_t *p;
/*
* A null source name is equivalent to the "any" device -
* which might not be supported on this platform, but
* this means that you'll get a "not supported" error
* rather than, say, a crash when we try to dereference
* the null pointer.
*/
if (source == NULL)
source = "any";
/*
* Try each of the non-local-network-interface capture
* source types until we find one that works for this
* device or run out of types.
*/
for (i = 0; capture_source_types[i].create_op != NULL; i++) {
is_theirs = 0;
p = capture_source_types[i].create_op(source, errbuf, &is_theirs);
if (is_theirs) {
/*
* The device name refers to a device of the
* type in question; either it succeeded,
* in which case p refers to a pcap_t to
* later activate for the device, or it
* failed, in which case p is null and we
* should return that to report the failure
* to create.
*/
return (p);
}
}
/*
* OK, try it as a regular network interface.
*/
return (pcap_create_interface(source, errbuf));
}
首先,当传入的设备名为空就这是该source = “any”,any 表示所有的设备都能够获取数据包。接着就是用一个for循环来尝试用每个non-local-network-interface捕捉源类型,直到我们发现一种适合该设备或耗尽类型。如果没有找到,则调用pcap_create_interface(source, errbuf))函数的返回结果作为返回值。
下面为pcap_create_interface(source, errbuf)函数的源代码:
#endif /* SO_ATTACH_FILTER */
pcap_t *
pcap_create_interface(const char *device, char *ebuf)
{
pcap_t *handle;
handle = pcap_create_common(device, ebuf, sizeof (struct pcap_linux));
if (handle == NULL)
return NULL;
// pcap_create_common为初始化的函数,通过网卡设备的名字获得pcap_t*的句柄,然后再设定handle的回调函数。
handle->activate_op = pcap_activate_linux;
handle->can_set_rfmon_op = pcap_can_set_rfmon_linux;
#if defined(HAVE_LINUX_NET_TSTAMP_H) && defined(PACKET_TIMESTAMP)
/*
* We claim that we support:
*
* software time stamps, with no details about their precision;
* hardware time stamps, synced to the host time;
* hardware time stamps, not synced to the host time.
*
* XXX - we can't ask a device whether it supports
* hardware time stamps, so we just claim all devices do.
*/
handle->tstamp_type_count = 3;
handle->tstamp_type_list = malloc(3 * sizeof(u_int));
if (handle->tstamp_type_list == NULL) {
snprintf(ebuf, PCAP_ERRBUF_SIZE, "malloc: %s",
pcap_strerror(errno));
free(handle);
return NULL;
}
handle->tstamp_type_list[0] = PCAP_TSTAMP_HOST;
handle->tstamp_type_list[1] = PCAP_TSTAMP_ADAPTER;
handle->tstamp_type_list[2] = PCAP_TSTAMP_ADAPTER_UNSYNCED;
#endif
#if defined(SIOCGSTAMPNS) && defined(SO_TIMESTAMPNS)
/*
* We claim that we support microsecond and nanosecond time
* stamps.
*
* XXX - with adapter-supplied time stamps, can we choose
* microsecond or nanosecond time stamps on arbitrary
* adapters?
*/
handle->tstamp_precision_count = 2;
handle->tstamp_precision_list = malloc(2 * sizeof(u_int));
if (handle->tstamp_precision_list == NULL) {
snprintf(ebuf, PCAP_ERRBUF_SIZE, "malloc: %s",
pcap_strerror(errno));
if (handle->tstamp_type_list != NULL)
free(handle->tstamp_type_list);
free(handle);
return NULL;
}
handle->tstamp_precision_list[0] = PCAP_TSTAMP_PRECISION_MICRO;
handle->tstamp_precision_list[1] = PCAP_TSTAMP_PRECISION_NANO;
#endif /* defined(SIOCGSTAMPNS) && defined(SO_TIMESTAMPNS) */
return handle;
}
为了能够支持不同的设备,pcap_create通过#ifdef进行区分,这样就将打开不同的设备集成在一个函数中,而在我们的应用中就是普通的网卡,所以它就是调用pcap_create_common函数,它在pcap.c中定义,感觉有点混乱,为什么不直接在pcap-linux.c中定义呢,个人观点,应该在pcap-linux中定义,显的直观些,害我跟踪的时候,还要到pcap.c中取找这个函数,因为libpcap还要兼容其它操作系统的原因吧,因为你把它放在pcap-linux.c,其它操作系统调用这个函数,就不方便了,从这一点考虑,libpcap的作者们的架构还是挺不错的。另外定义2个回调函数pcap_activate_linux和pcap_can_set_rfmon_linux函数。Pcap_create函数的返回值为pcap_t*类型的网卡的句柄。既然讲到了pcap_create函数,就必须跟踪到pcap_create_common函数及另外的2个回调函数中去。下面接着看pcap_create_common函数的源码:
pcap_t *
pcap_create_common(const char *source, char *ebuf, size_t size)
{
pcap_t *p;
p = pcap_alloc_pcap_t(ebuf, size);
if (p == NULL)
return (NULL);
p->opt.source = strdup(source);
if (p->opt.source == NULL) {
snprintf(ebuf, PCAP_ERRBUF_SIZE, "malloc: %s",
pcap_strerror(errno));
free(p);
return (NULL);
}
/*
* Default to "can't set rfmon mode"; if it's supported by
* a platform, the create routine that called us can set
* the op to its routine to check whether a particular
* device supports it.
*/
p->can_set_rfmon_op = pcap_cant_set_rfmon;
initialize_ops(p);
/* put in some defaults*/
pcap_set_snaplen(p, MAXIMUM_SNAPLEN); /* max packet size */
p->opt.timeout = 0; /* no timeout specified */
p->opt.buffer_size = 0; /* use the platform's default */
p->opt.promisc = 0;
p->opt.rfmon = 0;
p->opt.immediate = 0;
p->opt.tstamp_type = -1; /* default to not setting time stamp type */
p->opt.tstamp_precision = PCAP_TSTAMP_PRECISION_MICRO;
return (p);
}
首先调用pcap_alloc_pcap_t函数给p分配内存。然后调用strdup函数。它的作用是复制字符串。返回指向被复制的字符串的指针。需要加头文件#include<string.h>。
在p->can_set_rfmon_op = pcap_cant_set_rfmon这句代码中,默认不设置rfmon 模式。而initialize_ops(p)函数的作用就是设置初始化的一系列回调函数。其中initialize_ops(p)函数的源代码如下:
static void
initialize_ops(pcap_t *p)
{
/*
* Set operation pointers for operations that only work on
* an activated pcap_t to point to a routine that returns
* a "this isn't activated" error.
*/
p->read_op = (read_op_t)pcap_not_initialized;
p->inject_op = (inject_op_t)pcap_not_initialized;
p->setfilter_op = (setfilter_op_t)pcap_not_initialized;
p->setdirection_op = (setdirection_op_t)pcap_not_initialized;
p->set_datalink_op = (set_datalink_op_t)pcap_not_initialized;
p->getnonblock_op = (getnonblock_op_t)pcap_not_initialized;
p->setnonblock_op = (setnonblock_op_t)pcap_not_initialized;
p->stats_op = (stats_op_t)pcap_not_initialized;
#ifdef WIN32
p->setbuff_op = (setbuff_op_t)pcap_not_initialized;
p->setmode_op = (setmode_op_t)pcap_not_initialized;
p->setmintocopy_op = (setmintocopy_op_t)pcap_not_initialized;
p->getadapter_op = pcap_no_adapter;
#endif
/*
* Default cleanup operation - implementations can override
* this, but should call pcap_cleanup_live_common() after
* doing their own additional cleanup.
*/
p->cleanup_op = pcap_cleanup_live_common;
/*
* In most cases, the standard one-shot callback can
* be used for pcap_next()/pcap_next_ex().
*/
p->oneshot_callback = pcap_oneshot;
}
pcap_create_common讲解完了,接着讲解pcap_create函数中的另外一个回调函数,pcap_activate_linux。通过搜索。发现在pcap_linux.c这个文件中。在整个pcap的架构中,把linux要用到的函数都集成到pcap_linux.c中,把多个操作系统共用的函数都放到了pcap.c中,例如前面分析的pcap_create_common、pcap_create_interface函数。下面讲解pcap_activate_linux这个源码。从pcap_activate_linux的源码可以看到,通过pcap_create_common对pcap_t * p设定初始值,其实就像c++的初始化函数一样,比如c++的构造函数,MFC的OninitDialog函数一样。初始化就是初始化,对于不同的系统,就要进行不同的设置了,在linux函数中pcap_activate_linux中可以看到又对pcap_create_common中初始化的回调函数又重新进行了设置,看到这里我就佩服libpcap的作者了,把pcap_create_common函数放到了pcap.c文件中。
/*
* Get a handle for a live capture from the given device. You can
* pass NULL as device to get all packages (without link level
* information of course). If you pass 1 as promisc the interface
* will be set to promiscous mode (XXX: I think this usage should
* be deprecated and functions be added to select that later allow
* modification of that values -- Torsten).
*/
static int
pcap_activate_linux(pcap_t *handle)
{
struct pcap_linux *handlep = handle->priv;
const char *device;
struct ifreq ifr;
int status = 0;
int ret;
device = handle->opt.source; //网卡的名字
/*
* Make sure the name we were handed will fit into the ioctls we
* might perform on the device; if not, return a "No such device"
* indication, as the Linux kernel shouldn't support creating
* a device whose name won't fit into those ioctls.
*
* "Will fit" means "will fit, complete with a null terminator",
* so if the length, which does *not* include the null terminator,
* is greater than *or equal to* the size of the field into which
* we'll be copying it, that won't fit.
*/
if (strlen(device) >= sizeof(ifr.ifr_name)) {
status = PCAP_ERROR_NO_SUCH_DEVICE;
goto fail;
}
handle->inject_op = pcap_inject_linux;
handle->setfilter_op = pcap_setfilter_linux;
handle->setdirection_op = pcap_setdirection_linux;
handle->set_datalink_op = pcap_set_datalink_linux;
handle->getnonblock_op = pcap_getnonblock_fd;
handle->setnonblock_op = pcap_setnonblock_fd;
handle->cleanup_op = pcap_cleanup_linux;
handle->read_op = pcap_read_linux;
handle->stats_op = pcap_stats_linux;
/*
* The "any" device is a special device which causes us not
* to bind to a particular device and thus to look at all
* devices.
*/
if (strcmp(device, "any") == 0) {
if (handle->opt.promisc) {
handle->opt.promisc = 0;
/* Just a warning. */
snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
"Promiscuous mode not supported on the \"any\" device");
status = PCAP_WARNING_PROMISC_NOTSUP;
}
}
handlep->device = strdup(device);
if (handlep->device == NULL) {
snprintf(handle->errbuf, PCAP_ERRBUF_SIZE, "strdup: %s",
pcap_strerror(errno) );
return PCAP_ERROR;
}
/* copy timeout value */
handlep->timeout = handle->opt.timeout;
/*
* If we're in promiscuous mode, then we probably want
* to see when the interface drops packets too, so get an
* initial count from /proc/net/dev
*/
if (handle->opt.promisc)
handlep->proc_dropped = linux_if_drops(handlep->device);
/*
* Current Linux kernels use the protocol family PF_PACKET to
* allow direct access to all packets on the network while
* older kernels had a special socket type SOCK_PACKET to
* implement this feature.
* While this old implementation is kind of obsolete we need
* to be compatible with older kernels for a while so we are
* trying both methods with the newer method preferred.
*/
//现在的内核是采用的PF_PACKET。对于以前的内核采用SOCK_PACKET
ret = activate_new(handle);
//activate_new函数的作用在没有定义PF_RING的情况下通过PF_PACKET接口建立socket,返回1表示成功,可以采用PF_PACKET建立socket,返回0表示失败,这时可以尝试采用SOCKET_PACKET接口建立socket,该函数也在pcap-linux.c中可以找到源码;根据status的返回值,确定3种不同的情况,返回1成功,表示采用的是PF_PACKET建立socket,而返回0的时候,又调用activate_old函数进行判断,如果activate_old函数返回1表示调用的是SOCK_PACKET建立socket,而activate_old返回0表示失败;第3种情况是status不等于上面的2个值,则表示失败。在下面将详细分析activate_new函数。
if (ret < 0) {
/*
* Fatal error with the new way; just fail.
* ret has the error return; if it's PCAP_ERROR,
* handle->errbuf has been set appropriately.
*/
status = ret;
goto fail;
}
if (ret == 1) {
/*
* Success.
* Try to use memory-mapped access.
*/
switch (activate_mmap(handle, &status)) {
case 1:
/*
* We succeeded. status has been
* set to the status to return,
* which might be 0, or might be
* a PCAP_WARNING_ value.
*/
return status;
case 0:
/*
* Kernel doesn't support it - just continue
* with non-memory-mapped access.
*/
break;
case -1:
/*
* We failed to set up to use it, or the kernel
* supports it, but we failed to enable it.
* ret has been set to the error status to
* return and, if it's PCAP_ERROR, handle->errbuf
* contains the error message.
*/
status = ret;
goto fail;
}
}
else if (ret == 0) {
/* Non-fatal error; try old way */
if ((ret = activate_old(handle)) != 1) {
/*
* Both methods to open the packet socket failed.
* Tidy up and report our failure (handle->errbuf
* is expected to be set by the functions above).
*/
status = ret;
goto fail;
}
}
/*
* We set up the socket, but not with memory-mapped access.
*/
if (handle->opt.buffer_size != 0) {
//如果buffer_size不为0,pcap_set_buffer_size设置了内核缓冲区的大小,而不是采用默认的内核缓冲区,因此首先通过setsockopt发送设置命令,然后调用malloc分配内存
/*
* Set the socket buffer size to the specified value.
*/
if (setsockopt(handle->fd, SOL_SOCKET, SO_RCVBUF,
&handle->opt.buffer_size,
sizeof(handle->opt.buffer_size)) == -1) {
snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
"SO_RCVBUF: %s", pcap_strerror(errno));
status = PCAP_ERROR;
goto fail;
}
}
/* Allocate the buffer */
handle->buffer = malloc(handle->bufsize + handle->offset);
if (!handle->buffer) {
snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
"malloc: %s", pcap_strerror(errno));
status = PCAP_ERROR;
goto fail;
}
/*
* "handle->fd" is a socket, so "select()" and "poll()"
* should work on it.
*/
handle->selectable_fd = handle->fd;
return status;
fail:
pcap_cleanup_linux(handle);
return status;
}
pcap_activate_linux函数分析完了。但是其到底是怎么建立通讯的还不是很清楚,现在进入activate_new函数进行分析,其源码如下:
/* ===== Functions to interface to the newer kernels ================== */
/*
* Try to open a packet socket using the new kernel PF_PACKET interface.
* Returns 1 on success, 0 on an error that means the new interface isn't
* present (so the old SOCK_PACKET interface should be tried), and a
* PCAP_ERROR_ value on an error that means that the old mechanism won't
* work either (so it shouldn't be tried).
*/
static int
activate_new(pcap_t *handle)
{
#ifdef HAVE_PF_PACKET_SOCKETS
struct pcap_linux *handlep = handle->priv;
const char *device = handle->opt.source;
int is_any_device = (strcmp(device, "any") == 0);
int sock_fd = -1, arptype;
#ifdef HAVE_PACKET_AUXDATA
int val;
#endif
int err = 0;
struct packet_mreq mr;
/*
* Open a socket with protocol family packet. If the
* "any" device was specified, we open a SOCK_DGRAM
* socket for the cooked interface, otherwise we first
* try a SOCK_RAW socket for the raw interface.
*/
sock_fd = is_any_device ?
socket(PF_PACKET, SOCK_DGRAM, htons(ETH_P_ALL)) :
socket(PF_PACKET, SOCK_RAW, htons(ETH_P_ALL));
// 建立socket。当网卡设备名为any的时候用SOCK_DGRAM,当不为any时用SOCK_RAM 来建立。至于后面的通信就是在这里开始的。基于该socket描述符。在下面肯定有bind函数。
if (sock_fd == -1) {
if (errno == EINVAL || errno == EAFNOSUPPORT) {
/*
* We don't support PF_PACKET/SOCK_whatever
* sockets; try the old mechanism.
*/
return 0;
}
snprintf(handle->errbuf, PCAP_ERRBUF_SIZE, "socket: %s",
pcap_strerror(errno) );
if (errno == EPERM || errno == EACCES) {
/*
* You don't have permission to open the
* socket.
*/
return PCAP_ERROR_PERM_DENIED;
} else {
/*
* Other error.
*/
return PCAP_ERROR;
}
}
/* It seems the kernel supports the new interface. */
handlep->sock_packet = 0;
/*
* Get the interface index of the loopback device.
* If the attempt fails, don't fail, just set the
* "handlep->lo_ifindex" to -1.
*
* XXX - can there be more than one device that loops
* packets back, i.e. devices other than "lo"? If so,
* we'd need to find them all, and have an array of
* indices for them, and check all of them in
* "pcap_read_packet()".
*/
handlep->lo_ifindex = iface_get_id(sock_fd, "lo", handle->errbuf);
/*
* Default value for offset to align link-layer payload
* on a 4-byte boundary.
*/
handle->offset = 0;
/*
* What kind of frames do we have to deal with? Fall back
* to cooked mode if we have an unknown interface type
* or a type we know doesn't work well in raw mode.
*/
if (!is_any_device) {
/* Assume for now we don't need cooked mode. */
handlep->cooked = 0;
if (handle->opt.rfmon) {
/*
* We were asked to turn on monitor mode.
* Do so before we get the link-layer type,
* because entering monitor mode could change
* the link-layer type.
*/
err = enter_rfmon_mode(handle, sock_fd, device);
if (err < 0) {
/* Hard failure */
close(sock_fd);
return err;
}
if (err == 0) {
/*
* Nothing worked for turning monitor mode
* on.
*/
close(sock_fd);
return PCAP_ERROR_RFMON_NOTSUP;
}
/*
* Either monitor mode has been turned on for
* the device, or we've been given a different
* device to open for monitor mode. If we've
* been given a different device, use it.
*/
if (handlep->mondevice != NULL)
device = handlep->mondevice;
}
arptype = iface_get_arptype(sock_fd, device, handle->errbuf);
if (arptype < 0) {
close(sock_fd);
return arptype;
}
map_arphrd_to_dlt(handle, arptype, device, 1);
if (handle->linktype == -1 ||
handle->linktype == DLT_LINUX_SLL ||
handle->linktype == DLT_LINUX_IRDA ||
handle->linktype == DLT_LINUX_LAPD ||
handle->linktype == DLT_NETLINK ||
(handle->linktype == DLT_EN10MB &&
(strncmp("isdn", device, 4) == 0 ||
strncmp("isdY", device, 4) == 0))) {
/*
* Unknown interface type (-1), or a
* device we explicitly chose to run
* in cooked mode (e.g., PPP devices),
* or an ISDN device (whose link-layer
* type we can only determine by using
* APIs that may be different on different
* kernels) - reopen in cooked mode.
*/
if (close(sock_fd) == -1) {
snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
"close: %s", pcap_strerror(errno));
return PCAP_ERROR;
}
sock_fd = socket(PF_PACKET, SOCK_DGRAM,
htons(ETH_P_ALL));
if (sock_fd == -1) {
snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
"socket: %s", pcap_strerror(errno));
if (errno == EPERM || errno == EACCES) {
/*
* You don't have permission to
* open the socket.
*/
return PCAP_ERROR_PERM_DENIED;
} else {
/*
* Other error.
*/
return PCAP_ERROR;
}
}
handlep->cooked = 1;
/*
* Get rid of any link-layer type list
* we allocated - this only supports cooked
* capture.
*/
if (handle->dlt_list != NULL) {
free(handle->dlt_list);
handle->dlt_list = NULL;
handle->dlt_count = 0;
}
if (handle->linktype == -1) {
/*
* Warn that we're falling back on
* cooked mode; we may want to
* update "map_arphrd_to_dlt()"
* to handle the new type.
*/
snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
"arptype %d not "
"supported by libpcap - "
"falling back to cooked "
"socket",
arptype);
}
/*
* IrDA capture is not a real "cooked" capture,
* it's IrLAP frames, not IP packets. The
* same applies to LAPD capture.
*/
if (handle->linktype != DLT_LINUX_IRDA &&
handle->linktype != DLT_LINUX_LAPD &&
handle->linktype != DLT_NETLINK)
handle->linktype = DLT_LINUX_SLL;
}
handlep->ifindex = iface_get_id(sock_fd, device,
handle->errbuf);
if (handlep->ifindex == -1) {
close(sock_fd);
return PCAP_ERROR;
}
//在这里出现了iface_bind函数。在该函数里面bind(fd, (struct sockaddr *) &sll, sizeof(sll)) == -1进行绑定。
if ((err = iface_bind(sock_fd, handlep->ifindex,
handle->errbuf)) != 1) {
close(sock_fd);
if (err < 0)
return err;
else
return 0; /* try old mechanism */
}
} else {
/*
* The "any" device.
*/
if (handle->opt.rfmon) {
/*
* It doesn't support monitor mode.
*/
close(sock_fd);
return PCAP_ERROR_RFMON_NOTSUP;
}
/*
* It uses cooked mode.
*/
handlep->cooked = 1;
handle->linktype = DLT_LINUX_SLL;
/*
* We're not bound to a device.
* For now, we're using this as an indication
* that we can't transmit; stop doing that only
* if we figure out how to transmit in cooked
* mode.
*/
handlep->ifindex = -1;
}
/*
* Select promiscuous mode on if "promisc" is set.
*
* Do not turn allmulti mode on if we don't select
* promiscuous mode - on some devices (e.g., Orinoco
* wireless interfaces), allmulti mode isn't supported
* and the driver implements it by turning promiscuous
* mode on, and that screws up the operation of the
* card as a normal networking interface, and on no
* other platform I know of does starting a non-
* promiscuous capture affect which multicast packets
* are received by the interface.
*/
/*
* Hmm, how can we set promiscuous mode on all interfaces?
* I am not sure if that is possible at all. For now, we
* silently ignore attempts to turn promiscuous mode on
* for the "any" device (so you don't have to explicitly
* disable it in programs such as tcpdump).
*/
if (!is_any_device && handle->opt.promisc) {
memset(&mr, 0, sizeof(mr));
mr.mr_ifindex = handlep->ifindex;
mr.mr_type = PACKET_MR_PROMISC;
if (setsockopt(sock_fd, SOL_PACKET, PACKET_ADD_MEMBERSHIP,
&mr, sizeof(mr)) == -1) {
snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
"setsockopt: %s", pcap_strerror(errno));
close(sock_fd);
return PCAP_ERROR;
}
}
/* Enable auxillary data if supported and reserve room for
* reconstructing VLAN headers. */
#ifdef HAVE_PACKET_AUXDATA
val = 1;
if (setsockopt(sock_fd, SOL_PACKET, PACKET_AUXDATA, &val,
sizeof(val)) == -1 && errno != ENOPROTOOPT) {
snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
"setsockopt: %s", pcap_strerror(errno));
close(sock_fd);
return PCAP_ERROR;
}
handle->offset += VLAN_TAG_LEN;
#endif /* HAVE_PACKET_AUXDATA */
/*
* This is a 2.2[.x] or later kernel (we know that
* because we're not using a SOCK_PACKET socket -
* PF_PACKET is supported only in 2.2 and later
* kernels).
*
* We can safely pass "recvfrom()" a byte count
* based on the snapshot length.
*
* If we're in cooked mode, make the snapshot length
* large enough to hold a "cooked mode" header plus
* 1 byte of packet data (so we don't pass a byte
* count of 0 to "recvfrom()").
*/
if (handlep->cooked) {
if (handle->snapshot < SLL_HDR_LEN + 1)
handle->snapshot = SLL_HDR_LEN + 1;
}
handle->bufsize = handle->snapshot;
/*
* Set the offset at which to insert VLAN tags.
*/
switch (handle->linktype) {
case DLT_EN10MB:
handlep->vlan_offset = 2 * ETH_ALEN;
break;
case DLT_LINUX_SLL:
handlep->vlan_offset = 14;
break;
default:
handlep->vlan_offset = -1; /* unknown */
break;
}
#if defined(SIOCGSTAMPNS) && defined(SO_TIMESTAMPNS)
if (handle->opt.tstamp_precision == PCAP_TSTAMP_PRECISION_NANO) {
int nsec_tstamps = 1;
if (setsockopt(sock_fd, SOL_SOCKET, SO_TIMESTAMPNS, &nsec_tstamps, sizeof(nsec_tstamps)) < 0) {
snprintf(handle->errbuf, PCAP_ERRBUF_SIZE, "setsockopt: unable to set SO_TIMESTAMPNS");
close(sock_fd);
return PCAP_ERROR;
}
}
#endif /* defined(SIOCGSTAMPNS) && defined(SO_TIMESTAMPNS) */
/*
* We've succeeded. Save the socket FD in the pcap structure.
*/
handle->fd = sock_fd;
return 1;
#else /* HAVE_PF_PACKET_SOCKETS */
strlcpy(ebuf,
"New packet capturing interface not supported by build "
"environment", PCAP_ERRBUF_SIZE);
return 0;
#endif /* HAVE_PF_PACKET_SOCKETS */
}
在activate_new函数中,主要涉及到socket的创建与bind。下面将pcap_activate_linux函数中定义的重要回调函数罗列出来:
handle->inject_op = pcap_inject_linux;
handle->setfilter_op = pcap_setfilter_linux;
handle->setdirection_op = pcap_setdirection_linux;
handle->set_datalink_op = pcap_set_datalink_linux;
handle->getnonblock_op = pcap_getnonblock_fd;
handle->setnonblock_op = pcap_setnonblock_fd;
handle->cleanup_op = pcap_cleanup_linux;
handle->read_op = pcap_read_linux;
handle->stats_op = pcap_stats_linux;
其中一个重要的回调函数就是pcap_read_linux。进入其源码,如下:
/*
* Read at most max_packets from the capture stream and call the callback
* for each of them. Returns the number of packets handled or -1 if an
* error occured.
*/
static int
pcap_read_linux(pcap_t *handle, int max_packets, pcap_handler callback, u_char *user)
{
/*
* Currently, on Linux only one packet is delivered per read,
* so we don't loop.
*/
return pcap_read_packet(handle, callback, user);
}
其中就只有一句,return pcap_read_packet(handle, callback, user)。调用pcap_read_packet读取数据包。在该函数中,初步断定是在后面的pcap_next、pcap_dispatch、pcap_loop这几个函数读包时调用的。下面开始分析pcap_read_packet函数,源码如下:
/*
* Read a packet from the socket calling the handler provided by
* the user. Returns the number of packets received or -1 if an
* error occured.
*/
static int
pcap_read_packet(pcap_t *handle, pcap_handler callback, u_char *userdata)
{
struct pcap_linux *handlep = handle->priv;
u_char *bp; //数据包缓冲区指针
int offset;
//bp与捕获句柄pcap_t中handle->buffer之间的偏移量,其目的是为再加工模式捕获情况下,为合成的伪数据链路层头部流出空间
//PACKET_SOCKET方式下,recvfrom()返回sockeaddr_ll类型,而在SOCK_PACKET方式下返回sockaddr类型
#ifdef HAVE_PF_PACKET_SOCKETS
struct sockaddr_ll from;
struct sll_header *hdrp;
#else
struct sockaddr from;
#endif
#if defined(HAVE_PACKET_AUXDATA) && defined(HAVE_LINUX_TPACKET_AUXDATA_TP_VLAN_TCI)
struct iovec iov;
struct msghdr msg;
struct cmsghdr *cmsg;
union {
struct cmsghdr cmsg;
char buf[CMSG_SPACE(sizeof(struct tpacket_auxdata))];
} cmsg_buf;
#else /* defined(HAVE_PACKET_AUXDATA) && defined(HAVE_LINUX_TPACKET_AUXDATA_TP_VLAN_TCI) */
socklen_t fromlen;
#endif /* defined(HAVE_PACKET_AUXDATA) && defined(HAVE_LINUX_TPACKET_AUXDATA_TP_VLAN_TCI) */
int packet_len, caplen;
struct pcap_pkthdr pcap_header;
//libpcap自定义的头部,pcap_pkthdr结构体如下:
struct pcap_pkthdr {
struct timeval ts; /* time stamp */
bpf_u_int32 caplen; /* length of portion present */
bpf_u_int32 len; /* length this packet (off wire) */
};
该结构体主要记录时间戳、抓取的数据包以及数据包长度。通常后两者的长度是一样的。
#ifdef HAVE_PF_PACKET_SOCKETS
/*
* If this is a cooked device, leave extra room for a
* fake packet header.
*/
//如果是加工模式,则在合成的链路层头部留出空间
if (handlep->cooked)
offset = SLL_HDR_LEN;
//其他两种方式下,链路层头部不做修改返回,不需要留出空间
else
offset = 0;
#else
/*
* This system doesn't have PF_PACKET sockets, so it doesn't
* support cooked devices.
*/
offset = 0;
#endif
/*
* Receive a single packet from the kernel.
* We ignore EINTR, as that might just be due to a signal
* being delivered - if the signal should interrupt the
* loop, the signal handler should call pcap_breakloop()
* to set handle->break_loop (we ignore it on other
* platforms as well).
* We also ignore ENETDOWN, so that we can continue to
* capture traffic if the interface goes down and comes
* back up again; comments in the kernel indicate that
* we'll just block waiting for packets if we try to
* receive from a socket that delivered ENETDOWN, and,
* if we're using a memory-mapped buffer, we won't even
* get notified of "network down" events.
*/
bp = handle->buffer + handle->offset;
#if defined(HAVE_PACKET_AUXDATA) && defined(HAVE_LINUX_TPACKET_AUXDATA_TP_VLAN_TCI)
msg.msg_name = &from;
msg.msg_namelen = sizeof(from);
msg.msg_iov = &iov;
msg.msg_iovlen = 1;
msg.msg_control = &cmsg_buf;
msg.msg_controllen = sizeof(cmsg_buf);
msg.msg_flags = 0;
iov.iov_len = handle->bufsize - offset;
iov.iov_base = bp + offset;
#endif /* defined(HAVE_PACKET_AUXDATA) && defined(HAVE_LINUX_TPACKET_AUXDATA_TP_VLAN_TCI) */
do {
/*
* Has "pcap_breakloop()" been called?
*/
if (handle->break_loop) {
/*
* Yes - clear the flag that indicates that it has,
* and return PCAP_ERROR_BREAK as an indication that
* we were told to break out of the loop.
*/
handle->break_loop = 0;
return PCAP_ERROR_BREAK;
}
#if defined(HAVE_PACKET_AUXDATA) && defined(HAVE_LINUX_TPACKET_AUXDATA_TP_VLAN_TCI)
packet_len = recvmsg(handle->fd, &msg, MSG_TRUNC);
//在这里以及后面的recvfrom函数,说明了定义不同的类型,其接受的数据的方式是不一样的。
#else /* defined(HAVE_PACKET_AUXDATA) && defined(HAVE_LINUX_TPACKET_AUXDATA_TP_VLAN_TCI) */
fromlen = sizeof(from);
//从内核中接收一个数据包,注意函数入参中对bp的位置的修正
packet_len = recvfrom(
handle->fd, bp + offset,
handle->bufsize - offset, MSG_TRUNC,
(struct sockaddr *) &from, &fromlen);
#endif /* defined(HAVE_PACKET_AUXDATA) && defined(HAVE_LINUX_TPACKET_AUXDATA_TP_VLAN_TCI) */
} while (packet_len == -1 && errno == EINTR);
/* Check if an error occured */
if (packet_len == -1) {
switch (errno) {
case EAGAIN:
return 0; /* no packet there */
case ENETDOWN:
/*
* The device on which we're capturing went away.
*
* XXX - we should really return
* PCAP_ERROR_IFACE_NOT_UP, but pcap_dispatch()
* etc. aren't defined to return that.
*/
snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
"The interface went down");
return PCAP_ERROR;
default:
snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
"recvfrom: %s", pcap_strerror(errno));
return PCAP_ERROR;
}
}
#ifdef HAVE_PF_PACKET_SOCKETS
//
if (!handlep->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 (handlep->ifindex != -1 &&
from.sll_ifindex != handlep->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 (!linux_check_direction(handle, &from))
return 0;
}
#endif
#ifdef HAVE_PF_PACKET_SOCKETS
/*
* If this is a cooked device, fill in the fake packet header.
*/
//如果是加工模式,则合成伪链路层头部
if (handlep->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 (handlep->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) handlep->vlan_offset)
break;
bp -= VLAN_TAG_LEN;
memmove(bp, bp + VLAN_TAG_LEN, handlep->vlan_offset);
tag = (struct vlan_tag *)(bp + handlep->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 MAXIMUM_SNAPLEN so that the
* filter doesn't truncate the packet, and supplying that modified
* filter to the kernel.
*/
//修正捕获的数据包的成都,根据前面的讨论,SOCK_PACKET方式下长度可能是不准确的
caplen = packet_len;
if (caplen > handle->snapshot)
caplen = handle->snapshot;
/* Run the packet filter if not using kernel filter */
//如果没有使用内核级的包过滤,则在用户空间进行过滤
if (handlep->filter_in_userland && 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 */
//填充libpcap自定义数据包头部数据:捕获时间,捕获的成都,真实的长度
/* get timestamp for this packet */
#if defined(SIOCGSTAMPNS) && defined(SO_TIMESTAMPNS)
if (handle->opt.tstamp_precision == PCAP_TSTAMP_PRECISION_NANO) {
if (ioctl(handle->fd, SIOCGSTAMPNS, &pcap_header.ts) == -1) {
snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
"SIOCGSTAMPNS: %s", pcap_strerror(errno));
return PCAP_ERROR;
}
} else
#endif
{
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 "handlep->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 "handlep->stat.ps_recv" and
* "handlep->stat.ps_drop" as running counts, as reading the
* statistics from the kernel resets the kernel statistics,
* and if we directly increment "handlep->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().
*/
//累加捕获数据包数目,注意到在不同内核和捕获方式情况下数目可能不准确
handlep->packets_read++;
/* Call the user supplied callback function */
//调用用户定义的回调函数
callback(userdata, &pcap_header, bp);
return 1;
}
一直将怎个源码看一下,发现其中最主要的还是对数据包的接收,以及对其中的数据的收集整理,计数等操作。
在前面的几十页中,pcap_open_live还没有讲解完。就分析了其中的调用的一个pcap_create函数。这也体现了Libpcap的强大之处。下面将分析 pcap_open_live中的另一个函数pcap_activate(p)。其源码如下:
int
pcap_activate(pcap_t *p)
{
int status;
/*
* Catch attempts to re-activate an already-activated
* pcap_t; this should, for example, catch code that
* calls pcap_open_live() followed by pcap_activate(),
* as some code that showed up in a Stack Exchange
* question did.
*/
if (pcap_check_activated(p))
return (PCAP_ERROR_ACTIVATED);
status = p->activate_op(p);
//activate_op函数,通过搜索其原型为函数指针。它的初始化赋值在pcap-linux.c下410行。handle->activate_op = pcap_activate_linux;明白了在pcap_create中定义的pcap_activate_linux函数中赋值的回调函数activate_op终于在这里调用了。在pcap_create中只是赋值定义了该回调函数,而调用就是在这里。
if (status >= 0)
p->activated = 1;
else {
if (p->errbuf[0] == '\0') {
/*
* No error message supplied by the activate routine;
* for the benefit of programs that don't specially
* handle errors other than PCAP_ERROR, return the
* error message corresponding to the status.
*/
snprintf(p->errbuf, PCAP_ERRBUF_SIZE, "%s",
pcap_statustostr(status));
}
/*
* Undo any operation pointer setting, etc. done by
* the activate operation.
*/
initialize_ops(p);
}
return (status);
}
Pcap_open_live函数到现在终于分析完了。其实就pcap_create和pcap_activate两个函数。在pcap_create中主要是socket的建立和绑定。而在pcap_activate中定义的是接收消息回调函数的定义。接下来对pcap_loop函数的分析,其中肯定必定会调用该回调函数pcap_read_linux。在该回调函数中pcap_read_packet读取数据包。
4.3获取数据包
通过前面的分析,下面将讲解如何获取数据包,以及用户回调函数的处理。那就是pcap_loop函数。其源码如下:
int
pcap_loop(pcap_t *p, int cnt, pcap_handler callback, u_char *user)
{
register int n;
for (;;) {
//读取本地文件。
if (p->rfile != NULL) {
/*
* 0 means EOF, so don't loop if we get 0.
*/
n = pcap_offline_read(p, cnt, callback, user);
} else {
/*
* XXX keep reading until we get something
* (or an error occurs)
*/
do {
n = p->read_op(p, cnt, callback, user);
} while (n == 0);
}
if (n <= 0)
return (n);
if (!PACKET_COUNT_IS_UNLIMITED(cnt)) {
cnt -= n;
if (cnt <= 0)
return (0);
}
}
}
首先通过判断rfile是否为空,为空,则进行后面的数据包的获取。不为空就处理本地文件的读取。p->read_op(p, cnt, callback, user)回调函数。搜索整个工程,发现其位于pcap-linux.c函数的1265行。在这行定义的回调函数,终于在这里进行了调用。该回调函数的分析在上面已经进行分析了,主要是获取数据包。也都详细的讲解了。在最后又一个callback(userdata, &pcap_header, bp);函数,是调用用户自定义的回调函数。最后通过处理用户传送的捕获数据长度的参数,当cnt为有限的时候就行减操作,知道小于等于0时,其代码如下:
if (!PACKET_COUNT_IS_UNLIMITED(cnt)) {
cnt -= n;
if (cnt <= 0)
return (0);
}
-
Linux下Libpcap源码分析和包过虑机制
2012-01-20 08:31:18Linux下Libpcap源码分析和包过虑机制 2010年07月21日 Linux下Libpcap源码分析和包过虑机制 libpcap是Unix/Linux平台下的网络数据包捕获函数包,大多数网络监控软件都以它为基础.Libpcap可以在绝大多数类Unix...Linux下Libpcap源码分析和包过虑机制
2010年07月21日
Linux下Libpcap源码分析和包过虑机制
libpcap是Unix/Linux平台下的网络数据包捕获函数包,大多数网络监控软件都以它为基础.Libpcap可以在绝大多数类Unix平台下工作,本文分析了libpcap在Linux下的源代码实现,其中重点是Linux的底层包捕获机制和过滤器设置方式,同时也较浅的探讨libpcap使用的包过滤机制.
网络监控
绝大多数现代操作系统都提供了对底层数据包捕获机制,在捕获机制之上可以建立网络监控(Network Monitoring)应用软件.网络监控也常简称为Sniffer,其最初的目的在于对网络通信情况进行监控,以对网络的一些异常情况进行调试处理.但随着互联网的快速普及和网络攻击行为的频繁出现,保护网络的运行安全也成为监控软件的另一重要目的.例如, 网络监控在路由器,防火墙,入侵检查等方面使用也很广泛.它也是一种比较有效的黑客手段,例于,美国政府安全部门的"肉食动物"计划.
包捕获机制
从广义的角度上看,一个包捕获机制包含了三个主要部分:(1)最底层是针对特定的操作系统的包捕获机制.(2)最高层是针对用户的程式接口.(3)包过滤机制.
对不同的操作系统实现的底层包捕获机制可能是不一样的,但从形式上看大同小异.数据包常规的传输路径依次为:网卡 => 设备驱动层 => 数据链路层 => IP层 => 传输层 => 最后到达应用程式. 而包捕获机制是在数据链路层增加一个旁路处理,对发送和接收到的数据包做过滤/缓冲等相关处理,最后直接传递到应用程式.注意:包捕获机制并不影响操作系统对数据包的网络栈处理。对用户而言,包捕获机制提供了一个统一的接口,使用户程式只需要简单的调用若干函数就能获得所期望的数据包.这样一来,针对特定操作系统的捕获机制对用户透明,使用户程式有比较好的可移植性.包过滤机制是对所捕获到的数据包根据用户的要求进行筛选,最终只把满足过滤条件的数据包传递给用户程式.
Libpcap应用程式框架
Libpcap提供了系统独立的用户级别网络数据包捕获接口,并充分考虑到应用程式的可移植性.Libpcap可以从最上面的链接直接下载.然后执行类Unix系统最常用的以三条命令即可安装,但如果希望libpcap能在Linux正常工作,则必须使内核支持"packet"协议,也即在编译内核时打开配置选项 CONFIG_PACKET(选项缺省为打开).
[princezhou@zan]$ ./config
[princezhou@zan]$ make
[princezhou@zan]$ make install
Libpcap源代码由20多个C文件构成,但在Linux系统下并不是所有文件都能用到.可以查看命令make输出了解实际用的文件.Libpcap应用程式从形式上看很简单,下面是一个简单的程式框架:
char * device; /* 用来捕获数据包的网络接口名称 */
pcap_t * p; /* 捕获数据包句柄,最重要的数据结构*/
struct bpf_program fcode; /* BPF 过滤代码结构.*/
/* 第一步:查找可以捕获数据包的设备 */
device = pcap_lookupdev(errbuf);
/* 第二步:创建捕获句柄,准备进行捕获 */
p = pcap_open_live(device, 8000, 1, 500, errbuf);
/* 第三步:如果用户设置了过滤条件,则编译和安装过滤代码*/
pcap_compile(p, &fcode,filter_string, 0, netmask);
pcap_setfilter(p, &fcode);
/* 第四步:进入(死)循环,反复捕获数据包*/
for(;;)
{
while((ptr =(char *)(pcap_next(p, &hdr))) == NULL);
/*第五步:对捕获的数据进行类型转换,转化成以太数据包类型*/
eth = (struct libnet_ethernet_hdr *)ptr;
/*第六步:对以太头部进行分析,判断所包含的数据包类型,做进一步的处理*/
if(eth->ether_type == ntohs(ETHERTYPE_IP))
.................
if(eth->ether_type == ntohs(ETHERTYPE_ARP))
.................
}
/*最后一步:关闭句柄,一个简单的技巧是在程式初始化时增加信号处理函数,以便在程序退出前执行本条代码*/
pcap_close(p); 检查网络设备
libpcap程式的第一步通常是在系统中找到合适的网络接口设备.网络接口在linux网络体系中是一个很重要的概念,它是对具体网络硬件设备的一个抽象,在它的下面是具体的网卡驱程式,在其上则是网络协议层.Linux中最常见的接口设备名是eth0和L0.L0称为回路设备,是一种逻辑意义上的设备,其主要目的是为了调试网络程式之间的通讯功能.eht0对应了实际的物理网卡,在真实网络环境下,数据包的发送和接收都要通过eht0.如果计算机有多个网卡,则还可以有更多的网络接口,如eht1,eht2等等.调用命令ifconfig可以列出当前所有活跃的接口及相关的信息,在对eth0的描述中既有物理网卡的MAC地址,也有网络协议的IP地址.查看/proc/net/dev也可获得接口信息.
Libpcap中检查网络设备中主要使用到的函数关系如下图:
libpcap调用pcap_lookupdev()函数获得可用网络接口的设备名。首先利用函数 getifaddrs() 获得所有网络接口的地址,以及对应的网络掩码、广播地址、目标地址等相关信息,再利用 add_addr_to_iflist()、add_or_find_if()、get_instance() 把网络接口的信息增加到结构链表 pcap_if 中,最后从链表中提取第一个接口作为捕获设备。其中 get_instanced()的功能是从设备名开始,找第一个是数字的字符,做为接口的实例号。网络接口的设备号越小,则排在链表的越前面,因此,通常函数最后返回的设备名为 eth0。虽然 libpcap 可以工作在回路接口上,但显然 libpcap 开发者认为捕获本机进程之间的数据包没有多大意义。在检查网络设备操作中,主要用到的数据结构和代码如下:
/* libpcap 自定义的接口信息链表 [pcap.h] */
struct pcap_if
{
struct pcap_if *next;
char *name; /* 接口设备名 */
char *description; /* 接口描述 */
/*接口的 IP 地址, 地址掩码, 广播地址,目的地址 */
struct pcap_addr addresses;
bpf_u_int32 flags; /* 接口的参数 */
};
char * pcap_lookupdev(register char * errbuf)
{
pcap_if_t *alldevs;
……
pcap_findalldevs(&alldevs, errbuf);
……
strlcpy(device, alldevs->name, sizeof(device));
}
打开网络设备
当设备找到后,下一步工作就是打开设备以准备捕获数据包。Libpcap的包捕获是建立在具体的操作系统所提供的捕获机制上,而Linux系统随着版本的不同,所支持的捕获机制也有所不同。
2.0 及以前的内核版本使用一个特殊的socket类型SOCK_PACKET,调用形式是socket(PF_INET, SOCK_PACKET, int protocol),但 Linux 内核开发者明确指出这种方式已过时。Linux 在 2.2及以后的版本中提供了一种新的协议簇 PF_PACKET 来实现捕获机制。PF_PACKET 的调用形式为 socket(PF_PACKET, int socket_type, int protocol),其中socket类型可以是 SOCK_RAW和SOCK_DGRAM。SOCK_RAW 类型使得数据包从数据链路层取得后,不做任何修改直接传递给用户程序,而 SOCK_DRRAM 则要对数据包进行加工(cooked),把数据包的数据链路层头部去掉,而使用一个通用结构 sockaddr_ll 来保存链路信息。
使用 2.0 版本内核捕获数据包存在多个问题:首先,SOCK_PACKET 方式使用结构 sockaddr_pkt来保存数据链路层信息,但该结构缺乏包类型信息;其次,如果参数 MSG_TRUNC 传递给读包函数 recvmsg()、recv()、recvfrom() 等,则函数返回的数据包长度是实际读到的包数据长度,而不是数据包真正的长度。Libpcap 的开发者在源代码中明确建议不使用 2.0 版本进行捕获。
相对2.0版本SOCK_PACKET方式,2.2版本的PF_PACKET方式则不存在上述两个问题。在实际应用中,用户程序显然希望直接得到"原始"的数据包,因此使用 SOCK_RAW 类型最好。但在下面两种情况下,libpcap 不得不使用SOCK_DGRAM类型,从而也必须为数据包合成一个"伪"链路层头部(sockaddr_ll)。
某些类型的设备数据链路层头部不可用:例如 Linux 内核的 PPP 协议实现代码对 PPP 数据包头部的支持不可靠。
在捕获设备为"any"时:所有设备意味着libpcap对所有接口进行捕获,为了使包过滤机制能在所有类型的数据包上正常工作,要求所有的数据包有相同的数据链路头部。
打开网络设备的主函数是 pcap_open_live()[pcap-linux.c],其任务就是通过给定的接口设备名,获得一个捕获句柄:结构 pcap_t。pcap_t 是大多数libpcap函数都要用到的参数,其中最重要的属性则是上面讨论到的三种 socket方式中的某一种。首先我们看看pcap_t的具体构成。
struct pcap [pcap-int.h]
{
int fd; /* 文件描述字,实际就是 socket */
/* 在 socket 上,可以使用 select() 和 poll() 等 I/O 复用类型函数 */
int selectable_fd;
int snapshot; /* 用户期望的捕获数据包最大长度 */
int linktype; /* 设备类型 */
int tzoff; /* 时区位置,实际上没有被使用 */
int offset; /* 边界对齐偏移量 */
int break_loop; /* 强制从读数据包循环中跳出的标志 */
struct pcap_sf sf; /* 数据包保存到文件的相关配置数据结构 */
struct pcap_md md; /* 具体描述如下 */
int bufsize; /* 读缓冲区的长度 */
u_char buffer; /* 读缓冲区指针 */
u_char *bp;
int cc;
u_char *pkt;
/* 相关抽象操作的函数指针,最终指向特定操作系统的处理函数 */
int (*read_op)(pcap_t *, int cnt, pcap_handler, u_char *);
int (*setfilter_op)(pcap_t *, struct bpf_program *);
int (*set_datalink_op)(pcap_t *, int);
int (*getnonblock_op)(pcap_t *, char *);
int (*setnonblock_op)(pcap_t *, int, char *);
int (*stats_op)(pcap_t *, struct pcap_stat *);
void (*close_op)(pcap_t *);
/*如果 BPF 过滤代码不能在内核中执行,则将其保存并在用户空间执行 */
struct bpf_program fcode;
/* 函数调用出错信息缓冲区 */
char errbuf[PCAP_ERRBUF_SIZE + 1];
/* 当前设备支持的、可更改的数据链路类型的个数 */
int dlt_count;
/* 可更改的数据链路类型号链表,在 linux 下没有使用 */
int *dlt_list;
/* 数据包自定义头部,对数据包捕获时间、捕获长度、真实长度进行描述 [pcap.h] */
struct pcap_pkthdr pcap_header;
};
/* 包含了捕获句柄的接口、状态、过滤信息 [pcap-int.h] */
struct pcap_md {
/* 捕获状态结构 [pcap.h] */
struct pcap_stat stat;
int use_bpf; /* 如果为1,则代表使用内核过滤*/
u_long TotPkts;
u_long TotAccepted; /* 被接收数据包数目 */
u_long TotDrops; /* 被丢弃数据包数目 */
long TotMissed; /* 在过滤进行时被接口丢弃的数据包数目 */
long OrigMissed; /*在过滤进行前被接口丢弃的数据包数目*/
#ifdef linux
int sock_packet; /* 如果为 1,则代表使用 2.0 内核的 SOCK_PACKET 模式 */
int timeout; /* pcap_open_live() 函数超时返回时间*/
int clear_promisc; /* 关闭时设置接口为非混杂模式 */
int cooked; /* 使用 SOCK_DGRAM 类型 */
int lo_ifindex; /* 回路设备索引号 */
char *device; /* 接口设备名称 */
/* 以混杂模式打开 SOCK_PACKET 类型 socket 的 pcap_t 链表*/
struct pcap *next;
#endif
};
函数pcap_open_live()的调用形式是 pcap_t * pcap_open_live(const char *device, int snaplen, int promisc, int to_ms, char *ebuf),其中如果 device 为 NULL 或"any",则对所有接口捕获,snaplen 代表用户期望的捕获数据包最大长度,promisc 代表设置接口为混杂模式(捕获所有到达接口的数据包,但只有在设备给定的情况下有意义),to_ms 代表函数超时返回的时间。本函数的代码比较简单,其执行步骤如下:
* 为结构pcap_t分配空间并根据函数入参对其部分属性进行初试化。
* 分别利用函数 live_open_new() 或 live_open_old() 尝试创建 PF_PACKET 方式或 SOCK_PACKET 方式的socket,注意函数名中一个为"new",另一个为"old"。 * 根据 socket 的方式,设置捕获句柄的读缓冲区长度,并分配空间。 * 为捕获句柄pcap_t设置linux系统下的特定函数,其中最重要的是读数据包函数和设置过滤器函数。(注意到这种从抽象模式到具体模式的设计思想在 linux 源代码中也多次出现,如VFS文件系统) handle->read_op = pcap_read_linux; handle->setfilter_op = pcap_setfilter_linux;下面我们依次分析 2.2 和 2.0 内核版本下的socket创建函数。
static int
live_open_new(pcap_t *handle, const char *device, int promisc,
int to_ms, char *ebuf)
{
/* 如果设备给定,则打开一个 RAW 类型的套接字,否则,打开 DGRAM 类型的套接字 */
sock_fd = device ?
socket(PF_PACKET, SOCK_RAW, htons(ETH_P_ALL))
: socket(PF_PACKET, SOCK_DGRAM, htons(ETH_P_ALL));
/* 取得回路设备接口的索引 */
handle->md.lo_ifindex = iface_get_id(sock_fd, "lo", ebuf);
/* 如果设备给定,但接口类型未知或是某些必须工作在加工模式下的特定类型,则使用加工模式 */
if (device) {
/* 取得接口的硬件类型 */
arptype = iface_get_arptype(sock_fd, device, ebuf);
/* linux 使用 ARPHRD_xxx 标识接口的硬件类型,而 libpcap 使用DLT_xxx
来标识。本函数是对上述二者的做映射变换,设置句柄的链路层类型为
DLT_xxx,并设置句柄的偏移量为合适的值,使其与链路层头部之和为 4 的倍数,目的是边界对齐 */
map_arphrd_to_dlt(handle, arptype, 1);
/* 如果接口是前面谈到的不支持链路层头部的类型,则退而求其次,使用 SOCK_DGRAM 模式 */
if (handle->linktype == xxx)
{
close(sock_fd);
sock_fd = socket(PF_PACKET, SOCK_DGRAM, htons(ETH_P_ALL));
}
/* 获得给定的设备名的索引 */
device_id = iface_get_id(sock_fd, device, ebuf);
/* 把套接字和给定的设备绑定,意味着只从给定的设备上捕获数据包 */
iface_bind(sock_fd, device_id, ebuf);
} else { /* 现在是加工模式 */
handle->md.cooked = 1;
/* 数据包链路层头部为结构 sockaddr_ll, SLL 大概是结构名称的简写形式 */
handle->linktype = DLT_LINUX_SLL;
device_id = -1;
}
/* 设置给定设备为混杂模式 */
if (device && promisc)
{
memset(&mr, 0, sizeof(mr));
mr.mr_ifindex = device_id;
mr.mr_type = PACKET_MR_PROMISC;
setsockopt(sock_fd, SOL_PACKET, PACKET_ADD_MEMBERSHIP,
&mr, sizeof(mr));
}
/* 最后把创建的 socket 保存在句柄 pcap_t 中 */
handle->fd = sock_fd;
}
/* 2.0 内核下函数要简单的多,因为只有唯一的一种 socket 方式 */
static int
live_open_old(pcap_t *handle, const char *device, int promisc,
int to_ms, char *ebuf)
{
/* 首先创建一个SOCK_PACKET类型的 socket */
handle->fd = socket(PF_INET, SOCK_PACKET, htons(ETH_P_ALL));
/* 2.0 内核下,不支持捕获所有接口,设备必须给定 */
if (!device) {
strncpy(ebuf,
"pcap_open_live: The \"any\" device isn't
supported on 2.0[.x]-kernel systems",
PCAP_ERRBUF_SIZE);
break;
}
/* 把 socket 和给定的设备绑定 */
iface_bind_old(handle->fd, device, ebuf);
/*以下的处理和 2.2 版本下的相似,有所区别的是如果接口链路层类型未知,则 libpcap 直接退出 */
arptype = iface_get_arptype(handle->fd, device, ebuf);
map_arphrd_to_dlt(handle, arptype, 0);
if (handle->linktype == -1) {
snprintf(ebuf, PCAP_ERRBUF_SIZE, "unknown arptype %d", arptype);
break;
}
/* 设置给定设备为混杂模式 */
if (promisc) {
memset(&ifr, 0, sizeof(ifr));
strncpy(ifr.ifr_name, device, sizeof(ifr.ifr_name));
ioctl(handle->fd, SIOCGIFFLAGS, &ifr);
ifr.ifr_flags |= IFF_PROMISC;
ioctl(handle->fd, SIOCSIFFLAGS, &ifr);
}
}
比较上面两个函数的代码,还有两个细节上的区别。首先是 socket 与接口绑定所使用的结构:老式的绑定使用了结构 sockaddr,而新式的则使用了 2.2 内核中定义的通用链路头部层结构sockaddr_ll。
iface_bind_old(int fd, const char *device, char *ebuf)
{
struct sockaddr saddr;
memset(&saddr, 0, sizeof(saddr));
strncpy(saddr.sa_data, device, sizeof(saddr.sa_data));
bind(fd, &saddr, sizeof(saddr));
}
iface_bind(int fd, int ifindex, char *ebuf)
{
struct sockaddr_ll sll;
memset(&sll, 0, sizeof(sll));
sll.sll_family = AF_PACKET;
sll.sll_ifindex = ifindex;
sll.sll_protocol = htons(ETH_P_ALL);
bind(fd, (struct sockaddr *) &sll, sizeof(sll);
}
第二个是在 2.2 版本中设置设备为混杂模式时,使用了函数 setsockopt(),以及新的标志 PACKET_ADD_MEMBERSHIP 和结构 packet_mreq。我估计这种方式主要是希望提供一个统一的调用接口,以代替传统的(混乱的)ioctl 调用。
struct packet_mreq
{
int mr_ifindex; /* 接口索引号 */
unsigned short mr_type; /* 要执行的操作(号) */
unsigned short mr_alen; /* 地址长度 */
unsigned char mr_address[8]; /* 物理层地址 */
};
第二个是在 2.2 版本中设置设备为混杂模式时,使用了函数 setsockopt(),以及新的标志 PACKET_ADD_MEMBERSHIP 和结构 packet_mreq。我估计这种方式主要是希望提供一个统一的调用接口,以代替传统的(混乱的)ioctl 调用。
struct packet_mreq
{
int mr_ifindex; /* 接口索引号 */
unsigned short mr_type; /* 要执行的操作(号) */
unsigned short mr_alen; /* 地址长度 */
unsigned char mr_address[8]; /* 物理层地址 */
};
用户应用程序接口
Libpcap 提供的用户程序接口比较简单,通过反复调用函数pcap_next()[pcap.c]则可获得捕获到的数据包。下面是一些使用到的数据结构:
/* 单个数据包结构,包含数据包元信息和数据信息 */
struct singleton [pcap.c]
{
struct pcap_pkthdr hdr; /* libpcap 自定义数据包头部 */
const u_char * pkt; /* 指向捕获到的网络数据 */
};
/* 自定义头部在把数据包保存到文件中也被使用 */
struct pcap_pkthdr
{
struct timeval ts; /* 捕获时间戳 */
bpf_u_int32 caplen; /* 捕获到数据包的长度 */
bpf_u_int32 len; /* 数据包的真正长度 */
}
/* 函数 pcap_next() 实际上是对函数 pcap_dispatch()[pcap.c] 的一个包装 */
const u_char * pcap_next(pcap_t *p, struct pcap_pkthdr *h)
{
struct singleton s;
s.hdr = h;
/*入参"1"代表收到1个数据包就返回;回调函数 pcap_oneshot() 是对结构 singleton 的属性赋值 */
if (pcap_dispatch(p, 1, pcap_oneshot, (u_char*)&s) read_op(p, cnt, callback, user)。在 linux 系统下,对应的读函数为 pcap_read_linux()(在创建捕获句柄时已定义 [pcap-linux.c]),而pcap_read_linux() 则是直接调用 pcap_read_packet()([pcap-linux.c])。
pcap_read_packet() 的中心任务是利用了 recvfrom() 从已创建的 socket 上读数据包数据,但是考虑到 socket 可能为前面讨论到的三种方式中的某一种,因此对数据缓冲区的结构有相应的处理,主要表现在加工模式下对伪链路层头部的合成。具体代码分析如下:
static int
pcap_read_packet(pcap_t *handle, pcap_handler callback, u_char *userdata)
{
/* 数据包缓冲区指针 */
u_char * bp;
/* bp 与捕获句柄 pcap_t 中 handle->buffer
之间的偏移量,其目的是为在加工模式捕获情况下,为合成的伪数据链路层头部留出空间 */
int offset;
/* PACKET_SOCKET 方式下,recvfrom() 返回 scokaddr_ll 类型,而在SOCK_PACKET 方式下,
返回 sockaddr 类型 */
#ifdef HAVE_PF_PACKET_SOCKETS
struct sockaddr_ll from;
struct sll_header * hdrp;
#else
struct sockaddr from;
#endif
socklen_t fromlen;
int packet_len, caplen;
/* libpcap 自定义的头部 */
struct pcap_pkthdr pcap_header;
#ifdef HAVE_PF_PACKET_SOCKETS
/* 如果是加工模式,则为合成的链路层头部留出空间 */
if (handle->md.cooked)
offset = SLL_HDR_LEN;
/* 其它两中方式下,链路层头部不做修改的被返回,不需要留空间 */
else
offset = 0;
#else
offset = 0;
#endif
bp = handle->buffer + handle->offset;
/* 从内核中接收一个数据包,注意函数入参中对 bp 的位置进行修正 */
packet_len = recvfrom( handle->fd, bp + offset,
handle->bufsize - offset, MSG_TRUNC,
(struct sockaddr *) &from, &fromlen);
#ifdef HAVE_PF_PACKET_SOCKETS
/* 如果是回路设备,则只捕获接收的数据包,而拒绝发送的数据包。显然,我们只能在 PF_PACKET
方式下这样做,因为 SOCK_PACKET 方式下返回的链路层地址类型为
sockaddr_pkt,缺少了判断数据包类型的信息。*/
if (!handle->md.sock_packet &&
from.sll_ifindex == handle->md.lo_ifindex &&
from.sll_pkttype == PACKET_OUTGOING)
return 0;
#endif
#ifdef HAVE_PF_PACKET_SOCKETS
/* 如果是加工模式,则合成伪链路层头部 */
if (handle->md.cooked) {
/* 首先修正捕包数据的长度,加上链路层头部的长度 */
packet_len += SLL_HDR_LEN;
hdrp = (struct sll_header *)bp;
/* 以下的代码分别对伪链路层头部的数据赋值 */
hdrp->sll_pkttype = xxx;
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;
}
#endif
/* 修正捕获的数据包的长度,根据前面的讨论,SOCK_PACKET 方式下长度可能是不准确的 */
caplen = packet_len;
if (caplen > handle->snapshot)
caplen = handle->snapshot;
/* 如果没有使用内核级的包过滤,则在用户空间进行过滤*/
if (!handle->md.use_bpf && handle->fcode.bf_insns) {
if (bpf_filter(handle->fcode.bf_insns, bp,
packet_len, caplen) == 0)
{
/* 没有通过过滤,数据包被丢弃 */
return 0;
}
}
/* 填充 libpcap 自定义数据包头部数据:捕获时间,捕获的长度,真实的长度 */
ioctl(handle->fd, SIOCGSTAMP, &pcap_header.ts);
pcap_header.caplen = caplen;
pcap_header.len = packet_len;
/* 累加捕获数据包数目,注意到在不同内核/捕获方式情况下数目可能不准确 */
handle->md.stat.ps_recv++;
/* 调用用户定义的回调函数 */
callback(userdata, &pcap_header, bp);
}
数据包过滤机制
大量的网络监控程序目的不同,期望的数据包类型也不同,但绝大多数情况都都只需要所有数据包的一(小)部分。例如:对邮件系统进行监控可能只需要端口号为 25(smtp)和 110(pop3) 的 TCP 数据包,对 DNS 系统进行监控就只需要端口号为 53 的 UDP数据包。包过滤机制的引入就是为了解决上述问题,用户程序只需简单的设置一系列过滤条件,最终便能获得满足条件的数据包。包过滤操作可以在用户空间执行,也可以在内核空间执行,但必须注意到数据包从内核空间拷贝到用户空间的开销很大,所以如果能在内核空间进行过滤,会极大的提高捕获的效率。内核过滤的优势在低速网络下表现不明显,但在高速网络下是非常突出的。在理论研究和实际应用中,包捕获和包过滤从语意上并没有严格的区分,关键在于认识到捕获数据包必然有过滤操作。基本上可以认为,包过滤机制在包捕获机制中占中心地位。
包过滤机制实际上是针对数据包的布尔值操作函数,如果函数最终返回true,则通过过滤,反之则被丢弃。形式上包过滤由一个或多个谓词判断的并操作(AND)和或操作(OR)构成,每一个谓词判断基本上对应了数据包的协议类型或某个特定值,例如:只需要 TCP 类型且端口为110的数据包或ARP类型的数据包。包过滤机制在具体的实现上与数据包的协议类型并无多少关系,它只是把数据包简单的看成一个字节数组,而谓词判断会根据具体的协议映射到数组特定位置的值。如判断ARP类型数据包,只需要判断数组中第 13、14 个字节(以太头中的数据包类型)是否为0X0806。从理论研究的意思上看,包过滤机制是一个数学问题,或者说是一个算法问题,其中心任务是如何使用最少的判断操作、最少的时间完成过滤处理,提高过滤效率。
BPF
Libpcap 重点使用 BPF(BSD Packet Filter)包过滤机制,BPF 于 1992 年被设计出来,其设计目的主要是解决当时已存在的过滤机制效率低下的问题。BPF的工作步骤如下:当一个数据包到达网络接口时,数据链路层的驱动会把它向系统的协议栈传送。但如果 BPF 监听接口,驱动首先调用 BPF。BPF 首先进行过滤操作,然后把数据包存放在过滤器相关的缓冲区中,最后设备驱动再次获得控制。注意到BPF是先对数据包过滤再缓冲,避免了类似sun的NIT 过滤机制先缓冲每个数据包直到用户读数据时再过滤所造成的效率问题。参考资料D是关于BPF设计思想最重要的文献。
BPF 的设计思想和当时的计算机硬件的发展有很大联系,相对老式的过滤方式CSPF(CMU/Stanford Packet Filter)它有两大特点。1:基于寄存器的过滤机制,而不是早期内存堆栈过滤机制,2:直接使用独立的、非共享的内存缓冲区。同时,BPF 在过滤算法是也有很大进步,它使用无环控制流图(CFG control flow graph),而不是老式的布尔表达式树(boolean expression tree)。布尔表达式树理解上比较直观,它的每一个叶子节点即是一个谓词判断,而非叶子节点则为 AND 操作或 OR操作。CSPF有三个主要的缺点。1:过滤操作使用的栈在内存中被模拟,维护栈指针需要使用若干的加/减等操作,而内存操作是现代计算机架构的主要瓶颈。2:布尔表达式树造成了不需要的重复计算。3:不能分析数据包的变长头部。BPF 使用的CFG 算法实际上是一种特殊的状态机,每一节点代表了一个谓词判断,而左右边分别对应了判断失败和成功后的跳转,跳转后又是谓词判断,这样反复操作,直到到达成功或失败的终点。CFG算法的优点在于把对数据包的分析信息直接建立在图中,从而不需要重复计算。直观的看,CFG 是一种"快速的、一直向前"的算法。
过滤代码的编译
BPF 对 CFG 算法的代码实现非常复杂,它使用伪机器方式。BPF 伪机器是一个轻量级的,高效的状态机,对 BPF 过滤代码进行解释处理。BPF 过滤代码形式为"opcode jt jfk",分别代表了操作码和寻址方式、判断正确的跳转、判断失败的跳转、操作使用的通用数据域。BPF 过滤代码从逻辑上看很类似于汇编语言,但它实际上是机器语言,注意到上述 4 个域的数据类型都是 int 和 char 型。显然,由用户来写过滤代码太过复杂,因此 libpcap 允许用户书写高层的、容易理解的过滤字符串,然后将其编译为BPF代码。
Libpcap使用了4个源程序gencode.c、optimize.c、grammar.c、scanner.c完成编译操作,其中前两个实现了对过滤字符串的编译和优化,后两个主要是为编译提供从协议相关过滤条件到协议无关(的字符数组)位置信息的映射,并且它们由词汇分析器生成器 flex 和 bison 生成。参考资料 C 有对此两个工具的讲解。
flex -Ppcap_ -t scanner.l > $$.scanner.c; mv $$.scanner.c scanner.c
bison -y -p pcap_ -d grammar.y
mv y.tab.c grammar.c
mv y.tab.h tokdefs.h
编译过滤字符串调用了函数 pcap_compile()[getcode.c],形式为:
int pcap_compile(pcap_t *p, struct bpf_program *program,
char *buf, int optimize, bpf_u_int32 mask)
其中 buf 指向用户过滤字符串,编译后的 BPF 代码存在在结构 bpf_program中,标志 optimize 指示是否对 BPF 代码进行优化。
/* [pcap-bpf.h] */
struct bpf_program {
u_int bf_len; /* BPF 代码中谓词判断指令的数目 */
struct bpf_insn *bf_insns; /* 第一个谓词判断指令 */
};
/* 谓词判断指令结构,含意在前面已描述 [pcap-bpf.h] */
struct bpf_insn {
u_short code;
u_char jt;
u_char jf;
bpf_int32 k;
};
过滤代码的安装
前面我们曾经提到,在内核空间过滤数据包对整个捕获机制的效率是至关重要的。早期使用 SOCK_PACKET 方式的 Linux 不支持内核过滤,因此过滤操作只能在用户空间执行(请参阅函数 pcap_read_packet() 代码),在《UNIX 网络编程(第一卷)》(参考资料 B)的第 26 章中对此有明确的描述。不过现在看起来情况已经发生改变,linux 在 PF_PACKET 类型的 socket 上支持内核过滤。Linux 内核允许我们把一个名为 LPF(Linux Packet Filter) 的过滤器直接放到 PF_PACKET 类型 socket 的处理过程中,过滤器在网卡接收中断执行后立即执行。LSF 基于BPF机制,但两者在实现上有略微的不同。实际代码如下:
/* 在包捕获设备上附加 BPF 代码 [pcap-linux.c]*/
static int
pcap_setfilter_linux(pcap_t *handle, struct bpf_program *filter)
{
#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",
sizeof(handle->errbuf));
return -1;
}
/* 具体描述如下 */
if (install_bpf_program(handle, filter) md.use_bpf = 0;
/* 尝试在内核安装过滤器 */
#ifdef SO_ATTACH_FILTER
#ifdef USHRT_MAX
if (handle->fcode.bf_len > USHRT_MAX) {
/*过滤器代码太长,内核不支持 */
fprintf(stderr, "Warning: Filter too complex for kernel\n");
fcode.filter = NULL;
can_filter_in_kernel = 0;
} else
#endif /* USHRT_MAX */
{
/* linux 内核设置过滤器时使用的数据结构是 sock_fprog,
而不是 BPF 的结构 bpf_program ,因此应做结构之间的转换 */
switch (fix_program(handle, &fcode)) {
/* 严重错误,直接退出 */
case -1:
default:
return -1;
/* 通过检查,但不能工作在内核中 */
case 0:
can_filter_in_kernel = 0;
break;
/* BPF 可以在内核中工作 */
case 1:
can_filter_in_kernel = 1;
break;
}
}
/* 如果可以在内核中过滤,则安装过滤器到内核中 */
if (can_filter_in_kernel) {
if ((err = set_kernel_filter(handle, &fcode)) == 0)
{
/* 安装成功 !!! */
handle->md.use_bpf = 1;
}
else if (err == -1) /* 出现非致命性错误 */
{
if (errno != ENOPROTOOPT && errno != EOPNOTSUPP) {
fprintf(stderr, "Warning: Kernel filter failed:
%s\n",pcap_strerror(errno));
}
}
}
/* 如果不能在内核中使用过滤器,则去掉曾经可能在此 socket
上安装的内核过滤器。主要目的是为了避免存在的过滤器对数据包过滤的干扰 */
if (!handle->md.use_bpf)
reset_kernel_filter(handle);[pcap-linux.c]
#endif
}
/* 把 BPF 代码拷贝到 pcap_t 数据结构的 fcode 上 */
int install_bpf_program(pcap_t *p, struct bpf_program *fp)
{
size_t prog_size;
/* 首先释放可能已存在的 BPF 代码 */
pcap_freecode(&p->fcode);
/* 计算过滤代码的长度,分配内存空间 */
prog_size = sizeof(*fp->bf_insns) * fp->bf_len;
p->fcode.bf_len = fp->bf_len;
p->fcode.bf_insns = (struct bpf_insn *)malloc(prog_size);
if (p->fcode.bf_insns == NULL) {
snprintf(p->errbuf, sizeof(p->errbuf),
"malloc: %s", pcap_strerror(errno));
return (-1);
}
/* 把过滤代码保存在捕获句柄中 */
memcpy(p->fcode.bf_insns, fp->bf_insns, prog_size);
return (0);
}
/* 在内核中安装过滤器 */
static int set_kernel_filter(pcap_t *handle, struct sock_fprog *fcode)
{
int total_filter_on = 0;
int save_mode;
int ret;
int save_errno;
/*在设置过滤器前,socket 的数据包接收队列中可能已存在若干数据包。当设置过滤器后,
这些数据包极有可能不满足过滤条件,但它们不被过滤器丢弃。
这意味着,传递到用户空间的头几个数据包不满足过滤条件。
注意到在用户空间过滤这不是问题,因为用户空间的过滤器是在包进入队列后执行的。
Libpcap 解决这个问题的方法是在设置过滤器之前,
首先读完接收队列中所有的数据包。具体步骤如下。*/
/*为了避免无限循环的情况发生(反复的读数据包并丢弃,
但新的数据包不停的到达),首先设置一个过滤器,阻止所有的包进入 */
setsockopt(handle->fd, SOL_SOCKET, SO_ATTACH_FILTER,
&total_fcode, sizeof(total_fcode);
/* 保存 socket 当前的属性 */
save_mode = fcntl(handle->fd, F_GETFL, 0);
/* 设置 socket 它为非阻塞模式 */
fcntl(handle->fd, F_SETFL, save_mode | O_NONBLOCK);
/* 反复读队列中的数据包,直到没有数据包可读。这意味着接收队列已被清空 */
while (recv(handle->fd, &drain, sizeof drain, MSG_TRUNC) >= 0);
/* 恢复曾保存的 socket 属性 */
fcntl(handle->fd, F_SETFL, save_mode);
/* 现在安装新的过滤器 */
setsockopt(handle->fd, SOL_SOCKET, SO_ATTACH_FILTER,
fcode, sizeof(*fcode));
}
/* 释放 socket 上可能有的内核过滤器 */
static int reset_kernel_filter(pcap_t *handle)
{
int dummy;
return setsockopt(handle->fd, SOL_SOCKET, SO_DETACH_FILTER,
&dummy, sizeof(dummy));
}
linux 在安装和卸载过滤器时都使用了函数 setsockopt(),其中标志SOL_SOCKET 代表了对 socket 进行设置,而 SO_ATTACH_FILTER 和 SO_DETACH_FILTER 则分别对应了安装和卸载。下面是 linux 2.4.29 版本中的相关代码:
[net/core/sock.c]
#ifdef CONFIG_FILTER
case SO_ATTACH_FILTER:
……
/* 把过滤条件结构从用户空间拷贝到内核空间 */
if (copy_from_user(&fprog, optval, sizeof(fprog)))
break;
/* 在 socket 上安装过滤器 */
ret = sk_attach_filter(&fprog, sk);
……
case SO_DETACH_FILTER:
/* 使用自旋锁锁住 socket */
spin_lock_bh(&sk->lock.slock);
filter = sk->filter;
/* 如果在 socket 上有过滤器,则简单设置为空,并释放过滤器内存 */
if (filter) {
sk->filter = NULL;
spin_unlock_bh(&sk->lock.slock);
sk_filter_release(sk, filter);
break;
}
spin_unlock_bh(&sk->lock.slock);
ret = -ENONET;
break;
#endif
上面出现的 sk_attach_filter() 定义在 net/core/filter.c,它把结构sock_fprog 转换为结构 sk_filter, 最后把此结构设置为 socket 的过滤器:sk->filter = fp。
其他代码
libpcap 还提供了其它若干函数,但基本上是提供辅助或扩展功能,重要性相对弱一点。我个人认为,函数 pcap_dump_open() 和 pcap_open_offline() 可能比较有用,使用它们能把在线的数据包写入文件并事后进行分析处理。
总结
1994 年libpcap 的第一个版本被发布,到现在已有 11 年的历史,如今libpcap 被广泛的应用在各种网络监控软件中。Libpcap 最主要的优点在于平台无关性,用户程序几乎不需做任何改动就可移植到其它 unix 平台上;其次,libpcap也能适应各种过滤机制,特别对BPF的支持最好。分析它的源代码,可以学习开发者优秀的设计思想和实现技巧,也能了解到(linux)操作系统的网络内核实现,对个人能力的提高有很大帮助。 -
libpcap源码分析——pcap_open_live
2019-12-26 16:16:34libpcap是跨平台网络数据包捕获函数库... 以下分析源码时只列出核心逻辑 API: pcap_open_live 描述: 针对指定的网络接口创建一个捕获句柄,用于后续捕获数据 实现逻辑分析: @device- 指定网络接口名,比如"eth0"...libpcap是跨平台网络数据包捕获函数库:
注: 以下分析都基于libpcap-1.8.1版本进行
以下分析按照库的核心API为线索展开
以下分析源码时只列出核心逻辑API: pcap_open_live
描述: 针对指定的网络接口创建一个捕获句柄,用于后续捕获数据
实现逻辑分析:
@device - 指定网络接口名,比如"eth0"。如果传入NULL或"any",则意味着对所有接口进行捕获
@snaplen - 设置每个数据包的捕捉长度,上限MAXIMUM_SNAPLEN
@promisc - 是否打开混杂模式
@to_ms - 设置获取数据包时的超时时间(ms)
备注:to_ms值会影响3个捕获函数(pcap_next、pcap_loop、pcap_dispatch)的行为
pcap_t *pcap_open_live(const char *device, int snaplen, int promisc, int to_ms, char *errbuf) { pcap_t *p; // 基于指定的设备接口创建一个pcap句柄 p = pcap_create(device, errbuf); // 设置最大捕获包的长度 status = pcap_set_snaplen(p, snaplen); // 设置数据包的捕获模式 status = pcap_set_promisc(p, promisc); // 设置执行捕获操作的持续时间 status = pcap_set_timeout(p, to_ms); // 使指定pcap句柄进入活动状态,这里实际包含了创建捕获套接字的动作 status = pcap_activate(p); return p; } pcap_t *pcap_create(const char *device, char *errbuf) { pcap_t *p; char *device_str; // 转储传入的设备名,如果传入NULL,则设置为"any" if (device == NULL) device_str = strdup("any"); else device_str = strdup(device); // 创建一个普通网络接口类型的pcap句柄 p = pcap_create_interface(device_str, errbuf); p->opt.device = device_str; return p; } pcap_t *pcap_create_interface(const char *device, char *ebuf) { pcap_t *handle; // 创建并初始化一个包含私有空间struct pcap_linux的pcap句柄 handle = pcap_create_common(ebuf, sizeof (struct pcap_linux)); // 在刚创建了该pcap句柄后,这里首先覆盖了2个回调函数 handle->activate_op = pcap_activate_linux; handle->can_set_rfmon_op = pcap_can_set_rfmon_linux; } pcap_t *pcap_create_common(char *ebuf, size_t size) { pcap_t *p; // 申请一片连续内存,用作包含size长度私有空间的pcap句柄,其中私有空间紧跟在该pcap结构后 p = pcap_alloc_pcap_t(ebuf, size); // 为新建的pcap句柄注册一系列缺省的回调函数,这些缺省的回调函数大部分会在后面覆盖为linux下对应回调函数 p->can_set_rfmon_op = pcap_cant_set_rfmon; initialize_ops(p); return p; } int pcap_set_snaplen(pcap_t *p, int snaplen) { // 设置该pcap句柄捕获包的最大长度前,需要确保当前并未处于活动状态 if (pcap_check_activated(p)) return (PCAP_ERROR_ACTIVATED); // 如果传入了无效的最大包长,则会设置为缺省值 if (snaplen <= 0 || snaplen > MAXIMUM_SNAPLEN) snaplen = MAXIMUM_SNAPLEN; p->snapshot = snaplen; } int pcap_set_promisc(pcap_t *p, int promisc) { // 设置该pcap句柄关联接口的数据包捕获模式前,需要确保当前并未处于活动状态 if (pcap_check_activated(p)) return (PCAP_ERROR_ACTIVATED); p->opt.promisc = promisc; } int pcap_set_timeout(pcap_t *p, int timeout_ms) { // 设置该pcap句柄执行捕获操作的持续时间前,需要确保当前并未处于活动状态 if (pcap_check_activated(p)) return (PCAP_ERROR_ACTIVATED); p->opt.timeout = timeout_ms; } int pcap_activate(pcap_t *p) { int status; // 确保没有进行重复激活 if (pcap_check_activated(p)) return (PCAP_ERROR_ACTIVATED); // 调用事先注册的activate_op方法,完成对该pcap句柄的激活,这个过程中会创建用于捕获的套接字,以及尝试开启PACKET_MMAP机制 status = p->activate_op(p); return status; } int pcap_activate_linux(pcap_t *handle) { int status; // 获取该pcap句柄的私有空间 struct pcap_linux *handlep = handle->priv; device = handle->opt.device; // 为该pcap句柄注册linux平台相关的一系列回调函数(linux平台的回调函数又分为2组,这里缺省注册了一组不使用PACKET_MMAP机制的回调) handle->inject_op = pcap_inject_linux; handle->setfilter_op = pcap_setfilter_linux; handle->setdirection_op = pcap_setdirection_linux; handle->set_datalink_op = pcap_set_datalink_linux; handle->getnonblock_op = pcap_getnonblock_fd; handle->setnonblock_op = pcap_setnonblock_fd; handle->cleanup_op = pcap_cleanup_linux; handle->read_op = pcap_read_linux; handle->stats_op = pcap_stats_linux; // "any"设备不支持混杂模式 if (strcmp(device, "any") == 0) { if (handle->opt.promisc) handle->opt.promisc = 0; } handlep->device = strdup(device); handlep->timeout = handle->opt.timeout; // 开启混杂模式的接口,需要先从/proc/net/dev中获取该接口当前"drop"报文数量 if (handle->opt.promisc) handlep->proc_dropped = linux_if_drops(handlep->device); /* 创建用于捕获接口收到的原始报文的套接字 * 备注:旧版本的kernel使用SOCK_PACKET类型套接字来实现对原始报文的捕获,这种过时的方式不再展开分析 * 较新的kernel使用PF_PACKET来实现该功能 */ ret = activate_new(handle); // 这里只分析成功使用PF_PACKET创建套接字的情况 if (ret == 1) { /* 尝试对新创建的套接字开启PACKET_MMAP功能 * 备注:旧版本的kernel不支持开启PACKET_MMAP功能,所以只能作为普通的原始套接字使用 * 较新版本的kernel逐渐开始支持v1、v2、v3版本的PACKET_MMAP,这里将会尝试开启当前系统支持的最高版本PACKET_MMAP */ switch (activate_mmap(handle, &status)) { case 1: // 返回1意味着成功开启PACKET_MMAP功能,这里是为poll选择一个合适的超时时间 set_poll_timeout(handlep); return status; case 0: // 返回0意味着kernel不支持PACKET_MMAP break; } } /* 程序运行到这里只有2种可能: * 通过新式的PF_PACKET创建了套接字,但不支持PACKET_MMAP特性时 * 通过老式的SOCKET_PACKET创建了套接字之后 */ // 如果配置了套接字接收缓冲区长度,就在这里进行设置 if (handle->opt.buffer_size != 0) { setsockopt(handle->fd, SOL_SOCKET, SO_RCVBUF,&handle->opt.buffer_size,sizeof(handle->opt.buffer_size)); } // 不开启PACKET_MMAP的情况下,就在这里分配用户空间接收缓冲区 handle->buffer = malloc(handle->bufsize + handle->offset); handle->selectable_fd = handle->fd; } int activate_new(pcap_t *handle) { struct pcap_linux *handlep = handle->priv; const char *device = handle->opt.device; int is_any_device = (strcmp(device, "any") == 0); struct packet_mreq mr; // 如果是名为"any"的接口,则创建SOCK_DGRAM类型的套接字;通常情况下都是创建SOCK_RAW类型的套接字 sock_fd = is_any_device ? socket(PF_PACKET, SOCK_DGRAM, htons(ETH_P_ALL)) : socket(PF_PACKET, SOCK_RAW, htons(ETH_P_ALL)); // 记录下环回接口的序号 handlep->lo_ifindex = iface_get_id(sock_fd, "lo", handle->errbuf); handle->offset = 0; // 对于接口名不是"any"的接口,如果其接口类型未定义或者属于一种不支持工作在raw模式下的接口,这些接口仍旧要回退到cooked模式 if (!is_any_device) { // 获取该接口的硬件类型,linux中专门用ARPHRD_*来标识设备接口类型 arptype = iface_get_arptype(sock_fd, device, handle->errbuf); /* pcap中使用DLT_*来标识设备接口,所以这里就是将ARPHRD_*映射成对应的DLT_* * 除此之外,还会根据接口类型修改offset,从而确保 offset + 2层头长度 实现4字节对齐 */ map_arphrd_to_dlt(handle, sock_fd, arptype, device, 1); // 符合以下情况的都需要回退到cooked模式 if (handle->linktype == -1 || handle->linktype == DLT_LINUX_SLL || handle->linktype == DLT_LINUX_IRDA || handle->linktype == DLT_LINUX_LAPD || handle->linktype == DLT_NETLINK || (handle->linktype == DLT_EN10MB && (strncmp("isdn", device, 4) == 0 || strncmp("isdY", device, 4) == 0))) { close(sock_fd); sock_fd = socket(PF_PACKET, SOCK_DGRAM,htons(ETH_P_ALL)); handlep->cooked = 1; } // 获取该接口的序号 handlep->ifindex = iface_get_id(sock_fd, device,handle->errbuf); // 将创建的套接字绑定到该设备接口上 iface_bind(sock_fd, handlep->ifindex,handle->errbuf); } else { // 对于接口名为"any"的接口,直接将其设置为cooked模式 handlep->cooked = 1; handle->linktype = DLT_LINUX_SLL; // 接口名为"any"的接口只是一个泛指,实际不存在这个接口,所以也不进行绑定 handlep->ifindex = -1; } // 在非"any"设备接口上开启混杂模式 if (!is_any_device && handle->opt.promisc) { memset(&mr, 0, sizeof(mr)); mr.mr_ifindex = handlep->ifindex; mr.mr_type = PACKET_MR_PROMISC; setsockopt(sock_fd, SOL_PACKET, PACKET_ADD_MEMBERSHIP,&mr, sizeof(mr); } /* 使能对辅助数据的支持,辅助数据主要就是报文的vlan头信息,同时将offset增加vlan标签字段长 * 备注:后续如果启用了PACKET_MMAP V3机制,就不需要在这里启用该功能了 */ int val = 1; setsockopt(sock_fd, SOL_PACKET, PACKET_AUXDATA, &val,sizeof(val)); handle->offset += VLAN_TAG_LEN; // 加工模式下必须确保最大包的长度不小于 SLL_HDR_LEN + 1 if (handlep->cooked) if (handle->snapshot < SLL_HDR_LEN + 1) handle->snapshot = SLL_HDR_LEN + 1; handle->bufsize = handle->snapshot; // 设置vlan标签的偏移量 switch (handle->linktype) { case DLT_EN10MB: // 普通以太网设备VLAN标签位于目的mac和源mac之后位置 handlep->vlan_offset = 2 * ETH_ALEN; break; case DLT_LINUX_SLL: // cooked模式下的设备VLAN标签记录在sll_header->sll_protocol字段 handlep->vlan_offset = SLL_HDR_LEN - 2; break; } // 配置该pcap句柄的时间戳精度 if (handle->opt.tstamp_precision == PCAP_TSTAMP_PRECISION_NANO) { int nsec_tstamps = 1; setsockopt(sock_fd, SOL_SOCKET, SO_TIMESTAMPNS, &nsec_tstamps, sizeof(nsec_tstamps)); } handle->fd = sock_fd; return 1; }
相关数据结构:
// 对一个接口执行捕获操作的句柄结构 struct pcap { read_op_t read_op; // 在该接口上进行读操作的回调函数(linux上就是 pcap_read_linux / pcap_read_linux_mmap_v3) int fd; // 该接口关联的套接字 int selectable_fd; // 通常就是fd u_int bufsize; // 接收缓冲区的有效大小,该值初始时来自用户配置的snapshot,当开启PACKET_MMAP时,跟配置的接收环形缓冲区tp_frame_size值同步 void *buffer; /* 当开启PACKET_MMAP时,指向一个成员为union thdr结构的数组,记录了接收环形缓冲区中每个帧的帧头; * 当不支持PACKET_MMAP时,指向用户空间的接收缓冲区,其大小为 bufsize + offset */ int cc; // 跟配置的接收环形缓冲区tp_frame_nr值同步(由于pcap中内存块数量和帧数量相等,所以本字段也就是内存块数量) int break_loop; // 标识是否强制退出循环捕获 void *priv; // 指向该pcap句柄的私有空间(紧跟在本pcap结构后),linux下就是struct pcap_linux struct pcap *next; // 这张链表记录了所有已经打开的pcap句柄,目的是可以被用于关闭操作 int snapshot; // 该pcap句柄支持的最大捕获包的长度,对于普通的以太网接口可以设置为1518,对于环回口可以设置为65549,其他情况下可以设置为MAXIMUM_SNAPLEN int linktype; // 接口的链路类型,对于以太网设备/环回设备,通常就是DLT_EN10MB int offset; // 该值跟接口链路类型相关,目的是确保 offset + L2层头长度 实现4字节对齐 int activated; // 标识该pcap句柄是否处于运作状态,处于运作状态的pcap句柄将不允许进行修改 struct pcap_opt opt; // 该句柄包含的一个子结构 pcap_direction_t direction; // 捕包方向 struct bpf_program fcode; // BPF过滤模块 int dlt_count; // 该设备对应的dlt_list中元素数量,通常为2 u_int *dlt_list; // 指向该设备对应的DLT_*列表 activate_op_t activate_op; // 对应回调函数:pcap_activate_linux can_set_rfmon_op_t can_set_rfmon_op; // 对应回调函数:pcap_can_set_rfmon_linux inject_op_t inject_op; // 对应回调函数:pcap_inject_linux setfilter_op_t setfilter_op; // 对应回调函数:pcap_setfilter_linux / pcap_setfilter_linux_mmap setdirection_op_t setdirection_op; // 对应回调函数:pcap_setdirection_linux set_datalink_op_t set_datalink_op; // 对应回调函数:pcap_set_datalink_linux getnonblock_op_t getnonblock_op; // 对应回调函数:pcap_getnonblock_fd / pcap_getnonblock_mmap setnonblock_op_t setnonblock_op; // 对应回调函数:pcap_setnonblock_fd / pcap_setnonblock_mmap stats_op_t stats_op; // 对应回调函数:pcap_stats_linux pcap_handler oneshot_callback; // 对应回调函数:pcap_oneshot_mmap cleanup_op_t cleanup_op; // 对应回调函数:pcap_cleanup_linux_mmap } // pcap句柄包含的一个子结构 struct pcap_opt { char *device; // 接口名,比如"eth0" int timeout; // 该pcap句柄进行捕获操作的持续时间(ms),0意味着不超时 u_int buffer_size; // 接收缓冲区长度,缺省就是2M. 当PACKET_MMAP开启时,该值用来配置接收环形缓冲区;当不支持PACKET_MMAP时,该值用来配置套接字的接收缓冲区 int promisc; // 标识该pcap句柄是否开启混杂模式,需要注意的是,"any"设备不允许开启混杂模式 int rfmon; // 表示该pcap句柄是否开启监听模式,该模式只用于无线网卡 int immediate; // 标识收到报文时是否立即传递给用户 int tstamp_type; // 该pcap句柄使用的时间戳类型 int tstamp_precision; // 该pcap句柄使用的时间戳精度 } // 跟pcap句柄关联的linux平台私有空间 struct pcap_linux { u_int packets_read; // 统计捕获到的包数量 long proc_dropped; // 统计丢弃的包数量 char *device; // 接口名,同步自pcap->opt.device int filter_in_userland; // 标识用户空间是否需要过滤包 int timeout; // 进行捕获操作的持续时间,同步自pcap->opt.timeout int sock_packet; // 0意味着使用了PF_PACKET方式创建的套接字 int cooked; // 1意味着使用了SOCK_DGRAM类型套接字,0意味着使用了SOCK_RAW类型套接字 int ifindex; // 对于普通的以太网接口,这里记录了其接口序号 int lo_ifindex; // 记录了环回接口序号 u_char *mmapbuf; // 接收环形缓冲区在用户进程中的映射地址 size_t mmapbuflen; // mmap实际映射的接收环形缓冲区长度 int vlan_offset; // VLAN标签距离报文头部的偏移量,普通以太网链路上该值为12;cooked模式下为sll_header->sll_protocol字段 u_int tp_version; // 环形缓冲区的版本号 u_int tp_hdrlen; // 环形缓冲区的帧头长(跟环形缓冲区版本有关) int poll_timeout; // poll系统调用传入的超时参数,默认来自上面的timeout,但TPACKET_V3在3.19版本之前不允许不超时 unsigned char *current_packet; // (仅用于TPACKET_V3)指向当前待处理的帧 int packets_left; // (仅用于TPACKET_V3)待处理的帧数量 }
-
libpcap 源码解读
2009-11-11 11:02:00http://hi.baidu.com/suyupin/blog/item/c2b761123068140a5baf53fa.html http://hi.baidu.com/52hack/blog/item/4b915ce7eb7d5926b8382056.htmlhttp://industry.ccidnet.com/art/322/20050628/275739_4.htmlhttphttp://hi.baidu.com/suyupin/blog/item/c2b761123068140a5baf53fa.html http://hi.baidu.com/52hack/blog/item/4b915ce7eb7d5926b8382056.html
http://industry.ccidnet.com/art/322/20050628/275739_4.html
http://tech.techweb.com.cn/thread-214223-1-1.html
http://edu.5151doc.com/diannao/HTML/298623_8.html
-
基于Linux平台的libpcap源码分析和优化
2015-03-26 10:23:00目录 1..... libpcap简介... 1 2..... libpcap捕包过程...... 2.1 数据包基本捕包流程......2.2 libpcap捕包过程......2.3 libpcap 1.3.0源码对照... 6 2.3.1 创建环形队列... 6 2.3.2 捕获数据包... 6... -
libpcap源码分析_从pcap_open_live说起
2018-09-06 21:16:54libpcap是跨平台网络数据包捕获函数库,本文将基于Linux平台对其源码以及核心原理进行深入分析 备注: 以下分析都基于libpcap-1.8.1版本进行 以下分析按照库的核心API为线索展开 以下分析源码时只列出核心逻辑 ... -
libpcap源码分析_PACKET_MMAP机制
2018-09-11 16:30:34下面就从libpcap中的activate_mmap函数为线索,展开对PACKET_MMAP使用方法的分析。 /* 尝试对指定pcap句柄开启PACKET_MMAP功能 * @返回值 1表示成功开启;0表示系统不支持PACKET_MMAP功能;-1表示出错 */... -
Linux下Libpcap源码分析和包过滤机制
2012-12-06 23:22:24libpcap是unix/Linux平台下的网络数据包捕获函数包,大多数网络监控软件都以它为基础。libpcap可以在绝大多数类unix平台下工作,本文分析了libpcap在Linux 下的源代码实现,其中重点是Linux的底层包捕获机制和过滤... -
Linux下Libpcap源码分析和包过滤机制 (1)
2012-07-19 13:40:06Libpcap的包捕获是建立在具体的操作系统所提供的捕获机制上,而Linux系统随着版本的不同,所支持的捕获机制也有所不同。 libpcap是unix/Linux平台下的网络数据包捕获函数包,大多数网络监控软件都以它为基础。... -
Linux下Libpcap源码分析和包过滤机制 (2)
2012-07-19 13:41:59Libpcap的包捕获是建立在具体的操作系统所提供的捕获机制上,而Linux系统随着版本的不同,所支持的捕获机制也有所不同。 打开网络设备 当设备找到后,下一步工作就是打开设备以准备捕获数据包。libpcap的包... -
Linux下Libpcap源码分析和包过滤机制 (4)
2012-07-19 13:44:26libpcap 解决这个问题的方法是在设置过滤器之前, 首先读完接收队列中所有的数据包。具体步骤如下。*/ /*为了避免无限循环的情况发生(反复的读数据包并丢弃, 但新的数据包不停的到达),首先设置一个过滤器,... -
Linux下Libpcap源码分析和包过滤机制 (3)
2012-07-19 13:43:14libpcap 重点使用 BPF(BSD Packet Filter) 包过滤 机制,BPF 于 1992 年被设计出来,其设计目的主要是解决当时已存在的过滤机制效率低下的问题。BPF的工作步骤如下:当一个数据包到达网络接口时,数据链路层... -
linux sock_raw原始套接字编程 (转)和Linux下Libpcap源码分析和包过滤机制
2010-10-25 14:50:00sock_raw原始套接字编程可以接收到本机网卡上的数据帧或者数据包,对与监听网络的...Linux下Libpcap源码分析和包过滤机制 : http://www.360doc.com/content/07/0125/00/3630_343703.shtml Powered by Zoundry Raven -
Linux下libpcap编程源码
2018-06-14 13:30:09以下是官网的一个实例源码,libpcap安装和测试,在我别我文里有。 #define APP_NAME "TEST01" #define APP_DESC "JUST TEST01 #define APP_COPYRIGHT "CREAT BY GogY" #define APP_DISCLAIMER "THERE ... -
libpcap 库源码结构浅析
2004-07-13 22:56:00libpcap 库源码结构浅析作者:bobdai, 3.1 libpcap 函数库简介 libpcap是一个与实现无关的访问操作系统所提供的分组捕获机制的分组捕获函数库,用于访问数据链路层。这个库为不同的平台提供了一致的编程接口,... -
libpcap抓包源码
2011-09-18 16:50:19*程序功能:对捕获的数据包只输出网络访问层报头为以太祯 网际层报头为ip4 传输层报头为tcp的 源目的主机的,mac地址,ip地址,端口号*/ *程序功能:对捕获的数据包只输出网络访问层报头为以太祯网际层报头为ip4传输... -
libpcap 底层抓包源码
2011-03-30 22:20:06pcap实现底层IP抓包,ethereal就是用的这个库 ###########资源有误,不好意思 别下 了 -
linux 下 tcpdump 详解 前篇(libpcap库源码分析)
2019-08-23 15:29:11三 libpcap 源码理解 这里主要分析 pcap_open_live() , pcap_compile(),pcap_setfilter() ,pcap_loop四个接口函数 看函数前先介绍个重要的结构体 pcap_t typedef struct pcap pcap_t; struct pcap { read_op_t ... -
libpcap抓包并分析
2018-07-04 00:35:55基于libpcap的数据包抓取 1.libpcap安装 前提安装gcc ...在一个文件夹下下载libpcap源码并解压,在安装如下: wget -c http://www.tcpdump.org/release/libpcap-1.7.4.tar.gz 进入libpcap-...