summaryrefslogtreecommitdiff
path: root/networking/netstat.c
blob: e03ba5fcc18ad079d345411ed05f2502d3a36fd8 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
/* vi: set sw=4 ts=4: */
/*
 * Mini netstat implementation(s) for busybox
 * based in part on the netstat implementation from net-tools.
 *
 * Copyright (C) 2002 by Bart Visscher <magick@linux-fan.com>
 *
 * 2002-04-20
 * IPV6 support added by Bart Visscher <magick@linux-fan.com>
 *
 * 2008-07-10
 * optional '-p' flag support ported from net-tools by G. Somlo <somlo@cmu.edu>
 *
 * Licensed under GPLv2 or later, see file LICENSE in this tarball for details.
 */

#include "libbb.h"
#include "inet_common.h"

#define NETSTAT_OPTS "laentuwx" \
	USE_ROUTE(               "r") \
	USE_FEATURE_NETSTAT_WIDE("W") \
	USE_FEATURE_NETSTAT_PRG( "p")

enum {
	OPTBIT_KEEP_OLD = 7,
	USE_ROUTE(               OPTBIT_ROUTE,)
	USE_FEATURE_NETSTAT_WIDE(OPTBIT_WIDE ,)
	USE_FEATURE_NETSTAT_PRG( OPTBIT_PRG  ,)
	OPT_sock_listen = 1 << 0, // l
	OPT_sock_all    = 1 << 1, // a
	OPT_extended    = 1 << 2, // e
	OPT_noresolve   = 1 << 3, // n
	OPT_sock_tcp    = 1 << 4, // t
	OPT_sock_udp    = 1 << 5, // u
	OPT_sock_raw    = 1 << 6, // w
	OPT_sock_unix   = 1 << 7, // x
	OPT_route       = USE_ROUTE(               (1 << OPTBIT_ROUTE)) + 0, // r
	OPT_wide        = USE_FEATURE_NETSTAT_WIDE((1 << OPTBIT_WIDE )) + 0, // W
	OPT_prg         = USE_FEATURE_NETSTAT_PRG( (1 << OPTBIT_PRG  )) + 0, // p
};

#define NETSTAT_CONNECTED 0x01
#define NETSTAT_LISTENING 0x02
#define NETSTAT_NUMERIC   0x04
/* Must match getopt32 option string */
#define NETSTAT_TCP       0x10
#define NETSTAT_UDP       0x20
#define NETSTAT_RAW       0x40
#define NETSTAT_UNIX      0x80
#define NETSTAT_ALLPROTO  (NETSTAT_TCP|NETSTAT_UDP|NETSTAT_RAW|NETSTAT_UNIX)


enum {
	TCP_ESTABLISHED = 1,
	TCP_SYN_SENT,
	TCP_SYN_RECV,
	TCP_FIN_WAIT1,
	TCP_FIN_WAIT2,
	TCP_TIME_WAIT,
	TCP_CLOSE,
	TCP_CLOSE_WAIT,
	TCP_LAST_ACK,
	TCP_LISTEN,
	TCP_CLOSING, /* now a valid state */
};

static const char *const tcp_state[] = {
	"",
	"ESTABLISHED",
	"SYN_SENT",
	"SYN_RECV",
	"FIN_WAIT1",
	"FIN_WAIT2",
	"TIME_WAIT",
	"CLOSE",
	"CLOSE_WAIT",
	"LAST_ACK",
	"LISTEN",
	"CLOSING"
};

typedef enum {
	SS_FREE = 0,     /* not allocated                */
	SS_UNCONNECTED,  /* unconnected to any socket    */
	SS_CONNECTING,   /* in process of connecting     */
	SS_CONNECTED,    /* connected to socket          */
	SS_DISCONNECTING /* in process of disconnecting  */
} socket_state;

#define SO_ACCEPTCON (1<<16)	/* performed a listen           */
#define SO_WAITDATA  (1<<17)	/* wait data to read            */
#define SO_NOSPACE   (1<<18)	/* no space to write            */

/* Standard printout size */
#define PRINT_IP_MAX_SIZE           23
#define PRINT_NET_CONN              "%s   %6ld %6ld %-23s %-23s %-12s"
#define PRINT_NET_CONN_HEADER       "\nProto Recv-Q Send-Q %-23s %-23s State       "

