從ip_queue到nfnetlink_queue(下)

從ip_queue到nfnetlink_queue(下)
 
本文檔的Copyleft歸yfydz所有,使用GPL發佈,可以自由拷貝,轉載,轉載時請保持文檔的完整性,嚴
禁用於任何商業用途。
msn: [email protected]
來源:http://yfydz.cublog.cn
 
3. 內核空間
內核版本2.6.17.11。
內核空間的代碼程序包括net/netfilter/nfnetlink_queue.c和xt_NFQUEUE.c,前者是具體實現,後者
是iptables的一個目標,用來指定數據屬於哪個隊列。

3.1 數據結構

/* include/linux/netfilter/nfnetlink_queue.h */

// nfqueue netlink消息類型
enum nfqnl_msg_types {
 NFQNL_MSG_PACKET,  /* packet from kernel to userspace */
 NFQNL_MSG_VERDICT,  /* verdict from userspace to kernel */
 NFQNL_MSG_CONFIG,  /* connect to a particular queue */
 NFQNL_MSG_MAX
};

// nfqueue netlink消息數據包頭
struct nfqnl_msg_packet_hdr {
 u_int32_t packet_id; /* unique ID of packet in queue */
 u_int16_t hw_protocol; /* hw protocol (network order) */
 u_int8_t hook;  /* netfilter hook */
} __attribute__ ((packed));

// nfqueue netlink消息數據包頭硬件部分,MAC地址
struct nfqnl_msg_packet_hw {
 u_int16_t hw_addrlen;
 u_int16_t _pad;
 u_int8_t hw_addr[8];
} __attribute__ ((packed));

// nfqueue netlink消息數據包64位時間戳
struct nfqnl_msg_packet_timestamp {
 aligned_u64 sec;
 aligned_u64 usec;
} __attribute__ ((packed));

// nfqueue netlink屬性
enum nfqnl_attr_type {類型
 NFQA_UNSPEC,
 NFQA_PACKET_HDR,
 NFQA_VERDICT_HDR,  /* nfqnl_msg_verdict_hrd */
 NFQA_MARK,   /* u_int32_t nfmark */
 NFQA_TIMESTAMP,   /* nfqnl_msg_packet_timestamp */
 NFQA_IFINDEX_INDEV,  /* u_int32_t ifindex */
 NFQA_IFINDEX_OUTDEV,  /* u_int32_t ifindex */
 NFQA_IFINDEX_PHYSINDEV,  /* u_int32_t ifindex */
 NFQA_IFINDEX_PHYSOUTDEV, /* u_int32_t ifindex */
 NFQA_HWADDR,   /* nfqnl_msg_packet_hw */
 NFQA_PAYLOAD,   /* opaque data payload */
 __NFQA_MAX
};
#define NFQA_MAX (__NFQA_MAX - 1)

// nfqueue netlink消息數據判定頭
struct nfqnl_msg_verdict_hdr {
 u_int32_t verdict;
 u_int32_t id;
} __attribute__ ((packed));
 
// nfqueue netlink消息配置命令類型
enum nfqnl_msg_config_cmds {
 NFQNL_CFG_CMD_NONE,
 NFQNL_CFG_CMD_BIND,
 NFQNL_CFG_CMD_UNBIND,
 NFQNL_CFG_CMD_PF_BIND,
 NFQNL_CFG_CMD_PF_UNBIND,
};

// nfqueue netlink消息配置命令結構
struct nfqnl_msg_config_cmd {
 u_int8_t command; /* nfqnl_msg_config_cmds */
 u_int8_t _pad;
 u_int16_t pf;  /* AF_xxx for PF_[UN]BIND */
} __attribute__ ((packed));

// nfqueue netlink消息配置模式
enum nfqnl_config_mode {
 NFQNL_COPY_NONE,   // 不拷貝
 NFQNL_COPY_META,   // 只拷貝基本信息
 NFQNL_COPY_PACKET, // 拷貝整個數據包
};

// nfqueue netlink消息配置參數結構
struct nfqnl_msg_config_params {
 u_int32_t copy_range;
 u_int8_t copy_mode; /* enum nfqnl_config_mode */
} __attribute__ ((packed));
 
// nfqueue netlink消息配置模式
enum nfqnl_attr_config {
 NFQA_CFG_UNSPEC,
 NFQA_CFG_CMD,   /* nfqnl_msg_config_cmd */
 NFQA_CFG_PARAMS,  /* nfqnl_msg_config_params */
 __NFQA_CFG_MAX
};
#define NFQA_CFG_MAX (__NFQA_CFG_MAX-1)
 
/* include/linux/netfilter.c */
struct nf_info
{
 /* The ops struct which sent us to userspace. */
 struct nf_hook_ops *elem;
 
 /* If we're sent to userspace, this keeps housekeeping info */
 int pf;
 unsigned int hook;
 struct net_device *indev, *outdev;
 int (*okfn)(struct sk_buff *);
};
/* net/netfilter/nfnetlink_queue.c */
// 隊列項結構
struct nfqnl_queue_entry {
 struct list_head list;
 struct nf_info *info;
 struct sk_buff *skb;
 unsigned int id;
};
// 隊列實例結構
struct nfqnl_instance {
// HASH鏈表節點
 struct hlist_node hlist;  /* global list of queues */
 atomic_t use;
// 應用程序的pid
 int peer_pid;
// 隊列最大長度
 unsigned int queue_maxlen;
// 數據拷貝範圍
 unsigned int copy_range;
// 當前隊列元素數
 unsigned int queue_total;
// 隊列丟包數
 unsigned int queue_dropped;
// 用戶程序判定丟包
 unsigned int queue_user_dropped;
// ID序
 atomic_t id_sequence;   /* 'sequence' of pkt ids */
// 隊列號
 u_int16_t queue_num;   /* number of this queue */
// 拷貝模式
 u_int8_t copy_mode;
 spinlock_t lock;
// queue entry隊列
 struct list_head queue_list;  /* packets in queue */
};

