2 * ss.c "sockstat", socket statistics
4 * This program is free software; you can redistribute it and/or
5 * modify it under the terms of the GNU General Public License
6 * as published by the Free Software Foundation; either version
7 * 2 of the License, or (at your option) any later version.
9 * Authors: Alexey Kuznetsov, <kuznet@ms2.inr.ac.ru>
16 #include <sys/ioctl.h>
17 #include <sys/socket.h>
19 #include <sys/sysmacros.h>
20 #include <netinet/in.h>
24 #include <arpa/inet.h>
35 #include "libnetlink.h"
36 #include "namespace.h"
39 #include <linux/tcp.h>
40 #include <linux/sock_diag.h>
41 #include <linux/inet_diag.h>
42 #include <linux/unix_diag.h>
43 #include <linux/netdevice.h> /* for MAX_ADDR_LEN */
44 #include <linux/filter.h>
45 #include <linux/packet_diag.h>
46 #include <linux/netlink_diag.h>
47 #include <linux/sctp.h>
48 #include <linux/vm_sockets_diag.h>
49 #include <linux/net.h>
50 #include <linux/tipc.h>
51 #include <linux/tipc_netlink.h>
52 #include <linux/tipc_sockets_diag.h>
54 /* AF_VSOCK/PF_VSOCK is only provided since glibc 2.18 */
59 #define AF_VSOCK PF_VSOCK
62 #define MAGIC_SEQ 123456
63 #define BUF_CHUNK (1024 * 1024) /* Buffer chunk allocation size */
64 #define BUF_CHUNKS_MAX 5 /* Maximum number of allocated buffer chunks */
65 #define LEN_ALIGN(x) (((x) + 1) & ~1)
67 #define DIAG_REQUEST(_req, _r) \
69 struct nlmsghdr nlh; \
73 .nlmsg_type = SOCK_DIAG_BY_FAMILY, \
74 .nlmsg_flags = NLM_F_ROOT|NLM_F_MATCH|NLM_F_REQUEST,\
75 .nlmsg_seq = MAGIC_SEQ, \
76 .nlmsg_len = sizeof(_req), \
81 #include <selinux/selinux.h>
83 /* Stubs for SELinux functions */
84 static int is_selinux_enabled(void)
89 static int getpidcon(pid_t pid
, char **context
)
95 static int getfilecon(char *path
, char **context
)
101 static int security_get_initial_context(char *name
, char **context
)
108 static int resolve_services
= 1;
109 int preferred_family
= AF_UNSPEC
;
110 static int show_options
;
112 static int show_users
;
114 static int show_tcpinfo
;
116 static int show_proc_ctx
;
117 static int show_sock_ctx
;
118 static int show_header
= 1;
119 static int follow_events
;
121 static int show_tipcinfo
;
144 const enum col_align align
;
148 int width
; /* Calculated, including additional layout spacing */
149 int max_len
; /* Measured maximum field length in this column */
152 static struct column columns
[] = {
153 { ALIGN_LEFT
, "Netid", "", 0, 0, 0 },
154 { ALIGN_LEFT
, "State", " ", 0, 0, 0 },
155 { ALIGN_LEFT
, "Recv-Q", " ", 0, 0, 0 },
156 { ALIGN_LEFT
, "Send-Q", " ", 0, 0, 0 },
157 { ALIGN_RIGHT
, "Local Address:", " ", 0, 0, 0 },
158 { ALIGN_LEFT
, "Port", "", 0, 0, 0 },
159 { ALIGN_RIGHT
, "Peer Address:", " ", 0, 0, 0 },
160 { ALIGN_LEFT
, "Port", "", 0, 0, 0 },
161 { ALIGN_LEFT
, "", "", 0, 0, 0 },
164 static struct column
*current_field
= columns
;
166 /* Output buffer: chained chunks of BUF_CHUNK bytes. Each field is written to
167 * the buffer as a variable size token. A token consists of a 16 bits length
168 * field, followed by a string which is not NULL-terminated.
170 * A new chunk is allocated and linked when the current chunk doesn't have
171 * enough room to store the current token as a whole.
174 struct buf_chunk
*next
; /* Next chained chunk */
175 char *end
; /* Current end of content */
180 uint16_t len
; /* Data length, excluding length descriptor */
185 struct buf_token
*cur
; /* Position of current token in chunk */
186 struct buf_chunk
*head
; /* First chunk */
187 struct buf_chunk
*tail
; /* Current chunk */
188 int chunks
; /* Number of allocated chunks */
191 static const char *TCP_PROTO
= "tcp";
192 static const char *SCTP_PROTO
= "sctp";
193 static const char *UDP_PROTO
= "udp";
194 static const char *RAW_PROTO
= "raw";
195 static const char *dg_proto
;
215 #define PACKET_DBM ((1<<PACKET_DG_DB)|(1<<PACKET_R_DB))
216 #define UNIX_DBM ((1<<UNIX_DG_DB)|(1<<UNIX_ST_DB)|(1<<UNIX_SQ_DB))
217 #define ALL_DB ((1<<MAX_DB)-1)
218 #define INET_L4_DBM ((1<<TCP_DB)|(1<<UDP_DB)|(1<<DCCP_DB)|(1<<SCTP_DB))
219 #define INET_DBM (INET_L4_DBM | (1<<RAW_DB))
220 #define VSOCK_DBM ((1<<VSOCK_ST_DB)|(1<<VSOCK_DG_DB))
239 SCTP_STATE_CLOSED
= 0,
240 SCTP_STATE_COOKIE_WAIT
= 1,
241 SCTP_STATE_COOKIE_ECHOED
= 2,
242 SCTP_STATE_ESTABLISHED
= 3,
243 SCTP_STATE_SHUTDOWN_PENDING
= 4,
244 SCTP_STATE_SHUTDOWN_SENT
= 5,
245 SCTP_STATE_SHUTDOWN_RECEIVED
= 6,
246 SCTP_STATE_SHUTDOWN_ACK_SENT
= 7,
249 #define SS_ALL ((1 << SS_MAX) - 1)
250 #define SS_CONN (SS_ALL & ~((1<<SS_LISTEN)|(1<<SS_CLOSE)|(1<<SS_TIME_WAIT)|(1<<SS_SYN_RECV)))
251 #define TIPC_SS_CONN ((1<<SS_ESTABLISHED)|(1<<SS_LISTEN)|(1<<SS_CLOSE))
253 #include "ssfilter.h"
261 struct rtnl_handle
*rth_for_killing
;
264 #define FAMILY_MASK(family) ((uint64_t)1 << (family))
266 static const struct filter default_dbs
[MAX_DB
] = {
269 .families
= FAMILY_MASK(AF_INET
) | FAMILY_MASK(AF_INET6
),
273 .families
= FAMILY_MASK(AF_INET
) | FAMILY_MASK(AF_INET6
),
276 .states
= (1 << SS_ESTABLISHED
),
277 .families
= FAMILY_MASK(AF_INET
) | FAMILY_MASK(AF_INET6
),
280 .states
= (1 << SS_ESTABLISHED
),
281 .families
= FAMILY_MASK(AF_INET
) | FAMILY_MASK(AF_INET6
),
284 .states
= (1 << SS_CLOSE
),
285 .families
= FAMILY_MASK(AF_UNIX
),
289 .families
= FAMILY_MASK(AF_UNIX
),
293 .families
= FAMILY_MASK(AF_UNIX
),
296 .states
= (1 << SS_CLOSE
),
297 .families
= FAMILY_MASK(AF_PACKET
),
300 .states
= (1 << SS_CLOSE
),
301 .families
= FAMILY_MASK(AF_PACKET
),
304 .states
= (1 << SS_CLOSE
),
305 .families
= FAMILY_MASK(AF_NETLINK
),
309 .families
= FAMILY_MASK(AF_INET
) | FAMILY_MASK(AF_INET6
),
313 .families
= FAMILY_MASK(AF_VSOCK
),
317 .families
= FAMILY_MASK(AF_VSOCK
),
320 .states
= TIPC_SS_CONN
,
321 .families
= FAMILY_MASK(AF_TIPC
),
325 static const struct filter default_afs
[AF_MAX
] = {
340 .states
= (1 << SS_CLOSE
),
343 .dbs
= (1 << NETLINK_DB
),
344 .states
= (1 << SS_CLOSE
),
351 .dbs
= (1 << TIPC_DB
),
352 .states
= TIPC_SS_CONN
,
356 static int do_default
= 1;
357 static struct filter current_filter
;
359 static void filter_db_set(struct filter
*f
, int db
, bool enable
)
362 f
->states
|= default_dbs
[db
].states
;
365 f
->dbs
&= ~(1 << db
);
370 static int filter_db_parse(struct filter
*f
, const char *s
)
376 #define ENTRY(name, ...) { #name, { __VA_ARGS__, MAX_DB } }
377 ENTRY(all
, UDP_DB
, DCCP_DB
, TCP_DB
, RAW_DB
,
378 UNIX_ST_DB
, UNIX_DG_DB
, UNIX_SQ_DB
,
379 PACKET_R_DB
, PACKET_DG_DB
, NETLINK_DB
,
380 SCTP_DB
, VSOCK_ST_DB
, VSOCK_DG_DB
),
381 ENTRY(inet
, UDP_DB
, DCCP_DB
, TCP_DB
, SCTP_DB
, RAW_DB
),
383 ENTRY(dccp
, DCCP_DB
),
385 ENTRY(sctp
, SCTP_DB
),
387 ENTRY(unix
, UNIX_ST_DB
, UNIX_DG_DB
, UNIX_SQ_DB
),
388 ENTRY(unix_stream
, UNIX_ST_DB
),
389 ENTRY(u_str
, UNIX_ST_DB
), /* alias for unix_stream */
390 ENTRY(unix_dgram
, UNIX_DG_DB
),
391 ENTRY(u_dgr
, UNIX_DG_DB
), /* alias for unix_dgram */
392 ENTRY(unix_seqpacket
, UNIX_SQ_DB
),
393 ENTRY(u_seq
, UNIX_SQ_DB
), /* alias for unix_seqpacket */
394 ENTRY(packet
, PACKET_R_DB
, PACKET_DG_DB
),
395 ENTRY(packet_raw
, PACKET_R_DB
),
396 ENTRY(p_raw
, PACKET_R_DB
), /* alias for packet_raw */
397 ENTRY(packet_dgram
, PACKET_DG_DB
),
398 ENTRY(p_dgr
, PACKET_DG_DB
), /* alias for packet_dgram */
399 ENTRY(netlink
, NETLINK_DB
),
400 ENTRY(vsock
, VSOCK_ST_DB
, VSOCK_DG_DB
),
401 ENTRY(vsock_stream
, VSOCK_ST_DB
),
402 ENTRY(v_str
, VSOCK_ST_DB
), /* alias for vsock_stream */
403 ENTRY(vsock_dgram
, VSOCK_DG_DB
),
404 ENTRY(v_dgr
, VSOCK_DG_DB
), /* alias for vsock_dgram */
415 for (i
= 0; i
< ARRAY_SIZE(db_name_tbl
); i
++) {
416 if (strcmp(s
, db_name_tbl
[i
].name
))
418 for (dbp
= db_name_tbl
[i
].dbs
; *dbp
!= MAX_DB
; dbp
++)
419 filter_db_set(f
, *dbp
, enable
);
425 static void filter_af_set(struct filter
*f
, int af
)
427 f
->states
|= default_afs
[af
].states
;
428 f
->families
|= FAMILY_MASK(af
);
430 preferred_family
= af
;
433 static int filter_af_get(struct filter
*f
, int af
)
435 return !!(f
->families
& FAMILY_MASK(af
));
438 static void filter_states_set(struct filter
*f
, int states
)
444 static void filter_merge_defaults(struct filter
*f
)
449 for (db
= 0; db
< MAX_DB
; db
++) {
450 if (!(f
->dbs
& (1 << db
)))
453 if (!(default_dbs
[db
].families
& f
->families
))
454 f
->families
|= default_dbs
[db
].families
;
456 for (af
= 0; af
< AF_MAX
; af
++) {
457 if (!(f
->families
& FAMILY_MASK(af
)))
460 if (!(default_afs
[af
].dbs
& f
->dbs
))
461 f
->dbs
|= default_afs
[af
].dbs
;
465 static FILE *generic_proc_open(const char *env
, const char *name
)
467 const char *p
= getenv(env
);
471 p
= getenv("PROC_ROOT") ? : "/proc";
472 snprintf(store
, sizeof(store
)-1, "%s/%s", p
, name
);
476 return fopen(p
, "r");
478 #define net_tcp_open() generic_proc_open("PROC_NET_TCP", "net/tcp")
479 #define net_tcp6_open() generic_proc_open("PROC_NET_TCP6", "net/tcp6")
480 #define net_udp_open() generic_proc_open("PROC_NET_UDP", "net/udp")
481 #define net_udp6_open() generic_proc_open("PROC_NET_UDP6", "net/udp6")
482 #define net_raw_open() generic_proc_open("PROC_NET_RAW", "net/raw")
483 #define net_raw6_open() generic_proc_open("PROC_NET_RAW6", "net/raw6")
484 #define net_unix_open() generic_proc_open("PROC_NET_UNIX", "net/unix")
485 #define net_packet_open() generic_proc_open("PROC_NET_PACKET", \
487 #define net_netlink_open() generic_proc_open("PROC_NET_NETLINK", \
489 #define net_sockstat_open() generic_proc_open("PROC_NET_SOCKSTAT", \
491 #define net_sockstat6_open() generic_proc_open("PROC_NET_SOCKSTAT6", \
493 #define net_snmp_open() generic_proc_open("PROC_NET_SNMP", "net/snmp")
494 #define ephemeral_ports_open() generic_proc_open("PROC_IP_LOCAL_PORT_RANGE", \
495 "sys/net/ipv4/ip_local_port_range")
498 struct user_ent
*next
;
507 #define USER_ENT_HASH_SIZE 256
508 static struct user_ent
*user_ent_hash
[USER_ENT_HASH_SIZE
];
510 static int user_ent_hashfn(unsigned int ino
)
512 int val
= (ino
>> 24) ^ (ino
>> 16) ^ (ino
>> 8) ^ ino
;
514 return val
& (USER_ENT_HASH_SIZE
- 1);
517 static void user_ent_add(unsigned int ino
, char *process
,
522 struct user_ent
*p
, **pp
;
524 p
= malloc(sizeof(struct user_ent
));
526 fprintf(stderr
, "ss: failed to malloc buffer\n");
533 p
->process
= strdup(process
);
534 p
->process_ctx
= strdup(proc_ctx
);
535 p
->socket_ctx
= strdup(sock_ctx
);
537 pp
= &user_ent_hash
[user_ent_hashfn(ino
)];
542 static void user_ent_destroy(void)
544 struct user_ent
*p
, *p_next
;
547 while (cnt
!= USER_ENT_HASH_SIZE
) {
548 p
= user_ent_hash
[cnt
];
551 free(p
->process_ctx
);
561 static void user_ent_hash_build(void)
563 const char *root
= getenv("PROC_ROOT") ? : "/proc/";
570 const char *no_ctx
= "unavailable";
571 static int user_ent_hash_build_init
;
573 /* If show_users & show_proc_ctx set only do this once */
574 if (user_ent_hash_build_init
!= 0)
577 user_ent_hash_build_init
= 1;
579 strlcpy(name
, root
, sizeof(name
));
581 if (strlen(name
) == 0 || name
[strlen(name
)-1] != '/')
584 nameoff
= strlen(name
);
590 while ((d
= readdir(dir
)) != NULL
) {
598 if (sscanf(d
->d_name
, "%d%c", &pid
, &crap
) != 1)
601 if (getpidcon(pid
, &pid_context
) != 0)
602 pid_context
= strdup(no_ctx
);
604 snprintf(name
+ nameoff
, sizeof(name
) - nameoff
, "%d/fd/", pid
);
606 if ((dir1
= opendir(name
)) == NULL
) {
614 while ((d1
= readdir(dir1
)) != NULL
) {
615 const char *pattern
= "socket:[";
622 if (sscanf(d1
->d_name
, "%d%c", &fd
, &crap
) != 1)
625 snprintf(name
+pos
, sizeof(name
) - pos
, "%d", fd
);
627 link_len
= readlink(name
, lnk
, sizeof(lnk
)-1);
630 lnk
[link_len
] = '\0';
632 if (strncmp(lnk
, pattern
, strlen(pattern
)))
635 sscanf(lnk
, "socket:[%u]", &ino
);
637 snprintf(tmp
, sizeof(tmp
), "%s/%d/fd/%s",
638 root
, pid
, d1
->d_name
);
640 if (getfilecon(tmp
, &sock_context
) <= 0)
641 sock_context
= strdup(no_ctx
);
646 snprintf(tmp
, sizeof(tmp
), "%s/%d/stat",
648 if ((fp
= fopen(tmp
, "r")) != NULL
) {
649 if (fscanf(fp
, "%*d (%[^)])", p
) < 1)
654 user_ent_add(ino
, p
, pid
, fd
,
655 pid_context
, sock_context
);
670 #define ENTRY_BUF_SIZE 512
671 static int find_entry(unsigned int ino
, char **buf
, int type
)
677 int len
, new_buf_len
;
684 p
= user_ent_hash
[user_ent_hashfn(ino
)];
691 ptr
= *buf
+ buf_used
;
694 len
= snprintf(ptr
, buf_len
- buf_used
,
695 "(\"%s\",pid=%d,fd=%d),",
696 p
->process
, p
->pid
, p
->fd
);
699 len
= snprintf(ptr
, buf_len
- buf_used
,
700 "(\"%s\",pid=%d,proc_ctx=%s,fd=%d),",
702 p
->process_ctx
, p
->fd
);
705 len
= snprintf(ptr
, buf_len
- buf_used
,
706 "(\"%s\",pid=%d,proc_ctx=%s,fd=%d,sock_ctx=%s),",
708 p
->process_ctx
, p
->fd
,
712 fprintf(stderr
, "ss: invalid type: %d\n", type
);
716 if (len
< 0 || len
>= buf_len
- buf_used
) {
717 new_buf_len
= buf_len
+ ENTRY_BUF_SIZE
;
718 new_buf
= realloc(*buf
, new_buf_len
);
720 fprintf(stderr
, "ss: failed to malloc buffer\n");
724 buf_len
= new_buf_len
;
736 ptr
= *buf
+ buf_used
;
742 static unsigned long long cookie_sk_get(const uint32_t *cookie
)
744 return (((unsigned long long)cookie
[1] << 31) << 1) | cookie
[0];
747 static const char *sctp_sstate_name
[] = {
748 [SCTP_STATE_CLOSED
] = "CLOSED",
749 [SCTP_STATE_COOKIE_WAIT
] = "COOKIE_WAIT",
750 [SCTP_STATE_COOKIE_ECHOED
] = "COOKIE_ECHOED",
751 [SCTP_STATE_ESTABLISHED
] = "ESTAB",
752 [SCTP_STATE_SHUTDOWN_PENDING
] = "SHUTDOWN_PENDING",
753 [SCTP_STATE_SHUTDOWN_SENT
] = "SHUTDOWN_SENT",
754 [SCTP_STATE_SHUTDOWN_RECEIVED
] = "SHUTDOWN_RECEIVED",
755 [SCTP_STATE_SHUTDOWN_ACK_SENT
] = "ACK_SENT",
758 static const char * const stype_nameg
[] = {
760 [SOCK_STREAM
] = "STREAM",
761 [SOCK_DGRAM
] = "DGRAM",
763 [SOCK_SEQPACKET
] = "SEQPACKET",
767 struct sockstat
*next
;
781 unsigned long long sk
;
788 unsigned int ce_state
;
798 unsigned int timeout
;
801 double rto
, ato
, rtt
, rttvar
;
802 int qack
, ssthresh
, backoff
;
811 unsigned int lastsnd
;
812 unsigned int lastrcv
;
813 unsigned int lastack
;
815 double pacing_rate_max
;
816 double delivery_rate
;
817 unsigned long long bytes_acked
;
818 unsigned long long bytes_received
;
819 unsigned int segs_out
;
820 unsigned int segs_in
;
821 unsigned int data_segs_out
;
822 unsigned int data_segs_in
;
823 unsigned int unacked
;
824 unsigned int retrans
;
825 unsigned int retrans_total
;
828 unsigned int fackets
;
829 unsigned int reordering
;
830 unsigned int not_sent
;
831 unsigned int delivered
;
832 unsigned int delivered_ce
;
833 unsigned int dsack_dups
;
834 unsigned int reord_seen
;
838 unsigned int rcv_ssthresh
;
839 unsigned long long busy_time
;
840 unsigned long long rwnd_limited
;
841 unsigned long long sndbuf_limited
;
842 unsigned long long bytes_sent
;
843 unsigned long long bytes_retrans
;
847 bool has_ecnseen_opt
;
848 bool has_fastopen_opt
;
851 struct dctcpstat
*dctcp
;
852 struct tcp_bbr_info
*bbr_info
;
855 /* SCTP assocs share the same inode number with their parent endpoint. So if we
856 * have seen the inode number before, it must be an assoc instead of the next
858 static bool is_sctp_assoc(struct sockstat
*s
, const char *sock_name
)
860 if (strcmp(sock_name
, "sctp"))
862 if (!sctp_ino
|| sctp_ino
!= s
->ino
)
867 static const char *unix_netid_name(int type
)
880 static const char *proto_name(int protocol
)
900 static const char *vsock_netid_name(int type
)
912 static const char *tipc_netid_name(int type
)
928 /* Allocate and initialize a new buffer chunk */
929 static struct buf_chunk
*buf_chunk_new(void)
931 struct buf_chunk
*new = malloc(BUF_CHUNK
);
938 /* This is also the last block */
941 /* Next token will be stored at the beginning of chunk data area, and
942 * its initial length is zero.
944 buffer
.cur
= (struct buf_token
*)new->data
;
947 new->end
= buffer
.cur
->data
;
954 /* Return available tail room in given chunk */
955 static int buf_chunk_avail(struct buf_chunk
*chunk
)
957 return BUF_CHUNK
- offsetof(struct buf_chunk
, data
) -
958 (chunk
->end
- chunk
->data
);
961 /* Update end pointer and token length, link new chunk if we hit the end of the
962 * current one. Return -EAGAIN if we got a new chunk, caller has to print again.
964 static int buf_update(int len
)
966 struct buf_chunk
*chunk
= buffer
.tail
;
967 struct buf_token
*t
= buffer
.cur
;
969 /* Claim success if new content fits in the current chunk, and anyway
970 * if this is the first token in the chunk: in the latter case,
971 * allocating a new chunk won't help, so we'll just cut the output.
973 if ((len
< buf_chunk_avail(chunk
) && len
!= -1 /* glibc < 2.0.6 */) ||
974 t
== (struct buf_token
*)chunk
->data
) {
975 len
= min(len
, buf_chunk_avail(chunk
));
977 /* Total field length can't exceed 2^16 bytes, cut as needed */
978 len
= min(len
, USHRT_MAX
- t
->len
);
985 /* Content truncated, time to allocate more */
986 chunk
->next
= buf_chunk_new();
988 /* Copy current token over to new chunk, including length descriptor */
989 memcpy(chunk
->next
->data
, t
, sizeof(t
->len
) + t
->len
);
990 chunk
->next
->end
+= t
->len
;
992 /* Discard partially written field in old chunk */
993 chunk
->end
-= t
->len
+ sizeof(t
->len
);
998 /* Append content to buffer as part of the current field */
999 __attribute__((format(printf
, 1, 2)))
1000 static void out(const char *fmt
, ...)
1002 struct column
*f
= current_field
;
1011 buffer
.head
= buf_chunk_new();
1013 again
: /* Append to buffer: if we have a new chunk, print again */
1015 pos
= buffer
.cur
->data
+ buffer
.cur
->len
;
1016 va_start(args
, fmt
);
1018 /* Limit to tail room. If we hit the limit, buf_update() will tell us */
1019 len
= vsnprintf(pos
, buf_chunk_avail(buffer
.tail
), fmt
, args
);
1022 if (buf_update(len
))
1026 static int print_left_spacing(struct column
*f
, int stored
, int printed
)
1030 if (!f
->width
|| f
->align
== ALIGN_LEFT
)
1033 s
= f
->width
- stored
- printed
;
1034 if (f
->align
== ALIGN_CENTER
)
1035 /* If count of total spacing is odd, shift right by one */
1039 return printf("%*c", s
, ' ');
1044 static void print_right_spacing(struct column
*f
, int printed
)
1048 if (!f
->width
|| f
->align
== ALIGN_RIGHT
)
1051 s
= f
->width
- printed
;
1052 if (f
->align
== ALIGN_CENTER
)
1056 printf("%*c", s
, ' ');
1059 /* Done with field: update buffer pointer, start new token after current one */
1060 static void field_flush(struct column
*f
)
1062 struct buf_chunk
*chunk
;
1068 chunk
= buffer
.tail
;
1069 pad
= buffer
.cur
->len
% 2;
1071 if (buffer
.cur
->len
> f
->max_len
)
1072 f
->max_len
= buffer
.cur
->len
;
1074 /* We need a new chunk if we can't store the next length descriptor.
1075 * Mind the gap between end of previous token and next aligned position
1076 * for length descriptor.
1078 if (buf_chunk_avail(chunk
) - pad
< sizeof(buffer
.cur
->len
)) {
1080 chunk
->next
= buf_chunk_new();
1084 buffer
.cur
= (struct buf_token
*)(buffer
.cur
->data
+
1085 LEN_ALIGN(buffer
.cur
->len
));
1086 buffer
.cur
->len
= 0;
1087 buffer
.tail
->end
= buffer
.cur
->data
;
1090 static int field_is_last(struct column
*f
)
1092 return f
- columns
== COL_MAX
- 1;
1095 /* Get the next available token in the buffer starting from the current token */
1096 static struct buf_token
*buf_token_next(struct buf_token
*cur
)
1098 struct buf_chunk
*chunk
= buffer
.tail
;
1100 /* If we reached the end of chunk contents, get token from next chunk */
1101 if (cur
->data
+ LEN_ALIGN(cur
->len
) == chunk
->end
) {
1102 buffer
.tail
= chunk
= chunk
->next
;
1103 return chunk
? (struct buf_token
*)chunk
->data
: NULL
;
1106 return (struct buf_token
*)(cur
->data
+ LEN_ALIGN(cur
->len
));
1109 /* Free up all allocated buffer chunks */
1110 static void buf_free_all(void)
1112 struct buf_chunk
*tmp
;
1114 for (buffer
.tail
= buffer
.head
; buffer
.tail
; ) {
1116 buffer
.tail
= buffer
.tail
->next
;
1123 /* Get current screen width, default to 80 columns if TIOCGWINSZ fails */
1124 static int render_screen_width(void)
1128 if (isatty(STDOUT_FILENO
)) {
1131 if (ioctl(STDOUT_FILENO
, TIOCGWINSZ
, &w
) != -1) {
1140 /* Calculate column width from contents length. If columns don't fit on one
1141 * line, break them into the least possible amount of lines and keep them
1142 * aligned across lines. Available screen space is equally spread between fields
1143 * as additional spacing.
1145 static void render_calc_width(void)
1147 int screen_width
= render_screen_width();
1148 struct column
*c
, *eol
= columns
- 1;
1149 int first
, len
= 0, linecols
= 0;
1151 /* First pass: set width for each column to measured content length */
1152 for (first
= 1, c
= columns
; c
- columns
< COL_MAX
; c
++) {
1156 if (!first
&& c
->max_len
)
1157 c
->width
= c
->max_len
+ strlen(c
->ldelim
);
1159 c
->width
= c
->max_len
;
1161 /* But don't exceed screen size. If we exceed the screen size
1162 * for even a single field, it will just start on a line of its
1163 * own and then naturally wrap.
1165 c
->width
= min(c
->width
, screen_width
);
1171 /* Second pass: find out newlines and distribute available spacing */
1172 for (c
= columns
; c
- columns
< COL_MAX
; c
++) {
1173 int pad
, spacing
, rem
, last
;
1182 for (last
= 1, tmp
= c
+ 1; tmp
- columns
< COL_MAX
; tmp
++) {
1189 if (!last
&& len
< screen_width
) {
1190 /* Columns fit on screen so far, nothing to do yet */
1194 if (len
== screen_width
) {
1195 /* Exact fit, just start with new line */
1199 if (len
> screen_width
) {
1200 /* Screen width exceeded: go back one column */
1206 /* Distribute remaining space to columns on this line */
1207 pad
= screen_width
- len
;
1208 spacing
= pad
/ linecols
;
1209 rem
= pad
% linecols
;
1210 for (tmp
= c
; tmp
> eol
; tmp
--) {
1214 tmp
->width
+= spacing
;
1222 /* Line break: reset line counters, mark end-of-line */
1229 /* Render buffered output with spacing and delimiters, then free up buffers */
1230 static void render(void)
1232 struct buf_token
*token
;
1233 int printed
, line_started
= 0;
1239 token
= (struct buf_token
*)buffer
.head
->data
;
1241 /* Ensure end alignment of last token, it wasn't necessarily flushed */
1242 buffer
.tail
->end
+= buffer
.cur
->len
% 2;
1244 render_calc_width();
1246 /* Rewind and replay */
1247 buffer
.tail
= buffer
.head
;
1254 /* Print left delimiter only if we already started a line */
1256 printed
= printf("%s", f
->ldelim
);
1260 /* Print field content from token data with spacing */
1261 printed
+= print_left_spacing(f
, token
->len
, printed
);
1262 printed
+= fwrite(token
->data
, 1, token
->len
, stdout
);
1263 print_right_spacing(f
, printed
);
1265 /* Go to next non-empty field, deal with end-of-line */
1267 if (field_is_last(f
)) {
1274 } while (f
->disabled
);
1276 token
= buf_token_next(token
);
1280 current_field
= columns
;
1283 /* Move to next field, and render buffer if we reached the maximum number of
1284 * chunks, at the last field in a line.
1286 static void field_next(void)
1288 if (field_is_last(current_field
) && buffer
.chunks
>= BUF_CHUNKS_MAX
) {
1293 field_flush(current_field
);
1294 if (field_is_last(current_field
))
1295 current_field
= columns
;
1300 /* Walk through fields and flush them until we reach the desired one */
1301 static void field_set(enum col_id id
)
1303 while (id
!= current_field
- columns
)
1307 /* Print header for all non-empty columns */
1308 static void print_header(void)
1310 while (!field_is_last(current_field
)) {
1311 if (!current_field
->disabled
)
1312 out("%s", current_field
->header
);
1317 static void sock_state_print(struct sockstat
*s
)
1319 const char *sock_name
;
1320 static const char * const sstate_name
[] = {
1322 [SS_ESTABLISHED
] = "ESTAB",
1323 [SS_SYN_SENT
] = "SYN-SENT",
1324 [SS_SYN_RECV
] = "SYN-RECV",
1325 [SS_FIN_WAIT1
] = "FIN-WAIT-1",
1326 [SS_FIN_WAIT2
] = "FIN-WAIT-2",
1327 [SS_TIME_WAIT
] = "TIME-WAIT",
1328 [SS_CLOSE
] = "UNCONN",
1329 [SS_CLOSE_WAIT
] = "CLOSE-WAIT",
1330 [SS_LAST_ACK
] = "LAST-ACK",
1331 [SS_LISTEN
] = "LISTEN",
1332 [SS_CLOSING
] = "CLOSING",
1335 switch (s
->local
.family
) {
1337 sock_name
= unix_netid_name(s
->type
);
1341 sock_name
= proto_name(s
->type
);
1344 sock_name
= s
->type
== SOCK_RAW
? "p_raw" : "p_dgr";
1350 sock_name
= tipc_netid_name(s
->type
);
1353 sock_name
= vsock_netid_name(s
->type
);
1356 sock_name
= "unknown";
1359 if (is_sctp_assoc(s
, sock_name
)) {
1360 field_set(COL_STATE
); /* Empty Netid field */
1361 out("`- %s", sctp_sstate_name
[s
->state
]);
1363 field_set(COL_NETID
);
1364 out("%s", sock_name
);
1365 field_set(COL_STATE
);
1366 out("%s", sstate_name
[s
->state
]);
1369 field_set(COL_RECVQ
);
1371 field_set(COL_SENDQ
);
1373 field_set(COL_ADDR
);
1376 static void sock_details_print(struct sockstat
*s
)
1379 out(" uid:%u", s
->uid
);
1381 out(" ino:%u", s
->ino
);
1382 out(" sk:%llx", s
->sk
);
1385 out(" fwmark:0x%x", s
->mark
);
1388 static void sock_addr_print(const char *addr
, char *delim
, const char *port
,
1392 out("%s" "%%" "%s%s", addr
, ifname
, delim
);
1394 out("%s%s", addr
, delim
);
1401 static const char *print_ms_timer(unsigned int timeout
)
1403 static char buf
[64];
1404 int secs
, msecs
, minutes
;
1406 secs
= timeout
/1000;
1409 msecs
= timeout
%1000;
1413 snprintf(buf
, sizeof(buf
)-16, "%dmin", minutes
);
1420 sprintf(buf
+strlen(buf
), "%d%s", secs
, msecs
? "." : "sec");
1423 sprintf(buf
+strlen(buf
), "%03dms", msecs
);
1428 struct scache
*next
;
1434 static struct scache
*rlist
;
1436 static void init_service_resolver(void)
1439 FILE *fp
= popen("/usr/sbin/rpcinfo -p 2>/dev/null", "r");
1444 if (!fgets(buf
, sizeof(buf
), fp
)) {
1448 while (fgets(buf
, sizeof(buf
), fp
) != NULL
) {
1449 unsigned int progn
, port
;
1450 char proto
[128], prog
[128] = "rpc.";
1453 if (sscanf(buf
, "%u %*d %s %u %s",
1454 &progn
, proto
, &port
, prog
+4) != 4)
1457 if (!(c
= malloc(sizeof(*c
))))
1461 c
->name
= strdup(prog
);
1462 if (strcmp(proto
, TCP_PROTO
) == 0)
1463 c
->proto
= TCP_PROTO
;
1464 else if (strcmp(proto
, UDP_PROTO
) == 0)
1465 c
->proto
= UDP_PROTO
;
1466 else if (strcmp(proto
, SCTP_PROTO
) == 0)
1467 c
->proto
= SCTP_PROTO
;
1476 /* Even do not try default linux ephemeral port ranges:
1477 * default /etc/services contains so much of useless crap
1478 * wouldbe "allocated" to this area that resolution
1479 * is really harmful. I shrug each time when seeing
1480 * "socks" or "cfinger" in dumps.
1482 static int is_ephemeral(int port
)
1484 static int min
= 0, max
;
1487 FILE *f
= ephemeral_ports_open();
1489 if (!f
|| fscanf(f
, "%d %d", &min
, &max
) < 2) {
1496 return port
>= min
&& port
<= max
;
1500 static const char *__resolve_service(int port
)
1504 for (c
= rlist
; c
; c
= c
->next
) {
1505 if (c
->port
== port
&& c
->proto
== dg_proto
)
1509 if (!is_ephemeral(port
)) {
1510 static int notfirst
;
1517 se
= getservbyport(htons(port
), dg_proto
);
1525 #define SCACHE_BUCKETS 1024
1526 static struct scache
*cache_htab
[SCACHE_BUCKETS
];
1528 static const char *resolve_service(int port
)
1530 static char buf
[128];
1541 if (!resolve_services
)
1544 if (dg_proto
== RAW_PROTO
)
1545 return inet_proto_n2a(port
, buf
, sizeof(buf
));
1548 hash
= (port
^(((unsigned long)dg_proto
)>>2)) % SCACHE_BUCKETS
;
1550 for (c
= cache_htab
[hash
]; c
; c
= c
->next
) {
1551 if (c
->port
== port
&& c
->proto
== dg_proto
)
1555 c
= malloc(sizeof(*c
));
1558 res
= __resolve_service(port
);
1560 c
->name
= res
? strdup(res
) : NULL
;
1561 c
->proto
= dg_proto
;
1562 c
->next
= cache_htab
[hash
];
1563 cache_htab
[hash
] = c
;
1570 sprintf(buf
, "%u", port
);
1574 static void inet_addr_print(const inet_prefix
*a
, int port
,
1575 unsigned int ifindex
, bool v6only
)
1578 const char *ap
= buf
;
1579 const char *ifname
= NULL
;
1581 if (a
->family
== AF_INET
) {
1582 ap
= format_host(AF_INET
, 4, a
->data
);
1585 !memcmp(a
->data
, &in6addr_any
, sizeof(in6addr_any
))) {
1589 ap
= format_host(a
->family
, 16, a
->data
);
1591 /* Numeric IPv6 addresses should be bracketed */
1592 if (strchr(ap
, ':')) {
1593 snprintf(buf
, sizeof(buf
),
1601 ifname
= ll_index_to_name(ifindex
);
1603 sock_addr_print(ap
, ":", resolve_service(port
), ifname
);
1612 struct aafilter
*next
;
1615 static int inet2_addr_match(const inet_prefix
*a
, const inet_prefix
*p
,
1618 if (!inet_addr_match(a
, p
, plen
))
1621 /* Cursed "v4 mapped" addresses: v4 mapped socket matches
1622 * pure IPv4 rule, but v4-mapped rule selects only v4-mapped
1624 if (p
->family
== AF_INET
&& a
->family
== AF_INET6
) {
1625 if (a
->data
[0] == 0 && a
->data
[1] == 0 &&
1626 a
->data
[2] == htonl(0xffff)) {
1627 inet_prefix tmp
= *a
;
1629 tmp
.data
[0] = a
->data
[3];
1630 return inet_addr_match(&tmp
, p
, plen
);
1636 static int unix_match(const inet_prefix
*a
, const inet_prefix
*p
)
1638 char *addr
, *pattern
;
1640 memcpy(&addr
, a
->data
, sizeof(addr
));
1641 memcpy(&pattern
, p
->data
, sizeof(pattern
));
1642 if (pattern
== NULL
)
1646 return !fnmatch(pattern
, addr
, 0);
1649 static int run_ssfilter(struct ssfilter
*f
, struct sockstat
*s
)
1654 if (s
->local
.family
== AF_UNIX
) {
1657 memcpy(&p
, s
->local
.data
, sizeof(p
));
1658 return p
== NULL
|| (p
[0] == '@' && strlen(p
) == 6 &&
1659 strspn(p
+1, "0123456789abcdef") == 5);
1661 if (s
->local
.family
== AF_PACKET
)
1662 return s
->lport
== 0 && s
->local
.data
[0] == 0;
1663 if (s
->local
.family
== AF_NETLINK
)
1664 return s
->lport
< 0;
1665 if (s
->local
.family
== AF_VSOCK
)
1666 return s
->lport
> 1023;
1668 return is_ephemeral(s
->lport
);
1672 struct aafilter
*a
= (void *)f
->pred
;
1674 if (a
->addr
.family
== AF_UNIX
)
1675 return unix_match(&s
->remote
, &a
->addr
);
1676 if (a
->port
!= -1 && a
->port
!= s
->rport
)
1678 if (a
->addr
.bitlen
) {
1680 if (!inet2_addr_match(&s
->remote
, &a
->addr
, a
->addr
.bitlen
))
1682 } while ((a
= a
->next
) != NULL
);
1689 struct aafilter
*a
= (void *)f
->pred
;
1691 if (a
->addr
.family
== AF_UNIX
)
1692 return unix_match(&s
->local
, &a
->addr
);
1693 if (a
->port
!= -1 && a
->port
!= s
->lport
)
1695 if (a
->addr
.bitlen
) {
1697 if (!inet2_addr_match(&s
->local
, &a
->addr
, a
->addr
.bitlen
))
1699 } while ((a
= a
->next
) != NULL
);
1706 struct aafilter
*a
= (void *)f
->pred
;
1708 return s
->rport
>= a
->port
;
1712 struct aafilter
*a
= (void *)f
->pred
;
1714 return s
->rport
<= a
->port
;
1718 struct aafilter
*a
= (void *)f
->pred
;
1720 return s
->lport
>= a
->port
;
1724 struct aafilter
*a
= (void *)f
->pred
;
1726 return s
->lport
<= a
->port
;
1730 struct aafilter
*a
= (void *)f
->pred
;
1732 return s
->iface
== a
->iface
;
1736 struct aafilter
*a
= (void *)f
->pred
;
1738 return (s
->mark
& a
->mask
) == a
->mark
;
1740 /* Yup. It is recursion. Sorry. */
1742 return run_ssfilter(f
->pred
, s
) && run_ssfilter(f
->post
, s
);
1744 return run_ssfilter(f
->pred
, s
) || run_ssfilter(f
->post
, s
);
1746 return !run_ssfilter(f
->pred
, s
);
1752 /* Relocate external jumps by reloc. */
1753 static void ssfilter_patch(char *a
, int len
, int reloc
)
1756 struct inet_diag_bc_op
*op
= (struct inet_diag_bc_op
*)a
;
1758 if (op
->no
== len
+4)
1767 static int ssfilter_bytecompile(struct ssfilter
*f
, char **bytecode
)
1772 if (!(*bytecode
= malloc(4))) abort();
1773 ((struct inet_diag_bc_op
*)*bytecode
)[0] = (struct inet_diag_bc_op
){ INET_DIAG_BC_AUTO
, 4, 8 };
1779 struct aafilter
*a
= (void *)f
->pred
;
1782 int code
= (f
->type
== SSF_DCOND
? INET_DIAG_BC_D_COND
: INET_DIAG_BC_S_COND
);
1785 for (b
= a
; b
; b
= b
->next
) {
1786 len
+= 4 + sizeof(struct inet_diag_hostcond
);
1787 if (a
->addr
.family
== AF_INET6
)
1794 if (!(ptr
= malloc(len
))) abort();
1796 for (b
= a
; b
; b
= b
->next
) {
1797 struct inet_diag_bc_op
*op
= (struct inet_diag_bc_op
*)ptr
;
1798 int alen
= (a
->addr
.family
== AF_INET6
? 16 : 4);
1799 int oplen
= alen
+ 4 + sizeof(struct inet_diag_hostcond
);
1800 struct inet_diag_hostcond
*cond
= (struct inet_diag_hostcond
*)(ptr
+4);
1802 *op
= (struct inet_diag_bc_op
){ code
, oplen
, oplen
+4 };
1803 cond
->family
= a
->addr
.family
;
1804 cond
->port
= a
->port
;
1805 cond
->prefix_len
= a
->addr
.bitlen
;
1806 memcpy(cond
->addr
, a
->addr
.data
, alen
);
1809 op
= (struct inet_diag_bc_op
*)ptr
;
1810 *op
= (struct inet_diag_bc_op
){ INET_DIAG_BC_JMP
, 4, len
- (ptr
-*bytecode
)};
1814 return ptr
- *bytecode
;
1818 struct aafilter
*x
= (void *)f
->pred
;
1820 if (!(*bytecode
= malloc(8))) abort();
1821 ((struct inet_diag_bc_op
*)*bytecode
)[0] = (struct inet_diag_bc_op
){ INET_DIAG_BC_D_GE
, 8, 12 };
1822 ((struct inet_diag_bc_op
*)*bytecode
)[1] = (struct inet_diag_bc_op
){ 0, 0, x
->port
};
1827 struct aafilter
*x
= (void *)f
->pred
;
1829 if (!(*bytecode
= malloc(8))) abort();
1830 ((struct inet_diag_bc_op
*)*bytecode
)[0] = (struct inet_diag_bc_op
){ INET_DIAG_BC_D_LE
, 8, 12 };
1831 ((struct inet_diag_bc_op
*)*bytecode
)[1] = (struct inet_diag_bc_op
){ 0, 0, x
->port
};
1836 struct aafilter
*x
= (void *)f
->pred
;
1838 if (!(*bytecode
= malloc(8))) abort();
1839 ((struct inet_diag_bc_op
*)*bytecode
)[0] = (struct inet_diag_bc_op
){ INET_DIAG_BC_S_GE
, 8, 12 };
1840 ((struct inet_diag_bc_op
*)*bytecode
)[1] = (struct inet_diag_bc_op
){ 0, 0, x
->port
};
1845 struct aafilter
*x
= (void *)f
->pred
;
1847 if (!(*bytecode
= malloc(8))) abort();
1848 ((struct inet_diag_bc_op
*)*bytecode
)[0] = (struct inet_diag_bc_op
){ INET_DIAG_BC_S_LE
, 8, 12 };
1849 ((struct inet_diag_bc_op
*)*bytecode
)[1] = (struct inet_diag_bc_op
){ 0, 0, x
->port
};
1855 char *a1
= NULL
, *a2
= NULL
, *a
;
1858 l1
= ssfilter_bytecompile(f
->pred
, &a1
);
1859 l2
= ssfilter_bytecompile(f
->post
, &a2
);
1865 if (!(a
= malloc(l1
+l2
))) abort();
1867 memcpy(a
+l1
, a2
, l2
);
1869 ssfilter_patch(a
, l1
, l2
);
1875 char *a1
= NULL
, *a2
= NULL
, *a
;
1878 l1
= ssfilter_bytecompile(f
->pred
, &a1
);
1879 l2
= ssfilter_bytecompile(f
->post
, &a2
);
1885 if (!(a
= malloc(l1
+l2
+4))) abort();
1887 memcpy(a
+l1
+4, a2
, l2
);
1889 *(struct inet_diag_bc_op
*)(a
+l1
) = (struct inet_diag_bc_op
){ INET_DIAG_BC_JMP
, 4, l2
+4 };
1895 char *a1
= NULL
, *a
;
1898 l1
= ssfilter_bytecompile(f
->pred
, &a1
);
1903 if (!(a
= malloc(l1
+4))) abort();
1906 *(struct inet_diag_bc_op
*)(a
+l1
) = (struct inet_diag_bc_op
){ INET_DIAG_BC_JMP
, 4, 8 };
1912 /* bytecompile for SSF_DEVCOND not supported yet */
1917 struct aafilter
*a
= (void *)f
->pred
;
1919 struct inet_diag_bc_op op
;
1920 struct inet_diag_markcond cond
;
1922 int inslen
= sizeof(struct instr
);
1924 if (!(*bytecode
= malloc(inslen
))) abort();
1925 ((struct instr
*)*bytecode
)[0] = (struct instr
) {
1926 { INET_DIAG_BC_MARK_COND
, inslen
, inslen
+ 4 },
1927 { a
->mark
, a
->mask
},
1937 static int remember_he(struct aafilter
*a
, struct hostent
*he
)
1939 char **ptr
= he
->h_addr_list
;
1943 if (he
->h_addrtype
== AF_INET
)
1945 else if (he
->h_addrtype
== AF_INET6
)
1951 struct aafilter
*b
= a
;
1953 if (a
->addr
.bitlen
) {
1954 if ((b
= malloc(sizeof(*b
))) == NULL
)
1959 memcpy(b
->addr
.data
, *ptr
, len
);
1960 b
->addr
.bytelen
= len
;
1961 b
->addr
.bitlen
= len
*8;
1962 b
->addr
.family
= he
->h_addrtype
;
1969 static int get_dns_host(struct aafilter
*a
, const char *addr
, int fam
)
1971 static int notfirst
;
1980 he
= gethostbyname2(addr
, fam
== AF_UNSPEC
? AF_INET
: fam
);
1982 cnt
= remember_he(a
, he
);
1983 if (fam
== AF_UNSPEC
) {
1984 he
= gethostbyname2(addr
, AF_INET6
);
1986 cnt
+= remember_he(a
, he
);
1991 static int xll_initted
;
1993 static void xll_init(void)
1995 struct rtnl_handle rth
;
1997 if (rtnl_open(&rth
, 0) < 0)
2005 static const char *xll_index_to_name(int index
)
2009 return ll_index_to_name(index
);
2012 static int xll_name_to_index(const char *dev
)
2016 return ll_name_to_index(dev
);
2019 void *parse_devcond(char *name
)
2021 struct aafilter a
= { .iface
= 0 };
2022 struct aafilter
*res
;
2024 a
.iface
= xll_name_to_index(name
);
2029 n
= strtoul(name
, &end
, 0);
2030 if (!end
|| end
== name
|| *end
|| n
> UINT_MAX
)
2036 res
= malloc(sizeof(*res
));
2042 static void vsock_set_inet_prefix(inet_prefix
*a
, __u32 cid
)
2045 .bytelen
= sizeof(cid
),
2048 memcpy(a
->data
, &cid
, sizeof(cid
));
2051 void *parse_hostcond(char *addr
, bool is_port
)
2054 struct aafilter a
= { .port
= -1 };
2055 struct aafilter
*res
;
2056 int fam
= preferred_family
;
2057 struct filter
*f
= ¤t_filter
;
2059 if (fam
== AF_UNIX
|| strncmp(addr
, "unix:", 5) == 0) {
2062 a
.addr
.family
= AF_UNIX
;
2063 if (strncmp(addr
, "unix:", 5) == 0)
2066 a
.addr
.bitlen
= 8*strlen(p
);
2067 memcpy(a
.addr
.data
, &p
, sizeof(p
));
2072 if (fam
== AF_PACKET
|| strncmp(addr
, "link:", 5) == 0) {
2073 a
.addr
.family
= AF_PACKET
;
2075 if (strncmp(addr
, "link:", 5) == 0)
2077 port
= strchr(addr
, ':');
2080 if (port
[1] && strcmp(port
+1, "*")) {
2081 if (get_integer(&a
.port
, port
+1, 0)) {
2082 if ((a
.port
= xll_name_to_index(port
+1)) <= 0)
2087 if (addr
[0] && strcmp(addr
, "*")) {
2091 if (ll_proto_a2n(&tmp
, addr
))
2093 a
.addr
.data
[0] = ntohs(tmp
);
2099 if (fam
== AF_NETLINK
|| strncmp(addr
, "netlink:", 8) == 0) {
2100 a
.addr
.family
= AF_NETLINK
;
2102 if (strncmp(addr
, "netlink:", 8) == 0)
2104 port
= strchr(addr
, ':');
2107 if (port
[1] && strcmp(port
+1, "*")) {
2108 if (get_integer(&a
.port
, port
+1, 0)) {
2109 if (strcmp(port
+1, "kernel") == 0)
2116 if (addr
[0] && strcmp(addr
, "*")) {
2118 if (nl_proto_a2n(&a
.addr
.data
[0], addr
) == -1)
2125 if (fam
== AF_VSOCK
|| strncmp(addr
, "vsock:", 6) == 0) {
2126 __u32 cid
= ~(__u32
)0;
2128 a
.addr
.family
= AF_VSOCK
;
2129 if (strncmp(addr
, "vsock:", 6) == 0)
2135 port
= strchr(addr
, ':');
2142 if (port
&& strcmp(port
, "*") &&
2143 get_u32((__u32
*)&a
.port
, port
, 0))
2146 if (addr
[0] && strcmp(addr
, "*")) {
2148 if (get_u32(&cid
, addr
, 0))
2151 vsock_set_inet_prefix(&a
.addr
, cid
);
2156 if (fam
== AF_INET
|| !strncmp(addr
, "inet:", 5)) {
2158 if (!strncmp(addr
, "inet:", 5))
2160 } else if (fam
== AF_INET6
|| !strncmp(addr
, "inet6:", 6)) {
2162 if (!strncmp(addr
, "inet6:", 6))
2166 /* URL-like literal [] */
2167 if (addr
[0] == '[') {
2169 if ((port
= strchr(addr
, ']')) == NULL
)
2172 } else if (addr
[0] == '*') {
2175 port
= strrchr(strchr(addr
, '/') ? : addr
, ':');
2181 if (port
&& *port
) {
2185 if (*port
&& *port
!= '*') {
2186 if (get_integer(&a
.port
, port
, 0)) {
2187 struct servent
*se1
= NULL
;
2188 struct servent
*se2
= NULL
;
2190 if (current_filter
.dbs
&(1<<UDP_DB
))
2191 se1
= getservbyname(port
, UDP_PROTO
);
2192 if (current_filter
.dbs
&(1<<TCP_DB
))
2193 se2
= getservbyname(port
, TCP_PROTO
);
2194 if (se1
&& se2
&& se1
->s_port
!= se2
->s_port
) {
2195 fprintf(stderr
, "Error: ambiguous port \"%s\".\n", port
);
2201 a
.port
= ntohs(se1
->s_port
);
2205 for (s
= rlist
; s
; s
= s
->next
) {
2206 if ((s
->proto
== UDP_PROTO
&&
2207 (current_filter
.dbs
&(1<<UDP_DB
))) ||
2208 (s
->proto
== TCP_PROTO
&&
2209 (current_filter
.dbs
&(1<<TCP_DB
)))) {
2210 if (s
->name
&& strcmp(s
->name
, port
) == 0) {
2211 if (a
.port
> 0 && a
.port
!= s
->port
) {
2212 fprintf(stderr
, "Error: ambiguous port \"%s\".\n", port
);
2220 fprintf(stderr
, "Error: \"%s\" does not look like a port.\n", port
);
2227 if (!is_port
&& *addr
&& *addr
!= '*') {
2228 if (get_prefix_1(&a
.addr
, addr
, fam
)) {
2229 if (get_dns_host(&a
, addr
, fam
)) {
2230 fprintf(stderr
, "Error: an inet prefix is expected rather than \"%s\".\n", addr
);
2237 if (fam
!= AF_UNSPEC
) {
2238 int states
= f
->states
;
2240 filter_af_set(f
, fam
);
2241 filter_states_set(f
, states
);
2244 res
= malloc(sizeof(*res
));
2246 memcpy(res
, &a
, sizeof(a
));
2250 void *parse_markmask(const char *markmask
)
2252 struct aafilter a
, *res
;
2254 if (strchr(markmask
, '/')) {
2255 if (sscanf(markmask
, "%i/%i", &a
.mark
, &a
.mask
) != 2)
2258 a
.mask
= 0xffffffff;
2259 if (sscanf(markmask
, "%i", &a
.mark
) != 1)
2263 res
= malloc(sizeof(*res
));
2265 memcpy(res
, &a
, sizeof(a
));
2269 static void proc_ctx_print(struct sockstat
*s
)
2273 if (show_proc_ctx
|| show_sock_ctx
) {
2274 if (find_entry(s
->ino
, &buf
,
2275 (show_proc_ctx
& show_sock_ctx
) ?
2276 PROC_SOCK_CTX
: PROC_CTX
) > 0) {
2277 out(" users:(%s)", buf
);
2280 } else if (show_users
) {
2281 if (find_entry(s
->ino
, &buf
, USERS
) > 0) {
2282 out(" users:(%s)", buf
);
2288 static void inet_stats_print(struct sockstat
*s
, bool v6only
)
2290 sock_state_print(s
);
2292 inet_addr_print(&s
->local
, s
->lport
, s
->iface
, v6only
);
2293 inet_addr_print(&s
->remote
, s
->rport
, 0, v6only
);
2298 static int proc_parse_inet_addr(char *loc
, char *rem
, int family
, struct
2301 s
->local
.family
= s
->remote
.family
= family
;
2302 if (family
== AF_INET
) {
2303 sscanf(loc
, "%x:%x", s
->local
.data
, (unsigned *)&s
->lport
);
2304 sscanf(rem
, "%x:%x", s
->remote
.data
, (unsigned *)&s
->rport
);
2305 s
->local
.bytelen
= s
->remote
.bytelen
= 4;
2308 sscanf(loc
, "%08x%08x%08x%08x:%x",
2314 sscanf(rem
, "%08x%08x%08x%08x:%x",
2320 s
->local
.bytelen
= s
->remote
.bytelen
= 16;
2326 static int proc_inet_split_line(char *line
, char **loc
, char **rem
, char **data
)
2330 if ((p
= strchr(line
, ':')) == NULL
)
2334 if ((p
= strchr(*loc
, ':')) == NULL
)
2339 if ((p
= strchr(*rem
, ':')) == NULL
)
2347 static char *sprint_bw(char *buf
, double bw
)
2350 sprintf(buf
, "%.1fM", bw
/ 1000000.);
2351 else if (bw
> 1000.)
2352 sprintf(buf
, "%.1fK", bw
/ 1000.);
2354 sprintf(buf
, "%g", bw
);
2359 static void sctp_stats_print(struct sctp_info
*s
)
2362 out(" tag:%x", s
->sctpi_tag
);
2364 out(" state:%s", sctp_sstate_name
[s
->sctpi_state
]);
2366 out(" rwnd:%d", s
->sctpi_rwnd
);
2367 if (s
->sctpi_unackdata
)
2368 out(" unackdata:%d", s
->sctpi_unackdata
);
2369 if (s
->sctpi_penddata
)
2370 out(" penddata:%d", s
->sctpi_penddata
);
2371 if (s
->sctpi_instrms
)
2372 out(" instrms:%d", s
->sctpi_instrms
);
2373 if (s
->sctpi_outstrms
)
2374 out(" outstrms:%d", s
->sctpi_outstrms
);
2375 if (s
->sctpi_inqueue
)
2376 out(" inqueue:%d", s
->sctpi_inqueue
);
2377 if (s
->sctpi_outqueue
)
2378 out(" outqueue:%d", s
->sctpi_outqueue
);
2379 if (s
->sctpi_overall_error
)
2380 out(" overerr:%d", s
->sctpi_overall_error
);
2381 if (s
->sctpi_max_burst
)
2382 out(" maxburst:%d", s
->sctpi_max_burst
);
2383 if (s
->sctpi_maxseg
)
2384 out(" maxseg:%d", s
->sctpi_maxseg
);
2385 if (s
->sctpi_peer_rwnd
)
2386 out(" prwnd:%d", s
->sctpi_peer_rwnd
);
2387 if (s
->sctpi_peer_tag
)
2388 out(" ptag:%x", s
->sctpi_peer_tag
);
2389 if (s
->sctpi_peer_capable
)
2390 out(" pcapable:%d", s
->sctpi_peer_capable
);
2391 if (s
->sctpi_peer_sack
)
2392 out(" psack:%d", s
->sctpi_peer_sack
);
2393 if (s
->sctpi_s_autoclose
)
2394 out(" autoclose:%d", s
->sctpi_s_autoclose
);
2395 if (s
->sctpi_s_adaptation_ind
)
2396 out(" adapind:%d", s
->sctpi_s_adaptation_ind
);
2397 if (s
->sctpi_s_pd_point
)
2398 out(" pdpoint:%d", s
->sctpi_s_pd_point
);
2399 if (s
->sctpi_s_nodelay
)
2400 out(" nodealy:%d", s
->sctpi_s_nodelay
);
2401 if (s
->sctpi_s_disable_fragments
)
2402 out(" nofrag:%d", s
->sctpi_s_disable_fragments
);
2403 if (s
->sctpi_s_v4mapped
)
2404 out(" v4mapped:%d", s
->sctpi_s_v4mapped
);
2405 if (s
->sctpi_s_frag_interleave
)
2406 out(" fraginl:%d", s
->sctpi_s_frag_interleave
);
2409 static void tcp_stats_print(struct tcpstat
*s
)
2415 if (s
->has_sack_opt
)
2419 if (s
->has_ecnseen_opt
)
2421 if (s
->has_fastopen_opt
)
2424 out(" %s", s
->cong_alg
);
2425 if (s
->has_wscale_opt
)
2426 out(" wscale:%d,%d", s
->snd_wscale
, s
->rcv_wscale
);
2428 out(" rto:%g", s
->rto
);
2430 out(" backoff:%u", s
->backoff
);
2432 out(" rtt:%g/%g", s
->rtt
, s
->rttvar
);
2434 out(" ato:%g", s
->ato
);
2437 out(" qack:%d", s
->qack
);
2442 out(" mss:%d", s
->mss
);
2444 out(" pmtu:%u", s
->pmtu
);
2446 out(" rcvmss:%d", s
->rcv_mss
);
2448 out(" advmss:%d", s
->advmss
);
2450 out(" cwnd:%u", s
->cwnd
);
2452 out(" ssthresh:%d", s
->ssthresh
);
2455 out(" bytes_sent:%llu", s
->bytes_sent
);
2456 if (s
->bytes_retrans
)
2457 out(" bytes_retrans:%llu", s
->bytes_retrans
);
2459 out(" bytes_acked:%llu", s
->bytes_acked
);
2460 if (s
->bytes_received
)
2461 out(" bytes_received:%llu", s
->bytes_received
);
2463 out(" segs_out:%u", s
->segs_out
);
2465 out(" segs_in:%u", s
->segs_in
);
2466 if (s
->data_segs_out
)
2467 out(" data_segs_out:%u", s
->data_segs_out
);
2468 if (s
->data_segs_in
)
2469 out(" data_segs_in:%u", s
->data_segs_in
);
2471 if (s
->dctcp
&& s
->dctcp
->enabled
) {
2472 struct dctcpstat
*dctcp
= s
->dctcp
;
2474 out(" dctcp:(ce_state:%u,alpha:%u,ab_ecn:%u,ab_tot:%u)",
2475 dctcp
->ce_state
, dctcp
->alpha
, dctcp
->ab_ecn
,
2477 } else if (s
->dctcp
) {
2478 out(" dctcp:fallback_mode");
2484 bw
= s
->bbr_info
->bbr_bw_hi
;
2486 bw
|= s
->bbr_info
->bbr_bw_lo
;
2488 out(" bbr:(bw:%sbps,mrtt:%g",
2489 sprint_bw(b1
, bw
* 8.0),
2490 (double)s
->bbr_info
->bbr_min_rtt
/ 1000.0);
2491 if (s
->bbr_info
->bbr_pacing_gain
)
2492 out(",pacing_gain:%g",
2493 (double)s
->bbr_info
->bbr_pacing_gain
/ 256.0);
2494 if (s
->bbr_info
->bbr_cwnd_gain
)
2495 out(",cwnd_gain:%g",
2496 (double)s
->bbr_info
->bbr_cwnd_gain
/ 256.0);
2501 out(" send %sbps", sprint_bw(b1
, s
->send_bps
));
2503 out(" lastsnd:%u", s
->lastsnd
);
2505 out(" lastrcv:%u", s
->lastrcv
);
2507 out(" lastack:%u", s
->lastack
);
2509 if (s
->pacing_rate
) {
2510 out(" pacing_rate %sbps", sprint_bw(b1
, s
->pacing_rate
));
2511 if (s
->pacing_rate_max
)
2512 out("/%sbps", sprint_bw(b1
, s
->pacing_rate_max
));
2515 if (s
->delivery_rate
)
2516 out(" delivery_rate %sbps", sprint_bw(b1
, s
->delivery_rate
));
2518 out(" delivered:%u", s
->delivered
);
2519 if (s
->delivered_ce
)
2520 out(" delivered_ce:%u", s
->delivered_ce
);
2522 out(" app_limited");
2525 out(" busy:%llums", s
->busy_time
/ 1000);
2526 if (s
->rwnd_limited
)
2527 out(" rwnd_limited:%llums(%.1f%%)",
2528 s
->rwnd_limited
/ 1000,
2529 100.0 * s
->rwnd_limited
/ s
->busy_time
);
2530 if (s
->sndbuf_limited
)
2531 out(" sndbuf_limited:%llums(%.1f%%)",
2532 s
->sndbuf_limited
/ 1000,
2533 100.0 * s
->sndbuf_limited
/ s
->busy_time
);
2537 out(" unacked:%u", s
->unacked
);
2538 if (s
->retrans
|| s
->retrans_total
)
2539 out(" retrans:%u/%u", s
->retrans
, s
->retrans_total
);
2541 out(" lost:%u", s
->lost
);
2542 if (s
->sacked
&& s
->ss
.state
!= SS_LISTEN
)
2543 out(" sacked:%u", s
->sacked
);
2545 out(" dsack_dups:%u", s
->dsack_dups
);
2547 out(" fackets:%u", s
->fackets
);
2548 if (s
->reordering
!= 3)
2549 out(" reordering:%d", s
->reordering
);
2551 out(" reord_seen:%d", s
->reord_seen
);
2553 out(" rcv_rtt:%g", s
->rcv_rtt
);
2555 out(" rcv_space:%d", s
->rcv_space
);
2556 if (s
->rcv_ssthresh
)
2557 out(" rcv_ssthresh:%u", s
->rcv_ssthresh
);
2559 out(" notsent:%u", s
->not_sent
);
2561 out(" minrtt:%g", s
->min_rtt
);
2564 static void tcp_timer_print(struct tcpstat
*s
)
2566 static const char * const tmr_name
[] = {
2578 out(" timer:(%s,%s,%d)",
2580 print_ms_timer(s
->timeout
),
2585 static void sctp_timer_print(struct tcpstat
*s
)
2588 out(" timer:(T3_RTX,%s,%d)",
2589 print_ms_timer(s
->timeout
), s
->retrans
);
2592 static int tcp_show_line(char *line
, const struct filter
*f
, int family
)
2594 int rto
= 0, ato
= 0;
2595 struct tcpstat s
= {};
2596 char *loc
, *rem
, *data
;
2599 int hz
= get_user_hz();
2601 if (proc_inet_split_line(line
, &loc
, &rem
, &data
))
2604 int state
= (data
[1] >= 'A') ? (data
[1] - 'A' + 10) : (data
[1] - '0');
2606 if (!(f
->states
& (1 << state
)))
2609 proc_parse_inet_addr(loc
, rem
, family
, &s
.ss
);
2611 if (f
->f
&& run_ssfilter(f
->f
, &s
.ss
) == 0)
2615 n
= sscanf(data
, "%x %x:%x %x:%x %x %d %d %u %d %llx %d %d %d %u %d %[^\n]\n",
2616 &s
.ss
.state
, &s
.ss
.wq
, &s
.ss
.rq
,
2617 &s
.timer
, &s
.timeout
, &s
.retrans
, &s
.ss
.uid
, &s
.probes
,
2618 &s
.ss
.ino
, &s
.ss
.refcnt
, &s
.ss
.sk
, &rto
, &ato
, &s
.qack
, &s
.cwnd
,
2631 s
.retrans
= s
.timer
!= 1 ? s
.probes
: s
.retrans
;
2632 s
.timeout
= (s
.timeout
* 1000 + hz
- 1) / hz
;
2633 s
.ato
= (double)ato
/ hz
;
2635 s
.rto
= (double)rto
;
2636 s
.ssthresh
= s
.ssthresh
== -1 ? 0 : s
.ssthresh
;
2637 s
.rto
= s
.rto
!= 3 * hz
? s
.rto
/ hz
: 0;
2638 s
.ss
.type
= IPPROTO_TCP
;
2640 inet_stats_print(&s
.ss
, false);
2643 tcp_timer_print(&s
);
2646 sock_details_print(&s
.ss
);
2648 out(" opt:\"%s\"", opt
);
2652 tcp_stats_print(&s
);
2657 static int generic_record_read(FILE *fp
,
2658 int (*worker
)(char*, const struct filter
*, int),
2659 const struct filter
*f
, int fam
)
2664 if (fgets(line
, sizeof(line
), fp
) == NULL
)
2667 while (fgets(line
, sizeof(line
), fp
) != NULL
) {
2668 int n
= strlen(line
);
2670 if (n
== 0 || line
[n
-1] != '\n') {
2676 if (worker(line
, f
, fam
) < 0)
2681 return ferror(fp
) ? -1 : 0;
2684 static void print_skmeminfo(struct rtattr
*tb
[], int attrtype
)
2686 const __u32
*skmeminfo
;
2688 if (!tb
[attrtype
]) {
2689 if (attrtype
== INET_DIAG_SKMEMINFO
) {
2690 if (!tb
[INET_DIAG_MEMINFO
])
2693 const struct inet_diag_meminfo
*minfo
=
2694 RTA_DATA(tb
[INET_DIAG_MEMINFO
]);
2696 out(" mem:(r%u,w%u,f%u,t%u)",
2705 skmeminfo
= RTA_DATA(tb
[attrtype
]);
2707 out(" skmem:(r%u,rb%u,t%u,tb%u,f%u,w%u,o%u",
2708 skmeminfo
[SK_MEMINFO_RMEM_ALLOC
],
2709 skmeminfo
[SK_MEMINFO_RCVBUF
],
2710 skmeminfo
[SK_MEMINFO_WMEM_ALLOC
],
2711 skmeminfo
[SK_MEMINFO_SNDBUF
],
2712 skmeminfo
[SK_MEMINFO_FWD_ALLOC
],
2713 skmeminfo
[SK_MEMINFO_WMEM_QUEUED
],
2714 skmeminfo
[SK_MEMINFO_OPTMEM
]);
2716 if (RTA_PAYLOAD(tb
[attrtype
]) >=
2717 (SK_MEMINFO_BACKLOG
+ 1) * sizeof(__u32
))
2718 out(",bl%u", skmeminfo
[SK_MEMINFO_BACKLOG
]);
2720 if (RTA_PAYLOAD(tb
[attrtype
]) >=
2721 (SK_MEMINFO_DROPS
+ 1) * sizeof(__u32
))
2722 out(",d%u", skmeminfo
[SK_MEMINFO_DROPS
]);
2727 static void print_md5sig(struct tcp_diag_md5sig
*sig
)
2730 format_host(sig
->tcpm_family
,
2731 sig
->tcpm_family
== AF_INET6
? 16 : 4,
2733 sig
->tcpm_prefixlen
);
2734 print_escape_buf(sig
->tcpm_key
, sig
->tcpm_keylen
, " ,");
2737 #define TCPI_HAS_OPT(info, opt) !!(info->tcpi_options & (opt))
2739 static void tcp_show_info(const struct nlmsghdr
*nlh
, struct inet_diag_msg
*r
,
2740 struct rtattr
*tb
[])
2743 struct tcpstat s
= {};
2745 s
.ss
.state
= r
->idiag_state
;
2747 print_skmeminfo(tb
, INET_DIAG_SKMEMINFO
);
2749 if (tb
[INET_DIAG_INFO
]) {
2750 struct tcp_info
*info
;
2751 int len
= RTA_PAYLOAD(tb
[INET_DIAG_INFO
]);
2753 /* workaround for older kernels with less fields */
2754 if (len
< sizeof(*info
)) {
2755 info
= alloca(sizeof(*info
));
2756 memcpy(info
, RTA_DATA(tb
[INET_DIAG_INFO
]), len
);
2757 memset((char *)info
+ len
, 0, sizeof(*info
) - len
);
2759 info
= RTA_DATA(tb
[INET_DIAG_INFO
]);
2762 s
.has_ts_opt
= TCPI_HAS_OPT(info
, TCPI_OPT_TIMESTAMPS
);
2763 s
.has_sack_opt
= TCPI_HAS_OPT(info
, TCPI_OPT_SACK
);
2764 s
.has_ecn_opt
= TCPI_HAS_OPT(info
, TCPI_OPT_ECN
);
2765 s
.has_ecnseen_opt
= TCPI_HAS_OPT(info
, TCPI_OPT_ECN_SEEN
);
2766 s
.has_fastopen_opt
= TCPI_HAS_OPT(info
, TCPI_OPT_SYN_DATA
);
2769 if (tb
[INET_DIAG_CONG
])
2771 rta_getattr_str(tb
[INET_DIAG_CONG
]),
2772 sizeof(s
.cong_alg
) - 1);
2774 if (TCPI_HAS_OPT(info
, TCPI_OPT_WSCALE
)) {
2775 s
.has_wscale_opt
= true;
2776 s
.snd_wscale
= info
->tcpi_snd_wscale
;
2777 s
.rcv_wscale
= info
->tcpi_rcv_wscale
;
2780 if (info
->tcpi_rto
&& info
->tcpi_rto
!= 3000000)
2781 s
.rto
= (double)info
->tcpi_rto
/ 1000;
2783 s
.backoff
= info
->tcpi_backoff
;
2784 s
.rtt
= (double)info
->tcpi_rtt
/ 1000;
2785 s
.rttvar
= (double)info
->tcpi_rttvar
/ 1000;
2786 s
.ato
= (double)info
->tcpi_ato
/ 1000;
2787 s
.mss
= info
->tcpi_snd_mss
;
2788 s
.rcv_mss
= info
->tcpi_rcv_mss
;
2789 s
.advmss
= info
->tcpi_advmss
;
2790 s
.rcv_space
= info
->tcpi_rcv_space
;
2791 s
.rcv_rtt
= (double)info
->tcpi_rcv_rtt
/ 1000;
2792 s
.lastsnd
= info
->tcpi_last_data_sent
;
2793 s
.lastrcv
= info
->tcpi_last_data_recv
;
2794 s
.lastack
= info
->tcpi_last_ack_recv
;
2795 s
.unacked
= info
->tcpi_unacked
;
2796 s
.retrans
= info
->tcpi_retrans
;
2797 s
.retrans_total
= info
->tcpi_total_retrans
;
2798 s
.lost
= info
->tcpi_lost
;
2799 s
.sacked
= info
->tcpi_sacked
;
2800 s
.fackets
= info
->tcpi_fackets
;
2801 s
.reordering
= info
->tcpi_reordering
;
2802 s
.rcv_ssthresh
= info
->tcpi_rcv_ssthresh
;
2803 s
.cwnd
= info
->tcpi_snd_cwnd
;
2804 s
.pmtu
= info
->tcpi_pmtu
;
2806 if (info
->tcpi_snd_ssthresh
< 0xFFFF)
2807 s
.ssthresh
= info
->tcpi_snd_ssthresh
;
2809 rtt
= (double) info
->tcpi_rtt
;
2810 if (tb
[INET_DIAG_VEGASINFO
]) {
2811 const struct tcpvegas_info
*vinfo
2812 = RTA_DATA(tb
[INET_DIAG_VEGASINFO
]);
2814 if (vinfo
->tcpv_enabled
&&
2815 vinfo
->tcpv_rtt
&& vinfo
->tcpv_rtt
!= 0x7fffffff)
2816 rtt
= vinfo
->tcpv_rtt
;
2819 if (tb
[INET_DIAG_DCTCPINFO
]) {
2820 struct dctcpstat
*dctcp
= malloc(sizeof(struct
2823 const struct tcp_dctcp_info
*dinfo
2824 = RTA_DATA(tb
[INET_DIAG_DCTCPINFO
]);
2826 dctcp
->enabled
= !!dinfo
->dctcp_enabled
;
2827 dctcp
->ce_state
= dinfo
->dctcp_ce_state
;
2828 dctcp
->alpha
= dinfo
->dctcp_alpha
;
2829 dctcp
->ab_ecn
= dinfo
->dctcp_ab_ecn
;
2830 dctcp
->ab_tot
= dinfo
->dctcp_ab_tot
;
2834 if (tb
[INET_DIAG_BBRINFO
]) {
2835 const void *bbr_info
= RTA_DATA(tb
[INET_DIAG_BBRINFO
]);
2836 int len
= min(RTA_PAYLOAD(tb
[INET_DIAG_BBRINFO
]),
2837 sizeof(*s
.bbr_info
));
2839 s
.bbr_info
= calloc(1, sizeof(*s
.bbr_info
));
2840 if (s
.bbr_info
&& bbr_info
)
2841 memcpy(s
.bbr_info
, bbr_info
, len
);
2844 if (rtt
> 0 && info
->tcpi_snd_mss
&& info
->tcpi_snd_cwnd
) {
2845 s
.send_bps
= (double) info
->tcpi_snd_cwnd
*
2846 (double)info
->tcpi_snd_mss
* 8000000. / rtt
;
2849 if (info
->tcpi_pacing_rate
&&
2850 info
->tcpi_pacing_rate
!= ~0ULL) {
2851 s
.pacing_rate
= info
->tcpi_pacing_rate
* 8.;
2853 if (info
->tcpi_max_pacing_rate
&&
2854 info
->tcpi_max_pacing_rate
!= ~0ULL)
2855 s
.pacing_rate_max
= info
->tcpi_max_pacing_rate
* 8.;
2857 s
.bytes_acked
= info
->tcpi_bytes_acked
;
2858 s
.bytes_received
= info
->tcpi_bytes_received
;
2859 s
.segs_out
= info
->tcpi_segs_out
;
2860 s
.segs_in
= info
->tcpi_segs_in
;
2861 s
.data_segs_out
= info
->tcpi_data_segs_out
;
2862 s
.data_segs_in
= info
->tcpi_data_segs_in
;
2863 s
.not_sent
= info
->tcpi_notsent_bytes
;
2864 if (info
->tcpi_min_rtt
&& info
->tcpi_min_rtt
!= ~0U)
2865 s
.min_rtt
= (double) info
->tcpi_min_rtt
/ 1000;
2866 s
.delivery_rate
= info
->tcpi_delivery_rate
* 8.;
2867 s
.app_limited
= info
->tcpi_delivery_rate_app_limited
;
2868 s
.busy_time
= info
->tcpi_busy_time
;
2869 s
.rwnd_limited
= info
->tcpi_rwnd_limited
;
2870 s
.sndbuf_limited
= info
->tcpi_sndbuf_limited
;
2871 s
.delivered
= info
->tcpi_delivered
;
2872 s
.delivered_ce
= info
->tcpi_delivered_ce
;
2873 s
.dsack_dups
= info
->tcpi_dsack_dups
;
2874 s
.reord_seen
= info
->tcpi_reord_seen
;
2875 s
.bytes_sent
= info
->tcpi_bytes_sent
;
2876 s
.bytes_retrans
= info
->tcpi_bytes_retrans
;
2877 tcp_stats_print(&s
);
2881 if (tb
[INET_DIAG_MD5SIG
]) {
2882 struct tcp_diag_md5sig
*sig
= RTA_DATA(tb
[INET_DIAG_MD5SIG
]);
2883 int len
= RTA_PAYLOAD(tb
[INET_DIAG_MD5SIG
]);
2886 print_md5sig(sig
++);
2887 for (len
-= sizeof(*sig
); len
> 0; len
-= sizeof(*sig
)) {
2889 print_md5sig(sig
++);
2894 static const char *format_host_sa(struct sockaddr_storage
*sa
)
2897 struct sockaddr_in sin
;
2898 struct sockaddr_in6 sin6
;
2899 } *saddr
= (void *)sa
;
2901 switch (sa
->ss_family
) {
2903 return format_host(AF_INET
, 4, &saddr
->sin
.sin_addr
);
2905 return format_host(AF_INET6
, 16, &saddr
->sin6
.sin6_addr
);
2911 static void sctp_show_info(const struct nlmsghdr
*nlh
, struct inet_diag_msg
*r
,
2912 struct rtattr
*tb
[])
2914 struct sockaddr_storage
*sa
;
2917 print_skmeminfo(tb
, INET_DIAG_SKMEMINFO
);
2919 if (tb
[INET_DIAG_LOCALS
]) {
2920 len
= RTA_PAYLOAD(tb
[INET_DIAG_LOCALS
]);
2921 sa
= RTA_DATA(tb
[INET_DIAG_LOCALS
]);
2923 out("locals:%s", format_host_sa(sa
));
2924 for (sa
++, len
-= sizeof(*sa
); len
> 0; sa
++, len
-= sizeof(*sa
))
2925 out(",%s", format_host_sa(sa
));
2928 if (tb
[INET_DIAG_PEERS
]) {
2929 len
= RTA_PAYLOAD(tb
[INET_DIAG_PEERS
]);
2930 sa
= RTA_DATA(tb
[INET_DIAG_PEERS
]);
2932 out(" peers:%s", format_host_sa(sa
));
2933 for (sa
++, len
-= sizeof(*sa
); len
> 0; sa
++, len
-= sizeof(*sa
))
2934 out(",%s", format_host_sa(sa
));
2936 if (tb
[INET_DIAG_INFO
]) {
2937 struct sctp_info
*info
;
2938 len
= RTA_PAYLOAD(tb
[INET_DIAG_INFO
]);
2940 /* workaround for older kernels with less fields */
2941 if (len
< sizeof(*info
)) {
2942 info
= alloca(sizeof(*info
));
2943 memcpy(info
, RTA_DATA(tb
[INET_DIAG_INFO
]), len
);
2944 memset((char *)info
+ len
, 0, sizeof(*info
) - len
);
2946 info
= RTA_DATA(tb
[INET_DIAG_INFO
]);
2948 sctp_stats_print(info
);
2952 static void parse_diag_msg(struct nlmsghdr
*nlh
, struct sockstat
*s
)
2954 struct rtattr
*tb
[INET_DIAG_MAX
+1];
2955 struct inet_diag_msg
*r
= NLMSG_DATA(nlh
);
2957 parse_rtattr(tb
, INET_DIAG_MAX
, (struct rtattr
*)(r
+1),
2958 nlh
->nlmsg_len
- NLMSG_LENGTH(sizeof(*r
)));
2960 s
->state
= r
->idiag_state
;
2961 s
->local
.family
= s
->remote
.family
= r
->idiag_family
;
2962 s
->lport
= ntohs(r
->id
.idiag_sport
);
2963 s
->rport
= ntohs(r
->id
.idiag_dport
);
2964 s
->wq
= r
->idiag_wqueue
;
2965 s
->rq
= r
->idiag_rqueue
;
2966 s
->ino
= r
->idiag_inode
;
2967 s
->uid
= r
->idiag_uid
;
2968 s
->iface
= r
->id
.idiag_if
;
2969 s
->sk
= cookie_sk_get(&r
->id
.idiag_cookie
[0]);
2972 if (tb
[INET_DIAG_MARK
])
2973 s
->mark
= rta_getattr_u32(tb
[INET_DIAG_MARK
]);
2974 if (tb
[INET_DIAG_PROTOCOL
])
2975 s
->raw_prot
= rta_getattr_u8(tb
[INET_DIAG_PROTOCOL
]);
2979 if (s
->local
.family
== AF_INET
)
2980 s
->local
.bytelen
= s
->remote
.bytelen
= 4;
2982 s
->local
.bytelen
= s
->remote
.bytelen
= 16;
2984 memcpy(s
->local
.data
, r
->id
.idiag_src
, s
->local
.bytelen
);
2985 memcpy(s
->remote
.data
, r
->id
.idiag_dst
, s
->local
.bytelen
);
2988 static int inet_show_sock(struct nlmsghdr
*nlh
,
2991 struct rtattr
*tb
[INET_DIAG_MAX
+1];
2992 struct inet_diag_msg
*r
= NLMSG_DATA(nlh
);
2993 unsigned char v6only
= 0;
2995 parse_rtattr(tb
, INET_DIAG_MAX
, (struct rtattr
*)(r
+1),
2996 nlh
->nlmsg_len
- NLMSG_LENGTH(sizeof(*r
)));
2998 if (tb
[INET_DIAG_PROTOCOL
])
2999 s
->type
= rta_getattr_u8(tb
[INET_DIAG_PROTOCOL
]);
3001 if (s
->local
.family
== AF_INET6
&& tb
[INET_DIAG_SKV6ONLY
])
3002 v6only
= rta_getattr_u8(tb
[INET_DIAG_SKV6ONLY
]);
3004 inet_stats_print(s
, v6only
);
3007 struct tcpstat t
= {};
3009 t
.timer
= r
->idiag_timer
;
3010 t
.timeout
= r
->idiag_expires
;
3011 t
.retrans
= r
->idiag_retrans
;
3012 if (s
->type
== IPPROTO_SCTP
)
3013 sctp_timer_print(&t
);
3015 tcp_timer_print(&t
);
3019 sock_details_print(s
);
3020 if (s
->local
.family
== AF_INET6
&& tb
[INET_DIAG_SKV6ONLY
])
3021 out(" v6only:%u", v6only
);
3023 if (tb
[INET_DIAG_SHUTDOWN
]) {
3026 mask
= rta_getattr_u8(tb
[INET_DIAG_SHUTDOWN
]);
3028 mask
& 1 ? '-' : '<', mask
& 2 ? '-' : '>');
3033 if (tb
[INET_DIAG_TOS
])
3034 out(" tos:%#x", rta_getattr_u8(tb
[INET_DIAG_TOS
]));
3035 if (tb
[INET_DIAG_TCLASS
])
3036 out(" tclass:%#x", rta_getattr_u8(tb
[INET_DIAG_TCLASS
]));
3037 if (tb
[INET_DIAG_CLASS_ID
])
3038 out(" class_id:%#x", rta_getattr_u32(tb
[INET_DIAG_CLASS_ID
]));
3041 if (show_mem
|| (show_tcpinfo
&& s
->type
!= IPPROTO_UDP
)) {
3043 if (s
->type
== IPPROTO_SCTP
)
3044 sctp_show_info(nlh
, r
, tb
);
3046 tcp_show_info(nlh
, r
, tb
);
3053 static int tcpdiag_send(int fd
, int protocol
, struct filter
*f
)
3055 struct sockaddr_nl nladdr
= { .nl_family
= AF_NETLINK
};
3057 struct nlmsghdr nlh
;
3058 struct inet_diag_req r
;
3060 .nlh
.nlmsg_len
= sizeof(req
),
3061 .nlh
.nlmsg_flags
= NLM_F_ROOT
| NLM_F_MATCH
| NLM_F_REQUEST
,
3062 .nlh
.nlmsg_seq
= MAGIC_SEQ
,
3063 .r
.idiag_family
= AF_INET
,
3064 .r
.idiag_states
= f
->states
,
3070 struct iovec iov
[3];
3073 if (protocol
== IPPROTO_UDP
)
3076 if (protocol
== IPPROTO_TCP
)
3077 req
.nlh
.nlmsg_type
= TCPDIAG_GETSOCK
;
3079 req
.nlh
.nlmsg_type
= DCCPDIAG_GETSOCK
;
3081 req
.r
.idiag_ext
|= (1<<(INET_DIAG_MEMINFO
-1));
3082 req
.r
.idiag_ext
|= (1<<(INET_DIAG_SKMEMINFO
-1));
3086 req
.r
.idiag_ext
|= (1<<(INET_DIAG_INFO
-1));
3087 req
.r
.idiag_ext
|= (1<<(INET_DIAG_VEGASINFO
-1));
3088 req
.r
.idiag_ext
|= (1<<(INET_DIAG_CONG
-1));
3092 req
.r
.idiag_ext
|= (1<<(INET_DIAG_TOS
-1));
3093 req
.r
.idiag_ext
|= (1<<(INET_DIAG_TCLASS
-1));
3096 iov
[0] = (struct iovec
){
3098 .iov_len
= sizeof(req
)
3101 bclen
= ssfilter_bytecompile(f
->f
, &bc
);
3103 rta
.rta_type
= INET_DIAG_REQ_BYTECODE
;
3104 rta
.rta_len
= RTA_LENGTH(bclen
);
3105 iov
[1] = (struct iovec
){ &rta
, sizeof(rta
) };
3106 iov
[2] = (struct iovec
){ bc
, bclen
};
3107 req
.nlh
.nlmsg_len
+= RTA_LENGTH(bclen
);
3112 msg
= (struct msghdr
) {
3113 .msg_name
= (void *)&nladdr
,
3114 .msg_namelen
= sizeof(nladdr
),
3116 .msg_iovlen
= iovlen
,
3119 if (sendmsg(fd
, &msg
, 0) < 0) {
3127 static int sockdiag_send(int family
, int fd
, int protocol
, struct filter
*f
)
3129 struct sockaddr_nl nladdr
= { .nl_family
= AF_NETLINK
};
3130 DIAG_REQUEST(req
, struct inet_diag_req_v2 r
);
3135 struct iovec iov
[3];
3138 if (family
== PF_UNSPEC
)
3139 return tcpdiag_send(fd
, protocol
, f
);
3141 memset(&req
.r
, 0, sizeof(req
.r
));
3142 req
.r
.sdiag_family
= family
;
3143 req
.r
.sdiag_protocol
= protocol
;
3144 req
.r
.idiag_states
= f
->states
;
3146 req
.r
.idiag_ext
|= (1<<(INET_DIAG_MEMINFO
-1));
3147 req
.r
.idiag_ext
|= (1<<(INET_DIAG_SKMEMINFO
-1));
3151 req
.r
.idiag_ext
|= (1<<(INET_DIAG_INFO
-1));
3152 req
.r
.idiag_ext
|= (1<<(INET_DIAG_VEGASINFO
-1));
3153 req
.r
.idiag_ext
|= (1<<(INET_DIAG_CONG
-1));
3157 req
.r
.idiag_ext
|= (1<<(INET_DIAG_TOS
-1));
3158 req
.r
.idiag_ext
|= (1<<(INET_DIAG_TCLASS
-1));
3161 iov
[0] = (struct iovec
){
3163 .iov_len
= sizeof(req
)
3166 bclen
= ssfilter_bytecompile(f
->f
, &bc
);
3168 rta
.rta_type
= INET_DIAG_REQ_BYTECODE
;
3169 rta
.rta_len
= RTA_LENGTH(bclen
);
3170 iov
[1] = (struct iovec
){ &rta
, sizeof(rta
) };
3171 iov
[2] = (struct iovec
){ bc
, bclen
};
3172 req
.nlh
.nlmsg_len
+= RTA_LENGTH(bclen
);
3177 msg
= (struct msghdr
) {
3178 .msg_name
= (void *)&nladdr
,
3179 .msg_namelen
= sizeof(nladdr
),
3181 .msg_iovlen
= iovlen
,
3184 if (sendmsg(fd
, &msg
, 0) < 0) {
3192 struct inet_diag_arg
{
3195 struct rtnl_handle
*rth
;
3198 static int kill_inet_sock(struct nlmsghdr
*h
, void *arg
, struct sockstat
*s
)
3200 struct inet_diag_msg
*d
= NLMSG_DATA(h
);
3201 struct inet_diag_arg
*diag_arg
= arg
;
3202 struct rtnl_handle
*rth
= diag_arg
->rth
;
3204 DIAG_REQUEST(req
, struct inet_diag_req_v2 r
);
3206 req
.nlh
.nlmsg_type
= SOCK_DESTROY
;
3207 req
.nlh
.nlmsg_flags
= NLM_F_REQUEST
| NLM_F_ACK
;
3208 req
.nlh
.nlmsg_seq
= ++rth
->seq
;
3209 req
.r
.sdiag_family
= d
->idiag_family
;
3210 req
.r
.sdiag_protocol
= diag_arg
->protocol
;
3213 if (diag_arg
->protocol
== IPPROTO_RAW
) {
3214 struct inet_diag_req_raw
*raw
= (void *)&req
.r
;
3216 BUILD_BUG_ON(sizeof(req
.r
) != sizeof(*raw
));
3217 raw
->sdiag_raw_protocol
= s
->raw_prot
;
3220 return rtnl_talk(rth
, &req
.nlh
, NULL
);
3223 static int show_one_inet_sock(struct nlmsghdr
*h
, void *arg
)
3226 struct inet_diag_arg
*diag_arg
= arg
;
3227 struct inet_diag_msg
*r
= NLMSG_DATA(h
);
3228 struct sockstat s
= {};
3230 if (!(diag_arg
->f
->families
& FAMILY_MASK(r
->idiag_family
)))
3233 parse_diag_msg(h
, &s
);
3234 s
.type
= diag_arg
->protocol
;
3236 if (diag_arg
->f
->f
&& run_ssfilter(diag_arg
->f
->f
, &s
) == 0)
3239 if (diag_arg
->f
->kill
&& kill_inet_sock(h
, arg
, &s
) != 0) {
3240 if (errno
== EOPNOTSUPP
|| errno
== ENOENT
) {
3241 /* Socket can't be closed, or is already closed. */
3244 perror("SOCK_DESTROY answers");
3249 err
= inet_show_sock(h
, &s
);
3256 static int inet_show_netlink(struct filter
*f
, FILE *dump_fp
, int protocol
)
3259 struct rtnl_handle rth
, rth2
;
3260 int family
= PF_INET
;
3261 struct inet_diag_arg arg
= { .f
= f
, .protocol
= protocol
};
3263 if (rtnl_open_byproto(&rth
, 0, NETLINK_SOCK_DIAG
))
3267 if (rtnl_open_byproto(&rth2
, 0, NETLINK_SOCK_DIAG
)) {
3274 rth
.dump
= MAGIC_SEQ
;
3275 rth
.dump_fp
= dump_fp
;
3276 if (preferred_family
== PF_INET6
)
3280 if ((err
= sockdiag_send(family
, rth
.fd
, protocol
, f
)))
3283 if ((err
= rtnl_dump_filter(&rth
, show_one_inet_sock
, &arg
))) {
3284 if (family
!= PF_UNSPEC
) {
3290 if (family
== PF_INET
&& preferred_family
!= PF_INET
) {
3298 rtnl_close(arg
.rth
);
3302 static int tcp_show_netlink_file(struct filter
*f
)
3308 if ((fp
= fopen(getenv("TCPDIAG_FILE"), "r")) == NULL
) {
3309 perror("fopen($TCPDIAG_FILE)");
3315 struct nlmsghdr
*h
= (struct nlmsghdr
*)buf
;
3316 struct sockstat s
= {};
3318 status
= fread(buf
, 1, sizeof(*h
), fp
);
3320 perror("Reading header from $TCPDIAG_FILE");
3323 if (status
!= sizeof(*h
)) {
3324 perror("Unexpected EOF reading $TCPDIAG_FILE");
3328 status
= fread(h
+1, 1, NLMSG_ALIGN(h
->nlmsg_len
-sizeof(*h
)), fp
);
3331 perror("Reading $TCPDIAG_FILE");
3334 if (status
+ sizeof(*h
) < h
->nlmsg_len
) {
3335 perror("Unexpected EOF reading $TCPDIAG_FILE");
3339 /* The only legal exit point */
3340 if (h
->nlmsg_type
== NLMSG_DONE
) {
3345 if (h
->nlmsg_type
== NLMSG_ERROR
) {
3346 struct nlmsgerr
*err
= (struct nlmsgerr
*)NLMSG_DATA(h
);
3348 if (h
->nlmsg_len
< NLMSG_LENGTH(sizeof(struct nlmsgerr
))) {
3349 fprintf(stderr
, "ERROR truncated\n");
3351 errno
= -err
->error
;
3352 perror("TCPDIAG answered");
3357 parse_diag_msg(h
, &s
);
3358 s
.type
= IPPROTO_TCP
;
3360 if (f
&& f
->f
&& run_ssfilter(f
->f
, &s
) == 0)
3363 err2
= inet_show_sock(h
, &s
);
3374 static int tcp_show(struct filter
*f
)
3378 int bufsize
= 1024*1024;
3380 if (!filter_af_get(f
, AF_INET
) && !filter_af_get(f
, AF_INET6
))
3383 dg_proto
= TCP_PROTO
;
3385 if (getenv("TCPDIAG_FILE"))
3386 return tcp_show_netlink_file(f
);
3388 if (!getenv("PROC_NET_TCP") && !getenv("PROC_ROOT")
3389 && inet_show_netlink(f
, NULL
, IPPROTO_TCP
) == 0)
3392 /* Sigh... We have to parse /proc/net/tcp... */
3393 while (bufsize
>= 64*1024) {
3394 if ((buf
= malloc(bufsize
)) != NULL
)
3403 if (f
->families
& FAMILY_MASK(AF_INET
)) {
3404 if ((fp
= net_tcp_open()) == NULL
)
3407 setbuffer(fp
, buf
, bufsize
);
3408 if (generic_record_read(fp
, tcp_show_line
, f
, AF_INET
))
3413 if ((f
->families
& FAMILY_MASK(AF_INET6
)) &&
3414 (fp
= net_tcp6_open()) != NULL
) {
3415 setbuffer(fp
, buf
, bufsize
);
3416 if (generic_record_read(fp
, tcp_show_line
, f
, AF_INET6
))
3426 int saved_errno
= errno
;
3431 errno
= saved_errno
;
3436 static int dccp_show(struct filter
*f
)
3438 if (!filter_af_get(f
, AF_INET
) && !filter_af_get(f
, AF_INET6
))
3441 if (!getenv("PROC_NET_DCCP") && !getenv("PROC_ROOT")
3442 && inet_show_netlink(f
, NULL
, IPPROTO_DCCP
) == 0)
3448 static int sctp_show(struct filter
*f
)
3450 if (!filter_af_get(f
, AF_INET
) && !filter_af_get(f
, AF_INET6
))
3453 if (!getenv("PROC_NET_SCTP") && !getenv("PROC_ROOT")
3454 && inet_show_netlink(f
, NULL
, IPPROTO_SCTP
) == 0)
3460 static int dgram_show_line(char *line
, const struct filter
*f
, int family
)
3462 struct sockstat s
= {};
3463 char *loc
, *rem
, *data
;
3467 if (proc_inet_split_line(line
, &loc
, &rem
, &data
))
3470 int state
= (data
[1] >= 'A') ? (data
[1] - 'A' + 10) : (data
[1] - '0');
3472 if (!(f
->states
& (1 << state
)))
3475 proc_parse_inet_addr(loc
, rem
, family
, &s
);
3477 if (f
->f
&& run_ssfilter(f
->f
, &s
) == 0)
3481 n
= sscanf(data
, "%x %x:%x %*x:%*x %*x %d %*d %u %d %llx %[^\n]\n",
3482 &s
.state
, &s
.wq
, &s
.rq
,
3484 &s
.refcnt
, &s
.sk
, opt
);
3489 s
.type
= dg_proto
== UDP_PROTO
? IPPROTO_UDP
: 0;
3490 inet_stats_print(&s
, false);
3492 if (show_details
&& opt
[0])
3493 out(" opt:\"%s\"", opt
);
3498 static int udp_show(struct filter
*f
)
3502 if (!filter_af_get(f
, AF_INET
) && !filter_af_get(f
, AF_INET6
))
3505 dg_proto
= UDP_PROTO
;
3507 if (!getenv("PROC_NET_UDP") && !getenv("PROC_ROOT")
3508 && inet_show_netlink(f
, NULL
, IPPROTO_UDP
) == 0)
3511 if (f
->families
&FAMILY_MASK(AF_INET
)) {
3512 if ((fp
= net_udp_open()) == NULL
)
3514 if (generic_record_read(fp
, dgram_show_line
, f
, AF_INET
))
3519 if ((f
->families
&FAMILY_MASK(AF_INET6
)) &&
3520 (fp
= net_udp6_open()) != NULL
) {
3521 if (generic_record_read(fp
, dgram_show_line
, f
, AF_INET6
))
3529 int saved_errno
= errno
;
3533 errno
= saved_errno
;
3538 static int raw_show(struct filter
*f
)
3542 if (!filter_af_get(f
, AF_INET
) && !filter_af_get(f
, AF_INET6
))
3545 dg_proto
= RAW_PROTO
;
3547 if (!getenv("PROC_NET_RAW") && !getenv("PROC_ROOT") &&
3548 inet_show_netlink(f
, NULL
, IPPROTO_RAW
) == 0)
3551 if (f
->families
&FAMILY_MASK(AF_INET
)) {
3552 if ((fp
= net_raw_open()) == NULL
)
3554 if (generic_record_read(fp
, dgram_show_line
, f
, AF_INET
))
3559 if ((f
->families
&FAMILY_MASK(AF_INET6
)) &&
3560 (fp
= net_raw6_open()) != NULL
) {
3561 if (generic_record_read(fp
, dgram_show_line
, f
, AF_INET6
))
3569 int saved_errno
= errno
;
3573 errno
= saved_errno
;
3578 #define MAX_UNIX_REMEMBER (1024*1024/sizeof(struct sockstat))
3580 static void unix_list_drop_first(struct sockstat
**list
)
3582 struct sockstat
*s
= *list
;
3584 (*list
) = (*list
)->next
;
3589 static bool unix_type_skip(struct sockstat
*s
, struct filter
*f
)
3591 if (s
->type
== SOCK_STREAM
&& !(f
->dbs
&(1<<UNIX_ST_DB
)))
3593 if (s
->type
== SOCK_DGRAM
&& !(f
->dbs
&(1<<UNIX_DG_DB
)))
3595 if (s
->type
== SOCK_SEQPACKET
&& !(f
->dbs
&(1<<UNIX_SQ_DB
)))
3600 static void unix_stats_print(struct sockstat
*s
, struct filter
*f
)
3602 char port_name
[30] = {};
3604 sock_state_print(s
);
3606 sock_addr_print(s
->name
?: "*", " ",
3607 int_to_str(s
->lport
, port_name
), NULL
);
3608 sock_addr_print(s
->peer_name
?: "*", " ",
3609 int_to_str(s
->rport
, port_name
), NULL
);
3614 static int unix_show_sock(struct nlmsghdr
*nlh
, void *arg
)
3616 struct filter
*f
= (struct filter
*)arg
;
3617 struct unix_diag_msg
*r
= NLMSG_DATA(nlh
);
3618 struct rtattr
*tb
[UNIX_DIAG_MAX
+1];
3620 struct sockstat stat
= { .name
= "*", .peer_name
= "*" };
3622 parse_rtattr(tb
, UNIX_DIAG_MAX
, (struct rtattr
*)(r
+1),
3623 nlh
->nlmsg_len
- NLMSG_LENGTH(sizeof(*r
)));
3625 stat
.type
= r
->udiag_type
;
3626 stat
.state
= r
->udiag_state
;
3627 stat
.ino
= stat
.lport
= r
->udiag_ino
;
3628 stat
.local
.family
= stat
.remote
.family
= AF_UNIX
;
3630 if (unix_type_skip(&stat
, f
))
3633 if (tb
[UNIX_DIAG_RQLEN
]) {
3634 struct unix_diag_rqlen
*rql
= RTA_DATA(tb
[UNIX_DIAG_RQLEN
]);
3636 stat
.rq
= rql
->udiag_rqueue
;
3637 stat
.wq
= rql
->udiag_wqueue
;
3639 if (tb
[UNIX_DIAG_NAME
]) {
3640 int len
= RTA_PAYLOAD(tb
[UNIX_DIAG_NAME
]);
3642 memcpy(name
, RTA_DATA(tb
[UNIX_DIAG_NAME
]), len
);
3644 if (name
[0] == '\0') {
3646 for (i
= 0; i
< len
; i
++)
3647 if (name
[i
] == '\0')
3650 stat
.name
= &name
[0];
3651 memcpy(stat
.local
.data
, &stat
.name
, sizeof(stat
.name
));
3653 if (tb
[UNIX_DIAG_PEER
])
3654 stat
.rport
= rta_getattr_u32(tb
[UNIX_DIAG_PEER
]);
3656 if (f
->f
&& run_ssfilter(f
->f
, &stat
) == 0)
3659 unix_stats_print(&stat
, f
);
3662 print_skmeminfo(tb
, UNIX_DIAG_MEMINFO
);
3664 if (tb
[UNIX_DIAG_SHUTDOWN
]) {
3667 mask
= rta_getattr_u8(tb
[UNIX_DIAG_SHUTDOWN
]);
3669 mask
& 1 ? '-' : '<', mask
& 2 ? '-' : '>');
3671 if (tb
[UNIX_DIAG_VFS
]) {
3672 struct unix_diag_vfs
*uv
= RTA_DATA(tb
[UNIX_DIAG_VFS
]);
3674 out(" ino:%u dev:%u/%u", uv
->udiag_vfs_ino
, major(uv
->udiag_vfs_dev
),
3675 minor(uv
->udiag_vfs_dev
));
3677 if (tb
[UNIX_DIAG_ICONS
]) {
3678 int len
= RTA_PAYLOAD(tb
[UNIX_DIAG_ICONS
]);
3679 __u32
*peers
= RTA_DATA(tb
[UNIX_DIAG_ICONS
]);
3683 for (i
= 0; i
< len
/ sizeof(__u32
); i
++)
3684 out(" %u", peers
[i
]);
3691 static int handle_netlink_request(struct filter
*f
, struct nlmsghdr
*req
,
3692 size_t size
, rtnl_filter_t show_one_sock
)
3695 struct rtnl_handle rth
;
3697 if (rtnl_open_byproto(&rth
, 0, NETLINK_SOCK_DIAG
))
3700 rth
.dump
= MAGIC_SEQ
;
3702 if (rtnl_send(&rth
, req
, size
) < 0)
3705 if (rtnl_dump_filter(&rth
, show_one_sock
, f
))
3714 static int unix_show_netlink(struct filter
*f
)
3716 DIAG_REQUEST(req
, struct unix_diag_req r
);
3718 req
.r
.sdiag_family
= AF_UNIX
;
3719 req
.r
.udiag_states
= f
->states
;
3720 req
.r
.udiag_show
= UDIAG_SHOW_NAME
| UDIAG_SHOW_PEER
| UDIAG_SHOW_RQLEN
;
3722 req
.r
.udiag_show
|= UDIAG_SHOW_MEMINFO
;
3724 req
.r
.udiag_show
|= UDIAG_SHOW_VFS
| UDIAG_SHOW_ICONS
;
3726 return handle_netlink_request(f
, &req
.nlh
, sizeof(req
), unix_show_sock
);
3729 static int unix_show(struct filter
*f
)
3736 struct sockstat
*list
= NULL
;
3737 const int unix_state_map
[] = { SS_CLOSE
, SS_SYN_SENT
,
3738 SS_ESTABLISHED
, SS_CLOSING
};
3740 if (!filter_af_get(f
, AF_UNIX
))
3743 if (!getenv("PROC_NET_UNIX") && !getenv("PROC_ROOT")
3744 && unix_show_netlink(f
) == 0)
3747 if ((fp
= net_unix_open()) == NULL
)
3749 if (!fgets(buf
, sizeof(buf
), fp
)) {
3754 if (memcmp(buf
, "Peer", 4) == 0)
3758 while (fgets(buf
, sizeof(buf
), fp
)) {
3759 struct sockstat
*u
, **insp
;
3762 if (!(u
= calloc(1, sizeof(*u
))))
3765 if (sscanf(buf
, "%x: %x %x %x %x %x %d %s",
3766 &u
->rport
, &u
->rq
, &u
->wq
, &flags
, &u
->type
,
3767 &u
->state
, &u
->ino
, name
) < 8)
3771 u
->local
.family
= u
->remote
.family
= AF_UNIX
;
3773 if (flags
& (1 << 16)) {
3774 u
->state
= SS_LISTEN
;
3775 } else if (u
->state
> 0 &&
3776 u
->state
<= ARRAY_SIZE(unix_state_map
)) {
3777 u
->state
= unix_state_map
[u
->state
-1];
3778 if (u
->type
== SOCK_DGRAM
&& u
->state
== SS_CLOSE
&& u
->rport
)
3779 u
->state
= SS_ESTABLISHED
;
3781 if (unix_type_skip(u
, f
) ||
3782 !(f
->states
& (1 << u
->state
))) {
3794 u
->name
= strdup(name
);
3804 for (p
= list
; p
; p
= p
->next
) {
3805 if (u
->rport
== p
->lport
)
3811 u
->peer_name
= p
->name
? : "*";
3815 struct sockstat st
= {
3816 .local
.family
= AF_UNIX
,
3817 .remote
.family
= AF_UNIX
,
3820 memcpy(st
.local
.data
, &u
->name
, sizeof(u
->name
));
3821 /* when parsing the old format rport is set to 0 and
3822 * therefore peer_name remains NULL
3824 if (u
->peer_name
&& strcmp(u
->peer_name
, "*"))
3825 memcpy(st
.remote
.data
, &u
->peer_name
,
3826 sizeof(u
->peer_name
));
3827 if (run_ssfilter(f
->f
, &st
) == 0) {
3836 if (u
->type
< (*insp
)->type
||
3837 (u
->type
== (*insp
)->type
&&
3838 u
->ino
< (*insp
)->ino
))
3840 insp
= &(*insp
)->next
;
3845 if (++cnt
> MAX_UNIX_REMEMBER
) {
3847 unix_stats_print(list
, f
);
3848 unix_list_drop_first(&list
);
3855 unix_stats_print(list
, f
);
3856 unix_list_drop_first(&list
);
3862 static int packet_stats_print(struct sockstat
*s
, const struct filter
*f
)
3864 const char *addr
, *port
;
3867 s
->local
.family
= s
->remote
.family
= AF_PACKET
;
3870 s
->local
.data
[0] = s
->prot
;
3871 if (run_ssfilter(f
->f
, s
) == 0)
3875 sock_state_print(s
);
3880 addr
= ll_proto_n2a(htons(s
->prot
), ll_name
, sizeof(ll_name
));
3885 port
= xll_index_to_name(s
->iface
);
3887 sock_addr_print(addr
, ":", port
, NULL
);
3888 sock_addr_print("", "*", "", NULL
);
3893 sock_details_print(s
);
3898 static void packet_show_ring(struct packet_diag_ring
*ring
)
3900 out("blk_size:%d", ring
->pdr_block_size
);
3901 out(",blk_nr:%d", ring
->pdr_block_nr
);
3902 out(",frm_size:%d", ring
->pdr_frame_size
);
3903 out(",frm_nr:%d", ring
->pdr_frame_nr
);
3904 out(",tmo:%d", ring
->pdr_retire_tmo
);
3905 out(",features:0x%x", ring
->pdr_features
);
3908 static int packet_show_sock(struct nlmsghdr
*nlh
, void *arg
)
3910 const struct filter
*f
= arg
;
3911 struct packet_diag_msg
*r
= NLMSG_DATA(nlh
);
3912 struct packet_diag_info
*pinfo
= NULL
;
3913 struct packet_diag_ring
*ring_rx
= NULL
, *ring_tx
= NULL
;
3914 struct rtattr
*tb
[PACKET_DIAG_MAX
+1];
3915 struct sockstat stat
= {};
3916 uint32_t fanout
= 0;
3917 bool has_fanout
= false;
3919 parse_rtattr(tb
, PACKET_DIAG_MAX
, (struct rtattr
*)(r
+1),
3920 nlh
->nlmsg_len
- NLMSG_LENGTH(sizeof(*r
)));
3922 /* use /proc/net/packet if all info are not available */
3923 if (!tb
[PACKET_DIAG_MEMINFO
])
3926 stat
.type
= r
->pdiag_type
;
3927 stat
.prot
= r
->pdiag_num
;
3928 stat
.ino
= r
->pdiag_ino
;
3929 stat
.state
= SS_CLOSE
;
3930 stat
.sk
= cookie_sk_get(&r
->pdiag_cookie
[0]);
3932 if (tb
[PACKET_DIAG_MEMINFO
]) {
3933 __u32
*skmeminfo
= RTA_DATA(tb
[PACKET_DIAG_MEMINFO
]);
3935 stat
.rq
= skmeminfo
[SK_MEMINFO_RMEM_ALLOC
];
3938 if (tb
[PACKET_DIAG_INFO
]) {
3939 pinfo
= RTA_DATA(tb
[PACKET_DIAG_INFO
]);
3940 stat
.lport
= stat
.iface
= pinfo
->pdi_index
;
3943 if (tb
[PACKET_DIAG_UID
])
3944 stat
.uid
= rta_getattr_u32(tb
[PACKET_DIAG_UID
]);
3946 if (tb
[PACKET_DIAG_RX_RING
])
3947 ring_rx
= RTA_DATA(tb
[PACKET_DIAG_RX_RING
]);
3949 if (tb
[PACKET_DIAG_TX_RING
])
3950 ring_tx
= RTA_DATA(tb
[PACKET_DIAG_TX_RING
]);
3952 if (tb
[PACKET_DIAG_FANOUT
]) {
3954 fanout
= rta_getattr_u32(tb
[PACKET_DIAG_FANOUT
]);
3957 if (packet_stats_print(&stat
, f
))
3962 out("\n\tver:%d", pinfo
->pdi_version
);
3963 out(" cpy_thresh:%d", pinfo
->pdi_copy_thresh
);
3965 if (pinfo
->pdi_flags
& PDI_RUNNING
)
3967 if (pinfo
->pdi_flags
& PDI_AUXDATA
)
3969 if (pinfo
->pdi_flags
& PDI_ORIGDEV
)
3971 if (pinfo
->pdi_flags
& PDI_VNETHDR
)
3973 if (pinfo
->pdi_flags
& PDI_LOSS
)
3975 if (!pinfo
->pdi_flags
)
3980 out("\n\tring_rx(");
3981 packet_show_ring(ring_rx
);
3985 out("\n\tring_tx(");
3986 packet_show_ring(ring_tx
);
3990 uint16_t type
= (fanout
>> 16) & 0xffff;
3993 out("id:%d,", fanout
& 0xffff);
4015 if (show_bpf
&& tb
[PACKET_DIAG_FILTER
]) {
4016 struct sock_filter
*fil
=
4017 RTA_DATA(tb
[PACKET_DIAG_FILTER
]);
4018 int num
= RTA_PAYLOAD(tb
[PACKET_DIAG_FILTER
]) /
4019 sizeof(struct sock_filter
);
4021 out("\n\tbpf filter (%d): ", num
);
4023 out(" 0x%02x %u %u %u,",
4024 fil
->code
, fil
->jt
, fil
->jf
, fil
->k
);
4031 print_skmeminfo(tb
, PACKET_DIAG_MEMINFO
);
4035 static int packet_show_netlink(struct filter
*f
)
4037 DIAG_REQUEST(req
, struct packet_diag_req r
);
4039 req
.r
.sdiag_family
= AF_PACKET
;
4040 req
.r
.pdiag_show
= PACKET_SHOW_INFO
| PACKET_SHOW_MEMINFO
|
4041 PACKET_SHOW_FILTER
| PACKET_SHOW_RING_CFG
| PACKET_SHOW_FANOUT
;
4043 return handle_netlink_request(f
, &req
.nlh
, sizeof(req
), packet_show_sock
);
4046 static int packet_show_line(char *buf
, const struct filter
*f
, int fam
)
4048 unsigned long long sk
;
4049 struct sockstat stat
= {};
4050 int type
, prot
, iface
, state
, rq
, uid
, ino
;
4052 sscanf(buf
, "%llx %*d %d %x %d %d %u %u %u",
4054 &type
, &prot
, &iface
, &state
,
4057 if (stat
.type
== SOCK_RAW
&& !(f
->dbs
&(1<<PACKET_R_DB
)))
4059 if (stat
.type
== SOCK_DGRAM
&& !(f
->dbs
&(1<<PACKET_DG_DB
)))
4064 stat
.lport
= stat
.iface
= iface
;
4069 stat
.state
= SS_CLOSE
;
4071 if (packet_stats_print(&stat
, f
))
4077 static int packet_show(struct filter
*f
)
4082 if (!filter_af_get(f
, AF_PACKET
) || !(f
->states
& (1 << SS_CLOSE
)))
4085 if (!getenv("PROC_NET_PACKET") && !getenv("PROC_ROOT") &&
4086 packet_show_netlink(f
) == 0)
4089 if ((fp
= net_packet_open()) == NULL
)
4091 if (generic_record_read(fp
, packet_show_line
, f
, AF_PACKET
))
4098 static int netlink_show_one(struct filter
*f
,
4099 int prot
, int pid
, unsigned int groups
,
4100 int state
, int dst_pid
, unsigned int dst_group
,
4102 unsigned long long sk
, unsigned long long cb
)
4104 struct sockstat st
= {
4108 .local
.family
= AF_NETLINK
,
4109 .remote
.family
= AF_NETLINK
,
4112 SPRINT_BUF(prot_buf
) = {};
4113 const char *prot_name
;
4114 char procname
[64] = {};
4119 st
.local
.data
[0] = prot
;
4120 if (run_ssfilter(f
->f
, &st
) == 0)
4124 sock_state_print(&st
);
4126 if (resolve_services
)
4127 prot_name
= nl_proto_n2a(prot
, prot_buf
, sizeof(prot_buf
));
4129 prot_name
= int_to_str(prot
, prot_buf
);
4133 } else if (resolve_services
) {
4138 strncpy(procname
, "kernel", 7);
4139 } else if (pid
> 0) {
4142 snprintf(procname
, sizeof(procname
), "%s/%d/stat",
4143 getenv("PROC_ROOT") ? : "/proc", pid
);
4144 if ((fp
= fopen(procname
, "r")) != NULL
) {
4145 if (fscanf(fp
, "%*d (%[^)])", procname
) == 1) {
4146 snprintf(procname
+strlen(procname
),
4147 sizeof(procname
)-strlen(procname
),
4155 int_to_str(pid
, procname
);
4157 int_to_str(pid
, procname
);
4160 sock_addr_print(prot_name
, ":", procname
, NULL
);
4162 if (state
== NETLINK_CONNECTED
) {
4163 char dst_group_buf
[30];
4164 char dst_pid_buf
[30];
4166 sock_addr_print(int_to_str(dst_group
, dst_group_buf
), ":",
4167 int_to_str(dst_pid
, dst_pid_buf
), NULL
);
4169 sock_addr_print("", "*", "", NULL
);
4172 char *pid_context
= NULL
;
4174 if (show_proc_ctx
) {
4175 /* The pid value will either be:
4176 * 0 if destination kernel - show kernel initial context.
4177 * A valid process pid - use getpidcon.
4178 * A unique value allocated by the kernel or netlink user
4179 * to the process - show context as "not available".
4182 security_get_initial_context("kernel", &pid_context
);
4184 getpidcon(pid
, &pid_context
);
4186 out(" proc_ctx=%s", pid_context
? : "unavailable");
4191 out(" sk=%llx cb=%llx groups=0x%08x", sk
, cb
, groups
);
4197 static int netlink_show_sock(struct nlmsghdr
*nlh
, void *arg
)
4199 struct filter
*f
= (struct filter
*)arg
;
4200 struct netlink_diag_msg
*r
= NLMSG_DATA(nlh
);
4201 struct rtattr
*tb
[NETLINK_DIAG_MAX
+1];
4203 unsigned long groups
= 0;
4205 parse_rtattr(tb
, NETLINK_DIAG_MAX
, (struct rtattr
*)(r
+1),
4206 nlh
->nlmsg_len
- NLMSG_LENGTH(sizeof(*r
)));
4208 if (tb
[NETLINK_DIAG_GROUPS
] && RTA_PAYLOAD(tb
[NETLINK_DIAG_GROUPS
]))
4209 groups
= *(unsigned long *) RTA_DATA(tb
[NETLINK_DIAG_GROUPS
]);
4211 if (tb
[NETLINK_DIAG_MEMINFO
]) {
4212 const __u32
*skmeminfo
;
4214 skmeminfo
= RTA_DATA(tb
[NETLINK_DIAG_MEMINFO
]);
4216 rq
= skmeminfo
[SK_MEMINFO_RMEM_ALLOC
];
4217 wq
= skmeminfo
[SK_MEMINFO_WMEM_ALLOC
];
4220 if (netlink_show_one(f
, r
->ndiag_protocol
, r
->ndiag_portid
, groups
,
4221 r
->ndiag_state
, r
->ndiag_dst_portid
, r
->ndiag_dst_group
,
4228 print_skmeminfo(tb
, NETLINK_DIAG_MEMINFO
);
4234 static int netlink_show_netlink(struct filter
*f
)
4236 DIAG_REQUEST(req
, struct netlink_diag_req r
);
4238 req
.r
.sdiag_family
= AF_NETLINK
;
4239 req
.r
.sdiag_protocol
= NDIAG_PROTO_ALL
;
4240 req
.r
.ndiag_show
= NDIAG_SHOW_GROUPS
| NDIAG_SHOW_MEMINFO
;
4242 return handle_netlink_request(f
, &req
.nlh
, sizeof(req
), netlink_show_sock
);
4245 static int netlink_show(struct filter
*f
)
4250 unsigned int groups
;
4252 unsigned long long sk
, cb
;
4254 if (!filter_af_get(f
, AF_NETLINK
) || !(f
->states
& (1 << SS_CLOSE
)))
4257 if (!getenv("PROC_NET_NETLINK") && !getenv("PROC_ROOT") &&
4258 netlink_show_netlink(f
) == 0)
4261 if ((fp
= net_netlink_open()) == NULL
)
4263 if (!fgets(buf
, sizeof(buf
), fp
)) {
4268 while (fgets(buf
, sizeof(buf
), fp
)) {
4269 sscanf(buf
, "%llx %d %d %x %d %d %llx %d",
4271 &prot
, &pid
, &groups
, &rq
, &wq
, &cb
, &rc
);
4273 netlink_show_one(f
, prot
, pid
, groups
, 0, 0, 0, rq
, wq
, sk
, cb
);
4280 static bool vsock_type_skip(struct sockstat
*s
, struct filter
*f
)
4282 if (s
->type
== SOCK_STREAM
&& !(f
->dbs
& (1 << VSOCK_ST_DB
)))
4284 if (s
->type
== SOCK_DGRAM
&& !(f
->dbs
& (1 << VSOCK_DG_DB
)))
4289 static void vsock_addr_print(inet_prefix
*a
, __u32 port
)
4291 char cid_str
[sizeof("4294967295")];
4292 char port_str
[sizeof("4294967295")];
4295 memcpy(&cid
, a
->data
, sizeof(cid
));
4297 if (cid
== ~(__u32
)0)
4298 snprintf(cid_str
, sizeof(cid_str
), "*");
4300 snprintf(cid_str
, sizeof(cid_str
), "%u", cid
);
4302 if (port
== ~(__u32
)0)
4303 snprintf(port_str
, sizeof(port_str
), "*");
4305 snprintf(port_str
, sizeof(port_str
), "%u", port
);
4307 sock_addr_print(cid_str
, ":", port_str
, NULL
);
4310 static void vsock_stats_print(struct sockstat
*s
, struct filter
*f
)
4312 sock_state_print(s
);
4314 vsock_addr_print(&s
->local
, s
->lport
);
4315 vsock_addr_print(&s
->remote
, s
->rport
);
4320 static int vsock_show_sock(struct nlmsghdr
*nlh
, void *arg
)
4322 struct filter
*f
= (struct filter
*)arg
;
4323 struct vsock_diag_msg
*r
= NLMSG_DATA(nlh
);
4324 struct sockstat stat
= {
4325 .type
= r
->vdiag_type
,
4326 .lport
= r
->vdiag_src_port
,
4327 .rport
= r
->vdiag_dst_port
,
4328 .state
= r
->vdiag_state
,
4329 .ino
= r
->vdiag_ino
,
4332 vsock_set_inet_prefix(&stat
.local
, r
->vdiag_src_cid
);
4333 vsock_set_inet_prefix(&stat
.remote
, r
->vdiag_dst_cid
);
4335 if (vsock_type_skip(&stat
, f
))
4338 if (f
->f
&& run_ssfilter(f
->f
, &stat
) == 0)
4341 vsock_stats_print(&stat
, f
);
4346 static int vsock_show(struct filter
*f
)
4348 DIAG_REQUEST(req
, struct vsock_diag_req r
);
4350 if (!filter_af_get(f
, AF_VSOCK
))
4353 req
.r
.sdiag_family
= AF_VSOCK
;
4354 req
.r
.vdiag_states
= f
->states
;
4356 return handle_netlink_request(f
, &req
.nlh
, sizeof(req
), vsock_show_sock
);
4359 static void tipc_sock_addr_print(struct rtattr
*net_addr
, struct rtattr
*id
)
4361 uint32_t node
= rta_getattr_u32(net_addr
);
4362 uint32_t identity
= rta_getattr_u32(id
);
4364 SPRINT_BUF(addr
) = {};
4365 SPRINT_BUF(port
) = {};
4367 sprintf(addr
, "%u", node
);
4368 sprintf(port
, "%u", identity
);
4369 sock_addr_print(addr
, ":", port
, NULL
);
4373 static int tipc_show_sock(struct nlmsghdr
*nlh
, void *arg
)
4375 struct rtattr
*stat
[TIPC_NLA_SOCK_STAT_MAX
+ 1] = {};
4376 struct rtattr
*attrs
[TIPC_NLA_SOCK_MAX
+ 1] = {};
4377 struct rtattr
*con
[TIPC_NLA_CON_MAX
+ 1] = {};
4378 struct rtattr
*info
[TIPC_NLA_MAX
+ 1] = {};
4379 struct rtattr
*msg_ref
;
4380 struct sockstat ss
= {};
4382 parse_rtattr(info
, TIPC_NLA_MAX
, NLMSG_DATA(nlh
),
4383 NLMSG_PAYLOAD(nlh
, 0));
4385 if (!info
[TIPC_NLA_SOCK
])
4388 msg_ref
= info
[TIPC_NLA_SOCK
];
4389 parse_rtattr(attrs
, TIPC_NLA_SOCK_MAX
, RTA_DATA(msg_ref
),
4390 RTA_PAYLOAD(msg_ref
));
4392 msg_ref
= attrs
[TIPC_NLA_SOCK_STAT
];
4393 parse_rtattr(stat
, TIPC_NLA_SOCK_STAT_MAX
,
4394 RTA_DATA(msg_ref
), RTA_PAYLOAD(msg_ref
));
4397 ss
.local
.family
= AF_TIPC
;
4398 ss
.type
= rta_getattr_u32(attrs
[TIPC_NLA_SOCK_TYPE
]);
4399 ss
.state
= rta_getattr_u32(attrs
[TIPC_NLA_SOCK_TIPC_STATE
]);
4400 ss
.uid
= rta_getattr_u32(attrs
[TIPC_NLA_SOCK_UID
]);
4401 ss
.ino
= rta_getattr_u32(attrs
[TIPC_NLA_SOCK_INO
]);
4402 ss
.rq
= rta_getattr_u32(stat
[TIPC_NLA_SOCK_STAT_RCVQ
]);
4403 ss
.wq
= rta_getattr_u32(stat
[TIPC_NLA_SOCK_STAT_SENDQ
]);
4404 ss
.sk
= rta_getattr_u64(attrs
[TIPC_NLA_SOCK_COOKIE
]);
4406 sock_state_print (&ss
);
4408 tipc_sock_addr_print(attrs
[TIPC_NLA_SOCK_ADDR
],
4409 attrs
[TIPC_NLA_SOCK_REF
]);
4411 msg_ref
= attrs
[TIPC_NLA_SOCK_CON
];
4413 parse_rtattr(con
, TIPC_NLA_CON_MAX
,
4414 RTA_DATA(msg_ref
), RTA_PAYLOAD(msg_ref
));
4416 tipc_sock_addr_print(con
[TIPC_NLA_CON_NODE
],
4417 con
[TIPC_NLA_CON_SOCK
]);
4419 sock_addr_print("", "-", "", NULL
);
4422 sock_details_print(&ss
);
4424 proc_ctx_print(&ss
);
4426 if (show_tipcinfo
) {
4427 out("\n type:%s", stype_nameg
[ss
.type
]);
4429 stat
[TIPC_NLA_SOCK_STAT_LINK_CONG
] ? "link" :
4430 stat
[TIPC_NLA_SOCK_STAT_CONN_CONG
] ? "conn" : "none");
4432 rta_getattr_u32(stat
[TIPC_NLA_SOCK_STAT_DROP
]));
4434 if (attrs
[TIPC_NLA_SOCK_HAS_PUBL
])
4437 if (con
[TIPC_NLA_CON_FLAG
])
4438 out(" via {%u,%u} ",
4439 rta_getattr_u32(con
[TIPC_NLA_CON_TYPE
]),
4440 rta_getattr_u32(con
[TIPC_NLA_CON_INST
]));
4446 static int tipc_show(struct filter
*f
)
4448 DIAG_REQUEST(req
, struct tipc_sock_diag_req r
);
4450 memset(&req
.r
, 0, sizeof(req
.r
));
4451 req
.r
.sdiag_family
= AF_TIPC
;
4452 req
.r
.tidiag_states
= f
->states
;
4454 return handle_netlink_request(f
, &req
.nlh
, sizeof(req
), tipc_show_sock
);
4457 struct sock_diag_msg
{
4461 static int generic_show_sock(struct nlmsghdr
*nlh
, void *arg
)
4463 struct sock_diag_msg
*r
= NLMSG_DATA(nlh
);
4464 struct inet_diag_arg inet_arg
= { .f
= arg
, .protocol
= IPPROTO_MAX
};
4467 switch (r
->sdiag_family
) {
4470 inet_arg
.rth
= inet_arg
.f
->rth_for_killing
;
4471 ret
= show_one_inet_sock(nlh
, &inet_arg
);
4474 ret
= unix_show_sock(nlh
, arg
);
4477 ret
= packet_show_sock(nlh
, arg
);
4480 ret
= netlink_show_sock(nlh
, arg
);
4483 ret
= vsock_show_sock(nlh
, arg
);
4494 static int handle_follow_request(struct filter
*f
)
4498 struct rtnl_handle rth
, rth2
;
4500 if (f
->families
& FAMILY_MASK(AF_INET
) && f
->dbs
& (1 << TCP_DB
))
4501 groups
|= 1 << (SKNLGRP_INET_TCP_DESTROY
- 1);
4502 if (f
->families
& FAMILY_MASK(AF_INET
) && f
->dbs
& (1 << UDP_DB
))
4503 groups
|= 1 << (SKNLGRP_INET_UDP_DESTROY
- 1);
4504 if (f
->families
& FAMILY_MASK(AF_INET6
) && f
->dbs
& (1 << TCP_DB
))
4505 groups
|= 1 << (SKNLGRP_INET6_TCP_DESTROY
- 1);
4506 if (f
->families
& FAMILY_MASK(AF_INET6
) && f
->dbs
& (1 << UDP_DB
))
4507 groups
|= 1 << (SKNLGRP_INET6_UDP_DESTROY
- 1);
4512 if (rtnl_open_byproto(&rth
, groups
, NETLINK_SOCK_DIAG
))
4516 rth
.local
.nl_pid
= 0;
4519 if (rtnl_open_byproto(&rth2
, groups
, NETLINK_SOCK_DIAG
)) {
4523 f
->rth_for_killing
= &rth2
;
4526 if (rtnl_dump_filter(&rth
, generic_show_sock
, f
))
4530 if (f
->rth_for_killing
)
4531 rtnl_close(f
->rth_for_killing
);
4535 static int get_snmp_int(char *proto
, char *key
, int *result
)
4539 int protolen
= strlen(proto
);
4540 int keylen
= strlen(key
);
4544 if ((fp
= net_snmp_open()) == NULL
)
4547 while (fgets(buf
, sizeof(buf
), fp
) != NULL
) {
4551 if (memcmp(buf
, proto
, protolen
))
4553 while ((p
= strchr(p
, ' ')) != NULL
) {
4556 if (memcmp(p
, key
, keylen
) == 0 &&
4557 (p
[keylen
] == ' ' || p
[keylen
] == '\n'))
4560 if (fgets(buf
, sizeof(buf
), fp
) == NULL
)
4562 if (memcmp(buf
, proto
, protolen
))
4565 while ((p
= strchr(p
, ' ')) != NULL
) {
4568 sscanf(p
, "%d", result
);
4581 /* Get stats from sockstat */
4601 static void get_sockstat_line(char *line
, struct ssummary
*s
)
4603 char id
[256], rem
[256];
4605 if (sscanf(line
, "%[^ ] %[^\n]\n", id
, rem
) != 2)
4608 if (strcmp(id
, "sockets:") == 0)
4609 sscanf(rem
, "%*s%d", &s
->socks
);
4610 else if (strcmp(id
, "UDP:") == 0)
4611 sscanf(rem
, "%*s%d", &s
->udp4
);
4612 else if (strcmp(id
, "UDP6:") == 0)
4613 sscanf(rem
, "%*s%d", &s
->udp6
);
4614 else if (strcmp(id
, "RAW:") == 0)
4615 sscanf(rem
, "%*s%d", &s
->raw4
);
4616 else if (strcmp(id
, "RAW6:") == 0)
4617 sscanf(rem
, "%*s%d", &s
->raw6
);
4618 else if (strcmp(id
, "TCP6:") == 0)
4619 sscanf(rem
, "%*s%d", &s
->tcp6_hashed
);
4620 else if (strcmp(id
, "FRAG:") == 0)
4621 sscanf(rem
, "%*s%d%*s%d", &s
->frag4
, &s
->frag4_mem
);
4622 else if (strcmp(id
, "FRAG6:") == 0)
4623 sscanf(rem
, "%*s%d%*s%d", &s
->frag6
, &s
->frag6_mem
);
4624 else if (strcmp(id
, "TCP:") == 0)
4625 sscanf(rem
, "%*s%d%*s%d%*s%d%*s%d%*s%d",
4627 &s
->tcp_orphans
, &s
->tcp_tws
, &s
->tcp_total
, &s
->tcp_mem
);
4630 static int get_sockstat(struct ssummary
*s
)
4635 memset(s
, 0, sizeof(*s
));
4637 if ((fp
= net_sockstat_open()) == NULL
)
4639 while (fgets(buf
, sizeof(buf
), fp
) != NULL
)
4640 get_sockstat_line(buf
, s
);
4643 if ((fp
= net_sockstat6_open()) == NULL
)
4645 while (fgets(buf
, sizeof(buf
), fp
) != NULL
)
4646 get_sockstat_line(buf
, s
);
4652 static int print_summary(void)
4657 if (get_sockstat(&s
) < 0)
4658 perror("ss: get_sockstat");
4659 if (get_snmp_int("Tcp:", "CurrEstab", &tcp_estab
) < 0)
4660 perror("ss: get_snmpstat");
4662 printf("Total: %d\n", s
.socks
);
4664 printf("TCP: %d (estab %d, closed %d, orphaned %d, timewait %d)\n",
4665 s
.tcp_total
+ s
.tcp_tws
, tcp_estab
,
4666 s
.tcp_total
- (s
.tcp4_hashed
+ s
.tcp6_hashed
- s
.tcp_tws
),
4667 s
.tcp_orphans
, s
.tcp_tws
);
4670 printf("Transport Total IP IPv6\n");
4671 printf("RAW %-9d %-9d %-9d\n", s
.raw4
+s
.raw6
, s
.raw4
, s
.raw6
);
4672 printf("UDP %-9d %-9d %-9d\n", s
.udp4
+s
.udp6
, s
.udp4
, s
.udp6
);
4673 printf("TCP %-9d %-9d %-9d\n", s
.tcp4_hashed
+s
.tcp6_hashed
, s
.tcp4_hashed
, s
.tcp6_hashed
);
4674 printf("INET %-9d %-9d %-9d\n",
4675 s
.raw4
+s
.udp4
+s
.tcp4_hashed
+
4676 s
.raw6
+s
.udp6
+s
.tcp6_hashed
,
4677 s
.raw4
+s
.udp4
+s
.tcp4_hashed
,
4678 s
.raw6
+s
.udp6
+s
.tcp6_hashed
);
4679 printf("FRAG %-9d %-9d %-9d\n", s
.frag4
+s
.frag6
, s
.frag4
, s
.frag6
);
4686 static void _usage(FILE *dest
)
4689 "Usage: ss [ OPTIONS ]\n"
4690 " ss [ OPTIONS ] [ FILTER ]\n"
4691 " -h, --help this message\n"
4692 " -V, --version output version information\n"
4693 " -n, --numeric don't resolve service names\n"
4694 " -r, --resolve resolve host names\n"
4695 " -a, --all display all sockets\n"
4696 " -l, --listening display listening sockets\n"
4697 " -o, --options show timer information\n"
4698 " -e, --extended show detailed socket information\n"
4699 " -m, --memory show socket memory usage\n"
4700 " -p, --processes show process using socket\n"
4701 " -i, --info show internal TCP information\n"
4702 " --tipcinfo show internal tipc socket information\n"
4703 " -s, --summary show socket usage summary\n"
4704 " --tos show tos and priority information\n"
4705 " -b, --bpf show bpf filter socket information\n"
4706 " -E, --events continually display sockets as they are destroyed\n"
4707 " -Z, --context display process SELinux security contexts\n"
4708 " -z, --contexts display process and socket SELinux security contexts\n"
4709 " -N, --net switch to the specified network namespace name\n"
4711 " -4, --ipv4 display only IP version 4 sockets\n"
4712 " -6, --ipv6 display only IP version 6 sockets\n"
4713 " -0, --packet display PACKET sockets\n"
4714 " -t, --tcp display only TCP sockets\n"
4715 " -S, --sctp display only SCTP sockets\n"
4716 " -u, --udp display only UDP sockets\n"
4717 " -d, --dccp display only DCCP sockets\n"
4718 " -w, --raw display only RAW sockets\n"
4719 " -x, --unix display only Unix domain sockets\n"
4720 " --tipc display only TIPC sockets\n"
4721 " --vsock display only vsock sockets\n"
4722 " -f, --family=FAMILY display sockets of type FAMILY\n"
4723 " FAMILY := {inet|inet6|link|unix|netlink|vsock|tipc|help}\n"
4725 " -K, --kill forcibly close sockets, display what was closed\n"
4726 " -H, --no-header Suppress header line\n"
4728 " -A, --query=QUERY, --socket=QUERY\n"
4729 " QUERY := {all|inet|tcp|udp|raw|unix|unix_dgram|unix_stream|unix_seqpacket|packet|netlink|vsock_stream|vsock_dgram|tipc}[,QUERY]\n"
4731 " -D, --diag=FILE Dump raw information about TCP sockets to FILE\n"
4732 " -F, --filter=FILE read filter information from FILE\n"
4733 " FILTER := [ state STATE-FILTER ] [ EXPRESSION ]\n"
4734 " STATE-FILTER := {all|connected|synchronized|bucket|big|TCP-STATES}\n"
4735 " TCP-STATES := {established|syn-sent|syn-recv|fin-wait-{1,2}|time-wait|closed|close-wait|last-ack|listening|closing}\n"
4736 " connected := {established|syn-sent|syn-recv|fin-wait-{1,2}|time-wait|close-wait|last-ack|closing}\n"
4737 " synchronized := {established|syn-recv|fin-wait-{1,2}|time-wait|close-wait|last-ack|closing}\n"
4738 " bucket := {syn-recv|time-wait}\n"
4739 " big := {established|syn-sent|fin-wait-{1,2}|closed|close-wait|last-ack|listening|closing}\n"
4743 static void help(void) __attribute__((noreturn
));
4744 static void help(void)
4750 static void usage(void) __attribute__((noreturn
));
4751 static void usage(void)
4758 static int scan_state(const char *state
)
4760 static const char * const sstate_namel
[] = {
4762 [SS_ESTABLISHED
] = "established",
4763 [SS_SYN_SENT
] = "syn-sent",
4764 [SS_SYN_RECV
] = "syn-recv",
4765 [SS_FIN_WAIT1
] = "fin-wait-1",
4766 [SS_FIN_WAIT2
] = "fin-wait-2",
4767 [SS_TIME_WAIT
] = "time-wait",
4768 [SS_CLOSE
] = "unconnected",
4769 [SS_CLOSE_WAIT
] = "close-wait",
4770 [SS_LAST_ACK
] = "last-ack",
4771 [SS_LISTEN
] = "listening",
4772 [SS_CLOSING
] = "closing",
4776 if (strcasecmp(state
, "close") == 0 ||
4777 strcasecmp(state
, "closed") == 0)
4778 return (1<<SS_CLOSE
);
4779 if (strcasecmp(state
, "syn-rcv") == 0)
4780 return (1<<SS_SYN_RECV
);
4781 if (strcasecmp(state
, "established") == 0)
4782 return (1<<SS_ESTABLISHED
);
4783 if (strcasecmp(state
, "all") == 0)
4785 if (strcasecmp(state
, "connected") == 0)
4786 return SS_ALL
& ~((1<<SS_CLOSE
)|(1<<SS_LISTEN
));
4787 if (strcasecmp(state
, "synchronized") == 0)
4788 return SS_ALL
& ~((1<<SS_CLOSE
)|(1<<SS_LISTEN
)|(1<<SS_SYN_SENT
));
4789 if (strcasecmp(state
, "bucket") == 0)
4790 return (1<<SS_SYN_RECV
)|(1<<SS_TIME_WAIT
);
4791 if (strcasecmp(state
, "big") == 0)
4792 return SS_ALL
& ~((1<<SS_SYN_RECV
)|(1<<SS_TIME_WAIT
));
4793 for (i
= 0; i
< SS_MAX
; i
++) {
4794 if (strcasecmp(state
, sstate_namel
[i
]) == 0)
4798 fprintf(stderr
, "ss: wrong state name: %s\n", state
);
4802 /* Values 'v' and 'V' are already used so a non-character is used */
4803 #define OPT_VSOCK 256
4805 /* Values of 't' are already used so a non-character is used */
4806 #define OPT_TIPCSOCK 257
4807 #define OPT_TIPCINFO 258
4811 static const struct option long_opts
[] = {
4812 { "numeric", 0, 0, 'n' },
4813 { "resolve", 0, 0, 'r' },
4814 { "options", 0, 0, 'o' },
4815 { "extended", 0, 0, 'e' },
4816 { "memory", 0, 0, 'm' },
4817 { "info", 0, 0, 'i' },
4818 { "processes", 0, 0, 'p' },
4819 { "bpf", 0, 0, 'b' },
4820 { "events", 0, 0, 'E' },
4821 { "dccp", 0, 0, 'd' },
4822 { "tcp", 0, 0, 't' },
4823 { "sctp", 0, 0, 'S' },
4824 { "udp", 0, 0, 'u' },
4825 { "raw", 0, 0, 'w' },
4826 { "unix", 0, 0, 'x' },
4827 { "tipc", 0, 0, OPT_TIPCSOCK
},
4828 { "vsock", 0, 0, OPT_VSOCK
},
4829 { "all", 0, 0, 'a' },
4830 { "listening", 0, 0, 'l' },
4831 { "ipv4", 0, 0, '4' },
4832 { "ipv6", 0, 0, '6' },
4833 { "packet", 0, 0, '0' },
4834 { "family", 1, 0, 'f' },
4835 { "socket", 1, 0, 'A' },
4836 { "query", 1, 0, 'A' },
4837 { "summary", 0, 0, 's' },
4838 { "diag", 1, 0, 'D' },
4839 { "filter", 1, 0, 'F' },
4840 { "version", 0, 0, 'V' },
4841 { "help", 0, 0, 'h' },
4842 { "context", 0, 0, 'Z' },
4843 { "contexts", 0, 0, 'z' },
4844 { "net", 1, 0, 'N' },
4845 { "tipcinfo", 0, 0, OPT_TIPCINFO
},
4846 { "tos", 0, 0, OPT_TOS
},
4847 { "kill", 0, 0, 'K' },
4848 { "no-header", 0, 0, 'H' },
4853 int main(int argc
, char *argv
[])
4858 const char *dump_tcpdiag
= NULL
;
4859 FILE *filter_fp
= NULL
;
4861 int state_filter
= 0;
4863 while ((ch
= getopt_long(argc
, argv
,
4864 "dhaletuwxnro460spbEf:miA:D:F:vVzZN:KHS",
4865 long_opts
, NULL
)) != EOF
) {
4868 resolve_services
= 0;
4888 user_ent_hash_build();
4898 filter_db_set(¤t_filter
, DCCP_DB
, true);
4901 filter_db_set(¤t_filter
, TCP_DB
, true);
4904 filter_db_set(¤t_filter
, SCTP_DB
, true);
4907 filter_db_set(¤t_filter
, UDP_DB
, true);
4910 filter_db_set(¤t_filter
, RAW_DB
, true);
4913 filter_af_set(¤t_filter
, AF_UNIX
);
4916 filter_af_set(¤t_filter
, AF_VSOCK
);
4919 filter_af_set(¤t_filter
, AF_TIPC
);
4922 state_filter
= SS_ALL
;
4925 state_filter
= (1 << SS_LISTEN
) | (1 << SS_CLOSE
);
4928 filter_af_set(¤t_filter
, AF_INET
);
4931 filter_af_set(¤t_filter
, AF_INET6
);
4934 filter_af_set(¤t_filter
, AF_PACKET
);
4937 if (strcmp(optarg
, "inet") == 0)
4938 filter_af_set(¤t_filter
, AF_INET
);
4939 else if (strcmp(optarg
, "inet6") == 0)
4940 filter_af_set(¤t_filter
, AF_INET6
);
4941 else if (strcmp(optarg
, "link") == 0)
4942 filter_af_set(¤t_filter
, AF_PACKET
);
4943 else if (strcmp(optarg
, "unix") == 0)
4944 filter_af_set(¤t_filter
, AF_UNIX
);
4945 else if (strcmp(optarg
, "netlink") == 0)
4946 filter_af_set(¤t_filter
, AF_NETLINK
);
4947 else if (strcmp(optarg
, "tipc") == 0)
4948 filter_af_set(¤t_filter
, AF_TIPC
);
4949 else if (strcmp(optarg
, "vsock") == 0)
4950 filter_af_set(¤t_filter
, AF_VSOCK
);
4951 else if (strcmp(optarg
, "help") == 0)
4954 fprintf(stderr
, "ss: \"%s\" is invalid family\n",
4964 current_filter
.dbs
= 0;
4965 state_filter
= state_filter
?
4966 state_filter
: SS_CONN
;
4972 if ((p1
= strchr(p
, ',')) != NULL
)
4974 if (filter_db_parse(¤t_filter
, p
)) {
4975 fprintf(stderr
, "ss: \"%s\" is illegal socket table id\n", p
);
4986 dump_tcpdiag
= optarg
;
4990 fprintf(stderr
, "More than one filter file\n");
4993 if (optarg
[0] == '-')
4996 filter_fp
= fopen(optarg
, "r");
4998 perror("fopen filter file");
5004 printf("ss utility, iproute2-ss%s\n", SNAPSHOT
);
5010 if (is_selinux_enabled() <= 0) {
5011 fprintf(stderr
, "ss: SELinux is not enabled.\n");
5015 user_ent_hash_build();
5018 if (netns_switch(optarg
))
5028 current_filter
.kill
= 1;
5046 if (do_default
&& argc
== 0)
5051 if (strcmp(*argv
, "state") == 0) {
5055 state_filter
|= scan_state(*argv
);
5057 } else if (strcmp(*argv
, "exclude") == 0 ||
5058 strcmp(*argv
, "excl") == 0) {
5061 state_filter
= SS_ALL
;
5062 state_filter
&= ~scan_state(*argv
);
5071 state_filter
= state_filter
? state_filter
: SS_CONN
;
5072 filter_db_parse(¤t_filter
, "all");
5075 filter_states_set(¤t_filter
, state_filter
);
5076 filter_merge_defaults(¤t_filter
);
5078 if (resolve_services
&& resolve_hosts
&&
5079 (current_filter
.dbs
& (UNIX_DBM
|INET_L4_DBM
)))
5080 init_service_resolver();
5082 if (current_filter
.dbs
== 0) {
5083 fprintf(stderr
, "ss: no socket tables to show with such filter.\n");
5086 if (current_filter
.families
== 0) {
5087 fprintf(stderr
, "ss: no families to show with such filter.\n");
5090 if (current_filter
.states
== 0) {
5091 fprintf(stderr
, "ss: no socket states to show with such filter.\n");
5096 FILE *dump_fp
= stdout
;
5098 if (!(current_filter
.dbs
& (1<<TCP_DB
))) {
5099 fprintf(stderr
, "ss: tcpdiag dump requested and no tcp in filter.\n");
5102 if (dump_tcpdiag
[0] != '-') {
5103 dump_fp
= fopen(dump_tcpdiag
, "w");
5104 if (!dump_tcpdiag
) {
5105 perror("fopen dump file");
5109 inet_show_netlink(¤t_filter
, dump_fp
, IPPROTO_TCP
);
5114 if (ssfilter_parse(¤t_filter
.f
, argc
, argv
, filter_fp
))
5117 if (!(current_filter
.dbs
& (current_filter
.dbs
- 1)))
5118 columns
[COL_NETID
].disabled
= 1;
5120 if (!(current_filter
.states
& (current_filter
.states
- 1)))
5121 columns
[COL_STATE
].disabled
= 1;
5129 exit(handle_follow_request(¤t_filter
));
5131 if (current_filter
.dbs
& (1<<NETLINK_DB
))
5132 netlink_show(¤t_filter
);
5133 if (current_filter
.dbs
& PACKET_DBM
)
5134 packet_show(¤t_filter
);
5135 if (current_filter
.dbs
& UNIX_DBM
)
5136 unix_show(¤t_filter
);
5137 if (current_filter
.dbs
& (1<<RAW_DB
))
5138 raw_show(¤t_filter
);
5139 if (current_filter
.dbs
& (1<<UDP_DB
))
5140 udp_show(¤t_filter
);
5141 if (current_filter
.dbs
& (1<<TCP_DB
))
5142 tcp_show(¤t_filter
);
5143 if (current_filter
.dbs
& (1<<DCCP_DB
))
5144 dccp_show(¤t_filter
);
5145 if (current_filter
.dbs
& (1<<SCTP_DB
))
5146 sctp_show(¤t_filter
);
5147 if (current_filter
.dbs
& VSOCK_DBM
)
5148 vsock_show(¤t_filter
);
5149 if (current_filter
.dbs
& (1<<TIPC_DB
))
5150 tipc_show(¤t_filter
);
5152 if (show_users
|| show_proc_ctx
|| show_sock_ctx
)