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