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