3.2 內核程序流程

3.2.1 系統初始化
/* net/netfilter/nfnetlink_queue.c */
static int __init nfnetlink_queue_init(void)
{
 int i, status = -ENOMEM;
#ifdef CONFIG_PROC_FS
 struct proc_dir_entry *proc_nfqueue;
#endif
 
// 16個HASH鏈表
 for (i = 0; i < INSTANCE_BUCKETS; i++)
  INIT_HLIST_HEAD(&instance_table[i]);
// 登記netlink通知
 netlink_register_notifier(&nfqnl_rtnl_notifier);
// 登記nfnetlink子系統
 status = nfnetlink_subsys_register(&nfqnl_subsys);
 if (status < 0) {
  printk(KERN_ERR "nf_queue: failed to create netlink socket/n");
  goto cleanup_netlink_notifier;
 }
#ifdef CONFIG_PROC_FS
// 建立/proc/net/netfilter/nfnetlink_queue文件
 proc_nfqueue = create_proc_entry("nfnetlink_queue", 0440,
      proc_net_netfilter);
 if (!proc_nfqueue)
  goto cleanup_subsys;
 proc_nfqueue->proc_fops = &nfqnl_file_ops;
#endif

// 登記nfqueue netlink設備通知
 register_netdevice_notifier(&nfqnl_dev_notifier);
 return status;
#ifdef CONFIG_PROC_FS
cleanup_subsys:
 nfnetlink_subsys_unregister(&nfqnl_subsys);
#endif
cleanup_netlink_notifier:
 netlink_unregister_notifier(&nfqnl_rtnl_notifier);
 return status;
}

3.2.2
// netlink通知,只是定義一個通知回調函數, 在接收到netlink套接字信息時調用
static struct notifier_block nfqnl_rtnl_notifier = {
 .notifier_call = nfqnl_rcv_nl_event,
};
static int
nfqnl_rcv_nl_event(struct notifier_block *this,
     unsigned long event, void *ptr)
{
 struct netlink_notify *n = ptr;
// 就只處理釋放事件
 if (event == NETLINK_URELEASE &&
     n->protocol == NETLINK_NETFILTER && n->pid) {
  int i;
  /* destroy all instances for this pid */
  write_lock_bh(&instances_lock);
  for  (i = 0; i < INSTANCE_BUCKETS; i++) {
   struct hlist_node *tmp, *t2;
   struct nfqnl_instance *inst;
   struct hlist_head *head = &instance_table[i];
// 釋放指定pid的所有子隊列信息
   hlist_for_each_entry_safe(inst, tmp, t2, head, hlist) {
    if (n->pid == inst->peer_pid)
     __instance_destroy(inst);
   }
  }
  write_unlock_bh(&instances_lock);
 }
 return NOTIFY_DONE;
}

以下兩個函數實現釋放操作,實際是調用同一個函數,一個需要加鎖,一個不需要
static inline void
instance_destroy(struct nfqnl_instance *inst)
{
 _instance_destroy2(inst, 1);
}
static inline void
__instance_destroy(struct nfqnl_instance *inst)
{
 _instance_destroy2(inst, 0);
}
 

static void
_instance_destroy2(struct nfqnl_instance *inst, int lock)
{
 /* first pull it out of the global list */
 if (lock)
  write_lock_bh(&instances_lock);
 QDEBUG("removing instance %p (queuenum=%u) from hash/n",
  inst, inst->queue_num);
// 將隊列實例先從鏈表中移出
 hlist_del(&inst->hlist);
 if (lock)
  write_unlock_bh(&instances_lock);
 /* then flush all pending skbs from the queue */
// 將當前隊列中所有包的判定都設置DROP
 nfqnl_flush(inst, NF_DROP);
 /* and finally put the refcount */
// 釋放隊列實例本身
 instance_put(inst);
// 釋放模塊引用
 module_put(THIS_MODULE);
}

3.2.3 子系統
// 子系統定義
static struct nfnetlink_subsystem nfqnl_subsys = {
 .name  = "nf_queue",
 .subsys_id = NFNL_SUBSYS_QUEUE, // NFQUEUE的ID號爲3
 .cb_count = NFQNL_MSG_MAX, // 3個控制塊
 .cb  = nfqnl_cb,
};

// 子系統回調控制
static struct nfnl_callback nfqnl_cb[NFQNL_MSG_MAX] = {
// 接收數據包,實際沒進行定義
 [NFQNL_MSG_PACKET] = { .call = nfqnl_recv_unsupp,
        .attr_count = NFQA_MAX, },
// 接收判定
 [NFQNL_MSG_VERDICT] = { .call = nfqnl_recv_verdict,
        .attr_count = NFQA_MAX, },
// 接收配置
 [NFQNL_MSG_CONFIG] = { .call = nfqnl_recv_config,
        .attr_count = NFQA_CFG_MAX, },
};

3.2.3.1
// 實際沒定義
static int
nfqnl_recv_unsupp(struct sock *ctnl, struct sk_buff *skb,
    struct nlmsghdr *nlh, struct nfattr *nfqa[], int *errp)
{
 return -ENOTSUPP;
}

