xtables.c revision 73866357e4a7a0fdc1b293bf8863fee2bd56da9e
1/*
2 * (C) 2000-2006 by the netfilter coreteam <coreteam@netfilter.org>:
3 *
4 *	This program is free software; you can redistribute it and/or modify
5 *	it under the terms of the GNU General Public License as published by
6 *	the Free Software Foundation; either version 2 of the License, or
7 *	(at your option) any later version.
8 *
9 *	This program is distributed in the hope that it will be useful,
10 *	but WITHOUT ANY WARRANTY; without even the implied warranty of
11 *	MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12 *	GNU General Public License for more details.
13 *
14 *	You should have received a copy of the GNU General Public License
15 *	along with this program; if not, write to the Free Software
16 *	Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
17 */
18
19#include <errno.h>
20#include <fcntl.h>
21#include <netdb.h>
22#include <stdarg.h>
23#include <stdbool.h>
24#include <stdio.h>
25#include <stdlib.h>
26#include <string.h>
27#include <unistd.h>
28#include <sys/socket.h>
29#include <sys/stat.h>
30#include <sys/types.h>
31#include <sys/wait.h>
32#include <arpa/inet.h>
33
34#include <xtables.h>
35#include <limits.h> /* INT_MAX in ip_tables.h/ip6_tables.h */
36#include <linux/netfilter_ipv4/ip_tables.h>
37#include <linux/netfilter_ipv6/ip6_tables.h>
38#include <libiptc/libxtc.h>
39
40#ifndef NO_SHARED_LIBS
41#include <dlfcn.h>
42#endif
43#ifndef IPT_SO_GET_REVISION_MATCH /* Old kernel source. */
44#	define IPT_SO_GET_REVISION_MATCH	(IPT_BASE_CTL + 2)
45#	define IPT_SO_GET_REVISION_TARGET	(IPT_BASE_CTL + 3)
46#endif
47#ifndef IP6T_SO_GET_REVISION_MATCH /* Old kernel source. */
48#	define IP6T_SO_GET_REVISION_MATCH	68
49#	define IP6T_SO_GET_REVISION_TARGET	69
50#endif
51#include <getopt.h>
52#include "xshared.h"
53
54#define NPROTO	255
55
56#ifndef PROC_SYS_MODPROBE
57#define PROC_SYS_MODPROBE "/proc/sys/kernel/modprobe"
58#endif
59
60void basic_exit_err(enum xtables_exittype status, const char *msg, ...) __attribute__((noreturn, format(printf,2,3)));
61
62struct xtables_globals *xt_params = NULL;
63
64void basic_exit_err(enum xtables_exittype status, const char *msg, ...)
65{
66	va_list args;
67
68	va_start(args, msg);
69	fprintf(stderr, "%s v%s: ", xt_params->program_name, xt_params->program_version);
70	vfprintf(stderr, msg, args);
71	va_end(args);
72	fprintf(stderr, "\n");
73	exit(status);
74}
75
76void xtables_free_opts(int unused)
77{
78	if (xt_params->opts != xt_params->orig_opts) {
79		free(xt_params->opts);
80		xt_params->opts = NULL;
81	}
82}
83
84struct option *xtables_merge_options(struct option *orig_opts,
85				     struct option *oldopts,
86				     const struct option *newopts,
87				     unsigned int *option_offset)
88{
89	unsigned int num_oold = 0, num_old = 0, num_new = 0, i;
90	struct option *merge, *mp;
91
92	if (newopts == NULL)
93		return oldopts;
94
95	for (num_oold = 0; orig_opts[num_oold].name; num_oold++) ;
96	if (oldopts != NULL)
97		for (num_old = 0; oldopts[num_old].name; num_old++) ;
98	for (num_new = 0; newopts[num_new].name; num_new++) ;
99
100	/*
101	 * Since @oldopts also has @orig_opts already (and does so at the
102	 * start), skip these entries.
103	 */
104	oldopts += num_oold;
105	num_old -= num_oold;
106
107	merge = malloc(sizeof(*mp) * (num_oold + num_old + num_new + 1));
108	if (merge == NULL)
109		return NULL;
110
111	/* Let the base options -[ADI...] have precedence over everything */
112	memcpy(merge, orig_opts, sizeof(*mp) * num_oold);
113	mp = merge + num_oold;
114
115	/* Second, the new options */
116	xt_params->option_offset += XT_OPTION_OFFSET_SCALE;
117	*option_offset = xt_params->option_offset;
118	memcpy(mp, newopts, sizeof(*mp) * num_new);
119
120	for (i = 0; i < num_new; ++i, ++mp)
121		mp->val += *option_offset;
122
123	/* Third, the old options */
124	memcpy(mp, oldopts, sizeof(*mp) * num_old);
125	mp += num_old;
126	xtables_free_opts(0);
127
128	/* Clear trailing entry */
129	memset(mp, 0, sizeof(*mp));
130	return merge;
131}
132
133/**
134 * xtables_afinfo - protocol family dependent information
135 * @kmod:		kernel module basename (e.g. "ip_tables")
136 * @libprefix:		prefix of .so library name (e.g. "libipt_")
137 * @family:		nfproto family
138 * @ipproto:		used by setsockopt (e.g. IPPROTO_IP)
139 * @so_rev_match:	optname to check revision support of match
140 * @so_rev_target:	optname to check revision support of target
141 */
142struct xtables_afinfo {
143	const char *kmod;
144	const char *libprefix;
145	uint8_t family;
146	uint8_t ipproto;
147	int so_rev_match;
148	int so_rev_target;
149};
150
151static const struct xtables_afinfo afinfo_ipv4 = {
152	.kmod          = "ip_tables",
153	.libprefix     = "libipt_",
154	.family	       = NFPROTO_IPV4,
155	.ipproto       = IPPROTO_IP,
156	.so_rev_match  = IPT_SO_GET_REVISION_MATCH,
157	.so_rev_target = IPT_SO_GET_REVISION_TARGET,
158};
159
160static const struct xtables_afinfo afinfo_ipv6 = {
161	.kmod          = "ip6_tables",
162	.libprefix     = "libip6t_",
163	.family        = NFPROTO_IPV6,
164	.ipproto       = IPPROTO_IPV6,
165	.so_rev_match  = IP6T_SO_GET_REVISION_MATCH,
166	.so_rev_target = IP6T_SO_GET_REVISION_TARGET,
167};
168
169static const struct xtables_afinfo *afinfo;
170
171/* Search path for Xtables .so files */
172static const char *xtables_libdir;
173
174/* the path to command to load kernel module */
175const char *xtables_modprobe_program;
176
177/* Keeping track of external matches and targets: linked lists.  */
178struct xtables_match *xtables_matches;
179struct xtables_target *xtables_targets;
180
181void xtables_init(void)
182{
183	xtables_libdir = getenv("XTABLES_LIBDIR");
184	if (xtables_libdir != NULL)
185		return;
186	xtables_libdir = getenv("IPTABLES_LIB_DIR");
187	if (xtables_libdir != NULL) {
188		fprintf(stderr, "IPTABLES_LIB_DIR is deprecated, "
189		        "use XTABLES_LIBDIR.\n");
190		return;
191	}
192	/*
193	 * Well yes, IP6TABLES_LIB_DIR is of lower priority over
194	 * IPTABLES_LIB_DIR since this moved to libxtables; I think that is ok
195	 * for these env vars are deprecated anyhow, and in light of the
196	 * (shared) libxt_*.so files, makes less sense to have
197	 * IPTABLES_LIB_DIR != IP6TABLES_LIB_DIR.
198	 */
199	xtables_libdir = getenv("IP6TABLES_LIB_DIR");
200	if (xtables_libdir != NULL) {
201		fprintf(stderr, "IP6TABLES_LIB_DIR is deprecated, "
202		        "use XTABLES_LIBDIR.\n");
203		return;
204	}
205	xtables_libdir = XTABLES_LIBDIR;
206}
207
208void xtables_set_nfproto(uint8_t nfproto)
209{
210	switch (nfproto) {
211	case NFPROTO_IPV4:
212		afinfo = &afinfo_ipv4;
213		break;
214	case NFPROTO_IPV6:
215		afinfo = &afinfo_ipv6;
216		break;
217	default:
218		fprintf(stderr, "libxtables: unhandled NFPROTO in %s\n",
219		        __func__);
220	}
221}
222
223/**
224 * xtables_set_params - set the global parameters used by xtables
225 * @xtp:	input xtables_globals structure
226 *
227 * The app is expected to pass a valid xtables_globals data-filled
228 * with proper values
229 * @xtp cannot be NULL
230 *
231 * Returns -1 on failure to set and 0 on success
232 */
233int xtables_set_params(struct xtables_globals *xtp)
234{
235	if (!xtp) {
236		fprintf(stderr, "%s: Illegal global params\n",__func__);
237		return -1;
238	}
239
240	xt_params = xtp;
241
242	if (!xt_params->exit_err)
243		xt_params->exit_err = basic_exit_err;
244
245	return 0;
246}
247
248int xtables_init_all(struct xtables_globals *xtp, uint8_t nfproto)
249{
250	xtables_init();
251	xtables_set_nfproto(nfproto);
252	return xtables_set_params(xtp);
253}
254
255/**
256 * xtables_*alloc - wrappers that exit on failure
257 */
258void *xtables_calloc(size_t count, size_t size)
259{
260	void *p;
261
262	if ((p = calloc(count, size)) == NULL) {
263		perror("ip[6]tables: calloc failed");
264		exit(1);
265	}
266
267	return p;
268}
269
270void *xtables_malloc(size_t size)
271{
272	void *p;
273
274	if ((p = malloc(size)) == NULL) {
275		perror("ip[6]tables: malloc failed");
276		exit(1);
277	}
278
279	return p;
280}
281
282void *xtables_realloc(void *ptr, size_t size)
283{
284	void *p;
285
286	if ((p = realloc(ptr, size)) == NULL) {
287		perror("ip[6]tables: realloc failed");
288		exit(1);
289	}
290
291	return p;
292}
293
294static char *get_modprobe(void)
295{
296	int procfile;
297	char *ret;
298
299#define PROCFILE_BUFSIZ	1024
300	procfile = open(PROC_SYS_MODPROBE, O_RDONLY);
301	if (procfile < 0)
302		return NULL;
303
304	ret = malloc(PROCFILE_BUFSIZ);
305	if (ret) {
306		memset(ret, 0, PROCFILE_BUFSIZ);
307		switch (read(procfile, ret, PROCFILE_BUFSIZ)) {
308		case -1: goto fail;
309		case PROCFILE_BUFSIZ: goto fail; /* Partial read.  Wierd */
310		}
311		if (ret[strlen(ret)-1]=='\n')
312			ret[strlen(ret)-1]=0;
313		close(procfile);
314		return ret;
315	}
316 fail:
317	free(ret);
318	close(procfile);
319	return NULL;
320}
321
322int xtables_insmod(const char *modname, const char *modprobe, bool quiet)
323{
324	char *buf = NULL;
325	char *argv[4];
326	int status;
327
328	/* If they don't explicitly set it, read out of kernel */
329	if (!modprobe) {
330		buf = get_modprobe();
331		if (!buf)
332			return -1;
333		modprobe = buf;
334	}
335
336	/*
337	 * Need to flush the buffer, or the child may output it again
338	 * when switching the program thru execv.
339	 */
340	fflush(stdout);
341
342	switch (vfork()) {
343	case 0:
344		argv[0] = (char *)modprobe;
345		argv[1] = (char *)modname;
346		if (quiet) {
347			argv[2] = "-q";
348			argv[3] = NULL;
349		} else {
350			argv[2] = NULL;
351			argv[3] = NULL;
352		}
353		execv(argv[0], argv);
354
355		/* not usually reached */
356		exit(1);
357	case -1:
358		return -1;
359
360	default: /* parent */
361		wait(&status);
362	}
363
364	free(buf);
365	if (WIFEXITED(status) && WEXITSTATUS(status) == 0)
366		return 0;
367	return -1;
368}
369
370int xtables_load_ko(const char *modprobe, bool quiet)
371{
372	static bool loaded = false;
373	static int ret = -1;
374
375	if (!loaded) {
376		ret = xtables_insmod(afinfo->kmod, modprobe, quiet);
377		loaded = (ret == 0);
378	}
379
380	return ret;
381}
382
383/**
384 * xtables_strtou{i,l} - string to number conversion
385 * @s:	input string
386 * @end:	like strtoul's "end" pointer
387 * @value:	pointer for result
388 * @min:	minimum accepted value
389 * @max:	maximum accepted value
390 *
391 * If @end is NULL, we assume the caller wants a "strict strtoul", and hence
392 * "15a" is rejected.
393 * In either case, the value obtained is compared for min-max compliance.
394 * Base is always 0, i.e. autodetect depending on @s.
395 *
396 * Returns true/false whether number was accepted. On failure, *value has
397 * undefined contents.
398 */
399bool xtables_strtoul(const char *s, char **end, unsigned long *value,
400                     unsigned long min, unsigned long max)
401{
402	unsigned long v;
403	char *my_end;
404
405	errno = 0;
406	v = strtoul(s, &my_end, 0);
407
408	if (my_end == s)
409		return false;
410	if (end != NULL)
411		*end = my_end;
412
413	if (errno != ERANGE && min <= v && (max == 0 || v <= max)) {
414		if (value != NULL)
415			*value = v;
416		if (end == NULL)
417			return *my_end == '\0';
418		return true;
419	}
420
421	return false;
422}
423
424bool xtables_strtoui(const char *s, char **end, unsigned int *value,
425                     unsigned int min, unsigned int max)
426{
427	unsigned long v;
428	bool ret;
429
430	ret = xtables_strtoul(s, end, &v, min, max);
431	if (value != NULL)
432		*value = v;
433	return ret;
434}
435
436int xtables_service_to_port(const char *name, const char *proto)
437{
438	struct servent *service;
439
440	if ((service = getservbyname(name, proto)) != NULL)
441		return ntohs((unsigned short) service->s_port);
442
443	return -1;
444}
445
446uint16_t xtables_parse_port(const char *port, const char *proto)
447{
448	unsigned int portnum;
449
450	if (xtables_strtoui(port, NULL, &portnum, 0, UINT16_MAX) ||
451	    (portnum = xtables_service_to_port(port, proto)) != (unsigned)-1)
452		return portnum;
453
454	xt_params->exit_err(PARAMETER_PROBLEM,
455		   "invalid port/service `%s' specified", port);
456}
457
458void xtables_parse_interface(const char *arg, char *vianame,
459			     unsigned char *mask)
460{
461	unsigned int vialen = strlen(arg);
462	unsigned int i;
463
464	memset(mask, 0, IFNAMSIZ);
465	memset(vianame, 0, IFNAMSIZ);
466
467	if (vialen + 1 > IFNAMSIZ)
468		xt_params->exit_err(PARAMETER_PROBLEM,
469			   "interface name `%s' must be shorter than IFNAMSIZ"
470			   " (%i)", arg, IFNAMSIZ-1);
471
472	strcpy(vianame, arg);
473	if (vialen == 0)
474		memset(mask, 0, IFNAMSIZ);
475	else if (vianame[vialen - 1] == '+') {
476		memset(mask, 0xFF, vialen - 1);
477		memset(mask + vialen - 1, 0, IFNAMSIZ - vialen + 1);
478		/* Don't remove `+' here! -HW */
479	} else {
480		/* Include nul-terminator in match */
481		memset(mask, 0xFF, vialen + 1);
482		memset(mask + vialen + 1, 0, IFNAMSIZ - vialen - 1);
483		for (i = 0; vianame[i]; i++) {
484			if (vianame[i] == '/' ||
485			    vianame[i] == ' ') {
486				fprintf(stderr,
487					"Warning: weird character in interface"
488					" `%s' ('/' and ' ' are not allowed by the kernel).\n",
489					vianame);
490				break;
491			}
492		}
493	}
494}
495
496#ifndef NO_SHARED_LIBS
497static void *load_extension(const char *search_path, const char *af_prefix,
498    const char *name, bool is_target)
499{
500	const char *all_prefixes[] = {"libxt_", af_prefix, NULL};
501	const char **prefix;
502	const char *dir = search_path, *next;
503	void *ptr = NULL;
504	struct stat sb;
505	char path[256];
506
507	do {
508		next = strchr(dir, ':');
509		if (next == NULL)
510			next = dir + strlen(dir);
511
512		for (prefix = all_prefixes; *prefix != NULL; ++prefix) {
513			snprintf(path, sizeof(path), "%.*s/%s%s.so",
514			         (unsigned int)(next - dir), dir,
515			         *prefix, name);
516
517			if (stat(path, &sb) != 0) {
518				if (errno == ENOENT)
519					continue;
520				fprintf(stderr, "%s: %s\n", path,
521					strerror(errno));
522				return NULL;
523			}
524			if (dlopen(path, RTLD_NOW) == NULL) {
525				fprintf(stderr, "%s: %s\n", path, dlerror());
526				break;
527			}
528
529			if (is_target)
530				ptr = xtables_find_target(name, XTF_DONT_LOAD);
531			else
532				ptr = xtables_find_match(name,
533				      XTF_DONT_LOAD, NULL);
534
535			if (ptr != NULL)
536				return ptr;
537
538			fprintf(stderr, "%s: no \"%s\" extension found for "
539				"this protocol\n", path, name);
540			errno = ENOENT;
541			return NULL;
542		}
543		dir = next + 1;
544	} while (*next != '\0');
545
546	return NULL;
547}
548#endif
549
550struct xtables_match *
551xtables_find_match(const char *name, enum xtables_tryload tryload,
552		   struct xtables_rule_match **matches)
553{
554	struct xtables_match *ptr;
555	const char *icmp6 = "icmp6";
556
557	if (strlen(name) >= XT_EXTENSION_MAXNAMELEN)
558		xtables_error(PARAMETER_PROBLEM,
559			   "Invalid match name \"%s\" (%u chars max)",
560			   name, XT_EXTENSION_MAXNAMELEN - 1);
561
562	/* This is ugly as hell. Nonetheless, there is no way of changing
563	 * this without hurting backwards compatibility */
564	if ( (strcmp(name,"icmpv6") == 0) ||
565	     (strcmp(name,"ipv6-icmp") == 0) ||
566	     (strcmp(name,"icmp6") == 0) )
567		name = icmp6;
568
569	for (ptr = xtables_matches; ptr; ptr = ptr->next) {
570		if (strcmp(name, ptr->name) == 0) {
571			struct xtables_match *clone;
572
573			/* First match of this type: */
574			if (ptr->m == NULL)
575				break;
576
577			/* Second and subsequent clones */
578			clone = xtables_malloc(sizeof(struct xtables_match));
579			memcpy(clone, ptr, sizeof(struct xtables_match));
580			clone->mflags = 0;
581			/* This is a clone: */
582			clone->next = clone;
583
584			ptr = clone;
585			break;
586		}
587	}
588
589#ifndef NO_SHARED_LIBS
590	if (!ptr && tryload != XTF_DONT_LOAD && tryload != XTF_DURING_LOAD) {
591		ptr = load_extension(xtables_libdir, afinfo->libprefix,
592		      name, false);
593
594		if (ptr == NULL && tryload == XTF_LOAD_MUST_SUCCEED)
595			xt_params->exit_err(PARAMETER_PROBLEM,
596				   "Couldn't load match `%s':%s\n",
597				   name, strerror(errno));
598	}
599#else
600	if (ptr && !ptr->loaded) {
601		if (tryload != XTF_DONT_LOAD)
602			ptr->loaded = 1;
603		else
604			ptr = NULL;
605	}
606	if(!ptr && (tryload == XTF_LOAD_MUST_SUCCEED)) {
607		xt_params->exit_err(PARAMETER_PROBLEM,
608			   "Couldn't find match `%s'\n", name);
609	}
610#endif
611
612	if (ptr && matches) {
613		struct xtables_rule_match **i;
614		struct xtables_rule_match *newentry;
615
616		newentry = xtables_malloc(sizeof(struct xtables_rule_match));
617
618		for (i = matches; *i; i = &(*i)->next) {
619			if (strcmp(name, (*i)->match->name) == 0)
620				(*i)->completed = true;
621		}
622		newentry->match = ptr;
623		newentry->completed = false;
624		newentry->next = NULL;
625		*i = newentry;
626	}
627
628	return ptr;
629}
630
631struct xtables_target *
632xtables_find_target(const char *name, enum xtables_tryload tryload)
633{
634	struct xtables_target *ptr;
635
636	/* Standard target? */
637	if (strcmp(name, "") == 0
638	    || strcmp(name, XTC_LABEL_ACCEPT) == 0
639	    || strcmp(name, XTC_LABEL_DROP) == 0
640	    || strcmp(name, XTC_LABEL_QUEUE) == 0
641	    || strcmp(name, XTC_LABEL_RETURN) == 0)
642		name = "standard";
643
644	for (ptr = xtables_targets; ptr; ptr = ptr->next) {
645		if (strcmp(name, ptr->name) == 0)
646			break;
647	}
648
649#ifndef NO_SHARED_LIBS
650	if (!ptr && tryload != XTF_DONT_LOAD && tryload != XTF_DURING_LOAD) {
651		ptr = load_extension(xtables_libdir, afinfo->libprefix,
652		      name, true);
653
654		if (ptr == NULL && tryload == XTF_LOAD_MUST_SUCCEED)
655			xt_params->exit_err(PARAMETER_PROBLEM,
656				   "Couldn't load target `%s':%s\n",
657				   name, strerror(errno));
658	}
659#else
660	if (ptr && !ptr->loaded) {
661		if (tryload != XTF_DONT_LOAD)
662			ptr->loaded = 1;
663		else
664			ptr = NULL;
665	}
666	if (ptr == NULL && tryload == XTF_LOAD_MUST_SUCCEED) {
667		xt_params->exit_err(PARAMETER_PROBLEM,
668			   "Couldn't find target `%s'\n", name);
669	}
670#endif
671
672	if (ptr)
673		ptr->used = 1;
674
675	return ptr;
676}
677
678static int compatible_revision(const char *name, uint8_t revision, int opt)
679{
680	struct xt_get_revision rev;
681	socklen_t s = sizeof(rev);
682	int max_rev, sockfd;
683
684	sockfd = socket(afinfo->family, SOCK_RAW, IPPROTO_RAW);
685	if (sockfd < 0) {
686		if (errno == EPERM) {
687			/* revision 0 is always supported. */
688			if (revision != 0)
689				fprintf(stderr, "Could not determine whether "
690						"revision %u is supported, "
691						"assuming it is.\n",
692					revision);
693			return 1;
694		}
695		fprintf(stderr, "Could not open socket to kernel: %s\n",
696			strerror(errno));
697		exit(1);
698	}
699
700	xtables_load_ko(xtables_modprobe_program, true);
701
702	strcpy(rev.name, name);
703	rev.revision = revision;
704
705	max_rev = getsockopt(sockfd, afinfo->ipproto, opt, &rev, &s);
706	if (max_rev < 0) {
707		/* Definitely don't support this? */
708		if (errno == ENOENT || errno == EPROTONOSUPPORT) {
709			close(sockfd);
710			return 0;
711		} else if (errno == ENOPROTOOPT) {
712			close(sockfd);
713			/* Assume only revision 0 support (old kernel) */
714			return (revision == 0);
715		} else {
716			fprintf(stderr, "getsockopt failed strangely: %s\n",
717				strerror(errno));
718			exit(1);
719		}
720	}
721	close(sockfd);
722	return 1;
723}
724
725
726static int compatible_match_revision(const char *name, uint8_t revision)
727{
728	return compatible_revision(name, revision, afinfo->so_rev_match);
729}
730
731static int compatible_target_revision(const char *name, uint8_t revision)
732{
733	return compatible_revision(name, revision, afinfo->so_rev_target);
734}
735
736static void xtables_check_options(const char *name, const struct option *opt)
737{
738	for (; opt->name != NULL; ++opt)
739		if (opt->val < 0 || opt->val >= XT_OPTION_OFFSET_SCALE) {
740			fprintf(stderr, "%s: Extension %s uses invalid "
741			        "option value %d\n",xt_params->program_name,
742			        name, opt->val);
743			exit(1);
744		}
745}
746
747void xtables_register_match(struct xtables_match *me)
748{
749	struct xtables_match **i, *old;
750
751	if (me->version == NULL) {
752		fprintf(stderr, "%s: match %s<%u> is missing a version\n",
753		        xt_params->program_name, me->name, me->revision);
754		exit(1);
755	}
756	if (strcmp(me->version, XTABLES_VERSION) != 0) {
757		fprintf(stderr, "%s: match \"%s\" has version \"%s\", "
758		        "but \"%s\" is required.\n",
759			xt_params->program_name, me->name,
760			me->version, XTABLES_VERSION);
761		exit(1);
762	}
763
764	if (strlen(me->name) >= XT_EXTENSION_MAXNAMELEN) {
765		fprintf(stderr, "%s: match `%s' has invalid name\n",
766			xt_params->program_name, me->name);
767		exit(1);
768	}
769
770	if (me->family >= NPROTO) {
771		fprintf(stderr,
772			"%s: BUG: match %s has invalid protocol family\n",
773			xt_params->program_name, me->name);
774		exit(1);
775	}
776
777	if (me->extra_opts != NULL)
778		xtables_check_options(me->name, me->extra_opts);
779
780	/* ignore not interested match */
781	if (me->family != afinfo->family && me->family != AF_UNSPEC)
782		return;
783
784	old = xtables_find_match(me->name, XTF_DURING_LOAD, NULL);
785	if (old) {
786		if (old->revision == me->revision &&
787		    old->family == me->family) {
788			fprintf(stderr,
789				"%s: match `%s' already registered.\n",
790				xt_params->program_name, me->name);
791			exit(1);
792		}
793
794		/* Now we have two (or more) options, check compatibility. */
795		if (compatible_match_revision(old->name, old->revision)
796		    && old->revision > me->revision)
797			return;
798
799		/* See if new match can be used. */
800		if (!compatible_match_revision(me->name, me->revision))
801			return;
802
803		/* Prefer !AF_UNSPEC over AF_UNSPEC for same revision. */
804		if (old->revision == me->revision && me->family == AF_UNSPEC)
805			return;
806
807		/* Delete old one. */
808		for (i = &xtables_matches; *i!=old; i = &(*i)->next);
809		*i = old->next;
810	}
811
812	if (me->size != XT_ALIGN(me->size)) {
813		fprintf(stderr, "%s: match `%s' has invalid size %u.\n",
814		        xt_params->program_name, me->name,
815		        (unsigned int)me->size);
816		exit(1);
817	}
818
819	/* Append to list. */
820	for (i = &xtables_matches; *i; i = &(*i)->next);
821	me->next = NULL;
822	*i = me;
823
824	me->m = NULL;
825	me->mflags = 0;
826}
827
828void xtables_register_matches(struct xtables_match *match, unsigned int n)
829{
830	do {
831		xtables_register_match(&match[--n]);
832	} while (n > 0);
833}
834
835void xtables_register_target(struct xtables_target *me)
836{
837	struct xtables_target *old;
838
839	if (me->version == NULL) {
840		fprintf(stderr, "%s: target %s<%u> is missing a version\n",
841		        xt_params->program_name, me->name, me->revision);
842		exit(1);
843	}
844	if (strcmp(me->version, XTABLES_VERSION) != 0) {
845		fprintf(stderr, "%s: target \"%s\" has version \"%s\", "
846		        "but \"%s\" is required.\n",
847			xt_params->program_name, me->name,
848			me->version, XTABLES_VERSION);
849		exit(1);
850	}
851
852	if (strlen(me->name) >= XT_EXTENSION_MAXNAMELEN) {
853		fprintf(stderr, "%s: target `%s' has invalid name\n",
854			xt_params->program_name, me->name);
855		exit(1);
856	}
857
858	if (me->family >= NPROTO) {
859		fprintf(stderr,
860			"%s: BUG: target %s has invalid protocol family\n",
861			xt_params->program_name, me->name);
862		exit(1);
863	}
864
865	if (me->extra_opts != NULL)
866		xtables_check_options(me->name, me->extra_opts);
867
868	/* ignore not interested target */
869	if (me->family != afinfo->family && me->family != AF_UNSPEC)
870		return;
871
872	old = xtables_find_target(me->name, XTF_DURING_LOAD);
873	if (old) {
874		struct xtables_target **i;
875
876		if (old->revision == me->revision &&
877		    old->family == me->family) {
878			fprintf(stderr,
879				"%s: target `%s' already registered.\n",
880				xt_params->program_name, me->name);
881			exit(1);
882		}
883
884		/* Now we have two (or more) options, check compatibility. */
885		if (compatible_target_revision(old->name, old->revision)
886		    && old->revision > me->revision)
887			return;
888
889		/* See if new target can be used. */
890		if (!compatible_target_revision(me->name, me->revision))
891			return;
892
893		/* Prefer !AF_UNSPEC over AF_UNSPEC for same revision. */
894		if (old->revision == me->revision && me->family == AF_UNSPEC)
895			return;
896
897		/* Delete old one. */
898		for (i = &xtables_targets; *i!=old; i = &(*i)->next);
899		*i = old->next;
900	}
901
902	if (me->size != XT_ALIGN(me->size)) {
903		fprintf(stderr, "%s: target `%s' has invalid size %u.\n",
904		        xt_params->program_name, me->name,
905		        (unsigned int)me->size);
906		exit(1);
907	}
908
909	/* Prepend to list. */
910	me->next = xtables_targets;
911	xtables_targets = me;
912	me->t = NULL;
913	me->tflags = 0;
914}
915
916void xtables_register_targets(struct xtables_target *target, unsigned int n)
917{
918	do {
919		xtables_register_target(&target[--n]);
920	} while (n > 0);
921}
922
923/**
924 * xtables_param_act - act on condition
925 * @status:	a constant from enum xtables_exittype
926 *
927 * %XTF_ONLY_ONCE: print error message that option may only be used once.
928 * @p1:		module name (e.g. "mark")
929 * @p2(...):	option in conflict (e.g. "--mark")
930 * @p3(...):	condition to match on (see extensions/ for examples)
931 *
932 * %XTF_NO_INVERT: option does not support inversion
933 * @p1:		module name
934 * @p2:		option in conflict
935 * @p3:		condition to match on
936 *
937 * %XTF_BAD_VALUE: bad value for option
938 * @p1:		module name
939 * @p2:		option with which the problem occured (e.g. "--mark")
940 * @p3:		string the user passed in (e.g. "99999999999999")
941 *
942 * %XTF_ONE_ACTION: two mutually exclusive actions have been specified
943 * @p1:		module name
944 *
945 * Displays an error message and exits the program.
946 */
947void xtables_param_act(unsigned int status, const char *p1, ...)
948{
949	const char *p2, *p3;
950	va_list args;
951	bool b;
952
953	va_start(args, p1);
954
955	switch (status) {
956	case XTF_ONLY_ONCE:
957		p2 = va_arg(args, const char *);
958		b  = va_arg(args, unsigned int);
959		if (!b)
960			return;
961		xt_params->exit_err(PARAMETER_PROBLEM,
962		           "%s: \"%s\" option may only be specified once",
963		           p1, p2);
964		break;
965	case XTF_NO_INVERT:
966		p2 = va_arg(args, const char *);
967		b  = va_arg(args, unsigned int);
968		if (!b)
969			return;
970		xt_params->exit_err(PARAMETER_PROBLEM,
971		           "%s: \"%s\" option cannot be inverted", p1, p2);
972		break;
973	case XTF_BAD_VALUE:
974		p2 = va_arg(args, const char *);
975		p3 = va_arg(args, const char *);
976		xt_params->exit_err(PARAMETER_PROBLEM,
977		           "%s: Bad value for \"%s\" option: \"%s\"",
978		           p1, p2, p3);
979		break;
980	case XTF_ONE_ACTION:
981		b = va_arg(args, unsigned int);
982		if (!b)
983			return;
984		xt_params->exit_err(PARAMETER_PROBLEM,
985		           "%s: At most one action is possible", p1);
986		break;
987	default:
988		xt_params->exit_err(status, p1, args);
989		break;
990	}
991
992	va_end(args);
993}
994
995const char *xtables_ipaddr_to_numeric(const struct in_addr *addrp)
996{
997	static char buf[20];
998	const unsigned char *bytep = (const void *)&addrp->s_addr;
999
1000	sprintf(buf, "%u.%u.%u.%u", bytep[0], bytep[1], bytep[2], bytep[3]);
1001	return buf;
1002}
1003
1004static const char *ipaddr_to_host(const struct in_addr *addr)
1005{
1006	struct hostent *host;
1007
1008	host = gethostbyaddr(addr, sizeof(struct in_addr), AF_INET);
1009	if (host == NULL)
1010		return NULL;
1011
1012	return host->h_name;
1013}
1014
1015static const char *ipaddr_to_network(const struct in_addr *addr)
1016{
1017	struct netent *net;
1018
1019	if ((net = getnetbyaddr(ntohl(addr->s_addr), AF_INET)) != NULL)
1020		return net->n_name;
1021
1022	return NULL;
1023}
1024
1025const char *xtables_ipaddr_to_anyname(const struct in_addr *addr)
1026{
1027	const char *name;
1028
1029	if ((name = ipaddr_to_host(addr)) != NULL ||
1030	    (name = ipaddr_to_network(addr)) != NULL)
1031		return name;
1032
1033	return xtables_ipaddr_to_numeric(addr);
1034}
1035
1036const char *xtables_ipmask_to_numeric(const struct in_addr *mask)
1037{
1038	static char buf[20];
1039	uint32_t maskaddr, bits;
1040	int i;
1041
1042	maskaddr = ntohl(mask->s_addr);
1043
1044	if (maskaddr == 0xFFFFFFFFL)
1045		/* we don't want to see "/32" */
1046		return "";
1047
1048	i = 32;
1049	bits = 0xFFFFFFFEL;
1050	while (--i >= 0 && maskaddr != bits)
1051		bits <<= 1;
1052	if (i >= 0)
1053		sprintf(buf, "/%d", i);
1054	else
1055		/* mask was not a decent combination of 1's and 0's */
1056		sprintf(buf, "/%s", xtables_ipaddr_to_numeric(mask));
1057
1058	return buf;
1059}
1060
1061static struct in_addr *__numeric_to_ipaddr(const char *dotted, bool is_mask)
1062{
1063	static struct in_addr addr;
1064	unsigned char *addrp;
1065	unsigned int onebyte;
1066	char buf[20], *p, *q;
1067	int i;
1068
1069	/* copy dotted string, because we need to modify it */
1070	strncpy(buf, dotted, sizeof(buf) - 1);
1071	buf[sizeof(buf) - 1] = '\0';
1072	addrp = (void *)&addr.s_addr;
1073
1074	p = buf;
1075	for (i = 0; i < 3; ++i) {
1076		if ((q = strchr(p, '.')) == NULL) {
1077			if (is_mask)
1078				return NULL;
1079
1080			/* autocomplete, this is a network address */
1081			if (!xtables_strtoui(p, NULL, &onebyte, 0, UINT8_MAX))
1082				return NULL;
1083
1084			addrp[i] = onebyte;
1085			while (i < 3)
1086				addrp[++i] = 0;
1087
1088			return &addr;
1089		}
1090
1091		*q = '\0';
1092		if (!xtables_strtoui(p, NULL, &onebyte, 0, UINT8_MAX))
1093			return NULL;
1094
1095		addrp[i] = onebyte;
1096		p = q + 1;
1097	}
1098
1099	/* we have checked 3 bytes, now we check the last one */
1100	if (!xtables_strtoui(p, NULL, &onebyte, 0, UINT8_MAX))
1101		return NULL;
1102
1103	addrp[3] = onebyte;
1104	return &addr;
1105}
1106
1107struct in_addr *xtables_numeric_to_ipaddr(const char *dotted)
1108{
1109	return __numeric_to_ipaddr(dotted, false);
1110}
1111
1112struct in_addr *xtables_numeric_to_ipmask(const char *dotted)
1113{
1114	return __numeric_to_ipaddr(dotted, true);
1115}
1116
1117static struct in_addr *network_to_ipaddr(const char *name)
1118{
1119	static struct in_addr addr;
1120	struct netent *net;
1121
1122	if ((net = getnetbyname(name)) != NULL) {
1123		if (net->n_addrtype != AF_INET)
1124			return NULL;
1125		addr.s_addr = htonl(net->n_net);
1126		return &addr;
1127	}
1128
1129	return NULL;
1130}
1131
1132static struct in_addr *host_to_ipaddr(const char *name, unsigned int *naddr)
1133{
1134	struct hostent *host;
1135	struct in_addr *addr;
1136	unsigned int i;
1137
1138	*naddr = 0;
1139	if ((host = gethostbyname(name)) != NULL) {
1140		if (host->h_addrtype != AF_INET ||
1141		    host->h_length != sizeof(struct in_addr))
1142			return NULL;
1143
1144		while (host->h_addr_list[*naddr] != NULL)
1145			++*naddr;
1146		addr = xtables_calloc(*naddr, sizeof(struct in_addr) * *naddr);
1147		for (i = 0; i < *naddr; i++)
1148			memcpy(&addr[i], host->h_addr_list[i],
1149			       sizeof(struct in_addr));
1150		return addr;
1151	}
1152
1153	return NULL;
1154}
1155
1156static struct in_addr *
1157ipparse_hostnetwork(const char *name, unsigned int *naddrs)
1158{
1159	struct in_addr *addrptmp, *addrp;
1160
1161	if ((addrptmp = xtables_numeric_to_ipaddr(name)) != NULL ||
1162	    (addrptmp = network_to_ipaddr(name)) != NULL) {
1163		addrp = xtables_malloc(sizeof(struct in_addr));
1164		memcpy(addrp, addrptmp, sizeof(*addrp));
1165		*naddrs = 1;
1166		return addrp;
1167	}
1168	if ((addrptmp = host_to_ipaddr(name, naddrs)) != NULL)
1169		return addrptmp;
1170
1171	xt_params->exit_err(PARAMETER_PROBLEM, "host/network `%s' not found", name);
1172}
1173
1174static struct in_addr *parse_ipmask(const char *mask)
1175{
1176	static struct in_addr maskaddr;
1177	struct in_addr *addrp;
1178	unsigned int bits;
1179
1180	if (mask == NULL) {
1181		/* no mask at all defaults to 32 bits */
1182		maskaddr.s_addr = 0xFFFFFFFF;
1183		return &maskaddr;
1184	}
1185	if ((addrp = xtables_numeric_to_ipmask(mask)) != NULL)
1186		/* dotted_to_addr already returns a network byte order addr */
1187		return addrp;
1188	if (!xtables_strtoui(mask, NULL, &bits, 0, 32))
1189		xt_params->exit_err(PARAMETER_PROBLEM,
1190			   "invalid mask `%s' specified", mask);
1191	if (bits != 0) {
1192		maskaddr.s_addr = htonl(0xFFFFFFFF << (32 - bits));
1193		return &maskaddr;
1194	}
1195
1196	maskaddr.s_addr = 0U;
1197	return &maskaddr;
1198}
1199
1200void xtables_ipparse_multiple(const char *name, struct in_addr **addrpp,
1201                              struct in_addr **maskpp, unsigned int *naddrs)
1202{
1203	struct in_addr *addrp;
1204	char buf[256], *p;
1205	unsigned int len, i, j, n, count = 1;
1206	const char *loop = name;
1207
1208	while ((loop = strchr(loop, ',')) != NULL) {
1209		++count;
1210		++loop; /* skip ',' */
1211	}
1212
1213	*addrpp = xtables_malloc(sizeof(struct in_addr) * count);
1214	*maskpp = xtables_malloc(sizeof(struct in_addr) * count);
1215
1216	loop = name;
1217
1218	for (i = 0; i < count; ++i) {
1219		if (loop == NULL)
1220			break;
1221		if (*loop == ',')
1222			++loop;
1223		if (*loop == '\0')
1224			break;
1225		p = strchr(loop, ',');
1226		if (p != NULL)
1227			len = p - loop;
1228		else
1229			len = strlen(loop);
1230		if (len == 0 || sizeof(buf) - 1 < len)
1231			break;
1232
1233		strncpy(buf, loop, len);
1234		buf[len] = '\0';
1235		loop += len;
1236		if ((p = strrchr(buf, '/')) != NULL) {
1237			*p = '\0';
1238			addrp = parse_ipmask(p + 1);
1239		} else {
1240			addrp = parse_ipmask(NULL);
1241		}
1242		memcpy(*maskpp + i, addrp, sizeof(*addrp));
1243
1244		/* if a null mask is given, the name is ignored, like in "any/0" */
1245		if ((*maskpp + i)->s_addr == 0)
1246			/*
1247			 * A bit pointless to process multiple addresses
1248			 * in this case...
1249			 */
1250			strcpy(buf, "0.0.0.0");
1251
1252		addrp = ipparse_hostnetwork(buf, &n);
1253		if (n > 1) {
1254			count += n - 1;
1255			*addrpp = xtables_realloc(*addrpp,
1256			          sizeof(struct in_addr) * count);
1257			*maskpp = xtables_realloc(*maskpp,
1258			          sizeof(struct in_addr) * count);
1259			for (j = 0; j < n; ++j)
1260				/* for each new addr */
1261				memcpy(*addrpp + i + j, addrp + j,
1262				       sizeof(*addrp));
1263			for (j = 1; j < n; ++j)
1264				/* for each new mask */
1265				memcpy(*maskpp + i + j, *maskpp + i,
1266				       sizeof(*addrp));
1267			i += n - 1;
1268		} else {
1269			memcpy(*addrpp + i, addrp, sizeof(*addrp));
1270		}
1271		/* free what ipparse_hostnetwork had allocated: */
1272		free(addrp);
1273	}
1274	*naddrs = count;
1275	for (i = 0; i < n; ++i)
1276		(*addrpp+i)->s_addr &= (*maskpp+i)->s_addr;
1277}
1278
1279
1280/**
1281 * xtables_ipparse_any - transform arbitrary name to in_addr
1282 *
1283 * Possible inputs (pseudo regex):
1284 * 	m{^($hostname|$networkname|$ipaddr)(/$mask)?}
1285 * "1.2.3.4/5", "1.2.3.4", "hostname", "networkname"
1286 */
1287void xtables_ipparse_any(const char *name, struct in_addr **addrpp,
1288                         struct in_addr *maskp, unsigned int *naddrs)
1289{
1290	unsigned int i, j, k, n;
1291	struct in_addr *addrp;
1292	char buf[256], *p;
1293
1294	strncpy(buf, name, sizeof(buf) - 1);
1295	buf[sizeof(buf) - 1] = '\0';
1296	if ((p = strrchr(buf, '/')) != NULL) {
1297		*p = '\0';
1298		addrp = parse_ipmask(p + 1);
1299	} else {
1300		addrp = parse_ipmask(NULL);
1301	}
1302	memcpy(maskp, addrp, sizeof(*maskp));
1303
1304	/* if a null mask is given, the name is ignored, like in "any/0" */
1305	if (maskp->s_addr == 0U)
1306		strcpy(buf, "0.0.0.0");
1307
1308	addrp = *addrpp = ipparse_hostnetwork(buf, naddrs);
1309	n = *naddrs;
1310	for (i = 0, j = 0; i < n; ++i) {
1311		addrp[j++].s_addr &= maskp->s_addr;
1312		for (k = 0; k < j - 1; ++k)
1313			if (addrp[k].s_addr == addrp[j-1].s_addr) {
1314				--*naddrs;
1315				--j;
1316				break;
1317			}
1318	}
1319}
1320
1321const char *xtables_ip6addr_to_numeric(const struct in6_addr *addrp)
1322{
1323	/* 0000:0000:0000:0000:0000:000.000.000.000
1324	 * 0000:0000:0000:0000:0000:0000:0000:0000 */
1325	static char buf[50+1];
1326	return inet_ntop(AF_INET6, addrp, buf, sizeof(buf));
1327}
1328
1329static const char *ip6addr_to_host(const struct in6_addr *addr)
1330{
1331	static char hostname[NI_MAXHOST];
1332	struct sockaddr_in6 saddr;
1333	int err;
1334
1335	memset(&saddr, 0, sizeof(struct sockaddr_in6));
1336	memcpy(&saddr.sin6_addr, addr, sizeof(*addr));
1337	saddr.sin6_family = AF_INET6;
1338
1339	err = getnameinfo((const void *)&saddr, sizeof(struct sockaddr_in6),
1340	      hostname, sizeof(hostname) - 1, NULL, 0, 0);
1341	if (err != 0) {
1342#ifdef DEBUG
1343		fprintf(stderr,"IP2Name: %s\n",gai_strerror(err));
1344#endif
1345		return NULL;
1346	}
1347
1348#ifdef DEBUG
1349	fprintf (stderr, "\naddr2host: %s\n", hostname);
1350#endif
1351	return hostname;
1352}
1353
1354const char *xtables_ip6addr_to_anyname(const struct in6_addr *addr)
1355{
1356	const char *name;
1357
1358	if ((name = ip6addr_to_host(addr)) != NULL)
1359		return name;
1360
1361	return xtables_ip6addr_to_numeric(addr);
1362}
1363
1364static int ip6addr_prefix_length(const struct in6_addr *k)
1365{
1366	unsigned int bits = 0;
1367	uint32_t a, b, c, d;
1368
1369	a = ntohl(k->s6_addr32[0]);
1370	b = ntohl(k->s6_addr32[1]);
1371	c = ntohl(k->s6_addr32[2]);
1372	d = ntohl(k->s6_addr32[3]);
1373	while (a & 0x80000000U) {
1374		++bits;
1375		a <<= 1;
1376		a  |= (b >> 31) & 1;
1377		b <<= 1;
1378		b  |= (c >> 31) & 1;
1379		c <<= 1;
1380		c  |= (d >> 31) & 1;
1381		d <<= 1;
1382	}
1383	if (a != 0 || b != 0 || c != 0 || d != 0)
1384		return -1;
1385	return bits;
1386}
1387
1388const char *xtables_ip6mask_to_numeric(const struct in6_addr *addrp)
1389{
1390	static char buf[50+2];
1391	int l = ip6addr_prefix_length(addrp);
1392
1393	if (l == -1) {
1394		strcpy(buf, "/");
1395		strcat(buf, xtables_ip6addr_to_numeric(addrp));
1396		return buf;
1397	}
1398	sprintf(buf, "/%d", l);
1399	return buf;
1400}
1401
1402struct in6_addr *xtables_numeric_to_ip6addr(const char *num)
1403{
1404	static struct in6_addr ap;
1405	int err;
1406
1407	if ((err = inet_pton(AF_INET6, num, &ap)) == 1)
1408		return &ap;
1409#ifdef DEBUG
1410	fprintf(stderr, "\nnumeric2addr: %d\n", err);
1411#endif
1412	return NULL;
1413}
1414
1415static struct in6_addr *
1416host_to_ip6addr(const char *name, unsigned int *naddr)
1417{
1418	static struct in6_addr *addr;
1419	struct addrinfo hints;
1420	struct addrinfo *res;
1421	int err;
1422
1423	memset(&hints, 0, sizeof(hints));
1424	hints.ai_flags    = AI_CANONNAME;
1425	hints.ai_family   = AF_INET6;
1426	hints.ai_socktype = SOCK_RAW;
1427	hints.ai_protocol = IPPROTO_IPV6;
1428	hints.ai_next     = NULL;
1429
1430	*naddr = 0;
1431	if ((err = getaddrinfo(name, NULL, &hints, &res)) != 0) {
1432#ifdef DEBUG
1433		fprintf(stderr,"Name2IP: %s\n",gai_strerror(err));
1434#endif
1435		return NULL;
1436	} else {
1437		if (res->ai_family != AF_INET6 ||
1438		    res->ai_addrlen != sizeof(struct sockaddr_in6))
1439			return NULL;
1440
1441#ifdef DEBUG
1442		fprintf(stderr, "resolved: len=%d  %s ", res->ai_addrlen,
1443		        xtables_ip6addr_to_numeric(&((struct sockaddr_in6 *)res->ai_addr)->sin6_addr));
1444#endif
1445		/* Get the first element of the address-chain */
1446		addr = xtables_malloc(sizeof(struct in6_addr));
1447		memcpy(addr, &((const struct sockaddr_in6 *)res->ai_addr)->sin6_addr,
1448		       sizeof(struct in6_addr));
1449		freeaddrinfo(res);
1450		*naddr = 1;
1451		return addr;
1452	}
1453
1454	return NULL;
1455}
1456
1457static struct in6_addr *network_to_ip6addr(const char *name)
1458{
1459	/*	abort();*/
1460	/* TODO: not implemented yet, but the exception breaks the
1461	 *       name resolvation */
1462	return NULL;
1463}
1464
1465static struct in6_addr *
1466ip6parse_hostnetwork(const char *name, unsigned int *naddrs)
1467{
1468	struct in6_addr *addrp, *addrptmp;
1469
1470	if ((addrptmp = xtables_numeric_to_ip6addr(name)) != NULL ||
1471	    (addrptmp = network_to_ip6addr(name)) != NULL) {
1472		addrp = xtables_malloc(sizeof(struct in6_addr));
1473		memcpy(addrp, addrptmp, sizeof(*addrp));
1474		*naddrs = 1;
1475		return addrp;
1476	}
1477	if ((addrp = host_to_ip6addr(name, naddrs)) != NULL)
1478		return addrp;
1479
1480	xt_params->exit_err(PARAMETER_PROBLEM, "host/network `%s' not found", name);
1481}
1482
1483static struct in6_addr *parse_ip6mask(char *mask)
1484{
1485	static struct in6_addr maskaddr;
1486	struct in6_addr *addrp;
1487	unsigned int bits;
1488
1489	if (mask == NULL) {
1490		/* no mask at all defaults to 128 bits */
1491		memset(&maskaddr, 0xff, sizeof maskaddr);
1492		return &maskaddr;
1493	}
1494	if ((addrp = xtables_numeric_to_ip6addr(mask)) != NULL)
1495		return addrp;
1496	if (!xtables_strtoui(mask, NULL, &bits, 0, 128))
1497		xt_params->exit_err(PARAMETER_PROBLEM,
1498			   "invalid mask `%s' specified", mask);
1499	if (bits != 0) {
1500		char *p = (void *)&maskaddr;
1501		memset(p, 0xff, bits / 8);
1502		memset(p + (bits / 8) + 1, 0, (128 - bits) / 8);
1503		p[bits/8] = 0xff << (8 - (bits & 7));
1504		return &maskaddr;
1505	}
1506
1507	memset(&maskaddr, 0, sizeof(maskaddr));
1508	return &maskaddr;
1509}
1510
1511void
1512xtables_ip6parse_multiple(const char *name, struct in6_addr **addrpp,
1513		      struct in6_addr **maskpp, unsigned int *naddrs)
1514{
1515	static const struct in6_addr zero_addr;
1516	struct in6_addr *addrp;
1517	char buf[256], *p;
1518	unsigned int len, i, j, n, count = 1;
1519	const char *loop = name;
1520
1521	while ((loop = strchr(loop, ',')) != NULL) {
1522		++count;
1523		++loop; /* skip ',' */
1524	}
1525
1526	*addrpp = xtables_malloc(sizeof(struct in6_addr) * count);
1527	*maskpp = xtables_malloc(sizeof(struct in6_addr) * count);
1528
1529	loop = name;
1530
1531	for (i = 0; i < count /*NB: count can grow*/; ++i) {
1532		if (loop == NULL)
1533			break;
1534		if (*loop == ',')
1535			++loop;
1536		if (*loop == '\0')
1537			break;
1538		p = strchr(loop, ',');
1539		if (p != NULL)
1540			len = p - loop;
1541		else
1542			len = strlen(loop);
1543		if (len == 0 || sizeof(buf) - 1 < len)
1544			break;
1545
1546		strncpy(buf, loop, len);
1547		buf[len] = '\0';
1548		loop += len;
1549		if ((p = strrchr(buf, '/')) != NULL) {
1550			*p = '\0';
1551			addrp = parse_ip6mask(p + 1);
1552		} else {
1553			addrp = parse_ip6mask(NULL);
1554		}
1555		memcpy(*maskpp + i, addrp, sizeof(*addrp));
1556
1557		/* if a null mask is given, the name is ignored, like in "any/0" */
1558		if (memcmp(*maskpp + i, &zero_addr, sizeof(zero_addr)) == 0)
1559			strcpy(buf, "::");
1560
1561		addrp = ip6parse_hostnetwork(buf, &n);
1562		/* ip6parse_hostnetwork only ever returns one IP
1563		address (it exits if the resolution fails).
1564		Therefore, n will always be 1 here.  Leaving the
1565		code below in anyway in case ip6parse_hostnetwork
1566		is improved some day to behave like
1567		ipparse_hostnetwork: */
1568		if (n > 1) {
1569			count += n - 1;
1570			*addrpp = xtables_realloc(*addrpp,
1571			          sizeof(struct in6_addr) * count);
1572			*maskpp = xtables_realloc(*maskpp,
1573			          sizeof(struct in6_addr) * count);
1574			for (j = 0; j < n; ++j)
1575				/* for each new addr */
1576				memcpy(*addrpp + i + j, addrp + j,
1577				       sizeof(*addrp));
1578			for (j = 1; j < n; ++j)
1579				/* for each new mask */
1580				memcpy(*maskpp + i + j, *maskpp + i,
1581				       sizeof(*addrp));
1582			i += n - 1;
1583		} else {
1584			memcpy(*addrpp + i, addrp, sizeof(*addrp));
1585		}
1586		/* free what ip6parse_hostnetwork had allocated: */
1587		free(addrp);
1588	}
1589	*naddrs = count;
1590	for (i = 0; i < n; ++i)
1591		for (j = 0; j < 4; ++j)
1592			(*addrpp+i)->s6_addr32[j] &= (*maskpp+i)->s6_addr32[j];
1593}
1594
1595void xtables_ip6parse_any(const char *name, struct in6_addr **addrpp,
1596                          struct in6_addr *maskp, unsigned int *naddrs)
1597{
1598	static const struct in6_addr zero_addr;
1599	struct in6_addr *addrp;
1600	unsigned int i, j, k, n;
1601	char buf[256], *p;
1602
1603	strncpy(buf, name, sizeof(buf) - 1);
1604	buf[sizeof(buf)-1] = '\0';
1605	if ((p = strrchr(buf, '/')) != NULL) {
1606		*p = '\0';
1607		addrp = parse_ip6mask(p + 1);
1608	} else {
1609		addrp = parse_ip6mask(NULL);
1610	}
1611	memcpy(maskp, addrp, sizeof(*maskp));
1612
1613	/* if a null mask is given, the name is ignored, like in "any/0" */
1614	if (memcmp(maskp, &zero_addr, sizeof(zero_addr)) == 0)
1615		strcpy(buf, "::");
1616
1617	addrp = *addrpp = ip6parse_hostnetwork(buf, naddrs);
1618	n = *naddrs;
1619	for (i = 0, j = 0; i < n; ++i) {
1620		for (k = 0; k < 4; ++k)
1621			addrp[j].s6_addr32[k] &= maskp->s6_addr32[k];
1622		++j;
1623		for (k = 0; k < j - 1; ++k)
1624			if (IN6_ARE_ADDR_EQUAL(&addrp[k], &addrp[j - 1])) {
1625				--*naddrs;
1626				--j;
1627				break;
1628			}
1629	}
1630}
1631
1632void xtables_save_string(const char *value)
1633{
1634	static const char no_quote_chars[] = "_-0123456789"
1635		"abcdefghijklmnopqrstuvwxyz"
1636		"ABCDEFGHIJKLMNOPQRSTUVWXYZ";
1637	static const char escape_chars[] = "\"\\'";
1638	size_t length;
1639	const char *p;
1640
1641	length = strcspn(value, no_quote_chars);
1642	if (length > 0 && value[length] == 0) {
1643		/* no quoting required */
1644		putchar(' ');
1645		fputs(value, stdout);
1646	} else {
1647		/* there is at least one dangerous character in the
1648		   value, which we have to quote.  Write double quotes
1649		   around the value and escape special characters with
1650		   a backslash */
1651		printf(" \"");
1652
1653		for (p = strpbrk(value, escape_chars); p != NULL;
1654		     p = strpbrk(value, escape_chars)) {
1655			if (p > value)
1656				fwrite(value, 1, p - value, stdout);
1657			putchar('\\');
1658			putchar(*p);
1659			value = p + 1;
1660		}
1661
1662		/* print the rest and finish the double quoted
1663		   string */
1664		fputs(value, stdout);
1665		putchar('\"');
1666	}
1667}
1668
1669/**
1670 * Check for option-intrapositional negation.
1671 * Do not use in new code.
1672 */
1673int xtables_check_inverse(const char option[], int *invert,
1674			  int *my_optind, int argc, char **argv)
1675{
1676	if (option == NULL || strcmp(option, "!") != 0)
1677		return false;
1678
1679	fprintf(stderr, "Using intrapositioned negation "
1680	        "(`--option ! this`) is deprecated in favor of "
1681	        "extrapositioned (`! --option this`).\n");
1682
1683	if (*invert)
1684		xt_params->exit_err(PARAMETER_PROBLEM,
1685			   "Multiple `!' flags not allowed");
1686	*invert = true;
1687	if (my_optind != NULL) {
1688		optarg = argv[*my_optind];
1689		++*my_optind;
1690		if (argc && *my_optind > argc)
1691			xt_params->exit_err(PARAMETER_PROBLEM,
1692				   "no argument following `!'");
1693	}
1694
1695	return true;
1696}
1697
1698const struct xtables_pprot xtables_chain_protos[] = {
1699	{"tcp",       IPPROTO_TCP},
1700	{"sctp",      IPPROTO_SCTP},
1701	{"udp",       IPPROTO_UDP},
1702	{"udplite",   IPPROTO_UDPLITE},
1703	{"icmp",      IPPROTO_ICMP},
1704	{"icmpv6",    IPPROTO_ICMPV6},
1705	{"ipv6-icmp", IPPROTO_ICMPV6},
1706	{"esp",       IPPROTO_ESP},
1707	{"ah",        IPPROTO_AH},
1708	{"ipv6-mh",   IPPROTO_MH},
1709	{"mh",        IPPROTO_MH},
1710	{"all",       0},
1711	{NULL},
1712};
1713
1714uint16_t
1715xtables_parse_protocol(const char *s)
1716{
1717	unsigned int proto;
1718
1719	if (!xtables_strtoui(s, NULL, &proto, 0, UINT8_MAX)) {
1720		struct protoent *pent;
1721
1722		/* first deal with the special case of 'all' to prevent
1723		 * people from being able to redefine 'all' in nsswitch
1724		 * and/or provoke expensive [not working] ldap/nis/...
1725		 * lookups */
1726		if (!strcmp(s, "all"))
1727			return 0;
1728
1729		if ((pent = getprotobyname(s)))
1730			proto = pent->p_proto;
1731		else {
1732			unsigned int i;
1733			for (i = 0; i < ARRAY_SIZE(xtables_chain_protos); ++i) {
1734				if (xtables_chain_protos[i].name == NULL)
1735					continue;
1736
1737				if (strcmp(s, xtables_chain_protos[i].name) == 0) {
1738					proto = xtables_chain_protos[i].num;
1739					break;
1740				}
1741			}
1742			if (i == ARRAY_SIZE(xtables_chain_protos))
1743				xt_params->exit_err(PARAMETER_PROBLEM,
1744					   "unknown protocol `%s' specified",
1745					   s);
1746		}
1747	}
1748
1749	return proto;
1750}
1751