xtables.c revision 39bf9c8214d3073a496a8a1eff91046a8d6fbbdf
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/* Search path for Xtables .so files */
48static const char *xtables_libdir;
49
50/* the path to command to load kernel module */
51const char *xtables_modprobe_program;
52
53/* Keeping track of external matches and targets: linked lists.  */
54struct xtables_match *xtables_matches;
55struct xtables_target *xtables_targets;
56
57void xtables_init(void)
58{
59	xtables_libdir = getenv("XTABLES_LIBDIR");
60	if (xtables_libdir != NULL)
61		return;
62	xtables_libdir = getenv("IPTABLES_LIB_DIR");
63	if (xtables_libdir != NULL) {
64		fprintf(stderr, "IPTABLES_LIB_DIR is deprecated, "
65		        "use XTABLES_LIBDIR.\n");
66		return;
67	}
68	xtables_libdir = XTABLES_LIBDIR;
69}
70
71/**
72 * xtables_*alloc - wrappers that exit on failure
73 */
74void *xtables_calloc(size_t count, size_t size)
75{
76	void *p;
77
78	if ((p = calloc(count, size)) == NULL) {
79		perror("ip[6]tables: calloc failed");
80		exit(1);
81	}
82
83	return p;
84}
85
86void *xtables_malloc(size_t size)
87{
88	void *p;
89
90	if ((p = malloc(size)) == NULL) {
91		perror("ip[6]tables: malloc failed");
92		exit(1);
93	}
94
95	return p;
96}
97
98static char *get_modprobe(void)
99{
100	int procfile;
101	char *ret;
102
103#define PROCFILE_BUFSIZ	1024
104	procfile = open(PROC_SYS_MODPROBE, O_RDONLY);
105	if (procfile < 0)
106		return NULL;
107
108	ret = (char *) malloc(PROCFILE_BUFSIZ);
109	if (ret) {
110		memset(ret, 0, PROCFILE_BUFSIZ);
111		switch (read(procfile, ret, PROCFILE_BUFSIZ)) {
112		case -1: goto fail;
113		case PROCFILE_BUFSIZ: goto fail; /* Partial read.  Wierd */
114		}
115		if (ret[strlen(ret)-1]=='\n')
116			ret[strlen(ret)-1]=0;
117		close(procfile);
118		return ret;
119	}
120 fail:
121	free(ret);
122	close(procfile);
123	return NULL;
124}
125
126int xtables_insmod(const char *modname, const char *modprobe, bool quiet)
127{
128	char *buf = NULL;
129	char *argv[4];
130	int status;
131
132	/* If they don't explicitly set it, read out of kernel */
133	if (!modprobe) {
134		buf = get_modprobe();
135		if (!buf)
136			return -1;
137		modprobe = buf;
138	}
139
140	switch (fork()) {
141	case 0:
142		argv[0] = (char *)modprobe;
143		argv[1] = (char *)modname;
144		if (quiet) {
145			argv[2] = "-q";
146			argv[3] = NULL;
147		} else {
148			argv[2] = NULL;
149			argv[3] = NULL;
150		}
151		execv(argv[0], argv);
152
153		/* not usually reached */
154		exit(1);
155	case -1:
156		return -1;
157
158	default: /* parent */
159		wait(&status);
160	}
161
162	free(buf);
163	if (WIFEXITED(status) && WEXITSTATUS(status) == 0)
164		return 0;
165	return -1;
166}
167
168int xtables_load_ko(const char *modprobe, bool quiet)
169{
170	static bool loaded = false;
171	static int ret = -1;
172
173	if (!loaded) {
174		ret = xtables_insmod(afinfo.kmod, modprobe, quiet);
175		loaded = (ret == 0);
176	}
177
178	return ret;
179}
180
181int string_to_number_ll(const char *s, unsigned long long min,
182			unsigned long long max, unsigned long long *ret)
183{
184	unsigned long long number;
185	char *end;
186
187	/* Handle hex, octal, etc. */
188	errno = 0;
189	number = strtoull(s, &end, 0);
190	if (*end == '\0' && end != s) {
191		/* we parsed a number, let's see if we want this */
192		if (errno != ERANGE && min <= number && (!max || number <= max)) {
193			*ret = number;
194			return 0;
195		}
196	}
197	return -1;
198}
199
200int string_to_number_l(const char *s, unsigned long min, unsigned long max,
201		       unsigned long *ret)
202{
203	int result;
204	unsigned long long number;
205
206	result = string_to_number_ll(s, min, max, &number);
207	*ret = (unsigned long)number;
208
209	return result;
210}
211
212int string_to_number(const char *s, unsigned int min, unsigned int max,
213		unsigned int *ret)
214{
215	int result;
216	unsigned long number;
217
218	result = string_to_number_l(s, min, max, &number);
219	*ret = (unsigned int)number;
220
221	return result;
222}
223
224/*
225 * strtonum{,l} - string to number conversion
226 *
227 * If @end is NULL, we assume the caller does not want
228 * a case like "15a", so reject it.
229 */
230bool strtonuml(const char *s, char **end, unsigned long *value,
231               unsigned long min, unsigned long max)
232{
233	unsigned long v;
234	char *my_end;
235
236	errno = 0;
237	v = strtoul(s, &my_end, 0);
238
239	if (my_end == s)
240		return false;
241	if (end != NULL)
242		*end = my_end;
243
244	if (errno != ERANGE && min <= v && (max == 0 || v <= max)) {
245		if (value != NULL)
246			*value = v;
247		if (end == NULL)
248			return *my_end == '\0';
249		return true;
250	}
251
252	return false;
253}
254
255bool strtonum(const char *s, char **end, unsigned int *value,
256                  unsigned int min, unsigned int max)
257{
258	unsigned long v;
259	bool ret;
260
261	ret = strtonuml(s, end, &v, min, max);
262	if (value != NULL)
263		*value = v;
264	return ret;
265}
266
267int service_to_port(const char *name, const char *proto)
268{
269	struct servent *service;
270
271	if ((service = getservbyname(name, proto)) != NULL)
272		return ntohs((unsigned short) service->s_port);
273
274	return -1;
275}
276
277u_int16_t parse_port(const char *port, const char *proto)
278{
279	unsigned int portnum;
280
281	if (string_to_number(port, 0, UINT16_MAX, &portnum) != -1 ||
282	    (portnum = service_to_port(port, proto)) != (unsigned)-1)
283		return portnum;
284
285	exit_error(PARAMETER_PROBLEM,
286		   "invalid port/service `%s' specified", port);
287}
288
289void parse_interface(const char *arg, char *vianame, unsigned char *mask)
290{
291	int vialen = strlen(arg);
292	unsigned int i;
293
294	memset(mask, 0, IFNAMSIZ);
295	memset(vianame, 0, IFNAMSIZ);
296
297	if (vialen + 1 > IFNAMSIZ)
298		exit_error(PARAMETER_PROBLEM,
299			   "interface name `%s' must be shorter than IFNAMSIZ"
300			   " (%i)", arg, IFNAMSIZ-1);
301
302	strcpy(vianame, arg);
303	if ((vialen == 0) || (vialen == 1 && vianame[0] == '+'))
304		memset(mask, 0, IFNAMSIZ);
305	else if (vianame[vialen - 1] == '+') {
306		memset(mask, 0xFF, vialen - 1);
307		memset(mask + vialen - 1, 0, IFNAMSIZ - vialen + 1);
308		/* Don't remove `+' here! -HW */
309	} else {
310		/* Include nul-terminator in match */
311		memset(mask, 0xFF, vialen + 1);
312		memset(mask + vialen + 1, 0, IFNAMSIZ - vialen - 1);
313		for (i = 0; vianame[i]; i++) {
314			if (vianame[i] == ':' ||
315			    vianame[i] == '!' ||
316			    vianame[i] == '*') {
317				fprintf(stderr,
318					"Warning: weird character in interface"
319					" `%s' (No aliases, :, ! or *).\n",
320					vianame);
321				break;
322			}
323		}
324	}
325}
326
327#ifndef NO_SHARED_LIBS
328static void *load_extension(const char *search_path, const char *prefix,
329    const char *name, bool is_target)
330{
331	const char *dir = search_path, *next;
332	void *ptr = NULL;
333	struct stat sb;
334	char path[256];
335
336	do {
337		next = strchr(dir, ':');
338		if (next == NULL)
339			next = dir + strlen(dir);
340		snprintf(path, sizeof(path), "%.*s/libxt_%s.so",
341		         (unsigned int)(next - dir), dir, name);
342
343		if (dlopen(path, RTLD_NOW) != NULL) {
344			/* Found library.  If it didn't register itself,
345			   maybe they specified target as match. */
346			if (is_target)
347				ptr = xtables_find_target(name, XTF_DONT_LOAD);
348			else
349				ptr = xtables_find_match(name,
350				      XTF_DONT_LOAD, NULL);
351		} else if (stat(path, &sb) == 0) {
352			fprintf(stderr, "%s: %s\n", path, dlerror());
353		}
354
355		if (ptr != NULL)
356			return ptr;
357
358		snprintf(path, sizeof(path), "%.*s/%s%s.so",
359		         (unsigned int)(next - dir), dir, prefix, name);
360		if (dlopen(path, RTLD_NOW) != NULL) {
361			if (is_target)
362				ptr = xtables_find_target(name, XTF_DONT_LOAD);
363			else
364				ptr = xtables_find_match(name,
365				      XTF_DONT_LOAD, NULL);
366		} else if (stat(path, &sb) == 0) {
367			fprintf(stderr, "%s: %s\n", path, dlerror());
368		}
369
370		if (ptr != NULL)
371			return ptr;
372
373		dir = next + 1;
374	} while (*next != '\0');
375
376	return NULL;
377}
378#endif
379
380struct xtables_match *
381xtables_find_match(const char *name, enum xtables_tryload tryload,
382		   struct xtables_rule_match **matches)
383{
384	struct xtables_match *ptr;
385	const char *icmp6 = "icmp6";
386
387	/* This is ugly as hell. Nonetheless, there is no way of changing
388	 * this without hurting backwards compatibility */
389	if ( (strcmp(name,"icmpv6") == 0) ||
390	     (strcmp(name,"ipv6-icmp") == 0) ||
391	     (strcmp(name,"icmp6") == 0) )
392		name = icmp6;
393
394	for (ptr = xtables_matches; ptr; ptr = ptr->next) {
395		if (strcmp(name, ptr->name) == 0) {
396			struct xtables_match *clone;
397
398			/* First match of this type: */
399			if (ptr->m == NULL)
400				break;
401
402			/* Second and subsequent clones */
403			clone = xtables_malloc(sizeof(struct xtables_match));
404			memcpy(clone, ptr, sizeof(struct xtables_match));
405			clone->mflags = 0;
406			/* This is a clone: */
407			clone->next = clone;
408
409			ptr = clone;
410			break;
411		}
412	}
413
414#ifndef NO_SHARED_LIBS
415	if (!ptr && tryload != XTF_DONT_LOAD && tryload != XTF_DURING_LOAD) {
416		ptr = load_extension(xtables_libdir, afinfo.libprefix,
417		      name, false);
418
419		if (ptr == NULL && tryload == XTF_LOAD_MUST_SUCCEED)
420			exit_error(PARAMETER_PROBLEM,
421				   "Couldn't load match `%s':%s\n",
422				   name, dlerror());
423	}
424#else
425	if (ptr && !ptr->loaded) {
426		if (tryload != XTF_DONT_LOAD)
427			ptr->loaded = 1;
428		else
429			ptr = NULL;
430	}
431	if(!ptr && (tryload == XTF_LOAD_MUST_SUCCEED)) {
432		exit_error(PARAMETER_PROBLEM,
433			   "Couldn't find match `%s'\n", name);
434	}
435#endif
436
437	if (ptr && matches) {
438		struct xtables_rule_match **i;
439		struct xtables_rule_match *newentry;
440
441		newentry = xtables_malloc(sizeof(struct xtables_rule_match));
442
443		for (i = matches; *i; i = &(*i)->next) {
444			if (strcmp(name, (*i)->match->name) == 0)
445				(*i)->completed = true;
446		}
447		newentry->match = ptr;
448		newentry->completed = false;
449		newentry->next = NULL;
450		*i = newentry;
451	}
452
453	return ptr;
454}
455
456struct xtables_target *
457xtables_find_target(const char *name, enum xtables_tryload tryload)
458{
459	struct xtables_target *ptr;
460
461	/* Standard target? */
462	if (strcmp(name, "") == 0
463	    || strcmp(name, XTC_LABEL_ACCEPT) == 0
464	    || strcmp(name, XTC_LABEL_DROP) == 0
465	    || strcmp(name, XTC_LABEL_QUEUE) == 0
466	    || strcmp(name, XTC_LABEL_RETURN) == 0)
467		name = "standard";
468
469	for (ptr = xtables_targets; ptr; ptr = ptr->next) {
470		if (strcmp(name, ptr->name) == 0)
471			break;
472	}
473
474#ifndef NO_SHARED_LIBS
475	if (!ptr && tryload != XTF_DONT_LOAD && tryload != XTF_DURING_LOAD) {
476		ptr = load_extension(xtables_libdir, afinfo.libprefix,
477		      name, true);
478
479		if (ptr == NULL && tryload == XTF_LOAD_MUST_SUCCEED)
480			exit_error(PARAMETER_PROBLEM,
481				   "Couldn't load target `%s':%s\n",
482				   name, dlerror());
483	}
484#else
485	if (ptr && !ptr->loaded) {
486		if (tryload != XTF_DONT_LOAD)
487			ptr->loaded = 1;
488		else
489			ptr = NULL;
490	}
491	if(!ptr && (tryload == LOAD_MUST_SUCCEED)) {
492		exit_error(PARAMETER_PROBLEM,
493			   "Couldn't find target `%s'\n", name);
494	}
495#endif
496
497	if (ptr)
498		ptr->used = 1;
499
500	return ptr;
501}
502
503static int compatible_revision(const char *name, u_int8_t revision, int opt)
504{
505	struct xt_get_revision rev;
506	socklen_t s = sizeof(rev);
507	int max_rev, sockfd;
508
509	sockfd = socket(afinfo.family, SOCK_RAW, IPPROTO_RAW);
510	if (sockfd < 0) {
511		if (errno == EPERM) {
512			/* revision 0 is always supported. */
513			if (revision != 0)
514				fprintf(stderr, "Could not determine whether "
515						"revision %u is supported, "
516						"assuming it is.\n",
517					revision);
518			return 1;
519		}
520		fprintf(stderr, "Could not open socket to kernel: %s\n",
521			strerror(errno));
522		exit(1);
523	}
524
525	xtables_load_ko(xtables_modprobe_program, true);
526
527	strcpy(rev.name, name);
528	rev.revision = revision;
529
530	max_rev = getsockopt(sockfd, afinfo.ipproto, opt, &rev, &s);
531	if (max_rev < 0) {
532		/* Definitely don't support this? */
533		if (errno == ENOENT || errno == EPROTONOSUPPORT) {
534			close(sockfd);
535			return 0;
536		} else if (errno == ENOPROTOOPT) {
537			close(sockfd);
538			/* Assume only revision 0 support (old kernel) */
539			return (revision == 0);
540		} else {
541			fprintf(stderr, "getsockopt failed strangely: %s\n",
542				strerror(errno));
543			exit(1);
544		}
545	}
546	close(sockfd);
547	return 1;
548}
549
550
551static int compatible_match_revision(const char *name, u_int8_t revision)
552{
553	return compatible_revision(name, revision, afinfo.so_rev_match);
554}
555
556static int compatible_target_revision(const char *name, u_int8_t revision)
557{
558	return compatible_revision(name, revision, afinfo.so_rev_target);
559}
560
561void xtables_register_match(struct xtables_match *me)
562{
563	struct xtables_match **i, *old;
564
565	if (strcmp(me->version, program_version) != 0) {
566		fprintf(stderr, "%s: match `%s' v%s (I'm v%s).\n",
567			program_name, me->name, me->version, program_version);
568		exit(1);
569	}
570
571	/* Revision field stole a char from name. */
572	if (strlen(me->name) >= XT_FUNCTION_MAXNAMELEN-1) {
573		fprintf(stderr, "%s: target `%s' has invalid name\n",
574			program_name, me->name);
575		exit(1);
576	}
577
578	if (me->family >= NPROTO) {
579		fprintf(stderr,
580			"%s: BUG: match %s has invalid protocol family\n",
581			program_name, me->name);
582		exit(1);
583	}
584
585	/* ignore not interested match */
586	if (me->family != afinfo.family && me->family != AF_UNSPEC)
587		return;
588
589	old = xtables_find_match(me->name, XTF_DURING_LOAD, NULL);
590	if (old) {
591		if (old->revision == me->revision &&
592		    old->family == me->family) {
593			fprintf(stderr,
594				"%s: match `%s' already registered.\n",
595				program_name, me->name);
596			exit(1);
597		}
598
599		/* Now we have two (or more) options, check compatibility. */
600		if (compatible_match_revision(old->name, old->revision)
601		    && old->revision > me->revision)
602			return;
603
604		/* See if new match can be used. */
605		if (!compatible_match_revision(me->name, me->revision))
606			return;
607
608		/* Prefer !AF_UNSPEC over AF_UNSPEC for same revision. */
609		if (old->revision == me->revision && me->family == AF_UNSPEC)
610			return;
611
612		/* Delete old one. */
613		for (i = &xtables_matches; *i!=old; i = &(*i)->next);
614		*i = old->next;
615	}
616
617	if (me->size != XT_ALIGN(me->size)) {
618		fprintf(stderr, "%s: match `%s' has invalid size %u.\n",
619			program_name, me->name, (unsigned int)me->size);
620		exit(1);
621	}
622
623	/* Append to list. */
624	for (i = &xtables_matches; *i; i = &(*i)->next);
625	me->next = NULL;
626	*i = me;
627
628	me->m = NULL;
629	me->mflags = 0;
630}
631
632void xtables_register_target(struct xtables_target *me)
633{
634	struct xtables_target *old;
635
636	if (strcmp(me->version, program_version) != 0) {
637		fprintf(stderr, "%s: target `%s' v%s (I'm v%s).\n",
638			program_name, me->name, me->version, program_version);
639		exit(1);
640	}
641
642	/* Revision field stole a char from name. */
643	if (strlen(me->name) >= XT_FUNCTION_MAXNAMELEN-1) {
644		fprintf(stderr, "%s: target `%s' has invalid name\n",
645			program_name, me->name);
646		exit(1);
647	}
648
649	if (me->family >= NPROTO) {
650		fprintf(stderr,
651			"%s: BUG: target %s has invalid protocol family\n",
652			program_name, me->name);
653		exit(1);
654	}
655
656	/* ignore not interested target */
657	if (me->family != afinfo.family && me->family != AF_UNSPEC)
658		return;
659
660	old = xtables_find_target(me->name, XTF_DURING_LOAD);
661	if (old) {
662		struct xtables_target **i;
663
664		if (old->revision == me->revision &&
665		    old->family == me->family) {
666			fprintf(stderr,
667				"%s: target `%s' already registered.\n",
668				program_name, me->name);
669			exit(1);
670		}
671
672		/* Now we have two (or more) options, check compatibility. */
673		if (compatible_target_revision(old->name, old->revision)
674		    && old->revision > me->revision)
675			return;
676
677		/* See if new target can be used. */
678		if (!compatible_target_revision(me->name, me->revision))
679			return;
680
681		/* Prefer !AF_UNSPEC over AF_UNSPEC for same revision. */
682		if (old->revision == me->revision && me->family == AF_UNSPEC)
683			return;
684
685		/* Delete old one. */
686		for (i = &xtables_targets; *i!=old; i = &(*i)->next);
687		*i = old->next;
688	}
689
690	if (me->size != XT_ALIGN(me->size)) {
691		fprintf(stderr, "%s: target `%s' has invalid size %u.\n",
692			program_name, me->name, (unsigned int)me->size);
693		exit(1);
694	}
695
696	/* Prepend to list. */
697	me->next = xtables_targets;
698	xtables_targets = me;
699	me->t = NULL;
700	me->tflags = 0;
701}
702
703void 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 P_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 P_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 P_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 P_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 (!strtonum(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 (!strtonum(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 (!strtonum(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 (string_to_number(mask, 0, 32, &bits) == -1)
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 (string_to_number(mask, 0, 128, &bits) == -1)
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