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