[NETFILTER]: Use pskb_trim in {ip,ip6,nfnetlink}_queue
[safe/jmp/linux-2.6] / net / netfilter / nfnetlink_queue.c
1 /*
2  * This is a module which is used for queueing packets and communicating with
3  * userspace via nfetlink.
4  *
5  * (C) 2005 by Harald Welte <laforge@netfilter.org>
6  *
7  * Based on the old ipv4-only ip_queue.c:
8  * (C) 2000-2002 James Morris <jmorris@intercode.com.au>
9  * (C) 2003-2005 Netfilter Core Team <coreteam@netfilter.org>
10  *
11  * This program is free software; you can redistribute it and/or modify
12  * it under the terms of the GNU General Public License version 2 as
13  * published by the Free Software Foundation.
14  *
15  */
16 #include <linux/module.h>
17 #include <linux/skbuff.h>
18 #include <linux/init.h>
19 #include <linux/spinlock.h>
20 #include <linux/notifier.h>
21 #include <linux/netdevice.h>
22 #include <linux/netfilter.h>
23 #include <linux/proc_fs.h>
24 #include <linux/netfilter_ipv4.h>
25 #include <linux/netfilter_ipv6.h>
26 #include <linux/netfilter/nfnetlink.h>
27 #include <linux/netfilter/nfnetlink_queue.h>
28 #include <linux/list.h>
29 #include <net/sock.h>
30
31 #include <asm/atomic.h>
32
33 #ifdef CONFIG_BRIDGE_NETFILTER
34 #include "../bridge/br_private.h"
35 #endif
36
37 #define NFQNL_QMAX_DEFAULT 1024
38
39 #if 0
40 #define QDEBUG(x, args ...)     printk(KERN_DEBUG "%s(%d):%s(): " x,       \
41                                         __FILE__, __LINE__, __FUNCTION__,  \
42                                         ## args)
43 #else
44 #define QDEBUG(x, ...)
45 #endif
46
47 struct nfqnl_queue_entry {
48         struct list_head list;
49         struct nf_info *info;
50         struct sk_buff *skb;
51         unsigned int id;
52 };
53
54 struct nfqnl_instance {
55         struct hlist_node hlist;                /* global list of queues */
56         atomic_t use;
57
58         int peer_pid;
59         unsigned int queue_maxlen;
60         unsigned int copy_range;
61         unsigned int queue_total;
62         unsigned int queue_dropped;
63         unsigned int queue_user_dropped;
64
65         atomic_t id_sequence;                   /* 'sequence' of pkt ids */
66
67         u_int16_t queue_num;                    /* number of this queue */
68         u_int8_t copy_mode;
69
70         spinlock_t lock;
71
72         struct list_head queue_list;            /* packets in queue */
73 };
74
75 typedef int (*nfqnl_cmpfn)(struct nfqnl_queue_entry *, unsigned long);
76
77 static DEFINE_RWLOCK(instances_lock);
78
79 #define INSTANCE_BUCKETS        16
80 static struct hlist_head instance_table[INSTANCE_BUCKETS];
81
82 static inline u_int8_t instance_hashfn(u_int16_t queue_num)
83 {
84         return ((queue_num >> 8) | queue_num) % INSTANCE_BUCKETS;
85 }
86
87 static struct nfqnl_instance *
88 __instance_lookup(u_int16_t queue_num)
89 {
90         struct hlist_head *head;
91         struct hlist_node *pos;
92         struct nfqnl_instance *inst;
93
94         head = &instance_table[instance_hashfn(queue_num)];
95         hlist_for_each_entry(inst, pos, 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_lookup_get(u_int16_t queue_num)
104 {
105         struct nfqnl_instance *inst;
106
107         read_lock_bh(&instances_lock);
108         inst = __instance_lookup(queue_num);
109         if (inst)
110                 atomic_inc(&inst->use);
111         read_unlock_bh(&instances_lock);
112
113         return inst;
114 }
115
116 static void
117 instance_put(struct nfqnl_instance *inst)
118 {
119         if (inst && atomic_dec_and_test(&inst->use)) {
120                 QDEBUG("kfree(inst=%p)\n", inst);
121                 kfree(inst);
122         }
123 }
124
125 static struct nfqnl_instance *
126 instance_create(u_int16_t queue_num, int pid)
127 {
128         struct nfqnl_instance *inst;
129
130         QDEBUG("entering for queue_num=%u, pid=%d\n", queue_num, pid);
131
132         write_lock_bh(&instances_lock); 
133         if (__instance_lookup(queue_num)) {
134                 inst = NULL;
135                 QDEBUG("aborting, instance already exists\n");
136                 goto out_unlock;
137         }
138
139         inst = kzalloc(sizeof(*inst), GFP_ATOMIC);
140         if (!inst)
141                 goto out_unlock;
142
143         inst->queue_num = queue_num;
144         inst->peer_pid = pid;
145         inst->queue_maxlen = NFQNL_QMAX_DEFAULT;
146         inst->copy_range = 0xfffff;
147         inst->copy_mode = NFQNL_COPY_NONE;
148         atomic_set(&inst->id_sequence, 0);
149         /* needs to be two, since we _put() after creation */
150         atomic_set(&inst->use, 2);
151         spin_lock_init(&inst->lock);
152         INIT_LIST_HEAD(&inst->queue_list);
153
154         if (!try_module_get(THIS_MODULE))
155                 goto out_free;
156
157         hlist_add_head(&inst->hlist, 
158                        &instance_table[instance_hashfn(queue_num)]);
159
160         write_unlock_bh(&instances_lock);
161
162         QDEBUG("successfully created new instance\n");
163
164         return inst;
165
166 out_free:
167         kfree(inst);
168 out_unlock:
169         write_unlock_bh(&instances_lock);
170         return NULL;
171 }
172
173 static void nfqnl_flush(struct nfqnl_instance *queue, int verdict);
174
175 static void
176 _instance_destroy2(struct nfqnl_instance *inst, int lock)
177 {
178         /* first pull it out of the global list */
179         if (lock)
180                 write_lock_bh(&instances_lock);
181
182         QDEBUG("removing instance %p (queuenum=%u) from hash\n",
183                 inst, inst->queue_num);
184         hlist_del(&inst->hlist);
185
186         if (lock)
187                 write_unlock_bh(&instances_lock);
188
189         /* then flush all pending skbs from the queue */
190         nfqnl_flush(inst, NF_DROP);
191
192         /* and finally put the refcount */
193         instance_put(inst);
194
195         module_put(THIS_MODULE);
196 }
197
198 static inline void
199 __instance_destroy(struct nfqnl_instance *inst)
200 {
201         _instance_destroy2(inst, 0);
202 }
203
204 static inline void
205 instance_destroy(struct nfqnl_instance *inst)
206 {
207         _instance_destroy2(inst, 1);
208 }
209
210
211
212 static void
213 issue_verdict(struct nfqnl_queue_entry *entry, int verdict)
214 {
215         QDEBUG("entering for entry %p, verdict %u\n", entry, verdict);
216
217         /* TCP input path (and probably other bits) assume to be called
218          * from softirq context, not from syscall, like issue_verdict is
219          * called.  TCP input path deadlocks with locks taken from timer
220          * softirq, e.g.  We therefore emulate this by local_bh_disable() */
221
222         local_bh_disable();
223         nf_reinject(entry->skb, entry->info, verdict);
224         local_bh_enable();
225
226         kfree(entry);
227 }
228
229 static inline void
230 __enqueue_entry(struct nfqnl_instance *queue,
231                       struct nfqnl_queue_entry *entry)
232 {
233        list_add(&entry->list, &queue->queue_list);
234        queue->queue_total++;
235 }
236
237 /*
238  * Find and return a queued entry matched by cmpfn, or return the last
239  * entry if cmpfn is NULL.
240  */
241 static inline struct nfqnl_queue_entry *
242 __find_entry(struct nfqnl_instance *queue, nfqnl_cmpfn cmpfn, 
243                    unsigned long data)
244 {
245         struct list_head *p;
246
247         list_for_each_prev(p, &queue->queue_list) {
248                 struct nfqnl_queue_entry *entry = (struct nfqnl_queue_entry *)p;
249                 
250                 if (!cmpfn || cmpfn(entry, data))
251                         return entry;
252         }
253         return NULL;
254 }
255
256 static inline void
257 __dequeue_entry(struct nfqnl_instance *q, struct nfqnl_queue_entry *entry)
258 {
259         list_del(&entry->list);
260         q->queue_total--;
261 }
262
263 static inline struct nfqnl_queue_entry *
264 __find_dequeue_entry(struct nfqnl_instance *queue,
265                      nfqnl_cmpfn cmpfn, unsigned long data)
266 {
267         struct nfqnl_queue_entry *entry;
268
269         entry = __find_entry(queue, cmpfn, data);
270         if (entry == NULL)
271                 return NULL;
272
273         __dequeue_entry(queue, entry);
274         return entry;
275 }
276
277
278 static inline void
279 __nfqnl_flush(struct nfqnl_instance *queue, int verdict)
280 {
281         struct nfqnl_queue_entry *entry;
282         
283         while ((entry = __find_dequeue_entry(queue, NULL, 0)))
284                 issue_verdict(entry, verdict);
285 }
286
287 static inline int
288 __nfqnl_set_mode(struct nfqnl_instance *queue,
289                  unsigned char mode, unsigned int range)
290 {
291         int status = 0;
292         
293         switch (mode) {
294         case NFQNL_COPY_NONE:
295         case NFQNL_COPY_META:
296                 queue->copy_mode = mode;
297                 queue->copy_range = 0;
298                 break;
299                 
300         case NFQNL_COPY_PACKET:
301                 queue->copy_mode = mode;
302                 /* we're using struct nfattr which has 16bit nfa_len */
303                 if (range > 0xffff)
304                         queue->copy_range = 0xffff;
305                 else
306                         queue->copy_range = range;
307                 break;
308                 
309         default:
310                 status = -EINVAL;
311
312         }
313         return status;
314 }
315
316 static struct nfqnl_queue_entry *
317 find_dequeue_entry(struct nfqnl_instance *queue,
318                          nfqnl_cmpfn cmpfn, unsigned long data)
319 {
320         struct nfqnl_queue_entry *entry;
321         
322         spin_lock_bh(&queue->lock);
323         entry = __find_dequeue_entry(queue, cmpfn, data);
324         spin_unlock_bh(&queue->lock);
325
326         return entry;
327 }
328
329 static void
330 nfqnl_flush(struct nfqnl_instance *queue, int verdict)
331 {
332         spin_lock_bh(&queue->lock);
333         __nfqnl_flush(queue, verdict);
334         spin_unlock_bh(&queue->lock);
335 }
336
337 static struct sk_buff *
338 nfqnl_build_packet_message(struct nfqnl_instance *queue,
339                            struct nfqnl_queue_entry *entry, int *errp)
340 {
341         unsigned char *old_tail;
342         size_t size;
343         size_t data_len = 0;
344         struct sk_buff *skb;
345         struct nfqnl_msg_packet_hdr pmsg;
346         struct nlmsghdr *nlh;
347         struct nfgenmsg *nfmsg;
348         struct nf_info *entinf = entry->info;
349         struct sk_buff *entskb = entry->skb;
350         struct net_device *indev;
351         struct net_device *outdev;
352         unsigned int tmp_uint;
353
354         QDEBUG("entered\n");
355
356         /* all macros expand to constant values at compile time */
357         size =    NLMSG_SPACE(sizeof(struct nfgenmsg)) +
358                 + NFA_SPACE(sizeof(struct nfqnl_msg_packet_hdr))
359                 + NFA_SPACE(sizeof(u_int32_t))  /* ifindex */
360                 + NFA_SPACE(sizeof(u_int32_t))  /* ifindex */
361 #ifdef CONFIG_BRIDGE_NETFILTER
362                 + NFA_SPACE(sizeof(u_int32_t))  /* ifindex */
363                 + NFA_SPACE(sizeof(u_int32_t))  /* ifindex */
364 #endif
365                 + NFA_SPACE(sizeof(u_int32_t))  /* mark */
366                 + NFA_SPACE(sizeof(struct nfqnl_msg_packet_hw))
367                 + NFA_SPACE(sizeof(struct nfqnl_msg_packet_timestamp));
368
369         outdev = entinf->outdev;
370
371         spin_lock_bh(&queue->lock);
372         
373         switch (queue->copy_mode) {
374         case NFQNL_COPY_META:
375         case NFQNL_COPY_NONE:
376                 data_len = 0;
377                 break;
378         
379         case NFQNL_COPY_PACKET:
380                 if ((entskb->ip_summed == CHECKSUM_PARTIAL ||
381                      entskb->ip_summed == CHECKSUM_COMPLETE) &&
382                     (*errp = skb_checksum_help(entskb))) {
383                         spin_unlock_bh(&queue->lock);
384                         return NULL;
385                 }
386                 if (queue->copy_range == 0 
387                     || queue->copy_range > entskb->len)
388                         data_len = entskb->len;
389                 else
390                         data_len = queue->copy_range;
391                 
392                 size += NFA_SPACE(data_len);
393                 break;
394         
395         default:
396                 *errp = -EINVAL;
397                 spin_unlock_bh(&queue->lock);
398                 return NULL;
399         }
400
401         spin_unlock_bh(&queue->lock);
402
403         skb = alloc_skb(size, GFP_ATOMIC);
404         if (!skb)
405                 goto nlmsg_failure;
406                 
407         old_tail= skb->tail;
408         nlh = NLMSG_PUT(skb, 0, 0, 
409                         NFNL_SUBSYS_QUEUE << 8 | NFQNL_MSG_PACKET,
410                         sizeof(struct nfgenmsg));
411         nfmsg = NLMSG_DATA(nlh);
412         nfmsg->nfgen_family = entinf->pf;
413         nfmsg->version = NFNETLINK_V0;
414         nfmsg->res_id = htons(queue->queue_num);
415
416         pmsg.packet_id          = htonl(entry->id);
417         pmsg.hw_protocol        = entskb->protocol;
418         pmsg.hook               = entinf->hook;
419
420         NFA_PUT(skb, NFQA_PACKET_HDR, sizeof(pmsg), &pmsg);
421
422         indev = entinf->indev;
423         if (indev) {
424                 tmp_uint = htonl(indev->ifindex);
425 #ifndef CONFIG_BRIDGE_NETFILTER
426                 NFA_PUT(skb, NFQA_IFINDEX_INDEV, sizeof(tmp_uint), &tmp_uint);
427 #else
428                 if (entinf->pf == PF_BRIDGE) {
429                         /* Case 1: indev is physical input device, we need to
430                          * look for bridge group (when called from 
431                          * netfilter_bridge) */
432                         NFA_PUT(skb, NFQA_IFINDEX_PHYSINDEV, sizeof(tmp_uint), 
433                                 &tmp_uint);
434                         /* this is the bridge group "brX" */
435                         tmp_uint = htonl(indev->br_port->br->dev->ifindex);
436                         NFA_PUT(skb, NFQA_IFINDEX_INDEV, sizeof(tmp_uint),
437                                 &tmp_uint);
438                 } else {
439                         /* Case 2: indev is bridge group, we need to look for
440                          * physical device (when called from ipv4) */
441                         NFA_PUT(skb, NFQA_IFINDEX_INDEV, sizeof(tmp_uint),
442                                 &tmp_uint);
443                         if (entskb->nf_bridge
444                             && entskb->nf_bridge->physindev) {
445                                 tmp_uint = htonl(entskb->nf_bridge->physindev->ifindex);
446                                 NFA_PUT(skb, NFQA_IFINDEX_PHYSINDEV,
447                                         sizeof(tmp_uint), &tmp_uint);
448                         }
449                 }
450 #endif
451         }
452
453         if (outdev) {
454                 tmp_uint = htonl(outdev->ifindex);
455 #ifndef CONFIG_BRIDGE_NETFILTER
456                 NFA_PUT(skb, NFQA_IFINDEX_OUTDEV, sizeof(tmp_uint), &tmp_uint);
457 #else
458                 if (entinf->pf == PF_BRIDGE) {
459                         /* Case 1: outdev is physical output device, we need to
460                          * look for bridge group (when called from 
461                          * netfilter_bridge) */
462                         NFA_PUT(skb, NFQA_IFINDEX_PHYSOUTDEV, sizeof(tmp_uint),
463                                 &tmp_uint);
464                         /* this is the bridge group "brX" */
465                         tmp_uint = htonl(outdev->br_port->br->dev->ifindex);
466                         NFA_PUT(skb, NFQA_IFINDEX_OUTDEV, sizeof(tmp_uint),
467                                 &tmp_uint);
468                 } else {
469                         /* Case 2: outdev is bridge group, we need to look for
470                          * physical output device (when called from ipv4) */
471                         NFA_PUT(skb, NFQA_IFINDEX_OUTDEV, sizeof(tmp_uint),
472                                 &tmp_uint);
473                         if (entskb->nf_bridge
474                             && entskb->nf_bridge->physoutdev) {
475                                 tmp_uint = htonl(entskb->nf_bridge->physoutdev->ifindex);
476                                 NFA_PUT(skb, NFQA_IFINDEX_PHYSOUTDEV,
477                                         sizeof(tmp_uint), &tmp_uint);
478                         }
479                 }
480 #endif
481         }
482
483         if (entskb->nfmark) {
484                 tmp_uint = htonl(entskb->nfmark);
485                 NFA_PUT(skb, NFQA_MARK, sizeof(u_int32_t), &tmp_uint);
486         }
487
488         if (indev && entskb->dev
489             && entskb->dev->hard_header_parse) {
490                 struct nfqnl_msg_packet_hw phw;
491
492                 phw.hw_addrlen =
493                         entskb->dev->hard_header_parse(entskb,
494                                                            phw.hw_addr);
495                 phw.hw_addrlen = htons(phw.hw_addrlen);
496                 NFA_PUT(skb, NFQA_HWADDR, sizeof(phw), &phw);
497         }
498
499         if (entskb->tstamp.off_sec) {
500                 struct nfqnl_msg_packet_timestamp ts;
501
502                 ts.sec = cpu_to_be64(entskb->tstamp.off_sec);
503                 ts.usec = cpu_to_be64(entskb->tstamp.off_usec);
504
505                 NFA_PUT(skb, NFQA_TIMESTAMP, sizeof(ts), &ts);
506         }
507
508         if (data_len) {
509                 struct nfattr *nfa;
510                 int size = NFA_LENGTH(data_len);
511
512                 if (skb_tailroom(skb) < (int)NFA_SPACE(data_len)) {
513                         printk(KERN_WARNING "nf_queue: no tailroom!\n");
514                         goto nlmsg_failure;
515                 }
516
517                 nfa = (struct nfattr *)skb_put(skb, NFA_ALIGN(size));
518                 nfa->nfa_type = NFQA_PAYLOAD;
519                 nfa->nfa_len = size;
520
521                 if (skb_copy_bits(entskb, 0, NFA_DATA(nfa), data_len))
522                         BUG();
523         }
524                 
525         nlh->nlmsg_len = skb->tail - old_tail;
526         return skb;
527
528 nlmsg_failure:
529 nfattr_failure:
530         if (skb)
531                 kfree_skb(skb);
532         *errp = -EINVAL;
533         if (net_ratelimit())
534                 printk(KERN_ERR "nf_queue: error creating packet message\n");
535         return NULL;
536 }
537
538 static int
539 nfqnl_enqueue_packet(struct sk_buff *skb, struct nf_info *info, 
540                      unsigned int queuenum, void *data)
541 {
542         int status = -EINVAL;
543         struct sk_buff *nskb;
544         struct nfqnl_instance *queue;
545         struct nfqnl_queue_entry *entry;
546
547         QDEBUG("entered\n");
548
549         queue = instance_lookup_get(queuenum);
550         if (!queue) {
551                 QDEBUG("no queue instance matching\n");
552                 return -EINVAL;
553         }
554
555         if (queue->copy_mode == NFQNL_COPY_NONE) {
556                 QDEBUG("mode COPY_NONE, aborting\n");
557                 status = -EAGAIN;
558                 goto err_out_put;
559         }
560
561         entry = kmalloc(sizeof(*entry), GFP_ATOMIC);
562         if (entry == NULL) {
563                 if (net_ratelimit())
564                         printk(KERN_ERR 
565                                 "nf_queue: OOM in nfqnl_enqueue_packet()\n");
566                 status = -ENOMEM;
567                 goto err_out_put;
568         }
569
570         entry->info = info;
571         entry->skb = skb;
572         entry->id = atomic_inc_return(&queue->id_sequence);
573
574         nskb = nfqnl_build_packet_message(queue, entry, &status);
575         if (nskb == NULL)
576                 goto err_out_free;
577                 
578         spin_lock_bh(&queue->lock);
579         
580         if (!queue->peer_pid)
581                 goto err_out_free_nskb; 
582
583         if (queue->queue_total >= queue->queue_maxlen) {
584                 queue->queue_dropped++;
585                 status = -ENOSPC;
586                 if (net_ratelimit())
587                           printk(KERN_WARNING "nf_queue: full at %d entries, "
588                                  "dropping packets(s). Dropped: %d\n", 
589                                  queue->queue_total, queue->queue_dropped);
590                 goto err_out_free_nskb;
591         }
592
593         /* nfnetlink_unicast will either free the nskb or add it to a socket */
594         status = nfnetlink_unicast(nskb, queue->peer_pid, MSG_DONTWAIT);
595         if (status < 0) {
596                 queue->queue_user_dropped++;
597                 goto err_out_unlock;
598         }
599
600         __enqueue_entry(queue, entry);
601
602         spin_unlock_bh(&queue->lock);
603         instance_put(queue);
604         return status;
605
606 err_out_free_nskb:
607         kfree_skb(nskb); 
608         
609 err_out_unlock:
610         spin_unlock_bh(&queue->lock);
611
612 err_out_free:
613         kfree(entry);
614 err_out_put:
615         instance_put(queue);
616         return status;
617 }
618
619 static int
620 nfqnl_mangle(void *data, int data_len, struct nfqnl_queue_entry *e)
621 {
622         int diff;
623
624         diff = data_len - e->skb->len;
625         if (diff < 0) {
626                 if (pskb_trim(e->skb, data_len))
627                         return -ENOMEM;
628         } else if (diff > 0) {
629                 if (data_len > 0xFFFF)
630                         return -EINVAL;
631                 if (diff > skb_tailroom(e->skb)) {
632                         struct sk_buff *newskb;
633                         
634                         newskb = skb_copy_expand(e->skb,
635                                                  skb_headroom(e->skb),
636                                                  diff,
637                                                  GFP_ATOMIC);
638                         if (newskb == NULL) {
639                                 printk(KERN_WARNING "nf_queue: OOM "
640                                       "in mangle, dropping packet\n");
641                                 return -ENOMEM;
642                         }
643                         if (e->skb->sk)
644                                 skb_set_owner_w(newskb, e->skb->sk);
645                         kfree_skb(e->skb);
646                         e->skb = newskb;
647                 }
648                 skb_put(e->skb, diff);
649         }
650         if (!skb_make_writable(&e->skb, data_len))
651                 return -ENOMEM;
652         memcpy(e->skb->data, data, data_len);
653         e->skb->ip_summed = CHECKSUM_NONE;
654         return 0;
655 }
656
657 static inline int
658 id_cmp(struct nfqnl_queue_entry *e, unsigned long id)
659 {
660         return (id == e->id);
661 }
662
663 static int
664 nfqnl_set_mode(struct nfqnl_instance *queue,
665                unsigned char mode, unsigned int range)
666 {
667         int status;
668
669         spin_lock_bh(&queue->lock);
670         status = __nfqnl_set_mode(queue, mode, range);
671         spin_unlock_bh(&queue->lock);
672
673         return status;
674 }
675
676 static int
677 dev_cmp(struct nfqnl_queue_entry *entry, unsigned long ifindex)
678 {
679         struct nf_info *entinf = entry->info;
680         
681         if (entinf->indev)
682                 if (entinf->indev->ifindex == ifindex)
683                         return 1;
684         if (entinf->outdev)
685                 if (entinf->outdev->ifindex == ifindex)
686                         return 1;
687 #ifdef CONFIG_BRIDGE_NETFILTER
688         if (entry->skb->nf_bridge) {
689                 if (entry->skb->nf_bridge->physindev &&
690                     entry->skb->nf_bridge->physindev->ifindex == ifindex)
691                         return 1;
692                 if (entry->skb->nf_bridge->physoutdev &&
693                     entry->skb->nf_bridge->physoutdev->ifindex == ifindex)
694                         return 1;
695         }
696 #endif
697         return 0;
698 }
699
700 /* drop all packets with either indev or outdev == ifindex from all queue
701  * instances */
702 static void
703 nfqnl_dev_drop(int ifindex)
704 {
705         int i;
706         
707         QDEBUG("entering for ifindex %u\n", ifindex);
708
709         /* this only looks like we have to hold the readlock for a way too long
710          * time, issue_verdict(),  nf_reinject(), ... - but we always only
711          * issue NF_DROP, which is processed directly in nf_reinject() */
712         read_lock_bh(&instances_lock);
713
714         for  (i = 0; i < INSTANCE_BUCKETS; i++) {
715                 struct hlist_node *tmp;
716                 struct nfqnl_instance *inst;
717                 struct hlist_head *head = &instance_table[i];
718
719                 hlist_for_each_entry(inst, tmp, head, hlist) {
720                         struct nfqnl_queue_entry *entry;
721                         while ((entry = find_dequeue_entry(inst, dev_cmp, 
722                                                            ifindex)) != NULL)
723                                 issue_verdict(entry, NF_DROP);
724                 }
725         }
726
727         read_unlock_bh(&instances_lock);
728 }
729
730 #define RCV_SKB_FAIL(err) do { netlink_ack(skb, nlh, (err)); return; } while (0)
731
732 static int
733 nfqnl_rcv_dev_event(struct notifier_block *this,
734                     unsigned long event, void *ptr)
735 {
736         struct net_device *dev = ptr;
737
738         /* Drop any packets associated with the downed device */
739         if (event == NETDEV_DOWN)
740                 nfqnl_dev_drop(dev->ifindex);
741         return NOTIFY_DONE;
742 }
743
744 static struct notifier_block nfqnl_dev_notifier = {
745         .notifier_call  = nfqnl_rcv_dev_event,
746 };
747
748 static int
749 nfqnl_rcv_nl_event(struct notifier_block *this,
750                    unsigned long event, void *ptr)
751 {
752         struct netlink_notify *n = ptr;
753
754         if (event == NETLINK_URELEASE &&
755             n->protocol == NETLINK_NETFILTER && n->pid) {
756                 int i;
757
758                 /* destroy all instances for this pid */
759                 write_lock_bh(&instances_lock);
760                 for  (i = 0; i < INSTANCE_BUCKETS; i++) {
761                         struct hlist_node *tmp, *t2;
762                         struct nfqnl_instance *inst;
763                         struct hlist_head *head = &instance_table[i];
764
765                         hlist_for_each_entry_safe(inst, tmp, t2, head, hlist) {
766                                 if (n->pid == inst->peer_pid)
767                                         __instance_destroy(inst);
768                         }
769                 }
770                 write_unlock_bh(&instances_lock);
771         }
772         return NOTIFY_DONE;
773 }
774
775 static struct notifier_block nfqnl_rtnl_notifier = {
776         .notifier_call  = nfqnl_rcv_nl_event,
777 };
778
779 static const int nfqa_verdict_min[NFQA_MAX] = {
780         [NFQA_VERDICT_HDR-1]    = sizeof(struct nfqnl_msg_verdict_hdr),
781         [NFQA_MARK-1]           = sizeof(u_int32_t),
782         [NFQA_PAYLOAD-1]        = 0,
783 };
784
785 static int
786 nfqnl_recv_verdict(struct sock *ctnl, struct sk_buff *skb,
787                    struct nlmsghdr *nlh, struct nfattr *nfqa[], int *errp)
788 {
789         struct nfgenmsg *nfmsg = NLMSG_DATA(nlh);
790         u_int16_t queue_num = ntohs(nfmsg->res_id);
791
792         struct nfqnl_msg_verdict_hdr *vhdr;
793         struct nfqnl_instance *queue;
794         unsigned int verdict;
795         struct nfqnl_queue_entry *entry;
796         int err;
797
798         if (nfattr_bad_size(nfqa, NFQA_MAX, nfqa_verdict_min)) {
799                 QDEBUG("bad attribute size\n");
800                 return -EINVAL;
801         }
802
803         queue = instance_lookup_get(queue_num);
804         if (!queue)
805                 return -ENODEV;
806
807         if (queue->peer_pid != NETLINK_CB(skb).pid) {
808                 err = -EPERM;
809                 goto err_out_put;
810         }
811
812         if (!nfqa[NFQA_VERDICT_HDR-1]) {
813                 err = -EINVAL;
814                 goto err_out_put;
815         }
816
817         vhdr = NFA_DATA(nfqa[NFQA_VERDICT_HDR-1]);
818         verdict = ntohl(vhdr->verdict);
819
820         if ((verdict & NF_VERDICT_MASK) > NF_MAX_VERDICT) {
821                 err = -EINVAL;
822                 goto err_out_put;
823         }
824
825         entry = find_dequeue_entry(queue, id_cmp, ntohl(vhdr->id));
826         if (entry == NULL) {
827                 err = -ENOENT;
828                 goto err_out_put;
829         }
830
831         if (nfqa[NFQA_PAYLOAD-1]) {
832                 if (nfqnl_mangle(NFA_DATA(nfqa[NFQA_PAYLOAD-1]),
833                                  NFA_PAYLOAD(nfqa[NFQA_PAYLOAD-1]), entry) < 0)
834                         verdict = NF_DROP;
835         }
836
837         if (nfqa[NFQA_MARK-1])
838                 entry->skb->nfmark = ntohl(*(u_int32_t *)
839                                            NFA_DATA(nfqa[NFQA_MARK-1]));
840                 
841         issue_verdict(entry, verdict);
842         instance_put(queue);
843         return 0;
844
845 err_out_put:
846         instance_put(queue);
847         return err;
848 }
849
850 static int
851 nfqnl_recv_unsupp(struct sock *ctnl, struct sk_buff *skb,
852                   struct nlmsghdr *nlh, struct nfattr *nfqa[], int *errp)
853 {
854         return -ENOTSUPP;
855 }
856
857 static const int nfqa_cfg_min[NFQA_CFG_MAX] = {
858         [NFQA_CFG_CMD-1]        = sizeof(struct nfqnl_msg_config_cmd),
859         [NFQA_CFG_PARAMS-1]     = sizeof(struct nfqnl_msg_config_params),
860 };
861
862 static struct nf_queue_handler nfqh = {
863         .name   = "nf_queue",
864         .outfn  = &nfqnl_enqueue_packet,
865 };
866
867 static int
868 nfqnl_recv_config(struct sock *ctnl, struct sk_buff *skb,
869                   struct nlmsghdr *nlh, struct nfattr *nfqa[], int *errp)
870 {
871         struct nfgenmsg *nfmsg = NLMSG_DATA(nlh);
872         u_int16_t queue_num = ntohs(nfmsg->res_id);
873         struct nfqnl_instance *queue;
874         int ret = 0;
875
876         QDEBUG("entering for msg %u\n", NFNL_MSG_TYPE(nlh->nlmsg_type));
877
878         if (nfattr_bad_size(nfqa, NFQA_CFG_MAX, nfqa_cfg_min)) {
879                 QDEBUG("bad attribute size\n");
880                 return -EINVAL;
881         }
882
883         queue = instance_lookup_get(queue_num);
884         if (nfqa[NFQA_CFG_CMD-1]) {
885                 struct nfqnl_msg_config_cmd *cmd;
886                 cmd = NFA_DATA(nfqa[NFQA_CFG_CMD-1]);
887                 QDEBUG("found CFG_CMD\n");
888
889                 switch (cmd->command) {
890                 case NFQNL_CFG_CMD_BIND:
891                         if (queue)
892                                 return -EBUSY;
893
894                         queue = instance_create(queue_num, NETLINK_CB(skb).pid);
895                         if (!queue)
896                                 return -EINVAL;
897                         break;
898                 case NFQNL_CFG_CMD_UNBIND:
899                         if (!queue)
900                                 return -ENODEV;
901
902                         if (queue->peer_pid != NETLINK_CB(skb).pid) {
903                                 ret = -EPERM;
904                                 goto out_put;
905                         }
906
907                         instance_destroy(queue);
908                         break;
909                 case NFQNL_CFG_CMD_PF_BIND:
910                         QDEBUG("registering queue handler for pf=%u\n",
911                                 ntohs(cmd->pf));
912                         ret = nf_register_queue_handler(ntohs(cmd->pf), &nfqh);
913                         break;
914                 case NFQNL_CFG_CMD_PF_UNBIND:
915                         QDEBUG("unregistering queue handler for pf=%u\n",
916                                 ntohs(cmd->pf));
917                         /* This is a bug and a feature.  We can unregister
918                          * other handlers(!) */
919                         ret = nf_unregister_queue_handler(ntohs(cmd->pf));
920                         break;
921                 default:
922                         ret = -EINVAL;
923                         break;
924                 }
925         } else {
926                 if (!queue) {
927                         QDEBUG("no config command, and no instance ENOENT\n");
928                         ret = -ENOENT;
929                         goto out_put;
930                 }
931
932                 if (queue->peer_pid != NETLINK_CB(skb).pid) {
933                         QDEBUG("no config command, and wrong pid\n");
934                         ret = -EPERM;
935                         goto out_put;
936                 }
937         }
938
939         if (nfqa[NFQA_CFG_PARAMS-1]) {
940                 struct nfqnl_msg_config_params *params;
941
942                 if (!queue) {
943                         ret = -ENOENT;
944                         goto out_put;
945                 }
946                 params = NFA_DATA(nfqa[NFQA_CFG_PARAMS-1]);
947                 nfqnl_set_mode(queue, params->copy_mode,
948                                 ntohl(params->copy_range));
949         }
950
951 out_put:
952         instance_put(queue);
953         return ret;
954 }
955
956 static struct nfnl_callback nfqnl_cb[NFQNL_MSG_MAX] = {
957         [NFQNL_MSG_PACKET]      = { .call = nfqnl_recv_unsupp,
958                                     .attr_count = NFQA_MAX, },
959         [NFQNL_MSG_VERDICT]     = { .call = nfqnl_recv_verdict,
960                                     .attr_count = NFQA_MAX, },
961         [NFQNL_MSG_CONFIG]      = { .call = nfqnl_recv_config,
962                                     .attr_count = NFQA_CFG_MAX, },
963 };
964
965 static struct nfnetlink_subsystem nfqnl_subsys = {
966         .name           = "nf_queue",
967         .subsys_id      = NFNL_SUBSYS_QUEUE,
968         .cb_count       = NFQNL_MSG_MAX,
969         .cb             = nfqnl_cb,
970 };
971
972 #ifdef CONFIG_PROC_FS
973 struct iter_state {
974         unsigned int bucket;
975 };
976
977 static struct hlist_node *get_first(struct seq_file *seq)
978 {
979         struct iter_state *st = seq->private;
980
981         if (!st)
982                 return NULL;
983
984         for (st->bucket = 0; st->bucket < INSTANCE_BUCKETS; st->bucket++) {
985                 if (!hlist_empty(&instance_table[st->bucket]))
986                         return instance_table[st->bucket].first;
987         }
988         return NULL;
989 }
990
991 static struct hlist_node *get_next(struct seq_file *seq, struct hlist_node *h)
992 {
993         struct iter_state *st = seq->private;
994
995         h = h->next;
996         while (!h) {
997                 if (++st->bucket >= INSTANCE_BUCKETS)
998                         return NULL;
999
1000                 h = instance_table[st->bucket].first;
1001         }
1002         return h;
1003 }
1004
1005 static struct hlist_node *get_idx(struct seq_file *seq, loff_t pos)
1006 {
1007         struct hlist_node *head;
1008         head = get_first(seq);
1009
1010         if (head)
1011                 while (pos && (head = get_next(seq, head)))
1012                         pos--;
1013         return pos ? NULL : head;
1014 }
1015
1016 static void *seq_start(struct seq_file *seq, loff_t *pos)
1017 {
1018         read_lock_bh(&instances_lock);
1019         return get_idx(seq, *pos);
1020 }
1021
1022 static void *seq_next(struct seq_file *s, void *v, loff_t *pos)
1023 {
1024         (*pos)++;
1025         return get_next(s, v);
1026 }
1027
1028 static void seq_stop(struct seq_file *s, void *v)
1029 {
1030         read_unlock_bh(&instances_lock);
1031 }
1032
1033 static int seq_show(struct seq_file *s, void *v)
1034 {
1035         const struct nfqnl_instance *inst = v;
1036
1037         return seq_printf(s, "%5d %6d %5d %1d %5d %5d %5d %8d %2d\n",
1038                           inst->queue_num,
1039                           inst->peer_pid, inst->queue_total,
1040                           inst->copy_mode, inst->copy_range,
1041                           inst->queue_dropped, inst->queue_user_dropped,
1042                           atomic_read(&inst->id_sequence),
1043                           atomic_read(&inst->use));
1044 }
1045
1046 static struct seq_operations nfqnl_seq_ops = {
1047         .start  = seq_start,
1048         .next   = seq_next,
1049         .stop   = seq_stop,
1050         .show   = seq_show,
1051 };
1052
1053 static int nfqnl_open(struct inode *inode, struct file *file)
1054 {
1055         struct seq_file *seq;
1056         struct iter_state *is;
1057         int ret;
1058
1059         is = kzalloc(sizeof(*is), GFP_KERNEL);
1060         if (!is)
1061                 return -ENOMEM;
1062         ret = seq_open(file, &nfqnl_seq_ops);
1063         if (ret < 0)
1064                 goto out_free;
1065         seq = file->private_data;
1066         seq->private = is;
1067         return ret;
1068 out_free:
1069         kfree(is);
1070         return ret;
1071 }
1072
1073 static struct file_operations nfqnl_file_ops = {
1074         .owner   = THIS_MODULE,
1075         .open    = nfqnl_open,
1076         .read    = seq_read,
1077         .llseek  = seq_lseek,
1078         .release = seq_release_private,
1079 };
1080
1081 #endif /* PROC_FS */
1082
1083 static int __init nfnetlink_queue_init(void)
1084 {
1085         int i, status = -ENOMEM;
1086 #ifdef CONFIG_PROC_FS
1087         struct proc_dir_entry *proc_nfqueue;
1088 #endif
1089         
1090         for (i = 0; i < INSTANCE_BUCKETS; i++)
1091                 INIT_HLIST_HEAD(&instance_table[i]);
1092
1093         netlink_register_notifier(&nfqnl_rtnl_notifier);
1094         status = nfnetlink_subsys_register(&nfqnl_subsys);
1095         if (status < 0) {
1096                 printk(KERN_ERR "nf_queue: failed to create netlink socket\n");
1097                 goto cleanup_netlink_notifier;
1098         }
1099
1100 #ifdef CONFIG_PROC_FS
1101         proc_nfqueue = create_proc_entry("nfnetlink_queue", 0440,
1102                                          proc_net_netfilter);
1103         if (!proc_nfqueue)
1104                 goto cleanup_subsys;
1105         proc_nfqueue->proc_fops = &nfqnl_file_ops;
1106 #endif
1107
1108         register_netdevice_notifier(&nfqnl_dev_notifier);
1109         return status;
1110
1111 #ifdef CONFIG_PROC_FS
1112 cleanup_subsys:
1113         nfnetlink_subsys_unregister(&nfqnl_subsys);
1114 #endif
1115 cleanup_netlink_notifier:
1116         netlink_unregister_notifier(&nfqnl_rtnl_notifier);
1117         return status;
1118 }
1119
1120 static void __exit nfnetlink_queue_fini(void)
1121 {
1122         nf_unregister_queue_handlers(&nfqh);
1123         unregister_netdevice_notifier(&nfqnl_dev_notifier);
1124 #ifdef CONFIG_PROC_FS
1125         remove_proc_entry("nfnetlink_queue", proc_net_netfilter);
1126 #endif
1127         nfnetlink_subsys_unregister(&nfqnl_subsys);
1128         netlink_unregister_notifier(&nfqnl_rtnl_notifier);
1129 }
1130
1131 MODULE_DESCRIPTION("netfilter packet queue handler");
1132 MODULE_AUTHOR("Harald Welte <laforge@netfilter.org>");
1133 MODULE_LICENSE("GPL");
1134 MODULE_ALIAS_NFNL_SUBSYS(NFNL_SUBSYS_QUEUE);
1135
1136 module_init(nfnetlink_queue_init);
1137 module_exit(nfnetlink_queue_fini);