3.2.3.2 接收判定
該函數接收netlink套接字返回的數據包的判定結果,根據結果對包進行相關處理
static int
nfqnl_recv_verdict(struct sock *ctnl, struct sk_buff *skb,
     struct nlmsghdr *nlh, struct nfattr *nfqa[], int *errp)
{
 struct nfgenmsg *nfmsg = NLMSG_DATA(nlh);
 u_int16_t queue_num = ntohs(nfmsg->res_id);
 struct nfqnl_msg_verdict_hdr *vhdr;
 struct nfqnl_instance *queue;
 unsigned int verdict;
 struct nfqnl_queue_entry *entry;
 int err;
// 判定數據包大小是否有問題
 if (nfattr_bad_size(nfqa, NFQA_MAX, nfqa_verdict_min)) {
  QDEBUG("bad attribute size/n");
  return -EINVAL;
 }
// 根據隊列號找到隊列的實例,並增加計數
 queue = instance_lookup_get(queue_num);
 if (!queue)
  return -ENODEV;
// 檢查該隊列對應的pid是否和netlink數據包中的pid匹配
 if (queue->peer_pid != NETLINK_CB(skb).pid) {
  err = -EPERM;
  goto err_out_put;
 }
// 檢查是否返回了判定結果
 if (!nfqa[NFQA_VERDICT_HDR-1]) {
  err = -EINVAL;
  goto err_out_put;
 }
// 獲取判定結果
 vhdr = NFA_DATA(nfqa[NFQA_VERDICT_HDR-1]);
 verdict = ntohl(vhdr->verdict);
// 低16位爲判定結果, 不能超過NF_MAX_VERDICT(5)
 if ((verdict & NF_VERDICT_MASK) > NF_MAX_VERDICT) {
  err = -EINVAL;
  goto err_out_put;
 }
// 根據返回包的ID號在隊列中找緩存具體的數據包
 entry = find_dequeue_entry(queue, id_cmp, ntohl(vhdr->id));
 if (entry == NULL) {
  err = -ENOENT;
  goto err_out_put;
 }
 if (nfqa[NFQA_PAYLOAD-1]) {
// 返回了負載內容,說明要進行數據包的修改,如果不修改是不用返回載荷內容的
  if (nfqnl_mangle(NFA_DATA(nfqa[NFQA_PAYLOAD-1]),
     NFA_PAYLOAD(nfqa[NFQA_PAYLOAD-1]), entry) < 0)
// 修改出錯,丟棄數據包
   verdict = NF_DROP;
 }
// 是否修改數據包的mark值
 if (nfqa[NFQA_MARK-1])
  entry->skb->nfmark = ntohl(*(u_int32_t *)
                             NFA_DATA(nfqa[NFQA_MARK-1]));
// 和ip_queue一樣,調用nf_reinject()重新將數據包發回netfilter進行處理
// 然後將該entry的內存釋放掉
 issue_verdict(entry, verdict);
// 減少隊列引用計數
 instance_put(queue);
 return 0;
err_out_put:
 instance_put(queue);
 return err;
}

