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