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