On Mon, Jul 14, 2008 at 11:21:39PM +0200, Denys Vlasenko wrote:
> Cool eh? ;) Can you do the same?

Done, options are now taken care of.

> Lately there is a trend to have all new applets to be like this:
> 
> # size mdev.o
>    text    data     bss     dec     hex filename
>    2176       0       0    2176     880 mdev.o
> 
> zero zero :)

Allright, so I rewrote the whole prg_cache_* function set to
essentially use a linked list instead of a hash (slower, but doesn't
require global data beyond one single pointer for the list head, and
we don't care because we don't expect there to be *that* many
processes where linear lookup times would become noticeable).

So, what do you think about this latest version of the patch ?

Thanks,
Gabriel
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-16 20:37:41.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-16 20:37:41.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-17 13:42:32.000000000 
-0400
@@ -6,22 +6,41 @@
  * Copyright (C) 2002 by Bart Visscher <[EMAIL PROTECTED]>
  *
  * 2002-04-20
  * IPV6 support added by Bart Visscher <[EMAIL PROTECTED]>
  *
+ * 2008-07-10
+ * optional '-p' flag support ported from net-tools by G. Somlo <[EMAIL 
PROTECTED]>
+ *
  * Licensed under GPLv2 or later, see file LICENSE in this tarball for details.
  */
 
 #include "libbb.h"
 #include "inet_common.h"
 
+#define NETSTAT_OPTS "laentuwx" \
+       USE_ROUTE(               "r") \
+       USE_FEATURE_NETSTAT_WIDE("W") \
+       USE_FEATURE_NETSTAT_PRG( "p")
+
 enum {
-       OPT_extended = 0x4,
-       OPT_showroute = 0x100,
-       OPT_widedisplay = 0x200 * ENABLE_FEATURE_NETSTAT_WIDE,
+       OPTBIT_KEEP_OLD = 7,
+       USE_ROUTE(               OPTBIT_ROUTE,)
+       USE_FEATURE_NETSTAT_WIDE(OPTBIT_WIDE ,)
+       USE_FEATURE_NETSTAT_PRG( OPTBIT_PRG  ,)
+       OPT_sock_listen = 1 << 0, // l
+       OPT_sock_all    = 1 << 1, // a
+       OPT_extended    = 1 << 2, // e
+       OPT_noresolve   = 1 << 3, // n
+       OPT_sock_tcp    = 1 << 4, // t
+       OPT_sock_udp    = 1 << 5, // u
+       OPT_sock_raw    = 1 << 6, // w
+       OPT_sock_unix   = 1 << 7, // x
+       OPT_route       = USE_ROUTE(               (1<<OPTBIT_ROUTE)) + 0, // r
+       OPT_wide        = USE_FEATURE_NETSTAT_WIDE((1<<OPTBIT_WIDE )) + 0, // W
+       OPT_prg         = USE_FEATURE_NETSTAT_PRG( (1<<OPTBIT_PRG  )) + 0, // p
 };
-# define NETSTAT_OPTS "laentuwxr"USE_FEATURE_NETSTAT_WIDE("W")
 
 #define NETSTAT_CONNECTED 0x01
 #define NETSTAT_LISTENING 0x02
 #define NETSTAT_NUMERIC   0x04
 /* Must match getopt32 option string */
@@ -74,25 +93,211 @@
 #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
