Skip to contentSkip to conversation

ip: Use netlink to walk through network device list

PATCH In review Serhey Popovych 2 participants 8 messages Feb 7, 2018 – Feb 8, 2018

Subsystems (3)
lore
Share & tools
lore
#0 lore raw

v2 cover ip: Use netlink to walk through network device list

In this seris I replace /proc/net/dev and /sys/class/net usage for walk through network device list in iptunnel/ip6tunnel and iptuntap with netlink dump.

Following changed since RFC was sent:

1) Treat @struct rtnl_link_stats and @struct rtnl_link_stats64 as array with __u32 and __u64 elements respectively in copy_rtnl_link_stats64() as suggested by Stephen Hemminger.

2) Remove @name and @size parameters from @struct tnl_print_nlmsg_info since we can get them easily from other data.

Testing.
========

Following script is used to ensure I didn't broke things too much:

\#!/bin/bash

iproute2_dir="$1"
iface='gre1'

pushd "$iproute2_dir" &>/dev/null

for i in new old; do

	DIR="/tmp/$i"
	mkdir -p "$DIR"

	ln -snf ip.$i ip/ip

	for o in '' -s -d; do
		ip/ip $o tunnel show           >"$DIR/ip${o}-tunnel-show"
		ip/ip -4 $o tunnel show        >"$DIR/ip-4${o}-tunnel-show"
		ip/ip -6 $o tunnel show        >"$DIR/ip-6${o}-tunnel-show"
		ip/ip $o tunnel show dev "$iface" \
			>"$DIR/ip${o}-tunnel-show-$iface"
		ip/ip $o tuntap show           >"$DIR/ip${o}-tuntap-show"
	done

done
rm -f ip/ip

diff -urN /tmp/{old,new} |sed -n -Ee'/^(-{3}|\+{3})[[:space:]]+/!p' rc=$?

popd &>/dev/null
exit $rc

Results:
========

...
fopen /sys/class/net/ipip1/tun_flags: No such file or directory fopen /sys/class/net/ipip2/tun_flags: No such file or directory fopen /sys/class/net/gre10/tun_flags: No such file or directory ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ note that this comes from ip.old
...
diff -urN /tmp/old/ip-d-tuntap-show /tmp/new/ip-d-tuntap-show @@ -1,4 +1,4 @@
-tun1: tap user 1004 group 27
- Attached to processes:
tun0: tun user 1000 group 27
Attached to processes:
+tun1: tap user 1004 group 27
+ Attached to processes:
diff -urN /tmp/old/ip-s-tuntap-show /tmp/new/ip-s-tuntap-show @@ -1,2 +1,2 @@
-tun1: tap user 1004 group 27
tun0: tun user 1000 group 27
+tun1: tap user 1004 group 27
diff -urN /tmp/old/ip-tuntap-show /tmp/new/ip-tuntap-show @@ -1,2 +1,2 @@
-tun1: tap user 1004 group 27
tun0: tun user 1000 group 27
+tun1: tap user 1004 group 27

So basically only print order for ip tuntap get changes. Rest is intact.

v2
Fix build failure in 0/4 patch ("iptunnel/ip6tunnel: Code cleanups") and update it's description showing why this cleanup is necessary.

Update cover letter to explain origins of fopen /sys/class/net/... error message sources.

Thanks,
Serhii

Serhey Popovych (6):
ipaddress: Unify print_link_stats() and print_link_stats64()
ip: Introduce get_rtnl_link_stats_rta() to get link statistics
tunnel: Split statistic getting and printing iptunnel/ip6tunnel: Code cleanups iptunnel/ip6tunnel: Use netlink to walk through tunnels list
tuntap: Use netlink to walk through tuntap list

 include/utils.h |    3 +
 ip/ip6tunnel.c  |  115 +++++++++++----------------------
 ip/ipaddress.c  |  189 ++++---------------------------------------------------
 ip/iptunnel.c   |   93 +++++++++------------------
 ip/iptuntap.c   |  121 ++++++++++++++++++++++++++---------
 ip/tunnel.c     |  114 ++++++++++++++++++++++++++-------
 ip/tunnel.h     |   17 ++++-
 lib/utils.c     |   45 +++++++++++++
 8 files changed, 324 insertions(+), 373 deletions(-)
Signature · 1 line
1.7.10.4
#1 lore raw

PATCH v2 1/6 ipaddress: Unify print_link_stats() and print_link_stats64()

To show real differences between these two variants adjust whitespace intendation and use print_uint() instead of print_int() as all members in both @struct rtnl_link_stats and @struct rtnl_link_stats64 are unsigned.

---
 ip/ipaddress.c |   30 ++++++++++--------------------
 1 file changed, 10 insertions(+), 20 deletions(-)
