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