libpcap源码分析

今天刚好在写总结,就将之前分析的libpcap文档与大家分享一下。

百度文库的地址:http://wenku.baidu.com/view/1a8fc4baa26925c52cc5bff2# 

其中有部分是参考网上资料。

1Libpcap介绍


Libpcap是Packet Capture Library的英文缩写,即数据包捕获函数库。该库提供的C函数接口用于捕获及格过指定网络接口的数据包,该接口是被设为混杂模式。大多数网络监控软件都以它为基础,其提供的接口函数实现和封装了与数据包截获相关的过程。Libpcap提供了用户级别的网络数据包捕获接口,并充分考虑到引用程序的可移植性,可以在绝大多数类unix平台下工作。主要功能:

l 数据包捕获:捕获流经网卡的原始数据包

l 自定义数据包发送:构造任何格式的原始数据包

l 流量采集与统计:采集网络中的流量信息

l 规则过滤:提供自带规则过滤功能,按需要选择过滤规则

绝大多数的现代操作系统都提供了对底层网络数据包捕获的机制,在捕获机制之上可以建立网络监控(Network Monitoring)应用软件。网络监控也常简称为sniffer,其最初的目的在于对网络通信情况进行监控,以对网络的一些异常情况进行调试处理。但随着互连网的快速普及和网络攻击行为的频繁出现,保护网络的运行安全也成为监控软件的另一个重要目的。例如,网络监控在路由器,防火墙、入侵检查等方面使用也很广泛。本文分析了Libpcap在linux下的源代码实现,其中重点是linux的底层包捕获机制。


2Libpcap的安装


Libpcap的下载地址: http://www.tcpdump.org/  然后切换到下载的目录,解压压缩文件,配置,编译,安装。其命令如下:

cd ****

tar zxvf ****

./configure

Make

Make install

配置中如果出现错误,检查是否安装了所有的依赖包bison、m4、GNU、flex以及libpcap-dev。在运行的时候,是需要root权限的。

3Libpcap工作原理


作为捕获网络数据包的库,它是一个独立于系统的用户级的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);

}

 


  • 3
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值