edbae4caf75392148d7dab9516b4d2420be632e5
[linux-3.10.git] / net / netfilter / nfnetlink_queue_core.c
1 /*
2  * This is a module which is used for queueing packets and communicating with
3  * userspace via nfnetlink.
4  *
5  * (C) 2005 by Harald Welte <laforge@netfilter.org>
6  * (C) 2007 by Patrick McHardy <kaber@trash.net>
7  *
8  * Based on the old ipv4-only ip_queue.c:
9  * (C) 2000-2002 James Morris <jmorris@intercode.com.au>
10  * (C) 2003-2005 Netfilter Core Team <coreteam@netfilter.org>
11  *
12  * This program is free software; you can redistribute it and/or modify
13  * it under the terms of the GNU General Public License version 2 as
14  * published by the Free Software Foundation.
15  *
16  */
17 #include <linux/module.h>
18 #include <linux/skbuff.h>
19 #include <linux/init.h>
20 #include <linux/spinlock.h>
21 #include <linux/slab.h>
22 #include <linux/notifier.h>
23 #include <linux/netdevice.h>
24 #include <linux/netfilter.h>
25 #include <linux/proc_fs.h>
26 #include <linux/netfilter_ipv4.h>
27 #include <linux/netfilter_ipv6.h>
28 #include <linux/netfilter/nfnetlink.h>
29 #include <linux/netfilter/nfnetlink_queue.h>
30 #include <linux/list.h>
31 #include <net/sock.h>
32 #include <net/netfilter/nf_queue.h>
33 #include <net/netns/generic.h>
34 #include <net/netfilter/nfnetlink_queue.h>
35
36 #include <linux/atomic.h>
37
38 #ifdef CONFIG_BRIDGE_NETFILTER
39 #include "../bridge/br_private.h"
40 #endif
41
42 #define NFQNL_QMAX_DEFAULT 1024
43
44 struct nfqnl_instance {
45         struct hlist_node hlist;                /* global list of queues */
46         struct rcu_head rcu;
47
48         int peer_portid;
49         unsigned int queue_maxlen;
50         unsigned int copy_range;
51         unsigned int queue_dropped;
52         unsigned int queue_user_dropped;
53
54
55         u_int16_t queue_num;                    /* number of this queue */
56         u_int8_t copy_mode;
57         u_int32_t flags;                        /* Set using NFQA_CFG_FLAGS */
58 /*
59  * Following fields are dirtied for each queued packet,
60  * keep them in same cache line if possible.
61  */
62         spinlock_t      lock;
63         unsigned int    queue_total;
64         unsigned int    id_sequence;            /* 'sequence' of pkt ids */
65         struct list_head queue_list;            /* packets in queue */
66 };
67
68 typedef int (*nfqnl_cmpfn)(struct nf_queue_entry *, unsigned long);
69
70 static int nfnl_queue_net_id __read_mostly;
71
72 #define INSTANCE_BUCKETS        16
73 struct nfnl_queue_net {
74         spinlock_t instances_lock;
75         struct hlist_head instance_table[INSTANCE_BUCKETS];
76 };
77
78 static struct nfnl_queue_net *nfnl_queue_pernet(struct net *net)
79 {
80         return net_generic(net, nfnl_queue_net_id);
81 }
82
83 static inline u_int8_t instance_hashfn(u_int16_t queue_num)
84 {
85         return ((queue_num >> 8) ^ queue_num) % INSTANCE_BUCKETS;
86 }
87
88 static struct nfqnl_instance *
89 instance_lookup(struct nfnl_queue_net *q, u_int16_t queue_num)
90 {
91         struct hlist_head *head;
92         struct nfqnl_instance *inst;
93
94         head = &q->instance_table[instance_hashfn(queue_num)];
95         hlist_for_each_entry_rcu(inst, head, hlist) {
96                 if (inst->queue_num == queue_num)
97                         return inst;
98         }
99         return NULL;
100 }
101
102 static struct nfqnl_instance *
103 instance_create(struct nfnl_queue_net *q, u_int16_t queue_num,
104                 int portid)
105 {
106         struct nfqnl_instance *inst;
107         unsigned int h;
108         int err;
109
110         spin_lock(&q->instances_lock);
111         if (instance_lookup(q, queue_num)) {
112                 err = -EEXIST;
113                 goto out_unlock;
114         }
115
116         inst = kzalloc(sizeof(*inst), GFP_ATOMIC);
117         if (!inst) {
118                 err = -ENOMEM;
119                 goto out_unlock;
120         }
121
122         inst->queue_num = queue_num;
123         inst->peer_portid = portid;
124         inst->queue_maxlen = NFQNL_QMAX_DEFAULT;
125         inst->copy_range = 0xffff;
126         inst->copy_mode = NFQNL_COPY_NONE;
127         spin_lock_init(&inst->lock);
128         INIT_LIST_HEAD(&inst->queue_list);
129
130         if (!try_module_get(THIS_MODULE)) {
131                 err = -EAGAIN;
132                 goto out_free;
133         }
134
135         h = instance_hashfn(queue_num);
136         hlist_add_head_rcu(&inst->hlist, &q->instance_table[h]);
137
138         spin_unlock(&q->instances_lock);
139
140         return inst;
141
142 out_free:
143         kfree(inst);
144 out_unlock:
145         spin_unlock(&q->instances_lock);
146         return ERR_PTR(err);
147 }
148
149 static void nfqnl_flush(struct nfqnl_instance *queue, nfqnl_cmpfn cmpfn,
150                         unsigned long data);
151
152 static void
153 instance_destroy_rcu(struct rcu_head *head)
154 {
155         struct nfqnl_instance *inst = container_of(head, struct nfqnl_instance,
156                                                    rcu);
157
158         nfqnl_flush(inst, NULL, 0);
159         kfree(inst);
160         module_put(THIS_MODULE);
161 }
162
163 static void
164 __instance_destroy(struct nfqnl_instance *inst)
165 {
166         hlist_del_rcu(&inst->hlist);
167         call_rcu(&inst->rcu, instance_destroy_rcu);
168 }
169
170 static void
171 instance_destroy(struct nfnl_queue_net *q, struct nfqnl_instance *inst)
172 {
173         spin_lock(&q->instances_lock);
174         __instance_destroy(inst);
175         spin_unlock(&q->instances_lock);
176 }
177
178 static inline void
179 __enqueue_entry(struct nfqnl_instance *queue, struct nf_queue_entry *entry)
180 {
181        list_add_tail(&entry->list, &queue->queue_list);
182        queue->queue_total++;
183 }
184
185 static void
186 __dequeue_entry(struct nfqnl_instance *queue, struct nf_queue_entry *entry)
187 {
188         list_del(&entry->list);
189         queue->queue_total--;
190 }
191
192 static struct nf_queue_entry *
193 find_dequeue_entry(struct nfqnl_instance *queue, unsigned int id)
194 {
195         struct nf_queue_entry *entry = NULL, *i;
196
197         spin_lock_bh(&queue->lock);
198
199         list_for_each_entry(i, &queue->queue_list, list) {
200                 if (i->id == id) {
201                         entry = i;
202                         break;
203                 }
204         }
205
206         if (entry)
207                 __dequeue_entry(queue, entry);
208
209         spin_unlock_bh(&queue->lock);
210
211         return entry;
212 }
213
214 static void
215 nfqnl_flush(struct nfqnl_instance *queue, nfqnl_cmpfn cmpfn, unsigned long data)
216 {
217         struct nf_queue_entry *entry, *next;
218
219         spin_lock_bh(&queue->lock);
220         list_for_each_entry_safe(entry, next, &queue->queue_list, list) {
221                 if (!cmpfn || cmpfn(entry, data)) {
222                         list_del(&entry->list);
223                         queue->queue_total--;
224                         nf_reinject(entry, NF_DROP);
225                 }
226         }
227         spin_unlock_bh(&queue->lock);
228 }
229
230 static void
231 nfqnl_zcopy(struct sk_buff *to, const struct sk_buff *from, int len, int hlen)
232 {
233         int i, j = 0;
234         int plen = 0; /* length of skb->head fragment */
235         struct page *page;
236         unsigned int offset;
237
238         /* dont bother with small payloads */
239         if (len <= skb_tailroom(to)) {
240                 skb_copy_bits(from, 0, skb_put(to, len), len);
241                 return;
242         }
243
244         if (hlen) {
245                 skb_copy_bits(from, 0, skb_put(to, hlen), hlen);
246                 len -= hlen;
247         } else {
248                 plen = min_t(int, skb_headlen(from), len);
249                 if (plen) {
250                         page = virt_to_head_page(from->head);
251                         offset = from->data - (unsigned char *)page_address(page);
252                         __skb_fill_page_desc(to, 0, page, offset, plen);
253                         get_page(page);
254                         j = 1;
255                         len -= plen;
256                 }
257         }
258
259         to->truesize += len + plen;
260         to->len += len + plen;
261         to->data_len += len + plen;
262
263         for (i = 0; i < skb_shinfo(from)->nr_frags; i++) {
264                 if (!len)
265                         break;
266                 skb_shinfo(to)->frags[j] = skb_shinfo(from)->frags[i];
267                 skb_shinfo(to)->frags[j].size = min_t(int, skb_shinfo(to)->frags[j].size, len);
268                 len -= skb_shinfo(to)->frags[j].size;
269                 skb_frag_ref(to, j);
270                 j++;
271         }
272         skb_shinfo(to)->nr_frags = j;
273 }
274
275 static struct sk_buff *
276 nfqnl_build_packet_message(struct nfqnl_instance *queue,
277                            struct nf_queue_entry *entry,
278                            __be32 **packet_id_ptr)
279 {
280         size_t size;
281         size_t data_len = 0, cap_len = 0;
282         int hlen = 0;
283         struct sk_buff *skb;
284         struct nlattr *nla;
285         struct nfqnl_msg_packet_hdr *pmsg;
286         struct nlmsghdr *nlh;
287         struct nfgenmsg *nfmsg;
288         struct sk_buff *entskb = entry->skb;
289         struct net_device *indev;
290         struct net_device *outdev;
291         struct nf_conn *ct = NULL;
292         enum ip_conntrack_info uninitialized_var(ctinfo);
293
294         size =    nlmsg_total_size(sizeof(struct nfgenmsg))
295                 + nla_total_size(sizeof(struct nfqnl_msg_packet_hdr))
296                 + nla_total_size(sizeof(u_int32_t))     /* ifindex */
297                 + nla_total_size(sizeof(u_int32_t))     /* ifindex */
298 #ifdef CONFIG_BRIDGE_NETFILTER
299                 + nla_total_size(sizeof(u_int32_t))     /* ifindex */
300                 + nla_total_size(sizeof(u_int32_t))     /* ifindex */
301 #endif
302                 + nla_total_size(sizeof(u_int32_t))     /* mark */
303                 + nla_total_size(sizeof(struct nfqnl_msg_packet_hw))
304                 + nla_total_size(sizeof(u_int32_t));    /* cap_len */
305
306         if (entskb->tstamp.tv64)
307                 size += nla_total_size(sizeof(struct nfqnl_msg_packet_timestamp));
308
309         outdev = entry->outdev;
310
311         switch ((enum nfqnl_config_mode)ACCESS_ONCE(queue->copy_mode)) {
312         case NFQNL_COPY_META:
313         case NFQNL_COPY_NONE:
314                 break;
315
316         case NFQNL_COPY_PACKET:
317                 if (entskb->ip_summed == CHECKSUM_PARTIAL &&
318                     skb_checksum_help(entskb))
319                         return NULL;
320
321                 data_len = ACCESS_ONCE(queue->copy_range);
322                 if (data_len == 0 || data_len > entskb->len)
323                         data_len = entskb->len;
324
325
326                 if (!entskb->head_frag ||
327                     skb_headlen(entskb) < L1_CACHE_BYTES ||
328                     skb_shinfo(entskb)->nr_frags >= MAX_SKB_FRAGS)
329                         hlen = skb_headlen(entskb);
330
331                 if (skb_has_frag_list(entskb))
332                         hlen = entskb->len;
333                 hlen = min_t(int, data_len, hlen);
334                 size += sizeof(struct nlattr) + hlen;
335                 cap_len = entskb->len;
336                 break;
337         }
338
339         if (queue->flags & NFQA_CFG_F_CONNTRACK)
340                 ct = nfqnl_ct_get(entskb, &size, &ctinfo);
341
342         skb = nfnetlink_alloc_skb(&init_net, size, queue->peer_portid,
343                                   GFP_ATOMIC);
344         if (!skb)
345                 return NULL;
346
347         nlh = nlmsg_put(skb, 0, 0,
348                         NFNL_SUBSYS_QUEUE << 8 | NFQNL_MSG_PACKET,
349                         sizeof(struct nfgenmsg), 0);
350         if (!nlh) {
351                 kfree_skb(skb);
352                 return NULL;
353         }
354         nfmsg = nlmsg_data(nlh);
355         nfmsg->nfgen_family = entry->pf;
356         nfmsg->version = NFNETLINK_V0;
357         nfmsg->res_id = htons(queue->queue_num);
358
359         nla = __nla_reserve(skb, NFQA_PACKET_HDR, sizeof(*pmsg));
360         pmsg = nla_data(nla);
361         pmsg->hw_protocol       = entskb->protocol;
362         pmsg->hook              = entry->hook;
363         *packet_id_ptr          = &pmsg->packet_id;
364
365         indev = entry->indev;
366         if (indev) {
367 #ifndef CONFIG_BRIDGE_NETFILTER
368                 if (nla_put_be32(skb, NFQA_IFINDEX_INDEV, htonl(indev->ifindex)))
369                         goto nla_put_failure;
370 #else
371                 if (entry->pf == PF_BRIDGE) {
372                         /* Case 1: indev is physical input device, we need to
373                          * look for bridge group (when called from
374                          * netfilter_bridge) */
375                         if (nla_put_be32(skb, NFQA_IFINDEX_PHYSINDEV,
376                                          htonl(indev->ifindex)) ||
377                         /* this is the bridge group "brX" */
378                         /* rcu_read_lock()ed by __nf_queue */
379                             nla_put_be32(skb, NFQA_IFINDEX_INDEV,
380                                          htonl(br_port_get_rcu(indev)->br->dev->ifindex)))
381                                 goto nla_put_failure;
382                 } else {
383                         /* Case 2: indev is bridge group, we need to look for
384                          * physical device (when called from ipv4) */
385                         if (nla_put_be32(skb, NFQA_IFINDEX_INDEV,
386                                          htonl(indev->ifindex)))
387                                 goto nla_put_failure;
388                         if (entskb->nf_bridge && entskb->nf_bridge->physindev &&
389                             nla_put_be32(skb, NFQA_IFINDEX_PHYSINDEV,
390                                          htonl(entskb->nf_bridge->physindev->ifindex)))
391                                 goto nla_put_failure;
392                 }
393 #endif
394         }
395
396         if (outdev) {
397 #ifndef CONFIG_BRIDGE_NETFILTER
398                 if (nla_put_be32(skb, NFQA_IFINDEX_OUTDEV, htonl(outdev->ifindex)))
399                         goto nla_put_failure;
400 #else
401                 if (entry->pf == PF_BRIDGE) {
402                         /* Case 1: outdev is physical output device, we need to
403                          * look for bridge group (when called from
404                          * netfilter_bridge) */
405                         if (nla_put_be32(skb, NFQA_IFINDEX_PHYSOUTDEV,
406                                          htonl(outdev->ifindex)) ||
407                         /* this is the bridge group "brX" */
408                         /* rcu_read_lock()ed by __nf_queue */
409                             nla_put_be32(skb, NFQA_IFINDEX_OUTDEV,
410                                          htonl(br_port_get_rcu(outdev)->br->dev->ifindex)))
411                                 goto nla_put_failure;
412                 } else {
413                         /* Case 2: outdev is bridge group, we need to look for
414                          * physical output device (when called from ipv4) */
415                         if (nla_put_be32(skb, NFQA_IFINDEX_OUTDEV,
416                                          htonl(outdev->ifindex)))
417                                 goto nla_put_failure;
418                         if (entskb->nf_bridge && entskb->nf_bridge->physoutdev &&
419                             nla_put_be32(skb, NFQA_IFINDEX_PHYSOUTDEV,
420                                          htonl(entskb->nf_bridge->physoutdev->ifindex)))
421                                 goto nla_put_failure;
422                 }
423 #endif
424         }
425
426         if (entskb->mark &&
427             nla_put_be32(skb, NFQA_MARK, htonl(entskb->mark)))
428                 goto nla_put_failure;
429
430         if (indev && entskb->dev &&
431             entskb->mac_header != entskb->network_header) {
432                 struct nfqnl_msg_packet_hw phw;
433                 int len = dev_parse_header(entskb, phw.hw_addr);
434                 if (len) {
435                         phw.hw_addrlen = htons(len);
436                         if (nla_put(skb, NFQA_HWADDR, sizeof(phw), &phw))
437                                 goto nla_put_failure;
438                 }
439         }
440
441         if (entskb->tstamp.tv64) {
442                 struct nfqnl_msg_packet_timestamp ts;
443                 struct timeval tv = ktime_to_timeval(entskb->tstamp);
444                 ts.sec = cpu_to_be64(tv.tv_sec);
445                 ts.usec = cpu_to_be64(tv.tv_usec);
446
447                 if (nla_put(skb, NFQA_TIMESTAMP, sizeof(ts), &ts))
448                         goto nla_put_failure;
449         }
450
451         if (ct && nfqnl_ct_put(skb, ct, ctinfo) < 0)
452                 goto nla_put_failure;
453
454         if (cap_len > 0 && nla_put_be32(skb, NFQA_CAP_LEN, htonl(cap_len)))
455                 goto nla_put_failure;
456
457         if (data_len) {
458                 struct nlattr *nla;
459
460                 if (skb_tailroom(skb) < sizeof(*nla) + hlen)
461                         goto nla_put_failure;
462
463                 nla = (struct nlattr *)skb_put(skb, sizeof(*nla));
464                 nla->nla_type = NFQA_PAYLOAD;
465                 nla->nla_len = nla_attr_size(data_len);
466
467                 nfqnl_zcopy(skb, entskb, data_len, hlen);
468         }
469
470         nlh->nlmsg_len = skb->len;
471         return skb;
472
473 nla_put_failure:
474         kfree_skb(skb);
475         net_err_ratelimited("nf_queue: error creating packet message\n");
476         return NULL;
477 }
478
479 static int
480 __nfqnl_enqueue_packet(struct net *net, struct nfqnl_instance *queue,
481                         struct nf_queue_entry *entry)
482 {
483         struct sk_buff *nskb;
484         int err = -ENOBUFS;
485         __be32 *packet_id_ptr;
486         int failopen = 0;
487
488         nskb = nfqnl_build_packet_message(queue, entry, &packet_id_ptr);
489         if (nskb == NULL) {
490                 err = -ENOMEM;
491                 goto err_out;
492         }
493         spin_lock_bh(&queue->lock);
494
495         if (!queue->peer_portid) {
496                 err = -EINVAL;
497                 goto err_out_free_nskb;
498         }
499         if (queue->queue_total >= queue->queue_maxlen) {
500                 if (queue->flags & NFQA_CFG_F_FAIL_OPEN) {
501                         failopen = 1;
502                         err = 0;
503                 } else {
504                         queue->queue_dropped++;
505                         net_warn_ratelimited("nf_queue: full at %d entries, dropping packets(s)\n",
506                                              queue->queue_total);
507                 }
508                 goto err_out_free_nskb;
509         }
510         entry->id = ++queue->id_sequence;
511         *packet_id_ptr = htonl(entry->id);
512
513         /* nfnetlink_unicast will either free the nskb or add it to a socket */
514         err = nfnetlink_unicast(nskb, net, queue->peer_portid, MSG_DONTWAIT);
515         if (err < 0) {
516                 queue->queue_user_dropped++;
517                 goto err_out_unlock;
518         }
519
520         __enqueue_entry(queue, entry);
521
522         spin_unlock_bh(&queue->lock);
523         return 0;
524
525 err_out_free_nskb:
526         kfree_skb(nskb);
527 err_out_unlock:
528         spin_unlock_bh(&queue->lock);
529         if (failopen)
530                 nf_reinject(entry, NF_ACCEPT);
531 err_out:
532         return err;
533 }
534
535 static struct nf_queue_entry *
536 nf_queue_entry_dup(struct nf_queue_entry *e)
537 {
538         struct nf_queue_entry *entry = kmemdup(e, e->size, GFP_ATOMIC);
539         if (entry) {
540                 if (nf_queue_entry_get_refs(entry))
541                         return entry;
542                 kfree(entry);
543         }
544         return NULL;
545 }
546
547 #ifdef CONFIG_BRIDGE_NETFILTER
548 /* When called from bridge netfilter, skb->data must point to MAC header
549  * before calling skb_gso_segment(). Else, original MAC header is lost
550  * and segmented skbs will be sent to wrong destination.
551  */
552 static void nf_bridge_adjust_skb_data(struct sk_buff *skb)
553 {
554         if (skb->nf_bridge)
555                 __skb_push(skb, skb->network_header - skb->mac_header);
556 }
557
558 static void nf_bridge_adjust_segmented_data(struct sk_buff *skb)
559 {
560         if (skb->nf_bridge)
561                 __skb_pull(skb, skb->network_header - skb->mac_header);
562 }
563 #else
564 #define nf_bridge_adjust_skb_data(s) do {} while (0)
565 #define nf_bridge_adjust_segmented_data(s) do {} while (0)
566 #endif
567
568 static void free_entry(struct nf_queue_entry *entry)
569 {
570         nf_queue_entry_release_refs(entry);
571         kfree(entry);
572 }
573
574 static int
575 __nfqnl_enqueue_packet_gso(struct net *net, struct nfqnl_instance *queue,
576                            struct sk_buff *skb, struct nf_queue_entry *entry)
577 {
578         int ret = -ENOMEM;
579         struct nf_queue_entry *entry_seg;
580
581         nf_bridge_adjust_segmented_data(skb);
582
583         if (skb->next == NULL) { /* last packet, no need to copy entry */
584                 struct sk_buff *gso_skb = entry->skb;
585                 entry->skb = skb;
586                 ret = __nfqnl_enqueue_packet(net, queue, entry);
587                 if (ret)
588                         entry->skb = gso_skb;
589                 return ret;
590         }
591
592         skb->next = NULL;
593
594         entry_seg = nf_queue_entry_dup(entry);
595         if (entry_seg) {
596                 entry_seg->skb = skb;
597                 ret = __nfqnl_enqueue_packet(net, queue, entry_seg);
598                 if (ret)
599                         free_entry(entry_seg);
600         }
601         return ret;
602 }
603
604 static int
605 nfqnl_enqueue_packet(struct nf_queue_entry *entry, unsigned int queuenum)
606 {
607         unsigned int queued;
608         struct nfqnl_instance *queue;
609         struct sk_buff *skb, *segs;
610         int err = -ENOBUFS;
611         struct net *net = dev_net(entry->indev ?
612                                   entry->indev : entry->outdev);
613         struct nfnl_queue_net *q = nfnl_queue_pernet(net);
614
615         /* rcu_read_lock()ed by nf_hook_slow() */
616         queue = instance_lookup(q, queuenum);
617         if (!queue)
618                 return -ESRCH;
619
620         if (queue->copy_mode == NFQNL_COPY_NONE)
621                 return -EINVAL;
622
623         if (!skb_is_gso(entry->skb))
624                 return __nfqnl_enqueue_packet(net, queue, entry);
625
626         skb = entry->skb;
627
628         switch (entry->pf) {
629         case NFPROTO_IPV4:
630                 skb->protocol = htons(ETH_P_IP);
631                 break;
632         case NFPROTO_IPV6:
633                 skb->protocol = htons(ETH_P_IPV6);
634                 break;
635         }
636
637         nf_bridge_adjust_skb_data(skb);
638         segs = skb_gso_segment(skb, 0);
639         /* Does not use PTR_ERR to limit the number of error codes that can be
640          * returned by nf_queue.  For instance, callers rely on -ECANCELED to
641          * mean 'ignore this hook'.
642          */
643         if (IS_ERR(segs))
644                 goto out_err;
645         queued = 0;
646         err = 0;
647         do {
648                 struct sk_buff *nskb = segs->next;
649                 if (err == 0)
650                         err = __nfqnl_enqueue_packet_gso(net, queue,
651                                                         segs, entry);
652                 if (err == 0)
653                         queued++;
654                 else
655                         kfree_skb(segs);
656                 segs = nskb;
657         } while (segs);
658
659         if (queued) {
660                 if (err) /* some segments are already queued */
661                         free_entry(entry);
662                 kfree_skb(skb);
663                 return 0;
664         }
665  out_err:
666         nf_bridge_adjust_segmented_data(skb);
667         return err;
668 }
669
670 static int
671 nfqnl_mangle(void *data, int data_len, struct nf_queue_entry *e, int diff)
672 {
673         struct sk_buff *nskb;
674
675         if (diff < 0) {
676                 if (pskb_trim(e->skb, data_len))
677                         return -ENOMEM;
678         } else if (diff > 0) {
679                 if (data_len > 0xFFFF)
680                         return -EINVAL;
681                 if (diff > skb_tailroom(e->skb)) {
682                         nskb = skb_copy_expand(e->skb, skb_headroom(e->skb),
683                                                diff, GFP_ATOMIC);
684                         if (!nskb) {
685                                 printk(KERN_WARNING "nf_queue: OOM "
686                                       "in mangle, dropping packet\n");
687                                 return -ENOMEM;
688                         }
689                         kfree_skb(e->skb);
690                         e->skb = nskb;
691                 }
692                 skb_put(e->skb, diff);
693         }
694         if (!skb_make_writable(e->skb, data_len))
695                 return -ENOMEM;
696         skb_copy_to_linear_data(e->skb, data, data_len);
697         e->skb->ip_summed = CHECKSUM_NONE;
698         return 0;
699 }
700
701 static int
702 nfqnl_set_mode(struct nfqnl_instance *queue,
703                unsigned char mode, unsigned int range)
704 {
705         int status = 0;
706
707         spin_lock_bh(&queue->lock);
708         switch (mode) {
709         case NFQNL_COPY_NONE:
710         case NFQNL_COPY_META:
711                 queue->copy_mode = mode;
712                 queue->copy_range = 0;
713                 break;
714
715         case NFQNL_COPY_PACKET:
716                 queue->copy_mode = mode;
717                 /* We're using struct nlattr which has 16bit nla_len. Note that
718                  * nla_len includes the header length. Thus, the maximum packet
719                  * length that we support is 65531 bytes. We send truncated
720                  * packets if the specified length is larger than that.
721                  */
722                 if (range > 0xffff - NLA_HDRLEN)
723                         queue->copy_range = 0xffff - NLA_HDRLEN;
724                 else
725                         queue->copy_range = range;
726                 break;
727
728         default:
729                 status = -EINVAL;
730
731         }
732         spin_unlock_bh(&queue->lock);
733
734         return status;
735 }
736
737 static int
738 dev_cmp(struct nf_queue_entry *entry, unsigned long ifindex)
739 {
740         if (entry->indev)
741                 if (entry->indev->ifindex == ifindex)
742                         return 1;
743         if (entry->outdev)
744                 if (entry->outdev->ifindex == ifindex)
745                         return 1;
746 #ifdef CONFIG_BRIDGE_NETFILTER
747         if (entry->skb->nf_bridge) {
748                 if (entry->skb->nf_bridge->physindev &&
749                     entry->skb->nf_bridge->physindev->ifindex == ifindex)
750                         return 1;
751                 if (entry->skb->nf_bridge->physoutdev &&
752                     entry->skb->nf_bridge->physoutdev->ifindex == ifindex)
753                         return 1;
754         }
755 #endif
756         return 0;
757 }
758
759 /* drop all packets with either indev or outdev == ifindex from all queue
760  * instances */
761 static void
762 nfqnl_dev_drop(struct net *net, int ifindex)
763 {
764         int i;
765         struct nfnl_queue_net *q = nfnl_queue_pernet(net);
766
767         rcu_read_lock();
768
769         for (i = 0; i < INSTANCE_BUCKETS; i++) {
770                 struct nfqnl_instance *inst;
771                 struct hlist_head *head = &q->instance_table[i];
772
773                 hlist_for_each_entry_rcu(inst, head, hlist)
774                         nfqnl_flush(inst, dev_cmp, ifindex);
775         }
776
777         rcu_read_unlock();
778 }
779
780 #define RCV_SKB_FAIL(err) do { netlink_ack(skb, nlh, (err)); return; } while (0)
781
782 static int
783 nfqnl_rcv_dev_event(struct notifier_block *this,
784                     unsigned long event, void *ptr)
785 {
786         struct net_device *dev = ptr;
787
788         /* Drop any packets associated with the downed device */
789         if (event == NETDEV_DOWN)
790                 nfqnl_dev_drop(dev_net(dev), dev->ifindex);
791         return NOTIFY_DONE;
792 }
793
794 static struct notifier_block nfqnl_dev_notifier = {
795         .notifier_call  = nfqnl_rcv_dev_event,
796 };
797
798 static int
799 nfqnl_rcv_nl_event(struct notifier_block *this,
800                    unsigned long event, void *ptr)
801 {
802         struct netlink_notify *n = ptr;
803         struct nfnl_queue_net *q = nfnl_queue_pernet(n->net);
804
805         if (event == NETLINK_URELEASE && n->protocol == NETLINK_NETFILTER) {
806                 int i;
807
808                 /* destroy all instances for this portid */
809                 spin_lock(&q->instances_lock);
810                 for (i = 0; i < INSTANCE_BUCKETS; i++) {
811                         struct hlist_node *t2;
812                         struct nfqnl_instance *inst;
813                         struct hlist_head *head = &q->instance_table[i];
814
815                         hlist_for_each_entry_safe(inst, t2, head, hlist) {
816                                 if (n->portid == inst->peer_portid)
817                                         __instance_destroy(inst);
818                         }
819                 }
820                 spin_unlock(&q->instances_lock);
821         }
822         return NOTIFY_DONE;
823 }
824
825 static struct notifier_block nfqnl_rtnl_notifier = {
826         .notifier_call  = nfqnl_rcv_nl_event,
827 };
828
829 static const struct nla_policy nfqa_verdict_policy[NFQA_MAX+1] = {
830         [NFQA_VERDICT_HDR]      = { .len = sizeof(struct nfqnl_msg_verdict_hdr) },
831         [NFQA_MARK]             = { .type = NLA_U32 },
832         [NFQA_PAYLOAD]          = { .type = NLA_UNSPEC },
833         [NFQA_CT]               = { .type = NLA_UNSPEC },
834 };
835
836 static const struct nla_policy nfqa_verdict_batch_policy[NFQA_MAX+1] = {
837         [NFQA_VERDICT_HDR]      = { .len = sizeof(struct nfqnl_msg_verdict_hdr) },
838         [NFQA_MARK]             = { .type = NLA_U32 },
839 };
840
841 static struct nfqnl_instance *
842 verdict_instance_lookup(struct nfnl_queue_net *q, u16 queue_num, int nlportid)
843 {
844         struct nfqnl_instance *queue;
845
846         queue = instance_lookup(q, queue_num);
847         if (!queue)
848                 return ERR_PTR(-ENODEV);
849
850         if (queue->peer_portid != nlportid)
851                 return ERR_PTR(-EPERM);
852
853         return queue;
854 }
855
856 static struct nfqnl_msg_verdict_hdr*
857 verdicthdr_get(const struct nlattr * const nfqa[])
858 {
859         struct nfqnl_msg_verdict_hdr *vhdr;
860         unsigned int verdict;
861
862         if (!nfqa[NFQA_VERDICT_HDR])
863                 return NULL;
864
865         vhdr = nla_data(nfqa[NFQA_VERDICT_HDR]);
866         verdict = ntohl(vhdr->verdict) & NF_VERDICT_MASK;
867         if (verdict > NF_MAX_VERDICT || verdict == NF_STOLEN)
868                 return NULL;
869         return vhdr;
870 }
871
872 static int nfq_id_after(unsigned int id, unsigned int max)
873 {
874         return (int)(id - max) > 0;
875 }
876
877 static int
878 nfqnl_recv_verdict_batch(struct sock *ctnl, struct sk_buff *skb,
879                    const struct nlmsghdr *nlh,
880                    const struct nlattr * const nfqa[])
881 {
882         struct nfgenmsg *nfmsg = nlmsg_data(nlh);
883         struct nf_queue_entry *entry, *tmp;
884         unsigned int verdict, maxid;
885         struct nfqnl_msg_verdict_hdr *vhdr;
886         struct nfqnl_instance *queue;
887         LIST_HEAD(batch_list);
888         u16 queue_num = ntohs(nfmsg->res_id);
889
890         struct net *net = sock_net(ctnl);
891         struct nfnl_queue_net *q = nfnl_queue_pernet(net);
892
893         queue = verdict_instance_lookup(q, queue_num,
894                                         NETLINK_CB(skb).portid);
895         if (IS_ERR(queue))
896                 return PTR_ERR(queue);
897
898         vhdr = verdicthdr_get(nfqa);
899         if (!vhdr)
900                 return -EINVAL;
901
902         verdict = ntohl(vhdr->verdict);
903         maxid = ntohl(vhdr->id);
904
905         spin_lock_bh(&queue->lock);
906
907         list_for_each_entry_safe(entry, tmp, &queue->queue_list, list) {
908                 if (nfq_id_after(entry->id, maxid))
909                         break;
910                 __dequeue_entry(queue, entry);
911                 list_add_tail(&entry->list, &batch_list);
912         }
913
914         spin_unlock_bh(&queue->lock);
915
916         if (list_empty(&batch_list))
917                 return -ENOENT;
918
919         list_for_each_entry_safe(entry, tmp, &batch_list, list) {
920                 if (nfqa[NFQA_MARK])
921                         entry->skb->mark = ntohl(nla_get_be32(nfqa[NFQA_MARK]));
922                 nf_reinject(entry, verdict);
923         }
924         return 0;
925 }
926
927 static int
928 nfqnl_recv_verdict(struct sock *ctnl, struct sk_buff *skb,
929                    const struct nlmsghdr *nlh,
930                    const struct nlattr * const nfqa[])
931 {
932         struct nfgenmsg *nfmsg = nlmsg_data(nlh);
933         u_int16_t queue_num = ntohs(nfmsg->res_id);
934
935         struct nfqnl_msg_verdict_hdr *vhdr;
936         struct nfqnl_instance *queue;
937         unsigned int verdict;
938         struct nf_queue_entry *entry;
939         enum ip_conntrack_info uninitialized_var(ctinfo);
940         struct nf_conn *ct = NULL;
941
942         struct net *net = sock_net(ctnl);
943         struct nfnl_queue_net *q = nfnl_queue_pernet(net);
944
945         queue = instance_lookup(q, queue_num);
946         if (!queue)
947                 queue = verdict_instance_lookup(q, queue_num,
948                                                 NETLINK_CB(skb).portid);
949         if (IS_ERR(queue))
950                 return PTR_ERR(queue);
951
952         vhdr = verdicthdr_get(nfqa);
953         if (!vhdr)
954                 return -EINVAL;
955
956         verdict = ntohl(vhdr->verdict);
957
958         entry = find_dequeue_entry(queue, ntohl(vhdr->id));
959         if (entry == NULL)
960                 return -ENOENT;
961
962         rcu_read_lock();
963         if (nfqa[NFQA_CT] && (queue->flags & NFQA_CFG_F_CONNTRACK))
964                 ct = nfqnl_ct_parse(entry->skb, nfqa[NFQA_CT], &ctinfo);
965
966         if (nfqa[NFQA_PAYLOAD]) {
967                 u16 payload_len = nla_len(nfqa[NFQA_PAYLOAD]);
968                 int diff = payload_len - entry->skb->len;
969
970                 if (nfqnl_mangle(nla_data(nfqa[NFQA_PAYLOAD]),
971                                  payload_len, entry, diff) < 0)
972                         verdict = NF_DROP;
973
974                 if (ct)
975                         nfqnl_ct_seq_adjust(skb, ct, ctinfo, diff);
976         }
977         rcu_read_unlock();
978
979         if (nfqa[NFQA_MARK])
980                 entry->skb->mark = ntohl(nla_get_be32(nfqa[NFQA_MARK]));
981
982         nf_reinject(entry, verdict);
983         return 0;
984 }
985
986 static int
987 nfqnl_recv_unsupp(struct sock *ctnl, struct sk_buff *skb,
988                   const struct nlmsghdr *nlh,
989                   const struct nlattr * const nfqa[])
990 {
991         return -ENOTSUPP;
992 }
993
994 static const struct nla_policy nfqa_cfg_policy[NFQA_CFG_MAX+1] = {
995         [NFQA_CFG_CMD]          = { .len = sizeof(struct nfqnl_msg_config_cmd) },
996         [NFQA_CFG_PARAMS]       = { .len = sizeof(struct nfqnl_msg_config_params) },
997 };
998
999 static const struct nf_queue_handler nfqh = {
1000         .outfn  = &nfqnl_enqueue_packet,
1001 };
1002
1003 static int
1004 nfqnl_recv_config(struct sock *ctnl, struct sk_buff *skb,
1005                   const struct nlmsghdr *nlh,
1006                   const struct nlattr * const nfqa[])
1007 {
1008         struct nfgenmsg *nfmsg = nlmsg_data(nlh);
1009         u_int16_t queue_num = ntohs(nfmsg->res_id);
1010         struct nfqnl_instance *queue;
1011         struct nfqnl_msg_config_cmd *cmd = NULL;
1012         struct net *net = sock_net(ctnl);
1013         struct nfnl_queue_net *q = nfnl_queue_pernet(net);
1014         int ret = 0;
1015
1016         if (nfqa[NFQA_CFG_CMD]) {
1017                 cmd = nla_data(nfqa[NFQA_CFG_CMD]);
1018
1019                 /* Obsolete commands without queue context */
1020                 switch (cmd->command) {
1021                 case NFQNL_CFG_CMD_PF_BIND: return 0;
1022                 case NFQNL_CFG_CMD_PF_UNBIND: return 0;
1023                 }
1024         }
1025
1026         rcu_read_lock();
1027         queue = instance_lookup(q, queue_num);
1028         if (queue && queue->peer_portid != NETLINK_CB(skb).portid) {
1029                 ret = -EPERM;
1030                 goto err_out_unlock;
1031         }
1032
1033         if (cmd != NULL) {
1034                 switch (cmd->command) {
1035                 case NFQNL_CFG_CMD_BIND:
1036                         if (queue) {
1037                                 ret = -EBUSY;
1038                                 goto err_out_unlock;
1039                         }
1040                         queue = instance_create(q, queue_num,
1041                                                 NETLINK_CB(skb).portid);
1042                         if (IS_ERR(queue)) {
1043                                 ret = PTR_ERR(queue);
1044                                 goto err_out_unlock;
1045                         }
1046                         break;
1047                 case NFQNL_CFG_CMD_UNBIND:
1048                         if (!queue) {
1049                                 ret = -ENODEV;
1050                                 goto err_out_unlock;
1051                         }
1052                         instance_destroy(q, queue);
1053                         break;
1054                 case NFQNL_CFG_CMD_PF_BIND:
1055                 case NFQNL_CFG_CMD_PF_UNBIND:
1056                         break;
1057                 default:
1058                         ret = -ENOTSUPP;
1059                         break;
1060                 }
1061         }
1062
1063         if (nfqa[NFQA_CFG_PARAMS]) {
1064                 struct nfqnl_msg_config_params *params;
1065
1066                 if (!queue) {
1067                         ret = -ENODEV;
1068                         goto err_out_unlock;
1069                 }
1070                 params = nla_data(nfqa[NFQA_CFG_PARAMS]);
1071                 nfqnl_set_mode(queue, params->copy_mode,
1072                                 ntohl(params->copy_range));
1073         }
1074
1075         if (nfqa[NFQA_CFG_QUEUE_MAXLEN]) {
1076                 __be32 *queue_maxlen;
1077
1078                 if (!queue) {
1079                         ret = -ENODEV;
1080                         goto err_out_unlock;
1081                 }
1082                 queue_maxlen = nla_data(nfqa[NFQA_CFG_QUEUE_MAXLEN]);
1083                 spin_lock_bh(&queue->lock);
1084                 queue->queue_maxlen = ntohl(*queue_maxlen);
1085                 spin_unlock_bh(&queue->lock);
1086         }
1087
1088         if (nfqa[NFQA_CFG_FLAGS]) {
1089                 __u32 flags, mask;
1090
1091                 if (!queue) {
1092                         ret = -ENODEV;
1093                         goto err_out_unlock;
1094                 }
1095
1096                 if (!nfqa[NFQA_CFG_MASK]) {
1097                         /* A mask is needed to specify which flags are being
1098                          * changed.
1099                          */
1100                         ret = -EINVAL;
1101                         goto err_out_unlock;
1102                 }
1103
1104                 flags = ntohl(nla_get_be32(nfqa[NFQA_CFG_FLAGS]));
1105                 mask = ntohl(nla_get_be32(nfqa[NFQA_CFG_MASK]));
1106
1107                 if (flags >= NFQA_CFG_F_MAX) {
1108                         ret = -EOPNOTSUPP;
1109                         goto err_out_unlock;
1110                 }
1111
1112                 spin_lock_bh(&queue->lock);
1113                 queue->flags &= ~mask;
1114                 queue->flags |= flags & mask;
1115                 spin_unlock_bh(&queue->lock);
1116         }
1117
1118 err_out_unlock:
1119         rcu_read_unlock();
1120         return ret;
1121 }
1122
1123 static const struct nfnl_callback nfqnl_cb[NFQNL_MSG_MAX] = {
1124         [NFQNL_MSG_PACKET]      = { .call_rcu = nfqnl_recv_unsupp,
1125                                     .attr_count = NFQA_MAX, },
1126         [NFQNL_MSG_VERDICT]     = { .call_rcu = nfqnl_recv_verdict,
1127                                     .attr_count = NFQA_MAX,
1128                                     .policy = nfqa_verdict_policy },
1129         [NFQNL_MSG_CONFIG]      = { .call = nfqnl_recv_config,
1130                                     .attr_count = NFQA_CFG_MAX,
1131                                     .policy = nfqa_cfg_policy },
1132         [NFQNL_MSG_VERDICT_BATCH]={ .call_rcu = nfqnl_recv_verdict_batch,
1133                                     .attr_count = NFQA_MAX,
1134                                     .policy = nfqa_verdict_batch_policy },
1135 };
1136
1137 static const struct nfnetlink_subsystem nfqnl_subsys = {
1138         .name           = "nf_queue",
1139         .subsys_id      = NFNL_SUBSYS_QUEUE,
1140         .cb_count       = NFQNL_MSG_MAX,
1141         .cb             = nfqnl_cb,
1142 };
1143
1144 #ifdef CONFIG_PROC_FS
1145 struct iter_state {
1146         struct seq_net_private p;
1147         unsigned int bucket;
1148 };
1149
1150 static struct hlist_node *get_first(struct seq_file *seq)
1151 {
1152         struct iter_state *st = seq->private;
1153         struct net *net;
1154         struct nfnl_queue_net *q;
1155
1156         if (!st)
1157                 return NULL;
1158
1159         net = seq_file_net(seq);
1160         q = nfnl_queue_pernet(net);
1161         for (st->bucket = 0; st->bucket < INSTANCE_BUCKETS; st->bucket++) {
1162                 if (!hlist_empty(&q->instance_table[st->bucket]))
1163                         return q->instance_table[st->bucket].first;
1164         }
1165         return NULL;
1166 }
1167
1168 static struct hlist_node *get_next(struct seq_file *seq, struct hlist_node *h)
1169 {
1170         struct iter_state *st = seq->private;
1171         struct net *net = seq_file_net(seq);
1172
1173         h = h->next;
1174         while (!h) {
1175                 struct nfnl_queue_net *q;
1176
1177                 if (++st->bucket >= INSTANCE_BUCKETS)
1178                         return NULL;
1179
1180                 q = nfnl_queue_pernet(net);
1181                 h = q->instance_table[st->bucket].first;
1182         }
1183         return h;
1184 }
1185
1186 static struct hlist_node *get_idx(struct seq_file *seq, loff_t pos)
1187 {
1188         struct hlist_node *head;
1189         head = get_first(seq);
1190
1191         if (head)
1192                 while (pos && (head = get_next(seq, head)))
1193                         pos--;
1194         return pos ? NULL : head;
1195 }
1196
1197 static void *seq_start(struct seq_file *s, loff_t *pos)
1198         __acquires(nfnl_queue_pernet(seq_file_net(s))->instances_lock)
1199 {
1200         spin_lock(&nfnl_queue_pernet(seq_file_net(s))->instances_lock);
1201         return get_idx(s, *pos);
1202 }
1203
1204 static void *seq_next(struct seq_file *s, void *v, loff_t *pos)
1205 {
1206         (*pos)++;
1207         return get_next(s, v);
1208 }
1209
1210 static void seq_stop(struct seq_file *s, void *v)
1211         __releases(nfnl_queue_pernet(seq_file_net(s))->instances_lock)
1212 {
1213         spin_unlock(&nfnl_queue_pernet(seq_file_net(s))->instances_lock);
1214 }
1215
1216 static int seq_show(struct seq_file *s, void *v)
1217 {
1218         const struct nfqnl_instance *inst = v;
1219
1220         return seq_printf(s, "%5d %6d %5d %1d %5d %5d %5d %8d %2d\n",
1221                           inst->queue_num,
1222                           inst->peer_portid, inst->queue_total,
1223                           inst->copy_mode, inst->copy_range,
1224                           inst->queue_dropped, inst->queue_user_dropped,
1225                           inst->id_sequence, 1);
1226 }
1227
1228 static const struct seq_operations nfqnl_seq_ops = {
1229         .start  = seq_start,
1230         .next   = seq_next,
1231         .stop   = seq_stop,
1232         .show   = seq_show,
1233 };
1234
1235 static int nfqnl_open(struct inode *inode, struct file *file)
1236 {
1237         return seq_open_net(inode, file, &nfqnl_seq_ops,
1238                         sizeof(struct iter_state));
1239 }
1240
1241 static const struct file_operations nfqnl_file_ops = {
1242         .owner   = THIS_MODULE,
1243         .open    = nfqnl_open,
1244         .read    = seq_read,
1245         .llseek  = seq_lseek,
1246         .release = seq_release_net,
1247 };
1248
1249 #endif /* PROC_FS */
1250
1251 static int __net_init nfnl_queue_net_init(struct net *net)
1252 {
1253         unsigned int i;
1254         struct nfnl_queue_net *q = nfnl_queue_pernet(net);
1255
1256         for (i = 0; i < INSTANCE_BUCKETS; i++)
1257                 INIT_HLIST_HEAD(&q->instance_table[i]);
1258
1259         spin_lock_init(&q->instances_lock);
1260
1261 #ifdef CONFIG_PROC_FS
1262         if (!proc_create("nfnetlink_queue", 0440,
1263                          net->nf.proc_netfilter, &nfqnl_file_ops))
1264                 return -ENOMEM;
1265 #endif
1266         return 0;
1267 }
1268
1269 static void __net_exit nfnl_queue_net_exit(struct net *net)
1270 {
1271         remove_proc_entry("nfnetlink_queue", net->nf.proc_netfilter);
1272 }
1273
1274 static struct pernet_operations nfnl_queue_net_ops = {
1275         .init   = nfnl_queue_net_init,
1276         .exit   = nfnl_queue_net_exit,
1277         .id     = &nfnl_queue_net_id,
1278         .size   = sizeof(struct nfnl_queue_net),
1279 };
1280
1281 static int __init nfnetlink_queue_init(void)
1282 {
1283         int status = -ENOMEM;
1284
1285         netlink_register_notifier(&nfqnl_rtnl_notifier);
1286         status = nfnetlink_subsys_register(&nfqnl_subsys);
1287         if (status < 0) {
1288                 pr_err("nf_queue: failed to create netlink socket\n");
1289                 goto cleanup_netlink_notifier;
1290         }
1291
1292         status = register_pernet_subsys(&nfnl_queue_net_ops);
1293         if (status < 0) {
1294                 pr_err("nf_queue: failed to register pernet ops\n");
1295                 goto cleanup_subsys;
1296         }
1297         register_netdevice_notifier(&nfqnl_dev_notifier);
1298         nf_register_queue_handler(&nfqh);
1299         return status;
1300
1301 cleanup_subsys:
1302         nfnetlink_subsys_unregister(&nfqnl_subsys);
1303 cleanup_netlink_notifier:
1304         netlink_unregister_notifier(&nfqnl_rtnl_notifier);
1305         return status;
1306 }
1307
1308 static void __exit nfnetlink_queue_fini(void)
1309 {
1310         nf_unregister_queue_handler();
1311         unregister_netdevice_notifier(&nfqnl_dev_notifier);
1312         unregister_pernet_subsys(&nfnl_queue_net_ops);
1313         nfnetlink_subsys_unregister(&nfqnl_subsys);
1314         netlink_unregister_notifier(&nfqnl_rtnl_notifier);
1315
1316         rcu_barrier(); /* Wait for completion of call_rcu()'s */
1317 }
1318
1319 MODULE_DESCRIPTION("netfilter packet queue handler");
1320 MODULE_AUTHOR("Harald Welte <laforge@netfilter.org>");
1321 MODULE_LICENSE("GPL");
1322 MODULE_ALIAS_NFNL_SUBSYS(NFNL_SUBSYS_QUEUE);
1323
1324 module_init(nfnetlink_queue_init);
1325 module_exit(nfnetlink_queue_fini);