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