netstat.c 20 KB

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