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