linux下 ss -i 可显示rto.

how to display tcp rto

http://linuxaleph.blogspot.com/2013/07/how-to-display-tcp-rto.html

 /*
* ss.c "sockstat", socket statistics
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version
* 2 of the License, or (at your option) any later version.
*
* Authors: Alexey Kuznetsov, <kuznet@ms2.inr.ac.ru>
*/ #include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <syslog.h>
#include <fcntl.h>
#include <sys/ioctl.h>
#include <sys/socket.h>
#include <sys/uio.h>
#include <netinet/in.h>
#include <string.h>
#include <errno.h>
#include <netdb.h>
#include <arpa/inet.h>
#include <resolv.h>
#include <dirent.h>
#include <fnmatch.h>
#include <getopt.h> #include "utils.h"
#include "rt_names.h"
#include "ll_map.h"
#include "libnetlink.h"
#include "SNAPSHOT.h" #include <netinet/tcp.h>
#include <linux/inet_diag.h> int resolve_hosts = ;
int resolve_services = ;
int preferred_family = AF_UNSPEC;
int show_options = ;
int show_details = ;
int show_users = ;
int show_mem = ;
int show_tcpinfo = ; int netid_width;
int state_width;
int addrp_width;
int addr_width;
int serv_width;
int screen_width; static const char *TCP_PROTO = "tcp";
static const char *UDP_PROTO = "udp";
static const char *RAW_PROTO = "raw";
static const char *dg_proto = NULL; enum
{
TCP_DB,
DCCP_DB,
UDP_DB,
RAW_DB,
UNIX_DG_DB,
UNIX_ST_DB,
PACKET_DG_DB,
PACKET_R_DB,
NETLINK_DB,
MAX_DB
}; #define PACKET_DBM ((1<<PACKET_DG_DB)|(1<<PACKET_R_DB))
#define UNIX_DBM ((1<<UNIX_DG_DB)|(1<<UNIX_ST_DB))
#define ALL_DB ((1<<MAX_DB)-1) enum {
SS_UNKNOWN,
SS_ESTABLISHED,
SS_SYN_SENT,
SS_SYN_RECV,
SS_FIN_WAIT1,
SS_FIN_WAIT2,
SS_TIME_WAIT,
SS_CLOSE,
SS_CLOSE_WAIT,
SS_LAST_ACK,
SS_LISTEN,
SS_CLOSING,
SS_MAX
}; #define SS_ALL ((1<<SS_MAX)-1) #include "ssfilter.h" struct filter
{
int dbs;
int states;
int families;
struct ssfilter *f;
}; struct filter default_filter = {
.dbs = (<<TCP_DB),
.states = SS_ALL & ~((<<SS_LISTEN)|(<<SS_CLOSE)|(<<SS_TIME_WAIT)|(<<SS_SYN_RECV)),
.families= (<<AF_INET)|(<<AF_INET6),
}; struct filter current_filter; static FILE *generic_proc_open(const char *env, const char *name)
{
const char *p = getenv(env);
char store[]; if (!p) {
p = getenv("PROC_ROOT") ? : "/proc";
snprintf(store, sizeof(store)-, "%s/%s", p, name);
p = store;
} return fopen(p, "r");
} static FILE *net_tcp_open(void)
{
return generic_proc_open("PROC_NET_TCP", "net/tcp");
} static FILE *net_tcp6_open(void)
{
return generic_proc_open("PROC_NET_TCP6", "net/tcp6");
} static FILE *net_udp_open(void)
{
return generic_proc_open("PROC_NET_UDP", "net/udp");
} static FILE *net_udp6_open(void)
{
return generic_proc_open("PROC_NET_UDP6", "net/udp6");
} static FILE *net_raw_open(void)
{
return generic_proc_open("PROC_NET_RAW", "net/raw");
} static FILE *net_raw6_open(void)
{
return generic_proc_open("PROC_NET_RAW6", "net/raw6");
} static FILE *net_unix_open(void)
{
return generic_proc_open("PROC_NET_UNIX", "net/unix");
} static FILE *net_packet_open(void)
{
return generic_proc_open("PROC_NET_PACKET", "net/packet");
} static FILE *net_netlink_open(void)
{
return generic_proc_open("PROC_NET_NETLINK", "net/netlink");
} static FILE *slabinfo_open(void)
{
return generic_proc_open("PROC_SLABINFO", "slabinfo");
} static FILE *net_sockstat_open(void)
{
return generic_proc_open("PROC_NET_SOCKSTAT", "net/sockstat");
} static FILE *net_sockstat6_open(void)
{
return generic_proc_open("PROC_NET_SOCKSTAT6", "net/sockstat6");
} static FILE *net_snmp_open(void)
{
return generic_proc_open("PROC_NET_SNMP", "net/snmp");
} static FILE *ephemeral_ports_open(void)
{
return generic_proc_open("PROC_IP_LOCAL_PORT_RANGE", "sys/net/ipv4/ip_local_port_range");
} struct user_ent {
struct user_ent *next;
unsigned int ino;
int pid;
int fd;
char process[];
}; #define USER_ENT_HASH_SIZE 256
struct user_ent *user_ent_hash[USER_ENT_HASH_SIZE]; static int user_ent_hashfn(unsigned int ino)
{
int val = (ino >> ) ^ (ino >> ) ^ (ino >> ) ^ ino; return val & (USER_ENT_HASH_SIZE - );
} static void user_ent_add(unsigned int ino, const char *process, int pid, int fd)
{
struct user_ent *p, **pp;
int str_len; str_len = strlen(process) + ;
p = malloc(sizeof(struct user_ent) + str_len);
if (!p)
abort();
p->next = NULL;
p->ino = ino;
p->pid = pid;
p->fd = fd;
strcpy(p->process, process); pp = &user_ent_hash[user_ent_hashfn(ino)];
p->next = *pp;
*pp = p;
} static void user_ent_hash_build(void)
{
const char *root = getenv("PROC_ROOT") ? : "/proc/";
struct dirent *d;
char name[];
int nameoff;
DIR *dir; strcpy(name, root);
if (strlen(name) == || name[strlen(name)-] != '/')
strcat(name, "/"); nameoff = strlen(name); dir = opendir(name);
if (!dir)
return; while ((d = readdir(dir)) != NULL) {
struct dirent *d1;
char process[];
int pid, pos;
DIR *dir1;
char crap; if (sscanf(d->d_name, "%d%c", &pid, &crap) != )
continue; sprintf(name + nameoff, "%d/fd/", pid);
pos = strlen(name);
if ((dir1 = opendir(name)) == NULL)
continue; process[] = '\0'; while ((d1 = readdir(dir1)) != NULL) {
const char *pattern = "socket:[";
unsigned int ino;
char lnk[];
int fd; if (sscanf(d1->d_name, "%d%c", &fd, &crap) != )
continue; sprintf(name+pos, "%d", fd);
if (readlink(name, lnk, sizeof(lnk)-) < ||
strncmp(lnk, pattern, strlen(pattern)))
continue; sscanf(lnk, "socket:[%u]", &ino); if (process[] == '\0') {
char tmp[];
FILE *fp; snprintf(tmp, sizeof(tmp), "%s/%d/stat", root, pid);
if ((fp = fopen(tmp, "r")) != NULL) {
fscanf(fp, "%*d (%[^)])", process);
fclose(fp);
}
} user_ent_add(ino, process, pid, fd);
}
closedir(dir1);
}
closedir(dir);
} int find_users(unsigned ino, char *buf, int buflen)
{
struct user_ent *p;
int cnt = ;
char *ptr; if (!ino)
return ; p = user_ent_hash[user_ent_hashfn(ino)];
ptr = buf;
while (p) {
if (p->ino != ino)
goto next; if (ptr - buf >= buflen - )
break; snprintf(ptr, buflen - (ptr - buf),
"(\"%s\",%d,%d),",
p->process, p->pid, p->fd);
ptr += strlen(ptr);
cnt++; next:
p = p->next;
} if (ptr != buf)
ptr[-] = '\0'; return cnt;
} /* Get stats from slab */ struct slabstat
{
int socks;
int tcp_ports;
int tcp_tws;
int tcp_syns;
int skbs;
}; struct slabstat slabstat; static const char *slabstat_ids[] =
{
"sock",
"tcp_bind_bucket",
"tcp_tw_bucket",
"tcp_open_request",
"skbuff_head_cache",
}; int get_slabstat(struct slabstat *s)
{
char buf[];
FILE *fp;
int cnt; memset(s, , sizeof(*s)); fp = slabinfo_open();
if (!fp)
return -; cnt = sizeof(*s)/sizeof(int); fgets(buf, sizeof(buf), fp);
while(fgets(buf, sizeof(buf), fp) != NULL) {
int i;
for (i=; i<sizeof(slabstat_ids)/sizeof(slabstat_ids[]); i++) {
if (memcmp(buf, slabstat_ids[i], strlen(slabstat_ids[i])) == ) {
sscanf(buf, "%*s%d", ((int *)s) + i);
cnt--;
break;
}
}
if (cnt <= )
break;
} fclose(fp);
return ;
} static const char *sstate_name[] = {
"UNKNOWN",
[TCP_ESTABLISHED] = "ESTAB",
[TCP_SYN_SENT] = "SYN-SENT",
[TCP_SYN_RECV] = "SYN-RECV",
[TCP_FIN_WAIT1] = "FIN-WAIT-1",
[TCP_FIN_WAIT2] = "FIN-WAIT-2",
[TCP_TIME_WAIT] = "TIME-WAIT",
[TCP_CLOSE] = "UNCONN",
[TCP_CLOSE_WAIT] = "CLOSE-WAIT",
[TCP_LAST_ACK] = "LAST-ACK",
[TCP_LISTEN] = "LISTEN",
[TCP_CLOSING] = "CLOSING",
}; static const char *sstate_namel[] = {
"UNKNOWN",
[TCP_ESTABLISHED] = "established",
[TCP_SYN_SENT] = "syn-sent",
[TCP_SYN_RECV] = "syn-recv",
[TCP_FIN_WAIT1] = "fin-wait-1",
[TCP_FIN_WAIT2] = "fin-wait-2",
[TCP_TIME_WAIT] = "time-wait",
[TCP_CLOSE] = "unconnected",
[TCP_CLOSE_WAIT] = "close-wait",
[TCP_LAST_ACK] = "last-ack",
[TCP_LISTEN] = "listening",
[TCP_CLOSING] = "closing",
}; struct tcpstat
{
inet_prefix local;
inet_prefix remote;
int lport;
int rport;
int state;
int rq, wq;
int timer;
int timeout;
int retrs;
unsigned ino;
int probes;
unsigned uid;
int refcnt;
unsigned long long sk;
int rto, ato, qack, cwnd, ssthresh;
}; static const char *tmr_name[] = {
"off",
"on",
"keepalive",
"timewait",
"persist",
"unknown"
}; const char *print_ms_timer(int timeout)
{
static char buf[];
int secs, msecs, minutes;
if (timeout < )
timeout = ;
secs = timeout/;
minutes = secs/;
secs = secs%;
msecs = timeout%;
buf[] = ;
if (minutes) {
msecs = ;
snprintf(buf, sizeof(buf)-, "%dmin", minutes);
if (minutes > )
secs = ;
}
if (secs) {
if (secs > )
msecs = ;
sprintf(buf+strlen(buf), "%d%s", secs, msecs ? "." : "sec");
}
if (msecs)
sprintf(buf+strlen(buf), "%03dms", msecs);
return buf;
} const char *print_hz_timer(int timeout)
{
int hz = get_user_hz();
return print_ms_timer(((timeout*) + hz-)/hz);
} struct scache
{
struct scache *next;
int port;
char *name;
const char *proto;
}; struct scache *rlist; void init_service_resolver(void)
{
char buf[];
FILE *fp = popen("/usr/sbin/rpcinfo -p 2>/dev/null", "r");
if (fp) {
fgets(buf, sizeof(buf), fp);
while (fgets(buf, sizeof(buf), fp) != NULL) {
unsigned int progn, port;
char proto[], prog[];
if (sscanf(buf, "%u %*d %s %u %s", &progn, proto,
&port, prog+) == ) {
struct scache *c = malloc(sizeof(*c));
if (c) {
c->port = port;
memcpy(prog, "rpc.", );
c->name = strdup(prog);
if (strcmp(proto, TCP_PROTO) == )
c->proto = TCP_PROTO;
else if (strcmp(proto, UDP_PROTO) == )
c->proto = UDP_PROTO;
else
c->proto = NULL;
c->next = rlist;
rlist = c;
}
}
}
pclose(fp);
}
} static int ip_local_port_min, ip_local_port_max; /* Even do not try default linux ephemeral port ranges:
* default /etc/services contains so much of useless crap
* wouldbe "allocated" to this area that resolution
* is really harmful. I shrug each time when seeing
* "socks" or "cfinger" in dumps.
*/
static int is_ephemeral(int port)
{
if (!ip_local_port_min) {
FILE *f = ephemeral_ports_open();
if (f) {
fscanf(f, "%d %d",
&ip_local_port_min, &ip_local_port_max);
fclose(f);
} else {
ip_local_port_min = ;
ip_local_port_max = ;
}
} return (port >= ip_local_port_min && port<= ip_local_port_max);
} const char *__resolve_service(int port)
{
struct scache *c; for (c = rlist; c; c = c->next) {
if (c->port == port && c->proto == dg_proto)
return c->name;
} if (!is_ephemeral(port)) {
static int notfirst;
struct servent *se;
if (!notfirst) {
setservent();
notfirst = ;
}
se = getservbyport(htons(port), dg_proto);
if (se)
return se->s_name;
} return NULL;
} const char *resolve_service(int port)
{
static char buf[];
static struct scache cache[]; if (port == ) {
buf[] = '*';
buf[] = ;
return buf;
} if (resolve_services) {
if (dg_proto == RAW_PROTO) {
return inet_proto_n2a(port, buf, sizeof(buf));
} else {
struct scache *c;
const char *res;
int hash = (port^(((unsigned long)dg_proto)>>))&; for (c = &cache[hash]; c; c = c->next) {
if (c->port == port &&
c->proto == dg_proto) {
if (c->name)
return c->name;
goto do_numeric;
}
} if ((res = __resolve_service(port)) != NULL) {
if ((c = malloc(sizeof(*c))) == NULL)
goto do_numeric;
} else {
c = &cache[hash];
if (c->name)
free(c->name);
}
c->port = port;
c->name = NULL;
c->proto = dg_proto;
if (res) {
c->name = strdup(res);
c->next = cache[hash].next;
cache[hash].next = c;
}
if (c->name)
return c->name;
}
} do_numeric:
sprintf(buf, "%u", port);
return buf;
} void formatted_print(const inet_prefix *a, int port)
{
char buf[];
const char *ap = buf;
int est_len; est_len = addr_width; if (a->family == AF_INET) {
if (a->data[] == ) {
buf[] = '*';
buf[] = ;
} else {
ap = format_host(AF_INET, , a->data, buf, sizeof(buf));
}
} else {
ap = format_host(a->family, , a->data, buf, sizeof(buf));
est_len = strlen(ap);
if (est_len <= addr_width)
est_len = addr_width;
else
est_len = addr_width + ((est_len-addr_width+)/)*;
}
printf("%*s:%-*s ", est_len, ap, serv_width, resolve_service(port));
} struct aafilter
{
inet_prefix addr;
int port;
struct aafilter *next;
}; int inet2_addr_match(const inet_prefix *a, const inet_prefix *p, int plen)
{
if (!inet_addr_match(a, p, plen))
return ; /* Cursed "v4 mapped" addresses: v4 mapped socket matches
* pure IPv4 rule, but v4-mapped rule selects only v4-mapped
* sockets. Fair? */
if (p->family == AF_INET && a->family == AF_INET6) {
if (a->data[] == && a->data[] == &&
a->data[] == htonl(0xffff)) {
inet_prefix tmp = *a;
tmp.data[] = a->data[];
return inet_addr_match(&tmp, p, plen);
}
}
return ;
} int unix_match(const inet_prefix *a, const inet_prefix *p)
{
char *addr, *pattern;
memcpy(&addr, a->data, sizeof(addr));
memcpy(&pattern, p->data, sizeof(pattern));
if (pattern == NULL)
return ;
if (addr == NULL)
addr = "";
return !fnmatch(pattern, addr, );
} int run_ssfilter(struct ssfilter *f, struct tcpstat *s)
{
switch (f->type) {
case SSF_S_AUTO:
{
static int low, high=; if (s->local.family == AF_UNIX) {
char *p;
memcpy(&p, s->local.data, sizeof(p));
return p == NULL || (p[] == '@' && strlen(p) == &&
strspn(p+, "0123456789abcdef") == );
}
if (s->local.family == AF_PACKET)
return s->lport == && s->local.data == ;
if (s->local.family == AF_NETLINK)
return s->lport < ; if (!low) {
FILE *fp = ephemeral_ports_open();
if (fp) {
fscanf(fp, "%d%d", &low, &high);
fclose(fp);
}
}
return s->lport >= low && s->lport <= high;
}
case SSF_DCOND:
{
struct aafilter *a = (void*)f->pred;
if (a->addr.family == AF_UNIX)
return unix_match(&s->remote, &a->addr);
if (a->port != - && a->port != s->rport)
return ;
if (a->addr.bitlen) {
do {
if (!inet2_addr_match(&s->remote, &a->addr, a->addr.bitlen))
return ;
} while ((a = a->next) != NULL);
return ;
}
return ;
}
case SSF_SCOND:
{
struct aafilter *a = (void*)f->pred;
if (a->addr.family == AF_UNIX)
return unix_match(&s->local, &a->addr);
if (a->port != - && a->port != s->lport)
return ;
if (a->addr.bitlen) {
do {
if (!inet2_addr_match(&s->local, &a->addr, a->addr.bitlen))
return ;
} while ((a = a->next) != NULL);
return ;
}
return ;
}
case SSF_D_GE:
{
struct aafilter *a = (void*)f->pred;
return s->rport >= a->port;
}
case SSF_D_LE:
{
struct aafilter *a = (void*)f->pred;
return s->rport <= a->port;
}
case SSF_S_GE:
{
struct aafilter *a = (void*)f->pred;
return s->lport >= a->port;
}
case SSF_S_LE:
{
struct aafilter *a = (void*)f->pred;
return s->lport <= a->port;
} /* Yup. It is recursion. Sorry. */
case SSF_AND:
return run_ssfilter(f->pred, s) && run_ssfilter(f->post, s);
case SSF_OR:
return run_ssfilter(f->pred, s) || run_ssfilter(f->post, s);
case SSF_NOT:
return !run_ssfilter(f->pred, s);
default:
abort();
}
} /* Relocate external jumps by reloc. */
static void ssfilter_patch(char *a, int len, int reloc)
{
while (len > ) {
struct inet_diag_bc_op *op = (struct inet_diag_bc_op*)a;
if (op->no == len+)
op->no += reloc;
len -= op->yes;
a += op->yes;
}
if (len < )
abort();
} static int ssfilter_bytecompile(struct ssfilter *f, char **bytecode)
{
switch (f->type) {
case SSF_S_AUTO:
{
if (!(*bytecode=malloc())) abort();
((struct inet_diag_bc_op*)*bytecode)[] = (struct inet_diag_bc_op){ INET_DIAG_BC_AUTO, , };
return ;
}
case SSF_DCOND:
case SSF_SCOND:
{
struct aafilter *a = (void*)f->pred;
struct aafilter *b;
char *ptr;
int code = (f->type == SSF_DCOND ? INET_DIAG_BC_D_COND : INET_DIAG_BC_S_COND);
int len = ; for (b=a; b; b=b->next) {
len += + sizeof(struct inet_diag_hostcond);
if (a->addr.family == AF_INET6)
len += ;
else
len += ;
if (b->next)
len += ;
}
if (!(ptr = malloc(len))) abort();
*bytecode = ptr;
for (b=a; b; b=b->next) {
struct inet_diag_bc_op *op = (struct inet_diag_bc_op *)ptr;
int alen = (a->addr.family == AF_INET6 ? : );
int oplen = alen + + sizeof(struct inet_diag_hostcond);
struct inet_diag_hostcond *cond = (struct inet_diag_hostcond*)(ptr+); *op = (struct inet_diag_bc_op){ code, oplen, oplen+ };
cond->family = a->addr.family;
cond->port = a->port;
cond->prefix_len = a->addr.bitlen;
memcpy(cond->addr, a->addr.data, alen);
ptr += oplen;
if (b->next) {
op = (struct inet_diag_bc_op *)ptr;
*op = (struct inet_diag_bc_op){ INET_DIAG_BC_JMP, , len - (ptr-*bytecode)};
ptr += ;
}
}
return ptr - *bytecode;
}
case SSF_D_GE:
{
struct aafilter *x = (void*)f->pred;
if (!(*bytecode=malloc())) abort();
((struct inet_diag_bc_op*)*bytecode)[] = (struct inet_diag_bc_op){ INET_DIAG_BC_D_GE, , };
((struct inet_diag_bc_op*)*bytecode)[] = (struct inet_diag_bc_op){ , , x->port };
return ;
}
case SSF_D_LE:
{
struct aafilter *x = (void*)f->pred;
if (!(*bytecode=malloc())) abort();
((struct inet_diag_bc_op*)*bytecode)[] = (struct inet_diag_bc_op){ INET_DIAG_BC_D_LE, , };
((struct inet_diag_bc_op*)*bytecode)[] = (struct inet_diag_bc_op){ , , x->port };
return ;
}
case SSF_S_GE:
{
struct aafilter *x = (void*)f->pred;
if (!(*bytecode=malloc())) abort();
((struct inet_diag_bc_op*)*bytecode)[] = (struct inet_diag_bc_op){ INET_DIAG_BC_S_GE, , };
((struct inet_diag_bc_op*)*bytecode)[] = (struct inet_diag_bc_op){ , , x->port };
return ;
}
case SSF_S_LE:
{
struct aafilter *x = (void*)f->pred;
if (!(*bytecode=malloc())) abort();
((struct inet_diag_bc_op*)*bytecode)[] = (struct inet_diag_bc_op){ INET_DIAG_BC_S_LE, , };
((struct inet_diag_bc_op*)*bytecode)[] = (struct inet_diag_bc_op){ , , x->port };
return ;
} case SSF_AND:
{
char *a1, *a2, *a, l1, l2;
l1 = ssfilter_bytecompile(f->pred, &a1);
l2 = ssfilter_bytecompile(f->post, &a2);
if (!(a = malloc(l1+l2))) abort();
memcpy(a, a1, l1);
memcpy(a+l1, a2, l2);
free(a1); free(a2);
ssfilter_patch(a, l1, l2);
*bytecode = a;
return l1+l2;
}
case SSF_OR:
{
char *a1, *a2, *a, l1, l2;
l1 = ssfilter_bytecompile(f->pred, &a1);
l2 = ssfilter_bytecompile(f->post, &a2);
if (!(a = malloc(l1+l2+))) abort();
memcpy(a, a1, l1);
memcpy(a+l1+, a2, l2);
free(a1); free(a2);
*(struct inet_diag_bc_op*)(a+l1) = (struct inet_diag_bc_op){ INET_DIAG_BC_JMP, , l2+ };
*bytecode = a;
return l1+l2+;
}
case SSF_NOT:
{
char *a1, *a, l1;
l1 = ssfilter_bytecompile(f->pred, &a1);
if (!(a = malloc(l1+))) abort();
memcpy(a, a1, l1);
free(a1);
*(struct inet_diag_bc_op*)(a+l1) = (struct inet_diag_bc_op){ INET_DIAG_BC_JMP, , };
*bytecode = a;
return l1+;
}
default:
abort();
}
} static int remember_he(struct aafilter *a, struct hostent *he)
{
char **ptr = he->h_addr_list;
int cnt = ;
int len; if (he->h_addrtype == AF_INET)
len = ;
else if (he->h_addrtype == AF_INET6)
len = ;
else
return ; while (*ptr) {
struct aafilter *b = a;
if (a->addr.bitlen) {
if ((b = malloc(sizeof(*b))) == NULL)
return cnt;
*b = *a;
b->next = a->next;
a->next = b;
}
memcpy(b->addr.data, *ptr, len);
b->addr.bytelen = len;
b->addr.bitlen = len*;
b->addr.family = he->h_addrtype;
ptr++;
cnt++;
}
return cnt;
} static int get_dns_host(struct aafilter *a, const char *addr, int fam)
{
static int notfirst;
int cnt = ;
struct hostent *he; a->addr.bitlen = ;
if (!notfirst) {
sethostent();
notfirst = ;
}
he = gethostbyname2(addr, fam == AF_UNSPEC ? AF_INET : fam);
if (he)
cnt = remember_he(a, he);
if (fam == AF_UNSPEC) {
he = gethostbyname2(addr, AF_INET6);
if (he)
cnt += remember_he(a, he);
}
return !cnt;
} static int xll_initted = ; static void xll_init(void)
{
struct rtnl_handle rth;
rtnl_open(&rth, );
ll_init_map(&rth);
rtnl_close(&rth);
xll_initted = ;
} static const char *xll_index_to_name(int index)
{
if (!xll_initted)
xll_init();
return ll_index_to_name(index);
} static int xll_name_to_index(const char *dev)
{
if (!xll_initted)
xll_init();
return ll_name_to_index(dev);
} void *parse_hostcond(char *addr)
{
char *port = NULL;
struct aafilter a;
struct aafilter *res;
int fam = preferred_family; memset(&a, , sizeof(a));
a.port = -; if (fam == AF_UNIX || strncmp(addr, "unix:", ) == ) {
char *p;
a.addr.family = AF_UNIX;
if (strncmp(addr, "unix:", ) == )
addr+=;
p = strdup(addr);
a.addr.bitlen = *strlen(p);
memcpy(a.addr.data, &p, sizeof(p));
goto out;
} if (fam == AF_PACKET || strncmp(addr, "link:", ) == ) {
a.addr.family = AF_PACKET;
a.addr.bitlen = ;
if (strncmp(addr, "link:", ) == )
addr+=;
port = strchr(addr, ':');
if (port) {
*port = ;
if (port[] && strcmp(port+, "*")) {
if (get_integer(&a.port, port+, )) {
if ((a.port = xll_name_to_index(port+)) <= )
return NULL;
}
}
}
if (addr[] && strcmp(addr, "*")) {
unsigned short tmp;
a.addr.bitlen = ;
if (ll_proto_a2n(&tmp, addr))
return NULL;
a.addr.data[] = ntohs(tmp);
}
goto out;
} if (fam == AF_NETLINK || strncmp(addr, "netlink:", ) == ) {
a.addr.family = AF_NETLINK;
a.addr.bitlen = ;
if (strncmp(addr, "netlink:", ) == )
addr+=;
port = strchr(addr, ':');
if (port) {
*port = ;
if (port[] && strcmp(port+, "*")) {
if (get_integer(&a.port, port+, )) {
if (strcmp(port+, "kernel") == )
a.port = ;
else
return NULL;
}
}
}
if (addr[] && strcmp(addr, "*")) {
a.addr.bitlen = ;
if (get_u32(a.addr.data, addr, )) {
if (strcmp(addr, "rtnl") == )
a.addr.data[] = ;
else if (strcmp(addr, "fw") == )
a.addr.data[] = ;
else if (strcmp(addr, "tcpdiag") == )
a.addr.data[] = ;
else
return NULL;
}
}
goto out;
} if (strncmp(addr, "inet:", ) == ) {
addr += ;
fam = AF_INET;
} else if (strncmp(addr, "inet6:", ) == ) {
addr += ;
fam = AF_INET6;
} /* URL-like literal [] */
if (addr[] == '[') {
addr++;
if ((port = strchr(addr, ']')) == NULL)
return NULL;
*port++ = ;
} else if (addr[] == '*') {
port = addr+;
} else {
port = strrchr(strchr(addr, '/') ? : addr, ':');
}
if (port && *port) {
if (*port != ':')
return NULL;
*port++ = ;
if (*port && *port != '*') {
if (get_integer(&a.port, port, )) {
struct servent *se1 = NULL;
struct servent *se2 = NULL;
if (current_filter.dbs&(<<UDP_DB))
se1 = getservbyname(port, UDP_PROTO);
if (current_filter.dbs&(<<TCP_DB))
se2 = getservbyname(port, TCP_PROTO);
if (se1 && se2 && se1->s_port != se2->s_port) {
fprintf(stderr, "Error: ambiguous port \"%s\".\n", port);
return NULL;
}
if (!se1)
se1 = se2;
if (se1) {
a.port = ntohs(se1->s_port);
} else {
struct scache *s;
for (s = rlist; s; s = s->next) {
if ((s->proto == UDP_PROTO &&
(current_filter.dbs&(<<UDP_DB))) ||
(s->proto == TCP_PROTO &&
(current_filter.dbs&(<<TCP_DB)))) {
if (s->name && strcmp(s->name, port) == ) {
if (a.port > && a.port != s->port) {
fprintf(stderr, "Error: ambiguous port \"%s\".\n", port);
return NULL;
}
a.port = s->port;
}
}
}
if (a.port <= ) {
fprintf(stderr, "Error: \"%s\" does not look like a port.\n", port);
return NULL;
}
}
}
}
}
if (addr && *addr && *addr != '*') {
if (get_prefix_1(&a.addr, addr, fam)) {
if (get_dns_host(&a, addr, fam)) {
fprintf(stderr, "Error: an inet prefix is expected rather than \"%s\".\n", addr);
return NULL;
}
}
} out:
res = malloc(sizeof(*res));
if (res)
memcpy(res, &a, sizeof(a));
return res;
} static int tcp_show_line(char *line, const struct filter *f, int family)
{
struct tcpstat s;
char *loc, *rem, *data;
char opt[];
int n;
char *p; if ((p = strchr(line, ':')) == NULL)
return -;
loc = p+; if ((p = strchr(loc, ':')) == NULL)
return -;
p[] = ;
rem = p+; if ((p = strchr(rem, ':')) == NULL)
return -;
p[] = ;
data = p+; do {
int state = (data[] >= 'A') ? (data[] - 'A' + ) : (data[] - ''); if (!(f->states & (<<state)))
return ;
} while (); s.local.family = s.remote.family = family;
if (family == AF_INET) {
sscanf(loc, "%x:%x", s.local.data, (unsigned*)&s.lport);
sscanf(rem, "%x:%x", s.remote.data, (unsigned*)&s.rport);
s.local.bytelen = s.remote.bytelen = ;
} else {
sscanf(loc, "%08x%08x%08x%08x:%x",
s.local.data,
s.local.data+,
s.local.data+,
s.local.data+,
&s.lport);
sscanf(rem, "%08x%08x%08x%08x:%x",
s.remote.data,
s.remote.data+,
s.remote.data+,
s.remote.data+,
&s.rport);
s.local.bytelen = s.remote.bytelen = ;
} if (f->f && run_ssfilter(f->f, &s) == )
return ; opt[] = ;
n = sscanf(data, "%x %x:%x %x:%x %x %d %d %u %d %llx %d %d %d %d %d %[^\n]\n",
&s.state, &s.wq, &s.rq,
&s.timer, &s.timeout, &s.retrs, &s.uid, &s.probes, &s.ino,
&s.refcnt, &s.sk, &s.rto, &s.ato, &s.qack,
&s.cwnd, &s.ssthresh, opt); if (n < )
opt[] = ; if (n < ) {
s.rto = ;
s.cwnd = ;
s.ssthresh = -;
s.ato = s.qack = ;
} if (netid_width)
printf("%-*s ", netid_width, "tcp");
if (state_width)
printf("%-*s ", state_width, sstate_name[s.state]); printf("%-6d %-6d ", s.rq, s.wq); formatted_print(&s.local, s.lport);
formatted_print(&s.remote, s.rport); if (show_options) {
if (s.timer) {
if (s.timer > )
s.timer = ;
printf(" timer:(%s,%s,%d)",
tmr_name[s.timer],
print_hz_timer(s.timeout),
s.timer != ? s.probes : s.retrs);
}
}
if (show_tcpinfo) {
int hz = get_user_hz();
if (s.rto && s.rto != *hz)
printf(" rto:%g", (double)s.rto/hz);
if (s.ato)
printf(" ato:%g", (double)s.ato/hz);
if (s.cwnd != )
printf(" cwnd:%d", s.cwnd);
if (s.ssthresh != -)
printf(" ssthresh:%d", s.ssthresh);
if (s.qack/)
printf(" qack:%d", s.qack/);
if (s.qack&)
printf(" bidir");
}
if (show_users) {
char ubuf[];
if (find_users(s.ino, ubuf, sizeof(ubuf)) > )
printf(" users:(%s)", ubuf);
}
if (show_details) {
if (s.uid)
printf(" uid:%u", (unsigned)s.uid);
printf(" ino:%u", s.ino);
printf(" sk:%llx", s.sk);
if (opt[])
printf(" opt:\"%s\"", opt);
}
printf("\n"); return ;
} static int generic_record_read(FILE *fp,
int (*worker)(char*, const struct filter *, int),
const struct filter *f, int fam)
{
char line[]; /* skip header */
if (fgets(line, sizeof(line), fp) == NULL)
goto outerr; while (fgets(line, sizeof(line), fp) != NULL) {
int n = strlen(line);
if (n == || line[n-] != '\n') {
errno = -EINVAL;
return -;
}
line[n-] = ; if (worker(line, f, fam) < )
return ;
}
outerr: return ferror(fp) ? - : ;
} static char *sprint_bw(char *buf, double bw)
{
if (bw > .)
sprintf(buf,"%.1fM", bw / .);
else if (bw > .)
sprintf(buf,"%.1fK", bw / .);
else
sprintf(buf, "%g", bw); return buf;
} static void tcp_show_info(const struct nlmsghdr *nlh, struct inet_diag_msg *r)
{
struct rtattr * tb[INET_DIAG_MAX+];
char b1[];
double rtt = ; parse_rtattr(tb, INET_DIAG_MAX, (struct rtattr*)(r+),
nlh->nlmsg_len - NLMSG_LENGTH(sizeof(*r))); if (tb[INET_DIAG_MEMINFO]) {
const struct inet_diag_meminfo *minfo
= RTA_DATA(tb[INET_DIAG_MEMINFO]);
printf(" mem:(r%u,w%u,f%u,t%u)",
minfo->idiag_rmem,
minfo->idiag_wmem,
minfo->idiag_fmem,
minfo->idiag_tmem);
} if (tb[INET_DIAG_INFO]) {
struct tcp_info *info;
int len = RTA_PAYLOAD(tb[INET_DIAG_INFO]); /* workaround for older kernels with less fields */
if (len < sizeof(*info)) {
info = alloca(sizeof(*info));
memset(info, , sizeof(*info));
memcpy(info, RTA_DATA(tb[INET_DIAG_INFO]), len);
} else
info = RTA_DATA(tb[INET_DIAG_INFO]); if (show_options) {
if (info->tcpi_options & TCPI_OPT_TIMESTAMPS)
printf(" ts");
if (info->tcpi_options & TCPI_OPT_SACK)
printf(" sack");
if (info->tcpi_options & TCPI_OPT_ECN)
printf(" ecn");
} if (tb[INET_DIAG_CONG])
printf(" %s", (char *) RTA_DATA(tb[INET_DIAG_CONG])); if (info->tcpi_options & TCPI_OPT_WSCALE)
printf(" wscale:%d,%d", info->tcpi_snd_wscale,
info->tcpi_rcv_wscale);
if (info->tcpi_rto && info->tcpi_rto != )
printf(" rto:%g", (double)info->tcpi_rto/);
if (info->tcpi_rtt)
printf(" rtt:%g/%g", (double)info->tcpi_rtt/,
(double)info->tcpi_rttvar/);
if (info->tcpi_ato)
printf(" ato:%g", (double)info->tcpi_ato/);
if (info->tcpi_snd_cwnd != )
printf(" cwnd:%d", info->tcpi_snd_cwnd);
if (info->tcpi_snd_ssthresh < 0xFFFF)
printf(" ssthresh:%d", info->tcpi_snd_ssthresh); rtt = (double) info->tcpi_rtt;
if (tb[INET_DIAG_VEGASINFO]) {
const struct tcpvegas_info *vinfo
= RTA_DATA(tb[INET_DIAG_VEGASINFO]); if (vinfo->tcpv_enabled &&
vinfo->tcpv_rtt && vinfo->tcpv_rtt != 0x7fffffff)
rtt = vinfo->tcpv_rtt;
} if (rtt > && info->tcpi_snd_mss && info->tcpi_snd_cwnd) {
printf(" send %sbps",
sprint_bw(b1, (double) info->tcpi_snd_cwnd *
(double) info->tcpi_snd_mss * .
/ rtt));
} if (info->tcpi_rcv_rtt)
printf(" rcv_rtt:%g", (double) info->tcpi_rcv_rtt/);
if (info->tcpi_rcv_space)
printf(" rcv_space:%d", info->tcpi_rcv_space); }
} static int tcp_show_sock(struct nlmsghdr *nlh, struct filter *f)
{
struct inet_diag_msg *r = NLMSG_DATA(nlh);
struct tcpstat s; s.state = r->idiag_state;
s.local.family = s.remote.family = r->idiag_family;
s.lport = ntohs(r->id.idiag_sport);
s.rport = ntohs(r->id.idiag_dport);
if (s.local.family == AF_INET) {
s.local.bytelen = s.remote.bytelen = ;
} else {
s.local.bytelen = s.remote.bytelen = ;
}
memcpy(s.local.data, r->id.idiag_src, s.local.bytelen);
memcpy(s.remote.data, r->id.idiag_dst, s.local.bytelen); if (f && f->f && run_ssfilter(f->f, &s) == )
return ; if (netid_width)
printf("%-*s ", netid_width, "tcp");
if (state_width)
printf("%-*s ", state_width, sstate_name[s.state]); printf("%-6d %-6d ", r->idiag_rqueue, r->idiag_wqueue); formatted_print(&s.local, s.lport);
formatted_print(&s.remote, s.rport); if (show_options) {
if (r->idiag_timer) {
if (r->idiag_timer > )
r->idiag_timer = ;
printf(" timer:(%s,%s,%d)",
tmr_name[r->idiag_timer],
print_ms_timer(r->idiag_expires),
r->idiag_retrans);
}
}
if (show_users) {
char ubuf[];
if (find_users(r->idiag_inode, ubuf, sizeof(ubuf)) > )
printf(" users:(%s)", ubuf);
}
if (show_details) {
if (r->idiag_uid)
printf(" uid:%u", (unsigned)r->idiag_uid);
printf(" ino:%u", r->idiag_inode);
printf(" sk:");
if (r->id.idiag_cookie[] != )
printf("%08x", r->id.idiag_cookie[]);
printf("%08x", r->id.idiag_cookie[]);
}
if (show_mem || show_tcpinfo) {
printf("\n\t");
tcp_show_info(nlh, r);
} printf("\n"); return ;
} static int tcp_show_netlink(struct filter *f, FILE *dump_fp, int socktype)
{
int fd;
struct sockaddr_nl nladdr;
struct {
struct nlmsghdr nlh;
struct inet_diag_req r;
} req;
char *bc = NULL;
int bclen;
struct msghdr msg;
struct rtattr rta;
char buf[];
struct iovec iov[]; if ((fd = socket(AF_NETLINK, SOCK_RAW, NETLINK_INET_DIAG)) < )
return -; memset(&nladdr, , sizeof(nladdr));
nladdr.nl_family = AF_NETLINK; req.nlh.nlmsg_len = sizeof(req);
req.nlh.nlmsg_type = socktype;
req.nlh.nlmsg_flags = NLM_F_ROOT|NLM_F_MATCH|NLM_F_REQUEST;
req.nlh.nlmsg_pid = ;
req.nlh.nlmsg_seq = ;
memset(&req.r, , sizeof(req.r));
req.r.idiag_family = AF_INET;
req.r.idiag_states = f->states;
if (show_mem)
req.r.idiag_ext |= (<<(INET_DIAG_MEMINFO-)); if (show_tcpinfo) {
req.r.idiag_ext |= (<<(INET_DIAG_INFO-));
req.r.idiag_ext |= (<<(INET_DIAG_VEGASINFO-));
req.r.idiag_ext |= (<<(INET_DIAG_CONG-));
} iov[] = (struct iovec){
.iov_base = &req,
.iov_len = sizeof(req)
};
if (f->f) {
bclen = ssfilter_bytecompile(f->f, &bc);
rta.rta_type = INET_DIAG_REQ_BYTECODE;
rta.rta_len = RTA_LENGTH(bclen);
iov[] = (struct iovec){ &rta, sizeof(rta) };
iov[] = (struct iovec){ bc, bclen };
req.nlh.nlmsg_len += RTA_LENGTH(bclen);
} msg = (struct msghdr) {
.msg_name = (void*)&nladdr,
.msg_namelen = sizeof(nladdr),
.msg_iov = iov,
.msg_iovlen = f->f ? : ,
}; if (sendmsg(fd, &msg, ) < )
return -; iov[] = (struct iovec){
.iov_base = buf,
.iov_len = sizeof(buf)
}; while () {
int status;
struct nlmsghdr *h; msg = (struct msghdr) {
(void*)&nladdr, sizeof(nladdr),
iov, ,
NULL, , }; status = recvmsg(fd, &msg, ); if (status < ) {
if (errno == EINTR)
continue;
perror("OVERRUN");
continue;
}
if (status == ) {
fprintf(stderr, "EOF on netlink\n");
return ;
} if (dump_fp)
fwrite(buf, , NLMSG_ALIGN(status), dump_fp); h = (struct nlmsghdr*)buf;
while (NLMSG_OK(h, status)) {
int err;
struct inet_diag_msg *r = NLMSG_DATA(h); if (/*h->nlmsg_pid != rth->local.nl_pid ||*/
h->nlmsg_seq != )
goto skip_it; if (h->nlmsg_type == NLMSG_DONE)
return ;
if (h->nlmsg_type == NLMSG_ERROR) {
struct nlmsgerr *err = (struct nlmsgerr*)NLMSG_DATA(h);
if (h->nlmsg_len < NLMSG_LENGTH(sizeof(struct nlmsgerr))) {
fprintf(stderr, "ERROR truncated\n");
} else {
errno = -err->error;
perror("TCPDIAG answers");
}
return ;
}
if (!dump_fp) {
if (!(f->families & (<<r->idiag_family))) {
h = NLMSG_NEXT(h, status);
continue;
}
err = tcp_show_sock(h, NULL);
if (err < )
return err;
} skip_it:
h = NLMSG_NEXT(h, status);
}
if (msg.msg_flags & MSG_TRUNC) {
fprintf(stderr, "Message truncated\n");
continue;
}
if (status) {
fprintf(stderr, "!!!Remnant of size %d\n", status);
exit();
}
}
return ;
} static int tcp_show_netlink_file(struct filter *f)
{
FILE *fp;
char buf[]; if ((fp = fopen(getenv("TCPDIAG_FILE"), "r")) == NULL) {
perror("fopen($TCPDIAG_FILE)");
return -;
} while () {
int status, err;
struct nlmsghdr *h = (struct nlmsghdr*)buf; status = fread(buf, , sizeof(*h), fp);
if (status < ) {
perror("Reading header from $TCPDIAG_FILE");
return -;
}
if (status != sizeof(*h)) {
perror("Unexpected EOF reading $TCPDIAG_FILE");
return -;
} status = fread(h+, , NLMSG_ALIGN(h->nlmsg_len-sizeof(*h)), fp); if (status < ) {
perror("Reading $TCPDIAG_FILE");
return -;
}
if (status + sizeof(*h) < h->nlmsg_len) {
perror("Unexpected EOF reading $TCPDIAG_FILE");
return -;
} /* The only legal exit point */
if (h->nlmsg_type == NLMSG_DONE)
return ; if (h->nlmsg_type == NLMSG_ERROR) {
struct nlmsgerr *err = (struct nlmsgerr*)NLMSG_DATA(h);
if (h->nlmsg_len < NLMSG_LENGTH(sizeof(struct nlmsgerr))) {
fprintf(stderr, "ERROR truncated\n");
} else {
errno = -err->error;
perror("TCPDIAG answered");
}
return -;
} err = tcp_show_sock(h, f);
if (err < )
return err;
}
} static int tcp_show(struct filter *f, int socktype)
{
FILE *fp = NULL;
char *buf = NULL;
int bufsize = *; dg_proto = TCP_PROTO; if (getenv("TCPDIAG_FILE"))
return tcp_show_netlink_file(f); if (!getenv("PROC_NET_TCP") && !getenv("PROC_ROOT")
&& tcp_show_netlink(f, NULL, socktype) == )
return ; /* Sigh... We have to parse /proc/net/tcp... */ /* Estimate amount of sockets and try to allocate
* huge buffer to read all the table at one read.
* Limit it by 16MB though. The assumption is: as soon as
* kernel was able to hold information about N connections,
* it is able to give us some memory for snapshot.
*/
if () {
int guess = slabstat.socks+slabstat.tcp_syns;
if (f->states&(<<SS_TIME_WAIT))
guess += slabstat.tcp_tws;
if (guess > (**)/)
guess = (**)/;
guess *= ;
if (guess > bufsize)
bufsize = guess;
}
while (bufsize >= *) {
if ((buf = malloc(bufsize)) != NULL)
break;
bufsize /= ;
}
if (buf == NULL) {
errno = ENOMEM;
return -;
} if (f->families & (<<AF_INET)) {
if ((fp = net_tcp_open()) == NULL)
goto outerr; setbuffer(fp, buf, bufsize);
if (generic_record_read(fp, tcp_show_line, f, AF_INET))
goto outerr;
fclose(fp);
} if ((f->families & (<<AF_INET6)) &&
(fp = net_tcp6_open()) != NULL) {
setbuffer(fp, buf, bufsize);
if (generic_record_read(fp, tcp_show_line, f, AF_INET6))
goto outerr;
fclose(fp);
} free(buf);
return ; outerr:
do {
int saved_errno = errno;
if (buf)
free(buf);
if (fp)
fclose(fp);
errno = saved_errno;
return -;
} while ();
} int dgram_show_line(char *line, const struct filter *f, int family)
{
struct tcpstat s;
char *loc, *rem, *data;
char opt[];
int n;
char *p; if ((p = strchr(line, ':')) == NULL)
return -;
loc = p+; if ((p = strchr(loc, ':')) == NULL)
return -;
p[] = ;
rem = p+; if ((p = strchr(rem, ':')) == NULL)
return -;
p[] = ;
data = p+; do {
int state = (data[] >= 'A') ? (data[] - 'A' + ) : (data[] - ''); if (!(f->states & (<<state)))
return ;
} while (); s.local.family = s.remote.family = family;
if (family == AF_INET) {
sscanf(loc, "%x:%x", s.local.data, (unsigned*)&s.lport);
sscanf(rem, "%x:%x", s.remote.data, (unsigned*)&s.rport);
s.local.bytelen = s.remote.bytelen = ;
} else {
sscanf(loc, "%08x%08x%08x%08x:%x",
s.local.data,
s.local.data+,
s.local.data+,
s.local.data+,
&s.lport);
sscanf(rem, "%08x%08x%08x%08x:%x",
s.remote.data,
s.remote.data+,
s.remote.data+,
s.remote.data+,
&s.rport);
s.local.bytelen = s.remote.bytelen = ;
} if (f->f && run_ssfilter(f->f, &s) == )
return ; opt[] = ;
n = sscanf(data, "%x %x:%x %*x:%*x %*x %d %*d %u %d %llx %[^\n]\n",
&s.state, &s.wq, &s.rq,
&s.uid, &s.ino,
&s.refcnt, &s.sk, opt); if (n < )
opt[] = ; if (netid_width)
printf("%-*s ", netid_width, dg_proto);
if (state_width)
printf("%-*s ", state_width, sstate_name[s.state]); printf("%-6d %-6d ", s.rq, s.wq); formatted_print(&s.local, s.lport);
formatted_print(&s.remote, s.rport); if (show_users) {
char ubuf[];
if (find_users(s.ino, ubuf, sizeof(ubuf)) > )
printf(" users:(%s)", ubuf);
} if (show_details) {
if (s.uid)
printf(" uid=%u", (unsigned)s.uid);
printf(" ino=%u", s.ino);
printf(" sk=%llx", s.sk);
if (opt[])
printf(" opt:\"%s\"", opt);
}
printf("\n"); return ;
} int udp_show(struct filter *f)
{
FILE *fp = NULL; dg_proto = UDP_PROTO; if (f->families&(<<AF_INET)) {
if ((fp = net_udp_open()) == NULL)
goto outerr;
if (generic_record_read(fp, dgram_show_line, f, AF_INET))
goto outerr;
fclose(fp);
} if ((f->families&(<<AF_INET6)) &&
(fp = net_udp6_open()) != NULL) {
if (generic_record_read(fp, dgram_show_line, f, AF_INET6))
goto outerr;
fclose(fp);
}
return ; outerr:
do {
int saved_errno = errno;
if (fp)
fclose(fp);
errno = saved_errno;
return -;
} while ();
} int raw_show(struct filter *f)
{
FILE *fp = NULL; dg_proto = RAW_PROTO; if (f->families&(<<AF_INET)) {
if ((fp = net_raw_open()) == NULL)
goto outerr;
if (generic_record_read(fp, dgram_show_line, f, AF_INET))
goto outerr;
fclose(fp);
} if ((f->families&(<<AF_INET6)) &&
(fp = net_raw6_open()) != NULL) {
if (generic_record_read(fp, dgram_show_line, f, AF_INET6))
goto outerr;
fclose(fp);
}
return ; outerr:
do {
int saved_errno = errno;
if (fp)
fclose(fp);
errno = saved_errno;
return -;
} while ();
} struct unixstat
{
struct unixstat *next;
int ino;
int peer;
int rq;
int wq;
int state;
int type;
char *name;
}; int unix_state_map[] = { SS_CLOSE, SS_SYN_SENT,
SS_ESTABLISHED, SS_CLOSING }; #define MAX_UNIX_REMEMBER (1024*1024/sizeof(struct unixstat)) void unix_list_free(struct unixstat *list)
{
while (list) {
struct unixstat *s = list;
list = list->next;
if (s->name)
free(s->name);
free(s);
}
} void unix_list_print(struct unixstat *list, struct filter *f)
{
struct unixstat *s;
char *peer; for (s = list; s; s = s->next) {
if (!(f->states & (<<s->state)))
continue;
if (s->type == SOCK_STREAM && !(f->dbs&(<<UNIX_ST_DB)))
continue;
if (s->type == SOCK_DGRAM && !(f->dbs&(<<UNIX_DG_DB)))
continue; peer = "*";
if (s->peer) {
struct unixstat *p;
for (p = list; p; p = p->next) {
if (s->peer == p->ino)
break;
}
if (!p) {
peer = "?";
} else {
peer = p->name ? : "*";
}
} if (f->f) {
struct tcpstat tst;
tst.local.family = AF_UNIX;
tst.remote.family = AF_UNIX;
memcpy(tst.local.data, &s->name, sizeof(s->name));
if (strcmp(peer, "*") == )
memset(tst.remote.data, , sizeof(peer));
else
memcpy(tst.remote.data, &peer, sizeof(peer));
if (run_ssfilter(f->f, &tst) == )
continue;
} if (netid_width)
printf("%-*s ", netid_width,
s->type == SOCK_STREAM ? "u_str" : "u_dgr");
if (state_width)
printf("%-*s ", state_width, sstate_name[s->state]);
printf("%-6d %-6d ", s->rq, s->wq);
printf("%*s %-*d %*s %-*d",
addr_width, s->name ? : "*", serv_width, s->ino,
addr_width, peer, serv_width, s->peer);
if (show_users) {
char ubuf[];
if (find_users(s->ino, ubuf, sizeof(ubuf)) > )
printf(" users:(%s)", ubuf);
}
printf("\n");
}
} int unix_show(struct filter *f)
{
FILE *fp;
char buf[];
char name[];
int newformat = ;
int cnt;
struct unixstat *list = NULL; if ((fp = net_unix_open()) == NULL)
return -;
fgets(buf, sizeof(buf)-, fp); if (memcmp(buf, "Peer", ) == )
newformat = ;
cnt = ; while (fgets(buf, sizeof(buf)-, fp)) {
struct unixstat *u, **insp;
int flags; if (!(u = malloc(sizeof(*u))))
break;
u->name = NULL; if (sscanf(buf, "%x: %x %x %x %x %x %d %s",
&u->peer, &u->rq, &u->wq, &flags, &u->type,
&u->state, &u->ino, name) < )
name[] = ; if (flags&(<<)) {
u->state = SS_LISTEN;
} else {
u->state = unix_state_map[u->state-];
if (u->type == SOCK_DGRAM &&
u->state == SS_CLOSE &&
u->peer)
u->state = SS_ESTABLISHED;
} if (!newformat) {
u->peer = ;
u->rq = ;
u->wq = ;
} insp = &list;
while (*insp) {
if (u->type < (*insp)->type ||
(u->type == (*insp)->type &&
u->ino < (*insp)->ino))
break;
insp = &(*insp)->next;
}
u->next = *insp;
*insp = u; if (name[]) {
if ((u->name = malloc(strlen(name)+)) == NULL)
break;
strcpy(u->name, name);
}
if (++cnt > MAX_UNIX_REMEMBER) {
unix_list_print(list, f);
unix_list_free(list);
list = NULL;
cnt = ;
}
} if (list) {
unix_list_print(list, f);
unix_list_free(list);
list = NULL;
cnt = ;
} return ;
} int packet_show(struct filter *f)
{
FILE *fp;
char buf[];
int type;
int prot;
int iface;
int state;
int rq;
int uid;
int ino;
unsigned long long sk; if (!(f->states & (<<SS_CLOSE)))
return ; if ((fp = net_packet_open()) == NULL)
return -;
fgets(buf, sizeof(buf)-, fp); while (fgets(buf, sizeof(buf)-, fp)) {
sscanf(buf, "%llx %*d %d %x %d %d %u %u %u",
&sk,
&type, &prot, &iface, &state,
&rq, &uid, &ino); if (type == SOCK_RAW && !(f->dbs&(<<PACKET_R_DB)))
continue;
if (type == SOCK_DGRAM && !(f->dbs&(<<PACKET_DG_DB)))
continue;
if (f->f) {
struct tcpstat tst;
tst.local.family = AF_PACKET;
tst.remote.family = AF_PACKET;
tst.rport = ;
tst.lport = iface;
tst.local.data[] = prot;
tst.remote.data[] = ;
if (run_ssfilter(f->f, &tst) == )
continue;
} if (netid_width)
printf("%-*s ", netid_width,
type == SOCK_RAW ? "p_raw" : "p_dgr");
if (state_width)
printf("%-*s ", state_width, "UNCONN");
printf("%-6d %-6d ", rq, );
if (prot == ) {
printf("%*s:", addr_width, "*");
} else {
char tb[];
printf("%*s:", addr_width,
ll_proto_n2a(htons(prot), tb, sizeof(tb)));
}
if (iface == ) {
printf("%-*s ", serv_width, "*");
} else {
printf("%-*s ", serv_width, xll_index_to_name(iface));
}
printf("%*s*%-*s",
addr_width, "", serv_width, ""); if (show_users) {
char ubuf[];
if (find_users(ino, ubuf, sizeof(ubuf)) > )
printf(" users:(%s)", ubuf);
}
if (show_details) {
printf(" ino=%u uid=%u sk=%llx", ino, uid, sk);
}
printf("\n");
} return ;
} int netlink_show(struct filter *f)
{
FILE *fp;
char buf[];
int prot, pid;
unsigned groups;
int rq, wq, rc;
unsigned long long sk, cb; if (!(f->states & (<<SS_CLOSE)))
return ; if ((fp = net_netlink_open()) == NULL)
return -;
fgets(buf, sizeof(buf)-, fp); while (fgets(buf, sizeof(buf)-, fp)) {
sscanf(buf, "%llx %d %d %x %d %d %llx %d",
&sk,
&prot, &pid, &groups, &rq, &wq, &cb, &rc); if (f->f) {
struct tcpstat tst;
tst.local.family = AF_NETLINK;
tst.remote.family = AF_NETLINK;
tst.rport = -;
tst.lport = pid;
tst.local.data[] = prot;
tst.remote.data[] = ;
if (run_ssfilter(f->f, &tst) == )
continue;
} if (netid_width)
printf("%-*s ", netid_width, "nl");
if (state_width)
printf("%-*s ", state_width, "UNCONN");
printf("%-6d %-6d ", rq, wq);
if (resolve_services && prot == )
printf("%*s:", addr_width, "rtnl");
else if (resolve_services && prot == )
printf("%*s:", addr_width, "fw");
else if (resolve_services && prot == )
printf("%*s:", addr_width, "tcpdiag");
else
printf("%*d:", addr_width, prot);
if (pid == -) {
printf("%-*s ", serv_width, "*");
} else if (resolve_services) {
int done = ;
if (!pid) {
done = ;
printf("%-*s ", serv_width, "kernel");
} else if (pid > ) {
char procname[];
FILE *fp;
sprintf(procname, "%s/%d/stat",
getenv("PROC_ROOT") ? : "/proc", pid);
if ((fp = fopen(procname, "r")) != NULL) {
if (fscanf(fp, "%*d (%[^)])", procname) == ) {
sprintf(procname+strlen(procname), "/%d", pid);
printf("%-*s ", serv_width, procname);
done = ;
}
fclose(fp);
}
}
if (!done)
printf("%-*d ", serv_width, pid);
} else {
printf("%-*d ", serv_width, pid);
}
printf("%*s*%-*s",
addr_width, "", serv_width, ""); if (show_details) {
printf(" sk=%llx cb=%llx groups=0x%08x", sk, cb, groups);
}
printf("\n");
} return ;
} struct snmpstat
{
int tcp_estab;
}; int get_snmp_int(char *proto, char *key, int *result)
{
char buf[];
FILE *fp;
int protolen = strlen(proto);
int keylen = strlen(key); *result = ; if ((fp = net_snmp_open()) == NULL)
return -; while (fgets(buf, sizeof(buf), fp) != NULL) {
char *p = buf;
int pos = ;
if (memcmp(buf, proto, protolen))
continue;
while ((p = strchr(p, ' ')) != NULL) {
pos++;
p++;
if (memcmp(p, key, keylen) == &&
(p[keylen] == ' ' || p[keylen] == '\n'))
break;
}
if (fgets(buf, sizeof(buf), fp) == NULL)
break;
if (memcmp(buf, proto, protolen))
break;
p = buf;
while ((p = strchr(p, ' ')) != NULL) {
p++;
if (--pos == ) {
sscanf(p, "%d", result);
fclose(fp);
return ;
}
}
} fclose(fp);
errno = ESRCH;
return -;
} /* Get stats from sockstat */ struct sockstat
{
int socks;
int tcp_mem;
int tcp_total;
int tcp_orphans;
int tcp_tws;
int tcp4_hashed;
int udp4;
int raw4;
int frag4;
int frag4_mem;
int tcp6_hashed;
int udp6;
int raw6;
int frag6;
int frag6_mem;
}; static void get_sockstat_line(char *line, struct sockstat *s)
{
char id[], rem[]; if (sscanf(line, "%[^ ] %[^\n]\n", id, rem) != )
return; if (strcmp(id, "sockets:") == )
sscanf(rem, "%*s%d", &s->socks);
else if (strcmp(id, "UDP:") == )
sscanf(rem, "%*s%d", &s->udp4);
else if (strcmp(id, "UDP6:") == )
sscanf(rem, "%*s%d", &s->udp6);
else if (strcmp(id, "RAW:") == )
sscanf(rem, "%*s%d", &s->raw4);
else if (strcmp(id, "RAW6:") == )
sscanf(rem, "%*s%d", &s->raw6);
else if (strcmp(id, "TCP6:") == )
sscanf(rem, "%*s%d", &s->tcp6_hashed);
else if (strcmp(id, "FRAG:") == )
sscanf(rem, "%*s%d%*s%d", &s->frag4, &s->frag4_mem);
else if (strcmp(id, "FRAG6:") == )
sscanf(rem, "%*s%d%*s%d", &s->frag6, &s->frag6_mem);
else if (strcmp(id, "TCP:") == )
sscanf(rem, "%*s%d%*s%d%*s%d%*s%d%*s%d",
&s->tcp4_hashed,
&s->tcp_orphans, &s->tcp_tws, &s->tcp_total, &s->tcp_mem);
} int get_sockstat(struct sockstat *s)
{
char buf[];
FILE *fp; memset(s, , sizeof(*s)); if ((fp = net_sockstat_open()) == NULL)
return -;
while(fgets(buf, sizeof(buf), fp) != NULL)
get_sockstat_line(buf, s);
fclose(fp); if ((fp = net_sockstat6_open()) == NULL)
return ;
while(fgets(buf, sizeof(buf), fp) != NULL)
get_sockstat_line(buf, s);
fclose(fp); return ;
} int print_summary(void)
{
struct sockstat s;
struct snmpstat sn; if (get_sockstat(&s) < )
perror("ss: get_sockstat");
if (get_snmp_int("Tcp:", "CurrEstab", &sn.tcp_estab) < )
perror("ss: get_snmpstat"); printf("Total: %d (kernel %d)\n", s.socks, slabstat.socks); printf("TCP: %d (estab %d, closed %d, orphaned %d, synrecv %d, timewait %d/%d), ports %d\n",
s.tcp_total + slabstat.tcp_syns + s.tcp_tws,
sn.tcp_estab,
s.tcp_total - (s.tcp4_hashed+s.tcp6_hashed-s.tcp_tws),
s.tcp_orphans,
slabstat.tcp_syns,
s.tcp_tws, slabstat.tcp_tws,
slabstat.tcp_ports
); printf("\n");
printf("Transport Total IP IPv6\n");
printf("* %-9d %-9s %-9s\n", slabstat.socks, "-", "-");
printf("RAW %-9d %-9d %-9d\n", s.raw4+s.raw6, s.raw4, s.raw6);
printf("UDP %-9d %-9d %-9d\n", s.udp4+s.udp6, s.udp4, s.udp6);
printf("TCP %-9d %-9d %-9d\n", s.tcp4_hashed+s.tcp6_hashed, s.tcp4_hashed, s.tcp6_hashed);
printf("INET %-9d %-9d %-9d\n",
s.raw4+s.udp4+s.tcp4_hashed+
s.raw6+s.udp6+s.tcp6_hashed,
s.raw4+s.udp4+s.tcp4_hashed,
s.raw6+s.udp6+s.tcp6_hashed);
printf("FRAG %-9d %-9d %-9d\n", s.frag4+s.frag6, s.frag4, s.frag6); printf("\n"); return ;
} static void _usage(FILE *dest)
{
fprintf(dest,
"Usage: ss [ OPTIONS ]\n"
" ss [ OPTIONS ] [ FILTER ]\n"
" -h, --help this message\n"
" -V, --version output version information\n"
" -n, --numeric don't resolve service names\n"
" -r, --resolve resolve host names\n"
" -a, --all display all sockets\n"
" -l, --listening display listening sockets\n"
" -o, --options show timer information\n"
" -e, --extended show detailed socket information\n"
" -m, --memory show socket memory usage\n"
" -p, --processes show process using socket\n"
" -i, --info show internal TCP information\n"
" -s, --summary show socket usage summary\n"
"\n"
" -4, --ipv4 display only IP version 4 sockets\n"
" -6, --ipv6 display only IP version 6 sockets\n"
" -0, --packet display PACKET sockets\n"
" -t, --tcp display only TCP sockets\n"
" -u, --udp display only UDP sockets\n"
" -d, --dccp display only DCCP sockets\n"
" -w, --raw display only RAW sockets\n"
" -x, --unix display only Unix domain sockets\n"
" -f, --family=FAMILY display sockets of type FAMILY\n"
"\n"
" -A, --query=QUERY, --socket=QUERY\n"
" QUERY := {all|inet|tcp|udp|raw|unix|packet|netlink}[,QUERY]\n"
"\n"
" -D, --diag=FILE Dump raw information about TCP sockets to FILE\n"
" -F, --filter=FILE read filter information from FILE\n"
" FILTER := [ state TCP-STATE ] [ EXPRESSION ]\n"
);
} static void help(void) __attribute__((noreturn));
static void help(void)
{
_usage(stdout);
exit();
} static void usage(void) __attribute__((noreturn));
static void usage(void)
{
_usage(stderr);
exit(-);
} int scan_state(const char *state)
{
int i;
if (strcasecmp(state, "close") == ||
strcasecmp(state, "closed") == )
return (<<SS_CLOSE);
if (strcasecmp(state, "syn-rcv") == )
return (<<SS_SYN_RECV);
if (strcasecmp(state, "established") == )
return (<<SS_ESTABLISHED);
if (strcasecmp(state, "all") == )
return SS_ALL;
if (strcasecmp(state, "connected") == )
return SS_ALL & ~((<<SS_CLOSE)|(<<SS_LISTEN));
if (strcasecmp(state, "synchronized") == )
return SS_ALL & ~((<<SS_CLOSE)|(<<SS_LISTEN)|(<<SS_SYN_SENT));
if (strcasecmp(state, "bucket") == )
return (<<SS_SYN_RECV)|(<<SS_TIME_WAIT);
if (strcasecmp(state, "big") == )
return SS_ALL & ~((<<SS_SYN_RECV)|(<<SS_TIME_WAIT));
for (i=; i<SS_MAX; i++) {
if (strcasecmp(state, sstate_namel[i]) == )
return (<<i);
}
return ;
} static const struct option long_opts[] = {
{ "numeric", , , 'n' },
{ "resolve", , , 'r' },
{ "options", , , 'o' },
{ "extended", , , 'e' },
{ "memory", , , 'm' },
{ "info", , , 'i' },
{ "processes", , , 'p' },
{ "dccp", , , 'd' },
{ "tcp", , , 't' },
{ "udp", , , 'u' },
{ "raw", , , 'w' },
{ "unix", , , 'x' },
{ "all", , , 'a' },
{ "listening", , , 'l' },
{ "ipv4", , , '' },
{ "ipv6", , , '' },
{ "packet", , , '' },
{ "family", , , 'f' },
{ "socket", , , 'A' },
{ "query", , , 'A' },
{ "summary", , , 's' },
{ "diag", , , 'D' },
{ "filter", , , 'F' },
{ "version", , , 'V' },
{ "help", , , 'h' },
{ } }; int main(int argc, char *argv[])
{
int do_default = ;
int saw_states = ;
int saw_query = ;
int do_summary = ;
const char *dump_tcpdiag = NULL;
FILE *filter_fp = NULL;
int ch; memset(&current_filter, , sizeof(current_filter)); current_filter.states = default_filter.states; while ((ch = getopt_long(argc, argv, "dhaletuwxnro460spf:miA:D:F:vV",
long_opts, NULL)) != EOF) {
switch(ch) {
case 'n':
resolve_services = ;
break;
case 'r':
resolve_hosts = ;
break;
case 'o':
show_options = ;
break;
case 'e':
show_options = ;
show_details++;
break;
case 'm':
show_mem = ;
break;
case 'i':
show_tcpinfo = ;
break;
case 'p':
show_users++;
user_ent_hash_build();
break;
case 'd':
current_filter.dbs |= (<<DCCP_DB);
do_default = ;
break;
case 't':
current_filter.dbs |= (<<TCP_DB);
do_default = ;
break;
case 'u':
current_filter.dbs |= (<<UDP_DB);
do_default = ;
break;
case 'w':
current_filter.dbs |= (<<RAW_DB);
do_default = ;
break;
case 'x':
current_filter.dbs |= UNIX_DBM;
do_default = ;
break;
case 'a':
current_filter.states = SS_ALL;
break;
case 'l':
current_filter.states = (<<SS_LISTEN);
break;
case '':
preferred_family = AF_INET;
break;
case '':
preferred_family = AF_INET6;
break;
case '':
preferred_family = AF_PACKET;
break;
case 'f':
if (strcmp(optarg, "inet") == )
preferred_family = AF_INET;
else if (strcmp(optarg, "inet6") == )
preferred_family = AF_INET6;
else if (strcmp(optarg, "link") == )
preferred_family = AF_PACKET;
else if (strcmp(optarg, "unix") == )
preferred_family = AF_UNIX;
else if (strcmp(optarg, "netlink") == )
preferred_family = AF_NETLINK;
else if (strcmp(optarg, "help") == )
help();
else {
fprintf(stderr, "ss: \"%s\" is invalid family\n", optarg);
usage();
}
break;
case 'A':
{
char *p, *p1;
if (!saw_query) {
current_filter.dbs = ;
saw_query = ;
do_default = ;
}
p = p1 = optarg;
do {
if ((p1 = strchr(p, ',')) != NULL)
*p1 = ;
if (strcmp(p, "all") == ) {
current_filter.dbs = ALL_DB;
} else if (strcmp(p, "inet") == ) {
current_filter.dbs |= (<<TCP_DB)|(<<DCCP_DB)|(<<UDP_DB)|(<<RAW_DB);
} else if (strcmp(p, "udp") == ) {
current_filter.dbs |= (<<UDP_DB);
} else if (strcmp(p, "dccp") == ) {
current_filter.dbs |= (<<DCCP_DB);
} else if (strcmp(p, "tcp") == ) {
current_filter.dbs |= (<<TCP_DB);
} else if (strcmp(p, "raw") == ) {
current_filter.dbs |= (<<RAW_DB);
} else if (strcmp(p, "unix") == ) {
current_filter.dbs |= UNIX_DBM;
} else if (strcasecmp(p, "unix_stream") == ||
strcmp(p, "u_str") == ) {
current_filter.dbs |= (<<UNIX_ST_DB);
} else if (strcasecmp(p, "unix_dgram") == ||
strcmp(p, "u_dgr") == ) {
current_filter.dbs |= (<<UNIX_DG_DB);
} else if (strcmp(p, "packet") == ) {
current_filter.dbs |= PACKET_DBM;
} else if (strcmp(p, "packet_raw") == ||
strcmp(p, "p_raw") == ) {
current_filter.dbs |= (<<PACKET_R_DB);
} else if (strcmp(p, "packet_dgram") == ||
strcmp(p, "p_dgr") == ) {
current_filter.dbs |= (<<PACKET_DG_DB);
} else if (strcmp(p, "netlink") == ) {
current_filter.dbs |= (<<NETLINK_DB);
} else {
fprintf(stderr, "ss: \"%s\" is illegal socket table id\n", p);
usage();
}
p = p1 + ;
} while (p1);
break;
}
case 's':
do_summary = ;
break;
case 'D':
dump_tcpdiag = optarg;
break;
case 'F':
if (filter_fp) {
fprintf(stderr, "More than one filter file\n");
exit(-);
}
if (optarg[] == '-')
filter_fp = stdin;
else
filter_fp = fopen(optarg, "r");
if (!filter_fp) {
perror("fopen filter file");
exit(-);
}
break;
case 'v':
case 'V':
printf("ss utility, iproute2-ss%s\n", SNAPSHOT);
exit();
case 'h':
case '?':
help();
default:
usage();
}
} argc -= optind;
argv += optind; get_slabstat(&slabstat); if (do_summary) {
print_summary();
if (do_default && argc == )
exit();
} if (do_default)
current_filter.dbs = default_filter.dbs; if (preferred_family == AF_UNSPEC) {
if (!(current_filter.dbs&~UNIX_DBM))
preferred_family = AF_UNIX;
else if (!(current_filter.dbs&~PACKET_DBM))
preferred_family = AF_PACKET;
else if (!(current_filter.dbs&~(<<NETLINK_DB)))
preferred_family = AF_NETLINK;
} if (preferred_family != AF_UNSPEC) {
int mask2;
if (preferred_family == AF_INET ||
preferred_family == AF_INET6) {
mask2= current_filter.dbs;
} else if (preferred_family == AF_PACKET) {
mask2 = PACKET_DBM;
} else if (preferred_family == AF_UNIX) {
mask2 = UNIX_DBM;
} else if (preferred_family == AF_NETLINK) {
mask2 = (<<NETLINK_DB);
} else {
mask2 = ;
} if (do_default)
current_filter.dbs = mask2;
else
current_filter.dbs &= mask2;
current_filter.families = (<<preferred_family);
} else {
if (!do_default)
current_filter.families = ~;
else
current_filter.families = default_filter.families;
}
if (current_filter.dbs == ) {
fprintf(stderr, "ss: no socket tables to show with such filter.\n");
exit();
}
if (current_filter.families == ) {
fprintf(stderr, "ss: no families to show with such filter.\n");
exit();
} if (resolve_services && resolve_hosts &&
(current_filter.dbs&(UNIX_DBM|(<<TCP_DB)|(<<UDP_DB)|(<<DCCP_DB))))
init_service_resolver(); /* Now parse filter... */
if (argc == && filter_fp) {
if (ssfilter_parse(&current_filter.f, , NULL, filter_fp))
usage();
} while (argc > ) {
if (strcmp(*argv, "state") == ) {
NEXT_ARG();
if (!saw_states)
current_filter.states = ;
current_filter.states |= scan_state(*argv);
saw_states = ;
} else if (strcmp(*argv, "exclude") == ||
strcmp(*argv, "excl") == ) {
NEXT_ARG();
if (!saw_states)
current_filter.states = SS_ALL;
current_filter.states &= ~scan_state(*argv);
saw_states = ;
} else {
if (ssfilter_parse(&current_filter.f, argc, argv, filter_fp))
usage();
break;
}
argc--; argv++;
} if (current_filter.states == ) {
fprintf(stderr, "ss: no socket states to show with such filter.\n");
exit();
} if (dump_tcpdiag) {
FILE *dump_fp = stdout;
if (!(current_filter.dbs & (<<TCP_DB))) {
fprintf(stderr, "ss: tcpdiag dump requested and no tcp in filter.\n");
exit();
}
if (dump_tcpdiag[] != '-') {
dump_fp = fopen(dump_tcpdiag, "w");
if (!dump_tcpdiag) {
perror("fopen dump file");
exit(-);
}
}
tcp_show_netlink(&current_filter, dump_fp, TCPDIAG_GETSOCK);
fflush(dump_fp);
exit();
} netid_width = ;
if (current_filter.dbs&(current_filter.dbs-))
netid_width = ; state_width = ;
if (current_filter.states&(current_filter.states-))
state_width = ; screen_width = ;
if (isatty(STDOUT_FILENO)) {
struct winsize w; if (ioctl(STDOUT_FILENO, TIOCGWINSZ, &w) != -) {
if (w.ws_col > )
screen_width = w.ws_col;
}
} addrp_width = screen_width;
addrp_width -= netid_width+;
addrp_width -= state_width+;
addrp_width -= ; if (addrp_width&) {
if (netid_width)
netid_width++;
else if (state_width)
state_width++;
} addrp_width /= ;
addrp_width--; serv_width = resolve_services ? : ; if (addrp_width < +serv_width+)
addrp_width = +serv_width+; addr_width = addrp_width - serv_width - ; if (netid_width)
printf("%-*s ", netid_width, "Netid");
if (state_width)
printf("%-*s ", state_width, "State");
printf("%-6s %-6s ", "Recv-Q", "Send-Q"); printf("%*s:%-*s %*s:%-*s\n",
addr_width, "Local Address", serv_width, "Port",
addr_width, "Peer Address", serv_width, "Port"); fflush(stdout); if (current_filter.dbs & (<<NETLINK_DB))
netlink_show(&current_filter);
if (current_filter.dbs & PACKET_DBM)
packet_show(&current_filter);
if (current_filter.dbs & UNIX_DBM)
unix_show(&current_filter);
if (current_filter.dbs & (<<RAW_DB))
raw_show(&current_filter);
if (current_filter.dbs & (<<UDP_DB))
udp_show(&current_filter);
if (current_filter.dbs & (<<TCP_DB))
tcp_show(&current_filter, TCPDIAG_GETSOCK);
if (current_filter.dbs & (<<DCCP_DB))
tcp_show(&current_filter, DCCPDIAG_GETSOCK);
return ;
}

