libsodium: updated to 1.0.10
[tomato.git] / release / src / router / iptables / iptables.c
blobb460059363dece041d799faf6d30ac7deacc0a07
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 { "udplite", IPPROTO_UDPLITE },
231 { "icmp", IPPROTO_ICMP },
232 { "esp", IPPROTO_ESP },
233 { "ah", IPPROTO_AH },
234 { "sctp", IPPROTO_SCTP },
235 { "all", 0 },
238 static char *
239 proto_to_name(u_int8_t proto, int nolookup)
241 unsigned int i;
243 if (proto && !nolookup) {
244 struct protoent *pent = getprotobynumber(proto);
245 if (pent)
246 return pent->p_name;
249 for (i = 0; i < sizeof(chain_protos)/sizeof(struct pprot); i++)
250 if (chain_protos[i].num == proto)
251 return chain_protos[i].name;
253 return NULL;
257 service_to_port(const char *name, const char *proto)
259 struct servent *service;
261 if ((service = getservbyname(name, proto)) != NULL)
262 return ntohs((unsigned short) service->s_port);
264 return -1;
267 u_int16_t
268 parse_port(const char *port, const char *proto)
270 unsigned int portnum;
272 if ((string_to_number(port, 0, 65535, &portnum)) != -1 ||
273 (portnum = service_to_port(port, proto)) != -1)
274 return (u_int16_t)portnum;
276 exit_error(PARAMETER_PROBLEM,
277 "invalid port/service `%s' specified", port);
280 enum {
281 IPT_DOTTED_ADDR = 0,
282 IPT_DOTTED_MASK
285 static struct in_addr *
286 __dotted_to_addr(const char *dotted, int type)
288 static struct in_addr addr;
289 unsigned char *addrp;
290 char *p, *q;
291 unsigned int onebyte;
292 int i;
293 char buf[20];
295 /* copy dotted string, because we need to modify it */
296 strncpy(buf, dotted, sizeof(buf) - 1);
297 buf[sizeof(buf) - 1] = '\0';
298 addrp = (unsigned char *) &(addr.s_addr);
300 p = buf;
301 for (i = 0; i < 3; i++) {
302 if ((q = strchr(p, '.')) == NULL) {
303 if (type == IPT_DOTTED_ADDR) {
304 /* autocomplete, this is a network address */
305 if (string_to_number(p, 0, 255, &onebyte) == -1)
306 return (struct in_addr *) NULL;
308 addrp[i] = (unsigned char) onebyte;
309 while (i < 3)
310 addrp[++i] = 0;
312 return &addr;
313 } else
314 return (struct in_addr *) NULL;
317 *q = '\0';
318 if (string_to_number(p, 0, 255, &onebyte) == -1)
319 return (struct in_addr *) NULL;
321 addrp[i] = (unsigned char) onebyte;
322 p = q + 1;
325 /* we've checked 3 bytes, now we check the last one */
326 if (string_to_number(p, 0, 255, &onebyte) == -1)
327 return (struct in_addr *) NULL;
329 addrp[3] = (unsigned char) onebyte;
331 return &addr;
334 struct in_addr *
335 dotted_to_addr(const char *dotted)
337 return __dotted_to_addr(dotted, IPT_DOTTED_ADDR);
340 struct in_addr *
341 dotted_to_mask(const char *dotted)
343 return __dotted_to_addr(dotted, IPT_DOTTED_MASK);
346 static struct in_addr *
347 network_to_addr(const char *name)
349 struct netent *net;
350 static struct in_addr addr;
352 if ((net = getnetbyname(name)) != NULL) {
353 if (net->n_addrtype != AF_INET)
354 return (struct in_addr *) NULL;
355 addr.s_addr = htonl((unsigned long) net->n_net);
356 return &addr;
359 return (struct in_addr *) NULL;
362 static void
363 inaddrcpy(struct in_addr *dst, struct in_addr *src)
365 /* memcpy(dst, src, sizeof(struct in_addr)); */
366 dst->s_addr = src->s_addr;
369 static void free_opts(int reset_offset)
371 if (opts != original_opts) {
372 free(opts);
373 opts = original_opts;
374 if (reset_offset)
375 global_option_offset = 0;
379 void
380 exit_error(enum exittype status, char *msg, ...)
382 va_list args;
384 va_start(args, msg);
385 fprintf(stderr, "%s v%s: ", program_name, program_version);
386 vfprintf(stderr, msg, args);
387 va_end(args);
388 fprintf(stderr, "\n");
389 if (status == PARAMETER_PROBLEM)
390 exit_tryhelp(status);
391 if (status == VERSION_PROBLEM)
392 fprintf(stderr,
393 "Perhaps iptables or your kernel needs to be upgraded.\n");
394 /* On error paths, make sure that we don't leak memory */
395 free_opts(1);
396 exit(status);
399 void
400 exit_tryhelp(int status)
402 if (line != -1)
403 fprintf(stderr, "Error occurred at line: %d\n", line);
404 fprintf(stderr, "Try `%s -h' or '%s --help' for more information.\n",
405 program_name, program_name );
406 free_opts(1);
407 exit(status);
410 void
411 exit_printhelp(struct iptables_rule_match *matches)
413 struct iptables_rule_match *matchp = NULL;
414 struct iptables_target *t = NULL;
416 printf("%s v%s\n\n"
417 "Usage: %s -[AD] chain rule-specification [options]\n"
418 " %s -[RI] chain rulenum rule-specification [options]\n"
419 " %s -D chain rulenum [options]\n"
420 " %s -[LFZ] [chain] [options]\n"
421 " %s -[NX] chain\n"
422 " %s -E old-chain-name new-chain-name\n"
423 " %s -P chain target [options]\n"
424 " %s -h (print this help information)\n\n",
425 program_name, program_version, program_name, program_name,
426 program_name, program_name, program_name, program_name,
427 program_name, program_name);
429 printf(
430 "Commands:\n"
431 "Either long or short options are allowed.\n"
432 " --append -A chain Append to chain\n"
433 " --delete -D chain Delete matching rule from chain\n"
434 " --delete -D chain rulenum\n"
435 " Delete rule rulenum (1 = first) from chain\n"
436 " --insert -I chain [rulenum]\n"
437 " Insert in chain as rulenum (default 1=first)\n"
438 " --replace -R chain rulenum\n"
439 " Replace rule rulenum (1 = first) in chain\n"
440 " --list -L [chain] List the rules in a chain or all chains\n"
441 " --flush -F [chain] Delete all rules in chain or all chains\n"
442 " --zero -Z [chain] Zero counters in chain or all chains\n"
443 " --new -N chain Create a new user-defined chain\n"
444 " --delete-chain\n"
445 " -X [chain] Delete a user-defined chain\n"
446 " --policy -P chain target\n"
447 " Change policy on chain to target\n"
448 " --rename-chain\n"
449 " -E old-chain new-chain\n"
450 " Change chain name, (moving any references)\n"
452 "Options:\n"
453 " --proto -p [!] proto protocol: by number or name, eg. `tcp'\n"
454 " --source -s [!] address[/mask]\n"
455 " source specification\n"
456 " --destination -d [!] address[/mask]\n"
457 " destination specification\n"
458 " --in-interface -i [!] input name[+]\n"
459 " network interface name ([+] for wildcard)\n"
460 " --jump -j target\n"
461 " target for rule (may load target extension)\n"
462 #ifdef IPT_F_GOTO
463 " --goto -g chain\n"
464 " jump to chain with no return\n"
465 #endif
466 " --match -m match\n"
467 " extended match (may load extension)\n"
468 " --numeric -n numeric output of addresses and ports\n"
469 " --out-interface -o [!] output name[+]\n"
470 " network interface name ([+] for wildcard)\n"
471 " --table -t table table to manipulate (default: `filter')\n"
472 " --verbose -v verbose mode\n"
473 " --line-numbers print line numbers when listing\n"
474 " --exact -x expand numbers (display exact values)\n"
475 "[!] --fragment -f match second or further fragments only\n"
476 " --modprobe=<command> try to insert modules using this command\n"
477 " --set-counters PKTS BYTES set the counter during insert/append\n"
478 "[!] --version -V print package version.\n");
480 /* Print out any special helps. A user might like to be able
481 to add a --help to the commandline, and see expected
482 results. So we call help for all specified matches & targets */
483 for (t = iptables_targets; t ;t = t->next) {
484 if (t->used) {
485 printf("\n");
486 t->help();
489 for (matchp = matches; matchp; matchp = matchp->next) {
490 printf("\n");
491 matchp->match->help();
493 exit(0);
496 static void
497 generic_opt_check(int command, int options)
499 int i, j, legal = 0;
501 /* Check that commands are valid with options. Complicated by the
502 * fact that if an option is legal with *any* command given, it is
503 * legal overall (ie. -z and -l).
505 for (i = 0; i < NUMBER_OF_OPT; i++) {
506 legal = 0; /* -1 => illegal, 1 => legal, 0 => undecided. */
508 for (j = 0; j < NUMBER_OF_CMD; j++) {
509 if (!(command & (1<<j)))
510 continue;
512 if (!(options & (1<<i))) {
513 if (commands_v_options[j][i] == '+')
514 exit_error(PARAMETER_PROBLEM,
515 "You need to supply the `-%c' "
516 "option for this command\n",
517 optflags[i]);
518 } else {
519 if (commands_v_options[j][i] != 'x')
520 legal = 1;
521 else if (legal == 0)
522 legal = -1;
525 if (legal == -1)
526 exit_error(PARAMETER_PROBLEM,
527 "Illegal option `-%c' with this command\n",
528 optflags[i]);
532 static char
533 opt2char(int option)
535 const char *ptr;
536 for (ptr = optflags; option > 1; option >>= 1, ptr++);
538 return *ptr;
541 static char
542 cmd2char(int option)
544 const char *ptr;
545 for (ptr = cmdflags; option > 1; option >>= 1, ptr++);
547 return *ptr;
550 static void
551 add_command(unsigned int *cmd, const int newcmd, const int othercmds,
552 int invert)
554 if (invert)
555 exit_error(PARAMETER_PROBLEM, "unexpected ! flag");
556 if (*cmd & (~othercmds))
557 exit_error(PARAMETER_PROBLEM, "Can't use -%c with -%c\n",
558 cmd2char(newcmd), cmd2char(*cmd & (~othercmds)));
559 *cmd |= newcmd;
563 check_inverse(const char option[], int *invert, int *optind, int argc)
565 if (option && strcmp(option, "!") == 0) {
566 if (*invert)
567 exit_error(PARAMETER_PROBLEM,
568 "Multiple `!' flags not allowed");
569 *invert = TRUE;
570 if (optind) {
571 *optind = *optind+1;
572 if (argc && *optind > argc)
573 exit_error(PARAMETER_PROBLEM,
574 "no argument following `!'");
577 return TRUE;
579 return FALSE;
582 static void *
583 fw_calloc(size_t count, size_t size)
585 void *p;
587 if ((p = calloc(count, size)) == NULL) {
588 perror("iptables: calloc failed");
589 exit(1);
591 return p;
594 static void *
595 fw_malloc(size_t size)
597 void *p;
599 if ((p = malloc(size)) == NULL) {
600 perror("iptables: malloc failed");
601 exit(1);
603 return p;
606 static struct in_addr *
607 host_to_addr(const char *name, unsigned int *naddr)
609 struct hostent *host;
610 struct in_addr *addr;
611 unsigned int i;
613 *naddr = 0;
614 if ((host = gethostbyname(name)) != NULL) {
615 if (host->h_addrtype != AF_INET ||
616 host->h_length != sizeof(struct in_addr))
617 return (struct in_addr *) NULL;
619 while (host->h_addr_list[*naddr] != (char *) NULL)
620 (*naddr)++;
621 addr = fw_calloc(*naddr, sizeof(struct in_addr));
622 for (i = 0; i < *naddr; i++)
623 inaddrcpy(&(addr[i]),
624 (struct in_addr *) host->h_addr_list[i]);
625 return addr;
628 return (struct in_addr *) NULL;
631 static char *
632 addr_to_host(const struct in_addr *addr)
634 struct hostent *host;
636 if ((host = gethostbyaddr((char *) addr,
637 sizeof(struct in_addr), AF_INET)) != NULL)
638 return (char *) host->h_name;
640 return (char *) NULL;
644 * All functions starting with "parse" should succeed, otherwise
645 * the program fails.
646 * Most routines return pointers to static data that may change
647 * between calls to the same or other routines with a few exceptions:
648 * "host_to_addr", "parse_hostnetwork", and "parse_hostnetworkmask"
649 * return global static data.
652 static struct in_addr *
653 parse_hostnetwork(const char *name, unsigned int *naddrs)
655 struct in_addr *addrp, *addrptmp;
657 if ((addrptmp = dotted_to_addr(name)) != NULL ||
658 (addrptmp = network_to_addr(name)) != NULL) {
659 addrp = fw_malloc(sizeof(struct in_addr));
660 inaddrcpy(addrp, addrptmp);
661 *naddrs = 1;
662 return addrp;
664 if ((addrp = host_to_addr(name, naddrs)) != NULL)
665 return addrp;
667 exit_error(PARAMETER_PROBLEM, "host/network `%s' not found", name);
670 static struct in_addr *
671 parse_mask(char *mask)
673 static struct in_addr maskaddr;
674 struct in_addr *addrp;
675 unsigned int bits;
677 if (mask == NULL) {
678 /* no mask at all defaults to 32 bits */
679 maskaddr.s_addr = 0xFFFFFFFF;
680 return &maskaddr;
682 if ((addrp = dotted_to_mask(mask)) != NULL)
683 /* dotted_to_addr already returns a network byte order addr */
684 return addrp;
685 if (string_to_number(mask, 0, 32, &bits) == -1)
686 exit_error(PARAMETER_PROBLEM,
687 "invalid mask `%s' specified", mask);
688 if (bits != 0) {
689 maskaddr.s_addr = htonl(0xFFFFFFFF << (32 - bits));
690 return &maskaddr;
693 maskaddr.s_addr = 0L;
694 return &maskaddr;
697 void
698 parse_hostnetworkmask(const char *name, struct in_addr **addrpp,
699 struct in_addr *maskp, unsigned int *naddrs)
701 struct in_addr *addrp;
702 char buf[256];
703 char *p;
704 int i, j, k, n;
706 strncpy(buf, name, sizeof(buf) - 1);
707 buf[sizeof(buf) - 1] = '\0';
708 if ((p = strrchr(buf, '/')) != NULL) {
709 *p = '\0';
710 addrp = parse_mask(p + 1);
711 } else
712 addrp = parse_mask(NULL);
713 inaddrcpy(maskp, addrp);
715 /* if a null mask is given, the name is ignored, like in "any/0" */
716 if (maskp->s_addr == 0L)
717 strcpy(buf, "0.0.0.0");
719 addrp = *addrpp = parse_hostnetwork(buf, naddrs);
720 n = *naddrs;
721 for (i = 0, j = 0; i < n; i++) {
722 addrp[j++].s_addr &= maskp->s_addr;
723 for (k = 0; k < j - 1; k++) {
724 if (addrp[k].s_addr == addrp[j - 1].s_addr) {
725 inaddrcpy( &addrp[--j], &addrp[--(*naddrs)] );
726 break;
732 struct iptables_match *
733 find_match(const char *name, enum ipt_tryload tryload, struct iptables_rule_match **matches)
735 struct iptables_match *ptr;
737 for (ptr = iptables_matches; ptr; ptr = ptr->next) {
738 if (strcmp(name, ptr->name) == 0) {
739 struct iptables_match *clone;
741 /* First match of this type: */
742 if (ptr->m == NULL)
743 break;
745 /* Second and subsequent clones */
746 clone = fw_malloc(sizeof(struct iptables_match));
747 memcpy(clone, ptr, sizeof(struct iptables_match));
748 clone->mflags = 0;
749 /* This is a clone: */
750 clone->next = clone;
752 ptr = clone;
753 break;
757 #ifndef NO_SHARED_LIBS
758 if (!ptr && tryload != DONT_LOAD && tryload != DURING_LOAD) {
759 char path[strlen(lib_dir) + sizeof("/libipt_.so")
760 + strlen(name)];
761 #if 1 // for easier testing zzz
762 char s[256];
763 sprintf(s, "%s/libipt_%s.so", "/etc/iptext/", name);
764 if (dlopen(s, RTLD_NOW)) goto OPENED;
765 #endif
766 sprintf(path, "%s/libipt_%s.so", lib_dir, name);
767 if (dlopen(path, RTLD_NOW)) {
768 OPENED:
769 /* Found library. If it didn't register itself,
770 maybe they specified target as match. */
771 ptr = find_match(name, DONT_LOAD, NULL);
773 if (!ptr)
774 exit_error(PARAMETER_PROBLEM,
775 "Couldn't load match `%s'\n",
776 name);
777 } else if (tryload == LOAD_MUST_SUCCEED)
778 exit_error(PARAMETER_PROBLEM,
779 "Couldn't load match `%s':%s\n",
780 name, dlerror());
782 #else
783 if (ptr && !ptr->loaded) {
784 if (tryload != DONT_LOAD)
785 ptr->loaded = 1;
786 else
787 ptr = NULL;
789 if(!ptr && (tryload == LOAD_MUST_SUCCEED)) {
790 exit_error(PARAMETER_PROBLEM,
791 "Couldn't find match `%s'\n", name);
793 #endif
795 if (ptr && matches) {
796 struct iptables_rule_match **i;
797 struct iptables_rule_match *newentry;
799 newentry = fw_malloc(sizeof(struct iptables_rule_match));
801 for (i = matches; *i; i = &(*i)->next) {
802 if (strcmp(name, (*i)->match->name) == 0)
803 (*i)->completed = 1;
805 newentry->match = ptr;
806 newentry->completed = 0;
807 newentry->next = NULL;
808 *i = newentry;
811 return ptr;
814 /* Christophe Burki wants `-p 6' to imply `-m tcp'. */
815 static struct iptables_match *
816 find_proto(const char *pname, enum ipt_tryload tryload, int nolookup, struct iptables_rule_match **matches)
818 unsigned int proto;
820 if (string_to_number(pname, 0, 255, &proto) != -1) {
821 char *protoname = proto_to_name(proto, nolookup);
823 if (protoname)
824 return find_match(protoname, tryload, matches);
825 } else
826 return find_match(pname, tryload, matches);
828 return NULL;
831 u_int16_t
832 parse_protocol(const char *s)
834 unsigned int proto;
836 if (string_to_number(s, 0, 255, &proto) == -1) {
837 struct protoent *pent;
839 /* first deal with the special case of 'all' to prevent
840 * people from being able to redefine 'all' in nsswitch
841 * and/or provoke expensive [not working] ldap/nis/...
842 * lookups */
843 if (!strcmp(s, "all"))
844 return 0;
846 if ((pent = getprotobyname(s)))
847 proto = pent->p_proto;
848 else {
849 unsigned int i;
850 for (i = 0;
851 i < sizeof(chain_protos)/sizeof(struct pprot);
852 i++) {
853 if (chain_protos[i].name == NULL)
854 continue;
856 if (strcmp(s, chain_protos[i].name) == 0) {
857 proto = chain_protos[i].num;
858 break;
861 if (i == sizeof(chain_protos)/sizeof(struct pprot))
862 exit_error(PARAMETER_PROBLEM,
863 "unknown protocol `%s' specified",
868 return (u_int16_t)proto;
871 void parse_interface(const char *arg, char *vianame, unsigned char *mask)
873 int vialen = strlen(arg);
874 unsigned int i;
876 memset(mask, 0, IFNAMSIZ);
877 memset(vianame, 0, IFNAMSIZ);
879 if (vialen + 1 > IFNAMSIZ)
880 exit_error(PARAMETER_PROBLEM,
881 "interface name `%s' must be shorter than IFNAMSIZ"
882 " (%i)", arg, IFNAMSIZ-1);
884 strcpy(vianame, arg);
885 if ((vialen == 0) || (vialen == 1 && vianame[0] == '+'))
886 memset(mask, 0, IFNAMSIZ);
887 else if (vianame[vialen - 1] == '+') {
888 memset(mask, 0xFF, vialen - 1);
889 memset(mask + vialen - 1, 0, IFNAMSIZ - vialen + 1);
890 /* Don't remove `+' here! -HW */
891 } else {
892 /* Include nul-terminator in match */
893 memset(mask, 0xFF, vialen + 1);
894 memset(mask + vialen + 1, 0, IFNAMSIZ - vialen - 1);
895 for (i = 0; vianame[i]; i++) {
896 if (vianame[i] == ':' ||
897 vianame[i] == '!' ||
898 vianame[i] == '*') {
899 printf("Warning: weird character in interface"
900 " `%s' (No aliases, :, ! or *).\n",
901 vianame);
902 break;
908 /* Can't be zero. */
909 static int
910 parse_rulenumber(const char *rule)
912 unsigned int rulenum;
914 if (string_to_number(rule, 1, INT_MAX, &rulenum) == -1)
915 exit_error(PARAMETER_PROBLEM,
916 "Invalid rule number `%s'", rule);
918 return rulenum;
921 static const char *
922 parse_target(const char *targetname)
924 const char *ptr;
926 if (strlen(targetname) < 1)
927 exit_error(PARAMETER_PROBLEM,
928 "Invalid target name (too short)");
930 if (strlen(targetname)+1 > sizeof(ipt_chainlabel))
931 exit_error(PARAMETER_PROBLEM,
932 "Invalid target name `%s' (%u chars max)",
933 targetname, (unsigned int)sizeof(ipt_chainlabel)-1);
935 for (ptr = targetname; *ptr; ptr++)
936 if (isspace(*ptr))
937 exit_error(PARAMETER_PROBLEM,
938 "Invalid target name `%s'", targetname);
939 return targetname;
942 static char *
943 addr_to_network(const struct in_addr *addr)
945 struct netent *net;
947 if ((net = getnetbyaddr((long) ntohl(addr->s_addr), AF_INET)) != NULL)
948 return (char *) net->n_name;
950 return (char *) NULL;
953 char *
954 addr_to_dotted(const struct in_addr *addrp)
956 static char buf[20];
957 const unsigned char *bytep;
959 bytep = (const unsigned char *) &(addrp->s_addr);
960 sprintf(buf, "%d.%d.%d.%d", bytep[0], bytep[1], bytep[2], bytep[3]);
961 return buf;
964 char *
965 addr_to_anyname(const struct in_addr *addr)
967 char *name;
969 if ((name = addr_to_host(addr)) != NULL ||
970 (name = addr_to_network(addr)) != NULL)
971 return name;
973 return addr_to_dotted(addr);
976 char *
977 mask_to_dotted(const struct in_addr *mask)
979 int i;
980 static char buf[20];
981 u_int32_t maskaddr, bits;
983 maskaddr = ntohl(mask->s_addr);
985 if (maskaddr == 0xFFFFFFFFL)
986 /* we don't want to see "/32" */
987 return "";
989 i = 32;
990 bits = 0xFFFFFFFEL;
991 while (--i >= 0 && maskaddr != bits)
992 bits <<= 1;
993 if (i >= 0)
994 sprintf(buf, "/%d", i);
995 else
996 /* mask was not a decent combination of 1's and 0's */
997 sprintf(buf, "/%s", addr_to_dotted(mask));
999 return buf;
1003 string_to_number_ll(const char *s, unsigned long long min, unsigned long long max,
1004 unsigned long long *ret)
1006 unsigned long long number;
1007 char *end;
1009 /* Handle hex, octal, etc. */
1010 errno = 0;
1011 number = strtoull(s, &end, 0);
1012 if (*end == '\0' && end != s) {
1013 /* we parsed a number, let's see if we want this */
1014 if (errno != ERANGE && min <= number && (!max || number <= max)) {
1015 *ret = number;
1016 return 0;
1019 return -1;
1023 string_to_number_l(const char *s, unsigned long min, unsigned long max,
1024 unsigned long *ret)
1026 int result;
1027 unsigned long long number;
1029 result = string_to_number_ll(s, min, max, &number);
1030 *ret = (unsigned long)number;
1032 return result;
1035 int string_to_number(const char *s, unsigned int min, unsigned int max,
1036 unsigned int *ret)
1038 int result;
1039 unsigned long number;
1041 result = string_to_number_l(s, min, max, &number);
1042 *ret = (unsigned int)number;
1044 return result;
1047 static void
1048 set_option(unsigned int *options, unsigned int option, u_int8_t *invflg,
1049 int invert)
1051 if (*options & option)
1052 exit_error(PARAMETER_PROBLEM, "multiple -%c flags not allowed",
1053 opt2char(option));
1054 *options |= option;
1056 if (invert) {
1057 unsigned int i;
1058 for (i = 0; 1 << i != option; i++);
1060 if (!inverse_for_options[i])
1061 exit_error(PARAMETER_PROBLEM,
1062 "cannot have ! before -%c",
1063 opt2char(option));
1064 *invflg |= inverse_for_options[i];
1068 struct iptables_target *
1069 find_target(const char *name, enum ipt_tryload tryload)
1071 struct iptables_target *ptr;
1073 /* Standard target? */
1074 if (strcmp(name, "") == 0
1075 || strcmp(name, IPTC_LABEL_ACCEPT) == 0
1076 || strcmp(name, IPTC_LABEL_DROP) == 0
1077 || strcmp(name, IPTC_LABEL_QUEUE) == 0
1078 || strcmp(name, IPTC_LABEL_RETURN) == 0)
1079 name = "standard";
1081 for (ptr = iptables_targets; ptr; ptr = ptr->next) {
1082 if (strcmp(name, ptr->name) == 0)
1083 break;
1086 #ifndef NO_SHARED_LIBS
1087 if (!ptr && tryload != DONT_LOAD && tryload != DURING_LOAD) {
1088 char path[strlen(lib_dir) + sizeof("/libipt_.so")
1089 + strlen(name)];
1090 #if 1 // for easier testing zzz
1091 char s[256];
1092 sprintf(s, "%s/libipt_%s.so", "/etc/iptext/", name);
1093 if (dlopen(s, RTLD_NOW)) goto OPENED;
1094 #endif
1095 sprintf(path, "%s/libipt_%s.so", lib_dir, name);
1096 if (dlopen(path, RTLD_NOW)) {
1097 OPENED:
1098 /* Found library. If it didn't register itself,
1099 maybe they specified match as a target. */
1100 ptr = find_target(name, DONT_LOAD);
1101 if (!ptr)
1102 exit_error(PARAMETER_PROBLEM,
1103 "Couldn't load target `%s'\n",
1104 name);
1105 } else if (tryload == LOAD_MUST_SUCCEED)
1106 exit_error(PARAMETER_PROBLEM,
1107 "Couldn't load target `%s':%s\n",
1108 name, dlerror());
1110 #else
1111 if (ptr && !ptr->loaded) {
1112 if (tryload != DONT_LOAD)
1113 ptr->loaded = 1;
1114 else
1115 ptr = NULL;
1117 if(!ptr && (tryload == LOAD_MUST_SUCCEED)) {
1118 exit_error(PARAMETER_PROBLEM,
1119 "Couldn't find target `%s'\n", name);
1121 #endif
1123 if (ptr)
1124 ptr->used = 1;
1126 return ptr;
1129 static struct option *
1130 merge_options(struct option *oldopts, const struct option *newopts,
1131 unsigned int *option_offset)
1133 unsigned int num_old, num_new, i;
1134 struct option *merge;
1136 if (newopts == NULL)
1137 return oldopts;
1139 for (num_old = 0; oldopts[num_old].name; num_old++);
1140 for (num_new = 0; newopts[num_new].name; num_new++);
1142 global_option_offset += OPTION_OFFSET;
1143 *option_offset = global_option_offset;
1145 merge = malloc(sizeof(struct option) * (num_new + num_old + 1));
1146 memcpy(merge, oldopts, num_old * sizeof(struct option));
1147 free_opts(0); /* Release previous options merged if any */
1148 for (i = 0; i < num_new; i++) {
1149 merge[num_old + i] = newopts[i];
1150 merge[num_old + i].val += *option_offset;
1152 memset(merge + num_old + num_new, 0, sizeof(struct option));
1154 return merge;
1157 static int compatible_revision(const char *name, u_int8_t revision, int opt)
1159 struct ipt_get_revision rev;
1160 socklen_t s = sizeof(rev);
1161 int max_rev, sockfd;
1163 sockfd = socket(AF_INET, SOCK_RAW, IPPROTO_RAW);
1164 if (sockfd < 0) {
1165 fprintf(stderr, "Could not open socket to kernel: %s\n",
1166 strerror(errno));
1167 exit(1);
1170 load_iptables_ko(modprobe, 1);
1172 strcpy(rev.name, name);
1173 rev.revision = revision;
1175 max_rev = getsockopt(sockfd, IPPROTO_IP, opt, &rev, &s);
1176 if (max_rev < 0) {
1177 /* Definitely don't support this? */
1178 if (errno == ENOENT || errno == EPROTONOSUPPORT) {
1179 close(sockfd);
1180 return 0;
1181 } else if (errno == ENOPROTOOPT) {
1182 close(sockfd);
1183 /* Assume only revision 0 support (old kernel) */
1184 return (revision == 0);
1185 } else {
1186 fprintf(stderr, "getsockopt failed strangely: %s\n",
1187 strerror(errno));
1188 exit(1);
1191 close(sockfd);
1192 return 1;
1195 static int compatible_match_revision(const char *name, u_int8_t revision)
1197 return compatible_revision(name, revision, IPT_SO_GET_REVISION_MATCH);
1200 static int compatible_target_revision(const char *name, u_int8_t revision)
1202 return compatible_revision(name, revision, IPT_SO_GET_REVISION_TARGET);
1205 void
1206 register_match(struct iptables_match *me)
1208 struct iptables_match **i, *old;
1210 if (strcmp(me->version, program_version) != 0) {
1211 fprintf(stderr, "%s: match `%s' v%s (I'm v%s).\n",
1212 program_name, me->name, me->version, program_version);
1213 exit(1);
1216 /* Revision field stole a char from name. */
1217 if (strlen(me->name) >= IPT_FUNCTION_MAXNAMELEN-1) {
1218 fprintf(stderr, "%s: target `%s' has invalid name\n",
1219 program_name, me->name);
1220 exit(1);
1223 old = find_match(me->name, DURING_LOAD, NULL);
1224 if (old) {
1225 if (old->revision == me->revision) {
1226 fprintf(stderr,
1227 "%s: match `%s' already registered.\n",
1228 program_name, me->name);
1229 exit(1);
1232 /* Now we have two (or more) options, check compatibility. */
1233 if (compatible_match_revision(old->name, old->revision)
1234 && old->revision > me->revision)
1235 return;
1237 /* Replace if compatible. */
1238 if (!compatible_match_revision(me->name, me->revision))
1239 return;
1241 /* Delete old one. */
1242 for (i = &iptables_matches; *i!=old; i = &(*i)->next);
1243 *i = old->next;
1246 if (me->size != IPT_ALIGN(me->size)) {
1247 fprintf(stderr, "%s: match `%s' has invalid size %u.\n",
1248 program_name, me->name, (unsigned int)me->size);
1249 exit(1);
1252 /* Append to list. */
1253 for (i = &iptables_matches; *i; i = &(*i)->next);
1254 me->next = NULL;
1255 *i = me;
1257 me->m = NULL;
1258 me->mflags = 0;
1261 void
1262 register_target(struct iptables_target *me)
1264 struct iptables_target *old;
1266 if (strcmp(me->version, program_version) != 0) {
1267 fprintf(stderr, "%s: target `%s' v%s (I'm v%s).\n",
1268 program_name, me->name, me->version, program_version);
1269 exit(1);
1272 /* Revision field stole a char from name. */
1273 if (strlen(me->name) >= IPT_FUNCTION_MAXNAMELEN-1) {
1274 fprintf(stderr, "%s: target `%s' has invalid name\n",
1275 program_name, me->name);
1276 exit(1);
1279 old = find_target(me->name, DURING_LOAD);
1280 if (old) {
1281 struct iptables_target **i;
1283 if (old->revision == me->revision) {
1284 fprintf(stderr,
1285 "%s: target `%s' already registered.\n",
1286 program_name, me->name);
1287 exit(1);
1290 /* Now we have two (or more) options, check compatibility. */
1291 if (compatible_target_revision(old->name, old->revision)
1292 && old->revision > me->revision)
1293 return;
1295 /* Replace if compatible. */
1296 if (!compatible_target_revision(me->name, me->revision))
1297 return;
1299 /* Delete old one. */
1300 for (i = &iptables_targets; *i!=old; i = &(*i)->next);
1301 *i = old->next;
1304 if (me->size != IPT_ALIGN(me->size)) {
1305 fprintf(stderr, "%s: target `%s' has invalid size %u.\n",
1306 program_name, me->name, (unsigned int)me->size);
1307 exit(1);
1310 /* Prepend to list. */
1311 me->next = iptables_targets;
1312 iptables_targets = me;
1313 me->t = NULL;
1314 me->tflags = 0;
1317 static void
1318 print_num(u_int64_t number, unsigned int format)
1320 if (format & FMT_KILOMEGAGIGA) {
1321 if (number > 99999) {
1322 number = (number + 500) / 1000;
1323 if (number > 9999) {
1324 number = (number + 500) / 1000;
1325 if (number > 9999) {
1326 number = (number + 500) / 1000;
1327 if (number > 9999) {
1328 number = (number + 500) / 1000;
1329 printf(FMT("%4lluT ","%lluT "), (unsigned long long)number);
1331 else printf(FMT("%4lluG ","%lluG "), (unsigned long long)number);
1333 else printf(FMT("%4lluM ","%lluM "), (unsigned long long)number);
1334 } else
1335 printf(FMT("%4lluK ","%lluK "), (unsigned long long)number);
1336 } else
1337 printf(FMT("%5llu ","%llu "), (unsigned long long)number);
1338 } else
1339 printf(FMT("%8llu ","%llu "), (unsigned long long)number);
1343 static void
1344 print_header(unsigned int format, const char *chain, iptc_handle_t *handle)
1346 struct ipt_counters counters;
1347 const char *pol = iptc_get_policy(chain, &counters, handle);
1348 printf("Chain %s", chain);
1349 if (pol) {
1350 printf(" (policy %s", pol);
1351 if (!(format & FMT_NOCOUNTS)) {
1352 fputc(' ', stdout);
1353 print_num(counters.pcnt, (format|FMT_NOTABLE));
1354 fputs("packets, ", stdout);
1355 print_num(counters.bcnt, (format|FMT_NOTABLE));
1356 fputs("bytes", stdout);
1358 printf(")\n");
1359 } else {
1360 unsigned int refs;
1361 if (!iptc_get_references(&refs, chain, handle))
1362 printf(" (ERROR obtaining refs)\n");
1363 else
1364 printf(" (%u references)\n", refs);
1367 if (format & FMT_LINENUMBERS)
1368 printf(FMT("%-4s ", "%s "), "num");
1369 if (!(format & FMT_NOCOUNTS)) {
1370 if (format & FMT_KILOMEGAGIGA) {
1371 printf(FMT("%5s ","%s "), "pkts");
1372 printf(FMT("%5s ","%s "), "bytes");
1373 } else {
1374 printf(FMT("%8s ","%s "), "pkts");
1375 printf(FMT("%10s ","%s "), "bytes");
1378 if (!(format & FMT_NOTARGET))
1379 printf(FMT("%-9s ","%s "), "target");
1380 fputs(" prot ", stdout);
1381 if (format & FMT_OPTIONS)
1382 fputs("opt", stdout);
1383 if (format & FMT_VIA) {
1384 printf(FMT(" %-6s ","%s "), "in");
1385 printf(FMT("%-6s ","%s "), "out");
1387 printf(FMT(" %-19s ","%s "), "source");
1388 printf(FMT(" %-19s "," %s "), "destination");
1389 printf("\n");
1393 static int
1394 print_match(const struct ipt_entry_match *m,
1395 const struct ipt_ip *ip,
1396 int numeric)
1398 struct iptables_match *match = find_match(m->u.user.name, TRY_LOAD, NULL);
1400 if (match) {
1401 if (match->print)
1402 match->print(ip, m, numeric);
1403 else
1404 printf("%s ", match->name);
1405 } else {
1406 if (m->u.user.name[0])
1407 printf("UNKNOWN match `%s' ", m->u.user.name);
1409 /* Don't stop iterating. */
1410 return 0;
1413 /* e is called `fw' here for hysterical raisins */
1414 static void
1415 print_firewall(const struct ipt_entry *fw,
1416 const char *targname,
1417 unsigned int num,
1418 unsigned int format,
1419 const iptc_handle_t handle)
1421 struct iptables_target *target = NULL;
1422 const struct ipt_entry_target *t;
1423 u_int8_t flags;
1424 char buf[BUFSIZ];
1426 if (!iptc_is_chain(targname, handle))
1427 target = find_target(targname, TRY_LOAD);
1428 else
1429 target = find_target(IPT_STANDARD_TARGET, LOAD_MUST_SUCCEED);
1431 t = ipt_get_target((struct ipt_entry *)fw);
1432 flags = fw->ip.flags;
1434 if (format & FMT_LINENUMBERS)
1435 printf(FMT("%-4u ", "%u "), num+1);
1437 if (!(format & FMT_NOCOUNTS)) {
1438 print_num(fw->counters.pcnt, format);
1439 print_num(fw->counters.bcnt, format);
1442 if (!(format & FMT_NOTARGET))
1443 printf(FMT("%-9s ", "%s "), targname);
1445 fputc(fw->ip.invflags & IPT_INV_PROTO ? '!' : ' ', stdout);
1447 char *pname = proto_to_name(fw->ip.proto, format&FMT_NUMERIC);
1448 if (pname)
1449 printf(FMT("%-5s", "%s "), pname);
1450 else
1451 printf(FMT("%-5hu", "%hu "), fw->ip.proto);
1454 if (format & FMT_OPTIONS) {
1455 if (format & FMT_NOTABLE)
1456 fputs("opt ", stdout);
1457 fputc(fw->ip.invflags & IPT_INV_FRAG ? '!' : '-', stdout);
1458 fputc(flags & IPT_F_FRAG ? 'f' : '-', stdout);
1459 fputc(' ', stdout);
1462 if (format & FMT_VIA) {
1463 char iface[IFNAMSIZ+2];
1465 if (fw->ip.invflags & IPT_INV_VIA_IN) {
1466 iface[0] = '!';
1467 iface[1] = '\0';
1469 else iface[0] = '\0';
1471 if (fw->ip.iniface[0] != '\0') {
1472 strcat(iface, fw->ip.iniface);
1474 else if (format & FMT_NUMERIC) strcat(iface, "*");
1475 else strcat(iface, "any");
1476 printf(FMT(" %-6s ","in %s "), iface);
1478 if (fw->ip.invflags & IPT_INV_VIA_OUT) {
1479 iface[0] = '!';
1480 iface[1] = '\0';
1482 else iface[0] = '\0';
1484 if (fw->ip.outiface[0] != '\0') {
1485 strcat(iface, fw->ip.outiface);
1487 else if (format & FMT_NUMERIC) strcat(iface, "*");
1488 else strcat(iface, "any");
1489 printf(FMT("%-6s ","out %s "), iface);
1492 fputc(fw->ip.invflags & IPT_INV_SRCIP ? '!' : ' ', stdout);
1493 if (fw->ip.smsk.s_addr == 0L && !(format & FMT_NUMERIC))
1494 printf(FMT("%-19s ","%s "), "anywhere");
1495 else {
1496 if (format & FMT_NUMERIC)
1497 sprintf(buf, "%s", addr_to_dotted(&(fw->ip.src)));
1498 else
1499 sprintf(buf, "%s", addr_to_anyname(&(fw->ip.src)));
1500 strcat(buf, mask_to_dotted(&(fw->ip.smsk)));
1501 printf(FMT("%-19s ","%s "), buf);
1504 fputc(fw->ip.invflags & IPT_INV_DSTIP ? '!' : ' ', stdout);
1505 if (fw->ip.dmsk.s_addr == 0L && !(format & FMT_NUMERIC))
1506 printf(FMT("%-19s ","-> %s"), "anywhere");
1507 else {
1508 if (format & FMT_NUMERIC)
1509 sprintf(buf, "%s", addr_to_dotted(&(fw->ip.dst)));
1510 else
1511 sprintf(buf, "%s", addr_to_anyname(&(fw->ip.dst)));
1512 strcat(buf, mask_to_dotted(&(fw->ip.dmsk)));
1513 printf(FMT("%-19s ","-> %s"), buf);
1516 if (format & FMT_NOTABLE)
1517 fputs(" ", stdout);
1519 #ifdef IPT_F_GOTO
1520 if(fw->ip.flags & IPT_F_GOTO)
1521 printf("[goto] ");
1522 #endif
1524 IPT_MATCH_ITERATE(fw, print_match, &fw->ip, format & FMT_NUMERIC);
1526 if (target) {
1527 if (target->print)
1528 /* Print the target information. */
1529 target->print(&fw->ip, t, format & FMT_NUMERIC);
1530 } else if (t->u.target_size != sizeof(*t))
1531 printf("[%u bytes of unknown target data] ",
1532 (unsigned int)(t->u.target_size - sizeof(*t)));
1534 if (!(format & FMT_NONEWLINE))
1535 fputc('\n', stdout);
1538 static void
1539 print_firewall_line(const struct ipt_entry *fw,
1540 const iptc_handle_t h)
1542 struct ipt_entry_target *t;
1544 t = ipt_get_target((struct ipt_entry *)fw);
1545 print_firewall(fw, t->u.user.name, 0, FMT_PRINT_RULE, h);
1548 static int
1549 append_entry(const ipt_chainlabel chain,
1550 struct ipt_entry *fw,
1551 unsigned int nsaddrs,
1552 const struct in_addr saddrs[],
1553 unsigned int ndaddrs,
1554 const struct in_addr daddrs[],
1555 int verbose,
1556 iptc_handle_t *handle)
1558 unsigned int i, j;
1559 int ret = 1;
1561 for (i = 0; i < nsaddrs; i++) {
1562 fw->ip.src.s_addr = saddrs[i].s_addr;
1563 for (j = 0; j < ndaddrs; j++) {
1564 fw->ip.dst.s_addr = daddrs[j].s_addr;
1565 if (verbose)
1566 print_firewall_line(fw, *handle);
1567 ret &= iptc_append_entry(chain, fw, handle);
1571 return ret;
1574 static int
1575 replace_entry(const ipt_chainlabel chain,
1576 struct ipt_entry *fw,
1577 unsigned int rulenum,
1578 const struct in_addr *saddr,
1579 const struct in_addr *daddr,
1580 int verbose,
1581 iptc_handle_t *handle)
1583 fw->ip.src.s_addr = saddr->s_addr;
1584 fw->ip.dst.s_addr = daddr->s_addr;
1586 if (verbose)
1587 print_firewall_line(fw, *handle);
1588 return iptc_replace_entry(chain, fw, rulenum, handle);
1591 static int
1592 insert_entry(const ipt_chainlabel chain,
1593 struct ipt_entry *fw,
1594 unsigned int rulenum,
1595 unsigned int nsaddrs,
1596 const struct in_addr saddrs[],
1597 unsigned int ndaddrs,
1598 const struct in_addr daddrs[],
1599 int verbose,
1600 iptc_handle_t *handle)
1602 unsigned int i, j;
1603 int ret = 1;
1605 for (i = 0; i < nsaddrs; i++) {
1606 fw->ip.src.s_addr = saddrs[i].s_addr;
1607 for (j = 0; j < ndaddrs; j++) {
1608 fw->ip.dst.s_addr = daddrs[j].s_addr;
1609 if (verbose)
1610 print_firewall_line(fw, *handle);
1611 ret &= iptc_insert_entry(chain, fw, rulenum, handle);
1615 return ret;
1618 static unsigned char *
1619 make_delete_mask(struct ipt_entry *fw, struct iptables_rule_match *matches,
1620 const struct iptables_target *target)
1622 /* Establish mask for comparison */
1623 unsigned int size;
1624 struct iptables_rule_match *matchp;
1625 unsigned char *mask, *mptr;
1627 size = sizeof(struct ipt_entry);
1628 for (matchp = matches; matchp; matchp = matchp->next)
1629 size += IPT_ALIGN(sizeof(struct ipt_entry_match)) + matchp->match->size;
1631 mask = fw_calloc(1, size
1632 + IPT_ALIGN(sizeof(struct ipt_entry_target))
1633 + target->size);
1635 memset(mask, 0xFF, sizeof(struct ipt_entry));
1636 mptr = mask + sizeof(struct ipt_entry);
1638 for (matchp = matches; matchp; matchp = matchp->next) {
1639 memset(mptr, 0xFF,
1640 IPT_ALIGN(sizeof(struct ipt_entry_match))
1641 + matchp->match->userspacesize);
1642 mptr += IPT_ALIGN(sizeof(struct ipt_entry_match)) + matchp->match->size;
1645 memset(mptr, 0xFF,
1646 IPT_ALIGN(sizeof(struct ipt_entry_target))
1647 + target->userspacesize);
1649 return mask;
1652 static int
1653 delete_entry(const ipt_chainlabel chain,
1654 struct ipt_entry *fw,
1655 unsigned int nsaddrs,
1656 const struct in_addr saddrs[],
1657 unsigned int ndaddrs,
1658 const struct in_addr daddrs[],
1659 int verbose,
1660 iptc_handle_t *handle,
1661 struct iptables_rule_match *matches,
1662 const struct iptables_target *target)
1664 unsigned int i, j;
1665 int ret = 1;
1666 unsigned char *mask;
1668 mask = make_delete_mask(fw, matches, target);
1669 for (i = 0; i < nsaddrs; i++) {
1670 fw->ip.src.s_addr = saddrs[i].s_addr;
1671 for (j = 0; j < ndaddrs; j++) {
1672 fw->ip.dst.s_addr = daddrs[j].s_addr;
1673 if (verbose)
1674 print_firewall_line(fw, *handle);
1675 ret &= iptc_delete_entry(chain, fw, mask, handle);
1678 free(mask);
1680 return ret;
1684 for_each_chain(int (*fn)(const ipt_chainlabel, int, iptc_handle_t *),
1685 int verbose, int builtinstoo, iptc_handle_t *handle)
1687 int ret = 1;
1688 const char *chain;
1689 char *chains;
1690 unsigned int i, chaincount = 0;
1692 chain = iptc_first_chain(handle);
1693 while (chain) {
1694 chaincount++;
1695 chain = iptc_next_chain(handle);
1698 chains = fw_malloc(sizeof(ipt_chainlabel) * chaincount);
1699 i = 0;
1700 chain = iptc_first_chain(handle);
1701 while (chain) {
1702 strcpy(chains + i*sizeof(ipt_chainlabel), chain);
1703 i++;
1704 chain = iptc_next_chain(handle);
1707 for (i = 0; i < chaincount; i++) {
1708 if (!builtinstoo
1709 && iptc_builtin(chains + i*sizeof(ipt_chainlabel),
1710 *handle) == 1)
1711 continue;
1712 ret &= fn(chains + i*sizeof(ipt_chainlabel), verbose, handle);
1715 free(chains);
1716 return ret;
1720 flush_entries(const ipt_chainlabel chain, int verbose,
1721 iptc_handle_t *handle)
1723 if (!chain)
1724 return for_each_chain(flush_entries, verbose, 1, handle);
1726 if (verbose)
1727 fprintf(stdout, "Flushing chain `%s'\n", chain);
1728 return iptc_flush_entries(chain, handle);
1731 static int
1732 zero_entries(const ipt_chainlabel chain, int verbose,
1733 iptc_handle_t *handle)
1735 if (!chain)
1736 return for_each_chain(zero_entries, verbose, 1, handle);
1738 if (verbose)
1739 fprintf(stdout, "Zeroing chain `%s'\n", chain);
1740 return iptc_zero_entries(chain, handle);
1744 delete_chain(const ipt_chainlabel chain, int verbose,
1745 iptc_handle_t *handle)
1747 if (!chain)
1748 return for_each_chain(delete_chain, verbose, 0, handle);
1750 if (verbose)
1751 fprintf(stdout, "Deleting chain `%s'\n", chain);
1752 return iptc_delete_chain(chain, handle);
1755 static int
1756 list_entries(const ipt_chainlabel chain, int verbose, int numeric,
1757 int expanded, int linenumbers, iptc_handle_t *handle)
1759 int found = 0;
1760 unsigned int format;
1761 const char *this;
1763 format = FMT_OPTIONS;
1764 if (!verbose)
1765 format |= FMT_NOCOUNTS;
1766 else
1767 format |= FMT_VIA;
1769 if (numeric)
1770 format |= FMT_NUMERIC;
1772 if (!expanded)
1773 format |= FMT_KILOMEGAGIGA;
1775 if (linenumbers)
1776 format |= FMT_LINENUMBERS;
1778 for (this = iptc_first_chain(handle);
1779 this;
1780 this = iptc_next_chain(handle)) {
1781 const struct ipt_entry *i;
1782 unsigned int num;
1784 if (chain && strcmp(chain, this) != 0)
1785 continue;
1787 if (found) printf("\n");
1789 print_header(format, this, handle);
1790 i = iptc_first_rule(this, handle);
1792 num = 0;
1793 while (i) {
1794 print_firewall(i,
1795 iptc_get_target(i, handle),
1796 num++,
1797 format,
1798 *handle);
1799 i = iptc_next_rule(i, handle);
1801 found = 1;
1804 errno = ENOENT;
1805 return found;
1808 static char *get_modprobe(void)
1810 return strdup("/sbin/modprobe");
1811 #if 0
1812 int procfile;
1813 char *ret;
1815 #define PROCFILE_BUFSIZ 1024
1816 procfile = open(PROC_SYS_MODPROBE, O_RDONLY);
1817 if (procfile < 0)
1818 return NULL;
1820 ret = (char *) malloc(PROCFILE_BUFSIZ);
1821 if (ret) {
1822 memset(ret, 0, PROCFILE_BUFSIZ);
1823 switch (read(procfile, ret, PROCFILE_BUFSIZ)) {
1824 case -1: goto fail;
1825 case PROCFILE_BUFSIZ: goto fail; /* Partial read. Wierd */
1827 if (ret[strlen(ret)-1]=='\n')
1828 ret[strlen(ret)-1]=0;
1829 close(procfile);
1830 return ret;
1832 fail:
1833 free(ret);
1834 close(procfile);
1835 return NULL;
1836 #endif
1839 int iptables_insmod(const char *modname, const char *modprobe, int quiet)
1841 char *buf = NULL;
1842 char *argv[4];
1843 int status;
1845 /* If they don't explicitly set it, read out of kernel */
1846 if (!modprobe) {
1847 buf = get_modprobe();
1848 if (!buf)
1849 return -1;
1850 modprobe = buf;
1853 switch (fork()) {
1854 case 0:
1855 argv[0] = (char *)modprobe;
1856 argv[1] = (char *)modname;
1857 if (quiet) {
1858 argv[2] = "-q";
1859 argv[3] = NULL;
1860 } else {
1861 argv[2] = NULL;
1862 argv[3] = NULL;
1864 execv(argv[0], argv);
1866 /* not usually reached */
1867 exit(1);
1868 case -1:
1869 return -1;
1871 default: /* parent */
1872 wait(&status);
1875 free(buf);
1876 if (WIFEXITED(status) && WEXITSTATUS(status) == 0)
1877 return 0;
1878 return -1;
1881 int load_iptables_ko(const char *modprobe, int quiet)
1883 // not needed, modprobe will be just noisy -- zzz
1884 return 0;
1886 static int loaded = 0;
1887 static int ret = -1;
1889 if (!loaded) {
1890 ret = iptables_insmod("ip_tables", modprobe, quiet);
1891 loaded = (ret == 0);
1894 return ret;
1898 static struct ipt_entry *
1899 generate_entry(const struct ipt_entry *fw,
1900 struct iptables_rule_match *matches,
1901 struct ipt_entry_target *target)
1903 unsigned int size;
1904 struct iptables_rule_match *matchp;
1905 struct ipt_entry *e;
1907 size = sizeof(struct ipt_entry);
1908 for (matchp = matches; matchp; matchp = matchp->next)
1909 size += matchp->match->m->u.match_size;
1911 e = fw_malloc(size + target->u.target_size);
1912 *e = *fw;
1913 e->target_offset = size;
1914 e->next_offset = size + target->u.target_size;
1916 size = 0;
1917 for (matchp = matches; matchp; matchp = matchp->next) {
1918 memcpy(e->elems + size, matchp->match->m, matchp->match->m->u.match_size);
1919 size += matchp->match->m->u.match_size;
1921 memcpy(e->elems + size, target, target->u.target_size);
1923 return e;
1926 void clear_rule_matches(struct iptables_rule_match **matches)
1928 struct iptables_rule_match *matchp, *tmp;
1930 for (matchp = *matches; matchp;) {
1931 tmp = matchp->next;
1932 if (matchp->match->m) {
1933 free(matchp->match->m);
1934 matchp->match->m = NULL;
1936 if (matchp->match == matchp->match->next) {
1937 free(matchp->match);
1938 matchp->match = NULL;
1940 free(matchp);
1941 matchp = tmp;
1944 *matches = NULL;
1947 static void set_revision(char *name, u_int8_t revision)
1949 /* Old kernel sources don't have ".revision" field,
1950 but we stole a byte from name. */
1951 name[IPT_FUNCTION_MAXNAMELEN - 2] = '\0';
1952 name[IPT_FUNCTION_MAXNAMELEN - 1] = revision;
1955 void
1956 get_kernel_version(void) {
1957 static struct utsname uts;
1958 int x = 0, y = 0, z = 0;
1960 if (uname(&uts) == -1) {
1961 fprintf(stderr, "Unable to retrieve kernel version.\n");
1962 free_opts(1);
1963 exit(1);
1966 sscanf(uts.release, "%d.%d.%d", &x, &y, &z);
1967 kernel_version = LINUX_VERSION(x, y, z);
1970 int do_command(int argc, char *argv[], char **table, iptc_handle_t *handle)
1972 struct ipt_entry fw, *e = NULL;
1973 int invert = 0;
1974 unsigned int nsaddrs = 0, ndaddrs = 0;
1975 struct in_addr *saddrs = NULL, *daddrs = NULL;
1977 int c, verbose = 0;
1978 const char *chain = NULL;
1979 const char *shostnetworkmask = NULL, *dhostnetworkmask = NULL;
1980 const char *policy = NULL, *newname = NULL;
1981 unsigned int rulenum = 0, options = 0, command = 0;
1982 const char *pcnt = NULL, *bcnt = NULL;
1983 int ret = 1;
1984 struct iptables_match *m;
1985 struct iptables_rule_match *matches = NULL;
1986 struct iptables_rule_match *matchp;
1987 struct iptables_target *target = NULL;
1988 struct iptables_target *t;
1989 const char *jumpto = "";
1990 char *protocol = NULL;
1991 int proto_used = 0;
1992 unsigned long long cnt;
1994 memset(&fw, 0, sizeof(fw));
1996 /* re-set optind to 0 in case do_command gets called
1997 * a second time */
1998 optind = 0;
2000 /* clear mflags in case do_command gets called a second time
2001 * (we clear the global list of all matches for security)*/
2002 for (m = iptables_matches; m; m = m->next)
2003 m->mflags = 0;
2005 for (t = iptables_targets; t; t = t->next) {
2006 t->tflags = 0;
2007 t->used = 0;
2010 /* Suppress error messages: we may add new options if we
2011 demand-load a protocol. */
2012 opterr = 0;
2014 while ((c = getopt_long(argc, argv,
2015 "-A:D:R:I:L::M:F::Z::N:X::E:P:Vh::o:p:s:d:j:i:fbvnt:m:xc:g:",
2016 opts, NULL)) != -1) {
2017 switch (c) {
2019 * Command selection
2021 case 'A':
2022 add_command(&command, CMD_APPEND, CMD_NONE,
2023 invert);
2024 chain = optarg;
2025 break;
2027 case 'D':
2028 add_command(&command, CMD_DELETE, CMD_NONE,
2029 invert);
2030 chain = optarg;
2031 if (optind < argc && argv[optind][0] != '-'
2032 && argv[optind][0] != '!') {
2033 rulenum = parse_rulenumber(argv[optind++]);
2034 command = CMD_DELETE_NUM;
2036 break;
2038 case 'R':
2039 add_command(&command, CMD_REPLACE, CMD_NONE,
2040 invert);
2041 chain = optarg;
2042 if (optind < argc && argv[optind][0] != '-'
2043 && argv[optind][0] != '!')
2044 rulenum = parse_rulenumber(argv[optind++]);
2045 else
2046 exit_error(PARAMETER_PROBLEM,
2047 "-%c requires a rule number",
2048 cmd2char(CMD_REPLACE));
2049 break;
2051 case 'I':
2052 add_command(&command, CMD_INSERT, CMD_NONE,
2053 invert);
2054 chain = optarg;
2055 if (optind < argc && argv[optind][0] != '-'
2056 && argv[optind][0] != '!')
2057 rulenum = parse_rulenumber(argv[optind++]);
2058 else rulenum = 1;
2059 break;
2061 case 'L':
2062 add_command(&command, CMD_LIST, CMD_ZERO,
2063 invert);
2064 if (optarg) chain = optarg;
2065 else if (optind < argc && argv[optind][0] != '-'
2066 && argv[optind][0] != '!')
2067 chain = argv[optind++];
2068 break;
2070 case 'F':
2071 add_command(&command, CMD_FLUSH, CMD_NONE,
2072 invert);
2073 if (optarg) chain = optarg;
2074 else if (optind < argc && argv[optind][0] != '-'
2075 && argv[optind][0] != '!')
2076 chain = argv[optind++];
2077 break;
2079 case 'Z':
2080 add_command(&command, CMD_ZERO, CMD_LIST,
2081 invert);
2082 if (optarg) chain = optarg;
2083 else if (optind < argc && argv[optind][0] != '-'
2084 && argv[optind][0] != '!')
2085 chain = argv[optind++];
2086 break;
2088 case 'N':
2089 if (optarg && (*optarg == '-' || *optarg == '!'))
2090 exit_error(PARAMETER_PROBLEM,
2091 "chain name not allowed to start "
2092 "with `%c'\n", *optarg);
2093 if (find_target(optarg, TRY_LOAD))
2094 exit_error(PARAMETER_PROBLEM,
2095 "chain name may not clash "
2096 "with target name\n");
2097 add_command(&command, CMD_NEW_CHAIN, CMD_NONE,
2098 invert);
2099 chain = optarg;
2100 break;
2102 case 'X':
2103 add_command(&command, CMD_DELETE_CHAIN, CMD_NONE,
2104 invert);
2105 if (optarg) chain = optarg;
2106 else if (optind < argc && argv[optind][0] != '-'
2107 && argv[optind][0] != '!')
2108 chain = argv[optind++];
2109 break;
2111 case 'E':
2112 add_command(&command, CMD_RENAME_CHAIN, CMD_NONE,
2113 invert);
2114 chain = optarg;
2115 if (optind < argc && argv[optind][0] != '-'
2116 && argv[optind][0] != '!')
2117 newname = argv[optind++];
2118 else
2119 exit_error(PARAMETER_PROBLEM,
2120 "-%c requires old-chain-name and "
2121 "new-chain-name",
2122 cmd2char(CMD_RENAME_CHAIN));
2123 break;
2125 case 'P':
2126 add_command(&command, CMD_SET_POLICY, CMD_NONE,
2127 invert);
2128 chain = optarg;
2129 if (optind < argc && argv[optind][0] != '-'
2130 && argv[optind][0] != '!')
2131 policy = argv[optind++];
2132 else
2133 exit_error(PARAMETER_PROBLEM,
2134 "-%c requires a chain and a policy",
2135 cmd2char(CMD_SET_POLICY));
2136 break;
2138 case 'h':
2139 if (!optarg)
2140 optarg = argv[optind];
2142 /* iptables -p icmp -h */
2143 if (!matches && protocol)
2144 find_match(protocol, TRY_LOAD, &matches);
2146 exit_printhelp(matches);
2149 * Option selection
2151 case 'p':
2152 check_inverse(optarg, &invert, &optind, argc);
2153 set_option(&options, OPT_PROTOCOL, &fw.ip.invflags,
2154 invert);
2156 /* Canonicalize into lower case */
2157 for (protocol = argv[optind-1]; *protocol; protocol++)
2158 *protocol = tolower(*protocol);
2160 protocol = argv[optind-1];
2161 fw.ip.proto = parse_protocol(protocol);
2163 if (fw.ip.proto == 0
2164 && (fw.ip.invflags & IPT_INV_PROTO))
2165 exit_error(PARAMETER_PROBLEM,
2166 "rule would never match protocol");
2167 break;
2169 case 's':
2170 check_inverse(optarg, &invert, &optind, argc);
2171 set_option(&options, OPT_SOURCE, &fw.ip.invflags,
2172 invert);
2173 shostnetworkmask = argv[optind-1];
2174 break;
2176 case 'd':
2177 check_inverse(optarg, &invert, &optind, argc);
2178 set_option(&options, OPT_DESTINATION, &fw.ip.invflags,
2179 invert);
2180 dhostnetworkmask = argv[optind-1];
2181 break;
2183 #ifdef IPT_F_GOTO
2184 case 'g':
2185 set_option(&options, OPT_JUMP, &fw.ip.invflags,
2186 invert);
2187 fw.ip.flags |= IPT_F_GOTO;
2188 jumpto = parse_target(optarg);
2189 break;
2190 #endif
2192 case 'j':
2193 set_option(&options, OPT_JUMP, &fw.ip.invflags,
2194 invert);
2195 jumpto = parse_target(optarg);
2196 /* TRY_LOAD (may be chain name) */
2197 target = find_target(jumpto, TRY_LOAD);
2199 if (target) {
2200 size_t size;
2202 size = IPT_ALIGN(sizeof(struct ipt_entry_target))
2203 + target->size;
2205 target->t = fw_calloc(1, size);
2206 target->t->u.target_size = size;
2207 strcpy(target->t->u.user.name, jumpto);
2208 set_revision(target->t->u.user.name,
2209 target->revision);
2210 if (target->init != NULL)
2211 target->init(target->t, &fw.nfcache);
2212 opts = merge_options(opts,
2213 target->extra_opts,
2214 &target->option_offset);
2215 if (opts == NULL)
2216 exit_error(OTHER_PROBLEM,
2217 "can't alloc memory!");
2219 break;
2222 case 'i':
2223 check_inverse(optarg, &invert, &optind, argc);
2224 set_option(&options, OPT_VIANAMEIN, &fw.ip.invflags,
2225 invert);
2226 parse_interface(argv[optind-1],
2227 fw.ip.iniface,
2228 fw.ip.iniface_mask);
2229 break;
2231 case 'o':
2232 check_inverse(optarg, &invert, &optind, argc);
2233 set_option(&options, OPT_VIANAMEOUT, &fw.ip.invflags,
2234 invert);
2235 parse_interface(argv[optind-1],
2236 fw.ip.outiface,
2237 fw.ip.outiface_mask);
2238 break;
2240 case 'f':
2241 set_option(&options, OPT_FRAGMENT, &fw.ip.invflags,
2242 invert);
2243 fw.ip.flags |= IPT_F_FRAG;
2244 break;
2246 case 'v':
2247 if (!verbose)
2248 set_option(&options, OPT_VERBOSE,
2249 &fw.ip.invflags, invert);
2250 verbose++;
2251 break;
2253 case 'm': {
2254 size_t size;
2256 if (invert)
2257 exit_error(PARAMETER_PROBLEM,
2258 "unexpected ! flag before --match");
2260 m = find_match(optarg, LOAD_MUST_SUCCEED, &matches);
2261 size = IPT_ALIGN(sizeof(struct ipt_entry_match))
2262 + m->size;
2263 m->m = fw_calloc(1, size);
2264 m->m->u.match_size = size;
2265 strcpy(m->m->u.user.name, m->name);
2266 set_revision(m->m->u.user.name, m->revision);
2267 if (m->init != NULL)
2268 m->init(m->m, &fw.nfcache);
2269 if (m != m->next)
2270 /* Merge options for non-cloned matches */
2271 opts = merge_options(opts, m->extra_opts, &m->option_offset);
2273 break;
2275 case 'n':
2276 set_option(&options, OPT_NUMERIC, &fw.ip.invflags,
2277 invert);
2278 break;
2280 case 't':
2281 if (invert)
2282 exit_error(PARAMETER_PROBLEM,
2283 "unexpected ! flag before --table");
2284 *table = optarg;
2285 break;
2287 case 'x':
2288 set_option(&options, OPT_EXPANDED, &fw.ip.invflags,
2289 invert);
2290 break;
2292 case 'V':
2293 if (invert)
2294 printf("Not %s ;-)\n", program_version);
2295 else
2296 printf("%s v%s\n",
2297 program_name, program_version);
2298 exit(0);
2300 case '0':
2301 set_option(&options, OPT_LINENUMBERS, &fw.ip.invflags,
2302 invert);
2303 break;
2305 case 'M':
2306 modprobe = optarg;
2307 break;
2309 case 'c':
2311 set_option(&options, OPT_COUNTERS, &fw.ip.invflags,
2312 invert);
2313 pcnt = optarg;
2314 if (optind < argc && argv[optind][0] != '-'
2315 && argv[optind][0] != '!')
2316 bcnt = argv[optind++];
2317 else
2318 exit_error(PARAMETER_PROBLEM,
2319 "-%c requires packet and byte counter",
2320 opt2char(OPT_COUNTERS));
2322 if (sscanf(pcnt, "%llu", (unsigned long long *)&cnt) != 1)
2323 exit_error(PARAMETER_PROBLEM,
2324 "-%c packet counter not numeric",
2325 opt2char(OPT_COUNTERS));
2326 fw.counters.pcnt = cnt;
2328 if (sscanf(bcnt, "%llu", (unsigned long long *)&cnt) != 1)
2329 exit_error(PARAMETER_PROBLEM,
2330 "-%c byte counter not numeric",
2331 opt2char(OPT_COUNTERS));
2332 fw.counters.bcnt = cnt;
2334 break;
2337 case 1: /* non option */
2338 if (optarg[0] == '!' && optarg[1] == '\0') {
2339 if (invert)
2340 exit_error(PARAMETER_PROBLEM,
2341 "multiple consecutive ! not"
2342 " allowed");
2343 invert = TRUE;
2344 optarg[0] = '\0';
2345 continue;
2347 printf("Bad argument `%s'\n", optarg);
2348 exit_tryhelp(2);
2350 default:
2351 if (target == NULL || target->parse == NULL ||
2352 c < target->option_offset ||
2353 c >= target->option_offset + OPTION_OFFSET ||
2354 !(target->parse(c - target->option_offset,
2355 argv, invert,
2356 &target->tflags,
2357 &fw, &target->t))) {
2358 for (matchp = matches; matchp; matchp = matchp->next) {
2359 if (matchp->completed ||
2360 matchp->match->parse == NULL)
2361 continue;
2362 if (c < matchp->match->option_offset ||
2363 c >= matchp->match->option_offset + OPTION_OFFSET)
2364 continue;
2365 if (matchp->match->parse(c - matchp->match->option_offset,
2366 argv, invert,
2367 &matchp->match->mflags,
2368 &fw,
2369 &fw.nfcache,
2370 &matchp->match->m))
2371 break;
2373 m = matchp ? matchp->match : NULL;
2375 /* If you listen carefully, you can
2376 actually hear this code suck. */
2378 /* some explanations (after four different bugs
2379 * in 3 different releases): If we encounter a
2380 * parameter, that has not been parsed yet,
2381 * it's not an option of an explicitly loaded
2382 * match or a target. However, we support
2383 * implicit loading of the protocol match
2384 * extension. '-p tcp' means 'l4 proto 6' and
2385 * at the same time 'load tcp protocol match on
2386 * demand if we specify --dport'.
2388 * To make this work, we need to make sure:
2389 * - the parameter has not been parsed by
2390 * a match (m above)
2391 * - a protocol has been specified
2392 * - the protocol extension has not been
2393 * loaded yet, or is loaded and unused
2394 * [think of iptables-restore!]
2395 * - the protocol extension can be successively
2396 * loaded
2398 if (m == NULL
2399 && protocol
2400 && (!find_proto(protocol, DONT_LOAD,
2401 options&OPT_NUMERIC, NULL)
2402 || (find_proto(protocol, DONT_LOAD,
2403 options&OPT_NUMERIC, NULL)
2404 && (proto_used == 0))
2406 && (m = find_proto(protocol, TRY_LOAD,
2407 options&OPT_NUMERIC, &matches))) {
2408 /* Try loading protocol */
2409 size_t size;
2411 proto_used = 1;
2413 size = IPT_ALIGN(sizeof(struct ipt_entry_match))
2414 + m->size;
2416 m->m = fw_calloc(1, size);
2417 m->m->u.match_size = size;
2418 strcpy(m->m->u.user.name, m->name);
2419 set_revision(m->m->u.user.name,
2420 m->revision);
2421 if (m->init != NULL)
2422 m->init(m->m, &fw.nfcache);
2424 opts = merge_options(opts,
2425 m->extra_opts, &m->option_offset);
2427 optind--;
2428 continue;
2430 if (!m)
2431 exit_error(PARAMETER_PROBLEM,
2432 "Unknown arg `%s'", optarg);
2435 invert = FALSE;
2438 for (matchp = matches; matchp; matchp = matchp->next)
2439 matchp->match->final_check(matchp->match->mflags);
2441 if (target)
2442 target->final_check(target->tflags);
2444 /* Fix me: must put inverse options checking here --MN */
2446 if (optind < argc)
2447 exit_error(PARAMETER_PROBLEM,
2448 "unknown arguments found on commandline");
2449 if (!command)
2450 exit_error(PARAMETER_PROBLEM, "no command specified");
2451 if (invert)
2452 exit_error(PARAMETER_PROBLEM,
2453 "nothing appropriate following !");
2455 if (command & (CMD_REPLACE | CMD_INSERT | CMD_DELETE | CMD_APPEND)) {
2456 if (!(options & OPT_DESTINATION))
2457 dhostnetworkmask = "0.0.0.0/0";
2458 if (!(options & OPT_SOURCE))
2459 shostnetworkmask = "0.0.0.0/0";
2462 if (shostnetworkmask)
2463 parse_hostnetworkmask(shostnetworkmask, &saddrs,
2464 &(fw.ip.smsk), &nsaddrs);
2466 if (dhostnetworkmask)
2467 parse_hostnetworkmask(dhostnetworkmask, &daddrs,
2468 &(fw.ip.dmsk), &ndaddrs);
2470 if ((nsaddrs > 1 || ndaddrs > 1) &&
2471 (fw.ip.invflags & (IPT_INV_SRCIP | IPT_INV_DSTIP)))
2472 exit_error(PARAMETER_PROBLEM, "! not allowed with multiple"
2473 " source or destination IP addresses");
2475 if (command == CMD_REPLACE && (nsaddrs != 1 || ndaddrs != 1))
2476 exit_error(PARAMETER_PROBLEM, "Replacement rule does not "
2477 "specify a unique address");
2479 generic_opt_check(command, options);
2481 if (chain && strlen(chain) > IPT_FUNCTION_MAXNAMELEN)
2482 exit_error(PARAMETER_PROBLEM,
2483 "chain name `%s' too long (must be under %i chars)",
2484 chain, IPT_FUNCTION_MAXNAMELEN);
2486 /* only allocate handle if we weren't called with a handle */
2487 if (!*handle)
2488 *handle = iptc_init(*table);
2490 /* try to insmod the module if iptc_init failed */
2491 if (!*handle && load_iptables_ko(modprobe, 0) != -1)
2492 *handle = iptc_init(*table);
2494 if (!*handle)
2495 exit_error(VERSION_PROBLEM,
2496 "can't initialize iptables table `%s': %s",
2497 *table, iptc_strerror(errno));
2499 if (command == CMD_APPEND
2500 || command == CMD_DELETE
2501 || command == CMD_INSERT
2502 || command == CMD_REPLACE) {
2503 if (strcmp(chain, "PREROUTING") == 0
2504 || strcmp(chain, "INPUT") == 0) {
2505 /* -o not valid with incoming packets. */
2506 if (options & OPT_VIANAMEOUT)
2507 exit_error(PARAMETER_PROBLEM,
2508 "Can't use -%c with %s\n",
2509 opt2char(OPT_VIANAMEOUT),
2510 chain);
2513 if (strcmp(chain, "POSTROUTING") == 0
2514 || strcmp(chain, "OUTPUT") == 0) {
2515 /* -i not valid with outgoing packets */
2516 if (options & OPT_VIANAMEIN)
2517 exit_error(PARAMETER_PROBLEM,
2518 "Can't use -%c with %s\n",
2519 opt2char(OPT_VIANAMEIN),
2520 chain);
2523 if (target && iptc_is_chain(jumpto, *handle)) {
2524 printf("Warning: using chain %s, not extension\n",
2525 jumpto);
2527 if (target->t)
2528 free(target->t);
2530 target = NULL;
2533 /* If they didn't specify a target, or it's a chain
2534 name, use standard. */
2535 if (!target
2536 && (strlen(jumpto) == 0
2537 || iptc_is_chain(jumpto, *handle))) {
2538 size_t size;
2540 target = find_target(IPT_STANDARD_TARGET,
2541 LOAD_MUST_SUCCEED);
2543 size = sizeof(struct ipt_entry_target)
2544 + target->size;
2545 target->t = fw_calloc(1, size);
2546 target->t->u.target_size = size;
2547 strcpy(target->t->u.user.name, jumpto);
2548 if (!iptc_is_chain(jumpto, *handle))
2549 set_revision(target->t->u.user.name,
2550 target->revision);
2551 if (target->init != NULL)
2552 target->init(target->t, &fw.nfcache);
2555 if (!target) {
2556 /* it is no chain, and we can't load a plugin.
2557 * We cannot know if the plugin is corrupt, non
2558 * existant OR if the user just misspelled a
2559 * chain. */
2560 #ifdef IPT_F_GOTO
2561 if (fw.ip.flags & IPT_F_GOTO)
2562 exit_error(PARAMETER_PROBLEM,
2563 "goto '%s' is not a chain\n", jumpto);
2564 #endif
2565 find_target(jumpto, LOAD_MUST_SUCCEED);
2566 } else {
2567 e = generate_entry(&fw, matches, target->t);
2568 free(target->t);
2572 switch (command) {
2573 case CMD_APPEND:
2574 ret = append_entry(chain, e,
2575 nsaddrs, saddrs, ndaddrs, daddrs,
2576 options&OPT_VERBOSE,
2577 handle);
2578 break;
2579 case CMD_DELETE:
2580 ret = delete_entry(chain, e,
2581 nsaddrs, saddrs, ndaddrs, daddrs,
2582 options&OPT_VERBOSE,
2583 handle, matches, target);
2584 break;
2585 case CMD_DELETE_NUM:
2586 ret = iptc_delete_num_entry(chain, rulenum - 1, handle);
2587 break;
2588 case CMD_REPLACE:
2589 ret = replace_entry(chain, e, rulenum - 1,
2590 saddrs, daddrs, options&OPT_VERBOSE,
2591 handle);
2592 break;
2593 case CMD_INSERT:
2594 ret = insert_entry(chain, e, rulenum - 1,
2595 nsaddrs, saddrs, ndaddrs, daddrs,
2596 options&OPT_VERBOSE,
2597 handle);
2598 break;
2599 case CMD_LIST:
2600 ret = list_entries(chain,
2601 options&OPT_VERBOSE,
2602 options&OPT_NUMERIC,
2603 options&OPT_EXPANDED,
2604 options&OPT_LINENUMBERS,
2605 handle);
2606 break;
2607 case CMD_FLUSH:
2608 ret = flush_entries(chain, options&OPT_VERBOSE, handle);
2609 break;
2610 case CMD_ZERO:
2611 ret = zero_entries(chain, options&OPT_VERBOSE, handle);
2612 break;
2613 case CMD_LIST|CMD_ZERO:
2614 ret = list_entries(chain,
2615 options&OPT_VERBOSE,
2616 options&OPT_NUMERIC,
2617 options&OPT_EXPANDED,
2618 options&OPT_LINENUMBERS,
2619 handle);
2620 if (ret)
2621 ret = zero_entries(chain,
2622 options&OPT_VERBOSE, handle);
2623 break;
2624 case CMD_NEW_CHAIN:
2625 ret = iptc_create_chain(chain, handle);
2626 break;
2627 case CMD_DELETE_CHAIN:
2628 ret = delete_chain(chain, options&OPT_VERBOSE, handle);
2629 break;
2630 case CMD_RENAME_CHAIN:
2631 ret = iptc_rename_chain(chain, newname, handle);
2632 break;
2633 case CMD_SET_POLICY:
2634 ret = iptc_set_policy(chain, policy, NULL, handle);
2635 break;
2636 default:
2637 /* We should never reach this... */
2638 exit_tryhelp(2);
2641 if (verbose > 1)
2642 dump_entries(*handle);
2644 clear_rule_matches(&matches);
2646 if (e != NULL) {
2647 free(e);
2648 e = NULL;
2651 free(saddrs);
2652 free(daddrs);
2653 free_opts(1);
2655 return ret;