openbsd-nc

OpenBSD netcat port for Linux
git clone git://git.2f30.org/openbsd-nc
Log | Files | Refs | README

openbsd-nc.c (43959B)


      1 /* $OpenBSD: netcat.c,v 1.181 2017/04/16 15:11:01 deraadt Exp $ */
      2 /*
      3  * Copyright (c) 2001 Eric Jackson <ericj@monkey.org>
      4  * Copyright (c) 2015 Bob Beck.  All rights reserved.
      5  *
      6  * Redistribution and use in source and binary forms, with or without
      7  * modification, are permitted provided that the following conditions
      8  * are met:
      9  *
     10  * 1. Redistributions of source code must retain the above copyright
     11  *   notice, this list of conditions and the following disclaimer.
     12  * 2. Redistributions in binary form must reproduce the above copyright
     13  *   notice, this list of conditions and the following disclaimer in the
     14  *   documentation and/or other materials provided with the distribution.
     15  * 3. The name of the author may not be used to endorse or promote products
     16  *   derived from this software without specific prior written permission.
     17  *
     18  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
     19  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
     20  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
     21  * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
     22  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
     23  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
     24  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
     25  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
     26  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
     27  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
     28  */
     29 
     30 /*
     31  * Re-written nc(1) for OpenBSD. Original implementation by
     32  * *Hobbit* <hobbit@avian.org>.
     33  */
     34 
     35 #include <sys/types.h>
     36 #include <sys/socket.h>
     37 #include <sys/uio.h>
     38 #include <sys/un.h>
     39 
     40 #include <netinet/in.h>
     41 #include <netinet/tcp.h>
     42 #include <netinet/ip.h>
     43 #include <arpa/telnet.h>
     44 
     45 #include <linux/in6.h>
     46 
     47 #include <err.h>
     48 #include <errno.h>
     49 #include <limits.h>
     50 #include <netdb.h>
     51 #include <poll.h>
     52 #include <signal.h>
     53 #include <stdarg.h>
     54 #include <stdio.h>
     55 #include <stdlib.h>
     56 #include <string.h>
     57 #include <time.h>
     58 #include <unistd.h>
     59 #include <tls.h>
     60 
     61 #include <bsd/stdio.h>
     62 #include <bsd/stdlib.h>
     63 #include <bsd/string.h>
     64 
     65 #include "atomicio.h"
     66 #include "utils.h"
     67 
     68 #define PORT_MAX	65535
     69 #define UNIX_DG_TMP_SOCKET_SIZE	19
     70 
     71 #define POLL_STDIN 0
     72 #define POLL_NETOUT 1
     73 #define POLL_NETIN 2
     74 #define POLL_STDOUT 3
     75 #define BUFSIZE 16384
     76 #define DEFAULT_CA_FILE "/etc/ssl/cert.pem"
     77 
     78 #define TLS_ALL	(1 << 1)
     79 #define TLS_NOVERIFY	(1 << 2)
     80 #define TLS_NONAME	(1 << 3)
     81 #define TLS_CCERT	(1 << 4)
     82 #define TLS_MUSTSTAPLE	(1 << 5)
     83 
     84 /* Command Line Options */
     85 int	dflag;					/* detached, no stdin */
     86 int	Fflag;					/* fdpass sock to stdout */
     87 unsigned int iflag;				/* Interval Flag */
     88 int	kflag;					/* More than one connect */
     89 int	lflag;					/* Bind to local port */
     90 int	Nflag;					/* shutdown() network socket */
     91 int	nflag;					/* Don't do name look up */
     92 char   *Pflag;					/* Proxy username */
     93 char   *pflag;					/* Localport flag */
     94 int	rflag;					/* Random ports flag */
     95 char   *sflag;					/* Source Address */
     96 int	tflag;					/* Telnet Emulation */
     97 int	uflag;					/* UDP - Default to TCP */
     98 int	vflag;					/* Verbosity */
     99 int	xflag;					/* Socks proxy */
    100 int	zflag;					/* Port Scan Flag */
    101 int	Dflag;					/* sodebug */
    102 int	Iflag;					/* TCP receive buffer size */
    103 int	Oflag;					/* TCP send buffer size */
    104 int	Sflag;					/* TCP MD5 signature option */
    105 int	Tflag = -1;				/* IP Type of Service */
    106 
    107 int	usetls;					/* use TLS */
    108 char    *Cflag;					/* Public cert file */
    109 char    *Kflag;					/* Private key file */
    110 char    *oflag;					/* OCSP stapling file */
    111 char    *Rflag = DEFAULT_CA_FILE;		/* Root CA file */
    112 int	tls_cachanged;				/* Using non-default CA file */
    113 int     TLSopt;					/* TLS options */
    114 char	*tls_expectname;			/* required name in peer cert */
    115 char	*tls_expecthash;			/* required hash of peer cert */
    116 FILE	*Zflag;					/* file to save peer cert */
    117 
    118 int timeout = -1;
    119 int family = AF_UNSPEC;
    120 char *portlist[PORT_MAX+1];
    121 char *unix_dg_tmp_socket;
    122 int ttl = -1;
    123 int minttl = -1;
    124 
    125 void	atelnet(int, unsigned char *, unsigned int);
    126 void	build_ports(char *);
    127 void	help(void);
    128 int	local_listen(char *, char *, struct addrinfo);
    129 void	readwrite(int, struct tls *);
    130 void	fdpass(int nfd) __attribute__((noreturn));
    131 int	remote_connect(const char *, const char *, struct addrinfo);
    132 int	timeout_tls(int, struct tls *, int (*)(struct tls *));
    133 int	timeout_connect(int, const struct sockaddr *, socklen_t);
    134 int	socks_connect(const char *, const char *, struct addrinfo,
    135 	    const char *, const char *, struct addrinfo, int, const char *);
    136 int	udptest(int);
    137 int	unix_bind(char *, int);
    138 int	unix_connect(char *);
    139 int	unix_listen(char *);
    140 void	set_common_sockopts(int, int);
    141 int	map_tos(char *, int *);
    142 int	map_tls(char *, int *);
    143 void    save_peer_cert(struct tls *_tls_ctx, FILE *_fp);
    144 void	report_connect(const struct sockaddr *, socklen_t, char *);
    145 void	report_tls(struct tls *tls_ctx, char * host, char *tls_expectname);
    146 void	usage(int);
    147 ssize_t drainbuf(int, unsigned char *, size_t *, struct tls *);
    148 ssize_t fillbuf(int, unsigned char *, size_t *, struct tls *);
    149 void	tls_setup_client(struct tls *, int, char *);
    150 struct tls *tls_setup_server(struct tls *, int, char *);
    151 
    152 int
    153 main(int argc, char *argv[])
    154 {
    155 	int ch, s = -1, ret, socksv;
    156 	char *host, *uport;
    157 	struct addrinfo hints;
    158 	struct servent *sv;
    159 	socklen_t len;
    160 	struct sockaddr_storage cliaddr;
    161 	char *proxy, *proxyport = NULL;
    162 	const char *errstr;
    163 	struct addrinfo proxyhints;
    164 	char unix_dg_tmp_socket_buf[UNIX_DG_TMP_SOCKET_SIZE];
    165 	struct tls_config *tls_cfg = NULL;
    166 	struct tls *tls_ctx = NULL;
    167 
    168 	ret = 1;
    169 	socksv = 5;
    170 	host = NULL;
    171 	uport = NULL;
    172 	sv = NULL;
    173 
    174 	signal(SIGPIPE, SIG_IGN);
    175 
    176 	while ((ch = getopt(argc, argv,
    177 	    "46C:cDde:FH:hI:i:K:klM:m:NnO:o:P:p:R:rSs:T:tUuV:vw:X:x:Z:z")) != -1) {
    178 		switch (ch) {
    179 		case '4':
    180 			family = AF_INET;
    181 			break;
    182 		case '6':
    183 			family = AF_INET6;
    184 			break;
    185 		case 'U':
    186 			family = AF_UNIX;
    187 			break;
    188 		case 'X':
    189 			if (strcasecmp(optarg, "connect") == 0)
    190 				socksv = -1; /* HTTP proxy CONNECT */
    191 			else if (strcmp(optarg, "4") == 0)
    192 				socksv = 4; /* SOCKS v.4 */
    193 			else if (strcmp(optarg, "5") == 0)
    194 				socksv = 5; /* SOCKS v.5 */
    195 			else
    196 				errx(1, "unsupported proxy protocol");
    197 			break;
    198 		case 'C':
    199 			Cflag = optarg;
    200 			break;
    201 		case 'c':
    202 			usetls = 1;
    203 			break;
    204 		case 'd':
    205 			dflag = 1;
    206 			break;
    207 		case 'e':
    208 			tls_expectname = optarg;
    209 			break;
    210 		case 'F':
    211 			Fflag = 1;
    212 			break;
    213 		case 'H':
    214 			tls_expecthash = optarg;
    215 			break;
    216 		case 'h':
    217 			help();
    218 			break;
    219 		case 'i':
    220 			iflag = strtonum(optarg, 0, UINT_MAX, &errstr);
    221 			if (errstr)
    222 				errx(1, "interval %s: %s", errstr, optarg);
    223 			break;
    224 		case 'K':
    225 			Kflag = optarg;
    226 			break;
    227 		case 'k':
    228 			kflag = 1;
    229 			break;
    230 		case 'l':
    231 			lflag = 1;
    232 			break;
    233 		case 'M':
    234 			ttl = strtonum(optarg, 0, 255, &errstr);
    235 			if (errstr)
    236 				errx(1, "ttl is %s", errstr);
    237 			break;
    238 		case 'm':
    239 			minttl = strtonum(optarg, 0, 255, &errstr);
    240 			if (errstr)
    241 				errx(1, "minttl is %s", errstr);
    242 			break;
    243 		case 'N':
    244 			Nflag = 1;
    245 			break;
    246 		case 'n':
    247 			nflag = 1;
    248 			break;
    249 		case 'P':
    250 			Pflag = optarg;
    251 			break;
    252 		case 'p':
    253 			pflag = optarg;
    254 			break;
    255 		case 'R':
    256 			tls_cachanged = 1;
    257 			Rflag = optarg;
    258 			break;
    259 		case 'r':
    260 			rflag = 1;
    261 			break;
    262 		case 's':
    263 			sflag = optarg;
    264 			break;
    265 		case 't':
    266 			tflag = 1;
    267 			break;
    268 		case 'u':
    269 			uflag = 1;
    270 			break;
    271 		case 'V':
    272 			errx(1, "unsupported option");
    273 			break;
    274 		case 'v':
    275 			vflag = 1;
    276 			break;
    277 		case 'w':
    278 			timeout = strtonum(optarg, 0, INT_MAX / 1000, &errstr);
    279 			if (errstr)
    280 				errx(1, "timeout %s: %s", errstr, optarg);
    281 			timeout *= 1000;
    282 			break;
    283 		case 'x':
    284 			xflag = 1;
    285 			if ((proxy = strdup(optarg)) == NULL)
    286 				err(1, NULL);
    287 			break;
    288 		case 'Z':
    289 #if 0
    290 			if (strcmp(optarg, "-") == 0)
    291 				Zflag = stderr;
    292 			else if ((Zflag = fopen(optarg, "w")) == NULL)
    293 				err(1, "can't open %s", optarg);
    294 #else
    295 			errx(1, "unsupported option");
    296 #endif
    297 			break;
    298 		case 'z':
    299 			zflag = 1;
    300 			break;
    301 		case 'D':
    302 			Dflag = 1;
    303 			break;
    304 		case 'I':
    305 			Iflag = strtonum(optarg, 1, 65536 << 14, &errstr);
    306 			if (errstr != NULL)
    307 				errx(1, "TCP receive window %s: %s",
    308 				    errstr, optarg);
    309 			break;
    310 		case 'O':
    311 			Oflag = strtonum(optarg, 1, 65536 << 14, &errstr);
    312 			if (errstr != NULL)
    313 				errx(1, "TCP send window %s: %s",
    314 				    errstr, optarg);
    315 			break;
    316 		case 'o':
    317 			oflag = optarg;
    318 			break;
    319 		case 'S':
    320 			Sflag = 1;
    321 			break;
    322 		case 'T':
    323 			errstr = NULL;
    324 			errno = 0;
    325 			if (map_tos(optarg, &Tflag))
    326 				break;
    327 			if (map_tls(optarg, &TLSopt))
    328 				break;
    329 			if (strlen(optarg) > 1 && optarg[0] == '0' &&
    330 			    optarg[1] == 'x')
    331 				Tflag = (int)strtol(optarg, NULL, 16);
    332 			else
    333 				Tflag = (int)strtonum(optarg, 0, 255,
    334 				    &errstr);
    335 			if (Tflag < 0 || Tflag > 255 || errstr || errno)
    336 				errx(1, "illegal tos/tls value %s", optarg);
    337 			break;
    338 		default:
    339 			usage(1);
    340 		}
    341 	}
    342 	argc -= optind;
    343 	argv += optind;
    344 
    345 	if (family == AF_UNIX) {
    346 		if (pledge("stdio rpath wpath cpath tmppath unix", NULL) == -1)
    347 			err(1, "pledge");
    348 	} else if (Fflag) {
    349 		if (Pflag) {
    350 			if (pledge("stdio inet dns sendfd tty", NULL) == -1)
    351 				err(1, "pledge");
    352 		} else if (pledge("stdio inet dns sendfd", NULL) == -1)
    353 			err(1, "pledge");
    354 	} else if (Pflag) {
    355 		if (pledge("stdio inet dns tty", NULL) == -1)
    356 			err(1, "pledge");
    357 	} else if (usetls) {
    358 		if (pledge("stdio rpath inet dns", NULL) == -1)
    359 			err(1, "pledge");
    360 	} else if (pledge("stdio inet dns", NULL) == -1)
    361 		err(1, "pledge");
    362 
    363 	/* Cruft to make sure options are clean, and used properly. */
    364 	if (argv[0] && !argv[1] && family == AF_UNIX) {
    365 		host = argv[0];
    366 		uport = NULL;
    367 	} else if (argv[0] && !argv[1]) {
    368 		if  (!lflag)
    369 			usage(1);
    370 		uport = argv[0];
    371 		host = NULL;
    372 	} else if (argv[0] && argv[1]) {
    373 		host = argv[0];
    374 		uport = argv[1];
    375 	} else
    376 		usage(1);
    377 
    378 	if (lflag && sflag)
    379 		errx(1, "cannot use -s and -l");
    380 	if (lflag && pflag)
    381 		errx(1, "cannot use -p and -l");
    382 	if (lflag && zflag)
    383 		errx(1, "cannot use -z and -l");
    384 	if (!lflag && kflag)
    385 		errx(1, "must use -l with -k");
    386 	if (uflag && usetls)
    387 		errx(1, "cannot use -c and -u");
    388 	if ((family == AF_UNIX) && usetls)
    389 		errx(1, "cannot use -c and -U");
    390 	if ((family == AF_UNIX) && Fflag)
    391 		errx(1, "cannot use -F and -U");
    392 	if (Fflag && usetls)
    393 		errx(1, "cannot use -c and -F");
    394 	if (TLSopt && !usetls)
    395 		errx(1, "you must specify -c to use TLS options");
    396 	if (Cflag && !usetls)
    397 		errx(1, "you must specify -c to use -C");
    398 	if (Kflag && !usetls)
    399 		errx(1, "you must specify -c to use -K");
    400 	if (Zflag && !usetls)
    401 		errx(1, "you must specify -c to use -Z");
    402 	if (oflag && !Cflag)
    403 		errx(1, "you must specify -C to use -o");
    404 	if (tls_cachanged && !usetls)
    405 		errx(1, "you must specify -c to use -R");
    406 	if (tls_expecthash && !usetls)
    407 		errx(1, "you must specify -c to use -H");
    408 	if (tls_expectname && !usetls)
    409 		errx(1, "you must specify -c to use -e");
    410 
    411 	/* Get name of temporary socket for unix datagram client */
    412 	if ((family == AF_UNIX) && uflag && !lflag) {
    413 		if (sflag) {
    414 			unix_dg_tmp_socket = sflag;
    415 		} else {
    416 			strlcpy(unix_dg_tmp_socket_buf, "/tmp/nc.XXXXXXXXXX",
    417 			    UNIX_DG_TMP_SOCKET_SIZE);
    418 			if (mktemp(unix_dg_tmp_socket_buf) == NULL)
    419 				err(1, "mktemp");
    420 			unix_dg_tmp_socket = unix_dg_tmp_socket_buf;
    421 		}
    422 	}
    423 
    424 	/* Initialize addrinfo structure. */
    425 	if (family != AF_UNIX) {
    426 		memset(&hints, 0, sizeof(struct addrinfo));
    427 		hints.ai_family = family;
    428 		hints.ai_socktype = uflag ? SOCK_DGRAM : SOCK_STREAM;
    429 		hints.ai_protocol = uflag ? IPPROTO_UDP : IPPROTO_TCP;
    430 		if (nflag)
    431 			hints.ai_flags |= AI_NUMERICHOST;
    432 	}
    433 
    434 	if (xflag) {
    435 		if (uflag)
    436 			errx(1, "no proxy support for UDP mode");
    437 
    438 		if (lflag)
    439 			errx(1, "no proxy support for listen");
    440 
    441 		if (family == AF_UNIX)
    442 			errx(1, "no proxy support for unix sockets");
    443 
    444 		if (sflag)
    445 			errx(1, "no proxy support for local source address");
    446 
    447 		if (*proxy == '[') {
    448 			++proxy;
    449 			proxyport = strchr(proxy, ']');
    450 			if (proxyport == NULL)
    451 				errx(1, "missing closing bracket in proxy");
    452 			*proxyport++ = '\0';
    453 			if (*proxyport == '\0')
    454 				/* Use default proxy port. */
    455 				proxyport = NULL;
    456 			else {
    457 				if (*proxyport == ':')
    458 					++proxyport;
    459 				else
    460 					errx(1, "garbage proxy port delimiter");
    461 			}
    462 		} else {
    463 			proxyport = strrchr(proxy, ':');
    464 			if (proxyport != NULL)
    465 				*proxyport++ = '\0';
    466 		}
    467 
    468 		memset(&proxyhints, 0, sizeof(struct addrinfo));
    469 		proxyhints.ai_family = family;
    470 		proxyhints.ai_socktype = SOCK_STREAM;
    471 		proxyhints.ai_protocol = IPPROTO_TCP;
    472 		if (nflag)
    473 			proxyhints.ai_flags |= AI_NUMERICHOST;
    474 	}
    475 
    476 	if (usetls) {
    477 		if (Pflag) {
    478 			if (pledge("stdio inet dns tty rpath", NULL) == -1)
    479 				err(1, "pledge");
    480 		} else if (pledge("stdio inet dns rpath", NULL) == -1)
    481 			err(1, "pledge");
    482 
    483 		if (tls_init() == -1)
    484 			errx(1, "unable to initialize TLS");
    485 		if ((tls_cfg = tls_config_new()) == NULL)
    486 			errx(1, "unable to allocate TLS config");
    487 		if (Rflag && tls_config_set_ca_file(tls_cfg, Rflag) == -1)
    488 			errx(1, "%s", tls_config_error(tls_cfg));
    489 		if (Cflag && tls_config_set_cert_file(tls_cfg, Cflag) == -1)
    490 			errx(1, "%s", tls_config_error(tls_cfg));
    491 		if (Kflag && tls_config_set_key_file(tls_cfg, Kflag) == -1)
    492 			errx(1, "%s", tls_config_error(tls_cfg));
    493 		if (oflag && tls_config_set_ocsp_staple_file(tls_cfg, oflag) == -1)
    494 			errx(1, "%s", tls_config_error(tls_cfg));
    495 		if (TLSopt & TLS_ALL) {
    496 			if (tls_config_set_protocols(tls_cfg,
    497 			    TLS_PROTOCOLS_ALL) != 0)
    498 				errx(1, "%s", tls_config_error(tls_cfg));
    499 			if (tls_config_set_ciphers(tls_cfg, "all") != 0)
    500 				errx(1, "%s", tls_config_error(tls_cfg));
    501 		}
    502 		if (!lflag && (TLSopt & TLS_CCERT))
    503 			errx(1, "clientcert is only valid with -l");
    504 		if (TLSopt & TLS_NONAME)
    505 			tls_config_insecure_noverifyname(tls_cfg);
    506 		if (TLSopt & TLS_NOVERIFY) {
    507 			if (tls_expecthash != NULL)
    508 				errx(1, "-H and -T noverify may not be used"
    509 				    "together");
    510 			tls_config_insecure_noverifycert(tls_cfg);
    511 		}
    512 		if (TLSopt & TLS_MUSTSTAPLE)
    513 			tls_config_ocsp_require_stapling(tls_cfg);
    514 
    515 		if (Pflag) {
    516 			if (pledge("stdio inet dns tty", NULL) == -1)
    517 				err(1, "pledge");
    518 		} else if (pledge("stdio inet dns", NULL) == -1)
    519 			err(1, "pledge");
    520 	}
    521 	if (lflag) {
    522 		struct tls *tls_cctx = NULL;
    523 		int connfd;
    524 		ret = 0;
    525 
    526 		if (family == AF_UNIX) {
    527 			if (uflag)
    528 				s = unix_bind(host, 0);
    529 			else
    530 				s = unix_listen(host);
    531 		}
    532 
    533 		if (usetls) {
    534 			tls_config_verify_client_optional(tls_cfg);
    535 			if ((tls_ctx = tls_server()) == NULL)
    536 				errx(1, "tls server creation failed");
    537 			if (tls_configure(tls_ctx, tls_cfg) == -1)
    538 				errx(1, "tls configuration failed (%s)",
    539 				    tls_error(tls_ctx));
    540 		}
    541 		/* Allow only one connection at a time, but stay alive. */
    542 		for (;;) {
    543 			if (family != AF_UNIX)
    544 				s = local_listen(host, uport, hints);
    545 			if (s < 0)
    546 				err(1, NULL);
    547 			if (uflag && kflag) {
    548 				/*
    549 				 * For UDP and -k, don't connect the socket,
    550 				 * let it receive datagrams from multiple
    551 				 * socket pairs.
    552 				 */
    553 				readwrite(s, NULL);
    554 			} else if (uflag && !kflag) {
    555 				/*
    556 				 * For UDP and not -k, we will use recvfrom()
    557 				 * initially to wait for a caller, then use
    558 				 * the regular functions to talk to the caller.
    559 				 */
    560 				int rv, plen;
    561 				char buf[16384];
    562 				struct sockaddr_storage z;
    563 
    564 				len = sizeof(z);
    565 				plen = 2048;
    566 				rv = recvfrom(s, buf, plen, MSG_PEEK,
    567 				    (struct sockaddr *)&z, &len);
    568 				if (rv < 0)
    569 					err(1, "recvfrom");
    570 
    571 				rv = connect(s, (struct sockaddr *)&z, len);
    572 				if (rv < 0)
    573 					err(1, "connect");
    574 
    575 				if (vflag)
    576 					report_connect((struct sockaddr *)&z, len, NULL);
    577 
    578 				readwrite(s, NULL);
    579 			} else {
    580 				len = sizeof(cliaddr);
    581 				connfd = accept4(s, (struct sockaddr *)&cliaddr,
    582 				    &len, SOCK_NONBLOCK);
    583 				if (connfd == -1) {
    584 					/* For now, all errnos are fatal */
    585 					err(1, "accept");
    586 				}
    587 				if (vflag)
    588 					report_connect((struct sockaddr *)&cliaddr, len,
    589 					    family == AF_UNIX ? host : NULL);
    590 				if ((usetls) &&
    591 				    (tls_cctx = tls_setup_server(tls_ctx, connfd, host)))
    592 					readwrite(connfd, tls_cctx);
    593 				if (!usetls)
    594 					readwrite(connfd, NULL);
    595 				if (tls_cctx) {
    596 					timeout_tls(s, tls_cctx, tls_close);
    597 					tls_free(tls_cctx);
    598 					tls_cctx = NULL;
    599 				}
    600 				close(connfd);
    601 			}
    602 			if (family != AF_UNIX)
    603 				close(s);
    604 			else if (uflag) {
    605 				if (connect(s, NULL, 0) < 0)
    606 					err(1, "connect");
    607 			}
    608 
    609 			if (!kflag)
    610 				break;
    611 		}
    612 	} else if (family == AF_UNIX) {
    613 		ret = 0;
    614 
    615 		if ((s = unix_connect(host)) > 0) {
    616 			if (!zflag)
    617 				readwrite(s, NULL);
    618 			close(s);
    619 		} else
    620 			ret = 1;
    621 
    622 		if (uflag)
    623 			unlink(unix_dg_tmp_socket);
    624 		exit(ret);
    625 
    626 	} else {
    627 		int i = 0;
    628 
    629 		/* Construct the portlist[] array. */
    630 		build_ports(uport);
    631 
    632 		/* Cycle through portlist, connecting to each port. */
    633 		for (s = -1, i = 0; portlist[i] != NULL; i++) {
    634 			if (s != -1)
    635 				close(s);
    636 
    637 			if (usetls) {
    638 				if ((tls_ctx = tls_client()) == NULL)
    639 					errx(1, "tls client creation failed");
    640 				if (tls_configure(tls_ctx, tls_cfg) == -1)
    641 					errx(1, "tls configuration failed (%s)",
    642 					    tls_error(tls_ctx));
    643 			}
    644 			if (xflag)
    645 				s = socks_connect(host, portlist[i], hints,
    646 				    proxy, proxyport, proxyhints, socksv,
    647 				    Pflag);
    648 			else
    649 				s = remote_connect(host, portlist[i], hints);
    650 
    651 			if (s == -1)
    652 				continue;
    653 
    654 			ret = 0;
    655 			if (vflag || zflag) {
    656 				/* For UDP, make sure we are connected. */
    657 				if (uflag) {
    658 					if (udptest(s) == -1) {
    659 						ret = 1;
    660 						continue;
    661 					}
    662 				}
    663 
    664 				/* Don't look up port if -n. */
    665 				if (nflag)
    666 					sv = NULL;
    667 				else {
    668 					sv = getservbyport(
    669 					    ntohs(atoi(portlist[i])),
    670 					    uflag ? "udp" : "tcp");
    671 				}
    672 
    673 				fprintf(stderr,
    674 				    "Connection to %s %s port [%s/%s] "
    675 				    "succeeded!\n", host, portlist[i],
    676 				    uflag ? "udp" : "tcp",
    677 				    sv ? sv->s_name : "*");
    678 			}
    679 			if (Fflag)
    680 				fdpass(s);
    681 			else {
    682 				if (usetls)
    683 					tls_setup_client(tls_ctx, s, host);
    684 				if (!zflag)
    685 					readwrite(s, tls_ctx);
    686 				if (tls_ctx) {
    687 					timeout_tls(s, tls_ctx, tls_close);
    688 					tls_free(tls_ctx);
    689 					tls_ctx = NULL;
    690 				}
    691 			}
    692 		}
    693 	}
    694 
    695 	if (s != -1)
    696 		close(s);
    697 
    698 	tls_config_free(tls_cfg);
    699 
    700 	exit(ret);
    701 }
    702 
    703 /*
    704  * unix_bind()
    705  * Returns a unix socket bound to the given path
    706  */
    707 int
    708 unix_bind(char *path, int flags)
    709 {
    710 	struct sockaddr_un s_un;
    711 	int s, save_errno;
    712 
    713 	/* Create unix domain socket. */
    714 	if ((s = socket(AF_UNIX, flags | (uflag ? SOCK_DGRAM : SOCK_STREAM),
    715 	    0)) < 0)
    716 		return (-1);
    717 
    718 	memset(&s_un, 0, sizeof(struct sockaddr_un));
    719 	s_un.sun_family = AF_UNIX;
    720 
    721 	if (strlcpy(s_un.sun_path, path, sizeof(s_un.sun_path)) >=
    722 	    sizeof(s_un.sun_path)) {
    723 		close(s);
    724 		errno = ENAMETOOLONG;
    725 		return (-1);
    726 	}
    727 
    728 	if (bind(s, (struct sockaddr *)&s_un, sizeof(s_un)) < 0) {
    729 		save_errno = errno;
    730 		close(s);
    731 		errno = save_errno;
    732 		return (-1);
    733 	}
    734 	return (s);
    735 }
    736 
    737 int
    738 timeout_tls(int s, struct tls *tls_ctx, int (*func)(struct tls *))
    739 {
    740 	struct pollfd pfd;
    741 	int ret;
    742 
    743 	while ((ret = (*func)(tls_ctx)) != 0) {
    744 		if (ret == TLS_WANT_POLLIN)
    745 			pfd.events = POLLIN;
    746 		else if (ret == TLS_WANT_POLLOUT)
    747 			pfd.events = POLLOUT;
    748 		else
    749 			break;
    750 		pfd.fd = s;
    751 		if ((ret = poll(&pfd, 1, timeout)) == 1)
    752 			continue;
    753 		else if (ret == 0) {
    754 			errno = ETIMEDOUT;
    755 			ret = -1;
    756 			break;
    757 		} else
    758 			err(1, "poll failed");
    759 	}
    760 
    761 	return (ret);
    762 }
    763 
    764 void
    765 tls_setup_client(struct tls *tls_ctx, int s, char *host)
    766 {
    767 	const char *errstr;
    768 
    769 	if (tls_connect_socket(tls_ctx, s,
    770 		tls_expectname ? tls_expectname : host) == -1) {
    771 		errx(1, "tls connection failed (%s)",
    772 		    tls_error(tls_ctx));
    773 	}
    774 	if (timeout_tls(s, tls_ctx, tls_handshake) == -1) {
    775 		if ((errstr = tls_error(tls_ctx)) == NULL)
    776 			errstr = strerror(errno);
    777 		errx(1, "tls handshake failed (%s)", errstr);
    778 	}
    779 	if (vflag)
    780 		report_tls(tls_ctx, host, tls_expectname);
    781 	if (tls_expecthash && tls_peer_cert_hash(tls_ctx) &&
    782 	    strcmp(tls_expecthash, tls_peer_cert_hash(tls_ctx)) != 0)
    783 		errx(1, "peer certificate is not %s", tls_expecthash);
    784 	if (Zflag) {
    785 		save_peer_cert(tls_ctx, Zflag);
    786 		if (Zflag != stderr && (fclose(Zflag) != 0))
    787 			err(1, "fclose failed saving peer cert");
    788 	}
    789 }
    790 
    791 struct tls *
    792 tls_setup_server(struct tls *tls_ctx, int connfd, char *host)
    793 {
    794 	struct tls *tls_cctx;
    795 	const char *errstr;
    796 
    797 	if (tls_accept_socket(tls_ctx, &tls_cctx, connfd) == -1) {
    798 		warnx("tls accept failed (%s)", tls_error(tls_ctx));
    799 	} else if (timeout_tls(connfd, tls_cctx, tls_handshake) == -1) {
    800 		if ((errstr = tls_error(tls_cctx)) == NULL)
    801 			errstr = strerror(errno);
    802 		warnx("tls handshake failed (%s)", errstr);
    803 	} else {
    804 		int gotcert = tls_peer_cert_provided(tls_cctx);
    805 
    806 		if (vflag && gotcert)
    807 			report_tls(tls_cctx, host, tls_expectname);
    808 		if ((TLSopt & TLS_CCERT) && !gotcert)
    809 			warnx("No client certificate provided");
    810 		else if (gotcert && tls_peer_cert_hash(tls_ctx) && tls_expecthash &&
    811 		    strcmp(tls_expecthash, tls_peer_cert_hash(tls_ctx)) != 0)
    812 			warnx("peer certificate is not %s", tls_expecthash);
    813 		else if (gotcert && tls_expectname &&
    814 		    (!tls_peer_cert_contains_name(tls_cctx, tls_expectname)))
    815 			warnx("name (%s) not found in client cert",
    816 			    tls_expectname);
    817 		else {
    818 			return tls_cctx;
    819 		}
    820 	}
    821 	return NULL;
    822 }
    823 
    824 /*
    825  * unix_connect()
    826  * Returns a socket connected to a local unix socket. Returns -1 on failure.
    827  */
    828 int
    829 unix_connect(char *path)
    830 {
    831 	struct sockaddr_un s_un;
    832 	int s, save_errno;
    833 
    834 	if (uflag) {
    835 		if ((s = unix_bind(unix_dg_tmp_socket, SOCK_CLOEXEC)) < 0)
    836 			return (-1);
    837 	} else {
    838 		if ((s = socket(AF_UNIX, SOCK_STREAM | SOCK_CLOEXEC, 0)) < 0)
    839 			return (-1);
    840 	}
    841 
    842 	memset(&s_un, 0, sizeof(struct sockaddr_un));
    843 	s_un.sun_family = AF_UNIX;
    844 
    845 	if (strlcpy(s_un.sun_path, path, sizeof(s_un.sun_path)) >=
    846 	    sizeof(s_un.sun_path)) {
    847 		close(s);
    848 		errno = ENAMETOOLONG;
    849 		return (-1);
    850 	}
    851 	if (connect(s, (struct sockaddr *)&s_un, sizeof(s_un)) < 0) {
    852 		save_errno = errno;
    853 		close(s);
    854 		errno = save_errno;
    855 		return (-1);
    856 	}
    857 	return (s);
    858 
    859 }
    860 
    861 /*
    862  * unix_listen()
    863  * Create a unix domain socket, and listen on it.
    864  */
    865 int
    866 unix_listen(char *path)
    867 {
    868 	int s;
    869 	if ((s = unix_bind(path, 0)) < 0)
    870 		return (-1);
    871 
    872 	if (listen(s, 5) < 0) {
    873 		close(s);
    874 		return (-1);
    875 	}
    876 	return (s);
    877 }
    878 
    879 /*
    880  * remote_connect()
    881  * Returns a socket connected to a remote host. Properly binds to a local
    882  * port or source address if needed. Returns -1 on failure.
    883  */
    884 int
    885 remote_connect(const char *host, const char *port, struct addrinfo hints)
    886 {
    887 	struct addrinfo *res, *res0;
    888 	int s = -1, error, on = 1, save_errno;
    889 
    890 	if ((error = getaddrinfo(host, port, &hints, &res0)))
    891 		errx(1, "getaddrinfo for host \"%s\" port %s: %s", host,
    892 		    port, gai_strerror(error));
    893 
    894 	for (res = res0; res; res = res->ai_next) {
    895 		if ((s = socket(res->ai_family, res->ai_socktype |
    896 		    SOCK_NONBLOCK, res->ai_protocol)) < 0)
    897 			continue;
    898 
    899 		/* Bind to a local port or source address if specified. */
    900 		if (sflag || pflag) {
    901 			struct addrinfo ahints, *ares;
    902 
    903 			/* try IP_TRANSPARENT, but don't insist */
    904 			setsockopt(s, SOL_IP, IP_TRANSPARENT, &on, sizeof(on));
    905 			memset(&ahints, 0, sizeof(struct addrinfo));
    906 			ahints.ai_family = res->ai_family;
    907 			ahints.ai_socktype = uflag ? SOCK_DGRAM : SOCK_STREAM;
    908 			ahints.ai_protocol = uflag ? IPPROTO_UDP : IPPROTO_TCP;
    909 			ahints.ai_flags = AI_PASSIVE;
    910 			if ((error = getaddrinfo(sflag, pflag, &ahints, &ares)))
    911 				errx(1, "getaddrinfo: %s", gai_strerror(error));
    912 
    913 			if (bind(s, (struct sockaddr *)ares->ai_addr,
    914 			    ares->ai_addrlen) < 0)
    915 				err(1, "bind failed");
    916 			freeaddrinfo(ares);
    917 		}
    918 
    919 		set_common_sockopts(s, res->ai_family);
    920 
    921 		if (timeout_connect(s, res->ai_addr, res->ai_addrlen) == 0)
    922 			break;
    923 		if (vflag)
    924 			warn("connect to %s port %s (%s) failed", host, port,
    925 			    uflag ? "udp" : "tcp");
    926 
    927 		save_errno = errno;
    928 		close(s);
    929 		errno = save_errno;
    930 		s = -1;
    931 	}
    932 
    933 	freeaddrinfo(res0);
    934 
    935 	return (s);
    936 }
    937 
    938 int
    939 timeout_connect(int s, const struct sockaddr *name, socklen_t namelen)
    940 {
    941 	struct pollfd pfd;
    942 	socklen_t optlen;
    943 	int optval;
    944 	int ret;
    945 
    946 	if ((ret = connect(s, name, namelen)) != 0 && errno == EINPROGRESS) {
    947 		pfd.fd = s;
    948 		pfd.events = POLLOUT;
    949 		if ((ret = poll(&pfd, 1, timeout)) == 1) {
    950 			optlen = sizeof(optval);
    951 			if ((ret = getsockopt(s, SOL_SOCKET, SO_ERROR,
    952 			    &optval, &optlen)) == 0) {
    953 				errno = optval;
    954 				ret = optval == 0 ? 0 : -1;
    955 			}
    956 		} else if (ret == 0) {
    957 			errno = ETIMEDOUT;
    958 			ret = -1;
    959 		} else
    960 			err(1, "poll failed");
    961 	}
    962 
    963 	return (ret);
    964 }
    965 
    966 /*
    967  * local_listen()
    968  * Returns a socket listening on a local port, binds to specified source
    969  * address. Returns -1 on failure.
    970  */
    971 int
    972 local_listen(char *host, char *port, struct addrinfo hints)
    973 {
    974 	struct addrinfo *res, *res0;
    975 	int s = -1, ret, x = 1, save_errno;
    976 	int error;
    977 
    978 	/* Allow nodename to be null. */
    979 	hints.ai_flags |= AI_PASSIVE;
    980 
    981 	/*
    982 	 * In the case of binding to a wildcard address
    983 	 * default to binding to an ipv4 address.
    984 	 */
    985 	if (host == NULL && hints.ai_family == AF_UNSPEC)
    986 		hints.ai_family = AF_INET;
    987 
    988 	if ((error = getaddrinfo(host, port, &hints, &res0)))
    989 		errx(1, "getaddrinfo: %s", gai_strerror(error));
    990 
    991 	for (res = res0; res; res = res->ai_next) {
    992 		if ((s = socket(res->ai_family, res->ai_socktype,
    993 		    res->ai_protocol)) < 0)
    994 			continue;
    995 
    996 		ret = setsockopt(s, SOL_SOCKET, SO_REUSEPORT, &x, sizeof(x));
    997 		if (ret == -1)
    998 			err(1, NULL);
    999 
   1000 		set_common_sockopts(s, res->ai_family);
   1001 
   1002 		if (bind(s, (struct sockaddr *)res->ai_addr,
   1003 		    res->ai_addrlen) == 0)
   1004 			break;
   1005 
   1006 		save_errno = errno;
   1007 		close(s);
   1008 		errno = save_errno;
   1009 		s = -1;
   1010 	}
   1011 
   1012 	if (!uflag && s != -1) {
   1013 		if (listen(s, 1) < 0)
   1014 			err(1, "listen");
   1015 	}
   1016 
   1017 	freeaddrinfo(res0);
   1018 
   1019 	return (s);
   1020 }
   1021 
   1022 /*
   1023  * readwrite()
   1024  * Loop that polls on the network file descriptor and stdin.
   1025  */
   1026 void
   1027 readwrite(int net_fd, struct tls *tls_ctx)
   1028 {
   1029 	struct pollfd pfd[4];
   1030 	int stdin_fd = STDIN_FILENO;
   1031 	int stdout_fd = STDOUT_FILENO;
   1032 	unsigned char netinbuf[BUFSIZE];
   1033 	size_t netinbufpos = 0;
   1034 	unsigned char stdinbuf[BUFSIZE];
   1035 	size_t stdinbufpos = 0;
   1036 	int n, num_fds;
   1037 	ssize_t ret;
   1038 
   1039 	/* don't read from stdin if requested */
   1040 	if (dflag)
   1041 		stdin_fd = -1;
   1042 
   1043 	/* stdin */
   1044 	pfd[POLL_STDIN].fd = stdin_fd;
   1045 	pfd[POLL_STDIN].events = POLLIN;
   1046 
   1047 	/* network out */
   1048 	pfd[POLL_NETOUT].fd = net_fd;
   1049 	pfd[POLL_NETOUT].events = 0;
   1050 
   1051 	/* network in */
   1052 	pfd[POLL_NETIN].fd = net_fd;
   1053 	pfd[POLL_NETIN].events = POLLIN;
   1054 
   1055 	/* stdout */
   1056 	pfd[POLL_STDOUT].fd = stdout_fd;
   1057 	pfd[POLL_STDOUT].events = 0;
   1058 
   1059 	while (1) {
   1060 		/* both inputs are gone, buffers are empty, we are done */
   1061 		if (pfd[POLL_STDIN].fd == -1 && pfd[POLL_NETIN].fd == -1 &&
   1062 		    stdinbufpos == 0 && netinbufpos == 0)
   1063 			return;
   1064 		/* both outputs are gone, we can't continue */
   1065 		if (pfd[POLL_NETOUT].fd == -1 && pfd[POLL_STDOUT].fd == -1)
   1066 			return;
   1067 		/* listen and net in gone, queues empty, done */
   1068 		if (lflag && pfd[POLL_NETIN].fd == -1 &&
   1069 		    stdinbufpos == 0 && netinbufpos == 0)
   1070 			return;
   1071 
   1072 		/* help says -i is for "wait between lines sent". We read and
   1073 		 * write arbitrary amounts of data, and we don't want to start
   1074 		 * scanning for newlines, so this is as good as it gets */
   1075 		if (iflag)
   1076 			sleep(iflag);
   1077 
   1078 		/* poll */
   1079 		num_fds = poll(pfd, 4, timeout);
   1080 
   1081 		/* treat poll errors */
   1082 		if (num_fds == -1)
   1083 			err(1, "polling error");
   1084 
   1085 		/* timeout happened */
   1086 		if (num_fds == 0)
   1087 			return;
   1088 
   1089 		/* treat socket error conditions */
   1090 		for (n = 0; n < 4; n++) {
   1091 			if (pfd[n].revents & (POLLERR|POLLNVAL)) {
   1092 				pfd[n].fd = -1;
   1093 			}
   1094 		}
   1095 		/* reading is possible after HUP */
   1096 		if (pfd[POLL_STDIN].events & POLLIN &&
   1097 		    pfd[POLL_STDIN].revents & POLLHUP &&
   1098 		    !(pfd[POLL_STDIN].revents & POLLIN))
   1099 			pfd[POLL_STDIN].fd = -1;
   1100 
   1101 		if (pfd[POLL_NETIN].events & POLLIN &&
   1102 		    pfd[POLL_NETIN].revents & POLLHUP &&
   1103 		    !(pfd[POLL_NETIN].revents & POLLIN))
   1104 			pfd[POLL_NETIN].fd = -1;
   1105 
   1106 		if (pfd[POLL_NETOUT].revents & POLLHUP) {
   1107 			if (Nflag)
   1108 				shutdown(pfd[POLL_NETOUT].fd, SHUT_WR);
   1109 			pfd[POLL_NETOUT].fd = -1;
   1110 		}
   1111 		/* if HUP, stop watching stdout */
   1112 		if (pfd[POLL_STDOUT].revents & POLLHUP)
   1113 			pfd[POLL_STDOUT].fd = -1;
   1114 		/* if no net out, stop watching stdin */
   1115 		if (pfd[POLL_NETOUT].fd == -1)
   1116 			pfd[POLL_STDIN].fd = -1;
   1117 		/* if no stdout, stop watching net in */
   1118 		if (pfd[POLL_STDOUT].fd == -1) {
   1119 			if (pfd[POLL_NETIN].fd != -1)
   1120 				shutdown(pfd[POLL_NETIN].fd, SHUT_RD);
   1121 			pfd[POLL_NETIN].fd = -1;
   1122 		}
   1123 
   1124 		/* try to read from stdin */
   1125 		if (pfd[POLL_STDIN].revents & POLLIN && stdinbufpos < BUFSIZE) {
   1126 			ret = fillbuf(pfd[POLL_STDIN].fd, stdinbuf,
   1127 			    &stdinbufpos, NULL);
   1128 			if (ret == TLS_WANT_POLLIN)
   1129 				pfd[POLL_STDIN].events = POLLIN;
   1130 			else if (ret == TLS_WANT_POLLOUT)
   1131 				pfd[POLL_STDIN].events = POLLOUT;
   1132 			else if (ret == 0 || ret == -1)
   1133 				pfd[POLL_STDIN].fd = -1;
   1134 			/* read something - poll net out */
   1135 			if (stdinbufpos > 0)
   1136 				pfd[POLL_NETOUT].events = POLLOUT;
   1137 			/* filled buffer - remove self from polling */
   1138 			if (stdinbufpos == BUFSIZE)
   1139 				pfd[POLL_STDIN].events = 0;
   1140 		}
   1141 		/* try to write to network */
   1142 		if (pfd[POLL_NETOUT].revents & POLLOUT && stdinbufpos > 0) {
   1143 			ret = drainbuf(pfd[POLL_NETOUT].fd, stdinbuf,
   1144 			    &stdinbufpos, tls_ctx);
   1145 			if (ret == TLS_WANT_POLLIN)
   1146 				pfd[POLL_NETOUT].events = POLLIN;
   1147 			else if (ret == TLS_WANT_POLLOUT)
   1148 				pfd[POLL_NETOUT].events = POLLOUT;
   1149 			else if (ret == -1)
   1150 				pfd[POLL_NETOUT].fd = -1;
   1151 			/* buffer empty - remove self from polling */
   1152 			if (stdinbufpos == 0)
   1153 				pfd[POLL_NETOUT].events = 0;
   1154 			/* buffer no longer full - poll stdin again */
   1155 			if (stdinbufpos < BUFSIZE)
   1156 				pfd[POLL_STDIN].events = POLLIN;
   1157 		}
   1158 		/* try to read from network */
   1159 		if (pfd[POLL_NETIN].revents & POLLIN && netinbufpos < BUFSIZE) {
   1160 			ret = fillbuf(pfd[POLL_NETIN].fd, netinbuf,
   1161 			    &netinbufpos, tls_ctx);
   1162 			if (ret == TLS_WANT_POLLIN)
   1163 				pfd[POLL_NETIN].events = POLLIN;
   1164 			else if (ret == TLS_WANT_POLLOUT)
   1165 				pfd[POLL_NETIN].events = POLLOUT;
   1166 			else if (ret == -1)
   1167 				pfd[POLL_NETIN].fd = -1;
   1168 			/* eof on net in - remove from pfd */
   1169 			if (ret == 0) {
   1170 				shutdown(pfd[POLL_NETIN].fd, SHUT_RD);
   1171 				pfd[POLL_NETIN].fd = -1;
   1172 			}
   1173 			/* read something - poll stdout */
   1174 			if (netinbufpos > 0)
   1175 				pfd[POLL_STDOUT].events = POLLOUT;
   1176 			/* filled buffer - remove self from polling */
   1177 			if (netinbufpos == BUFSIZE)
   1178 				pfd[POLL_NETIN].events = 0;
   1179 			/* handle telnet */
   1180 			if (tflag)
   1181 				atelnet(pfd[POLL_NETIN].fd, netinbuf,
   1182 				    netinbufpos);
   1183 		}
   1184 		/* try to write to stdout */
   1185 		if (pfd[POLL_STDOUT].revents & POLLOUT && netinbufpos > 0) {
   1186 			ret = drainbuf(pfd[POLL_STDOUT].fd, netinbuf,
   1187 			    &netinbufpos, NULL);
   1188 			if (ret == TLS_WANT_POLLIN)
   1189 				pfd[POLL_STDOUT].events = POLLIN;
   1190 			else if (ret == TLS_WANT_POLLOUT)
   1191 				pfd[POLL_STDOUT].events = POLLOUT;
   1192 			else if (ret == -1)
   1193 				pfd[POLL_STDOUT].fd = -1;
   1194 			/* buffer empty - remove self from polling */
   1195 			if (netinbufpos == 0)
   1196 				pfd[POLL_STDOUT].events = 0;
   1197 			/* buffer no longer full - poll net in again */
   1198 			if (netinbufpos < BUFSIZE)
   1199 				pfd[POLL_NETIN].events = POLLIN;
   1200 		}
   1201 
   1202 		/* stdin gone and queue empty? */
   1203 		if (pfd[POLL_STDIN].fd == -1 && stdinbufpos == 0) {
   1204 			if (pfd[POLL_NETOUT].fd != -1 && Nflag)
   1205 				shutdown(pfd[POLL_NETOUT].fd, SHUT_WR);
   1206 			pfd[POLL_NETOUT].fd = -1;
   1207 		}
   1208 		/* net in gone and queue empty? */
   1209 		if (pfd[POLL_NETIN].fd == -1 && netinbufpos == 0) {
   1210 			pfd[POLL_STDOUT].fd = -1;
   1211 		}
   1212 	}
   1213 }
   1214 
   1215 ssize_t
   1216 drainbuf(int fd, unsigned char *buf, size_t *bufpos, struct tls *tls)
   1217 {
   1218 	ssize_t n;
   1219 	ssize_t adjust;
   1220 
   1221 	if (tls)
   1222 		n = tls_write(tls, buf, *bufpos);
   1223 	else {
   1224 		n = write(fd, buf, *bufpos);
   1225 		/* don't treat EAGAIN, EINTR as error */
   1226 		if (n == -1 && (errno == EAGAIN || errno == EINTR))
   1227 			n = TLS_WANT_POLLOUT;
   1228 	}
   1229 	if (n <= 0)
   1230 		return n;
   1231 	/* adjust buffer */
   1232 	adjust = *bufpos - n;
   1233 	if (adjust > 0)
   1234 		memmove(buf, buf + n, adjust);
   1235 	*bufpos -= n;
   1236 	return n;
   1237 }
   1238 
   1239 ssize_t
   1240 fillbuf(int fd, unsigned char *buf, size_t *bufpos, struct tls *tls)
   1241 {
   1242 	size_t num = BUFSIZE - *bufpos;
   1243 	ssize_t n;
   1244 
   1245 	if (tls)
   1246 		n = tls_read(tls, buf + *bufpos, num);
   1247 	else {
   1248 		n = read(fd, buf + *bufpos, num);
   1249 		/* don't treat EAGAIN, EINTR as error */
   1250 		if (n == -1 && (errno == EAGAIN || errno == EINTR))
   1251 			n = TLS_WANT_POLLIN;
   1252 	}
   1253 	if (n <= 0)
   1254 		return n;
   1255 	*bufpos += n;
   1256 	return n;
   1257 }
   1258 
   1259 /*
   1260  * fdpass()
   1261  * Pass the connected file descriptor to stdout and exit.
   1262  */
   1263 void
   1264 fdpass(int nfd)
   1265 {
   1266 	struct msghdr mh;
   1267 	union {
   1268 		struct cmsghdr hdr;
   1269 		char buf[CMSG_SPACE(sizeof(int))];
   1270 	} cmsgbuf;
   1271 	struct cmsghdr *cmsg;
   1272 	struct iovec iov;
   1273 	char c = '\0';
   1274 	ssize_t r;
   1275 	struct pollfd pfd;
   1276 
   1277 	/* Avoid obvious stupidity */
   1278 	if (isatty(STDOUT_FILENO))
   1279 		errx(1, "Cannot pass file descriptor to tty");
   1280 
   1281 	bzero(&mh, sizeof(mh));
   1282 	bzero(&cmsgbuf, sizeof(cmsgbuf));
   1283 	bzero(&iov, sizeof(iov));
   1284 
   1285 	mh.msg_control = (caddr_t)&cmsgbuf.buf;
   1286 	mh.msg_controllen = sizeof(cmsgbuf.buf);
   1287 	cmsg = CMSG_FIRSTHDR(&mh);
   1288 	cmsg->cmsg_len = CMSG_LEN(sizeof(int));
   1289 	cmsg->cmsg_level = SOL_SOCKET;
   1290 	cmsg->cmsg_type = SCM_RIGHTS;
   1291 	*(int *)CMSG_DATA(cmsg) = nfd;
   1292 
   1293 	iov.iov_base = &c;
   1294 	iov.iov_len = 1;
   1295 	mh.msg_iov = &iov;
   1296 	mh.msg_iovlen = 1;
   1297 
   1298 	bzero(&pfd, sizeof(pfd));
   1299 	pfd.fd = STDOUT_FILENO;
   1300 	pfd.events = POLLOUT;
   1301 	for (;;) {
   1302 		r = sendmsg(STDOUT_FILENO, &mh, 0);
   1303 		if (r == -1) {
   1304 			if (errno == EAGAIN || errno == EINTR) {
   1305 				if (poll(&pfd, 1, -1) == -1)
   1306 					err(1, "poll");
   1307 				continue;
   1308 			}
   1309 			err(1, "sendmsg");
   1310 		} else if (r != 1)
   1311 			errx(1, "sendmsg: unexpected return value %zd", r);
   1312 		else
   1313 			break;
   1314 	}
   1315 	exit(0);
   1316 }
   1317 
   1318 /* Deal with RFC 854 WILL/WONT DO/DONT negotiation. */
   1319 void
   1320 atelnet(int nfd, unsigned char *buf, unsigned int size)
   1321 {
   1322 	unsigned char *p, *end;
   1323 	unsigned char obuf[4];
   1324 
   1325 	if (size < 3)
   1326 		return;
   1327 	end = buf + size - 2;
   1328 
   1329 	for (p = buf; p < end; p++) {
   1330 		if (*p != IAC)
   1331 			continue;
   1332 
   1333 		obuf[0] = IAC;
   1334 		p++;
   1335 		if ((*p == WILL) || (*p == WONT))
   1336 			obuf[1] = DONT;
   1337 		else if ((*p == DO) || (*p == DONT))
   1338 			obuf[1] = WONT;
   1339 		else
   1340 			continue;
   1341 
   1342 		p++;
   1343 		obuf[2] = *p;
   1344 		if (atomicio(vwrite, nfd, obuf, 3) != 3)
   1345 			warn("Write Error!");
   1346 	}
   1347 }
   1348 
   1349 
   1350 int
   1351 strtoport(char *portstr, int udp)
   1352 {
   1353 	struct servent *entry;
   1354 	const char *errstr;
   1355 	char *proto;
   1356 	int port = -1;
   1357 
   1358 	proto = udp ? "udp" : "tcp";
   1359 
   1360 	port = strtonum(portstr, 1, PORT_MAX, &errstr);
   1361 	if (errstr == NULL)
   1362 		return port;
   1363 	if (errno != EINVAL)
   1364 		errx(1, "port number %s: %s", errstr, portstr);
   1365 	if ((entry = getservbyname(portstr, proto)) == NULL)
   1366 		errx(1, "service \"%s\" unknown", portstr);
   1367 	return ntohs(entry->s_port);
   1368 }
   1369 
   1370 /*
   1371  * build_ports()
   1372  * Build an array of ports in portlist[], listing each port
   1373  * that we should try to connect to.
   1374  */
   1375 void
   1376 build_ports(char *p)
   1377 {
   1378 	char *n;
   1379 	int hi, lo, cp;
   1380 	int x = 0;
   1381 
   1382 	if ((n = strchr(p, '-')) != NULL) {
   1383 		*n = '\0';
   1384 		n++;
   1385 
   1386 		/* Make sure the ports are in order: lowest->highest. */
   1387 		hi = strtoport(n, uflag);
   1388 		lo = strtoport(p, uflag);
   1389 		if (lo > hi) {
   1390 			cp = hi;
   1391 			hi = lo;
   1392 			lo = cp;
   1393 		}
   1394 
   1395 		/*
   1396 		 * Initialize portlist with a random permutation.  Based on
   1397 		 * Knuth, as in ip_randomid() in sys/netinet/ip_id.c.
   1398 		 */
   1399 		if (rflag) {
   1400 			for (x = 0; x <= hi - lo; x++) {
   1401 				cp = arc4random_uniform(x + 1);
   1402 				portlist[x] = portlist[cp];
   1403 				if (asprintf(&portlist[cp], "%d", x + lo) < 0)
   1404 					err(1, "asprintf");
   1405 			}
   1406 		} else { /* Load ports sequentially. */
   1407 			for (cp = lo; cp <= hi; cp++) {
   1408 				if (asprintf(&portlist[x], "%d", cp) < 0)
   1409 					err(1, "asprintf");
   1410 				x++;
   1411 			}
   1412 		}
   1413 	} else {
   1414 		char *tmp;
   1415 
   1416 		hi = strtoport(p, uflag);
   1417 		if (asprintf(&tmp, "%d", hi) != -1)
   1418 			portlist[0] = tmp;
   1419 		else
   1420 			err(1, NULL);
   1421 	}
   1422 }
   1423 
   1424 /*
   1425  * udptest()
   1426  * Do a few writes to see if the UDP port is there.
   1427  * Fails once PF state table is full.
   1428  */
   1429 int
   1430 udptest(int s)
   1431 {
   1432 	int i, ret;
   1433 
   1434 	for (i = 0; i <= 3; i++) {
   1435 		if (write(s, "X", 1) == 1)
   1436 			ret = 1;
   1437 		else
   1438 			ret = -1;
   1439 	}
   1440 	return (ret);
   1441 }
   1442 
   1443 void
   1444 set_common_sockopts(int s, int af)
   1445 {
   1446 	int x = 1;
   1447 
   1448 	if (Sflag) {
   1449 		if (setsockopt(s, IPPROTO_TCP, TCP_MD5SIG,
   1450 			&x, sizeof(x)) == -1)
   1451 			err(1, NULL);
   1452 	}
   1453 	if (Dflag) {
   1454 		if (setsockopt(s, SOL_SOCKET, SO_DEBUG,
   1455 			&x, sizeof(x)) == -1)
   1456 			err(1, NULL);
   1457 	}
   1458 	if (Tflag != -1) {
   1459 		if (af == AF_INET && setsockopt(s, IPPROTO_IP,
   1460 		    IP_TOS, &Tflag, sizeof(Tflag)) == -1)
   1461 			err(1, "set IP ToS");
   1462 
   1463 		else if (af == AF_INET6 && setsockopt(s, IPPROTO_IPV6,
   1464 		    IPV6_TCLASS, &Tflag, sizeof(Tflag)) == -1)
   1465 			err(1, "set IPv6 traffic class");
   1466 	}
   1467 	if (Iflag) {
   1468 		if (setsockopt(s, SOL_SOCKET, SO_RCVBUF,
   1469 		    &Iflag, sizeof(Iflag)) == -1)
   1470 			err(1, "set TCP receive buffer size");
   1471 	}
   1472 	if (Oflag) {
   1473 		if (setsockopt(s, SOL_SOCKET, SO_SNDBUF,
   1474 		    &Oflag, sizeof(Oflag)) == -1)
   1475 			err(1, "set TCP send buffer size");
   1476 	}
   1477 
   1478 	if (ttl != -1) {
   1479 		if (af == AF_INET && setsockopt(s, IPPROTO_IP,
   1480 		    IP_TTL, &ttl, sizeof(ttl)))
   1481 			err(1, "set IP TTL");
   1482 
   1483 		else if (af == AF_INET6 && setsockopt(s, IPPROTO_IPV6,
   1484 		    IPV6_UNICAST_HOPS, &ttl, sizeof(ttl)))
   1485 			err(1, "set IPv6 unicast hops");
   1486 	}
   1487 
   1488 	if (minttl != -1) {
   1489 		if (af == AF_INET && setsockopt(s, IPPROTO_IP,
   1490 		    IP_MINTTL, &minttl, sizeof(minttl)))
   1491 			err(1, "set IP min TTL");
   1492 
   1493 		else if (af == AF_INET6 && setsockopt(s, IPPROTO_IPV6,
   1494 		    IPV6_MINHOPCOUNT, &minttl, sizeof(minttl)))
   1495 			err(1, "set IPv6 min hop count");
   1496 	}
   1497 }
   1498 
   1499 int
   1500 map_tos(char *s, int *val)
   1501 {
   1502 #define IPTOS_DSCP_CS0 0x00
   1503 #define IPTOS_DSCP_CS1 0x20
   1504 #define IPTOS_DSCP_CS2 0x40
   1505 #define IPTOS_DSCP_CS3 0x60
   1506 #define IPTOS_DSCP_CS4 0x80
   1507 #define IPTOS_DSCP_CS5 0xa0
   1508 #define IPTOS_DSCP_CS6 0xc0
   1509 #define IPTOS_DSCP_CS7 0xe0
   1510 	/* DiffServ Codepoints and other TOS mappings */
   1511 	const struct toskeywords {
   1512 		const char	*keyword;
   1513 		int		 val;
   1514 	} *t, toskeywords[] = {
   1515 		{ "af11",		IPTOS_DSCP_AF11 },
   1516 		{ "af12",		IPTOS_DSCP_AF12 },
   1517 		{ "af13",		IPTOS_DSCP_AF13 },
   1518 		{ "af21",		IPTOS_DSCP_AF21 },
   1519 		{ "af22",		IPTOS_DSCP_AF22 },
   1520 		{ "af23",		IPTOS_DSCP_AF23 },
   1521 		{ "af31",		IPTOS_DSCP_AF31 },
   1522 		{ "af32",		IPTOS_DSCP_AF32 },
   1523 		{ "af33",		IPTOS_DSCP_AF33 },
   1524 		{ "af41",		IPTOS_DSCP_AF41 },
   1525 		{ "af42",		IPTOS_DSCP_AF42 },
   1526 		{ "af43",		IPTOS_DSCP_AF43 },
   1527 		{ "critical",		IPTOS_PREC_CRITIC_ECP },
   1528 		{ "cs0",		IPTOS_DSCP_CS0 },
   1529 		{ "cs1",		IPTOS_DSCP_CS1 },
   1530 		{ "cs2",		IPTOS_DSCP_CS2 },
   1531 		{ "cs3",		IPTOS_DSCP_CS3 },
   1532 		{ "cs4",		IPTOS_DSCP_CS4 },
   1533 		{ "cs5",		IPTOS_DSCP_CS5 },
   1534 		{ "cs6",		IPTOS_DSCP_CS6 },
   1535 		{ "cs7",		IPTOS_DSCP_CS7 },
   1536 		{ "ef",			IPTOS_DSCP_EF },
   1537 		{ "inetcontrol",	IPTOS_PREC_INTERNETCONTROL },
   1538 		{ "lowdelay",		IPTOS_LOWDELAY },
   1539 		{ "netcontrol",		IPTOS_PREC_NETCONTROL },
   1540 		{ "reliability",	IPTOS_RELIABILITY },
   1541 		{ "throughput",		IPTOS_THROUGHPUT },
   1542 		{ NULL,			-1 },
   1543 	};
   1544 
   1545 	for (t = toskeywords; t->keyword != NULL; t++) {
   1546 		if (strcmp(s, t->keyword) == 0) {
   1547 			*val = t->val;
   1548 			return (1);
   1549 		}
   1550 	}
   1551 
   1552 	return (0);
   1553 }
   1554 
   1555 int
   1556 map_tls(char *s, int *val)
   1557 {
   1558 	const struct tlskeywords {
   1559 		const char	*keyword;
   1560 		int		 val;
   1561 	} *t, tlskeywords[] = {
   1562 		{ "tlsall",		TLS_ALL },
   1563 		{ "noverify",		TLS_NOVERIFY },
   1564 		{ "noname",		TLS_NONAME },
   1565 		{ "clientcert",		TLS_CCERT},
   1566 		{ "muststaple",		TLS_MUSTSTAPLE},
   1567 		{ NULL,			-1 },
   1568 	};
   1569 
   1570 	for (t = tlskeywords; t->keyword != NULL; t++) {
   1571 		if (strcmp(s, t->keyword) == 0) {
   1572 			*val |= t->val;
   1573 			return (1);
   1574 		}
   1575 	}
   1576 	return (0);
   1577 }
   1578 
   1579 void
   1580 save_peer_cert(struct tls *tls_ctx, FILE *fp)
   1581 {
   1582 	/* currently unsupported on Linux */
   1583 #if 0
   1584 	const char *pem;
   1585 	size_t plen;
   1586 
   1587 	if ((pem = tls_peer_cert_chain_pem(tls_ctx, &plen)) == NULL)
   1588 		errx(1, "Can't get peer certificate");
   1589 	if (fprintf(fp, "%.*s", (int)plen, pem) < 0)
   1590 		err(1, "unable to save peer cert");
   1591 	if (fflush(fp) != 0)
   1592 		err(1, "unable to flush peer cert");
   1593 #endif
   1594 }
   1595 
   1596 void
   1597 report_tls(struct tls * tls_ctx, char * host, char *tls_expectname)
   1598 {
   1599 	time_t t;
   1600 	const char *ocsp_url;
   1601 
   1602 	fprintf(stderr, "TLS handshake negotiated %s/%s with host %s\n",
   1603 	    tls_conn_version(tls_ctx), tls_conn_cipher(tls_ctx), host);
   1604 	fprintf(stderr, "Peer name: %s\n",
   1605 	    tls_expectname ? tls_expectname : host);
   1606 	if (tls_peer_cert_subject(tls_ctx))
   1607 		fprintf(stderr, "Subject: %s\n",
   1608 		    tls_peer_cert_subject(tls_ctx));
   1609 	if (tls_peer_cert_issuer(tls_ctx))
   1610 		fprintf(stderr, "Issuer: %s\n",
   1611 		    tls_peer_cert_issuer(tls_ctx));
   1612 	if ((t = tls_peer_cert_notbefore(tls_ctx)) != -1)
   1613 		fprintf(stderr, "Valid From: %s", ctime(&t));
   1614 	if ((t = tls_peer_cert_notafter(tls_ctx)) != -1)
   1615 		fprintf(stderr, "Valid Until: %s", ctime(&t));
   1616 	if (tls_peer_cert_hash(tls_ctx))
   1617 		fprintf(stderr, "Cert Hash: %s\n",
   1618 		    tls_peer_cert_hash(tls_ctx));
   1619 	ocsp_url = tls_peer_ocsp_url(tls_ctx);
   1620 	if (ocsp_url != NULL)
   1621 		fprintf(stderr, "OCSP URL: %s\n", ocsp_url);
   1622 	switch (tls_peer_ocsp_response_status(tls_ctx)) {
   1623 	case TLS_OCSP_RESPONSE_SUCCESSFUL:
   1624 		fprintf(stderr, "OCSP Stapling: %s\n",
   1625 		    tls_peer_ocsp_result(tls_ctx) == NULL ?  "" :
   1626 		    tls_peer_ocsp_result(tls_ctx));
   1627 		fprintf(stderr,
   1628 		    "  response_status=%d cert_status=%d crl_reason=%d\n",
   1629 		    tls_peer_ocsp_response_status(tls_ctx),
   1630 		    tls_peer_ocsp_cert_status(tls_ctx),
   1631 		    tls_peer_ocsp_crl_reason(tls_ctx));
   1632 		t = tls_peer_ocsp_this_update(tls_ctx);
   1633 		fprintf(stderr, "  this update: %s",
   1634 		    t != -1 ? ctime(&t) : "\n");
   1635 		t =  tls_peer_ocsp_next_update(tls_ctx);
   1636 		fprintf(stderr, "  next update: %s",
   1637 		    t != -1 ? ctime(&t) : "\n");
   1638 		t =  tls_peer_ocsp_revocation_time(tls_ctx);
   1639 		fprintf(stderr, "  revocation: %s",
   1640 		    t != -1 ? ctime(&t) : "\n");
   1641 		break;
   1642 	case -1:
   1643 		break;
   1644 	default:
   1645 		fprintf(stderr, "OCSP Stapling:  failure - response_status %d (%s)\n",
   1646 		    tls_peer_ocsp_response_status(tls_ctx),
   1647 		    tls_peer_ocsp_result(tls_ctx) == NULL ?  "" :
   1648 		    tls_peer_ocsp_result(tls_ctx));
   1649 		break;
   1650 
   1651 	}
   1652 }
   1653 
   1654 void
   1655 report_connect(const struct sockaddr *sa, socklen_t salen, char *path)
   1656 {
   1657 	char remote_host[NI_MAXHOST];
   1658 	char remote_port[NI_MAXSERV];
   1659 	int herr;
   1660 	int flags = NI_NUMERICSERV;
   1661 
   1662 	if (path != NULL) {
   1663 		fprintf(stderr, "Connection on %s received!\n", path);
   1664 		return;
   1665 	}
   1666 
   1667 	if (nflag)
   1668 		flags |= NI_NUMERICHOST;
   1669 
   1670 	if ((herr = getnameinfo(sa, salen,
   1671 	    remote_host, sizeof(remote_host),
   1672 	    remote_port, sizeof(remote_port),
   1673 	    flags)) != 0) {
   1674 		if (herr == EAI_SYSTEM)
   1675 			err(1, "getnameinfo");
   1676 		else
   1677 			errx(1, "getnameinfo: %s", gai_strerror(herr));
   1678 	}
   1679 
   1680 	fprintf(stderr,
   1681 	    "Connection from %s %s "
   1682 	    "received!\n", remote_host, remote_port);
   1683 }
   1684 
   1685 void
   1686 help(void)
   1687 {
   1688 	usage(0);
   1689 	fprintf(stderr, "\tCommand Summary:\n\
   1690 	\t-4		Use IPv4\n\
   1691 	\t-6		Use IPv6\n\
   1692 	\t-C certfile	Public key file\n\
   1693 	\t-c		Use TLS\n\
   1694 	\t-D		Enable the debug socket option\n\
   1695 	\t-d		Detach from stdin\n\
   1696 	\t-e name\t	Required name in peer certificate\n\
   1697 	\t-F		Pass socket fd\n\
   1698 	\t-H hash\t	Hash string of peer certificate\n\
   1699 	\t-h		This help text\n\
   1700 	\t-I length	TCP receive buffer length\n\
   1701 	\t-i interval	Delay interval for lines sent, ports scanned\n\
   1702 	\t-K keyfile	Private key file\n\
   1703 	\t-k		Keep inbound sockets open for multiple connects\n\
   1704 	\t-l		Listen mode, for inbound connects\n\
   1705 	\t-M ttl		Outgoing TTL / Hop Limit\n\
   1706 	\t-m minttl	Minimum incoming TTL / Hop Limit\n\
   1707 	\t-N		Shutdown the network socket after EOF on stdin\n\
   1708 	\t-n		Suppress name/port resolutions\n\
   1709 	\t-O length	TCP send buffer length\n\
   1710 	\t-o staplefile	Staple file\n\
   1711 	\t-P proxyuser\tUsername for proxy authentication\n\
   1712 	\t-p port\t	Specify local port for remote connects\n\
   1713 	\t-R CAfile	CA bundle\n\
   1714 	\t-r		Randomize remote ports\n\
   1715 	\t-S		Enable the TCP MD5 signature option\n\
   1716 	\t-s source	Local source address\n\
   1717 	\t-T keyword	TOS value or TLS options\n\
   1718 	\t-t		Answer TELNET negotiation\n\
   1719 	\t-U		Use UNIX domain socket\n\
   1720 	\t-u		UDP mode\n\
   1721 	\t-V rtable	Specify alternate routing table\n\
   1722 	\t-v		Verbose\n\
   1723 	\t-w timeout	Timeout for connects and final net reads\n\
   1724 	\t-X proto	Proxy protocol: \"4\", \"5\" (SOCKS) or \"connect\"\n\
   1725 	\t-x addr[:port]\tSpecify proxy address and port\n\
   1726 	\t-Z		Peer certificate file\n\
   1727 	\t-z		Zero-I/O mode [used for scanning]\n\
   1728 	Port numbers can be individual or ranges: lo-hi [inclusive]\n");
   1729 	exit(1);
   1730 }
   1731 
   1732 void
   1733 usage(int ret)
   1734 {
   1735 	fprintf(stderr,
   1736 	    "usage: nc [-46cDdFhklNnrStUuvz] [-C certfile] [-e name] "
   1737 	    "[-H hash] [-I length]\n"
   1738 	    "\t  [-i interval] [-K keyfile] [-M ttl] [-m minttl] [-O length]\n"
   1739 	    "\t  [-o staplefile] [-P proxy_username] [-p source_port] "
   1740 	    "[-R CAfile]\n"
   1741 	    "\t  [-s source] [-T keyword] [-V rtable] [-w timeout] "
   1742 	    "[-X proxy_protocol]\n"
   1743 	    "\t  [-x proxy_address[:port]] [-Z peercertfile] "
   1744 	    "[destination] [port]\n");
   1745 	if (ret)
   1746 		exit(1);
   1747 }