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