/* When there are IPv6 connections the IPv6 addresses will be
 * truncated to none-recognition. The '-W' option makes the
 * address columns wide enough to accomodate for longest possible
 * IPv6 addresses, i.e. addresses of the form
 * xxxx:xxxx:xxxx:xxxx:xxxx:xxxx:ddd.ddd.ddd.ddd
 */
#define PRINT_IP_MAX_SIZE_WIDE      51  /* INET6_ADDRSTRLEN + 5 for the port number */
#define PRINT_NET_CONN_WIDE         "%s   %6ld %6ld %-51s %-51s %-12s"
#define PRINT_NET_CONN_HEADER_WIDE  "\nProto Recv-Q Send-Q %-51s %-51s State       "


#define PROGNAME_WIDTH     20
#define PROGNAME_WIDTH_STR "20"
/* PROGNAME_WIDTH chars: 12345678901234567890 */
#define PROGNAME_BANNER "PID/Program name    "

struct prg_node {
	struct prg_node *next;
	long inode;
	char name[PROGNAME_WIDTH];
};

#define PRG_HASH_SIZE 211


struct globals {
	const char *net_conn_line;
	smallint flags;
#if ENABLE_FEATURE_NETSTAT_PRG
	smallint prg_cache_loaded;
	struct prg_node *prg_hash[PRG_HASH_SIZE];
#endif
};
#define G (*ptr_to_globals)
#define flags            (G.flags           )
#define net_conn_line    (G.net_conn_line   )
#define prg_hash         (G.prg_hash        )
#define prg_cache_loaded (G.prg_cache_loaded)
#define INIT_G() do { \
	SET_PTR_TO_GLOBALS(xzalloc(sizeof(G))); \
	flags = NETSTAT_CONNECTED | NETSTAT_ALLPROTO; \
	net_conn_line = PRINT_NET_CONN; \
} while (0)


#if ENABLE_FEATURE_NETSTAT_PRG

/* Deliberately truncating long to unsigned *int* */
#define PRG_HASHIT(x) ((unsigned)(x) % PRG_HASH_SIZE)

#define print_progname_banner() do { \
	if (option_mask32 & OPT_prg) printf(PROGNAME_BANNER); \
} while (0)

static void prg_cache_add(long inode, char *name)
{
	unsigned hi = PRG_HASHIT(inode);
	struct prg_node **pnp, *pn;

	prg_cache_loaded = 2;
	for (pnp = prg_hash + hi; (pn = *pnp) != NULL; pnp = &pn->next) {
		if (pn->inode == inode) {
			/* Some warning should be appropriate here
			   as we got multiple processes for one i-node */
			return;
		}
	}
	*pnp = xzalloc(sizeof(struct prg_node));
	pn = *pnp;
	pn->inode = inode;
	safe_strncpy(pn->name, name, PROGNAME_WIDTH);
}

static const char *prg_cache_get(long inode)
{
	unsigned hi = PRG_HASHIT(inode);
	struct prg_node *pn;

	for (pn = prg_hash[hi]; pn; pn = pn->next)
		if (pn->inode == inode)
			return pn->name;
	return "-";
}

#if ENABLE_FEATURE_CLEAN_UP
static void prg_cache_clear(void)
{
	struct prg_node **pnp, *pn;

	for (pnp = prg_hash; pnp < prg_hash + PRG_HASH_SIZE; pnp++) {
		while ((pn = *pnp) != NULL) {
			*pnp = pn->next;
			free(pn);
		}
	}
}
#else
#define prg_cache_clear() ((void)0)
#endif

static long extract_socket_inode(const char *lname)
{
	long inode = -1;

	if (strncmp(lname, "socket:[", sizeof("socket:[")-1) == 0) {
		/* "socket:[12345]", extract the "12345" as inode */
		inode = bb_strtol(lname + sizeof("socket:[")-1, (char**)&lname, 0);
		if (*lname != ']')
			inode = -1;
	} else if (strncmp(lname, "[0000]:", sizeof("[0000]:")-1) == 0) {
		/* "[0000]:12345", extract the "12345" as inode */
		inode = bb_strtol(lname + sizeof("[0000]:")-1, NULL, 0);
		if (errno) /* not NUL terminated? */
			inode = -1;
	}

#if 0 /* bb_strtol returns all-ones bit pattern on ERANGE anyway */
	if (errno == ERANGE)
		inode = -1;
#endif
	return inode;
}

