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