Linux系统上TCP/IP协议栈在内核态(DPDK等在用户态收包情况例外),用户态如果想要干预报文的处理就需要向内核态注入hook函数,如Linux的iptables,netfilter框架中的HOOK机制即是提供该功能的。通过之前分析ip报文的内核处理路径点击打开链接可知,内核中有如下5个hook点,他们和iptables中chain一一对应。
对应hook函数在内核中是NF_HOOK调用的位于include/linux/netfilter.h文件。(上图中的NF_IP_xx等定义较老,最新的定义应该是NF_INET_xx)
/**
* nf_hook_thresh - call a netfilter hook
*
* Returns 1 if the hook has allowed the packet to pass. The function
* okfn must be invoked by the caller in this case. Any other return
* value indicates the packet has been consumed by the hook.
*/
static inline int nf_hook_thresh(u_int8_t pf, unsigned int hook,
struct sk_buff *skb,
struct net_device *indev,
struct net_device *outdev,
int (*okfn)(struct sk_buff *), int thresh)
{
#ifndef CONFIG_NETFILTER_DEBUG
if (list_empty(&nf_hooks[pf][hook]))
return 1;
#endif
return nf_hook_slow(pf, hook, skb, indev, outdev, okfn, thresh);
}
static inline int nf_hook(u_int8_t pf, unsigned int hook, struct sk_buff *skb,
struct net_dev