ss.c的更多相关文章

  1. 极路由2(极贰)在OpenWrt下定制自己的ss服务

    默认刷入的OpenWrt带的ss, 只有ss-redir服务, 但是在实际使用中, 很多时候还是希望访问直接通过正常网关, 只有少部分访问需要通过ss, 所以希望能配置成为ss-local服务. 在保 ...

  2. 记一次ss故障

    本文主要参考: https://github.com/shadowsocks/shadowsocks shadowssocks 分为客户端和服务器端. 我们平时买的服务,使用是要用的是客户端. 如果你 ...

  3. ss命令和Recv-Q和Send-Q状态

    ss 用来显示处于活动状态的套接字信息.ss命令可以用来获取socket统计信息,它可以显示和netstat类似的内容.但ss的优势在于它能够显示更多更详细的有关TCP和连接状态的信息,而且比nets ...

  4. SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//设置日期格式

    java日期格式大全 format SimpleDateFormat(转) SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH ...

  5. SS - DIY一个前端模板引擎.(一)

    前端MVVM 模式有点很多,完全摆脱了意大利面条式的代码. 个人认为,所有MVVM 的框架基础就是一个高性能的JS模板引擎,它极大简化了 DOM 操作, 使页面渲染和业务逻辑彻底分离. 为了理解模板引 ...

  6. YYYY-mm-dd HH:MM:SS

    备忘:YYYY-mm-dd HH:MM:SS部分解释 d               月中的某一天.一位数的日期没有前导零.    dd             月中的某一天.一位数的日期有一个前导零 ...

  7. js 获取当前日期时间3种格式化方法 yyyy-mm-dd hh:MM:ss

    方法一: Date.prototype.format = function (format) { var args = { "M+": this.getMonth() + 1, & ...

  8. 在VPS上搭建SS访问火星

    前段时间发布了Visual Studio 2017 RC,由于现在VS没有离线的ISO了,只有一个在线安装文件.虽然可以通过这个在线安装文件生成完整的离线安装包(之前的ISO版本在安装过程中仍然需要联 ...

  9. 每天一个linux命令(57):ss命令

    ss是Socket Statistics​的缩写.顾名思义,ss命令可以用来获取socket统计信息,它可以显示和netstat类似的内容.但ss的优势在于它能够显示更多更详细的有关TCP和连接状态的 ...

  10. Oracle中把一个DateTime的字符串转化成date类型。to_date('2016/12/8 18:55:43','yyyy/MM/dd hh24:mi:ss'),

    Oracle中把一个DateTime或者该形态字符串转化成date类型. to_date('2016/12/8 18:55:43','yyyy/MM/dd hh24:mi:ss'), 或者: sele ...

随机推荐

  1. 整理的最全 python常见面试题

      整理的最全 python常见面试题(基本必考)① ②③④⑤⑥⑦⑧⑨⑩ 1.大数据的文件读取: ① 利用生成器generator: ②迭代器进行迭代遍历:for line in file; 2.迭代 ...

  2. 4:Median of Two Sorted Arrays

    here are two sorted arrays nums1 and nums2 of size m and n respectively. Find the median of the two ...

  3. 转帖 利用伪元素和css3实现鼠标移入下划线向两边展开效果

    原帖地址   https://www.cnblogs.com/yangjunfei/p/6739683.html 感谢分享 一.思路: 将伪元素:before和:after定位到元素底部中间,设置宽度 ...

  4. Digispark(ATTINY85) 微型开发板驱动安装与开发环境配置教程

    前几天无聊就弄了弄这个玩,网上教程可能有点杂,在这里就总结一下. Digispark开发板(也就是badusb)能干什么,自己搜去,/坏笑. 1.准备材料:Attiny85微型 USB接口开发板 Di ...

  5. Robot Framework(AutoItLibrary库关键字介绍)

    AutoItLibrary库关键字 AutoItLibrary 的对象操作大体上有几大主要部分,Window 操作.Control 操作.Mouse 操作.Process操作.Run 操作.Reg 操 ...

  6. iOS设备的屏幕分辨率

    全部列在这里吧.方便自己方便别人.保持更新…… iPhone: iPhone 1G320x480 iPhone 3G320x480 iPhone 3GS320x480 iPhone 4640x960 ...

  7. ZOJ 3607 Lazier Salesgirl

    Kochiya Sanae is a lazy girl who makes and sells bread. She is an expert at bread making and selling ...

  8. 修改MyEclipse8.5的workspaces

    到MyEclipse8.5的安装目录下 我安装在D盘,路径为:D:\Genuitec\MyEclipse 8.5\configuration\config.ini   打开config.ini文件: ...

  9. js验证身份证号码是否合规

    需求:最近要做实名验证的功能,但是验证身份证号码和身份证图片的接口不想短信,比较贵,所以之前我们要验证严谨一点,参考了网上关于验证身份证号码的代码,总结一下 代码: //验证身份证号码 functio ...

  10. php 命名空间与文件引入

    问题描述:这两天试着自己写一些东西,也是为了复习一下忘了的PHP基础知识,但是写到命名空间的时候遇到了一点问题,在这记录一下:当我写好文件之后,添加了命名空间,结果一直提示命名空间下类不存在,一直以为 ...