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