libpcap原始碼分析
今天剛好在寫總結,就將之前分析的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、程式框架
在上面的流程中,通過查詢網路裝置,開啟網路裝置,獲取網路引數,捕獲資料包等操作簡單的描述了一個抓包的流程。
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