linux 2.6.16.38 w/ vs2.0.3-rc1
[linux-2.6.git] / net / ipv4 / netfilter / ipt_ULOG.c
1 /*
2  * netfilter module for userspace packet logging daemons
3  *
4  * (C) 2000-2004 by Harald Welte <laforge@netfilter.org>
5  *
6  * 2000/09/22 ulog-cprange feature added
7  * 2001/01/04 in-kernel queue as proposed by Sebastian Zander 
8  *                                              <zander@fokus.gmd.de>
9  * 2001/01/30 per-rule nlgroup conflicts with global queue. 
10  *            nlgroup now global (sysctl)
11  * 2001/04/19 ulog-queue reworked, now fixed buffer size specified at
12  *            module loadtime -HW
13  * 2002/07/07 remove broken nflog_rcv() function -HW
14  * 2002/08/29 fix shifted/unshifted nlgroup bug -HW
15  * 2002/10/30 fix uninitialized mac_len field - <Anders K. Pedersen>
16  * 2004/10/25 fix erroneous calculation of 'len' parameter to NLMSG_PUT
17  *            resulting in bogus 'error during NLMSG_PUT' messages.
18  *
19  * (C) 1999-2001 Paul `Rusty' Russell
20  * (C) 2002-2004 Netfilter Core Team <coreteam@netfilter.org>
21  *
22  * This program is free software; you can redistribute it and/or modify
23  * it under the terms of the GNU General Public License version 2 as
24  * published by the Free Software Foundation.
25  *
26  * This module accepts two parameters: 
27  * 
28  * nlbufsiz:
29  *   The parameter specifies how big the buffer for each netlink multicast
30  * group is. e.g. If you say nlbufsiz=8192, up to eight kb of packets will
31  * get accumulated in the kernel until they are sent to userspace. It is
32  * NOT possible to allocate more than 128kB, and it is strongly discouraged,
33  * because atomically allocating 128kB inside the network rx softirq is not
34  * reliable. Please also keep in mind that this buffer size is allocated for
35  * each nlgroup you are using, so the total kernel memory usage increases
36  * by that factor.
37  *
38  * Actually you should use nlbufsiz a bit smaller than PAGE_SIZE, since
39  * nlbufsiz is used with alloc_skb, which adds another
40  * sizeof(struct skb_shared_info).  Use NLMSG_GOODSIZE instead.
41  *
42  * flushtimeout:
43  *   Specify, after how many hundredths of a second the queue should be
44  *   flushed even if it is not full yet.
45  *
46  * ipt_ULOG.c,v 1.22 2002/10/30 09:07:31 laforge Exp
47  */
48
49 #include <linux/module.h>
50 #include <linux/config.h>
51 #include <linux/spinlock.h>
52 #include <linux/socket.h>
53 #include <linux/skbuff.h>
54 #include <linux/kernel.h>
55 #include <linux/timer.h>
56 #include <linux/netlink.h>
57 #include <linux/netdevice.h>
58 #include <linux/mm.h>
59 #include <linux/moduleparam.h>
60 #include <linux/netfilter.h>
61 #include <linux/netfilter_ipv4/ip_tables.h>
62 #include <linux/netfilter_ipv4/ipt_ULOG.h>
63 #include <net/sock.h>
64 #include <linux/bitops.h>
65
66 MODULE_LICENSE("GPL");
67 MODULE_AUTHOR("Harald Welte <laforge@gnumonks.org>");
68 MODULE_DESCRIPTION("iptables userspace logging module");
69 MODULE_ALIAS_NET_PF_PROTO(PF_NETLINK, NETLINK_NFLOG);
70
71 #define ULOG_NL_EVENT           111             /* Harald's favorite number */
72 #define ULOG_MAXNLGROUPS        32              /* numer of nlgroups */
73
74 #if 0
75 #define DEBUGP(format, args...) printk("%s:%s:" format, \
76                                        __FILE__, __FUNCTION__ , ## args)
77 #else
78 #define DEBUGP(format, args...)
79 #endif
80
81 #define PRINTR(format, args...) do { if (net_ratelimit()) printk(format , ## args); } while (0)
82
83 static unsigned int nlbufsiz = NLMSG_GOODSIZE;
84 module_param(nlbufsiz, uint, 0400);
85 MODULE_PARM_DESC(nlbufsiz, "netlink buffer size");
86
87 static unsigned int flushtimeout = 10;
88 module_param(flushtimeout, uint, 0600);
89 MODULE_PARM_DESC(flushtimeout, "buffer flush timeout (hundredths of a second)");
90
91 static int nflog = 1;
92 module_param(nflog, bool, 0400);
93 MODULE_PARM_DESC(nflog, "register as internal netfilter logging module");
94
95 /* global data structures */
96
97 typedef struct {
98         unsigned int qlen;              /* number of nlmsgs' in the skb */
99         struct nlmsghdr *lastnlh;       /* netlink header of last msg in skb */
100         struct sk_buff *skb;            /* the pre-allocated skb */
101         struct timer_list timer;        /* the timer function */
102 } ulog_buff_t;
103
104 static ulog_buff_t ulog_buffers[ULOG_MAXNLGROUPS];      /* array of buffers */
105
106 static struct sock *nflognl;            /* our socket */
107 static DEFINE_SPINLOCK(ulog_lock);      /* spinlock */
108
109 /* send one ulog_buff_t to userspace */
110 static void ulog_send(unsigned int nlgroupnum)
111 {
112         ulog_buff_t *ub = &ulog_buffers[nlgroupnum];
113
114         if (timer_pending(&ub->timer)) {
115                 DEBUGP("ipt_ULOG: ulog_send: timer was pending, deleting\n");
116                 del_timer(&ub->timer);
117         }
118
119         if (!ub->skb) {
120                 DEBUGP("ipt_ULOG: ulog_send: nothing to send\n");
121                 return;
122         }
123
124         /* last nlmsg needs NLMSG_DONE */
125         if (ub->qlen > 1)
126                 ub->lastnlh->nlmsg_type = NLMSG_DONE;
127
128         if (!ub->skb) {
129                 DEBUGP("ipt_ULOG: ulog_send: nothing to send\n");
130                 return;
131         }
132
133         NETLINK_CB(ub->skb).dst_group = nlgroupnum + 1;
134         DEBUGP("ipt_ULOG: throwing %d packets to netlink group %u\n",
135                 ub->qlen, nlgroupnum + 1);
136         netlink_broadcast(nflognl, ub->skb, 0, nlgroupnum + 1, GFP_ATOMIC);
137
138         ub->qlen = 0;
139         ub->skb = NULL;
140         ub->lastnlh = NULL;
141
142 }
143
144
145 /* timer function to flush queue in flushtimeout time */
146 static void ulog_timer(unsigned long data)
147 {
148         DEBUGP("ipt_ULOG: timer function called, calling ulog_send\n");
149
150         /* lock to protect against somebody modifying our structure
151          * from ipt_ulog_target at the same time */
152         spin_lock_bh(&ulog_lock);
153         ulog_send(data);
154         spin_unlock_bh(&ulog_lock);
155 }
156
157 static struct sk_buff *ulog_alloc_skb(unsigned int size)
158 {
159         struct sk_buff *skb;
160         unsigned int n;
161
162         /* alloc skb which should be big enough for a whole
163          * multipart message. WARNING: has to be <= 131000
164          * due to slab allocator restrictions */
165
166         n = max(size, nlbufsiz);
167         skb = alloc_skb(n, GFP_ATOMIC);
168         if (!skb) {
169                 PRINTR("ipt_ULOG: can't alloc whole buffer %ub!\n", n);
170
171                 if (n > size) {
172                         /* try to allocate only as much as we need for 
173                          * current packet */
174
175                         skb = alloc_skb(size, GFP_ATOMIC);
176                         if (!skb)
177                                 PRINTR("ipt_ULOG: can't even allocate %ub\n",
178                                        size);
179                 }
180         }
181
182         return skb;
183 }
184
185 static void ipt_ulog_packet(unsigned int hooknum,
186                             const struct sk_buff *skb,
187                             const struct net_device *in,
188                             const struct net_device *out,
189                             const struct ipt_ulog_info *loginfo,
190                             const char *prefix)
191 {
192         ulog_buff_t *ub;
193         ulog_packet_msg_t *pm;
194         size_t size, copy_len;
195         struct nlmsghdr *nlh;
196
197         /* ffs == find first bit set, necessary because userspace
198          * is already shifting groupnumber, but we need unshifted.
199          * ffs() returns [1..32], we need [0..31] */
200         unsigned int groupnum = ffs(loginfo->nl_group) - 1;
201
202         /* calculate the size of the skb needed */
203         if ((loginfo->copy_range == 0) ||
204             (loginfo->copy_range > skb->len)) {
205                 copy_len = skb->len;
206         } else {
207                 copy_len = loginfo->copy_range;
208         }
209
210         size = NLMSG_SPACE(sizeof(*pm) + copy_len);
211
212         ub = &ulog_buffers[groupnum];
213         
214         spin_lock_bh(&ulog_lock);
215
216         if (!ub->skb) {
217                 if (!(ub->skb = ulog_alloc_skb(size)))
218                         goto alloc_failure;
219         } else if (ub->qlen >= loginfo->qthreshold ||
220                    size > skb_tailroom(ub->skb)) {
221                 /* either the queue len is too high or we don't have 
222                  * enough room in nlskb left. send it to userspace. */
223
224                 ulog_send(groupnum);
225
226                 if (!(ub->skb = ulog_alloc_skb(size)))
227                         goto alloc_failure;
228         }
229
230         DEBUGP("ipt_ULOG: qlen %d, qthreshold %d\n", ub->qlen, 
231                 loginfo->qthreshold);
232
233         /* NLMSG_PUT contains a hidden goto nlmsg_failure !!! */
234         nlh = NLMSG_PUT(ub->skb, 0, ub->qlen, ULOG_NL_EVENT, 
235                         sizeof(*pm)+copy_len);
236         ub->qlen++;
237
238         pm = NLMSG_DATA(nlh);
239
240         /* We might not have a timestamp, get one */
241         if (skb->tstamp.off_sec == 0)
242                 __net_timestamp((struct sk_buff *)skb);
243
244         /* copy hook, prefix, timestamp, payload, etc. */
245         pm->data_len = copy_len;
246         pm->timestamp_sec = skb->tstamp.off_sec;
247         pm->timestamp_usec = skb->tstamp.off_usec;
248         pm->mark = skb->nfmark;
249         pm->hook = hooknum;
250         if (prefix != NULL)
251                 strncpy(pm->prefix, prefix, sizeof(pm->prefix));
252         else if (loginfo->prefix[0] != '\0')
253                 strncpy(pm->prefix, loginfo->prefix, sizeof(pm->prefix));
254         else
255                 *(pm->prefix) = '\0';
256
257         if (in && in->hard_header_len > 0
258             && skb->mac.raw != (void *) skb->nh.iph
259             && in->hard_header_len <= ULOG_MAC_LEN) {
260                 memcpy(pm->mac, skb->mac.raw, in->hard_header_len);
261                 pm->mac_len = in->hard_header_len;
262         } else
263                 pm->mac_len = 0;
264
265         if (in)
266                 strncpy(pm->indev_name, in->name, sizeof(pm->indev_name));
267         else
268                 pm->indev_name[0] = '\0';
269
270         if (out)
271                 strncpy(pm->outdev_name, out->name, sizeof(pm->outdev_name));
272         else
273                 pm->outdev_name[0] = '\0';
274
275         /* copy_len <= skb->len, so can't fail. */
276         if (skb_copy_bits(skb, 0, pm->payload, copy_len) < 0)
277                 BUG();
278         
279         /* check if we are building multi-part messages */
280         if (ub->qlen > 1) {
281                 ub->lastnlh->nlmsg_flags |= NLM_F_MULTI;
282         }
283
284         ub->lastnlh = nlh;
285
286         /* if timer isn't already running, start it */
287         if (!timer_pending(&ub->timer)) {
288                 ub->timer.expires = jiffies + flushtimeout * HZ / 100;
289                 add_timer(&ub->timer);
290         }
291
292         /* if threshold is reached, send message to userspace */
293         if (ub->qlen >= loginfo->qthreshold) {
294                 if (loginfo->qthreshold > 1)
295                         nlh->nlmsg_type = NLMSG_DONE;
296                 ulog_send(groupnum);
297         }
298
299         spin_unlock_bh(&ulog_lock);
300
301         return;
302
303 nlmsg_failure:
304         PRINTR("ipt_ULOG: error during NLMSG_PUT\n");
305
306 alloc_failure:
307         PRINTR("ipt_ULOG: Error building netlink message\n");
308
309         spin_unlock_bh(&ulog_lock);
310 }
311
312 static unsigned int ipt_ulog_target(struct sk_buff **pskb,
313                                     const struct net_device *in,
314                                     const struct net_device *out,
315                                     unsigned int hooknum,
316                                     const void *targinfo, void *userinfo)
317 {
318         struct ipt_ulog_info *loginfo = (struct ipt_ulog_info *) targinfo;
319
320         ipt_ulog_packet(hooknum, *pskb, in, out, loginfo, NULL);
321  
322         return IPT_CONTINUE;
323 }
324  
325 static void ipt_logfn(unsigned int pf,
326                       unsigned int hooknum,
327                       const struct sk_buff *skb,
328                       const struct net_device *in,
329                       const struct net_device *out,
330                       const struct nf_loginfo *li,
331                       const char *prefix)
332 {
333         struct ipt_ulog_info loginfo;
334
335         if (!li || li->type != NF_LOG_TYPE_ULOG) {
336                 loginfo.nl_group = ULOG_DEFAULT_NLGROUP;
337                 loginfo.copy_range = 0;
338                 loginfo.qthreshold = ULOG_DEFAULT_QTHRESHOLD;
339                 loginfo.prefix[0] = '\0';
340         } else {
341                 loginfo.nl_group = li->u.ulog.group;
342                 loginfo.copy_range = li->u.ulog.copy_len;
343                 loginfo.qthreshold = li->u.ulog.qthreshold;
344                 strlcpy(loginfo.prefix, prefix, sizeof(loginfo.prefix));
345         }
346
347         ipt_ulog_packet(hooknum, skb, in, out, &loginfo, prefix);
348 }
349
350 static int ipt_ulog_checkentry(const char *tablename,
351                                const void *e,
352                                void *targinfo,
353                                unsigned int targinfosize,
354                                unsigned int hookmask)
355 {
356         struct ipt_ulog_info *loginfo = (struct ipt_ulog_info *) targinfo;
357
358         if (targinfosize != IPT_ALIGN(sizeof(struct ipt_ulog_info))) {
359                 DEBUGP("ipt_ULOG: targinfosize %u != 0\n", targinfosize);
360                 return 0;
361         }
362
363         if (loginfo->prefix[sizeof(loginfo->prefix) - 1] != '\0') {
364                 DEBUGP("ipt_ULOG: prefix term %i\n",
365                        loginfo->prefix[sizeof(loginfo->prefix) - 1]);
366                 return 0;
367         }
368
369         if (loginfo->qthreshold > ULOG_MAX_QLEN) {
370                 DEBUGP("ipt_ULOG: queue threshold %i > MAX_QLEN\n",
371                         loginfo->qthreshold);
372                 return 0;
373         }
374
375         return 1;
376 }
377
378 static struct ipt_target ipt_ulog_reg = {
379         .name           = "ULOG",
380         .target         = ipt_ulog_target,
381         .checkentry     = ipt_ulog_checkentry,
382         .me             = THIS_MODULE,
383 };
384
385 static struct nf_logger ipt_ulog_logger = {
386         .name           = "ipt_ULOG",
387         .logfn          = &ipt_logfn,
388         .me             = THIS_MODULE,
389 };
390
391 static int __init init(void)
392 {
393         int i;
394
395         DEBUGP("ipt_ULOG: init module\n");
396
397         if (nlbufsiz > 128*1024) {
398                 printk("Netlink buffer has to be <= 128kB\n");
399                 return -EINVAL;
400         }
401
402         /* initialize ulog_buffers */
403         for (i = 0; i < ULOG_MAXNLGROUPS; i++) {
404                 init_timer(&ulog_buffers[i].timer);
405                 ulog_buffers[i].timer.function = ulog_timer;
406                 ulog_buffers[i].timer.data = i;
407         }
408
409         nflognl = netlink_kernel_create(NETLINK_NFLOG, ULOG_MAXNLGROUPS, NULL,
410                                         THIS_MODULE);
411         if (!nflognl)
412                 return -ENOMEM;
413
414         if (ipt_register_target(&ipt_ulog_reg) != 0) {
415                 sock_release(nflognl->sk_socket);
416                 return -EINVAL;
417         }
418         if (nflog)
419                 nf_log_register(PF_INET, &ipt_ulog_logger);
420         
421         return 0;
422 }
423
424 static void __exit fini(void)
425 {
426         ulog_buff_t *ub;
427         int i;
428
429         DEBUGP("ipt_ULOG: cleanup_module\n");
430
431         if (nflog)
432                 nf_log_unregister_logger(&ipt_ulog_logger);
433         ipt_unregister_target(&ipt_ulog_reg);
434         sock_release(nflognl->sk_socket);
435
436         /* remove pending timers and free allocated skb's */
437         for (i = 0; i < ULOG_MAXNLGROUPS; i++) {
438                 ub = &ulog_buffers[i];
439                 if (timer_pending(&ub->timer)) {
440                         DEBUGP("timer was pending, deleting\n");
441                         del_timer(&ub->timer);
442                 }
443
444                 if (ub->skb) {
445                         kfree_skb(ub->skb);
446                         ub->skb = NULL;
447                 }
448         }
449
450 }
451
452 module_init(init);
453 module_exit(fini);