# # CDDL HEADER START # # This file and its contents are supplied under the terms of the # Common Development and Distribution License ("CDDL"), version 1.0. # You may only use this file in accordance with the terms of version # 1.0 of the CDDL. # # A full copy of the text of the CDDL should have accompanied this # source. A copy of the CDDL is also available via the Internet at # http://www.illumos.org/license/CDDL. # # CDDL HEADER END # # # Copyright (c) 2015 by Delphix. All rights reserved. # PROG= connstat OBJS= connstat_main.o connstat_mib.o connstat_tcp.o SRCS= $(OBJS:%.o=%.c) POFILES= connstat_main.po connstat_tcp.po connstat_mib.po POFILE= connstat.po include ../Makefile.cmd include ../Makefile.ctf CSTD= $(CSTD_GNU99) LDLIBS += -lsocket -lnsl -lumem -lofmt XGETFLAGS += -a -x $(PROG).xcl .KEEP_STATE: all: $(PROG) $(PROG): $(OBJS) $(LINK.c) -o $@ $(OBJS) $(LDLIBS) $(POST_PROCESS) $(POFILE): $(POFILES) $(RM) $@ cat $(POFILES) > $@ install: all $(ROOTPROG) clean: $(RM) $(OBJS) lint: lint_SRCS include ../Makefile.targ /* * CDDL HEADER START * * This file and its contents are supplied under the terms of the * Common Development and Distribution License ("CDDL"), version 1.0. * You may only use this file in accordance with the terms of version * 1.0 of the CDDL. * * A full copy of the text of the CDDL should have accompanied this * source. A copy of the CDDL is also available via the Internet at * http://www.illumos.org/license/CDDL. * * CDDL HEADER END */ /* * Copyright (c) 2015, 2016 by Delphix. All rights reserved. */ #ifndef _CONNSTAT_H #define _CONNSTAT_H #include #include #include #include #ifdef __cplusplus extern "C" { #endif typedef struct connstat_conn_attr_s { struct sockaddr_storage ca_laddr; struct sockaddr_storage ca_raddr; int ca_lport; int ca_rport; int ca_state; } connstat_conn_attr_t; typedef struct conn_walk_state_s { ofmt_handle_t cws_ofmt; uint_t cws_flags; connstat_conn_attr_t cws_filter; } conn_walk_state_t; /* cws_flags */ #define CS_LOOPBACK 0x0001 /* Include loopback connections */ #define CS_IPV4 0x0002 /* Show only IPv4 connections */ #define CS_IPV6 0x0004 /* Show only IPv6 connections */ #define CS_LADDR 0x0008 /* Filter by laddr in cws_filter */ #define CS_RADDR 0x0010 /* Filter by raddr in cws_filter */ #define CS_LPORT 0x0020 /* Filter by lport in cws_filter */ #define CS_RPORT 0x0040 /* Filter by rport in cws_filter */ #define CS_STATE 0x0080 /* Filter by state in cws_filter */ #define CS_PARSABLE 0x0100 /* Parsable output */ typedef ofmt_field_t *connstat_getfieldsfunc_t(void); typedef void connstat_walkfunc_t(struct strbuf *, conn_walk_state_t *); typedef struct connstat_proto_s { char *csp_proto; char *csp_default_fields; int csp_miblevel; int csp_mibv4name; int csp_mibv6name; connstat_getfieldsfunc_t *csp_getfields; connstat_walkfunc_t *csp_v4walk; connstat_walkfunc_t *csp_v6walk; } connstat_proto_t; boolean_t print_string(ofmt_arg_t *, char *, uint_t); boolean_t print_uint16(ofmt_arg_t *, char *, uint_t); boolean_t print_uint32(ofmt_arg_t *, char *, uint_t); boolean_t print_uint64(ofmt_arg_t *, char *, uint_t); #ifdef __cplusplus } #endif #endif /* _CONNSTAT_H */ # # CDDL HEADER START # # This file and its contents are supplied under the terms of the # Common Development and Distribution License ("CDDL"), version 1.0. # You may only use this file in accordance with the terms of version # 1.0 of the CDDL. # # A full copy of the text of the CDDL should have accompanied this # source. A copy of the CDDL is also available via the Internet at # http://www.illumos.org/license/CDDL. # # CDDL HEADER END # # # Copyright (c) 2015 by Delphix. All rights reserved. # msgid "count" msgid "established" msgid "filter" msgid "help" msgid "interval" msgid "ipv4" msgid "ipv6" msgid "no-loopback" msgid "output" msgid "parsable" msgid "protocol" msgid "timestamp" msgid "tcp" msgid "laddr,lport,raddr,rport,inbytes,outbytes," "retransbytes,suna,swnd,cwnd,rwnd" msgid " %s\n" msgid "" msgid "c:eF:hi:Lo:Pp:T:46" msgid "all" msgid "laddr" msgid "raddr" msgid "lport" msgid "rport" msgid "= " msgid "%s%ld\n" msgid "%s%s\n" msgid "%hu" msgid "%u" msgid "%llu" msgid "%s: " msgid "LADDR" msgid "RADDR" msgid "LPORT" msgid "RPORT" msgid "INBYTES" msgid "INSEGS" msgid "INUNORDERBYTES" msgid "INUNORDERSEGS" msgid "OUTBYTES" msgid "OUTSEGS" msgid "RETRANSBYTES" msgid "RETRANSSEGS" msgid "SUNA" msgid "count" msgid "SWND" msgid "CWND" msgid "RWND" msgid "STATE" msgid "CLOSED" msgid "IDLE" msgid "BOUND" msgid "LISTEN" msgid "SYN_SENT" msgid "SYN_RCVD" msgid "ESTABLISHED" msgid "CLOSE_WAIT" msgid "FIN_WAIT_1" msgid "CLOSING" msgid "LAST_ACK" msgid "FIN_WAIT_2" msgid "TIME_WAIT" msgid "UNKNOWN(%d)" msgid "/dev/arp" msgid "putmsg" msgid "getmsg" msgid "malloc" /* * CDDL HEADER START * * This file and its contents are supplied under the terms of the * Common Development and Distribution License ("CDDL"), version 1.0. * You may only use this file in accordance with the terms of version * 1.0 of the CDDL. * * A full copy of the text of the CDDL should have accompanied this * source. A copy of the CDDL is also available via the Internet at * http://www.illumos.org/license/CDDL. * * CDDL HEADER END */ /* * Copyright (c) 2015, 2016 by Delphix. All rights reserved. */ #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include "connstat.h" #include "connstat_mib.h" #include "connstat_tcp.h" #define DEFAULT_PROTO "tcp" static const char *invalid_v4v6_msg = "Invalid combination of IPv4 and IPv6 arguments\n"; static const char *invalid_T_msg = "Invalid -T arg \"%s\". Must be \"u\" or \"d\"\n"; static const struct option longopts[] = { { "count", required_argument, 0, 'c' }, { "established", no_argument, 0, 'e' }, { "filter", required_argument, 0, 'F' }, { "help", no_argument, 0, 'h' }, { "interval", required_argument, 0, 'i' }, { "ipv4", no_argument, 0, '4' }, { "ipv6", no_argument, 0, '6' }, { "no-loopback", no_argument, 0, 'L' }, { "output", required_argument, 0, 'o' }, { "parsable", no_argument, 0, 'P' }, { "protocol", required_argument, 0, 'p' }, { "timestamp", required_argument, 0, 'T' }, { NULL, 0, 0, 0 } }; static connstat_proto_t connstat_protos[] = { CONNSTAT_TCP_PROTO, { NULL, NULL, 0, 0, 0, NULL, NULL, NULL } }; typedef enum { NOTIMESTAMP, UTIMESTAMP, DTIMESTAMP } timestamp_fmt_t; static void die(const char *, ...) __NORETURN; static void process_filter(char *, connstat_conn_attr_t *, uint_t *); static void show_stats(connstat_proto_t *, ofmt_handle_t, uint_t, connstat_conn_attr_t *, timestamp_fmt_t, uint_t, uint_t); static void __NORETURN usage(int code) { static const char *opts[] = { "-4, --ipv4 Only display IPv4 connections", "-6, --ipv6 Only display IPv6 connections", "-c, --count=COUNT Only print COUNT reports", "-e, --established Only display established connections", "-F, --filter=FILTER Only display connections that match " "FILTER", "-h, --help Print this help", "-i, --interval=SECONDS Report once every SECONDS seconds", "-L, --no-loopback Omit loopback connections", "-o, --output=FIELDS Restrict output to the comma-separated " "list of fields\n" " specified", "-P, --parsable Parsable output mode", "-T, --timestamp=TYPE Display a timestamp for each iteration", NULL }; (void) fprintf(stderr, gettext("usage: ")); (void) fprintf(stderr, gettext("%s [-eLP] [-4|-6] [-T d|u] [-F ]\n" " [-i [-c ]] [-o [,...]]\n"), getprogname()); (void) fprintf(stderr, gettext("\nOptions:\n")); for (const char **optp = opts; *optp != NULL; optp++) { (void) fprintf(stderr, " %s\n", gettext(*optp)); } (void) fprintf(stderr, gettext("\nFilter:\n")); (void) fprintf(stderr, gettext(" The FILTER argument for the -F " "option is of the form:\n" " =,[=,...]\n")); (void) fprintf(stderr, gettext(" Filterable fields are laddr, lport, " "raddr, rport, and state.\n")); (void) fprintf(stderr, gettext("\nFields:\n")); (void) fprintf(stderr, gettext( " laddr Local IP address\n" " raddr Remote IP address\n" " lport Local port\n" " rport Remote port\n" " inbytes Total bytes received\n" " insegs Total segments received\n" " inunorderbytes Bytes received out of order\n" " inunordersegs Segments received out of order\n" " outbytes Total bytes sent\n" " outsegs Total segments sent\n" " retransbytes Bytes retransmitted\n" " retranssegs Segments retransmitted\n" " suna Current unacknowledged bytes sent\n" " unsent Unsent bytes on the transmit queue\n" " swnd Send window size (peer's receive window)\n" " cwnd Congestion window size\n" " rwnd Receive window size\n" " mss Maximum segment size\n" " rto Retransmission timeout (ms)\n" " rtt Smoothed round-trip time (us)\n" " rtts Sum round-trip time (us)\n" " rttc Count of round-trip times\n" " state Connection state\n")); exit(code); } static connstat_proto_t * getproto(const char *proto) { for (connstat_proto_t *current = &connstat_protos[0]; current->csp_proto != NULL; current++) { if (strcasecmp(proto, current->csp_proto) == 0) { return (current); } } return (NULL); } int main(int argc, char *argv[]) { int option; int count = 0; int interval = 0; const char *errstr = NULL; char *fields = NULL; char *filterstr = NULL; connstat_conn_attr_t filter = {0}; char *protostr = DEFAULT_PROTO; connstat_proto_t *proto; ofmt_handle_t ofmt; ofmt_status_t oferr; char oferrbuf[OFMT_BUFSIZE]; uint_t ofmtflags = OFMT_NOHEADER; uint_t flags = CS_LOOPBACK | CS_IPV4 | CS_IPV6; timestamp_fmt_t timestamp_fmt = NOTIMESTAMP; (void) setlocale(LC_ALL, ""); #if !defined(TEXT_DOMAIN) #define TEXT_DOMAIN "SYS_TEST" #endif (void) textdomain(TEXT_DOMAIN); setprogname(basename(argv[0])); while ((option = getopt_long(argc, argv, "c:eF:hi:Lo:Pp:T:46", longopts, NULL)) != -1) { switch (option) { case 'c': count = strtonum(optarg, 1, INT_MAX, &errstr); if (errstr != NULL) { (void) fprintf(stderr, gettext( "error parsing -c argument (%s): %s\n"), optarg, errstr); usage(1); } break; case 'e': flags |= CS_STATE; filter.ca_state = TCPS_ESTABLISHED; break; case 'F': filterstr = optarg; break; case 'i': interval = strtonum(optarg, 1, INT_MAX, &errstr); if (errstr != NULL) { (void) fprintf(stderr, gettext( "error parsing -i argument (%s): %s\n"), optarg, errstr); usage(1); } break; case 'L': flags &= ~CS_LOOPBACK; break; case 'o': fields = optarg; break; case 'P': ofmtflags |= OFMT_PARSABLE; flags |= CS_PARSABLE; break; case 'p': /* * -p is an undocumented flag whose only supported * argument is "tcp". The idea is to reserve this * flag for potential future use in case connstat * is extended to support stats for other protocols. */ protostr = optarg; break; case 'T': if (strcmp(optarg, "u") == 0) { timestamp_fmt = UTIMESTAMP; } else if (strcmp(optarg, "d") == 0) { timestamp_fmt = DTIMESTAMP; } else { (void) fprintf(stderr, gettext( invalid_T_msg), optarg); usage(1); } break; case '4': if (!(flags & CS_IPV4)) { (void) fprintf(stderr, gettext( invalid_v4v6_msg)); usage(1); } flags &= ~CS_IPV6; break; case '6': if (!(flags & CS_IPV6)) { (void) fprintf(stderr, gettext( invalid_v4v6_msg)); usage(1); } flags &= ~CS_IPV4; break; case '?': default: usage(1); break; } } if ((proto = getproto(protostr)) == NULL) { die("unknown protocol given to \"-p\": %s", protostr); } if ((ofmtflags & OFMT_PARSABLE) && fields == NULL) { die("parsable output requires \"-o\""); } if ((ofmtflags & OFMT_PARSABLE) && fields != NULL && strcasecmp(fields, "all") == 0) { die("\"-o all\" is invalid with parsable output"); } if (fields == NULL) { fields = proto->csp_default_fields; } /* If count is specified, then interval must also be specified. */ if (count != 0 && interval == 0) { die("\"-c\" requires \"-i\""); } /* If interval is not specified, then the default count is 1. */ if (interval == 0 && count == 0) { count = 1; } if (filterstr != NULL) { process_filter(filterstr, &filter, &flags); } oferr = ofmt_open(fields, proto->csp_getfields(), ofmtflags, 0, &ofmt); if (oferr != OFMT_SUCCESS) { (void) ofmt_strerror(ofmt, oferr, oferrbuf, sizeof (oferrbuf)); die(oferrbuf); } ofmt_set_fs(ofmt, ','); show_stats(proto, ofmt, flags, &filter, timestamp_fmt, interval, count); ofmt_close(ofmt); return (0); } /* * Convert the input IP address literal to sockaddr of the appropriate address * family. Preserves any potential port number that may have been set in the * input sockaddr_storage structure. */ static void str2sockaddr(const char *addr, struct sockaddr_storage *ss) { struct addrinfo hints, *res; bzero(&hints, sizeof (hints)); hints.ai_flags = AI_NUMERICHOST; if (getaddrinfo(addr, NULL, &hints, &res) != 0) { die("invalid literal IP address: %s", addr); } bcopy(res->ai_addr, ss, res->ai_addrlen); freeaddrinfo(res); } /* * The filterstr argument is of the form: =[,...] * Possible attributes are laddr, raddr, lport, and rport. Parse this * filter and store the results into the provided attribute structure. */ static void process_filter(char *filterstr, connstat_conn_attr_t *filter, uint_t *flags) { int option; char *val; enum { F_LADDR, F_RADDR, F_LPORT, F_RPORT, F_STATE }; static char *filter_optstr[] = { "laddr", "raddr", "lport", "rport", "state", NULL }; uint_t flag = 0; struct sockaddr_storage *addrp = NULL; const char *errstr = NULL; int *portp = NULL; while (*filterstr != '\0') { option = getsubopt(&filterstr, filter_optstr, &val); errno = 0; switch (option) { case F_LADDR: flag = CS_LADDR; addrp = &filter->ca_laddr; break; case F_RADDR: flag = CS_RADDR; addrp = &filter->ca_raddr; break; case F_LPORT: flag = CS_LPORT; portp = &filter->ca_lport; break; case F_RPORT: flag = CS_RPORT; portp = &filter->ca_rport; break; case F_STATE: flag = CS_STATE; break; default: usage(1); } if (*flags & flag) { (void) fprintf(stderr, gettext( "Ambiguous filter provided. The \"%s\" field " "appears more than once.\n"), filter_optstr[option]); usage(1); } *flags |= flag; switch (flag) { case CS_LADDR: case CS_RADDR: str2sockaddr(val, addrp); if (addrp->ss_family == AF_INET) { if (!(*flags & CS_IPV4)) { (void) fprintf(stderr, gettext( invalid_v4v6_msg)); usage(1); } *flags &= ~CS_IPV6; } else { if (!(*flags & CS_IPV6)) { (void) fprintf(stderr, gettext( invalid_v4v6_msg)); usage(1); } *flags &= ~CS_IPV4; } break; case CS_LPORT: case CS_RPORT: *portp = strtonum(val, 1, UINT16_MAX, &errstr); if (errstr != NULL) { (void) fprintf(stderr, gettext( "error parsing port (%s): %s\n"), val, errstr); usage(1); } break; case CS_STATE: filter->ca_state = tcp_str2state(val); if (filter->ca_state < TCPS_CLOSED) { (void) fprintf(stderr, gettext( "invalid TCP state: %s\n"), val); usage(1); } break; } } /* Make sure that laddr and raddr are at least in the same family. */ if ((*flags & (CS_LADDR|CS_RADDR)) == (CS_LADDR|CS_RADDR)) { if (filter->ca_laddr.ss_family != filter->ca_raddr.ss_family) { die("laddr and raddr must be of the same family."); } } } /* * Print timestamp as decimal representation of time_t value (-T u was * specified) or in date(1) format (-T d was specified). */ static void print_timestamp(timestamp_fmt_t timestamp_fmt, boolean_t parsable) { time_t t = time(NULL); char *pfx = parsable ? "= " : ""; static char *fmt = NULL; /* We only need to retrieve this once per invocation */ if (fmt == NULL) { fmt = nl_langinfo(_DATE_FMT); } switch (timestamp_fmt) { case NOTIMESTAMP: break; case UTIMESTAMP: (void) printf("%s%ld\n", pfx, t); break; case DTIMESTAMP: { char dstr[64]; size_t len; len = strftime(dstr, sizeof (dstr), fmt, localtime(&t)); if (len > 0) { (void) printf("%s%s\n", pfx, dstr); } break; } default: abort(); break; } } static void show_stats(connstat_proto_t *proto, ofmt_handle_t ofmt, uint_t flags, connstat_conn_attr_t *filter, timestamp_fmt_t timestamp_fmt, uint_t interval, uint_t count) { boolean_t done = B_FALSE; uint_t i = 0; int mibfd; conn_walk_state_t state; state.cws_ofmt = ofmt; state.cws_flags = flags; state.cws_filter = *filter; if ((mibfd = mibopen(proto->csp_proto)) == -1) { die("failed to open MIB stream: %s", strerror(errno)); } do { if (timestamp_fmt != NOTIMESTAMP) { print_timestamp(timestamp_fmt, flags & CS_PARSABLE); } if (!(flags & CS_PARSABLE)) { ofmt_print_header(ofmt); } if (conn_walk(mibfd, proto, &state) != 0) { die("failed to fetch and print connection info"); } if (count != 0 && ++i == count) { done = B_TRUE; } else { (void) sleep(interval); } } while (!done); } /* * ofmt callbacks for printing individual fields of various types. */ boolean_t print_string(ofmt_arg_t *ofarg, char *buf, uint_t bufsize) { char *value; value = (char *)ofarg->ofmt_cbarg + ofarg->ofmt_id; (void) strlcpy(buf, value, bufsize); return (B_TRUE); } boolean_t print_uint16(ofmt_arg_t *ofarg, char *buf, uint_t bufsize) { uint16_t value; /* LINTED E_BAD_PTR_CAST_ALIGN */ value = *(uint16_t *)((char *)ofarg->ofmt_cbarg + ofarg->ofmt_id); (void) snprintf(buf, bufsize, "%hu", value); return (B_TRUE); } boolean_t print_uint32(ofmt_arg_t *ofarg, char *buf, uint_t bufsize) { uint32_t value; /* LINTED E_BAD_PTR_CAST_ALIGN */ value = *(uint32_t *)((char *)ofarg->ofmt_cbarg + ofarg->ofmt_id); (void) snprintf(buf, bufsize, "%u", value); return (B_TRUE); } boolean_t print_uint64(ofmt_arg_t *ofarg, char *buf, uint_t bufsize) { uint64_t value; /* LINTED E_BAD_PTR_CAST_ALIGN */ value = *(uint64_t *)((char *)ofarg->ofmt_cbarg + ofarg->ofmt_id); (void) snprintf(buf, bufsize, "%llu", value); return (B_TRUE); } /* PRINTFLIKE1 */ static void die(const char *format, ...) { va_list alist; format = gettext(format); va_start(alist, format); verrx(1, format, alist); va_end(alist); } /* * CDDL HEADER START * * This file and its contents are supplied under the terms of the * Common Development and Distribution License ("CDDL"), version 1.0. * You may only use this file in accordance with the terms of version * 1.0 of the CDDL. * * A full copy of the text of the CDDL should have accompanied this * source. A copy of the CDDL is also available via the Internet at * http://www.illumos.org/license/CDDL. * * CDDL HEADER END */ /* * Copyright (c) 2015 by Delphix. All rights reserved. */ #include #include #include #include #include #include #include #include #include #include #include "connstat.h" int mibopen(const char *proto) { int saved; int fd; fd = open("/dev/arp", O_RDWR); if (fd == -1) { return (-1); } if (ioctl(fd, I_PUSH, proto) == -1) { saved = errno; (void) close(fd); errno = saved; return (-1); } return (fd); } int conn_walk(int fd, connstat_proto_t *proto, conn_walk_state_t *state) { struct strbuf cbuf, dbuf; struct opthdr *hdr; int flags, r, err = 0; struct { struct T_optmgmt_req req; struct opthdr hdr; } req; union { struct T_optmgmt_ack ack; uint8_t space[sizeof (struct T_optmgmt_ack) + sizeof (struct opthdr) * 2]; } ack; bzero(&cbuf, sizeof (cbuf)); bzero(&dbuf, sizeof (dbuf)); req.req.PRIM_type = T_OPTMGMT_REQ; req.req.OPT_offset = (caddr_t)&req.hdr - (caddr_t)&req; req.req.OPT_length = sizeof (req.hdr); req.req.MGMT_flags = T_CURRENT; req.hdr.level = proto->csp_miblevel; req.hdr.name = 0; req.hdr.len = 0; cbuf.buf = (caddr_t)&req; cbuf.len = sizeof (req); if (putmsg(fd, &cbuf, NULL, 0) == -1) { warn("failed to request connection info: putmsg"); return (-1); } /* * Each reply consists of a control part for one fixed structure or * table, as defined in mib2.h. The format is a T_OPTMGMT_ACK * containing an opthdr structure. The level and name identify the * entry, and len is the size of the data part of the message. */ for (;;) { cbuf.buf = (caddr_t)&ack; cbuf.maxlen = sizeof (ack); flags = 0; /* * We first do a getmsg() for the control part so that we * can allocate a properly sized buffer to read the data * part. */ do { r = getmsg(fd, &cbuf, NULL, &flags); } while (r < 0 && errno == EINTR); if (r < 0) { warn("failed to fetch further connection info"); err = -1; break; } else if ((r & MORECTL) != 0) { warnx("failed to fetch full control message"); err = -1; break; } if (cbuf.len < sizeof (struct T_optmgmt_ack) || ack.ack.PRIM_type != T_OPTMGMT_ACK || ack.ack.MGMT_flags != T_SUCCESS || ack.ack.OPT_length < sizeof (struct opthdr)) { warnx("cannot process invalid message from getmsg()"); err = -1; break; } /* LINTED E_BAD_PTR_CAST_ALIGN */ hdr = (struct opthdr *)((caddr_t)&ack + ack.ack.OPT_offset); if (r == 0 && hdr->level == 0 && hdr->name == 0) { /* * snmpcom_req() has sent us the final End-Of-Data * message, so there's nothing further to read. */ break; } /* Only data should remain. */ VERIFY3S(r, ==, MOREDATA); /* Allocate a buffer to hold the data portion of the message */ if ((dbuf.buf = realloc(dbuf.buf, hdr->len)) == NULL) { warn("failed to realloc() buffer"); err = -1; break; } dbuf.maxlen = hdr->len; dbuf.len = 0; flags = 0; do { r = getmsg(fd, NULL, &dbuf, &flags); } while (r < 0 && errno == EINTR); if (r < 0) { warn("failed to fetch connection data: getmsg()"); err = -1; break; } else if (r != 0) { warnx("failed to fetch all data: " "getmsg() returned %d", r); err = -1; break; } if ((state->cws_flags & CS_IPV4) && hdr->name == proto->csp_mibv4name) { proto->csp_v4walk(&dbuf, state); } else if ((state->cws_flags & CS_IPV6) && hdr->name == proto->csp_mibv6name) { proto->csp_v6walk(&dbuf, state); } } free(dbuf.buf); return (err); } /* * CDDL HEADER START * * This file and its contents are supplied under the terms of the * Common Development and Distribution License ("CDDL"), version 1.0. * You may only use this file in accordance with the terms of version * 1.0 of the CDDL. * * A full copy of the text of the CDDL should have accompanied this * source. A copy of the CDDL is also available via the Internet at * http://www.illumos.org/license/CDDL. * * CDDL HEADER END */ /* * Copyright (c) 2015 by Delphix. All rights reserved. */ #ifndef _CONNSTAT_MIB_H #define _CONNSTAT_MIB_H #include "connstat.h" #ifdef __cplusplus extern "C" { #endif int mibopen(const char *); int conn_walk(int, connstat_proto_t *, conn_walk_state_t *); #ifdef __cplusplus } #endif #endif /* _CONNSTAT_MIB_H */ /* * CDDL HEADER START * * This file and its contents are supplied under the terms of the * Common Development and Distribution License ("CDDL"), version 1.0. * You may only use this file in accordance with the terms of version * 1.0 of the CDDL. * * A full copy of the text of the CDDL should have accompanied this * source. A copy of the CDDL is also available via the Internet at * http://www.illumos.org/license/CDDL. * * CDDL HEADER END */ /* * Copyright (c) 2015, 2016 by Delphix. All rights reserved. */ #include #include #include #include #include #include #include #include #include #include #include #include #include #include "connstat_mib.h" #include "connstat_tcp.h" /* * The byte order of some of the fields in this code can be a bit confusing. * When using sockaddr_in(6) structs, the address and ports are always in * Network Byte Order (Big Endian), as required by sockaddr(3SOCKET). * * When using the structs mib2_tcpConnEntry_t and mib2_tcp6ConnEntry_t, the * address fields (tcp(6)ConnLocalAddress and tcp(6)ConnRemAdddress) are in * Network Byte Order. Note, however, that the port fields ARE NOT, but are * instead in Host Byte Order. This isn't a problem though, since the ports * we filter on from the command-line (ca_lport and ca_rport) are kept in * Host Byte Order after parsing. * * Since the t_lport and t_rport fields come from the MIB structs, they are * likewise stored in Host Byte Order (and need to be for printing). The * t_laddr and t_raddr fields are string representations of the addresses, * so they don't require any special attention. * * All of the statistics (such as bytes read and written, current window * sizes, etc.) are in Host Byte Order. */ typedef struct tcp_fields_buf_s { char t_laddr[INET6_ADDRSTRLEN]; char t_raddr[INET6_ADDRSTRLEN]; uint16_t t_lport; uint16_t t_rport; uint64_t t_inbytes; uint64_t t_insegs; uint64_t t_inunorderbytes; uint64_t t_inunordersegs; uint64_t t_outbytes; uint64_t t_outsegs; uint64_t t_retransbytes; uint64_t t_retranssegs; uint32_t t_suna; uint32_t t_unsent; uint32_t t_swnd; uint32_t t_cwnd; uint32_t t_rwnd; uint32_t t_mss; uint32_t t_rto; uint32_t t_rtt_cnt; uint64_t t_rtt_sum; int t_state; uint64_t t_rtt; } tcp_fields_buf_t; static boolean_t print_tcp_state(ofmt_arg_t *, char *, uint_t); static ofmt_field_t tcp_fields[] = { { "LADDR", 26, offsetof(tcp_fields_buf_t, t_laddr), print_string }, { "RADDR", 26, offsetof(tcp_fields_buf_t, t_raddr), print_string }, { "LPORT", 6, offsetof(tcp_fields_buf_t, t_lport), print_uint16 }, { "RPORT", 6, offsetof(tcp_fields_buf_t, t_rport), print_uint16 }, { "INBYTES", 11, offsetof(tcp_fields_buf_t, t_inbytes), print_uint64 }, { "INSEGS", 11, offsetof(tcp_fields_buf_t, t_insegs), print_uint64 }, { "INUNORDERBYTES", 15, offsetof(tcp_fields_buf_t, t_inunorderbytes), print_uint64 }, { "INUNORDERSEGS", 14, offsetof(tcp_fields_buf_t, t_inunordersegs), print_uint64 }, { "OUTBYTES", 11, offsetof(tcp_fields_buf_t, t_outbytes), print_uint64 }, { "OUTSEGS", 11, offsetof(tcp_fields_buf_t, t_outsegs), print_uint64 }, { "RETRANSBYTES", 13, offsetof(tcp_fields_buf_t, t_retransbytes), print_uint64 }, { "RETRANSSEGS", 12, offsetof(tcp_fields_buf_t, t_retranssegs), print_uint64 }, { "SUNA", 11, offsetof(tcp_fields_buf_t, t_suna), print_uint32 }, { "UNSENT", 11, offsetof(tcp_fields_buf_t, t_unsent), print_uint32 }, { "SWND", 11, offsetof(tcp_fields_buf_t, t_swnd), print_uint32 }, { "CWND", 11, offsetof(tcp_fields_buf_t, t_cwnd), print_uint32 }, { "RWND", 11, offsetof(tcp_fields_buf_t, t_rwnd), print_uint32 }, { "MSS", 6, offsetof(tcp_fields_buf_t, t_mss), print_uint32 }, { "RTO", 8, offsetof(tcp_fields_buf_t, t_rto), print_uint32 }, { "RTT", 8, offsetof(tcp_fields_buf_t, t_rtt), print_uint64 }, { "RTTS", 8, offsetof(tcp_fields_buf_t, t_rtt_sum), print_uint64 }, { "RTTC", 11, offsetof(tcp_fields_buf_t, t_rtt_cnt), print_uint32 }, { "STATE", 12, offsetof(tcp_fields_buf_t, t_state), print_tcp_state }, { NULL, 0, 0, NULL} }; static tcp_fields_buf_t fields_buf; typedef struct tcp_state_info_s { int tsi_state; const char *tsi_string; } tcp_state_info_t; tcp_state_info_t tcp_state_info[] = { { TCPS_CLOSED, "CLOSED" }, { TCPS_IDLE, "IDLE" }, { TCPS_BOUND, "BOUND" }, { TCPS_LISTEN, "LISTEN" }, { TCPS_SYN_SENT, "SYN_SENT" }, { TCPS_SYN_RCVD, "SYN_RCVD" }, { TCPS_ESTABLISHED, "ESTABLISHED" }, { TCPS_CLOSE_WAIT, "CLOSE_WAIT" }, { TCPS_FIN_WAIT_1, "FIN_WAIT_1" }, { TCPS_CLOSING, "CLOSING" }, { TCPS_LAST_ACK, "LAST_ACK" }, { TCPS_FIN_WAIT_2, "FIN_WAIT_2" }, { TCPS_TIME_WAIT, "TIME_WAIT" }, { TCPS_CLOSED - 1, NULL } }; ofmt_field_t * tcp_get_fields(void) { return (tcp_fields); } /* * Extract information from the connection info structure into the global * output buffer. */ static void tcp_ci2buf(struct tcpConnEntryInfo_s *ci) { fields_buf.t_inbytes = ci->ce_in_data_inorder_bytes + ci->ce_in_data_unorder_bytes; fields_buf.t_insegs = ci->ce_in_data_inorder_segs + ci->ce_in_data_unorder_segs; fields_buf.t_inunorderbytes = ci->ce_in_data_unorder_bytes; fields_buf.t_inunordersegs = ci->ce_in_data_unorder_segs; fields_buf.t_outbytes = ci->ce_out_data_bytes; fields_buf.t_outsegs = ci->ce_out_data_segs; fields_buf.t_retransbytes = ci->ce_out_retrans_bytes; fields_buf.t_retranssegs = ci->ce_out_retrans_segs; fields_buf.t_suna = ci->ce_snxt - ci->ce_suna; fields_buf.t_unsent = ci->ce_unsent; fields_buf.t_swnd = ci->ce_swnd; fields_buf.t_cwnd = ci->ce_cwnd; fields_buf.t_rwnd = ci->ce_rwnd; fields_buf.t_mss = ci->ce_mss; fields_buf.t_rto = ci->ce_rto; fields_buf.t_rtt = (ci->ce_out_data_segs == 0 ? 0 : ci->ce_rtt_sa); fields_buf.t_rtt_sum = ci->ce_rtt_sum; fields_buf.t_rtt_cnt = ci->ce_rtt_cnt; fields_buf.t_state = ci->ce_state; } /* * Extract information from the connection entry into the global output * buffer. */ static void tcp_ipv4_ce2buf(mib2_tcpConnEntry_t *ce) { VERIFY3P(inet_ntop(AF_INET, (void *)&ce->tcpConnLocalAddress, fields_buf.t_laddr, sizeof (fields_buf.t_laddr)), !=, NULL); VERIFY3P(inet_ntop(AF_INET, (void *)&ce->tcpConnRemAddress, fields_buf.t_raddr, sizeof (fields_buf.t_raddr)), !=, NULL); fields_buf.t_lport = ce->tcpConnLocalPort; fields_buf.t_rport = ce->tcpConnRemPort; tcp_ci2buf(&ce->tcpConnEntryInfo); } static void tcp_ipv6_ce2buf(mib2_tcp6ConnEntry_t *ce) { VERIFY3P(inet_ntop(AF_INET6, (void *)&ce->tcp6ConnLocalAddress, fields_buf.t_laddr, sizeof (fields_buf.t_laddr)), !=, NULL); VERIFY3P(inet_ntop(AF_INET6, (void *)&ce->tcp6ConnRemAddress, fields_buf.t_raddr, sizeof (fields_buf.t_raddr)), !=, NULL); fields_buf.t_lport = ce->tcp6ConnLocalPort; fields_buf.t_rport = ce->tcp6ConnRemPort; tcp_ci2buf(&ce->tcp6ConnEntryInfo); } /* * Print a single IPv4 connection entry, taking into account possible * filters that have been set in state. */ static void tcp_ipv4_print(mib2_tcpConnEntry_t *ce, conn_walk_state_t *state) { if (!(state->cws_flags & CS_LOOPBACK) && ntohl(ce->tcpConnLocalAddress) == INADDR_LOOPBACK) { return; } if (state->cws_flags & CS_LADDR) { struct sockaddr_in *sin = (struct sockaddr_in *)&state->cws_filter.ca_laddr; if (ce->tcpConnLocalAddress != sin->sin_addr.s_addr) { return; } } if (state->cws_flags & CS_RADDR) { struct sockaddr_in *sin = (struct sockaddr_in *)&state->cws_filter.ca_raddr; if (ce->tcpConnRemAddress != sin->sin_addr.s_addr) { return; } } if (state->cws_flags & CS_LPORT) { if (ce->tcpConnLocalPort != state->cws_filter.ca_lport) { return; } } if (state->cws_flags & CS_RPORT) { if (ce->tcpConnRemPort != state->cws_filter.ca_rport) { return; } } if ((state->cws_flags & CS_STATE) && ce->tcpConnEntryInfo.ce_state != state->cws_filter.ca_state) { return; } tcp_ipv4_ce2buf(ce); ofmt_print(state->cws_ofmt, &fields_buf); } /* * Print a single IPv6 connection entry, taking into account possible * filters that have been set in state. */ static void tcp_ipv6_print(mib2_tcp6ConnEntry_t *ce, conn_walk_state_t *state) { if (!(state->cws_flags & CS_LOOPBACK) && IN6_IS_ADDR_LOOPBACK( (struct in6_addr *)&ce->tcp6ConnLocalAddress)) { return; } if (state->cws_flags & CS_LADDR) { struct sockaddr_in6 *sin6 = (struct sockaddr_in6 *)&state->cws_filter.ca_laddr; if (!IN6_ARE_ADDR_EQUAL( (struct in6_addr *)&ce->tcp6ConnLocalAddress, &sin6->sin6_addr)) { return; } } if (state->cws_flags & CS_RADDR) { struct sockaddr_in6 *sin6 = (struct sockaddr_in6 *)&state->cws_filter.ca_raddr; if (!IN6_ARE_ADDR_EQUAL( (struct in6_addr *)&ce->tcp6ConnRemAddress, &sin6->sin6_addr)) { return; } } if (state->cws_flags & CS_LPORT) { if (ce->tcp6ConnLocalPort != state->cws_filter.ca_lport) { return; } } if (state->cws_flags & CS_RPORT) { if (ce->tcp6ConnRemPort != state->cws_filter.ca_rport) { return; } } if ((state->cws_flags & CS_STATE) && ce->tcp6ConnEntryInfo.ce_state != state->cws_filter.ca_state) { return; } tcp_ipv6_ce2buf(ce); ofmt_print(state->cws_ofmt, &fields_buf); } void tcp_walk_ipv4(struct strbuf *dbuf, conn_walk_state_t *state) { uint_t nconns = (dbuf->len / sizeof (mib2_tcpConnEntry_t)); /* LINTED E_BAD_PTR_CAST_ALIGN */ mib2_tcpConnEntry_t *ce = (mib2_tcpConnEntry_t *)dbuf->buf; for (; nconns > 0; ce++, nconns--) { tcp_ipv4_print(ce, state); } } void tcp_walk_ipv6(struct strbuf *dbuf, conn_walk_state_t *state) { uint_t nconns = (dbuf->len / sizeof (mib2_tcp6ConnEntry_t)); /* LINTED E_BAD_PTR_CAST_ALIGN */ mib2_tcp6ConnEntry_t *ce = (mib2_tcp6ConnEntry_t *)dbuf->buf; for (; nconns > 0; ce++, nconns--) { tcp_ipv6_print(ce, state); } } static tcp_state_info_t * tcp_stateinfobystate(int state) { tcp_state_info_t *sip; for (sip = tcp_state_info; sip->tsi_string != NULL; sip++) { if (sip->tsi_state == state) { return (sip); } } return (NULL); } static tcp_state_info_t * tcp_stateinfobystr(const char *statestr) { tcp_state_info_t *sip; for (sip = tcp_state_info; sip->tsi_string != NULL; sip++) { if (strncasecmp(statestr, sip->tsi_string, strlen(sip->tsi_string)) == 0) { return (sip); } } return (NULL); } int tcp_str2state(const char *statestr) { tcp_state_info_t *sip = tcp_stateinfobystr(statestr); return (sip == NULL ? TCPS_CLOSED - 1 : sip->tsi_state); } static const char * tcp_state2str(int state) { tcp_state_info_t *sip = tcp_stateinfobystate(state); return (sip == NULL ? NULL : sip->tsi_string); } static boolean_t print_tcp_state(ofmt_arg_t *ofarg, char *buf, uint_t bufsize) { /* LINTED E_BAD_PTR_CAST_ALIGN */ int state = *(int *)((char *)ofarg->ofmt_cbarg + ofarg->ofmt_id); const char *statestr = tcp_state2str(state); if (statestr != NULL) { (void) strlcpy(buf, statestr, bufsize); } else { (void) snprintf(buf, bufsize, "UNKNOWN(%d)", state); } return (B_TRUE); } /* * CDDL HEADER START * * This file and its contents are supplied under the terms of the * Common Development and Distribution License ("CDDL"), version 1.0. * You may only use this file in accordance with the terms of version * 1.0 of the CDDL. * * A full copy of the text of the CDDL should have accompanied this * source. A copy of the CDDL is also available via the Internet at * http://www.illumos.org/license/CDDL. * * CDDL HEADER END */ /* * Copyright (c) 2015, 2016 by Delphix. All rights reserved. */ #ifndef _CONNSTAT_TCP_H #define _CONNSTAT_TCP_H #include #include "connstat.h" #ifdef __cplusplus extern "C" { #endif int tcp_str2state(const char *state); connstat_getfieldsfunc_t tcp_get_fields; connstat_walkfunc_t tcp_walk_ipv4, tcp_walk_ipv6; /* * Keep the default output to < 80 columns. For most interactive workflows, * the user will run the command without arguments to get an idea of what * connections exist before narrowing down the investigation to a single * connection (with filtering) and specifying additional fields to output * depending on what the user is interested in. */ #define TCP_DEFAULT_FIELDS "laddr,lport,raddr,rport,state" #define CONNSTAT_TCP_PROTO \ { "tcp", TCP_DEFAULT_FIELDS, MIB2_TCP, MIB2_TCP_CONN, MIB2_TCP6_CONN, \ tcp_get_fields, tcp_walk_ipv4, tcp_walk_ipv6 } #ifdef __cplusplus } #endif #endif /* _CONNSTAT_TCP_H */