PATCH: netstat '-p' optional feature

L. Gabriel Somlo somlo at cmu.edu
Thu Jul 10 21:51:52 UTC 2008


Denys & All,

I needed -p support in busybox's netstat for a project I'm working
on, so I ported the functionality over from net-tools.

The attached patch (against svn 22735) adds optional -p support
allowing netstat to print out process IDs and command names.

Please let me know what you think, and apply if you agree.

Thanks,
Gabriel
-------------- next part --------------
diff -NarU5 busybox-svn-22735.orig/include/usage.h busybox-svn-22735/include/usage.h
--- busybox-svn-22735.orig/include/usage.h	2008-07-09 23:04:08.000000000 -0400
+++ busybox-svn-22735/include/usage.h	2008-07-10 17:24:22.000000000 -0400
@@ -2813,11 +2813,11 @@
 /*   "\nport numbers can be individual or ranges: lo-hi [inclusive]" */
 
 #endif
 
 #define netstat_trivial_usage \
-       "[-laentuwxr"USE_FEATURE_NETSTAT_WIDE("W")"]"
+       "[-laentuwxr"USE_FEATURE_NETSTAT_WIDE("W")USE_FEATURE_NETSTAT_PRG("p")"]"
 #define netstat_full_usage "\n\n" \
        "Display networking information\n" \
      "\nOptions:" \
      "\n	-l	Display listening server sockets" \
      "\n	-a	Display all sockets (default: connected)" \
@@ -2828,10 +2828,13 @@
      "\n	-w	Raw sockets" \
      "\n	-x	Unix sockets" \
      "\n	-r	Display routing table" \
 	USE_FEATURE_NETSTAT_WIDE( \
      "\n	-W	Display with no column truncation" \
+	) \
+	USE_FEATURE_NETSTAT_PRG( \
+     "\n	-p	Display PID/Program name for sockets" \
 	)
 
 #define nice_trivial_usage \
        "[-n ADJUST] [COMMAND [ARG]...]"
 #define nice_full_usage "\n\n" \
diff -NarU5 busybox-svn-22735.orig/networking/Config.in busybox-svn-22735/networking/Config.in
--- busybox-svn-22735.orig/networking/Config.in	2008-07-09 23:04:03.000000000 -0400
+++ busybox-svn-22735/networking/Config.in	2008-07-10 17:24:22.000000000 -0400
@@ -630,10 +630,17 @@
 	depends on NETSTAT
 	help
 	  Add support for wide columns. Useful when displaying IPv6 addresses
 	  (-W option).
 
+config FEATURE_NETSTAT_PRG
+	bool "Enable PID/Program name output"
+	default n
+	depends on NETSTAT
+	help
+	  Add support for -p flag to print out PID and program name.
+
 config NSLOOKUP
 	bool "nslookup"
 	default n
 	help
 	  nslookup is a tool to query Internet name servers.
diff -NarU5 busybox-svn-22735.orig/networking/netstat.c busybox-svn-22735/networking/netstat.c
--- busybox-svn-22735.orig/networking/netstat.c	2008-07-09 23:04:03.000000000 -0400
+++ busybox-svn-22735/networking/netstat.c	2008-07-10 17:39:35.000000000 -0400
@@ -6,22 +6,26 @@
  * Copyright (C) 2002 by Bart Visscher <magick at linux-fan.com>
  *
  * 2002-04-20
  * IPV6 support added by Bart Visscher <magick at linux-fan.com>
  *
+ * 2008-07-10
+ * optional '-p' flag support ported from net-tools by G. Somlo <somlo at cmu.edu>
+ *
  * Licensed under GPLv2 or later, see file LICENSE in this tarball for details.
  */
 
 #include "libbb.h"
 #include "inet_common.h"
 
 enum {
 	OPT_extended = 0x4,
 	OPT_showroute = 0x100,
-	OPT_widedisplay = 0x200 * ENABLE_FEATURE_NETSTAT_WIDE,
+	OPT_widedisplay = 0x200,
+	OPT_showprog = 0x400,
 };
