xtables.c revision a41545ca7cde43e0ba53260ba74bd9bf74025a68
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 <libiptc/libxtc.h>
36
37#ifndef NO_SHARED_LIBS
38#include <dlfcn.h>
39#endif
40
41#define NPROTO	255
42
43#ifndef PROC_SYS_MODPROBE
44#define PROC_SYS_MODPROBE "/proc/sys/kernel/modprobe"
45#endif
46
47/**
48 * Program will set this to its own name.
49 */
50const char *xtables_program_name;
51
52/* Search path for Xtables .so files */
53static const char *xtables_libdir;
54
55/* the path to command to load kernel module */
56const char *xtables_modprobe_program;
57
58/* Keeping track of external matches and targets: linked lists.  */
59struct xtables_match *xtables_matches;
60struct xtables_target *xtables_targets;
61
62void xtables_init(void)
63{
64	xtables_libdir = getenv("XTABLES_LIBDIR");
65	if (xtables_libdir != NULL)
66		return;
67	xtables_libdir = getenv("IPTABLES_LIB_DIR");
68	if (xtables_libdir != NULL) {
69		fprintf(stderr, "IPTABLES_LIB_DIR is deprecated, "
70		        "use XTABLES_LIBDIR.\n");
71		return;
72	}
73	xtables_libdir = XTABLES_LIBDIR;
74}
75
76/**
77 * xtables_*alloc - wrappers that exit on failure
78 */
79void *xtables_calloc(size_t count, size_t size)
80{
81	void *p;
82
83	if ((p = calloc(count, size)) == NULL) {
84		perror("ip[6]tables: calloc failed");
85		exit(1);
86	}
87
88	return p;
89}
90
91void *xtables_malloc(size_t size)
92{
93	void *p;
94
95	if ((p = malloc(size)) == NULL) {
96		perror("ip[6]tables: malloc failed");
97		exit(1);
98	}
99
100	return p;
101}
102
103static char *get_modprobe(void)
104{
105	int procfile;
106	char *ret;
107
108#define PROCFILE_BUFSIZ	1024
109	procfile = open(PROC_SYS_MODPROBE, O_RDONLY);
110	if (procfile < 0)
111		return NULL;
112
113	ret = (char *) malloc(PROCFILE_BUFSIZ);
114	if (ret) {
115		memset(ret, 0, PROCFILE_BUFSIZ);
116		switch (read(procfile, ret, PROCFILE_BUFSIZ)) {
117		case -1: goto fail;
118		case PROCFILE_BUFSIZ: goto fail; /* Partial read.  Wierd */
119		}
120		if (ret[strlen(ret)-1]=='\n')
121			ret[strlen(ret)-1]=0;
122		close(procfile);
123		return ret;
124	}
125 fail:
126	free(ret);
127	close(procfile);
128	return NULL;
129}
130
131int xtables_insmod(const char *modname, const char *modprobe, bool quiet)
132{
133	char *buf = NULL;
134	char *argv[4];
135	int status;
136
137	/* If they don't explicitly set it, read out of kernel */
138	if (!modprobe) {
139		buf = get_modprobe();
140		if (!buf)
141			return -1;
142		modprobe = buf;
143	}
144
145	switch (fork()) {
146	case 0:
147		argv[0] = (char *)modprobe;
148		argv[1] = (char *)modname;
149		if (quiet) {
150			argv[2] = "-q";
151			argv[3] = NULL;
152		} else {
153			argv[2] = NULL;
154			argv[3] = NULL;
155		}
156		execv(argv[0], argv);
157
158		/* not usually reached */
159		exit(1);
160	case -1:
161		return -1;
162
163	default: /* parent */
164		wait(&status);
165	}
166
167	free(buf);
168	if (WIFEXITED(status) && WEXITSTATUS(status) == 0)
169		return 0;
170	return -1;
171}
172
173int xtables_load_ko(const char *modprobe, bool quiet)
174{
175	static bool loaded = false;
176	static int ret = -1;
177
178	if (!loaded) {
179		ret = xtables_insmod(afinfo.kmod, modprobe, quiet);
180		loaded = (ret == 0);
181	}
182
183	return ret;
184}
185
186/**
187 * xtables_strtou{i,l} - string to number conversion
188 * @s:	input string
189 * @end:	like strtoul's "end" pointer
190 * @value:	pointer for result
191 * @min:	minimum accepted value
192 * @max:	maximum accepted value
193 *
194 * If @end is NULL, we assume the caller wants a "strict strtoul", and hence
195 * "15a" is rejected.
196 * In either case, the value obtained is compared for min-max compliance.
197 * Base is always 0, i.e. autodetect depending on @s.
198 *
199 * Returns true/false whether number was accepted. On failure, *value has
200 * undefined contents.
201 */
202bool xtables_strtoul(const char *s, char **end, unsigned long *value,
203                     unsigned long min, unsigned long max)
204{
205	unsigned long v;
206	char *my_end;
207
208	errno = 0;
209	v = strtoul(s, &my_end, 0);
210
211	if (my_end == s)
212		return false;
213	if (end != NULL)
214		*end = my_end;
215
216	if (errno != ERANGE && min <= v && (max == 0 || v <= max)) {
217		if (value != NULL)
218			*value = v;
219		if (end == NULL)
220			return *my_end == '\0';
221		return true;
222	}
223
224	return false;
225}
226
227bool xtables_strtoui(const char *s, char **end, unsigned int *value,
228                     unsigned int min, unsigned int max)
229{
230	unsigned long v;
231	bool ret;
232
233	ret = xtables_strtoul(s, end, &v, min, max);
234	if (value != NULL)
235		*value = v;
236	return ret;
237}
238
239int service_to_port(const char *name, const char *proto)
240{
241	struct servent *service;
242
243	if ((service = getservbyname(name, proto)) != NULL)
244		return ntohs((unsigned short) service->s_port);
245
246	return -1;
247}
248
249u_int16_t parse_port(const char *port, const char *proto)
250{
251	unsigned int portnum;
252
253	if (xtables_strtoui(port, NULL, &portnum, 0, UINT16_MAX) ||
254	    (portnum = service_to_port(port, proto)) != (unsigned)-1)
255		return portnum;
256
257	exit_error(PARAMETER_PROBLEM,
258		   "invalid port/service `%s' specified", port);
259}
260
261void parse_interface(const char *arg, char *vianame, unsigned char *mask)
262{
263	int vialen = strlen(arg);
264	unsigned int i;
265
266	memset(mask, 0, IFNAMSIZ);
267	memset(vianame, 0, IFNAMSIZ);
268
269	if (vialen + 1 > IFNAMSIZ)
270		exit_error(PARAMETER_PROBLEM,
271			   "interface name `%s' must be shorter than IFNAMSIZ"
272			   " (%i)", arg, IFNAMSIZ-1);
273
274	strcpy(vianame, arg);
275	if ((vialen == 0) || (vialen == 1 && vianame[0] == '+'))
276		memset(mask, 0, IFNAMSIZ);
277	else if (vianame[vialen - 1] == '+') {
278		memset(mask, 0xFF, vialen - 1);
279		memset(mask + vialen - 1, 0, IFNAMSIZ - vialen + 1);
280		/* Don't remove `+' here! -HW */
281	} else {
282		/* Include nul-terminator in match */
283		memset(mask, 0xFF, vialen + 1);
284		memset(mask + vialen + 1, 0, IFNAMSIZ - vialen - 1);
285		for (i = 0; vianame[i]; i++) {
286			if (vianame[i] == ':' ||
287			    vianame[i] == '!' ||
288			    vianame[i] == '*') {
289				fprintf(stderr,
290					"Warning: weird character in interface"
291					" `%s' (No aliases, :, ! or *).\n",
292					vianame);
293				break;
294			}
295		}
296	}
297}
298
299#ifndef NO_SHARED_LIBS
300static void *load_extension(const char *search_path, const char *prefix,
301    const char *name, bool is_target)
302{
303	const char *dir = search_path, *next;
304	void *ptr = NULL;
305	struct stat sb;
306	char path[256];
307
308	do {
309		next = strchr(dir, ':');
310		if (next == NULL)
311			next = dir + strlen(dir);
312		snprintf(path, sizeof(path), "%.*s/libxt_%s.so",
313		         (unsigned int)(next - dir), dir, name);
314
315		if (dlopen(path, RTLD_NOW) != NULL) {
316			/* Found library.  If it didn't register itself,
317			   maybe they specified target as match. */
318			if (is_target)
319				ptr = xtables_find_target(name, XTF_DONT_LOAD);
320			else
321				ptr = xtables_find_match(name,
322				      XTF_DONT_LOAD, NULL);
323		} else if (stat(path, &sb) == 0) {
324			fprintf(stderr, "%s: %s\n", path, dlerror());
325		}
326
327		if (ptr != NULL)
328			return ptr;
329
330		snprintf(path, sizeof(path), "%.*s/%s%s.so",
331		         (unsigned int)(next - dir), dir, prefix, name);
332		if (dlopen(path, RTLD_NOW) != NULL) {
333			if (is_target)
334				ptr = xtables_find_target(name, XTF_DONT_LOAD);
335			else
336				ptr = xtables_find_match(name,
337				      XTF_DONT_LOAD, NULL);
338		} else if (stat(path, &sb) == 0) {
339			fprintf(stderr, "%s: %s\n", path, dlerror());
340		}
341
342		if (ptr != NULL)
343			return ptr;
344
345		dir = next + 1;
346	} while (*next != '\0');
347
348	return NULL;
349}
350#endif
351
352struct xtables_match *
353xtables_find_match(const char *name, enum xtables_tryload tryload,
354		   struct xtables_rule_match **matches)
355{
356	struct xtables_match *ptr;
357	const char *icmp6 = "icmp6";
358
359	/* This is ugly as hell. Nonetheless, there is no way of changing
360	 * this without hurting backwards compatibility */
361	if ( (strcmp(name,"icmpv6") == 0) ||
362	     (strcmp(name,"ipv6-icmp") == 0) ||
363	     (strcmp(name,"icmp6") == 0) )
364		name = icmp6;
365
366	for (ptr = xtables_matches; ptr; ptr = ptr->next) {
367		if (strcmp(name, ptr->name) == 0) {
368			struct xtables_match *clone;
369
370			/* First match of this type: */
371			if (ptr->m == NULL)
372				break;
373
374			/* Second and subsequent clones */
375			clone = xtables_malloc(sizeof(struct xtables_match));
376			memcpy(clone, ptr, sizeof(struct xtables_match));
377			clone->mflags = 0;
378			/* This is a clone: */
379			clone->next = clone;
380
381			ptr = clone;
382			break;
383		}
384	}
385
386#ifndef NO_SHARED_LIBS
387	if (!ptr && tryload != XTF_DONT_LOAD && tryload != XTF_DURING_LOAD) {
388		ptr = load_extension(xtables_libdir, afinfo.libprefix,
389		      name, false);
390
391		if (ptr == NULL && tryload == XTF_LOAD_MUST_SUCCEED)
392			exit_error(PARAMETER_PROBLEM,
393				   "Couldn't load match `%s':%s\n",
394				   name, dlerror());
395	}
396#else
397	if (ptr && !ptr->loaded) {
398		if (tryload != XTF_DONT_LOAD)
399			ptr->loaded = 1;
400		else
401			ptr = NULL;
402	}
403	if(!ptr && (tryload == XTF_LOAD_MUST_SUCCEED)) {
404		exit_error(PARAMETER_PROBLEM,
405			   "Couldn't find match `%s'\n", name);
406	}
407#endif
408
409	if (ptr && matches) {
410		struct xtables_rule_match **i;
411		struct xtables_rule_match *newentry;
412
413		newentry = xtables_malloc(sizeof(struct xtables_rule_match));
414
415		for (i = matches; *i; i = &(*i)->next) {
416			if (strcmp(name, (*i)->match->name) == 0)
417				(*i)->completed = true;
418		}
419		newentry->match = ptr;
420		newentry->completed = false;
421		newentry->next = NULL;
422		*i = newentry;
423	}
424
425	return ptr;
426}
427
428struct xtables_target *
429xtables_find_target(const char *name, enum xtables_tryload tryload)
430{
431	struct xtables_target *ptr;
432
433	/* Standard target? */
434	if (strcmp(name, "") == 0
435	    || strcmp(name, XTC_LABEL_ACCEPT) == 0
436	    || strcmp(name, XTC_LABEL_DROP) == 0
437	    || strcmp(name, XTC_LABEL_QUEUE) == 0
438	    || strcmp(name, XTC_LABEL_RETURN) == 0)
439		name = "standard";
440
441	for (ptr = xtables_targets; ptr; ptr = ptr->next) {
442		if (strcmp(name, ptr->name) == 0)
443			break;
444	}
445
446#ifndef NO_SHARED_LIBS
447	if (!ptr && tryload != XTF_DONT_LOAD && tryload != XTF_DURING_LOAD) {
448		ptr = load_extension(xtables_libdir, afinfo.libprefix,
449		      name, true);
450
451		if (ptr == NULL && tryload == XTF_LOAD_MUST_SUCCEED)
452			exit_error(PARAMETER_PROBLEM,
453				   "Couldn't load target `%s':%s\n",
454				   name, dlerror());
455	}
456#else
457	if (ptr && !ptr->loaded) {
458		if (tryload != XTF_DONT_LOAD)
459			ptr->loaded = 1;
460		else
461			ptr = NULL;
462	}
463	if(!ptr && (tryload == LOAD_MUST_SUCCEED)) {
464		exit_error(PARAMETER_PROBLEM,
465			   "Couldn't find target `%s'\n", name);
466	}
467#endif
468
469	if (ptr)
470		ptr->used = 1;
471
472	return ptr;
473}
474
475static int compatible_revision(const char *name, u_int8_t revision, int opt)
476{
477	struct xt_get_revision rev;
478	socklen_t s = sizeof(rev);
479	int max_rev, sockfd;
480
481	sockfd = socket(afinfo.family, SOCK_RAW, IPPROTO_RAW);
482	if (sockfd < 0) {
483		if (errno == EPERM) {
484			/* revision 0 is always supported. */
485			if (revision != 0)
486				fprintf(stderr, "Could not determine whether "
487						"revision %u is supported, "
488						"assuming it is.\n",
489					revision);
490			return 1;
491		}
492		fprintf(stderr, "Could not open socket to kernel: %s\n",
493			strerror(errno));
494		exit(1);
495	}
496
497	xtables_load_ko(xtables_modprobe_program, true);
498
499	strcpy(rev.name, name);
500	rev.revision = revision;
501
502	max_rev = getsockopt(sockfd, afinfo.ipproto, opt, &rev, &s);
503	if (max_rev < 0) {
504		/* Definitely don't support this? */
505		if (errno == ENOENT || errno == EPROTONOSUPPORT) {
506			close(sockfd);
507			return 0;
508		} else if (errno == ENOPROTOOPT) {
509			close(sockfd);
510			/* Assume only revision 0 support (old kernel) */
511			return (revision == 0);
512		} else {
513			fprintf(stderr, "getsockopt failed strangely: %s\n",
514				strerror(errno));
515			exit(1);
516		}
517	}
518	close(sockfd);
519	return 1;
520}
521
522
523static int compatible_match_revision(const char *name, u_int8_t revision)
524{
525	return compatible_revision(name, revision, afinfo.so_rev_match);
526}
527
528static int compatible_target_revision(const char *name, u_int8_t revision)
529{
530	return compatible_revision(name, revision, afinfo.so_rev_target);
531}
532
533void xtables_register_match(struct xtables_match *me)
534{
535	struct xtables_match **i, *old;
536
537	if (strcmp(me->version, XTABLES_VERSION) != 0) {
538		fprintf(stderr, "%s: match \"%s\" has version \"%s\", "
539		        "but \"%s\" is required.\n",
540			xtables_program_name, me->name,
541			me->version, XTABLES_VERSION);
542		exit(1);
543	}
544
545	/* Revision field stole a char from name. */
546	if (strlen(me->name) >= XT_FUNCTION_MAXNAMELEN-1) {
547		fprintf(stderr, "%s: target `%s' has invalid name\n",
548			xtables_program_name, me->name);
549		exit(1);
550	}
551
552	if (me->family >= NPROTO) {
553		fprintf(stderr,
554			"%s: BUG: match %s has invalid protocol family\n",
555			xtables_program_name, me->name);
556		exit(1);
557	}
558
559	/* ignore not interested match */
560	if (me->family != afinfo.family && me->family != AF_UNSPEC)
561		return;
562
563	old = xtables_find_match(me->name, XTF_DURING_LOAD, NULL);
564	if (old) {
565		if (old->revision == me->revision &&
566		    old->family == me->family) {
567			fprintf(stderr,
568				"%s: match `%s' already registered.\n",
569				xtables_program_name, me->name);
570			exit(1);
571		}
572
573		/* Now we have two (or more) options, check compatibility. */
574		if (compatible_match_revision(old->name, old->revision)
575		    && old->revision > me->revision)
576			return;
577
578		/* See if new match can be used. */
579		if (!compatible_match_revision(me->name, me->revision))
580			return;
581
582		/* Prefer !AF_UNSPEC over AF_UNSPEC for same revision. */
583		if (old->revision == me->revision && me->family == AF_UNSPEC)
584			return;
585
586		/* Delete old one. */
587		for (i = &xtables_matches; *i!=old; i = &(*i)->next);
588		*i = old->next;
589	}
590
591	if (me->size != XT_ALIGN(me->size)) {
592		fprintf(stderr, "%s: match `%s' has invalid size %u.\n",
593			xtables_program_name, me->name, (unsigned int)me->size);
594		exit(1);
595	}
596
597	/* Append to list. */
598	for (i = &xtables_matches; *i; i = &(*i)->next);
599	me->next = NULL;
600	*i = me;
601
602	me->m = NULL;
603	me->mflags = 0;
604}
605
606void xtables_register_target(struct xtables_target *me)
607{
608	struct xtables_target *old;
609
610	if (strcmp(me->version, XTABLES_VERSION) != 0) {
611		fprintf(stderr, "%s: target \"%s\" has version \"%s\", "
612		        "but \"%s\" is required.\n",
613			xtables_program_name, me->name,
614			me->version, XTABLES_VERSION);
615		exit(1);
616	}
617
618	/* Revision field stole a char from name. */
619	if (strlen(me->name) >= XT_FUNCTION_MAXNAMELEN-1) {
620		fprintf(stderr, "%s: target `%s' has invalid name\n",
621			xtables_program_name, me->name);
622		exit(1);
623	}
624
625	if (me->family >= NPROTO) {
626		fprintf(stderr,
627			"%s: BUG: target %s has invalid protocol family\n",
628			xtables_program_name, me->name);
629		exit(1);
630	}
631
632	/* ignore not interested target */
633	if (me->family != afinfo.family && me->family != AF_UNSPEC)
634		return;
635
636	old = xtables_find_target(me->name, XTF_DURING_LOAD);
637	if (old) {
638		struct xtables_target **i;
639
640		if (old->revision == me->revision &&
641		    old->family == me->family) {
642			fprintf(stderr,
643				"%s: target `%s' already registered.\n",
644				xtables_program_name, me->name);
645			exit(1);
646		}
647
648		/* Now we have two (or more) options, check compatibility. */
649		if (compatible_target_revision(old->name, old->revision)
650		    && old->revision > me->revision)
651			return;
652
653		/* See if new target can be used. */
654		if (!compatible_target_revision(me->name, me->revision))
655			return;
656
657		/* Prefer !AF_UNSPEC over AF_UNSPEC for same revision. */
658		if (old->revision == me->revision && me->family == AF_UNSPEC)
659			return;
660
661		/* Delete old one. */
662		for (i = &xtables_targets; *i!=old; i = &(*i)->next);
663		*i = old->next;
664	}
665
666	if (me->size != XT_ALIGN(me->size)) {
667		fprintf(stderr, "%s: target `%s' has invalid size %u.\n",
668			xtables_program_name, me->name, (unsigned int)me->size);
669		exit(1);
670	}
671
672	/* Prepend to list. */
673	me->next = xtables_targets;
674	xtables_targets = me;
675	me->t = NULL;
676	me->tflags = 0;
677}
678
679/**
680 * xtables_param_act - act on condition
681 * @status:	a constant from enum xtables_exittype
682 *
683 * %XTF_ONLY_ONCE: print error message that option may only be used once.
684 * @p1:		module name (e.g. "mark")
685 * @p2(...):	option in conflict (e.g. "--mark")
686 * @p3(...):	condition to match on (see extensions/ for examples)
687 *
688 * %XTF_NO_INVERT: option does not support inversion
689 * @p1:		module name
690 * @p2:		option in conflict
691 * @p3:		condition to match on
692 *
693 * %XTF_BAD_VALUE: bad value for option
694 * @p1:		module name
695 * @p2:		option with which the problem occured (e.g. "--mark")
696 * @p3:		string the user passed in (e.g. "99999999999999")
697 *
698 * %XTF_ONE_ACTION: two mutually exclusive actions have been specified
699 * @p1:		module name
700 *
701 * Displays an error message and exits the program.
702 */
703void xtables_param_act(unsigned int status, const char *p1, ...)
704{
705	const char *p2, *p3;
706	va_list args;
707	bool b;
708
709	va_start(args, p1);
710
711	switch (status) {
712	case XTF_ONLY_ONCE:
713		p2 = va_arg(args, const char *);
714		b  = va_arg(args, unsigned int);
715		if (!b)
716			return;
717		exit_error(PARAMETER_PROBLEM,
718		           "%s: \"%s\" option may only be specified once",
719		           p1, p2);
720		break;
721	case XTF_NO_INVERT:
722		p2 = va_arg(args, const char *);
723		b  = va_arg(args, unsigned int);
724		if (!b)
725			return;
726		exit_error(PARAMETER_PROBLEM,
727		           "%s: \"%s\" option cannot be inverted", p1, p2);
728		break;
729	case XTF_BAD_VALUE:
730		p2 = va_arg(args, const char *);
731		p3 = va_arg(args, const char *);
732		exit_error(PARAMETER_PROBLEM,
733		           "%s: Bad value for \"%s\" option: \"%s\"",
734		           p1, p2, p3);
735		break;
736	case XTF_ONE_ACTION:
737		b = va_arg(args, unsigned int);
738		if (!b)
739			return;
740		exit_error(PARAMETER_PROBLEM,
741		           "%s: At most one action is possible", p1);
742		break;
743	default:
744		exit_error(status, p1, args);
745		break;
746	}
747
748	va_end(args);
749}
750
751const char *ipaddr_to_numeric(const struct in_addr *addrp)
752{
753	static char buf[20];
754	const unsigned char *bytep = (const void *)&addrp->s_addr;
755
756	sprintf(buf, "%u.%u.%u.%u", bytep[0], bytep[1], bytep[2], bytep[3]);
757	return buf;
758}
759
760static const char *ipaddr_to_host(const struct in_addr *addr)
761{
762	struct hostent *host;
763
764	host = gethostbyaddr(addr, sizeof(struct in_addr), AF_INET);
765	if (host == NULL)
766		return NULL;
767
768	return host->h_name;
769}
770
771static const char *ipaddr_to_network(const struct in_addr *addr)
772{
773	struct netent *net;
774
775	if ((net = getnetbyaddr(ntohl(addr->s_addr), AF_INET)) != NULL)
776		return net->n_name;
777
778	return NULL;
779}
780
781const char *ipaddr_to_anyname(const struct in_addr *addr)
782{
783	const char *name;
784
785	if ((name = ipaddr_to_host(addr)) != NULL ||
786	    (name = ipaddr_to_network(addr)) != NULL)
787		return name;
788
789	return ipaddr_to_numeric(addr);
790}
791
792const char *ipmask_to_numeric(const struct in_addr *mask)
793{
794	static char buf[20];
795	uint32_t maskaddr, bits;
796	int i;
797
798	maskaddr = ntohl(mask->s_addr);
799
800	if (maskaddr == 0xFFFFFFFFL)
801		/* we don't want to see "/32" */
802		return "";
803
804	i = 32;
805	bits = 0xFFFFFFFEL;
806	while (--i >= 0 && maskaddr != bits)
807		bits <<= 1;
808	if (i >= 0)
809		sprintf(buf, "/%d", i);
810	else
811		/* mask was not a decent combination of 1's and 0's */
812		sprintf(buf, "/%s", ipaddr_to_numeric(mask));
813
814	return buf;
815}
816
817static struct in_addr *__numeric_to_ipaddr(const char *dotted, bool is_mask)
818{
819	static struct in_addr addr;
820	unsigned char *addrp;
821	unsigned int onebyte;
822	char buf[20], *p, *q;
823	int i;
824
825	/* copy dotted string, because we need to modify it */
826	strncpy(buf, dotted, sizeof(buf) - 1);
827	buf[sizeof(buf) - 1] = '\0';
828	addrp = (void *)&addr.s_addr;
829
830	p = buf;
831	for (i = 0; i < 3; ++i) {
832		if ((q = strchr(p, '.')) == NULL) {
833			if (is_mask)
834				return NULL;
835
836			/* autocomplete, this is a network address */
837			if (!xtables_strtoui(p, NULL, &onebyte, 0, UINT8_MAX))
838				return NULL;
839
840			addrp[i] = onebyte;
841			while (i < 3)
842				addrp[++i] = 0;
843
844			return &addr;
845		}
846
847		*q = '\0';
848		if (!xtables_strtoui(p, NULL, &onebyte, 0, UINT8_MAX))
849			return NULL;
850
851		addrp[i] = onebyte;
852		p = q + 1;
853	}
854
855	/* we have checked 3 bytes, now we check the last one */
856	if (!xtables_strtoui(p, NULL, &onebyte, 0, UINT8_MAX))
857		return NULL;
858
859	addrp[3] = onebyte;
860	return &addr;
861}
862
863struct in_addr *numeric_to_ipaddr(const char *dotted)
864{
865	return __numeric_to_ipaddr(dotted, false);
866}
867
868struct in_addr *numeric_to_ipmask(const char *dotted)
869{
870	return __numeric_to_ipaddr(dotted, true);
871}
872
873static struct in_addr *network_to_ipaddr(const char *name)
874{
875	static struct in_addr addr;
876	struct netent *net;
877
878	if ((net = getnetbyname(name)) != NULL) {
879		if (net->n_addrtype != AF_INET)
880			return NULL;
881		addr.s_addr = htonl(net->n_net);
882		return &addr;
883	}
884
885	return NULL;
886}
887
888static struct in_addr *host_to_ipaddr(const char *name, unsigned int *naddr)
889{
890	struct hostent *host;
891	struct in_addr *addr;
892	unsigned int i;
893
894	*naddr = 0;
895	if ((host = gethostbyname(name)) != NULL) {
896		if (host->h_addrtype != AF_INET ||
897		    host->h_length != sizeof(struct in_addr))
898			return NULL;
899
900		while (host->h_addr_list[*naddr] != NULL)
901			++*naddr;
902		addr = xtables_calloc(*naddr, sizeof(struct in_addr) * *naddr);
903		for (i = 0; i < *naddr; i++)
904			memcpy(&addr[i], host->h_addr_list[i],
905			       sizeof(struct in_addr));
906		return addr;
907	}
908
909	return NULL;
910}
911
912static struct in_addr *
913ipparse_hostnetwork(const char *name, unsigned int *naddrs)
914{
915	struct in_addr *addrptmp, *addrp;
916
917	if ((addrptmp = numeric_to_ipaddr(name)) != NULL ||
918	    (addrptmp = network_to_ipaddr(name)) != NULL) {
919		addrp = xtables_malloc(sizeof(struct in_addr));
920		memcpy(addrp, addrptmp, sizeof(*addrp));
921		*naddrs = 1;
922		return addrp;
923	}
924	if ((addrptmp = host_to_ipaddr(name, naddrs)) != NULL)
925		return addrptmp;
926
927	exit_error(PARAMETER_PROBLEM, "host/network `%s' not found", name);
928}
929
930static struct in_addr *parse_ipmask(const char *mask)
931{
932	static struct in_addr maskaddr;
933	struct in_addr *addrp;
934	unsigned int bits;
935
936	if (mask == NULL) {
937		/* no mask at all defaults to 32 bits */
938		maskaddr.s_addr = 0xFFFFFFFF;
939		return &maskaddr;
940	}
941	if ((addrp = numeric_to_ipmask(mask)) != NULL)
942		/* dotted_to_addr already returns a network byte order addr */
943		return addrp;
944	if (!xtables_strtoui(mask, NULL, &bits, 0, 32))
945		exit_error(PARAMETER_PROBLEM,
946			   "invalid mask `%s' specified", mask);
947	if (bits != 0) {
948		maskaddr.s_addr = htonl(0xFFFFFFFF << (32 - bits));
949		return &maskaddr;
950	}
951
952	maskaddr.s_addr = 0U;
953	return &maskaddr;
954}
955
956void ipparse_hostnetworkmask(const char *name, struct in_addr **addrpp,
957                             struct in_addr *maskp, unsigned int *naddrs)
958{
959	unsigned int i, j, k, n;
960	struct in_addr *addrp;
961	char buf[256], *p;
962
963	strncpy(buf, name, sizeof(buf) - 1);
964	buf[sizeof(buf) - 1] = '\0';
965	if ((p = strrchr(buf, '/')) != NULL) {
966		*p = '\0';
967		addrp = parse_ipmask(p + 1);
968	} else {
969		addrp = parse_ipmask(NULL);
970	}
971	memcpy(maskp, addrp, sizeof(*maskp));
972
973	/* if a null mask is given, the name is ignored, like in "any/0" */
974	if (maskp->s_addr == 0U)
975		strcpy(buf, "0.0.0.0");
976
977	addrp = *addrpp = ipparse_hostnetwork(buf, naddrs);
978	n = *naddrs;
979	for (i = 0, j = 0; i < n; ++i) {
980		addrp[j++].s_addr &= maskp->s_addr;
981		for (k = 0; k < j - 1; ++k)
982			if (addrp[k].s_addr == addrp[j-1].s_addr) {
983				--*naddrs;
984				--j;
985				break;
986			}
987	}
988}
989
990const char *ip6addr_to_numeric(const struct in6_addr *addrp)
991{
992	/* 0000:0000:0000:0000:0000:000.000.000.000
993	 * 0000:0000:0000:0000:0000:0000:0000:0000 */
994	static char buf[50+1];
995	return inet_ntop(AF_INET6, addrp, buf, sizeof(buf));
996}
997
998static const char *ip6addr_to_host(const struct in6_addr *addr)
999{
1000	static char hostname[NI_MAXHOST];
1001	struct sockaddr_in6 saddr;
1002	int err;
1003
1004	memset(&saddr, 0, sizeof(struct sockaddr_in6));
1005	memcpy(&saddr.sin6_addr, addr, sizeof(*addr));
1006	saddr.sin6_family = AF_INET6;
1007
1008	err = getnameinfo((const void *)&saddr, sizeof(struct sockaddr_in6),
1009	      hostname, sizeof(hostname) - 1, NULL, 0, 0);
1010	if (err != 0) {
1011#ifdef DEBUG
1012		fprintf(stderr,"IP2Name: %s\n",gai_strerror(err));
1013#endif
1014		return NULL;
1015	}
1016
1017#ifdef DEBUG
1018	fprintf (stderr, "\naddr2host: %s\n", hostname);
1019#endif
1020	return hostname;
1021}
1022
1023const char *ip6addr_to_anyname(const struct in6_addr *addr)
1024{
1025	const char *name;
1026
1027	if ((name = ip6addr_to_host(addr)) != NULL)
1028		return name;
1029
1030	return ip6addr_to_numeric(addr);
1031}
1032
1033static int ip6addr_prefix_length(const struct in6_addr *k)
1034{
1035	unsigned int bits = 0;
1036	uint32_t a, b, c, d;
1037
1038	a = ntohl(k->s6_addr32[0]);
1039	b = ntohl(k->s6_addr32[1]);
1040	c = ntohl(k->s6_addr32[2]);
1041	d = ntohl(k->s6_addr32[3]);
1042	while (a & 0x80000000U) {
1043		++bits;
1044		a <<= 1;
1045		a  |= (b >> 31) & 1;
1046		b <<= 1;
1047		b  |= (c >> 31) & 1;
1048		c <<= 1;
1049		c  |= (d >> 31) & 1;
1050		d <<= 1;
1051	}
1052	if (a != 0 || b != 0 || c != 0 || d != 0)
1053		return -1;
1054	return bits;
1055}
1056
1057const char *ip6mask_to_numeric(const struct in6_addr *addrp)
1058{
1059	static char buf[50+2];
1060	int l = ip6addr_prefix_length(addrp);
1061
1062	if (l == -1) {
1063		strcpy(buf, "/");
1064		strcat(buf, ip6addr_to_numeric(addrp));
1065		return buf;
1066	}
1067	sprintf(buf, "/%d", l);
1068	return buf;
1069}
1070
1071struct in6_addr *numeric_to_ip6addr(const char *num)
1072{
1073	static struct in6_addr ap;
1074	int err;
1075
1076	if ((err = inet_pton(AF_INET6, num, &ap)) == 1)
1077		return &ap;
1078#ifdef DEBUG
1079	fprintf(stderr, "\nnumeric2addr: %d\n", err);
1080#endif
1081	return NULL;
1082}
1083
1084static struct in6_addr *
1085host_to_ip6addr(const char *name, unsigned int *naddr)
1086{
1087	static struct in6_addr *addr;
1088	struct addrinfo hints;
1089	struct addrinfo *res;
1090	int err;
1091
1092	memset(&hints, 0, sizeof(hints));
1093	hints.ai_flags    = AI_CANONNAME;
1094	hints.ai_family   = AF_INET6;
1095	hints.ai_socktype = SOCK_RAW;
1096	hints.ai_protocol = IPPROTO_IPV6;
1097	hints.ai_next     = NULL;
1098
1099	*naddr = 0;
1100	if ((err = getaddrinfo(name, NULL, &hints, &res)) != 0) {
1101#ifdef DEBUG
1102		fprintf(stderr,"Name2IP: %s\n",gai_strerror(err));
1103#endif
1104		return NULL;
1105	} else {
1106		if (res->ai_family != AF_INET6 ||
1107		    res->ai_addrlen != sizeof(struct sockaddr_in6))
1108			return NULL;
1109
1110#ifdef DEBUG
1111		fprintf(stderr, "resolved: len=%d  %s ", res->ai_addrlen,
1112		        ip6addr_to_numeric(&((struct sockaddr_in6 *)res->ai_addr)->sin6_addr));
1113#endif
1114		/* Get the first element of the address-chain */
1115		addr = xtables_malloc(sizeof(struct in6_addr));
1116		memcpy(addr, &((const struct sockaddr_in6 *)res->ai_addr)->sin6_addr,
1117		       sizeof(struct in6_addr));
1118		freeaddrinfo(res);
1119		*naddr = 1;
1120		return addr;
1121	}
1122
1123	return NULL;
1124}
1125
1126static struct in6_addr *network_to_ip6addr(const char *name)
1127{
1128	/*	abort();*/
1129	/* TODO: not implemented yet, but the exception breaks the
1130	 *       name resolvation */
1131	return NULL;
1132}
1133
1134static struct in6_addr *
1135ip6parse_hostnetwork(const char *name, unsigned int *naddrs)
1136{
1137	struct in6_addr *addrp, *addrptmp;
1138
1139	if ((addrptmp = numeric_to_ip6addr(name)) != NULL ||
1140	    (addrptmp = network_to_ip6addr(name)) != NULL) {
1141		addrp = xtables_malloc(sizeof(struct in6_addr));
1142		memcpy(addrp, addrptmp, sizeof(*addrp));
1143		*naddrs = 1;
1144		return addrp;
1145	}
1146	if ((addrp = host_to_ip6addr(name, naddrs)) != NULL)
1147		return addrp;
1148
1149	exit_error(PARAMETER_PROBLEM, "host/network `%s' not found", name);
1150}
1151
1152static struct in6_addr *parse_ip6mask(char *mask)
1153{
1154	static struct in6_addr maskaddr;
1155	struct in6_addr *addrp;
1156	unsigned int bits;
1157
1158	if (mask == NULL) {
1159		/* no mask at all defaults to 128 bits */
1160		memset(&maskaddr, 0xff, sizeof maskaddr);
1161		return &maskaddr;
1162	}
1163	if ((addrp = numeric_to_ip6addr(mask)) != NULL)
1164		return addrp;
1165	if (!xtables_strtoui(mask, NULL, &bits, 0, 128))
1166		exit_error(PARAMETER_PROBLEM,
1167			   "invalid mask `%s' specified", mask);
1168	if (bits != 0) {
1169		char *p = (void *)&maskaddr;
1170		memset(p, 0xff, bits / 8);
1171		memset(p + (bits / 8) + 1, 0, (128 - bits) / 8);
1172		p[bits/8] = 0xff << (8 - (bits & 7));
1173		return &maskaddr;
1174	}
1175
1176	memset(&maskaddr, 0, sizeof(maskaddr));
1177	return &maskaddr;
1178}
1179
1180void ip6parse_hostnetworkmask(const char *name, struct in6_addr **addrpp,
1181                              struct in6_addr *maskp, unsigned int *naddrs)
1182{
1183	struct in6_addr *addrp;
1184	unsigned int i, j, k, n;
1185	char buf[256], *p;
1186
1187	strncpy(buf, name, sizeof(buf) - 1);
1188	buf[sizeof(buf)-1] = '\0';
1189	if ((p = strrchr(buf, '/')) != NULL) {
1190		*p = '\0';
1191		addrp = parse_ip6mask(p + 1);
1192	} else {
1193		addrp = parse_ip6mask(NULL);
1194	}
1195	memcpy(maskp, addrp, sizeof(*maskp));
1196
1197	/* if a null mask is given, the name is ignored, like in "any/0" */
1198	if (memcmp(maskp, &in6addr_any, sizeof(in6addr_any)) == 0)
1199		strcpy(buf, "::");
1200
1201	addrp = *addrpp = ip6parse_hostnetwork(buf, naddrs);
1202	n = *naddrs;
1203	for (i = 0, j = 0; i < n; ++i) {
1204		for (k = 0; k < 4; ++k)
1205			addrp[j].s6_addr32[k] &= maskp->s6_addr32[k];
1206		++j;
1207		for (k = 0; k < j - 1; ++k)
1208			if (IN6_ARE_ADDR_EQUAL(&addrp[k], &addrp[j - 1])) {
1209				--*naddrs;
1210				--j;
1211				break;
1212			}
1213	}
1214}
1215
1216void save_string(const char *value)
1217{
1218	static const char no_quote_chars[] = "_-0123456789"
1219		"abcdefghijklmnopqrstuvwxyz"
1220		"ABCDEFGHIJKLMNOPQRSTUVWXYZ";
1221	static const char escape_chars[] = "\"\\'";
1222	size_t length;
1223	const char *p;
1224
1225	length = strcspn(value, no_quote_chars);
1226	if (length > 0 && value[length] == 0) {
1227		/* no quoting required */
1228		fputs(value, stdout);
1229		putchar(' ');
1230	} else {
1231		/* there is at least one dangerous character in the
1232		   value, which we have to quote.  Write double quotes
1233		   around the value and escape special characters with
1234		   a backslash */
1235		putchar('"');
1236
1237		for (p = strpbrk(value, escape_chars); p != NULL;
1238		     p = strpbrk(value, escape_chars)) {
1239			if (p > value)
1240				fwrite(value, 1, p - value, stdout);
1241			putchar('\\');
1242			putchar(*p);
1243			value = p + 1;
1244		}
1245
1246		/* print the rest and finish the double quoted
1247		   string */
1248		fputs(value, stdout);
1249		printf("\" ");
1250	}
1251}
1252