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