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