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