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