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