netstat.c 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772
  1. /* vi: set sw=4 ts=4: */
  2. /*
  3. * Mini netstat implementation(s) for busybox
  4. * based in part on the netstat implementation from net-tools.
  5. *
  6. * Copyright (C) 2002 by Bart Visscher <magick@linux-fan.com>
  7. *
  8. * 2002-04-20
  9. * IPV6 support added by Bart Visscher <magick@linux-fan.com>
  10. *
  11. * 2008-07-10
  12. * optional '-p' flag support ported from net-tools by G. Somlo <somlo@cmu.edu>
  13. *
  14. * Licensed under GPLv2 or later, see file LICENSE in this source tree.
  15. */
  16. //config:config NETSTAT
  17. //config: bool "netstat"
  18. //config: default y
  19. //config: select PLATFORM_LINUX
  20. //config: help
  21. //config: netstat prints information about the Linux networking subsystem.
  22. //config:
  23. //config:config FEATURE_NETSTAT_WIDE
  24. //config: bool "Enable wide output"
  25. //config: default y
  26. //config: depends on NETSTAT
  27. //config: help
  28. //config: Add support for wide columns. Useful when displaying IPv6 addresses
  29. //config: (-W option).
  30. //config:
  31. //config:config FEATURE_NETSTAT_PRG
  32. //config: bool "Enable PID/Program name output"
  33. //config: default y
  34. //config: depends on NETSTAT
  35. //config: help
  36. //config: Add support for -p flag to print out PID and program name.
  37. //config: +700 bytes of code.
  38. //applet:IF_NETSTAT(APPLET(netstat, BB_DIR_BIN, BB_SUID_DROP))
  39. //kbuild:lib-$(CONFIG_NETSTAT) += netstat.o
  40. #include "libbb.h"
  41. #include "inet_common.h"
  42. //usage:#define netstat_trivial_usage
  43. //usage: "[-"IF_ROUTE("r")"al] [-tuwx] [-en"IF_FEATURE_NETSTAT_WIDE("W")IF_FEATURE_NETSTAT_PRG("p")"]"
  44. //usage:#define netstat_full_usage "\n\n"
  45. //usage: "Display networking information\n"
  46. //usage: IF_ROUTE(
  47. //usage: "\n -r Routing table"
  48. //usage: )
  49. //usage: "\n -a All sockets"
  50. //usage: "\n -l Listening sockets"
  51. //usage: "\n Else: connected sockets"
  52. //usage: "\n -t TCP sockets"
  53. //usage: "\n -u UDP sockets"
  54. //usage: "\n -w Raw sockets"
  55. //usage: "\n -x Unix sockets"
  56. //usage: "\n Else: all socket types"
  57. //usage: "\n -e Other/more information"
  58. //usage: "\n -n Don't resolve names"
  59. //usage: IF_FEATURE_NETSTAT_WIDE(
  60. //usage: "\n -W Wide display"
  61. //usage: )
  62. //usage: IF_FEATURE_NETSTAT_PRG(
  63. //usage: "\n -p Show PID/program name for sockets"
  64. //usage: )
  65. #define NETSTAT_OPTS "laentuwx" \
  66. IF_ROUTE( "r") \
  67. IF_FEATURE_NETSTAT_WIDE("W") \
  68. IF_FEATURE_NETSTAT_PRG( "p")
  69. enum {
  70. OPT_sock_listen = 1 << 0, // l
  71. OPT_sock_all = 1 << 1, // a
  72. OPT_extended = 1 << 2, // e
  73. OPT_noresolve = 1 << 3, // n
  74. OPT_sock_tcp = 1 << 4, // t
  75. OPT_sock_udp = 1 << 5, // u
  76. OPT_sock_raw = 1 << 6, // w
  77. OPT_sock_unix = 1 << 7, // x
  78. OPTBIT_x = 7,
  79. IF_ROUTE( OPTBIT_ROUTE,)
  80. IF_FEATURE_NETSTAT_WIDE(OPTBIT_WIDE ,)
  81. IF_FEATURE_NETSTAT_PRG( OPTBIT_PRG ,)
  82. OPT_route = IF_ROUTE( (1 << OPTBIT_ROUTE)) + 0, // r
  83. OPT_wide = IF_FEATURE_NETSTAT_WIDE((1 << OPTBIT_WIDE )) + 0, // W
  84. OPT_prg = IF_FEATURE_NETSTAT_PRG( (1 << OPTBIT_PRG )) + 0, // p
  85. };
  86. #define NETSTAT_CONNECTED 0x01
  87. #define NETSTAT_LISTENING 0x02
  88. #define NETSTAT_NUMERIC 0x04
  89. /* Must match getopt32 option string */
  90. #define NETSTAT_TCP 0x10
  91. #define NETSTAT_UDP 0x20
  92. #define NETSTAT_RAW 0x40
  93. #define NETSTAT_UNIX 0x80
  94. #define NETSTAT_ALLPROTO (NETSTAT_TCP|NETSTAT_UDP|NETSTAT_RAW|NETSTAT_UNIX)
  95. enum {
  96. TCP_ESTABLISHED = 1,
  97. TCP_SYN_SENT,
  98. TCP_SYN_RECV,
  99. TCP_FIN_WAIT1,
  100. TCP_FIN_WAIT2,
  101. TCP_TIME_WAIT,
  102. TCP_CLOSE,
  103. TCP_CLOSE_WAIT,
  104. TCP_LAST_ACK,
  105. TCP_LISTEN,
  106. TCP_CLOSING, /* now a valid state */
  107. };
  108. static const char *const tcp_state[] = {
  109. "",
  110. "ESTABLISHED",
  111. "SYN_SENT",
  112. "SYN_RECV",
  113. "FIN_WAIT1",
  114. "FIN_WAIT2",
  115. "TIME_WAIT",
  116. "CLOSE",
  117. "CLOSE_WAIT",
  118. "LAST_ACK",
  119. "LISTEN",
  120. "CLOSING"
  121. };
  122. typedef enum {
  123. SS_FREE = 0, /* not allocated */
  124. SS_UNCONNECTED, /* unconnected to any socket */
  125. SS_CONNECTING, /* in process of connecting */
  126. SS_CONNECTED, /* connected to socket */
  127. SS_DISCONNECTING /* in process of disconnecting */
  128. } socket_state;
  129. #define SO_ACCEPTCON (1<<16) /* performed a listen */
  130. #define SO_WAITDATA (1<<17) /* wait data to read */
  131. #define SO_NOSPACE (1<<18) /* no space to write */
  132. #define ADDR_NORMAL_WIDTH 23
  133. /* When there are IPv6 connections the IPv6 addresses will be
  134. * truncated to none-recognition. The '-W' option makes the
  135. * address columns wide enough to accommodate for longest possible
  136. * IPv6 addresses, i.e. addresses of the form
  137. * xxxx:xxxx:xxxx:xxxx:xxxx:xxxx:ddd.ddd.ddd.ddd
  138. */
  139. #define ADDR_WIDE 51 /* INET6_ADDRSTRLEN + 5 for the port number */
  140. #if ENABLE_FEATURE_NETSTAT_WIDE
  141. # define FMT_NET_CONN_DATA "%s %6lu %6lu %-*s %-*s %-12s"
  142. # define FMT_NET_CONN_HEADER "\nProto Recv-Q Send-Q %-*s %-*s State %s\n"
  143. #else
  144. # define FMT_NET_CONN_DATA "%s %6lu %6lu %-23s %-23s %-12s"
  145. # define FMT_NET_CONN_HEADER "\nProto Recv-Q Send-Q %-23s %-23s State %s\n"
  146. #endif
  147. #define PROGNAME_WIDTH 20
  148. #define PROGNAME_WIDTH_STR "20"
  149. /* PROGNAME_WIDTH chars: 12345678901234567890 */
  150. #define PROGNAME_BANNER "PID/Program name "
  151. struct prg_node {
  152. struct prg_node *next;
  153. long inode;
  154. char name[PROGNAME_WIDTH];
  155. };
  156. #define PRG_HASH_SIZE 211
  157. struct globals {
  158. smallint flags;
  159. #if ENABLE_FEATURE_NETSTAT_PRG
  160. smallint prg_cache_loaded;
  161. struct prg_node *prg_hash[PRG_HASH_SIZE];
  162. #endif
  163. #if ENABLE_FEATURE_NETSTAT_PRG
  164. const char *progname_banner;
  165. #endif
  166. #if ENABLE_FEATURE_NETSTAT_WIDE
  167. unsigned addr_width;
  168. #endif
  169. };
  170. #define G (*ptr_to_globals)
  171. #define flags (G.flags )
  172. #define prg_cache_loaded (G.prg_cache_loaded)
  173. #define prg_hash (G.prg_hash )
  174. #if ENABLE_FEATURE_NETSTAT_PRG
  175. # define progname_banner (G.progname_banner )
  176. #else
  177. # define progname_banner ""
  178. #endif
  179. #define INIT_G() do { \
  180. SET_PTR_TO_GLOBALS(xzalloc(sizeof(G))); \
  181. flags = NETSTAT_CONNECTED | NETSTAT_ALLPROTO; \
  182. } while (0)
  183. #if ENABLE_FEATURE_NETSTAT_PRG
  184. /* Deliberately truncating long to unsigned *int* */
  185. #define PRG_HASHIT(x) ((unsigned)(x) % PRG_HASH_SIZE)
  186. static void prg_cache_add(long inode, char *name)
  187. {
  188. unsigned hi = PRG_HASHIT(inode);
  189. struct prg_node **pnp, *pn;
  190. prg_cache_loaded = 2;
  191. for (pnp = prg_hash + hi; (pn = *pnp) != NULL; pnp = &pn->next) {
  192. if (pn->inode == inode) {
  193. /* Some warning should be appropriate here
  194. * as we got multiple processes for one i-node */
  195. return;
  196. }
  197. }
  198. *pnp = xzalloc(sizeof(struct prg_node));
  199. pn = *pnp;
  200. pn->inode = inode;
  201. safe_strncpy(pn->name, name, PROGNAME_WIDTH);
  202. }
  203. static const char *prg_cache_get(long inode)
  204. {
  205. unsigned hi = PRG_HASHIT(inode);
  206. struct prg_node *pn;
  207. for (pn = prg_hash[hi]; pn; pn = pn->next)
  208. if (pn->inode == inode)
  209. return pn->name;
  210. return "-";
  211. }
  212. #if ENABLE_FEATURE_CLEAN_UP
  213. static void prg_cache_clear(void)
  214. {
  215. struct prg_node **pnp, *pn;
  216. for (pnp = prg_hash; pnp < prg_hash + PRG_HASH_SIZE; pnp++) {
  217. while ((pn = *pnp) != NULL) {
  218. *pnp = pn->next;
  219. free(pn);
  220. }
  221. }
  222. }
  223. #else
  224. #define prg_cache_clear() ((void)0)
  225. #endif
  226. static long extract_socket_inode(const char *lname)
  227. {
  228. long inode = -1;
  229. if (is_prefixed_with(lname, "socket:[")) {
  230. /* "socket:[12345]", extract the "12345" as inode */
  231. inode = bb_strtoul(lname + sizeof("socket:[")-1, (char**)&lname, 0);
  232. if (*lname != ']')
  233. inode = -1;
  234. } else if (is_prefixed_with(lname, "[0000]:")) {
  235. /* "[0000]:12345", extract the "12345" as inode */
  236. inode = bb_strtoul(lname + sizeof("[0000]:")-1, NULL, 0);
  237. if (errno) /* not NUL terminated? */
  238. inode = -1;
  239. }
  240. #if 0 /* bb_strtol returns all-ones bit pattern on ERANGE anyway */
  241. if (errno == ERANGE)
  242. inode = -1;
  243. #endif
  244. return inode;
  245. }
  246. static int FAST_FUNC add_to_prg_cache_if_socket(const char *fileName,
  247. struct stat *statbuf UNUSED_PARAM,
  248. void *pid_slash_progname,
  249. int depth UNUSED_PARAM)
  250. {
  251. char *linkname;
  252. long inode;
  253. linkname = xmalloc_readlink(fileName);
  254. if (linkname != NULL) {
  255. inode = extract_socket_inode(linkname);
  256. free(linkname);
  257. if (inode >= 0)
  258. prg_cache_add(inode, (char *)pid_slash_progname);
  259. }
  260. return TRUE;
  261. }
  262. static int FAST_FUNC dir_act(const char *fileName,
  263. struct stat *statbuf UNUSED_PARAM,
  264. void *userData UNUSED_PARAM,
  265. int depth)
  266. {
  267. const char *pid;
  268. char *pid_slash_progname;
  269. char proc_pid_fname[sizeof("/proc/%u/cmdline") + sizeof(long)*3];
  270. char cmdline_buf[512];
  271. int n, len;
  272. if (depth == 0) /* "/proc" itself */
  273. return TRUE; /* continue looking one level below /proc */
  274. pid = fileName + sizeof("/proc/")-1; /* point after "/proc/" */
  275. if (!isdigit(pid[0])) /* skip /proc entries which aren't processes */
  276. return SKIP;
  277. len = snprintf(proc_pid_fname, sizeof(proc_pid_fname), "%s/cmdline", fileName);
  278. n = open_read_close(proc_pid_fname, cmdline_buf, sizeof(cmdline_buf) - 1);
  279. if (n < 0)
  280. return FALSE;
  281. cmdline_buf[n] = '\0';
  282. /* go through all files in /proc/PID/fd and check whether they are sockets */
  283. strcpy(proc_pid_fname + len - (sizeof("cmdline")-1), "fd");
  284. pid_slash_progname = concat_path_file(pid, bb_basename(cmdline_buf)); /* "PID/argv0" */
  285. n = recursive_action(proc_pid_fname,
  286. ACTION_RECURSE | ACTION_QUIET,
  287. add_to_prg_cache_if_socket,
  288. NULL,
  289. (void *)pid_slash_progname,
  290. 0);
  291. free(pid_slash_progname);
  292. if (!n)
  293. return FALSE; /* signal permissions error to caller */
  294. return SKIP; /* caller should not recurse further into this dir */
  295. }
  296. static void prg_cache_load(void)
  297. {
  298. int load_ok;
  299. prg_cache_loaded = 1;
  300. load_ok = recursive_action("/proc", ACTION_RECURSE | ACTION_QUIET,
  301. NULL, dir_act, NULL, 0);
  302. if (load_ok)
  303. return;
  304. if (prg_cache_loaded == 1)
  305. bb_error_msg("can't scan /proc - are you root?");
  306. else
  307. bb_error_msg("showing only processes with your user ID");
  308. }
  309. #else
  310. #define prg_cache_clear() ((void)0)
  311. #endif //ENABLE_FEATURE_NETSTAT_PRG
  312. #if ENABLE_FEATURE_IPV6
  313. static void build_ipv6_addr(char* local_addr, struct sockaddr_in6* localaddr)
  314. {
  315. char addr6[INET6_ADDRSTRLEN];
  316. struct in6_addr in6;
  317. sscanf(local_addr, "%08X%08X%08X%08X",
  318. &in6.s6_addr32[0], &in6.s6_addr32[1],
  319. &in6.s6_addr32[2], &in6.s6_addr32[3]);
  320. inet_ntop(AF_INET6, &in6, addr6, sizeof(addr6));
  321. inet_pton(AF_INET6, addr6, &localaddr->sin6_addr);
  322. localaddr->sin6_family = AF_INET6;
  323. }
  324. #endif
  325. static void build_ipv4_addr(char* local_addr, struct sockaddr_in* localaddr)
  326. {
  327. sscanf(local_addr, "%X", &localaddr->sin_addr.s_addr);
  328. localaddr->sin_family = AF_INET;
  329. }
  330. static const char *get_sname(int port, const char *proto, int numeric)
  331. {
  332. if (!port)
  333. return "*";
  334. if (!numeric) {
  335. struct servent *se = getservbyport(port, proto);
  336. if (se)
  337. return se->s_name;
  338. }
  339. /* hummm, we may return static buffer here!! */
  340. return itoa(ntohs(port));
  341. }
  342. static char *ip_port_str(struct sockaddr *addr, int port, const char *proto, int numeric)
  343. {
  344. char *host, *host_port;
  345. /* Code which used "*" for INADDR_ANY is removed: it's ambiguous
  346. * in IPv6, while "0.0.0.0" is not. */
  347. host = numeric ? xmalloc_sockaddr2dotted_noport(addr)
  348. : xmalloc_sockaddr2host_noport(addr);
  349. host_port = xasprintf("%s:%s", host, get_sname(htons(port), proto, numeric));
  350. free(host);
  351. return host_port;
  352. }
  353. struct inet_params {
  354. int local_port, rem_port, state, uid;
  355. union {
  356. struct sockaddr sa;
  357. struct sockaddr_in sin;
  358. #if ENABLE_FEATURE_IPV6
  359. struct sockaddr_in6 sin6;
  360. #endif
  361. } localaddr, remaddr;
  362. unsigned long rxq, txq, inode;
  363. };
  364. static int scan_inet_proc_line(struct inet_params *param, char *line)
  365. {
  366. int num;
  367. /* IPv6 /proc files use 32-char hex representation
  368. * of IPv6 address, followed by :PORT_IN_HEX
  369. */
  370. char local_addr[33], rem_addr[33]; /* 32 + 1 for NUL */
  371. num = sscanf(line,
  372. "%*d: %32[0-9A-Fa-f]:%X "
  373. "%32[0-9A-Fa-f]:%X %X "
  374. "%lX:%lX %*X:%*X "
  375. "%*X %d %*d %lu ",
  376. local_addr, &param->local_port,
  377. rem_addr, &param->rem_port, &param->state,
  378. &param->txq, &param->rxq,
  379. &param->uid, &param->inode);
  380. if (num < 9) {
  381. return 1; /* error */
  382. }
  383. if (strlen(local_addr) > 8) {
  384. #if ENABLE_FEATURE_IPV6
  385. build_ipv6_addr(local_addr, &param->localaddr.sin6);
  386. build_ipv6_addr(rem_addr, &param->remaddr.sin6);
  387. #endif
  388. } else {
  389. build_ipv4_addr(local_addr, &param->localaddr.sin);
  390. build_ipv4_addr(rem_addr, &param->remaddr.sin);
  391. }
  392. return 0;
  393. }
  394. static void print_inet_line(struct inet_params *param,
  395. const char *state_str, const char *proto, int is_connected)
  396. {
  397. if ((is_connected && (flags & NETSTAT_CONNECTED))
  398. || (!is_connected && (flags & NETSTAT_LISTENING))
  399. ) {
  400. char *l = ip_port_str(
  401. &param->localaddr.sa, param->local_port,
  402. proto, flags & NETSTAT_NUMERIC);
  403. char *r = ip_port_str(
  404. &param->remaddr.sa, param->rem_port,
  405. proto, flags & NETSTAT_NUMERIC);
  406. printf(FMT_NET_CONN_DATA,
  407. proto, param->rxq, param->txq,
  408. IF_FEATURE_NETSTAT_WIDE(G.addr_width,) l,
  409. IF_FEATURE_NETSTAT_WIDE(G.addr_width,) r,
  410. state_str);
  411. #if ENABLE_FEATURE_NETSTAT_PRG
  412. if (option_mask32 & OPT_prg)
  413. printf("%."PROGNAME_WIDTH_STR"s", prg_cache_get(param->inode));
  414. #endif
  415. bb_putchar('\n');
  416. free(l);
  417. free(r);
  418. }
  419. }
  420. static int FAST_FUNC tcp_do_one(char *line)
  421. {
  422. struct inet_params param;
  423. memset(&param, 0, sizeof(param));
  424. if (scan_inet_proc_line(&param, line))
  425. return 1;
  426. print_inet_line(&param, tcp_state[param.state], "tcp", param.rem_port);
  427. return 0;
  428. }
  429. #if ENABLE_FEATURE_IPV6
  430. # define NOT_NULL_ADDR(A) ( \
  431. ( (A.sa.sa_family == AF_INET6) \
  432. && (A.sin6.sin6_addr.s6_addr32[0] | A.sin6.sin6_addr.s6_addr32[1] | \
  433. A.sin6.sin6_addr.s6_addr32[2] | A.sin6.sin6_addr.s6_addr32[3]) \
  434. ) || ( \
  435. (A.sa.sa_family == AF_INET) \
  436. && A.sin.sin_addr.s_addr != 0 \
  437. ) \
  438. )
  439. #else
  440. # define NOT_NULL_ADDR(A) (A.sin.sin_addr.s_addr)
  441. #endif
  442. static int FAST_FUNC udp_do_one(char *line)
  443. {
  444. int have_remaddr;
  445. const char *state_str;
  446. struct inet_params param;
  447. memset(&param, 0, sizeof(param)); /* otherwise we display garbage IPv6 scope_ids */
  448. if (scan_inet_proc_line(&param, line))
  449. return 1;
  450. state_str = "UNKNOWN";
  451. switch (param.state) {
  452. case TCP_ESTABLISHED:
  453. state_str = "ESTABLISHED";
  454. break;
  455. case TCP_CLOSE:
  456. state_str = "";
  457. break;
  458. }
  459. have_remaddr = NOT_NULL_ADDR(param.remaddr);
  460. print_inet_line(&param, state_str, "udp", have_remaddr);
  461. return 0;
  462. }
  463. static int FAST_FUNC raw_do_one(char *line)
  464. {
  465. int have_remaddr;
  466. struct inet_params param;
  467. if (scan_inet_proc_line(&param, line))
  468. return 1;
  469. have_remaddr = NOT_NULL_ADDR(param.remaddr);
  470. print_inet_line(&param, itoa(param.state), "raw", have_remaddr);
  471. return 0;
  472. }
  473. static int FAST_FUNC unix_do_one(char *line)
  474. {
  475. unsigned long refcnt, proto, unix_flags;
  476. unsigned long inode;
  477. int type, state;
  478. int num, path_ofs;
  479. const char *ss_proto, *ss_state, *ss_type;
  480. char ss_flags[32];
  481. /* 2.6.15 may report lines like "... @/tmp/fam-user-^@^@^@^@^@^@^@..."
  482. * Other users report long lines filled by NUL bytes.
  483. * (those ^@ are NUL bytes too). We see them as empty lines. */
  484. if (!line[0])
  485. return 0;
  486. path_ofs = 0; /* paranoia */
  487. num = sscanf(line, "%*p: %lX %lX %lX %X %X %lu %n",
  488. &refcnt, &proto, &unix_flags, &type, &state, &inode, &path_ofs);
  489. if (num < 6) {
  490. return 1; /* error */
  491. }
  492. if ((flags & (NETSTAT_LISTENING|NETSTAT_CONNECTED)) != (NETSTAT_LISTENING|NETSTAT_CONNECTED)) {
  493. if ((state == SS_UNCONNECTED) && (unix_flags & SO_ACCEPTCON)) {
  494. if (!(flags & NETSTAT_LISTENING))
  495. return 0;
  496. } else {
  497. if (!(flags & NETSTAT_CONNECTED))
  498. return 0;
  499. }
  500. }
  501. switch (proto) {
  502. case 0:
  503. ss_proto = "unix";
  504. break;
  505. default:
  506. ss_proto = "??";
  507. }
  508. switch (type) {
  509. case SOCK_STREAM:
  510. ss_type = "STREAM";
  511. break;
  512. case SOCK_DGRAM:
  513. ss_type = "DGRAM";
  514. break;
  515. case SOCK_RAW:
  516. ss_type = "RAW";
  517. break;
  518. case SOCK_RDM:
  519. ss_type = "RDM";
  520. break;
  521. case SOCK_SEQPACKET:
  522. ss_type = "SEQPACKET";
  523. break;
  524. default:
  525. ss_type = "UNKNOWN";
  526. }
  527. switch (state) {
  528. case SS_FREE:
  529. ss_state = "FREE";
  530. break;
  531. case SS_UNCONNECTED:
  532. /*
  533. * Unconnected sockets may be listening
  534. * for something.
  535. */
  536. if (unix_flags & SO_ACCEPTCON) {
  537. ss_state = "LISTENING";
  538. } else {
  539. ss_state = "";
  540. }
  541. break;
  542. case SS_CONNECTING:
  543. ss_state = "CONNECTING";
  544. break;
  545. case SS_CONNECTED:
  546. ss_state = "CONNECTED";
  547. break;
  548. case SS_DISCONNECTING:
  549. ss_state = "DISCONNECTING";
  550. break;
  551. default:
  552. ss_state = "UNKNOWN";
  553. }
  554. strcpy(ss_flags, "[ ");
  555. if (unix_flags & SO_ACCEPTCON)
  556. strcat(ss_flags, "ACC ");
  557. if (unix_flags & SO_WAITDATA)
  558. strcat(ss_flags, "W ");
  559. if (unix_flags & SO_NOSPACE)
  560. strcat(ss_flags, "N ");
  561. strcat(ss_flags, "]");
  562. printf("%-5s %-6lu %-11s %-10s %-13s %6lu ",
  563. ss_proto, refcnt, ss_flags, ss_type, ss_state, inode
  564. );
  565. #if ENABLE_FEATURE_NETSTAT_PRG
  566. if (option_mask32 & OPT_prg)
  567. printf("%-"PROGNAME_WIDTH_STR"s", prg_cache_get(inode));
  568. #endif
  569. /* TODO: currently we stop at first NUL byte. Is it a problem? */
  570. line += path_ofs;
  571. chomp(line);
  572. while (*line)
  573. fputc_printable(*line++, stdout);
  574. bb_putchar('\n');
  575. return 0;
  576. }
  577. static void do_info(const char *file, int FAST_FUNC (*proc)(char *))
  578. {
  579. int lnr;
  580. FILE *procinfo;
  581. char *buffer;
  582. /* _stdin is just to save "r" param */
  583. procinfo = fopen_or_warn_stdin(file);
  584. if (procinfo == NULL) {
  585. return;
  586. }
  587. lnr = 0;
  588. /* Why xmalloc_fgets_str? because it doesn't stop on NULs */
  589. while ((buffer = xmalloc_fgets_str(procinfo, "\n")) != NULL) {
  590. /* line 0 is skipped */
  591. if (lnr && proc(buffer))
  592. bb_error_msg("%s: bogus data on line %d", file, lnr + 1);
  593. lnr++;
  594. free(buffer);
  595. }
  596. fclose(procinfo);
  597. }
  598. int netstat_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
  599. int netstat_main(int argc UNUSED_PARAM, char **argv)
  600. {
  601. unsigned opt;
  602. INIT_G();
  603. /* Option string must match NETSTAT_xxx constants */
  604. opt = getopt32(argv, NETSTAT_OPTS);
  605. if (opt & OPT_sock_listen) { // -l
  606. flags &= ~NETSTAT_CONNECTED;
  607. flags |= NETSTAT_LISTENING;
  608. }
  609. if (opt & OPT_sock_all) flags |= NETSTAT_LISTENING | NETSTAT_CONNECTED; // -a
  610. //if (opt & OPT_extended) // -e
  611. if (opt & OPT_noresolve) flags |= NETSTAT_NUMERIC; // -n
  612. //if (opt & OPT_sock_tcp) // -t: NETSTAT_TCP
  613. //if (opt & OPT_sock_udp) // -u: NETSTAT_UDP
  614. //if (opt & OPT_sock_raw) // -w: NETSTAT_RAW
  615. //if (opt & OPT_sock_unix) // -x: NETSTAT_UNIX
  616. #if ENABLE_ROUTE
  617. if (opt & OPT_route) { // -r
  618. bb_displayroutes(flags & NETSTAT_NUMERIC, !(opt & OPT_extended));
  619. return 0;
  620. }
  621. #endif
  622. #if ENABLE_FEATURE_NETSTAT_WIDE
  623. G.addr_width = ADDR_NORMAL_WIDTH;
  624. if (opt & OPT_wide) { // -W
  625. G.addr_width = ADDR_WIDE;
  626. }
  627. #endif
  628. #if ENABLE_FEATURE_NETSTAT_PRG
  629. progname_banner = "";
  630. if (opt & OPT_prg) { // -p
  631. progname_banner = PROGNAME_BANNER;
  632. prg_cache_load();
  633. }
  634. #endif
  635. opt &= NETSTAT_ALLPROTO;
  636. if (opt) {
  637. flags &= ~NETSTAT_ALLPROTO;
  638. flags |= opt;
  639. }
  640. if (flags & (NETSTAT_TCP|NETSTAT_UDP|NETSTAT_RAW)) {
  641. printf("Active Internet connections "); /* xxx */
  642. if ((flags & (NETSTAT_LISTENING|NETSTAT_CONNECTED)) == (NETSTAT_LISTENING|NETSTAT_CONNECTED))
  643. printf("(servers and established)");
  644. else if (flags & NETSTAT_LISTENING)
  645. printf("(only servers)");
  646. else
  647. printf("(w/o servers)");
  648. printf(FMT_NET_CONN_HEADER,
  649. IF_FEATURE_NETSTAT_WIDE(G.addr_width,) "Local Address",
  650. IF_FEATURE_NETSTAT_WIDE(G.addr_width,) "Foreign Address",
  651. progname_banner
  652. );
  653. }
  654. if (flags & NETSTAT_TCP) {
  655. do_info("/proc/net/tcp", tcp_do_one);
  656. #if ENABLE_FEATURE_IPV6
  657. do_info("/proc/net/tcp6", tcp_do_one);
  658. #endif
  659. }
  660. if (flags & NETSTAT_UDP) {
  661. do_info("/proc/net/udp", udp_do_one);
  662. #if ENABLE_FEATURE_IPV6
  663. do_info("/proc/net/udp6", udp_do_one);
  664. #endif
  665. }
  666. if (flags & NETSTAT_RAW) {
  667. do_info("/proc/net/raw", raw_do_one);
  668. #if ENABLE_FEATURE_IPV6
  669. do_info("/proc/net/raw6", raw_do_one);
  670. #endif
  671. }
  672. if (flags & NETSTAT_UNIX) {
  673. printf("Active UNIX domain sockets ");
  674. if ((flags & (NETSTAT_LISTENING|NETSTAT_CONNECTED)) == (NETSTAT_LISTENING|NETSTAT_CONNECTED))
  675. printf("(servers and established)");
  676. else if (flags & NETSTAT_LISTENING)
  677. printf("(only servers)");
  678. else
  679. printf("(w/o servers)");
  680. printf("\nProto RefCnt Flags Type State I-Node %sPath\n", progname_banner);
  681. do_info("/proc/net/unix", unix_do_one);
  682. }
  683. prg_cache_clear();
  684. return 0;
  685. }