]> git.proxmox.com Git - mirror_iproute2.git/blame - misc/ss.c
ss: Dont show netlink and packet sockets by default
[mirror_iproute2.git] / misc / ss.c
CommitLineData
b9de3ecf 1/*
aba5acdf
SH
2 * ss.c "sockstat", socket statistics
3 *
4 * This program is free software; you can redistribute it and/or
5 * modify it under the terms of the GNU General Public License
6 * as published by the Free Software Foundation; either version
7 * 2 of the License, or (at your option) any later version.
8 *
9 * Authors: Alexey Kuznetsov, <kuznet@ms2.inr.ac.ru>
10 */
11
12#include <stdio.h>
13#include <stdlib.h>
14#include <unistd.h>
15#include <syslog.h>
16#include <fcntl.h>
17#include <sys/ioctl.h>
18#include <sys/socket.h>
19#include <sys/uio.h>
20#include <netinet/in.h>
21#include <string.h>
22#include <errno.h>
23#include <netdb.h>
24#include <arpa/inet.h>
aba5acdf
SH
25#include <dirent.h>
26#include <fnmatch.h>
ab61159a 27#include <getopt.h>
aba5acdf
SH
28
29#include "utils.h"
30#include "rt_names.h"
31#include "ll_map.h"
32#include "libnetlink.h"
aba5acdf
SH
33#include "SNAPSHOT.h"
34
9cb1eccf 35#include <linux/tcp.h>
f6062360 36#include <linux/sock_diag.h>
351efcde 37#include <linux/inet_diag.h>
dfbaa90d 38#include <linux/unix_diag.h>
372c30d2
ND
39#include <linux/netdevice.h> /* for MAX_ADDR_LEN */
40#include <linux/filter.h>
41#include <linux/packet_diag.h>
ecb928c8 42#include <linux/netlink_diag.h>
aba5acdf 43
8a4025f6 44#define MAGIC_SEQ 123456
45
5fb421d4 46#define DIAG_REQUEST(_req, _r) \
47 struct { \
48 struct nlmsghdr nlh; \
49 _r; \
50 } _req = { \
51 .nlh = { \
52 .nlmsg_type = SOCK_DIAG_BY_FAMILY, \
53 .nlmsg_flags = NLM_F_ROOT|NLM_F_MATCH|NLM_F_REQUEST,\
8a4025f6 54 .nlmsg_seq = MAGIC_SEQ, \
5fb421d4 55 .nlmsg_len = sizeof(_req), \
56 }, \
57 }
58
116ac927
RH
59#if HAVE_SELINUX
60#include <selinux/selinux.h>
61#else
62/* Stubs for SELinux functions */
63static int is_selinux_enabled(void)
64{
65 return -1;
66}
67
68static int getpidcon(pid_t pid, char **context)
69{
70 *context = NULL;
71 return -1;
72}
73
74static int getfilecon(char *path, char **context)
75{
76 *context = NULL;
77 return -1;
78}
79
80static int security_get_initial_context(char *name, char **context)
81{
82 *context = NULL;
83 return -1;
84}
85#endif
86
aba5acdf
SH
87int resolve_hosts = 0;
88int resolve_services = 1;
89int preferred_family = AF_UNSPEC;
90int show_options = 0;
91int show_details = 0;
92int show_users = 0;
93int show_mem = 0;
94int show_tcpinfo = 0;
372c30d2 95int show_bpf = 0;
116ac927
RH
96int show_proc_ctx = 0;
97int show_sock_ctx = 0;
98/* If show_users & show_proc_ctx only do user_ent_hash_build() once */
99int user_ent_hash_build_init = 0;
aba5acdf
SH
100
101int netid_width;
102int state_width;
103int addrp_width;
104int addr_width;
105int serv_width;
106int screen_width;
107
108static const char *TCP_PROTO = "tcp";
109static const char *UDP_PROTO = "udp";
110static const char *RAW_PROTO = "raw";
111static const char *dg_proto = NULL;
112
113enum
114{
115 TCP_DB,
351efcde 116 DCCP_DB,
aba5acdf
SH
117 UDP_DB,
118 RAW_DB,
119 UNIX_DG_DB,
120 UNIX_ST_DB,
30b669d7 121 UNIX_SQ_DB,
aba5acdf
SH
122 PACKET_DG_DB,
123 PACKET_R_DB,
124 NETLINK_DB,
125 MAX_DB
126};
127
128#define PACKET_DBM ((1<<PACKET_DG_DB)|(1<<PACKET_R_DB))
30b669d7 129#define UNIX_DBM ((1<<UNIX_DG_DB)|(1<<UNIX_ST_DB)|(1<<UNIX_SQ_DB))
aba5acdf
SH
130#define ALL_DB ((1<<MAX_DB)-1)
131
132enum {
7d105b56
SH
133 SS_UNKNOWN,
134 SS_ESTABLISHED,
135 SS_SYN_SENT,
136 SS_SYN_RECV,
137 SS_FIN_WAIT1,
138 SS_FIN_WAIT2,
139 SS_TIME_WAIT,
140 SS_CLOSE,
141 SS_CLOSE_WAIT,
142 SS_LAST_ACK,
143 SS_LISTEN,
144 SS_CLOSING,
145 SS_MAX
aba5acdf
SH
146};
147
148#define SS_ALL ((1<<SS_MAX)-1)
149
150#include "ssfilter.h"
151
152struct filter
153{
154 int dbs;
155 int states;
156 int families;
157 struct ssfilter *f;
158};
159
160struct filter default_filter = {
7de7e591 161 .dbs = ~0,
e7113c61
SH
162 .states = SS_ALL & ~((1<<SS_LISTEN)|(1<<SS_CLOSE)|(1<<SS_TIME_WAIT)|(1<<SS_SYN_RECV)),
163 .families= (1<<AF_INET)|(1<<AF_INET6),
aba5acdf
SH
164};
165
166struct filter current_filter;
167
ab01dbbb 168static FILE *generic_proc_open(const char *env, const char *name)
aba5acdf 169{
ab01dbbb 170 const char *p = getenv(env);
aba5acdf 171 char store[128];
ab01dbbb 172
aba5acdf
SH
173 if (!p) {
174 p = getenv("PROC_ROOT") ? : "/proc";
175 snprintf(store, sizeof(store)-1, "%s/%s", p, name);
176 p = store;
177 }
ab01dbbb
SH
178
179 return fopen(p, "r");
aba5acdf
SH
180}
181
ab01dbbb 182static FILE *net_tcp_open(void)
aba5acdf
SH
183{
184 return generic_proc_open("PROC_NET_TCP", "net/tcp");
185}
186
ab01dbbb 187static FILE *net_tcp6_open(void)
aba5acdf
SH
188{
189 return generic_proc_open("PROC_NET_TCP6", "net/tcp6");
190}
191
ab01dbbb 192static FILE *net_udp_open(void)
aba5acdf
SH
193{
194 return generic_proc_open("PROC_NET_UDP", "net/udp");
195}
196
ab01dbbb 197static FILE *net_udp6_open(void)
aba5acdf
SH
198{
199 return generic_proc_open("PROC_NET_UDP6", "net/udp6");
200}
201
ab01dbbb 202static FILE *net_raw_open(void)
aba5acdf
SH
203{
204 return generic_proc_open("PROC_NET_RAW", "net/raw");
205}
206
ab01dbbb 207static FILE *net_raw6_open(void)
aba5acdf
SH
208{
209 return generic_proc_open("PROC_NET_RAW6", "net/raw6");
210}
211
ab01dbbb 212static FILE *net_unix_open(void)
aba5acdf
SH
213{
214 return generic_proc_open("PROC_NET_UNIX", "net/unix");
215}
216
ab01dbbb 217static FILE *net_packet_open(void)
aba5acdf
SH
218{
219 return generic_proc_open("PROC_NET_PACKET", "net/packet");
220}
221
ab01dbbb 222static FILE *net_netlink_open(void)
aba5acdf
SH
223{
224 return generic_proc_open("PROC_NET_NETLINK", "net/netlink");
225}
226
ab01dbbb 227static FILE *slabinfo_open(void)
aba5acdf
SH
228{
229 return generic_proc_open("PROC_SLABINFO", "slabinfo");
230}
231
ab01dbbb 232static FILE *net_sockstat_open(void)
aba5acdf
SH
233{
234 return generic_proc_open("PROC_NET_SOCKSTAT", "net/sockstat");
235}
236
ab01dbbb 237static FILE *net_sockstat6_open(void)
aba5acdf
SH
238{
239 return generic_proc_open("PROC_NET_SOCKSTAT6", "net/sockstat6");
240}
241
ab01dbbb 242static FILE *net_snmp_open(void)
aba5acdf
SH
243{
244 return generic_proc_open("PROC_NET_SNMP", "net/snmp");
245}
246
ab01dbbb 247static FILE *ephemeral_ports_open(void)
aba5acdf
SH
248{
249 return generic_proc_open("PROC_IP_LOCAL_PORT_RANGE", "sys/net/ipv4/ip_local_port_range");
250}
251
fbc0f876
SF
252struct user_ent {
253 struct user_ent *next;
254 unsigned int ino;
255 int pid;
256 int fd;
116ac927
RH
257 char *process;
258 char *process_ctx;
259 char *socket_ctx;
fbc0f876
SF
260};
261
262#define USER_ENT_HASH_SIZE 256
263struct user_ent *user_ent_hash[USER_ENT_HASH_SIZE];
264
265static int user_ent_hashfn(unsigned int ino)
aba5acdf 266{
fbc0f876 267 int val = (ino >> 24) ^ (ino >> 16) ^ (ino >> 8) ^ ino;
aba5acdf 268
fbc0f876
SF
269 return val & (USER_ENT_HASH_SIZE - 1);
270}
271
116ac927
RH
272static void user_ent_add(unsigned int ino, char *process,
273 int pid, int fd,
274 char *proc_ctx,
275 char *sock_ctx)
fbc0f876
SF
276{
277 struct user_ent *p, **pp;
aba5acdf 278
116ac927
RH
279 p = malloc(sizeof(struct user_ent));
280 if (!p) {
281 fprintf(stderr, "ss: failed to malloc buffer\n");
fbc0f876 282 abort();
116ac927 283 }
fbc0f876
SF
284 p->next = NULL;
285 p->ino = ino;
286 p->pid = pid;
287 p->fd = fd;
116ac927
RH
288 p->process = strdup(process);
289 p->process_ctx = strdup(proc_ctx);
290 p->socket_ctx = strdup(sock_ctx);
fbc0f876
SF
291
292 pp = &user_ent_hash[user_ent_hashfn(ino)];
293 p->next = *pp;
294 *pp = p;
295}
aba5acdf 296
116ac927
RH
297static void user_ent_destroy(void)
298{
299 struct user_ent *p, *p_next;
300 int cnt = 0;
301
302 while (cnt != USER_ENT_HASH_SIZE) {
303 p = user_ent_hash[cnt];
304 while (p) {
305 free(p->process);
306 free(p->process_ctx);
307 free(p->socket_ctx);
308 p_next = p->next;
309 free(p);
310 p = p_next;
311 }
312 cnt++;
313 }
314}
315
fbc0f876
SF
316static void user_ent_hash_build(void)
317{
318 const char *root = getenv("PROC_ROOT") ? : "/proc/";
319 struct dirent *d;
320 char name[1024];
321 int nameoff;
322 DIR *dir;
116ac927
RH
323 char *pid_context;
324 char *sock_context;
325 const char *no_ctx = "unavailable";
326
327 /* If show_users & show_proc_ctx set only do this once */
328 if (user_ent_hash_build_init != 0)
329 return;
330
331 user_ent_hash_build_init = 1;
fbc0f876
SF
332
333 strcpy(name, root);
334 if (strlen(name) == 0 || name[strlen(name)-1] != '/')
aba5acdf 335 strcat(name, "/");
fbc0f876 336
aba5acdf 337 nameoff = strlen(name);
fbc0f876
SF
338
339 dir = opendir(name);
340 if (!dir)
341 return;
aba5acdf
SH
342
343 while ((d = readdir(dir)) != NULL) {
aba5acdf 344 struct dirent *d1;
aba5acdf 345 char process[16];
116ac927 346 char *p;
fbc0f876
SF
347 int pid, pos;
348 DIR *dir1;
349 char crap;
aba5acdf
SH
350
351 if (sscanf(d->d_name, "%d%c", &pid, &crap) != 1)
352 continue;
353
116ac927
RH
354 if (getpidcon(pid, &pid_context) != 0)
355 pid_context = strdup(no_ctx);
356
fbc0f876 357 sprintf(name + nameoff, "%d/fd/", pid);
aba5acdf
SH
358 pos = strlen(name);
359 if ((dir1 = opendir(name)) == NULL)
360 continue;
361
fbc0f876 362 process[0] = '\0';
116ac927 363 p = process;
aba5acdf
SH
364
365 while ((d1 = readdir(dir1)) != NULL) {
fbc0f876
SF
366 const char *pattern = "socket:[";
367 unsigned int ino;
aba5acdf 368 char lnk[64];
18445b3e 369 int fd;
788731b3 370 ssize_t link_len;
116ac927 371 char tmp[1024];
aba5acdf
SH
372
373 if (sscanf(d1->d_name, "%d%c", &fd, &crap) != 1)
374 continue;
375
376 sprintf(name+pos, "%d", fd);
788731b3
TJ
377
378 link_len = readlink(name, lnk, sizeof(lnk)-1);
379 if (link_len == -1)
380 continue;
381 lnk[link_len] = '\0';
382
383 if (strncmp(lnk, pattern, strlen(pattern)))
aba5acdf
SH
384 continue;
385
fbc0f876 386 sscanf(lnk, "socket:[%u]", &ino);
aba5acdf 387
116ac927
RH
388 snprintf(tmp, sizeof(tmp), "%s/%d/fd/%s",
389 root, pid, d1->d_name);
390
391 if (getfilecon(tmp, &sock_context) <= 0)
392 sock_context = strdup(no_ctx);
393
394 if (*p == '\0') {
aba5acdf 395 FILE *fp;
fbc0f876 396
116ac927
RH
397 snprintf(tmp, sizeof(tmp), "%s/%d/stat",
398 root, pid);
aba5acdf 399 if ((fp = fopen(tmp, "r")) != NULL) {
116ac927 400 fscanf(fp, "%*d (%[^)])", p);
aba5acdf
SH
401 fclose(fp);
402 }
403 }
116ac927
RH
404 user_ent_add(ino, p, pid, fd,
405 pid_context, sock_context);
406 free(sock_context);
aba5acdf 407 }
116ac927 408 free(pid_context);
aba5acdf
SH
409 closedir(dir1);
410 }
411 closedir(dir);
fbc0f876
SF
412}
413
116ac927
RH
414enum entry_types {
415 USERS,
416 PROC_CTX,
417 PROC_SOCK_CTX
418};
419
420#define ENTRY_BUF_SIZE 512
421static int find_entry(unsigned ino, char **buf, int type)
fbc0f876
SF
422{
423 struct user_ent *p;
424 int cnt = 0;
425 char *ptr;
116ac927
RH
426 char **new_buf = buf;
427 int len, new_buf_len;
428 int buf_used = 0;
429 int buf_len = 0;
fbc0f876
SF
430
431 if (!ino)
432 return 0;
433
434 p = user_ent_hash[user_ent_hashfn(ino)];
116ac927 435 ptr = *buf = NULL;
fbc0f876
SF
436 while (p) {
437 if (p->ino != ino)
438 goto next;
439
116ac927
RH
440 while (1) {
441 ptr = *buf + buf_used;
442 switch (type) {
443 case USERS:
444 len = snprintf(ptr, buf_len - buf_used,
445 "(\"%s\",pid=%d,fd=%d),",
446 p->process, p->pid, p->fd);
447 break;
448 case PROC_CTX:
449 len = snprintf(ptr, buf_len - buf_used,
450 "(\"%s\",pid=%d,proc_ctx=%s,fd=%d),",
451 p->process, p->pid,
452 p->process_ctx, p->fd);
453 break;
454 case PROC_SOCK_CTX:
455 len = snprintf(ptr, buf_len - buf_used,
456 "(\"%s\",pid=%d,proc_ctx=%s,fd=%d,sock_ctx=%s),",
457 p->process, p->pid,
458 p->process_ctx, p->fd,
459 p->socket_ctx);
460 break;
461 default:
462 fprintf(stderr, "ss: invalid type: %d\n", type);
463 abort();
464 }
fbc0f876 465
116ac927
RH
466 if (len < 0 || len >= buf_len - buf_used) {
467 new_buf_len = buf_len + ENTRY_BUF_SIZE;
468 *new_buf = realloc(*buf, new_buf_len);
469 if (!new_buf) {
470 fprintf(stderr, "ss: failed to malloc buffer\n");
471 abort();
472 }
473 **buf = **new_buf;
474 buf_len = new_buf_len;
475 continue;
476 } else {
477 buf_used += len;
478 break;
479 }
480 }
fbc0f876 481 cnt++;
116ac927 482next:
fbc0f876
SF
483 p = p->next;
484 }
116ac927
RH
485 if (buf_used) {
486 ptr = *buf + buf_used;
fbc0f876 487 ptr[-1] = '\0';
116ac927 488 }
aba5acdf
SH
489 return cnt;
490}
491
aba5acdf
SH
492/* Get stats from slab */
493
494struct slabstat
495{
496 int socks;
497 int tcp_ports;
498 int tcp_tws;
499 int tcp_syns;
500 int skbs;
501};
502
503struct slabstat slabstat;
504
ae665a52 505static const char *slabstat_ids[] =
aba5acdf
SH
506{
507 "sock",
508 "tcp_bind_bucket",
509 "tcp_tw_bucket",
510 "tcp_open_request",
511 "skbuff_head_cache",
512};
513
d1f28cf1 514static int get_slabstat(struct slabstat *s)
aba5acdf
SH
515{
516 char buf[256];
517 FILE *fp;
518 int cnt;
519
520 memset(s, 0, sizeof(*s));
521
ab01dbbb
SH
522 fp = slabinfo_open();
523 if (!fp)
aba5acdf
SH
524 return -1;
525
526 cnt = sizeof(*s)/sizeof(int);
527
528 fgets(buf, sizeof(buf), fp);
529 while(fgets(buf, sizeof(buf), fp) != NULL) {
530 int i;
531 for (i=0; i<sizeof(slabstat_ids)/sizeof(slabstat_ids[0]); i++) {
532 if (memcmp(buf, slabstat_ids[i], strlen(slabstat_ids[i])) == 0) {
533 sscanf(buf, "%*s%d", ((int *)s) + i);
534 cnt--;
535 break;
536 }
537 }
538 if (cnt <= 0)
539 break;
540 }
541
542 fclose(fp);
543 return 0;
544}
545
7d105b56
SH
546static const char *sstate_name[] = {
547 "UNKNOWN",
9cb1eccf
ED
548 [SS_ESTABLISHED] = "ESTAB",
549 [SS_SYN_SENT] = "SYN-SENT",
550 [SS_SYN_RECV] = "SYN-RECV",
551 [SS_FIN_WAIT1] = "FIN-WAIT-1",
552 [SS_FIN_WAIT2] = "FIN-WAIT-2",
553 [SS_TIME_WAIT] = "TIME-WAIT",
554 [SS_CLOSE] = "UNCONN",
555 [SS_CLOSE_WAIT] = "CLOSE-WAIT",
556 [SS_LAST_ACK] = "LAST-ACK",
557 [SS_LISTEN] = "LISTEN",
558 [SS_CLOSING] = "CLOSING",
aba5acdf
SH
559};
560
7d105b56
SH
561static const char *sstate_namel[] = {
562 "UNKNOWN",
9cb1eccf
ED
563 [SS_ESTABLISHED] = "established",
564 [SS_SYN_SENT] = "syn-sent",
565 [SS_SYN_RECV] = "syn-recv",
566 [SS_FIN_WAIT1] = "fin-wait-1",
567 [SS_FIN_WAIT2] = "fin-wait-2",
568 [SS_TIME_WAIT] = "time-wait",
569 [SS_CLOSE] = "unconnected",
570 [SS_CLOSE_WAIT] = "close-wait",
571 [SS_LAST_ACK] = "last-ack",
572 [SS_LISTEN] = "listening",
573 [SS_CLOSING] = "closing",
aba5acdf
SH
574};
575
576struct tcpstat
577{
578 inet_prefix local;
579 inet_prefix remote;
580 int lport;
581 int rport;
582 int state;
583 int rq, wq;
584 int timer;
585 int timeout;
586 int retrs;
e7113c61 587 unsigned ino;
aba5acdf 588 int probes;
e7113c61 589 unsigned uid;
aba5acdf
SH
590 int refcnt;
591 unsigned long long sk;
592 int rto, ato, qack, cwnd, ssthresh;
593};
594
7d105b56 595static const char *tmr_name[] = {
aba5acdf
SH
596 "off",
597 "on",
598 "keepalive",
599 "timewait",
600 "persist",
601 "unknown"
602};
603
d1f28cf1 604static const char *print_ms_timer(int timeout)
aba5acdf
SH
605{
606 static char buf[64];
607 int secs, msecs, minutes;
608 if (timeout < 0)
609 timeout = 0;
610 secs = timeout/1000;
611 minutes = secs/60;
612 secs = secs%60;
613 msecs = timeout%1000;
614 buf[0] = 0;
615 if (minutes) {
616 msecs = 0;
617 snprintf(buf, sizeof(buf)-16, "%dmin", minutes);
618 if (minutes > 9)
619 secs = 0;
620 }
621 if (secs) {
622 if (secs > 9)
623 msecs = 0;
624 sprintf(buf+strlen(buf), "%d%s", secs, msecs ? "." : "sec");
625 }
626 if (msecs)
627 sprintf(buf+strlen(buf), "%03dms", msecs);
628 return buf;
e7113c61 629}
aba5acdf 630
d1f28cf1 631static const char *print_hz_timer(int timeout)
aba5acdf 632{
2d44be19 633 int hz = get_user_hz();
aba5acdf 634 return print_ms_timer(((timeout*1000) + hz-1)/hz);
e7113c61 635}
aba5acdf
SH
636
637struct scache
638{
639 struct scache *next;
640 int port;
641 char *name;
642 const char *proto;
643};
644
645struct scache *rlist;
646
d1f28cf1 647static void init_service_resolver(void)
aba5acdf
SH
648{
649 char buf[128];
650 FILE *fp = popen("/usr/sbin/rpcinfo -p 2>/dev/null", "r");
651 if (fp) {
652 fgets(buf, sizeof(buf), fp);
653 while (fgets(buf, sizeof(buf), fp) != NULL) {
654 unsigned int progn, port;
655 char proto[128], prog[128];
656 if (sscanf(buf, "%u %*d %s %u %s", &progn, proto,
657 &port, prog+4) == 4) {
658 struct scache *c = malloc(sizeof(*c));
659 if (c) {
660 c->port = port;
661 memcpy(prog, "rpc.", 4);
662 c->name = strdup(prog);
663 if (strcmp(proto, TCP_PROTO) == 0)
664 c->proto = TCP_PROTO;
665 else if (strcmp(proto, UDP_PROTO) == 0)
666 c->proto = UDP_PROTO;
667 else
668 c->proto = NULL;
669 c->next = rlist;
670 rlist = c;
671 }
672 }
673 }
2bcc3c16 674 pclose(fp);
aba5acdf
SH
675 }
676}
677
ab61159a
SH
678static int ip_local_port_min, ip_local_port_max;
679
680/* Even do not try default linux ephemeral port ranges:
681 * default /etc/services contains so much of useless crap
682 * wouldbe "allocated" to this area that resolution
683 * is really harmful. I shrug each time when seeing
684 * "socks" or "cfinger" in dumps.
685 */
686static int is_ephemeral(int port)
687{
688 if (!ip_local_port_min) {
ab01dbbb 689 FILE *f = ephemeral_ports_open();
ab61159a 690 if (f) {
ae665a52 691 fscanf(f, "%d %d",
ab61159a
SH
692 &ip_local_port_min, &ip_local_port_max);
693 fclose(f);
694 } else {
695 ip_local_port_min = 1024;
696 ip_local_port_max = 4999;
697 }
698 }
699
700 return (port >= ip_local_port_min && port<= ip_local_port_max);
701}
702
703
d1f28cf1 704static const char *__resolve_service(int port)
aba5acdf
SH
705{
706 struct scache *c;
707
708 for (c = rlist; c; c = c->next) {
709 if (c->port == port && c->proto == dg_proto)
710 return c->name;
711 }
712
ab61159a 713 if (!is_ephemeral(port)) {
aba5acdf
SH
714 static int notfirst;
715 struct servent *se;
716 if (!notfirst) {
717 setservent(1);
718 notfirst = 1;
ae665a52 719 }
aba5acdf
SH
720 se = getservbyport(htons(port), dg_proto);
721 if (se)
722 return se->s_name;
723 }
724
725 return NULL;
726}
727
728
d1f28cf1 729static const char *resolve_service(int port)
aba5acdf
SH
730{
731 static char buf[128];
732 static struct scache cache[256];
733
734 if (port == 0) {
735 buf[0] = '*';
736 buf[1] = 0;
737 return buf;
738 }
739
740 if (resolve_services) {
741 if (dg_proto == RAW_PROTO) {
742 return inet_proto_n2a(port, buf, sizeof(buf));
743 } else {
744 struct scache *c;
745 const char *res;
746 int hash = (port^(((unsigned long)dg_proto)>>2))&255;
747
ae665a52 748 for (c = &cache[hash]; c; c = c->next) {
aba5acdf
SH
749 if (c->port == port &&
750 c->proto == dg_proto) {
751 if (c->name)
752 return c->name;
753 goto do_numeric;
754 }
755 }
756
757 if ((res = __resolve_service(port)) != NULL) {
758 if ((c = malloc(sizeof(*c))) == NULL)
759 goto do_numeric;
760 } else {
761 c = &cache[hash];
762 if (c->name)
763 free(c->name);
764 }
765 c->port = port;
766 c->name = NULL;
767 c->proto = dg_proto;
768 if (res) {
769 c->name = strdup(res);
770 c->next = cache[hash].next;
771 cache[hash].next = c;
772 }
773 if (c->name)
774 return c->name;
775 }
776 }
777
778 do_numeric:
779 sprintf(buf, "%u", port);
780 return buf;
781}
782
7c8a3cfb 783static void formatted_print(const inet_prefix *a, int port, unsigned int ifindex)
aba5acdf
SH
784{
785 char buf[1024];
786 const char *ap = buf;
787 int est_len;
788
789 est_len = addr_width;
790
791 if (a->family == AF_INET) {
792 if (a->data[0] == 0) {
793 buf[0] = '*';
794 buf[1] = 0;
795 } else {
796 ap = format_host(AF_INET, 4, a->data, buf, sizeof(buf));
797 }
798 } else {
799 ap = format_host(a->family, 16, a->data, buf, sizeof(buf));
800 est_len = strlen(ap);
801 if (est_len <= addr_width)
802 est_len = addr_width;
803 else
804 est_len = addr_width + ((est_len-addr_width+3)/4)*4;
805 }
7c8a3cfb
FLB
806 if (ifindex) {
807 const char *ifname = ll_index_to_name(ifindex);
808 const int len = strlen(ifname) + 1; /* +1 for percent char */
809
810 printf("%*s%%%s:%-*s ", est_len - len, ap, ifname, serv_width,
811 resolve_service(port));
812 } else
813 printf("%*s:%-*s ", est_len, ap, serv_width, resolve_service(port));
aba5acdf
SH
814}
815
816struct aafilter
817{
818 inet_prefix addr;
819 int port;
820 struct aafilter *next;
821};
822
d1f28cf1
SH
823static int inet2_addr_match(const inet_prefix *a, const inet_prefix *p,
824 int plen)
aba5acdf
SH
825{
826 if (!inet_addr_match(a, p, plen))
827 return 0;
7d105b56 828
aba5acdf
SH
829 /* Cursed "v4 mapped" addresses: v4 mapped socket matches
830 * pure IPv4 rule, but v4-mapped rule selects only v4-mapped
831 * sockets. Fair? */
832 if (p->family == AF_INET && a->family == AF_INET6) {
833 if (a->data[0] == 0 && a->data[1] == 0 &&
834 a->data[2] == htonl(0xffff)) {
835 inet_prefix tmp = *a;
836 tmp.data[0] = a->data[3];
837 return inet_addr_match(&tmp, p, plen);
838 }
839 }
840 return 1;
841}
842
d1f28cf1 843static int unix_match(const inet_prefix *a, const inet_prefix *p)
aba5acdf
SH
844{
845 char *addr, *pattern;
846 memcpy(&addr, a->data, sizeof(addr));
847 memcpy(&pattern, p->data, sizeof(pattern));
848 if (pattern == NULL)
849 return 1;
850 if (addr == NULL)
851 addr = "";
852 return !fnmatch(pattern, addr, 0);
853}
854
d1f28cf1 855static int run_ssfilter(struct ssfilter *f, struct tcpstat *s)
aba5acdf
SH
856{
857 switch (f->type) {
858 case SSF_S_AUTO:
859 {
860 static int low, high=65535;
861
862 if (s->local.family == AF_UNIX) {
863 char *p;
864 memcpy(&p, s->local.data, sizeof(p));
865 return p == NULL || (p[0] == '@' && strlen(p) == 6 &&
ae665a52 866 strspn(p+1, "0123456789abcdef") == 5);
aba5acdf
SH
867 }
868 if (s->local.family == AF_PACKET)
869 return s->lport == 0 && s->local.data == 0;
870 if (s->local.family == AF_NETLINK)
871 return s->lport < 0;
872
873 if (!low) {
ab01dbbb 874 FILE *fp = ephemeral_ports_open();
aba5acdf
SH
875 if (fp) {
876 fscanf(fp, "%d%d", &low, &high);
877 fclose(fp);
878 }
879 }
880 return s->lport >= low && s->lport <= high;
881 }
882 case SSF_DCOND:
883 {
884 struct aafilter *a = (void*)f->pred;
885 if (a->addr.family == AF_UNIX)
886 return unix_match(&s->remote, &a->addr);
887 if (a->port != -1 && a->port != s->rport)
888 return 0;
889 if (a->addr.bitlen) {
890 do {
891 if (!inet2_addr_match(&s->remote, &a->addr, a->addr.bitlen))
892 return 1;
893 } while ((a = a->next) != NULL);
894 return 0;
895 }
896 return 1;
897 }
898 case SSF_SCOND:
899 {
900 struct aafilter *a = (void*)f->pred;
901 if (a->addr.family == AF_UNIX)
902 return unix_match(&s->local, &a->addr);
903 if (a->port != -1 && a->port != s->lport)
904 return 0;
905 if (a->addr.bitlen) {
906 do {
907 if (!inet2_addr_match(&s->local, &a->addr, a->addr.bitlen))
908 return 1;
ae665a52 909 } while ((a = a->next) != NULL);
aba5acdf
SH
910 return 0;
911 }
912 return 1;
913 }
914 case SSF_D_GE:
915 {
916 struct aafilter *a = (void*)f->pred;
917 return s->rport >= a->port;
918 }
919 case SSF_D_LE:
920 {
921 struct aafilter *a = (void*)f->pred;
922 return s->rport <= a->port;
923 }
924 case SSF_S_GE:
925 {
926 struct aafilter *a = (void*)f->pred;
927 return s->lport >= a->port;
928 }
929 case SSF_S_LE:
930 {
931 struct aafilter *a = (void*)f->pred;
932 return s->lport <= a->port;
933 }
934
935 /* Yup. It is recursion. Sorry. */
936 case SSF_AND:
937 return run_ssfilter(f->pred, s) && run_ssfilter(f->post, s);
938 case SSF_OR:
939 return run_ssfilter(f->pred, s) || run_ssfilter(f->post, s);
940 case SSF_NOT:
941 return !run_ssfilter(f->pred, s);
942 default:
943 abort();
944 }
945}
946
ae665a52 947/* Relocate external jumps by reloc. */
b4b0b7d5 948static void ssfilter_patch(char *a, int len, int reloc)
aba5acdf
SH
949{
950 while (len > 0) {
351efcde 951 struct inet_diag_bc_op *op = (struct inet_diag_bc_op*)a;
aba5acdf
SH
952 if (op->no == len+4)
953 op->no += reloc;
954 len -= op->yes;
955 a += op->yes;
956 }
957 if (len < 0)
958 abort();
959}
960
b4b0b7d5 961static int ssfilter_bytecompile(struct ssfilter *f, char **bytecode)
aba5acdf
SH
962{
963 switch (f->type) {
964 case SSF_S_AUTO:
965 {
966 if (!(*bytecode=malloc(4))) abort();
351efcde 967 ((struct inet_diag_bc_op*)*bytecode)[0] = (struct inet_diag_bc_op){ INET_DIAG_BC_AUTO, 4, 8 };
df39de8d 968 return 4;
aba5acdf
SH
969 }
970 case SSF_DCOND:
971 case SSF_SCOND:
972 {
973 struct aafilter *a = (void*)f->pred;
974 struct aafilter *b;
975 char *ptr;
351efcde 976 int code = (f->type == SSF_DCOND ? INET_DIAG_BC_D_COND : INET_DIAG_BC_S_COND);
aba5acdf
SH
977 int len = 0;
978
979 for (b=a; b; b=b->next) {
351efcde 980 len += 4 + sizeof(struct inet_diag_hostcond);
aba5acdf
SH
981 if (a->addr.family == AF_INET6)
982 len += 16;
983 else
984 len += 4;
985 if (b->next)
986 len += 4;
987 }
988 if (!(ptr = malloc(len))) abort();
989 *bytecode = ptr;
990 for (b=a; b; b=b->next) {
351efcde 991 struct inet_diag_bc_op *op = (struct inet_diag_bc_op *)ptr;
aba5acdf 992 int alen = (a->addr.family == AF_INET6 ? 16 : 4);
351efcde
SH
993 int oplen = alen + 4 + sizeof(struct inet_diag_hostcond);
994 struct inet_diag_hostcond *cond = (struct inet_diag_hostcond*)(ptr+4);
aba5acdf 995
351efcde 996 *op = (struct inet_diag_bc_op){ code, oplen, oplen+4 };
aba5acdf
SH
997 cond->family = a->addr.family;
998 cond->port = a->port;
999 cond->prefix_len = a->addr.bitlen;
1000 memcpy(cond->addr, a->addr.data, alen);
1001 ptr += oplen;
1002 if (b->next) {
351efcde
SH
1003 op = (struct inet_diag_bc_op *)ptr;
1004 *op = (struct inet_diag_bc_op){ INET_DIAG_BC_JMP, 4, len - (ptr-*bytecode)};
aba5acdf
SH
1005 ptr += 4;
1006 }
1007 }
1008 return ptr - *bytecode;
1009 }
1010 case SSF_D_GE:
1011 {
1012 struct aafilter *x = (void*)f->pred;
1013 if (!(*bytecode=malloc(8))) abort();
351efcde
SH
1014 ((struct inet_diag_bc_op*)*bytecode)[0] = (struct inet_diag_bc_op){ INET_DIAG_BC_D_GE, 8, 12 };
1015 ((struct inet_diag_bc_op*)*bytecode)[1] = (struct inet_diag_bc_op){ 0, 0, x->port };
aba5acdf
SH
1016 return 8;
1017 }
1018 case SSF_D_LE:
1019 {
1020 struct aafilter *x = (void*)f->pred;
1021 if (!(*bytecode=malloc(8))) abort();
351efcde
SH
1022 ((struct inet_diag_bc_op*)*bytecode)[0] = (struct inet_diag_bc_op){ INET_DIAG_BC_D_LE, 8, 12 };
1023 ((struct inet_diag_bc_op*)*bytecode)[1] = (struct inet_diag_bc_op){ 0, 0, x->port };
aba5acdf
SH
1024 return 8;
1025 }
1026 case SSF_S_GE:
1027 {
1028 struct aafilter *x = (void*)f->pred;
1029 if (!(*bytecode=malloc(8))) abort();
351efcde
SH
1030 ((struct inet_diag_bc_op*)*bytecode)[0] = (struct inet_diag_bc_op){ INET_DIAG_BC_S_GE, 8, 12 };
1031 ((struct inet_diag_bc_op*)*bytecode)[1] = (struct inet_diag_bc_op){ 0, 0, x->port };
aba5acdf
SH
1032 return 8;
1033 }
1034 case SSF_S_LE:
1035 {
1036 struct aafilter *x = (void*)f->pred;
1037 if (!(*bytecode=malloc(8))) abort();
351efcde
SH
1038 ((struct inet_diag_bc_op*)*bytecode)[0] = (struct inet_diag_bc_op){ INET_DIAG_BC_S_LE, 8, 12 };
1039 ((struct inet_diag_bc_op*)*bytecode)[1] = (struct inet_diag_bc_op){ 0, 0, x->port };
aba5acdf
SH
1040 return 8;
1041 }
1042
1043 case SSF_AND:
1044 {
2a4fa1c3
AH
1045 char *a1, *a2, *a;
1046 int l1, l2;
aba5acdf
SH
1047 l1 = ssfilter_bytecompile(f->pred, &a1);
1048 l2 = ssfilter_bytecompile(f->post, &a2);
1049 if (!(a = malloc(l1+l2))) abort();
1050 memcpy(a, a1, l1);
1051 memcpy(a+l1, a2, l2);
1052 free(a1); free(a2);
1053 ssfilter_patch(a, l1, l2);
1054 *bytecode = a;
1055 return l1+l2;
1056 }
1057 case SSF_OR:
1058 {
2a4fa1c3
AH
1059 char *a1, *a2, *a;
1060 int l1, l2;
aba5acdf
SH
1061 l1 = ssfilter_bytecompile(f->pred, &a1);
1062 l2 = ssfilter_bytecompile(f->post, &a2);
1063 if (!(a = malloc(l1+l2+4))) abort();
1064 memcpy(a, a1, l1);
1065 memcpy(a+l1+4, a2, l2);
1066 free(a1); free(a2);
351efcde 1067 *(struct inet_diag_bc_op*)(a+l1) = (struct inet_diag_bc_op){ INET_DIAG_BC_JMP, 4, l2+4 };
aba5acdf
SH
1068 *bytecode = a;
1069 return l1+l2+4;
1070 }
1071 case SSF_NOT:
1072 {
2a4fa1c3
AH
1073 char *a1, *a;
1074 int l1;
aba5acdf
SH
1075 l1 = ssfilter_bytecompile(f->pred, &a1);
1076 if (!(a = malloc(l1+4))) abort();
1077 memcpy(a, a1, l1);
1078 free(a1);
351efcde 1079 *(struct inet_diag_bc_op*)(a+l1) = (struct inet_diag_bc_op){ INET_DIAG_BC_JMP, 4, 8 };
aba5acdf
SH
1080 *bytecode = a;
1081 return l1+4;
1082 }
1083 default:
1084 abort();
1085 }
1086}
1087
b4b0b7d5 1088static int remember_he(struct aafilter *a, struct hostent *he)
aba5acdf 1089{
ae665a52 1090 char **ptr = he->h_addr_list;
aba5acdf
SH
1091 int cnt = 0;
1092 int len;
1093
1094 if (he->h_addrtype == AF_INET)
1095 len = 4;
1096 else if (he->h_addrtype == AF_INET6)
1097 len = 16;
1098 else
1099 return 0;
1100
1101 while (*ptr) {
1102 struct aafilter *b = a;
1103 if (a->addr.bitlen) {
1104 if ((b = malloc(sizeof(*b))) == NULL)
1105 return cnt;
1106 *b = *a;
1107 b->next = a->next;
1108 a->next = b;
1109 }
1110 memcpy(b->addr.data, *ptr, len);
1111 b->addr.bytelen = len;
1112 b->addr.bitlen = len*8;
1113 b->addr.family = he->h_addrtype;
1114 ptr++;
1115 cnt++;
1116 }
1117 return cnt;
1118}
1119
b4b0b7d5 1120static int get_dns_host(struct aafilter *a, const char *addr, int fam)
aba5acdf
SH
1121{
1122 static int notfirst;
1123 int cnt = 0;
1124 struct hostent *he;
1125
1126 a->addr.bitlen = 0;
1127 if (!notfirst) {
1128 sethostent(1);
1129 notfirst = 1;
1130 }
1131 he = gethostbyname2(addr, fam == AF_UNSPEC ? AF_INET : fam);
1132 if (he)
1133 cnt = remember_he(a, he);
1134 if (fam == AF_UNSPEC) {
1135 he = gethostbyname2(addr, AF_INET6);
1136 if (he)
1137 cnt += remember_he(a, he);
1138 }
1139 return !cnt;
1140}
1141
b4b0b7d5 1142static int xll_initted = 0;
aba5acdf 1143
b4b0b7d5 1144static void xll_init(void)
aba5acdf
SH
1145{
1146 struct rtnl_handle rth;
d2468da0
SH
1147 if (rtnl_open(&rth, 0) < 0)
1148 exit(1);
1149
aba5acdf
SH
1150 ll_init_map(&rth);
1151 rtnl_close(&rth);
1152 xll_initted = 1;
1153}
1154
b4b0b7d5 1155static const char *xll_index_to_name(int index)
aba5acdf
SH
1156{
1157 if (!xll_initted)
1158 xll_init();
1159 return ll_index_to_name(index);
1160}
1161
b4b0b7d5 1162static int xll_name_to_index(const char *dev)
aba5acdf
SH
1163{
1164 if (!xll_initted)
1165 xll_init();
1166 return ll_name_to_index(dev);
1167}
1168
1169void *parse_hostcond(char *addr)
1170{
1171 char *port = NULL;
1172 struct aafilter a;
1173 struct aafilter *res;
1174 int fam = preferred_family;
1175
1176 memset(&a, 0, sizeof(a));
1177 a.port = -1;
1178
1179 if (fam == AF_UNIX || strncmp(addr, "unix:", 5) == 0) {
1180 char *p;
1181 a.addr.family = AF_UNIX;
1182 if (strncmp(addr, "unix:", 5) == 0)
1183 addr+=5;
1184 p = strdup(addr);
1185 a.addr.bitlen = 8*strlen(p);
1186 memcpy(a.addr.data, &p, sizeof(p));
1187 goto out;
1188 }
1189
1190 if (fam == AF_PACKET || strncmp(addr, "link:", 5) == 0) {
1191 a.addr.family = AF_PACKET;
1192 a.addr.bitlen = 0;
1193 if (strncmp(addr, "link:", 5) == 0)
1194 addr+=5;
1195 port = strchr(addr, ':');
1196 if (port) {
1197 *port = 0;
1198 if (port[1] && strcmp(port+1, "*")) {
1199 if (get_integer(&a.port, port+1, 0)) {
1200 if ((a.port = xll_name_to_index(port+1)) <= 0)
1201 return NULL;
1202 }
1203 }
1204 }
1205 if (addr[0] && strcmp(addr, "*")) {
1206 unsigned short tmp;
1207 a.addr.bitlen = 32;
1208 if (ll_proto_a2n(&tmp, addr))
1209 return NULL;
1210 a.addr.data[0] = ntohs(tmp);
1211 }
1212 goto out;
1213 }
1214
1215 if (fam == AF_NETLINK || strncmp(addr, "netlink:", 8) == 0) {
1216 a.addr.family = AF_NETLINK;
1217 a.addr.bitlen = 0;
1218 if (strncmp(addr, "netlink:", 8) == 0)
1219 addr+=8;
1220 port = strchr(addr, ':');
1221 if (port) {
1222 *port = 0;
1223 if (port[1] && strcmp(port+1, "*")) {
1224 if (get_integer(&a.port, port+1, 0)) {
1225 if (strcmp(port+1, "kernel") == 0)
1226 a.port = 0;
1227 else
1228 return NULL;
1229 }
1230 }
1231 }
1232 if (addr[0] && strcmp(addr, "*")) {
1233 a.addr.bitlen = 32;
b00daf6a 1234 if (nl_proto_a2n(&a.addr.data[0], addr) == -1)
1235 return NULL;
aba5acdf
SH
1236 }
1237 goto out;
1238 }
1239
1240 if (strncmp(addr, "inet:", 5) == 0) {
1241 addr += 5;
1242 fam = AF_INET;
1243 } else if (strncmp(addr, "inet6:", 6) == 0) {
1244 addr += 6;
1245 fam = AF_INET6;
1246 }
1247
1248 /* URL-like literal [] */
1249 if (addr[0] == '[') {
1250 addr++;
1251 if ((port = strchr(addr, ']')) == NULL)
1252 return NULL;
1253 *port++ = 0;
1254 } else if (addr[0] == '*') {
1255 port = addr+1;
1256 } else {
1257 port = strrchr(strchr(addr, '/') ? : addr, ':');
1258 }
1259 if (port && *port) {
1260 if (*port != ':')
1261 return NULL;
1262 *port++ = 0;
1263 if (*port && *port != '*') {
1264 if (get_integer(&a.port, port, 0)) {
1265 struct servent *se1 = NULL;
1266 struct servent *se2 = NULL;
1267 if (current_filter.dbs&(1<<UDP_DB))
1268 se1 = getservbyname(port, UDP_PROTO);
1269 if (current_filter.dbs&(1<<TCP_DB))
1270 se2 = getservbyname(port, TCP_PROTO);
1271 if (se1 && se2 && se1->s_port != se2->s_port) {
1272 fprintf(stderr, "Error: ambiguous port \"%s\".\n", port);
1273 return NULL;
1274 }
1275 if (!se1)
1276 se1 = se2;
1277 if (se1) {
1278 a.port = ntohs(se1->s_port);
1279 } else {
1280 struct scache *s;
1281 for (s = rlist; s; s = s->next) {
1282 if ((s->proto == UDP_PROTO &&
1283 (current_filter.dbs&(1<<UDP_DB))) ||
1284 (s->proto == TCP_PROTO &&
1285 (current_filter.dbs&(1<<TCP_DB)))) {
1286 if (s->name && strcmp(s->name, port) == 0) {
1287 if (a.port > 0 && a.port != s->port) {
1288 fprintf(stderr, "Error: ambiguous port \"%s\".\n", port);
1289 return NULL;
1290 }
1291 a.port = s->port;
1292 }
1293 }
1294 }
1295 if (a.port <= 0) {
1296 fprintf(stderr, "Error: \"%s\" does not look like a port.\n", port);
1297 return NULL;
1298 }
1299 }
1300 }
1301 }
1302 }
1303 if (addr && *addr && *addr != '*') {
1304 if (get_prefix_1(&a.addr, addr, fam)) {
1305 if (get_dns_host(&a, addr, fam)) {
1306 fprintf(stderr, "Error: an inet prefix is expected rather than \"%s\".\n", addr);
1307 return NULL;
1308 }
1309 }
1310 }
1311
1312 out:
1313 res = malloc(sizeof(*res));
1314 if (res)
1315 memcpy(res, &a, sizeof(a));
1316 return res;
1317}
1318
ab01dbbb 1319static int tcp_show_line(char *line, const struct filter *f, int family)
aba5acdf
SH
1320{
1321 struct tcpstat s;
1322 char *loc, *rem, *data;
1323 char opt[256];
1324 int n;
1325 char *p;
ae665a52 1326
aba5acdf
SH
1327 if ((p = strchr(line, ':')) == NULL)
1328 return -1;
1329 loc = p+2;
ae665a52 1330
aba5acdf
SH
1331 if ((p = strchr(loc, ':')) == NULL)
1332 return -1;
1333 p[5] = 0;
1334 rem = p+6;
ae665a52 1335
aba5acdf
SH
1336 if ((p = strchr(rem, ':')) == NULL)
1337 return -1;
1338 p[5] = 0;
1339 data = p+6;
ae665a52 1340
aba5acdf
SH
1341 do {
1342 int state = (data[1] >= 'A') ? (data[1] - 'A' + 10) : (data[1] - '0');
1343
1344 if (!(f->states & (1<<state)))
1345 return 0;
1346 } while (0);
ae665a52 1347
aba5acdf
SH
1348 s.local.family = s.remote.family = family;
1349 if (family == AF_INET) {
1350 sscanf(loc, "%x:%x", s.local.data, (unsigned*)&s.lport);
1351 sscanf(rem, "%x:%x", s.remote.data, (unsigned*)&s.rport);
1352 s.local.bytelen = s.remote.bytelen = 4;
1353 } else {
1354 sscanf(loc, "%08x%08x%08x%08x:%x",
1355 s.local.data,
1356 s.local.data+1,
1357 s.local.data+2,
1358 s.local.data+3,
1359 &s.lport);
1360 sscanf(rem, "%08x%08x%08x%08x:%x",
1361 s.remote.data,
1362 s.remote.data+1,
1363 s.remote.data+2,
1364 s.remote.data+3,
1365 &s.rport);
1366 s.local.bytelen = s.remote.bytelen = 16;
1367 }
ae665a52 1368
aba5acdf
SH
1369 if (f->f && run_ssfilter(f->f, &s) == 0)
1370 return 0;
ae665a52 1371
aba5acdf 1372 opt[0] = 0;
e7113c61 1373 n = sscanf(data, "%x %x:%x %x:%x %x %d %d %u %d %llx %d %d %d %d %d %[^\n]\n",
aba5acdf
SH
1374 &s.state, &s.wq, &s.rq,
1375 &s.timer, &s.timeout, &s.retrs, &s.uid, &s.probes, &s.ino,
1376 &s.refcnt, &s.sk, &s.rto, &s.ato, &s.qack,
1377 &s.cwnd, &s.ssthresh, opt);
ae665a52 1378
aba5acdf
SH
1379 if (n < 17)
1380 opt[0] = 0;
ae665a52 1381
aba5acdf
SH
1382 if (n < 12) {
1383 s.rto = 0;
1384 s.cwnd = 2;
1385 s.ssthresh = -1;
1386 s.ato = s.qack = 0;
1387 }
ae665a52 1388
aba5acdf
SH
1389 if (netid_width)
1390 printf("%-*s ", netid_width, "tcp");
1391 if (state_width)
1392 printf("%-*s ", state_width, sstate_name[s.state]);
ae665a52 1393
aba5acdf 1394 printf("%-6d %-6d ", s.rq, s.wq);
ae665a52 1395
7c8a3cfb
FLB
1396 formatted_print(&s.local, s.lport, 0);
1397 formatted_print(&s.remote, s.rport, 0);
ae665a52 1398
aba5acdf
SH
1399 if (show_options) {
1400 if (s.timer) {
1401 if (s.timer > 4)
1402 s.timer = 5;
1403 printf(" timer:(%s,%s,%d)",
1404 tmr_name[s.timer],
1405 print_hz_timer(s.timeout),
1406 s.timer != 1 ? s.probes : s.retrs);
1407 }
1408 }
1409 if (show_tcpinfo) {
4c1db131
SH
1410 int hz = get_user_hz();
1411 if (s.rto && s.rto != 3*hz)
1412 printf(" rto:%g", (double)s.rto/hz);
aba5acdf 1413 if (s.ato)
4c1db131 1414 printf(" ato:%g", (double)s.ato/hz);
aba5acdf
SH
1415 if (s.cwnd != 2)
1416 printf(" cwnd:%d", s.cwnd);
1417 if (s.ssthresh != -1)
1418 printf(" ssthresh:%d", s.ssthresh);
1419 if (s.qack/2)
1420 printf(" qack:%d", s.qack/2);
1421 if (s.qack&1)
1422 printf(" bidir");
1423 }
116ac927
RH
1424 char *buf = NULL;
1425 if (show_proc_ctx || show_sock_ctx) {
1426 if (find_entry(s.ino, &buf,
1427 (show_proc_ctx & show_sock_ctx) ?
1428 PROC_SOCK_CTX : PROC_CTX) > 0) {
1429 printf(" users:(%s)", buf);
1430 free(buf);
1431 }
1432 } else if (show_users) {
1433 if (find_entry(s.ino, &buf, USERS) > 0) {
1434 printf(" users:(%s)", buf);
1435 free(buf);
1436 }
aba5acdf 1437 }
116ac927 1438
aba5acdf
SH
1439 if (show_details) {
1440 if (s.uid)
1441 printf(" uid:%u", (unsigned)s.uid);
e7113c61 1442 printf(" ino:%u", s.ino);
aba5acdf
SH
1443 printf(" sk:%llx", s.sk);
1444 if (opt[0])
1445 printf(" opt:\"%s\"", opt);
1446 }
1447 printf("\n");
1448
1449 return 0;
1450}
1451
ab01dbbb
SH
1452static int generic_record_read(FILE *fp,
1453 int (*worker)(char*, const struct filter *, int),
1454 const struct filter *f, int fam)
aba5acdf 1455{
ab01dbbb 1456 char line[256];
aba5acdf 1457
ab01dbbb
SH
1458 /* skip header */
1459 if (fgets(line, sizeof(line), fp) == NULL)
aba5acdf 1460 goto outerr;
ab01dbbb
SH
1461
1462 while (fgets(line, sizeof(line), fp) != NULL) {
1463 int n = strlen(line);
1464 if (n == 0 || line[n-1] != '\n') {
1465 errno = -EINVAL;
1466 return -1;
aba5acdf 1467 }
ab01dbbb 1468 line[n-1] = 0;
aba5acdf 1469
ab01dbbb
SH
1470 if (worker(line, f, fam) < 0)
1471 return 0;
1472 }
aba5acdf 1473outerr:
ab01dbbb
SH
1474
1475 return ferror(fp) ? -1 : 0;
aba5acdf 1476}
ae665a52 1477
b4b0b7d5
SH
1478static char *sprint_bw(char *buf, double bw)
1479{
ae665a52 1480 if (bw > 1000000.)
b4b0b7d5
SH
1481 sprintf(buf,"%.1fM", bw / 1000000.);
1482 else if (bw > 1000.)
1483 sprintf(buf,"%.1fK", bw / 1000.);
1484 else
1485 sprintf(buf, "%g", bw);
1486
1487 return buf;
1488}
aba5acdf 1489
51ff9f24
HFS
1490static void print_skmeminfo(struct rtattr *tb[], int attrtype)
1491{
1492 const __u32 *skmeminfo;
1493 if (!tb[attrtype])
1494 return;
1495 skmeminfo = RTA_DATA(tb[attrtype]);
1496
1497 printf(" skmem:(r%u,rb%u,t%u,tb%u,f%u,w%u,o%u",
1498 skmeminfo[SK_MEMINFO_RMEM_ALLOC],
1499 skmeminfo[SK_MEMINFO_RCVBUF],
1500 skmeminfo[SK_MEMINFO_WMEM_ALLOC],
1501 skmeminfo[SK_MEMINFO_SNDBUF],
1502 skmeminfo[SK_MEMINFO_FWD_ALLOC],
1503 skmeminfo[SK_MEMINFO_WMEM_QUEUED],
1504 skmeminfo[SK_MEMINFO_OPTMEM]);
1505
1506 if (RTA_PAYLOAD(tb[attrtype]) >=
1507 (SK_MEMINFO_BACKLOG + 1) * sizeof(__u32))
1508 printf(",bl%u", skmeminfo[SK_MEMINFO_BACKLOG]);
1509
1510 printf(")");
1511}
1512
5b816047
PE
1513static void tcp_show_info(const struct nlmsghdr *nlh, struct inet_diag_msg *r,
1514 struct rtattr *tb[])
7d105b56 1515{
b4b0b7d5
SH
1516 char b1[64];
1517 double rtt = 0;
7d105b56 1518
910b0397 1519 if (tb[INET_DIAG_SKMEMINFO]) {
51ff9f24 1520 print_skmeminfo(tb, INET_DIAG_SKMEMINFO);
c6d6c92c 1521 } else if (tb[INET_DIAG_MEMINFO]) {
351efcde
SH
1522 const struct inet_diag_meminfo *minfo
1523 = RTA_DATA(tb[INET_DIAG_MEMINFO]);
7d105b56 1524 printf(" mem:(r%u,w%u,f%u,t%u)",
351efcde
SH
1525 minfo->idiag_rmem,
1526 minfo->idiag_wmem,
1527 minfo->idiag_fmem,
1528 minfo->idiag_tmem);
7d105b56
SH
1529 }
1530
351efcde 1531 if (tb[INET_DIAG_INFO]) {
05e18118 1532 struct tcp_info *info;
351efcde 1533 int len = RTA_PAYLOAD(tb[INET_DIAG_INFO]);
05e18118
SH
1534
1535 /* workaround for older kernels with less fields */
1536 if (len < sizeof(*info)) {
1537 info = alloca(sizeof(*info));
1538 memset(info, 0, sizeof(*info));
351efcde 1539 memcpy(info, RTA_DATA(tb[INET_DIAG_INFO]), len);
05e18118 1540 } else
351efcde 1541 info = RTA_DATA(tb[INET_DIAG_INFO]);
05e18118 1542
b4b0b7d5
SH
1543 if (show_options) {
1544 if (info->tcpi_options & TCPI_OPT_TIMESTAMPS)
1545 printf(" ts");
1546 if (info->tcpi_options & TCPI_OPT_SACK)
1547 printf(" sack");
1548 if (info->tcpi_options & TCPI_OPT_ECN)
1549 printf(" ecn");
719b958b
ED
1550 if (info->tcpi_options & TCPI_OPT_ECN_SEEN)
1551 printf(" ecnseen");
9cb1eccf
ED
1552 if (info->tcpi_options & TCPI_OPT_SYN_DATA)
1553 printf(" fastopen");
b4b0b7d5 1554 }
52d5ac3f 1555
351efcde 1556 if (tb[INET_DIAG_CONG])
ff24746c 1557 printf(" %s", rta_getattr_str(tb[INET_DIAG_CONG]));
ea8fc104 1558
ae665a52 1559 if (info->tcpi_options & TCPI_OPT_WSCALE)
05e18118
SH
1560 printf(" wscale:%d,%d", info->tcpi_snd_wscale,
1561 info->tcpi_rcv_wscale);
7d105b56
SH
1562 if (info->tcpi_rto && info->tcpi_rto != 3000000)
1563 printf(" rto:%g", (double)info->tcpi_rto/1000);
624a06e6
ED
1564 if (info->tcpi_backoff)
1565 printf(" backoff:%u", info->tcpi_backoff);
7d105b56
SH
1566 if (info->tcpi_rtt)
1567 printf(" rtt:%g/%g", (double)info->tcpi_rtt/1000,
1568 (double)info->tcpi_rttvar/1000);
1569 if (info->tcpi_ato)
1570 printf(" ato:%g", (double)info->tcpi_ato/1000);
4d354347
BH
1571 if (info->tcpi_snd_mss)
1572 printf(" mss:%d", info->tcpi_snd_mss);
7d105b56
SH
1573 if (info->tcpi_snd_cwnd != 2)
1574 printf(" cwnd:%d", info->tcpi_snd_cwnd);
1575 if (info->tcpi_snd_ssthresh < 0xFFFF)
1576 printf(" ssthresh:%d", info->tcpi_snd_ssthresh);
52d5ac3f 1577
b4b0b7d5 1578 rtt = (double) info->tcpi_rtt;
351efcde 1579 if (tb[INET_DIAG_VEGASINFO]) {
05e18118 1580 const struct tcpvegas_info *vinfo
351efcde 1581 = RTA_DATA(tb[INET_DIAG_VEGASINFO]);
7d105b56 1582
ae665a52 1583 if (vinfo->tcpv_enabled &&
ea8fc104
SH
1584 vinfo->tcpv_rtt && vinfo->tcpv_rtt != 0x7fffffff)
1585 rtt = vinfo->tcpv_rtt;
b4b0b7d5
SH
1586 }
1587
907e1aca
DB
1588 if (tb[INET_DIAG_DCTCPINFO]) {
1589 const struct tcp_dctcp_info *dinfo
1590 = RTA_DATA(tb[INET_DIAG_DCTCPINFO]);
1591
1592 if (dinfo->dctcp_enabled) {
1593 printf(" ce_state %u alpha %u ab_ecn %u ab_tot %u",
1594 dinfo->dctcp_ce_state, dinfo->dctcp_alpha,
1595 dinfo->dctcp_ab_ecn, dinfo->dctcp_ab_tot);
1596 } else {
1597 printf(" fallback_mode");
1598 }
1599 }
1600
b4b0b7d5
SH
1601 if (rtt > 0 && info->tcpi_snd_mss && info->tcpi_snd_cwnd) {
1602 printf(" send %sbps",
1603 sprint_bw(b1, (double) info->tcpi_snd_cwnd *
1604 (double) info->tcpi_snd_mss * 8000000.
1605 / rtt));
7d105b56 1606 }
b4b0b7d5 1607
624a06e6
ED
1608 if (info->tcpi_last_data_sent)
1609 printf(" lastsnd:%u", info->tcpi_last_data_sent);
1610
1611 if (info->tcpi_last_data_recv)
1612 printf(" lastrcv:%u", info->tcpi_last_data_recv);
1613
1614 if (info->tcpi_last_ack_recv)
1615 printf(" lastack:%u", info->tcpi_last_ack_recv);
1616
eb6028b2
ED
1617 if (info->tcpi_pacing_rate &&
1618 info->tcpi_pacing_rate != ~0ULL) {
1619 printf(" pacing_rate %sbps",
1620 sprint_bw(b1, info->tcpi_pacing_rate * 8.));
1621
1622 if (info->tcpi_max_pacing_rate &&
1623 info->tcpi_max_pacing_rate != ~0ULL)
1624 printf("/%sbps",
1625 sprint_bw(b1, info->tcpi_max_pacing_rate * 8.));
1626 }
260804f4
ED
1627 if (info->tcpi_unacked)
1628 printf(" unacked:%u", info->tcpi_unacked);
1629 if (info->tcpi_retrans || info->tcpi_total_retrans)
1630 printf(" retrans:%u/%u", info->tcpi_retrans,
1631 info->tcpi_total_retrans);
1632 if (info->tcpi_lost)
1633 printf(" lost:%u", info->tcpi_lost);
1634 if (info->tcpi_sacked && r->idiag_state != SS_LISTEN)
1635 printf(" sacked:%u", info->tcpi_sacked);
1636 if (info->tcpi_fackets)
1637 printf(" fackets:%u", info->tcpi_fackets);
1638 if (info->tcpi_reordering != 3)
1639 printf(" reordering:%d", info->tcpi_reordering);
b4b0b7d5
SH
1640 if (info->tcpi_rcv_rtt)
1641 printf(" rcv_rtt:%g", (double) info->tcpi_rcv_rtt/1000);
1642 if (info->tcpi_rcv_space)
1643 printf(" rcv_space:%d", info->tcpi_rcv_space);
1644
7d105b56 1645 }
7d105b56 1646}
aba5acdf 1647
77a8ca81
PE
1648static char *proto_name(int protocol)
1649{
1650 switch (protocol) {
1651 case IPPROTO_UDP:
1652 return "udp";
1653 case IPPROTO_TCP:
1654 return "tcp";
1655 case IPPROTO_DCCP:
1656 return "dccp";
1657 }
1658
1659 return "???";
1660}
1661
1662static int inet_show_sock(struct nlmsghdr *nlh, struct filter *f, int protocol)
aba5acdf 1663{
5b816047 1664 struct rtattr * tb[INET_DIAG_MAX+1];
351efcde 1665 struct inet_diag_msg *r = NLMSG_DATA(nlh);
aba5acdf
SH
1666 struct tcpstat s;
1667
5b816047
PE
1668 parse_rtattr(tb, INET_DIAG_MAX, (struct rtattr*)(r+1),
1669 nlh->nlmsg_len - NLMSG_LENGTH(sizeof(*r)));
1670
351efcde
SH
1671 s.state = r->idiag_state;
1672 s.local.family = s.remote.family = r->idiag_family;
1673 s.lport = ntohs(r->id.idiag_sport);
1674 s.rport = ntohs(r->id.idiag_dport);
aba5acdf
SH
1675 if (s.local.family == AF_INET) {
1676 s.local.bytelen = s.remote.bytelen = 4;
1677 } else {
1678 s.local.bytelen = s.remote.bytelen = 16;
1679 }
351efcde
SH
1680 memcpy(s.local.data, r->id.idiag_src, s.local.bytelen);
1681 memcpy(s.remote.data, r->id.idiag_dst, s.local.bytelen);
aba5acdf
SH
1682
1683 if (f && f->f && run_ssfilter(f->f, &s) == 0)
1684 return 0;
1685
1686 if (netid_width)
77a8ca81 1687 printf("%-*s ", netid_width, proto_name(protocol));
aba5acdf
SH
1688 if (state_width)
1689 printf("%-*s ", state_width, sstate_name[s.state]);
1690
351efcde 1691 printf("%-6d %-6d ", r->idiag_rqueue, r->idiag_wqueue);
aba5acdf 1692
7c8a3cfb
FLB
1693 formatted_print(&s.local, s.lport, r->id.idiag_if);
1694 formatted_print(&s.remote, s.rport, 0);
aba5acdf
SH
1695
1696 if (show_options) {
351efcde
SH
1697 if (r->idiag_timer) {
1698 if (r->idiag_timer > 4)
1699 r->idiag_timer = 5;
aba5acdf 1700 printf(" timer:(%s,%s,%d)",
351efcde
SH
1701 tmr_name[r->idiag_timer],
1702 print_ms_timer(r->idiag_expires),
1703 r->idiag_retrans);
aba5acdf
SH
1704 }
1705 }
116ac927
RH
1706 char *buf = NULL;
1707
1708 if (show_proc_ctx || show_sock_ctx) {
1709 if (find_entry(r->idiag_inode, &buf,
1710 (show_proc_ctx & show_sock_ctx) ?
1711 PROC_SOCK_CTX : PROC_CTX) > 0) {
1712 printf(" users:(%s)", buf);
1713 free(buf);
1714 }
1715 } else if (show_users) {
1716 if (find_entry(r->idiag_inode, &buf, USERS) > 0) {
1717 printf(" users:(%s)", buf);
1718 free(buf);
1719 }
aba5acdf 1720 }
116ac927 1721
aba5acdf 1722 if (show_details) {
351efcde
SH
1723 if (r->idiag_uid)
1724 printf(" uid:%u", (unsigned)r->idiag_uid);
e7113c61 1725 printf(" ino:%u", r->idiag_inode);
bbe32053 1726 printf(" sk:");
351efcde
SH
1727 if (r->id.idiag_cookie[1] != 0)
1728 printf("%08x", r->id.idiag_cookie[1]);
bbe32053 1729 printf("%08x", r->id.idiag_cookie[0]);
5b816047
PE
1730 if (tb[INET_DIAG_SHUTDOWN]) {
1731 unsigned char mask;
1732 mask = *(__u8 *)RTA_DATA(tb[INET_DIAG_SHUTDOWN]);
1733 printf(" %c-%c", mask & 1 ? '-' : '<', mask & 2 ? '-' : '>');
1734 }
aba5acdf
SH
1735 }
1736 if (show_mem || show_tcpinfo) {
7d105b56 1737 printf("\n\t");
5b816047 1738 tcp_show_info(nlh, r, tb);
aba5acdf 1739 }
7d105b56 1740
aba5acdf
SH
1741 printf("\n");
1742
1743 return 0;
aba5acdf
SH
1744}
1745
746a695f 1746static int tcpdiag_send(int fd, int protocol, struct filter *f)
aba5acdf 1747{
aba5acdf
SH
1748 struct sockaddr_nl nladdr;
1749 struct {
1750 struct nlmsghdr nlh;
351efcde 1751 struct inet_diag_req r;
aba5acdf
SH
1752 } req;
1753 char *bc = NULL;
1754 int bclen;
1755 struct msghdr msg;
1756 struct rtattr rta;
aba5acdf
SH
1757 struct iovec iov[3];
1758
346f8ca8
PE
1759 if (protocol == IPPROTO_UDP)
1760 return -1;
1761
aba5acdf
SH
1762 memset(&nladdr, 0, sizeof(nladdr));
1763 nladdr.nl_family = AF_NETLINK;
1764
1765 req.nlh.nlmsg_len = sizeof(req);
3fe5b534
PE
1766 if (protocol == IPPROTO_TCP)
1767 req.nlh.nlmsg_type = TCPDIAG_GETSOCK;
1768 else
1769 req.nlh.nlmsg_type = DCCPDIAG_GETSOCK;
aba5acdf
SH
1770 req.nlh.nlmsg_flags = NLM_F_ROOT|NLM_F_MATCH|NLM_F_REQUEST;
1771 req.nlh.nlmsg_pid = 0;
8a4025f6 1772 req.nlh.nlmsg_seq = MAGIC_SEQ;
aba5acdf 1773 memset(&req.r, 0, sizeof(req.r));
351efcde
SH
1774 req.r.idiag_family = AF_INET;
1775 req.r.idiag_states = f->states;
910b0397 1776 if (show_mem) {
ae665a52 1777 req.r.idiag_ext |= (1<<(INET_DIAG_MEMINFO-1));
910b0397
SW
1778 req.r.idiag_ext |= (1<<(INET_DIAG_SKMEMINFO-1));
1779 }
b4b0b7d5 1780
7d105b56 1781 if (show_tcpinfo) {
351efcde
SH
1782 req.r.idiag_ext |= (1<<(INET_DIAG_INFO-1));
1783 req.r.idiag_ext |= (1<<(INET_DIAG_VEGASINFO-1));
1784 req.r.idiag_ext |= (1<<(INET_DIAG_CONG-1));
7d105b56 1785 }
aba5acdf 1786
ae665a52
SH
1787 iov[0] = (struct iovec){
1788 .iov_base = &req,
1789 .iov_len = sizeof(req)
ea8fc104 1790 };
aba5acdf
SH
1791 if (f->f) {
1792 bclen = ssfilter_bytecompile(f->f, &bc);
351efcde 1793 rta.rta_type = INET_DIAG_REQ_BYTECODE;
aba5acdf
SH
1794 rta.rta_len = RTA_LENGTH(bclen);
1795 iov[1] = (struct iovec){ &rta, sizeof(rta) };
1796 iov[2] = (struct iovec){ bc, bclen };
1797 req.nlh.nlmsg_len += RTA_LENGTH(bclen);
1798 }
1799
1800 msg = (struct msghdr) {
ae665a52 1801 .msg_name = (void*)&nladdr,
ea8fc104 1802 .msg_namelen = sizeof(nladdr),
ae665a52 1803 .msg_iov = iov,
ea8fc104 1804 .msg_iovlen = f->f ? 3 : 1,
aba5acdf
SH
1805 };
1806
930a75f9
ED
1807 if (sendmsg(fd, &msg, 0) < 0) {
1808 close(fd);
aba5acdf 1809 return -1;
930a75f9 1810 }
aba5acdf 1811
746a695f
PE
1812 return 0;
1813}
1814
886d19d6
PE
1815static int sockdiag_send(int family, int fd, int protocol, struct filter *f)
1816{
1817 struct sockaddr_nl nladdr;
5fb421d4 1818 DIAG_REQUEST(req, struct inet_diag_req_v2 r);
886d19d6
PE
1819 char *bc = NULL;
1820 int bclen;
1821 struct msghdr msg;
1822 struct rtattr rta;
1823 struct iovec iov[3];
1824
1825 if (family == PF_UNSPEC)
1826 return tcpdiag_send(fd, protocol, f);
1827
1828 memset(&nladdr, 0, sizeof(nladdr));
1829 nladdr.nl_family = AF_NETLINK;
1830
886d19d6
PE
1831 memset(&req.r, 0, sizeof(req.r));
1832 req.r.sdiag_family = family;
1833 req.r.sdiag_protocol = protocol;
1834 req.r.idiag_states = f->states;
1835 if (show_mem) {
1836 req.r.idiag_ext |= (1<<(INET_DIAG_MEMINFO-1));
1837 req.r.idiag_ext |= (1<<(INET_DIAG_SKMEMINFO-1));
1838 }
1839
1840 if (show_tcpinfo) {
1841 req.r.idiag_ext |= (1<<(INET_DIAG_INFO-1));
1842 req.r.idiag_ext |= (1<<(INET_DIAG_VEGASINFO-1));
1843 req.r.idiag_ext |= (1<<(INET_DIAG_CONG-1));
1844 }
1845
1846 iov[0] = (struct iovec){
1847 .iov_base = &req,
1848 .iov_len = sizeof(req)
1849 };
1850 if (f->f) {
1851 bclen = ssfilter_bytecompile(f->f, &bc);
1852 rta.rta_type = INET_DIAG_REQ_BYTECODE;
1853 rta.rta_len = RTA_LENGTH(bclen);
1854 iov[1] = (struct iovec){ &rta, sizeof(rta) };
1855 iov[2] = (struct iovec){ bc, bclen };
1856 req.nlh.nlmsg_len += RTA_LENGTH(bclen);
1857 }
1858
1859 msg = (struct msghdr) {
1860 .msg_name = (void*)&nladdr,
1861 .msg_namelen = sizeof(nladdr),
1862 .msg_iov = iov,
1863 .msg_iovlen = f->f ? 3 : 1,
1864 };
1865
1866 if (sendmsg(fd, &msg, 0) < 0) {
1867 close(fd);
1868 return -1;
1869 }
1870
1871 return 0;
1872}
1873
746a695f
PE
1874static int inet_show_netlink(struct filter *f, FILE *dump_fp, int protocol)
1875{
886d19d6 1876 int fd, family;
746a695f
PE
1877 struct sockaddr_nl nladdr;
1878 struct msghdr msg;
e557212e 1879 char buf[16384];
746a695f
PE
1880 struct iovec iov[3];
1881
1882 if ((fd = socket(AF_NETLINK, SOCK_RAW, NETLINK_INET_DIAG)) < 0)
1883 return -1;
1884
886d19d6
PE
1885 family = PF_INET;
1886again:
1887 if (sockdiag_send(family, fd, protocol, f))
746a695f
PE
1888 return -1;
1889
1890 memset(&nladdr, 0, sizeof(nladdr));
1891 nladdr.nl_family = AF_NETLINK;
1892
ae665a52
SH
1893 iov[0] = (struct iovec){
1894 .iov_base = buf,
1895 .iov_len = sizeof(buf)
ea8fc104 1896 };
aba5acdf
SH
1897
1898 while (1) {
1899 int status;
1900 struct nlmsghdr *h;
1901
1902 msg = (struct msghdr) {
1903 (void*)&nladdr, sizeof(nladdr),
1904 iov, 1,
1905 NULL, 0,
1906 0
1907 };
1908
1909 status = recvmsg(fd, &msg, 0);
1910
1911 if (status < 0) {
1912 if (errno == EINTR)
1913 continue;
1914 perror("OVERRUN");
1915 continue;
1916 }
1917 if (status == 0) {
1918 fprintf(stderr, "EOF on netlink\n");
c51577cd 1919 close(fd);
aba5acdf
SH
1920 return 0;
1921 }
1922
1923 if (dump_fp)
1924 fwrite(buf, 1, NLMSG_ALIGN(status), dump_fp);
1925
1926 h = (struct nlmsghdr*)buf;
1927 while (NLMSG_OK(h, status)) {
1928 int err;
a37b01c1 1929 struct inet_diag_msg *r = NLMSG_DATA(h);
aba5acdf
SH
1930
1931 if (/*h->nlmsg_pid != rth->local.nl_pid ||*/
8a4025f6 1932 h->nlmsg_seq != MAGIC_SEQ)
aba5acdf
SH
1933 goto skip_it;
1934
886d19d6
PE
1935 if (h->nlmsg_type == NLMSG_DONE)
1936 goto done;
1937
aba5acdf
SH
1938 if (h->nlmsg_type == NLMSG_ERROR) {
1939 struct nlmsgerr *err = (struct nlmsgerr*)NLMSG_DATA(h);
1940 if (h->nlmsg_len < NLMSG_LENGTH(sizeof(struct nlmsgerr))) {
1941 fprintf(stderr, "ERROR truncated\n");
1942 } else {
886d19d6
PE
1943 if (family != PF_UNSPEC) {
1944 family = PF_UNSPEC;
1945 goto again;
1946 }
1947
aba5acdf 1948 errno = -err->error;
930a75f9
ED
1949 if (errno == EOPNOTSUPP) {
1950 close(fd);
1951 return -1;
1952 }
aba5acdf
SH
1953 perror("TCPDIAG answers");
1954 }
886d19d6
PE
1955
1956 goto done;
aba5acdf
SH
1957 }
1958 if (!dump_fp) {
a37b01c1
LY
1959 if (!(f->families & (1<<r->idiag_family))) {
1960 h = NLMSG_NEXT(h, status);
1961 continue;
1962 }
77a8ca81 1963 err = inet_show_sock(h, NULL, protocol);
c51577cd
MT
1964 if (err < 0) {
1965 close(fd);
aba5acdf 1966 return err;
c51577cd 1967 }
aba5acdf
SH
1968 }
1969
1970skip_it:
1971 h = NLMSG_NEXT(h, status);
1972 }
1973 if (msg.msg_flags & MSG_TRUNC) {
1974 fprintf(stderr, "Message truncated\n");
1975 continue;
1976 }
1977 if (status) {
1978 fprintf(stderr, "!!!Remnant of size %d\n", status);
1979 exit(1);
1980 }
1981 }
886d19d6
PE
1982done:
1983 if (family == PF_INET) {
1984 family = PF_INET6;
1985 goto again;
1986 }
1987
c51577cd 1988 close(fd);
aba5acdf
SH
1989 return 0;
1990}
1991
ab01dbbb 1992static int tcp_show_netlink_file(struct filter *f)
aba5acdf
SH
1993{
1994 FILE *fp;
e557212e 1995 char buf[16384];
aba5acdf
SH
1996
1997 if ((fp = fopen(getenv("TCPDIAG_FILE"), "r")) == NULL) {
1998 perror("fopen($TCPDIAG_FILE)");
1999 return -1;
2000 }
2001
2002 while (1) {
2003 int status, err;
2004 struct nlmsghdr *h = (struct nlmsghdr*)buf;
2005
2006 status = fread(buf, 1, sizeof(*h), fp);
2007 if (status < 0) {
2008 perror("Reading header from $TCPDIAG_FILE");
2009 return -1;
2010 }
2011 if (status != sizeof(*h)) {
2012 perror("Unexpected EOF reading $TCPDIAG_FILE");
2013 return -1;
2014 }
2015
2016 status = fread(h+1, 1, NLMSG_ALIGN(h->nlmsg_len-sizeof(*h)), fp);
2017
2018 if (status < 0) {
2019 perror("Reading $TCPDIAG_FILE");
2020 return -1;
2021 }
2022 if (status + sizeof(*h) < h->nlmsg_len) {
2023 perror("Unexpected EOF reading $TCPDIAG_FILE");
2024 return -1;
2025 }
2026
2027 /* The only legal exit point */
2028 if (h->nlmsg_type == NLMSG_DONE)
2029 return 0;
2030
2031 if (h->nlmsg_type == NLMSG_ERROR) {
2032 struct nlmsgerr *err = (struct nlmsgerr*)NLMSG_DATA(h);
2033 if (h->nlmsg_len < NLMSG_LENGTH(sizeof(struct nlmsgerr))) {
2034 fprintf(stderr, "ERROR truncated\n");
2035 } else {
2036 errno = -err->error;
2037 perror("TCPDIAG answered");
2038 }
2039 return -1;
2040 }
2041
77a8ca81 2042 err = inet_show_sock(h, f, IPPROTO_TCP);
aba5acdf
SH
2043 if (err < 0)
2044 return err;
2045 }
2046}
2047
ab01dbbb 2048static int tcp_show(struct filter *f, int socktype)
aba5acdf 2049{
ab01dbbb 2050 FILE *fp = NULL;
aba5acdf
SH
2051 char *buf = NULL;
2052 int bufsize = 64*1024;
2053
2054 dg_proto = TCP_PROTO;
2055
2056 if (getenv("TCPDIAG_FILE"))
2057 return tcp_show_netlink_file(f);
2058
2059 if (!getenv("PROC_NET_TCP") && !getenv("PROC_ROOT")
3fe5b534 2060 && inet_show_netlink(f, NULL, socktype) == 0)
aba5acdf
SH
2061 return 0;
2062
2063 /* Sigh... We have to parse /proc/net/tcp... */
2064
ab01dbbb 2065
aba5acdf
SH
2066 /* Estimate amount of sockets and try to allocate
2067 * huge buffer to read all the table at one read.
2068 * Limit it by 16MB though. The assumption is: as soon as
2069 * kernel was able to hold information about N connections,
2070 * it is able to give us some memory for snapshot.
2071 */
2072 if (1) {
2073 int guess = slabstat.socks+slabstat.tcp_syns;
2074 if (f->states&(1<<SS_TIME_WAIT))
2075 guess += slabstat.tcp_tws;
2076 if (guess > (16*1024*1024)/128)
2077 guess = (16*1024*1024)/128;
2078 guess *= 128;
2079 if (guess > bufsize)
2080 bufsize = guess;
2081 }
2082 while (bufsize >= 64*1024) {
2083 if ((buf = malloc(bufsize)) != NULL)
2084 break;
2085 bufsize /= 2;
2086 }
2087 if (buf == NULL) {
2088 errno = ENOMEM;
2089 return -1;
2090 }
2091
2092 if (f->families & (1<<AF_INET)) {
69cae645 2093 if ((fp = net_tcp_open()) == NULL)
aba5acdf 2094 goto outerr;
ab01dbbb
SH
2095
2096 setbuffer(fp, buf, bufsize);
2097 if (generic_record_read(fp, tcp_show_line, f, AF_INET))
aba5acdf 2098 goto outerr;
ab01dbbb 2099 fclose(fp);
aba5acdf
SH
2100 }
2101
2102 if ((f->families & (1<<AF_INET6)) &&
69cae645 2103 (fp = net_tcp6_open()) != NULL) {
ab01dbbb
SH
2104 setbuffer(fp, buf, bufsize);
2105 if (generic_record_read(fp, tcp_show_line, f, AF_INET6))
aba5acdf 2106 goto outerr;
ab01dbbb 2107 fclose(fp);
aba5acdf
SH
2108 }
2109
2110 free(buf);
2111 return 0;
2112
2113outerr:
2114 do {
2115 int saved_errno = errno;
2116 if (buf)
2117 free(buf);
ab01dbbb
SH
2118 if (fp)
2119 fclose(fp);
aba5acdf
SH
2120 errno = saved_errno;
2121 return -1;
2122 } while (0);
2123}
2124
2125
d1f28cf1 2126static int dgram_show_line(char *line, const struct filter *f, int family)
aba5acdf
SH
2127{
2128 struct tcpstat s;
2129 char *loc, *rem, *data;
2130 char opt[256];
2131 int n;
2132 char *p;
2133
2134 if ((p = strchr(line, ':')) == NULL)
2135 return -1;
2136 loc = p+2;
2137
2138 if ((p = strchr(loc, ':')) == NULL)
2139 return -1;
2140 p[5] = 0;
2141 rem = p+6;
2142
2143 if ((p = strchr(rem, ':')) == NULL)
2144 return -1;
2145 p[5] = 0;
2146 data = p+6;
2147
2148 do {
2149 int state = (data[1] >= 'A') ? (data[1] - 'A' + 10) : (data[1] - '0');
2150
2151 if (!(f->states & (1<<state)))
2152 return 0;
2153 } while (0);
2154
2155 s.local.family = s.remote.family = family;
2156 if (family == AF_INET) {
2157 sscanf(loc, "%x:%x", s.local.data, (unsigned*)&s.lport);
2158 sscanf(rem, "%x:%x", s.remote.data, (unsigned*)&s.rport);
2159 s.local.bytelen = s.remote.bytelen = 4;
2160 } else {
2161 sscanf(loc, "%08x%08x%08x%08x:%x",
2162 s.local.data,
2163 s.local.data+1,
2164 s.local.data+2,
2165 s.local.data+3,
2166 &s.lport);
2167 sscanf(rem, "%08x%08x%08x%08x:%x",
2168 s.remote.data,
2169 s.remote.data+1,
2170 s.remote.data+2,
2171 s.remote.data+3,
2172 &s.rport);
2173 s.local.bytelen = s.remote.bytelen = 16;
2174 }
2175
2176 if (f->f && run_ssfilter(f->f, &s) == 0)
2177 return 0;
2178
2179 opt[0] = 0;
e7113c61 2180 n = sscanf(data, "%x %x:%x %*x:%*x %*x %d %*d %u %d %llx %[^\n]\n",
aba5acdf
SH
2181 &s.state, &s.wq, &s.rq,
2182 &s.uid, &s.ino,
2183 &s.refcnt, &s.sk, opt);
2184
2185 if (n < 9)
2186 opt[0] = 0;
2187
2188 if (netid_width)
2189 printf("%-*s ", netid_width, dg_proto);
2190 if (state_width)
2191 printf("%-*s ", state_width, sstate_name[s.state]);
2192
2193 printf("%-6d %-6d ", s.rq, s.wq);
2194
7c8a3cfb
FLB
2195 formatted_print(&s.local, s.lport, 0);
2196 formatted_print(&s.remote, s.rport, 0);
aba5acdf 2197
116ac927
RH
2198 char *buf = NULL;
2199
2200 if (show_proc_ctx || show_sock_ctx) {
2201 if (find_entry(s.ino, &buf,
2202 (show_proc_ctx & show_sock_ctx) ?
2203 PROC_SOCK_CTX : PROC_CTX) > 0) {
2204 printf(" users:(%s)", buf);
2205 free(buf);
2206 }
2207 } else if (show_users) {
2208 if (find_entry(s.ino, &buf, USERS) > 0) {
2209 printf(" users:(%s)", buf);
2210 free(buf);
2211 }
aba5acdf
SH
2212 }
2213
2214 if (show_details) {
2215 if (s.uid)
2216 printf(" uid=%u", (unsigned)s.uid);
e7113c61 2217 printf(" ino=%u", s.ino);
aba5acdf
SH
2218 printf(" sk=%llx", s.sk);
2219 if (opt[0])
2220 printf(" opt:\"%s\"", opt);
2221 }
2222 printf("\n");
2223
2224 return 0;
2225}
2226
2227
d1f28cf1 2228static int udp_show(struct filter *f)
aba5acdf 2229{
ab01dbbb 2230 FILE *fp = NULL;
aba5acdf 2231
346f8ca8
PE
2232 if (!getenv("PROC_NET_UDP") && !getenv("PROC_ROOT")
2233 && inet_show_netlink(f, NULL, IPPROTO_UDP) == 0)
2234 return 0;
2235
aba5acdf
SH
2236 dg_proto = UDP_PROTO;
2237
2238 if (f->families&(1<<AF_INET)) {
69cae645 2239 if ((fp = net_udp_open()) == NULL)
aba5acdf 2240 goto outerr;
ab01dbbb 2241 if (generic_record_read(fp, dgram_show_line, f, AF_INET))
aba5acdf 2242 goto outerr;
ab01dbbb 2243 fclose(fp);
aba5acdf
SH
2244 }
2245
2246 if ((f->families&(1<<AF_INET6)) &&
69cae645 2247 (fp = net_udp6_open()) != NULL) {
ab01dbbb 2248 if (generic_record_read(fp, dgram_show_line, f, AF_INET6))
aba5acdf 2249 goto outerr;
ab01dbbb 2250 fclose(fp);
aba5acdf
SH
2251 }
2252 return 0;
2253
2254outerr:
2255 do {
2256 int saved_errno = errno;
ab01dbbb
SH
2257 if (fp)
2258 fclose(fp);
aba5acdf
SH
2259 errno = saved_errno;
2260 return -1;
2261 } while (0);
2262}
2263
d1f28cf1 2264static int raw_show(struct filter *f)
aba5acdf 2265{
ab01dbbb 2266 FILE *fp = NULL;
aba5acdf
SH
2267
2268 dg_proto = RAW_PROTO;
2269
2270 if (f->families&(1<<AF_INET)) {
69cae645 2271 if ((fp = net_raw_open()) == NULL)
aba5acdf 2272 goto outerr;
ab01dbbb 2273 if (generic_record_read(fp, dgram_show_line, f, AF_INET))
aba5acdf 2274 goto outerr;
ab01dbbb 2275 fclose(fp);
aba5acdf
SH
2276 }
2277
2278 if ((f->families&(1<<AF_INET6)) &&
69cae645 2279 (fp = net_raw6_open()) != NULL) {
ab01dbbb 2280 if (generic_record_read(fp, dgram_show_line, f, AF_INET6))
aba5acdf 2281 goto outerr;
ab01dbbb 2282 fclose(fp);
aba5acdf
SH
2283 }
2284 return 0;
2285
2286outerr:
2287 do {
2288 int saved_errno = errno;
ab01dbbb
SH
2289 if (fp)
2290 fclose(fp);
aba5acdf
SH
2291 errno = saved_errno;
2292 return -1;
2293 } while (0);
2294}
2295
2296
2297struct unixstat
2298{
2299 struct unixstat *next;
2300 int ino;
2301 int peer;
2302 int rq;
2303 int wq;
2304 int state;
2305 int type;
2306 char *name;
2307};
2308
2309
2310
2311int unix_state_map[] = { SS_CLOSE, SS_SYN_SENT,
2312 SS_ESTABLISHED, SS_CLOSING };
2313
2314
2315#define MAX_UNIX_REMEMBER (1024*1024/sizeof(struct unixstat))
2316
d1f28cf1 2317static void unix_list_free(struct unixstat *list)
aba5acdf
SH
2318{
2319 while (list) {
2320 struct unixstat *s = list;
2321 list = list->next;
2322 if (s->name)
2323 free(s->name);
2324 free(s);
2325 }
2326}
2327
30b669d7
MY
2328static const char *unix_netid_name(int type)
2329{
2330 const char *netid;
2331
2332 switch (type) {
2333 case SOCK_STREAM:
2334 netid = "u_str";
2335 break;
2336 case SOCK_SEQPACKET:
2337 netid = "u_seq";
2338 break;
2339 case SOCK_DGRAM:
2340 default:
2341 netid = "u_dgr";
2342 break;
2343 }
2344 return netid;
2345}
2346
d1f28cf1 2347static void unix_list_print(struct unixstat *list, struct filter *f)
aba5acdf
SH
2348{
2349 struct unixstat *s;
2350 char *peer;
2351
2352 for (s = list; s; s = s->next) {
2353 if (!(f->states & (1<<s->state)))
2354 continue;
2355 if (s->type == SOCK_STREAM && !(f->dbs&(1<<UNIX_ST_DB)))
2356 continue;
2357 if (s->type == SOCK_DGRAM && !(f->dbs&(1<<UNIX_DG_DB)))
2358 continue;
30b669d7
MY
2359 if (s->type == SOCK_SEQPACKET && !(f->dbs&(1<<UNIX_SQ_DB)))
2360 continue;
aba5acdf
SH
2361
2362 peer = "*";
2363 if (s->peer) {
2364 struct unixstat *p;
2365 for (p = list; p; p = p->next) {
2366 if (s->peer == p->ino)
2367 break;
2368 }
2369 if (!p) {
2370 peer = "?";
2371 } else {
2372 peer = p->name ? : "*";
2373 }
2374 }
2375
2376 if (f->f) {
2377 struct tcpstat tst;
2378 tst.local.family = AF_UNIX;
2379 tst.remote.family = AF_UNIX;
2380 memcpy(tst.local.data, &s->name, sizeof(s->name));
2381 if (strcmp(peer, "*") == 0)
2382 memset(tst.remote.data, 0, sizeof(peer));
2383 else
ae665a52 2384 memcpy(tst.remote.data, &peer, sizeof(peer));
aba5acdf
SH
2385 if (run_ssfilter(f->f, &tst) == 0)
2386 continue;
2387 }
2388
2389 if (netid_width)
ae665a52 2390 printf("%-*s ", netid_width,
30b669d7 2391 unix_netid_name(s->type));
aba5acdf
SH
2392 if (state_width)
2393 printf("%-*s ", state_width, sstate_name[s->state]);
2394 printf("%-6d %-6d ", s->rq, s->wq);
2395 printf("%*s %-*d %*s %-*d",
2396 addr_width, s->name ? : "*", serv_width, s->ino,
2397 addr_width, peer, serv_width, s->peer);
116ac927
RH
2398 char *buf = NULL;
2399
2400 if (show_proc_ctx || show_sock_ctx) {
2401 if (find_entry(s->ino, &buf,
2402 (show_proc_ctx & show_sock_ctx) ?
2403 PROC_SOCK_CTX : PROC_CTX) > 0) {
2404 printf(" users:(%s)", buf);
2405 free(buf);
2406 }
2407 } else if (show_users) {
2408 if (find_entry(s->ino, &buf, USERS) > 0) {
2409 printf(" users:(%s)", buf);
2410 free(buf);
2411 }
aba5acdf
SH
2412 }
2413 printf("\n");
2414 }
2415}
2416
8a4025f6 2417static int unix_show_sock(const struct sockaddr_nl *addr, struct nlmsghdr *nlh,
2418 void *arg)
dfbaa90d 2419{
8a4025f6 2420 struct filter *f = (struct filter *)arg;
dfbaa90d
PE
2421 struct unix_diag_msg *r = NLMSG_DATA(nlh);
2422 struct rtattr *tb[UNIX_DIAG_MAX+1];
2423 char name[128];
2424 int peer_ino;
defd61ca 2425 __u32 rqlen, wqlen;
dfbaa90d
PE
2426
2427 parse_rtattr(tb, UNIX_DIAG_MAX, (struct rtattr*)(r+1),
2428 nlh->nlmsg_len - NLMSG_LENGTH(sizeof(*r)));
2429
0d2e01c5
MY
2430 if (r->udiag_type == SOCK_STREAM && !(f->dbs&(1<<UNIX_ST_DB)))
2431 return 0;
2432 if (r->udiag_type == SOCK_DGRAM && !(f->dbs&(1<<UNIX_DG_DB)))
2433 return 0;
2434 if (r->udiag_type == SOCK_SEQPACKET && !(f->dbs&(1<<UNIX_SQ_DB)))
2435 return 0;
2436
dfbaa90d
PE
2437 if (netid_width)
2438 printf("%-*s ", netid_width,
30b669d7 2439 unix_netid_name(r->udiag_type));
dfbaa90d
PE
2440 if (state_width)
2441 printf("%-*s ", state_width, sstate_name[r->udiag_state]);
2442
defd61ca
HFS
2443 if (tb[UNIX_DIAG_RQLEN]) {
2444 struct unix_diag_rqlen *rql = RTA_DATA(tb[UNIX_DIAG_RQLEN]);
2445 rqlen = rql->udiag_rqueue;
2446 wqlen = rql->udiag_wqueue;
2447 } else {
dfbaa90d 2448 rqlen = 0;
defd61ca
HFS
2449 wqlen = 0;
2450 }
dfbaa90d 2451
defd61ca 2452 printf("%-6u %-6u ", rqlen, wqlen);
dfbaa90d
PE
2453
2454 if (tb[UNIX_DIAG_NAME]) {
2455 int len = RTA_PAYLOAD(tb[UNIX_DIAG_NAME]);
2456
2457 memcpy(name, RTA_DATA(tb[UNIX_DIAG_NAME]), len);
2458 name[len] = '\0';
2459 if (name[0] == '\0')
2460 name[0] = '@';
2461 } else
2462 sprintf(name, "*");
2463
2464 if (tb[UNIX_DIAG_PEER])
5048f9a0 2465 peer_ino = rta_getattr_u32(tb[UNIX_DIAG_PEER]);
dfbaa90d
PE
2466 else
2467 peer_ino = 0;
2468
2469 printf("%*s %-*d %*s %-*d",
2470 addr_width, name,
2471 serv_width, r->udiag_ino,
2472 addr_width, "*", /* FIXME */
2473 serv_width, peer_ino);
2474
116ac927
RH
2475 char *buf = NULL;
2476
2477 if (show_proc_ctx || show_sock_ctx) {
2478 if (find_entry(r->udiag_ino, &buf,
2479 (show_proc_ctx & show_sock_ctx) ?
2480 PROC_SOCK_CTX : PROC_CTX) > 0) {
2481 printf(" users:(%s)", buf);
2482 free(buf);
2483 }
2484 } else if (show_users) {
2485 if (find_entry(r->udiag_ino, &buf, USERS) > 0) {
2486 printf(" users:(%s)", buf);
2487 free(buf);
2488 }
dfbaa90d
PE
2489 }
2490
51ff9f24
HFS
2491 if (show_mem) {
2492 printf("\n\t");
2493 print_skmeminfo(tb, UNIX_DIAG_MEMINFO);
2494 }
2495
5b816047
PE
2496 if (show_details) {
2497 if (tb[UNIX_DIAG_SHUTDOWN]) {
2498 unsigned char mask;
2499 mask = *(__u8 *)RTA_DATA(tb[UNIX_DIAG_SHUTDOWN]);
2500 printf(" %c-%c", mask & 1 ? '-' : '<', mask & 2 ? '-' : '>');
2501 }
2502 }
2503
dfbaa90d
PE
2504 printf("\n");
2505
2506 return 0;
2507}
2508
8a4025f6 2509static int handle_netlink_request(struct filter *f, struct nlmsghdr *req,
2510 size_t size, rtnl_filter_t show_one_sock)
dfbaa90d 2511{
8a4025f6 2512 int ret = -1;
2513 struct rtnl_handle rth;
dfbaa90d 2514
8a4025f6 2515 if (rtnl_open_byproto(&rth, 0, NETLINK_SOCK_DIAG))
dfbaa90d
PE
2516 return -1;
2517
8a4025f6 2518 rth.dump = MAGIC_SEQ;
dfbaa90d 2519
8a4025f6 2520 if (rtnl_send(&rth, req, size) < 0)
2521 goto Exit;
dfbaa90d 2522
8a4025f6 2523 if (rtnl_dump_filter(&rth, show_one_sock, f))
2524 goto Exit;
dfbaa90d 2525
8a4025f6 2526 ret = 0;
2527Exit:
2528 rtnl_close(&rth);
2529 return ret;
dfbaa90d
PE
2530}
2531
8a4025f6 2532static int unix_show_netlink(struct filter *f)
d8402b96 2533{
5fb421d4 2534 DIAG_REQUEST(req, struct unix_diag_req r);
d8402b96
AV
2535
2536 req.r.sdiag_family = AF_UNIX;
2537 req.r.udiag_states = f->states;
2538 req.r.udiag_show = UDIAG_SHOW_NAME | UDIAG_SHOW_PEER | UDIAG_SHOW_RQLEN;
2539 if (show_mem)
2540 req.r.udiag_show |= UDIAG_SHOW_MEMINFO;
2541
8a4025f6 2542 return handle_netlink_request(f, &req.nlh, sizeof(req), unix_show_sock);
d8402b96
AV
2543}
2544
d1f28cf1 2545static int unix_show(struct filter *f)
aba5acdf
SH
2546{
2547 FILE *fp;
2548 char buf[256];
2549 char name[128];
2550 int newformat = 0;
2551 int cnt;
2552 struct unixstat *list = NULL;
2553
dfbaa90d 2554 if (!getenv("PROC_NET_UNIX") && !getenv("PROC_ROOT")
8a4025f6 2555 && unix_show_netlink(f) == 0)
dfbaa90d
PE
2556 return 0;
2557
ab01dbbb 2558 if ((fp = net_unix_open()) == NULL)
aba5acdf
SH
2559 return -1;
2560 fgets(buf, sizeof(buf)-1, fp);
2561
ae665a52 2562 if (memcmp(buf, "Peer", 4) == 0)
aba5acdf
SH
2563 newformat = 1;
2564 cnt = 0;
2565
2566 while (fgets(buf, sizeof(buf)-1, fp)) {
2567 struct unixstat *u, **insp;
2568 int flags;
2569
2570 if (!(u = malloc(sizeof(*u))))
2571 break;
2572 u->name = NULL;
2573
2574 if (sscanf(buf, "%x: %x %x %x %x %x %d %s",
2575 &u->peer, &u->rq, &u->wq, &flags, &u->type,
2576 &u->state, &u->ino, name) < 8)
2577 name[0] = 0;
2578
2579 if (flags&(1<<16)) {
2580 u->state = SS_LISTEN;
2581 } else {
2582 u->state = unix_state_map[u->state-1];
2583 if (u->type == SOCK_DGRAM &&
2584 u->state == SS_CLOSE &&
2585 u->peer)
2586 u->state = SS_ESTABLISHED;
2587 }
2588
2589 if (!newformat) {
2590 u->peer = 0;
2591 u->rq = 0;
2592 u->wq = 0;
2593 }
2594
2595 insp = &list;
2596 while (*insp) {
2597 if (u->type < (*insp)->type ||
2598 (u->type == (*insp)->type &&
2599 u->ino < (*insp)->ino))
2600 break;
2601 insp = &(*insp)->next;
2602 }
2603 u->next = *insp;
2604 *insp = u;
2605
2606 if (name[0]) {
2607 if ((u->name = malloc(strlen(name)+1)) == NULL)
2608 break;
2609 strcpy(u->name, name);
2610 }
2611 if (++cnt > MAX_UNIX_REMEMBER) {
2612 unix_list_print(list, f);
2613 unix_list_free(list);
2614 list = NULL;
2615 cnt = 0;
2616 }
2617 }
a3fd8e58 2618 fclose(fp);
aba5acdf
SH
2619 if (list) {
2620 unix_list_print(list, f);
2621 unix_list_free(list);
2622 list = NULL;
2623 cnt = 0;
2624 }
2625
2626 return 0;
2627}
2628
8a4025f6 2629static int packet_show_sock(const struct sockaddr_nl *addr,
2630 struct nlmsghdr *nlh, void *arg)
372c30d2
ND
2631{
2632 struct packet_diag_msg *r = NLMSG_DATA(nlh);
2633 struct rtattr *tb[PACKET_DIAG_MAX+1];
2634 __u32 rq;
2635
2636 parse_rtattr(tb, PACKET_DIAG_MAX, (struct rtattr*)(r+1),
2637 nlh->nlmsg_len - NLMSG_LENGTH(sizeof(*r)));
2638
2639 /* use /proc/net/packet if all info are not available */
2640 if (!tb[PACKET_DIAG_MEMINFO])
2641 return -1;
2642
2643 if (netid_width)
2644 printf("%-*s ", netid_width,
2645 r->pdiag_type == SOCK_RAW ? "p_raw" : "p_dgr");
2646 if (state_width)
2647 printf("%-*s ", state_width, "UNCONN");
2648
2649 if (tb[PACKET_DIAG_MEMINFO]) {
2650 __u32 *skmeminfo = RTA_DATA(tb[PACKET_DIAG_MEMINFO]);
2651
2652 rq = skmeminfo[SK_MEMINFO_RMEM_ALLOC];
2653 } else
2654 rq = 0;
2655 printf("%-6d %-6d ", rq, 0);
2656
2657 if (r->pdiag_num == 3) {
2658 printf("%*s:", addr_width, "*");
2659 } else {
2660 char tb2[16];
2661 printf("%*s:", addr_width,
2662 ll_proto_n2a(htons(r->pdiag_num), tb2, sizeof(tb2)));
2663 }
2664 if (tb[PACKET_DIAG_INFO]) {
2665 struct packet_diag_info *pinfo = RTA_DATA(tb[PACKET_DIAG_INFO]);
2666
2667 if (pinfo->pdi_index == 0)
2668 printf("%-*s ", serv_width, "*");
2669 else
2670 printf("%-*s ", serv_width, xll_index_to_name(pinfo->pdi_index));
2671 } else
2672 printf("%-*s ", serv_width, "*");
2673
2674 printf("%*s*%-*s",
2675 addr_width, "", serv_width, "");
2676
116ac927
RH
2677 char *buf = NULL;
2678
2679 if (show_proc_ctx || show_sock_ctx) {
2680 if (find_entry(r->pdiag_ino, &buf,
2681 (show_proc_ctx & show_sock_ctx) ?
2682 PROC_SOCK_CTX : PROC_CTX) > 0) {
2683 printf(" users:(%s)", buf);
2684 free(buf);
2685 }
2686 } else if (show_users) {
2687 if (find_entry(r->pdiag_ino, &buf, USERS) > 0) {
2688 printf(" users:(%s)", buf);
2689 free(buf);
2690 }
372c30d2 2691 }
116ac927 2692
372c30d2
ND
2693 if (show_details) {
2694 __u32 uid = 0;
2695
2696 if (tb[PACKET_DIAG_UID])
2697 uid = *(__u32 *)RTA_DATA(tb[PACKET_DIAG_UID]);
2698
2699 printf(" ino=%u uid=%u sk=", r->pdiag_ino, uid);
2700 if (r->pdiag_cookie[1] != 0)
2701 printf("%08x", r->pdiag_cookie[1]);
2702 printf("%08x", r->pdiag_cookie[0]);
2703 }
2704
2705 if (show_bpf && tb[PACKET_DIAG_FILTER]) {
2706 struct sock_filter *fil =
2707 RTA_DATA(tb[PACKET_DIAG_FILTER]);
2708 int num = RTA_PAYLOAD(tb[PACKET_DIAG_FILTER]) /
2709 sizeof(struct sock_filter);
2710
2711 printf("\n\tbpf filter (%d): ", num);
2712 while (num) {
2713 printf(" 0x%02x %u %u %u,",
2714 fil->code, fil->jt, fil->jf, fil->k);
2715 num--;
2716 fil++;
2717 }
2718 }
2719 printf("\n");
2720 return 0;
2721}
2722
8a4025f6 2723static int packet_show_netlink(struct filter *f)
372c30d2 2724{
5fb421d4 2725 DIAG_REQUEST(req, struct packet_diag_req r);
372c30d2 2726
372c30d2
ND
2727 req.r.sdiag_family = AF_PACKET;
2728 req.r.pdiag_show = PACKET_SHOW_INFO | PACKET_SHOW_MEMINFO | PACKET_SHOW_FILTER;
2729
8a4025f6 2730 return handle_netlink_request(f, &req.nlh, sizeof(req), packet_show_sock);
372c30d2
ND
2731}
2732
aba5acdf 2733
d1f28cf1 2734static int packet_show(struct filter *f)
aba5acdf
SH
2735{
2736 FILE *fp;
2737 char buf[256];
2738 int type;
2739 int prot;
2740 int iface;
2741 int state;
2742 int rq;
2743 int uid;
2744 int ino;
2745 unsigned long long sk;
b9ea445d
VK
2746
2747 if (preferred_family != AF_PACKET && !(f->states & (1 << SS_CLOSE)))
2748 return 0;
aba5acdf 2749
8a4025f6 2750 if (packet_show_netlink(f) == 0)
372c30d2
ND
2751 return 0;
2752
ab01dbbb 2753 if ((fp = net_packet_open()) == NULL)
aba5acdf
SH
2754 return -1;
2755 fgets(buf, sizeof(buf)-1, fp);
2756
2757 while (fgets(buf, sizeof(buf)-1, fp)) {
2758 sscanf(buf, "%llx %*d %d %x %d %d %u %u %u",
2759 &sk,
2760 &type, &prot, &iface, &state,
2761 &rq, &uid, &ino);
2762
2763 if (type == SOCK_RAW && !(f->dbs&(1<<PACKET_R_DB)))
2764 continue;
2765 if (type == SOCK_DGRAM && !(f->dbs&(1<<PACKET_DG_DB)))
2766 continue;
2767 if (f->f) {
2768 struct tcpstat tst;
2769 tst.local.family = AF_PACKET;
2770 tst.remote.family = AF_PACKET;
2771 tst.rport = 0;
2772 tst.lport = iface;
2773 tst.local.data[0] = prot;
2774 tst.remote.data[0] = 0;
2775 if (run_ssfilter(f->f, &tst) == 0)
2776 continue;
2777 }
2778
2779 if (netid_width)
ae665a52 2780 printf("%-*s ", netid_width,
aba5acdf
SH
2781 type == SOCK_RAW ? "p_raw" : "p_dgr");
2782 if (state_width)
2783 printf("%-*s ", state_width, "UNCONN");
2784 printf("%-6d %-6d ", rq, 0);
2785 if (prot == 3) {
2786 printf("%*s:", addr_width, "*");
2787 } else {
2788 char tb[16];
ae665a52 2789 printf("%*s:", addr_width,
aba5acdf
SH
2790 ll_proto_n2a(htons(prot), tb, sizeof(tb)));
2791 }
2792 if (iface == 0) {
2793 printf("%-*s ", serv_width, "*");
2794 } else {
2795 printf("%-*s ", serv_width, xll_index_to_name(iface));
2796 }
2797 printf("%*s*%-*s",
2798 addr_width, "", serv_width, "");
2799
116ac927
RH
2800 char *buf = NULL;
2801
2802 if (show_proc_ctx || show_sock_ctx) {
2803 if (find_entry(ino, &buf,
2804 (show_proc_ctx & show_sock_ctx) ?
2805 PROC_SOCK_CTX : PROC_CTX) > 0) {
2806 printf(" users:(%s)", buf);
2807 free(buf);
2808 }
2809 } else if (show_users) {
2810 if (find_entry(ino, &buf, USERS) > 0) {
2811 printf(" users:(%s)", buf);
2812 free(buf);
2813 }
aba5acdf 2814 }
116ac927 2815
aba5acdf
SH
2816 if (show_details) {
2817 printf(" ino=%u uid=%u sk=%llx", ino, uid, sk);
2818 }
2819 printf("\n");
2820 }
2821
2822 return 0;
2823}
2824
129709ae
AV
2825static void netlink_show_one(struct filter *f,
2826 int prot, int pid, unsigned groups,
f271fe01 2827 int state, int dst_pid, unsigned dst_group,
129709ae
AV
2828 int rq, int wq,
2829 unsigned long long sk, unsigned long long cb)
2830{
eef43b50 2831 SPRINT_BUF(prot_name);
2832
129709ae
AV
2833 if (f->f) {
2834 struct tcpstat tst;
2835 tst.local.family = AF_NETLINK;
2836 tst.remote.family = AF_NETLINK;
2837 tst.rport = -1;
2838 tst.lport = pid;
2839 tst.local.data[0] = prot;
2840 tst.remote.data[0] = 0;
2841 if (run_ssfilter(f->f, &tst) == 0)
2842 return;
2843 }
2844
2845 if (netid_width)
2846 printf("%-*s ", netid_width, "nl");
2847 if (state_width)
2848 printf("%-*s ", state_width, "UNCONN");
2849 printf("%-6d %-6d ", rq, wq);
eef43b50 2850
d68e00f7 2851 if (resolve_services) {
eef43b50 2852 printf("%*s:", addr_width, nl_proto_n2a(prot, prot_name,
2853 sizeof(prot_name)));
d68e00f7 2854 } else {
2855 printf("%*d:", addr_width, prot);
eef43b50 2856 }
2857
129709ae
AV
2858 if (pid == -1) {
2859 printf("%-*s ", serv_width, "*");
2860 } else if (resolve_services) {
2861 int done = 0;
2862 if (!pid) {
2863 done = 1;
2864 printf("%-*s ", serv_width, "kernel");
2865 } else if (pid > 0) {
2866 char procname[64];
2867 FILE *fp;
2868 sprintf(procname, "%s/%d/stat",
2869 getenv("PROC_ROOT") ? : "/proc", pid);
2870 if ((fp = fopen(procname, "r")) != NULL) {
2871 if (fscanf(fp, "%*d (%[^)])", procname) == 1) {
2872 sprintf(procname+strlen(procname), "/%d", pid);
2873 printf("%-*s ", serv_width, procname);
2874 done = 1;
2875 }
2876 fclose(fp);
2877 }
2878 }
2879 if (!done)
2880 printf("%-*d ", serv_width, pid);
2881 } else {
2882 printf("%-*d ", serv_width, pid);
2883 }
f271fe01
AV
2884
2885 if (state == NETLINK_CONNECTED) {
2886 printf("%*d:%-*d",
d68e00f7 2887 addr_width, dst_group, serv_width, dst_pid);
f271fe01
AV
2888 } else {
2889 printf("%*s*%-*s",
d68e00f7 2890 addr_width, "", serv_width, "");
f271fe01 2891 }
129709ae 2892
116ac927
RH
2893 char *pid_context = NULL;
2894 if (show_proc_ctx) {
2895 /* The pid value will either be:
2896 * 0 if destination kernel - show kernel initial context.
2897 * A valid process pid - use getpidcon.
2898 * A unique value allocated by the kernel or netlink user
2899 * to the process - show context as "not available".
2900 */
2901 if (!pid)
2902 security_get_initial_context("kernel", &pid_context);
2903 else if (pid > 0)
2904 getpidcon(pid, &pid_context);
2905
2906 if (pid_context != NULL) {
2907 printf("proc_ctx=%-*s ", serv_width, pid_context);
2908 free(pid_context);
2909 } else {
2910 printf("proc_ctx=%-*s ", serv_width, "unavailable");
2911 }
2912 }
2913
129709ae
AV
2914 if (show_details) {
2915 printf(" sk=%llx cb=%llx groups=0x%08x", sk, cb, groups);
2916 }
2917 printf("\n");
2918
2919 return;
2920}
2921
8a4025f6 2922static int netlink_show_sock(const struct sockaddr_nl *addr,
2923 struct nlmsghdr *nlh, void *arg)
ecb928c8 2924{
8a4025f6 2925 struct filter *f = (struct filter *)arg;
ecb928c8
AV
2926 struct netlink_diag_msg *r = NLMSG_DATA(nlh);
2927 struct rtattr *tb[NETLINK_DIAG_MAX+1];
2928 int rq = 0, wq = 0;
2929 unsigned long groups = 0;
2930
2931 parse_rtattr(tb, NETLINK_DIAG_MAX, (struct rtattr*)(r+1),
2932 nlh->nlmsg_len - NLMSG_LENGTH(sizeof(*r)));
2933
2934 if (tb[NETLINK_DIAG_GROUPS] && RTA_PAYLOAD(tb[NETLINK_DIAG_GROUPS]))
2935 groups = *(unsigned long *) RTA_DATA(tb[NETLINK_DIAG_GROUPS]);
2936
2937 if (tb[NETLINK_DIAG_MEMINFO]) {
2938 const __u32 *skmeminfo;
2939 skmeminfo = RTA_DATA(tb[NETLINK_DIAG_MEMINFO]);
2940
2941 rq = skmeminfo[SK_MEMINFO_RMEM_ALLOC];
2942 wq = skmeminfo[SK_MEMINFO_WMEM_ALLOC];
2943 }
2944
2945 netlink_show_one(f, r->ndiag_protocol, r->ndiag_portid, groups,
2946 r->ndiag_state, r->ndiag_dst_portid, r->ndiag_dst_group,
2947 rq, wq, 0, 0);
2948
2949 if (show_mem) {
2950 printf("\t");
2951 print_skmeminfo(tb, NETLINK_DIAG_MEMINFO);
2952 printf("\n");
2953 }
2954
2955 return 0;
2956}
2957
8a4025f6 2958static int netlink_show_netlink(struct filter *f)
ecb928c8 2959{
5fb421d4 2960 DIAG_REQUEST(req, struct netlink_diag_req r);
ecb928c8
AV
2961
2962 req.r.sdiag_family = AF_NETLINK;
2963 req.r.sdiag_protocol = NDIAG_PROTO_ALL;
2964 req.r.ndiag_show = NDIAG_SHOW_GROUPS | NDIAG_SHOW_MEMINFO;
2965
8a4025f6 2966 return handle_netlink_request(f, &req.nlh, sizeof(req), netlink_show_sock);
ecb928c8
AV
2967}
2968
d1f28cf1 2969static int netlink_show(struct filter *f)
aba5acdf
SH
2970{
2971 FILE *fp;
2972 char buf[256];
2973 int prot, pid;
2974 unsigned groups;
2975 int rq, wq, rc;
2976 unsigned long long sk, cb;
2977
b9ea445d
VK
2978 if (preferred_family != AF_NETLINK && !(f->states & (1 << SS_CLOSE)))
2979 return 0;
2980
129709ae 2981 if (!getenv("PROC_NET_NETLINK") && !getenv("PROC_ROOT") &&
8a4025f6 2982 netlink_show_netlink(f) == 0)
129709ae
AV
2983 return 0;
2984
ab01dbbb 2985 if ((fp = net_netlink_open()) == NULL)
aba5acdf
SH
2986 return -1;
2987 fgets(buf, sizeof(buf)-1, fp);
2988
2989 while (fgets(buf, sizeof(buf)-1, fp)) {
2990 sscanf(buf, "%llx %d %d %x %d %d %llx %d",
2991 &sk,
2992 &prot, &pid, &groups, &rq, &wq, &cb, &rc);
2993
f271fe01 2994 netlink_show_one(f, prot, pid, groups, 0, 0, 0, rq, wq, sk, cb);
aba5acdf
SH
2995 }
2996
2997 return 0;
2998}
2999
3000struct snmpstat
3001{
3002 int tcp_estab;
3003};
3004
d1f28cf1 3005static int get_snmp_int(char *proto, char *key, int *result)
aba5acdf
SH
3006{
3007 char buf[1024];
3008 FILE *fp;
3009 int protolen = strlen(proto);
3010 int keylen = strlen(key);
3011
3012 *result = 0;
3013
ab01dbbb 3014 if ((fp = net_snmp_open()) == NULL)
aba5acdf
SH
3015 return -1;
3016
3017 while (fgets(buf, sizeof(buf), fp) != NULL) {
3018 char *p = buf;
3019 int pos = 0;
3020 if (memcmp(buf, proto, protolen))
3021 continue;
3022 while ((p = strchr(p, ' ')) != NULL) {
3023 pos++;
3024 p++;
3025 if (memcmp(p, key, keylen) == 0 &&
3026 (p[keylen] == ' ' || p[keylen] == '\n'))
3027 break;
3028 }
3029 if (fgets(buf, sizeof(buf), fp) == NULL)
3030 break;
3031 if (memcmp(buf, proto, protolen))
3032 break;
3033 p = buf;
3034 while ((p = strchr(p, ' ')) != NULL) {
3035 p++;
3036 if (--pos == 0) {
3037 sscanf(p, "%d", result);
3038 fclose(fp);
3039 return 0;
3040 }
3041 }
3042 }
3043
3044 fclose(fp);
3045 errno = ESRCH;
3046 return -1;
3047}
3048
3049
3050/* Get stats from sockstat */
3051
3052struct sockstat
3053{
3054 int socks;
3055 int tcp_mem;
3056 int tcp_total;
3057 int tcp_orphans;
3058 int tcp_tws;
3059 int tcp4_hashed;
3060 int udp4;
3061 int raw4;
3062 int frag4;
3063 int frag4_mem;
3064 int tcp6_hashed;
3065 int udp6;
3066 int raw6;
3067 int frag6;
3068 int frag6_mem;
3069};
3070
3071static void get_sockstat_line(char *line, struct sockstat *s)
3072{
3073 char id[256], rem[256];
3074
3075 if (sscanf(line, "%[^ ] %[^\n]\n", id, rem) != 2)
3076 return;
3077
3078 if (strcmp(id, "sockets:") == 0)
3079 sscanf(rem, "%*s%d", &s->socks);
3080 else if (strcmp(id, "UDP:") == 0)
3081 sscanf(rem, "%*s%d", &s->udp4);
3082 else if (strcmp(id, "UDP6:") == 0)
3083 sscanf(rem, "%*s%d", &s->udp6);
3084 else if (strcmp(id, "RAW:") == 0)
3085 sscanf(rem, "%*s%d", &s->raw4);
3086 else if (strcmp(id, "RAW6:") == 0)
3087 sscanf(rem, "%*s%d", &s->raw6);
3088 else if (strcmp(id, "TCP6:") == 0)
3089 sscanf(rem, "%*s%d", &s->tcp6_hashed);
3090 else if (strcmp(id, "FRAG:") == 0)
3091 sscanf(rem, "%*s%d%*s%d", &s->frag4, &s->frag4_mem);
3092 else if (strcmp(id, "FRAG6:") == 0)
3093 sscanf(rem, "%*s%d%*s%d", &s->frag6, &s->frag6_mem);
3094 else if (strcmp(id, "TCP:") == 0)
3095 sscanf(rem, "%*s%d%*s%d%*s%d%*s%d%*s%d",
3096 &s->tcp4_hashed,
3097 &s->tcp_orphans, &s->tcp_tws, &s->tcp_total, &s->tcp_mem);
3098}
3099
d1f28cf1 3100static int get_sockstat(struct sockstat *s)
aba5acdf
SH
3101{
3102 char buf[256];
3103 FILE *fp;
3104
3105 memset(s, 0, sizeof(*s));
3106
ab01dbbb 3107 if ((fp = net_sockstat_open()) == NULL)
aba5acdf
SH
3108 return -1;
3109 while(fgets(buf, sizeof(buf), fp) != NULL)
3110 get_sockstat_line(buf, s);
3111 fclose(fp);
3112
ab01dbbb 3113 if ((fp = net_sockstat6_open()) == NULL)
aba5acdf
SH
3114 return 0;
3115 while(fgets(buf, sizeof(buf), fp) != NULL)
3116 get_sockstat_line(buf, s);
3117 fclose(fp);
3118
3119 return 0;
3120}
3121
d1f28cf1 3122static int print_summary(void)
aba5acdf
SH
3123{
3124 struct sockstat s;
3125 struct snmpstat sn;
3126
3127 if (get_sockstat(&s) < 0)
3128 perror("ss: get_sockstat");
3129 if (get_snmp_int("Tcp:", "CurrEstab", &sn.tcp_estab) < 0)
3130 perror("ss: get_snmpstat");
3131
3132 printf("Total: %d (kernel %d)\n", s.socks, slabstat.socks);
3133
3134 printf("TCP: %d (estab %d, closed %d, orphaned %d, synrecv %d, timewait %d/%d), ports %d\n",
3135 s.tcp_total + slabstat.tcp_syns + s.tcp_tws,
3136 sn.tcp_estab,
3137 s.tcp_total - (s.tcp4_hashed+s.tcp6_hashed-s.tcp_tws),
3138 s.tcp_orphans,
3139 slabstat.tcp_syns,
3140 s.tcp_tws, slabstat.tcp_tws,
3141 slabstat.tcp_ports
3142 );
3143
3144 printf("\n");
3145 printf("Transport Total IP IPv6\n");
3146 printf("* %-9d %-9s %-9s\n", slabstat.socks, "-", "-");
3147 printf("RAW %-9d %-9d %-9d\n", s.raw4+s.raw6, s.raw4, s.raw6);
3148 printf("UDP %-9d %-9d %-9d\n", s.udp4+s.udp6, s.udp4, s.udp6);
3149 printf("TCP %-9d %-9d %-9d\n", s.tcp4_hashed+s.tcp6_hashed, s.tcp4_hashed, s.tcp6_hashed);
ae665a52 3150 printf("INET %-9d %-9d %-9d\n",
aba5acdf
SH
3151 s.raw4+s.udp4+s.tcp4_hashed+
3152 s.raw6+s.udp6+s.tcp6_hashed,
3153 s.raw4+s.udp4+s.tcp4_hashed,
3154 s.raw6+s.udp6+s.tcp6_hashed);
3155 printf("FRAG %-9d %-9d %-9d\n", s.frag4+s.frag6, s.frag4, s.frag6);
3156
3157 printf("\n");
3158
3159 return 0;
3160}
3161
7a96e199 3162static void _usage(FILE *dest)
aba5acdf 3163{
7a96e199 3164 fprintf(dest,
aba5acdf
SH
3165"Usage: ss [ OPTIONS ]\n"
3166" ss [ OPTIONS ] [ FILTER ]\n"
ab61159a
SH
3167" -h, --help this message\n"
3168" -V, --version output version information\n"
3169" -n, --numeric don't resolve service names\n"
3170" -r, --resolve resolve host names\n"
3171" -a, --all display all sockets\n"
3172" -l, --listening display listening sockets\n"
3173" -o, --options show timer information\n"
3174" -e, --extended show detailed socket information\n"
3175" -m, --memory show socket memory usage\n"
3176" -p, --processes show process using socket\n"
3177" -i, --info show internal TCP information\n"
3178" -s, --summary show socket usage summary\n"
b0f01cf6 3179" -b, --bpf show bpf filter socket information\n"
116ac927
RH
3180" -Z, --context display process SELinux security contexts\n"
3181" -z, --contexts display process and socket SELinux security contexts\n"
ab61159a
SH
3182"\n"
3183" -4, --ipv4 display only IP version 4 sockets\n"
3184" -6, --ipv6 display only IP version 6 sockets\n"
3185" -0, --packet display PACKET sockets\n"
3186" -t, --tcp display only TCP sockets\n"
3187" -u, --udp display only UDP sockets\n"
351efcde 3188" -d, --dccp display only DCCP sockets\n"
ab61159a
SH
3189" -w, --raw display only RAW sockets\n"
3190" -x, --unix display only Unix domain sockets\n"
3191" -f, --family=FAMILY display sockets of type FAMILY\n"
3192"\n"
583de149 3193" -A, --query=QUERY, --socket=QUERY\n"
56dee73e 3194" QUERY := {all|inet|tcp|udp|raw|unix|unix_dgram|unix_stream|unix_seqpacket|packet|netlink}[,QUERY]\n"
ab61159a 3195"\n"
583de149 3196" -D, --diag=FILE Dump raw information about TCP sockets to FILE\n"
ab61159a 3197" -F, --filter=FILE read filter information from FILE\n"
aba5acdf 3198" FILTER := [ state TCP-STATE ] [ EXPRESSION ]\n"
ab61159a 3199 );
7a96e199
AH
3200}
3201
3202static void help(void) __attribute__((noreturn));
3203static void help(void)
3204{
3205 _usage(stdout);
3206 exit(0);
3207}
3208
3209static void usage(void) __attribute__((noreturn));
3210static void usage(void)
3211{
3212 _usage(stderr);
aba5acdf
SH
3213 exit(-1);
3214}
3215
3216
d1f28cf1 3217static int scan_state(const char *state)
aba5acdf
SH
3218{
3219 int i;
3220 if (strcasecmp(state, "close") == 0 ||
3221 strcasecmp(state, "closed") == 0)
3222 return (1<<SS_CLOSE);
3223 if (strcasecmp(state, "syn-rcv") == 0)
3224 return (1<<SS_SYN_RECV);
1a5bad5a 3225 if (strcasecmp(state, "established") == 0)
aba5acdf
SH
3226 return (1<<SS_ESTABLISHED);
3227 if (strcasecmp(state, "all") == 0)
3228 return SS_ALL;
3229 if (strcasecmp(state, "connected") == 0)
3230 return SS_ALL & ~((1<<SS_CLOSE)|(1<<SS_LISTEN));
1a5bad5a 3231 if (strcasecmp(state, "synchronized") == 0)
aba5acdf
SH
3232 return SS_ALL & ~((1<<SS_CLOSE)|(1<<SS_LISTEN)|(1<<SS_SYN_SENT));
3233 if (strcasecmp(state, "bucket") == 0)
3234 return (1<<SS_SYN_RECV)|(1<<SS_TIME_WAIT);
3235 if (strcasecmp(state, "big") == 0)
3236 return SS_ALL & ~((1<<SS_SYN_RECV)|(1<<SS_TIME_WAIT));
3237 for (i=0; i<SS_MAX; i++) {
1a5bad5a 3238 if (strcasecmp(state, sstate_namel[i]) == 0)
aba5acdf
SH
3239 return (1<<i);
3240 }
3241 return 0;
3242}
3243
ab61159a
SH
3244static const struct option long_opts[] = {
3245 { "numeric", 0, 0, 'n' },
3246 { "resolve", 0, 0, 'r' },
3247 { "options", 0, 0, 'o' },
3248 { "extended", 0, 0, 'e' },
3249 { "memory", 0, 0, 'm' },
3250 { "info", 0, 0, 'i' },
3251 { "processes", 0, 0, 'p' },
372c30d2 3252 { "bpf", 0, 0, 'b' },
351efcde 3253 { "dccp", 0, 0, 'd' },
ab61159a
SH
3254 { "tcp", 0, 0, 't' },
3255 { "udp", 0, 0, 'u' },
3256 { "raw", 0, 0, 'w' },
3257 { "unix", 0, 0, 'x' },
3258 { "all", 0, 0, 'a' },
3259 { "listening", 0, 0, 'l' },
3260 { "ipv4", 0, 0, '4' },
3261 { "ipv6", 0, 0, '6' },
3262 { "packet", 0, 0, '0' },
3263 { "family", 1, 0, 'f' },
3264 { "socket", 1, 0, 'A' },
583de149 3265 { "query", 1, 0, 'A' },
c3f346b0 3266 { "summary", 0, 0, 's' },
583de149 3267 { "diag", 1, 0, 'D' },
ab61159a
SH
3268 { "filter", 1, 0, 'F' },
3269 { "version", 0, 0, 'V' },
3270 { "help", 0, 0, 'h' },
116ac927
RH
3271 { "context", 0, 0, 'Z' },
3272 { "contexts", 0, 0, 'z' },
ab61159a 3273 { 0 }
ae665a52 3274
ab61159a
SH
3275};
3276
aba5acdf
SH
3277int main(int argc, char *argv[])
3278{
3279 int do_default = 1;
3280 int saw_states = 0;
3281 int saw_query = 0;
3282 int do_summary = 0;
7d105b56 3283 const char *dump_tcpdiag = NULL;
aba5acdf
SH
3284 FILE *filter_fp = NULL;
3285 int ch;
3286
3287 memset(&current_filter, 0, sizeof(current_filter));
3288
3289 current_filter.states = default_filter.states;
3290
116ac927 3291 while ((ch = getopt_long(argc, argv, "dhaletuwxnro460spbf:miA:D:F:vVzZ",
ab61159a 3292 long_opts, NULL)) != EOF) {
aba5acdf
SH
3293 switch(ch) {
3294 case 'n':
3295 resolve_services = 0;
3296 break;
3297 case 'r':
3298 resolve_hosts = 1;
3299 break;
3300 case 'o':
3301 show_options = 1;
3302 break;
3303 case 'e':
3304 show_options = 1;
3305 show_details++;
3306 break;
3307 case 'm':
3308 show_mem = 1;
3309 break;
3310 case 'i':
3311 show_tcpinfo = 1;
3312 break;
3313 case 'p':
3314 show_users++;
fbc0f876 3315 user_ent_hash_build();
aba5acdf 3316 break;
372c30d2
ND
3317 case 'b':
3318 show_options = 1;
3319 show_bpf++;
3320 break;
351efcde
SH
3321 case 'd':
3322 current_filter.dbs |= (1<<DCCP_DB);
3323 do_default = 0;
3324 break;
aba5acdf
SH
3325 case 't':
3326 current_filter.dbs |= (1<<TCP_DB);
3327 do_default = 0;
3328 break;
3329 case 'u':
3330 current_filter.dbs |= (1<<UDP_DB);
3331 do_default = 0;
3332 break;
3333 case 'w':
3334 current_filter.dbs |= (1<<RAW_DB);
3335 do_default = 0;
3336 break;
3337 case 'x':
3338 current_filter.dbs |= UNIX_DBM;
3339 do_default = 0;
3340 break;
3341 case 'a':
3342 current_filter.states = SS_ALL;
3343 break;
3344 case 'l':
16963ce6 3345 current_filter.states = (1<<SS_LISTEN) | (1<<SS_CLOSE);
aba5acdf
SH
3346 break;
3347 case '4':
3348 preferred_family = AF_INET;
3349 break;
3350 case '6':
3351 preferred_family = AF_INET6;
3352 break;
3353 case '0':
3354 preferred_family = AF_PACKET;
3355 break;
3356 case 'f':
3357 if (strcmp(optarg, "inet") == 0)
3358 preferred_family = AF_INET;
3359 else if (strcmp(optarg, "inet6") == 0)
3360 preferred_family = AF_INET6;
3361 else if (strcmp(optarg, "link") == 0)
3362 preferred_family = AF_PACKET;
3363 else if (strcmp(optarg, "unix") == 0)
3364 preferred_family = AF_UNIX;
3365 else if (strcmp(optarg, "netlink") == 0)
3366 preferred_family = AF_NETLINK;
3367 else if (strcmp(optarg, "help") == 0)
7a96e199 3368 help();
aba5acdf
SH
3369 else {
3370 fprintf(stderr, "ss: \"%s\" is invalid family\n", optarg);
3371 usage();
3372 }
3373 break;
3374 case 'A':
3375 {
3376 char *p, *p1;
3377 if (!saw_query) {
3378 current_filter.dbs = 0;
3379 saw_query = 1;
3380 do_default = 0;
3381 }
3382 p = p1 = optarg;
3383 do {
3384 if ((p1 = strchr(p, ',')) != NULL)
ae665a52 3385 *p1 = 0;
aba5acdf
SH
3386 if (strcmp(p, "all") == 0) {
3387 current_filter.dbs = ALL_DB;
3388 } else if (strcmp(p, "inet") == 0) {
351efcde 3389 current_filter.dbs |= (1<<TCP_DB)|(1<<DCCP_DB)|(1<<UDP_DB)|(1<<RAW_DB);
aba5acdf
SH
3390 } else if (strcmp(p, "udp") == 0) {
3391 current_filter.dbs |= (1<<UDP_DB);
351efcde
SH
3392 } else if (strcmp(p, "dccp") == 0) {
3393 current_filter.dbs |= (1<<DCCP_DB);
aba5acdf
SH
3394 } else if (strcmp(p, "tcp") == 0) {
3395 current_filter.dbs |= (1<<TCP_DB);
3396 } else if (strcmp(p, "raw") == 0) {
3397 current_filter.dbs |= (1<<RAW_DB);
3398 } else if (strcmp(p, "unix") == 0) {
3399 current_filter.dbs |= UNIX_DBM;
1a5bad5a 3400 } else if (strcasecmp(p, "unix_stream") == 0 ||
aba5acdf
SH
3401 strcmp(p, "u_str") == 0) {
3402 current_filter.dbs |= (1<<UNIX_ST_DB);
1a5bad5a 3403 } else if (strcasecmp(p, "unix_dgram") == 0 ||
aba5acdf
SH
3404 strcmp(p, "u_dgr") == 0) {
3405 current_filter.dbs |= (1<<UNIX_DG_DB);
30b669d7
MY
3406 } else if (strcasecmp(p, "unix_seqpacket") == 0 ||
3407 strcmp(p, "u_seq") == 0) {
3408 current_filter.dbs |= (1<<UNIX_SQ_DB);
aba5acdf
SH
3409 } else if (strcmp(p, "packet") == 0) {
3410 current_filter.dbs |= PACKET_DBM;
3411 } else if (strcmp(p, "packet_raw") == 0 ||
3412 strcmp(p, "p_raw") == 0) {
3413 current_filter.dbs |= (1<<PACKET_R_DB);
3414 } else if (strcmp(p, "packet_dgram") == 0 ||
3415 strcmp(p, "p_dgr") == 0) {
3416 current_filter.dbs |= (1<<PACKET_DG_DB);
3417 } else if (strcmp(p, "netlink") == 0) {
3418 current_filter.dbs |= (1<<NETLINK_DB);
3419 } else {
3420 fprintf(stderr, "ss: \"%s\" is illegal socket table id\n", p);
3421 usage();
3422 }
3423 p = p1 + 1;
3424 } while (p1);
3425 break;
3426 }
3427 case 's':
3428 do_summary = 1;
3429 break;
3430 case 'D':
3431 dump_tcpdiag = optarg;
3432 break;
3433 case 'F':
3434 if (filter_fp) {
3435 fprintf(stderr, "More than one filter file\n");
3436 exit(-1);
3437 }
3438 if (optarg[0] == '-')
3439 filter_fp = stdin;
3440 else
3441 filter_fp = fopen(optarg, "r");
3442 if (!filter_fp) {
3443 perror("fopen filter file");
3444 exit(-1);
3445 }
3446 break;
3447 case 'v':
3448 case 'V':
3449 printf("ss utility, iproute2-ss%s\n", SNAPSHOT);
3450 exit(0);
116ac927
RH
3451 case 'z':
3452 show_sock_ctx++;
3453 case 'Z':
3454 if (is_selinux_enabled() <= 0) {
3455 fprintf(stderr, "ss: SELinux is not enabled.\n");
3456 exit(1);
3457 }
3458 show_proc_ctx++;
3459 user_ent_hash_build();
3460 break;
aba5acdf
SH
3461 case 'h':
3462 case '?':
7a96e199 3463 help();
aba5acdf
SH
3464 default:
3465 usage();
3466 }
3467 }
3468
3469 argc -= optind;
3470 argv += optind;
3471
3472 get_slabstat(&slabstat);
3473
3474 if (do_summary) {
3475 print_summary();
3476 if (do_default && argc == 0)
3477 exit(0);
3478 }
3479
3480 if (do_default)
3481 current_filter.dbs = default_filter.dbs;
3482
3483 if (preferred_family == AF_UNSPEC) {
3484 if (!(current_filter.dbs&~UNIX_DBM))
3485 preferred_family = AF_UNIX;
3486 else if (!(current_filter.dbs&~PACKET_DBM))
3487 preferred_family = AF_PACKET;
3488 else if (!(current_filter.dbs&~(1<<NETLINK_DB)))
3489 preferred_family = AF_NETLINK;
3490 }
3491
3492 if (preferred_family != AF_UNSPEC) {
3493 int mask2;
3494 if (preferred_family == AF_INET ||
3495 preferred_family == AF_INET6) {
f70d96a4 3496 mask2= current_filter.dbs;
aba5acdf
SH
3497 } else if (preferred_family == AF_PACKET) {
3498 mask2 = PACKET_DBM;
3499 } else if (preferred_family == AF_UNIX) {
3500 mask2 = UNIX_DBM;
3501 } else if (preferred_family == AF_NETLINK) {
3502 mask2 = (1<<NETLINK_DB);
3503 } else {
3504 mask2 = 0;
3505 }
3506
3507 if (do_default)
3508 current_filter.dbs = mask2;
3509 else
3510 current_filter.dbs &= mask2;
3511 current_filter.families = (1<<preferred_family);
3512 } else {
3513 if (!do_default)
3514 current_filter.families = ~0;
3515 else
3516 current_filter.families = default_filter.families;
3517 }
3518 if (current_filter.dbs == 0) {
3519 fprintf(stderr, "ss: no socket tables to show with such filter.\n");
3520 exit(0);
3521 }
3522 if (current_filter.families == 0) {
3523 fprintf(stderr, "ss: no families to show with such filter.\n");
3524 exit(0);
3525 }
3526
3527 if (resolve_services && resolve_hosts &&
351efcde 3528 (current_filter.dbs&(UNIX_DBM|(1<<TCP_DB)|(1<<UDP_DB)|(1<<DCCP_DB))))
aba5acdf
SH
3529 init_service_resolver();
3530
3531 /* Now parse filter... */
3532 if (argc == 0 && filter_fp) {
3533 if (ssfilter_parse(&current_filter.f, 0, NULL, filter_fp))
3534 usage();
3535 }
3536
3537 while (argc > 0) {
3538 if (strcmp(*argv, "state") == 0) {
3539 NEXT_ARG();
3540 if (!saw_states)
3541 current_filter.states = 0;
3542 current_filter.states |= scan_state(*argv);
3543 saw_states = 1;
3544 } else if (strcmp(*argv, "exclude") == 0 ||
3545 strcmp(*argv, "excl") == 0) {
3546 NEXT_ARG();
3547 if (!saw_states)
3548 current_filter.states = SS_ALL;
3549 current_filter.states &= ~scan_state(*argv);
3550 saw_states = 1;
3551 } else {
3552 if (ssfilter_parse(&current_filter.f, argc, argv, filter_fp))
3553 usage();
3554 break;
3555 }
3556 argc--; argv++;
3557 }
3558
3559 if (current_filter.states == 0) {
3560 fprintf(stderr, "ss: no socket states to show with such filter.\n");
3561 exit(0);
3562 }
3563
3564 if (dump_tcpdiag) {
3565 FILE *dump_fp = stdout;
3566 if (!(current_filter.dbs & (1<<TCP_DB))) {
3567 fprintf(stderr, "ss: tcpdiag dump requested and no tcp in filter.\n");
3568 exit(0);
3569 }
3570 if (dump_tcpdiag[0] != '-') {
3571 dump_fp = fopen(dump_tcpdiag, "w");
3572 if (!dump_tcpdiag) {
3573 perror("fopen dump file");
3574 exit(-1);
3575 }
3576 }
3fe5b534 3577 inet_show_netlink(&current_filter, dump_fp, IPPROTO_TCP);
aba5acdf
SH
3578 fflush(dump_fp);
3579 exit(0);
3580 }
3581
3582 netid_width = 0;
3583 if (current_filter.dbs&(current_filter.dbs-1))
3584 netid_width = 5;
3585
3586 state_width = 0;
3587 if (current_filter.states&(current_filter.states-1))
3588 state_width = 10;
3589
3590 screen_width = 80;
3591 if (isatty(STDOUT_FILENO)) {
3592 struct winsize w;
3593
3594 if (ioctl(STDOUT_FILENO, TIOCGWINSZ, &w) != -1) {
3595 if (w.ws_col > 0)
3596 screen_width = w.ws_col;
3597 }
3598 }
3599
3600 addrp_width = screen_width;
3601 addrp_width -= netid_width+1;
3602 addrp_width -= state_width+1;
3603 addrp_width -= 14;
3604
3605 if (addrp_width&1) {
3606 if (netid_width)
3607 netid_width++;
3608 else if (state_width)
3609 state_width++;
3610 }
3611
3612 addrp_width /= 2;
3613 addrp_width--;
3614
3615 serv_width = resolve_services ? 7 : 5;
3616
3617 if (addrp_width < 15+serv_width+1)
3618 addrp_width = 15+serv_width+1;
3619
ae665a52 3620 addr_width = addrp_width - serv_width - 1;
aba5acdf
SH
3621
3622 if (netid_width)
3623 printf("%-*s ", netid_width, "Netid");
3624 if (state_width)
3625 printf("%-*s ", state_width, "State");
3626 printf("%-6s %-6s ", "Recv-Q", "Send-Q");
3627
d68e00f7 3628 /* Make enough space for the local/remote port field */
3629 addr_width -= 13;
3630 serv_width += 13;
2dc85485 3631
aba5acdf
SH
3632 printf("%*s:%-*s %*s:%-*s\n",
3633 addr_width, "Local Address", serv_width, "Port",
d68e00f7 3634 addr_width, "Peer Address", serv_width, "Port");
aba5acdf 3635
aba5acdf
SH
3636 fflush(stdout);
3637
3638 if (current_filter.dbs & (1<<NETLINK_DB))
3639 netlink_show(&current_filter);
3640 if (current_filter.dbs & PACKET_DBM)
3641 packet_show(&current_filter);
3642 if (current_filter.dbs & UNIX_DBM)
3643 unix_show(&current_filter);
3644 if (current_filter.dbs & (1<<RAW_DB))
3645 raw_show(&current_filter);
3646 if (current_filter.dbs & (1<<UDP_DB))
3647 udp_show(&current_filter);
3648 if (current_filter.dbs & (1<<TCP_DB))
3fe5b534 3649 tcp_show(&current_filter, IPPROTO_TCP);
351efcde 3650 if (current_filter.dbs & (1<<DCCP_DB))
3fe5b534 3651 tcp_show(&current_filter, IPPROTO_DCCP);
116ac927
RH
3652
3653 if (show_users || show_proc_ctx || show_sock_ctx)
3654 user_ent_destroy();
3655
aba5acdf
SH
3656 return 0;
3657}