[NETFILTER]: Convert arp_tables targets to centralized error checking
[safe/jmp/linux-2.6] / net / ipv4 / netfilter / arp_tables.c
1 /*
2  * Packet matching code for ARP packets.
3  *
4  * Based heavily, if not almost entirely, upon ip_tables.c framework.
5  *
6  * Some ARP specific bits are:
7  *
8  * Copyright (C) 2002 David S. Miller (davem@redhat.com)
9  *
10  */
11
12 #include <linux/config.h>
13 #include <linux/kernel.h>
14 #include <linux/skbuff.h>
15 #include <linux/netdevice.h>
16 #include <linux/capability.h>
17 #include <linux/if_arp.h>
18 #include <linux/kmod.h>
19 #include <linux/vmalloc.h>
20 #include <linux/proc_fs.h>
21 #include <linux/module.h>
22 #include <linux/init.h>
23
24 #include <asm/uaccess.h>
25 #include <asm/semaphore.h>
26
27 #include <linux/netfilter/x_tables.h>
28 #include <linux/netfilter_arp/arp_tables.h>
29
30 MODULE_LICENSE("GPL");
31 MODULE_AUTHOR("David S. Miller <davem@redhat.com>");
32 MODULE_DESCRIPTION("arptables core");
33
34 /*#define DEBUG_ARP_TABLES*/
35 /*#define DEBUG_ARP_TABLES_USER*/
36
37 #ifdef DEBUG_ARP_TABLES
38 #define dprintf(format, args...)  printk(format , ## args)
39 #else
40 #define dprintf(format, args...)
41 #endif
42
43 #ifdef DEBUG_ARP_TABLES_USER
44 #define duprintf(format, args...) printk(format , ## args)
45 #else
46 #define duprintf(format, args...)
47 #endif
48
49 #ifdef CONFIG_NETFILTER_DEBUG
50 #define ARP_NF_ASSERT(x)                                        \
51 do {                                                            \
52         if (!(x))                                               \
53                 printk("ARP_NF_ASSERT: %s:%s:%u\n",             \
54                        __FUNCTION__, __FILE__, __LINE__);       \
55 } while(0)
56 #else
57 #define ARP_NF_ASSERT(x)
58 #endif
59
60 #include <linux/netfilter_ipv4/listhelp.h>
61
62 static inline int arp_devaddr_compare(const struct arpt_devaddr_info *ap,
63                                       char *hdr_addr, int len)
64 {
65         int i, ret;
66
67         if (len > ARPT_DEV_ADDR_LEN_MAX)
68                 len = ARPT_DEV_ADDR_LEN_MAX;
69
70         ret = 0;
71         for (i = 0; i < len; i++)
72                 ret |= (hdr_addr[i] ^ ap->addr[i]) & ap->mask[i];
73
74         return (ret != 0);
75 }
76
77 /* Returns whether packet matches rule or not. */
78 static inline int arp_packet_match(const struct arphdr *arphdr,
79                                    struct net_device *dev,
80                                    const char *indev,
81                                    const char *outdev,
82                                    const struct arpt_arp *arpinfo)
83 {
84         char *arpptr = (char *)(arphdr + 1);
85         char *src_devaddr, *tgt_devaddr;
86         u32 src_ipaddr, tgt_ipaddr;
87         int i, ret;
88
89 #define FWINV(bool,invflg) ((bool) ^ !!(arpinfo->invflags & invflg))
90
91         if (FWINV((arphdr->ar_op & arpinfo->arpop_mask) != arpinfo->arpop,
92                   ARPT_INV_ARPOP)) {
93                 dprintf("ARP operation field mismatch.\n");
94                 dprintf("ar_op: %04x info->arpop: %04x info->arpop_mask: %04x\n",
95                         arphdr->ar_op, arpinfo->arpop, arpinfo->arpop_mask);
96                 return 0;
97         }
98
99         if (FWINV((arphdr->ar_hrd & arpinfo->arhrd_mask) != arpinfo->arhrd,
100                   ARPT_INV_ARPHRD)) {
101                 dprintf("ARP hardware address format mismatch.\n");
102                 dprintf("ar_hrd: %04x info->arhrd: %04x info->arhrd_mask: %04x\n",
103                         arphdr->ar_hrd, arpinfo->arhrd, arpinfo->arhrd_mask);
104                 return 0;
105         }
106
107         if (FWINV((arphdr->ar_pro & arpinfo->arpro_mask) != arpinfo->arpro,
108                   ARPT_INV_ARPPRO)) {
109                 dprintf("ARP protocol address format mismatch.\n");
110                 dprintf("ar_pro: %04x info->arpro: %04x info->arpro_mask: %04x\n",
111                         arphdr->ar_pro, arpinfo->arpro, arpinfo->arpro_mask);
112                 return 0;
113         }
114
115         if (FWINV((arphdr->ar_hln & arpinfo->arhln_mask) != arpinfo->arhln,
116                   ARPT_INV_ARPHLN)) {
117                 dprintf("ARP hardware address length mismatch.\n");
118                 dprintf("ar_hln: %02x info->arhln: %02x info->arhln_mask: %02x\n",
119                         arphdr->ar_hln, arpinfo->arhln, arpinfo->arhln_mask);
120                 return 0;
121         }
122
123         src_devaddr = arpptr;
124         arpptr += dev->addr_len;
125         memcpy(&src_ipaddr, arpptr, sizeof(u32));
126         arpptr += sizeof(u32);
127         tgt_devaddr = arpptr;
128         arpptr += dev->addr_len;
129         memcpy(&tgt_ipaddr, arpptr, sizeof(u32));
130
131         if (FWINV(arp_devaddr_compare(&arpinfo->src_devaddr, src_devaddr, dev->addr_len),
132                   ARPT_INV_SRCDEVADDR) ||
133             FWINV(arp_devaddr_compare(&arpinfo->tgt_devaddr, tgt_devaddr, dev->addr_len),
134                   ARPT_INV_TGTDEVADDR)) {
135                 dprintf("Source or target device address mismatch.\n");
136
137                 return 0;
138         }
139
140         if (FWINV((src_ipaddr & arpinfo->smsk.s_addr) != arpinfo->src.s_addr,
141                   ARPT_INV_SRCIP) ||
142             FWINV(((tgt_ipaddr & arpinfo->tmsk.s_addr) != arpinfo->tgt.s_addr),
143                   ARPT_INV_TGTIP)) {
144                 dprintf("Source or target IP address mismatch.\n");
145
146                 dprintf("SRC: %u.%u.%u.%u. Mask: %u.%u.%u.%u. Target: %u.%u.%u.%u.%s\n",
147                         NIPQUAD(src_ipaddr),
148                         NIPQUAD(arpinfo->smsk.s_addr),
149                         NIPQUAD(arpinfo->src.s_addr),
150                         arpinfo->invflags & ARPT_INV_SRCIP ? " (INV)" : "");
151                 dprintf("TGT: %u.%u.%u.%u Mask: %u.%u.%u.%u Target: %u.%u.%u.%u.%s\n",
152                         NIPQUAD(tgt_ipaddr),
153                         NIPQUAD(arpinfo->tmsk.s_addr),
154                         NIPQUAD(arpinfo->tgt.s_addr),
155                         arpinfo->invflags & ARPT_INV_TGTIP ? " (INV)" : "");
156                 return 0;
157         }
158
159         /* Look for ifname matches.  */
160         for (i = 0, ret = 0; i < IFNAMSIZ; i++) {
161                 ret |= (indev[i] ^ arpinfo->iniface[i])
162                         & arpinfo->iniface_mask[i];
163         }
164
165         if (FWINV(ret != 0, ARPT_INV_VIA_IN)) {
166                 dprintf("VIA in mismatch (%s vs %s).%s\n",
167                         indev, arpinfo->iniface,
168                         arpinfo->invflags&ARPT_INV_VIA_IN ?" (INV)":"");
169                 return 0;
170         }
171
172         for (i = 0, ret = 0; i < IFNAMSIZ/sizeof(unsigned long); i++) {
173                 unsigned long odev;
174                 memcpy(&odev, outdev + i*sizeof(unsigned long),
175                        sizeof(unsigned long));
176                 ret |= (odev
177                         ^ ((const unsigned long *)arpinfo->outiface)[i])
178                         & ((const unsigned long *)arpinfo->outiface_mask)[i];
179         }
180
181         if (FWINV(ret != 0, ARPT_INV_VIA_OUT)) {
182                 dprintf("VIA out mismatch (%s vs %s).%s\n",
183                         outdev, arpinfo->outiface,
184                         arpinfo->invflags&ARPT_INV_VIA_OUT ?" (INV)":"");
185                 return 0;
186         }
187
188         return 1;
189 }
190
191 static inline int arp_checkentry(const struct arpt_arp *arp)
192 {
193         if (arp->flags & ~ARPT_F_MASK) {
194                 duprintf("Unknown flag bits set: %08X\n",
195                          arp->flags & ~ARPT_F_MASK);
196                 return 0;
197         }
198         if (arp->invflags & ~ARPT_INV_MASK) {
199                 duprintf("Unknown invflag bits set: %08X\n",
200                          arp->invflags & ~ARPT_INV_MASK);
201                 return 0;
202         }
203
204         return 1;
205 }
206
207 static unsigned int arpt_error(struct sk_buff **pskb,
208                                const struct net_device *in,
209                                const struct net_device *out,
210                                unsigned int hooknum,
211                                const void *targinfo,
212                                void *userinfo)
213 {
214         if (net_ratelimit())
215                 printk("arp_tables: error: '%s'\n", (char *)targinfo);
216
217         return NF_DROP;
218 }
219
220 static inline struct arpt_entry *get_entry(void *base, unsigned int offset)
221 {
222         return (struct arpt_entry *)(base + offset);
223 }
224
225 unsigned int arpt_do_table(struct sk_buff **pskb,
226                            unsigned int hook,
227                            const struct net_device *in,
228                            const struct net_device *out,
229                            struct arpt_table *table,
230                            void *userdata)
231 {
232         static const char nulldevname[IFNAMSIZ];
233         unsigned int verdict = NF_DROP;
234         struct arphdr *arp;
235         int hotdrop = 0;
236         struct arpt_entry *e, *back;
237         const char *indev, *outdev;
238         void *table_base;
239         struct xt_table_info *private = table->private;
240
241         /* ARP header, plus 2 device addresses, plus 2 IP addresses.  */
242         if (!pskb_may_pull((*pskb), (sizeof(struct arphdr) +
243                                      (2 * (*pskb)->dev->addr_len) +
244                                      (2 * sizeof(u32)))))
245                 return NF_DROP;
246
247         indev = in ? in->name : nulldevname;
248         outdev = out ? out->name : nulldevname;
249
250         read_lock_bh(&table->lock);
251         table_base = (void *)private->entries[smp_processor_id()];
252         e = get_entry(table_base, private->hook_entry[hook]);
253         back = get_entry(table_base, private->underflow[hook]);
254
255         arp = (*pskb)->nh.arph;
256         do {
257                 if (arp_packet_match(arp, (*pskb)->dev, indev, outdev, &e->arp)) {
258                         struct arpt_entry_target *t;
259                         int hdr_len;
260
261                         hdr_len = sizeof(*arp) + (2 * sizeof(struct in_addr)) +
262                                 (2 * (*pskb)->dev->addr_len);
263                         ADD_COUNTER(e->counters, hdr_len, 1);
264
265                         t = arpt_get_target(e);
266
267                         /* Standard target? */
268                         if (!t->u.kernel.target->target) {
269                                 int v;
270
271                                 v = ((struct arpt_standard_target *)t)->verdict;
272                                 if (v < 0) {
273                                         /* Pop from stack? */
274                                         if (v != ARPT_RETURN) {
275                                                 verdict = (unsigned)(-v) - 1;
276                                                 break;
277                                         }
278                                         e = back;
279                                         back = get_entry(table_base,
280                                                          back->comefrom);
281                                         continue;
282                                 }
283                                 if (table_base + v
284                                     != (void *)e + e->next_offset) {
285                                         /* Save old back ptr in next entry */
286                                         struct arpt_entry *next
287                                                 = (void *)e + e->next_offset;
288                                         next->comefrom =
289                                                 (void *)back - table_base;
290
291                                         /* set back pointer to next entry */
292                                         back = next;
293                                 }
294
295                                 e = get_entry(table_base, v);
296                         } else {
297                                 /* Targets which reenter must return
298                                  * abs. verdicts
299                                  */
300                                 verdict = t->u.kernel.target->target(pskb,
301                                                                      in, out,
302                                                                      hook,
303                                                                      t->data,
304                                                                      userdata);
305
306                                 /* Target might have changed stuff. */
307                                 arp = (*pskb)->nh.arph;
308
309                                 if (verdict == ARPT_CONTINUE)
310                                         e = (void *)e + e->next_offset;
311                                 else
312                                         /* Verdict */
313                                         break;
314                         }
315                 } else {
316                         e = (void *)e + e->next_offset;
317                 }
318         } while (!hotdrop);
319         read_unlock_bh(&table->lock);
320
321         if (hotdrop)
322                 return NF_DROP;
323         else
324                 return verdict;
325 }
326
327 /* All zeroes == unconditional rule. */
328 static inline int unconditional(const struct arpt_arp *arp)
329 {
330         unsigned int i;
331
332         for (i = 0; i < sizeof(*arp)/sizeof(__u32); i++)
333                 if (((__u32 *)arp)[i])
334                         return 0;
335
336         return 1;
337 }
338
339 /* Figures out from what hook each rule can be called: returns 0 if
340  * there are loops.  Puts hook bitmask in comefrom.
341  */
342 static int mark_source_chains(struct xt_table_info *newinfo,
343                               unsigned int valid_hooks, void *entry0)
344 {
345         unsigned int hook;
346
347         /* No recursion; use packet counter to save back ptrs (reset
348          * to 0 as we leave), and comefrom to save source hook bitmask.
349          */
350         for (hook = 0; hook < NF_ARP_NUMHOOKS; hook++) {
351                 unsigned int pos = newinfo->hook_entry[hook];
352                 struct arpt_entry *e
353                         = (struct arpt_entry *)(entry0 + pos);
354
355                 if (!(valid_hooks & (1 << hook)))
356                         continue;
357
358                 /* Set initial back pointer. */
359                 e->counters.pcnt = pos;
360
361                 for (;;) {
362                         struct arpt_standard_target *t
363                                 = (void *)arpt_get_target(e);
364
365                         if (e->comefrom & (1 << NF_ARP_NUMHOOKS)) {
366                                 printk("arptables: loop hook %u pos %u %08X.\n",
367                                        hook, pos, e->comefrom);
368                                 return 0;
369                         }
370                         e->comefrom
371                                 |= ((1 << hook) | (1 << NF_ARP_NUMHOOKS));
372
373                         /* Unconditional return/END. */
374                         if (e->target_offset == sizeof(struct arpt_entry)
375                             && (strcmp(t->target.u.user.name,
376                                        ARPT_STANDARD_TARGET) == 0)
377                             && t->verdict < 0
378                             && unconditional(&e->arp)) {
379                                 unsigned int oldpos, size;
380
381                                 /* Return: backtrack through the last
382                                  * big jump.
383                                  */
384                                 do {
385                                         e->comefrom ^= (1<<NF_ARP_NUMHOOKS);
386                                         oldpos = pos;
387                                         pos = e->counters.pcnt;
388                                         e->counters.pcnt = 0;
389
390                                         /* We're at the start. */
391                                         if (pos == oldpos)
392                                                 goto next;
393
394                                         e = (struct arpt_entry *)
395                                                 (entry0 + pos);
396                                 } while (oldpos == pos + e->next_offset);
397
398                                 /* Move along one */
399                                 size = e->next_offset;
400                                 e = (struct arpt_entry *)
401                                         (entry0 + pos + size);
402                                 e->counters.pcnt = pos;
403                                 pos += size;
404                         } else {
405                                 int newpos = t->verdict;
406
407                                 if (strcmp(t->target.u.user.name,
408                                            ARPT_STANDARD_TARGET) == 0
409                                     && newpos >= 0) {
410                                         /* This a jump; chase it. */
411                                         duprintf("Jump rule %u -> %u\n",
412                                                  pos, newpos);
413                                 } else {
414                                         /* ... this is a fallthru */
415                                         newpos = pos + e->next_offset;
416                                 }
417                                 e = (struct arpt_entry *)
418                                         (entry0 + newpos);
419                                 e->counters.pcnt = pos;
420                                 pos = newpos;
421                         }
422                 }
423                 next:
424                 duprintf("Finished chain %u\n", hook);
425         }
426         return 1;
427 }
428
429 static inline int standard_check(const struct arpt_entry_target *t,
430                                  unsigned int max_offset)
431 {
432         struct arpt_standard_target *targ = (void *)t;
433
434         /* Check standard info. */
435         if (t->u.target_size
436             != ARPT_ALIGN(sizeof(struct arpt_standard_target))) {
437                 duprintf("arpt_standard_check: target size %u != %Zu\n",
438                          t->u.target_size,
439                          ARPT_ALIGN(sizeof(struct arpt_standard_target)));
440                 return 0;
441         }
442
443         if (targ->verdict >= 0
444             && targ->verdict > max_offset - sizeof(struct arpt_entry)) {
445                 duprintf("arpt_standard_check: bad verdict (%i)\n",
446                          targ->verdict);
447                 return 0;
448         }
449
450         if (targ->verdict < -NF_MAX_VERDICT - 1) {
451                 duprintf("arpt_standard_check: bad negative verdict (%i)\n",
452                          targ->verdict);
453                 return 0;
454         }
455         return 1;
456 }
457
458 static struct arpt_target arpt_standard_target;
459
460 static inline int check_entry(struct arpt_entry *e, const char *name, unsigned int size,
461                               unsigned int *i)
462 {
463         struct arpt_entry_target *t;
464         struct arpt_target *target;
465         int ret;
466
467         if (!arp_checkentry(&e->arp)) {
468                 duprintf("arp_tables: arp check failed %p %s.\n", e, name);
469                 return -EINVAL;
470         }
471
472         t = arpt_get_target(e);
473         target = try_then_request_module(xt_find_target(NF_ARP, t->u.user.name,
474                                                         t->u.user.revision),
475                                          "arpt_%s", t->u.user.name);
476         if (IS_ERR(target) || !target) {
477                 duprintf("check_entry: `%s' not found\n", t->u.user.name);
478                 ret = target ? PTR_ERR(target) : -ENOENT;
479                 goto out;
480         }
481         t->u.kernel.target = target;
482
483         ret = xt_check_target(target, NF_ARP, t->u.target_size - sizeof(*t),
484                               name, e->comefrom, 0, 0);
485         if (ret)
486                 goto err;
487
488         if (t->u.kernel.target == &arpt_standard_target) {
489                 if (!standard_check(t, size)) {
490                         ret = -EINVAL;
491                         goto out;
492                 }
493         } else if (t->u.kernel.target->checkentry
494                    && !t->u.kernel.target->checkentry(name, e, t->data,
495                                                       t->u.target_size
496                                                       - sizeof(*t),
497                                                       e->comefrom)) {
498                 duprintf("arp_tables: check failed for `%s'.\n",
499                          t->u.kernel.target->name);
500                 ret = -EINVAL;
501                 goto err;
502         }
503
504         (*i)++;
505         return 0;
506 err:
507         module_put(t->u.kernel.target->me);
508 out:
509         return ret;
510 }
511
512 static inline int check_entry_size_and_hooks(struct arpt_entry *e,
513                                              struct xt_table_info *newinfo,
514                                              unsigned char *base,
515                                              unsigned char *limit,
516                                              const unsigned int *hook_entries,
517                                              const unsigned int *underflows,
518                                              unsigned int *i)
519 {
520         unsigned int h;
521
522         if ((unsigned long)e % __alignof__(struct arpt_entry) != 0
523             || (unsigned char *)e + sizeof(struct arpt_entry) >= limit) {
524                 duprintf("Bad offset %p\n", e);
525                 return -EINVAL;
526         }
527
528         if (e->next_offset
529             < sizeof(struct arpt_entry) + sizeof(struct arpt_entry_target)) {
530                 duprintf("checking: element %p size %u\n",
531                          e, e->next_offset);
532                 return -EINVAL;
533         }
534
535         /* Check hooks & underflows */
536         for (h = 0; h < NF_ARP_NUMHOOKS; h++) {
537                 if ((unsigned char *)e - base == hook_entries[h])
538                         newinfo->hook_entry[h] = hook_entries[h];
539                 if ((unsigned char *)e - base == underflows[h])
540                         newinfo->underflow[h] = underflows[h];
541         }
542
543         /* FIXME: underflows must be unconditional, standard verdicts
544            < 0 (not ARPT_RETURN). --RR */
545
546         /* Clear counters and comefrom */
547         e->counters = ((struct xt_counters) { 0, 0 });
548         e->comefrom = 0;
549
550         (*i)++;
551         return 0;
552 }
553
554 static inline int cleanup_entry(struct arpt_entry *e, unsigned int *i)
555 {
556         struct arpt_entry_target *t;
557
558         if (i && (*i)-- == 0)
559                 return 1;
560
561         t = arpt_get_target(e);
562         if (t->u.kernel.target->destroy)
563                 t->u.kernel.target->destroy(t->data,
564                                             t->u.target_size - sizeof(*t));
565         module_put(t->u.kernel.target->me);
566         return 0;
567 }
568
569 /* Checks and translates the user-supplied table segment (held in
570  * newinfo).
571  */
572 static int translate_table(const char *name,
573                            unsigned int valid_hooks,
574                            struct xt_table_info *newinfo,
575                            void *entry0,
576                            unsigned int size,
577                            unsigned int number,
578                            const unsigned int *hook_entries,
579                            const unsigned int *underflows)
580 {
581         unsigned int i;
582         int ret;
583
584         newinfo->size = size;
585         newinfo->number = number;
586
587         /* Init all hooks to impossible value. */
588         for (i = 0; i < NF_ARP_NUMHOOKS; i++) {
589                 newinfo->hook_entry[i] = 0xFFFFFFFF;
590                 newinfo->underflow[i] = 0xFFFFFFFF;
591         }
592
593         duprintf("translate_table: size %u\n", newinfo->size);
594         i = 0;
595
596         /* Walk through entries, checking offsets. */
597         ret = ARPT_ENTRY_ITERATE(entry0, newinfo->size,
598                                  check_entry_size_and_hooks,
599                                  newinfo,
600                                  entry0,
601                                  entry0 + size,
602                                  hook_entries, underflows, &i);
603         duprintf("translate_table: ARPT_ENTRY_ITERATE gives %d\n", ret);
604         if (ret != 0)
605                 return ret;
606
607         if (i != number) {
608                 duprintf("translate_table: %u not %u entries\n",
609                          i, number);
610                 return -EINVAL;
611         }
612
613         /* Check hooks all assigned */
614         for (i = 0; i < NF_ARP_NUMHOOKS; i++) {
615                 /* Only hooks which are valid */
616                 if (!(valid_hooks & (1 << i)))
617                         continue;
618                 if (newinfo->hook_entry[i] == 0xFFFFFFFF) {
619                         duprintf("Invalid hook entry %u %u\n",
620                                  i, hook_entries[i]);
621                         return -EINVAL;
622                 }
623                 if (newinfo->underflow[i] == 0xFFFFFFFF) {
624                         duprintf("Invalid underflow %u %u\n",
625                                  i, underflows[i]);
626                         return -EINVAL;
627                 }
628         }
629
630         if (!mark_source_chains(newinfo, valid_hooks, entry0)) {
631                 duprintf("Looping hook\n");
632                 return -ELOOP;
633         }
634
635         /* Finally, each sanity check must pass */
636         i = 0;
637         ret = ARPT_ENTRY_ITERATE(entry0, newinfo->size,
638                                  check_entry, name, size, &i);
639
640         if (ret != 0) {
641                 ARPT_ENTRY_ITERATE(entry0, newinfo->size,
642                                    cleanup_entry, &i);
643                 return ret;
644         }
645
646         /* And one copy for every other CPU */
647         for_each_cpu(i) {
648                 if (newinfo->entries[i] && newinfo->entries[i] != entry0)
649                         memcpy(newinfo->entries[i], entry0, newinfo->size);
650         }
651
652         return ret;
653 }
654
655 /* Gets counters. */
656 static inline int add_entry_to_counter(const struct arpt_entry *e,
657                                        struct xt_counters total[],
658                                        unsigned int *i)
659 {
660         ADD_COUNTER(total[*i], e->counters.bcnt, e->counters.pcnt);
661
662         (*i)++;
663         return 0;
664 }
665
666 static inline int set_entry_to_counter(const struct arpt_entry *e,
667                                        struct xt_counters total[],
668                                        unsigned int *i)
669 {
670         SET_COUNTER(total[*i], e->counters.bcnt, e->counters.pcnt);
671
672         (*i)++;
673         return 0;
674 }
675
676 static void get_counters(const struct xt_table_info *t,
677                          struct xt_counters counters[])
678 {
679         unsigned int cpu;
680         unsigned int i;
681         unsigned int curcpu;
682
683         /* Instead of clearing (by a previous call to memset())
684          * the counters and using adds, we set the counters
685          * with data used by 'current' CPU
686          * We dont care about preemption here.
687          */
688         curcpu = raw_smp_processor_id();
689
690         i = 0;
691         ARPT_ENTRY_ITERATE(t->entries[curcpu],
692                            t->size,
693                            set_entry_to_counter,
694                            counters,
695                            &i);
696
697         for_each_cpu(cpu) {
698                 if (cpu == curcpu)
699                         continue;
700                 i = 0;
701                 ARPT_ENTRY_ITERATE(t->entries[cpu],
702                                    t->size,
703                                    add_entry_to_counter,
704                                    counters,
705                                    &i);
706         }
707 }
708
709 static int copy_entries_to_user(unsigned int total_size,
710                                 struct arpt_table *table,
711                                 void __user *userptr)
712 {
713         unsigned int off, num, countersize;
714         struct arpt_entry *e;
715         struct xt_counters *counters;
716         struct xt_table_info *private = table->private;
717         int ret = 0;
718         void *loc_cpu_entry;
719
720         /* We need atomic snapshot of counters: rest doesn't change
721          * (other than comefrom, which userspace doesn't care
722          * about).
723          */
724         countersize = sizeof(struct xt_counters) * private->number;
725         counters = vmalloc_node(countersize, numa_node_id());
726
727         if (counters == NULL)
728                 return -ENOMEM;
729
730         /* First, sum counters... */
731         write_lock_bh(&table->lock);
732         get_counters(private, counters);
733         write_unlock_bh(&table->lock);
734
735         loc_cpu_entry = private->entries[raw_smp_processor_id()];
736         /* ... then copy entire thing ... */
737         if (copy_to_user(userptr, loc_cpu_entry, total_size) != 0) {
738                 ret = -EFAULT;
739                 goto free_counters;
740         }
741
742         /* FIXME: use iterator macros --RR */
743         /* ... then go back and fix counters and names */
744         for (off = 0, num = 0; off < total_size; off += e->next_offset, num++){
745                 struct arpt_entry_target *t;
746
747                 e = (struct arpt_entry *)(loc_cpu_entry + off);
748                 if (copy_to_user(userptr + off
749                                  + offsetof(struct arpt_entry, counters),
750                                  &counters[num],
751                                  sizeof(counters[num])) != 0) {
752                         ret = -EFAULT;
753                         goto free_counters;
754                 }
755
756                 t = arpt_get_target(e);
757                 if (copy_to_user(userptr + off + e->target_offset
758                                  + offsetof(struct arpt_entry_target,
759                                             u.user.name),
760                                  t->u.kernel.target->name,
761                                  strlen(t->u.kernel.target->name)+1) != 0) {
762                         ret = -EFAULT;
763                         goto free_counters;
764                 }
765         }
766
767  free_counters:
768         vfree(counters);
769         return ret;
770 }
771
772 static int get_entries(const struct arpt_get_entries *entries,
773                        struct arpt_get_entries __user *uptr)
774 {
775         int ret;
776         struct arpt_table *t;
777
778         t = xt_find_table_lock(NF_ARP, entries->name);
779         if (t && !IS_ERR(t)) {
780                 struct xt_table_info *private = t->private;
781                 duprintf("t->private->number = %u\n",
782                          private->number);
783                 if (entries->size == private->size)
784                         ret = copy_entries_to_user(private->size,
785                                                    t, uptr->entrytable);
786                 else {
787                         duprintf("get_entries: I've got %u not %u!\n",
788                                  private->size, entries->size);
789                         ret = -EINVAL;
790                 }
791                 module_put(t->me);
792                 xt_table_unlock(t);
793         } else
794                 ret = t ? PTR_ERR(t) : -ENOENT;
795
796         return ret;
797 }
798
799 static int do_replace(void __user *user, unsigned int len)
800 {
801         int ret;
802         struct arpt_replace tmp;
803         struct arpt_table *t;
804         struct xt_table_info *newinfo, *oldinfo;
805         struct xt_counters *counters;
806         void *loc_cpu_entry, *loc_cpu_old_entry;
807
808         if (copy_from_user(&tmp, user, sizeof(tmp)) != 0)
809                 return -EFAULT;
810
811         /* Hack: Causes ipchains to give correct error msg --RR */
812         if (len != sizeof(tmp) + tmp.size)
813                 return -ENOPROTOOPT;
814
815         /* overflow check */
816         if (tmp.size >= (INT_MAX - sizeof(struct xt_table_info)) / NR_CPUS -
817                         SMP_CACHE_BYTES)
818                 return -ENOMEM;
819         if (tmp.num_counters >= INT_MAX / sizeof(struct xt_counters))
820                 return -ENOMEM;
821
822         newinfo = xt_alloc_table_info(tmp.size);
823         if (!newinfo)
824                 return -ENOMEM;
825
826         /* choose the copy that is on our node/cpu */
827         loc_cpu_entry = newinfo->entries[raw_smp_processor_id()];
828         if (copy_from_user(loc_cpu_entry, user + sizeof(tmp),
829                            tmp.size) != 0) {
830                 ret = -EFAULT;
831                 goto free_newinfo;
832         }
833
834         counters = vmalloc(tmp.num_counters * sizeof(struct xt_counters));
835         if (!counters) {
836                 ret = -ENOMEM;
837                 goto free_newinfo;
838         }
839
840         ret = translate_table(tmp.name, tmp.valid_hooks,
841                               newinfo, loc_cpu_entry, tmp.size, tmp.num_entries,
842                               tmp.hook_entry, tmp.underflow);
843         if (ret != 0)
844                 goto free_newinfo_counters;
845
846         duprintf("arp_tables: Translated table\n");
847
848         t = try_then_request_module(xt_find_table_lock(NF_ARP, tmp.name),
849                                     "arptable_%s", tmp.name);
850         if (!t || IS_ERR(t)) {
851                 ret = t ? PTR_ERR(t) : -ENOENT;
852                 goto free_newinfo_counters_untrans;
853         }
854
855         /* You lied! */
856         if (tmp.valid_hooks != t->valid_hooks) {
857                 duprintf("Valid hook crap: %08X vs %08X\n",
858                          tmp.valid_hooks, t->valid_hooks);
859                 ret = -EINVAL;
860                 goto put_module;
861         }
862
863         oldinfo = xt_replace_table(t, tmp.num_counters, newinfo, &ret);
864         if (!oldinfo)
865                 goto put_module;
866
867         /* Update module usage count based on number of rules */
868         duprintf("do_replace: oldnum=%u, initnum=%u, newnum=%u\n",
869                 oldinfo->number, oldinfo->initial_entries, newinfo->number);
870         if ((oldinfo->number > oldinfo->initial_entries) || 
871             (newinfo->number <= oldinfo->initial_entries)) 
872                 module_put(t->me);
873         if ((oldinfo->number > oldinfo->initial_entries) &&
874             (newinfo->number <= oldinfo->initial_entries))
875                 module_put(t->me);
876
877         /* Get the old counters. */
878         get_counters(oldinfo, counters);
879         /* Decrease module usage counts and free resource */
880         loc_cpu_old_entry = oldinfo->entries[raw_smp_processor_id()];
881         ARPT_ENTRY_ITERATE(loc_cpu_old_entry, oldinfo->size, cleanup_entry,NULL);
882
883         xt_free_table_info(oldinfo);
884         if (copy_to_user(tmp.counters, counters,
885                          sizeof(struct xt_counters) * tmp.num_counters) != 0)
886                 ret = -EFAULT;
887         vfree(counters);
888         xt_table_unlock(t);
889         return ret;
890
891  put_module:
892         module_put(t->me);
893         xt_table_unlock(t);
894  free_newinfo_counters_untrans:
895         ARPT_ENTRY_ITERATE(loc_cpu_entry, newinfo->size, cleanup_entry, NULL);
896  free_newinfo_counters:
897         vfree(counters);
898  free_newinfo:
899         xt_free_table_info(newinfo);
900         return ret;
901 }
902
903 /* We're lazy, and add to the first CPU; overflow works its fey magic
904  * and everything is OK.
905  */
906 static inline int add_counter_to_entry(struct arpt_entry *e,
907                                        const struct xt_counters addme[],
908                                        unsigned int *i)
909 {
910
911         ADD_COUNTER(e->counters, addme[*i].bcnt, addme[*i].pcnt);
912
913         (*i)++;
914         return 0;
915 }
916
917 static int do_add_counters(void __user *user, unsigned int len)
918 {
919         unsigned int i;
920         struct xt_counters_info tmp, *paddc;
921         struct arpt_table *t;
922         struct xt_table_info *private;
923         int ret = 0;
924         void *loc_cpu_entry;
925
926         if (copy_from_user(&tmp, user, sizeof(tmp)) != 0)
927                 return -EFAULT;
928
929         if (len != sizeof(tmp) + tmp.num_counters*sizeof(struct xt_counters))
930                 return -EINVAL;
931
932         paddc = vmalloc(len);
933         if (!paddc)
934                 return -ENOMEM;
935
936         if (copy_from_user(paddc, user, len) != 0) {
937                 ret = -EFAULT;
938                 goto free;
939         }
940
941         t = xt_find_table_lock(NF_ARP, tmp.name);
942         if (!t || IS_ERR(t)) {
943                 ret = t ? PTR_ERR(t) : -ENOENT;
944                 goto free;
945         }
946
947         write_lock_bh(&t->lock);
948         private = t->private;
949         if (private->number != paddc->num_counters) {
950                 ret = -EINVAL;
951                 goto unlock_up_free;
952         }
953
954         i = 0;
955         /* Choose the copy that is on our node */
956         loc_cpu_entry = private->entries[smp_processor_id()];
957         ARPT_ENTRY_ITERATE(loc_cpu_entry,
958                            private->size,
959                            add_counter_to_entry,
960                            paddc->counters,
961                            &i);
962  unlock_up_free:
963         write_unlock_bh(&t->lock);
964         xt_table_unlock(t);
965         module_put(t->me);
966  free:
967         vfree(paddc);
968
969         return ret;
970 }
971
972 static int do_arpt_set_ctl(struct sock *sk, int cmd, void __user *user, unsigned int len)
973 {
974         int ret;
975
976         if (!capable(CAP_NET_ADMIN))
977                 return -EPERM;
978
979         switch (cmd) {
980         case ARPT_SO_SET_REPLACE:
981                 ret = do_replace(user, len);
982                 break;
983
984         case ARPT_SO_SET_ADD_COUNTERS:
985                 ret = do_add_counters(user, len);
986                 break;
987
988         default:
989                 duprintf("do_arpt_set_ctl:  unknown request %i\n", cmd);
990                 ret = -EINVAL;
991         }
992
993         return ret;
994 }
995
996 static int do_arpt_get_ctl(struct sock *sk, int cmd, void __user *user, int *len)
997 {
998         int ret;
999
1000         if (!capable(CAP_NET_ADMIN))
1001                 return -EPERM;
1002
1003         switch (cmd) {
1004         case ARPT_SO_GET_INFO: {
1005                 char name[ARPT_TABLE_MAXNAMELEN];
1006                 struct arpt_table *t;
1007
1008                 if (*len != sizeof(struct arpt_getinfo)) {
1009                         duprintf("length %u != %Zu\n", *len,
1010                                  sizeof(struct arpt_getinfo));
1011                         ret = -EINVAL;
1012                         break;
1013                 }
1014
1015                 if (copy_from_user(name, user, sizeof(name)) != 0) {
1016                         ret = -EFAULT;
1017                         break;
1018                 }
1019                 name[ARPT_TABLE_MAXNAMELEN-1] = '\0';
1020
1021                 t = try_then_request_module(xt_find_table_lock(NF_ARP, name),
1022                                             "arptable_%s", name);
1023                 if (t && !IS_ERR(t)) {
1024                         struct arpt_getinfo info;
1025                         struct xt_table_info *private = t->private;
1026
1027                         info.valid_hooks = t->valid_hooks;
1028                         memcpy(info.hook_entry, private->hook_entry,
1029                                sizeof(info.hook_entry));
1030                         memcpy(info.underflow, private->underflow,
1031                                sizeof(info.underflow));
1032                         info.num_entries = private->number;
1033                         info.size = private->size;
1034                         strcpy(info.name, name);
1035
1036                         if (copy_to_user(user, &info, *len) != 0)
1037                                 ret = -EFAULT;
1038                         else
1039                                 ret = 0;
1040                         xt_table_unlock(t);
1041                         module_put(t->me);
1042                 } else
1043                         ret = t ? PTR_ERR(t) : -ENOENT;
1044         }
1045         break;
1046
1047         case ARPT_SO_GET_ENTRIES: {
1048                 struct arpt_get_entries get;
1049
1050                 if (*len < sizeof(get)) {
1051                         duprintf("get_entries: %u < %Zu\n", *len, sizeof(get));
1052                         ret = -EINVAL;
1053                 } else if (copy_from_user(&get, user, sizeof(get)) != 0) {
1054                         ret = -EFAULT;
1055                 } else if (*len != sizeof(struct arpt_get_entries) + get.size) {
1056                         duprintf("get_entries: %u != %Zu\n", *len,
1057                                  sizeof(struct arpt_get_entries) + get.size);
1058                         ret = -EINVAL;
1059                 } else
1060                         ret = get_entries(&get, user);
1061                 break;
1062         }
1063
1064         case ARPT_SO_GET_REVISION_TARGET: {
1065                 struct xt_get_revision rev;
1066
1067                 if (*len != sizeof(rev)) {
1068                         ret = -EINVAL;
1069                         break;
1070                 }
1071                 if (copy_from_user(&rev, user, sizeof(rev)) != 0) {
1072                         ret = -EFAULT;
1073                         break;
1074                 }
1075
1076                 try_then_request_module(xt_find_revision(NF_ARP, rev.name,
1077                                                          rev.revision, 1, &ret),
1078                                         "arpt_%s", rev.name);
1079                 break;
1080         }
1081
1082         default:
1083                 duprintf("do_arpt_get_ctl: unknown request %i\n", cmd);
1084                 ret = -EINVAL;
1085         }
1086
1087         return ret;
1088 }
1089
1090 int arpt_register_table(struct arpt_table *table,
1091                         const struct arpt_replace *repl)
1092 {
1093         int ret;
1094         struct xt_table_info *newinfo;
1095         static struct xt_table_info bootstrap
1096                 = { 0, 0, 0, { 0 }, { 0 }, { } };
1097         void *loc_cpu_entry;
1098
1099         newinfo = xt_alloc_table_info(repl->size);
1100         if (!newinfo) {
1101                 ret = -ENOMEM;
1102                 return ret;
1103         }
1104
1105         /* choose the copy on our node/cpu */
1106         loc_cpu_entry = newinfo->entries[raw_smp_processor_id()];
1107         memcpy(loc_cpu_entry, repl->entries, repl->size);
1108
1109         ret = translate_table(table->name, table->valid_hooks,
1110                               newinfo, loc_cpu_entry, repl->size,
1111                               repl->num_entries,
1112                               repl->hook_entry,
1113                               repl->underflow);
1114
1115         duprintf("arpt_register_table: translate table gives %d\n", ret);
1116         if (ret != 0) {
1117                 xt_free_table_info(newinfo);
1118                 return ret;
1119         }
1120
1121         if (xt_register_table(table, &bootstrap, newinfo) != 0) {
1122                 xt_free_table_info(newinfo);
1123                 return ret;
1124         }
1125
1126         return 0;
1127 }
1128
1129 void arpt_unregister_table(struct arpt_table *table)
1130 {
1131         struct xt_table_info *private;
1132         void *loc_cpu_entry;
1133
1134         private = xt_unregister_table(table);
1135
1136         /* Decrease module usage counts and free resources */
1137         loc_cpu_entry = private->entries[raw_smp_processor_id()];
1138         ARPT_ENTRY_ITERATE(loc_cpu_entry, private->size,
1139                            cleanup_entry, NULL);
1140         xt_free_table_info(private);
1141 }
1142
1143 /* The built-in targets: standard (NULL) and error. */
1144 static struct arpt_target arpt_standard_target = {
1145         .name           = ARPT_STANDARD_TARGET,
1146         .targetsize     = sizeof(int),
1147 };
1148
1149 static struct arpt_target arpt_error_target = {
1150         .name           = ARPT_ERROR_TARGET,
1151         .target         = arpt_error,
1152         .targetsize     = ARPT_FUNCTION_MAXNAMELEN,
1153 };
1154
1155 static struct nf_sockopt_ops arpt_sockopts = {
1156         .pf             = PF_INET,
1157         .set_optmin     = ARPT_BASE_CTL,
1158         .set_optmax     = ARPT_SO_SET_MAX+1,
1159         .set            = do_arpt_set_ctl,
1160         .get_optmin     = ARPT_BASE_CTL,
1161         .get_optmax     = ARPT_SO_GET_MAX+1,
1162         .get            = do_arpt_get_ctl,
1163 };
1164
1165 static int __init init(void)
1166 {
1167         int ret;
1168
1169         xt_proto_init(NF_ARP);
1170
1171         /* Noone else will be downing sem now, so we won't sleep */
1172         xt_register_target(NF_ARP, &arpt_standard_target);
1173         xt_register_target(NF_ARP, &arpt_error_target);
1174
1175         /* Register setsockopt */
1176         ret = nf_register_sockopt(&arpt_sockopts);
1177         if (ret < 0) {
1178                 duprintf("Unable to register sockopts.\n");
1179                 return ret;
1180         }
1181
1182         printk("arp_tables: (C) 2002 David S. Miller\n");
1183         return 0;
1184 }
1185
1186 static void __exit fini(void)
1187 {
1188         nf_unregister_sockopt(&arpt_sockopts);
1189         xt_proto_fini(NF_ARP);
1190 }
1191
1192 EXPORT_SYMBOL(arpt_register_table);
1193 EXPORT_SYMBOL(arpt_unregister_table);
1194 EXPORT_SYMBOL(arpt_do_table);
1195
1196 module_init(init);
1197 module_exit(fini);