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