iptables: support for ip6tables "--goto" option
[tomato.git] / release / src / router / iptables / ip6tables.c
blob9ab8b1b9fc88be863fc591c8d4a723b6e748079b
1 /* Code to take an ip6tables-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 <ip6tables.h>
39 #include <arpa/inet.h>
40 #include <unistd.h>
41 #include <fcntl.h>
42 #include <sys/wait.h>
43 #include <sys/types.h>
44 #include <sys/socket.h>
46 #ifndef TRUE
47 #define TRUE 1
48 #endif
49 #ifndef FALSE
50 #define FALSE 0
51 #endif
53 #ifndef PROC_SYS_MODPROBE
54 #define PROC_SYS_MODPROBE "/proc/sys/kernel/modprobe"
55 #endif
57 #define FMT_NUMERIC 0x0001
58 #define FMT_NOCOUNTS 0x0002
59 #define FMT_KILOMEGAGIGA 0x0004
60 #define FMT_OPTIONS 0x0008
61 #define FMT_NOTABLE 0x0010
62 #define FMT_NOTARGET 0x0020
63 #define FMT_VIA 0x0040
64 #define FMT_NONEWLINE 0x0080
65 #define FMT_LINENUMBERS 0x0100
67 #define FMT_PRINT_RULE (FMT_NOCOUNTS | FMT_OPTIONS | FMT_VIA \
68 | FMT_NUMERIC | FMT_NOTABLE)
69 #define FMT(tab,notab) ((format) & FMT_NOTABLE ? (notab) : (tab))
72 #define CMD_NONE 0x0000U
73 #define CMD_INSERT 0x0001U
74 #define CMD_DELETE 0x0002U
75 #define CMD_DELETE_NUM 0x0004U
76 #define CMD_REPLACE 0x0008U
77 #define CMD_APPEND 0x0010U
78 #define CMD_LIST 0x0020U
79 #define CMD_FLUSH 0x0040U
80 #define CMD_ZERO 0x0080U
81 #define CMD_NEW_CHAIN 0x0100U
82 #define CMD_DELETE_CHAIN 0x0200U
83 #define CMD_SET_POLICY 0x0400U
84 #define CMD_RENAME_CHAIN 0x0800U
85 #define NUMBER_OF_CMD 13
86 static const char cmdflags[] = { 'I', 'D', 'D', 'R', 'A', 'L', 'F', 'Z',
87 'N', 'X', 'P', 'E' };
89 #define OPTION_OFFSET 256
91 #define OPT_NONE 0x00000U
92 #define OPT_NUMERIC 0x00001U
93 #define OPT_SOURCE 0x00002U
94 #define OPT_DESTINATION 0x00004U
95 #define OPT_PROTOCOL 0x00008U
96 #define OPT_JUMP 0x00010U
97 #define OPT_VERBOSE 0x00020U
98 #define OPT_EXPANDED 0x00040U
99 #define OPT_VIANAMEIN 0x00080U
100 #define OPT_VIANAMEOUT 0x00100U
101 #define OPT_LINENUMBERS 0x00200U
102 #define OPT_COUNTERS 0x00400U
103 #define NUMBER_OF_OPT 11
104 static const char optflags[NUMBER_OF_OPT]
105 = { 'n', 's', 'd', 'p', 'j', 'v', 'x', 'i', 'o', '0', 'c'};
107 static struct option original_opts[] = {
108 { "append", 1, 0, 'A' },
109 { "delete", 1, 0, 'D' },
110 { "insert", 1, 0, 'I' },
111 { "replace", 1, 0, 'R' },
112 { "list", 2, 0, 'L' },
113 { "flush", 2, 0, 'F' },
114 { "zero", 2, 0, 'Z' },
115 { "new-chain", 1, 0, 'N' },
116 { "delete-chain", 2, 0, 'X' },
117 { "rename-chain", 1, 0, 'E' },
118 { "policy", 1, 0, 'P' },
119 { "source", 1, 0, 's' },
120 { "destination", 1, 0, 'd' },
121 { "src", 1, 0, 's' }, /* synonym */
122 { "dst", 1, 0, 'd' }, /* synonym */
123 { "protocol", 1, 0, 'p' },
124 { "in-interface", 1, 0, 'i' },
125 { "jump", 1, 0, 'j' },
126 { "table", 1, 0, 't' },
127 { "match", 1, 0, 'm' },
128 { "numeric", 0, 0, 'n' },
129 { "out-interface", 1, 0, 'o' },
130 { "verbose", 0, 0, 'v' },
131 { "exact", 0, 0, 'x' },
132 { "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 ip6tables-restore. ip6tables-restore.c sets line to the
142 * current line of the input file, in order to give a more precise error
143 * message. ip6tables 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 --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'},
166 /*REPLACE*/ {'x',' ',' ',' ',' ',' ','x',' ',' ','x',' '},
167 /*APPEND*/ {'x',' ',' ',' ',' ',' ','x',' ',' ','x',' '},
168 /*LIST*/ {' ','x','x','x','x',' ',' ','x','x',' ','x'},
169 /*FLUSH*/ {'x','x','x','x','x',' ','x','x','x','x','x'},
170 /*ZERO*/ {'x','x','x','x','x',' ','x','x','x','x','x'},
171 /*NEW_CHAIN*/ {'x','x','x','x','x',' ','x','x','x','x','x'},
172 /*DEL_CHAIN*/ {'x','x','x','x','x',' ','x','x','x','x','x'},
173 /*SET_POLICY*/{'x','x','x','x','x',' ','x','x','x','x','x'},
174 /*RENAME*/ {'x','x','x','x','x',' ','x','x','x','x','x'}
177 static int inverse_for_options[NUMBER_OF_OPT] =
179 /* -n */ 0,
180 /* -s */ IP6T_INV_SRCIP,
181 /* -d */ IP6T_INV_DSTIP,
182 /* -p */ IP6T_INV_PROTO,
183 /* -j */ 0,
184 /* -v */ 0,
185 /* -x */ 0,
186 /* -i */ IP6T_INV_VIA_IN,
187 /* -o */ IP6T_INV_VIA_OUT,
188 /*--line*/ 0,
189 /* -c */ 0,
192 const char *program_version;
193 const char *program_name;
194 char *lib_dir;
196 /* the path to command to load kernel module */
197 const char *modprobe = NULL;
199 /* Keeping track of external matches and targets: linked lists. */
200 struct ip6tables_match *ip6tables_matches = NULL;
201 struct ip6tables_target *ip6tables_targets = NULL;
203 /* Extra debugging from libiptc */
204 extern void dump_entries6(const ip6tc_handle_t handle);
206 /* A few hardcoded protocols for 'all' and in case the user has no
207 /etc/protocols */
208 struct pprot {
209 char *name;
210 u_int8_t num;
213 /* Primitive headers... */
214 /* defined in netinet/in.h */
215 #if 0
216 #ifndef IPPROTO_ESP
217 #define IPPROTO_ESP 50
218 #endif
219 #ifndef IPPROTO_AH
220 #define IPPROTO_AH 51
221 #endif
222 #endif
223 #ifndef IPPROTO_MH
224 #define IPPROTO_MH 135
225 #endif
227 static const struct pprot chain_protos[] = {
228 { "tcp", IPPROTO_TCP },
229 { "udp", IPPROTO_UDP },
230 { "udplite", IPPROTO_UDPLITE },
231 { "icmpv6", IPPROTO_ICMPV6 },
232 { "ipv6-icmp", IPPROTO_ICMPV6 },
233 { "esp", IPPROTO_ESP },
234 { "ah", IPPROTO_AH },
235 { "ipv6-mh", IPPROTO_MH },
236 { "mh", IPPROTO_MH },
237 { "all", 0 },
240 static char *
241 proto_to_name(u_int8_t proto, int nolookup)
243 unsigned int i;
245 if (proto && !nolookup) {
246 struct protoent *pent = getprotobynumber(proto);
247 if (pent)
248 return pent->p_name;
251 for (i = 0; i < sizeof(chain_protos)/sizeof(struct pprot); i++)
252 if (chain_protos[i].num == proto)
253 return chain_protos[i].name;
255 return NULL;
259 service_to_port(const char *name, const char *proto)
261 struct servent *service;
263 if ((service = getservbyname(name, proto)) != NULL)
264 return ntohs((unsigned short) service->s_port);
266 return -1;
269 u_int16_t
270 parse_port(const char *port, const char *proto)
272 unsigned int portnum;
274 if ((string_to_number(port, 0, 65535, &portnum)) != -1 ||
275 (portnum = service_to_port(port, proto)) != -1)
276 return (u_int16_t)portnum;
278 exit_error(PARAMETER_PROBLEM,
279 "invalid port/service `%s' specified", port);
282 static void
283 in6addrcpy(struct in6_addr *dst, struct in6_addr *src)
285 memcpy(dst, src, sizeof(struct in6_addr));
286 /* dst->s6_addr = src->s6_addr; */
289 static void free_opts(int reset_offset)
291 if (opts != original_opts) {
292 free(opts);
293 opts = original_opts;
294 if (reset_offset)
295 global_option_offset = 0;
299 void
300 exit_error(enum exittype status, char *msg, ...)
302 va_list args;
304 va_start(args, msg);
305 fprintf(stderr, "%s v%s: ", program_name, program_version);
306 vfprintf(stderr, msg, args);
307 va_end(args);
308 fprintf(stderr, "\n");
309 if (status == PARAMETER_PROBLEM)
310 exit_tryhelp(status);
311 if (status == VERSION_PROBLEM)
312 fprintf(stderr,
313 "Perhaps ip6tables or your kernel needs to be upgraded.\n");
314 /* On error paths, make sure that we don't leak memory */
315 free_opts(1);
316 exit(status);
319 void
320 exit_tryhelp(int status)
322 if (line != -1)
323 fprintf(stderr, "Error occurred at line: %d\n", line);
324 fprintf(stderr, "Try `%s -h' or '%s --help' for more information.\n",
325 program_name, program_name );
326 free_opts(1);
327 exit(status);
330 void
331 exit_printhelp(struct ip6tables_rule_match *matches)
333 struct ip6tables_rule_match *matchp = NULL;
334 struct ip6tables_target *t = NULL;
336 printf("%s v%s\n\n"
337 "Usage: %s -[AD] chain rule-specification [options]\n"
338 " %s -[RI] chain rulenum rule-specification [options]\n"
339 " %s -D chain rulenum [options]\n"
340 " %s -[LFZ] [chain] [options]\n"
341 " %s -[NX] chain\n"
342 " %s -E old-chain-name new-chain-name\n"
343 " %s -P chain target [options]\n"
344 " %s -h (print this help information)\n\n",
345 program_name, program_version, program_name, program_name,
346 program_name, program_name, program_name, program_name,
347 program_name, program_name);
349 printf(
350 "Commands:\n"
351 "Either long or short options are allowed.\n"
352 " --append -A chain Append to chain\n"
353 " --delete -D chain Delete matching rule from chain\n"
354 " --delete -D chain rulenum\n"
355 " Delete rule rulenum (1 = first) from chain\n"
356 " --insert -I chain [rulenum]\n"
357 " Insert in chain as rulenum (default 1=first)\n"
358 " --replace -R chain rulenum\n"
359 " Replace rule rulenum (1 = first) in chain\n"
360 " --list -L [chain] List the rules in a chain or all chains\n"
361 " --flush -F [chain] Delete all rules in chain or all chains\n"
362 " --zero -Z [chain] Zero counters in chain or all chains\n"
363 " --new -N chain Create a new user-defined chain\n"
364 " --delete-chain\n"
365 " -X [chain] Delete a user-defined chain\n"
366 " --policy -P chain target\n"
367 " Change policy on chain to target\n"
368 " --rename-chain\n"
369 " -E old-chain new-chain\n"
370 " Change chain name, (moving any references)\n"
372 "Options:\n"
373 " --proto -p [!] proto protocol: by number or name, eg. `tcp'\n"
374 " --source -s [!] address[/mask]\n"
375 " source specification\n"
376 " --destination -d [!] address[/mask]\n"
377 " destination specification\n"
378 " --in-interface -i [!] input name[+]\n"
379 " network interface name ([+] for wildcard)\n"
380 " --jump -j target\n"
381 " target for rule (may load target extension)\n"
382 #ifdef IP6T_F_GOTO
383 " --goto -g chain\n"
384 " jump to chain with no return\n"
385 #endif
386 " --match -m match\n"
387 " extended match (may load extension)\n"
388 " --numeric -n numeric output of addresses and ports\n"
389 " --out-interface -o [!] output name[+]\n"
390 " network interface name ([+] for wildcard)\n"
391 " --table -t table table to manipulate (default: `filter')\n"
392 " --verbose -v verbose mode\n"
393 " --line-numbers print line numbers when listing\n"
394 " --exact -x expand numbers (display exact values)\n"
395 /*"[!] --fragment -f match second or further fragments only\n"*/
396 " --modprobe=<command> try to insert modules using this command\n"
397 " --set-counters PKTS BYTES set the counter during insert/append\n"
398 "[!] --version -V print package version.\n");
400 /* Print out any special helps. A user might like to be able to add a --help
401 to the commandline, and see expected results. So we call help for all
402 specified matches & targets */
403 for (t = ip6tables_targets; t; t = t->next) {
404 if (t->used) {
405 printf("\n");
406 t->help();
409 for (matchp = matches; matchp; matchp = matchp->next) {
410 printf("\n");
411 matchp->match->help();
413 exit(0);
416 static void
417 generic_opt_check(int command, int options)
419 int i, j, legal = 0;
421 /* Check that commands are valid with options. Complicated by the
422 * fact that if an option is legal with *any* command given, it is
423 * legal overall (ie. -z and -l).
425 for (i = 0; i < NUMBER_OF_OPT; i++) {
426 legal = 0; /* -1 => illegal, 1 => legal, 0 => undecided. */
428 for (j = 0; j < NUMBER_OF_CMD; j++) {
429 if (!(command & (1<<j)))
430 continue;
432 if (!(options & (1<<i))) {
433 if (commands_v_options[j][i] == '+')
434 exit_error(PARAMETER_PROBLEM,
435 "You need to supply the `-%c' "
436 "option for this command\n",
437 optflags[i]);
438 } else {
439 if (commands_v_options[j][i] != 'x')
440 legal = 1;
441 else if (legal == 0)
442 legal = -1;
445 if (legal == -1)
446 exit_error(PARAMETER_PROBLEM,
447 "Illegal option `-%c' with this command\n",
448 optflags[i]);
452 static char
453 opt2char(int option)
455 const char *ptr;
456 for (ptr = optflags; option > 1; option >>= 1, ptr++);
458 return *ptr;
461 static char
462 cmd2char(int option)
464 const char *ptr;
465 for (ptr = cmdflags; option > 1; option >>= 1, ptr++);
467 return *ptr;
470 static void
471 add_command(unsigned int *cmd, const int newcmd, const int othercmds,
472 int invert)
474 if (invert)
475 exit_error(PARAMETER_PROBLEM, "unexpected ! flag");
476 if (*cmd & (~othercmds))
477 exit_error(PARAMETER_PROBLEM, "Can't use -%c with -%c\n",
478 cmd2char(newcmd), cmd2char(*cmd & (~othercmds)));
479 *cmd |= newcmd;
483 check_inverse(const char option[], int *invert, int *optind, int argc)
485 if (option && strcmp(option, "!") == 0) {
486 if (*invert)
487 exit_error(PARAMETER_PROBLEM,
488 "Multiple `!' flags not allowed");
489 *invert = TRUE;
490 if (optind) {
491 *optind = *optind+1;
492 if (argc && *optind > argc)
493 exit_error(PARAMETER_PROBLEM,
494 "no argument following `!'");
497 return TRUE;
499 return FALSE;
502 static void *
503 fw_calloc(size_t count, size_t size)
505 void *p;
507 if ((p = calloc(count, size)) == NULL) {
508 perror("ip6tables: calloc failed");
509 exit(1);
511 return p;
514 static void *
515 fw_malloc(size_t size)
517 void *p;
519 if ((p = malloc(size)) == NULL) {
520 perror("ip6tables: malloc failed");
521 exit(1);
523 return p;
526 static char *
527 addr_to_numeric(const struct in6_addr *addrp)
529 /* 0000:0000:0000:0000:0000:000.000.000.000
530 * 0000:0000:0000:0000:0000:0000:0000:0000 */
531 static char buf[50+1];
532 return (char *)inet_ntop(AF_INET6, addrp, buf, sizeof(buf));
535 static struct in6_addr *
536 numeric_to_addr(const char *num)
538 static struct in6_addr ap;
539 int err;
540 if ((err=inet_pton(AF_INET6, num, &ap)) == 1)
541 return &ap;
542 #ifdef DEBUG
543 fprintf(stderr, "\nnumeric2addr: %d\n", err);
544 #endif
545 return (struct in6_addr *)NULL;
549 static struct in6_addr *
550 host_to_addr(const char *name, unsigned int *naddr)
552 struct addrinfo hints;
553 struct addrinfo *res;
554 struct addrinfo *p;
555 struct in6_addr *addr;
556 int err;
557 unsigned int i;
559 memset(&hints, 0, sizeof(hints));
560 hints.ai_flags=AI_CANONNAME;
561 hints.ai_family=AF_INET6;
562 hints.ai_socktype=SOCK_RAW;
564 *naddr = 0;
565 if ( (err=getaddrinfo(name, NULL, &hints, &res)) != 0 ){
566 #ifdef DEBUG
567 fprintf(stderr,"Name2IP: %s\n",gai_strerror(err));
568 #endif
569 return (struct in6_addr *) NULL;
570 } else {
571 /* Find length of address-chain */
572 for(p = res; p != NULL; p = p->ai_next)
573 (*naddr)++;
574 #ifdef DEBUG
575 fprintf(stderr, "resolved: len=%d %s ", res->ai_addrlen,
576 addr_to_numeric(&(((struct sockaddr_in6 *)res->ai_addr)->sin6_addr)));
577 #endif
578 addr = fw_calloc(*naddr, sizeof(struct in6_addr));
579 i = 0;
580 for(p = res; p != NULL; p = p->ai_next)
581 in6addrcpy(&(addr[i++]), (struct in6_addr *)
582 &((struct sockaddr_in6 *)p->ai_addr)->sin6_addr);
583 freeaddrinfo(res);
584 return addr;
587 return (struct in6_addr *) NULL;
590 static char *
591 addr_to_host(const struct in6_addr *addr)
593 struct sockaddr_in6 saddr;
594 int err;
595 static char hostname[NI_MAXHOST];
597 memset(&saddr, 0, sizeof(struct sockaddr_in6));
598 in6addrcpy(&(saddr.sin6_addr),(struct in6_addr *)addr);
599 saddr.sin6_family = AF_INET6;
601 if ( (err=getnameinfo((struct sockaddr *)&saddr,
602 sizeof(struct sockaddr_in6),
603 hostname, sizeof(hostname)-1,
604 NULL, 0, 0)) != 0 ){
605 #ifdef DEBUG
606 fprintf(stderr,"IP2Name: %s\n",gai_strerror(err));
607 #endif
608 return (char *) NULL;
609 } else {
610 #ifdef DEBUG
611 fprintf (stderr, "\naddr2host: %s\n", hostname);
612 #endif
614 return hostname;
617 return (char *) NULL;
620 static char *
621 mask_to_numeric(const struct in6_addr *addrp)
623 static char buf[50+2];
624 int l = ipv6_prefix_length(addrp);
625 if (l == -1) {
626 strcpy(buf, "/");
627 strcat(buf, addr_to_numeric(addrp));
628 return buf;
630 sprintf(buf, "/%d", l);
631 return buf;
634 static struct in6_addr *
635 network_to_addr(const char *name)
637 /* abort();*/
638 /* TODO: not implemented yet, but the exception breaks the
639 * name resolvation */
640 return (struct in6_addr *)NULL;
643 static char *
644 addr_to_anyname(const struct in6_addr *addr)
646 char *name;
648 if ((name = addr_to_host(addr)) != NULL)
649 return name;
651 return addr_to_numeric(addr);
655 * All functions starting with "parse" should succeed, otherwise
656 * the program fails.
657 * Most routines return pointers to static data that may change
658 * between calls to the same or other routines with a few exceptions:
659 * "host_to_addr", "parse_hostnetwork", and "parse_hostnetworkmask"
660 * return global static data.
663 static struct in6_addr *
664 parse_hostnetwork(const char *name, unsigned int *naddrs)
666 struct in6_addr *addrp, *addrptmp;
668 if ((addrptmp = numeric_to_addr(name)) != NULL ||
669 (addrptmp = network_to_addr(name)) != NULL) {
670 addrp = fw_malloc(sizeof(struct in6_addr));
671 in6addrcpy(addrp, addrptmp);
672 *naddrs = 1;
673 return addrp;
675 if ((addrp = host_to_addr(name, naddrs)) != NULL)
676 return addrp;
678 exit_error(PARAMETER_PROBLEM, "host/network `%s' not found", name);
681 static struct in6_addr *
682 parse_mask(char *mask)
684 static struct in6_addr maskaddr;
685 struct in6_addr *addrp;
686 unsigned int bits;
688 if (mask == NULL) {
689 /* no mask at all defaults to 128 bits */
690 memset(&maskaddr, 0xff, sizeof maskaddr);
691 return &maskaddr;
693 if ((addrp = numeric_to_addr(mask)) != NULL)
694 return addrp;
695 if (string_to_number(mask, 0, 128, &bits) == -1)
696 exit_error(PARAMETER_PROBLEM,
697 "invalid mask `%s' specified", mask);
698 if (bits != 0) {
699 char *p = (char *)&maskaddr;
700 memset(p, 0xff, bits / 8);
701 memset(p + (bits / 8) + 1, 0, (128 - bits) / 8);
702 p[bits / 8] = 0xff << (8 - (bits & 7));
703 return &maskaddr;
706 memset(&maskaddr, 0, sizeof maskaddr);
707 return &maskaddr;
710 void
711 parse_hostnetworkmask(const char *name, struct in6_addr **addrpp,
712 struct in6_addr *maskp, unsigned int *naddrs)
714 struct in6_addr *addrp;
715 char buf[256];
716 char *p;
717 int i, j, n;
719 strncpy(buf, name, sizeof(buf) - 1);
720 buf[sizeof(buf) - 1] = '\0';
721 if ((p = strrchr(buf, '/')) != NULL) {
722 *p = '\0';
723 addrp = parse_mask(p + 1);
724 } else
725 addrp = parse_mask(NULL);
726 in6addrcpy(maskp, addrp);
728 /* if a null mask is given, the name is ignored, like in "any/0" */
729 if (!memcmp(maskp, &in6addr_any, sizeof(in6addr_any)))
730 strcpy(buf, "::");
732 addrp = *addrpp = parse_hostnetwork(buf, naddrs);
733 n = *naddrs;
734 for (i = 0, j = 0; i < n; i++) {
735 int k;
736 for (k = 0; k < 4; k++)
737 addrp[j].in6_u.u6_addr32[k] &= maskp->in6_u.u6_addr32[k];
738 j++;
739 for (k = 0; k < j - 1; k++) {
740 if (IN6_ARE_ADDR_EQUAL(&addrp[k], &addrp[j - 1])) {
741 in6addrcpy( &addrp[--j], &addrp[--(*naddrs)] );
742 break;
748 struct ip6tables_match *
749 find_match(const char *match_name, enum ip6t_tryload tryload, struct ip6tables_rule_match **matches)
751 struct ip6tables_match *ptr;
752 const char *icmp6 = "icmp6";
753 const char *name;
755 /* This is ugly as hell. Nonetheless, there is no way of changing
756 * this without hurting backwards compatibility */
757 if ( (strcmp(match_name,"icmpv6") == 0) ||
758 (strcmp(match_name,"ipv6-icmp") == 0) ||
759 (strcmp(match_name,"icmp6") == 0) )
760 name = icmp6;
761 else
762 name = match_name;
764 for (ptr = ip6tables_matches; ptr; ptr = ptr->next) {
765 if (strcmp(name, ptr->name) == 0) {
766 struct ip6tables_match *clone;
768 /* First match of this type: */
769 if (ptr->m == NULL)
770 break;
772 /* Second and subsequent clones */
773 clone = fw_malloc(sizeof(struct ip6tables_match));
774 memcpy(clone, ptr, sizeof(struct ip6tables_match));
775 clone->mflags = 0;
776 /* This is a clone: */
777 clone->next = clone;
779 ptr = clone;
780 break;
784 #ifndef NO_SHARED_LIBS
785 if (!ptr && tryload != DONT_LOAD && tryload != DURING_LOAD) {
786 char path[strlen(lib_dir) + sizeof("/libip6t_.so")
787 + strlen(name)];
788 sprintf(path, "%s/libip6t_%s.so", lib_dir, name);
789 if (dlopen(path, RTLD_NOW)) {
790 /* Found library. If it didn't register itself,
791 maybe they specified target as match. */
792 ptr = find_match(name, DONT_LOAD, NULL);
794 if (!ptr)
795 exit_error(PARAMETER_PROBLEM,
796 "Couldn't load match `%s'\n",
797 name);
798 } else if (tryload == LOAD_MUST_SUCCEED)
799 exit_error(PARAMETER_PROBLEM,
800 "Couldn't load match `%s':%s\n",
801 name, dlerror());
803 #else
804 if (ptr && !ptr->loaded) {
805 if (tryload != DONT_LOAD)
806 ptr->loaded = 1;
807 else
808 ptr = NULL;
810 if(!ptr && (tryload == LOAD_MUST_SUCCEED)) {
811 exit_error(PARAMETER_PROBLEM,
812 "Couldn't find match `%s'\n", name);
814 #endif
816 if (ptr && matches) {
817 struct ip6tables_rule_match **i;
818 struct ip6tables_rule_match *newentry;
820 newentry = fw_malloc(sizeof(struct ip6tables_rule_match));
822 for (i = matches; *i; i = &(*i)->next) {
823 if (strcmp(name, (*i)->match->name) == 0)
824 (*i)->completed = 1;
826 newentry->match = ptr;
827 newentry->completed = 0;
828 newentry->next = NULL;
829 *i = newentry;
832 return ptr;
835 /* Christophe Burki wants `-p 6' to imply `-m tcp'. */
836 static struct ip6tables_match *
837 find_proto(const char *pname, enum ip6t_tryload tryload, int nolookup, struct ip6tables_rule_match **matches)
839 unsigned int proto;
841 if (string_to_number(pname, 0, 255, &proto) != -1) {
842 char *protoname = proto_to_name(proto, nolookup);
844 if (protoname)
845 return find_match(protoname, tryload, matches);
846 } else
847 return find_match(pname, tryload, matches);
849 return NULL;
852 u_int16_t
853 parse_protocol(const char *s)
855 unsigned int proto;
857 if (string_to_number(s, 0, 255, &proto) == -1) {
858 struct protoent *pent;
860 /* first deal with the special case of 'all' to prevent
861 * people from being able to redefine 'all' in nsswitch
862 * and/or provoke expensive [not working] ldap/nis/...
863 * lookups */
864 if (!strcmp(s, "all"))
865 return 0;
867 if ((pent = getprotobyname(s)))
868 proto = pent->p_proto;
869 else {
870 unsigned int i;
871 for (i = 0;
872 i < sizeof(chain_protos)/sizeof(struct pprot);
873 i++) {
874 if (strcmp(s, chain_protos[i].name) == 0) {
875 proto = chain_protos[i].num;
876 break;
879 if (i == sizeof(chain_protos)/sizeof(struct pprot))
880 exit_error(PARAMETER_PROBLEM,
881 "unknown protocol `%s' specified",
886 return (u_int16_t)proto;
889 /* These are invalid numbers as upper layer protocol */
890 static int is_exthdr(u_int16_t proto)
892 return (proto == IPPROTO_ROUTING ||
893 proto == IPPROTO_FRAGMENT ||
894 proto == IPPROTO_AH ||
895 proto == IPPROTO_DSTOPTS);
898 void parse_interface(const char *arg, char *vianame, unsigned char *mask)
900 int vialen = strlen(arg);
901 unsigned int i;
903 memset(mask, 0, IFNAMSIZ);
904 memset(vianame, 0, IFNAMSIZ);
906 if (vialen + 1 > IFNAMSIZ)
907 exit_error(PARAMETER_PROBLEM,
908 "interface name `%s' must be shorter than IFNAMSIZ"
909 " (%i)", arg, IFNAMSIZ-1);
911 strcpy(vianame, arg);
912 if ((vialen == 0) || (vialen == 1 && vianame[0] == '+'))
913 memset(mask, 0, IFNAMSIZ);
914 else if (vianame[vialen - 1] == '+') {
915 memset(mask, 0xFF, vialen - 1);
916 memset(mask + vialen - 1, 0, IFNAMSIZ - vialen + 1);
917 /* Don't remove `+' here! -HW */
918 } else {
919 /* Include nul-terminator in match */
920 memset(mask, 0xFF, vialen + 1);
921 memset(mask + vialen + 1, 0, IFNAMSIZ - vialen - 1);
922 for (i = 0; vianame[i]; i++) {
923 if (vianame[i] == ':' ||
924 vianame[i] == '!' ||
925 vianame[i] == '*') {
926 printf("Warning: weird character in interface"
927 " `%s' (No aliases, :, ! or *).\n",
928 vianame);
929 break;
935 /* Can't be zero. */
936 static int
937 parse_rulenumber(const char *rule)
939 unsigned int rulenum;
941 if (string_to_number(rule, 1, INT_MAX, &rulenum) == -1)
942 exit_error(PARAMETER_PROBLEM,
943 "Invalid rule number `%s'", rule);
945 return rulenum;
948 static const char *
949 parse_target(const char *targetname)
951 const char *ptr;
953 if (strlen(targetname) < 1)
954 exit_error(PARAMETER_PROBLEM,
955 "Invalid target name (too short)");
957 if (strlen(targetname)+1 > sizeof(ip6t_chainlabel))
958 exit_error(PARAMETER_PROBLEM,
959 "Invalid target name `%s' (%u chars max)",
960 targetname, (unsigned int)sizeof(ip6t_chainlabel)-1);
962 for (ptr = targetname; *ptr; ptr++)
963 if (isspace(*ptr))
964 exit_error(PARAMETER_PROBLEM,
965 "Invalid target name `%s'", targetname);
966 return targetname;
970 string_to_number_ll(const char *s, unsigned long long min, unsigned long long max,
971 unsigned long long *ret)
973 unsigned long long number;
974 char *end;
976 /* Handle hex, octal, etc. */
977 errno = 0;
978 number = strtoull(s, &end, 0);
979 if (*end == '\0' && end != s) {
980 /* we parsed a number, let's see if we want this */
981 if (errno != ERANGE && min <= number && (!max || number <= max)) {
982 *ret = number;
983 return 0;
986 return -1;
990 string_to_number_l(const char *s, unsigned long min, unsigned long max,
991 unsigned long *ret)
993 int result;
994 unsigned long long number;
996 result = string_to_number_ll(s, min, max, &number);
997 *ret = (unsigned long)number;
999 return result;
1002 int string_to_number(const char *s, unsigned int min, unsigned int max,
1003 unsigned int *ret)
1005 int result;
1006 unsigned long number;
1008 result = string_to_number_l(s, min, max, &number);
1009 *ret = (unsigned int)number;
1011 return result;
1014 static void
1015 set_option(unsigned int *options, unsigned int option, u_int8_t *invflg,
1016 int invert)
1018 if (*options & option)
1019 exit_error(PARAMETER_PROBLEM, "multiple -%c flags not allowed",
1020 opt2char(option));
1021 *options |= option;
1023 if (invert) {
1024 unsigned int i;
1025 for (i = 0; 1 << i != option; i++);
1027 if (!inverse_for_options[i])
1028 exit_error(PARAMETER_PROBLEM,
1029 "cannot have ! before -%c",
1030 opt2char(option));
1031 *invflg |= inverse_for_options[i];
1035 struct ip6tables_target *
1036 find_target(const char *name, enum ip6t_tryload tryload)
1038 struct ip6tables_target *ptr;
1040 /* Standard target? */
1041 if (strcmp(name, "") == 0
1042 || strcmp(name, IP6TC_LABEL_ACCEPT) == 0
1043 || strcmp(name, IP6TC_LABEL_DROP) == 0
1044 || strcmp(name, IP6TC_LABEL_QUEUE) == 0
1045 || strcmp(name, IP6TC_LABEL_RETURN) == 0)
1046 name = "standard";
1048 for (ptr = ip6tables_targets; ptr; ptr = ptr->next) {
1049 if (strcmp(name, ptr->name) == 0)
1050 break;
1053 #ifndef NO_SHARED_LIBS
1054 if (!ptr && tryload != DONT_LOAD && tryload != DURING_LOAD) {
1055 char path[strlen(lib_dir) + sizeof("/libip6t_.so")
1056 + strlen(name)];
1057 sprintf(path, "%s/libip6t_%s.so", lib_dir, name);
1058 if (dlopen(path, RTLD_NOW)) {
1059 /* Found library. If it didn't register itself,
1060 maybe they specified match as a target. */
1061 ptr = find_target(name, DONT_LOAD);
1062 if (!ptr)
1063 exit_error(PARAMETER_PROBLEM,
1064 "Couldn't load target `%s'\n",
1065 name);
1066 } else if (tryload == LOAD_MUST_SUCCEED)
1067 exit_error(PARAMETER_PROBLEM,
1068 "Couldn't load target `%s':%s\n",
1069 name, dlerror());
1071 #else
1072 if (ptr && !ptr->loaded) {
1073 if (tryload != DONT_LOAD)
1074 ptr->loaded = 1;
1075 else
1076 ptr = NULL;
1078 if(!ptr && (tryload == LOAD_MUST_SUCCEED)) {
1079 exit_error(PARAMETER_PROBLEM,
1080 "Couldn't find target `%s'\n", name);
1082 #endif
1084 if (ptr)
1085 ptr->used = 1;
1087 return ptr;
1090 static struct option *
1091 merge_options(struct option *oldopts, const struct option *newopts,
1092 unsigned int *option_offset)
1094 unsigned int num_old, num_new, i;
1095 struct option *merge;
1097 for (num_old = 0; oldopts[num_old].name; num_old++);
1098 for (num_new = 0; newopts[num_new].name; num_new++);
1100 global_option_offset += OPTION_OFFSET;
1101 *option_offset = global_option_offset;
1103 merge = malloc(sizeof(struct option) * (num_new + num_old + 1));
1104 memcpy(merge, oldopts, num_old * sizeof(struct option));
1105 free_opts(0); /* Release previous options merged if any */
1106 for (i = 0; i < num_new; i++) {
1107 merge[num_old + i] = newopts[i];
1108 merge[num_old + i].val += *option_offset;
1110 memset(merge + num_old + num_new, 0, sizeof(struct option));
1112 return merge;
1115 static int compatible_revision(const char *name, u_int8_t revision, int opt)
1117 struct ip6t_get_revision rev;
1118 socklen_t s = sizeof(rev);
1119 int max_rev, sockfd;
1121 sockfd = socket(AF_INET6, SOCK_RAW, IPPROTO_RAW);
1122 if (sockfd < 0) {
1123 fprintf(stderr, "Could not open socket to kernel: %s\n",
1124 strerror(errno));
1125 exit(1);
1128 strcpy(rev.name, name);
1129 rev.revision = revision;
1131 load_ip6tables_ko(modprobe, 1);
1133 max_rev = getsockopt(sockfd, IPPROTO_IPV6, opt, &rev, &s);
1134 if (max_rev < 0) {
1135 /* Definitely don't support this? */
1136 if (errno == ENOENT || errno == EPROTONOSUPPORT) {
1137 close(sockfd);
1138 return 0;
1139 } else if (errno == ENOPROTOOPT) {
1140 close(sockfd);
1141 /* Assume only revision 0 support (old kernel) */
1142 return (revision == 0);
1143 } else {
1144 fprintf(stderr, "getsockopt failed strangely: %s\n",
1145 strerror(errno));
1146 exit(1);
1149 close(sockfd);
1150 return 1;
1153 static int compatible_match_revision(const char *name, u_int8_t revision)
1155 return compatible_revision(name, revision, IP6T_SO_GET_REVISION_MATCH);
1158 void
1159 register_match6(struct ip6tables_match *me)
1161 struct ip6tables_match **i, *old;
1163 if (strcmp(me->version, program_version) != 0) {
1164 fprintf(stderr, "%s: match `%s' v%s (I'm v%s).\n",
1165 program_name, me->name, me->version, program_version);
1166 exit(1);
1169 /* Revision field stole a char from name. */
1170 if (strlen(me->name) >= IP6T_FUNCTION_MAXNAMELEN-1) {
1171 fprintf(stderr, "%s: target `%s' has invalid name\n",
1172 program_name, me->name);
1173 exit(1);
1176 old = find_match(me->name, DURING_LOAD, NULL);
1177 if (old) {
1178 if (old->revision == me->revision) {
1179 fprintf(stderr,
1180 "%s: match `%s' already registered.\n",
1181 program_name, me->name);
1182 exit(1);
1185 /* Now we have two (or more) options, check compatibility. */
1186 if (compatible_match_revision(old->name, old->revision)
1187 && old->revision > me->revision)
1188 return;
1190 /* Replace if compatible. */
1191 if (!compatible_match_revision(me->name, me->revision))
1192 return;
1194 /* Delete old one. */
1195 for (i = &ip6tables_matches; *i!=old; i = &(*i)->next);
1196 *i = old->next;
1199 if (me->size != IP6T_ALIGN(me->size)) {
1200 fprintf(stderr, "%s: match `%s' has invalid size %u.\n",
1201 program_name, me->name, (unsigned int)me->size);
1202 exit(1);
1205 /* Append to list. */
1206 for (i = &ip6tables_matches; *i; i = &(*i)->next);
1207 me->next = NULL;
1208 *i = me;
1210 me->m = NULL;
1211 me->mflags = 0;
1214 void
1215 register_target6(struct ip6tables_target *me)
1217 if (strcmp(me->version, program_version) != 0) {
1218 fprintf(stderr, "%s: target `%s' v%s (I'm v%s).\n",
1219 program_name, me->name, me->version, program_version);
1220 exit(1);
1223 if (find_target(me->name, DURING_LOAD)) {
1224 fprintf(stderr, "%s: target `%s' already registered.\n",
1225 program_name, me->name);
1226 exit(1);
1229 if (me->size != IP6T_ALIGN(me->size)) {
1230 fprintf(stderr, "%s: target `%s' has invalid size %u.\n",
1231 program_name, me->name, (unsigned int)me->size);
1232 exit(1);
1235 /* Prepend to list. */
1236 me->next = ip6tables_targets;
1237 ip6tables_targets = me;
1238 me->t = NULL;
1239 me->tflags = 0;
1242 static void
1243 print_num(u_int64_t number, unsigned int format)
1245 if (format & FMT_KILOMEGAGIGA) {
1246 if (number > 99999) {
1247 number = (number + 500) / 1000;
1248 if (number > 9999) {
1249 number = (number + 500) / 1000;
1250 if (number > 9999) {
1251 number = (number + 500) / 1000;
1252 if (number > 9999) {
1253 number = (number + 500) / 1000;
1254 printf(FMT("%4lluT ","%lluT "), (unsigned long long)number);
1256 else printf(FMT("%4lluG ","%lluG "), (unsigned long long)number);
1258 else printf(FMT("%4lluM ","%lluM "), (unsigned long long)number);
1259 } else
1260 printf(FMT("%4lluK ","%lluK "), (unsigned long long)number);
1261 } else
1262 printf(FMT("%5llu ","%llu "), (unsigned long long)number);
1263 } else
1264 printf(FMT("%8llu ","%llu "), (unsigned long long)number);
1268 static void
1269 print_header(unsigned int format, const char *chain, ip6tc_handle_t *handle)
1271 struct ip6t_counters counters;
1272 const char *pol = ip6tc_get_policy(chain, &counters, handle);
1273 printf("Chain %s", chain);
1274 if (pol) {
1275 printf(" (policy %s", pol);
1276 if (!(format & FMT_NOCOUNTS)) {
1277 fputc(' ', stdout);
1278 print_num(counters.pcnt, (format|FMT_NOTABLE));
1279 fputs("packets, ", stdout);
1280 print_num(counters.bcnt, (format|FMT_NOTABLE));
1281 fputs("bytes", stdout);
1283 printf(")\n");
1284 } else {
1285 unsigned int refs;
1286 if (!ip6tc_get_references(&refs, chain, handle))
1287 printf(" (ERROR obtaining refs)\n");
1288 else
1289 printf(" (%u references)\n", refs);
1292 if (format & FMT_LINENUMBERS)
1293 printf(FMT("%-4s ", "%s "), "num");
1294 if (!(format & FMT_NOCOUNTS)) {
1295 if (format & FMT_KILOMEGAGIGA) {
1296 printf(FMT("%5s ","%s "), "pkts");
1297 printf(FMT("%5s ","%s "), "bytes");
1298 } else {
1299 printf(FMT("%8s ","%s "), "pkts");
1300 printf(FMT("%10s ","%s "), "bytes");
1303 if (!(format & FMT_NOTARGET))
1304 printf(FMT("%-9s ","%s "), "target");
1305 fputs(" prot ", stdout);
1306 if (format & FMT_OPTIONS)
1307 fputs("opt", stdout);
1308 if (format & FMT_VIA) {
1309 printf(FMT(" %-6s ","%s "), "in");
1310 printf(FMT("%-6s ","%s "), "out");
1312 printf(FMT(" %-19s ","%s "), "source");
1313 printf(FMT(" %-19s "," %s "), "destination");
1314 printf("\n");
1318 static int
1319 print_match(const struct ip6t_entry_match *m,
1320 const struct ip6t_ip6 *ip,
1321 int numeric)
1323 struct ip6tables_match *match = find_match(m->u.user.name, TRY_LOAD, NULL);
1325 if (match) {
1326 if (match->print)
1327 match->print(ip, m, numeric);
1328 else
1329 printf("%s ", match->name);
1330 } else {
1331 if (m->u.user.name[0])
1332 printf("UNKNOWN match `%s' ", m->u.user.name);
1334 /* Don't stop iterating. */
1335 return 0;
1338 /* e is called `fw' here for hysterical raisins */
1339 static void
1340 print_firewall(const struct ip6t_entry *fw,
1341 const char *targname,
1342 unsigned int num,
1343 unsigned int format,
1344 const ip6tc_handle_t handle)
1346 struct ip6tables_target *target = NULL;
1347 const struct ip6t_entry_target *t;
1348 u_int8_t flags;
1349 char buf[BUFSIZ];
1351 if (!ip6tc_is_chain(targname, handle))
1352 target = find_target(targname, TRY_LOAD);
1353 else
1354 target = find_target(IP6T_STANDARD_TARGET, LOAD_MUST_SUCCEED);
1356 t = ip6t_get_target((struct ip6t_entry *)fw);
1357 flags = fw->ipv6.flags;
1359 if (format & FMT_LINENUMBERS)
1360 printf(FMT("%-4u ", "%u "), num+1);
1362 if (!(format & FMT_NOCOUNTS)) {
1363 print_num(fw->counters.pcnt, format);
1364 print_num(fw->counters.bcnt, format);
1367 if (!(format & FMT_NOTARGET))
1368 printf(FMT("%-9s ", "%s "), targname);
1370 fputc(fw->ipv6.invflags & IP6T_INV_PROTO ? '!' : ' ', stdout);
1372 char *pname = proto_to_name(fw->ipv6.proto, format&FMT_NUMERIC);
1373 if (pname)
1374 printf(FMT("%-5s", "%s "), pname);
1375 else
1376 printf(FMT("%-5hu", "%hu "), fw->ipv6.proto);
1379 if (format & FMT_OPTIONS) {
1380 if (format & FMT_NOTABLE)
1381 fputs("opt ", stdout);
1382 fputc(' ', stdout); /* Invert flag of FRAG */
1383 fputc(' ', stdout); /* -f */
1384 fputc(' ', stdout);
1387 if (format & FMT_VIA) {
1388 char iface[IFNAMSIZ+2];
1390 if (fw->ipv6.invflags & IP6T_INV_VIA_IN) {
1391 iface[0] = '!';
1392 iface[1] = '\0';
1394 else iface[0] = '\0';
1396 if (fw->ipv6.iniface[0] != '\0') {
1397 strcat(iface, fw->ipv6.iniface);
1399 else if (format & FMT_NUMERIC) strcat(iface, "*");
1400 else strcat(iface, "any");
1401 printf(FMT(" %-6s ","in %s "), iface);
1403 if (fw->ipv6.invflags & IP6T_INV_VIA_OUT) {
1404 iface[0] = '!';
1405 iface[1] = '\0';
1407 else iface[0] = '\0';
1409 if (fw->ipv6.outiface[0] != '\0') {
1410 strcat(iface, fw->ipv6.outiface);
1412 else if (format & FMT_NUMERIC) strcat(iface, "*");
1413 else strcat(iface, "any");
1414 printf(FMT("%-6s ","out %s "), iface);
1417 fputc(fw->ipv6.invflags & IP6T_INV_SRCIP ? '!' : ' ', stdout);
1418 if (!memcmp(&fw->ipv6.smsk, &in6addr_any, sizeof in6addr_any)
1419 && !(format & FMT_NUMERIC))
1420 printf(FMT("%-19s ","%s "), "anywhere");
1421 else {
1422 if (format & FMT_NUMERIC)
1423 sprintf(buf, "%s", addr_to_numeric(&(fw->ipv6.src)));
1424 else
1425 sprintf(buf, "%s", addr_to_anyname(&(fw->ipv6.src)));
1426 strcat(buf, mask_to_numeric(&(fw->ipv6.smsk)));
1427 printf(FMT("%-19s ","%s "), buf);
1430 fputc(fw->ipv6.invflags & IP6T_INV_DSTIP ? '!' : ' ', stdout);
1431 if (!memcmp(&fw->ipv6.dmsk, &in6addr_any, sizeof in6addr_any)
1432 && !(format & FMT_NUMERIC))
1433 printf(FMT("%-19s","-> %s"), "anywhere");
1434 else {
1435 if (format & FMT_NUMERIC)
1436 sprintf(buf, "%s", addr_to_numeric(&(fw->ipv6.dst)));
1437 else
1438 sprintf(buf, "%s", addr_to_anyname(&(fw->ipv6.dst)));
1439 strcat(buf, mask_to_numeric(&(fw->ipv6.dmsk)));
1440 printf(FMT("%-19s","-> %s"), buf);
1443 if (format & FMT_NOTABLE)
1444 fputs(" ", stdout);
1446 #ifdef IP6T_F_GOTO
1447 if(fw->ipv6.flags & IP6T_F_GOTO)
1448 printf("[goto] ");
1449 #endif
1451 IP6T_MATCH_ITERATE(fw, print_match, &fw->ipv6, format & FMT_NUMERIC);
1453 if (target) {
1454 if (target->print)
1455 /* Print the target information. */
1456 target->print(&fw->ipv6, t, format & FMT_NUMERIC);
1457 } else if (t->u.target_size != sizeof(*t))
1458 printf("[%u bytes of unknown target data] ",
1459 (unsigned int)(t->u.target_size - sizeof(*t)));
1461 if (!(format & FMT_NONEWLINE))
1462 fputc('\n', stdout);
1465 static void
1466 print_firewall_line(const struct ip6t_entry *fw,
1467 const ip6tc_handle_t h)
1469 struct ip6t_entry_target *t;
1471 t = ip6t_get_target((struct ip6t_entry *)fw);
1472 print_firewall(fw, t->u.user.name, 0, FMT_PRINT_RULE, h);
1475 static int
1476 append_entry(const ip6t_chainlabel chain,
1477 struct ip6t_entry *fw,
1478 unsigned int nsaddrs,
1479 const struct in6_addr saddrs[],
1480 unsigned int ndaddrs,
1481 const struct in6_addr daddrs[],
1482 int verbose,
1483 ip6tc_handle_t *handle)
1485 unsigned int i, j;
1486 int ret = 1;
1488 for (i = 0; i < nsaddrs; i++) {
1489 fw->ipv6.src = saddrs[i];
1490 for (j = 0; j < ndaddrs; j++) {
1491 fw->ipv6.dst = daddrs[j];
1492 if (verbose)
1493 print_firewall_line(fw, *handle);
1494 ret &= ip6tc_append_entry(chain, fw, handle);
1498 return ret;
1501 static int
1502 replace_entry(const ip6t_chainlabel chain,
1503 struct ip6t_entry *fw,
1504 unsigned int rulenum,
1505 const struct in6_addr *saddr,
1506 const struct in6_addr *daddr,
1507 int verbose,
1508 ip6tc_handle_t *handle)
1510 fw->ipv6.src = *saddr;
1511 fw->ipv6.dst = *daddr;
1513 if (verbose)
1514 print_firewall_line(fw, *handle);
1515 return ip6tc_replace_entry(chain, fw, rulenum, handle);
1518 static int
1519 insert_entry(const ip6t_chainlabel chain,
1520 struct ip6t_entry *fw,
1521 unsigned int rulenum,
1522 unsigned int nsaddrs,
1523 const struct in6_addr saddrs[],
1524 unsigned int ndaddrs,
1525 const struct in6_addr daddrs[],
1526 int verbose,
1527 ip6tc_handle_t *handle)
1529 unsigned int i, j;
1530 int ret = 1;
1532 for (i = 0; i < nsaddrs; i++) {
1533 fw->ipv6.src = saddrs[i];
1534 for (j = 0; j < ndaddrs; j++) {
1535 fw->ipv6.dst = daddrs[j];
1536 if (verbose)
1537 print_firewall_line(fw, *handle);
1538 ret &= ip6tc_insert_entry(chain, fw, rulenum, handle);
1542 return ret;
1545 static unsigned char *
1546 make_delete_mask(struct ip6t_entry *fw, struct ip6tables_rule_match *matches)
1548 /* Establish mask for comparison */
1549 unsigned int size;
1550 struct ip6tables_rule_match *matchp;
1551 unsigned char *mask, *mptr;
1553 size = sizeof(struct ip6t_entry);
1554 for (matchp = matches; matchp; matchp = matchp->next)
1555 size += IP6T_ALIGN(sizeof(struct ip6t_entry_match)) + matchp->match->size;
1557 mask = fw_calloc(1, size
1558 + IP6T_ALIGN(sizeof(struct ip6t_entry_target))
1559 + ip6tables_targets->size);
1561 memset(mask, 0xFF, sizeof(struct ip6t_entry));
1562 mptr = mask + sizeof(struct ip6t_entry);
1564 for (matchp = matches; matchp; matchp = matchp->next) {
1565 memset(mptr, 0xFF,
1566 IP6T_ALIGN(sizeof(struct ip6t_entry_match))
1567 + matchp->match->userspacesize);
1568 mptr += IP6T_ALIGN(sizeof(struct ip6t_entry_match)) + matchp->match->size;
1571 memset(mptr, 0xFF,
1572 IP6T_ALIGN(sizeof(struct ip6t_entry_target))
1573 + ip6tables_targets->userspacesize);
1575 return mask;
1578 static int
1579 delete_entry(const ip6t_chainlabel chain,
1580 struct ip6t_entry *fw,
1581 unsigned int nsaddrs,
1582 const struct in6_addr saddrs[],
1583 unsigned int ndaddrs,
1584 const struct in6_addr daddrs[],
1585 int verbose,
1586 ip6tc_handle_t *handle,
1587 struct ip6tables_rule_match *matches)
1589 unsigned int i, j;
1590 int ret = 1;
1591 unsigned char *mask;
1593 mask = make_delete_mask(fw, matches);
1594 for (i = 0; i < nsaddrs; i++) {
1595 fw->ipv6.src = saddrs[i];
1596 for (j = 0; j < ndaddrs; j++) {
1597 fw->ipv6.dst = daddrs[j];
1598 if (verbose)
1599 print_firewall_line(fw, *handle);
1600 ret &= ip6tc_delete_entry(chain, fw, mask, handle);
1603 free(mask);
1605 return ret;
1609 for_each_chain(int (*fn)(const ip6t_chainlabel, int, ip6tc_handle_t *),
1610 int verbose, int builtinstoo, ip6tc_handle_t *handle)
1612 int ret = 1;
1613 const char *chain;
1614 char *chains;
1615 unsigned int i, chaincount = 0;
1617 chain = ip6tc_first_chain(handle);
1618 while (chain) {
1619 chaincount++;
1620 chain = ip6tc_next_chain(handle);
1623 chains = fw_malloc(sizeof(ip6t_chainlabel) * chaincount);
1624 i = 0;
1625 chain = ip6tc_first_chain(handle);
1626 while (chain) {
1627 strcpy(chains + i*sizeof(ip6t_chainlabel), chain);
1628 i++;
1629 chain = ip6tc_next_chain(handle);
1632 for (i = 0; i < chaincount; i++) {
1633 if (!builtinstoo
1634 && ip6tc_builtin(chains + i*sizeof(ip6t_chainlabel),
1635 *handle) == 1)
1636 continue;
1637 ret &= fn(chains + i*sizeof(ip6t_chainlabel), verbose, handle);
1640 free(chains);
1641 return ret;
1645 flush_entries(const ip6t_chainlabel chain, int verbose,
1646 ip6tc_handle_t *handle)
1648 if (!chain)
1649 return for_each_chain(flush_entries, verbose, 1, handle);
1651 if (verbose)
1652 fprintf(stdout, "Flushing chain `%s'\n", chain);
1653 return ip6tc_flush_entries(chain, handle);
1656 static int
1657 zero_entries(const ip6t_chainlabel chain, int verbose,
1658 ip6tc_handle_t *handle)
1660 if (!chain)
1661 return for_each_chain(zero_entries, verbose, 1, handle);
1663 if (verbose)
1664 fprintf(stdout, "Zeroing chain `%s'\n", chain);
1665 return ip6tc_zero_entries(chain, handle);
1669 delete_chain(const ip6t_chainlabel chain, int verbose,
1670 ip6tc_handle_t *handle)
1672 if (!chain)
1673 return for_each_chain(delete_chain, verbose, 0, handle);
1675 if (verbose)
1676 fprintf(stdout, "Deleting chain `%s'\n", chain);
1677 return ip6tc_delete_chain(chain, handle);
1680 static int
1681 list_entries(const ip6t_chainlabel chain, int verbose, int numeric,
1682 int expanded, int linenumbers, ip6tc_handle_t *handle)
1684 int found = 0;
1685 unsigned int format;
1686 const char *this;
1688 format = FMT_OPTIONS;
1689 if (!verbose)
1690 format |= FMT_NOCOUNTS;
1691 else
1692 format |= FMT_VIA;
1694 if (numeric)
1695 format |= FMT_NUMERIC;
1697 if (!expanded)
1698 format |= FMT_KILOMEGAGIGA;
1700 if (linenumbers)
1701 format |= FMT_LINENUMBERS;
1703 for (this = ip6tc_first_chain(handle);
1704 this;
1705 this = ip6tc_next_chain(handle)) {
1706 const struct ip6t_entry *i;
1707 unsigned int num;
1709 if (chain && strcmp(chain, this) != 0)
1710 continue;
1712 if (found) printf("\n");
1714 print_header(format, this, handle);
1715 i = ip6tc_first_rule(this, handle);
1717 num = 0;
1718 while (i) {
1719 print_firewall(i,
1720 ip6tc_get_target(i, handle),
1721 num++,
1722 format,
1723 *handle);
1724 i = ip6tc_next_rule(i, handle);
1726 found = 1;
1729 errno = ENOENT;
1730 return found;
1733 static char *get_modprobe(void)
1735 int procfile;
1736 char *ret;
1738 #define PROCFILE_BUFSIZ 1024
1739 procfile = open(PROC_SYS_MODPROBE, O_RDONLY);
1740 if (procfile < 0)
1741 return NULL;
1743 ret = malloc(PROCFILE_BUFSIZ);
1744 if (ret) {
1745 memset(ret, 0, PROCFILE_BUFSIZ);
1746 switch (read(procfile, ret, PROCFILE_BUFSIZ)) {
1747 case -1: goto fail;
1748 case PROCFILE_BUFSIZ: goto fail; /* Partial read. Wierd */
1750 if (ret[strlen(ret)-1]=='\n')
1751 ret[strlen(ret)-1]=0;
1752 close(procfile);
1753 return ret;
1755 fail:
1756 free(ret);
1757 close(procfile);
1758 return NULL;
1761 int ip6tables_insmod(const char *modname, const char *modprobe, int quiet)
1763 char *buf = NULL;
1764 char *argv[4];
1765 int status;
1767 /* If they don't explicitly set it, read out of kernel */
1768 if (!modprobe) {
1769 buf = get_modprobe();
1770 if (!buf)
1771 return -1;
1772 modprobe = buf;
1775 switch (fork()) {
1776 case 0:
1777 argv[0] = (char *)modprobe;
1778 argv[1] = (char *)modname;
1779 if (quiet) {
1780 argv[2] = "-q";
1781 argv[3] = NULL;
1782 } else {
1783 argv[2] = NULL;
1784 argv[3] = NULL;
1786 execv(argv[0], argv);
1788 /* not usually reached */
1789 exit(1);
1790 case -1:
1791 return -1;
1793 default: /* parent */
1794 wait(&status);
1797 free(buf);
1798 if (WIFEXITED(status) && WEXITSTATUS(status) == 0)
1799 return 0;
1800 return -1;
1803 int load_ip6tables_ko(const char *modprobe, int quiet)
1805 static int loaded = 0;
1806 static int ret = -1;
1808 if (!loaded) {
1809 ret = ip6tables_insmod("ip6_tables", modprobe, quiet);
1810 loaded = (ret == 0);
1813 return ret;
1816 static struct ip6t_entry *
1817 generate_entry(const struct ip6t_entry *fw,
1818 struct ip6tables_rule_match *matches,
1819 struct ip6t_entry_target *target)
1821 unsigned int size;
1822 struct ip6tables_rule_match *matchp;
1823 struct ip6t_entry *e;
1825 size = sizeof(struct ip6t_entry);
1826 for (matchp = matches; matchp; matchp = matchp->next)
1827 size += matchp->match->m->u.match_size;
1829 e = fw_malloc(size + target->u.target_size);
1830 *e = *fw;
1831 e->target_offset = size;
1832 e->next_offset = size + target->u.target_size;
1834 size = 0;
1835 for (matchp = matches; matchp; matchp = matchp->next) {
1836 memcpy(e->elems + size, matchp->match->m, matchp->match->m->u.match_size);
1837 size += matchp->match->m->u.match_size;
1839 memcpy(e->elems + size, target, target->u.target_size);
1841 return e;
1844 void clear_rule_matches(struct ip6tables_rule_match **matches)
1846 struct ip6tables_rule_match *matchp, *tmp;
1848 for (matchp = *matches; matchp;) {
1849 tmp = matchp->next;
1850 if (matchp->match->m) {
1851 free(matchp->match->m);
1852 matchp->match->m = NULL;
1854 if (matchp->match == matchp->match->next) {
1855 free(matchp->match);
1856 matchp->match = NULL;
1858 free(matchp);
1859 matchp = tmp;
1862 *matches = NULL;
1865 static void set_revision(char *name, u_int8_t revision)
1867 /* Old kernel sources don't have ".revision" field,
1868 but we stole a byte from name. */
1869 name[IP6T_FUNCTION_MAXNAMELEN - 2] = '\0';
1870 name[IP6T_FUNCTION_MAXNAMELEN - 1] = revision;
1873 int do_command6(int argc, char *argv[], char **table, ip6tc_handle_t *handle)
1875 struct ip6t_entry fw, *e = NULL;
1876 int invert = 0;
1877 unsigned int nsaddrs = 0, ndaddrs = 0;
1878 struct in6_addr *saddrs = NULL, *daddrs = NULL;
1880 int c, verbose = 0;
1881 const char *chain = NULL;
1882 const char *shostnetworkmask = NULL, *dhostnetworkmask = NULL;
1883 const char *policy = NULL, *newname = NULL;
1884 unsigned int rulenum = 0, options = 0, command = 0;
1885 const char *pcnt = NULL, *bcnt = NULL;
1886 int ret = 1;
1887 struct ip6tables_match *m;
1888 struct ip6tables_rule_match *matches = NULL;
1889 struct ip6tables_rule_match *matchp;
1890 struct ip6tables_target *target = NULL;
1891 struct ip6tables_target *t;
1892 const char *jumpto = "";
1893 char *protocol = NULL;
1894 int proto_used = 0;
1896 memset(&fw, 0, sizeof(fw));
1898 /* re-set optind to 0 in case do_command gets called
1899 * a second time */
1900 optind = 0;
1902 /* clear mflags in case do_command gets called a second time
1903 * (we clear the global list of all matches for security)*/
1904 for (m = ip6tables_matches; m; m = m->next)
1905 m->mflags = 0;
1907 for (t = ip6tables_targets; t; t = t->next) {
1908 t->tflags = 0;
1909 t->used = 0;
1912 /* Suppress error messages: we may add new options if we
1913 demand-load a protocol. */
1914 opterr = 0;
1916 while ((c = getopt_long(argc, argv,
1917 "-A:D:R:I:L::M:F::Z::N:X::E:P:Vh::o:p:s:d:j:i:bvnt:m:xc:g:",
1918 opts, NULL)) != -1) {
1919 switch (c) {
1921 * Command selection
1923 case 'A':
1924 add_command(&command, CMD_APPEND, CMD_NONE,
1925 invert);
1926 chain = optarg;
1927 break;
1929 case 'D':
1930 add_command(&command, CMD_DELETE, CMD_NONE,
1931 invert);
1932 chain = optarg;
1933 if (optind < argc && argv[optind][0] != '-'
1934 && argv[optind][0] != '!') {
1935 rulenum = parse_rulenumber(argv[optind++]);
1936 command = CMD_DELETE_NUM;
1938 break;
1940 case 'R':
1941 add_command(&command, CMD_REPLACE, CMD_NONE,
1942 invert);
1943 chain = optarg;
1944 if (optind < argc && argv[optind][0] != '-'
1945 && argv[optind][0] != '!')
1946 rulenum = parse_rulenumber(argv[optind++]);
1947 else
1948 exit_error(PARAMETER_PROBLEM,
1949 "-%c requires a rule number",
1950 cmd2char(CMD_REPLACE));
1951 break;
1953 case 'I':
1954 add_command(&command, CMD_INSERT, CMD_NONE,
1955 invert);
1956 chain = optarg;
1957 if (optind < argc && argv[optind][0] != '-'
1958 && argv[optind][0] != '!')
1959 rulenum = parse_rulenumber(argv[optind++]);
1960 else rulenum = 1;
1961 break;
1963 case 'L':
1964 add_command(&command, CMD_LIST, CMD_ZERO,
1965 invert);
1966 if (optarg) chain = optarg;
1967 else if (optind < argc && argv[optind][0] != '-'
1968 && argv[optind][0] != '!')
1969 chain = argv[optind++];
1970 break;
1972 case 'F':
1973 add_command(&command, CMD_FLUSH, CMD_NONE,
1974 invert);
1975 if (optarg) chain = optarg;
1976 else if (optind < argc && argv[optind][0] != '-'
1977 && argv[optind][0] != '!')
1978 chain = argv[optind++];
1979 break;
1981 case 'Z':
1982 add_command(&command, CMD_ZERO, CMD_LIST,
1983 invert);
1984 if (optarg) chain = optarg;
1985 else if (optind < argc && argv[optind][0] != '-'
1986 && argv[optind][0] != '!')
1987 chain = argv[optind++];
1988 break;
1990 case 'N':
1991 if (optarg && (*optarg == '-' || *optarg == '!'))
1992 exit_error(PARAMETER_PROBLEM,
1993 "chain name not allowed to start "
1994 "with `%c'\n", *optarg);
1995 if (find_target(optarg, TRY_LOAD))
1996 exit_error(PARAMETER_PROBLEM,
1997 "chain name may not clash "
1998 "with target name\n");
1999 add_command(&command, CMD_NEW_CHAIN, CMD_NONE,
2000 invert);
2001 chain = optarg;
2002 break;
2004 case 'X':
2005 add_command(&command, CMD_DELETE_CHAIN, CMD_NONE,
2006 invert);
2007 if (optarg) chain = optarg;
2008 else if (optind < argc && argv[optind][0] != '-'
2009 && argv[optind][0] != '!')
2010 chain = argv[optind++];
2011 break;
2013 case 'E':
2014 add_command(&command, CMD_RENAME_CHAIN, CMD_NONE,
2015 invert);
2016 chain = optarg;
2017 if (optind < argc && argv[optind][0] != '-'
2018 && argv[optind][0] != '!')
2019 newname = argv[optind++];
2020 else
2021 exit_error(PARAMETER_PROBLEM,
2022 "-%c requires old-chain-name and "
2023 "new-chain-name",
2024 cmd2char(CMD_RENAME_CHAIN));
2025 break;
2027 case 'P':
2028 add_command(&command, CMD_SET_POLICY, CMD_NONE,
2029 invert);
2030 chain = optarg;
2031 if (optind < argc && argv[optind][0] != '-'
2032 && argv[optind][0] != '!')
2033 policy = argv[optind++];
2034 else
2035 exit_error(PARAMETER_PROBLEM,
2036 "-%c requires a chain and a policy",
2037 cmd2char(CMD_SET_POLICY));
2038 break;
2040 case 'h':
2041 if (!optarg)
2042 optarg = argv[optind];
2044 /* ip6tables -p icmp -h */
2045 if (!matches && protocol)
2046 find_match(protocol, TRY_LOAD, &matches);
2048 exit_printhelp(matches);
2051 * Option selection
2053 case 'p':
2054 check_inverse(optarg, &invert, &optind, argc);
2055 set_option(&options, OPT_PROTOCOL, &fw.ipv6.invflags,
2056 invert);
2058 /* Canonicalize into lower case */
2059 for (protocol = argv[optind-1]; *protocol; protocol++)
2060 *protocol = tolower(*protocol);
2062 protocol = argv[optind-1];
2063 fw.ipv6.proto = parse_protocol(protocol);
2064 fw.ipv6.flags |= IP6T_F_PROTO;
2066 if (fw.ipv6.proto == 0
2067 && (fw.ipv6.invflags & IP6T_INV_PROTO))
2068 exit_error(PARAMETER_PROBLEM,
2069 "rule would never match protocol");
2071 if (is_exthdr(fw.ipv6.proto)
2072 && (fw.ipv6.invflags & IP6T_INV_PROTO) == 0)
2073 printf("Warning: never matched protocol: %s. "
2074 "use extension match instead.\n",
2075 protocol);
2076 break;
2078 case 's':
2079 check_inverse(optarg, &invert, &optind, argc);
2080 set_option(&options, OPT_SOURCE, &fw.ipv6.invflags,
2081 invert);
2082 shostnetworkmask = argv[optind-1];
2083 break;
2085 case 'd':
2086 check_inverse(optarg, &invert, &optind, argc);
2087 set_option(&options, OPT_DESTINATION, &fw.ipv6.invflags,
2088 invert);
2089 dhostnetworkmask = argv[optind-1];
2090 break;
2092 #ifdef IP6T_F_GOTO
2093 case 'g':
2094 set_option(&options, OPT_JUMP, &fw.ipv6.invflags,
2095 invert);
2096 fw.ipv6.flags |= IP6T_F_GOTO;
2097 jumpto = parse_target(optarg);
2098 break;
2099 #endif
2101 case 'j':
2102 set_option(&options, OPT_JUMP, &fw.ipv6.invflags,
2103 invert);
2104 jumpto = parse_target(optarg);
2105 /* TRY_LOAD (may be chain name) */
2106 target = find_target(jumpto, TRY_LOAD);
2108 if (target) {
2109 size_t size;
2111 size = IP6T_ALIGN(sizeof(struct ip6t_entry_target))
2112 + target->size;
2114 target->t = fw_calloc(1, size);
2115 target->t->u.target_size = size;
2116 strcpy(target->t->u.user.name, jumpto);
2117 if (target->init != NULL)
2118 target->init(target->t, &fw.nfcache);
2119 opts = merge_options(opts, target->extra_opts, &target->option_offset);
2121 break;
2124 case 'i':
2125 check_inverse(optarg, &invert, &optind, argc);
2126 set_option(&options, OPT_VIANAMEIN, &fw.ipv6.invflags,
2127 invert);
2128 parse_interface(argv[optind-1],
2129 fw.ipv6.iniface,
2130 fw.ipv6.iniface_mask);
2131 break;
2133 case 'o':
2134 check_inverse(optarg, &invert, &optind, argc);
2135 set_option(&options, OPT_VIANAMEOUT, &fw.ipv6.invflags,
2136 invert);
2137 parse_interface(argv[optind-1],
2138 fw.ipv6.outiface,
2139 fw.ipv6.outiface_mask);
2140 break;
2142 case 'v':
2143 if (!verbose)
2144 set_option(&options, OPT_VERBOSE,
2145 &fw.ipv6.invflags, invert);
2146 verbose++;
2147 break;
2149 case 'm': {
2150 size_t size;
2152 if (invert)
2153 exit_error(PARAMETER_PROBLEM,
2154 "unexpected ! flag before --match");
2156 m = find_match(optarg, LOAD_MUST_SUCCEED, &matches);
2157 size = IP6T_ALIGN(sizeof(struct ip6t_entry_match))
2158 + m->size;
2159 m->m = fw_calloc(1, size);
2160 m->m->u.match_size = size;
2161 strcpy(m->m->u.user.name, m->name);
2162 set_revision(m->m->u.user.name, m->revision);
2163 if (m->init != NULL)
2164 m->init(m->m, &fw.nfcache);
2165 if (m != m->next)
2166 /* Merge options for non-cloned matches */
2167 opts = merge_options(opts, m->extra_opts, &m->option_offset);
2169 break;
2171 case 'n':
2172 set_option(&options, OPT_NUMERIC, &fw.ipv6.invflags,
2173 invert);
2174 break;
2176 case 't':
2177 if (invert)
2178 exit_error(PARAMETER_PROBLEM,
2179 "unexpected ! flag before --table");
2180 *table = argv[optind-1];
2181 break;
2183 case 'x':
2184 set_option(&options, OPT_EXPANDED, &fw.ipv6.invflags,
2185 invert);
2186 break;
2188 case 'V':
2189 if (invert)
2190 printf("Not %s ;-)\n", program_version);
2191 else
2192 printf("%s v%s\n",
2193 program_name, program_version);
2194 exit(0);
2196 case '0':
2197 set_option(&options, OPT_LINENUMBERS, &fw.ipv6.invflags,
2198 invert);
2199 break;
2201 case 'M':
2202 modprobe = optarg;
2203 break;
2205 case 'c':
2207 set_option(&options, OPT_COUNTERS, &fw.ipv6.invflags,
2208 invert);
2209 pcnt = optarg;
2210 if (optind < argc && argv[optind][0] != '-'
2211 && argv[optind][0] != '!')
2212 bcnt = argv[optind++];
2213 else
2214 exit_error(PARAMETER_PROBLEM,
2215 "-%c requires packet and byte counter",
2216 opt2char(OPT_COUNTERS));
2218 if (sscanf(pcnt, "%llu", (unsigned long long *)&fw.counters.pcnt) != 1)
2219 exit_error(PARAMETER_PROBLEM,
2220 "-%c packet counter not numeric",
2221 opt2char(OPT_COUNTERS));
2223 if (sscanf(bcnt, "%llu", (unsigned long long *)&fw.counters.bcnt) != 1)
2224 exit_error(PARAMETER_PROBLEM,
2225 "-%c byte counter not numeric",
2226 opt2char(OPT_COUNTERS));
2228 break;
2231 case 1: /* non option */
2232 if (optarg[0] == '!' && optarg[1] == '\0') {
2233 if (invert)
2234 exit_error(PARAMETER_PROBLEM,
2235 "multiple consecutive ! not"
2236 " allowed");
2237 invert = TRUE;
2238 optarg[0] = '\0';
2239 continue;
2241 printf("Bad argument `%s'\n", optarg);
2242 exit_tryhelp(2);
2244 default:
2245 if (!target
2246 || !(target->parse(c - target->option_offset,
2247 argv, invert,
2248 &target->tflags,
2249 &fw, &target->t))) {
2250 for (matchp = matches; matchp; matchp = matchp->next) {
2251 if (matchp->completed)
2252 continue;
2253 if (matchp->match->parse(c - matchp->match->option_offset,
2254 argv, invert,
2255 &matchp->match->mflags,
2256 &fw,
2257 &fw.nfcache,
2258 &matchp->match->m))
2259 break;
2261 m = matchp ? matchp->match : NULL;
2263 /* If you listen carefully, you can
2264 actually hear this code suck. */
2266 /* some explanations (after four different bugs
2267 * in 3 different releases): If we encounter a
2268 * parameter, that has not been parsed yet,
2269 * it's not an option of an explicitly loaded
2270 * match or a target. However, we support
2271 * implicit loading of the protocol match
2272 * extension. '-p tcp' means 'l4 proto 6' and
2273 * at the same time 'load tcp protocol match on
2274 * demand if we specify --dport'.
2276 * To make this work, we need to make sure:
2277 * - the parameter has not been parsed by
2278 * a match (m above)
2279 * - a protocol has been specified
2280 * - the protocol extension has not been
2281 * loaded yet, or is loaded and unused
2282 * [think of ip6tables-restore!]
2283 * - the protocol extension can be successively
2284 * loaded
2286 if (m == NULL
2287 && protocol
2288 && (!find_proto(protocol, DONT_LOAD,
2289 options&OPT_NUMERIC, NULL)
2290 || (find_proto(protocol, DONT_LOAD,
2291 options&OPT_NUMERIC, NULL)
2292 && (proto_used == 0))
2294 && (m = find_proto(protocol, TRY_LOAD,
2295 options&OPT_NUMERIC, &matches))) {
2296 /* Try loading protocol */
2297 size_t size;
2299 proto_used = 1;
2301 size = IP6T_ALIGN(sizeof(struct ip6t_entry_match))
2302 + m->size;
2304 m->m = fw_calloc(1, size);
2305 m->m->u.match_size = size;
2306 strcpy(m->m->u.user.name, m->name);
2307 set_revision(m->m->u.user.name,
2308 m->revision);
2309 if (m->init != NULL)
2310 m->init(m->m, &fw.nfcache);
2312 opts = merge_options(opts,
2313 m->extra_opts, &m->option_offset);
2315 optind--;
2316 continue;
2319 if (!m)
2320 exit_error(PARAMETER_PROBLEM,
2321 "Unknown arg `%s'",
2322 argv[optind-1]);
2325 invert = FALSE;
2328 for (matchp = matches; matchp; matchp = matchp->next)
2329 matchp->match->final_check(matchp->match->mflags);
2331 if (target)
2332 target->final_check(target->tflags);
2334 /* Fix me: must put inverse options checking here --MN */
2336 if (optind < argc)
2337 exit_error(PARAMETER_PROBLEM,
2338 "unknown arguments found on commandline");
2339 if (!command)
2340 exit_error(PARAMETER_PROBLEM, "no command specified");
2341 if (invert)
2342 exit_error(PARAMETER_PROBLEM,
2343 "nothing appropriate following !");
2345 if (command & (CMD_REPLACE | CMD_INSERT | CMD_DELETE | CMD_APPEND)) {
2346 if (!(options & OPT_DESTINATION))
2347 dhostnetworkmask = "::0/0";
2348 if (!(options & OPT_SOURCE))
2349 shostnetworkmask = "::0/0";
2352 if (shostnetworkmask)
2353 parse_hostnetworkmask(shostnetworkmask, &saddrs,
2354 &(fw.ipv6.smsk), &nsaddrs);
2356 if (dhostnetworkmask)
2357 parse_hostnetworkmask(dhostnetworkmask, &daddrs,
2358 &(fw.ipv6.dmsk), &ndaddrs);
2360 if ((nsaddrs > 1 || ndaddrs > 1) &&
2361 (fw.ipv6.invflags & (IP6T_INV_SRCIP | IP6T_INV_DSTIP)))
2362 exit_error(PARAMETER_PROBLEM, "! not allowed with multiple"
2363 " source or destination IP addresses");
2365 if (command == CMD_REPLACE && (nsaddrs != 1 || ndaddrs != 1))
2366 exit_error(PARAMETER_PROBLEM, "Replacement rule does not "
2367 "specify a unique address");
2369 generic_opt_check(command, options);
2371 if (chain && strlen(chain) > IP6T_FUNCTION_MAXNAMELEN)
2372 exit_error(PARAMETER_PROBLEM,
2373 "chain name `%s' too long (must be under %i chars)",
2374 chain, IP6T_FUNCTION_MAXNAMELEN);
2376 /* only allocate handle if we weren't called with a handle */
2377 if (!*handle)
2378 *handle = ip6tc_init(*table);
2380 /* try to insmod the module if iptc_init failed */
2381 if (!*handle && load_ip6tables_ko(modprobe, 0) != -1)
2382 *handle = ip6tc_init(*table);
2384 if (!*handle)
2385 exit_error(VERSION_PROBLEM,
2386 "can't initialize ip6tables table `%s': %s",
2387 *table, ip6tc_strerror(errno));
2389 if (command == CMD_APPEND
2390 || command == CMD_DELETE
2391 || command == CMD_INSERT
2392 || command == CMD_REPLACE) {
2393 if (strcmp(chain, "PREROUTING") == 0
2394 || strcmp(chain, "INPUT") == 0) {
2395 /* -o not valid with incoming packets. */
2396 if (options & OPT_VIANAMEOUT)
2397 exit_error(PARAMETER_PROBLEM,
2398 "Can't use -%c with %s\n",
2399 opt2char(OPT_VIANAMEOUT),
2400 chain);
2403 if (strcmp(chain, "POSTROUTING") == 0
2404 || strcmp(chain, "OUTPUT") == 0) {
2405 /* -i not valid with outgoing packets */
2406 if (options & OPT_VIANAMEIN)
2407 exit_error(PARAMETER_PROBLEM,
2408 "Can't use -%c with %s\n",
2409 opt2char(OPT_VIANAMEIN),
2410 chain);
2413 if (target && ip6tc_is_chain(jumpto, *handle)) {
2414 printf("Warning: using chain %s, not extension\n",
2415 jumpto);
2417 if (target->t)
2418 free(target->t);
2420 target = NULL;
2423 /* If they didn't specify a target, or it's a chain
2424 name, use standard. */
2425 if (!target
2426 && (strlen(jumpto) == 0
2427 || ip6tc_is_chain(jumpto, *handle))) {
2428 size_t size;
2430 target = find_target(IP6T_STANDARD_TARGET,
2431 LOAD_MUST_SUCCEED);
2433 size = sizeof(struct ip6t_entry_target)
2434 + target->size;
2435 target->t = fw_calloc(1, size);
2436 target->t->u.target_size = size;
2437 strcpy(target->t->u.user.name, jumpto);
2438 if (target->init != NULL)
2439 target->init(target->t, &fw.nfcache);
2442 if (!target) {
2443 /* it is no chain, and we can't load a plugin.
2444 * We cannot know if the plugin is corrupt, non
2445 * existant OR if the user just misspelled a
2446 * chain. */
2447 #ifdef IP6T_F_GOTO
2448 if (fw.ipv6.flags & IP6T_F_GOTO)
2449 exit_error(PARAMETER_PROBLEM,
2450 "goto '%s' is not a chain\n", jumpto);
2451 #endif
2452 find_target(jumpto, LOAD_MUST_SUCCEED);
2453 } else {
2454 e = generate_entry(&fw, matches, target->t);
2455 free(target->t);
2459 switch (command) {
2460 case CMD_APPEND:
2461 ret = append_entry(chain, e,
2462 nsaddrs, saddrs, ndaddrs, daddrs,
2463 options&OPT_VERBOSE,
2464 handle);
2465 break;
2466 case CMD_DELETE:
2467 ret = delete_entry(chain, e,
2468 nsaddrs, saddrs, ndaddrs, daddrs,
2469 options&OPT_VERBOSE,
2470 handle, matches);
2471 break;
2472 case CMD_DELETE_NUM:
2473 ret = ip6tc_delete_num_entry(chain, rulenum - 1, handle);
2474 break;
2475 case CMD_REPLACE:
2476 ret = replace_entry(chain, e, rulenum - 1,
2477 saddrs, daddrs, options&OPT_VERBOSE,
2478 handle);
2479 break;
2480 case CMD_INSERT:
2481 ret = insert_entry(chain, e, rulenum - 1,
2482 nsaddrs, saddrs, ndaddrs, daddrs,
2483 options&OPT_VERBOSE,
2484 handle);
2485 break;
2486 case CMD_LIST:
2487 ret = list_entries(chain,
2488 options&OPT_VERBOSE,
2489 options&OPT_NUMERIC,
2490 options&OPT_EXPANDED,
2491 options&OPT_LINENUMBERS,
2492 handle);
2493 break;
2494 case CMD_FLUSH:
2495 ret = flush_entries(chain, options&OPT_VERBOSE, handle);
2496 break;
2497 case CMD_ZERO:
2498 ret = zero_entries(chain, options&OPT_VERBOSE, handle);
2499 break;
2500 case CMD_LIST|CMD_ZERO:
2501 ret = list_entries(chain,
2502 options&OPT_VERBOSE,
2503 options&OPT_NUMERIC,
2504 options&OPT_EXPANDED,
2505 options&OPT_LINENUMBERS,
2506 handle);
2507 if (ret)
2508 ret = zero_entries(chain,
2509 options&OPT_VERBOSE, handle);
2510 break;
2511 case CMD_NEW_CHAIN:
2512 ret = ip6tc_create_chain(chain, handle);
2513 break;
2514 case CMD_DELETE_CHAIN:
2515 ret = delete_chain(chain, options&OPT_VERBOSE, handle);
2516 break;
2517 case CMD_RENAME_CHAIN:
2518 ret = ip6tc_rename_chain(chain, newname, handle);
2519 break;
2520 case CMD_SET_POLICY:
2521 ret = ip6tc_set_policy(chain, policy, NULL, handle);
2522 break;
2523 default:
2524 /* We should never reach this... */
2525 exit_tryhelp(2);
2528 if (verbose > 1)
2529 dump_entries6(*handle);
2531 clear_rule_matches(&matches);
2533 if (e != NULL) {
2534 free(e);
2535 e = NULL;
2538 free(saddrs);
2539 free(daddrs);
2540 free_opts(1);
2542 return ret;