-# define NETSTAT_OPTS "laentuwxr"USE_FEATURE_NETSTAT_WIDE("W")
+# define NETSTAT_OPTS "laentuwxrWp"
 
 #define NETSTAT_CONNECTED 0x01
 #define NETSTAT_LISTENING 0x02
 #define NETSTAT_NUMERIC   0x04
 /* Must match getopt32 option string */
@@ -74,25 +78,235 @@
 #define SO_WAITDATA  (1<<17)	/* wait data to read            */
 #define SO_NOSPACE   (1<<18)	/* no space to write            */
 
 /* Standard printout size */
 #define PRINT_IP_MAX_SIZE           23
-#define PRINT_NET_CONN              "%s   %6ld %6ld %-23s %-23s %-12s\n"
-#define PRINT_NET_CONN_HEADER       "\nProto Recv-Q Send-Q %-23s %-23s State\n"
+#define PRINT_NET_CONN              "%s   %6ld %6ld %-23s %-23s %-12s"
+#define PRINT_NET_CONN_HEADER       "\nProto Recv-Q Send-Q %-23s %-23s State      "
 
 /* When there are IPv6 connections the IPv6 addresses will be
  * truncated to none-recognition. The '-W' option makes the
  * address columns wide enough to accomodate for longest possible
  * IPv6 addresses, i.e. addresses of the form
  * xxxx:xxxx:xxxx:xxxx:xxxx:xxxx:ddd.ddd.ddd.ddd
  */
 #define PRINT_IP_MAX_SIZE_WIDE      51  /* INET6_ADDRSTRLEN + 5 for the port number */
-#define PRINT_NET_CONN_WIDE         "%s   %6ld %6ld %-51s %-51s %-12s\n"
-#define PRINT_NET_CONN_HEADER_WIDE  "\nProto Recv-Q Send-Q %-51s %-51s State\n"
+#define PRINT_NET_CONN_WIDE         "%s   %6ld %6ld %-51s %-51s %-12s"
+#define PRINT_NET_CONN_HEADER_WIDE  "\nProto Recv-Q Send-Q %-51s %-51s State      "
 
 static const char *net_conn_line = PRINT_NET_CONN;
 
