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 #include "config.h"
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 <stdbool.h>
37 #include <limits.h>
38 #include <ip6tables.h>
39 #include <xtables.h>
40 #include <arpa/inet.h>
41 #include <unistd.h>
42 #include <fcntl.h>
43 #include <sys/types.h>
44 #include <sys/socket.h>
45 #include "ip6tables-multi.h"
46 #include "xshared.h"
47 
48 static const char unsupported_rev[] = " [unsupported revision]";
49 
50 static struct option original_opts[] = {
51 	{.name = "append",        .has_arg = 1, .val = 'A'},
52 	{.name = "delete",        .has_arg = 1, .val = 'D'},
53 	{.name = "check" ,        .has_arg = 1, .val = 'C'},
54 	{.name = "insert",        .has_arg = 1, .val = 'I'},
55 	{.name = "replace",       .has_arg = 1, .val = 'R'},
56 	{.name = "list",          .has_arg = 2, .val = 'L'},
57 	{.name = "list-rules",    .has_arg = 2, .val = 'S'},
58 	{.name = "flush",         .has_arg = 2, .val = 'F'},
59 	{.name = "zero",          .has_arg = 2, .val = 'Z'},
60 	{.name = "new-chain",     .has_arg = 1, .val = 'N'},
61 	{.name = "delete-chain",  .has_arg = 2, .val = 'X'},
62 	{.name = "rename-chain",  .has_arg = 1, .val = 'E'},
63 	{.name = "policy",        .has_arg = 1, .val = 'P'},
64 	{.name = "source",        .has_arg = 1, .val = 's'},
65 	{.name = "destination",   .has_arg = 1, .val = 'd'},
66 	{.name = "src",           .has_arg = 1, .val = 's'}, /* synonym */
67 	{.name = "dst",           .has_arg = 1, .val = 'd'}, /* synonym */
68 	{.name = "protocol",      .has_arg = 1, .val = 'p'},
69 	{.name = "in-interface",  .has_arg = 1, .val = 'i'},
70 	{.name = "jump",          .has_arg = 1, .val = 'j'},
71 	{.name = "table",         .has_arg = 1, .val = 't'},
72 	{.name = "match",         .has_arg = 1, .val = 'm'},
73 	{.name = "numeric",       .has_arg = 0, .val = 'n'},
74 	{.name = "out-interface", .has_arg = 1, .val = 'o'},
75 	{.name = "verbose",       .has_arg = 0, .val = 'v'},
76 	{.name = "wait",          .has_arg = 2, .val = 'w'},
77 	{.name = "wait-interval", .has_arg = 2, .val = 'W'},
78 	{.name = "exact",         .has_arg = 0, .val = 'x'},
79 	{.name = "version",       .has_arg = 0, .val = 'V'},
80 	{.name = "help",          .has_arg = 2, .val = 'h'},
81 	{.name = "line-numbers",  .has_arg = 0, .val = '0'},
82 	{.name = "modprobe",      .has_arg = 1, .val = 'M'},
83 	{.name = "set-counters",  .has_arg = 1, .val = 'c'},
84 	{.name = "goto",          .has_arg = 1, .val = 'g'},
85 	{.name = "ipv4",          .has_arg = 0, .val = '4'},
86 	{.name = "ipv6",          .has_arg = 0, .val = '6'},
87 	{NULL},
88 };
89 
90 void ip6tables_exit_error(enum xtables_exittype status, const char *msg, ...) __attribute__((noreturn, format(printf,2,3)));
91 struct xtables_globals ip6tables_globals = {
92 	.option_offset = 0,
93 	.program_version = PACKAGE_VERSION,
94 	.orig_opts = original_opts,
95 	.exit_err = ip6tables_exit_error,
96 	.compat_rev = xtables_compatible_revision,
97 };
98 
99 static const unsigned int inverse_for_options[NUMBER_OF_OPT] =
100 {
101 /* -n */ 0,
102 /* -s */ IP6T_INV_SRCIP,
103 /* -d */ IP6T_INV_DSTIP,
104 /* -p */ XT_INV_PROTO,
105 /* -j */ 0,
106 /* -v */ 0,
107 /* -x */ 0,
108 /* -i */ IP6T_INV_VIA_IN,
109 /* -o */ IP6T_INV_VIA_OUT,
110 /*--line*/ 0,
111 /* -c */ 0,
112 };
113 
114 #define opts ip6tables_globals.opts
115 #define prog_name ip6tables_globals.program_name
116 #define prog_vers ip6tables_globals.program_version
117 
118 static void __attribute__((noreturn))
exit_tryhelp(int status)119 exit_tryhelp(int status)
120 {
121 	if (line != -1)
122 		fprintf(stderr, "Error occurred at line: %d\n", line);
123 	fprintf(stderr, "Try `%s -h' or '%s --help' for more information.\n",
124 			prog_name, prog_name);
125 	xtables_free_opts(1);
126 	exit(status);
127 }
128 
129 static void
exit_printhelp(const struct xtables_rule_match * matches)130 exit_printhelp(const struct xtables_rule_match *matches)
131 {
132 	printf("%s v%s\n\n"
133 "Usage: %s -[ACD] chain rule-specification [options]\n"
134 "       %s -I chain [rulenum] rule-specification [options]\n"
135 "       %s -R chain rulenum rule-specification [options]\n"
136 "       %s -D chain rulenum [options]\n"
137 "       %s -[LS] [chain [rulenum]] [options]\n"
138 "       %s -[FZ] [chain] [options]\n"
139 "       %s -[NX] chain\n"
140 "       %s -E old-chain-name new-chain-name\n"
141 "       %s -P chain target [options]\n"
142 "       %s -h (print this help information)\n\n",
143 	       prog_name, prog_vers, prog_name, prog_name,
144 	       prog_name, prog_name, prog_name, prog_name,
145 	       prog_name, prog_name, prog_name, prog_name);
146 
147 	printf(
148 "Commands:\n"
149 "Either long or short options are allowed.\n"
150 "  --append  -A chain		Append to chain\n"
151 "  --check   -C chain		Check for the existence of a rule\n"
152 "  --delete  -D chain		Delete matching rule from chain\n"
153 "  --delete  -D chain rulenum\n"
154 "				Delete rule rulenum (1 = first) from chain\n"
155 "  --insert  -I chain [rulenum]\n"
156 "				Insert in chain as rulenum (default 1=first)\n"
157 "  --replace -R chain rulenum\n"
158 "				Replace rule rulenum (1 = first) in chain\n"
159 "  --list    -L [chain [rulenum]]\n"
160 "				List the rules in a chain or all chains\n"
161 "  --list-rules -S [chain [rulenum]]\n"
162 "				Print the rules in a chain or all chains\n"
163 "  --flush   -F [chain]		Delete all rules in  chain or all chains\n"
164 "  --zero    -Z [chain [rulenum]]\n"
165 "				Zero counters in chain or all chains\n"
166 "  --new     -N chain		Create a new user-defined chain\n"
167 "  --delete-chain\n"
168 "            -X [chain]		Delete a user-defined chain\n"
169 "  --policy  -P chain target\n"
170 "				Change policy on chain to target\n"
171 "  --rename-chain\n"
172 "            -E old-chain new-chain\n"
173 "				Change chain name, (moving any references)\n"
174 
175 "Options:\n"
176 "    --ipv4	-4		Error (line is ignored by ip6tables-restore)\n"
177 "    --ipv6	-6		Nothing (line is ignored by iptables-restore)\n"
178 "[!] --protocol	-p proto	protocol: by number or name, eg. `tcp'\n"
179 "[!] --source	-s address[/mask][,...]\n"
180 "				source specification\n"
181 "[!] --destination -d address[/mask][,...]\n"
182 "				destination specification\n"
183 "[!] --in-interface -i input name[+]\n"
184 "				network interface name ([+] for wildcard)\n"
185 "  --jump	-j target\n"
186 "				target for rule (may load target extension)\n"
187 #ifdef IP6T_F_GOTO
188 "  --goto	-g chain\n"
189 "				jump to chain with no return\n"
190 #endif
191 "  --match	-m match\n"
192 "				extended match (may load extension)\n"
193 "  --numeric	-n		numeric output of addresses and ports\n"
194 "[!] --out-interface -o output name[+]\n"
195 "				network interface name ([+] for wildcard)\n"
196 "  --table	-t table	table to manipulate (default: `filter')\n"
197 "  --verbose	-v		verbose mode\n"
198 "  --wait	-w [seconds]	maximum wait to acquire xtables lock before give up\n"
199 "  --wait-interval -W [usecs]	wait time to try to acquire xtables lock\n"
200 "				interval to wait for xtables lock\n"
201 "				default is 1 second\n"
202 "  --line-numbers		print line numbers when listing\n"
203 "  --exact	-x		expand numbers (display exact values)\n"
204 /*"[!] --fragment	-f		match second or further fragments only\n"*/
205 "  --modprobe=<command>		try to insert modules using this command\n"
206 "  --set-counters PKTS BYTES	set the counter during insert/append\n"
207 "[!] --version	-V		print package version.\n");
208 
209 	print_extension_helps(xtables_targets, matches);
210 	exit(0);
211 }
212 
213 void
ip6tables_exit_error(enum xtables_exittype status,const char * msg,...)214 ip6tables_exit_error(enum xtables_exittype status, const char *msg, ...)
215 {
216 	va_list args;
217 
218 	va_start(args, msg);
219 	fprintf(stderr, "%s v%s (legacy): ", prog_name, prog_vers);
220 	vfprintf(stderr, msg, args);
221 	va_end(args);
222 	fprintf(stderr, "\n");
223 	if (status == PARAMETER_PROBLEM)
224 		exit_tryhelp(status);
225 	if (status == VERSION_PROBLEM)
226 		fprintf(stderr,
227 			"Perhaps ip6tables or your kernel needs to be upgraded.\n");
228 	/* On error paths, make sure that we don't leak memory */
229 	xtables_free_opts(1);
230 	exit(status);
231 }
232 
233 /*
234  *	All functions starting with "parse" should succeed, otherwise
235  *	the program fails.
236  *	Most routines return pointers to static data that may change
237  *	between calls to the same or other routines with a few exceptions:
238  *	"host_to_addr", "parse_hostnetwork", and "parse_hostnetworkmask"
239  *	return global static data.
240 */
241 
242 /* These are invalid numbers as upper layer protocol */
is_exthdr(uint16_t proto)243 static int is_exthdr(uint16_t proto)
244 {
245 	return (proto == IPPROTO_ROUTING ||
246 		proto == IPPROTO_FRAGMENT ||
247 		proto == IPPROTO_AH ||
248 		proto == IPPROTO_DSTOPTS);
249 }
250 
251 static void
parse_chain(const char * chainname)252 parse_chain(const char *chainname)
253 {
254 	const char *ptr;
255 
256 	if (strlen(chainname) >= XT_EXTENSION_MAXNAMELEN)
257 		xtables_error(PARAMETER_PROBLEM,
258 			   "chain name `%s' too long (must be under %u chars)",
259 			   chainname, XT_EXTENSION_MAXNAMELEN);
260 
261 	if (*chainname == '-' || *chainname == '!')
262 		xtables_error(PARAMETER_PROBLEM,
263 			   "chain name not allowed to start "
264 			   "with `%c'\n", *chainname);
265 
266 	if (xtables_find_target(chainname, XTF_TRY_LOAD))
267 		xtables_error(PARAMETER_PROBLEM,
268 			   "chain name may not clash "
269 			   "with target name\n");
270 
271 	for (ptr = chainname; *ptr; ptr++)
272 		if (isspace(*ptr))
273 			xtables_error(PARAMETER_PROBLEM,
274 				   "Invalid chain name `%s'", chainname);
275 }
276 
277 static void
set_option(unsigned int * options,unsigned int option,uint8_t * invflg,int invert)278 set_option(unsigned int *options, unsigned int option, uint8_t *invflg,
279 	   int invert)
280 {
281 	if (*options & option)
282 		xtables_error(PARAMETER_PROBLEM, "multiple -%c flags not allowed",
283 			   opt2char(option));
284 	*options |= option;
285 
286 	if (invert) {
287 		unsigned int i;
288 		for (i = 0; 1 << i != option; i++);
289 
290 		if (!inverse_for_options[i])
291 			xtables_error(PARAMETER_PROBLEM,
292 				   "cannot have ! before -%c",
293 				   opt2char(option));
294 		*invflg |= inverse_for_options[i];
295 	}
296 }
297 
298 
299 static void
print_header(unsigned int format,const char * chain,struct xtc_handle * handle)300 print_header(unsigned int format, const char *chain, struct xtc_handle *handle)
301 {
302 	struct xt_counters counters;
303 	const char *pol = ip6tc_get_policy(chain, &counters, handle);
304 	printf("Chain %s", chain);
305 	if (pol) {
306 		printf(" (policy %s", pol);
307 		if (!(format & FMT_NOCOUNTS)) {
308 			fputc(' ', stdout);
309 			xtables_print_num(counters.pcnt, (format|FMT_NOTABLE));
310 			fputs("packets, ", stdout);
311 			xtables_print_num(counters.bcnt, (format|FMT_NOTABLE));
312 			fputs("bytes", stdout);
313 		}
314 		printf(")\n");
315 	} else {
316 		unsigned int refs;
317 		if (!ip6tc_get_references(&refs, chain, handle))
318 			printf(" (ERROR obtaining refs)\n");
319 		else
320 			printf(" (%u references)\n", refs);
321 	}
322 
323 	if (format & FMT_LINENUMBERS)
324 		printf(FMT("%-4s ", "%s "), "num");
325 	if (!(format & FMT_NOCOUNTS)) {
326 		if (format & FMT_KILOMEGAGIGA) {
327 			printf(FMT("%5s ","%s "), "pkts");
328 			printf(FMT("%5s ","%s "), "bytes");
329 		} else {
330 			printf(FMT("%8s ","%s "), "pkts");
331 			printf(FMT("%10s ","%s "), "bytes");
332 		}
333 	}
334 	if (!(format & FMT_NOTARGET))
335 		printf(FMT("%-9s ","%s "), "target");
336 	fputs(" prot ", stdout);
337 	if (format & FMT_OPTIONS)
338 		fputs("opt", stdout);
339 	if (format & FMT_VIA) {
340 		printf(FMT(" %-6s ","%s "), "in");
341 		printf(FMT("%-6s ","%s "), "out");
342 	}
343 	printf(FMT(" %-19s ","%s "), "source");
344 	printf(FMT(" %-19s "," %s "), "destination");
345 	printf("\n");
346 }
347 
348 
349 static int
print_match(const struct xt_entry_match * m,const struct ip6t_ip6 * ip,int numeric)350 print_match(const struct xt_entry_match *m,
351 	    const struct ip6t_ip6 *ip,
352 	    int numeric)
353 {
354 	const char *name = m->u.user.name;
355 	const int revision = m->u.user.revision;
356 	struct xtables_match *match, *mt;
357 
358 	match = xtables_find_match(name, XTF_TRY_LOAD, NULL);
359 	if (match) {
360 		mt = xtables_find_match_revision(name, XTF_TRY_LOAD,
361 						 match, revision);
362 		if (mt && mt->print)
363 			mt->print(ip, m, numeric);
364 		else if (match->print)
365 			printf("%s%s ", match->name, unsupported_rev);
366 		else
367 			printf("%s ", match->name);
368 	} else {
369 		if (name[0])
370 			printf("UNKNOWN match `%s' ", name);
371 	}
372 	/* Don't stop iterating. */
373 	return 0;
374 }
375 
376 /* e is called `fw' here for historical reasons */
377 static void
print_firewall(const struct ip6t_entry * fw,const char * targname,unsigned int num,unsigned int format,struct xtc_handle * const handle)378 print_firewall(const struct ip6t_entry *fw,
379 	       const char *targname,
380 	       unsigned int num,
381 	       unsigned int format,
382 	       struct xtc_handle *const handle)
383 {
384 	struct xtables_target *target, *tg;
385 	const struct xt_entry_target *t;
386 
387 	if (!ip6tc_is_chain(targname, handle))
388 		target = xtables_find_target(targname, XTF_TRY_LOAD);
389 	else
390 		target = xtables_find_target(XT_STANDARD_TARGET,
391 		         XTF_LOAD_MUST_SUCCEED);
392 
393 	t = ip6t_get_target((struct ip6t_entry *)fw);
394 
395 	if (format & FMT_LINENUMBERS)
396 		printf(FMT("%-4u ", "%u "), num);
397 
398 	if (!(format & FMT_NOCOUNTS)) {
399 		xtables_print_num(fw->counters.pcnt, format);
400 		xtables_print_num(fw->counters.bcnt, format);
401 	}
402 
403 	if (!(format & FMT_NOTARGET))
404 		printf(FMT("%-9s ", "%s "), targname);
405 
406 	fputc(fw->ipv6.invflags & XT_INV_PROTO ? '!' : ' ', stdout);
407 	{
408 		const char *pname = proto_to_name(fw->ipv6.proto, format&FMT_NUMERIC);
409 		if (pname)
410 			printf(FMT("%-5s", "%s "), pname);
411 		else
412 			printf(FMT("%-5hu", "%hu "), fw->ipv6.proto);
413 	}
414 
415 	if (format & FMT_OPTIONS) {
416 		if (format & FMT_NOTABLE)
417 			fputs("opt ", stdout);
418 		fputc(' ', stdout); /* Invert flag of FRAG */
419 		fputc(' ', stdout); /* -f */
420 		fputc(' ', stdout);
421 	}
422 
423 	print_ifaces(fw->ipv6.iniface, fw->ipv6.outiface,
424 		     fw->ipv6.invflags, format);
425 
426 	print_ipv6_addresses(fw, format);
427 
428 	if (format & FMT_NOTABLE)
429 		fputs("  ", stdout);
430 
431 #ifdef IP6T_F_GOTO
432 	if(fw->ipv6.flags & IP6T_F_GOTO)
433 		printf("[goto] ");
434 #endif
435 
436 	IP6T_MATCH_ITERATE(fw, print_match, &fw->ipv6, format & FMT_NUMERIC);
437 
438 	if (target) {
439 		const int revision = t->u.user.revision;
440 
441 		tg = xtables_find_target_revision(targname, XTF_TRY_LOAD,
442 						  target, revision);
443 		if (tg && tg->print)
444 			/* Print the target information. */
445 			tg->print(&fw->ipv6, t, format & FMT_NUMERIC);
446 		else if (target->print)
447 			printf(" %s%s", target->name, unsupported_rev);
448 	} else if (t->u.target_size != sizeof(*t))
449 		printf("[%u bytes of unknown target data] ",
450 		       (unsigned int)(t->u.target_size - sizeof(*t)));
451 
452 	if (!(format & FMT_NONEWLINE))
453 		fputc('\n', stdout);
454 }
455 
456 static void
print_firewall_line(const struct ip6t_entry * fw,struct xtc_handle * const h)457 print_firewall_line(const struct ip6t_entry *fw,
458 		    struct xtc_handle *const h)
459 {
460 	struct xt_entry_target *t;
461 
462 	t = ip6t_get_target((struct ip6t_entry *)fw);
463 	print_firewall(fw, t->u.user.name, 0, FMT_PRINT_RULE, h);
464 }
465 
466 static int
append_entry(const xt_chainlabel chain,struct ip6t_entry * fw,unsigned int nsaddrs,const struct in6_addr saddrs[],const struct in6_addr smasks[],unsigned int ndaddrs,const struct in6_addr daddrs[],const struct in6_addr dmasks[],int verbose,struct xtc_handle * handle)467 append_entry(const xt_chainlabel chain,
468 	     struct ip6t_entry *fw,
469 	     unsigned int nsaddrs,
470 	     const struct in6_addr saddrs[],
471 	     const struct in6_addr smasks[],
472 	     unsigned int ndaddrs,
473 	     const struct in6_addr daddrs[],
474 	     const struct in6_addr dmasks[],
475 	     int verbose,
476 	     struct xtc_handle *handle)
477 {
478 	unsigned int i, j;
479 	int ret = 1;
480 
481 	for (i = 0; i < nsaddrs; i++) {
482 		fw->ipv6.src = saddrs[i];
483 		fw->ipv6.smsk = smasks[i];
484 		for (j = 0; j < ndaddrs; j++) {
485 			fw->ipv6.dst = daddrs[j];
486 			fw->ipv6.dmsk = dmasks[j];
487 			if (verbose)
488 				print_firewall_line(fw, handle);
489 			ret &= ip6tc_append_entry(chain, fw, handle);
490 		}
491 	}
492 
493 	return ret;
494 }
495 
496 static int
replace_entry(const xt_chainlabel chain,struct ip6t_entry * fw,unsigned int rulenum,const struct in6_addr * saddr,const struct in6_addr * smask,const struct in6_addr * daddr,const struct in6_addr * dmask,int verbose,struct xtc_handle * handle)497 replace_entry(const xt_chainlabel chain,
498 	      struct ip6t_entry *fw,
499 	      unsigned int rulenum,
500 	      const struct in6_addr *saddr, const struct in6_addr *smask,
501 	      const struct in6_addr *daddr, const struct in6_addr *dmask,
502 	      int verbose,
503 	      struct xtc_handle *handle)
504 {
505 	fw->ipv6.src = *saddr;
506 	fw->ipv6.dst = *daddr;
507 	fw->ipv6.smsk = *smask;
508 	fw->ipv6.dmsk = *dmask;
509 
510 	if (verbose)
511 		print_firewall_line(fw, handle);
512 	return ip6tc_replace_entry(chain, fw, rulenum, handle);
513 }
514 
515 static int
insert_entry(const xt_chainlabel chain,struct ip6t_entry * fw,unsigned int rulenum,unsigned int nsaddrs,const struct in6_addr saddrs[],const struct in6_addr smasks[],unsigned int ndaddrs,const struct in6_addr daddrs[],const struct in6_addr dmasks[],int verbose,struct xtc_handle * handle)516 insert_entry(const xt_chainlabel chain,
517 	     struct ip6t_entry *fw,
518 	     unsigned int rulenum,
519 	     unsigned int nsaddrs,
520 	     const struct in6_addr saddrs[],
521 	     const struct in6_addr smasks[],
522 	     unsigned int ndaddrs,
523 	     const struct in6_addr daddrs[],
524 	     const struct in6_addr dmasks[],
525 	     int verbose,
526 	     struct xtc_handle *handle)
527 {
528 	unsigned int i, j;
529 	int ret = 1;
530 
531 	for (i = 0; i < nsaddrs; i++) {
532 		fw->ipv6.src = saddrs[i];
533 		fw->ipv6.smsk = smasks[i];
534 		for (j = 0; j < ndaddrs; j++) {
535 			fw->ipv6.dst = daddrs[j];
536 			fw->ipv6.dmsk = dmasks[j];
537 			if (verbose)
538 				print_firewall_line(fw, handle);
539 			ret &= ip6tc_insert_entry(chain, fw, rulenum, handle);
540 		}
541 	}
542 
543 	return ret;
544 }
545 
546 static unsigned char *
make_delete_mask(const struct xtables_rule_match * matches,const struct xtables_target * target)547 make_delete_mask(const struct xtables_rule_match *matches,
548 		 const struct xtables_target *target)
549 {
550 	/* Establish mask for comparison */
551 	unsigned int size;
552 	const struct xtables_rule_match *matchp;
553 	unsigned char *mask, *mptr;
554 
555 	size = sizeof(struct ip6t_entry);
556 	for (matchp = matches; matchp; matchp = matchp->next)
557 		size += XT_ALIGN(sizeof(struct xt_entry_match)) + matchp->match->size;
558 
559 	mask = xtables_calloc(1, size
560 			 + XT_ALIGN(sizeof(struct xt_entry_target))
561 			 + target->size);
562 
563 	memset(mask, 0xFF, sizeof(struct ip6t_entry));
564 	mptr = mask + sizeof(struct ip6t_entry);
565 
566 	for (matchp = matches; matchp; matchp = matchp->next) {
567 		memset(mptr, 0xFF,
568 		       XT_ALIGN(sizeof(struct xt_entry_match))
569 		       + matchp->match->userspacesize);
570 		mptr += XT_ALIGN(sizeof(struct xt_entry_match)) + matchp->match->size;
571 	}
572 
573 	memset(mptr, 0xFF,
574 	       XT_ALIGN(sizeof(struct xt_entry_target))
575 	       + target->userspacesize);
576 
577 	return mask;
578 }
579 
580 static int
delete_entry(const xt_chainlabel chain,struct ip6t_entry * fw,unsigned int nsaddrs,const struct in6_addr saddrs[],const struct in6_addr smasks[],unsigned int ndaddrs,const struct in6_addr daddrs[],const struct in6_addr dmasks[],int verbose,struct xtc_handle * handle,struct xtables_rule_match * matches,const struct xtables_target * target)581 delete_entry(const xt_chainlabel chain,
582 	     struct ip6t_entry *fw,
583 	     unsigned int nsaddrs,
584 	     const struct in6_addr saddrs[],
585 	     const struct in6_addr smasks[],
586 	     unsigned int ndaddrs,
587 	     const struct in6_addr daddrs[],
588 	     const struct in6_addr dmasks[],
589 	     int verbose,
590 	     struct xtc_handle *handle,
591 	     struct xtables_rule_match *matches,
592 	     const struct xtables_target *target)
593 {
594 	unsigned int i, j;
595 	int ret = 1;
596 	unsigned char *mask;
597 
598 	mask = make_delete_mask(matches, target);
599 	for (i = 0; i < nsaddrs; i++) {
600 		fw->ipv6.src = saddrs[i];
601 		fw->ipv6.smsk = smasks[i];
602 		for (j = 0; j < ndaddrs; j++) {
603 			fw->ipv6.dst = daddrs[j];
604 			fw->ipv6.dmsk = dmasks[j];
605 			if (verbose)
606 				print_firewall_line(fw, handle);
607 			ret &= ip6tc_delete_entry(chain, fw, mask, handle);
608 		}
609 	}
610 	free(mask);
611 
612 	return ret;
613 }
614 
615 static int
check_entry(const xt_chainlabel chain,struct ip6t_entry * fw,unsigned int nsaddrs,const struct in6_addr * saddrs,const struct in6_addr * smasks,unsigned int ndaddrs,const struct in6_addr * daddrs,const struct in6_addr * dmasks,bool verbose,struct xtc_handle * handle,struct xtables_rule_match * matches,const struct xtables_target * target)616 check_entry(const xt_chainlabel chain, struct ip6t_entry *fw,
617 	    unsigned int nsaddrs, const struct in6_addr *saddrs,
618 	    const struct in6_addr *smasks, unsigned int ndaddrs,
619 	    const struct in6_addr *daddrs, const struct in6_addr *dmasks,
620 	    bool verbose, struct xtc_handle *handle,
621 	    struct xtables_rule_match *matches,
622 	    const struct xtables_target *target)
623 {
624 	unsigned int i, j;
625 	int ret = 1;
626 	unsigned char *mask;
627 
628 	mask = make_delete_mask(matches, target);
629 	for (i = 0; i < nsaddrs; i++) {
630 		fw->ipv6.src = saddrs[i];
631 		fw->ipv6.smsk = smasks[i];
632 		for (j = 0; j < ndaddrs; j++) {
633 			fw->ipv6.dst = daddrs[j];
634 			fw->ipv6.dmsk = dmasks[j];
635 			if (verbose)
636 				print_firewall_line(fw, handle);
637 			ret &= ip6tc_check_entry(chain, fw, mask, handle);
638 		}
639 	}
640 
641 	free(mask);
642 	return ret;
643 }
644 
645 int
for_each_chain6(int (* fn)(const xt_chainlabel,int,struct xtc_handle *),int verbose,int builtinstoo,struct xtc_handle * handle)646 for_each_chain6(int (*fn)(const xt_chainlabel, int, struct xtc_handle *),
647 	       int verbose, int builtinstoo, struct xtc_handle *handle)
648 {
649 	int ret = 1;
650 	const char *chain;
651 	char *chains;
652 	unsigned int i, chaincount = 0;
653 
654 	chain = ip6tc_first_chain(handle);
655 	while (chain) {
656 		chaincount++;
657 		chain = ip6tc_next_chain(handle);
658 	}
659 
660 	chains = xtables_malloc(sizeof(xt_chainlabel) * chaincount);
661 	i = 0;
662 	chain = ip6tc_first_chain(handle);
663 	while (chain) {
664 		strcpy(chains + i*sizeof(xt_chainlabel), chain);
665 		i++;
666 		chain = ip6tc_next_chain(handle);
667 	}
668 
669 	for (i = 0; i < chaincount; i++) {
670 		if (!builtinstoo
671 		    && ip6tc_builtin(chains + i*sizeof(xt_chainlabel),
672 				    handle) == 1)
673 			continue;
674 		ret &= fn(chains + i*sizeof(xt_chainlabel), verbose, handle);
675 	}
676 
677 	free(chains);
678 	return ret;
679 }
680 
681 int
flush_entries6(const xt_chainlabel chain,int verbose,struct xtc_handle * handle)682 flush_entries6(const xt_chainlabel chain, int verbose,
683 	      struct xtc_handle *handle)
684 {
685 	if (!chain)
686 		return for_each_chain6(flush_entries6, verbose, 1, handle);
687 
688 	if (verbose)
689 		fprintf(stdout, "Flushing chain `%s'\n", chain);
690 	return ip6tc_flush_entries(chain, handle);
691 }
692 
693 static int
zero_entries(const xt_chainlabel chain,int verbose,struct xtc_handle * handle)694 zero_entries(const xt_chainlabel chain, int verbose,
695 	     struct xtc_handle *handle)
696 {
697 	if (!chain)
698 		return for_each_chain6(zero_entries, verbose, 1, handle);
699 
700 	if (verbose)
701 		fprintf(stdout, "Zeroing chain `%s'\n", chain);
702 	return ip6tc_zero_entries(chain, handle);
703 }
704 
705 int
delete_chain6(const xt_chainlabel chain,int verbose,struct xtc_handle * handle)706 delete_chain6(const xt_chainlabel chain, int verbose,
707 	     struct xtc_handle *handle)
708 {
709 	if (!chain)
710 		return for_each_chain6(delete_chain6, verbose, 0, handle);
711 
712 	if (verbose)
713 		fprintf(stdout, "Deleting chain `%s'\n", chain);
714 	return ip6tc_delete_chain(chain, handle);
715 }
716 
717 static int
list_entries(const xt_chainlabel chain,int rulenum,int verbose,int numeric,int expanded,int linenumbers,struct xtc_handle * handle)718 list_entries(const xt_chainlabel chain, int rulenum, int verbose, int numeric,
719 	     int expanded, int linenumbers, struct xtc_handle *handle)
720 {
721 	int found = 0;
722 	unsigned int format;
723 	const char *this;
724 
725 	format = FMT_OPTIONS;
726 	if (!verbose)
727 		format |= FMT_NOCOUNTS;
728 	else
729 		format |= FMT_VIA;
730 
731 	if (numeric)
732 		format |= FMT_NUMERIC;
733 
734 	if (!expanded)
735 		format |= FMT_KILOMEGAGIGA;
736 
737 	if (linenumbers)
738 		format |= FMT_LINENUMBERS;
739 
740 	for (this = ip6tc_first_chain(handle);
741 	     this;
742 	     this = ip6tc_next_chain(handle)) {
743 		const struct ip6t_entry *i;
744 		unsigned int num;
745 
746 		if (chain && strcmp(chain, this) != 0)
747 			continue;
748 
749 		if (found) printf("\n");
750 
751 		if (!rulenum)
752 		    print_header(format, this, handle);
753 		i = ip6tc_first_rule(this, handle);
754 
755 		num = 0;
756 		while (i) {
757 			num++;
758 			if (!rulenum || num == rulenum)
759 				print_firewall(i,
760 					       ip6tc_get_target(i, handle),
761 					       num,
762 					       format,
763 					       handle);
764 			i = ip6tc_next_rule(i, handle);
765 		}
766 		found = 1;
767 	}
768 
769 	errno = ENOENT;
770 	return found;
771 }
772 
773 /* This assumes that mask is contiguous, and byte-bounded. */
774 static void
print_iface(char letter,const char * iface,const unsigned char * mask,int invert)775 print_iface(char letter, const char *iface, const unsigned char *mask,
776 	    int invert)
777 {
778 	unsigned int i;
779 
780 	if (mask[0] == 0)
781 		return;
782 
783 	printf("%s -%c ", invert ? " !" : "", letter);
784 
785 	for (i = 0; i < IFNAMSIZ; i++) {
786 		if (mask[i] != 0) {
787 			if (iface[i] != '\0')
788 				printf("%c", iface[i]);
789 		} else {
790 			/* we can access iface[i-1] here, because
791 			 * a few lines above we make sure that mask[0] != 0 */
792 			if (iface[i-1] != '\0')
793 				printf("+");
794 			break;
795 		}
796 	}
797 }
798 
799 /* The ip6tables looks up the /etc/protocols. */
print_proto(uint16_t proto,int invert)800 static void print_proto(uint16_t proto, int invert)
801 {
802 	if (proto) {
803 		unsigned int i;
804 		const char *invertstr = invert ? " !" : "";
805 
806 		const struct protoent *pent = getprotobynumber(proto);
807 		if (pent) {
808 			printf("%s -p %s",
809 			       invertstr, pent->p_name);
810 			return;
811 		}
812 
813 		for (i = 0; xtables_chain_protos[i].name != NULL; ++i)
814 			if (xtables_chain_protos[i].num == proto) {
815 				printf("%s -p %s",
816 				       invertstr, xtables_chain_protos[i].name);
817 				return;
818 			}
819 
820 		printf("%s -p %u", invertstr, proto);
821 	}
822 }
823 
print_match_save(const struct xt_entry_match * e,const struct ip6t_ip6 * ip)824 static int print_match_save(const struct xt_entry_match *e,
825 			const struct ip6t_ip6 *ip)
826 {
827 	const char *name = e->u.user.name;
828 	const int revision = e->u.user.revision;
829 	struct xtables_match *match, *mt, *mt2;
830 
831 	match = xtables_find_match(name, XTF_TRY_LOAD, NULL);
832 	if (match) {
833 		mt = mt2 = xtables_find_match_revision(name, XTF_TRY_LOAD,
834 						       match, revision);
835 		if (!mt2)
836 			mt2 = match;
837 		printf(" -m %s", mt2->alias ? mt2->alias(e) : name);
838 
839 		/* some matches don't provide a save function */
840 		if (mt && mt->save)
841 			mt->save(ip, e);
842 		else if (match->save)
843 			printf(unsupported_rev);
844 	} else {
845 		if (e->u.match_size) {
846 			fprintf(stderr,
847 				"Can't find library for match `%s'\n",
848 				name);
849 			exit(1);
850 		}
851 	}
852 	return 0;
853 }
854 
855 /* Print a given ip including mask if necessary. */
print_ip(const char * prefix,const struct in6_addr * ip,const struct in6_addr * mask,int invert)856 static void print_ip(const char *prefix, const struct in6_addr *ip,
857 		     const struct in6_addr *mask, int invert)
858 {
859 	char buf[51];
860 	int l = xtables_ip6mask_to_cidr(mask);
861 
862 	if (l == 0 && !invert)
863 		return;
864 
865 	printf("%s %s %s",
866 		invert ? " !" : "",
867 		prefix,
868 		inet_ntop(AF_INET6, ip, buf, sizeof buf));
869 
870 	if (l == -1)
871 		printf("/%s", inet_ntop(AF_INET6, mask, buf, sizeof buf));
872 	else
873 		printf("/%d", l);
874 }
875 
876 /* We want this to be readable, so only print out necessary fields.
877  * Because that's the kind of world I want to live in.
878  */
print_rule6(const struct ip6t_entry * e,struct xtc_handle * h,const char * chain,int counters)879 void print_rule6(const struct ip6t_entry *e,
880 		       struct xtc_handle *h, const char *chain, int counters)
881 {
882 	const struct xt_entry_target *t;
883 	const char *target_name;
884 
885 	/* print counters for iptables-save */
886 	if (counters > 0)
887 		printf("[%llu:%llu] ", (unsigned long long)e->counters.pcnt, (unsigned long long)e->counters.bcnt);
888 
889 	/* print chain name */
890 	printf("-A %s", chain);
891 
892 	/* Print IP part. */
893 	print_ip("-s", &(e->ipv6.src), &(e->ipv6.smsk),
894 			e->ipv6.invflags & IP6T_INV_SRCIP);
895 
896 	print_ip("-d", &(e->ipv6.dst), &(e->ipv6.dmsk),
897 			e->ipv6.invflags & IP6T_INV_DSTIP);
898 
899 	print_iface('i', e->ipv6.iniface, e->ipv6.iniface_mask,
900 		    e->ipv6.invflags & IP6T_INV_VIA_IN);
901 
902 	print_iface('o', e->ipv6.outiface, e->ipv6.outiface_mask,
903 		    e->ipv6.invflags & IP6T_INV_VIA_OUT);
904 
905 	print_proto(e->ipv6.proto, e->ipv6.invflags & XT_INV_PROTO);
906 
907 #if 0
908 	/* not definied in ipv6
909 	 * FIXME: linux/netfilter_ipv6/ip6_tables: IP6T_INV_FRAG why definied? */
910 	if (e->ipv6.flags & IPT_F_FRAG)
911 		printf("%s -f",
912 		       e->ipv6.invflags & IP6T_INV_FRAG ? " !" : "");
913 #endif
914 
915 	if (e->ipv6.flags & IP6T_F_TOS)
916 		printf("%s -? %d",
917 		       e->ipv6.invflags & IP6T_INV_TOS ? " !" : "",
918 		       e->ipv6.tos);
919 
920 	/* Print matchinfo part */
921 	if (e->target_offset) {
922 		IP6T_MATCH_ITERATE(e, print_match_save, &e->ipv6);
923 	}
924 
925 	/* print counters for iptables -R */
926 	if (counters < 0)
927 		printf(" -c %llu %llu", (unsigned long long)e->counters.pcnt, (unsigned long long)e->counters.bcnt);
928 
929 	/* Print target name and targinfo part */
930 	target_name = ip6tc_get_target(e, h);
931 	t = ip6t_get_target((struct ip6t_entry *)e);
932 	if (t->u.user.name[0]) {
933 		const char *name = t->u.user.name;
934 		const int revision = t->u.user.revision;
935 		struct xtables_target *target, *tg, *tg2;
936 
937 		target = xtables_find_target(name, XTF_TRY_LOAD);
938 		if (!target) {
939 			fprintf(stderr, "Can't find library for target `%s'\n",
940 				name);
941 			exit(1);
942 		}
943 
944 		tg = tg2 = xtables_find_target_revision(name, XTF_TRY_LOAD,
945 							target, revision);
946 		if (!tg2)
947 			tg2 = target;
948 		printf(" -j %s", tg2->alias ? tg2->alias(t) : target_name);
949 
950 		if (tg && tg->save)
951 			tg->save(&e->ipv6, t);
952 		else if (target->save)
953 			printf(unsupported_rev);
954 		else {
955 			/* If the target size is greater than xt_entry_target
956 			 * there is something to be saved, we just don't know
957 			 * how to print it */
958 			if (t->u.target_size !=
959 			    sizeof(struct xt_entry_target)) {
960 				fprintf(stderr, "Target `%s' is missing "
961 						"save function\n",
962 					name);
963 				exit(1);
964 			}
965 		}
966 	} else if (target_name && (*target_name != '\0'))
967 #ifdef IP6T_F_GOTO
968 		printf(" -%c %s", e->ipv6.flags & IP6T_F_GOTO ? 'g' : 'j', target_name);
969 #else
970 		printf(" -j %s", target_name);
971 #endif
972 
973 	printf("\n");
974 }
975 
976 static int
list_rules(const xt_chainlabel chain,int rulenum,int counters,struct xtc_handle * handle)977 list_rules(const xt_chainlabel chain, int rulenum, int counters,
978 	     struct xtc_handle *handle)
979 {
980 	const char *this = NULL;
981 	int found = 0;
982 
983 	if (counters)
984 	    counters = -1;		/* iptables -c format */
985 
986 	/* Dump out chain names first,
987 	 * thereby preventing dependency conflicts */
988 	if (!rulenum) for (this = ip6tc_first_chain(handle);
989 	     this;
990 	     this = ip6tc_next_chain(handle)) {
991 		if (chain && strcmp(this, chain) != 0)
992 			continue;
993 
994 		if (ip6tc_builtin(this, handle)) {
995 			struct xt_counters count;
996 			printf("-P %s %s", this, ip6tc_get_policy(this, &count, handle));
997 			if (counters)
998 			    printf(" -c %llu %llu", (unsigned long long)count.pcnt, (unsigned long long)count.bcnt);
999 			printf("\n");
1000 		} else {
1001 			printf("-N %s\n", this);
1002 		}
1003 	}
1004 
1005 	for (this = ip6tc_first_chain(handle);
1006 	     this;
1007 	     this = ip6tc_next_chain(handle)) {
1008 		const struct ip6t_entry *e;
1009 		int num = 0;
1010 
1011 		if (chain && strcmp(this, chain) != 0)
1012 			continue;
1013 
1014 		/* Dump out rules */
1015 		e = ip6tc_first_rule(this, handle);
1016 		while(e) {
1017 			num++;
1018 			if (!rulenum || num == rulenum)
1019 			    print_rule6(e, handle, this, counters);
1020 			e = ip6tc_next_rule(e, handle);
1021 		}
1022 		found = 1;
1023 	}
1024 
1025 	errno = ENOENT;
1026 	return found;
1027 }
1028 
1029 static struct ip6t_entry *
generate_entry(const struct ip6t_entry * fw,struct xtables_rule_match * matches,struct xt_entry_target * target)1030 generate_entry(const struct ip6t_entry *fw,
1031 	       struct xtables_rule_match *matches,
1032 	       struct xt_entry_target *target)
1033 {
1034 	unsigned int size;
1035 	struct xtables_rule_match *matchp;
1036 	struct ip6t_entry *e;
1037 
1038 	size = sizeof(struct ip6t_entry);
1039 	for (matchp = matches; matchp; matchp = matchp->next)
1040 		size += matchp->match->m->u.match_size;
1041 
1042 	e = xtables_malloc(size + target->u.target_size);
1043 	*e = *fw;
1044 	e->target_offset = size;
1045 	e->next_offset = size + target->u.target_size;
1046 
1047 	size = 0;
1048 	for (matchp = matches; matchp; matchp = matchp->next) {
1049 		memcpy(e->elems + size, matchp->match->m, matchp->match->m->u.match_size);
1050 		size += matchp->match->m->u.match_size;
1051 	}
1052 	memcpy(e->elems + size, target, target->u.target_size);
1053 
1054 	return e;
1055 }
1056 
do_command6(int argc,char * argv[],char ** table,struct xtc_handle ** handle,bool restore)1057 int do_command6(int argc, char *argv[], char **table,
1058 		struct xtc_handle **handle, bool restore)
1059 {
1060 	struct iptables_command_state cs = {
1061 		.jumpto	= "",
1062 		.argv	= argv,
1063 	};
1064 	struct ip6t_entry *e = NULL;
1065 	unsigned int nsaddrs = 0, ndaddrs = 0;
1066 	struct in6_addr *saddrs = NULL, *daddrs = NULL;
1067 	struct in6_addr *smasks = NULL, *dmasks = NULL;
1068 
1069 	int verbose = 0;
1070 	int wait = 0;
1071 	struct timeval wait_interval = {
1072 		.tv_sec	= 1,
1073 	};
1074 	bool wait_interval_set = false;
1075 	const char *chain = NULL;
1076 	const char *shostnetworkmask = NULL, *dhostnetworkmask = NULL;
1077 	const char *policy = NULL, *newname = NULL;
1078 	unsigned int rulenum = 0, command = 0;
1079 	const char *pcnt = NULL, *bcnt = NULL;
1080 	int ret = 1;
1081 	struct xtables_match *m;
1082 	struct xtables_rule_match *matchp;
1083 	struct xtables_target *t;
1084 	unsigned long long cnt;
1085 	bool table_set = false;
1086 
1087 	/* re-set optind to 0 in case do_command6 gets called
1088 	 * a second time */
1089 	optind = 0;
1090 
1091 	/* clear mflags in case do_command6 gets called a second time
1092 	 * (we clear the global list of all matches for security)*/
1093 	for (m = xtables_matches; m; m = m->next)
1094 		m->mflags = 0;
1095 
1096 	for (t = xtables_targets; t; t = t->next) {
1097 		t->tflags = 0;
1098 		t->used = 0;
1099 	}
1100 
1101 	/* Suppress error messages: we may add new options if we
1102            demand-load a protocol. */
1103 	opterr = 0;
1104 
1105 	opts = xt_params->orig_opts;
1106 	while ((cs.c = getopt_long(argc, argv,
1107 	   "-:A:C:D:R:I:L::S::M:F::Z::N:X::E:P:Vh::o:p:s:d:j:i:bvw::W::nt:m:xc:g:46",
1108 					   opts, NULL)) != -1) {
1109 		switch (cs.c) {
1110 			/*
1111 			 * Command selection
1112 			 */
1113 		case 'A':
1114 			add_command(&command, CMD_APPEND, CMD_NONE,
1115 				    cs.invert);
1116 			chain = optarg;
1117 			break;
1118 
1119 		case 'C':
1120 			add_command(&command, CMD_CHECK, CMD_NONE,
1121 			            cs.invert);
1122 			chain = optarg;
1123 			break;
1124 
1125 		case 'D':
1126 			add_command(&command, CMD_DELETE, CMD_NONE,
1127 				    cs.invert);
1128 			chain = optarg;
1129 			if (xs_has_arg(argc, argv)) {
1130 				rulenum = parse_rulenumber(argv[optind++]);
1131 				command = CMD_DELETE_NUM;
1132 			}
1133 			break;
1134 
1135 		case 'R':
1136 			add_command(&command, CMD_REPLACE, CMD_NONE,
1137 				    cs.invert);
1138 			chain = optarg;
1139 			if (xs_has_arg(argc, argv))
1140 				rulenum = parse_rulenumber(argv[optind++]);
1141 			else
1142 				xtables_error(PARAMETER_PROBLEM,
1143 					   "-%c requires a rule number",
1144 					   cmd2char(CMD_REPLACE));
1145 			break;
1146 
1147 		case 'I':
1148 			add_command(&command, CMD_INSERT, CMD_NONE,
1149 				    cs.invert);
1150 			chain = optarg;
1151 			if (xs_has_arg(argc, argv))
1152 				rulenum = parse_rulenumber(argv[optind++]);
1153 			else rulenum = 1;
1154 			break;
1155 
1156 		case 'L':
1157 			add_command(&command, CMD_LIST,
1158 				    CMD_ZERO | CMD_ZERO_NUM, cs.invert);
1159 			if (optarg) chain = optarg;
1160 			else if (xs_has_arg(argc, argv))
1161 				chain = argv[optind++];
1162 			if (xs_has_arg(argc, argv))
1163 				rulenum = parse_rulenumber(argv[optind++]);
1164 			break;
1165 
1166 		case 'S':
1167 			add_command(&command, CMD_LIST_RULES,
1168 				    CMD_ZERO | CMD_ZERO_NUM, cs.invert);
1169 			if (optarg) chain = optarg;
1170 			else if (xs_has_arg(argc, argv))
1171 				chain = argv[optind++];
1172 			if (xs_has_arg(argc, argv))
1173 				rulenum = parse_rulenumber(argv[optind++]);
1174 			break;
1175 
1176 		case 'F':
1177 			add_command(&command, CMD_FLUSH, CMD_NONE,
1178 				    cs.invert);
1179 			if (optarg) chain = optarg;
1180 			else if (xs_has_arg(argc, argv))
1181 				chain = argv[optind++];
1182 			break;
1183 
1184 		case 'Z':
1185 			add_command(&command, CMD_ZERO, CMD_LIST|CMD_LIST_RULES,
1186 				    cs.invert);
1187 			if (optarg) chain = optarg;
1188 			else if (xs_has_arg(argc, argv))
1189 				chain = argv[optind++];
1190 			if (xs_has_arg(argc, argv)) {
1191 				rulenum = parse_rulenumber(argv[optind++]);
1192 				command = CMD_ZERO_NUM;
1193 			}
1194 			break;
1195 
1196 		case 'N':
1197 			parse_chain(optarg);
1198 			add_command(&command, CMD_NEW_CHAIN, CMD_NONE,
1199 				    cs.invert);
1200 			chain = optarg;
1201 			break;
1202 
1203 		case 'X':
1204 			add_command(&command, CMD_DELETE_CHAIN, CMD_NONE,
1205 				    cs.invert);
1206 			if (optarg) chain = optarg;
1207 			else if (xs_has_arg(argc, argv))
1208 				chain = argv[optind++];
1209 			break;
1210 
1211 		case 'E':
1212 			add_command(&command, CMD_RENAME_CHAIN, CMD_NONE,
1213 				    cs.invert);
1214 			chain = optarg;
1215 			if (xs_has_arg(argc, argv))
1216 				newname = argv[optind++];
1217 			else
1218 				xtables_error(PARAMETER_PROBLEM,
1219 					   "-%c requires old-chain-name and "
1220 					   "new-chain-name",
1221 					    cmd2char(CMD_RENAME_CHAIN));
1222 			break;
1223 
1224 		case 'P':
1225 			add_command(&command, CMD_SET_POLICY, CMD_NONE,
1226 				    cs.invert);
1227 			chain = optarg;
1228 			if (xs_has_arg(argc, argv))
1229 				policy = argv[optind++];
1230 			else
1231 				xtables_error(PARAMETER_PROBLEM,
1232 					   "-%c requires a chain and a policy",
1233 					   cmd2char(CMD_SET_POLICY));
1234 			break;
1235 
1236 		case 'h':
1237 			if (!optarg)
1238 				optarg = argv[optind];
1239 
1240 			/* ip6tables -p icmp -h */
1241 			if (!cs.matches && cs.protocol)
1242 				xtables_find_match(cs.protocol, XTF_TRY_LOAD,
1243 					&cs.matches);
1244 
1245 			exit_printhelp(cs.matches);
1246 
1247 			/*
1248 			 * Option selection
1249 			 */
1250 		case 'p':
1251 			set_option(&cs.options, OPT_PROTOCOL, &cs.fw6.ipv6.invflags,
1252 				   cs.invert);
1253 
1254 			/* Canonicalize into lower case */
1255 			for (cs.protocol = optarg; *cs.protocol; cs.protocol++)
1256 				*cs.protocol = tolower(*cs.protocol);
1257 
1258 			cs.protocol = optarg;
1259 			cs.fw6.ipv6.proto = xtables_parse_protocol(cs.protocol);
1260 			cs.fw6.ipv6.flags |= IP6T_F_PROTO;
1261 
1262 			if (cs.fw6.ipv6.proto == 0
1263 			    && (cs.fw6.ipv6.invflags & XT_INV_PROTO))
1264 				xtables_error(PARAMETER_PROBLEM,
1265 					   "rule would never match protocol");
1266 
1267 			if (is_exthdr(cs.fw6.ipv6.proto)
1268 			    && (cs.fw6.ipv6.invflags & XT_INV_PROTO) == 0)
1269 				fprintf(stderr,
1270 					"Warning: never matched protocol: %s. "
1271 					"use extension match instead.\n",
1272 					cs.protocol);
1273 			break;
1274 
1275 		case 's':
1276 			set_option(&cs.options, OPT_SOURCE, &cs.fw6.ipv6.invflags,
1277 				   cs.invert);
1278 			shostnetworkmask = optarg;
1279 			break;
1280 
1281 		case 'd':
1282 			set_option(&cs.options, OPT_DESTINATION, &cs.fw6.ipv6.invflags,
1283 				   cs.invert);
1284 			dhostnetworkmask = optarg;
1285 			break;
1286 
1287 #ifdef IP6T_F_GOTO
1288 		case 'g':
1289 			set_option(&cs.options, OPT_JUMP, &cs.fw6.ipv6.invflags,
1290 					cs.invert);
1291 			cs.fw6.ipv6.flags |= IP6T_F_GOTO;
1292 			cs.jumpto = xt_parse_target(optarg);
1293 			break;
1294 #endif
1295 
1296 		case 'j':
1297 			set_option(&cs.options, OPT_JUMP, &cs.fw6.ipv6.invflags,
1298 					cs.invert);
1299 			command_jump(&cs, optarg);
1300 			break;
1301 
1302 
1303 		case 'i':
1304 			if (*optarg == '\0')
1305 				xtables_error(PARAMETER_PROBLEM,
1306 					"Empty interface is likely to be "
1307 					"undesired");
1308 			set_option(&cs.options, OPT_VIANAMEIN, &cs.fw6.ipv6.invflags,
1309 				   cs.invert);
1310 			xtables_parse_interface(optarg,
1311 					cs.fw6.ipv6.iniface,
1312 					cs.fw6.ipv6.iniface_mask);
1313 			break;
1314 
1315 		case 'o':
1316 			if (*optarg == '\0')
1317 				xtables_error(PARAMETER_PROBLEM,
1318 					"Empty interface is likely to be "
1319 					"undesired");
1320 			set_option(&cs.options, OPT_VIANAMEOUT, &cs.fw6.ipv6.invflags,
1321 				   cs.invert);
1322 			xtables_parse_interface(optarg,
1323 					cs.fw6.ipv6.outiface,
1324 					cs.fw6.ipv6.outiface_mask);
1325 			break;
1326 
1327 		case 'v':
1328 			if (!verbose)
1329 				set_option(&cs.options, OPT_VERBOSE,
1330 					   &cs.fw6.ipv6.invflags, cs.invert);
1331 			verbose++;
1332 			break;
1333 
1334 		case 'w':
1335 			if (restore) {
1336 				xtables_error(PARAMETER_PROBLEM,
1337 					      "You cannot use `-w' from "
1338 					      "ip6tables-restore");
1339 			}
1340 			wait = parse_wait_time(argc, argv);
1341 			break;
1342 
1343 		case 'W':
1344 			if (restore) {
1345 				xtables_error(PARAMETER_PROBLEM,
1346 					      "You cannot use `-W' from "
1347 					      "ip6tables-restore");
1348 			}
1349 			parse_wait_interval(argc, argv, &wait_interval);
1350 			wait_interval_set = true;
1351 			break;
1352 
1353 		case 'm':
1354 			command_match(&cs);
1355 			break;
1356 
1357 		case 'n':
1358 			set_option(&cs.options, OPT_NUMERIC, &cs.fw6.ipv6.invflags,
1359 				   cs.invert);
1360 			break;
1361 
1362 		case 't':
1363 			if (cs.invert)
1364 				xtables_error(PARAMETER_PROBLEM,
1365 					   "unexpected ! flag before --table");
1366 			if (restore && table_set)
1367 				xtables_error(PARAMETER_PROBLEM,
1368 					      "The -t option (seen in line %u) cannot be used in %s.\n",
1369 					      line, xt_params->program_name);
1370 			*table = optarg;
1371 			table_set = true;
1372 			break;
1373 
1374 		case 'x':
1375 			set_option(&cs.options, OPT_EXPANDED, &cs.fw6.ipv6.invflags,
1376 				   cs.invert);
1377 			break;
1378 
1379 		case 'V':
1380 			if (cs.invert)
1381 				printf("Not %s ;-)\n", prog_vers);
1382 			else
1383 				printf("%s v%s (legacy)\n",
1384 				       prog_name, prog_vers);
1385 			exit(0);
1386 
1387 		case '0':
1388 			set_option(&cs.options, OPT_LINENUMBERS, &cs.fw6.ipv6.invflags,
1389 				   cs.invert);
1390 			break;
1391 
1392 		case 'M':
1393 			xtables_modprobe_program = optarg;
1394 			break;
1395 
1396 		case 'c':
1397 
1398 			set_option(&cs.options, OPT_COUNTERS, &cs.fw6.ipv6.invflags,
1399 				   cs.invert);
1400 			pcnt = optarg;
1401 			bcnt = strchr(pcnt + 1, ',');
1402 			if (bcnt)
1403 			    bcnt++;
1404 			if (!bcnt && xs_has_arg(argc, argv))
1405 				bcnt = argv[optind++];
1406 			if (!bcnt)
1407 				xtables_error(PARAMETER_PROBLEM,
1408 					"-%c requires packet and byte counter",
1409 					opt2char(OPT_COUNTERS));
1410 
1411 			if (sscanf(pcnt, "%llu", &cnt) != 1)
1412 				xtables_error(PARAMETER_PROBLEM,
1413 					"-%c packet counter not numeric",
1414 					opt2char(OPT_COUNTERS));
1415 			cs.fw6.counters.pcnt = cnt;
1416 
1417 			if (sscanf(bcnt, "%llu", &cnt) != 1)
1418 				xtables_error(PARAMETER_PROBLEM,
1419 					"-%c byte counter not numeric",
1420 					opt2char(OPT_COUNTERS));
1421 			cs.fw6.counters.bcnt = cnt;
1422 			break;
1423 
1424 		case '4':
1425 			/* This is not the IPv4 iptables */
1426 			if (line != -1)
1427 				return 1; /* success: line ignored */
1428 			fprintf(stderr, "This is the IPv6 version of ip6tables.\n");
1429 			exit_tryhelp(2);
1430 
1431 		case '6':
1432 			/* This is indeed the IPv6 ip6tables */
1433 			break;
1434 
1435 		case 1: /* non option */
1436 			if (optarg[0] == '!' && optarg[1] == '\0') {
1437 				if (cs.invert)
1438 					xtables_error(PARAMETER_PROBLEM,
1439 						   "multiple consecutive ! not"
1440 						   " allowed");
1441 				cs.invert = true;
1442 				optarg[0] = '\0';
1443 				continue;
1444 			}
1445 			fprintf(stderr, "Bad argument `%s'\n", optarg);
1446 			exit_tryhelp(2);
1447 
1448 		default:
1449 			if (command_default(&cs, &ip6tables_globals) == 1)
1450 				/*
1451 				 * If new options were loaded, we must retry
1452 				 * getopt immediately and not allow
1453 				 * cs.invert=false to be executed.
1454 				 */
1455 				continue;
1456 			break;
1457 		}
1458 		cs.invert = false;
1459 	}
1460 
1461 	if (!wait && wait_interval_set)
1462 		xtables_error(PARAMETER_PROBLEM,
1463 			      "--wait-interval only makes sense with --wait\n");
1464 
1465 	if (strcmp(*table, "nat") == 0 &&
1466 	    ((policy != NULL && strcmp(policy, "DROP") == 0) ||
1467 	    (cs.jumpto != NULL && strcmp(cs.jumpto, "DROP") == 0)))
1468 		xtables_error(PARAMETER_PROBLEM,
1469 			"\nThe \"nat\" table is not intended for filtering, "
1470 		        "the use of DROP is therefore inhibited.\n\n");
1471 
1472 	for (matchp = cs.matches; matchp; matchp = matchp->next)
1473 		xtables_option_mfcall(matchp->match);
1474 	if (cs.target != NULL)
1475 		xtables_option_tfcall(cs.target);
1476 
1477 	/* Fix me: must put inverse options checking here --MN */
1478 
1479 	if (optind < argc)
1480 		xtables_error(PARAMETER_PROBLEM,
1481 			   "unknown arguments found on commandline");
1482 	if (!command)
1483 		xtables_error(PARAMETER_PROBLEM, "no command specified");
1484 	if (cs.invert)
1485 		xtables_error(PARAMETER_PROBLEM,
1486 			   "nothing appropriate following !");
1487 
1488 	if (command & (CMD_REPLACE | CMD_INSERT | CMD_DELETE | CMD_APPEND | CMD_CHECK)) {
1489 		if (!(cs.options & OPT_DESTINATION))
1490 			dhostnetworkmask = "::0/0";
1491 		if (!(cs.options & OPT_SOURCE))
1492 			shostnetworkmask = "::0/0";
1493 	}
1494 
1495 	if (shostnetworkmask)
1496 		xtables_ip6parse_multiple(shostnetworkmask, &saddrs,
1497 					  &smasks, &nsaddrs);
1498 
1499 	if (dhostnetworkmask)
1500 		xtables_ip6parse_multiple(dhostnetworkmask, &daddrs,
1501 					  &dmasks, &ndaddrs);
1502 
1503 	if ((nsaddrs > 1 || ndaddrs > 1) &&
1504 	    (cs.fw6.ipv6.invflags & (IP6T_INV_SRCIP | IP6T_INV_DSTIP)))
1505 		xtables_error(PARAMETER_PROBLEM, "! not allowed with multiple"
1506 			   " source or destination IP addresses");
1507 
1508 	if (command == CMD_REPLACE && (nsaddrs != 1 || ndaddrs != 1))
1509 		xtables_error(PARAMETER_PROBLEM, "Replacement rule does not "
1510 			   "specify a unique address");
1511 
1512 	generic_opt_check(command, cs.options);
1513 
1514 	/* Attempt to acquire the xtables lock */
1515 	if (!restore)
1516 		xtables_lock_or_exit(wait, &wait_interval);
1517 
1518 	/* only allocate handle if we weren't called with a handle */
1519 	if (!*handle)
1520 		*handle = ip6tc_init(*table);
1521 
1522 	/* try to insmod the module if iptc_init failed */
1523 	if (!*handle && xtables_load_ko(xtables_modprobe_program, false) != -1)
1524 		*handle = ip6tc_init(*table);
1525 
1526 	if (!*handle)
1527 		xtables_error(VERSION_PROBLEM,
1528 			"can't initialize ip6tables table `%s': %s",
1529 			*table, ip6tc_strerror(errno));
1530 
1531 	if (command == CMD_APPEND
1532 	    || command == CMD_DELETE
1533 	    || command == CMD_CHECK
1534 	    || command == CMD_INSERT
1535 	    || command == CMD_REPLACE) {
1536 		if (strcmp(chain, "PREROUTING") == 0
1537 		    || strcmp(chain, "INPUT") == 0) {
1538 			/* -o not valid with incoming packets. */
1539 			if (cs.options & OPT_VIANAMEOUT)
1540 				xtables_error(PARAMETER_PROBLEM,
1541 					   "Can't use -%c with %s\n",
1542 					   opt2char(OPT_VIANAMEOUT),
1543 					   chain);
1544 		}
1545 
1546 		if (strcmp(chain, "POSTROUTING") == 0
1547 		    || strcmp(chain, "OUTPUT") == 0) {
1548 			/* -i not valid with outgoing packets */
1549 			if (cs.options & OPT_VIANAMEIN)
1550 				xtables_error(PARAMETER_PROBLEM,
1551 					   "Can't use -%c with %s\n",
1552 					   opt2char(OPT_VIANAMEIN),
1553 					   chain);
1554 		}
1555 
1556 		if (cs.target && ip6tc_is_chain(cs.jumpto, *handle)) {
1557 			fprintf(stderr,
1558 				"Warning: using chain %s, not extension\n",
1559 				cs.jumpto);
1560 
1561 			if (cs.target->t)
1562 				free(cs.target->t);
1563 
1564 			cs.target = NULL;
1565 		}
1566 
1567 		/* If they didn't specify a target, or it's a chain
1568 		   name, use standard. */
1569 		if (!cs.target
1570 		    && (strlen(cs.jumpto) == 0
1571 			|| ip6tc_is_chain(cs.jumpto, *handle))) {
1572 			size_t size;
1573 
1574 			cs.target = xtables_find_target(XT_STANDARD_TARGET,
1575 					XTF_LOAD_MUST_SUCCEED);
1576 
1577 			size = sizeof(struct xt_entry_target)
1578 				+ cs.target->size;
1579 			cs.target->t = xtables_calloc(1, size);
1580 			cs.target->t->u.target_size = size;
1581 			strcpy(cs.target->t->u.user.name, cs.jumpto);
1582 			xs_init_target(cs.target);
1583 		}
1584 
1585 		if (!cs.target) {
1586 			/* It is no chain, and we can't load a plugin.
1587 			 * We cannot know if the plugin is corrupt, non
1588 			 * existent OR if the user just misspelled a
1589 			 * chain.
1590 			 */
1591 #ifdef IP6T_F_GOTO
1592 			if (cs.fw6.ipv6.flags & IP6T_F_GOTO)
1593 				xtables_error(PARAMETER_PROBLEM,
1594 						"goto '%s' is not a chain\n",
1595 						cs.jumpto);
1596 #endif
1597 			xtables_find_target(cs.jumpto, XTF_LOAD_MUST_SUCCEED);
1598 		} else {
1599 			e = generate_entry(&cs.fw6, cs.matches, cs.target->t);
1600 			free(cs.target->t);
1601 		}
1602 	}
1603 
1604 	switch (command) {
1605 	case CMD_APPEND:
1606 		ret = append_entry(chain, e,
1607 				   nsaddrs, saddrs, smasks,
1608 				   ndaddrs, daddrs, dmasks,
1609 				   cs.options&OPT_VERBOSE,
1610 				   *handle);
1611 		break;
1612 	case CMD_DELETE:
1613 		ret = delete_entry(chain, e,
1614 				   nsaddrs, saddrs, smasks,
1615 				   ndaddrs, daddrs, dmasks,
1616 				   cs.options&OPT_VERBOSE,
1617 				   *handle, cs.matches, cs.target);
1618 		break;
1619 	case CMD_DELETE_NUM:
1620 		ret = ip6tc_delete_num_entry(chain, rulenum - 1, *handle);
1621 		break;
1622 	case CMD_CHECK:
1623 		ret = check_entry(chain, e,
1624 				   nsaddrs, saddrs, smasks,
1625 				   ndaddrs, daddrs, dmasks,
1626 				   cs.options&OPT_VERBOSE,
1627 				   *handle, cs.matches, cs.target);
1628 		break;
1629 	case CMD_REPLACE:
1630 		ret = replace_entry(chain, e, rulenum - 1,
1631 				    saddrs, smasks, daddrs, dmasks,
1632 				    cs.options&OPT_VERBOSE, *handle);
1633 		break;
1634 	case CMD_INSERT:
1635 		ret = insert_entry(chain, e, rulenum - 1,
1636 				   nsaddrs, saddrs, smasks,
1637 				   ndaddrs, daddrs, dmasks,
1638 				   cs.options&OPT_VERBOSE,
1639 				   *handle);
1640 		break;
1641 	case CMD_FLUSH:
1642 		ret = flush_entries6(chain, cs.options&OPT_VERBOSE, *handle);
1643 		break;
1644 	case CMD_ZERO:
1645 		ret = zero_entries(chain, cs.options&OPT_VERBOSE, *handle);
1646 		break;
1647 	case CMD_ZERO_NUM:
1648 		ret = ip6tc_zero_counter(chain, rulenum, *handle);
1649 		break;
1650 	case CMD_LIST:
1651 	case CMD_LIST|CMD_ZERO:
1652 	case CMD_LIST|CMD_ZERO_NUM:
1653 		ret = list_entries(chain,
1654 				   rulenum,
1655 				   cs.options&OPT_VERBOSE,
1656 				   cs.options&OPT_NUMERIC,
1657 				   cs.options&OPT_EXPANDED,
1658 				   cs.options&OPT_LINENUMBERS,
1659 				   *handle);
1660 		if (ret && (command & CMD_ZERO))
1661 			ret = zero_entries(chain,
1662 					   cs.options&OPT_VERBOSE, *handle);
1663 		if (ret && (command & CMD_ZERO_NUM))
1664 			ret = ip6tc_zero_counter(chain, rulenum, *handle);
1665 		break;
1666 	case CMD_LIST_RULES:
1667 	case CMD_LIST_RULES|CMD_ZERO:
1668 	case CMD_LIST_RULES|CMD_ZERO_NUM:
1669 		ret = list_rules(chain,
1670 				   rulenum,
1671 				   cs.options&OPT_VERBOSE,
1672 				   *handle);
1673 		if (ret && (command & CMD_ZERO))
1674 			ret = zero_entries(chain,
1675 					   cs.options&OPT_VERBOSE, *handle);
1676 		if (ret && (command & CMD_ZERO_NUM))
1677 			ret = ip6tc_zero_counter(chain, rulenum, *handle);
1678 		break;
1679 	case CMD_NEW_CHAIN:
1680 		ret = ip6tc_create_chain(chain, *handle);
1681 		break;
1682 	case CMD_DELETE_CHAIN:
1683 		ret = delete_chain6(chain, cs.options&OPT_VERBOSE, *handle);
1684 		break;
1685 	case CMD_RENAME_CHAIN:
1686 		ret = ip6tc_rename_chain(chain, newname,	*handle);
1687 		break;
1688 	case CMD_SET_POLICY:
1689 		ret = ip6tc_set_policy(chain, policy, cs.options&OPT_COUNTERS ? &cs.fw6.counters : NULL, *handle);
1690 		break;
1691 	default:
1692 		/* We should never reach this... */
1693 		exit_tryhelp(2);
1694 	}
1695 
1696 	if (verbose > 1)
1697 		dump_entries6(*handle);
1698 
1699 	xtables_rule_matches_free(&cs.matches);
1700 
1701 	if (e != NULL) {
1702 		free(e);
1703 		e = NULL;
1704 	}
1705 
1706 	free(saddrs);
1707 	free(smasks);
1708 	free(daddrs);
1709 	free(dmasks);
1710 	xtables_free_opts(1);
1711 
1712 	return ret;
1713 }
1714