1 /* vi: set sw=4 ts=4: */
3 * Mini netstat implementation(s) for busybox
4 * based in part on the netstat implementation from net-tools.
6 * Copyright (C) 2002 by Bart Visscher <magick@linux-fan.com>
9 * IPV6 support added by Bart Visscher <magick@linux-fan.com>
12 * optional '-p' flag support ported from net-tools by G. Somlo <somlo@cmu.edu>
14 * Licensed under GPLv2 or later, see file LICENSE in this tarball for details.
18 #include "inet_common.h"
20 #define NETSTAT_OPTS "laentuwx" \
22 USE_FEATURE_NETSTAT_WIDE("W") \
23 USE_FEATURE_NETSTAT_PRG( "p")
27 USE_ROUTE( OPTBIT_ROUTE,)
28 USE_FEATURE_NETSTAT_WIDE(OPTBIT_WIDE ,)
29 USE_FEATURE_NETSTAT_PRG( OPTBIT_PRG ,)
30 OPT_sock_listen = 1 << 0, // l
31 OPT_sock_all = 1 << 1, // a
32 OPT_extended = 1 << 2, // e
33 OPT_noresolve = 1 << 3, // n
34 OPT_sock_tcp = 1 << 4, // t
35 OPT_sock_udp = 1 << 5, // u
36 OPT_sock_raw = 1 << 6, // w
37 OPT_sock_unix = 1 << 7, // x
38 OPT_route = USE_ROUTE( (1 << OPTBIT_ROUTE)) + 0, // r
39 OPT_wide = USE_FEATURE_NETSTAT_WIDE((1 << OPTBIT_WIDE )) + 0, // W
40 OPT_prg = USE_FEATURE_NETSTAT_PRG( (1 << OPTBIT_PRG )) + 0, // p
43 #define NETSTAT_CONNECTED 0x01
44 #define NETSTAT_LISTENING 0x02
45 #define NETSTAT_NUMERIC 0x04
46 /* Must match getopt32 option string */
47 #define NETSTAT_TCP 0x10
48 #define NETSTAT_UDP 0x20
49 #define NETSTAT_RAW 0x40
50 #define NETSTAT_UNIX 0x80
51 #define NETSTAT_ALLPROTO (NETSTAT_TCP|NETSTAT_UDP|NETSTAT_RAW|NETSTAT_UNIX)
65 TCP_CLOSING, /* now a valid state */
68 static const char *const tcp_state[] = {
84 SS_FREE = 0, /* not allocated */
85 SS_UNCONNECTED, /* unconnected to any socket */
86 SS_CONNECTING, /* in process of connecting */
87 SS_CONNECTED, /* connected to socket */
88 SS_DISCONNECTING /* in process of disconnecting */
91 #define SO_ACCEPTCON (1<<16) /* performed a listen */
92 #define SO_WAITDATA (1<<17) /* wait data to read */
93 #define SO_NOSPACE (1<<18) /* no space to write */
95 /* Standard printout size */
96 #define PRINT_IP_MAX_SIZE 23
97 #define PRINT_NET_CONN "%s %6ld %6ld %-23s %-23s %-12s"
98 #define PRINT_NET_CONN_HEADER "\nProto Recv-Q Send-Q %-23s %-23s State "
100 /* When there are IPv6 connections the IPv6 addresses will be
101 * truncated to none-recognition. The '-W' option makes the
102 * address columns wide enough to accomodate for longest possible
103 * IPv6 addresses, i.e. addresses of the form
104 * xxxx:xxxx:xxxx:xxxx:xxxx:xxxx:ddd.ddd.ddd.ddd
106 #define PRINT_IP_MAX_SIZE_WIDE 51 /* INET6_ADDRSTRLEN + 5 for the port number */
107 #define PRINT_NET_CONN_WIDE "%s %6ld %6ld %-51s %-51s %-12s"
108 #define PRINT_NET_CONN_HEADER_WIDE "\nProto Recv-Q Send-Q %-51s %-51s State "
111 #define PROGNAME_WIDTH 20
112 #define PROGNAME_WIDTH_STR "20"
113 /* PROGNAME_WIDTH chars: 12345678901234567890 */
114 #define PROGNAME_BANNER "PID/Program name "
117 struct prg_node *next;
119 char name[PROGNAME_WIDTH];
122 #define PRG_HASH_SIZE 211
126 const char *net_conn_line;
128 #if ENABLE_FEATURE_NETSTAT_PRG
129 smallint prg_cache_loaded;
130 struct prg_node *prg_hash[PRG_HASH_SIZE];
133 #define G (*ptr_to_globals)
134 #define flags (G.flags )
135 #define net_conn_line (G.net_conn_line )
136 #define prg_hash (G.prg_hash )
137 #define prg_cache_loaded (G.prg_cache_loaded)
138 #define INIT_G() do { \
139 SET_PTR_TO_GLOBALS(xzalloc(sizeof(G))); \
140 flags = NETSTAT_CONNECTED | NETSTAT_ALLPROTO; \
141 net_conn_line = PRINT_NET_CONN; \
145 #if ENABLE_FEATURE_NETSTAT_PRG
147 /* Deliberately truncating long to unsigned *int* */
148 #define PRG_HASHIT(x) ((unsigned)(x) % PRG_HASH_SIZE)
150 #define print_progname_banner() do { \
151 if (option_mask32 & OPT_prg) printf(PROGNAME_BANNER); \
154 static void prg_cache_add(long inode, char *name)
156 unsigned hi = PRG_HASHIT(inode);
157 struct prg_node **pnp, *pn;
159 prg_cache_loaded = 2;
160 for (pnp = prg_hash + hi; (pn = *pnp) != NULL; pnp = &pn->next) {
161 if (pn->inode == inode) {
162 /* Some warning should be appropriate here
163 as we got multiple processes for one i-node */
167 *pnp = xzalloc(sizeof(struct prg_node));
170 safe_strncpy(pn->name, name, PROGNAME_WIDTH);
173 static const char *prg_cache_get(long inode)
175 unsigned hi = PRG_HASHIT(inode);
178 for (pn = prg_hash[hi]; pn; pn = pn->next)
179 if (pn->inode == inode)
184 #if ENABLE_FEATURE_CLEAN_UP
185 static void prg_cache_clear(void)
187 struct prg_node **pnp, *pn;
189 for (pnp = prg_hash; pnp < prg_hash + PRG_HASH_SIZE; pnp++) {
190 while ((pn = *pnp) != NULL) {
197 #define prg_cache_clear() ((void)0)
200 static long extract_socket_inode(const char *lname)
204 if (strncmp(lname, "socket:[", sizeof("socket:[")-1) == 0) {
205 /* "socket:[12345]", extract the "12345" as inode */
206 inode = bb_strtol(lname + sizeof("socket:[")-1, (char**)&lname, 0);
209 } else if (strncmp(lname, "[0000]:", sizeof("[0000]:")-1) == 0) {
210 /* "[0000]:12345", extract the "12345" as inode */
211 inode = bb_strtol(lname + sizeof("[0000]:")-1, NULL, 0);
212 if (errno) /* not NUL terminated? */
216 #if 0 /* bb_strtol returns all-ones bit pattern on ERANGE anyway */
223 static int FAST_FUNC file_act(const char *fileName,
224 struct stat *statbuf UNUSED_PARAM,
226 int depth UNUSED_PARAM)
231 linkname = xmalloc_readlink(fileName);
232 if (linkname != NULL) {
233 inode = extract_socket_inode(linkname);
236 prg_cache_add(inode, (char *)userData);
241 static int FAST_FUNC dir_act(const char *fileName,
242 struct stat *statbuf UNUSED_PARAM,
243 void *userData UNUSED_PARAM,
246 const char *shortName;
248 char cmdline_buf[512];
251 if (depth == 0) /* "/proc" itself */
252 return TRUE; /* continue looking one level below /proc */
254 shortName = fileName + sizeof("/proc/")-1; /* point after "/proc/" */
255 if (!isdigit(shortName[0])) /* skip /proc entries whic aren't processes */
258 p = concat_path_file(fileName, "cmdline"); /* "/proc/PID/cmdline" */
259 i = open_read_close(p, cmdline_buf, sizeof(cmdline_buf) - 1);
263 cmdline_buf[i] = '\0';
264 q = concat_path_file(shortName, bb_basename(cmdline_buf)); /* "PID/argv0" */
266 /* go through all files in /proc/PID/fd */
267 p = concat_path_file(fileName, "fd");
268 i = recursive_action(p, ACTION_RECURSE | ACTION_QUIET,
269 file_act, NULL, (void *)q, 0);
275 return FALSE; /* signal permissions error to caller */
277 return SKIP; /* caller should not recurse further into this dir. */
280 static void prg_cache_load(void)
284 prg_cache_loaded = 1;
285 load_ok = recursive_action("/proc", ACTION_RECURSE | ACTION_QUIET,
286 NULL, dir_act, NULL, 0);
290 if (prg_cache_loaded == 1)
291 bb_error_msg("can't scan /proc - are you root?");
293 bb_error_msg("showing only processes with your user ID");
298 #define prg_cache_clear() ((void)0)
299 #define print_progname_banner() ((void)0)
301 #endif //ENABLE_FEATURE_NETSTAT_PRG
304 #if ENABLE_FEATURE_IPV6
305 static void build_ipv6_addr(char* local_addr, struct sockaddr_in6* localaddr)
307 char addr6[INET6_ADDRSTRLEN];
310 sscanf(local_addr, "%08X%08X%08X%08X",
311 &in6.s6_addr32[0], &in6.s6_addr32[1],
312 &in6.s6_addr32[2], &in6.s6_addr32[3]);
313 inet_ntop(AF_INET6, &in6, addr6, sizeof(addr6));
314 inet_pton(AF_INET6, addr6, (struct sockaddr *) &localaddr->sin6_addr);
316 localaddr->sin6_family = AF_INET6;
320 #if ENABLE_FEATURE_IPV6
321 static void build_ipv4_addr(char* local_addr, struct sockaddr_in6* localaddr)
323 static void build_ipv4_addr(char* local_addr, struct sockaddr_in* localaddr)
326 sscanf(local_addr, "%X",
327 &((struct sockaddr_in *) localaddr)->sin_addr.s_addr);
328 ((struct sockaddr *) localaddr)->sa_family = AF_INET;
331 static const char *get_sname(int port, const char *proto, int numeric)
336 struct servent *se = getservbyport(port, proto);
340 /* hummm, we may return static buffer here!! */
341 return itoa(ntohs(port));
344 static char *ip_port_str(struct sockaddr *addr, int port, const char *proto, int numeric)
346 char *host, *host_port;
348 /* Code which used "*" for INADDR_ANY is removed: it's ambiguous
349 * in IPv6, while "0.0.0.0" is not. */
351 host = numeric ? xmalloc_sockaddr2dotted_noport(addr)
352 : xmalloc_sockaddr2host_noport(addr);
354 host_port = xasprintf("%s:%s", host, get_sname(htons(port), proto, numeric));
360 int local_port, rem_port, state, uid;
361 #if ENABLE_FEATURE_IPV6
362 struct sockaddr_in6 localaddr, remaddr;
364 struct sockaddr_in localaddr, remaddr;
366 unsigned long rxq, txq, inode;
369 static int scan_inet_proc_line(struct inet_params *param, char *line)
372 char local_addr[64], rem_addr[64];
375 "%*d: %64[0-9A-Fa-f]:%X "
376 "%64[0-9A-Fa-f]:%X %X "
379 local_addr, ¶m->local_port,
380 rem_addr, ¶m->rem_port, ¶m->state,
381 ¶m->txq, ¶m->rxq,
382 ¶m->uid, ¶m->inode);
384 return 1; /* error */
387 if (strlen(local_addr) > 8) {
388 #if ENABLE_FEATURE_IPV6
389 build_ipv6_addr(local_addr, ¶m->localaddr);
390 build_ipv6_addr(rem_addr, ¶m->remaddr);
393 build_ipv4_addr(local_addr, ¶m->localaddr);
394 build_ipv4_addr(rem_addr, ¶m->remaddr);
399 static void print_inet_line(struct inet_params *param,
400 const char *state_str, const char *proto, int is_connected)
402 if ((is_connected && (flags & NETSTAT_CONNECTED))
403 || (!is_connected && (flags & NETSTAT_LISTENING))
405 char *l = ip_port_str(
406 (struct sockaddr *) ¶m->localaddr, param->local_port,
407 proto, flags & NETSTAT_NUMERIC);
408 char *r = ip_port_str(
409 (struct sockaddr *) ¶m->remaddr, param->rem_port,
410 proto, flags & NETSTAT_NUMERIC);
411 printf(net_conn_line,
412 proto, param->rxq, param->txq, l, r, state_str);
413 #if ENABLE_FEATURE_NETSTAT_PRG
414 if (option_mask32 & OPT_prg)
415 printf("%."PROGNAME_WIDTH_STR"s", prg_cache_get(param->inode));
423 static int FAST_FUNC tcp_do_one(char *line)
425 struct inet_params param;
427 if (scan_inet_proc_line(¶m, line))
430 print_inet_line(¶m, tcp_state[param.state], "tcp", param.rem_port);
434 #if ENABLE_FEATURE_IPV6
435 # define notnull(A) ( \
436 ( (A.sin6_family == AF_INET6) \
437 && (A.sin6_addr.s6_addr32[0] | A.sin6_addr.s6_addr32[1] | \
438 A.sin6_addr.s6_addr32[2] | A.sin6_addr.s6_addr32[3]) \
440 (A.sin6_family == AF_INET) \
441 && ((struct sockaddr_in*)&A)->sin_addr.s_addr \
445 # define notnull(A) (A.sin_addr.s_addr)
448 static int FAST_FUNC udp_do_one(char *line)
451 const char *state_str;
452 struct inet_params param;
454 if (scan_inet_proc_line(¶m, line))
457 state_str = "UNKNOWN";
458 switch (param.state) {
459 case TCP_ESTABLISHED:
460 state_str = "ESTABLISHED";
467 have_remaddr = notnull(param.remaddr);
468 print_inet_line(¶m, state_str, "udp", have_remaddr);
472 static int FAST_FUNC raw_do_one(char *line)
475 struct inet_params param;
477 if (scan_inet_proc_line(¶m, line))
480 have_remaddr = notnull(param.remaddr);
481 print_inet_line(¶m, itoa(param.state), "raw", have_remaddr);
485 static int FAST_FUNC unix_do_one(char *line)
487 unsigned long refcnt, proto, unix_flags;
491 const char *ss_proto, *ss_state, *ss_type;
494 /* 2.6.15 may report lines like "... @/tmp/fam-user-^@^@^@^@^@^@^@..."
495 * Other users report long lines filled by NUL bytes.
496 * (those ^@ are NUL bytes too). We see them as empty lines. */
500 path_ofs = 0; /* paranoia */
501 num = sscanf(line, "%*p: %lX %lX %lX %X %X %lu %n",
502 &refcnt, &proto, &unix_flags, &type, &state, &inode, &path_ofs);
504 return 1; /* error */
506 if ((flags & (NETSTAT_LISTENING|NETSTAT_CONNECTED)) != (NETSTAT_LISTENING|NETSTAT_CONNECTED)) {
507 if ((state == SS_UNCONNECTED) && (unix_flags & SO_ACCEPTCON)) {
508 if (!(flags & NETSTAT_LISTENING))
511 if (!(flags & NETSTAT_CONNECTED))
538 ss_type = "SEQPACKET";
550 * Unconnected sockets may be listening
553 if (unix_flags & SO_ACCEPTCON) {
554 ss_state = "LISTENING";
560 ss_state = "CONNECTING";
563 ss_state = "CONNECTED";
565 case SS_DISCONNECTING:
566 ss_state = "DISCONNECTING";
569 ss_state = "UNKNOWN";
572 strcpy(ss_flags, "[ ");
573 if (unix_flags & SO_ACCEPTCON)
574 strcat(ss_flags, "ACC ");
575 if (unix_flags & SO_WAITDATA)
576 strcat(ss_flags, "W ");
577 if (unix_flags & SO_NOSPACE)
578 strcat(ss_flags, "N ");
579 strcat(ss_flags, "]");
581 printf("%-5s %-6ld %-11s %-10s %-13s %6lu ",
582 ss_proto, refcnt, ss_flags, ss_type, ss_state, inode
585 #if ENABLE_FEATURE_NETSTAT_PRG
586 if (option_mask32 & OPT_prg)
587 printf("%-"PROGNAME_WIDTH_STR"s", prg_cache_get(inode));
590 /* TODO: currently we stop at first NUL byte. Is it a problem? */
592 *strchrnul(line, '\n') = '\0';
594 fputc_printable(*line++, stdout);
599 static void do_info(const char *file, int FAST_FUNC (*proc)(char *))
605 /* _stdin is just to save "r" param */
606 procinfo = fopen_or_warn_stdin(file);
607 if (procinfo == NULL) {
611 /* Why xmalloc_fgets_str? because it doesn't stop on NULs */
612 while ((buffer = xmalloc_fgets_str(procinfo, "\n")) != NULL) {
613 /* line 0 is skipped */
614 if (lnr && proc(buffer))
615 bb_error_msg("%s: bogus data on line %d", file, lnr + 1);
622 int netstat_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
623 int netstat_main(int argc UNUSED_PARAM, char **argv)
625 const char *net_conn_line_header = PRINT_NET_CONN_HEADER;
630 /* Option string must match NETSTAT_xxx constants */
631 opt = getopt32(argv, NETSTAT_OPTS);
632 if (opt & 0x1) { // -l
633 flags &= ~NETSTAT_CONNECTED;
634 flags |= NETSTAT_LISTENING;
636 if (opt & 0x2) flags |= NETSTAT_LISTENING | NETSTAT_CONNECTED; // -a
637 //if (opt & 0x4) // -e
638 if (opt & 0x8) flags |= NETSTAT_NUMERIC; // -n
639 //if (opt & 0x10) // -t: NETSTAT_TCP
640 //if (opt & 0x20) // -u: NETSTAT_UDP
641 //if (opt & 0x40) // -w: NETSTAT_RAW
642 //if (opt & 0x80) // -x: NETSTAT_UNIX
643 if (opt & OPT_route) { // -r
645 bb_displayroutes(flags & NETSTAT_NUMERIC, !(opt & OPT_extended));
651 if (opt & OPT_wide) { // -W
652 net_conn_line = PRINT_NET_CONN_WIDE;
653 net_conn_line_header = PRINT_NET_CONN_HEADER_WIDE;
655 #if ENABLE_FEATURE_NETSTAT_PRG
656 if (opt & OPT_prg) { // -p
661 opt &= NETSTAT_ALLPROTO;
663 flags &= ~NETSTAT_ALLPROTO;
666 if (flags & (NETSTAT_TCP|NETSTAT_UDP|NETSTAT_RAW)) {
667 printf("Active Internet connections "); /* xxx */
669 if ((flags & (NETSTAT_LISTENING|NETSTAT_CONNECTED)) == (NETSTAT_LISTENING|NETSTAT_CONNECTED))
670 printf("(servers and established)");
671 else if (flags & NETSTAT_LISTENING)
672 printf("(only servers)");
674 printf("(w/o servers)");
675 printf(net_conn_line_header, "Local Address", "Foreign Address");
676 print_progname_banner();
679 if (flags & NETSTAT_TCP) {
680 do_info("/proc/net/tcp", tcp_do_one);
681 #if ENABLE_FEATURE_IPV6
682 do_info("/proc/net/tcp6", tcp_do_one);
685 if (flags & NETSTAT_UDP) {
686 do_info("/proc/net/udp", udp_do_one);
687 #if ENABLE_FEATURE_IPV6
688 do_info("/proc/net/udp6", udp_do_one);
691 if (flags & NETSTAT_RAW) {
692 do_info("/proc/net/raw", raw_do_one);
693 #if ENABLE_FEATURE_IPV6
694 do_info("/proc/net/raw6", raw_do_one);
697 if (flags & NETSTAT_UNIX) {
698 printf("Active UNIX domain sockets ");
699 if ((flags & (NETSTAT_LISTENING|NETSTAT_CONNECTED)) == (NETSTAT_LISTENING|NETSTAT_CONNECTED))
700 printf("(servers and established)");
701 else if (flags & NETSTAT_LISTENING)
702 printf("(only servers)");
704 printf("(w/o servers)");
705 printf("\nProto RefCnt Flags Type State I-Node ");
706 print_progname_banner();
708 do_info("/proc/net/unix", unix_do_one);