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