www.usr.com/support/gpl/USR9108_release1.3.tar.gz
[bcm963xx.git] / userapps / opensource / iptables / iptables-restore.c
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  * $Id: iptables-restore.c,v 1.34 2004/05/26 16:04:48 gandalf Exp $
8  */
9
10 #include <getopt.h>
11 #include <sys/errno.h>
12 #include <string.h>
13 #include <stdio.h>
14 #include <stdlib.h>
15 #include "iptables.h"
16 #include "libiptc/libiptc.h"
17
18 #ifdef DEBUG
19 #define DEBUGP(x, args...) fprintf(stderr, x, ## args)
20 #else
21 #define DEBUGP(x, args...) 
22 #endif
23
24 static int binary = 0, counters = 0, verbose = 0, noflush = 0;
25
26 /* Keeping track of external matches and targets.  */
27 static struct option options[] = {
28         { "binary", 0, 0, 'b' },
29         { "counters", 0, 0, 'c' },
30         { "verbose", 0, 0, 'v' },
31         { "test", 0, 0, 't' },
32         { "help", 0, 0, 'h' },
33         { "noflush", 0, 0, 'n'},
34         { "modprobe", 1, 0, 'M'},
35         { 0 }
36 };
37
38 static void print_usage(const char *name, const char *version) __attribute__((noreturn));
39
40 static void print_usage(const char *name, const char *version)
41 {
42         fprintf(stderr, "Usage: %s [-b] [-c] [-v] [-t] [-h]\n"
43                         "          [ --binary ]\n"
44                         "          [ --counters ]\n"
45                         "          [ --verbose ]\n"
46                         "          [ --test ]\n"
47                         "          [ --help ]\n"
48                         "          [ --noflush ]\n"
49                         "          [ --modprobe=<command>]\n", name);
50                 
51         exit(1);
52 }
53
54 iptc_handle_t create_handle(const char *tablename, const char* modprobe )
55 {
56         iptc_handle_t handle;
57
58         handle = iptc_init(tablename);
59
60         if (!handle) {
61                 /* try to insmod the module if iptc_init failed */
62                 iptables_insmod("ip_tables", modprobe);
63                 handle = iptc_init(tablename);
64         }
65
66         if (!handle) {
67                 exit_error(PARAMETER_PROBLEM, "%s: unable to initialize"
68                         "table '%s'\n", program_name, tablename);
69                 exit(1);
70         }
71         return handle;
72 }
73
74 int parse_counters(char *string, struct ipt_counters *ctr)
75 {
76         return (sscanf(string, "[%llu:%llu]", (unsigned long long *)&ctr->pcnt, (unsigned long long *)&ctr->bcnt) == 2);
77 }
78
79 /* global new argv and argc */
80 static char *newargv[255];
81 static int newargc;
82
83 /* function adding one argument to newargv, updating newargc 
84  * returns true if argument added, false otherwise */
85 static int add_argv(char *what) {
86         DEBUGP("add_argv: %s\n", what);
87         if (what && ((newargc + 1) < sizeof(newargv)/sizeof(char *))) {
88                 newargv[newargc] = strdup(what);
89                 newargc++;
90                 return 1;
91         } else 
92                 return 0;
93 }
94
95 static void free_argv(void) {
96         int i;
97
98         for (i = 0; i < newargc; i++)
99                 free(newargv[i]);
100 }
101
102 int main(int argc, char *argv[])
103 {
104         iptc_handle_t handle = NULL;
105         char buffer[10240];
106         int c;
107         char curtable[IPT_TABLE_MAXNAMELEN + 1];
108         FILE *in;
109         const char *modprobe = 0;
110         int in_table = 0, testing = 0;
111
112         program_name = "iptables-restore";
113         program_version = IPTABLES_VERSION;
114         line = 0;
115
116 #ifdef NO_SHARED_LIBS
117         init_extensions();
118 #endif
119
120         while ((c = getopt_long(argc, argv, "bcvthnM:", options, NULL)) != -1) {
121                 switch (c) {
122                         case 'b':
123                                 binary = 1;
124                                 break;
125                         case 'c':
126                                 counters = 1;
127                                 break;
128                         case 'v':
129                                 verbose = 1;
130                                 break;
131                         case 't':
132                                 testing = 1;
133                                 break;
134                         case 'h':
135                                 print_usage("iptables-restore",
136                                             IPTABLES_VERSION);
137                                 break;
138                         case 'n':
139                                 noflush = 1;
140                                 break;
141                         case 'M':
142                                 modprobe = optarg;
143                                 break;
144                 }
145         }
146         
147         if (optind == argc - 1) {
148                 in = fopen(argv[optind], "r");
149                 if (!in) {
150                         fprintf(stderr, "Can't open %s: %s", argv[optind],
151                                 strerror(errno));
152                         exit(1);
153                 }
154         }
155         else if (optind < argc) {
156                 fprintf(stderr, "Unknown arguments found on commandline");
157                 exit(1);
158         }
159         else in = stdin;
160         
161         /* Grab standard input. */
162         while (fgets(buffer, sizeof(buffer), in)) {
163                 int ret = 0;
164
165                 line++;
166                 if (buffer[0] == '\n')
167                         continue;
168                 else if (buffer[0] == '#') {
169                         if (verbose)
170                                 fputs(buffer, stdout);
171                         continue;
172                 } else if ((strcmp(buffer, "COMMIT\n") == 0) && (in_table)) {
173                         if (!testing) {
174                                 DEBUGP("Calling commit\n");
175                                 ret = iptc_commit(&handle);
176                         } else {
177                                 DEBUGP("Not calling commit, testing\n");
178                                 ret = 1;
179                         }
180                         in_table = 0;
181                 } else if ((buffer[0] == '*') && (!in_table)) {
182                         /* New table */
183                         char *table;
184
185                         table = strtok(buffer+1, " \t\n");
186                         DEBUGP("line %u, table '%s'\n", line, table);
187                         if (!table) {
188                                 exit_error(PARAMETER_PROBLEM, 
189                                         "%s: line %u table name invalid\n",
190                                         program_name, line);
191                                 exit(1);
192                         }
193                         strncpy(curtable, table, IPT_TABLE_MAXNAMELEN);
194                         curtable[IPT_TABLE_MAXNAMELEN] = '\0';
195
196                         if (handle)
197                                 iptc_free(&handle);
198
199                         handle = create_handle(table, modprobe);
200                         if (noflush == 0) {
201                                 DEBUGP("Cleaning all chains of table '%s'\n",
202                                         table);
203                                 for_each_chain(flush_entries, verbose, 1, 
204                                                 &handle);
205         
206                                 DEBUGP("Deleting all user-defined chains "
207                                        "of table '%s'\n", table);
208                                 for_each_chain(delete_chain, verbose, 0, 
209                                                 &handle) ;
210                         }
211
212                         ret = 1;
213                         in_table = 1;
214
215                 } else if ((buffer[0] == ':') && (in_table)) {
216                         /* New chain. */
217                         char *policy, *chain;
218
219                         chain = strtok(buffer+1, " \t\n");
220                         DEBUGP("line %u, chain '%s'\n", line, chain);
221                         if (!chain) {
222                                 exit_error(PARAMETER_PROBLEM,
223                                            "%s: line %u chain name invalid\n",
224                                            program_name, line);
225                                 exit(1);
226                         }
227
228                         if (!iptc_builtin(chain, handle)) {
229                                 DEBUGP("Creating new chain '%s'\n", chain);
230                                 if (!iptc_create_chain(chain, &handle)) 
231                                         exit_error(PARAMETER_PROBLEM, 
232                                                    "error creating chain "
233                                                    "'%s':%s\n", chain, 
234                                                    strerror(errno));
235                         }
236
237                         policy = strtok(NULL, " \t\n");
238                         DEBUGP("line %u, policy '%s'\n", line, policy);
239                         if (!policy) {
240                                 exit_error(PARAMETER_PROBLEM,
241                                            "%s: line %u policy invalid\n",
242                                            program_name, line);
243                                 exit(1);
244                         }
245
246                         if (strcmp(policy, "-") != 0) {
247                                 struct ipt_counters count;
248
249                                 if (counters) {
250                                         char *ctrs;
251                                         ctrs = strtok(NULL, " \t\n");
252
253                                         parse_counters(ctrs, &count);
254
255                                 } else {
256                                         memset(&count, 0, 
257                                                sizeof(struct ipt_counters));
258                                 }
259
260                                 DEBUGP("Setting policy of chain %s to %s\n",
261                                         chain, policy);
262
263                                 if (!iptc_set_policy(chain, policy, &count,
264                                                      &handle))
265                                         exit_error(OTHER_PROBLEM,
266                                                 "Can't set policy `%s'"
267                                                 " on `%s' line %u: %s\n",
268                                                 chain, policy, line,
269                                                 iptc_strerror(errno));
270                         }
271
272                         ret = 1;
273
274                 } else if (in_table) {
275                         int a;
276                         char *ptr = buffer;
277                         char *pcnt = NULL;
278                         char *bcnt = NULL;
279                         char *parsestart;
280
281                         /* the parser */
282                         char *param_start, *curchar;
283                         int quote_open;
284
285                         /* reset the newargv */
286                         newargc = 0;
287
288                         if (buffer[0] == '[') {
289                                 /* we have counters in our input */
290                                 ptr = strchr(buffer, ']');
291                                 if (!ptr)
292                                         exit_error(PARAMETER_PROBLEM,
293                                                    "Bad line %u: need ]\n",
294                                                    line);
295
296                                 pcnt = strtok(buffer+1, ":");
297                                 if (!pcnt)
298                                         exit_error(PARAMETER_PROBLEM,
299                                                    "Bad line %u: need :\n",
300                                                    line);
301
302                                 bcnt = strtok(NULL, "]");
303                                 if (!bcnt)
304                                         exit_error(PARAMETER_PROBLEM,
305                                                    "Bad line %u: need ]\n",
306                                                    line);
307
308                                 /* start command parsing after counter */
309                                 parsestart = ptr + 1;
310                         } else {
311                                 /* start command parsing at start of line */
312                                 parsestart = buffer;
313                         }
314
315                         add_argv(argv[0]);
316                         add_argv("-t");
317                         add_argv((char *) &curtable);
318                         
319                         if (counters && pcnt && bcnt) {
320                                 add_argv("--set-counters");
321                                 add_argv((char *) pcnt);
322                                 add_argv((char *) bcnt);
323                         }
324
325                         /* After fighting with strtok enough, here's now
326                          * a 'real' parser. According to Rusty I'm now no
327                          * longer a real hacker, but I can live with that */
328
329                         quote_open = 0;
330                         param_start = parsestart;
331                         
332                         for (curchar = parsestart; *curchar; curchar++) {
333                                 if (*curchar == '"') {
334                                         /* quote_open cannot be true if there
335                                          * was no previous character.  Thus, 
336                                          * curchar-1 has to be within bounds */
337                                         if (quote_open && 
338                                             *(curchar-1) != '\\') {
339                                                 quote_open = 0;
340                                                 *curchar = ' ';
341                                         } else {
342                                                 quote_open = 1;
343                                                 param_start++;
344                                         }
345                                 } 
346                                 if (*curchar == ' '
347                                     || *curchar == '\t'
348                                     || * curchar == '\n') {
349                                         char param_buffer[1024];
350                                         int param_len = curchar-param_start;
351
352                                         if (quote_open)
353                                                 continue;
354
355                                         if (!param_len) {
356                                                 /* two spaces? */
357                                                 param_start++;
358                                                 continue;
359                                         }
360                                         
361                                         /* end of one parameter */
362                                         strncpy(param_buffer, param_start,
363                                                 param_len);
364                                         *(param_buffer+param_len) = '\0';
365
366                                         /* check if table name specified */
367                                         if (!strncmp(param_buffer, "-t", 3)
368                                             || !strncmp(param_buffer, "--table", 8)) {
369                                                 exit_error(PARAMETER_PROBLEM, 
370                                                    "Line %u seems to have a "
371                                                    "-t table option.\n", line);
372                                                 exit(1);
373                                         }
374
375                                         add_argv(param_buffer);
376                                         param_start += param_len + 1;
377                                 } else {
378                                         /* regular character, skip */
379                                 }
380                         }
381
382                         DEBUGP("calling do_command(%u, argv, &%s, handle):\n",
383                                 newargc, curtable);
384
385                         for (a = 0; a < newargc; a++)
386                                 DEBUGP("argv[%u]: %s\n", a, newargv[a]);
387
388                         ret = do_command(newargc, newargv, 
389                                          &newargv[2], &handle);
390
391                         free_argv();
392                 }
393                 if (!ret) {
394                         fprintf(stderr, "%s: line %u failed\n",
395                                         program_name, line);
396                         exit(1);
397                 }
398         }
399         if (in_table) {
400                 fprintf(stderr, "%s: COMMIT expected at line %u\n",
401                                 program_name, line + 1);
402                 exit(1);
403         }
404
405         return 0;
406 }