ip/ipaddress.c +10 -20
index 4707c2b..a80a385 100644
@@ -609,8 +609,7 @@ static void print_link_stats64(FILE *fp, const struct rtnl_link_stats64 *s,
 		print_uint(PRINT_JSON, "multicast", NULL, s->multicast);
 		if (s->rx_compressed)
 			print_uint(PRINT_JSON,
-				   "compressed",
-				   NULL, s->rx_compressed);
+				   "compressed", NULL, s->rx_compressed);
 
 		/* RX error stats */
 		if (show_stats > 1) {
@@ -647,8 +646,7 @@ static void print_link_stats64(FILE *fp, const struct rtnl_link_stats64 *s,
 		print_uint(PRINT_JSON, "collisions", NULL, s->collisions);
 		if (s->tx_compressed)
 			print_uint(PRINT_JSON,
-				   "compressed",
-				   NULL, s->tx_compressed);
+				   "compressed", NULL, s->tx_compressed);
 
 		/* TX error stats */
 		if (show_stats > 1) {
@@ -668,9 +666,9 @@ static void print_link_stats64(FILE *fp, const struct rtnl_link_stats64 *s,
 				print_uint(PRINT_JSON, "carrier_changes", NULL,
 					   rta_getattr_u32(carrier_changes));
 		}
+
 		close_json_object();
 		close_json_object();
-
 	} else {
 		/* RX stats */
 		fprintf(fp, "    RX: bytes  packets  errors  dropped overrun mcast   %s%s",
@@ -691,7 +689,6 @@ static void print_link_stats64(FILE *fp, const struct rtnl_link_stats64 *s,
 			fprintf(fp, "%s", _SL_);
 			fprintf(fp, "    RX errors: length   crc     frame   fifo    missed%s%s",
 				s->rx_nohandler ? "   nohandler" : "", _SL_);
-
 			fprintf(fp, "               ");
 			print_num(fp, 8, s->rx_length_errors);
 			print_num(fp, 7, s->rx_crc_errors);
@@ -700,7 +697,6 @@ static void print_link_stats64(FILE *fp, const struct rtnl_link_stats64 *s,
 			print_num(fp, 7, s->rx_missed_errors);
 			if (s->rx_nohandler)
 				print_num(fp, 7, s->rx_nohandler);
-
 		}
 		fprintf(fp, "%s", _SL_);
 
@@ -753,9 +749,8 @@ static void print_link_stats32(FILE *fp, const struct rtnl_link_stats *s,
 		print_uint(PRINT_JSON, "over_errors", NULL, s->rx_over_errors);
 		print_uint(PRINT_JSON, "multicast", NULL, s->multicast);
 		if (s->rx_compressed)
-			print_int(PRINT_JSON,
-				  "compressed",
-				  NULL, s->rx_compressed);
+			print_uint(PRINT_JSON,
+				   "compressed", NULL, s->rx_compressed);
 
 		/* RX error stats */
 		if (show_stats > 1) {
@@ -775,9 +770,8 @@ static void print_link_stats32(FILE *fp, const struct rtnl_link_stats *s,
 				   "missed_errors",
 				   NULL, s->rx_missed_errors);
 			if (s->rx_nohandler)
-				print_int(PRINT_JSON,
-					  "nohandler",
-					  NULL, s->rx_nohandler);
+				print_uint(PRINT_JSON,
+					   "nohandler", NULL, s->rx_nohandler);
 		}
 		close_json_object();
 
@@ -792,9 +786,8 @@ static void print_link_stats32(FILE *fp, const struct rtnl_link_stats *s,
 			   NULL, s->tx_carrier_errors);
 		print_uint(PRINT_JSON, "collisions", NULL, s->collisions);
 		if (s->tx_compressed)
-			print_int(PRINT_JSON,
-				  "compressed",
-				  NULL, s->tx_compressed);
+			print_uint(PRINT_JSON,
+				   "compressed", NULL, s->tx_compressed);
 
 		/* TX error stats */
 		if (show_stats > 1) {
@@ -811,9 +804,7 @@ static void print_link_stats32(FILE *fp, const struct rtnl_link_stats *s,
 				   "heartbeat_errors",
 				   NULL, s->tx_heartbeat_errors);
 			if (carrier_changes)
-				print_uint(PRINT_JSON,
-					   "carrier_changes",
-					   NULL,
+				print_uint(PRINT_JSON, "carrier_changes", NULL,
 					   rta_getattr_u32(carrier_changes));
 		}
 
@@ -824,7 +815,6 @@ static void print_link_stats32(FILE *fp, const struct rtnl_link_stats *s,
 		fprintf(fp, "    RX: bytes  packets  errors  dropped overrun mcast   %s%s",
 			s->rx_compressed ? "compressed" : "", _SL_);
 
-
 		fprintf(fp, "    ");
 		print_num(fp, 10, s->rx_bytes);
 		print_num(fp, 8, s->rx_packets);
Signature · 1 line
1.7.10.4
#2 lore raw

PATCH v2 2/6 ip: Introduce get_rtnl_link_stats_rta() to get link statistics

In reply to Serhey Popovych

Assume all statistics in ip(8) represented either by IFLA_STATS64 or IFLA_STATS is 64 bit. It is clean that we can store __u32 counters of @struct rtnl_link_stats in __u64 counters in @struct rtnl_link_stats64.

New get_rtnl_link_stats_rta() follows __print_link_stats() behaviour on handling of stats attribute: copy no more than size of data structure and no less than attribute length zeroing rest.

Drop print_link_stats32() as it's functionality can be handled by 64bit variant. Move code from __print_link_stats() to print_link_stats64() and finally rename print_link_stats64() to __print_link_stats().

More users of introduced function will come in future.

---
 include/utils.h |    3 +
 ip/ipaddress.c  |  171 +++----------------------------------------------------
 lib/utils.c     |   45 +++++++++++++++
 3 files changed, 56 insertions(+), 163 deletions(-)
include/utils.h +3 -0
index f81928a..8b8ee2e 100644
@@ -284,6 +284,9 @@ int make_path(const char *path, mode_t mode);
 char *find_cgroup2_mount(void);
 int get_command_name(const char *pid, char *comm, size_t len);
 
+int get_rtnl_link_stats_rta(struct rtnl_link_stats64 *stats64,
+			    struct rtattr *tb[]);
+
 #ifdef NEED_STRLCPY
 size_t strlcpy(char *dst, const char *src, size_t size);
 size_t strlcat(char *dst, const char *src, size_t size);
ip/ipaddress.c +8 -163

187 lines not on this page · raw message

lib/utils.c +45 -0

51 lines not on this page · raw message

Signature · 1 line
1.7.10.4
#3 lore raw

PATCH v2 3/6 tunnel: Split statistic getting and printing

In reply to Serhey Popovych

This is first step to move tunnel code to use rtnl dump interface instead of /proc/net/dev read.

Make tnl_print_stats() to accept @struct rtnl_link_stats64 parameter, introduce tnl_get_stats() that will parse line from /proc/net/dev into @struct rtnl_link_stats64.

---
 ip/ip6tunnel.c |    8 ++++++--
 ip/iptunnel.c  |    8 ++++++--
 ip/tunnel.c    |   57 +++++++++++++++++++++++++++++++++++---------------------
 ip/tunnel.h    |    5 ++++-
 4 files changed, 52 insertions(+), 26 deletions(-)
ip/ip6tunnel.c +6 -2
index 783e28a..3e99559 100644
@@ -390,8 +390,12 @@ static int do_tunnels_list(struct ip6_tnl_parm2 *p)
 		if (!ip6_tnl_parm_match(p, &p1))
 			continue;
 		print_tunnel(&p1);
-		if (show_stats)
-			tnl_print_stats(ptr);
+		if (show_stats) {
+			struct rtnl_link_stats64 s;
+
+			if (!tnl_get_stats(ptr, &s))
+				tnl_print_stats(&s);
+		}
 		printf("\n");
 	}
 	err = 0;
ip/iptunnel.c +6 -2
index 0aa3b33..6639055 100644
@@ -425,8 +425,12 @@ static int do_tunnels_list(struct ip_tunnel_parm *p)
 		    (p->i_key && p1.i_key != p->i_key))
 			continue;
 		print_tunnel(&p1);
-		if (show_stats)
-			tnl_print_stats(ptr);
+		if (show_stats) {
+			struct rtnl_link_stats64 s;
+
+			if (!tnl_get_stats(ptr, &s))
+				tnl_print_stats(&s);
+		}
 		printf("\n");
 	}
 	err = 0;
ip/tunnel.c +36 -21

66 lines not on this page · raw message

ip/tunnel.h +4 -1
index 5bd27c3..5fe488b 100644
@@ -24,6 +24,7 @@
 #include <linux/types.h>
 
 struct rtattr;
+struct rtnl_link_stats64;
 
 const char *tnl_strproto(__u8 proto);
 
@@ -39,6 +40,8 @@ void tnl_print_encap(struct rtattr *tb[],
 		     int encap_sport, int encap_dport);
 void tnl_print_endpoint(const char *name,
 			const struct rtattr *rta, int family);
-void tnl_print_stats(const char *buf);
+void tnl_print_stats(const struct rtnl_link_stats64 *s);
+
+int tnl_get_stats(const char *buf, struct rtnl_link_stats64 *s);
 
 #endif
Signature · 1 line
1.7.10.4
#4 lore raw

PATCH v2 4/6 iptunnel/ip6tunnel: Code cleanups

In reply to Serhey Popovych

Use switch () instead of if () to compare tunnel type to fit into 80 columns and make code more readable. Print "\n" using fputc().

In iptunnel.c abstract tunnel parameters matching code in iptunnel.c into ip_tunnel_parm_match() helper to conform with ip6tunnel.c. Use memset() to initialize @p1.

In ip6tunnel.c no need to call ll_name_to_index() with name twice: just use found previously index. Do not initialize @p1: this is done in ip6_tnl_parm_init().

This is to show real differences between ip and ipv6 do_tunnels_list() implementations and prepare for upcoming unification of them.

---
 ip/ip6tunnel.c |   33 ++++++++++++++++++---------------
 ip/iptunnel.c  |   39 ++++++++++++++++++++++++++++-----------
 2 files changed, 46 insertions(+), 26 deletions(-)
ip/ip6tunnel.c +18 -15
index 3e99559..2e6f513 100644
@@ -357,11 +357,12 @@ static int do_tunnels_list(struct ip6_tnl_parm2 *p)
 	while (fgets(buf, sizeof(buf), fp) != NULL) {
 		char name[IFNAMSIZ];
 		int index, type;
-		struct ip6_tnl_parm2 p1 = {};
+		struct ip6_tnl_parm2 p1;
 		char *ptr;
 
 		buf[sizeof(buf) - 1] = '\0';
-		if ((ptr = strchr(buf, ':')) == NULL ||
+		ptr = strchr(buf, ':');
+		if (ptr == NULL ||
 		    (*ptr++ = 0, sscanf(buf, "%s", name) != 1)) {
 			fprintf(stderr, "Wrong format for /proc/net/dev. Giving up.\n");
 			goto end;
@@ -376,16 +377,19 @@ static int do_tunnels_list(struct ip6_tnl_parm2 *p)
 			fprintf(stderr, "Failed to get type of \"%s\"\n", name);
 			continue;
 		}
-		if (type != ARPHRD_TUNNEL6 && type != ARPHRD_IP6GRE)
+		switch (type) {
+		case ARPHRD_TUNNEL6:
+		case ARPHRD_IP6GRE:
+			break;
+		default:
 			continue;
+		}
 		ip6_tnl_parm_init(&p1, 0);
 		if (type == ARPHRD_IP6GRE)
 			p1.proto = IPPROTO_GRE;
+		p1.link = index;
 		strcpy(p1.name, name);
-		p1.link = ll_name_to_index(p1.name);
-		if (p1.link == 0)
-			continue;
-		if (tnl_get_ioctl(p1.name, &p1))
+		if (tnl_get_ioctl(name, &p1))
 			continue;
 		if (!ip6_tnl_parm_match(p, &p1))
 			continue;
@@ -396,7 +400,7 @@ static int do_tunnels_list(struct ip6_tnl_parm2 *p)
 			if (!tnl_get_stats(ptr, &s))
 				tnl_print_stats(&s);
 		}
-		printf("\n");
+		fputc('\n', stdout);
 	}
 	err = 0;
  end:
@@ -416,14 +420,13 @@ static int do_show(int argc, char **argv)
 		return -1;
 
 	if (!p.name[0] || show_stats)
-		do_tunnels_list(&p);
-	else {
-		if (tnl_get_ioctl(p.name, &p))
-			return -1;
-		print_tunnel(&p);
-		printf("\n");
-	}
+		return do_tunnels_list(&p);
+
+	if (tnl_get_ioctl(p.name, &p))
+		return -1;
 
+	print_tunnel(&p);
+	fputc('\n', stdout);
 	return 0;
 }
 
ip/iptunnel.c +28 -11
index 6639055..ff201a7 100644
@@ -373,6 +373,20 @@ static void print_tunnel(struct ip_tunnel_parm *p)
 		printf("%s  Checksum output packets.", _SL_);
 }
 
+/*
+ * @p1: user specified parameter
+ * @p2: database entry
+ */
+static int ip_tunnel_parm_match(const struct ip_tunnel_parm *p1,
+				const struct ip_tunnel_parm *p2)
+{
+	return ((!p1->link || p1->link == p2->link) &&
+		(!p1->name[0] || strcmp(p1->name, p2->name) == 0) &&
+		(!p1->iph.daddr || p1->iph.daddr == p2->iph.daddr) &&
+		(!p1->iph.saddr || p1->iph.saddr == p2->iph.saddr) &&
+		(!p1->i_key || p1->i_key == p2->i_key));
+}
+
 static int do_tunnels_list(struct ip_tunnel_parm *p)
 {
 	char buf[512];
@@ -384,7 +398,7 @@ static int do_tunnels_list(struct ip_tunnel_parm *p)
 		return -1;
 	}
 
-	/* skip header lines */
+	/* skip two lines at the begenning of the file */
 	if (!fgets(buf, sizeof(buf), fp) ||
 	    !fgets(buf, sizeof(buf), fp)) {
 		fprintf(stderr, "/proc/net/dev read error\n");
@@ -394,10 +408,10 @@ static int do_tunnels_list(struct ip_tunnel_parm *p)
 	while (fgets(buf, sizeof(buf), fp) != NULL) {
 		char name[IFNAMSIZ];
 		int index, type;
-		struct ip_tunnel_parm p1 = {};
+		struct ip_tunnel_parm p1;
 		char *ptr;
 
-		buf[sizeof(buf) - 1] = 0;
+		buf[sizeof(buf) - 1] = '\0';
 		ptr = strchr(buf, ':');
 		if (ptr == NULL ||
 		    (*ptr++ = 0, sscanf(buf, "%s", name) != 1)) {
@@ -414,15 +428,18 @@ static int do_tunnels_list(struct ip_tunnel_parm *p)
 			fprintf(stderr, "Failed to get type of \"%s\"\n", name);
 			continue;
 		}
-		if (type != ARPHRD_TUNNEL && type != ARPHRD_IPGRE && type != ARPHRD_SIT)
+		switch (type) {
+		case ARPHRD_TUNNEL:
+		case ARPHRD_IPGRE:
+		case ARPHRD_SIT:
+			break;
+		default:
 			continue;
+		}
+		memset(&p1, 0, sizeof(p1));
 		if (tnl_get_ioctl(name, &p1))
 			continue;
-		if ((p->link && p1.link != p->link) ||
-		    (p->name[0] && strcmp(p1.name, p->name)) ||
-		    (p->iph.daddr && p1.iph.daddr != p->iph.daddr) ||
-		    (p->iph.saddr && p1.iph.saddr != p->iph.saddr) ||
-		    (p->i_key && p1.i_key != p->i_key))
+		if (!ip_tunnel_parm_match(p, &p1))
 			continue;
 		print_tunnel(&p1);
 		if (show_stats) {
@@ -431,7 +448,7 @@ static int do_tunnels_list(struct ip_tunnel_parm *p)
 			if (!tnl_get_stats(ptr, &s))
 				tnl_print_stats(&s);
 		}
-		printf("\n");
+		fputc('\n', stdout);
 	}
 	err = 0;
  end:
@@ -456,7 +473,7 @@ static int do_show(int argc, char **argv)
 		return -1;
 
 	print_tunnel(&p);
-	printf("\n");
+	fputc('\n', stdout);
 	return 0;
 }
 
Signature · 1 line
1.7.10.4
#5 lore raw

PATCH v2 5/6 iptunnel/ip6tunnel: Use netlink to walk through tunnels list

In reply to Serhey Popovych

Both tunnels use legacy /proc/net/dev interface to get tunnel device and it's statistics. This may cause problems for cases when procfs either not mounted or not unshare(2)d for given network namespace.

Use netlink to walk through list of tunnel devices which is network namespace aware and provides additional information such as statistics in the dump message.

Since both address family specific variants of do_tunnels_list() nearly the same, except for tunnel parameters structure initialization, matching and printing we can introduce common one in tunnel.c.

To implement address family specific parts introduce new data structure @struct tnl_print_nlmsg_info what contains all necessary information as well as pointers to ->init(), ->match() and ->print() callbacks.

Annotate data structures by const where appropriate.

---
 ip/ip6tunnel.c |  114 +++++++++++++++---------------------------------------
 ip/iptunnel.c  |  106 +++++++++++++-------------------------------------
 ip/tunnel.c    |  117 +++++++++++++++++++++++++++++++++++++++++---------------
 ip/tunnel.h    |   20 ++++++++--
 4 files changed, 159 insertions(+), 198 deletions(-)
ip/ip6tunnel.c +31 -83
index 2e6f513..c7fa082 100644
@@ -67,8 +67,9 @@ static void usage(void)
 	exit(-1);
 }
 
-static void print_tunnel(struct ip6_tnl_parm2 *p)
+static void print_tunnel(const void *t)
 {
+	const struct ip6_tnl_parm2 *p = t;
 	char s1[1024];
 	char s2[1024];
 
@@ -313,13 +314,24 @@ static void ip6_tnl_parm_init(struct ip6_tnl_parm2 *p, int apply_default)
 	}
 }
 
