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