3.2.3.3 接收配置
static int
nfqnl_recv_config(struct sock *ctnl, struct sk_buff *skb,
    struct nlmsghdr *nlh, struct nfattr *nfqa[], int *errp)
{
 struct nfgenmsg *nfmsg = NLMSG_DATA(nlh);
 u_int16_t queue_num = ntohs(nfmsg->res_id);
 struct nfqnl_instance *queue;
 int ret = 0;
 QDEBUG("entering for msg %u/n", NFNL_MSG_TYPE(nlh->nlmsg_type));
// 數據大小檢查
 if (nfattr_bad_size(nfqa, NFQA_CFG_MAX, nfqa_cfg_min)) {
  QDEBUG("bad attribute size/n");
  return -EINVAL;
 }
//
// 根據隊列號找到隊列的實例,並增加計數
 queue = instance_lookup_get(queue_num);
 if (nfqa[NFQA_CFG_CMD-1]) {
// 配置命令,由於可能是進行新建queue操作,所以此時的queue值可能爲空
//
  struct nfqnl_msg_config_cmd *cmd;
  cmd = NFA_DATA(nfqa[NFQA_CFG_CMD-1]);
  QDEBUG("found CFG_CMD/n");
  switch (cmd->command) {
  case NFQNL_CFG_CMD_BIND:
   if (queue)
    return -EBUSY;
// 綁定命令,就是新建一個queue和對應的pid綁定
   queue = instance_create(queue_num, NETLINK_CB(skb).pid);
   if (!queue)
    return -EINVAL;
   break;
  case NFQNL_CFG_CMD_UNBIND:
// 取消綁定
   if (!queue)
    return -ENODEV;
// 檢查pid是否匹配
   if (queue->peer_pid != NETLINK_CB(skb).pid) {
    ret = -EPERM;
    goto out_put;
   }
// 是否隊列實例
   instance_destroy(queue);
   break;
  case NFQNL_CFG_CMD_PF_BIND:
// 綁定協議族, 將nfqueue handler綁定到指定的協議
   QDEBUG("registering queue handler for pf=%u/n",
    ntohs(cmd->pf));
   ret = nf_register_queue_handler(ntohs(cmd->pf), &nfqh);
   break;
  case NFQNL_CFG_CMD_PF_UNBIND:
// 取消協議族的綁定
   QDEBUG("unregistering queue handler for pf=%u/n",
    ntohs(cmd->pf));
   /* This is a bug and a feature.  We can unregister
    * other handlers(!) */
   ret = nf_unregister_queue_handler(ntohs(cmd->pf));
   break;
  default:
   ret = -EINVAL;
   break;
  }
 } else {
// 如果不是配置命令,檢查queue是否存在,pid是否匹配
  if (!queue) {
   QDEBUG("no config command, and no instance ENOENT/n");
   ret = -ENOENT;
   goto out_put;
  }
  if (queue->peer_pid != NETLINK_CB(skb).pid) {
   QDEBUG("no config command, and wrong pid/n");
   ret = -EPERM;
   goto out_put;
  }
 }
 if (nfqa[NFQA_CFG_PARAMS-1]) {
// 配置參數
  struct nfqnl_msg_config_params *params;
  if (!queue) {
   ret = -ENOENT;
   goto out_put;
  }
  params = NFA_DATA(nfqa[NFQA_CFG_PARAMS-1]);
// 設置數據拷貝模式
  nfqnl_set_mode(queue, params->copy_mode,
    ntohl(params->copy_range));
 }
out_put:
// 減少引用計數
// 除了初始化函數和釋放函數外,所有其他處理函數的計數增加和減少操作都是成對出現的
 instance_put(queue);
 return ret;
}
其中隊列實例建立函數如下:
static struct nfqnl_instance *
instance_create(u_int16_t queue_num, int pid)
{
 struct nfqnl_instance *inst;
 QDEBUG("entering for queue_num=%u, pid=%d/n", queue_num, pid);
 write_lock_bh(&instances_lock); 
//
// 根據隊列號找到隊列的實例,這裏是不增加計數的
 if (__instance_lookup(queue_num)) {
// 理論上是不可能進入這裏的
  inst = NULL;
  QDEBUG("aborting, instance already exists/n");
  goto out_unlock;
 }
// 分配queue實例空間, 初始化參數
 inst = kzalloc(sizeof(*inst), GFP_ATOMIC);
 if (!inst)
  goto out_unlock;
 inst->queue_num = queue_num;
 inst->peer_pid = pid;
 inst->queue_maxlen = NFQNL_QMAX_DEFAULT;
 inst->copy_range = 0xfffff;
 inst->copy_mode = NFQNL_COPY_NONE;
 atomic_set(&inst->id_sequence, 0);
 /* needs to be two, since we _put() after creation */
// 初始引用計數爲2,因爲nfqnl_recv_config()會釋放掉一次
 atomic_set(&inst->use, 2);
 spin_lock_init(&inst->lock);
 INIT_LIST_HEAD(&inst->queue_list);
 if (!try_module_get(THIS_MODULE))
  goto out_free;
// 將該隊列實例添加到總的隊列HASH鏈表中
 hlist_add_head(&inst->hlist,
         &instance_table[instance_hashfn(queue_num)]);
 write_unlock_bh(&instances_lock);
 QDEBUG("successfully created new instance/n");
 return inst;
out_free:
 kfree(inst);
out_unlock:
 write_unlock_bh(&instances_lock);
 return NULL;
}
 
其中nf_queue_handler定義如下, 主要是定義數據進入協議隊列函數,這個就是數據包進入nf_queue的
進入點:
static struct nf_queue_handler nfqh = {
 .name  = "nf_queue",
 .outfn = &nfqnl_enqueue_packet,
};
static int
nfqnl_enqueue_packet(struct sk_buff *skb, struct nf_info *info,
       unsigned int queuenum, void *data)
{
 int status = -EINVAL;
 struct sk_buff *nskb;
 struct nfqnl_instance *queue;
 struct nfqnl_queue_entry *entry;
 QDEBUG("entered/n");
//
// 根據隊列號找到隊列的實例,並增加計數
 queue = instance_lookup_get(queuenum);
 if (!queue) {
  QDEBUG("no queue instance matching/n");
  return -EINVAL;
 }
// 如果該子隊列拷貝模式是NFQNL_COPY_NONE,出錯返回
 if (queue->copy_mode == NFQNL_COPY_NONE) {
  QDEBUG("mode COPY_NONE, aborting/n");
  status = -EAGAIN;
  goto err_out_put;
 }
// 分配一個隊列項entry
 entry = kmalloc(sizeof(*entry), GFP_ATOMIC);
 if (entry == NULL) {
  if (net_ratelimit())
   printk(KERN_ERR
    "nf_queue: OOM in nfqnl_enqueue_packet()/n");
  status = -ENOMEM;
  goto err_out_put;
 }
 entry->info = info;
 entry->skb = skb;
// 數據包的ID是順序增加的
 entry->id = atomic_inc_return(&queue->id_sequence);
// 構建一個netlink協議的skb包
 nskb = nfqnl_build_packet_message(queue, entry, &status);
 if (nskb == NULL)
  goto err_out_free;
  
 spin_lock_bh(&queue->lock);
// pid是否存在,pid爲0的進程不存在
 if (!queue->peer_pid)
  goto err_out_free_nskb;
// 隊列長度是否過長
 if (queue->queue_total >= queue->queue_maxlen) {
                queue->queue_dropped++;
  status = -ENOSPC;
  if (net_ratelimit())
            printk(KERN_WARNING "ip_queue: full at %d entries, "
     "dropping packets(s). Dropped: %d/n",
     queue->queue_total, queue->queue_dropped);
  goto err_out_free_nskb;
 }
 /* nfnetlink_unicast will either free the nskb or add it to a socket */
// 將新構造的netlink數據包發送給上層的netlink套接字
 status = nfnetlink_unicast(nskb, queue->peer_pid, MSG_DONTWAIT);
 if (status < 0) {
         queue->queue_user_dropped++;
  goto err_out_unlock;
 }
// 將隊列項entry放入隊列
 __enqueue_entry(queue, entry);
 spin_unlock_bh(&queue->lock);
// 減少隊列計數
 instance_put(queue);
 return status;
err_out_free_nskb:
 kfree_skb(nskb);
 
err_out_unlock:
 spin_unlock_bh(&queue->lock);
err_out_free:
 kfree(entry);
err_out_put:
 instance_put(queue);
 return status;
}

