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