m_ipt.c revision f7cd9b0354c1d60415f5aaddf3e608ca0e546e1b
1/*
2 * m_ipt.c	iptables based targets
3 * 		utilities mostly ripped from iptables <duh, its the linux way>
4 *
5 *		This program is free software; you can distribute it and/or
6 *		modify it under the terms of the GNU General Public License
7 *		as published by the Free Software Foundation; either version
8 *		2 of the License, or (at your option) any later version.
9 *
10 * Authors:  J Hadi Salim (hadi@cyberus.ca)
11 */
12
13#include <syslog.h>
14#include <sys/socket.h>
15#include <netinet/in.h>
16#include <arpa/inet.h>
17#include <linux/if.h>
18#include <iptables.h>
19#include <linux/netfilter_ipv4/ip_tables.h>
20#include "utils.h"
21#include "tc_util.h"
22#include <linux/tc_act/tc_ipt.h>
23#include <stdio.h>
24#include <dlfcn.h>
25#include <getopt.h>
26#include <errno.h>
27#include <string.h>
28#include <netdb.h>
29#include <stdlib.h>
30#include <ctype.h>
31#include <stdarg.h>
32#include <limits.h>
33#include <unistd.h>
34#include <fcntl.h>
35#include <sys/wait.h>
36
37static const char *pname = "tc-ipt";
38static const char *tname = "mangle";
39static const char *pversion = "0.1";
40
41static const char *ipthooks[] = {
42	"NF_IP_PRE_ROUTING",
43	"NF_IP_LOCAL_IN",
44	"NF_IP_FORWARD",
45	"NF_IP_LOCAL_OUT",
46	"NF_IP_POST_ROUTING",
47};
48
49static struct option original_opts[] = {
50	{"jump", 1, 0, 'j'},
51	{0, 0, 0, 0}
52};
53
54static struct iptables_target *t_list = NULL;
55static struct option *opts = original_opts;
56static unsigned int global_option_offset = 0;
57#define OPTION_OFFSET 256
58
59char *lib_dir;
60
61void
62register_target(struct iptables_target *me)
63{
64/*      fprintf(stderr, "\nDummy register_target %s \n", me->name);
65*/
66	me->next = t_list;
67	t_list = me;
68
69}
70
71void
72exit_tryhelp(int status)
73{
74	fprintf(stderr, "Try `%s -h' or '%s --help' for more information.\n",
75		pname, pname);
76	exit(status);
77}
78
79void
80exit_error(enum exittype status, char *msg, ...)
81{
82	va_list args;
83
84	va_start(args, msg);
85	fprintf(stderr, "%s v%s: ", pname, pversion);
86	vfprintf(stderr, msg, args);
87	va_end(args);
88	fprintf(stderr, "\n");
89	if (status == PARAMETER_PROBLEM)
90		exit_tryhelp(status);
91	if (status == VERSION_PROBLEM)
92		fprintf(stderr,
93			"Perhaps iptables or your kernel needs to be upgraded.\n");
94	exit(status);
95}
96
97/* stolen from iptables 1.2.11
98They should really have them as a library so i can link to them
99Email them next time i remember
100*/
101
102char *
103addr_to_dotted(const struct in_addr *addrp)
104{
105	static char buf[20];
106	const unsigned char *bytep;
107
108	bytep = (const unsigned char *) &(addrp->s_addr);
109	sprintf(buf, "%d.%d.%d.%d", bytep[0], bytep[1], bytep[2], bytep[3]);
110	return buf;
111}
112
113int string_to_number_ll(const char *s, unsigned long long min,
114			unsigned long long max,
115		 unsigned long long *ret)
116{
117	unsigned long long number;
118	char *end;
119
120	/* Handle hex, octal, etc. */
121	errno = 0;
122	number = strtoull(s, &end, 0);
123	if (*end == '\0' && end != s) {
124		/* we parsed a number, let's see if we want this */
125		if (errno != ERANGE && min <= number && (!max || number <= max)) {
126			*ret = number;
127			return 0;
128		}
129	}
130	return -1;
131}
132
133int string_to_number_l(const char *s, unsigned long min, unsigned long max,
134		       unsigned long *ret)
135{
136	int result;
137	unsigned long long number;
138
139	result = string_to_number_ll(s, min, max, &number);
140	*ret = (unsigned long)number;
141
142	return result;
143}
144
145int string_to_number(const char *s, unsigned int min, unsigned int max,
146		unsigned int *ret)
147{
148	int result;
149	unsigned long number;
150
151	result = string_to_number_l(s, min, max, &number);
152	*ret = (unsigned int)number;
153
154	return result;
155}
156
157static void free_opts(struct option *opts)
158{
159	if (opts != original_opts) {
160		free(opts);
161		opts = original_opts;
162		global_option_offset = 0;
163	}
164}
165
166static struct option *
167merge_options(struct option *oldopts, const struct option *newopts,
168	      unsigned int *option_offset)
169{
170	struct option *merge;
171	unsigned int num_old, num_new, i;
172
173	for (num_old = 0; oldopts[num_old].name; num_old++) ;
174	for (num_new = 0; newopts[num_new].name; num_new++) ;
175
176	*option_offset = global_option_offset + OPTION_OFFSET;
177
178	merge = malloc(sizeof (struct option) * (num_new + num_old + 1));
179	memcpy(merge, oldopts, num_old * sizeof (struct option));
180	for (i = 0; i < num_new; i++) {
181		merge[num_old + i] = newopts[i];
182		merge[num_old + i].val += *option_offset;
183	}
184	memset(merge + num_old + num_new, 0, sizeof (struct option));
185
186	return merge;
187}
188
189static void *
190fw_calloc(size_t count, size_t size)
191{
192	void *p;
193
194	if ((p = (void *) calloc(count, size)) == NULL) {
195		perror("iptables: calloc failed");
196		exit(1);
197	}
198	return p;
199}
200
201static struct iptables_target *
202find_t(char *name)
203{
204	struct iptables_target *m;
205	for (m = t_list; m; m = m->next) {
206		if (strcmp(m->name, name) == 0)
207			return m;
208	}
209
210	return NULL;
211}
212
213static struct iptables_target *
214get_target_name(const char *name)
215{
216	void *handle;
217	char *error;
218	char *new_name, *lname;
219	struct iptables_target *m;
220	char path[strlen(lib_dir) + sizeof ("/libipt_.so") + strlen(name)];
221
222	new_name = malloc(strlen(name) + 1);
223	lname = malloc(strlen(name) + 1);
224	if (new_name)
225		memset(new_name, '\0', strlen(name) + 1);
226	else
227		exit_error(PARAMETER_PROBLEM, "get_target_name");
228
229	if (lname)
230		memset(lname, '\0', strlen(name) + 1);
231	else
232		exit_error(PARAMETER_PROBLEM, "get_target_name");
233
234	strcpy(new_name, name);
235	strcpy(lname, name);
236
237	if (isupper(lname[0])) {
238		int i;
239		for (i = 0; i < strlen(name); i++) {
240			lname[i] = tolower(lname[i]);
241		}
242	}
243
244	if (islower(new_name[0])) {
245		int i;
246		for (i = 0; i < strlen(new_name); i++) {
247			new_name[i] = toupper(new_name[i]);
248		}
249	}
250
251	sprintf(path,  "%s/libipt_%s.so",lib_dir, new_name);
252	handle = dlopen(path, RTLD_LAZY);
253	if (!handle) {
254		sprintf(path, lib_dir, "/libipt_%s.so", lname);
255		handle = dlopen(path, RTLD_LAZY);
256		if (!handle) {
257			fputs(dlerror(), stderr);
258			printf("\n");
259			return NULL;
260		}
261	}
262
263	m = dlsym(handle, new_name);
264	if ((error = dlerror()) != NULL) {
265		m = (struct iptables_target *) dlsym(handle, lname);
266		if ((error = dlerror()) != NULL) {
267			m = find_t(new_name);
268			if (NULL == m) {
269				m = find_t(lname);
270				if (NULL == m) {
271					fputs(error, stderr);
272					fprintf(stderr, "\n");
273					dlclose(handle);
274					return NULL;
275				}
276			}
277		}
278	}
279
280	return m;
281}
282
283
284struct in_addr *dotted_to_addr(const char *dotted)
285{
286	static struct in_addr addr;
287	unsigned char *addrp;
288	char *p, *q;
289	unsigned int onebyte;
290	int i;
291	char buf[20];
292
293	/* copy dotted string, because we need to modify it */
294	strncpy(buf, dotted, sizeof (buf) - 1);
295	addrp = (unsigned char *) &(addr.s_addr);
296
297	p = buf;
298	for (i = 0; i < 3; i++) {
299		if ((q = strchr(p, '.')) == NULL)
300			return (struct in_addr *) NULL;
301
302		*q = '\0';
303		if (string_to_number(p, 0, 255, &onebyte) == -1)
304			return (struct in_addr *) NULL;
305
306		addrp[i] = (unsigned char) onebyte;
307		p = q + 1;
308	}
309
310	/* we've checked 3 bytes, now we check the last one */
311	if (string_to_number(p, 0, 255, &onebyte) == -1)
312		return (struct in_addr *) NULL;
313
314	addrp[3] = (unsigned char) onebyte;
315
316	return &addr;
317}
318
319static void set_revision(char *name, u_int8_t revision)
320{
321	/* Old kernel sources don't have ".revision" field,
322	*  but we stole a byte from name. */
323	name[IPT_FUNCTION_MAXNAMELEN - 2] = '\0';
324	name[IPT_FUNCTION_MAXNAMELEN - 1] = revision;
325}
326
327/*
328 * we may need to check for version mismatch
329*/
330int
331build_st(struct iptables_target *target, struct ipt_entry_target *t)
332{
333	unsigned int nfcache = 0;
334
335	if (target) {
336		size_t size;
337
338		size =
339		    IPT_ALIGN(sizeof (struct ipt_entry_target)) + target->size;
340
341		if (NULL == t) {
342			target->t = fw_calloc(1, size);
343			target->t->u.target_size = size;
344
345			if (target->init != NULL)
346				target->init(target->t, &nfcache);
347			set_revision(target->t->u.user.name, target->revision);
348		} else {
349			target->t = t;
350		}
351		strcpy(target->t->u.user.name, target->name);
352		return 0;
353	}
354
355	return -1;
356}
357
358static int parse_ipt(struct action_util *a,int *argc_p,
359		     char ***argv_p, int tca_id, struct nlmsghdr *n)
360{
361	struct iptables_target *m = NULL;
362	struct ipt_entry fw;
363	struct rtattr *tail;
364	int c;
365	int rargc = *argc_p;
366	char **argv = *argv_p;
367	int argc = 0, iargc = 0;
368	char k[16];
369	int res = -1;
370	int size = 0;
371	int iok = 0, ok = 0;
372	__u32 hook = 0, index = 0;
373	res = 0;
374
375	lib_dir = getenv("IPTABLES_LIB_DIR");
376	if (!lib_dir)
377		lib_dir = IPT_LIB_DIR;
378
379	{
380		int i;
381		for (i = 0; i < rargc; i++) {
382			if (NULL == argv[i] || 0 == strcmp(argv[i], "action")) {
383				break;
384			}
385		}
386		iargc = argc = i;
387	}
388
389	if (argc <= 2) {
390		fprintf(stderr,"bad arguements to ipt %d vs %d \n", argc, rargc);
391		return -1;
392	}
393
394	while (1) {
395		c = getopt_long(argc, argv, "j:", opts, NULL);
396		if (c == -1)
397			break;
398		switch (c) {
399		case 'j':
400			m = get_target_name(optarg);
401			if (NULL != m) {
402
403				if (0 > build_st(m, NULL)) {
404					printf(" %s error \n", m->name);
405					return -1;
406				}
407				opts =
408				    merge_options(opts, m->extra_opts,
409						  &m->option_offset);
410			} else {
411				fprintf(stderr," failed to find target %s\n\n", optarg);
412				return -1;
413			}
414			ok++;
415			break;
416
417		default:
418			memset(&fw, 0, sizeof (fw));
419			if (m) {
420				m->parse(c - m->option_offset, argv, 0,
421					 &m->tflags, NULL, &m->t);
422			} else {
423				fprintf(stderr," failed to find target %s\n\n", optarg);
424				return -1;
425
426			}
427			ok++;
428			break;
429
430		}
431	}
432
433	if (iargc > optind) {
434		if (matches(argv[optind], "index") == 0) {
435			if (get_u32(&index, argv[optind + 1], 10)) {
436				fprintf(stderr, "Illegal \"index\"\n");
437				free_opts(opts);
438				return -1;
439			}
440			iok++;
441
442			optind += 2;
443		}
444	}
445
446	if (!ok && !iok) {
447		fprintf(stderr," ipt Parser BAD!! (%s)\n", *argv);
448		return -1;
449	}
450
451	/* check that we passed the correct parameters to the target */
452	if (m)
453		m->final_check(m->tflags);
454
455	{
456		struct tcmsg *t = NLMSG_DATA(n);
457		if (t->tcm_parent != TC_H_ROOT
458		    && t->tcm_parent == TC_H_MAJ(TC_H_INGRESS)) {
459			hook = NF_IP_PRE_ROUTING;
460		} else {
461			hook = NF_IP_POST_ROUTING;
462		}
463	}
464
465	tail = NLMSG_TAIL(n);
466	addattr_l(n, MAX_MSG, tca_id, NULL, 0);
467	fprintf(stdout, "tablename: %s hook: %s\n ", tname, ipthooks[hook]);
468	fprintf(stdout, "\ttarget: ");
469
470	if (m)
471		m->print(NULL, m->t, 0);
472	fprintf(stdout, " index %d\n", index);
473
474	if (strlen(tname) > 16) {
475		size = 16;
476		k[15] = 0;
477	} else {
478		size = 1 + strlen(tname);
479	}
480	strncpy(k, tname, size);
481
482	addattr_l(n, MAX_MSG, TCA_IPT_TABLE, k, size);
483	addattr_l(n, MAX_MSG, TCA_IPT_HOOK, &hook, 4);
484	addattr_l(n, MAX_MSG, TCA_IPT_INDEX, &index, 4);
485	if (m)
486		addattr_l(n, MAX_MSG, TCA_IPT_TARG, m->t, m->t->u.target_size);
487	tail->rta_len = (void *) NLMSG_TAIL(n) - (void *) tail;
488
489	argc -= optind;
490	argv += optind;
491	*argc_p = rargc - iargc;
492	*argv_p = argv;
493
494	optind = 1;
495	free_opts(opts);
496
497	return 0;
498
499}
500
501static int
502print_ipt(struct action_util *au,FILE * f, struct rtattr *arg)
503{
504	struct rtattr *tb[TCA_IPT_MAX + 1];
505	struct ipt_entry_target *t = NULL;
506
507	if (arg == NULL)
508		return -1;
509
510	lib_dir = getenv("IPTABLES_LIB_DIR");
511	if (!lib_dir)
512		lib_dir = IPT_LIB_DIR;
513
514	parse_rtattr_nested(tb, TCA_IPT_MAX, arg);
515
516	if (tb[TCA_IPT_TABLE] == NULL) {
517		fprintf(f, "[NULL ipt table name ] assuming mangle ");
518	} else {
519		fprintf(f, "tablename: %s ",
520			(char *) RTA_DATA(tb[TCA_IPT_TABLE]));
521	}
522
523	if (tb[TCA_IPT_HOOK] == NULL) {
524		fprintf(f, "[NULL ipt hook name ]\n ");
525		return -1;
526	} else {
527		__u32 hook;
528		hook = *(__u32 *) RTA_DATA(tb[TCA_IPT_HOOK]);
529		fprintf(f, " hook: %s \n", ipthooks[hook]);
530	}
531
532	if (tb[TCA_IPT_TARG] == NULL) {
533		fprintf(f, "\t[NULL ipt target parameters ] \n");
534		return -1;
535	} else {
536		struct iptables_target *m = NULL;
537		t = RTA_DATA(tb[TCA_IPT_TARG]);
538		m = get_target_name(t->u.user.name);
539		if (NULL != m) {
540			if (0 > build_st(m, t)) {
541				fprintf(stderr, " %s error \n", m->name);
542				return -1;
543			}
544
545			opts =
546			    merge_options(opts, m->extra_opts,
547					  &m->option_offset);
548		} else {
549			fprintf(stderr, " failed to find target %s\n\n",
550				t->u.user.name);
551			return -1;
552		}
553		fprintf(f, "\ttarget ");
554		m->print(NULL, m->t, 0);
555		if (tb[TCA_IPT_INDEX] == NULL) {
556			fprintf(f, " [NULL ipt target index ]\n");
557		} else {
558			__u32 index;
559			index = *(__u32 *) RTA_DATA(tb[TCA_IPT_INDEX]);
560			fprintf(f, " \n\tindex %d", index);
561		}
562
563		if (tb[TCA_IPT_CNT]) {
564			struct tc_cnt *c  = RTA_DATA(tb[TCA_IPT_CNT]);;
565			fprintf(f, " ref %d bind %d", c->refcnt, c->bindcnt);
566		}
567		if (show_stats) {
568			if (tb[TCA_IPT_TM]) {
569				struct tcf_t *tm = RTA_DATA(tb[TCA_IPT_TM]);
570				print_tm(f,tm);
571			}
572		}
573		fprintf(f, " \n");
574
575	}
576	free_opts(opts);
577
578	return 0;
579}
580
581struct action_util ipt_action_util = {
582        .id = "ipt",
583        .parse_aopt = parse_ipt,
584        .print_aopt = print_ipt,
585};
586
587