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>
48 #include <linux/net.h>
49 #include <linux/tipc.h>
50 #include <linux/tipc_netlink.h>
51 #include <linux/tipc_sockets_diag.h>
53 #define MAGIC_SEQ 123456
54 #define BUF_CHUNK (1024 * 1024)
55 #define LEN_ALIGN(x) (((x) + 1) & ~1)
57 #define DIAG_REQUEST(_req, _r) \
59 struct nlmsghdr nlh; \
63 .nlmsg_type = SOCK_DIAG_BY_FAMILY, \
64 .nlmsg_flags = NLM_F_ROOT|NLM_F_MATCH|NLM_F_REQUEST,\
65 .nlmsg_seq = MAGIC_SEQ, \
66 .nlmsg_len = sizeof(_req), \
71 #include <selinux/selinux.h>
73 /* Stubs for SELinux functions */
74 static int is_selinux_enabled(void)
79 static int getpidcon(pid_t pid
, char **context
)
85 static int getfilecon(char *path
, char **context
)
91 static int security_get_initial_context(char *name
, char **context
)
98 int resolve_services
= 1;
99 int preferred_family
= AF_UNSPEC
;
133 const enum col_align align
;
137 int width
; /* Calculated, including additional layout spacing */
138 int max_len
; /* Measured maximum field length in this column */
141 static struct column columns
[] = {
142 { ALIGN_LEFT
, "Netid", "", 0, 0, 0 },
143 { ALIGN_LEFT
, "State", " ", 0, 0, 0 },
144 { ALIGN_LEFT
, "Recv-Q", " ", 0, 0, 0 },
145 { ALIGN_LEFT
, "Send-Q", " ", 0, 0, 0 },
146 { ALIGN_RIGHT
, "Local Address:", " ", 0, 0, 0 },
147 { ALIGN_LEFT
, "Port", "", 0, 0, 0 },
148 { ALIGN_RIGHT
, "Peer Address:", " ", 0, 0, 0 },
149 { ALIGN_LEFT
, "Port", "", 0, 0, 0 },
150 { ALIGN_LEFT
, "", "", 0, 0, 0 },
153 static struct column
*current_field
= columns
;
155 /* Output buffer: chained chunks of BUF_CHUNK bytes. Each field is written to
156 * the buffer as a variable size token. A token consists of a 16 bits length
157 * field, followed by a string which is not NULL-terminated.
159 * A new chunk is allocated and linked when the current chunk doesn't have
160 * enough room to store the current token as a whole.
163 struct buf_chunk
*next
; /* Next chained chunk */
164 char *end
; /* Current end of content */
169 uint16_t len
; /* Data length, excluding length descriptor */
174 struct buf_token
*cur
; /* Position of current token in chunk */
175 struct buf_chunk
*head
; /* First chunk */
176 struct buf_chunk
*tail
; /* Current chunk */
179 static const char *TCP_PROTO
= "tcp";
180 static const char *SCTP_PROTO
= "sctp";
181 static const char *UDP_PROTO
= "udp";
182 static const char *RAW_PROTO
= "raw";
183 static const char *dg_proto
;
203 #define PACKET_DBM ((1<<PACKET_DG_DB)|(1<<PACKET_R_DB))
204 #define UNIX_DBM ((1<<UNIX_DG_DB)|(1<<UNIX_ST_DB)|(1<<UNIX_SQ_DB))
205 #define ALL_DB ((1<<MAX_DB)-1)
206 #define INET_L4_DBM ((1<<TCP_DB)|(1<<UDP_DB)|(1<<DCCP_DB)|(1<<SCTP_DB))
207 #define INET_DBM (INET_L4_DBM | (1<<RAW_DB))
208 #define VSOCK_DBM ((1<<VSOCK_ST_DB)|(1<<VSOCK_DG_DB))
227 SCTP_STATE_CLOSED
= 0,
228 SCTP_STATE_COOKIE_WAIT
= 1,
229 SCTP_STATE_COOKIE_ECHOED
= 2,
230 SCTP_STATE_ESTABLISHED
= 3,
231 SCTP_STATE_SHUTDOWN_PENDING
= 4,
232 SCTP_STATE_SHUTDOWN_SENT
= 5,
233 SCTP_STATE_SHUTDOWN_RECEIVED
= 6,
234 SCTP_STATE_SHUTDOWN_ACK_SENT
= 7,
237 #define SS_ALL ((1 << SS_MAX) - 1)
238 #define SS_CONN (SS_ALL & ~((1<<SS_LISTEN)|(1<<SS_CLOSE)|(1<<SS_TIME_WAIT)|(1<<SS_SYN_RECV)))
239 #define TIPC_SS_CONN ((1<<SS_ESTABLISHED)|(1<<SS_LISTEN)|(1<<SS_CLOSE))
241 #include "ssfilter.h"
249 struct rtnl_handle
*rth_for_killing
;
252 #define FAMILY_MASK(family) ((uint64_t)1 << (family))
254 static const struct filter default_dbs
[MAX_DB
] = {
257 .families
= FAMILY_MASK(AF_INET
) | FAMILY_MASK(AF_INET6
),
261 .families
= FAMILY_MASK(AF_INET
) | FAMILY_MASK(AF_INET6
),
264 .states
= (1 << SS_ESTABLISHED
),
265 .families
= FAMILY_MASK(AF_INET
) | FAMILY_MASK(AF_INET6
),
268 .states
= (1 << SS_ESTABLISHED
),
269 .families
= FAMILY_MASK(AF_INET
) | FAMILY_MASK(AF_INET6
),
272 .states
= (1 << SS_CLOSE
),
273 .families
= FAMILY_MASK(AF_UNIX
),
277 .families
= FAMILY_MASK(AF_UNIX
),
281 .families
= FAMILY_MASK(AF_UNIX
),
284 .states
= (1 << SS_CLOSE
),
285 .families
= FAMILY_MASK(AF_PACKET
),
288 .states
= (1 << SS_CLOSE
),
289 .families
= FAMILY_MASK(AF_PACKET
),
292 .states
= (1 << SS_CLOSE
),
293 .families
= FAMILY_MASK(AF_NETLINK
),
297 .families
= FAMILY_MASK(AF_INET
) | FAMILY_MASK(AF_INET6
),
301 .families
= FAMILY_MASK(AF_VSOCK
),
305 .families
= FAMILY_MASK(AF_VSOCK
),
308 .states
= TIPC_SS_CONN
,
309 .families
= FAMILY_MASK(AF_TIPC
),
313 static const struct filter default_afs
[AF_MAX
] = {
328 .states
= (1 << SS_CLOSE
),
331 .dbs
= (1 << NETLINK_DB
),
332 .states
= (1 << SS_CLOSE
),
339 .dbs
= (1 << TIPC_DB
),
340 .states
= TIPC_SS_CONN
,
344 static int do_default
= 1;
345 static struct filter current_filter
;
347 static void filter_db_set(struct filter
*f
, int db
, bool enable
)
350 f
->states
|= default_dbs
[db
].states
;
353 f
->dbs
&= ~(1 << db
);
358 static int filter_db_parse(struct filter
*f
, const char *s
)
364 #define ENTRY(name, ...) { #name, { __VA_ARGS__, MAX_DB } }
365 ENTRY(all
, UDP_DB
, DCCP_DB
, TCP_DB
, RAW_DB
,
366 UNIX_ST_DB
, UNIX_DG_DB
, UNIX_SQ_DB
,
367 PACKET_R_DB
, PACKET_DG_DB
, NETLINK_DB
,
368 SCTP_DB
, VSOCK_ST_DB
, VSOCK_DG_DB
),
369 ENTRY(inet
, UDP_DB
, DCCP_DB
, TCP_DB
, SCTP_DB
, RAW_DB
),
371 ENTRY(dccp
, DCCP_DB
),
373 ENTRY(sctp
, SCTP_DB
),
375 ENTRY(unix
, UNIX_ST_DB
, UNIX_DG_DB
, UNIX_SQ_DB
),
376 ENTRY(unix_stream
, UNIX_ST_DB
),
377 ENTRY(u_str
, UNIX_ST_DB
), /* alias for unix_stream */
378 ENTRY(unix_dgram
, UNIX_DG_DB
),
379 ENTRY(u_dgr
, UNIX_DG_DB
), /* alias for unix_dgram */
380 ENTRY(unix_seqpacket
, UNIX_SQ_DB
),
381 ENTRY(u_seq
, UNIX_SQ_DB
), /* alias for unix_seqpacket */
382 ENTRY(packet
, PACKET_R_DB
, PACKET_DG_DB
),
383 ENTRY(packet_raw
, PACKET_R_DB
),
384 ENTRY(p_raw
, PACKET_R_DB
), /* alias for packet_raw */
385 ENTRY(packet_dgram
, PACKET_DG_DB
),
386 ENTRY(p_dgr
, PACKET_DG_DB
), /* alias for packet_dgram */
387 ENTRY(netlink
, NETLINK_DB
),
388 ENTRY(vsock
, VSOCK_ST_DB
, VSOCK_DG_DB
),
389 ENTRY(vsock_stream
, VSOCK_ST_DB
),
390 ENTRY(v_str
, VSOCK_ST_DB
), /* alias for vsock_stream */
391 ENTRY(vsock_dgram
, VSOCK_DG_DB
),
392 ENTRY(v_dgr
, VSOCK_DG_DB
), /* alias for vsock_dgram */
403 for (i
= 0; i
< ARRAY_SIZE(db_name_tbl
); i
++) {
404 if (strcmp(s
, db_name_tbl
[i
].name
))
406 for (dbp
= db_name_tbl
[i
].dbs
; *dbp
!= MAX_DB
; dbp
++)
407 filter_db_set(f
, *dbp
, enable
);
413 static void filter_af_set(struct filter
*f
, int af
)
415 f
->states
|= default_afs
[af
].states
;
416 f
->families
|= FAMILY_MASK(af
);
418 preferred_family
= af
;
421 static int filter_af_get(struct filter
*f
, int af
)
423 return !!(f
->families
& FAMILY_MASK(af
));
426 static void filter_states_set(struct filter
*f
, int states
)
432 static void filter_merge_defaults(struct filter
*f
)
437 for (db
= 0; db
< MAX_DB
; db
++) {
438 if (!(f
->dbs
& (1 << db
)))
441 if (!(default_dbs
[db
].families
& f
->families
))
442 f
->families
|= default_dbs
[db
].families
;
444 for (af
= 0; af
< AF_MAX
; af
++) {
445 if (!(f
->families
& FAMILY_MASK(af
)))
448 if (!(default_afs
[af
].dbs
& f
->dbs
))
449 f
->dbs
|= default_afs
[af
].dbs
;
453 static FILE *generic_proc_open(const char *env
, const char *name
)
455 const char *p
= getenv(env
);
459 p
= getenv("PROC_ROOT") ? : "/proc";
460 snprintf(store
, sizeof(store
)-1, "%s/%s", p
, name
);
464 return fopen(p
, "r");
466 #define net_tcp_open() generic_proc_open("PROC_NET_TCP", "net/tcp")
467 #define net_tcp6_open() generic_proc_open("PROC_NET_TCP6", "net/tcp6")
468 #define net_udp_open() generic_proc_open("PROC_NET_UDP", "net/udp")
469 #define net_udp6_open() generic_proc_open("PROC_NET_UDP6", "net/udp6")
470 #define net_raw_open() generic_proc_open("PROC_NET_RAW", "net/raw")
471 #define net_raw6_open() generic_proc_open("PROC_NET_RAW6", "net/raw6")
472 #define net_unix_open() generic_proc_open("PROC_NET_UNIX", "net/unix")
473 #define net_packet_open() generic_proc_open("PROC_NET_PACKET", \
475 #define net_netlink_open() generic_proc_open("PROC_NET_NETLINK", \
477 #define net_sockstat_open() generic_proc_open("PROC_NET_SOCKSTAT", \
479 #define net_sockstat6_open() generic_proc_open("PROC_NET_SOCKSTAT6", \
481 #define net_snmp_open() generic_proc_open("PROC_NET_SNMP", "net/snmp")
482 #define ephemeral_ports_open() generic_proc_open("PROC_IP_LOCAL_PORT_RANGE", \
483 "sys/net/ipv4/ip_local_port_range")
486 struct user_ent
*next
;
495 #define USER_ENT_HASH_SIZE 256
496 struct user_ent
*user_ent_hash
[USER_ENT_HASH_SIZE
];
498 static int user_ent_hashfn(unsigned int ino
)
500 int val
= (ino
>> 24) ^ (ino
>> 16) ^ (ino
>> 8) ^ ino
;
502 return val
& (USER_ENT_HASH_SIZE
- 1);
505 static void user_ent_add(unsigned int ino
, char *process
,
510 struct user_ent
*p
, **pp
;
512 p
= malloc(sizeof(struct user_ent
));
514 fprintf(stderr
, "ss: failed to malloc buffer\n");
521 p
->process
= strdup(process
);
522 p
->process_ctx
= strdup(proc_ctx
);
523 p
->socket_ctx
= strdup(sock_ctx
);
525 pp
= &user_ent_hash
[user_ent_hashfn(ino
)];
530 static void user_ent_destroy(void)
532 struct user_ent
*p
, *p_next
;
535 while (cnt
!= USER_ENT_HASH_SIZE
) {
536 p
= user_ent_hash
[cnt
];
539 free(p
->process_ctx
);
549 static void user_ent_hash_build(void)
551 const char *root
= getenv("PROC_ROOT") ? : "/proc/";
558 const char *no_ctx
= "unavailable";
559 static int user_ent_hash_build_init
;
561 /* If show_users & show_proc_ctx set only do this once */
562 if (user_ent_hash_build_init
!= 0)
565 user_ent_hash_build_init
= 1;
567 strlcpy(name
, root
, sizeof(name
));
569 if (strlen(name
) == 0 || name
[strlen(name
)-1] != '/')
572 nameoff
= strlen(name
);
578 while ((d
= readdir(dir
)) != NULL
) {
586 if (sscanf(d
->d_name
, "%d%c", &pid
, &crap
) != 1)
589 if (getpidcon(pid
, &pid_context
) != 0)
590 pid_context
= strdup(no_ctx
);
592 snprintf(name
+ nameoff
, sizeof(name
) - nameoff
, "%d/fd/", pid
);
594 if ((dir1
= opendir(name
)) == NULL
) {
602 while ((d1
= readdir(dir1
)) != NULL
) {
603 const char *pattern
= "socket:[";
610 if (sscanf(d1
->d_name
, "%d%c", &fd
, &crap
) != 1)
613 snprintf(name
+pos
, sizeof(name
) - pos
, "%d", fd
);
615 link_len
= readlink(name
, lnk
, sizeof(lnk
)-1);
618 lnk
[link_len
] = '\0';
620 if (strncmp(lnk
, pattern
, strlen(pattern
)))
623 sscanf(lnk
, "socket:[%u]", &ino
);
625 snprintf(tmp
, sizeof(tmp
), "%s/%d/fd/%s",
626 root
, pid
, d1
->d_name
);
628 if (getfilecon(tmp
, &sock_context
) <= 0)
629 sock_context
= strdup(no_ctx
);
634 snprintf(tmp
, sizeof(tmp
), "%s/%d/stat",
636 if ((fp
= fopen(tmp
, "r")) != NULL
) {
637 if (fscanf(fp
, "%*d (%[^)])", p
) < 1)
642 user_ent_add(ino
, p
, pid
, fd
,
643 pid_context
, sock_context
);
658 #define ENTRY_BUF_SIZE 512
659 static int find_entry(unsigned int ino
, char **buf
, int type
)
665 int len
, new_buf_len
;
672 p
= user_ent_hash
[user_ent_hashfn(ino
)];
679 ptr
= *buf
+ buf_used
;
682 len
= snprintf(ptr
, buf_len
- buf_used
,
683 "(\"%s\",pid=%d,fd=%d),",
684 p
->process
, p
->pid
, p
->fd
);
687 len
= snprintf(ptr
, buf_len
- buf_used
,
688 "(\"%s\",pid=%d,proc_ctx=%s,fd=%d),",
690 p
->process_ctx
, p
->fd
);
693 len
= snprintf(ptr
, buf_len
- buf_used
,
694 "(\"%s\",pid=%d,proc_ctx=%s,fd=%d,sock_ctx=%s),",
696 p
->process_ctx
, p
->fd
,
700 fprintf(stderr
, "ss: invalid type: %d\n", type
);
704 if (len
< 0 || len
>= buf_len
- buf_used
) {
705 new_buf_len
= buf_len
+ ENTRY_BUF_SIZE
;
706 new_buf
= realloc(*buf
, new_buf_len
);
708 fprintf(stderr
, "ss: failed to malloc buffer\n");
712 buf_len
= new_buf_len
;
724 ptr
= *buf
+ buf_used
;
730 static unsigned long long cookie_sk_get(const uint32_t *cookie
)
732 return (((unsigned long long)cookie
[1] << 31) << 1) | cookie
[0];
735 static const char *sctp_sstate_name
[] = {
736 [SCTP_STATE_CLOSED
] = "CLOSED",
737 [SCTP_STATE_COOKIE_WAIT
] = "COOKIE_WAIT",
738 [SCTP_STATE_COOKIE_ECHOED
] = "COOKIE_ECHOED",
739 [SCTP_STATE_ESTABLISHED
] = "ESTAB",
740 [SCTP_STATE_SHUTDOWN_PENDING
] = "SHUTDOWN_PENDING",
741 [SCTP_STATE_SHUTDOWN_SENT
] = "SHUTDOWN_SENT",
742 [SCTP_STATE_SHUTDOWN_RECEIVED
] = "SHUTDOWN_RECEIVED",
743 [SCTP_STATE_SHUTDOWN_ACK_SENT
] = "ACK_SENT",
746 static const char * const stype_nameg
[] = {
748 [SOCK_STREAM
] = "STREAM",
749 [SOCK_DGRAM
] = "DGRAM",
751 [SOCK_SEQPACKET
] = "SEQPACKET",
755 struct sockstat
*next
;
769 unsigned long long sk
;
776 unsigned int ce_state
;
786 unsigned int timeout
;
789 double rto
, ato
, rtt
, rttvar
;
790 int qack
, ssthresh
, backoff
;
799 unsigned int lastsnd
;
800 unsigned int lastrcv
;
801 unsigned int lastack
;
803 double pacing_rate_max
;
804 double delivery_rate
;
805 unsigned long long bytes_acked
;
806 unsigned long long bytes_received
;
807 unsigned int segs_out
;
808 unsigned int segs_in
;
809 unsigned int data_segs_out
;
810 unsigned int data_segs_in
;
811 unsigned int unacked
;
812 unsigned int retrans
;
813 unsigned int retrans_total
;
816 unsigned int fackets
;
817 unsigned int reordering
;
818 unsigned int not_sent
;
822 unsigned int rcv_ssthresh
;
823 unsigned long long busy_time
;
824 unsigned long long rwnd_limited
;
825 unsigned long long sndbuf_limited
;
829 bool has_ecnseen_opt
;
830 bool has_fastopen_opt
;
833 struct dctcpstat
*dctcp
;
834 struct tcp_bbr_info
*bbr_info
;
837 /* SCTP assocs share the same inode number with their parent endpoint. So if we
838 * have seen the inode number before, it must be an assoc instead of the next
840 static bool is_sctp_assoc(struct sockstat
*s
, const char *sock_name
)
842 if (strcmp(sock_name
, "sctp"))
844 if (!sctp_ino
|| sctp_ino
!= s
->ino
)
849 static const char *unix_netid_name(int type
)
862 static const char *proto_name(int protocol
)
882 static const char *vsock_netid_name(int type
)
894 static const char *tipc_netid_name(int type
)
910 /* Allocate and initialize a new buffer chunk */
911 static struct buf_chunk
*buf_chunk_new(void)
913 struct buf_chunk
*new = malloc(BUF_CHUNK
);
920 /* This is also the last block */
923 /* Next token will be stored at the beginning of chunk data area, and
924 * its initial length is zero.
926 buffer
.cur
= (struct buf_token
*)new->data
;
929 new->end
= buffer
.cur
->data
;
934 /* Return available tail room in given chunk */
935 static int buf_chunk_avail(struct buf_chunk
*chunk
)
937 return BUF_CHUNK
- offsetof(struct buf_chunk
, data
) -
938 (chunk
->end
- chunk
->data
);
941 /* Update end pointer and token length, link new chunk if we hit the end of the
942 * current one. Return -EAGAIN if we got a new chunk, caller has to print again.
944 static int buf_update(int len
)
946 struct buf_chunk
*chunk
= buffer
.tail
;
947 struct buf_token
*t
= buffer
.cur
;
949 /* Claim success if new content fits in the current chunk, and anyway
950 * if this is the first token in the chunk: in the latter case,
951 * allocating a new chunk won't help, so we'll just cut the output.
953 if ((len
< buf_chunk_avail(chunk
) && len
!= -1 /* glibc < 2.0.6 */) ||
954 t
== (struct buf_token
*)chunk
->data
) {
955 len
= min(len
, buf_chunk_avail(chunk
));
957 /* Total field length can't exceed 2^16 bytes, cut as needed */
958 len
= min(len
, USHRT_MAX
- t
->len
);
965 /* Content truncated, time to allocate more */
966 chunk
->next
= buf_chunk_new();
968 /* Copy current token over to new chunk, including length descriptor */
969 memcpy(chunk
->next
->data
, t
, sizeof(t
->len
) + t
->len
);
970 chunk
->next
->end
+= t
->len
;
972 /* Discard partially written field in old chunk */
973 chunk
->end
-= t
->len
+ sizeof(t
->len
);
978 /* Append content to buffer as part of the current field */
979 static void out(const char *fmt
, ...)
981 struct column
*f
= current_field
;
990 buffer
.head
= buf_chunk_new();
992 again
: /* Append to buffer: if we have a new chunk, print again */
994 pos
= buffer
.cur
->data
+ buffer
.cur
->len
;
997 /* Limit to tail room. If we hit the limit, buf_update() will tell us */
998 len
= vsnprintf(pos
, buf_chunk_avail(buffer
.tail
), fmt
, args
);
1001 if (buf_update(len
))
1005 static int print_left_spacing(struct column
*f
, int stored
, int printed
)
1009 if (!f
->width
|| f
->align
== ALIGN_LEFT
)
1012 s
= f
->width
- stored
- printed
;
1013 if (f
->align
== ALIGN_CENTER
)
1014 /* If count of total spacing is odd, shift right by one */
1018 return printf("%*c", s
, ' ');
1023 static void print_right_spacing(struct column
*f
, int printed
)
1027 if (!f
->width
|| f
->align
== ALIGN_RIGHT
)
1030 s
= f
->width
- printed
;
1031 if (f
->align
== ALIGN_CENTER
)
1035 printf("%*c", s
, ' ');
1038 /* Done with field: update buffer pointer, start new token after current one */
1039 static void field_flush(struct column
*f
)
1041 struct buf_chunk
*chunk
;
1047 chunk
= buffer
.tail
;
1048 pad
= buffer
.cur
->len
% 2;
1050 if (buffer
.cur
->len
> f
->max_len
)
1051 f
->max_len
= buffer
.cur
->len
;
1053 /* We need a new chunk if we can't store the next length descriptor.
1054 * Mind the gap between end of previous token and next aligned position
1055 * for length descriptor.
1057 if (buf_chunk_avail(chunk
) - pad
< sizeof(buffer
.cur
->len
)) {
1059 chunk
->next
= buf_chunk_new();
1063 buffer
.cur
= (struct buf_token
*)(buffer
.cur
->data
+
1064 LEN_ALIGN(buffer
.cur
->len
));
1065 buffer
.cur
->len
= 0;
1066 buffer
.tail
->end
= buffer
.cur
->data
;
1069 static int field_is_last(struct column
*f
)
1071 return f
- columns
== COL_MAX
- 1;
1074 static void field_next(void)
1076 field_flush(current_field
);
1078 if (field_is_last(current_field
))
1079 current_field
= columns
;
1084 /* Walk through fields and flush them until we reach the desired one */
1085 static void field_set(enum col_id id
)
1087 while (id
!= current_field
- columns
)
1091 /* Print header for all non-empty columns */
1092 static void print_header(void)
1094 while (!field_is_last(current_field
)) {
1095 if (!current_field
->disabled
)
1096 out(current_field
->header
);
1101 /* Get the next available token in the buffer starting from the current token */
1102 static struct buf_token
*buf_token_next(struct buf_token
*cur
)
1104 struct buf_chunk
*chunk
= buffer
.tail
;
1106 /* If we reached the end of chunk contents, get token from next chunk */
1107 if (cur
->data
+ LEN_ALIGN(cur
->len
) == chunk
->end
) {
1108 buffer
.tail
= chunk
= chunk
->next
;
1109 return chunk
? (struct buf_token
*)chunk
->data
: NULL
;
1112 return (struct buf_token
*)(cur
->data
+ LEN_ALIGN(cur
->len
));
1115 /* Free up all allocated buffer chunks */
1116 static void buf_free_all(void)
1118 struct buf_chunk
*tmp
;
1120 for (buffer
.tail
= buffer
.head
; buffer
.tail
; ) {
1122 buffer
.tail
= buffer
.tail
->next
;
1128 /* Get current screen width, default to 80 columns if TIOCGWINSZ fails */
1129 static int render_screen_width(void)
1133 if (isatty(STDOUT_FILENO
)) {
1136 if (ioctl(STDOUT_FILENO
, TIOCGWINSZ
, &w
) != -1) {
1145 /* Calculate column width from contents length. If columns don't fit on one
1146 * line, break them into the least possible amount of lines and keep them
1147 * aligned across lines. Available screen space is equally spread between fields
1148 * as additional spacing.
1150 static void render_calc_width(void)
1152 int screen_width
= render_screen_width();
1153 struct column
*c
, *eol
= columns
- 1;
1154 int first
, len
= 0, linecols
= 0;
1156 /* First pass: set width for each column to measured content length */
1157 for (first
= 1, c
= columns
; c
- columns
< COL_MAX
; c
++) {
1161 if (!first
&& c
->max_len
)
1162 c
->width
= c
->max_len
+ strlen(c
->ldelim
);
1164 c
->width
= c
->max_len
;
1166 /* But don't exceed screen size. If we exceed the screen size
1167 * for even a single field, it will just start on a line of its
1168 * own and then naturally wrap.
1170 c
->width
= min(c
->width
, screen_width
);
1176 /* Second pass: find out newlines and distribute available spacing */
1177 for (c
= columns
; c
- columns
< COL_MAX
; c
++) {
1178 int pad
, spacing
, rem
, last
;
1187 for (last
= 1, tmp
= c
+ 1; tmp
- columns
< COL_MAX
; tmp
++) {
1194 if (!last
&& len
< screen_width
) {
1195 /* Columns fit on screen so far, nothing to do yet */
1199 if (len
== screen_width
) {
1200 /* Exact fit, just start with new line */
1204 if (len
> screen_width
) {
1205 /* Screen width exceeded: go back one column */
1211 /* Distribute remaining space to columns on this line */
1212 pad
= screen_width
- len
;
1213 spacing
= pad
/ linecols
;
1214 rem
= pad
% linecols
;
1215 for (tmp
= c
; tmp
> eol
; tmp
--) {
1219 tmp
->width
+= spacing
;
1227 /* Line break: reset line counters, mark end-of-line */
1234 /* Render buffered output with spacing and delimiters, then free up buffers */
1235 static void render(void)
1237 struct buf_token
*token
;
1238 int printed
, line_started
= 0;
1244 token
= (struct buf_token
*)buffer
.head
->data
;
1246 /* Ensure end alignment of last token, it wasn't necessarily flushed */
1247 buffer
.tail
->end
+= buffer
.cur
->len
% 2;
1249 render_calc_width();
1251 /* Rewind and replay */
1252 buffer
.tail
= buffer
.head
;
1259 /* Print left delimiter only if we already started a line */
1261 printed
= printf("%s", current_field
->ldelim
);
1265 /* Print field content from token data with spacing */
1266 printed
+= print_left_spacing(f
, token
->len
, printed
);
1267 printed
+= fwrite(token
->data
, 1, token
->len
, stdout
);
1268 print_right_spacing(f
, printed
);
1270 /* Go to next non-empty field, deal with end-of-line */
1272 if (field_is_last(f
)) {
1279 } while (f
->disabled
);
1281 token
= buf_token_next(token
);
1285 current_field
= columns
;
1288 static void sock_state_print(struct sockstat
*s
)
1290 const char *sock_name
;
1291 static const char * const sstate_name
[] = {
1293 [SS_ESTABLISHED
] = "ESTAB",
1294 [SS_SYN_SENT
] = "SYN-SENT",
1295 [SS_SYN_RECV
] = "SYN-RECV",
1296 [SS_FIN_WAIT1
] = "FIN-WAIT-1",
1297 [SS_FIN_WAIT2
] = "FIN-WAIT-2",
1298 [SS_TIME_WAIT
] = "TIME-WAIT",
1299 [SS_CLOSE
] = "UNCONN",
1300 [SS_CLOSE_WAIT
] = "CLOSE-WAIT",
1301 [SS_LAST_ACK
] = "LAST-ACK",
1302 [SS_LISTEN
] = "LISTEN",
1303 [SS_CLOSING
] = "CLOSING",
1306 switch (s
->local
.family
) {
1308 sock_name
= unix_netid_name(s
->type
);
1312 sock_name
= proto_name(s
->type
);
1315 sock_name
= s
->type
== SOCK_RAW
? "p_raw" : "p_dgr";
1321 sock_name
= tipc_netid_name(s
->type
);
1324 sock_name
= vsock_netid_name(s
->type
);
1327 sock_name
= "unknown";
1330 if (is_sctp_assoc(s
, sock_name
)) {
1331 field_set(COL_STATE
); /* Empty Netid field */
1332 out("`- %s", sctp_sstate_name
[s
->state
]);
1334 field_set(COL_NETID
);
1335 out("%s", sock_name
);
1336 field_set(COL_STATE
);
1337 out("%s", sstate_name
[s
->state
]);
1340 field_set(COL_RECVQ
);
1342 field_set(COL_SENDQ
);
1344 field_set(COL_ADDR
);
1347 static void sock_details_print(struct sockstat
*s
)
1350 out(" uid:%u", s
->uid
);
1352 out(" ino:%u", s
->ino
);
1353 out(" sk:%llx", s
->sk
);
1356 out(" fwmark:0x%x", s
->mark
);
1359 static void sock_addr_print(const char *addr
, char *delim
, const char *port
,
1363 out("%s" "%%" "%s%s", addr
, ifname
, delim
);
1365 out("%s%s", addr
, delim
);
1372 static const char *print_ms_timer(unsigned int timeout
)
1374 static char buf
[64];
1375 int secs
, msecs
, minutes
;
1377 secs
= timeout
/1000;
1380 msecs
= timeout
%1000;
1384 snprintf(buf
, sizeof(buf
)-16, "%dmin", minutes
);
1391 sprintf(buf
+strlen(buf
), "%d%s", secs
, msecs
? "." : "sec");
1394 sprintf(buf
+strlen(buf
), "%03dms", msecs
);
1399 struct scache
*next
;
1405 struct scache
*rlist
;
1407 static void init_service_resolver(void)
1410 FILE *fp
= popen("/usr/sbin/rpcinfo -p 2>/dev/null", "r");
1415 if (!fgets(buf
, sizeof(buf
), fp
)) {
1419 while (fgets(buf
, sizeof(buf
), fp
) != NULL
) {
1420 unsigned int progn
, port
;
1421 char proto
[128], prog
[128] = "rpc.";
1424 if (sscanf(buf
, "%u %*d %s %u %s",
1425 &progn
, proto
, &port
, prog
+4) != 4)
1428 if (!(c
= malloc(sizeof(*c
))))
1432 c
->name
= strdup(prog
);
1433 if (strcmp(proto
, TCP_PROTO
) == 0)
1434 c
->proto
= TCP_PROTO
;
1435 else if (strcmp(proto
, UDP_PROTO
) == 0)
1436 c
->proto
= UDP_PROTO
;
1437 else if (strcmp(proto
, SCTP_PROTO
) == 0)
1438 c
->proto
= SCTP_PROTO
;
1447 /* Even do not try default linux ephemeral port ranges:
1448 * default /etc/services contains so much of useless crap
1449 * wouldbe "allocated" to this area that resolution
1450 * is really harmful. I shrug each time when seeing
1451 * "socks" or "cfinger" in dumps.
1453 static int is_ephemeral(int port
)
1455 static int min
= 0, max
;
1458 FILE *f
= ephemeral_ports_open();
1460 if (!f
|| fscanf(f
, "%d %d", &min
, &max
) < 2) {
1467 return port
>= min
&& port
<= max
;
1471 static const char *__resolve_service(int port
)
1475 for (c
= rlist
; c
; c
= c
->next
) {
1476 if (c
->port
== port
&& c
->proto
== dg_proto
)
1480 if (!is_ephemeral(port
)) {
1481 static int notfirst
;
1488 se
= getservbyport(htons(port
), dg_proto
);
1496 #define SCACHE_BUCKETS 1024
1497 static struct scache
*cache_htab
[SCACHE_BUCKETS
];
1499 static const char *resolve_service(int port
)
1501 static char buf
[128];
1512 if (!resolve_services
)
1515 if (dg_proto
== RAW_PROTO
)
1516 return inet_proto_n2a(port
, buf
, sizeof(buf
));
1519 hash
= (port
^(((unsigned long)dg_proto
)>>2)) % SCACHE_BUCKETS
;
1521 for (c
= cache_htab
[hash
]; c
; c
= c
->next
) {
1522 if (c
->port
== port
&& c
->proto
== dg_proto
)
1526 c
= malloc(sizeof(*c
));
1529 res
= __resolve_service(port
);
1531 c
->name
= res
? strdup(res
) : NULL
;
1532 c
->proto
= dg_proto
;
1533 c
->next
= cache_htab
[hash
];
1534 cache_htab
[hash
] = c
;
1541 sprintf(buf
, "%u", port
);
1545 static void inet_addr_print(const inet_prefix
*a
, int port
,
1546 unsigned int ifindex
, bool v6only
)
1549 const char *ap
= buf
;
1550 const char *ifname
= NULL
;
1552 if (a
->family
== AF_INET
) {
1553 ap
= format_host(AF_INET
, 4, a
->data
);
1556 !memcmp(a
->data
, &in6addr_any
, sizeof(in6addr_any
))) {
1560 ap
= format_host(a
->family
, 16, a
->data
);
1562 /* Numeric IPv6 addresses should be bracketed */
1563 if (strchr(ap
, ':')) {
1564 snprintf(buf
, sizeof(buf
),
1572 ifname
= ll_index_to_name(ifindex
);
1574 sock_addr_print(ap
, ":", resolve_service(port
), ifname
);
1583 struct aafilter
*next
;
1586 static int inet2_addr_match(const inet_prefix
*a
, const inet_prefix
*p
,
1589 if (!inet_addr_match(a
, p
, plen
))
1592 /* Cursed "v4 mapped" addresses: v4 mapped socket matches
1593 * pure IPv4 rule, but v4-mapped rule selects only v4-mapped
1595 if (p
->family
== AF_INET
&& a
->family
== AF_INET6
) {
1596 if (a
->data
[0] == 0 && a
->data
[1] == 0 &&
1597 a
->data
[2] == htonl(0xffff)) {
1598 inet_prefix tmp
= *a
;
1600 tmp
.data
[0] = a
->data
[3];
1601 return inet_addr_match(&tmp
, p
, plen
);
1607 static int unix_match(const inet_prefix
*a
, const inet_prefix
*p
)
1609 char *addr
, *pattern
;
1611 memcpy(&addr
, a
->data
, sizeof(addr
));
1612 memcpy(&pattern
, p
->data
, sizeof(pattern
));
1613 if (pattern
== NULL
)
1617 return !fnmatch(pattern
, addr
, 0);
1620 static int run_ssfilter(struct ssfilter
*f
, struct sockstat
*s
)
1625 if (s
->local
.family
== AF_UNIX
) {
1628 memcpy(&p
, s
->local
.data
, sizeof(p
));
1629 return p
== NULL
|| (p
[0] == '@' && strlen(p
) == 6 &&
1630 strspn(p
+1, "0123456789abcdef") == 5);
1632 if (s
->local
.family
== AF_PACKET
)
1633 return s
->lport
== 0 && s
->local
.data
[0] == 0;
1634 if (s
->local
.family
== AF_NETLINK
)
1635 return s
->lport
< 0;
1636 if (s
->local
.family
== AF_VSOCK
)
1637 return s
->lport
> 1023;
1639 return is_ephemeral(s
->lport
);
1643 struct aafilter
*a
= (void *)f
->pred
;
1645 if (a
->addr
.family
== AF_UNIX
)
1646 return unix_match(&s
->remote
, &a
->addr
);
1647 if (a
->port
!= -1 && a
->port
!= s
->rport
)
1649 if (a
->addr
.bitlen
) {
1651 if (!inet2_addr_match(&s
->remote
, &a
->addr
, a
->addr
.bitlen
))
1653 } while ((a
= a
->next
) != NULL
);
1660 struct aafilter
*a
= (void *)f
->pred
;
1662 if (a
->addr
.family
== AF_UNIX
)
1663 return unix_match(&s
->local
, &a
->addr
);
1664 if (a
->port
!= -1 && a
->port
!= s
->lport
)
1666 if (a
->addr
.bitlen
) {
1668 if (!inet2_addr_match(&s
->local
, &a
->addr
, a
->addr
.bitlen
))
1670 } while ((a
= a
->next
) != NULL
);
1677 struct aafilter
*a
= (void *)f
->pred
;
1679 return s
->rport
>= a
->port
;
1683 struct aafilter
*a
= (void *)f
->pred
;
1685 return s
->rport
<= a
->port
;
1689 struct aafilter
*a
= (void *)f
->pred
;
1691 return s
->lport
>= a
->port
;
1695 struct aafilter
*a
= (void *)f
->pred
;
1697 return s
->lport
<= a
->port
;
1701 struct aafilter
*a
= (void *)f
->pred
;
1703 return s
->iface
== a
->iface
;
1707 struct aafilter
*a
= (void *)f
->pred
;
1709 return (s
->mark
& a
->mask
) == a
->mark
;
1711 /* Yup. It is recursion. Sorry. */
1713 return run_ssfilter(f
->pred
, s
) && run_ssfilter(f
->post
, s
);
1715 return run_ssfilter(f
->pred
, s
) || run_ssfilter(f
->post
, s
);
1717 return !run_ssfilter(f
->pred
, s
);
1723 /* Relocate external jumps by reloc. */
1724 static void ssfilter_patch(char *a
, int len
, int reloc
)
1727 struct inet_diag_bc_op
*op
= (struct inet_diag_bc_op
*)a
;
1729 if (op
->no
== len
+4)
1738 static int ssfilter_bytecompile(struct ssfilter
*f
, char **bytecode
)
1743 if (!(*bytecode
= malloc(4))) abort();
1744 ((struct inet_diag_bc_op
*)*bytecode
)[0] = (struct inet_diag_bc_op
){ INET_DIAG_BC_AUTO
, 4, 8 };
1750 struct aafilter
*a
= (void *)f
->pred
;
1753 int code
= (f
->type
== SSF_DCOND
? INET_DIAG_BC_D_COND
: INET_DIAG_BC_S_COND
);
1756 for (b
= a
; b
; b
= b
->next
) {
1757 len
+= 4 + sizeof(struct inet_diag_hostcond
);
1758 if (a
->addr
.family
== AF_INET6
)
1765 if (!(ptr
= malloc(len
))) abort();
1767 for (b
= a
; b
; b
= b
->next
) {
1768 struct inet_diag_bc_op
*op
= (struct inet_diag_bc_op
*)ptr
;
1769 int alen
= (a
->addr
.family
== AF_INET6
? 16 : 4);
1770 int oplen
= alen
+ 4 + sizeof(struct inet_diag_hostcond
);
1771 struct inet_diag_hostcond
*cond
= (struct inet_diag_hostcond
*)(ptr
+4);
1773 *op
= (struct inet_diag_bc_op
){ code
, oplen
, oplen
+4 };
1774 cond
->family
= a
->addr
.family
;
1775 cond
->port
= a
->port
;
1776 cond
->prefix_len
= a
->addr
.bitlen
;
1777 memcpy(cond
->addr
, a
->addr
.data
, alen
);
1780 op
= (struct inet_diag_bc_op
*)ptr
;
1781 *op
= (struct inet_diag_bc_op
){ INET_DIAG_BC_JMP
, 4, len
- (ptr
-*bytecode
)};
1785 return ptr
- *bytecode
;
1789 struct aafilter
*x
= (void *)f
->pred
;
1791 if (!(*bytecode
= malloc(8))) abort();
1792 ((struct inet_diag_bc_op
*)*bytecode
)[0] = (struct inet_diag_bc_op
){ INET_DIAG_BC_D_GE
, 8, 12 };
1793 ((struct inet_diag_bc_op
*)*bytecode
)[1] = (struct inet_diag_bc_op
){ 0, 0, x
->port
};
1798 struct aafilter
*x
= (void *)f
->pred
;
1800 if (!(*bytecode
= malloc(8))) abort();
1801 ((struct inet_diag_bc_op
*)*bytecode
)[0] = (struct inet_diag_bc_op
){ INET_DIAG_BC_D_LE
, 8, 12 };
1802 ((struct inet_diag_bc_op
*)*bytecode
)[1] = (struct inet_diag_bc_op
){ 0, 0, x
->port
};
1807 struct aafilter
*x
= (void *)f
->pred
;
1809 if (!(*bytecode
= malloc(8))) abort();
1810 ((struct inet_diag_bc_op
*)*bytecode
)[0] = (struct inet_diag_bc_op
){ INET_DIAG_BC_S_GE
, 8, 12 };
1811 ((struct inet_diag_bc_op
*)*bytecode
)[1] = (struct inet_diag_bc_op
){ 0, 0, x
->port
};
1816 struct aafilter
*x
= (void *)f
->pred
;
1818 if (!(*bytecode
= malloc(8))) abort();
1819 ((struct inet_diag_bc_op
*)*bytecode
)[0] = (struct inet_diag_bc_op
){ INET_DIAG_BC_S_LE
, 8, 12 };
1820 ((struct inet_diag_bc_op
*)*bytecode
)[1] = (struct inet_diag_bc_op
){ 0, 0, x
->port
};
1826 char *a1
= NULL
, *a2
= NULL
, *a
;
1829 l1
= ssfilter_bytecompile(f
->pred
, &a1
);
1830 l2
= ssfilter_bytecompile(f
->post
, &a2
);
1836 if (!(a
= malloc(l1
+l2
))) abort();
1838 memcpy(a
+l1
, a2
, l2
);
1840 ssfilter_patch(a
, l1
, l2
);
1846 char *a1
= NULL
, *a2
= NULL
, *a
;
1849 l1
= ssfilter_bytecompile(f
->pred
, &a1
);
1850 l2
= ssfilter_bytecompile(f
->post
, &a2
);
1856 if (!(a
= malloc(l1
+l2
+4))) abort();
1858 memcpy(a
+l1
+4, a2
, l2
);
1860 *(struct inet_diag_bc_op
*)(a
+l1
) = (struct inet_diag_bc_op
){ INET_DIAG_BC_JMP
, 4, l2
+4 };
1866 char *a1
= NULL
, *a
;
1869 l1
= ssfilter_bytecompile(f
->pred
, &a1
);
1874 if (!(a
= malloc(l1
+4))) abort();
1877 *(struct inet_diag_bc_op
*)(a
+l1
) = (struct inet_diag_bc_op
){ INET_DIAG_BC_JMP
, 4, 8 };
1883 /* bytecompile for SSF_DEVCOND not supported yet */
1888 struct aafilter
*a
= (void *)f
->pred
;
1890 struct inet_diag_bc_op op
;
1891 struct inet_diag_markcond cond
;
1893 int inslen
= sizeof(struct instr
);
1895 if (!(*bytecode
= malloc(inslen
))) abort();
1896 ((struct instr
*)*bytecode
)[0] = (struct instr
) {
1897 { INET_DIAG_BC_MARK_COND
, inslen
, inslen
+ 4 },
1898 { a
->mark
, a
->mask
},
1908 static int remember_he(struct aafilter
*a
, struct hostent
*he
)
1910 char **ptr
= he
->h_addr_list
;
1914 if (he
->h_addrtype
== AF_INET
)
1916 else if (he
->h_addrtype
== AF_INET6
)
1922 struct aafilter
*b
= a
;
1924 if (a
->addr
.bitlen
) {
1925 if ((b
= malloc(sizeof(*b
))) == NULL
)
1930 memcpy(b
->addr
.data
, *ptr
, len
);
1931 b
->addr
.bytelen
= len
;
1932 b
->addr
.bitlen
= len
*8;
1933 b
->addr
.family
= he
->h_addrtype
;
1940 static int get_dns_host(struct aafilter
*a
, const char *addr
, int fam
)
1942 static int notfirst
;
1951 he
= gethostbyname2(addr
, fam
== AF_UNSPEC
? AF_INET
: fam
);
1953 cnt
= remember_he(a
, he
);
1954 if (fam
== AF_UNSPEC
) {
1955 he
= gethostbyname2(addr
, AF_INET6
);
1957 cnt
+= remember_he(a
, he
);
1962 static int xll_initted
;
1964 static void xll_init(void)
1966 struct rtnl_handle rth
;
1968 if (rtnl_open(&rth
, 0) < 0)
1976 static const char *xll_index_to_name(int index
)
1980 return ll_index_to_name(index
);
1983 static int xll_name_to_index(const char *dev
)
1987 return ll_name_to_index(dev
);
1990 void *parse_devcond(char *name
)
1992 struct aafilter a
= { .iface
= 0 };
1993 struct aafilter
*res
;
1995 a
.iface
= xll_name_to_index(name
);
2000 n
= strtoul(name
, &end
, 0);
2001 if (!end
|| end
== name
|| *end
|| n
> UINT_MAX
)
2007 res
= malloc(sizeof(*res
));
2013 static void vsock_set_inet_prefix(inet_prefix
*a
, __u32 cid
)
2016 .bytelen
= sizeof(cid
),
2019 memcpy(a
->data
, &cid
, sizeof(cid
));
2022 void *parse_hostcond(char *addr
, bool is_port
)
2025 struct aafilter a
= { .port
= -1 };
2026 struct aafilter
*res
;
2027 int fam
= preferred_family
;
2028 struct filter
*f
= ¤t_filter
;
2030 if (fam
== AF_UNIX
|| strncmp(addr
, "unix:", 5) == 0) {
2033 a
.addr
.family
= AF_UNIX
;
2034 if (strncmp(addr
, "unix:", 5) == 0)
2037 a
.addr
.bitlen
= 8*strlen(p
);
2038 memcpy(a
.addr
.data
, &p
, sizeof(p
));
2043 if (fam
== AF_PACKET
|| strncmp(addr
, "link:", 5) == 0) {
2044 a
.addr
.family
= AF_PACKET
;
2046 if (strncmp(addr
, "link:", 5) == 0)
2048 port
= strchr(addr
, ':');
2051 if (port
[1] && strcmp(port
+1, "*")) {
2052 if (get_integer(&a
.port
, port
+1, 0)) {
2053 if ((a
.port
= xll_name_to_index(port
+1)) <= 0)
2058 if (addr
[0] && strcmp(addr
, "*")) {
2062 if (ll_proto_a2n(&tmp
, addr
))
2064 a
.addr
.data
[0] = ntohs(tmp
);
2070 if (fam
== AF_NETLINK
|| strncmp(addr
, "netlink:", 8) == 0) {
2071 a
.addr
.family
= AF_NETLINK
;
2073 if (strncmp(addr
, "netlink:", 8) == 0)
2075 port
= strchr(addr
, ':');
2078 if (port
[1] && strcmp(port
+1, "*")) {
2079 if (get_integer(&a
.port
, port
+1, 0)) {
2080 if (strcmp(port
+1, "kernel") == 0)
2087 if (addr
[0] && strcmp(addr
, "*")) {
2089 if (nl_proto_a2n(&a
.addr
.data
[0], addr
) == -1)
2096 if (fam
== AF_VSOCK
|| strncmp(addr
, "vsock:", 6) == 0) {
2097 __u32 cid
= ~(__u32
)0;
2099 a
.addr
.family
= AF_VSOCK
;
2100 if (strncmp(addr
, "vsock:", 6) == 0)
2106 port
= strchr(addr
, ':');
2113 if (port
&& strcmp(port
, "*") &&
2114 get_u32((__u32
*)&a
.port
, port
, 0))
2117 if (addr
[0] && strcmp(addr
, "*")) {
2119 if (get_u32(&cid
, addr
, 0))
2122 vsock_set_inet_prefix(&a
.addr
, cid
);
2127 if (fam
== AF_INET
|| !strncmp(addr
, "inet:", 5)) {
2129 if (!strncmp(addr
, "inet:", 5))
2131 } else if (fam
== AF_INET6
|| !strncmp(addr
, "inet6:", 6)) {
2133 if (!strncmp(addr
, "inet6:", 6))
2137 /* URL-like literal [] */
2138 if (addr
[0] == '[') {
2140 if ((port
= strchr(addr
, ']')) == NULL
)
2143 } else if (addr
[0] == '*') {
2146 port
= strrchr(strchr(addr
, '/') ? : addr
, ':');
2152 if (port
&& *port
) {
2156 if (*port
&& *port
!= '*') {
2157 if (get_integer(&a
.port
, port
, 0)) {
2158 struct servent
*se1
= NULL
;
2159 struct servent
*se2
= NULL
;
2161 if (current_filter
.dbs
&(1<<UDP_DB
))
2162 se1
= getservbyname(port
, UDP_PROTO
);
2163 if (current_filter
.dbs
&(1<<TCP_DB
))
2164 se2
= getservbyname(port
, TCP_PROTO
);
2165 if (se1
&& se2
&& se1
->s_port
!= se2
->s_port
) {
2166 fprintf(stderr
, "Error: ambiguous port \"%s\".\n", port
);
2172 a
.port
= ntohs(se1
->s_port
);
2176 for (s
= rlist
; s
; s
= s
->next
) {
2177 if ((s
->proto
== UDP_PROTO
&&
2178 (current_filter
.dbs
&(1<<UDP_DB
))) ||
2179 (s
->proto
== TCP_PROTO
&&
2180 (current_filter
.dbs
&(1<<TCP_DB
)))) {
2181 if (s
->name
&& strcmp(s
->name
, port
) == 0) {
2182 if (a
.port
> 0 && a
.port
!= s
->port
) {
2183 fprintf(stderr
, "Error: ambiguous port \"%s\".\n", port
);
2191 fprintf(stderr
, "Error: \"%s\" does not look like a port.\n", port
);
2198 if (!is_port
&& *addr
&& *addr
!= '*') {
2199 if (get_prefix_1(&a
.addr
, addr
, fam
)) {
2200 if (get_dns_host(&a
, addr
, fam
)) {
2201 fprintf(stderr
, "Error: an inet prefix is expected rather than \"%s\".\n", addr
);
2208 if (fam
!= AF_UNSPEC
) {
2209 int states
= f
->states
;
2211 filter_af_set(f
, fam
);
2212 filter_states_set(f
, states
);
2215 res
= malloc(sizeof(*res
));
2217 memcpy(res
, &a
, sizeof(a
));
2221 void *parse_markmask(const char *markmask
)
2223 struct aafilter a
, *res
;
2225 if (strchr(markmask
, '/')) {
2226 if (sscanf(markmask
, "%i/%i", &a
.mark
, &a
.mask
) != 2)
2229 a
.mask
= 0xffffffff;
2230 if (sscanf(markmask
, "%i", &a
.mark
) != 1)
2234 res
= malloc(sizeof(*res
));
2236 memcpy(res
, &a
, sizeof(a
));
2240 static void proc_ctx_print(struct sockstat
*s
)
2244 if (show_proc_ctx
|| show_sock_ctx
) {
2245 if (find_entry(s
->ino
, &buf
,
2246 (show_proc_ctx
& show_sock_ctx
) ?
2247 PROC_SOCK_CTX
: PROC_CTX
) > 0) {
2248 out(" users:(%s)", buf
);
2251 } else if (show_users
) {
2252 if (find_entry(s
->ino
, &buf
, USERS
) > 0) {
2253 out(" users:(%s)", buf
);
2259 static void inet_stats_print(struct sockstat
*s
, bool v6only
)
2261 sock_state_print(s
);
2263 inet_addr_print(&s
->local
, s
->lport
, s
->iface
, v6only
);
2264 inet_addr_print(&s
->remote
, s
->rport
, 0, v6only
);
2269 static int proc_parse_inet_addr(char *loc
, char *rem
, int family
, struct
2272 s
->local
.family
= s
->remote
.family
= family
;
2273 if (family
== AF_INET
) {
2274 sscanf(loc
, "%x:%x", s
->local
.data
, (unsigned *)&s
->lport
);
2275 sscanf(rem
, "%x:%x", s
->remote
.data
, (unsigned *)&s
->rport
);
2276 s
->local
.bytelen
= s
->remote
.bytelen
= 4;
2279 sscanf(loc
, "%08x%08x%08x%08x:%x",
2285 sscanf(rem
, "%08x%08x%08x%08x:%x",
2291 s
->local
.bytelen
= s
->remote
.bytelen
= 16;
2297 static int proc_inet_split_line(char *line
, char **loc
, char **rem
, char **data
)
2301 if ((p
= strchr(line
, ':')) == NULL
)
2305 if ((p
= strchr(*loc
, ':')) == NULL
)
2310 if ((p
= strchr(*rem
, ':')) == NULL
)
2318 static char *sprint_bw(char *buf
, double bw
)
2321 sprintf(buf
, "%.1fM", bw
/ 1000000.);
2322 else if (bw
> 1000.)
2323 sprintf(buf
, "%.1fK", bw
/ 1000.);
2325 sprintf(buf
, "%g", bw
);
2330 static void sctp_stats_print(struct sctp_info
*s
)
2333 out(" tag:%x", s
->sctpi_tag
);
2335 out(" state:%s", sctp_sstate_name
[s
->sctpi_state
]);
2337 out(" rwnd:%d", s
->sctpi_rwnd
);
2338 if (s
->sctpi_unackdata
)
2339 out(" unackdata:%d", s
->sctpi_unackdata
);
2340 if (s
->sctpi_penddata
)
2341 out(" penddata:%d", s
->sctpi_penddata
);
2342 if (s
->sctpi_instrms
)
2343 out(" instrms:%d", s
->sctpi_instrms
);
2344 if (s
->sctpi_outstrms
)
2345 out(" outstrms:%d", s
->sctpi_outstrms
);
2346 if (s
->sctpi_inqueue
)
2347 out(" inqueue:%d", s
->sctpi_inqueue
);
2348 if (s
->sctpi_outqueue
)
2349 out(" outqueue:%d", s
->sctpi_outqueue
);
2350 if (s
->sctpi_overall_error
)
2351 out(" overerr:%d", s
->sctpi_overall_error
);
2352 if (s
->sctpi_max_burst
)
2353 out(" maxburst:%d", s
->sctpi_max_burst
);
2354 if (s
->sctpi_maxseg
)
2355 out(" maxseg:%d", s
->sctpi_maxseg
);
2356 if (s
->sctpi_peer_rwnd
)
2357 out(" prwnd:%d", s
->sctpi_peer_rwnd
);
2358 if (s
->sctpi_peer_tag
)
2359 out(" ptag:%x", s
->sctpi_peer_tag
);
2360 if (s
->sctpi_peer_capable
)
2361 out(" pcapable:%d", s
->sctpi_peer_capable
);
2362 if (s
->sctpi_peer_sack
)
2363 out(" psack:%d", s
->sctpi_peer_sack
);
2364 if (s
->sctpi_s_autoclose
)
2365 out(" autoclose:%d", s
->sctpi_s_autoclose
);
2366 if (s
->sctpi_s_adaptation_ind
)
2367 out(" adapind:%d", s
->sctpi_s_adaptation_ind
);
2368 if (s
->sctpi_s_pd_point
)
2369 out(" pdpoint:%d", s
->sctpi_s_pd_point
);
2370 if (s
->sctpi_s_nodelay
)
2371 out(" nodealy:%d", s
->sctpi_s_nodelay
);
2372 if (s
->sctpi_s_disable_fragments
)
2373 out(" nofrag:%d", s
->sctpi_s_disable_fragments
);
2374 if (s
->sctpi_s_v4mapped
)
2375 out(" v4mapped:%d", s
->sctpi_s_v4mapped
);
2376 if (s
->sctpi_s_frag_interleave
)
2377 out(" fraginl:%d", s
->sctpi_s_frag_interleave
);
2380 static void tcp_stats_print(struct tcpstat
*s
)
2386 if (s
->has_sack_opt
)
2390 if (s
->has_ecnseen_opt
)
2392 if (s
->has_fastopen_opt
)
2395 out(" %s", s
->cong_alg
);
2396 if (s
->has_wscale_opt
)
2397 out(" wscale:%d,%d", s
->snd_wscale
, s
->rcv_wscale
);
2399 out(" rto:%g", s
->rto
);
2401 out(" backoff:%u", s
->backoff
);
2403 out(" rtt:%g/%g", s
->rtt
, s
->rttvar
);
2405 out(" ato:%g", s
->ato
);
2408 out(" qack:%d", s
->qack
);
2413 out(" mss:%d", s
->mss
);
2415 out(" pmtu:%u", s
->pmtu
);
2417 out(" rcvmss:%d", s
->rcv_mss
);
2419 out(" advmss:%d", s
->advmss
);
2421 out(" cwnd:%u", s
->cwnd
);
2423 out(" ssthresh:%d", s
->ssthresh
);
2426 out(" bytes_acked:%llu", s
->bytes_acked
);
2427 if (s
->bytes_received
)
2428 out(" bytes_received:%llu", s
->bytes_received
);
2430 out(" segs_out:%u", s
->segs_out
);
2432 out(" segs_in:%u", s
->segs_in
);
2433 if (s
->data_segs_out
)
2434 out(" data_segs_out:%u", s
->data_segs_out
);
2435 if (s
->data_segs_in
)
2436 out(" data_segs_in:%u", s
->data_segs_in
);
2438 if (s
->dctcp
&& s
->dctcp
->enabled
) {
2439 struct dctcpstat
*dctcp
= s
->dctcp
;
2441 out(" dctcp:(ce_state:%u,alpha:%u,ab_ecn:%u,ab_tot:%u)",
2442 dctcp
->ce_state
, dctcp
->alpha
, dctcp
->ab_ecn
,
2444 } else if (s
->dctcp
) {
2445 out(" dctcp:fallback_mode");
2451 bw
= s
->bbr_info
->bbr_bw_hi
;
2453 bw
|= s
->bbr_info
->bbr_bw_lo
;
2455 out(" bbr:(bw:%sbps,mrtt:%g",
2456 sprint_bw(b1
, bw
* 8.0),
2457 (double)s
->bbr_info
->bbr_min_rtt
/ 1000.0);
2458 if (s
->bbr_info
->bbr_pacing_gain
)
2459 out(",pacing_gain:%g",
2460 (double)s
->bbr_info
->bbr_pacing_gain
/ 256.0);
2461 if (s
->bbr_info
->bbr_cwnd_gain
)
2462 out(",cwnd_gain:%g",
2463 (double)s
->bbr_info
->bbr_cwnd_gain
/ 256.0);
2468 out(" send %sbps", sprint_bw(b1
, s
->send_bps
));
2470 out(" lastsnd:%u", s
->lastsnd
);
2472 out(" lastrcv:%u", s
->lastrcv
);
2474 out(" lastack:%u", s
->lastack
);
2476 if (s
->pacing_rate
) {
2477 out(" pacing_rate %sbps", sprint_bw(b1
, s
->pacing_rate
));
2478 if (s
->pacing_rate_max
)
2479 out("/%sbps", sprint_bw(b1
, s
->pacing_rate_max
));
2482 if (s
->delivery_rate
)
2483 out(" delivery_rate %sbps", sprint_bw(b1
, s
->delivery_rate
));
2485 out(" app_limited");
2488 out(" busy:%llums", s
->busy_time
/ 1000);
2489 if (s
->rwnd_limited
)
2490 out(" rwnd_limited:%llums(%.1f%%)",
2491 s
->rwnd_limited
/ 1000,
2492 100.0 * s
->rwnd_limited
/ s
->busy_time
);
2493 if (s
->sndbuf_limited
)
2494 out(" sndbuf_limited:%llums(%.1f%%)",
2495 s
->sndbuf_limited
/ 1000,
2496 100.0 * s
->sndbuf_limited
/ s
->busy_time
);
2500 out(" unacked:%u", s
->unacked
);
2501 if (s
->retrans
|| s
->retrans_total
)
2502 out(" retrans:%u/%u", s
->retrans
, s
->retrans_total
);
2504 out(" lost:%u", s
->lost
);
2505 if (s
->sacked
&& s
->ss
.state
!= SS_LISTEN
)
2506 out(" sacked:%u", s
->sacked
);
2508 out(" fackets:%u", s
->fackets
);
2509 if (s
->reordering
!= 3)
2510 out(" reordering:%d", s
->reordering
);
2512 out(" rcv_rtt:%g", s
->rcv_rtt
);
2514 out(" rcv_space:%d", s
->rcv_space
);
2515 if (s
->rcv_ssthresh
)
2516 out(" rcv_ssthresh:%u", s
->rcv_ssthresh
);
2518 out(" notsent:%u", s
->not_sent
);
2520 out(" minrtt:%g", s
->min_rtt
);
2523 static void tcp_timer_print(struct tcpstat
*s
)
2525 static const char * const tmr_name
[] = {
2537 out(" timer:(%s,%s,%d)",
2539 print_ms_timer(s
->timeout
),
2544 static void sctp_timer_print(struct tcpstat
*s
)
2547 out(" timer:(T3_RTX,%s,%d)",
2548 print_ms_timer(s
->timeout
), s
->retrans
);
2551 static int tcp_show_line(char *line
, const struct filter
*f
, int family
)
2553 int rto
= 0, ato
= 0;
2554 struct tcpstat s
= {};
2555 char *loc
, *rem
, *data
;
2558 int hz
= get_user_hz();
2560 if (proc_inet_split_line(line
, &loc
, &rem
, &data
))
2563 int state
= (data
[1] >= 'A') ? (data
[1] - 'A' + 10) : (data
[1] - '0');
2565 if (!(f
->states
& (1 << state
)))
2568 proc_parse_inet_addr(loc
, rem
, family
, &s
.ss
);
2570 if (f
->f
&& run_ssfilter(f
->f
, &s
.ss
) == 0)
2574 n
= sscanf(data
, "%x %x:%x %x:%x %x %d %d %u %d %llx %d %d %d %u %d %[^\n]\n",
2575 &s
.ss
.state
, &s
.ss
.wq
, &s
.ss
.rq
,
2576 &s
.timer
, &s
.timeout
, &s
.retrans
, &s
.ss
.uid
, &s
.probes
,
2577 &s
.ss
.ino
, &s
.ss
.refcnt
, &s
.ss
.sk
, &rto
, &ato
, &s
.qack
, &s
.cwnd
,
2590 s
.retrans
= s
.timer
!= 1 ? s
.probes
: s
.retrans
;
2591 s
.timeout
= (s
.timeout
* 1000 + hz
- 1) / hz
;
2592 s
.ato
= (double)ato
/ hz
;
2594 s
.rto
= (double)rto
;
2595 s
.ssthresh
= s
.ssthresh
== -1 ? 0 : s
.ssthresh
;
2596 s
.rto
= s
.rto
!= 3 * hz
? s
.rto
/ hz
: 0;
2597 s
.ss
.type
= IPPROTO_TCP
;
2599 inet_stats_print(&s
.ss
, false);
2602 tcp_timer_print(&s
);
2605 sock_details_print(&s
.ss
);
2607 out(" opt:\"%s\"", opt
);
2611 tcp_stats_print(&s
);
2616 static int generic_record_read(FILE *fp
,
2617 int (*worker
)(char*, const struct filter
*, int),
2618 const struct filter
*f
, int fam
)
2623 if (fgets(line
, sizeof(line
), fp
) == NULL
)
2626 while (fgets(line
, sizeof(line
), fp
) != NULL
) {
2627 int n
= strlen(line
);
2629 if (n
== 0 || line
[n
-1] != '\n') {
2635 if (worker(line
, f
, fam
) < 0)
2640 return ferror(fp
) ? -1 : 0;
2643 static void print_skmeminfo(struct rtattr
*tb
[], int attrtype
)
2645 const __u32
*skmeminfo
;
2647 if (!tb
[attrtype
]) {
2648 if (attrtype
== INET_DIAG_SKMEMINFO
) {
2649 if (!tb
[INET_DIAG_MEMINFO
])
2652 const struct inet_diag_meminfo
*minfo
=
2653 RTA_DATA(tb
[INET_DIAG_MEMINFO
]);
2655 out(" mem:(r%u,w%u,f%u,t%u)",
2664 skmeminfo
= RTA_DATA(tb
[attrtype
]);
2666 out(" skmem:(r%u,rb%u,t%u,tb%u,f%u,w%u,o%u",
2667 skmeminfo
[SK_MEMINFO_RMEM_ALLOC
],
2668 skmeminfo
[SK_MEMINFO_RCVBUF
],
2669 skmeminfo
[SK_MEMINFO_WMEM_ALLOC
],
2670 skmeminfo
[SK_MEMINFO_SNDBUF
],
2671 skmeminfo
[SK_MEMINFO_FWD_ALLOC
],
2672 skmeminfo
[SK_MEMINFO_WMEM_QUEUED
],
2673 skmeminfo
[SK_MEMINFO_OPTMEM
]);
2675 if (RTA_PAYLOAD(tb
[attrtype
]) >=
2676 (SK_MEMINFO_BACKLOG
+ 1) * sizeof(__u32
))
2677 out(",bl%u", skmeminfo
[SK_MEMINFO_BACKLOG
]);
2679 if (RTA_PAYLOAD(tb
[attrtype
]) >=
2680 (SK_MEMINFO_DROPS
+ 1) * sizeof(__u32
))
2681 out(",d%u", skmeminfo
[SK_MEMINFO_DROPS
]);
2686 static void print_md5sig(struct tcp_diag_md5sig
*sig
)
2689 format_host(sig
->tcpm_family
,
2690 sig
->tcpm_family
== AF_INET6
? 16 : 4,
2692 sig
->tcpm_prefixlen
);
2693 print_escape_buf(sig
->tcpm_key
, sig
->tcpm_keylen
, " ,");
2696 #define TCPI_HAS_OPT(info, opt) !!(info->tcpi_options & (opt))
2698 static void tcp_show_info(const struct nlmsghdr
*nlh
, struct inet_diag_msg
*r
,
2699 struct rtattr
*tb
[])
2702 struct tcpstat s
= {};
2704 s
.ss
.state
= r
->idiag_state
;
2706 print_skmeminfo(tb
, INET_DIAG_SKMEMINFO
);
2708 if (tb
[INET_DIAG_INFO
]) {
2709 struct tcp_info
*info
;
2710 int len
= RTA_PAYLOAD(tb
[INET_DIAG_INFO
]);
2712 /* workaround for older kernels with less fields */
2713 if (len
< sizeof(*info
)) {
2714 info
= alloca(sizeof(*info
));
2715 memcpy(info
, RTA_DATA(tb
[INET_DIAG_INFO
]), len
);
2716 memset((char *)info
+ len
, 0, sizeof(*info
) - len
);
2718 info
= RTA_DATA(tb
[INET_DIAG_INFO
]);
2721 s
.has_ts_opt
= TCPI_HAS_OPT(info
, TCPI_OPT_TIMESTAMPS
);
2722 s
.has_sack_opt
= TCPI_HAS_OPT(info
, TCPI_OPT_SACK
);
2723 s
.has_ecn_opt
= TCPI_HAS_OPT(info
, TCPI_OPT_ECN
);
2724 s
.has_ecnseen_opt
= TCPI_HAS_OPT(info
, TCPI_OPT_ECN_SEEN
);
2725 s
.has_fastopen_opt
= TCPI_HAS_OPT(info
, TCPI_OPT_SYN_DATA
);
2728 if (tb
[INET_DIAG_CONG
])
2730 rta_getattr_str(tb
[INET_DIAG_CONG
]),
2731 sizeof(s
.cong_alg
) - 1);
2733 if (TCPI_HAS_OPT(info
, TCPI_OPT_WSCALE
)) {
2734 s
.has_wscale_opt
= true;
2735 s
.snd_wscale
= info
->tcpi_snd_wscale
;
2736 s
.rcv_wscale
= info
->tcpi_rcv_wscale
;
2739 if (info
->tcpi_rto
&& info
->tcpi_rto
!= 3000000)
2740 s
.rto
= (double)info
->tcpi_rto
/ 1000;
2742 s
.backoff
= info
->tcpi_backoff
;
2743 s
.rtt
= (double)info
->tcpi_rtt
/ 1000;
2744 s
.rttvar
= (double)info
->tcpi_rttvar
/ 1000;
2745 s
.ato
= (double)info
->tcpi_ato
/ 1000;
2746 s
.mss
= info
->tcpi_snd_mss
;
2747 s
.rcv_mss
= info
->tcpi_rcv_mss
;
2748 s
.advmss
= info
->tcpi_advmss
;
2749 s
.rcv_space
= info
->tcpi_rcv_space
;
2750 s
.rcv_rtt
= (double)info
->tcpi_rcv_rtt
/ 1000;
2751 s
.lastsnd
= info
->tcpi_last_data_sent
;
2752 s
.lastrcv
= info
->tcpi_last_data_recv
;
2753 s
.lastack
= info
->tcpi_last_ack_recv
;
2754 s
.unacked
= info
->tcpi_unacked
;
2755 s
.retrans
= info
->tcpi_retrans
;
2756 s
.retrans_total
= info
->tcpi_total_retrans
;
2757 s
.lost
= info
->tcpi_lost
;
2758 s
.sacked
= info
->tcpi_sacked
;
2759 s
.fackets
= info
->tcpi_fackets
;
2760 s
.reordering
= info
->tcpi_reordering
;
2761 s
.rcv_ssthresh
= info
->tcpi_rcv_ssthresh
;
2762 s
.cwnd
= info
->tcpi_snd_cwnd
;
2763 s
.pmtu
= info
->tcpi_pmtu
;
2765 if (info
->tcpi_snd_ssthresh
< 0xFFFF)
2766 s
.ssthresh
= info
->tcpi_snd_ssthresh
;
2768 rtt
= (double) info
->tcpi_rtt
;
2769 if (tb
[INET_DIAG_VEGASINFO
]) {
2770 const struct tcpvegas_info
*vinfo
2771 = RTA_DATA(tb
[INET_DIAG_VEGASINFO
]);
2773 if (vinfo
->tcpv_enabled
&&
2774 vinfo
->tcpv_rtt
&& vinfo
->tcpv_rtt
!= 0x7fffffff)
2775 rtt
= vinfo
->tcpv_rtt
;
2778 if (tb
[INET_DIAG_DCTCPINFO
]) {
2779 struct dctcpstat
*dctcp
= malloc(sizeof(struct
2782 const struct tcp_dctcp_info
*dinfo
2783 = RTA_DATA(tb
[INET_DIAG_DCTCPINFO
]);
2785 dctcp
->enabled
= !!dinfo
->dctcp_enabled
;
2786 dctcp
->ce_state
= dinfo
->dctcp_ce_state
;
2787 dctcp
->alpha
= dinfo
->dctcp_alpha
;
2788 dctcp
->ab_ecn
= dinfo
->dctcp_ab_ecn
;
2789 dctcp
->ab_tot
= dinfo
->dctcp_ab_tot
;
2793 if (tb
[INET_DIAG_BBRINFO
]) {
2794 const void *bbr_info
= RTA_DATA(tb
[INET_DIAG_BBRINFO
]);
2795 int len
= min(RTA_PAYLOAD(tb
[INET_DIAG_BBRINFO
]),
2796 sizeof(*s
.bbr_info
));
2798 s
.bbr_info
= calloc(1, sizeof(*s
.bbr_info
));
2799 if (s
.bbr_info
&& bbr_info
)
2800 memcpy(s
.bbr_info
, bbr_info
, len
);
2803 if (rtt
> 0 && info
->tcpi_snd_mss
&& info
->tcpi_snd_cwnd
) {
2804 s
.send_bps
= (double) info
->tcpi_snd_cwnd
*
2805 (double)info
->tcpi_snd_mss
* 8000000. / rtt
;
2808 if (info
->tcpi_pacing_rate
&&
2809 info
->tcpi_pacing_rate
!= ~0ULL) {
2810 s
.pacing_rate
= info
->tcpi_pacing_rate
* 8.;
2812 if (info
->tcpi_max_pacing_rate
&&
2813 info
->tcpi_max_pacing_rate
!= ~0ULL)
2814 s
.pacing_rate_max
= info
->tcpi_max_pacing_rate
* 8.;
2816 s
.bytes_acked
= info
->tcpi_bytes_acked
;
2817 s
.bytes_received
= info
->tcpi_bytes_received
;
2818 s
.segs_out
= info
->tcpi_segs_out
;
2819 s
.segs_in
= info
->tcpi_segs_in
;
2820 s
.data_segs_out
= info
->tcpi_data_segs_out
;
2821 s
.data_segs_in
= info
->tcpi_data_segs_in
;
2822 s
.not_sent
= info
->tcpi_notsent_bytes
;
2823 if (info
->tcpi_min_rtt
&& info
->tcpi_min_rtt
!= ~0U)
2824 s
.min_rtt
= (double) info
->tcpi_min_rtt
/ 1000;
2825 s
.delivery_rate
= info
->tcpi_delivery_rate
* 8.;
2826 s
.app_limited
= info
->tcpi_delivery_rate_app_limited
;
2827 s
.busy_time
= info
->tcpi_busy_time
;
2828 s
.rwnd_limited
= info
->tcpi_rwnd_limited
;
2829 s
.sndbuf_limited
= info
->tcpi_sndbuf_limited
;
2830 tcp_stats_print(&s
);
2834 if (tb
[INET_DIAG_MD5SIG
]) {
2835 struct tcp_diag_md5sig
*sig
= RTA_DATA(tb
[INET_DIAG_MD5SIG
]);
2836 int len
= RTA_PAYLOAD(tb
[INET_DIAG_MD5SIG
]);
2839 print_md5sig(sig
++);
2840 for (len
-= sizeof(*sig
); len
> 0; len
-= sizeof(*sig
)) {
2842 print_md5sig(sig
++);
2847 static const char *format_host_sa(struct sockaddr_storage
*sa
)
2850 struct sockaddr_in sin
;
2851 struct sockaddr_in6 sin6
;
2852 } *saddr
= (void *)sa
;
2854 switch (sa
->ss_family
) {
2856 return format_host(AF_INET
, 4, &saddr
->sin
.sin_addr
);
2858 return format_host(AF_INET6
, 16, &saddr
->sin6
.sin6_addr
);
2864 static void sctp_show_info(const struct nlmsghdr
*nlh
, struct inet_diag_msg
*r
,
2865 struct rtattr
*tb
[])
2867 struct sockaddr_storage
*sa
;
2870 print_skmeminfo(tb
, INET_DIAG_SKMEMINFO
);
2872 if (tb
[INET_DIAG_LOCALS
]) {
2873 len
= RTA_PAYLOAD(tb
[INET_DIAG_LOCALS
]);
2874 sa
= RTA_DATA(tb
[INET_DIAG_LOCALS
]);
2876 out("locals:%s", format_host_sa(sa
));
2877 for (sa
++, len
-= sizeof(*sa
); len
> 0; sa
++, len
-= sizeof(*sa
))
2878 out(",%s", format_host_sa(sa
));
2881 if (tb
[INET_DIAG_PEERS
]) {
2882 len
= RTA_PAYLOAD(tb
[INET_DIAG_PEERS
]);
2883 sa
= RTA_DATA(tb
[INET_DIAG_PEERS
]);
2885 out(" peers:%s", format_host_sa(sa
));
2886 for (sa
++, len
-= sizeof(*sa
); len
> 0; sa
++, len
-= sizeof(*sa
))
2887 out(",%s", format_host_sa(sa
));
2889 if (tb
[INET_DIAG_INFO
]) {
2890 struct sctp_info
*info
;
2891 len
= RTA_PAYLOAD(tb
[INET_DIAG_INFO
]);
2893 /* workaround for older kernels with less fields */
2894 if (len
< sizeof(*info
)) {
2895 info
= alloca(sizeof(*info
));
2896 memcpy(info
, RTA_DATA(tb
[INET_DIAG_INFO
]), len
);
2897 memset((char *)info
+ len
, 0, sizeof(*info
) - len
);
2899 info
= RTA_DATA(tb
[INET_DIAG_INFO
]);
2901 sctp_stats_print(info
);
2905 static void parse_diag_msg(struct nlmsghdr
*nlh
, struct sockstat
*s
)
2907 struct rtattr
*tb
[INET_DIAG_MAX
+1];
2908 struct inet_diag_msg
*r
= NLMSG_DATA(nlh
);
2910 parse_rtattr(tb
, INET_DIAG_MAX
, (struct rtattr
*)(r
+1),
2911 nlh
->nlmsg_len
- NLMSG_LENGTH(sizeof(*r
)));
2913 s
->state
= r
->idiag_state
;
2914 s
->local
.family
= s
->remote
.family
= r
->idiag_family
;
2915 s
->lport
= ntohs(r
->id
.idiag_sport
);
2916 s
->rport
= ntohs(r
->id
.idiag_dport
);
2917 s
->wq
= r
->idiag_wqueue
;
2918 s
->rq
= r
->idiag_rqueue
;
2919 s
->ino
= r
->idiag_inode
;
2920 s
->uid
= r
->idiag_uid
;
2921 s
->iface
= r
->id
.idiag_if
;
2922 s
->sk
= cookie_sk_get(&r
->id
.idiag_cookie
[0]);
2925 if (tb
[INET_DIAG_MARK
])
2926 s
->mark
= rta_getattr_u32(tb
[INET_DIAG_MARK
]);
2927 if (tb
[INET_DIAG_PROTOCOL
])
2928 s
->raw_prot
= rta_getattr_u8(tb
[INET_DIAG_PROTOCOL
]);
2932 if (s
->local
.family
== AF_INET
)
2933 s
->local
.bytelen
= s
->remote
.bytelen
= 4;
2935 s
->local
.bytelen
= s
->remote
.bytelen
= 16;
2937 memcpy(s
->local
.data
, r
->id
.idiag_src
, s
->local
.bytelen
);
2938 memcpy(s
->remote
.data
, r
->id
.idiag_dst
, s
->local
.bytelen
);
2941 static int inet_show_sock(struct nlmsghdr
*nlh
,
2944 struct rtattr
*tb
[INET_DIAG_MAX
+1];
2945 struct inet_diag_msg
*r
= NLMSG_DATA(nlh
);
2946 unsigned char v6only
= 0;
2948 parse_rtattr(tb
, INET_DIAG_MAX
, (struct rtattr
*)(r
+1),
2949 nlh
->nlmsg_len
- NLMSG_LENGTH(sizeof(*r
)));
2951 if (tb
[INET_DIAG_PROTOCOL
])
2952 s
->type
= rta_getattr_u8(tb
[INET_DIAG_PROTOCOL
]);
2954 if (s
->local
.family
== AF_INET6
&& tb
[INET_DIAG_SKV6ONLY
])
2955 v6only
= rta_getattr_u8(tb
[INET_DIAG_SKV6ONLY
]);
2957 inet_stats_print(s
, v6only
);
2960 struct tcpstat t
= {};
2962 t
.timer
= r
->idiag_timer
;
2963 t
.timeout
= r
->idiag_expires
;
2964 t
.retrans
= r
->idiag_retrans
;
2965 if (s
->type
== IPPROTO_SCTP
)
2966 sctp_timer_print(&t
);
2968 tcp_timer_print(&t
);
2972 sock_details_print(s
);
2973 if (s
->local
.family
== AF_INET6
&& tb
[INET_DIAG_SKV6ONLY
])
2974 out(" v6only:%u", v6only
);
2976 if (tb
[INET_DIAG_SHUTDOWN
]) {
2979 mask
= rta_getattr_u8(tb
[INET_DIAG_SHUTDOWN
]);
2981 mask
& 1 ? '-' : '<', mask
& 2 ? '-' : '>');
2985 if (show_mem
|| (show_tcpinfo
&& s
->type
!= IPPROTO_UDP
)) {
2987 if (s
->type
== IPPROTO_SCTP
)
2988 sctp_show_info(nlh
, r
, tb
);
2990 tcp_show_info(nlh
, r
, tb
);
2997 static int tcpdiag_send(int fd
, int protocol
, struct filter
*f
)
2999 struct sockaddr_nl nladdr
= { .nl_family
= AF_NETLINK
};
3001 struct nlmsghdr nlh
;
3002 struct inet_diag_req r
;
3004 .nlh
.nlmsg_len
= sizeof(req
),
3005 .nlh
.nlmsg_flags
= NLM_F_ROOT
| NLM_F_MATCH
| NLM_F_REQUEST
,
3006 .nlh
.nlmsg_seq
= MAGIC_SEQ
,
3007 .r
.idiag_family
= AF_INET
,
3008 .r
.idiag_states
= f
->states
,
3014 struct iovec iov
[3];
3017 if (protocol
== IPPROTO_UDP
)
3020 if (protocol
== IPPROTO_TCP
)
3021 req
.nlh
.nlmsg_type
= TCPDIAG_GETSOCK
;
3023 req
.nlh
.nlmsg_type
= DCCPDIAG_GETSOCK
;
3025 req
.r
.idiag_ext
|= (1<<(INET_DIAG_MEMINFO
-1));
3026 req
.r
.idiag_ext
|= (1<<(INET_DIAG_SKMEMINFO
-1));
3030 req
.r
.idiag_ext
|= (1<<(INET_DIAG_INFO
-1));
3031 req
.r
.idiag_ext
|= (1<<(INET_DIAG_VEGASINFO
-1));
3032 req
.r
.idiag_ext
|= (1<<(INET_DIAG_CONG
-1));
3035 iov
[0] = (struct iovec
){
3037 .iov_len
= sizeof(req
)
3040 bclen
= ssfilter_bytecompile(f
->f
, &bc
);
3042 rta
.rta_type
= INET_DIAG_REQ_BYTECODE
;
3043 rta
.rta_len
= RTA_LENGTH(bclen
);
3044 iov
[1] = (struct iovec
){ &rta
, sizeof(rta
) };
3045 iov
[2] = (struct iovec
){ bc
, bclen
};
3046 req
.nlh
.nlmsg_len
+= RTA_LENGTH(bclen
);
3051 msg
= (struct msghdr
) {
3052 .msg_name
= (void *)&nladdr
,
3053 .msg_namelen
= sizeof(nladdr
),
3055 .msg_iovlen
= iovlen
,
3058 if (sendmsg(fd
, &msg
, 0) < 0) {
3066 static int sockdiag_send(int family
, int fd
, int protocol
, struct filter
*f
)
3068 struct sockaddr_nl nladdr
= { .nl_family
= AF_NETLINK
};
3069 DIAG_REQUEST(req
, struct inet_diag_req_v2 r
);
3074 struct iovec iov
[3];
3077 if (family
== PF_UNSPEC
)
3078 return tcpdiag_send(fd
, protocol
, f
);
3080 memset(&req
.r
, 0, sizeof(req
.r
));
3081 req
.r
.sdiag_family
= family
;
3082 req
.r
.sdiag_protocol
= protocol
;
3083 req
.r
.idiag_states
= f
->states
;
3085 req
.r
.idiag_ext
|= (1<<(INET_DIAG_MEMINFO
-1));
3086 req
.r
.idiag_ext
|= (1<<(INET_DIAG_SKMEMINFO
-1));
3090 req
.r
.idiag_ext
|= (1<<(INET_DIAG_INFO
-1));
3091 req
.r
.idiag_ext
|= (1<<(INET_DIAG_VEGASINFO
-1));
3092 req
.r
.idiag_ext
|= (1<<(INET_DIAG_CONG
-1));
3095 iov
[0] = (struct iovec
){
3097 .iov_len
= sizeof(req
)
3100 bclen
= ssfilter_bytecompile(f
->f
, &bc
);
3102 rta
.rta_type
= INET_DIAG_REQ_BYTECODE
;
3103 rta
.rta_len
= RTA_LENGTH(bclen
);
3104 iov
[1] = (struct iovec
){ &rta
, sizeof(rta
) };
3105 iov
[2] = (struct iovec
){ bc
, bclen
};
3106 req
.nlh
.nlmsg_len
+= RTA_LENGTH(bclen
);
3111 msg
= (struct msghdr
) {
3112 .msg_name
= (void *)&nladdr
,
3113 .msg_namelen
= sizeof(nladdr
),
3115 .msg_iovlen
= iovlen
,
3118 if (sendmsg(fd
, &msg
, 0) < 0) {
3126 struct inet_diag_arg
{
3129 struct rtnl_handle
*rth
;
3132 static int kill_inet_sock(struct nlmsghdr
*h
, void *arg
, struct sockstat
*s
)
3134 struct inet_diag_msg
*d
= NLMSG_DATA(h
);
3135 struct inet_diag_arg
*diag_arg
= arg
;
3136 struct rtnl_handle
*rth
= diag_arg
->rth
;
3138 DIAG_REQUEST(req
, struct inet_diag_req_v2 r
);
3140 req
.nlh
.nlmsg_type
= SOCK_DESTROY
;
3141 req
.nlh
.nlmsg_flags
= NLM_F_REQUEST
| NLM_F_ACK
;
3142 req
.nlh
.nlmsg_seq
= ++rth
->seq
;
3143 req
.r
.sdiag_family
= d
->idiag_family
;
3144 req
.r
.sdiag_protocol
= diag_arg
->protocol
;
3147 if (diag_arg
->protocol
== IPPROTO_RAW
) {
3148 struct inet_diag_req_raw
*raw
= (void *)&req
.r
;
3150 BUILD_BUG_ON(sizeof(req
.r
) != sizeof(*raw
));
3151 raw
->sdiag_raw_protocol
= s
->raw_prot
;
3154 return rtnl_talk(rth
, &req
.nlh
, NULL
);
3157 static int show_one_inet_sock(const struct sockaddr_nl
*addr
,
3158 struct nlmsghdr
*h
, void *arg
)
3161 struct inet_diag_arg
*diag_arg
= arg
;
3162 struct inet_diag_msg
*r
= NLMSG_DATA(h
);
3163 struct sockstat s
= {};
3165 if (!(diag_arg
->f
->families
& FAMILY_MASK(r
->idiag_family
)))
3168 parse_diag_msg(h
, &s
);
3169 s
.type
= diag_arg
->protocol
;
3171 if (diag_arg
->f
->f
&& run_ssfilter(diag_arg
->f
->f
, &s
) == 0)
3174 if (diag_arg
->f
->kill
&& kill_inet_sock(h
, arg
, &s
) != 0) {
3175 if (errno
== EOPNOTSUPP
|| errno
== ENOENT
) {
3176 /* Socket can't be closed, or is already closed. */
3179 perror("SOCK_DESTROY answers");
3184 err
= inet_show_sock(h
, &s
);
3191 static int inet_show_netlink(struct filter
*f
, FILE *dump_fp
, int protocol
)
3194 struct rtnl_handle rth
, rth2
;
3195 int family
= PF_INET
;
3196 struct inet_diag_arg arg
= { .f
= f
, .protocol
= protocol
};
3198 if (rtnl_open_byproto(&rth
, 0, NETLINK_SOCK_DIAG
))
3202 if (rtnl_open_byproto(&rth2
, 0, NETLINK_SOCK_DIAG
)) {
3209 rth
.dump
= MAGIC_SEQ
;
3210 rth
.dump_fp
= dump_fp
;
3211 if (preferred_family
== PF_INET6
)
3215 if ((err
= sockdiag_send(family
, rth
.fd
, protocol
, f
)))
3218 if ((err
= rtnl_dump_filter(&rth
, show_one_inet_sock
, &arg
))) {
3219 if (family
!= PF_UNSPEC
) {
3225 if (family
== PF_INET
&& preferred_family
!= PF_INET
) {
3233 rtnl_close(arg
.rth
);
3237 static int tcp_show_netlink_file(struct filter
*f
)
3243 if ((fp
= fopen(getenv("TCPDIAG_FILE"), "r")) == NULL
) {
3244 perror("fopen($TCPDIAG_FILE)");
3250 struct nlmsghdr
*h
= (struct nlmsghdr
*)buf
;
3251 struct sockstat s
= {};
3253 status
= fread(buf
, 1, sizeof(*h
), fp
);
3255 perror("Reading header from $TCPDIAG_FILE");
3258 if (status
!= sizeof(*h
)) {
3259 perror("Unexpected EOF reading $TCPDIAG_FILE");
3263 status
= fread(h
+1, 1, NLMSG_ALIGN(h
->nlmsg_len
-sizeof(*h
)), fp
);
3266 perror("Reading $TCPDIAG_FILE");
3269 if (status
+ sizeof(*h
) < h
->nlmsg_len
) {
3270 perror("Unexpected EOF reading $TCPDIAG_FILE");
3274 /* The only legal exit point */
3275 if (h
->nlmsg_type
== NLMSG_DONE
) {
3280 if (h
->nlmsg_type
== NLMSG_ERROR
) {
3281 struct nlmsgerr
*err
= (struct nlmsgerr
*)NLMSG_DATA(h
);
3283 if (h
->nlmsg_len
< NLMSG_LENGTH(sizeof(struct nlmsgerr
))) {
3284 fprintf(stderr
, "ERROR truncated\n");
3286 errno
= -err
->error
;
3287 perror("TCPDIAG answered");
3292 parse_diag_msg(h
, &s
);
3293 s
.type
= IPPROTO_TCP
;
3295 if (f
&& f
->f
&& run_ssfilter(f
->f
, &s
) == 0)
3298 err2
= inet_show_sock(h
, &s
);
3309 static int tcp_show(struct filter
*f
)
3313 int bufsize
= 1024*1024;
3315 if (!filter_af_get(f
, AF_INET
) && !filter_af_get(f
, AF_INET6
))
3318 dg_proto
= TCP_PROTO
;
3320 if (getenv("TCPDIAG_FILE"))
3321 return tcp_show_netlink_file(f
);
3323 if (!getenv("PROC_NET_TCP") && !getenv("PROC_ROOT")
3324 && inet_show_netlink(f
, NULL
, IPPROTO_TCP
) == 0)
3327 /* Sigh... We have to parse /proc/net/tcp... */
3328 while (bufsize
>= 64*1024) {
3329 if ((buf
= malloc(bufsize
)) != NULL
)
3338 if (f
->families
& FAMILY_MASK(AF_INET
)) {
3339 if ((fp
= net_tcp_open()) == NULL
)
3342 setbuffer(fp
, buf
, bufsize
);
3343 if (generic_record_read(fp
, tcp_show_line
, f
, AF_INET
))
3348 if ((f
->families
& FAMILY_MASK(AF_INET6
)) &&
3349 (fp
= net_tcp6_open()) != NULL
) {
3350 setbuffer(fp
, buf
, bufsize
);
3351 if (generic_record_read(fp
, tcp_show_line
, f
, AF_INET6
))
3361 int saved_errno
= errno
;
3366 errno
= saved_errno
;
3371 static int dccp_show(struct filter
*f
)
3373 if (!filter_af_get(f
, AF_INET
) && !filter_af_get(f
, AF_INET6
))
3376 if (!getenv("PROC_NET_DCCP") && !getenv("PROC_ROOT")
3377 && inet_show_netlink(f
, NULL
, IPPROTO_DCCP
) == 0)
3383 static int sctp_show(struct filter
*f
)
3385 if (!filter_af_get(f
, AF_INET
) && !filter_af_get(f
, AF_INET6
))
3388 if (!getenv("PROC_NET_SCTP") && !getenv("PROC_ROOT")
3389 && inet_show_netlink(f
, NULL
, IPPROTO_SCTP
) == 0)
3395 static int dgram_show_line(char *line
, const struct filter
*f
, int family
)
3397 struct sockstat s
= {};
3398 char *loc
, *rem
, *data
;
3402 if (proc_inet_split_line(line
, &loc
, &rem
, &data
))
3405 int state
= (data
[1] >= 'A') ? (data
[1] - 'A' + 10) : (data
[1] - '0');
3407 if (!(f
->states
& (1 << state
)))
3410 proc_parse_inet_addr(loc
, rem
, family
, &s
);
3412 if (f
->f
&& run_ssfilter(f
->f
, &s
) == 0)
3416 n
= sscanf(data
, "%x %x:%x %*x:%*x %*x %d %*d %u %d %llx %[^\n]\n",
3417 &s
.state
, &s
.wq
, &s
.rq
,
3419 &s
.refcnt
, &s
.sk
, opt
);
3424 s
.type
= dg_proto
== UDP_PROTO
? IPPROTO_UDP
: 0;
3425 inet_stats_print(&s
, false);
3427 if (show_details
&& opt
[0])
3428 out(" opt:\"%s\"", opt
);
3433 static int udp_show(struct filter
*f
)
3437 if (!filter_af_get(f
, AF_INET
) && !filter_af_get(f
, AF_INET6
))
3440 dg_proto
= UDP_PROTO
;
3442 if (!getenv("PROC_NET_UDP") && !getenv("PROC_ROOT")
3443 && inet_show_netlink(f
, NULL
, IPPROTO_UDP
) == 0)
3446 if (f
->families
&FAMILY_MASK(AF_INET
)) {
3447 if ((fp
= net_udp_open()) == NULL
)
3449 if (generic_record_read(fp
, dgram_show_line
, f
, AF_INET
))
3454 if ((f
->families
&FAMILY_MASK(AF_INET6
)) &&
3455 (fp
= net_udp6_open()) != NULL
) {
3456 if (generic_record_read(fp
, dgram_show_line
, f
, AF_INET6
))
3464 int saved_errno
= errno
;
3468 errno
= saved_errno
;
3473 static int raw_show(struct filter
*f
)
3477 if (!filter_af_get(f
, AF_INET
) && !filter_af_get(f
, AF_INET6
))
3480 dg_proto
= RAW_PROTO
;
3482 if (!getenv("PROC_NET_RAW") && !getenv("PROC_ROOT") &&
3483 inet_show_netlink(f
, NULL
, IPPROTO_RAW
) == 0)
3486 if (f
->families
&FAMILY_MASK(AF_INET
)) {
3487 if ((fp
= net_raw_open()) == NULL
)
3489 if (generic_record_read(fp
, dgram_show_line
, f
, AF_INET
))
3494 if ((f
->families
&FAMILY_MASK(AF_INET6
)) &&
3495 (fp
= net_raw6_open()) != NULL
) {
3496 if (generic_record_read(fp
, dgram_show_line
, f
, AF_INET6
))
3504 int saved_errno
= errno
;
3508 errno
= saved_errno
;
3513 #define MAX_UNIX_REMEMBER (1024*1024/sizeof(struct sockstat))
3515 static void unix_list_drop_first(struct sockstat
**list
)
3517 struct sockstat
*s
= *list
;
3519 (*list
) = (*list
)->next
;
3524 static bool unix_type_skip(struct sockstat
*s
, struct filter
*f
)
3526 if (s
->type
== SOCK_STREAM
&& !(f
->dbs
&(1<<UNIX_ST_DB
)))
3528 if (s
->type
== SOCK_DGRAM
&& !(f
->dbs
&(1<<UNIX_DG_DB
)))
3530 if (s
->type
== SOCK_SEQPACKET
&& !(f
->dbs
&(1<<UNIX_SQ_DB
)))
3535 static void unix_stats_print(struct sockstat
*s
, struct filter
*f
)
3537 char port_name
[30] = {};
3539 sock_state_print(s
);
3541 sock_addr_print(s
->name
?: "*", " ",
3542 int_to_str(s
->lport
, port_name
), NULL
);
3543 sock_addr_print(s
->peer_name
?: "*", " ",
3544 int_to_str(s
->rport
, port_name
), NULL
);
3549 static int unix_show_sock(const struct sockaddr_nl
*addr
, struct nlmsghdr
*nlh
,
3552 struct filter
*f
= (struct filter
*)arg
;
3553 struct unix_diag_msg
*r
= NLMSG_DATA(nlh
);
3554 struct rtattr
*tb
[UNIX_DIAG_MAX
+1];
3556 struct sockstat stat
= { .name
= "*", .peer_name
= "*" };
3558 parse_rtattr(tb
, UNIX_DIAG_MAX
, (struct rtattr
*)(r
+1),
3559 nlh
->nlmsg_len
- NLMSG_LENGTH(sizeof(*r
)));
3561 stat
.type
= r
->udiag_type
;
3562 stat
.state
= r
->udiag_state
;
3563 stat
.ino
= stat
.lport
= r
->udiag_ino
;
3564 stat
.local
.family
= stat
.remote
.family
= AF_UNIX
;
3566 if (unix_type_skip(&stat
, f
))
3569 if (tb
[UNIX_DIAG_RQLEN
]) {
3570 struct unix_diag_rqlen
*rql
= RTA_DATA(tb
[UNIX_DIAG_RQLEN
]);
3572 stat
.rq
= rql
->udiag_rqueue
;
3573 stat
.wq
= rql
->udiag_wqueue
;
3575 if (tb
[UNIX_DIAG_NAME
]) {
3576 int len
= RTA_PAYLOAD(tb
[UNIX_DIAG_NAME
]);
3578 memcpy(name
, RTA_DATA(tb
[UNIX_DIAG_NAME
]), len
);
3580 if (name
[0] == '\0') {
3582 for (i
= 0; i
< len
; i
++)
3583 if (name
[i
] == '\0')
3586 stat
.name
= &name
[0];
3587 memcpy(stat
.local
.data
, &stat
.name
, sizeof(stat
.name
));
3589 if (tb
[UNIX_DIAG_PEER
])
3590 stat
.rport
= rta_getattr_u32(tb
[UNIX_DIAG_PEER
]);
3592 if (f
->f
&& run_ssfilter(f
->f
, &stat
) == 0)
3595 unix_stats_print(&stat
, f
);
3598 print_skmeminfo(tb
, UNIX_DIAG_MEMINFO
);
3600 if (tb
[UNIX_DIAG_SHUTDOWN
]) {
3603 mask
= rta_getattr_u8(tb
[UNIX_DIAG_SHUTDOWN
]);
3605 mask
& 1 ? '-' : '<', mask
& 2 ? '-' : '>');
3612 static int handle_netlink_request(struct filter
*f
, struct nlmsghdr
*req
,
3613 size_t size
, rtnl_filter_t show_one_sock
)
3616 struct rtnl_handle rth
;
3618 if (rtnl_open_byproto(&rth
, 0, NETLINK_SOCK_DIAG
))
3621 rth
.dump
= MAGIC_SEQ
;
3623 if (rtnl_send(&rth
, req
, size
) < 0)
3626 if (rtnl_dump_filter(&rth
, show_one_sock
, f
))
3635 static int unix_show_netlink(struct filter
*f
)
3637 DIAG_REQUEST(req
, struct unix_diag_req r
);
3639 req
.r
.sdiag_family
= AF_UNIX
;
3640 req
.r
.udiag_states
= f
->states
;
3641 req
.r
.udiag_show
= UDIAG_SHOW_NAME
| UDIAG_SHOW_PEER
| UDIAG_SHOW_RQLEN
;
3643 req
.r
.udiag_show
|= UDIAG_SHOW_MEMINFO
;
3645 return handle_netlink_request(f
, &req
.nlh
, sizeof(req
), unix_show_sock
);
3648 static int unix_show(struct filter
*f
)
3655 struct sockstat
*list
= NULL
;
3656 const int unix_state_map
[] = { SS_CLOSE
, SS_SYN_SENT
,
3657 SS_ESTABLISHED
, SS_CLOSING
};
3659 if (!filter_af_get(f
, AF_UNIX
))
3662 if (!getenv("PROC_NET_UNIX") && !getenv("PROC_ROOT")
3663 && unix_show_netlink(f
) == 0)
3666 if ((fp
= net_unix_open()) == NULL
)
3668 if (!fgets(buf
, sizeof(buf
), fp
)) {
3673 if (memcmp(buf
, "Peer", 4) == 0)
3677 while (fgets(buf
, sizeof(buf
), fp
)) {
3678 struct sockstat
*u
, **insp
;
3681 if (!(u
= calloc(1, sizeof(*u
))))
3684 if (sscanf(buf
, "%x: %x %x %x %x %x %d %s",
3685 &u
->rport
, &u
->rq
, &u
->wq
, &flags
, &u
->type
,
3686 &u
->state
, &u
->ino
, name
) < 8)
3690 u
->local
.family
= u
->remote
.family
= AF_UNIX
;
3692 if (flags
& (1 << 16)) {
3693 u
->state
= SS_LISTEN
;
3694 } else if (u
->state
> 0 &&
3695 u
->state
<= ARRAY_SIZE(unix_state_map
)) {
3696 u
->state
= unix_state_map
[u
->state
-1];
3697 if (u
->type
== SOCK_DGRAM
&& u
->state
== SS_CLOSE
&& u
->rport
)
3698 u
->state
= SS_ESTABLISHED
;
3700 if (unix_type_skip(u
, f
) ||
3701 !(f
->states
& (1 << u
->state
))) {
3713 u
->name
= strdup(name
);
3723 for (p
= list
; p
; p
= p
->next
) {
3724 if (u
->rport
== p
->lport
)
3730 u
->peer_name
= p
->name
? : "*";
3734 struct sockstat st
= {
3735 .local
.family
= AF_UNIX
,
3736 .remote
.family
= AF_UNIX
,
3739 memcpy(st
.local
.data
, &u
->name
, sizeof(u
->name
));
3740 /* when parsing the old format rport is set to 0 and
3741 * therefore peer_name remains NULL
3743 if (u
->peer_name
&& strcmp(u
->peer_name
, "*"))
3744 memcpy(st
.remote
.data
, &u
->peer_name
,
3745 sizeof(u
->peer_name
));
3746 if (run_ssfilter(f
->f
, &st
) == 0) {
3755 if (u
->type
< (*insp
)->type
||
3756 (u
->type
== (*insp
)->type
&&
3757 u
->ino
< (*insp
)->ino
))
3759 insp
= &(*insp
)->next
;
3764 if (++cnt
> MAX_UNIX_REMEMBER
) {
3766 unix_stats_print(list
, f
);
3767 unix_list_drop_first(&list
);
3774 unix_stats_print(list
, f
);
3775 unix_list_drop_first(&list
);
3781 static int packet_stats_print(struct sockstat
*s
, const struct filter
*f
)
3783 const char *addr
, *port
;
3786 s
->local
.family
= s
->remote
.family
= AF_PACKET
;
3789 s
->local
.data
[0] = s
->prot
;
3790 if (run_ssfilter(f
->f
, s
) == 0)
3794 sock_state_print(s
);
3799 addr
= ll_proto_n2a(htons(s
->prot
), ll_name
, sizeof(ll_name
));
3804 port
= xll_index_to_name(s
->iface
);
3806 sock_addr_print(addr
, ":", port
, NULL
);
3807 sock_addr_print("", "*", "", NULL
);
3812 sock_details_print(s
);
3817 static void packet_show_ring(struct packet_diag_ring
*ring
)
3819 out("blk_size:%d", ring
->pdr_block_size
);
3820 out(",blk_nr:%d", ring
->pdr_block_nr
);
3821 out(",frm_size:%d", ring
->pdr_frame_size
);
3822 out(",frm_nr:%d", ring
->pdr_frame_nr
);
3823 out(",tmo:%d", ring
->pdr_retire_tmo
);
3824 out(",features:0x%x", ring
->pdr_features
);
3827 static int packet_show_sock(const struct sockaddr_nl
*addr
,
3828 struct nlmsghdr
*nlh
, void *arg
)
3830 const struct filter
*f
= arg
;
3831 struct packet_diag_msg
*r
= NLMSG_DATA(nlh
);
3832 struct packet_diag_info
*pinfo
= NULL
;
3833 struct packet_diag_ring
*ring_rx
= NULL
, *ring_tx
= NULL
;
3834 struct rtattr
*tb
[PACKET_DIAG_MAX
+1];
3835 struct sockstat stat
= {};
3836 uint32_t fanout
= 0;
3837 bool has_fanout
= false;
3839 parse_rtattr(tb
, PACKET_DIAG_MAX
, (struct rtattr
*)(r
+1),
3840 nlh
->nlmsg_len
- NLMSG_LENGTH(sizeof(*r
)));
3842 /* use /proc/net/packet if all info are not available */
3843 if (!tb
[PACKET_DIAG_MEMINFO
])
3846 stat
.type
= r
->pdiag_type
;
3847 stat
.prot
= r
->pdiag_num
;
3848 stat
.ino
= r
->pdiag_ino
;
3849 stat
.state
= SS_CLOSE
;
3850 stat
.sk
= cookie_sk_get(&r
->pdiag_cookie
[0]);
3852 if (tb
[PACKET_DIAG_MEMINFO
]) {
3853 __u32
*skmeminfo
= RTA_DATA(tb
[PACKET_DIAG_MEMINFO
]);
3855 stat
.rq
= skmeminfo
[SK_MEMINFO_RMEM_ALLOC
];
3858 if (tb
[PACKET_DIAG_INFO
]) {
3859 pinfo
= RTA_DATA(tb
[PACKET_DIAG_INFO
]);
3860 stat
.lport
= stat
.iface
= pinfo
->pdi_index
;
3863 if (tb
[PACKET_DIAG_UID
])
3864 stat
.uid
= rta_getattr_u32(tb
[PACKET_DIAG_UID
]);
3866 if (tb
[PACKET_DIAG_RX_RING
])
3867 ring_rx
= RTA_DATA(tb
[PACKET_DIAG_RX_RING
]);
3869 if (tb
[PACKET_DIAG_TX_RING
])
3870 ring_tx
= RTA_DATA(tb
[PACKET_DIAG_TX_RING
]);
3872 if (tb
[PACKET_DIAG_FANOUT
]) {
3874 fanout
= rta_getattr_u32(tb
[PACKET_DIAG_FANOUT
]);
3877 if (packet_stats_print(&stat
, f
))
3882 out("\n\tver:%d", pinfo
->pdi_version
);
3883 out(" cpy_thresh:%d", pinfo
->pdi_copy_thresh
);
3885 if (pinfo
->pdi_flags
& PDI_RUNNING
)
3887 if (pinfo
->pdi_flags
& PDI_AUXDATA
)
3889 if (pinfo
->pdi_flags
& PDI_ORIGDEV
)
3891 if (pinfo
->pdi_flags
& PDI_VNETHDR
)
3893 if (pinfo
->pdi_flags
& PDI_LOSS
)
3895 if (!pinfo
->pdi_flags
)
3900 out("\n\tring_rx(");
3901 packet_show_ring(ring_rx
);
3905 out("\n\tring_tx(");
3906 packet_show_ring(ring_tx
);
3910 uint16_t type
= (fanout
>> 16) & 0xffff;
3913 out("id:%d,", fanout
& 0xffff);
3935 if (show_bpf
&& tb
[PACKET_DIAG_FILTER
]) {
3936 struct sock_filter
*fil
=
3937 RTA_DATA(tb
[PACKET_DIAG_FILTER
]);
3938 int num
= RTA_PAYLOAD(tb
[PACKET_DIAG_FILTER
]) /
3939 sizeof(struct sock_filter
);
3941 out("\n\tbpf filter (%d): ", num
);
3943 out(" 0x%02x %u %u %u,",
3944 fil
->code
, fil
->jt
, fil
->jf
, fil
->k
);
3951 print_skmeminfo(tb
, PACKET_DIAG_MEMINFO
);
3955 static int packet_show_netlink(struct filter
*f
)
3957 DIAG_REQUEST(req
, struct packet_diag_req r
);
3959 req
.r
.sdiag_family
= AF_PACKET
;
3960 req
.r
.pdiag_show
= PACKET_SHOW_INFO
| PACKET_SHOW_MEMINFO
|
3961 PACKET_SHOW_FILTER
| PACKET_SHOW_RING_CFG
| PACKET_SHOW_FANOUT
;
3963 return handle_netlink_request(f
, &req
.nlh
, sizeof(req
), packet_show_sock
);
3966 static int packet_show_line(char *buf
, const struct filter
*f
, int fam
)
3968 unsigned long long sk
;
3969 struct sockstat stat
= {};
3970 int type
, prot
, iface
, state
, rq
, uid
, ino
;
3972 sscanf(buf
, "%llx %*d %d %x %d %d %u %u %u",
3974 &type
, &prot
, &iface
, &state
,
3977 if (stat
.type
== SOCK_RAW
&& !(f
->dbs
&(1<<PACKET_R_DB
)))
3979 if (stat
.type
== SOCK_DGRAM
&& !(f
->dbs
&(1<<PACKET_DG_DB
)))
3984 stat
.lport
= stat
.iface
= iface
;
3989 stat
.state
= SS_CLOSE
;
3991 if (packet_stats_print(&stat
, f
))
3997 static int packet_show(struct filter
*f
)
4002 if (!filter_af_get(f
, AF_PACKET
) || !(f
->states
& (1 << SS_CLOSE
)))
4005 if (!getenv("PROC_NET_PACKET") && !getenv("PROC_ROOT") &&
4006 packet_show_netlink(f
) == 0)
4009 if ((fp
= net_packet_open()) == NULL
)
4011 if (generic_record_read(fp
, packet_show_line
, f
, AF_PACKET
))
4018 static int netlink_show_one(struct filter
*f
,
4019 int prot
, int pid
, unsigned int groups
,
4020 int state
, int dst_pid
, unsigned int dst_group
,
4022 unsigned long long sk
, unsigned long long cb
)
4024 struct sockstat st
= {
4028 .local
.family
= AF_NETLINK
,
4029 .remote
.family
= AF_NETLINK
,
4032 SPRINT_BUF(prot_buf
) = {};
4033 const char *prot_name
;
4034 char procname
[64] = {};
4039 st
.local
.data
[0] = prot
;
4040 if (run_ssfilter(f
->f
, &st
) == 0)
4044 sock_state_print(&st
);
4046 if (resolve_services
)
4047 prot_name
= nl_proto_n2a(prot
, prot_buf
, sizeof(prot_buf
));
4049 prot_name
= int_to_str(prot
, prot_buf
);
4053 } else if (resolve_services
) {
4058 strncpy(procname
, "kernel", 7);
4059 } else if (pid
> 0) {
4062 snprintf(procname
, sizeof(procname
), "%s/%d/stat",
4063 getenv("PROC_ROOT") ? : "/proc", pid
);
4064 if ((fp
= fopen(procname
, "r")) != NULL
) {
4065 if (fscanf(fp
, "%*d (%[^)])", procname
) == 1) {
4066 snprintf(procname
+strlen(procname
),
4067 sizeof(procname
)-strlen(procname
),
4075 int_to_str(pid
, procname
);
4077 int_to_str(pid
, procname
);
4080 sock_addr_print(prot_name
, ":", procname
, NULL
);
4082 if (state
== NETLINK_CONNECTED
) {
4083 char dst_group_buf
[30];
4084 char dst_pid_buf
[30];
4086 sock_addr_print(int_to_str(dst_group
, dst_group_buf
), ":",
4087 int_to_str(dst_pid
, dst_pid_buf
), NULL
);
4089 sock_addr_print("", "*", "", NULL
);
4092 char *pid_context
= NULL
;
4094 if (show_proc_ctx
) {
4095 /* The pid value will either be:
4096 * 0 if destination kernel - show kernel initial context.
4097 * A valid process pid - use getpidcon.
4098 * A unique value allocated by the kernel or netlink user
4099 * to the process - show context as "not available".
4102 security_get_initial_context("kernel", &pid_context
);
4104 getpidcon(pid
, &pid_context
);
4106 out(" proc_ctx=%s", pid_context
? : "unavailable");
4111 out(" sk=%llx cb=%llx groups=0x%08x", sk
, cb
, groups
);
4117 static int netlink_show_sock(const struct sockaddr_nl
*addr
,
4118 struct nlmsghdr
*nlh
, void *arg
)
4120 struct filter
*f
= (struct filter
*)arg
;
4121 struct netlink_diag_msg
*r
= NLMSG_DATA(nlh
);
4122 struct rtattr
*tb
[NETLINK_DIAG_MAX
+1];
4124 unsigned long groups
= 0;
4126 parse_rtattr(tb
, NETLINK_DIAG_MAX
, (struct rtattr
*)(r
+1),
4127 nlh
->nlmsg_len
- NLMSG_LENGTH(sizeof(*r
)));
4129 if (tb
[NETLINK_DIAG_GROUPS
] && RTA_PAYLOAD(tb
[NETLINK_DIAG_GROUPS
]))
4130 groups
= *(unsigned long *) RTA_DATA(tb
[NETLINK_DIAG_GROUPS
]);
4132 if (tb
[NETLINK_DIAG_MEMINFO
]) {
4133 const __u32
*skmeminfo
;
4135 skmeminfo
= RTA_DATA(tb
[NETLINK_DIAG_MEMINFO
]);
4137 rq
= skmeminfo
[SK_MEMINFO_RMEM_ALLOC
];
4138 wq
= skmeminfo
[SK_MEMINFO_WMEM_ALLOC
];
4141 if (netlink_show_one(f
, r
->ndiag_protocol
, r
->ndiag_portid
, groups
,
4142 r
->ndiag_state
, r
->ndiag_dst_portid
, r
->ndiag_dst_group
,
4149 print_skmeminfo(tb
, NETLINK_DIAG_MEMINFO
);
4155 static int netlink_show_netlink(struct filter
*f
)
4157 DIAG_REQUEST(req
, struct netlink_diag_req r
);
4159 req
.r
.sdiag_family
= AF_NETLINK
;
4160 req
.r
.sdiag_protocol
= NDIAG_PROTO_ALL
;
4161 req
.r
.ndiag_show
= NDIAG_SHOW_GROUPS
| NDIAG_SHOW_MEMINFO
;
4163 return handle_netlink_request(f
, &req
.nlh
, sizeof(req
), netlink_show_sock
);
4166 static int netlink_show(struct filter
*f
)
4171 unsigned int groups
;
4173 unsigned long long sk
, cb
;
4175 if (!filter_af_get(f
, AF_NETLINK
) || !(f
->states
& (1 << SS_CLOSE
)))
4178 if (!getenv("PROC_NET_NETLINK") && !getenv("PROC_ROOT") &&
4179 netlink_show_netlink(f
) == 0)
4182 if ((fp
= net_netlink_open()) == NULL
)
4184 if (!fgets(buf
, sizeof(buf
), fp
)) {
4189 while (fgets(buf
, sizeof(buf
), fp
)) {
4190 sscanf(buf
, "%llx %d %d %x %d %d %llx %d",
4192 &prot
, &pid
, &groups
, &rq
, &wq
, &cb
, &rc
);
4194 netlink_show_one(f
, prot
, pid
, groups
, 0, 0, 0, rq
, wq
, sk
, cb
);
4201 static bool vsock_type_skip(struct sockstat
*s
, struct filter
*f
)
4203 if (s
->type
== SOCK_STREAM
&& !(f
->dbs
& (1 << VSOCK_ST_DB
)))
4205 if (s
->type
== SOCK_DGRAM
&& !(f
->dbs
& (1 << VSOCK_DG_DB
)))
4210 static void vsock_addr_print(inet_prefix
*a
, __u32 port
)
4212 char cid_str
[sizeof("4294967295")];
4213 char port_str
[sizeof("4294967295")];
4216 memcpy(&cid
, a
->data
, sizeof(cid
));
4218 if (cid
== ~(__u32
)0)
4219 snprintf(cid_str
, sizeof(cid_str
), "*");
4221 snprintf(cid_str
, sizeof(cid_str
), "%u", cid
);
4223 if (port
== ~(__u32
)0)
4224 snprintf(port_str
, sizeof(port_str
), "*");
4226 snprintf(port_str
, sizeof(port_str
), "%u", port
);
4228 sock_addr_print(cid_str
, ":", port_str
, NULL
);
4231 static void vsock_stats_print(struct sockstat
*s
, struct filter
*f
)
4233 sock_state_print(s
);
4235 vsock_addr_print(&s
->local
, s
->lport
);
4236 vsock_addr_print(&s
->remote
, s
->rport
);
4241 static int vsock_show_sock(const struct sockaddr_nl
*addr
,
4242 struct nlmsghdr
*nlh
, void *arg
)
4244 struct filter
*f
= (struct filter
*)arg
;
4245 struct vsock_diag_msg
*r
= NLMSG_DATA(nlh
);
4246 struct sockstat stat
= {
4247 .type
= r
->vdiag_type
,
4248 .lport
= r
->vdiag_src_port
,
4249 .rport
= r
->vdiag_dst_port
,
4250 .state
= r
->vdiag_state
,
4251 .ino
= r
->vdiag_ino
,
4254 vsock_set_inet_prefix(&stat
.local
, r
->vdiag_src_cid
);
4255 vsock_set_inet_prefix(&stat
.remote
, r
->vdiag_dst_cid
);
4257 if (vsock_type_skip(&stat
, f
))
4260 if (f
->f
&& run_ssfilter(f
->f
, &stat
) == 0)
4263 vsock_stats_print(&stat
, f
);
4268 static int vsock_show(struct filter
*f
)
4270 DIAG_REQUEST(req
, struct vsock_diag_req r
);
4272 if (!filter_af_get(f
, AF_VSOCK
))
4275 req
.r
.sdiag_family
= AF_VSOCK
;
4276 req
.r
.vdiag_states
= f
->states
;
4278 return handle_netlink_request(f
, &req
.nlh
, sizeof(req
), vsock_show_sock
);
4281 static void tipc_sock_addr_print(struct rtattr
*net_addr
, struct rtattr
*id
)
4283 uint32_t node
= rta_getattr_u32(net_addr
);
4284 uint32_t identity
= rta_getattr_u32(id
);
4286 SPRINT_BUF(addr
) = {};
4287 SPRINT_BUF(port
) = {};
4289 sprintf(addr
, "%u", node
);
4290 sprintf(port
, "%u", identity
);
4291 sock_addr_print(addr
, ":", port
, NULL
);
4295 static int tipc_show_sock(const struct sockaddr_nl
*addr
, struct nlmsghdr
*nlh
,
4298 struct rtattr
*stat
[TIPC_NLA_SOCK_STAT_MAX
+ 1] = {};
4299 struct rtattr
*attrs
[TIPC_NLA_SOCK_MAX
+ 1] = {};
4300 struct rtattr
*con
[TIPC_NLA_CON_MAX
+ 1] = {};
4301 struct rtattr
*info
[TIPC_NLA_MAX
+ 1] = {};
4302 struct rtattr
*msg_ref
;
4303 struct sockstat ss
= {};
4305 parse_rtattr(info
, TIPC_NLA_MAX
, NLMSG_DATA(nlh
),
4306 NLMSG_PAYLOAD(nlh
, 0));
4308 if (!info
[TIPC_NLA_SOCK
])
4311 msg_ref
= info
[TIPC_NLA_SOCK
];
4312 parse_rtattr(attrs
, TIPC_NLA_SOCK_MAX
, RTA_DATA(msg_ref
),
4313 RTA_PAYLOAD(msg_ref
));
4315 msg_ref
= attrs
[TIPC_NLA_SOCK_STAT
];
4316 parse_rtattr(stat
, TIPC_NLA_SOCK_STAT_MAX
,
4317 RTA_DATA(msg_ref
), RTA_PAYLOAD(msg_ref
));
4320 ss
.local
.family
= AF_TIPC
;
4321 ss
.type
= rta_getattr_u32(attrs
[TIPC_NLA_SOCK_TYPE
]);
4322 ss
.state
= rta_getattr_u32(attrs
[TIPC_NLA_SOCK_TIPC_STATE
]);
4323 ss
.uid
= rta_getattr_u32(attrs
[TIPC_NLA_SOCK_UID
]);
4324 ss
.ino
= rta_getattr_u32(attrs
[TIPC_NLA_SOCK_INO
]);
4325 ss
.rq
= rta_getattr_u32(stat
[TIPC_NLA_SOCK_STAT_RCVQ
]);
4326 ss
.wq
= rta_getattr_u32(stat
[TIPC_NLA_SOCK_STAT_SENDQ
]);
4327 ss
.sk
= rta_getattr_u64(attrs
[TIPC_NLA_SOCK_COOKIE
]);
4329 sock_state_print (&ss
);
4331 tipc_sock_addr_print(attrs
[TIPC_NLA_SOCK_ADDR
],
4332 attrs
[TIPC_NLA_SOCK_REF
]);
4334 msg_ref
= attrs
[TIPC_NLA_SOCK_CON
];
4336 parse_rtattr(con
, TIPC_NLA_CON_MAX
,
4337 RTA_DATA(msg_ref
), RTA_PAYLOAD(msg_ref
));
4339 tipc_sock_addr_print(con
[TIPC_NLA_CON_NODE
],
4340 con
[TIPC_NLA_CON_SOCK
]);
4342 sock_addr_print("", "-", "", NULL
);
4345 sock_details_print(&ss
);
4347 proc_ctx_print(&ss
);
4349 if (show_tipcinfo
) {
4350 out("\n type:%s", stype_nameg
[ss
.type
]);
4352 stat
[TIPC_NLA_SOCK_STAT_LINK_CONG
] ? "link" :
4353 stat
[TIPC_NLA_SOCK_STAT_CONN_CONG
] ? "conn" : "none");
4355 rta_getattr_u32(stat
[TIPC_NLA_SOCK_STAT_DROP
]));
4357 if (attrs
[TIPC_NLA_SOCK_HAS_PUBL
])
4360 if (con
[TIPC_NLA_CON_FLAG
])
4361 out(" via {%u,%u} ",
4362 rta_getattr_u32(con
[TIPC_NLA_CON_TYPE
]),
4363 rta_getattr_u32(con
[TIPC_NLA_CON_INST
]));
4369 static int tipc_show(struct filter
*f
)
4371 DIAG_REQUEST(req
, struct tipc_sock_diag_req r
);
4373 memset(&req
.r
, 0, sizeof(req
.r
));
4374 req
.r
.sdiag_family
= AF_TIPC
;
4375 req
.r
.tidiag_states
= f
->states
;
4377 return handle_netlink_request(f
, &req
.nlh
, sizeof(req
), tipc_show_sock
);
4380 struct sock_diag_msg
{
4384 static int generic_show_sock(const struct sockaddr_nl
*addr
,
4385 struct nlmsghdr
*nlh
, void *arg
)
4387 struct sock_diag_msg
*r
= NLMSG_DATA(nlh
);
4388 struct inet_diag_arg inet_arg
= { .f
= arg
, .protocol
= IPPROTO_MAX
};
4391 switch (r
->sdiag_family
) {
4394 inet_arg
.rth
= inet_arg
.f
->rth_for_killing
;
4395 ret
= show_one_inet_sock(addr
, nlh
, &inet_arg
);
4398 ret
= unix_show_sock(addr
, nlh
, arg
);
4401 ret
= packet_show_sock(addr
, nlh
, arg
);
4404 ret
= netlink_show_sock(addr
, nlh
, arg
);
4407 ret
= vsock_show_sock(addr
, nlh
, arg
);
4418 static int handle_follow_request(struct filter
*f
)
4422 struct rtnl_handle rth
, rth2
;
4424 if (f
->families
& FAMILY_MASK(AF_INET
) && f
->dbs
& (1 << TCP_DB
))
4425 groups
|= 1 << (SKNLGRP_INET_TCP_DESTROY
- 1);
4426 if (f
->families
& FAMILY_MASK(AF_INET
) && f
->dbs
& (1 << UDP_DB
))
4427 groups
|= 1 << (SKNLGRP_INET_UDP_DESTROY
- 1);
4428 if (f
->families
& FAMILY_MASK(AF_INET6
) && f
->dbs
& (1 << TCP_DB
))
4429 groups
|= 1 << (SKNLGRP_INET6_TCP_DESTROY
- 1);
4430 if (f
->families
& FAMILY_MASK(AF_INET6
) && f
->dbs
& (1 << UDP_DB
))
4431 groups
|= 1 << (SKNLGRP_INET6_UDP_DESTROY
- 1);
4436 if (rtnl_open_byproto(&rth
, groups
, NETLINK_SOCK_DIAG
))
4440 rth
.local
.nl_pid
= 0;
4443 if (rtnl_open_byproto(&rth2
, groups
, NETLINK_SOCK_DIAG
)) {
4447 f
->rth_for_killing
= &rth2
;
4450 if (rtnl_dump_filter(&rth
, generic_show_sock
, f
))
4454 if (f
->rth_for_killing
)
4455 rtnl_close(f
->rth_for_killing
);
4459 static int get_snmp_int(char *proto
, char *key
, int *result
)
4463 int protolen
= strlen(proto
);
4464 int keylen
= strlen(key
);
4468 if ((fp
= net_snmp_open()) == NULL
)
4471 while (fgets(buf
, sizeof(buf
), fp
) != NULL
) {
4475 if (memcmp(buf
, proto
, protolen
))
4477 while ((p
= strchr(p
, ' ')) != NULL
) {
4480 if (memcmp(p
, key
, keylen
) == 0 &&
4481 (p
[keylen
] == ' ' || p
[keylen
] == '\n'))
4484 if (fgets(buf
, sizeof(buf
), fp
) == NULL
)
4486 if (memcmp(buf
, proto
, protolen
))
4489 while ((p
= strchr(p
, ' ')) != NULL
) {
4492 sscanf(p
, "%d", result
);
4505 /* Get stats from sockstat */
4525 static void get_sockstat_line(char *line
, struct ssummary
*s
)
4527 char id
[256], rem
[256];
4529 if (sscanf(line
, "%[^ ] %[^\n]\n", id
, rem
) != 2)
4532 if (strcmp(id
, "sockets:") == 0)
4533 sscanf(rem
, "%*s%d", &s
->socks
);
4534 else if (strcmp(id
, "UDP:") == 0)
4535 sscanf(rem
, "%*s%d", &s
->udp4
);
4536 else if (strcmp(id
, "UDP6:") == 0)
4537 sscanf(rem
, "%*s%d", &s
->udp6
);
4538 else if (strcmp(id
, "RAW:") == 0)
4539 sscanf(rem
, "%*s%d", &s
->raw4
);
4540 else if (strcmp(id
, "RAW6:") == 0)
4541 sscanf(rem
, "%*s%d", &s
->raw6
);
4542 else if (strcmp(id
, "TCP6:") == 0)
4543 sscanf(rem
, "%*s%d", &s
->tcp6_hashed
);
4544 else if (strcmp(id
, "FRAG:") == 0)
4545 sscanf(rem
, "%*s%d%*s%d", &s
->frag4
, &s
->frag4_mem
);
4546 else if (strcmp(id
, "FRAG6:") == 0)
4547 sscanf(rem
, "%*s%d%*s%d", &s
->frag6
, &s
->frag6_mem
);
4548 else if (strcmp(id
, "TCP:") == 0)
4549 sscanf(rem
, "%*s%d%*s%d%*s%d%*s%d%*s%d",
4551 &s
->tcp_orphans
, &s
->tcp_tws
, &s
->tcp_total
, &s
->tcp_mem
);
4554 static int get_sockstat(struct ssummary
*s
)
4559 memset(s
, 0, sizeof(*s
));
4561 if ((fp
= net_sockstat_open()) == NULL
)
4563 while (fgets(buf
, sizeof(buf
), fp
) != NULL
)
4564 get_sockstat_line(buf
, s
);
4567 if ((fp
= net_sockstat6_open()) == NULL
)
4569 while (fgets(buf
, sizeof(buf
), fp
) != NULL
)
4570 get_sockstat_line(buf
, s
);
4576 static int print_summary(void)
4581 if (get_sockstat(&s
) < 0)
4582 perror("ss: get_sockstat");
4583 if (get_snmp_int("Tcp:", "CurrEstab", &tcp_estab
) < 0)
4584 perror("ss: get_snmpstat");
4586 printf("Total: %d\n", s
.socks
);
4588 printf("TCP: %d (estab %d, closed %d, orphaned %d, timewait %d)\n",
4589 s
.tcp_total
+ s
.tcp_tws
, tcp_estab
,
4590 s
.tcp_total
- (s
.tcp4_hashed
+ s
.tcp6_hashed
- s
.tcp_tws
),
4591 s
.tcp_orphans
, s
.tcp_tws
);
4594 printf("Transport Total IP IPv6\n");
4595 printf("RAW %-9d %-9d %-9d\n", s
.raw4
+s
.raw6
, s
.raw4
, s
.raw6
);
4596 printf("UDP %-9d %-9d %-9d\n", s
.udp4
+s
.udp6
, s
.udp4
, s
.udp6
);
4597 printf("TCP %-9d %-9d %-9d\n", s
.tcp4_hashed
+s
.tcp6_hashed
, s
.tcp4_hashed
, s
.tcp6_hashed
);
4598 printf("INET %-9d %-9d %-9d\n",
4599 s
.raw4
+s
.udp4
+s
.tcp4_hashed
+
4600 s
.raw6
+s
.udp6
+s
.tcp6_hashed
,
4601 s
.raw4
+s
.udp4
+s
.tcp4_hashed
,
4602 s
.raw6
+s
.udp6
+s
.tcp6_hashed
);
4603 printf("FRAG %-9d %-9d %-9d\n", s
.frag4
+s
.frag6
, s
.frag4
, s
.frag6
);
4610 static void _usage(FILE *dest
)
4613 "Usage: ss [ OPTIONS ]\n"
4614 " ss [ OPTIONS ] [ FILTER ]\n"
4615 " -h, --help this message\n"
4616 " -V, --version output version information\n"
4617 " -n, --numeric don't resolve service names\n"
4618 " -r, --resolve resolve host names\n"
4619 " -a, --all display all sockets\n"
4620 " -l, --listening display listening sockets\n"
4621 " -o, --options show timer information\n"
4622 " -e, --extended show detailed socket information\n"
4623 " -m, --memory show socket memory usage\n"
4624 " -p, --processes show process using socket\n"
4625 " -i, --info show internal TCP information\n"
4626 " --tipcinfo show internal tipc socket information\n"
4627 " -s, --summary show socket usage summary\n"
4628 " -b, --bpf show bpf filter socket information\n"
4629 " -E, --events continually display sockets as they are destroyed\n"
4630 " -Z, --context display process SELinux security contexts\n"
4631 " -z, --contexts display process and socket SELinux security contexts\n"
4632 " -N, --net switch to the specified network namespace name\n"
4634 " -4, --ipv4 display only IP version 4 sockets\n"
4635 " -6, --ipv6 display only IP version 6 sockets\n"
4636 " -0, --packet display PACKET sockets\n"
4637 " -t, --tcp display only TCP sockets\n"
4638 " -S, --sctp display only SCTP sockets\n"
4639 " -u, --udp display only UDP sockets\n"
4640 " -d, --dccp display only DCCP sockets\n"
4641 " -w, --raw display only RAW sockets\n"
4642 " -x, --unix display only Unix domain sockets\n"
4643 " --tipc display only TIPC sockets\n"
4644 " --vsock display only vsock sockets\n"
4645 " -f, --family=FAMILY display sockets of type FAMILY\n"
4646 " FAMILY := {inet|inet6|link|unix|netlink|vsock|tipc|help}\n"
4648 " -K, --kill forcibly close sockets, display what was closed\n"
4649 " -H, --no-header Suppress header line\n"
4651 " -A, --query=QUERY, --socket=QUERY\n"
4652 " QUERY := {all|inet|tcp|udp|raw|unix|unix_dgram|unix_stream|unix_seqpacket|packet|netlink|vsock_stream|vsock_dgram|tipc}[,QUERY]\n"
4654 " -D, --diag=FILE Dump raw information about TCP sockets to FILE\n"
4655 " -F, --filter=FILE read filter information from FILE\n"
4656 " FILTER := [ state STATE-FILTER ] [ EXPRESSION ]\n"
4657 " STATE-FILTER := {all|connected|synchronized|bucket|big|TCP-STATES}\n"
4658 " TCP-STATES := {established|syn-sent|syn-recv|fin-wait-{1,2}|time-wait|closed|close-wait|last-ack|listening|closing}\n"
4659 " connected := {established|syn-sent|syn-recv|fin-wait-{1,2}|time-wait|close-wait|last-ack|closing}\n"
4660 " synchronized := {established|syn-recv|fin-wait-{1,2}|time-wait|close-wait|last-ack|closing}\n"
4661 " bucket := {syn-recv|time-wait}\n"
4662 " big := {established|syn-sent|fin-wait-{1,2}|closed|close-wait|last-ack|listening|closing}\n"
4666 static void help(void) __attribute__((noreturn
));
4667 static void help(void)
4673 static void usage(void) __attribute__((noreturn
));
4674 static void usage(void)
4681 static int scan_state(const char *state
)
4683 static const char * const sstate_namel
[] = {
4685 [SS_ESTABLISHED
] = "established",
4686 [SS_SYN_SENT
] = "syn-sent",
4687 [SS_SYN_RECV
] = "syn-recv",
4688 [SS_FIN_WAIT1
] = "fin-wait-1",
4689 [SS_FIN_WAIT2
] = "fin-wait-2",
4690 [SS_TIME_WAIT
] = "time-wait",
4691 [SS_CLOSE
] = "unconnected",
4692 [SS_CLOSE_WAIT
] = "close-wait",
4693 [SS_LAST_ACK
] = "last-ack",
4694 [SS_LISTEN
] = "listening",
4695 [SS_CLOSING
] = "closing",
4699 if (strcasecmp(state
, "close") == 0 ||
4700 strcasecmp(state
, "closed") == 0)
4701 return (1<<SS_CLOSE
);
4702 if (strcasecmp(state
, "syn-rcv") == 0)
4703 return (1<<SS_SYN_RECV
);
4704 if (strcasecmp(state
, "established") == 0)
4705 return (1<<SS_ESTABLISHED
);
4706 if (strcasecmp(state
, "all") == 0)
4708 if (strcasecmp(state
, "connected") == 0)
4709 return SS_ALL
& ~((1<<SS_CLOSE
)|(1<<SS_LISTEN
));
4710 if (strcasecmp(state
, "synchronized") == 0)
4711 return SS_ALL
& ~((1<<SS_CLOSE
)|(1<<SS_LISTEN
)|(1<<SS_SYN_SENT
));
4712 if (strcasecmp(state
, "bucket") == 0)
4713 return (1<<SS_SYN_RECV
)|(1<<SS_TIME_WAIT
);
4714 if (strcasecmp(state
, "big") == 0)
4715 return SS_ALL
& ~((1<<SS_SYN_RECV
)|(1<<SS_TIME_WAIT
));
4716 for (i
= 0; i
< SS_MAX
; i
++) {
4717 if (strcasecmp(state
, sstate_namel
[i
]) == 0)
4721 fprintf(stderr
, "ss: wrong state name: %s\n", state
);
4725 /* Values 'v' and 'V' are already used so a non-character is used */
4726 #define OPT_VSOCK 256
4728 /* Values of 't' are already used so a non-character is used */
4729 #define OPT_TIPCSOCK 257
4730 #define OPT_TIPCINFO 258
4732 static const struct option long_opts
[] = {
4733 { "numeric", 0, 0, 'n' },
4734 { "resolve", 0, 0, 'r' },
4735 { "options", 0, 0, 'o' },
4736 { "extended", 0, 0, 'e' },
4737 { "memory", 0, 0, 'm' },
4738 { "info", 0, 0, 'i' },
4739 { "processes", 0, 0, 'p' },
4740 { "bpf", 0, 0, 'b' },
4741 { "events", 0, 0, 'E' },
4742 { "dccp", 0, 0, 'd' },
4743 { "tcp", 0, 0, 't' },
4744 { "sctp", 0, 0, 'S' },
4745 { "udp", 0, 0, 'u' },
4746 { "raw", 0, 0, 'w' },
4747 { "unix", 0, 0, 'x' },
4748 { "tipc", 0, 0, OPT_TIPCSOCK
},
4749 { "vsock", 0, 0, OPT_VSOCK
},
4750 { "all", 0, 0, 'a' },
4751 { "listening", 0, 0, 'l' },
4752 { "ipv4", 0, 0, '4' },
4753 { "ipv6", 0, 0, '6' },
4754 { "packet", 0, 0, '0' },
4755 { "family", 1, 0, 'f' },
4756 { "socket", 1, 0, 'A' },
4757 { "query", 1, 0, 'A' },
4758 { "summary", 0, 0, 's' },
4759 { "diag", 1, 0, 'D' },
4760 { "filter", 1, 0, 'F' },
4761 { "version", 0, 0, 'V' },
4762 { "help", 0, 0, 'h' },
4763 { "context", 0, 0, 'Z' },
4764 { "contexts", 0, 0, 'z' },
4765 { "net", 1, 0, 'N' },
4766 { "tipcinfo", 0, 0, OPT_TIPCINFO
},
4767 { "kill", 0, 0, 'K' },
4768 { "no-header", 0, 0, 'H' },
4773 int main(int argc
, char *argv
[])
4778 const char *dump_tcpdiag
= NULL
;
4779 FILE *filter_fp
= NULL
;
4781 int state_filter
= 0;
4783 while ((ch
= getopt_long(argc
, argv
,
4784 "dhaletuwxnro460spbEf:miA:D:F:vVzZN:KHS",
4785 long_opts
, NULL
)) != EOF
) {
4788 resolve_services
= 0;
4808 user_ent_hash_build();
4818 filter_db_set(¤t_filter
, DCCP_DB
, true);
4821 filter_db_set(¤t_filter
, TCP_DB
, true);
4824 filter_db_set(¤t_filter
, SCTP_DB
, true);
4827 filter_db_set(¤t_filter
, UDP_DB
, true);
4830 filter_db_set(¤t_filter
, RAW_DB
, true);
4833 filter_af_set(¤t_filter
, AF_UNIX
);
4836 filter_af_set(¤t_filter
, AF_VSOCK
);
4839 filter_af_set(¤t_filter
, AF_TIPC
);
4842 state_filter
= SS_ALL
;
4845 state_filter
= (1 << SS_LISTEN
) | (1 << SS_CLOSE
);
4848 filter_af_set(¤t_filter
, AF_INET
);
4851 filter_af_set(¤t_filter
, AF_INET6
);
4854 filter_af_set(¤t_filter
, AF_PACKET
);
4857 if (strcmp(optarg
, "inet") == 0)
4858 filter_af_set(¤t_filter
, AF_INET
);
4859 else if (strcmp(optarg
, "inet6") == 0)
4860 filter_af_set(¤t_filter
, AF_INET6
);
4861 else if (strcmp(optarg
, "link") == 0)
4862 filter_af_set(¤t_filter
, AF_PACKET
);
4863 else if (strcmp(optarg
, "unix") == 0)
4864 filter_af_set(¤t_filter
, AF_UNIX
);
4865 else if (strcmp(optarg
, "netlink") == 0)
4866 filter_af_set(¤t_filter
, AF_NETLINK
);
4867 else if (strcmp(optarg
, "tipc") == 0)
4868 filter_af_set(¤t_filter
, AF_TIPC
);
4869 else if (strcmp(optarg
, "vsock") == 0)
4870 filter_af_set(¤t_filter
, AF_VSOCK
);
4871 else if (strcmp(optarg
, "help") == 0)
4874 fprintf(stderr
, "ss: \"%s\" is invalid family\n",
4884 current_filter
.dbs
= 0;
4885 state_filter
= state_filter
?
4886 state_filter
: SS_CONN
;
4892 if ((p1
= strchr(p
, ',')) != NULL
)
4894 if (filter_db_parse(¤t_filter
, p
)) {
4895 fprintf(stderr
, "ss: \"%s\" is illegal socket table id\n", p
);
4906 dump_tcpdiag
= optarg
;
4910 fprintf(stderr
, "More than one filter file\n");
4913 if (optarg
[0] == '-')
4916 filter_fp
= fopen(optarg
, "r");
4918 perror("fopen filter file");
4924 printf("ss utility, iproute2-ss%s\n", SNAPSHOT
);
4930 if (is_selinux_enabled() <= 0) {
4931 fprintf(stderr
, "ss: SELinux is not enabled.\n");
4935 user_ent_hash_build();
4938 if (netns_switch(optarg
))
4945 current_filter
.kill
= 1;
4963 if (do_default
&& argc
== 0)
4968 if (strcmp(*argv
, "state") == 0) {
4972 state_filter
|= scan_state(*argv
);
4974 } else if (strcmp(*argv
, "exclude") == 0 ||
4975 strcmp(*argv
, "excl") == 0) {
4978 state_filter
= SS_ALL
;
4979 state_filter
&= ~scan_state(*argv
);
4988 state_filter
= state_filter
? state_filter
: SS_CONN
;
4989 filter_db_parse(¤t_filter
, "all");
4992 filter_states_set(¤t_filter
, state_filter
);
4993 filter_merge_defaults(¤t_filter
);
4995 if (resolve_services
&& resolve_hosts
&&
4996 (current_filter
.dbs
& (UNIX_DBM
|INET_L4_DBM
)))
4997 init_service_resolver();
4999 if (current_filter
.dbs
== 0) {
5000 fprintf(stderr
, "ss: no socket tables to show with such filter.\n");
5003 if (current_filter
.families
== 0) {
5004 fprintf(stderr
, "ss: no families to show with such filter.\n");
5007 if (current_filter
.states
== 0) {
5008 fprintf(stderr
, "ss: no socket states to show with such filter.\n");
5013 FILE *dump_fp
= stdout
;
5015 if (!(current_filter
.dbs
& (1<<TCP_DB
))) {
5016 fprintf(stderr
, "ss: tcpdiag dump requested and no tcp in filter.\n");
5019 if (dump_tcpdiag
[0] != '-') {
5020 dump_fp
= fopen(dump_tcpdiag
, "w");
5021 if (!dump_tcpdiag
) {
5022 perror("fopen dump file");
5026 inet_show_netlink(¤t_filter
, dump_fp
, IPPROTO_TCP
);
5031 if (ssfilter_parse(¤t_filter
.f
, argc
, argv
, filter_fp
))
5034 if (!(current_filter
.dbs
& (current_filter
.dbs
- 1)))
5035 columns
[COL_NETID
].disabled
= 1;
5037 if (!(current_filter
.states
& (current_filter
.states
- 1)))
5038 columns
[COL_STATE
].disabled
= 1;
5046 exit(handle_follow_request(¤t_filter
));
5048 if (current_filter
.dbs
& (1<<NETLINK_DB
))
5049 netlink_show(¤t_filter
);
5050 if (current_filter
.dbs
& PACKET_DBM
)
5051 packet_show(¤t_filter
);
5052 if (current_filter
.dbs
& UNIX_DBM
)
5053 unix_show(¤t_filter
);
5054 if (current_filter
.dbs
& (1<<RAW_DB
))
5055 raw_show(¤t_filter
);
5056 if (current_filter
.dbs
& (1<<UDP_DB
))
5057 udp_show(¤t_filter
);
5058 if (current_filter
.dbs
& (1<<TCP_DB
))
5059 tcp_show(¤t_filter
);
5060 if (current_filter
.dbs
& (1<<DCCP_DB
))
5061 dccp_show(¤t_filter
);
5062 if (current_filter
.dbs
& (1<<SCTP_DB
))
5063 sctp_show(¤t_filter
);
5064 if (current_filter
.dbs
& VSOCK_DBM
)
5065 vsock_show(¤t_filter
);
5066 if (current_filter
.dbs
& (1<<TIPC_DB
))
5067 tipc_show(¤t_filter
);
5069 if (show_users
|| show_proc_ctx
|| show_sock_ctx
)