1/* $OpenBSD: netcat.c,v 1.130 2015/07/26 19:12:28 chl 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/sysctl.h>
40#include <sys/time.h>
41#include <sys/uio.h>
42#include <sys/un.h>
43
44#include <netinet/in.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 <fcntl.h>
56#include <limits.h>
57#include <netdb.h>
58#include <poll.h>
59#include <signal.h>
60#include <stdarg.h>
61#include <stdio.h>
62#include <stdlib.h>
63#include <string.h>
64#include <unistd.h>
65#include "atomicio.h"
66
67#ifndef SUN_LEN
68#define SUN_LEN(su) \
69	(sizeof(*(su)) - sizeof((su)->sun_path) + strlen((su)->sun_path))
70#endif
71
72#define PORT_MAX	65535
73#define PORT_MAX_LEN	6
74#define UNIX_DG_TMP_SOCKET_SIZE	19
75
76#define POLL_STDIN 0
77#define POLL_NETOUT 1
78#define POLL_NETIN 2
79#define POLL_STDOUT 3
80#define BUFSIZE 16384
81
82/* Command Line Options */
83int	dflag;					/* detached, no stdin */
84int	Fflag;					/* fdpass sock to stdout */
85unsigned int iflag;				/* Interval Flag */
86int	kflag;					/* More than one connect */
87int	lflag;					/* Bind to local port */
88int	Nflag;					/* shutdown() network socket */
89int	nflag;					/* Don't do name look up */
90int	FreeBSD_Oflag;				/* Do not use TCP options */
91int	FreeBSD_sctp;				/* Use SCTP */
92char   *Pflag;					/* Proxy username */
93char   *pflag;					/* Localport flag */
94int	rflag;					/* Random ports flag */
95char   *sflag;					/* Source Address */
96int	tflag;					/* Telnet Emulation */
97int	uflag;					/* UDP - Default to TCP */
98int	vflag;					/* Verbosity */
99int	xflag;					/* Socks proxy */
100int	zflag;					/* Port Scan Flag */
101int	Dflag;					/* sodebug */
102int	Iflag;					/* TCP receive buffer size */
103int	Oflag;					/* TCP send buffer size */
104int	Sflag;					/* TCP MD5 signature option */
105int	Tflag = -1;				/* IP Type of Service */
106int	rtableid = -1;
107
108int timeout = -1;
109int family = AF_UNSPEC;
110char *portlist[PORT_MAX+1];
111char *unix_dg_tmp_socket;
112
113void	atelnet(int, unsigned char *, unsigned int);
114void	build_ports(char *);
115void	help(void);
116int	local_listen(char *, char *, struct addrinfo);
117void	readwrite(int);
118void	fdpass(int nfd) __attribute__((noreturn));
119int	remote_connect(const char *, const char *, struct addrinfo);
120int	timeout_connect(int, const struct sockaddr *, socklen_t);
121int	socks_connect(const char *, const char *, struct addrinfo,
122	    const char *, const char *, struct addrinfo, int, const char *);
123int	udptest(int);
124int	unix_bind(char *);
125int	unix_connect(char *);
126int	unix_listen(char *);
127void	set_common_sockopts(int, int);
128int	map_tos(char *, int *);
129void	report_connect(const struct sockaddr *, socklen_t);
130void	usage(int);
131ssize_t drainbuf(int, unsigned char *, size_t *);
132ssize_t fillbuf(int, unsigned char *, size_t *);
133
134#ifdef IPSEC
135void	add_ipsec_policy(int, int, char *);
136
137char	*ipsec_policy[2];
138#endif
139
140int
141main(int argc, char *argv[])
142{
143	int ch, s, ret, socksv, ipsec_count;
144	int numfibs;
145	size_t intsize = sizeof(int);
146	char *host, *uport;
147	struct addrinfo hints;
148	struct servent *sv;
149	socklen_t len;
150	struct sockaddr_storage cliaddr;
151	char *proxy;
152	const char *errstr, *proxyhost = "", *proxyport = NULL;
153	struct addrinfo proxyhints;
154	char unix_dg_tmp_socket_buf[UNIX_DG_TMP_SOCKET_SIZE];
155	struct option longopts[] = {
156		{ "no-tcpopt",	no_argument,	&FreeBSD_Oflag,	1 },
157		{ "sctp",	no_argument,	&FreeBSD_sctp,	1 },
158		{ NULL,		0,		NULL,		0 }
159	};
160
161	ret = 1;
162	ipsec_count = 0;
163	s = 0;
164	socksv = 5;
165	host = NULL;
166	uport = NULL;
167	sv = NULL;
168
169	signal(SIGPIPE, SIG_IGN);
170
171	while ((ch = getopt_long(argc, argv,
172	    "46DdEe:FhI:i:klNnoO:P:p:rSs:tT:UuV:vw:X:x:z",
173	    longopts, NULL)) != -1) {
174		switch (ch) {
175		case '4':
176			family = AF_INET;
177			break;
178		case '6':
179			family = AF_INET6;
180			break;
181		case 'U':
182			family = AF_UNIX;
183			break;
184		case 'X':
185			if (strcasecmp(optarg, "connect") == 0)
186				socksv = -1; /* HTTP proxy CONNECT */
187			else if (strcmp(optarg, "4") == 0)
188				socksv = 4; /* SOCKS v.4 */
189			else if (strcmp(optarg, "5") == 0)
190				socksv = 5; /* SOCKS v.5 */
191			else
192				errx(1, "unsupported proxy protocol");
193			break;
194		case 'd':
195			dflag = 1;
196			break;
197		case 'e':
198#ifdef IPSEC
199			ipsec_policy[ipsec_count++ % 2] = optarg;
200#else
201			errx(1, "IPsec support unavailable.");
202#endif
203			break;
204		case 'E':
205#ifdef IPSEC
206			ipsec_policy[0] = "in  ipsec esp/transport//require";
207			ipsec_policy[1] = "out ipsec esp/transport//require";
208#else
209			errx(1, "IPsec support unavailable.");
210#endif
211			break;
212		case 'F':
213			Fflag = 1;
214			break;
215		case 'h':
216			help();
217			break;
218		case 'i':
219			iflag = strtonum(optarg, 0, UINT_MAX, &errstr);
220			if (errstr)
221				errx(1, "interval %s: %s", errstr, optarg);
222			break;
223		case 'k':
224			kflag = 1;
225			break;
226		case 'l':
227			lflag = 1;
228			break;
229		case 'N':
230			Nflag = 1;
231			break;
232		case 'n':
233			nflag = 1;
234			break;
235		case 'o':
236			fprintf(stderr, "option -o is deprecated.\n");
237			break;
238		case 'P':
239			Pflag = optarg;
240			break;
241		case 'p':
242			pflag = optarg;
243			break;
244		case 'r':
245			rflag = 1;
246			break;
247		case 's':
248			sflag = optarg;
249			break;
250		case 't':
251			tflag = 1;
252			break;
253		case 'u':
254			uflag = 1;
255			break;
256		case 'V':
257			if (sysctlbyname("net.fibs", &numfibs, &intsize, NULL, 0) == -1)
258				errx(1, "Multiple FIBS not supported");
259			rtableid = (int)strtonum(optarg, 0,
260			    numfibs - 1, &errstr);
261			if (errstr)
262				errx(1, "rtable %s: %s", errstr, optarg);
263			break;
264		case 'v':
265			vflag = 1;
266			break;
267		case 'w':
268			timeout = strtonum(optarg, 0, INT_MAX / 1000, &errstr);
269			if (errstr)
270				errx(1, "timeout %s: %s", errstr, optarg);
271			timeout *= 1000;
272			break;
273		case 'x':
274			xflag = 1;
275			if ((proxy = strdup(optarg)) == NULL)
276				err(1, NULL);
277			break;
278		case 'z':
279			zflag = 1;
280			break;
281		case 'D':
282			Dflag = 1;
283			break;
284		case 'I':
285			Iflag = strtonum(optarg, 1, 65536 << 14, &errstr);
286			if (errstr != NULL)
287				errx(1, "TCP receive window %s: %s",
288				    errstr, optarg);
289			break;
290		case 'O':
291			Oflag = strtonum(optarg, 1, 65536 << 14, &errstr);
292			if (errstr != NULL) {
293			    if (strcmp(errstr, "invalid") != 0)
294				errx(1, "TCP send window %s: %s",
295				    errstr, optarg);
296			}
297			break;
298		case 'S':
299			Sflag = 1;
300			break;
301		case 'T':
302			errstr = NULL;
303			errno = 0;
304			if (map_tos(optarg, &Tflag))
305				break;
306			if (strlen(optarg) > 1 && optarg[0] == '0' &&
307			    optarg[1] == 'x')
308				Tflag = (int)strtol(optarg, NULL, 16);
309			else
310				Tflag = (int)strtonum(optarg, 0, 255,
311				    &errstr);
312			if (Tflag < 0 || Tflag > 255 || errstr || errno)
313				errx(1, "illegal tos value %s", optarg);
314			break;
315		case 0:
316			/* Long option. */
317			break;
318		default:
319			usage(1);
320		}
321	}
322	argc -= optind;
323	argv += optind;
324
325	/* Cruft to make sure options are clean, and used properly. */
326	if (argv[0] && !argv[1] && family == AF_UNIX) {
327		host = argv[0];
328		uport = NULL;
329	} else if (argv[0] && !argv[1]) {
330		if  (!lflag)
331			usage(1);
332		uport = argv[0];
333		host = NULL;
334	} else if (argv[0] && argv[1]) {
335		host = argv[0];
336		uport = argv[1];
337	} else
338		usage(1);
339
340	if (lflag && sflag)
341		errx(1, "cannot use -s and -l");
342	if (lflag && pflag)
343		errx(1, "cannot use -p and -l");
344	if (lflag && zflag)
345		errx(1, "cannot use -z and -l");
346	if (!lflag && kflag)
347		errx(1, "must use -l with -k");
348	if (FreeBSD_sctp) {
349		if (uflag)
350			errx(1, "cannot use -u and --sctp");
351		if (family == AF_UNIX)
352			errx(1, "cannot use -U and --sctp");
353	}
354
355	/* Get name of temporary socket for unix datagram client */
356	if ((family == AF_UNIX) && uflag && !lflag) {
357		if (sflag) {
358			unix_dg_tmp_socket = sflag;
359		} else {
360			strlcpy(unix_dg_tmp_socket_buf, "/tmp/nc.XXXXXXXXXX",
361				UNIX_DG_TMP_SOCKET_SIZE);
362			if (mktemp(unix_dg_tmp_socket_buf) == NULL)
363				err(1, "mktemp");
364			unix_dg_tmp_socket = unix_dg_tmp_socket_buf;
365		}
366	}
367
368	/* Initialize addrinfo structure. */
369	if (family != AF_UNIX) {
370		memset(&hints, 0, sizeof(struct addrinfo));
371		hints.ai_family = family;
372		hints.ai_socktype = uflag ? SOCK_DGRAM : SOCK_STREAM;
373		hints.ai_protocol = uflag ? IPPROTO_UDP :
374		    FreeBSD_sctp ? IPPROTO_SCTP : IPPROTO_TCP;
375		if (nflag)
376			hints.ai_flags |= AI_NUMERICHOST;
377	}
378
379	if (xflag) {
380		if (uflag)
381			errx(1, "no proxy support for UDP mode");
382
383		if (FreeBSD_sctp)
384			errx(1, "no proxy support for SCTP mode");
385
386		if (lflag)
387			errx(1, "no proxy support for listen");
388
389		if (family == AF_UNIX)
390			errx(1, "no proxy support for unix sockets");
391
392		/* XXX IPv6 transport to proxy would probably work */
393		if (family == AF_INET6)
394			errx(1, "no proxy support for IPv6");
395
396		if (sflag)
397			errx(1, "no proxy support for local source address");
398
399		proxyhost = strsep(&proxy, ":");
400		proxyport = proxy;
401
402		memset(&proxyhints, 0, sizeof(struct addrinfo));
403		proxyhints.ai_family = family;
404		proxyhints.ai_socktype = SOCK_STREAM;
405		proxyhints.ai_protocol = IPPROTO_TCP;
406		if (nflag)
407			proxyhints.ai_flags |= AI_NUMERICHOST;
408	}
409
410	if (lflag) {
411		int connfd;
412		ret = 0;
413
414		if (family == AF_UNIX) {
415			if (uflag)
416				s = unix_bind(host);
417			else
418				s = unix_listen(host);
419		}
420
421		/* Allow only one connection at a time, but stay alive. */
422		for (;;) {
423			if (family != AF_UNIX)
424				s = local_listen(host, uport, hints);
425			if (s < 0)
426				err(1, NULL);
427			/*
428			 * For UDP and -k, don't connect the socket, let it
429			 * receive datagrams from multiple socket pairs.
430			 */
431			if (uflag && kflag)
432				readwrite(s);
433			/*
434			 * For UDP and not -k, we will use recvfrom() initially
435			 * to wait for a caller, then use the regular functions
436			 * to talk to the caller.
437			 */
438			else if (uflag && !kflag) {
439				int rv, plen;
440				char buf[16384];
441				struct sockaddr_storage z;
442
443				len = sizeof(z);
444				plen = 2048;
445				rv = recvfrom(s, buf, plen, MSG_PEEK,
446				    (struct sockaddr *)&z, &len);
447				if (rv < 0)
448					err(1, "recvfrom");
449
450				rv = connect(s, (struct sockaddr *)&z, len);
451				if (rv < 0)
452					err(1, "connect");
453
454				if (vflag)
455					report_connect((struct sockaddr *)&z, len);
456
457				readwrite(s);
458			} else {
459				len = sizeof(cliaddr);
460				connfd = accept(s, (struct sockaddr *)&cliaddr,
461				    &len);
462				if (connfd == -1) {
463					/* For now, all errnos are fatal */
464					err(1, "accept");
465				}
466				if (vflag)
467					report_connect((struct sockaddr *)&cliaddr, len);
468
469				readwrite(connfd);
470				close(connfd);
471			}
472
473			if (family != AF_UNIX)
474				close(s);
475			else if (uflag) {
476				if (connect(s, NULL, 0) < 0)
477					err(1, "connect");
478			}
479
480			if (!kflag)
481				break;
482		}
483	} else if (family == AF_UNIX) {
484		ret = 0;
485
486		if ((s = unix_connect(host)) > 0 && !zflag) {
487			readwrite(s);
488			close(s);
489		} else
490			ret = 1;
491
492		if (uflag)
493			unlink(unix_dg_tmp_socket);
494		exit(ret);
495
496	} else {
497		int i = 0;
498
499		/* Construct the portlist[] array. */
500		build_ports(uport);
501
502		/* Cycle through portlist, connecting to each port. */
503		for (i = 0; portlist[i] != NULL; i++) {
504			if (s)
505				close(s);
506
507			if (xflag)
508				s = socks_connect(host, portlist[i], hints,
509				    proxyhost, proxyport, proxyhints, socksv,
510				    Pflag);
511			else
512				s = remote_connect(host, portlist[i], hints);
513
514			if (s < 0)
515				continue;
516
517			ret = 0;
518			if (vflag || zflag) {
519				/* For UDP, make sure we are connected. */
520				if (uflag) {
521					if (udptest(s) == -1) {
522						ret = 1;
523						continue;
524					}
525				}
526
527				/* Don't look up port if -n. */
528				if (nflag)
529					sv = NULL;
530				else {
531					sv = getservbyport(
532					    ntohs(atoi(portlist[i])),
533					    uflag ? "udp" : "tcp");
534				}
535
536				fprintf(stderr,
537				    "Connection to %s %s port [%s/%s] "
538				    "succeeded!\n", host, portlist[i],
539				    uflag ? "udp" : "tcp",
540				    sv ? sv->s_name : "*");
541			}
542			if (Fflag)
543				fdpass(s);
544			else if (!zflag)
545				readwrite(s);
546		}
547	}
548
549	if (s)
550		close(s);
551
552	exit(ret);
553}
554
555/*
556 * unix_bind()
557 * Returns a unix socket bound to the given path
558 */
559int
560unix_bind(char *path)
561{
562	struct sockaddr_un sun;
563	int s;
564
565	/* Create unix domain socket. */
566	if ((s = socket(AF_UNIX, uflag ? SOCK_DGRAM : SOCK_STREAM,
567	     0)) < 0)
568		return (-1);
569
570	memset(&sun, 0, sizeof(struct sockaddr_un));
571	sun.sun_family = AF_UNIX;
572
573	if (strlcpy(sun.sun_path, path, sizeof(sun.sun_path)) >=
574	    sizeof(sun.sun_path)) {
575		close(s);
576		errno = ENAMETOOLONG;
577		return (-1);
578	}
579
580	if (bind(s, (struct sockaddr *)&sun, SUN_LEN(&sun)) < 0) {
581		close(s);
582		return (-1);
583	}
584	return (s);
585}
586
587/*
588 * unix_connect()
589 * Returns a socket connected to a local unix socket. Returns -1 on failure.
590 */
591int
592unix_connect(char *path)
593{
594	struct sockaddr_un sun;
595	int s;
596
597	if (uflag) {
598		if ((s = unix_bind(unix_dg_tmp_socket)) < 0)
599			return (-1);
600	} else {
601		if ((s = socket(AF_UNIX, SOCK_STREAM, 0)) < 0)
602			return (-1);
603	}
604	(void)fcntl(s, F_SETFD, FD_CLOEXEC);
605
606	memset(&sun, 0, sizeof(struct sockaddr_un));
607	sun.sun_family = AF_UNIX;
608
609	if (strlcpy(sun.sun_path, path, sizeof(sun.sun_path)) >=
610	    sizeof(sun.sun_path)) {
611		close(s);
612		errno = ENAMETOOLONG;
613		return (-1);
614	}
615	if (connect(s, (struct sockaddr *)&sun, SUN_LEN(&sun)) < 0) {
616		close(s);
617		return (-1);
618	}
619	return (s);
620
621}
622
623/*
624 * unix_listen()
625 * Create a unix domain socket, and listen on it.
626 */
627int
628unix_listen(char *path)
629{
630	int s;
631	if ((s = unix_bind(path)) < 0)
632		return (-1);
633
634	if (listen(s, 5) < 0) {
635		close(s);
636		return (-1);
637	}
638	return (s);
639}
640
641/*
642 * remote_connect()
643 * Returns a socket connected to a remote host. Properly binds to a local
644 * port or source address if needed. Returns -1 on failure.
645 */
646int
647remote_connect(const char *host, const char *port, struct addrinfo hints)
648{
649	struct addrinfo *res, *res0;
650	int s, error, on = 1;
651
652	if ((error = getaddrinfo(host, port, &hints, &res)))
653		errx(1, "getaddrinfo: %s", gai_strerror(error));
654
655	res0 = res;
656	do {
657		if ((s = socket(res0->ai_family, res0->ai_socktype,
658		    res0->ai_protocol)) < 0)
659			continue;
660
661		if (rtableid >= 0 && (setsockopt(s, SOL_SOCKET, SO_SETFIB,
662		    &rtableid, sizeof(rtableid)) == -1))
663			err(1, "setsockopt SO_SETFIB");
664
665		/* Bind to a local port or source address if specified. */
666		if (sflag || pflag) {
667			struct addrinfo ahints, *ares;
668
669			/* try IP_BINDANY, but don't insist */
670			setsockopt(s, IPPROTO_IP, IP_BINDANY, &on, sizeof(on));
671			memset(&ahints, 0, sizeof(struct addrinfo));
672			ahints.ai_family = res0->ai_family;
673			ahints.ai_socktype = uflag ? SOCK_DGRAM : SOCK_STREAM;
674			ahints.ai_protocol = uflag ? IPPROTO_UDP : IPPROTO_TCP;
675			ahints.ai_flags = AI_PASSIVE;
676			if ((error = getaddrinfo(sflag, pflag, &ahints, &ares)))
677				errx(1, "getaddrinfo: %s", gai_strerror(error));
678
679			if (bind(s, (struct sockaddr *)ares->ai_addr,
680			    ares->ai_addrlen) < 0)
681				err(1, "bind failed");
682			freeaddrinfo(ares);
683		}
684
685		set_common_sockopts(s, res0->ai_family);
686
687		if (timeout_connect(s, res0->ai_addr, res0->ai_addrlen) == 0)
688			break;
689		else if (vflag)
690			warn("connect to %s port %s (%s) failed", host, port,
691			    uflag ? "udp" : "tcp");
692
693		close(s);
694		s = -1;
695	} while ((res0 = res0->ai_next) != NULL);
696
697	freeaddrinfo(res);
698
699	return (s);
700}
701
702int
703timeout_connect(int s, const struct sockaddr *name, socklen_t namelen)
704{
705	struct pollfd pfd;
706	socklen_t optlen;
707	int flags, optval;
708	int ret;
709
710	if (timeout != -1) {
711		flags = fcntl(s, F_GETFL, 0);
712		if (fcntl(s, F_SETFL, flags | O_NONBLOCK) == -1)
713			err(1, "set non-blocking mode");
714	}
715
716	if ((ret = connect(s, name, namelen)) != 0 && errno == EINPROGRESS) {
717		pfd.fd = s;
718		pfd.events = POLLOUT;
719		if ((ret = poll(&pfd, 1, timeout)) == 1) {
720			optlen = sizeof(optval);
721			if ((ret = getsockopt(s, SOL_SOCKET, SO_ERROR,
722			    &optval, &optlen)) == 0) {
723				errno = optval;
724				ret = optval == 0 ? 0 : -1;
725			}
726		} else if (ret == 0) {
727			errno = ETIMEDOUT;
728			ret = -1;
729		} else
730			err(1, "poll failed");
731	}
732
733	if (timeout != -1 && fcntl(s, F_SETFL, flags) == -1)
734		err(1, "restoring flags");
735
736	return (ret);
737}
738
739/*
740 * local_listen()
741 * Returns a socket listening on a local port, binds to specified source
742 * address. Returns -1 on failure.
743 */
744int
745local_listen(char *host, char *port, struct addrinfo hints)
746{
747	struct addrinfo *res, *res0;
748	int s, ret, x = 1;
749	int error;
750
751	/* Allow nodename to be null. */
752	hints.ai_flags |= AI_PASSIVE;
753
754	/*
755	 * In the case of binding to a wildcard address
756	 * default to binding to an ipv4 address.
757	 */
758	if (host == NULL && hints.ai_family == AF_UNSPEC)
759		hints.ai_family = AF_INET;
760
761	if ((error = getaddrinfo(host, port, &hints, &res)))
762		errx(1, "getaddrinfo: %s", gai_strerror(error));
763
764	res0 = res;
765	do {
766		if ((s = socket(res0->ai_family, res0->ai_socktype,
767		    res0->ai_protocol)) < 0)
768			continue;
769
770		if (rtableid >= 0 && (setsockopt(s, SOL_SOCKET, SO_SETFIB,
771		    &rtableid, sizeof(rtableid)) == -1))
772			err(1, "setsockopt SO_SETFIB");
773
774		ret = setsockopt(s, SOL_SOCKET, SO_REUSEPORT, &x, sizeof(x));
775		if (ret == -1)
776			err(1, NULL);
777
778		if (FreeBSD_Oflag) {
779			if (setsockopt(s, IPPROTO_TCP, TCP_NOOPT,
780			    &FreeBSD_Oflag, sizeof(FreeBSD_Oflag)) == -1)
781				err(1, "disable TCP options");
782		}
783
784		set_common_sockopts(s, res0->ai_family);
785
786		if (bind(s, (struct sockaddr *)res0->ai_addr,
787		    res0->ai_addrlen) == 0)
788			break;
789
790		close(s);
791		s = -1;
792	} while ((res0 = res0->ai_next) != NULL);
793
794	if (!uflag && s != -1) {
795		if (listen(s, 1) < 0)
796			err(1, "listen");
797	}
798
799	freeaddrinfo(res);
800
801	return (s);
802}
803
804/*
805 * readwrite()
806 * Loop that polls on the network file descriptor and stdin.
807 */
808void
809readwrite(int net_fd)
810{
811	struct pollfd pfd[4];
812	int stdin_fd = STDIN_FILENO;
813	int stdout_fd = STDOUT_FILENO;
814	unsigned char netinbuf[BUFSIZE];
815	size_t netinbufpos = 0;
816	unsigned char stdinbuf[BUFSIZE];
817	size_t stdinbufpos = 0;
818	int n, num_fds;
819	ssize_t ret;
820
821	/* don't read from stdin if requested */
822	if (dflag)
823		stdin_fd = -1;
824
825	/* stdin */
826	pfd[POLL_STDIN].fd = stdin_fd;
827	pfd[POLL_STDIN].events = POLLIN;
828
829	/* network out */
830	pfd[POLL_NETOUT].fd = net_fd;
831	pfd[POLL_NETOUT].events = 0;
832
833	/* network in */
834	pfd[POLL_NETIN].fd = net_fd;
835	pfd[POLL_NETIN].events = POLLIN;
836
837	/* stdout */
838	pfd[POLL_STDOUT].fd = stdout_fd;
839	pfd[POLL_STDOUT].events = 0;
840
841	while (1) {
842		/* both inputs are gone, buffers are empty, we are done */
843		if (pfd[POLL_STDIN].fd == -1 && pfd[POLL_NETIN].fd == -1
844		    && stdinbufpos == 0 && netinbufpos == 0) {
845			close(net_fd);
846			return;
847		}
848		/* both outputs are gone, we can't continue */
849		if (pfd[POLL_NETOUT].fd == -1 && pfd[POLL_STDOUT].fd == -1) {
850			close(net_fd);
851			return;
852		}
853		/* listen and net in gone, queues empty, done */
854		if (lflag && pfd[POLL_NETIN].fd == -1
855		    && stdinbufpos == 0 && netinbufpos == 0) {
856			close(net_fd);
857			return;
858		}
859
860		/* help says -i is for "wait between lines sent". We read and
861		 * write arbitrary amounts of data, and we don't want to start
862		 * scanning for newlines, so this is as good as it gets */
863		if (iflag)
864			sleep(iflag);
865
866		/* poll */
867		num_fds = poll(pfd, 4, timeout);
868
869		/* treat poll errors */
870		if (num_fds == -1) {
871			close(net_fd);
872			err(1, "polling error");
873		}
874
875		/* timeout happened */
876		if (num_fds == 0)
877			return;
878
879		/* treat socket error conditions */
880		for (n = 0; n < 4; n++) {
881			if (pfd[n].revents & (POLLERR|POLLNVAL)) {
882				pfd[n].fd = -1;
883			}
884		}
885		/* reading is possible after HUP */
886		if (pfd[POLL_STDIN].events & POLLIN &&
887		    pfd[POLL_STDIN].revents & POLLHUP &&
888		    ! (pfd[POLL_STDIN].revents & POLLIN))
889				pfd[POLL_STDIN].fd = -1;
890
891		if (pfd[POLL_NETIN].events & POLLIN &&
892		    pfd[POLL_NETIN].revents & POLLHUP &&
893		    ! (pfd[POLL_NETIN].revents & POLLIN))
894				pfd[POLL_NETIN].fd = -1;
895
896		if (pfd[POLL_NETOUT].revents & POLLHUP) {
897			if (Nflag)
898				shutdown(pfd[POLL_NETOUT].fd, SHUT_WR);
899			pfd[POLL_NETOUT].fd = -1;
900		}
901		/* if HUP, stop watching stdout */
902		if (pfd[POLL_STDOUT].revents & POLLHUP)
903			pfd[POLL_STDOUT].fd = -1;
904		/* if no net out, stop watching stdin */
905		if (pfd[POLL_NETOUT].fd == -1)
906			pfd[POLL_STDIN].fd = -1;
907		/* if no stdout, stop watching net in */
908		if (pfd[POLL_STDOUT].fd == -1) {
909			if (pfd[POLL_NETIN].fd != -1)
910				shutdown(pfd[POLL_NETIN].fd, SHUT_RD);
911			pfd[POLL_NETIN].fd = -1;
912		}
913
914		/* try to read from stdin */
915		if (pfd[POLL_STDIN].revents & POLLIN && stdinbufpos < BUFSIZE) {
916			ret = fillbuf(pfd[POLL_STDIN].fd, stdinbuf,
917			    &stdinbufpos);
918			/* error or eof on stdin - remove from pfd */
919			if (ret == 0 || ret == -1)
920				pfd[POLL_STDIN].fd = -1;
921			/* read something - poll net out */
922			if (stdinbufpos > 0)
923				pfd[POLL_NETOUT].events = POLLOUT;
924			/* filled buffer - remove self from polling */
925			if (stdinbufpos == BUFSIZE)
926				pfd[POLL_STDIN].events = 0;
927		}
928		/* try to write to network */
929		if (pfd[POLL_NETOUT].revents & POLLOUT && stdinbufpos > 0) {
930			ret = drainbuf(pfd[POLL_NETOUT].fd, stdinbuf,
931			    &stdinbufpos);
932			if (ret == -1)
933				pfd[POLL_NETOUT].fd = -1;
934			/* buffer empty - remove self from polling */
935			if (stdinbufpos == 0)
936				pfd[POLL_NETOUT].events = 0;
937			/* buffer no longer full - poll stdin again */
938			if (stdinbufpos < BUFSIZE)
939				pfd[POLL_STDIN].events = POLLIN;
940		}
941		/* try to read from network */
942		if (pfd[POLL_NETIN].revents & POLLIN && netinbufpos < BUFSIZE) {
943			ret = fillbuf(pfd[POLL_NETIN].fd, netinbuf,
944			    &netinbufpos);
945			if (ret == -1)
946				pfd[POLL_NETIN].fd = -1;
947			/* eof on net in - remove from pfd */
948			if (ret == 0) {
949				shutdown(pfd[POLL_NETIN].fd, SHUT_RD);
950				pfd[POLL_NETIN].fd = -1;
951			}
952			/* read something - poll stdout */
953			if (netinbufpos > 0)
954				pfd[POLL_STDOUT].events = POLLOUT;
955			/* filled buffer - remove self from polling */
956			if (netinbufpos == BUFSIZE)
957				pfd[POLL_NETIN].events = 0;
958			/* handle telnet */
959			if (tflag)
960				atelnet(pfd[POLL_NETIN].fd, netinbuf,
961				    netinbufpos);
962		}
963		/* try to write to stdout */
964		if (pfd[POLL_STDOUT].revents & POLLOUT && netinbufpos > 0) {
965			ret = drainbuf(pfd[POLL_STDOUT].fd, netinbuf,
966			    &netinbufpos);
967			if (ret == -1)
968				pfd[POLL_STDOUT].fd = -1;
969			/* buffer empty - remove self from polling */
970			if (netinbufpos == 0)
971				pfd[POLL_STDOUT].events = 0;
972			/* buffer no longer full - poll net in again */
973			if (netinbufpos < BUFSIZE)
974				pfd[POLL_NETIN].events = POLLIN;
975		}
976
977		/* stdin gone and queue empty? */
978		if (pfd[POLL_STDIN].fd == -1 && stdinbufpos == 0) {
979			if (pfd[POLL_NETOUT].fd != -1 && Nflag)
980				shutdown(pfd[POLL_NETOUT].fd, SHUT_WR);
981			pfd[POLL_NETOUT].fd = -1;
982		}
983		/* net in gone and queue empty? */
984		if (pfd[POLL_NETIN].fd == -1 && netinbufpos == 0) {
985			pfd[POLL_STDOUT].fd = -1;
986		}
987	}
988}
989
990ssize_t
991drainbuf(int fd, unsigned char *buf, size_t *bufpos)
992{
993	ssize_t n;
994	ssize_t adjust;
995
996	n = write(fd, buf, *bufpos);
997	/* don't treat EAGAIN, EINTR as error */
998	if (n == -1 && (errno == EAGAIN || errno == EINTR))
999		n = -2;
1000	if (n <= 0)
1001		return n;
1002	/* adjust buffer */
1003	adjust = *bufpos - n;
1004	if (adjust > 0)
1005		memmove(buf, buf + n, adjust);
1006	*bufpos -= n;
1007	return n;
1008}
1009
1010
1011ssize_t
1012fillbuf(int fd, unsigned char *buf, size_t *bufpos)
1013{
1014	size_t num = BUFSIZE - *bufpos;
1015	ssize_t n;
1016
1017	n = read(fd, buf + *bufpos, num);
1018	/* don't treat EAGAIN, EINTR as error */
1019	if (n == -1 && (errno == EAGAIN || errno == EINTR))
1020		n = -2;
1021	if (n <= 0)
1022		return n;
1023	*bufpos += n;
1024	return n;
1025}
1026
1027/*
1028 * fdpass()
1029 * Pass the connected file descriptor to stdout and exit.
1030 */
1031void
1032fdpass(int nfd)
1033{
1034	struct msghdr mh;
1035	union {
1036		struct cmsghdr hdr;
1037		char buf[CMSG_SPACE(sizeof(int))];
1038	} cmsgbuf;
1039	struct cmsghdr *cmsg;
1040	struct iovec iov;
1041	char c = '\0';
1042	ssize_t r;
1043	struct pollfd pfd;
1044
1045	/* Avoid obvious stupidity */
1046	if (isatty(STDOUT_FILENO))
1047		errx(1, "Cannot pass file descriptor to tty");
1048
1049	bzero(&mh, sizeof(mh));
1050	bzero(&cmsgbuf, sizeof(cmsgbuf));
1051	bzero(&iov, sizeof(iov));
1052
1053	mh.msg_control = (caddr_t)&cmsgbuf.buf;
1054	mh.msg_controllen = sizeof(cmsgbuf.buf);
1055	cmsg = CMSG_FIRSTHDR(&mh);
1056	cmsg->cmsg_len = CMSG_LEN(sizeof(int));
1057	cmsg->cmsg_level = SOL_SOCKET;
1058	cmsg->cmsg_type = SCM_RIGHTS;
1059	*(int *)CMSG_DATA(cmsg) = nfd;
1060
1061	iov.iov_base = &c;
1062	iov.iov_len = 1;
1063	mh.msg_iov = &iov;
1064	mh.msg_iovlen = 1;
1065
1066	bzero(&pfd, sizeof(pfd));
1067	pfd.fd = STDOUT_FILENO;
1068	pfd.events = POLLOUT;
1069	for (;;) {
1070		r = sendmsg(STDOUT_FILENO, &mh, 0);
1071		if (r == -1) {
1072			if (errno == EAGAIN || errno == EINTR) {
1073				if (poll(&pfd, 1, -1) == -1)
1074					err(1, "poll");
1075				continue;
1076			}
1077			err(1, "sendmsg");
1078		} else if (r != 1)
1079			errx(1, "sendmsg: unexpected return value %zd", r);
1080		else
1081			break;
1082	}
1083	exit(0);
1084}
1085
1086/* Deal with RFC 854 WILL/WONT DO/DONT negotiation. */
1087void
1088atelnet(int nfd, unsigned char *buf, unsigned int size)
1089{
1090	unsigned char *p, *end;
1091	unsigned char obuf[4];
1092
1093	if (size < 3)
1094		return;
1095	end = buf + size - 2;
1096
1097	for (p = buf; p < end; p++) {
1098		if (*p != IAC)
1099			continue;
1100
1101		obuf[0] = IAC;
1102		p++;
1103		if ((*p == WILL) || (*p == WONT))
1104			obuf[1] = DONT;
1105		else if ((*p == DO) || (*p == DONT))
1106			obuf[1] = WONT;
1107		else
1108			continue;
1109
1110		p++;
1111		obuf[2] = *p;
1112		if (atomicio(vwrite, nfd, obuf, 3) != 3)
1113			warn("Write Error!");
1114	}
1115}
1116
1117/*
1118 * build_ports()
1119 * Build an array of ports in portlist[], listing each port
1120 * that we should try to connect to.
1121 */
1122void
1123build_ports(char *p)
1124{
1125	const char *errstr;
1126	char *n;
1127	int hi, lo, cp;
1128	int x = 0;
1129
1130	if ((n = strchr(p, '-')) != NULL) {
1131		*n = '\0';
1132		n++;
1133
1134		/* Make sure the ports are in order: lowest->highest. */
1135		hi = strtonum(n, 1, PORT_MAX, &errstr);
1136		if (errstr)
1137			errx(1, "port number %s: %s", errstr, n);
1138		lo = strtonum(p, 1, PORT_MAX, &errstr);
1139		if (errstr)
1140			errx(1, "port number %s: %s", errstr, p);
1141
1142		if (lo > hi) {
1143			cp = hi;
1144			hi = lo;
1145			lo = cp;
1146		}
1147
1148		/* Load ports sequentially. */
1149		for (cp = lo; cp <= hi; cp++) {
1150			portlist[x] = calloc(1, PORT_MAX_LEN);
1151			if (portlist[x] == NULL)
1152				err(1, NULL);
1153			snprintf(portlist[x], PORT_MAX_LEN, "%d", cp);
1154			x++;
1155		}
1156
1157		/* Randomly swap ports. */
1158		if (rflag) {
1159			int y;
1160			char *c;
1161
1162			for (x = 0; x <= (hi - lo); x++) {
1163				y = (arc4random() & 0xFFFF) % (hi - lo);
1164				c = portlist[x];
1165				portlist[x] = portlist[y];
1166				portlist[y] = c;
1167			}
1168		}
1169	} else {
1170		hi = strtonum(p, 1, PORT_MAX, &errstr);
1171		if (errstr)
1172			errx(1, "port number %s: %s", errstr, p);
1173		portlist[0] = strdup(p);
1174		if (portlist[0] == NULL)
1175			err(1, NULL);
1176	}
1177}
1178
1179/*
1180 * udptest()
1181 * Do a few writes to see if the UDP port is there.
1182 * Fails once PF state table is full.
1183 */
1184int
1185udptest(int s)
1186{
1187	int i, ret;
1188
1189	for (i = 0; i <= 3; i++) {
1190		if (write(s, "X", 1) == 1)
1191			ret = 1;
1192		else
1193			ret = -1;
1194	}
1195	return (ret);
1196}
1197
1198void
1199set_common_sockopts(int s, int af)
1200{
1201	int x = 1;
1202
1203	if (Sflag) {
1204		if (setsockopt(s, IPPROTO_TCP, TCP_MD5SIG,
1205			&x, sizeof(x)) == -1)
1206			err(1, NULL);
1207	}
1208	if (Dflag) {
1209		if (setsockopt(s, SOL_SOCKET, SO_DEBUG,
1210			&x, sizeof(x)) == -1)
1211			err(1, NULL);
1212	}
1213	if (Tflag != -1) {
1214		int proto, option;
1215
1216		if (af == AF_INET6) {
1217			proto = IPPROTO_IPV6;
1218			option = IPV6_TCLASS;
1219		} else {
1220			proto = IPPROTO_IP;
1221			option = IP_TOS;
1222		}
1223
1224		if (setsockopt(s, proto, option, &Tflag, sizeof(Tflag)) == -1)
1225			err(1, "set IP ToS");
1226	}
1227	if (Iflag) {
1228		if (setsockopt(s, SOL_SOCKET, SO_RCVBUF,
1229		    &Iflag, sizeof(Iflag)) == -1)
1230			err(1, "set TCP receive buffer size");
1231	}
1232	if (Oflag) {
1233		if (setsockopt(s, SOL_SOCKET, SO_SNDBUF,
1234		    &Oflag, sizeof(Oflag)) == -1)
1235			err(1, "set TCP send buffer size");
1236	}
1237	if (FreeBSD_Oflag) {
1238		if (setsockopt(s, IPPROTO_TCP, TCP_NOOPT,
1239		    &FreeBSD_Oflag, sizeof(FreeBSD_Oflag)) == -1)
1240			err(1, "disable TCP options");
1241	}
1242#ifdef IPSEC
1243	if (ipsec_policy[0] != NULL)
1244		add_ipsec_policy(s, af, ipsec_policy[0]);
1245	if (ipsec_policy[1] != NULL)
1246		add_ipsec_policy(s, af, ipsec_policy[1]);
1247#endif
1248}
1249
1250int
1251map_tos(char *s, int *val)
1252{
1253	/* DiffServ Codepoints and other TOS mappings */
1254	const struct toskeywords {
1255		const char	*keyword;
1256		int		 val;
1257	} *t, toskeywords[] = {
1258		{ "af11",		IPTOS_DSCP_AF11 },
1259		{ "af12",		IPTOS_DSCP_AF12 },
1260		{ "af13",		IPTOS_DSCP_AF13 },
1261		{ "af21",		IPTOS_DSCP_AF21 },
1262		{ "af22",		IPTOS_DSCP_AF22 },
1263		{ "af23",		IPTOS_DSCP_AF23 },
1264		{ "af31",		IPTOS_DSCP_AF31 },
1265		{ "af32",		IPTOS_DSCP_AF32 },
1266		{ "af33",		IPTOS_DSCP_AF33 },
1267		{ "af41",		IPTOS_DSCP_AF41 },
1268		{ "af42",		IPTOS_DSCP_AF42 },
1269		{ "af43",		IPTOS_DSCP_AF43 },
1270		{ "critical",		IPTOS_PREC_CRITIC_ECP },
1271		{ "cs0",		IPTOS_DSCP_CS0 },
1272		{ "cs1",		IPTOS_DSCP_CS1 },
1273		{ "cs2",		IPTOS_DSCP_CS2 },
1274		{ "cs3",		IPTOS_DSCP_CS3 },
1275		{ "cs4",		IPTOS_DSCP_CS4 },
1276		{ "cs5",		IPTOS_DSCP_CS5 },
1277		{ "cs6",		IPTOS_DSCP_CS6 },
1278		{ "cs7",		IPTOS_DSCP_CS7 },
1279		{ "ef",			IPTOS_DSCP_EF },
1280		{ "inetcontrol",	IPTOS_PREC_INTERNETCONTROL },
1281		{ "lowdelay",		IPTOS_LOWDELAY },
1282		{ "netcontrol",		IPTOS_PREC_NETCONTROL },
1283		{ "reliability",	IPTOS_RELIABILITY },
1284		{ "throughput",		IPTOS_THROUGHPUT },
1285		{ NULL, 		-1 },
1286	};
1287
1288	for (t = toskeywords; t->keyword != NULL; t++) {
1289		if (strcmp(s, t->keyword) == 0) {
1290			*val = t->val;
1291			return (1);
1292		}
1293	}
1294
1295	return (0);
1296}
1297
1298void
1299report_connect(const struct sockaddr *sa, socklen_t salen)
1300{
1301	char remote_host[NI_MAXHOST];
1302	char remote_port[NI_MAXSERV];
1303	int herr;
1304	int flags = NI_NUMERICSERV;
1305
1306	if (nflag)
1307		flags |= NI_NUMERICHOST;
1308
1309	if ((herr = getnameinfo(sa, salen,
1310	    remote_host, sizeof(remote_host),
1311	    remote_port, sizeof(remote_port),
1312	    flags)) != 0) {
1313		if (herr == EAI_SYSTEM)
1314			err(1, "getnameinfo");
1315		else
1316			errx(1, "getnameinfo: %s", gai_strerror(herr));
1317	}
1318
1319	fprintf(stderr,
1320	    "Connection from %s %s "
1321	    "received!\n", remote_host, remote_port);
1322}
1323
1324void
1325help(void)
1326{
1327	usage(0);
1328	fprintf(stderr, "\tCommand Summary:\n\
1329	\t-4		Use IPv4\n\
1330	\t-6		Use IPv6\n\
1331	\t-D		Enable the debug socket option\n\
1332	\t-d		Detach from stdin\n");
1333#ifdef IPSEC
1334	fprintf(stderr, "\
1335	\t-E		Use IPsec ESP\n\
1336	\t-e policy	Use specified IPsec policy\n");
1337#endif
1338	fprintf(stderr, "\
1339	\t-F		Pass socket fd\n\
1340	\t-h		This help text\n\
1341	\t-I length	TCP receive buffer length\n\
1342	\t-i secs\t	Delay interval for lines sent, ports scanned\n\
1343	\t-k		Keep inbound sockets open for multiple connects\n\
1344	\t-l		Listen mode, for inbound connects\n\
1345	\t-N		Shutdown the network socket after EOF on stdin\n\
1346	\t-n		Suppress name/port resolutions\n\
1347	\t--no-tcpopt	Disable TCP options\n\
1348	\t--sctp\t	SCTP mode\n\
1349	\t-O length	TCP send buffer length\n\
1350	\t-P proxyuser\tUsername for proxy authentication\n\
1351	\t-p port\t	Specify local port for remote connects\n\
1352	\t-r		Randomize remote ports\n\
1353	\t-S		Enable the TCP MD5 signature option\n\
1354	\t-s addr\t	Local source address\n\
1355	\t-T toskeyword\tSet IP Type of Service\n\
1356	\t-t		Answer TELNET negotiation\n\
1357	\t-U		Use UNIX domain socket\n\
1358	\t-u		UDP mode\n\
1359	\t-V rtable	Specify alternate routing table\n\
1360	\t-v		Verbose\n\
1361	\t-w secs\t	Timeout for connects and final net reads\n\
1362	\t-X proto	Proxy protocol: \"4\", \"5\" (SOCKS) or \"connect\"\n\
1363	\t-x addr[:port]\tSpecify proxy address and port\n\
1364	\t-z		Zero-I/O mode [used for scanning]\n\
1365	Port numbers can be individual or ranges: lo-hi [inclusive]\n");
1366#ifdef IPSEC
1367	fprintf(stderr, "\tSee ipsec_set_policy(3) for -e argument format\n");
1368#endif
1369	exit(1);
1370}
1371
1372#ifdef IPSEC
1373void
1374add_ipsec_policy(int s, int af, char *policy)
1375{
1376	char *raw;
1377	int e;
1378
1379	raw = ipsec_set_policy(policy, strlen(policy));
1380	if (raw == NULL)
1381		errx(1, "ipsec_set_policy `%s': %s", policy,
1382		     ipsec_strerror());
1383	if (af == AF_INET)
1384		e = setsockopt(s, IPPROTO_IP, IP_IPSEC_POLICY, raw,
1385		    ipsec_get_policylen(raw));
1386	if (af == AF_INET6)
1387		e = setsockopt(s, IPPROTO_IPV6, IPV6_IPSEC_POLICY, raw,
1388		    ipsec_get_policylen(raw));
1389	if (e < 0)
1390		err(1, "ipsec policy cannot be configured");
1391	free(raw);
1392	if (vflag)
1393		fprintf(stderr, "ipsec policy configured: `%s'\n", policy);
1394	return;
1395}
1396#endif /* IPSEC */
1397
1398void
1399usage(int ret)
1400{
1401	fprintf(stderr,
1402#ifdef IPSEC
1403	    "usage: nc [-46DdEFhklNnrStUuvz] [-e policy] [-I length] [-i interval] [-O length]\n"
1404#else
1405	    "usage: nc [-46DdFhklNnrStUuvz] [-I length] [-i interval] [-O length]\n"
1406#endif
1407	    "\t  [--no-tcpopt] [--sctp]\n"
1408	    "\t  [-P proxy_username] [-p source_port] [-s source] [-T ToS]\n"
1409	    "\t  [-V rtable] [-w timeout] [-X proxy_protocol]\n"
1410	    "\t  [-x proxy_address[:port]] [destination] [port]\n");
1411	if (ret)
1412		exit(1);
1413}
1414