1/*
2 * tc_monitor.c		"tc monitor".
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:	Jamal Hadi Salim
10 *
11 */
12
13#include <stdio.h>
14#include <stdlib.h>
15#include <unistd.h>
16#include <syslog.h>
17#include <fcntl.h>
18#include <sys/socket.h>
19#include <netinet/in.h>
20#include <arpa/inet.h>
21#include <string.h>
22#include <time.h>
23#include "rt_names.h"
24#include "utils.h"
25#include "tc_util.h"
26#include "tc_common.h"
27
28
29static void usage(void) __attribute__((noreturn));
30
31static void usage(void)
32{
33	fprintf(stderr, "Usage: tc monitor\n");
34	exit(-1);
35}
36
37
38int accept_tcmsg(const struct sockaddr_nl *who, struct nlmsghdr *n, void *arg)
39{
40	FILE *fp = (FILE*)arg;
41
42	if (n->nlmsg_type == RTM_NEWTFILTER || n->nlmsg_type == RTM_DELTFILTER) {
43		print_filter(who, n, arg);
44		return 0;
45	}
46	if (n->nlmsg_type == RTM_NEWTCLASS || n->nlmsg_type == RTM_DELTCLASS) {
47		print_class(who, n, arg);
48		return 0;
49	}
50	if (n->nlmsg_type == RTM_NEWQDISC || n->nlmsg_type == RTM_DELQDISC) {
51		print_qdisc(who, n, arg);
52		return 0;
53	}
54	if (n->nlmsg_type == RTM_GETACTION || n->nlmsg_type == RTM_NEWACTION ||
55	    n->nlmsg_type == RTM_DELACTION) {
56		print_action(who, n, arg);
57		return 0;
58	}
59	if (n->nlmsg_type != NLMSG_ERROR && n->nlmsg_type != NLMSG_NOOP &&
60	    n->nlmsg_type != NLMSG_DONE) {
61		fprintf(fp, "Unknown message: length %08d type %08x flags %08x\n",
62			n->nlmsg_len, n->nlmsg_type, n->nlmsg_flags);
63	}
64	return 0;
65}
66
67int do_tcmonitor(int argc, char **argv)
68{
69	struct rtnl_handle rth;
70	char *file = NULL;
71	unsigned groups = nl_mgrp(RTNLGRP_TC);
72
73	while (argc > 0) {
74		if (matches(*argv, "file") == 0) {
75			NEXT_ARG();
76			file = *argv;
77		} else {
78			if (matches(*argv, "help") == 0) {
79				usage();
80			} else {
81				fprintf(stderr, "Argument \"%s\" is unknown, try \"tc monitor help\".\n", *argv);
82				exit(-1);
83			}
84		}
85		argc--;	argv++;
86	}
87
88	if (file) {
89		FILE *fp;
90		fp = fopen(file, "r");
91		if (fp == NULL) {
92			perror("Cannot fopen");
93			exit(-1);
94		}
95		return rtnl_from_file(fp, accept_tcmsg, (void*)stdout);
96	}
97
98	if (rtnl_open(&rth, groups) < 0)
99		exit(1);
100
101	ll_init_map(&rth);
102
103	if (rtnl_listen(&rth, accept_tcmsg, (void*)stdout) < 0) {
104		rtnl_close(&rth);
105		exit(2);
106	}
107
108	rtnl_close(&rth);
109	exit(0);
110}
111