netcat.c revision 206675
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 206675 2010-04-15 19:15: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/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#ifdef SO_BINDANY
574			/* try SO_BINDANY, but don't insist */
575			setsockopt(s, SOL_SOCKET, SO_BINDANY, &on, sizeof(on));
576#endif
577			memset(&ahints, 0, sizeof(struct addrinfo));
578			ahints.ai_family = res0->ai_family;
579			ahints.ai_socktype = uflag ? SOCK_DGRAM : SOCK_STREAM;
580			ahints.ai_protocol = uflag ? IPPROTO_UDP : IPPROTO_TCP;
581			ahints.ai_flags = AI_PASSIVE;
582			if ((error = getaddrinfo(sflag, pflag, &ahints, &ares)))
583				errx(1, "getaddrinfo: %s", gai_strerror(error));
584
585			if (bind(s, (struct sockaddr *)ares->ai_addr,
586			    ares->ai_addrlen) < 0)
587				errx(1, "bind failed: %s", strerror(errno));
588			freeaddrinfo(ares);
589		}
590
591		set_common_sockopts(s);
592
593		if (connect(s, res0->ai_addr, res0->ai_addrlen) == 0)
594			break;
595		else if (vflag)
596			warn("connect to %s port %s (%s) failed", host, port,
597			    uflag ? "udp" : "tcp");
598
599		close(s);
600		s = -1;
601	} while ((res0 = res0->ai_next) != NULL);
602
603	freeaddrinfo(res);
604
605	return (s);
606}
607
608/*
609 * local_listen()
610 * Returns a socket listening on a local port, binds to specified source
611 * address. Returns -1 on failure.
612 */
613int
614local_listen(char *host, char *port, struct addrinfo hints)
615{
616	struct addrinfo *res, *res0;
617	int s, ret, x = 1;
618	int error;
619
620	/* Allow nodename to be null. */
621	hints.ai_flags |= AI_PASSIVE;
622
623	/*
624	 * In the case of binding to a wildcard address
625	 * default to binding to an ipv4 address.
626	 */
627	if (host == NULL && hints.ai_family == AF_UNSPEC)
628		hints.ai_family = AF_INET;
629
630	if ((error = getaddrinfo(host, port, &hints, &res)))
631		errx(1, "getaddrinfo: %s", gai_strerror(error));
632
633	res0 = res;
634	do {
635		if ((s = socket(res0->ai_family, res0->ai_socktype,
636		    res0->ai_protocol)) < 0)
637			continue;
638
639		if (rdomain) {
640			if (setfib(rdomain) == -1)
641				err(1, "setfib");
642		}
643
644		ret = setsockopt(s, SOL_SOCKET, SO_REUSEPORT, &x, sizeof(x));
645		if (ret == -1)
646			err(1, NULL);
647#ifdef IPSEC
648		if (ipsec_policy[0] != NULL)
649			add_ipsec_policy(s, ipsec_policy[0]);
650		if (ipsec_policy[1] != NULL)
651			add_ipsec_policy(s, ipsec_policy[1]);
652#endif
653		if (FreeBSD_Oflag) {
654			if (setsockopt(s, IPPROTO_TCP, TCP_NOOPT,
655			    &FreeBSD_Oflag, sizeof(FreeBSD_Oflag)) == -1)
656				err(1, "disable TCP options");
657		}
658
659		if (bind(s, (struct sockaddr *)res0->ai_addr,
660		    res0->ai_addrlen) == 0)
661			break;
662
663		close(s);
664		s = -1;
665	} while ((res0 = res0->ai_next) != NULL);
666
667	if (!uflag && s != -1) {
668		if (listen(s, 1) < 0)
669			err(1, "listen");
670	}
671
672	freeaddrinfo(res);
673
674	return (s);
675}
676
677/*
678 * readwrite()
679 * Loop that polls on the network file descriptor and stdin.
680 */
681void
682readwrite(int nfd)
683{
684	struct pollfd pfd[2];
685	unsigned char buf[8192];
686	int n, wfd = fileno(stdin);
687	int lfd = fileno(stdout);
688	int plen;
689
690	plen = jflag ? 8192 : 1024;
691
692	/* Setup Network FD */
693	pfd[0].fd = nfd;
694	pfd[0].events = POLLIN;
695
696	/* Set up STDIN FD. */
697	pfd[1].fd = wfd;
698	pfd[1].events = POLLIN;
699
700	while (pfd[0].fd != -1) {
701		if (iflag)
702			sleep(iflag);
703
704		if ((n = poll(pfd, 2 - dflag, timeout)) < 0) {
705			close(nfd);
706			err(1, "Polling Error");
707		}
708
709		if (n == 0)
710			return;
711
712		if (pfd[0].revents & POLLIN) {
713			if ((n = read(nfd, buf, plen)) < 0)
714				return;
715			else if (n == 0) {
716				shutdown(nfd, SHUT_RD);
717				pfd[0].fd = -1;
718				pfd[0].events = 0;
719			} else {
720				if (tflag)
721					atelnet(nfd, buf, n);
722				if (atomicio(vwrite, lfd, buf, n) != n)
723					return;
724			}
725		}
726
727		if (!dflag && pfd[1].revents & POLLIN) {
728			if ((n = read(wfd, buf, plen)) < 0)
729				return;
730			else if (n == 0) {
731				shutdown(nfd, SHUT_WR);
732				pfd[1].fd = -1;
733				pfd[1].events = 0;
734			} else {
735				if (atomicio(vwrite, nfd, buf, n) != n)
736					return;
737			}
738		}
739	}
740}
741
742/* Deal with RFC 854 WILL/WONT DO/DONT negotiation. */
743void
744atelnet(int nfd, unsigned char *buf, unsigned int size)
745{
746	unsigned char *p, *end;
747	unsigned char obuf[4];
748
749	if (size < 3)
750		return;
751	end = buf + size - 2;
752
753	for (p = buf; p < end; p++) {
754		if (*p != IAC)
755			continue;
756
757		obuf[0] = IAC;
758		p++;
759		if ((*p == WILL) || (*p == WONT))
760			obuf[1] = DONT;
761		else if ((*p == DO) || (*p == DONT))
762			obuf[1] = WONT;
763		else
764			continue;
765
766		p++;
767		obuf[2] = *p;
768		if (atomicio(vwrite, nfd, obuf, 3) != 3)
769			warn("Write Error!");
770	}
771}
772
773/*
774 * build_ports()
775 * Build an array or ports in portlist[], listing each port
776 * that we should try to connect to.
777 */
778void
779build_ports(char *p)
780{
781	const char *errstr;
782	char *n;
783	int hi, lo, cp;
784	int x = 0;
785
786	if ((n = strchr(p, '-')) != NULL) {
787		if (lflag)
788			errx(1, "Cannot use -l with multiple ports!");
789
790		*n = '\0';
791		n++;
792
793		/* Make sure the ports are in order: lowest->highest. */
794		hi = strtonum(n, 1, PORT_MAX, &errstr);
795		if (errstr)
796			errx(1, "port number %s: %s", errstr, n);
797		lo = strtonum(p, 1, PORT_MAX, &errstr);
798		if (errstr)
799			errx(1, "port number %s: %s", errstr, p);
800
801		if (lo > hi) {
802			cp = hi;
803			hi = lo;
804			lo = cp;
805		}
806
807		/* Load ports sequentially. */
808		for (cp = lo; cp <= hi; cp++) {
809			portlist[x] = calloc(1, PORT_MAX_LEN);
810			if (portlist[x] == NULL)
811				err(1, NULL);
812			snprintf(portlist[x], PORT_MAX_LEN, "%d", cp);
813			x++;
814		}
815
816		/* Randomly swap ports. */
817		if (rflag) {
818			int y;
819			char *c;
820
821			for (x = 0; x <= (hi - lo); x++) {
822				y = (arc4random() & 0xFFFF) % (hi - lo);
823				c = portlist[x];
824				portlist[x] = portlist[y];
825				portlist[y] = c;
826			}
827		}
828	} else {
829		hi = strtonum(p, 1, PORT_MAX, &errstr);
830		if (errstr)
831			errx(1, "port number %s: %s", errstr, p);
832		portlist[0] = calloc(1, PORT_MAX_LEN);
833		if (portlist[0] == NULL)
834			err(1, NULL);
835		portlist[0] = p;
836	}
837}
838
839/*
840 * udptest()
841 * Do a few writes to see if the UDP port is there.
842 * XXX - Better way of doing this? Doesn't work for IPv6.
843 * Also fails after around 100 ports checked.
844 */
845int
846udptest(int s)
847{
848	int i, ret;
849
850	for (i = 0; i <= 3; i++) {
851		if (write(s, "X", 1) == 1)
852			ret = 1;
853		else
854			ret = -1;
855	}
856	return (ret);
857}
858
859void
860set_common_sockopts(int s)
861{
862	int x = 1;
863
864	if (Sflag) {
865		if (setsockopt(s, IPPROTO_TCP, TCP_MD5SIG,
866			&x, sizeof(x)) == -1)
867			err(1, NULL);
868	}
869	if (Dflag) {
870		if (setsockopt(s, SOL_SOCKET, SO_DEBUG,
871			&x, sizeof(x)) == -1)
872			err(1, NULL);
873	}
874#ifdef SO_JUMBO
875	if (jflag) {
876		if (setsockopt(s, SOL_SOCKET, SO_JUMBO,
877			&x, sizeof(x)) == -1)
878			err(1, NULL);
879	}
880#endif
881	if (Tflag != -1) {
882		if (setsockopt(s, IPPROTO_IP, IP_TOS,
883		    &Tflag, sizeof(Tflag)) == -1)
884			err(1, "set IP ToS");
885	}
886	if (Iflag) {
887		if (setsockopt(s, SOL_SOCKET, SO_RCVBUF,
888		    &Iflag, sizeof(Iflag)) == -1)
889			err(1, "set TCP receive buffer size");
890	}
891	if (Oflag) {
892		if (setsockopt(s, SOL_SOCKET, SO_SNDBUF,
893		    &Oflag, sizeof(Oflag)) == -1)
894			err(1, "set TCP send buffer size");
895	}
896	if (FreeBSD_Oflag) {
897		if (setsockopt(s, IPPROTO_TCP, TCP_NOOPT,
898		    &FreeBSD_Oflag, sizeof(FreeBSD_Oflag)) == -1)
899			err(1, "disable TCP options");
900	}
901}
902
903int
904parse_iptos(char *s)
905{
906	int tos = -1;
907
908	if (strcmp(s, "lowdelay") == 0)
909		return (IPTOS_LOWDELAY);
910	if (strcmp(s, "throughput") == 0)
911		return (IPTOS_THROUGHPUT);
912	if (strcmp(s, "reliability") == 0)
913		return (IPTOS_RELIABILITY);
914
915	if (sscanf(s, "0x%x", &tos) != 1 || tos < 0 || tos > 0xff)
916		errx(1, "invalid IP Type of Service");
917	return (tos);
918}
919
920void
921help(void)
922{
923	usage(0);
924	fprintf(stderr, "\tCommand Summary:\n\
925	\t-4		Use IPv4\n\
926	\t-6		Use IPv6\n\
927	\t-D		Enable the debug socket option\n\
928	\t-d		Detach from stdin\n");
929#ifdef IPSEC
930	fprintf(stderr, "\
931	\t-E		Use IPsec ESP\n\
932	\t-e policy	Use specified IPsec policy\n");
933#endif
934	fprintf(stderr, "\
935	\t-h		This help text\n\
936	\t-I length	TCP receive buffer length\n\
937	\t-i secs\t	Delay interval for lines sent, ports scanned\n\
938	\t-k		Keep inbound sockets open for multiple connects\n\
939	\t-l		Listen mode, for inbound connects\n\
940	\t-n		Suppress name/port resolutions\n\
941	\t--no-tcpopt	Disable TCP options\n\
942	\t-O length	TCP send buffer length\n\
943	\t-P proxyuser\tUsername for proxy authentication\n\
944	\t-p port\t	Specify local port for remote connects\n\
945	\t-r		Randomize remote ports\n\
946	\t-S		Enable the TCP MD5 signature option\n\
947	\t-s addr\t	Local source address\n\
948	\t-T ToS\t	Set IP Type of Service\n\
949	\t-t		Answer TELNET negotiation\n\
950	\t-U		Use UNIX domain socket\n\
951	\t-u		UDP mode\n\
952	\t-V fib	Specify alternate routing table (FIB)\n\
953	\t-v		Verbose\n\
954	\t-w secs\t	Timeout for connects and final net reads\n\
955	\t-X proto	Proxy protocol: \"4\", \"5\" (SOCKS) or \"connect\"\n\
956	\t-x addr[:port]\tSpecify proxy address and port\n\
957	\t-z		Zero-I/O mode [used for scanning]\n\
958	Port numbers can be individual or ranges: lo-hi [inclusive]\n");
959#ifdef IPSEC
960	fprintf(stderr, "See ipsec_set_policy(3) for -e argument format\n");
961#endif
962	exit(1);
963}
964
965#ifdef IPSEC
966void
967add_ipsec_policy(int s, char *policy)
968{
969	char *raw;
970	int e;
971
972	raw = ipsec_set_policy(policy, strlen(policy));
973	if (raw == NULL)
974		errx(1, "ipsec_set_policy `%s': %s", policy,
975		     ipsec_strerror());
976	e = setsockopt(s, IPPROTO_IP, IP_IPSEC_POLICY, raw,
977			ipsec_get_policylen(raw));
978	if (e < 0)
979		err(1, "ipsec policy cannot be configured");
980	free(raw);
981	if (vflag)
982		fprintf(stderr, "ipsec policy configured: `%s'\n", policy);
983	return;
984}
985#endif /* IPSEC */
986
987void
988usage(int ret)
989{
990	fprintf(stderr,
991#ifdef IPSEC
992	    "usage: nc [-46DdEhklnrStUuvz] [-e policy] [-I length] [-i interval] [-O length]\n"
993#else
994	    "usage: nc [-46DdhklnrStUuvz] [-I length] [-i interval] [-O length]\n"
995#endif
996	    "\t  [-P proxy_username] [-p source_port] [-s source_ip_address] [-T ToS]\n"
997	    "\t  [-V fib] [-w timeout] [-X proxy_protocol]\n"
998	    "\t  [-x proxy_address[:port]] [hostname] [port]\n");
999	if (ret)
1000		exit(1);
1001}
1002