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