static int FAST_FUNC file_act(const char *fileName,
		struct stat *statbuf UNUSED_PARAM,
		void *userData,
		int depth UNUSED_PARAM)
{
	char *linkname;
	long inode;

	linkname = xmalloc_readlink(fileName);
	if (linkname != NULL) {
		inode = extract_socket_inode(linkname);
		free(linkname);
		if (inode >= 0)
			prg_cache_add(inode, (char *)userData);
	}
	return TRUE;
}

static int FAST_FUNC dir_act(const char *fileName,
		struct stat *statbuf UNUSED_PARAM,
		void *userData UNUSED_PARAM,
		int depth)
{
	const char *shortName;
	char *p, *q;
	char cmdline_buf[512];
	int i;

	if (depth == 0) /* "/proc" itself */
		return TRUE; /* continue looking one level below /proc */

	shortName = fileName + sizeof("/proc/")-1; /* point after "/proc/" */
	if (!isdigit(shortName[0])) /* skip /proc entries whic aren't processes */
		return SKIP;

	p = concat_path_file(fileName, "cmdline"); /* "/proc/PID/cmdline" */
	i = open_read_close(p, cmdline_buf, sizeof(cmdline_buf) - 1);
	free(p);
	if (i < 0)
		return FALSE;
	cmdline_buf[i] = '\0';
	q = concat_path_file(shortName, bb_basename(cmdline_buf)); /* "PID/argv0" */

	/* go through all files in /proc/PID/fd */
	p = concat_path_file(fileName, "fd");
	i = recursive_action(p, ACTION_RECURSE | ACTION_QUIET,
				file_act, NULL, (void *)q, 0);

	free(p);
	free(q);

	if (!i)
		return FALSE;	/* signal permissions error to caller */

	return SKIP;		/* caller should not recurse further into this dir. */
}

static void prg_cache_load(void)
{
	int load_ok;

	prg_cache_loaded = 1;
	load_ok = recursive_action("/proc", ACTION_RECURSE | ACTION_QUIET,
				NULL, dir_act, NULL, 0);
	if (load_ok)
		return;

	if (prg_cache_loaded == 1)
		bb_error_msg("can't scan /proc - are you root?");
	else
		bb_error_msg("showing only processes with your user ID");
}

#else

#define prg_cache_clear()       ((void)0)
#define print_progname_banner() ((void)0)

#endif //ENABLE_FEATURE_NETSTAT_PRG


#if ENABLE_FEATURE_IPV6
static void build_ipv6_addr(char* local_addr, struct sockaddr_in6* localaddr)
{
	char addr6[INET6_ADDRSTRLEN];
	struct in6_addr in6;

	sscanf(local_addr, "%08X%08X%08X%08X",
		   &in6.s6_addr32[0], &in6.s6_addr32[1],
		   &in6.s6_addr32[2], &in6.s6_addr32[3]);
	inet_ntop(AF_INET6, &in6, addr6, sizeof(addr6));
	inet_pton(AF_INET6, addr6, (struct sockaddr *) &localaddr->sin6_addr);

	localaddr->sin6_family = AF_INET6;
}
#endif

#if ENABLE_FEATURE_IPV6
static void build_ipv4_addr(char* local_addr, struct sockaddr_in6* localaddr)
#else
static void build_ipv4_addr(char* local_addr, struct sockaddr_in* localaddr)
#endif
{
	sscanf(local_addr, "%X",
		   &((struct sockaddr_in *) localaddr)->sin_addr.s_addr);
	((struct sockaddr *) localaddr)->sa_family = AF_INET;
}

static const char *get_sname(int port, const char *proto, int numeric)
{
	if (!port)
		return "*";
	if (!numeric) {
		struct servent *se = getservbyport(port, proto);
		if (se)
			return se->s_name;
	}
	/* hummm, we may return static buffer here!! */
	return itoa(ntohs(port));
}

