iptables: refer to dmesg when we hit error
[jleu-iptables.git] / ip6tables.c
blob3c45c0729e6ffbb63307ec20fea6fd853dcc4351
1 /* Code to take an ip6tables-style command line and do it. */
3 /*
4 * Author: Paul.Russell@rustcorp.com.au and mneuling@radlogic.com.au
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>
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.
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.
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.
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"
46 #ifndef TRUE
47 #define TRUE 1
48 #endif
49 #ifndef FALSE
50 #define FALSE 0
51 #endif
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
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))
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' };
86 #define OPTION_OFFSET 256
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'};
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 {.name = "goto", .has_arg = 1, .val = 'g'},
136 {NULL},
139 /* we need this for ip6tables-restore. ip6tables-restore.c sets line to the
140 * current line of the input file, in order to give a more precise error
141 * message. ip6tables itself doesn't need this, so it is initialized to the
142 * magic number of -1 */
143 int line = -1;
145 static struct option *opts = original_opts;
146 static unsigned int global_option_offset = 0;
148 /* Table of legal combinations of commands and options. If any of the
149 * given commands make an option legal, that option is legal (applies to
150 * CMD_LIST and CMD_ZERO only).
151 * Key:
152 * + compulsory
153 * x illegal
154 * optional
157 static char commands_v_options[NUMBER_OF_CMD][NUMBER_OF_OPT] =
158 /* Well, it's better than "Re: Linux vs FreeBSD" */
160 /* -n -s -d -p -j -v -x -i -o --line -c */
161 /*INSERT*/ {'x',' ',' ',' ',' ',' ','x',' ',' ','x',' '},
162 /*DELETE*/ {'x',' ',' ',' ',' ',' ','x',' ',' ','x','x'},
163 /*DELETE_NUM*/{'x','x','x','x','x',' ','x','x','x','x','x'},
164 /*REPLACE*/ {'x',' ',' ',' ',' ',' ','x',' ',' ','x',' '},
165 /*APPEND*/ {'x',' ',' ',' ',' ',' ','x',' ',' ','x',' '},
166 /*LIST*/ {' ','x','x','x','x',' ',' ','x','x',' ','x'},
167 /*FLUSH*/ {'x','x','x','x','x',' ','x','x','x','x','x'},
168 /*ZERO*/ {'x','x','x','x','x',' ','x','x','x','x','x'},
169 /*NEW_CHAIN*/ {'x','x','x','x','x',' ','x','x','x','x','x'},
170 /*DEL_CHAIN*/ {'x','x','x','x','x',' ','x','x','x','x','x'},
171 /*SET_POLICY*/{'x','x','x','x','x',' ','x','x','x','x',' '},
172 /*RENAME*/ {'x','x','x','x','x',' ','x','x','x','x','x'},
173 /*LIST_RULES*/{'x','x','x','x','x',' ','x','x','x','x','x'}
176 static int inverse_for_options[NUMBER_OF_OPT] =
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,
191 const char *program_version;
192 const char *program_name;
194 /* A few hardcoded protocols for 'all' and in case the user has no
195 /etc/protocols */
196 struct pprot {
197 char *name;
198 u_int8_t num;
201 struct afinfo afinfo = {
202 .family = NFPROTO_IPV6,
203 .libprefix = "libip6t_",
204 .ipproto = IPPROTO_IPV6,
205 .kmod = "ip6_tables",
206 .so_rev_match = IP6T_SO_GET_REVISION_MATCH,
207 .so_rev_target = IP6T_SO_GET_REVISION_TARGET,
210 /* Primitive headers... */
211 /* defined in netinet/in.h */
212 #if 0
213 #ifndef IPPROTO_ESP
214 #define IPPROTO_ESP 50
215 #endif
216 #ifndef IPPROTO_AH
217 #define IPPROTO_AH 51
218 #endif
219 #endif
220 #ifndef IPPROTO_MH
221 #define IPPROTO_MH 135
222 #endif
224 static const struct pprot chain_protos[] = {
225 { "tcp", IPPROTO_TCP },
226 { "udp", IPPROTO_UDP },
227 { "udplite", IPPROTO_UDPLITE },
228 { "icmpv6", IPPROTO_ICMPV6 },
229 { "ipv6-icmp", IPPROTO_ICMPV6 },
230 { "esp", IPPROTO_ESP },
231 { "ah", IPPROTO_AH },
232 { "ipv6-mh", IPPROTO_MH },
233 { "mh", IPPROTO_MH },
234 { "all", 0 },
237 static char *
238 proto_to_name(u_int8_t proto, int nolookup)
240 unsigned int i;
242 if (proto && !nolookup) {
243 struct protoent *pent = getprotobynumber(proto);
244 if (pent)
245 return pent->p_name;
248 for (i = 0; i < sizeof(chain_protos)/sizeof(struct pprot); i++)
249 if (chain_protos[i].num == proto)
250 return chain_protos[i].name;
252 return NULL;
255 static void free_opts(int reset_offset)
257 if (opts != original_opts) {
258 free(opts);
259 opts = original_opts;
260 if (reset_offset)
261 global_option_offset = 0;
265 static void
266 exit_tryhelp(int status)
268 if (line != -1)
269 fprintf(stderr, "Error occurred at line: %d\n", line);
270 fprintf(stderr, "Try `%s -h' or '%s --help' for more information.\n",
271 program_name, program_name );
272 free_opts(1);
273 exit(status);
276 static void
277 exit_printhelp(struct ip6tables_rule_match *matches)
279 struct ip6tables_rule_match *matchp = NULL;
280 struct xtables_target *t = NULL;
282 printf("%s v%s\n\n"
283 "Usage: %s -[AD] chain rule-specification [options]\n"
284 " %s -[RI] chain rulenum rule-specification [options]\n"
285 " %s -D chain rulenum [options]\n"
286 " %s -[LS] [chain [rulenum]] [options]\n"
287 " %s -[FZ] [chain] [options]\n"
288 " %s -[NX] chain\n"
289 " %s -E old-chain-name new-chain-name\n"
290 " %s -P chain target [options]\n"
291 " %s -h (print this help information)\n\n",
292 program_name, program_version, program_name, program_name,
293 program_name, program_name, program_name, program_name,
294 program_name, program_name, program_name);
296 printf(
297 "Commands:\n"
298 "Either long or short options are allowed.\n"
299 " --append -A chain Append to chain\n"
300 " --delete -D chain Delete matching rule from chain\n"
301 " --delete -D chain rulenum\n"
302 " Delete rule rulenum (1 = first) from chain\n"
303 " --insert -I chain [rulenum]\n"
304 " Insert in chain as rulenum (default 1=first)\n"
305 " --replace -R chain rulenum\n"
306 " Replace rule rulenum (1 = first) in chain\n"
307 " --list -L [chain [rulenum]]\n"
308 " List the rules in a chain or all chains\n"
309 " --list-rules -S [chain [rulenum]]\n"
310 " Print the rules in a chain or all chains\n"
311 " --flush -F [chain] Delete all rules in chain or all chains\n"
312 " --zero -Z [chain] Zero counters in chain or all chains\n"
313 " --new -N chain Create a new user-defined chain\n"
314 " --delete-chain\n"
315 " -X [chain] Delete a user-defined chain\n"
316 " --policy -P chain target\n"
317 " Change policy on chain to target\n"
318 " --rename-chain\n"
319 " -E old-chain new-chain\n"
320 " Change chain name, (moving any references)\n"
322 "Options:\n"
323 "[!] --proto -p proto protocol: by number or name, eg. `tcp'\n"
324 "[!] --source -s address[/mask]\n"
325 " source specification\n"
326 "[!] --destination -d address[/mask]\n"
327 " destination specification\n"
328 "[!] --in-interface -i input name[+]\n"
329 " network interface name ([+] for wildcard)\n"
330 " --jump -j target\n"
331 " target for rule (may load target extension)\n"
332 #ifdef IP6T_F_GOTO
333 " --goto -g chain\n"
334 " jump to chain with no return\n"
335 #endif
336 " --match -m match\n"
337 " extended match (may load extension)\n"
338 " --numeric -n numeric output of addresses and ports\n"
339 "[!] --out-interface -o output name[+]\n"
340 " network interface name ([+] for wildcard)\n"
341 " --table -t table table to manipulate (default: `filter')\n"
342 " --verbose -v verbose mode\n"
343 " --line-numbers print line numbers when listing\n"
344 " --exact -x expand numbers (display exact values)\n"
345 /*"[!] --fragment -f match second or further fragments only\n"*/
346 " --modprobe=<command> try to insert modules using this command\n"
347 " --set-counters PKTS BYTES set the counter during insert/append\n"
348 "[!] --version -V print package version.\n");
350 /* Print out any special helps. A user might like to be able to add a --help
351 to the commandline, and see expected results. So we call help for all
352 specified matches & targets */
353 for (t = xtables_targets; t; t = t->next) {
354 if (t->used) {
355 printf("\n");
356 t->help();
359 for (matchp = matches; matchp; matchp = matchp->next) {
360 printf("\n");
361 matchp->match->help();
363 exit(0);
366 void
367 exit_error(enum exittype status, const char *msg, ...)
369 va_list args;
371 va_start(args, msg);
372 fprintf(stderr, "%s v%s: ", program_name, program_version);
373 vfprintf(stderr, msg, args);
374 va_end(args);
375 fprintf(stderr, "\n");
376 if (status == PARAMETER_PROBLEM)
377 exit_tryhelp(status);
378 if (status == VERSION_PROBLEM)
379 fprintf(stderr,
380 "Perhaps ip6tables or your kernel needs to be upgraded.\n");
381 /* On error paths, make sure that we don't leak memory */
382 free_opts(1);
383 exit(status);
386 static void
387 generic_opt_check(int command, int options)
389 int i, j, legal = 0;
391 /* Check that commands are valid with options. Complicated by the
392 * fact that if an option is legal with *any* command given, it is
393 * legal overall (ie. -z and -l).
395 for (i = 0; i < NUMBER_OF_OPT; i++) {
396 legal = 0; /* -1 => illegal, 1 => legal, 0 => undecided. */
398 for (j = 0; j < NUMBER_OF_CMD; j++) {
399 if (!(command & (1<<j)))
400 continue;
402 if (!(options & (1<<i))) {
403 if (commands_v_options[j][i] == '+')
404 exit_error(PARAMETER_PROBLEM,
405 "You need to supply the `-%c' "
406 "option for this command\n",
407 optflags[i]);
408 } else {
409 if (commands_v_options[j][i] != 'x')
410 legal = 1;
411 else if (legal == 0)
412 legal = -1;
415 if (legal == -1)
416 exit_error(PARAMETER_PROBLEM,
417 "Illegal option `-%c' with this command\n",
418 optflags[i]);
422 static char
423 opt2char(int option)
425 const char *ptr;
426 for (ptr = optflags; option > 1; option >>= 1, ptr++);
428 return *ptr;
431 static char
432 cmd2char(int option)
434 const char *ptr;
435 for (ptr = cmdflags; option > 1; option >>= 1, ptr++);
437 return *ptr;
440 static void
441 add_command(unsigned int *cmd, const int newcmd, const int othercmds,
442 int invert)
444 if (invert)
445 exit_error(PARAMETER_PROBLEM, "unexpected ! flag");
446 if (*cmd & (~othercmds))
447 exit_error(PARAMETER_PROBLEM, "Can't use -%c with -%c\n",
448 cmd2char(newcmd), cmd2char(*cmd & (~othercmds)));
449 *cmd |= newcmd;
453 check_inverse(const char option[], int *invert, int *my_optind, int argc)
455 if (option && strcmp(option, "!") == 0) {
456 if (*invert)
457 exit_error(PARAMETER_PROBLEM,
458 "Multiple `!' flags not allowed");
459 *invert = TRUE;
460 if (my_optind != NULL) {
461 ++*my_optind;
462 if (argc && *my_optind > argc)
463 exit_error(PARAMETER_PROBLEM,
464 "no argument following `!'");
467 return TRUE;
469 return FALSE;
473 * All functions starting with "parse" should succeed, otherwise
474 * the program fails.
475 * Most routines return pointers to static data that may change
476 * between calls to the same or other routines with a few exceptions:
477 * "host_to_addr", "parse_hostnetwork", and "parse_hostnetworkmask"
478 * return global static data.
481 /* Christophe Burki wants `-p 6' to imply `-m tcp'. */
482 static struct xtables_match *
483 find_proto(const char *pname, enum ip6t_tryload tryload, int nolookup, struct ip6tables_rule_match **matches)
485 unsigned int proto;
487 if (string_to_number(pname, 0, 255, &proto) != -1) {
488 char *protoname = proto_to_name(proto, nolookup);
490 if (protoname)
491 return find_match(protoname, tryload, matches);
492 } else
493 return find_match(pname, tryload, matches);
495 return NULL;
498 u_int16_t
499 parse_protocol(const char *s)
501 unsigned int proto;
503 if (string_to_number(s, 0, 255, &proto) == -1) {
504 struct protoent *pent;
506 /* first deal with the special case of 'all' to prevent
507 * people from being able to redefine 'all' in nsswitch
508 * and/or provoke expensive [not working] ldap/nis/...
509 * lookups */
510 if (!strcmp(s, "all"))
511 return 0;
513 if ((pent = getprotobyname(s)))
514 proto = pent->p_proto;
515 else {
516 unsigned int i;
517 for (i = 0;
518 i < sizeof(chain_protos)/sizeof(struct pprot);
519 i++) {
520 if (strcmp(s, chain_protos[i].name) == 0) {
521 proto = chain_protos[i].num;
522 break;
525 if (i == sizeof(chain_protos)/sizeof(struct pprot))
526 exit_error(PARAMETER_PROBLEM,
527 "unknown protocol `%s' specified",
532 return (u_int16_t)proto;
535 /* These are invalid numbers as upper layer protocol */
536 static int is_exthdr(u_int16_t proto)
538 return (proto == IPPROTO_ROUTING ||
539 proto == IPPROTO_FRAGMENT ||
540 proto == IPPROTO_AH ||
541 proto == IPPROTO_DSTOPTS);
544 /* Can't be zero. */
545 static int
546 parse_rulenumber(const char *rule)
548 unsigned int rulenum;
550 if (string_to_number(rule, 1, INT_MAX, &rulenum) == -1)
551 exit_error(PARAMETER_PROBLEM,
552 "Invalid rule number `%s'", rule);
554 return rulenum;
557 static const char *
558 parse_target(const char *targetname)
560 const char *ptr;
562 if (strlen(targetname) < 1)
563 exit_error(PARAMETER_PROBLEM,
564 "Invalid target name (too short)");
566 if (strlen(targetname)+1 > sizeof(ip6t_chainlabel))
567 exit_error(PARAMETER_PROBLEM,
568 "Invalid target name `%s' (%u chars max)",
569 targetname, (unsigned int)sizeof(ip6t_chainlabel)-1);
571 for (ptr = targetname; *ptr; ptr++)
572 if (isspace(*ptr))
573 exit_error(PARAMETER_PROBLEM,
574 "Invalid target name `%s'", targetname);
575 return targetname;
578 static void
579 set_option(unsigned int *options, unsigned int option, u_int8_t *invflg,
580 int invert)
582 if (*options & option)
583 exit_error(PARAMETER_PROBLEM, "multiple -%c flags not allowed",
584 opt2char(option));
585 *options |= option;
587 if (invert) {
588 unsigned int i;
589 for (i = 0; 1 << i != option; i++);
591 if (!inverse_for_options[i])
592 exit_error(PARAMETER_PROBLEM,
593 "cannot have ! before -%c",
594 opt2char(option));
595 *invflg |= inverse_for_options[i];
599 static struct option *
600 merge_options(struct option *oldopts, const struct option *newopts,
601 unsigned int *option_offset)
603 unsigned int num_old, num_new, i;
604 struct option *merge;
606 if (newopts == NULL)
607 return oldopts;
609 for (num_old = 0; oldopts[num_old].name; num_old++);
610 for (num_new = 0; newopts[num_new].name; num_new++);
612 global_option_offset += OPTION_OFFSET;
613 *option_offset = global_option_offset;
615 merge = malloc(sizeof(struct option) * (num_new + num_old + 1));
616 memcpy(merge, oldopts, num_old * sizeof(struct option));
617 free_opts(0); /* Release previous options merged if any */
618 for (i = 0; i < num_new; i++) {
619 merge[num_old + i] = newopts[i];
620 merge[num_old + i].val += *option_offset;
622 memset(merge + num_old + num_new, 0, sizeof(struct option));
624 return merge;
627 static void
628 print_num(u_int64_t number, unsigned int format)
630 if (format & FMT_KILOMEGAGIGA) {
631 if (number > 99999) {
632 number = (number + 500) / 1000;
633 if (number > 9999) {
634 number = (number + 500) / 1000;
635 if (number > 9999) {
636 number = (number + 500) / 1000;
637 if (number > 9999) {
638 number = (number + 500) / 1000;
639 printf(FMT("%4lluT ","%lluT "), (unsigned long long)number);
641 else printf(FMT("%4lluG ","%lluG "), (unsigned long long)number);
643 else printf(FMT("%4lluM ","%lluM "), (unsigned long long)number);
644 } else
645 printf(FMT("%4lluK ","%lluK "), (unsigned long long)number);
646 } else
647 printf(FMT("%5llu ","%llu "), (unsigned long long)number);
648 } else
649 printf(FMT("%8llu ","%llu "), (unsigned long long)number);
653 static void
654 print_header(unsigned int format, const char *chain, struct ip6tc_handle *handle)
656 struct ip6t_counters counters;
657 const char *pol = ip6tc_get_policy(chain, &counters, handle);
658 printf("Chain %s", chain);
659 if (pol) {
660 printf(" (policy %s", pol);
661 if (!(format & FMT_NOCOUNTS)) {
662 fputc(' ', stdout);
663 print_num(counters.pcnt, (format|FMT_NOTABLE));
664 fputs("packets, ", stdout);
665 print_num(counters.bcnt, (format|FMT_NOTABLE));
666 fputs("bytes", stdout);
668 printf(")\n");
669 } else {
670 unsigned int refs;
671 if (!ip6tc_get_references(&refs, chain, handle))
672 printf(" (ERROR obtaining refs)\n");
673 else
674 printf(" (%u references)\n", refs);
677 if (format & FMT_LINENUMBERS)
678 printf(FMT("%-4s ", "%s "), "num");
679 if (!(format & FMT_NOCOUNTS)) {
680 if (format & FMT_KILOMEGAGIGA) {
681 printf(FMT("%5s ","%s "), "pkts");
682 printf(FMT("%5s ","%s "), "bytes");
683 } else {
684 printf(FMT("%8s ","%s "), "pkts");
685 printf(FMT("%10s ","%s "), "bytes");
688 if (!(format & FMT_NOTARGET))
689 printf(FMT("%-9s ","%s "), "target");
690 fputs(" prot ", stdout);
691 if (format & FMT_OPTIONS)
692 fputs("opt", stdout);
693 if (format & FMT_VIA) {
694 printf(FMT(" %-6s ","%s "), "in");
695 printf(FMT("%-6s ","%s "), "out");
697 printf(FMT(" %-19s ","%s "), "source");
698 printf(FMT(" %-19s "," %s "), "destination");
699 printf("\n");
703 static int
704 print_match(const struct ip6t_entry_match *m,
705 const struct ip6t_ip6 *ip,
706 int numeric)
708 struct xtables_match *match = find_match(m->u.user.name, TRY_LOAD, NULL);
710 if (match) {
711 if (match->print)
712 match->print(ip, m, numeric);
713 else
714 printf("%s ", match->name);
715 } else {
716 if (m->u.user.name[0])
717 printf("UNKNOWN match `%s' ", m->u.user.name);
719 /* Don't stop iterating. */
720 return 0;
723 /* e is called `fw' here for historical reasons */
724 static void
725 print_firewall(const struct ip6t_entry *fw,
726 const char *targname,
727 unsigned int num,
728 unsigned int format,
729 struct ip6tc_handle *const handle)
731 struct xtables_target *target = NULL;
732 const struct ip6t_entry_target *t;
733 u_int8_t flags;
734 char buf[BUFSIZ];
736 if (!ip6tc_is_chain(targname, handle))
737 target = find_target(targname, TRY_LOAD);
738 else
739 target = find_target(IP6T_STANDARD_TARGET, LOAD_MUST_SUCCEED);
741 t = ip6t_get_target((struct ip6t_entry *)fw);
742 flags = fw->ipv6.flags;
744 if (format & FMT_LINENUMBERS)
745 printf(FMT("%-4u ", "%u "), num);
747 if (!(format & FMT_NOCOUNTS)) {
748 print_num(fw->counters.pcnt, format);
749 print_num(fw->counters.bcnt, format);
752 if (!(format & FMT_NOTARGET))
753 printf(FMT("%-9s ", "%s "), targname);
755 fputc(fw->ipv6.invflags & IP6T_INV_PROTO ? '!' : ' ', stdout);
757 char *pname = proto_to_name(fw->ipv6.proto, format&FMT_NUMERIC);
758 if (pname)
759 printf(FMT("%-5s", "%s "), pname);
760 else
761 printf(FMT("%-5hu", "%hu "), fw->ipv6.proto);
764 if (format & FMT_OPTIONS) {
765 if (format & FMT_NOTABLE)
766 fputs("opt ", stdout);
767 fputc(' ', stdout); /* Invert flag of FRAG */
768 fputc(' ', stdout); /* -f */
769 fputc(' ', stdout);
772 if (format & FMT_VIA) {
773 char iface[IFNAMSIZ+2];
775 if (fw->ipv6.invflags & IP6T_INV_VIA_IN) {
776 iface[0] = '!';
777 iface[1] = '\0';
779 else iface[0] = '\0';
781 if (fw->ipv6.iniface[0] != '\0') {
782 strcat(iface, fw->ipv6.iniface);
784 else if (format & FMT_NUMERIC) strcat(iface, "*");
785 else strcat(iface, "any");
786 printf(FMT(" %-6s ","in %s "), iface);
788 if (fw->ipv6.invflags & IP6T_INV_VIA_OUT) {
789 iface[0] = '!';
790 iface[1] = '\0';
792 else iface[0] = '\0';
794 if (fw->ipv6.outiface[0] != '\0') {
795 strcat(iface, fw->ipv6.outiface);
797 else if (format & FMT_NUMERIC) strcat(iface, "*");
798 else strcat(iface, "any");
799 printf(FMT("%-6s ","out %s "), iface);
802 fputc(fw->ipv6.invflags & IP6T_INV_SRCIP ? '!' : ' ', stdout);
803 if (!memcmp(&fw->ipv6.smsk, &in6addr_any, sizeof in6addr_any)
804 && !(format & FMT_NUMERIC))
805 printf(FMT("%-19s ","%s "), "anywhere");
806 else {
807 if (format & FMT_NUMERIC)
808 sprintf(buf, "%s", ip6addr_to_numeric(&fw->ipv6.src));
809 else
810 sprintf(buf, "%s", ip6addr_to_anyname(&fw->ipv6.src));
811 strcat(buf, ip6mask_to_numeric(&fw->ipv6.smsk));
812 printf(FMT("%-19s ","%s "), buf);
815 fputc(fw->ipv6.invflags & IP6T_INV_DSTIP ? '!' : ' ', stdout);
816 if (!memcmp(&fw->ipv6.dmsk, &in6addr_any, sizeof in6addr_any)
817 && !(format & FMT_NUMERIC))
818 printf(FMT("%-19s ","-> %s"), "anywhere");
819 else {
820 if (format & FMT_NUMERIC)
821 sprintf(buf, "%s", ip6addr_to_numeric(&fw->ipv6.dst));
822 else
823 sprintf(buf, "%s", ip6addr_to_anyname(&fw->ipv6.dst));
824 strcat(buf, ip6mask_to_numeric(&fw->ipv6.dmsk));
825 printf(FMT("%-19s ","-> %s"), buf);
828 if (format & FMT_NOTABLE)
829 fputs(" ", stdout);
831 #ifdef IP6T_F_GOTO
832 if(fw->ipv6.flags & IP6T_F_GOTO)
833 printf("[goto] ");
834 #endif
836 IP6T_MATCH_ITERATE(fw, print_match, &fw->ipv6, format & FMT_NUMERIC);
838 if (target) {
839 if (target->print)
840 /* Print the target information. */
841 target->print(&fw->ipv6, t, format & FMT_NUMERIC);
842 } else if (t->u.target_size != sizeof(*t))
843 printf("[%u bytes of unknown target data] ",
844 (unsigned int)(t->u.target_size - sizeof(*t)));
846 if (!(format & FMT_NONEWLINE))
847 fputc('\n', stdout);
850 static void
851 print_firewall_line(const struct ip6t_entry *fw,
852 struct ip6tc_handle *const h)
854 struct ip6t_entry_target *t;
856 t = ip6t_get_target((struct ip6t_entry *)fw);
857 print_firewall(fw, t->u.user.name, 0, FMT_PRINT_RULE, h);
860 static int
861 append_entry(const ip6t_chainlabel chain,
862 struct ip6t_entry *fw,
863 unsigned int nsaddrs,
864 const struct in6_addr saddrs[],
865 unsigned int ndaddrs,
866 const struct in6_addr daddrs[],
867 int verbose,
868 struct ip6tc_handle *handle)
870 unsigned int i, j;
871 int ret = 1;
873 for (i = 0; i < nsaddrs; i++) {
874 fw->ipv6.src = saddrs[i];
875 for (j = 0; j < ndaddrs; j++) {
876 fw->ipv6.dst = daddrs[j];
877 if (verbose)
878 print_firewall_line(fw, handle);
879 ret &= ip6tc_append_entry(chain, fw, handle);
883 return ret;
886 static int
887 replace_entry(const ip6t_chainlabel chain,
888 struct ip6t_entry *fw,
889 unsigned int rulenum,
890 const struct in6_addr *saddr,
891 const struct in6_addr *daddr,
892 int verbose,
893 struct ip6tc_handle *handle)
895 fw->ipv6.src = *saddr;
896 fw->ipv6.dst = *daddr;
898 if (verbose)
899 print_firewall_line(fw, handle);
900 return ip6tc_replace_entry(chain, fw, rulenum, handle);
903 static int
904 insert_entry(const ip6t_chainlabel chain,
905 struct ip6t_entry *fw,
906 unsigned int rulenum,
907 unsigned int nsaddrs,
908 const struct in6_addr saddrs[],
909 unsigned int ndaddrs,
910 const struct in6_addr daddrs[],
911 int verbose,
912 struct ip6tc_handle *handle)
914 unsigned int i, j;
915 int ret = 1;
917 for (i = 0; i < nsaddrs; i++) {
918 fw->ipv6.src = saddrs[i];
919 for (j = 0; j < ndaddrs; j++) {
920 fw->ipv6.dst = daddrs[j];
921 if (verbose)
922 print_firewall_line(fw, handle);
923 ret &= ip6tc_insert_entry(chain, fw, rulenum, handle);
927 return ret;
930 static unsigned char *
931 make_delete_mask(struct ip6t_entry *fw, struct ip6tables_rule_match *matches)
933 /* Establish mask for comparison */
934 unsigned int size;
935 struct ip6tables_rule_match *matchp;
936 unsigned char *mask, *mptr;
938 size = sizeof(struct ip6t_entry);
939 for (matchp = matches; matchp; matchp = matchp->next)
940 size += IP6T_ALIGN(sizeof(struct ip6t_entry_match)) + matchp->match->size;
942 mask = fw_calloc(1, size
943 + IP6T_ALIGN(sizeof(struct ip6t_entry_target))
944 + xtables_targets->size);
946 memset(mask, 0xFF, sizeof(struct ip6t_entry));
947 mptr = mask + sizeof(struct ip6t_entry);
949 for (matchp = matches; matchp; matchp = matchp->next) {
950 memset(mptr, 0xFF,
951 IP6T_ALIGN(sizeof(struct ip6t_entry_match))
952 + matchp->match->userspacesize);
953 mptr += IP6T_ALIGN(sizeof(struct ip6t_entry_match)) + matchp->match->size;
956 memset(mptr, 0xFF,
957 IP6T_ALIGN(sizeof(struct ip6t_entry_target))
958 + xtables_targets->userspacesize);
960 return mask;
963 static int
964 delete_entry(const ip6t_chainlabel chain,
965 struct ip6t_entry *fw,
966 unsigned int nsaddrs,
967 const struct in6_addr saddrs[],
968 unsigned int ndaddrs,
969 const struct in6_addr daddrs[],
970 int verbose,
971 struct ip6tc_handle *handle,
972 struct ip6tables_rule_match *matches)
974 unsigned int i, j;
975 int ret = 1;
976 unsigned char *mask;
978 mask = make_delete_mask(fw, matches);
979 for (i = 0; i < nsaddrs; i++) {
980 fw->ipv6.src = saddrs[i];
981 for (j = 0; j < ndaddrs; j++) {
982 fw->ipv6.dst = daddrs[j];
983 if (verbose)
984 print_firewall_line(fw, handle);
985 ret &= ip6tc_delete_entry(chain, fw, mask, handle);
988 free(mask);
990 return ret;
994 for_each_chain(int (*fn)(const ip6t_chainlabel, int, struct ip6tc_handle *),
995 int verbose, int builtinstoo, struct ip6tc_handle *handle)
997 int ret = 1;
998 const char *chain;
999 char *chains;
1000 unsigned int i, chaincount = 0;
1002 chain = ip6tc_first_chain(handle);
1003 while (chain) {
1004 chaincount++;
1005 chain = ip6tc_next_chain(handle);
1008 chains = fw_malloc(sizeof(ip6t_chainlabel) * chaincount);
1009 i = 0;
1010 chain = ip6tc_first_chain(handle);
1011 while (chain) {
1012 strcpy(chains + i*sizeof(ip6t_chainlabel), chain);
1013 i++;
1014 chain = ip6tc_next_chain(handle);
1017 for (i = 0; i < chaincount; i++) {
1018 if (!builtinstoo
1019 && ip6tc_builtin(chains + i*sizeof(ip6t_chainlabel),
1020 handle) == 1)
1021 continue;
1022 ret &= fn(chains + i*sizeof(ip6t_chainlabel), verbose, handle);
1025 free(chains);
1026 return ret;
1030 flush_entries(const ip6t_chainlabel chain, int verbose,
1031 struct ip6tc_handle *handle)
1033 if (!chain)
1034 return for_each_chain(flush_entries, verbose, 1, handle);
1036 if (verbose)
1037 fprintf(stdout, "Flushing chain `%s'\n", chain);
1038 return ip6tc_flush_entries(chain, handle);
1041 static int
1042 zero_entries(const ip6t_chainlabel chain, int verbose,
1043 struct ip6tc_handle *handle)
1045 if (!chain)
1046 return for_each_chain(zero_entries, verbose, 1, handle);
1048 if (verbose)
1049 fprintf(stdout, "Zeroing chain `%s'\n", chain);
1050 return ip6tc_zero_entries(chain, handle);
1054 delete_chain(const ip6t_chainlabel chain, int verbose,
1055 struct ip6tc_handle *handle)
1057 if (!chain)
1058 return for_each_chain(delete_chain, verbose, 0, handle);
1060 if (verbose)
1061 fprintf(stdout, "Deleting chain `%s'\n", chain);
1062 return ip6tc_delete_chain(chain, handle);
1065 static int
1066 list_entries(const ip6t_chainlabel chain, int rulenum, int verbose, int numeric,
1067 int expanded, int linenumbers, struct ip6tc_handle *handle)
1069 int found = 0;
1070 unsigned int format;
1071 const char *this;
1073 format = FMT_OPTIONS;
1074 if (!verbose)
1075 format |= FMT_NOCOUNTS;
1076 else
1077 format |= FMT_VIA;
1079 if (numeric)
1080 format |= FMT_NUMERIC;
1082 if (!expanded)
1083 format |= FMT_KILOMEGAGIGA;
1085 if (linenumbers)
1086 format |= FMT_LINENUMBERS;
1088 for (this = ip6tc_first_chain(handle);
1089 this;
1090 this = ip6tc_next_chain(handle)) {
1091 const struct ip6t_entry *i;
1092 unsigned int num;
1094 if (chain && strcmp(chain, this) != 0)
1095 continue;
1097 if (found) printf("\n");
1099 if (!rulenum)
1100 print_header(format, this, handle);
1101 i = ip6tc_first_rule(this, handle);
1103 num = 0;
1104 while (i) {
1105 num++;
1106 if (!rulenum || num == rulenum)
1107 print_firewall(i,
1108 ip6tc_get_target(i, handle),
1109 num,
1110 format,
1111 handle);
1112 i = ip6tc_next_rule(i, handle);
1114 found = 1;
1117 errno = ENOENT;
1118 return found;
1121 /* This assumes that mask is contiguous, and byte-bounded. */
1122 static void
1123 print_iface(char letter, const char *iface, const unsigned char *mask,
1124 int invert)
1126 unsigned int i;
1128 if (mask[0] == 0)
1129 return;
1131 printf("-%c %s", letter, invert ? "! " : "");
1133 for (i = 0; i < IFNAMSIZ; i++) {
1134 if (mask[i] != 0) {
1135 if (iface[i] != '\0')
1136 printf("%c", iface[i]);
1137 } else {
1138 /* we can access iface[i-1] here, because
1139 * a few lines above we make sure that mask[0] != 0 */
1140 if (iface[i-1] != '\0')
1141 printf("+");
1142 break;
1146 printf(" ");
1149 /* The ip6tables looks up the /etc/protocols. */
1150 static void print_proto(u_int16_t proto, int invert)
1152 if (proto) {
1153 unsigned int i;
1154 const char *invertstr = invert ? "! " : "";
1156 struct protoent *pent = getprotobynumber(proto);
1157 if (pent) {
1158 printf("-p %s%s ",
1159 invertstr, pent->p_name);
1160 return;
1163 for (i = 0; i < sizeof(chain_protos)/sizeof(struct pprot); i++)
1164 if (chain_protos[i].num == proto) {
1165 printf("-p %s%s ",
1166 invertstr, chain_protos[i].name);
1167 return;
1170 printf("-p %s%u ", invertstr, proto);
1174 static int print_match_save(const struct ip6t_entry_match *e,
1175 const struct ip6t_ip6 *ip)
1177 struct xtables_match *match
1178 = find_match(e->u.user.name, TRY_LOAD, NULL);
1180 if (match) {
1181 printf("-m %s ", e->u.user.name);
1183 /* some matches don't provide a save function */
1184 if (match->save)
1185 match->save(ip, e);
1186 } else {
1187 if (e->u.match_size) {
1188 fprintf(stderr,
1189 "Can't find library for match `%s'\n",
1190 e->u.user.name);
1191 exit(1);
1194 return 0;
1197 /* print a given ip including mask if neccessary */
1198 static void print_ip(char *prefix, const struct in6_addr *ip, const struct in6_addr *mask, int invert)
1200 char buf[51];
1201 int l = ipv6_prefix_length(mask);
1203 if (l == 0 && !invert)
1204 return;
1206 printf("%s %s%s",
1207 prefix,
1208 invert ? "! " : "",
1209 inet_ntop(AF_INET6, ip, buf, sizeof buf));
1211 if (l == -1)
1212 printf("/%s ", inet_ntop(AF_INET6, mask, buf, sizeof buf));
1213 else
1214 printf("/%d ", l);
1217 /* We want this to be readable, so only print out neccessary fields.
1218 * Because that's the kind of world I want to live in. */
1219 void print_rule(const struct ip6t_entry *e,
1220 struct ip6tc_handle *h, const char *chain, int counters)
1222 struct ip6t_entry_target *t;
1223 const char *target_name;
1225 /* print counters for iptables-save */
1226 if (counters > 0)
1227 printf("[%llu:%llu] ", (unsigned long long)e->counters.pcnt, (unsigned long long)e->counters.bcnt);
1229 /* print chain name */
1230 printf("-A %s ", chain);
1232 /* Print IP part. */
1233 print_ip("-s", &(e->ipv6.src), &(e->ipv6.smsk),
1234 e->ipv6.invflags & IP6T_INV_SRCIP);
1236 print_ip("-d", &(e->ipv6.dst), &(e->ipv6.dmsk),
1237 e->ipv6.invflags & IP6T_INV_DSTIP);
1239 print_iface('i', e->ipv6.iniface, e->ipv6.iniface_mask,
1240 e->ipv6.invflags & IP6T_INV_VIA_IN);
1242 print_iface('o', e->ipv6.outiface, e->ipv6.outiface_mask,
1243 e->ipv6.invflags & IP6T_INV_VIA_OUT);
1245 print_proto(e->ipv6.proto, e->ipv6.invflags & IP6T_INV_PROTO);
1247 #if 0
1248 /* not definied in ipv6
1249 * FIXME: linux/netfilter_ipv6/ip6_tables: IP6T_INV_FRAG why definied? */
1250 if (e->ipv6.flags & IPT_F_FRAG)
1251 printf("%s-f ",
1252 e->ipv6.invflags & IP6T_INV_FRAG ? "! " : "");
1253 #endif
1255 if (e->ipv6.flags & IP6T_F_TOS)
1256 printf("%s-? %d ",
1257 e->ipv6.invflags & IP6T_INV_TOS ? "! " : "",
1258 e->ipv6.tos);
1260 /* Print matchinfo part */
1261 if (e->target_offset) {
1262 IP6T_MATCH_ITERATE(e, print_match_save, &e->ipv6);
1265 /* print counters for iptables -R */
1266 if (counters < 0)
1267 printf("-c %llu %llu ", (unsigned long long)e->counters.pcnt, (unsigned long long)e->counters.bcnt);
1269 /* Print target name */
1270 target_name = ip6tc_get_target(e, h);
1271 if (target_name && (*target_name != '\0'))
1272 #ifdef IP6T_F_GOTO
1273 printf("-%c %s ", e->ipv6.flags & IP6T_F_GOTO ? 'g' : 'j', target_name);
1274 #else
1275 printf("-j %s ", target_name);
1276 #endif
1278 /* Print targinfo part */
1279 t = ip6t_get_target((struct ip6t_entry *)e);
1280 if (t->u.user.name[0]) {
1281 struct xtables_target *target
1282 = find_target(t->u.user.name, TRY_LOAD);
1284 if (!target) {
1285 fprintf(stderr, "Can't find library for target `%s'\n",
1286 t->u.user.name);
1287 exit(1);
1290 if (target->save)
1291 target->save(&e->ipv6, t);
1292 else {
1293 /* If the target size is greater than ip6t_entry_target
1294 * there is something to be saved, we just don't know
1295 * how to print it */
1296 if (t->u.target_size !=
1297 sizeof(struct ip6t_entry_target)) {
1298 fprintf(stderr, "Target `%s' is missing "
1299 "save function\n",
1300 t->u.user.name);
1301 exit(1);
1305 printf("\n");
1308 static int
1309 list_rules(const ip6t_chainlabel chain, int rulenum, int counters,
1310 struct ip6tc_handle *handle)
1312 const char *this = NULL;
1313 int found = 0;
1315 if (counters)
1316 counters = -1; /* iptables -c format */
1318 /* Dump out chain names first,
1319 * thereby preventing dependency conflicts */
1320 if (!rulenum) for (this = ip6tc_first_chain(handle);
1321 this;
1322 this = ip6tc_next_chain(handle)) {
1323 if (chain && strcmp(this, chain) != 0)
1324 continue;
1326 if (ip6tc_builtin(this, handle)) {
1327 struct ip6t_counters count;
1328 printf("-P %s %s", this, ip6tc_get_policy(this, &count, handle));
1329 if (counters)
1330 printf(" -c %llu %llu", (unsigned long long)count.pcnt, (unsigned long long)count.bcnt);
1331 printf("\n");
1332 } else {
1333 printf("-N %s\n", this);
1337 for (this = ip6tc_first_chain(handle);
1338 this;
1339 this = ip6tc_next_chain(handle)) {
1340 const struct ip6t_entry *e;
1341 int num = 0;
1343 if (chain && strcmp(this, chain) != 0)
1344 continue;
1346 /* Dump out rules */
1347 e = ip6tc_first_rule(this, handle);
1348 while(e) {
1349 num++;
1350 if (!rulenum || num == rulenum)
1351 print_rule(e, handle, this, counters);
1352 e = ip6tc_next_rule(e, handle);
1354 found = 1;
1357 errno = ENOENT;
1358 return found;
1361 static struct ip6t_entry *
1362 generate_entry(const struct ip6t_entry *fw,
1363 struct ip6tables_rule_match *matches,
1364 struct ip6t_entry_target *target)
1366 unsigned int size;
1367 struct ip6tables_rule_match *matchp;
1368 struct ip6t_entry *e;
1370 size = sizeof(struct ip6t_entry);
1371 for (matchp = matches; matchp; matchp = matchp->next)
1372 size += matchp->match->m->u.match_size;
1374 e = fw_malloc(size + target->u.target_size);
1375 *e = *fw;
1376 e->target_offset = size;
1377 e->next_offset = size + target->u.target_size;
1379 size = 0;
1380 for (matchp = matches; matchp; matchp = matchp->next) {
1381 memcpy(e->elems + size, matchp->match->m, matchp->match->m->u.match_size);
1382 size += matchp->match->m->u.match_size;
1384 memcpy(e->elems + size, target, target->u.target_size);
1386 return e;
1389 static void clear_rule_matches(struct ip6tables_rule_match **matches)
1391 struct ip6tables_rule_match *matchp, *tmp;
1393 for (matchp = *matches; matchp;) {
1394 tmp = matchp->next;
1395 if (matchp->match->m) {
1396 free(matchp->match->m);
1397 matchp->match->m = NULL;
1399 if (matchp->match == matchp->match->next) {
1400 free(matchp->match);
1401 matchp->match = NULL;
1403 free(matchp);
1404 matchp = tmp;
1407 *matches = NULL;
1410 static void set_revision(char *name, u_int8_t revision)
1412 /* Old kernel sources don't have ".revision" field,
1413 but we stole a byte from name. */
1414 name[IP6T_FUNCTION_MAXNAMELEN - 2] = '\0';
1415 name[IP6T_FUNCTION_MAXNAMELEN - 1] = revision;
1418 int do_command6(int argc, char *argv[], char **table, struct ip6tc_handle **handle)
1420 struct ip6t_entry fw, *e = NULL;
1421 int invert = 0;
1422 unsigned int nsaddrs = 0, ndaddrs = 0;
1423 struct in6_addr *saddrs = NULL, *daddrs = NULL;
1425 int c, verbose = 0;
1426 unsigned i;
1427 const char *chain = NULL;
1428 const char *shostnetworkmask = NULL, *dhostnetworkmask = NULL;
1429 const char *policy = NULL, *newname = NULL;
1430 unsigned int rulenum = 0, options = 0, command = 0;
1431 const char *pcnt = NULL, *bcnt = NULL;
1432 int ret = 1;
1433 struct xtables_match *m;
1434 struct ip6tables_rule_match *matches = NULL;
1435 struct ip6tables_rule_match *matchp;
1436 struct xtables_target *target = NULL;
1437 struct xtables_target *t;
1438 const char *jumpto = "";
1439 char *protocol = NULL;
1440 int proto_used = 0;
1441 unsigned long long cnt;
1443 memset(&fw, 0, sizeof(fw));
1445 /* re-set optind to 0 in case do_command gets called
1446 * a second time */
1447 optind = 0;
1449 /* clear mflags in case do_command gets called a second time
1450 * (we clear the global list of all matches for security)*/
1451 for (m = xtables_matches; m; m = m->next)
1452 m->mflags = 0;
1454 for (t = xtables_targets; t; t = t->next) {
1455 t->tflags = 0;
1456 t->used = 0;
1459 /* Suppress error messages: we may add new options if we
1460 demand-load a protocol. */
1461 opterr = 0;
1463 while ((c = getopt_long(argc, argv,
1464 "-A:D:R:I:L::S::M:F::Z::N:X::E:P:Vh::o:p:s:d:j:i:bvnt:m:xc:g:",
1465 opts, NULL)) != -1) {
1466 switch (c) {
1468 * Command selection
1470 case 'A':
1471 add_command(&command, CMD_APPEND, CMD_NONE,
1472 invert);
1473 chain = optarg;
1474 break;
1476 case 'D':
1477 add_command(&command, CMD_DELETE, CMD_NONE,
1478 invert);
1479 chain = optarg;
1480 if (optind < argc && argv[optind][0] != '-'
1481 && argv[optind][0] != '!') {
1482 rulenum = parse_rulenumber(argv[optind++]);
1483 command = CMD_DELETE_NUM;
1485 break;
1487 case 'R':
1488 add_command(&command, CMD_REPLACE, CMD_NONE,
1489 invert);
1490 chain = optarg;
1491 if (optind < argc && argv[optind][0] != '-'
1492 && argv[optind][0] != '!')
1493 rulenum = parse_rulenumber(argv[optind++]);
1494 else
1495 exit_error(PARAMETER_PROBLEM,
1496 "-%c requires a rule number",
1497 cmd2char(CMD_REPLACE));
1498 break;
1500 case 'I':
1501 add_command(&command, CMD_INSERT, CMD_NONE,
1502 invert);
1503 chain = optarg;
1504 if (optind < argc && argv[optind][0] != '-'
1505 && argv[optind][0] != '!')
1506 rulenum = parse_rulenumber(argv[optind++]);
1507 else rulenum = 1;
1508 break;
1510 case 'L':
1511 add_command(&command, CMD_LIST, CMD_ZERO,
1512 invert);
1513 if (optarg) chain = optarg;
1514 else if (optind < argc && argv[optind][0] != '-'
1515 && argv[optind][0] != '!')
1516 chain = argv[optind++];
1517 if (optind < argc && argv[optind][0] != '-'
1518 && argv[optind][0] != '!')
1519 rulenum = parse_rulenumber(argv[optind++]);
1520 break;
1522 case 'S':
1523 add_command(&command, CMD_LIST_RULES, CMD_ZERO,
1524 invert);
1525 if (optarg) chain = optarg;
1526 else if (optind < argc && argv[optind][0] != '-'
1527 && argv[optind][0] != '!')
1528 chain = argv[optind++];
1529 if (optind < argc && argv[optind][0] != '-'
1530 && argv[optind][0] != '!')
1531 rulenum = parse_rulenumber(argv[optind++]);
1532 break;
1534 case 'F':
1535 add_command(&command, CMD_FLUSH, CMD_NONE,
1536 invert);
1537 if (optarg) chain = optarg;
1538 else if (optind < argc && argv[optind][0] != '-'
1539 && argv[optind][0] != '!')
1540 chain = argv[optind++];
1541 break;
1543 case 'Z':
1544 add_command(&command, CMD_ZERO, CMD_LIST|CMD_LIST_RULES,
1545 invert);
1546 if (optarg) chain = optarg;
1547 else if (optind < argc && argv[optind][0] != '-'
1548 && argv[optind][0] != '!')
1549 chain = argv[optind++];
1550 break;
1552 case 'N':
1553 if (optarg && (*optarg == '-' || *optarg == '!'))
1554 exit_error(PARAMETER_PROBLEM,
1555 "chain name not allowed to start "
1556 "with `%c'\n", *optarg);
1557 if (find_target(optarg, TRY_LOAD))
1558 exit_error(PARAMETER_PROBLEM,
1559 "chain name may not clash "
1560 "with target name\n");
1561 add_command(&command, CMD_NEW_CHAIN, CMD_NONE,
1562 invert);
1563 chain = optarg;
1564 break;
1566 case 'X':
1567 add_command(&command, CMD_DELETE_CHAIN, CMD_NONE,
1568 invert);
1569 if (optarg) chain = optarg;
1570 else if (optind < argc && argv[optind][0] != '-'
1571 && argv[optind][0] != '!')
1572 chain = argv[optind++];
1573 break;
1575 case 'E':
1576 add_command(&command, CMD_RENAME_CHAIN, CMD_NONE,
1577 invert);
1578 chain = optarg;
1579 if (optind < argc && argv[optind][0] != '-'
1580 && argv[optind][0] != '!')
1581 newname = argv[optind++];
1582 else
1583 exit_error(PARAMETER_PROBLEM,
1584 "-%c requires old-chain-name and "
1585 "new-chain-name",
1586 cmd2char(CMD_RENAME_CHAIN));
1587 break;
1589 case 'P':
1590 add_command(&command, CMD_SET_POLICY, CMD_NONE,
1591 invert);
1592 chain = optarg;
1593 if (optind < argc && argv[optind][0] != '-'
1594 && argv[optind][0] != '!')
1595 policy = argv[optind++];
1596 else
1597 exit_error(PARAMETER_PROBLEM,
1598 "-%c requires a chain and a policy",
1599 cmd2char(CMD_SET_POLICY));
1600 break;
1602 case 'h':
1603 if (!optarg)
1604 optarg = argv[optind];
1606 /* ip6tables -p icmp -h */
1607 if (!matches && protocol)
1608 find_match(protocol, TRY_LOAD, &matches);
1610 exit_printhelp(matches);
1613 * Option selection
1615 case 'p':
1616 check_inverse(optarg, &invert, &optind, argc);
1617 set_option(&options, OPT_PROTOCOL, &fw.ipv6.invflags,
1618 invert);
1620 /* Canonicalize into lower case */
1621 for (protocol = argv[optind-1]; *protocol; protocol++)
1622 *protocol = tolower(*protocol);
1624 protocol = argv[optind-1];
1625 fw.ipv6.proto = parse_protocol(protocol);
1626 fw.ipv6.flags |= IP6T_F_PROTO;
1628 if (fw.ipv6.proto == 0
1629 && (fw.ipv6.invflags & IP6T_INV_PROTO))
1630 exit_error(PARAMETER_PROBLEM,
1631 "rule would never match protocol");
1633 if (is_exthdr(fw.ipv6.proto)
1634 && (fw.ipv6.invflags & IP6T_INV_PROTO) == 0)
1635 fprintf(stderr,
1636 "Warning: never matched protocol: %s. "
1637 "use extension match instead.\n",
1638 protocol);
1639 break;
1641 case 's':
1642 check_inverse(optarg, &invert, &optind, argc);
1643 set_option(&options, OPT_SOURCE, &fw.ipv6.invflags,
1644 invert);
1645 shostnetworkmask = argv[optind-1];
1646 break;
1648 case 'd':
1649 check_inverse(optarg, &invert, &optind, argc);
1650 set_option(&options, OPT_DESTINATION, &fw.ipv6.invflags,
1651 invert);
1652 dhostnetworkmask = argv[optind-1];
1653 break;
1655 #ifdef IP6T_F_GOTO
1656 case 'g':
1657 set_option(&options, OPT_JUMP, &fw.ipv6.invflags,
1658 invert);
1659 fw.ipv6.flags |= IP6T_F_GOTO;
1660 jumpto = parse_target(optarg);
1661 break;
1662 #endif
1664 case 'j':
1665 set_option(&options, OPT_JUMP, &fw.ipv6.invflags,
1666 invert);
1667 jumpto = parse_target(optarg);
1668 /* TRY_LOAD (may be chain name) */
1669 target = find_target(jumpto, TRY_LOAD);
1671 if (target) {
1672 size_t size;
1674 size = IP6T_ALIGN(sizeof(struct ip6t_entry_target))
1675 + target->size;
1677 target->t = fw_calloc(1, size);
1678 target->t->u.target_size = size;
1679 strcpy(target->t->u.user.name, jumpto);
1680 set_revision(target->t->u.user.name,
1681 target->revision);
1682 if (target->init != NULL)
1683 target->init(target->t);
1684 opts = merge_options(opts,
1685 target->extra_opts,
1686 &target->option_offset);
1687 if (opts == NULL)
1688 exit_error(OTHER_PROBLEM,
1689 "can't alloc memory!");
1691 break;
1694 case 'i':
1695 check_inverse(optarg, &invert, &optind, argc);
1696 set_option(&options, OPT_VIANAMEIN, &fw.ipv6.invflags,
1697 invert);
1698 parse_interface(argv[optind-1],
1699 fw.ipv6.iniface,
1700 fw.ipv6.iniface_mask);
1701 break;
1703 case 'o':
1704 check_inverse(optarg, &invert, &optind, argc);
1705 set_option(&options, OPT_VIANAMEOUT, &fw.ipv6.invflags,
1706 invert);
1707 parse_interface(argv[optind-1],
1708 fw.ipv6.outiface,
1709 fw.ipv6.outiface_mask);
1710 break;
1712 case 'v':
1713 if (!verbose)
1714 set_option(&options, OPT_VERBOSE,
1715 &fw.ipv6.invflags, invert);
1716 verbose++;
1717 break;
1719 case 'm': {
1720 size_t size;
1722 if (invert)
1723 exit_error(PARAMETER_PROBLEM,
1724 "unexpected ! flag before --match");
1726 m = find_match(optarg, LOAD_MUST_SUCCEED, &matches);
1727 size = IP6T_ALIGN(sizeof(struct ip6t_entry_match))
1728 + m->size;
1729 m->m = fw_calloc(1, size);
1730 m->m->u.match_size = size;
1731 strcpy(m->m->u.user.name, m->name);
1732 set_revision(m->m->u.user.name, m->revision);
1733 if (m->init != NULL)
1734 m->init(m->m);
1735 if (m != m->next)
1736 /* Merge options for non-cloned matches */
1737 opts = merge_options(opts, m->extra_opts, &m->option_offset);
1739 break;
1741 case 'n':
1742 set_option(&options, OPT_NUMERIC, &fw.ipv6.invflags,
1743 invert);
1744 break;
1746 case 't':
1747 if (invert)
1748 exit_error(PARAMETER_PROBLEM,
1749 "unexpected ! flag before --table");
1750 *table = optarg;
1751 break;
1753 case 'x':
1754 set_option(&options, OPT_EXPANDED, &fw.ipv6.invflags,
1755 invert);
1756 break;
1758 case 'V':
1759 if (invert)
1760 printf("Not %s ;-)\n", program_version);
1761 else
1762 printf("%s v%s\n",
1763 program_name, program_version);
1764 exit(0);
1766 case '0':
1767 set_option(&options, OPT_LINENUMBERS, &fw.ipv6.invflags,
1768 invert);
1769 break;
1771 case 'M':
1772 modprobe_program = optarg;
1773 break;
1775 case 'c':
1777 set_option(&options, OPT_COUNTERS, &fw.ipv6.invflags,
1778 invert);
1779 pcnt = optarg;
1780 bcnt = strchr(pcnt + 1, ',');
1781 if (bcnt)
1782 bcnt++;
1783 if (!bcnt && optind < argc && argv[optind][0] != '-'
1784 && argv[optind][0] != '!')
1785 bcnt = argv[optind++];
1786 if (!bcnt)
1787 exit_error(PARAMETER_PROBLEM,
1788 "-%c requires packet and byte counter",
1789 opt2char(OPT_COUNTERS));
1791 if (sscanf(pcnt, "%llu", &cnt) != 1)
1792 exit_error(PARAMETER_PROBLEM,
1793 "-%c packet counter not numeric",
1794 opt2char(OPT_COUNTERS));
1795 fw.counters.pcnt = cnt;
1797 if (sscanf(bcnt, "%llu", &cnt) != 1)
1798 exit_error(PARAMETER_PROBLEM,
1799 "-%c byte counter not numeric",
1800 opt2char(OPT_COUNTERS));
1801 fw.counters.bcnt = cnt;
1802 break;
1804 case 1: /* non option */
1805 if (optarg[0] == '!' && optarg[1] == '\0') {
1806 if (invert)
1807 exit_error(PARAMETER_PROBLEM,
1808 "multiple consecutive ! not"
1809 " allowed");
1810 invert = TRUE;
1811 optarg[0] = '\0';
1812 continue;
1814 fprintf(stderr, "Bad argument `%s'\n", optarg);
1815 exit_tryhelp(2);
1817 default:
1818 if (!target
1819 || !(target->parse(c - target->option_offset,
1820 argv, invert,
1821 &target->tflags,
1822 &fw, &target->t))) {
1823 for (matchp = matches; matchp; matchp = matchp->next) {
1824 if (matchp->completed)
1825 continue;
1826 if (matchp->match->parse(c - matchp->match->option_offset,
1827 argv, invert,
1828 &matchp->match->mflags,
1829 &fw,
1830 &matchp->match->m))
1831 break;
1833 m = matchp ? matchp->match : NULL;
1835 /* If you listen carefully, you can
1836 actually hear this code suck. */
1838 /* some explanations (after four different bugs
1839 * in 3 different releases): If we encounter a
1840 * parameter, that has not been parsed yet,
1841 * it's not an option of an explicitly loaded
1842 * match or a target. However, we support
1843 * implicit loading of the protocol match
1844 * extension. '-p tcp' means 'l4 proto 6' and
1845 * at the same time 'load tcp protocol match on
1846 * demand if we specify --dport'.
1848 * To make this work, we need to make sure:
1849 * - the parameter has not been parsed by
1850 * a match (m above)
1851 * - a protocol has been specified
1852 * - the protocol extension has not been
1853 * loaded yet, or is loaded and unused
1854 * [think of ip6tables-restore!]
1855 * - the protocol extension can be successively
1856 * loaded
1858 if (m == NULL
1859 && protocol
1860 && (!find_proto(protocol, DONT_LOAD,
1861 options&OPT_NUMERIC, NULL)
1862 || (find_proto(protocol, DONT_LOAD,
1863 options&OPT_NUMERIC, NULL)
1864 && (proto_used == 0))
1866 && (m = find_proto(protocol, TRY_LOAD,
1867 options&OPT_NUMERIC, &matches))) {
1868 /* Try loading protocol */
1869 size_t size;
1871 proto_used = 1;
1873 size = IP6T_ALIGN(sizeof(struct ip6t_entry_match))
1874 + m->size;
1876 m->m = fw_calloc(1, size);
1877 m->m->u.match_size = size;
1878 strcpy(m->m->u.user.name, m->name);
1879 set_revision(m->m->u.user.name,
1880 m->revision);
1881 if (m->init != NULL)
1882 m->init(m->m);
1884 opts = merge_options(opts,
1885 m->extra_opts, &m->option_offset);
1887 optind--;
1888 continue;
1891 if (!m) {
1892 if (c == '?') {
1893 if (optopt) {
1894 exit_error(
1895 PARAMETER_PROBLEM,
1896 "option `%s' "
1897 "requires an "
1898 "argument",
1899 argv[optind-1]);
1900 } else {
1901 exit_error(
1902 PARAMETER_PROBLEM,
1903 "unknown option "
1904 "`%s'",
1905 argv[optind-1]);
1908 exit_error(PARAMETER_PROBLEM,
1909 "Unknown arg `%s'", optarg);
1913 invert = FALSE;
1916 for (matchp = matches; matchp; matchp = matchp->next)
1917 if (matchp->match->final_check != NULL)
1918 matchp->match->final_check(matchp->match->mflags);
1920 if (target != NULL && target->final_check != NULL)
1921 target->final_check(target->tflags);
1923 /* Fix me: must put inverse options checking here --MN */
1925 if (optind < argc)
1926 exit_error(PARAMETER_PROBLEM,
1927 "unknown arguments found on commandline");
1928 if (!command)
1929 exit_error(PARAMETER_PROBLEM, "no command specified");
1930 if (invert)
1931 exit_error(PARAMETER_PROBLEM,
1932 "nothing appropriate following !");
1934 if (command & (CMD_REPLACE | CMD_INSERT | CMD_DELETE | CMD_APPEND)) {
1935 if (!(options & OPT_DESTINATION))
1936 dhostnetworkmask = "::0/0";
1937 if (!(options & OPT_SOURCE))
1938 shostnetworkmask = "::0/0";
1941 if (shostnetworkmask)
1942 ip6parse_hostnetworkmask(shostnetworkmask, &saddrs,
1943 &fw.ipv6.smsk, &nsaddrs);
1945 if (dhostnetworkmask)
1946 ip6parse_hostnetworkmask(dhostnetworkmask, &daddrs,
1947 &fw.ipv6.dmsk, &ndaddrs);
1949 if ((nsaddrs > 1 || ndaddrs > 1) &&
1950 (fw.ipv6.invflags & (IP6T_INV_SRCIP | IP6T_INV_DSTIP)))
1951 exit_error(PARAMETER_PROBLEM, "! not allowed with multiple"
1952 " source or destination IP addresses");
1954 if (command == CMD_REPLACE && (nsaddrs != 1 || ndaddrs != 1))
1955 exit_error(PARAMETER_PROBLEM, "Replacement rule does not "
1956 "specify a unique address");
1958 generic_opt_check(command, options);
1960 if (chain && strlen(chain) > IP6T_FUNCTION_MAXNAMELEN)
1961 exit_error(PARAMETER_PROBLEM,
1962 "chain name `%s' too long (must be under %i chars)",
1963 chain, IP6T_FUNCTION_MAXNAMELEN);
1965 /* only allocate handle if we weren't called with a handle */
1966 if (!*handle)
1967 *handle = ip6tc_init(*table);
1969 /* try to insmod the module if iptc_init failed */
1970 if (!*handle && load_xtables_ko(modprobe_program, 0) != -1)
1971 *handle = ip6tc_init(*table);
1973 if (!*handle)
1974 exit_error(VERSION_PROBLEM,
1975 "can't initialize ip6tables table `%s': %s",
1976 *table, ip6tc_strerror(errno));
1978 if (command == CMD_APPEND
1979 || command == CMD_DELETE
1980 || command == CMD_INSERT
1981 || command == CMD_REPLACE) {
1982 if (strcmp(chain, "PREROUTING") == 0
1983 || strcmp(chain, "INPUT") == 0) {
1984 /* -o not valid with incoming packets. */
1985 if (options & OPT_VIANAMEOUT)
1986 exit_error(PARAMETER_PROBLEM,
1987 "Can't use -%c with %s\n",
1988 opt2char(OPT_VIANAMEOUT),
1989 chain);
1992 if (strcmp(chain, "POSTROUTING") == 0
1993 || strcmp(chain, "OUTPUT") == 0) {
1994 /* -i not valid with outgoing packets */
1995 if (options & OPT_VIANAMEIN)
1996 exit_error(PARAMETER_PROBLEM,
1997 "Can't use -%c with %s\n",
1998 opt2char(OPT_VIANAMEIN),
1999 chain);
2002 if (target && ip6tc_is_chain(jumpto, *handle)) {
2003 fprintf(stderr,
2004 "Warning: using chain %s, not extension\n",
2005 jumpto);
2007 if (target->t)
2008 free(target->t);
2010 target = NULL;
2013 /* If they didn't specify a target, or it's a chain
2014 name, use standard. */
2015 if (!target
2016 && (strlen(jumpto) == 0
2017 || ip6tc_is_chain(jumpto, *handle))) {
2018 size_t size;
2020 target = find_target(IP6T_STANDARD_TARGET,
2021 LOAD_MUST_SUCCEED);
2023 size = sizeof(struct ip6t_entry_target)
2024 + target->size;
2025 target->t = fw_calloc(1, size);
2026 target->t->u.target_size = size;
2027 strcpy(target->t->u.user.name, jumpto);
2028 if (target->init != NULL)
2029 target->init(target->t);
2032 if (!target) {
2033 /* it is no chain, and we can't load a plugin.
2034 * We cannot know if the plugin is corrupt, non
2035 * existant OR if the user just misspelled a
2036 * chain. */
2037 #ifdef IP6T_F_GOTO
2038 if (fw.ipv6.flags & IP6T_F_GOTO)
2039 exit_error(PARAMETER_PROBLEM,
2040 "goto '%s' is not a chain\n", jumpto);
2041 #endif
2042 find_target(jumpto, LOAD_MUST_SUCCEED);
2043 } else {
2044 e = generate_entry(&fw, matches, target->t);
2045 free(target->t);
2049 switch (command) {
2050 case CMD_APPEND:
2051 ret = append_entry(chain, e,
2052 nsaddrs, saddrs, ndaddrs, daddrs,
2053 options&OPT_VERBOSE,
2054 *handle);
2055 break;
2056 case CMD_DELETE:
2057 ret = delete_entry(chain, e,
2058 nsaddrs, saddrs, ndaddrs, daddrs,
2059 options&OPT_VERBOSE,
2060 *handle, matches);
2061 break;
2062 case CMD_DELETE_NUM:
2063 ret = ip6tc_delete_num_entry(chain, rulenum - 1, *handle);
2064 break;
2065 case CMD_REPLACE:
2066 ret = replace_entry(chain, e, rulenum - 1,
2067 saddrs, daddrs, options&OPT_VERBOSE,
2068 *handle);
2069 break;
2070 case CMD_INSERT:
2071 ret = insert_entry(chain, e, rulenum - 1,
2072 nsaddrs, saddrs, ndaddrs, daddrs,
2073 options&OPT_VERBOSE,
2074 *handle);
2075 break;
2076 case CMD_FLUSH:
2077 ret = flush_entries(chain, options&OPT_VERBOSE, *handle);
2078 break;
2079 case CMD_ZERO:
2080 ret = zero_entries(chain, options&OPT_VERBOSE, *handle);
2081 break;
2082 case CMD_LIST:
2083 case CMD_LIST|CMD_ZERO:
2084 ret = list_entries(chain,
2085 rulenum,
2086 options&OPT_VERBOSE,
2087 options&OPT_NUMERIC,
2088 options&OPT_EXPANDED,
2089 options&OPT_LINENUMBERS,
2090 *handle);
2091 if (ret && (command & CMD_ZERO))
2092 ret = zero_entries(chain,
2093 options&OPT_VERBOSE, *handle);
2094 break;
2095 case CMD_LIST_RULES:
2096 case CMD_LIST_RULES|CMD_ZERO:
2097 ret = list_rules(chain,
2098 rulenum,
2099 options&OPT_VERBOSE,
2100 *handle);
2101 if (ret && (command & CMD_ZERO))
2102 ret = zero_entries(chain,
2103 options&OPT_VERBOSE, *handle);
2104 break;
2105 case CMD_NEW_CHAIN:
2106 ret = ip6tc_create_chain(chain, *handle);
2107 break;
2108 case CMD_DELETE_CHAIN:
2109 ret = delete_chain(chain, options&OPT_VERBOSE, *handle);
2110 break;
2111 case CMD_RENAME_CHAIN:
2112 ret = ip6tc_rename_chain(chain, newname, *handle);
2113 break;
2114 case CMD_SET_POLICY:
2115 ret = ip6tc_set_policy(chain, policy, options&OPT_COUNTERS ? &fw.counters : NULL, *handle);
2116 break;
2117 default:
2118 /* We should never reach this... */
2119 exit_tryhelp(2);
2122 if (verbose > 1)
2123 dump_entries6(*handle);
2125 clear_rule_matches(&matches);
2127 if (e != NULL) {
2128 free(e);
2129 e = NULL;
2132 for (i = 0; i < nsaddrs; i++)
2133 free(&saddrs[i]);
2135 for (i = 0; i < ndaddrs; i++)
2136 free(&daddrs[i]);
2138 free_opts(1);
2140 return ret;