+#if ENABLE_FEATURE_NETSTAT_PRG
+
+#define PROGNAME_WIDTH 20
+
+#define PROGNAME_WIDTHs PROGNAME_WIDTH1(PROGNAME_WIDTH)
+#define PROGNAME_WIDTH1(s) PROGNAME_WIDTH2(s)
+#define PROGNAME_WIDTH2(s) #s
+
+#define PRG_HASH_SIZE 211
+
+static struct prg_node {
+	struct prg_node *next;
+	int inode;
+	char name[PROGNAME_WIDTH];
+} *prg_hash[PRG_HASH_SIZE];
+
+static char prg_cache_loaded = 0;
+
+int flag_prg = 0;
+
+#define PRG_HASHIT(x) ((x) % PRG_HASH_SIZE)
+
+#define PROGNAME_BANNER "PID/Program name"
+
+#define print_progname_banner() do { if (flag_prg) printf("%-" PROGNAME_WIDTHs "s"," " PROGNAME_BANNER); } while (0)
+
+#define PRG_LOCAL_ADDRESS "local_address"
+#define PRG_INODE	 "inode"
+#define PRG_SOCKET_PFX    "socket:["
+#define PRG_SOCKET_PFXl (strlen(PRG_SOCKET_PFX))
+#define PRG_SOCKET_PFX2   "[0000]:"
+#define PRG_SOCKET_PFX2l  (strlen(PRG_SOCKET_PFX2))
+
+#define PATH_PROC          "/proc"
+#define PATH_FD_SUFF    "fd"
+#define PATH_FD_SUFFl       strlen(PATH_FD_SUFF)
+#define PATH_PROC_X_FD      PATH_PROC "/%s/" PATH_FD_SUFF
+#define PATH_CMDLINE    "cmdline"
+#define PATH_CMDLINEl       strlen(PATH_CMDLINE)
+
+static void prg_cache_add(int inode, char *name)
+{
+	unsigned hi = PRG_HASHIT(inode);
+	struct prg_node **pnp, *pn;
+
+	prg_cache_loaded = 2;
+	for (pnp = prg_hash + hi; (pn = *pnp); pnp = &pn->next) {
+		if (pn->inode == inode) {
+			/* Some warning should be appropriate here
+			   as we got multiple processes for one i-node */
+			return;
+		}
+	}
+	if (!(*pnp = malloc(sizeof(**pnp)))) 
+		return;
+	pn = *pnp;
+	pn->next = NULL;
+	pn->inode = inode;
+	if (strlen(name) > sizeof(pn->name) - 1) 
+		name[sizeof(pn->name) - 1] = '\0';
+	strcpy(pn->name, name);
+}
+
+static const char *prg_cache_get(int inode)
+{
+	unsigned hi = PRG_HASHIT(inode);
+	struct prg_node *pn;
+
+	for (pn = prg_hash[hi]; pn; pn = pn->next)
+		if (pn->inode == inode) return(pn->name);
+	return("-");
+}
+
+static void prg_cache_clear(void)
+{
+	struct prg_node **pnp, *pn;
+
+	if (prg_cache_loaded == 2)
+	for (pnp = prg_hash; pnp < prg_hash + PRG_HASH_SIZE; pnp++)
+		while ((pn = *pnp)) {
+			*pnp = pn->next;
+			free(pn);
+		}
+	prg_cache_loaded = 0;
+}
+
+static void extract_type_1_socket_inode(const char lname[], long * inode_p) {
+
+	/* If lname is of the form "socket:[12345]", extract the "12345"
+	   as *inode_p.  Otherwise, return -1 as *inode_p.
+	   */
+
+	if (strlen(lname) < PRG_SOCKET_PFXl + 3 )
+		*inode_p = -1;
+	else if (memcmp(lname, PRG_SOCKET_PFX, PRG_SOCKET_PFXl))
+		*inode_p = -1;
+	else if (lname[strlen(lname) - 1] != ']')
+		*inode_p = -1;
+	else {
+		char inode_str[strlen(lname + 1)];  /* e.g. "12345" */
+		const int inode_str_len = strlen(lname) - PRG_SOCKET_PFXl - 1;
+		char *serr;
+
+		strncpy(inode_str, lname+PRG_SOCKET_PFXl, inode_str_len);
+		inode_str[inode_str_len] = '\0';
+		*inode_p = strtol(inode_str, &serr, 0);
+		if (!serr || *serr || *inode_p < 0 || *inode_p >= INT_MAX) 
+			*inode_p = -1;
+	}
+}
+
+static void extract_type_2_socket_inode(const char lname[], long * inode_p) {
+
+	/* If lname is of the form "[0000]:12345", extract the "12345"
+	   as *inode_p.  Otherwise, return -1 as *inode_p.
+	   */
+
+	if (strlen(lname) < PRG_SOCKET_PFX2l + 1)
+		*inode_p = -1;
+	else if (memcmp(lname, PRG_SOCKET_PFX2, PRG_SOCKET_PFX2l))
+		*inode_p = -1;
+	else {
+		char *serr;
+
+		*inode_p = strtol(lname + PRG_SOCKET_PFX2l, &serr, 0);
+		if (!serr || *serr || *inode_p < 0 || *inode_p >= INT_MAX) 
+			*inode_p = -1;
+	}
+}
+
+static void prg_cache_load(void)
+{
+	char line[LINE_MAX], eacces = 0;
+	int procfdlen, fd, cmdllen, lnamelen;
+	char lname[30], cmdlbuf[512], finbuf[PROGNAME_WIDTH];
+	long inode;
+	const char *cs, *cmdlp;
+	DIR *dirproc = NULL, *pdirfd = NULL;
+	struct dirent *direproc, *direfd;
+
+	if (prg_cache_loaded || !flag_prg) return;
+	prg_cache_loaded = 1;
+	cmdlbuf[sizeof(cmdlbuf) - 1] = '\0';
+	dirproc = opendir(PATH_PROC);
+	if (!dirproc) goto fail;
+	while (errno = 0, direproc = readdir(dirproc)) {
+		if (direproc->d_type != DT_DIR) continue;
+		for (cs = direproc->d_name; *cs && isdigit(*cs); cs++);
+		if (*cs) continue;
+		procfdlen = snprintf(line, sizeof(line),
+								PATH_PROC_X_FD, direproc->d_name);
+		if (procfdlen <= 0 || procfdlen >= sizeof(line) - 5) continue;
+		errno = 0;
+		pdirfd = opendir(line);
+		if (!pdirfd) {
+			if (errno == EACCES) eacces = 1;
+			continue;
+		}
+		line[procfdlen] = '/';
+		cmdlp = NULL;
+		while ((direfd = readdir(pdirfd))) {
+			if (direfd->d_type != DT_LNK ||
+				procfdlen + 1 + strlen(direfd->d_name) + 1 > sizeof(line)) 
+				continue;
+			memcpy(line + procfdlen - PATH_FD_SUFFl, PATH_FD_SUFF "/",
+					PATH_FD_SUFFl + 1);
+			strcpy(line + procfdlen + 1, direfd->d_name);
+			lnamelen=readlink(line, lname, sizeof(lname) - 1);
+            lname[lnamelen] = '\0';  /*make it a null-terminated string*/
+
+            extract_type_1_socket_inode(lname, &inode);
+            if (inode < 0) extract_type_2_socket_inode(lname, &inode);
+            if (inode < 0) continue;
+
+			if (!cmdlp) {
+				if (procfdlen - PATH_FD_SUFFl + PATH_CMDLINEl >=
+						sizeof(line) - 5) continue;
+				strcpy(line + procfdlen-PATH_FD_SUFFl, PATH_CMDLINE);
+				fd = open(line, O_RDONLY);
+				if (fd < 0) continue;
+				cmdllen = read(fd, cmdlbuf, sizeof(cmdlbuf) - 1);
+				if (close(fd) || cmdllen == -1) continue;
+				if (cmdllen < sizeof(cmdlbuf) - 1) 
+					cmdlbuf[cmdllen] = '\0';
+				if ((cmdlp = strrchr(cmdlbuf, '/'))) 
+					cmdlp++;
+				else 
+					cmdlp = cmdlbuf;
+	    	}
+
+			snprintf(finbuf, sizeof(finbuf), "%s/%s", direproc->d_name, cmdlp);
+			prg_cache_add(inode, finbuf);
+		}
+		closedir(pdirfd); 
+		pdirfd = NULL;
+	}
+	if (dirproc) closedir(dirproc);
+	if (pdirfd) closedir(pdirfd);
+	if (!eacces) return;
+	if (prg_cache_loaded == 1) {
+fail:
+		fprintf(stderr, "(No info could be read for \"-p\": geteuid()=%d "
+						"but you should be root.)\n", geteuid());
+    } else
+		fprintf(stderr, "(Not all processes could be identified, "
+						"non-owned process info will not be shown, "
+						"you would have to be root to see it all.)\n");
+}
+
+#endif /*ENABLE_FEATURE_NETSTAT_PRG*/
 
 #if ENABLE_FEATURE_IPV6
 static void build_ipv6_addr(char* local_addr, struct sockaddr_in6* localaddr)
 {
 	char addr6[INET6_ADDRSTRLEN];
@@ -193,10 +407,15 @@
 		char *r = ip_port_str(
 				(struct sockaddr *) &remaddr, rem_port,
 				"tcp", flags & NETSTAT_NUMERIC);
 		printf(net_conn_line,
 			"tcp", rxq, txq, l, r, tcp_state[state]);
+#if ENABLE_FEATURE_NETSTAT_PRG
+		if (flag_prg)
+			printf("%-" PROGNAME_WIDTHs "s", prg_cache_get(inode));
+#endif
+		printf("\n");
 		free(l);
 		free(r);
 	}
 	return 0;
 }