static char *ip_port_str(struct sockaddr *addr, int port, const char *proto, int numeric)
{
	enum { salen = USE_FEATURE_IPV6(sizeof(struct sockaddr_in6)) SKIP_FEATURE_IPV6(sizeof(struct sockaddr_in)) };
	char *host, *host_port;

	/* Code which used "*" for INADDR_ANY is removed: it's ambiguous in IPv6,
	 * while "0.0.0.0" is not. */

	host = numeric ? xmalloc_sockaddr2dotted_noport(addr)
	               : xmalloc_sockaddr2host_noport(addr);

	host_port = xasprintf("%s:%s", host, get_sname(htons(port), proto, numeric));
	free(host);
	return host_port;
}

static int tcp_do_one(int lnr, char *line)
{
	char local_addr[64], rem_addr[64];
	char more[512];
	int num, local_port, rem_port, d, state, timer_run, uid, timeout;
#if ENABLE_FEATURE_IPV6
	struct sockaddr_in6 localaddr, remaddr;
#else
	struct sockaddr_in localaddr, remaddr;
#endif
	unsigned long rxq, txq, time_len, retr, inode;

	if (lnr == 0)
		return 0;

	more[0] = '\0';
	num = sscanf(line,
			"%d: %64[0-9A-Fa-f]:%X %64[0-9A-Fa-f]:%X %X %lX:%lX %X:%lX %lX %d %d %ld %512s\n",
			&d, local_addr, &local_port,
			rem_addr, &rem_port, &state,
			&txq, &rxq, &timer_run, &time_len, &retr, &uid, &timeout, &inode, more);

	if (num < 10) {
		return 1; /* error */
	}

	if (strlen(local_addr) > 8) {
#if ENABLE_FEATURE_IPV6
		build_ipv6_addr(local_addr, &localaddr);
		build_ipv6_addr(rem_addr, &remaddr);
#endif
	} else {
		build_ipv4_addr(local_addr, &localaddr);
		build_ipv4_addr(rem_addr, &remaddr);
	}

	if ((rem_port && (flags & NETSTAT_CONNECTED))
	 || (!rem_port && (flags & NETSTAT_LISTENING))
	) {
		char *l = ip_port_str(
				(struct sockaddr *) &localaddr, local_port,
				"tcp", flags & NETSTAT_NUMERIC);
		char *r = ip_port_str(
				(struct sockaddr *) &remaddr, rem_port,
				"tcp", flags & NETSTAT_NUMERIC);
		printf(net_conn_line,
			"tcp", rxq, txq, l, r, tcp_state[state]);
#if ENABLE_FEATURE_NETSTAT_PRG
		if (option_mask32 & OPT_prg)
			printf("%."PROGNAME_WIDTH_STR"s", prg_cache_get(inode));
#endif
		bb_putchar('\n');
		free(l);
		free(r);
	}
	return 0;
}

static int udp_do_one(int lnr, char *line)
{
	char local_addr[64], rem_addr[64];
	const char *state_str;
	char more[512];
	int num, local_port, rem_port, d, state, timer_run, uid, timeout;
#if ENABLE_FEATURE_IPV6
	struct sockaddr_in6 localaddr, remaddr;
#else
	struct sockaddr_in localaddr, remaddr;
#endif
	unsigned long rxq, txq, time_len, retr, inode;

	if (lnr == 0)
		return 0;

	more[0] = '\0';
	num = sscanf(line,
			"%d: %64[0-9A-Fa-f]:%X %64[0-9A-Fa-f]:%X %X %lX:%lX %X:%lX %lX %d %d %ld %512s\n",
			&d, local_addr, &local_port,
			rem_addr, &rem_port, &state,
			&txq, &rxq, &timer_run, &time_len, &retr, &uid, &timeout, &inode, more);

	if (strlen(local_addr) > 8) {
#if ENABLE_FEATURE_IPV6
		/* Demangle what the kernel gives us */
		build_ipv6_addr(local_addr, &localaddr);
		build_ipv6_addr(rem_addr, &remaddr);
#endif
	} else {
		build_ipv4_addr(local_addr, &localaddr);
		build_ipv4_addr(rem_addr, &remaddr);
	}

	if (num < 10) {
		return 1; /* error */
	}
	switch (state) {
		case TCP_ESTABLISHED:
			state_str = "ESTABLISHED";
			break;
		case TCP_CLOSE:
			state_str = "";
			break;
		default:
			state_str = "UNKNOWN";
			break;
	}

#if ENABLE_FEATURE_IPV6
# define notnull(A) ( \
	( (A.sin6_family == AF_INET6)                               \
	  && (A.sin6_addr.s6_addr32[0] | A.sin6_addr.s6_addr32[1] | \
	      A.sin6_addr.s6_addr32[2] | A.sin6_addr.s6_addr32[3])  \
	) || (                                                      \
	  (A.sin6_family == AF_INET)                                \
	  && ((struct sockaddr_in*)&A)->sin_addr.s_addr             \
	)                                                           \
)
#else
# define notnull(A) (A.sin_addr.s_addr)
#endif
	{
		int have_remaddr = notnull(remaddr);
		if ((have_remaddr && (flags & NETSTAT_CONNECTED))
		 || (!have_remaddr && (flags & NETSTAT_LISTENING))
		) {
			char *l = ip_port_str(
				(struct sockaddr *) &localaddr, local_port,
				"udp", flags & NETSTAT_NUMERIC);
			char *r = ip_port_str(
				(struct sockaddr *) &remaddr, rem_port,
				"udp", flags & NETSTAT_NUMERIC);
			printf(net_conn_line,
				"udp", rxq, txq, l, r, state_str);
#if ENABLE_FEATURE_NETSTAT_PRG
			if (option_mask32 & OPT_prg)
				printf("%."PROGNAME_WIDTH_STR"s", prg_cache_get(inode));
#endif
			bb_putchar('\n');
			free(l);
			free(r);
		}
	}
	return 0;
}

