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