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