static int raw_do_one(int lnr, char *line)
{
	char local_addr[64], rem_addr[64];
	char more[512];
	int num, local_port, rem_port, d, state, timer_run, uid, timeout;
#if ENABLE_FEATURE_IPV6
	struct sockaddr_in6 localaddr, remaddr;
#else
	struct sockaddr_in localaddr, remaddr;
#endif
	unsigned long rxq, txq, time_len, retr, inode;

	if (lnr == 0)
		return 0;

	more[0] = '\0';
	num = sscanf(line,
			"%d: %64[0-9A-Fa-f]:%X %64[0-9A-Fa-f]:%X %X %lX:%lX %X:%lX %lX %d %d %ld %512s\n",
			&d, local_addr, &local_port,
			rem_addr, &rem_port, &state,
			&txq, &rxq, &timer_run, &time_len, &retr, &uid, &timeout, &inode, more);

	if (strlen(local_addr) > 8) {
#if ENABLE_FEATURE_IPV6
		build_ipv6_addr(local_addr, &localaddr);
		build_ipv6_addr(rem_addr, &remaddr);
#endif
	} else {
		build_ipv4_addr(local_addr, &localaddr);
		build_ipv4_addr(rem_addr, &remaddr);
	}

	if (num < 10) {
		return 1; /* error */
	}

	{
		int have_remaddr = notnull(remaddr);
		if ((have_remaddr && (flags & NETSTAT_CONNECTED))
		 || (!have_remaddr && (flags & NETSTAT_LISTENING))
		) {
			char *l = ip_port_str(
				(struct sockaddr *) &localaddr, local_port,
				"raw", flags & NETSTAT_NUMERIC);
			char *r = ip_port_str(
				(struct sockaddr *) &remaddr, rem_port,
				"raw", flags & NETSTAT_NUMERIC);
			printf(net_conn_line,
				"raw", rxq, txq, l, r, itoa(state));
#if ENABLE_FEATURE_NETSTAT_PRG
			if (option_mask32 & OPT_prg)
				printf("%-"PROGNAME_WIDTH_STR"s", prg_cache_get(inode));
#endif
			bb_putchar('\n');
			free(l);
			free(r);
		}
	}
	return 0;
}

