Merge commit 'origin/trunk@12184' into fedora
[iptables.git] / ip6tables.c.selinux
1 /* Code to take an iptables-style command line and do it. */
2
3 /*
4  * Author: Paul.Russell@rustcorp.com.au and mneuling@radlogic.com.au
5  *
6  * (C) 2000-2002 by the netfilter coreteam <coreteam@netfilter.org>:
7  *                  Paul 'Rusty' Russell <rusty@rustcorp.com.au>
8  *                  Marc Boucher <marc+nf@mbsi.ca>
9  *                  James Morris <jmorris@intercode.com.au>
10  *                  Harald Welte <laforge@gnumonks.org>
11  *                  Jozsef Kadlecsik <kadlec@blackhole.kfki.hu>
12  *
13  *      This program is free software; you can redistribute it and/or modify
14  *      it under the terms of the GNU General Public License as published by
15  *      the Free Software Foundation; either version 2 of the License, or
16  *      (at your option) any later version.
17  *
18  *      This program is distributed in the hope that it will be useful,
19  *      but WITHOUT ANY WARRANTY; without even the implied warranty of
20  *      MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
21  *      GNU General Public License for more details.
22  *
23  *      You should have received a copy of the GNU General Public License
24  *      along with this program; if not, write to the Free Software
25  *      Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
26  */
27
28 #include <getopt.h>
29 #include <string.h>
30 #include <netdb.h>
31 #include <errno.h>
32 #include <stdio.h>
33 #include <stdlib.h>
34 #include <dlfcn.h>
35 #include <ctype.h>
36 #include <stdarg.h>
37 #include <limits.h>
38 #include <ip6tables.h>
39 #include <arpa/inet.h>
40 #include <unistd.h>
41 #include <fcntl.h>
42 #include <sys/wait.h>
43 #include <sys/types.h>
44 #include <sys/socket.h>
45
46 #ifndef TRUE
47 #define TRUE 1
48 #endif
49 #ifndef FALSE
50 #define FALSE 0
51 #endif
52
53 #ifndef IP6T_LIB_DIR
54 #define IP6T_LIB_DIR "/usr/lib/iptables"
55 #endif
56
57 #ifndef PROC_SYS_MODPROBE
58 #define PROC_SYS_MODPROBE "/proc/sys/kernel/modprobe"
59 #endif
60
61 #define FMT_NUMERIC     0x0001
62 #define FMT_NOCOUNTS    0x0002
63 #define FMT_KILOMEGAGIGA 0x0004
64 #define FMT_OPTIONS     0x0008
65 #define FMT_NOTABLE     0x0010
66 #define FMT_NOTARGET    0x0020
67 #define FMT_VIA         0x0040
68 #define FMT_NONEWLINE   0x0080
69 #define FMT_LINENUMBERS 0x0100
70
71 #define FMT_PRINT_RULE (FMT_NOCOUNTS | FMT_OPTIONS | FMT_VIA \
72                         | FMT_NUMERIC | FMT_NOTABLE)
73 #define FMT(tab,notab) ((format) & FMT_NOTABLE ? (notab) : (tab))
74
75
76 #define CMD_NONE                0x0000U
77 #define CMD_INSERT              0x0001U
78 #define CMD_DELETE              0x0002U
79 #define CMD_DELETE_NUM          0x0004U
80 #define CMD_REPLACE             0x0008U
81 #define CMD_APPEND              0x0010U
82 #define CMD_LIST                0x0020U
83 #define CMD_FLUSH               0x0040U
84 #define CMD_ZERO                0x0080U
85 #define CMD_NEW_CHAIN           0x0100U
86 #define CMD_DELETE_CHAIN        0x0200U
87 #define CMD_SET_POLICY          0x0400U
88 #define CMD_CHECK               0x0800U
89 #define CMD_RENAME_CHAIN        0x1000U
90 #define NUMBER_OF_CMD   13
91 static const char cmdflags[] = { 'I', 'D', 'D', 'R', 'A', 'L', 'F', 'Z',
92                                  'N', 'X', 'P', 'E' };
93
94 #define OPTION_OFFSET 256
95
96 #define OPT_NONE        0x00000U
97 #define OPT_NUMERIC     0x00001U
98 #define OPT_SOURCE      0x00002U
99 #define OPT_DESTINATION 0x00004U
100 #define OPT_PROTOCOL    0x00008U
101 #define OPT_JUMP        0x00010U
102 #define OPT_VERBOSE     0x00020U
103 #define OPT_EXPANDED    0x00040U
104 #define OPT_VIANAMEIN   0x00080U
105 #define OPT_VIANAMEOUT  0x00100U
106 #define OPT_LINENUMBERS 0x00200U
107 #define OPT_COUNTERS    0x00400U
108 #define NUMBER_OF_OPT   11
109 static const char optflags[NUMBER_OF_OPT]
110 = { 'n', 's', 'd', 'p', 'j', 'v', 'x', 'i', 'o', '3', 'c'};
111
112 static struct option original_opts[] = {
113         { "append", 1, 0, 'A' },
114         { "delete", 1, 0,  'D' },
115         { "insert", 1, 0,  'I' },
116         { "replace", 1, 0,  'R' },
117         { "list", 2, 0,  'L' },
118         { "flush", 2, 0,  'F' },
119         { "zero", 2, 0,  'Z' },
120         { "new-chain", 1, 0,  'N' },
121         { "delete-chain", 2, 0,  'X' },
122         { "rename-chain", 1, 0,  'E' },
123         { "policy", 1, 0,  'P' },
124         { "source", 1, 0, 's' },
125         { "destination", 1, 0,  'd' },
126         { "src", 1, 0,  's' }, /* synonym */
127         { "dst", 1, 0,  'd' }, /* synonym */
128         { "protocol", 1, 0,  'p' },
129         { "in-interface", 1, 0, 'i' },
130         { "jump", 1, 0, 'j' },
131         { "table", 1, 0, 't' },
132         { "match", 1, 0, 'm' },
133         { "numeric", 0, 0, 'n' },
134         { "out-interface", 1, 0, 'o' },
135         { "verbose", 0, 0, 'v' },
136         { "exact", 0, 0, 'x' },
137         { "version", 0, 0, 'V' },
138         { "help", 2, 0, 'h' },
139         { "line-numbers", 0, 0, '0' },
140         { "modprobe", 1, 0, 'M' },
141         { "set-counters", 1, 0, 'c' },
142         { 0 }
143 };
144
145 /* we need this for ip6tables-restore. ip6tables-restore.c sets line to the
146  * current line of the input file, in order to give a more precise error
147  * message. ip6tables itself doesn't need this, so it is initialized to the
148  * magic number of -1 */
149 int line = -1;
150
151 #ifndef __OPTIMIZE__
152 struct ip6t_entry_target *
153 ip6t_get_target(struct ip6t_entry *e)
154 {
155         return (void *)e + e->target_offset;
156 }
157 #endif
158
159 static struct option *opts = original_opts;
160 static unsigned int global_option_offset = 0;
161
162 /* Table of legal combinations of commands and options.  If any of the
163  * given commands make an option legal, that option is legal (applies to
164  * CMD_LIST and CMD_ZERO only).
165  * Key:
166  *  +  compulsory
167  *  x  illegal
168  *     optional
169  */
170
171 static char commands_v_options[NUMBER_OF_CMD][NUMBER_OF_OPT] =
172 /* Well, it's better than "Re: Linux vs FreeBSD" */
173 {
174         /*     -n  -s  -d  -p  -j  -v  -x  -i  -o  --line */
175 /*INSERT*/    {'x',' ',' ',' ',' ',' ','x',' ',' ','x'},
176 /*DELETE*/    {'x',' ',' ',' ',' ',' ','x',' ',' ','x'},
177 /*DELETE_NUM*/{'x','x','x','x','x',' ','x','x','x','x'},
178 /*REPLACE*/   {'x',' ',' ',' ',' ',' ','x',' ',' ','x'},
179 /*APPEND*/    {'x',' ',' ',' ',' ',' ','x',' ',' ','x'},
180 /*LIST*/      {' ','x','x','x','x',' ',' ','x','x',' '},
181 /*FLUSH*/     {'x','x','x','x','x',' ','x','x','x','x'},
182 /*ZERO*/      {'x','x','x','x','x',' ','x','x','x','x'},
183 /*NEW_CHAIN*/ {'x','x','x','x','x',' ','x','x','x','x'},
184 /*DEL_CHAIN*/ {'x','x','x','x','x',' ','x','x','x','x'},
185 /*SET_POLICY*/{'x','x','x','x','x',' ','x','x','x','x'},
186 /*CHECK*/     {'x','+','+','+','x',' ','x',' ',' ','x'},
187 /*RENAME*/    {'x','x','x','x','x',' ','x','x','x','x'}
188 };
189
190 static int inverse_for_options[NUMBER_OF_OPT] =
191 {
192 /* -n */ 0,
193 /* -s */ IP6T_INV_SRCIP,
194 /* -d */ IP6T_INV_DSTIP,
195 /* -p */ IP6T_INV_PROTO,
196 /* -j */ 0,
197 /* -v */ 0,
198 /* -x */ 0,
199 /* -i */ IP6T_INV_VIA_IN,
200 /* -o */ IP6T_INV_VIA_OUT,
201 /*--line*/ 0
202 };
203
204 const char *program_version;
205 const char *program_name;
206
207 /* Keeping track of external matches and targets: linked lists.  */
208 struct ip6tables_match *ip6tables_matches = NULL;
209 struct ip6tables_target *ip6tables_targets = NULL;
210
211 /* Extra debugging from libiptc */
212 extern void dump_entries6(const ip6tc_handle_t handle);
213
214 /* A few hardcoded protocols for 'all' and in case the user has no
215    /etc/protocols */
216 struct pprot {
217         char *name;
218         u_int8_t num;
219 };
220
221 /* Primitive headers... */
222 /* defined in netinet/in.h */
223 #if 0
224 #ifndef IPPROTO_ESP
225 #define IPPROTO_ESP 50
226 #endif
227 #ifndef IPPROTO_AH
228 #define IPPROTO_AH 51
229 #endif
230 #endif
231
232 static const struct pprot chain_protos[] = {
233         { "tcp", IPPROTO_TCP },
234         { "udp", IPPROTO_UDP },
235         { "icmpv6", IPPROTO_ICMPV6 },
236         { "esp", IPPROTO_ESP },
237         { "ah", IPPROTO_AH },
238         { "all", 0 },
239 };
240
241 static char *
242 proto_to_name(u_int8_t proto, int nolookup)
243 {
244         unsigned int i;
245
246         if (proto && !nolookup) {
247                 struct protoent *pent = getprotobynumber(proto);
248                 if (pent)
249                         return pent->p_name;
250         }
251
252         for (i = 0; i < sizeof(chain_protos)/sizeof(struct pprot); i++)
253                 if (chain_protos[i].num == proto)
254                         return chain_protos[i].name;
255
256         return NULL;
257 }
258
259 static void
260 in6addrcpy(struct in6_addr *dst, struct in6_addr *src)
261 {
262         memcpy(dst, src, sizeof(struct in6_addr));
263         /* dst->s6_addr = src->s6_addr; */
264 }
265
266 void
267 exit_error(enum exittype status, char *msg, ...)
268 {
269         va_list args;
270
271         va_start(args, msg);
272         fprintf(stderr, "%s v%s: ", program_name, program_version);
273         vfprintf(stderr, msg, args);
274         va_end(args);
275         fprintf(stderr, "\n");
276         if (status == PARAMETER_PROBLEM)
277                 exit_tryhelp(status);
278         if (status == VERSION_PROBLEM)
279                 fprintf(stderr,
280                         "Perhaps iptables or your kernel needs to be upgraded.\n");
281         exit(status);
282 }
283
284 void
285 exit_tryhelp(int status)
286 {
287         if (line != -1)
288                 fprintf(stderr, "Error occurred at line: %d\n", line);
289         fprintf(stderr, "Try `%s -h' or '%s --help' for more information.\n",
290                         program_name, program_name );
291         exit(status);
292 }
293
294 void
295 exit_printhelp(void)
296 {
297         struct ip6tables_match *m = NULL;
298         struct ip6tables_target *t = NULL;
299
300         printf("%s v%s\n\n"
301 "Usage: %s -[AD] chain rule-specification [options]\n"
302 "       %s -[RI] chain rulenum rule-specification [options]\n"
303 "       %s -D chain rulenum [options]\n"
304 "       %s -[LFZ] [chain] [options]\n"
305 "       %s -[NX] chain\n"
306 "       %s -E old-chain-name new-chain-name\n"
307 "       %s -P chain target [options]\n"
308 "       %s -h (print this help information)\n\n",
309                program_name, program_version, program_name, program_name,
310                program_name, program_name, program_name, program_name,
311                program_name, program_name);
312
313         printf(
314 "Commands:\n"
315 "Either long or short options are allowed.\n"
316 "  --append  -A chain           Append to chain\n"
317 "  --delete  -D chain           Delete matching rule from chain\n"
318 "  --delete  -D chain rulenum\n"
319 "                               Delete rule rulenum (1 = first) from chain\n"
320 "  --insert  -I chain [rulenum]\n"
321 "                               Insert in chain as rulenum (default 1=first)\n"
322 "  --replace -R chain rulenum\n"
323 "                               Replace rule rulenum (1 = first) in chain\n"
324 "  --list    -L [chain]         List the rules in a chain or all chains\n"
325 "  --flush   -F [chain]         Delete all rules in  chain or all chains\n"
326 "  --zero    -Z [chain]         Zero counters in chain or all chains\n"
327 "  --new     -N chain           Create a new user-defined chain\n"
328 "  --delete-chain\n"
329 "            -X [chain]         Delete a user-defined chain\n"
330 "  --policy  -P chain target\n"
331 "                               Change policy on chain to target\n"
332 "  --rename-chain\n"
333 "            -E old-chain new-chain\n"
334 "                               Change chain name, (moving any references)\n"
335
336 "Options:\n"
337 "  --proto      -p [!] proto    protocol: by number or name, eg. `tcp'\n"
338 "  --source     -s [!] address[/mask]\n"
339 "                               source specification\n"
340 "  --destination -d [!] address[/mask]\n"
341 "                               destination specification\n"
342 "  --in-interface -i [!] input name[+]\n"
343 "                               network interface name ([+] for wildcard)\n"
344 "  --jump       -j target\n"
345 "                               target for rule (may load target extension)\n"
346 "  --match      -m match\n"
347 "                               extended match (may load extension)\n"
348 "  --numeric    -n              numeric output of addresses and ports\n"
349 "  --out-interface -o [!] output name[+]\n"
350 "                               network interface name ([+] for wildcard)\n"
351 "  --table      -t table        table to manipulate (default: `filter')\n"
352 "  --verbose    -v              verbose mode\n"
353 "  --line-numbers               print line numbers when listing\n"
354 "  --exact      -x              expand numbers (display exact values)\n"
355 /*"[!] --fragment       -f              match second or further fragments only\n"*/
356 "  --modprobe=<command>         try to insert modules using this command\n"
357 "  --set-counters PKTS BYTES    set the counter during insert/append\n"
358 "[!] --version  -V              print package version.\n");
359
360         /* Print out any special helps. A user might like to be able to add a --help 
361            to the commandline, and see expected results. So we call help for all 
362            matches & targets */
363         for (t=ip6tables_targets;t;t=t->next) {
364                 printf("\n");
365                 t->help();
366         }
367         for (m=ip6tables_matches;m;m=m->next) {
368                 printf("\n");
369                 m->help();
370         }
371         exit(0);
372 }
373
374 static void
375 generic_opt_check(int command, int options)
376 {
377         int i, j, legal = 0;
378
379         /* Check that commands are valid with options.  Complicated by the
380          * fact that if an option is legal with *any* command given, it is
381          * legal overall (ie. -z and -l).
382          */
383         for (i = 0; i < NUMBER_OF_OPT; i++) {
384                 legal = 0; /* -1 => illegal, 1 => legal, 0 => undecided. */
385
386                 for (j = 0; j < NUMBER_OF_CMD; j++) {
387                         if (!(command & (1<<j)))
388                                 continue;
389
390                         if (!(options & (1<<i))) {
391                                 if (commands_v_options[j][i] == '+')
392                                         exit_error(PARAMETER_PROBLEM,
393                                                    "You need to supply the `-%c' "
394                                                    "option for this command\n",
395                                                    optflags[i]);
396                         } else {
397                                 if (commands_v_options[j][i] != 'x')
398                                         legal = 1;
399                                 else if (legal == 0)
400                                         legal = -1;
401                         }
402                 }
403                 if (legal == -1)
404                         exit_error(PARAMETER_PROBLEM,
405                                    "Illegal option `-%c' with this command\n",
406                                    optflags[i]);
407         }
408 }
409
410 static char
411 opt2char(int option)
412 {
413         const char *ptr;
414         for (ptr = optflags; option > 1; option >>= 1, ptr++);
415
416         return *ptr;
417 }
418
419 static char
420 cmd2char(int option)
421 {
422         const char *ptr;
423         for (ptr = cmdflags; option > 1; option >>= 1, ptr++);
424
425         return *ptr;
426 }
427
428 static void
429 add_command(int *cmd, const int newcmd, const int othercmds, int invert)
430 {
431         if (invert)
432                 exit_error(PARAMETER_PROBLEM, "unexpected ! flag");
433         if (*cmd & (~othercmds))
434                 exit_error(PARAMETER_PROBLEM, "Can't use -%c with -%c\n",
435                            cmd2char(newcmd), cmd2char(*cmd & (~othercmds)));
436         *cmd |= newcmd;
437 }
438
439 int
440 check_inverse(const char option[], int *invert, int *optind, int argc)
441 {
442         if (option && strcmp(option, "!") == 0) {
443                 if (*invert)
444                         exit_error(PARAMETER_PROBLEM,
445                                    "Multiple `!' flags not allowed");
446                 *invert = TRUE;
447                 if (optind) {
448                         *optind = *optind+1;
449                         if (argc && *optind > argc)
450                                 exit_error(PARAMETER_PROBLEM,
451                                            "no argument following `!'");
452                 }
453
454                 return TRUE;
455         }
456         return FALSE;
457 }
458
459 static void *
460 fw_calloc(size_t count, size_t size)
461 {
462         void *p;
463
464         if ((p = calloc(count, size)) == NULL) {
465                 perror("ip6tables: calloc failed");
466                 exit(1);
467         }
468         return p;
469 }
470
471 static void *
472 fw_malloc(size_t size)
473 {
474         void *p;
475
476         if ((p = malloc(size)) == NULL) {
477                 perror("ip6tables: malloc failed");
478                 exit(1);
479         }
480         return p;
481 }
482
483 static char *
484 addr_to_numeric(const struct in6_addr *addrp)
485 {
486         /* 0000:0000:0000:0000:0000:000.000.000.000
487          * 0000:0000:0000:0000:0000:0000:0000:0000 */
488         static char buf[50+1];
489         return (char *)inet_ntop(AF_INET6, addrp, buf, sizeof(buf));
490 }
491
492 static struct in6_addr *
493 numeric_to_addr(const char *num)
494 {
495         static struct in6_addr ap;
496         int err;
497         if ((err=inet_pton(AF_INET6, num, &ap)) == 1)
498                 return &ap;
499 #ifdef DEBUG
500         fprintf(stderr, "\nnumeric2addr: %d\n", err);
501 #endif
502         return (struct in6_addr *)NULL;
503 }
504
505
506 static struct in6_addr *
507 host_to_addr(const char *name, unsigned int *naddr)
508 {
509         struct addrinfo hints;
510         struct addrinfo *res;
511         static struct in6_addr *addr;
512         int err;
513
514         memset(&hints, 0, sizeof(hints));
515         hints.ai_flags=AI_CANONNAME;
516         hints.ai_family=AF_INET6;
517         hints.ai_socktype=SOCK_RAW;
518         hints.ai_protocol=41;
519         hints.ai_next=NULL;
520
521         *naddr = 0;
522         if ( (err=getaddrinfo(name, NULL, &hints, &res)) != 0 ){
523 #ifdef DEBUG
524                 fprintf(stderr,"Name2IP: %s\n",gai_strerror(err)); 
525 #endif
526                 return (struct in6_addr *) NULL;
527         } else {
528                 if (res->ai_family != AF_INET6 ||
529                     res->ai_addrlen != sizeof(struct sockaddr_in6))
530                         return (struct in6_addr *) NULL;
531
532 #ifdef DEBUG
533                 fprintf(stderr, "resolved: len=%d  %s ", res->ai_addrlen, 
534                     addr_to_numeric(&(((struct sockaddr_in6 *)res->ai_addr)->sin6_addr)));
535 #endif
536                 /* Get the first element of the address-chain */
537                 addr = fw_calloc(1, sizeof(struct in6_addr));
538                 in6addrcpy(addr, (struct in6_addr *)
539                         &((struct sockaddr_in6 *)res->ai_addr)->sin6_addr);
540                 freeaddrinfo(res);
541                 *naddr = 1;
542                 return addr;
543         }
544
545         return (struct in6_addr *) NULL;
546 }
547
548 static char *
549 addr_to_host(const struct in6_addr *addr)
550 {
551         struct sockaddr_in6 saddr;
552         int err;
553         static char hostname[NI_MAXHOST];
554
555         memset(&saddr, 0, sizeof(struct sockaddr_in6));
556         in6addrcpy(&(saddr.sin6_addr),(struct in6_addr *)addr);
557         saddr.sin6_family = AF_INET6;
558
559         if ( (err=getnameinfo((struct sockaddr *)&saddr,
560                                sizeof(struct sockaddr_in6),
561                                hostname, sizeof(hostname)-1,
562                                NULL, 0, 0)) != 0 ){
563 #ifdef DEBUG
564                 fprintf(stderr,"IP2Name: %s\n",gai_strerror(err)); 
565 #endif
566                 return (char *) NULL;
567         } else {
568 #ifdef DEBUG
569                 fprintf (stderr, "\naddr2host: %s\n", hostname);
570 #endif
571
572                 return hostname;
573         }
574
575         return (char *) NULL;
576 }
577
578 static char *
579 mask_to_numeric(const struct in6_addr *addrp)
580 {
581         static char buf[50+2];
582         int l = ipv6_prefix_length(addrp);
583         if (l == -1) {
584                 strcpy(buf, "/");
585                 strcat(buf, addr_to_numeric(addrp));
586                 return buf;
587         }
588         sprintf(buf, "/%d", l);
589         return buf;
590 }
591
592 static struct in6_addr *
593 network_to_addr(const char *name)
594 {
595         /*      abort();*/
596         /* TODO: not implemented yet, but the exception breaks the
597          *       name resolvation */
598         return (struct in6_addr *)NULL;
599 }
600
601 static char *
602 addr_to_anyname(const struct in6_addr *addr)
603 {
604         char *name;
605
606         if ((name = addr_to_host(addr)) != NULL)
607                 return name;
608
609         return addr_to_numeric(addr);
610 }
611
612 /*
613  *      All functions starting with "parse" should succeed, otherwise
614  *      the program fails.
615  *      Most routines return pointers to static data that may change
616  *      between calls to the same or other routines with a few exceptions:
617  *      "host_to_addr", "parse_hostnetwork", and "parse_hostnetworkmask"
618  *      return global static data.
619 */
620
621 static struct in6_addr *
622 parse_hostnetwork(const char *name, unsigned int *naddrs)
623 {
624         struct in6_addr *addrp, *addrptmp;
625
626         if ((addrptmp = numeric_to_addr(name)) != NULL ||
627             (addrptmp = network_to_addr(name)) != NULL) {
628                 addrp = fw_malloc(sizeof(struct in6_addr));
629                 in6addrcpy(addrp, addrptmp);
630                 *naddrs = 1;
631                 return addrp;
632         }
633         if ((addrp = host_to_addr(name, naddrs)) != NULL)
634                 return addrp;
635
636         exit_error(PARAMETER_PROBLEM, "host/network `%s' not found", name);
637 }
638
639 static struct in6_addr *
640 parse_mask(char *mask)
641 {
642         static struct in6_addr maskaddr;
643         struct in6_addr *addrp;
644         unsigned int bits;
645
646         if (mask == NULL) {
647                 /* no mask at all defaults to 128 bits */
648                 memset(&maskaddr, 0xff, sizeof maskaddr);
649                 return &maskaddr;
650         }
651         if ((addrp = numeric_to_addr(mask)) != NULL)
652                 return addrp;
653         if (string_to_number(mask, 0, 128, &bits) == -1)
654                 exit_error(PARAMETER_PROBLEM,
655                            "invalid mask `%s' specified", mask);
656         if (bits != 0) {
657                 char *p = (char *)&maskaddr;
658                 memset(p, 0xff, bits / 8);
659                 memset(p + (bits / 8) + 1, 0, (128 - bits) / 8);
660                 p[bits / 8] = 0xff << (8 - (bits & 7));
661                 return &maskaddr;
662         }
663
664         memset(&maskaddr, 0, sizeof maskaddr);
665         return &maskaddr;
666 }
667
668 void
669 parse_hostnetworkmask(const char *name, struct in6_addr **addrpp,
670                       struct in6_addr *maskp, unsigned int *naddrs)
671 {
672         struct in6_addr *addrp;
673         char buf[256];
674         char *p;
675         int i, j, n;
676
677         strncpy(buf, name, sizeof(buf) - 1);
678         if ((p = strrchr(buf, '/')) != NULL) {
679                 *p = '\0';
680                 addrp = parse_mask(p + 1);
681         } else
682                 addrp = parse_mask(NULL);
683         in6addrcpy(maskp, addrp);
684
685         /* if a null mask is given, the name is ignored, like in "any/0" */
686         if (!memcmp(maskp, &in6addr_any, sizeof(in6addr_any)))
687                 strcpy(buf, "::");
688
689         addrp = *addrpp = parse_hostnetwork(buf, naddrs);
690         n = *naddrs;
691         for (i = 0, j = 0; i < n; i++) {
692                 int k;
693                 for (k = 0; k < 4; k++)
694                         addrp[j].in6_u.u6_addr32[k] &= maskp->in6_u.u6_addr32[k];
695                 j++;
696                 for (k = 0; k < j - 1; k++) {
697                         if (IN6_ARE_ADDR_EQUAL(&addrp[k], &addrp[j - 1])) {
698                                 (*naddrs)--;
699                                 j--;
700                                 break;
701                         }
702                 }
703         }
704 }
705
706 struct ip6tables_match *
707 find_match(const char *name, enum ip6t_tryload tryload)
708 {
709         struct ip6tables_match *ptr;
710         int icmphack = 0;
711   
712         /* This is ugly as hell. Nonetheless, there is no way of changing
713          * this without hurting backwards compatibility */
714         if ( (strcmp(name,"icmpv6") == 0) ||
715              (strcmp(name,"ipv6-icmp") == 0) ||
716              (strcmp(name,"icmp6") == 0) ) icmphack = 1;
717  
718         if (!icmphack) {
719                 for (ptr = ip6tables_matches; ptr; ptr = ptr->next) {
720                         if (strcmp(name, ptr->name) == 0)
721                                 break;
722                 }
723         } else {
724                 for (ptr = ip6tables_matches; ptr; ptr = ptr->next) {
725                         if (strcmp("icmp6", ptr->name) == 0)
726                                 break;
727                 }
728         }
729
730 #ifndef NO_SHARED_LIBS
731         if (!ptr && tryload != DONT_LOAD) {
732                 char path[sizeof(IP6T_LIB_DIR) + sizeof("/libip6t_.so")
733                          + strlen(name)];
734                 if (!icmphack)
735                         sprintf(path, IP6T_LIB_DIR "/libip6t_%s.so", name);
736                 else
737                         sprintf(path, IP6T_LIB_DIR "/libip6t_%s.so", "icmpv6");
738                 if (dlopen(path, RTLD_NOW)) {
739                         /* Found library.  If it didn't register itself,
740                            maybe they specified target as match. */
741                         ptr = find_match(name, DONT_LOAD);
742
743                         if (!ptr)
744                                 exit_error(PARAMETER_PROBLEM,
745                                            "Couldn't load match `%s'\n",
746                                            name);
747                 } else if (tryload == LOAD_MUST_SUCCEED)
748                         exit_error(PARAMETER_PROBLEM,
749                                    "Couldn't load match `%s':%s\n",
750                                    name, dlerror());
751         }
752 #else
753         if (ptr && !ptr->loaded) {
754                 if (tryload != DONT_LOAD)
755                         ptr->loaded = 1;
756                 else
757                         ptr = NULL;
758         }
759         if(!ptr && (tryload == LOAD_MUST_SUCCEED)) {
760                 exit_error(PARAMETER_PROBLEM,
761                            "Couldn't find match `%s'\n", name);
762         }
763 #endif
764
765         if (ptr)
766                 ptr->used = 1;
767
768         return ptr;
769 }
770
771 /* Christophe Burki wants `-p 6' to imply `-m tcp'.  */
772 static struct ip6tables_match *
773 find_proto(const char *pname, enum ip6t_tryload tryload, int nolookup)
774 {
775         unsigned int proto;
776
777         if (string_to_number(pname, 0, 255, &proto) != -1) {
778                 char *protoname = proto_to_name(proto, nolookup);
779
780                 if (protoname)
781                         return find_match(protoname, tryload);
782         } else
783                 return find_match(pname, tryload);
784
785         return NULL;
786 }
787
788 u_int16_t
789 parse_protocol(const char *s)
790 {
791         unsigned int proto;
792
793         if (string_to_number(s, 0, 255, &proto) == -1) {
794                 struct protoent *pent;
795
796                 if ((pent = getprotobyname(s)))
797                         proto = pent->p_proto;
798                 else {
799                         unsigned int i;
800                         for (i = 0;
801                              i < sizeof(chain_protos)/sizeof(struct pprot);
802                              i++) {
803                                 if (strcmp(s, chain_protos[i].name) == 0) {
804                                         proto = chain_protos[i].num;
805                                         break;
806                                 }
807                         }
808                         if (i == sizeof(chain_protos)/sizeof(struct pprot))
809                                 exit_error(PARAMETER_PROBLEM,
810                                            "unknown protocol `%s' specified",
811                                            s);
812                 }
813         }
814
815         return (u_int16_t)proto;
816 }
817
818 static void
819 parse_interface(const char *arg, char *vianame, unsigned char *mask)
820 {
821         int vialen = strlen(arg);
822         unsigned int i;
823
824         memset(mask, 0, IFNAMSIZ);
825         memset(vianame, 0, IFNAMSIZ);
826
827         if (vialen + 1 > IFNAMSIZ)
828                 exit_error(PARAMETER_PROBLEM,
829                            "interface name `%s' must be shorter than IFNAMSIZ"
830                            " (%i)", arg, IFNAMSIZ-1);
831
832         strcpy(vianame, arg);
833         if (vialen == 0)
834                 memset(mask, 0, IFNAMSIZ);
835         else if (vianame[vialen - 1] == '+') {
836                 memset(mask, 0xFF, vialen - 1);
837                 memset(mask + vialen - 1, 0, IFNAMSIZ - vialen + 1);
838                 /* Don't remove `+' here! -HW */
839         } else {
840                 /* Include nul-terminator in match */
841                 memset(mask, 0xFF, vialen + 1);
842                 memset(mask + vialen + 1, 0, IFNAMSIZ - vialen - 1);
843                 for (i = 0; vianame[i]; i++) {
844                         if (!isalnum(vianame[i]) 
845                             && vianame[i] != '_' 
846                             && vianame[i] != '.') {
847                                 printf("Warning: wierd character in interface"
848                                        " `%s' (No aliases, :, ! or *).\n",
849                                        vianame);
850                                 break;
851                         }
852                 }
853         }
854 }
855
856 /* Can't be zero. */
857 static int
858 parse_rulenumber(const char *rule)
859 {
860         unsigned int rulenum;
861
862         if (string_to_number(rule, 1, INT_MAX, &rulenum) == -1)
863                 exit_error(PARAMETER_PROBLEM,
864                            "Invalid rule number `%s'", rule);
865
866         return rulenum;
867 }
868
869 static const char *
870 parse_target(const char *targetname)
871 {
872         const char *ptr;
873
874         if (strlen(targetname) < 1)
875                 exit_error(PARAMETER_PROBLEM,
876                            "Invalid target name (too short)");
877
878         if (strlen(targetname)+1 > sizeof(ip6t_chainlabel))
879                 exit_error(PARAMETER_PROBLEM,
880                            "Invalid target name `%s' (%i chars max)",
881                            targetname, sizeof(ip6t_chainlabel)-1);
882
883         for (ptr = targetname; *ptr; ptr++)
884                 if (isspace(*ptr))
885                         exit_error(PARAMETER_PROBLEM,
886                                    "Invalid target name `%s'", targetname);
887         return targetname;
888 }
889
890 int
891 string_to_number(const char *s, unsigned int min, unsigned int max,
892                  unsigned int *ret)
893 {
894         long number;
895         char *end;
896
897         /* Handle hex, octal, etc. */
898         errno = 0;
899         number = strtol(s, &end, 0);
900         if (*end == '\0' && end != s) {
901                 /* we parsed a number, let's see if we want this */
902                 if (errno != ERANGE && min <= number && number <= max) {
903                         *ret = number;
904                         return 0;
905                 }
906         }
907         return -1;
908 }
909
910 static void
911 set_option(unsigned int *options, unsigned int option, u_int8_t *invflg,
912            int invert)
913 {
914         if (*options & option)
915                 exit_error(PARAMETER_PROBLEM, "multiple -%c flags not allowed",
916                            opt2char(option));
917         *options |= option;
918
919         if (invert) {
920                 unsigned int i;
921                 for (i = 0; 1 << i != option; i++);
922
923                 if (!inverse_for_options[i])
924                         exit_error(PARAMETER_PROBLEM,
925                                    "cannot have ! before -%c",
926                                    opt2char(option));
927                 *invflg |= inverse_for_options[i];
928         }
929 }
930
931 struct ip6tables_target *
932 find_target(const char *name, enum ip6t_tryload tryload)
933 {
934         struct ip6tables_target *ptr;
935
936         /* Standard target? */
937         if (strcmp(name, "") == 0
938             || strcmp(name, IP6TC_LABEL_ACCEPT) == 0
939             || strcmp(name, IP6TC_LABEL_DROP) == 0
940             || strcmp(name, IP6TC_LABEL_QUEUE) == 0
941             || strcmp(name, IP6TC_LABEL_RETURN) == 0)
942                 name = "standard";
943
944         for (ptr = ip6tables_targets; ptr; ptr = ptr->next) {
945                 if (strcmp(name, ptr->name) == 0)
946                         break;
947         }
948
949 #ifndef NO_SHARED_LIBS
950         if (!ptr && tryload != DONT_LOAD) {
951                 char path[sizeof(IP6T_LIB_DIR) + sizeof("/libip6t_.so")
952                          + strlen(name)];
953                 sprintf(path, IP6T_LIB_DIR "/libip6t_%s.so", name);
954                 if (dlopen(path, RTLD_NOW)) {
955                         /* Found library.  If it didn't register itself,
956                            maybe they specified match as a target. */
957                         ptr = find_target(name, DONT_LOAD);
958                         if (!ptr)
959                                 exit_error(PARAMETER_PROBLEM,
960                                            "Couldn't load target `%s'\n",
961                                            name);
962                 } else if (tryload == LOAD_MUST_SUCCEED)
963                         exit_error(PARAMETER_PROBLEM,
964                                    "Couldn't load target `%s':%s\n",
965                                    name, dlerror());
966         }
967 #else
968         if (ptr && !ptr->loaded) {
969                 if (tryload != DONT_LOAD)
970                         ptr->loaded = 1;
971                 else
972                         ptr = NULL;
973         }
974         if(!ptr && (tryload == LOAD_MUST_SUCCEED)) {
975                 exit_error(PARAMETER_PROBLEM,
976                            "Couldn't find target `%s'\n", name);
977         }
978 #endif
979
980         if (ptr)
981                 ptr->used = 1;
982
983         return ptr;
984 }
985
986 static struct option *
987 merge_options(struct option *oldopts, const struct option *newopts,
988               unsigned int *option_offset)
989 {
990         unsigned int num_old, num_new, i;
991         struct option *merge;
992
993         for (num_old = 0; oldopts[num_old].name; num_old++);
994         for (num_new = 0; newopts[num_new].name; num_new++);
995
996         global_option_offset += OPTION_OFFSET;
997         *option_offset = global_option_offset;
998
999         merge = malloc(sizeof(struct option) * (num_new + num_old + 1));
1000         memcpy(merge, oldopts, num_old * sizeof(struct option));
1001         for (i = 0; i < num_new; i++) {
1002                 merge[num_old + i] = newopts[i];
1003                 merge[num_old + i].val += *option_offset;
1004         }
1005         memset(merge + num_old + num_new, 0, sizeof(struct option));
1006
1007         return merge;
1008 }
1009
1010 void
1011 register_match6(struct ip6tables_match *me)
1012 {
1013         struct ip6tables_match **i;
1014
1015         if (strcmp(me->version, program_version) != 0) {
1016                 fprintf(stderr, "%s: match `%s' v%s (I'm v%s).\n",
1017                         program_name, me->name, me->version, program_version);
1018                 exit(1);
1019         }
1020
1021         if (find_match(me->name, DONT_LOAD)) {
1022                 fprintf(stderr, "%s: match `%s' already registered.\n",
1023                         program_name, me->name);
1024                 exit(1);
1025         }
1026
1027         if (me->size != IP6T_ALIGN(me->size)) {
1028                 fprintf(stderr, "%s: match `%s' has invalid size %u.\n",
1029                         program_name, me->name, me->size);
1030                 exit(1);
1031         }
1032
1033         /* Append to list. */
1034         for (i = &ip6tables_matches; *i; i = &(*i)->next);
1035         me->next = NULL;
1036         *i = me;
1037
1038         me->m = NULL;
1039         me->mflags = 0;
1040 }
1041
1042 void
1043 register_target6(struct ip6tables_target *me)
1044 {
1045         if (strcmp(me->version, program_version) != 0) {
1046                 fprintf(stderr, "%s: target `%s' v%s (I'm v%s).\n",
1047                         program_name, me->name, me->version, program_version);
1048                 exit(1);
1049         }
1050
1051         if (find_target(me->name, DONT_LOAD)) {
1052                 fprintf(stderr, "%s: target `%s' already registered.\n",
1053                         program_name, me->name);
1054                 exit(1);
1055         }
1056
1057         if (me->size != IP6T_ALIGN(me->size)) {
1058                 fprintf(stderr, "%s: target `%s' has invalid size %u.\n",
1059                         program_name, me->name, me->size);
1060                 exit(1);
1061         }
1062
1063         /* Prepend to list. */
1064         me->next = ip6tables_targets;
1065         ip6tables_targets = me;
1066         me->t = NULL;
1067         me->tflags = 0;
1068 }
1069
1070 static void
1071 print_num(u_int64_t number, unsigned int format)
1072 {
1073         if (format & FMT_KILOMEGAGIGA) {
1074                 if (number > 99999) {
1075                         number = (number + 500) / 1000;
1076                         if (number > 9999) {
1077                                 number = (number + 500) / 1000;
1078                                 if (number > 9999) {
1079                                         number = (number + 500) / 1000;
1080                                         if (number > 9999) {
1081                                                 number = (number + 500) / 1000;
1082                                                 printf(FMT("%4lluT ","%lluT "), number);
1083                                         }
1084                                         else printf(FMT("%4lluG ","%lluG "), number);
1085                                 }
1086                                 else printf(FMT("%4lluM ","%lluM "), number);
1087                         } else
1088                                 printf(FMT("%4lluK ","%lluK "), number);
1089                 } else
1090                         printf(FMT("%5llu ","%llu "), number);
1091         } else
1092                 printf(FMT("%8llu ","%llu "), number);
1093 }
1094
1095
1096 static void
1097 print_header(unsigned int format, const char *chain, ip6tc_handle_t *handle)
1098 {
1099         struct ip6t_counters counters;
1100         const char *pol = ip6tc_get_policy(chain, &counters, handle);
1101         printf("Chain %s", chain);
1102         if (pol) {
1103                 printf(" (policy %s", pol);
1104                 if (!(format & FMT_NOCOUNTS)) {
1105                         fputc(' ', stdout);
1106                         print_num(counters.pcnt, (format|FMT_NOTABLE));
1107                         fputs("packets, ", stdout);
1108                         print_num(counters.bcnt, (format|FMT_NOTABLE));
1109                         fputs("bytes", stdout);
1110                 }
1111                 printf(")\n");
1112         } else {
1113                 unsigned int refs;
1114                 if (!ip6tc_get_references(&refs, chain, handle))
1115                         printf(" (ERROR obtaining refs)\n");
1116                 else
1117                         printf(" (%u references)\n", refs);
1118         }
1119
1120         if (format & FMT_LINENUMBERS)
1121                 printf(FMT("%-4s ", "%s "), "num");
1122         if (!(format & FMT_NOCOUNTS)) {
1123                 if (format & FMT_KILOMEGAGIGA) {
1124                         printf(FMT("%5s ","%s "), "pkts");
1125                         printf(FMT("%5s ","%s "), "bytes");
1126                 } else {
1127                         printf(FMT("%8s ","%s "), "pkts");
1128                         printf(FMT("%10s ","%s "), "bytes");
1129                 }
1130         }
1131         if (!(format & FMT_NOTARGET))
1132                 printf(FMT("%-9s ","%s "), "target");
1133         fputs(" prot ", stdout);
1134         if (format & FMT_OPTIONS)
1135                 fputs("opt", stdout);
1136         if (format & FMT_VIA) {
1137                 printf(FMT(" %-6s ","%s "), "in");
1138                 printf(FMT("%-6s ","%s "), "out");
1139         }
1140         printf(FMT(" %-19s ","%s "), "source");
1141         printf(FMT(" %-19s "," %s "), "destination");
1142         printf("\n");
1143 }
1144
1145
1146 static int
1147 print_match(const struct ip6t_entry_match *m,
1148             const struct ip6t_ip6 *ip,
1149             int numeric)
1150 {
1151         struct ip6tables_match *match = find_match(m->u.user.name, TRY_LOAD);
1152
1153         if (match) {
1154                 if (match->print)
1155                         match->print(ip, m, numeric);
1156                 else
1157                         printf("%s ", match->name);
1158         } else {
1159                 if (m->u.user.name[0])
1160                         printf("UNKNOWN match `%s' ", m->u.user.name);
1161         }
1162         /* Don't stop iterating. */
1163         return 0;
1164 }
1165
1166 /* e is called `fw' here for hysterical raisins */
1167 static void
1168 print_firewall(const struct ip6t_entry *fw,
1169                const char *targname,
1170                unsigned int num,
1171                unsigned int format,
1172                const ip6tc_handle_t handle)
1173 {
1174         struct ip6tables_target *target = NULL;
1175         const struct ip6t_entry_target *t;
1176         u_int8_t flags;
1177         char buf[BUFSIZ];
1178
1179         if (!ip6tc_is_chain(targname, handle))
1180                 target = find_target(targname, TRY_LOAD);
1181         else
1182                 target = find_target(IP6T_STANDARD_TARGET, LOAD_MUST_SUCCEED);
1183
1184         t = ip6t_get_target((struct ip6t_entry *)fw);
1185         flags = fw->ipv6.flags;
1186
1187         if (format & FMT_LINENUMBERS)
1188                 printf(FMT("%-4u ", "%u "), num+1);
1189
1190         if (!(format & FMT_NOCOUNTS)) {
1191                 print_num(fw->counters.pcnt, format);
1192                 print_num(fw->counters.bcnt, format);
1193         }
1194
1195         if (!(format & FMT_NOTARGET))
1196                 printf(FMT("%-9s ", "%s "), targname);
1197
1198         fputc(fw->ipv6.invflags & IP6T_INV_PROTO ? '!' : ' ', stdout);
1199         {
1200                 char *pname = proto_to_name(fw->ipv6.proto, format&FMT_NUMERIC);
1201                 if (pname)
1202                         printf(FMT("%-5s", "%s "), pname);
1203                 else
1204                         printf(FMT("%-5hu", "%hu "), fw->ipv6.proto);
1205         }
1206
1207         if (format & FMT_OPTIONS) {
1208                 if (format & FMT_NOTABLE)
1209                         fputs("opt ", stdout);
1210                 fputc(' ', stdout); /* Invert flag of FRAG */
1211                 fputc(' ', stdout); /* -f */
1212                 fputc(' ', stdout);
1213         }
1214
1215         if (format & FMT_VIA) {
1216                 char iface[IFNAMSIZ+2];
1217
1218                 if (fw->ipv6.invflags & IP6T_INV_VIA_IN) {
1219                         iface[0] = '!';
1220                         iface[1] = '\0';
1221                 }
1222                 else iface[0] = '\0';
1223
1224                 if (fw->ipv6.iniface[0] != '\0') {
1225                         strcat(iface, fw->ipv6.iniface);
1226                 }
1227                 else if (format & FMT_NUMERIC) strcat(iface, "*");
1228                 else strcat(iface, "any");
1229                 printf(FMT(" %-6s ","in %s "), iface);
1230
1231                 if (fw->ipv6.invflags & IP6T_INV_VIA_OUT) {
1232                         iface[0] = '!';
1233                         iface[1] = '\0';
1234                 }
1235                 else iface[0] = '\0';
1236
1237                 if (fw->ipv6.outiface[0] != '\0') {
1238                         strcat(iface, fw->ipv6.outiface);
1239                 }
1240                 else if (format & FMT_NUMERIC) strcat(iface, "*");
1241                 else strcat(iface, "any");
1242                 printf(FMT("%-6s ","out %s "), iface);
1243         }
1244
1245         fputc(fw->ipv6.invflags & IP6T_INV_SRCIP ? '!' : ' ', stdout);
1246         if (!memcmp(&fw->ipv6.smsk, &in6addr_any, sizeof in6addr_any) 
1247             && !(format & FMT_NUMERIC))
1248                 printf(FMT("%-19s ","%s "), "anywhere");
1249         else {
1250                 if (format & FMT_NUMERIC)
1251                         sprintf(buf, "%s", addr_to_numeric(&(fw->ipv6.src)));
1252                 else
1253                         sprintf(buf, "%s", addr_to_anyname(&(fw->ipv6.src)));
1254                 strcat(buf, mask_to_numeric(&(fw->ipv6.smsk)));
1255                 printf(FMT("%-19s ","%s "), buf);
1256         }
1257
1258         fputc(fw->ipv6.invflags & IP6T_INV_DSTIP ? '!' : ' ', stdout);
1259         if (!memcmp(&fw->ipv6.dmsk, &in6addr_any, sizeof in6addr_any)
1260             && !(format & FMT_NUMERIC))
1261                 printf(FMT("%-19s","-> %s"), "anywhere");
1262         else {
1263                 if (format & FMT_NUMERIC)
1264                         sprintf(buf, "%s", addr_to_numeric(&(fw->ipv6.dst)));
1265                 else
1266                         sprintf(buf, "%s", addr_to_anyname(&(fw->ipv6.dst)));
1267                 strcat(buf, mask_to_numeric(&(fw->ipv6.dmsk)));
1268                 printf(FMT("%-19s","-> %s"), buf);
1269         }
1270
1271         if (format & FMT_NOTABLE)
1272                 fputs("  ", stdout);
1273
1274         IP6T_MATCH_ITERATE(fw, print_match, &fw->ipv6, format & FMT_NUMERIC);
1275
1276         if (target) {
1277                 if (target->print)
1278                         /* Print the target information. */
1279                         target->print(&fw->ipv6, t, format & FMT_NUMERIC);
1280         } else if (t->u.target_size != sizeof(*t))
1281                 printf("[%u bytes of unknown target data] ",
1282                        t->u.target_size - sizeof(*t));
1283
1284         if (!(format & FMT_NONEWLINE))
1285                 fputc('\n', stdout);
1286 }
1287
1288 static void
1289 print_firewall_line(const struct ip6t_entry *fw,
1290                     const ip6tc_handle_t h)
1291 {
1292         struct ip6t_entry_target *t;
1293
1294         t = ip6t_get_target((struct ip6t_entry *)fw);
1295         print_firewall(fw, t->u.user.name, 0, FMT_PRINT_RULE, h);
1296 }
1297
1298 static int
1299 append_entry(const ip6t_chainlabel chain,
1300              struct ip6t_entry *fw,
1301              unsigned int nsaddrs,
1302              const struct in6_addr saddrs[],
1303              unsigned int ndaddrs,
1304              const struct in6_addr daddrs[],
1305              int verbose,
1306              ip6tc_handle_t *handle)
1307 {
1308         unsigned int i, j;
1309         int ret = 1;
1310
1311         for (i = 0; i < nsaddrs; i++) {
1312                 fw->ipv6.src = saddrs[i];
1313                 for (j = 0; j < ndaddrs; j++) {
1314                         fw->ipv6.dst = daddrs[j];
1315                         if (verbose)
1316                                 print_firewall_line(fw, *handle);
1317                         ret &= ip6tc_append_entry(chain, fw, handle);
1318                 }
1319         }
1320
1321         return ret;
1322 }
1323
1324 static int
1325 replace_entry(const ip6t_chainlabel chain,
1326               struct ip6t_entry *fw,
1327               unsigned int rulenum,
1328               const struct in6_addr *saddr,
1329               const struct in6_addr *daddr,
1330               int verbose,
1331               ip6tc_handle_t *handle)
1332 {
1333         fw->ipv6.src = *saddr;
1334         fw->ipv6.dst = *daddr;
1335
1336         if (verbose)
1337                 print_firewall_line(fw, *handle);
1338         return ip6tc_replace_entry(chain, fw, rulenum, handle);
1339 }
1340
1341 static int
1342 insert_entry(const ip6t_chainlabel chain,
1343              struct ip6t_entry *fw,
1344              unsigned int rulenum,
1345              unsigned int nsaddrs,
1346              const struct in6_addr saddrs[],
1347              unsigned int ndaddrs,
1348              const struct in6_addr daddrs[],
1349              int verbose,
1350              ip6tc_handle_t *handle)
1351 {
1352         unsigned int i, j;
1353         int ret = 1;
1354
1355         for (i = 0; i < nsaddrs; i++) {
1356                 fw->ipv6.src = saddrs[i];
1357                 for (j = 0; j < ndaddrs; j++) {
1358                         fw->ipv6.dst = daddrs[j];
1359                         if (verbose)
1360                                 print_firewall_line(fw, *handle);
1361                         ret &= ip6tc_insert_entry(chain, fw, rulenum, handle);
1362                 }
1363         }
1364
1365         return ret;
1366 }
1367
1368 static unsigned char *
1369 make_delete_mask(struct ip6t_entry *fw)
1370 {
1371         /* Establish mask for comparison */
1372         unsigned int size;
1373         struct ip6tables_match *m;
1374         unsigned char *mask, *mptr;
1375
1376         size = sizeof(struct ip6t_entry);
1377         for (m = ip6tables_matches; m; m = m->next) {
1378                 if (!m->used)
1379                         continue;
1380
1381                 size += IP6T_ALIGN(sizeof(struct ip6t_entry_match)) + m->size;
1382         }
1383
1384         mask = fw_calloc(1, size
1385                          + IP6T_ALIGN(sizeof(struct ip6t_entry_target))
1386                          + ip6tables_targets->size);
1387
1388         memset(mask, 0xFF, sizeof(struct ip6t_entry));
1389         mptr = mask + sizeof(struct ip6t_entry);
1390
1391         for (m = ip6tables_matches; m; m = m->next) {
1392                 if (!m->used)
1393                         continue;
1394
1395                 memset(mptr, 0xFF,
1396                        IP6T_ALIGN(sizeof(struct ip6t_entry_match))
1397                        + m->userspacesize);
1398                 mptr += IP6T_ALIGN(sizeof(struct ip6t_entry_match)) + m->size;
1399         }
1400
1401         memset(mptr, 0xFF, 
1402                IP6T_ALIGN(sizeof(struct ip6t_entry_target))
1403                + ip6tables_targets->userspacesize);
1404
1405         return mask;
1406 }
1407
1408 static int
1409 delete_entry(const ip6t_chainlabel chain,
1410              struct ip6t_entry *fw,
1411              unsigned int nsaddrs,
1412              const struct in6_addr saddrs[],
1413              unsigned int ndaddrs,
1414              const struct in6_addr daddrs[],
1415              int verbose,
1416              ip6tc_handle_t *handle)
1417 {
1418         unsigned int i, j;
1419         int ret = 1;
1420         unsigned char *mask;
1421
1422         mask = make_delete_mask(fw);
1423         for (i = 0; i < nsaddrs; i++) {
1424                 fw->ipv6.src = saddrs[i];
1425                 for (j = 0; j < ndaddrs; j++) {
1426                         fw->ipv6.dst = daddrs[j];
1427                         if (verbose)
1428                                 print_firewall_line(fw, *handle);
1429                         ret &= ip6tc_delete_entry(chain, fw, mask, handle);
1430                 }
1431         }
1432         return ret;
1433 }
1434
1435 int
1436 for_each_chain(int (*fn)(const ip6t_chainlabel, int, ip6tc_handle_t *),
1437                int verbose, int builtinstoo, ip6tc_handle_t *handle)
1438 {
1439         int ret = 1;
1440         const char *chain;
1441         char *chains;
1442         unsigned int i, chaincount = 0;
1443
1444         chain = ip6tc_first_chain(handle);
1445         while (chain) {
1446                 chaincount++;
1447                 chain = ip6tc_next_chain(handle);
1448         }
1449
1450         chains = fw_malloc(sizeof(ip6t_chainlabel) * chaincount);
1451         i = 0;
1452         chain = ip6tc_first_chain(handle);
1453         while (chain) {
1454                 strcpy(chains + i*sizeof(ip6t_chainlabel), chain);
1455                 i++;
1456                 chain = ip6tc_next_chain(handle);
1457         }
1458
1459         for (i = 0; i < chaincount; i++) {
1460                 if (!builtinstoo
1461                     && ip6tc_builtin(chains + i*sizeof(ip6t_chainlabel),
1462                                     *handle))
1463                         continue;
1464                 ret &= fn(chains + i*sizeof(ip6t_chainlabel), verbose, handle);
1465         }
1466
1467         free(chains);
1468         return ret;
1469 }
1470
1471 int
1472 flush_entries(const ip6t_chainlabel chain, int verbose,
1473               ip6tc_handle_t *handle)
1474 {
1475         if (!chain)
1476                 return for_each_chain(flush_entries, verbose, 1, handle);
1477
1478         if (verbose)
1479                 fprintf(stdout, "Flushing chain `%s'\n", chain);
1480         return ip6tc_flush_entries(chain, handle);
1481 }
1482
1483 static int
1484 zero_entries(const ip6t_chainlabel chain, int verbose,
1485              ip6tc_handle_t *handle)
1486 {
1487         if (!chain)
1488                 return for_each_chain(zero_entries, verbose, 1, handle);
1489
1490         if (verbose)
1491                 fprintf(stdout, "Zeroing chain `%s'\n", chain);
1492         return ip6tc_zero_entries(chain, handle);
1493 }
1494
1495 int
1496 delete_chain(const ip6t_chainlabel chain, int verbose,
1497              ip6tc_handle_t *handle)
1498 {
1499         if (!chain)
1500                 return for_each_chain(delete_chain, verbose, 0, handle);
1501
1502         if (verbose)
1503                 fprintf(stdout, "Deleting chain `%s'\n", chain);
1504         return ip6tc_delete_chain(chain, handle);
1505 }
1506
1507 static int
1508 list_entries(const ip6t_chainlabel chain, int verbose, int numeric,
1509              int expanded, int linenumbers, ip6tc_handle_t *handle)
1510 {
1511         int found = 0;
1512         unsigned int format;
1513         const char *this;
1514
1515         format = FMT_OPTIONS;
1516         if (!verbose)
1517                 format |= FMT_NOCOUNTS;
1518         else
1519                 format |= FMT_VIA;
1520
1521         if (numeric)
1522                 format |= FMT_NUMERIC;
1523
1524         if (!expanded)
1525                 format |= FMT_KILOMEGAGIGA;
1526
1527         if (linenumbers)
1528                 format |= FMT_LINENUMBERS;
1529
1530         for (this = ip6tc_first_chain(handle);
1531              this;
1532              this = ip6tc_next_chain(handle)) {
1533                 const struct ip6t_entry *i;
1534                 unsigned int num;
1535
1536                 if (chain && strcmp(chain, this) != 0)
1537                         continue;
1538
1539                 if (found) printf("\n");
1540
1541                 print_header(format, this, handle);
1542                 i = ip6tc_first_rule(this, handle);
1543
1544                 num = 0;
1545                 while (i) {
1546                         print_firewall(i,
1547                                        ip6tc_get_target(i, handle),
1548                                        num++,
1549                                        format,
1550                                        *handle);
1551                         i = ip6tc_next_rule(i, handle);
1552                 }
1553                 found = 1;
1554         }
1555
1556         errno = ENOENT;
1557         return found;
1558 }
1559
1560 static char *get_modprobe(void)
1561 {
1562         int procfile;
1563         char *ret;
1564
1565         procfile = open(PROC_SYS_MODPROBE, O_RDONLY);
1566         if (procfile < 0)
1567                 return NULL;
1568
1569         ret = malloc(1024);
1570         if (ret) {
1571                 switch (read(procfile, ret, 1024)) {
1572                 case -1: goto fail;
1573                 case 1024: goto fail; /* Partial read.  Wierd */
1574                 }
1575                 if (ret[strlen(ret)-1]=='\n') 
1576                         ret[strlen(ret)-1]=0;
1577                 close(procfile);
1578                 return ret;
1579         }
1580  fail:
1581         free(ret);
1582         close(procfile);
1583         return NULL;
1584 }
1585
1586 int ip6tables_insmod(const char *modname, const char *modprobe)
1587 {
1588         char *buf = NULL;
1589         char *argv[3];
1590
1591         /* If they don't explicitly set it, read out of kernel */
1592         if (!modprobe) {
1593                 buf = get_modprobe();
1594                 if (!buf)
1595                         return -1;
1596                 modprobe = buf;
1597         }
1598
1599         switch (fork()) {
1600         case 0:
1601                 argv[0] = (char *)modprobe;
1602                 argv[1] = (char *)modname;
1603                 argv[2] = NULL;
1604                 execv(argv[0], argv);
1605
1606                 /* not usually reached */
1607                 exit(0);
1608         case -1:
1609                 return -1;
1610
1611         default: /* parent */
1612                 wait(NULL);
1613         }
1614
1615         free(buf);
1616         return 0;
1617 }
1618
1619 static struct ip6t_entry *
1620 generate_entry(const struct ip6t_entry *fw,
1621                struct ip6tables_match *matches,
1622                struct ip6t_entry_target *target)
1623 {
1624         unsigned int size;
1625         struct ip6tables_match *m;
1626         struct ip6t_entry *e;
1627
1628         size = sizeof(struct ip6t_entry);
1629         for (m = matches; m; m = m->next) {
1630                 if (!m->used)
1631                         continue;
1632
1633                 size += m->m->u.match_size;
1634         }
1635
1636         e = fw_malloc(size + target->u.target_size);
1637         *e = *fw;
1638         e->target_offset = size;
1639         e->next_offset = size + target->u.target_size;
1640
1641         size = 0;
1642         for (m = matches; m; m = m->next) {
1643                 if (!m->used)
1644                         continue;
1645
1646                 memcpy(e->elems + size, m->m, m->m->u.match_size);
1647                 size += m->m->u.match_size;
1648         }
1649         memcpy(e->elems + size, target, target->u.target_size);
1650
1651         return e;
1652 }
1653
1654 int do_command6(int argc, char *argv[], char **table, ip6tc_handle_t *handle)
1655 {
1656         struct ip6t_entry fw, *e = NULL;
1657         int invert = 0;
1658         unsigned int nsaddrs = 0, ndaddrs = 0;
1659         struct in6_addr *saddrs = NULL, *daddrs = NULL;
1660
1661         int c, verbose = 0;
1662         const char *chain = NULL;
1663         const char *shostnetworkmask = NULL, *dhostnetworkmask = NULL;
1664         const char *policy = NULL, *newname = NULL;
1665         unsigned int rulenum = 0, options = 0, command = 0;
1666         const char *pcnt = NULL, *bcnt = NULL;
1667         int ret = 1;
1668         struct ip6tables_match *m;
1669         struct ip6tables_target *target = NULL;
1670         struct ip6tables_target *t;
1671         const char *jumpto = "";
1672         char *protocol = NULL;
1673         const char *modprobe = NULL;
1674         int proto_used = 0;
1675         char icmp6p[] = "icmpv6";
1676
1677         memset(&fw, 0, sizeof(fw));
1678
1679         opts = original_opts;
1680         global_option_offset = 0;
1681
1682         /* re-set optind to 0 in case do_command gets called
1683          * a second time */
1684         optind = 0;
1685
1686         /* clear mflags in case do_command gets called a second time
1687          * (we clear the global list of all matches for security)*/
1688         for (m = ip6tables_matches; m; m = m->next) {
1689                 m->mflags = 0;
1690                 m->used = 0;
1691         }
1692
1693         for (t = ip6tables_targets; t; t = t->next) {
1694                 t->tflags = 0;
1695                 t->used = 0;
1696         }
1697
1698         /* Suppress error messages: we may add new options if we
1699            demand-load a protocol. */
1700         opterr = 0;
1701
1702         while ((c = getopt_long(argc, argv,
1703            "-A:D:R:I:L::M:F::Z::N:X::E:P:Vh::o:p:s:d:j:i:bvnt:m:xc:",
1704                                            opts, NULL)) != -1) {
1705                 switch (c) {
1706                         /*
1707                          * Command selection
1708                          */
1709                 case 'A':
1710                         add_command(&command, CMD_APPEND, CMD_NONE,
1711                                     invert);
1712                         chain = optarg;
1713                         break;
1714
1715                 case 'D':
1716                         add_command(&command, CMD_DELETE, CMD_NONE,
1717                                     invert);
1718                         chain = optarg;
1719                         if (optind < argc && argv[optind][0] != '-'
1720                             && argv[optind][0] != '!') {
1721                                 rulenum = parse_rulenumber(argv[optind++]);
1722                                 command = CMD_DELETE_NUM;
1723                         }
1724                         break;
1725
1726                 case 'R':
1727                         add_command(&command, CMD_REPLACE, CMD_NONE,
1728                                     invert);
1729                         chain = optarg;
1730                         if (optind < argc && argv[optind][0] != '-'
1731                             && argv[optind][0] != '!')
1732                                 rulenum = parse_rulenumber(argv[optind++]);
1733                         else
1734                                 exit_error(PARAMETER_PROBLEM,
1735                                            "-%c requires a rule number",
1736                                            cmd2char(CMD_REPLACE));
1737                         break;
1738
1739                 case 'I':
1740                         add_command(&command, CMD_INSERT, CMD_NONE,
1741                                     invert);
1742                         chain = optarg;
1743                         if (optind < argc && argv[optind][0] != '-'
1744                             && argv[optind][0] != '!')
1745                                 rulenum = parse_rulenumber(argv[optind++]);
1746                         else rulenum = 1;
1747                         break;
1748
1749                 case 'L':
1750                         add_command(&command, CMD_LIST, CMD_ZERO,
1751                                     invert);
1752                         if (optarg) chain = optarg;
1753                         else if (optind < argc && argv[optind][0] != '-'
1754                                  && argv[optind][0] != '!')
1755                                 chain = argv[optind++];
1756                         break;
1757
1758                 case 'F':
1759                         add_command(&command, CMD_FLUSH, CMD_NONE,
1760                                     invert);
1761                         if (optarg) chain = optarg;
1762                         else if (optind < argc && argv[optind][0] != '-'
1763                                  && argv[optind][0] != '!')
1764                                 chain = argv[optind++];
1765                         break;
1766
1767                 case 'Z':
1768                         add_command(&command, CMD_ZERO, CMD_LIST,
1769                                     invert);
1770                         if (optarg) chain = optarg;
1771                         else if (optind < argc && argv[optind][0] != '-'
1772                                 && argv[optind][0] != '!')
1773                                 chain = argv[optind++];
1774                         break;
1775
1776                 case 'N':
1777                         if (optarg && *optarg == '-')
1778                                 exit_error(PARAMETER_PROBLEM,
1779                                            "chain name not allowed to start "
1780                                            "with `-'\n");
1781                         if (find_target(optarg, TRY_LOAD))
1782                                 exit_error(PARAMETER_PROBLEM,
1783                                            "chain name may not clash "
1784                                            "with target name\n");
1785                         add_command(&command, CMD_NEW_CHAIN, CMD_NONE,
1786                                     invert);
1787                         chain = optarg;
1788                         break;
1789
1790                 case 'X':
1791                         add_command(&command, CMD_DELETE_CHAIN, CMD_NONE,
1792                                     invert);
1793                         if (optarg) chain = optarg;
1794                         else if (optind < argc && argv[optind][0] != '-'
1795                                  && argv[optind][0] != '!')
1796                                 chain = argv[optind++];
1797                         break;
1798
1799                 case 'E':
1800                         add_command(&command, CMD_RENAME_CHAIN, CMD_NONE,
1801                                     invert);
1802                         chain = optarg;
1803                         if (optind < argc && argv[optind][0] != '-'
1804                             && argv[optind][0] != '!')
1805                                 newname = argv[optind++];
1806                         else
1807                                 exit_error(PARAMETER_PROBLEM,
1808                                            "-%c requires old-chain-name and "
1809                                            "new-chain-name",
1810                                             cmd2char(CMD_RENAME_CHAIN));
1811                         break;
1812
1813                 case 'P':
1814                         add_command(&command, CMD_SET_POLICY, CMD_NONE,
1815                                     invert);
1816                         chain = optarg;
1817                         if (optind < argc && argv[optind][0] != '-'
1818                             && argv[optind][0] != '!')
1819                                 policy = argv[optind++];
1820                         else
1821                                 exit_error(PARAMETER_PROBLEM,
1822                                            "-%c requires a chain and a policy",
1823                                            cmd2char(CMD_SET_POLICY));
1824                         break;
1825
1826                 case 'h':
1827                         if (!optarg)
1828                                 optarg = argv[optind];
1829
1830                         /* iptables -p icmp -h */
1831                         if (!ip6tables_matches && protocol)
1832                                 find_match(protocol, TRY_LOAD);
1833
1834                         exit_printhelp();
1835
1836                         /*
1837                          * Option selection
1838                          */
1839                 case 'p':
1840                         check_inverse(optarg, &invert, &optind, argc);
1841                         set_option(&options, OPT_PROTOCOL, &fw.ipv6.invflags,
1842                                    invert);
1843
1844                         /* Canonicalize into lower case */
1845                         for (protocol = argv[optind-1]; *protocol; protocol++)
1846                                 *protocol = tolower(*protocol);
1847
1848                         protocol = argv[optind-1];
1849                         if ( strcmp(protocol,"ipv6-icmp") == 0)
1850                                 protocol = icmp6p;
1851                         fw.ipv6.proto = parse_protocol(protocol);
1852                         fw.ipv6.flags |= IP6T_F_PROTO;
1853
1854                         if (fw.ipv6.proto == 0
1855                             && (fw.ipv6.invflags & IP6T_INV_PROTO))
1856                                 exit_error(PARAMETER_PROBLEM,
1857                                            "rule would never match protocol");
1858                         fw.nfcache |= NFC_IP6_PROTO;
1859                         break;
1860
1861                 case 's':
1862                         check_inverse(optarg, &invert, &optind, argc);
1863                         set_option(&options, OPT_SOURCE, &fw.ipv6.invflags,
1864                                    invert);
1865                         shostnetworkmask = argv[optind-1];
1866                         fw.nfcache |= NFC_IP6_SRC;
1867                         break;
1868
1869                 case 'd':
1870                         check_inverse(optarg, &invert, &optind, argc);
1871                         set_option(&options, OPT_DESTINATION, &fw.ipv6.invflags,
1872                                    invert);
1873                         dhostnetworkmask = argv[optind-1];
1874                         fw.nfcache |= NFC_IP6_DST;
1875                         break;
1876
1877                 case 'j':
1878                         set_option(&options, OPT_JUMP, &fw.ipv6.invflags,
1879                                    invert);
1880                         jumpto = parse_target(optarg);
1881                         /* TRY_LOAD (may be chain name) */
1882                         target = find_target(jumpto, TRY_LOAD);
1883
1884                         if (target) {
1885                                 size_t size;
1886
1887                                 size = IP6T_ALIGN(sizeof(struct ip6t_entry_target))
1888                                         + target->size;
1889
1890                                 target->t = fw_calloc(1, size);
1891                                 target->t->u.target_size = size;
1892                                 strcpy(target->t->u.user.name, jumpto);
1893                                 target->init(target->t, &fw.nfcache);
1894                                 opts = merge_options(opts, target->extra_opts, &target->option_offset);
1895                         }
1896                         break;
1897
1898
1899                 case 'i':
1900                         check_inverse(optarg, &invert, &optind, argc);
1901                         set_option(&options, OPT_VIANAMEIN, &fw.ipv6.invflags,
1902                                    invert);
1903                         parse_interface(argv[optind-1],
1904                                         fw.ipv6.iniface,
1905                                         fw.ipv6.iniface_mask);
1906                         fw.nfcache |= NFC_IP6_IF_IN;
1907                         break;
1908
1909                 case 'o':
1910                         check_inverse(optarg, &invert, &optind, argc);
1911                         set_option(&options, OPT_VIANAMEOUT, &fw.ipv6.invflags,
1912                                    invert);
1913                         parse_interface(argv[optind-1],
1914                                         fw.ipv6.outiface,
1915                                         fw.ipv6.outiface_mask);
1916                         fw.nfcache |= NFC_IP6_IF_OUT;
1917                         break;
1918
1919                 case 'v':
1920                         if (!verbose)
1921                                 set_option(&options, OPT_VERBOSE,
1922                                            &fw.ipv6.invflags, invert);
1923                         verbose++;
1924                         break;
1925
1926                 case 'm': {
1927                         size_t size;
1928
1929                         if (invert)
1930                                 exit_error(PARAMETER_PROBLEM,
1931                                            "unexpected ! flag before --match");
1932
1933                         m = find_match(optarg, LOAD_MUST_SUCCEED);
1934                         size = IP6T_ALIGN(sizeof(struct ip6t_entry_match))
1935                                          + m->size;
1936                         m->m = fw_calloc(1, size);
1937                         m->m->u.match_size = size;
1938                         strcpy(m->m->u.user.name, m->name);
1939                         m->init(m->m, &fw.nfcache);
1940                         opts = merge_options(opts, m->extra_opts, &m->option_offset);
1941                 }
1942                 break;
1943
1944                 case 'n':
1945                         set_option(&options, OPT_NUMERIC, &fw.ipv6.invflags,
1946                                    invert);
1947                         break;
1948
1949                 case 't':
1950                         if (invert)
1951                                 exit_error(PARAMETER_PROBLEM,
1952                                            "unexpected ! flag before --table");
1953                         *table = argv[optind-1];
1954                         break;
1955
1956                 case 'x':
1957                         set_option(&options, OPT_EXPANDED, &fw.ipv6.invflags,
1958                                    invert);
1959                         break;
1960
1961                 case 'V':
1962                         if (invert)
1963                                 printf("Not %s ;-)\n", program_version);
1964                         else
1965                                 printf("%s v%s\n",
1966                                        program_name, program_version);
1967                         exit(0);
1968
1969                 case '0':
1970                         set_option(&options, OPT_LINENUMBERS, &fw.ipv6.invflags,
1971                                    invert);
1972                         break;
1973
1974                 case 'M':
1975                         modprobe = optarg;
1976                         break;
1977
1978                 case 'c':
1979
1980                         set_option(&options, OPT_COUNTERS, &fw.ipv6.invflags,
1981                                    invert);
1982                         pcnt = optarg;
1983                         if (optind < argc && argv[optind][0] != '-'
1984                             && argv[optind][0] != '!')
1985                                 bcnt = argv[optind++];
1986                         else
1987                                 exit_error(PARAMETER_PROBLEM,
1988                                         "-%c requires packet and byte counter",
1989                                         opt2char(OPT_COUNTERS));
1990
1991                         if (sscanf(pcnt, "%llu", &fw.counters.pcnt) != 1)
1992                                 exit_error(PARAMETER_PROBLEM,
1993                                         "-%c packet counter not numeric",
1994                                         opt2char(OPT_COUNTERS));
1995
1996                         if (sscanf(bcnt, "%llu", &fw.counters.bcnt) != 1)
1997                                 exit_error(PARAMETER_PROBLEM,
1998                                         "-%c byte counter not numeric",
1999                                         opt2char(OPT_COUNTERS));
2000                         
2001                         break;
2002
2003
2004                 case 1: /* non option */
2005                         if (optarg[0] == '!' && optarg[1] == '\0') {
2006                                 if (invert)
2007                                         exit_error(PARAMETER_PROBLEM,
2008                                                    "multiple consecutive ! not"
2009                                                    " allowed");
2010                                 invert = TRUE;
2011                                 optarg[0] = '\0';
2012                                 continue;
2013                         }
2014                         printf("Bad argument `%s'\n", optarg);
2015                         exit_tryhelp(2);
2016
2017                 default:
2018                         /* FIXME: This scheme doesn't allow two of the same
2019                            matches --RR */
2020                         if (!target
2021                             || !(target->parse(c - target->option_offset,
2022                                                argv, invert,
2023                                                &target->tflags,
2024                                                &fw, &target->t))) {
2025                                 for (m = ip6tables_matches; m; m = m->next) {
2026                                         if (!m->used)
2027                                                 continue;
2028
2029                                         if (m->parse(c - m->option_offset,
2030                                                      argv, invert,
2031                                                      &m->mflags,
2032                                                      &fw,
2033                                                      &fw.nfcache,
2034                                                      &m->m))
2035                                                 break;
2036                                 }
2037
2038                                 /* If you listen carefully, you can
2039                                    actually hear this code suck. */
2040
2041                                 /* some explanations (after four different bugs
2042                                  * in 3 different releases): If we encountere a
2043                                  * parameter, that has not been parsed yet,
2044                                  * it's not an option of an explicitly loaded
2045                                  * match or a target.  However, we support
2046                                  * implicit loading of the protocol match
2047                                  * extension.  '-p tcp' means 'l4 proto 6' and
2048                                  * at the same time 'load tcp protocol match on
2049                                  * demand if we specify --dport'.
2050                                  *
2051                                  * To make this work, we need to make sure:
2052                                  * - the parameter has not been parsed by
2053                                  *   a match (m above)
2054                                  * - a protocol has been specified
2055                                  * - the protocol extension has not been
2056                                  *   loaded yet, or is loaded and unused
2057                                  *   [think of iptables-restore!]
2058                                  * - the protocol extension can be successively
2059                                  *   loaded
2060                                  */
2061                                 if (m == NULL
2062                                     && protocol
2063                                     && (!find_proto(protocol, DONT_LOAD,
2064                                                    options&OPT_NUMERIC) 
2065                                         || (find_proto(protocol, DONT_LOAD,
2066                                                         options&OPT_NUMERIC)
2067                                             && (proto_used == 0))
2068                                        )
2069                                     && (m = find_proto(protocol, TRY_LOAD,
2070                                                        options&OPT_NUMERIC))) {
2071                                         /* Try loading protocol */
2072                                         size_t size;
2073                                         
2074                                         proto_used = 1;
2075
2076                                         size = IP6T_ALIGN(sizeof(struct ip6t_entry_match))
2077                                                          + m->size;
2078
2079                                         m->m = fw_calloc(1, size);
2080                                         m->m->u.match_size = size;
2081                                         strcpy(m->m->u.user.name, m->name);
2082                                         m->init(m->m, &fw.nfcache);
2083
2084                                         opts = merge_options(opts,
2085                                             m->extra_opts, &m->option_offset);
2086
2087                                         optind--;
2088                                         continue;
2089                                 }
2090
2091                                 if (!m)
2092                                         exit_error(PARAMETER_PROBLEM,
2093                                                    "Unknown arg `%s'",
2094                                                    argv[optind-1]);
2095                         }
2096                 }
2097                 invert = FALSE;
2098         }
2099
2100         for (m = ip6tables_matches; m; m = m->next) {
2101                 if (!m->used)
2102                         continue;
2103
2104                 m->final_check(m->mflags);
2105         }
2106
2107         if (target)
2108                 target->final_check(target->tflags);
2109
2110         /* Fix me: must put inverse options checking here --MN */
2111
2112         if (optind < argc)
2113                 exit_error(PARAMETER_PROBLEM,
2114                            "unknown arguments found on commandline");
2115         if (!command)
2116                 exit_error(PARAMETER_PROBLEM, "no command specified");
2117         if (invert)
2118                 exit_error(PARAMETER_PROBLEM,
2119                            "nothing appropriate following !");
2120
2121         if (command & (CMD_REPLACE | CMD_INSERT | CMD_DELETE | CMD_APPEND)) {
2122                 if (!(options & OPT_DESTINATION))
2123                         dhostnetworkmask = "::0/0";
2124                 if (!(options & OPT_SOURCE))
2125                         shostnetworkmask = "::0/0";
2126         }
2127
2128         if (shostnetworkmask)
2129                 parse_hostnetworkmask(shostnetworkmask, &saddrs,
2130                                       &(fw.ipv6.smsk), &nsaddrs);
2131
2132         if (dhostnetworkmask)
2133                 parse_hostnetworkmask(dhostnetworkmask, &daddrs,
2134                                       &(fw.ipv6.dmsk), &ndaddrs);
2135
2136         if ((nsaddrs > 1 || ndaddrs > 1) &&
2137             (fw.ipv6.invflags & (IP6T_INV_SRCIP | IP6T_INV_DSTIP)))
2138                 exit_error(PARAMETER_PROBLEM, "! not allowed with multiple"
2139                            " source or destination IP addresses");
2140
2141         if (command == CMD_REPLACE && (nsaddrs != 1 || ndaddrs != 1))
2142                 exit_error(PARAMETER_PROBLEM, "Replacement rule does not "
2143                            "specify a unique address");
2144
2145         generic_opt_check(command, options);
2146
2147         if (chain && strlen(chain) > IP6T_FUNCTION_MAXNAMELEN)
2148                 exit_error(PARAMETER_PROBLEM,
2149                            "chain name `%s' too long (must be under %i chars)",
2150                            chain, IP6T_FUNCTION_MAXNAMELEN);
2151
2152         /* only allocate handle if we weren't called with a handle */
2153         if (!*handle)
2154                 *handle = ip6tc_init(*table);
2155
2156         if (!*handle) {
2157                 /* try to insmod the module if iptc_init failed */
2158                 ip6tables_insmod("ip6_tables", modprobe);
2159                 *handle = ip6tc_init(*table);
2160         }
2161
2162         if (!*handle)
2163                 exit_error(VERSION_PROBLEM,
2164                         "can't initialize ip6tables table `%s': %s",
2165                         *table, ip6tc_strerror(errno));
2166
2167         if (command == CMD_APPEND
2168             || command == CMD_DELETE
2169             || command == CMD_INSERT
2170             || command == CMD_REPLACE) {
2171                 if (strcmp(chain, "PREROUTING") == 0
2172                     || strcmp(chain, "INPUT") == 0) {
2173                         /* -o not valid with incoming packets. */
2174                         if (options & OPT_VIANAMEOUT)
2175                                 exit_error(PARAMETER_PROBLEM,
2176                                            "Can't use -%c with %s\n",
2177                                            opt2char(OPT_VIANAMEOUT),
2178                                            chain);
2179                 }
2180
2181                 if (strcmp(chain, "POSTROUTING") == 0
2182                     || strcmp(chain, "OUTPUT") == 0) {
2183                         /* -i not valid with outgoing packets */
2184                         if (options & OPT_VIANAMEIN)
2185                                 exit_error(PARAMETER_PROBLEM,
2186                                            "Can't use -%c with %s\n",
2187                                            opt2char(OPT_VIANAMEIN),
2188                                            chain);
2189                 }
2190
2191                 if (target && ip6tc_is_chain(jumpto, *handle)) {
2192                         printf("Warning: using chain %s, not extension\n",
2193                                jumpto);
2194
2195                         target = NULL;
2196                 }
2197
2198                 /* If they didn't specify a target, or it's a chain
2199                    name, use standard. */
2200                 if (!target
2201                     && (strlen(jumpto) == 0
2202                         || ip6tc_is_chain(jumpto, *handle))) {
2203                         size_t size;
2204
2205                         target = find_target(IP6T_STANDARD_TARGET,
2206                                              LOAD_MUST_SUCCEED);
2207
2208                         size = sizeof(struct ip6t_entry_target)
2209                                 + target->size;
2210                         target->t = fw_calloc(1, size);
2211                         target->t->u.target_size = size;
2212                         strcpy(target->t->u.user.name, jumpto);
2213                         target->init(target->t, &fw.nfcache);
2214                 }
2215
2216                 if (!target) {
2217                         /* it is no chain, and we can't load a plugin.
2218                          * We cannot know if the plugin is corrupt, non
2219                          * existant OR if the user just misspelled a
2220                          * chain. */
2221                         find_target(jumpto, LOAD_MUST_SUCCEED);
2222                 } else {
2223                         e = generate_entry(&fw, ip6tables_matches, target->t);
2224                 }
2225         }
2226
2227         switch (command) {
2228         case CMD_APPEND:
2229                 ret = append_entry(chain, e,
2230                                    nsaddrs, saddrs, ndaddrs, daddrs,
2231                                    options&OPT_VERBOSE,
2232                                    handle);
2233                 break;
2234         case CMD_DELETE:
2235                 ret = delete_entry(chain, e,
2236                                    nsaddrs, saddrs, ndaddrs, daddrs,
2237                                    options&OPT_VERBOSE,
2238                                    handle);
2239                 break;
2240         case CMD_DELETE_NUM:
2241                 ret = ip6tc_delete_num_entry(chain, rulenum - 1, handle);
2242                 break;
2243         case CMD_REPLACE:
2244                 ret = replace_entry(chain, e, rulenum - 1,
2245                                     saddrs, daddrs, options&OPT_VERBOSE,
2246                                     handle);
2247                 break;
2248         case CMD_INSERT:
2249                 ret = insert_entry(chain, e, rulenum - 1,
2250                                    nsaddrs, saddrs, ndaddrs, daddrs,
2251                                    options&OPT_VERBOSE,
2252                                    handle);
2253                 break;
2254         case CMD_LIST:
2255                 ret = list_entries(chain,
2256                                    options&OPT_VERBOSE,
2257                                    options&OPT_NUMERIC,
2258                                    options&OPT_EXPANDED,
2259                                    options&OPT_LINENUMBERS,
2260                                    handle);
2261                 break;
2262         case CMD_FLUSH:
2263                 ret = flush_entries(chain, options&OPT_VERBOSE, handle);
2264                 break;
2265         case CMD_ZERO:
2266                 ret = zero_entries(chain, options&OPT_VERBOSE, handle);
2267                 break;
2268         case CMD_LIST|CMD_ZERO:
2269                 ret = list_entries(chain,
2270                                    options&OPT_VERBOSE,
2271                                    options&OPT_NUMERIC,
2272                                    options&OPT_EXPANDED,
2273                                    options&OPT_LINENUMBERS,
2274                                    handle);
2275                 if (ret)
2276                         ret = zero_entries(chain,
2277                                            options&OPT_VERBOSE, handle);
2278                 break;
2279         case CMD_NEW_CHAIN:
2280                 ret = ip6tc_create_chain(chain, handle);
2281                 break;
2282         case CMD_DELETE_CHAIN:
2283                 ret = delete_chain(chain, options&OPT_VERBOSE, handle);
2284                 break;
2285         case CMD_RENAME_CHAIN:
2286                 ret = ip6tc_rename_chain(chain, newname,        handle);
2287                 break;
2288         case CMD_SET_POLICY:
2289                 ret = ip6tc_set_policy(chain, policy, NULL, handle);
2290                 break;
2291         default:
2292                 /* We should never reach this... */
2293                 exit_tryhelp(2);
2294         }
2295
2296         if (verbose > 1)
2297                 dump_entries6(*handle);
2298
2299         return ret;
2300 }