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 source tree.
16 //config:config NETSTAT
17 //config: bool "netstat (10 kb)"
19 //config: select PLATFORM_LINUX
21 //config: netstat prints information about the Linux networking subsystem.
23 //config:config FEATURE_NETSTAT_WIDE
24 //config: bool "Enable wide output"
26 //config: depends on NETSTAT
28 //config: Add support for wide columns. Useful when displaying IPv6 addresses
29 //config: (-W option).
31 //config:config FEATURE_NETSTAT_PRG
32 //config: bool "Enable PID/Program name output"
34 //config: depends on NETSTAT
36 //config: Add support for -p flag to print out PID and program name.
37 //config: +700 bytes of code.
39 //applet:IF_NETSTAT(APPLET(netstat, BB_DIR_BIN, BB_SUID_DROP))
41 //kbuild:lib-$(CONFIG_NETSTAT) += netstat.o
44 #include "inet_common.h"
46 //usage:#define netstat_trivial_usage
47 //usage: "[-"IF_ROUTE("r")"al] [-tuwx] [-en"IF_FEATURE_NETSTAT_WIDE("W")IF_FEATURE_NETSTAT_PRG("p")"]"
48 //usage:#define netstat_full_usage "\n\n"
49 //usage: "Display networking information\n"
51 //usage: "\n -r Routing table"
53 //usage: "\n -a All sockets"
54 //usage: "\n -l Listening sockets"
55 //usage: "\n Else: connected sockets"
56 //usage: "\n -t TCP sockets"
57 //usage: "\n -u UDP sockets"
58 //usage: "\n -w Raw sockets"
59 //usage: "\n -x Unix sockets"
60 //usage: "\n Else: all socket types"
61 //usage: "\n -e Other/more information"
62 //usage: "\n -n Don't resolve names"
63 //usage: IF_FEATURE_NETSTAT_WIDE(
64 //usage: "\n -W Wide display"
66 //usage: IF_FEATURE_NETSTAT_PRG(
67 //usage: "\n -p Show PID/program name for sockets"
70 #define NETSTAT_OPTS "laentuwx" \
72 IF_FEATURE_NETSTAT_WIDE("W") \
73 IF_FEATURE_NETSTAT_PRG( "p")
76 OPT_sock_listen = 1 << 0, // l
77 OPT_sock_all = 1 << 1, // a
78 OPT_extended = 1 << 2, // e
79 OPT_noresolve = 1 << 3, // n
80 OPT_sock_tcp = 1 << 4, // t
81 OPT_sock_udp = 1 << 5, // u
82 OPT_sock_raw = 1 << 6, // w
83 OPT_sock_unix = 1 << 7, // x
85 IF_ROUTE( OPTBIT_ROUTE,)
86 IF_FEATURE_NETSTAT_WIDE(OPTBIT_WIDE ,)
87 IF_FEATURE_NETSTAT_PRG( OPTBIT_PRG ,)
88 OPT_route = IF_ROUTE( (1 << OPTBIT_ROUTE)) + 0, // r
89 OPT_wide = IF_FEATURE_NETSTAT_WIDE((1 << OPTBIT_WIDE )) + 0, // W
90 OPT_prg = IF_FEATURE_NETSTAT_PRG( (1 << OPTBIT_PRG )) + 0, // p
93 #define NETSTAT_CONNECTED 0x01
94 #define NETSTAT_LISTENING 0x02
95 #define NETSTAT_NUMERIC 0x04
96 /* Must match getopt32 option string */
97 #define NETSTAT_TCP 0x10
98 #define NETSTAT_UDP 0x20
99 #define NETSTAT_RAW 0x40
100 #define NETSTAT_UNIX 0x80
101 #define NETSTAT_ALLPROTO (NETSTAT_TCP|NETSTAT_UDP|NETSTAT_RAW|NETSTAT_UNIX)
115 TCP_CLOSING, /* now a valid state */
118 static const char *const tcp_state[] = {
134 SS_FREE = 0, /* not allocated */
135 SS_UNCONNECTED, /* unconnected to any socket */
136 SS_CONNECTING, /* in process of connecting */
137 SS_CONNECTED, /* connected to socket */
138 SS_DISCONNECTING /* in process of disconnecting */
141 #define SO_ACCEPTCON (1<<16) /* performed a listen */
142 #define SO_WAITDATA (1<<17) /* wait data to read */
143 #define SO_NOSPACE (1<<18) /* no space to write */
145 #define ADDR_NORMAL_WIDTH 23
146 /* When there are IPv6 connections the IPv6 addresses will be
147 * truncated to none-recognition. The '-W' option makes the
148 * address columns wide enough to accommodate for longest possible
149 * IPv6 addresses, i.e. addresses of the form
150 * xxxx:xxxx:xxxx:xxxx:xxxx:xxxx:ddd.ddd.ddd.ddd
152 #define ADDR_WIDE 51 /* INET6_ADDRSTRLEN + 5 for the port number */
153 #if ENABLE_FEATURE_NETSTAT_WIDE
154 # define FMT_NET_CONN_DATA "%s %6lu %6lu %-*s %-*s %-12s"
155 # define FMT_NET_CONN_HEADER "\nProto Recv-Q Send-Q %-*s %-*s State %s\n"
157 # define FMT_NET_CONN_DATA "%s %6lu %6lu %-23s %-23s %-12s"
158 # define FMT_NET_CONN_HEADER "\nProto Recv-Q Send-Q %-23s %-23s State %s\n"
161 #define PROGNAME_WIDTH 20
162 #define PROGNAME_WIDTH_STR "20"
163 /* PROGNAME_WIDTH chars: 12345678901234567890 */
164 #define PROGNAME_BANNER "PID/Program name "
167 struct prg_node *next;
169 char name[PROGNAME_WIDTH];
172 #define PRG_HASH_SIZE 211
176 #if ENABLE_FEATURE_NETSTAT_PRG
177 smallint prg_cache_loaded;
178 struct prg_node *prg_hash[PRG_HASH_SIZE];
180 #if ENABLE_FEATURE_NETSTAT_PRG
181 const char *progname_banner;
183 #if ENABLE_FEATURE_NETSTAT_WIDE
187 #define G (*ptr_to_globals)
188 #define flags (G.flags )
189 #define prg_cache_loaded (G.prg_cache_loaded)
190 #define prg_hash (G.prg_hash )
191 #if ENABLE_FEATURE_NETSTAT_PRG
192 # define progname_banner (G.progname_banner )
194 # define progname_banner ""
196 #define INIT_G() do { \
197 SET_PTR_TO_GLOBALS(xzalloc(sizeof(G))); \
198 flags = NETSTAT_CONNECTED | NETSTAT_ALLPROTO; \
202 #if ENABLE_FEATURE_NETSTAT_PRG
204 /* Deliberately truncating long to unsigned *int* */
205 #define PRG_HASHIT(x) ((unsigned)(x) % PRG_HASH_SIZE)
207 static void prg_cache_add(long inode, char *name)
209 unsigned hi = PRG_HASHIT(inode);
210 struct prg_node **pnp, *pn;
212 prg_cache_loaded = 2;
213 for (pnp = prg_hash + hi; (pn = *pnp) != NULL; pnp = &pn->next) {
214 if (pn->inode == inode) {
215 /* Some warning should be appropriate here
216 * as we got multiple processes for one i-node */
220 *pnp = xzalloc(sizeof(struct prg_node));
223 safe_strncpy(pn->name, name, PROGNAME_WIDTH);
226 static const char *prg_cache_get(long inode)
228 unsigned hi = PRG_HASHIT(inode);
231 for (pn = prg_hash[hi]; pn; pn = pn->next)
232 if (pn->inode == inode)
237 #if ENABLE_FEATURE_CLEAN_UP
238 static void prg_cache_clear(void)
240 struct prg_node **pnp, *pn;
242 for (pnp = prg_hash; pnp < prg_hash + PRG_HASH_SIZE; pnp++) {
243 while ((pn = *pnp) != NULL) {
250 #define prg_cache_clear() ((void)0)
253 static long extract_socket_inode(const char *lname)
257 if (is_prefixed_with(lname, "socket:[")) {
258 /* "socket:[12345]", extract the "12345" as inode */
259 inode = bb_strtoul(lname + sizeof("socket:[")-1, (char**)&lname, 0);
262 } else if (is_prefixed_with(lname, "[0000]:")) {
263 /* "[0000]:12345", extract the "12345" as inode */
264 inode = bb_strtoul(lname + sizeof("[0000]:")-1, NULL, 0);
265 if (errno) /* not NUL terminated? */
269 #if 0 /* bb_strtol returns all-ones bit pattern on ERANGE anyway */
276 static int FAST_FUNC add_to_prg_cache_if_socket(const char *fileName,
277 struct stat *statbuf UNUSED_PARAM,
278 void *pid_slash_progname,
279 int depth UNUSED_PARAM)
284 linkname = xmalloc_readlink(fileName);
285 if (linkname != NULL) {
286 inode = extract_socket_inode(linkname);
289 prg_cache_add(inode, (char *)pid_slash_progname);
294 static int FAST_FUNC dir_act(const char *fileName,
295 struct stat *statbuf UNUSED_PARAM,
296 void *userData UNUSED_PARAM,
300 char *pid_slash_progname;
301 char proc_pid_fname[sizeof("/proc/%u/cmdline") + sizeof(long)*3];
302 char cmdline_buf[512];
305 if (depth == 0) /* "/proc" itself */
306 return TRUE; /* continue looking one level below /proc */
308 pid = fileName + sizeof("/proc/")-1; /* point after "/proc/" */
309 if (!isdigit(pid[0])) /* skip /proc entries which aren't processes */
312 len = snprintf(proc_pid_fname, sizeof(proc_pid_fname), "%s/cmdline", fileName);
313 n = open_read_close(proc_pid_fname, cmdline_buf, sizeof(cmdline_buf) - 1);
316 cmdline_buf[n] = '\0';
318 /* go through all files in /proc/PID/fd and check whether they are sockets */
319 strcpy(proc_pid_fname + len - (sizeof("cmdline")-1), "fd");
320 pid_slash_progname = concat_path_file(pid, bb_basename(cmdline_buf)); /* "PID/argv0" */
321 n = recursive_action(proc_pid_fname,
322 ACTION_RECURSE | ACTION_QUIET,
323 add_to_prg_cache_if_socket,
325 (void *)pid_slash_progname,
327 free(pid_slash_progname);
330 return FALSE; /* signal permissions error to caller */
332 return SKIP; /* caller should not recurse further into this dir */
335 static void prg_cache_load(void)
339 prg_cache_loaded = 1;
340 load_ok = recursive_action("/proc", ACTION_RECURSE | ACTION_QUIET,
341 NULL, dir_act, NULL, 0);
345 if (prg_cache_loaded == 1)
346 bb_error_msg("can't scan /proc - are you root?");
348 bb_error_msg("showing only processes with your user ID");
353 #define prg_cache_clear() ((void)0)
355 #endif //ENABLE_FEATURE_NETSTAT_PRG
358 #if ENABLE_FEATURE_IPV6
359 static void build_ipv6_addr(char* local_addr, struct sockaddr_in6* localaddr)
361 char addr6[INET6_ADDRSTRLEN];
364 sscanf(local_addr, "%08X%08X%08X%08X",
365 &in6.s6_addr32[0], &in6.s6_addr32[1],
366 &in6.s6_addr32[2], &in6.s6_addr32[3]);
367 inet_ntop(AF_INET6, &in6, addr6, sizeof(addr6));
368 inet_pton(AF_INET6, addr6, &localaddr->sin6_addr);
370 localaddr->sin6_family = AF_INET6;
374 static void build_ipv4_addr(char* local_addr, struct sockaddr_in* localaddr)
376 sscanf(local_addr, "%X", &localaddr->sin_addr.s_addr);
377 localaddr->sin_family = AF_INET;
380 static const char *get_sname(int port, const char *proto, int numeric)
385 struct servent *se = getservbyport(port, proto);
389 /* hummm, we may return static buffer here!! */
390 return itoa(ntohs(port));
393 static char *ip_port_str(struct sockaddr *addr, int port, const char *proto, int numeric)
395 char *host, *host_port;
397 /* Code which used "*" for INADDR_ANY is removed: it's ambiguous
398 * in IPv6, while "0.0.0.0" is not. */
400 host = numeric ? xmalloc_sockaddr2dotted_noport(addr)
401 : xmalloc_sockaddr2host_noport(addr);
403 host_port = xasprintf("%s:%s", host, get_sname(htons(port), proto, numeric));
409 int local_port, rem_port, state, uid;
412 struct sockaddr_in sin;
413 #if ENABLE_FEATURE_IPV6
414 struct sockaddr_in6 sin6;
416 } localaddr, remaddr;
417 unsigned long rxq, txq, inode;
420 static int scan_inet_proc_line(struct inet_params *param, char *line)
423 /* IPv6 /proc files use 32-char hex representation
424 * of IPv6 address, followed by :PORT_IN_HEX
426 char local_addr[33], rem_addr[33]; /* 32 + 1 for NUL */
429 "%*d: %32[0-9A-Fa-f]:%X "
430 "%32[0-9A-Fa-f]:%X %X "
433 local_addr, ¶m->local_port,
434 rem_addr, ¶m->rem_port, ¶m->state,
435 ¶m->txq, ¶m->rxq,
436 ¶m->uid, ¶m->inode);
438 return 1; /* error */
441 if (strlen(local_addr) > 8) {
442 #if ENABLE_FEATURE_IPV6
443 build_ipv6_addr(local_addr, ¶m->localaddr.sin6);
444 build_ipv6_addr(rem_addr, ¶m->remaddr.sin6);
447 build_ipv4_addr(local_addr, ¶m->localaddr.sin);
448 build_ipv4_addr(rem_addr, ¶m->remaddr.sin);
453 static void print_inet_line(struct inet_params *param,
454 const char *state_str, const char *proto, int is_connected)
456 if ((is_connected && (flags & NETSTAT_CONNECTED))
457 || (!is_connected && (flags & NETSTAT_LISTENING))
459 char *l = ip_port_str(
460 ¶m->localaddr.sa, param->local_port,
461 proto, flags & NETSTAT_NUMERIC);
462 char *r = ip_port_str(
463 ¶m->remaddr.sa, param->rem_port,
464 proto, flags & NETSTAT_NUMERIC);
465 printf(FMT_NET_CONN_DATA,
466 proto, param->rxq, param->txq,
467 IF_FEATURE_NETSTAT_WIDE(G.addr_width,) l,
468 IF_FEATURE_NETSTAT_WIDE(G.addr_width,) r,
470 #if ENABLE_FEATURE_NETSTAT_PRG
471 if (option_mask32 & OPT_prg)
472 printf("%."PROGNAME_WIDTH_STR"s", prg_cache_get(param->inode));
480 static int FAST_FUNC tcp_do_one(char *line)
482 struct inet_params param;
484 memset(¶m, 0, sizeof(param));
485 if (scan_inet_proc_line(¶m, line))
488 print_inet_line(¶m, tcp_state[param.state], "tcp", param.rem_port);
492 #if ENABLE_FEATURE_IPV6
493 # define NOT_NULL_ADDR(A) ( \
494 ( (A.sa.sa_family == AF_INET6) \
495 && (A.sin6.sin6_addr.s6_addr32[0] | A.sin6.sin6_addr.s6_addr32[1] | \
496 A.sin6.sin6_addr.s6_addr32[2] | A.sin6.sin6_addr.s6_addr32[3]) \
498 (A.sa.sa_family == AF_INET) \
499 && A.sin.sin_addr.s_addr != 0 \
503 # define NOT_NULL_ADDR(A) (A.sin.sin_addr.s_addr)
506 static int FAST_FUNC udp_do_one(char *line)
509 const char *state_str;
510 struct inet_params param;
512 memset(¶m, 0, sizeof(param)); /* otherwise we display garbage IPv6 scope_ids */
513 if (scan_inet_proc_line(¶m, line))
516 state_str = "UNKNOWN";
517 switch (param.state) {
518 case TCP_ESTABLISHED:
519 state_str = "ESTABLISHED";
526 have_remaddr = NOT_NULL_ADDR(param.remaddr);
527 print_inet_line(¶m, state_str, "udp", have_remaddr);
531 static int FAST_FUNC raw_do_one(char *line)
534 struct inet_params param;
536 if (scan_inet_proc_line(¶m, line))
539 have_remaddr = NOT_NULL_ADDR(param.remaddr);
540 print_inet_line(¶m, itoa(param.state), "raw", have_remaddr);
544 static int FAST_FUNC unix_do_one(char *line)
546 unsigned long refcnt, proto, unix_flags;
550 const char *ss_proto, *ss_state, *ss_type;
553 /* 2.6.15 may report lines like "... @/tmp/fam-user-^@^@^@^@^@^@^@..."
554 * Other users report long lines filled by NUL bytes.
555 * (those ^@ are NUL bytes too). We see them as empty lines. */
559 path_ofs = 0; /* paranoia */
560 num = sscanf(line, "%*p: %lX %lX %lX %X %X %lu %n",
561 &refcnt, &proto, &unix_flags, &type, &state, &inode, &path_ofs);
563 return 1; /* error */
565 if ((flags & (NETSTAT_LISTENING|NETSTAT_CONNECTED)) != (NETSTAT_LISTENING|NETSTAT_CONNECTED)) {
566 if ((state == SS_UNCONNECTED) && (unix_flags & SO_ACCEPTCON)) {
567 if (!(flags & NETSTAT_LISTENING))
570 if (!(flags & NETSTAT_CONNECTED))
597 ss_type = "SEQPACKET";
609 * Unconnected sockets may be listening
612 if (unix_flags & SO_ACCEPTCON) {
613 ss_state = "LISTENING";
619 ss_state = "CONNECTING";
622 ss_state = "CONNECTED";
624 case SS_DISCONNECTING:
625 ss_state = "DISCONNECTING";
628 ss_state = "UNKNOWN";
631 strcpy(ss_flags, "[ ");
632 if (unix_flags & SO_ACCEPTCON)
633 strcat(ss_flags, "ACC ");
634 if (unix_flags & SO_WAITDATA)
635 strcat(ss_flags, "W ");
636 if (unix_flags & SO_NOSPACE)
637 strcat(ss_flags, "N ");
638 strcat(ss_flags, "]");
640 printf("%-5s %-6lu %-11s %-10s %-13s %6lu ",
641 ss_proto, refcnt, ss_flags, ss_type, ss_state, inode
644 #if ENABLE_FEATURE_NETSTAT_PRG
645 if (option_mask32 & OPT_prg)
646 printf("%-"PROGNAME_WIDTH_STR"s", prg_cache_get(inode));
649 /* TODO: currently we stop at first NUL byte. Is it a problem? */
653 fputc_printable(*line++, stdout);
658 static void do_info(const char *file, int FAST_FUNC (*proc)(char *))
664 /* _stdin is just to save "r" param */
665 procinfo = fopen_or_warn_stdin(file);
666 if (procinfo == NULL) {
670 /* Why xmalloc_fgets_str? because it doesn't stop on NULs */
671 while ((buffer = xmalloc_fgets_str(procinfo, "\n")) != NULL) {
672 /* line 0 is skipped */
673 if (lnr && proc(buffer))
674 bb_error_msg("%s: bogus data on line %d", file, lnr + 1);
681 int netstat_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
682 int netstat_main(int argc UNUSED_PARAM, char **argv)
688 /* Option string must match NETSTAT_xxx constants */
689 opt = getopt32(argv, NETSTAT_OPTS);
690 if (opt & OPT_sock_listen) { // -l
691 flags &= ~NETSTAT_CONNECTED;
692 flags |= NETSTAT_LISTENING;
694 if (opt & OPT_sock_all) flags |= NETSTAT_LISTENING | NETSTAT_CONNECTED; // -a
695 //if (opt & OPT_extended) // -e
696 if (opt & OPT_noresolve) flags |= NETSTAT_NUMERIC; // -n
697 //if (opt & OPT_sock_tcp) // -t: NETSTAT_TCP
698 //if (opt & OPT_sock_udp) // -u: NETSTAT_UDP
699 //if (opt & OPT_sock_raw) // -w: NETSTAT_RAW
700 //if (opt & OPT_sock_unix) // -x: NETSTAT_UNIX
702 if (opt & OPT_route) { // -r
703 bb_displayroutes(flags & NETSTAT_NUMERIC, !(opt & OPT_extended));
707 #if ENABLE_FEATURE_NETSTAT_WIDE
708 G.addr_width = ADDR_NORMAL_WIDTH;
709 if (opt & OPT_wide) { // -W
710 G.addr_width = ADDR_WIDE;
713 #if ENABLE_FEATURE_NETSTAT_PRG
714 progname_banner = "";
715 if (opt & OPT_prg) { // -p
716 progname_banner = PROGNAME_BANNER;
721 opt &= NETSTAT_ALLPROTO;
723 flags &= ~NETSTAT_ALLPROTO;
726 if (flags & (NETSTAT_TCP|NETSTAT_UDP|NETSTAT_RAW)) {
727 printf("Active Internet connections "); /* xxx */
729 if ((flags & (NETSTAT_LISTENING|NETSTAT_CONNECTED)) == (NETSTAT_LISTENING|NETSTAT_CONNECTED))
730 printf("(servers and established)");
731 else if (flags & NETSTAT_LISTENING)
732 printf("(only servers)");
734 printf("(w/o servers)");
735 printf(FMT_NET_CONN_HEADER,
736 IF_FEATURE_NETSTAT_WIDE(G.addr_width,) "Local Address",
737 IF_FEATURE_NETSTAT_WIDE(G.addr_width,) "Foreign Address",
741 if (flags & NETSTAT_TCP) {
742 do_info("/proc/net/tcp", tcp_do_one);
743 #if ENABLE_FEATURE_IPV6
744 do_info("/proc/net/tcp6", tcp_do_one);
747 if (flags & NETSTAT_UDP) {
748 do_info("/proc/net/udp", udp_do_one);
749 #if ENABLE_FEATURE_IPV6
750 do_info("/proc/net/udp6", udp_do_one);
753 if (flags & NETSTAT_RAW) {
754 do_info("/proc/net/raw", raw_do_one);
755 #if ENABLE_FEATURE_IPV6
756 do_info("/proc/net/raw6", raw_do_one);
759 if (flags & NETSTAT_UNIX) {
760 printf("Active UNIX domain sockets ");
761 if ((flags & (NETSTAT_LISTENING|NETSTAT_CONNECTED)) == (NETSTAT_LISTENING|NETSTAT_CONNECTED))
762 printf("(servers and established)");
763 else if (flags & NETSTAT_LISTENING)
764 printf("(only servers)");
766 printf("(w/o servers)");
767 printf("\nProto RefCnt Flags Type State I-Node %sPath\n", progname_banner);
768 do_info("/proc/net/unix", unix_do_one);