3
0

netstat.c 19 KB

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