]> git.proxmox.com Git - mirror_iproute2.git/blob - misc/ss.c
netlink route attribute cleanup
[mirror_iproute2.git] / misc / ss.c
1 /*
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>
25 #include <dirent.h>
26 #include <fnmatch.h>
27 #include <getopt.h>
28 #include <stdbool.h>
29 #include <limits.h>
30
31 #include "utils.h"
32 #include "rt_names.h"
33 #include "ll_map.h"
34 #include "libnetlink.h"
35 #include "namespace.h"
36 #include "SNAPSHOT.h"
37
38 #include <linux/tcp.h>
39 #include <linux/sock_diag.h>
40 #include <linux/inet_diag.h>
41 #include <linux/unix_diag.h>
42 #include <linux/netdevice.h> /* for MAX_ADDR_LEN */
43 #include <linux/filter.h>
44 #include <linux/packet_diag.h>
45 #include <linux/netlink_diag.h>
46 #include <linux/sctp.h>
47
48 #define MAGIC_SEQ 123456
49
50 #define DIAG_REQUEST(_req, _r) \
51 struct { \
52 struct nlmsghdr nlh; \
53 _r; \
54 } _req = { \
55 .nlh = { \
56 .nlmsg_type = SOCK_DIAG_BY_FAMILY, \
57 .nlmsg_flags = NLM_F_ROOT|NLM_F_MATCH|NLM_F_REQUEST,\
58 .nlmsg_seq = MAGIC_SEQ, \
59 .nlmsg_len = sizeof(_req), \
60 }, \
61 }
62
63 #if HAVE_SELINUX
64 #include <selinux/selinux.h>
65 #else
66 /* Stubs for SELinux functions */
67 static int is_selinux_enabled(void)
68 {
69 return -1;
70 }
71
72 static int getpidcon(pid_t pid, char **context)
73 {
74 *context = NULL;
75 return -1;
76 }
77
78 static int getfilecon(char *path, char **context)
79 {
80 *context = NULL;
81 return -1;
82 }
83
84 static int security_get_initial_context(char *name, char **context)
85 {
86 *context = NULL;
87 return -1;
88 }
89 #endif
90
91 int resolve_hosts;
92 int resolve_services = 1;
93 int preferred_family = AF_UNSPEC;
94 int show_options;
95 int show_details;
96 int show_users;
97 int show_mem;
98 int show_tcpinfo;
99 int show_bpf;
100 int show_proc_ctx;
101 int show_sock_ctx;
102 int show_header = 1;
103 int follow_events;
104 int sctp_ino;
105
106 int netid_width;
107 int state_width;
108 int addr_width;
109 int serv_width;
110
111 static const char *TCP_PROTO = "tcp";
112 static const char *SCTP_PROTO = "sctp";
113 static const char *UDP_PROTO = "udp";
114 static const char *RAW_PROTO = "raw";
115 static const char *dg_proto;
116
117 enum {
118 TCP_DB,
119 DCCP_DB,
120 UDP_DB,
121 RAW_DB,
122 UNIX_DG_DB,
123 UNIX_ST_DB,
124 UNIX_SQ_DB,
125 PACKET_DG_DB,
126 PACKET_R_DB,
127 NETLINK_DB,
128 SCTP_DB,
129 MAX_DB
130 };
131
132 #define PACKET_DBM ((1<<PACKET_DG_DB)|(1<<PACKET_R_DB))
133 #define UNIX_DBM ((1<<UNIX_DG_DB)|(1<<UNIX_ST_DB)|(1<<UNIX_SQ_DB))
134 #define ALL_DB ((1<<MAX_DB)-1)
135 #define INET_L4_DBM ((1<<TCP_DB)|(1<<UDP_DB)|(1<<DCCP_DB)|(1<<SCTP_DB))
136 #define INET_DBM (INET_L4_DBM | (1<<RAW_DB))
137
138 enum {
139 SS_UNKNOWN,
140 SS_ESTABLISHED,
141 SS_SYN_SENT,
142 SS_SYN_RECV,
143 SS_FIN_WAIT1,
144 SS_FIN_WAIT2,
145 SS_TIME_WAIT,
146 SS_CLOSE,
147 SS_CLOSE_WAIT,
148 SS_LAST_ACK,
149 SS_LISTEN,
150 SS_CLOSING,
151 SS_MAX
152 };
153
154 enum {
155 SCTP_STATE_CLOSED = 0,
156 SCTP_STATE_COOKIE_WAIT = 1,
157 SCTP_STATE_COOKIE_ECHOED = 2,
158 SCTP_STATE_ESTABLISHED = 3,
159 SCTP_STATE_SHUTDOWN_PENDING = 4,
160 SCTP_STATE_SHUTDOWN_SENT = 5,
161 SCTP_STATE_SHUTDOWN_RECEIVED = 6,
162 SCTP_STATE_SHUTDOWN_ACK_SENT = 7,
163 };
164
165 #define SS_ALL ((1 << SS_MAX) - 1)
166 #define SS_CONN (SS_ALL & ~((1<<SS_LISTEN)|(1<<SS_CLOSE)|(1<<SS_TIME_WAIT)|(1<<SS_SYN_RECV)))
167
168 #include "ssfilter.h"
169
170 struct filter {
171 int dbs;
172 int states;
173 int families;
174 struct ssfilter *f;
175 bool kill;
176 };
177
178 static const struct filter default_dbs[MAX_DB] = {
179 [TCP_DB] = {
180 .states = SS_CONN,
181 .families = (1 << AF_INET) | (1 << AF_INET6),
182 },
183 [DCCP_DB] = {
184 .states = SS_CONN,
185 .families = (1 << AF_INET) | (1 << AF_INET6),
186 },
187 [UDP_DB] = {
188 .states = (1 << SS_ESTABLISHED),
189 .families = (1 << AF_INET) | (1 << AF_INET6),
190 },
191 [RAW_DB] = {
192 .states = (1 << SS_ESTABLISHED),
193 .families = (1 << AF_INET) | (1 << AF_INET6),
194 },
195 [UNIX_DG_DB] = {
196 .states = (1 << SS_CLOSE),
197 .families = (1 << AF_UNIX),
198 },
199 [UNIX_ST_DB] = {
200 .states = SS_CONN,
201 .families = (1 << AF_UNIX),
202 },
203 [UNIX_SQ_DB] = {
204 .states = SS_CONN,
205 .families = (1 << AF_UNIX),
206 },
207 [PACKET_DG_DB] = {
208 .states = (1 << SS_CLOSE),
209 .families = (1 << AF_PACKET),
210 },
211 [PACKET_R_DB] = {
212 .states = (1 << SS_CLOSE),
213 .families = (1 << AF_PACKET),
214 },
215 [NETLINK_DB] = {
216 .states = (1 << SS_CLOSE),
217 .families = (1 << AF_NETLINK),
218 },
219 [SCTP_DB] = {
220 .states = SS_CONN,
221 .families = (1 << AF_INET) | (1 << AF_INET6),
222 },
223 };
224
225 static const struct filter default_afs[AF_MAX] = {
226 [AF_INET] = {
227 .dbs = INET_DBM,
228 .states = SS_CONN,
229 },
230 [AF_INET6] = {
231 .dbs = INET_DBM,
232 .states = SS_CONN,
233 },
234 [AF_UNIX] = {
235 .dbs = UNIX_DBM,
236 .states = SS_CONN,
237 },
238 [AF_PACKET] = {
239 .dbs = PACKET_DBM,
240 .states = (1 << SS_CLOSE),
241 },
242 [AF_NETLINK] = {
243 .dbs = (1 << NETLINK_DB),
244 .states = (1 << SS_CLOSE),
245 },
246 };
247
248 static int do_default = 1;
249 static struct filter current_filter;
250
251 static void filter_db_set(struct filter *f, int db)
252 {
253 f->states |= default_dbs[db].states;
254 f->dbs |= 1 << db;
255 do_default = 0;
256 }
257
258 static void filter_af_set(struct filter *f, int af)
259 {
260 f->states |= default_afs[af].states;
261 f->families |= 1 << af;
262 do_default = 0;
263 preferred_family = af;
264 }
265
266 static int filter_af_get(struct filter *f, int af)
267 {
268 return f->families & (1 << af);
269 }
270
271 static void filter_default_dbs(struct filter *f)
272 {
273 filter_db_set(f, UDP_DB);
274 filter_db_set(f, DCCP_DB);
275 filter_db_set(f, TCP_DB);
276 filter_db_set(f, RAW_DB);
277 filter_db_set(f, UNIX_ST_DB);
278 filter_db_set(f, UNIX_DG_DB);
279 filter_db_set(f, UNIX_SQ_DB);
280 filter_db_set(f, PACKET_R_DB);
281 filter_db_set(f, PACKET_DG_DB);
282 filter_db_set(f, NETLINK_DB);
283 filter_db_set(f, SCTP_DB);
284 }
285
286 static void filter_states_set(struct filter *f, int states)
287 {
288 if (states)
289 f->states = states;
290 }
291
292 static void filter_merge_defaults(struct filter *f)
293 {
294 int db;
295 int af;
296
297 for (db = 0; db < MAX_DB; db++) {
298 if (!(f->dbs & (1 << db)))
299 continue;
300
301 if (!(default_dbs[db].families & f->families))
302 f->families |= default_dbs[db].families;
303 }
304 for (af = 0; af < AF_MAX; af++) {
305 if (!(f->families & (1 << af)))
306 continue;
307
308 if (!(default_afs[af].dbs & f->dbs))
309 f->dbs |= default_afs[af].dbs;
310 }
311 }
312
313 static FILE *generic_proc_open(const char *env, const char *name)
314 {
315 const char *p = getenv(env);
316 char store[128];
317
318 if (!p) {
319 p = getenv("PROC_ROOT") ? : "/proc";
320 snprintf(store, sizeof(store)-1, "%s/%s", p, name);
321 p = store;
322 }
323
324 return fopen(p, "r");
325 }
326 #define net_tcp_open() generic_proc_open("PROC_NET_TCP", "net/tcp")
327 #define net_tcp6_open() generic_proc_open("PROC_NET_TCP6", "net/tcp6")
328 #define net_udp_open() generic_proc_open("PROC_NET_UDP", "net/udp")
329 #define net_udp6_open() generic_proc_open("PROC_NET_UDP6", "net/udp6")
330 #define net_raw_open() generic_proc_open("PROC_NET_RAW", "net/raw")
331 #define net_raw6_open() generic_proc_open("PROC_NET_RAW6", "net/raw6")
332 #define net_unix_open() generic_proc_open("PROC_NET_UNIX", "net/unix")
333 #define net_packet_open() generic_proc_open("PROC_NET_PACKET", \
334 "net/packet")
335 #define net_netlink_open() generic_proc_open("PROC_NET_NETLINK", \
336 "net/netlink")
337 #define slabinfo_open() generic_proc_open("PROC_SLABINFO", "slabinfo")
338 #define net_sockstat_open() generic_proc_open("PROC_NET_SOCKSTAT", \
339 "net/sockstat")
340 #define net_sockstat6_open() generic_proc_open("PROC_NET_SOCKSTAT6", \
341 "net/sockstat6")
342 #define net_snmp_open() generic_proc_open("PROC_NET_SNMP", "net/snmp")
343 #define ephemeral_ports_open() generic_proc_open("PROC_IP_LOCAL_PORT_RANGE", \
344 "sys/net/ipv4/ip_local_port_range")
345
346 struct user_ent {
347 struct user_ent *next;
348 unsigned int ino;
349 int pid;
350 int fd;
351 char *process;
352 char *process_ctx;
353 char *socket_ctx;
354 };
355
356 #define USER_ENT_HASH_SIZE 256
357 struct user_ent *user_ent_hash[USER_ENT_HASH_SIZE];
358
359 static int user_ent_hashfn(unsigned int ino)
360 {
361 int val = (ino >> 24) ^ (ino >> 16) ^ (ino >> 8) ^ ino;
362
363 return val & (USER_ENT_HASH_SIZE - 1);
364 }
365
366 static void user_ent_add(unsigned int ino, char *process,
367 int pid, int fd,
368 char *proc_ctx,
369 char *sock_ctx)
370 {
371 struct user_ent *p, **pp;
372
373 p = malloc(sizeof(struct user_ent));
374 if (!p) {
375 fprintf(stderr, "ss: failed to malloc buffer\n");
376 abort();
377 }
378 p->next = NULL;
379 p->ino = ino;
380 p->pid = pid;
381 p->fd = fd;
382 p->process = strdup(process);
383 p->process_ctx = strdup(proc_ctx);
384 p->socket_ctx = strdup(sock_ctx);
385
386 pp = &user_ent_hash[user_ent_hashfn(ino)];
387 p->next = *pp;
388 *pp = p;
389 }
390
391 static void user_ent_destroy(void)
392 {
393 struct user_ent *p, *p_next;
394 int cnt = 0;
395
396 while (cnt != USER_ENT_HASH_SIZE) {
397 p = user_ent_hash[cnt];
398 while (p) {
399 free(p->process);
400 free(p->process_ctx);
401 free(p->socket_ctx);
402 p_next = p->next;
403 free(p);
404 p = p_next;
405 }
406 cnt++;
407 }
408 }
409
410 static void user_ent_hash_build(void)
411 {
412 const char *root = getenv("PROC_ROOT") ? : "/proc/";
413 struct dirent *d;
414 char name[1024];
415 int nameoff;
416 DIR *dir;
417 char *pid_context;
418 char *sock_context;
419 const char *no_ctx = "unavailable";
420 static int user_ent_hash_build_init;
421
422 /* If show_users & show_proc_ctx set only do this once */
423 if (user_ent_hash_build_init != 0)
424 return;
425
426 user_ent_hash_build_init = 1;
427
428 strncpy(name, root, sizeof(name)-1);
429 name[sizeof(name)-1] = 0;
430
431 if (strlen(name) == 0 || name[strlen(name)-1] != '/')
432 strcat(name, "/");
433
434 nameoff = strlen(name);
435
436 dir = opendir(name);
437 if (!dir)
438 return;
439
440 while ((d = readdir(dir)) != NULL) {
441 struct dirent *d1;
442 char process[16];
443 char *p;
444 int pid, pos;
445 DIR *dir1;
446 char crap;
447
448 if (sscanf(d->d_name, "%d%c", &pid, &crap) != 1)
449 continue;
450
451 if (getpidcon(pid, &pid_context) != 0)
452 pid_context = strdup(no_ctx);
453
454 snprintf(name + nameoff, sizeof(name) - nameoff, "%d/fd/", pid);
455 pos = strlen(name);
456 if ((dir1 = opendir(name)) == NULL) {
457 free(pid_context);
458 continue;
459 }
460
461 process[0] = '\0';
462 p = process;
463
464 while ((d1 = readdir(dir1)) != NULL) {
465 const char *pattern = "socket:[";
466 unsigned int ino;
467 char lnk[64];
468 int fd;
469 ssize_t link_len;
470 char tmp[1024];
471
472 if (sscanf(d1->d_name, "%d%c", &fd, &crap) != 1)
473 continue;
474
475 snprintf(name+pos, sizeof(name) - pos, "%d", fd);
476
477 link_len = readlink(name, lnk, sizeof(lnk)-1);
478 if (link_len == -1)
479 continue;
480 lnk[link_len] = '\0';
481
482 if (strncmp(lnk, pattern, strlen(pattern)))
483 continue;
484
485 sscanf(lnk, "socket:[%u]", &ino);
486
487 snprintf(tmp, sizeof(tmp), "%s/%d/fd/%s",
488 root, pid, d1->d_name);
489
490 if (getfilecon(tmp, &sock_context) <= 0)
491 sock_context = strdup(no_ctx);
492
493 if (*p == '\0') {
494 FILE *fp;
495
496 snprintf(tmp, sizeof(tmp), "%s/%d/stat",
497 root, pid);
498 if ((fp = fopen(tmp, "r")) != NULL) {
499 if (fscanf(fp, "%*d (%[^)])", p) < 1)
500 ; /* ignore */
501 fclose(fp);
502 }
503 }
504 user_ent_add(ino, p, pid, fd,
505 pid_context, sock_context);
506 free(sock_context);
507 }
508 free(pid_context);
509 closedir(dir1);
510 }
511 closedir(dir);
512 }
513
514 enum entry_types {
515 USERS,
516 PROC_CTX,
517 PROC_SOCK_CTX
518 };
519
520 #define ENTRY_BUF_SIZE 512
521 static int find_entry(unsigned int ino, char **buf, int type)
522 {
523 struct user_ent *p;
524 int cnt = 0;
525 char *ptr;
526 char *new_buf;
527 int len, new_buf_len;
528 int buf_used = 0;
529 int buf_len = 0;
530
531 if (!ino)
532 return 0;
533
534 p = user_ent_hash[user_ent_hashfn(ino)];
535 ptr = *buf = NULL;
536 while (p) {
537 if (p->ino != ino)
538 goto next;
539
540 while (1) {
541 ptr = *buf + buf_used;
542 switch (type) {
543 case USERS:
544 len = snprintf(ptr, buf_len - buf_used,
545 "(\"%s\",pid=%d,fd=%d),",
546 p->process, p->pid, p->fd);
547 break;
548 case PROC_CTX:
549 len = snprintf(ptr, buf_len - buf_used,
550 "(\"%s\",pid=%d,proc_ctx=%s,fd=%d),",
551 p->process, p->pid,
552 p->process_ctx, p->fd);
553 break;
554 case PROC_SOCK_CTX:
555 len = snprintf(ptr, buf_len - buf_used,
556 "(\"%s\",pid=%d,proc_ctx=%s,fd=%d,sock_ctx=%s),",
557 p->process, p->pid,
558 p->process_ctx, p->fd,
559 p->socket_ctx);
560 break;
561 default:
562 fprintf(stderr, "ss: invalid type: %d\n", type);
563 abort();
564 }
565
566 if (len < 0 || len >= buf_len - buf_used) {
567 new_buf_len = buf_len + ENTRY_BUF_SIZE;
568 new_buf = realloc(*buf, new_buf_len);
569 if (!new_buf) {
570 fprintf(stderr, "ss: failed to malloc buffer\n");
571 abort();
572 }
573 *buf = new_buf;
574 buf_len = new_buf_len;
575 continue;
576 } else {
577 buf_used += len;
578 break;
579 }
580 }
581 cnt++;
582 next:
583 p = p->next;
584 }
585 if (buf_used) {
586 ptr = *buf + buf_used;
587 ptr[-1] = '\0';
588 }
589 return cnt;
590 }
591
592 /* Get stats from slab */
593
594 struct slabstat {
595 int socks;
596 int tcp_ports;
597 int tcp_tws;
598 int tcp_syns;
599 int skbs;
600 };
601
602 static struct slabstat slabstat;
603
604 static int get_slabstat(struct slabstat *s)
605 {
606 char buf[256];
607 FILE *fp;
608 int cnt;
609 static int slabstat_valid;
610 static const char * const slabstat_ids[] = {
611 "sock",
612 "tcp_bind_bucket",
613 "tcp_tw_bucket",
614 "tcp_open_request",
615 "skbuff_head_cache",
616 };
617
618 if (slabstat_valid)
619 return 0;
620
621 memset(s, 0, sizeof(*s));
622
623 fp = slabinfo_open();
624 if (!fp)
625 return -1;
626
627 cnt = sizeof(*s)/sizeof(int);
628
629 if (!fgets(buf, sizeof(buf), fp)) {
630 fclose(fp);
631 return -1;
632 }
633 while (fgets(buf, sizeof(buf), fp) != NULL) {
634 int i;
635
636 for (i = 0; i < ARRAY_SIZE(slabstat_ids); i++) {
637 if (memcmp(buf, slabstat_ids[i], strlen(slabstat_ids[i])) == 0) {
638 sscanf(buf, "%*s%d", ((int *)s) + i);
639 cnt--;
640 break;
641 }
642 }
643 if (cnt <= 0)
644 break;
645 }
646
647 slabstat_valid = 1;
648
649 fclose(fp);
650 return 0;
651 }
652
653 static unsigned long long cookie_sk_get(const uint32_t *cookie)
654 {
655 return (((unsigned long long)cookie[1] << 31) << 1) | cookie[0];
656 }
657
658 static const char *sctp_sstate_name[] = {
659 [SCTP_STATE_CLOSED] = "CLOSED",
660 [SCTP_STATE_COOKIE_WAIT] = "COOKIE_WAIT",
661 [SCTP_STATE_COOKIE_ECHOED] = "COOKIE_ECHOED",
662 [SCTP_STATE_ESTABLISHED] = "ESTAB",
663 [SCTP_STATE_SHUTDOWN_PENDING] = "SHUTDOWN_PENDING",
664 [SCTP_STATE_SHUTDOWN_SENT] = "SHUTDOWN_SENT",
665 [SCTP_STATE_SHUTDOWN_RECEIVED] = "SHUTDOWN_RECEIVED",
666 [SCTP_STATE_SHUTDOWN_ACK_SENT] = "ACK_SENT",
667 };
668
669 struct sockstat {
670 struct sockstat *next;
671 unsigned int type;
672 uint16_t prot;
673 uint16_t raw_prot;
674 inet_prefix local;
675 inet_prefix remote;
676 int lport;
677 int rport;
678 int state;
679 int rq, wq;
680 unsigned int ino;
681 unsigned int uid;
682 int refcnt;
683 unsigned int iface;
684 unsigned long long sk;
685 char *name;
686 char *peer_name;
687 __u32 mark;
688 };
689
690 struct dctcpstat {
691 unsigned int ce_state;
692 unsigned int alpha;
693 unsigned int ab_ecn;
694 unsigned int ab_tot;
695 bool enabled;
696 };
697
698 struct tcpstat {
699 struct sockstat ss;
700 int timer;
701 int timeout;
702 int probes;
703 char cong_alg[16];
704 double rto, ato, rtt, rttvar;
705 int qack, ssthresh, backoff;
706 double send_bps;
707 int snd_wscale;
708 int rcv_wscale;
709 int mss;
710 int rcv_mss;
711 int advmss;
712 unsigned int cwnd;
713 unsigned int lastsnd;
714 unsigned int lastrcv;
715 unsigned int lastack;
716 double pacing_rate;
717 double pacing_rate_max;
718 double delivery_rate;
719 unsigned long long bytes_acked;
720 unsigned long long bytes_received;
721 unsigned int segs_out;
722 unsigned int segs_in;
723 unsigned int data_segs_out;
724 unsigned int data_segs_in;
725 unsigned int unacked;
726 unsigned int retrans;
727 unsigned int retrans_total;
728 unsigned int lost;
729 unsigned int sacked;
730 unsigned int fackets;
731 unsigned int reordering;
732 unsigned int not_sent;
733 double rcv_rtt;
734 double min_rtt;
735 int rcv_space;
736 unsigned long long busy_time;
737 unsigned long long rwnd_limited;
738 unsigned long long sndbuf_limited;
739 bool has_ts_opt;
740 bool has_sack_opt;
741 bool has_ecn_opt;
742 bool has_ecnseen_opt;
743 bool has_fastopen_opt;
744 bool has_wscale_opt;
745 bool app_limited;
746 struct dctcpstat *dctcp;
747 struct tcp_bbr_info *bbr_info;
748 };
749
750 /* SCTP assocs share the same inode number with their parent endpoint. So if we
751 * have seen the inode number before, it must be an assoc instead of the next
752 * endpoint. */
753 static bool is_sctp_assoc(struct sockstat *s, const char *sock_name)
754 {
755 if (strcmp(sock_name, "sctp"))
756 return false;
757 if (!sctp_ino || sctp_ino != s->ino)
758 return false;
759 return true;
760 }
761
762 static const char *unix_netid_name(int type)
763 {
764 switch (type) {
765 case SOCK_STREAM:
766 return "u_str";
767 case SOCK_SEQPACKET:
768 return "u_seq";
769 case SOCK_DGRAM:
770 default:
771 return "u_dgr";
772 }
773 }
774
775 static const char *proto_name(int protocol)
776 {
777 switch (protocol) {
778 case 0:
779 return "raw";
780 case IPPROTO_UDP:
781 return "udp";
782 case IPPROTO_TCP:
783 return "tcp";
784 case IPPROTO_SCTP:
785 return "sctp";
786 case IPPROTO_DCCP:
787 return "dccp";
788 }
789
790 return "???";
791 }
792
793 static void sock_state_print(struct sockstat *s)
794 {
795 const char *sock_name;
796 static const char * const sstate_name[] = {
797 "UNKNOWN",
798 [SS_ESTABLISHED] = "ESTAB",
799 [SS_SYN_SENT] = "SYN-SENT",
800 [SS_SYN_RECV] = "SYN-RECV",
801 [SS_FIN_WAIT1] = "FIN-WAIT-1",
802 [SS_FIN_WAIT2] = "FIN-WAIT-2",
803 [SS_TIME_WAIT] = "TIME-WAIT",
804 [SS_CLOSE] = "UNCONN",
805 [SS_CLOSE_WAIT] = "CLOSE-WAIT",
806 [SS_LAST_ACK] = "LAST-ACK",
807 [SS_LISTEN] = "LISTEN",
808 [SS_CLOSING] = "CLOSING",
809 };
810
811 switch (s->local.family) {
812 case AF_UNIX:
813 sock_name = unix_netid_name(s->type);
814 break;
815 case AF_INET:
816 case AF_INET6:
817 sock_name = proto_name(s->type);
818 break;
819 case AF_PACKET:
820 sock_name = s->type == SOCK_RAW ? "p_raw" : "p_dgr";
821 break;
822 case AF_NETLINK:
823 sock_name = "nl";
824 break;
825 default:
826 sock_name = "unknown";
827 }
828
829 if (netid_width)
830 printf("%-*s ", netid_width,
831 is_sctp_assoc(s, sock_name) ? "" : sock_name);
832 if (state_width) {
833 if (is_sctp_assoc(s, sock_name))
834 printf("`- %-*s ", state_width - 3,
835 sctp_sstate_name[s->state]);
836 else
837 printf("%-*s ", state_width, sstate_name[s->state]);
838 }
839
840 printf("%-6d %-6d ", s->rq, s->wq);
841 }
842
843 static void sock_details_print(struct sockstat *s)
844 {
845 if (s->uid)
846 printf(" uid:%u", s->uid);
847
848 printf(" ino:%u", s->ino);
849 printf(" sk:%llx", s->sk);
850
851 if (s->mark)
852 printf(" fwmark:0x%x", s->mark);
853 }
854
855 static void sock_addr_print_width(int addr_len, const char *addr, char *delim,
856 int port_len, const char *port, const char *ifname)
857 {
858 if (ifname) {
859 printf("%*s%%%s%s%-*s ", addr_len, addr, ifname, delim,
860 port_len, port);
861 } else {
862 printf("%*s%s%-*s ", addr_len, addr, delim, port_len, port);
863 }
864 }
865
866 static void sock_addr_print(const char *addr, char *delim, const char *port,
867 const char *ifname)
868 {
869 sock_addr_print_width(addr_width, addr, delim, serv_width, port, ifname);
870 }
871
872 static const char *print_ms_timer(int timeout)
873 {
874 static char buf[64];
875 int secs, msecs, minutes;
876
877 if (timeout < 0)
878 timeout = 0;
879 secs = timeout/1000;
880 minutes = secs/60;
881 secs = secs%60;
882 msecs = timeout%1000;
883 buf[0] = 0;
884 if (minutes) {
885 msecs = 0;
886 snprintf(buf, sizeof(buf)-16, "%dmin", minutes);
887 if (minutes > 9)
888 secs = 0;
889 }
890 if (secs) {
891 if (secs > 9)
892 msecs = 0;
893 sprintf(buf+strlen(buf), "%d%s", secs, msecs ? "." : "sec");
894 }
895 if (msecs)
896 sprintf(buf+strlen(buf), "%03dms", msecs);
897 return buf;
898 }
899
900 struct scache {
901 struct scache *next;
902 int port;
903 char *name;
904 const char *proto;
905 };
906
907 struct scache *rlist;
908
909 static void init_service_resolver(void)
910 {
911 char buf[128];
912 FILE *fp = popen("/usr/sbin/rpcinfo -p 2>/dev/null", "r");
913
914 if (!fp)
915 return;
916
917 if (!fgets(buf, sizeof(buf), fp)) {
918 pclose(fp);
919 return;
920 }
921 while (fgets(buf, sizeof(buf), fp) != NULL) {
922 unsigned int progn, port;
923 char proto[128], prog[128] = "rpc.";
924 struct scache *c;
925
926 if (sscanf(buf, "%u %*d %s %u %s",
927 &progn, proto, &port, prog+4) != 4)
928 continue;
929
930 if (!(c = malloc(sizeof(*c))))
931 continue;
932
933 c->port = port;
934 c->name = strdup(prog);
935 if (strcmp(proto, TCP_PROTO) == 0)
936 c->proto = TCP_PROTO;
937 else if (strcmp(proto, UDP_PROTO) == 0)
938 c->proto = UDP_PROTO;
939 else if (strcmp(proto, SCTP_PROTO) == 0)
940 c->proto = SCTP_PROTO;
941 else
942 c->proto = NULL;
943 c->next = rlist;
944 rlist = c;
945 }
946 pclose(fp);
947 }
948
949 /* Even do not try default linux ephemeral port ranges:
950 * default /etc/services contains so much of useless crap
951 * wouldbe "allocated" to this area that resolution
952 * is really harmful. I shrug each time when seeing
953 * "socks" or "cfinger" in dumps.
954 */
955 static int is_ephemeral(int port)
956 {
957 static int min = 0, max;
958
959 if (!min) {
960 FILE *f = ephemeral_ports_open();
961
962 if (!f || fscanf(f, "%d %d", &min, &max) < 2) {
963 min = 1024;
964 max = 4999;
965 }
966 if (f)
967 fclose(f);
968 }
969 return port >= min && port <= max;
970 }
971
972
973 static const char *__resolve_service(int port)
974 {
975 struct scache *c;
976
977 for (c = rlist; c; c = c->next) {
978 if (c->port == port && c->proto == dg_proto)
979 return c->name;
980 }
981
982 if (!is_ephemeral(port)) {
983 static int notfirst;
984 struct servent *se;
985
986 if (!notfirst) {
987 setservent(1);
988 notfirst = 1;
989 }
990 se = getservbyport(htons(port), dg_proto);
991 if (se)
992 return se->s_name;
993 }
994
995 return NULL;
996 }
997
998 #define SCACHE_BUCKETS 1024
999 static struct scache *cache_htab[SCACHE_BUCKETS];
1000
1001 static const char *resolve_service(int port)
1002 {
1003 static char buf[128];
1004 struct scache *c;
1005 const char *res;
1006 int hash;
1007
1008 if (port == 0) {
1009 buf[0] = '*';
1010 buf[1] = 0;
1011 return buf;
1012 }
1013
1014 if (!resolve_services)
1015 goto do_numeric;
1016
1017 if (dg_proto == RAW_PROTO)
1018 return inet_proto_n2a(port, buf, sizeof(buf));
1019
1020
1021 hash = (port^(((unsigned long)dg_proto)>>2)) % SCACHE_BUCKETS;
1022
1023 for (c = cache_htab[hash]; c; c = c->next) {
1024 if (c->port == port && c->proto == dg_proto)
1025 goto do_cache;
1026 }
1027
1028 c = malloc(sizeof(*c));
1029 if (!c)
1030 goto do_numeric;
1031 res = __resolve_service(port);
1032 c->port = port;
1033 c->name = res ? strdup(res) : NULL;
1034 c->proto = dg_proto;
1035 c->next = cache_htab[hash];
1036 cache_htab[hash] = c;
1037
1038 do_cache:
1039 if (c->name)
1040 return c->name;
1041
1042 do_numeric:
1043 sprintf(buf, "%u", port);
1044 return buf;
1045 }
1046
1047 static void inet_addr_print(const inet_prefix *a, int port, unsigned int ifindex)
1048 {
1049 char buf[1024];
1050 const char *ap = buf;
1051 int est_len = addr_width;
1052 const char *ifname = NULL;
1053
1054 if (a->family == AF_INET) {
1055 if (a->data[0] == 0) {
1056 buf[0] = '*';
1057 buf[1] = 0;
1058 } else {
1059 ap = format_host(AF_INET, 4, a->data);
1060 }
1061 } else {
1062 ap = format_host(a->family, 16, a->data);
1063 est_len = strlen(ap);
1064 if (est_len <= addr_width)
1065 est_len = addr_width;
1066 else
1067 est_len = addr_width + ((est_len-addr_width+3)/4)*4;
1068 }
1069
1070 if (ifindex) {
1071 ifname = ll_index_to_name(ifindex);
1072 est_len -= strlen(ifname) + 1; /* +1 for percent char */
1073 if (est_len < 0)
1074 est_len = 0;
1075 }
1076
1077 sock_addr_print_width(est_len, ap, ":", serv_width, resolve_service(port),
1078 ifname);
1079 }
1080
1081 struct aafilter {
1082 inet_prefix addr;
1083 int port;
1084 unsigned int iface;
1085 __u32 mark;
1086 __u32 mask;
1087 struct aafilter *next;
1088 };
1089
1090 static int inet2_addr_match(const inet_prefix *a, const inet_prefix *p,
1091 int plen)
1092 {
1093 if (!inet_addr_match(a, p, plen))
1094 return 0;
1095
1096 /* Cursed "v4 mapped" addresses: v4 mapped socket matches
1097 * pure IPv4 rule, but v4-mapped rule selects only v4-mapped
1098 * sockets. Fair? */
1099 if (p->family == AF_INET && a->family == AF_INET6) {
1100 if (a->data[0] == 0 && a->data[1] == 0 &&
1101 a->data[2] == htonl(0xffff)) {
1102 inet_prefix tmp = *a;
1103
1104 tmp.data[0] = a->data[3];
1105 return inet_addr_match(&tmp, p, plen);
1106 }
1107 }
1108 return 1;
1109 }
1110
1111 static int unix_match(const inet_prefix *a, const inet_prefix *p)
1112 {
1113 char *addr, *pattern;
1114
1115 memcpy(&addr, a->data, sizeof(addr));
1116 memcpy(&pattern, p->data, sizeof(pattern));
1117 if (pattern == NULL)
1118 return 1;
1119 if (addr == NULL)
1120 addr = "";
1121 return !fnmatch(pattern, addr, 0);
1122 }
1123
1124 static int run_ssfilter(struct ssfilter *f, struct sockstat *s)
1125 {
1126 switch (f->type) {
1127 case SSF_S_AUTO:
1128 {
1129 if (s->local.family == AF_UNIX) {
1130 char *p;
1131
1132 memcpy(&p, s->local.data, sizeof(p));
1133 return p == NULL || (p[0] == '@' && strlen(p) == 6 &&
1134 strspn(p+1, "0123456789abcdef") == 5);
1135 }
1136 if (s->local.family == AF_PACKET)
1137 return s->lport == 0 && s->local.data[0] == 0;
1138 if (s->local.family == AF_NETLINK)
1139 return s->lport < 0;
1140
1141 return is_ephemeral(s->lport);
1142 }
1143 case SSF_DCOND:
1144 {
1145 struct aafilter *a = (void *)f->pred;
1146
1147 if (a->addr.family == AF_UNIX)
1148 return unix_match(&s->remote, &a->addr);
1149 if (a->port != -1 && a->port != s->rport)
1150 return 0;
1151 if (a->addr.bitlen) {
1152 do {
1153 if (!inet2_addr_match(&s->remote, &a->addr, a->addr.bitlen))
1154 return 1;
1155 } while ((a = a->next) != NULL);
1156 return 0;
1157 }
1158 return 1;
1159 }
1160 case SSF_SCOND:
1161 {
1162 struct aafilter *a = (void *)f->pred;
1163
1164 if (a->addr.family == AF_UNIX)
1165 return unix_match(&s->local, &a->addr);
1166 if (a->port != -1 && a->port != s->lport)
1167 return 0;
1168 if (a->addr.bitlen) {
1169 do {
1170 if (!inet2_addr_match(&s->local, &a->addr, a->addr.bitlen))
1171 return 1;
1172 } while ((a = a->next) != NULL);
1173 return 0;
1174 }
1175 return 1;
1176 }
1177 case SSF_D_GE:
1178 {
1179 struct aafilter *a = (void *)f->pred;
1180
1181 return s->rport >= a->port;
1182 }
1183 case SSF_D_LE:
1184 {
1185 struct aafilter *a = (void *)f->pred;
1186
1187 return s->rport <= a->port;
1188 }
1189 case SSF_S_GE:
1190 {
1191 struct aafilter *a = (void *)f->pred;
1192
1193 return s->lport >= a->port;
1194 }
1195 case SSF_S_LE:
1196 {
1197 struct aafilter *a = (void *)f->pred;
1198
1199 return s->lport <= a->port;
1200 }
1201 case SSF_DEVCOND:
1202 {
1203 struct aafilter *a = (void *)f->pred;
1204
1205 return s->iface == a->iface;
1206 }
1207 case SSF_MARKMASK:
1208 {
1209 struct aafilter *a = (void *)f->pred;
1210
1211 return (s->mark & a->mask) == a->mark;
1212 }
1213 /* Yup. It is recursion. Sorry. */
1214 case SSF_AND:
1215 return run_ssfilter(f->pred, s) && run_ssfilter(f->post, s);
1216 case SSF_OR:
1217 return run_ssfilter(f->pred, s) || run_ssfilter(f->post, s);
1218 case SSF_NOT:
1219 return !run_ssfilter(f->pred, s);
1220 default:
1221 abort();
1222 }
1223 }
1224
1225 /* Relocate external jumps by reloc. */
1226 static void ssfilter_patch(char *a, int len, int reloc)
1227 {
1228 while (len > 0) {
1229 struct inet_diag_bc_op *op = (struct inet_diag_bc_op *)a;
1230
1231 if (op->no == len+4)
1232 op->no += reloc;
1233 len -= op->yes;
1234 a += op->yes;
1235 }
1236 if (len < 0)
1237 abort();
1238 }
1239
1240 static int ssfilter_bytecompile(struct ssfilter *f, char **bytecode)
1241 {
1242 switch (f->type) {
1243 case SSF_S_AUTO:
1244 {
1245 if (!(*bytecode = malloc(4))) abort();
1246 ((struct inet_diag_bc_op *)*bytecode)[0] = (struct inet_diag_bc_op){ INET_DIAG_BC_AUTO, 4, 8 };
1247 return 4;
1248 }
1249 case SSF_DCOND:
1250 case SSF_SCOND:
1251 {
1252 struct aafilter *a = (void *)f->pred;
1253 struct aafilter *b;
1254 char *ptr;
1255 int code = (f->type == SSF_DCOND ? INET_DIAG_BC_D_COND : INET_DIAG_BC_S_COND);
1256 int len = 0;
1257
1258 for (b = a; b; b = b->next) {
1259 len += 4 + sizeof(struct inet_diag_hostcond);
1260 if (a->addr.family == AF_INET6)
1261 len += 16;
1262 else
1263 len += 4;
1264 if (b->next)
1265 len += 4;
1266 }
1267 if (!(ptr = malloc(len))) abort();
1268 *bytecode = ptr;
1269 for (b = a; b; b = b->next) {
1270 struct inet_diag_bc_op *op = (struct inet_diag_bc_op *)ptr;
1271 int alen = (a->addr.family == AF_INET6 ? 16 : 4);
1272 int oplen = alen + 4 + sizeof(struct inet_diag_hostcond);
1273 struct inet_diag_hostcond *cond = (struct inet_diag_hostcond *)(ptr+4);
1274
1275 *op = (struct inet_diag_bc_op){ code, oplen, oplen+4 };
1276 cond->family = a->addr.family;
1277 cond->port = a->port;
1278 cond->prefix_len = a->addr.bitlen;
1279 memcpy(cond->addr, a->addr.data, alen);
1280 ptr += oplen;
1281 if (b->next) {
1282 op = (struct inet_diag_bc_op *)ptr;
1283 *op = (struct inet_diag_bc_op){ INET_DIAG_BC_JMP, 4, len - (ptr-*bytecode)};
1284 ptr += 4;
1285 }
1286 }
1287 return ptr - *bytecode;
1288 }
1289 case SSF_D_GE:
1290 {
1291 struct aafilter *x = (void *)f->pred;
1292
1293 if (!(*bytecode = malloc(8))) abort();
1294 ((struct inet_diag_bc_op *)*bytecode)[0] = (struct inet_diag_bc_op){ INET_DIAG_BC_D_GE, 8, 12 };
1295 ((struct inet_diag_bc_op *)*bytecode)[1] = (struct inet_diag_bc_op){ 0, 0, x->port };
1296 return 8;
1297 }
1298 case SSF_D_LE:
1299 {
1300 struct aafilter *x = (void *)f->pred;
1301
1302 if (!(*bytecode = malloc(8))) abort();
1303 ((struct inet_diag_bc_op *)*bytecode)[0] = (struct inet_diag_bc_op){ INET_DIAG_BC_D_LE, 8, 12 };
1304 ((struct inet_diag_bc_op *)*bytecode)[1] = (struct inet_diag_bc_op){ 0, 0, x->port };
1305 return 8;
1306 }
1307 case SSF_S_GE:
1308 {
1309 struct aafilter *x = (void *)f->pred;
1310
1311 if (!(*bytecode = malloc(8))) abort();
1312 ((struct inet_diag_bc_op *)*bytecode)[0] = (struct inet_diag_bc_op){ INET_DIAG_BC_S_GE, 8, 12 };
1313 ((struct inet_diag_bc_op *)*bytecode)[1] = (struct inet_diag_bc_op){ 0, 0, x->port };
1314 return 8;
1315 }
1316 case SSF_S_LE:
1317 {
1318 struct aafilter *x = (void *)f->pred;
1319
1320 if (!(*bytecode = malloc(8))) abort();
1321 ((struct inet_diag_bc_op *)*bytecode)[0] = (struct inet_diag_bc_op){ INET_DIAG_BC_S_LE, 8, 12 };
1322 ((struct inet_diag_bc_op *)*bytecode)[1] = (struct inet_diag_bc_op){ 0, 0, x->port };
1323 return 8;
1324 }
1325
1326 case SSF_AND:
1327 {
1328 char *a1 = NULL, *a2 = NULL, *a;
1329 int l1, l2;
1330
1331 l1 = ssfilter_bytecompile(f->pred, &a1);
1332 l2 = ssfilter_bytecompile(f->post, &a2);
1333 if (!l1 || !l2) {
1334 free(a1);
1335 free(a2);
1336 return 0;
1337 }
1338 if (!(a = malloc(l1+l2))) abort();
1339 memcpy(a, a1, l1);
1340 memcpy(a+l1, a2, l2);
1341 free(a1); free(a2);
1342 ssfilter_patch(a, l1, l2);
1343 *bytecode = a;
1344 return l1+l2;
1345 }
1346 case SSF_OR:
1347 {
1348 char *a1 = NULL, *a2 = NULL, *a;
1349 int l1, l2;
1350
1351 l1 = ssfilter_bytecompile(f->pred, &a1);
1352 l2 = ssfilter_bytecompile(f->post, &a2);
1353 if (!l1 || !l2) {
1354 free(a1);
1355 free(a2);
1356 return 0;
1357 }
1358 if (!(a = malloc(l1+l2+4))) abort();
1359 memcpy(a, a1, l1);
1360 memcpy(a+l1+4, a2, l2);
1361 free(a1); free(a2);
1362 *(struct inet_diag_bc_op *)(a+l1) = (struct inet_diag_bc_op){ INET_DIAG_BC_JMP, 4, l2+4 };
1363 *bytecode = a;
1364 return l1+l2+4;
1365 }
1366 case SSF_NOT:
1367 {
1368 char *a1 = NULL, *a;
1369 int l1;
1370
1371 l1 = ssfilter_bytecompile(f->pred, &a1);
1372 if (!l1) {
1373 free(a1);
1374 return 0;
1375 }
1376 if (!(a = malloc(l1+4))) abort();
1377 memcpy(a, a1, l1);
1378 free(a1);
1379 *(struct inet_diag_bc_op *)(a+l1) = (struct inet_diag_bc_op){ INET_DIAG_BC_JMP, 4, 8 };
1380 *bytecode = a;
1381 return l1+4;
1382 }
1383 case SSF_DEVCOND:
1384 {
1385 /* bytecompile for SSF_DEVCOND not supported yet */
1386 return 0;
1387 }
1388 case SSF_MARKMASK:
1389 {
1390 struct aafilter *a = (void *)f->pred;
1391 struct instr {
1392 struct inet_diag_bc_op op;
1393 struct inet_diag_markcond cond;
1394 };
1395 int inslen = sizeof(struct instr);
1396
1397 if (!(*bytecode = malloc(inslen))) abort();
1398 ((struct instr *)*bytecode)[0] = (struct instr) {
1399 { INET_DIAG_BC_MARK_COND, inslen, inslen + 4 },
1400 { a->mark, a->mask},
1401 };
1402
1403 return inslen;
1404 }
1405 default:
1406 abort();
1407 }
1408 }
1409
1410 static int remember_he(struct aafilter *a, struct hostent *he)
1411 {
1412 char **ptr = he->h_addr_list;
1413 int cnt = 0;
1414 int len;
1415
1416 if (he->h_addrtype == AF_INET)
1417 len = 4;
1418 else if (he->h_addrtype == AF_INET6)
1419 len = 16;
1420 else
1421 return 0;
1422
1423 while (*ptr) {
1424 struct aafilter *b = a;
1425
1426 if (a->addr.bitlen) {
1427 if ((b = malloc(sizeof(*b))) == NULL)
1428 return cnt;
1429 *b = *a;
1430 b->next = a->next;
1431 a->next = b;
1432 }
1433 memcpy(b->addr.data, *ptr, len);
1434 b->addr.bytelen = len;
1435 b->addr.bitlen = len*8;
1436 b->addr.family = he->h_addrtype;
1437 ptr++;
1438 cnt++;
1439 }
1440 return cnt;
1441 }
1442
1443 static int get_dns_host(struct aafilter *a, const char *addr, int fam)
1444 {
1445 static int notfirst;
1446 int cnt = 0;
1447 struct hostent *he;
1448
1449 a->addr.bitlen = 0;
1450 if (!notfirst) {
1451 sethostent(1);
1452 notfirst = 1;
1453 }
1454 he = gethostbyname2(addr, fam == AF_UNSPEC ? AF_INET : fam);
1455 if (he)
1456 cnt = remember_he(a, he);
1457 if (fam == AF_UNSPEC) {
1458 he = gethostbyname2(addr, AF_INET6);
1459 if (he)
1460 cnt += remember_he(a, he);
1461 }
1462 return !cnt;
1463 }
1464
1465 static int xll_initted;
1466
1467 static void xll_init(void)
1468 {
1469 struct rtnl_handle rth;
1470
1471 if (rtnl_open(&rth, 0) < 0)
1472 exit(1);
1473
1474 ll_init_map(&rth);
1475 rtnl_close(&rth);
1476 xll_initted = 1;
1477 }
1478
1479 static const char *xll_index_to_name(int index)
1480 {
1481 if (!xll_initted)
1482 xll_init();
1483 return ll_index_to_name(index);
1484 }
1485
1486 static int xll_name_to_index(const char *dev)
1487 {
1488 if (!xll_initted)
1489 xll_init();
1490 return ll_name_to_index(dev);
1491 }
1492
1493 void *parse_devcond(char *name)
1494 {
1495 struct aafilter a = { .iface = 0 };
1496 struct aafilter *res;
1497
1498 a.iface = xll_name_to_index(name);
1499 if (a.iface == 0) {
1500 char *end;
1501 unsigned long n;
1502
1503 n = strtoul(name, &end, 0);
1504 if (!end || end == name || *end || n > UINT_MAX)
1505 return NULL;
1506
1507 a.iface = n;
1508 }
1509
1510 res = malloc(sizeof(*res));
1511 *res = a;
1512
1513 return res;
1514 }
1515
1516 void *parse_hostcond(char *addr, bool is_port)
1517 {
1518 char *port = NULL;
1519 struct aafilter a = { .port = -1 };
1520 struct aafilter *res;
1521 int fam = preferred_family;
1522 struct filter *f = &current_filter;
1523
1524 if (fam == AF_UNIX || strncmp(addr, "unix:", 5) == 0) {
1525 char *p;
1526
1527 a.addr.family = AF_UNIX;
1528 if (strncmp(addr, "unix:", 5) == 0)
1529 addr += 5;
1530 p = strdup(addr);
1531 a.addr.bitlen = 8*strlen(p);
1532 memcpy(a.addr.data, &p, sizeof(p));
1533 fam = AF_UNIX;
1534 goto out;
1535 }
1536
1537 if (fam == AF_PACKET || strncmp(addr, "link:", 5) == 0) {
1538 a.addr.family = AF_PACKET;
1539 a.addr.bitlen = 0;
1540 if (strncmp(addr, "link:", 5) == 0)
1541 addr += 5;
1542 port = strchr(addr, ':');
1543 if (port) {
1544 *port = 0;
1545 if (port[1] && strcmp(port+1, "*")) {
1546 if (get_integer(&a.port, port+1, 0)) {
1547 if ((a.port = xll_name_to_index(port+1)) <= 0)
1548 return NULL;
1549 }
1550 }
1551 }
1552 if (addr[0] && strcmp(addr, "*")) {
1553 unsigned short tmp;
1554
1555 a.addr.bitlen = 32;
1556 if (ll_proto_a2n(&tmp, addr))
1557 return NULL;
1558 a.addr.data[0] = ntohs(tmp);
1559 }
1560 fam = AF_PACKET;
1561 goto out;
1562 }
1563
1564 if (fam == AF_NETLINK || strncmp(addr, "netlink:", 8) == 0) {
1565 a.addr.family = AF_NETLINK;
1566 a.addr.bitlen = 0;
1567 if (strncmp(addr, "netlink:", 8) == 0)
1568 addr += 8;
1569 port = strchr(addr, ':');
1570 if (port) {
1571 *port = 0;
1572 if (port[1] && strcmp(port+1, "*")) {
1573 if (get_integer(&a.port, port+1, 0)) {
1574 if (strcmp(port+1, "kernel") == 0)
1575 a.port = 0;
1576 else
1577 return NULL;
1578 }
1579 }
1580 }
1581 if (addr[0] && strcmp(addr, "*")) {
1582 a.addr.bitlen = 32;
1583 if (nl_proto_a2n(&a.addr.data[0], addr) == -1)
1584 return NULL;
1585 }
1586 fam = AF_NETLINK;
1587 goto out;
1588 }
1589
1590 if (fam == AF_INET || !strncmp(addr, "inet:", 5)) {
1591 fam = AF_INET;
1592 if (!strncmp(addr, "inet:", 5))
1593 addr += 5;
1594 } else if (fam == AF_INET6 || !strncmp(addr, "inet6:", 6)) {
1595 fam = AF_INET6;
1596 if (!strncmp(addr, "inet6:", 6))
1597 addr += 6;
1598 }
1599
1600 /* URL-like literal [] */
1601 if (addr[0] == '[') {
1602 addr++;
1603 if ((port = strchr(addr, ']')) == NULL)
1604 return NULL;
1605 *port++ = 0;
1606 } else if (addr[0] == '*') {
1607 port = addr+1;
1608 } else {
1609 port = strrchr(strchr(addr, '/') ? : addr, ':');
1610 }
1611
1612 if (is_port)
1613 port = addr;
1614
1615 if (port && *port) {
1616 if (*port == ':')
1617 *port++ = 0;
1618
1619 if (*port && *port != '*') {
1620 if (get_integer(&a.port, port, 0)) {
1621 struct servent *se1 = NULL;
1622 struct servent *se2 = NULL;
1623
1624 if (current_filter.dbs&(1<<UDP_DB))
1625 se1 = getservbyname(port, UDP_PROTO);
1626 if (current_filter.dbs&(1<<TCP_DB))
1627 se2 = getservbyname(port, TCP_PROTO);
1628 if (se1 && se2 && se1->s_port != se2->s_port) {
1629 fprintf(stderr, "Error: ambiguous port \"%s\".\n", port);
1630 return NULL;
1631 }
1632 if (!se1)
1633 se1 = se2;
1634 if (se1) {
1635 a.port = ntohs(se1->s_port);
1636 } else {
1637 struct scache *s;
1638
1639 for (s = rlist; s; s = s->next) {
1640 if ((s->proto == UDP_PROTO &&
1641 (current_filter.dbs&(1<<UDP_DB))) ||
1642 (s->proto == TCP_PROTO &&
1643 (current_filter.dbs&(1<<TCP_DB)))) {
1644 if (s->name && strcmp(s->name, port) == 0) {
1645 if (a.port > 0 && a.port != s->port) {
1646 fprintf(stderr, "Error: ambiguous port \"%s\".\n", port);
1647 return NULL;
1648 }
1649 a.port = s->port;
1650 }
1651 }
1652 }
1653 if (a.port <= 0) {
1654 fprintf(stderr, "Error: \"%s\" does not look like a port.\n", port);
1655 return NULL;
1656 }
1657 }
1658 }
1659 }
1660 }
1661 if (!is_port && addr && *addr && *addr != '*') {
1662 if (get_prefix_1(&a.addr, addr, fam)) {
1663 if (get_dns_host(&a, addr, fam)) {
1664 fprintf(stderr, "Error: an inet prefix is expected rather than \"%s\".\n", addr);
1665 return NULL;
1666 }
1667 }
1668 }
1669
1670 out:
1671 if (fam != AF_UNSPEC) {
1672 int states = f->states;
1673 f->families = 0;
1674 filter_af_set(f, fam);
1675 filter_states_set(f, states);
1676 }
1677
1678 res = malloc(sizeof(*res));
1679 if (res)
1680 memcpy(res, &a, sizeof(a));
1681 return res;
1682 }
1683
1684 void *parse_markmask(const char *markmask)
1685 {
1686 struct aafilter a, *res;
1687
1688 if (strchr(markmask, '/')) {
1689 if (sscanf(markmask, "%i/%i", &a.mark, &a.mask) != 2)
1690 return NULL;
1691 } else {
1692 a.mask = 0xffffffff;
1693 if (sscanf(markmask, "%i", &a.mark) != 1)
1694 return NULL;
1695 }
1696
1697 res = malloc(sizeof(*res));
1698 if (res)
1699 memcpy(res, &a, sizeof(a));
1700 return res;
1701 }
1702
1703 static void proc_ctx_print(struct sockstat *s)
1704 {
1705 char *buf;
1706
1707 if (show_proc_ctx || show_sock_ctx) {
1708 if (find_entry(s->ino, &buf,
1709 (show_proc_ctx & show_sock_ctx) ?
1710 PROC_SOCK_CTX : PROC_CTX) > 0) {
1711 printf(" users:(%s)", buf);
1712 free(buf);
1713 }
1714 } else if (show_users) {
1715 if (find_entry(s->ino, &buf, USERS) > 0) {
1716 printf(" users:(%s)", buf);
1717 free(buf);
1718 }
1719 }
1720 }
1721
1722 static void inet_stats_print(struct sockstat *s)
1723 {
1724 sock_state_print(s);
1725
1726 inet_addr_print(&s->local, s->lport, s->iface);
1727 inet_addr_print(&s->remote, s->rport, 0);
1728
1729 proc_ctx_print(s);
1730 }
1731
1732 static int proc_parse_inet_addr(char *loc, char *rem, int family, struct
1733 sockstat * s)
1734 {
1735 s->local.family = s->remote.family = family;
1736 if (family == AF_INET) {
1737 sscanf(loc, "%x:%x", s->local.data, (unsigned *)&s->lport);
1738 sscanf(rem, "%x:%x", s->remote.data, (unsigned *)&s->rport);
1739 s->local.bytelen = s->remote.bytelen = 4;
1740 return 0;
1741 } else {
1742 sscanf(loc, "%08x%08x%08x%08x:%x",
1743 s->local.data,
1744 s->local.data + 1,
1745 s->local.data + 2,
1746 s->local.data + 3,
1747 &s->lport);
1748 sscanf(rem, "%08x%08x%08x%08x:%x",
1749 s->remote.data,
1750 s->remote.data + 1,
1751 s->remote.data + 2,
1752 s->remote.data + 3,
1753 &s->rport);
1754 s->local.bytelen = s->remote.bytelen = 16;
1755 return 0;
1756 }
1757 return -1;
1758 }
1759
1760 static int proc_inet_split_line(char *line, char **loc, char **rem, char **data)
1761 {
1762 char *p;
1763
1764 if ((p = strchr(line, ':')) == NULL)
1765 return -1;
1766
1767 *loc = p+2;
1768 if ((p = strchr(*loc, ':')) == NULL)
1769 return -1;
1770
1771 p[5] = 0;
1772 *rem = p+6;
1773 if ((p = strchr(*rem, ':')) == NULL)
1774 return -1;
1775
1776 p[5] = 0;
1777 *data = p+6;
1778 return 0;
1779 }
1780
1781 static char *sprint_bw(char *buf, double bw)
1782 {
1783 if (bw > 1000000.)
1784 sprintf(buf, "%.1fM", bw / 1000000.);
1785 else if (bw > 1000.)
1786 sprintf(buf, "%.1fK", bw / 1000.);
1787 else
1788 sprintf(buf, "%g", bw);
1789
1790 return buf;
1791 }
1792
1793 static void sctp_stats_print(struct sctp_info *s)
1794 {
1795 if (s->sctpi_tag)
1796 printf(" tag:%x", s->sctpi_tag);
1797 if (s->sctpi_state)
1798 printf(" state:%s", sctp_sstate_name[s->sctpi_state]);
1799 if (s->sctpi_rwnd)
1800 printf(" rwnd:%d", s->sctpi_rwnd);
1801 if (s->sctpi_unackdata)
1802 printf(" unackdata:%d", s->sctpi_unackdata);
1803 if (s->sctpi_penddata)
1804 printf(" penddata:%d", s->sctpi_penddata);
1805 if (s->sctpi_instrms)
1806 printf(" instrms:%d", s->sctpi_instrms);
1807 if (s->sctpi_outstrms)
1808 printf(" outstrms:%d", s->sctpi_outstrms);
1809 if (s->sctpi_inqueue)
1810 printf(" inqueue:%d", s->sctpi_inqueue);
1811 if (s->sctpi_outqueue)
1812 printf(" outqueue:%d", s->sctpi_outqueue);
1813 if (s->sctpi_overall_error)
1814 printf(" overerr:%d", s->sctpi_overall_error);
1815 if (s->sctpi_max_burst)
1816 printf(" maxburst:%d", s->sctpi_max_burst);
1817 if (s->sctpi_maxseg)
1818 printf(" maxseg:%d", s->sctpi_maxseg);
1819 if (s->sctpi_peer_rwnd)
1820 printf(" prwnd:%d", s->sctpi_peer_rwnd);
1821 if (s->sctpi_peer_tag)
1822 printf(" ptag:%x", s->sctpi_peer_tag);
1823 if (s->sctpi_peer_capable)
1824 printf(" pcapable:%d", s->sctpi_peer_capable);
1825 if (s->sctpi_peer_sack)
1826 printf(" psack:%d", s->sctpi_peer_sack);
1827 if (s->sctpi_s_autoclose)
1828 printf(" autoclose:%d", s->sctpi_s_autoclose);
1829 if (s->sctpi_s_adaptation_ind)
1830 printf(" adapind:%d", s->sctpi_s_adaptation_ind);
1831 if (s->sctpi_s_pd_point)
1832 printf(" pdpoint:%d", s->sctpi_s_pd_point);
1833 if (s->sctpi_s_nodelay)
1834 printf(" nodealy:%d", s->sctpi_s_nodelay);
1835 if (s->sctpi_s_disable_fragments)
1836 printf(" nofrag:%d", s->sctpi_s_disable_fragments);
1837 if (s->sctpi_s_v4mapped)
1838 printf(" v4mapped:%d", s->sctpi_s_v4mapped);
1839 if (s->sctpi_s_frag_interleave)
1840 printf(" fraginl:%d", s->sctpi_s_frag_interleave);
1841 }
1842
1843 static void tcp_stats_print(struct tcpstat *s)
1844 {
1845 char b1[64];
1846
1847 if (s->has_ts_opt)
1848 printf(" ts");
1849 if (s->has_sack_opt)
1850 printf(" sack");
1851 if (s->has_ecn_opt)
1852 printf(" ecn");
1853 if (s->has_ecnseen_opt)
1854 printf(" ecnseen");
1855 if (s->has_fastopen_opt)
1856 printf(" fastopen");
1857 if (s->cong_alg[0])
1858 printf(" %s", s->cong_alg);
1859 if (s->has_wscale_opt)
1860 printf(" wscale:%d,%d", s->snd_wscale, s->rcv_wscale);
1861 if (s->rto)
1862 printf(" rto:%g", s->rto);
1863 if (s->backoff)
1864 printf(" backoff:%u", s->backoff);
1865 if (s->rtt)
1866 printf(" rtt:%g/%g", s->rtt, s->rttvar);
1867 if (s->ato)
1868 printf(" ato:%g", s->ato);
1869
1870 if (s->qack)
1871 printf(" qack:%d", s->qack);
1872 if (s->qack & 1)
1873 printf(" bidir");
1874
1875 if (s->mss)
1876 printf(" mss:%d", s->mss);
1877 if (s->rcv_mss)
1878 printf(" rcvmss:%d", s->rcv_mss);
1879 if (s->advmss)
1880 printf(" advmss:%d", s->advmss);
1881 if (s->cwnd)
1882 printf(" cwnd:%u", s->cwnd);
1883 if (s->ssthresh)
1884 printf(" ssthresh:%d", s->ssthresh);
1885
1886 if (s->bytes_acked)
1887 printf(" bytes_acked:%llu", s->bytes_acked);
1888 if (s->bytes_received)
1889 printf(" bytes_received:%llu", s->bytes_received);
1890 if (s->segs_out)
1891 printf(" segs_out:%u", s->segs_out);
1892 if (s->segs_in)
1893 printf(" segs_in:%u", s->segs_in);
1894 if (s->data_segs_out)
1895 printf(" data_segs_out:%u", s->data_segs_out);
1896 if (s->data_segs_in)
1897 printf(" data_segs_in:%u", s->data_segs_in);
1898
1899 if (s->dctcp && s->dctcp->enabled) {
1900 struct dctcpstat *dctcp = s->dctcp;
1901
1902 printf(" dctcp:(ce_state:%u,alpha:%u,ab_ecn:%u,ab_tot:%u)",
1903 dctcp->ce_state, dctcp->alpha, dctcp->ab_ecn,
1904 dctcp->ab_tot);
1905 } else if (s->dctcp) {
1906 printf(" dctcp:fallback_mode");
1907 }
1908
1909 if (s->bbr_info) {
1910 __u64 bw;
1911
1912 bw = s->bbr_info->bbr_bw_hi;
1913 bw <<= 32;
1914 bw |= s->bbr_info->bbr_bw_lo;
1915
1916 printf(" bbr:(bw:%sbps,mrtt:%g",
1917 sprint_bw(b1, bw * 8.0),
1918 (double)s->bbr_info->bbr_min_rtt / 1000.0);
1919 if (s->bbr_info->bbr_pacing_gain)
1920 printf(",pacing_gain:%g",
1921 (double)s->bbr_info->bbr_pacing_gain / 256.0);
1922 if (s->bbr_info->bbr_cwnd_gain)
1923 printf(",cwnd_gain:%g",
1924 (double)s->bbr_info->bbr_cwnd_gain / 256.0);
1925 printf(")");
1926 }
1927
1928 if (s->send_bps)
1929 printf(" send %sbps", sprint_bw(b1, s->send_bps));
1930 if (s->lastsnd)
1931 printf(" lastsnd:%u", s->lastsnd);
1932 if (s->lastrcv)
1933 printf(" lastrcv:%u", s->lastrcv);
1934 if (s->lastack)
1935 printf(" lastack:%u", s->lastack);
1936
1937 if (s->pacing_rate) {
1938 printf(" pacing_rate %sbps", sprint_bw(b1, s->pacing_rate));
1939 if (s->pacing_rate_max)
1940 printf("/%sbps", sprint_bw(b1,
1941 s->pacing_rate_max));
1942 }
1943
1944 if (s->delivery_rate)
1945 printf(" delivery_rate %sbps", sprint_bw(b1, s->delivery_rate));
1946 if (s->app_limited)
1947 printf(" app_limited");
1948
1949 if (s->busy_time) {
1950 printf(" busy:%llums", s->busy_time / 1000);
1951 if (s->rwnd_limited)
1952 printf(" rwnd_limited:%llums(%.1f%%)",
1953 s->rwnd_limited / 1000,
1954 100.0 * s->rwnd_limited / s->busy_time);
1955 if (s->sndbuf_limited)
1956 printf(" sndbuf_limited:%llums(%.1f%%)",
1957 s->sndbuf_limited / 1000,
1958 100.0 * s->sndbuf_limited / s->busy_time);
1959 }
1960
1961 if (s->unacked)
1962 printf(" unacked:%u", s->unacked);
1963 if (s->retrans || s->retrans_total)
1964 printf(" retrans:%u/%u", s->retrans, s->retrans_total);
1965 if (s->lost)
1966 printf(" lost:%u", s->lost);
1967 if (s->sacked && s->ss.state != SS_LISTEN)
1968 printf(" sacked:%u", s->sacked);
1969 if (s->fackets)
1970 printf(" fackets:%u", s->fackets);
1971 if (s->reordering != 3)
1972 printf(" reordering:%d", s->reordering);
1973 if (s->rcv_rtt)
1974 printf(" rcv_rtt:%g", s->rcv_rtt);
1975 if (s->rcv_space)
1976 printf(" rcv_space:%d", s->rcv_space);
1977 if (s->not_sent)
1978 printf(" notsent:%u", s->not_sent);
1979 if (s->min_rtt)
1980 printf(" minrtt:%g", s->min_rtt);
1981 }
1982
1983 static void tcp_timer_print(struct tcpstat *s)
1984 {
1985 static const char * const tmr_name[] = {
1986 "off",
1987 "on",
1988 "keepalive",
1989 "timewait",
1990 "persist",
1991 "unknown"
1992 };
1993
1994 if (s->timer) {
1995 if (s->timer > 4)
1996 s->timer = 5;
1997 printf(" timer:(%s,%s,%d)",
1998 tmr_name[s->timer],
1999 print_ms_timer(s->timeout),
2000 s->retrans);
2001 }
2002 }
2003
2004 static void sctp_timer_print(struct tcpstat *s)
2005 {
2006 if (s->timer)
2007 printf(" timer:(T3_RTX,%s,%d)",
2008 print_ms_timer(s->timeout), s->retrans);
2009 }
2010
2011 static int tcp_show_line(char *line, const struct filter *f, int family)
2012 {
2013 int rto = 0, ato = 0;
2014 struct tcpstat s = {};
2015 char *loc, *rem, *data;
2016 char opt[256];
2017 int n;
2018 int hz = get_user_hz();
2019
2020 if (proc_inet_split_line(line, &loc, &rem, &data))
2021 return -1;
2022
2023 int state = (data[1] >= 'A') ? (data[1] - 'A' + 10) : (data[1] - '0');
2024
2025 if (!(f->states & (1 << state)))
2026 return 0;
2027
2028 proc_parse_inet_addr(loc, rem, family, &s.ss);
2029
2030 if (f->f && run_ssfilter(f->f, &s.ss) == 0)
2031 return 0;
2032
2033 opt[0] = 0;
2034 n = sscanf(data, "%x %x:%x %x:%x %x %d %d %u %d %llx %d %d %d %u %d %[^\n]\n",
2035 &s.ss.state, &s.ss.wq, &s.ss.rq,
2036 &s.timer, &s.timeout, &s.retrans, &s.ss.uid, &s.probes,
2037 &s.ss.ino, &s.ss.refcnt, &s.ss.sk, &rto, &ato, &s.qack, &s.cwnd,
2038 &s.ssthresh, opt);
2039
2040 if (n < 17)
2041 opt[0] = 0;
2042
2043 if (n < 12) {
2044 rto = 0;
2045 s.cwnd = 2;
2046 s.ssthresh = -1;
2047 ato = s.qack = 0;
2048 }
2049
2050 s.retrans = s.timer != 1 ? s.probes : s.retrans;
2051 s.timeout = (s.timeout * 1000 + hz - 1) / hz;
2052 s.ato = (double)ato / hz;
2053 s.qack /= 2;
2054 s.rto = (double)rto;
2055 s.ssthresh = s.ssthresh == -1 ? 0 : s.ssthresh;
2056 s.rto = s.rto != 3 * hz ? s.rto / hz : 0;
2057 s.ss.type = IPPROTO_TCP;
2058
2059 inet_stats_print(&s.ss);
2060
2061 if (show_options)
2062 tcp_timer_print(&s);
2063
2064 if (show_details) {
2065 sock_details_print(&s.ss);
2066 if (opt[0])
2067 printf(" opt:\"%s\"", opt);
2068 }
2069
2070 if (show_tcpinfo)
2071 tcp_stats_print(&s);
2072
2073 printf("\n");
2074 return 0;
2075 }
2076
2077 static int generic_record_read(FILE *fp,
2078 int (*worker)(char*, const struct filter *, int),
2079 const struct filter *f, int fam)
2080 {
2081 char line[256];
2082
2083 /* skip header */
2084 if (fgets(line, sizeof(line), fp) == NULL)
2085 goto outerr;
2086
2087 while (fgets(line, sizeof(line), fp) != NULL) {
2088 int n = strlen(line);
2089
2090 if (n == 0 || line[n-1] != '\n') {
2091 errno = -EINVAL;
2092 return -1;
2093 }
2094 line[n-1] = 0;
2095
2096 if (worker(line, f, fam) < 0)
2097 return 0;
2098 }
2099 outerr:
2100
2101 return ferror(fp) ? -1 : 0;
2102 }
2103
2104 static void print_skmeminfo(struct rtattr *tb[], int attrtype)
2105 {
2106 const __u32 *skmeminfo;
2107
2108 if (!tb[attrtype]) {
2109 if (attrtype == INET_DIAG_SKMEMINFO) {
2110 if (!tb[INET_DIAG_MEMINFO])
2111 return;
2112
2113 const struct inet_diag_meminfo *minfo =
2114 RTA_DATA(tb[INET_DIAG_MEMINFO]);
2115
2116 printf(" mem:(r%u,w%u,f%u,t%u)",
2117 minfo->idiag_rmem,
2118 minfo->idiag_wmem,
2119 minfo->idiag_fmem,
2120 minfo->idiag_tmem);
2121 }
2122 return;
2123 }
2124
2125 skmeminfo = RTA_DATA(tb[attrtype]);
2126
2127 printf(" skmem:(r%u,rb%u,t%u,tb%u,f%u,w%u,o%u",
2128 skmeminfo[SK_MEMINFO_RMEM_ALLOC],
2129 skmeminfo[SK_MEMINFO_RCVBUF],
2130 skmeminfo[SK_MEMINFO_WMEM_ALLOC],
2131 skmeminfo[SK_MEMINFO_SNDBUF],
2132 skmeminfo[SK_MEMINFO_FWD_ALLOC],
2133 skmeminfo[SK_MEMINFO_WMEM_QUEUED],
2134 skmeminfo[SK_MEMINFO_OPTMEM]);
2135
2136 if (RTA_PAYLOAD(tb[attrtype]) >=
2137 (SK_MEMINFO_BACKLOG + 1) * sizeof(__u32))
2138 printf(",bl%u", skmeminfo[SK_MEMINFO_BACKLOG]);
2139
2140 if (RTA_PAYLOAD(tb[attrtype]) >=
2141 (SK_MEMINFO_DROPS + 1) * sizeof(__u32))
2142 printf(",d%u", skmeminfo[SK_MEMINFO_DROPS]);
2143
2144 printf(")");
2145 }
2146
2147 #define TCPI_HAS_OPT(info, opt) !!(info->tcpi_options & (opt))
2148
2149 static void tcp_show_info(const struct nlmsghdr *nlh, struct inet_diag_msg *r,
2150 struct rtattr *tb[])
2151 {
2152 double rtt = 0;
2153 struct tcpstat s = {};
2154
2155 s.ss.state = r->idiag_state;
2156
2157 print_skmeminfo(tb, INET_DIAG_SKMEMINFO);
2158
2159 if (tb[INET_DIAG_INFO]) {
2160 struct tcp_info *info;
2161 int len = RTA_PAYLOAD(tb[INET_DIAG_INFO]);
2162
2163 /* workaround for older kernels with less fields */
2164 if (len < sizeof(*info)) {
2165 info = alloca(sizeof(*info));
2166 memcpy(info, RTA_DATA(tb[INET_DIAG_INFO]), len);
2167 memset((char *)info + len, 0, sizeof(*info) - len);
2168 } else
2169 info = RTA_DATA(tb[INET_DIAG_INFO]);
2170
2171 if (show_options) {
2172 s.has_ts_opt = TCPI_HAS_OPT(info, TCPI_OPT_TIMESTAMPS);
2173 s.has_sack_opt = TCPI_HAS_OPT(info, TCPI_OPT_SACK);
2174 s.has_ecn_opt = TCPI_HAS_OPT(info, TCPI_OPT_ECN);
2175 s.has_ecnseen_opt = TCPI_HAS_OPT(info, TCPI_OPT_ECN_SEEN);
2176 s.has_fastopen_opt = TCPI_HAS_OPT(info, TCPI_OPT_SYN_DATA);
2177 }
2178
2179 if (tb[INET_DIAG_CONG])
2180 strncpy(s.cong_alg,
2181 rta_getattr_str(tb[INET_DIAG_CONG]),
2182 sizeof(s.cong_alg) - 1);
2183
2184 if (TCPI_HAS_OPT(info, TCPI_OPT_WSCALE)) {
2185 s.has_wscale_opt = true;
2186 s.snd_wscale = info->tcpi_snd_wscale;
2187 s.rcv_wscale = info->tcpi_rcv_wscale;
2188 }
2189
2190 if (info->tcpi_rto && info->tcpi_rto != 3000000)
2191 s.rto = (double)info->tcpi_rto / 1000;
2192
2193 s.backoff = info->tcpi_backoff;
2194 s.rtt = (double)info->tcpi_rtt / 1000;
2195 s.rttvar = (double)info->tcpi_rttvar / 1000;
2196 s.ato = (double)info->tcpi_ato / 1000;
2197 s.mss = info->tcpi_snd_mss;
2198 s.rcv_mss = info->tcpi_rcv_mss;
2199 s.advmss = info->tcpi_advmss;
2200 s.rcv_space = info->tcpi_rcv_space;
2201 s.rcv_rtt = (double)info->tcpi_rcv_rtt / 1000;
2202 s.lastsnd = info->tcpi_last_data_sent;
2203 s.lastrcv = info->tcpi_last_data_recv;
2204 s.lastack = info->tcpi_last_ack_recv;
2205 s.unacked = info->tcpi_unacked;
2206 s.retrans = info->tcpi_retrans;
2207 s.retrans_total = info->tcpi_total_retrans;
2208 s.lost = info->tcpi_lost;
2209 s.sacked = info->tcpi_sacked;
2210 s.reordering = info->tcpi_reordering;
2211 s.rcv_space = info->tcpi_rcv_space;
2212 s.cwnd = info->tcpi_snd_cwnd;
2213
2214 if (info->tcpi_snd_ssthresh < 0xFFFF)
2215 s.ssthresh = info->tcpi_snd_ssthresh;
2216
2217 rtt = (double) info->tcpi_rtt;
2218 if (tb[INET_DIAG_VEGASINFO]) {
2219 const struct tcpvegas_info *vinfo
2220 = RTA_DATA(tb[INET_DIAG_VEGASINFO]);
2221
2222 if (vinfo->tcpv_enabled &&
2223 vinfo->tcpv_rtt && vinfo->tcpv_rtt != 0x7fffffff)
2224 rtt = vinfo->tcpv_rtt;
2225 }
2226
2227 if (tb[INET_DIAG_DCTCPINFO]) {
2228 struct dctcpstat *dctcp = malloc(sizeof(struct
2229 dctcpstat));
2230
2231 const struct tcp_dctcp_info *dinfo
2232 = RTA_DATA(tb[INET_DIAG_DCTCPINFO]);
2233
2234 dctcp->enabled = !!dinfo->dctcp_enabled;
2235 dctcp->ce_state = dinfo->dctcp_ce_state;
2236 dctcp->alpha = dinfo->dctcp_alpha;
2237 dctcp->ab_ecn = dinfo->dctcp_ab_ecn;
2238 dctcp->ab_tot = dinfo->dctcp_ab_tot;
2239 s.dctcp = dctcp;
2240 }
2241
2242 if (tb[INET_DIAG_BBRINFO]) {
2243 const void *bbr_info = RTA_DATA(tb[INET_DIAG_BBRINFO]);
2244 int len = min(RTA_PAYLOAD(tb[INET_DIAG_BBRINFO]),
2245 sizeof(*s.bbr_info));
2246
2247 s.bbr_info = calloc(1, sizeof(*s.bbr_info));
2248 if (s.bbr_info && bbr_info)
2249 memcpy(s.bbr_info, bbr_info, len);
2250 }
2251
2252 if (rtt > 0 && info->tcpi_snd_mss && info->tcpi_snd_cwnd) {
2253 s.send_bps = (double) info->tcpi_snd_cwnd *
2254 (double)info->tcpi_snd_mss * 8000000. / rtt;
2255 }
2256
2257 if (info->tcpi_pacing_rate &&
2258 info->tcpi_pacing_rate != ~0ULL) {
2259 s.pacing_rate = info->tcpi_pacing_rate * 8.;
2260
2261 if (info->tcpi_max_pacing_rate &&
2262 info->tcpi_max_pacing_rate != ~0ULL)
2263 s.pacing_rate_max = info->tcpi_max_pacing_rate * 8.;
2264 }
2265 s.bytes_acked = info->tcpi_bytes_acked;
2266 s.bytes_received = info->tcpi_bytes_received;
2267 s.segs_out = info->tcpi_segs_out;
2268 s.segs_in = info->tcpi_segs_in;
2269 s.data_segs_out = info->tcpi_data_segs_out;
2270 s.data_segs_in = info->tcpi_data_segs_in;
2271 s.not_sent = info->tcpi_notsent_bytes;
2272 if (info->tcpi_min_rtt && info->tcpi_min_rtt != ~0U)
2273 s.min_rtt = (double) info->tcpi_min_rtt / 1000;
2274 s.delivery_rate = info->tcpi_delivery_rate * 8.;
2275 s.app_limited = info->tcpi_delivery_rate_app_limited;
2276 s.busy_time = info->tcpi_busy_time;
2277 s.rwnd_limited = info->tcpi_rwnd_limited;
2278 s.sndbuf_limited = info->tcpi_sndbuf_limited;
2279 tcp_stats_print(&s);
2280 free(s.dctcp);
2281 free(s.bbr_info);
2282 }
2283 }
2284
2285 static const char *format_host_sa(struct sockaddr_storage *sa)
2286 {
2287 union {
2288 struct sockaddr_in sin;
2289 struct sockaddr_in6 sin6;
2290 } *saddr = (void *)sa;
2291
2292 switch (sa->ss_family) {
2293 case AF_INET:
2294 return format_host(AF_INET, 4, &saddr->sin.sin_addr);
2295 case AF_INET6:
2296 return format_host(AF_INET6, 16, &saddr->sin6.sin6_addr);
2297 default:
2298 return "";
2299 }
2300 }
2301
2302 static void sctp_show_info(const struct nlmsghdr *nlh, struct inet_diag_msg *r,
2303 struct rtattr *tb[])
2304 {
2305 struct sockaddr_storage *sa;
2306 int len;
2307
2308 print_skmeminfo(tb, INET_DIAG_SKMEMINFO);
2309
2310 if (tb[INET_DIAG_LOCALS]) {
2311 len = RTA_PAYLOAD(tb[INET_DIAG_LOCALS]);
2312 sa = RTA_DATA(tb[INET_DIAG_LOCALS]);
2313
2314 printf("locals:%s", format_host_sa(sa));
2315 for (sa++, len -= sizeof(*sa); len > 0; sa++, len -= sizeof(*sa))
2316 printf(",%s", format_host_sa(sa));
2317
2318 }
2319 if (tb[INET_DIAG_PEERS]) {
2320 len = RTA_PAYLOAD(tb[INET_DIAG_PEERS]);
2321 sa = RTA_DATA(tb[INET_DIAG_PEERS]);
2322
2323 printf(" peers:%s", format_host_sa(sa));
2324 for (sa++, len -= sizeof(*sa); len > 0; sa++, len -= sizeof(*sa))
2325 printf(",%s", format_host_sa(sa));
2326 }
2327 if (tb[INET_DIAG_INFO]) {
2328 struct sctp_info *info;
2329 len = RTA_PAYLOAD(tb[INET_DIAG_INFO]);
2330
2331 /* workaround for older kernels with less fields */
2332 if (len < sizeof(*info)) {
2333 info = alloca(sizeof(*info));
2334 memcpy(info, RTA_DATA(tb[INET_DIAG_INFO]), len);
2335 memset((char *)info + len, 0, sizeof(*info) - len);
2336 } else
2337 info = RTA_DATA(tb[INET_DIAG_INFO]);
2338
2339 sctp_stats_print(info);
2340 }
2341 }
2342
2343 static void parse_diag_msg(struct nlmsghdr *nlh, struct sockstat *s)
2344 {
2345 struct rtattr *tb[INET_DIAG_MAX+1];
2346 struct inet_diag_msg *r = NLMSG_DATA(nlh);
2347
2348 parse_rtattr(tb, INET_DIAG_MAX, (struct rtattr *)(r+1),
2349 nlh->nlmsg_len - NLMSG_LENGTH(sizeof(*r)));
2350
2351 s->state = r->idiag_state;
2352 s->local.family = s->remote.family = r->idiag_family;
2353 s->lport = ntohs(r->id.idiag_sport);
2354 s->rport = ntohs(r->id.idiag_dport);
2355 s->wq = r->idiag_wqueue;
2356 s->rq = r->idiag_rqueue;
2357 s->ino = r->idiag_inode;
2358 s->uid = r->idiag_uid;
2359 s->iface = r->id.idiag_if;
2360 s->sk = cookie_sk_get(&r->id.idiag_cookie[0]);
2361
2362 s->mark = 0;
2363 if (tb[INET_DIAG_MARK])
2364 s->mark = rta_getattr_u32(tb[INET_DIAG_MARK]);
2365 if (tb[INET_DIAG_PROTOCOL])
2366 s->raw_prot = rta_getattr_u8(tb[INET_DIAG_PROTOCOL]);
2367 else
2368 s->raw_prot = 0;
2369
2370 if (s->local.family == AF_INET)
2371 s->local.bytelen = s->remote.bytelen = 4;
2372 else
2373 s->local.bytelen = s->remote.bytelen = 16;
2374
2375 memcpy(s->local.data, r->id.idiag_src, s->local.bytelen);
2376 memcpy(s->remote.data, r->id.idiag_dst, s->local.bytelen);
2377 }
2378
2379 static int inet_show_sock(struct nlmsghdr *nlh,
2380 struct sockstat *s)
2381 {
2382 struct rtattr *tb[INET_DIAG_MAX+1];
2383 struct inet_diag_msg *r = NLMSG_DATA(nlh);
2384
2385 parse_rtattr(tb, INET_DIAG_MAX, (struct rtattr *)(r+1),
2386 nlh->nlmsg_len - NLMSG_LENGTH(sizeof(*r)));
2387
2388 if (tb[INET_DIAG_PROTOCOL])
2389 s->type = rta_getattr_u8(tb[INET_DIAG_PROTOCOL]);
2390
2391 inet_stats_print(s);
2392
2393 if (show_options) {
2394 struct tcpstat t = {};
2395
2396 t.timer = r->idiag_timer;
2397 t.timeout = r->idiag_expires;
2398 t.retrans = r->idiag_retrans;
2399 if (s->type == IPPROTO_SCTP)
2400 sctp_timer_print(&t);
2401 else
2402 tcp_timer_print(&t);
2403 }
2404
2405 if (show_details) {
2406 sock_details_print(s);
2407 if (s->local.family == AF_INET6 && tb[INET_DIAG_SKV6ONLY]) {
2408 unsigned char v6only;
2409
2410 v6only = rta_getattr_u8(tb[INET_DIAG_SKV6ONLY]);
2411 printf(" v6only:%u", v6only);
2412 }
2413 if (tb[INET_DIAG_SHUTDOWN]) {
2414 unsigned char mask;
2415
2416 mask = rta_getattr_u8(tb[INET_DIAG_SHUTDOWN]);
2417 printf(" %c-%c", mask & 1 ? '-' : '<', mask & 2 ? '-' : '>');
2418 }
2419 }
2420
2421 if (show_mem || (show_tcpinfo && s->type != IPPROTO_UDP)) {
2422 printf("\n\t");
2423 if (s->type == IPPROTO_SCTP)
2424 sctp_show_info(nlh, r, tb);
2425 else
2426 tcp_show_info(nlh, r, tb);
2427 }
2428 sctp_ino = s->ino;
2429
2430 printf("\n");
2431 return 0;
2432 }
2433
2434 static int tcpdiag_send(int fd, int protocol, struct filter *f)
2435 {
2436 struct sockaddr_nl nladdr = { .nl_family = AF_NETLINK };
2437 struct {
2438 struct nlmsghdr nlh;
2439 struct inet_diag_req r;
2440 } req = {
2441 .nlh.nlmsg_len = sizeof(req),
2442 .nlh.nlmsg_flags = NLM_F_ROOT | NLM_F_MATCH | NLM_F_REQUEST,
2443 .nlh.nlmsg_seq = MAGIC_SEQ,
2444 .r.idiag_family = AF_INET,
2445 .r.idiag_states = f->states,
2446 };
2447 char *bc = NULL;
2448 int bclen;
2449 struct msghdr msg;
2450 struct rtattr rta;
2451 struct iovec iov[3];
2452 int iovlen = 1;
2453
2454 if (protocol == IPPROTO_UDP)
2455 return -1;
2456
2457 if (protocol == IPPROTO_TCP)
2458 req.nlh.nlmsg_type = TCPDIAG_GETSOCK;
2459 else
2460 req.nlh.nlmsg_type = DCCPDIAG_GETSOCK;
2461 if (show_mem) {
2462 req.r.idiag_ext |= (1<<(INET_DIAG_MEMINFO-1));
2463 req.r.idiag_ext |= (1<<(INET_DIAG_SKMEMINFO-1));
2464 }
2465
2466 if (show_tcpinfo) {
2467 req.r.idiag_ext |= (1<<(INET_DIAG_INFO-1));
2468 req.r.idiag_ext |= (1<<(INET_DIAG_VEGASINFO-1));
2469 req.r.idiag_ext |= (1<<(INET_DIAG_CONG-1));
2470 }
2471
2472 iov[0] = (struct iovec){
2473 .iov_base = &req,
2474 .iov_len = sizeof(req)
2475 };
2476 if (f->f) {
2477 bclen = ssfilter_bytecompile(f->f, &bc);
2478 if (bclen) {
2479 rta.rta_type = INET_DIAG_REQ_BYTECODE;
2480 rta.rta_len = RTA_LENGTH(bclen);
2481 iov[1] = (struct iovec){ &rta, sizeof(rta) };
2482 iov[2] = (struct iovec){ bc, bclen };
2483 req.nlh.nlmsg_len += RTA_LENGTH(bclen);
2484 iovlen = 3;
2485 }
2486 }
2487
2488 msg = (struct msghdr) {
2489 .msg_name = (void *)&nladdr,
2490 .msg_namelen = sizeof(nladdr),
2491 .msg_iov = iov,
2492 .msg_iovlen = iovlen,
2493 };
2494
2495 if (sendmsg(fd, &msg, 0) < 0) {
2496 close(fd);
2497 return -1;
2498 }
2499
2500 return 0;
2501 }
2502
2503 static int sockdiag_send(int family, int fd, int protocol, struct filter *f)
2504 {
2505 struct sockaddr_nl nladdr = { .nl_family = AF_NETLINK };
2506 DIAG_REQUEST(req, struct inet_diag_req_v2 r);
2507 char *bc = NULL;
2508 int bclen;
2509 struct msghdr msg;
2510 struct rtattr rta;
2511 struct iovec iov[3];
2512 int iovlen = 1;
2513
2514 if (family == PF_UNSPEC)
2515 return tcpdiag_send(fd, protocol, f);
2516
2517 memset(&req.r, 0, sizeof(req.r));
2518 req.r.sdiag_family = family;
2519 req.r.sdiag_protocol = protocol;
2520 req.r.idiag_states = f->states;
2521 if (show_mem) {
2522 req.r.idiag_ext |= (1<<(INET_DIAG_MEMINFO-1));
2523 req.r.idiag_ext |= (1<<(INET_DIAG_SKMEMINFO-1));
2524 }
2525
2526 if (show_tcpinfo) {
2527 req.r.idiag_ext |= (1<<(INET_DIAG_INFO-1));
2528 req.r.idiag_ext |= (1<<(INET_DIAG_VEGASINFO-1));
2529 req.r.idiag_ext |= (1<<(INET_DIAG_CONG-1));
2530 }
2531
2532 iov[0] = (struct iovec){
2533 .iov_base = &req,
2534 .iov_len = sizeof(req)
2535 };
2536 if (f->f) {
2537 bclen = ssfilter_bytecompile(f->f, &bc);
2538 if (bclen) {
2539 rta.rta_type = INET_DIAG_REQ_BYTECODE;
2540 rta.rta_len = RTA_LENGTH(bclen);
2541 iov[1] = (struct iovec){ &rta, sizeof(rta) };
2542 iov[2] = (struct iovec){ bc, bclen };
2543 req.nlh.nlmsg_len += RTA_LENGTH(bclen);
2544 iovlen = 3;
2545 }
2546 }
2547
2548 msg = (struct msghdr) {
2549 .msg_name = (void *)&nladdr,
2550 .msg_namelen = sizeof(nladdr),
2551 .msg_iov = iov,
2552 .msg_iovlen = iovlen,
2553 };
2554
2555 if (sendmsg(fd, &msg, 0) < 0) {
2556 close(fd);
2557 return -1;
2558 }
2559
2560 return 0;
2561 }
2562
2563 struct inet_diag_arg {
2564 struct filter *f;
2565 int protocol;
2566 struct rtnl_handle *rth;
2567 };
2568
2569 static int kill_inet_sock(struct nlmsghdr *h, void *arg, struct sockstat *s)
2570 {
2571 struct inet_diag_msg *d = NLMSG_DATA(h);
2572 struct inet_diag_arg *diag_arg = arg;
2573 struct rtnl_handle *rth = diag_arg->rth;
2574
2575 DIAG_REQUEST(req, struct inet_diag_req_v2 r);
2576
2577 req.nlh.nlmsg_type = SOCK_DESTROY;
2578 req.nlh.nlmsg_flags = NLM_F_REQUEST | NLM_F_ACK;
2579 req.nlh.nlmsg_seq = ++rth->seq;
2580 req.r.sdiag_family = d->idiag_family;
2581 req.r.sdiag_protocol = diag_arg->protocol;
2582 req.r.id = d->id;
2583
2584 if (diag_arg->protocol == IPPROTO_RAW) {
2585 struct inet_diag_req_raw *raw = (void *)&req.r;
2586
2587 BUILD_BUG_ON(sizeof(req.r) != sizeof(*raw));
2588 raw->sdiag_raw_protocol = s->raw_prot;
2589 }
2590
2591 return rtnl_talk(rth, &req.nlh, NULL, 0);
2592 }
2593
2594 static int show_one_inet_sock(const struct sockaddr_nl *addr,
2595 struct nlmsghdr *h, void *arg)
2596 {
2597 int err;
2598 struct inet_diag_arg *diag_arg = arg;
2599 struct inet_diag_msg *r = NLMSG_DATA(h);
2600 struct sockstat s = {};
2601
2602 if (!(diag_arg->f->families & (1 << r->idiag_family)))
2603 return 0;
2604
2605 parse_diag_msg(h, &s);
2606 s.type = diag_arg->protocol;
2607
2608 if (diag_arg->f->f && run_ssfilter(diag_arg->f->f, &s) == 0)
2609 return 0;
2610
2611 if (diag_arg->f->kill && kill_inet_sock(h, arg, &s) != 0) {
2612 if (errno == EOPNOTSUPP || errno == ENOENT) {
2613 /* Socket can't be closed, or is already closed. */
2614 return 0;
2615 } else {
2616 perror("SOCK_DESTROY answers");
2617 return -1;
2618 }
2619 }
2620
2621 err = inet_show_sock(h, &s);
2622 if (err < 0)
2623 return err;
2624
2625 return 0;
2626 }
2627
2628 static int inet_show_netlink(struct filter *f, FILE *dump_fp, int protocol)
2629 {
2630 int err = 0;
2631 struct rtnl_handle rth, rth2;
2632 int family = PF_INET;
2633 struct inet_diag_arg arg = { .f = f, .protocol = protocol };
2634
2635 if (rtnl_open_byproto(&rth, 0, NETLINK_SOCK_DIAG))
2636 return -1;
2637
2638 if (f->kill) {
2639 if (rtnl_open_byproto(&rth2, 0, NETLINK_SOCK_DIAG)) {
2640 rtnl_close(&rth);
2641 return -1;
2642 }
2643 arg.rth = &rth2;
2644 }
2645
2646 rth.dump = MAGIC_SEQ;
2647 rth.dump_fp = dump_fp;
2648 if (preferred_family == PF_INET6)
2649 family = PF_INET6;
2650
2651 again:
2652 if ((err = sockdiag_send(family, rth.fd, protocol, f)))
2653 goto Exit;
2654
2655 if ((err = rtnl_dump_filter(&rth, show_one_inet_sock, &arg))) {
2656 if (family != PF_UNSPEC) {
2657 family = PF_UNSPEC;
2658 goto again;
2659 }
2660 goto Exit;
2661 }
2662 if (family == PF_INET && preferred_family != PF_INET) {
2663 family = PF_INET6;
2664 goto again;
2665 }
2666
2667 Exit:
2668 rtnl_close(&rth);
2669 if (arg.rth)
2670 rtnl_close(arg.rth);
2671 return err;
2672 }
2673
2674 static int tcp_show_netlink_file(struct filter *f)
2675 {
2676 FILE *fp;
2677 char buf[16384];
2678
2679 if ((fp = fopen(getenv("TCPDIAG_FILE"), "r")) == NULL) {
2680 perror("fopen($TCPDIAG_FILE)");
2681 return -1;
2682 }
2683
2684 while (1) {
2685 int status, err;
2686 struct nlmsghdr *h = (struct nlmsghdr *)buf;
2687 struct sockstat s = {};
2688
2689 status = fread(buf, 1, sizeof(*h), fp);
2690 if (status < 0) {
2691 perror("Reading header from $TCPDIAG_FILE");
2692 return -1;
2693 }
2694 if (status != sizeof(*h)) {
2695 perror("Unexpected EOF reading $TCPDIAG_FILE");
2696 return -1;
2697 }
2698
2699 status = fread(h+1, 1, NLMSG_ALIGN(h->nlmsg_len-sizeof(*h)), fp);
2700
2701 if (status < 0) {
2702 perror("Reading $TCPDIAG_FILE");
2703 return -1;
2704 }
2705 if (status + sizeof(*h) < h->nlmsg_len) {
2706 perror("Unexpected EOF reading $TCPDIAG_FILE");
2707 return -1;
2708 }
2709
2710 /* The only legal exit point */
2711 if (h->nlmsg_type == NLMSG_DONE)
2712 return 0;
2713
2714 if (h->nlmsg_type == NLMSG_ERROR) {
2715 struct nlmsgerr *err = (struct nlmsgerr *)NLMSG_DATA(h);
2716
2717 if (h->nlmsg_len < NLMSG_LENGTH(sizeof(struct nlmsgerr))) {
2718 fprintf(stderr, "ERROR truncated\n");
2719 } else {
2720 errno = -err->error;
2721 perror("TCPDIAG answered");
2722 }
2723 return -1;
2724 }
2725
2726 parse_diag_msg(h, &s);
2727 s.type = IPPROTO_TCP;
2728
2729 if (f && f->f && run_ssfilter(f->f, &s) == 0)
2730 continue;
2731
2732 err = inet_show_sock(h, &s);
2733 if (err < 0)
2734 return err;
2735 }
2736 }
2737
2738 static int tcp_show(struct filter *f, int socktype)
2739 {
2740 FILE *fp = NULL;
2741 char *buf = NULL;
2742 int bufsize = 64*1024;
2743
2744 if (!filter_af_get(f, AF_INET) && !filter_af_get(f, AF_INET6))
2745 return 0;
2746
2747 dg_proto = TCP_PROTO;
2748
2749 if (getenv("TCPDIAG_FILE"))
2750 return tcp_show_netlink_file(f);
2751
2752 if (!getenv("PROC_NET_TCP") && !getenv("PROC_ROOT")
2753 && inet_show_netlink(f, NULL, socktype) == 0)
2754 return 0;
2755
2756 /* Sigh... We have to parse /proc/net/tcp... */
2757
2758
2759 /* Estimate amount of sockets and try to allocate
2760 * huge buffer to read all the table at one read.
2761 * Limit it by 16MB though. The assumption is: as soon as
2762 * kernel was able to hold information about N connections,
2763 * it is able to give us some memory for snapshot.
2764 */
2765 if (1) {
2766 get_slabstat(&slabstat);
2767
2768 int guess = slabstat.socks+slabstat.tcp_syns;
2769
2770 if (f->states&(1<<SS_TIME_WAIT))
2771 guess += slabstat.tcp_tws;
2772 if (guess > (16*1024*1024)/128)
2773 guess = (16*1024*1024)/128;
2774 guess *= 128;
2775 if (guess > bufsize)
2776 bufsize = guess;
2777 }
2778 while (bufsize >= 64*1024) {
2779 if ((buf = malloc(bufsize)) != NULL)
2780 break;
2781 bufsize /= 2;
2782 }
2783 if (buf == NULL) {
2784 errno = ENOMEM;
2785 return -1;
2786 }
2787
2788 if (f->families & (1<<AF_INET)) {
2789 if ((fp = net_tcp_open()) == NULL)
2790 goto outerr;
2791
2792 setbuffer(fp, buf, bufsize);
2793 if (generic_record_read(fp, tcp_show_line, f, AF_INET))
2794 goto outerr;
2795 fclose(fp);
2796 }
2797
2798 if ((f->families & (1<<AF_INET6)) &&
2799 (fp = net_tcp6_open()) != NULL) {
2800 setbuffer(fp, buf, bufsize);
2801 if (generic_record_read(fp, tcp_show_line, f, AF_INET6))
2802 goto outerr;
2803 fclose(fp);
2804 }
2805
2806 free(buf);
2807 return 0;
2808
2809 outerr:
2810 do {
2811 int saved_errno = errno;
2812
2813 free(buf);
2814 if (fp)
2815 fclose(fp);
2816 errno = saved_errno;
2817 return -1;
2818 } while (0);
2819 }
2820
2821 static int sctp_show(struct filter *f)
2822 {
2823 if (!filter_af_get(f, AF_INET) && !filter_af_get(f, AF_INET6))
2824 return 0;
2825
2826 if (!getenv("PROC_NET_SCTP") && !getenv("PROC_ROOT")
2827 && inet_show_netlink(f, NULL, IPPROTO_SCTP) == 0)
2828 return 0;
2829
2830 return 0;
2831 }
2832
2833 static int dgram_show_line(char *line, const struct filter *f, int family)
2834 {
2835 struct sockstat s = {};
2836 char *loc, *rem, *data;
2837 char opt[256];
2838 int n;
2839
2840 if (proc_inet_split_line(line, &loc, &rem, &data))
2841 return -1;
2842
2843 int state = (data[1] >= 'A') ? (data[1] - 'A' + 10) : (data[1] - '0');
2844
2845 if (!(f->states & (1 << state)))
2846 return 0;
2847
2848 proc_parse_inet_addr(loc, rem, family, &s);
2849
2850 if (f->f && run_ssfilter(f->f, &s) == 0)
2851 return 0;
2852
2853 opt[0] = 0;
2854 n = sscanf(data, "%x %x:%x %*x:%*x %*x %d %*d %u %d %llx %[^\n]\n",
2855 &s.state, &s.wq, &s.rq,
2856 &s.uid, &s.ino,
2857 &s.refcnt, &s.sk, opt);
2858
2859 if (n < 9)
2860 opt[0] = 0;
2861
2862 s.type = dg_proto == UDP_PROTO ? IPPROTO_UDP : 0;
2863 inet_stats_print(&s);
2864
2865 if (show_details && opt[0])
2866 printf(" opt:\"%s\"", opt);
2867
2868 printf("\n");
2869 return 0;
2870 }
2871
2872 static int udp_show(struct filter *f)
2873 {
2874 FILE *fp = NULL;
2875
2876 if (!filter_af_get(f, AF_INET) && !filter_af_get(f, AF_INET6))
2877 return 0;
2878
2879 dg_proto = UDP_PROTO;
2880
2881 if (!getenv("PROC_NET_UDP") && !getenv("PROC_ROOT")
2882 && inet_show_netlink(f, NULL, IPPROTO_UDP) == 0)
2883 return 0;
2884
2885 if (f->families&(1<<AF_INET)) {
2886 if ((fp = net_udp_open()) == NULL)
2887 goto outerr;
2888 if (generic_record_read(fp, dgram_show_line, f, AF_INET))
2889 goto outerr;
2890 fclose(fp);
2891 }
2892
2893 if ((f->families&(1<<AF_INET6)) &&
2894 (fp = net_udp6_open()) != NULL) {
2895 if (generic_record_read(fp, dgram_show_line, f, AF_INET6))
2896 goto outerr;
2897 fclose(fp);
2898 }
2899 return 0;
2900
2901 outerr:
2902 do {
2903 int saved_errno = errno;
2904
2905 if (fp)
2906 fclose(fp);
2907 errno = saved_errno;
2908 return -1;
2909 } while (0);
2910 }
2911
2912 static int raw_show(struct filter *f)
2913 {
2914 FILE *fp = NULL;
2915
2916 if (!filter_af_get(f, AF_INET) && !filter_af_get(f, AF_INET6))
2917 return 0;
2918
2919 dg_proto = RAW_PROTO;
2920
2921 if (!getenv("PROC_NET_RAW") && !getenv("PROC_ROOT") &&
2922 inet_show_netlink(f, NULL, IPPROTO_RAW) == 0)
2923 return 0;
2924
2925 if (f->families&(1<<AF_INET)) {
2926 if ((fp = net_raw_open()) == NULL)
2927 goto outerr;
2928 if (generic_record_read(fp, dgram_show_line, f, AF_INET))
2929 goto outerr;
2930 fclose(fp);
2931 }
2932
2933 if ((f->families&(1<<AF_INET6)) &&
2934 (fp = net_raw6_open()) != NULL) {
2935 if (generic_record_read(fp, dgram_show_line, f, AF_INET6))
2936 goto outerr;
2937 fclose(fp);
2938 }
2939 return 0;
2940
2941 outerr:
2942 do {
2943 int saved_errno = errno;
2944
2945 if (fp)
2946 fclose(fp);
2947 errno = saved_errno;
2948 return -1;
2949 } while (0);
2950 }
2951
2952 #define MAX_UNIX_REMEMBER (1024*1024/sizeof(struct sockstat))
2953
2954 static void unix_list_drop_first(struct sockstat **list)
2955 {
2956 struct sockstat *s = *list;
2957
2958 (*list) = (*list)->next;
2959 free(s->name);
2960 free(s);
2961 }
2962
2963 static bool unix_type_skip(struct sockstat *s, struct filter *f)
2964 {
2965 if (s->type == SOCK_STREAM && !(f->dbs&(1<<UNIX_ST_DB)))
2966 return true;
2967 if (s->type == SOCK_DGRAM && !(f->dbs&(1<<UNIX_DG_DB)))
2968 return true;
2969 if (s->type == SOCK_SEQPACKET && !(f->dbs&(1<<UNIX_SQ_DB)))
2970 return true;
2971 return false;
2972 }
2973
2974 static void unix_stats_print(struct sockstat *s, struct filter *f)
2975 {
2976 char port_name[30] = {};
2977
2978 sock_state_print(s);
2979
2980 sock_addr_print(s->name ?: "*", " ",
2981 int_to_str(s->lport, port_name), NULL);
2982 sock_addr_print(s->peer_name ?: "*", " ",
2983 int_to_str(s->rport, port_name), NULL);
2984
2985 proc_ctx_print(s);
2986 }
2987
2988 static int unix_show_sock(const struct sockaddr_nl *addr, struct nlmsghdr *nlh,
2989 void *arg)
2990 {
2991 struct filter *f = (struct filter *)arg;
2992 struct unix_diag_msg *r = NLMSG_DATA(nlh);
2993 struct rtattr *tb[UNIX_DIAG_MAX+1];
2994 char name[128];
2995 struct sockstat stat = { .name = "*", .peer_name = "*" };
2996
2997 parse_rtattr(tb, UNIX_DIAG_MAX, (struct rtattr *)(r+1),
2998 nlh->nlmsg_len - NLMSG_LENGTH(sizeof(*r)));
2999
3000 stat.type = r->udiag_type;
3001 stat.state = r->udiag_state;
3002 stat.ino = stat.lport = r->udiag_ino;
3003 stat.local.family = stat.remote.family = AF_UNIX;
3004
3005 if (unix_type_skip(&stat, f))
3006 return 0;
3007
3008 if (tb[UNIX_DIAG_RQLEN]) {
3009 struct unix_diag_rqlen *rql = RTA_DATA(tb[UNIX_DIAG_RQLEN]);
3010
3011 stat.rq = rql->udiag_rqueue;
3012 stat.wq = rql->udiag_wqueue;
3013 }
3014 if (tb[UNIX_DIAG_NAME]) {
3015 int len = RTA_PAYLOAD(tb[UNIX_DIAG_NAME]);
3016
3017 memcpy(name, RTA_DATA(tb[UNIX_DIAG_NAME]), len);
3018 name[len] = '\0';
3019 if (name[0] == '\0') {
3020 int i;
3021 for (i = 0; i < len; i++)
3022 if (name[i] == '\0')
3023 name[i] = '@';
3024 }
3025 stat.name = &name[0];
3026 memcpy(stat.local.data, &stat.name, sizeof(stat.name));
3027 }
3028 if (tb[UNIX_DIAG_PEER])
3029 stat.rport = rta_getattr_u32(tb[UNIX_DIAG_PEER]);
3030
3031 if (f->f && run_ssfilter(f->f, &stat) == 0)
3032 return 0;
3033
3034 unix_stats_print(&stat, f);
3035
3036 if (show_mem)
3037 print_skmeminfo(tb, UNIX_DIAG_MEMINFO);
3038 if (show_details) {
3039 if (tb[UNIX_DIAG_SHUTDOWN]) {
3040 unsigned char mask;
3041
3042 mask = rta_getattr_u8(tb[UNIX_DIAG_SHUTDOWN]);
3043 printf(" %c-%c", mask & 1 ? '-' : '<', mask & 2 ? '-' : '>');
3044 }
3045 }
3046 printf("\n");
3047
3048 return 0;
3049 }
3050
3051 static int handle_netlink_request(struct filter *f, struct nlmsghdr *req,
3052 size_t size, rtnl_filter_t show_one_sock)
3053 {
3054 int ret = -1;
3055 struct rtnl_handle rth;
3056
3057 if (rtnl_open_byproto(&rth, 0, NETLINK_SOCK_DIAG))
3058 return -1;
3059
3060 rth.dump = MAGIC_SEQ;
3061
3062 if (rtnl_send(&rth, req, size) < 0)
3063 goto Exit;
3064
3065 if (rtnl_dump_filter(&rth, show_one_sock, f))
3066 goto Exit;
3067
3068 ret = 0;
3069 Exit:
3070 rtnl_close(&rth);
3071 return ret;
3072 }
3073
3074 static int unix_show_netlink(struct filter *f)
3075 {
3076 DIAG_REQUEST(req, struct unix_diag_req r);
3077
3078 req.r.sdiag_family = AF_UNIX;
3079 req.r.udiag_states = f->states;
3080 req.r.udiag_show = UDIAG_SHOW_NAME | UDIAG_SHOW_PEER | UDIAG_SHOW_RQLEN;
3081 if (show_mem)
3082 req.r.udiag_show |= UDIAG_SHOW_MEMINFO;
3083
3084 return handle_netlink_request(f, &req.nlh, sizeof(req), unix_show_sock);
3085 }
3086
3087 static int unix_show(struct filter *f)
3088 {
3089 FILE *fp;
3090 char buf[256];
3091 char name[128];
3092 int newformat = 0;
3093 int cnt;
3094 struct sockstat *list = NULL;
3095 const int unix_state_map[] = { SS_CLOSE, SS_SYN_SENT,
3096 SS_ESTABLISHED, SS_CLOSING };
3097
3098 if (!filter_af_get(f, AF_UNIX))
3099 return 0;
3100
3101 if (!getenv("PROC_NET_UNIX") && !getenv("PROC_ROOT")
3102 && unix_show_netlink(f) == 0)
3103 return 0;
3104
3105 if ((fp = net_unix_open()) == NULL)
3106 return -1;
3107 if (!fgets(buf, sizeof(buf), fp)) {
3108 fclose(fp);
3109 return -1;
3110 }
3111
3112 if (memcmp(buf, "Peer", 4) == 0)
3113 newformat = 1;
3114 cnt = 0;
3115
3116 while (fgets(buf, sizeof(buf), fp)) {
3117 struct sockstat *u, **insp;
3118 int flags;
3119
3120 if (!(u = calloc(1, sizeof(*u))))
3121 break;
3122
3123 if (sscanf(buf, "%x: %x %x %x %x %x %d %s",
3124 &u->rport, &u->rq, &u->wq, &flags, &u->type,
3125 &u->state, &u->ino, name) < 8)
3126 name[0] = 0;
3127
3128 u->lport = u->ino;
3129 u->local.family = u->remote.family = AF_UNIX;
3130
3131 if (flags & (1 << 16)) {
3132 u->state = SS_LISTEN;
3133 } else {
3134 u->state = unix_state_map[u->state-1];
3135 if (u->type == SOCK_DGRAM && u->state == SS_CLOSE && u->rport)
3136 u->state = SS_ESTABLISHED;
3137 }
3138 if (unix_type_skip(u, f) ||
3139 !(f->states & (1 << u->state))) {
3140 free(u);
3141 continue;
3142 }
3143
3144 if (!newformat) {
3145 u->rport = 0;
3146 u->rq = 0;
3147 u->wq = 0;
3148 }
3149
3150 if (name[0]) {
3151 u->name = strdup(name);
3152 if (!u->name)
3153 break;
3154 }
3155
3156 if (u->rport) {
3157 struct sockstat *p;
3158
3159 for (p = list; p; p = p->next) {
3160 if (u->rport == p->lport)
3161 break;
3162 }
3163 if (!p)
3164 u->peer_name = "?";
3165 else
3166 u->peer_name = p->name ? : "*";
3167 }
3168
3169 if (f->f) {
3170 struct sockstat st = {
3171 .local.family = AF_UNIX,
3172 .remote.family = AF_UNIX,
3173 };
3174
3175 memcpy(st.local.data, &u->name, sizeof(u->name));
3176 if (strcmp(u->peer_name, "*"))
3177 memcpy(st.remote.data, &u->peer_name,
3178 sizeof(u->peer_name));
3179 if (run_ssfilter(f->f, &st) == 0) {
3180 free(u->name);
3181 free(u);
3182 continue;
3183 }
3184 }
3185
3186 insp = &list;
3187 while (*insp) {
3188 if (u->type < (*insp)->type ||
3189 (u->type == (*insp)->type &&
3190 u->ino < (*insp)->ino))
3191 break;
3192 insp = &(*insp)->next;
3193 }
3194 u->next = *insp;
3195 *insp = u;
3196
3197 if (++cnt > MAX_UNIX_REMEMBER) {
3198 while (list) {
3199 unix_stats_print(list, f);
3200 printf("\n");
3201
3202 unix_list_drop_first(&list);
3203 }
3204 cnt = 0;
3205 }
3206 }
3207 fclose(fp);
3208 while (list) {
3209 unix_stats_print(list, f);
3210 printf("\n");
3211
3212 unix_list_drop_first(&list);
3213 }
3214
3215 return 0;
3216 }
3217
3218 static int packet_stats_print(struct sockstat *s, const struct filter *f)
3219 {
3220 const char *addr, *port;
3221 char ll_name[16];
3222
3223 s->local.family = s->remote.family = AF_PACKET;
3224
3225 if (f->f) {
3226 s->local.data[0] = s->prot;
3227 if (run_ssfilter(f->f, s) == 0)
3228 return 1;
3229 }
3230
3231 sock_state_print(s);
3232
3233 if (s->prot == 3)
3234 addr = "*";
3235 else
3236 addr = ll_proto_n2a(htons(s->prot), ll_name, sizeof(ll_name));
3237
3238 if (s->iface == 0)
3239 port = "*";
3240 else
3241 port = xll_index_to_name(s->iface);
3242
3243 sock_addr_print(addr, ":", port, NULL);
3244 sock_addr_print("", "*", "", NULL);
3245
3246 proc_ctx_print(s);
3247
3248 if (show_details)
3249 sock_details_print(s);
3250
3251 return 0;
3252 }
3253
3254 static void packet_show_ring(struct packet_diag_ring *ring)
3255 {
3256 printf("blk_size:%d", ring->pdr_block_size);
3257 printf(",blk_nr:%d", ring->pdr_block_nr);
3258 printf(",frm_size:%d", ring->pdr_frame_size);
3259 printf(",frm_nr:%d", ring->pdr_frame_nr);
3260 printf(",tmo:%d", ring->pdr_retire_tmo);
3261 printf(",features:0x%x", ring->pdr_features);
3262 }
3263
3264 static int packet_show_sock(const struct sockaddr_nl *addr,
3265 struct nlmsghdr *nlh, void *arg)
3266 {
3267 const struct filter *f = arg;
3268 struct packet_diag_msg *r = NLMSG_DATA(nlh);
3269 struct packet_diag_info *pinfo = NULL;
3270 struct packet_diag_ring *ring_rx = NULL, *ring_tx = NULL;
3271 struct rtattr *tb[PACKET_DIAG_MAX+1];
3272 struct sockstat stat = {};
3273 uint32_t fanout = 0;
3274 bool has_fanout = false;
3275
3276 parse_rtattr(tb, PACKET_DIAG_MAX, (struct rtattr *)(r+1),
3277 nlh->nlmsg_len - NLMSG_LENGTH(sizeof(*r)));
3278
3279 /* use /proc/net/packet if all info are not available */
3280 if (!tb[PACKET_DIAG_MEMINFO])
3281 return -1;
3282
3283 stat.type = r->pdiag_type;
3284 stat.prot = r->pdiag_num;
3285 stat.ino = r->pdiag_ino;
3286 stat.state = SS_CLOSE;
3287 stat.sk = cookie_sk_get(&r->pdiag_cookie[0]);
3288
3289 if (tb[PACKET_DIAG_MEMINFO]) {
3290 __u32 *skmeminfo = RTA_DATA(tb[PACKET_DIAG_MEMINFO]);
3291
3292 stat.rq = skmeminfo[SK_MEMINFO_RMEM_ALLOC];
3293 }
3294
3295 if (tb[PACKET_DIAG_INFO]) {
3296 pinfo = RTA_DATA(tb[PACKET_DIAG_INFO]);
3297 stat.lport = stat.iface = pinfo->pdi_index;
3298 }
3299
3300 if (tb[PACKET_DIAG_UID])
3301 stat.uid = rta_getattr_u32(tb[PACKET_DIAG_UID]);
3302
3303 if (tb[PACKET_DIAG_RX_RING])
3304 ring_rx = RTA_DATA(tb[PACKET_DIAG_RX_RING]);
3305
3306 if (tb[PACKET_DIAG_TX_RING])
3307 ring_tx = RTA_DATA(tb[PACKET_DIAG_TX_RING]);
3308
3309 if (tb[PACKET_DIAG_FANOUT]) {
3310 has_fanout = true;
3311 fanout = rta_getattr_u32(tb[PACKET_DIAG_FANOUT]);
3312 }
3313
3314 if (packet_stats_print(&stat, f))
3315 return 0;
3316
3317 if (show_details) {
3318 if (pinfo) {
3319 printf("\n\tver:%d", pinfo->pdi_version);
3320 printf(" cpy_thresh:%d", pinfo->pdi_copy_thresh);
3321 printf(" flags( ");
3322 if (pinfo->pdi_flags & PDI_RUNNING)
3323 printf("running");
3324 if (pinfo->pdi_flags & PDI_AUXDATA)
3325 printf(" auxdata");
3326 if (pinfo->pdi_flags & PDI_ORIGDEV)
3327 printf(" origdev");
3328 if (pinfo->pdi_flags & PDI_VNETHDR)
3329 printf(" vnethdr");
3330 if (pinfo->pdi_flags & PDI_LOSS)
3331 printf(" loss");
3332 if (!pinfo->pdi_flags)
3333 printf("0");
3334 printf(" )");
3335 }
3336 if (ring_rx) {
3337 printf("\n\tring_rx(");
3338 packet_show_ring(ring_rx);
3339 printf(")");
3340 }
3341 if (ring_tx) {
3342 printf("\n\tring_tx(");
3343 packet_show_ring(ring_tx);
3344 printf(")");
3345 }
3346 if (has_fanout) {
3347 uint16_t type = (fanout >> 16) & 0xffff;
3348
3349 printf("\n\tfanout(");
3350 printf("id:%d,", fanout & 0xffff);
3351 printf("type:");
3352
3353 if (type == 0)
3354 printf("hash");
3355 else if (type == 1)
3356 printf("lb");
3357 else if (type == 2)
3358 printf("cpu");
3359 else if (type == 3)
3360 printf("roll");
3361 else if (type == 4)
3362 printf("random");
3363 else if (type == 5)
3364 printf("qm");
3365 else
3366 printf("0x%x", type);
3367
3368 printf(")");
3369 }
3370 }
3371
3372 if (show_bpf && tb[PACKET_DIAG_FILTER]) {
3373 struct sock_filter *fil =
3374 RTA_DATA(tb[PACKET_DIAG_FILTER]);
3375 int num = RTA_PAYLOAD(tb[PACKET_DIAG_FILTER]) /
3376 sizeof(struct sock_filter);
3377
3378 printf("\n\tbpf filter (%d): ", num);
3379 while (num) {
3380 printf(" 0x%02x %u %u %u,",
3381 fil->code, fil->jt, fil->jf, fil->k);
3382 num--;
3383 fil++;
3384 }
3385 }
3386 printf("\n");
3387 return 0;
3388 }
3389
3390 static int packet_show_netlink(struct filter *f)
3391 {
3392 DIAG_REQUEST(req, struct packet_diag_req r);
3393
3394 req.r.sdiag_family = AF_PACKET;
3395 req.r.pdiag_show = PACKET_SHOW_INFO | PACKET_SHOW_MEMINFO |
3396 PACKET_SHOW_FILTER | PACKET_SHOW_RING_CFG | PACKET_SHOW_FANOUT;
3397
3398 return handle_netlink_request(f, &req.nlh, sizeof(req), packet_show_sock);
3399 }
3400
3401 static int packet_show_line(char *buf, const struct filter *f, int fam)
3402 {
3403 unsigned long long sk;
3404 struct sockstat stat = {};
3405 int type, prot, iface, state, rq, uid, ino;
3406
3407 sscanf(buf, "%llx %*d %d %x %d %d %u %u %u",
3408 &sk,
3409 &type, &prot, &iface, &state,
3410 &rq, &uid, &ino);
3411
3412 if (stat.type == SOCK_RAW && !(f->dbs&(1<<PACKET_R_DB)))
3413 return 0;
3414 if (stat.type == SOCK_DGRAM && !(f->dbs&(1<<PACKET_DG_DB)))
3415 return 0;
3416
3417 stat.type = type;
3418 stat.prot = prot;
3419 stat.lport = stat.iface = iface;
3420 stat.state = state;
3421 stat.rq = rq;
3422 stat.uid = uid;
3423 stat.ino = ino;
3424 stat.state = SS_CLOSE;
3425
3426 if (packet_stats_print(&stat, f))
3427 return 0;
3428
3429 printf("\n");
3430 return 0;
3431 }
3432
3433 static int packet_show(struct filter *f)
3434 {
3435 FILE *fp;
3436 int rc = 0;
3437
3438 if (!filter_af_get(f, AF_PACKET) || !(f->states & (1 << SS_CLOSE)))
3439 return 0;
3440
3441 if (!getenv("PROC_NET_PACKET") && !getenv("PROC_ROOT") &&
3442 packet_show_netlink(f) == 0)
3443 return 0;
3444
3445 if ((fp = net_packet_open()) == NULL)
3446 return -1;
3447 if (generic_record_read(fp, packet_show_line, f, AF_PACKET))
3448 rc = -1;
3449
3450 fclose(fp);
3451 return rc;
3452 }
3453
3454 static int netlink_show_one(struct filter *f,
3455 int prot, int pid, unsigned int groups,
3456 int state, int dst_pid, unsigned int dst_group,
3457 int rq, int wq,
3458 unsigned long long sk, unsigned long long cb)
3459 {
3460 struct sockstat st;
3461
3462 SPRINT_BUF(prot_buf) = {};
3463 const char *prot_name;
3464 char procname[64] = {};
3465
3466 st.state = SS_CLOSE;
3467 st.rq = rq;
3468 st.wq = wq;
3469 st.local.family = st.remote.family = AF_NETLINK;
3470
3471 if (f->f) {
3472 st.rport = -1;
3473 st.lport = pid;
3474 st.local.data[0] = prot;
3475 if (run_ssfilter(f->f, &st) == 0)
3476 return 1;
3477 }
3478
3479 sock_state_print(&st);
3480
3481 if (resolve_services)
3482 prot_name = nl_proto_n2a(prot, prot_buf, sizeof(prot_buf));
3483 else
3484 prot_name = int_to_str(prot, prot_buf);
3485
3486 if (pid == -1) {
3487 procname[0] = '*';
3488 } else if (resolve_services) {
3489 int done = 0;
3490
3491 if (!pid) {
3492 done = 1;
3493 strncpy(procname, "kernel", 6);
3494 } else if (pid > 0) {
3495 FILE *fp;
3496
3497 snprintf(procname, sizeof(procname), "%s/%d/stat",
3498 getenv("PROC_ROOT") ? : "/proc", pid);
3499 if ((fp = fopen(procname, "r")) != NULL) {
3500 if (fscanf(fp, "%*d (%[^)])", procname) == 1) {
3501 snprintf(procname+strlen(procname),
3502 sizeof(procname)-strlen(procname),
3503 "/%d", pid);
3504 done = 1;
3505 }
3506 fclose(fp);
3507 }
3508 }
3509 if (!done)
3510 int_to_str(pid, procname);
3511 } else {
3512 int_to_str(pid, procname);
3513 }
3514
3515 sock_addr_print(prot_name, ":", procname, NULL);
3516
3517 if (state == NETLINK_CONNECTED) {
3518 char dst_group_buf[30];
3519 char dst_pid_buf[30];
3520
3521 sock_addr_print(int_to_str(dst_group, dst_group_buf), ":",
3522 int_to_str(dst_pid, dst_pid_buf), NULL);
3523 } else {
3524 sock_addr_print("", "*", "", NULL);
3525 }
3526
3527 char *pid_context = NULL;
3528
3529 if (show_proc_ctx) {
3530 /* The pid value will either be:
3531 * 0 if destination kernel - show kernel initial context.
3532 * A valid process pid - use getpidcon.
3533 * A unique value allocated by the kernel or netlink user
3534 * to the process - show context as "not available".
3535 */
3536 if (!pid)
3537 security_get_initial_context("kernel", &pid_context);
3538 else if (pid > 0)
3539 getpidcon(pid, &pid_context);
3540
3541 if (pid_context != NULL) {
3542 printf("proc_ctx=%-*s ", serv_width, pid_context);
3543 free(pid_context);
3544 } else {
3545 printf("proc_ctx=%-*s ", serv_width, "unavailable");
3546 }
3547 }
3548
3549 if (show_details) {
3550 printf(" sk=%llx cb=%llx groups=0x%08x", sk, cb, groups);
3551 }
3552 printf("\n");
3553
3554 return 0;
3555 }
3556
3557 static int netlink_show_sock(const struct sockaddr_nl *addr,
3558 struct nlmsghdr *nlh, void *arg)
3559 {
3560 struct filter *f = (struct filter *)arg;
3561 struct netlink_diag_msg *r = NLMSG_DATA(nlh);
3562 struct rtattr *tb[NETLINK_DIAG_MAX+1];
3563 int rq = 0, wq = 0;
3564 unsigned long groups = 0;
3565
3566 parse_rtattr(tb, NETLINK_DIAG_MAX, (struct rtattr *)(r+1),
3567 nlh->nlmsg_len - NLMSG_LENGTH(sizeof(*r)));
3568
3569 if (tb[NETLINK_DIAG_GROUPS] && RTA_PAYLOAD(tb[NETLINK_DIAG_GROUPS]))
3570 groups = *(unsigned long *) RTA_DATA(tb[NETLINK_DIAG_GROUPS]);
3571
3572 if (tb[NETLINK_DIAG_MEMINFO]) {
3573 const __u32 *skmeminfo;
3574
3575 skmeminfo = RTA_DATA(tb[NETLINK_DIAG_MEMINFO]);
3576
3577 rq = skmeminfo[SK_MEMINFO_RMEM_ALLOC];
3578 wq = skmeminfo[SK_MEMINFO_WMEM_ALLOC];
3579 }
3580
3581 if (netlink_show_one(f, r->ndiag_protocol, r->ndiag_portid, groups,
3582 r->ndiag_state, r->ndiag_dst_portid, r->ndiag_dst_group,
3583 rq, wq, 0, 0)) {
3584 return 0;
3585 }
3586
3587 if (show_mem) {
3588 printf("\t");
3589 print_skmeminfo(tb, NETLINK_DIAG_MEMINFO);
3590 printf("\n");
3591 }
3592
3593 return 0;
3594 }
3595
3596 static int netlink_show_netlink(struct filter *f)
3597 {
3598 DIAG_REQUEST(req, struct netlink_diag_req r);
3599
3600 req.r.sdiag_family = AF_NETLINK;
3601 req.r.sdiag_protocol = NDIAG_PROTO_ALL;
3602 req.r.ndiag_show = NDIAG_SHOW_GROUPS | NDIAG_SHOW_MEMINFO;
3603
3604 return handle_netlink_request(f, &req.nlh, sizeof(req), netlink_show_sock);
3605 }
3606
3607 static int netlink_show(struct filter *f)
3608 {
3609 FILE *fp;
3610 char buf[256];
3611 int prot, pid;
3612 unsigned int groups;
3613 int rq, wq, rc;
3614 unsigned long long sk, cb;
3615
3616 if (!filter_af_get(f, AF_NETLINK) || !(f->states & (1 << SS_CLOSE)))
3617 return 0;
3618
3619 if (!getenv("PROC_NET_NETLINK") && !getenv("PROC_ROOT") &&
3620 netlink_show_netlink(f) == 0)
3621 return 0;
3622
3623 if ((fp = net_netlink_open()) == NULL)
3624 return -1;
3625 if (!fgets(buf, sizeof(buf), fp)) {
3626 fclose(fp);
3627 return -1;
3628 }
3629
3630 while (fgets(buf, sizeof(buf), fp)) {
3631 sscanf(buf, "%llx %d %d %x %d %d %llx %d",
3632 &sk,
3633 &prot, &pid, &groups, &rq, &wq, &cb, &rc);
3634
3635 netlink_show_one(f, prot, pid, groups, 0, 0, 0, rq, wq, sk, cb);
3636 }
3637
3638 fclose(fp);
3639 return 0;
3640 }
3641
3642 struct sock_diag_msg {
3643 __u8 sdiag_family;
3644 };
3645
3646 static int generic_show_sock(const struct sockaddr_nl *addr,
3647 struct nlmsghdr *nlh, void *arg)
3648 {
3649 struct sock_diag_msg *r = NLMSG_DATA(nlh);
3650 struct inet_diag_arg inet_arg = { .f = arg, .protocol = IPPROTO_MAX };
3651
3652 switch (r->sdiag_family) {
3653 case AF_INET:
3654 case AF_INET6:
3655 return show_one_inet_sock(addr, nlh, &inet_arg);
3656 case AF_UNIX:
3657 return unix_show_sock(addr, nlh, arg);
3658 case AF_PACKET:
3659 return packet_show_sock(addr, nlh, arg);
3660 case AF_NETLINK:
3661 return netlink_show_sock(addr, nlh, arg);
3662 default:
3663 return -1;
3664 }
3665 }
3666
3667 static int handle_follow_request(struct filter *f)
3668 {
3669 int ret = 0;
3670 int groups = 0;
3671 struct rtnl_handle rth;
3672
3673 if (f->families & (1 << AF_INET) && f->dbs & (1 << TCP_DB))
3674 groups |= 1 << (SKNLGRP_INET_TCP_DESTROY - 1);
3675 if (f->families & (1 << AF_INET) && f->dbs & (1 << UDP_DB))
3676 groups |= 1 << (SKNLGRP_INET_UDP_DESTROY - 1);
3677 if (f->families & (1 << AF_INET6) && f->dbs & (1 << TCP_DB))
3678 groups |= 1 << (SKNLGRP_INET6_TCP_DESTROY - 1);
3679 if (f->families & (1 << AF_INET6) && f->dbs & (1 << UDP_DB))
3680 groups |= 1 << (SKNLGRP_INET6_UDP_DESTROY - 1);
3681
3682 if (groups == 0)
3683 return -1;
3684
3685 if (rtnl_open_byproto(&rth, groups, NETLINK_SOCK_DIAG))
3686 return -1;
3687
3688 rth.dump = 0;
3689 rth.local.nl_pid = 0;
3690
3691 if (rtnl_dump_filter(&rth, generic_show_sock, f))
3692 ret = -1;
3693
3694 rtnl_close(&rth);
3695 return ret;
3696 }
3697
3698 static int get_snmp_int(char *proto, char *key, int *result)
3699 {
3700 char buf[1024];
3701 FILE *fp;
3702 int protolen = strlen(proto);
3703 int keylen = strlen(key);
3704
3705 *result = 0;
3706
3707 if ((fp = net_snmp_open()) == NULL)
3708 return -1;
3709
3710 while (fgets(buf, sizeof(buf), fp) != NULL) {
3711 char *p = buf;
3712 int pos = 0;
3713
3714 if (memcmp(buf, proto, protolen))
3715 continue;
3716 while ((p = strchr(p, ' ')) != NULL) {
3717 pos++;
3718 p++;
3719 if (memcmp(p, key, keylen) == 0 &&
3720 (p[keylen] == ' ' || p[keylen] == '\n'))
3721 break;
3722 }
3723 if (fgets(buf, sizeof(buf), fp) == NULL)
3724 break;
3725 if (memcmp(buf, proto, protolen))
3726 break;
3727 p = buf;
3728 while ((p = strchr(p, ' ')) != NULL) {
3729 p++;
3730 if (--pos == 0) {
3731 sscanf(p, "%d", result);
3732 fclose(fp);
3733 return 0;
3734 }
3735 }
3736 }
3737
3738 fclose(fp);
3739 errno = ESRCH;
3740 return -1;
3741 }
3742
3743
3744 /* Get stats from sockstat */
3745
3746 struct ssummary {
3747 int socks;
3748 int tcp_mem;
3749 int tcp_total;
3750 int tcp_orphans;
3751 int tcp_tws;
3752 int tcp4_hashed;
3753 int udp4;
3754 int raw4;
3755 int frag4;
3756 int frag4_mem;
3757 int tcp6_hashed;
3758 int udp6;
3759 int raw6;
3760 int frag6;
3761 int frag6_mem;
3762 };
3763
3764 static void get_sockstat_line(char *line, struct ssummary *s)
3765 {
3766 char id[256], rem[256];
3767
3768 if (sscanf(line, "%[^ ] %[^\n]\n", id, rem) != 2)
3769 return;
3770
3771 if (strcmp(id, "sockets:") == 0)
3772 sscanf(rem, "%*s%d", &s->socks);
3773 else if (strcmp(id, "UDP:") == 0)
3774 sscanf(rem, "%*s%d", &s->udp4);
3775 else if (strcmp(id, "UDP6:") == 0)
3776 sscanf(rem, "%*s%d", &s->udp6);
3777 else if (strcmp(id, "RAW:") == 0)
3778 sscanf(rem, "%*s%d", &s->raw4);
3779 else if (strcmp(id, "RAW6:") == 0)
3780 sscanf(rem, "%*s%d", &s->raw6);
3781 else if (strcmp(id, "TCP6:") == 0)
3782 sscanf(rem, "%*s%d", &s->tcp6_hashed);
3783 else if (strcmp(id, "FRAG:") == 0)
3784 sscanf(rem, "%*s%d%*s%d", &s->frag4, &s->frag4_mem);
3785 else if (strcmp(id, "FRAG6:") == 0)
3786 sscanf(rem, "%*s%d%*s%d", &s->frag6, &s->frag6_mem);
3787 else if (strcmp(id, "TCP:") == 0)
3788 sscanf(rem, "%*s%d%*s%d%*s%d%*s%d%*s%d",
3789 &s->tcp4_hashed,
3790 &s->tcp_orphans, &s->tcp_tws, &s->tcp_total, &s->tcp_mem);
3791 }
3792
3793 static int get_sockstat(struct ssummary *s)
3794 {
3795 char buf[256];
3796 FILE *fp;
3797
3798 memset(s, 0, sizeof(*s));
3799
3800 if ((fp = net_sockstat_open()) == NULL)
3801 return -1;
3802 while (fgets(buf, sizeof(buf), fp) != NULL)
3803 get_sockstat_line(buf, s);
3804 fclose(fp);
3805
3806 if ((fp = net_sockstat6_open()) == NULL)
3807 return 0;
3808 while (fgets(buf, sizeof(buf), fp) != NULL)
3809 get_sockstat_line(buf, s);
3810 fclose(fp);
3811
3812 return 0;
3813 }
3814
3815 static int print_summary(void)
3816 {
3817 struct ssummary s;
3818 int tcp_estab;
3819
3820 if (get_sockstat(&s) < 0)
3821 perror("ss: get_sockstat");
3822 if (get_snmp_int("Tcp:", "CurrEstab", &tcp_estab) < 0)
3823 perror("ss: get_snmpstat");
3824
3825 get_slabstat(&slabstat);
3826
3827 printf("Total: %d (kernel %d)\n", s.socks, slabstat.socks);
3828
3829 printf("TCP: %d (estab %d, closed %d, orphaned %d, synrecv %d, timewait %d/%d), ports %d\n",
3830 s.tcp_total + slabstat.tcp_syns + s.tcp_tws,
3831 tcp_estab,
3832 s.tcp_total - (s.tcp4_hashed+s.tcp6_hashed-s.tcp_tws),
3833 s.tcp_orphans,
3834 slabstat.tcp_syns,
3835 s.tcp_tws, slabstat.tcp_tws,
3836 slabstat.tcp_ports
3837 );
3838
3839 printf("\n");
3840 printf("Transport Total IP IPv6\n");
3841 printf("* %-9d %-9s %-9s\n", slabstat.socks, "-", "-");
3842 printf("RAW %-9d %-9d %-9d\n", s.raw4+s.raw6, s.raw4, s.raw6);
3843 printf("UDP %-9d %-9d %-9d\n", s.udp4+s.udp6, s.udp4, s.udp6);
3844 printf("TCP %-9d %-9d %-9d\n", s.tcp4_hashed+s.tcp6_hashed, s.tcp4_hashed, s.tcp6_hashed);
3845 printf("INET %-9d %-9d %-9d\n",
3846 s.raw4+s.udp4+s.tcp4_hashed+
3847 s.raw6+s.udp6+s.tcp6_hashed,
3848 s.raw4+s.udp4+s.tcp4_hashed,
3849 s.raw6+s.udp6+s.tcp6_hashed);
3850 printf("FRAG %-9d %-9d %-9d\n", s.frag4+s.frag6, s.frag4, s.frag6);
3851
3852 printf("\n");
3853
3854 return 0;
3855 }
3856
3857 static void _usage(FILE *dest)
3858 {
3859 fprintf(dest,
3860 "Usage: ss [ OPTIONS ]\n"
3861 " ss [ OPTIONS ] [ FILTER ]\n"
3862 " -h, --help this message\n"
3863 " -V, --version output version information\n"
3864 " -n, --numeric don't resolve service names\n"
3865 " -r, --resolve resolve host names\n"
3866 " -a, --all display all sockets\n"
3867 " -l, --listening display listening sockets\n"
3868 " -o, --options show timer information\n"
3869 " -e, --extended show detailed socket information\n"
3870 " -m, --memory show socket memory usage\n"
3871 " -p, --processes show process using socket\n"
3872 " -i, --info show internal TCP information\n"
3873 " -s, --summary show socket usage summary\n"
3874 " -b, --bpf show bpf filter socket information\n"
3875 " -E, --events continually display sockets as they are destroyed\n"
3876 " -Z, --context display process SELinux security contexts\n"
3877 " -z, --contexts display process and socket SELinux security contexts\n"
3878 " -N, --net switch to the specified network namespace name\n"
3879 "\n"
3880 " -4, --ipv4 display only IP version 4 sockets\n"
3881 " -6, --ipv6 display only IP version 6 sockets\n"
3882 " -0, --packet display PACKET sockets\n"
3883 " -t, --tcp display only TCP sockets\n"
3884 " -S, --sctp display only SCTP sockets\n"
3885 " -u, --udp display only UDP sockets\n"
3886 " -d, --dccp display only DCCP sockets\n"
3887 " -w, --raw display only RAW sockets\n"
3888 " -x, --unix display only Unix domain sockets\n"
3889 " -f, --family=FAMILY display sockets of type FAMILY\n"
3890 " FAMILY := {inet|inet6|link|unix|netlink|help}\n"
3891 "\n"
3892 " -K, --kill forcibly close sockets, display what was closed\n"
3893 " -H, --no-header Suppress header line\n"
3894 "\n"
3895 " -A, --query=QUERY, --socket=QUERY\n"
3896 " QUERY := {all|inet|tcp|udp|raw|unix|unix_dgram|unix_stream|unix_seqpacket|packet|netlink}[,QUERY]\n"
3897 "\n"
3898 " -D, --diag=FILE Dump raw information about TCP sockets to FILE\n"
3899 " -F, --filter=FILE read filter information from FILE\n"
3900 " FILTER := [ state STATE-FILTER ] [ EXPRESSION ]\n"
3901 " STATE-FILTER := {all|connected|synchronized|bucket|big|TCP-STATES}\n"
3902 " TCP-STATES := {established|syn-sent|syn-recv|fin-wait-{1,2}|time-wait|closed|close-wait|last-ack|listen|closing}\n"
3903 " connected := {established|syn-sent|syn-recv|fin-wait-{1,2}|time-wait|close-wait|last-ack|closing}\n"
3904 " synchronized := {established|syn-recv|fin-wait-{1,2}|time-wait|close-wait|last-ack|closing}\n"
3905 " bucket := {syn-recv|time-wait}\n"
3906 " big := {established|syn-sent|fin-wait-{1,2}|closed|close-wait|last-ack|listen|closing}\n"
3907 );
3908 }
3909
3910 static void help(void) __attribute__((noreturn));
3911 static void help(void)
3912 {
3913 _usage(stdout);
3914 exit(0);
3915 }
3916
3917 static void usage(void) __attribute__((noreturn));
3918 static void usage(void)
3919 {
3920 _usage(stderr);
3921 exit(-1);
3922 }
3923
3924
3925 static int scan_state(const char *state)
3926 {
3927 static const char * const sstate_namel[] = {
3928 "UNKNOWN",
3929 [SS_ESTABLISHED] = "established",
3930 [SS_SYN_SENT] = "syn-sent",
3931 [SS_SYN_RECV] = "syn-recv",
3932 [SS_FIN_WAIT1] = "fin-wait-1",
3933 [SS_FIN_WAIT2] = "fin-wait-2",
3934 [SS_TIME_WAIT] = "time-wait",
3935 [SS_CLOSE] = "unconnected",
3936 [SS_CLOSE_WAIT] = "close-wait",
3937 [SS_LAST_ACK] = "last-ack",
3938 [SS_LISTEN] = "listening",
3939 [SS_CLOSING] = "closing",
3940 };
3941 int i;
3942
3943 if (strcasecmp(state, "close") == 0 ||
3944 strcasecmp(state, "closed") == 0)
3945 return (1<<SS_CLOSE);
3946 if (strcasecmp(state, "syn-rcv") == 0)
3947 return (1<<SS_SYN_RECV);
3948 if (strcasecmp(state, "established") == 0)
3949 return (1<<SS_ESTABLISHED);
3950 if (strcasecmp(state, "all") == 0)
3951 return SS_ALL;
3952 if (strcasecmp(state, "connected") == 0)
3953 return SS_ALL & ~((1<<SS_CLOSE)|(1<<SS_LISTEN));
3954 if (strcasecmp(state, "synchronized") == 0)
3955 return SS_ALL & ~((1<<SS_CLOSE)|(1<<SS_LISTEN)|(1<<SS_SYN_SENT));
3956 if (strcasecmp(state, "bucket") == 0)
3957 return (1<<SS_SYN_RECV)|(1<<SS_TIME_WAIT);
3958 if (strcasecmp(state, "big") == 0)
3959 return SS_ALL & ~((1<<SS_SYN_RECV)|(1<<SS_TIME_WAIT));
3960 for (i = 0; i < SS_MAX; i++) {
3961 if (strcasecmp(state, sstate_namel[i]) == 0)
3962 return (1<<i);
3963 }
3964
3965 fprintf(stderr, "ss: wrong state name: %s\n", state);
3966 exit(-1);
3967 }
3968
3969 static const struct option long_opts[] = {
3970 { "numeric", 0, 0, 'n' },
3971 { "resolve", 0, 0, 'r' },
3972 { "options", 0, 0, 'o' },
3973 { "extended", 0, 0, 'e' },
3974 { "memory", 0, 0, 'm' },
3975 { "info", 0, 0, 'i' },
3976 { "processes", 0, 0, 'p' },
3977 { "bpf", 0, 0, 'b' },
3978 { "events", 0, 0, 'E' },
3979 { "dccp", 0, 0, 'd' },
3980 { "tcp", 0, 0, 't' },
3981 { "sctp", 0, 0, 'S' },
3982 { "udp", 0, 0, 'u' },
3983 { "raw", 0, 0, 'w' },
3984 { "unix", 0, 0, 'x' },
3985 { "all", 0, 0, 'a' },
3986 { "listening", 0, 0, 'l' },
3987 { "ipv4", 0, 0, '4' },
3988 { "ipv6", 0, 0, '6' },
3989 { "packet", 0, 0, '0' },
3990 { "family", 1, 0, 'f' },
3991 { "socket", 1, 0, 'A' },
3992 { "query", 1, 0, 'A' },
3993 { "summary", 0, 0, 's' },
3994 { "diag", 1, 0, 'D' },
3995 { "filter", 1, 0, 'F' },
3996 { "version", 0, 0, 'V' },
3997 { "help", 0, 0, 'h' },
3998 { "context", 0, 0, 'Z' },
3999 { "contexts", 0, 0, 'z' },
4000 { "net", 1, 0, 'N' },
4001 { "kill", 0, 0, 'K' },
4002 { "no-header", 0, 0, 'H' },
4003 { 0 }
4004
4005 };
4006
4007 int main(int argc, char *argv[])
4008 {
4009 int saw_states = 0;
4010 int saw_query = 0;
4011 int do_summary = 0;
4012 const char *dump_tcpdiag = NULL;
4013 FILE *filter_fp = NULL;
4014 int ch;
4015 int state_filter = 0;
4016 int addrp_width, screen_width = 80;
4017
4018 while ((ch = getopt_long(argc, argv,
4019 "dhaletuwxnro460spbEf:miA:D:F:vVzZN:KHS",
4020 long_opts, NULL)) != EOF) {
4021 switch (ch) {
4022 case 'n':
4023 resolve_services = 0;
4024 break;
4025 case 'r':
4026 resolve_hosts = 1;
4027 break;
4028 case 'o':
4029 show_options = 1;
4030 break;
4031 case 'e':
4032 show_options = 1;
4033 show_details++;
4034 break;
4035 case 'm':
4036 show_mem = 1;
4037 break;
4038 case 'i':
4039 show_tcpinfo = 1;
4040 break;
4041 case 'p':
4042 show_users++;
4043 user_ent_hash_build();
4044 break;
4045 case 'b':
4046 show_options = 1;
4047 show_bpf++;
4048 break;
4049 case 'E':
4050 follow_events = 1;
4051 break;
4052 case 'd':
4053 filter_db_set(&current_filter, DCCP_DB);
4054 break;
4055 case 't':
4056 filter_db_set(&current_filter, TCP_DB);
4057 break;
4058 case 'S':
4059 filter_db_set(&current_filter, SCTP_DB);
4060 break;
4061 case 'u':
4062 filter_db_set(&current_filter, UDP_DB);
4063 break;
4064 case 'w':
4065 filter_db_set(&current_filter, RAW_DB);
4066 break;
4067 case 'x':
4068 filter_af_set(&current_filter, AF_UNIX);
4069 break;
4070 case 'a':
4071 state_filter = SS_ALL;
4072 break;
4073 case 'l':
4074 state_filter = (1 << SS_LISTEN) | (1 << SS_CLOSE);
4075 break;
4076 case '4':
4077 filter_af_set(&current_filter, AF_INET);
4078 break;
4079 case '6':
4080 filter_af_set(&current_filter, AF_INET6);
4081 break;
4082 case '0':
4083 filter_af_set(&current_filter, AF_PACKET);
4084 break;
4085 case 'f':
4086 if (strcmp(optarg, "inet") == 0)
4087 filter_af_set(&current_filter, AF_INET);
4088 else if (strcmp(optarg, "inet6") == 0)
4089 filter_af_set(&current_filter, AF_INET6);
4090 else if (strcmp(optarg, "link") == 0)
4091 filter_af_set(&current_filter, AF_PACKET);
4092 else if (strcmp(optarg, "unix") == 0)
4093 filter_af_set(&current_filter, AF_UNIX);
4094 else if (strcmp(optarg, "netlink") == 0)
4095 filter_af_set(&current_filter, AF_NETLINK);
4096 else if (strcmp(optarg, "help") == 0)
4097 help();
4098 else {
4099 fprintf(stderr, "ss: \"%s\" is invalid family\n",
4100 optarg);
4101 usage();
4102 }
4103 break;
4104 case 'A':
4105 {
4106 char *p, *p1;
4107
4108 if (!saw_query) {
4109 current_filter.dbs = 0;
4110 state_filter = state_filter ?
4111 state_filter : SS_CONN;
4112 saw_query = 1;
4113 do_default = 0;
4114 }
4115 p = p1 = optarg;
4116 do {
4117 if ((p1 = strchr(p, ',')) != NULL)
4118 *p1 = 0;
4119 if (strcmp(p, "all") == 0) {
4120 filter_default_dbs(&current_filter);
4121 } else if (strcmp(p, "inet") == 0) {
4122 filter_db_set(&current_filter, UDP_DB);
4123 filter_db_set(&current_filter, DCCP_DB);
4124 filter_db_set(&current_filter, TCP_DB);
4125 filter_db_set(&current_filter, SCTP_DB);
4126 filter_db_set(&current_filter, RAW_DB);
4127 } else if (strcmp(p, "udp") == 0) {
4128 filter_db_set(&current_filter, UDP_DB);
4129 } else if (strcmp(p, "dccp") == 0) {
4130 filter_db_set(&current_filter, DCCP_DB);
4131 } else if (strcmp(p, "tcp") == 0) {
4132 filter_db_set(&current_filter, TCP_DB);
4133 } else if (strcmp(p, "sctp") == 0) {
4134 filter_db_set(&current_filter, SCTP_DB);
4135 } else if (strcmp(p, "raw") == 0) {
4136 filter_db_set(&current_filter, RAW_DB);
4137 } else if (strcmp(p, "unix") == 0) {
4138 filter_db_set(&current_filter, UNIX_ST_DB);
4139 filter_db_set(&current_filter, UNIX_DG_DB);
4140 filter_db_set(&current_filter, UNIX_SQ_DB);
4141 } else if (strcasecmp(p, "unix_stream") == 0 ||
4142 strcmp(p, "u_str") == 0) {
4143 filter_db_set(&current_filter, UNIX_ST_DB);
4144 } else if (strcasecmp(p, "unix_dgram") == 0 ||
4145 strcmp(p, "u_dgr") == 0) {
4146 filter_db_set(&current_filter, UNIX_DG_DB);
4147 } else if (strcasecmp(p, "unix_seqpacket") == 0 ||
4148 strcmp(p, "u_seq") == 0) {
4149 filter_db_set(&current_filter, UNIX_SQ_DB);
4150 } else if (strcmp(p, "packet") == 0) {
4151 filter_db_set(&current_filter, PACKET_R_DB);
4152 filter_db_set(&current_filter, PACKET_DG_DB);
4153 } else if (strcmp(p, "packet_raw") == 0 ||
4154 strcmp(p, "p_raw") == 0) {
4155 filter_db_set(&current_filter, PACKET_R_DB);
4156 } else if (strcmp(p, "packet_dgram") == 0 ||
4157 strcmp(p, "p_dgr") == 0) {
4158 filter_db_set(&current_filter, PACKET_DG_DB);
4159 } else if (strcmp(p, "netlink") == 0) {
4160 filter_db_set(&current_filter, NETLINK_DB);
4161 } else {
4162 fprintf(stderr, "ss: \"%s\" is illegal socket table id\n", p);
4163 usage();
4164 }
4165 p = p1 + 1;
4166 } while (p1);
4167 break;
4168 }
4169 case 's':
4170 do_summary = 1;
4171 break;
4172 case 'D':
4173 dump_tcpdiag = optarg;
4174 break;
4175 case 'F':
4176 if (filter_fp) {
4177 fprintf(stderr, "More than one filter file\n");
4178 exit(-1);
4179 }
4180 if (optarg[0] == '-')
4181 filter_fp = stdin;
4182 else
4183 filter_fp = fopen(optarg, "r");
4184 if (!filter_fp) {
4185 perror("fopen filter file");
4186 exit(-1);
4187 }
4188 break;
4189 case 'v':
4190 case 'V':
4191 printf("ss utility, iproute2-ss%s\n", SNAPSHOT);
4192 exit(0);
4193 case 'z':
4194 show_sock_ctx++;
4195 /* fall through */
4196 case 'Z':
4197 if (is_selinux_enabled() <= 0) {
4198 fprintf(stderr, "ss: SELinux is not enabled.\n");
4199 exit(1);
4200 }
4201 show_proc_ctx++;
4202 user_ent_hash_build();
4203 break;
4204 case 'N':
4205 if (netns_switch(optarg))
4206 exit(1);
4207 break;
4208 case 'K':
4209 current_filter.kill = 1;
4210 break;
4211 case 'H':
4212 show_header = 0;
4213 break;
4214 case 'h':
4215 help();
4216 case '?':
4217 default:
4218 usage();
4219 }
4220 }
4221
4222 argc -= optind;
4223 argv += optind;
4224
4225 if (do_summary) {
4226 print_summary();
4227 if (do_default && argc == 0)
4228 exit(0);
4229 }
4230
4231 while (argc > 0) {
4232 if (strcmp(*argv, "state") == 0) {
4233 NEXT_ARG();
4234 if (!saw_states)
4235 state_filter = 0;
4236 state_filter |= scan_state(*argv);
4237 saw_states = 1;
4238 } else if (strcmp(*argv, "exclude") == 0 ||
4239 strcmp(*argv, "excl") == 0) {
4240 NEXT_ARG();
4241 if (!saw_states)
4242 state_filter = SS_ALL;
4243 state_filter &= ~scan_state(*argv);
4244 saw_states = 1;
4245 } else {
4246 break;
4247 }
4248 argc--; argv++;
4249 }
4250
4251 if (do_default) {
4252 state_filter = state_filter ? state_filter : SS_CONN;
4253 filter_default_dbs(&current_filter);
4254 }
4255
4256 filter_states_set(&current_filter, state_filter);
4257 filter_merge_defaults(&current_filter);
4258
4259 if (resolve_services && resolve_hosts &&
4260 (current_filter.dbs & (UNIX_DBM|INET_L4_DBM)))
4261 init_service_resolver();
4262
4263 if (current_filter.dbs == 0) {
4264 fprintf(stderr, "ss: no socket tables to show with such filter.\n");
4265 exit(0);
4266 }
4267 if (current_filter.families == 0) {
4268 fprintf(stderr, "ss: no families to show with such filter.\n");
4269 exit(0);
4270 }
4271 if (current_filter.states == 0) {
4272 fprintf(stderr, "ss: no socket states to show with such filter.\n");
4273 exit(0);
4274 }
4275
4276 if (dump_tcpdiag) {
4277 FILE *dump_fp = stdout;
4278
4279 if (!(current_filter.dbs & (1<<TCP_DB))) {
4280 fprintf(stderr, "ss: tcpdiag dump requested and no tcp in filter.\n");
4281 exit(0);
4282 }
4283 if (dump_tcpdiag[0] != '-') {
4284 dump_fp = fopen(dump_tcpdiag, "w");
4285 if (!dump_tcpdiag) {
4286 perror("fopen dump file");
4287 exit(-1);
4288 }
4289 }
4290 inet_show_netlink(&current_filter, dump_fp, IPPROTO_TCP);
4291 fflush(dump_fp);
4292 exit(0);
4293 }
4294
4295 if (ssfilter_parse(&current_filter.f, argc, argv, filter_fp))
4296 usage();
4297
4298 netid_width = 0;
4299 if (current_filter.dbs&(current_filter.dbs-1))
4300 netid_width = 5;
4301
4302 state_width = 0;
4303 if (current_filter.states&(current_filter.states-1))
4304 state_width = 10;
4305
4306 if (isatty(STDOUT_FILENO)) {
4307 struct winsize w;
4308
4309 if (ioctl(STDOUT_FILENO, TIOCGWINSZ, &w) != -1) {
4310 if (w.ws_col > 0)
4311 screen_width = w.ws_col;
4312 }
4313 }
4314
4315 addrp_width = screen_width;
4316 addrp_width -= netid_width+1;
4317 addrp_width -= state_width+1;
4318 addrp_width -= 14;
4319
4320 if (addrp_width&1) {
4321 if (netid_width)
4322 netid_width++;
4323 else if (state_width)
4324 state_width++;
4325 }
4326
4327 addrp_width /= 2;
4328 addrp_width--;
4329
4330 serv_width = resolve_services ? 7 : 5;
4331
4332 if (addrp_width < 15+serv_width+1)
4333 addrp_width = 15+serv_width+1;
4334
4335 addr_width = addrp_width - serv_width - 1;
4336
4337 if (show_header) {
4338 if (netid_width)
4339 printf("%-*s ", netid_width, "Netid");
4340 if (state_width)
4341 printf("%-*s ", state_width, "State");
4342 printf("%-6s %-6s ", "Recv-Q", "Send-Q");
4343 }
4344
4345 /* Make enough space for the local/remote port field */
4346 addr_width -= 13;
4347 serv_width += 13;
4348
4349 if (show_header) {
4350 printf("%*s:%-*s %*s:%-*s\n",
4351 addr_width, "Local Address", serv_width, "Port",
4352 addr_width, "Peer Address", serv_width, "Port");
4353 }
4354
4355 fflush(stdout);
4356
4357 if (follow_events)
4358 exit(handle_follow_request(&current_filter));
4359
4360 if (current_filter.dbs & (1<<NETLINK_DB))
4361 netlink_show(&current_filter);
4362 if (current_filter.dbs & PACKET_DBM)
4363 packet_show(&current_filter);
4364 if (current_filter.dbs & UNIX_DBM)
4365 unix_show(&current_filter);
4366 if (current_filter.dbs & (1<<RAW_DB))
4367 raw_show(&current_filter);
4368 if (current_filter.dbs & (1<<UDP_DB))
4369 udp_show(&current_filter);
4370 if (current_filter.dbs & (1<<TCP_DB))
4371 tcp_show(&current_filter, IPPROTO_TCP);
4372 if (current_filter.dbs & (1<<DCCP_DB))
4373 tcp_show(&current_filter, IPPROTO_DCCP);
4374 if (current_filter.dbs & (1<<SCTP_DB))
4375 sctp_show(&current_filter);
4376
4377 if (show_users || show_proc_ctx || show_sock_ctx)
4378 user_ent_destroy();
4379
4380 return 0;
4381 }