]> git.proxmox.com Git - mirror_iproute2.git/blame - misc/ss.c
libnetlink: add parse_rtattr_one_nested helper
[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]);
3d0b7439 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
486ccd99
VK
1874struct inet_diag_arg {
1875 struct filter *f;
1876 int protocol;
1877};
aba5acdf 1878
486ccd99
VK
1879static int show_one_inet_sock(const struct sockaddr_nl *addr,
1880 struct nlmsghdr *h, void *arg)
1881{
1882 int err;
1883 struct inet_diag_arg *diag_arg = arg;
1884 struct inet_diag_msg *r = NLMSG_DATA(h);
aba5acdf 1885
486ccd99
VK
1886 if (!(diag_arg->f->families & (1 << r->idiag_family)))
1887 return 0;
1888 if ((err = inet_show_sock(h, NULL, diag_arg->protocol)) < 0)
1889 return err;
aba5acdf 1890
486ccd99
VK
1891 return 0;
1892}
886d19d6 1893
486ccd99
VK
1894static int inet_show_netlink(struct filter *f, FILE *dump_fp, int protocol)
1895{
1896 int err = 0;
1897 struct rtnl_handle rth;
1898 int family = PF_INET;
1899 struct inet_diag_arg arg = { .f = f, .protocol = protocol };
886d19d6 1900
486ccd99
VK
1901 if (rtnl_open_byproto(&rth, 0, NETLINK_SOCK_DIAG))
1902 return -1;
1903 rth.dump = MAGIC_SEQ;
1904 rth.dump_fp = dump_fp;
886d19d6 1905
486ccd99
VK
1906again:
1907 if ((err = sockdiag_send(family, rth.fd, protocol, f)))
1908 goto Exit;
aba5acdf 1909
486ccd99
VK
1910 if ((err = rtnl_dump_filter(&rth, show_one_inet_sock, &arg))) {
1911 if (family != PF_UNSPEC) {
1912 family = PF_UNSPEC;
1913 goto again;
aba5acdf 1914 }
486ccd99 1915 goto Exit;
aba5acdf 1916 }
886d19d6
PE
1917 if (family == PF_INET) {
1918 family = PF_INET6;
1919 goto again;
1920 }
1921
486ccd99
VK
1922Exit:
1923 rtnl_close(&rth);
1924 return err;
aba5acdf
SH
1925}
1926
ab01dbbb 1927static int tcp_show_netlink_file(struct filter *f)
aba5acdf
SH
1928{
1929 FILE *fp;
e557212e 1930 char buf[16384];
aba5acdf
SH
1931
1932 if ((fp = fopen(getenv("TCPDIAG_FILE"), "r")) == NULL) {
1933 perror("fopen($TCPDIAG_FILE)");
1934 return -1;
1935 }
1936
1937 while (1) {
1938 int status, err;
1939 struct nlmsghdr *h = (struct nlmsghdr*)buf;
1940
1941 status = fread(buf, 1, sizeof(*h), fp);
1942 if (status < 0) {
1943 perror("Reading header from $TCPDIAG_FILE");
1944 return -1;
1945 }
1946 if (status != sizeof(*h)) {
1947 perror("Unexpected EOF reading $TCPDIAG_FILE");
1948 return -1;
1949 }
1950
1951 status = fread(h+1, 1, NLMSG_ALIGN(h->nlmsg_len-sizeof(*h)), fp);
1952
1953 if (status < 0) {
1954 perror("Reading $TCPDIAG_FILE");
1955 return -1;
1956 }
1957 if (status + sizeof(*h) < h->nlmsg_len) {
1958 perror("Unexpected EOF reading $TCPDIAG_FILE");
1959 return -1;
1960 }
1961
1962 /* The only legal exit point */
1963 if (h->nlmsg_type == NLMSG_DONE)
1964 return 0;
1965
1966 if (h->nlmsg_type == NLMSG_ERROR) {
1967 struct nlmsgerr *err = (struct nlmsgerr*)NLMSG_DATA(h);
1968 if (h->nlmsg_len < NLMSG_LENGTH(sizeof(struct nlmsgerr))) {
1969 fprintf(stderr, "ERROR truncated\n");
1970 } else {
1971 errno = -err->error;
1972 perror("TCPDIAG answered");
1973 }
1974 return -1;
1975 }
1976
77a8ca81 1977 err = inet_show_sock(h, f, IPPROTO_TCP);
aba5acdf
SH
1978 if (err < 0)
1979 return err;
1980 }
1981}
1982
ab01dbbb 1983static int tcp_show(struct filter *f, int socktype)
aba5acdf 1984{
ab01dbbb 1985 FILE *fp = NULL;
aba5acdf
SH
1986 char *buf = NULL;
1987 int bufsize = 64*1024;
1988
1989 dg_proto = TCP_PROTO;
1990
1991 if (getenv("TCPDIAG_FILE"))
1992 return tcp_show_netlink_file(f);
1993
1994 if (!getenv("PROC_NET_TCP") && !getenv("PROC_ROOT")
3fe5b534 1995 && inet_show_netlink(f, NULL, socktype) == 0)
aba5acdf
SH
1996 return 0;
1997
1998 /* Sigh... We have to parse /proc/net/tcp... */
1999
ab01dbbb 2000
aba5acdf
SH
2001 /* Estimate amount of sockets and try to allocate
2002 * huge buffer to read all the table at one read.
2003 * Limit it by 16MB though. The assumption is: as soon as
2004 * kernel was able to hold information about N connections,
2005 * it is able to give us some memory for snapshot.
2006 */
2007 if (1) {
2008 int guess = slabstat.socks+slabstat.tcp_syns;
2009 if (f->states&(1<<SS_TIME_WAIT))
2010 guess += slabstat.tcp_tws;
2011 if (guess > (16*1024*1024)/128)
2012 guess = (16*1024*1024)/128;
2013 guess *= 128;
2014 if (guess > bufsize)
2015 bufsize = guess;
2016 }
2017 while (bufsize >= 64*1024) {
2018 if ((buf = malloc(bufsize)) != NULL)
2019 break;
2020 bufsize /= 2;
2021 }
2022 if (buf == NULL) {
2023 errno = ENOMEM;
2024 return -1;
2025 }
2026
2027 if (f->families & (1<<AF_INET)) {
69cae645 2028 if ((fp = net_tcp_open()) == NULL)
aba5acdf 2029 goto outerr;
ab01dbbb
SH
2030
2031 setbuffer(fp, buf, bufsize);
2032 if (generic_record_read(fp, tcp_show_line, f, AF_INET))
aba5acdf 2033 goto outerr;
ab01dbbb 2034 fclose(fp);
aba5acdf
SH
2035 }
2036
2037 if ((f->families & (1<<AF_INET6)) &&
69cae645 2038 (fp = net_tcp6_open()) != NULL) {
ab01dbbb
SH
2039 setbuffer(fp, buf, bufsize);
2040 if (generic_record_read(fp, tcp_show_line, f, AF_INET6))
aba5acdf 2041 goto outerr;
ab01dbbb 2042 fclose(fp);
aba5acdf
SH
2043 }
2044
2045 free(buf);
2046 return 0;
2047
2048outerr:
2049 do {
2050 int saved_errno = errno;
2051 if (buf)
2052 free(buf);
ab01dbbb
SH
2053 if (fp)
2054 fclose(fp);
aba5acdf
SH
2055 errno = saved_errno;
2056 return -1;
2057 } while (0);
2058}
2059
2060
d1f28cf1 2061static int dgram_show_line(char *line, const struct filter *f, int family)
aba5acdf
SH
2062{
2063 struct tcpstat s;
2064 char *loc, *rem, *data;
2065 char opt[256];
2066 int n;
2067 char *p;
2068
2069 if ((p = strchr(line, ':')) == NULL)
2070 return -1;
2071 loc = p+2;
2072
2073 if ((p = strchr(loc, ':')) == NULL)
2074 return -1;
2075 p[5] = 0;
2076 rem = p+6;
2077
2078 if ((p = strchr(rem, ':')) == NULL)
2079 return -1;
2080 p[5] = 0;
2081 data = p+6;
2082
2083 do {
2084 int state = (data[1] >= 'A') ? (data[1] - 'A' + 10) : (data[1] - '0');
2085
2086 if (!(f->states & (1<<state)))
2087 return 0;
2088 } while (0);
2089
2090 s.local.family = s.remote.family = family;
2091 if (family == AF_INET) {
2092 sscanf(loc, "%x:%x", s.local.data, (unsigned*)&s.lport);
2093 sscanf(rem, "%x:%x", s.remote.data, (unsigned*)&s.rport);
2094 s.local.bytelen = s.remote.bytelen = 4;
2095 } else {
2096 sscanf(loc, "%08x%08x%08x%08x:%x",
2097 s.local.data,
2098 s.local.data+1,
2099 s.local.data+2,
2100 s.local.data+3,
2101 &s.lport);
2102 sscanf(rem, "%08x%08x%08x%08x:%x",
2103 s.remote.data,
2104 s.remote.data+1,
2105 s.remote.data+2,
2106 s.remote.data+3,
2107 &s.rport);
2108 s.local.bytelen = s.remote.bytelen = 16;
2109 }
2110
2111 if (f->f && run_ssfilter(f->f, &s) == 0)
2112 return 0;
2113
2114 opt[0] = 0;
e7113c61 2115 n = sscanf(data, "%x %x:%x %*x:%*x %*x %d %*d %u %d %llx %[^\n]\n",
aba5acdf
SH
2116 &s.state, &s.wq, &s.rq,
2117 &s.uid, &s.ino,
2118 &s.refcnt, &s.sk, opt);
2119
2120 if (n < 9)
2121 opt[0] = 0;
2122
2123 if (netid_width)
2124 printf("%-*s ", netid_width, dg_proto);
2125 if (state_width)
2126 printf("%-*s ", state_width, sstate_name[s.state]);
2127
2128 printf("%-6d %-6d ", s.rq, s.wq);
2129
7c8a3cfb
FLB
2130 formatted_print(&s.local, s.lport, 0);
2131 formatted_print(&s.remote, s.rport, 0);
aba5acdf 2132
116ac927
RH
2133 char *buf = NULL;
2134
2135 if (show_proc_ctx || show_sock_ctx) {
2136 if (find_entry(s.ino, &buf,
2137 (show_proc_ctx & show_sock_ctx) ?
2138 PROC_SOCK_CTX : PROC_CTX) > 0) {
2139 printf(" users:(%s)", buf);
2140 free(buf);
2141 }
2142 } else if (show_users) {
2143 if (find_entry(s.ino, &buf, USERS) > 0) {
2144 printf(" users:(%s)", buf);
2145 free(buf);
2146 }
aba5acdf
SH
2147 }
2148
2149 if (show_details) {
2150 if (s.uid)
2151 printf(" uid=%u", (unsigned)s.uid);
e7113c61 2152 printf(" ino=%u", s.ino);
aba5acdf
SH
2153 printf(" sk=%llx", s.sk);
2154 if (opt[0])
2155 printf(" opt:\"%s\"", opt);
2156 }
2157 printf("\n");
2158
2159 return 0;
2160}
2161
2162
d1f28cf1 2163static int udp_show(struct filter *f)
aba5acdf 2164{
ab01dbbb 2165 FILE *fp = NULL;
aba5acdf 2166
346f8ca8
PE
2167 if (!getenv("PROC_NET_UDP") && !getenv("PROC_ROOT")
2168 && inet_show_netlink(f, NULL, IPPROTO_UDP) == 0)
2169 return 0;
2170
aba5acdf
SH
2171 dg_proto = UDP_PROTO;
2172
2173 if (f->families&(1<<AF_INET)) {
69cae645 2174 if ((fp = net_udp_open()) == NULL)
aba5acdf 2175 goto outerr;
ab01dbbb 2176 if (generic_record_read(fp, dgram_show_line, f, AF_INET))
aba5acdf 2177 goto outerr;
ab01dbbb 2178 fclose(fp);
aba5acdf
SH
2179 }
2180
2181 if ((f->families&(1<<AF_INET6)) &&
69cae645 2182 (fp = net_udp6_open()) != NULL) {
ab01dbbb 2183 if (generic_record_read(fp, dgram_show_line, f, AF_INET6))
aba5acdf 2184 goto outerr;
ab01dbbb 2185 fclose(fp);
aba5acdf
SH
2186 }
2187 return 0;
2188
2189outerr:
2190 do {
2191 int saved_errno = errno;
ab01dbbb
SH
2192 if (fp)
2193 fclose(fp);
aba5acdf
SH
2194 errno = saved_errno;
2195 return -1;
2196 } while (0);
2197}
2198
d1f28cf1 2199static int raw_show(struct filter *f)
aba5acdf 2200{
ab01dbbb 2201 FILE *fp = NULL;
aba5acdf
SH
2202
2203 dg_proto = RAW_PROTO;
2204
2205 if (f->families&(1<<AF_INET)) {
69cae645 2206 if ((fp = net_raw_open()) == NULL)
aba5acdf 2207 goto outerr;
ab01dbbb 2208 if (generic_record_read(fp, dgram_show_line, f, AF_INET))
aba5acdf 2209 goto outerr;
ab01dbbb 2210 fclose(fp);
aba5acdf
SH
2211 }
2212
2213 if ((f->families&(1<<AF_INET6)) &&
69cae645 2214 (fp = net_raw6_open()) != NULL) {
ab01dbbb 2215 if (generic_record_read(fp, dgram_show_line, f, AF_INET6))
aba5acdf 2216 goto outerr;
ab01dbbb 2217 fclose(fp);
aba5acdf
SH
2218 }
2219 return 0;
2220
2221outerr:
2222 do {
2223 int saved_errno = errno;
ab01dbbb
SH
2224 if (fp)
2225 fclose(fp);
aba5acdf
SH
2226 errno = saved_errno;
2227 return -1;
2228 } while (0);
2229}
2230
2231
2232struct unixstat
2233{
2234 struct unixstat *next;
2235 int ino;
2236 int peer;
2237 int rq;
2238 int wq;
2239 int state;
2240 int type;
2241 char *name;
2242};
2243
2244
2245
2246int unix_state_map[] = { SS_CLOSE, SS_SYN_SENT,
2247 SS_ESTABLISHED, SS_CLOSING };
2248
2249
2250#define MAX_UNIX_REMEMBER (1024*1024/sizeof(struct unixstat))
2251
d1f28cf1 2252static void unix_list_free(struct unixstat *list)
aba5acdf
SH
2253{
2254 while (list) {
2255 struct unixstat *s = list;
2256 list = list->next;
2257 if (s->name)
2258 free(s->name);
2259 free(s);
2260 }
2261}
2262
30b669d7
MY
2263static const char *unix_netid_name(int type)
2264{
2265 const char *netid;
2266
2267 switch (type) {
2268 case SOCK_STREAM:
2269 netid = "u_str";
2270 break;
2271 case SOCK_SEQPACKET:
2272 netid = "u_seq";
2273 break;
2274 case SOCK_DGRAM:
2275 default:
2276 netid = "u_dgr";
2277 break;
2278 }
2279 return netid;
2280}
2281
d1f28cf1 2282static void unix_list_print(struct unixstat *list, struct filter *f)
aba5acdf
SH
2283{
2284 struct unixstat *s;
2285 char *peer;
2286
2287 for (s = list; s; s = s->next) {
2288 if (!(f->states & (1<<s->state)))
2289 continue;
2290 if (s->type == SOCK_STREAM && !(f->dbs&(1<<UNIX_ST_DB)))
2291 continue;
2292 if (s->type == SOCK_DGRAM && !(f->dbs&(1<<UNIX_DG_DB)))
2293 continue;
30b669d7
MY
2294 if (s->type == SOCK_SEQPACKET && !(f->dbs&(1<<UNIX_SQ_DB)))
2295 continue;
aba5acdf
SH
2296
2297 peer = "*";
2298 if (s->peer) {
2299 struct unixstat *p;
2300 for (p = list; p; p = p->next) {
2301 if (s->peer == p->ino)
2302 break;
2303 }
2304 if (!p) {
2305 peer = "?";
2306 } else {
2307 peer = p->name ? : "*";
2308 }
2309 }
2310
2311 if (f->f) {
2312 struct tcpstat tst;
2313 tst.local.family = AF_UNIX;
2314 tst.remote.family = AF_UNIX;
2315 memcpy(tst.local.data, &s->name, sizeof(s->name));
2316 if (strcmp(peer, "*") == 0)
2317 memset(tst.remote.data, 0, sizeof(peer));
2318 else
ae665a52 2319 memcpy(tst.remote.data, &peer, sizeof(peer));
aba5acdf
SH
2320 if (run_ssfilter(f->f, &tst) == 0)
2321 continue;
2322 }
2323
2324 if (netid_width)
ae665a52 2325 printf("%-*s ", netid_width,
30b669d7 2326 unix_netid_name(s->type));
aba5acdf
SH
2327 if (state_width)
2328 printf("%-*s ", state_width, sstate_name[s->state]);
2329 printf("%-6d %-6d ", s->rq, s->wq);
2330 printf("%*s %-*d %*s %-*d",
2331 addr_width, s->name ? : "*", serv_width, s->ino,
2332 addr_width, peer, serv_width, s->peer);
116ac927
RH
2333 char *buf = NULL;
2334
2335 if (show_proc_ctx || show_sock_ctx) {
2336 if (find_entry(s->ino, &buf,
2337 (show_proc_ctx & show_sock_ctx) ?
2338 PROC_SOCK_CTX : PROC_CTX) > 0) {
2339 printf(" users:(%s)", buf);
2340 free(buf);
2341 }
2342 } else if (show_users) {
2343 if (find_entry(s->ino, &buf, USERS) > 0) {
2344 printf(" users:(%s)", buf);
2345 free(buf);
2346 }
aba5acdf
SH
2347 }
2348 printf("\n");
2349 }
2350}
2351
8a4025f6 2352static int unix_show_sock(const struct sockaddr_nl *addr, struct nlmsghdr *nlh,
2353 void *arg)
dfbaa90d 2354{
8a4025f6 2355 struct filter *f = (struct filter *)arg;
dfbaa90d
PE
2356 struct unix_diag_msg *r = NLMSG_DATA(nlh);
2357 struct rtattr *tb[UNIX_DIAG_MAX+1];
2358 char name[128];
2359 int peer_ino;
defd61ca 2360 __u32 rqlen, wqlen;
dfbaa90d
PE
2361
2362 parse_rtattr(tb, UNIX_DIAG_MAX, (struct rtattr*)(r+1),
2363 nlh->nlmsg_len - NLMSG_LENGTH(sizeof(*r)));
2364
0d2e01c5
MY
2365 if (r->udiag_type == SOCK_STREAM && !(f->dbs&(1<<UNIX_ST_DB)))
2366 return 0;
2367 if (r->udiag_type == SOCK_DGRAM && !(f->dbs&(1<<UNIX_DG_DB)))
2368 return 0;
2369 if (r->udiag_type == SOCK_SEQPACKET && !(f->dbs&(1<<UNIX_SQ_DB)))
2370 return 0;
2371
dfbaa90d
PE
2372 if (netid_width)
2373 printf("%-*s ", netid_width,
30b669d7 2374 unix_netid_name(r->udiag_type));
dfbaa90d
PE
2375 if (state_width)
2376 printf("%-*s ", state_width, sstate_name[r->udiag_state]);
2377
defd61ca
HFS
2378 if (tb[UNIX_DIAG_RQLEN]) {
2379 struct unix_diag_rqlen *rql = RTA_DATA(tb[UNIX_DIAG_RQLEN]);
2380 rqlen = rql->udiag_rqueue;
2381 wqlen = rql->udiag_wqueue;
2382 } else {
dfbaa90d 2383 rqlen = 0;
defd61ca
HFS
2384 wqlen = 0;
2385 }
dfbaa90d 2386
defd61ca 2387 printf("%-6u %-6u ", rqlen, wqlen);
dfbaa90d
PE
2388
2389 if (tb[UNIX_DIAG_NAME]) {
2390 int len = RTA_PAYLOAD(tb[UNIX_DIAG_NAME]);
2391
2392 memcpy(name, RTA_DATA(tb[UNIX_DIAG_NAME]), len);
2393 name[len] = '\0';
2394 if (name[0] == '\0')
2395 name[0] = '@';
2396 } else
2397 sprintf(name, "*");
2398
2399 if (tb[UNIX_DIAG_PEER])
5048f9a0 2400 peer_ino = rta_getattr_u32(tb[UNIX_DIAG_PEER]);
dfbaa90d
PE
2401 else
2402 peer_ino = 0;
2403
2404 printf("%*s %-*d %*s %-*d",
2405 addr_width, name,
2406 serv_width, r->udiag_ino,
2407 addr_width, "*", /* FIXME */
2408 serv_width, peer_ino);
2409
116ac927
RH
2410 char *buf = NULL;
2411
2412 if (show_proc_ctx || show_sock_ctx) {
2413 if (find_entry(r->udiag_ino, &buf,
2414 (show_proc_ctx & show_sock_ctx) ?
2415 PROC_SOCK_CTX : PROC_CTX) > 0) {
2416 printf(" users:(%s)", buf);
2417 free(buf);
2418 }
2419 } else if (show_users) {
2420 if (find_entry(r->udiag_ino, &buf, USERS) > 0) {
2421 printf(" users:(%s)", buf);
2422 free(buf);
2423 }
dfbaa90d
PE
2424 }
2425
51ff9f24
HFS
2426 if (show_mem) {
2427 printf("\n\t");
2428 print_skmeminfo(tb, UNIX_DIAG_MEMINFO);
2429 }
2430
5b816047
PE
2431 if (show_details) {
2432 if (tb[UNIX_DIAG_SHUTDOWN]) {
2433 unsigned char mask;
2434 mask = *(__u8 *)RTA_DATA(tb[UNIX_DIAG_SHUTDOWN]);
2435 printf(" %c-%c", mask & 1 ? '-' : '<', mask & 2 ? '-' : '>');
2436 }
2437 }
2438
dfbaa90d
PE
2439 printf("\n");
2440
2441 return 0;
2442}
2443
8a4025f6 2444static int handle_netlink_request(struct filter *f, struct nlmsghdr *req,
2445 size_t size, rtnl_filter_t show_one_sock)
dfbaa90d 2446{
8a4025f6 2447 int ret = -1;
2448 struct rtnl_handle rth;
dfbaa90d 2449
8a4025f6 2450 if (rtnl_open_byproto(&rth, 0, NETLINK_SOCK_DIAG))
dfbaa90d
PE
2451 return -1;
2452
8a4025f6 2453 rth.dump = MAGIC_SEQ;
dfbaa90d 2454
8a4025f6 2455 if (rtnl_send(&rth, req, size) < 0)
2456 goto Exit;
dfbaa90d 2457
8a4025f6 2458 if (rtnl_dump_filter(&rth, show_one_sock, f))
2459 goto Exit;
dfbaa90d 2460
8a4025f6 2461 ret = 0;
2462Exit:
2463 rtnl_close(&rth);
2464 return ret;
dfbaa90d
PE
2465}
2466
8a4025f6 2467static int unix_show_netlink(struct filter *f)
d8402b96 2468{
5fb421d4 2469 DIAG_REQUEST(req, struct unix_diag_req r);
d8402b96
AV
2470
2471 req.r.sdiag_family = AF_UNIX;
2472 req.r.udiag_states = f->states;
2473 req.r.udiag_show = UDIAG_SHOW_NAME | UDIAG_SHOW_PEER | UDIAG_SHOW_RQLEN;
2474 if (show_mem)
2475 req.r.udiag_show |= UDIAG_SHOW_MEMINFO;
2476
8a4025f6 2477 return handle_netlink_request(f, &req.nlh, sizeof(req), unix_show_sock);
d8402b96
AV
2478}
2479
d1f28cf1 2480static int unix_show(struct filter *f)
aba5acdf
SH
2481{
2482 FILE *fp;
2483 char buf[256];
2484 char name[128];
2485 int newformat = 0;
2486 int cnt;
2487 struct unixstat *list = NULL;
2488
dfbaa90d 2489 if (!getenv("PROC_NET_UNIX") && !getenv("PROC_ROOT")
8a4025f6 2490 && unix_show_netlink(f) == 0)
dfbaa90d
PE
2491 return 0;
2492
ab01dbbb 2493 if ((fp = net_unix_open()) == NULL)
aba5acdf
SH
2494 return -1;
2495 fgets(buf, sizeof(buf)-1, fp);
2496
ae665a52 2497 if (memcmp(buf, "Peer", 4) == 0)
aba5acdf
SH
2498 newformat = 1;
2499 cnt = 0;
2500
2501 while (fgets(buf, sizeof(buf)-1, fp)) {
2502 struct unixstat *u, **insp;
2503 int flags;
2504
2505 if (!(u = malloc(sizeof(*u))))
2506 break;
2507 u->name = NULL;
2508
2509 if (sscanf(buf, "%x: %x %x %x %x %x %d %s",
2510 &u->peer, &u->rq, &u->wq, &flags, &u->type,
2511 &u->state, &u->ino, name) < 8)
2512 name[0] = 0;
2513
2514 if (flags&(1<<16)) {
2515 u->state = SS_LISTEN;
2516 } else {
2517 u->state = unix_state_map[u->state-1];
2518 if (u->type == SOCK_DGRAM &&
2519 u->state == SS_CLOSE &&
2520 u->peer)
2521 u->state = SS_ESTABLISHED;
2522 }
2523
2524 if (!newformat) {
2525 u->peer = 0;
2526 u->rq = 0;
2527 u->wq = 0;
2528 }
2529
2530 insp = &list;
2531 while (*insp) {
2532 if (u->type < (*insp)->type ||
2533 (u->type == (*insp)->type &&
2534 u->ino < (*insp)->ino))
2535 break;
2536 insp = &(*insp)->next;
2537 }
2538 u->next = *insp;
2539 *insp = u;
2540
2541 if (name[0]) {
2542 if ((u->name = malloc(strlen(name)+1)) == NULL)
2543 break;
2544 strcpy(u->name, name);
2545 }
2546 if (++cnt > MAX_UNIX_REMEMBER) {
2547 unix_list_print(list, f);
2548 unix_list_free(list);
2549 list = NULL;
2550 cnt = 0;
2551 }
2552 }
a3fd8e58 2553 fclose(fp);
aba5acdf
SH
2554 if (list) {
2555 unix_list_print(list, f);
2556 unix_list_free(list);
2557 list = NULL;
2558 cnt = 0;
2559 }
2560
2561 return 0;
2562}
2563
8a4025f6 2564static int packet_show_sock(const struct sockaddr_nl *addr,
2565 struct nlmsghdr *nlh, void *arg)
372c30d2
ND
2566{
2567 struct packet_diag_msg *r = NLMSG_DATA(nlh);
2568 struct rtattr *tb[PACKET_DIAG_MAX+1];
2569 __u32 rq;
2570
2571 parse_rtattr(tb, PACKET_DIAG_MAX, (struct rtattr*)(r+1),
2572 nlh->nlmsg_len - NLMSG_LENGTH(sizeof(*r)));
2573
2574 /* use /proc/net/packet if all info are not available */
2575 if (!tb[PACKET_DIAG_MEMINFO])
2576 return -1;
2577
2578 if (netid_width)
2579 printf("%-*s ", netid_width,
2580 r->pdiag_type == SOCK_RAW ? "p_raw" : "p_dgr");
2581 if (state_width)
2582 printf("%-*s ", state_width, "UNCONN");
2583
2584 if (tb[PACKET_DIAG_MEMINFO]) {
2585 __u32 *skmeminfo = RTA_DATA(tb[PACKET_DIAG_MEMINFO]);
2586
2587 rq = skmeminfo[SK_MEMINFO_RMEM_ALLOC];
2588 } else
2589 rq = 0;
2590 printf("%-6d %-6d ", rq, 0);
2591
2592 if (r->pdiag_num == 3) {
2593 printf("%*s:", addr_width, "*");
2594 } else {
2595 char tb2[16];
2596 printf("%*s:", addr_width,
2597 ll_proto_n2a(htons(r->pdiag_num), tb2, sizeof(tb2)));
2598 }
2599 if (tb[PACKET_DIAG_INFO]) {
2600 struct packet_diag_info *pinfo = RTA_DATA(tb[PACKET_DIAG_INFO]);
2601
2602 if (pinfo->pdi_index == 0)
2603 printf("%-*s ", serv_width, "*");
2604 else
2605 printf("%-*s ", serv_width, xll_index_to_name(pinfo->pdi_index));
2606 } else
2607 printf("%-*s ", serv_width, "*");
2608
2609 printf("%*s*%-*s",
2610 addr_width, "", serv_width, "");
2611
116ac927
RH
2612 char *buf = NULL;
2613
2614 if (show_proc_ctx || show_sock_ctx) {
2615 if (find_entry(r->pdiag_ino, &buf,
2616 (show_proc_ctx & show_sock_ctx) ?
2617 PROC_SOCK_CTX : PROC_CTX) > 0) {
2618 printf(" users:(%s)", buf);
2619 free(buf);
2620 }
2621 } else if (show_users) {
2622 if (find_entry(r->pdiag_ino, &buf, USERS) > 0) {
2623 printf(" users:(%s)", buf);
2624 free(buf);
2625 }
372c30d2 2626 }
116ac927 2627
372c30d2
ND
2628 if (show_details) {
2629 __u32 uid = 0;
2630
2631 if (tb[PACKET_DIAG_UID])
2632 uid = *(__u32 *)RTA_DATA(tb[PACKET_DIAG_UID]);
2633
2634 printf(" ino=%u uid=%u sk=", r->pdiag_ino, uid);
2635 if (r->pdiag_cookie[1] != 0)
2636 printf("%08x", r->pdiag_cookie[1]);
2637 printf("%08x", r->pdiag_cookie[0]);
2638 }
2639
2640 if (show_bpf && tb[PACKET_DIAG_FILTER]) {
2641 struct sock_filter *fil =
2642 RTA_DATA(tb[PACKET_DIAG_FILTER]);
2643 int num = RTA_PAYLOAD(tb[PACKET_DIAG_FILTER]) /
2644 sizeof(struct sock_filter);
2645
2646 printf("\n\tbpf filter (%d): ", num);
2647 while (num) {
2648 printf(" 0x%02x %u %u %u,",
2649 fil->code, fil->jt, fil->jf, fil->k);
2650 num--;
2651 fil++;
2652 }
2653 }
2654 printf("\n");
2655 return 0;
2656}
2657
8a4025f6 2658static int packet_show_netlink(struct filter *f)
372c30d2 2659{
5fb421d4 2660 DIAG_REQUEST(req, struct packet_diag_req r);
372c30d2 2661
372c30d2
ND
2662 req.r.sdiag_family = AF_PACKET;
2663 req.r.pdiag_show = PACKET_SHOW_INFO | PACKET_SHOW_MEMINFO | PACKET_SHOW_FILTER;
2664
8a4025f6 2665 return handle_netlink_request(f, &req.nlh, sizeof(req), packet_show_sock);
372c30d2
ND
2666}
2667
aba5acdf 2668
d1f28cf1 2669static int packet_show(struct filter *f)
aba5acdf
SH
2670{
2671 FILE *fp;
2672 char buf[256];
2673 int type;
2674 int prot;
2675 int iface;
2676 int state;
2677 int rq;
2678 int uid;
2679 int ino;
2680 unsigned long long sk;
3d0b7439 2681
b9ea445d
VK
2682 if (preferred_family != AF_PACKET && !(f->states & (1 << SS_CLOSE)))
2683 return 0;
aba5acdf 2684
8a4025f6 2685 if (packet_show_netlink(f) == 0)
372c30d2
ND
2686 return 0;
2687
ab01dbbb 2688 if ((fp = net_packet_open()) == NULL)
aba5acdf
SH
2689 return -1;
2690 fgets(buf, sizeof(buf)-1, fp);
2691
2692 while (fgets(buf, sizeof(buf)-1, fp)) {
2693 sscanf(buf, "%llx %*d %d %x %d %d %u %u %u",
2694 &sk,
2695 &type, &prot, &iface, &state,
2696 &rq, &uid, &ino);
2697
2698 if (type == SOCK_RAW && !(f->dbs&(1<<PACKET_R_DB)))
2699 continue;
2700 if (type == SOCK_DGRAM && !(f->dbs&(1<<PACKET_DG_DB)))
2701 continue;
2702 if (f->f) {
2703 struct tcpstat tst;
2704 tst.local.family = AF_PACKET;
2705 tst.remote.family = AF_PACKET;
2706 tst.rport = 0;
2707 tst.lport = iface;
2708 tst.local.data[0] = prot;
2709 tst.remote.data[0] = 0;
2710 if (run_ssfilter(f->f, &tst) == 0)
2711 continue;
2712 }
2713
2714 if (netid_width)
ae665a52 2715 printf("%-*s ", netid_width,
aba5acdf
SH
2716 type == SOCK_RAW ? "p_raw" : "p_dgr");
2717 if (state_width)
2718 printf("%-*s ", state_width, "UNCONN");
2719 printf("%-6d %-6d ", rq, 0);
2720 if (prot == 3) {
2721 printf("%*s:", addr_width, "*");
2722 } else {
2723 char tb[16];
ae665a52 2724 printf("%*s:", addr_width,
aba5acdf
SH
2725 ll_proto_n2a(htons(prot), tb, sizeof(tb)));
2726 }
2727 if (iface == 0) {
2728 printf("%-*s ", serv_width, "*");
2729 } else {
2730 printf("%-*s ", serv_width, xll_index_to_name(iface));
2731 }
2732 printf("%*s*%-*s",
2733 addr_width, "", serv_width, "");
2734
116ac927
RH
2735 char *buf = NULL;
2736
2737 if (show_proc_ctx || show_sock_ctx) {
2738 if (find_entry(ino, &buf,
2739 (show_proc_ctx & show_sock_ctx) ?
2740 PROC_SOCK_CTX : PROC_CTX) > 0) {
2741 printf(" users:(%s)", buf);
2742 free(buf);
2743 }
2744 } else if (show_users) {
2745 if (find_entry(ino, &buf, USERS) > 0) {
2746 printf(" users:(%s)", buf);
2747 free(buf);
2748 }
aba5acdf 2749 }
116ac927 2750
aba5acdf
SH
2751 if (show_details) {
2752 printf(" ino=%u uid=%u sk=%llx", ino, uid, sk);
2753 }
2754 printf("\n");
2755 }
2756
2757 return 0;
2758}
2759
129709ae
AV
2760static void netlink_show_one(struct filter *f,
2761 int prot, int pid, unsigned groups,
f271fe01 2762 int state, int dst_pid, unsigned dst_group,
129709ae
AV
2763 int rq, int wq,
2764 unsigned long long sk, unsigned long long cb)
2765{
eef43b50 2766 SPRINT_BUF(prot_name);
2767
129709ae
AV
2768 if (f->f) {
2769 struct tcpstat tst;
2770 tst.local.family = AF_NETLINK;
2771 tst.remote.family = AF_NETLINK;
2772 tst.rport = -1;
2773 tst.lport = pid;
2774 tst.local.data[0] = prot;
2775 tst.remote.data[0] = 0;
2776 if (run_ssfilter(f->f, &tst) == 0)
2777 return;
2778 }
2779
2780 if (netid_width)
2781 printf("%-*s ", netid_width, "nl");
2782 if (state_width)
2783 printf("%-*s ", state_width, "UNCONN");
2784 printf("%-6d %-6d ", rq, wq);
eef43b50 2785
d68e00f7 2786 if (resolve_services) {
eef43b50 2787 printf("%*s:", addr_width, nl_proto_n2a(prot, prot_name,
2788 sizeof(prot_name)));
d68e00f7 2789 } else {
2790 printf("%*d:", addr_width, prot);
eef43b50 2791 }
2792
129709ae
AV
2793 if (pid == -1) {
2794 printf("%-*s ", serv_width, "*");
2795 } else if (resolve_services) {
2796 int done = 0;
2797 if (!pid) {
2798 done = 1;
2799 printf("%-*s ", serv_width, "kernel");
2800 } else if (pid > 0) {
2801 char procname[64];
2802 FILE *fp;
2803 sprintf(procname, "%s/%d/stat",
2804 getenv("PROC_ROOT") ? : "/proc", pid);
2805 if ((fp = fopen(procname, "r")) != NULL) {
2806 if (fscanf(fp, "%*d (%[^)])", procname) == 1) {
2807 sprintf(procname+strlen(procname), "/%d", pid);
2808 printf("%-*s ", serv_width, procname);
2809 done = 1;
2810 }
2811 fclose(fp);
2812 }
2813 }
2814 if (!done)
2815 printf("%-*d ", serv_width, pid);
2816 } else {
2817 printf("%-*d ", serv_width, pid);
2818 }
f271fe01
AV
2819
2820 if (state == NETLINK_CONNECTED) {
2821 printf("%*d:%-*d",
d68e00f7 2822 addr_width, dst_group, serv_width, dst_pid);
f271fe01
AV
2823 } else {
2824 printf("%*s*%-*s",
d68e00f7 2825 addr_width, "", serv_width, "");
f271fe01 2826 }
129709ae 2827
116ac927
RH
2828 char *pid_context = NULL;
2829 if (show_proc_ctx) {
2830 /* The pid value will either be:
2831 * 0 if destination kernel - show kernel initial context.
2832 * A valid process pid - use getpidcon.
2833 * A unique value allocated by the kernel or netlink user
2834 * to the process - show context as "not available".
2835 */
2836 if (!pid)
2837 security_get_initial_context("kernel", &pid_context);
2838 else if (pid > 0)
2839 getpidcon(pid, &pid_context);
2840
2841 if (pid_context != NULL) {
2842 printf("proc_ctx=%-*s ", serv_width, pid_context);
2843 free(pid_context);
2844 } else {
2845 printf("proc_ctx=%-*s ", serv_width, "unavailable");
2846 }
2847 }
2848
129709ae
AV
2849 if (show_details) {
2850 printf(" sk=%llx cb=%llx groups=0x%08x", sk, cb, groups);
2851 }
2852 printf("\n");
2853
2854 return;
2855}
2856
8a4025f6 2857static int netlink_show_sock(const struct sockaddr_nl *addr,
2858 struct nlmsghdr *nlh, void *arg)
ecb928c8 2859{
8a4025f6 2860 struct filter *f = (struct filter *)arg;
ecb928c8
AV
2861 struct netlink_diag_msg *r = NLMSG_DATA(nlh);
2862 struct rtattr *tb[NETLINK_DIAG_MAX+1];
2863 int rq = 0, wq = 0;
2864 unsigned long groups = 0;
2865
2866 parse_rtattr(tb, NETLINK_DIAG_MAX, (struct rtattr*)(r+1),
2867 nlh->nlmsg_len - NLMSG_LENGTH(sizeof(*r)));
2868
2869 if (tb[NETLINK_DIAG_GROUPS] && RTA_PAYLOAD(tb[NETLINK_DIAG_GROUPS]))
2870 groups = *(unsigned long *) RTA_DATA(tb[NETLINK_DIAG_GROUPS]);
2871
2872 if (tb[NETLINK_DIAG_MEMINFO]) {
2873 const __u32 *skmeminfo;
2874 skmeminfo = RTA_DATA(tb[NETLINK_DIAG_MEMINFO]);
2875
2876 rq = skmeminfo[SK_MEMINFO_RMEM_ALLOC];
2877 wq = skmeminfo[SK_MEMINFO_WMEM_ALLOC];
2878 }
2879
2880 netlink_show_one(f, r->ndiag_protocol, r->ndiag_portid, groups,
2881 r->ndiag_state, r->ndiag_dst_portid, r->ndiag_dst_group,
2882 rq, wq, 0, 0);
2883
2884 if (show_mem) {
2885 printf("\t");
2886 print_skmeminfo(tb, NETLINK_DIAG_MEMINFO);
2887 printf("\n");
2888 }
2889
2890 return 0;
2891}
2892
8a4025f6 2893static int netlink_show_netlink(struct filter *f)
ecb928c8 2894{
5fb421d4 2895 DIAG_REQUEST(req, struct netlink_diag_req r);
ecb928c8
AV
2896
2897 req.r.sdiag_family = AF_NETLINK;
2898 req.r.sdiag_protocol = NDIAG_PROTO_ALL;
2899 req.r.ndiag_show = NDIAG_SHOW_GROUPS | NDIAG_SHOW_MEMINFO;
2900
8a4025f6 2901 return handle_netlink_request(f, &req.nlh, sizeof(req), netlink_show_sock);
ecb928c8
AV
2902}
2903
d1f28cf1 2904static int netlink_show(struct filter *f)
aba5acdf
SH
2905{
2906 FILE *fp;
2907 char buf[256];
2908 int prot, pid;
2909 unsigned groups;
2910 int rq, wq, rc;
2911 unsigned long long sk, cb;
2912
b9ea445d
VK
2913 if (preferred_family != AF_NETLINK && !(f->states & (1 << SS_CLOSE)))
2914 return 0;
2915
129709ae 2916 if (!getenv("PROC_NET_NETLINK") && !getenv("PROC_ROOT") &&
8a4025f6 2917 netlink_show_netlink(f) == 0)
129709ae
AV
2918 return 0;
2919
ab01dbbb 2920 if ((fp = net_netlink_open()) == NULL)
aba5acdf
SH
2921 return -1;
2922 fgets(buf, sizeof(buf)-1, fp);
2923
2924 while (fgets(buf, sizeof(buf)-1, fp)) {
2925 sscanf(buf, "%llx %d %d %x %d %d %llx %d",
2926 &sk,
2927 &prot, &pid, &groups, &rq, &wq, &cb, &rc);
2928
f271fe01 2929 netlink_show_one(f, prot, pid, groups, 0, 0, 0, rq, wq, sk, cb);
aba5acdf
SH
2930 }
2931
2932 return 0;
2933}
2934
2935struct snmpstat
2936{
2937 int tcp_estab;
2938};
2939
d1f28cf1 2940static int get_snmp_int(char *proto, char *key, int *result)
aba5acdf
SH
2941{
2942 char buf[1024];
2943 FILE *fp;
2944 int protolen = strlen(proto);
2945 int keylen = strlen(key);
2946
2947 *result = 0;
2948
ab01dbbb 2949 if ((fp = net_snmp_open()) == NULL)
aba5acdf
SH
2950 return -1;
2951
2952 while (fgets(buf, sizeof(buf), fp) != NULL) {
2953 char *p = buf;
2954 int pos = 0;
2955 if (memcmp(buf, proto, protolen))
2956 continue;
2957 while ((p = strchr(p, ' ')) != NULL) {
2958 pos++;
2959 p++;
2960 if (memcmp(p, key, keylen) == 0 &&
2961 (p[keylen] == ' ' || p[keylen] == '\n'))
2962 break;
2963 }
2964 if (fgets(buf, sizeof(buf), fp) == NULL)
2965 break;
2966 if (memcmp(buf, proto, protolen))
2967 break;
2968 p = buf;
2969 while ((p = strchr(p, ' ')) != NULL) {
2970 p++;
2971 if (--pos == 0) {
2972 sscanf(p, "%d", result);
2973 fclose(fp);
2974 return 0;
2975 }
2976 }
2977 }
2978
2979 fclose(fp);
2980 errno = ESRCH;
2981 return -1;
2982}
2983
2984
2985/* Get stats from sockstat */
2986
2987struct sockstat
2988{
2989 int socks;
2990 int tcp_mem;
2991 int tcp_total;
2992 int tcp_orphans;
2993 int tcp_tws;
2994 int tcp4_hashed;
2995 int udp4;
2996 int raw4;
2997 int frag4;
2998 int frag4_mem;
2999 int tcp6_hashed;
3000 int udp6;
3001 int raw6;
3002 int frag6;
3003 int frag6_mem;
3004};
3005
3006static void get_sockstat_line(char *line, struct sockstat *s)
3007{
3008 char id[256], rem[256];
3009
3010 if (sscanf(line, "%[^ ] %[^\n]\n", id, rem) != 2)
3011 return;
3012
3013 if (strcmp(id, "sockets:") == 0)
3014 sscanf(rem, "%*s%d", &s->socks);
3015 else if (strcmp(id, "UDP:") == 0)
3016 sscanf(rem, "%*s%d", &s->udp4);
3017 else if (strcmp(id, "UDP6:") == 0)
3018 sscanf(rem, "%*s%d", &s->udp6);
3019 else if (strcmp(id, "RAW:") == 0)
3020 sscanf(rem, "%*s%d", &s->raw4);
3021 else if (strcmp(id, "RAW6:") == 0)
3022 sscanf(rem, "%*s%d", &s->raw6);
3023 else if (strcmp(id, "TCP6:") == 0)
3024 sscanf(rem, "%*s%d", &s->tcp6_hashed);
3025 else if (strcmp(id, "FRAG:") == 0)
3026 sscanf(rem, "%*s%d%*s%d", &s->frag4, &s->frag4_mem);
3027 else if (strcmp(id, "FRAG6:") == 0)
3028 sscanf(rem, "%*s%d%*s%d", &s->frag6, &s->frag6_mem);
3029 else if (strcmp(id, "TCP:") == 0)
3030 sscanf(rem, "%*s%d%*s%d%*s%d%*s%d%*s%d",
3031 &s->tcp4_hashed,
3032 &s->tcp_orphans, &s->tcp_tws, &s->tcp_total, &s->tcp_mem);
3033}
3034
d1f28cf1 3035static int get_sockstat(struct sockstat *s)
aba5acdf
SH
3036{
3037 char buf[256];
3038 FILE *fp;
3039
3040 memset(s, 0, sizeof(*s));
3041
ab01dbbb 3042 if ((fp = net_sockstat_open()) == NULL)
aba5acdf
SH
3043 return -1;
3044 while(fgets(buf, sizeof(buf), fp) != NULL)
3045 get_sockstat_line(buf, s);
3046 fclose(fp);
3047
ab01dbbb 3048 if ((fp = net_sockstat6_open()) == NULL)
aba5acdf
SH
3049 return 0;
3050 while(fgets(buf, sizeof(buf), fp) != NULL)
3051 get_sockstat_line(buf, s);
3052 fclose(fp);
3053
3054 return 0;
3055}
3056
d1f28cf1 3057static int print_summary(void)
aba5acdf
SH
3058{
3059 struct sockstat s;
3060 struct snmpstat sn;
3061
3062 if (get_sockstat(&s) < 0)
3063 perror("ss: get_sockstat");
3064 if (get_snmp_int("Tcp:", "CurrEstab", &sn.tcp_estab) < 0)
3065 perror("ss: get_snmpstat");
3066
3067 printf("Total: %d (kernel %d)\n", s.socks, slabstat.socks);
3068
3069 printf("TCP: %d (estab %d, closed %d, orphaned %d, synrecv %d, timewait %d/%d), ports %d\n",
3070 s.tcp_total + slabstat.tcp_syns + s.tcp_tws,
3071 sn.tcp_estab,
3072 s.tcp_total - (s.tcp4_hashed+s.tcp6_hashed-s.tcp_tws),
3073 s.tcp_orphans,
3074 slabstat.tcp_syns,
3075 s.tcp_tws, slabstat.tcp_tws,
3076 slabstat.tcp_ports
3077 );
3078
3079 printf("\n");
3080 printf("Transport Total IP IPv6\n");
3081 printf("* %-9d %-9s %-9s\n", slabstat.socks, "-", "-");
3082 printf("RAW %-9d %-9d %-9d\n", s.raw4+s.raw6, s.raw4, s.raw6);
3083 printf("UDP %-9d %-9d %-9d\n", s.udp4+s.udp6, s.udp4, s.udp6);
3084 printf("TCP %-9d %-9d %-9d\n", s.tcp4_hashed+s.tcp6_hashed, s.tcp4_hashed, s.tcp6_hashed);
ae665a52 3085 printf("INET %-9d %-9d %-9d\n",
aba5acdf
SH
3086 s.raw4+s.udp4+s.tcp4_hashed+
3087 s.raw6+s.udp6+s.tcp6_hashed,
3088 s.raw4+s.udp4+s.tcp4_hashed,
3089 s.raw6+s.udp6+s.tcp6_hashed);
3090 printf("FRAG %-9d %-9d %-9d\n", s.frag4+s.frag6, s.frag4, s.frag6);
3091
3092 printf("\n");
3093
3094 return 0;
3095}
3096
7a96e199 3097static void _usage(FILE *dest)
aba5acdf 3098{
7a96e199 3099 fprintf(dest,
aba5acdf
SH
3100"Usage: ss [ OPTIONS ]\n"
3101" ss [ OPTIONS ] [ FILTER ]\n"
ab61159a
SH
3102" -h, --help this message\n"
3103" -V, --version output version information\n"
3104" -n, --numeric don't resolve service names\n"
3105" -r, --resolve resolve host names\n"
3106" -a, --all display all sockets\n"
3107" -l, --listening display listening sockets\n"
3108" -o, --options show timer information\n"
3109" -e, --extended show detailed socket information\n"
3110" -m, --memory show socket memory usage\n"
3111" -p, --processes show process using socket\n"
3112" -i, --info show internal TCP information\n"
3113" -s, --summary show socket usage summary\n"
b0f01cf6 3114" -b, --bpf show bpf filter socket information\n"
116ac927
RH
3115" -Z, --context display process SELinux security contexts\n"
3116" -z, --contexts display process and socket SELinux security contexts\n"
ab61159a
SH
3117"\n"
3118" -4, --ipv4 display only IP version 4 sockets\n"
3119" -6, --ipv6 display only IP version 6 sockets\n"
3120" -0, --packet display PACKET sockets\n"
3121" -t, --tcp display only TCP sockets\n"
3122" -u, --udp display only UDP sockets\n"
351efcde 3123" -d, --dccp display only DCCP sockets\n"
ab61159a
SH
3124" -w, --raw display only RAW sockets\n"
3125" -x, --unix display only Unix domain sockets\n"
3126" -f, --family=FAMILY display sockets of type FAMILY\n"
3127"\n"
583de149 3128" -A, --query=QUERY, --socket=QUERY\n"
56dee73e 3129" QUERY := {all|inet|tcp|udp|raw|unix|unix_dgram|unix_stream|unix_seqpacket|packet|netlink}[,QUERY]\n"
ab61159a 3130"\n"
583de149 3131" -D, --diag=FILE Dump raw information about TCP sockets to FILE\n"
ab61159a 3132" -F, --filter=FILE read filter information from FILE\n"
aba5acdf 3133" FILTER := [ state TCP-STATE ] [ EXPRESSION ]\n"
ab61159a 3134 );
7a96e199
AH
3135}
3136
3137static void help(void) __attribute__((noreturn));
3138static void help(void)
3139{
3140 _usage(stdout);
3141 exit(0);
3142}
3143
3144static void usage(void) __attribute__((noreturn));
3145static void usage(void)
3146{
3147 _usage(stderr);
aba5acdf
SH
3148 exit(-1);
3149}
3150
3151
d1f28cf1 3152static int scan_state(const char *state)
aba5acdf
SH
3153{
3154 int i;
3155 if (strcasecmp(state, "close") == 0 ||
3156 strcasecmp(state, "closed") == 0)
3157 return (1<<SS_CLOSE);
3158 if (strcasecmp(state, "syn-rcv") == 0)
3159 return (1<<SS_SYN_RECV);
1a5bad5a 3160 if (strcasecmp(state, "established") == 0)
aba5acdf
SH
3161 return (1<<SS_ESTABLISHED);
3162 if (strcasecmp(state, "all") == 0)
3163 return SS_ALL;
3164 if (strcasecmp(state, "connected") == 0)
3165 return SS_ALL & ~((1<<SS_CLOSE)|(1<<SS_LISTEN));
1a5bad5a 3166 if (strcasecmp(state, "synchronized") == 0)
aba5acdf
SH
3167 return SS_ALL & ~((1<<SS_CLOSE)|(1<<SS_LISTEN)|(1<<SS_SYN_SENT));
3168 if (strcasecmp(state, "bucket") == 0)
3169 return (1<<SS_SYN_RECV)|(1<<SS_TIME_WAIT);
3170 if (strcasecmp(state, "big") == 0)
3171 return SS_ALL & ~((1<<SS_SYN_RECV)|(1<<SS_TIME_WAIT));
3172 for (i=0; i<SS_MAX; i++) {
1a5bad5a 3173 if (strcasecmp(state, sstate_namel[i]) == 0)
aba5acdf
SH
3174 return (1<<i);
3175 }
3176 return 0;
3177}
3178
ab61159a
SH
3179static const struct option long_opts[] = {
3180 { "numeric", 0, 0, 'n' },
3181 { "resolve", 0, 0, 'r' },
3182 { "options", 0, 0, 'o' },
3183 { "extended", 0, 0, 'e' },
3184 { "memory", 0, 0, 'm' },
3185 { "info", 0, 0, 'i' },
3186 { "processes", 0, 0, 'p' },
372c30d2 3187 { "bpf", 0, 0, 'b' },
351efcde 3188 { "dccp", 0, 0, 'd' },
ab61159a
SH
3189 { "tcp", 0, 0, 't' },
3190 { "udp", 0, 0, 'u' },
3191 { "raw", 0, 0, 'w' },
3192 { "unix", 0, 0, 'x' },
3193 { "all", 0, 0, 'a' },
3194 { "listening", 0, 0, 'l' },
3195 { "ipv4", 0, 0, '4' },
3196 { "ipv6", 0, 0, '6' },
3197 { "packet", 0, 0, '0' },
3198 { "family", 1, 0, 'f' },
3199 { "socket", 1, 0, 'A' },
583de149 3200 { "query", 1, 0, 'A' },
c3f346b0 3201 { "summary", 0, 0, 's' },
583de149 3202 { "diag", 1, 0, 'D' },
ab61159a
SH
3203 { "filter", 1, 0, 'F' },
3204 { "version", 0, 0, 'V' },
3205 { "help", 0, 0, 'h' },
116ac927
RH
3206 { "context", 0, 0, 'Z' },
3207 { "contexts", 0, 0, 'z' },
ab61159a 3208 { 0 }
ae665a52 3209
ab61159a
SH
3210};
3211
aba5acdf
SH
3212int main(int argc, char *argv[])
3213{
3214 int do_default = 1;
3215 int saw_states = 0;
3216 int saw_query = 0;
3217 int do_summary = 0;
7d105b56 3218 const char *dump_tcpdiag = NULL;
aba5acdf
SH
3219 FILE *filter_fp = NULL;
3220 int ch;
3221
3222 memset(&current_filter, 0, sizeof(current_filter));
3223
3224 current_filter.states = default_filter.states;
3225
116ac927 3226 while ((ch = getopt_long(argc, argv, "dhaletuwxnro460spbf:miA:D:F:vVzZ",
ab61159a 3227 long_opts, NULL)) != EOF) {
aba5acdf
SH
3228 switch(ch) {
3229 case 'n':
3230 resolve_services = 0;
3231 break;
3232 case 'r':
3233 resolve_hosts = 1;
3234 break;
3235 case 'o':
3236 show_options = 1;
3237 break;
3238 case 'e':
3239 show_options = 1;
3240 show_details++;
3241 break;
3242 case 'm':
3243 show_mem = 1;
3244 break;
3245 case 'i':
3246 show_tcpinfo = 1;
3247 break;
3248 case 'p':
3249 show_users++;
fbc0f876 3250 user_ent_hash_build();
aba5acdf 3251 break;
372c30d2
ND
3252 case 'b':
3253 show_options = 1;
3254 show_bpf++;
3255 break;
351efcde
SH
3256 case 'd':
3257 current_filter.dbs |= (1<<DCCP_DB);
3258 do_default = 0;
3259 break;
aba5acdf
SH
3260 case 't':
3261 current_filter.dbs |= (1<<TCP_DB);
3262 do_default = 0;
3263 break;
3264 case 'u':
3265 current_filter.dbs |= (1<<UDP_DB);
3266 do_default = 0;
3267 break;
3268 case 'w':
3269 current_filter.dbs |= (1<<RAW_DB);
3270 do_default = 0;
3271 break;
3272 case 'x':
3273 current_filter.dbs |= UNIX_DBM;
3274 do_default = 0;
3275 break;
3276 case 'a':
3277 current_filter.states = SS_ALL;
3278 break;
3279 case 'l':
16963ce6 3280 current_filter.states = (1<<SS_LISTEN) | (1<<SS_CLOSE);
aba5acdf
SH
3281 break;
3282 case '4':
3283 preferred_family = AF_INET;
3284 break;
3285 case '6':
3286 preferred_family = AF_INET6;
3287 break;
3288 case '0':
3289 preferred_family = AF_PACKET;
3290 break;
3291 case 'f':
3292 if (strcmp(optarg, "inet") == 0)
3293 preferred_family = AF_INET;
3294 else if (strcmp(optarg, "inet6") == 0)
3295 preferred_family = AF_INET6;
3296 else if (strcmp(optarg, "link") == 0)
3297 preferred_family = AF_PACKET;
3298 else if (strcmp(optarg, "unix") == 0)
3299 preferred_family = AF_UNIX;
3300 else if (strcmp(optarg, "netlink") == 0)
3301 preferred_family = AF_NETLINK;
3302 else if (strcmp(optarg, "help") == 0)
7a96e199 3303 help();
aba5acdf
SH
3304 else {
3305 fprintf(stderr, "ss: \"%s\" is invalid family\n", optarg);
3306 usage();
3307 }
3308 break;
3309 case 'A':
3310 {
3311 char *p, *p1;
3312 if (!saw_query) {
3313 current_filter.dbs = 0;
3314 saw_query = 1;
3315 do_default = 0;
3316 }
3317 p = p1 = optarg;
3318 do {
3319 if ((p1 = strchr(p, ',')) != NULL)
ae665a52 3320 *p1 = 0;
aba5acdf
SH
3321 if (strcmp(p, "all") == 0) {
3322 current_filter.dbs = ALL_DB;
3323 } else if (strcmp(p, "inet") == 0) {
351efcde 3324 current_filter.dbs |= (1<<TCP_DB)|(1<<DCCP_DB)|(1<<UDP_DB)|(1<<RAW_DB);
aba5acdf
SH
3325 } else if (strcmp(p, "udp") == 0) {
3326 current_filter.dbs |= (1<<UDP_DB);
351efcde
SH
3327 } else if (strcmp(p, "dccp") == 0) {
3328 current_filter.dbs |= (1<<DCCP_DB);
aba5acdf
SH
3329 } else if (strcmp(p, "tcp") == 0) {
3330 current_filter.dbs |= (1<<TCP_DB);
3331 } else if (strcmp(p, "raw") == 0) {
3332 current_filter.dbs |= (1<<RAW_DB);
3333 } else if (strcmp(p, "unix") == 0) {
3334 current_filter.dbs |= UNIX_DBM;
1a5bad5a 3335 } else if (strcasecmp(p, "unix_stream") == 0 ||
aba5acdf
SH
3336 strcmp(p, "u_str") == 0) {
3337 current_filter.dbs |= (1<<UNIX_ST_DB);
1a5bad5a 3338 } else if (strcasecmp(p, "unix_dgram") == 0 ||
aba5acdf
SH
3339 strcmp(p, "u_dgr") == 0) {
3340 current_filter.dbs |= (1<<UNIX_DG_DB);
30b669d7
MY
3341 } else if (strcasecmp(p, "unix_seqpacket") == 0 ||
3342 strcmp(p, "u_seq") == 0) {
3343 current_filter.dbs |= (1<<UNIX_SQ_DB);
aba5acdf
SH
3344 } else if (strcmp(p, "packet") == 0) {
3345 current_filter.dbs |= PACKET_DBM;
3346 } else if (strcmp(p, "packet_raw") == 0 ||
3347 strcmp(p, "p_raw") == 0) {
3348 current_filter.dbs |= (1<<PACKET_R_DB);
3349 } else if (strcmp(p, "packet_dgram") == 0 ||
3350 strcmp(p, "p_dgr") == 0) {
3351 current_filter.dbs |= (1<<PACKET_DG_DB);
3352 } else if (strcmp(p, "netlink") == 0) {
3353 current_filter.dbs |= (1<<NETLINK_DB);
3354 } else {
3355 fprintf(stderr, "ss: \"%s\" is illegal socket table id\n", p);
3356 usage();
3357 }
3358 p = p1 + 1;
3359 } while (p1);
3360 break;
3361 }
3362 case 's':
3363 do_summary = 1;
3364 break;
3365 case 'D':
3366 dump_tcpdiag = optarg;
3367 break;
3368 case 'F':
3369 if (filter_fp) {
3370 fprintf(stderr, "More than one filter file\n");
3371 exit(-1);
3372 }
3373 if (optarg[0] == '-')
3374 filter_fp = stdin;
3375 else
3376 filter_fp = fopen(optarg, "r");
3377 if (!filter_fp) {
3378 perror("fopen filter file");
3379 exit(-1);
3380 }
3381 break;
3382 case 'v':
3383 case 'V':
3384 printf("ss utility, iproute2-ss%s\n", SNAPSHOT);
3385 exit(0);
116ac927
RH
3386 case 'z':
3387 show_sock_ctx++;
3388 case 'Z':
3389 if (is_selinux_enabled() <= 0) {
3390 fprintf(stderr, "ss: SELinux is not enabled.\n");
3391 exit(1);
3392 }
3393 show_proc_ctx++;
3394 user_ent_hash_build();
3395 break;
aba5acdf
SH
3396 case 'h':
3397 case '?':
7a96e199 3398 help();
aba5acdf
SH
3399 default:
3400 usage();
3401 }
3402 }
3403
3404 argc -= optind;
3405 argv += optind;
3406
3407 get_slabstat(&slabstat);
3408
3409 if (do_summary) {
3410 print_summary();
3411 if (do_default && argc == 0)
3412 exit(0);
3413 }
3414
3415 if (do_default)
3416 current_filter.dbs = default_filter.dbs;
3417
3418 if (preferred_family == AF_UNSPEC) {
3419 if (!(current_filter.dbs&~UNIX_DBM))
3420 preferred_family = AF_UNIX;
3421 else if (!(current_filter.dbs&~PACKET_DBM))
3422 preferred_family = AF_PACKET;
3423 else if (!(current_filter.dbs&~(1<<NETLINK_DB)))
3424 preferred_family = AF_NETLINK;
3425 }
3426
3427 if (preferred_family != AF_UNSPEC) {
3428 int mask2;
3429 if (preferred_family == AF_INET ||
3430 preferred_family == AF_INET6) {
f70d96a4 3431 mask2= current_filter.dbs;
aba5acdf
SH
3432 } else if (preferred_family == AF_PACKET) {
3433 mask2 = PACKET_DBM;
3434 } else if (preferred_family == AF_UNIX) {
3435 mask2 = UNIX_DBM;
3436 } else if (preferred_family == AF_NETLINK) {
3437 mask2 = (1<<NETLINK_DB);
3438 } else {
3439 mask2 = 0;
3440 }
3441
3442 if (do_default)
3443 current_filter.dbs = mask2;
3444 else
3445 current_filter.dbs &= mask2;
3446 current_filter.families = (1<<preferred_family);
3447 } else {
3448 if (!do_default)
3449 current_filter.families = ~0;
3450 else
3451 current_filter.families = default_filter.families;
3452 }
3453 if (current_filter.dbs == 0) {
3454 fprintf(stderr, "ss: no socket tables to show with such filter.\n");
3455 exit(0);
3456 }
3457 if (current_filter.families == 0) {
3458 fprintf(stderr, "ss: no families to show with such filter.\n");
3459 exit(0);
3460 }
3461
3462 if (resolve_services && resolve_hosts &&
351efcde 3463 (current_filter.dbs&(UNIX_DBM|(1<<TCP_DB)|(1<<UDP_DB)|(1<<DCCP_DB))))
aba5acdf
SH
3464 init_service_resolver();
3465
3466 /* Now parse filter... */
3467 if (argc == 0 && filter_fp) {
3468 if (ssfilter_parse(&current_filter.f, 0, NULL, filter_fp))
3469 usage();
3470 }
3471
3472 while (argc > 0) {
3473 if (strcmp(*argv, "state") == 0) {
3474 NEXT_ARG();
3475 if (!saw_states)
3476 current_filter.states = 0;
3477 current_filter.states |= scan_state(*argv);
3478 saw_states = 1;
3479 } else if (strcmp(*argv, "exclude") == 0 ||
3480 strcmp(*argv, "excl") == 0) {
3481 NEXT_ARG();
3482 if (!saw_states)
3483 current_filter.states = SS_ALL;
3484 current_filter.states &= ~scan_state(*argv);
3485 saw_states = 1;
3486 } else {
3487 if (ssfilter_parse(&current_filter.f, argc, argv, filter_fp))
3488 usage();
3489 break;
3490 }
3491 argc--; argv++;
3492 }
3493
3494 if (current_filter.states == 0) {
3495 fprintf(stderr, "ss: no socket states to show with such filter.\n");
3496 exit(0);
3497 }
3498
3499 if (dump_tcpdiag) {
3500 FILE *dump_fp = stdout;
3501 if (!(current_filter.dbs & (1<<TCP_DB))) {
3502 fprintf(stderr, "ss: tcpdiag dump requested and no tcp in filter.\n");
3503 exit(0);
3504 }
3505 if (dump_tcpdiag[0] != '-') {
3506 dump_fp = fopen(dump_tcpdiag, "w");
3507 if (!dump_tcpdiag) {
3508 perror("fopen dump file");
3509 exit(-1);
3510 }
3511 }
3fe5b534 3512 inet_show_netlink(&current_filter, dump_fp, IPPROTO_TCP);
aba5acdf
SH
3513 fflush(dump_fp);
3514 exit(0);
3515 }
3516
3517 netid_width = 0;
3518 if (current_filter.dbs&(current_filter.dbs-1))
3519 netid_width = 5;
3520
3521 state_width = 0;
3522 if (current_filter.states&(current_filter.states-1))
3523 state_width = 10;
3524
3525 screen_width = 80;
3526 if (isatty(STDOUT_FILENO)) {
3527 struct winsize w;
3528
3529 if (ioctl(STDOUT_FILENO, TIOCGWINSZ, &w) != -1) {
3530 if (w.ws_col > 0)
3531 screen_width = w.ws_col;
3532 }
3533 }
3534
3535 addrp_width = screen_width;
3536 addrp_width -= netid_width+1;
3537 addrp_width -= state_width+1;
3538 addrp_width -= 14;
3539
3540 if (addrp_width&1) {
3541 if (netid_width)
3542 netid_width++;
3543 else if (state_width)
3544 state_width++;
3545 }
3546
3547 addrp_width /= 2;
3548 addrp_width--;
3549
3550 serv_width = resolve_services ? 7 : 5;
3551
3552 if (addrp_width < 15+serv_width+1)
3553 addrp_width = 15+serv_width+1;
3554
ae665a52 3555 addr_width = addrp_width - serv_width - 1;
aba5acdf
SH
3556
3557 if (netid_width)
3558 printf("%-*s ", netid_width, "Netid");
3559 if (state_width)
3560 printf("%-*s ", state_width, "State");
3561 printf("%-6s %-6s ", "Recv-Q", "Send-Q");
3562
d68e00f7 3563 /* Make enough space for the local/remote port field */
3564 addr_width -= 13;
3565 serv_width += 13;
2dc85485 3566
aba5acdf
SH
3567 printf("%*s:%-*s %*s:%-*s\n",
3568 addr_width, "Local Address", serv_width, "Port",
d68e00f7 3569 addr_width, "Peer Address", serv_width, "Port");
aba5acdf 3570
aba5acdf
SH
3571 fflush(stdout);
3572
3573 if (current_filter.dbs & (1<<NETLINK_DB))
3574 netlink_show(&current_filter);
3575 if (current_filter.dbs & PACKET_DBM)
3576 packet_show(&current_filter);
3577 if (current_filter.dbs & UNIX_DBM)
3578 unix_show(&current_filter);
3579 if (current_filter.dbs & (1<<RAW_DB))
3580 raw_show(&current_filter);
3581 if (current_filter.dbs & (1<<UDP_DB))
3582 udp_show(&current_filter);
3583 if (current_filter.dbs & (1<<TCP_DB))
3fe5b534 3584 tcp_show(&current_filter, IPPROTO_TCP);
351efcde 3585 if (current_filter.dbs & (1<<DCCP_DB))
3fe5b534 3586 tcp_show(&current_filter, IPPROTO_DCCP);
116ac927
RH
3587
3588 if (show_users || show_proc_ctx || show_sock_ctx)
3589 user_ent_destroy();
3590
aba5acdf
SH
3591 return 0;
3592}