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