// 構造netlink數據包
static struct sk_buff *
nfqnl_build_packet_message(struct nfqnl_instance *queue,
      struct nfqnl_queue_entry *entry, int *errp)
{
 unsigned char *old_tail;
 size_t size;
 size_t data_len = 0;
 struct sk_buff *skb;
 struct nfqnl_msg_packet_hdr pmsg;
 struct nlmsghdr *nlh;
 struct nfgenmsg *nfmsg;
// entry info, 可得到inif,outif,hook等
 struct nf_info *entinf = entry->info;
// entry skb, 原始skb
 struct sk_buff *entskb = entry->skb;
 struct net_device *indev;
 struct net_device *outdev;
 unsigned int tmp_uint;
 QDEBUG("entered/n");
 /* all macros expand to constant values at compile time */
// 頭部固定長度
 size =    NLMSG_SPACE(sizeof(struct nfgenmsg)) +
  + NFA_SPACE(sizeof(struct nfqnl_msg_packet_hdr))
  + NFA_SPACE(sizeof(u_int32_t)) /* ifindex */
  + NFA_SPACE(sizeof(u_int32_t)) /* ifindex */
#ifdef CONFIG_BRIDGE_NETFILTER
  + NFA_SPACE(sizeof(u_int32_t)) /* ifindex */
  + NFA_SPACE(sizeof(u_int32_t)) /* ifindex */
#endif
  + NFA_SPACE(sizeof(u_int32_t)) /* mark */
  + NFA_SPACE(sizeof(struct nfqnl_msg_packet_hw))
  + NFA_SPACE(sizeof(struct nfqnl_msg_packet_timestamp));
// 數據包出網卡
 outdev = entinf->outdev;
 spin_lock_bh(&queue->lock);
 
 switch (queue->copy_mode) {
 case NFQNL_COPY_META:
 case NFQNL_COPY_NONE:
// 這兩種拷貝類型數據長度爲0
  data_len = 0;
  break;
 
 case NFQNL_COPY_PACKET:
// 拷貝整個包
  if (entskb->ip_summed == CHECKSUM_HW &&
      (*errp = skb_checksum_help(entskb,
                                 outdev == NULL))) {
// 校驗和檢查失敗
   spin_unlock_bh(&queue->lock);
   return NULL;
  }
  if (queue->copy_range == 0   // 爲0表示不限制拷貝範圍長度
      || queue->copy_range > entskb->len) // 拷貝限制大於數據包長
// 數據長度爲實際數據包長度
   data_len = entskb->len;
  else
// 數據長度爲限制的拷貝長度限制
   data_len = queue->copy_range;
// 將data_len對齊後添加包頭長度  
  size += NFA_SPACE(data_len);
  break;
 
 default:
  *errp = -EINVAL;
  spin_unlock_bh(&queue->lock);
  return NULL;
 }
 spin_unlock_bh(&queue->lock);
// 分配skb
 skb = alloc_skb(size, GFP_ATOMIC);
 if (!skb)
  goto nlmsg_failure;
  
