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