-/*
- * @p1: user specified parameter
- * @p2: database entry
- */
-static int ip6_tnl_parm_match(const struct ip6_tnl_parm2 *p1,
-			      const struct ip6_tnl_parm2 *p2)
+static void ip6_tnl_parm_initialize(const struct tnl_print_nlmsg_info *info)
+{
+	const struct ifinfomsg *ifi = info->ifi;
+	const struct ip6_tnl_parm2 *p1 = info->p1;
+	struct ip6_tnl_parm2 *p2 = info->p2;
+
+	ip6_tnl_parm_init(p2, 0);
+	if (ifi->ifi_type == ARPHRD_IP6GRE)
+		p2->proto = IPPROTO_GRE;
+	p2->link = ifi->ifi_index;
+	strcpy(p2->name, p1->name);
+}
+
+static bool ip6_tnl_parm_match(const struct tnl_print_nlmsg_info *info)
 {
+	const struct ip6_tnl_parm2 *p1 = info->p1;
+	const struct ip6_tnl_parm2 *p2 = info->p2;
+
 	return ((!p1->link || p1->link == p2->link) &&
 		(!p1->name[0] || strcmp(p1->name, p2->name) == 0) &&
 		(IN6_IS_ADDR_UNSPECIFIED(&p1->laddr) ||
@@ -336,91 +348,27 @@ static int ip6_tnl_parm_match(const struct ip6_tnl_parm2 *p1,
 		(!p1->flags || (p1->flags & p2->flags)));
 }
 
-static int do_tunnels_list(struct ip6_tnl_parm2 *p)
-{
-	char buf[512];
-	int err = -1;
-	FILE *fp = fopen("/proc/net/dev", "r");
-
-	if (fp == NULL) {
-		perror("fopen");
-		return -1;
-	}
-
-	/* skip two lines at the begenning of the file */
-	if (!fgets(buf, sizeof(buf), fp) ||
-	    !fgets(buf, sizeof(buf), fp)) {
-		fprintf(stderr, "/proc/net/dev read error\n");
-		goto end;
-	}
-
-	while (fgets(buf, sizeof(buf), fp) != NULL) {
-		char name[IFNAMSIZ];
-		int index, type;
-		struct ip6_tnl_parm2 p1;
-		char *ptr;
-
-		buf[sizeof(buf) - 1] = '\0';
-		ptr = strchr(buf, ':');
-		if (ptr == NULL ||
-		    (*ptr++ = 0, sscanf(buf, "%s", name) != 1)) {
-			fprintf(stderr, "Wrong format for /proc/net/dev. Giving up.\n");
-			goto end;
-		}
-		if (p->name[0] && strcmp(p->name, name))
-			continue;
-		index = ll_name_to_index(name);
-		if (index == 0)
-			continue;
-		type = ll_index_to_type(index);
-		if (type == -1) {
-			fprintf(stderr, "Failed to get type of \"%s\"\n", name);
-			continue;
-		}
-		switch (type) {
-		case ARPHRD_TUNNEL6:
-		case ARPHRD_IP6GRE:
-			break;
-		default:
-			continue;
-		}
-		ip6_tnl_parm_init(&p1, 0);
-		if (type == ARPHRD_IP6GRE)
-			p1.proto = IPPROTO_GRE;
-		p1.link = index;
-		strcpy(p1.name, name);
-		if (tnl_get_ioctl(name, &p1))
-			continue;
-		if (!ip6_tnl_parm_match(p, &p1))
-			continue;
-		print_tunnel(&p1);
-		if (show_stats) {
-			struct rtnl_link_stats64 s;
-
-			if (!tnl_get_stats(ptr, &s))
-				tnl_print_stats(&s);
-		}
-		fputc('\n', stdout);
-	}
-	err = 0;
- end:
-	fclose(fp);
-	return err;
-}
-
 static int do_show(int argc, char **argv)
 {
-	struct ip6_tnl_parm2 p;
+	struct ip6_tnl_parm2 p, p1;
 
-	ll_init_map(&rth);
 	ip6_tnl_parm_init(&p, 0);
 	p.proto = 0;  /* default to any */
 
 	if (parse_args(argc, argv, SIOCGETTUNNEL, &p) < 0)
 		return -1;
 
-	if (!p.name[0] || show_stats)
-		return do_tunnels_list(&p);
+	if (!p.name[0] || show_stats) {
+		struct tnl_print_nlmsg_info info = {
+			.p1    = &p,
+			.p2    = &p1,
+			.init  = ip6_tnl_parm_initialize,
+			.match = ip6_tnl_parm_match,
+			.print = print_tunnel,
+		};
+
+		return do_tunnels_list(&info);
+	}
 
 	if (tnl_get_ioctl(p.name, &p))
 		return -1;
ip/iptunnel.c +26 -80

134 lines not on this page · raw message

ip/tunnel.c +86 -31

132 lines not on this page · raw message

ip/tunnel.h +16 -4
index 5fe488b..e530d07 100644
@@ -21,10 +21,25 @@
 #ifndef __TUNNEL_H__
 #define __TUNNEL_H__ 1
 
+#include <stdbool.h>
 #include <linux/types.h>
 
 struct rtattr;
-struct rtnl_link_stats64;
+struct ifinfomsg;
+
+extern struct rtnl_handle rth;
+
+struct tnl_print_nlmsg_info {
+	const struct ifinfomsg *ifi;
+	const void *p1;
+	void *p2;
+
+	void (*init)(const struct tnl_print_nlmsg_info *info);
+	bool (*match)(const struct tnl_print_nlmsg_info *info);
+	void (*print)(const void *t);
+};
+
+int do_tunnels_list(struct tnl_print_nlmsg_info *info);
 
 const char *tnl_strproto(__u8 proto);
 
@@ -40,8 +55,5 @@ void tnl_print_encap(struct rtattr *tb[],
 		     int encap_sport, int encap_dport);
 void tnl_print_endpoint(const char *name,
 			const struct rtattr *rta, int family);
-void tnl_print_stats(const struct rtnl_link_stats64 *s);
-
-int tnl_get_stats(const char *buf, struct rtnl_link_stats64 *s);
 
 #endif
Signature · 1 line
1.7.10.4
#6 lore raw

PATCH v2 6/6 tuntap: Use netlink to walk through tuntap list

In reply to Serhey Popovych

It seems bad idea to depend on sysfs being mounted and reflected to the current network namespace. Same applies to procfs.

Instead netlink should be used to talk to the kernel and get list of specific network devices among with their parameters.

Support for kernel netlink message filtering by passing IFLA_INFO_KIND in RTM_GETLINK request: if kernel does not support filtering by the kind we will check it in reply anyway. Check for ifi->ifi_type to be either ARPHRD_NONE or ARPHRD_ETHER to seed up things a bit without kernel level filtering.

Unfortunately tun driver does not implement dumping it's configuration via netlink and we still need to use read_prop() which depends on sysfs to get additional tun device information.

---
 ip/iptuntap.c |  121 +++++++++++++++++++++++++++++++++++++++++++--------------
 1 file changed, 91 insertions(+), 30 deletions(-)
ip/iptuntap.c +91 -30
index 09f2be2..4628db2 100644
@@ -20,6 +20,7 @@
 #include <sys/ioctl.h>
 #include <linux/if.h>
 #include <linux/if_tun.h>
+#include <linux/if_arp.h>
 #include <pwd.h>
 #include <grp.h>
 #include <fcntl.h>
@@ -31,6 +32,8 @@
 #include "utils.h"
 #include "ip_common.h"
 
+static const char drv_name[] = "tun";
+
 #define TUNDEV "/dev/net/tun"
 
 static void usage(void) __attribute__((noreturn));
@@ -348,43 +351,101 @@ next:
 	globfree(&globbuf);
 }
 
+static int tuntap_filter_req(struct nlmsghdr *nlh, int reqlen)
+{
+	struct rtattr *linkinfo;
+	int err;
 
-static int do_show(int argc, char **argv)
+	linkinfo = addattr_nest(nlh, reqlen, IFLA_LINKINFO);
+
+	err = addattr_l(nlh, reqlen, IFLA_INFO_KIND,
+			drv_name, sizeof(drv_name) - 1);
+	if (err)
+		return err;
+
+	addattr_nest_end(nlh, linkinfo);
+
+	return 0;
+}
+
+static int print_tuntap(const struct sockaddr_nl *who,
+			struct nlmsghdr *n, void *arg)
 {
-	DIR *dir;
-	struct dirent *d;
+	struct ifinfomsg *ifi = NLMSG_DATA(n);
+	struct rtattr *tb[IFLA_MAX+1];
+	struct rtattr *linkinfo[IFLA_INFO_MAX+1];
+	const char *name, *kind;
 	long flags, owner = -1, group = -1;
 
-	dir = opendir("/sys/class/net");
-	if (!dir) {
-		perror("opendir");
+	if (n->nlmsg_type != RTM_NEWLINK && n->nlmsg_type != RTM_DELLINK)
+		return 0;
+
+	if (n->nlmsg_len < NLMSG_LENGTH(sizeof(*ifi)))
 		return -1;
+
+	switch (ifi->ifi_type) {
+	case ARPHRD_NONE:
+	case ARPHRD_ETHER:
+		break;
+	default:
+		return 0;
 	}
-	while ((d = readdir(dir))) {
-		if (d->d_name[0] == '.' &&
-		    (d->d_name[1] == 0 || d->d_name[1] == '.'))
-			continue;
-
-		if (read_prop(d->d_name, "tun_flags", &flags))
-			continue;
-
-		read_prop(d->d_name, "owner", &owner);
-		read_prop(d->d_name, "group", &group);
-
-		printf("%s:", d->d_name);
-		print_flags(flags);
-		if (owner != -1)
-			printf(" user %ld", owner);
-		if (group != -1)
-			printf(" group %ld", group);
-		printf("\n");
-		if (show_details) {
-			printf("\tAttached to processes:");
-			show_processes(d->d_name);
-			printf("\n");
-		}
+
+	parse_rtattr(tb, IFLA_MAX, IFLA_RTA(ifi), IFLA_PAYLOAD(n));
+
+	if (!tb[IFLA_IFNAME])
+		return 0;
+
+	if (!tb[IFLA_LINKINFO])
+		return 0;
+
+	parse_rtattr_nested(linkinfo, IFLA_INFO_MAX, tb[IFLA_LINKINFO]);
+
+	if (!linkinfo[IFLA_INFO_KIND])
+		return 0;
+
+	kind = rta_getattr_str(linkinfo[IFLA_INFO_KIND]);
+	if (strcmp(kind, drv_name))
+		return 0;
+
+	name = rta_getattr_str(tb[IFLA_IFNAME]);
+
+	if (read_prop(name, "tun_flags", &flags))
+		return 0;
+	if (read_prop(name, "owner", &owner))
+		return 0;
+	if (read_prop(name, "group", &group))
+		return 0;
+
+	printf("%s:", name);
+	print_flags(flags);
+	if (owner != -1)
+		printf(" user %ld", owner);
+	if (group != -1)
+		printf(" group %ld", group);
+	fputc('\n', stdout);
+	if (show_details) {
+		printf("\tAttached to processes:");
+		show_processes(name);
+		fputc('\n', stdout);
 	}
-	closedir(dir);
+
+	return 0;
+}
+
+static int do_show(int argc, char **argv)
+{
+	if (rtnl_wilddump_req_filter_fn(&rth, AF_UNSPEC, RTM_GETLINK,
+					tuntap_filter_req) < 0) {
+		perror("Cannot send dump request\n");
+		return -1;
+	}
+
+	if (rtnl_dump_filter(&rth, print_tuntap, NULL) < 0) {
+		fprintf(stderr, "Dump terminated\n");
+		return -1;
+	}
+
 	return 0;
 }
 
Signature · 1 line
1.7.10.4
#7 lore raw
In reply to Serhey Popovych
Quoted 97 lines · Serhey Popovych

In this seris I replace /proc/net/dev and /sys/class/net usage for walk through network device list in iptunnel/ip6tunnel and iptuntap with netlink dump.

Following changed since RFC was sent:

1) Treat @struct rtnl_link_stats and @struct rtnl_link_stats64 as array with __u32 and __u64 elements respectively in copy_rtnl_link_stats64() as suggested by Stephen Hemminger.

2) Remove @name and @size parameters from @struct tnl_print_nlmsg_info since we can get them easily from other data.

Testing.
========

Following script is used to ensure I didn't broke things too much:

\#!/bin/bash

iproute2_dir="$1"
iface='gre1'

pushd "$iproute2_dir" &>/dev/null

for i in new old; do

	DIR="/tmp/$i"
	mkdir -p "$DIR"

	ln -snf ip.$i ip/ip

	for o in '' -s -d; do
		ip/ip $o tunnel show           >"$DIR/ip${o}-tunnel-show"
		ip/ip -4 $o tunnel show        >"$DIR/ip-4${o}-tunnel-show"
		ip/ip -6 $o tunnel show        >"$DIR/ip-6${o}-tunnel-show"
		ip/ip $o tunnel show dev "$iface" \
			>"$DIR/ip${o}-tunnel-show-$iface"
		ip/ip $o tuntap show           >"$DIR/ip${o}-tuntap-show"
	done

done
rm -f ip/ip

diff -urN /tmp/{old,new} |sed -n -Ee'/^(-{3}|\+{3})[[:space:]]+/!p' rc=$?

popd &>/dev/null
exit $rc

Results:
========

...
fopen /sys/class/net/ipip1/tun_flags: No such file or directory fopen /sys/class/net/ipip2/tun_flags: No such file or directory fopen /sys/class/net/gre10/tun_flags: No such file or directory ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ note that this comes from ip.old
...
diff -urN /tmp/old/ip-d-tuntap-show /tmp/new/ip-d-tuntap-show

(quoted diff) +2 -2
@@ -1,4 +1,4 @@
-tun1: tap user 1004 group 27
-	Attached to processes:
 tun0: tun user 1000 group 27
 	Attached to processes:
+tun1: tap user 1004 group 27
+	Attached to processes:

diff -urN /tmp/old/ip-s-tuntap-show /tmp/new/ip-s-tuntap-show

(quoted diff) +1 -1
@@ -1,2 +1,2 @@
-tun1: tap user 1004 group 27
 tun0: tun user 1000 group 27
+tun1: tap user 1004 group 27

diff -urN /tmp/old/ip-tuntap-show /tmp/new/ip-tuntap-show

(quoted diff) +1 -1
@@ -1,2 +1,2 @@
-tun1: tap user 1004 group 27
 tun0: tun user 1000 group 27
+tun1: tap user 1004 group 27

So basically only print order for ip tuntap get changes. Rest is intact.

v2
Fix build failure in 0/4 patch ("iptunnel/ip6tunnel: Code cleanups") and update it's description showing why this cleanup is necessary.

Update cover letter to explain origins of fopen /sys/class/net/... error message sources.

Thanks,
Serhii

Serhey Popovych (6):
ipaddress: Unify print_link_stats() and print_link_stats64()
ip: Introduce get_rtnl_link_stats_rta() to get link statistics
tunnel: Split statistic getting and printing iptunnel/ip6tunnel: Code cleanups iptunnel/ip6tunnel: Use netlink to walk through tunnels list
tuntap: Use netlink to walk through tuntap list

Quoted 10 lines
 include/utils.h |    3 +
 ip/ip6tunnel.c  |  115 +++++++++++----------------------
 ip/ipaddress.c  |  189 ++++---------------------------------------------------
 ip/iptunnel.c   |   93 +++++++++------------------
 ip/iptuntap.c   |  121 ++++++++++++++++++++++++++---------
 ip/tunnel.c     |  114 ++++++++++++++++++++++++++-------
 ip/tunnel.h     |   17 ++++-
 lib/utils.c     |   45 +++++++++++++
 8 files changed, 324 insertions(+), 373 deletions(-)

series applied to iproute2-next