static int unix_do_one(int nr, char *line)
{
	unsigned long refcnt, proto, unix_flags;
	unsigned long inode;
	int type, state;
	int num, path_ofs;
	void *d;
	const char *ss_proto, *ss_state, *ss_type;
	char ss_flags[32];

	if (nr == 0)
		return 0; /* skip header */

	/* 2.6.15 may report lines like "... @/tmp/fam-user-^@^@^@^@^@^@^@..."
	 * Other users report long lines filled by NUL bytes.
	 * (those ^@ are NUL bytes too). We see them as empty lines. */
	if (!line[0])
		return 0;

	path_ofs = 0; /* paranoia */
	num = sscanf(line, "%p: %lX %lX %lX %X %X %lu %n",
			&d, &refcnt, &proto, &unix_flags, &type, &state, &inode, &path_ofs);
	if (num < 7) {
		return 1; /* error */
	}
	if ((flags & (NETSTAT_LISTENING|NETSTAT_CONNECTED)) != (NETSTAT_LISTENING|NETSTAT_CONNECTED)) {
		if ((state == SS_UNCONNECTED) && (unix_flags & SO_ACCEPTCON)) {
			if (!(flags & NETSTAT_LISTENING))
				return 0;
		} else {
			if (!(flags & NETSTAT_CONNECTED))
				return 0;
		}
	}

	switch (proto) {
		case 0:
			ss_proto = "unix";
			break;
		default:
			ss_proto = "??";
	}

	switch (type) {
		case SOCK_STREAM:
			ss_type = "STREAM";
			break;
		case SOCK_DGRAM:
			ss_type = "DGRAM";
			break;
		case SOCK_RAW:
			ss_type = "RAW";
			break;
		case SOCK_RDM:
			ss_type = "RDM";
			break;
		case SOCK_SEQPACKET:
			ss_type = "SEQPACKET";
			break;
		default:
			ss_type = "UNKNOWN";
	}

	switch (state) {
		case SS_FREE:
			ss_state = "FREE";
			break;
		case SS_UNCONNECTED:
			/*
			 * Unconnected sockets may be listening
			 * for something.
			 */
			if (unix_flags & SO_ACCEPTCON) {
				ss_state = "LISTENING";
			} else {
				ss_state = "";
			}
			break;
		case SS_CONNECTING:
			ss_state = "CONNECTING";
			break;
		case SS_CONNECTED:
			ss_state = "CONNECTED";
			break;
		case SS_DISCONNECTING:
			ss_state = "DISCONNECTING";
			break;
		default:
			ss_state = "UNKNOWN";
	}

	strcpy(ss_flags, "[ ");
	if (unix_flags & SO_ACCEPTCON)
		strcat(ss_flags, "ACC ");
	if (unix_flags & SO_WAITDATA)
		strcat(ss_flags, "W ");
	if (unix_flags & SO_NOSPACE)
		strcat(ss_flags, "N ");
	strcat(ss_flags, "]");

	printf("%-5s %-6ld %-11s %-10s %-13s %6lu ",
		ss_proto, refcnt, ss_flags, ss_type, ss_state, inode
		);

#if ENABLE_FEATURE_NETSTAT_PRG
	if (option_mask32 & OPT_prg)
		printf("%-"PROGNAME_WIDTH_STR"s", prg_cache_get(inode));
#endif

	/* TODO: currently we stop at first NUL byte. Is it a problem? */
	line += path_ofs;
	*strchrnul(line, '\n') = '\0';
	while (*line)
		fputc_printable(*line++, stdout);
	bb_putchar('\n');
	return 0;
}

#define _PATH_PROCNET_UDP "/proc/net/udp"
#define _PATH_PROCNET_UDP6 "/proc/net/udp6"
#define _PATH_PROCNET_TCP "/proc/net/tcp"
#define _PATH_PROCNET_TCP6 "/proc/net/tcp6"
#define _PATH_PROCNET_RAW "/proc/net/raw"
#define _PATH_PROCNET_RAW6 "/proc/net/raw6"
#define _PATH_PROCNET_UNIX "/proc/net/unix"

static void do_info(const char *file, const char *name, int (*proc)(int, char *))
{
	int lnr;
	FILE *procinfo;
	char *buffer;

	procinfo = fopen_for_read(file);
	if (procinfo == NULL) {
		if (errno != ENOENT) {
			bb_simple_perror_msg(file);
		} else {
			bb_error_msg("no kernel support for %s", name);
		}
		return;
	}
	lnr = 0;
	/* Why? because xmalloc_fgets_str doesn't stop on NULs */
	while ((buffer = xmalloc_fgets_str(procinfo, "\n")) != NULL) {
		if (proc(lnr++, buffer))
			bb_error_msg("%s: bogus data on line %d", file, lnr);
		free(buffer);
	}
	fclose(procinfo);
}