+
+static struct prg_node {
+       struct prg_node *next;
+       int inode;
+       char name[PROGNAME_WIDTH];
+} *prg_list = NULL;
+
+static int flag_prg = 0;
+
+#define PROGNAME_BANNER "PID/Program name"
+
+#define print_progname_banner() do { if (flag_prg) printf("%-" PROGNAME_WIDTHs 
"s"," " PROGNAME_BANNER); } while (0)
+
+#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)
+{
+       struct prg_node *pn;
+
+       pn = xmalloc(sizeof(struct prg_node));
+       pn->next = prg_list;
+       pn->inode = inode;
+       safe_strncpy(pn->name, name, PROGNAME_WIDTH);
+       prg_list = pn;
+}
+
+static const char *prg_cache_get(int inode)
+{
+       struct prg_node *pn;
+
+       for (pn = prg_list; pn; pn = pn->next)
+               if (pn->inode == inode)
+                       return pn->name;
+       return "-";
+}
+
+static void prg_cache_clear(void)
+{
+       struct prg_node *pn;
+
+       while (prg_list) {
+               pn = prg_list;
+               prg_list = prg_list->next;
+               free(pn);
+       }
+}
+
+static long extract_socket_inode(const char lname[]) {
+
+       size_t llen = strlen(lname);
+       long inode = -1;
+
+       if (llen >= PRG_SOCKET_PFXl + 3 &&
+               memcmp(lname, PRG_SOCKET_PFX, PRG_SOCKET_PFXl) == 0 &&
+               lname[llen - 1] == ']') {
+
+               /* If lname is of the form "socket:[12345]",
+                * extract the "12345" as inode.
+                */
+
+               char inode_str[llen + 1];  /* e.g. "12345" */
+               const int inode_str_len = llen - PRG_SOCKET_PFXl - 1;
+
+               strncpy(inode_str, lname + PRG_SOCKET_PFXl, inode_str_len);
+               inode_str[inode_str_len] = '\0';
+               inode = bb_strtol(inode_str, NULL, 0);
+       } else if (llen >= PRG_SOCKET_PFX2l + 1 &&
+                               memcmp(lname, PRG_SOCKET_PFX2, 
PRG_SOCKET_PFX2l) == 0) {
+
+               /* If lname is of the form "[0000]:12345",
+                * extract the "12345" as inode.
+                */
+
+               inode = bb_strtol(lname + PRG_SOCKET_PFX2l, NULL, 0);
+       }
+
+       if (errno)      /* bb_strtol() encountered an error */
+               inode = -1;
+
+       return inode;
+}
+
+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 *dir_proc = NULL, *dir_fd = NULL;
+       struct dirent *pde, *fde;
+
+       if (prg_list)
+               return;
+
+       cmdlbuf[sizeof(cmdlbuf) - 1] = '\0';
+
+       dir_proc = opendir(PATH_PROC);
+       if (!dir_proc)
+               goto fail;
+       while ((pde = readdir(dir_proc))) {
+               for (cs = pde->d_name; *cs && isdigit(*cs); cs++)
+                       continue;
+               if (*cs)
+                       continue;
+               procfdlen = snprintf(line, sizeof(line),
+                                                               PATH_PROC_X_FD, 
pde->d_name);
+               if (procfdlen <= 0 || procfdlen >= sizeof(line) - 5)
+                       continue;
+               dir_fd = opendir(line);
+               if (!dir_fd) {
+                       if (errno == EACCES)
+                               eacces = 1;
+                       continue;
+               }
+               line[procfdlen] = '/';
+               cmdlp = NULL;
+               while ((fde = readdir(dir_fd))) {
+                       if ( procfdlen + 1 + strlen(fde->d_name) + 1 > 
sizeof(line)) 
+                               continue;
+                       memcpy(line + procfdlen - PATH_FD_SUFFl, PATH_FD_SUFF 
"/",
+                                       PATH_FD_SUFFl + 1);
+                       strcpy(line + procfdlen + 1, fde->d_name);
+                       lnamelen=readlink(line, lname, sizeof(lname) - 1);
+                       lname[lnamelen] = '\0';  /*make it a null-terminated 
string*/
+
+                       inode = extract_socket_inode(lname);
+                       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", pde->d_name, 
cmdlp);
+                       prg_cache_add(inode, finbuf);
+               }
+               closedir(dir_fd); 
+               dir_fd = NULL;
+       }
+       if (dir_proc)
+               closedir(dir_proc);
+       if (dir_fd)
+               closedir(dir_fd);
+       if (!eacces)
+               return;
+       if (prg_list == NULL) {
+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 +398,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 +484,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 +545,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 +661,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);
@@ -508,24 +733,25 @@
        if (opt & 0x8) flags |= NETSTAT_NUMERIC; // -n
        //if (opt & 0x10) // -t: NETSTAT_TCP
        //if (opt & 0x20) // -u: NETSTAT_UDP
        //if (opt & 0x40) // -w: NETSTAT_RAW
        //if (opt & 0x80) // -x: NETSTAT_UNIX
-       if (opt & OPT_showroute) { // -r
-#if ENABLE_ROUTE
+       if (opt & OPT_route) { // -r
                bb_displayroutes(flags & NETSTAT_NUMERIC, !(opt & 
OPT_extended));
                return 0;
-#else
-               bb_show_usage();
-#endif
        }
 
-       if (opt & OPT_widedisplay) { // -W
+       if (opt & OPT_wide) { // -W
                net_conn_line = PRINT_NET_CONN_WIDE;
                net_conn_line_header = PRINT_NET_CONN_HEADER_WIDE;
        }
 
+       if (opt & OPT_prg) { // -p
+               flag_prg = 1;
+               prg_cache_load();
+       }
+
        opt &= NETSTAT_ALLPROTO;
        if (opt) {
                flags &= ~NETSTAT_ALLPROTO;
                flags |= opt;
        }
@@ -537,10 +763,14 @@
                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
+               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 +794,17 @@
                        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
+               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;
 }
_______________________________________________
busybox mailing list
[email protected]
http://busybox.net/cgi-bin/mailman/listinfo/busybox

Reply via email to