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>
23 #include <bsd/string.h>
27 #include <arpa/inet.h>
38 #include "libnetlink.h"
39 #include "namespace.h"
42 #include <linux/tcp.h>
43 #include <linux/sock_diag.h>
44 #include <linux/inet_diag.h>
45 #include <linux/unix_diag.h>
46 #include <linux/netdevice.h> /* for MAX_ADDR_LEN */
47 #include <linux/filter.h>
48 #include <linux/packet_diag.h>
49 #include <linux/netlink_diag.h>
50 #include <linux/sctp.h>
51 #include <linux/vm_sockets_diag.h>
52 #include <linux/net.h>
53 #include <linux/tipc.h>
54 #include <linux/tipc_netlink.h>
55 #include <linux/tipc_sockets_diag.h>
57 #define MAGIC_SEQ 123456
58 #define BUF_CHUNK (1024 * 1024)
59 #define LEN_ALIGN(x) (((x) + 1) & ~1)
61 #define DIAG_REQUEST(_req, _r) \
63 struct nlmsghdr nlh; \
67 .nlmsg_type = SOCK_DIAG_BY_FAMILY, \
68 .nlmsg_flags = NLM_F_ROOT|NLM_F_MATCH|NLM_F_REQUEST,\
69 .nlmsg_seq = MAGIC_SEQ, \
70 .nlmsg_len = sizeof(_req), \
75 #include <selinux/selinux.h>
77 /* Stubs for SELinux functions */
78 static int is_selinux_enabled(void)
83 static int getpidcon(pid_t pid
, char **context
)
89 static int getfilecon(char *path
, char **context
)
95 static int security_get_initial_context(char *name
, char **context
)
102 int resolve_services
= 1;
103 int preferred_family
= AF_UNSPEC
;
137 const enum col_align align
;
141 int width
; /* Calculated, including additional layout spacing */
142 int max_len
; /* Measured maximum field length in this column */
145 static struct column columns
[] = {
146 { ALIGN_LEFT
, "Netid", "", 0, 0, 0 },
147 { ALIGN_LEFT
, "State", " ", 0, 0, 0 },
148 { ALIGN_LEFT
, "Recv-Q", " ", 0, 0, 0 },
149 { ALIGN_LEFT
, "Send-Q", " ", 0, 0, 0 },
150 { ALIGN_RIGHT
, "Local Address:", " ", 0, 0, 0 },
151 { ALIGN_LEFT
, "Port", "", 0, 0, 0 },
152 { ALIGN_RIGHT
, "Peer Address:", " ", 0, 0, 0 },
153 { ALIGN_LEFT
, "Port", "", 0, 0, 0 },
154 { ALIGN_LEFT
, "", "", 0, 0, 0 },
157 static struct column
*current_field
= columns
;
159 /* Output buffer: chained chunks of BUF_CHUNK bytes. Each field is written to
160 * the buffer as a variable size token. A token consists of a 16 bits length
161 * field, followed by a string which is not NULL-terminated.
163 * A new chunk is allocated and linked when the current chunk doesn't have
164 * enough room to store the current token as a whole.
167 struct buf_chunk
*next
; /* Next chained chunk */
168 char *end
; /* Current end of content */
173 uint16_t len
; /* Data length, excluding length descriptor */
178 struct buf_token
*cur
; /* Position of current token in chunk */
179 struct buf_chunk
*head
; /* First chunk */
180 struct buf_chunk
*tail
; /* Current chunk */
183 static const char *TCP_PROTO
= "tcp";
184 static const char *SCTP_PROTO
= "sctp";
185 static const char *UDP_PROTO
= "udp";
186 static const char *RAW_PROTO
= "raw";
187 static const char *dg_proto
;
207 #define PACKET_DBM ((1<<PACKET_DG_DB)|(1<<PACKET_R_DB))
208 #define UNIX_DBM ((1<<UNIX_DG_DB)|(1<<UNIX_ST_DB)|(1<<UNIX_SQ_DB))
209 #define ALL_DB ((1<<MAX_DB)-1)
210 #define INET_L4_DBM ((1<<TCP_DB)|(1<<UDP_DB)|(1<<DCCP_DB)|(1<<SCTP_DB))
211 #define INET_DBM (INET_L4_DBM | (1<<RAW_DB))
212 #define VSOCK_DBM ((1<<VSOCK_ST_DB)|(1<<VSOCK_DG_DB))
231 SCTP_STATE_CLOSED
= 0,
232 SCTP_STATE_COOKIE_WAIT
= 1,
233 SCTP_STATE_COOKIE_ECHOED
= 2,
234 SCTP_STATE_ESTABLISHED
= 3,
235 SCTP_STATE_SHUTDOWN_PENDING
= 4,
236 SCTP_STATE_SHUTDOWN_SENT
= 5,
237 SCTP_STATE_SHUTDOWN_RECEIVED
= 6,
238 SCTP_STATE_SHUTDOWN_ACK_SENT
= 7,
241 #define SS_ALL ((1 << SS_MAX) - 1)
242 #define SS_CONN (SS_ALL & ~((1<<SS_LISTEN)|(1<<SS_CLOSE)|(1<<SS_TIME_WAIT)|(1<<SS_SYN_RECV)))
243 #define TIPC_SS_CONN ((1<<SS_ESTABLISHED)|(1<<SS_LISTEN)|(1<<SS_CLOSE))
245 #include "ssfilter.h"
253 struct rtnl_handle
*rth_for_killing
;
256 #define FAMILY_MASK(family) ((uint64_t)1 << (family))
258 static const struct filter default_dbs
[MAX_DB
] = {
261 .families
= FAMILY_MASK(AF_INET
) | FAMILY_MASK(AF_INET6
),
265 .families
= FAMILY_MASK(AF_INET
) | FAMILY_MASK(AF_INET6
),
268 .states
= (1 << SS_ESTABLISHED
),
269 .families
= FAMILY_MASK(AF_INET
) | FAMILY_MASK(AF_INET6
),
272 .states
= (1 << SS_ESTABLISHED
),
273 .families
= FAMILY_MASK(AF_INET
) | FAMILY_MASK(AF_INET6
),
276 .states
= (1 << SS_CLOSE
),
277 .families
= FAMILY_MASK(AF_UNIX
),
281 .families
= FAMILY_MASK(AF_UNIX
),
285 .families
= FAMILY_MASK(AF_UNIX
),
288 .states
= (1 << SS_CLOSE
),
289 .families
= FAMILY_MASK(AF_PACKET
),
292 .states
= (1 << SS_CLOSE
),
293 .families
= FAMILY_MASK(AF_PACKET
),
296 .states
= (1 << SS_CLOSE
),
297 .families
= FAMILY_MASK(AF_NETLINK
),
301 .families
= FAMILY_MASK(AF_INET
) | FAMILY_MASK(AF_INET6
),
305 .families
= FAMILY_MASK(AF_VSOCK
),
309 .families
= FAMILY_MASK(AF_VSOCK
),
312 .states
= TIPC_SS_CONN
,
313 .families
= FAMILY_MASK(AF_TIPC
),
317 static const struct filter default_afs
[AF_MAX
] = {
332 .states
= (1 << SS_CLOSE
),
335 .dbs
= (1 << NETLINK_DB
),
336 .states
= (1 << SS_CLOSE
),
343 .dbs
= (1 << TIPC_DB
),
344 .states
= TIPC_SS_CONN
,
348 static int do_default
= 1;
349 static struct filter current_filter
;
351 static void filter_db_set(struct filter
*f
, int db
, bool enable
)
354 f
->states
|= default_dbs
[db
].states
;
357 f
->dbs
&= ~(1 << db
);
362 static int filter_db_parse(struct filter
*f
, const char *s
)
368 #define ENTRY(name, ...) { #name, { __VA_ARGS__, MAX_DB } }
369 ENTRY(all
, UDP_DB
, DCCP_DB
, TCP_DB
, RAW_DB
,
370 UNIX_ST_DB
, UNIX_DG_DB
, UNIX_SQ_DB
,
371 PACKET_R_DB
, PACKET_DG_DB
, NETLINK_DB
,
372 SCTP_DB
, VSOCK_ST_DB
, VSOCK_DG_DB
),
373 ENTRY(inet
, UDP_DB
, DCCP_DB
, TCP_DB
, SCTP_DB
, RAW_DB
),
375 ENTRY(dccp
, DCCP_DB
),
377 ENTRY(sctp
, SCTP_DB
),
379 ENTRY(unix
, UNIX_ST_DB
, UNIX_DG_DB
, UNIX_SQ_DB
),
380 ENTRY(unix_stream
, UNIX_ST_DB
),
381 ENTRY(u_str
, UNIX_ST_DB
), /* alias for unix_stream */
382 ENTRY(unix_dgram
, UNIX_DG_DB
),
383 ENTRY(u_dgr
, UNIX_DG_DB
), /* alias for unix_dgram */
384 ENTRY(unix_seqpacket
, UNIX_SQ_DB
),
385 ENTRY(u_seq
, UNIX_SQ_DB
), /* alias for unix_seqpacket */
386 ENTRY(packet
, PACKET_R_DB
, PACKET_DG_DB
),
387 ENTRY(packet_raw
, PACKET_R_DB
),
388 ENTRY(p_raw
, PACKET_R_DB
), /* alias for packet_raw */
389 ENTRY(packet_dgram
, PACKET_DG_DB
),
390 ENTRY(p_dgr
, PACKET_DG_DB
), /* alias for packet_dgram */
391 ENTRY(netlink
, NETLINK_DB
),
392 ENTRY(vsock
, VSOCK_ST_DB
, VSOCK_DG_DB
),
393 ENTRY(vsock_stream
, VSOCK_ST_DB
),
394 ENTRY(v_str
, VSOCK_ST_DB
), /* alias for vsock_stream */
395 ENTRY(vsock_dgram
, VSOCK_DG_DB
),
396 ENTRY(v_dgr
, VSOCK_DG_DB
), /* alias for vsock_dgram */
407 for (i
= 0; i
< ARRAY_SIZE(db_name_tbl
); i
++) {
408 if (strcmp(s
, db_name_tbl
[i
].name
))
410 for (dbp
= db_name_tbl
[i
].dbs
; *dbp
!= MAX_DB
; dbp
++)
411 filter_db_set(f
, *dbp
, enable
);
417 static void filter_af_set(struct filter
*f
, int af
)
419 f
->states
|= default_afs
[af
].states
;
420 f
->families
|= FAMILY_MASK(af
);
422 preferred_family
= af
;
425 static int filter_af_get(struct filter
*f
, int af
)
427 return !!(f
->families
& FAMILY_MASK(af
));
430 static void filter_states_set(struct filter
*f
, int states
)
436 static void filter_merge_defaults(struct filter
*f
)
441 for (db
= 0; db
< MAX_DB
; db
++) {
442 if (!(f
->dbs
& (1 << db
)))
445 if (!(default_dbs
[db
].families
& f
->families
))
446 f
->families
|= default_dbs
[db
].families
;
448 for (af
= 0; af
< AF_MAX
; af
++) {
449 if (!(f
->families
& FAMILY_MASK(af
)))
452 if (!(default_afs
[af
].dbs
& f
->dbs
))
453 f
->dbs
|= default_afs
[af
].dbs
;
457 static FILE *generic_proc_open(const char *env
, const char *name
)
459 const char *p
= getenv(env
);
463 p
= getenv("PROC_ROOT") ? : "/proc";
464 snprintf(store
, sizeof(store
)-1, "%s/%s", p
, name
);
468 return fopen(p
, "r");
470 #define net_tcp_open() generic_proc_open("PROC_NET_TCP", "net/tcp")
471 #define net_tcp6_open() generic_proc_open("PROC_NET_TCP6", "net/tcp6")
472 #define net_udp_open() generic_proc_open("PROC_NET_UDP", "net/udp")
473 #define net_udp6_open() generic_proc_open("PROC_NET_UDP6", "net/udp6")
474 #define net_raw_open() generic_proc_open("PROC_NET_RAW", "net/raw")
475 #define net_raw6_open() generic_proc_open("PROC_NET_RAW6", "net/raw6")
476 #define net_unix_open() generic_proc_open("PROC_NET_UNIX", "net/unix")
477 #define net_packet_open() generic_proc_open("PROC_NET_PACKET", \
479 #define net_netlink_open() generic_proc_open("PROC_NET_NETLINK", \
481 #define net_sockstat_open() generic_proc_open("PROC_NET_SOCKSTAT", \
483 #define net_sockstat6_open() generic_proc_open("PROC_NET_SOCKSTAT6", \
485 #define net_snmp_open() generic_proc_open("PROC_NET_SNMP", "net/snmp")
486 #define ephemeral_ports_open() generic_proc_open("PROC_IP_LOCAL_PORT_RANGE", \
487 "sys/net/ipv4/ip_local_port_range")
490 struct user_ent
*next
;
499 #define USER_ENT_HASH_SIZE 256
500 struct user_ent
*user_ent_hash
[USER_ENT_HASH_SIZE
];
502 static int user_ent_hashfn(unsigned int ino
)
504 int val
= (ino
>> 24) ^ (ino
>> 16) ^ (ino
>> 8) ^ ino
;
506 return val
& (USER_ENT_HASH_SIZE
- 1);
509 static void user_ent_add(unsigned int ino
, char *process
,
514 struct user_ent
*p
, **pp
;
516 p
= malloc(sizeof(struct user_ent
));
518 fprintf(stderr
, "ss: failed to malloc buffer\n");
525 p
->process
= strdup(process
);
526 p
->process_ctx
= strdup(proc_ctx
);
527 p
->socket_ctx
= strdup(sock_ctx
);
529 pp
= &user_ent_hash
[user_ent_hashfn(ino
)];
534 static void user_ent_destroy(void)
536 struct user_ent
*p
, *p_next
;
539 while (cnt
!= USER_ENT_HASH_SIZE
) {
540 p
= user_ent_hash
[cnt
];
543 free(p
->process_ctx
);
553 static void user_ent_hash_build(void)
555 const char *root
= getenv("PROC_ROOT") ? : "/proc/";
562 const char *no_ctx
= "unavailable";
563 static int user_ent_hash_build_init
;
565 /* If show_users & show_proc_ctx set only do this once */
566 if (user_ent_hash_build_init
!= 0)
569 user_ent_hash_build_init
= 1;
571 strlcpy(name
, root
, sizeof(name
));
573 if (strlen(name
) == 0 || name
[strlen(name
)-1] != '/')
576 nameoff
= strlen(name
);
582 while ((d
= readdir(dir
)) != NULL
) {
590 if (sscanf(d
->d_name
, "%d%c", &pid
, &crap
) != 1)
593 if (getpidcon(pid
, &pid_context
) != 0)
594 pid_context
= strdup(no_ctx
);
596 snprintf(name
+ nameoff
, sizeof(name
) - nameoff
, "%d/fd/", pid
);
598 if ((dir1
= opendir(name
)) == NULL
) {
606 while ((d1
= readdir(dir1
)) != NULL
) {
607 const char *pattern
= "socket:[";
614 if (sscanf(d1
->d_name
, "%d%c", &fd
, &crap
) != 1)
617 snprintf(name
+pos
, sizeof(name
) - pos
, "%d", fd
);
619 link_len
= readlink(name
, lnk
, sizeof(lnk
)-1);
622 lnk
[link_len
] = '\0';
624 if (strncmp(lnk
, pattern
, strlen(pattern
)))
627 sscanf(lnk
, "socket:[%u]", &ino
);
629 snprintf(tmp
, sizeof(tmp
), "%s/%d/fd/%s",
630 root
, pid
, d1
->d_name
);
632 if (getfilecon(tmp
, &sock_context
) <= 0)
633 sock_context
= strdup(no_ctx
);
638 snprintf(tmp
, sizeof(tmp
), "%s/%d/stat",
640 if ((fp
= fopen(tmp
, "r")) != NULL
) {
641 if (fscanf(fp
, "%*d (%[^)])", p
) < 1)
646 user_ent_add(ino
, p
, pid
, fd
,
647 pid_context
, sock_context
);
662 #define ENTRY_BUF_SIZE 512
663 static int find_entry(unsigned int ino
, char **buf
, int type
)
669 int len
, new_buf_len
;
676 p
= user_ent_hash
[user_ent_hashfn(ino
)];
683 ptr
= *buf
+ buf_used
;
686 len
= snprintf(ptr
, buf_len
- buf_used
,
687 "(\"%s\",pid=%d,fd=%d),",
688 p
->process
, p
->pid
, p
->fd
);
691 len
= snprintf(ptr
, buf_len
- buf_used
,
692 "(\"%s\",pid=%d,proc_ctx=%s,fd=%d),",
694 p
->process_ctx
, p
->fd
);
697 len
= snprintf(ptr
, buf_len
- buf_used
,
698 "(\"%s\",pid=%d,proc_ctx=%s,fd=%d,sock_ctx=%s),",
700 p
->process_ctx
, p
->fd
,
704 fprintf(stderr
, "ss: invalid type: %d\n", type
);
708 if (len
< 0 || len
>= buf_len
- buf_used
) {
709 new_buf_len
= buf_len
+ ENTRY_BUF_SIZE
;
710 new_buf
= realloc(*buf
, new_buf_len
);
712 fprintf(stderr
, "ss: failed to malloc buffer\n");
716 buf_len
= new_buf_len
;
728 ptr
= *buf
+ buf_used
;
734 static unsigned long long cookie_sk_get(const uint32_t *cookie
)
736 return (((unsigned long long)cookie
[1] << 31) << 1) | cookie
[0];
739 static const char *sctp_sstate_name
[] = {
740 [SCTP_STATE_CLOSED
] = "CLOSED",
741 [SCTP_STATE_COOKIE_WAIT
] = "COOKIE_WAIT",
742 [SCTP_STATE_COOKIE_ECHOED
] = "COOKIE_ECHOED",
743 [SCTP_STATE_ESTABLISHED
] = "ESTAB",
744 [SCTP_STATE_SHUTDOWN_PENDING
] = "SHUTDOWN_PENDING",
745 [SCTP_STATE_SHUTDOWN_SENT
] = "SHUTDOWN_SENT",
746 [SCTP_STATE_SHUTDOWN_RECEIVED
] = "SHUTDOWN_RECEIVED",
747 [SCTP_STATE_SHUTDOWN_ACK_SENT
] = "ACK_SENT",
750 static const char * const stype_nameg
[] = {
752 [SOCK_STREAM
] = "STREAM",
753 [SOCK_DGRAM
] = "DGRAM",
755 [SOCK_SEQPACKET
] = "SEQPACKET",
759 struct sockstat
*next
;
773 unsigned long long sk
;
780 unsigned int ce_state
;
790 unsigned int timeout
;
793 double rto
, ato
, rtt
, rttvar
;
794 int qack
, ssthresh
, backoff
;
803 unsigned int lastsnd
;
804 unsigned int lastrcv
;
805 unsigned int lastack
;
807 double pacing_rate_max
;
808 double delivery_rate
;
809 unsigned long long bytes_acked
;
810 unsigned long long bytes_received
;
811 unsigned int segs_out
;
812 unsigned int segs_in
;
813 unsigned int data_segs_out
;
814 unsigned int data_segs_in
;
815 unsigned int unacked
;
816 unsigned int retrans
;
817 unsigned int retrans_total
;
820 unsigned int fackets
;
821 unsigned int reordering
;
822 unsigned int not_sent
;
826 unsigned int rcv_ssthresh
;
827 unsigned long long busy_time
;
828 unsigned long long rwnd_limited
;
829 unsigned long long sndbuf_limited
;
833 bool has_ecnseen_opt
;
834 bool has_fastopen_opt
;
837 struct dctcpstat
*dctcp
;
838 struct tcp_bbr_info
*bbr_info
;
841 /* SCTP assocs share the same inode number with their parent endpoint. So if we
842 * have seen the inode number before, it must be an assoc instead of the next
844 static bool is_sctp_assoc(struct sockstat
*s
, const char *sock_name
)
846 if (strcmp(sock_name
, "sctp"))
848 if (!sctp_ino
|| sctp_ino
!= s
->ino
)
853 static const char *unix_netid_name(int type
)
866 static const char *proto_name(int protocol
)
886 static const char *vsock_netid_name(int type
)
898 static const char *tipc_netid_name(int type
)
914 /* Allocate and initialize a new buffer chunk */
915 static struct buf_chunk
*buf_chunk_new(void)
917 struct buf_chunk
*new = malloc(BUF_CHUNK
);
924 /* This is also the last block */
927 /* Next token will be stored at the beginning of chunk data area, and
928 * its initial length is zero.
930 buffer
.cur
= (struct buf_token
*)new->data
;
933 new->end
= buffer
.cur
->data
;
938 /* Return available tail room in given chunk */
939 static int buf_chunk_avail(struct buf_chunk
*chunk
)
941 return BUF_CHUNK
- offsetof(struct buf_chunk
, data
) -
942 (chunk
->end
- chunk
->data
);
945 /* Update end pointer and token length, link new chunk if we hit the end of the
946 * current one. Return -EAGAIN if we got a new chunk, caller has to print again.
948 static int buf_update(int len
)
950 struct buf_chunk
*chunk
= buffer
.tail
;
951 struct buf_token
*t
= buffer
.cur
;
953 /* Claim success if new content fits in the current chunk, and anyway
954 * if this is the first token in the chunk: in the latter case,
955 * allocating a new chunk won't help, so we'll just cut the output.
957 if ((len
< buf_chunk_avail(chunk
) && len
!= -1 /* glibc < 2.0.6 */) ||
958 t
== (struct buf_token
*)chunk
->data
) {
959 len
= min(len
, buf_chunk_avail(chunk
));
961 /* Total field length can't exceed 2^16 bytes, cut as needed */
962 len
= min(len
, USHRT_MAX
- t
->len
);
969 /* Content truncated, time to allocate more */
970 chunk
->next
= buf_chunk_new();
972 /* Copy current token over to new chunk, including length descriptor */
973 memcpy(chunk
->next
->data
, t
, sizeof(t
->len
) + t
->len
);
974 chunk
->next
->end
+= t
->len
;
976 /* Discard partially written field in old chunk */
977 chunk
->end
-= t
->len
+ sizeof(t
->len
);
982 /* Append content to buffer as part of the current field */
983 __attribute__((format(printf
, 1, 2)))
984 static void out(const char *fmt
, ...)
986 struct column
*f
= current_field
;
995 buffer
.head
= buf_chunk_new();
997 again
: /* Append to buffer: if we have a new chunk, print again */
999 pos
= buffer
.cur
->data
+ buffer
.cur
->len
;
1000 va_start(args
, fmt
);
1002 /* Limit to tail room. If we hit the limit, buf_update() will tell us */
1003 len
= vsnprintf(pos
, buf_chunk_avail(buffer
.tail
), fmt
, args
);
1006 if (buf_update(len
))
1010 static int print_left_spacing(struct column
*f
, int stored
, int printed
)
1014 if (!f
->width
|| f
->align
== ALIGN_LEFT
)
1017 s
= f
->width
- stored
- printed
;
1018 if (f
->align
== ALIGN_CENTER
)
1019 /* If count of total spacing is odd, shift right by one */
1023 return printf("%*c", s
, ' ');
1028 static void print_right_spacing(struct column
*f
, int printed
)
1032 if (!f
->width
|| f
->align
== ALIGN_RIGHT
)
1035 s
= f
->width
- printed
;
1036 if (f
->align
== ALIGN_CENTER
)
1040 printf("%*c", s
, ' ');
1043 /* Done with field: update buffer pointer, start new token after current one */
1044 static void field_flush(struct column
*f
)
1046 struct buf_chunk
*chunk
;
1052 chunk
= buffer
.tail
;
1053 pad
= buffer
.cur
->len
% 2;
1055 if (buffer
.cur
->len
> f
->max_len
)
1056 f
->max_len
= buffer
.cur
->len
;
1058 /* We need a new chunk if we can't store the next length descriptor.
1059 * Mind the gap between end of previous token and next aligned position
1060 * for length descriptor.
1062 if (buf_chunk_avail(chunk
) - pad
< sizeof(buffer
.cur
->len
)) {
1064 chunk
->next
= buf_chunk_new();
1068 buffer
.cur
= (struct buf_token
*)(buffer
.cur
->data
+
1069 LEN_ALIGN(buffer
.cur
->len
));
1070 buffer
.cur
->len
= 0;
1071 buffer
.tail
->end
= buffer
.cur
->data
;
1074 static int field_is_last(struct column
*f
)
1076 return f
- columns
== COL_MAX
- 1;
1079 static void field_next(void)
1081 field_flush(current_field
);
1083 if (field_is_last(current_field
))
1084 current_field
= columns
;
1089 /* Walk through fields and flush them until we reach the desired one */
1090 static void field_set(enum col_id id
)
1092 while (id
!= current_field
- columns
)
1096 /* Print header for all non-empty columns */
1097 static void print_header(void)
1099 while (!field_is_last(current_field
)) {
1100 if (!current_field
->disabled
)
1101 out("%s", current_field
->header
);
1106 /* Get the next available token in the buffer starting from the current token */
1107 static struct buf_token
*buf_token_next(struct buf_token
*cur
)
1109 struct buf_chunk
*chunk
= buffer
.tail
;
1111 /* If we reached the end of chunk contents, get token from next chunk */
1112 if (cur
->data
+ LEN_ALIGN(cur
->len
) == chunk
->end
) {
1113 buffer
.tail
= chunk
= chunk
->next
;
1114 return chunk
? (struct buf_token
*)chunk
->data
: NULL
;
1117 return (struct buf_token
*)(cur
->data
+ LEN_ALIGN(cur
->len
));
1120 /* Free up all allocated buffer chunks */
1121 static void buf_free_all(void)
1123 struct buf_chunk
*tmp
;
1125 for (buffer
.tail
= buffer
.head
; buffer
.tail
; ) {
1127 buffer
.tail
= buffer
.tail
->next
;
1133 /* Get current screen width, default to 80 columns if TIOCGWINSZ fails */
1134 static int render_screen_width(void)
1138 if (isatty(STDOUT_FILENO
)) {
1141 if (ioctl(STDOUT_FILENO
, TIOCGWINSZ
, &w
) != -1) {
1150 /* Calculate column width from contents length. If columns don't fit on one
1151 * line, break them into the least possible amount of lines and keep them
1152 * aligned across lines. Available screen space is equally spread between fields
1153 * as additional spacing.
1155 static void render_calc_width(void)
1157 int screen_width
= render_screen_width();
1158 struct column
*c
, *eol
= columns
- 1;
1159 int first
, len
= 0, linecols
= 0;
1161 /* First pass: set width for each column to measured content length */
1162 for (first
= 1, c
= columns
; c
- columns
< COL_MAX
; c
++) {
1166 if (!first
&& c
->max_len
)
1167 c
->width
= c
->max_len
+ strlen(c
->ldelim
);
1169 c
->width
= c
->max_len
;
1171 /* But don't exceed screen size. If we exceed the screen size
1172 * for even a single field, it will just start on a line of its
1173 * own and then naturally wrap.
1175 c
->width
= min(c
->width
, screen_width
);
1181 /* Second pass: find out newlines and distribute available spacing */
1182 for (c
= columns
; c
- columns
< COL_MAX
; c
++) {
1183 int pad
, spacing
, rem
, last
;
1192 for (last
= 1, tmp
= c
+ 1; tmp
- columns
< COL_MAX
; tmp
++) {
1199 if (!last
&& len
< screen_width
) {
1200 /* Columns fit on screen so far, nothing to do yet */
1204 if (len
== screen_width
) {
1205 /* Exact fit, just start with new line */
1209 if (len
> screen_width
) {
1210 /* Screen width exceeded: go back one column */
1216 /* Distribute remaining space to columns on this line */
1217 pad
= screen_width
- len
;
1218 spacing
= pad
/ linecols
;
1219 rem
= pad
% linecols
;
1220 for (tmp
= c
; tmp
> eol
; tmp
--) {
1224 tmp
->width
+= spacing
;
1232 /* Line break: reset line counters, mark end-of-line */
1239 /* Render buffered output with spacing and delimiters, then free up buffers */
1240 static void render(void)
1242 struct buf_token
*token
;
1243 int printed
, line_started
= 0;
1249 token
= (struct buf_token
*)buffer
.head
->data
;
1251 /* Ensure end alignment of last token, it wasn't necessarily flushed */
1252 buffer
.tail
->end
+= buffer
.cur
->len
% 2;
1254 render_calc_width();
1256 /* Rewind and replay */
1257 buffer
.tail
= buffer
.head
;
1264 /* Print left delimiter only if we already started a line */
1266 printed
= printf("%s", f
->ldelim
);
1270 /* Print field content from token data with spacing */
1271 printed
+= print_left_spacing(f
, token
->len
, printed
);
1272 printed
+= fwrite(token
->data
, 1, token
->len
, stdout
);
1273 print_right_spacing(f
, printed
);
1275 /* Go to next non-empty field, deal with end-of-line */
1277 if (field_is_last(f
)) {
1284 } while (f
->disabled
);
1286 token
= buf_token_next(token
);
1290 current_field
= columns
;
1293 static void sock_state_print(struct sockstat
*s
)
1295 const char *sock_name
;
1296 static const char * const sstate_name
[] = {
1298 [SS_ESTABLISHED
] = "ESTAB",
1299 [SS_SYN_SENT
] = "SYN-SENT",
1300 [SS_SYN_RECV
] = "SYN-RECV",
1301 [SS_FIN_WAIT1
] = "FIN-WAIT-1",
1302 [SS_FIN_WAIT2
] = "FIN-WAIT-2",
1303 [SS_TIME_WAIT
] = "TIME-WAIT",
1304 [SS_CLOSE
] = "UNCONN",
1305 [SS_CLOSE_WAIT
] = "CLOSE-WAIT",
1306 [SS_LAST_ACK
] = "LAST-ACK",
1307 [SS_LISTEN
] = "LISTEN",
1308 [SS_CLOSING
] = "CLOSING",
1311 switch (s
->local
.family
) {
1313 sock_name
= unix_netid_name(s
->type
);
1317 sock_name
= proto_name(s
->type
);
1320 sock_name
= s
->type
== SOCK_RAW
? "p_raw" : "p_dgr";
1326 sock_name
= tipc_netid_name(s
->type
);
1329 sock_name
= vsock_netid_name(s
->type
);
1332 sock_name
= "unknown";
1335 if (is_sctp_assoc(s
, sock_name
)) {
1336 field_set(COL_STATE
); /* Empty Netid field */
1337 out("`- %s", sctp_sstate_name
[s
->state
]);
1339 field_set(COL_NETID
);
1340 out("%s", sock_name
);
1341 field_set(COL_STATE
);
1342 out("%s", sstate_name
[s
->state
]);
1345 field_set(COL_RECVQ
);
1347 field_set(COL_SENDQ
);
1349 field_set(COL_ADDR
);
1352 static void sock_details_print(struct sockstat
*s
)
1355 out(" uid:%u", s
->uid
);
1357 out(" ino:%u", s
->ino
);
1358 out(" sk:%llx", s
->sk
);
1361 out(" fwmark:0x%x", s
->mark
);
1364 static void sock_addr_print(const char *addr
, char *delim
, const char *port
,
1368 out("%s" "%%" "%s%s", addr
, ifname
, delim
);
1370 out("%s%s", addr
, delim
);
1377 static const char *print_ms_timer(unsigned int timeout
)
1379 static char buf
[64];
1380 int secs
, msecs
, minutes
;
1382 secs
= timeout
/1000;
1385 msecs
= timeout
%1000;
1389 snprintf(buf
, sizeof(buf
)-16, "%dmin", minutes
);
1396 sprintf(buf
+strlen(buf
), "%d%s", secs
, msecs
? "." : "sec");
1399 sprintf(buf
+strlen(buf
), "%03dms", msecs
);
1404 struct scache
*next
;
1410 struct scache
*rlist
;
1412 static void init_service_resolver(void)
1415 FILE *fp
= popen("/usr/sbin/rpcinfo -p 2>/dev/null", "r");
1420 if (!fgets(buf
, sizeof(buf
), fp
)) {
1424 while (fgets(buf
, sizeof(buf
), fp
) != NULL
) {
1425 unsigned int progn
, port
;
1426 char proto
[128], prog
[128] = "rpc.";
1429 if (sscanf(buf
, "%u %*d %s %u %s",
1430 &progn
, proto
, &port
, prog
+4) != 4)
1433 if (!(c
= malloc(sizeof(*c
))))
1437 c
->name
= strdup(prog
);
1438 if (strcmp(proto
, TCP_PROTO
) == 0)
1439 c
->proto
= TCP_PROTO
;
1440 else if (strcmp(proto
, UDP_PROTO
) == 0)
1441 c
->proto
= UDP_PROTO
;
1442 else if (strcmp(proto
, SCTP_PROTO
) == 0)
1443 c
->proto
= SCTP_PROTO
;
1452 /* Even do not try default linux ephemeral port ranges:
1453 * default /etc/services contains so much of useless crap
1454 * wouldbe "allocated" to this area that resolution
1455 * is really harmful. I shrug each time when seeing
1456 * "socks" or "cfinger" in dumps.
1458 static int is_ephemeral(int port
)
1460 static int min
= 0, max
;
1463 FILE *f
= ephemeral_ports_open();
1465 if (!f
|| fscanf(f
, "%d %d", &min
, &max
) < 2) {
1472 return port
>= min
&& port
<= max
;
1476 static const char *__resolve_service(int port
)
1480 for (c
= rlist
; c
; c
= c
->next
) {
1481 if (c
->port
== port
&& c
->proto
== dg_proto
)
1485 if (!is_ephemeral(port
)) {
1486 static int notfirst
;
1493 se
= getservbyport(htons(port
), dg_proto
);
1501 #define SCACHE_BUCKETS 1024
1502 static struct scache
*cache_htab
[SCACHE_BUCKETS
];
1504 static const char *resolve_service(int port
)
1506 static char buf
[128];
1517 if (!resolve_services
)
1520 if (dg_proto
== RAW_PROTO
)
1521 return inet_proto_n2a(port
, buf
, sizeof(buf
));
1524 hash
= (port
^(((unsigned long)dg_proto
)>>2)) % SCACHE_BUCKETS
;
1526 for (c
= cache_htab
[hash
]; c
; c
= c
->next
) {
1527 if (c
->port
== port
&& c
->proto
== dg_proto
)
1531 c
= malloc(sizeof(*c
));
1534 res
= __resolve_service(port
);
1536 c
->name
= res
? strdup(res
) : NULL
;
1537 c
->proto
= dg_proto
;
1538 c
->next
= cache_htab
[hash
];
1539 cache_htab
[hash
] = c
;
1546 sprintf(buf
, "%u", port
);
1550 static void inet_addr_print(const inet_prefix
*a
, int port
,
1551 unsigned int ifindex
, bool v6only
)
1554 const char *ap
= buf
;
1555 const char *ifname
= NULL
;
1557 if (a
->family
== AF_INET
) {
1558 ap
= format_host(AF_INET
, 4, a
->data
);
1561 !memcmp(a
->data
, &in6addr_any
, sizeof(in6addr_any
))) {
1565 ap
= format_host(a
->family
, 16, a
->data
);
1567 /* Numeric IPv6 addresses should be bracketed */
1568 if (strchr(ap
, ':')) {
1569 snprintf(buf
, sizeof(buf
),
1577 ifname
= ll_index_to_name(ifindex
);
1579 sock_addr_print(ap
, ":", resolve_service(port
), ifname
);
1588 struct aafilter
*next
;
1591 static int inet2_addr_match(const inet_prefix
*a
, const inet_prefix
*p
,
1594 if (!inet_addr_match(a
, p
, plen
))
1597 /* Cursed "v4 mapped" addresses: v4 mapped socket matches
1598 * pure IPv4 rule, but v4-mapped rule selects only v4-mapped
1600 if (p
->family
== AF_INET
&& a
->family
== AF_INET6
) {
1601 if (a
->data
[0] == 0 && a
->data
[1] == 0 &&
1602 a
->data
[2] == htonl(0xffff)) {
1603 inet_prefix tmp
= *a
;
1605 tmp
.data
[0] = a
->data
[3];
1606 return inet_addr_match(&tmp
, p
, plen
);
1612 static int unix_match(const inet_prefix
*a
, const inet_prefix
*p
)
1614 char *addr
, *pattern
;
1616 memcpy(&addr
, a
->data
, sizeof(addr
));
1617 memcpy(&pattern
, p
->data
, sizeof(pattern
));
1618 if (pattern
== NULL
)
1622 return !fnmatch(pattern
, addr
, 0);
1625 static int run_ssfilter(struct ssfilter
*f
, struct sockstat
*s
)
1630 if (s
->local
.family
== AF_UNIX
) {
1633 memcpy(&p
, s
->local
.data
, sizeof(p
));
1634 return p
== NULL
|| (p
[0] == '@' && strlen(p
) == 6 &&
1635 strspn(p
+1, "0123456789abcdef") == 5);
1637 if (s
->local
.family
== AF_PACKET
)
1638 return s
->lport
== 0 && s
->local
.data
[0] == 0;
1639 if (s
->local
.family
== AF_NETLINK
)
1640 return s
->lport
< 0;
1641 if (s
->local
.family
== AF_VSOCK
)
1642 return s
->lport
> 1023;
1644 return is_ephemeral(s
->lport
);
1648 struct aafilter
*a
= (void *)f
->pred
;
1650 if (a
->addr
.family
== AF_UNIX
)
1651 return unix_match(&s
->remote
, &a
->addr
);
1652 if (a
->port
!= -1 && a
->port
!= s
->rport
)
1654 if (a
->addr
.bitlen
) {
1656 if (!inet2_addr_match(&s
->remote
, &a
->addr
, a
->addr
.bitlen
))
1658 } while ((a
= a
->next
) != NULL
);
1665 struct aafilter
*a
= (void *)f
->pred
;
1667 if (a
->addr
.family
== AF_UNIX
)
1668 return unix_match(&s
->local
, &a
->addr
);
1669 if (a
->port
!= -1 && a
->port
!= s
->lport
)
1671 if (a
->addr
.bitlen
) {
1673 if (!inet2_addr_match(&s
->local
, &a
->addr
, a
->addr
.bitlen
))
1675 } while ((a
= a
->next
) != NULL
);
1682 struct aafilter
*a
= (void *)f
->pred
;
1684 return s
->rport
>= a
->port
;
1688 struct aafilter
*a
= (void *)f
->pred
;
1690 return s
->rport
<= a
->port
;
1694 struct aafilter
*a
= (void *)f
->pred
;
1696 return s
->lport
>= a
->port
;
1700 struct aafilter
*a
= (void *)f
->pred
;
1702 return s
->lport
<= a
->port
;
1706 struct aafilter
*a
= (void *)f
->pred
;
1708 return s
->iface
== a
->iface
;
1712 struct aafilter
*a
= (void *)f
->pred
;
1714 return (s
->mark
& a
->mask
) == a
->mark
;
1716 /* Yup. It is recursion. Sorry. */
1718 return run_ssfilter(f
->pred
, s
) && run_ssfilter(f
->post
, s
);
1720 return run_ssfilter(f
->pred
, s
) || run_ssfilter(f
->post
, s
);
1722 return !run_ssfilter(f
->pred
, s
);
1728 /* Relocate external jumps by reloc. */
1729 static void ssfilter_patch(char *a
, int len
, int reloc
)
1732 struct inet_diag_bc_op
*op
= (struct inet_diag_bc_op
*)a
;
1734 if (op
->no
== len
+4)
1743 static int ssfilter_bytecompile(struct ssfilter
*f
, char **bytecode
)
1748 if (!(*bytecode
= malloc(4))) abort();
1749 ((struct inet_diag_bc_op
*)*bytecode
)[0] = (struct inet_diag_bc_op
){ INET_DIAG_BC_AUTO
, 4, 8 };
1755 struct aafilter
*a
= (void *)f
->pred
;
1758 int code
= (f
->type
== SSF_DCOND
? INET_DIAG_BC_D_COND
: INET_DIAG_BC_S_COND
);
1761 for (b
= a
; b
; b
= b
->next
) {
1762 len
+= 4 + sizeof(struct inet_diag_hostcond
);
1763 if (a
->addr
.family
== AF_INET6
)
1770 if (!(ptr
= malloc(len
))) abort();
1772 for (b
= a
; b
; b
= b
->next
) {
1773 struct inet_diag_bc_op
*op
= (struct inet_diag_bc_op
*)ptr
;
1774 int alen
= (a
->addr
.family
== AF_INET6
? 16 : 4);
1775 int oplen
= alen
+ 4 + sizeof(struct inet_diag_hostcond
);
1776 struct inet_diag_hostcond
*cond
= (struct inet_diag_hostcond
*)(ptr
+4);
1778 *op
= (struct inet_diag_bc_op
){ code
, oplen
, oplen
+4 };
1779 cond
->family
= a
->addr
.family
;
1780 cond
->port
= a
->port
;
1781 cond
->prefix_len
= a
->addr
.bitlen
;
1782 memcpy(cond
->addr
, a
->addr
.data
, alen
);
1785 op
= (struct inet_diag_bc_op
*)ptr
;
1786 *op
= (struct inet_diag_bc_op
){ INET_DIAG_BC_JMP
, 4, len
- (ptr
-*bytecode
)};
1790 return ptr
- *bytecode
;
1794 struct aafilter
*x
= (void *)f
->pred
;
1796 if (!(*bytecode
= malloc(8))) abort();
1797 ((struct inet_diag_bc_op
*)*bytecode
)[0] = (struct inet_diag_bc_op
){ INET_DIAG_BC_D_GE
, 8, 12 };
1798 ((struct inet_diag_bc_op
*)*bytecode
)[1] = (struct inet_diag_bc_op
){ 0, 0, x
->port
};
1803 struct aafilter
*x
= (void *)f
->pred
;
1805 if (!(*bytecode
= malloc(8))) abort();
1806 ((struct inet_diag_bc_op
*)*bytecode
)[0] = (struct inet_diag_bc_op
){ INET_DIAG_BC_D_LE
, 8, 12 };
1807 ((struct inet_diag_bc_op
*)*bytecode
)[1] = (struct inet_diag_bc_op
){ 0, 0, x
->port
};
1812 struct aafilter
*x
= (void *)f
->pred
;
1814 if (!(*bytecode
= malloc(8))) abort();
1815 ((struct inet_diag_bc_op
*)*bytecode
)[0] = (struct inet_diag_bc_op
){ INET_DIAG_BC_S_GE
, 8, 12 };
1816 ((struct inet_diag_bc_op
*)*bytecode
)[1] = (struct inet_diag_bc_op
){ 0, 0, x
->port
};
1821 struct aafilter
*x
= (void *)f
->pred
;
1823 if (!(*bytecode
= malloc(8))) abort();
1824 ((struct inet_diag_bc_op
*)*bytecode
)[0] = (struct inet_diag_bc_op
){ INET_DIAG_BC_S_LE
, 8, 12 };
1825 ((struct inet_diag_bc_op
*)*bytecode
)[1] = (struct inet_diag_bc_op
){ 0, 0, x
->port
};
1831 char *a1
= NULL
, *a2
= NULL
, *a
;
1834 l1
= ssfilter_bytecompile(f
->pred
, &a1
);
1835 l2
= ssfilter_bytecompile(f
->post
, &a2
);
1841 if (!(a
= malloc(l1
+l2
))) abort();
1843 memcpy(a
+l1
, a2
, l2
);
1845 ssfilter_patch(a
, l1
, l2
);
1851 char *a1
= NULL
, *a2
= NULL
, *a
;
1854 l1
= ssfilter_bytecompile(f
->pred
, &a1
);
1855 l2
= ssfilter_bytecompile(f
->post
, &a2
);
1861 if (!(a
= malloc(l1
+l2
+4))) abort();
1863 memcpy(a
+l1
+4, a2
, l2
);
1865 *(struct inet_diag_bc_op
*)(a
+l1
) = (struct inet_diag_bc_op
){ INET_DIAG_BC_JMP
, 4, l2
+4 };
1871 char *a1
= NULL
, *a
;
1874 l1
= ssfilter_bytecompile(f
->pred
, &a1
);
1879 if (!(a
= malloc(l1
+4))) abort();
1882 *(struct inet_diag_bc_op
*)(a
+l1
) = (struct inet_diag_bc_op
){ INET_DIAG_BC_JMP
, 4, 8 };
1888 /* bytecompile for SSF_DEVCOND not supported yet */
1893 struct aafilter
*a
= (void *)f
->pred
;
1895 struct inet_diag_bc_op op
;
1896 struct inet_diag_markcond cond
;
1898 int inslen
= sizeof(struct instr
);
1900 if (!(*bytecode
= malloc(inslen
))) abort();
1901 ((struct instr
*)*bytecode
)[0] = (struct instr
) {
1902 { INET_DIAG_BC_MARK_COND
, inslen
, inslen
+ 4 },
1903 { a
->mark
, a
->mask
},
1913 static int remember_he(struct aafilter
*a
, struct hostent
*he
)
1915 char **ptr
= he
->h_addr_list
;
1919 if (he
->h_addrtype
== AF_INET
)
1921 else if (he
->h_addrtype
== AF_INET6
)
1927 struct aafilter
*b
= a
;
1929 if (a
->addr
.bitlen
) {
1930 if ((b
= malloc(sizeof(*b
))) == NULL
)
1935 memcpy(b
->addr
.data
, *ptr
, len
);
1936 b
->addr
.bytelen
= len
;
1937 b
->addr
.bitlen
= len
*8;
1938 b
->addr
.family
= he
->h_addrtype
;
1945 static int get_dns_host(struct aafilter
*a
, const char *addr
, int fam
)
1947 static int notfirst
;
1956 he
= gethostbyname2(addr
, fam
== AF_UNSPEC
? AF_INET
: fam
);
1958 cnt
= remember_he(a
, he
);
1959 if (fam
== AF_UNSPEC
) {
1960 he
= gethostbyname2(addr
, AF_INET6
);
1962 cnt
+= remember_he(a
, he
);
1967 static int xll_initted
;
1969 static void xll_init(void)
1971 struct rtnl_handle rth
;
1973 if (rtnl_open(&rth
, 0) < 0)
1981 static const char *xll_index_to_name(int index
)
1985 return ll_index_to_name(index
);
1988 static int xll_name_to_index(const char *dev
)
1992 return ll_name_to_index(dev
);
1995 void *parse_devcond(char *name
)
1997 struct aafilter a
= { .iface
= 0 };
1998 struct aafilter
*res
;
2000 a
.iface
= xll_name_to_index(name
);
2005 n
= strtoul(name
, &end
, 0);
2006 if (!end
|| end
== name
|| *end
|| n
> UINT_MAX
)
2012 res
= malloc(sizeof(*res
));
2018 static void vsock_set_inet_prefix(inet_prefix
*a
, __u32 cid
)
2021 .bytelen
= sizeof(cid
),
2024 memcpy(a
->data
, &cid
, sizeof(cid
));
2027 void *parse_hostcond(char *addr
, bool is_port
)
2030 struct aafilter a
= { .port
= -1 };
2031 struct aafilter
*res
;
2032 int fam
= preferred_family
;
2033 struct filter
*f
= ¤t_filter
;
2035 if (fam
== AF_UNIX
|| strncmp(addr
, "unix:", 5) == 0) {
2038 a
.addr
.family
= AF_UNIX
;
2039 if (strncmp(addr
, "unix:", 5) == 0)
2042 a
.addr
.bitlen
= 8*strlen(p
);
2043 memcpy(a
.addr
.data
, &p
, sizeof(p
));
2048 if (fam
== AF_PACKET
|| strncmp(addr
, "link:", 5) == 0) {
2049 a
.addr
.family
= AF_PACKET
;
2051 if (strncmp(addr
, "link:", 5) == 0)
2053 port
= strchr(addr
, ':');
2056 if (port
[1] && strcmp(port
+1, "*")) {
2057 if (get_integer(&a
.port
, port
+1, 0)) {
2058 if ((a
.port
= xll_name_to_index(port
+1)) <= 0)
2063 if (addr
[0] && strcmp(addr
, "*")) {
2067 if (ll_proto_a2n(&tmp
, addr
))
2069 a
.addr
.data
[0] = ntohs(tmp
);
2075 if (fam
== AF_NETLINK
|| strncmp(addr
, "netlink:", 8) == 0) {
2076 a
.addr
.family
= AF_NETLINK
;
2078 if (strncmp(addr
, "netlink:", 8) == 0)
2080 port
= strchr(addr
, ':');
2083 if (port
[1] && strcmp(port
+1, "*")) {
2084 if (get_integer(&a
.port
, port
+1, 0)) {
2085 if (strcmp(port
+1, "kernel") == 0)
2092 if (addr
[0] && strcmp(addr
, "*")) {
2094 if (nl_proto_a2n(&a
.addr
.data
[0], addr
) == -1)
2101 if (fam
== AF_VSOCK
|| strncmp(addr
, "vsock:", 6) == 0) {
2102 __u32 cid
= ~(__u32
)0;
2104 a
.addr
.family
= AF_VSOCK
;
2105 if (strncmp(addr
, "vsock:", 6) == 0)
2111 port
= strchr(addr
, ':');
2118 if (port
&& strcmp(port
, "*") &&
2119 get_u32((__u32
*)&a
.port
, port
, 0))
2122 if (addr
[0] && strcmp(addr
, "*")) {
2124 if (get_u32(&cid
, addr
, 0))
2127 vsock_set_inet_prefix(&a
.addr
, cid
);
2132 if (fam
== AF_INET
|| !strncmp(addr
, "inet:", 5)) {
2134 if (!strncmp(addr
, "inet:", 5))
2136 } else if (fam
== AF_INET6
|| !strncmp(addr
, "inet6:", 6)) {
2138 if (!strncmp(addr
, "inet6:", 6))
2142 /* URL-like literal [] */
2143 if (addr
[0] == '[') {
2145 if ((port
= strchr(addr
, ']')) == NULL
)
2148 } else if (addr
[0] == '*') {
2151 port
= strrchr(strchr(addr
, '/') ? : addr
, ':');
2157 if (port
&& *port
) {
2161 if (*port
&& *port
!= '*') {
2162 if (get_integer(&a
.port
, port
, 0)) {
2163 struct servent
*se1
= NULL
;
2164 struct servent
*se2
= NULL
;
2166 if (current_filter
.dbs
&(1<<UDP_DB
))
2167 se1
= getservbyname(port
, UDP_PROTO
);
2168 if (current_filter
.dbs
&(1<<TCP_DB
))
2169 se2
= getservbyname(port
, TCP_PROTO
);
2170 if (se1
&& se2
&& se1
->s_port
!= se2
->s_port
) {
2171 fprintf(stderr
, "Error: ambiguous port \"%s\".\n", port
);
2177 a
.port
= ntohs(se1
->s_port
);
2181 for (s
= rlist
; s
; s
= s
->next
) {
2182 if ((s
->proto
== UDP_PROTO
&&
2183 (current_filter
.dbs
&(1<<UDP_DB
))) ||
2184 (s
->proto
== TCP_PROTO
&&
2185 (current_filter
.dbs
&(1<<TCP_DB
)))) {
2186 if (s
->name
&& strcmp(s
->name
, port
) == 0) {
2187 if (a
.port
> 0 && a
.port
!= s
->port
) {
2188 fprintf(stderr
, "Error: ambiguous port \"%s\".\n", port
);
2196 fprintf(stderr
, "Error: \"%s\" does not look like a port.\n", port
);
2203 if (!is_port
&& *addr
&& *addr
!= '*') {
2204 if (get_prefix_1(&a
.addr
, addr
, fam
)) {
2205 if (get_dns_host(&a
, addr
, fam
)) {
2206 fprintf(stderr
, "Error: an inet prefix is expected rather than \"%s\".\n", addr
);
2213 if (fam
!= AF_UNSPEC
) {
2214 int states
= f
->states
;
2216 filter_af_set(f
, fam
);
2217 filter_states_set(f
, states
);
2220 res
= malloc(sizeof(*res
));
2222 memcpy(res
, &a
, sizeof(a
));
2226 void *parse_markmask(const char *markmask
)
2228 struct aafilter a
, *res
;
2230 if (strchr(markmask
, '/')) {
2231 if (sscanf(markmask
, "%i/%i", &a
.mark
, &a
.mask
) != 2)
2234 a
.mask
= 0xffffffff;
2235 if (sscanf(markmask
, "%i", &a
.mark
) != 1)
2239 res
= malloc(sizeof(*res
));
2241 memcpy(res
, &a
, sizeof(a
));
2245 static void proc_ctx_print(struct sockstat
*s
)
2249 if (show_proc_ctx
|| show_sock_ctx
) {
2250 if (find_entry(s
->ino
, &buf
,
2251 (show_proc_ctx
& show_sock_ctx
) ?
2252 PROC_SOCK_CTX
: PROC_CTX
) > 0) {
2253 out(" users:(%s)", buf
);
2256 } else if (show_users
) {
2257 if (find_entry(s
->ino
, &buf
, USERS
) > 0) {
2258 out(" users:(%s)", buf
);
2264 static void inet_stats_print(struct sockstat
*s
, bool v6only
)
2266 sock_state_print(s
);
2268 inet_addr_print(&s
->local
, s
->lport
, s
->iface
, v6only
);
2269 inet_addr_print(&s
->remote
, s
->rport
, 0, v6only
);
2274 static int proc_parse_inet_addr(char *loc
, char *rem
, int family
, struct
2277 s
->local
.family
= s
->remote
.family
= family
;
2278 if (family
== AF_INET
) {
2279 sscanf(loc
, "%x:%x", s
->local
.data
, (unsigned *)&s
->lport
);
2280 sscanf(rem
, "%x:%x", s
->remote
.data
, (unsigned *)&s
->rport
);
2281 s
->local
.bytelen
= s
->remote
.bytelen
= 4;
2284 sscanf(loc
, "%08x%08x%08x%08x:%x",
2290 sscanf(rem
, "%08x%08x%08x%08x:%x",
2296 s
->local
.bytelen
= s
->remote
.bytelen
= 16;
2302 static int proc_inet_split_line(char *line
, char **loc
, char **rem
, char **data
)
2306 if ((p
= strchr(line
, ':')) == NULL
)
2310 if ((p
= strchr(*loc
, ':')) == NULL
)
2315 if ((p
= strchr(*rem
, ':')) == NULL
)
2323 static char *sprint_bw(char *buf
, double bw
)
2326 sprintf(buf
, "%.1fM", bw
/ 1000000.);
2327 else if (bw
> 1000.)
2328 sprintf(buf
, "%.1fK", bw
/ 1000.);
2330 sprintf(buf
, "%g", bw
);
2335 static void sctp_stats_print(struct sctp_info
*s
)
2338 out(" tag:%x", s
->sctpi_tag
);
2340 out(" state:%s", sctp_sstate_name
[s
->sctpi_state
]);
2342 out(" rwnd:%d", s
->sctpi_rwnd
);
2343 if (s
->sctpi_unackdata
)
2344 out(" unackdata:%d", s
->sctpi_unackdata
);
2345 if (s
->sctpi_penddata
)
2346 out(" penddata:%d", s
->sctpi_penddata
);
2347 if (s
->sctpi_instrms
)
2348 out(" instrms:%d", s
->sctpi_instrms
);
2349 if (s
->sctpi_outstrms
)
2350 out(" outstrms:%d", s
->sctpi_outstrms
);
2351 if (s
->sctpi_inqueue
)
2352 out(" inqueue:%d", s
->sctpi_inqueue
);
2353 if (s
->sctpi_outqueue
)
2354 out(" outqueue:%d", s
->sctpi_outqueue
);
2355 if (s
->sctpi_overall_error
)
2356 out(" overerr:%d", s
->sctpi_overall_error
);
2357 if (s
->sctpi_max_burst
)
2358 out(" maxburst:%d", s
->sctpi_max_burst
);
2359 if (s
->sctpi_maxseg
)
2360 out(" maxseg:%d", s
->sctpi_maxseg
);
2361 if (s
->sctpi_peer_rwnd
)
2362 out(" prwnd:%d", s
->sctpi_peer_rwnd
);
2363 if (s
->sctpi_peer_tag
)
2364 out(" ptag:%x", s
->sctpi_peer_tag
);
2365 if (s
->sctpi_peer_capable
)
2366 out(" pcapable:%d", s
->sctpi_peer_capable
);
2367 if (s
->sctpi_peer_sack
)
2368 out(" psack:%d", s
->sctpi_peer_sack
);
2369 if (s
->sctpi_s_autoclose
)
2370 out(" autoclose:%d", s
->sctpi_s_autoclose
);
2371 if (s
->sctpi_s_adaptation_ind
)
2372 out(" adapind:%d", s
->sctpi_s_adaptation_ind
);
2373 if (s
->sctpi_s_pd_point
)
2374 out(" pdpoint:%d", s
->sctpi_s_pd_point
);
2375 if (s
->sctpi_s_nodelay
)
2376 out(" nodealy:%d", s
->sctpi_s_nodelay
);
2377 if (s
->sctpi_s_disable_fragments
)
2378 out(" nofrag:%d", s
->sctpi_s_disable_fragments
);
2379 if (s
->sctpi_s_v4mapped
)
2380 out(" v4mapped:%d", s
->sctpi_s_v4mapped
);
2381 if (s
->sctpi_s_frag_interleave
)
2382 out(" fraginl:%d", s
->sctpi_s_frag_interleave
);
2385 static void tcp_stats_print(struct tcpstat
*s
)
2391 if (s
->has_sack_opt
)
2395 if (s
->has_ecnseen_opt
)
2397 if (s
->has_fastopen_opt
)
2400 out(" %s", s
->cong_alg
);
2401 if (s
->has_wscale_opt
)
2402 out(" wscale:%d,%d", s
->snd_wscale
, s
->rcv_wscale
);
2404 out(" rto:%g", s
->rto
);
2406 out(" backoff:%u", s
->backoff
);
2408 out(" rtt:%g/%g", s
->rtt
, s
->rttvar
);
2410 out(" ato:%g", s
->ato
);
2413 out(" qack:%d", s
->qack
);
2418 out(" mss:%d", s
->mss
);
2420 out(" pmtu:%u", s
->pmtu
);
2422 out(" rcvmss:%d", s
->rcv_mss
);
2424 out(" advmss:%d", s
->advmss
);
2426 out(" cwnd:%u", s
->cwnd
);
2428 out(" ssthresh:%d", s
->ssthresh
);
2431 out(" bytes_acked:%llu", s
->bytes_acked
);
2432 if (s
->bytes_received
)
2433 out(" bytes_received:%llu", s
->bytes_received
);
2435 out(" segs_out:%u", s
->segs_out
);
2437 out(" segs_in:%u", s
->segs_in
);
2438 if (s
->data_segs_out
)
2439 out(" data_segs_out:%u", s
->data_segs_out
);
2440 if (s
->data_segs_in
)
2441 out(" data_segs_in:%u", s
->data_segs_in
);
2443 if (s
->dctcp
&& s
->dctcp
->enabled
) {
2444 struct dctcpstat
*dctcp
= s
->dctcp
;
2446 out(" dctcp:(ce_state:%u,alpha:%u,ab_ecn:%u,ab_tot:%u)",
2447 dctcp
->ce_state
, dctcp
->alpha
, dctcp
->ab_ecn
,
2449 } else if (s
->dctcp
) {
2450 out(" dctcp:fallback_mode");
2456 bw
= s
->bbr_info
->bbr_bw_hi
;
2458 bw
|= s
->bbr_info
->bbr_bw_lo
;
2460 out(" bbr:(bw:%sbps,mrtt:%g",
2461 sprint_bw(b1
, bw
* 8.0),
2462 (double)s
->bbr_info
->bbr_min_rtt
/ 1000.0);
2463 if (s
->bbr_info
->bbr_pacing_gain
)
2464 out(",pacing_gain:%g",
2465 (double)s
->bbr_info
->bbr_pacing_gain
/ 256.0);
2466 if (s
->bbr_info
->bbr_cwnd_gain
)
2467 out(",cwnd_gain:%g",
2468 (double)s
->bbr_info
->bbr_cwnd_gain
/ 256.0);
2473 out(" send %sbps", sprint_bw(b1
, s
->send_bps
));
2475 out(" lastsnd:%u", s
->lastsnd
);
2477 out(" lastrcv:%u", s
->lastrcv
);
2479 out(" lastack:%u", s
->lastack
);
2481 if (s
->pacing_rate
) {
2482 out(" pacing_rate %sbps", sprint_bw(b1
, s
->pacing_rate
));
2483 if (s
->pacing_rate_max
)
2484 out("/%sbps", sprint_bw(b1
, s
->pacing_rate_max
));
2487 if (s
->delivery_rate
)
2488 out(" delivery_rate %sbps", sprint_bw(b1
, s
->delivery_rate
));
2490 out(" app_limited");
2493 out(" busy:%llums", s
->busy_time
/ 1000);
2494 if (s
->rwnd_limited
)
2495 out(" rwnd_limited:%llums(%.1f%%)",
2496 s
->rwnd_limited
/ 1000,
2497 100.0 * s
->rwnd_limited
/ s
->busy_time
);
2498 if (s
->sndbuf_limited
)
2499 out(" sndbuf_limited:%llums(%.1f%%)",
2500 s
->sndbuf_limited
/ 1000,
2501 100.0 * s
->sndbuf_limited
/ s
->busy_time
);
2505 out(" unacked:%u", s
->unacked
);
2506 if (s
->retrans
|| s
->retrans_total
)
2507 out(" retrans:%u/%u", s
->retrans
, s
->retrans_total
);
2509 out(" lost:%u", s
->lost
);
2510 if (s
->sacked
&& s
->ss
.state
!= SS_LISTEN
)
2511 out(" sacked:%u", s
->sacked
);
2513 out(" fackets:%u", s
->fackets
);
2514 if (s
->reordering
!= 3)
2515 out(" reordering:%d", s
->reordering
);
2517 out(" rcv_rtt:%g", s
->rcv_rtt
);
2519 out(" rcv_space:%d", s
->rcv_space
);
2520 if (s
->rcv_ssthresh
)
2521 out(" rcv_ssthresh:%u", s
->rcv_ssthresh
);
2523 out(" notsent:%u", s
->not_sent
);
2525 out(" minrtt:%g", s
->min_rtt
);
2528 static void tcp_timer_print(struct tcpstat
*s
)
2530 static const char * const tmr_name
[] = {
2542 out(" timer:(%s,%s,%d)",
2544 print_ms_timer(s
->timeout
),
2549 static void sctp_timer_print(struct tcpstat
*s
)
2552 out(" timer:(T3_RTX,%s,%d)",
2553 print_ms_timer(s
->timeout
), s
->retrans
);
2556 static int tcp_show_line(char *line
, const struct filter
*f
, int family
)
2558 int rto
= 0, ato
= 0;
2559 struct tcpstat s
= {};
2560 char *loc
, *rem
, *data
;
2563 int hz
= get_user_hz();
2565 if (proc_inet_split_line(line
, &loc
, &rem
, &data
))
2568 int state
= (data
[1] >= 'A') ? (data
[1] - 'A' + 10) : (data
[1] - '0');
2570 if (!(f
->states
& (1 << state
)))
2573 proc_parse_inet_addr(loc
, rem
, family
, &s
.ss
);
2575 if (f
->f
&& run_ssfilter(f
->f
, &s
.ss
) == 0)
2579 n
= sscanf(data
, "%x %x:%x %x:%x %x %d %d %u %d %llx %d %d %d %u %d %[^\n]\n",
2580 &s
.ss
.state
, &s
.ss
.wq
, &s
.ss
.rq
,
2581 &s
.timer
, &s
.timeout
, &s
.retrans
, &s
.ss
.uid
, &s
.probes
,
2582 &s
.ss
.ino
, &s
.ss
.refcnt
, &s
.ss
.sk
, &rto
, &ato
, &s
.qack
, &s
.cwnd
,
2595 s
.retrans
= s
.timer
!= 1 ? s
.probes
: s
.retrans
;
2596 s
.timeout
= (s
.timeout
* 1000 + hz
- 1) / hz
;
2597 s
.ato
= (double)ato
/ hz
;
2599 s
.rto
= (double)rto
;
2600 s
.ssthresh
= s
.ssthresh
== -1 ? 0 : s
.ssthresh
;
2601 s
.rto
= s
.rto
!= 3 * hz
? s
.rto
/ hz
: 0;
2602 s
.ss
.type
= IPPROTO_TCP
;
2604 inet_stats_print(&s
.ss
, false);
2607 tcp_timer_print(&s
);
2610 sock_details_print(&s
.ss
);
2612 out(" opt:\"%s\"", opt
);
2616 tcp_stats_print(&s
);
2621 static int generic_record_read(FILE *fp
,
2622 int (*worker
)(char*, const struct filter
*, int),
2623 const struct filter
*f
, int fam
)
2628 if (fgets(line
, sizeof(line
), fp
) == NULL
)
2631 while (fgets(line
, sizeof(line
), fp
) != NULL
) {
2632 int n
= strlen(line
);
2634 if (n
== 0 || line
[n
-1] != '\n') {
2640 if (worker(line
, f
, fam
) < 0)
2645 return ferror(fp
) ? -1 : 0;
2648 static void print_skmeminfo(struct rtattr
*tb
[], int attrtype
)
2650 const __u32
*skmeminfo
;
2652 if (!tb
[attrtype
]) {
2653 if (attrtype
== INET_DIAG_SKMEMINFO
) {
2654 if (!tb
[INET_DIAG_MEMINFO
])
2657 const struct inet_diag_meminfo
*minfo
=
2658 RTA_DATA(tb
[INET_DIAG_MEMINFO
]);
2660 out(" mem:(r%u,w%u,f%u,t%u)",
2669 skmeminfo
= RTA_DATA(tb
[attrtype
]);
2671 out(" skmem:(r%u,rb%u,t%u,tb%u,f%u,w%u,o%u",
2672 skmeminfo
[SK_MEMINFO_RMEM_ALLOC
],
2673 skmeminfo
[SK_MEMINFO_RCVBUF
],
2674 skmeminfo
[SK_MEMINFO_WMEM_ALLOC
],
2675 skmeminfo
[SK_MEMINFO_SNDBUF
],
2676 skmeminfo
[SK_MEMINFO_FWD_ALLOC
],
2677 skmeminfo
[SK_MEMINFO_WMEM_QUEUED
],
2678 skmeminfo
[SK_MEMINFO_OPTMEM
]);
2680 if (RTA_PAYLOAD(tb
[attrtype
]) >=
2681 (SK_MEMINFO_BACKLOG
+ 1) * sizeof(__u32
))
2682 out(",bl%u", skmeminfo
[SK_MEMINFO_BACKLOG
]);
2684 if (RTA_PAYLOAD(tb
[attrtype
]) >=
2685 (SK_MEMINFO_DROPS
+ 1) * sizeof(__u32
))
2686 out(",d%u", skmeminfo
[SK_MEMINFO_DROPS
]);
2691 static void print_md5sig(struct tcp_diag_md5sig
*sig
)
2694 format_host(sig
->tcpm_family
,
2695 sig
->tcpm_family
== AF_INET6
? 16 : 4,
2697 sig
->tcpm_prefixlen
);
2698 print_escape_buf(sig
->tcpm_key
, sig
->tcpm_keylen
, " ,");
2701 #define TCPI_HAS_OPT(info, opt) !!(info->tcpi_options & (opt))
2703 static void tcp_show_info(const struct nlmsghdr
*nlh
, struct inet_diag_msg
*r
,
2704 struct rtattr
*tb
[])
2707 struct tcpstat s
= {};
2709 s
.ss
.state
= r
->idiag_state
;
2711 print_skmeminfo(tb
, INET_DIAG_SKMEMINFO
);
2713 if (tb
[INET_DIAG_INFO
]) {
2714 struct tcp_info
*info
;
2715 int len
= RTA_PAYLOAD(tb
[INET_DIAG_INFO
]);
2717 /* workaround for older kernels with less fields */
2718 if (len
< sizeof(*info
)) {
2719 info
= alloca(sizeof(*info
));
2720 memcpy(info
, RTA_DATA(tb
[INET_DIAG_INFO
]), len
);
2721 memset((char *)info
+ len
, 0, sizeof(*info
) - len
);
2723 info
= RTA_DATA(tb
[INET_DIAG_INFO
]);
2726 s
.has_ts_opt
= TCPI_HAS_OPT(info
, TCPI_OPT_TIMESTAMPS
);
2727 s
.has_sack_opt
= TCPI_HAS_OPT(info
, TCPI_OPT_SACK
);
2728 s
.has_ecn_opt
= TCPI_HAS_OPT(info
, TCPI_OPT_ECN
);
2729 s
.has_ecnseen_opt
= TCPI_HAS_OPT(info
, TCPI_OPT_ECN_SEEN
);
2730 s
.has_fastopen_opt
= TCPI_HAS_OPT(info
, TCPI_OPT_SYN_DATA
);
2733 if (tb
[INET_DIAG_CONG
])
2735 rta_getattr_str(tb
[INET_DIAG_CONG
]),
2736 sizeof(s
.cong_alg
) - 1);
2738 if (TCPI_HAS_OPT(info
, TCPI_OPT_WSCALE
)) {
2739 s
.has_wscale_opt
= true;
2740 s
.snd_wscale
= info
->tcpi_snd_wscale
;
2741 s
.rcv_wscale
= info
->tcpi_rcv_wscale
;
2744 if (info
->tcpi_rto
&& info
->tcpi_rto
!= 3000000)
2745 s
.rto
= (double)info
->tcpi_rto
/ 1000;
2747 s
.backoff
= info
->tcpi_backoff
;
2748 s
.rtt
= (double)info
->tcpi_rtt
/ 1000;
2749 s
.rttvar
= (double)info
->tcpi_rttvar
/ 1000;
2750 s
.ato
= (double)info
->tcpi_ato
/ 1000;
2751 s
.mss
= info
->tcpi_snd_mss
;
2752 s
.rcv_mss
= info
->tcpi_rcv_mss
;
2753 s
.advmss
= info
->tcpi_advmss
;
2754 s
.rcv_space
= info
->tcpi_rcv_space
;
2755 s
.rcv_rtt
= (double)info
->tcpi_rcv_rtt
/ 1000;
2756 s
.lastsnd
= info
->tcpi_last_data_sent
;
2757 s
.lastrcv
= info
->tcpi_last_data_recv
;
2758 s
.lastack
= info
->tcpi_last_ack_recv
;
2759 s
.unacked
= info
->tcpi_unacked
;
2760 s
.retrans
= info
->tcpi_retrans
;
2761 s
.retrans_total
= info
->tcpi_total_retrans
;
2762 s
.lost
= info
->tcpi_lost
;
2763 s
.sacked
= info
->tcpi_sacked
;
2764 s
.fackets
= info
->tcpi_fackets
;
2765 s
.reordering
= info
->tcpi_reordering
;
2766 s
.rcv_ssthresh
= info
->tcpi_rcv_ssthresh
;
2767 s
.cwnd
= info
->tcpi_snd_cwnd
;
2768 s
.pmtu
= info
->tcpi_pmtu
;
2770 if (info
->tcpi_snd_ssthresh
< 0xFFFF)
2771 s
.ssthresh
= info
->tcpi_snd_ssthresh
;
2773 rtt
= (double) info
->tcpi_rtt
;
2774 if (tb
[INET_DIAG_VEGASINFO
]) {
2775 const struct tcpvegas_info
*vinfo
2776 = RTA_DATA(tb
[INET_DIAG_VEGASINFO
]);
2778 if (vinfo
->tcpv_enabled
&&
2779 vinfo
->tcpv_rtt
&& vinfo
->tcpv_rtt
!= 0x7fffffff)
2780 rtt
= vinfo
->tcpv_rtt
;
2783 if (tb
[INET_DIAG_DCTCPINFO
]) {
2784 struct dctcpstat
*dctcp
= malloc(sizeof(struct
2787 const struct tcp_dctcp_info
*dinfo
2788 = RTA_DATA(tb
[INET_DIAG_DCTCPINFO
]);
2790 dctcp
->enabled
= !!dinfo
->dctcp_enabled
;
2791 dctcp
->ce_state
= dinfo
->dctcp_ce_state
;
2792 dctcp
->alpha
= dinfo
->dctcp_alpha
;
2793 dctcp
->ab_ecn
= dinfo
->dctcp_ab_ecn
;
2794 dctcp
->ab_tot
= dinfo
->dctcp_ab_tot
;
2798 if (tb
[INET_DIAG_BBRINFO
]) {
2799 const void *bbr_info
= RTA_DATA(tb
[INET_DIAG_BBRINFO
]);
2800 int len
= min(RTA_PAYLOAD(tb
[INET_DIAG_BBRINFO
]),
2801 sizeof(*s
.bbr_info
));
2803 s
.bbr_info
= calloc(1, sizeof(*s
.bbr_info
));
2804 if (s
.bbr_info
&& bbr_info
)
2805 memcpy(s
.bbr_info
, bbr_info
, len
);
2808 if (rtt
> 0 && info
->tcpi_snd_mss
&& info
->tcpi_snd_cwnd
) {
2809 s
.send_bps
= (double) info
->tcpi_snd_cwnd
*
2810 (double)info
->tcpi_snd_mss
* 8000000. / rtt
;
2813 if (info
->tcpi_pacing_rate
&&
2814 info
->tcpi_pacing_rate
!= ~0ULL) {
2815 s
.pacing_rate
= info
->tcpi_pacing_rate
* 8.;
2817 if (info
->tcpi_max_pacing_rate
&&
2818 info
->tcpi_max_pacing_rate
!= ~0ULL)
2819 s
.pacing_rate_max
= info
->tcpi_max_pacing_rate
* 8.;
2821 s
.bytes_acked
= info
->tcpi_bytes_acked
;
2822 s
.bytes_received
= info
->tcpi_bytes_received
;
2823 s
.segs_out
= info
->tcpi_segs_out
;
2824 s
.segs_in
= info
->tcpi_segs_in
;
2825 s
.data_segs_out
= info
->tcpi_data_segs_out
;
2826 s
.data_segs_in
= info
->tcpi_data_segs_in
;
2827 s
.not_sent
= info
->tcpi_notsent_bytes
;
2828 if (info
->tcpi_min_rtt
&& info
->tcpi_min_rtt
!= ~0U)
2829 s
.min_rtt
= (double) info
->tcpi_min_rtt
/ 1000;
2830 s
.delivery_rate
= info
->tcpi_delivery_rate
* 8.;
2831 s
.app_limited
= info
->tcpi_delivery_rate_app_limited
;
2832 s
.busy_time
= info
->tcpi_busy_time
;
2833 s
.rwnd_limited
= info
->tcpi_rwnd_limited
;
2834 s
.sndbuf_limited
= info
->tcpi_sndbuf_limited
;
2835 tcp_stats_print(&s
);
2839 if (tb
[INET_DIAG_MD5SIG
]) {
2840 struct tcp_diag_md5sig
*sig
= RTA_DATA(tb
[INET_DIAG_MD5SIG
]);
2841 int len
= RTA_PAYLOAD(tb
[INET_DIAG_MD5SIG
]);
2844 print_md5sig(sig
++);
2845 for (len
-= sizeof(*sig
); len
> 0; len
-= sizeof(*sig
)) {
2847 print_md5sig(sig
++);
2852 static const char *format_host_sa(struct sockaddr_storage
*sa
)
2855 struct sockaddr_in sin
;
2856 struct sockaddr_in6 sin6
;
2857 } *saddr
= (void *)sa
;
2859 switch (sa
->ss_family
) {
2861 return format_host(AF_INET
, 4, &saddr
->sin
.sin_addr
);
2863 return format_host(AF_INET6
, 16, &saddr
->sin6
.sin6_addr
);
2869 static void sctp_show_info(const struct nlmsghdr
*nlh
, struct inet_diag_msg
*r
,
2870 struct rtattr
*tb
[])
2872 struct sockaddr_storage
*sa
;
2875 print_skmeminfo(tb
, INET_DIAG_SKMEMINFO
);
2877 if (tb
[INET_DIAG_LOCALS
]) {
2878 len
= RTA_PAYLOAD(tb
[INET_DIAG_LOCALS
]);
2879 sa
= RTA_DATA(tb
[INET_DIAG_LOCALS
]);
2881 out("locals:%s", format_host_sa(sa
));
2882 for (sa
++, len
-= sizeof(*sa
); len
> 0; sa
++, len
-= sizeof(*sa
))
2883 out(",%s", format_host_sa(sa
));
2886 if (tb
[INET_DIAG_PEERS
]) {
2887 len
= RTA_PAYLOAD(tb
[INET_DIAG_PEERS
]);
2888 sa
= RTA_DATA(tb
[INET_DIAG_PEERS
]);
2890 out(" peers:%s", format_host_sa(sa
));
2891 for (sa
++, len
-= sizeof(*sa
); len
> 0; sa
++, len
-= sizeof(*sa
))
2892 out(",%s", format_host_sa(sa
));
2894 if (tb
[INET_DIAG_INFO
]) {
2895 struct sctp_info
*info
;
2896 len
= RTA_PAYLOAD(tb
[INET_DIAG_INFO
]);
2898 /* workaround for older kernels with less fields */
2899 if (len
< sizeof(*info
)) {
2900 info
= alloca(sizeof(*info
));
2901 memcpy(info
, RTA_DATA(tb
[INET_DIAG_INFO
]), len
);
2902 memset((char *)info
+ len
, 0, sizeof(*info
) - len
);
2904 info
= RTA_DATA(tb
[INET_DIAG_INFO
]);
2906 sctp_stats_print(info
);
2910 static void parse_diag_msg(struct nlmsghdr
*nlh
, struct sockstat
*s
)
2912 struct rtattr
*tb
[INET_DIAG_MAX
+1];
2913 struct inet_diag_msg
*r
= NLMSG_DATA(nlh
);
2915 parse_rtattr(tb
, INET_DIAG_MAX
, (struct rtattr
*)(r
+1),
2916 nlh
->nlmsg_len
- NLMSG_LENGTH(sizeof(*r
)));
2918 s
->state
= r
->idiag_state
;
2919 s
->local
.family
= s
->remote
.family
= r
->idiag_family
;
2920 s
->lport
= ntohs(r
->id
.idiag_sport
);
2921 s
->rport
= ntohs(r
->id
.idiag_dport
);
2922 s
->wq
= r
->idiag_wqueue
;
2923 s
->rq
= r
->idiag_rqueue
;
2924 s
->ino
= r
->idiag_inode
;
2925 s
->uid
= r
->idiag_uid
;
2926 s
->iface
= r
->id
.idiag_if
;
2927 s
->sk
= cookie_sk_get(&r
->id
.idiag_cookie
[0]);
2930 if (tb
[INET_DIAG_MARK
])
2931 s
->mark
= rta_getattr_u32(tb
[INET_DIAG_MARK
]);
2932 if (tb
[INET_DIAG_PROTOCOL
])
2933 s
->raw_prot
= rta_getattr_u8(tb
[INET_DIAG_PROTOCOL
]);
2937 if (s
->local
.family
== AF_INET
)
2938 s
->local
.bytelen
= s
->remote
.bytelen
= 4;
2940 s
->local
.bytelen
= s
->remote
.bytelen
= 16;
2942 memcpy(s
->local
.data
, r
->id
.idiag_src
, s
->local
.bytelen
);
2943 memcpy(s
->remote
.data
, r
->id
.idiag_dst
, s
->local
.bytelen
);
2946 static int inet_show_sock(struct nlmsghdr
*nlh
,
2949 struct rtattr
*tb
[INET_DIAG_MAX
+1];
2950 struct inet_diag_msg
*r
= NLMSG_DATA(nlh
);
2951 unsigned char v6only
= 0;
2953 parse_rtattr(tb
, INET_DIAG_MAX
, (struct rtattr
*)(r
+1),
2954 nlh
->nlmsg_len
- NLMSG_LENGTH(sizeof(*r
)));
2956 if (tb
[INET_DIAG_PROTOCOL
])
2957 s
->type
= rta_getattr_u8(tb
[INET_DIAG_PROTOCOL
]);
2959 if (s
->local
.family
== AF_INET6
&& tb
[INET_DIAG_SKV6ONLY
])
2960 v6only
= rta_getattr_u8(tb
[INET_DIAG_SKV6ONLY
]);
2962 inet_stats_print(s
, v6only
);
2965 struct tcpstat t
= {};
2967 t
.timer
= r
->idiag_timer
;
2968 t
.timeout
= r
->idiag_expires
;
2969 t
.retrans
= r
->idiag_retrans
;
2970 if (s
->type
== IPPROTO_SCTP
)
2971 sctp_timer_print(&t
);
2973 tcp_timer_print(&t
);
2977 sock_details_print(s
);
2978 if (s
->local
.family
== AF_INET6
&& tb
[INET_DIAG_SKV6ONLY
])
2979 out(" v6only:%u", v6only
);
2981 if (tb
[INET_DIAG_SHUTDOWN
]) {
2984 mask
= rta_getattr_u8(tb
[INET_DIAG_SHUTDOWN
]);
2986 mask
& 1 ? '-' : '<', mask
& 2 ? '-' : '>');
2990 if (show_mem
|| (show_tcpinfo
&& s
->type
!= IPPROTO_UDP
)) {
2992 if (s
->type
== IPPROTO_SCTP
)
2993 sctp_show_info(nlh
, r
, tb
);
2995 tcp_show_info(nlh
, r
, tb
);
3002 static int tcpdiag_send(int fd
, int protocol
, struct filter
*f
)
3004 struct sockaddr_nl nladdr
= { .nl_family
= AF_NETLINK
};
3006 struct nlmsghdr nlh
;
3007 struct inet_diag_req r
;
3009 .nlh
.nlmsg_len
= sizeof(req
),
3010 .nlh
.nlmsg_flags
= NLM_F_ROOT
| NLM_F_MATCH
| NLM_F_REQUEST
,
3011 .nlh
.nlmsg_seq
= MAGIC_SEQ
,
3012 .r
.idiag_family
= AF_INET
,
3013 .r
.idiag_states
= f
->states
,
3019 struct iovec iov
[3];
3022 if (protocol
== IPPROTO_UDP
)
3025 if (protocol
== IPPROTO_TCP
)
3026 req
.nlh
.nlmsg_type
= TCPDIAG_GETSOCK
;
3028 req
.nlh
.nlmsg_type
= DCCPDIAG_GETSOCK
;
3030 req
.r
.idiag_ext
|= (1<<(INET_DIAG_MEMINFO
-1));
3031 req
.r
.idiag_ext
|= (1<<(INET_DIAG_SKMEMINFO
-1));
3035 req
.r
.idiag_ext
|= (1<<(INET_DIAG_INFO
-1));
3036 req
.r
.idiag_ext
|= (1<<(INET_DIAG_VEGASINFO
-1));
3037 req
.r
.idiag_ext
|= (1<<(INET_DIAG_CONG
-1));
3040 iov
[0] = (struct iovec
){
3042 .iov_len
= sizeof(req
)
3045 bclen
= ssfilter_bytecompile(f
->f
, &bc
);
3047 rta
.rta_type
= INET_DIAG_REQ_BYTECODE
;
3048 rta
.rta_len
= RTA_LENGTH(bclen
);
3049 iov
[1] = (struct iovec
){ &rta
, sizeof(rta
) };
3050 iov
[2] = (struct iovec
){ bc
, bclen
};
3051 req
.nlh
.nlmsg_len
+= RTA_LENGTH(bclen
);
3056 msg
= (struct msghdr
) {
3057 .msg_name
= (void *)&nladdr
,
3058 .msg_namelen
= sizeof(nladdr
),
3060 .msg_iovlen
= iovlen
,
3063 if (sendmsg(fd
, &msg
, 0) < 0) {
3071 static int sockdiag_send(int family
, int fd
, int protocol
, struct filter
*f
)
3073 struct sockaddr_nl nladdr
= { .nl_family
= AF_NETLINK
};
3074 DIAG_REQUEST(req
, struct inet_diag_req_v2 r
);
3079 struct iovec iov
[3];
3082 if (family
== PF_UNSPEC
)
3083 return tcpdiag_send(fd
, protocol
, f
);
3085 memset(&req
.r
, 0, sizeof(req
.r
));
3086 req
.r
.sdiag_family
= family
;
3087 req
.r
.sdiag_protocol
= protocol
;
3088 req
.r
.idiag_states
= f
->states
;
3090 req
.r
.idiag_ext
|= (1<<(INET_DIAG_MEMINFO
-1));
3091 req
.r
.idiag_ext
|= (1<<(INET_DIAG_SKMEMINFO
-1));
3095 req
.r
.idiag_ext
|= (1<<(INET_DIAG_INFO
-1));
3096 req
.r
.idiag_ext
|= (1<<(INET_DIAG_VEGASINFO
-1));
3097 req
.r
.idiag_ext
|= (1<<(INET_DIAG_CONG
-1));
3100 iov
[0] = (struct iovec
){
3102 .iov_len
= sizeof(req
)
3105 bclen
= ssfilter_bytecompile(f
->f
, &bc
);
3107 rta
.rta_type
= INET_DIAG_REQ_BYTECODE
;
3108 rta
.rta_len
= RTA_LENGTH(bclen
);
3109 iov
[1] = (struct iovec
){ &rta
, sizeof(rta
) };
3110 iov
[2] = (struct iovec
){ bc
, bclen
};
3111 req
.nlh
.nlmsg_len
+= RTA_LENGTH(bclen
);
3116 msg
= (struct msghdr
) {
3117 .msg_name
= (void *)&nladdr
,
3118 .msg_namelen
= sizeof(nladdr
),
3120 .msg_iovlen
= iovlen
,
3123 if (sendmsg(fd
, &msg
, 0) < 0) {
3131 struct inet_diag_arg
{
3134 struct rtnl_handle
*rth
;
3137 static int kill_inet_sock(struct nlmsghdr
*h
, void *arg
, struct sockstat
*s
)
3139 struct inet_diag_msg
*d
= NLMSG_DATA(h
);
3140 struct inet_diag_arg
*diag_arg
= arg
;
3141 struct rtnl_handle
*rth
= diag_arg
->rth
;
3143 DIAG_REQUEST(req
, struct inet_diag_req_v2 r
);
3145 req
.nlh
.nlmsg_type
= SOCK_DESTROY
;
3146 req
.nlh
.nlmsg_flags
= NLM_F_REQUEST
| NLM_F_ACK
;
3147 req
.nlh
.nlmsg_seq
= ++rth
->seq
;
3148 req
.r
.sdiag_family
= d
->idiag_family
;
3149 req
.r
.sdiag_protocol
= diag_arg
->protocol
;
3152 if (diag_arg
->protocol
== IPPROTO_RAW
) {
3153 struct inet_diag_req_raw
*raw
= (void *)&req
.r
;
3155 BUILD_BUG_ON(sizeof(req
.r
) != sizeof(*raw
));
3156 raw
->sdiag_raw_protocol
= s
->raw_prot
;
3159 return rtnl_talk(rth
, &req
.nlh
, NULL
);
3162 static int show_one_inet_sock(struct nlmsghdr
*h
, void *arg
)
3165 struct inet_diag_arg
*diag_arg
= arg
;
3166 struct inet_diag_msg
*r
= NLMSG_DATA(h
);
3167 struct sockstat s
= {};
3169 if (!(diag_arg
->f
->families
& FAMILY_MASK(r
->idiag_family
)))
3172 parse_diag_msg(h
, &s
);
3173 s
.type
= diag_arg
->protocol
;
3175 if (diag_arg
->f
->f
&& run_ssfilter(diag_arg
->f
->f
, &s
) == 0)
3178 if (diag_arg
->f
->kill
&& kill_inet_sock(h
, arg
, &s
) != 0) {
3179 if (errno
== EOPNOTSUPP
|| errno
== ENOENT
) {
3180 /* Socket can't be closed, or is already closed. */
3183 perror("SOCK_DESTROY answers");
3188 err
= inet_show_sock(h
, &s
);
3195 static int inet_show_netlink(struct filter
*f
, FILE *dump_fp
, int protocol
)
3198 struct rtnl_handle rth
, rth2
;
3199 int family
= PF_INET
;
3200 struct inet_diag_arg arg
= { .f
= f
, .protocol
= protocol
};
3202 if (rtnl_open_byproto(&rth
, 0, NETLINK_SOCK_DIAG
))
3206 if (rtnl_open_byproto(&rth2
, 0, NETLINK_SOCK_DIAG
)) {
3213 rth
.dump
= MAGIC_SEQ
;
3214 rth
.dump_fp
= dump_fp
;
3215 if (preferred_family
== PF_INET6
)
3219 if ((err
= sockdiag_send(family
, rth
.fd
, protocol
, f
)))
3222 if ((err
= rtnl_dump_filter(&rth
, show_one_inet_sock
, &arg
))) {
3223 if (family
!= PF_UNSPEC
) {
3229 if (family
== PF_INET
&& preferred_family
!= PF_INET
) {
3237 rtnl_close(arg
.rth
);
3241 static int tcp_show_netlink_file(struct filter
*f
)
3247 if ((fp
= fopen(getenv("TCPDIAG_FILE"), "r")) == NULL
) {
3248 perror("fopen($TCPDIAG_FILE)");
3254 struct nlmsghdr
*h
= (struct nlmsghdr
*)buf
;
3255 struct sockstat s
= {};
3257 status
= fread(buf
, 1, sizeof(*h
), fp
);
3259 perror("Reading header from $TCPDIAG_FILE");
3262 if (status
!= sizeof(*h
)) {
3263 perror("Unexpected EOF reading $TCPDIAG_FILE");
3267 status
= fread(h
+1, 1, NLMSG_ALIGN(h
->nlmsg_len
-sizeof(*h
)), fp
);
3270 perror("Reading $TCPDIAG_FILE");
3273 if (status
+ sizeof(*h
) < h
->nlmsg_len
) {
3274 perror("Unexpected EOF reading $TCPDIAG_FILE");
3278 /* The only legal exit point */
3279 if (h
->nlmsg_type
== NLMSG_DONE
) {
3284 if (h
->nlmsg_type
== NLMSG_ERROR
) {
3285 struct nlmsgerr
*err
= (struct nlmsgerr
*)NLMSG_DATA(h
);
3287 if (h
->nlmsg_len
< NLMSG_LENGTH(sizeof(struct nlmsgerr
))) {
3288 fprintf(stderr
, "ERROR truncated\n");
3290 errno
= -err
->error
;
3291 perror("TCPDIAG answered");
3296 parse_diag_msg(h
, &s
);
3297 s
.type
= IPPROTO_TCP
;
3299 if (f
&& f
->f
&& run_ssfilter(f
->f
, &s
) == 0)
3302 err2
= inet_show_sock(h
, &s
);
3313 static int tcp_show(struct filter
*f
)
3317 int bufsize
= 1024*1024;
3319 if (!filter_af_get(f
, AF_INET
) && !filter_af_get(f
, AF_INET6
))
3322 dg_proto
= TCP_PROTO
;
3324 if (getenv("TCPDIAG_FILE"))
3325 return tcp_show_netlink_file(f
);
3327 if (!getenv("PROC_NET_TCP") && !getenv("PROC_ROOT")
3328 && inet_show_netlink(f
, NULL
, IPPROTO_TCP
) == 0)
3331 /* Sigh... We have to parse /proc/net/tcp... */
3332 while (bufsize
>= 64*1024) {
3333 if ((buf
= malloc(bufsize
)) != NULL
)
3342 if (f
->families
& FAMILY_MASK(AF_INET
)) {
3343 if ((fp
= net_tcp_open()) == NULL
)
3346 setbuffer(fp
, buf
, bufsize
);
3347 if (generic_record_read(fp
, tcp_show_line
, f
, AF_INET
))
3352 if ((f
->families
& FAMILY_MASK(AF_INET6
)) &&
3353 (fp
= net_tcp6_open()) != NULL
) {
3354 setbuffer(fp
, buf
, bufsize
);
3355 if (generic_record_read(fp
, tcp_show_line
, f
, AF_INET6
))
3365 int saved_errno
= errno
;
3370 errno
= saved_errno
;
3375 static int dccp_show(struct filter
*f
)
3377 if (!filter_af_get(f
, AF_INET
) && !filter_af_get(f
, AF_INET6
))
3380 if (!getenv("PROC_NET_DCCP") && !getenv("PROC_ROOT")
3381 && inet_show_netlink(f
, NULL
, IPPROTO_DCCP
) == 0)
3387 static int sctp_show(struct filter
*f
)
3389 if (!filter_af_get(f
, AF_INET
) && !filter_af_get(f
, AF_INET6
))
3392 if (!getenv("PROC_NET_SCTP") && !getenv("PROC_ROOT")
3393 && inet_show_netlink(f
, NULL
, IPPROTO_SCTP
) == 0)
3399 static int dgram_show_line(char *line
, const struct filter
*f
, int family
)
3401 struct sockstat s
= {};
3402 char *loc
, *rem
, *data
;
3406 if (proc_inet_split_line(line
, &loc
, &rem
, &data
))
3409 int state
= (data
[1] >= 'A') ? (data
[1] - 'A' + 10) : (data
[1] - '0');
3411 if (!(f
->states
& (1 << state
)))
3414 proc_parse_inet_addr(loc
, rem
, family
, &s
);
3416 if (f
->f
&& run_ssfilter(f
->f
, &s
) == 0)
3420 n
= sscanf(data
, "%x %x:%x %*x:%*x %*x %d %*d %u %d %llx %[^\n]\n",
3421 &s
.state
, &s
.wq
, &s
.rq
,
3423 &s
.refcnt
, &s
.sk
, opt
);
3428 s
.type
= dg_proto
== UDP_PROTO
? IPPROTO_UDP
: 0;
3429 inet_stats_print(&s
, false);
3431 if (show_details
&& opt
[0])
3432 out(" opt:\"%s\"", opt
);
3437 static int udp_show(struct filter
*f
)
3441 if (!filter_af_get(f
, AF_INET
) && !filter_af_get(f
, AF_INET6
))
3444 dg_proto
= UDP_PROTO
;
3446 if (!getenv("PROC_NET_UDP") && !getenv("PROC_ROOT")
3447 && inet_show_netlink(f
, NULL
, IPPROTO_UDP
) == 0)
3450 if (f
->families
&FAMILY_MASK(AF_INET
)) {
3451 if ((fp
= net_udp_open()) == NULL
)
3453 if (generic_record_read(fp
, dgram_show_line
, f
, AF_INET
))
3458 if ((f
->families
&FAMILY_MASK(AF_INET6
)) &&
3459 (fp
= net_udp6_open()) != NULL
) {
3460 if (generic_record_read(fp
, dgram_show_line
, f
, AF_INET6
))
3468 int saved_errno
= errno
;
3472 errno
= saved_errno
;
3477 static int raw_show(struct filter
*f
)
3481 if (!filter_af_get(f
, AF_INET
) && !filter_af_get(f
, AF_INET6
))
3484 dg_proto
= RAW_PROTO
;
3486 if (!getenv("PROC_NET_RAW") && !getenv("PROC_ROOT") &&
3487 inet_show_netlink(f
, NULL
, IPPROTO_RAW
) == 0)
3490 if (f
->families
&FAMILY_MASK(AF_INET
)) {
3491 if ((fp
= net_raw_open()) == NULL
)
3493 if (generic_record_read(fp
, dgram_show_line
, f
, AF_INET
))
3498 if ((f
->families
&FAMILY_MASK(AF_INET6
)) &&
3499 (fp
= net_raw6_open()) != NULL
) {
3500 if (generic_record_read(fp
, dgram_show_line
, f
, AF_INET6
))
3508 int saved_errno
= errno
;
3512 errno
= saved_errno
;
3517 #define MAX_UNIX_REMEMBER (1024*1024/sizeof(struct sockstat))
3519 static void unix_list_drop_first(struct sockstat
**list
)
3521 struct sockstat
*s
= *list
;
3523 (*list
) = (*list
)->next
;
3528 static bool unix_type_skip(struct sockstat
*s
, struct filter
*f
)
3530 if (s
->type
== SOCK_STREAM
&& !(f
->dbs
&(1<<UNIX_ST_DB
)))
3532 if (s
->type
== SOCK_DGRAM
&& !(f
->dbs
&(1<<UNIX_DG_DB
)))
3534 if (s
->type
== SOCK_SEQPACKET
&& !(f
->dbs
&(1<<UNIX_SQ_DB
)))
3539 static void unix_stats_print(struct sockstat
*s
, struct filter
*f
)
3541 char port_name
[30] = {};
3543 sock_state_print(s
);
3545 sock_addr_print(s
->name
?: "*", " ",
3546 int_to_str(s
->lport
, port_name
), NULL
);
3547 sock_addr_print(s
->peer_name
?: "*", " ",
3548 int_to_str(s
->rport
, port_name
), NULL
);
3553 static int unix_show_sock(struct nlmsghdr
*nlh
, void *arg
)
3555 struct filter
*f
= (struct filter
*)arg
;
3556 struct unix_diag_msg
*r
= NLMSG_DATA(nlh
);
3557 struct rtattr
*tb
[UNIX_DIAG_MAX
+1];
3559 struct sockstat stat
= { .name
= "*", .peer_name
= "*" };
3561 parse_rtattr(tb
, UNIX_DIAG_MAX
, (struct rtattr
*)(r
+1),
3562 nlh
->nlmsg_len
- NLMSG_LENGTH(sizeof(*r
)));
3564 stat
.type
= r
->udiag_type
;
3565 stat
.state
= r
->udiag_state
;
3566 stat
.ino
= stat
.lport
= r
->udiag_ino
;
3567 stat
.local
.family
= stat
.remote
.family
= AF_UNIX
;
3569 if (unix_type_skip(&stat
, f
))
3572 if (tb
[UNIX_DIAG_RQLEN
]) {
3573 struct unix_diag_rqlen
*rql
= RTA_DATA(tb
[UNIX_DIAG_RQLEN
]);
3575 stat
.rq
= rql
->udiag_rqueue
;
3576 stat
.wq
= rql
->udiag_wqueue
;
3578 if (tb
[UNIX_DIAG_NAME
]) {
3579 int len
= RTA_PAYLOAD(tb
[UNIX_DIAG_NAME
]);
3581 memcpy(name
, RTA_DATA(tb
[UNIX_DIAG_NAME
]), len
);
3583 if (name
[0] == '\0') {
3585 for (i
= 0; i
< len
; i
++)
3586 if (name
[i
] == '\0')
3589 stat
.name
= &name
[0];
3590 memcpy(stat
.local
.data
, &stat
.name
, sizeof(stat
.name
));
3592 if (tb
[UNIX_DIAG_PEER
])
3593 stat
.rport
= rta_getattr_u32(tb
[UNIX_DIAG_PEER
]);
3595 if (f
->f
&& run_ssfilter(f
->f
, &stat
) == 0)
3598 unix_stats_print(&stat
, f
);
3601 print_skmeminfo(tb
, UNIX_DIAG_MEMINFO
);
3603 if (tb
[UNIX_DIAG_SHUTDOWN
]) {
3606 mask
= rta_getattr_u8(tb
[UNIX_DIAG_SHUTDOWN
]);
3608 mask
& 1 ? '-' : '<', mask
& 2 ? '-' : '>');
3610 if (tb
[UNIX_DIAG_VFS
]) {
3611 struct unix_diag_vfs
*uv
= RTA_DATA(tb
[UNIX_DIAG_VFS
]);
3613 out(" ino:%u dev:%u/%u", uv
->udiag_vfs_ino
, major(uv
->udiag_vfs_dev
),
3614 minor(uv
->udiag_vfs_dev
));
3616 if (tb
[UNIX_DIAG_ICONS
]) {
3617 int len
= RTA_PAYLOAD(tb
[UNIX_DIAG_ICONS
]);
3618 __u32
*peers
= RTA_DATA(tb
[UNIX_DIAG_ICONS
]);
3622 for (i
= 0; i
< len
/ sizeof(__u32
); i
++)
3623 out(" %u", peers
[i
]);
3630 static int handle_netlink_request(struct filter
*f
, struct nlmsghdr
*req
,
3631 size_t size
, rtnl_filter_t show_one_sock
)
3634 struct rtnl_handle rth
;
3636 if (rtnl_open_byproto(&rth
, 0, NETLINK_SOCK_DIAG
))
3639 rth
.dump
= MAGIC_SEQ
;
3641 if (rtnl_send(&rth
, req
, size
) < 0)
3644 if (rtnl_dump_filter(&rth
, show_one_sock
, f
))
3653 static int unix_show_netlink(struct filter
*f
)
3655 DIAG_REQUEST(req
, struct unix_diag_req r
);
3657 req
.r
.sdiag_family
= AF_UNIX
;
3658 req
.r
.udiag_states
= f
->states
;
3659 req
.r
.udiag_show
= UDIAG_SHOW_NAME
| UDIAG_SHOW_PEER
| UDIAG_SHOW_RQLEN
;
3661 req
.r
.udiag_show
|= UDIAG_SHOW_MEMINFO
;
3663 req
.r
.udiag_show
|= UDIAG_SHOW_VFS
| UDIAG_SHOW_ICONS
;
3665 return handle_netlink_request(f
, &req
.nlh
, sizeof(req
), unix_show_sock
);
3668 static int unix_show(struct filter
*f
)
3675 struct sockstat
*list
= NULL
;
3676 const int unix_state_map
[] = { SS_CLOSE
, SS_SYN_SENT
,
3677 SS_ESTABLISHED
, SS_CLOSING
};
3679 if (!filter_af_get(f
, AF_UNIX
))
3682 if (!getenv("PROC_NET_UNIX") && !getenv("PROC_ROOT")
3683 && unix_show_netlink(f
) == 0)
3686 if ((fp
= net_unix_open()) == NULL
)
3688 if (!fgets(buf
, sizeof(buf
), fp
)) {
3693 if (memcmp(buf
, "Peer", 4) == 0)
3697 while (fgets(buf
, sizeof(buf
), fp
)) {
3698 struct sockstat
*u
, **insp
;
3701 if (!(u
= calloc(1, sizeof(*u
))))
3704 if (sscanf(buf
, "%x: %x %x %x %x %x %d %s",
3705 &u
->rport
, &u
->rq
, &u
->wq
, &flags
, &u
->type
,
3706 &u
->state
, &u
->ino
, name
) < 8)
3710 u
->local
.family
= u
->remote
.family
= AF_UNIX
;
3712 if (flags
& (1 << 16)) {
3713 u
->state
= SS_LISTEN
;
3714 } else if (u
->state
> 0 &&
3715 u
->state
<= ARRAY_SIZE(unix_state_map
)) {
3716 u
->state
= unix_state_map
[u
->state
-1];
3717 if (u
->type
== SOCK_DGRAM
&& u
->state
== SS_CLOSE
&& u
->rport
)
3718 u
->state
= SS_ESTABLISHED
;
3720 if (unix_type_skip(u
, f
) ||
3721 !(f
->states
& (1 << u
->state
))) {
3733 u
->name
= strdup(name
);
3743 for (p
= list
; p
; p
= p
->next
) {
3744 if (u
->rport
== p
->lport
)
3750 u
->peer_name
= p
->name
? : "*";
3754 struct sockstat st
= {
3755 .local
.family
= AF_UNIX
,
3756 .remote
.family
= AF_UNIX
,
3759 memcpy(st
.local
.data
, &u
->name
, sizeof(u
->name
));
3760 /* when parsing the old format rport is set to 0 and
3761 * therefore peer_name remains NULL
3763 if (u
->peer_name
&& strcmp(u
->peer_name
, "*"))
3764 memcpy(st
.remote
.data
, &u
->peer_name
,
3765 sizeof(u
->peer_name
));
3766 if (run_ssfilter(f
->f
, &st
) == 0) {
3775 if (u
->type
< (*insp
)->type
||
3776 (u
->type
== (*insp
)->type
&&
3777 u
->ino
< (*insp
)->ino
))
3779 insp
= &(*insp
)->next
;
3784 if (++cnt
> MAX_UNIX_REMEMBER
) {
3786 unix_stats_print(list
, f
);
3787 unix_list_drop_first(&list
);
3794 unix_stats_print(list
, f
);
3795 unix_list_drop_first(&list
);
3801 static int packet_stats_print(struct sockstat
*s
, const struct filter
*f
)
3803 const char *addr
, *port
;
3806 s
->local
.family
= s
->remote
.family
= AF_PACKET
;
3809 s
->local
.data
[0] = s
->prot
;
3810 if (run_ssfilter(f
->f
, s
) == 0)
3814 sock_state_print(s
);
3819 addr
= ll_proto_n2a(htons(s
->prot
), ll_name
, sizeof(ll_name
));
3824 port
= xll_index_to_name(s
->iface
);
3826 sock_addr_print(addr
, ":", port
, NULL
);
3827 sock_addr_print("", "*", "", NULL
);
3832 sock_details_print(s
);
3837 static void packet_show_ring(struct packet_diag_ring
*ring
)
3839 out("blk_size:%d", ring
->pdr_block_size
);
3840 out(",blk_nr:%d", ring
->pdr_block_nr
);
3841 out(",frm_size:%d", ring
->pdr_frame_size
);
3842 out(",frm_nr:%d", ring
->pdr_frame_nr
);
3843 out(",tmo:%d", ring
->pdr_retire_tmo
);
3844 out(",features:0x%x", ring
->pdr_features
);
3847 static int packet_show_sock(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(struct nlmsghdr
*nlh
, void *arg
)
4138 struct filter
*f
= (struct filter
*)arg
;
4139 struct netlink_diag_msg
*r
= NLMSG_DATA(nlh
);
4140 struct rtattr
*tb
[NETLINK_DIAG_MAX
+1];
4142 unsigned long groups
= 0;
4144 parse_rtattr(tb
, NETLINK_DIAG_MAX
, (struct rtattr
*)(r
+1),
4145 nlh
->nlmsg_len
- NLMSG_LENGTH(sizeof(*r
)));
4147 if (tb
[NETLINK_DIAG_GROUPS
] && RTA_PAYLOAD(tb
[NETLINK_DIAG_GROUPS
]))
4148 groups
= *(unsigned long *) RTA_DATA(tb
[NETLINK_DIAG_GROUPS
]);
4150 if (tb
[NETLINK_DIAG_MEMINFO
]) {
4151 const __u32
*skmeminfo
;
4153 skmeminfo
= RTA_DATA(tb
[NETLINK_DIAG_MEMINFO
]);
4155 rq
= skmeminfo
[SK_MEMINFO_RMEM_ALLOC
];
4156 wq
= skmeminfo
[SK_MEMINFO_WMEM_ALLOC
];
4159 if (netlink_show_one(f
, r
->ndiag_protocol
, r
->ndiag_portid
, groups
,
4160 r
->ndiag_state
, r
->ndiag_dst_portid
, r
->ndiag_dst_group
,
4167 print_skmeminfo(tb
, NETLINK_DIAG_MEMINFO
);
4173 static int netlink_show_netlink(struct filter
*f
)
4175 DIAG_REQUEST(req
, struct netlink_diag_req r
);
4177 req
.r
.sdiag_family
= AF_NETLINK
;
4178 req
.r
.sdiag_protocol
= NDIAG_PROTO_ALL
;
4179 req
.r
.ndiag_show
= NDIAG_SHOW_GROUPS
| NDIAG_SHOW_MEMINFO
;
4181 return handle_netlink_request(f
, &req
.nlh
, sizeof(req
), netlink_show_sock
);
4184 static int netlink_show(struct filter
*f
)
4189 unsigned int groups
;
4191 unsigned long long sk
, cb
;
4193 if (!filter_af_get(f
, AF_NETLINK
) || !(f
->states
& (1 << SS_CLOSE
)))
4196 if (!getenv("PROC_NET_NETLINK") && !getenv("PROC_ROOT") &&
4197 netlink_show_netlink(f
) == 0)
4200 if ((fp
= net_netlink_open()) == NULL
)
4202 if (!fgets(buf
, sizeof(buf
), fp
)) {
4207 while (fgets(buf
, sizeof(buf
), fp
)) {
4208 sscanf(buf
, "%llx %d %d %x %d %d %llx %d",
4210 &prot
, &pid
, &groups
, &rq
, &wq
, &cb
, &rc
);
4212 netlink_show_one(f
, prot
, pid
, groups
, 0, 0, 0, rq
, wq
, sk
, cb
);
4219 static bool vsock_type_skip(struct sockstat
*s
, struct filter
*f
)
4221 if (s
->type
== SOCK_STREAM
&& !(f
->dbs
& (1 << VSOCK_ST_DB
)))
4223 if (s
->type
== SOCK_DGRAM
&& !(f
->dbs
& (1 << VSOCK_DG_DB
)))
4228 static void vsock_addr_print(inet_prefix
*a
, __u32 port
)
4230 char cid_str
[sizeof("4294967295")];
4231 char port_str
[sizeof("4294967295")];
4234 memcpy(&cid
, a
->data
, sizeof(cid
));
4236 if (cid
== ~(__u32
)0)
4237 snprintf(cid_str
, sizeof(cid_str
), "*");
4239 snprintf(cid_str
, sizeof(cid_str
), "%u", cid
);
4241 if (port
== ~(__u32
)0)
4242 snprintf(port_str
, sizeof(port_str
), "*");
4244 snprintf(port_str
, sizeof(port_str
), "%u", port
);
4246 sock_addr_print(cid_str
, ":", port_str
, NULL
);
4249 static void vsock_stats_print(struct sockstat
*s
, struct filter
*f
)
4251 sock_state_print(s
);
4253 vsock_addr_print(&s
->local
, s
->lport
);
4254 vsock_addr_print(&s
->remote
, s
->rport
);
4259 static int vsock_show_sock(struct nlmsghdr
*nlh
, void *arg
)
4261 struct filter
*f
= (struct filter
*)arg
;
4262 struct vsock_diag_msg
*r
= NLMSG_DATA(nlh
);
4263 struct sockstat stat
= {
4264 .type
= r
->vdiag_type
,
4265 .lport
= r
->vdiag_src_port
,
4266 .rport
= r
->vdiag_dst_port
,
4267 .state
= r
->vdiag_state
,
4268 .ino
= r
->vdiag_ino
,
4271 vsock_set_inet_prefix(&stat
.local
, r
->vdiag_src_cid
);
4272 vsock_set_inet_prefix(&stat
.remote
, r
->vdiag_dst_cid
);
4274 if (vsock_type_skip(&stat
, f
))
4277 if (f
->f
&& run_ssfilter(f
->f
, &stat
) == 0)
4280 vsock_stats_print(&stat
, f
);
4285 static int vsock_show(struct filter
*f
)
4287 DIAG_REQUEST(req
, struct vsock_diag_req r
);
4289 if (!filter_af_get(f
, AF_VSOCK
))
4292 req
.r
.sdiag_family
= AF_VSOCK
;
4293 req
.r
.vdiag_states
= f
->states
;
4295 return handle_netlink_request(f
, &req
.nlh
, sizeof(req
), vsock_show_sock
);
4298 static void tipc_sock_addr_print(struct rtattr
*net_addr
, struct rtattr
*id
)
4300 uint32_t node
= rta_getattr_u32(net_addr
);
4301 uint32_t identity
= rta_getattr_u32(id
);
4303 SPRINT_BUF(addr
) = {};
4304 SPRINT_BUF(port
) = {};
4306 sprintf(addr
, "%u", node
);
4307 sprintf(port
, "%u", identity
);
4308 sock_addr_print(addr
, ":", port
, NULL
);
4312 static int tipc_show_sock(struct nlmsghdr
*nlh
, void *arg
)
4314 struct rtattr
*stat
[TIPC_NLA_SOCK_STAT_MAX
+ 1] = {};
4315 struct rtattr
*attrs
[TIPC_NLA_SOCK_MAX
+ 1] = {};
4316 struct rtattr
*con
[TIPC_NLA_CON_MAX
+ 1] = {};
4317 struct rtattr
*info
[TIPC_NLA_MAX
+ 1] = {};
4318 struct rtattr
*msg_ref
;
4319 struct sockstat ss
= {};
4321 parse_rtattr(info
, TIPC_NLA_MAX
, NLMSG_DATA(nlh
),
4322 NLMSG_PAYLOAD(nlh
, 0));
4324 if (!info
[TIPC_NLA_SOCK
])
4327 msg_ref
= info
[TIPC_NLA_SOCK
];
4328 parse_rtattr(attrs
, TIPC_NLA_SOCK_MAX
, RTA_DATA(msg_ref
),
4329 RTA_PAYLOAD(msg_ref
));
4331 msg_ref
= attrs
[TIPC_NLA_SOCK_STAT
];
4332 parse_rtattr(stat
, TIPC_NLA_SOCK_STAT_MAX
,
4333 RTA_DATA(msg_ref
), RTA_PAYLOAD(msg_ref
));
4336 ss
.local
.family
= AF_TIPC
;
4337 ss
.type
= rta_getattr_u32(attrs
[TIPC_NLA_SOCK_TYPE
]);
4338 ss
.state
= rta_getattr_u32(attrs
[TIPC_NLA_SOCK_TIPC_STATE
]);
4339 ss
.uid
= rta_getattr_u32(attrs
[TIPC_NLA_SOCK_UID
]);
4340 ss
.ino
= rta_getattr_u32(attrs
[TIPC_NLA_SOCK_INO
]);
4341 ss
.rq
= rta_getattr_u32(stat
[TIPC_NLA_SOCK_STAT_RCVQ
]);
4342 ss
.wq
= rta_getattr_u32(stat
[TIPC_NLA_SOCK_STAT_SENDQ
]);
4343 ss
.sk
= rta_getattr_u64(attrs
[TIPC_NLA_SOCK_COOKIE
]);
4345 sock_state_print (&ss
);
4347 tipc_sock_addr_print(attrs
[TIPC_NLA_SOCK_ADDR
],
4348 attrs
[TIPC_NLA_SOCK_REF
]);
4350 msg_ref
= attrs
[TIPC_NLA_SOCK_CON
];
4352 parse_rtattr(con
, TIPC_NLA_CON_MAX
,
4353 RTA_DATA(msg_ref
), RTA_PAYLOAD(msg_ref
));
4355 tipc_sock_addr_print(con
[TIPC_NLA_CON_NODE
],
4356 con
[TIPC_NLA_CON_SOCK
]);
4358 sock_addr_print("", "-", "", NULL
);
4361 sock_details_print(&ss
);
4363 proc_ctx_print(&ss
);
4365 if (show_tipcinfo
) {
4366 out("\n type:%s", stype_nameg
[ss
.type
]);
4368 stat
[TIPC_NLA_SOCK_STAT_LINK_CONG
] ? "link" :
4369 stat
[TIPC_NLA_SOCK_STAT_CONN_CONG
] ? "conn" : "none");
4371 rta_getattr_u32(stat
[TIPC_NLA_SOCK_STAT_DROP
]));
4373 if (attrs
[TIPC_NLA_SOCK_HAS_PUBL
])
4376 if (con
[TIPC_NLA_CON_FLAG
])
4377 out(" via {%u,%u} ",
4378 rta_getattr_u32(con
[TIPC_NLA_CON_TYPE
]),
4379 rta_getattr_u32(con
[TIPC_NLA_CON_INST
]));
4385 static int tipc_show(struct filter
*f
)
4387 DIAG_REQUEST(req
, struct tipc_sock_diag_req r
);
4389 memset(&req
.r
, 0, sizeof(req
.r
));
4390 req
.r
.sdiag_family
= AF_TIPC
;
4391 req
.r
.tidiag_states
= f
->states
;
4393 return handle_netlink_request(f
, &req
.nlh
, sizeof(req
), tipc_show_sock
);
4396 struct sock_diag_msg
{
4400 static int generic_show_sock(struct nlmsghdr
*nlh
, void *arg
)
4402 struct sock_diag_msg
*r
= NLMSG_DATA(nlh
);
4403 struct inet_diag_arg inet_arg
= { .f
= arg
, .protocol
= IPPROTO_MAX
};
4406 switch (r
->sdiag_family
) {
4409 inet_arg
.rth
= inet_arg
.f
->rth_for_killing
;
4410 ret
= show_one_inet_sock(nlh
, &inet_arg
);
4413 ret
= unix_show_sock(nlh
, arg
);
4416 ret
= packet_show_sock(nlh
, arg
);
4419 ret
= netlink_show_sock(nlh
, arg
);
4422 ret
= vsock_show_sock(nlh
, arg
);
4433 static int handle_follow_request(struct filter
*f
)
4437 struct rtnl_handle rth
, rth2
;
4439 if (f
->families
& FAMILY_MASK(AF_INET
) && f
->dbs
& (1 << TCP_DB
))
4440 groups
|= 1 << (SKNLGRP_INET_TCP_DESTROY
- 1);
4441 if (f
->families
& FAMILY_MASK(AF_INET
) && f
->dbs
& (1 << UDP_DB
))
4442 groups
|= 1 << (SKNLGRP_INET_UDP_DESTROY
- 1);
4443 if (f
->families
& FAMILY_MASK(AF_INET6
) && f
->dbs
& (1 << TCP_DB
))
4444 groups
|= 1 << (SKNLGRP_INET6_TCP_DESTROY
- 1);
4445 if (f
->families
& FAMILY_MASK(AF_INET6
) && f
->dbs
& (1 << UDP_DB
))
4446 groups
|= 1 << (SKNLGRP_INET6_UDP_DESTROY
- 1);
4451 if (rtnl_open_byproto(&rth
, groups
, NETLINK_SOCK_DIAG
))
4455 rth
.local
.nl_pid
= 0;
4458 if (rtnl_open_byproto(&rth2
, groups
, NETLINK_SOCK_DIAG
)) {
4462 f
->rth_for_killing
= &rth2
;
4465 if (rtnl_dump_filter(&rth
, generic_show_sock
, f
))
4469 if (f
->rth_for_killing
)
4470 rtnl_close(f
->rth_for_killing
);
4474 static int get_snmp_int(char *proto
, char *key
, int *result
)
4478 int protolen
= strlen(proto
);
4479 int keylen
= strlen(key
);
4483 if ((fp
= net_snmp_open()) == NULL
)
4486 while (fgets(buf
, sizeof(buf
), fp
) != NULL
) {
4490 if (memcmp(buf
, proto
, protolen
))
4492 while ((p
= strchr(p
, ' ')) != NULL
) {
4495 if (memcmp(p
, key
, keylen
) == 0 &&
4496 (p
[keylen
] == ' ' || p
[keylen
] == '\n'))
4499 if (fgets(buf
, sizeof(buf
), fp
) == NULL
)
4501 if (memcmp(buf
, proto
, protolen
))
4504 while ((p
= strchr(p
, ' ')) != NULL
) {
4507 sscanf(p
, "%d", result
);
4520 /* Get stats from sockstat */
4540 static void get_sockstat_line(char *line
, struct ssummary
*s
)
4542 char id
[256], rem
[256];
4544 if (sscanf(line
, "%[^ ] %[^\n]\n", id
, rem
) != 2)
4547 if (strcmp(id
, "sockets:") == 0)
4548 sscanf(rem
, "%*s%d", &s
->socks
);
4549 else if (strcmp(id
, "UDP:") == 0)
4550 sscanf(rem
, "%*s%d", &s
->udp4
);
4551 else if (strcmp(id
, "UDP6:") == 0)
4552 sscanf(rem
, "%*s%d", &s
->udp6
);
4553 else if (strcmp(id
, "RAW:") == 0)
4554 sscanf(rem
, "%*s%d", &s
->raw4
);
4555 else if (strcmp(id
, "RAW6:") == 0)
4556 sscanf(rem
, "%*s%d", &s
->raw6
);
4557 else if (strcmp(id
, "TCP6:") == 0)
4558 sscanf(rem
, "%*s%d", &s
->tcp6_hashed
);
4559 else if (strcmp(id
, "FRAG:") == 0)
4560 sscanf(rem
, "%*s%d%*s%d", &s
->frag4
, &s
->frag4_mem
);
4561 else if (strcmp(id
, "FRAG6:") == 0)
4562 sscanf(rem
, "%*s%d%*s%d", &s
->frag6
, &s
->frag6_mem
);
4563 else if (strcmp(id
, "TCP:") == 0)
4564 sscanf(rem
, "%*s%d%*s%d%*s%d%*s%d%*s%d",
4566 &s
->tcp_orphans
, &s
->tcp_tws
, &s
->tcp_total
, &s
->tcp_mem
);
4569 static int get_sockstat(struct ssummary
*s
)
4574 memset(s
, 0, sizeof(*s
));
4576 if ((fp
= net_sockstat_open()) == NULL
)
4578 while (fgets(buf
, sizeof(buf
), fp
) != NULL
)
4579 get_sockstat_line(buf
, s
);
4582 if ((fp
= net_sockstat6_open()) == NULL
)
4584 while (fgets(buf
, sizeof(buf
), fp
) != NULL
)
4585 get_sockstat_line(buf
, s
);
4591 static int print_summary(void)
4596 if (get_sockstat(&s
) < 0)
4597 perror("ss: get_sockstat");
4598 if (get_snmp_int("Tcp:", "CurrEstab", &tcp_estab
) < 0)
4599 perror("ss: get_snmpstat");
4601 printf("Total: %d\n", s
.socks
);
4603 printf("TCP: %d (estab %d, closed %d, orphaned %d, timewait %d)\n",
4604 s
.tcp_total
+ s
.tcp_tws
, tcp_estab
,
4605 s
.tcp_total
- (s
.tcp4_hashed
+ s
.tcp6_hashed
- s
.tcp_tws
),
4606 s
.tcp_orphans
, s
.tcp_tws
);
4609 printf("Transport Total IP IPv6\n");
4610 printf("RAW %-9d %-9d %-9d\n", s
.raw4
+s
.raw6
, s
.raw4
, s
.raw6
);
4611 printf("UDP %-9d %-9d %-9d\n", s
.udp4
+s
.udp6
, s
.udp4
, s
.udp6
);
4612 printf("TCP %-9d %-9d %-9d\n", s
.tcp4_hashed
+s
.tcp6_hashed
, s
.tcp4_hashed
, s
.tcp6_hashed
);
4613 printf("INET %-9d %-9d %-9d\n",
4614 s
.raw4
+s
.udp4
+s
.tcp4_hashed
+
4615 s
.raw6
+s
.udp6
+s
.tcp6_hashed
,
4616 s
.raw4
+s
.udp4
+s
.tcp4_hashed
,
4617 s
.raw6
+s
.udp6
+s
.tcp6_hashed
);
4618 printf("FRAG %-9d %-9d %-9d\n", s
.frag4
+s
.frag6
, s
.frag4
, s
.frag6
);
4625 static void _usage(FILE *dest
)
4628 "Usage: ss [ OPTIONS ]\n"
4629 " ss [ OPTIONS ] [ FILTER ]\n"
4630 " -h, --help this message\n"
4631 " -V, --version output version information\n"
4632 " -n, --numeric don't resolve service names\n"
4633 " -r, --resolve resolve host names\n"
4634 " -a, --all display all sockets\n"
4635 " -l, --listening display listening sockets\n"
4636 " -o, --options show timer information\n"
4637 " -e, --extended show detailed socket information\n"
4638 " -m, --memory show socket memory usage\n"
4639 " -p, --processes show process using socket\n"
4640 " -i, --info show internal TCP information\n"
4641 " --tipcinfo show internal tipc socket information\n"
4642 " -s, --summary show socket usage summary\n"
4643 " -b, --bpf show bpf filter socket information\n"
4644 " -E, --events continually display sockets as they are destroyed\n"
4645 " -Z, --context display process SELinux security contexts\n"
4646 " -z, --contexts display process and socket SELinux security contexts\n"
4647 " -N, --net switch to the specified network namespace name\n"
4649 " -4, --ipv4 display only IP version 4 sockets\n"
4650 " -6, --ipv6 display only IP version 6 sockets\n"
4651 " -0, --packet display PACKET sockets\n"
4652 " -t, --tcp display only TCP sockets\n"
4653 " -S, --sctp display only SCTP sockets\n"
4654 " -u, --udp display only UDP sockets\n"
4655 " -d, --dccp display only DCCP sockets\n"
4656 " -w, --raw display only RAW sockets\n"
4657 " -x, --unix display only Unix domain sockets\n"
4658 " --tipc display only TIPC sockets\n"
4659 " --vsock display only vsock sockets\n"
4660 " -f, --family=FAMILY display sockets of type FAMILY\n"
4661 " FAMILY := {inet|inet6|link|unix|netlink|vsock|tipc|help}\n"
4663 " -K, --kill forcibly close sockets, display what was closed\n"
4664 " -H, --no-header Suppress header line\n"
4666 " -A, --query=QUERY, --socket=QUERY\n"
4667 " QUERY := {all|inet|tcp|udp|raw|unix|unix_dgram|unix_stream|unix_seqpacket|packet|netlink|vsock_stream|vsock_dgram|tipc}[,QUERY]\n"
4669 " -D, --diag=FILE Dump raw information about TCP sockets to FILE\n"
4670 " -F, --filter=FILE read filter information from FILE\n"
4671 " FILTER := [ state STATE-FILTER ] [ EXPRESSION ]\n"
4672 " STATE-FILTER := {all|connected|synchronized|bucket|big|TCP-STATES}\n"
4673 " TCP-STATES := {established|syn-sent|syn-recv|fin-wait-{1,2}|time-wait|closed|close-wait|last-ack|listening|closing}\n"
4674 " connected := {established|syn-sent|syn-recv|fin-wait-{1,2}|time-wait|close-wait|last-ack|closing}\n"
4675 " synchronized := {established|syn-recv|fin-wait-{1,2}|time-wait|close-wait|last-ack|closing}\n"
4676 " bucket := {syn-recv|time-wait}\n"
4677 " big := {established|syn-sent|fin-wait-{1,2}|closed|close-wait|last-ack|listening|closing}\n"
4681 static void help(void) __attribute__((noreturn
));
4682 static void help(void)
4688 static void usage(void) __attribute__((noreturn
));
4689 static void usage(void)
4696 static int scan_state(const char *state
)
4698 static const char * const sstate_namel
[] = {
4700 [SS_ESTABLISHED
] = "established",
4701 [SS_SYN_SENT
] = "syn-sent",
4702 [SS_SYN_RECV
] = "syn-recv",
4703 [SS_FIN_WAIT1
] = "fin-wait-1",
4704 [SS_FIN_WAIT2
] = "fin-wait-2",
4705 [SS_TIME_WAIT
] = "time-wait",
4706 [SS_CLOSE
] = "unconnected",
4707 [SS_CLOSE_WAIT
] = "close-wait",
4708 [SS_LAST_ACK
] = "last-ack",
4709 [SS_LISTEN
] = "listening",
4710 [SS_CLOSING
] = "closing",
4714 if (strcasecmp(state
, "close") == 0 ||
4715 strcasecmp(state
, "closed") == 0)
4716 return (1<<SS_CLOSE
);
4717 if (strcasecmp(state
, "syn-rcv") == 0)
4718 return (1<<SS_SYN_RECV
);
4719 if (strcasecmp(state
, "established") == 0)
4720 return (1<<SS_ESTABLISHED
);
4721 if (strcasecmp(state
, "all") == 0)
4723 if (strcasecmp(state
, "connected") == 0)
4724 return SS_ALL
& ~((1<<SS_CLOSE
)|(1<<SS_LISTEN
));
4725 if (strcasecmp(state
, "synchronized") == 0)
4726 return SS_ALL
& ~((1<<SS_CLOSE
)|(1<<SS_LISTEN
)|(1<<SS_SYN_SENT
));
4727 if (strcasecmp(state
, "bucket") == 0)
4728 return (1<<SS_SYN_RECV
)|(1<<SS_TIME_WAIT
);
4729 if (strcasecmp(state
, "big") == 0)
4730 return SS_ALL
& ~((1<<SS_SYN_RECV
)|(1<<SS_TIME_WAIT
));
4731 for (i
= 0; i
< SS_MAX
; i
++) {
4732 if (strcasecmp(state
, sstate_namel
[i
]) == 0)
4736 fprintf(stderr
, "ss: wrong state name: %s\n", state
);
4740 /* Values 'v' and 'V' are already used so a non-character is used */
4741 #define OPT_VSOCK 256
4743 /* Values of 't' are already used so a non-character is used */
4744 #define OPT_TIPCSOCK 257
4745 #define OPT_TIPCINFO 258
4747 static const struct option long_opts
[] = {
4748 { "numeric", 0, 0, 'n' },
4749 { "resolve", 0, 0, 'r' },
4750 { "options", 0, 0, 'o' },
4751 { "extended", 0, 0, 'e' },
4752 { "memory", 0, 0, 'm' },
4753 { "info", 0, 0, 'i' },
4754 { "processes", 0, 0, 'p' },
4755 { "bpf", 0, 0, 'b' },
4756 { "events", 0, 0, 'E' },
4757 { "dccp", 0, 0, 'd' },
4758 { "tcp", 0, 0, 't' },
4759 { "sctp", 0, 0, 'S' },
4760 { "udp", 0, 0, 'u' },
4761 { "raw", 0, 0, 'w' },
4762 { "unix", 0, 0, 'x' },
4763 { "tipc", 0, 0, OPT_TIPCSOCK
},
4764 { "vsock", 0, 0, OPT_VSOCK
},
4765 { "all", 0, 0, 'a' },
4766 { "listening", 0, 0, 'l' },
4767 { "ipv4", 0, 0, '4' },
4768 { "ipv6", 0, 0, '6' },
4769 { "packet", 0, 0, '0' },
4770 { "family", 1, 0, 'f' },
4771 { "socket", 1, 0, 'A' },
4772 { "query", 1, 0, 'A' },
4773 { "summary", 0, 0, 's' },
4774 { "diag", 1, 0, 'D' },
4775 { "filter", 1, 0, 'F' },
4776 { "version", 0, 0, 'V' },
4777 { "help", 0, 0, 'h' },
4778 { "context", 0, 0, 'Z' },
4779 { "contexts", 0, 0, 'z' },
4780 { "net", 1, 0, 'N' },
4781 { "tipcinfo", 0, 0, OPT_TIPCINFO
},
4782 { "kill", 0, 0, 'K' },
4783 { "no-header", 0, 0, 'H' },
4788 int main(int argc
, char *argv
[])
4793 const char *dump_tcpdiag
= NULL
;
4794 FILE *filter_fp
= NULL
;
4796 int state_filter
= 0;
4798 while ((ch
= getopt_long(argc
, argv
,
4799 "dhaletuwxnro460spbEf:miA:D:F:vVzZN:KHS",
4800 long_opts
, NULL
)) != EOF
) {
4803 resolve_services
= 0;
4823 user_ent_hash_build();
4833 filter_db_set(¤t_filter
, DCCP_DB
, true);
4836 filter_db_set(¤t_filter
, TCP_DB
, true);
4839 filter_db_set(¤t_filter
, SCTP_DB
, true);
4842 filter_db_set(¤t_filter
, UDP_DB
, true);
4845 filter_db_set(¤t_filter
, RAW_DB
, true);
4848 filter_af_set(¤t_filter
, AF_UNIX
);
4851 filter_af_set(¤t_filter
, AF_VSOCK
);
4854 filter_af_set(¤t_filter
, AF_TIPC
);
4857 state_filter
= SS_ALL
;
4860 state_filter
= (1 << SS_LISTEN
) | (1 << SS_CLOSE
);
4863 filter_af_set(¤t_filter
, AF_INET
);
4866 filter_af_set(¤t_filter
, AF_INET6
);
4869 filter_af_set(¤t_filter
, AF_PACKET
);
4872 if (strcmp(optarg
, "inet") == 0)
4873 filter_af_set(¤t_filter
, AF_INET
);
4874 else if (strcmp(optarg
, "inet6") == 0)
4875 filter_af_set(¤t_filter
, AF_INET6
);
4876 else if (strcmp(optarg
, "link") == 0)
4877 filter_af_set(¤t_filter
, AF_PACKET
);
4878 else if (strcmp(optarg
, "unix") == 0)
4879 filter_af_set(¤t_filter
, AF_UNIX
);
4880 else if (strcmp(optarg
, "netlink") == 0)
4881 filter_af_set(¤t_filter
, AF_NETLINK
);
4882 else if (strcmp(optarg
, "tipc") == 0)
4883 filter_af_set(¤t_filter
, AF_TIPC
);
4884 else if (strcmp(optarg
, "vsock") == 0)
4885 filter_af_set(¤t_filter
, AF_VSOCK
);
4886 else if (strcmp(optarg
, "help") == 0)
4889 fprintf(stderr
, "ss: \"%s\" is invalid family\n",
4899 current_filter
.dbs
= 0;
4900 state_filter
= state_filter
?
4901 state_filter
: SS_CONN
;
4907 if ((p1
= strchr(p
, ',')) != NULL
)
4909 if (filter_db_parse(¤t_filter
, p
)) {
4910 fprintf(stderr
, "ss: \"%s\" is illegal socket table id\n", p
);
4921 dump_tcpdiag
= optarg
;
4925 fprintf(stderr
, "More than one filter file\n");
4928 if (optarg
[0] == '-')
4931 filter_fp
= fopen(optarg
, "r");
4933 perror("fopen filter file");
4939 printf("ss utility, iproute2-ss%s\n", SNAPSHOT
);
4945 if (is_selinux_enabled() <= 0) {
4946 fprintf(stderr
, "ss: SELinux is not enabled.\n");
4950 user_ent_hash_build();
4953 if (netns_switch(optarg
))
4960 current_filter
.kill
= 1;
4978 if (do_default
&& argc
== 0)
4983 if (strcmp(*argv
, "state") == 0) {
4987 state_filter
|= scan_state(*argv
);
4989 } else if (strcmp(*argv
, "exclude") == 0 ||
4990 strcmp(*argv
, "excl") == 0) {
4993 state_filter
= SS_ALL
;
4994 state_filter
&= ~scan_state(*argv
);
5003 state_filter
= state_filter
? state_filter
: SS_CONN
;
5004 filter_db_parse(¤t_filter
, "all");
5007 filter_states_set(¤t_filter
, state_filter
);
5008 filter_merge_defaults(¤t_filter
);
5010 if (resolve_services
&& resolve_hosts
&&
5011 (current_filter
.dbs
& (UNIX_DBM
|INET_L4_DBM
)))
5012 init_service_resolver();
5014 if (current_filter
.dbs
== 0) {
5015 fprintf(stderr
, "ss: no socket tables to show with such filter.\n");
5018 if (current_filter
.families
== 0) {
5019 fprintf(stderr
, "ss: no families to show with such filter.\n");
5022 if (current_filter
.states
== 0) {
5023 fprintf(stderr
, "ss: no socket states to show with such filter.\n");
5028 FILE *dump_fp
= stdout
;
5030 if (!(current_filter
.dbs
& (1<<TCP_DB
))) {
5031 fprintf(stderr
, "ss: tcpdiag dump requested and no tcp in filter.\n");
5034 if (dump_tcpdiag
[0] != '-') {
5035 dump_fp
= fopen(dump_tcpdiag
, "w");
5036 if (!dump_tcpdiag
) {
5037 perror("fopen dump file");
5041 inet_show_netlink(¤t_filter
, dump_fp
, IPPROTO_TCP
);
5046 if (ssfilter_parse(¤t_filter
.f
, argc
, argv
, filter_fp
))
5049 if (!(current_filter
.dbs
& (current_filter
.dbs
- 1)))
5050 columns
[COL_NETID
].disabled
= 1;
5052 if (!(current_filter
.states
& (current_filter
.states
- 1)))
5053 columns
[COL_STATE
].disabled
= 1;
5061 exit(handle_follow_request(¤t_filter
));
5063 if (current_filter
.dbs
& (1<<NETLINK_DB
))
5064 netlink_show(¤t_filter
);
5065 if (current_filter
.dbs
& PACKET_DBM
)
5066 packet_show(¤t_filter
);
5067 if (current_filter
.dbs
& UNIX_DBM
)
5068 unix_show(¤t_filter
);
5069 if (current_filter
.dbs
& (1<<RAW_DB
))
5070 raw_show(¤t_filter
);
5071 if (current_filter
.dbs
& (1<<UDP_DB
))
5072 udp_show(¤t_filter
);
5073 if (current_filter
.dbs
& (1<<TCP_DB
))
5074 tcp_show(¤t_filter
);
5075 if (current_filter
.dbs
& (1<<DCCP_DB
))
5076 dccp_show(¤t_filter
);
5077 if (current_filter
.dbs
& (1<<SCTP_DB
))
5078 sctp_show(¤t_filter
);
5079 if (current_filter
.dbs
& VSOCK_DBM
)
5080 vsock_show(¤t_filter
);
5081 if (current_filter
.dbs
& (1<<TIPC_DB
))
5082 tipc_show(¤t_filter
);
5084 if (show_users
|| show_proc_ctx
|| show_sock_ctx
)