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"
39 #include <linux/tcp.h>
40 #include <linux/sock_diag.h>
41 #include <linux/inet_diag.h>
42 #include <linux/unix_diag.h>
43 #include <linux/netdevice.h> /* for MAX_ADDR_LEN */
44 #include <linux/filter.h>
45 #include <linux/packet_diag.h>
46 #include <linux/netlink_diag.h>
47 #include <linux/sctp.h>
48 #include <linux/vm_sockets_diag.h>
49 #include <linux/net.h>
50 #include <linux/tipc.h>
51 #include <linux/tipc_netlink.h>
52 #include <linux/tipc_sockets_diag.h>
54 #define MAGIC_SEQ 123456
55 #define BUF_CHUNK (1024 * 1024)
56 #define LEN_ALIGN(x) (((x) + 1) & ~1)
58 #define DIAG_REQUEST(_req, _r) \
60 struct nlmsghdr nlh; \
64 .nlmsg_type = SOCK_DIAG_BY_FAMILY, \
65 .nlmsg_flags = NLM_F_ROOT|NLM_F_MATCH|NLM_F_REQUEST,\
66 .nlmsg_seq = MAGIC_SEQ, \
67 .nlmsg_len = sizeof(_req), \
72 #include <selinux/selinux.h>
74 /* Stubs for SELinux functions */
75 static int is_selinux_enabled(void)
80 static int getpidcon(pid_t pid
, char **context
)
86 static int getfilecon(char *path
, char **context
)
92 static int security_get_initial_context(char *name
, char **context
)
99 int resolve_services
= 1;
100 int preferred_family
= AF_UNSPEC
;
134 const enum col_align align
;
138 int width
; /* Calculated, including additional layout spacing */
139 int max_len
; /* Measured maximum field length in this column */
142 static struct column columns
[] = {
143 { ALIGN_LEFT
, "Netid", "", 0, 0, 0 },
144 { ALIGN_LEFT
, "State", " ", 0, 0, 0 },
145 { ALIGN_LEFT
, "Recv-Q", " ", 0, 0, 0 },
146 { ALIGN_LEFT
, "Send-Q", " ", 0, 0, 0 },
147 { ALIGN_RIGHT
, "Local Address:", " ", 0, 0, 0 },
148 { ALIGN_LEFT
, "Port", "", 0, 0, 0 },
149 { ALIGN_RIGHT
, "Peer Address:", " ", 0, 0, 0 },
150 { ALIGN_LEFT
, "Port", "", 0, 0, 0 },
151 { ALIGN_LEFT
, "", "", 0, 0, 0 },
154 static struct column
*current_field
= columns
;
156 /* Output buffer: chained chunks of BUF_CHUNK bytes. Each field is written to
157 * the buffer as a variable size token. A token consists of a 16 bits length
158 * field, followed by a string which is not NULL-terminated.
160 * A new chunk is allocated and linked when the current chunk doesn't have
161 * enough room to store the current token as a whole.
164 struct buf_chunk
*next
; /* Next chained chunk */
165 char *end
; /* Current end of content */
170 uint16_t len
; /* Data length, excluding length descriptor */
175 struct buf_token
*cur
; /* Position of current token in chunk */
176 struct buf_chunk
*head
; /* First chunk */
177 struct buf_chunk
*tail
; /* Current chunk */
180 static const char *TCP_PROTO
= "tcp";
181 static const char *SCTP_PROTO
= "sctp";
182 static const char *UDP_PROTO
= "udp";
183 static const char *RAW_PROTO
= "raw";
184 static const char *dg_proto
;
204 #define PACKET_DBM ((1<<PACKET_DG_DB)|(1<<PACKET_R_DB))
205 #define UNIX_DBM ((1<<UNIX_DG_DB)|(1<<UNIX_ST_DB)|(1<<UNIX_SQ_DB))
206 #define ALL_DB ((1<<MAX_DB)-1)
207 #define INET_L4_DBM ((1<<TCP_DB)|(1<<UDP_DB)|(1<<DCCP_DB)|(1<<SCTP_DB))
208 #define INET_DBM (INET_L4_DBM | (1<<RAW_DB))
209 #define VSOCK_DBM ((1<<VSOCK_ST_DB)|(1<<VSOCK_DG_DB))
228 SCTP_STATE_CLOSED
= 0,
229 SCTP_STATE_COOKIE_WAIT
= 1,
230 SCTP_STATE_COOKIE_ECHOED
= 2,
231 SCTP_STATE_ESTABLISHED
= 3,
232 SCTP_STATE_SHUTDOWN_PENDING
= 4,
233 SCTP_STATE_SHUTDOWN_SENT
= 5,
234 SCTP_STATE_SHUTDOWN_RECEIVED
= 6,
235 SCTP_STATE_SHUTDOWN_ACK_SENT
= 7,
238 #define SS_ALL ((1 << SS_MAX) - 1)
239 #define SS_CONN (SS_ALL & ~((1<<SS_LISTEN)|(1<<SS_CLOSE)|(1<<SS_TIME_WAIT)|(1<<SS_SYN_RECV)))
240 #define TIPC_SS_CONN ((1<<SS_ESTABLISHED)|(1<<SS_LISTEN)|(1<<SS_CLOSE))
242 #include "ssfilter.h"
250 struct rtnl_handle
*rth_for_killing
;
253 #define FAMILY_MASK(family) ((uint64_t)1 << (family))
255 static const struct filter default_dbs
[MAX_DB
] = {
258 .families
= FAMILY_MASK(AF_INET
) | FAMILY_MASK(AF_INET6
),
262 .families
= FAMILY_MASK(AF_INET
) | FAMILY_MASK(AF_INET6
),
265 .states
= (1 << SS_ESTABLISHED
),
266 .families
= FAMILY_MASK(AF_INET
) | FAMILY_MASK(AF_INET6
),
269 .states
= (1 << SS_ESTABLISHED
),
270 .families
= FAMILY_MASK(AF_INET
) | FAMILY_MASK(AF_INET6
),
273 .states
= (1 << SS_CLOSE
),
274 .families
= FAMILY_MASK(AF_UNIX
),
278 .families
= FAMILY_MASK(AF_UNIX
),
282 .families
= FAMILY_MASK(AF_UNIX
),
285 .states
= (1 << SS_CLOSE
),
286 .families
= FAMILY_MASK(AF_PACKET
),
289 .states
= (1 << SS_CLOSE
),
290 .families
= FAMILY_MASK(AF_PACKET
),
293 .states
= (1 << SS_CLOSE
),
294 .families
= FAMILY_MASK(AF_NETLINK
),
298 .families
= FAMILY_MASK(AF_INET
) | FAMILY_MASK(AF_INET6
),
302 .families
= FAMILY_MASK(AF_VSOCK
),
306 .families
= FAMILY_MASK(AF_VSOCK
),
309 .states
= TIPC_SS_CONN
,
310 .families
= FAMILY_MASK(AF_TIPC
),
314 static const struct filter default_afs
[AF_MAX
] = {
329 .states
= (1 << SS_CLOSE
),
332 .dbs
= (1 << NETLINK_DB
),
333 .states
= (1 << SS_CLOSE
),
340 .dbs
= (1 << TIPC_DB
),
341 .states
= TIPC_SS_CONN
,
345 static int do_default
= 1;
346 static struct filter current_filter
;
348 static void filter_db_set(struct filter
*f
, int db
, bool enable
)
351 f
->states
|= default_dbs
[db
].states
;
354 f
->dbs
&= ~(1 << db
);
359 static int filter_db_parse(struct filter
*f
, const char *s
)
365 #define ENTRY(name, ...) { #name, { __VA_ARGS__, MAX_DB } }
366 ENTRY(all
, UDP_DB
, DCCP_DB
, TCP_DB
, RAW_DB
,
367 UNIX_ST_DB
, UNIX_DG_DB
, UNIX_SQ_DB
,
368 PACKET_R_DB
, PACKET_DG_DB
, NETLINK_DB
,
369 SCTP_DB
, VSOCK_ST_DB
, VSOCK_DG_DB
),
370 ENTRY(inet
, UDP_DB
, DCCP_DB
, TCP_DB
, SCTP_DB
, RAW_DB
),
372 ENTRY(dccp
, DCCP_DB
),
374 ENTRY(sctp
, SCTP_DB
),
376 ENTRY(unix
, UNIX_ST_DB
, UNIX_DG_DB
, UNIX_SQ_DB
),
377 ENTRY(unix_stream
, UNIX_ST_DB
),
378 ENTRY(u_str
, UNIX_ST_DB
), /* alias for unix_stream */
379 ENTRY(unix_dgram
, UNIX_DG_DB
),
380 ENTRY(u_dgr
, UNIX_DG_DB
), /* alias for unix_dgram */
381 ENTRY(unix_seqpacket
, UNIX_SQ_DB
),
382 ENTRY(u_seq
, UNIX_SQ_DB
), /* alias for unix_seqpacket */
383 ENTRY(packet
, PACKET_R_DB
, PACKET_DG_DB
),
384 ENTRY(packet_raw
, PACKET_R_DB
),
385 ENTRY(p_raw
, PACKET_R_DB
), /* alias for packet_raw */
386 ENTRY(packet_dgram
, PACKET_DG_DB
),
387 ENTRY(p_dgr
, PACKET_DG_DB
), /* alias for packet_dgram */
388 ENTRY(netlink
, NETLINK_DB
),
389 ENTRY(vsock
, VSOCK_ST_DB
, VSOCK_DG_DB
),
390 ENTRY(vsock_stream
, VSOCK_ST_DB
),
391 ENTRY(v_str
, VSOCK_ST_DB
), /* alias for vsock_stream */
392 ENTRY(vsock_dgram
, VSOCK_DG_DB
),
393 ENTRY(v_dgr
, VSOCK_DG_DB
), /* alias for vsock_dgram */
404 for (i
= 0; i
< ARRAY_SIZE(db_name_tbl
); i
++) {
405 if (strcmp(s
, db_name_tbl
[i
].name
))
407 for (dbp
= db_name_tbl
[i
].dbs
; *dbp
!= MAX_DB
; dbp
++)
408 filter_db_set(f
, *dbp
, enable
);
414 static void filter_af_set(struct filter
*f
, int af
)
416 f
->states
|= default_afs
[af
].states
;
417 f
->families
|= FAMILY_MASK(af
);
419 preferred_family
= af
;
422 static int filter_af_get(struct filter
*f
, int af
)
424 return !!(f
->families
& FAMILY_MASK(af
));
427 static void filter_states_set(struct filter
*f
, int states
)
433 static void filter_merge_defaults(struct filter
*f
)
438 for (db
= 0; db
< MAX_DB
; db
++) {
439 if (!(f
->dbs
& (1 << db
)))
442 if (!(default_dbs
[db
].families
& f
->families
))
443 f
->families
|= default_dbs
[db
].families
;
445 for (af
= 0; af
< AF_MAX
; af
++) {
446 if (!(f
->families
& FAMILY_MASK(af
)))
449 if (!(default_afs
[af
].dbs
& f
->dbs
))
450 f
->dbs
|= default_afs
[af
].dbs
;
454 static FILE *generic_proc_open(const char *env
, const char *name
)
456 const char *p
= getenv(env
);
460 p
= getenv("PROC_ROOT") ? : "/proc";
461 snprintf(store
, sizeof(store
)-1, "%s/%s", p
, name
);
465 return fopen(p
, "r");
467 #define net_tcp_open() generic_proc_open("PROC_NET_TCP", "net/tcp")
468 #define net_tcp6_open() generic_proc_open("PROC_NET_TCP6", "net/tcp6")
469 #define net_udp_open() generic_proc_open("PROC_NET_UDP", "net/udp")
470 #define net_udp6_open() generic_proc_open("PROC_NET_UDP6", "net/udp6")
471 #define net_raw_open() generic_proc_open("PROC_NET_RAW", "net/raw")
472 #define net_raw6_open() generic_proc_open("PROC_NET_RAW6", "net/raw6")
473 #define net_unix_open() generic_proc_open("PROC_NET_UNIX", "net/unix")
474 #define net_packet_open() generic_proc_open("PROC_NET_PACKET", \
476 #define net_netlink_open() generic_proc_open("PROC_NET_NETLINK", \
478 #define net_sockstat_open() generic_proc_open("PROC_NET_SOCKSTAT", \
480 #define net_sockstat6_open() generic_proc_open("PROC_NET_SOCKSTAT6", \
482 #define net_snmp_open() generic_proc_open("PROC_NET_SNMP", "net/snmp")
483 #define ephemeral_ports_open() generic_proc_open("PROC_IP_LOCAL_PORT_RANGE", \
484 "sys/net/ipv4/ip_local_port_range")
487 struct user_ent
*next
;
496 #define USER_ENT_HASH_SIZE 256
497 struct user_ent
*user_ent_hash
[USER_ENT_HASH_SIZE
];
499 static int user_ent_hashfn(unsigned int ino
)
501 int val
= (ino
>> 24) ^ (ino
>> 16) ^ (ino
>> 8) ^ ino
;
503 return val
& (USER_ENT_HASH_SIZE
- 1);
506 static void user_ent_add(unsigned int ino
, char *process
,
511 struct user_ent
*p
, **pp
;
513 p
= malloc(sizeof(struct user_ent
));
515 fprintf(stderr
, "ss: failed to malloc buffer\n");
522 p
->process
= strdup(process
);
523 p
->process_ctx
= strdup(proc_ctx
);
524 p
->socket_ctx
= strdup(sock_ctx
);
526 pp
= &user_ent_hash
[user_ent_hashfn(ino
)];
531 static void user_ent_destroy(void)
533 struct user_ent
*p
, *p_next
;
536 while (cnt
!= USER_ENT_HASH_SIZE
) {
537 p
= user_ent_hash
[cnt
];
540 free(p
->process_ctx
);
550 static void user_ent_hash_build(void)
552 const char *root
= getenv("PROC_ROOT") ? : "/proc/";
559 const char *no_ctx
= "unavailable";
560 static int user_ent_hash_build_init
;
562 /* If show_users & show_proc_ctx set only do this once */
563 if (user_ent_hash_build_init
!= 0)
566 user_ent_hash_build_init
= 1;
568 strlcpy(name
, root
, sizeof(name
));
570 if (strlen(name
) == 0 || name
[strlen(name
)-1] != '/')
573 nameoff
= strlen(name
);
579 while ((d
= readdir(dir
)) != NULL
) {
587 if (sscanf(d
->d_name
, "%d%c", &pid
, &crap
) != 1)
590 if (getpidcon(pid
, &pid_context
) != 0)
591 pid_context
= strdup(no_ctx
);
593 snprintf(name
+ nameoff
, sizeof(name
) - nameoff
, "%d/fd/", pid
);
595 if ((dir1
= opendir(name
)) == NULL
) {
603 while ((d1
= readdir(dir1
)) != NULL
) {
604 const char *pattern
= "socket:[";
611 if (sscanf(d1
->d_name
, "%d%c", &fd
, &crap
) != 1)
614 snprintf(name
+pos
, sizeof(name
) - pos
, "%d", fd
);
616 link_len
= readlink(name
, lnk
, sizeof(lnk
)-1);
619 lnk
[link_len
] = '\0';
621 if (strncmp(lnk
, pattern
, strlen(pattern
)))
624 sscanf(lnk
, "socket:[%u]", &ino
);
626 snprintf(tmp
, sizeof(tmp
), "%s/%d/fd/%s",
627 root
, pid
, d1
->d_name
);
629 if (getfilecon(tmp
, &sock_context
) <= 0)
630 sock_context
= strdup(no_ctx
);
635 snprintf(tmp
, sizeof(tmp
), "%s/%d/stat",
637 if ((fp
= fopen(tmp
, "r")) != NULL
) {
638 if (fscanf(fp
, "%*d (%[^)])", p
) < 1)
643 user_ent_add(ino
, p
, pid
, fd
,
644 pid_context
, sock_context
);
659 #define ENTRY_BUF_SIZE 512
660 static int find_entry(unsigned int ino
, char **buf
, int type
)
666 int len
, new_buf_len
;
673 p
= user_ent_hash
[user_ent_hashfn(ino
)];
680 ptr
= *buf
+ buf_used
;
683 len
= snprintf(ptr
, buf_len
- buf_used
,
684 "(\"%s\",pid=%d,fd=%d),",
685 p
->process
, p
->pid
, p
->fd
);
688 len
= snprintf(ptr
, buf_len
- buf_used
,
689 "(\"%s\",pid=%d,proc_ctx=%s,fd=%d),",
691 p
->process_ctx
, p
->fd
);
694 len
= snprintf(ptr
, buf_len
- buf_used
,
695 "(\"%s\",pid=%d,proc_ctx=%s,fd=%d,sock_ctx=%s),",
697 p
->process_ctx
, p
->fd
,
701 fprintf(stderr
, "ss: invalid type: %d\n", type
);
705 if (len
< 0 || len
>= buf_len
- buf_used
) {
706 new_buf_len
= buf_len
+ ENTRY_BUF_SIZE
;
707 new_buf
= realloc(*buf
, new_buf_len
);
709 fprintf(stderr
, "ss: failed to malloc buffer\n");
713 buf_len
= new_buf_len
;
725 ptr
= *buf
+ buf_used
;
731 static unsigned long long cookie_sk_get(const uint32_t *cookie
)
733 return (((unsigned long long)cookie
[1] << 31) << 1) | cookie
[0];
736 static const char *sctp_sstate_name
[] = {
737 [SCTP_STATE_CLOSED
] = "CLOSED",
738 [SCTP_STATE_COOKIE_WAIT
] = "COOKIE_WAIT",
739 [SCTP_STATE_COOKIE_ECHOED
] = "COOKIE_ECHOED",
740 [SCTP_STATE_ESTABLISHED
] = "ESTAB",
741 [SCTP_STATE_SHUTDOWN_PENDING
] = "SHUTDOWN_PENDING",
742 [SCTP_STATE_SHUTDOWN_SENT
] = "SHUTDOWN_SENT",
743 [SCTP_STATE_SHUTDOWN_RECEIVED
] = "SHUTDOWN_RECEIVED",
744 [SCTP_STATE_SHUTDOWN_ACK_SENT
] = "ACK_SENT",
747 static const char * const stype_nameg
[] = {
749 [SOCK_STREAM
] = "STREAM",
750 [SOCK_DGRAM
] = "DGRAM",
752 [SOCK_SEQPACKET
] = "SEQPACKET",
756 struct sockstat
*next
;
770 unsigned long long sk
;
777 unsigned int ce_state
;
787 unsigned int timeout
;
790 double rto
, ato
, rtt
, rttvar
;
791 int qack
, ssthresh
, backoff
;
800 unsigned int lastsnd
;
801 unsigned int lastrcv
;
802 unsigned int lastack
;
804 double pacing_rate_max
;
805 double delivery_rate
;
806 unsigned long long bytes_acked
;
807 unsigned long long bytes_received
;
808 unsigned int segs_out
;
809 unsigned int segs_in
;
810 unsigned int data_segs_out
;
811 unsigned int data_segs_in
;
812 unsigned int unacked
;
813 unsigned int retrans
;
814 unsigned int retrans_total
;
817 unsigned int fackets
;
818 unsigned int reordering
;
819 unsigned int not_sent
;
823 unsigned int rcv_ssthresh
;
824 unsigned long long busy_time
;
825 unsigned long long rwnd_limited
;
826 unsigned long long sndbuf_limited
;
830 bool has_ecnseen_opt
;
831 bool has_fastopen_opt
;
834 struct dctcpstat
*dctcp
;
835 struct tcp_bbr_info
*bbr_info
;
838 /* SCTP assocs share the same inode number with their parent endpoint. So if we
839 * have seen the inode number before, it must be an assoc instead of the next
841 static bool is_sctp_assoc(struct sockstat
*s
, const char *sock_name
)
843 if (strcmp(sock_name
, "sctp"))
845 if (!sctp_ino
|| sctp_ino
!= s
->ino
)
850 static const char *unix_netid_name(int type
)
863 static const char *proto_name(int protocol
)
883 static const char *vsock_netid_name(int type
)
895 static const char *tipc_netid_name(int type
)
911 /* Allocate and initialize a new buffer chunk */
912 static struct buf_chunk
*buf_chunk_new(void)
914 struct buf_chunk
*new = malloc(BUF_CHUNK
);
921 /* This is also the last block */
924 /* Next token will be stored at the beginning of chunk data area, and
925 * its initial length is zero.
927 buffer
.cur
= (struct buf_token
*)new->data
;
930 new->end
= buffer
.cur
->data
;
935 /* Return available tail room in given chunk */
936 static int buf_chunk_avail(struct buf_chunk
*chunk
)
938 return BUF_CHUNK
- offsetof(struct buf_chunk
, data
) -
939 (chunk
->end
- chunk
->data
);
942 /* Update end pointer and token length, link new chunk if we hit the end of the
943 * current one. Return -EAGAIN if we got a new chunk, caller has to print again.
945 static int buf_update(int len
)
947 struct buf_chunk
*chunk
= buffer
.tail
;
948 struct buf_token
*t
= buffer
.cur
;
950 /* Claim success if new content fits in the current chunk, and anyway
951 * if this is the first token in the chunk: in the latter case,
952 * allocating a new chunk won't help, so we'll just cut the output.
954 if ((len
< buf_chunk_avail(chunk
) && len
!= -1 /* glibc < 2.0.6 */) ||
955 t
== (struct buf_token
*)chunk
->data
) {
956 len
= min(len
, buf_chunk_avail(chunk
));
958 /* Total field length can't exceed 2^16 bytes, cut as needed */
959 len
= min(len
, USHRT_MAX
- t
->len
);
966 /* Content truncated, time to allocate more */
967 chunk
->next
= buf_chunk_new();
969 /* Copy current token over to new chunk, including length descriptor */
970 memcpy(chunk
->next
->data
, t
, sizeof(t
->len
) + t
->len
);
971 chunk
->next
->end
+= t
->len
;
973 /* Discard partially written field in old chunk */
974 chunk
->end
-= t
->len
+ sizeof(t
->len
);
979 /* Append content to buffer as part of the current field */
980 __attribute__((format(printf
, 1, 2)))
981 static void out(const char *fmt
, ...)
983 struct column
*f
= current_field
;
992 buffer
.head
= buf_chunk_new();
994 again
: /* Append to buffer: if we have a new chunk, print again */
996 pos
= buffer
.cur
->data
+ buffer
.cur
->len
;
999 /* Limit to tail room. If we hit the limit, buf_update() will tell us */
1000 len
= vsnprintf(pos
, buf_chunk_avail(buffer
.tail
), fmt
, args
);
1003 if (buf_update(len
))
1007 static int print_left_spacing(struct column
*f
, int stored
, int printed
)
1011 if (!f
->width
|| f
->align
== ALIGN_LEFT
)
1014 s
= f
->width
- stored
- printed
;
1015 if (f
->align
== ALIGN_CENTER
)
1016 /* If count of total spacing is odd, shift right by one */
1020 return printf("%*c", s
, ' ');
1025 static void print_right_spacing(struct column
*f
, int printed
)
1029 if (!f
->width
|| f
->align
== ALIGN_RIGHT
)
1032 s
= f
->width
- printed
;
1033 if (f
->align
== ALIGN_CENTER
)
1037 printf("%*c", s
, ' ');
1040 /* Done with field: update buffer pointer, start new token after current one */
1041 static void field_flush(struct column
*f
)
1043 struct buf_chunk
*chunk
;
1049 chunk
= buffer
.tail
;
1050 pad
= buffer
.cur
->len
% 2;
1052 if (buffer
.cur
->len
> f
->max_len
)
1053 f
->max_len
= buffer
.cur
->len
;
1055 /* We need a new chunk if we can't store the next length descriptor.
1056 * Mind the gap between end of previous token and next aligned position
1057 * for length descriptor.
1059 if (buf_chunk_avail(chunk
) - pad
< sizeof(buffer
.cur
->len
)) {
1061 chunk
->next
= buf_chunk_new();
1065 buffer
.cur
= (struct buf_token
*)(buffer
.cur
->data
+
1066 LEN_ALIGN(buffer
.cur
->len
));
1067 buffer
.cur
->len
= 0;
1068 buffer
.tail
->end
= buffer
.cur
->data
;
1071 static int field_is_last(struct column
*f
)
1073 return f
- columns
== COL_MAX
- 1;
1076 static void field_next(void)
1078 field_flush(current_field
);
1080 if (field_is_last(current_field
))
1081 current_field
= columns
;
1086 /* Walk through fields and flush them until we reach the desired one */
1087 static void field_set(enum col_id id
)
1089 while (id
!= current_field
- columns
)
1093 /* Print header for all non-empty columns */
1094 static void print_header(void)
1096 while (!field_is_last(current_field
)) {
1097 if (!current_field
->disabled
)
1098 out("%s", current_field
->header
);
1103 /* Get the next available token in the buffer starting from the current token */
1104 static struct buf_token
*buf_token_next(struct buf_token
*cur
)
1106 struct buf_chunk
*chunk
= buffer
.tail
;
1108 /* If we reached the end of chunk contents, get token from next chunk */
1109 if (cur
->data
+ LEN_ALIGN(cur
->len
) == chunk
->end
) {
1110 buffer
.tail
= chunk
= chunk
->next
;
1111 return chunk
? (struct buf_token
*)chunk
->data
: NULL
;
1114 return (struct buf_token
*)(cur
->data
+ LEN_ALIGN(cur
->len
));
1117 /* Free up all allocated buffer chunks */
1118 static void buf_free_all(void)
1120 struct buf_chunk
*tmp
;
1122 for (buffer
.tail
= buffer
.head
; buffer
.tail
; ) {
1124 buffer
.tail
= buffer
.tail
->next
;
1130 /* Get current screen width, default to 80 columns if TIOCGWINSZ fails */
1131 static int render_screen_width(void)
1135 if (isatty(STDOUT_FILENO
)) {
1138 if (ioctl(STDOUT_FILENO
, TIOCGWINSZ
, &w
) != -1) {
1147 /* Calculate column width from contents length. If columns don't fit on one
1148 * line, break them into the least possible amount of lines and keep them
1149 * aligned across lines. Available screen space is equally spread between fields
1150 * as additional spacing.
1152 static void render_calc_width(void)
1154 int screen_width
= render_screen_width();
1155 struct column
*c
, *eol
= columns
- 1;
1156 int first
, len
= 0, linecols
= 0;
1158 /* First pass: set width for each column to measured content length */
1159 for (first
= 1, c
= columns
; c
- columns
< COL_MAX
; c
++) {
1163 if (!first
&& c
->max_len
)
1164 c
->width
= c
->max_len
+ strlen(c
->ldelim
);
1166 c
->width
= c
->max_len
;
1168 /* But don't exceed screen size. If we exceed the screen size
1169 * for even a single field, it will just start on a line of its
1170 * own and then naturally wrap.
1172 c
->width
= min(c
->width
, screen_width
);
1178 /* Second pass: find out newlines and distribute available spacing */
1179 for (c
= columns
; c
- columns
< COL_MAX
; c
++) {
1180 int pad
, spacing
, rem
, last
;
1189 for (last
= 1, tmp
= c
+ 1; tmp
- columns
< COL_MAX
; tmp
++) {
1196 if (!last
&& len
< screen_width
) {
1197 /* Columns fit on screen so far, nothing to do yet */
1201 if (len
== screen_width
) {
1202 /* Exact fit, just start with new line */
1206 if (len
> screen_width
) {
1207 /* Screen width exceeded: go back one column */
1213 /* Distribute remaining space to columns on this line */
1214 pad
= screen_width
- len
;
1215 spacing
= pad
/ linecols
;
1216 rem
= pad
% linecols
;
1217 for (tmp
= c
; tmp
> eol
; tmp
--) {
1221 tmp
->width
+= spacing
;
1229 /* Line break: reset line counters, mark end-of-line */
1236 /* Render buffered output with spacing and delimiters, then free up buffers */
1237 static void render(void)
1239 struct buf_token
*token
;
1240 int printed
, line_started
= 0;
1246 token
= (struct buf_token
*)buffer
.head
->data
;
1248 /* Ensure end alignment of last token, it wasn't necessarily flushed */
1249 buffer
.tail
->end
+= buffer
.cur
->len
% 2;
1251 render_calc_width();
1253 /* Rewind and replay */
1254 buffer
.tail
= buffer
.head
;
1261 /* Print left delimiter only if we already started a line */
1263 printed
= printf("%s", current_field
->ldelim
);
1267 /* Print field content from token data with spacing */
1268 printed
+= print_left_spacing(f
, token
->len
, printed
);
1269 printed
+= fwrite(token
->data
, 1, token
->len
, stdout
);
1270 print_right_spacing(f
, printed
);
1272 /* Go to next non-empty field, deal with end-of-line */
1274 if (field_is_last(f
)) {
1281 } while (f
->disabled
);
1283 token
= buf_token_next(token
);
1287 current_field
= columns
;
1290 static void sock_state_print(struct sockstat
*s
)
1292 const char *sock_name
;
1293 static const char * const sstate_name
[] = {
1295 [SS_ESTABLISHED
] = "ESTAB",
1296 [SS_SYN_SENT
] = "SYN-SENT",
1297 [SS_SYN_RECV
] = "SYN-RECV",
1298 [SS_FIN_WAIT1
] = "FIN-WAIT-1",
1299 [SS_FIN_WAIT2
] = "FIN-WAIT-2",
1300 [SS_TIME_WAIT
] = "TIME-WAIT",
1301 [SS_CLOSE
] = "UNCONN",
1302 [SS_CLOSE_WAIT
] = "CLOSE-WAIT",
1303 [SS_LAST_ACK
] = "LAST-ACK",
1304 [SS_LISTEN
] = "LISTEN",
1305 [SS_CLOSING
] = "CLOSING",
1308 switch (s
->local
.family
) {
1310 sock_name
= unix_netid_name(s
->type
);
1314 sock_name
= proto_name(s
->type
);
1317 sock_name
= s
->type
== SOCK_RAW
? "p_raw" : "p_dgr";
1323 sock_name
= tipc_netid_name(s
->type
);
1326 sock_name
= vsock_netid_name(s
->type
);
1329 sock_name
= "unknown";
1332 if (is_sctp_assoc(s
, sock_name
)) {
1333 field_set(COL_STATE
); /* Empty Netid field */
1334 out("`- %s", sctp_sstate_name
[s
->state
]);
1336 field_set(COL_NETID
);
1337 out("%s", sock_name
);
1338 field_set(COL_STATE
);
1339 out("%s", sstate_name
[s
->state
]);
1342 field_set(COL_RECVQ
);
1344 field_set(COL_SENDQ
);
1346 field_set(COL_ADDR
);
1349 static void sock_details_print(struct sockstat
*s
)
1352 out(" uid:%u", s
->uid
);
1354 out(" ino:%u", s
->ino
);
1355 out(" sk:%llx", s
->sk
);
1358 out(" fwmark:0x%x", s
->mark
);
1361 static void sock_addr_print(const char *addr
, char *delim
, const char *port
,
1365 out("%s" "%%" "%s%s", addr
, ifname
, delim
);
1367 out("%s%s", addr
, delim
);
1374 static const char *print_ms_timer(unsigned int timeout
)
1376 static char buf
[64];
1377 int secs
, msecs
, minutes
;
1379 secs
= timeout
/1000;
1382 msecs
= timeout
%1000;
1386 snprintf(buf
, sizeof(buf
)-16, "%dmin", minutes
);
1393 sprintf(buf
+strlen(buf
), "%d%s", secs
, msecs
? "." : "sec");
1396 sprintf(buf
+strlen(buf
), "%03dms", msecs
);
1401 struct scache
*next
;
1407 struct scache
*rlist
;
1409 static void init_service_resolver(void)
1412 FILE *fp
= popen("/usr/sbin/rpcinfo -p 2>/dev/null", "r");
1417 if (!fgets(buf
, sizeof(buf
), fp
)) {
1421 while (fgets(buf
, sizeof(buf
), fp
) != NULL
) {
1422 unsigned int progn
, port
;
1423 char proto
[128], prog
[128] = "rpc.";
1426 if (sscanf(buf
, "%u %*d %s %u %s",
1427 &progn
, proto
, &port
, prog
+4) != 4)
1430 if (!(c
= malloc(sizeof(*c
))))
1434 c
->name
= strdup(prog
);
1435 if (strcmp(proto
, TCP_PROTO
) == 0)
1436 c
->proto
= TCP_PROTO
;
1437 else if (strcmp(proto
, UDP_PROTO
) == 0)
1438 c
->proto
= UDP_PROTO
;
1439 else if (strcmp(proto
, SCTP_PROTO
) == 0)
1440 c
->proto
= SCTP_PROTO
;
1449 /* Even do not try default linux ephemeral port ranges:
1450 * default /etc/services contains so much of useless crap
1451 * wouldbe "allocated" to this area that resolution
1452 * is really harmful. I shrug each time when seeing
1453 * "socks" or "cfinger" in dumps.
1455 static int is_ephemeral(int port
)
1457 static int min
= 0, max
;
1460 FILE *f
= ephemeral_ports_open();
1462 if (!f
|| fscanf(f
, "%d %d", &min
, &max
) < 2) {
1469 return port
>= min
&& port
<= max
;
1473 static const char *__resolve_service(int port
)
1477 for (c
= rlist
; c
; c
= c
->next
) {
1478 if (c
->port
== port
&& c
->proto
== dg_proto
)
1482 if (!is_ephemeral(port
)) {
1483 static int notfirst
;
1490 se
= getservbyport(htons(port
), dg_proto
);
1498 #define SCACHE_BUCKETS 1024
1499 static struct scache
*cache_htab
[SCACHE_BUCKETS
];
1501 static const char *resolve_service(int port
)
1503 static char buf
[128];
1514 if (!resolve_services
)
1517 if (dg_proto
== RAW_PROTO
)
1518 return inet_proto_n2a(port
, buf
, sizeof(buf
));
1521 hash
= (port
^(((unsigned long)dg_proto
)>>2)) % SCACHE_BUCKETS
;
1523 for (c
= cache_htab
[hash
]; c
; c
= c
->next
) {
1524 if (c
->port
== port
&& c
->proto
== dg_proto
)
1528 c
= malloc(sizeof(*c
));
1531 res
= __resolve_service(port
);
1533 c
->name
= res
? strdup(res
) : NULL
;
1534 c
->proto
= dg_proto
;
1535 c
->next
= cache_htab
[hash
];
1536 cache_htab
[hash
] = c
;
1543 sprintf(buf
, "%u", port
);
1547 static void inet_addr_print(const inet_prefix
*a
, int port
,
1548 unsigned int ifindex
, bool v6only
)
1551 const char *ap
= buf
;
1552 const char *ifname
= NULL
;
1554 if (a
->family
== AF_INET
) {
1555 ap
= format_host(AF_INET
, 4, a
->data
);
1558 !memcmp(a
->data
, &in6addr_any
, sizeof(in6addr_any
))) {
1562 ap
= format_host(a
->family
, 16, a
->data
);
1564 /* Numeric IPv6 addresses should be bracketed */
1565 if (strchr(ap
, ':')) {
1566 snprintf(buf
, sizeof(buf
),
1574 ifname
= ll_index_to_name(ifindex
);
1576 sock_addr_print(ap
, ":", resolve_service(port
), ifname
);
1585 struct aafilter
*next
;
1588 static int inet2_addr_match(const inet_prefix
*a
, const inet_prefix
*p
,
1591 if (!inet_addr_match(a
, p
, plen
))
1594 /* Cursed "v4 mapped" addresses: v4 mapped socket matches
1595 * pure IPv4 rule, but v4-mapped rule selects only v4-mapped
1597 if (p
->family
== AF_INET
&& a
->family
== AF_INET6
) {
1598 if (a
->data
[0] == 0 && a
->data
[1] == 0 &&
1599 a
->data
[2] == htonl(0xffff)) {
1600 inet_prefix tmp
= *a
;
1602 tmp
.data
[0] = a
->data
[3];
1603 return inet_addr_match(&tmp
, p
, plen
);
1609 static int unix_match(const inet_prefix
*a
, const inet_prefix
*p
)
1611 char *addr
, *pattern
;
1613 memcpy(&addr
, a
->data
, sizeof(addr
));
1614 memcpy(&pattern
, p
->data
, sizeof(pattern
));
1615 if (pattern
== NULL
)
1619 return !fnmatch(pattern
, addr
, 0);
1622 static int run_ssfilter(struct ssfilter
*f
, struct sockstat
*s
)
1627 if (s
->local
.family
== AF_UNIX
) {
1630 memcpy(&p
, s
->local
.data
, sizeof(p
));
1631 return p
== NULL
|| (p
[0] == '@' && strlen(p
) == 6 &&
1632 strspn(p
+1, "0123456789abcdef") == 5);
1634 if (s
->local
.family
== AF_PACKET
)
1635 return s
->lport
== 0 && s
->local
.data
[0] == 0;
1636 if (s
->local
.family
== AF_NETLINK
)
1637 return s
->lport
< 0;
1638 if (s
->local
.family
== AF_VSOCK
)
1639 return s
->lport
> 1023;
1641 return is_ephemeral(s
->lport
);
1645 struct aafilter
*a
= (void *)f
->pred
;
1647 if (a
->addr
.family
== AF_UNIX
)
1648 return unix_match(&s
->remote
, &a
->addr
);
1649 if (a
->port
!= -1 && a
->port
!= s
->rport
)
1651 if (a
->addr
.bitlen
) {
1653 if (!inet2_addr_match(&s
->remote
, &a
->addr
, a
->addr
.bitlen
))
1655 } while ((a
= a
->next
) != NULL
);
1662 struct aafilter
*a
= (void *)f
->pred
;
1664 if (a
->addr
.family
== AF_UNIX
)
1665 return unix_match(&s
->local
, &a
->addr
);
1666 if (a
->port
!= -1 && a
->port
!= s
->lport
)
1668 if (a
->addr
.bitlen
) {
1670 if (!inet2_addr_match(&s
->local
, &a
->addr
, a
->addr
.bitlen
))
1672 } while ((a
= a
->next
) != NULL
);
1679 struct aafilter
*a
= (void *)f
->pred
;
1681 return s
->rport
>= a
->port
;
1685 struct aafilter
*a
= (void *)f
->pred
;
1687 return s
->rport
<= a
->port
;
1691 struct aafilter
*a
= (void *)f
->pred
;
1693 return s
->lport
>= a
->port
;
1697 struct aafilter
*a
= (void *)f
->pred
;
1699 return s
->lport
<= a
->port
;
1703 struct aafilter
*a
= (void *)f
->pred
;
1705 return s
->iface
== a
->iface
;
1709 struct aafilter
*a
= (void *)f
->pred
;
1711 return (s
->mark
& a
->mask
) == a
->mark
;
1713 /* Yup. It is recursion. Sorry. */
1715 return run_ssfilter(f
->pred
, s
) && run_ssfilter(f
->post
, s
);
1717 return run_ssfilter(f
->pred
, s
) || run_ssfilter(f
->post
, s
);
1719 return !run_ssfilter(f
->pred
, s
);
1725 /* Relocate external jumps by reloc. */
1726 static void ssfilter_patch(char *a
, int len
, int reloc
)
1729 struct inet_diag_bc_op
*op
= (struct inet_diag_bc_op
*)a
;
1731 if (op
->no
== len
+4)
1740 static int ssfilter_bytecompile(struct ssfilter
*f
, char **bytecode
)
1745 if (!(*bytecode
= malloc(4))) abort();
1746 ((struct inet_diag_bc_op
*)*bytecode
)[0] = (struct inet_diag_bc_op
){ INET_DIAG_BC_AUTO
, 4, 8 };
1752 struct aafilter
*a
= (void *)f
->pred
;
1755 int code
= (f
->type
== SSF_DCOND
? INET_DIAG_BC_D_COND
: INET_DIAG_BC_S_COND
);
1758 for (b
= a
; b
; b
= b
->next
) {
1759 len
+= 4 + sizeof(struct inet_diag_hostcond
);
1760 if (a
->addr
.family
== AF_INET6
)
1767 if (!(ptr
= malloc(len
))) abort();
1769 for (b
= a
; b
; b
= b
->next
) {
1770 struct inet_diag_bc_op
*op
= (struct inet_diag_bc_op
*)ptr
;
1771 int alen
= (a
->addr
.family
== AF_INET6
? 16 : 4);
1772 int oplen
= alen
+ 4 + sizeof(struct inet_diag_hostcond
);
1773 struct inet_diag_hostcond
*cond
= (struct inet_diag_hostcond
*)(ptr
+4);
1775 *op
= (struct inet_diag_bc_op
){ code
, oplen
, oplen
+4 };
1776 cond
->family
= a
->addr
.family
;
1777 cond
->port
= a
->port
;
1778 cond
->prefix_len
= a
->addr
.bitlen
;
1779 memcpy(cond
->addr
, a
->addr
.data
, alen
);
1782 op
= (struct inet_diag_bc_op
*)ptr
;
1783 *op
= (struct inet_diag_bc_op
){ INET_DIAG_BC_JMP
, 4, len
- (ptr
-*bytecode
)};
1787 return ptr
- *bytecode
;
1791 struct aafilter
*x
= (void *)f
->pred
;
1793 if (!(*bytecode
= malloc(8))) abort();
1794 ((struct inet_diag_bc_op
*)*bytecode
)[0] = (struct inet_diag_bc_op
){ INET_DIAG_BC_D_GE
, 8, 12 };
1795 ((struct inet_diag_bc_op
*)*bytecode
)[1] = (struct inet_diag_bc_op
){ 0, 0, x
->port
};
1800 struct aafilter
*x
= (void *)f
->pred
;
1802 if (!(*bytecode
= malloc(8))) abort();
1803 ((struct inet_diag_bc_op
*)*bytecode
)[0] = (struct inet_diag_bc_op
){ INET_DIAG_BC_D_LE
, 8, 12 };
1804 ((struct inet_diag_bc_op
*)*bytecode
)[1] = (struct inet_diag_bc_op
){ 0, 0, x
->port
};
1809 struct aafilter
*x
= (void *)f
->pred
;
1811 if (!(*bytecode
= malloc(8))) abort();
1812 ((struct inet_diag_bc_op
*)*bytecode
)[0] = (struct inet_diag_bc_op
){ INET_DIAG_BC_S_GE
, 8, 12 };
1813 ((struct inet_diag_bc_op
*)*bytecode
)[1] = (struct inet_diag_bc_op
){ 0, 0, x
->port
};
1818 struct aafilter
*x
= (void *)f
->pred
;
1820 if (!(*bytecode
= malloc(8))) abort();
1821 ((struct inet_diag_bc_op
*)*bytecode
)[0] = (struct inet_diag_bc_op
){ INET_DIAG_BC_S_LE
, 8, 12 };
1822 ((struct inet_diag_bc_op
*)*bytecode
)[1] = (struct inet_diag_bc_op
){ 0, 0, x
->port
};
1828 char *a1
= NULL
, *a2
= NULL
, *a
;
1831 l1
= ssfilter_bytecompile(f
->pred
, &a1
);
1832 l2
= ssfilter_bytecompile(f
->post
, &a2
);
1838 if (!(a
= malloc(l1
+l2
))) abort();
1840 memcpy(a
+l1
, a2
, l2
);
1842 ssfilter_patch(a
, l1
, l2
);
1848 char *a1
= NULL
, *a2
= NULL
, *a
;
1851 l1
= ssfilter_bytecompile(f
->pred
, &a1
);
1852 l2
= ssfilter_bytecompile(f
->post
, &a2
);
1858 if (!(a
= malloc(l1
+l2
+4))) abort();
1860 memcpy(a
+l1
+4, a2
, l2
);
1862 *(struct inet_diag_bc_op
*)(a
+l1
) = (struct inet_diag_bc_op
){ INET_DIAG_BC_JMP
, 4, l2
+4 };
1868 char *a1
= NULL
, *a
;
1871 l1
= ssfilter_bytecompile(f
->pred
, &a1
);
1876 if (!(a
= malloc(l1
+4))) abort();
1879 *(struct inet_diag_bc_op
*)(a
+l1
) = (struct inet_diag_bc_op
){ INET_DIAG_BC_JMP
, 4, 8 };
1885 /* bytecompile for SSF_DEVCOND not supported yet */
1890 struct aafilter
*a
= (void *)f
->pred
;
1892 struct inet_diag_bc_op op
;
1893 struct inet_diag_markcond cond
;
1895 int inslen
= sizeof(struct instr
);
1897 if (!(*bytecode
= malloc(inslen
))) abort();
1898 ((struct instr
*)*bytecode
)[0] = (struct instr
) {
1899 { INET_DIAG_BC_MARK_COND
, inslen
, inslen
+ 4 },
1900 { a
->mark
, a
->mask
},
1910 static int remember_he(struct aafilter
*a
, struct hostent
*he
)
1912 char **ptr
= he
->h_addr_list
;
1916 if (he
->h_addrtype
== AF_INET
)
1918 else if (he
->h_addrtype
== AF_INET6
)
1924 struct aafilter
*b
= a
;
1926 if (a
->addr
.bitlen
) {
1927 if ((b
= malloc(sizeof(*b
))) == NULL
)
1932 memcpy(b
->addr
.data
, *ptr
, len
);
1933 b
->addr
.bytelen
= len
;
1934 b
->addr
.bitlen
= len
*8;
1935 b
->addr
.family
= he
->h_addrtype
;
1942 static int get_dns_host(struct aafilter
*a
, const char *addr
, int fam
)
1944 static int notfirst
;
1953 he
= gethostbyname2(addr
, fam
== AF_UNSPEC
? AF_INET
: fam
);
1955 cnt
= remember_he(a
, he
);
1956 if (fam
== AF_UNSPEC
) {
1957 he
= gethostbyname2(addr
, AF_INET6
);
1959 cnt
+= remember_he(a
, he
);
1964 static int xll_initted
;
1966 static void xll_init(void)
1968 struct rtnl_handle rth
;
1970 if (rtnl_open(&rth
, 0) < 0)
1978 static const char *xll_index_to_name(int index
)
1982 return ll_index_to_name(index
);
1985 static int xll_name_to_index(const char *dev
)
1989 return ll_name_to_index(dev
);
1992 void *parse_devcond(char *name
)
1994 struct aafilter a
= { .iface
= 0 };
1995 struct aafilter
*res
;
1997 a
.iface
= xll_name_to_index(name
);
2002 n
= strtoul(name
, &end
, 0);
2003 if (!end
|| end
== name
|| *end
|| n
> UINT_MAX
)
2009 res
= malloc(sizeof(*res
));
2015 static void vsock_set_inet_prefix(inet_prefix
*a
, __u32 cid
)
2018 .bytelen
= sizeof(cid
),
2021 memcpy(a
->data
, &cid
, sizeof(cid
));
2024 void *parse_hostcond(char *addr
, bool is_port
)
2027 struct aafilter a
= { .port
= -1 };
2028 struct aafilter
*res
;
2029 int fam
= preferred_family
;
2030 struct filter
*f
= ¤t_filter
;
2032 if (fam
== AF_UNIX
|| strncmp(addr
, "unix:", 5) == 0) {
2035 a
.addr
.family
= AF_UNIX
;
2036 if (strncmp(addr
, "unix:", 5) == 0)
2039 a
.addr
.bitlen
= 8*strlen(p
);
2040 memcpy(a
.addr
.data
, &p
, sizeof(p
));
2045 if (fam
== AF_PACKET
|| strncmp(addr
, "link:", 5) == 0) {
2046 a
.addr
.family
= AF_PACKET
;
2048 if (strncmp(addr
, "link:", 5) == 0)
2050 port
= strchr(addr
, ':');
2053 if (port
[1] && strcmp(port
+1, "*")) {
2054 if (get_integer(&a
.port
, port
+1, 0)) {
2055 if ((a
.port
= xll_name_to_index(port
+1)) <= 0)
2060 if (addr
[0] && strcmp(addr
, "*")) {
2064 if (ll_proto_a2n(&tmp
, addr
))
2066 a
.addr
.data
[0] = ntohs(tmp
);
2072 if (fam
== AF_NETLINK
|| strncmp(addr
, "netlink:", 8) == 0) {
2073 a
.addr
.family
= AF_NETLINK
;
2075 if (strncmp(addr
, "netlink:", 8) == 0)
2077 port
= strchr(addr
, ':');
2080 if (port
[1] && strcmp(port
+1, "*")) {
2081 if (get_integer(&a
.port
, port
+1, 0)) {
2082 if (strcmp(port
+1, "kernel") == 0)
2089 if (addr
[0] && strcmp(addr
, "*")) {
2091 if (nl_proto_a2n(&a
.addr
.data
[0], addr
) == -1)
2098 if (fam
== AF_VSOCK
|| strncmp(addr
, "vsock:", 6) == 0) {
2099 __u32 cid
= ~(__u32
)0;
2101 a
.addr
.family
= AF_VSOCK
;
2102 if (strncmp(addr
, "vsock:", 6) == 0)
2108 port
= strchr(addr
, ':');
2115 if (port
&& strcmp(port
, "*") &&
2116 get_u32((__u32
*)&a
.port
, port
, 0))
2119 if (addr
[0] && strcmp(addr
, "*")) {
2121 if (get_u32(&cid
, addr
, 0))
2124 vsock_set_inet_prefix(&a
.addr
, cid
);
2129 if (fam
== AF_INET
|| !strncmp(addr
, "inet:", 5)) {
2131 if (!strncmp(addr
, "inet:", 5))
2133 } else if (fam
== AF_INET6
|| !strncmp(addr
, "inet6:", 6)) {
2135 if (!strncmp(addr
, "inet6:", 6))
2139 /* URL-like literal [] */
2140 if (addr
[0] == '[') {
2142 if ((port
= strchr(addr
, ']')) == NULL
)
2145 } else if (addr
[0] == '*') {
2148 port
= strrchr(strchr(addr
, '/') ? : addr
, ':');
2154 if (port
&& *port
) {
2158 if (*port
&& *port
!= '*') {
2159 if (get_integer(&a
.port
, port
, 0)) {
2160 struct servent
*se1
= NULL
;
2161 struct servent
*se2
= NULL
;
2163 if (current_filter
.dbs
&(1<<UDP_DB
))
2164 se1
= getservbyname(port
, UDP_PROTO
);
2165 if (current_filter
.dbs
&(1<<TCP_DB
))
2166 se2
= getservbyname(port
, TCP_PROTO
);
2167 if (se1
&& se2
&& se1
->s_port
!= se2
->s_port
) {
2168 fprintf(stderr
, "Error: ambiguous port \"%s\".\n", port
);
2174 a
.port
= ntohs(se1
->s_port
);
2178 for (s
= rlist
; s
; s
= s
->next
) {
2179 if ((s
->proto
== UDP_PROTO
&&
2180 (current_filter
.dbs
&(1<<UDP_DB
))) ||
2181 (s
->proto
== TCP_PROTO
&&
2182 (current_filter
.dbs
&(1<<TCP_DB
)))) {
2183 if (s
->name
&& strcmp(s
->name
, port
) == 0) {
2184 if (a
.port
> 0 && a
.port
!= s
->port
) {
2185 fprintf(stderr
, "Error: ambiguous port \"%s\".\n", port
);
2193 fprintf(stderr
, "Error: \"%s\" does not look like a port.\n", port
);
2200 if (!is_port
&& *addr
&& *addr
!= '*') {
2201 if (get_prefix_1(&a
.addr
, addr
, fam
)) {
2202 if (get_dns_host(&a
, addr
, fam
)) {
2203 fprintf(stderr
, "Error: an inet prefix is expected rather than \"%s\".\n", addr
);
2210 if (fam
!= AF_UNSPEC
) {
2211 int states
= f
->states
;
2213 filter_af_set(f
, fam
);
2214 filter_states_set(f
, states
);
2217 res
= malloc(sizeof(*res
));
2219 memcpy(res
, &a
, sizeof(a
));
2223 void *parse_markmask(const char *markmask
)
2225 struct aafilter a
, *res
;
2227 if (strchr(markmask
, '/')) {
2228 if (sscanf(markmask
, "%i/%i", &a
.mark
, &a
.mask
) != 2)
2231 a
.mask
= 0xffffffff;
2232 if (sscanf(markmask
, "%i", &a
.mark
) != 1)
2236 res
= malloc(sizeof(*res
));
2238 memcpy(res
, &a
, sizeof(a
));
2242 static void proc_ctx_print(struct sockstat
*s
)
2246 if (show_proc_ctx
|| show_sock_ctx
) {
2247 if (find_entry(s
->ino
, &buf
,
2248 (show_proc_ctx
& show_sock_ctx
) ?
2249 PROC_SOCK_CTX
: PROC_CTX
) > 0) {
2250 out(" users:(%s)", buf
);
2253 } else if (show_users
) {
2254 if (find_entry(s
->ino
, &buf
, USERS
) > 0) {
2255 out(" users:(%s)", buf
);
2261 static void inet_stats_print(struct sockstat
*s
, bool v6only
)
2263 sock_state_print(s
);
2265 inet_addr_print(&s
->local
, s
->lport
, s
->iface
, v6only
);
2266 inet_addr_print(&s
->remote
, s
->rport
, 0, v6only
);
2271 static int proc_parse_inet_addr(char *loc
, char *rem
, int family
, struct
2274 s
->local
.family
= s
->remote
.family
= family
;
2275 if (family
== AF_INET
) {
2276 sscanf(loc
, "%x:%x", s
->local
.data
, (unsigned *)&s
->lport
);
2277 sscanf(rem
, "%x:%x", s
->remote
.data
, (unsigned *)&s
->rport
);
2278 s
->local
.bytelen
= s
->remote
.bytelen
= 4;
2281 sscanf(loc
, "%08x%08x%08x%08x:%x",
2287 sscanf(rem
, "%08x%08x%08x%08x:%x",
2293 s
->local
.bytelen
= s
->remote
.bytelen
= 16;
2299 static int proc_inet_split_line(char *line
, char **loc
, char **rem
, char **data
)
2303 if ((p
= strchr(line
, ':')) == NULL
)
2307 if ((p
= strchr(*loc
, ':')) == NULL
)
2312 if ((p
= strchr(*rem
, ':')) == NULL
)
2320 static char *sprint_bw(char *buf
, double bw
)
2323 sprintf(buf
, "%.1fM", bw
/ 1000000.);
2324 else if (bw
> 1000.)
2325 sprintf(buf
, "%.1fK", bw
/ 1000.);
2327 sprintf(buf
, "%g", bw
);
2332 static void sctp_stats_print(struct sctp_info
*s
)
2335 out(" tag:%x", s
->sctpi_tag
);
2337 out(" state:%s", sctp_sstate_name
[s
->sctpi_state
]);
2339 out(" rwnd:%d", s
->sctpi_rwnd
);
2340 if (s
->sctpi_unackdata
)
2341 out(" unackdata:%d", s
->sctpi_unackdata
);
2342 if (s
->sctpi_penddata
)
2343 out(" penddata:%d", s
->sctpi_penddata
);
2344 if (s
->sctpi_instrms
)
2345 out(" instrms:%d", s
->sctpi_instrms
);
2346 if (s
->sctpi_outstrms
)
2347 out(" outstrms:%d", s
->sctpi_outstrms
);
2348 if (s
->sctpi_inqueue
)
2349 out(" inqueue:%d", s
->sctpi_inqueue
);
2350 if (s
->sctpi_outqueue
)
2351 out(" outqueue:%d", s
->sctpi_outqueue
);
2352 if (s
->sctpi_overall_error
)
2353 out(" overerr:%d", s
->sctpi_overall_error
);
2354 if (s
->sctpi_max_burst
)
2355 out(" maxburst:%d", s
->sctpi_max_burst
);
2356 if (s
->sctpi_maxseg
)
2357 out(" maxseg:%d", s
->sctpi_maxseg
);
2358 if (s
->sctpi_peer_rwnd
)
2359 out(" prwnd:%d", s
->sctpi_peer_rwnd
);
2360 if (s
->sctpi_peer_tag
)
2361 out(" ptag:%x", s
->sctpi_peer_tag
);
2362 if (s
->sctpi_peer_capable
)
2363 out(" pcapable:%d", s
->sctpi_peer_capable
);
2364 if (s
->sctpi_peer_sack
)
2365 out(" psack:%d", s
->sctpi_peer_sack
);
2366 if (s
->sctpi_s_autoclose
)
2367 out(" autoclose:%d", s
->sctpi_s_autoclose
);
2368 if (s
->sctpi_s_adaptation_ind
)
2369 out(" adapind:%d", s
->sctpi_s_adaptation_ind
);
2370 if (s
->sctpi_s_pd_point
)
2371 out(" pdpoint:%d", s
->sctpi_s_pd_point
);
2372 if (s
->sctpi_s_nodelay
)
2373 out(" nodealy:%d", s
->sctpi_s_nodelay
);
2374 if (s
->sctpi_s_disable_fragments
)
2375 out(" nofrag:%d", s
->sctpi_s_disable_fragments
);
2376 if (s
->sctpi_s_v4mapped
)
2377 out(" v4mapped:%d", s
->sctpi_s_v4mapped
);
2378 if (s
->sctpi_s_frag_interleave
)
2379 out(" fraginl:%d", s
->sctpi_s_frag_interleave
);
2382 static void tcp_stats_print(struct tcpstat
*s
)
2388 if (s
->has_sack_opt
)
2392 if (s
->has_ecnseen_opt
)
2394 if (s
->has_fastopen_opt
)
2397 out(" %s", s
->cong_alg
);
2398 if (s
->has_wscale_opt
)
2399 out(" wscale:%d,%d", s
->snd_wscale
, s
->rcv_wscale
);
2401 out(" rto:%g", s
->rto
);
2403 out(" backoff:%u", s
->backoff
);
2405 out(" rtt:%g/%g", s
->rtt
, s
->rttvar
);
2407 out(" ato:%g", s
->ato
);
2410 out(" qack:%d", s
->qack
);
2415 out(" mss:%d", s
->mss
);
2417 out(" pmtu:%u", s
->pmtu
);
2419 out(" rcvmss:%d", s
->rcv_mss
);
2421 out(" advmss:%d", s
->advmss
);
2423 out(" cwnd:%u", s
->cwnd
);
2425 out(" ssthresh:%d", s
->ssthresh
);
2428 out(" bytes_acked:%llu", s
->bytes_acked
);
2429 if (s
->bytes_received
)
2430 out(" bytes_received:%llu", s
->bytes_received
);
2432 out(" segs_out:%u", s
->segs_out
);
2434 out(" segs_in:%u", s
->segs_in
);
2435 if (s
->data_segs_out
)
2436 out(" data_segs_out:%u", s
->data_segs_out
);
2437 if (s
->data_segs_in
)
2438 out(" data_segs_in:%u", s
->data_segs_in
);
2440 if (s
->dctcp
&& s
->dctcp
->enabled
) {
2441 struct dctcpstat
*dctcp
= s
->dctcp
;
2443 out(" dctcp:(ce_state:%u,alpha:%u,ab_ecn:%u,ab_tot:%u)",
2444 dctcp
->ce_state
, dctcp
->alpha
, dctcp
->ab_ecn
,
2446 } else if (s
->dctcp
) {
2447 out(" dctcp:fallback_mode");
2453 bw
= s
->bbr_info
->bbr_bw_hi
;
2455 bw
|= s
->bbr_info
->bbr_bw_lo
;
2457 out(" bbr:(bw:%sbps,mrtt:%g",
2458 sprint_bw(b1
, bw
* 8.0),
2459 (double)s
->bbr_info
->bbr_min_rtt
/ 1000.0);
2460 if (s
->bbr_info
->bbr_pacing_gain
)
2461 out(",pacing_gain:%g",
2462 (double)s
->bbr_info
->bbr_pacing_gain
/ 256.0);
2463 if (s
->bbr_info
->bbr_cwnd_gain
)
2464 out(",cwnd_gain:%g",
2465 (double)s
->bbr_info
->bbr_cwnd_gain
/ 256.0);
2470 out(" send %sbps", sprint_bw(b1
, s
->send_bps
));
2472 out(" lastsnd:%u", s
->lastsnd
);
2474 out(" lastrcv:%u", s
->lastrcv
);
2476 out(" lastack:%u", s
->lastack
);
2478 if (s
->pacing_rate
) {
2479 out(" pacing_rate %sbps", sprint_bw(b1
, s
->pacing_rate
));
2480 if (s
->pacing_rate_max
)
2481 out("/%sbps", sprint_bw(b1
, s
->pacing_rate_max
));
2484 if (s
->delivery_rate
)
2485 out(" delivery_rate %sbps", sprint_bw(b1
, s
->delivery_rate
));
2487 out(" app_limited");
2490 out(" busy:%llums", s
->busy_time
/ 1000);
2491 if (s
->rwnd_limited
)
2492 out(" rwnd_limited:%llums(%.1f%%)",
2493 s
->rwnd_limited
/ 1000,
2494 100.0 * s
->rwnd_limited
/ s
->busy_time
);
2495 if (s
->sndbuf_limited
)
2496 out(" sndbuf_limited:%llums(%.1f%%)",
2497 s
->sndbuf_limited
/ 1000,
2498 100.0 * s
->sndbuf_limited
/ s
->busy_time
);
2502 out(" unacked:%u", s
->unacked
);
2503 if (s
->retrans
|| s
->retrans_total
)
2504 out(" retrans:%u/%u", s
->retrans
, s
->retrans_total
);
2506 out(" lost:%u", s
->lost
);
2507 if (s
->sacked
&& s
->ss
.state
!= SS_LISTEN
)
2508 out(" sacked:%u", s
->sacked
);
2510 out(" fackets:%u", s
->fackets
);
2511 if (s
->reordering
!= 3)
2512 out(" reordering:%d", s
->reordering
);
2514 out(" rcv_rtt:%g", s
->rcv_rtt
);
2516 out(" rcv_space:%d", s
->rcv_space
);
2517 if (s
->rcv_ssthresh
)
2518 out(" rcv_ssthresh:%u", s
->rcv_ssthresh
);
2520 out(" notsent:%u", s
->not_sent
);
2522 out(" minrtt:%g", s
->min_rtt
);
2525 static void tcp_timer_print(struct tcpstat
*s
)
2527 static const char * const tmr_name
[] = {
2539 out(" timer:(%s,%s,%d)",
2541 print_ms_timer(s
->timeout
),
2546 static void sctp_timer_print(struct tcpstat
*s
)
2549 out(" timer:(T3_RTX,%s,%d)",
2550 print_ms_timer(s
->timeout
), s
->retrans
);
2553 static int tcp_show_line(char *line
, const struct filter
*f
, int family
)
2555 int rto
= 0, ato
= 0;
2556 struct tcpstat s
= {};
2557 char *loc
, *rem
, *data
;
2560 int hz
= get_user_hz();
2562 if (proc_inet_split_line(line
, &loc
, &rem
, &data
))
2565 int state
= (data
[1] >= 'A') ? (data
[1] - 'A' + 10) : (data
[1] - '0');
2567 if (!(f
->states
& (1 << state
)))
2570 proc_parse_inet_addr(loc
, rem
, family
, &s
.ss
);
2572 if (f
->f
&& run_ssfilter(f
->f
, &s
.ss
) == 0)
2576 n
= sscanf(data
, "%x %x:%x %x:%x %x %d %d %u %d %llx %d %d %d %u %d %[^\n]\n",
2577 &s
.ss
.state
, &s
.ss
.wq
, &s
.ss
.rq
,
2578 &s
.timer
, &s
.timeout
, &s
.retrans
, &s
.ss
.uid
, &s
.probes
,
2579 &s
.ss
.ino
, &s
.ss
.refcnt
, &s
.ss
.sk
, &rto
, &ato
, &s
.qack
, &s
.cwnd
,
2592 s
.retrans
= s
.timer
!= 1 ? s
.probes
: s
.retrans
;
2593 s
.timeout
= (s
.timeout
* 1000 + hz
- 1) / hz
;
2594 s
.ato
= (double)ato
/ hz
;
2596 s
.rto
= (double)rto
;
2597 s
.ssthresh
= s
.ssthresh
== -1 ? 0 : s
.ssthresh
;
2598 s
.rto
= s
.rto
!= 3 * hz
? s
.rto
/ hz
: 0;
2599 s
.ss
.type
= IPPROTO_TCP
;
2601 inet_stats_print(&s
.ss
, false);
2604 tcp_timer_print(&s
);
2607 sock_details_print(&s
.ss
);
2609 out(" opt:\"%s\"", opt
);
2613 tcp_stats_print(&s
);
2618 static int generic_record_read(FILE *fp
,
2619 int (*worker
)(char*, const struct filter
*, int),
2620 const struct filter
*f
, int fam
)
2625 if (fgets(line
, sizeof(line
), fp
) == NULL
)
2628 while (fgets(line
, sizeof(line
), fp
) != NULL
) {
2629 int n
= strlen(line
);
2631 if (n
== 0 || line
[n
-1] != '\n') {
2637 if (worker(line
, f
, fam
) < 0)
2642 return ferror(fp
) ? -1 : 0;
2645 static void print_skmeminfo(struct rtattr
*tb
[], int attrtype
)
2647 const __u32
*skmeminfo
;
2649 if (!tb
[attrtype
]) {
2650 if (attrtype
== INET_DIAG_SKMEMINFO
) {
2651 if (!tb
[INET_DIAG_MEMINFO
])
2654 const struct inet_diag_meminfo
*minfo
=
2655 RTA_DATA(tb
[INET_DIAG_MEMINFO
]);
2657 out(" mem:(r%u,w%u,f%u,t%u)",
2666 skmeminfo
= RTA_DATA(tb
[attrtype
]);
2668 out(" skmem:(r%u,rb%u,t%u,tb%u,f%u,w%u,o%u",
2669 skmeminfo
[SK_MEMINFO_RMEM_ALLOC
],
2670 skmeminfo
[SK_MEMINFO_RCVBUF
],
2671 skmeminfo
[SK_MEMINFO_WMEM_ALLOC
],
2672 skmeminfo
[SK_MEMINFO_SNDBUF
],
2673 skmeminfo
[SK_MEMINFO_FWD_ALLOC
],
2674 skmeminfo
[SK_MEMINFO_WMEM_QUEUED
],
2675 skmeminfo
[SK_MEMINFO_OPTMEM
]);
2677 if (RTA_PAYLOAD(tb
[attrtype
]) >=
2678 (SK_MEMINFO_BACKLOG
+ 1) * sizeof(__u32
))
2679 out(",bl%u", skmeminfo
[SK_MEMINFO_BACKLOG
]);
2681 if (RTA_PAYLOAD(tb
[attrtype
]) >=
2682 (SK_MEMINFO_DROPS
+ 1) * sizeof(__u32
))
2683 out(",d%u", skmeminfo
[SK_MEMINFO_DROPS
]);
2688 static void print_md5sig(struct tcp_diag_md5sig
*sig
)
2691 format_host(sig
->tcpm_family
,
2692 sig
->tcpm_family
== AF_INET6
? 16 : 4,
2694 sig
->tcpm_prefixlen
);
2695 print_escape_buf(sig
->tcpm_key
, sig
->tcpm_keylen
, " ,");
2698 #define TCPI_HAS_OPT(info, opt) !!(info->tcpi_options & (opt))
2700 static void tcp_show_info(const struct nlmsghdr
*nlh
, struct inet_diag_msg
*r
,
2701 struct rtattr
*tb
[])
2704 struct tcpstat s
= {};
2706 s
.ss
.state
= r
->idiag_state
;
2708 print_skmeminfo(tb
, INET_DIAG_SKMEMINFO
);
2710 if (tb
[INET_DIAG_INFO
]) {
2711 struct tcp_info
*info
;
2712 int len
= RTA_PAYLOAD(tb
[INET_DIAG_INFO
]);
2714 /* workaround for older kernels with less fields */
2715 if (len
< sizeof(*info
)) {
2716 info
= alloca(sizeof(*info
));
2717 memcpy(info
, RTA_DATA(tb
[INET_DIAG_INFO
]), len
);
2718 memset((char *)info
+ len
, 0, sizeof(*info
) - len
);
2720 info
= RTA_DATA(tb
[INET_DIAG_INFO
]);
2723 s
.has_ts_opt
= TCPI_HAS_OPT(info
, TCPI_OPT_TIMESTAMPS
);
2724 s
.has_sack_opt
= TCPI_HAS_OPT(info
, TCPI_OPT_SACK
);
2725 s
.has_ecn_opt
= TCPI_HAS_OPT(info
, TCPI_OPT_ECN
);
2726 s
.has_ecnseen_opt
= TCPI_HAS_OPT(info
, TCPI_OPT_ECN_SEEN
);
2727 s
.has_fastopen_opt
= TCPI_HAS_OPT(info
, TCPI_OPT_SYN_DATA
);
2730 if (tb
[INET_DIAG_CONG
])
2732 rta_getattr_str(tb
[INET_DIAG_CONG
]),
2733 sizeof(s
.cong_alg
) - 1);
2735 if (TCPI_HAS_OPT(info
, TCPI_OPT_WSCALE
)) {
2736 s
.has_wscale_opt
= true;
2737 s
.snd_wscale
= info
->tcpi_snd_wscale
;
2738 s
.rcv_wscale
= info
->tcpi_rcv_wscale
;
2741 if (info
->tcpi_rto
&& info
->tcpi_rto
!= 3000000)
2742 s
.rto
= (double)info
->tcpi_rto
/ 1000;
2744 s
.backoff
= info
->tcpi_backoff
;
2745 s
.rtt
= (double)info
->tcpi_rtt
/ 1000;
2746 s
.rttvar
= (double)info
->tcpi_rttvar
/ 1000;
2747 s
.ato
= (double)info
->tcpi_ato
/ 1000;
2748 s
.mss
= info
->tcpi_snd_mss
;
2749 s
.rcv_mss
= info
->tcpi_rcv_mss
;
2750 s
.advmss
= info
->tcpi_advmss
;
2751 s
.rcv_space
= info
->tcpi_rcv_space
;
2752 s
.rcv_rtt
= (double)info
->tcpi_rcv_rtt
/ 1000;
2753 s
.lastsnd
= info
->tcpi_last_data_sent
;
2754 s
.lastrcv
= info
->tcpi_last_data_recv
;
2755 s
.lastack
= info
->tcpi_last_ack_recv
;
2756 s
.unacked
= info
->tcpi_unacked
;
2757 s
.retrans
= info
->tcpi_retrans
;
2758 s
.retrans_total
= info
->tcpi_total_retrans
;
2759 s
.lost
= info
->tcpi_lost
;
2760 s
.sacked
= info
->tcpi_sacked
;
2761 s
.fackets
= info
->tcpi_fackets
;
2762 s
.reordering
= info
->tcpi_reordering
;
2763 s
.rcv_ssthresh
= info
->tcpi_rcv_ssthresh
;
2764 s
.cwnd
= info
->tcpi_snd_cwnd
;
2765 s
.pmtu
= info
->tcpi_pmtu
;
2767 if (info
->tcpi_snd_ssthresh
< 0xFFFF)
2768 s
.ssthresh
= info
->tcpi_snd_ssthresh
;
2770 rtt
= (double) info
->tcpi_rtt
;
2771 if (tb
[INET_DIAG_VEGASINFO
]) {
2772 const struct tcpvegas_info
*vinfo
2773 = RTA_DATA(tb
[INET_DIAG_VEGASINFO
]);
2775 if (vinfo
->tcpv_enabled
&&
2776 vinfo
->tcpv_rtt
&& vinfo
->tcpv_rtt
!= 0x7fffffff)
2777 rtt
= vinfo
->tcpv_rtt
;
2780 if (tb
[INET_DIAG_DCTCPINFO
]) {
2781 struct dctcpstat
*dctcp
= malloc(sizeof(struct
2784 const struct tcp_dctcp_info
*dinfo
2785 = RTA_DATA(tb
[INET_DIAG_DCTCPINFO
]);
2787 dctcp
->enabled
= !!dinfo
->dctcp_enabled
;
2788 dctcp
->ce_state
= dinfo
->dctcp_ce_state
;
2789 dctcp
->alpha
= dinfo
->dctcp_alpha
;
2790 dctcp
->ab_ecn
= dinfo
->dctcp_ab_ecn
;
2791 dctcp
->ab_tot
= dinfo
->dctcp_ab_tot
;
2795 if (tb
[INET_DIAG_BBRINFO
]) {
2796 const void *bbr_info
= RTA_DATA(tb
[INET_DIAG_BBRINFO
]);
2797 int len
= min(RTA_PAYLOAD(tb
[INET_DIAG_BBRINFO
]),
2798 sizeof(*s
.bbr_info
));
2800 s
.bbr_info
= calloc(1, sizeof(*s
.bbr_info
));
2801 if (s
.bbr_info
&& bbr_info
)
2802 memcpy(s
.bbr_info
, bbr_info
, len
);
2805 if (rtt
> 0 && info
->tcpi_snd_mss
&& info
->tcpi_snd_cwnd
) {
2806 s
.send_bps
= (double) info
->tcpi_snd_cwnd
*
2807 (double)info
->tcpi_snd_mss
* 8000000. / rtt
;
2810 if (info
->tcpi_pacing_rate
&&
2811 info
->tcpi_pacing_rate
!= ~0ULL) {
2812 s
.pacing_rate
= info
->tcpi_pacing_rate
* 8.;
2814 if (info
->tcpi_max_pacing_rate
&&
2815 info
->tcpi_max_pacing_rate
!= ~0ULL)
2816 s
.pacing_rate_max
= info
->tcpi_max_pacing_rate
* 8.;
2818 s
.bytes_acked
= info
->tcpi_bytes_acked
;
2819 s
.bytes_received
= info
->tcpi_bytes_received
;
2820 s
.segs_out
= info
->tcpi_segs_out
;
2821 s
.segs_in
= info
->tcpi_segs_in
;
2822 s
.data_segs_out
= info
->tcpi_data_segs_out
;
2823 s
.data_segs_in
= info
->tcpi_data_segs_in
;
2824 s
.not_sent
= info
->tcpi_notsent_bytes
;
2825 if (info
->tcpi_min_rtt
&& info
->tcpi_min_rtt
!= ~0U)
2826 s
.min_rtt
= (double) info
->tcpi_min_rtt
/ 1000;
2827 s
.delivery_rate
= info
->tcpi_delivery_rate
* 8.;
2828 s
.app_limited
= info
->tcpi_delivery_rate_app_limited
;
2829 s
.busy_time
= info
->tcpi_busy_time
;
2830 s
.rwnd_limited
= info
->tcpi_rwnd_limited
;
2831 s
.sndbuf_limited
= info
->tcpi_sndbuf_limited
;
2832 tcp_stats_print(&s
);
2836 if (tb
[INET_DIAG_MD5SIG
]) {
2837 struct tcp_diag_md5sig
*sig
= RTA_DATA(tb
[INET_DIAG_MD5SIG
]);
2838 int len
= RTA_PAYLOAD(tb
[INET_DIAG_MD5SIG
]);
2841 print_md5sig(sig
++);
2842 for (len
-= sizeof(*sig
); len
> 0; len
-= sizeof(*sig
)) {
2844 print_md5sig(sig
++);
2849 static const char *format_host_sa(struct sockaddr_storage
*sa
)
2852 struct sockaddr_in sin
;
2853 struct sockaddr_in6 sin6
;
2854 } *saddr
= (void *)sa
;
2856 switch (sa
->ss_family
) {
2858 return format_host(AF_INET
, 4, &saddr
->sin
.sin_addr
);
2860 return format_host(AF_INET6
, 16, &saddr
->sin6
.sin6_addr
);
2866 static void sctp_show_info(const struct nlmsghdr
*nlh
, struct inet_diag_msg
*r
,
2867 struct rtattr
*tb
[])
2869 struct sockaddr_storage
*sa
;
2872 print_skmeminfo(tb
, INET_DIAG_SKMEMINFO
);
2874 if (tb
[INET_DIAG_LOCALS
]) {
2875 len
= RTA_PAYLOAD(tb
[INET_DIAG_LOCALS
]);
2876 sa
= RTA_DATA(tb
[INET_DIAG_LOCALS
]);
2878 out("locals:%s", format_host_sa(sa
));
2879 for (sa
++, len
-= sizeof(*sa
); len
> 0; sa
++, len
-= sizeof(*sa
))
2880 out(",%s", format_host_sa(sa
));
2883 if (tb
[INET_DIAG_PEERS
]) {
2884 len
= RTA_PAYLOAD(tb
[INET_DIAG_PEERS
]);
2885 sa
= RTA_DATA(tb
[INET_DIAG_PEERS
]);
2887 out(" peers:%s", format_host_sa(sa
));
2888 for (sa
++, len
-= sizeof(*sa
); len
> 0; sa
++, len
-= sizeof(*sa
))
2889 out(",%s", format_host_sa(sa
));
2891 if (tb
[INET_DIAG_INFO
]) {
2892 struct sctp_info
*info
;
2893 len
= RTA_PAYLOAD(tb
[INET_DIAG_INFO
]);
2895 /* workaround for older kernels with less fields */
2896 if (len
< sizeof(*info
)) {
2897 info
= alloca(sizeof(*info
));
2898 memcpy(info
, RTA_DATA(tb
[INET_DIAG_INFO
]), len
);
2899 memset((char *)info
+ len
, 0, sizeof(*info
) - len
);
2901 info
= RTA_DATA(tb
[INET_DIAG_INFO
]);
2903 sctp_stats_print(info
);
2907 static void parse_diag_msg(struct nlmsghdr
*nlh
, struct sockstat
*s
)
2909 struct rtattr
*tb
[INET_DIAG_MAX
+1];
2910 struct inet_diag_msg
*r
= NLMSG_DATA(nlh
);
2912 parse_rtattr(tb
, INET_DIAG_MAX
, (struct rtattr
*)(r
+1),
2913 nlh
->nlmsg_len
- NLMSG_LENGTH(sizeof(*r
)));
2915 s
->state
= r
->idiag_state
;
2916 s
->local
.family
= s
->remote
.family
= r
->idiag_family
;
2917 s
->lport
= ntohs(r
->id
.idiag_sport
);
2918 s
->rport
= ntohs(r
->id
.idiag_dport
);
2919 s
->wq
= r
->idiag_wqueue
;
2920 s
->rq
= r
->idiag_rqueue
;
2921 s
->ino
= r
->idiag_inode
;
2922 s
->uid
= r
->idiag_uid
;
2923 s
->iface
= r
->id
.idiag_if
;
2924 s
->sk
= cookie_sk_get(&r
->id
.idiag_cookie
[0]);
2927 if (tb
[INET_DIAG_MARK
])
2928 s
->mark
= rta_getattr_u32(tb
[INET_DIAG_MARK
]);
2929 if (tb
[INET_DIAG_PROTOCOL
])
2930 s
->raw_prot
= rta_getattr_u8(tb
[INET_DIAG_PROTOCOL
]);
2934 if (s
->local
.family
== AF_INET
)
2935 s
->local
.bytelen
= s
->remote
.bytelen
= 4;
2937 s
->local
.bytelen
= s
->remote
.bytelen
= 16;
2939 memcpy(s
->local
.data
, r
->id
.idiag_src
, s
->local
.bytelen
);
2940 memcpy(s
->remote
.data
, r
->id
.idiag_dst
, s
->local
.bytelen
);
2943 static int inet_show_sock(struct nlmsghdr
*nlh
,
2946 struct rtattr
*tb
[INET_DIAG_MAX
+1];
2947 struct inet_diag_msg
*r
= NLMSG_DATA(nlh
);
2948 unsigned char v6only
= 0;
2950 parse_rtattr(tb
, INET_DIAG_MAX
, (struct rtattr
*)(r
+1),
2951 nlh
->nlmsg_len
- NLMSG_LENGTH(sizeof(*r
)));
2953 if (tb
[INET_DIAG_PROTOCOL
])
2954 s
->type
= rta_getattr_u8(tb
[INET_DIAG_PROTOCOL
]);
2956 if (s
->local
.family
== AF_INET6
&& tb
[INET_DIAG_SKV6ONLY
])
2957 v6only
= rta_getattr_u8(tb
[INET_DIAG_SKV6ONLY
]);
2959 inet_stats_print(s
, v6only
);
2962 struct tcpstat t
= {};
2964 t
.timer
= r
->idiag_timer
;
2965 t
.timeout
= r
->idiag_expires
;
2966 t
.retrans
= r
->idiag_retrans
;
2967 if (s
->type
== IPPROTO_SCTP
)
2968 sctp_timer_print(&t
);
2970 tcp_timer_print(&t
);
2974 sock_details_print(s
);
2975 if (s
->local
.family
== AF_INET6
&& tb
[INET_DIAG_SKV6ONLY
])
2976 out(" v6only:%u", v6only
);
2978 if (tb
[INET_DIAG_SHUTDOWN
]) {
2981 mask
= rta_getattr_u8(tb
[INET_DIAG_SHUTDOWN
]);
2983 mask
& 1 ? '-' : '<', mask
& 2 ? '-' : '>');
2987 if (show_mem
|| (show_tcpinfo
&& s
->type
!= IPPROTO_UDP
)) {
2989 if (s
->type
== IPPROTO_SCTP
)
2990 sctp_show_info(nlh
, r
, tb
);
2992 tcp_show_info(nlh
, r
, tb
);
2999 static int tcpdiag_send(int fd
, int protocol
, struct filter
*f
)
3001 struct sockaddr_nl nladdr
= { .nl_family
= AF_NETLINK
};
3003 struct nlmsghdr nlh
;
3004 struct inet_diag_req r
;
3006 .nlh
.nlmsg_len
= sizeof(req
),
3007 .nlh
.nlmsg_flags
= NLM_F_ROOT
| NLM_F_MATCH
| NLM_F_REQUEST
,
3008 .nlh
.nlmsg_seq
= MAGIC_SEQ
,
3009 .r
.idiag_family
= AF_INET
,
3010 .r
.idiag_states
= f
->states
,
3016 struct iovec iov
[3];
3019 if (protocol
== IPPROTO_UDP
)
3022 if (protocol
== IPPROTO_TCP
)
3023 req
.nlh
.nlmsg_type
= TCPDIAG_GETSOCK
;
3025 req
.nlh
.nlmsg_type
= DCCPDIAG_GETSOCK
;
3027 req
.r
.idiag_ext
|= (1<<(INET_DIAG_MEMINFO
-1));
3028 req
.r
.idiag_ext
|= (1<<(INET_DIAG_SKMEMINFO
-1));
3032 req
.r
.idiag_ext
|= (1<<(INET_DIAG_INFO
-1));
3033 req
.r
.idiag_ext
|= (1<<(INET_DIAG_VEGASINFO
-1));
3034 req
.r
.idiag_ext
|= (1<<(INET_DIAG_CONG
-1));
3037 iov
[0] = (struct iovec
){
3039 .iov_len
= sizeof(req
)
3042 bclen
= ssfilter_bytecompile(f
->f
, &bc
);
3044 rta
.rta_type
= INET_DIAG_REQ_BYTECODE
;
3045 rta
.rta_len
= RTA_LENGTH(bclen
);
3046 iov
[1] = (struct iovec
){ &rta
, sizeof(rta
) };
3047 iov
[2] = (struct iovec
){ bc
, bclen
};
3048 req
.nlh
.nlmsg_len
+= RTA_LENGTH(bclen
);
3053 msg
= (struct msghdr
) {
3054 .msg_name
= (void *)&nladdr
,
3055 .msg_namelen
= sizeof(nladdr
),
3057 .msg_iovlen
= iovlen
,
3060 if (sendmsg(fd
, &msg
, 0) < 0) {
3068 static int sockdiag_send(int family
, int fd
, int protocol
, struct filter
*f
)
3070 struct sockaddr_nl nladdr
= { .nl_family
= AF_NETLINK
};
3071 DIAG_REQUEST(req
, struct inet_diag_req_v2 r
);
3076 struct iovec iov
[3];
3079 if (family
== PF_UNSPEC
)
3080 return tcpdiag_send(fd
, protocol
, f
);
3082 memset(&req
.r
, 0, sizeof(req
.r
));
3083 req
.r
.sdiag_family
= family
;
3084 req
.r
.sdiag_protocol
= protocol
;
3085 req
.r
.idiag_states
= f
->states
;
3087 req
.r
.idiag_ext
|= (1<<(INET_DIAG_MEMINFO
-1));
3088 req
.r
.idiag_ext
|= (1<<(INET_DIAG_SKMEMINFO
-1));
3092 req
.r
.idiag_ext
|= (1<<(INET_DIAG_INFO
-1));
3093 req
.r
.idiag_ext
|= (1<<(INET_DIAG_VEGASINFO
-1));
3094 req
.r
.idiag_ext
|= (1<<(INET_DIAG_CONG
-1));
3097 iov
[0] = (struct iovec
){
3099 .iov_len
= sizeof(req
)
3102 bclen
= ssfilter_bytecompile(f
->f
, &bc
);
3104 rta
.rta_type
= INET_DIAG_REQ_BYTECODE
;
3105 rta
.rta_len
= RTA_LENGTH(bclen
);
3106 iov
[1] = (struct iovec
){ &rta
, sizeof(rta
) };
3107 iov
[2] = (struct iovec
){ bc
, bclen
};
3108 req
.nlh
.nlmsg_len
+= RTA_LENGTH(bclen
);
3113 msg
= (struct msghdr
) {
3114 .msg_name
= (void *)&nladdr
,
3115 .msg_namelen
= sizeof(nladdr
),
3117 .msg_iovlen
= iovlen
,
3120 if (sendmsg(fd
, &msg
, 0) < 0) {
3128 struct inet_diag_arg
{
3131 struct rtnl_handle
*rth
;
3134 static int kill_inet_sock(struct nlmsghdr
*h
, void *arg
, struct sockstat
*s
)
3136 struct inet_diag_msg
*d
= NLMSG_DATA(h
);
3137 struct inet_diag_arg
*diag_arg
= arg
;
3138 struct rtnl_handle
*rth
= diag_arg
->rth
;
3140 DIAG_REQUEST(req
, struct inet_diag_req_v2 r
);
3142 req
.nlh
.nlmsg_type
= SOCK_DESTROY
;
3143 req
.nlh
.nlmsg_flags
= NLM_F_REQUEST
| NLM_F_ACK
;
3144 req
.nlh
.nlmsg_seq
= ++rth
->seq
;
3145 req
.r
.sdiag_family
= d
->idiag_family
;
3146 req
.r
.sdiag_protocol
= diag_arg
->protocol
;
3149 if (diag_arg
->protocol
== IPPROTO_RAW
) {
3150 struct inet_diag_req_raw
*raw
= (void *)&req
.r
;
3152 BUILD_BUG_ON(sizeof(req
.r
) != sizeof(*raw
));
3153 raw
->sdiag_raw_protocol
= s
->raw_prot
;
3156 return rtnl_talk(rth
, &req
.nlh
, NULL
);
3159 static int show_one_inet_sock(const struct sockaddr_nl
*addr
,
3160 struct nlmsghdr
*h
, void *arg
)
3163 struct inet_diag_arg
*diag_arg
= arg
;
3164 struct inet_diag_msg
*r
= NLMSG_DATA(h
);
3165 struct sockstat s
= {};
3167 if (!(diag_arg
->f
->families
& FAMILY_MASK(r
->idiag_family
)))
3170 parse_diag_msg(h
, &s
);
3171 s
.type
= diag_arg
->protocol
;
3173 if (diag_arg
->f
->f
&& run_ssfilter(diag_arg
->f
->f
, &s
) == 0)
3176 if (diag_arg
->f
->kill
&& kill_inet_sock(h
, arg
, &s
) != 0) {
3177 if (errno
== EOPNOTSUPP
|| errno
== ENOENT
) {
3178 /* Socket can't be closed, or is already closed. */
3181 perror("SOCK_DESTROY answers");
3186 err
= inet_show_sock(h
, &s
);
3193 static int inet_show_netlink(struct filter
*f
, FILE *dump_fp
, int protocol
)
3196 struct rtnl_handle rth
, rth2
;
3197 int family
= PF_INET
;
3198 struct inet_diag_arg arg
= { .f
= f
, .protocol
= protocol
};
3200 if (rtnl_open_byproto(&rth
, 0, NETLINK_SOCK_DIAG
))
3204 if (rtnl_open_byproto(&rth2
, 0, NETLINK_SOCK_DIAG
)) {
3211 rth
.dump
= MAGIC_SEQ
;
3212 rth
.dump_fp
= dump_fp
;
3213 if (preferred_family
== PF_INET6
)
3217 if ((err
= sockdiag_send(family
, rth
.fd
, protocol
, f
)))
3220 if ((err
= rtnl_dump_filter(&rth
, show_one_inet_sock
, &arg
))) {
3221 if (family
!= PF_UNSPEC
) {
3227 if (family
== PF_INET
&& preferred_family
!= PF_INET
) {
3235 rtnl_close(arg
.rth
);
3239 static int tcp_show_netlink_file(struct filter
*f
)
3245 if ((fp
= fopen(getenv("TCPDIAG_FILE"), "r")) == NULL
) {
3246 perror("fopen($TCPDIAG_FILE)");
3252 struct nlmsghdr
*h
= (struct nlmsghdr
*)buf
;
3253 struct sockstat s
= {};
3255 status
= fread(buf
, 1, sizeof(*h
), fp
);
3257 perror("Reading header from $TCPDIAG_FILE");
3260 if (status
!= sizeof(*h
)) {
3261 perror("Unexpected EOF reading $TCPDIAG_FILE");
3265 status
= fread(h
+1, 1, NLMSG_ALIGN(h
->nlmsg_len
-sizeof(*h
)), fp
);
3268 perror("Reading $TCPDIAG_FILE");
3271 if (status
+ sizeof(*h
) < h
->nlmsg_len
) {
3272 perror("Unexpected EOF reading $TCPDIAG_FILE");
3276 /* The only legal exit point */
3277 if (h
->nlmsg_type
== NLMSG_DONE
) {
3282 if (h
->nlmsg_type
== NLMSG_ERROR
) {
3283 struct nlmsgerr
*err
= (struct nlmsgerr
*)NLMSG_DATA(h
);
3285 if (h
->nlmsg_len
< NLMSG_LENGTH(sizeof(struct nlmsgerr
))) {
3286 fprintf(stderr
, "ERROR truncated\n");
3288 errno
= -err
->error
;
3289 perror("TCPDIAG answered");
3294 parse_diag_msg(h
, &s
);
3295 s
.type
= IPPROTO_TCP
;
3297 if (f
&& f
->f
&& run_ssfilter(f
->f
, &s
) == 0)
3300 err2
= inet_show_sock(h
, &s
);
3311 static int tcp_show(struct filter
*f
)
3315 int bufsize
= 1024*1024;
3317 if (!filter_af_get(f
, AF_INET
) && !filter_af_get(f
, AF_INET6
))
3320 dg_proto
= TCP_PROTO
;
3322 if (getenv("TCPDIAG_FILE"))
3323 return tcp_show_netlink_file(f
);
3325 if (!getenv("PROC_NET_TCP") && !getenv("PROC_ROOT")
3326 && inet_show_netlink(f
, NULL
, IPPROTO_TCP
) == 0)
3329 /* Sigh... We have to parse /proc/net/tcp... */
3330 while (bufsize
>= 64*1024) {
3331 if ((buf
= malloc(bufsize
)) != NULL
)
3340 if (f
->families
& FAMILY_MASK(AF_INET
)) {
3341 if ((fp
= net_tcp_open()) == NULL
)
3344 setbuffer(fp
, buf
, bufsize
);
3345 if (generic_record_read(fp
, tcp_show_line
, f
, AF_INET
))
3350 if ((f
->families
& FAMILY_MASK(AF_INET6
)) &&
3351 (fp
= net_tcp6_open()) != NULL
) {
3352 setbuffer(fp
, buf
, bufsize
);
3353 if (generic_record_read(fp
, tcp_show_line
, f
, AF_INET6
))
3363 int saved_errno
= errno
;
3368 errno
= saved_errno
;
3373 static int dccp_show(struct filter
*f
)
3375 if (!filter_af_get(f
, AF_INET
) && !filter_af_get(f
, AF_INET6
))
3378 if (!getenv("PROC_NET_DCCP") && !getenv("PROC_ROOT")
3379 && inet_show_netlink(f
, NULL
, IPPROTO_DCCP
) == 0)
3385 static int sctp_show(struct filter
*f
)
3387 if (!filter_af_get(f
, AF_INET
) && !filter_af_get(f
, AF_INET6
))
3390 if (!getenv("PROC_NET_SCTP") && !getenv("PROC_ROOT")
3391 && inet_show_netlink(f
, NULL
, IPPROTO_SCTP
) == 0)
3397 static int dgram_show_line(char *line
, const struct filter
*f
, int family
)
3399 struct sockstat s
= {};
3400 char *loc
, *rem
, *data
;
3404 if (proc_inet_split_line(line
, &loc
, &rem
, &data
))
3407 int state
= (data
[1] >= 'A') ? (data
[1] - 'A' + 10) : (data
[1] - '0');
3409 if (!(f
->states
& (1 << state
)))
3412 proc_parse_inet_addr(loc
, rem
, family
, &s
);
3414 if (f
->f
&& run_ssfilter(f
->f
, &s
) == 0)
3418 n
= sscanf(data
, "%x %x:%x %*x:%*x %*x %d %*d %u %d %llx %[^\n]\n",
3419 &s
.state
, &s
.wq
, &s
.rq
,
3421 &s
.refcnt
, &s
.sk
, opt
);
3426 s
.type
= dg_proto
== UDP_PROTO
? IPPROTO_UDP
: 0;
3427 inet_stats_print(&s
, false);
3429 if (show_details
&& opt
[0])
3430 out(" opt:\"%s\"", opt
);
3435 static int udp_show(struct filter
*f
)
3439 if (!filter_af_get(f
, AF_INET
) && !filter_af_get(f
, AF_INET6
))
3442 dg_proto
= UDP_PROTO
;
3444 if (!getenv("PROC_NET_UDP") && !getenv("PROC_ROOT")
3445 && inet_show_netlink(f
, NULL
, IPPROTO_UDP
) == 0)
3448 if (f
->families
&FAMILY_MASK(AF_INET
)) {
3449 if ((fp
= net_udp_open()) == NULL
)
3451 if (generic_record_read(fp
, dgram_show_line
, f
, AF_INET
))
3456 if ((f
->families
&FAMILY_MASK(AF_INET6
)) &&
3457 (fp
= net_udp6_open()) != NULL
) {
3458 if (generic_record_read(fp
, dgram_show_line
, f
, AF_INET6
))
3466 int saved_errno
= errno
;
3470 errno
= saved_errno
;
3475 static int raw_show(struct filter
*f
)
3479 if (!filter_af_get(f
, AF_INET
) && !filter_af_get(f
, AF_INET6
))
3482 dg_proto
= RAW_PROTO
;
3484 if (!getenv("PROC_NET_RAW") && !getenv("PROC_ROOT") &&
3485 inet_show_netlink(f
, NULL
, IPPROTO_RAW
) == 0)
3488 if (f
->families
&FAMILY_MASK(AF_INET
)) {
3489 if ((fp
= net_raw_open()) == NULL
)
3491 if (generic_record_read(fp
, dgram_show_line
, f
, AF_INET
))
3496 if ((f
->families
&FAMILY_MASK(AF_INET6
)) &&
3497 (fp
= net_raw6_open()) != NULL
) {
3498 if (generic_record_read(fp
, dgram_show_line
, f
, AF_INET6
))
3506 int saved_errno
= errno
;
3510 errno
= saved_errno
;
3515 #define MAX_UNIX_REMEMBER (1024*1024/sizeof(struct sockstat))
3517 static void unix_list_drop_first(struct sockstat
**list
)
3519 struct sockstat
*s
= *list
;
3521 (*list
) = (*list
)->next
;
3526 static bool unix_type_skip(struct sockstat
*s
, struct filter
*f
)
3528 if (s
->type
== SOCK_STREAM
&& !(f
->dbs
&(1<<UNIX_ST_DB
)))
3530 if (s
->type
== SOCK_DGRAM
&& !(f
->dbs
&(1<<UNIX_DG_DB
)))
3532 if (s
->type
== SOCK_SEQPACKET
&& !(f
->dbs
&(1<<UNIX_SQ_DB
)))
3537 static void unix_stats_print(struct sockstat
*s
, struct filter
*f
)
3539 char port_name
[30] = {};
3541 sock_state_print(s
);
3543 sock_addr_print(s
->name
?: "*", " ",
3544 int_to_str(s
->lport
, port_name
), NULL
);
3545 sock_addr_print(s
->peer_name
?: "*", " ",
3546 int_to_str(s
->rport
, port_name
), NULL
);
3551 static int unix_show_sock(const struct sockaddr_nl
*addr
, struct nlmsghdr
*nlh
,
3554 struct filter
*f
= (struct filter
*)arg
;
3555 struct unix_diag_msg
*r
= NLMSG_DATA(nlh
);
3556 struct rtattr
*tb
[UNIX_DIAG_MAX
+1];
3558 struct sockstat stat
= { .name
= "*", .peer_name
= "*" };
3560 parse_rtattr(tb
, UNIX_DIAG_MAX
, (struct rtattr
*)(r
+1),
3561 nlh
->nlmsg_len
- NLMSG_LENGTH(sizeof(*r
)));
3563 stat
.type
= r
->udiag_type
;
3564 stat
.state
= r
->udiag_state
;
3565 stat
.ino
= stat
.lport
= r
->udiag_ino
;
3566 stat
.local
.family
= stat
.remote
.family
= AF_UNIX
;
3568 if (unix_type_skip(&stat
, f
))
3571 if (tb
[UNIX_DIAG_RQLEN
]) {
3572 struct unix_diag_rqlen
*rql
= RTA_DATA(tb
[UNIX_DIAG_RQLEN
]);
3574 stat
.rq
= rql
->udiag_rqueue
;
3575 stat
.wq
= rql
->udiag_wqueue
;
3577 if (tb
[UNIX_DIAG_NAME
]) {
3578 int len
= RTA_PAYLOAD(tb
[UNIX_DIAG_NAME
]);
3580 memcpy(name
, RTA_DATA(tb
[UNIX_DIAG_NAME
]), len
);
3582 if (name
[0] == '\0') {
3584 for (i
= 0; i
< len
; i
++)
3585 if (name
[i
] == '\0')
3588 stat
.name
= &name
[0];
3589 memcpy(stat
.local
.data
, &stat
.name
, sizeof(stat
.name
));
3591 if (tb
[UNIX_DIAG_PEER
])
3592 stat
.rport
= rta_getattr_u32(tb
[UNIX_DIAG_PEER
]);
3594 if (f
->f
&& run_ssfilter(f
->f
, &stat
) == 0)
3597 unix_stats_print(&stat
, f
);
3600 print_skmeminfo(tb
, UNIX_DIAG_MEMINFO
);
3602 if (tb
[UNIX_DIAG_SHUTDOWN
]) {
3605 mask
= rta_getattr_u8(tb
[UNIX_DIAG_SHUTDOWN
]);
3607 mask
& 1 ? '-' : '<', mask
& 2 ? '-' : '>');
3609 if (tb
[UNIX_DIAG_VFS
]) {
3610 struct unix_diag_vfs
*uv
= RTA_DATA(tb
[UNIX_DIAG_VFS
]);
3612 out(" ino:%u dev:%u/%u", uv
->udiag_vfs_ino
, major(uv
->udiag_vfs_dev
),
3613 minor(uv
->udiag_vfs_dev
));
3615 if (tb
[UNIX_DIAG_ICONS
]) {
3616 int len
= RTA_PAYLOAD(tb
[UNIX_DIAG_ICONS
]);
3617 __u32
*peers
= RTA_DATA(tb
[UNIX_DIAG_ICONS
]);
3621 for (i
= 0; i
< len
/ sizeof(__u32
); i
++)
3622 out(" %u", peers
[i
]);
3629 static int handle_netlink_request(struct filter
*f
, struct nlmsghdr
*req
,
3630 size_t size
, rtnl_filter_t show_one_sock
)
3633 struct rtnl_handle rth
;
3635 if (rtnl_open_byproto(&rth
, 0, NETLINK_SOCK_DIAG
))
3638 rth
.dump
= MAGIC_SEQ
;
3640 if (rtnl_send(&rth
, req
, size
) < 0)
3643 if (rtnl_dump_filter(&rth
, show_one_sock
, f
))
3652 static int unix_show_netlink(struct filter
*f
)
3654 DIAG_REQUEST(req
, struct unix_diag_req r
);
3656 req
.r
.sdiag_family
= AF_UNIX
;
3657 req
.r
.udiag_states
= f
->states
;
3658 req
.r
.udiag_show
= UDIAG_SHOW_NAME
| UDIAG_SHOW_PEER
| UDIAG_SHOW_RQLEN
;
3660 req
.r
.udiag_show
|= UDIAG_SHOW_MEMINFO
;
3662 req
.r
.udiag_show
|= UDIAG_SHOW_VFS
| UDIAG_SHOW_ICONS
;
3664 return handle_netlink_request(f
, &req
.nlh
, sizeof(req
), unix_show_sock
);
3667 static int unix_show(struct filter
*f
)
3674 struct sockstat
*list
= NULL
;
3675 const int unix_state_map
[] = { SS_CLOSE
, SS_SYN_SENT
,
3676 SS_ESTABLISHED
, SS_CLOSING
};
3678 if (!filter_af_get(f
, AF_UNIX
))
3681 if (!getenv("PROC_NET_UNIX") && !getenv("PROC_ROOT")
3682 && unix_show_netlink(f
) == 0)
3685 if ((fp
= net_unix_open()) == NULL
)
3687 if (!fgets(buf
, sizeof(buf
), fp
)) {
3692 if (memcmp(buf
, "Peer", 4) == 0)
3696 while (fgets(buf
, sizeof(buf
), fp
)) {
3697 struct sockstat
*u
, **insp
;
3700 if (!(u
= calloc(1, sizeof(*u
))))
3703 if (sscanf(buf
, "%x: %x %x %x %x %x %d %s",
3704 &u
->rport
, &u
->rq
, &u
->wq
, &flags
, &u
->type
,
3705 &u
->state
, &u
->ino
, name
) < 8)
3709 u
->local
.family
= u
->remote
.family
= AF_UNIX
;
3711 if (flags
& (1 << 16)) {
3712 u
->state
= SS_LISTEN
;
3713 } else if (u
->state
> 0 &&
3714 u
->state
<= ARRAY_SIZE(unix_state_map
)) {
3715 u
->state
= unix_state_map
[u
->state
-1];
3716 if (u
->type
== SOCK_DGRAM
&& u
->state
== SS_CLOSE
&& u
->rport
)
3717 u
->state
= SS_ESTABLISHED
;
3719 if (unix_type_skip(u
, f
) ||
3720 !(f
->states
& (1 << u
->state
))) {
3732 u
->name
= strdup(name
);
3742 for (p
= list
; p
; p
= p
->next
) {
3743 if (u
->rport
== p
->lport
)
3749 u
->peer_name
= p
->name
? : "*";
3753 struct sockstat st
= {
3754 .local
.family
= AF_UNIX
,
3755 .remote
.family
= AF_UNIX
,
3758 memcpy(st
.local
.data
, &u
->name
, sizeof(u
->name
));
3759 /* when parsing the old format rport is set to 0 and
3760 * therefore peer_name remains NULL
3762 if (u
->peer_name
&& strcmp(u
->peer_name
, "*"))
3763 memcpy(st
.remote
.data
, &u
->peer_name
,
3764 sizeof(u
->peer_name
));
3765 if (run_ssfilter(f
->f
, &st
) == 0) {
3774 if (u
->type
< (*insp
)->type
||
3775 (u
->type
== (*insp
)->type
&&
3776 u
->ino
< (*insp
)->ino
))
3778 insp
= &(*insp
)->next
;
3783 if (++cnt
> MAX_UNIX_REMEMBER
) {
3785 unix_stats_print(list
, f
);
3786 unix_list_drop_first(&list
);
3793 unix_stats_print(list
, f
);
3794 unix_list_drop_first(&list
);
3800 static int packet_stats_print(struct sockstat
*s
, const struct filter
*f
)
3802 const char *addr
, *port
;
3805 s
->local
.family
= s
->remote
.family
= AF_PACKET
;
3808 s
->local
.data
[0] = s
->prot
;
3809 if (run_ssfilter(f
->f
, s
) == 0)
3813 sock_state_print(s
);
3818 addr
= ll_proto_n2a(htons(s
->prot
), ll_name
, sizeof(ll_name
));
3823 port
= xll_index_to_name(s
->iface
);
3825 sock_addr_print(addr
, ":", port
, NULL
);
3826 sock_addr_print("", "*", "", NULL
);
3831 sock_details_print(s
);
3836 static void packet_show_ring(struct packet_diag_ring
*ring
)
3838 out("blk_size:%d", ring
->pdr_block_size
);
3839 out(",blk_nr:%d", ring
->pdr_block_nr
);
3840 out(",frm_size:%d", ring
->pdr_frame_size
);
3841 out(",frm_nr:%d", ring
->pdr_frame_nr
);
3842 out(",tmo:%d", ring
->pdr_retire_tmo
);
3843 out(",features:0x%x", ring
->pdr_features
);
3846 static int packet_show_sock(const struct sockaddr_nl
*addr
,
3847 struct nlmsghdr
*nlh
, void *arg
)
3849 const struct filter
*f
= arg
;
3850 struct packet_diag_msg
*r
= NLMSG_DATA(nlh
);
3851 struct packet_diag_info
*pinfo
= NULL
;
3852 struct packet_diag_ring
*ring_rx
= NULL
, *ring_tx
= NULL
;
3853 struct rtattr
*tb
[PACKET_DIAG_MAX
+1];
3854 struct sockstat stat
= {};
3855 uint32_t fanout
= 0;
3856 bool has_fanout
= false;
3858 parse_rtattr(tb
, PACKET_DIAG_MAX
, (struct rtattr
*)(r
+1),
3859 nlh
->nlmsg_len
- NLMSG_LENGTH(sizeof(*r
)));
3861 /* use /proc/net/packet if all info are not available */
3862 if (!tb
[PACKET_DIAG_MEMINFO
])
3865 stat
.type
= r
->pdiag_type
;
3866 stat
.prot
= r
->pdiag_num
;
3867 stat
.ino
= r
->pdiag_ino
;
3868 stat
.state
= SS_CLOSE
;
3869 stat
.sk
= cookie_sk_get(&r
->pdiag_cookie
[0]);
3871 if (tb
[PACKET_DIAG_MEMINFO
]) {
3872 __u32
*skmeminfo
= RTA_DATA(tb
[PACKET_DIAG_MEMINFO
]);
3874 stat
.rq
= skmeminfo
[SK_MEMINFO_RMEM_ALLOC
];
3877 if (tb
[PACKET_DIAG_INFO
]) {
3878 pinfo
= RTA_DATA(tb
[PACKET_DIAG_INFO
]);
3879 stat
.lport
= stat
.iface
= pinfo
->pdi_index
;
3882 if (tb
[PACKET_DIAG_UID
])
3883 stat
.uid
= rta_getattr_u32(tb
[PACKET_DIAG_UID
]);
3885 if (tb
[PACKET_DIAG_RX_RING
])
3886 ring_rx
= RTA_DATA(tb
[PACKET_DIAG_RX_RING
]);
3888 if (tb
[PACKET_DIAG_TX_RING
])
3889 ring_tx
= RTA_DATA(tb
[PACKET_DIAG_TX_RING
]);
3891 if (tb
[PACKET_DIAG_FANOUT
]) {
3893 fanout
= rta_getattr_u32(tb
[PACKET_DIAG_FANOUT
]);
3896 if (packet_stats_print(&stat
, f
))
3901 out("\n\tver:%d", pinfo
->pdi_version
);
3902 out(" cpy_thresh:%d", pinfo
->pdi_copy_thresh
);
3904 if (pinfo
->pdi_flags
& PDI_RUNNING
)
3906 if (pinfo
->pdi_flags
& PDI_AUXDATA
)
3908 if (pinfo
->pdi_flags
& PDI_ORIGDEV
)
3910 if (pinfo
->pdi_flags
& PDI_VNETHDR
)
3912 if (pinfo
->pdi_flags
& PDI_LOSS
)
3914 if (!pinfo
->pdi_flags
)
3919 out("\n\tring_rx(");
3920 packet_show_ring(ring_rx
);
3924 out("\n\tring_tx(");
3925 packet_show_ring(ring_tx
);
3929 uint16_t type
= (fanout
>> 16) & 0xffff;
3932 out("id:%d,", fanout
& 0xffff);
3954 if (show_bpf
&& tb
[PACKET_DIAG_FILTER
]) {
3955 struct sock_filter
*fil
=
3956 RTA_DATA(tb
[PACKET_DIAG_FILTER
]);
3957 int num
= RTA_PAYLOAD(tb
[PACKET_DIAG_FILTER
]) /
3958 sizeof(struct sock_filter
);
3960 out("\n\tbpf filter (%d): ", num
);
3962 out(" 0x%02x %u %u %u,",
3963 fil
->code
, fil
->jt
, fil
->jf
, fil
->k
);
3970 print_skmeminfo(tb
, PACKET_DIAG_MEMINFO
);
3974 static int packet_show_netlink(struct filter
*f
)
3976 DIAG_REQUEST(req
, struct packet_diag_req r
);
3978 req
.r
.sdiag_family
= AF_PACKET
;
3979 req
.r
.pdiag_show
= PACKET_SHOW_INFO
| PACKET_SHOW_MEMINFO
|
3980 PACKET_SHOW_FILTER
| PACKET_SHOW_RING_CFG
| PACKET_SHOW_FANOUT
;
3982 return handle_netlink_request(f
, &req
.nlh
, sizeof(req
), packet_show_sock
);
3985 static int packet_show_line(char *buf
, const struct filter
*f
, int fam
)
3987 unsigned long long sk
;
3988 struct sockstat stat
= {};
3989 int type
, prot
, iface
, state
, rq
, uid
, ino
;
3991 sscanf(buf
, "%llx %*d %d %x %d %d %u %u %u",
3993 &type
, &prot
, &iface
, &state
,
3996 if (stat
.type
== SOCK_RAW
&& !(f
->dbs
&(1<<PACKET_R_DB
)))
3998 if (stat
.type
== SOCK_DGRAM
&& !(f
->dbs
&(1<<PACKET_DG_DB
)))
4003 stat
.lport
= stat
.iface
= iface
;
4008 stat
.state
= SS_CLOSE
;
4010 if (packet_stats_print(&stat
, f
))
4016 static int packet_show(struct filter
*f
)
4021 if (!filter_af_get(f
, AF_PACKET
) || !(f
->states
& (1 << SS_CLOSE
)))
4024 if (!getenv("PROC_NET_PACKET") && !getenv("PROC_ROOT") &&
4025 packet_show_netlink(f
) == 0)
4028 if ((fp
= net_packet_open()) == NULL
)
4030 if (generic_record_read(fp
, packet_show_line
, f
, AF_PACKET
))
4037 static int netlink_show_one(struct filter
*f
,
4038 int prot
, int pid
, unsigned int groups
,
4039 int state
, int dst_pid
, unsigned int dst_group
,
4041 unsigned long long sk
, unsigned long long cb
)
4043 struct sockstat st
= {
4047 .local
.family
= AF_NETLINK
,
4048 .remote
.family
= AF_NETLINK
,
4051 SPRINT_BUF(prot_buf
) = {};
4052 const char *prot_name
;
4053 char procname
[64] = {};
4058 st
.local
.data
[0] = prot
;
4059 if (run_ssfilter(f
->f
, &st
) == 0)
4063 sock_state_print(&st
);
4065 if (resolve_services
)
4066 prot_name
= nl_proto_n2a(prot
, prot_buf
, sizeof(prot_buf
));
4068 prot_name
= int_to_str(prot
, prot_buf
);
4072 } else if (resolve_services
) {
4077 strncpy(procname
, "kernel", 7);
4078 } else if (pid
> 0) {
4081 snprintf(procname
, sizeof(procname
), "%s/%d/stat",
4082 getenv("PROC_ROOT") ? : "/proc", pid
);
4083 if ((fp
= fopen(procname
, "r")) != NULL
) {
4084 if (fscanf(fp
, "%*d (%[^)])", procname
) == 1) {
4085 snprintf(procname
+strlen(procname
),
4086 sizeof(procname
)-strlen(procname
),
4094 int_to_str(pid
, procname
);
4096 int_to_str(pid
, procname
);
4099 sock_addr_print(prot_name
, ":", procname
, NULL
);
4101 if (state
== NETLINK_CONNECTED
) {
4102 char dst_group_buf
[30];
4103 char dst_pid_buf
[30];
4105 sock_addr_print(int_to_str(dst_group
, dst_group_buf
), ":",
4106 int_to_str(dst_pid
, dst_pid_buf
), NULL
);
4108 sock_addr_print("", "*", "", NULL
);
4111 char *pid_context
= NULL
;
4113 if (show_proc_ctx
) {
4114 /* The pid value will either be:
4115 * 0 if destination kernel - show kernel initial context.
4116 * A valid process pid - use getpidcon.
4117 * A unique value allocated by the kernel or netlink user
4118 * to the process - show context as "not available".
4121 security_get_initial_context("kernel", &pid_context
);
4123 getpidcon(pid
, &pid_context
);
4125 out(" proc_ctx=%s", pid_context
? : "unavailable");
4130 out(" sk=%llx cb=%llx groups=0x%08x", sk
, cb
, groups
);
4136 static int netlink_show_sock(const struct sockaddr_nl
*addr
,
4137 struct nlmsghdr
*nlh
, void *arg
)
4139 struct filter
*f
= (struct filter
*)arg
;
4140 struct netlink_diag_msg
*r
= NLMSG_DATA(nlh
);
4141 struct rtattr
*tb
[NETLINK_DIAG_MAX
+1];
4143 unsigned long groups
= 0;
4145 parse_rtattr(tb
, NETLINK_DIAG_MAX
, (struct rtattr
*)(r
+1),
4146 nlh
->nlmsg_len
- NLMSG_LENGTH(sizeof(*r
)));
4148 if (tb
[NETLINK_DIAG_GROUPS
] && RTA_PAYLOAD(tb
[NETLINK_DIAG_GROUPS
]))
4149 groups
= *(unsigned long *) RTA_DATA(tb
[NETLINK_DIAG_GROUPS
]);
4151 if (tb
[NETLINK_DIAG_MEMINFO
]) {
4152 const __u32
*skmeminfo
;
4154 skmeminfo
= RTA_DATA(tb
[NETLINK_DIAG_MEMINFO
]);
4156 rq
= skmeminfo
[SK_MEMINFO_RMEM_ALLOC
];
4157 wq
= skmeminfo
[SK_MEMINFO_WMEM_ALLOC
];
4160 if (netlink_show_one(f
, r
->ndiag_protocol
, r
->ndiag_portid
, groups
,
4161 r
->ndiag_state
, r
->ndiag_dst_portid
, r
->ndiag_dst_group
,
4168 print_skmeminfo(tb
, NETLINK_DIAG_MEMINFO
);
4174 static int netlink_show_netlink(struct filter
*f
)
4176 DIAG_REQUEST(req
, struct netlink_diag_req r
);
4178 req
.r
.sdiag_family
= AF_NETLINK
;
4179 req
.r
.sdiag_protocol
= NDIAG_PROTO_ALL
;
4180 req
.r
.ndiag_show
= NDIAG_SHOW_GROUPS
| NDIAG_SHOW_MEMINFO
;
4182 return handle_netlink_request(f
, &req
.nlh
, sizeof(req
), netlink_show_sock
);
4185 static int netlink_show(struct filter
*f
)
4190 unsigned int groups
;
4192 unsigned long long sk
, cb
;
4194 if (!filter_af_get(f
, AF_NETLINK
) || !(f
->states
& (1 << SS_CLOSE
)))
4197 if (!getenv("PROC_NET_NETLINK") && !getenv("PROC_ROOT") &&
4198 netlink_show_netlink(f
) == 0)
4201 if ((fp
= net_netlink_open()) == NULL
)
4203 if (!fgets(buf
, sizeof(buf
), fp
)) {
4208 while (fgets(buf
, sizeof(buf
), fp
)) {
4209 sscanf(buf
, "%llx %d %d %x %d %d %llx %d",
4211 &prot
, &pid
, &groups
, &rq
, &wq
, &cb
, &rc
);
4213 netlink_show_one(f
, prot
, pid
, groups
, 0, 0, 0, rq
, wq
, sk
, cb
);
4220 static bool vsock_type_skip(struct sockstat
*s
, struct filter
*f
)
4222 if (s
->type
== SOCK_STREAM
&& !(f
->dbs
& (1 << VSOCK_ST_DB
)))
4224 if (s
->type
== SOCK_DGRAM
&& !(f
->dbs
& (1 << VSOCK_DG_DB
)))
4229 static void vsock_addr_print(inet_prefix
*a
, __u32 port
)
4231 char cid_str
[sizeof("4294967295")];
4232 char port_str
[sizeof("4294967295")];
4235 memcpy(&cid
, a
->data
, sizeof(cid
));
4237 if (cid
== ~(__u32
)0)
4238 snprintf(cid_str
, sizeof(cid_str
), "*");
4240 snprintf(cid_str
, sizeof(cid_str
), "%u", cid
);
4242 if (port
== ~(__u32
)0)
4243 snprintf(port_str
, sizeof(port_str
), "*");
4245 snprintf(port_str
, sizeof(port_str
), "%u", port
);
4247 sock_addr_print(cid_str
, ":", port_str
, NULL
);
4250 static void vsock_stats_print(struct sockstat
*s
, struct filter
*f
)
4252 sock_state_print(s
);
4254 vsock_addr_print(&s
->local
, s
->lport
);
4255 vsock_addr_print(&s
->remote
, s
->rport
);
4260 static int vsock_show_sock(const struct sockaddr_nl
*addr
,
4261 struct nlmsghdr
*nlh
, void *arg
)
4263 struct filter
*f
= (struct filter
*)arg
;
4264 struct vsock_diag_msg
*r
= NLMSG_DATA(nlh
);
4265 struct sockstat stat
= {
4266 .type
= r
->vdiag_type
,
4267 .lport
= r
->vdiag_src_port
,
4268 .rport
= r
->vdiag_dst_port
,
4269 .state
= r
->vdiag_state
,
4270 .ino
= r
->vdiag_ino
,
4273 vsock_set_inet_prefix(&stat
.local
, r
->vdiag_src_cid
);
4274 vsock_set_inet_prefix(&stat
.remote
, r
->vdiag_dst_cid
);
4276 if (vsock_type_skip(&stat
, f
))
4279 if (f
->f
&& run_ssfilter(f
->f
, &stat
) == 0)
4282 vsock_stats_print(&stat
, f
);
4287 static int vsock_show(struct filter
*f
)
4289 DIAG_REQUEST(req
, struct vsock_diag_req r
);
4291 if (!filter_af_get(f
, AF_VSOCK
))
4294 req
.r
.sdiag_family
= AF_VSOCK
;
4295 req
.r
.vdiag_states
= f
->states
;
4297 return handle_netlink_request(f
, &req
.nlh
, sizeof(req
), vsock_show_sock
);
4300 static void tipc_sock_addr_print(struct rtattr
*net_addr
, struct rtattr
*id
)
4302 uint32_t node
= rta_getattr_u32(net_addr
);
4303 uint32_t identity
= rta_getattr_u32(id
);
4305 SPRINT_BUF(addr
) = {};
4306 SPRINT_BUF(port
) = {};
4308 sprintf(addr
, "%u", node
);
4309 sprintf(port
, "%u", identity
);
4310 sock_addr_print(addr
, ":", port
, NULL
);
4314 static int tipc_show_sock(const struct sockaddr_nl
*addr
, struct nlmsghdr
*nlh
,
4317 struct rtattr
*stat
[TIPC_NLA_SOCK_STAT_MAX
+ 1] = {};
4318 struct rtattr
*attrs
[TIPC_NLA_SOCK_MAX
+ 1] = {};
4319 struct rtattr
*con
[TIPC_NLA_CON_MAX
+ 1] = {};
4320 struct rtattr
*info
[TIPC_NLA_MAX
+ 1] = {};
4321 struct rtattr
*msg_ref
;
4322 struct sockstat ss
= {};
4324 parse_rtattr(info
, TIPC_NLA_MAX
, NLMSG_DATA(nlh
),
4325 NLMSG_PAYLOAD(nlh
, 0));
4327 if (!info
[TIPC_NLA_SOCK
])
4330 msg_ref
= info
[TIPC_NLA_SOCK
];
4331 parse_rtattr(attrs
, TIPC_NLA_SOCK_MAX
, RTA_DATA(msg_ref
),
4332 RTA_PAYLOAD(msg_ref
));
4334 msg_ref
= attrs
[TIPC_NLA_SOCK_STAT
];
4335 parse_rtattr(stat
, TIPC_NLA_SOCK_STAT_MAX
,
4336 RTA_DATA(msg_ref
), RTA_PAYLOAD(msg_ref
));
4339 ss
.local
.family
= AF_TIPC
;
4340 ss
.type
= rta_getattr_u32(attrs
[TIPC_NLA_SOCK_TYPE
]);
4341 ss
.state
= rta_getattr_u32(attrs
[TIPC_NLA_SOCK_TIPC_STATE
]);
4342 ss
.uid
= rta_getattr_u32(attrs
[TIPC_NLA_SOCK_UID
]);
4343 ss
.ino
= rta_getattr_u32(attrs
[TIPC_NLA_SOCK_INO
]);
4344 ss
.rq
= rta_getattr_u32(stat
[TIPC_NLA_SOCK_STAT_RCVQ
]);
4345 ss
.wq
= rta_getattr_u32(stat
[TIPC_NLA_SOCK_STAT_SENDQ
]);
4346 ss
.sk
= rta_getattr_u64(attrs
[TIPC_NLA_SOCK_COOKIE
]);
4348 sock_state_print (&ss
);
4350 tipc_sock_addr_print(attrs
[TIPC_NLA_SOCK_ADDR
],
4351 attrs
[TIPC_NLA_SOCK_REF
]);
4353 msg_ref
= attrs
[TIPC_NLA_SOCK_CON
];
4355 parse_rtattr(con
, TIPC_NLA_CON_MAX
,
4356 RTA_DATA(msg_ref
), RTA_PAYLOAD(msg_ref
));
4358 tipc_sock_addr_print(con
[TIPC_NLA_CON_NODE
],
4359 con
[TIPC_NLA_CON_SOCK
]);
4361 sock_addr_print("", "-", "", NULL
);
4364 sock_details_print(&ss
);
4366 proc_ctx_print(&ss
);
4368 if (show_tipcinfo
) {
4369 out("\n type:%s", stype_nameg
[ss
.type
]);
4371 stat
[TIPC_NLA_SOCK_STAT_LINK_CONG
] ? "link" :
4372 stat
[TIPC_NLA_SOCK_STAT_CONN_CONG
] ? "conn" : "none");
4374 rta_getattr_u32(stat
[TIPC_NLA_SOCK_STAT_DROP
]));
4376 if (attrs
[TIPC_NLA_SOCK_HAS_PUBL
])
4379 if (con
[TIPC_NLA_CON_FLAG
])
4380 out(" via {%u,%u} ",
4381 rta_getattr_u32(con
[TIPC_NLA_CON_TYPE
]),
4382 rta_getattr_u32(con
[TIPC_NLA_CON_INST
]));
4388 static int tipc_show(struct filter
*f
)
4390 DIAG_REQUEST(req
, struct tipc_sock_diag_req r
);
4392 memset(&req
.r
, 0, sizeof(req
.r
));
4393 req
.r
.sdiag_family
= AF_TIPC
;
4394 req
.r
.tidiag_states
= f
->states
;
4396 return handle_netlink_request(f
, &req
.nlh
, sizeof(req
), tipc_show_sock
);
4399 struct sock_diag_msg
{
4403 static int generic_show_sock(const struct sockaddr_nl
*addr
,
4404 struct nlmsghdr
*nlh
, void *arg
)
4406 struct sock_diag_msg
*r
= NLMSG_DATA(nlh
);
4407 struct inet_diag_arg inet_arg
= { .f
= arg
, .protocol
= IPPROTO_MAX
};
4410 switch (r
->sdiag_family
) {
4413 inet_arg
.rth
= inet_arg
.f
->rth_for_killing
;
4414 ret
= show_one_inet_sock(addr
, nlh
, &inet_arg
);
4417 ret
= unix_show_sock(addr
, nlh
, arg
);
4420 ret
= packet_show_sock(addr
, nlh
, arg
);
4423 ret
= netlink_show_sock(addr
, nlh
, arg
);
4426 ret
= vsock_show_sock(addr
, nlh
, arg
);
4437 static int handle_follow_request(struct filter
*f
)
4441 struct rtnl_handle rth
, rth2
;
4443 if (f
->families
& FAMILY_MASK(AF_INET
) && f
->dbs
& (1 << TCP_DB
))
4444 groups
|= 1 << (SKNLGRP_INET_TCP_DESTROY
- 1);
4445 if (f
->families
& FAMILY_MASK(AF_INET
) && f
->dbs
& (1 << UDP_DB
))
4446 groups
|= 1 << (SKNLGRP_INET_UDP_DESTROY
- 1);
4447 if (f
->families
& FAMILY_MASK(AF_INET6
) && f
->dbs
& (1 << TCP_DB
))
4448 groups
|= 1 << (SKNLGRP_INET6_TCP_DESTROY
- 1);
4449 if (f
->families
& FAMILY_MASK(AF_INET6
) && f
->dbs
& (1 << UDP_DB
))
4450 groups
|= 1 << (SKNLGRP_INET6_UDP_DESTROY
- 1);
4455 if (rtnl_open_byproto(&rth
, groups
, NETLINK_SOCK_DIAG
))
4459 rth
.local
.nl_pid
= 0;
4462 if (rtnl_open_byproto(&rth2
, groups
, NETLINK_SOCK_DIAG
)) {
4466 f
->rth_for_killing
= &rth2
;
4469 if (rtnl_dump_filter(&rth
, generic_show_sock
, f
))
4473 if (f
->rth_for_killing
)
4474 rtnl_close(f
->rth_for_killing
);
4478 static int get_snmp_int(char *proto
, char *key
, int *result
)
4482 int protolen
= strlen(proto
);
4483 int keylen
= strlen(key
);
4487 if ((fp
= net_snmp_open()) == NULL
)
4490 while (fgets(buf
, sizeof(buf
), fp
) != NULL
) {
4494 if (memcmp(buf
, proto
, protolen
))
4496 while ((p
= strchr(p
, ' ')) != NULL
) {
4499 if (memcmp(p
, key
, keylen
) == 0 &&
4500 (p
[keylen
] == ' ' || p
[keylen
] == '\n'))
4503 if (fgets(buf
, sizeof(buf
), fp
) == NULL
)
4505 if (memcmp(buf
, proto
, protolen
))
4508 while ((p
= strchr(p
, ' ')) != NULL
) {
4511 sscanf(p
, "%d", result
);
4524 /* Get stats from sockstat */
4544 static void get_sockstat_line(char *line
, struct ssummary
*s
)
4546 char id
[256], rem
[256];
4548 if (sscanf(line
, "%[^ ] %[^\n]\n", id
, rem
) != 2)
4551 if (strcmp(id
, "sockets:") == 0)
4552 sscanf(rem
, "%*s%d", &s
->socks
);
4553 else if (strcmp(id
, "UDP:") == 0)
4554 sscanf(rem
, "%*s%d", &s
->udp4
);
4555 else if (strcmp(id
, "UDP6:") == 0)
4556 sscanf(rem
, "%*s%d", &s
->udp6
);
4557 else if (strcmp(id
, "RAW:") == 0)
4558 sscanf(rem
, "%*s%d", &s
->raw4
);
4559 else if (strcmp(id
, "RAW6:") == 0)
4560 sscanf(rem
, "%*s%d", &s
->raw6
);
4561 else if (strcmp(id
, "TCP6:") == 0)
4562 sscanf(rem
, "%*s%d", &s
->tcp6_hashed
);
4563 else if (strcmp(id
, "FRAG:") == 0)
4564 sscanf(rem
, "%*s%d%*s%d", &s
->frag4
, &s
->frag4_mem
);
4565 else if (strcmp(id
, "FRAG6:") == 0)
4566 sscanf(rem
, "%*s%d%*s%d", &s
->frag6
, &s
->frag6_mem
);
4567 else if (strcmp(id
, "TCP:") == 0)
4568 sscanf(rem
, "%*s%d%*s%d%*s%d%*s%d%*s%d",
4570 &s
->tcp_orphans
, &s
->tcp_tws
, &s
->tcp_total
, &s
->tcp_mem
);
4573 static int get_sockstat(struct ssummary
*s
)
4578 memset(s
, 0, sizeof(*s
));
4580 if ((fp
= net_sockstat_open()) == NULL
)
4582 while (fgets(buf
, sizeof(buf
), fp
) != NULL
)
4583 get_sockstat_line(buf
, s
);
4586 if ((fp
= net_sockstat6_open()) == NULL
)
4588 while (fgets(buf
, sizeof(buf
), fp
) != NULL
)
4589 get_sockstat_line(buf
, s
);
4595 static int print_summary(void)
4600 if (get_sockstat(&s
) < 0)
4601 perror("ss: get_sockstat");
4602 if (get_snmp_int("Tcp:", "CurrEstab", &tcp_estab
) < 0)
4603 perror("ss: get_snmpstat");
4605 printf("Total: %d\n", s
.socks
);
4607 printf("TCP: %d (estab %d, closed %d, orphaned %d, timewait %d)\n",
4608 s
.tcp_total
+ s
.tcp_tws
, tcp_estab
,
4609 s
.tcp_total
- (s
.tcp4_hashed
+ s
.tcp6_hashed
- s
.tcp_tws
),
4610 s
.tcp_orphans
, s
.tcp_tws
);
4613 printf("Transport Total IP IPv6\n");
4614 printf("RAW %-9d %-9d %-9d\n", s
.raw4
+s
.raw6
, s
.raw4
, s
.raw6
);
4615 printf("UDP %-9d %-9d %-9d\n", s
.udp4
+s
.udp6
, s
.udp4
, s
.udp6
);
4616 printf("TCP %-9d %-9d %-9d\n", s
.tcp4_hashed
+s
.tcp6_hashed
, s
.tcp4_hashed
, s
.tcp6_hashed
);
4617 printf("INET %-9d %-9d %-9d\n",
4618 s
.raw4
+s
.udp4
+s
.tcp4_hashed
+
4619 s
.raw6
+s
.udp6
+s
.tcp6_hashed
,
4620 s
.raw4
+s
.udp4
+s
.tcp4_hashed
,
4621 s
.raw6
+s
.udp6
+s
.tcp6_hashed
);
4622 printf("FRAG %-9d %-9d %-9d\n", s
.frag4
+s
.frag6
, s
.frag4
, s
.frag6
);
4629 static void _usage(FILE *dest
)
4632 "Usage: ss [ OPTIONS ]\n"
4633 " ss [ OPTIONS ] [ FILTER ]\n"
4634 " -h, --help this message\n"
4635 " -V, --version output version information\n"
4636 " -n, --numeric don't resolve service names\n"
4637 " -r, --resolve resolve host names\n"
4638 " -a, --all display all sockets\n"
4639 " -l, --listening display listening sockets\n"
4640 " -o, --options show timer information\n"
4641 " -e, --extended show detailed socket information\n"
4642 " -m, --memory show socket memory usage\n"
4643 " -p, --processes show process using socket\n"
4644 " -i, --info show internal TCP information\n"
4645 " --tipcinfo show internal tipc socket information\n"
4646 " -s, --summary show socket usage summary\n"
4647 " -b, --bpf show bpf filter socket information\n"
4648 " -E, --events continually display sockets as they are destroyed\n"
4649 " -Z, --context display process SELinux security contexts\n"
4650 " -z, --contexts display process and socket SELinux security contexts\n"
4651 " -N, --net switch to the specified network namespace name\n"
4653 " -4, --ipv4 display only IP version 4 sockets\n"
4654 " -6, --ipv6 display only IP version 6 sockets\n"
4655 " -0, --packet display PACKET sockets\n"
4656 " -t, --tcp display only TCP sockets\n"
4657 " -S, --sctp display only SCTP sockets\n"
4658 " -u, --udp display only UDP sockets\n"
4659 " -d, --dccp display only DCCP sockets\n"
4660 " -w, --raw display only RAW sockets\n"
4661 " -x, --unix display only Unix domain sockets\n"
4662 " --tipc display only TIPC sockets\n"
4663 " --vsock display only vsock sockets\n"
4664 " -f, --family=FAMILY display sockets of type FAMILY\n"
4665 " FAMILY := {inet|inet6|link|unix|netlink|vsock|tipc|help}\n"
4667 " -K, --kill forcibly close sockets, display what was closed\n"
4668 " -H, --no-header Suppress header line\n"
4670 " -A, --query=QUERY, --socket=QUERY\n"
4671 " QUERY := {all|inet|tcp|udp|raw|unix|unix_dgram|unix_stream|unix_seqpacket|packet|netlink|vsock_stream|vsock_dgram|tipc}[,QUERY]\n"
4673 " -D, --diag=FILE Dump raw information about TCP sockets to FILE\n"
4674 " -F, --filter=FILE read filter information from FILE\n"
4675 " FILTER := [ state STATE-FILTER ] [ EXPRESSION ]\n"
4676 " STATE-FILTER := {all|connected|synchronized|bucket|big|TCP-STATES}\n"
4677 " TCP-STATES := {established|syn-sent|syn-recv|fin-wait-{1,2}|time-wait|closed|close-wait|last-ack|listening|closing}\n"
4678 " connected := {established|syn-sent|syn-recv|fin-wait-{1,2}|time-wait|close-wait|last-ack|closing}\n"
4679 " synchronized := {established|syn-recv|fin-wait-{1,2}|time-wait|close-wait|last-ack|closing}\n"
4680 " bucket := {syn-recv|time-wait}\n"
4681 " big := {established|syn-sent|fin-wait-{1,2}|closed|close-wait|last-ack|listening|closing}\n"
4685 static void help(void) __attribute__((noreturn
));
4686 static void help(void)
4692 static void usage(void) __attribute__((noreturn
));
4693 static void usage(void)
4700 static int scan_state(const char *state
)
4702 static const char * const sstate_namel
[] = {
4704 [SS_ESTABLISHED
] = "established",
4705 [SS_SYN_SENT
] = "syn-sent",
4706 [SS_SYN_RECV
] = "syn-recv",
4707 [SS_FIN_WAIT1
] = "fin-wait-1",
4708 [SS_FIN_WAIT2
] = "fin-wait-2",
4709 [SS_TIME_WAIT
] = "time-wait",
4710 [SS_CLOSE
] = "unconnected",
4711 [SS_CLOSE_WAIT
] = "close-wait",
4712 [SS_LAST_ACK
] = "last-ack",
4713 [SS_LISTEN
] = "listening",
4714 [SS_CLOSING
] = "closing",
4718 if (strcasecmp(state
, "close") == 0 ||
4719 strcasecmp(state
, "closed") == 0)
4720 return (1<<SS_CLOSE
);
4721 if (strcasecmp(state
, "syn-rcv") == 0)
4722 return (1<<SS_SYN_RECV
);
4723 if (strcasecmp(state
, "established") == 0)
4724 return (1<<SS_ESTABLISHED
);
4725 if (strcasecmp(state
, "all") == 0)
4727 if (strcasecmp(state
, "connected") == 0)
4728 return SS_ALL
& ~((1<<SS_CLOSE
)|(1<<SS_LISTEN
));
4729 if (strcasecmp(state
, "synchronized") == 0)
4730 return SS_ALL
& ~((1<<SS_CLOSE
)|(1<<SS_LISTEN
)|(1<<SS_SYN_SENT
));
4731 if (strcasecmp(state
, "bucket") == 0)
4732 return (1<<SS_SYN_RECV
)|(1<<SS_TIME_WAIT
);
4733 if (strcasecmp(state
, "big") == 0)
4734 return SS_ALL
& ~((1<<SS_SYN_RECV
)|(1<<SS_TIME_WAIT
));
4735 for (i
= 0; i
< SS_MAX
; i
++) {
4736 if (strcasecmp(state
, sstate_namel
[i
]) == 0)
4740 fprintf(stderr
, "ss: wrong state name: %s\n", state
);
4744 /* Values 'v' and 'V' are already used so a non-character is used */
4745 #define OPT_VSOCK 256
4747 /* Values of 't' are already used so a non-character is used */
4748 #define OPT_TIPCSOCK 257
4749 #define OPT_TIPCINFO 258
4751 static const struct option long_opts
[] = {
4752 { "numeric", 0, 0, 'n' },
4753 { "resolve", 0, 0, 'r' },
4754 { "options", 0, 0, 'o' },
4755 { "extended", 0, 0, 'e' },
4756 { "memory", 0, 0, 'm' },
4757 { "info", 0, 0, 'i' },
4758 { "processes", 0, 0, 'p' },
4759 { "bpf", 0, 0, 'b' },
4760 { "events", 0, 0, 'E' },
4761 { "dccp", 0, 0, 'd' },
4762 { "tcp", 0, 0, 't' },
4763 { "sctp", 0, 0, 'S' },
4764 { "udp", 0, 0, 'u' },
4765 { "raw", 0, 0, 'w' },
4766 { "unix", 0, 0, 'x' },
4767 { "tipc", 0, 0, OPT_TIPCSOCK
},
4768 { "vsock", 0, 0, OPT_VSOCK
},
4769 { "all", 0, 0, 'a' },
4770 { "listening", 0, 0, 'l' },
4771 { "ipv4", 0, 0, '4' },
4772 { "ipv6", 0, 0, '6' },
4773 { "packet", 0, 0, '0' },
4774 { "family", 1, 0, 'f' },
4775 { "socket", 1, 0, 'A' },
4776 { "query", 1, 0, 'A' },
4777 { "summary", 0, 0, 's' },
4778 { "diag", 1, 0, 'D' },
4779 { "filter", 1, 0, 'F' },
4780 { "version", 0, 0, 'V' },
4781 { "help", 0, 0, 'h' },
4782 { "context", 0, 0, 'Z' },
4783 { "contexts", 0, 0, 'z' },
4784 { "net", 1, 0, 'N' },
4785 { "tipcinfo", 0, 0, OPT_TIPCINFO
},
4786 { "kill", 0, 0, 'K' },
4787 { "no-header", 0, 0, 'H' },
4792 int main(int argc
, char *argv
[])
4797 const char *dump_tcpdiag
= NULL
;
4798 FILE *filter_fp
= NULL
;
4800 int state_filter
= 0;
4802 while ((ch
= getopt_long(argc
, argv
,
4803 "dhaletuwxnro460spbEf:miA:D:F:vVzZN:KHS",
4804 long_opts
, NULL
)) != EOF
) {
4807 resolve_services
= 0;
4827 user_ent_hash_build();
4837 filter_db_set(¤t_filter
, DCCP_DB
, true);
4840 filter_db_set(¤t_filter
, TCP_DB
, true);
4843 filter_db_set(¤t_filter
, SCTP_DB
, true);
4846 filter_db_set(¤t_filter
, UDP_DB
, true);
4849 filter_db_set(¤t_filter
, RAW_DB
, true);
4852 filter_af_set(¤t_filter
, AF_UNIX
);
4855 filter_af_set(¤t_filter
, AF_VSOCK
);
4858 filter_af_set(¤t_filter
, AF_TIPC
);
4861 state_filter
= SS_ALL
;
4864 state_filter
= (1 << SS_LISTEN
) | (1 << SS_CLOSE
);
4867 filter_af_set(¤t_filter
, AF_INET
);
4870 filter_af_set(¤t_filter
, AF_INET6
);
4873 filter_af_set(¤t_filter
, AF_PACKET
);
4876 if (strcmp(optarg
, "inet") == 0)
4877 filter_af_set(¤t_filter
, AF_INET
);
4878 else if (strcmp(optarg
, "inet6") == 0)
4879 filter_af_set(¤t_filter
, AF_INET6
);
4880 else if (strcmp(optarg
, "link") == 0)
4881 filter_af_set(¤t_filter
, AF_PACKET
);
4882 else if (strcmp(optarg
, "unix") == 0)
4883 filter_af_set(¤t_filter
, AF_UNIX
);
4884 else if (strcmp(optarg
, "netlink") == 0)
4885 filter_af_set(¤t_filter
, AF_NETLINK
);
4886 else if (strcmp(optarg
, "tipc") == 0)
4887 filter_af_set(¤t_filter
, AF_TIPC
);
4888 else if (strcmp(optarg
, "vsock") == 0)
4889 filter_af_set(¤t_filter
, AF_VSOCK
);
4890 else if (strcmp(optarg
, "help") == 0)
4893 fprintf(stderr
, "ss: \"%s\" is invalid family\n",
4903 current_filter
.dbs
= 0;
4904 state_filter
= state_filter
?
4905 state_filter
: SS_CONN
;
4911 if ((p1
= strchr(p
, ',')) != NULL
)
4913 if (filter_db_parse(¤t_filter
, p
)) {
4914 fprintf(stderr
, "ss: \"%s\" is illegal socket table id\n", p
);
4925 dump_tcpdiag
= optarg
;
4929 fprintf(stderr
, "More than one filter file\n");
4932 if (optarg
[0] == '-')
4935 filter_fp
= fopen(optarg
, "r");
4937 perror("fopen filter file");
4943 printf("ss utility, iproute2-ss%s\n", SNAPSHOT
);
4949 if (is_selinux_enabled() <= 0) {
4950 fprintf(stderr
, "ss: SELinux is not enabled.\n");
4954 user_ent_hash_build();
4957 if (netns_switch(optarg
))
4964 current_filter
.kill
= 1;
4982 if (do_default
&& argc
== 0)
4987 if (strcmp(*argv
, "state") == 0) {
4991 state_filter
|= scan_state(*argv
);
4993 } else if (strcmp(*argv
, "exclude") == 0 ||
4994 strcmp(*argv
, "excl") == 0) {
4997 state_filter
= SS_ALL
;
4998 state_filter
&= ~scan_state(*argv
);
5007 state_filter
= state_filter
? state_filter
: SS_CONN
;
5008 filter_db_parse(¤t_filter
, "all");
5011 filter_states_set(¤t_filter
, state_filter
);
5012 filter_merge_defaults(¤t_filter
);
5014 if (resolve_services
&& resolve_hosts
&&
5015 (current_filter
.dbs
& (UNIX_DBM
|INET_L4_DBM
)))
5016 init_service_resolver();
5018 if (current_filter
.dbs
== 0) {
5019 fprintf(stderr
, "ss: no socket tables to show with such filter.\n");
5022 if (current_filter
.families
== 0) {
5023 fprintf(stderr
, "ss: no families to show with such filter.\n");
5026 if (current_filter
.states
== 0) {
5027 fprintf(stderr
, "ss: no socket states to show with such filter.\n");
5032 FILE *dump_fp
= stdout
;
5034 if (!(current_filter
.dbs
& (1<<TCP_DB
))) {
5035 fprintf(stderr
, "ss: tcpdiag dump requested and no tcp in filter.\n");
5038 if (dump_tcpdiag
[0] != '-') {
5039 dump_fp
= fopen(dump_tcpdiag
, "w");
5040 if (!dump_tcpdiag
) {
5041 perror("fopen dump file");
5045 inet_show_netlink(¤t_filter
, dump_fp
, IPPROTO_TCP
);
5050 if (ssfilter_parse(¤t_filter
.f
, argc
, argv
, filter_fp
))
5053 if (!(current_filter
.dbs
& (current_filter
.dbs
- 1)))
5054 columns
[COL_NETID
].disabled
= 1;
5056 if (!(current_filter
.states
& (current_filter
.states
- 1)))
5057 columns
[COL_STATE
].disabled
= 1;
5065 exit(handle_follow_request(¤t_filter
));
5067 if (current_filter
.dbs
& (1<<NETLINK_DB
))
5068 netlink_show(¤t_filter
);
5069 if (current_filter
.dbs
& PACKET_DBM
)
5070 packet_show(¤t_filter
);
5071 if (current_filter
.dbs
& UNIX_DBM
)
5072 unix_show(¤t_filter
);
5073 if (current_filter
.dbs
& (1<<RAW_DB
))
5074 raw_show(¤t_filter
);
5075 if (current_filter
.dbs
& (1<<UDP_DB
))
5076 udp_show(¤t_filter
);
5077 if (current_filter
.dbs
& (1<<TCP_DB
))
5078 tcp_show(¤t_filter
);
5079 if (current_filter
.dbs
& (1<<DCCP_DB
))
5080 dccp_show(¤t_filter
);
5081 if (current_filter
.dbs
& (1<<SCTP_DB
))
5082 sctp_show(¤t_filter
);
5083 if (current_filter
.dbs
& VSOCK_DBM
)
5084 vsock_show(¤t_filter
);
5085 if (current_filter
.dbs
& (1<<TIPC_DB
))
5086 tipc_show(¤t_filter
);
5088 if (show_users
|| show_proc_ctx
|| show_sock_ctx
)