 old_tail= skb->tail;
// netlink信息頭放在skb的tailroom中
 nlh = NLMSG_PUT(skb, 0, 0,
   NFNL_SUBSYS_QUEUE << 8 | NFQNL_MSG_PACKET,
   sizeof(struct nfgenmsg));
 nfmsg = NLMSG_DATA(nlh);
// 協議族
 nfmsg->nfgen_family = entinf->pf;
// 版本
 nfmsg->version = NFNETLINK_V0;
// 隊列號
 nfmsg->res_id = htons(queue->queue_num);
// 包ID號
 pmsg.packet_id   = htonl(entry->id);
// 硬件協議
 pmsg.hw_protocol = htons(entskb->protocol);
// nf的hook點
 pmsg.hook  = entinf->hook;
 NFA_PUT(skb, NFQA_PACKET_HDR, sizeof(pmsg), &pmsg);
// 數據進入網卡
 indev = entinf->indev;
 if (indev) {
  tmp_uint = htonl(indev->ifindex);
#ifndef CONFIG_BRIDGE_NETFILTER
  NFA_PUT(skb, NFQA_IFINDEX_INDEV, sizeof(tmp_uint), &tmp_uint);
#else
  if (entinf->pf == PF_BRIDGE) {
// 如果是橋協議族,填入物理網卡和進入網卡參數
   /* Case 1: indev is physical input device, we need to
    * look for bridge group (when called from
    * netfilter_bridge) */
   NFA_PUT(skb, NFQA_IFINDEX_PHYSINDEV, sizeof(tmp_uint),
    &tmp_uint);
   /* this is the bridge group "brX" */
   tmp_uint = htonl(indev->br_port->br->dev->ifindex);
   NFA_PUT(skb, NFQA_IFINDEX_INDEV, sizeof(tmp_uint),
    &tmp_uint);
  } else {
   /* Case 2: indev is bridge group, we need to look for
    * physical device (when called from ipv4) */
// 填入輸入網卡信息
   NFA_PUT(skb, NFQA_IFINDEX_INDEV, sizeof(tmp_uint),
    &tmp_uint);
   if (entskb->nf_bridge
       && entskb->nf_bridge->physindev) {
// 如果存在橋信息和物理進入網卡信息,填入
    tmp_uint = htonl(entskb->nf_bridge->physindev->ifindex
);
    NFA_PUT(skb, NFQA_IFINDEX_PHYSINDEV,
     sizeof(tmp_uint), &tmp_uint);
   }
  }
#endif
 }
// 數據包發出網卡
 if (outdev) {
  tmp_uint = htonl(outdev->ifindex);
#ifndef CONFIG_BRIDGE_NETFILTER
// 沒定義橋模塊時直接填入發出網卡信息
  NFA_PUT(skb, NFQA_IFINDEX_OUTDEV, sizeof(tmp_uint), &tmp_uint);
#else
  if (entinf->pf == PF_BRIDGE) {
// 橋協議組,  分別填入物理髮出網卡和發出網卡信息
   /* Case 1: outdev is physical output device, we need to
    * look for bridge group (when called from
    * netfilter_bridge) */
   NFA_PUT(skb, NFQA_IFINDEX_PHYSOUTDEV, sizeof(tmp_uint),
    &tmp_uint);
   /* this is the bridge group "brX" */
   tmp_uint = htonl(outdev->br_port->br->dev->ifindex);
   NFA_PUT(skb, NFQA_IFINDEX_OUTDEV, sizeof(tmp_uint),
    &tmp_uint);
  } else {
   /* Case 2: outdev is bridge group, we need to look for
    * physical output device (when called from ipv4) */
// 填入發出網卡信息
   NFA_PUT(skb, NFQA_IFINDEX_OUTDEV, sizeof(tmp_uint),
    &tmp_uint);
   if (entskb->nf_bridge
       && entskb->nf_bridge->physoutdev) {
// 如果存在橋信息和物理髮出網卡信息,填入
    tmp_uint = htonl(entskb->nf_bridge->physoutdev-
>ifindex);
    NFA_PUT(skb, NFQA_IFINDEX_PHYSOUTDEV,
     sizeof(tmp_uint), &tmp_uint);
   }
  }
#endif
 }
 if (entskb->nfmark) {
// 如果數據包MARK值不爲0, 填入
  tmp_uint = htonl(entskb->nfmark);
  NFA_PUT(skb, NFQA_MARK, sizeof(u_int32_t), &tmp_uint);
 }
 if (indev && entskb->dev
     && entskb->dev->hard_header_parse) {
// 填入輸入網卡的硬件信息
  struct nfqnl_msg_packet_hw phw;
  phw.hw_addrlen =
   entskb->dev->hard_header_parse(entskb,
                                      phw.hw_addr);
  phw.hw_addrlen = htons(phw.hw_addrlen);
  NFA_PUT(skb, NFQA_HWADDR, sizeof(phw), &phw);
 }
 if (entskb->tstamp.off_sec) {
// 時間戳
  struct nfqnl_msg_packet_timestamp ts;
  ts.sec = cpu_to_be64(entskb->tstamp.off_sec);
  ts.usec = cpu_to_be64(entskb->tstamp.off_usec);
  NFA_PUT(skb, NFQA_TIMESTAMP, sizeof(ts), &ts);
 }
 if (data_len) {
// 填入數據包長, 以struct nfattr結構方式
  struct nfattr *nfa;
  int size = NFA_LENGTH(data_len);
  if (skb_tailroom(skb) < (int)NFA_SPACE(data_len)) {
   printk(KERN_WARNING "nf_queue: no tailroom!/n");
   goto nlmsg_failure;
  }
  nfa = (struct nfattr *)skb_put(skb, NFA_ALIGN(size));
  nfa->nfa_type = NFQA_PAYLOAD;
  nfa->nfa_len = size;
  if (skb_copy_bits(entskb, 0, NFA_DATA(nfa), data_len))
   BUG();
 }
// netlink信息長度,新tail減老的tail值
 nlh->nlmsg_len = skb->tail - old_tail;
 return skb;
nlmsg_failure:
nfattr_failure:
 if (skb)
  kfree_skb(skb);
 *errp = -EINVAL;
 if (net_ratelimit())
  printk(KERN_ERR "nf_queue: error creating packet message/n");
 return NULL;
}

3.2.4 登記nfqueue netlink設備通知

static struct notifier_block nfqnl_dev_notifier = {
 .notifier_call = nfqnl_rcv_dev_event,
};

static int
nfqnl_rcv_dev_event(struct notifier_block *this,
      unsigned long event, void *ptr)
{
 struct net_device *dev = ptr;
// 只處理設備釋放事件,如果網卡DOWN了,就會進行相關處理
 /* Drop any packets associated with the downed device */
 if (event == NETDEV_DOWN)
  nfqnl_dev_drop(dev->ifindex);
 return NOTIFY_DONE;
}

/* drop all packets with either indev or outdev == ifindex from all queue
 * instances */
