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