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
;
795 unsigned int lastsnd
;
796 unsigned int lastrcv
;
797 unsigned int lastack
;
799 double pacing_rate_max
;
800 double delivery_rate
;
801 unsigned long long bytes_acked
;
802 unsigned long long bytes_received
;
803 unsigned int segs_out
;
804 unsigned int segs_in
;
805 unsigned int data_segs_out
;
806 unsigned int data_segs_in
;
807 unsigned int unacked
;
808 unsigned int retrans
;
809 unsigned int retrans_total
;
812 unsigned int fackets
;
813 unsigned int reordering
;
814 unsigned int not_sent
;
818 unsigned int rcv_ssthresh
;
819 unsigned long long busy_time
;
820 unsigned long long rwnd_limited
;
821 unsigned long long sndbuf_limited
;
825 bool has_ecnseen_opt
;
826 bool has_fastopen_opt
;
829 struct dctcpstat
*dctcp
;
830 struct tcp_bbr_info
*bbr_info
;
833 /* SCTP assocs share the same inode number with their parent endpoint. So if we
834 * have seen the inode number before, it must be an assoc instead of the next
836 static bool is_sctp_assoc(struct sockstat
*s
, const char *sock_name
)
838 if (strcmp(sock_name
, "sctp"))
840 if (!sctp_ino
|| sctp_ino
!= s
->ino
)
845 static const char *unix_netid_name(int type
)
858 static const char *proto_name(int protocol
)
878 static const char *vsock_netid_name(int type
)
890 /* Allocate and initialize a new buffer chunk */
891 static struct buf_chunk
*buf_chunk_new(void)
893 struct buf_chunk
*new = malloc(BUF_CHUNK
);
900 /* This is also the last block */
903 /* Next token will be stored at the beginning of chunk data area, and
904 * its initial length is zero.
906 buffer
.cur
= (struct buf_token
*)new->data
;
909 new->end
= buffer
.cur
->data
;
914 /* Return available tail room in given chunk */
915 static int buf_chunk_avail(struct buf_chunk
*chunk
)
917 return BUF_CHUNK
- offsetof(struct buf_chunk
, data
) -
918 (chunk
->end
- chunk
->data
);
921 /* Update end pointer and token length, link new chunk if we hit the end of the
922 * current one. Return -EAGAIN if we got a new chunk, caller has to print again.
924 static int buf_update(int len
)
926 struct buf_chunk
*chunk
= buffer
.tail
;
927 struct buf_token
*t
= buffer
.cur
;
929 /* Claim success if new content fits in the current chunk, and anyway
930 * if this is the first token in the chunk: in the latter case,
931 * allocating a new chunk won't help, so we'll just cut the output.
933 if ((len
< buf_chunk_avail(chunk
) && len
!= -1 /* glibc < 2.0.6 */) ||
934 t
== (struct buf_token
*)chunk
->data
) {
935 len
= min(len
, buf_chunk_avail(chunk
));
937 /* Total field length can't exceed 2^16 bytes, cut as needed */
938 len
= min(len
, USHRT_MAX
- t
->len
);
945 /* Content truncated, time to allocate more */
946 chunk
->next
= buf_chunk_new();
948 /* Copy current token over to new chunk, including length descriptor */
949 memcpy(chunk
->next
->data
, t
, sizeof(t
->len
) + t
->len
);
950 chunk
->next
->end
+= t
->len
;
952 /* Discard partially written field in old chunk */
953 chunk
->end
-= t
->len
+ sizeof(t
->len
);
958 /* Append content to buffer as part of the current field */
959 static void out(const char *fmt
, ...)
961 struct column
*f
= current_field
;
970 buffer
.head
= buf_chunk_new();
972 again
: /* Append to buffer: if we have a new chunk, print again */
974 pos
= buffer
.cur
->data
+ buffer
.cur
->len
;
977 /* Limit to tail room. If we hit the limit, buf_update() will tell us */
978 len
= vsnprintf(pos
, buf_chunk_avail(buffer
.tail
), fmt
, args
);
985 static int print_left_spacing(struct column
*f
, int stored
, int printed
)
989 if (!f
->width
|| f
->align
== ALIGN_LEFT
)
992 s
= f
->width
- stored
- printed
;
993 if (f
->align
== ALIGN_CENTER
)
994 /* If count of total spacing is odd, shift right by one */
998 return printf("%*c", s
, ' ');
1003 static void print_right_spacing(struct column
*f
, int printed
)
1007 if (!f
->width
|| f
->align
== ALIGN_RIGHT
)
1010 s
= f
->width
- printed
;
1011 if (f
->align
== ALIGN_CENTER
)
1015 printf("%*c", s
, ' ');
1018 /* Done with field: update buffer pointer, start new token after current one */
1019 static void field_flush(struct column
*f
)
1021 struct buf_chunk
*chunk
= buffer
.tail
;
1022 unsigned int pad
= buffer
.cur
->len
% 2;
1027 if (buffer
.cur
->len
> f
->max_len
)
1028 f
->max_len
= buffer
.cur
->len
;
1030 /* We need a new chunk if we can't store the next length descriptor.
1031 * Mind the gap between end of previous token and next aligned position
1032 * for length descriptor.
1034 if (buf_chunk_avail(chunk
) - pad
< sizeof(buffer
.cur
->len
)) {
1036 chunk
->next
= buf_chunk_new();
1040 buffer
.cur
= (struct buf_token
*)(buffer
.cur
->data
+
1041 LEN_ALIGN(buffer
.cur
->len
));
1042 buffer
.cur
->len
= 0;
1043 buffer
.tail
->end
= buffer
.cur
->data
;
1046 static int field_is_last(struct column
*f
)
1048 return f
- columns
== COL_MAX
- 1;
1051 static void field_next(void)
1053 field_flush(current_field
);
1055 if (field_is_last(current_field
))
1056 current_field
= columns
;
1061 /* Walk through fields and flush them until we reach the desired one */
1062 static void field_set(enum col_id id
)
1064 while (id
!= current_field
- columns
)
1068 /* Print header for all non-empty columns */
1069 static void print_header(void)
1071 while (!field_is_last(current_field
)) {
1072 if (!current_field
->disabled
)
1073 out(current_field
->header
);
1078 /* Get the next available token in the buffer starting from the current token */
1079 static struct buf_token
*buf_token_next(struct buf_token
*cur
)
1081 struct buf_chunk
*chunk
= buffer
.tail
;
1083 /* If we reached the end of chunk contents, get token from next chunk */
1084 if (cur
->data
+ LEN_ALIGN(cur
->len
) == chunk
->end
) {
1085 buffer
.tail
= chunk
= chunk
->next
;
1086 return chunk
? (struct buf_token
*)chunk
->data
: NULL
;
1089 return (struct buf_token
*)(cur
->data
+ LEN_ALIGN(cur
->len
));
1092 /* Free up all allocated buffer chunks */
1093 static void buf_free_all(void)
1095 struct buf_chunk
*tmp
;
1097 for (buffer
.tail
= buffer
.head
; buffer
.tail
; ) {
1099 buffer
.tail
= buffer
.tail
->next
;
1105 /* Calculate column width from contents length. If columns don't fit on one
1106 * line, break them into the least possible amount of lines and keep them
1107 * aligned across lines. Available screen space is equally spread between fields
1108 * as additional spacing.
1110 static void render_calc_width(int screen_width
)
1112 int first
, len
= 0, linecols
= 0;
1113 struct column
*c
, *eol
= columns
- 1;
1115 /* First pass: set width for each column to measured content length */
1116 for (first
= 1, c
= columns
; c
- columns
< COL_MAX
; c
++) {
1120 if (!first
&& c
->max_len
)
1121 c
->width
= c
->max_len
+ strlen(c
->ldelim
);
1123 c
->width
= c
->max_len
;
1125 /* But don't exceed screen size. If we exceed the screen size
1126 * for even a single field, it will just start on a line of its
1127 * own and then naturally wrap.
1129 c
->width
= min(c
->width
, screen_width
);
1135 /* Second pass: find out newlines and distribute available spacing */
1136 for (c
= columns
; c
- columns
< COL_MAX
; c
++) {
1137 int pad
, spacing
, rem
, last
;
1146 for (last
= 1, tmp
= c
+ 1; tmp
- columns
< COL_MAX
; tmp
++) {
1153 if (!last
&& len
< screen_width
) {
1154 /* Columns fit on screen so far, nothing to do yet */
1158 if (len
== screen_width
) {
1159 /* Exact fit, just start with new line */
1163 if (len
> screen_width
) {
1164 /* Screen width exceeded: go back one column */
1170 /* Distribute remaining space to columns on this line */
1171 pad
= screen_width
- len
;
1172 spacing
= pad
/ linecols
;
1173 rem
= pad
% linecols
;
1174 for (tmp
= c
; tmp
> eol
; tmp
--) {
1178 tmp
->width
+= spacing
;
1186 /* Line break: reset line counters, mark end-of-line */
1193 /* Render buffered output with spacing and delimiters, then free up buffers */
1194 static void render(int screen_width
)
1196 struct buf_token
*token
= (struct buf_token
*)buffer
.head
->data
;
1197 int printed
, line_started
= 0;
1200 /* Ensure end alignment of last token, it wasn't necessarily flushed */
1201 buffer
.tail
->end
+= buffer
.cur
->len
% 2;
1203 render_calc_width(screen_width
);
1205 /* Rewind and replay */
1206 buffer
.tail
= buffer
.head
;
1213 /* Print left delimiter only if we already started a line */
1215 printed
= printf("%s", current_field
->ldelim
);
1219 /* Print field content from token data with spacing */
1220 printed
+= print_left_spacing(f
, token
->len
, printed
);
1221 printed
+= fwrite(token
->data
, 1, token
->len
, stdout
);
1222 print_right_spacing(f
, printed
);
1224 /* Go to next non-empty field, deal with end-of-line */
1226 if (field_is_last(f
)) {
1233 } while (f
->disabled
);
1235 token
= buf_token_next(token
);
1241 static void sock_state_print(struct sockstat
*s
)
1243 const char *sock_name
;
1244 static const char * const sstate_name
[] = {
1246 [SS_ESTABLISHED
] = "ESTAB",
1247 [SS_SYN_SENT
] = "SYN-SENT",
1248 [SS_SYN_RECV
] = "SYN-RECV",
1249 [SS_FIN_WAIT1
] = "FIN-WAIT-1",
1250 [SS_FIN_WAIT2
] = "FIN-WAIT-2",
1251 [SS_TIME_WAIT
] = "TIME-WAIT",
1252 [SS_CLOSE
] = "UNCONN",
1253 [SS_CLOSE_WAIT
] = "CLOSE-WAIT",
1254 [SS_LAST_ACK
] = "LAST-ACK",
1255 [SS_LISTEN
] = "LISTEN",
1256 [SS_CLOSING
] = "CLOSING",
1259 switch (s
->local
.family
) {
1261 sock_name
= unix_netid_name(s
->type
);
1265 sock_name
= proto_name(s
->type
);
1268 sock_name
= s
->type
== SOCK_RAW
? "p_raw" : "p_dgr";
1274 sock_name
= vsock_netid_name(s
->type
);
1277 sock_name
= "unknown";
1280 if (is_sctp_assoc(s
, sock_name
)) {
1281 field_set(COL_STATE
); /* Empty Netid field */
1282 out("`- %s", sctp_sstate_name
[s
->state
]);
1284 field_set(COL_NETID
);
1285 out("%s", sock_name
);
1286 field_set(COL_STATE
);
1287 out("%s", sstate_name
[s
->state
]);
1290 field_set(COL_RECVQ
);
1292 field_set(COL_SENDQ
);
1294 field_set(COL_ADDR
);
1297 static void sock_details_print(struct sockstat
*s
)
1300 out(" uid:%u", s
->uid
);
1302 out(" ino:%u", s
->ino
);
1303 out(" sk:%llx", s
->sk
);
1306 out(" fwmark:0x%x", s
->mark
);
1309 static void sock_addr_print(const char *addr
, char *delim
, const char *port
,
1313 out("%s" "%%" "%s%s", addr
, ifname
, delim
);
1315 out("%s%s", addr
, delim
);
1322 static const char *print_ms_timer(unsigned int timeout
)
1324 static char buf
[64];
1325 int secs
, msecs
, minutes
;
1327 secs
= timeout
/1000;
1330 msecs
= timeout
%1000;
1334 snprintf(buf
, sizeof(buf
)-16, "%dmin", minutes
);
1341 sprintf(buf
+strlen(buf
), "%d%s", secs
, msecs
? "." : "sec");
1344 sprintf(buf
+strlen(buf
), "%03dms", msecs
);
1349 struct scache
*next
;
1355 struct scache
*rlist
;
1357 static void init_service_resolver(void)
1360 FILE *fp
= popen("/usr/sbin/rpcinfo -p 2>/dev/null", "r");
1365 if (!fgets(buf
, sizeof(buf
), fp
)) {
1369 while (fgets(buf
, sizeof(buf
), fp
) != NULL
) {
1370 unsigned int progn
, port
;
1371 char proto
[128], prog
[128] = "rpc.";
1374 if (sscanf(buf
, "%u %*d %s %u %s",
1375 &progn
, proto
, &port
, prog
+4) != 4)
1378 if (!(c
= malloc(sizeof(*c
))))
1382 c
->name
= strdup(prog
);
1383 if (strcmp(proto
, TCP_PROTO
) == 0)
1384 c
->proto
= TCP_PROTO
;
1385 else if (strcmp(proto
, UDP_PROTO
) == 0)
1386 c
->proto
= UDP_PROTO
;
1387 else if (strcmp(proto
, SCTP_PROTO
) == 0)
1388 c
->proto
= SCTP_PROTO
;
1397 /* Even do not try default linux ephemeral port ranges:
1398 * default /etc/services contains so much of useless crap
1399 * wouldbe "allocated" to this area that resolution
1400 * is really harmful. I shrug each time when seeing
1401 * "socks" or "cfinger" in dumps.
1403 static int is_ephemeral(int port
)
1405 static int min
= 0, max
;
1408 FILE *f
= ephemeral_ports_open();
1410 if (!f
|| fscanf(f
, "%d %d", &min
, &max
) < 2) {
1417 return port
>= min
&& port
<= max
;
1421 static const char *__resolve_service(int port
)
1425 for (c
= rlist
; c
; c
= c
->next
) {
1426 if (c
->port
== port
&& c
->proto
== dg_proto
)
1430 if (!is_ephemeral(port
)) {
1431 static int notfirst
;
1438 se
= getservbyport(htons(port
), dg_proto
);
1446 #define SCACHE_BUCKETS 1024
1447 static struct scache
*cache_htab
[SCACHE_BUCKETS
];
1449 static const char *resolve_service(int port
)
1451 static char buf
[128];
1462 if (!resolve_services
)
1465 if (dg_proto
== RAW_PROTO
)
1466 return inet_proto_n2a(port
, buf
, sizeof(buf
));
1469 hash
= (port
^(((unsigned long)dg_proto
)>>2)) % SCACHE_BUCKETS
;
1471 for (c
= cache_htab
[hash
]; c
; c
= c
->next
) {
1472 if (c
->port
== port
&& c
->proto
== dg_proto
)
1476 c
= malloc(sizeof(*c
));
1479 res
= __resolve_service(port
);
1481 c
->name
= res
? strdup(res
) : NULL
;
1482 c
->proto
= dg_proto
;
1483 c
->next
= cache_htab
[hash
];
1484 cache_htab
[hash
] = c
;
1491 sprintf(buf
, "%u", port
);
1495 static void inet_addr_print(const inet_prefix
*a
, int port
,
1496 unsigned int ifindex
, bool v6only
)
1499 const char *ap
= buf
;
1500 const char *ifname
= NULL
;
1502 if (a
->family
== AF_INET
) {
1503 ap
= format_host(AF_INET
, 4, a
->data
);
1506 !memcmp(a
->data
, &in6addr_any
, sizeof(in6addr_any
))) {
1510 ap
= format_host(a
->family
, 16, a
->data
);
1512 /* Numeric IPv6 addresses should be bracketed */
1513 if (strchr(ap
, ':')) {
1514 snprintf(buf
, sizeof(buf
),
1522 ifname
= ll_index_to_name(ifindex
);
1524 sock_addr_print(ap
, ":", resolve_service(port
), ifname
);
1533 struct aafilter
*next
;
1536 static int inet2_addr_match(const inet_prefix
*a
, const inet_prefix
*p
,
1539 if (!inet_addr_match(a
, p
, plen
))
1542 /* Cursed "v4 mapped" addresses: v4 mapped socket matches
1543 * pure IPv4 rule, but v4-mapped rule selects only v4-mapped
1545 if (p
->family
== AF_INET
&& a
->family
== AF_INET6
) {
1546 if (a
->data
[0] == 0 && a
->data
[1] == 0 &&
1547 a
->data
[2] == htonl(0xffff)) {
1548 inet_prefix tmp
= *a
;
1550 tmp
.data
[0] = a
->data
[3];
1551 return inet_addr_match(&tmp
, p
, plen
);
1557 static int unix_match(const inet_prefix
*a
, const inet_prefix
*p
)
1559 char *addr
, *pattern
;
1561 memcpy(&addr
, a
->data
, sizeof(addr
));
1562 memcpy(&pattern
, p
->data
, sizeof(pattern
));
1563 if (pattern
== NULL
)
1567 return !fnmatch(pattern
, addr
, 0);
1570 static int run_ssfilter(struct ssfilter
*f
, struct sockstat
*s
)
1575 if (s
->local
.family
== AF_UNIX
) {
1578 memcpy(&p
, s
->local
.data
, sizeof(p
));
1579 return p
== NULL
|| (p
[0] == '@' && strlen(p
) == 6 &&
1580 strspn(p
+1, "0123456789abcdef") == 5);
1582 if (s
->local
.family
== AF_PACKET
)
1583 return s
->lport
== 0 && s
->local
.data
[0] == 0;
1584 if (s
->local
.family
== AF_NETLINK
)
1585 return s
->lport
< 0;
1586 if (s
->local
.family
== AF_VSOCK
)
1587 return s
->lport
> 1023;
1589 return is_ephemeral(s
->lport
);
1593 struct aafilter
*a
= (void *)f
->pred
;
1595 if (a
->addr
.family
== AF_UNIX
)
1596 return unix_match(&s
->remote
, &a
->addr
);
1597 if (a
->port
!= -1 && a
->port
!= s
->rport
)
1599 if (a
->addr
.bitlen
) {
1601 if (!inet2_addr_match(&s
->remote
, &a
->addr
, a
->addr
.bitlen
))
1603 } while ((a
= a
->next
) != NULL
);
1610 struct aafilter
*a
= (void *)f
->pred
;
1612 if (a
->addr
.family
== AF_UNIX
)
1613 return unix_match(&s
->local
, &a
->addr
);
1614 if (a
->port
!= -1 && a
->port
!= s
->lport
)
1616 if (a
->addr
.bitlen
) {
1618 if (!inet2_addr_match(&s
->local
, &a
->addr
, a
->addr
.bitlen
))
1620 } while ((a
= a
->next
) != NULL
);
1627 struct aafilter
*a
= (void *)f
->pred
;
1629 return s
->rport
>= a
->port
;
1633 struct aafilter
*a
= (void *)f
->pred
;
1635 return s
->rport
<= a
->port
;
1639 struct aafilter
*a
= (void *)f
->pred
;
1641 return s
->lport
>= a
->port
;
1645 struct aafilter
*a
= (void *)f
->pred
;
1647 return s
->lport
<= a
->port
;
1651 struct aafilter
*a
= (void *)f
->pred
;
1653 return s
->iface
== a
->iface
;
1657 struct aafilter
*a
= (void *)f
->pred
;
1659 return (s
->mark
& a
->mask
) == a
->mark
;
1661 /* Yup. It is recursion. Sorry. */
1663 return run_ssfilter(f
->pred
, s
) && run_ssfilter(f
->post
, s
);
1665 return run_ssfilter(f
->pred
, s
) || run_ssfilter(f
->post
, s
);
1667 return !run_ssfilter(f
->pred
, s
);
1673 /* Relocate external jumps by reloc. */
1674 static void ssfilter_patch(char *a
, int len
, int reloc
)
1677 struct inet_diag_bc_op
*op
= (struct inet_diag_bc_op
*)a
;
1679 if (op
->no
== len
+4)
1688 static int ssfilter_bytecompile(struct ssfilter
*f
, char **bytecode
)
1693 if (!(*bytecode
= malloc(4))) abort();
1694 ((struct inet_diag_bc_op
*)*bytecode
)[0] = (struct inet_diag_bc_op
){ INET_DIAG_BC_AUTO
, 4, 8 };
1700 struct aafilter
*a
= (void *)f
->pred
;
1703 int code
= (f
->type
== SSF_DCOND
? INET_DIAG_BC_D_COND
: INET_DIAG_BC_S_COND
);
1706 for (b
= a
; b
; b
= b
->next
) {
1707 len
+= 4 + sizeof(struct inet_diag_hostcond
);
1708 if (a
->addr
.family
== AF_INET6
)
1715 if (!(ptr
= malloc(len
))) abort();
1717 for (b
= a
; b
; b
= b
->next
) {
1718 struct inet_diag_bc_op
*op
= (struct inet_diag_bc_op
*)ptr
;
1719 int alen
= (a
->addr
.family
== AF_INET6
? 16 : 4);
1720 int oplen
= alen
+ 4 + sizeof(struct inet_diag_hostcond
);
1721 struct inet_diag_hostcond
*cond
= (struct inet_diag_hostcond
*)(ptr
+4);
1723 *op
= (struct inet_diag_bc_op
){ code
, oplen
, oplen
+4 };
1724 cond
->family
= a
->addr
.family
;
1725 cond
->port
= a
->port
;
1726 cond
->prefix_len
= a
->addr
.bitlen
;
1727 memcpy(cond
->addr
, a
->addr
.data
, alen
);
1730 op
= (struct inet_diag_bc_op
*)ptr
;
1731 *op
= (struct inet_diag_bc_op
){ INET_DIAG_BC_JMP
, 4, len
- (ptr
-*bytecode
)};
1735 return ptr
- *bytecode
;
1739 struct aafilter
*x
= (void *)f
->pred
;
1741 if (!(*bytecode
= malloc(8))) abort();
1742 ((struct inet_diag_bc_op
*)*bytecode
)[0] = (struct inet_diag_bc_op
){ INET_DIAG_BC_D_GE
, 8, 12 };
1743 ((struct inet_diag_bc_op
*)*bytecode
)[1] = (struct inet_diag_bc_op
){ 0, 0, x
->port
};
1748 struct aafilter
*x
= (void *)f
->pred
;
1750 if (!(*bytecode
= malloc(8))) abort();
1751 ((struct inet_diag_bc_op
*)*bytecode
)[0] = (struct inet_diag_bc_op
){ INET_DIAG_BC_D_LE
, 8, 12 };
1752 ((struct inet_diag_bc_op
*)*bytecode
)[1] = (struct inet_diag_bc_op
){ 0, 0, x
->port
};
1757 struct aafilter
*x
= (void *)f
->pred
;
1759 if (!(*bytecode
= malloc(8))) abort();
1760 ((struct inet_diag_bc_op
*)*bytecode
)[0] = (struct inet_diag_bc_op
){ INET_DIAG_BC_S_GE
, 8, 12 };
1761 ((struct inet_diag_bc_op
*)*bytecode
)[1] = (struct inet_diag_bc_op
){ 0, 0, x
->port
};
1766 struct aafilter
*x
= (void *)f
->pred
;
1768 if (!(*bytecode
= malloc(8))) abort();
1769 ((struct inet_diag_bc_op
*)*bytecode
)[0] = (struct inet_diag_bc_op
){ INET_DIAG_BC_S_LE
, 8, 12 };
1770 ((struct inet_diag_bc_op
*)*bytecode
)[1] = (struct inet_diag_bc_op
){ 0, 0, x
->port
};
1776 char *a1
= NULL
, *a2
= NULL
, *a
;
1779 l1
= ssfilter_bytecompile(f
->pred
, &a1
);
1780 l2
= ssfilter_bytecompile(f
->post
, &a2
);
1786 if (!(a
= malloc(l1
+l2
))) abort();
1788 memcpy(a
+l1
, a2
, l2
);
1790 ssfilter_patch(a
, l1
, l2
);
1796 char *a1
= NULL
, *a2
= NULL
, *a
;
1799 l1
= ssfilter_bytecompile(f
->pred
, &a1
);
1800 l2
= ssfilter_bytecompile(f
->post
, &a2
);
1806 if (!(a
= malloc(l1
+l2
+4))) abort();
1808 memcpy(a
+l1
+4, a2
, l2
);
1810 *(struct inet_diag_bc_op
*)(a
+l1
) = (struct inet_diag_bc_op
){ INET_DIAG_BC_JMP
, 4, l2
+4 };
1816 char *a1
= NULL
, *a
;
1819 l1
= ssfilter_bytecompile(f
->pred
, &a1
);
1824 if (!(a
= malloc(l1
+4))) abort();
1827 *(struct inet_diag_bc_op
*)(a
+l1
) = (struct inet_diag_bc_op
){ INET_DIAG_BC_JMP
, 4, 8 };
1833 /* bytecompile for SSF_DEVCOND not supported yet */
1838 struct aafilter
*a
= (void *)f
->pred
;
1840 struct inet_diag_bc_op op
;
1841 struct inet_diag_markcond cond
;
1843 int inslen
= sizeof(struct instr
);
1845 if (!(*bytecode
= malloc(inslen
))) abort();
1846 ((struct instr
*)*bytecode
)[0] = (struct instr
) {
1847 { INET_DIAG_BC_MARK_COND
, inslen
, inslen
+ 4 },
1848 { a
->mark
, a
->mask
},
1858 static int remember_he(struct aafilter
*a
, struct hostent
*he
)
1860 char **ptr
= he
->h_addr_list
;
1864 if (he
->h_addrtype
== AF_INET
)
1866 else if (he
->h_addrtype
== AF_INET6
)
1872 struct aafilter
*b
= a
;
1874 if (a
->addr
.bitlen
) {
1875 if ((b
= malloc(sizeof(*b
))) == NULL
)
1880 memcpy(b
->addr
.data
, *ptr
, len
);
1881 b
->addr
.bytelen
= len
;
1882 b
->addr
.bitlen
= len
*8;
1883 b
->addr
.family
= he
->h_addrtype
;
1890 static int get_dns_host(struct aafilter
*a
, const char *addr
, int fam
)
1892 static int notfirst
;
1901 he
= gethostbyname2(addr
, fam
== AF_UNSPEC
? AF_INET
: fam
);
1903 cnt
= remember_he(a
, he
);
1904 if (fam
== AF_UNSPEC
) {
1905 he
= gethostbyname2(addr
, AF_INET6
);
1907 cnt
+= remember_he(a
, he
);
1912 static int xll_initted
;
1914 static void xll_init(void)
1916 struct rtnl_handle rth
;
1918 if (rtnl_open(&rth
, 0) < 0)
1926 static const char *xll_index_to_name(int index
)
1930 return ll_index_to_name(index
);
1933 static int xll_name_to_index(const char *dev
)
1937 return ll_name_to_index(dev
);
1940 void *parse_devcond(char *name
)
1942 struct aafilter a
= { .iface
= 0 };
1943 struct aafilter
*res
;
1945 a
.iface
= xll_name_to_index(name
);
1950 n
= strtoul(name
, &end
, 0);
1951 if (!end
|| end
== name
|| *end
|| n
> UINT_MAX
)
1957 res
= malloc(sizeof(*res
));
1963 static void vsock_set_inet_prefix(inet_prefix
*a
, __u32 cid
)
1966 .bytelen
= sizeof(cid
),
1969 memcpy(a
->data
, &cid
, sizeof(cid
));
1972 void *parse_hostcond(char *addr
, bool is_port
)
1975 struct aafilter a
= { .port
= -1 };
1976 struct aafilter
*res
;
1977 int fam
= preferred_family
;
1978 struct filter
*f
= ¤t_filter
;
1980 if (fam
== AF_UNIX
|| strncmp(addr
, "unix:", 5) == 0) {
1983 a
.addr
.family
= AF_UNIX
;
1984 if (strncmp(addr
, "unix:", 5) == 0)
1987 a
.addr
.bitlen
= 8*strlen(p
);
1988 memcpy(a
.addr
.data
, &p
, sizeof(p
));
1993 if (fam
== AF_PACKET
|| strncmp(addr
, "link:", 5) == 0) {
1994 a
.addr
.family
= AF_PACKET
;
1996 if (strncmp(addr
, "link:", 5) == 0)
1998 port
= strchr(addr
, ':');
2001 if (port
[1] && strcmp(port
+1, "*")) {
2002 if (get_integer(&a
.port
, port
+1, 0)) {
2003 if ((a
.port
= xll_name_to_index(port
+1)) <= 0)
2008 if (addr
[0] && strcmp(addr
, "*")) {
2012 if (ll_proto_a2n(&tmp
, addr
))
2014 a
.addr
.data
[0] = ntohs(tmp
);
2020 if (fam
== AF_NETLINK
|| strncmp(addr
, "netlink:", 8) == 0) {
2021 a
.addr
.family
= AF_NETLINK
;
2023 if (strncmp(addr
, "netlink:", 8) == 0)
2025 port
= strchr(addr
, ':');
2028 if (port
[1] && strcmp(port
+1, "*")) {
2029 if (get_integer(&a
.port
, port
+1, 0)) {
2030 if (strcmp(port
+1, "kernel") == 0)
2037 if (addr
[0] && strcmp(addr
, "*")) {
2039 if (nl_proto_a2n(&a
.addr
.data
[0], addr
) == -1)
2046 if (fam
== AF_VSOCK
|| strncmp(addr
, "vsock:", 6) == 0) {
2047 __u32 cid
= ~(__u32
)0;
2049 a
.addr
.family
= AF_VSOCK
;
2050 if (strncmp(addr
, "vsock:", 6) == 0)
2056 port
= strchr(addr
, ':');
2063 if (port
&& strcmp(port
, "*") &&
2064 get_u32((__u32
*)&a
.port
, port
, 0))
2067 if (addr
[0] && strcmp(addr
, "*")) {
2069 if (get_u32(&cid
, addr
, 0))
2072 vsock_set_inet_prefix(&a
.addr
, cid
);
2077 if (fam
== AF_INET
|| !strncmp(addr
, "inet:", 5)) {
2079 if (!strncmp(addr
, "inet:", 5))
2081 } else if (fam
== AF_INET6
|| !strncmp(addr
, "inet6:", 6)) {
2083 if (!strncmp(addr
, "inet6:", 6))
2087 /* URL-like literal [] */
2088 if (addr
[0] == '[') {
2090 if ((port
= strchr(addr
, ']')) == NULL
)
2093 } else if (addr
[0] == '*') {
2096 port
= strrchr(strchr(addr
, '/') ? : addr
, ':');
2102 if (port
&& *port
) {
2106 if (*port
&& *port
!= '*') {
2107 if (get_integer(&a
.port
, port
, 0)) {
2108 struct servent
*se1
= NULL
;
2109 struct servent
*se2
= NULL
;
2111 if (current_filter
.dbs
&(1<<UDP_DB
))
2112 se1
= getservbyname(port
, UDP_PROTO
);
2113 if (current_filter
.dbs
&(1<<TCP_DB
))
2114 se2
= getservbyname(port
, TCP_PROTO
);
2115 if (se1
&& se2
&& se1
->s_port
!= se2
->s_port
) {
2116 fprintf(stderr
, "Error: ambiguous port \"%s\".\n", port
);
2122 a
.port
= ntohs(se1
->s_port
);
2126 for (s
= rlist
; s
; s
= s
->next
) {
2127 if ((s
->proto
== UDP_PROTO
&&
2128 (current_filter
.dbs
&(1<<UDP_DB
))) ||
2129 (s
->proto
== TCP_PROTO
&&
2130 (current_filter
.dbs
&(1<<TCP_DB
)))) {
2131 if (s
->name
&& strcmp(s
->name
, port
) == 0) {
2132 if (a
.port
> 0 && a
.port
!= s
->port
) {
2133 fprintf(stderr
, "Error: ambiguous port \"%s\".\n", port
);
2141 fprintf(stderr
, "Error: \"%s\" does not look like a port.\n", port
);
2148 if (!is_port
&& *addr
&& *addr
!= '*') {
2149 if (get_prefix_1(&a
.addr
, addr
, fam
)) {
2150 if (get_dns_host(&a
, addr
, fam
)) {
2151 fprintf(stderr
, "Error: an inet prefix is expected rather than \"%s\".\n", addr
);
2158 if (fam
!= AF_UNSPEC
) {
2159 int states
= f
->states
;
2161 filter_af_set(f
, fam
);
2162 filter_states_set(f
, states
);
2165 res
= malloc(sizeof(*res
));
2167 memcpy(res
, &a
, sizeof(a
));
2171 void *parse_markmask(const char *markmask
)
2173 struct aafilter a
, *res
;
2175 if (strchr(markmask
, '/')) {
2176 if (sscanf(markmask
, "%i/%i", &a
.mark
, &a
.mask
) != 2)
2179 a
.mask
= 0xffffffff;
2180 if (sscanf(markmask
, "%i", &a
.mark
) != 1)
2184 res
= malloc(sizeof(*res
));
2186 memcpy(res
, &a
, sizeof(a
));
2190 static void proc_ctx_print(struct sockstat
*s
)
2194 if (show_proc_ctx
|| show_sock_ctx
) {
2195 if (find_entry(s
->ino
, &buf
,
2196 (show_proc_ctx
& show_sock_ctx
) ?
2197 PROC_SOCK_CTX
: PROC_CTX
) > 0) {
2198 out(" users:(%s)", buf
);
2201 } else if (show_users
) {
2202 if (find_entry(s
->ino
, &buf
, USERS
) > 0) {
2203 out(" users:(%s)", buf
);
2209 static void inet_stats_print(struct sockstat
*s
, bool v6only
)
2211 sock_state_print(s
);
2213 inet_addr_print(&s
->local
, s
->lport
, s
->iface
, v6only
);
2214 inet_addr_print(&s
->remote
, s
->rport
, 0, v6only
);
2219 static int proc_parse_inet_addr(char *loc
, char *rem
, int family
, struct
2222 s
->local
.family
= s
->remote
.family
= family
;
2223 if (family
== AF_INET
) {
2224 sscanf(loc
, "%x:%x", s
->local
.data
, (unsigned *)&s
->lport
);
2225 sscanf(rem
, "%x:%x", s
->remote
.data
, (unsigned *)&s
->rport
);
2226 s
->local
.bytelen
= s
->remote
.bytelen
= 4;
2229 sscanf(loc
, "%08x%08x%08x%08x:%x",
2235 sscanf(rem
, "%08x%08x%08x%08x:%x",
2241 s
->local
.bytelen
= s
->remote
.bytelen
= 16;
2247 static int proc_inet_split_line(char *line
, char **loc
, char **rem
, char **data
)
2251 if ((p
= strchr(line
, ':')) == NULL
)
2255 if ((p
= strchr(*loc
, ':')) == NULL
)
2260 if ((p
= strchr(*rem
, ':')) == NULL
)
2268 static char *sprint_bw(char *buf
, double bw
)
2271 sprintf(buf
, "%.1fM", bw
/ 1000000.);
2272 else if (bw
> 1000.)
2273 sprintf(buf
, "%.1fK", bw
/ 1000.);
2275 sprintf(buf
, "%g", bw
);
2280 static void sctp_stats_print(struct sctp_info
*s
)
2283 out(" tag:%x", s
->sctpi_tag
);
2285 out(" state:%s", sctp_sstate_name
[s
->sctpi_state
]);
2287 out(" rwnd:%d", s
->sctpi_rwnd
);
2288 if (s
->sctpi_unackdata
)
2289 out(" unackdata:%d", s
->sctpi_unackdata
);
2290 if (s
->sctpi_penddata
)
2291 out(" penddata:%d", s
->sctpi_penddata
);
2292 if (s
->sctpi_instrms
)
2293 out(" instrms:%d", s
->sctpi_instrms
);
2294 if (s
->sctpi_outstrms
)
2295 out(" outstrms:%d", s
->sctpi_outstrms
);
2296 if (s
->sctpi_inqueue
)
2297 out(" inqueue:%d", s
->sctpi_inqueue
);
2298 if (s
->sctpi_outqueue
)
2299 out(" outqueue:%d", s
->sctpi_outqueue
);
2300 if (s
->sctpi_overall_error
)
2301 out(" overerr:%d", s
->sctpi_overall_error
);
2302 if (s
->sctpi_max_burst
)
2303 out(" maxburst:%d", s
->sctpi_max_burst
);
2304 if (s
->sctpi_maxseg
)
2305 out(" maxseg:%d", s
->sctpi_maxseg
);
2306 if (s
->sctpi_peer_rwnd
)
2307 out(" prwnd:%d", s
->sctpi_peer_rwnd
);
2308 if (s
->sctpi_peer_tag
)
2309 out(" ptag:%x", s
->sctpi_peer_tag
);
2310 if (s
->sctpi_peer_capable
)
2311 out(" pcapable:%d", s
->sctpi_peer_capable
);
2312 if (s
->sctpi_peer_sack
)
2313 out(" psack:%d", s
->sctpi_peer_sack
);
2314 if (s
->sctpi_s_autoclose
)
2315 out(" autoclose:%d", s
->sctpi_s_autoclose
);
2316 if (s
->sctpi_s_adaptation_ind
)
2317 out(" adapind:%d", s
->sctpi_s_adaptation_ind
);
2318 if (s
->sctpi_s_pd_point
)
2319 out(" pdpoint:%d", s
->sctpi_s_pd_point
);
2320 if (s
->sctpi_s_nodelay
)
2321 out(" nodealy:%d", s
->sctpi_s_nodelay
);
2322 if (s
->sctpi_s_disable_fragments
)
2323 out(" nofrag:%d", s
->sctpi_s_disable_fragments
);
2324 if (s
->sctpi_s_v4mapped
)
2325 out(" v4mapped:%d", s
->sctpi_s_v4mapped
);
2326 if (s
->sctpi_s_frag_interleave
)
2327 out(" fraginl:%d", s
->sctpi_s_frag_interleave
);
2330 static void tcp_stats_print(struct tcpstat
*s
)
2336 if (s
->has_sack_opt
)
2340 if (s
->has_ecnseen_opt
)
2342 if (s
->has_fastopen_opt
)
2345 out(" %s", s
->cong_alg
);
2346 if (s
->has_wscale_opt
)
2347 out(" wscale:%d,%d", s
->snd_wscale
, s
->rcv_wscale
);
2349 out(" rto:%g", s
->rto
);
2351 out(" backoff:%u", s
->backoff
);
2353 out(" rtt:%g/%g", s
->rtt
, s
->rttvar
);
2355 out(" ato:%g", s
->ato
);
2358 out(" qack:%d", s
->qack
);
2363 out(" mss:%d", s
->mss
);
2365 out(" pmtu:%u", s
->pmtu
);
2367 out(" rcvmss:%d", s
->rcv_mss
);
2369 out(" advmss:%d", s
->advmss
);
2371 out(" cwnd:%u", s
->cwnd
);
2373 out(" ssthresh:%d", s
->ssthresh
);
2376 out(" bytes_acked:%llu", s
->bytes_acked
);
2377 if (s
->bytes_received
)
2378 out(" bytes_received:%llu", s
->bytes_received
);
2380 out(" segs_out:%u", s
->segs_out
);
2382 out(" segs_in:%u", s
->segs_in
);
2383 if (s
->data_segs_out
)
2384 out(" data_segs_out:%u", s
->data_segs_out
);
2385 if (s
->data_segs_in
)
2386 out(" data_segs_in:%u", s
->data_segs_in
);
2388 if (s
->dctcp
&& s
->dctcp
->enabled
) {
2389 struct dctcpstat
*dctcp
= s
->dctcp
;
2391 out(" dctcp:(ce_state:%u,alpha:%u,ab_ecn:%u,ab_tot:%u)",
2392 dctcp
->ce_state
, dctcp
->alpha
, dctcp
->ab_ecn
,
2394 } else if (s
->dctcp
) {
2395 out(" dctcp:fallback_mode");
2401 bw
= s
->bbr_info
->bbr_bw_hi
;
2403 bw
|= s
->bbr_info
->bbr_bw_lo
;
2405 out(" bbr:(bw:%sbps,mrtt:%g",
2406 sprint_bw(b1
, bw
* 8.0),
2407 (double)s
->bbr_info
->bbr_min_rtt
/ 1000.0);
2408 if (s
->bbr_info
->bbr_pacing_gain
)
2409 out(",pacing_gain:%g",
2410 (double)s
->bbr_info
->bbr_pacing_gain
/ 256.0);
2411 if (s
->bbr_info
->bbr_cwnd_gain
)
2412 out(",cwnd_gain:%g",
2413 (double)s
->bbr_info
->bbr_cwnd_gain
/ 256.0);
2418 out(" send %sbps", sprint_bw(b1
, s
->send_bps
));
2420 out(" lastsnd:%u", s
->lastsnd
);
2422 out(" lastrcv:%u", s
->lastrcv
);
2424 out(" lastack:%u", s
->lastack
);
2426 if (s
->pacing_rate
) {
2427 out(" pacing_rate %sbps", sprint_bw(b1
, s
->pacing_rate
));
2428 if (s
->pacing_rate_max
)
2429 out("/%sbps", sprint_bw(b1
, s
->pacing_rate_max
));
2432 if (s
->delivery_rate
)
2433 out(" delivery_rate %sbps", sprint_bw(b1
, s
->delivery_rate
));
2435 out(" app_limited");
2438 out(" busy:%llums", s
->busy_time
/ 1000);
2439 if (s
->rwnd_limited
)
2440 out(" rwnd_limited:%llums(%.1f%%)",
2441 s
->rwnd_limited
/ 1000,
2442 100.0 * s
->rwnd_limited
/ s
->busy_time
);
2443 if (s
->sndbuf_limited
)
2444 out(" sndbuf_limited:%llums(%.1f%%)",
2445 s
->sndbuf_limited
/ 1000,
2446 100.0 * s
->sndbuf_limited
/ s
->busy_time
);
2450 out(" unacked:%u", s
->unacked
);
2451 if (s
->retrans
|| s
->retrans_total
)
2452 out(" retrans:%u/%u", s
->retrans
, s
->retrans_total
);
2454 out(" lost:%u", s
->lost
);
2455 if (s
->sacked
&& s
->ss
.state
!= SS_LISTEN
)
2456 out(" sacked:%u", s
->sacked
);
2458 out(" fackets:%u", s
->fackets
);
2459 if (s
->reordering
!= 3)
2460 out(" reordering:%d", s
->reordering
);
2462 out(" rcv_rtt:%g", s
->rcv_rtt
);
2464 out(" rcv_space:%d", s
->rcv_space
);
2465 if (s
->rcv_ssthresh
)
2466 out(" rcv_ssthresh:%u", s
->rcv_ssthresh
);
2468 out(" notsent:%u", s
->not_sent
);
2470 out(" minrtt:%g", s
->min_rtt
);
2473 static void tcp_timer_print(struct tcpstat
*s
)
2475 static const char * const tmr_name
[] = {
2487 out(" timer:(%s,%s,%d)",
2489 print_ms_timer(s
->timeout
),
2494 static void sctp_timer_print(struct tcpstat
*s
)
2497 out(" timer:(T3_RTX,%s,%d)",
2498 print_ms_timer(s
->timeout
), s
->retrans
);
2501 static int tcp_show_line(char *line
, const struct filter
*f
, int family
)
2503 int rto
= 0, ato
= 0;
2504 struct tcpstat s
= {};
2505 char *loc
, *rem
, *data
;
2508 int hz
= get_user_hz();
2510 if (proc_inet_split_line(line
, &loc
, &rem
, &data
))
2513 int state
= (data
[1] >= 'A') ? (data
[1] - 'A' + 10) : (data
[1] - '0');
2515 if (!(f
->states
& (1 << state
)))
2518 proc_parse_inet_addr(loc
, rem
, family
, &s
.ss
);
2520 if (f
->f
&& run_ssfilter(f
->f
, &s
.ss
) == 0)
2524 n
= sscanf(data
, "%x %x:%x %x:%x %x %d %d %u %d %llx %d %d %d %u %d %[^\n]\n",
2525 &s
.ss
.state
, &s
.ss
.wq
, &s
.ss
.rq
,
2526 &s
.timer
, &s
.timeout
, &s
.retrans
, &s
.ss
.uid
, &s
.probes
,
2527 &s
.ss
.ino
, &s
.ss
.refcnt
, &s
.ss
.sk
, &rto
, &ato
, &s
.qack
, &s
.cwnd
,
2540 s
.retrans
= s
.timer
!= 1 ? s
.probes
: s
.retrans
;
2541 s
.timeout
= (s
.timeout
* 1000 + hz
- 1) / hz
;
2542 s
.ato
= (double)ato
/ hz
;
2544 s
.rto
= (double)rto
;
2545 s
.ssthresh
= s
.ssthresh
== -1 ? 0 : s
.ssthresh
;
2546 s
.rto
= s
.rto
!= 3 * hz
? s
.rto
/ hz
: 0;
2547 s
.ss
.type
= IPPROTO_TCP
;
2549 inet_stats_print(&s
.ss
, false);
2552 tcp_timer_print(&s
);
2555 sock_details_print(&s
.ss
);
2557 out(" opt:\"%s\"", opt
);
2561 tcp_stats_print(&s
);
2566 static int generic_record_read(FILE *fp
,
2567 int (*worker
)(char*, const struct filter
*, int),
2568 const struct filter
*f
, int fam
)
2573 if (fgets(line
, sizeof(line
), fp
) == NULL
)
2576 while (fgets(line
, sizeof(line
), fp
) != NULL
) {
2577 int n
= strlen(line
);
2579 if (n
== 0 || line
[n
-1] != '\n') {
2585 if (worker(line
, f
, fam
) < 0)
2590 return ferror(fp
) ? -1 : 0;
2593 static void print_skmeminfo(struct rtattr
*tb
[], int attrtype
)
2595 const __u32
*skmeminfo
;
2597 if (!tb
[attrtype
]) {
2598 if (attrtype
== INET_DIAG_SKMEMINFO
) {
2599 if (!tb
[INET_DIAG_MEMINFO
])
2602 const struct inet_diag_meminfo
*minfo
=
2603 RTA_DATA(tb
[INET_DIAG_MEMINFO
]);
2605 out(" mem:(r%u,w%u,f%u,t%u)",
2614 skmeminfo
= RTA_DATA(tb
[attrtype
]);
2616 out(" skmem:(r%u,rb%u,t%u,tb%u,f%u,w%u,o%u",
2617 skmeminfo
[SK_MEMINFO_RMEM_ALLOC
],
2618 skmeminfo
[SK_MEMINFO_RCVBUF
],
2619 skmeminfo
[SK_MEMINFO_WMEM_ALLOC
],
2620 skmeminfo
[SK_MEMINFO_SNDBUF
],
2621 skmeminfo
[SK_MEMINFO_FWD_ALLOC
],
2622 skmeminfo
[SK_MEMINFO_WMEM_QUEUED
],
2623 skmeminfo
[SK_MEMINFO_OPTMEM
]);
2625 if (RTA_PAYLOAD(tb
[attrtype
]) >=
2626 (SK_MEMINFO_BACKLOG
+ 1) * sizeof(__u32
))
2627 out(",bl%u", skmeminfo
[SK_MEMINFO_BACKLOG
]);
2629 if (RTA_PAYLOAD(tb
[attrtype
]) >=
2630 (SK_MEMINFO_DROPS
+ 1) * sizeof(__u32
))
2631 out(",d%u", skmeminfo
[SK_MEMINFO_DROPS
]);
2636 static void print_md5sig(struct tcp_diag_md5sig
*sig
)
2639 format_host(sig
->tcpm_family
,
2640 sig
->tcpm_family
== AF_INET6
? 16 : 4,
2642 sig
->tcpm_prefixlen
);
2643 print_escape_buf(sig
->tcpm_key
, sig
->tcpm_keylen
, " ,");
2646 #define TCPI_HAS_OPT(info, opt) !!(info->tcpi_options & (opt))
2648 static void tcp_show_info(const struct nlmsghdr
*nlh
, struct inet_diag_msg
*r
,
2649 struct rtattr
*tb
[])
2652 struct tcpstat s
= {};
2654 s
.ss
.state
= r
->idiag_state
;
2656 print_skmeminfo(tb
, INET_DIAG_SKMEMINFO
);
2658 if (tb
[INET_DIAG_INFO
]) {
2659 struct tcp_info
*info
;
2660 int len
= RTA_PAYLOAD(tb
[INET_DIAG_INFO
]);
2662 /* workaround for older kernels with less fields */
2663 if (len
< sizeof(*info
)) {
2664 info
= alloca(sizeof(*info
));
2665 memcpy(info
, RTA_DATA(tb
[INET_DIAG_INFO
]), len
);
2666 memset((char *)info
+ len
, 0, sizeof(*info
) - len
);
2668 info
= RTA_DATA(tb
[INET_DIAG_INFO
]);
2671 s
.has_ts_opt
= TCPI_HAS_OPT(info
, TCPI_OPT_TIMESTAMPS
);
2672 s
.has_sack_opt
= TCPI_HAS_OPT(info
, TCPI_OPT_SACK
);
2673 s
.has_ecn_opt
= TCPI_HAS_OPT(info
, TCPI_OPT_ECN
);
2674 s
.has_ecnseen_opt
= TCPI_HAS_OPT(info
, TCPI_OPT_ECN_SEEN
);
2675 s
.has_fastopen_opt
= TCPI_HAS_OPT(info
, TCPI_OPT_SYN_DATA
);
2678 if (tb
[INET_DIAG_CONG
])
2680 rta_getattr_str(tb
[INET_DIAG_CONG
]),
2681 sizeof(s
.cong_alg
) - 1);
2683 if (TCPI_HAS_OPT(info
, TCPI_OPT_WSCALE
)) {
2684 s
.has_wscale_opt
= true;
2685 s
.snd_wscale
= info
->tcpi_snd_wscale
;
2686 s
.rcv_wscale
= info
->tcpi_rcv_wscale
;
2689 if (info
->tcpi_rto
&& info
->tcpi_rto
!= 3000000)
2690 s
.rto
= (double)info
->tcpi_rto
/ 1000;
2692 s
.backoff
= info
->tcpi_backoff
;
2693 s
.rtt
= (double)info
->tcpi_rtt
/ 1000;
2694 s
.rttvar
= (double)info
->tcpi_rttvar
/ 1000;
2695 s
.ato
= (double)info
->tcpi_ato
/ 1000;
2696 s
.mss
= info
->tcpi_snd_mss
;
2697 s
.rcv_mss
= info
->tcpi_rcv_mss
;
2698 s
.advmss
= info
->tcpi_advmss
;
2699 s
.rcv_space
= info
->tcpi_rcv_space
;
2700 s
.rcv_rtt
= (double)info
->tcpi_rcv_rtt
/ 1000;
2701 s
.lastsnd
= info
->tcpi_last_data_sent
;
2702 s
.lastrcv
= info
->tcpi_last_data_recv
;
2703 s
.lastack
= info
->tcpi_last_ack_recv
;
2704 s
.unacked
= info
->tcpi_unacked
;
2705 s
.retrans
= info
->tcpi_retrans
;
2706 s
.retrans_total
= info
->tcpi_total_retrans
;
2707 s
.lost
= info
->tcpi_lost
;
2708 s
.sacked
= info
->tcpi_sacked
;
2709 s
.fackets
= info
->tcpi_fackets
;
2710 s
.reordering
= info
->tcpi_reordering
;
2711 s
.rcv_ssthresh
= info
->tcpi_rcv_ssthresh
;
2712 s
.cwnd
= info
->tcpi_snd_cwnd
;
2713 s
.pmtu
= info
->tcpi_pmtu
;
2715 if (info
->tcpi_snd_ssthresh
< 0xFFFF)
2716 s
.ssthresh
= info
->tcpi_snd_ssthresh
;
2718 rtt
= (double) info
->tcpi_rtt
;
2719 if (tb
[INET_DIAG_VEGASINFO
]) {
2720 const struct tcpvegas_info
*vinfo
2721 = RTA_DATA(tb
[INET_DIAG_VEGASINFO
]);
2723 if (vinfo
->tcpv_enabled
&&
2724 vinfo
->tcpv_rtt
&& vinfo
->tcpv_rtt
!= 0x7fffffff)
2725 rtt
= vinfo
->tcpv_rtt
;
2728 if (tb
[INET_DIAG_DCTCPINFO
]) {
2729 struct dctcpstat
*dctcp
= malloc(sizeof(struct
2732 const struct tcp_dctcp_info
*dinfo
2733 = RTA_DATA(tb
[INET_DIAG_DCTCPINFO
]);
2735 dctcp
->enabled
= !!dinfo
->dctcp_enabled
;
2736 dctcp
->ce_state
= dinfo
->dctcp_ce_state
;
2737 dctcp
->alpha
= dinfo
->dctcp_alpha
;
2738 dctcp
->ab_ecn
= dinfo
->dctcp_ab_ecn
;
2739 dctcp
->ab_tot
= dinfo
->dctcp_ab_tot
;
2743 if (tb
[INET_DIAG_BBRINFO
]) {
2744 const void *bbr_info
= RTA_DATA(tb
[INET_DIAG_BBRINFO
]);
2745 int len
= min(RTA_PAYLOAD(tb
[INET_DIAG_BBRINFO
]),
2746 sizeof(*s
.bbr_info
));
2748 s
.bbr_info
= calloc(1, sizeof(*s
.bbr_info
));
2749 if (s
.bbr_info
&& bbr_info
)
2750 memcpy(s
.bbr_info
, bbr_info
, len
);
2753 if (rtt
> 0 && info
->tcpi_snd_mss
&& info
->tcpi_snd_cwnd
) {
2754 s
.send_bps
= (double) info
->tcpi_snd_cwnd
*
2755 (double)info
->tcpi_snd_mss
* 8000000. / rtt
;
2758 if (info
->tcpi_pacing_rate
&&
2759 info
->tcpi_pacing_rate
!= ~0ULL) {
2760 s
.pacing_rate
= info
->tcpi_pacing_rate
* 8.;
2762 if (info
->tcpi_max_pacing_rate
&&
2763 info
->tcpi_max_pacing_rate
!= ~0ULL)
2764 s
.pacing_rate_max
= info
->tcpi_max_pacing_rate
* 8.;
2766 s
.bytes_acked
= info
->tcpi_bytes_acked
;
2767 s
.bytes_received
= info
->tcpi_bytes_received
;
2768 s
.segs_out
= info
->tcpi_segs_out
;
2769 s
.segs_in
= info
->tcpi_segs_in
;
2770 s
.data_segs_out
= info
->tcpi_data_segs_out
;
2771 s
.data_segs_in
= info
->tcpi_data_segs_in
;
2772 s
.not_sent
= info
->tcpi_notsent_bytes
;
2773 if (info
->tcpi_min_rtt
&& info
->tcpi_min_rtt
!= ~0U)
2774 s
.min_rtt
= (double) info
->tcpi_min_rtt
/ 1000;
2775 s
.delivery_rate
= info
->tcpi_delivery_rate
* 8.;
2776 s
.app_limited
= info
->tcpi_delivery_rate_app_limited
;
2777 s
.busy_time
= info
->tcpi_busy_time
;
2778 s
.rwnd_limited
= info
->tcpi_rwnd_limited
;
2779 s
.sndbuf_limited
= info
->tcpi_sndbuf_limited
;
2780 tcp_stats_print(&s
);
2784 if (tb
[INET_DIAG_MD5SIG
]) {
2785 struct tcp_diag_md5sig
*sig
= RTA_DATA(tb
[INET_DIAG_MD5SIG
]);
2786 int len
= RTA_PAYLOAD(tb
[INET_DIAG_MD5SIG
]);
2789 print_md5sig(sig
++);
2790 for (len
-= sizeof(*sig
); len
> 0; len
-= sizeof(*sig
)) {
2792 print_md5sig(sig
++);
2797 static const char *format_host_sa(struct sockaddr_storage
*sa
)
2800 struct sockaddr_in sin
;
2801 struct sockaddr_in6 sin6
;
2802 } *saddr
= (void *)sa
;
2804 switch (sa
->ss_family
) {
2806 return format_host(AF_INET
, 4, &saddr
->sin
.sin_addr
);
2808 return format_host(AF_INET6
, 16, &saddr
->sin6
.sin6_addr
);
2814 static void sctp_show_info(const struct nlmsghdr
*nlh
, struct inet_diag_msg
*r
,
2815 struct rtattr
*tb
[])
2817 struct sockaddr_storage
*sa
;
2820 print_skmeminfo(tb
, INET_DIAG_SKMEMINFO
);
2822 if (tb
[INET_DIAG_LOCALS
]) {
2823 len
= RTA_PAYLOAD(tb
[INET_DIAG_LOCALS
]);
2824 sa
= RTA_DATA(tb
[INET_DIAG_LOCALS
]);
2826 out("locals:%s", format_host_sa(sa
));
2827 for (sa
++, len
-= sizeof(*sa
); len
> 0; sa
++, len
-= sizeof(*sa
))
2828 out(",%s", format_host_sa(sa
));
2831 if (tb
[INET_DIAG_PEERS
]) {
2832 len
= RTA_PAYLOAD(tb
[INET_DIAG_PEERS
]);
2833 sa
= RTA_DATA(tb
[INET_DIAG_PEERS
]);
2835 out(" peers:%s", format_host_sa(sa
));
2836 for (sa
++, len
-= sizeof(*sa
); len
> 0; sa
++, len
-= sizeof(*sa
))
2837 out(",%s", format_host_sa(sa
));
2839 if (tb
[INET_DIAG_INFO
]) {
2840 struct sctp_info
*info
;
2841 len
= RTA_PAYLOAD(tb
[INET_DIAG_INFO
]);
2843 /* workaround for older kernels with less fields */
2844 if (len
< sizeof(*info
)) {
2845 info
= alloca(sizeof(*info
));
2846 memcpy(info
, RTA_DATA(tb
[INET_DIAG_INFO
]), len
);
2847 memset((char *)info
+ len
, 0, sizeof(*info
) - len
);
2849 info
= RTA_DATA(tb
[INET_DIAG_INFO
]);
2851 sctp_stats_print(info
);
2855 static void parse_diag_msg(struct nlmsghdr
*nlh
, struct sockstat
*s
)
2857 struct rtattr
*tb
[INET_DIAG_MAX
+1];
2858 struct inet_diag_msg
*r
= NLMSG_DATA(nlh
);
2860 parse_rtattr(tb
, INET_DIAG_MAX
, (struct rtattr
*)(r
+1),
2861 nlh
->nlmsg_len
- NLMSG_LENGTH(sizeof(*r
)));
2863 s
->state
= r
->idiag_state
;
2864 s
->local
.family
= s
->remote
.family
= r
->idiag_family
;
2865 s
->lport
= ntohs(r
->id
.idiag_sport
);
2866 s
->rport
= ntohs(r
->id
.idiag_dport
);
2867 s
->wq
= r
->idiag_wqueue
;
2868 s
->rq
= r
->idiag_rqueue
;
2869 s
->ino
= r
->idiag_inode
;
2870 s
->uid
= r
->idiag_uid
;
2871 s
->iface
= r
->id
.idiag_if
;
2872 s
->sk
= cookie_sk_get(&r
->id
.idiag_cookie
[0]);
2875 if (tb
[INET_DIAG_MARK
])
2876 s
->mark
= rta_getattr_u32(tb
[INET_DIAG_MARK
]);
2877 if (tb
[INET_DIAG_PROTOCOL
])
2878 s
->raw_prot
= rta_getattr_u8(tb
[INET_DIAG_PROTOCOL
]);
2882 if (s
->local
.family
== AF_INET
)
2883 s
->local
.bytelen
= s
->remote
.bytelen
= 4;
2885 s
->local
.bytelen
= s
->remote
.bytelen
= 16;
2887 memcpy(s
->local
.data
, r
->id
.idiag_src
, s
->local
.bytelen
);
2888 memcpy(s
->remote
.data
, r
->id
.idiag_dst
, s
->local
.bytelen
);
2891 static int inet_show_sock(struct nlmsghdr
*nlh
,
2894 struct rtattr
*tb
[INET_DIAG_MAX
+1];
2895 struct inet_diag_msg
*r
= NLMSG_DATA(nlh
);
2896 unsigned char v6only
= 0;
2898 parse_rtattr(tb
, INET_DIAG_MAX
, (struct rtattr
*)(r
+1),
2899 nlh
->nlmsg_len
- NLMSG_LENGTH(sizeof(*r
)));
2901 if (tb
[INET_DIAG_PROTOCOL
])
2902 s
->type
= rta_getattr_u8(tb
[INET_DIAG_PROTOCOL
]);
2904 if (s
->local
.family
== AF_INET6
&& tb
[INET_DIAG_SKV6ONLY
])
2905 v6only
= rta_getattr_u8(tb
[INET_DIAG_SKV6ONLY
]);
2907 inet_stats_print(s
, v6only
);
2910 struct tcpstat t
= {};
2912 t
.timer
= r
->idiag_timer
;
2913 t
.timeout
= r
->idiag_expires
;
2914 t
.retrans
= r
->idiag_retrans
;
2915 if (s
->type
== IPPROTO_SCTP
)
2916 sctp_timer_print(&t
);
2918 tcp_timer_print(&t
);
2922 sock_details_print(s
);
2923 if (s
->local
.family
== AF_INET6
&& tb
[INET_DIAG_SKV6ONLY
])
2924 out(" v6only:%u", v6only
);
2926 if (tb
[INET_DIAG_SHUTDOWN
]) {
2929 mask
= rta_getattr_u8(tb
[INET_DIAG_SHUTDOWN
]);
2931 mask
& 1 ? '-' : '<', mask
& 2 ? '-' : '>');
2935 if (show_mem
|| (show_tcpinfo
&& s
->type
!= IPPROTO_UDP
)) {
2937 if (s
->type
== IPPROTO_SCTP
)
2938 sctp_show_info(nlh
, r
, tb
);
2940 tcp_show_info(nlh
, r
, tb
);
2947 static int tcpdiag_send(int fd
, int protocol
, struct filter
*f
)
2949 struct sockaddr_nl nladdr
= { .nl_family
= AF_NETLINK
};
2951 struct nlmsghdr nlh
;
2952 struct inet_diag_req r
;
2954 .nlh
.nlmsg_len
= sizeof(req
),
2955 .nlh
.nlmsg_flags
= NLM_F_ROOT
| NLM_F_MATCH
| NLM_F_REQUEST
,
2956 .nlh
.nlmsg_seq
= MAGIC_SEQ
,
2957 .r
.idiag_family
= AF_INET
,
2958 .r
.idiag_states
= f
->states
,
2964 struct iovec iov
[3];
2967 if (protocol
== IPPROTO_UDP
)
2970 if (protocol
== IPPROTO_TCP
)
2971 req
.nlh
.nlmsg_type
= TCPDIAG_GETSOCK
;
2973 req
.nlh
.nlmsg_type
= DCCPDIAG_GETSOCK
;
2975 req
.r
.idiag_ext
|= (1<<(INET_DIAG_MEMINFO
-1));
2976 req
.r
.idiag_ext
|= (1<<(INET_DIAG_SKMEMINFO
-1));
2980 req
.r
.idiag_ext
|= (1<<(INET_DIAG_INFO
-1));
2981 req
.r
.idiag_ext
|= (1<<(INET_DIAG_VEGASINFO
-1));
2982 req
.r
.idiag_ext
|= (1<<(INET_DIAG_CONG
-1));
2985 iov
[0] = (struct iovec
){
2987 .iov_len
= sizeof(req
)
2990 bclen
= ssfilter_bytecompile(f
->f
, &bc
);
2992 rta
.rta_type
= INET_DIAG_REQ_BYTECODE
;
2993 rta
.rta_len
= RTA_LENGTH(bclen
);
2994 iov
[1] = (struct iovec
){ &rta
, sizeof(rta
) };
2995 iov
[2] = (struct iovec
){ bc
, bclen
};
2996 req
.nlh
.nlmsg_len
+= RTA_LENGTH(bclen
);
3001 msg
= (struct msghdr
) {
3002 .msg_name
= (void *)&nladdr
,
3003 .msg_namelen
= sizeof(nladdr
),
3005 .msg_iovlen
= iovlen
,
3008 if (sendmsg(fd
, &msg
, 0) < 0) {
3016 static int sockdiag_send(int family
, int fd
, int protocol
, struct filter
*f
)
3018 struct sockaddr_nl nladdr
= { .nl_family
= AF_NETLINK
};
3019 DIAG_REQUEST(req
, struct inet_diag_req_v2 r
);
3024 struct iovec iov
[3];
3027 if (family
== PF_UNSPEC
)
3028 return tcpdiag_send(fd
, protocol
, f
);
3030 memset(&req
.r
, 0, sizeof(req
.r
));
3031 req
.r
.sdiag_family
= family
;
3032 req
.r
.sdiag_protocol
= protocol
;
3033 req
.r
.idiag_states
= f
->states
;
3035 req
.r
.idiag_ext
|= (1<<(INET_DIAG_MEMINFO
-1));
3036 req
.r
.idiag_ext
|= (1<<(INET_DIAG_SKMEMINFO
-1));
3040 req
.r
.idiag_ext
|= (1<<(INET_DIAG_INFO
-1));
3041 req
.r
.idiag_ext
|= (1<<(INET_DIAG_VEGASINFO
-1));
3042 req
.r
.idiag_ext
|= (1<<(INET_DIAG_CONG
-1));
3045 iov
[0] = (struct iovec
){
3047 .iov_len
= sizeof(req
)
3050 bclen
= ssfilter_bytecompile(f
->f
, &bc
);
3052 rta
.rta_type
= INET_DIAG_REQ_BYTECODE
;
3053 rta
.rta_len
= RTA_LENGTH(bclen
);
3054 iov
[1] = (struct iovec
){ &rta
, sizeof(rta
) };
3055 iov
[2] = (struct iovec
){ bc
, bclen
};
3056 req
.nlh
.nlmsg_len
+= RTA_LENGTH(bclen
);
3061 msg
= (struct msghdr
) {
3062 .msg_name
= (void *)&nladdr
,
3063 .msg_namelen
= sizeof(nladdr
),
3065 .msg_iovlen
= iovlen
,
3068 if (sendmsg(fd
, &msg
, 0) < 0) {
3076 struct inet_diag_arg
{
3079 struct rtnl_handle
*rth
;
3082 static int kill_inet_sock(struct nlmsghdr
*h
, void *arg
, struct sockstat
*s
)
3084 struct inet_diag_msg
*d
= NLMSG_DATA(h
);
3085 struct inet_diag_arg
*diag_arg
= arg
;
3086 struct rtnl_handle
*rth
= diag_arg
->rth
;
3088 DIAG_REQUEST(req
, struct inet_diag_req_v2 r
);
3090 req
.nlh
.nlmsg_type
= SOCK_DESTROY
;
3091 req
.nlh
.nlmsg_flags
= NLM_F_REQUEST
| NLM_F_ACK
;
3092 req
.nlh
.nlmsg_seq
= ++rth
->seq
;
3093 req
.r
.sdiag_family
= d
->idiag_family
;
3094 req
.r
.sdiag_protocol
= diag_arg
->protocol
;
3097 if (diag_arg
->protocol
== IPPROTO_RAW
) {
3098 struct inet_diag_req_raw
*raw
= (void *)&req
.r
;
3100 BUILD_BUG_ON(sizeof(req
.r
) != sizeof(*raw
));
3101 raw
->sdiag_raw_protocol
= s
->raw_prot
;
3104 return rtnl_talk(rth
, &req
.nlh
, NULL
);
3107 static int show_one_inet_sock(const struct sockaddr_nl
*addr
,
3108 struct nlmsghdr
*h
, void *arg
)
3111 struct inet_diag_arg
*diag_arg
= arg
;
3112 struct inet_diag_msg
*r
= NLMSG_DATA(h
);
3113 struct sockstat s
= {};
3115 if (!(diag_arg
->f
->families
& FAMILY_MASK(r
->idiag_family
)))
3118 parse_diag_msg(h
, &s
);
3119 s
.type
= diag_arg
->protocol
;
3121 if (diag_arg
->f
->f
&& run_ssfilter(diag_arg
->f
->f
, &s
) == 0)
3124 if (diag_arg
->f
->kill
&& kill_inet_sock(h
, arg
, &s
) != 0) {
3125 if (errno
== EOPNOTSUPP
|| errno
== ENOENT
) {
3126 /* Socket can't be closed, or is already closed. */
3129 perror("SOCK_DESTROY answers");
3134 err
= inet_show_sock(h
, &s
);
3141 static int inet_show_netlink(struct filter
*f
, FILE *dump_fp
, int protocol
)
3144 struct rtnl_handle rth
, rth2
;
3145 int family
= PF_INET
;
3146 struct inet_diag_arg arg
= { .f
= f
, .protocol
= protocol
};
3148 if (rtnl_open_byproto(&rth
, 0, NETLINK_SOCK_DIAG
))
3152 if (rtnl_open_byproto(&rth2
, 0, NETLINK_SOCK_DIAG
)) {
3159 rth
.dump
= MAGIC_SEQ
;
3160 rth
.dump_fp
= dump_fp
;
3161 if (preferred_family
== PF_INET6
)
3165 if ((err
= sockdiag_send(family
, rth
.fd
, protocol
, f
)))
3168 if ((err
= rtnl_dump_filter(&rth
, show_one_inet_sock
, &arg
))) {
3169 if (family
!= PF_UNSPEC
) {
3175 if (family
== PF_INET
&& preferred_family
!= PF_INET
) {
3183 rtnl_close(arg
.rth
);
3187 static int tcp_show_netlink_file(struct filter
*f
)
3193 if ((fp
= fopen(getenv("TCPDIAG_FILE"), "r")) == NULL
) {
3194 perror("fopen($TCPDIAG_FILE)");
3200 struct nlmsghdr
*h
= (struct nlmsghdr
*)buf
;
3201 struct sockstat s
= {};
3203 status
= fread(buf
, 1, sizeof(*h
), fp
);
3205 perror("Reading header from $TCPDIAG_FILE");
3208 if (status
!= sizeof(*h
)) {
3209 perror("Unexpected EOF reading $TCPDIAG_FILE");
3213 status
= fread(h
+1, 1, NLMSG_ALIGN(h
->nlmsg_len
-sizeof(*h
)), fp
);
3216 perror("Reading $TCPDIAG_FILE");
3219 if (status
+ sizeof(*h
) < h
->nlmsg_len
) {
3220 perror("Unexpected EOF reading $TCPDIAG_FILE");
3224 /* The only legal exit point */
3225 if (h
->nlmsg_type
== NLMSG_DONE
) {
3230 if (h
->nlmsg_type
== NLMSG_ERROR
) {
3231 struct nlmsgerr
*err
= (struct nlmsgerr
*)NLMSG_DATA(h
);
3233 if (h
->nlmsg_len
< NLMSG_LENGTH(sizeof(struct nlmsgerr
))) {
3234 fprintf(stderr
, "ERROR truncated\n");
3236 errno
= -err
->error
;
3237 perror("TCPDIAG answered");
3242 parse_diag_msg(h
, &s
);
3243 s
.type
= IPPROTO_TCP
;
3245 if (f
&& f
->f
&& run_ssfilter(f
->f
, &s
) == 0)
3248 err2
= inet_show_sock(h
, &s
);
3259 static int tcp_show(struct filter
*f
)
3263 int bufsize
= 64*1024;
3265 if (!filter_af_get(f
, AF_INET
) && !filter_af_get(f
, AF_INET6
))
3268 dg_proto
= TCP_PROTO
;
3270 if (getenv("TCPDIAG_FILE"))
3271 return tcp_show_netlink_file(f
);
3273 if (!getenv("PROC_NET_TCP") && !getenv("PROC_ROOT")
3274 && inet_show_netlink(f
, NULL
, IPPROTO_TCP
) == 0)
3277 /* Sigh... We have to parse /proc/net/tcp... */
3280 /* Estimate amount of sockets and try to allocate
3281 * huge buffer to read all the table at one read.
3282 * Limit it by 16MB though. The assumption is: as soon as
3283 * kernel was able to hold information about N connections,
3284 * it is able to give us some memory for snapshot.
3287 get_slabstat(&slabstat
);
3289 int guess
= slabstat
.socks
+slabstat
.tcp_syns
;
3291 if (f
->states
&(1<<SS_TIME_WAIT
))
3292 guess
+= slabstat
.tcp_tws
;
3293 if (guess
> (16*1024*1024)/128)
3294 guess
= (16*1024*1024)/128;
3296 if (guess
> bufsize
)
3299 while (bufsize
>= 64*1024) {
3300 if ((buf
= malloc(bufsize
)) != NULL
)
3309 if (f
->families
& FAMILY_MASK(AF_INET
)) {
3310 if ((fp
= net_tcp_open()) == NULL
)
3313 setbuffer(fp
, buf
, bufsize
);
3314 if (generic_record_read(fp
, tcp_show_line
, f
, AF_INET
))
3319 if ((f
->families
& FAMILY_MASK(AF_INET6
)) &&
3320 (fp
= net_tcp6_open()) != NULL
) {
3321 setbuffer(fp
, buf
, bufsize
);
3322 if (generic_record_read(fp
, tcp_show_line
, f
, AF_INET6
))
3332 int saved_errno
= errno
;
3337 errno
= saved_errno
;
3342 static int dccp_show(struct filter
*f
)
3344 if (!filter_af_get(f
, AF_INET
) && !filter_af_get(f
, AF_INET6
))
3347 if (!getenv("PROC_NET_DCCP") && !getenv("PROC_ROOT")
3348 && inet_show_netlink(f
, NULL
, IPPROTO_DCCP
) == 0)
3354 static int sctp_show(struct filter
*f
)
3356 if (!filter_af_get(f
, AF_INET
) && !filter_af_get(f
, AF_INET6
))
3359 if (!getenv("PROC_NET_SCTP") && !getenv("PROC_ROOT")
3360 && inet_show_netlink(f
, NULL
, IPPROTO_SCTP
) == 0)
3366 static int dgram_show_line(char *line
, const struct filter
*f
, int family
)
3368 struct sockstat s
= {};
3369 char *loc
, *rem
, *data
;
3373 if (proc_inet_split_line(line
, &loc
, &rem
, &data
))
3376 int state
= (data
[1] >= 'A') ? (data
[1] - 'A' + 10) : (data
[1] - '0');
3378 if (!(f
->states
& (1 << state
)))
3381 proc_parse_inet_addr(loc
, rem
, family
, &s
);
3383 if (f
->f
&& run_ssfilter(f
->f
, &s
) == 0)
3387 n
= sscanf(data
, "%x %x:%x %*x:%*x %*x %d %*d %u %d %llx %[^\n]\n",
3388 &s
.state
, &s
.wq
, &s
.rq
,
3390 &s
.refcnt
, &s
.sk
, opt
);
3395 s
.type
= dg_proto
== UDP_PROTO
? IPPROTO_UDP
: 0;
3396 inet_stats_print(&s
, false);
3398 if (show_details
&& opt
[0])
3399 out(" opt:\"%s\"", opt
);
3404 static int udp_show(struct filter
*f
)
3408 if (!filter_af_get(f
, AF_INET
) && !filter_af_get(f
, AF_INET6
))
3411 dg_proto
= UDP_PROTO
;
3413 if (!getenv("PROC_NET_UDP") && !getenv("PROC_ROOT")
3414 && inet_show_netlink(f
, NULL
, IPPROTO_UDP
) == 0)
3417 if (f
->families
&FAMILY_MASK(AF_INET
)) {
3418 if ((fp
= net_udp_open()) == NULL
)
3420 if (generic_record_read(fp
, dgram_show_line
, f
, AF_INET
))
3425 if ((f
->families
&FAMILY_MASK(AF_INET6
)) &&
3426 (fp
= net_udp6_open()) != NULL
) {
3427 if (generic_record_read(fp
, dgram_show_line
, f
, AF_INET6
))
3435 int saved_errno
= errno
;
3439 errno
= saved_errno
;
3444 static int raw_show(struct filter
*f
)
3448 if (!filter_af_get(f
, AF_INET
) && !filter_af_get(f
, AF_INET6
))
3451 dg_proto
= RAW_PROTO
;
3453 if (!getenv("PROC_NET_RAW") && !getenv("PROC_ROOT") &&
3454 inet_show_netlink(f
, NULL
, IPPROTO_RAW
) == 0)
3457 if (f
->families
&FAMILY_MASK(AF_INET
)) {
3458 if ((fp
= net_raw_open()) == NULL
)
3460 if (generic_record_read(fp
, dgram_show_line
, f
, AF_INET
))
3465 if ((f
->families
&FAMILY_MASK(AF_INET6
)) &&
3466 (fp
= net_raw6_open()) != NULL
) {
3467 if (generic_record_read(fp
, dgram_show_line
, f
, AF_INET6
))
3475 int saved_errno
= errno
;
3479 errno
= saved_errno
;
3484 #define MAX_UNIX_REMEMBER (1024*1024/sizeof(struct sockstat))
3486 static void unix_list_drop_first(struct sockstat
**list
)
3488 struct sockstat
*s
= *list
;
3490 (*list
) = (*list
)->next
;
3495 static bool unix_type_skip(struct sockstat
*s
, struct filter
*f
)
3497 if (s
->type
== SOCK_STREAM
&& !(f
->dbs
&(1<<UNIX_ST_DB
)))
3499 if (s
->type
== SOCK_DGRAM
&& !(f
->dbs
&(1<<UNIX_DG_DB
)))
3501 if (s
->type
== SOCK_SEQPACKET
&& !(f
->dbs
&(1<<UNIX_SQ_DB
)))
3506 static void unix_stats_print(struct sockstat
*s
, struct filter
*f
)
3508 char port_name
[30] = {};
3510 sock_state_print(s
);
3512 sock_addr_print(s
->name
?: "*", " ",
3513 int_to_str(s
->lport
, port_name
), NULL
);
3514 sock_addr_print(s
->peer_name
?: "*", " ",
3515 int_to_str(s
->rport
, port_name
), NULL
);
3520 static int unix_show_sock(const struct sockaddr_nl
*addr
, struct nlmsghdr
*nlh
,
3523 struct filter
*f
= (struct filter
*)arg
;
3524 struct unix_diag_msg
*r
= NLMSG_DATA(nlh
);
3525 struct rtattr
*tb
[UNIX_DIAG_MAX
+1];
3527 struct sockstat stat
= { .name
= "*", .peer_name
= "*" };
3529 parse_rtattr(tb
, UNIX_DIAG_MAX
, (struct rtattr
*)(r
+1),
3530 nlh
->nlmsg_len
- NLMSG_LENGTH(sizeof(*r
)));
3532 stat
.type
= r
->udiag_type
;
3533 stat
.state
= r
->udiag_state
;
3534 stat
.ino
= stat
.lport
= r
->udiag_ino
;
3535 stat
.local
.family
= stat
.remote
.family
= AF_UNIX
;
3537 if (unix_type_skip(&stat
, f
))
3540 if (tb
[UNIX_DIAG_RQLEN
]) {
3541 struct unix_diag_rqlen
*rql
= RTA_DATA(tb
[UNIX_DIAG_RQLEN
]);
3543 stat
.rq
= rql
->udiag_rqueue
;
3544 stat
.wq
= rql
->udiag_wqueue
;
3546 if (tb
[UNIX_DIAG_NAME
]) {
3547 int len
= RTA_PAYLOAD(tb
[UNIX_DIAG_NAME
]);
3549 memcpy(name
, RTA_DATA(tb
[UNIX_DIAG_NAME
]), len
);
3551 if (name
[0] == '\0') {
3553 for (i
= 0; i
< len
; i
++)
3554 if (name
[i
] == '\0')
3557 stat
.name
= &name
[0];
3558 memcpy(stat
.local
.data
, &stat
.name
, sizeof(stat
.name
));
3560 if (tb
[UNIX_DIAG_PEER
])
3561 stat
.rport
= rta_getattr_u32(tb
[UNIX_DIAG_PEER
]);
3563 if (f
->f
&& run_ssfilter(f
->f
, &stat
) == 0)
3566 unix_stats_print(&stat
, f
);
3569 print_skmeminfo(tb
, UNIX_DIAG_MEMINFO
);
3571 if (tb
[UNIX_DIAG_SHUTDOWN
]) {
3574 mask
= rta_getattr_u8(tb
[UNIX_DIAG_SHUTDOWN
]);
3576 mask
& 1 ? '-' : '<', mask
& 2 ? '-' : '>');
3583 static int handle_netlink_request(struct filter
*f
, struct nlmsghdr
*req
,
3584 size_t size
, rtnl_filter_t show_one_sock
)
3587 struct rtnl_handle rth
;
3589 if (rtnl_open_byproto(&rth
, 0, NETLINK_SOCK_DIAG
))
3592 rth
.dump
= MAGIC_SEQ
;
3594 if (rtnl_send(&rth
, req
, size
) < 0)
3597 if (rtnl_dump_filter(&rth
, show_one_sock
, f
))
3606 static int unix_show_netlink(struct filter
*f
)
3608 DIAG_REQUEST(req
, struct unix_diag_req r
);
3610 req
.r
.sdiag_family
= AF_UNIX
;
3611 req
.r
.udiag_states
= f
->states
;
3612 req
.r
.udiag_show
= UDIAG_SHOW_NAME
| UDIAG_SHOW_PEER
| UDIAG_SHOW_RQLEN
;
3614 req
.r
.udiag_show
|= UDIAG_SHOW_MEMINFO
;
3616 return handle_netlink_request(f
, &req
.nlh
, sizeof(req
), unix_show_sock
);
3619 static int unix_show(struct filter
*f
)
3626 struct sockstat
*list
= NULL
;
3627 const int unix_state_map
[] = { SS_CLOSE
, SS_SYN_SENT
,
3628 SS_ESTABLISHED
, SS_CLOSING
};
3630 if (!filter_af_get(f
, AF_UNIX
))
3633 if (!getenv("PROC_NET_UNIX") && !getenv("PROC_ROOT")
3634 && unix_show_netlink(f
) == 0)
3637 if ((fp
= net_unix_open()) == NULL
)
3639 if (!fgets(buf
, sizeof(buf
), fp
)) {
3644 if (memcmp(buf
, "Peer", 4) == 0)
3648 while (fgets(buf
, sizeof(buf
), fp
)) {
3649 struct sockstat
*u
, **insp
;
3652 if (!(u
= calloc(1, sizeof(*u
))))
3655 if (sscanf(buf
, "%x: %x %x %x %x %x %d %s",
3656 &u
->rport
, &u
->rq
, &u
->wq
, &flags
, &u
->type
,
3657 &u
->state
, &u
->ino
, name
) < 8)
3661 u
->local
.family
= u
->remote
.family
= AF_UNIX
;
3663 if (flags
& (1 << 16)) {
3664 u
->state
= SS_LISTEN
;
3665 } else if (u
->state
> 0 &&
3666 u
->state
<= ARRAY_SIZE(unix_state_map
)) {
3667 u
->state
= unix_state_map
[u
->state
-1];
3668 if (u
->type
== SOCK_DGRAM
&& u
->state
== SS_CLOSE
&& u
->rport
)
3669 u
->state
= SS_ESTABLISHED
;
3671 if (unix_type_skip(u
, f
) ||
3672 !(f
->states
& (1 << u
->state
))) {
3684 u
->name
= strdup(name
);
3694 for (p
= list
; p
; p
= p
->next
) {
3695 if (u
->rport
== p
->lport
)
3701 u
->peer_name
= p
->name
? : "*";
3705 struct sockstat st
= {
3706 .local
.family
= AF_UNIX
,
3707 .remote
.family
= AF_UNIX
,
3710 memcpy(st
.local
.data
, &u
->name
, sizeof(u
->name
));
3711 if (strcmp(u
->peer_name
, "*"))
3712 memcpy(st
.remote
.data
, &u
->peer_name
,
3713 sizeof(u
->peer_name
));
3714 if (run_ssfilter(f
->f
, &st
) == 0) {
3723 if (u
->type
< (*insp
)->type
||
3724 (u
->type
== (*insp
)->type
&&
3725 u
->ino
< (*insp
)->ino
))
3727 insp
= &(*insp
)->next
;
3732 if (++cnt
> MAX_UNIX_REMEMBER
) {
3734 unix_stats_print(list
, f
);
3735 unix_list_drop_first(&list
);
3742 unix_stats_print(list
, f
);
3743 unix_list_drop_first(&list
);
3749 static int packet_stats_print(struct sockstat
*s
, const struct filter
*f
)
3751 const char *addr
, *port
;
3754 s
->local
.family
= s
->remote
.family
= AF_PACKET
;
3757 s
->local
.data
[0] = s
->prot
;
3758 if (run_ssfilter(f
->f
, s
) == 0)
3762 sock_state_print(s
);
3767 addr
= ll_proto_n2a(htons(s
->prot
), ll_name
, sizeof(ll_name
));
3772 port
= xll_index_to_name(s
->iface
);
3774 sock_addr_print(addr
, ":", port
, NULL
);
3775 sock_addr_print("", "*", "", NULL
);
3780 sock_details_print(s
);
3785 static void packet_show_ring(struct packet_diag_ring
*ring
)
3787 out("blk_size:%d", ring
->pdr_block_size
);
3788 out(",blk_nr:%d", ring
->pdr_block_nr
);
3789 out(",frm_size:%d", ring
->pdr_frame_size
);
3790 out(",frm_nr:%d", ring
->pdr_frame_nr
);
3791 out(",tmo:%d", ring
->pdr_retire_tmo
);
3792 out(",features:0x%x", ring
->pdr_features
);
3795 static int packet_show_sock(const struct sockaddr_nl
*addr
,
3796 struct nlmsghdr
*nlh
, void *arg
)
3798 const struct filter
*f
= arg
;
3799 struct packet_diag_msg
*r
= NLMSG_DATA(nlh
);
3800 struct packet_diag_info
*pinfo
= NULL
;
3801 struct packet_diag_ring
*ring_rx
= NULL
, *ring_tx
= NULL
;
3802 struct rtattr
*tb
[PACKET_DIAG_MAX
+1];
3803 struct sockstat stat
= {};
3804 uint32_t fanout
= 0;
3805 bool has_fanout
= false;
3807 parse_rtattr(tb
, PACKET_DIAG_MAX
, (struct rtattr
*)(r
+1),
3808 nlh
->nlmsg_len
- NLMSG_LENGTH(sizeof(*r
)));
3810 /* use /proc/net/packet if all info are not available */
3811 if (!tb
[PACKET_DIAG_MEMINFO
])
3814 stat
.type
= r
->pdiag_type
;
3815 stat
.prot
= r
->pdiag_num
;
3816 stat
.ino
= r
->pdiag_ino
;
3817 stat
.state
= SS_CLOSE
;
3818 stat
.sk
= cookie_sk_get(&r
->pdiag_cookie
[0]);
3820 if (tb
[PACKET_DIAG_MEMINFO
]) {
3821 __u32
*skmeminfo
= RTA_DATA(tb
[PACKET_DIAG_MEMINFO
]);
3823 stat
.rq
= skmeminfo
[SK_MEMINFO_RMEM_ALLOC
];
3826 if (tb
[PACKET_DIAG_INFO
]) {
3827 pinfo
= RTA_DATA(tb
[PACKET_DIAG_INFO
]);
3828 stat
.lport
= stat
.iface
= pinfo
->pdi_index
;
3831 if (tb
[PACKET_DIAG_UID
])
3832 stat
.uid
= rta_getattr_u32(tb
[PACKET_DIAG_UID
]);
3834 if (tb
[PACKET_DIAG_RX_RING
])
3835 ring_rx
= RTA_DATA(tb
[PACKET_DIAG_RX_RING
]);
3837 if (tb
[PACKET_DIAG_TX_RING
])
3838 ring_tx
= RTA_DATA(tb
[PACKET_DIAG_TX_RING
]);
3840 if (tb
[PACKET_DIAG_FANOUT
]) {
3842 fanout
= rta_getattr_u32(tb
[PACKET_DIAG_FANOUT
]);
3845 if (packet_stats_print(&stat
, f
))
3850 out("\n\tver:%d", pinfo
->pdi_version
);
3851 out(" cpy_thresh:%d", pinfo
->pdi_copy_thresh
);
3853 if (pinfo
->pdi_flags
& PDI_RUNNING
)
3855 if (pinfo
->pdi_flags
& PDI_AUXDATA
)
3857 if (pinfo
->pdi_flags
& PDI_ORIGDEV
)
3859 if (pinfo
->pdi_flags
& PDI_VNETHDR
)
3861 if (pinfo
->pdi_flags
& PDI_LOSS
)
3863 if (!pinfo
->pdi_flags
)
3868 out("\n\tring_rx(");
3869 packet_show_ring(ring_rx
);
3873 out("\n\tring_tx(");
3874 packet_show_ring(ring_tx
);
3878 uint16_t type
= (fanout
>> 16) & 0xffff;
3881 out("id:%d,", fanout
& 0xffff);
3903 if (show_bpf
&& tb
[PACKET_DIAG_FILTER
]) {
3904 struct sock_filter
*fil
=
3905 RTA_DATA(tb
[PACKET_DIAG_FILTER
]);
3906 int num
= RTA_PAYLOAD(tb
[PACKET_DIAG_FILTER
]) /
3907 sizeof(struct sock_filter
);
3909 out("\n\tbpf filter (%d): ", num
);
3911 out(" 0x%02x %u %u %u,",
3912 fil
->code
, fil
->jt
, fil
->jf
, fil
->k
);
3920 static int packet_show_netlink(struct filter
*f
)
3922 DIAG_REQUEST(req
, struct packet_diag_req r
);
3924 req
.r
.sdiag_family
= AF_PACKET
;
3925 req
.r
.pdiag_show
= PACKET_SHOW_INFO
| PACKET_SHOW_MEMINFO
|
3926 PACKET_SHOW_FILTER
| PACKET_SHOW_RING_CFG
| PACKET_SHOW_FANOUT
;
3928 return handle_netlink_request(f
, &req
.nlh
, sizeof(req
), packet_show_sock
);
3931 static int packet_show_line(char *buf
, const struct filter
*f
, int fam
)
3933 unsigned long long sk
;
3934 struct sockstat stat
= {};
3935 int type
, prot
, iface
, state
, rq
, uid
, ino
;
3937 sscanf(buf
, "%llx %*d %d %x %d %d %u %u %u",
3939 &type
, &prot
, &iface
, &state
,
3942 if (stat
.type
== SOCK_RAW
&& !(f
->dbs
&(1<<PACKET_R_DB
)))
3944 if (stat
.type
== SOCK_DGRAM
&& !(f
->dbs
&(1<<PACKET_DG_DB
)))
3949 stat
.lport
= stat
.iface
= iface
;
3954 stat
.state
= SS_CLOSE
;
3956 if (packet_stats_print(&stat
, f
))
3962 static int packet_show(struct filter
*f
)
3967 if (!filter_af_get(f
, AF_PACKET
) || !(f
->states
& (1 << SS_CLOSE
)))
3970 if (!getenv("PROC_NET_PACKET") && !getenv("PROC_ROOT") &&
3971 packet_show_netlink(f
) == 0)
3974 if ((fp
= net_packet_open()) == NULL
)
3976 if (generic_record_read(fp
, packet_show_line
, f
, AF_PACKET
))
3983 static int netlink_show_one(struct filter
*f
,
3984 int prot
, int pid
, unsigned int groups
,
3985 int state
, int dst_pid
, unsigned int dst_group
,
3987 unsigned long long sk
, unsigned long long cb
)
3989 struct sockstat st
= {
3993 .local
.family
= AF_NETLINK
,
3994 .remote
.family
= AF_NETLINK
,
3997 SPRINT_BUF(prot_buf
) = {};
3998 const char *prot_name
;
3999 char procname
[64] = {};
4004 st
.local
.data
[0] = prot
;
4005 if (run_ssfilter(f
->f
, &st
) == 0)
4009 sock_state_print(&st
);
4011 if (resolve_services
)
4012 prot_name
= nl_proto_n2a(prot
, prot_buf
, sizeof(prot_buf
));
4014 prot_name
= int_to_str(prot
, prot_buf
);
4018 } else if (resolve_services
) {
4023 strncpy(procname
, "kernel", 6);
4024 } else if (pid
> 0) {
4027 snprintf(procname
, sizeof(procname
), "%s/%d/stat",
4028 getenv("PROC_ROOT") ? : "/proc", pid
);
4029 if ((fp
= fopen(procname
, "r")) != NULL
) {
4030 if (fscanf(fp
, "%*d (%[^)])", procname
) == 1) {
4031 snprintf(procname
+strlen(procname
),
4032 sizeof(procname
)-strlen(procname
),
4040 int_to_str(pid
, procname
);
4042 int_to_str(pid
, procname
);
4045 sock_addr_print(prot_name
, ":", procname
, NULL
);
4047 if (state
== NETLINK_CONNECTED
) {
4048 char dst_group_buf
[30];
4049 char dst_pid_buf
[30];
4051 sock_addr_print(int_to_str(dst_group
, dst_group_buf
), ":",
4052 int_to_str(dst_pid
, dst_pid_buf
), NULL
);
4054 sock_addr_print("", "*", "", NULL
);
4057 char *pid_context
= NULL
;
4059 if (show_proc_ctx
) {
4060 /* The pid value will either be:
4061 * 0 if destination kernel - show kernel initial context.
4062 * A valid process pid - use getpidcon.
4063 * A unique value allocated by the kernel or netlink user
4064 * to the process - show context as "not available".
4067 security_get_initial_context("kernel", &pid_context
);
4069 getpidcon(pid
, &pid_context
);
4071 out(" proc_ctx=%s", pid_context
? : "unavailable");
4076 out(" sk=%llx cb=%llx groups=0x%08x", sk
, cb
, groups
);
4082 static int netlink_show_sock(const struct sockaddr_nl
*addr
,
4083 struct nlmsghdr
*nlh
, void *arg
)
4085 struct filter
*f
= (struct filter
*)arg
;
4086 struct netlink_diag_msg
*r
= NLMSG_DATA(nlh
);
4087 struct rtattr
*tb
[NETLINK_DIAG_MAX
+1];
4089 unsigned long groups
= 0;
4091 parse_rtattr(tb
, NETLINK_DIAG_MAX
, (struct rtattr
*)(r
+1),
4092 nlh
->nlmsg_len
- NLMSG_LENGTH(sizeof(*r
)));
4094 if (tb
[NETLINK_DIAG_GROUPS
] && RTA_PAYLOAD(tb
[NETLINK_DIAG_GROUPS
]))
4095 groups
= *(unsigned long *) RTA_DATA(tb
[NETLINK_DIAG_GROUPS
]);
4097 if (tb
[NETLINK_DIAG_MEMINFO
]) {
4098 const __u32
*skmeminfo
;
4100 skmeminfo
= RTA_DATA(tb
[NETLINK_DIAG_MEMINFO
]);
4102 rq
= skmeminfo
[SK_MEMINFO_RMEM_ALLOC
];
4103 wq
= skmeminfo
[SK_MEMINFO_WMEM_ALLOC
];
4106 if (netlink_show_one(f
, r
->ndiag_protocol
, r
->ndiag_portid
, groups
,
4107 r
->ndiag_state
, r
->ndiag_dst_portid
, r
->ndiag_dst_group
,
4114 print_skmeminfo(tb
, NETLINK_DIAG_MEMINFO
);
4120 static int netlink_show_netlink(struct filter
*f
)
4122 DIAG_REQUEST(req
, struct netlink_diag_req r
);
4124 req
.r
.sdiag_family
= AF_NETLINK
;
4125 req
.r
.sdiag_protocol
= NDIAG_PROTO_ALL
;
4126 req
.r
.ndiag_show
= NDIAG_SHOW_GROUPS
| NDIAG_SHOW_MEMINFO
;
4128 return handle_netlink_request(f
, &req
.nlh
, sizeof(req
), netlink_show_sock
);
4131 static int netlink_show(struct filter
*f
)
4136 unsigned int groups
;
4138 unsigned long long sk
, cb
;
4140 if (!filter_af_get(f
, AF_NETLINK
) || !(f
->states
& (1 << SS_CLOSE
)))
4143 if (!getenv("PROC_NET_NETLINK") && !getenv("PROC_ROOT") &&
4144 netlink_show_netlink(f
) == 0)
4147 if ((fp
= net_netlink_open()) == NULL
)
4149 if (!fgets(buf
, sizeof(buf
), fp
)) {
4154 while (fgets(buf
, sizeof(buf
), fp
)) {
4155 sscanf(buf
, "%llx %d %d %x %d %d %llx %d",
4157 &prot
, &pid
, &groups
, &rq
, &wq
, &cb
, &rc
);
4159 netlink_show_one(f
, prot
, pid
, groups
, 0, 0, 0, rq
, wq
, sk
, cb
);
4166 static bool vsock_type_skip(struct sockstat
*s
, struct filter
*f
)
4168 if (s
->type
== SOCK_STREAM
&& !(f
->dbs
& (1 << VSOCK_ST_DB
)))
4170 if (s
->type
== SOCK_DGRAM
&& !(f
->dbs
& (1 << VSOCK_DG_DB
)))
4175 static void vsock_addr_print(inet_prefix
*a
, __u32 port
)
4177 char cid_str
[sizeof("4294967295")];
4178 char port_str
[sizeof("4294967295")];
4181 memcpy(&cid
, a
->data
, sizeof(cid
));
4183 if (cid
== ~(__u32
)0)
4184 snprintf(cid_str
, sizeof(cid_str
), "*");
4186 snprintf(cid_str
, sizeof(cid_str
), "%u", cid
);
4188 if (port
== ~(__u32
)0)
4189 snprintf(port_str
, sizeof(port_str
), "*");
4191 snprintf(port_str
, sizeof(port_str
), "%u", port
);
4193 sock_addr_print(cid_str
, ":", port_str
, NULL
);
4196 static void vsock_stats_print(struct sockstat
*s
, struct filter
*f
)
4198 sock_state_print(s
);
4200 vsock_addr_print(&s
->local
, s
->lport
);
4201 vsock_addr_print(&s
->remote
, s
->rport
);
4206 static int vsock_show_sock(const struct sockaddr_nl
*addr
,
4207 struct nlmsghdr
*nlh
, void *arg
)
4209 struct filter
*f
= (struct filter
*)arg
;
4210 struct vsock_diag_msg
*r
= NLMSG_DATA(nlh
);
4211 struct sockstat stat
= {
4212 .type
= r
->vdiag_type
,
4213 .lport
= r
->vdiag_src_port
,
4214 .rport
= r
->vdiag_dst_port
,
4215 .state
= r
->vdiag_state
,
4216 .ino
= r
->vdiag_ino
,
4219 vsock_set_inet_prefix(&stat
.local
, r
->vdiag_src_cid
);
4220 vsock_set_inet_prefix(&stat
.remote
, r
->vdiag_dst_cid
);
4222 if (vsock_type_skip(&stat
, f
))
4225 if (f
->f
&& run_ssfilter(f
->f
, &stat
) == 0)
4228 vsock_stats_print(&stat
, f
);
4233 static int vsock_show(struct filter
*f
)
4235 DIAG_REQUEST(req
, struct vsock_diag_req r
);
4237 if (!filter_af_get(f
, AF_VSOCK
))
4240 req
.r
.sdiag_family
= AF_VSOCK
;
4241 req
.r
.vdiag_states
= f
->states
;
4243 return handle_netlink_request(f
, &req
.nlh
, sizeof(req
), vsock_show_sock
);
4246 struct sock_diag_msg
{
4250 static int generic_show_sock(const struct sockaddr_nl
*addr
,
4251 struct nlmsghdr
*nlh
, void *arg
)
4253 struct sock_diag_msg
*r
= NLMSG_DATA(nlh
);
4254 struct inet_diag_arg inet_arg
= { .f
= arg
, .protocol
= IPPROTO_MAX
};
4256 switch (r
->sdiag_family
) {
4259 return show_one_inet_sock(addr
, nlh
, &inet_arg
);
4261 return unix_show_sock(addr
, nlh
, arg
);
4263 return packet_show_sock(addr
, nlh
, arg
);
4265 return netlink_show_sock(addr
, nlh
, arg
);
4267 return vsock_show_sock(addr
, nlh
, arg
);
4273 static int handle_follow_request(struct filter
*f
)
4277 struct rtnl_handle rth
;
4279 if (f
->families
& FAMILY_MASK(AF_INET
) && f
->dbs
& (1 << TCP_DB
))
4280 groups
|= 1 << (SKNLGRP_INET_TCP_DESTROY
- 1);
4281 if (f
->families
& FAMILY_MASK(AF_INET
) && f
->dbs
& (1 << UDP_DB
))
4282 groups
|= 1 << (SKNLGRP_INET_UDP_DESTROY
- 1);
4283 if (f
->families
& FAMILY_MASK(AF_INET6
) && f
->dbs
& (1 << TCP_DB
))
4284 groups
|= 1 << (SKNLGRP_INET6_TCP_DESTROY
- 1);
4285 if (f
->families
& FAMILY_MASK(AF_INET6
) && f
->dbs
& (1 << UDP_DB
))
4286 groups
|= 1 << (SKNLGRP_INET6_UDP_DESTROY
- 1);
4291 if (rtnl_open_byproto(&rth
, groups
, NETLINK_SOCK_DIAG
))
4295 rth
.local
.nl_pid
= 0;
4297 if (rtnl_dump_filter(&rth
, generic_show_sock
, f
))
4304 static int get_snmp_int(char *proto
, char *key
, int *result
)
4308 int protolen
= strlen(proto
);
4309 int keylen
= strlen(key
);
4313 if ((fp
= net_snmp_open()) == NULL
)
4316 while (fgets(buf
, sizeof(buf
), fp
) != NULL
) {
4320 if (memcmp(buf
, proto
, protolen
))
4322 while ((p
= strchr(p
, ' ')) != NULL
) {
4325 if (memcmp(p
, key
, keylen
) == 0 &&
4326 (p
[keylen
] == ' ' || p
[keylen
] == '\n'))
4329 if (fgets(buf
, sizeof(buf
), fp
) == NULL
)
4331 if (memcmp(buf
, proto
, protolen
))
4334 while ((p
= strchr(p
, ' ')) != NULL
) {
4337 sscanf(p
, "%d", result
);
4350 /* Get stats from sockstat */
4370 static void get_sockstat_line(char *line
, struct ssummary
*s
)
4372 char id
[256], rem
[256];
4374 if (sscanf(line
, "%[^ ] %[^\n]\n", id
, rem
) != 2)
4377 if (strcmp(id
, "sockets:") == 0)
4378 sscanf(rem
, "%*s%d", &s
->socks
);
4379 else if (strcmp(id
, "UDP:") == 0)
4380 sscanf(rem
, "%*s%d", &s
->udp4
);
4381 else if (strcmp(id
, "UDP6:") == 0)
4382 sscanf(rem
, "%*s%d", &s
->udp6
);
4383 else if (strcmp(id
, "RAW:") == 0)
4384 sscanf(rem
, "%*s%d", &s
->raw4
);
4385 else if (strcmp(id
, "RAW6:") == 0)
4386 sscanf(rem
, "%*s%d", &s
->raw6
);
4387 else if (strcmp(id
, "TCP6:") == 0)
4388 sscanf(rem
, "%*s%d", &s
->tcp6_hashed
);
4389 else if (strcmp(id
, "FRAG:") == 0)
4390 sscanf(rem
, "%*s%d%*s%d", &s
->frag4
, &s
->frag4_mem
);
4391 else if (strcmp(id
, "FRAG6:") == 0)
4392 sscanf(rem
, "%*s%d%*s%d", &s
->frag6
, &s
->frag6_mem
);
4393 else if (strcmp(id
, "TCP:") == 0)
4394 sscanf(rem
, "%*s%d%*s%d%*s%d%*s%d%*s%d",
4396 &s
->tcp_orphans
, &s
->tcp_tws
, &s
->tcp_total
, &s
->tcp_mem
);
4399 static int get_sockstat(struct ssummary
*s
)
4404 memset(s
, 0, sizeof(*s
));
4406 if ((fp
= net_sockstat_open()) == NULL
)
4408 while (fgets(buf
, sizeof(buf
), fp
) != NULL
)
4409 get_sockstat_line(buf
, s
);
4412 if ((fp
= net_sockstat6_open()) == NULL
)
4414 while (fgets(buf
, sizeof(buf
), fp
) != NULL
)
4415 get_sockstat_line(buf
, s
);
4421 static int print_summary(void)
4426 if (get_sockstat(&s
) < 0)
4427 perror("ss: get_sockstat");
4428 if (get_snmp_int("Tcp:", "CurrEstab", &tcp_estab
) < 0)
4429 perror("ss: get_snmpstat");
4431 get_slabstat(&slabstat
);
4433 printf("Total: %d (kernel %d)\n", s
.socks
, slabstat
.socks
);
4435 printf("TCP: %d (estab %d, closed %d, orphaned %d, synrecv %d, timewait %d/%d), ports %d\n",
4436 s
.tcp_total
+ slabstat
.tcp_syns
+ s
.tcp_tws
,
4438 s
.tcp_total
- (s
.tcp4_hashed
+s
.tcp6_hashed
-s
.tcp_tws
),
4441 s
.tcp_tws
, slabstat
.tcp_tws
,
4446 printf("Transport Total IP IPv6\n");
4447 printf("* %-9d %-9s %-9s\n", slabstat
.socks
, "-", "-");
4448 printf("RAW %-9d %-9d %-9d\n", s
.raw4
+s
.raw6
, s
.raw4
, s
.raw6
);
4449 printf("UDP %-9d %-9d %-9d\n", s
.udp4
+s
.udp6
, s
.udp4
, s
.udp6
);
4450 printf("TCP %-9d %-9d %-9d\n", s
.tcp4_hashed
+s
.tcp6_hashed
, s
.tcp4_hashed
, s
.tcp6_hashed
);
4451 printf("INET %-9d %-9d %-9d\n",
4452 s
.raw4
+s
.udp4
+s
.tcp4_hashed
+
4453 s
.raw6
+s
.udp6
+s
.tcp6_hashed
,
4454 s
.raw4
+s
.udp4
+s
.tcp4_hashed
,
4455 s
.raw6
+s
.udp6
+s
.tcp6_hashed
);
4456 printf("FRAG %-9d %-9d %-9d\n", s
.frag4
+s
.frag6
, s
.frag4
, s
.frag6
);
4463 static void _usage(FILE *dest
)
4466 "Usage: ss [ OPTIONS ]\n"
4467 " ss [ OPTIONS ] [ FILTER ]\n"
4468 " -h, --help this message\n"
4469 " -V, --version output version information\n"
4470 " -n, --numeric don't resolve service names\n"
4471 " -r, --resolve resolve host names\n"
4472 " -a, --all display all sockets\n"
4473 " -l, --listening display listening sockets\n"
4474 " -o, --options show timer information\n"
4475 " -e, --extended show detailed socket information\n"
4476 " -m, --memory show socket memory usage\n"
4477 " -p, --processes show process using socket\n"
4478 " -i, --info show internal TCP information\n"
4479 " -s, --summary show socket usage summary\n"
4480 " -b, --bpf show bpf filter socket information\n"
4481 " -E, --events continually display sockets as they are destroyed\n"
4482 " -Z, --context display process SELinux security contexts\n"
4483 " -z, --contexts display process and socket SELinux security contexts\n"
4484 " -N, --net switch to the specified network namespace name\n"
4486 " -4, --ipv4 display only IP version 4 sockets\n"
4487 " -6, --ipv6 display only IP version 6 sockets\n"
4488 " -0, --packet display PACKET sockets\n"
4489 " -t, --tcp display only TCP sockets\n"
4490 " -S, --sctp display only SCTP sockets\n"
4491 " -u, --udp display only UDP sockets\n"
4492 " -d, --dccp display only DCCP sockets\n"
4493 " -w, --raw display only RAW sockets\n"
4494 " -x, --unix display only Unix domain sockets\n"
4495 " --vsock display only vsock sockets\n"
4496 " -f, --family=FAMILY display sockets of type FAMILY\n"
4497 " FAMILY := {inet|inet6|link|unix|netlink|vsock|help}\n"
4499 " -K, --kill forcibly close sockets, display what was closed\n"
4500 " -H, --no-header Suppress header line\n"
4502 " -A, --query=QUERY, --socket=QUERY\n"
4503 " QUERY := {all|inet|tcp|udp|raw|unix|unix_dgram|unix_stream|unix_seqpacket|packet|netlink|vsock_stream|vsock_dgram}[,QUERY]\n"
4505 " -D, --diag=FILE Dump raw information about TCP sockets to FILE\n"
4506 " -F, --filter=FILE read filter information from FILE\n"
4507 " FILTER := [ state STATE-FILTER ] [ EXPRESSION ]\n"
4508 " STATE-FILTER := {all|connected|synchronized|bucket|big|TCP-STATES}\n"
4509 " TCP-STATES := {established|syn-sent|syn-recv|fin-wait-{1,2}|time-wait|closed|close-wait|last-ack|listening|closing}\n"
4510 " connected := {established|syn-sent|syn-recv|fin-wait-{1,2}|time-wait|close-wait|last-ack|closing}\n"
4511 " synchronized := {established|syn-recv|fin-wait-{1,2}|time-wait|close-wait|last-ack|closing}\n"
4512 " bucket := {syn-recv|time-wait}\n"
4513 " big := {established|syn-sent|fin-wait-{1,2}|closed|close-wait|last-ack|listening|closing}\n"
4517 static void help(void) __attribute__((noreturn
));
4518 static void help(void)
4524 static void usage(void) __attribute__((noreturn
));
4525 static void usage(void)
4532 static int scan_state(const char *state
)
4534 static const char * const sstate_namel
[] = {
4536 [SS_ESTABLISHED
] = "established",
4537 [SS_SYN_SENT
] = "syn-sent",
4538 [SS_SYN_RECV
] = "syn-recv",
4539 [SS_FIN_WAIT1
] = "fin-wait-1",
4540 [SS_FIN_WAIT2
] = "fin-wait-2",
4541 [SS_TIME_WAIT
] = "time-wait",
4542 [SS_CLOSE
] = "unconnected",
4543 [SS_CLOSE_WAIT
] = "close-wait",
4544 [SS_LAST_ACK
] = "last-ack",
4545 [SS_LISTEN
] = "listening",
4546 [SS_CLOSING
] = "closing",
4550 if (strcasecmp(state
, "close") == 0 ||
4551 strcasecmp(state
, "closed") == 0)
4552 return (1<<SS_CLOSE
);
4553 if (strcasecmp(state
, "syn-rcv") == 0)
4554 return (1<<SS_SYN_RECV
);
4555 if (strcasecmp(state
, "established") == 0)
4556 return (1<<SS_ESTABLISHED
);
4557 if (strcasecmp(state
, "all") == 0)
4559 if (strcasecmp(state
, "connected") == 0)
4560 return SS_ALL
& ~((1<<SS_CLOSE
)|(1<<SS_LISTEN
));
4561 if (strcasecmp(state
, "synchronized") == 0)
4562 return SS_ALL
& ~((1<<SS_CLOSE
)|(1<<SS_LISTEN
)|(1<<SS_SYN_SENT
));
4563 if (strcasecmp(state
, "bucket") == 0)
4564 return (1<<SS_SYN_RECV
)|(1<<SS_TIME_WAIT
);
4565 if (strcasecmp(state
, "big") == 0)
4566 return SS_ALL
& ~((1<<SS_SYN_RECV
)|(1<<SS_TIME_WAIT
));
4567 for (i
= 0; i
< SS_MAX
; i
++) {
4568 if (strcasecmp(state
, sstate_namel
[i
]) == 0)
4572 fprintf(stderr
, "ss: wrong state name: %s\n", state
);
4576 /* Values 'v' and 'V' are already used so a non-character is used */
4577 #define OPT_VSOCK 256
4579 static const struct option long_opts
[] = {
4580 { "numeric", 0, 0, 'n' },
4581 { "resolve", 0, 0, 'r' },
4582 { "options", 0, 0, 'o' },
4583 { "extended", 0, 0, 'e' },
4584 { "memory", 0, 0, 'm' },
4585 { "info", 0, 0, 'i' },
4586 { "processes", 0, 0, 'p' },
4587 { "bpf", 0, 0, 'b' },
4588 { "events", 0, 0, 'E' },
4589 { "dccp", 0, 0, 'd' },
4590 { "tcp", 0, 0, 't' },
4591 { "sctp", 0, 0, 'S' },
4592 { "udp", 0, 0, 'u' },
4593 { "raw", 0, 0, 'w' },
4594 { "unix", 0, 0, 'x' },
4595 { "vsock", 0, 0, OPT_VSOCK
},
4596 { "all", 0, 0, 'a' },
4597 { "listening", 0, 0, 'l' },
4598 { "ipv4", 0, 0, '4' },
4599 { "ipv6", 0, 0, '6' },
4600 { "packet", 0, 0, '0' },
4601 { "family", 1, 0, 'f' },
4602 { "socket", 1, 0, 'A' },
4603 { "query", 1, 0, 'A' },
4604 { "summary", 0, 0, 's' },
4605 { "diag", 1, 0, 'D' },
4606 { "filter", 1, 0, 'F' },
4607 { "version", 0, 0, 'V' },
4608 { "help", 0, 0, 'h' },
4609 { "context", 0, 0, 'Z' },
4610 { "contexts", 0, 0, 'z' },
4611 { "net", 1, 0, 'N' },
4612 { "kill", 0, 0, 'K' },
4613 { "no-header", 0, 0, 'H' },
4618 int main(int argc
, char *argv
[])
4623 const char *dump_tcpdiag
= NULL
;
4624 FILE *filter_fp
= NULL
;
4626 int state_filter
= 0;
4627 int screen_width
= 80;
4629 while ((ch
= getopt_long(argc
, argv
,
4630 "dhaletuwxnro460spbEf:miA:D:F:vVzZN:KHS",
4631 long_opts
, NULL
)) != EOF
) {
4634 resolve_services
= 0;
4654 user_ent_hash_build();
4664 filter_db_set(¤t_filter
, DCCP_DB
);
4667 filter_db_set(¤t_filter
, TCP_DB
);
4670 filter_db_set(¤t_filter
, SCTP_DB
);
4673 filter_db_set(¤t_filter
, UDP_DB
);
4676 filter_db_set(¤t_filter
, RAW_DB
);
4679 filter_af_set(¤t_filter
, AF_UNIX
);
4682 filter_af_set(¤t_filter
, AF_VSOCK
);
4685 state_filter
= SS_ALL
;
4688 state_filter
= (1 << SS_LISTEN
) | (1 << SS_CLOSE
);
4691 filter_af_set(¤t_filter
, AF_INET
);
4694 filter_af_set(¤t_filter
, AF_INET6
);
4697 filter_af_set(¤t_filter
, AF_PACKET
);
4700 if (strcmp(optarg
, "inet") == 0)
4701 filter_af_set(¤t_filter
, AF_INET
);
4702 else if (strcmp(optarg
, "inet6") == 0)
4703 filter_af_set(¤t_filter
, AF_INET6
);
4704 else if (strcmp(optarg
, "link") == 0)
4705 filter_af_set(¤t_filter
, AF_PACKET
);
4706 else if (strcmp(optarg
, "unix") == 0)
4707 filter_af_set(¤t_filter
, AF_UNIX
);
4708 else if (strcmp(optarg
, "netlink") == 0)
4709 filter_af_set(¤t_filter
, AF_NETLINK
);
4710 else if (strcmp(optarg
, "vsock") == 0)
4711 filter_af_set(¤t_filter
, AF_VSOCK
);
4712 else if (strcmp(optarg
, "help") == 0)
4715 fprintf(stderr
, "ss: \"%s\" is invalid family\n",
4725 current_filter
.dbs
= 0;
4726 state_filter
= state_filter
?
4727 state_filter
: SS_CONN
;
4733 if ((p1
= strchr(p
, ',')) != NULL
)
4735 if (strcmp(p
, "all") == 0) {
4736 filter_default_dbs(¤t_filter
);
4737 } else if (strcmp(p
, "inet") == 0) {
4738 filter_db_set(¤t_filter
, UDP_DB
);
4739 filter_db_set(¤t_filter
, DCCP_DB
);
4740 filter_db_set(¤t_filter
, TCP_DB
);
4741 filter_db_set(¤t_filter
, SCTP_DB
);
4742 filter_db_set(¤t_filter
, RAW_DB
);
4743 } else if (strcmp(p
, "udp") == 0) {
4744 filter_db_set(¤t_filter
, UDP_DB
);
4745 } else if (strcmp(p
, "dccp") == 0) {
4746 filter_db_set(¤t_filter
, DCCP_DB
);
4747 } else if (strcmp(p
, "tcp") == 0) {
4748 filter_db_set(¤t_filter
, TCP_DB
);
4749 } else if (strcmp(p
, "sctp") == 0) {
4750 filter_db_set(¤t_filter
, SCTP_DB
);
4751 } else if (strcmp(p
, "raw") == 0) {
4752 filter_db_set(¤t_filter
, RAW_DB
);
4753 } else if (strcmp(p
, "unix") == 0) {
4754 filter_db_set(¤t_filter
, UNIX_ST_DB
);
4755 filter_db_set(¤t_filter
, UNIX_DG_DB
);
4756 filter_db_set(¤t_filter
, UNIX_SQ_DB
);
4757 } else if (strcasecmp(p
, "unix_stream") == 0 ||
4758 strcmp(p
, "u_str") == 0) {
4759 filter_db_set(¤t_filter
, UNIX_ST_DB
);
4760 } else if (strcasecmp(p
, "unix_dgram") == 0 ||
4761 strcmp(p
, "u_dgr") == 0) {
4762 filter_db_set(¤t_filter
, UNIX_DG_DB
);
4763 } else if (strcasecmp(p
, "unix_seqpacket") == 0 ||
4764 strcmp(p
, "u_seq") == 0) {
4765 filter_db_set(¤t_filter
, UNIX_SQ_DB
);
4766 } else if (strcmp(p
, "packet") == 0) {
4767 filter_db_set(¤t_filter
, PACKET_R_DB
);
4768 filter_db_set(¤t_filter
, PACKET_DG_DB
);
4769 } else if (strcmp(p
, "packet_raw") == 0 ||
4770 strcmp(p
, "p_raw") == 0) {
4771 filter_db_set(¤t_filter
, PACKET_R_DB
);
4772 } else if (strcmp(p
, "packet_dgram") == 0 ||
4773 strcmp(p
, "p_dgr") == 0) {
4774 filter_db_set(¤t_filter
, PACKET_DG_DB
);
4775 } else if (strcmp(p
, "netlink") == 0) {
4776 filter_db_set(¤t_filter
, NETLINK_DB
);
4777 } else if (strcmp(p
, "vsock") == 0) {
4778 filter_db_set(¤t_filter
, VSOCK_ST_DB
);
4779 filter_db_set(¤t_filter
, VSOCK_DG_DB
);
4780 } else if (strcmp(p
, "vsock_stream") == 0 ||
4781 strcmp(p
, "v_str") == 0) {
4782 filter_db_set(¤t_filter
, VSOCK_ST_DB
);
4783 } else if (strcmp(p
, "vsock_dgram") == 0 ||
4784 strcmp(p
, "v_dgr") == 0) {
4785 filter_db_set(¤t_filter
, VSOCK_DG_DB
);
4787 fprintf(stderr
, "ss: \"%s\" is illegal socket table id\n", p
);
4798 dump_tcpdiag
= optarg
;
4802 fprintf(stderr
, "More than one filter file\n");
4805 if (optarg
[0] == '-')
4808 filter_fp
= fopen(optarg
, "r");
4810 perror("fopen filter file");
4816 printf("ss utility, iproute2-ss%s\n", SNAPSHOT
);
4822 if (is_selinux_enabled() <= 0) {
4823 fprintf(stderr
, "ss: SELinux is not enabled.\n");
4827 user_ent_hash_build();
4830 if (netns_switch(optarg
))
4834 current_filter
.kill
= 1;
4852 if (do_default
&& argc
== 0)
4857 if (strcmp(*argv
, "state") == 0) {
4861 state_filter
|= scan_state(*argv
);
4863 } else if (strcmp(*argv
, "exclude") == 0 ||
4864 strcmp(*argv
, "excl") == 0) {
4867 state_filter
= SS_ALL
;
4868 state_filter
&= ~scan_state(*argv
);
4877 state_filter
= state_filter
? state_filter
: SS_CONN
;
4878 filter_default_dbs(¤t_filter
);
4881 filter_states_set(¤t_filter
, state_filter
);
4882 filter_merge_defaults(¤t_filter
);
4884 if (resolve_services
&& resolve_hosts
&&
4885 (current_filter
.dbs
& (UNIX_DBM
|INET_L4_DBM
)))
4886 init_service_resolver();
4888 if (current_filter
.dbs
== 0) {
4889 fprintf(stderr
, "ss: no socket tables to show with such filter.\n");
4892 if (current_filter
.families
== 0) {
4893 fprintf(stderr
, "ss: no families to show with such filter.\n");
4896 if (current_filter
.states
== 0) {
4897 fprintf(stderr
, "ss: no socket states to show with such filter.\n");
4902 FILE *dump_fp
= stdout
;
4904 if (!(current_filter
.dbs
& (1<<TCP_DB
))) {
4905 fprintf(stderr
, "ss: tcpdiag dump requested and no tcp in filter.\n");
4908 if (dump_tcpdiag
[0] != '-') {
4909 dump_fp
= fopen(dump_tcpdiag
, "w");
4910 if (!dump_tcpdiag
) {
4911 perror("fopen dump file");
4915 inet_show_netlink(¤t_filter
, dump_fp
, IPPROTO_TCP
);
4920 if (ssfilter_parse(¤t_filter
.f
, argc
, argv
, filter_fp
))
4923 if (!(current_filter
.dbs
& (current_filter
.dbs
- 1)))
4924 columns
[COL_NETID
].disabled
= 1;
4926 if (!(current_filter
.states
& (current_filter
.states
- 1)))
4927 columns
[COL_STATE
].disabled
= 1;
4929 if (isatty(STDOUT_FILENO
)) {
4932 if (ioctl(STDOUT_FILENO
, TIOCGWINSZ
, &w
) != -1) {
4934 screen_width
= w
.ws_col
;
4944 exit(handle_follow_request(¤t_filter
));
4946 if (current_filter
.dbs
& (1<<NETLINK_DB
))
4947 netlink_show(¤t_filter
);
4948 if (current_filter
.dbs
& PACKET_DBM
)
4949 packet_show(¤t_filter
);
4950 if (current_filter
.dbs
& UNIX_DBM
)
4951 unix_show(¤t_filter
);
4952 if (current_filter
.dbs
& (1<<RAW_DB
))
4953 raw_show(¤t_filter
);
4954 if (current_filter
.dbs
& (1<<UDP_DB
))
4955 udp_show(¤t_filter
);
4956 if (current_filter
.dbs
& (1<<TCP_DB
))
4957 tcp_show(¤t_filter
);
4958 if (current_filter
.dbs
& (1<<DCCP_DB
))
4959 dccp_show(¤t_filter
);
4960 if (current_filter
.dbs
& (1<<SCTP_DB
))
4961 sctp_show(¤t_filter
);
4962 if (current_filter
.dbs
& VSOCK_DBM
)
4963 vsock_show(¤t_filter
);
4965 if (show_users
|| show_proc_ctx
|| show_sock_ctx
)
4968 render(screen_width
);