static void
nfqnl_dev_drop(int ifindex)
{
 int i;
 
 QDEBUG("entering for ifindex %u/n", ifindex);
 /* this only looks like we have to hold the readlock for a way too long
  * time, issue_verdict(),  nf_reinject(), ... - but we always only
  * issue NF_DROP, which is processed directly in nf_reinject() */
 read_lock_bh(&instances_lock);
// 查找所有隊列
 for  (i = 0; i < INSTANCE_BUCKETS; i++) {
  struct hlist_node *tmp;
  struct nfqnl_instance *inst;
  struct hlist_head *head = &instance_table[i];
  hlist_for_each_entry(inst, tmp, head, hlist) {
   struct nfqnl_queue_entry *entry;
   while ((entry = find_dequeue_entry(inst, dev_cmp,
          ifindex)) != NULL)
// 一旦數據包的進入或發出網卡是DOWN掉的網卡,就丟棄該數據包
    issue_verdict(entry, NF_DROP);
  }
 }
 read_unlock_bh(&instances_lock);
}
// 比較設備,不論是in還是out的設備,只要和ifindex符合的就匹配成功
static int
dev_cmp(struct nfqnl_queue_entry *entry, unsigned long ifindex)
{
 struct nf_info *entinf = entry->info;
 
 if (entinf->indev)
  if (entinf->indev->ifindex == ifindex)
   return 1;
   
 if (entinf->outdev)
  if (entinf->outdev->ifindex == ifindex)
   return 1;
 return 0;
}
 
3.2.5 /proc
就是以前介紹的2.6.*中用於實現/proc只讀文件的seq操作
static struct file_operations nfqnl_file_ops = {
 .owner  = THIS_MODULE,
 .open  = nfqnl_open,
 .read  = seq_read,
 .llseek  = seq_lseek,
 .release = seq_release_private,
};
static int nfqnl_open(struct inode *inode, struct file *file)
{
 struct seq_file *seq;
 struct iter_state *is;
 int ret;
 is = kzalloc(sizeof(*is), GFP_KERNEL);
 if (!is)
  return -ENOMEM;
// 打開nfqueue netlink的順序操作
// 文件內容就是16個HASH表中的各項的參數,最多65536項
 ret = seq_open(file, &nfqnl_seq_ops);
 if (ret < 0)
  goto out_free;
 seq = file->private_data;
 seq->private = is;
 return ret;
out_free:
 kfree(is);
 return ret;
}

static int seq_show(struct seq_file *s, void *v)
{
 const struct nfqnl_instance *inst = v;
// 該/proc文件中最大可能會有65536行, 每行表示一個子queue的信息
 return seq_printf(s, "%5d %6d %5d %1d %5d %5d %5d %8d %2d/n",
     inst->queue_num,
     inst->peer_pid, inst->queue_total,
     inst->copy_mode, inst->copy_range,
     inst->queue_dropped, inst->queue_user_dropped,
     atomic_read(&inst->id_sequence),
     atomic_read(&inst->use));
}

3.3 NFQUEUE目標

該目標很簡單,返回一個無符號32位值,該值的生成就是提供一個16位的隊列號,然後左移16位作爲結果的
高16位,低16位置爲NF_QUEUE(3).
#define NF_VERDICT_MASK 0x0000ffff
#define NF_VERDICT_BITS 16
#define NF_VERDICT_QMASK 0xffff0000
#define NF_VERDICT_QBITS 16
#define NF_QUEUE_NR(x) (((x << NF_VERDICT_QBITS) & NF_VERDICT_QMASK) | NF_QUEUE)
static unsigned int
target(struct sk_buff **pskb,
       const struct net_device *in,
       const struct net_device *out,
       unsigned int hooknum,
       const struct xt_target *target,
       const void *targinfo,
       void *userinfo)
{
 const struct xt_NFQ_info *tinfo = targinfo;
 return NF_QUEUE_NR(tinfo->queuenum);
}
在iptables命令行就可以將指定的數據包設置爲進入指定的子隊列,例:
iptables -A INPUT -s 1.1.1.1 -d 2.2.2.2 -j NFQUEUE --queue-num 100
將從1.1.1.1到2.2.2.2的包發送到子隊列100.
 
3.4 NFQUEUE包處理

