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