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