2 * ss.c "sockstat", socket statistics
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.
9 * Authors: Alexey Kuznetsov, <kuznet@ms2.inr.ac.ru>
16 #include <sys/ioctl.h>
17 #include <sys/socket.h>
19 #include <sys/sysmacros.h>
20 #include <netinet/in.h>
24 #include <arpa/inet.h>
35 #include "libnetlink.h"
36 #include "namespace.h"
40 #include <linux/tcp.h>
41 #include <linux/sock_diag.h>
42 #include <linux/inet_diag.h>
43 #include <linux/unix_diag.h>
44 #include <linux/netdevice.h> /* for MAX_ADDR_LEN */
45 #include <linux/filter.h>
46 #include <linux/xdp_diag.h>
47 #include <linux/packet_diag.h>
48 #include <linux/netlink_diag.h>
49 #include <linux/sctp.h>
50 #include <linux/vm_sockets_diag.h>
51 #include <linux/net.h>
52 #include <linux/tipc.h>
53 #include <linux/tipc_netlink.h>
54 #include <linux/tipc_sockets_diag.h>
55 #include <linux/tls.h>
56 #include <linux/mptcp.h>
58 /* AF_VSOCK/PF_VSOCK is only provided since glibc 2.18 */
63 #define AF_VSOCK PF_VSOCK
66 #define MAGIC_SEQ 123456
67 #define BUF_CHUNK (1024 * 1024) /* Buffer chunk allocation size */
68 #define BUF_CHUNKS_MAX 5 /* Maximum number of allocated buffer chunks */
69 #define LEN_ALIGN(x) (((x) + 1) & ~1)
71 #define DIAG_REQUEST(_req, _r) \
73 struct nlmsghdr nlh; \
77 .nlmsg_type = SOCK_DIAG_BY_FAMILY, \
78 .nlmsg_flags = NLM_F_ROOT|NLM_F_MATCH|NLM_F_REQUEST,\
79 .nlmsg_seq = MAGIC_SEQ, \
80 .nlmsg_len = sizeof(_req), \
85 #include <selinux/selinux.h>
87 /* Stubs for SELinux functions */
88 static int is_selinux_enabled(void)
93 static int getpidcon(pid_t pid
, char **context
)
99 static int getfilecon(char *path
, char **context
)
105 static int security_get_initial_context(char *name
, char **context
)
112 int preferred_family
= AF_UNSPEC
;
113 static int show_options
;
115 static int show_users
;
117 static int show_tcpinfo
;
119 static int show_proc_ctx
;
120 static int show_sock_ctx
;
121 static int show_header
= 1;
122 static int follow_events
;
124 static int show_tipcinfo
;
149 const enum col_align align
;
153 int width
; /* Calculated, including additional layout spacing */
154 int max_len
; /* Measured maximum field length in this column */
157 static struct column columns
[] = {
158 { ALIGN_LEFT
, "Netid", "", 0, 0, 0 },
159 { ALIGN_LEFT
, "State", " ", 0, 0, 0 },
160 { ALIGN_LEFT
, "Recv-Q", " ", 0, 0, 0 },
161 { ALIGN_LEFT
, "Send-Q", " ", 0, 0, 0 },
162 { ALIGN_RIGHT
, "Local Address:", " ", 0, 0, 0 },
163 { ALIGN_LEFT
, "Port", "", 0, 0, 0 },
164 { ALIGN_RIGHT
, "Peer Address:", " ", 0, 0, 0 },
165 { ALIGN_LEFT
, "Port", "", 0, 0, 0 },
166 { ALIGN_LEFT
, "Process", "", 0, 0, 0 },
167 { ALIGN_LEFT
, "", "", 0, 0, 0 },
170 static struct column
*current_field
= columns
;
172 /* Output buffer: chained chunks of BUF_CHUNK bytes. Each field is written to
173 * the buffer as a variable size token. A token consists of a 16 bits length
174 * field, followed by a string which is not NULL-terminated.
176 * A new chunk is allocated and linked when the current chunk doesn't have
177 * enough room to store the current token as a whole.
180 struct buf_chunk
*next
; /* Next chained chunk */
181 char *end
; /* Current end of content */
186 uint16_t len
; /* Data length, excluding length descriptor */
191 struct buf_token
*cur
; /* Position of current token in chunk */
192 struct buf_chunk
*head
; /* First chunk */
193 struct buf_chunk
*tail
; /* Current chunk */
194 int chunks
; /* Number of allocated chunks */
197 static const char *TCP_PROTO
= "tcp";
198 static const char *SCTP_PROTO
= "sctp";
199 static const char *UDP_PROTO
= "udp";
200 static const char *RAW_PROTO
= "raw";
201 static const char *dg_proto
;
222 #define PACKET_DBM ((1<<PACKET_DG_DB)|(1<<PACKET_R_DB))
223 #define UNIX_DBM ((1<<UNIX_DG_DB)|(1<<UNIX_ST_DB)|(1<<UNIX_SQ_DB))
224 #define ALL_DB ((1<<MAX_DB)-1)
225 #define INET_L4_DBM ((1<<TCP_DB)|(1<<UDP_DB)|(1<<DCCP_DB)|(1<<SCTP_DB))
226 #define INET_DBM (INET_L4_DBM | (1<<RAW_DB))
227 #define VSOCK_DBM ((1<<VSOCK_ST_DB)|(1<<VSOCK_DG_DB))
246 SCTP_STATE_CLOSED
= 0,
247 SCTP_STATE_COOKIE_WAIT
= 1,
248 SCTP_STATE_COOKIE_ECHOED
= 2,
249 SCTP_STATE_ESTABLISHED
= 3,
250 SCTP_STATE_SHUTDOWN_PENDING
= 4,
251 SCTP_STATE_SHUTDOWN_SENT
= 5,
252 SCTP_STATE_SHUTDOWN_RECEIVED
= 6,
253 SCTP_STATE_SHUTDOWN_ACK_SENT
= 7,
256 #define SS_ALL ((1 << SS_MAX) - 1)
257 #define SS_CONN (SS_ALL & ~((1<<SS_LISTEN)|(1<<SS_CLOSE)|(1<<SS_TIME_WAIT)|(1<<SS_SYN_RECV)))
258 #define TIPC_SS_CONN ((1<<SS_ESTABLISHED)|(1<<SS_LISTEN)|(1<<SS_CLOSE))
260 #include "ssfilter.h"
268 struct rtnl_handle
*rth_for_killing
;
271 #define FAMILY_MASK(family) ((uint64_t)1 << (family))
273 static const struct filter default_dbs
[MAX_DB
] = {
276 .families
= FAMILY_MASK(AF_INET
) | FAMILY_MASK(AF_INET6
),
280 .families
= FAMILY_MASK(AF_INET
) | FAMILY_MASK(AF_INET6
),
283 .states
= (1 << SS_ESTABLISHED
),
284 .families
= FAMILY_MASK(AF_INET
) | FAMILY_MASK(AF_INET6
),
287 .states
= (1 << SS_ESTABLISHED
),
288 .families
= FAMILY_MASK(AF_INET
) | FAMILY_MASK(AF_INET6
),
291 .states
= (1 << SS_CLOSE
),
292 .families
= FAMILY_MASK(AF_UNIX
),
296 .families
= FAMILY_MASK(AF_UNIX
),
300 .families
= FAMILY_MASK(AF_UNIX
),
303 .states
= (1 << SS_CLOSE
),
304 .families
= FAMILY_MASK(AF_PACKET
),
307 .states
= (1 << SS_CLOSE
),
308 .families
= FAMILY_MASK(AF_PACKET
),
311 .states
= (1 << SS_CLOSE
),
312 .families
= FAMILY_MASK(AF_NETLINK
),
316 .families
= FAMILY_MASK(AF_INET
) | FAMILY_MASK(AF_INET6
),
320 .families
= FAMILY_MASK(AF_VSOCK
),
324 .families
= FAMILY_MASK(AF_VSOCK
),
327 .states
= TIPC_SS_CONN
,
328 .families
= FAMILY_MASK(AF_TIPC
),
331 .states
= (1 << SS_CLOSE
),
332 .families
= FAMILY_MASK(AF_XDP
),
336 static const struct filter default_afs
[AF_MAX
] = {
351 .states
= (1 << SS_CLOSE
),
354 .dbs
= (1 << NETLINK_DB
),
355 .states
= (1 << SS_CLOSE
),
362 .dbs
= (1 << TIPC_DB
),
363 .states
= TIPC_SS_CONN
,
366 .dbs
= (1 << XDP_DB
),
367 .states
= (1 << SS_CLOSE
),
371 static int do_default
= 1;
372 static struct filter current_filter
;
374 static void filter_db_set(struct filter
*f
, int db
, bool enable
)
377 f
->states
|= default_dbs
[db
].states
;
380 f
->dbs
&= ~(1 << db
);
385 static int filter_db_parse(struct filter
*f
, const char *s
)
391 #define ENTRY(name, ...) { #name, { __VA_ARGS__, MAX_DB } }
392 ENTRY(all
, UDP_DB
, DCCP_DB
, TCP_DB
, RAW_DB
,
393 UNIX_ST_DB
, UNIX_DG_DB
, UNIX_SQ_DB
,
394 PACKET_R_DB
, PACKET_DG_DB
, NETLINK_DB
,
395 SCTP_DB
, VSOCK_ST_DB
, VSOCK_DG_DB
, XDP_DB
),
396 ENTRY(inet
, UDP_DB
, DCCP_DB
, TCP_DB
, SCTP_DB
, RAW_DB
),
398 ENTRY(dccp
, DCCP_DB
),
400 ENTRY(sctp
, SCTP_DB
),
402 ENTRY(unix
, UNIX_ST_DB
, UNIX_DG_DB
, UNIX_SQ_DB
),
403 ENTRY(unix_stream
, UNIX_ST_DB
),
404 ENTRY(u_str
, UNIX_ST_DB
), /* alias for unix_stream */
405 ENTRY(unix_dgram
, UNIX_DG_DB
),
406 ENTRY(u_dgr
, UNIX_DG_DB
), /* alias for unix_dgram */
407 ENTRY(unix_seqpacket
, UNIX_SQ_DB
),
408 ENTRY(u_seq
, UNIX_SQ_DB
), /* alias for unix_seqpacket */
409 ENTRY(packet
, PACKET_R_DB
, PACKET_DG_DB
),
410 ENTRY(packet_raw
, PACKET_R_DB
),
411 ENTRY(p_raw
, PACKET_R_DB
), /* alias for packet_raw */
412 ENTRY(packet_dgram
, PACKET_DG_DB
),
413 ENTRY(p_dgr
, PACKET_DG_DB
), /* alias for packet_dgram */
414 ENTRY(netlink
, NETLINK_DB
),
415 ENTRY(vsock
, VSOCK_ST_DB
, VSOCK_DG_DB
),
416 ENTRY(vsock_stream
, VSOCK_ST_DB
),
417 ENTRY(v_str
, VSOCK_ST_DB
), /* alias for vsock_stream */
418 ENTRY(vsock_dgram
, VSOCK_DG_DB
),
419 ENTRY(v_dgr
, VSOCK_DG_DB
), /* alias for vsock_dgram */
431 for (i
= 0; i
< ARRAY_SIZE(db_name_tbl
); i
++) {
432 if (strcmp(s
, db_name_tbl
[i
].name
))
434 for (dbp
= db_name_tbl
[i
].dbs
; *dbp
!= MAX_DB
; dbp
++)
435 filter_db_set(f
, *dbp
, enable
);
441 static void filter_af_set(struct filter
*f
, int af
)
443 f
->states
|= default_afs
[af
].states
;
444 f
->families
|= FAMILY_MASK(af
);
446 preferred_family
= af
;
449 static int filter_af_get(struct filter
*f
, int af
)
451 return !!(f
->families
& FAMILY_MASK(af
));
454 static void filter_states_set(struct filter
*f
, int states
)
460 static void filter_merge_defaults(struct filter
*f
)
465 for (db
= 0; db
< MAX_DB
; db
++) {
466 if (!(f
->dbs
& (1 << db
)))
469 if (!(default_dbs
[db
].families
& f
->families
))
470 f
->families
|= default_dbs
[db
].families
;
472 for (af
= 0; af
< AF_MAX
; af
++) {
473 if (!(f
->families
& FAMILY_MASK(af
)))
476 if (!(default_afs
[af
].dbs
& f
->dbs
))
477 f
->dbs
|= default_afs
[af
].dbs
;
481 static FILE *generic_proc_open(const char *env
, const char *name
)
483 const char *p
= getenv(env
);
487 p
= getenv("PROC_ROOT") ? : "/proc";
488 snprintf(store
, sizeof(store
)-1, "%s/%s", p
, name
);
492 return fopen(p
, "r");
494 #define net_tcp_open() generic_proc_open("PROC_NET_TCP", "net/tcp")
495 #define net_tcp6_open() generic_proc_open("PROC_NET_TCP6", "net/tcp6")
496 #define net_udp_open() generic_proc_open("PROC_NET_UDP", "net/udp")
497 #define net_udp6_open() generic_proc_open("PROC_NET_UDP6", "net/udp6")
498 #define net_raw_open() generic_proc_open("PROC_NET_RAW", "net/raw")
499 #define net_raw6_open() generic_proc_open("PROC_NET_RAW6", "net/raw6")
500 #define net_unix_open() generic_proc_open("PROC_NET_UNIX", "net/unix")
501 #define net_packet_open() generic_proc_open("PROC_NET_PACKET", \
503 #define net_netlink_open() generic_proc_open("PROC_NET_NETLINK", \
505 #define net_sockstat_open() generic_proc_open("PROC_NET_SOCKSTAT", \
507 #define net_sockstat6_open() generic_proc_open("PROC_NET_SOCKSTAT6", \
509 #define net_snmp_open() generic_proc_open("PROC_NET_SNMP", "net/snmp")
510 #define ephemeral_ports_open() generic_proc_open("PROC_IP_LOCAL_PORT_RANGE", \
511 "sys/net/ipv4/ip_local_port_range")
514 struct user_ent
*next
;
523 #define USER_ENT_HASH_SIZE 256
524 static struct user_ent
*user_ent_hash
[USER_ENT_HASH_SIZE
];
526 static int user_ent_hashfn(unsigned int ino
)
528 int val
= (ino
>> 24) ^ (ino
>> 16) ^ (ino
>> 8) ^ ino
;
530 return val
& (USER_ENT_HASH_SIZE
- 1);
533 static void user_ent_add(unsigned int ino
, char *process
,
538 struct user_ent
*p
, **pp
;
540 p
= malloc(sizeof(struct user_ent
));
542 fprintf(stderr
, "ss: failed to malloc buffer\n");
549 p
->process
= strdup(process
);
550 p
->process_ctx
= strdup(proc_ctx
);
551 p
->socket_ctx
= strdup(sock_ctx
);
553 pp
= &user_ent_hash
[user_ent_hashfn(ino
)];
558 static void user_ent_destroy(void)
560 struct user_ent
*p
, *p_next
;
563 while (cnt
!= USER_ENT_HASH_SIZE
) {
564 p
= user_ent_hash
[cnt
];
567 free(p
->process_ctx
);
577 static void user_ent_hash_build(void)
579 const char *root
= getenv("PROC_ROOT") ? : "/proc/";
586 const char *no_ctx
= "unavailable";
587 static int user_ent_hash_build_init
;
589 /* If show_users & show_proc_ctx set only do this once */
590 if (user_ent_hash_build_init
!= 0)
593 user_ent_hash_build_init
= 1;
595 strlcpy(name
, root
, sizeof(name
));
597 if (strlen(name
) == 0 || name
[strlen(name
)-1] != '/')
600 nameoff
= strlen(name
);
606 while ((d
= readdir(dir
)) != NULL
) {
614 if (sscanf(d
->d_name
, "%d%c", &pid
, &crap
) != 1)
617 if (getpidcon(pid
, &pid_context
) != 0)
618 pid_context
= strdup(no_ctx
);
620 snprintf(name
+ nameoff
, sizeof(name
) - nameoff
, "%d/fd/", pid
);
622 if ((dir1
= opendir(name
)) == NULL
) {
630 while ((d1
= readdir(dir1
)) != NULL
) {
631 const char *pattern
= "socket:[";
638 if (sscanf(d1
->d_name
, "%d%c", &fd
, &crap
) != 1)
641 snprintf(name
+pos
, sizeof(name
) - pos
, "%d", fd
);
643 link_len
= readlink(name
, lnk
, sizeof(lnk
)-1);
646 lnk
[link_len
] = '\0';
648 if (strncmp(lnk
, pattern
, strlen(pattern
)))
651 sscanf(lnk
, "socket:[%u]", &ino
);
653 snprintf(tmp
, sizeof(tmp
), "%s/%d/fd/%s",
654 root
, pid
, d1
->d_name
);
656 if (getfilecon(tmp
, &sock_context
) <= 0)
657 sock_context
= strdup(no_ctx
);
662 snprintf(tmp
, sizeof(tmp
), "%s/%d/stat",
664 if ((fp
= fopen(tmp
, "r")) != NULL
) {
665 if (fscanf(fp
, "%*d (%[^)])", p
) < 1)
670 user_ent_add(ino
, p
, pid
, fd
,
671 pid_context
, sock_context
);
686 #define ENTRY_BUF_SIZE 512
687 static int find_entry(unsigned int ino
, char **buf
, int type
)
693 int len
, new_buf_len
;
700 p
= user_ent_hash
[user_ent_hashfn(ino
)];
707 ptr
= *buf
+ buf_used
;
710 len
= snprintf(ptr
, buf_len
- buf_used
,
711 "(\"%s\",pid=%d,fd=%d),",
712 p
->process
, p
->pid
, p
->fd
);
715 len
= snprintf(ptr
, buf_len
- buf_used
,
716 "(\"%s\",pid=%d,proc_ctx=%s,fd=%d),",
718 p
->process_ctx
, p
->fd
);
721 len
= snprintf(ptr
, buf_len
- buf_used
,
722 "(\"%s\",pid=%d,proc_ctx=%s,fd=%d,sock_ctx=%s),",
724 p
->process_ctx
, p
->fd
,
728 fprintf(stderr
, "ss: invalid type: %d\n", type
);
732 if (len
< 0 || len
>= buf_len
- buf_used
) {
733 new_buf_len
= buf_len
+ ENTRY_BUF_SIZE
;
734 new_buf
= realloc(*buf
, new_buf_len
);
736 fprintf(stderr
, "ss: failed to malloc buffer\n");
740 buf_len
= new_buf_len
;
752 ptr
= *buf
+ buf_used
;
758 static unsigned long long cookie_sk_get(const uint32_t *cookie
)
760 return (((unsigned long long)cookie
[1] << 31) << 1) | cookie
[0];
763 static const char *sctp_sstate_name
[] = {
764 [SCTP_STATE_CLOSED
] = "CLOSED",
765 [SCTP_STATE_COOKIE_WAIT
] = "COOKIE_WAIT",
766 [SCTP_STATE_COOKIE_ECHOED
] = "COOKIE_ECHOED",
767 [SCTP_STATE_ESTABLISHED
] = "ESTAB",
768 [SCTP_STATE_SHUTDOWN_PENDING
] = "SHUTDOWN_PENDING",
769 [SCTP_STATE_SHUTDOWN_SENT
] = "SHUTDOWN_SENT",
770 [SCTP_STATE_SHUTDOWN_RECEIVED
] = "SHUTDOWN_RECEIVED",
771 [SCTP_STATE_SHUTDOWN_ACK_SENT
] = "ACK_SENT",
774 static const char * const stype_nameg
[] = {
776 [SOCK_STREAM
] = "STREAM",
777 [SOCK_DGRAM
] = "DGRAM",
779 [SOCK_SEQPACKET
] = "SEQPACKET",
783 struct sockstat
*next
;
797 unsigned long long sk
;
804 unsigned int ce_state
;
814 unsigned int timeout
;
817 double rto
, ato
, rtt
, rttvar
;
818 int qack
, ssthresh
, backoff
;
827 unsigned int lastsnd
;
828 unsigned int lastrcv
;
829 unsigned int lastack
;
831 double pacing_rate_max
;
832 double delivery_rate
;
833 unsigned long long bytes_acked
;
834 unsigned long long bytes_received
;
835 unsigned int segs_out
;
836 unsigned int segs_in
;
837 unsigned int data_segs_out
;
838 unsigned int data_segs_in
;
839 unsigned int unacked
;
840 unsigned int retrans
;
841 unsigned int retrans_total
;
844 unsigned int fackets
;
845 unsigned int reordering
;
846 unsigned int not_sent
;
847 unsigned int delivered
;
848 unsigned int delivered_ce
;
849 unsigned int dsack_dups
;
850 unsigned int reord_seen
;
854 unsigned int rcv_ssthresh
;
855 unsigned long long busy_time
;
856 unsigned long long rwnd_limited
;
857 unsigned long long sndbuf_limited
;
858 unsigned long long bytes_sent
;
859 unsigned long long bytes_retrans
;
863 bool has_ecnseen_opt
;
864 bool has_fastopen_opt
;
867 struct dctcpstat
*dctcp
;
868 struct tcp_bbr_info
*bbr_info
;
871 /* SCTP assocs share the same inode number with their parent endpoint. So if we
872 * have seen the inode number before, it must be an assoc instead of the next
874 static bool is_sctp_assoc(struct sockstat
*s
, const char *sock_name
)
876 if (strcmp(sock_name
, "sctp"))
878 if (!sctp_ino
|| sctp_ino
!= s
->ino
)
883 static const char *unix_netid_name(int type
)
896 static const char *proto_name(int protocol
)
916 static const char *vsock_netid_name(int type
)
928 static const char *tipc_netid_name(int type
)
944 /* Allocate and initialize a new buffer chunk */
945 static struct buf_chunk
*buf_chunk_new(void)
947 struct buf_chunk
*new = malloc(BUF_CHUNK
);
954 /* This is also the last block */
957 /* Next token will be stored at the beginning of chunk data area, and
958 * its initial length is zero.
960 buffer
.cur
= (struct buf_token
*)new->data
;
963 new->end
= buffer
.cur
->data
;
970 /* Return available tail room in given chunk */
971 static int buf_chunk_avail(struct buf_chunk
*chunk
)
973 return BUF_CHUNK
- offsetof(struct buf_chunk
, data
) -
974 (chunk
->end
- chunk
->data
);
977 /* Update end pointer and token length, link new chunk if we hit the end of the
978 * current one. Return -EAGAIN if we got a new chunk, caller has to print again.
980 static int buf_update(int len
)
982 struct buf_chunk
*chunk
= buffer
.tail
;
983 struct buf_token
*t
= buffer
.cur
;
985 /* Claim success if new content fits in the current chunk, and anyway
986 * if this is the first token in the chunk: in the latter case,
987 * allocating a new chunk won't help, so we'll just cut the output.
989 if ((len
< buf_chunk_avail(chunk
) && len
!= -1 /* glibc < 2.0.6 */) ||
990 t
== (struct buf_token
*)chunk
->data
) {
991 len
= min(len
, buf_chunk_avail(chunk
));
993 /* Total field length can't exceed 2^16 bytes, cut as needed */
994 len
= min(len
, USHRT_MAX
- t
->len
);
1001 /* Content truncated, time to allocate more */
1002 chunk
->next
= buf_chunk_new();
1004 /* Copy current token over to new chunk, including length descriptor */
1005 memcpy(chunk
->next
->data
, t
, sizeof(t
->len
) + t
->len
);
1006 chunk
->next
->end
+= t
->len
;
1008 /* Discard partially written field in old chunk */
1009 chunk
->end
-= t
->len
+ sizeof(t
->len
);
1014 /* Append content to buffer as part of the current field */
1015 __attribute__((format(printf
, 1, 2)))
1016 static void out(const char *fmt
, ...)
1018 struct column
*f
= current_field
;
1027 buffer
.head
= buf_chunk_new();
1029 again
: /* Append to buffer: if we have a new chunk, print again */
1031 pos
= buffer
.cur
->data
+ buffer
.cur
->len
;
1032 va_start(args
, fmt
);
1034 /* Limit to tail room. If we hit the limit, buf_update() will tell us */
1035 len
= vsnprintf(pos
, buf_chunk_avail(buffer
.tail
), fmt
, args
);
1038 if (buf_update(len
))
1042 static int print_left_spacing(struct column
*f
, int stored
, int printed
)
1046 if (!f
->width
|| f
->align
== ALIGN_LEFT
)
1049 s
= f
->width
- stored
- printed
;
1050 if (f
->align
== ALIGN_CENTER
)
1051 /* If count of total spacing is odd, shift right by one */
1055 return printf("%*c", s
, ' ');
1060 static void print_right_spacing(struct column
*f
, int printed
)
1064 if (!f
->width
|| f
->align
== ALIGN_RIGHT
)
1067 s
= f
->width
- printed
;
1068 if (f
->align
== ALIGN_CENTER
)
1072 printf("%*c", s
, ' ');
1075 /* Done with field: update buffer pointer, start new token after current one */
1076 static void field_flush(struct column
*f
)
1078 struct buf_chunk
*chunk
;
1084 chunk
= buffer
.tail
;
1085 pad
= buffer
.cur
->len
% 2;
1087 if (buffer
.cur
->len
> f
->max_len
)
1088 f
->max_len
= buffer
.cur
->len
;
1090 /* We need a new chunk if we can't store the next length descriptor.
1091 * Mind the gap between end of previous token and next aligned position
1092 * for length descriptor.
1094 if (buf_chunk_avail(chunk
) - pad
< sizeof(buffer
.cur
->len
)) {
1096 chunk
->next
= buf_chunk_new();
1100 buffer
.cur
= (struct buf_token
*)(buffer
.cur
->data
+
1101 LEN_ALIGN(buffer
.cur
->len
));
1102 buffer
.cur
->len
= 0;
1103 buffer
.tail
->end
= buffer
.cur
->data
;
1106 static int field_is_last(struct column
*f
)
1108 return f
- columns
== COL_MAX
- 1;
1111 /* Get the next available token in the buffer starting from the current token */
1112 static struct buf_token
*buf_token_next(struct buf_token
*cur
)
1114 struct buf_chunk
*chunk
= buffer
.tail
;
1116 /* If we reached the end of chunk contents, get token from next chunk */
1117 if (cur
->data
+ LEN_ALIGN(cur
->len
) == chunk
->end
) {
1118 buffer
.tail
= chunk
= chunk
->next
;
1119 return chunk
? (struct buf_token
*)chunk
->data
: NULL
;
1122 return (struct buf_token
*)(cur
->data
+ LEN_ALIGN(cur
->len
));
1125 /* Free up all allocated buffer chunks */
1126 static void buf_free_all(void)
1128 struct buf_chunk
*tmp
;
1130 for (buffer
.tail
= buffer
.head
; buffer
.tail
; ) {
1132 buffer
.tail
= buffer
.tail
->next
;
1139 /* Get current screen width, returns -1 if TIOCGWINSZ fails */
1140 static int render_screen_width(void)
1144 if (isatty(STDOUT_FILENO
)) {
1147 if (ioctl(STDOUT_FILENO
, TIOCGWINSZ
, &w
) != -1) {
1156 /* Calculate column width from contents length. If columns don't fit on one
1157 * line, break them into the least possible amount of lines and keep them
1158 * aligned across lines. Available screen space is equally spread between fields
1159 * as additional spacing.
1161 static void render_calc_width(void)
1163 int screen_width
, first
, len
= 0, linecols
= 0;
1164 struct column
*c
, *eol
= columns
- 1;
1165 bool compact_output
= false;
1167 screen_width
= render_screen_width();
1168 if (screen_width
== -1) {
1169 screen_width
= INT_MAX
;
1170 compact_output
= true;
1173 /* First pass: set width for each column to measured content length */
1174 for (first
= 1, c
= columns
; c
- columns
< COL_MAX
; c
++) {
1178 if (!first
&& c
->max_len
)
1179 c
->width
= c
->max_len
+ strlen(c
->ldelim
);
1181 c
->width
= c
->max_len
;
1183 /* But don't exceed screen size. If we exceed the screen size
1184 * for even a single field, it will just start on a line of its
1185 * own and then naturally wrap.
1187 c
->width
= min(c
->width
, screen_width
);
1193 if (compact_output
) {
1194 /* Compact output, skip extending columns. */
1198 /* Second pass: find out newlines and distribute available spacing */
1199 for (c
= columns
; c
- columns
< COL_MAX
; c
++) {
1200 int pad
, spacing
, rem
, last
;
1209 for (last
= 1, tmp
= c
+ 1; tmp
- columns
< COL_MAX
; tmp
++) {
1216 if (!last
&& len
< screen_width
) {
1217 /* Columns fit on screen so far, nothing to do yet */
1221 if (len
== screen_width
) {
1222 /* Exact fit, just start with new line */
1226 if (len
> screen_width
) {
1227 /* Screen width exceeded: go back one column */
1233 /* Distribute remaining space to columns on this line */
1234 pad
= screen_width
- len
;
1235 spacing
= pad
/ linecols
;
1236 rem
= pad
% linecols
;
1237 for (tmp
= c
; tmp
> eol
; tmp
--) {
1241 tmp
->width
+= spacing
;
1249 /* Line break: reset line counters, mark end-of-line */
1256 /* Render buffered output with spacing and delimiters, then free up buffers */
1257 static void render(void)
1259 struct buf_token
*token
;
1260 int printed
, line_started
= 0;
1266 token
= (struct buf_token
*)buffer
.head
->data
;
1268 /* Ensure end alignment of last token, it wasn't necessarily flushed */
1269 buffer
.tail
->end
+= buffer
.cur
->len
% 2;
1271 render_calc_width();
1273 /* Rewind and replay */
1274 buffer
.tail
= buffer
.head
;
1281 /* Print left delimiter only if we already started a line */
1283 printed
= printf("%s", f
->ldelim
);
1287 /* Print field content from token data with spacing */
1288 printed
+= print_left_spacing(f
, token
->len
, printed
);
1289 printed
+= fwrite(token
->data
, 1, token
->len
, stdout
);
1290 print_right_spacing(f
, printed
);
1292 /* Go to next non-empty field, deal with end-of-line */
1294 if (field_is_last(f
)) {
1301 } while (f
->disabled
);
1303 token
= buf_token_next(token
);
1305 /* Deal with final end-of-line when the last non-empty field printed
1306 * is not the last field.
1312 current_field
= columns
;
1315 /* Move to next field, and render buffer if we reached the maximum number of
1316 * chunks, at the last field in a line.
1318 static void field_next(void)
1320 if (field_is_last(current_field
) && buffer
.chunks
>= BUF_CHUNKS_MAX
) {
1325 field_flush(current_field
);
1326 if (field_is_last(current_field
))
1327 current_field
= columns
;
1332 /* Walk through fields and flush them until we reach the desired one */
1333 static void field_set(enum col_id id
)
1335 while (id
!= current_field
- columns
)
1339 /* Print header for all non-empty columns */
1340 static void print_header(void)
1342 while (!field_is_last(current_field
)) {
1343 if (!current_field
->disabled
)
1344 out("%s", current_field
->header
);
1349 static void sock_state_print(struct sockstat
*s
)
1351 const char *sock_name
;
1352 static const char * const sstate_name
[] = {
1354 [SS_ESTABLISHED
] = "ESTAB",
1355 [SS_SYN_SENT
] = "SYN-SENT",
1356 [SS_SYN_RECV
] = "SYN-RECV",
1357 [SS_FIN_WAIT1
] = "FIN-WAIT-1",
1358 [SS_FIN_WAIT2
] = "FIN-WAIT-2",
1359 [SS_TIME_WAIT
] = "TIME-WAIT",
1360 [SS_CLOSE
] = "UNCONN",
1361 [SS_CLOSE_WAIT
] = "CLOSE-WAIT",
1362 [SS_LAST_ACK
] = "LAST-ACK",
1363 [SS_LISTEN
] = "LISTEN",
1364 [SS_CLOSING
] = "CLOSING",
1367 switch (s
->local
.family
) {
1369 sock_name
= unix_netid_name(s
->type
);
1373 sock_name
= proto_name(s
->type
);
1376 sock_name
= s
->type
== SOCK_RAW
? "p_raw" : "p_dgr";
1382 sock_name
= tipc_netid_name(s
->type
);
1385 sock_name
= vsock_netid_name(s
->type
);
1391 sock_name
= "unknown";
1394 if (is_sctp_assoc(s
, sock_name
)) {
1395 field_set(COL_STATE
); /* Empty Netid field */
1396 out("`- %s", sctp_sstate_name
[s
->state
]);
1398 field_set(COL_NETID
);
1399 out("%s", sock_name
);
1400 field_set(COL_STATE
);
1401 out("%s", sstate_name
[s
->state
]);
1404 field_set(COL_RECVQ
);
1406 field_set(COL_SENDQ
);
1408 field_set(COL_ADDR
);
1411 static void sock_details_print(struct sockstat
*s
)
1414 out(" uid:%u", s
->uid
);
1416 out(" ino:%u", s
->ino
);
1417 out(" sk:%llx", s
->sk
);
1420 out(" fwmark:0x%x", s
->mark
);
1423 static void sock_addr_print(const char *addr
, char *delim
, const char *port
,
1427 out("%s" "%%" "%s%s", addr
, ifname
, delim
);
1429 out("%s%s", addr
, delim
);
1436 static const char *print_ms_timer(unsigned int timeout
)
1438 static char buf
[64];
1439 int secs
, msecs
, minutes
;
1441 secs
= timeout
/1000;
1444 msecs
= timeout
%1000;
1448 snprintf(buf
, sizeof(buf
)-16, "%dmin", minutes
);
1455 sprintf(buf
+strlen(buf
), "%d%s", secs
, msecs
? "." : "sec");
1458 sprintf(buf
+strlen(buf
), "%03dms", msecs
);
1463 struct scache
*next
;
1469 static struct scache
*rlist
;
1471 static void init_service_resolver(void)
1474 FILE *fp
= popen("/usr/sbin/rpcinfo -p 2>/dev/null", "r");
1479 if (!fgets(buf
, sizeof(buf
), fp
)) {
1483 while (fgets(buf
, sizeof(buf
), fp
) != NULL
) {
1484 unsigned int progn
, port
;
1485 char proto
[128], prog
[128] = "rpc.";
1488 if (sscanf(buf
, "%u %*d %s %u %s",
1489 &progn
, proto
, &port
, prog
+4) != 4)
1492 if (!(c
= malloc(sizeof(*c
))))
1496 c
->name
= strdup(prog
);
1497 if (strcmp(proto
, TCP_PROTO
) == 0)
1498 c
->proto
= TCP_PROTO
;
1499 else if (strcmp(proto
, UDP_PROTO
) == 0)
1500 c
->proto
= UDP_PROTO
;
1501 else if (strcmp(proto
, SCTP_PROTO
) == 0)
1502 c
->proto
= SCTP_PROTO
;
1511 /* Even do not try default linux ephemeral port ranges:
1512 * default /etc/services contains so much of useless crap
1513 * wouldbe "allocated" to this area that resolution
1514 * is really harmful. I shrug each time when seeing
1515 * "socks" or "cfinger" in dumps.
1517 static int is_ephemeral(int port
)
1519 static int min
= 0, max
;
1522 FILE *f
= ephemeral_ports_open();
1524 if (!f
|| fscanf(f
, "%d %d", &min
, &max
) < 2) {
1531 return port
>= min
&& port
<= max
;
1535 static const char *__resolve_service(int port
)
1539 for (c
= rlist
; c
; c
= c
->next
) {
1540 if (c
->port
== port
&& c
->proto
== dg_proto
)
1544 if (!is_ephemeral(port
)) {
1545 static int notfirst
;
1552 se
= getservbyport(htons(port
), dg_proto
);
1560 #define SCACHE_BUCKETS 1024
1561 static struct scache
*cache_htab
[SCACHE_BUCKETS
];
1563 static const char *resolve_service(int port
)
1565 static char buf
[128];
1579 if (dg_proto
== RAW_PROTO
)
1580 return inet_proto_n2a(port
, buf
, sizeof(buf
));
1583 hash
= (port
^(((unsigned long)dg_proto
)>>2)) % SCACHE_BUCKETS
;
1585 for (c
= cache_htab
[hash
]; c
; c
= c
->next
) {
1586 if (c
->port
== port
&& c
->proto
== dg_proto
)
1590 c
= malloc(sizeof(*c
));
1593 res
= __resolve_service(port
);
1595 c
->name
= res
? strdup(res
) : NULL
;
1596 c
->proto
= dg_proto
;
1597 c
->next
= cache_htab
[hash
];
1598 cache_htab
[hash
] = c
;
1605 sprintf(buf
, "%u", port
);
1609 static void inet_addr_print(const inet_prefix
*a
, int port
,
1610 unsigned int ifindex
, bool v6only
)
1613 const char *ap
= buf
;
1614 const char *ifname
= NULL
;
1616 if (a
->family
== AF_INET
) {
1617 ap
= format_host(AF_INET
, 4, a
->data
);
1620 !memcmp(a
->data
, &in6addr_any
, sizeof(in6addr_any
))) {
1624 ap
= format_host(a
->family
, 16, a
->data
);
1626 /* Numeric IPv6 addresses should be bracketed */
1627 if (strchr(ap
, ':')) {
1628 snprintf(buf
, sizeof(buf
),
1636 ifname
= ll_index_to_name(ifindex
);
1638 sock_addr_print(ap
, ":", resolve_service(port
), ifname
);
1647 struct aafilter
*next
;
1650 static int inet2_addr_match(const inet_prefix
*a
, const inet_prefix
*p
,
1653 if (!inet_addr_match(a
, p
, plen
))
1656 /* Cursed "v4 mapped" addresses: v4 mapped socket matches
1657 * pure IPv4 rule, but v4-mapped rule selects only v4-mapped
1659 if (p
->family
== AF_INET
&& a
->family
== AF_INET6
) {
1660 if (a
->data
[0] == 0 && a
->data
[1] == 0 &&
1661 a
->data
[2] == htonl(0xffff)) {
1662 inet_prefix tmp
= *a
;
1664 tmp
.data
[0] = a
->data
[3];
1665 return inet_addr_match(&tmp
, p
, plen
);
1671 static int unix_match(const inet_prefix
*a
, const inet_prefix
*p
)
1673 char *addr
, *pattern
;
1675 memcpy(&addr
, a
->data
, sizeof(addr
));
1676 memcpy(&pattern
, p
->data
, sizeof(pattern
));
1677 if (pattern
== NULL
)
1681 return !fnmatch(pattern
, addr
, 0);
1684 static int run_ssfilter(struct ssfilter
*f
, struct sockstat
*s
)
1689 if (s
->local
.family
== AF_UNIX
) {
1692 memcpy(&p
, s
->local
.data
, sizeof(p
));
1693 return p
== NULL
|| (p
[0] == '@' && strlen(p
) == 6 &&
1694 strspn(p
+1, "0123456789abcdef") == 5);
1696 if (s
->local
.family
== AF_PACKET
)
1697 return s
->lport
== 0 && s
->local
.data
[0] == 0;
1698 if (s
->local
.family
== AF_NETLINK
)
1699 return s
->lport
< 0;
1700 if (s
->local
.family
== AF_VSOCK
)
1701 return s
->lport
> 1023;
1703 return is_ephemeral(s
->lport
);
1707 struct aafilter
*a
= (void *)f
->pred
;
1709 if (a
->addr
.family
== AF_UNIX
)
1710 return unix_match(&s
->remote
, &a
->addr
);
1711 if (a
->port
!= -1 && a
->port
!= s
->rport
)
1713 if (a
->addr
.bitlen
) {
1715 if (!inet2_addr_match(&s
->remote
, &a
->addr
, a
->addr
.bitlen
))
1717 } while ((a
= a
->next
) != NULL
);
1724 struct aafilter
*a
= (void *)f
->pred
;
1726 if (a
->addr
.family
== AF_UNIX
)
1727 return unix_match(&s
->local
, &a
->addr
);
1728 if (a
->port
!= -1 && a
->port
!= s
->lport
)
1730 if (a
->addr
.bitlen
) {
1732 if (!inet2_addr_match(&s
->local
, &a
->addr
, a
->addr
.bitlen
))
1734 } while ((a
= a
->next
) != NULL
);
1741 struct aafilter
*a
= (void *)f
->pred
;
1743 return s
->rport
>= a
->port
;
1747 struct aafilter
*a
= (void *)f
->pred
;
1749 return s
->rport
<= a
->port
;
1753 struct aafilter
*a
= (void *)f
->pred
;
1755 return s
->lport
>= a
->port
;
1759 struct aafilter
*a
= (void *)f
->pred
;
1761 return s
->lport
<= a
->port
;
1765 struct aafilter
*a
= (void *)f
->pred
;
1767 return s
->iface
== a
->iface
;
1771 struct aafilter
*a
= (void *)f
->pred
;
1773 return (s
->mark
& a
->mask
) == a
->mark
;
1775 /* Yup. It is recursion. Sorry. */
1777 return run_ssfilter(f
->pred
, s
) && run_ssfilter(f
->post
, s
);
1779 return run_ssfilter(f
->pred
, s
) || run_ssfilter(f
->post
, s
);
1781 return !run_ssfilter(f
->pred
, s
);
1787 /* Relocate external jumps by reloc. */
1788 static void ssfilter_patch(char *a
, int len
, int reloc
)
1791 struct inet_diag_bc_op
*op
= (struct inet_diag_bc_op
*)a
;
1793 if (op
->no
== len
+4)
1802 static int ssfilter_bytecompile(struct ssfilter
*f
, char **bytecode
)
1807 if (!(*bytecode
= malloc(4))) abort();
1808 ((struct inet_diag_bc_op
*)*bytecode
)[0] = (struct inet_diag_bc_op
){ INET_DIAG_BC_AUTO
, 4, 8 };
1814 struct aafilter
*a
= (void *)f
->pred
;
1817 int code
= (f
->type
== SSF_DCOND
? INET_DIAG_BC_D_COND
: INET_DIAG_BC_S_COND
);
1820 for (b
= a
; b
; b
= b
->next
) {
1821 len
+= 4 + sizeof(struct inet_diag_hostcond
);
1822 if (a
->addr
.family
== AF_INET6
)
1829 if (!(ptr
= malloc(len
))) abort();
1831 for (b
= a
; b
; b
= b
->next
) {
1832 struct inet_diag_bc_op
*op
= (struct inet_diag_bc_op
*)ptr
;
1833 int alen
= (a
->addr
.family
== AF_INET6
? 16 : 4);
1834 int oplen
= alen
+ 4 + sizeof(struct inet_diag_hostcond
);
1835 struct inet_diag_hostcond
*cond
= (struct inet_diag_hostcond
*)(ptr
+4);
1837 *op
= (struct inet_diag_bc_op
){ code
, oplen
, oplen
+4 };
1838 cond
->family
= a
->addr
.family
;
1839 cond
->port
= a
->port
;
1840 cond
->prefix_len
= a
->addr
.bitlen
;
1841 memcpy(cond
->addr
, a
->addr
.data
, alen
);
1844 op
= (struct inet_diag_bc_op
*)ptr
;
1845 *op
= (struct inet_diag_bc_op
){ INET_DIAG_BC_JMP
, 4, len
- (ptr
-*bytecode
)};
1849 return ptr
- *bytecode
;
1853 struct aafilter
*x
= (void *)f
->pred
;
1855 if (!(*bytecode
= malloc(8))) abort();
1856 ((struct inet_diag_bc_op
*)*bytecode
)[0] = (struct inet_diag_bc_op
){ INET_DIAG_BC_D_GE
, 8, 12 };
1857 ((struct inet_diag_bc_op
*)*bytecode
)[1] = (struct inet_diag_bc_op
){ 0, 0, x
->port
};
1862 struct aafilter
*x
= (void *)f
->pred
;
1864 if (!(*bytecode
= malloc(8))) abort();
1865 ((struct inet_diag_bc_op
*)*bytecode
)[0] = (struct inet_diag_bc_op
){ INET_DIAG_BC_D_LE
, 8, 12 };
1866 ((struct inet_diag_bc_op
*)*bytecode
)[1] = (struct inet_diag_bc_op
){ 0, 0, x
->port
};
1871 struct aafilter
*x
= (void *)f
->pred
;
1873 if (!(*bytecode
= malloc(8))) abort();
1874 ((struct inet_diag_bc_op
*)*bytecode
)[0] = (struct inet_diag_bc_op
){ INET_DIAG_BC_S_GE
, 8, 12 };
1875 ((struct inet_diag_bc_op
*)*bytecode
)[1] = (struct inet_diag_bc_op
){ 0, 0, x
->port
};
1880 struct aafilter
*x
= (void *)f
->pred
;
1882 if (!(*bytecode
= malloc(8))) abort();
1883 ((struct inet_diag_bc_op
*)*bytecode
)[0] = (struct inet_diag_bc_op
){ INET_DIAG_BC_S_LE
, 8, 12 };
1884 ((struct inet_diag_bc_op
*)*bytecode
)[1] = (struct inet_diag_bc_op
){ 0, 0, x
->port
};
1890 char *a1
= NULL
, *a2
= NULL
, *a
;
1893 l1
= ssfilter_bytecompile(f
->pred
, &a1
);
1894 l2
= ssfilter_bytecompile(f
->post
, &a2
);
1900 if (!(a
= malloc(l1
+l2
))) abort();
1902 memcpy(a
+l1
, a2
, l2
);
1904 ssfilter_patch(a
, l1
, l2
);
1910 char *a1
= NULL
, *a2
= NULL
, *a
;
1913 l1
= ssfilter_bytecompile(f
->pred
, &a1
);
1914 l2
= ssfilter_bytecompile(f
->post
, &a2
);
1920 if (!(a
= malloc(l1
+l2
+4))) abort();
1922 memcpy(a
+l1
+4, a2
, l2
);
1924 *(struct inet_diag_bc_op
*)(a
+l1
) = (struct inet_diag_bc_op
){ INET_DIAG_BC_JMP
, 4, l2
+4 };
1930 char *a1
= NULL
, *a
;
1933 l1
= ssfilter_bytecompile(f
->pred
, &a1
);
1938 if (!(a
= malloc(l1
+4))) abort();
1941 *(struct inet_diag_bc_op
*)(a
+l1
) = (struct inet_diag_bc_op
){ INET_DIAG_BC_JMP
, 4, 8 };
1947 /* bytecompile for SSF_DEVCOND not supported yet */
1952 struct aafilter
*a
= (void *)f
->pred
;
1954 struct inet_diag_bc_op op
;
1955 struct inet_diag_markcond cond
;
1957 int inslen
= sizeof(struct instr
);
1959 if (!(*bytecode
= malloc(inslen
))) abort();
1960 ((struct instr
*)*bytecode
)[0] = (struct instr
) {
1961 { INET_DIAG_BC_MARK_COND
, inslen
, inslen
+ 4 },
1962 { a
->mark
, a
->mask
},
1972 static int remember_he(struct aafilter
*a
, struct hostent
*he
)
1974 char **ptr
= he
->h_addr_list
;
1978 if (he
->h_addrtype
== AF_INET
)
1980 else if (he
->h_addrtype
== AF_INET6
)
1986 struct aafilter
*b
= a
;
1988 if (a
->addr
.bitlen
) {
1989 if ((b
= malloc(sizeof(*b
))) == NULL
)
1994 memcpy(b
->addr
.data
, *ptr
, len
);
1995 b
->addr
.bytelen
= len
;
1996 b
->addr
.bitlen
= len
*8;
1997 b
->addr
.family
= he
->h_addrtype
;
2004 static int get_dns_host(struct aafilter
*a
, const char *addr
, int fam
)
2006 static int notfirst
;
2015 he
= gethostbyname2(addr
, fam
== AF_UNSPEC
? AF_INET
: fam
);
2017 cnt
= remember_he(a
, he
);
2018 if (fam
== AF_UNSPEC
) {
2019 he
= gethostbyname2(addr
, AF_INET6
);
2021 cnt
+= remember_he(a
, he
);
2026 static int xll_initted
;
2028 static void xll_init(void)
2030 struct rtnl_handle rth
;
2032 if (rtnl_open(&rth
, 0) < 0)
2040 static const char *xll_index_to_name(int index
)
2044 return ll_index_to_name(index
);
2047 static int xll_name_to_index(const char *dev
)
2051 return ll_name_to_index(dev
);
2054 void *parse_devcond(char *name
)
2056 struct aafilter a
= { .iface
= 0 };
2057 struct aafilter
*res
;
2059 a
.iface
= xll_name_to_index(name
);
2064 n
= strtoul(name
, &end
, 0);
2065 if (!end
|| end
== name
|| *end
|| n
> UINT_MAX
)
2071 res
= malloc(sizeof(*res
));
2077 static void vsock_set_inet_prefix(inet_prefix
*a
, __u32 cid
)
2080 .bytelen
= sizeof(cid
),
2083 memcpy(a
->data
, &cid
, sizeof(cid
));
2086 void *parse_hostcond(char *addr
, bool is_port
)
2089 struct aafilter a
= { .port
= -1 };
2090 struct aafilter
*res
;
2091 int fam
= preferred_family
;
2092 struct filter
*f
= ¤t_filter
;
2094 if (fam
== AF_UNIX
|| strncmp(addr
, "unix:", 5) == 0) {
2097 a
.addr
.family
= AF_UNIX
;
2098 if (strncmp(addr
, "unix:", 5) == 0)
2101 a
.addr
.bitlen
= 8*strlen(p
);
2102 memcpy(a
.addr
.data
, &p
, sizeof(p
));
2107 if (fam
== AF_PACKET
|| strncmp(addr
, "link:", 5) == 0) {
2108 a
.addr
.family
= AF_PACKET
;
2110 if (strncmp(addr
, "link:", 5) == 0)
2112 port
= strchr(addr
, ':');
2115 if (port
[1] && strcmp(port
+1, "*")) {
2116 if (get_integer(&a
.port
, port
+1, 0)) {
2117 if ((a
.port
= xll_name_to_index(port
+1)) <= 0)
2122 if (addr
[0] && strcmp(addr
, "*")) {
2126 if (ll_proto_a2n(&tmp
, addr
))
2128 a
.addr
.data
[0] = ntohs(tmp
);
2134 if (fam
== AF_NETLINK
|| strncmp(addr
, "netlink:", 8) == 0) {
2135 a
.addr
.family
= AF_NETLINK
;
2137 if (strncmp(addr
, "netlink:", 8) == 0)
2139 port
= strchr(addr
, ':');
2142 if (port
[1] && strcmp(port
+1, "*")) {
2143 if (get_integer(&a
.port
, port
+1, 0)) {
2144 if (strcmp(port
+1, "kernel") == 0)
2151 if (addr
[0] && strcmp(addr
, "*")) {
2153 if (nl_proto_a2n(&a
.addr
.data
[0], addr
) == -1)
2160 if (fam
== AF_VSOCK
|| strncmp(addr
, "vsock:", 6) == 0) {
2161 __u32 cid
= ~(__u32
)0;
2163 a
.addr
.family
= AF_VSOCK
;
2164 if (strncmp(addr
, "vsock:", 6) == 0)
2170 port
= strchr(addr
, ':');
2177 if (port
&& strcmp(port
, "*") &&
2178 get_u32((__u32
*)&a
.port
, port
, 0))
2181 if (addr
[0] && strcmp(addr
, "*")) {
2183 if (get_u32(&cid
, addr
, 0))
2186 vsock_set_inet_prefix(&a
.addr
, cid
);
2191 if (fam
== AF_INET
|| !strncmp(addr
, "inet:", 5)) {
2193 if (!strncmp(addr
, "inet:", 5))
2195 } else if (fam
== AF_INET6
|| !strncmp(addr
, "inet6:", 6)) {
2197 if (!strncmp(addr
, "inet6:", 6))
2201 /* URL-like literal [] */
2202 if (addr
[0] == '[') {
2204 if ((port
= strchr(addr
, ']')) == NULL
)
2207 } else if (addr
[0] == '*') {
2210 port
= strrchr(strchr(addr
, '/') ? : addr
, ':');
2216 if (port
&& *port
) {
2220 if (*port
&& *port
!= '*') {
2221 if (get_integer(&a
.port
, port
, 0)) {
2222 struct servent
*se1
= NULL
;
2223 struct servent
*se2
= NULL
;
2225 if (current_filter
.dbs
&(1<<UDP_DB
))
2226 se1
= getservbyname(port
, UDP_PROTO
);
2227 if (current_filter
.dbs
&(1<<TCP_DB
))
2228 se2
= getservbyname(port
, TCP_PROTO
);
2229 if (se1
&& se2
&& se1
->s_port
!= se2
->s_port
) {
2230 fprintf(stderr
, "Error: ambiguous port \"%s\".\n", port
);
2236 a
.port
= ntohs(se1
->s_port
);
2240 for (s
= rlist
; s
; s
= s
->next
) {
2241 if ((s
->proto
== UDP_PROTO
&&
2242 (current_filter
.dbs
&(1<<UDP_DB
))) ||
2243 (s
->proto
== TCP_PROTO
&&
2244 (current_filter
.dbs
&(1<<TCP_DB
)))) {
2245 if (s
->name
&& strcmp(s
->name
, port
) == 0) {
2246 if (a
.port
> 0 && a
.port
!= s
->port
) {
2247 fprintf(stderr
, "Error: ambiguous port \"%s\".\n", port
);
2255 fprintf(stderr
, "Error: \"%s\" does not look like a port.\n", port
);
2262 if (!is_port
&& *addr
&& *addr
!= '*') {
2263 if (get_prefix_1(&a
.addr
, addr
, fam
)) {
2264 if (get_dns_host(&a
, addr
, fam
)) {
2265 fprintf(stderr
, "Error: an inet prefix is expected rather than \"%s\".\n", addr
);
2272 if (fam
!= AF_UNSPEC
) {
2273 int states
= f
->states
;
2275 filter_af_set(f
, fam
);
2276 filter_states_set(f
, states
);
2279 res
= malloc(sizeof(*res
));
2281 memcpy(res
, &a
, sizeof(a
));
2285 void *parse_markmask(const char *markmask
)
2287 struct aafilter a
, *res
;
2289 if (strchr(markmask
, '/')) {
2290 if (sscanf(markmask
, "%i/%i", &a
.mark
, &a
.mask
) != 2)
2293 a
.mask
= 0xffffffff;
2294 if (sscanf(markmask
, "%i", &a
.mark
) != 1)
2298 res
= malloc(sizeof(*res
));
2300 memcpy(res
, &a
, sizeof(a
));
2304 static void proc_ctx_print(struct sockstat
*s
)
2308 if (show_proc_ctx
|| show_sock_ctx
) {
2309 if (find_entry(s
->ino
, &buf
,
2310 (show_proc_ctx
& show_sock_ctx
) ?
2311 PROC_SOCK_CTX
: PROC_CTX
) > 0) {
2312 out(" users:(%s)", buf
);
2315 } else if (show_users
) {
2316 if (find_entry(s
->ino
, &buf
, USERS
) > 0) {
2317 out(" users:(%s)", buf
);
2323 static void inet_stats_print(struct sockstat
*s
, bool v6only
)
2325 sock_state_print(s
);
2327 inet_addr_print(&s
->local
, s
->lport
, s
->iface
, v6only
);
2328 inet_addr_print(&s
->remote
, s
->rport
, 0, v6only
);
2333 static int proc_parse_inet_addr(char *loc
, char *rem
, int family
, struct
2336 s
->local
.family
= s
->remote
.family
= family
;
2337 if (family
== AF_INET
) {
2338 sscanf(loc
, "%x:%x", s
->local
.data
, (unsigned *)&s
->lport
);
2339 sscanf(rem
, "%x:%x", s
->remote
.data
, (unsigned *)&s
->rport
);
2340 s
->local
.bytelen
= s
->remote
.bytelen
= 4;
2343 sscanf(loc
, "%08x%08x%08x%08x:%x",
2349 sscanf(rem
, "%08x%08x%08x%08x:%x",
2355 s
->local
.bytelen
= s
->remote
.bytelen
= 16;
2361 static int proc_inet_split_line(char *line
, char **loc
, char **rem
, char **data
)
2365 if ((p
= strchr(line
, ':')) == NULL
)
2369 if ((p
= strchr(*loc
, ':')) == NULL
)
2374 if ((p
= strchr(*rem
, ':')) == NULL
)
2382 static char *sprint_bw(char *buf
, double bw
)
2385 sprintf(buf
, "%.0f", bw
);
2386 else if (bw
> 1000000.)
2387 sprintf(buf
, "%.1fM", bw
/ 1000000.);
2388 else if (bw
> 1000.)
2389 sprintf(buf
, "%.1fK", bw
/ 1000.);
2391 sprintf(buf
, "%g", bw
);
2396 static void sctp_stats_print(struct sctp_info
*s
)
2399 out(" tag:%x", s
->sctpi_tag
);
2401 out(" state:%s", sctp_sstate_name
[s
->sctpi_state
]);
2403 out(" rwnd:%d", s
->sctpi_rwnd
);
2404 if (s
->sctpi_unackdata
)
2405 out(" unackdata:%d", s
->sctpi_unackdata
);
2406 if (s
->sctpi_penddata
)
2407 out(" penddata:%d", s
->sctpi_penddata
);
2408 if (s
->sctpi_instrms
)
2409 out(" instrms:%d", s
->sctpi_instrms
);
2410 if (s
->sctpi_outstrms
)
2411 out(" outstrms:%d", s
->sctpi_outstrms
);
2412 if (s
->sctpi_inqueue
)
2413 out(" inqueue:%d", s
->sctpi_inqueue
);
2414 if (s
->sctpi_outqueue
)
2415 out(" outqueue:%d", s
->sctpi_outqueue
);
2416 if (s
->sctpi_overall_error
)
2417 out(" overerr:%d", s
->sctpi_overall_error
);
2418 if (s
->sctpi_max_burst
)
2419 out(" maxburst:%d", s
->sctpi_max_burst
);
2420 if (s
->sctpi_maxseg
)
2421 out(" maxseg:%d", s
->sctpi_maxseg
);
2422 if (s
->sctpi_peer_rwnd
)
2423 out(" prwnd:%d", s
->sctpi_peer_rwnd
);
2424 if (s
->sctpi_peer_tag
)
2425 out(" ptag:%x", s
->sctpi_peer_tag
);
2426 if (s
->sctpi_peer_capable
)
2427 out(" pcapable:%d", s
->sctpi_peer_capable
);
2428 if (s
->sctpi_peer_sack
)
2429 out(" psack:%d", s
->sctpi_peer_sack
);
2430 if (s
->sctpi_s_autoclose
)
2431 out(" autoclose:%d", s
->sctpi_s_autoclose
);
2432 if (s
->sctpi_s_adaptation_ind
)
2433 out(" adapind:%d", s
->sctpi_s_adaptation_ind
);
2434 if (s
->sctpi_s_pd_point
)
2435 out(" pdpoint:%d", s
->sctpi_s_pd_point
);
2436 if (s
->sctpi_s_nodelay
)
2437 out(" nodelay:%d", s
->sctpi_s_nodelay
);
2438 if (s
->sctpi_s_disable_fragments
)
2439 out(" nofrag:%d", s
->sctpi_s_disable_fragments
);
2440 if (s
->sctpi_s_v4mapped
)
2441 out(" v4mapped:%d", s
->sctpi_s_v4mapped
);
2442 if (s
->sctpi_s_frag_interleave
)
2443 out(" fraginl:%d", s
->sctpi_s_frag_interleave
);
2446 static void tcp_stats_print(struct tcpstat
*s
)
2452 if (s
->has_sack_opt
)
2456 if (s
->has_ecnseen_opt
)
2458 if (s
->has_fastopen_opt
)
2461 out(" %s", s
->cong_alg
);
2462 if (s
->has_wscale_opt
)
2463 out(" wscale:%d,%d", s
->snd_wscale
, s
->rcv_wscale
);
2465 out(" rto:%g", s
->rto
);
2467 out(" backoff:%u", s
->backoff
);
2469 out(" rtt:%g/%g", s
->rtt
, s
->rttvar
);
2471 out(" ato:%g", s
->ato
);
2474 out(" qack:%d", s
->qack
);
2479 out(" mss:%d", s
->mss
);
2481 out(" pmtu:%u", s
->pmtu
);
2483 out(" rcvmss:%d", s
->rcv_mss
);
2485 out(" advmss:%d", s
->advmss
);
2487 out(" cwnd:%u", s
->cwnd
);
2489 out(" ssthresh:%d", s
->ssthresh
);
2492 out(" bytes_sent:%llu", s
->bytes_sent
);
2493 if (s
->bytes_retrans
)
2494 out(" bytes_retrans:%llu", s
->bytes_retrans
);
2496 out(" bytes_acked:%llu", s
->bytes_acked
);
2497 if (s
->bytes_received
)
2498 out(" bytes_received:%llu", s
->bytes_received
);
2500 out(" segs_out:%u", s
->segs_out
);
2502 out(" segs_in:%u", s
->segs_in
);
2503 if (s
->data_segs_out
)
2504 out(" data_segs_out:%u", s
->data_segs_out
);
2505 if (s
->data_segs_in
)
2506 out(" data_segs_in:%u", s
->data_segs_in
);
2508 if (s
->dctcp
&& s
->dctcp
->enabled
) {
2509 struct dctcpstat
*dctcp
= s
->dctcp
;
2511 out(" dctcp:(ce_state:%u,alpha:%u,ab_ecn:%u,ab_tot:%u)",
2512 dctcp
->ce_state
, dctcp
->alpha
, dctcp
->ab_ecn
,
2514 } else if (s
->dctcp
) {
2515 out(" dctcp:fallback_mode");
2521 bw
= s
->bbr_info
->bbr_bw_hi
;
2523 bw
|= s
->bbr_info
->bbr_bw_lo
;
2525 out(" bbr:(bw:%sbps,mrtt:%g",
2526 sprint_bw(b1
, bw
* 8.0),
2527 (double)s
->bbr_info
->bbr_min_rtt
/ 1000.0);
2528 if (s
->bbr_info
->bbr_pacing_gain
)
2529 out(",pacing_gain:%g",
2530 (double)s
->bbr_info
->bbr_pacing_gain
/ 256.0);
2531 if (s
->bbr_info
->bbr_cwnd_gain
)
2532 out(",cwnd_gain:%g",
2533 (double)s
->bbr_info
->bbr_cwnd_gain
/ 256.0);
2538 out(" send %sbps", sprint_bw(b1
, s
->send_bps
));
2540 out(" lastsnd:%u", s
->lastsnd
);
2542 out(" lastrcv:%u", s
->lastrcv
);
2544 out(" lastack:%u", s
->lastack
);
2546 if (s
->pacing_rate
) {
2547 out(" pacing_rate %sbps", sprint_bw(b1
, s
->pacing_rate
));
2548 if (s
->pacing_rate_max
)
2549 out("/%sbps", sprint_bw(b1
, s
->pacing_rate_max
));
2552 if (s
->delivery_rate
)
2553 out(" delivery_rate %sbps", sprint_bw(b1
, s
->delivery_rate
));
2555 out(" delivered:%u", s
->delivered
);
2556 if (s
->delivered_ce
)
2557 out(" delivered_ce:%u", s
->delivered_ce
);
2559 out(" app_limited");
2562 out(" busy:%llums", s
->busy_time
/ 1000);
2563 if (s
->rwnd_limited
)
2564 out(" rwnd_limited:%llums(%.1f%%)",
2565 s
->rwnd_limited
/ 1000,
2566 100.0 * s
->rwnd_limited
/ s
->busy_time
);
2567 if (s
->sndbuf_limited
)
2568 out(" sndbuf_limited:%llums(%.1f%%)",
2569 s
->sndbuf_limited
/ 1000,
2570 100.0 * s
->sndbuf_limited
/ s
->busy_time
);
2574 out(" unacked:%u", s
->unacked
);
2575 if (s
->retrans
|| s
->retrans_total
)
2576 out(" retrans:%u/%u", s
->retrans
, s
->retrans_total
);
2578 out(" lost:%u", s
->lost
);
2579 if (s
->sacked
&& s
->ss
.state
!= SS_LISTEN
)
2580 out(" sacked:%u", s
->sacked
);
2582 out(" dsack_dups:%u", s
->dsack_dups
);
2584 out(" fackets:%u", s
->fackets
);
2585 if (s
->reordering
!= 3)
2586 out(" reordering:%d", s
->reordering
);
2588 out(" reord_seen:%d", s
->reord_seen
);
2590 out(" rcv_rtt:%g", s
->rcv_rtt
);
2592 out(" rcv_space:%d", s
->rcv_space
);
2593 if (s
->rcv_ssthresh
)
2594 out(" rcv_ssthresh:%u", s
->rcv_ssthresh
);
2596 out(" notsent:%u", s
->not_sent
);
2598 out(" minrtt:%g", s
->min_rtt
);
2601 static void tcp_timer_print(struct tcpstat
*s
)
2603 static const char * const tmr_name
[] = {
2615 out(" timer:(%s,%s,%d)",
2617 print_ms_timer(s
->timeout
),
2622 static void sctp_timer_print(struct tcpstat
*s
)
2625 out(" timer:(T3_RTX,%s,%d)",
2626 print_ms_timer(s
->timeout
), s
->retrans
);
2629 static int tcp_show_line(char *line
, const struct filter
*f
, int family
)
2631 int rto
= 0, ato
= 0;
2632 struct tcpstat s
= {};
2633 char *loc
, *rem
, *data
;
2636 int hz
= get_user_hz();
2638 if (proc_inet_split_line(line
, &loc
, &rem
, &data
))
2641 int state
= (data
[1] >= 'A') ? (data
[1] - 'A' + 10) : (data
[1] - '0');
2643 if (!(f
->states
& (1 << state
)))
2646 proc_parse_inet_addr(loc
, rem
, family
, &s
.ss
);
2648 if (f
->f
&& run_ssfilter(f
->f
, &s
.ss
) == 0)
2652 n
= sscanf(data
, "%x %x:%x %x:%x %x %d %d %u %d %llx %d %d %d %u %d %[^\n]\n",
2653 &s
.ss
.state
, &s
.ss
.wq
, &s
.ss
.rq
,
2654 &s
.timer
, &s
.timeout
, &s
.retrans
, &s
.ss
.uid
, &s
.probes
,
2655 &s
.ss
.ino
, &s
.ss
.refcnt
, &s
.ss
.sk
, &rto
, &ato
, &s
.qack
, &s
.cwnd
,
2668 s
.retrans
= s
.timer
!= 1 ? s
.probes
: s
.retrans
;
2669 s
.timeout
= (s
.timeout
* 1000 + hz
- 1) / hz
;
2670 s
.ato
= (double)ato
/ hz
;
2672 s
.rto
= (double)rto
;
2673 s
.ssthresh
= s
.ssthresh
== -1 ? 0 : s
.ssthresh
;
2674 s
.rto
= s
.rto
!= 3 * hz
? s
.rto
/ hz
: 0;
2675 s
.ss
.type
= IPPROTO_TCP
;
2677 inet_stats_print(&s
.ss
, false);
2680 tcp_timer_print(&s
);
2683 sock_details_print(&s
.ss
);
2685 out(" opt:\"%s\"", opt
);
2689 tcp_stats_print(&s
);
2694 static int generic_record_read(FILE *fp
,
2695 int (*worker
)(char*, const struct filter
*, int),
2696 const struct filter
*f
, int fam
)
2701 if (fgets(line
, sizeof(line
), fp
) == NULL
)
2704 while (fgets(line
, sizeof(line
), fp
) != NULL
) {
2705 int n
= strlen(line
);
2707 if (n
== 0 || line
[n
-1] != '\n') {
2713 if (worker(line
, f
, fam
) < 0)
2718 return ferror(fp
) ? -1 : 0;
2721 static void print_skmeminfo(struct rtattr
*tb
[], int attrtype
)
2723 const __u32
*skmeminfo
;
2725 if (!tb
[attrtype
]) {
2726 if (attrtype
== INET_DIAG_SKMEMINFO
) {
2727 if (!tb
[INET_DIAG_MEMINFO
])
2730 const struct inet_diag_meminfo
*minfo
=
2731 RTA_DATA(tb
[INET_DIAG_MEMINFO
]);
2733 out(" mem:(r%u,w%u,f%u,t%u)",
2742 skmeminfo
= RTA_DATA(tb
[attrtype
]);
2744 out(" skmem:(r%u,rb%u,t%u,tb%u,f%u,w%u,o%u",
2745 skmeminfo
[SK_MEMINFO_RMEM_ALLOC
],
2746 skmeminfo
[SK_MEMINFO_RCVBUF
],
2747 skmeminfo
[SK_MEMINFO_WMEM_ALLOC
],
2748 skmeminfo
[SK_MEMINFO_SNDBUF
],
2749 skmeminfo
[SK_MEMINFO_FWD_ALLOC
],
2750 skmeminfo
[SK_MEMINFO_WMEM_QUEUED
],
2751 skmeminfo
[SK_MEMINFO_OPTMEM
]);
2753 if (RTA_PAYLOAD(tb
[attrtype
]) >=
2754 (SK_MEMINFO_BACKLOG
+ 1) * sizeof(__u32
))
2755 out(",bl%u", skmeminfo
[SK_MEMINFO_BACKLOG
]);
2757 if (RTA_PAYLOAD(tb
[attrtype
]) >=
2758 (SK_MEMINFO_DROPS
+ 1) * sizeof(__u32
))
2759 out(",d%u", skmeminfo
[SK_MEMINFO_DROPS
]);
2764 static void print_md5sig(struct tcp_diag_md5sig
*sig
)
2767 format_host(sig
->tcpm_family
,
2768 sig
->tcpm_family
== AF_INET6
? 16 : 4,
2770 sig
->tcpm_prefixlen
);
2771 print_escape_buf(sig
->tcpm_key
, sig
->tcpm_keylen
, " ,");
2774 static void tcp_tls_version(struct rtattr
*attr
)
2780 val
= rta_getattr_u16(attr
);
2783 case TLS_1_2_VERSION
:
2784 out(" version: 1.2");
2786 case TLS_1_3_VERSION
:
2787 out(" version: 1.3");
2790 out(" version: unknown(%hu)", val
);
2795 static void tcp_tls_cipher(struct rtattr
*attr
)
2801 val
= rta_getattr_u16(attr
);
2804 case TLS_CIPHER_AES_GCM_128
:
2805 out(" cipher: aes-gcm-128");
2807 case TLS_CIPHER_AES_GCM_256
:
2808 out(" cipher: aes-gcm-256");
2813 static void tcp_tls_conf(const char *name
, struct rtattr
*attr
)
2819 val
= rta_getattr_u16(attr
);
2823 out(" %s: none", name
);
2826 out(" %s: sw", name
);
2829 out(" %s: hw", name
);
2831 case TLS_CONF_HW_RECORD
:
2832 out(" %s: hw-record", name
);
2835 out(" %s: unknown(%hu)", name
, val
);
2840 static void mptcp_subflow_info(struct rtattr
*tb
[])
2842 u_int32_t flags
= 0;
2844 if (tb
[MPTCP_SUBFLOW_ATTR_FLAGS
]) {
2845 char caps
[32 + 1] = { 0 }, *cap
= &caps
[0];
2847 flags
= rta_getattr_u32(tb
[MPTCP_SUBFLOW_ATTR_FLAGS
]);
2849 if (flags
& MPTCP_SUBFLOW_FLAG_MCAP_REM
)
2851 if (flags
& MPTCP_SUBFLOW_FLAG_MCAP_LOC
)
2853 if (flags
& MPTCP_SUBFLOW_FLAG_JOIN_REM
)
2855 if (flags
& MPTCP_SUBFLOW_FLAG_JOIN_LOC
)
2857 if (flags
& MPTCP_SUBFLOW_FLAG_BKUP_REM
)
2859 if (flags
& MPTCP_SUBFLOW_FLAG_BKUP_LOC
)
2861 if (flags
& MPTCP_SUBFLOW_FLAG_FULLY_ESTABLISHED
)
2863 if (flags
& MPTCP_SUBFLOW_FLAG_CONNECTED
)
2865 if (flags
& MPTCP_SUBFLOW_FLAG_MAPVALID
)
2868 out(" flags:%s", caps
);
2870 if (tb
[MPTCP_SUBFLOW_ATTR_TOKEN_REM
] &&
2871 tb
[MPTCP_SUBFLOW_ATTR_TOKEN_LOC
] &&
2872 tb
[MPTCP_SUBFLOW_ATTR_ID_REM
] &&
2873 tb
[MPTCP_SUBFLOW_ATTR_ID_LOC
])
2874 out(" token:%04x(id:%hhu)/%04x(id:%hhu)",
2875 rta_getattr_u32(tb
[MPTCP_SUBFLOW_ATTR_TOKEN_REM
]),
2876 rta_getattr_u8(tb
[MPTCP_SUBFLOW_ATTR_ID_REM
]),
2877 rta_getattr_u32(tb
[MPTCP_SUBFLOW_ATTR_TOKEN_LOC
]),
2878 rta_getattr_u8(tb
[MPTCP_SUBFLOW_ATTR_ID_LOC
]));
2879 if (tb
[MPTCP_SUBFLOW_ATTR_MAP_SEQ
])
2881 rta_getattr_u64(tb
[MPTCP_SUBFLOW_ATTR_MAP_SEQ
]));
2882 if (tb
[MPTCP_SUBFLOW_ATTR_MAP_SFSEQ
])
2884 rta_getattr_u32(tb
[MPTCP_SUBFLOW_ATTR_MAP_SFSEQ
]));
2885 if (tb
[MPTCP_SUBFLOW_ATTR_SSN_OFFSET
])
2887 rta_getattr_u32(tb
[MPTCP_SUBFLOW_ATTR_SSN_OFFSET
]));
2888 if (tb
[MPTCP_SUBFLOW_ATTR_MAP_DATALEN
])
2890 rta_getattr_u32(tb
[MPTCP_SUBFLOW_ATTR_MAP_DATALEN
]));
2893 #define TCPI_HAS_OPT(info, opt) !!(info->tcpi_options & (opt))
2895 static void tcp_show_info(const struct nlmsghdr
*nlh
, struct inet_diag_msg
*r
,
2896 struct rtattr
*tb
[])
2899 struct tcpstat s
= {};
2901 s
.ss
.state
= r
->idiag_state
;
2903 print_skmeminfo(tb
, INET_DIAG_SKMEMINFO
);
2905 if (tb
[INET_DIAG_INFO
]) {
2906 struct tcp_info
*info
;
2907 int len
= RTA_PAYLOAD(tb
[INET_DIAG_INFO
]);
2909 /* workaround for older kernels with less fields */
2910 if (len
< sizeof(*info
)) {
2911 info
= alloca(sizeof(*info
));
2912 memcpy(info
, RTA_DATA(tb
[INET_DIAG_INFO
]), len
);
2913 memset((char *)info
+ len
, 0, sizeof(*info
) - len
);
2915 info
= RTA_DATA(tb
[INET_DIAG_INFO
]);
2918 s
.has_ts_opt
= TCPI_HAS_OPT(info
, TCPI_OPT_TIMESTAMPS
);
2919 s
.has_sack_opt
= TCPI_HAS_OPT(info
, TCPI_OPT_SACK
);
2920 s
.has_ecn_opt
= TCPI_HAS_OPT(info
, TCPI_OPT_ECN
);
2921 s
.has_ecnseen_opt
= TCPI_HAS_OPT(info
, TCPI_OPT_ECN_SEEN
);
2922 s
.has_fastopen_opt
= TCPI_HAS_OPT(info
, TCPI_OPT_SYN_DATA
);
2925 if (tb
[INET_DIAG_CONG
])
2927 rta_getattr_str(tb
[INET_DIAG_CONG
]),
2928 sizeof(s
.cong_alg
) - 1);
2930 if (TCPI_HAS_OPT(info
, TCPI_OPT_WSCALE
)) {
2931 s
.has_wscale_opt
= true;
2932 s
.snd_wscale
= info
->tcpi_snd_wscale
;
2933 s
.rcv_wscale
= info
->tcpi_rcv_wscale
;
2936 if (info
->tcpi_rto
&& info
->tcpi_rto
!= 3000000)
2937 s
.rto
= (double)info
->tcpi_rto
/ 1000;
2939 s
.backoff
= info
->tcpi_backoff
;
2940 s
.rtt
= (double)info
->tcpi_rtt
/ 1000;
2941 s
.rttvar
= (double)info
->tcpi_rttvar
/ 1000;
2942 s
.ato
= (double)info
->tcpi_ato
/ 1000;
2943 s
.mss
= info
->tcpi_snd_mss
;
2944 s
.rcv_mss
= info
->tcpi_rcv_mss
;
2945 s
.advmss
= info
->tcpi_advmss
;
2946 s
.rcv_space
= info
->tcpi_rcv_space
;
2947 s
.rcv_rtt
= (double)info
->tcpi_rcv_rtt
/ 1000;
2948 s
.lastsnd
= info
->tcpi_last_data_sent
;
2949 s
.lastrcv
= info
->tcpi_last_data_recv
;
2950 s
.lastack
= info
->tcpi_last_ack_recv
;
2951 s
.unacked
= info
->tcpi_unacked
;
2952 s
.retrans
= info
->tcpi_retrans
;
2953 s
.retrans_total
= info
->tcpi_total_retrans
;
2954 s
.lost
= info
->tcpi_lost
;
2955 s
.sacked
= info
->tcpi_sacked
;
2956 s
.fackets
= info
->tcpi_fackets
;
2957 s
.reordering
= info
->tcpi_reordering
;
2958 s
.rcv_ssthresh
= info
->tcpi_rcv_ssthresh
;
2959 s
.cwnd
= info
->tcpi_snd_cwnd
;
2960 s
.pmtu
= info
->tcpi_pmtu
;
2962 if (info
->tcpi_snd_ssthresh
< 0xFFFF)
2963 s
.ssthresh
= info
->tcpi_snd_ssthresh
;
2965 rtt
= (double) info
->tcpi_rtt
;
2966 if (tb
[INET_DIAG_VEGASINFO
]) {
2967 const struct tcpvegas_info
*vinfo
2968 = RTA_DATA(tb
[INET_DIAG_VEGASINFO
]);
2970 if (vinfo
->tcpv_enabled
&&
2971 vinfo
->tcpv_rtt
&& vinfo
->tcpv_rtt
!= 0x7fffffff)
2972 rtt
= vinfo
->tcpv_rtt
;
2975 if (tb
[INET_DIAG_DCTCPINFO
]) {
2976 struct dctcpstat
*dctcp
= malloc(sizeof(struct
2979 const struct tcp_dctcp_info
*dinfo
2980 = RTA_DATA(tb
[INET_DIAG_DCTCPINFO
]);
2982 dctcp
->enabled
= !!dinfo
->dctcp_enabled
;
2983 dctcp
->ce_state
= dinfo
->dctcp_ce_state
;
2984 dctcp
->alpha
= dinfo
->dctcp_alpha
;
2985 dctcp
->ab_ecn
= dinfo
->dctcp_ab_ecn
;
2986 dctcp
->ab_tot
= dinfo
->dctcp_ab_tot
;
2990 if (tb
[INET_DIAG_BBRINFO
]) {
2991 const void *bbr_info
= RTA_DATA(tb
[INET_DIAG_BBRINFO
]);
2992 int len
= min(RTA_PAYLOAD(tb
[INET_DIAG_BBRINFO
]),
2993 sizeof(*s
.bbr_info
));
2995 s
.bbr_info
= calloc(1, sizeof(*s
.bbr_info
));
2996 if (s
.bbr_info
&& bbr_info
)
2997 memcpy(s
.bbr_info
, bbr_info
, len
);
3000 if (rtt
> 0 && info
->tcpi_snd_mss
&& info
->tcpi_snd_cwnd
) {
3001 s
.send_bps
= (double) info
->tcpi_snd_cwnd
*
3002 (double)info
->tcpi_snd_mss
* 8000000. / rtt
;
3005 if (info
->tcpi_pacing_rate
&&
3006 info
->tcpi_pacing_rate
!= ~0ULL) {
3007 s
.pacing_rate
= info
->tcpi_pacing_rate
* 8.;
3009 if (info
->tcpi_max_pacing_rate
&&
3010 info
->tcpi_max_pacing_rate
!= ~0ULL)
3011 s
.pacing_rate_max
= info
->tcpi_max_pacing_rate
* 8.;
3013 s
.bytes_acked
= info
->tcpi_bytes_acked
;
3014 s
.bytes_received
= info
->tcpi_bytes_received
;
3015 s
.segs_out
= info
->tcpi_segs_out
;
3016 s
.segs_in
= info
->tcpi_segs_in
;
3017 s
.data_segs_out
= info
->tcpi_data_segs_out
;
3018 s
.data_segs_in
= info
->tcpi_data_segs_in
;
3019 s
.not_sent
= info
->tcpi_notsent_bytes
;
3020 if (info
->tcpi_min_rtt
&& info
->tcpi_min_rtt
!= ~0U)
3021 s
.min_rtt
= (double) info
->tcpi_min_rtt
/ 1000;
3022 s
.delivery_rate
= info
->tcpi_delivery_rate
* 8.;
3023 s
.app_limited
= info
->tcpi_delivery_rate_app_limited
;
3024 s
.busy_time
= info
->tcpi_busy_time
;
3025 s
.rwnd_limited
= info
->tcpi_rwnd_limited
;
3026 s
.sndbuf_limited
= info
->tcpi_sndbuf_limited
;
3027 s
.delivered
= info
->tcpi_delivered
;
3028 s
.delivered_ce
= info
->tcpi_delivered_ce
;
3029 s
.dsack_dups
= info
->tcpi_dsack_dups
;
3030 s
.reord_seen
= info
->tcpi_reord_seen
;
3031 s
.bytes_sent
= info
->tcpi_bytes_sent
;
3032 s
.bytes_retrans
= info
->tcpi_bytes_retrans
;
3033 tcp_stats_print(&s
);
3037 if (tb
[INET_DIAG_MD5SIG
]) {
3038 struct tcp_diag_md5sig
*sig
= RTA_DATA(tb
[INET_DIAG_MD5SIG
]);
3039 int len
= RTA_PAYLOAD(tb
[INET_DIAG_MD5SIG
]);
3042 print_md5sig(sig
++);
3043 for (len
-= sizeof(*sig
); len
> 0; len
-= sizeof(*sig
)) {
3045 print_md5sig(sig
++);
3048 if (tb
[INET_DIAG_ULP_INFO
]) {
3049 struct rtattr
*ulpinfo
[INET_ULP_INFO_MAX
+ 1] = { 0 };
3051 parse_rtattr_nested(ulpinfo
, INET_ULP_INFO_MAX
,
3052 tb
[INET_DIAG_ULP_INFO
]);
3054 if (ulpinfo
[INET_ULP_INFO_NAME
])
3056 rta_getattr_str(ulpinfo
[INET_ULP_INFO_NAME
]));
3058 if (ulpinfo
[INET_ULP_INFO_TLS
]) {
3059 struct rtattr
*tlsinfo
[TLS_INFO_MAX
+ 1] = { 0 };
3061 parse_rtattr_nested(tlsinfo
, TLS_INFO_MAX
,
3062 ulpinfo
[INET_ULP_INFO_TLS
]);
3064 tcp_tls_version(tlsinfo
[TLS_INFO_VERSION
]);
3065 tcp_tls_cipher(tlsinfo
[TLS_INFO_CIPHER
]);
3066 tcp_tls_conf("rxconf", tlsinfo
[TLS_INFO_RXCONF
]);
3067 tcp_tls_conf("txconf", tlsinfo
[TLS_INFO_TXCONF
]);
3069 if (ulpinfo
[INET_ULP_INFO_MPTCP
]) {
3070 struct rtattr
*sfinfo
[MPTCP_SUBFLOW_ATTR_MAX
+ 1] =
3073 parse_rtattr_nested(sfinfo
, MPTCP_SUBFLOW_ATTR_MAX
,
3074 ulpinfo
[INET_ULP_INFO_MPTCP
]);
3075 mptcp_subflow_info(sfinfo
);
3080 static const char *format_host_sa(struct sockaddr_storage
*sa
)
3083 struct sockaddr_in sin
;
3084 struct sockaddr_in6 sin6
;
3085 } *saddr
= (void *)sa
;
3087 switch (sa
->ss_family
) {
3089 return format_host(AF_INET
, 4, &saddr
->sin
.sin_addr
);
3091 return format_host(AF_INET6
, 16, &saddr
->sin6
.sin6_addr
);
3097 static void sctp_show_info(const struct nlmsghdr
*nlh
, struct inet_diag_msg
*r
,
3098 struct rtattr
*tb
[])
3100 struct sockaddr_storage
*sa
;
3103 print_skmeminfo(tb
, INET_DIAG_SKMEMINFO
);
3105 if (tb
[INET_DIAG_LOCALS
]) {
3106 len
= RTA_PAYLOAD(tb
[INET_DIAG_LOCALS
]);
3107 sa
= RTA_DATA(tb
[INET_DIAG_LOCALS
]);
3109 out(" locals:%s", format_host_sa(sa
));
3110 for (sa
++, len
-= sizeof(*sa
); len
> 0; sa
++, len
-= sizeof(*sa
))
3111 out(",%s", format_host_sa(sa
));
3114 if (tb
[INET_DIAG_PEERS
]) {
3115 len
= RTA_PAYLOAD(tb
[INET_DIAG_PEERS
]);
3116 sa
= RTA_DATA(tb
[INET_DIAG_PEERS
]);
3118 out(" peers:%s", format_host_sa(sa
));
3119 for (sa
++, len
-= sizeof(*sa
); len
> 0; sa
++, len
-= sizeof(*sa
))
3120 out(",%s", format_host_sa(sa
));
3122 if (tb
[INET_DIAG_INFO
]) {
3123 struct sctp_info
*info
;
3124 len
= RTA_PAYLOAD(tb
[INET_DIAG_INFO
]);
3126 /* workaround for older kernels with less fields */
3127 if (len
< sizeof(*info
)) {
3128 info
= alloca(sizeof(*info
));
3129 memcpy(info
, RTA_DATA(tb
[INET_DIAG_INFO
]), len
);
3130 memset((char *)info
+ len
, 0, sizeof(*info
) - len
);
3132 info
= RTA_DATA(tb
[INET_DIAG_INFO
]);
3134 sctp_stats_print(info
);
3138 static void parse_diag_msg(struct nlmsghdr
*nlh
, struct sockstat
*s
)
3140 struct rtattr
*tb
[INET_DIAG_MAX
+1];
3141 struct inet_diag_msg
*r
= NLMSG_DATA(nlh
);
3143 parse_rtattr(tb
, INET_DIAG_MAX
, (struct rtattr
*)(r
+1),
3144 nlh
->nlmsg_len
- NLMSG_LENGTH(sizeof(*r
)));
3146 s
->state
= r
->idiag_state
;
3147 s
->local
.family
= s
->remote
.family
= r
->idiag_family
;
3148 s
->lport
= ntohs(r
->id
.idiag_sport
);
3149 s
->rport
= ntohs(r
->id
.idiag_dport
);
3150 s
->wq
= r
->idiag_wqueue
;
3151 s
->rq
= r
->idiag_rqueue
;
3152 s
->ino
= r
->idiag_inode
;
3153 s
->uid
= r
->idiag_uid
;
3154 s
->iface
= r
->id
.idiag_if
;
3155 s
->sk
= cookie_sk_get(&r
->id
.idiag_cookie
[0]);
3158 if (tb
[INET_DIAG_MARK
])
3159 s
->mark
= rta_getattr_u32(tb
[INET_DIAG_MARK
]);
3160 if (tb
[INET_DIAG_PROTOCOL
])
3161 s
->raw_prot
= rta_getattr_u8(tb
[INET_DIAG_PROTOCOL
]);
3165 if (s
->local
.family
== AF_INET
)
3166 s
->local
.bytelen
= s
->remote
.bytelen
= 4;
3168 s
->local
.bytelen
= s
->remote
.bytelen
= 16;
3170 memcpy(s
->local
.data
, r
->id
.idiag_src
, s
->local
.bytelen
);
3171 memcpy(s
->remote
.data
, r
->id
.idiag_dst
, s
->local
.bytelen
);
3174 static int inet_show_sock(struct nlmsghdr
*nlh
,
3177 struct rtattr
*tb
[INET_DIAG_MAX
+1];
3178 struct inet_diag_msg
*r
= NLMSG_DATA(nlh
);
3179 unsigned char v6only
= 0;
3181 parse_rtattr(tb
, INET_DIAG_MAX
, (struct rtattr
*)(r
+1),
3182 nlh
->nlmsg_len
- NLMSG_LENGTH(sizeof(*r
)));
3184 if (tb
[INET_DIAG_PROTOCOL
])
3185 s
->type
= rta_getattr_u8(tb
[INET_DIAG_PROTOCOL
]);
3187 if (s
->local
.family
== AF_INET6
&& tb
[INET_DIAG_SKV6ONLY
])
3188 v6only
= rta_getattr_u8(tb
[INET_DIAG_SKV6ONLY
]);
3190 inet_stats_print(s
, v6only
);
3193 struct tcpstat t
= {};
3195 t
.timer
= r
->idiag_timer
;
3196 t
.timeout
= r
->idiag_expires
;
3197 t
.retrans
= r
->idiag_retrans
;
3198 if (s
->type
== IPPROTO_SCTP
)
3199 sctp_timer_print(&t
);
3201 tcp_timer_print(&t
);
3205 sock_details_print(s
);
3206 if (s
->local
.family
== AF_INET6
&& tb
[INET_DIAG_SKV6ONLY
])
3207 out(" v6only:%u", v6only
);
3209 if (tb
[INET_DIAG_SHUTDOWN
]) {
3212 mask
= rta_getattr_u8(tb
[INET_DIAG_SHUTDOWN
]);
3214 mask
& 1 ? '-' : '<', mask
& 2 ? '-' : '>');
3219 if (tb
[INET_DIAG_TOS
])
3220 out(" tos:%#x", rta_getattr_u8(tb
[INET_DIAG_TOS
]));
3221 if (tb
[INET_DIAG_TCLASS
])
3222 out(" tclass:%#x", rta_getattr_u8(tb
[INET_DIAG_TCLASS
]));
3223 if (tb
[INET_DIAG_CLASS_ID
])
3224 out(" class_id:%#x", rta_getattr_u32(tb
[INET_DIAG_CLASS_ID
]));
3227 if (show_mem
|| (show_tcpinfo
&& s
->type
!= IPPROTO_UDP
)) {
3230 if (s
->type
== IPPROTO_SCTP
)
3231 sctp_show_info(nlh
, r
, tb
);
3233 tcp_show_info(nlh
, r
, tb
);
3240 static int tcpdiag_send(int fd
, int protocol
, struct filter
*f
)
3242 struct sockaddr_nl nladdr
= { .nl_family
= AF_NETLINK
};
3244 struct nlmsghdr nlh
;
3245 struct inet_diag_req r
;
3247 .nlh
.nlmsg_len
= sizeof(req
),
3248 .nlh
.nlmsg_flags
= NLM_F_ROOT
| NLM_F_MATCH
| NLM_F_REQUEST
,
3249 .nlh
.nlmsg_seq
= MAGIC_SEQ
,
3250 .r
.idiag_family
= AF_INET
,
3251 .r
.idiag_states
= f
->states
,
3257 struct iovec iov
[3];
3260 if (protocol
== IPPROTO_UDP
)
3263 if (protocol
== IPPROTO_TCP
)
3264 req
.nlh
.nlmsg_type
= TCPDIAG_GETSOCK
;
3266 req
.nlh
.nlmsg_type
= DCCPDIAG_GETSOCK
;
3268 req
.r
.idiag_ext
|= (1<<(INET_DIAG_MEMINFO
-1));
3269 req
.r
.idiag_ext
|= (1<<(INET_DIAG_SKMEMINFO
-1));
3273 req
.r
.idiag_ext
|= (1<<(INET_DIAG_INFO
-1));
3274 req
.r
.idiag_ext
|= (1<<(INET_DIAG_VEGASINFO
-1));
3275 req
.r
.idiag_ext
|= (1<<(INET_DIAG_CONG
-1));
3279 req
.r
.idiag_ext
|= (1<<(INET_DIAG_TOS
-1));
3280 req
.r
.idiag_ext
|= (1<<(INET_DIAG_TCLASS
-1));
3283 iov
[0] = (struct iovec
){
3285 .iov_len
= sizeof(req
)
3288 bclen
= ssfilter_bytecompile(f
->f
, &bc
);
3290 rta
.rta_type
= INET_DIAG_REQ_BYTECODE
;
3291 rta
.rta_len
= RTA_LENGTH(bclen
);
3292 iov
[1] = (struct iovec
){ &rta
, sizeof(rta
) };
3293 iov
[2] = (struct iovec
){ bc
, bclen
};
3294 req
.nlh
.nlmsg_len
+= RTA_LENGTH(bclen
);
3299 msg
= (struct msghdr
) {
3300 .msg_name
= (void *)&nladdr
,
3301 .msg_namelen
= sizeof(nladdr
),
3303 .msg_iovlen
= iovlen
,
3306 if (sendmsg(fd
, &msg
, 0) < 0) {
3314 static int sockdiag_send(int family
, int fd
, int protocol
, struct filter
*f
)
3316 struct sockaddr_nl nladdr
= { .nl_family
= AF_NETLINK
};
3317 DIAG_REQUEST(req
, struct inet_diag_req_v2 r
);
3322 struct iovec iov
[3];
3325 if (family
== PF_UNSPEC
)
3326 return tcpdiag_send(fd
, protocol
, f
);
3328 memset(&req
.r
, 0, sizeof(req
.r
));
3329 req
.r
.sdiag_family
= family
;
3330 req
.r
.sdiag_protocol
= protocol
;
3331 req
.r
.idiag_states
= f
->states
;
3333 req
.r
.idiag_ext
|= (1<<(INET_DIAG_MEMINFO
-1));
3334 req
.r
.idiag_ext
|= (1<<(INET_DIAG_SKMEMINFO
-1));
3338 req
.r
.idiag_ext
|= (1<<(INET_DIAG_INFO
-1));
3339 req
.r
.idiag_ext
|= (1<<(INET_DIAG_VEGASINFO
-1));
3340 req
.r
.idiag_ext
|= (1<<(INET_DIAG_CONG
-1));
3344 req
.r
.idiag_ext
|= (1<<(INET_DIAG_TOS
-1));
3345 req
.r
.idiag_ext
|= (1<<(INET_DIAG_TCLASS
-1));
3348 iov
[0] = (struct iovec
){
3350 .iov_len
= sizeof(req
)
3353 bclen
= ssfilter_bytecompile(f
->f
, &bc
);
3355 rta
.rta_type
= INET_DIAG_REQ_BYTECODE
;
3356 rta
.rta_len
= RTA_LENGTH(bclen
);
3357 iov
[1] = (struct iovec
){ &rta
, sizeof(rta
) };
3358 iov
[2] = (struct iovec
){ bc
, bclen
};
3359 req
.nlh
.nlmsg_len
+= RTA_LENGTH(bclen
);
3364 msg
= (struct msghdr
) {
3365 .msg_name
= (void *)&nladdr
,
3366 .msg_namelen
= sizeof(nladdr
),
3368 .msg_iovlen
= iovlen
,
3371 if (sendmsg(fd
, &msg
, 0) < 0) {
3379 struct inet_diag_arg
{
3382 struct rtnl_handle
*rth
;
3385 static int kill_inet_sock(struct nlmsghdr
*h
, void *arg
, struct sockstat
*s
)
3387 struct inet_diag_msg
*d
= NLMSG_DATA(h
);
3388 struct inet_diag_arg
*diag_arg
= arg
;
3389 struct rtnl_handle
*rth
= diag_arg
->rth
;
3391 DIAG_REQUEST(req
, struct inet_diag_req_v2 r
);
3393 req
.nlh
.nlmsg_type
= SOCK_DESTROY
;
3394 req
.nlh
.nlmsg_flags
= NLM_F_REQUEST
| NLM_F_ACK
;
3395 req
.nlh
.nlmsg_seq
= ++rth
->seq
;
3396 req
.r
.sdiag_family
= d
->idiag_family
;
3397 req
.r
.sdiag_protocol
= diag_arg
->protocol
;
3400 if (diag_arg
->protocol
== IPPROTO_RAW
) {
3401 struct inet_diag_req_raw
*raw
= (void *)&req
.r
;
3403 BUILD_BUG_ON(sizeof(req
.r
) != sizeof(*raw
));
3404 raw
->sdiag_raw_protocol
= s
->raw_prot
;
3407 return rtnl_talk(rth
, &req
.nlh
, NULL
);
3410 static int show_one_inet_sock(struct nlmsghdr
*h
, void *arg
)
3413 struct inet_diag_arg
*diag_arg
= arg
;
3414 struct inet_diag_msg
*r
= NLMSG_DATA(h
);
3415 struct sockstat s
= {};
3417 if (!(diag_arg
->f
->families
& FAMILY_MASK(r
->idiag_family
)))
3420 parse_diag_msg(h
, &s
);
3421 s
.type
= diag_arg
->protocol
;
3423 if (diag_arg
->f
->f
&& run_ssfilter(diag_arg
->f
->f
, &s
) == 0)
3426 if (diag_arg
->f
->kill
&& kill_inet_sock(h
, arg
, &s
) != 0) {
3427 if (errno
== EOPNOTSUPP
|| errno
== ENOENT
) {
3428 /* Socket can't be closed, or is already closed. */
3431 perror("SOCK_DESTROY answers");
3436 err
= inet_show_sock(h
, &s
);
3443 static int inet_show_netlink(struct filter
*f
, FILE *dump_fp
, int protocol
)
3446 struct rtnl_handle rth
, rth2
;
3447 int family
= PF_INET
;
3448 struct inet_diag_arg arg
= { .f
= f
, .protocol
= protocol
};
3450 if (rtnl_open_byproto(&rth
, 0, NETLINK_SOCK_DIAG
))
3454 if (rtnl_open_byproto(&rth2
, 0, NETLINK_SOCK_DIAG
)) {
3461 rth
.dump
= MAGIC_SEQ
;
3462 rth
.dump_fp
= dump_fp
;
3463 if (preferred_family
== PF_INET6
)
3467 if ((err
= sockdiag_send(family
, rth
.fd
, protocol
, f
)))
3470 if ((err
= rtnl_dump_filter(&rth
, show_one_inet_sock
, &arg
))) {
3471 if (family
!= PF_UNSPEC
) {
3477 if (family
== PF_INET
&& preferred_family
!= PF_INET
) {
3485 rtnl_close(arg
.rth
);
3489 static int tcp_show_netlink_file(struct filter
*f
)
3495 if ((fp
= fopen(getenv("TCPDIAG_FILE"), "r")) == NULL
) {
3496 perror("fopen($TCPDIAG_FILE)");
3502 size_t status
, nitems
;
3503 struct nlmsghdr
*h
= (struct nlmsghdr
*)buf
;
3504 struct sockstat s
= {};
3506 status
= fread(buf
, 1, sizeof(*h
), fp
);
3507 if (status
!= sizeof(*h
)) {
3509 perror("Reading header from $TCPDIAG_FILE");
3511 fprintf(stderr
, "Unexpected EOF reading $TCPDIAG_FILE");
3515 nitems
= NLMSG_ALIGN(h
->nlmsg_len
- sizeof(*h
));
3516 status
= fread(h
+1, 1, nitems
, fp
);
3518 if (status
!= nitems
) {
3520 perror("Reading $TCPDIAG_FILE");
3522 fprintf(stderr
, "Unexpected EOF reading $TCPDIAG_FILE");
3526 /* The only legal exit point */
3527 if (h
->nlmsg_type
== NLMSG_DONE
) {
3532 if (h
->nlmsg_type
== NLMSG_ERROR
) {
3533 struct nlmsgerr
*err
= (struct nlmsgerr
*)NLMSG_DATA(h
);
3535 if (h
->nlmsg_len
< NLMSG_LENGTH(sizeof(struct nlmsgerr
))) {
3536 fprintf(stderr
, "ERROR truncated\n");
3538 errno
= -err
->error
;
3539 perror("TCPDIAG answered");
3544 parse_diag_msg(h
, &s
);
3545 s
.type
= IPPROTO_TCP
;
3547 if (f
&& f
->f
&& run_ssfilter(f
->f
, &s
) == 0)
3550 err2
= inet_show_sock(h
, &s
);
3561 static int tcp_show(struct filter
*f
)
3565 int bufsize
= 1024*1024;
3567 if (!filter_af_get(f
, AF_INET
) && !filter_af_get(f
, AF_INET6
))
3570 dg_proto
= TCP_PROTO
;
3572 if (getenv("TCPDIAG_FILE"))
3573 return tcp_show_netlink_file(f
);
3575 if (!getenv("PROC_NET_TCP") && !getenv("PROC_ROOT")
3576 && inet_show_netlink(f
, NULL
, IPPROTO_TCP
) == 0)
3579 /* Sigh... We have to parse /proc/net/tcp... */
3580 while (bufsize
>= 64*1024) {
3581 if ((buf
= malloc(bufsize
)) != NULL
)
3590 if (f
->families
& FAMILY_MASK(AF_INET
)) {
3591 if ((fp
= net_tcp_open()) == NULL
)
3594 setbuffer(fp
, buf
, bufsize
);
3595 if (generic_record_read(fp
, tcp_show_line
, f
, AF_INET
))
3600 if ((f
->families
& FAMILY_MASK(AF_INET6
)) &&
3601 (fp
= net_tcp6_open()) != NULL
) {
3602 setbuffer(fp
, buf
, bufsize
);
3603 if (generic_record_read(fp
, tcp_show_line
, f
, AF_INET6
))
3613 int saved_errno
= errno
;
3618 errno
= saved_errno
;
3623 static int dccp_show(struct filter
*f
)
3625 if (!filter_af_get(f
, AF_INET
) && !filter_af_get(f
, AF_INET6
))
3628 if (!getenv("PROC_NET_DCCP") && !getenv("PROC_ROOT")
3629 && inet_show_netlink(f
, NULL
, IPPROTO_DCCP
) == 0)
3635 static int sctp_show(struct filter
*f
)
3637 if (!filter_af_get(f
, AF_INET
) && !filter_af_get(f
, AF_INET6
))
3640 if (!getenv("PROC_NET_SCTP") && !getenv("PROC_ROOT")
3641 && inet_show_netlink(f
, NULL
, IPPROTO_SCTP
) == 0)
3647 static int dgram_show_line(char *line
, const struct filter
*f
, int family
)
3649 struct sockstat s
= {};
3650 char *loc
, *rem
, *data
;
3654 if (proc_inet_split_line(line
, &loc
, &rem
, &data
))
3657 int state
= (data
[1] >= 'A') ? (data
[1] - 'A' + 10) : (data
[1] - '0');
3659 if (!(f
->states
& (1 << state
)))
3662 proc_parse_inet_addr(loc
, rem
, family
, &s
);
3664 if (f
->f
&& run_ssfilter(f
->f
, &s
) == 0)
3668 n
= sscanf(data
, "%x %x:%x %*x:%*x %*x %d %*d %u %d %llx %[^\n]\n",
3669 &s
.state
, &s
.wq
, &s
.rq
,
3671 &s
.refcnt
, &s
.sk
, opt
);
3676 s
.type
= dg_proto
== UDP_PROTO
? IPPROTO_UDP
: 0;
3677 inet_stats_print(&s
, false);
3679 if (show_details
&& opt
[0])
3680 out(" opt:\"%s\"", opt
);
3685 static int udp_show(struct filter
*f
)
3689 if (!filter_af_get(f
, AF_INET
) && !filter_af_get(f
, AF_INET6
))
3692 dg_proto
= UDP_PROTO
;
3694 if (!getenv("PROC_NET_UDP") && !getenv("PROC_ROOT")
3695 && inet_show_netlink(f
, NULL
, IPPROTO_UDP
) == 0)
3698 if (f
->families
&FAMILY_MASK(AF_INET
)) {
3699 if ((fp
= net_udp_open()) == NULL
)
3701 if (generic_record_read(fp
, dgram_show_line
, f
, AF_INET
))
3706 if ((f
->families
&FAMILY_MASK(AF_INET6
)) &&
3707 (fp
= net_udp6_open()) != NULL
) {
3708 if (generic_record_read(fp
, dgram_show_line
, f
, AF_INET6
))
3716 int saved_errno
= errno
;
3720 errno
= saved_errno
;
3725 static int raw_show(struct filter
*f
)
3729 if (!filter_af_get(f
, AF_INET
) && !filter_af_get(f
, AF_INET6
))
3732 dg_proto
= RAW_PROTO
;
3734 if (!getenv("PROC_NET_RAW") && !getenv("PROC_ROOT") &&
3735 inet_show_netlink(f
, NULL
, IPPROTO_RAW
) == 0)
3738 if (f
->families
&FAMILY_MASK(AF_INET
)) {
3739 if ((fp
= net_raw_open()) == NULL
)
3741 if (generic_record_read(fp
, dgram_show_line
, f
, AF_INET
))
3746 if ((f
->families
&FAMILY_MASK(AF_INET6
)) &&
3747 (fp
= net_raw6_open()) != NULL
) {
3748 if (generic_record_read(fp
, dgram_show_line
, f
, AF_INET6
))
3756 int saved_errno
= errno
;
3760 errno
= saved_errno
;
3765 #define MAX_UNIX_REMEMBER (1024*1024/sizeof(struct sockstat))
3767 static void unix_list_drop_first(struct sockstat
**list
)
3769 struct sockstat
*s
= *list
;
3771 (*list
) = (*list
)->next
;
3776 static bool unix_type_skip(struct sockstat
*s
, struct filter
*f
)
3778 if (s
->type
== SOCK_STREAM
&& !(f
->dbs
&(1<<UNIX_ST_DB
)))
3780 if (s
->type
== SOCK_DGRAM
&& !(f
->dbs
&(1<<UNIX_DG_DB
)))
3782 if (s
->type
== SOCK_SEQPACKET
&& !(f
->dbs
&(1<<UNIX_SQ_DB
)))
3787 static void unix_stats_print(struct sockstat
*s
, struct filter
*f
)
3789 char port_name
[30] = {};
3791 sock_state_print(s
);
3793 sock_addr_print(s
->name
?: "*", " ",
3794 int_to_str(s
->lport
, port_name
), NULL
);
3795 sock_addr_print(s
->peer_name
?: "*", " ",
3796 int_to_str(s
->rport
, port_name
), NULL
);
3801 static int unix_show_sock(struct nlmsghdr
*nlh
, void *arg
)
3803 struct filter
*f
= (struct filter
*)arg
;
3804 struct unix_diag_msg
*r
= NLMSG_DATA(nlh
);
3805 struct rtattr
*tb
[UNIX_DIAG_MAX
+1];
3807 struct sockstat stat
= { .name
= "*", .peer_name
= "*" };
3809 parse_rtattr(tb
, UNIX_DIAG_MAX
, (struct rtattr
*)(r
+1),
3810 nlh
->nlmsg_len
- NLMSG_LENGTH(sizeof(*r
)));
3812 stat
.type
= r
->udiag_type
;
3813 stat
.state
= r
->udiag_state
;
3814 stat
.ino
= stat
.lport
= r
->udiag_ino
;
3815 stat
.local
.family
= stat
.remote
.family
= AF_UNIX
;
3817 if (unix_type_skip(&stat
, f
))
3820 if (tb
[UNIX_DIAG_RQLEN
]) {
3821 struct unix_diag_rqlen
*rql
= RTA_DATA(tb
[UNIX_DIAG_RQLEN
]);
3823 stat
.rq
= rql
->udiag_rqueue
;
3824 stat
.wq
= rql
->udiag_wqueue
;
3826 if (tb
[UNIX_DIAG_NAME
]) {
3827 int len
= RTA_PAYLOAD(tb
[UNIX_DIAG_NAME
]);
3829 memcpy(name
, RTA_DATA(tb
[UNIX_DIAG_NAME
]), len
);
3831 if (name
[0] == '\0') {
3833 for (i
= 0; i
< len
; i
++)
3834 if (name
[i
] == '\0')
3837 stat
.name
= &name
[0];
3838 memcpy(stat
.local
.data
, &stat
.name
, sizeof(stat
.name
));
3840 if (tb
[UNIX_DIAG_PEER
])
3841 stat
.rport
= rta_getattr_u32(tb
[UNIX_DIAG_PEER
]);
3843 if (f
->f
&& run_ssfilter(f
->f
, &stat
) == 0)
3846 unix_stats_print(&stat
, f
);
3849 print_skmeminfo(tb
, UNIX_DIAG_MEMINFO
);
3851 if (tb
[UNIX_DIAG_SHUTDOWN
]) {
3854 mask
= rta_getattr_u8(tb
[UNIX_DIAG_SHUTDOWN
]);
3856 mask
& 1 ? '-' : '<', mask
& 2 ? '-' : '>');
3858 if (tb
[UNIX_DIAG_VFS
]) {
3859 struct unix_diag_vfs
*uv
= RTA_DATA(tb
[UNIX_DIAG_VFS
]);
3861 out(" ino:%u dev:%u/%u", uv
->udiag_vfs_ino
, major(uv
->udiag_vfs_dev
),
3862 minor(uv
->udiag_vfs_dev
));
3864 if (tb
[UNIX_DIAG_ICONS
]) {
3865 int len
= RTA_PAYLOAD(tb
[UNIX_DIAG_ICONS
]);
3866 __u32
*peers
= RTA_DATA(tb
[UNIX_DIAG_ICONS
]);
3870 for (i
= 0; i
< len
/ sizeof(__u32
); i
++)
3871 out(" %u", peers
[i
]);
3878 static int handle_netlink_request(struct filter
*f
, struct nlmsghdr
*req
,
3879 size_t size
, rtnl_filter_t show_one_sock
)
3882 struct rtnl_handle rth
;
3884 if (rtnl_open_byproto(&rth
, 0, NETLINK_SOCK_DIAG
))
3887 rth
.dump
= MAGIC_SEQ
;
3889 if (rtnl_send(&rth
, req
, size
) < 0)
3892 if (rtnl_dump_filter(&rth
, show_one_sock
, f
))
3901 static int unix_show_netlink(struct filter
*f
)
3903 DIAG_REQUEST(req
, struct unix_diag_req r
);
3905 req
.r
.sdiag_family
= AF_UNIX
;
3906 req
.r
.udiag_states
= f
->states
;
3907 req
.r
.udiag_show
= UDIAG_SHOW_NAME
| UDIAG_SHOW_PEER
| UDIAG_SHOW_RQLEN
;
3909 req
.r
.udiag_show
|= UDIAG_SHOW_MEMINFO
;
3911 req
.r
.udiag_show
|= UDIAG_SHOW_VFS
| UDIAG_SHOW_ICONS
;
3913 return handle_netlink_request(f
, &req
.nlh
, sizeof(req
), unix_show_sock
);
3916 static int unix_show(struct filter
*f
)
3923 struct sockstat
*list
= NULL
;
3924 const int unix_state_map
[] = { SS_CLOSE
, SS_SYN_SENT
,
3925 SS_ESTABLISHED
, SS_CLOSING
};
3927 if (!filter_af_get(f
, AF_UNIX
))
3930 if (!getenv("PROC_NET_UNIX") && !getenv("PROC_ROOT")
3931 && unix_show_netlink(f
) == 0)
3934 if ((fp
= net_unix_open()) == NULL
)
3936 if (!fgets(buf
, sizeof(buf
), fp
)) {
3941 if (memcmp(buf
, "Peer", 4) == 0)
3945 while (fgets(buf
, sizeof(buf
), fp
)) {
3946 struct sockstat
*u
, **insp
;
3949 if (!(u
= calloc(1, sizeof(*u
))))
3952 if (sscanf(buf
, "%x: %x %x %x %x %x %d %s",
3953 &u
->rport
, &u
->rq
, &u
->wq
, &flags
, &u
->type
,
3954 &u
->state
, &u
->ino
, name
) < 8)
3958 u
->local
.family
= u
->remote
.family
= AF_UNIX
;
3960 if (flags
& (1 << 16)) {
3961 u
->state
= SS_LISTEN
;
3962 } else if (u
->state
> 0 &&
3963 u
->state
<= ARRAY_SIZE(unix_state_map
)) {
3964 u
->state
= unix_state_map
[u
->state
-1];
3965 if (u
->type
== SOCK_DGRAM
&& u
->state
== SS_CLOSE
&& u
->rport
)
3966 u
->state
= SS_ESTABLISHED
;
3968 if (unix_type_skip(u
, f
) ||
3969 !(f
->states
& (1 << u
->state
))) {
3981 u
->name
= strdup(name
);
3991 for (p
= list
; p
; p
= p
->next
) {
3992 if (u
->rport
== p
->lport
)
3998 u
->peer_name
= p
->name
? : "*";
4002 struct sockstat st
= {
4003 .local
.family
= AF_UNIX
,
4004 .remote
.family
= AF_UNIX
,
4007 memcpy(st
.local
.data
, &u
->name
, sizeof(u
->name
));
4008 /* when parsing the old format rport is set to 0 and
4009 * therefore peer_name remains NULL
4011 if (u
->peer_name
&& strcmp(u
->peer_name
, "*"))
4012 memcpy(st
.remote
.data
, &u
->peer_name
,
4013 sizeof(u
->peer_name
));
4014 if (run_ssfilter(f
->f
, &st
) == 0) {
4023 if (u
->type
< (*insp
)->type
||
4024 (u
->type
== (*insp
)->type
&&
4025 u
->ino
< (*insp
)->ino
))
4027 insp
= &(*insp
)->next
;
4032 if (++cnt
> MAX_UNIX_REMEMBER
) {
4034 unix_stats_print(list
, f
);
4035 unix_list_drop_first(&list
);
4042 unix_stats_print(list
, f
);
4043 unix_list_drop_first(&list
);
4049 static int packet_stats_print(struct sockstat
*s
, const struct filter
*f
)
4051 const char *addr
, *port
;
4054 s
->local
.family
= s
->remote
.family
= AF_PACKET
;
4057 s
->local
.data
[0] = s
->prot
;
4058 if (run_ssfilter(f
->f
, s
) == 0)
4062 sock_state_print(s
);
4067 addr
= ll_proto_n2a(htons(s
->prot
), ll_name
, sizeof(ll_name
));
4072 port
= xll_index_to_name(s
->iface
);
4074 sock_addr_print(addr
, ":", port
, NULL
);
4075 sock_addr_print("", "*", "", NULL
);
4080 sock_details_print(s
);
4085 static void packet_show_ring(struct packet_diag_ring
*ring
)
4087 out("blk_size:%d", ring
->pdr_block_size
);
4088 out(",blk_nr:%d", ring
->pdr_block_nr
);
4089 out(",frm_size:%d", ring
->pdr_frame_size
);
4090 out(",frm_nr:%d", ring
->pdr_frame_nr
);
4091 out(",tmo:%d", ring
->pdr_retire_tmo
);
4092 out(",features:0x%x", ring
->pdr_features
);
4095 static int packet_show_sock(struct nlmsghdr
*nlh
, void *arg
)
4097 const struct filter
*f
= arg
;
4098 struct packet_diag_msg
*r
= NLMSG_DATA(nlh
);
4099 struct packet_diag_info
*pinfo
= NULL
;
4100 struct packet_diag_ring
*ring_rx
= NULL
, *ring_tx
= NULL
;
4101 struct rtattr
*tb
[PACKET_DIAG_MAX
+1];
4102 struct sockstat stat
= {};
4103 uint32_t fanout
= 0;
4104 bool has_fanout
= false;
4106 parse_rtattr(tb
, PACKET_DIAG_MAX
, (struct rtattr
*)(r
+1),
4107 nlh
->nlmsg_len
- NLMSG_LENGTH(sizeof(*r
)));
4109 /* use /proc/net/packet if all info are not available */
4110 if (!tb
[PACKET_DIAG_MEMINFO
])
4113 stat
.type
= r
->pdiag_type
;
4114 stat
.prot
= r
->pdiag_num
;
4115 stat
.ino
= r
->pdiag_ino
;
4116 stat
.state
= SS_CLOSE
;
4117 stat
.sk
= cookie_sk_get(&r
->pdiag_cookie
[0]);
4119 if (tb
[PACKET_DIAG_MEMINFO
]) {
4120 __u32
*skmeminfo
= RTA_DATA(tb
[PACKET_DIAG_MEMINFO
]);
4122 stat
.rq
= skmeminfo
[SK_MEMINFO_RMEM_ALLOC
];
4125 if (tb
[PACKET_DIAG_INFO
]) {
4126 pinfo
= RTA_DATA(tb
[PACKET_DIAG_INFO
]);
4127 stat
.lport
= stat
.iface
= pinfo
->pdi_index
;
4130 if (tb
[PACKET_DIAG_UID
])
4131 stat
.uid
= rta_getattr_u32(tb
[PACKET_DIAG_UID
]);
4133 if (tb
[PACKET_DIAG_RX_RING
])
4134 ring_rx
= RTA_DATA(tb
[PACKET_DIAG_RX_RING
]);
4136 if (tb
[PACKET_DIAG_TX_RING
])
4137 ring_tx
= RTA_DATA(tb
[PACKET_DIAG_TX_RING
]);
4139 if (tb
[PACKET_DIAG_FANOUT
]) {
4141 fanout
= rta_getattr_u32(tb
[PACKET_DIAG_FANOUT
]);
4144 if (packet_stats_print(&stat
, f
))
4150 out(" ver:%d", pinfo
->pdi_version
);
4152 out("\n\tver:%d", pinfo
->pdi_version
);
4153 out(" cpy_thresh:%d", pinfo
->pdi_copy_thresh
);
4155 if (pinfo
->pdi_flags
& PDI_RUNNING
)
4157 if (pinfo
->pdi_flags
& PDI_AUXDATA
)
4159 if (pinfo
->pdi_flags
& PDI_ORIGDEV
)
4161 if (pinfo
->pdi_flags
& PDI_VNETHDR
)
4163 if (pinfo
->pdi_flags
& PDI_LOSS
)
4165 if (!pinfo
->pdi_flags
)
4173 out("\n\tring_rx(");
4174 packet_show_ring(ring_rx
);
4181 out("\n\tring_tx(");
4182 packet_show_ring(ring_tx
);
4186 uint16_t type
= (fanout
>> 16) & 0xffff;
4192 out("id:%d,", fanout
& 0xffff);
4214 if (show_bpf
&& tb
[PACKET_DIAG_FILTER
]) {
4215 struct sock_filter
*fil
=
4216 RTA_DATA(tb
[PACKET_DIAG_FILTER
]);
4217 int num
= RTA_PAYLOAD(tb
[PACKET_DIAG_FILTER
]) /
4218 sizeof(struct sock_filter
);
4221 out(" bpf filter (%d): ", num
);
4223 out("\n\tbpf filter (%d): ", num
);
4225 out(" 0x%02x %u %u %u,",
4226 fil
->code
, fil
->jt
, fil
->jf
, fil
->k
);
4233 print_skmeminfo(tb
, PACKET_DIAG_MEMINFO
);
4237 static int packet_show_netlink(struct filter
*f
)
4239 DIAG_REQUEST(req
, struct packet_diag_req r
);
4241 req
.r
.sdiag_family
= AF_PACKET
;
4242 req
.r
.pdiag_show
= PACKET_SHOW_INFO
| PACKET_SHOW_MEMINFO
|
4243 PACKET_SHOW_FILTER
| PACKET_SHOW_RING_CFG
| PACKET_SHOW_FANOUT
;
4245 return handle_netlink_request(f
, &req
.nlh
, sizeof(req
), packet_show_sock
);
4248 static int packet_show_line(char *buf
, const struct filter
*f
, int fam
)
4250 unsigned long long sk
;
4251 struct sockstat stat
= {};
4252 int type
, prot
, iface
, state
, rq
, uid
, ino
;
4254 sscanf(buf
, "%llx %*d %d %x %d %d %u %u %u",
4256 &type
, &prot
, &iface
, &state
,
4259 if (stat
.type
== SOCK_RAW
&& !(f
->dbs
&(1<<PACKET_R_DB
)))
4261 if (stat
.type
== SOCK_DGRAM
&& !(f
->dbs
&(1<<PACKET_DG_DB
)))
4266 stat
.lport
= stat
.iface
= iface
;
4271 stat
.state
= SS_CLOSE
;
4273 if (packet_stats_print(&stat
, f
))
4279 static int packet_show(struct filter
*f
)
4284 if (!filter_af_get(f
, AF_PACKET
) || !(f
->states
& (1 << SS_CLOSE
)))
4287 if (!getenv("PROC_NET_PACKET") && !getenv("PROC_ROOT") &&
4288 packet_show_netlink(f
) == 0)
4291 if ((fp
= net_packet_open()) == NULL
)
4293 if (generic_record_read(fp
, packet_show_line
, f
, AF_PACKET
))
4300 static int xdp_stats_print(struct sockstat
*s
, const struct filter
*f
)
4302 const char *addr
, *port
;
4305 s
->local
.family
= s
->remote
.family
= AF_XDP
;
4308 if (run_ssfilter(f
->f
, s
) == 0)
4312 sock_state_print(s
);
4315 addr
= xll_index_to_name(s
->iface
);
4316 snprintf(q_str
, sizeof(q_str
), "q%d", s
->lport
);
4318 sock_addr_print(addr
, ":", port
, NULL
);
4320 sock_addr_print("", "*", "", NULL
);
4323 sock_addr_print("", "*", "", NULL
);
4328 sock_details_print(s
);
4333 static void xdp_show_ring(const char *name
, struct xdp_diag_ring
*ring
)
4338 out("\n\t%s(", name
);
4339 out("entries:%u", ring
->entries
);
4343 static void xdp_show_umem(struct xdp_diag_umem
*umem
, struct xdp_diag_ring
*fr
,
4344 struct xdp_diag_ring
*cr
)
4350 out("id:%u", umem
->id
);
4351 out(",size:%llu", umem
->size
);
4352 out(",num_pages:%u", umem
->num_pages
);
4353 out(",chunk_size:%u", umem
->chunk_size
);
4354 out(",headroom:%u", umem
->headroom
);
4355 out(",ifindex:%u", umem
->ifindex
);
4356 out(",qid:%u", umem
->queue_id
);
4357 out(",zc:%u", umem
->flags
& XDP_DU_F_ZEROCOPY
);
4358 out(",refs:%u", umem
->refs
);
4362 xdp_show_ring("fr", fr
);
4364 xdp_show_ring("cr", cr
);
4367 static int xdp_show_sock(struct nlmsghdr
*nlh
, void *arg
)
4369 struct xdp_diag_ring
*rx
= NULL
, *tx
= NULL
, *fr
= NULL
, *cr
= NULL
;
4370 struct xdp_diag_msg
*msg
= NLMSG_DATA(nlh
);
4371 struct rtattr
*tb
[XDP_DIAG_MAX
+ 1];
4372 struct xdp_diag_info
*info
= NULL
;
4373 struct xdp_diag_umem
*umem
= NULL
;
4374 const struct filter
*f
= arg
;
4375 struct sockstat stat
= {};
4377 parse_rtattr(tb
, XDP_DIAG_MAX
, (struct rtattr
*)(msg
+ 1),
4378 nlh
->nlmsg_len
- NLMSG_LENGTH(sizeof(*msg
)));
4380 stat
.type
= msg
->xdiag_type
;
4381 stat
.ino
= msg
->xdiag_ino
;
4382 stat
.state
= SS_CLOSE
;
4383 stat
.sk
= cookie_sk_get(&msg
->xdiag_cookie
[0]);
4385 if (tb
[XDP_DIAG_INFO
]) {
4386 info
= RTA_DATA(tb
[XDP_DIAG_INFO
]);
4387 stat
.iface
= info
->ifindex
;
4388 stat
.lport
= info
->queue_id
;
4391 if (tb
[XDP_DIAG_UID
])
4392 stat
.uid
= rta_getattr_u32(tb
[XDP_DIAG_UID
]);
4393 if (tb
[XDP_DIAG_RX_RING
])
4394 rx
= RTA_DATA(tb
[XDP_DIAG_RX_RING
]);
4395 if (tb
[XDP_DIAG_TX_RING
])
4396 tx
= RTA_DATA(tb
[XDP_DIAG_TX_RING
]);
4397 if (tb
[XDP_DIAG_UMEM
])
4398 umem
= RTA_DATA(tb
[XDP_DIAG_UMEM
]);
4399 if (tb
[XDP_DIAG_UMEM_FILL_RING
])
4400 fr
= RTA_DATA(tb
[XDP_DIAG_UMEM_FILL_RING
]);
4401 if (tb
[XDP_DIAG_UMEM_COMPLETION_RING
])
4402 cr
= RTA_DATA(tb
[XDP_DIAG_UMEM_COMPLETION_RING
]);
4403 if (tb
[XDP_DIAG_MEMINFO
]) {
4404 __u32
*skmeminfo
= RTA_DATA(tb
[XDP_DIAG_MEMINFO
]);
4406 stat
.rq
= skmeminfo
[SK_MEMINFO_RMEM_ALLOC
];
4409 if (xdp_stats_print(&stat
, f
))
4414 xdp_show_ring("rx", rx
);
4416 xdp_show_ring("tx", tx
);
4418 xdp_show_umem(umem
, fr
, cr
);
4422 print_skmeminfo(tb
, XDP_DIAG_MEMINFO
); // really?
4428 static int xdp_show(struct filter
*f
)
4430 DIAG_REQUEST(req
, struct xdp_diag_req r
);
4432 if (!filter_af_get(f
, AF_XDP
) || !(f
->states
& (1 << SS_CLOSE
)))
4435 req
.r
.sdiag_family
= AF_XDP
;
4436 req
.r
.xdiag_show
= XDP_SHOW_INFO
| XDP_SHOW_RING_CFG
| XDP_SHOW_UMEM
|
4439 return handle_netlink_request(f
, &req
.nlh
, sizeof(req
), xdp_show_sock
);
4442 static int netlink_show_one(struct filter
*f
,
4443 int prot
, int pid
, unsigned int groups
,
4444 int state
, int dst_pid
, unsigned int dst_group
,
4446 unsigned long long sk
, unsigned long long cb
)
4448 struct sockstat st
= {
4452 .local
.family
= AF_NETLINK
,
4453 .remote
.family
= AF_NETLINK
,
4456 SPRINT_BUF(prot_buf
) = {};
4457 const char *prot_name
;
4458 char procname
[64] = {};
4463 st
.local
.data
[0] = prot
;
4464 if (run_ssfilter(f
->f
, &st
) == 0)
4468 sock_state_print(&st
);
4470 prot_name
= nl_proto_n2a(prot
, prot_buf
, sizeof(prot_buf
));
4474 } else if (!numeric
) {
4479 strncpy(procname
, "kernel", 7);
4480 } else if (pid
> 0) {
4483 snprintf(procname
, sizeof(procname
), "%s/%d/stat",
4484 getenv("PROC_ROOT") ? : "/proc", pid
);
4485 if ((fp
= fopen(procname
, "r")) != NULL
) {
4486 if (fscanf(fp
, "%*d (%[^)])", procname
) == 1) {
4487 snprintf(procname
+strlen(procname
),
4488 sizeof(procname
)-strlen(procname
),
4496 int_to_str(pid
, procname
);
4498 int_to_str(pid
, procname
);
4501 sock_addr_print(prot_name
, ":", procname
, NULL
);
4503 if (state
== NETLINK_CONNECTED
) {
4504 char dst_group_buf
[30];
4505 char dst_pid_buf
[30];
4507 sock_addr_print(int_to_str(dst_group
, dst_group_buf
), ":",
4508 int_to_str(dst_pid
, dst_pid_buf
), NULL
);
4510 sock_addr_print("", "*", "", NULL
);
4513 char *pid_context
= NULL
;
4515 if (show_proc_ctx
) {
4516 /* The pid value will either be:
4517 * 0 if destination kernel - show kernel initial context.
4518 * A valid process pid - use getpidcon.
4519 * A unique value allocated by the kernel or netlink user
4520 * to the process - show context as "not available".
4523 security_get_initial_context("kernel", &pid_context
);
4525 getpidcon(pid
, &pid_context
);
4527 out(" proc_ctx=%s", pid_context
? : "unavailable");
4532 out(" sk=%llx cb=%llx groups=0x%08x", sk
, cb
, groups
);
4538 static int netlink_show_sock(struct nlmsghdr
*nlh
, void *arg
)
4540 struct filter
*f
= (struct filter
*)arg
;
4541 struct netlink_diag_msg
*r
= NLMSG_DATA(nlh
);
4542 struct rtattr
*tb
[NETLINK_DIAG_MAX
+1];
4544 unsigned long groups
= 0;
4546 parse_rtattr(tb
, NETLINK_DIAG_MAX
, (struct rtattr
*)(r
+1),
4547 nlh
->nlmsg_len
- NLMSG_LENGTH(sizeof(*r
)));
4549 if (tb
[NETLINK_DIAG_GROUPS
] && RTA_PAYLOAD(tb
[NETLINK_DIAG_GROUPS
]))
4550 groups
= *(unsigned long *) RTA_DATA(tb
[NETLINK_DIAG_GROUPS
]);
4552 if (tb
[NETLINK_DIAG_MEMINFO
]) {
4553 const __u32
*skmeminfo
;
4555 skmeminfo
= RTA_DATA(tb
[NETLINK_DIAG_MEMINFO
]);
4557 rq
= skmeminfo
[SK_MEMINFO_RMEM_ALLOC
];
4558 wq
= skmeminfo
[SK_MEMINFO_WMEM_ALLOC
];
4561 if (netlink_show_one(f
, r
->ndiag_protocol
, r
->ndiag_portid
, groups
,
4562 r
->ndiag_state
, r
->ndiag_dst_portid
, r
->ndiag_dst_group
,
4569 print_skmeminfo(tb
, NETLINK_DIAG_MEMINFO
);
4575 static int netlink_show_netlink(struct filter
*f
)
4577 DIAG_REQUEST(req
, struct netlink_diag_req r
);
4579 req
.r
.sdiag_family
= AF_NETLINK
;
4580 req
.r
.sdiag_protocol
= NDIAG_PROTO_ALL
;
4581 req
.r
.ndiag_show
= NDIAG_SHOW_GROUPS
| NDIAG_SHOW_MEMINFO
;
4583 return handle_netlink_request(f
, &req
.nlh
, sizeof(req
), netlink_show_sock
);
4586 static int netlink_show(struct filter
*f
)
4591 unsigned int groups
;
4593 unsigned long long sk
, cb
;
4595 if (!filter_af_get(f
, AF_NETLINK
) || !(f
->states
& (1 << SS_CLOSE
)))
4598 if (!getenv("PROC_NET_NETLINK") && !getenv("PROC_ROOT") &&
4599 netlink_show_netlink(f
) == 0)
4602 if ((fp
= net_netlink_open()) == NULL
)
4604 if (!fgets(buf
, sizeof(buf
), fp
)) {
4609 while (fgets(buf
, sizeof(buf
), fp
)) {
4610 sscanf(buf
, "%llx %d %d %x %d %d %llx %d",
4612 &prot
, &pid
, &groups
, &rq
, &wq
, &cb
, &rc
);
4614 netlink_show_one(f
, prot
, pid
, groups
, 0, 0, 0, rq
, wq
, sk
, cb
);
4621 static bool vsock_type_skip(struct sockstat
*s
, struct filter
*f
)
4623 if (s
->type
== SOCK_STREAM
&& !(f
->dbs
& (1 << VSOCK_ST_DB
)))
4625 if (s
->type
== SOCK_DGRAM
&& !(f
->dbs
& (1 << VSOCK_DG_DB
)))
4630 static void vsock_addr_print(inet_prefix
*a
, __u32 port
)
4632 char cid_str
[sizeof("4294967295")];
4633 char port_str
[sizeof("4294967295")];
4636 memcpy(&cid
, a
->data
, sizeof(cid
));
4638 if (cid
== ~(__u32
)0)
4639 snprintf(cid_str
, sizeof(cid_str
), "*");
4641 snprintf(cid_str
, sizeof(cid_str
), "%u", cid
);
4643 if (port
== ~(__u32
)0)
4644 snprintf(port_str
, sizeof(port_str
), "*");
4646 snprintf(port_str
, sizeof(port_str
), "%u", port
);
4648 sock_addr_print(cid_str
, ":", port_str
, NULL
);
4651 static void vsock_stats_print(struct sockstat
*s
, struct filter
*f
)
4653 sock_state_print(s
);
4655 vsock_addr_print(&s
->local
, s
->lport
);
4656 vsock_addr_print(&s
->remote
, s
->rport
);
4661 static int vsock_show_sock(struct nlmsghdr
*nlh
, void *arg
)
4663 struct filter
*f
= (struct filter
*)arg
;
4664 struct vsock_diag_msg
*r
= NLMSG_DATA(nlh
);
4665 struct sockstat stat
= {
4666 .type
= r
->vdiag_type
,
4667 .lport
= r
->vdiag_src_port
,
4668 .rport
= r
->vdiag_dst_port
,
4669 .state
= r
->vdiag_state
,
4670 .ino
= r
->vdiag_ino
,
4673 vsock_set_inet_prefix(&stat
.local
, r
->vdiag_src_cid
);
4674 vsock_set_inet_prefix(&stat
.remote
, r
->vdiag_dst_cid
);
4676 if (vsock_type_skip(&stat
, f
))
4679 if (f
->f
&& run_ssfilter(f
->f
, &stat
) == 0)
4682 vsock_stats_print(&stat
, f
);
4687 static int vsock_show(struct filter
*f
)
4689 DIAG_REQUEST(req
, struct vsock_diag_req r
);
4691 if (!filter_af_get(f
, AF_VSOCK
))
4694 req
.r
.sdiag_family
= AF_VSOCK
;
4695 req
.r
.vdiag_states
= f
->states
;
4697 return handle_netlink_request(f
, &req
.nlh
, sizeof(req
), vsock_show_sock
);
4700 static void tipc_sock_addr_print(struct rtattr
*net_addr
, struct rtattr
*id
)
4702 uint32_t node
= rta_getattr_u32(net_addr
);
4703 uint32_t identity
= rta_getattr_u32(id
);
4705 SPRINT_BUF(addr
) = {};
4706 SPRINT_BUF(port
) = {};
4708 sprintf(addr
, "%u", node
);
4709 sprintf(port
, "%u", identity
);
4710 sock_addr_print(addr
, ":", port
, NULL
);
4714 static int tipc_show_sock(struct nlmsghdr
*nlh
, void *arg
)
4716 struct rtattr
*stat
[TIPC_NLA_SOCK_STAT_MAX
+ 1] = {};
4717 struct rtattr
*attrs
[TIPC_NLA_SOCK_MAX
+ 1] = {};
4718 struct rtattr
*con
[TIPC_NLA_CON_MAX
+ 1] = {};
4719 struct rtattr
*info
[TIPC_NLA_MAX
+ 1] = {};
4720 struct rtattr
*msg_ref
;
4721 struct sockstat ss
= {};
4723 parse_rtattr(info
, TIPC_NLA_MAX
, NLMSG_DATA(nlh
),
4724 NLMSG_PAYLOAD(nlh
, 0));
4726 if (!info
[TIPC_NLA_SOCK
])
4729 msg_ref
= info
[TIPC_NLA_SOCK
];
4730 parse_rtattr(attrs
, TIPC_NLA_SOCK_MAX
, RTA_DATA(msg_ref
),
4731 RTA_PAYLOAD(msg_ref
));
4733 msg_ref
= attrs
[TIPC_NLA_SOCK_STAT
];
4734 parse_rtattr(stat
, TIPC_NLA_SOCK_STAT_MAX
,
4735 RTA_DATA(msg_ref
), RTA_PAYLOAD(msg_ref
));
4738 ss
.local
.family
= AF_TIPC
;
4739 ss
.type
= rta_getattr_u32(attrs
[TIPC_NLA_SOCK_TYPE
]);
4740 ss
.state
= rta_getattr_u32(attrs
[TIPC_NLA_SOCK_TIPC_STATE
]);
4741 ss
.uid
= rta_getattr_u32(attrs
[TIPC_NLA_SOCK_UID
]);
4742 ss
.ino
= rta_getattr_u32(attrs
[TIPC_NLA_SOCK_INO
]);
4743 ss
.rq
= rta_getattr_u32(stat
[TIPC_NLA_SOCK_STAT_RCVQ
]);
4744 ss
.wq
= rta_getattr_u32(stat
[TIPC_NLA_SOCK_STAT_SENDQ
]);
4745 ss
.sk
= rta_getattr_u64(attrs
[TIPC_NLA_SOCK_COOKIE
]);
4747 sock_state_print (&ss
);
4749 tipc_sock_addr_print(attrs
[TIPC_NLA_SOCK_ADDR
],
4750 attrs
[TIPC_NLA_SOCK_REF
]);
4752 msg_ref
= attrs
[TIPC_NLA_SOCK_CON
];
4754 parse_rtattr(con
, TIPC_NLA_CON_MAX
,
4755 RTA_DATA(msg_ref
), RTA_PAYLOAD(msg_ref
));
4757 tipc_sock_addr_print(con
[TIPC_NLA_CON_NODE
],
4758 con
[TIPC_NLA_CON_SOCK
]);
4760 sock_addr_print("", "-", "", NULL
);
4763 sock_details_print(&ss
);
4765 proc_ctx_print(&ss
);
4767 if (show_tipcinfo
) {
4769 out(" type:%s", stype_nameg
[ss
.type
]);
4771 out("\n type:%s", stype_nameg
[ss
.type
]);
4773 stat
[TIPC_NLA_SOCK_STAT_LINK_CONG
] ? "link" :
4774 stat
[TIPC_NLA_SOCK_STAT_CONN_CONG
] ? "conn" : "none");
4776 rta_getattr_u32(stat
[TIPC_NLA_SOCK_STAT_DROP
]));
4778 if (attrs
[TIPC_NLA_SOCK_HAS_PUBL
])
4781 if (con
[TIPC_NLA_CON_FLAG
])
4782 out(" via {%u,%u} ",
4783 rta_getattr_u32(con
[TIPC_NLA_CON_TYPE
]),
4784 rta_getattr_u32(con
[TIPC_NLA_CON_INST
]));
4790 static int tipc_show(struct filter
*f
)
4792 DIAG_REQUEST(req
, struct tipc_sock_diag_req r
);
4794 memset(&req
.r
, 0, sizeof(req
.r
));
4795 req
.r
.sdiag_family
= AF_TIPC
;
4796 req
.r
.tidiag_states
= f
->states
;
4798 return handle_netlink_request(f
, &req
.nlh
, sizeof(req
), tipc_show_sock
);
4801 struct sock_diag_msg
{
4805 static int generic_show_sock(struct nlmsghdr
*nlh
, void *arg
)
4807 struct sock_diag_msg
*r
= NLMSG_DATA(nlh
);
4808 struct inet_diag_arg inet_arg
= { .f
= arg
, .protocol
= IPPROTO_MAX
};
4811 switch (r
->sdiag_family
) {
4814 inet_arg
.rth
= inet_arg
.f
->rth_for_killing
;
4815 ret
= show_one_inet_sock(nlh
, &inet_arg
);
4818 ret
= unix_show_sock(nlh
, arg
);
4821 ret
= packet_show_sock(nlh
, arg
);
4824 ret
= netlink_show_sock(nlh
, arg
);
4827 ret
= vsock_show_sock(nlh
, arg
);
4830 ret
= xdp_show_sock(nlh
, arg
);
4841 static int handle_follow_request(struct filter
*f
)
4845 struct rtnl_handle rth
, rth2
;
4847 if (f
->families
& FAMILY_MASK(AF_INET
) && f
->dbs
& (1 << TCP_DB
))
4848 groups
|= 1 << (SKNLGRP_INET_TCP_DESTROY
- 1);
4849 if (f
->families
& FAMILY_MASK(AF_INET
) && f
->dbs
& (1 << UDP_DB
))
4850 groups
|= 1 << (SKNLGRP_INET_UDP_DESTROY
- 1);
4851 if (f
->families
& FAMILY_MASK(AF_INET6
) && f
->dbs
& (1 << TCP_DB
))
4852 groups
|= 1 << (SKNLGRP_INET6_TCP_DESTROY
- 1);
4853 if (f
->families
& FAMILY_MASK(AF_INET6
) && f
->dbs
& (1 << UDP_DB
))
4854 groups
|= 1 << (SKNLGRP_INET6_UDP_DESTROY
- 1);
4859 if (rtnl_open_byproto(&rth
, groups
, NETLINK_SOCK_DIAG
))
4863 rth
.local
.nl_pid
= 0;
4866 if (rtnl_open_byproto(&rth2
, groups
, NETLINK_SOCK_DIAG
)) {
4870 f
->rth_for_killing
= &rth2
;
4873 if (rtnl_dump_filter(&rth
, generic_show_sock
, f
))
4877 if (f
->rth_for_killing
)
4878 rtnl_close(f
->rth_for_killing
);
4882 static int get_snmp_int(char *proto
, char *key
, int *result
)
4886 int protolen
= strlen(proto
);
4887 int keylen
= strlen(key
);
4891 if ((fp
= net_snmp_open()) == NULL
)
4894 while (fgets(buf
, sizeof(buf
), fp
) != NULL
) {
4898 if (memcmp(buf
, proto
, protolen
))
4900 while ((p
= strchr(p
, ' ')) != NULL
) {
4903 if (memcmp(p
, key
, keylen
) == 0 &&
4904 (p
[keylen
] == ' ' || p
[keylen
] == '\n'))
4907 if (fgets(buf
, sizeof(buf
), fp
) == NULL
)
4909 if (memcmp(buf
, proto
, protolen
))
4912 while ((p
= strchr(p
, ' ')) != NULL
) {
4915 sscanf(p
, "%d", result
);
4928 /* Get stats from sockstat */
4948 static void get_sockstat_line(char *line
, struct ssummary
*s
)
4950 char id
[256], rem
[256];
4952 if (sscanf(line
, "%[^ ] %[^\n]\n", id
, rem
) != 2)
4955 if (strcmp(id
, "sockets:") == 0)
4956 sscanf(rem
, "%*s%d", &s
->socks
);
4957 else if (strcmp(id
, "UDP:") == 0)
4958 sscanf(rem
, "%*s%d", &s
->udp4
);
4959 else if (strcmp(id
, "UDP6:") == 0)
4960 sscanf(rem
, "%*s%d", &s
->udp6
);
4961 else if (strcmp(id
, "RAW:") == 0)
4962 sscanf(rem
, "%*s%d", &s
->raw4
);
4963 else if (strcmp(id
, "RAW6:") == 0)
4964 sscanf(rem
, "%*s%d", &s
->raw6
);
4965 else if (strcmp(id
, "TCP6:") == 0)
4966 sscanf(rem
, "%*s%d", &s
->tcp6_hashed
);
4967 else if (strcmp(id
, "FRAG:") == 0)
4968 sscanf(rem
, "%*s%d%*s%d", &s
->frag4
, &s
->frag4_mem
);
4969 else if (strcmp(id
, "FRAG6:") == 0)
4970 sscanf(rem
, "%*s%d%*s%d", &s
->frag6
, &s
->frag6_mem
);
4971 else if (strcmp(id
, "TCP:") == 0)
4972 sscanf(rem
, "%*s%d%*s%d%*s%d%*s%d%*s%d",
4974 &s
->tcp_orphans
, &s
->tcp_tws
, &s
->tcp_total
, &s
->tcp_mem
);
4977 static int get_sockstat(struct ssummary
*s
)
4982 memset(s
, 0, sizeof(*s
));
4984 if ((fp
= net_sockstat_open()) == NULL
)
4986 while (fgets(buf
, sizeof(buf
), fp
) != NULL
)
4987 get_sockstat_line(buf
, s
);
4990 if ((fp
= net_sockstat6_open()) == NULL
)
4992 while (fgets(buf
, sizeof(buf
), fp
) != NULL
)
4993 get_sockstat_line(buf
, s
);
4999 static int print_summary(void)
5004 if (get_sockstat(&s
) < 0)
5005 perror("ss: get_sockstat");
5006 if (get_snmp_int("Tcp:", "CurrEstab", &tcp_estab
) < 0)
5007 perror("ss: get_snmpstat");
5009 printf("Total: %d\n", s
.socks
);
5011 printf("TCP: %d (estab %d, closed %d, orphaned %d, timewait %d)\n",
5012 s
.tcp_total
+ s
.tcp_tws
, tcp_estab
,
5013 s
.tcp_total
- (s
.tcp4_hashed
+ s
.tcp6_hashed
- s
.tcp_tws
),
5014 s
.tcp_orphans
, s
.tcp_tws
);
5017 printf("Transport Total IP IPv6\n");
5018 printf("RAW %-9d %-9d %-9d\n", s
.raw4
+s
.raw6
, s
.raw4
, s
.raw6
);
5019 printf("UDP %-9d %-9d %-9d\n", s
.udp4
+s
.udp6
, s
.udp4
, s
.udp6
);
5020 printf("TCP %-9d %-9d %-9d\n", s
.tcp4_hashed
+s
.tcp6_hashed
, s
.tcp4_hashed
, s
.tcp6_hashed
);
5021 printf("INET %-9d %-9d %-9d\n",
5022 s
.raw4
+s
.udp4
+s
.tcp4_hashed
+
5023 s
.raw6
+s
.udp6
+s
.tcp6_hashed
,
5024 s
.raw4
+s
.udp4
+s
.tcp4_hashed
,
5025 s
.raw6
+s
.udp6
+s
.tcp6_hashed
);
5026 printf("FRAG %-9d %-9d %-9d\n", s
.frag4
+s
.frag6
, s
.frag4
, s
.frag6
);
5033 static void _usage(FILE *dest
)
5036 "Usage: ss [ OPTIONS ]\n"
5037 " ss [ OPTIONS ] [ FILTER ]\n"
5038 " -h, --help this message\n"
5039 " -V, --version output version information\n"
5040 " -n, --numeric don't resolve service names\n"
5041 " -r, --resolve resolve host names\n"
5042 " -a, --all display all sockets\n"
5043 " -l, --listening display listening sockets\n"
5044 " -o, --options show timer information\n"
5045 " -e, --extended show detailed socket information\n"
5046 " -m, --memory show socket memory usage\n"
5047 " -p, --processes show process using socket\n"
5048 " -i, --info show internal TCP information\n"
5049 " --tipcinfo show internal tipc socket information\n"
5050 " -s, --summary show socket usage summary\n"
5051 " --tos show tos and priority information\n"
5052 " -b, --bpf show bpf filter socket information\n"
5053 " -E, --events continually display sockets as they are destroyed\n"
5054 " -Z, --context display process SELinux security contexts\n"
5055 " -z, --contexts display process and socket SELinux security contexts\n"
5056 " -N, --net switch to the specified network namespace name\n"
5058 " -4, --ipv4 display only IP version 4 sockets\n"
5059 " -6, --ipv6 display only IP version 6 sockets\n"
5060 " -0, --packet display PACKET sockets\n"
5061 " -t, --tcp display only TCP sockets\n"
5062 " -S, --sctp display only SCTP sockets\n"
5063 " -u, --udp display only UDP sockets\n"
5064 " -d, --dccp display only DCCP sockets\n"
5065 " -w, --raw display only RAW sockets\n"
5066 " -x, --unix display only Unix domain sockets\n"
5067 " --tipc display only TIPC sockets\n"
5068 " --vsock display only vsock sockets\n"
5069 " -f, --family=FAMILY display sockets of type FAMILY\n"
5070 " FAMILY := {inet|inet6|link|unix|netlink|vsock|tipc|xdp|help}\n"
5072 " -K, --kill forcibly close sockets, display what was closed\n"
5073 " -H, --no-header Suppress header line\n"
5074 " -O, --oneline socket's data printed on a single line\n"
5076 " -A, --query=QUERY, --socket=QUERY\n"
5077 " QUERY := {all|inet|tcp|udp|raw|unix|unix_dgram|unix_stream|unix_seqpacket|packet|netlink|vsock_stream|vsock_dgram|tipc}[,QUERY]\n"
5079 " -D, --diag=FILE Dump raw information about TCP sockets to FILE\n"
5080 " -F, --filter=FILE read filter information from FILE\n"
5081 " FILTER := [ state STATE-FILTER ] [ EXPRESSION ]\n"
5082 " STATE-FILTER := {all|connected|synchronized|bucket|big|TCP-STATES}\n"
5083 " TCP-STATES := {established|syn-sent|syn-recv|fin-wait-{1,2}|time-wait|closed|close-wait|last-ack|listening|closing}\n"
5084 " connected := {established|syn-sent|syn-recv|fin-wait-{1,2}|time-wait|close-wait|last-ack|closing}\n"
5085 " synchronized := {established|syn-recv|fin-wait-{1,2}|time-wait|close-wait|last-ack|closing}\n"
5086 " bucket := {syn-recv|time-wait}\n"
5087 " big := {established|syn-sent|fin-wait-{1,2}|closed|close-wait|last-ack|listening|closing}\n"
5091 static void help(void) __attribute__((noreturn
));
5092 static void help(void)
5098 static void usage(void) __attribute__((noreturn
));
5099 static void usage(void)
5106 static int scan_state(const char *state
)
5108 static const char * const sstate_namel
[] = {
5110 [SS_ESTABLISHED
] = "established",
5111 [SS_SYN_SENT
] = "syn-sent",
5112 [SS_SYN_RECV
] = "syn-recv",
5113 [SS_FIN_WAIT1
] = "fin-wait-1",
5114 [SS_FIN_WAIT2
] = "fin-wait-2",
5115 [SS_TIME_WAIT
] = "time-wait",
5116 [SS_CLOSE
] = "unconnected",
5117 [SS_CLOSE_WAIT
] = "close-wait",
5118 [SS_LAST_ACK
] = "last-ack",
5119 [SS_LISTEN
] = "listening",
5120 [SS_CLOSING
] = "closing",
5124 if (strcasecmp(state
, "close") == 0 ||
5125 strcasecmp(state
, "closed") == 0)
5126 return (1<<SS_CLOSE
);
5127 if (strcasecmp(state
, "syn-rcv") == 0)
5128 return (1<<SS_SYN_RECV
);
5129 if (strcasecmp(state
, "established") == 0)
5130 return (1<<SS_ESTABLISHED
);
5131 if (strcasecmp(state
, "all") == 0)
5133 if (strcasecmp(state
, "connected") == 0)
5134 return SS_ALL
& ~((1<<SS_CLOSE
)|(1<<SS_LISTEN
));
5135 if (strcasecmp(state
, "synchronized") == 0)
5136 return SS_ALL
& ~((1<<SS_CLOSE
)|(1<<SS_LISTEN
)|(1<<SS_SYN_SENT
));
5137 if (strcasecmp(state
, "bucket") == 0)
5138 return (1<<SS_SYN_RECV
)|(1<<SS_TIME_WAIT
);
5139 if (strcasecmp(state
, "big") == 0)
5140 return SS_ALL
& ~((1<<SS_SYN_RECV
)|(1<<SS_TIME_WAIT
));
5141 for (i
= 0; i
< SS_MAX
; i
++) {
5142 if (strcasecmp(state
, sstate_namel
[i
]) == 0)
5146 fprintf(stderr
, "ss: wrong state name: %s\n", state
);
5150 /* Values 'v' and 'V' are already used so a non-character is used */
5151 #define OPT_VSOCK 256
5153 /* Values of 't' are already used so a non-character is used */
5154 #define OPT_TIPCSOCK 257
5155 #define OPT_TIPCINFO 258
5159 /* Values of 'x' are already used so a non-character is used */
5160 #define OPT_XDPSOCK 260
5162 static const struct option long_opts
[] = {
5163 { "numeric", 0, 0, 'n' },
5164 { "resolve", 0, 0, 'r' },
5165 { "options", 0, 0, 'o' },
5166 { "extended", 0, 0, 'e' },
5167 { "memory", 0, 0, 'm' },
5168 { "info", 0, 0, 'i' },
5169 { "processes", 0, 0, 'p' },
5170 { "bpf", 0, 0, 'b' },
5171 { "events", 0, 0, 'E' },
5172 { "dccp", 0, 0, 'd' },
5173 { "tcp", 0, 0, 't' },
5174 { "sctp", 0, 0, 'S' },
5175 { "udp", 0, 0, 'u' },
5176 { "raw", 0, 0, 'w' },
5177 { "unix", 0, 0, 'x' },
5178 { "tipc", 0, 0, OPT_TIPCSOCK
},
5179 { "vsock", 0, 0, OPT_VSOCK
},
5180 { "all", 0, 0, 'a' },
5181 { "listening", 0, 0, 'l' },
5182 { "ipv4", 0, 0, '4' },
5183 { "ipv6", 0, 0, '6' },
5184 { "packet", 0, 0, '0' },
5185 { "family", 1, 0, 'f' },
5186 { "socket", 1, 0, 'A' },
5187 { "query", 1, 0, 'A' },
5188 { "summary", 0, 0, 's' },
5189 { "diag", 1, 0, 'D' },
5190 { "filter", 1, 0, 'F' },
5191 { "version", 0, 0, 'V' },
5192 { "help", 0, 0, 'h' },
5193 { "context", 0, 0, 'Z' },
5194 { "contexts", 0, 0, 'z' },
5195 { "net", 1, 0, 'N' },
5196 { "tipcinfo", 0, 0, OPT_TIPCINFO
},
5197 { "tos", 0, 0, OPT_TOS
},
5198 { "kill", 0, 0, 'K' },
5199 { "no-header", 0, 0, 'H' },
5200 { "xdp", 0, 0, OPT_XDPSOCK
},
5201 { "oneline", 0, 0, 'O' },
5206 int main(int argc
, char *argv
[])
5211 const char *dump_tcpdiag
= NULL
;
5212 FILE *filter_fp
= NULL
;
5214 int state_filter
= 0;
5216 while ((ch
= getopt_long(argc
, argv
,
5217 "dhaletuwxnro460spbEf:miA:D:F:vVzZN:KHSO",
5218 long_opts
, NULL
)) != EOF
) {
5241 user_ent_hash_build();
5251 filter_db_set(¤t_filter
, DCCP_DB
, true);
5254 filter_db_set(¤t_filter
, TCP_DB
, true);
5257 filter_db_set(¤t_filter
, SCTP_DB
, true);
5260 filter_db_set(¤t_filter
, UDP_DB
, true);
5263 filter_db_set(¤t_filter
, RAW_DB
, true);
5266 filter_af_set(¤t_filter
, AF_UNIX
);
5269 filter_af_set(¤t_filter
, AF_VSOCK
);
5272 filter_af_set(¤t_filter
, AF_TIPC
);
5275 state_filter
= SS_ALL
;
5278 state_filter
= (1 << SS_LISTEN
) | (1 << SS_CLOSE
);
5281 filter_af_set(¤t_filter
, AF_INET
);
5284 filter_af_set(¤t_filter
, AF_INET6
);
5287 filter_af_set(¤t_filter
, AF_PACKET
);
5290 filter_af_set(¤t_filter
, AF_XDP
);
5293 if (strcmp(optarg
, "inet") == 0)
5294 filter_af_set(¤t_filter
, AF_INET
);
5295 else if (strcmp(optarg
, "inet6") == 0)
5296 filter_af_set(¤t_filter
, AF_INET6
);
5297 else if (strcmp(optarg
, "link") == 0)
5298 filter_af_set(¤t_filter
, AF_PACKET
);
5299 else if (strcmp(optarg
, "unix") == 0)
5300 filter_af_set(¤t_filter
, AF_UNIX
);
5301 else if (strcmp(optarg
, "netlink") == 0)
5302 filter_af_set(¤t_filter
, AF_NETLINK
);
5303 else if (strcmp(optarg
, "tipc") == 0)
5304 filter_af_set(¤t_filter
, AF_TIPC
);
5305 else if (strcmp(optarg
, "vsock") == 0)
5306 filter_af_set(¤t_filter
, AF_VSOCK
);
5307 else if (strcmp(optarg
, "xdp") == 0)
5308 filter_af_set(¤t_filter
, AF_XDP
);
5309 else if (strcmp(optarg
, "help") == 0)
5312 fprintf(stderr
, "ss: \"%s\" is invalid family\n",
5322 current_filter
.dbs
= 0;
5323 state_filter
= state_filter
?
5324 state_filter
: SS_CONN
;
5330 if ((p1
= strchr(p
, ',')) != NULL
)
5332 if (filter_db_parse(¤t_filter
, p
)) {
5333 fprintf(stderr
, "ss: \"%s\" is illegal socket table id\n", p
);
5344 dump_tcpdiag
= optarg
;
5348 fprintf(stderr
, "More than one filter file\n");
5351 if (optarg
[0] == '-')
5354 filter_fp
= fopen(optarg
, "r");
5356 perror("fopen filter file");
5362 printf("ss utility, iproute2-ss%s\n", SNAPSHOT
);
5368 if (is_selinux_enabled() <= 0) {
5369 fprintf(stderr
, "ss: SELinux is not enabled.\n");
5373 user_ent_hash_build();
5376 if (netns_switch(optarg
))
5386 current_filter
.kill
= 1;
5407 if (do_default
&& argc
== 0)
5412 if (strcmp(*argv
, "state") == 0) {
5416 state_filter
|= scan_state(*argv
);
5418 } else if (strcmp(*argv
, "exclude") == 0 ||
5419 strcmp(*argv
, "excl") == 0) {
5422 state_filter
= SS_ALL
;
5423 state_filter
&= ~scan_state(*argv
);
5432 state_filter
= state_filter
? state_filter
: SS_CONN
;
5433 filter_db_parse(¤t_filter
, "all");
5436 filter_states_set(¤t_filter
, state_filter
);
5437 filter_merge_defaults(¤t_filter
);
5439 if (!numeric
&& resolve_hosts
&&
5440 (current_filter
.dbs
& (UNIX_DBM
|INET_L4_DBM
)))
5441 init_service_resolver();
5443 if (current_filter
.dbs
== 0) {
5444 fprintf(stderr
, "ss: no socket tables to show with such filter.\n");
5447 if (current_filter
.families
== 0) {
5448 fprintf(stderr
, "ss: no families to show with such filter.\n");
5451 if (current_filter
.states
== 0) {
5452 fprintf(stderr
, "ss: no socket states to show with such filter.\n");
5457 FILE *dump_fp
= stdout
;
5459 if (!(current_filter
.dbs
& (1<<TCP_DB
))) {
5460 fprintf(stderr
, "ss: tcpdiag dump requested and no tcp in filter.\n");
5463 if (dump_tcpdiag
[0] != '-') {
5464 dump_fp
= fopen(dump_tcpdiag
, "w");
5465 if (!dump_tcpdiag
) {
5466 perror("fopen dump file");
5470 inet_show_netlink(¤t_filter
, dump_fp
, IPPROTO_TCP
);
5475 if (ssfilter_parse(¤t_filter
.f
, argc
, argv
, filter_fp
))
5478 if (!(current_filter
.dbs
& (current_filter
.dbs
- 1)))
5479 columns
[COL_NETID
].disabled
= 1;
5481 if (!(current_filter
.states
& (current_filter
.states
- 1)))
5482 columns
[COL_STATE
].disabled
= 1;
5490 exit(handle_follow_request(¤t_filter
));
5492 if (current_filter
.dbs
& (1<<NETLINK_DB
))
5493 netlink_show(¤t_filter
);
5494 if (current_filter
.dbs
& PACKET_DBM
)
5495 packet_show(¤t_filter
);
5496 if (current_filter
.dbs
& UNIX_DBM
)
5497 unix_show(¤t_filter
);
5498 if (current_filter
.dbs
& (1<<RAW_DB
))
5499 raw_show(¤t_filter
);
5500 if (current_filter
.dbs
& (1<<UDP_DB
))
5501 udp_show(¤t_filter
);
5502 if (current_filter
.dbs
& (1<<TCP_DB
))
5503 tcp_show(¤t_filter
);
5504 if (current_filter
.dbs
& (1<<DCCP_DB
))
5505 dccp_show(¤t_filter
);
5506 if (current_filter
.dbs
& (1<<SCTP_DB
))
5507 sctp_show(¤t_filter
);
5508 if (current_filter
.dbs
& VSOCK_DBM
)
5509 vsock_show(¤t_filter
);
5510 if (current_filter
.dbs
& (1<<TIPC_DB
))
5511 tipc_show(¤t_filter
);
5512 if (current_filter
.dbs
& (1<<XDP_DB
))
5513 xdp_show(¤t_filter
);
5515 if (show_users
|| show_proc_ctx
|| show_sock_ctx
)