xref: /freebsd/contrib/netcat/netcat.c (revision 19261079b74319502c6ffa1249920079f0f69a72)
1 /* $OpenBSD: netcat.c,v 1.130 2015/07/26 19:12:28 chl Exp $ */
2 /*
3  * Copyright (c) 2001 Eric Jackson <ericj@monkey.org>
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
8  *
9  * 1. Redistributions of source code must retain the above copyright
10  *   notice, this list of conditions and the following disclaimer.
11  * 2. Redistributions in binary form must reproduce the above copyright
12  *   notice, this list of conditions and the following disclaimer in the
13  *   documentation and/or other materials provided with the distribution.
14  * 3. The name of the author may not be used to endorse or promote products
15  *   derived from this software without specific prior written permission.
16  *
17  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
18  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
19  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
20  * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
21  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
22  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
23  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
24  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
25  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
26  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
27  *
28  * $FreeBSD$
29  */
30 
31 /*
32  * Re-written nc(1) for OpenBSD. Original implementation by
33  * *Hobbit* <hobbit@avian.org>.
34  */
35 
36 #include <errno.h>
37 #include <stdio.h>
38 #include <sys/arb.h>
39 #include <sys/limits.h>
40 #include <sys/types.h>
41 #include <sys/sbuf.h>
42 #include <sys/socket.h>
43 #include <sys/sysctl.h>
44 #include <sys/qmath.h>
45 #include <sys/stats.h>
46 #include <sys/time.h>
47 #include <sys/uio.h>
48 #include <sys/un.h>
49 
50 #include <netinet/in.h>
51 #ifdef IPSEC
52 #include <netipsec/ipsec.h>
53 #endif
54 #include <netinet/tcp.h>
55 #include <netinet/ip.h>
56 #include <arpa/telnet.h>
57 
58 #include <err.h>
59 #include <getopt.h>
60 #include <fcntl.h>
61 #include <limits.h>
62 #include <netdb.h>
63 #include <poll.h>
64 #include <signal.h>
65 #include <stdarg.h>
66 #include <stdlib.h>
67 #include <string.h>
68 #include <unistd.h>
69 #include "atomicio.h"
70 
71 #ifndef SUN_LEN
72 #define SUN_LEN(su) \
73 	(sizeof(*(su)) - sizeof((su)->sun_path) + strlen((su)->sun_path))
74 #endif
75 
76 #define PORT_MAX	65535
77 #define PORT_MAX_LEN	6
78 #define UNIX_DG_TMP_SOCKET_SIZE	19
79 
80 #define POLL_STDIN 0
81 #define POLL_NETOUT 1
82 #define POLL_NETIN 2
83 #define POLL_STDOUT 3
84 #define BUFSIZE 16384
85 
86 /* Command Line Options */
87 int	dflag;					/* detached, no stdin */
88 int	Fflag;					/* fdpass sock to stdout */
89 unsigned int iflag;				/* Interval Flag */
90 int	kflag;					/* More than one connect */
91 int	lflag;					/* Bind to local port */
92 int	FreeBSD_Mflag;				/* Measure using stats(3) */
93 int	Nflag;					/* shutdown() network socket */
94 int	nflag;					/* Don't do name look up */
95 int	FreeBSD_Oflag;				/* Do not use TCP options */
96 int	FreeBSD_sctp;				/* Use SCTP */
97 char   *Pflag;					/* Proxy username */
98 char   *pflag;					/* Localport flag */
99 int	rflag;					/* Random ports flag */
100 char   *sflag;					/* Source Address */
101 int	tflag;					/* Telnet Emulation */
102 int	uflag;					/* UDP - Default to TCP */
103 int	vflag;					/* Verbosity */
104 int	xflag;					/* Socks proxy */
105 int	zflag;					/* Port Scan Flag */
106 int	Dflag;					/* sodebug */
107 int	Iflag;					/* TCP receive buffer size */
108 int	Oflag;					/* TCP send buffer size */
109 int	Sflag;					/* TCP MD5 signature option */
110 int	Tflag = -1;				/* IP Type of Service */
111 int	rtableid = -1;
112 
113 int timeout = -1;
114 int family = AF_UNSPEC;
115 char *portlist[PORT_MAX+1];
116 char *unix_dg_tmp_socket;
117 
118 void	atelnet(int, unsigned char *, unsigned int);
119 void	build_ports(char *);
120 void	help(void);
121 int	local_listen(char *, char *, struct addrinfo);
122 void	readwrite(int);
123 void	fdpass(int nfd) __attribute__((noreturn));
124 int	remote_connect(const char *, const char *, struct addrinfo);
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 *);
130 int	unix_connect(char *);
131 int	unix_listen(char *);
132 void	FreeBSD_stats_setup(int);
133 void	FreeBSD_stats_print(int);
134 void	set_common_sockopts(int, int);
135 int	map_tos(char *, int *);
136 void	report_connect(const struct sockaddr *, socklen_t);
137 void	usage(int);
138 ssize_t drainbuf(int, unsigned char *, size_t *);
139 ssize_t fillbuf(int, unsigned char *, size_t *);
140 
141 #ifdef IPSEC
142 void	add_ipsec_policy(int, int, char *);
143 
144 char	*ipsec_policy[2];
145 #endif
146 
147 int
148 main(int argc, char *argv[])
149 {
150 	int ch, s, ret, socksv, ipsec_count;
151 	int numfibs;
152 	size_t intsize = sizeof(int);
153 	char *host, *uport;
154 	struct addrinfo hints;
155 	struct servent *sv;
156 	socklen_t len;
157 	struct sockaddr_storage cliaddr;
158 	char *proxy;
159 	const char *errstr, *proxyhost = "", *proxyport = NULL;
160 	struct addrinfo proxyhints;
161 	char unix_dg_tmp_socket_buf[UNIX_DG_TMP_SOCKET_SIZE];
162 	struct option longopts[] = {
163 		{ "no-tcpopt",	no_argument,	&FreeBSD_Oflag,	1 },
164 		{ "sctp",	no_argument,	&FreeBSD_sctp,	1 },
165 		{ NULL,		0,		NULL,		0 }
166 	};
167 
168 	ret = 1;
169 	ipsec_count = 0;
170 	s = 0;
171 	socksv = 5;
172 	host = NULL;
173 	uport = NULL;
174 	sv = NULL;
175 
176 	signal(SIGPIPE, SIG_IGN);
177 
178 	while ((ch = getopt_long(argc, argv,
179 	    "46DdEe:FhI:i:klMNnoO:P:p:rSs:tT:UuV:vw:X:x:z",
180 	    longopts, NULL)) != -1) {
181 		switch (ch) {
182 		case '4':
183 			family = AF_INET;
184 			break;
185 		case '6':
186 			family = AF_INET6;
187 			break;
188 		case 'U':
189 			family = AF_UNIX;
190 			break;
191 		case 'X':
192 			if (strcasecmp(optarg, "connect") == 0)
193 				socksv = -1; /* HTTP proxy CONNECT */
194 			else if (strcmp(optarg, "4") == 0)
195 				socksv = 4; /* SOCKS v.4 */
196 			else if (strcmp(optarg, "5") == 0)
197 				socksv = 5; /* SOCKS v.5 */
198 			else
199 				errx(1, "unsupported proxy protocol");
200 			break;
201 		case 'd':
202 			dflag = 1;
203 			break;
204 		case 'e':
205 #ifdef IPSEC
206 			ipsec_policy[ipsec_count++ % 2] = optarg;
207 #else
208 			errx(1, "IPsec support unavailable.");
209 #endif
210 			break;
211 		case 'E':
212 #ifdef IPSEC
213 			ipsec_policy[0] = "in  ipsec esp/transport//require";
214 			ipsec_policy[1] = "out ipsec esp/transport//require";
215 #else
216 			errx(1, "IPsec support unavailable.");
217 #endif
218 			break;
219 		case 'F':
220 			Fflag = 1;
221 			break;
222 		case 'h':
223 			help();
224 			break;
225 		case 'i':
226 			iflag = strtonum(optarg, 0, UINT_MAX, &errstr);
227 			if (errstr)
228 				errx(1, "interval %s: %s", errstr, optarg);
229 			break;
230 		case 'k':
231 			kflag = 1;
232 			break;
233 		case 'l':
234 			lflag = 1;
235 			break;
236 		case 'M':
237 #ifndef WITH_STATS
238 			errx(1, "-M requires stats(3) support");
239 #else
240 			FreeBSD_Mflag = 1;
241 #endif
242 			break;
243 		case 'N':
244 			Nflag = 1;
245 			break;
246 		case 'n':
247 			nflag = 1;
248 			break;
249 		case 'o':
250 			fprintf(stderr, "option -o is deprecated.\n");
251 			break;
252 		case 'P':
253 			Pflag = optarg;
254 			break;
255 		case 'p':
256 			pflag = optarg;
257 			break;
258 		case 'r':
259 			rflag = 1;
260 			break;
261 		case 's':
262 			sflag = optarg;
263 			break;
264 		case 't':
265 			tflag = 1;
266 			break;
267 		case 'u':
268 			uflag = 1;
269 			break;
270 		case 'V':
271 			if (sysctlbyname("net.fibs", &numfibs, &intsize, NULL, 0) == -1)
272 				errx(1, "Multiple FIBS not supported");
273 			rtableid = (int)strtonum(optarg, 0,
274 			    numfibs - 1, &errstr);
275 			if (errstr)
276 				errx(1, "rtable %s: %s", errstr, optarg);
277 			break;
278 		case 'v':
279 			vflag = 1;
280 			break;
281 		case 'w':
282 			timeout = strtonum(optarg, 0, INT_MAX / 1000, &errstr);
283 			if (errstr)
284 				errx(1, "timeout %s: %s", errstr, optarg);
285 			timeout *= 1000;
286 			break;
287 		case 'x':
288 			xflag = 1;
289 			if ((proxy = strdup(optarg)) == NULL)
290 				err(1, NULL);
291 			break;
292 		case 'z':
293 			zflag = 1;
294 			break;
295 		case 'D':
296 			Dflag = 1;
297 			break;
298 		case 'I':
299 			Iflag = strtonum(optarg, 1, 65536 << 14, &errstr);
300 			if (errstr != NULL)
301 				errx(1, "TCP receive window %s: %s",
302 				    errstr, optarg);
303 			break;
304 		case 'O':
305 			Oflag = strtonum(optarg, 1, 65536 << 14, &errstr);
306 			if (errstr != NULL) {
307 			    if (strcmp(errstr, "invalid") != 0)
308 				errx(1, "TCP send window %s: %s",
309 				    errstr, optarg);
310 			}
311 			break;
312 		case 'S':
313 			Sflag = 1;
314 			break;
315 		case 'T':
316 			errstr = NULL;
317 			errno = 0;
318 			if (map_tos(optarg, &Tflag))
319 				break;
320 			if (strlen(optarg) > 1 && optarg[0] == '0' &&
321 			    optarg[1] == 'x')
322 				Tflag = (int)strtol(optarg, NULL, 16);
323 			else
324 				Tflag = (int)strtonum(optarg, 0, 255,
325 				    &errstr);
326 			if (Tflag < 0 || Tflag > 255 || errstr || errno)
327 				errx(1, "illegal tos value %s", optarg);
328 			break;
329 		case 0:
330 			/* Long option. */
331 			break;
332 		default:
333 			usage(1);
334 		}
335 	}
336 	argc -= optind;
337 	argv += optind;
338 
339 	/* Cruft to make sure options are clean, and used properly. */
340 	if (argv[0] && !argv[1] && family == AF_UNIX) {
341 		host = argv[0];
342 		uport = NULL;
343 	} else if (argv[0] && !argv[1]) {
344 		if  (!lflag)
345 			usage(1);
346 		uport = argv[0];
347 		host = NULL;
348 	} else if (argv[0] && argv[1]) {
349 		host = argv[0];
350 		uport = argv[1];
351 	} else
352 		usage(1);
353 
354 	if (lflag && sflag)
355 		errx(1, "cannot use -s and -l");
356 	if (lflag && pflag)
357 		errx(1, "cannot use -p and -l");
358 	if (lflag && zflag)
359 		errx(1, "cannot use -z and -l");
360 	if (!lflag && kflag)
361 		errx(1, "must use -l with -k");
362 	if (FreeBSD_sctp) {
363 		if (uflag)
364 			errx(1, "cannot use -u and --sctp");
365 		if (family == AF_UNIX)
366 			errx(1, "cannot use -U and --sctp");
367 	}
368 
369 	/* Get name of temporary socket for unix datagram client */
370 	if ((family == AF_UNIX) && uflag && !lflag) {
371 		if (sflag) {
372 			unix_dg_tmp_socket = sflag;
373 		} else {
374 			strlcpy(unix_dg_tmp_socket_buf, "/tmp/nc.XXXXXXXXXX",
375 				UNIX_DG_TMP_SOCKET_SIZE);
376 			if (mktemp(unix_dg_tmp_socket_buf) == NULL)
377 				err(1, "mktemp");
378 			unix_dg_tmp_socket = unix_dg_tmp_socket_buf;
379 		}
380 	}
381 
382 	/* Initialize addrinfo structure. */
383 	if (family != AF_UNIX) {
384 		memset(&hints, 0, sizeof(struct addrinfo));
385 		hints.ai_family = family;
386 		hints.ai_socktype = uflag ? SOCK_DGRAM : SOCK_STREAM;
387 		hints.ai_protocol = uflag ? IPPROTO_UDP :
388 		    FreeBSD_sctp ? IPPROTO_SCTP : IPPROTO_TCP;
389 		if (nflag)
390 			hints.ai_flags |= AI_NUMERICHOST;
391 	}
392 
393 	if (xflag) {
394 		if (uflag)
395 			errx(1, "no proxy support for UDP mode");
396 
397 		if (FreeBSD_sctp)
398 			errx(1, "no proxy support for SCTP mode");
399 
400 		if (lflag)
401 			errx(1, "no proxy support for listen");
402 
403 		if (family == AF_UNIX)
404 			errx(1, "no proxy support for unix sockets");
405 
406 		/* XXX IPv6 transport to proxy would probably work */
407 		if (family == AF_INET6)
408 			errx(1, "no proxy support for IPv6");
409 
410 		if (sflag)
411 			errx(1, "no proxy support for local source address");
412 
413 		proxyhost = strsep(&proxy, ":");
414 		proxyport = proxy;
415 
416 		memset(&proxyhints, 0, sizeof(struct addrinfo));
417 		proxyhints.ai_family = family;
418 		proxyhints.ai_socktype = SOCK_STREAM;
419 		proxyhints.ai_protocol = IPPROTO_TCP;
420 		if (nflag)
421 			proxyhints.ai_flags |= AI_NUMERICHOST;
422 	}
423 
424 	if (lflag) {
425 		int connfd;
426 		ret = 0;
427 
428 		if (family == AF_UNIX) {
429 			if (uflag)
430 				s = unix_bind(host);
431 			else
432 				s = unix_listen(host);
433 		}
434 
435 		/* Allow only one connection at a time, but stay alive. */
436 		for (;;) {
437 			if (family != AF_UNIX)
438 				s = local_listen(host, uport, hints);
439 			if (s < 0)
440 				err(1, NULL);
441 			/*
442 			 * For UDP and -k, don't connect the socket, let it
443 			 * receive datagrams from multiple socket pairs.
444 			 */
445 			if (uflag && kflag)
446 				readwrite(s);
447 			/*
448 			 * For UDP and not -k, we will use recvfrom() initially
449 			 * to wait for a caller, then use the regular functions
450 			 * to talk to the caller.
451 			 */
452 			else if (uflag && !kflag) {
453 				int rv, plen;
454 				char buf[16384];
455 				struct sockaddr_storage z;
456 
457 				len = sizeof(z);
458 				plen = 2048;
459 				rv = recvfrom(s, buf, plen, MSG_PEEK,
460 				    (struct sockaddr *)&z, &len);
461 				if (rv < 0)
462 					err(1, "recvfrom");
463 
464 				rv = connect(s, (struct sockaddr *)&z, len);
465 				if (rv < 0)
466 					err(1, "connect");
467 
468 				if (vflag)
469 					report_connect((struct sockaddr *)&z, len);
470 
471 				readwrite(s);
472 			} else {
473 				len = sizeof(cliaddr);
474 				connfd = accept(s, (struct sockaddr *)&cliaddr,
475 				    &len);
476 				if (connfd == -1) {
477 					/* For now, all errnos are fatal */
478 					err(1, "accept");
479 				}
480 				if (vflag)
481 					report_connect((struct sockaddr *)&cliaddr, len);
482 
483 				if (FreeBSD_Mflag)
484 					FreeBSD_stats_setup(connfd);
485 				readwrite(connfd);
486 				close(connfd);
487 			}
488 
489 			if (family != AF_UNIX)
490 				close(s);
491 			else if (uflag) {
492 				if (connect(s, NULL, 0) < 0)
493 					err(1, "connect");
494 			}
495 
496 			if (!kflag)
497 				break;
498 		}
499 	} else if (family == AF_UNIX) {
500 		ret = 0;
501 
502 		if ((s = unix_connect(host)) > 0 && !zflag) {
503 			readwrite(s);
504 			close(s);
505 		} else
506 			ret = 1;
507 
508 		if (uflag)
509 			unlink(unix_dg_tmp_socket);
510 		exit(ret);
511 
512 	} else {
513 		int i = 0;
514 
515 		/* Construct the portlist[] array. */
516 		build_ports(uport);
517 
518 		/* Cycle through portlist, connecting to each port. */
519 		for (i = 0; portlist[i] != NULL; i++) {
520 			if (s)
521 				close(s);
522 
523 			if (xflag)
524 				s = socks_connect(host, portlist[i], hints,
525 				    proxyhost, proxyport, proxyhints, socksv,
526 				    Pflag);
527 			else
528 				s = remote_connect(host, portlist[i], hints);
529 
530 			if (s < 0)
531 				continue;
532 
533 			ret = 0;
534 			if (vflag || zflag) {
535 				/* For UDP, make sure we are connected. */
536 				if (uflag) {
537 					if (udptest(s) == -1) {
538 						ret = 1;
539 						continue;
540 					}
541 				}
542 
543 				/* Don't look up port if -n. */
544 				if (nflag)
545 					sv = NULL;
546 				else {
547 					sv = getservbyport(
548 					    ntohs(atoi(portlist[i])),
549 					    uflag ? "udp" : "tcp");
550 				}
551 
552 				fprintf(stderr,
553 				    "Connection to %s %s port [%s/%s] "
554 				    "succeeded!\n", host, portlist[i],
555 				    uflag ? "udp" : "tcp",
556 				    sv ? sv->s_name : "*");
557 			}
558 			if (Fflag)
559 				fdpass(s);
560 			else if (!zflag)
561 				readwrite(s);
562 		}
563 	}
564 
565 	if (s)
566 		close(s);
567 
568 	exit(ret);
569 }
570 
571 /*
572  * unix_bind()
573  * Returns a unix socket bound to the given path
574  */
575 int
576 unix_bind(char *path)
577 {
578 	struct sockaddr_un sun;
579 	int s;
580 
581 	/* Create unix domain socket. */
582 	if ((s = socket(AF_UNIX, uflag ? SOCK_DGRAM : SOCK_STREAM,
583 	     0)) < 0)
584 		return (-1);
585 
586 	memset(&sun, 0, sizeof(struct sockaddr_un));
587 	sun.sun_family = AF_UNIX;
588 
589 	if (strlcpy(sun.sun_path, path, sizeof(sun.sun_path)) >=
590 	    sizeof(sun.sun_path)) {
591 		close(s);
592 		errno = ENAMETOOLONG;
593 		return (-1);
594 	}
595 
596 	if (bind(s, (struct sockaddr *)&sun, SUN_LEN(&sun)) < 0) {
597 		close(s);
598 		return (-1);
599 	}
600 	return (s);
601 }
602 
603 /*
604  * unix_connect()
605  * Returns a socket connected to a local unix socket. Returns -1 on failure.
606  */
607 int
608 unix_connect(char *path)
609 {
610 	struct sockaddr_un sun;
611 	int s;
612 
613 	if (uflag) {
614 		if ((s = unix_bind(unix_dg_tmp_socket)) < 0)
615 			return (-1);
616 	} else {
617 		if ((s = socket(AF_UNIX, SOCK_STREAM, 0)) < 0)
618 			return (-1);
619 	}
620 	(void)fcntl(s, F_SETFD, FD_CLOEXEC);
621 
622 	memset(&sun, 0, sizeof(struct sockaddr_un));
623 	sun.sun_family = AF_UNIX;
624 
625 	if (strlcpy(sun.sun_path, path, sizeof(sun.sun_path)) >=
626 	    sizeof(sun.sun_path)) {
627 		close(s);
628 		errno = ENAMETOOLONG;
629 		return (-1);
630 	}
631 	if (connect(s, (struct sockaddr *)&sun, SUN_LEN(&sun)) < 0) {
632 		close(s);
633 		return (-1);
634 	}
635 	return (s);
636 
637 }
638 
639 /*
640  * unix_listen()
641  * Create a unix domain socket, and listen on it.
642  */
643 int
644 unix_listen(char *path)
645 {
646 	int s;
647 	if ((s = unix_bind(path)) < 0)
648 		return (-1);
649 
650 	if (listen(s, 5) < 0) {
651 		close(s);
652 		return (-1);
653 	}
654 	return (s);
655 }
656 
657 /*
658  * remote_connect()
659  * Returns a socket connected to a remote host. Properly binds to a local
660  * port or source address if needed. Returns -1 on failure.
661  */
662 int
663 remote_connect(const char *host, const char *port, struct addrinfo hints)
664 {
665 	struct addrinfo *res, *res0;
666 	int s, error, on = 1;
667 
668 	if ((error = getaddrinfo(host, port, &hints, &res)))
669 		errx(1, "getaddrinfo: %s", gai_strerror(error));
670 
671 	res0 = res;
672 	do {
673 		if ((s = socket(res0->ai_family, res0->ai_socktype,
674 		    res0->ai_protocol)) < 0)
675 			continue;
676 
677 		if (rtableid >= 0 && (setsockopt(s, SOL_SOCKET, SO_SETFIB,
678 		    &rtableid, sizeof(rtableid)) == -1))
679 			err(1, "setsockopt SO_SETFIB");
680 
681 		/* Bind to a local port or source address if specified. */
682 		if (sflag || pflag) {
683 			struct addrinfo ahints, *ares;
684 
685 			/* try IP_BINDANY, but don't insist */
686 			setsockopt(s, IPPROTO_IP, IP_BINDANY, &on, sizeof(on));
687 			memset(&ahints, 0, sizeof(struct addrinfo));
688 			ahints.ai_family = res0->ai_family;
689 			ahints.ai_socktype = uflag ? SOCK_DGRAM : SOCK_STREAM;
690 			ahints.ai_protocol = uflag ? IPPROTO_UDP : IPPROTO_TCP;
691 			ahints.ai_flags = AI_PASSIVE;
692 			if ((error = getaddrinfo(sflag, pflag, &ahints, &ares)))
693 				errx(1, "getaddrinfo: %s", gai_strerror(error));
694 
695 			if (bind(s, (struct sockaddr *)ares->ai_addr,
696 			    ares->ai_addrlen) < 0)
697 				err(1, "bind failed");
698 			freeaddrinfo(ares);
699 		}
700 
701 		set_common_sockopts(s, res0->ai_family);
702 
703 		if (timeout_connect(s, res0->ai_addr, res0->ai_addrlen) == 0)
704 			break;
705 		else if (vflag)
706 			warn("connect to %s port %s (%s) failed", host, port,
707 			    uflag ? "udp" : "tcp");
708 
709 		close(s);
710 		s = -1;
711 	} while ((res0 = res0->ai_next) != NULL);
712 
713 	freeaddrinfo(res);
714 
715 	return (s);
716 }
717 
718 int
719 timeout_connect(int s, const struct sockaddr *name, socklen_t namelen)
720 {
721 	struct pollfd pfd;
722 	socklen_t optlen;
723 	int flags, optval;
724 	int ret;
725 
726 	if (timeout != -1) {
727 		flags = fcntl(s, F_GETFL, 0);
728 		if (fcntl(s, F_SETFL, flags | O_NONBLOCK) == -1)
729 			err(1, "set non-blocking mode");
730 	}
731 
732 	if ((ret = connect(s, name, namelen)) != 0 && errno == EINPROGRESS) {
733 		pfd.fd = s;
734 		pfd.events = POLLOUT;
735 		if ((ret = poll(&pfd, 1, timeout)) == 1) {
736 			optlen = sizeof(optval);
737 			if ((ret = getsockopt(s, SOL_SOCKET, SO_ERROR,
738 			    &optval, &optlen)) == 0) {
739 				errno = optval;
740 				ret = optval == 0 ? 0 : -1;
741 			}
742 		} else if (ret == 0) {
743 			errno = ETIMEDOUT;
744 			ret = -1;
745 		} else
746 			err(1, "poll failed");
747 	}
748 
749 	if (timeout != -1 && fcntl(s, F_SETFL, flags) == -1)
750 		err(1, "restoring flags");
751 
752 	return (ret);
753 }
754 
755 /*
756  * local_listen()
757  * Returns a socket listening on a local port, binds to specified source
758  * address. Returns -1 on failure.
759  */
760 int
761 local_listen(char *host, char *port, struct addrinfo hints)
762 {
763 	struct addrinfo *res, *res0;
764 	int s, ret, x = 1;
765 	int error;
766 
767 	/* Allow nodename to be null. */
768 	hints.ai_flags |= AI_PASSIVE;
769 
770 	/*
771 	 * In the case of binding to a wildcard address
772 	 * default to binding to an ipv4 address.
773 	 */
774 	if (host == NULL && hints.ai_family == AF_UNSPEC)
775 		hints.ai_family = AF_INET;
776 
777 	if ((error = getaddrinfo(host, port, &hints, &res)))
778 		errx(1, "getaddrinfo: %s", gai_strerror(error));
779 
780 	res0 = res;
781 	do {
782 		if ((s = socket(res0->ai_family, res0->ai_socktype,
783 		    res0->ai_protocol)) < 0)
784 			continue;
785 
786 		if (rtableid >= 0 && (setsockopt(s, SOL_SOCKET, SO_SETFIB,
787 		    &rtableid, sizeof(rtableid)) == -1))
788 			err(1, "setsockopt SO_SETFIB");
789 
790 		ret = setsockopt(s, SOL_SOCKET, SO_REUSEPORT, &x, sizeof(x));
791 		if (ret == -1)
792 			err(1, NULL);
793 
794 		if (FreeBSD_Oflag) {
795 			if (setsockopt(s, IPPROTO_TCP, TCP_NOOPT,
796 			    &FreeBSD_Oflag, sizeof(FreeBSD_Oflag)) == -1)
797 				err(1, "disable TCP options");
798 		}
799 
800 		set_common_sockopts(s, res0->ai_family);
801 
802 		if (bind(s, (struct sockaddr *)res0->ai_addr,
803 		    res0->ai_addrlen) == 0)
804 			break;
805 
806 		close(s);
807 		s = -1;
808 	} while ((res0 = res0->ai_next) != NULL);
809 
810 	if (!uflag && s != -1) {
811 		if (listen(s, 1) < 0)
812 			err(1, "listen");
813 	}
814 
815 	freeaddrinfo(res);
816 
817 	return (s);
818 }
819 
820 /*
821  * readwrite()
822  * Loop that polls on the network file descriptor and stdin.
823  */
824 void
825 readwrite(int net_fd)
826 {
827 	struct pollfd pfd[4];
828 	int stdin_fd = STDIN_FILENO;
829 	int stdout_fd = STDOUT_FILENO;
830 	unsigned char netinbuf[BUFSIZE];
831 	size_t netinbufpos = 0;
832 	unsigned char stdinbuf[BUFSIZE];
833 	size_t stdinbufpos = 0;
834 	int n, num_fds;
835 	int stats_printed = 0;
836 	ssize_t ret;
837 
838 	/* don't read from stdin if requested */
839 	if (dflag)
840 		stdin_fd = -1;
841 
842 	/* stdin */
843 	pfd[POLL_STDIN].fd = stdin_fd;
844 	pfd[POLL_STDIN].events = POLLIN;
845 
846 	/* network out */
847 	pfd[POLL_NETOUT].fd = net_fd;
848 	pfd[POLL_NETOUT].events = 0;
849 
850 	/* network in */
851 	pfd[POLL_NETIN].fd = net_fd;
852 	pfd[POLL_NETIN].events = POLLIN;
853 
854 	/* stdout */
855 	pfd[POLL_STDOUT].fd = stdout_fd;
856 	pfd[POLL_STDOUT].events = 0;
857 
858 	while (1) {
859 		/* both inputs are gone, buffers are empty, we are done */
860 		if (pfd[POLL_STDIN].fd == -1 && pfd[POLL_NETIN].fd == -1
861 		    && stdinbufpos == 0 && netinbufpos == 0) {
862 			if (FreeBSD_Mflag && !stats_printed)
863 				FreeBSD_stats_print(net_fd);
864 			close(net_fd);
865 			return;
866 		}
867 		/* both outputs are gone, we can't continue */
868 		if (pfd[POLL_NETOUT].fd == -1 && pfd[POLL_STDOUT].fd == -1) {
869 			if (FreeBSD_Mflag && !stats_printed)
870 				FreeBSD_stats_print(net_fd);
871 			close(net_fd);
872 			return;
873 		}
874 		/* listen and net in gone, queues empty, done */
875 		if (lflag && pfd[POLL_NETIN].fd == -1
876 		    && stdinbufpos == 0 && netinbufpos == 0) {
877 			if (FreeBSD_Mflag && !stats_printed)
878 				FreeBSD_stats_print(net_fd);
879 			close(net_fd);
880 			return;
881 		}
882 
883 		/* help says -i is for "wait between lines sent". We read and
884 		 * write arbitrary amounts of data, and we don't want to start
885 		 * scanning for newlines, so this is as good as it gets */
886 		if (iflag)
887 			sleep(iflag);
888 
889 		/* poll */
890 		num_fds = poll(pfd, 4, timeout);
891 
892 		/* treat poll errors */
893 		if (num_fds == -1) {
894 			close(net_fd);
895 			err(1, "polling error");
896 		}
897 
898 		/* timeout happened */
899 		if (num_fds == 0) {
900 			if (FreeBSD_Mflag)
901 				FreeBSD_stats_print(net_fd);
902 			return;
903 		}
904 
905 		/* treat socket error conditions */
906 		for (n = 0; n < 4; n++) {
907 			if (pfd[n].revents & (POLLERR|POLLNVAL)) {
908 				pfd[n].fd = -1;
909 			}
910 		}
911 		/* reading is possible after HUP */
912 		if (pfd[POLL_STDIN].events & POLLIN &&
913 		    pfd[POLL_STDIN].revents & POLLHUP &&
914 		    ! (pfd[POLL_STDIN].revents & POLLIN))
915 				pfd[POLL_STDIN].fd = -1;
916 
917 		if (pfd[POLL_NETIN].events & POLLIN &&
918 		    pfd[POLL_NETIN].revents & POLLHUP &&
919 		    ! (pfd[POLL_NETIN].revents & POLLIN))
920 				pfd[POLL_NETIN].fd = -1;
921 
922 		if (pfd[POLL_NETOUT].revents & POLLHUP) {
923 			if (Nflag)
924 				shutdown(pfd[POLL_NETOUT].fd, SHUT_WR);
925 			pfd[POLL_NETOUT].fd = -1;
926 		}
927 		/* if HUP, stop watching stdout */
928 		if (pfd[POLL_STDOUT].revents & POLLHUP)
929 			pfd[POLL_STDOUT].fd = -1;
930 		/* if no net out, stop watching stdin */
931 		if (pfd[POLL_NETOUT].fd == -1)
932 			pfd[POLL_STDIN].fd = -1;
933 		/* if no stdout, stop watching net in */
934 		if (pfd[POLL_STDOUT].fd == -1) {
935 			if (pfd[POLL_NETIN].fd != -1)
936 				shutdown(pfd[POLL_NETIN].fd, SHUT_RD);
937 			pfd[POLL_NETIN].fd = -1;
938 		}
939 
940 		/* try to read from stdin */
941 		if (pfd[POLL_STDIN].revents & POLLIN && stdinbufpos < BUFSIZE) {
942 			ret = fillbuf(pfd[POLL_STDIN].fd, stdinbuf,
943 			    &stdinbufpos);
944 			/* error or eof on stdin - remove from pfd */
945 			if (ret == 0 || ret == -1)
946 				pfd[POLL_STDIN].fd = -1;
947 			/* read something - poll net out */
948 			if (stdinbufpos > 0)
949 				pfd[POLL_NETOUT].events = POLLOUT;
950 			/* filled buffer - remove self from polling */
951 			if (stdinbufpos == BUFSIZE)
952 				pfd[POLL_STDIN].events = 0;
953 		}
954 		/* try to write to network */
955 		if (pfd[POLL_NETOUT].revents & POLLOUT && stdinbufpos > 0) {
956 			ret = drainbuf(pfd[POLL_NETOUT].fd, stdinbuf,
957 			    &stdinbufpos);
958 			if (ret == -1)
959 				pfd[POLL_NETOUT].fd = -1;
960 			/* buffer empty - remove self from polling */
961 			if (stdinbufpos == 0)
962 				pfd[POLL_NETOUT].events = 0;
963 			/* buffer no longer full - poll stdin again */
964 			if (stdinbufpos < BUFSIZE)
965 				pfd[POLL_STDIN].events = POLLIN;
966 		}
967 		/* try to read from network */
968 		if (pfd[POLL_NETIN].revents & POLLIN && netinbufpos < BUFSIZE) {
969 			ret = fillbuf(pfd[POLL_NETIN].fd, netinbuf,
970 			    &netinbufpos);
971 			if (ret == -1)
972 				pfd[POLL_NETIN].fd = -1;
973 			/* eof on net in - remove from pfd */
974 			if (ret == 0) {
975 				shutdown(pfd[POLL_NETIN].fd, SHUT_RD);
976 				pfd[POLL_NETIN].fd = -1;
977 			}
978 			/* read something - poll stdout */
979 			if (netinbufpos > 0)
980 				pfd[POLL_STDOUT].events = POLLOUT;
981 			/* filled buffer - remove self from polling */
982 			if (netinbufpos == BUFSIZE)
983 				pfd[POLL_NETIN].events = 0;
984 			/* handle telnet */
985 			if (tflag)
986 				atelnet(pfd[POLL_NETIN].fd, netinbuf,
987 				    netinbufpos);
988 		}
989 		/* try to write to stdout */
990 		if (pfd[POLL_STDOUT].revents & POLLOUT && netinbufpos > 0) {
991 			ret = drainbuf(pfd[POLL_STDOUT].fd, netinbuf,
992 			    &netinbufpos);
993 			if (ret == -1)
994 				pfd[POLL_STDOUT].fd = -1;
995 			/* buffer empty - remove self from polling */
996 			if (netinbufpos == 0)
997 				pfd[POLL_STDOUT].events = 0;
998 			/* buffer no longer full - poll net in again */
999 			if (netinbufpos < BUFSIZE)
1000 				pfd[POLL_NETIN].events = POLLIN;
1001 		}
1002 
1003 		/* stdin gone and queue empty? */
1004 		if (pfd[POLL_STDIN].fd == -1 && stdinbufpos == 0) {
1005 			if (pfd[POLL_NETOUT].fd != -1 && Nflag) {
1006 				if (FreeBSD_Mflag) {
1007 					FreeBSD_stats_print(net_fd);
1008 					stats_printed = 1;
1009 				}
1010 				shutdown(pfd[POLL_NETOUT].fd, SHUT_WR);
1011 			}
1012 			pfd[POLL_NETOUT].fd = -1;
1013 		}
1014 		/* net in gone and queue empty? */
1015 		if (pfd[POLL_NETIN].fd == -1 && netinbufpos == 0) {
1016 			pfd[POLL_STDOUT].fd = -1;
1017 		}
1018 	}
1019 }
1020 
1021 ssize_t
1022 drainbuf(int fd, unsigned char *buf, size_t *bufpos)
1023 {
1024 	ssize_t n;
1025 	ssize_t adjust;
1026 
1027 	n = write(fd, buf, *bufpos);
1028 	/* don't treat EAGAIN, EINTR as error */
1029 	if (n == -1 && (errno == EAGAIN || errno == EINTR))
1030 		n = -2;
1031 	if (n <= 0)
1032 		return n;
1033 	/* adjust buffer */
1034 	adjust = *bufpos - n;
1035 	if (adjust > 0)
1036 		memmove(buf, buf + n, adjust);
1037 	*bufpos -= n;
1038 	return n;
1039 }
1040 
1041 
1042 ssize_t
1043 fillbuf(int fd, unsigned char *buf, size_t *bufpos)
1044 {
1045 	size_t num = BUFSIZE - *bufpos;
1046 	ssize_t n;
1047 
1048 	n = read(fd, buf + *bufpos, num);
1049 	/* don't treat EAGAIN, EINTR as error */
1050 	if (n == -1 && (errno == EAGAIN || errno == EINTR))
1051 		n = -2;
1052 	if (n <= 0)
1053 		return n;
1054 	*bufpos += n;
1055 	return n;
1056 }
1057 
1058 /*
1059  * fdpass()
1060  * Pass the connected file descriptor to stdout and exit.
1061  */
1062 void
1063 fdpass(int nfd)
1064 {
1065 	struct msghdr mh;
1066 	union {
1067 		struct cmsghdr hdr;
1068 		char buf[CMSG_SPACE(sizeof(int))];
1069 	} cmsgbuf;
1070 	struct cmsghdr *cmsg;
1071 	struct iovec iov;
1072 	char c = '\0';
1073 	ssize_t r;
1074 	struct pollfd pfd;
1075 
1076 	/* Avoid obvious stupidity */
1077 	if (isatty(STDOUT_FILENO))
1078 		errx(1, "Cannot pass file descriptor to tty");
1079 
1080 	bzero(&mh, sizeof(mh));
1081 	bzero(&cmsgbuf, sizeof(cmsgbuf));
1082 	bzero(&iov, sizeof(iov));
1083 
1084 	mh.msg_control = (caddr_t)&cmsgbuf.buf;
1085 	mh.msg_controllen = sizeof(cmsgbuf.buf);
1086 	cmsg = CMSG_FIRSTHDR(&mh);
1087 	cmsg->cmsg_len = CMSG_LEN(sizeof(int));
1088 	cmsg->cmsg_level = SOL_SOCKET;
1089 	cmsg->cmsg_type = SCM_RIGHTS;
1090 	*(int *)CMSG_DATA(cmsg) = nfd;
1091 
1092 	iov.iov_base = &c;
1093 	iov.iov_len = 1;
1094 	mh.msg_iov = &iov;
1095 	mh.msg_iovlen = 1;
1096 
1097 	bzero(&pfd, sizeof(pfd));
1098 	pfd.fd = STDOUT_FILENO;
1099 	pfd.events = POLLOUT;
1100 	for (;;) {
1101 		r = sendmsg(STDOUT_FILENO, &mh, 0);
1102 		if (r == -1) {
1103 			if (errno == EAGAIN || errno == EINTR) {
1104 				if (poll(&pfd, 1, -1) == -1)
1105 					err(1, "poll");
1106 				continue;
1107 			}
1108 			err(1, "sendmsg");
1109 		} else if (r != 1)
1110 			errx(1, "sendmsg: unexpected return value %zd", r);
1111 		else
1112 			break;
1113 	}
1114 	exit(0);
1115 }
1116 
1117 /* Deal with RFC 854 WILL/WONT DO/DONT negotiation. */
1118 void
1119 atelnet(int nfd, unsigned char *buf, unsigned int size)
1120 {
1121 	unsigned char *p, *end;
1122 	unsigned char obuf[4];
1123 
1124 	if (size < 3)
1125 		return;
1126 	end = buf + size - 2;
1127 
1128 	for (p = buf; p < end; p++) {
1129 		if (*p != IAC)
1130 			continue;
1131 
1132 		obuf[0] = IAC;
1133 		p++;
1134 		if ((*p == WILL) || (*p == WONT))
1135 			obuf[1] = DONT;
1136 		else if ((*p == DO) || (*p == DONT))
1137 			obuf[1] = WONT;
1138 		else
1139 			continue;
1140 
1141 		p++;
1142 		obuf[2] = *p;
1143 		if (atomicio(vwrite, nfd, obuf, 3) != 3)
1144 			warn("Write Error!");
1145 	}
1146 }
1147 
1148 /*
1149  * build_ports()
1150  * Build an array of ports in portlist[], listing each port
1151  * that we should try to connect to.
1152  */
1153 void
1154 build_ports(char *p)
1155 {
1156 	const char *errstr;
1157 	char *n;
1158 	int hi, lo, cp;
1159 	int x = 0;
1160 
1161 	if ((n = strchr(p, '-')) != NULL) {
1162 		*n = '\0';
1163 		n++;
1164 
1165 		/* Make sure the ports are in order: lowest->highest. */
1166 		hi = strtonum(n, 1, PORT_MAX, &errstr);
1167 		if (errstr)
1168 			errx(1, "port number %s: %s", errstr, n);
1169 		lo = strtonum(p, 1, PORT_MAX, &errstr);
1170 		if (errstr)
1171 			errx(1, "port number %s: %s", errstr, p);
1172 
1173 		if (lo > hi) {
1174 			cp = hi;
1175 			hi = lo;
1176 			lo = cp;
1177 		}
1178 
1179 		/* Load ports sequentially. */
1180 		for (cp = lo; cp <= hi; cp++) {
1181 			portlist[x] = calloc(1, PORT_MAX_LEN);
1182 			if (portlist[x] == NULL)
1183 				err(1, NULL);
1184 			snprintf(portlist[x], PORT_MAX_LEN, "%d", cp);
1185 			x++;
1186 		}
1187 
1188 		/* Randomly swap ports. */
1189 		if (rflag) {
1190 			int y;
1191 			char *c;
1192 
1193 			for (x = 0; x <= (hi - lo); x++) {
1194 				y = (arc4random() & 0xFFFF) % (hi - lo);
1195 				c = portlist[x];
1196 				portlist[x] = portlist[y];
1197 				portlist[y] = c;
1198 			}
1199 		}
1200 	} else {
1201 		hi = strtonum(p, 1, PORT_MAX, &errstr);
1202 		if (errstr)
1203 			errx(1, "port number %s: %s", errstr, p);
1204 		portlist[0] = strdup(p);
1205 		if (portlist[0] == NULL)
1206 			err(1, NULL);
1207 	}
1208 }
1209 
1210 /*
1211  * udptest()
1212  * Do a few writes to see if the UDP port is there.
1213  * Fails once PF state table is full.
1214  */
1215 int
1216 udptest(int s)
1217 {
1218 	int i, ret;
1219 
1220 	for (i = 0; i <= 3; i++) {
1221 		if (write(s, "X", 1) == 1)
1222 			ret = 1;
1223 		else
1224 			ret = -1;
1225 	}
1226 	return (ret);
1227 }
1228 
1229 void
1230 FreeBSD_stats_setup(int s)
1231 {
1232 
1233 	if (setsockopt(s, IPPROTO_TCP, TCP_STATS,
1234 	    &FreeBSD_Mflag, sizeof(FreeBSD_Mflag)) == -1) {
1235 		if (errno == EOPNOTSUPP) {
1236 			warnx("getsockopt(TCP_STATS) failed; "
1237 			    "kernel built without \"options STATS\"?");
1238 		}
1239 		err(1, "enable TCP_STATS gathering");
1240 	}
1241 }
1242 
1243 void
1244 FreeBSD_stats_print(int s)
1245 {
1246 #ifdef WITH_STATS
1247 	struct statsblob *statsb;
1248 	struct sbuf *sb;
1249 	socklen_t sockoptlen;
1250 	int error;
1251 
1252 	/*
1253 	 * This usleep is a workaround for TCP_STATS reporting
1254 	 * incorrect values for TXPB.
1255 	 */
1256 	usleep(100000);
1257 
1258 	sockoptlen = 2048;
1259 	statsb = malloc(sockoptlen);
1260 	if (statsb == NULL)
1261 		err(1, "malloc");
1262 	error = getsockopt(s, IPPROTO_TCP, TCP_STATS, statsb, &sockoptlen);
1263 	if (error != 0) {
1264 		if (errno == EOVERFLOW && statsb->cursz > sockoptlen) {
1265 			/* Retry with a larger size. */
1266 			sockoptlen = statsb->cursz;
1267 			statsb = realloc(statsb, sockoptlen);
1268 			if (statsb == NULL)
1269 				err(1, "realloc");
1270 			error = getsockopt(s, IPPROTO_TCP, TCP_STATS,
1271 			    statsb, &sockoptlen);
1272 		}
1273 		if (error != 0)
1274 			err(1, "getsockopt");
1275 	}
1276 
1277 	sb = sbuf_new_auto();
1278 	error = stats_blob_tostr(statsb, sb, SB_STRFMT_JSON, SB_TOSTR_META);
1279 	if (error != 0)
1280 		errc(1, error, "stats_blob_tostr");
1281 
1282 	error = sbuf_finish(sb);
1283 	if (error != 0)
1284 		err(1, "sbuf_finish");
1285 
1286 	fprintf(stderr, "%s\n", sbuf_data(sb));
1287 #endif
1288 }
1289 
1290 void
1291 set_common_sockopts(int s, int af)
1292 {
1293 	int x = 1;
1294 
1295 	if (Sflag) {
1296 		if (setsockopt(s, IPPROTO_TCP, TCP_MD5SIG,
1297 			&x, sizeof(x)) == -1)
1298 			err(1, NULL);
1299 	}
1300 	if (Dflag) {
1301 		if (setsockopt(s, SOL_SOCKET, SO_DEBUG,
1302 			&x, sizeof(x)) == -1)
1303 			err(1, NULL);
1304 	}
1305 	if (Tflag != -1) {
1306 		int proto, option;
1307 
1308 		if (af == AF_INET6) {
1309 			proto = IPPROTO_IPV6;
1310 			option = IPV6_TCLASS;
1311 		} else {
1312 			proto = IPPROTO_IP;
1313 			option = IP_TOS;
1314 		}
1315 
1316 		if (setsockopt(s, proto, option, &Tflag, sizeof(Tflag)) == -1)
1317 			err(1, "set IP ToS");
1318 	}
1319 	if (Iflag) {
1320 		if (setsockopt(s, SOL_SOCKET, SO_RCVBUF,
1321 		    &Iflag, sizeof(Iflag)) == -1)
1322 			err(1, "set TCP receive buffer size");
1323 	}
1324 	if (Oflag) {
1325 		if (setsockopt(s, SOL_SOCKET, SO_SNDBUF,
1326 		    &Oflag, sizeof(Oflag)) == -1)
1327 			err(1, "set TCP send buffer size");
1328 	}
1329 	if (FreeBSD_Oflag) {
1330 		if (setsockopt(s, IPPROTO_TCP, TCP_NOOPT,
1331 		    &FreeBSD_Oflag, sizeof(FreeBSD_Oflag)) == -1)
1332 			err(1, "disable TCP options");
1333 	}
1334 	if (FreeBSD_Mflag)
1335 		FreeBSD_stats_setup(s);
1336 #ifdef IPSEC
1337 	if (ipsec_policy[0] != NULL)
1338 		add_ipsec_policy(s, af, ipsec_policy[0]);
1339 	if (ipsec_policy[1] != NULL)
1340 		add_ipsec_policy(s, af, ipsec_policy[1]);
1341 #endif
1342 }
1343 
1344 int
1345 map_tos(char *s, int *val)
1346 {
1347 	/* DiffServ Codepoints and other TOS mappings */
1348 	const struct toskeywords {
1349 		const char	*keyword;
1350 		int		 val;
1351 	} *t, toskeywords[] = {
1352 		{ "af11",		IPTOS_DSCP_AF11 },
1353 		{ "af12",		IPTOS_DSCP_AF12 },
1354 		{ "af13",		IPTOS_DSCP_AF13 },
1355 		{ "af21",		IPTOS_DSCP_AF21 },
1356 		{ "af22",		IPTOS_DSCP_AF22 },
1357 		{ "af23",		IPTOS_DSCP_AF23 },
1358 		{ "af31",		IPTOS_DSCP_AF31 },
1359 		{ "af32",		IPTOS_DSCP_AF32 },
1360 		{ "af33",		IPTOS_DSCP_AF33 },
1361 		{ "af41",		IPTOS_DSCP_AF41 },
1362 		{ "af42",		IPTOS_DSCP_AF42 },
1363 		{ "af43",		IPTOS_DSCP_AF43 },
1364 		{ "critical",		IPTOS_PREC_CRITIC_ECP },
1365 		{ "cs0",		IPTOS_DSCP_CS0 },
1366 		{ "cs1",		IPTOS_DSCP_CS1 },
1367 		{ "cs2",		IPTOS_DSCP_CS2 },
1368 		{ "cs3",		IPTOS_DSCP_CS3 },
1369 		{ "cs4",		IPTOS_DSCP_CS4 },
1370 		{ "cs5",		IPTOS_DSCP_CS5 },
1371 		{ "cs6",		IPTOS_DSCP_CS6 },
1372 		{ "cs7",		IPTOS_DSCP_CS7 },
1373 		{ "ef",			IPTOS_DSCP_EF },
1374 		{ "inetcontrol",	IPTOS_PREC_INTERNETCONTROL },
1375 		{ "lowdelay",		IPTOS_LOWDELAY },
1376 		{ "netcontrol",		IPTOS_PREC_NETCONTROL },
1377 		{ "reliability",	IPTOS_RELIABILITY },
1378 		{ "throughput",		IPTOS_THROUGHPUT },
1379 		{ NULL, 		-1 },
1380 	};
1381 
1382 	for (t = toskeywords; t->keyword != NULL; t++) {
1383 		if (strcmp(s, t->keyword) == 0) {
1384 			*val = t->val;
1385 			return (1);
1386 		}
1387 	}
1388 
1389 	return (0);
1390 }
1391 
1392 void
1393 report_connect(const struct sockaddr *sa, socklen_t salen)
1394 {
1395 	char remote_host[NI_MAXHOST];
1396 	char remote_port[NI_MAXSERV];
1397 	int herr;
1398 	int flags = NI_NUMERICSERV;
1399 
1400 	if (nflag)
1401 		flags |= NI_NUMERICHOST;
1402 
1403 	if ((herr = getnameinfo(sa, salen,
1404 	    remote_host, sizeof(remote_host),
1405 	    remote_port, sizeof(remote_port),
1406 	    flags)) != 0) {
1407 		if (herr == EAI_SYSTEM)
1408 			err(1, "getnameinfo");
1409 		else
1410 			errx(1, "getnameinfo: %s", gai_strerror(herr));
1411 	}
1412 
1413 	fprintf(stderr,
1414 	    "Connection from %s %s "
1415 	    "received!\n", remote_host, remote_port);
1416 }
1417 
1418 void
1419 help(void)
1420 {
1421 	usage(0);
1422 	fprintf(stderr, "\tCommand Summary:\n\
1423 	\t-4		Use IPv4\n\
1424 	\t-6		Use IPv6\n\
1425 	\t-D		Enable the debug socket option\n\
1426 	\t-d		Detach from stdin\n");
1427 #ifdef IPSEC
1428 	fprintf(stderr, "\
1429 	\t-E		Use IPsec ESP\n\
1430 	\t-e policy	Use specified IPsec policy\n");
1431 #endif
1432 	fprintf(stderr, "\
1433 	\t-F		Pass socket fd\n\
1434 	\t-h		This help text\n\
1435 	\t-I length	TCP receive buffer length\n\
1436 	\t-i secs\t	Delay interval for lines sent, ports scanned\n\
1437 	\t-k		Keep inbound sockets open for multiple connects\n\
1438 	\t-l		Listen mode, for inbound connects\n\
1439 	\t-N		Shutdown the network socket after EOF on stdin\n\
1440 	\t-n		Suppress name/port resolutions\n\
1441 	\t--no-tcpopt	Disable TCP options\n\
1442 	\t--sctp\t	SCTP mode\n\
1443 	\t-O length	TCP send buffer length\n\
1444 	\t-P proxyuser\tUsername for proxy authentication\n\
1445 	\t-p port\t	Specify local port for remote connects\n\
1446 	\t-r		Randomize remote ports\n\
1447 	\t-S		Enable the TCP MD5 signature option\n\
1448 	\t-s addr\t	Local source address\n\
1449 	\t-T toskeyword\tSet IP Type of Service\n\
1450 	\t-t		Answer TELNET negotiation\n\
1451 	\t-U		Use UNIX domain socket\n\
1452 	\t-u		UDP mode\n\
1453 	\t-V rtable	Specify alternate routing table\n\
1454 	\t-v		Verbose\n\
1455 	\t-w secs\t	Timeout for connects and final net reads\n\
1456 	\t-X proto	Proxy protocol: \"4\", \"5\" (SOCKS) or \"connect\"\n\
1457 	\t-x addr[:port]\tSpecify proxy address and port\n\
1458 	\t-z		Zero-I/O mode [used for scanning]\n\
1459 	Port numbers can be individual or ranges: lo-hi [inclusive]\n");
1460 #ifdef IPSEC
1461 	fprintf(stderr, "\tSee ipsec_set_policy(3) for -e argument format\n");
1462 #endif
1463 	exit(1);
1464 }
1465 
1466 #ifdef IPSEC
1467 void
1468 add_ipsec_policy(int s, int af, char *policy)
1469 {
1470 	char *raw;
1471 	int e;
1472 
1473 	raw = ipsec_set_policy(policy, strlen(policy));
1474 	if (raw == NULL)
1475 		errx(1, "ipsec_set_policy `%s': %s", policy,
1476 		     ipsec_strerror());
1477 	if (af == AF_INET)
1478 		e = setsockopt(s, IPPROTO_IP, IP_IPSEC_POLICY, raw,
1479 		    ipsec_get_policylen(raw));
1480 	if (af == AF_INET6)
1481 		e = setsockopt(s, IPPROTO_IPV6, IPV6_IPSEC_POLICY, raw,
1482 		    ipsec_get_policylen(raw));
1483 	if (e < 0)
1484 		err(1, "ipsec policy cannot be configured");
1485 	free(raw);
1486 	if (vflag)
1487 		fprintf(stderr, "ipsec policy configured: `%s'\n", policy);
1488 	return;
1489 }
1490 #endif /* IPSEC */
1491 
1492 void
1493 usage(int ret)
1494 {
1495 	fprintf(stderr,
1496 #ifdef IPSEC
1497 	    "usage: nc [-46DdEFhklNnrStUuvz] [-e policy] [-I length] [-i interval] [-O length]\n"
1498 #else
1499 	    "usage: nc [-46DdFhklNnrStUuvz] [-I length] [-i interval] [-O length]\n"
1500 #endif
1501 	    "\t  [--no-tcpopt] [--sctp]\n"
1502 	    "\t  [-P proxy_username] [-p source_port] [-s source] [-T ToS]\n"
1503 	    "\t  [-V rtable] [-w timeout] [-X proxy_protocol]\n"
1504 	    "\t  [-x proxy_address[:port]] [destination] [port]\n");
1505 	if (ret)
1506 		exit(1);
1507 }
1508