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 <netinet/in.h>
23 #include <arpa/inet.h>
34 #include "libnetlink.h"
35 #include "namespace.h"
38 #include <linux/tcp.h>
39 #include <linux/sock_diag.h>
40 #include <linux/inet_diag.h>
41 #include <linux/unix_diag.h>
42 #include <linux/netdevice.h> /* for MAX_ADDR_LEN */
43 #include <linux/filter.h>
44 #include <linux/packet_diag.h>
45 #include <linux/netlink_diag.h>
46 #include <linux/sctp.h>
47 #include <linux/vm_sockets_diag.h>
49 #define MAGIC_SEQ 123456
50 #define BUF_CHUNK (1024 * 1024)
51 #define LEN_ALIGN(x) (((x) + 1) & ~1)
53 #define DIAG_REQUEST(_req, _r) \
55 struct nlmsghdr nlh; \
59 .nlmsg_type = SOCK_DIAG_BY_FAMILY, \
60 .nlmsg_flags = NLM_F_ROOT|NLM_F_MATCH|NLM_F_REQUEST,\
61 .nlmsg_seq = MAGIC_SEQ, \
62 .nlmsg_len = sizeof(_req), \
67 #include <selinux/selinux.h>
69 /* Stubs for SELinux functions */
70 static int is_selinux_enabled(void)
75 static int getpidcon(pid_t pid
, char **context
)
81 static int getfilecon(char *path
, char **context
)
87 static int security_get_initial_context(char *name
, char **context
)
94 int resolve_services
= 1;
95 int preferred_family
= AF_UNSPEC
;
128 const enum col_align align
;
132 int width
; /* Calculated, including additional layout spacing */
133 int max_len
; /* Measured maximum field length in this column */
136 static struct column columns
[] = {
137 { ALIGN_LEFT
, "Netid", "", 0, 0, 0 },
138 { ALIGN_LEFT
, "State", " ", 0, 0, 0 },
139 { ALIGN_LEFT
, "Recv-Q", " ", 0, 0, 0 },
140 { ALIGN_LEFT
, "Send-Q", " ", 0, 0, 0 },
141 { ALIGN_RIGHT
, "Local Address:", " ", 0, 0, 0 },
142 { ALIGN_LEFT
, "Port", "", 0, 0, 0 },
143 { ALIGN_RIGHT
, "Peer Address:", " ", 0, 0, 0 },
144 { ALIGN_LEFT
, "Port", "", 0, 0, 0 },
145 { ALIGN_LEFT
, "", "", 0, 0, 0 },
148 static struct column
*current_field
= columns
;
150 /* Output buffer: chained chunks of BUF_CHUNK bytes. Each field is written to
151 * the buffer as a variable size token. A token consists of a 16 bits length
152 * field, followed by a string which is not NULL-terminated.
154 * A new chunk is allocated and linked when the current chunk doesn't have
155 * enough room to store the current token as a whole.
158 struct buf_chunk
*next
; /* Next chained chunk */
159 char *end
; /* Current end of content */
164 uint16_t len
; /* Data length, excluding length descriptor */
169 struct buf_token
*cur
; /* Position of current token in chunk */
170 struct buf_chunk
*head
; /* First chunk */
171 struct buf_chunk
*tail
; /* Current chunk */
174 static const char *TCP_PROTO
= "tcp";
175 static const char *SCTP_PROTO
= "sctp";
176 static const char *UDP_PROTO
= "udp";
177 static const char *RAW_PROTO
= "raw";
178 static const char *dg_proto
;
197 #define PACKET_DBM ((1<<PACKET_DG_DB)|(1<<PACKET_R_DB))
198 #define UNIX_DBM ((1<<UNIX_DG_DB)|(1<<UNIX_ST_DB)|(1<<UNIX_SQ_DB))
199 #define ALL_DB ((1<<MAX_DB)-1)
200 #define INET_L4_DBM ((1<<TCP_DB)|(1<<UDP_DB)|(1<<DCCP_DB)|(1<<SCTP_DB))
201 #define INET_DBM (INET_L4_DBM | (1<<RAW_DB))
202 #define VSOCK_DBM ((1<<VSOCK_ST_DB)|(1<<VSOCK_DG_DB))
221 SCTP_STATE_CLOSED
= 0,
222 SCTP_STATE_COOKIE_WAIT
= 1,
223 SCTP_STATE_COOKIE_ECHOED
= 2,
224 SCTP_STATE_ESTABLISHED
= 3,
225 SCTP_STATE_SHUTDOWN_PENDING
= 4,
226 SCTP_STATE_SHUTDOWN_SENT
= 5,
227 SCTP_STATE_SHUTDOWN_RECEIVED
= 6,
228 SCTP_STATE_SHUTDOWN_ACK_SENT
= 7,
231 #define SS_ALL ((1 << SS_MAX) - 1)
232 #define SS_CONN (SS_ALL & ~((1<<SS_LISTEN)|(1<<SS_CLOSE)|(1<<SS_TIME_WAIT)|(1<<SS_SYN_RECV)))
234 #include "ssfilter.h"
244 #define FAMILY_MASK(family) ((uint64_t)1 << (family))
246 static const struct filter default_dbs
[MAX_DB
] = {
249 .families
= FAMILY_MASK(AF_INET
) | FAMILY_MASK(AF_INET6
),
253 .families
= FAMILY_MASK(AF_INET
) | FAMILY_MASK(AF_INET6
),
256 .states
= (1 << SS_ESTABLISHED
),
257 .families
= FAMILY_MASK(AF_INET
) | FAMILY_MASK(AF_INET6
),
260 .states
= (1 << SS_ESTABLISHED
),
261 .families
= FAMILY_MASK(AF_INET
) | FAMILY_MASK(AF_INET6
),
264 .states
= (1 << SS_CLOSE
),
265 .families
= FAMILY_MASK(AF_UNIX
),
269 .families
= FAMILY_MASK(AF_UNIX
),
273 .families
= FAMILY_MASK(AF_UNIX
),
276 .states
= (1 << SS_CLOSE
),
277 .families
= FAMILY_MASK(AF_PACKET
),
280 .states
= (1 << SS_CLOSE
),
281 .families
= FAMILY_MASK(AF_PACKET
),
284 .states
= (1 << SS_CLOSE
),
285 .families
= FAMILY_MASK(AF_NETLINK
),
289 .families
= FAMILY_MASK(AF_INET
) | FAMILY_MASK(AF_INET6
),
293 .families
= FAMILY_MASK(AF_VSOCK
),
297 .families
= FAMILY_MASK(AF_VSOCK
),
301 static const struct filter default_afs
[AF_MAX
] = {
316 .states
= (1 << SS_CLOSE
),
319 .dbs
= (1 << NETLINK_DB
),
320 .states
= (1 << SS_CLOSE
),
328 static int do_default
= 1;
329 static struct filter current_filter
;
331 static void filter_db_set(struct filter
*f
, int db
)
333 f
->states
|= default_dbs
[db
].states
;
338 static void filter_af_set(struct filter
*f
, int af
)
340 f
->states
|= default_afs
[af
].states
;
341 f
->families
|= FAMILY_MASK(af
);
343 preferred_family
= af
;
346 static int filter_af_get(struct filter
*f
, int af
)
348 return !!(f
->families
& FAMILY_MASK(af
));
351 static void filter_default_dbs(struct filter
*f
)
353 filter_db_set(f
, UDP_DB
);
354 filter_db_set(f
, DCCP_DB
);
355 filter_db_set(f
, TCP_DB
);
356 filter_db_set(f
, RAW_DB
);
357 filter_db_set(f
, UNIX_ST_DB
);
358 filter_db_set(f
, UNIX_DG_DB
);
359 filter_db_set(f
, UNIX_SQ_DB
);
360 filter_db_set(f
, PACKET_R_DB
);
361 filter_db_set(f
, PACKET_DG_DB
);
362 filter_db_set(f
, NETLINK_DB
);
363 filter_db_set(f
, SCTP_DB
);
364 filter_db_set(f
, VSOCK_ST_DB
);
365 filter_db_set(f
, VSOCK_DG_DB
);
368 static void filter_states_set(struct filter
*f
, int states
)
374 static void filter_merge_defaults(struct filter
*f
)
379 for (db
= 0; db
< MAX_DB
; db
++) {
380 if (!(f
->dbs
& (1 << db
)))
383 if (!(default_dbs
[db
].families
& f
->families
))
384 f
->families
|= default_dbs
[db
].families
;
386 for (af
= 0; af
< AF_MAX
; af
++) {
387 if (!(f
->families
& FAMILY_MASK(af
)))
390 if (!(default_afs
[af
].dbs
& f
->dbs
))
391 f
->dbs
|= default_afs
[af
].dbs
;
395 static FILE *generic_proc_open(const char *env
, const char *name
)
397 const char *p
= getenv(env
);
401 p
= getenv("PROC_ROOT") ? : "/proc";
402 snprintf(store
, sizeof(store
)-1, "%s/%s", p
, name
);
406 return fopen(p
, "r");
408 #define net_tcp_open() generic_proc_open("PROC_NET_TCP", "net/tcp")
409 #define net_tcp6_open() generic_proc_open("PROC_NET_TCP6", "net/tcp6")
410 #define net_udp_open() generic_proc_open("PROC_NET_UDP", "net/udp")
411 #define net_udp6_open() generic_proc_open("PROC_NET_UDP6", "net/udp6")
412 #define net_raw_open() generic_proc_open("PROC_NET_RAW", "net/raw")
413 #define net_raw6_open() generic_proc_open("PROC_NET_RAW6", "net/raw6")
414 #define net_unix_open() generic_proc_open("PROC_NET_UNIX", "net/unix")
415 #define net_packet_open() generic_proc_open("PROC_NET_PACKET", \
417 #define net_netlink_open() generic_proc_open("PROC_NET_NETLINK", \
419 #define slabinfo_open() generic_proc_open("PROC_SLABINFO", "slabinfo")
420 #define net_sockstat_open() generic_proc_open("PROC_NET_SOCKSTAT", \
422 #define net_sockstat6_open() generic_proc_open("PROC_NET_SOCKSTAT6", \
424 #define net_snmp_open() generic_proc_open("PROC_NET_SNMP", "net/snmp")
425 #define ephemeral_ports_open() generic_proc_open("PROC_IP_LOCAL_PORT_RANGE", \
426 "sys/net/ipv4/ip_local_port_range")
429 struct user_ent
*next
;
438 #define USER_ENT_HASH_SIZE 256
439 struct user_ent
*user_ent_hash
[USER_ENT_HASH_SIZE
];
441 static int user_ent_hashfn(unsigned int ino
)
443 int val
= (ino
>> 24) ^ (ino
>> 16) ^ (ino
>> 8) ^ ino
;
445 return val
& (USER_ENT_HASH_SIZE
- 1);
448 static void user_ent_add(unsigned int ino
, char *process
,
453 struct user_ent
*p
, **pp
;
455 p
= malloc(sizeof(struct user_ent
));
457 fprintf(stderr
, "ss: failed to malloc buffer\n");
464 p
->process
= strdup(process
);
465 p
->process_ctx
= strdup(proc_ctx
);
466 p
->socket_ctx
= strdup(sock_ctx
);
468 pp
= &user_ent_hash
[user_ent_hashfn(ino
)];
473 static void user_ent_destroy(void)
475 struct user_ent
*p
, *p_next
;
478 while (cnt
!= USER_ENT_HASH_SIZE
) {
479 p
= user_ent_hash
[cnt
];
482 free(p
->process_ctx
);
492 static void user_ent_hash_build(void)
494 const char *root
= getenv("PROC_ROOT") ? : "/proc/";
501 const char *no_ctx
= "unavailable";
502 static int user_ent_hash_build_init
;
504 /* If show_users & show_proc_ctx set only do this once */
505 if (user_ent_hash_build_init
!= 0)
508 user_ent_hash_build_init
= 1;
510 strlcpy(name
, root
, sizeof(name
));
512 if (strlen(name
) == 0 || name
[strlen(name
)-1] != '/')
515 nameoff
= strlen(name
);
521 while ((d
= readdir(dir
)) != NULL
) {
529 if (sscanf(d
->d_name
, "%d%c", &pid
, &crap
) != 1)
532 if (getpidcon(pid
, &pid_context
) != 0)
533 pid_context
= strdup(no_ctx
);
535 snprintf(name
+ nameoff
, sizeof(name
) - nameoff
, "%d/fd/", pid
);
537 if ((dir1
= opendir(name
)) == NULL
) {
545 while ((d1
= readdir(dir1
)) != NULL
) {
546 const char *pattern
= "socket:[";
553 if (sscanf(d1
->d_name
, "%d%c", &fd
, &crap
) != 1)
556 snprintf(name
+pos
, sizeof(name
) - pos
, "%d", fd
);
558 link_len
= readlink(name
, lnk
, sizeof(lnk
)-1);
561 lnk
[link_len
] = '\0';
563 if (strncmp(lnk
, pattern
, strlen(pattern
)))
566 sscanf(lnk
, "socket:[%u]", &ino
);
568 snprintf(tmp
, sizeof(tmp
), "%s/%d/fd/%s",
569 root
, pid
, d1
->d_name
);
571 if (getfilecon(tmp
, &sock_context
) <= 0)
572 sock_context
= strdup(no_ctx
);
577 snprintf(tmp
, sizeof(tmp
), "%s/%d/stat",
579 if ((fp
= fopen(tmp
, "r")) != NULL
) {
580 if (fscanf(fp
, "%*d (%[^)])", p
) < 1)
585 user_ent_add(ino
, p
, pid
, fd
,
586 pid_context
, sock_context
);
601 #define ENTRY_BUF_SIZE 512
602 static int find_entry(unsigned int ino
, char **buf
, int type
)
608 int len
, new_buf_len
;
615 p
= user_ent_hash
[user_ent_hashfn(ino
)];
622 ptr
= *buf
+ buf_used
;
625 len
= snprintf(ptr
, buf_len
- buf_used
,
626 "(\"%s\",pid=%d,fd=%d),",
627 p
->process
, p
->pid
, p
->fd
);
630 len
= snprintf(ptr
, buf_len
- buf_used
,
631 "(\"%s\",pid=%d,proc_ctx=%s,fd=%d),",
633 p
->process_ctx
, p
->fd
);
636 len
= snprintf(ptr
, buf_len
- buf_used
,
637 "(\"%s\",pid=%d,proc_ctx=%s,fd=%d,sock_ctx=%s),",
639 p
->process_ctx
, p
->fd
,
643 fprintf(stderr
, "ss: invalid type: %d\n", type
);
647 if (len
< 0 || len
>= buf_len
- buf_used
) {
648 new_buf_len
= buf_len
+ ENTRY_BUF_SIZE
;
649 new_buf
= realloc(*buf
, new_buf_len
);
651 fprintf(stderr
, "ss: failed to malloc buffer\n");
655 buf_len
= new_buf_len
;
667 ptr
= *buf
+ buf_used
;
673 /* Get stats from slab */
683 static struct slabstat slabstat
;
685 static int get_slabstat(struct slabstat
*s
)
690 static int slabstat_valid
;
691 static const char * const slabstat_ids
[] = {
702 memset(s
, 0, sizeof(*s
));
704 fp
= slabinfo_open();
708 cnt
= sizeof(*s
)/sizeof(int);
710 if (!fgets(buf
, sizeof(buf
), fp
)) {
714 while (fgets(buf
, sizeof(buf
), fp
) != NULL
) {
717 for (i
= 0; i
< ARRAY_SIZE(slabstat_ids
); i
++) {
718 if (memcmp(buf
, slabstat_ids
[i
], strlen(slabstat_ids
[i
])) == 0) {
719 sscanf(buf
, "%*s%d", ((int *)s
) + i
);
734 static unsigned long long cookie_sk_get(const uint32_t *cookie
)
736 return (((unsigned long long)cookie
[1] << 31) << 1) | cookie
[0];
739 static const char *sctp_sstate_name
[] = {
740 [SCTP_STATE_CLOSED
] = "CLOSED",
741 [SCTP_STATE_COOKIE_WAIT
] = "COOKIE_WAIT",
742 [SCTP_STATE_COOKIE_ECHOED
] = "COOKIE_ECHOED",
743 [SCTP_STATE_ESTABLISHED
] = "ESTAB",
744 [SCTP_STATE_SHUTDOWN_PENDING
] = "SHUTDOWN_PENDING",
745 [SCTP_STATE_SHUTDOWN_SENT
] = "SHUTDOWN_SENT",
746 [SCTP_STATE_SHUTDOWN_RECEIVED
] = "SHUTDOWN_RECEIVED",
747 [SCTP_STATE_SHUTDOWN_ACK_SENT
] = "ACK_SENT",
751 struct sockstat
*next
;
765 unsigned long long sk
;
772 unsigned int ce_state
;
782 unsigned int timeout
;
785 double rto
, ato
, rtt
, rttvar
;
786 int qack
, ssthresh
, backoff
;
794 unsigned int lastsnd
;
795 unsigned int lastrcv
;
796 unsigned int lastack
;
798 double pacing_rate_max
;
799 double delivery_rate
;
800 unsigned long long bytes_acked
;
801 unsigned long long bytes_received
;
802 unsigned int segs_out
;
803 unsigned int segs_in
;
804 unsigned int data_segs_out
;
805 unsigned int data_segs_in
;
806 unsigned int unacked
;
807 unsigned int retrans
;
808 unsigned int retrans_total
;
811 unsigned int fackets
;
812 unsigned int reordering
;
813 unsigned int not_sent
;
817 unsigned int rcv_ssthresh
;
818 unsigned long long busy_time
;
819 unsigned long long rwnd_limited
;
820 unsigned long long sndbuf_limited
;
824 bool has_ecnseen_opt
;
825 bool has_fastopen_opt
;
828 struct dctcpstat
*dctcp
;
829 struct tcp_bbr_info
*bbr_info
;
832 /* SCTP assocs share the same inode number with their parent endpoint. So if we
833 * have seen the inode number before, it must be an assoc instead of the next
835 static bool is_sctp_assoc(struct sockstat
*s
, const char *sock_name
)
837 if (strcmp(sock_name
, "sctp"))
839 if (!sctp_ino
|| sctp_ino
!= s
->ino
)
844 static const char *unix_netid_name(int type
)
857 static const char *proto_name(int protocol
)
877 static const char *vsock_netid_name(int type
)
889 /* Allocate and initialize a new buffer chunk */
890 static struct buf_chunk
*buf_chunk_new(void)
892 struct buf_chunk
*new = malloc(BUF_CHUNK
);
899 /* This is also the last block */
902 /* Next token will be stored at the beginning of chunk data area, and
903 * its initial length is zero.
905 buffer
.cur
= (struct buf_token
*)new->data
;
908 new->end
= buffer
.cur
->data
;
913 /* Return available tail room in given chunk */
914 static int buf_chunk_avail(struct buf_chunk
*chunk
)
916 return BUF_CHUNK
- offsetof(struct buf_chunk
, data
) -
917 (chunk
->end
- chunk
->data
);
920 /* Update end pointer and token length, link new chunk if we hit the end of the
921 * current one. Return -EAGAIN if we got a new chunk, caller has to print again.
923 static int buf_update(int len
)
925 struct buf_chunk
*chunk
= buffer
.tail
;
926 struct buf_token
*t
= buffer
.cur
;
928 /* Claim success if new content fits in the current chunk, and anyway
929 * if this is the first token in the chunk: in the latter case,
930 * allocating a new chunk won't help, so we'll just cut the output.
932 if ((len
< buf_chunk_avail(chunk
) && len
!= -1 /* glibc < 2.0.6 */) ||
933 t
== (struct buf_token
*)chunk
->data
) {
934 len
= min(len
, buf_chunk_avail(chunk
));
936 /* Total field length can't exceed 2^16 bytes, cut as needed */
937 len
= min(len
, USHRT_MAX
- t
->len
);
944 /* Content truncated, time to allocate more */
945 chunk
->next
= buf_chunk_new();
947 /* Copy current token over to new chunk, including length descriptor */
948 memcpy(chunk
->next
->data
, t
, sizeof(t
->len
) + t
->len
);
949 chunk
->next
->end
+= t
->len
;
951 /* Discard partially written field in old chunk */
952 chunk
->end
-= t
->len
+ sizeof(t
->len
);
957 /* Append content to buffer as part of the current field */
958 static void out(const char *fmt
, ...)
960 struct column
*f
= current_field
;
969 buffer
.head
= buf_chunk_new();
971 again
: /* Append to buffer: if we have a new chunk, print again */
973 pos
= buffer
.cur
->data
+ buffer
.cur
->len
;
976 /* Limit to tail room. If we hit the limit, buf_update() will tell us */
977 len
= vsnprintf(pos
, buf_chunk_avail(buffer
.tail
), fmt
, args
);
984 static int print_left_spacing(struct column
*f
, int stored
, int printed
)
988 if (!f
->width
|| f
->align
== ALIGN_LEFT
)
991 s
= f
->width
- stored
- printed
;
992 if (f
->align
== ALIGN_CENTER
)
993 /* If count of total spacing is odd, shift right by one */
997 return printf("%*c", s
, ' ');
1002 static void print_right_spacing(struct column
*f
, int printed
)
1006 if (!f
->width
|| f
->align
== ALIGN_RIGHT
)
1009 s
= f
->width
- printed
;
1010 if (f
->align
== ALIGN_CENTER
)
1014 printf("%*c", s
, ' ');
1017 /* Done with field: update buffer pointer, start new token after current one */
1018 static void field_flush(struct column
*f
)
1020 struct buf_chunk
*chunk
= buffer
.tail
;
1021 unsigned int pad
= buffer
.cur
->len
% 2;
1026 if (buffer
.cur
->len
> f
->max_len
)
1027 f
->max_len
= buffer
.cur
->len
;
1029 /* We need a new chunk if we can't store the next length descriptor.
1030 * Mind the gap between end of previous token and next aligned position
1031 * for length descriptor.
1033 if (buf_chunk_avail(chunk
) - pad
< sizeof(buffer
.cur
->len
)) {
1035 chunk
->next
= buf_chunk_new();
1039 buffer
.cur
= (struct buf_token
*)(buffer
.cur
->data
+
1040 LEN_ALIGN(buffer
.cur
->len
));
1041 buffer
.cur
->len
= 0;
1042 buffer
.tail
->end
= buffer
.cur
->data
;
1045 static int field_is_last(struct column
*f
)
1047 return f
- columns
== COL_MAX
- 1;
1050 static void field_next(void)
1052 field_flush(current_field
);
1054 if (field_is_last(current_field
))
1055 current_field
= columns
;
1060 /* Walk through fields and flush them until we reach the desired one */
1061 static void field_set(enum col_id id
)
1063 while (id
!= current_field
- columns
)
1067 /* Print header for all non-empty columns */
1068 static void print_header(void)
1070 while (!field_is_last(current_field
)) {
1071 if (!current_field
->disabled
)
1072 out(current_field
->header
);
1077 /* Get the next available token in the buffer starting from the current token */
1078 static struct buf_token
*buf_token_next(struct buf_token
*cur
)
1080 struct buf_chunk
*chunk
= buffer
.tail
;
1082 /* If we reached the end of chunk contents, get token from next chunk */
1083 if (cur
->data
+ LEN_ALIGN(cur
->len
) == chunk
->end
) {
1084 buffer
.tail
= chunk
= chunk
->next
;
1085 return chunk
? (struct buf_token
*)chunk
->data
: NULL
;
1088 return (struct buf_token
*)(cur
->data
+ LEN_ALIGN(cur
->len
));
1091 /* Free up all allocated buffer chunks */
1092 static void buf_free_all(void)
1094 struct buf_chunk
*tmp
;
1096 for (buffer
.tail
= buffer
.head
; buffer
.tail
; ) {
1098 buffer
.tail
= buffer
.tail
->next
;
1104 /* Calculate column width from contents length. If columns don't fit on one
1105 * line, break them into the least possible amount of lines and keep them
1106 * aligned across lines. Available screen space is equally spread between fields
1107 * as additional spacing.
1109 static void render_calc_width(int screen_width
)
1111 int first
, len
= 0, linecols
= 0;
1112 struct column
*c
, *eol
= columns
- 1;
1114 /* First pass: set width for each column to measured content length */
1115 for (first
= 1, c
= columns
; c
- columns
< COL_MAX
; c
++) {
1119 if (!first
&& c
->max_len
)
1120 c
->width
= c
->max_len
+ strlen(c
->ldelim
);
1122 c
->width
= c
->max_len
;
1124 /* But don't exceed screen size. If we exceed the screen size
1125 * for even a single field, it will just start on a line of its
1126 * own and then naturally wrap.
1128 c
->width
= min(c
->width
, screen_width
);
1134 /* Second pass: find out newlines and distribute available spacing */
1135 for (c
= columns
; c
- columns
< COL_MAX
; c
++) {
1136 int pad
, spacing
, rem
, last
;
1145 for (last
= 1, tmp
= c
+ 1; tmp
- columns
< COL_MAX
; tmp
++) {
1152 if (!last
&& len
< screen_width
) {
1153 /* Columns fit on screen so far, nothing to do yet */
1157 if (len
== screen_width
) {
1158 /* Exact fit, just start with new line */
1162 if (len
> screen_width
) {
1163 /* Screen width exceeded: go back one column */
1169 /* Distribute remaining space to columns on this line */
1170 pad
= screen_width
- len
;
1171 spacing
= pad
/ linecols
;
1172 rem
= pad
% linecols
;
1173 for (tmp
= c
; tmp
> eol
; tmp
--) {
1177 tmp
->width
+= spacing
;
1185 /* Line break: reset line counters, mark end-of-line */
1192 /* Render buffered output with spacing and delimiters, then free up buffers */
1193 static void render(int screen_width
)
1195 struct buf_token
*token
= (struct buf_token
*)buffer
.head
->data
;
1196 int printed
, line_started
= 0;
1199 /* Ensure end alignment of last token, it wasn't necessarily flushed */
1200 buffer
.tail
->end
+= buffer
.cur
->len
% 2;
1202 render_calc_width(screen_width
);
1204 /* Rewind and replay */
1205 buffer
.tail
= buffer
.head
;
1212 /* Print left delimiter only if we already started a line */
1214 printed
= printf("%s", current_field
->ldelim
);
1218 /* Print field content from token data with spacing */
1219 printed
+= print_left_spacing(f
, token
->len
, printed
);
1220 printed
+= fwrite(token
->data
, 1, token
->len
, stdout
);
1221 print_right_spacing(f
, printed
);
1223 /* Go to next non-empty field, deal with end-of-line */
1225 if (field_is_last(f
)) {
1232 } while (f
->disabled
);
1234 token
= buf_token_next(token
);
1240 static void sock_state_print(struct sockstat
*s
)
1242 const char *sock_name
;
1243 static const char * const sstate_name
[] = {
1245 [SS_ESTABLISHED
] = "ESTAB",
1246 [SS_SYN_SENT
] = "SYN-SENT",
1247 [SS_SYN_RECV
] = "SYN-RECV",
1248 [SS_FIN_WAIT1
] = "FIN-WAIT-1",
1249 [SS_FIN_WAIT2
] = "FIN-WAIT-2",
1250 [SS_TIME_WAIT
] = "TIME-WAIT",
1251 [SS_CLOSE
] = "UNCONN",
1252 [SS_CLOSE_WAIT
] = "CLOSE-WAIT",
1253 [SS_LAST_ACK
] = "LAST-ACK",
1254 [SS_LISTEN
] = "LISTEN",
1255 [SS_CLOSING
] = "CLOSING",
1258 switch (s
->local
.family
) {
1260 sock_name
= unix_netid_name(s
->type
);
1264 sock_name
= proto_name(s
->type
);
1267 sock_name
= s
->type
== SOCK_RAW
? "p_raw" : "p_dgr";
1273 sock_name
= vsock_netid_name(s
->type
);
1276 sock_name
= "unknown";
1279 if (is_sctp_assoc(s
, sock_name
)) {
1280 field_set(COL_STATE
); /* Empty Netid field */
1281 out("`- %s", sctp_sstate_name
[s
->state
]);
1283 field_set(COL_NETID
);
1284 out("%s", sock_name
);
1285 field_set(COL_STATE
);
1286 out("%s", sstate_name
[s
->state
]);
1289 field_set(COL_RECVQ
);
1291 field_set(COL_SENDQ
);
1293 field_set(COL_ADDR
);
1296 static void sock_details_print(struct sockstat
*s
)
1299 out(" uid:%u", s
->uid
);
1301 out(" ino:%u", s
->ino
);
1302 out(" sk:%llx", s
->sk
);
1305 out(" fwmark:0x%x", s
->mark
);
1308 static void sock_addr_print(const char *addr
, char *delim
, const char *port
,
1312 out("%s" "%%" "%s%s", addr
, ifname
, delim
);
1314 out("%s%s", addr
, delim
);
1321 static const char *print_ms_timer(unsigned int timeout
)
1323 static char buf
[64];
1324 int secs
, msecs
, minutes
;
1326 secs
= timeout
/1000;
1329 msecs
= timeout
%1000;
1333 snprintf(buf
, sizeof(buf
)-16, "%dmin", minutes
);
1340 sprintf(buf
+strlen(buf
), "%d%s", secs
, msecs
? "." : "sec");
1343 sprintf(buf
+strlen(buf
), "%03dms", msecs
);
1348 struct scache
*next
;
1354 struct scache
*rlist
;
1356 static void init_service_resolver(void)
1359 FILE *fp
= popen("/usr/sbin/rpcinfo -p 2>/dev/null", "r");
1364 if (!fgets(buf
, sizeof(buf
), fp
)) {
1368 while (fgets(buf
, sizeof(buf
), fp
) != NULL
) {
1369 unsigned int progn
, port
;
1370 char proto
[128], prog
[128] = "rpc.";
1373 if (sscanf(buf
, "%u %*d %s %u %s",
1374 &progn
, proto
, &port
, prog
+4) != 4)
1377 if (!(c
= malloc(sizeof(*c
))))
1381 c
->name
= strdup(prog
);
1382 if (strcmp(proto
, TCP_PROTO
) == 0)
1383 c
->proto
= TCP_PROTO
;
1384 else if (strcmp(proto
, UDP_PROTO
) == 0)
1385 c
->proto
= UDP_PROTO
;
1386 else if (strcmp(proto
, SCTP_PROTO
) == 0)
1387 c
->proto
= SCTP_PROTO
;
1396 /* Even do not try default linux ephemeral port ranges:
1397 * default /etc/services contains so much of useless crap
1398 * wouldbe "allocated" to this area that resolution
1399 * is really harmful. I shrug each time when seeing
1400 * "socks" or "cfinger" in dumps.
1402 static int is_ephemeral(int port
)
1404 static int min
= 0, max
;
1407 FILE *f
= ephemeral_ports_open();
1409 if (!f
|| fscanf(f
, "%d %d", &min
, &max
) < 2) {
1416 return port
>= min
&& port
<= max
;
1420 static const char *__resolve_service(int port
)
1424 for (c
= rlist
; c
; c
= c
->next
) {
1425 if (c
->port
== port
&& c
->proto
== dg_proto
)
1429 if (!is_ephemeral(port
)) {
1430 static int notfirst
;
1437 se
= getservbyport(htons(port
), dg_proto
);
1445 #define SCACHE_BUCKETS 1024
1446 static struct scache
*cache_htab
[SCACHE_BUCKETS
];
1448 static const char *resolve_service(int port
)
1450 static char buf
[128];
1461 if (!resolve_services
)
1464 if (dg_proto
== RAW_PROTO
)
1465 return inet_proto_n2a(port
, buf
, sizeof(buf
));
1468 hash
= (port
^(((unsigned long)dg_proto
)>>2)) % SCACHE_BUCKETS
;
1470 for (c
= cache_htab
[hash
]; c
; c
= c
->next
) {
1471 if (c
->port
== port
&& c
->proto
== dg_proto
)
1475 c
= malloc(sizeof(*c
));
1478 res
= __resolve_service(port
);
1480 c
->name
= res
? strdup(res
) : NULL
;
1481 c
->proto
= dg_proto
;
1482 c
->next
= cache_htab
[hash
];
1483 cache_htab
[hash
] = c
;
1490 sprintf(buf
, "%u", port
);
1494 static void inet_addr_print(const inet_prefix
*a
, int port
,
1495 unsigned int ifindex
, bool v6only
)
1498 const char *ap
= buf
;
1499 const char *ifname
= NULL
;
1501 if (a
->family
== AF_INET
) {
1502 ap
= format_host(AF_INET
, 4, a
->data
);
1505 !memcmp(a
->data
, &in6addr_any
, sizeof(in6addr_any
))) {
1509 ap
= format_host(a
->family
, 16, a
->data
);
1511 /* Numeric IPv6 addresses should be bracketed */
1512 if (strchr(ap
, ':')) {
1513 snprintf(buf
, sizeof(buf
),
1521 ifname
= ll_index_to_name(ifindex
);
1523 sock_addr_print(ap
, ":", resolve_service(port
), ifname
);
1532 struct aafilter
*next
;
1535 static int inet2_addr_match(const inet_prefix
*a
, const inet_prefix
*p
,
1538 if (!inet_addr_match(a
, p
, plen
))
1541 /* Cursed "v4 mapped" addresses: v4 mapped socket matches
1542 * pure IPv4 rule, but v4-mapped rule selects only v4-mapped
1544 if (p
->family
== AF_INET
&& a
->family
== AF_INET6
) {
1545 if (a
->data
[0] == 0 && a
->data
[1] == 0 &&
1546 a
->data
[2] == htonl(0xffff)) {
1547 inet_prefix tmp
= *a
;
1549 tmp
.data
[0] = a
->data
[3];
1550 return inet_addr_match(&tmp
, p
, plen
);
1556 static int unix_match(const inet_prefix
*a
, const inet_prefix
*p
)
1558 char *addr
, *pattern
;
1560 memcpy(&addr
, a
->data
, sizeof(addr
));
1561 memcpy(&pattern
, p
->data
, sizeof(pattern
));
1562 if (pattern
== NULL
)
1566 return !fnmatch(pattern
, addr
, 0);
1569 static int run_ssfilter(struct ssfilter
*f
, struct sockstat
*s
)
1574 if (s
->local
.family
== AF_UNIX
) {
1577 memcpy(&p
, s
->local
.data
, sizeof(p
));
1578 return p
== NULL
|| (p
[0] == '@' && strlen(p
) == 6 &&
1579 strspn(p
+1, "0123456789abcdef") == 5);
1581 if (s
->local
.family
== AF_PACKET
)
1582 return s
->lport
== 0 && s
->local
.data
[0] == 0;
1583 if (s
->local
.family
== AF_NETLINK
)
1584 return s
->lport
< 0;
1585 if (s
->local
.family
== AF_VSOCK
)
1586 return s
->lport
> 1023;
1588 return is_ephemeral(s
->lport
);
1592 struct aafilter
*a
= (void *)f
->pred
;
1594 if (a
->addr
.family
== AF_UNIX
)
1595 return unix_match(&s
->remote
, &a
->addr
);
1596 if (a
->port
!= -1 && a
->port
!= s
->rport
)
1598 if (a
->addr
.bitlen
) {
1600 if (!inet2_addr_match(&s
->remote
, &a
->addr
, a
->addr
.bitlen
))
1602 } while ((a
= a
->next
) != NULL
);
1609 struct aafilter
*a
= (void *)f
->pred
;
1611 if (a
->addr
.family
== AF_UNIX
)
1612 return unix_match(&s
->local
, &a
->addr
);
1613 if (a
->port
!= -1 && a
->port
!= s
->lport
)
1615 if (a
->addr
.bitlen
) {
1617 if (!inet2_addr_match(&s
->local
, &a
->addr
, a
->addr
.bitlen
))
1619 } while ((a
= a
->next
) != NULL
);
1626 struct aafilter
*a
= (void *)f
->pred
;
1628 return s
->rport
>= a
->port
;
1632 struct aafilter
*a
= (void *)f
->pred
;
1634 return s
->rport
<= a
->port
;
1638 struct aafilter
*a
= (void *)f
->pred
;
1640 return s
->lport
>= a
->port
;
1644 struct aafilter
*a
= (void *)f
->pred
;
1646 return s
->lport
<= a
->port
;
1650 struct aafilter
*a
= (void *)f
->pred
;
1652 return s
->iface
== a
->iface
;
1656 struct aafilter
*a
= (void *)f
->pred
;
1658 return (s
->mark
& a
->mask
) == a
->mark
;
1660 /* Yup. It is recursion. Sorry. */
1662 return run_ssfilter(f
->pred
, s
) && run_ssfilter(f
->post
, s
);
1664 return run_ssfilter(f
->pred
, s
) || run_ssfilter(f
->post
, s
);
1666 return !run_ssfilter(f
->pred
, s
);
1672 /* Relocate external jumps by reloc. */
1673 static void ssfilter_patch(char *a
, int len
, int reloc
)
1676 struct inet_diag_bc_op
*op
= (struct inet_diag_bc_op
*)a
;
1678 if (op
->no
== len
+4)
1687 static int ssfilter_bytecompile(struct ssfilter
*f
, char **bytecode
)
1692 if (!(*bytecode
= malloc(4))) abort();
1693 ((struct inet_diag_bc_op
*)*bytecode
)[0] = (struct inet_diag_bc_op
){ INET_DIAG_BC_AUTO
, 4, 8 };
1699 struct aafilter
*a
= (void *)f
->pred
;
1702 int code
= (f
->type
== SSF_DCOND
? INET_DIAG_BC_D_COND
: INET_DIAG_BC_S_COND
);
1705 for (b
= a
; b
; b
= b
->next
) {
1706 len
+= 4 + sizeof(struct inet_diag_hostcond
);
1707 if (a
->addr
.family
== AF_INET6
)
1714 if (!(ptr
= malloc(len
))) abort();
1716 for (b
= a
; b
; b
= b
->next
) {
1717 struct inet_diag_bc_op
*op
= (struct inet_diag_bc_op
*)ptr
;
1718 int alen
= (a
->addr
.family
== AF_INET6
? 16 : 4);
1719 int oplen
= alen
+ 4 + sizeof(struct inet_diag_hostcond
);
1720 struct inet_diag_hostcond
*cond
= (struct inet_diag_hostcond
*)(ptr
+4);
1722 *op
= (struct inet_diag_bc_op
){ code
, oplen
, oplen
+4 };
1723 cond
->family
= a
->addr
.family
;
1724 cond
->port
= a
->port
;
1725 cond
->prefix_len
= a
->addr
.bitlen
;
1726 memcpy(cond
->addr
, a
->addr
.data
, alen
);
1729 op
= (struct inet_diag_bc_op
*)ptr
;
1730 *op
= (struct inet_diag_bc_op
){ INET_DIAG_BC_JMP
, 4, len
- (ptr
-*bytecode
)};
1734 return ptr
- *bytecode
;
1738 struct aafilter
*x
= (void *)f
->pred
;
1740 if (!(*bytecode
= malloc(8))) abort();
1741 ((struct inet_diag_bc_op
*)*bytecode
)[0] = (struct inet_diag_bc_op
){ INET_DIAG_BC_D_GE
, 8, 12 };
1742 ((struct inet_diag_bc_op
*)*bytecode
)[1] = (struct inet_diag_bc_op
){ 0, 0, x
->port
};
1747 struct aafilter
*x
= (void *)f
->pred
;
1749 if (!(*bytecode
= malloc(8))) abort();
1750 ((struct inet_diag_bc_op
*)*bytecode
)[0] = (struct inet_diag_bc_op
){ INET_DIAG_BC_D_LE
, 8, 12 };
1751 ((struct inet_diag_bc_op
*)*bytecode
)[1] = (struct inet_diag_bc_op
){ 0, 0, x
->port
};
1756 struct aafilter
*x
= (void *)f
->pred
;
1758 if (!(*bytecode
= malloc(8))) abort();
1759 ((struct inet_diag_bc_op
*)*bytecode
)[0] = (struct inet_diag_bc_op
){ INET_DIAG_BC_S_GE
, 8, 12 };
1760 ((struct inet_diag_bc_op
*)*bytecode
)[1] = (struct inet_diag_bc_op
){ 0, 0, x
->port
};
1765 struct aafilter
*x
= (void *)f
->pred
;
1767 if (!(*bytecode
= malloc(8))) abort();
1768 ((struct inet_diag_bc_op
*)*bytecode
)[0] = (struct inet_diag_bc_op
){ INET_DIAG_BC_S_LE
, 8, 12 };
1769 ((struct inet_diag_bc_op
*)*bytecode
)[1] = (struct inet_diag_bc_op
){ 0, 0, x
->port
};
1775 char *a1
= NULL
, *a2
= NULL
, *a
;
1778 l1
= ssfilter_bytecompile(f
->pred
, &a1
);
1779 l2
= ssfilter_bytecompile(f
->post
, &a2
);
1785 if (!(a
= malloc(l1
+l2
))) abort();
1787 memcpy(a
+l1
, a2
, l2
);
1789 ssfilter_patch(a
, l1
, l2
);
1795 char *a1
= NULL
, *a2
= NULL
, *a
;
1798 l1
= ssfilter_bytecompile(f
->pred
, &a1
);
1799 l2
= ssfilter_bytecompile(f
->post
, &a2
);
1805 if (!(a
= malloc(l1
+l2
+4))) abort();
1807 memcpy(a
+l1
+4, a2
, l2
);
1809 *(struct inet_diag_bc_op
*)(a
+l1
) = (struct inet_diag_bc_op
){ INET_DIAG_BC_JMP
, 4, l2
+4 };
1815 char *a1
= NULL
, *a
;
1818 l1
= ssfilter_bytecompile(f
->pred
, &a1
);
1823 if (!(a
= malloc(l1
+4))) abort();
1826 *(struct inet_diag_bc_op
*)(a
+l1
) = (struct inet_diag_bc_op
){ INET_DIAG_BC_JMP
, 4, 8 };
1832 /* bytecompile for SSF_DEVCOND not supported yet */
1837 struct aafilter
*a
= (void *)f
->pred
;
1839 struct inet_diag_bc_op op
;
1840 struct inet_diag_markcond cond
;
1842 int inslen
= sizeof(struct instr
);
1844 if (!(*bytecode
= malloc(inslen
))) abort();
1845 ((struct instr
*)*bytecode
)[0] = (struct instr
) {
1846 { INET_DIAG_BC_MARK_COND
, inslen
, inslen
+ 4 },
1847 { a
->mark
, a
->mask
},
1857 static int remember_he(struct aafilter
*a
, struct hostent
*he
)
1859 char **ptr
= he
->h_addr_list
;
1863 if (he
->h_addrtype
== AF_INET
)
1865 else if (he
->h_addrtype
== AF_INET6
)
1871 struct aafilter
*b
= a
;
1873 if (a
->addr
.bitlen
) {
1874 if ((b
= malloc(sizeof(*b
))) == NULL
)
1879 memcpy(b
->addr
.data
, *ptr
, len
);
1880 b
->addr
.bytelen
= len
;
1881 b
->addr
.bitlen
= len
*8;
1882 b
->addr
.family
= he
->h_addrtype
;
1889 static int get_dns_host(struct aafilter
*a
, const char *addr
, int fam
)
1891 static int notfirst
;
1900 he
= gethostbyname2(addr
, fam
== AF_UNSPEC
? AF_INET
: fam
);
1902 cnt
= remember_he(a
, he
);
1903 if (fam
== AF_UNSPEC
) {
1904 he
= gethostbyname2(addr
, AF_INET6
);
1906 cnt
+= remember_he(a
, he
);
1911 static int xll_initted
;
1913 static void xll_init(void)
1915 struct rtnl_handle rth
;
1917 if (rtnl_open(&rth
, 0) < 0)
1925 static const char *xll_index_to_name(int index
)
1929 return ll_index_to_name(index
);
1932 static int xll_name_to_index(const char *dev
)
1936 return ll_name_to_index(dev
);
1939 void *parse_devcond(char *name
)
1941 struct aafilter a
= { .iface
= 0 };
1942 struct aafilter
*res
;
1944 a
.iface
= xll_name_to_index(name
);
1949 n
= strtoul(name
, &end
, 0);
1950 if (!end
|| end
== name
|| *end
|| n
> UINT_MAX
)
1956 res
= malloc(sizeof(*res
));
1962 static void vsock_set_inet_prefix(inet_prefix
*a
, __u32 cid
)
1965 .bytelen
= sizeof(cid
),
1968 memcpy(a
->data
, &cid
, sizeof(cid
));
1971 void *parse_hostcond(char *addr
, bool is_port
)
1974 struct aafilter a
= { .port
= -1 };
1975 struct aafilter
*res
;
1976 int fam
= preferred_family
;
1977 struct filter
*f
= ¤t_filter
;
1979 if (fam
== AF_UNIX
|| strncmp(addr
, "unix:", 5) == 0) {
1982 a
.addr
.family
= AF_UNIX
;
1983 if (strncmp(addr
, "unix:", 5) == 0)
1986 a
.addr
.bitlen
= 8*strlen(p
);
1987 memcpy(a
.addr
.data
, &p
, sizeof(p
));
1992 if (fam
== AF_PACKET
|| strncmp(addr
, "link:", 5) == 0) {
1993 a
.addr
.family
= AF_PACKET
;
1995 if (strncmp(addr
, "link:", 5) == 0)
1997 port
= strchr(addr
, ':');
2000 if (port
[1] && strcmp(port
+1, "*")) {
2001 if (get_integer(&a
.port
, port
+1, 0)) {
2002 if ((a
.port
= xll_name_to_index(port
+1)) <= 0)
2007 if (addr
[0] && strcmp(addr
, "*")) {
2011 if (ll_proto_a2n(&tmp
, addr
))
2013 a
.addr
.data
[0] = ntohs(tmp
);
2019 if (fam
== AF_NETLINK
|| strncmp(addr
, "netlink:", 8) == 0) {
2020 a
.addr
.family
= AF_NETLINK
;
2022 if (strncmp(addr
, "netlink:", 8) == 0)
2024 port
= strchr(addr
, ':');
2027 if (port
[1] && strcmp(port
+1, "*")) {
2028 if (get_integer(&a
.port
, port
+1, 0)) {
2029 if (strcmp(port
+1, "kernel") == 0)
2036 if (addr
[0] && strcmp(addr
, "*")) {
2038 if (nl_proto_a2n(&a
.addr
.data
[0], addr
) == -1)
2045 if (fam
== AF_VSOCK
|| strncmp(addr
, "vsock:", 6) == 0) {
2046 __u32 cid
= ~(__u32
)0;
2048 a
.addr
.family
= AF_VSOCK
;
2049 if (strncmp(addr
, "vsock:", 6) == 0)
2055 port
= strchr(addr
, ':');
2062 if (port
&& strcmp(port
, "*") &&
2063 get_u32((__u32
*)&a
.port
, port
, 0))
2066 if (addr
[0] && strcmp(addr
, "*")) {
2068 if (get_u32(&cid
, addr
, 0))
2071 vsock_set_inet_prefix(&a
.addr
, cid
);
2076 if (fam
== AF_INET
|| !strncmp(addr
, "inet:", 5)) {
2078 if (!strncmp(addr
, "inet:", 5))
2080 } else if (fam
== AF_INET6
|| !strncmp(addr
, "inet6:", 6)) {
2082 if (!strncmp(addr
, "inet6:", 6))
2086 /* URL-like literal [] */
2087 if (addr
[0] == '[') {
2089 if ((port
= strchr(addr
, ']')) == NULL
)
2092 } else if (addr
[0] == '*') {
2095 port
= strrchr(strchr(addr
, '/') ? : addr
, ':');
2101 if (port
&& *port
) {
2105 if (*port
&& *port
!= '*') {
2106 if (get_integer(&a
.port
, port
, 0)) {
2107 struct servent
*se1
= NULL
;
2108 struct servent
*se2
= NULL
;
2110 if (current_filter
.dbs
&(1<<UDP_DB
))
2111 se1
= getservbyname(port
, UDP_PROTO
);
2112 if (current_filter
.dbs
&(1<<TCP_DB
))
2113 se2
= getservbyname(port
, TCP_PROTO
);
2114 if (se1
&& se2
&& se1
->s_port
!= se2
->s_port
) {
2115 fprintf(stderr
, "Error: ambiguous port \"%s\".\n", port
);
2121 a
.port
= ntohs(se1
->s_port
);
2125 for (s
= rlist
; s
; s
= s
->next
) {
2126 if ((s
->proto
== UDP_PROTO
&&
2127 (current_filter
.dbs
&(1<<UDP_DB
))) ||
2128 (s
->proto
== TCP_PROTO
&&
2129 (current_filter
.dbs
&(1<<TCP_DB
)))) {
2130 if (s
->name
&& strcmp(s
->name
, port
) == 0) {
2131 if (a
.port
> 0 && a
.port
!= s
->port
) {
2132 fprintf(stderr
, "Error: ambiguous port \"%s\".\n", port
);
2140 fprintf(stderr
, "Error: \"%s\" does not look like a port.\n", port
);
2147 if (!is_port
&& *addr
&& *addr
!= '*') {
2148 if (get_prefix_1(&a
.addr
, addr
, fam
)) {
2149 if (get_dns_host(&a
, addr
, fam
)) {
2150 fprintf(stderr
, "Error: an inet prefix is expected rather than \"%s\".\n", addr
);
2157 if (fam
!= AF_UNSPEC
) {
2158 int states
= f
->states
;
2160 filter_af_set(f
, fam
);
2161 filter_states_set(f
, states
);
2164 res
= malloc(sizeof(*res
));
2166 memcpy(res
, &a
, sizeof(a
));
2170 void *parse_markmask(const char *markmask
)
2172 struct aafilter a
, *res
;
2174 if (strchr(markmask
, '/')) {
2175 if (sscanf(markmask
, "%i/%i", &a
.mark
, &a
.mask
) != 2)
2178 a
.mask
= 0xffffffff;
2179 if (sscanf(markmask
, "%i", &a
.mark
) != 1)
2183 res
= malloc(sizeof(*res
));
2185 memcpy(res
, &a
, sizeof(a
));
2189 static void proc_ctx_print(struct sockstat
*s
)
2193 if (show_proc_ctx
|| show_sock_ctx
) {
2194 if (find_entry(s
->ino
, &buf
,
2195 (show_proc_ctx
& show_sock_ctx
) ?
2196 PROC_SOCK_CTX
: PROC_CTX
) > 0) {
2197 out(" users:(%s)", buf
);
2200 } else if (show_users
) {
2201 if (find_entry(s
->ino
, &buf
, USERS
) > 0) {
2202 out(" users:(%s)", buf
);
2208 static void inet_stats_print(struct sockstat
*s
, bool v6only
)
2210 sock_state_print(s
);
2212 inet_addr_print(&s
->local
, s
->lport
, s
->iface
, v6only
);
2213 inet_addr_print(&s
->remote
, s
->rport
, 0, v6only
);
2218 static int proc_parse_inet_addr(char *loc
, char *rem
, int family
, struct
2221 s
->local
.family
= s
->remote
.family
= family
;
2222 if (family
== AF_INET
) {
2223 sscanf(loc
, "%x:%x", s
->local
.data
, (unsigned *)&s
->lport
);
2224 sscanf(rem
, "%x:%x", s
->remote
.data
, (unsigned *)&s
->rport
);
2225 s
->local
.bytelen
= s
->remote
.bytelen
= 4;
2228 sscanf(loc
, "%08x%08x%08x%08x:%x",
2234 sscanf(rem
, "%08x%08x%08x%08x:%x",
2240 s
->local
.bytelen
= s
->remote
.bytelen
= 16;
2246 static int proc_inet_split_line(char *line
, char **loc
, char **rem
, char **data
)
2250 if ((p
= strchr(line
, ':')) == NULL
)
2254 if ((p
= strchr(*loc
, ':')) == NULL
)
2259 if ((p
= strchr(*rem
, ':')) == NULL
)
2267 static char *sprint_bw(char *buf
, double bw
)
2270 sprintf(buf
, "%.1fM", bw
/ 1000000.);
2271 else if (bw
> 1000.)
2272 sprintf(buf
, "%.1fK", bw
/ 1000.);
2274 sprintf(buf
, "%g", bw
);
2279 static void sctp_stats_print(struct sctp_info
*s
)
2282 out(" tag:%x", s
->sctpi_tag
);
2284 out(" state:%s", sctp_sstate_name
[s
->sctpi_state
]);
2286 out(" rwnd:%d", s
->sctpi_rwnd
);
2287 if (s
->sctpi_unackdata
)
2288 out(" unackdata:%d", s
->sctpi_unackdata
);
2289 if (s
->sctpi_penddata
)
2290 out(" penddata:%d", s
->sctpi_penddata
);
2291 if (s
->sctpi_instrms
)
2292 out(" instrms:%d", s
->sctpi_instrms
);
2293 if (s
->sctpi_outstrms
)
2294 out(" outstrms:%d", s
->sctpi_outstrms
);
2295 if (s
->sctpi_inqueue
)
2296 out(" inqueue:%d", s
->sctpi_inqueue
);
2297 if (s
->sctpi_outqueue
)
2298 out(" outqueue:%d", s
->sctpi_outqueue
);
2299 if (s
->sctpi_overall_error
)
2300 out(" overerr:%d", s
->sctpi_overall_error
);
2301 if (s
->sctpi_max_burst
)
2302 out(" maxburst:%d", s
->sctpi_max_burst
);
2303 if (s
->sctpi_maxseg
)
2304 out(" maxseg:%d", s
->sctpi_maxseg
);
2305 if (s
->sctpi_peer_rwnd
)
2306 out(" prwnd:%d", s
->sctpi_peer_rwnd
);
2307 if (s
->sctpi_peer_tag
)
2308 out(" ptag:%x", s
->sctpi_peer_tag
);
2309 if (s
->sctpi_peer_capable
)
2310 out(" pcapable:%d", s
->sctpi_peer_capable
);
2311 if (s
->sctpi_peer_sack
)
2312 out(" psack:%d", s
->sctpi_peer_sack
);
2313 if (s
->sctpi_s_autoclose
)
2314 out(" autoclose:%d", s
->sctpi_s_autoclose
);
2315 if (s
->sctpi_s_adaptation_ind
)
2316 out(" adapind:%d", s
->sctpi_s_adaptation_ind
);
2317 if (s
->sctpi_s_pd_point
)
2318 out(" pdpoint:%d", s
->sctpi_s_pd_point
);
2319 if (s
->sctpi_s_nodelay
)
2320 out(" nodealy:%d", s
->sctpi_s_nodelay
);
2321 if (s
->sctpi_s_disable_fragments
)
2322 out(" nofrag:%d", s
->sctpi_s_disable_fragments
);
2323 if (s
->sctpi_s_v4mapped
)
2324 out(" v4mapped:%d", s
->sctpi_s_v4mapped
);
2325 if (s
->sctpi_s_frag_interleave
)
2326 out(" fraginl:%d", s
->sctpi_s_frag_interleave
);
2329 static void tcp_stats_print(struct tcpstat
*s
)
2335 if (s
->has_sack_opt
)
2339 if (s
->has_ecnseen_opt
)
2341 if (s
->has_fastopen_opt
)
2344 out(" %s", s
->cong_alg
);
2345 if (s
->has_wscale_opt
)
2346 out(" wscale:%d,%d", s
->snd_wscale
, s
->rcv_wscale
);
2348 out(" rto:%g", s
->rto
);
2350 out(" backoff:%u", s
->backoff
);
2352 out(" rtt:%g/%g", s
->rtt
, s
->rttvar
);
2354 out(" ato:%g", s
->ato
);
2357 out(" qack:%d", s
->qack
);
2362 out(" mss:%d", s
->mss
);
2364 out(" rcvmss:%d", s
->rcv_mss
);
2366 out(" advmss:%d", s
->advmss
);
2368 out(" cwnd:%u", s
->cwnd
);
2370 out(" ssthresh:%d", s
->ssthresh
);
2373 out(" bytes_acked:%llu", s
->bytes_acked
);
2374 if (s
->bytes_received
)
2375 out(" bytes_received:%llu", s
->bytes_received
);
2377 out(" segs_out:%u", s
->segs_out
);
2379 out(" segs_in:%u", s
->segs_in
);
2380 if (s
->data_segs_out
)
2381 out(" data_segs_out:%u", s
->data_segs_out
);
2382 if (s
->data_segs_in
)
2383 out(" data_segs_in:%u", s
->data_segs_in
);
2385 if (s
->dctcp
&& s
->dctcp
->enabled
) {
2386 struct dctcpstat
*dctcp
= s
->dctcp
;
2388 out(" dctcp:(ce_state:%u,alpha:%u,ab_ecn:%u,ab_tot:%u)",
2389 dctcp
->ce_state
, dctcp
->alpha
, dctcp
->ab_ecn
,
2391 } else if (s
->dctcp
) {
2392 out(" dctcp:fallback_mode");
2398 bw
= s
->bbr_info
->bbr_bw_hi
;
2400 bw
|= s
->bbr_info
->bbr_bw_lo
;
2402 out(" bbr:(bw:%sbps,mrtt:%g",
2403 sprint_bw(b1
, bw
* 8.0),
2404 (double)s
->bbr_info
->bbr_min_rtt
/ 1000.0);
2405 if (s
->bbr_info
->bbr_pacing_gain
)
2406 out(",pacing_gain:%g",
2407 (double)s
->bbr_info
->bbr_pacing_gain
/ 256.0);
2408 if (s
->bbr_info
->bbr_cwnd_gain
)
2409 out(",cwnd_gain:%g",
2410 (double)s
->bbr_info
->bbr_cwnd_gain
/ 256.0);
2415 out(" send %sbps", sprint_bw(b1
, s
->send_bps
));
2417 out(" lastsnd:%u", s
->lastsnd
);
2419 out(" lastrcv:%u", s
->lastrcv
);
2421 out(" lastack:%u", s
->lastack
);
2423 if (s
->pacing_rate
) {
2424 out(" pacing_rate %sbps", sprint_bw(b1
, s
->pacing_rate
));
2425 if (s
->pacing_rate_max
)
2426 out("/%sbps", sprint_bw(b1
, s
->pacing_rate_max
));
2429 if (s
->delivery_rate
)
2430 out(" delivery_rate %sbps", sprint_bw(b1
, s
->delivery_rate
));
2432 out(" app_limited");
2435 out(" busy:%llums", s
->busy_time
/ 1000);
2436 if (s
->rwnd_limited
)
2437 out(" rwnd_limited:%llums(%.1f%%)",
2438 s
->rwnd_limited
/ 1000,
2439 100.0 * s
->rwnd_limited
/ s
->busy_time
);
2440 if (s
->sndbuf_limited
)
2441 out(" sndbuf_limited:%llums(%.1f%%)",
2442 s
->sndbuf_limited
/ 1000,
2443 100.0 * s
->sndbuf_limited
/ s
->busy_time
);
2447 out(" unacked:%u", s
->unacked
);
2448 if (s
->retrans
|| s
->retrans_total
)
2449 out(" retrans:%u/%u", s
->retrans
, s
->retrans_total
);
2451 out(" lost:%u", s
->lost
);
2452 if (s
->sacked
&& s
->ss
.state
!= SS_LISTEN
)
2453 out(" sacked:%u", s
->sacked
);
2455 out(" fackets:%u", s
->fackets
);
2456 if (s
->reordering
!= 3)
2457 out(" reordering:%d", s
->reordering
);
2459 out(" rcv_rtt:%g", s
->rcv_rtt
);
2461 out(" rcv_space:%d", s
->rcv_space
);
2462 if (s
->rcv_ssthresh
)
2463 out(" rcv_ssthresh:%u", s
->rcv_ssthresh
);
2465 out(" notsent:%u", s
->not_sent
);
2467 out(" minrtt:%g", s
->min_rtt
);
2470 static void tcp_timer_print(struct tcpstat
*s
)
2472 static const char * const tmr_name
[] = {
2484 out(" timer:(%s,%s,%d)",
2486 print_ms_timer(s
->timeout
),
2491 static void sctp_timer_print(struct tcpstat
*s
)
2494 out(" timer:(T3_RTX,%s,%d)",
2495 print_ms_timer(s
->timeout
), s
->retrans
);
2498 static int tcp_show_line(char *line
, const struct filter
*f
, int family
)
2500 int rto
= 0, ato
= 0;
2501 struct tcpstat s
= {};
2502 char *loc
, *rem
, *data
;
2505 int hz
= get_user_hz();
2507 if (proc_inet_split_line(line
, &loc
, &rem
, &data
))
2510 int state
= (data
[1] >= 'A') ? (data
[1] - 'A' + 10) : (data
[1] - '0');
2512 if (!(f
->states
& (1 << state
)))
2515 proc_parse_inet_addr(loc
, rem
, family
, &s
.ss
);
2517 if (f
->f
&& run_ssfilter(f
->f
, &s
.ss
) == 0)
2521 n
= sscanf(data
, "%x %x:%x %x:%x %x %d %d %u %d %llx %d %d %d %u %d %[^\n]\n",
2522 &s
.ss
.state
, &s
.ss
.wq
, &s
.ss
.rq
,
2523 &s
.timer
, &s
.timeout
, &s
.retrans
, &s
.ss
.uid
, &s
.probes
,
2524 &s
.ss
.ino
, &s
.ss
.refcnt
, &s
.ss
.sk
, &rto
, &ato
, &s
.qack
, &s
.cwnd
,
2537 s
.retrans
= s
.timer
!= 1 ? s
.probes
: s
.retrans
;
2538 s
.timeout
= (s
.timeout
* 1000 + hz
- 1) / hz
;
2539 s
.ato
= (double)ato
/ hz
;
2541 s
.rto
= (double)rto
;
2542 s
.ssthresh
= s
.ssthresh
== -1 ? 0 : s
.ssthresh
;
2543 s
.rto
= s
.rto
!= 3 * hz
? s
.rto
/ hz
: 0;
2544 s
.ss
.type
= IPPROTO_TCP
;
2546 inet_stats_print(&s
.ss
, false);
2549 tcp_timer_print(&s
);
2552 sock_details_print(&s
.ss
);
2554 out(" opt:\"%s\"", opt
);
2558 tcp_stats_print(&s
);
2563 static int generic_record_read(FILE *fp
,
2564 int (*worker
)(char*, const struct filter
*, int),
2565 const struct filter
*f
, int fam
)
2570 if (fgets(line
, sizeof(line
), fp
) == NULL
)
2573 while (fgets(line
, sizeof(line
), fp
) != NULL
) {
2574 int n
= strlen(line
);
2576 if (n
== 0 || line
[n
-1] != '\n') {
2582 if (worker(line
, f
, fam
) < 0)
2587 return ferror(fp
) ? -1 : 0;
2590 static void print_skmeminfo(struct rtattr
*tb
[], int attrtype
)
2592 const __u32
*skmeminfo
;
2594 if (!tb
[attrtype
]) {
2595 if (attrtype
== INET_DIAG_SKMEMINFO
) {
2596 if (!tb
[INET_DIAG_MEMINFO
])
2599 const struct inet_diag_meminfo
*minfo
=
2600 RTA_DATA(tb
[INET_DIAG_MEMINFO
]);
2602 out(" mem:(r%u,w%u,f%u,t%u)",
2611 skmeminfo
= RTA_DATA(tb
[attrtype
]);
2613 out(" skmem:(r%u,rb%u,t%u,tb%u,f%u,w%u,o%u",
2614 skmeminfo
[SK_MEMINFO_RMEM_ALLOC
],
2615 skmeminfo
[SK_MEMINFO_RCVBUF
],
2616 skmeminfo
[SK_MEMINFO_WMEM_ALLOC
],
2617 skmeminfo
[SK_MEMINFO_SNDBUF
],
2618 skmeminfo
[SK_MEMINFO_FWD_ALLOC
],
2619 skmeminfo
[SK_MEMINFO_WMEM_QUEUED
],
2620 skmeminfo
[SK_MEMINFO_OPTMEM
]);
2622 if (RTA_PAYLOAD(tb
[attrtype
]) >=
2623 (SK_MEMINFO_BACKLOG
+ 1) * sizeof(__u32
))
2624 out(",bl%u", skmeminfo
[SK_MEMINFO_BACKLOG
]);
2626 if (RTA_PAYLOAD(tb
[attrtype
]) >=
2627 (SK_MEMINFO_DROPS
+ 1) * sizeof(__u32
))
2628 out(",d%u", skmeminfo
[SK_MEMINFO_DROPS
]);
2633 static void print_md5sig(struct tcp_diag_md5sig
*sig
)
2636 format_host(sig
->tcpm_family
,
2637 sig
->tcpm_family
== AF_INET6
? 16 : 4,
2639 sig
->tcpm_prefixlen
);
2640 print_escape_buf(sig
->tcpm_key
, sig
->tcpm_keylen
, " ,");
2643 #define TCPI_HAS_OPT(info, opt) !!(info->tcpi_options & (opt))
2645 static void tcp_show_info(const struct nlmsghdr
*nlh
, struct inet_diag_msg
*r
,
2646 struct rtattr
*tb
[])
2649 struct tcpstat s
= {};
2651 s
.ss
.state
= r
->idiag_state
;
2653 print_skmeminfo(tb
, INET_DIAG_SKMEMINFO
);
2655 if (tb
[INET_DIAG_INFO
]) {
2656 struct tcp_info
*info
;
2657 int len
= RTA_PAYLOAD(tb
[INET_DIAG_INFO
]);
2659 /* workaround for older kernels with less fields */
2660 if (len
< sizeof(*info
)) {
2661 info
= alloca(sizeof(*info
));
2662 memcpy(info
, RTA_DATA(tb
[INET_DIAG_INFO
]), len
);
2663 memset((char *)info
+ len
, 0, sizeof(*info
) - len
);
2665 info
= RTA_DATA(tb
[INET_DIAG_INFO
]);
2668 s
.has_ts_opt
= TCPI_HAS_OPT(info
, TCPI_OPT_TIMESTAMPS
);
2669 s
.has_sack_opt
= TCPI_HAS_OPT(info
, TCPI_OPT_SACK
);
2670 s
.has_ecn_opt
= TCPI_HAS_OPT(info
, TCPI_OPT_ECN
);
2671 s
.has_ecnseen_opt
= TCPI_HAS_OPT(info
, TCPI_OPT_ECN_SEEN
);
2672 s
.has_fastopen_opt
= TCPI_HAS_OPT(info
, TCPI_OPT_SYN_DATA
);
2675 if (tb
[INET_DIAG_CONG
])
2677 rta_getattr_str(tb
[INET_DIAG_CONG
]),
2678 sizeof(s
.cong_alg
) - 1);
2680 if (TCPI_HAS_OPT(info
, TCPI_OPT_WSCALE
)) {
2681 s
.has_wscale_opt
= true;
2682 s
.snd_wscale
= info
->tcpi_snd_wscale
;
2683 s
.rcv_wscale
= info
->tcpi_rcv_wscale
;
2686 if (info
->tcpi_rto
&& info
->tcpi_rto
!= 3000000)
2687 s
.rto
= (double)info
->tcpi_rto
/ 1000;
2689 s
.backoff
= info
->tcpi_backoff
;
2690 s
.rtt
= (double)info
->tcpi_rtt
/ 1000;
2691 s
.rttvar
= (double)info
->tcpi_rttvar
/ 1000;
2692 s
.ato
= (double)info
->tcpi_ato
/ 1000;
2693 s
.mss
= info
->tcpi_snd_mss
;
2694 s
.rcv_mss
= info
->tcpi_rcv_mss
;
2695 s
.advmss
= info
->tcpi_advmss
;
2696 s
.rcv_space
= info
->tcpi_rcv_space
;
2697 s
.rcv_rtt
= (double)info
->tcpi_rcv_rtt
/ 1000;
2698 s
.lastsnd
= info
->tcpi_last_data_sent
;
2699 s
.lastrcv
= info
->tcpi_last_data_recv
;
2700 s
.lastack
= info
->tcpi_last_ack_recv
;
2701 s
.unacked
= info
->tcpi_unacked
;
2702 s
.retrans
= info
->tcpi_retrans
;
2703 s
.retrans_total
= info
->tcpi_total_retrans
;
2704 s
.lost
= info
->tcpi_lost
;
2705 s
.sacked
= info
->tcpi_sacked
;
2706 s
.fackets
= info
->tcpi_fackets
;
2707 s
.reordering
= info
->tcpi_reordering
;
2708 s
.rcv_ssthresh
= info
->tcpi_rcv_ssthresh
;
2709 s
.cwnd
= info
->tcpi_snd_cwnd
;
2711 if (info
->tcpi_snd_ssthresh
< 0xFFFF)
2712 s
.ssthresh
= info
->tcpi_snd_ssthresh
;
2714 rtt
= (double) info
->tcpi_rtt
;
2715 if (tb
[INET_DIAG_VEGASINFO
]) {
2716 const struct tcpvegas_info
*vinfo
2717 = RTA_DATA(tb
[INET_DIAG_VEGASINFO
]);
2719 if (vinfo
->tcpv_enabled
&&
2720 vinfo
->tcpv_rtt
&& vinfo
->tcpv_rtt
!= 0x7fffffff)
2721 rtt
= vinfo
->tcpv_rtt
;
2724 if (tb
[INET_DIAG_DCTCPINFO
]) {
2725 struct dctcpstat
*dctcp
= malloc(sizeof(struct
2728 const struct tcp_dctcp_info
*dinfo
2729 = RTA_DATA(tb
[INET_DIAG_DCTCPINFO
]);
2731 dctcp
->enabled
= !!dinfo
->dctcp_enabled
;
2732 dctcp
->ce_state
= dinfo
->dctcp_ce_state
;
2733 dctcp
->alpha
= dinfo
->dctcp_alpha
;
2734 dctcp
->ab_ecn
= dinfo
->dctcp_ab_ecn
;
2735 dctcp
->ab_tot
= dinfo
->dctcp_ab_tot
;
2739 if (tb
[INET_DIAG_BBRINFO
]) {
2740 const void *bbr_info
= RTA_DATA(tb
[INET_DIAG_BBRINFO
]);
2741 int len
= min(RTA_PAYLOAD(tb
[INET_DIAG_BBRINFO
]),
2742 sizeof(*s
.bbr_info
));
2744 s
.bbr_info
= calloc(1, sizeof(*s
.bbr_info
));
2745 if (s
.bbr_info
&& bbr_info
)
2746 memcpy(s
.bbr_info
, bbr_info
, len
);
2749 if (rtt
> 0 && info
->tcpi_snd_mss
&& info
->tcpi_snd_cwnd
) {
2750 s
.send_bps
= (double) info
->tcpi_snd_cwnd
*
2751 (double)info
->tcpi_snd_mss
* 8000000. / rtt
;
2754 if (info
->tcpi_pacing_rate
&&
2755 info
->tcpi_pacing_rate
!= ~0ULL) {
2756 s
.pacing_rate
= info
->tcpi_pacing_rate
* 8.;
2758 if (info
->tcpi_max_pacing_rate
&&
2759 info
->tcpi_max_pacing_rate
!= ~0ULL)
2760 s
.pacing_rate_max
= info
->tcpi_max_pacing_rate
* 8.;
2762 s
.bytes_acked
= info
->tcpi_bytes_acked
;
2763 s
.bytes_received
= info
->tcpi_bytes_received
;
2764 s
.segs_out
= info
->tcpi_segs_out
;
2765 s
.segs_in
= info
->tcpi_segs_in
;
2766 s
.data_segs_out
= info
->tcpi_data_segs_out
;
2767 s
.data_segs_in
= info
->tcpi_data_segs_in
;
2768 s
.not_sent
= info
->tcpi_notsent_bytes
;
2769 if (info
->tcpi_min_rtt
&& info
->tcpi_min_rtt
!= ~0U)
2770 s
.min_rtt
= (double) info
->tcpi_min_rtt
/ 1000;
2771 s
.delivery_rate
= info
->tcpi_delivery_rate
* 8.;
2772 s
.app_limited
= info
->tcpi_delivery_rate_app_limited
;
2773 s
.busy_time
= info
->tcpi_busy_time
;
2774 s
.rwnd_limited
= info
->tcpi_rwnd_limited
;
2775 s
.sndbuf_limited
= info
->tcpi_sndbuf_limited
;
2776 tcp_stats_print(&s
);
2780 if (tb
[INET_DIAG_MD5SIG
]) {
2781 struct tcp_diag_md5sig
*sig
= RTA_DATA(tb
[INET_DIAG_MD5SIG
]);
2782 int len
= RTA_PAYLOAD(tb
[INET_DIAG_MD5SIG
]);
2785 print_md5sig(sig
++);
2786 for (len
-= sizeof(*sig
); len
> 0; len
-= sizeof(*sig
)) {
2788 print_md5sig(sig
++);
2793 static const char *format_host_sa(struct sockaddr_storage
*sa
)
2796 struct sockaddr_in sin
;
2797 struct sockaddr_in6 sin6
;
2798 } *saddr
= (void *)sa
;
2800 switch (sa
->ss_family
) {
2802 return format_host(AF_INET
, 4, &saddr
->sin
.sin_addr
);
2804 return format_host(AF_INET6
, 16, &saddr
->sin6
.sin6_addr
);
2810 static void sctp_show_info(const struct nlmsghdr
*nlh
, struct inet_diag_msg
*r
,
2811 struct rtattr
*tb
[])
2813 struct sockaddr_storage
*sa
;
2816 print_skmeminfo(tb
, INET_DIAG_SKMEMINFO
);
2818 if (tb
[INET_DIAG_LOCALS
]) {
2819 len
= RTA_PAYLOAD(tb
[INET_DIAG_LOCALS
]);
2820 sa
= RTA_DATA(tb
[INET_DIAG_LOCALS
]);
2822 out("locals:%s", format_host_sa(sa
));
2823 for (sa
++, len
-= sizeof(*sa
); len
> 0; sa
++, len
-= sizeof(*sa
))
2824 out(",%s", format_host_sa(sa
));
2827 if (tb
[INET_DIAG_PEERS
]) {
2828 len
= RTA_PAYLOAD(tb
[INET_DIAG_PEERS
]);
2829 sa
= RTA_DATA(tb
[INET_DIAG_PEERS
]);
2831 out(" peers:%s", format_host_sa(sa
));
2832 for (sa
++, len
-= sizeof(*sa
); len
> 0; sa
++, len
-= sizeof(*sa
))
2833 out(",%s", format_host_sa(sa
));
2835 if (tb
[INET_DIAG_INFO
]) {
2836 struct sctp_info
*info
;
2837 len
= RTA_PAYLOAD(tb
[INET_DIAG_INFO
]);
2839 /* workaround for older kernels with less fields */
2840 if (len
< sizeof(*info
)) {
2841 info
= alloca(sizeof(*info
));
2842 memcpy(info
, RTA_DATA(tb
[INET_DIAG_INFO
]), len
);
2843 memset((char *)info
+ len
, 0, sizeof(*info
) - len
);
2845 info
= RTA_DATA(tb
[INET_DIAG_INFO
]);
2847 sctp_stats_print(info
);
2851 static void parse_diag_msg(struct nlmsghdr
*nlh
, struct sockstat
*s
)
2853 struct rtattr
*tb
[INET_DIAG_MAX
+1];
2854 struct inet_diag_msg
*r
= NLMSG_DATA(nlh
);
2856 parse_rtattr(tb
, INET_DIAG_MAX
, (struct rtattr
*)(r
+1),
2857 nlh
->nlmsg_len
- NLMSG_LENGTH(sizeof(*r
)));
2859 s
->state
= r
->idiag_state
;
2860 s
->local
.family
= s
->remote
.family
= r
->idiag_family
;
2861 s
->lport
= ntohs(r
->id
.idiag_sport
);
2862 s
->rport
= ntohs(r
->id
.idiag_dport
);
2863 s
->wq
= r
->idiag_wqueue
;
2864 s
->rq
= r
->idiag_rqueue
;
2865 s
->ino
= r
->idiag_inode
;
2866 s
->uid
= r
->idiag_uid
;
2867 s
->iface
= r
->id
.idiag_if
;
2868 s
->sk
= cookie_sk_get(&r
->id
.idiag_cookie
[0]);
2871 if (tb
[INET_DIAG_MARK
])
2872 s
->mark
= rta_getattr_u32(tb
[INET_DIAG_MARK
]);
2873 if (tb
[INET_DIAG_PROTOCOL
])
2874 s
->raw_prot
= rta_getattr_u8(tb
[INET_DIAG_PROTOCOL
]);
2878 if (s
->local
.family
== AF_INET
)
2879 s
->local
.bytelen
= s
->remote
.bytelen
= 4;
2881 s
->local
.bytelen
= s
->remote
.bytelen
= 16;
2883 memcpy(s
->local
.data
, r
->id
.idiag_src
, s
->local
.bytelen
);
2884 memcpy(s
->remote
.data
, r
->id
.idiag_dst
, s
->local
.bytelen
);
2887 static int inet_show_sock(struct nlmsghdr
*nlh
,
2890 struct rtattr
*tb
[INET_DIAG_MAX
+1];
2891 struct inet_diag_msg
*r
= NLMSG_DATA(nlh
);
2892 unsigned char v6only
= 0;
2894 parse_rtattr(tb
, INET_DIAG_MAX
, (struct rtattr
*)(r
+1),
2895 nlh
->nlmsg_len
- NLMSG_LENGTH(sizeof(*r
)));
2897 if (tb
[INET_DIAG_PROTOCOL
])
2898 s
->type
= rta_getattr_u8(tb
[INET_DIAG_PROTOCOL
]);
2900 if (s
->local
.family
== AF_INET6
&& tb
[INET_DIAG_SKV6ONLY
])
2901 v6only
= rta_getattr_u8(tb
[INET_DIAG_SKV6ONLY
]);
2903 inet_stats_print(s
, v6only
);
2906 struct tcpstat t
= {};
2908 t
.timer
= r
->idiag_timer
;
2909 t
.timeout
= r
->idiag_expires
;
2910 t
.retrans
= r
->idiag_retrans
;
2911 if (s
->type
== IPPROTO_SCTP
)
2912 sctp_timer_print(&t
);
2914 tcp_timer_print(&t
);
2918 sock_details_print(s
);
2919 if (s
->local
.family
== AF_INET6
&& tb
[INET_DIAG_SKV6ONLY
])
2920 out(" v6only:%u", v6only
);
2922 if (tb
[INET_DIAG_SHUTDOWN
]) {
2925 mask
= rta_getattr_u8(tb
[INET_DIAG_SHUTDOWN
]);
2927 mask
& 1 ? '-' : '<', mask
& 2 ? '-' : '>');
2931 if (show_mem
|| (show_tcpinfo
&& s
->type
!= IPPROTO_UDP
)) {
2933 if (s
->type
== IPPROTO_SCTP
)
2934 sctp_show_info(nlh
, r
, tb
);
2936 tcp_show_info(nlh
, r
, tb
);
2943 static int tcpdiag_send(int fd
, int protocol
, struct filter
*f
)
2945 struct sockaddr_nl nladdr
= { .nl_family
= AF_NETLINK
};
2947 struct nlmsghdr nlh
;
2948 struct inet_diag_req r
;
2950 .nlh
.nlmsg_len
= sizeof(req
),
2951 .nlh
.nlmsg_flags
= NLM_F_ROOT
| NLM_F_MATCH
| NLM_F_REQUEST
,
2952 .nlh
.nlmsg_seq
= MAGIC_SEQ
,
2953 .r
.idiag_family
= AF_INET
,
2954 .r
.idiag_states
= f
->states
,
2960 struct iovec iov
[3];
2963 if (protocol
== IPPROTO_UDP
)
2966 if (protocol
== IPPROTO_TCP
)
2967 req
.nlh
.nlmsg_type
= TCPDIAG_GETSOCK
;
2969 req
.nlh
.nlmsg_type
= DCCPDIAG_GETSOCK
;
2971 req
.r
.idiag_ext
|= (1<<(INET_DIAG_MEMINFO
-1));
2972 req
.r
.idiag_ext
|= (1<<(INET_DIAG_SKMEMINFO
-1));
2976 req
.r
.idiag_ext
|= (1<<(INET_DIAG_INFO
-1));
2977 req
.r
.idiag_ext
|= (1<<(INET_DIAG_VEGASINFO
-1));
2978 req
.r
.idiag_ext
|= (1<<(INET_DIAG_CONG
-1));
2981 iov
[0] = (struct iovec
){
2983 .iov_len
= sizeof(req
)
2986 bclen
= ssfilter_bytecompile(f
->f
, &bc
);
2988 rta
.rta_type
= INET_DIAG_REQ_BYTECODE
;
2989 rta
.rta_len
= RTA_LENGTH(bclen
);
2990 iov
[1] = (struct iovec
){ &rta
, sizeof(rta
) };
2991 iov
[2] = (struct iovec
){ bc
, bclen
};
2992 req
.nlh
.nlmsg_len
+= RTA_LENGTH(bclen
);
2997 msg
= (struct msghdr
) {
2998 .msg_name
= (void *)&nladdr
,
2999 .msg_namelen
= sizeof(nladdr
),
3001 .msg_iovlen
= iovlen
,
3004 if (sendmsg(fd
, &msg
, 0) < 0) {
3012 static int sockdiag_send(int family
, int fd
, int protocol
, struct filter
*f
)
3014 struct sockaddr_nl nladdr
= { .nl_family
= AF_NETLINK
};
3015 DIAG_REQUEST(req
, struct inet_diag_req_v2 r
);
3020 struct iovec iov
[3];
3023 if (family
== PF_UNSPEC
)
3024 return tcpdiag_send(fd
, protocol
, f
);
3026 memset(&req
.r
, 0, sizeof(req
.r
));
3027 req
.r
.sdiag_family
= family
;
3028 req
.r
.sdiag_protocol
= protocol
;
3029 req
.r
.idiag_states
= f
->states
;
3031 req
.r
.idiag_ext
|= (1<<(INET_DIAG_MEMINFO
-1));
3032 req
.r
.idiag_ext
|= (1<<(INET_DIAG_SKMEMINFO
-1));
3036 req
.r
.idiag_ext
|= (1<<(INET_DIAG_INFO
-1));
3037 req
.r
.idiag_ext
|= (1<<(INET_DIAG_VEGASINFO
-1));
3038 req
.r
.idiag_ext
|= (1<<(INET_DIAG_CONG
-1));
3041 iov
[0] = (struct iovec
){
3043 .iov_len
= sizeof(req
)
3046 bclen
= ssfilter_bytecompile(f
->f
, &bc
);
3048 rta
.rta_type
= INET_DIAG_REQ_BYTECODE
;
3049 rta
.rta_len
= RTA_LENGTH(bclen
);
3050 iov
[1] = (struct iovec
){ &rta
, sizeof(rta
) };
3051 iov
[2] = (struct iovec
){ bc
, bclen
};
3052 req
.nlh
.nlmsg_len
+= RTA_LENGTH(bclen
);
3057 msg
= (struct msghdr
) {
3058 .msg_name
= (void *)&nladdr
,
3059 .msg_namelen
= sizeof(nladdr
),
3061 .msg_iovlen
= iovlen
,
3064 if (sendmsg(fd
, &msg
, 0) < 0) {
3072 struct inet_diag_arg
{
3075 struct rtnl_handle
*rth
;
3078 static int kill_inet_sock(struct nlmsghdr
*h
, void *arg
, struct sockstat
*s
)
3080 struct inet_diag_msg
*d
= NLMSG_DATA(h
);
3081 struct inet_diag_arg
*diag_arg
= arg
;
3082 struct rtnl_handle
*rth
= diag_arg
->rth
;
3084 DIAG_REQUEST(req
, struct inet_diag_req_v2 r
);
3086 req
.nlh
.nlmsg_type
= SOCK_DESTROY
;
3087 req
.nlh
.nlmsg_flags
= NLM_F_REQUEST
| NLM_F_ACK
;
3088 req
.nlh
.nlmsg_seq
= ++rth
->seq
;
3089 req
.r
.sdiag_family
= d
->idiag_family
;
3090 req
.r
.sdiag_protocol
= diag_arg
->protocol
;
3093 if (diag_arg
->protocol
== IPPROTO_RAW
) {
3094 struct inet_diag_req_raw
*raw
= (void *)&req
.r
;
3096 BUILD_BUG_ON(sizeof(req
.r
) != sizeof(*raw
));
3097 raw
->sdiag_raw_protocol
= s
->raw_prot
;
3100 return rtnl_talk(rth
, &req
.nlh
, NULL
);
3103 static int show_one_inet_sock(const struct sockaddr_nl
*addr
,
3104 struct nlmsghdr
*h
, void *arg
)
3107 struct inet_diag_arg
*diag_arg
= arg
;
3108 struct inet_diag_msg
*r
= NLMSG_DATA(h
);
3109 struct sockstat s
= {};
3111 if (!(diag_arg
->f
->families
& FAMILY_MASK(r
->idiag_family
)))
3114 parse_diag_msg(h
, &s
);
3115 s
.type
= diag_arg
->protocol
;
3117 if (diag_arg
->f
->f
&& run_ssfilter(diag_arg
->f
->f
, &s
) == 0)
3120 if (diag_arg
->f
->kill
&& kill_inet_sock(h
, arg
, &s
) != 0) {
3121 if (errno
== EOPNOTSUPP
|| errno
== ENOENT
) {
3122 /* Socket can't be closed, or is already closed. */
3125 perror("SOCK_DESTROY answers");
3130 err
= inet_show_sock(h
, &s
);
3137 static int inet_show_netlink(struct filter
*f
, FILE *dump_fp
, int protocol
)
3140 struct rtnl_handle rth
, rth2
;
3141 int family
= PF_INET
;
3142 struct inet_diag_arg arg
= { .f
= f
, .protocol
= protocol
};
3144 if (rtnl_open_byproto(&rth
, 0, NETLINK_SOCK_DIAG
))
3148 if (rtnl_open_byproto(&rth2
, 0, NETLINK_SOCK_DIAG
)) {
3155 rth
.dump
= MAGIC_SEQ
;
3156 rth
.dump_fp
= dump_fp
;
3157 if (preferred_family
== PF_INET6
)
3161 if ((err
= sockdiag_send(family
, rth
.fd
, protocol
, f
)))
3164 if ((err
= rtnl_dump_filter(&rth
, show_one_inet_sock
, &arg
))) {
3165 if (family
!= PF_UNSPEC
) {
3171 if (family
== PF_INET
&& preferred_family
!= PF_INET
) {
3179 rtnl_close(arg
.rth
);
3183 static int tcp_show_netlink_file(struct filter
*f
)
3189 if ((fp
= fopen(getenv("TCPDIAG_FILE"), "r")) == NULL
) {
3190 perror("fopen($TCPDIAG_FILE)");
3196 struct nlmsghdr
*h
= (struct nlmsghdr
*)buf
;
3197 struct sockstat s
= {};
3199 status
= fread(buf
, 1, sizeof(*h
), fp
);
3201 perror("Reading header from $TCPDIAG_FILE");
3204 if (status
!= sizeof(*h
)) {
3205 perror("Unexpected EOF reading $TCPDIAG_FILE");
3209 status
= fread(h
+1, 1, NLMSG_ALIGN(h
->nlmsg_len
-sizeof(*h
)), fp
);
3212 perror("Reading $TCPDIAG_FILE");
3215 if (status
+ sizeof(*h
) < h
->nlmsg_len
) {
3216 perror("Unexpected EOF reading $TCPDIAG_FILE");
3220 /* The only legal exit point */
3221 if (h
->nlmsg_type
== NLMSG_DONE
) {
3226 if (h
->nlmsg_type
== NLMSG_ERROR
) {
3227 struct nlmsgerr
*err
= (struct nlmsgerr
*)NLMSG_DATA(h
);
3229 if (h
->nlmsg_len
< NLMSG_LENGTH(sizeof(struct nlmsgerr
))) {
3230 fprintf(stderr
, "ERROR truncated\n");
3232 errno
= -err
->error
;
3233 perror("TCPDIAG answered");
3238 parse_diag_msg(h
, &s
);
3239 s
.type
= IPPROTO_TCP
;
3241 if (f
&& f
->f
&& run_ssfilter(f
->f
, &s
) == 0)
3244 err2
= inet_show_sock(h
, &s
);
3255 static int tcp_show(struct filter
*f
)
3259 int bufsize
= 64*1024;
3261 if (!filter_af_get(f
, AF_INET
) && !filter_af_get(f
, AF_INET6
))
3264 dg_proto
= TCP_PROTO
;
3266 if (getenv("TCPDIAG_FILE"))
3267 return tcp_show_netlink_file(f
);
3269 if (!getenv("PROC_NET_TCP") && !getenv("PROC_ROOT")
3270 && inet_show_netlink(f
, NULL
, IPPROTO_TCP
) == 0)
3273 /* Sigh... We have to parse /proc/net/tcp... */
3276 /* Estimate amount of sockets and try to allocate
3277 * huge buffer to read all the table at one read.
3278 * Limit it by 16MB though. The assumption is: as soon as
3279 * kernel was able to hold information about N connections,
3280 * it is able to give us some memory for snapshot.
3283 get_slabstat(&slabstat
);
3285 int guess
= slabstat
.socks
+slabstat
.tcp_syns
;
3287 if (f
->states
&(1<<SS_TIME_WAIT
))
3288 guess
+= slabstat
.tcp_tws
;
3289 if (guess
> (16*1024*1024)/128)
3290 guess
= (16*1024*1024)/128;
3292 if (guess
> bufsize
)
3295 while (bufsize
>= 64*1024) {
3296 if ((buf
= malloc(bufsize
)) != NULL
)
3305 if (f
->families
& FAMILY_MASK(AF_INET
)) {
3306 if ((fp
= net_tcp_open()) == NULL
)
3309 setbuffer(fp
, buf
, bufsize
);
3310 if (generic_record_read(fp
, tcp_show_line
, f
, AF_INET
))
3315 if ((f
->families
& FAMILY_MASK(AF_INET6
)) &&
3316 (fp
= net_tcp6_open()) != NULL
) {
3317 setbuffer(fp
, buf
, bufsize
);
3318 if (generic_record_read(fp
, tcp_show_line
, f
, AF_INET6
))
3328 int saved_errno
= errno
;
3333 errno
= saved_errno
;
3338 static int dccp_show(struct filter
*f
)
3340 if (!filter_af_get(f
, AF_INET
) && !filter_af_get(f
, AF_INET6
))
3343 if (!getenv("PROC_NET_DCCP") && !getenv("PROC_ROOT")
3344 && inet_show_netlink(f
, NULL
, IPPROTO_DCCP
) == 0)
3350 static int sctp_show(struct filter
*f
)
3352 if (!filter_af_get(f
, AF_INET
) && !filter_af_get(f
, AF_INET6
))
3355 if (!getenv("PROC_NET_SCTP") && !getenv("PROC_ROOT")
3356 && inet_show_netlink(f
, NULL
, IPPROTO_SCTP
) == 0)
3362 static int dgram_show_line(char *line
, const struct filter
*f
, int family
)
3364 struct sockstat s
= {};
3365 char *loc
, *rem
, *data
;
3369 if (proc_inet_split_line(line
, &loc
, &rem
, &data
))
3372 int state
= (data
[1] >= 'A') ? (data
[1] - 'A' + 10) : (data
[1] - '0');
3374 if (!(f
->states
& (1 << state
)))
3377 proc_parse_inet_addr(loc
, rem
, family
, &s
);
3379 if (f
->f
&& run_ssfilter(f
->f
, &s
) == 0)
3383 n
= sscanf(data
, "%x %x:%x %*x:%*x %*x %d %*d %u %d %llx %[^\n]\n",
3384 &s
.state
, &s
.wq
, &s
.rq
,
3386 &s
.refcnt
, &s
.sk
, opt
);
3391 s
.type
= dg_proto
== UDP_PROTO
? IPPROTO_UDP
: 0;
3392 inet_stats_print(&s
, false);
3394 if (show_details
&& opt
[0])
3395 out(" opt:\"%s\"", opt
);
3400 static int udp_show(struct filter
*f
)
3404 if (!filter_af_get(f
, AF_INET
) && !filter_af_get(f
, AF_INET6
))
3407 dg_proto
= UDP_PROTO
;
3409 if (!getenv("PROC_NET_UDP") && !getenv("PROC_ROOT")
3410 && inet_show_netlink(f
, NULL
, IPPROTO_UDP
) == 0)
3413 if (f
->families
&FAMILY_MASK(AF_INET
)) {
3414 if ((fp
= net_udp_open()) == NULL
)
3416 if (generic_record_read(fp
, dgram_show_line
, f
, AF_INET
))
3421 if ((f
->families
&FAMILY_MASK(AF_INET6
)) &&
3422 (fp
= net_udp6_open()) != NULL
) {
3423 if (generic_record_read(fp
, dgram_show_line
, f
, AF_INET6
))
3431 int saved_errno
= errno
;
3435 errno
= saved_errno
;
3440 static int raw_show(struct filter
*f
)
3444 if (!filter_af_get(f
, AF_INET
) && !filter_af_get(f
, AF_INET6
))
3447 dg_proto
= RAW_PROTO
;
3449 if (!getenv("PROC_NET_RAW") && !getenv("PROC_ROOT") &&
3450 inet_show_netlink(f
, NULL
, IPPROTO_RAW
) == 0)
3453 if (f
->families
&FAMILY_MASK(AF_INET
)) {
3454 if ((fp
= net_raw_open()) == NULL
)
3456 if (generic_record_read(fp
, dgram_show_line
, f
, AF_INET
))
3461 if ((f
->families
&FAMILY_MASK(AF_INET6
)) &&
3462 (fp
= net_raw6_open()) != NULL
) {
3463 if (generic_record_read(fp
, dgram_show_line
, f
, AF_INET6
))
3471 int saved_errno
= errno
;
3475 errno
= saved_errno
;
3480 #define MAX_UNIX_REMEMBER (1024*1024/sizeof(struct sockstat))
3482 static void unix_list_drop_first(struct sockstat
**list
)
3484 struct sockstat
*s
= *list
;
3486 (*list
) = (*list
)->next
;
3491 static bool unix_type_skip(struct sockstat
*s
, struct filter
*f
)
3493 if (s
->type
== SOCK_STREAM
&& !(f
->dbs
&(1<<UNIX_ST_DB
)))
3495 if (s
->type
== SOCK_DGRAM
&& !(f
->dbs
&(1<<UNIX_DG_DB
)))
3497 if (s
->type
== SOCK_SEQPACKET
&& !(f
->dbs
&(1<<UNIX_SQ_DB
)))
3502 static void unix_stats_print(struct sockstat
*s
, struct filter
*f
)
3504 char port_name
[30] = {};
3506 sock_state_print(s
);
3508 sock_addr_print(s
->name
?: "*", " ",
3509 int_to_str(s
->lport
, port_name
), NULL
);
3510 sock_addr_print(s
->peer_name
?: "*", " ",
3511 int_to_str(s
->rport
, port_name
), NULL
);
3516 static int unix_show_sock(const struct sockaddr_nl
*addr
, struct nlmsghdr
*nlh
,
3519 struct filter
*f
= (struct filter
*)arg
;
3520 struct unix_diag_msg
*r
= NLMSG_DATA(nlh
);
3521 struct rtattr
*tb
[UNIX_DIAG_MAX
+1];
3523 struct sockstat stat
= { .name
= "*", .peer_name
= "*" };
3525 parse_rtattr(tb
, UNIX_DIAG_MAX
, (struct rtattr
*)(r
+1),
3526 nlh
->nlmsg_len
- NLMSG_LENGTH(sizeof(*r
)));
3528 stat
.type
= r
->udiag_type
;
3529 stat
.state
= r
->udiag_state
;
3530 stat
.ino
= stat
.lport
= r
->udiag_ino
;
3531 stat
.local
.family
= stat
.remote
.family
= AF_UNIX
;
3533 if (unix_type_skip(&stat
, f
))
3536 if (tb
[UNIX_DIAG_RQLEN
]) {
3537 struct unix_diag_rqlen
*rql
= RTA_DATA(tb
[UNIX_DIAG_RQLEN
]);
3539 stat
.rq
= rql
->udiag_rqueue
;
3540 stat
.wq
= rql
->udiag_wqueue
;
3542 if (tb
[UNIX_DIAG_NAME
]) {
3543 int len
= RTA_PAYLOAD(tb
[UNIX_DIAG_NAME
]);
3545 memcpy(name
, RTA_DATA(tb
[UNIX_DIAG_NAME
]), len
);
3547 if (name
[0] == '\0') {
3549 for (i
= 0; i
< len
; i
++)
3550 if (name
[i
] == '\0')
3553 stat
.name
= &name
[0];
3554 memcpy(stat
.local
.data
, &stat
.name
, sizeof(stat
.name
));
3556 if (tb
[UNIX_DIAG_PEER
])
3557 stat
.rport
= rta_getattr_u32(tb
[UNIX_DIAG_PEER
]);
3559 if (f
->f
&& run_ssfilter(f
->f
, &stat
) == 0)
3562 unix_stats_print(&stat
, f
);
3565 print_skmeminfo(tb
, UNIX_DIAG_MEMINFO
);
3567 if (tb
[UNIX_DIAG_SHUTDOWN
]) {
3570 mask
= rta_getattr_u8(tb
[UNIX_DIAG_SHUTDOWN
]);
3572 mask
& 1 ? '-' : '<', mask
& 2 ? '-' : '>');
3579 static int handle_netlink_request(struct filter
*f
, struct nlmsghdr
*req
,
3580 size_t size
, rtnl_filter_t show_one_sock
)
3583 struct rtnl_handle rth
;
3585 if (rtnl_open_byproto(&rth
, 0, NETLINK_SOCK_DIAG
))
3588 rth
.dump
= MAGIC_SEQ
;
3590 if (rtnl_send(&rth
, req
, size
) < 0)
3593 if (rtnl_dump_filter(&rth
, show_one_sock
, f
))
3602 static int unix_show_netlink(struct filter
*f
)
3604 DIAG_REQUEST(req
, struct unix_diag_req r
);
3606 req
.r
.sdiag_family
= AF_UNIX
;
3607 req
.r
.udiag_states
= f
->states
;
3608 req
.r
.udiag_show
= UDIAG_SHOW_NAME
| UDIAG_SHOW_PEER
| UDIAG_SHOW_RQLEN
;
3610 req
.r
.udiag_show
|= UDIAG_SHOW_MEMINFO
;
3612 return handle_netlink_request(f
, &req
.nlh
, sizeof(req
), unix_show_sock
);
3615 static int unix_show(struct filter
*f
)
3622 struct sockstat
*list
= NULL
;
3623 const int unix_state_map
[] = { SS_CLOSE
, SS_SYN_SENT
,
3624 SS_ESTABLISHED
, SS_CLOSING
};
3626 if (!filter_af_get(f
, AF_UNIX
))
3629 if (!getenv("PROC_NET_UNIX") && !getenv("PROC_ROOT")
3630 && unix_show_netlink(f
) == 0)
3633 if ((fp
= net_unix_open()) == NULL
)
3635 if (!fgets(buf
, sizeof(buf
), fp
)) {
3640 if (memcmp(buf
, "Peer", 4) == 0)
3644 while (fgets(buf
, sizeof(buf
), fp
)) {
3645 struct sockstat
*u
, **insp
;
3648 if (!(u
= calloc(1, sizeof(*u
))))
3651 if (sscanf(buf
, "%x: %x %x %x %x %x %d %s",
3652 &u
->rport
, &u
->rq
, &u
->wq
, &flags
, &u
->type
,
3653 &u
->state
, &u
->ino
, name
) < 8)
3657 u
->local
.family
= u
->remote
.family
= AF_UNIX
;
3659 if (flags
& (1 << 16)) {
3660 u
->state
= SS_LISTEN
;
3661 } else if (u
->state
> 0 &&
3662 u
->state
<= ARRAY_SIZE(unix_state_map
)) {
3663 u
->state
= unix_state_map
[u
->state
-1];
3664 if (u
->type
== SOCK_DGRAM
&& u
->state
== SS_CLOSE
&& u
->rport
)
3665 u
->state
= SS_ESTABLISHED
;
3667 if (unix_type_skip(u
, f
) ||
3668 !(f
->states
& (1 << u
->state
))) {
3680 u
->name
= strdup(name
);
3690 for (p
= list
; p
; p
= p
->next
) {
3691 if (u
->rport
== p
->lport
)
3697 u
->peer_name
= p
->name
? : "*";
3701 struct sockstat st
= {
3702 .local
.family
= AF_UNIX
,
3703 .remote
.family
= AF_UNIX
,
3706 memcpy(st
.local
.data
, &u
->name
, sizeof(u
->name
));
3707 if (strcmp(u
->peer_name
, "*"))
3708 memcpy(st
.remote
.data
, &u
->peer_name
,
3709 sizeof(u
->peer_name
));
3710 if (run_ssfilter(f
->f
, &st
) == 0) {
3719 if (u
->type
< (*insp
)->type
||
3720 (u
->type
== (*insp
)->type
&&
3721 u
->ino
< (*insp
)->ino
))
3723 insp
= &(*insp
)->next
;
3728 if (++cnt
> MAX_UNIX_REMEMBER
) {
3730 unix_stats_print(list
, f
);
3731 unix_list_drop_first(&list
);
3738 unix_stats_print(list
, f
);
3739 unix_list_drop_first(&list
);
3745 static int packet_stats_print(struct sockstat
*s
, const struct filter
*f
)
3747 const char *addr
, *port
;
3750 s
->local
.family
= s
->remote
.family
= AF_PACKET
;
3753 s
->local
.data
[0] = s
->prot
;
3754 if (run_ssfilter(f
->f
, s
) == 0)
3758 sock_state_print(s
);
3763 addr
= ll_proto_n2a(htons(s
->prot
), ll_name
, sizeof(ll_name
));
3768 port
= xll_index_to_name(s
->iface
);
3770 sock_addr_print(addr
, ":", port
, NULL
);
3771 sock_addr_print("", "*", "", NULL
);
3776 sock_details_print(s
);
3781 static void packet_show_ring(struct packet_diag_ring
*ring
)
3783 out("blk_size:%d", ring
->pdr_block_size
);
3784 out(",blk_nr:%d", ring
->pdr_block_nr
);
3785 out(",frm_size:%d", ring
->pdr_frame_size
);
3786 out(",frm_nr:%d", ring
->pdr_frame_nr
);
3787 out(",tmo:%d", ring
->pdr_retire_tmo
);
3788 out(",features:0x%x", ring
->pdr_features
);
3791 static int packet_show_sock(const struct sockaddr_nl
*addr
,
3792 struct nlmsghdr
*nlh
, void *arg
)
3794 const struct filter
*f
= arg
;
3795 struct packet_diag_msg
*r
= NLMSG_DATA(nlh
);
3796 struct packet_diag_info
*pinfo
= NULL
;
3797 struct packet_diag_ring
*ring_rx
= NULL
, *ring_tx
= NULL
;
3798 struct rtattr
*tb
[PACKET_DIAG_MAX
+1];
3799 struct sockstat stat
= {};
3800 uint32_t fanout
= 0;
3801 bool has_fanout
= false;
3803 parse_rtattr(tb
, PACKET_DIAG_MAX
, (struct rtattr
*)(r
+1),
3804 nlh
->nlmsg_len
- NLMSG_LENGTH(sizeof(*r
)));
3806 /* use /proc/net/packet if all info are not available */
3807 if (!tb
[PACKET_DIAG_MEMINFO
])
3810 stat
.type
= r
->pdiag_type
;
3811 stat
.prot
= r
->pdiag_num
;
3812 stat
.ino
= r
->pdiag_ino
;
3813 stat
.state
= SS_CLOSE
;
3814 stat
.sk
= cookie_sk_get(&r
->pdiag_cookie
[0]);
3816 if (tb
[PACKET_DIAG_MEMINFO
]) {
3817 __u32
*skmeminfo
= RTA_DATA(tb
[PACKET_DIAG_MEMINFO
]);
3819 stat
.rq
= skmeminfo
[SK_MEMINFO_RMEM_ALLOC
];
3822 if (tb
[PACKET_DIAG_INFO
]) {
3823 pinfo
= RTA_DATA(tb
[PACKET_DIAG_INFO
]);
3824 stat
.lport
= stat
.iface
= pinfo
->pdi_index
;
3827 if (tb
[PACKET_DIAG_UID
])
3828 stat
.uid
= rta_getattr_u32(tb
[PACKET_DIAG_UID
]);
3830 if (tb
[PACKET_DIAG_RX_RING
])
3831 ring_rx
= RTA_DATA(tb
[PACKET_DIAG_RX_RING
]);
3833 if (tb
[PACKET_DIAG_TX_RING
])
3834 ring_tx
= RTA_DATA(tb
[PACKET_DIAG_TX_RING
]);
3836 if (tb
[PACKET_DIAG_FANOUT
]) {
3838 fanout
= rta_getattr_u32(tb
[PACKET_DIAG_FANOUT
]);
3841 if (packet_stats_print(&stat
, f
))
3846 out("\n\tver:%d", pinfo
->pdi_version
);
3847 out(" cpy_thresh:%d", pinfo
->pdi_copy_thresh
);
3849 if (pinfo
->pdi_flags
& PDI_RUNNING
)
3851 if (pinfo
->pdi_flags
& PDI_AUXDATA
)
3853 if (pinfo
->pdi_flags
& PDI_ORIGDEV
)
3855 if (pinfo
->pdi_flags
& PDI_VNETHDR
)
3857 if (pinfo
->pdi_flags
& PDI_LOSS
)
3859 if (!pinfo
->pdi_flags
)
3864 out("\n\tring_rx(");
3865 packet_show_ring(ring_rx
);
3869 out("\n\tring_tx(");
3870 packet_show_ring(ring_tx
);
3874 uint16_t type
= (fanout
>> 16) & 0xffff;
3877 out("id:%d,", fanout
& 0xffff);
3899 if (show_bpf
&& tb
[PACKET_DIAG_FILTER
]) {
3900 struct sock_filter
*fil
=
3901 RTA_DATA(tb
[PACKET_DIAG_FILTER
]);
3902 int num
= RTA_PAYLOAD(tb
[PACKET_DIAG_FILTER
]) /
3903 sizeof(struct sock_filter
);
3905 out("\n\tbpf filter (%d): ", num
);
3907 out(" 0x%02x %u %u %u,",
3908 fil
->code
, fil
->jt
, fil
->jf
, fil
->k
);
3916 static int packet_show_netlink(struct filter
*f
)
3918 DIAG_REQUEST(req
, struct packet_diag_req r
);
3920 req
.r
.sdiag_family
= AF_PACKET
;
3921 req
.r
.pdiag_show
= PACKET_SHOW_INFO
| PACKET_SHOW_MEMINFO
|
3922 PACKET_SHOW_FILTER
| PACKET_SHOW_RING_CFG
| PACKET_SHOW_FANOUT
;
3924 return handle_netlink_request(f
, &req
.nlh
, sizeof(req
), packet_show_sock
);
3927 static int packet_show_line(char *buf
, const struct filter
*f
, int fam
)
3929 unsigned long long sk
;
3930 struct sockstat stat
= {};
3931 int type
, prot
, iface
, state
, rq
, uid
, ino
;
3933 sscanf(buf
, "%llx %*d %d %x %d %d %u %u %u",
3935 &type
, &prot
, &iface
, &state
,
3938 if (stat
.type
== SOCK_RAW
&& !(f
->dbs
&(1<<PACKET_R_DB
)))
3940 if (stat
.type
== SOCK_DGRAM
&& !(f
->dbs
&(1<<PACKET_DG_DB
)))
3945 stat
.lport
= stat
.iface
= iface
;
3950 stat
.state
= SS_CLOSE
;
3952 if (packet_stats_print(&stat
, f
))
3958 static int packet_show(struct filter
*f
)
3963 if (!filter_af_get(f
, AF_PACKET
) || !(f
->states
& (1 << SS_CLOSE
)))
3966 if (!getenv("PROC_NET_PACKET") && !getenv("PROC_ROOT") &&
3967 packet_show_netlink(f
) == 0)
3970 if ((fp
= net_packet_open()) == NULL
)
3972 if (generic_record_read(fp
, packet_show_line
, f
, AF_PACKET
))
3979 static int netlink_show_one(struct filter
*f
,
3980 int prot
, int pid
, unsigned int groups
,
3981 int state
, int dst_pid
, unsigned int dst_group
,
3983 unsigned long long sk
, unsigned long long cb
)
3985 struct sockstat st
= {
3989 .local
.family
= AF_NETLINK
,
3990 .remote
.family
= AF_NETLINK
,
3993 SPRINT_BUF(prot_buf
) = {};
3994 const char *prot_name
;
3995 char procname
[64] = {};
4000 st
.local
.data
[0] = prot
;
4001 if (run_ssfilter(f
->f
, &st
) == 0)
4005 sock_state_print(&st
);
4007 if (resolve_services
)
4008 prot_name
= nl_proto_n2a(prot
, prot_buf
, sizeof(prot_buf
));
4010 prot_name
= int_to_str(prot
, prot_buf
);
4014 } else if (resolve_services
) {
4019 strncpy(procname
, "kernel", 6);
4020 } else if (pid
> 0) {
4023 snprintf(procname
, sizeof(procname
), "%s/%d/stat",
4024 getenv("PROC_ROOT") ? : "/proc", pid
);
4025 if ((fp
= fopen(procname
, "r")) != NULL
) {
4026 if (fscanf(fp
, "%*d (%[^)])", procname
) == 1) {
4027 snprintf(procname
+strlen(procname
),
4028 sizeof(procname
)-strlen(procname
),
4036 int_to_str(pid
, procname
);
4038 int_to_str(pid
, procname
);
4041 sock_addr_print(prot_name
, ":", procname
, NULL
);
4043 if (state
== NETLINK_CONNECTED
) {
4044 char dst_group_buf
[30];
4045 char dst_pid_buf
[30];
4047 sock_addr_print(int_to_str(dst_group
, dst_group_buf
), ":",
4048 int_to_str(dst_pid
, dst_pid_buf
), NULL
);
4050 sock_addr_print("", "*", "", NULL
);
4053 char *pid_context
= NULL
;
4055 if (show_proc_ctx
) {
4056 /* The pid value will either be:
4057 * 0 if destination kernel - show kernel initial context.
4058 * A valid process pid - use getpidcon.
4059 * A unique value allocated by the kernel or netlink user
4060 * to the process - show context as "not available".
4063 security_get_initial_context("kernel", &pid_context
);
4065 getpidcon(pid
, &pid_context
);
4067 out(" proc_ctx=%s", pid_context
? : "unavailable");
4072 out(" sk=%llx cb=%llx groups=0x%08x", sk
, cb
, groups
);
4078 static int netlink_show_sock(const struct sockaddr_nl
*addr
,
4079 struct nlmsghdr
*nlh
, void *arg
)
4081 struct filter
*f
= (struct filter
*)arg
;
4082 struct netlink_diag_msg
*r
= NLMSG_DATA(nlh
);
4083 struct rtattr
*tb
[NETLINK_DIAG_MAX
+1];
4085 unsigned long groups
= 0;
4087 parse_rtattr(tb
, NETLINK_DIAG_MAX
, (struct rtattr
*)(r
+1),
4088 nlh
->nlmsg_len
- NLMSG_LENGTH(sizeof(*r
)));
4090 if (tb
[NETLINK_DIAG_GROUPS
] && RTA_PAYLOAD(tb
[NETLINK_DIAG_GROUPS
]))
4091 groups
= *(unsigned long *) RTA_DATA(tb
[NETLINK_DIAG_GROUPS
]);
4093 if (tb
[NETLINK_DIAG_MEMINFO
]) {
4094 const __u32
*skmeminfo
;
4096 skmeminfo
= RTA_DATA(tb
[NETLINK_DIAG_MEMINFO
]);
4098 rq
= skmeminfo
[SK_MEMINFO_RMEM_ALLOC
];
4099 wq
= skmeminfo
[SK_MEMINFO_WMEM_ALLOC
];
4102 if (netlink_show_one(f
, r
->ndiag_protocol
, r
->ndiag_portid
, groups
,
4103 r
->ndiag_state
, r
->ndiag_dst_portid
, r
->ndiag_dst_group
,
4110 print_skmeminfo(tb
, NETLINK_DIAG_MEMINFO
);
4116 static int netlink_show_netlink(struct filter
*f
)
4118 DIAG_REQUEST(req
, struct netlink_diag_req r
);
4120 req
.r
.sdiag_family
= AF_NETLINK
;
4121 req
.r
.sdiag_protocol
= NDIAG_PROTO_ALL
;
4122 req
.r
.ndiag_show
= NDIAG_SHOW_GROUPS
| NDIAG_SHOW_MEMINFO
;
4124 return handle_netlink_request(f
, &req
.nlh
, sizeof(req
), netlink_show_sock
);
4127 static int netlink_show(struct filter
*f
)
4132 unsigned int groups
;
4134 unsigned long long sk
, cb
;
4136 if (!filter_af_get(f
, AF_NETLINK
) || !(f
->states
& (1 << SS_CLOSE
)))
4139 if (!getenv("PROC_NET_NETLINK") && !getenv("PROC_ROOT") &&
4140 netlink_show_netlink(f
) == 0)
4143 if ((fp
= net_netlink_open()) == NULL
)
4145 if (!fgets(buf
, sizeof(buf
), fp
)) {
4150 while (fgets(buf
, sizeof(buf
), fp
)) {
4151 sscanf(buf
, "%llx %d %d %x %d %d %llx %d",
4153 &prot
, &pid
, &groups
, &rq
, &wq
, &cb
, &rc
);
4155 netlink_show_one(f
, prot
, pid
, groups
, 0, 0, 0, rq
, wq
, sk
, cb
);
4162 static bool vsock_type_skip(struct sockstat
*s
, struct filter
*f
)
4164 if (s
->type
== SOCK_STREAM
&& !(f
->dbs
& (1 << VSOCK_ST_DB
)))
4166 if (s
->type
== SOCK_DGRAM
&& !(f
->dbs
& (1 << VSOCK_DG_DB
)))
4171 static void vsock_addr_print(inet_prefix
*a
, __u32 port
)
4173 char cid_str
[sizeof("4294967295")];
4174 char port_str
[sizeof("4294967295")];
4177 memcpy(&cid
, a
->data
, sizeof(cid
));
4179 if (cid
== ~(__u32
)0)
4180 snprintf(cid_str
, sizeof(cid_str
), "*");
4182 snprintf(cid_str
, sizeof(cid_str
), "%u", cid
);
4184 if (port
== ~(__u32
)0)
4185 snprintf(port_str
, sizeof(port_str
), "*");
4187 snprintf(port_str
, sizeof(port_str
), "%u", port
);
4189 sock_addr_print(cid_str
, ":", port_str
, NULL
);
4192 static void vsock_stats_print(struct sockstat
*s
, struct filter
*f
)
4194 sock_state_print(s
);
4196 vsock_addr_print(&s
->local
, s
->lport
);
4197 vsock_addr_print(&s
->remote
, s
->rport
);
4202 static int vsock_show_sock(const struct sockaddr_nl
*addr
,
4203 struct nlmsghdr
*nlh
, void *arg
)
4205 struct filter
*f
= (struct filter
*)arg
;
4206 struct vsock_diag_msg
*r
= NLMSG_DATA(nlh
);
4207 struct sockstat stat
= {
4208 .type
= r
->vdiag_type
,
4209 .lport
= r
->vdiag_src_port
,
4210 .rport
= r
->vdiag_dst_port
,
4211 .state
= r
->vdiag_state
,
4212 .ino
= r
->vdiag_ino
,
4215 vsock_set_inet_prefix(&stat
.local
, r
->vdiag_src_cid
);
4216 vsock_set_inet_prefix(&stat
.remote
, r
->vdiag_dst_cid
);
4218 if (vsock_type_skip(&stat
, f
))
4221 if (f
->f
&& run_ssfilter(f
->f
, &stat
) == 0)
4224 vsock_stats_print(&stat
, f
);
4229 static int vsock_show(struct filter
*f
)
4231 DIAG_REQUEST(req
, struct vsock_diag_req r
);
4233 if (!filter_af_get(f
, AF_VSOCK
))
4236 req
.r
.sdiag_family
= AF_VSOCK
;
4237 req
.r
.vdiag_states
= f
->states
;
4239 return handle_netlink_request(f
, &req
.nlh
, sizeof(req
), vsock_show_sock
);
4242 struct sock_diag_msg
{
4246 static int generic_show_sock(const struct sockaddr_nl
*addr
,
4247 struct nlmsghdr
*nlh
, void *arg
)
4249 struct sock_diag_msg
*r
= NLMSG_DATA(nlh
);
4250 struct inet_diag_arg inet_arg
= { .f
= arg
, .protocol
= IPPROTO_MAX
};
4252 switch (r
->sdiag_family
) {
4255 return show_one_inet_sock(addr
, nlh
, &inet_arg
);
4257 return unix_show_sock(addr
, nlh
, arg
);
4259 return packet_show_sock(addr
, nlh
, arg
);
4261 return netlink_show_sock(addr
, nlh
, arg
);
4263 return vsock_show_sock(addr
, nlh
, arg
);
4269 static int handle_follow_request(struct filter
*f
)
4273 struct rtnl_handle rth
;
4275 if (f
->families
& FAMILY_MASK(AF_INET
) && f
->dbs
& (1 << TCP_DB
))
4276 groups
|= 1 << (SKNLGRP_INET_TCP_DESTROY
- 1);
4277 if (f
->families
& FAMILY_MASK(AF_INET
) && f
->dbs
& (1 << UDP_DB
))
4278 groups
|= 1 << (SKNLGRP_INET_UDP_DESTROY
- 1);
4279 if (f
->families
& FAMILY_MASK(AF_INET6
) && f
->dbs
& (1 << TCP_DB
))
4280 groups
|= 1 << (SKNLGRP_INET6_TCP_DESTROY
- 1);
4281 if (f
->families
& FAMILY_MASK(AF_INET6
) && f
->dbs
& (1 << UDP_DB
))
4282 groups
|= 1 << (SKNLGRP_INET6_UDP_DESTROY
- 1);
4287 if (rtnl_open_byproto(&rth
, groups
, NETLINK_SOCK_DIAG
))
4291 rth
.local
.nl_pid
= 0;
4293 if (rtnl_dump_filter(&rth
, generic_show_sock
, f
))
4300 static int get_snmp_int(char *proto
, char *key
, int *result
)
4304 int protolen
= strlen(proto
);
4305 int keylen
= strlen(key
);
4309 if ((fp
= net_snmp_open()) == NULL
)
4312 while (fgets(buf
, sizeof(buf
), fp
) != NULL
) {
4316 if (memcmp(buf
, proto
, protolen
))
4318 while ((p
= strchr(p
, ' ')) != NULL
) {
4321 if (memcmp(p
, key
, keylen
) == 0 &&
4322 (p
[keylen
] == ' ' || p
[keylen
] == '\n'))
4325 if (fgets(buf
, sizeof(buf
), fp
) == NULL
)
4327 if (memcmp(buf
, proto
, protolen
))
4330 while ((p
= strchr(p
, ' ')) != NULL
) {
4333 sscanf(p
, "%d", result
);
4346 /* Get stats from sockstat */
4366 static void get_sockstat_line(char *line
, struct ssummary
*s
)
4368 char id
[256], rem
[256];
4370 if (sscanf(line
, "%[^ ] %[^\n]\n", id
, rem
) != 2)
4373 if (strcmp(id
, "sockets:") == 0)
4374 sscanf(rem
, "%*s%d", &s
->socks
);
4375 else if (strcmp(id
, "UDP:") == 0)
4376 sscanf(rem
, "%*s%d", &s
->udp4
);
4377 else if (strcmp(id
, "UDP6:") == 0)
4378 sscanf(rem
, "%*s%d", &s
->udp6
);
4379 else if (strcmp(id
, "RAW:") == 0)
4380 sscanf(rem
, "%*s%d", &s
->raw4
);
4381 else if (strcmp(id
, "RAW6:") == 0)
4382 sscanf(rem
, "%*s%d", &s
->raw6
);
4383 else if (strcmp(id
, "TCP6:") == 0)
4384 sscanf(rem
, "%*s%d", &s
->tcp6_hashed
);
4385 else if (strcmp(id
, "FRAG:") == 0)
4386 sscanf(rem
, "%*s%d%*s%d", &s
->frag4
, &s
->frag4_mem
);
4387 else if (strcmp(id
, "FRAG6:") == 0)
4388 sscanf(rem
, "%*s%d%*s%d", &s
->frag6
, &s
->frag6_mem
);
4389 else if (strcmp(id
, "TCP:") == 0)
4390 sscanf(rem
, "%*s%d%*s%d%*s%d%*s%d%*s%d",
4392 &s
->tcp_orphans
, &s
->tcp_tws
, &s
->tcp_total
, &s
->tcp_mem
);
4395 static int get_sockstat(struct ssummary
*s
)
4400 memset(s
, 0, sizeof(*s
));
4402 if ((fp
= net_sockstat_open()) == NULL
)
4404 while (fgets(buf
, sizeof(buf
), fp
) != NULL
)
4405 get_sockstat_line(buf
, s
);
4408 if ((fp
= net_sockstat6_open()) == NULL
)
4410 while (fgets(buf
, sizeof(buf
), fp
) != NULL
)
4411 get_sockstat_line(buf
, s
);
4417 static int print_summary(void)
4422 if (get_sockstat(&s
) < 0)
4423 perror("ss: get_sockstat");
4424 if (get_snmp_int("Tcp:", "CurrEstab", &tcp_estab
) < 0)
4425 perror("ss: get_snmpstat");
4427 get_slabstat(&slabstat
);
4429 printf("Total: %d (kernel %d)\n", s
.socks
, slabstat
.socks
);
4431 printf("TCP: %d (estab %d, closed %d, orphaned %d, synrecv %d, timewait %d/%d), ports %d\n",
4432 s
.tcp_total
+ slabstat
.tcp_syns
+ s
.tcp_tws
,
4434 s
.tcp_total
- (s
.tcp4_hashed
+s
.tcp6_hashed
-s
.tcp_tws
),
4437 s
.tcp_tws
, slabstat
.tcp_tws
,
4442 printf("Transport Total IP IPv6\n");
4443 printf("* %-9d %-9s %-9s\n", slabstat
.socks
, "-", "-");
4444 printf("RAW %-9d %-9d %-9d\n", s
.raw4
+s
.raw6
, s
.raw4
, s
.raw6
);
4445 printf("UDP %-9d %-9d %-9d\n", s
.udp4
+s
.udp6
, s
.udp4
, s
.udp6
);
4446 printf("TCP %-9d %-9d %-9d\n", s
.tcp4_hashed
+s
.tcp6_hashed
, s
.tcp4_hashed
, s
.tcp6_hashed
);
4447 printf("INET %-9d %-9d %-9d\n",
4448 s
.raw4
+s
.udp4
+s
.tcp4_hashed
+
4449 s
.raw6
+s
.udp6
+s
.tcp6_hashed
,
4450 s
.raw4
+s
.udp4
+s
.tcp4_hashed
,
4451 s
.raw6
+s
.udp6
+s
.tcp6_hashed
);
4452 printf("FRAG %-9d %-9d %-9d\n", s
.frag4
+s
.frag6
, s
.frag4
, s
.frag6
);
4459 static void _usage(FILE *dest
)
4462 "Usage: ss [ OPTIONS ]\n"
4463 " ss [ OPTIONS ] [ FILTER ]\n"
4464 " -h, --help this message\n"
4465 " -V, --version output version information\n"
4466 " -n, --numeric don't resolve service names\n"
4467 " -r, --resolve resolve host names\n"
4468 " -a, --all display all sockets\n"
4469 " -l, --listening display listening sockets\n"
4470 " -o, --options show timer information\n"
4471 " -e, --extended show detailed socket information\n"
4472 " -m, --memory show socket memory usage\n"
4473 " -p, --processes show process using socket\n"
4474 " -i, --info show internal TCP information\n"
4475 " -s, --summary show socket usage summary\n"
4476 " -b, --bpf show bpf filter socket information\n"
4477 " -E, --events continually display sockets as they are destroyed\n"
4478 " -Z, --context display process SELinux security contexts\n"
4479 " -z, --contexts display process and socket SELinux security contexts\n"
4480 " -N, --net switch to the specified network namespace name\n"
4482 " -4, --ipv4 display only IP version 4 sockets\n"
4483 " -6, --ipv6 display only IP version 6 sockets\n"
4484 " -0, --packet display PACKET sockets\n"
4485 " -t, --tcp display only TCP sockets\n"
4486 " -S, --sctp display only SCTP sockets\n"
4487 " -u, --udp display only UDP sockets\n"
4488 " -d, --dccp display only DCCP sockets\n"
4489 " -w, --raw display only RAW sockets\n"
4490 " -x, --unix display only Unix domain sockets\n"
4491 " --vsock display only vsock sockets\n"
4492 " -f, --family=FAMILY display sockets of type FAMILY\n"
4493 " FAMILY := {inet|inet6|link|unix|netlink|vsock|help}\n"
4495 " -K, --kill forcibly close sockets, display what was closed\n"
4496 " -H, --no-header Suppress header line\n"
4498 " -A, --query=QUERY, --socket=QUERY\n"
4499 " QUERY := {all|inet|tcp|udp|raw|unix|unix_dgram|unix_stream|unix_seqpacket|packet|netlink|vsock_stream|vsock_dgram}[,QUERY]\n"
4501 " -D, --diag=FILE Dump raw information about TCP sockets to FILE\n"
4502 " -F, --filter=FILE read filter information from FILE\n"
4503 " FILTER := [ state STATE-FILTER ] [ EXPRESSION ]\n"
4504 " STATE-FILTER := {all|connected|synchronized|bucket|big|TCP-STATES}\n"
4505 " TCP-STATES := {established|syn-sent|syn-recv|fin-wait-{1,2}|time-wait|closed|close-wait|last-ack|listening|closing}\n"
4506 " connected := {established|syn-sent|syn-recv|fin-wait-{1,2}|time-wait|close-wait|last-ack|closing}\n"
4507 " synchronized := {established|syn-recv|fin-wait-{1,2}|time-wait|close-wait|last-ack|closing}\n"
4508 " bucket := {syn-recv|time-wait}\n"
4509 " big := {established|syn-sent|fin-wait-{1,2}|closed|close-wait|last-ack|listening|closing}\n"
4513 static void help(void) __attribute__((noreturn
));
4514 static void help(void)
4520 static void usage(void) __attribute__((noreturn
));
4521 static void usage(void)
4528 static int scan_state(const char *state
)
4530 static const char * const sstate_namel
[] = {
4532 [SS_ESTABLISHED
] = "established",
4533 [SS_SYN_SENT
] = "syn-sent",
4534 [SS_SYN_RECV
] = "syn-recv",
4535 [SS_FIN_WAIT1
] = "fin-wait-1",
4536 [SS_FIN_WAIT2
] = "fin-wait-2",
4537 [SS_TIME_WAIT
] = "time-wait",
4538 [SS_CLOSE
] = "unconnected",
4539 [SS_CLOSE_WAIT
] = "close-wait",
4540 [SS_LAST_ACK
] = "last-ack",
4541 [SS_LISTEN
] = "listening",
4542 [SS_CLOSING
] = "closing",
4546 if (strcasecmp(state
, "close") == 0 ||
4547 strcasecmp(state
, "closed") == 0)
4548 return (1<<SS_CLOSE
);
4549 if (strcasecmp(state
, "syn-rcv") == 0)
4550 return (1<<SS_SYN_RECV
);
4551 if (strcasecmp(state
, "established") == 0)
4552 return (1<<SS_ESTABLISHED
);
4553 if (strcasecmp(state
, "all") == 0)
4555 if (strcasecmp(state
, "connected") == 0)
4556 return SS_ALL
& ~((1<<SS_CLOSE
)|(1<<SS_LISTEN
));
4557 if (strcasecmp(state
, "synchronized") == 0)
4558 return SS_ALL
& ~((1<<SS_CLOSE
)|(1<<SS_LISTEN
)|(1<<SS_SYN_SENT
));
4559 if (strcasecmp(state
, "bucket") == 0)
4560 return (1<<SS_SYN_RECV
)|(1<<SS_TIME_WAIT
);
4561 if (strcasecmp(state
, "big") == 0)
4562 return SS_ALL
& ~((1<<SS_SYN_RECV
)|(1<<SS_TIME_WAIT
));
4563 for (i
= 0; i
< SS_MAX
; i
++) {
4564 if (strcasecmp(state
, sstate_namel
[i
]) == 0)
4568 fprintf(stderr
, "ss: wrong state name: %s\n", state
);
4572 /* Values 'v' and 'V' are already used so a non-character is used */
4573 #define OPT_VSOCK 256
4575 static const struct option long_opts
[] = {
4576 { "numeric", 0, 0, 'n' },
4577 { "resolve", 0, 0, 'r' },
4578 { "options", 0, 0, 'o' },
4579 { "extended", 0, 0, 'e' },
4580 { "memory", 0, 0, 'm' },
4581 { "info", 0, 0, 'i' },
4582 { "processes", 0, 0, 'p' },
4583 { "bpf", 0, 0, 'b' },
4584 { "events", 0, 0, 'E' },
4585 { "dccp", 0, 0, 'd' },
4586 { "tcp", 0, 0, 't' },
4587 { "sctp", 0, 0, 'S' },
4588 { "udp", 0, 0, 'u' },
4589 { "raw", 0, 0, 'w' },
4590 { "unix", 0, 0, 'x' },
4591 { "vsock", 0, 0, OPT_VSOCK
},
4592 { "all", 0, 0, 'a' },
4593 { "listening", 0, 0, 'l' },
4594 { "ipv4", 0, 0, '4' },
4595 { "ipv6", 0, 0, '6' },
4596 { "packet", 0, 0, '0' },
4597 { "family", 1, 0, 'f' },
4598 { "socket", 1, 0, 'A' },
4599 { "query", 1, 0, 'A' },
4600 { "summary", 0, 0, 's' },
4601 { "diag", 1, 0, 'D' },
4602 { "filter", 1, 0, 'F' },
4603 { "version", 0, 0, 'V' },
4604 { "help", 0, 0, 'h' },
4605 { "context", 0, 0, 'Z' },
4606 { "contexts", 0, 0, 'z' },
4607 { "net", 1, 0, 'N' },
4608 { "kill", 0, 0, 'K' },
4609 { "no-header", 0, 0, 'H' },
4614 int main(int argc
, char *argv
[])
4619 const char *dump_tcpdiag
= NULL
;
4620 FILE *filter_fp
= NULL
;
4622 int state_filter
= 0;
4623 int screen_width
= 80;
4625 while ((ch
= getopt_long(argc
, argv
,
4626 "dhaletuwxnro460spbEf:miA:D:F:vVzZN:KHS",
4627 long_opts
, NULL
)) != EOF
) {
4630 resolve_services
= 0;
4650 user_ent_hash_build();
4660 filter_db_set(¤t_filter
, DCCP_DB
);
4663 filter_db_set(¤t_filter
, TCP_DB
);
4666 filter_db_set(¤t_filter
, SCTP_DB
);
4669 filter_db_set(¤t_filter
, UDP_DB
);
4672 filter_db_set(¤t_filter
, RAW_DB
);
4675 filter_af_set(¤t_filter
, AF_UNIX
);
4678 filter_af_set(¤t_filter
, AF_VSOCK
);
4681 state_filter
= SS_ALL
;
4684 state_filter
= (1 << SS_LISTEN
) | (1 << SS_CLOSE
);
4687 filter_af_set(¤t_filter
, AF_INET
);
4690 filter_af_set(¤t_filter
, AF_INET6
);
4693 filter_af_set(¤t_filter
, AF_PACKET
);
4696 if (strcmp(optarg
, "inet") == 0)
4697 filter_af_set(¤t_filter
, AF_INET
);
4698 else if (strcmp(optarg
, "inet6") == 0)
4699 filter_af_set(¤t_filter
, AF_INET6
);
4700 else if (strcmp(optarg
, "link") == 0)
4701 filter_af_set(¤t_filter
, AF_PACKET
);
4702 else if (strcmp(optarg
, "unix") == 0)
4703 filter_af_set(¤t_filter
, AF_UNIX
);
4704 else if (strcmp(optarg
, "netlink") == 0)
4705 filter_af_set(¤t_filter
, AF_NETLINK
);
4706 else if (strcmp(optarg
, "vsock") == 0)
4707 filter_af_set(¤t_filter
, AF_VSOCK
);
4708 else if (strcmp(optarg
, "help") == 0)
4711 fprintf(stderr
, "ss: \"%s\" is invalid family\n",
4721 current_filter
.dbs
= 0;
4722 state_filter
= state_filter
?
4723 state_filter
: SS_CONN
;
4729 if ((p1
= strchr(p
, ',')) != NULL
)
4731 if (strcmp(p
, "all") == 0) {
4732 filter_default_dbs(¤t_filter
);
4733 } else if (strcmp(p
, "inet") == 0) {
4734 filter_db_set(¤t_filter
, UDP_DB
);
4735 filter_db_set(¤t_filter
, DCCP_DB
);
4736 filter_db_set(¤t_filter
, TCP_DB
);
4737 filter_db_set(¤t_filter
, SCTP_DB
);
4738 filter_db_set(¤t_filter
, RAW_DB
);
4739 } else if (strcmp(p
, "udp") == 0) {
4740 filter_db_set(¤t_filter
, UDP_DB
);
4741 } else if (strcmp(p
, "dccp") == 0) {
4742 filter_db_set(¤t_filter
, DCCP_DB
);
4743 } else if (strcmp(p
, "tcp") == 0) {
4744 filter_db_set(¤t_filter
, TCP_DB
);
4745 } else if (strcmp(p
, "sctp") == 0) {
4746 filter_db_set(¤t_filter
, SCTP_DB
);
4747 } else if (strcmp(p
, "raw") == 0) {
4748 filter_db_set(¤t_filter
, RAW_DB
);
4749 } else if (strcmp(p
, "unix") == 0) {
4750 filter_db_set(¤t_filter
, UNIX_ST_DB
);
4751 filter_db_set(¤t_filter
, UNIX_DG_DB
);
4752 filter_db_set(¤t_filter
, UNIX_SQ_DB
);
4753 } else if (strcasecmp(p
, "unix_stream") == 0 ||
4754 strcmp(p
, "u_str") == 0) {
4755 filter_db_set(¤t_filter
, UNIX_ST_DB
);
4756 } else if (strcasecmp(p
, "unix_dgram") == 0 ||
4757 strcmp(p
, "u_dgr") == 0) {
4758 filter_db_set(¤t_filter
, UNIX_DG_DB
);
4759 } else if (strcasecmp(p
, "unix_seqpacket") == 0 ||
4760 strcmp(p
, "u_seq") == 0) {
4761 filter_db_set(¤t_filter
, UNIX_SQ_DB
);
4762 } else if (strcmp(p
, "packet") == 0) {
4763 filter_db_set(¤t_filter
, PACKET_R_DB
);
4764 filter_db_set(¤t_filter
, PACKET_DG_DB
);
4765 } else if (strcmp(p
, "packet_raw") == 0 ||
4766 strcmp(p
, "p_raw") == 0) {
4767 filter_db_set(¤t_filter
, PACKET_R_DB
);
4768 } else if (strcmp(p
, "packet_dgram") == 0 ||
4769 strcmp(p
, "p_dgr") == 0) {
4770 filter_db_set(¤t_filter
, PACKET_DG_DB
);
4771 } else if (strcmp(p
, "netlink") == 0) {
4772 filter_db_set(¤t_filter
, NETLINK_DB
);
4773 } else if (strcmp(p
, "vsock") == 0) {
4774 filter_db_set(¤t_filter
, VSOCK_ST_DB
);
4775 filter_db_set(¤t_filter
, VSOCK_DG_DB
);
4776 } else if (strcmp(p
, "vsock_stream") == 0 ||
4777 strcmp(p
, "v_str") == 0) {
4778 filter_db_set(¤t_filter
, VSOCK_ST_DB
);
4779 } else if (strcmp(p
, "vsock_dgram") == 0 ||
4780 strcmp(p
, "v_dgr") == 0) {
4781 filter_db_set(¤t_filter
, VSOCK_DG_DB
);
4783 fprintf(stderr
, "ss: \"%s\" is illegal socket table id\n", p
);
4794 dump_tcpdiag
= optarg
;
4798 fprintf(stderr
, "More than one filter file\n");
4801 if (optarg
[0] == '-')
4804 filter_fp
= fopen(optarg
, "r");
4806 perror("fopen filter file");
4812 printf("ss utility, iproute2-ss%s\n", SNAPSHOT
);
4818 if (is_selinux_enabled() <= 0) {
4819 fprintf(stderr
, "ss: SELinux is not enabled.\n");
4823 user_ent_hash_build();
4826 if (netns_switch(optarg
))
4830 current_filter
.kill
= 1;
4848 if (do_default
&& argc
== 0)
4853 if (strcmp(*argv
, "state") == 0) {
4857 state_filter
|= scan_state(*argv
);
4859 } else if (strcmp(*argv
, "exclude") == 0 ||
4860 strcmp(*argv
, "excl") == 0) {
4863 state_filter
= SS_ALL
;
4864 state_filter
&= ~scan_state(*argv
);
4873 state_filter
= state_filter
? state_filter
: SS_CONN
;
4874 filter_default_dbs(¤t_filter
);
4877 filter_states_set(¤t_filter
, state_filter
);
4878 filter_merge_defaults(¤t_filter
);
4880 if (resolve_services
&& resolve_hosts
&&
4881 (current_filter
.dbs
& (UNIX_DBM
|INET_L4_DBM
)))
4882 init_service_resolver();
4884 if (current_filter
.dbs
== 0) {
4885 fprintf(stderr
, "ss: no socket tables to show with such filter.\n");
4888 if (current_filter
.families
== 0) {
4889 fprintf(stderr
, "ss: no families to show with such filter.\n");
4892 if (current_filter
.states
== 0) {
4893 fprintf(stderr
, "ss: no socket states to show with such filter.\n");
4898 FILE *dump_fp
= stdout
;
4900 if (!(current_filter
.dbs
& (1<<TCP_DB
))) {
4901 fprintf(stderr
, "ss: tcpdiag dump requested and no tcp in filter.\n");
4904 if (dump_tcpdiag
[0] != '-') {
4905 dump_fp
= fopen(dump_tcpdiag
, "w");
4906 if (!dump_tcpdiag
) {
4907 perror("fopen dump file");
4911 inet_show_netlink(¤t_filter
, dump_fp
, IPPROTO_TCP
);
4916 if (ssfilter_parse(¤t_filter
.f
, argc
, argv
, filter_fp
))
4919 if (!(current_filter
.dbs
& (current_filter
.dbs
- 1)))
4920 columns
[COL_NETID
].disabled
= 1;
4922 if (!(current_filter
.states
& (current_filter
.states
- 1)))
4923 columns
[COL_STATE
].disabled
= 1;
4925 if (isatty(STDOUT_FILENO
)) {
4928 if (ioctl(STDOUT_FILENO
, TIOCGWINSZ
, &w
) != -1) {
4930 screen_width
= w
.ws_col
;
4940 exit(handle_follow_request(¤t_filter
));
4942 if (current_filter
.dbs
& (1<<NETLINK_DB
))
4943 netlink_show(¤t_filter
);
4944 if (current_filter
.dbs
& PACKET_DBM
)
4945 packet_show(¤t_filter
);
4946 if (current_filter
.dbs
& UNIX_DBM
)
4947 unix_show(¤t_filter
);
4948 if (current_filter
.dbs
& (1<<RAW_DB
))
4949 raw_show(¤t_filter
);
4950 if (current_filter
.dbs
& (1<<UDP_DB
))
4951 udp_show(¤t_filter
);
4952 if (current_filter
.dbs
& (1<<TCP_DB
))
4953 tcp_show(¤t_filter
);
4954 if (current_filter
.dbs
& (1<<DCCP_DB
))
4955 dccp_show(¤t_filter
);
4956 if (current_filter
.dbs
& (1<<SCTP_DB
))
4957 sctp_show(¤t_filter
);
4958 if (current_filter
.dbs
& VSOCK_DBM
)
4959 vsock_show(¤t_filter
);
4961 if (show_users
|| show_proc_ctx
|| show_sock_ctx
)
4964 render(screen_width
);