netcat.c revision 206689
1/* $OpenBSD: netcat.c,v 1.95 2010/02/27 00:58:56 nicm 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: head/contrib/netcat/netcat.c 206689 2010-04-15 23:21:24Z 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/un.h>
42
43#include <netinet/in.h>
44#include <netinet/in_systm.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 <netdb.h>
56#include <poll.h>
57#include <stdarg.h>
58#include <stdio.h>
59#include <stdlib.h>
60#include <string.h>
61#include <unistd.h>
62#include <fcntl.h>
63#include <limits.h>
64#include "atomicio.h"
65
66#ifndef SUN_LEN
67#define SUN_LEN(su) \
68	(sizeof(*(su)) - sizeof((su)->sun_path) + strlen((su)->sun_path))
69#endif
70
71#define PORT_MAX	65535
72#define PORT_MAX_LEN	6
73
74/* Command Line Options */
75int	dflag;					/* detached, no stdin */
76unsigned int iflag;				/* Interval Flag */
77int	jflag;					/* use jumbo frames if we can */
78int	kflag;					/* More than one connect */
79int	lflag;					/* Bind to local port */
80int	nflag;					/* Don't do name look up */
81int	FreeBSD_Oflag;				/* Do not use TCP options */
82char   *Pflag;					/* Proxy username */
83char   *pflag;					/* Localport flag */
84int	rflag;					/* Random ports flag */
85char   *sflag;					/* Source Address */
86int	tflag;					/* Telnet Emulation */
87int	uflag;					/* UDP - Default to TCP */
88int	vflag;					/* Verbosity */
89int	xflag;					/* Socks proxy */
90int	zflag;					/* Port Scan Flag */
91int	Dflag;					/* sodebug */
92int	Iflag;					/* TCP receive buffer size */
93int	Oflag;					/* TCP send buffer size */
94int	Sflag;					/* TCP MD5 signature option */
95int	Tflag = -1;				/* IP Type of Service */
96u_int	rdomain;
97
98int timeout = -1;
99int family = AF_UNSPEC;
100char *portlist[PORT_MAX+1];
101
102void	atelnet(int, unsigned char *, unsigned int);
103void	build_ports(char *);
104void	help(void);
105int	local_listen(char *, char *, struct addrinfo);
106void	readwrite(int);
107int	remote_connect(const char *, const char *, struct addrinfo);
108int	socks_connect(const char *, const char *, struct addrinfo,
109	    const char *, const char *, struct addrinfo, int, const char *);
110int	udptest(int);
111int	unix_connect(char *);
112int	unix_listen(char *);
113void	set_common_sockopts(int);
114int	parse_iptos(char *);
115void	usage(int);
116
117#ifdef IPSEC
118void	add_ipsec_policy(int, char *);
119
120char	*ipsec_policy[2];
121#endif
122
123int
124main(int argc, char *argv[])
125{
126	int ch, s, ret, socksv, ipsec_count;
127	int numfibs;
128	size_t intsize = sizeof(int);
129	char *host, *uport;
130	struct addrinfo hints;
131	struct servent *sv;
132	socklen_t len;
133	struct sockaddr_storage cliaddr;
134	char *proxy;
135	const char *errstr, *proxyhost = "", *proxyport = NULL;
136	struct addrinfo proxyhints;
137	struct option longopts[] = {
138		{ "no-tcpopt",	no_argument,	&FreeBSD_Oflag,	1 },
139		{ NULL,		0,		NULL,		0 }
140	};
141
142	rdomain = 0;
143	ret = 1;
144	ipsec_count = 0;
145	s = 0;
146	socksv = 5;
147	host = NULL;
148	uport = NULL;
149	sv = NULL;
150
151	while ((ch = getopt_long(argc, argv,
152	    "46DdEe:hI:i:jklnoO:P:p:rSs:tT:UuV:vw:X:x:z",
153	    longopts, NULL)) != -1) {
154		switch (ch) {
155		case '4':
156			family = AF_INET;
157			break;
158		case '6':
159			family = AF_INET6;
160			break;
161		case 'U':
162			family = AF_UNIX;
163			break;
164		case 'X':
165			if (strcasecmp(optarg, "connect") == 0)
166				socksv = -1; /* HTTP proxy CONNECT */
167			else if (strcmp(optarg, "4") == 0)
168				socksv = 4; /* SOCKS v.4 */
169			else if (strcmp(optarg, "5") == 0)
170				socksv = 5; /* SOCKS v.5 */
171			else
172				errx(1, "unsupported proxy protocol");
173			break;
174		case 'd':
175			dflag = 1;
176			break;
177		case 'e':
178#ifdef IPSEC
179			ipsec_policy[ipsec_count++ % 2] = optarg;
180#else
181			errx(1, "IPsec support unavailable.");
182#endif
183			break;
184		case 'E':
185#ifdef IPSEC
186			ipsec_policy[0] = "in  ipsec esp/transport//require";
187			ipsec_policy[1] = "out ipsec esp/transport//require";
188#else
189			errx(1, "IPsec support unavailable.");
190#endif
191			break;
192		case 'h':
193			help();
194			break;
195		case 'i':
196			iflag = strtonum(optarg, 0, UINT_MAX, &errstr);
197			if (errstr)
198				errx(1, "interval %s: %s", errstr, optarg);
199			break;
200#ifdef SO_JUMBO
201		case 'j':
202			jflag = 1;
203			break;
204#endif
205		case 'k':
206			kflag = 1;
207			break;
208		case 'l':
209			lflag = 1;
210			break;
211		case 'n':
212			nflag = 1;
213			break;
214		case 'o':
215			fprintf(stderr, "option -o is deprecated.\n");
216			break;
217		case 'P':
218			Pflag = optarg;
219			break;
220		case 'p':
221			pflag = optarg;
222			break;
223		case 'r':
224			rflag = 1;
225			break;
226		case 's':
227			sflag = optarg;
228			break;
229		case 't':
230			tflag = 1;
231			break;
232		case 'u':
233			uflag = 1;
234			break;
235		case 'V':
236			if (sysctlbyname("net.fibs", &numfibs, &intsize, NULL, 0) == -1)
237				errx(1, "Multiple FIBS not supported");
238			rdomain = (unsigned int)strtonum(optarg, 0,
239			    numfibs - 1, &errstr);
240			if (errstr)
241				errx(1, "FIB %s: %s", errstr, optarg);
242			break;
243		case 'v':
244			vflag = 1;
245			break;
246		case 'w':
247			timeout = strtonum(optarg, 0, INT_MAX / 1000, &errstr);
248			if (errstr)
249				errx(1, "timeout %s: %s", errstr, optarg);
250			timeout *= 1000;
251			break;
252		case 'x':
253			xflag = 1;
254			if ((proxy = strdup(optarg)) == NULL)
255				err(1, NULL);
256			break;
257		case 'z':
258			zflag = 1;
259			break;
260		case 'D':
261			Dflag = 1;
262			break;
263		case 'I':
264			Iflag = strtonum(optarg, 1, 65536 << 14, &errstr);
265			if (errstr != NULL)
266				errx(1, "TCP receive window %s: %s",
267				    errstr, optarg);
268			break;
269		case 'O':
270			Oflag = strtonum(optarg, 1, 65536 << 14, &errstr);
271			if (errstr != NULL) {
272			    if (strcmp(errstr, "invalid") != 0)
273				errx(1, "TCP send window %s: %s",
274				    errstr, optarg);
275			}
276			break;
277		case 'S':
278			Sflag = 1;
279			break;
280		case 'T':
281			Tflag = parse_iptos(optarg);
282			break;
283		default:
284			usage(1);
285		}
286	}
287	argc -= optind;
288	argv += optind;
289
290	/* Cruft to make sure options are clean, and used properly. */
291	if (argv[0] && !argv[1] && family == AF_UNIX) {
292		if (uflag)
293			errx(1, "cannot use -u and -U");
294		host = argv[0];
295		uport = NULL;
296	} else if (argv[0] && !argv[1]) {
297		if  (!lflag)
298			usage(1);
299		uport = argv[0];
300		host = NULL;
301	} else if (argv[0] && argv[1]) {
302		host = argv[0];
303		uport = argv[1];
304	} else
305		usage(1);
306
307	if (lflag && sflag)
308		errx(1, "cannot use -s and -l");
309	if (lflag && pflag)
310		errx(1, "cannot use -p and -l");
311	if (lflag && zflag)
312		errx(1, "cannot use -z and -l");
313	if (!lflag && kflag)
314		errx(1, "must use -l with -k");
315
316	/* Initialize addrinfo structure. */
317	if (family != AF_UNIX) {
318		memset(&hints, 0, sizeof(struct addrinfo));
319		hints.ai_family = family;
320		hints.ai_socktype = uflag ? SOCK_DGRAM : SOCK_STREAM;
321		hints.ai_protocol = uflag ? IPPROTO_UDP : IPPROTO_TCP;
322		if (nflag)
323			hints.ai_flags |= AI_NUMERICHOST;
324	}
325
326	if (xflag) {
327		if (uflag)
328			errx(1, "no proxy support for UDP mode");
329
330		if (lflag)
331			errx(1, "no proxy support for listen");
332
333		if (family == AF_UNIX)
334			errx(1, "no proxy support for unix sockets");
335
336		/* XXX IPv6 transport to proxy would probably work */
337		if (family == AF_INET6)
338			errx(1, "no proxy support for IPv6");
339
340		if (sflag)
341			errx(1, "no proxy support for local source address");
342
343		proxyhost = strsep(&proxy, ":");
344		proxyport = proxy;
345
346		memset(&proxyhints, 0, sizeof(struct addrinfo));
347		proxyhints.ai_family = family;
348		proxyhints.ai_socktype = SOCK_STREAM;
349		proxyhints.ai_protocol = IPPROTO_TCP;
350		if (nflag)
351			proxyhints.ai_flags |= AI_NUMERICHOST;
352	}
353
354	if (lflag) {
355		int connfd;
356		ret = 0;
357
358		if (family == AF_UNIX)
359			s = unix_listen(host);
360
361		/* Allow only one connection at a time, but stay alive. */
362		for (;;) {
363			if (family != AF_UNIX)
364				s = local_listen(host, uport, hints);
365			if (s < 0)
366				err(1, NULL);
367			/*
368			 * For UDP, we will use recvfrom() initially
369			 * to wait for a caller, then use the regular
370			 * functions to talk to the caller.
371			 */
372			if (uflag) {
373				int rv, plen;
374				char buf[8192];
375				struct sockaddr_storage z;
376
377				len = sizeof(z);
378				plen = jflag ? 8192 : 1024;
379				rv = recvfrom(s, buf, plen, MSG_PEEK,
380				    (struct sockaddr *)&z, &len);
381				if (rv < 0)
382					err(1, "recvfrom");
383
384				rv = connect(s, (struct sockaddr *)&z, len);
385				if (rv < 0)
386					err(1, "connect");
387
388				connfd = s;
389			} else {
390				len = sizeof(cliaddr);
391				connfd = accept(s, (struct sockaddr *)&cliaddr,
392				    &len);
393			}
394
395			readwrite(connfd);
396			close(connfd);
397			if (family != AF_UNIX)
398				close(s);
399
400			if (!kflag)
401				break;
402		}
403	} else if (family == AF_UNIX) {
404		ret = 0;
405
406		if ((s = unix_connect(host)) > 0 && !zflag) {
407			readwrite(s);
408			close(s);
409		} else
410			ret = 1;
411
412		exit(ret);
413
414	} else {
415		int i = 0;
416
417		/* Construct the portlist[] array. */
418		build_ports(uport);
419
420		/* Cycle through portlist, connecting to each port. */
421		for (i = 0; portlist[i] != NULL; i++) {
422			if (s)
423				close(s);
424
425			if (xflag)
426				s = socks_connect(host, portlist[i], hints,
427				    proxyhost, proxyport, proxyhints, socksv,
428				    Pflag);
429			else
430				s = remote_connect(host, portlist[i], hints);
431
432			if (s < 0)
433				continue;
434
435			ret = 0;
436			if (vflag || zflag) {
437				/* For UDP, make sure we are connected. */
438				if (uflag) {
439					if (udptest(s) == -1) {
440						ret = 1;
441						continue;
442					}
443				}
444
445				/* Don't look up port if -n. */
446				if (nflag)
447					sv = NULL;
448				else {
449					sv = getservbyport(
450					    ntohs(atoi(portlist[i])),
451					    uflag ? "udp" : "tcp");
452				}
453
454				fprintf(stderr,
455				    "Connection to %s %s port [%s/%s] "
456				    "succeeded!\n", host, portlist[i],
457				    uflag ? "udp" : "tcp",
458				    sv ? sv->s_name : "*");
459			}
460			if (!zflag)
461				readwrite(s);
462		}
463	}
464
465	if (s)
466		close(s);
467
468	exit(ret);
469}
470
471/*
472 * unix_connect()
473 * Returns a socket connected to a local unix socket. Returns -1 on failure.
474 */
475int
476unix_connect(char *path)
477{
478	struct sockaddr_un sun;
479	int s;
480
481	if ((s = socket(AF_UNIX, SOCK_STREAM, 0)) < 0)
482		return (-1);
483	(void)fcntl(s, F_SETFD, 1);
484
485	memset(&sun, 0, sizeof(struct sockaddr_un));
486	sun.sun_family = AF_UNIX;
487
488	if (strlcpy(sun.sun_path, path, sizeof(sun.sun_path)) >=
489	    sizeof(sun.sun_path)) {
490		close(s);
491		errno = ENAMETOOLONG;
492		return (-1);
493	}
494	if (connect(s, (struct sockaddr *)&sun, SUN_LEN(&sun)) < 0) {
495		close(s);
496		return (-1);
497	}
498	return (s);
499
500}
501
502/*
503 * unix_listen()
504 * Create a unix domain socket, and listen on it.
505 */
506int
507unix_listen(char *path)
508{
509	struct sockaddr_un sun;
510	int s;
511
512	/* Create unix domain socket. */
513	if ((s = socket(AF_UNIX, SOCK_STREAM, 0)) < 0)
514		return (-1);
515
516	memset(&sun, 0, sizeof(struct sockaddr_un));
517	sun.sun_family = AF_UNIX;
518
519	if (strlcpy(sun.sun_path, path, sizeof(sun.sun_path)) >=
520	    sizeof(sun.sun_path)) {
521		close(s);
522		errno = ENAMETOOLONG;
523		return (-1);
524	}
525
526	if (bind(s, (struct sockaddr *)&sun, SUN_LEN(&sun)) < 0) {
527		close(s);
528		return (-1);
529	}
530
531	if (listen(s, 5) < 0) {
532		close(s);
533		return (-1);
534	}
535	return (s);
536}
537
538/*
539 * remote_connect()
540 * Returns a socket connected to a remote host. Properly binds to a local
541 * port or source address if needed. Returns -1 on failure.
542 */
543int
544remote_connect(const char *host, const char *port, struct addrinfo hints)
545{
546	struct addrinfo *res, *res0;
547	int s, error, on = 1;
548
549	if ((error = getaddrinfo(host, port, &hints, &res)))
550		errx(1, "getaddrinfo: %s", gai_strerror(error));
551
552	res0 = res;
553	do {
554		if ((s = socket(res0->ai_family, res0->ai_socktype,
555		    res0->ai_protocol)) < 0)
556			continue;
557#ifdef IPSEC
558		if (ipsec_policy[0] != NULL)
559			add_ipsec_policy(s, ipsec_policy[0]);
560		if (ipsec_policy[1] != NULL)
561			add_ipsec_policy(s, ipsec_policy[1]);
562#endif
563
564		if (rdomain) {
565			if (setfib(rdomain) == -1)
566				err(1, "setfib");
567		}
568
569		/* Bind to a local port or source address if specified. */
570		if (sflag || pflag) {
571			struct addrinfo ahints, *ares;
572
573			/* try IP_BINDANY, but don't insist */
574			setsockopt(s, IPPROTO_IP, IP_BINDANY, &on, sizeof(on));
575			memset(&ahints, 0, sizeof(struct addrinfo));
576			ahints.ai_family = res0->ai_family;
577			ahints.ai_socktype = uflag ? SOCK_DGRAM : SOCK_STREAM;
578			ahints.ai_protocol = uflag ? IPPROTO_UDP : IPPROTO_TCP;
579			ahints.ai_flags = AI_PASSIVE;
580			if ((error = getaddrinfo(sflag, pflag, &ahints, &ares)))
581				errx(1, "getaddrinfo: %s", gai_strerror(error));
582
583			if (bind(s, (struct sockaddr *)ares->ai_addr,
584			    ares->ai_addrlen) < 0)
585				errx(1, "bind failed: %s", strerror(errno));
586			freeaddrinfo(ares);
587		}
588
589		set_common_sockopts(s);
590
591		if (connect(s, res0->ai_addr, res0->ai_addrlen) == 0)
592			break;
593		else if (vflag)
594			warn("connect to %s port %s (%s) failed", host, port,
595			    uflag ? "udp" : "tcp");
596
597		close(s);
598		s = -1;
599	} while ((res0 = res0->ai_next) != NULL);
600
601	freeaddrinfo(res);
602
603	return (s);
604}
605
606/*
607 * local_listen()
608 * Returns a socket listening on a local port, binds to specified source
609 * address. Returns -1 on failure.
610 */
611int
612local_listen(char *host, char *port, struct addrinfo hints)
613{
614	struct addrinfo *res, *res0;
615	int s, ret, x = 1;
616	int error;
617
618	/* Allow nodename to be null. */
619	hints.ai_flags |= AI_PASSIVE;
620
621	/*
622	 * In the case of binding to a wildcard address
623	 * default to binding to an ipv4 address.
624	 */
625	if (host == NULL && hints.ai_family == AF_UNSPEC)
626		hints.ai_family = AF_INET;
627
628	if ((error = getaddrinfo(host, port, &hints, &res)))
629		errx(1, "getaddrinfo: %s", gai_strerror(error));
630
631	res0 = res;
632	do {
633		if ((s = socket(res0->ai_family, res0->ai_socktype,
634		    res0->ai_protocol)) < 0)
635			continue;
636
637		if (rdomain) {
638			if (setfib(rdomain) == -1)
639				err(1, "setfib");
640		}
641
642		ret = setsockopt(s, SOL_SOCKET, SO_REUSEPORT, &x, sizeof(x));
643		if (ret == -1)
644			err(1, NULL);
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		if (FreeBSD_Oflag) {
652			if (setsockopt(s, IPPROTO_TCP, TCP_NOOPT,
653			    &FreeBSD_Oflag, sizeof(FreeBSD_Oflag)) == -1)
654				err(1, "disable TCP options");
655		}
656
657		if (bind(s, (struct sockaddr *)res0->ai_addr,
658		    res0->ai_addrlen) == 0)
659			break;
660
661		close(s);
662		s = -1;
663	} while ((res0 = res0->ai_next) != NULL);
664
665	if (!uflag && s != -1) {
666		if (listen(s, 1) < 0)
667			err(1, "listen");
668	}
669
670	freeaddrinfo(res);
671
672	return (s);
673}
674
675/*
676 * readwrite()
677 * Loop that polls on the network file descriptor and stdin.
678 */
679void
680readwrite(int nfd)
681{
682	struct pollfd pfd[2];
683	unsigned char buf[8192];
684	int n, wfd = fileno(stdin);
685	int lfd = fileno(stdout);
686	int plen;
687
688	plen = jflag ? 8192 : 1024;
689
690	/* Setup Network FD */
691	pfd[0].fd = nfd;
692	pfd[0].events = POLLIN;
693
694	/* Set up STDIN FD. */
695	pfd[1].fd = wfd;
696	pfd[1].events = POLLIN;
697
698	while (pfd[0].fd != -1) {
699		if (iflag)
700			sleep(iflag);
701
702		if ((n = poll(pfd, 2 - dflag, timeout)) < 0) {
703			close(nfd);
704			err(1, "Polling Error");
705		}
706
707		if (n == 0)
708			return;
709
710		if (pfd[0].revents & POLLIN) {
711			if ((n = read(nfd, buf, plen)) < 0)
712				return;
713			else if (n == 0) {
714				shutdown(nfd, SHUT_RD);
715				pfd[0].fd = -1;
716				pfd[0].events = 0;
717			} else {
718				if (tflag)
719					atelnet(nfd, buf, n);
720				if (atomicio(vwrite, lfd, buf, n) != n)
721					return;
722			}
723		}
724
725		if (!dflag && pfd[1].revents & POLLIN) {
726			if ((n = read(wfd, buf, plen)) < 0)
727				return;
728			else if (n == 0) {
729				shutdown(nfd, SHUT_WR);
730				pfd[1].fd = -1;
731				pfd[1].events = 0;
732			} else {
733				if (atomicio(vwrite, nfd, buf, n) != n)
734					return;
735			}
736		}
737	}
738}
739
740/* Deal with RFC 854 WILL/WONT DO/DONT negotiation. */
741void
742atelnet(int nfd, unsigned char *buf, unsigned int size)
743{
744	unsigned char *p, *end;
745	unsigned char obuf[4];
746
747	if (size < 3)
748		return;
749	end = buf + size - 2;
750
751	for (p = buf; p < end; p++) {
752		if (*p != IAC)
753			continue;
754
755		obuf[0] = IAC;
756		p++;
757		if ((*p == WILL) || (*p == WONT))
758			obuf[1] = DONT;
759		else if ((*p == DO) || (*p == DONT))
760			obuf[1] = WONT;
761		else
762			continue;
763
764		p++;
765		obuf[2] = *p;
766		if (atomicio(vwrite, nfd, obuf, 3) != 3)
767			warn("Write Error!");
768	}
769}
770
771/*
772 * build_ports()
773 * Build an array or ports in portlist[], listing each port
774 * that we should try to connect to.
775 */
776void
777build_ports(char *p)
778{
779	const char *errstr;
780	char *n;
781	int hi, lo, cp;
782	int x = 0;
783
784	if ((n = strchr(p, '-')) != NULL) {
785		if (lflag)
786			errx(1, "Cannot use -l with multiple ports!");
787
788		*n = '\0';
789		n++;
790
791		/* Make sure the ports are in order: lowest->highest. */
792		hi = strtonum(n, 1, PORT_MAX, &errstr);
793		if (errstr)
794			errx(1, "port number %s: %s", errstr, n);
795		lo = strtonum(p, 1, PORT_MAX, &errstr);
796		if (errstr)
797			errx(1, "port number %s: %s", errstr, p);
798
799		if (lo > hi) {
800			cp = hi;
801			hi = lo;
802			lo = cp;
803		}
804
805		/* Load ports sequentially. */
806		for (cp = lo; cp <= hi; cp++) {
807			portlist[x] = calloc(1, PORT_MAX_LEN);
808			if (portlist[x] == NULL)
809				err(1, NULL);
810			snprintf(portlist[x], PORT_MAX_LEN, "%d", cp);
811			x++;
812		}
813
814		/* Randomly swap ports. */
815		if (rflag) {
816			int y;
817			char *c;
818
819			for (x = 0; x <= (hi - lo); x++) {
820				y = (arc4random() & 0xFFFF) % (hi - lo);
821				c = portlist[x];
822				portlist[x] = portlist[y];
823				portlist[y] = c;
824			}
825		}
826	} else {
827		hi = strtonum(p, 1, PORT_MAX, &errstr);
828		if (errstr)
829			errx(1, "port number %s: %s", errstr, p);
830		portlist[0] = calloc(1, PORT_MAX_LEN);
831		if (portlist[0] == NULL)
832			err(1, NULL);
833		portlist[0] = p;
834	}
835}
836
837/*
838 * udptest()
839 * Do a few writes to see if the UDP port is there.
840 * XXX - Better way of doing this? Doesn't work for IPv6.
841 * Also fails after around 100 ports checked.
842 */
843int
844udptest(int s)
845{
846	int i, ret;
847
848	for (i = 0; i <= 3; i++) {
849		if (write(s, "X", 1) == 1)
850			ret = 1;
851		else
852			ret = -1;
853	}
854	return (ret);
855}
856
857void
858set_common_sockopts(int s)
859{
860	int x = 1;
861
862	if (Sflag) {
863		if (setsockopt(s, IPPROTO_TCP, TCP_MD5SIG,
864			&x, sizeof(x)) == -1)
865			err(1, NULL);
866	}
867	if (Dflag) {
868		if (setsockopt(s, SOL_SOCKET, SO_DEBUG,
869			&x, sizeof(x)) == -1)
870			err(1, NULL);
871	}
872#ifdef SO_JUMBO
873	if (jflag) {
874		if (setsockopt(s, SOL_SOCKET, SO_JUMBO,
875			&x, sizeof(x)) == -1)
876			err(1, NULL);
877	}
878#endif
879	if (Tflag != -1) {
880		if (setsockopt(s, IPPROTO_IP, IP_TOS,
881		    &Tflag, sizeof(Tflag)) == -1)
882			err(1, "set IP ToS");
883	}
884	if (Iflag) {
885		if (setsockopt(s, SOL_SOCKET, SO_RCVBUF,
886		    &Iflag, sizeof(Iflag)) == -1)
887			err(1, "set TCP receive buffer size");
888	}
889	if (Oflag) {
890		if (setsockopt(s, SOL_SOCKET, SO_SNDBUF,
891		    &Oflag, sizeof(Oflag)) == -1)
892			err(1, "set TCP send buffer size");
893	}
894	if (FreeBSD_Oflag) {
895		if (setsockopt(s, IPPROTO_TCP, TCP_NOOPT,
896		    &FreeBSD_Oflag, sizeof(FreeBSD_Oflag)) == -1)
897			err(1, "disable TCP options");
898	}
899}
900
901int
902parse_iptos(char *s)
903{
904	int tos = -1;
905
906	if (strcmp(s, "lowdelay") == 0)
907		return (IPTOS_LOWDELAY);
908	if (strcmp(s, "throughput") == 0)
909		return (IPTOS_THROUGHPUT);
910	if (strcmp(s, "reliability") == 0)
911		return (IPTOS_RELIABILITY);
912
913	if (sscanf(s, "0x%x", &tos) != 1 || tos < 0 || tos > 0xff)
914		errx(1, "invalid IP Type of Service");
915	return (tos);
916}
917
918void
919help(void)
920{
921	usage(0);
922	fprintf(stderr, "\tCommand Summary:\n\
923	\t-4		Use IPv4\n\
924	\t-6		Use IPv6\n\
925	\t-D		Enable the debug socket option\n\
926	\t-d		Detach from stdin\n");
927#ifdef IPSEC
928	fprintf(stderr, "\
929	\t-E		Use IPsec ESP\n\
930	\t-e policy	Use specified IPsec policy\n");
931#endif
932	fprintf(stderr, "\
933	\t-h		This help text\n\
934	\t-I length	TCP receive buffer length\n\
935	\t-i secs\t	Delay interval for lines sent, ports scanned\n\
936	\t-k		Keep inbound sockets open for multiple connects\n\
937	\t-l		Listen mode, for inbound connects\n\
938	\t-n		Suppress name/port resolutions\n\
939	\t--no-tcpopt	Disable TCP options\n\
940	\t-O length	TCP send buffer length\n\
941	\t-P proxyuser\tUsername for proxy authentication\n\
942	\t-p port\t	Specify local port for remote connects\n\
943	\t-r		Randomize remote ports\n\
944	\t-S		Enable the TCP MD5 signature option\n\
945	\t-s addr\t	Local source address\n\
946	\t-T ToS\t	Set IP Type of Service\n\
947	\t-t		Answer TELNET negotiation\n\
948	\t-U		Use UNIX domain socket\n\
949	\t-u		UDP mode\n\
950	\t-V fib	Specify alternate routing table (FIB)\n\
951	\t-v		Verbose\n\
952	\t-w secs\t	Timeout for connects and final net reads\n\
953	\t-X proto	Proxy protocol: \"4\", \"5\" (SOCKS) or \"connect\"\n\
954	\t-x addr[:port]\tSpecify proxy address and port\n\
955	\t-z		Zero-I/O mode [used for scanning]\n\
956	Port numbers can be individual or ranges: lo-hi [inclusive]\n");
957#ifdef IPSEC
958	fprintf(stderr, "See ipsec_set_policy(3) for -e argument format\n");
959#endif
960	exit(1);
961}
962
963#ifdef IPSEC
964void
965add_ipsec_policy(int s, char *policy)
966{
967	char *raw;
968	int e;
969
970	raw = ipsec_set_policy(policy, strlen(policy));
971	if (raw == NULL)
972		errx(1, "ipsec_set_policy `%s': %s", policy,
973		     ipsec_strerror());
974	e = setsockopt(s, IPPROTO_IP, IP_IPSEC_POLICY, raw,
975			ipsec_get_policylen(raw));
976	if (e < 0)
977		err(1, "ipsec policy cannot be configured");
978	free(raw);
979	if (vflag)
980		fprintf(stderr, "ipsec policy configured: `%s'\n", policy);
981	return;
982}
983#endif /* IPSEC */
984
985void
986usage(int ret)
987{
988	fprintf(stderr,
989#ifdef IPSEC
990	    "usage: nc [-46DdEhklnrStUuvz] [-e policy] [-I length] [-i interval] [-O length]\n"
991#else
992	    "usage: nc [-46DdhklnrStUuvz] [-I length] [-i interval] [-O length]\n"
993#endif
994	    "\t  [-P proxy_username] [-p source_port] [-s source_ip_address] [-T ToS]\n"
995	    "\t  [-V fib] [-w timeout] [-X proxy_protocol]\n"
996	    "\t  [-x proxy_address[:port]] [hostname] [port]\n");
997	if (ret)
998		exit(1);
999}
1000