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