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