int netstat_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
int netstat_main(int argc UNUSED_PARAM, char **argv)
{
	const char *net_conn_line_header = PRINT_NET_CONN_HEADER;
	unsigned opt;
#if ENABLE_FEATURE_IPV6
	smallint inet = 1;
	smallint inet6 = 1;
#else
	enum { inet = 1, inet6 = 0 };
#endif

	INIT_G();

	/* Option string must match NETSTAT_xxx constants */
	opt = getopt32(argv, NETSTAT_OPTS);
	if (opt & 0x1) { // -l
		flags &= ~NETSTAT_CONNECTED;
		flags |= NETSTAT_LISTENING;
	}
	if (opt & 0x2) flags |= NETSTAT_LISTENING | NETSTAT_CONNECTED; // -a
	//if (opt & 0x4) // -e
	if (opt & 0x8) flags |= NETSTAT_NUMERIC; // -n
	//if (opt & 0x10) // -t: NETSTAT_TCP
	//if (opt & 0x20) // -u: NETSTAT_UDP
	//if (opt & 0x40) // -w: NETSTAT_RAW
	//if (opt & 0x80) // -x: NETSTAT_UNIX
	if (opt & OPT_route) { // -r
#if ENABLE_ROUTE
		bb_displayroutes(flags & NETSTAT_NUMERIC, !(opt & OPT_extended));
		return 0;
#else
		bb_show_usage();
#endif
	}
	if (opt & OPT_wide) { // -W
		net_conn_line = PRINT_NET_CONN_WIDE;
		net_conn_line_header = PRINT_NET_CONN_HEADER_WIDE;
	}
#if ENABLE_FEATURE_NETSTAT_PRG
	if (opt & OPT_prg) { // -p
		prg_cache_load();
	}
#endif

	opt &= NETSTAT_ALLPROTO;
	if (opt) {
		flags &= ~NETSTAT_ALLPROTO;
		flags |= opt;
	}
	if (flags & (NETSTAT_TCP|NETSTAT_UDP|NETSTAT_RAW)) {
		printf("Active Internet connections ");	/* xxx */

		if ((flags & (NETSTAT_LISTENING|NETSTAT_CONNECTED)) == (NETSTAT_LISTENING|NETSTAT_CONNECTED))
			printf("(servers and established)");
		else if (flags & NETSTAT_LISTENING)
			printf("(only servers)");
		else
			printf("(w/o servers)");
		printf(net_conn_line_header, "Local Address", "Foreign Address");
		print_progname_banner();
		bb_putchar('\n');
	}
	if (inet && (flags & NETSTAT_TCP))
		do_info(_PATH_PROCNET_TCP, "AF INET (tcp)", tcp_do_one);
#if ENABLE_FEATURE_IPV6
	if (inet6 && (flags & NETSTAT_TCP))
		do_info(_PATH_PROCNET_TCP6, "AF INET6 (tcp)", tcp_do_one);
#endif
	if (inet && (flags & NETSTAT_UDP))
		do_info(_PATH_PROCNET_UDP, "AF INET (udp)", udp_do_one);
#if ENABLE_FEATURE_IPV6
	if (inet6 && (flags & NETSTAT_UDP))
		do_info(_PATH_PROCNET_UDP6, "AF INET6 (udp)", udp_do_one);
#endif
	if (inet && (flags & NETSTAT_RAW))
		do_info(_PATH_PROCNET_RAW, "AF INET (raw)", raw_do_one);
#if ENABLE_FEATURE_IPV6
	if (inet6 && (flags & NETSTAT_RAW))
		do_info(_PATH_PROCNET_RAW6, "AF INET6 (raw)", raw_do_one);
#endif
	if (flags & NETSTAT_UNIX) {
		printf("Active UNIX domain sockets ");
		if ((flags & (NETSTAT_LISTENING|NETSTAT_CONNECTED)) == (NETSTAT_LISTENING|NETSTAT_CONNECTED))
			printf("(servers and established)");
		else if (flags & NETSTAT_LISTENING)
			printf("(only servers)");
		else
			printf("(w/o servers)");
		printf("\nProto RefCnt Flags       Type       State         I-Node ");
		print_progname_banner();
		printf("Path\n");
		do_info(_PATH_PROCNET_UNIX, "AF UNIX", unix_do_one);
	}
	prg_cache_clear();
	return 0;
}