@@ -274,10 +493,15 @@
 			char *r = ip_port_str(
 				(struct sockaddr *) &remaddr, rem_port,
 				"udp", flags & NETSTAT_NUMERIC);
 			printf(net_conn_line,
 				"udp", rxq, txq, l, r, state_str);
+#if ENABLE_FEATURE_NETSTAT_PRG
+			if (flag_prg)
+				printf("%-" PROGNAME_WIDTHs "s", prg_cache_get(inode));
+#endif
+			printf("\n");
 			free(l);
 			free(r);
 		}
 	}
 	return 0;
@@ -330,10 +554,15 @@
 			char *r = ip_port_str(
 				(struct sockaddr *) &remaddr, rem_port,
 				"raw", flags & NETSTAT_NUMERIC);
 			printf(net_conn_line,
 				"raw", rxq, txq, l, r, itoa(state));
+#if ENABLE_FEATURE_NETSTAT_PRG
+			if (flag_prg)
+				printf("%-" PROGNAME_WIDTHs "s", prg_cache_get(inode));
+#endif
+			printf("\n");
 			free(l);
 			free(r);
 		}
 	}
 	return 0;
@@ -441,10 +670,15 @@
 
 	printf("%-5s %-6ld %-11s %-10s %-13s %6lu ",
 		ss_proto, refcnt, ss_flags, ss_type, ss_state, inode
 		);
 
