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