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