Tomato 1.26 beta(1766)
[tomato/tomato-null.git] / release / src / router / iptables / iptables.c
blob3dfcc990b034ca5a9f9d44e35421da6fc2eea2f9
1 /* Code to take an iptables-style command line and do it. */
3 /*
4 * Author: Paul.Russell@rustcorp.com.au and mneuling@radlogic.com.au
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>
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.
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.
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.
28 #include <getopt.h>
29 #include <string.h>
30 #include <netdb.h>
31 #include <errno.h>
32 #include <stdio.h>
33 #include <stdlib.h>
34 #include <dlfcn.h>
35 #include <ctype.h>
36 #include <stdarg.h>
37 #include <limits.h>
38 #include <unistd.h>
39 #include <iptables.h>
40 #include <fcntl.h>
41 #include <sys/wait.h>
42 #include <sys/utsname.h>
44 #ifndef TRUE
45 #define TRUE 1
46 #endif
47 #ifndef FALSE
48 #define FALSE 0
49 #endif
51 #ifndef PROC_SYS_MODPROBE
52 #define PROC_SYS_MODPROBE "/proc/sys/kernel/modprobe"
53 #endif
55 #define FMT_NUMERIC 0x0001
56 #define FMT_NOCOUNTS 0x0002
57 #define FMT_KILOMEGAGIGA 0x0004
58 #define FMT_OPTIONS 0x0008
59 #define FMT_NOTABLE 0x0010
60 #define FMT_NOTARGET 0x0020
61 #define FMT_VIA 0x0040
62 #define FMT_NONEWLINE 0x0080
63 #define FMT_LINENUMBERS 0x0100
65 #define FMT_PRINT_RULE (FMT_NOCOUNTS | FMT_OPTIONS | FMT_VIA \
66 | FMT_NUMERIC | FMT_NOTABLE)
67 #define FMT(tab,notab) ((format) & FMT_NOTABLE ? (notab) : (tab))
70 #define CMD_NONE 0x0000U
71 #define CMD_INSERT 0x0001U
72 #define CMD_DELETE 0x0002U
73 #define CMD_DELETE_NUM 0x0004U
74 #define CMD_REPLACE 0x0008U
75 #define CMD_APPEND 0x0010U
76 #define CMD_LIST 0x0020U
77 #define CMD_FLUSH 0x0040U
78 #define CMD_ZERO 0x0080U
79 #define CMD_NEW_CHAIN 0x0100U
80 #define CMD_DELETE_CHAIN 0x0200U
81 #define CMD_SET_POLICY 0x0400U
82 #define CMD_RENAME_CHAIN 0x0800U
83 #define NUMBER_OF_CMD 13
84 static const char cmdflags[] = { 'I', 'D', 'D', 'R', 'A', 'L', 'F', 'Z',
85 'N', 'X', 'P', 'E' };
87 #define OPTION_OFFSET 256
89 #define OPT_NONE 0x00000U
90 #define OPT_NUMERIC 0x00001U
91 #define OPT_SOURCE 0x00002U
92 #define OPT_DESTINATION 0x00004U
93 #define OPT_PROTOCOL 0x00008U
94 #define OPT_JUMP 0x00010U
95 #define OPT_VERBOSE 0x00020U
96 #define OPT_EXPANDED 0x00040U
97 #define OPT_VIANAMEIN 0x00080U
98 #define OPT_VIANAMEOUT 0x00100U
99 #define OPT_FRAGMENT 0x00200U
100 #define OPT_LINENUMBERS 0x00400U
101 #define OPT_COUNTERS 0x00800U
102 #define NUMBER_OF_OPT 12
103 static const char optflags[NUMBER_OF_OPT]
104 = { 'n', 's', 'd', 'p', 'j', 'v', 'x', 'i', 'o', 'f', '0', 'c'};
106 static struct option original_opts[] = {
107 { "append", 1, 0, 'A' },
108 { "delete", 1, 0, 'D' },
109 { "insert", 1, 0, 'I' },
110 { "replace", 1, 0, 'R' },
111 { "list", 2, 0, 'L' },
112 { "flush", 2, 0, 'F' },
113 { "zero", 2, 0, 'Z' },
114 { "new-chain", 1, 0, 'N' },
115 { "delete-chain", 2, 0, 'X' },
116 { "rename-chain", 1, 0, 'E' },
117 { "policy", 1, 0, 'P' },
118 { "source", 1, 0, 's' },
119 { "destination", 1, 0, 'd' },
120 { "src", 1, 0, 's' }, /* synonym */
121 { "dst", 1, 0, 'd' }, /* synonym */
122 { "protocol", 1, 0, 'p' },
123 { "in-interface", 1, 0, 'i' },
124 { "jump", 1, 0, 'j' },
125 { "table", 1, 0, 't' },
126 { "match", 1, 0, 'm' },
127 { "numeric", 0, 0, 'n' },
128 { "out-interface", 1, 0, 'o' },
129 { "verbose", 0, 0, 'v' },
130 { "exact", 0, 0, 'x' },
131 { "fragments", 0, 0, 'f' },
132 { "version", 0, 0, 'V' },
133 { "help", 2, 0, 'h' },
134 { "line-numbers", 0, 0, '0' },
135 { "modprobe", 1, 0, 'M' },
136 { "set-counters", 1, 0, 'c' },
137 { "goto", 1, 0, 'g' },
138 { 0 }
141 /* we need this for iptables-restore. iptables-restore.c sets line to the
142 * current line of the input file, in order to give a more precise error
143 * message. iptables itself doesn't need this, so it is initialized to the
144 * magic number of -1 */
145 int line = -1;
147 static struct option *opts = original_opts;
148 static unsigned int global_option_offset = 0;
150 /* Table of legal combinations of commands and options. If any of the
151 * given commands make an option legal, that option is legal (applies to
152 * CMD_LIST and CMD_ZERO only).
153 * Key:
154 * + compulsory
155 * x illegal
156 * optional
159 static char commands_v_options[NUMBER_OF_CMD][NUMBER_OF_OPT] =
160 /* Well, it's better than "Re: Linux vs FreeBSD" */
162 /* -n -s -d -p -j -v -x -i -o -f --line -c */
163 /*INSERT*/ {'x',' ',' ',' ',' ',' ','x',' ',' ',' ','x',' '},
164 /*DELETE*/ {'x',' ',' ',' ',' ',' ','x',' ',' ',' ','x','x'},
165 /*DELETE_NUM*/{'x','x','x','x','x',' ','x','x','x','x','x','x'},
166 /*REPLACE*/ {'x',' ',' ',' ',' ',' ','x',' ',' ',' ','x',' '},
167 /*APPEND*/ {'x',' ',' ',' ',' ',' ','x',' ',' ',' ','x',' '},
168 /*LIST*/ {' ','x','x','x','x',' ',' ','x','x','x',' ','x'},
169 /*FLUSH*/ {'x','x','x','x','x',' ','x','x','x','x','x','x'},
170 /*ZERO*/ {'x','x','x','x','x',' ','x','x','x','x','x','x'},
171 /*NEW_CHAIN*/ {'x','x','x','x','x',' ','x','x','x','x','x','x'},
172 /*DEL_CHAIN*/ {'x','x','x','x','x',' ','x','x','x','x','x','x'},
173 /*SET_POLICY*/{'x','x','x','x','x',' ','x','x','x','x','x','x'},
174 /*RENAME*/ {'x','x','x','x','x',' ','x','x','x','x','x','x'}
177 static int inverse_for_options[NUMBER_OF_OPT] =
179 /* -n */ 0,
180 /* -s */ IPT_INV_SRCIP,
181 /* -d */ IPT_INV_DSTIP,
182 /* -p */ IPT_INV_PROTO,
183 /* -j */ 0,
184 /* -v */ 0,
185 /* -x */ 0,
186 /* -i */ IPT_INV_VIA_IN,
187 /* -o */ IPT_INV_VIA_OUT,
188 /* -f */ IPT_INV_FRAG,
189 /*--line*/ 0,
190 /* -c */ 0,
193 const char *program_version;
194 const char *program_name;
195 char *lib_dir;
197 int kernel_version;
199 /* the path to command to load kernel module */
200 const char *modprobe = NULL;
202 /* Keeping track of external matches and targets: linked lists. */
203 struct iptables_match *iptables_matches = NULL;
204 struct iptables_target *iptables_targets = NULL;
206 /* Extra debugging from libiptc */
207 extern void dump_entries(const iptc_handle_t handle);
209 /* A few hardcoded protocols for 'all' and in case the user has no
210 /etc/protocols */
211 struct pprot {
212 char *name;
213 u_int8_t num;
216 /* Primitive headers... */
217 /* defined in netinet/in.h */
218 #if 0
219 #ifndef IPPROTO_ESP
220 #define IPPROTO_ESP 50
221 #endif
222 #ifndef IPPROTO_AH
223 #define IPPROTO_AH 51
224 #endif
225 #endif
227 static const struct pprot chain_protos[] = {
228 { "tcp", IPPROTO_TCP },
229 { "udp", IPPROTO_UDP },
230 { "icmp", IPPROTO_ICMP },
231 { "esp", IPPROTO_ESP },
232 { "ah", IPPROTO_AH },
233 { "sctp", IPPROTO_SCTP },
236 static char *
237 proto_to_name(u_int8_t proto, int nolookup)
239 unsigned int i;
241 if (proto && !nolookup) {
242 struct protoent *pent = getprotobynumber(proto);
243 if (pent)
244 return pent->p_name;
247 for (i = 0; i < sizeof(chain_protos)/sizeof(struct pprot); i++)
248 if (chain_protos[i].num == proto)
249 return chain_protos[i].name;
251 return NULL;
255 service_to_port(const char *name, const char *proto)
257 struct servent *service;
259 if ((service = getservbyname(name, proto)) != NULL)
260 return ntohs((unsigned short) service->s_port);
262 return -1;
265 u_int16_t
266 parse_port(const char *port, const char *proto)
268 unsigned int portnum;
270 if ((string_to_number(port, 0, 65535, &portnum)) != -1 ||
271 (portnum = service_to_port(port, proto)) != -1)
272 return (u_int16_t)portnum;
274 exit_error(PARAMETER_PROBLEM,
275 "invalid port/service `%s' specified", port);
278 enum {
279 IPT_DOTTED_ADDR = 0,
280 IPT_DOTTED_MASK
283 static struct in_addr *
284 __dotted_to_addr(const char *dotted, int type)
286 static struct in_addr addr;
287 unsigned char *addrp;
288 char *p, *q;
289 unsigned int onebyte;
290 int i;
291 char buf[20];
293 /* copy dotted string, because we need to modify it */
294 strncpy(buf, dotted, sizeof(buf) - 1);
295 buf[sizeof(buf) - 1] = '\0';
296 addrp = (unsigned char *) &(addr.s_addr);
298 p = buf;
299 for (i = 0; i < 3; i++) {
300 if ((q = strchr(p, '.')) == NULL) {
301 if (type == IPT_DOTTED_ADDR) {
302 /* autocomplete, this is a network address */
303 if (string_to_number(p, 0, 255, &onebyte) == -1)
304 return (struct in_addr *) NULL;
306 addrp[i] = (unsigned char) onebyte;
307 while (i < 3)
308 addrp[++i] = 0;
310 return &addr;
311 } else
312 return (struct in_addr *) NULL;
315 *q = '\0';
316 if (string_to_number(p, 0, 255, &onebyte) == -1)
317 return (struct in_addr *) NULL;
319 addrp[i] = (unsigned char) onebyte;
320 p = q + 1;
323 /* we've checked 3 bytes, now we check the last one */
324 if (string_to_number(p, 0, 255, &onebyte) == -1)
325 return (struct in_addr *) NULL;
327 addrp[3] = (unsigned char) onebyte;
329 return &addr;
332 struct in_addr *
333 dotted_to_addr(const char *dotted)
335 return __dotted_to_addr(dotted, IPT_DOTTED_ADDR);
338 struct in_addr *
339 dotted_to_mask(const char *dotted)
341 return __dotted_to_addr(dotted, IPT_DOTTED_MASK);
344 static struct in_addr *
345 network_to_addr(const char *name)
347 struct netent *net;
348 static struct in_addr addr;
350 if ((net = getnetbyname(name)) != NULL) {
351 if (net->n_addrtype != AF_INET)
352 return (struct in_addr *) NULL;
353 addr.s_addr = htonl((unsigned long) net->n_net);
354 return &addr;
357 return (struct in_addr *) NULL;
360 static void
361 inaddrcpy(struct in_addr *dst, struct in_addr *src)
363 /* memcpy(dst, src, sizeof(struct in_addr)); */
364 dst->s_addr = src->s_addr;
367 static void free_opts(int reset_offset)
369 if (opts != original_opts) {
370 free(opts);
371 opts = original_opts;
372 if (reset_offset)
373 global_option_offset = 0;
377 void
378 exit_error(enum exittype status, char *msg, ...)
380 va_list args;
382 va_start(args, msg);
383 fprintf(stderr, "%s v%s: ", program_name, program_version);
384 vfprintf(stderr, msg, args);
385 va_end(args);
386 fprintf(stderr, "\n");
387 if (status == PARAMETER_PROBLEM)
388 exit_tryhelp(status);
389 if (status == VERSION_PROBLEM)
390 fprintf(stderr,
391 "Perhaps iptables or your kernel needs to be upgraded.\n");
392 /* On error paths, make sure that we don't leak memory */
393 free_opts(1);
394 exit(status);
397 void
398 exit_tryhelp(int status)
400 if (line != -1)
401 fprintf(stderr, "Error occurred at line: %d\n", line);
402 fprintf(stderr, "Try `%s -h' or '%s --help' for more information.\n",
403 program_name, program_name );
404 free_opts(1);
405 exit(status);
408 void
409 exit_printhelp(struct iptables_rule_match *matches)
411 struct iptables_rule_match *matchp = NULL;
412 struct iptables_target *t = NULL;
414 printf("%s v%s\n\n"
415 "Usage: %s -[AD] chain rule-specification [options]\n"
416 " %s -[RI] chain rulenum rule-specification [options]\n"
417 " %s -D chain rulenum [options]\n"
418 " %s -[LFZ] [chain] [options]\n"
419 " %s -[NX] chain\n"
420 " %s -E old-chain-name new-chain-name\n"
421 " %s -P chain target [options]\n"
422 " %s -h (print this help information)\n\n",
423 program_name, program_version, program_name, program_name,
424 program_name, program_name, program_name, program_name,
425 program_name, program_name);
427 printf(
428 "Commands:\n"
429 "Either long or short options are allowed.\n"
430 " --append -A chain Append to chain\n"
431 " --delete -D chain Delete matching rule from chain\n"
432 " --delete -D chain rulenum\n"
433 " Delete rule rulenum (1 = first) from chain\n"
434 " --insert -I chain [rulenum]\n"
435 " Insert in chain as rulenum (default 1=first)\n"
436 " --replace -R chain rulenum\n"
437 " Replace rule rulenum (1 = first) in chain\n"
438 " --list -L [chain] List the rules in a chain or all chains\n"
439 " --flush -F [chain] Delete all rules in chain or all chains\n"
440 " --zero -Z [chain] Zero counters in chain or all chains\n"
441 " --new -N chain Create a new user-defined chain\n"
442 " --delete-chain\n"
443 " -X [chain] Delete a user-defined chain\n"
444 " --policy -P chain target\n"
445 " Change policy on chain to target\n"
446 " --rename-chain\n"
447 " -E old-chain new-chain\n"
448 " Change chain name, (moving any references)\n"
450 "Options:\n"
451 " --proto -p [!] proto protocol: by number or name, eg. `tcp'\n"
452 " --source -s [!] address[/mask]\n"
453 " source specification\n"
454 " --destination -d [!] address[/mask]\n"
455 " destination specification\n"
456 " --in-interface -i [!] input name[+]\n"
457 " network interface name ([+] for wildcard)\n"
458 " --jump -j target\n"
459 " target for rule (may load target extension)\n"
460 #ifdef IPT_F_GOTO
461 " --goto -g chain\n"
462 " jump to chain with no return\n"
463 #endif
464 " --match -m match\n"
465 " extended match (may load extension)\n"
466 " --numeric -n numeric output of addresses and ports\n"
467 " --out-interface -o [!] output name[+]\n"
468 " network interface name ([+] for wildcard)\n"
469 " --table -t table table to manipulate (default: `filter')\n"
470 " --verbose -v verbose mode\n"
471 " --line-numbers print line numbers when listing\n"
472 " --exact -x expand numbers (display exact values)\n"
473 "[!] --fragment -f match second or further fragments only\n"
474 " --modprobe=<command> try to insert modules using this command\n"
475 " --set-counters PKTS BYTES set the counter during insert/append\n"
476 "[!] --version -V print package version.\n");
478 /* Print out any special helps. A user might like to be able
479 to add a --help to the commandline, and see expected
480 results. So we call help for all specified matches & targets */
481 for (t = iptables_targets; t ;t = t->next) {
482 if (t->used) {
483 printf("\n");
484 t->help();
487 for (matchp = matches; matchp; matchp = matchp->next) {
488 printf("\n");
489 matchp->match->help();
491 exit(0);
494 static void
495 generic_opt_check(int command, int options)
497 int i, j, legal = 0;
499 /* Check that commands are valid with options. Complicated by the
500 * fact that if an option is legal with *any* command given, it is
501 * legal overall (ie. -z and -l).
503 for (i = 0; i < NUMBER_OF_OPT; i++) {
504 legal = 0; /* -1 => illegal, 1 => legal, 0 => undecided. */
506 for (j = 0; j < NUMBER_OF_CMD; j++) {
507 if (!(command & (1<<j)))
508 continue;
510 if (!(options & (1<<i))) {
511 if (commands_v_options[j][i] == '+')
512 exit_error(PARAMETER_PROBLEM,
513 "You need to supply the `-%c' "
514 "option for this command\n",
515 optflags[i]);
516 } else {
517 if (commands_v_options[j][i] != 'x')
518 legal = 1;
519 else if (legal == 0)
520 legal = -1;
523 if (legal == -1)
524 exit_error(PARAMETER_PROBLEM,
525 "Illegal option `-%c' with this command\n",
526 optflags[i]);
530 static char
531 opt2char(int option)
533 const char *ptr;
534 for (ptr = optflags; option > 1; option >>= 1, ptr++);
536 return *ptr;
539 static char
540 cmd2char(int option)
542 const char *ptr;
543 for (ptr = cmdflags; option > 1; option >>= 1, ptr++);
545 return *ptr;
548 static void
549 add_command(unsigned int *cmd, const int newcmd, const int othercmds,
550 int invert)
552 if (invert)
553 exit_error(PARAMETER_PROBLEM, "unexpected ! flag");
554 if (*cmd & (~othercmds))
555 exit_error(PARAMETER_PROBLEM, "Can't use -%c with -%c\n",
556 cmd2char(newcmd), cmd2char(*cmd & (~othercmds)));
557 *cmd |= newcmd;
561 check_inverse(const char option[], int *invert, int *optind, int argc)
563 if (option && strcmp(option, "!") == 0) {
564 if (*invert)
565 exit_error(PARAMETER_PROBLEM,
566 "Multiple `!' flags not allowed");
567 *invert = TRUE;
568 if (optind) {
569 *optind = *optind+1;
570 if (argc && *optind > argc)
571 exit_error(PARAMETER_PROBLEM,
572 "no argument following `!'");
575 return TRUE;
577 return FALSE;
580 static void *
581 fw_calloc(size_t count, size_t size)
583 void *p;
585 if ((p = calloc(count, size)) == NULL) {
586 perror("iptables: calloc failed");
587 exit(1);
589 return p;
592 static void *
593 fw_malloc(size_t size)
595 void *p;
597 if ((p = malloc(size)) == NULL) {
598 perror("iptables: malloc failed");
599 exit(1);
601 return p;
604 static struct in_addr *
605 host_to_addr(const char *name, unsigned int *naddr)
607 struct hostent *host;
608 struct in_addr *addr;
609 unsigned int i;
611 *naddr = 0;
612 if ((host = gethostbyname(name)) != NULL) {
613 if (host->h_addrtype != AF_INET ||
614 host->h_length != sizeof(struct in_addr))
615 return (struct in_addr *) NULL;
617 while (host->h_addr_list[*naddr] != (char *) NULL)
618 (*naddr)++;
619 addr = fw_calloc(*naddr, sizeof(struct in_addr) * *naddr);
620 for (i = 0; i < *naddr; i++)
621 inaddrcpy(&(addr[i]),
622 (struct in_addr *) host->h_addr_list[i]);
623 return addr;
626 return (struct in_addr *) NULL;
629 static char *
630 addr_to_host(const struct in_addr *addr)
632 struct hostent *host;
634 if ((host = gethostbyaddr((char *) addr,
635 sizeof(struct in_addr), AF_INET)) != NULL)
636 return (char *) host->h_name;
638 return (char *) NULL;
642 * All functions starting with "parse" should succeed, otherwise
643 * the program fails.
644 * Most routines return pointers to static data that may change
645 * between calls to the same or other routines with a few exceptions:
646 * "host_to_addr", "parse_hostnetwork", and "parse_hostnetworkmask"
647 * return global static data.
650 static struct in_addr *
651 parse_hostnetwork(const char *name, unsigned int *naddrs)
653 struct in_addr *addrp, *addrptmp;
655 if ((addrptmp = dotted_to_addr(name)) != NULL ||
656 (addrptmp = network_to_addr(name)) != NULL) {
657 addrp = fw_malloc(sizeof(struct in_addr));
658 inaddrcpy(addrp, addrptmp);
659 *naddrs = 1;
660 return addrp;
662 if ((addrp = host_to_addr(name, naddrs)) != NULL)
663 return addrp;
665 exit_error(PARAMETER_PROBLEM, "host/network `%s' not found", name);
668 static struct in_addr *
669 parse_mask(char *mask)
671 static struct in_addr maskaddr;
672 struct in_addr *addrp;
673 unsigned int bits;
675 if (mask == NULL) {
676 /* no mask at all defaults to 32 bits */
677 maskaddr.s_addr = 0xFFFFFFFF;
678 return &maskaddr;
680 if ((addrp = dotted_to_mask(mask)) != NULL)
681 /* dotted_to_addr already returns a network byte order addr */
682 return addrp;
683 if (string_to_number(mask, 0, 32, &bits) == -1)
684 exit_error(PARAMETER_PROBLEM,
685 "invalid mask `%s' specified", mask);
686 if (bits != 0) {
687 maskaddr.s_addr = htonl(0xFFFFFFFF << (32 - bits));
688 return &maskaddr;
691 maskaddr.s_addr = 0L;
692 return &maskaddr;
695 void
696 parse_hostnetworkmask(const char *name, struct in_addr **addrpp,
697 struct in_addr *maskp, unsigned int *naddrs)
699 struct in_addr *addrp;
700 char buf[256];
701 char *p;
702 int i, j, k, n;
704 strncpy(buf, name, sizeof(buf) - 1);
705 buf[sizeof(buf) - 1] = '\0';
706 if ((p = strrchr(buf, '/')) != NULL) {
707 *p = '\0';
708 addrp = parse_mask(p + 1);
709 } else
710 addrp = parse_mask(NULL);
711 inaddrcpy(maskp, addrp);
713 /* if a null mask is given, the name is ignored, like in "any/0" */
714 if (maskp->s_addr == 0L)
715 strcpy(buf, "0.0.0.0");
717 addrp = *addrpp = parse_hostnetwork(buf, naddrs);
718 n = *naddrs;
719 for (i = 0, j = 0; i < n; i++) {
720 addrp[j++].s_addr &= maskp->s_addr;
721 for (k = 0; k < j - 1; k++) {
722 if (addrp[k].s_addr == addrp[j - 1].s_addr) {
723 (*naddrs)--;
724 j--;
725 break;
731 struct iptables_match *
732 find_match(const char *name, enum ipt_tryload tryload, struct iptables_rule_match **matches)
734 struct iptables_match *ptr;
736 for (ptr = iptables_matches; ptr; ptr = ptr->next) {
737 if (strcmp(name, ptr->name) == 0) {
738 struct iptables_match *clone;
740 /* First match of this type: */
741 if (ptr->m == NULL)
742 break;
744 /* Second and subsequent clones */
745 clone = fw_malloc(sizeof(struct iptables_match));
746 memcpy(clone, ptr, sizeof(struct iptables_match));
747 clone->mflags = 0;
748 /* This is a clone: */
749 clone->next = clone;
751 ptr = clone;
752 break;
756 #ifndef NO_SHARED_LIBS
757 if (!ptr && tryload != DONT_LOAD && tryload != DURING_LOAD) {
758 char path[strlen(lib_dir) + sizeof("/libipt_.so")
759 + strlen(name)];
760 #if 1 // for easier testing zzz
761 char s[256];
762 sprintf(s, "%s/libipt_%s.so", "/etc/iptext/", name);
763 if (dlopen(s, RTLD_NOW)) goto OPENED;
764 #endif
765 sprintf(path, "%s/libipt_%s.so", lib_dir, name);
766 if (dlopen(path, RTLD_NOW)) {
767 OPENED:
768 /* Found library. If it didn't register itself,
769 maybe they specified target as match. */
770 ptr = find_match(name, DONT_LOAD, NULL);
772 if (!ptr)
773 exit_error(PARAMETER_PROBLEM,
774 "Couldn't load match `%s'\n",
775 name);
776 } else if (tryload == LOAD_MUST_SUCCEED)
777 exit_error(PARAMETER_PROBLEM,
778 "Couldn't load match `%s':%s\n",
779 name, dlerror());
781 #else
782 if (ptr && !ptr->loaded) {
783 if (tryload != DONT_LOAD)
784 ptr->loaded = 1;
785 else
786 ptr = NULL;
788 if(!ptr && (tryload == LOAD_MUST_SUCCEED)) {
789 exit_error(PARAMETER_PROBLEM,
790 "Couldn't find match `%s'\n", name);
792 #endif
794 if (ptr && matches) {
795 struct iptables_rule_match **i;
796 struct iptables_rule_match *newentry;
798 newentry = fw_malloc(sizeof(struct iptables_rule_match));
800 for (i = matches; *i; i = &(*i)->next) {
801 if (strcmp(name, (*i)->match->name) == 0)
802 (*i)->completed = 1;
804 newentry->match = ptr;
805 newentry->completed = 0;
806 newentry->next = NULL;
807 *i = newentry;
810 return ptr;
813 /* Christophe Burki wants `-p 6' to imply `-m tcp'. */
814 static struct iptables_match *
815 find_proto(const char *pname, enum ipt_tryload tryload, int nolookup, struct iptables_rule_match **matches)
817 unsigned int proto;
819 if (string_to_number(pname, 0, 255, &proto) != -1) {
820 char *protoname = proto_to_name(proto, nolookup);
822 if (protoname)
823 return find_match(protoname, tryload, matches);
824 } else
825 return find_match(pname, tryload, matches);
827 return NULL;
830 u_int16_t
831 parse_protocol(const char *s)
833 unsigned int proto;
835 if (string_to_number(s, 0, 255, &proto) == -1) {
836 struct protoent *pent;
838 /* first deal with the special case of 'all' to prevent
839 * people from being able to redefine 'all' in nsswitch
840 * and/or provoke expensive [not working] ldap/nis/...
841 * lookups */
842 if (!strcmp(s, "all"))
843 return 0;
845 if ((pent = getprotobyname(s)))
846 proto = pent->p_proto;
847 else {
848 unsigned int i;
849 for (i = 0;
850 i < sizeof(chain_protos)/sizeof(struct pprot);
851 i++) {
852 if (strcmp(s, chain_protos[i].name) == 0) {
853 proto = chain_protos[i].num;
854 break;
857 if (i == sizeof(chain_protos)/sizeof(struct pprot))
858 exit_error(PARAMETER_PROBLEM,
859 "unknown protocol `%s' specified",
864 return (u_int16_t)proto;
867 void parse_interface(const char *arg, char *vianame, unsigned char *mask)
869 int vialen = strlen(arg);
870 unsigned int i;
872 memset(mask, 0, IFNAMSIZ);
873 memset(vianame, 0, IFNAMSIZ);
875 if (vialen + 1 > IFNAMSIZ)
876 exit_error(PARAMETER_PROBLEM,
877 "interface name `%s' must be shorter than IFNAMSIZ"
878 " (%i)", arg, IFNAMSIZ-1);
880 strcpy(vianame, arg);
881 if ((vialen == 0) || (vialen == 1 && vianame[0] == '+'))
882 memset(mask, 0, IFNAMSIZ);
883 else if (vianame[vialen - 1] == '+') {
884 memset(mask, 0xFF, vialen - 1);
885 memset(mask + vialen - 1, 0, IFNAMSIZ - vialen + 1);
886 /* Don't remove `+' here! -HW */
887 } else {
888 /* Include nul-terminator in match */
889 memset(mask, 0xFF, vialen + 1);
890 memset(mask + vialen + 1, 0, IFNAMSIZ - vialen - 1);
891 for (i = 0; vianame[i]; i++) {
892 if (vianame[i] == ':' ||
893 vianame[i] == '!' ||
894 vianame[i] == '*') {
895 printf("Warning: weird character in interface"
896 " `%s' (No aliases, :, ! or *).\n",
897 vianame);
898 break;
904 /* Can't be zero. */
905 static int
906 parse_rulenumber(const char *rule)
908 unsigned int rulenum;
910 if (string_to_number(rule, 1, INT_MAX, &rulenum) == -1)
911 exit_error(PARAMETER_PROBLEM,
912 "Invalid rule number `%s'", rule);
914 return rulenum;
917 static const char *
918 parse_target(const char *targetname)
920 const char *ptr;
922 if (strlen(targetname) < 1)
923 exit_error(PARAMETER_PROBLEM,
924 "Invalid target name (too short)");
926 if (strlen(targetname)+1 > sizeof(ipt_chainlabel))
927 exit_error(PARAMETER_PROBLEM,
928 "Invalid target name `%s' (%u chars max)",
929 targetname, (unsigned int)sizeof(ipt_chainlabel)-1);
931 for (ptr = targetname; *ptr; ptr++)
932 if (isspace(*ptr))
933 exit_error(PARAMETER_PROBLEM,
934 "Invalid target name `%s'", targetname);
935 return targetname;
938 static char *
939 addr_to_network(const struct in_addr *addr)
941 struct netent *net;
943 if ((net = getnetbyaddr((long) ntohl(addr->s_addr), AF_INET)) != NULL)
944 return (char *) net->n_name;
946 return (char *) NULL;
949 char *
950 addr_to_dotted(const struct in_addr *addrp)
952 static char buf[20];
953 const unsigned char *bytep;
955 bytep = (const unsigned char *) &(addrp->s_addr);
956 sprintf(buf, "%d.%d.%d.%d", bytep[0], bytep[1], bytep[2], bytep[3]);
957 return buf;
960 char *
961 addr_to_anyname(const struct in_addr *addr)
963 char *name;
965 if ((name = addr_to_host(addr)) != NULL ||
966 (name = addr_to_network(addr)) != NULL)
967 return name;
969 return addr_to_dotted(addr);
972 char *
973 mask_to_dotted(const struct in_addr *mask)
975 int i;
976 static char buf[20];
977 u_int32_t maskaddr, bits;
979 maskaddr = ntohl(mask->s_addr);
981 if (maskaddr == 0xFFFFFFFFL)
982 /* we don't want to see "/32" */
983 return "";
985 i = 32;
986 bits = 0xFFFFFFFEL;
987 while (--i >= 0 && maskaddr != bits)
988 bits <<= 1;
989 if (i >= 0)
990 sprintf(buf, "/%d", i);
991 else
992 /* mask was not a decent combination of 1's and 0's */
993 sprintf(buf, "/%s", addr_to_dotted(mask));
995 return buf;
999 string_to_number_ll(const char *s, unsigned long long min, unsigned long long max,
1000 unsigned long long *ret)
1002 unsigned long long number;
1003 char *end;
1005 /* Handle hex, octal, etc. */
1006 errno = 0;
1007 number = strtoull(s, &end, 0);
1008 if (*end == '\0' && end != s) {
1009 /* we parsed a number, let's see if we want this */
1010 if (errno != ERANGE && min <= number && (!max || number <= max)) {
1011 *ret = number;
1012 return 0;
1015 return -1;
1019 string_to_number_l(const char *s, unsigned long min, unsigned long max,
1020 unsigned long *ret)
1022 int result;
1023 unsigned long long number;
1025 result = string_to_number_ll(s, min, max, &number);
1026 *ret = (unsigned long)number;
1028 return result;
1031 int string_to_number(const char *s, unsigned int min, unsigned int max,
1032 unsigned int *ret)
1034 int result;
1035 unsigned long number;
1037 result = string_to_number_l(s, min, max, &number);
1038 *ret = (unsigned int)number;
1040 return result;
1043 static void
1044 set_option(unsigned int *options, unsigned int option, u_int8_t *invflg,
1045 int invert)
1047 if (*options & option)
1048 exit_error(PARAMETER_PROBLEM, "multiple -%c flags not allowed",
1049 opt2char(option));
1050 *options |= option;
1052 if (invert) {
1053 unsigned int i;
1054 for (i = 0; 1 << i != option; i++);
1056 if (!inverse_for_options[i])
1057 exit_error(PARAMETER_PROBLEM,
1058 "cannot have ! before -%c",
1059 opt2char(option));
1060 *invflg |= inverse_for_options[i];
1064 struct iptables_target *
1065 find_target(const char *name, enum ipt_tryload tryload)
1067 struct iptables_target *ptr;
1069 /* Standard target? */
1070 if (strcmp(name, "") == 0
1071 || strcmp(name, IPTC_LABEL_ACCEPT) == 0
1072 || strcmp(name, IPTC_LABEL_DROP) == 0
1073 || strcmp(name, IPTC_LABEL_QUEUE) == 0
1074 || strcmp(name, IPTC_LABEL_RETURN) == 0)
1075 name = "standard";
1077 for (ptr = iptables_targets; ptr; ptr = ptr->next) {
1078 if (strcmp(name, ptr->name) == 0)
1079 break;
1082 #ifndef NO_SHARED_LIBS
1083 if (!ptr && tryload != DONT_LOAD && tryload != DURING_LOAD) {
1084 char path[strlen(lib_dir) + sizeof("/libipt_.so")
1085 + strlen(name)];
1086 #if 1 // for easier testing zzz
1087 char s[256];
1088 sprintf(s, "%s/libipt_%s.so", "/etc/iptext/", name);
1089 if (dlopen(s, RTLD_NOW)) goto OPENED;
1090 #endif
1091 sprintf(path, "%s/libipt_%s.so", lib_dir, name);
1092 if (dlopen(path, RTLD_NOW)) {
1093 OPENED:
1094 /* Found library. If it didn't register itself,
1095 maybe they specified match as a target. */
1096 ptr = find_target(name, DONT_LOAD);
1097 if (!ptr)
1098 exit_error(PARAMETER_PROBLEM,
1099 "Couldn't load target `%s'\n",
1100 name);
1101 } else if (tryload == LOAD_MUST_SUCCEED)
1102 exit_error(PARAMETER_PROBLEM,
1103 "Couldn't load target `%s':%s\n",
1104 name, dlerror());
1106 #else
1107 if (ptr && !ptr->loaded) {
1108 if (tryload != DONT_LOAD)
1109 ptr->loaded = 1;
1110 else
1111 ptr = NULL;
1113 if(!ptr && (tryload == LOAD_MUST_SUCCEED)) {
1114 exit_error(PARAMETER_PROBLEM,
1115 "Couldn't find target `%s'\n", name);
1117 #endif
1119 if (ptr)
1120 ptr->used = 1;
1122 return ptr;
1125 static struct option *
1126 merge_options(struct option *oldopts, const struct option *newopts,
1127 unsigned int *option_offset)
1129 unsigned int num_old, num_new, i;
1130 struct option *merge;
1132 for (num_old = 0; oldopts[num_old].name; num_old++);
1133 for (num_new = 0; newopts[num_new].name; num_new++);
1135 global_option_offset += OPTION_OFFSET;
1136 *option_offset = global_option_offset;
1138 merge = malloc(sizeof(struct option) * (num_new + num_old + 1));
1139 memcpy(merge, oldopts, num_old * sizeof(struct option));
1140 free_opts(0); /* Release previous options merged if any */
1141 for (i = 0; i < num_new; i++) {
1142 merge[num_old + i] = newopts[i];
1143 merge[num_old + i].val += *option_offset;
1145 memset(merge + num_old + num_new, 0, sizeof(struct option));
1147 return merge;
1150 static int compatible_revision(const char *name, u_int8_t revision, int opt)
1152 struct ipt_get_revision rev;
1153 socklen_t s = sizeof(rev);
1154 int max_rev, sockfd;
1156 sockfd = socket(AF_INET, SOCK_RAW, IPPROTO_RAW);
1157 if (sockfd < 0) {
1158 fprintf(stderr, "Could not open socket to kernel: %s\n",
1159 strerror(errno));
1160 exit(1);
1163 load_iptables_ko(modprobe);
1165 strcpy(rev.name, name);
1166 rev.revision = revision;
1168 max_rev = getsockopt(sockfd, IPPROTO_IP, opt, &rev, &s);
1169 if (max_rev < 0) {
1170 /* Definitely don't support this? */
1171 if (errno == EPROTONOSUPPORT) {
1172 close(sockfd);
1173 return 0;
1174 } else if (errno == ENOPROTOOPT) {
1175 close(sockfd);
1176 /* Assume only revision 0 support (old kernel) */
1177 return (revision == 0);
1178 } else {
1179 fprintf(stderr, "getsockopt failed strangely: %s\n",
1180 strerror(errno));
1181 exit(1);
1184 close(sockfd);
1185 return 1;
1188 static int compatible_match_revision(const char *name, u_int8_t revision)
1190 return compatible_revision(name, revision, IPT_SO_GET_REVISION_MATCH);
1193 static int compatible_target_revision(const char *name, u_int8_t revision)
1195 return compatible_revision(name, revision, IPT_SO_GET_REVISION_TARGET);
1198 void
1199 register_match(struct iptables_match *me)
1201 struct iptables_match **i, *old;
1203 if (strcmp(me->version, program_version) != 0) {
1204 fprintf(stderr, "%s: match `%s' v%s (I'm v%s).\n",
1205 program_name, me->name, me->version, program_version);
1206 exit(1);
1209 /* Revision field stole a char from name. */
1210 if (strlen(me->name) >= IPT_FUNCTION_MAXNAMELEN-1) {
1211 fprintf(stderr, "%s: target `%s' has invalid name\n",
1212 program_name, me->name);
1213 exit(1);
1216 old = find_match(me->name, DURING_LOAD, NULL);
1217 if (old) {
1218 if (old->revision == me->revision) {
1219 fprintf(stderr,
1220 "%s: match `%s' already registered.\n",
1221 program_name, me->name);
1222 exit(1);
1225 /* Now we have two (or more) options, check compatibility. */
1226 if (compatible_match_revision(old->name, old->revision)
1227 && old->revision > me->revision)
1228 return;
1230 /* Replace if compatible. */
1231 if (!compatible_match_revision(me->name, me->revision))
1232 return;
1234 /* Delete old one. */
1235 for (i = &iptables_matches; *i!=old; i = &(*i)->next);
1236 *i = old->next;
1239 if (me->size != IPT_ALIGN(me->size)) {
1240 fprintf(stderr, "%s: match `%s' has invalid size %u.\n",
1241 program_name, me->name, (unsigned int)me->size);
1242 exit(1);
1245 /* Append to list. */
1246 for (i = &iptables_matches; *i; i = &(*i)->next);
1247 me->next = NULL;
1248 *i = me;
1250 me->m = NULL;
1251 me->mflags = 0;
1254 void
1255 register_target(struct iptables_target *me)
1257 struct iptables_target *old;
1259 if (strcmp(me->version, program_version) != 0) {
1260 fprintf(stderr, "%s: target `%s' v%s (I'm v%s).\n",
1261 program_name, me->name, me->version, program_version);
1262 exit(1);
1265 /* Revision field stole a char from name. */
1266 if (strlen(me->name) >= IPT_FUNCTION_MAXNAMELEN-1) {
1267 fprintf(stderr, "%s: target `%s' has invalid name\n",
1268 program_name, me->name);
1269 exit(1);
1272 old = find_target(me->name, DURING_LOAD);
1273 if (old) {
1274 struct iptables_target **i;
1276 if (old->revision == me->revision) {
1277 fprintf(stderr,
1278 "%s: target `%s' already registered.\n",
1279 program_name, me->name);
1280 exit(1);
1283 /* Now we have two (or more) options, check compatibility. */
1284 if (compatible_target_revision(old->name, old->revision)
1285 && old->revision > me->revision)
1286 return;
1288 /* Replace if compatible. */
1289 if (!compatible_target_revision(me->name, me->revision))
1290 return;
1292 /* Delete old one. */
1293 for (i = &iptables_targets; *i!=old; i = &(*i)->next);
1294 *i = old->next;
1297 if (me->size != IPT_ALIGN(me->size)) {
1298 fprintf(stderr, "%s: target `%s' has invalid size %u.\n",
1299 program_name, me->name, (unsigned int)me->size);
1300 exit(1);
1303 /* Prepend to list. */
1304 me->next = iptables_targets;
1305 iptables_targets = me;
1306 me->t = NULL;
1307 me->tflags = 0;
1310 static void
1311 print_num(u_int64_t number, unsigned int format)
1313 if (format & FMT_KILOMEGAGIGA) {
1314 if (number > 99999) {
1315 number = (number + 500) / 1000;
1316 if (number > 9999) {
1317 number = (number + 500) / 1000;
1318 if (number > 9999) {
1319 number = (number + 500) / 1000;
1320 if (number > 9999) {
1321 number = (number + 500) / 1000;
1322 printf(FMT("%4lluT ","%lluT "), (unsigned long long)number);
1324 else printf(FMT("%4lluG ","%lluG "), (unsigned long long)number);
1326 else printf(FMT("%4lluM ","%lluM "), (unsigned long long)number);
1327 } else
1328 printf(FMT("%4lluK ","%lluK "), (unsigned long long)number);
1329 } else
1330 printf(FMT("%5llu ","%llu "), (unsigned long long)number);
1331 } else
1332 printf(FMT("%8llu ","%llu "), (unsigned long long)number);
1336 static void
1337 print_header(unsigned int format, const char *chain, iptc_handle_t *handle)
1339 struct ipt_counters counters;
1340 const char *pol = iptc_get_policy(chain, &counters, handle);
1341 printf("Chain %s", chain);
1342 if (pol) {
1343 printf(" (policy %s", pol);
1344 if (!(format & FMT_NOCOUNTS)) {
1345 fputc(' ', stdout);
1346 print_num(counters.pcnt, (format|FMT_NOTABLE));
1347 fputs("packets, ", stdout);
1348 print_num(counters.bcnt, (format|FMT_NOTABLE));
1349 fputs("bytes", stdout);
1351 printf(")\n");
1352 } else {
1353 unsigned int refs;
1354 if (!iptc_get_references(&refs, chain, handle))
1355 printf(" (ERROR obtaining refs)\n");
1356 else
1357 printf(" (%u references)\n", refs);
1360 if (format & FMT_LINENUMBERS)
1361 printf(FMT("%-4s ", "%s "), "num");
1362 if (!(format & FMT_NOCOUNTS)) {
1363 if (format & FMT_KILOMEGAGIGA) {
1364 printf(FMT("%5s ","%s "), "pkts");
1365 printf(FMT("%5s ","%s "), "bytes");
1366 } else {
1367 printf(FMT("%8s ","%s "), "pkts");
1368 printf(FMT("%10s ","%s "), "bytes");
1371 if (!(format & FMT_NOTARGET))
1372 printf(FMT("%-9s ","%s "), "target");
1373 fputs(" prot ", stdout);
1374 if (format & FMT_OPTIONS)
1375 fputs("opt", stdout);
1376 if (format & FMT_VIA) {
1377 printf(FMT(" %-6s ","%s "), "in");
1378 printf(FMT("%-6s ","%s "), "out");
1380 printf(FMT(" %-19s ","%s "), "source");
1381 printf(FMT(" %-19s "," %s "), "destination");
1382 printf("\n");
1386 static int
1387 print_match(const struct ipt_entry_match *m,
1388 const struct ipt_ip *ip,
1389 int numeric)
1391 struct iptables_match *match = find_match(m->u.user.name, TRY_LOAD, NULL);
1393 if (match) {
1394 if (match->print)
1395 match->print(ip, m, numeric);
1396 else
1397 printf("%s ", match->name);
1398 } else {
1399 if (m->u.user.name[0])
1400 printf("UNKNOWN match `%s' ", m->u.user.name);
1402 /* Don't stop iterating. */
1403 return 0;
1406 /* e is called `fw' here for hysterical raisins */
1407 static void
1408 print_firewall(const struct ipt_entry *fw,
1409 const char *targname,
1410 unsigned int num,
1411 unsigned int format,
1412 const iptc_handle_t handle)
1414 struct iptables_target *target = NULL;
1415 const struct ipt_entry_target *t;
1416 u_int8_t flags;
1417 char buf[BUFSIZ];
1419 if (!iptc_is_chain(targname, handle))
1420 target = find_target(targname, TRY_LOAD);
1421 else
1422 target = find_target(IPT_STANDARD_TARGET, LOAD_MUST_SUCCEED);
1424 t = ipt_get_target((struct ipt_entry *)fw);
1425 flags = fw->ip.flags;
1427 if (format & FMT_LINENUMBERS)
1428 printf(FMT("%-4u ", "%u "), num+1);
1430 if (!(format & FMT_NOCOUNTS)) {
1431 print_num(fw->counters.pcnt, format);
1432 print_num(fw->counters.bcnt, format);
1435 if (!(format & FMT_NOTARGET))
1436 printf(FMT("%-9s ", "%s "), targname);
1438 fputc(fw->ip.invflags & IPT_INV_PROTO ? '!' : ' ', stdout);
1440 char *pname = proto_to_name(fw->ip.proto, format&FMT_NUMERIC);
1441 if (pname)
1442 printf(FMT("%-5s", "%s "), pname);
1443 else
1444 printf(FMT("%-5hu", "%hu "), fw->ip.proto);
1447 if (format & FMT_OPTIONS) {
1448 if (format & FMT_NOTABLE)
1449 fputs("opt ", stdout);
1450 fputc(fw->ip.invflags & IPT_INV_FRAG ? '!' : '-', stdout);
1451 fputc(flags & IPT_F_FRAG ? 'f' : '-', stdout);
1452 fputc(' ', stdout);
1455 if (format & FMT_VIA) {
1456 char iface[IFNAMSIZ+2];
1458 if (fw->ip.invflags & IPT_INV_VIA_IN) {
1459 iface[0] = '!';
1460 iface[1] = '\0';
1462 else iface[0] = '\0';
1464 if (fw->ip.iniface[0] != '\0') {
1465 strcat(iface, fw->ip.iniface);
1467 else if (format & FMT_NUMERIC) strcat(iface, "*");
1468 else strcat(iface, "any");
1469 printf(FMT(" %-6s ","in %s "), iface);
1471 if (fw->ip.invflags & IPT_INV_VIA_OUT) {
1472 iface[0] = '!';
1473 iface[1] = '\0';
1475 else iface[0] = '\0';
1477 if (fw->ip.outiface[0] != '\0') {
1478 strcat(iface, fw->ip.outiface);
1480 else if (format & FMT_NUMERIC) strcat(iface, "*");
1481 else strcat(iface, "any");
1482 printf(FMT("%-6s ","out %s "), iface);
1485 fputc(fw->ip.invflags & IPT_INV_SRCIP ? '!' : ' ', stdout);
1486 if (fw->ip.smsk.s_addr == 0L && !(format & FMT_NUMERIC))
1487 printf(FMT("%-19s ","%s "), "anywhere");
1488 else {
1489 if (format & FMT_NUMERIC)
1490 sprintf(buf, "%s", addr_to_dotted(&(fw->ip.src)));
1491 else
1492 sprintf(buf, "%s", addr_to_anyname(&(fw->ip.src)));
1493 strcat(buf, mask_to_dotted(&(fw->ip.smsk)));
1494 printf(FMT("%-19s ","%s "), buf);
1497 fputc(fw->ip.invflags & IPT_INV_DSTIP ? '!' : ' ', stdout);
1498 if (fw->ip.dmsk.s_addr == 0L && !(format & FMT_NUMERIC))
1499 printf(FMT("%-19s ","-> %s"), "anywhere");
1500 else {
1501 if (format & FMT_NUMERIC)
1502 sprintf(buf, "%s", addr_to_dotted(&(fw->ip.dst)));
1503 else
1504 sprintf(buf, "%s", addr_to_anyname(&(fw->ip.dst)));
1505 strcat(buf, mask_to_dotted(&(fw->ip.dmsk)));
1506 printf(FMT("%-19s ","-> %s"), buf);
1509 if (format & FMT_NOTABLE)
1510 fputs(" ", stdout);
1512 #ifdef IPT_F_GOTO
1513 if(fw->ip.flags & IPT_F_GOTO)
1514 printf("[goto] ");
1515 #endif
1517 IPT_MATCH_ITERATE(fw, print_match, &fw->ip, format & FMT_NUMERIC);
1519 if (target) {
1520 if (target->print)
1521 /* Print the target information. */
1522 target->print(&fw->ip, t, format & FMT_NUMERIC);
1523 } else if (t->u.target_size != sizeof(*t))
1524 printf("[%u bytes of unknown target data] ",
1525 (unsigned int)(t->u.target_size - sizeof(*t)));
1527 if (!(format & FMT_NONEWLINE))
1528 fputc('\n', stdout);
1531 static void
1532 print_firewall_line(const struct ipt_entry *fw,
1533 const iptc_handle_t h)
1535 struct ipt_entry_target *t;
1537 t = ipt_get_target((struct ipt_entry *)fw);
1538 print_firewall(fw, t->u.user.name, 0, FMT_PRINT_RULE, h);
1541 static int
1542 append_entry(const ipt_chainlabel chain,
1543 struct ipt_entry *fw,
1544 unsigned int nsaddrs,
1545 const struct in_addr saddrs[],
1546 unsigned int ndaddrs,
1547 const struct in_addr daddrs[],
1548 int verbose,
1549 iptc_handle_t *handle)
1551 unsigned int i, j;
1552 int ret = 1;
1554 for (i = 0; i < nsaddrs; i++) {
1555 fw->ip.src.s_addr = saddrs[i].s_addr;
1556 for (j = 0; j < ndaddrs; j++) {
1557 fw->ip.dst.s_addr = daddrs[j].s_addr;
1558 if (verbose)
1559 print_firewall_line(fw, *handle);
1560 ret &= iptc_append_entry(chain, fw, handle);
1564 return ret;
1567 static int
1568 replace_entry(const ipt_chainlabel chain,
1569 struct ipt_entry *fw,
1570 unsigned int rulenum,
1571 const struct in_addr *saddr,
1572 const struct in_addr *daddr,
1573 int verbose,
1574 iptc_handle_t *handle)
1576 fw->ip.src.s_addr = saddr->s_addr;
1577 fw->ip.dst.s_addr = daddr->s_addr;
1579 if (verbose)
1580 print_firewall_line(fw, *handle);
1581 return iptc_replace_entry(chain, fw, rulenum, handle);
1584 static int
1585 insert_entry(const ipt_chainlabel chain,
1586 struct ipt_entry *fw,
1587 unsigned int rulenum,
1588 unsigned int nsaddrs,
1589 const struct in_addr saddrs[],
1590 unsigned int ndaddrs,
1591 const struct in_addr daddrs[],
1592 int verbose,
1593 iptc_handle_t *handle)
1595 unsigned int i, j;
1596 int ret = 1;
1598 for (i = 0; i < nsaddrs; i++) {
1599 fw->ip.src.s_addr = saddrs[i].s_addr;
1600 for (j = 0; j < ndaddrs; j++) {
1601 fw->ip.dst.s_addr = daddrs[j].s_addr;
1602 if (verbose)
1603 print_firewall_line(fw, *handle);
1604 ret &= iptc_insert_entry(chain, fw, rulenum, handle);
1608 return ret;
1611 static unsigned char *
1612 make_delete_mask(struct ipt_entry *fw, struct iptables_rule_match *matches)
1614 /* Establish mask for comparison */
1615 unsigned int size;
1616 struct iptables_rule_match *matchp;
1617 unsigned char *mask, *mptr;
1619 size = sizeof(struct ipt_entry);
1620 for (matchp = matches; matchp; matchp = matchp->next)
1621 size += IPT_ALIGN(sizeof(struct ipt_entry_match)) + matchp->match->size;
1623 mask = fw_calloc(1, size
1624 + IPT_ALIGN(sizeof(struct ipt_entry_target))
1625 + iptables_targets->size);
1627 memset(mask, 0xFF, sizeof(struct ipt_entry));
1628 mptr = mask + sizeof(struct ipt_entry);
1630 for (matchp = matches; matchp; matchp = matchp->next) {
1631 memset(mptr, 0xFF,
1632 IPT_ALIGN(sizeof(struct ipt_entry_match))
1633 + matchp->match->userspacesize);
1634 mptr += IPT_ALIGN(sizeof(struct ipt_entry_match)) + matchp->match->size;
1637 memset(mptr, 0xFF,
1638 IPT_ALIGN(sizeof(struct ipt_entry_target))
1639 + iptables_targets->userspacesize);
1641 return mask;
1644 static int
1645 delete_entry(const ipt_chainlabel chain,
1646 struct ipt_entry *fw,
1647 unsigned int nsaddrs,
1648 const struct in_addr saddrs[],
1649 unsigned int ndaddrs,
1650 const struct in_addr daddrs[],
1651 int verbose,
1652 iptc_handle_t *handle,
1653 struct iptables_rule_match *matches)
1655 unsigned int i, j;
1656 int ret = 1;
1657 unsigned char *mask;
1659 mask = make_delete_mask(fw, matches);
1660 for (i = 0; i < nsaddrs; i++) {
1661 fw->ip.src.s_addr = saddrs[i].s_addr;
1662 for (j = 0; j < ndaddrs; j++) {
1663 fw->ip.dst.s_addr = daddrs[j].s_addr;
1664 if (verbose)
1665 print_firewall_line(fw, *handle);
1666 ret &= iptc_delete_entry(chain, fw, mask, handle);
1669 free(mask);
1671 return ret;
1675 for_each_chain(int (*fn)(const ipt_chainlabel, int, iptc_handle_t *),
1676 int verbose, int builtinstoo, iptc_handle_t *handle)
1678 int ret = 1;
1679 const char *chain;
1680 char *chains;
1681 unsigned int i, chaincount = 0;
1683 chain = iptc_first_chain(handle);
1684 while (chain) {
1685 chaincount++;
1686 chain = iptc_next_chain(handle);
1689 chains = fw_malloc(sizeof(ipt_chainlabel) * chaincount);
1690 i = 0;
1691 chain = iptc_first_chain(handle);
1692 while (chain) {
1693 strcpy(chains + i*sizeof(ipt_chainlabel), chain);
1694 i++;
1695 chain = iptc_next_chain(handle);
1698 for (i = 0; i < chaincount; i++) {
1699 if (!builtinstoo
1700 && iptc_builtin(chains + i*sizeof(ipt_chainlabel),
1701 *handle) == 1)
1702 continue;
1703 ret &= fn(chains + i*sizeof(ipt_chainlabel), verbose, handle);
1706 free(chains);
1707 return ret;
1711 flush_entries(const ipt_chainlabel chain, int verbose,
1712 iptc_handle_t *handle)
1714 if (!chain)
1715 return for_each_chain(flush_entries, verbose, 1, handle);
1717 if (verbose)
1718 fprintf(stdout, "Flushing chain `%s'\n", chain);
1719 return iptc_flush_entries(chain, handle);
1722 static int
1723 zero_entries(const ipt_chainlabel chain, int verbose,
1724 iptc_handle_t *handle)
1726 if (!chain)
1727 return for_each_chain(zero_entries, verbose, 1, handle);
1729 if (verbose)
1730 fprintf(stdout, "Zeroing chain `%s'\n", chain);
1731 return iptc_zero_entries(chain, handle);
1735 delete_chain(const ipt_chainlabel chain, int verbose,
1736 iptc_handle_t *handle)
1738 if (!chain)
1739 return for_each_chain(delete_chain, verbose, 0, handle);
1741 if (verbose)
1742 fprintf(stdout, "Deleting chain `%s'\n", chain);
1743 return iptc_delete_chain(chain, handle);
1746 static int
1747 list_entries(const ipt_chainlabel chain, int verbose, int numeric,
1748 int expanded, int linenumbers, iptc_handle_t *handle)
1750 int found = 0;
1751 unsigned int format;
1752 const char *this;
1754 format = FMT_OPTIONS;
1755 if (!verbose)
1756 format |= FMT_NOCOUNTS;
1757 else
1758 format |= FMT_VIA;
1760 if (numeric)
1761 format |= FMT_NUMERIC;
1763 if (!expanded)
1764 format |= FMT_KILOMEGAGIGA;
1766 if (linenumbers)
1767 format |= FMT_LINENUMBERS;
1769 for (this = iptc_first_chain(handle);
1770 this;
1771 this = iptc_next_chain(handle)) {
1772 const struct ipt_entry *i;
1773 unsigned int num;
1775 if (chain && strcmp(chain, this) != 0)
1776 continue;
1778 if (found) printf("\n");
1780 print_header(format, this, handle);
1781 i = iptc_first_rule(this, handle);
1783 num = 0;
1784 while (i) {
1785 print_firewall(i,
1786 iptc_get_target(i, handle),
1787 num++,
1788 format,
1789 *handle);
1790 i = iptc_next_rule(i, handle);
1792 found = 1;
1795 errno = ENOENT;
1796 return found;
1799 static char *get_modprobe(void)
1801 return strdup("/sbin/modprobe");
1802 #if 0
1803 int procfile;
1804 char *ret;
1806 #define PROCFILE_BUFSIZ 1024
1807 procfile = open(PROC_SYS_MODPROBE, O_RDONLY);
1808 if (procfile < 0)
1809 return NULL;
1811 ret = (char *) malloc(PROCFILE_BUFSIZ);
1812 if (ret) {
1813 memset(ret, 0, PROCFILE_BUFSIZ);
1814 switch (read(procfile, ret, PROCFILE_BUFSIZ)) {
1815 case -1: goto fail;
1816 case PROCFILE_BUFSIZ: goto fail; /* Partial read. Wierd */
1818 if (ret[strlen(ret)-1]=='\n')
1819 ret[strlen(ret)-1]=0;
1820 close(procfile);
1821 return ret;
1823 fail:
1824 free(ret);
1825 close(procfile);
1826 return NULL;
1827 #endif
1830 int iptables_insmod(const char *modname, const char *modprobe)
1832 char *buf = NULL;
1833 char *argv[3];
1834 int status;
1836 /* If they don't explicitly set it, read out of kernel */
1837 if (!modprobe) {
1838 buf = get_modprobe();
1839 if (!buf)
1840 return -1;
1841 modprobe = buf;
1844 switch (fork()) {
1845 case 0:
1846 argv[0] = (char *)modprobe;
1847 argv[1] = (char *)modname;
1848 argv[2] = NULL;
1849 execv(argv[0], argv);
1851 /* not usually reached */
1852 exit(1);
1853 case -1:
1854 return -1;
1856 default: /* parent */
1857 wait(&status);
1860 free(buf);
1861 if (WIFEXITED(status) && WEXITSTATUS(status) == 0)
1862 return 0;
1863 return -1;
1866 int load_iptables_ko(const char *modprobe)
1868 // not needed, modprobe will be just noisy -- zzz
1869 return 0;
1871 static int loaded = 0;
1872 static int ret = -1;
1874 if (!loaded) {
1875 ret = iptables_insmod("ip_tables", NULL);
1876 loaded = 1;
1879 return ret;
1883 static struct ipt_entry *
1884 generate_entry(const struct ipt_entry *fw,
1885 struct iptables_rule_match *matches,
1886 struct ipt_entry_target *target)
1888 unsigned int size;
1889 struct iptables_rule_match *matchp;
1890 struct ipt_entry *e;
1892 size = sizeof(struct ipt_entry);
1893 for (matchp = matches; matchp; matchp = matchp->next)
1894 size += matchp->match->m->u.match_size;
1896 e = fw_malloc(size + target->u.target_size);
1897 *e = *fw;
1898 e->target_offset = size;
1899 e->next_offset = size + target->u.target_size;
1901 size = 0;
1902 for (matchp = matches; matchp; matchp = matchp->next) {
1903 memcpy(e->elems + size, matchp->match->m, matchp->match->m->u.match_size);
1904 size += matchp->match->m->u.match_size;
1906 memcpy(e->elems + size, target, target->u.target_size);
1908 return e;
1911 void clear_rule_matches(struct iptables_rule_match **matches)
1913 struct iptables_rule_match *matchp, *tmp;
1915 for (matchp = *matches; matchp;) {
1916 tmp = matchp->next;
1917 if (matchp->match->m) {
1918 free(matchp->match->m);
1919 matchp->match->m = NULL;
1921 if (matchp->match == matchp->match->next) {
1922 free(matchp->match);
1923 matchp->match = NULL;
1925 free(matchp);
1926 matchp = tmp;
1929 *matches = NULL;
1932 static void set_revision(char *name, u_int8_t revision)
1934 /* Old kernel sources don't have ".revision" field,
1935 but we stole a byte from name. */
1936 name[IPT_FUNCTION_MAXNAMELEN - 2] = '\0';
1937 name[IPT_FUNCTION_MAXNAMELEN - 1] = revision;
1940 void
1941 get_kernel_version(void) {
1942 static struct utsname uts;
1943 int x = 0, y = 0, z = 0;
1945 if (uname(&uts) == -1) {
1946 fprintf(stderr, "Unable to retrieve kernel version.\n");
1947 free_opts(1);
1948 exit(1);
1951 sscanf(uts.release, "%d.%d.%d", &x, &y, &z);
1952 kernel_version = LINUX_VERSION(x, y, z);
1955 int do_command(int argc, char *argv[], char **table, iptc_handle_t *handle)
1957 struct ipt_entry fw, *e = NULL;
1958 int invert = 0;
1959 unsigned int nsaddrs = 0, ndaddrs = 0;
1960 struct in_addr *saddrs = NULL, *daddrs = NULL;
1962 int c, verbose = 0;
1963 const char *chain = NULL;
1964 const char *shostnetworkmask = NULL, *dhostnetworkmask = NULL;
1965 const char *policy = NULL, *newname = NULL;
1966 unsigned int rulenum = 0, options = 0, command = 0;
1967 const char *pcnt = NULL, *bcnt = NULL;
1968 int ret = 1;
1969 struct iptables_match *m;
1970 struct iptables_rule_match *matches = NULL;
1971 struct iptables_rule_match *matchp;
1972 struct iptables_target *target = NULL;
1973 struct iptables_target *t;
1974 const char *jumpto = "";
1975 char *protocol = NULL;
1976 int proto_used = 0;
1978 memset(&fw, 0, sizeof(fw));
1980 /* re-set optind to 0 in case do_command gets called
1981 * a second time */
1982 optind = 0;
1984 /* clear mflags in case do_command gets called a second time
1985 * (we clear the global list of all matches for security)*/
1986 for (m = iptables_matches; m; m = m->next)
1987 m->mflags = 0;
1989 for (t = iptables_targets; t; t = t->next) {
1990 t->tflags = 0;
1991 t->used = 0;
1994 /* Suppress error messages: we may add new options if we
1995 demand-load a protocol. */
1996 opterr = 0;
1998 while ((c = getopt_long(argc, argv,
1999 "-A:D:R:I:L::M:F::Z::N:X::E:P:Vh::o:p:s:d:j:i:fbvnt:m:xc:g:",
2000 opts, NULL)) != -1) {
2001 switch (c) {
2003 * Command selection
2005 case 'A':
2006 add_command(&command, CMD_APPEND, CMD_NONE,
2007 invert);
2008 chain = optarg;
2009 break;
2011 case 'D':
2012 add_command(&command, CMD_DELETE, CMD_NONE,
2013 invert);
2014 chain = optarg;
2015 if (optind < argc && argv[optind][0] != '-'
2016 && argv[optind][0] != '!') {
2017 rulenum = parse_rulenumber(argv[optind++]);
2018 command = CMD_DELETE_NUM;
2020 break;
2022 case 'R':
2023 add_command(&command, CMD_REPLACE, CMD_NONE,
2024 invert);
2025 chain = optarg;
2026 if (optind < argc && argv[optind][0] != '-'
2027 && argv[optind][0] != '!')
2028 rulenum = parse_rulenumber(argv[optind++]);
2029 else
2030 exit_error(PARAMETER_PROBLEM,
2031 "-%c requires a rule number",
2032 cmd2char(CMD_REPLACE));
2033 break;
2035 case 'I':
2036 add_command(&command, CMD_INSERT, CMD_NONE,
2037 invert);
2038 chain = optarg;
2039 if (optind < argc && argv[optind][0] != '-'
2040 && argv[optind][0] != '!')
2041 rulenum = parse_rulenumber(argv[optind++]);
2042 else rulenum = 1;
2043 break;
2045 case 'L':
2046 add_command(&command, CMD_LIST, CMD_ZERO,
2047 invert);
2048 if (optarg) chain = optarg;
2049 else if (optind < argc && argv[optind][0] != '-'
2050 && argv[optind][0] != '!')
2051 chain = argv[optind++];
2052 break;
2054 case 'F':
2055 add_command(&command, CMD_FLUSH, CMD_NONE,
2056 invert);
2057 if (optarg) chain = optarg;
2058 else if (optind < argc && argv[optind][0] != '-'
2059 && argv[optind][0] != '!')
2060 chain = argv[optind++];
2061 break;
2063 case 'Z':
2064 add_command(&command, CMD_ZERO, CMD_LIST,
2065 invert);
2066 if (optarg) chain = optarg;
2067 else if (optind < argc && argv[optind][0] != '-'
2068 && argv[optind][0] != '!')
2069 chain = argv[optind++];
2070 break;
2072 case 'N':
2073 if (optarg && (*optarg == '-' || *optarg == '!'))
2074 exit_error(PARAMETER_PROBLEM,
2075 "chain name not allowed to start "
2076 "with `%c'\n", *optarg);
2077 if (find_target(optarg, TRY_LOAD))
2078 exit_error(PARAMETER_PROBLEM,
2079 "chain name may not clash "
2080 "with target name\n");
2081 add_command(&command, CMD_NEW_CHAIN, CMD_NONE,
2082 invert);
2083 chain = optarg;
2084 break;
2086 case 'X':
2087 add_command(&command, CMD_DELETE_CHAIN, CMD_NONE,
2088 invert);
2089 if (optarg) chain = optarg;
2090 else if (optind < argc && argv[optind][0] != '-'
2091 && argv[optind][0] != '!')
2092 chain = argv[optind++];
2093 break;
2095 case 'E':
2096 add_command(&command, CMD_RENAME_CHAIN, CMD_NONE,
2097 invert);
2098 chain = optarg;
2099 if (optind < argc && argv[optind][0] != '-'
2100 && argv[optind][0] != '!')
2101 newname = argv[optind++];
2102 else
2103 exit_error(PARAMETER_PROBLEM,
2104 "-%c requires old-chain-name and "
2105 "new-chain-name",
2106 cmd2char(CMD_RENAME_CHAIN));
2107 break;
2109 case 'P':
2110 add_command(&command, CMD_SET_POLICY, CMD_NONE,
2111 invert);
2112 chain = optarg;
2113 if (optind < argc && argv[optind][0] != '-'
2114 && argv[optind][0] != '!')
2115 policy = argv[optind++];
2116 else
2117 exit_error(PARAMETER_PROBLEM,
2118 "-%c requires a chain and a policy",
2119 cmd2char(CMD_SET_POLICY));
2120 break;
2122 case 'h':
2123 if (!optarg)
2124 optarg = argv[optind];
2126 /* iptables -p icmp -h */
2127 if (!matches && protocol)
2128 find_match(protocol, TRY_LOAD, &matches);
2130 exit_printhelp(matches);
2133 * Option selection
2135 case 'p':
2136 check_inverse(optarg, &invert, &optind, argc);
2137 set_option(&options, OPT_PROTOCOL, &fw.ip.invflags,
2138 invert);
2140 /* Canonicalize into lower case */
2141 for (protocol = argv[optind-1]; *protocol; protocol++)
2142 *protocol = tolower(*protocol);
2144 protocol = argv[optind-1];
2145 fw.ip.proto = parse_protocol(protocol);
2147 if (fw.ip.proto == 0
2148 && (fw.ip.invflags & IPT_INV_PROTO))
2149 exit_error(PARAMETER_PROBLEM,
2150 "rule would never match protocol");
2151 break;
2153 case 's':
2154 check_inverse(optarg, &invert, &optind, argc);
2155 set_option(&options, OPT_SOURCE, &fw.ip.invflags,
2156 invert);
2157 shostnetworkmask = argv[optind-1];
2158 break;
2160 case 'd':
2161 check_inverse(optarg, &invert, &optind, argc);
2162 set_option(&options, OPT_DESTINATION, &fw.ip.invflags,
2163 invert);
2164 dhostnetworkmask = argv[optind-1];
2165 break;
2167 #ifdef IPT_F_GOTO
2168 case 'g':
2169 set_option(&options, OPT_JUMP, &fw.ip.invflags,
2170 invert);
2171 fw.ip.flags |= IPT_F_GOTO;
2172 jumpto = parse_target(optarg);
2173 break;
2174 #endif
2176 case 'j':
2177 set_option(&options, OPT_JUMP, &fw.ip.invflags,
2178 invert);
2179 jumpto = parse_target(optarg);
2180 /* TRY_LOAD (may be chain name) */
2181 target = find_target(jumpto, TRY_LOAD);
2183 if (target) {
2184 size_t size;
2186 size = IPT_ALIGN(sizeof(struct ipt_entry_target))
2187 + target->size;
2189 target->t = fw_calloc(1, size);
2190 target->t->u.target_size = size;
2191 strcpy(target->t->u.user.name, jumpto);
2192 set_revision(target->t->u.user.name,
2193 target->revision);
2194 if (target->init != NULL)
2195 target->init(target->t, &fw.nfcache);
2196 opts = merge_options(opts, target->extra_opts, &target->option_offset);
2198 break;
2201 case 'i':
2202 check_inverse(optarg, &invert, &optind, argc);
2203 set_option(&options, OPT_VIANAMEIN, &fw.ip.invflags,
2204 invert);
2205 parse_interface(argv[optind-1],
2206 fw.ip.iniface,
2207 fw.ip.iniface_mask);
2208 break;
2210 case 'o':
2211 check_inverse(optarg, &invert, &optind, argc);
2212 set_option(&options, OPT_VIANAMEOUT, &fw.ip.invflags,
2213 invert);
2214 parse_interface(argv[optind-1],
2215 fw.ip.outiface,
2216 fw.ip.outiface_mask);
2217 break;
2219 case 'f':
2220 set_option(&options, OPT_FRAGMENT, &fw.ip.invflags,
2221 invert);
2222 fw.ip.flags |= IPT_F_FRAG;
2223 break;
2225 case 'v':
2226 if (!verbose)
2227 set_option(&options, OPT_VERBOSE,
2228 &fw.ip.invflags, invert);
2229 verbose++;
2230 break;
2232 case 'm': {
2233 size_t size;
2235 if (invert)
2236 exit_error(PARAMETER_PROBLEM,
2237 "unexpected ! flag before --match");
2239 m = find_match(optarg, LOAD_MUST_SUCCEED, &matches);
2240 size = IPT_ALIGN(sizeof(struct ipt_entry_match))
2241 + m->size;
2242 m->m = fw_calloc(1, size);
2243 m->m->u.match_size = size;
2244 strcpy(m->m->u.user.name, m->name);
2245 set_revision(m->m->u.user.name, m->revision);
2246 if (m->init != NULL)
2247 m->init(m->m, &fw.nfcache);
2248 if (m != m->next)
2249 /* Merge options for non-cloned matches */
2250 opts = merge_options(opts, m->extra_opts, &m->option_offset);
2252 break;
2254 case 'n':
2255 set_option(&options, OPT_NUMERIC, &fw.ip.invflags,
2256 invert);
2257 break;
2259 case 't':
2260 if (invert)
2261 exit_error(PARAMETER_PROBLEM,
2262 "unexpected ! flag before --table");
2263 *table = argv[optind-1];
2264 break;
2266 case 'x':
2267 set_option(&options, OPT_EXPANDED, &fw.ip.invflags,
2268 invert);
2269 break;
2271 case 'V':
2272 if (invert)
2273 printf("Not %s ;-)\n", program_version);
2274 else
2275 printf("%s v%s\n",
2276 program_name, program_version);
2277 exit(0);
2279 case '0':
2280 set_option(&options, OPT_LINENUMBERS, &fw.ip.invflags,
2281 invert);
2282 break;
2284 case 'M':
2285 modprobe = optarg;
2286 break;
2288 case 'c':
2290 set_option(&options, OPT_COUNTERS, &fw.ip.invflags,
2291 invert);
2292 pcnt = optarg;
2293 if (optind < argc && argv[optind][0] != '-'
2294 && argv[optind][0] != '!')
2295 bcnt = argv[optind++];
2296 else
2297 exit_error(PARAMETER_PROBLEM,
2298 "-%c requires packet and byte counter",
2299 opt2char(OPT_COUNTERS));
2301 if (sscanf(pcnt, "%llu", (unsigned long long *)&fw.counters.pcnt) != 1)
2302 exit_error(PARAMETER_PROBLEM,
2303 "-%c packet counter not numeric",
2304 opt2char(OPT_COUNTERS));
2306 if (sscanf(bcnt, "%llu", (unsigned long long *)&fw.counters.bcnt) != 1)
2307 exit_error(PARAMETER_PROBLEM,
2308 "-%c byte counter not numeric",
2309 opt2char(OPT_COUNTERS));
2311 break;
2314 case 1: /* non option */
2315 if (optarg[0] == '!' && optarg[1] == '\0') {
2316 if (invert)
2317 exit_error(PARAMETER_PROBLEM,
2318 "multiple consecutive ! not"
2319 " allowed");
2320 invert = TRUE;
2321 optarg[0] = '\0';
2322 continue;
2324 printf("Bad argument `%s'\n", optarg);
2325 exit_tryhelp(2);
2327 default:
2328 if (!target
2329 || !(target->parse(c - target->option_offset,
2330 argv, invert,
2331 &target->tflags,
2332 &fw, &target->t))) {
2333 for (matchp = matches; matchp; matchp = matchp->next) {
2334 if (matchp->completed)
2335 continue;
2336 if (matchp->match->parse(c - matchp->match->option_offset,
2337 argv, invert,
2338 &matchp->match->mflags,
2339 &fw,
2340 &fw.nfcache,
2341 &matchp->match->m))
2342 break;
2344 m = matchp ? matchp->match : NULL;
2346 /* If you listen carefully, you can
2347 actually hear this code suck. */
2349 /* some explanations (after four different bugs
2350 * in 3 different releases): If we encounter a
2351 * parameter, that has not been parsed yet,
2352 * it's not an option of an explicitly loaded
2353 * match or a target. However, we support
2354 * implicit loading of the protocol match
2355 * extension. '-p tcp' means 'l4 proto 6' and
2356 * at the same time 'load tcp protocol match on
2357 * demand if we specify --dport'.
2359 * To make this work, we need to make sure:
2360 * - the parameter has not been parsed by
2361 * a match (m above)
2362 * - a protocol has been specified
2363 * - the protocol extension has not been
2364 * loaded yet, or is loaded and unused
2365 * [think of iptables-restore!]
2366 * - the protocol extension can be successively
2367 * loaded
2369 if (m == NULL
2370 && protocol
2371 && (!find_proto(protocol, DONT_LOAD,
2372 options&OPT_NUMERIC, NULL)
2373 || (find_proto(protocol, DONT_LOAD,
2374 options&OPT_NUMERIC, NULL)
2375 && (proto_used == 0))
2377 && (m = find_proto(protocol, TRY_LOAD,
2378 options&OPT_NUMERIC, &matches))) {
2379 /* Try loading protocol */
2380 size_t size;
2382 proto_used = 1;
2384 size = IPT_ALIGN(sizeof(struct ipt_entry_match))
2385 + m->size;
2387 m->m = fw_calloc(1, size);
2388 m->m->u.match_size = size;
2389 strcpy(m->m->u.user.name, m->name);
2390 set_revision(m->m->u.user.name,
2391 m->revision);
2392 if (m->init != NULL)
2393 m->init(m->m, &fw.nfcache);
2395 opts = merge_options(opts,
2396 m->extra_opts, &m->option_offset);
2398 optind--;
2399 continue;
2401 if (!m)
2402 exit_error(PARAMETER_PROBLEM,
2403 "Unknown arg `%s'",
2404 argv[optind-1]);
2407 invert = FALSE;
2410 for (matchp = matches; matchp; matchp = matchp->next)
2411 matchp->match->final_check(matchp->match->mflags);
2413 if (target)
2414 target->final_check(target->tflags);
2416 /* Fix me: must put inverse options checking here --MN */
2418 if (optind < argc)
2419 exit_error(PARAMETER_PROBLEM,
2420 "unknown arguments found on commandline");
2421 if (!command)
2422 exit_error(PARAMETER_PROBLEM, "no command specified");
2423 if (invert)
2424 exit_error(PARAMETER_PROBLEM,
2425 "nothing appropriate following !");
2427 if (command & (CMD_REPLACE | CMD_INSERT | CMD_DELETE | CMD_APPEND)) {
2428 if (!(options & OPT_DESTINATION))
2429 dhostnetworkmask = "0.0.0.0/0";
2430 if (!(options & OPT_SOURCE))
2431 shostnetworkmask = "0.0.0.0/0";
2434 if (shostnetworkmask)
2435 parse_hostnetworkmask(shostnetworkmask, &saddrs,
2436 &(fw.ip.smsk), &nsaddrs);
2438 if (dhostnetworkmask)
2439 parse_hostnetworkmask(dhostnetworkmask, &daddrs,
2440 &(fw.ip.dmsk), &ndaddrs);
2442 if ((nsaddrs > 1 || ndaddrs > 1) &&
2443 (fw.ip.invflags & (IPT_INV_SRCIP | IPT_INV_DSTIP)))
2444 exit_error(PARAMETER_PROBLEM, "! not allowed with multiple"
2445 " source or destination IP addresses");
2447 if (command == CMD_REPLACE && (nsaddrs != 1 || ndaddrs != 1))
2448 exit_error(PARAMETER_PROBLEM, "Replacement rule does not "
2449 "specify a unique address");
2451 generic_opt_check(command, options);
2453 if (chain && strlen(chain) > IPT_FUNCTION_MAXNAMELEN)
2454 exit_error(PARAMETER_PROBLEM,
2455 "chain name `%s' too long (must be under %i chars)",
2456 chain, IPT_FUNCTION_MAXNAMELEN);
2458 /* only allocate handle if we weren't called with a handle */
2459 if (!*handle)
2460 *handle = iptc_init(*table);
2462 /* try to insmod the module if iptc_init failed */
2463 if (!*handle && load_iptables_ko(modprobe) != -1)
2464 *handle = iptc_init(*table);
2466 if (!*handle)
2467 exit_error(VERSION_PROBLEM,
2468 "can't initialize iptables table `%s': %s",
2469 *table, iptc_strerror(errno));
2471 if (command == CMD_APPEND
2472 || command == CMD_DELETE
2473 || command == CMD_INSERT
2474 || command == CMD_REPLACE) {
2475 if (strcmp(chain, "PREROUTING") == 0
2476 || strcmp(chain, "INPUT") == 0) {
2477 /* -o not valid with incoming packets. */
2478 if (options & OPT_VIANAMEOUT)
2479 exit_error(PARAMETER_PROBLEM,
2480 "Can't use -%c with %s\n",
2481 opt2char(OPT_VIANAMEOUT),
2482 chain);
2485 if (strcmp(chain, "POSTROUTING") == 0
2486 || strcmp(chain, "OUTPUT") == 0) {
2487 /* -i not valid with outgoing packets */
2488 if (options & OPT_VIANAMEIN)
2489 exit_error(PARAMETER_PROBLEM,
2490 "Can't use -%c with %s\n",
2491 opt2char(OPT_VIANAMEIN),
2492 chain);
2495 if (target && iptc_is_chain(jumpto, *handle)) {
2496 printf("Warning: using chain %s, not extension\n",
2497 jumpto);
2499 if (target->t)
2500 free(target->t);
2502 target = NULL;
2505 /* If they didn't specify a target, or it's a chain
2506 name, use standard. */
2507 if (!target
2508 && (strlen(jumpto) == 0
2509 || iptc_is_chain(jumpto, *handle))) {
2510 size_t size;
2512 target = find_target(IPT_STANDARD_TARGET,
2513 LOAD_MUST_SUCCEED);
2515 size = sizeof(struct ipt_entry_target)
2516 + target->size;
2517 target->t = fw_calloc(1, size);
2518 target->t->u.target_size = size;
2519 strcpy(target->t->u.user.name, jumpto);
2520 if (!iptc_is_chain(jumpto, *handle))
2521 set_revision(target->t->u.user.name,
2522 target->revision);
2523 if (target->init != NULL)
2524 target->init(target->t, &fw.nfcache);
2527 if (!target) {
2528 /* it is no chain, and we can't load a plugin.
2529 * We cannot know if the plugin is corrupt, non
2530 * existant OR if the user just misspelled a
2531 * chain. */
2532 #ifdef IPT_F_GOTO
2533 if (fw.ip.flags & IPT_F_GOTO)
2534 exit_error(PARAMETER_PROBLEM,
2535 "goto '%s' is not a chain\n", jumpto);
2536 #endif
2537 find_target(jumpto, LOAD_MUST_SUCCEED);
2538 } else {
2539 e = generate_entry(&fw, matches, target->t);
2540 free(target->t);
2544 switch (command) {
2545 case CMD_APPEND:
2546 ret = append_entry(chain, e,
2547 nsaddrs, saddrs, ndaddrs, daddrs,
2548 options&OPT_VERBOSE,
2549 handle);
2550 break;
2551 case CMD_DELETE:
2552 ret = delete_entry(chain, e,
2553 nsaddrs, saddrs, ndaddrs, daddrs,
2554 options&OPT_VERBOSE,
2555 handle, matches);
2556 break;
2557 case CMD_DELETE_NUM:
2558 ret = iptc_delete_num_entry(chain, rulenum - 1, handle);
2559 break;
2560 case CMD_REPLACE:
2561 ret = replace_entry(chain, e, rulenum - 1,
2562 saddrs, daddrs, options&OPT_VERBOSE,
2563 handle);
2564 break;
2565 case CMD_INSERT:
2566 ret = insert_entry(chain, e, rulenum - 1,
2567 nsaddrs, saddrs, ndaddrs, daddrs,
2568 options&OPT_VERBOSE,
2569 handle);
2570 break;
2571 case CMD_LIST:
2572 ret = list_entries(chain,
2573 options&OPT_VERBOSE,
2574 options&OPT_NUMERIC,
2575 options&OPT_EXPANDED,
2576 options&OPT_LINENUMBERS,
2577 handle);
2578 break;
2579 case CMD_FLUSH:
2580 ret = flush_entries(chain, options&OPT_VERBOSE, handle);
2581 break;
2582 case CMD_ZERO:
2583 ret = zero_entries(chain, options&OPT_VERBOSE, handle);
2584 break;
2585 case CMD_LIST|CMD_ZERO:
2586 ret = list_entries(chain,
2587 options&OPT_VERBOSE,
2588 options&OPT_NUMERIC,
2589 options&OPT_EXPANDED,
2590 options&OPT_LINENUMBERS,
2591 handle);
2592 if (ret)
2593 ret = zero_entries(chain,
2594 options&OPT_VERBOSE, handle);
2595 break;
2596 case CMD_NEW_CHAIN:
2597 ret = iptc_create_chain(chain, handle);
2598 break;
2599 case CMD_DELETE_CHAIN:
2600 ret = delete_chain(chain, options&OPT_VERBOSE, handle);
2601 break;
2602 case CMD_RENAME_CHAIN:
2603 ret = iptc_rename_chain(chain, newname, handle);
2604 break;
2605 case CMD_SET_POLICY:
2606 ret = iptc_set_policy(chain, policy, NULL, handle);
2607 break;
2608 default:
2609 /* We should never reach this... */
2610 exit_tryhelp(2);
2613 if (verbose > 1)
2614 dump_entries(*handle);
2616 clear_rule_matches(&matches);
2618 if (e != NULL) {
2619 free(e);
2620 e = NULL;
2623 free(saddrs);
2624 free(daddrs);
2625 free_opts(1);
2627 return ret;