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