和正常netfilter數據包處理一樣, 要進行NFQUEUE的數據包也進入nf_hook_slow()函數處理:
/* net/netfilter/core.c */
int nf_hook_slow(int pf, unsigned int hook, struct sk_buff **pskb,
   struct net_device *indev,
   struct net_device *outdev,
   int (*okfn)(struct sk_buff *),
   int hook_thresh)
{
......
// 對於NFQUEUE的包,看verdict的低16位是否爲NF_QUEUE
 } else if ((verdict & NF_VERDICT_MASK)  == NF_QUEUE) {
  NFDEBUG("nf_hook: Verdict = QUEUE./n");
// 進入nf_queue進行處理
  if (!nf_queue(pskb, elem, pf, hook, indev, outdev, okfn,
         verdict >> NF_VERDICT_BITS))
   goto next_hook;
......
 
/* net/netfilter/nf_queue.c */
// nf_queue()函數和以前2.4基本是相同的,從這裏是看不出ip_queue和nf_queue的區別,
// 每個協議族還是隻有一個QUEUE的handler,但這時掛接的nf_queue的handler
// 的處理函數nfqnl_enqueue_packet()
/*
 * Any packet that leaves via this function must come back
 * through nf_reinject().
 */
int nf_queue(struct sk_buff **skb,
      struct list_head *elem,
      int pf, unsigned int hook,
      struct net_device *indev,
      struct net_device *outdev,
      int (*okfn)(struct sk_buff *),
      unsigned int queuenum)
{
 int status;
 struct nf_info *info;
#ifdef CONFIG_BRIDGE_NETFILTER
 struct net_device *physindev = NULL;
 struct net_device *physoutdev = NULL;
#endif
 struct nf_afinfo *afinfo;
 /* QUEUE == DROP if noone is waiting, to be safe. */
 read_lock(&queue_handler_lock);
 if (!queue_handler[pf]) {
  read_unlock(&queue_handler_lock);
  kfree_skb(*skb);
  return 1;
 }
 afinfo = nf_get_afinfo(pf);
 if (!afinfo) {
  read_unlock(&queue_handler_lock);
  kfree_skb(*skb);
  return 1;
 }
 info = kmalloc(sizeof(*info) + afinfo->route_key_size, GFP_ATOMIC);
 if (!info) {
  if (net_ratelimit())
   printk(KERN_ERR "OOM queueing packet %p/n",
          *skb);
  read_unlock(&queue_handler_lock);
  kfree_skb(*skb);
  return 1;
 }
 *info = (struct nf_info) {
  (struct nf_hook_ops *)elem, pf, hook, indev, outdev, okfn };
 /* If it's going away, ignore hook. */
 if (!try_module_get(info->elem->owner)) {
  read_unlock(&queue_handler_lock);
  kfree(info);
  return 0;
 }
 /* Bump dev refs so they don't vanish while packet is out */
 if (indev) dev_hold(indev);
 if (outdev) dev_hold(outdev);
#ifdef CONFIG_BRIDGE_NETFILTER
 if ((*skb)->nf_bridge) {
  physindev = (*skb)->nf_bridge->physindev;
  if (physindev) dev_hold(physindev);
  physoutdev = (*skb)->nf_bridge->physoutdev;
  if (physoutdev) dev_hold(physoutdev);
 }
#endif
 afinfo->saveroute(*skb, info);
 status = queue_handler[pf]->outfn(*skb, info, queuenum,
       queue_handler[pf]->data);
 read_unlock(&queue_handler_lock);
 if (status < 0) {
  /* James M doesn't say fuck enough. */
  if (indev) dev_put(indev);
  if (outdev) dev_put(outdev);
#ifdef CONFIG_BRIDGE_NETFILTER
  if (physindev) dev_put(physindev);
  if (physoutdev) dev_put(physoutdev);
#endif
  module_put(info->elem->owner);
  kfree(info);
  kfree_skb(*skb);
  return 1;
 }
 return 1;
}
4. 結論

nf_queue擴展了ip_queue的功能,使用類似802.1qVLAN的技術,將數據包打上不同的“標籤”使之歸到
不同的隊列,而不再象ip_queue那樣只支持一個隊列,這樣就可以使最多65536個應用程序接收內核數據
包,從而分別進行更仔細
的分類處理。

發表於: 2006-11-20,修改於: 2006-11-27 08:53,已瀏覽1347次,有評論4條 推薦 投訴
網友: 本站網友 時間:2007-04-04 22:33:19 IP地址:219.142.158.★
 
 
 
請教:你實際編譯加載過netfilter_queue沒有?我最近在看這個,安裝完nfnetlink之後安裝netfilter_queue,加載該模塊的時候提示找不到該模塊.能給點建議嗎?

 
網友: yfydz 時間:2007-04-05 09:29:45 IP地址:218.247.216.★
 
 
 
編內核時選了NETFILTER_NETLINK, NETFILTER_NETLINK_QUEUE了麼?

 
網友: 本站網友 時間:2007-04-05 23:00:34 IP地址:58.31.130.★
 
 
 
全選了啊,OMG。





Module                  Size  Used by

autofs4                24964  2 

sunrpc                156092  1 

iptable_filter          7172  0 

ip_tables              16852  1 iptable_filter

ip6t_REJECT             9344  1 

xt_tcpudp               7552  5 

ip6table_filter         6916  1 

ip6_tables             18004  1 ip6table_filter

x_tables               19204  4 ip_tables,ip6t_REJECT,xt_tcpudp,ip6_tables

ipv6                  261024  23 ip6t_REJECT

dm_multipath           22664  0 

video                  21124  0 

sbs                    19808  0 

i2c_ec                  9216  1 sbs

dock                   14552  0 

button                 12048  0 

battery                14212  0 

asus_acpi              20644  0 

backlight              10496  1 asus_acpi

ac                      9348  0 

parport_pc             30948  1 

lp                     16712  0 

parport                39112  2 parport_pc,lp

floppy                 61444  0 

pcspkr                  7296  0 

BusLogic               75028  0 

scsi_mod              141772  1 BusLogic

serio_raw              11268  0 

i2c_piix4              12820  0 

i2c_core               25216  2 i2c_ec,i2c_piix4

ide_cd                 42120  0 

cdrom                  40512  1 ide_cd

dm_snapshot            21808  0 

dm_zero                 6144  0 

dm_mirror              26900  0 

dm_mod                 61516  9 dm_multipath,dm_snapshot,dm_zero,dm_mirror

ext3                  127368  2 

jbd                    62376  1 ext3

ehci_hcd               35352  0 

ohci_hcd               24076  0 

uhci_hcd               27412  0 





[root@localhost ~]# modprobe netfilter_queue

FATAL: Module netfilter_queue not found.

[root@localhost ~]# 





[root@localhost ~]# insmod /usr/local/lib/libnetfilter_queue.so

insmod: error inserting '/usr/local/lib/libnetfilter_queue.so': -1 Invalid module format

[root@localhost ~]# 




 
網友: yfydz 時間:2007-04-09 08:59:14 IP地址:218.247.216.★
 
 
 
沒看出有這模塊, 你直接編內核裏吧



另外.so文件只是用戶空間動態庫, 不是內核模塊
 
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章