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