3
0

netstat.c 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775
  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: 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 = NULL;
  348. if (!numeric)
  349. host = xmalloc_sockaddr2host_noport(addr);
  350. if (!host)
  351. host = xmalloc_sockaddr2dotted_noport(addr);
  352. host_port = xasprintf("%s:%s", host, get_sname(htons(port), proto, numeric));
  353. free(host);
  354. return host_port;
  355. }
  356. struct inet_params {
  357. int local_port, rem_port, state, uid;
  358. union {
  359. struct sockaddr sa;
  360. struct sockaddr_in sin;
  361. #if ENABLE_FEATURE_IPV6
  362. struct sockaddr_in6 sin6;
  363. #endif
  364. } localaddr, remaddr;
  365. unsigned long rxq, txq, inode;
  366. };
  367. static int scan_inet_proc_line(struct inet_params *param, char *line)
  368. {
  369. int num;
  370. /* IPv6 /proc files use 32-char hex representation
  371. * of IPv6 address, followed by :PORT_IN_HEX
  372. */
  373. char local_addr[33], rem_addr[33]; /* 32 + 1 for NUL */
  374. num = sscanf(line,
  375. "%*d: %32[0-9A-Fa-f]:%X "
  376. "%32[0-9A-Fa-f]:%X %X "
  377. "%lX:%lX %*X:%*X "
  378. "%*X %d %*d %lu ",
  379. local_addr, &param->local_port,
  380. rem_addr, &param->rem_port, &param->state,
  381. &param->txq, &param->rxq,
  382. &param->uid, &param->inode);
  383. if (num < 9) {
  384. return 1; /* error */
  385. }
  386. if (strlen(local_addr) > 8) {
  387. #if ENABLE_FEATURE_IPV6
  388. build_ipv6_addr(local_addr, &param->localaddr.sin6);
  389. build_ipv6_addr(rem_addr, &param->remaddr.sin6);
  390. #endif
  391. } else {
  392. build_ipv4_addr(local_addr, &param->localaddr.sin);
  393. build_ipv4_addr(rem_addr, &param->remaddr.sin);
  394. }
  395. return 0;
  396. }
  397. static void print_inet_line(struct inet_params *param,
  398. const char *state_str, const char *proto, int is_connected)
  399. {
  400. if ((is_connected && (flags & NETSTAT_CONNECTED))
  401. || (!is_connected && (flags & NETSTAT_LISTENING))
  402. ) {
  403. char *l = ip_port_str(
  404. &param->localaddr.sa, param->local_port,
  405. proto, flags & NETSTAT_NUMERIC);
  406. char *r = ip_port_str(
  407. &param->remaddr.sa, param->rem_port,
  408. proto, flags & NETSTAT_NUMERIC);
  409. printf(FMT_NET_CONN_DATA,
  410. proto, param->rxq, param->txq,
  411. IF_FEATURE_NETSTAT_WIDE(G.addr_width,) l,
  412. IF_FEATURE_NETSTAT_WIDE(G.addr_width,) r,
  413. state_str);
  414. #if ENABLE_FEATURE_NETSTAT_PRG
  415. if (option_mask32 & OPT_prg)
  416. printf("%."PROGNAME_WIDTH_STR"s", prg_cache_get(param->inode));
  417. #endif
  418. bb_putchar('\n');
  419. free(l);
  420. free(r);
  421. }
  422. }
  423. static int FAST_FUNC tcp_do_one(char *line)
  424. {
  425. struct inet_params param;
  426. memset(&param, 0, sizeof(param));
  427. if (scan_inet_proc_line(&param, line))
  428. return 1;
  429. print_inet_line(&param, tcp_state[param.state], "tcp", param.rem_port);
  430. return 0;
  431. }
  432. #if ENABLE_FEATURE_IPV6
  433. # define NOT_NULL_ADDR(A) ( \
  434. ( (A.sa.sa_family == AF_INET6) \
  435. && (A.sin6.sin6_addr.s6_addr32[0] | A.sin6.sin6_addr.s6_addr32[1] | \
  436. A.sin6.sin6_addr.s6_addr32[2] | A.sin6.sin6_addr.s6_addr32[3]) \
  437. ) || ( \
  438. (A.sa.sa_family == AF_INET) \
  439. && A.sin.sin_addr.s_addr != 0 \
  440. ) \
  441. )
  442. #else
  443. # define NOT_NULL_ADDR(A) (A.sin.sin_addr.s_addr)
  444. #endif
  445. static int FAST_FUNC udp_do_one(char *line)
  446. {
  447. int have_remaddr;
  448. const char *state_str;
  449. struct inet_params param;
  450. memset(&param, 0, sizeof(param)); /* otherwise we display garbage IPv6 scope_ids */
  451. if (scan_inet_proc_line(&param, line))
  452. return 1;
  453. state_str = "UNKNOWN";
  454. switch (param.state) {
  455. case TCP_ESTABLISHED:
  456. state_str = "ESTABLISHED";
  457. break;
  458. case TCP_CLOSE:
  459. state_str = "";
  460. break;
  461. }
  462. have_remaddr = NOT_NULL_ADDR(param.remaddr);
  463. print_inet_line(&param, state_str, "udp", have_remaddr);
  464. return 0;
  465. }
  466. static int FAST_FUNC raw_do_one(char *line)
  467. {
  468. int have_remaddr;
  469. struct inet_params param;
  470. if (scan_inet_proc_line(&param, line))
  471. return 1;
  472. have_remaddr = NOT_NULL_ADDR(param.remaddr);
  473. print_inet_line(&param, itoa(param.state), "raw", have_remaddr);
  474. return 0;
  475. }
  476. static int FAST_FUNC unix_do_one(char *line)
  477. {
  478. unsigned long refcnt, proto, unix_flags;
  479. unsigned long inode;
  480. int type, state;
  481. int num, path_ofs;
  482. const char *ss_proto, *ss_state, *ss_type;
  483. char ss_flags[32];
  484. /* 2.6.15 may report lines like "... @/tmp/fam-user-^@^@^@^@^@^@^@..."
  485. * Other users report long lines filled by NUL bytes.
  486. * (those ^@ are NUL bytes too). We see them as empty lines. */
  487. if (!line[0])
  488. return 0;
  489. path_ofs = 0; /* paranoia */
  490. num = sscanf(line, "%*p: %lX %lX %lX %X %X %lu %n",
  491. &refcnt, &proto, &unix_flags, &type, &state, &inode, &path_ofs);
  492. if (num < 6) {
  493. return 1; /* error */
  494. }
  495. if ((flags & (NETSTAT_LISTENING|NETSTAT_CONNECTED)) != (NETSTAT_LISTENING|NETSTAT_CONNECTED)) {
  496. if ((state == SS_UNCONNECTED) && (unix_flags & SO_ACCEPTCON)) {
  497. if (!(flags & NETSTAT_LISTENING))
  498. return 0;
  499. } else {
  500. if (!(flags & NETSTAT_CONNECTED))
  501. return 0;
  502. }
  503. }
  504. switch (proto) {
  505. case 0:
  506. ss_proto = "unix";
  507. break;
  508. default:
  509. ss_proto = "??";
  510. }
  511. switch (type) {
  512. case SOCK_STREAM:
  513. ss_type = "STREAM";
  514. break;
  515. case SOCK_DGRAM:
  516. ss_type = "DGRAM";
  517. break;
  518. case SOCK_RAW:
  519. ss_type = "RAW";
  520. break;
  521. case SOCK_RDM:
  522. ss_type = "RDM";
  523. break;
  524. case SOCK_SEQPACKET:
  525. ss_type = "SEQPACKET";
  526. break;
  527. default:
  528. ss_type = "UNKNOWN";
  529. }
  530. switch (state) {
  531. case SS_FREE:
  532. ss_state = "FREE";
  533. break;
  534. case SS_UNCONNECTED:
  535. /*
  536. * Unconnected sockets may be listening
  537. * for something.
  538. */
  539. if (unix_flags & SO_ACCEPTCON) {
  540. ss_state = "LISTENING";
  541. } else {
  542. ss_state = "";
  543. }
  544. break;
  545. case SS_CONNECTING:
  546. ss_state = "CONNECTING";
  547. break;
  548. case SS_CONNECTED:
  549. ss_state = "CONNECTED";
  550. break;
  551. case SS_DISCONNECTING:
  552. ss_state = "DISCONNECTING";
  553. break;
  554. default:
  555. ss_state = "UNKNOWN";
  556. }
  557. strcpy(ss_flags, "[ ");
  558. if (unix_flags & SO_ACCEPTCON)
  559. strcat(ss_flags, "ACC ");
  560. if (unix_flags & SO_WAITDATA)
  561. strcat(ss_flags, "W ");
  562. if (unix_flags & SO_NOSPACE)
  563. strcat(ss_flags, "N ");
  564. strcat(ss_flags, "]");
  565. printf("%-5s %-6lu %-11s %-10s %-13s %6lu ",
  566. ss_proto, refcnt, ss_flags, ss_type, ss_state, inode
  567. );
  568. #if ENABLE_FEATURE_NETSTAT_PRG
  569. if (option_mask32 & OPT_prg)
  570. printf("%-"PROGNAME_WIDTH_STR"s", prg_cache_get(inode));
  571. #endif
  572. /* TODO: currently we stop at first NUL byte. Is it a problem? */
  573. line += path_ofs;
  574. chomp(line);
  575. while (*line)
  576. fputc_printable(*line++, stdout);
  577. bb_putchar('\n');
  578. return 0;
  579. }
  580. static void do_info(const char *file, int FAST_FUNC (*proc)(char *))
  581. {
  582. int lnr;
  583. FILE *procinfo;
  584. char *buffer;
  585. /* _stdin is just to save "r" param */
  586. procinfo = fopen_or_warn_stdin(file);
  587. if (procinfo == NULL) {
  588. return;
  589. }
  590. lnr = 0;
  591. /* Why xmalloc_fgets_str? because it doesn't stop on NULs */
  592. while ((buffer = xmalloc_fgets_str(procinfo, "\n")) != NULL) {
  593. /* line 0 is skipped */
  594. if (lnr && proc(buffer))
  595. bb_error_msg("%s: bogus data on line %d", file, lnr + 1);
  596. lnr++;
  597. free(buffer);
  598. }
  599. fclose(procinfo);
  600. }
  601. int netstat_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
  602. int netstat_main(int argc UNUSED_PARAM, char **argv)
  603. {
  604. unsigned opt;
  605. INIT_G();
  606. /* Option string must match NETSTAT_xxx constants */
  607. opt = getopt32(argv, NETSTAT_OPTS);
  608. if (opt & OPT_sock_listen) { // -l
  609. flags &= ~NETSTAT_CONNECTED;
  610. flags |= NETSTAT_LISTENING;
  611. }
  612. if (opt & OPT_sock_all) flags |= NETSTAT_LISTENING | NETSTAT_CONNECTED; // -a
  613. //if (opt & OPT_extended) // -e
  614. if (opt & OPT_noresolve) flags |= NETSTAT_NUMERIC; // -n
  615. //if (opt & OPT_sock_tcp) // -t: NETSTAT_TCP
  616. //if (opt & OPT_sock_udp) // -u: NETSTAT_UDP
  617. //if (opt & OPT_sock_raw) // -w: NETSTAT_RAW
  618. //if (opt & OPT_sock_unix) // -x: NETSTAT_UNIX
  619. #if ENABLE_ROUTE
  620. if (opt & OPT_route) { // -r
  621. bb_displayroutes(flags & NETSTAT_NUMERIC, !(opt & OPT_extended));
  622. return 0;
  623. }
  624. #endif
  625. #if ENABLE_FEATURE_NETSTAT_WIDE
  626. G.addr_width = ADDR_NORMAL_WIDTH;
  627. if (opt & OPT_wide) { // -W
  628. G.addr_width = ADDR_WIDE;
  629. }
  630. #endif
  631. #if ENABLE_FEATURE_NETSTAT_PRG
  632. progname_banner = "";
  633. if (opt & OPT_prg) { // -p
  634. progname_banner = PROGNAME_BANNER;
  635. prg_cache_load();
  636. }
  637. #endif
  638. opt &= NETSTAT_ALLPROTO;
  639. if (opt) {
  640. flags &= ~NETSTAT_ALLPROTO;
  641. flags |= opt;
  642. }
  643. if (flags & (NETSTAT_TCP|NETSTAT_UDP|NETSTAT_RAW)) {
  644. printf("Active Internet connections "); /* xxx */
  645. if ((flags & (NETSTAT_LISTENING|NETSTAT_CONNECTED)) == (NETSTAT_LISTENING|NETSTAT_CONNECTED))
  646. printf("(servers and established)");
  647. else if (flags & NETSTAT_LISTENING)
  648. printf("(only servers)");
  649. else
  650. printf("(w/o servers)");
  651. printf(FMT_NET_CONN_HEADER,
  652. IF_FEATURE_NETSTAT_WIDE(G.addr_width,) "Local Address",
  653. IF_FEATURE_NETSTAT_WIDE(G.addr_width,) "Foreign Address",
  654. progname_banner
  655. );
  656. }
  657. if (flags & NETSTAT_TCP) {
  658. do_info("/proc/net/tcp", tcp_do_one);
  659. #if ENABLE_FEATURE_IPV6
  660. do_info("/proc/net/tcp6", tcp_do_one);
  661. #endif
  662. }
  663. if (flags & NETSTAT_UDP) {
  664. do_info("/proc/net/udp", udp_do_one);
  665. #if ENABLE_FEATURE_IPV6
  666. do_info("/proc/net/udp6", udp_do_one);
  667. #endif
  668. }
  669. if (flags & NETSTAT_RAW) {
  670. do_info("/proc/net/raw", raw_do_one);
  671. #if ENABLE_FEATURE_IPV6
  672. do_info("/proc/net/raw6", raw_do_one);
  673. #endif
  674. }
  675. if (flags & NETSTAT_UNIX) {
  676. printf("Active UNIX domain sockets ");
  677. if ((flags & (NETSTAT_LISTENING|NETSTAT_CONNECTED)) == (NETSTAT_LISTENING|NETSTAT_CONNECTED))
  678. printf("(servers and established)");
  679. else if (flags & NETSTAT_LISTENING)
  680. printf("(only servers)");
  681. else
  682. printf("(w/o servers)");
  683. printf("\nProto RefCnt Flags Type State I-Node %sPath\n", progname_banner);
  684. do_info("/proc/net/unix", unix_do_one);
  685. }
  686. prg_cache_clear();
  687. return 0;
  688. }