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