iptables-restore.c revision 1639fe86579f86f5f6a954a9b0adde2e16ad1980
1/* Code to restore the iptables state, from file by iptables-save.
2 * (C) 2000-2002 by Harald Welte <laforge@gnumonks.org>
3 * based on previous code from Rusty Russell <rusty@linuxcare.com.au>
4 *
5 * This code is distributed under the terms of GNU GPL v2
6 */
7
8#include <getopt.h>
9#include <sys/errno.h>
10#include <stdbool.h>
11#include <string.h>
12#include <stdio.h>
13#include <stdlib.h>
14#include "iptables.h"
15#include "xtables.h"
16#include "libiptc/libiptc.h"
17#include "iptables-multi.h"
18
19#ifdef DEBUG
20#define DEBUGP(x, args...) fprintf(stderr, x, ## args)
21#else
22#define DEBUGP(x, args...)
23#endif
24
25static int binary = 0, counters = 0, verbose = 0, noflush = 0;
26
27/* Keeping track of external matches and targets.  */
28static const struct option options[] = {
29	{.name = "binary",   .has_arg = false, .val = 'b'},
30	{.name = "counters", .has_arg = false, .val = 'c'},
31	{.name = "verbose",  .has_arg = false, .val = 'v'},
32	{.name = "test",     .has_arg = false, .val = 't'},
33	{.name = "help",     .has_arg = false, .val = 'h'},
34	{.name = "noflush",  .has_arg = false, .val = 'n'},
35	{.name = "modprobe", .has_arg = true,  .val = 'M'},
36	{.name = "table",    .has_arg = true,  .val = 'T'},
37	{NULL},
38};
39
40static void print_usage(const char *name, const char *version) __attribute__((noreturn));
41
42#define prog_name iptables_globals.program_name
43
44static void print_usage(const char *name, const char *version)
45{
46	fprintf(stderr, "Usage: %s [-b] [-c] [-v] [-t] [-h]\n"
47			"	   [ --binary ]\n"
48			"	   [ --counters ]\n"
49			"	   [ --verbose ]\n"
50			"	   [ --test ]\n"
51			"	   [ --help ]\n"
52			"	   [ --noflush ]\n"
53			"	   [ --table=<TABLE> ]\n"
54			"          [ --modprobe=<command>]\n", name);
55
56	exit(1);
57}
58
59static struct xtc_handle *create_handle(const char *tablename)
60{
61	struct xtc_handle *handle;
62
63	handle = iptc_init(tablename);
64
65	if (!handle) {
66		/* try to insmod the module if iptc_init failed */
67		xtables_load_ko(xtables_modprobe_program, false);
68		handle = iptc_init(tablename);
69	}
70
71	if (!handle) {
72		xtables_error(PARAMETER_PROBLEM, "%s: unable to initialize "
73			"table '%s'\n", prog_name, tablename);
74		exit(1);
75	}
76	return handle;
77}
78
79static int parse_counters(char *string, struct ipt_counters *ctr)
80{
81	unsigned long long pcnt, bcnt;
82	int ret;
83
84	ret = sscanf(string, "[%llu:%llu]", &pcnt, &bcnt);
85	ctr->pcnt = pcnt;
86	ctr->bcnt = bcnt;
87	return ret == 2;
88}
89
90/* global new argv and argc */
91static char *newargv[255];
92static int newargc;
93
94/* function adding one argument to newargv, updating newargc
95 * returns true if argument added, false otherwise */
96static int add_argv(char *what) {
97	DEBUGP("add_argv: %s\n", what);
98	if (what && newargc + 1 < ARRAY_SIZE(newargv)) {
99		newargv[newargc] = strdup(what);
100		newargc++;
101		return 1;
102	} else {
103		xtables_error(PARAMETER_PROBLEM,
104			"Parser cannot handle more arguments\n");
105		return 0;
106	}
107}
108
109static void free_argv(void) {
110	int i;
111
112	for (i = 0; i < newargc; i++)
113		free(newargv[i]);
114}
115
116int
117iptables_restore_main(int argc, char *argv[])
118{
119	struct xtc_handle *handle = NULL;
120	char buffer[10240];
121	int c;
122	char curtable[IPT_TABLE_MAXNAMELEN + 1];
123	FILE *in;
124	int in_table = 0, testing = 0;
125	const char *tablename = NULL;
126
127	line = 0;
128
129	iptables_globals.program_name = "iptables-restore";
130	c = xtables_init_all(&iptables_globals, NFPROTO_IPV4);
131	if (c < 0) {
132		fprintf(stderr, "%s/%s Failed to initialize xtables\n",
133				iptables_globals.program_name,
134				iptables_globals.program_version);
135		exit(1);
136	}
137#if defined(ALL_INCLUSIVE) || defined(NO_SHARED_LIBS)
138	init_extensions();
139	init_extensions4();
140#endif
141
142	while ((c = getopt_long(argc, argv, "bcvthnM:T:", options, NULL)) != -1) {
143		switch (c) {
144			case 'b':
145				binary = 1;
146				break;
147			case 'c':
148				counters = 1;
149				break;
150			case 'v':
151				verbose = 1;
152				break;
153			case 't':
154				testing = 1;
155				break;
156			case 'h':
157				print_usage("iptables-restore",
158					    IPTABLES_VERSION);
159				break;
160			case 'n':
161				noflush = 1;
162				break;
163			case 'M':
164				xtables_modprobe_program = optarg;
165				break;
166			case 'T':
167				tablename = optarg;
168				break;
169		}
170	}
171
172	if (optind == argc - 1) {
173		in = fopen(argv[optind], "re");
174		if (!in) {
175			fprintf(stderr, "Can't open %s: %s\n", argv[optind],
176				strerror(errno));
177			exit(1);
178		}
179	}
180	else if (optind < argc) {
181		fprintf(stderr, "Unknown arguments found on commandline\n");
182		exit(1);
183	}
184	else in = stdin;
185
186	/* Grab standard input. */
187	while (fgets(buffer, sizeof(buffer), in)) {
188		int ret = 0;
189
190		line++;
191		if (buffer[0] == '\n')
192			continue;
193		else if (buffer[0] == '#') {
194			if (verbose)
195				fputs(buffer, stdout);
196			continue;
197		} else if ((strcmp(buffer, "COMMIT\n") == 0) && (in_table)) {
198			if (!testing) {
199				DEBUGP("Calling commit\n");
200				ret = iptc_commit(handle);
201				iptc_free(handle);
202				handle = NULL;
203			} else {
204				DEBUGP("Not calling commit, testing\n");
205				ret = 1;
206			}
207			in_table = 0;
208		} else if ((buffer[0] == '*') && (!in_table)) {
209			/* New table */
210			char *table;
211
212			table = strtok(buffer+1, " \t\n");
213			DEBUGP("line %u, table '%s'\n", line, table);
214			if (!table) {
215				xtables_error(PARAMETER_PROBLEM,
216					"%s: line %u table name invalid\n",
217					prog_name, line);
218				exit(1);
219			}
220			strncpy(curtable, table, IPT_TABLE_MAXNAMELEN);
221			curtable[IPT_TABLE_MAXNAMELEN] = '\0';
222
223			if (tablename && (strcmp(tablename, table) != 0))
224				continue;
225			if (handle)
226				iptc_free(handle);
227
228			handle = create_handle(table);
229			if (noflush == 0) {
230				DEBUGP("Cleaning all chains of table '%s'\n",
231					table);
232				for_each_chain4(flush_entries4, verbose, 1,
233						handle);
234
235				DEBUGP("Deleting all user-defined chains "
236				       "of table '%s'\n", table);
237				for_each_chain4(delete_chain4, verbose, 0,
238						handle);
239			}
240
241			ret = 1;
242			in_table = 1;
243
244		} else if ((buffer[0] == ':') && (in_table)) {
245			/* New chain. */
246			char *policy, *chain;
247
248			chain = strtok(buffer+1, " \t\n");
249			DEBUGP("line %u, chain '%s'\n", line, chain);
250			if (!chain) {
251				xtables_error(PARAMETER_PROBLEM,
252					   "%s: line %u chain name invalid\n",
253					   prog_name, line);
254				exit(1);
255			}
256
257			if (strlen(chain) >= XT_EXTENSION_MAXNAMELEN)
258				xtables_error(PARAMETER_PROBLEM,
259					   "Invalid chain name `%s' "
260					   "(%u chars max)",
261					   chain, XT_EXTENSION_MAXNAMELEN - 1);
262
263			if (iptc_builtin(chain, handle) <= 0) {
264				if (noflush && iptc_is_chain(chain, handle)) {
265					DEBUGP("Flushing existing user defined chain '%s'\n", chain);
266					if (!iptc_flush_entries(chain, handle))
267						xtables_error(PARAMETER_PROBLEM,
268							   "error flushing chain "
269							   "'%s':%s\n", chain,
270							   strerror(errno));
271				} else {
272					DEBUGP("Creating new chain '%s'\n", chain);
273					if (!iptc_create_chain(chain, handle))
274						xtables_error(PARAMETER_PROBLEM,
275							   "error creating chain "
276							   "'%s':%s\n", chain,
277							   strerror(errno));
278				}
279			}
280
281			policy = strtok(NULL, " \t\n");
282			DEBUGP("line %u, policy '%s'\n", line, policy);
283			if (!policy) {
284				xtables_error(PARAMETER_PROBLEM,
285					   "%s: line %u policy invalid\n",
286					   prog_name, line);
287				exit(1);
288			}
289
290			if (strcmp(policy, "-") != 0) {
291				struct ipt_counters count;
292
293				if (counters) {
294					char *ctrs;
295					ctrs = strtok(NULL, " \t\n");
296
297					if (!ctrs || !parse_counters(ctrs, &count))
298						xtables_error(PARAMETER_PROBLEM,
299							   "invalid policy counters "
300							   "for chain '%s'\n", chain);
301
302				} else {
303					memset(&count, 0,
304					       sizeof(struct ipt_counters));
305				}
306
307				DEBUGP("Setting policy of chain %s to %s\n",
308					chain, policy);
309
310				if (!iptc_set_policy(chain, policy, &count,
311						     handle))
312					xtables_error(OTHER_PROBLEM,
313						"Can't set policy `%s'"
314						" on `%s' line %u: %s\n",
315						policy, chain, line,
316						iptc_strerror(errno));
317			}
318
319			ret = 1;
320
321		} else if (in_table) {
322			int a;
323			char *ptr = buffer;
324			char *pcnt = NULL;
325			char *bcnt = NULL;
326			char *parsestart;
327
328			/* the parser */
329			char *curchar;
330			int quote_open, escaped;
331			size_t param_len;
332
333			/* reset the newargv */
334			newargc = 0;
335
336			if (buffer[0] == '[') {
337				/* we have counters in our input */
338				ptr = strchr(buffer, ']');
339				if (!ptr)
340					xtables_error(PARAMETER_PROBLEM,
341						   "Bad line %u: need ]\n",
342						   line);
343
344				pcnt = strtok(buffer+1, ":");
345				if (!pcnt)
346					xtables_error(PARAMETER_PROBLEM,
347						   "Bad line %u: need :\n",
348						   line);
349
350				bcnt = strtok(NULL, "]");
351				if (!bcnt)
352					xtables_error(PARAMETER_PROBLEM,
353						   "Bad line %u: need ]\n",
354						   line);
355
356				/* start command parsing after counter */
357				parsestart = ptr + 1;
358			} else {
359				/* start command parsing at start of line */
360				parsestart = buffer;
361			}
362
363			add_argv(argv[0]);
364			add_argv("-t");
365			add_argv(curtable);
366
367			if (counters && pcnt && bcnt) {
368				add_argv("--set-counters");
369				add_argv((char *) pcnt);
370				add_argv((char *) bcnt);
371			}
372
373			/* After fighting with strtok enough, here's now
374			 * a 'real' parser. According to Rusty I'm now no
375			 * longer a real hacker, but I can live with that */
376
377			quote_open = 0;
378			escaped = 0;
379			param_len = 0;
380
381			for (curchar = parsestart; *curchar; curchar++) {
382				char param_buffer[1024];
383
384				if (quote_open) {
385					if (escaped) {
386						param_buffer[param_len++] = *curchar;
387						escaped = 0;
388						continue;
389					} else if (*curchar == '\\') {
390						escaped = 1;
391						continue;
392					} else if (*curchar == '"') {
393						quote_open = 0;
394						*curchar = ' ';
395					} else {
396						param_buffer[param_len++] = *curchar;
397						continue;
398					}
399				} else {
400					if (*curchar == '"') {
401						quote_open = 1;
402						continue;
403					}
404				}
405
406				if (*curchar == ' '
407				    || *curchar == '\t'
408				    || * curchar == '\n') {
409					if (!param_len) {
410						/* two spaces? */
411						continue;
412					}
413
414					param_buffer[param_len] = '\0';
415
416					/* check if table name specified */
417					if (!strncmp(param_buffer, "-t", 2)
418					    || !strncmp(param_buffer, "--table", 8)) {
419						xtables_error(PARAMETER_PROBLEM,
420						   "Line %u seems to have a "
421						   "-t table option.\n", line);
422						exit(1);
423					}
424
425					add_argv(param_buffer);
426					param_len = 0;
427				} else {
428					/* regular character, copy to buffer */
429					param_buffer[param_len++] = *curchar;
430
431					if (param_len >= sizeof(param_buffer))
432						xtables_error(PARAMETER_PROBLEM,
433						   "Parameter too long!");
434				}
435			}
436
437			DEBUGP("calling do_command4(%u, argv, &%s, handle):\n",
438				newargc, curtable);
439
440			for (a = 0; a < newargc; a++)
441				DEBUGP("argv[%u]: %s\n", a, newargv[a]);
442
443			ret = do_command4(newargc, newargv,
444					 &newargv[2], &handle);
445
446			free_argv();
447			fflush(stdout);
448		}
449		if (tablename && (strcmp(tablename, curtable) != 0))
450			continue;
451		if (!ret) {
452			fprintf(stderr, "%s: line %u failed\n",
453					prog_name, line);
454			exit(1);
455		}
456	}
457	if (in_table) {
458		fprintf(stderr, "%s: COMMIT expected at line %u\n",
459				prog_name, line + 1);
460		exit(1);
461	}
462
463	fclose(in);
464	return 0;
465}
466