netstat.c 19 KB

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