1/*
2 * iprule.c		"ip rule".
3 *
4 *		This program is free software; you can redistribute it and/or
5 *		modify it under the terms of the GNU General Public License
6 *		as published by the Free Software Foundation; either version
7 *		2 of the License, or (at your option) any later version.
8 *
9 * Authors:	Alexey Kuznetsov, <kuznet@ms2.inr.ac.ru>
10 *
11 *
12 * Changes:
13 *
14 * Rani Assaf <rani@magic.metawire.com> 980929:	resolve addresses
15 */
16
17#include <stdio.h>
18#include <stdlib.h>
19#include <unistd.h>
20#include <syslog.h>
21#include <fcntl.h>
22#include <sys/socket.h>
23#include <netinet/in.h>
24#include <netinet/ip.h>
25#include <arpa/inet.h>
26#include <string.h>
27
28#include "rt_names.h"
29#include "utils.h"
30
31extern struct rtnl_handle rth;
32
33static int print_rule(const struct sockaddr_nl * who, struct nlmsghdr * n, void * arg)
34{
35	FILE * fp = (FILE*)arg;
36	struct rtmsg * r = NLMSG_DATA(n);
37	int len = n->nlmsg_len;
38	struct rtattr * tb[RTA_MAX+1];
39	char abuf[256];
40	char b1[SPRINT_BSIZE];
41
42	if (n->nlmsg_type != RTM_NEWRULE)
43		return 0;
44
45	len -= NLMSG_LENGTH(sizeof(*r));
46	if (len < 0)
47		return -1;
48
49	parse_rtattr(tb, RTA_MAX, RTM_RTA(r), len);
50
51	if (tb[RTA_PRIORITY])
52		fprintf(fp, "%u:\t", *(unsigned*)RTA_DATA(tb[RTA_PRIORITY]));
53	else
54		fprintf(fp, "0:\t");
55
56	if (tb[RTA_SRC])
57		fprintf(fp, "from %s ", rt_addr_n2a(r->rtm_family, RTA_PAYLOAD(tb[RTA_SRC]),
58					RTA_DATA(tb[RTA_SRC]), abuf, sizeof(abuf)));
59	else if (r->rtm_src_len)
60		fprintf(fp, "from 0/%d ", r->rtm_src_len);
61	else
62		fprintf(fp, "from all ");
63
64	if (tb[RTA_PROTOINFO])
65		fprintf(fp, "fwmark %#x ", *(unsigned int *)RTA_DATA(tb[RTA_PROTOINFO]));
66
67	if (r->rtm_table)
68		fprintf(fp, "lookup %s ", rtnl_rttable_n2a(r->rtm_table, b1, sizeof(b1)));
69
70	fprintf(fp, "\n");
71	fflush(fp);
72
73	return 0;
74}
75
76static int iprule_list(int argc, char **argv)
77{
78	if (rtnl_request(&rth, AF_INET, RTM_GETRULE) < 0 ||
79	     rtnl_filter(&rth, print_rule, stdout) < 0)
80		return -1;
81
82	return 0;
83}
84
85int do_iprule(int argc, char **argv)
86{
87	if (strcmp(argv[0], "list") == 0 )
88		return iprule_list(argc-1, argv+1);
89
90	exit(0);
91}
92
93