+#if ENABLE_FEATURE_NETSTAT_PRG
+	if (flag_prg)
+		printf("%-" PROGNAME_WIDTHs "s", prg_cache_get(inode));
+#endif
+
 	/* TODO: currently we stop at first NUL byte. Is it a problem? */
 	line += path_ofs;
 	*strchrnul(line, '\n') = '\0';
 	while (*line)
 		fputc_printable(*line++, stdout);
@@ -518,12 +752,24 @@
 		bb_show_usage();
 #endif
 	}
 
 	if (opt & OPT_widedisplay) { // -W
+#if ENABLE_FEATURE_NETSTAT_WIDE
 		net_conn_line = PRINT_NET_CONN_WIDE;
 		net_conn_line_header = PRINT_NET_CONN_HEADER_WIDE;
+#else
+		bb_show_usage();
+#endif
+	}
+
+	if (opt & OPT_showprog) { // -p
+#if ENABLE_FEATURE_NETSTAT_PRG
+		flag_prg = 1;
+#else
+		bb_show_usage();
+#endif
 	}
 
 	opt &= NETSTAT_ALLPROTO;
 	if (opt) {
 		flags &= ~NETSTAT_ALLPROTO;
@@ -537,10 +783,15 @@
 		else if (flags & NETSTAT_LISTENING)
 			printf("(only servers)");
 		else
 			printf("(w/o servers)");
 		printf(net_conn_line_header, "Local Address", "Foreign Address");
+#if ENABLE_FEATURE_NETSTAT_PRG
+		prg_cache_load();
+		print_progname_banner();
+#endif
+		printf("\n");
 	}
 	if (inet && flags & NETSTAT_TCP)
 		do_info(_PATH_PROCNET_TCP, "AF INET (tcp)", tcp_do_one);
 #if ENABLE_FEATURE_IPV6
 	if (inet6 && flags & NETSTAT_TCP)
@@ -564,10 +815,18 @@
 			printf("(servers and established)");
 		else if (flags & NETSTAT_LISTENING)
 			printf("(only servers)");
 		else
 			printf("(w/o servers)");
-		printf("\nProto RefCnt Flags       Type       State         I-Node Path\n");
+		printf("\nProto RefCnt Flags       Type       State         I-Node");
+#if ENABLE_FEATURE_NETSTAT_PRG
+		prg_cache_load();
+		print_progname_banner();
+#endif
+		printf(" Path\n");
 		do_info(_PATH_PROCNET_UNIX, "AF UNIX", unix_do_one);
 	}
+#if ENABLE_FEATURE_NETSTAT_PRG
+	prg_cache_clear();
+#endif
 	return 0;
 }


More information about the busybox mailing list