OSDN Git Service

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