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