Home | History | Annotate | Line # | Download | only in ftp
ftp.c revision 1.110
      1 /*	$NetBSD: ftp.c,v 1.110 2000/10/11 14:46:03 is Exp $	*/
      2 
      3 /*-
      4  * Copyright (c) 1996-2000 The NetBSD Foundation, Inc.
      5  * All rights reserved.
      6  *
      7  * This code is derived from software contributed to The NetBSD Foundation
      8  * by Luke Mewburn.
      9  *
     10  * Redistribution and use in source and binary forms, with or without
     11  * modification, are permitted provided that the following conditions
     12  * are met:
     13  * 1. Redistributions of source code must retain the above copyright
     14  *    notice, this list of conditions and the following disclaimer.
     15  * 2. Redistributions in binary form must reproduce the above copyright
     16  *    notice, this list of conditions and the following disclaimer in the
     17  *    documentation and/or other materials provided with the distribution.
     18  * 3. All advertising materials mentioning features or use of this software
     19  *    must display the following acknowledgement:
     20  *	This product includes software developed by the NetBSD
     21  *	Foundation, Inc. and its contributors.
     22  * 4. Neither the name of The NetBSD Foundation nor the names of its
     23  *    contributors may be used to endorse or promote products derived
     24  *    from this software without specific prior written permission.
     25  *
     26  * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
     27  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
     28  * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
     29  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
     30  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
     31  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
     32  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
     33  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
     34  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
     35  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
     36  * POSSIBILITY OF SUCH DAMAGE.
     37  */
     38 
     39 /*
     40  * Copyright (c) 1985, 1989, 1993, 1994
     41  *	The Regents of the University of California.  All rights reserved.
     42  *
     43  * Redistribution and use in source and binary forms, with or without
     44  * modification, are permitted provided that the following conditions
     45  * are met:
     46  * 1. Redistributions of source code must retain the above copyright
     47  *    notice, this list of conditions and the following disclaimer.
     48  * 2. Redistributions in binary form must reproduce the above copyright
     49  *    notice, this list of conditions and the following disclaimer in the
     50  *    documentation and/or other materials provided with the distribution.
     51  * 3. All advertising materials mentioning features or use of this software
     52  *    must display the following acknowledgement:
     53  *	This product includes software developed by the University of
     54  *	California, Berkeley and its contributors.
     55  * 4. Neither the name of the University nor the names of its contributors
     56  *    may be used to endorse or promote products derived from this software
     57  *    without specific prior written permission.
     58  *
     59  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
     60  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
     61  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
     62  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
     63  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
     64  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
     65  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
     66  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
     67  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
     68  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
     69  * SUCH DAMAGE.
     70  */
     71 
     72 /*
     73  * Copyright (C) 1997 and 1998 WIDE Project.
     74  * All rights reserved.
     75  *
     76  * Redistribution and use in source and binary forms, with or without
     77  * modification, are permitted provided that the following conditions
     78  * are met:
     79  * 1. Redistributions of source code must retain the above copyright
     80  *    notice, this list of conditions and the following disclaimer.
     81  * 2. Redistributions in binary form must reproduce the above copyright
     82  *    notice, this list of conditions and the following disclaimer in the
     83  *    documentation and/or other materials provided with the distribution.
     84  * 3. Neither the name of the project nor the names of its contributors
     85  *    may be used to endorse or promote products derived from this software
     86  *    without specific prior written permission.
     87  *
     88  * THIS SOFTWARE IS PROVIDED BY THE PROJECT AND CONTRIBUTORS ``AS IS'' AND
     89  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
     90  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
     91  * ARE DISCLAIMED.  IN NO EVENT SHALL THE PROJECT OR CONTRIBUTORS BE LIABLE
     92  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
     93  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
     94  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
     95  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
     96  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
     97  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
     98  * SUCH DAMAGE.
     99  */
    100 
    101 #include <sys/cdefs.h>
    102 #ifndef lint
    103 #if 0
    104 static char sccsid[] = "@(#)ftp.c	8.6 (Berkeley) 10/27/94";
    105 #else
    106 __RCSID("$NetBSD: ftp.c,v 1.110 2000/10/11 14:46:03 is Exp $");
    107 #endif
    108 #endif /* not lint */
    109 
    110 #include <sys/types.h>
    111 #include <sys/stat.h>
    112 #include <sys/socket.h>
    113 #include <sys/time.h>
    114 
    115 #include <netinet/in.h>
    116 #include <netinet/in_systm.h>
    117 #include <netinet/ip.h>
    118 #include <arpa/inet.h>
    119 #include <arpa/ftp.h>
    120 #include <arpa/telnet.h>
    121 
    122 #include <ctype.h>
    123 #include <err.h>
    124 #include <errno.h>
    125 #include <netdb.h>
    126 #include <stdio.h>
    127 #include <stdlib.h>
    128 #include <string.h>
    129 #include <time.h>
    130 #include <unistd.h>
    131 #include <stdarg.h>
    132 #ifndef USE_SELECT
    133 #include <poll.h>
    134 #endif
    135 
    136 #include "ftp_var.h"
    137 
    138 volatile int	abrtflag = 0;
    139 volatile int	timeoutflag = 0;
    140 sigjmp_buf	ptabort;
    141 int	ptabflg;
    142 int	ptflag = 0;
    143 char	pasv[BUFSIZ];	/* passive port for proxy data connection */
    144 
    145 static int empty(FILE *, FILE *, int);
    146 
    147 struct sockinet {
    148 	union sockunion {
    149 		struct sockaddr_in  su_sin;
    150 #ifdef INET6
    151 		struct sockaddr_in6 su_sin6;
    152 #endif
    153 	} si_su;
    154 #if !HAVE_SOCKADDR_SA_LEN
    155 	int	si_len;
    156 #endif
    157 };
    158 
    159 #if !HAVE_SOCKADDR_SA_LEN
    160 # define su_len		si_len
    161 #else
    162 # define su_len		si_su.su_sin.sin_len
    163 #endif
    164 #define su_family	si_su.su_sin.sin_family
    165 #define su_port		si_su.su_sin.sin_port
    166 
    167 struct sockinet myctladdr, hisctladdr, data_addr;
    168 
    169 char *
    170 hookup(char *host, char *port)
    171 {
    172 	int s = -1, len, error, portnum;
    173 	struct addrinfo hints, *res, *res0;
    174 	char hbuf[MAXHOSTNAMELEN];
    175 	static char hostnamebuf[MAXHOSTNAMELEN];
    176 	char *cause = "unknown";
    177 
    178 	memset((char *)&hisctladdr, 0, sizeof (hisctladdr));
    179 	memset((char *)&myctladdr, 0, sizeof (myctladdr));
    180 	memset(&hints, 0, sizeof(hints));
    181 	portnum = parseport(port, FTP_PORT);
    182 	hints.ai_flags = AI_CANONNAME;
    183 	hints.ai_family = AF_UNSPEC;
    184 	hints.ai_socktype = SOCK_STREAM;
    185 	hints.ai_protocol = 0;
    186 	error = getaddrinfo(host, NULL, &hints, &res0);
    187 	if (error) {
    188 		warnx("%s", gai_strerror(error));
    189 		code = -1;
    190 		return (0);
    191 	}
    192 
    193 	if (res0->ai_canonname)
    194 		(void)strlcpy(hostnamebuf, res0->ai_canonname,
    195 		    sizeof(hostnamebuf));
    196 	else
    197 		(void)strlcpy(hostnamebuf, host, sizeof(hostnamebuf));
    198 	hostname = hostnamebuf;
    199 
    200 	for (res = res0; res; res = res->ai_next) {
    201 		/*
    202 		 * make sure that ai_addr is NOT an IPv4 mapped address.
    203 		 * IPv4 mapped address complicates too many things in FTP
    204 		 * protocol handling, as FTP protocol is defined differently
    205 		 * between IPv4 and IPv6.
    206 		 *
    207 		 * This may not be the best way to handle this situation,
    208 		 * since the semantics of IPv4 mapped address is defined in
    209 		 * the kernel.  There are configurations where we should use
    210 		 * IPv4 mapped address as native IPv6 address, not as
    211 		 * "an IPv6 address that embeds IPv4 address" (namely, SIIT).
    212 		 *
    213 		 * More complete solution would be to have an additional
    214 		 * getsockopt to grab "real" peername/sockname.  "real"
    215 		 * peername/sockname will be AF_INET if IPv4 mapped address
    216 		 * is used to embed IPv4 address, and will be AF_INET6 if
    217 		 * we use it as native.  What a mess!
    218 		 */
    219 		ai_unmapped(res);
    220 #if 0	/*old behavior*/
    221 		if (res != res0)	/* not on the first address */
    222 #else
    223 		if (res0->ai_next)	/* if we have multiple possibilities */
    224 #endif
    225 		{
    226 			getnameinfo(res->ai_addr, res->ai_addrlen,
    227 			    hbuf, sizeof(hbuf), NULL, 0, NI_NUMERICHOST);
    228 			fprintf(ttyout, "Trying %s...\n", hbuf);
    229 		}
    230 		((struct sockaddr_in *)res->ai_addr)->sin_port = htons(portnum);
    231 		s = socket(res->ai_family, SOCK_STREAM, res->ai_protocol);
    232 		if (s < 0) {
    233 			cause = "socket";
    234 			continue;
    235 		}
    236 		while ((error = xconnect(s, res->ai_addr, res->ai_addrlen)) < 0
    237 				&& errno == EINTR) {
    238 			;
    239 		}
    240 		if (error) {
    241 			/* this "if" clause is to prevent print warning twice */
    242 			if (res->ai_next) {
    243 				getnameinfo(res->ai_addr, res->ai_addrlen,
    244 				    hbuf, sizeof(hbuf), NULL, 0,
    245 				    NI_NUMERICHOST);
    246 				warn("connect to address %s", hbuf);
    247 			}
    248 			cause = "connect";
    249 			close(s);
    250 			s = -1;
    251 			continue;
    252 		}
    253 
    254 		/* finally we got one */
    255 		break;
    256 	}
    257 	if (s < 0) {
    258 		warn("%s", cause);
    259 		code = -1;
    260 		freeaddrinfo(res0);
    261 		return 0;
    262 	}
    263 	memcpy(&hisctladdr.si_su, res->ai_addr, res->ai_addrlen);
    264 	hisctladdr.su_len = res->ai_addrlen;
    265 	freeaddrinfo(res0);
    266 	res0 = res = NULL;
    267 
    268 	len = hisctladdr.su_len;
    269 	if (getsockname(s, (struct sockaddr *)&myctladdr.si_su, &len) < 0) {
    270 		warn("getsockname");
    271 		code = -1;
    272 		goto bad;
    273 	}
    274 	myctladdr.su_len = len;
    275 
    276 #ifdef IPTOS_LOWDELAY
    277 	if (hisctladdr.su_family == AF_INET) {
    278 		int tos = IPTOS_LOWDELAY;
    279 		if (setsockopt(s, IPPROTO_IP, IP_TOS, (char *)&tos,
    280 			       sizeof(int)) < 0)
    281 			warn("setsockopt TOS (ignored)");
    282 	}
    283 #endif
    284 	cin = fdopen(s, "r");
    285 	cout = fdopen(s, "w");
    286 	if (cin == NULL || cout == NULL) {
    287 		warnx("fdopen failed.");
    288 		if (cin)
    289 			(void)fclose(cin);
    290 		if (cout)
    291 			(void)fclose(cout);
    292 		code = -1;
    293 		goto bad;
    294 	}
    295 	if (verbose)
    296 		fprintf(ttyout, "Connected to %s.\n", hostname);
    297 	if (getreply(0) > 2) {	/* read startup message from server */
    298 		if (cin)
    299 			(void)fclose(cin);
    300 		if (cout)
    301 			(void)fclose(cout);
    302 		code = -1;
    303 		goto bad;
    304 	}
    305 	{
    306 	int on = 1;
    307 
    308 	if (setsockopt(s, SOL_SOCKET, SO_OOBINLINE, (char *)&on, sizeof(on))
    309 		< 0 && debug) {
    310 			warn("setsockopt");
    311 		}
    312 	}
    313 
    314 	return (hostname);
    315  bad:
    316 	(void)close(s);
    317 	return (NULL);
    318 }
    319 
    320 void
    321 cmdabort(int notused)
    322 {
    323 	int oerrno = errno;
    324 
    325 	alarmtimer(0);
    326 	if (fromatty)
    327 		write(fileno(ttyout), "\n", 1);
    328 	abrtflag++;
    329 	if (ptflag)
    330 		siglongjmp(ptabort, 1);
    331 	errno = oerrno;
    332 }
    333 
    334 void
    335 cmdtimeout(int notused)
    336 {
    337 	int oerrno = errno;
    338 
    339 	alarmtimer(0);
    340 	if (fromatty)
    341 		write(fileno(ttyout), "\n", 1);
    342 	timeoutflag++;
    343 	if (ptflag)
    344 		siglongjmp(ptabort, 1);
    345 	errno = oerrno;
    346 }
    347 
    348 /*VARARGS*/
    349 int
    350 command(const char *fmt, ...)
    351 {
    352 	va_list ap;
    353 	int r;
    354 	sigfunc oldsigint;
    355 
    356 	if (debug) {
    357 		fputs("---> ", ttyout);
    358 		va_start(ap, fmt);
    359 		if (strncmp("PASS ", fmt, 5) == 0)
    360 			fputs("PASS XXXX", ttyout);
    361 		else if (strncmp("ACCT ", fmt, 5) == 0)
    362 			fputs("ACCT XXXX", ttyout);
    363 		else
    364 			vfprintf(ttyout, fmt, ap);
    365 		va_end(ap);
    366 		putc('\n', ttyout);
    367 	}
    368 	if (cout == NULL) {
    369 		warnx("No control connection for command.");
    370 		code = -1;
    371 		return (0);
    372 	}
    373 
    374 	abrtflag = 0;
    375 
    376 	oldsigint = xsignal(SIGINT, cmdabort);
    377 
    378 	va_start(ap, fmt);
    379 	vfprintf(cout, fmt, ap);
    380 	va_end(ap);
    381 	fputs("\r\n", cout);
    382 	(void)fflush(cout);
    383 	cpend = 1;
    384 	r = getreply(!strcmp(fmt, "QUIT"));
    385 	if (abrtflag && oldsigint != SIG_IGN)
    386 		(*oldsigint)(SIGINT);
    387 	(void)xsignal(SIGINT, oldsigint);
    388 	return (r);
    389 }
    390 
    391 int
    392 getreply(int expecteof)
    393 {
    394 	char current_line[BUFSIZ];	/* last line of previous reply */
    395 	int c, n, line;
    396 	int dig;
    397 	int originalcode = 0, continuation = 0;
    398 	sigfunc oldsigint, oldsigalrm;
    399 	int pflag = 0;
    400 	char *cp, *pt = pasv;
    401 
    402 	abrtflag = 0;
    403 	timeoutflag = 0;
    404 
    405 	oldsigint = xsignal(SIGINT, cmdabort);
    406 	oldsigalrm = xsignal(SIGALRM, cmdtimeout);
    407 
    408 	for (line = 0 ;; line++) {
    409 		dig = n = code = 0;
    410 		cp = current_line;
    411 		while (alarmtimer(60),((c = getc(cin)) != '\n')) {
    412 			if (c == IAC) {     /* handle telnet commands */
    413 				switch (c = getc(cin)) {
    414 				case WILL:
    415 				case WONT:
    416 					c = getc(cin);
    417 					fprintf(cout, "%c%c%c", IAC, DONT, c);
    418 					(void)fflush(cout);
    419 					break;
    420 				case DO:
    421 				case DONT:
    422 					c = getc(cin);
    423 					fprintf(cout, "%c%c%c", IAC, WONT, c);
    424 					(void)fflush(cout);
    425 					break;
    426 				default:
    427 					break;
    428 				}
    429 				continue;
    430 			}
    431 			dig++;
    432 			if (c == EOF) {
    433 				/*
    434 				 * these will get trashed by pswitch()
    435 				 * in lostpeer()
    436 				 */
    437 				int reply_timeoutflag = timeoutflag;
    438 				int reply_abrtflag = abrtflag;
    439 
    440 				alarmtimer(0);
    441 				if (expecteof && feof(cin)) {
    442 					(void)xsignal(SIGINT, oldsigint);
    443 					(void)xsignal(SIGALRM, oldsigalrm);
    444 					code = 221;
    445 					return (0);
    446 				}
    447 				cpend = 0;
    448 				lostpeer(0);
    449 				if (verbose) {
    450 					if (reply_timeoutflag)
    451 						fputs(
    452     "421 Service not available, remote server timed out. Connection closed\n",
    453 						    ttyout);
    454 					else if (reply_abrtflag)
    455 						fputs(
    456     "421 Service not available, user interrupt. Connection closed.\n",
    457 						    ttyout);
    458 					else
    459 						fputs(
    460     "421 Service not available, remote server has closed connection.\n",
    461 						    ttyout);
    462 					(void)fflush(ttyout);
    463 				}
    464 				code = 421;
    465 				(void)xsignal(SIGINT, oldsigint);
    466 				(void)xsignal(SIGALRM, oldsigalrm);
    467 				return (4);
    468 			}
    469 			if (c != '\r' && (verbose > 0 ||
    470 			    ((verbose > -1 && n == '5' && dig > 4) &&
    471 			    (((!n && c < '5') || (n && n < '5'))
    472 			     || !retry_connect)))) {
    473 				if (proxflag &&
    474 				   (dig == 1 || (dig == 5 && verbose == 0)))
    475 					fprintf(ttyout, "%s:", hostname);
    476 				(void)putc(c, ttyout);
    477 			}
    478 			if (dig < 4 && isdigit(c))
    479 				code = code * 10 + (c - '0');
    480 			if (!pflag && (code == 227 || code == 228))
    481 				pflag = 1;
    482 			else if (!pflag && code == 229)
    483 				pflag = 100;
    484 			if (dig > 4 && pflag == 1 && isdigit(c))
    485 				pflag = 2;
    486 			if (pflag == 2) {
    487 				if (c != '\r' && c != ')')
    488 					*pt++ = c;
    489 				else {
    490 					*pt = '\0';
    491 					pflag = 3;
    492 				}
    493 			}
    494 			if (pflag == 100 && c == '(')
    495 				pflag = 2;
    496 			if (dig == 4 && c == '-') {
    497 				if (continuation)
    498 					code = 0;
    499 				continuation++;
    500 			}
    501 			if (n == 0)
    502 				n = c;
    503 			if (cp < &current_line[sizeof(current_line) - 1])
    504 				*cp++ = c;
    505 		}
    506 		if (verbose > 0 || ((verbose > -1 && n == '5') &&
    507 		    (n < '5' || !retry_connect))) {
    508 			(void)putc(c, ttyout);
    509 			(void)fflush (ttyout);
    510 		}
    511 		if (cp[-1] == '\r')
    512 			cp[-1] = '\0';
    513 		*cp = '\0';
    514 		if (line == 0)
    515 			(void)strlcpy(reply_string, current_line,
    516 			    sizeof(reply_string));
    517 		if (line > 0 && code == 0 && reply_callback != NULL)
    518 			(*reply_callback)(current_line);
    519 		if (continuation && code != originalcode) {
    520 			if (originalcode == 0)
    521 				originalcode = code;
    522 			continue;
    523 		}
    524 		if (n != '1')
    525 			cpend = 0;
    526 		alarmtimer(0);
    527 		(void)xsignal(SIGINT, oldsigint);
    528 		(void)xsignal(SIGALRM, oldsigalrm);
    529 		if (code == 421 || originalcode == 421)
    530 			lostpeer(0);
    531 		if (abrtflag && oldsigint != cmdabort && oldsigint != SIG_IGN)
    532 			(*oldsigint)(SIGINT);
    533 		if (timeoutflag && oldsigalrm != cmdtimeout &&
    534 		    oldsigalrm != SIG_IGN)
    535 			(*oldsigalrm)(SIGINT);
    536 		return (n - '0');
    537 	}
    538 }
    539 
    540 static int
    541 empty(FILE *cin, FILE *din, int sec)
    542 {
    543 	int nr;
    544 	int nfd = 0;
    545 
    546 #ifdef USE_SELECT
    547 	struct timeval t;
    548 	fd_set rmask;
    549 
    550 	FD_ZERO(&rmask);
    551 	if (cin) {
    552 		if (nfd < fileno(cin))
    553 			nfd = fileno(cin);
    554 		FD_SET(fileno(cin), &rmask);
    555 	}
    556 	if (din) {
    557 		if (nfd < fileno(din))
    558 			nfd = fileno(din);
    559 		FD_SET(fileno(din), &rmask);
    560 	}
    561 
    562 	t.tv_sec = (long) sec;
    563 	t.tv_usec = 0;
    564 	if ((nr = select(nfd, &rmask, NULL, NULL, &t)) <= 0)
    565 		return nr;
    566 
    567 	nr = 0;
    568 	if (cin)
    569 		nr |= FD_ISSET(fileno(cin), &rmask) ? 1 : 0;
    570 	if (din)
    571 		nr |= FD_ISSET(fileno(din), &rmask) ? 2 : 0;
    572 
    573 #else
    574 	struct pollfd pfd[2];
    575 
    576 	if (cin) {
    577 	    pfd[nfd].fd = fileno(cin);
    578 	    pfd[nfd++].events = POLLIN;
    579 	}
    580 
    581 	if (din) {
    582 	    pfd[nfd].fd = fileno(din);
    583 	    pfd[nfd++].events = POLLIN;
    584 	}
    585 
    586 	if ((nr = poll(pfd, nfd, sec * 1000)) <= 0)
    587 		return nr;
    588 
    589 	nr = 0;
    590 	nfd = 0;
    591 	if (cin)
    592 		nr |= (pfd[nfd++].revents & POLLIN) ? 1 : 0;
    593 	if (din)
    594 		nr |= (pfd[nfd++].revents & POLLIN) ? 2 : 0;
    595 #endif
    596 	return nr;
    597 }
    598 
    599 sigjmp_buf	xferabort;
    600 
    601 void
    602 abortxfer(int notused)
    603 {
    604 	char msgbuf[100];
    605 	int len;
    606 
    607 	alarmtimer(0);
    608 	mflag = 0;
    609 	abrtflag = 0;
    610 	switch (direction[0]) {
    611 	case 'r':
    612 		strlcpy(msgbuf, "\nreceive", sizeof(msgbuf));
    613 		break;
    614 	case 's':
    615 		strlcpy(msgbuf, "\nsend", sizeof(msgbuf));
    616 		break;
    617 	default:
    618 		errx(1, "abortxfer called with unknown direction `%s'",
    619 		    direction);
    620 	}
    621 	len = strlcat(msgbuf, " aborted. Waiting for remote to finish abort.\n",
    622 	    sizeof(msgbuf));
    623 	write(fileno(ttyout), msgbuf, len);
    624 	siglongjmp(xferabort, 1);
    625 }
    626 
    627 void
    628 sendrequest(const char *cmd, const char *local, const char *remote,
    629 	    int printnames)
    630 {
    631 	struct stat st;
    632 	int c, d;
    633 	FILE *fin, *dout;
    634 	int (*closefunc)(FILE *);
    635 	sigfunc oldintr, oldintp;
    636 	volatile off_t hashbytes;
    637 	char *lmode, *bufp;
    638 	static size_t bufsize;
    639 	static char *buf;
    640 	int oprogress;
    641 
    642 #ifdef __GNUC__			/* to shut up gcc warnings */
    643 	(void)&fin;
    644 	(void)&dout;
    645 	(void)&closefunc;
    646 	(void)&oldintr;
    647 	(void)&oldintp;
    648 	(void)&lmode;
    649 #endif
    650 
    651 	hashbytes = mark;
    652 	direction = "sent";
    653 	dout = NULL;
    654 	bytes = 0;
    655 	filesize = -1;
    656 	oprogress = progress;
    657 	if (verbose && printnames) {
    658 		if (local && *local != '-')
    659 			fprintf(ttyout, "local: %s ", local);
    660 		if (remote)
    661 			fprintf(ttyout, "remote: %s\n", remote);
    662 	}
    663 	if (proxy) {
    664 		proxtrans(cmd, local, remote);
    665 		return;
    666 	}
    667 	if (curtype != type)
    668 		changetype(type, 0);
    669 	closefunc = NULL;
    670 	oldintr = NULL;
    671 	oldintp = NULL;
    672 	lmode = "w";
    673 	if (sigsetjmp(xferabort, 1)) {
    674 		while (cpend)
    675 			(void)getreply(0);
    676 		code = -1;
    677 		goto cleanupsend;
    678 	}
    679 	(void)xsignal(SIGQUIT, psummary);
    680 	oldintr = xsignal(SIGINT, abortxfer);
    681 	if (strcmp(local, "-") == 0) {
    682 		fin = stdin;
    683 		progress = 0;
    684 	} else if (*local == '|') {
    685 		oldintp = xsignal(SIGPIPE, SIG_IGN);
    686 		fin = popen(local + 1, "r");
    687 		if (fin == NULL) {
    688 			warn("%s", local + 1);
    689 			code = -1;
    690 			goto cleanupsend;
    691 		}
    692 		progress = 0;
    693 		closefunc = pclose;
    694 	} else {
    695 		fin = fopen(local, "r");
    696 		if (fin == NULL) {
    697 			warn("local: %s", local);
    698 			code = -1;
    699 			goto cleanupsend;
    700 		}
    701 		closefunc = fclose;
    702 		if (fstat(fileno(fin), &st) < 0 || !S_ISREG(st.st_mode)) {
    703 			fprintf(ttyout, "%s: not a plain file.\n", local);
    704 			code = -1;
    705 			goto cleanupsend;
    706 		}
    707 		filesize = st.st_size;
    708 	}
    709 	if (initconn()) {
    710 		code = -1;
    711 		goto cleanupsend;
    712 	}
    713 	if (sigsetjmp(xferabort, 1))
    714 		goto abort;
    715 
    716 	if (restart_point &&
    717 	    (strcmp(cmd, "STOR") == 0 || strcmp(cmd, "APPE") == 0)) {
    718 		int rc;
    719 
    720 		rc = -1;
    721 		switch (curtype) {
    722 		case TYPE_A:
    723 			rc = fseek(fin, (long) restart_point, SEEK_SET);
    724 			break;
    725 		case TYPE_I:
    726 		case TYPE_L:
    727 			rc = lseek(fileno(fin), restart_point, SEEK_SET);
    728 			break;
    729 		}
    730 		if (rc < 0) {
    731 			warn("local: %s", local);
    732 			goto cleanupsend;
    733 		}
    734 		if (command("REST " LLF, (LLT)restart_point) != CONTINUE)
    735 			goto cleanupsend;
    736 		lmode = "r+w";
    737 	}
    738 	if (remote) {
    739 		if (command("%s %s", cmd, remote) != PRELIM)
    740 			goto cleanupsend;
    741 	} else {
    742 		if (command("%s", cmd) != PRELIM)
    743 			goto cleanupsend;
    744 	}
    745 	dout = dataconn(lmode);
    746 	if (dout == NULL)
    747 		goto abort;
    748 
    749 	if (sndbuf_size > bufsize) {
    750 		if (buf)
    751 			(void)free(buf);
    752 		bufsize = sndbuf_size;
    753 		buf = xmalloc(bufsize);
    754 	}
    755 
    756 	progressmeter(-1);
    757 	oldintp = xsignal(SIGPIPE, SIG_IGN);
    758 
    759 	switch (curtype) {
    760 
    761 	case TYPE_I:
    762 	case TYPE_L:
    763 		if (rate_put) {		/* rate limited */
    764 			while (1) {
    765 				struct timeval then, now, td;
    766 				off_t bufrem;
    767 
    768 				(void)gettimeofday(&then, NULL);
    769 				errno = c = d = 0;
    770 				bufrem = rate_put;
    771 				while (bufrem > 0) {
    772 					if ((c = read(fileno(fin), buf,
    773 					    MIN(bufsize, bufrem))) <= 0)
    774 						goto senddone;
    775 					bytes += c;
    776 					bufrem -= c;
    777 					for (bufp = buf; c > 0;
    778 					    c -= d, bufp += d)
    779 						if ((d = write(fileno(dout),
    780 						    bufp, c)) <= 0)
    781 							break;
    782 					if (d < 0)
    783 						goto senddone;
    784 					if (hash &&
    785 					    (!progress || filesize < 0) ) {
    786 						while (bytes >= hashbytes) {
    787 							(void)putc('#', ttyout);
    788 							hashbytes += mark;
    789 						}
    790 						(void)fflush(ttyout);
    791 					}
    792 				}
    793 				while (1) {
    794 					(void)gettimeofday(&now, NULL);
    795 					timersub(&now, &then, &td);
    796 					if (td.tv_sec > 0)
    797 						break;
    798 					usleep(1000000 - td.tv_usec);
    799 				}
    800 			}
    801 		} else {		/* simpler/faster; no rate limit */
    802 			while (1) {
    803 				errno = c = d = 0;
    804 				if ((c = read(fileno(fin), buf, bufsize)) <= 0)
    805 					goto senddone;
    806 				bytes += c;
    807 				for (bufp = buf; c > 0; c -= d, bufp += d)
    808 					if ((d = write(fileno(dout), bufp, c))
    809 					    <= 0)
    810 						break;
    811 				if (d < 0)
    812 					goto senddone;
    813 				if (hash && (!progress || filesize < 0) ) {
    814 					while (bytes >= hashbytes) {
    815 						(void)putc('#', ttyout);
    816 						hashbytes += mark;
    817 					}
    818 					(void)fflush(ttyout);
    819 				}
    820 			}
    821 		}
    822  senddone:
    823 		if (hash && (!progress || filesize < 0) && bytes > 0) {
    824 			if (bytes < mark)
    825 				(void)putc('#', ttyout);
    826 			(void)putc('\n', ttyout);
    827 		}
    828 		if (c < 0)
    829 			warn("local: %s", local);
    830 		if (d < 0) {
    831 			if (errno != EPIPE)
    832 				warn("netout");
    833 			bytes = -1;
    834 		}
    835 		break;
    836 
    837 	case TYPE_A:
    838 		while ((c = getc(fin)) != EOF) {
    839 			if (c == '\n') {
    840 				while (hash && (!progress || filesize < 0) &&
    841 				    (bytes >= hashbytes)) {
    842 					(void)putc('#', ttyout);
    843 					(void)fflush(ttyout);
    844 					hashbytes += mark;
    845 				}
    846 				if (ferror(dout))
    847 					break;
    848 				(void)putc('\r', dout);
    849 				bytes++;
    850 			}
    851 			(void)putc(c, dout);
    852 			bytes++;
    853 #if 0	/* this violates RFC */
    854 			if (c == '\r') {
    855 				(void)putc('\0', dout);
    856 				bytes++;
    857 			}
    858 #endif
    859 		}
    860 		if (hash && (!progress || filesize < 0)) {
    861 			if (bytes < hashbytes)
    862 				(void)putc('#', ttyout);
    863 			(void)putc('\n', ttyout);
    864 		}
    865 		if (ferror(fin))
    866 			warn("local: %s", local);
    867 		if (ferror(dout)) {
    868 			if (errno != EPIPE)
    869 				warn("netout");
    870 			bytes = -1;
    871 		}
    872 		break;
    873 	}
    874 
    875 	progressmeter(1);
    876 	if (closefunc != NULL) {
    877 		(*closefunc)(fin);
    878 		fin = NULL;
    879 	}
    880 	(void)fclose(dout);
    881 	dout = NULL;
    882 	(void)getreply(0);
    883 	if (bytes > 0)
    884 		ptransfer(0);
    885 	goto cleanupsend;
    886 
    887  abort:
    888 	(void)xsignal(SIGINT, oldintr);
    889 	oldintr = NULL;
    890 	if (!cpend) {
    891 		code = -1;
    892 		goto cleanupsend;
    893 	}
    894 	if (data >= 0) {
    895 		(void)close(data);
    896 		data = -1;
    897 	}
    898 	if (dout) {
    899 		(void)fclose(dout);
    900 		dout = NULL;
    901 	}
    902 	(void)getreply(0);
    903 	code = -1;
    904 	if (bytes > 0)
    905 		ptransfer(0);
    906 
    907  cleanupsend:
    908 	if (oldintr)
    909 		(void)xsignal(SIGINT, oldintr);
    910 	if (oldintp)
    911 		(void)xsignal(SIGPIPE, oldintp);
    912 	if (data >= 0) {
    913 		(void)close(data);
    914 		data = -1;
    915 	}
    916 	if (closefunc != NULL && fin != NULL)
    917 		(*closefunc)(fin);
    918 	if (dout)
    919 		(void)fclose(dout);
    920 	progress = oprogress;
    921 	restart_point = 0;
    922 	bytes = 0;
    923 }
    924 
    925 void
    926 recvrequest(const char *cmd, const char *local, const char *remote,
    927 	    const char *lmode, int printnames, int ignorespecial)
    928 {
    929 	FILE *fout, *din;
    930 	int (*closefunc)(FILE *);
    931 	sigfunc oldintr, oldintp;
    932 	int c, d;
    933 	volatile int is_retr, tcrflag, bare_lfs;
    934 	static size_t bufsize;
    935 	static char *buf;
    936 	volatile off_t hashbytes;
    937 	struct stat st;
    938 	time_t mtime;
    939 	struct timeval tval[2];
    940 	int oprogress;
    941 	int opreserve;
    942 
    943 #ifdef __GNUC__			/* to shut up gcc warnings */
    944 	(void)&local;
    945 	(void)&fout;
    946 	(void)&din;
    947 	(void)&closefunc;
    948 	(void)&oldintr;
    949 	(void)&oldintp;
    950 #endif
    951 
    952 	fout = NULL;
    953 	din = NULL;
    954 	hashbytes = mark;
    955 	direction = "received";
    956 	bytes = 0;
    957 	bare_lfs = 0;
    958 	filesize = -1;
    959 	oprogress = progress;
    960 	opreserve = preserve;
    961 	is_retr = (strcmp(cmd, "RETR") == 0);
    962 	if (is_retr && verbose && printnames) {
    963 		if (local && (ignorespecial || *local != '-'))
    964 			fprintf(ttyout, "local: %s ", local);
    965 		if (remote)
    966 			fprintf(ttyout, "remote: %s\n", remote);
    967 	}
    968 	if (proxy && is_retr) {
    969 		proxtrans(cmd, local, remote);
    970 		return;
    971 	}
    972 	closefunc = NULL;
    973 	oldintr = NULL;
    974 	oldintp = NULL;
    975 	tcrflag = !crflag && is_retr;
    976 	if (sigsetjmp(xferabort, 1)) {
    977 		while (cpend)
    978 			(void)getreply(0);
    979 		code = -1;
    980 		goto cleanuprecv;
    981 	}
    982 	(void)xsignal(SIGQUIT, psummary);
    983 	oldintr = xsignal(SIGINT, abortxfer);
    984 	if (ignorespecial || (strcmp(local, "-") && *local != '|')) {
    985 		if (access(local, W_OK) < 0) {
    986 			char *dir = strrchr(local, '/');
    987 
    988 			if (errno != ENOENT && errno != EACCES) {
    989 				warn("local: %s", local);
    990 				code = -1;
    991 				goto cleanuprecv;
    992 			}
    993 			if (dir != NULL)
    994 				*dir = 0;
    995 			d = access(dir == local ? "/" :
    996 			    dir ? local : ".", W_OK);
    997 			if (dir != NULL)
    998 				*dir = '/';
    999 			if (d < 0) {
   1000 				warn("local: %s", local);
   1001 				code = -1;
   1002 				goto cleanuprecv;
   1003 			}
   1004 			if (!runique && errno == EACCES &&
   1005 			    chmod(local, (S_IRUSR|S_IWUSR)) < 0) {
   1006 				warn("local: %s", local);
   1007 				code = -1;
   1008 				goto cleanuprecv;
   1009 			}
   1010 			if (runique && errno == EACCES &&
   1011 			   (local = gunique(local)) == NULL) {
   1012 				code = -1;
   1013 				goto cleanuprecv;
   1014 			}
   1015 		}
   1016 		else if (runique && (local = gunique(local)) == NULL) {
   1017 			code = -1;
   1018 			goto cleanuprecv;
   1019 		}
   1020 	}
   1021 	if (!is_retr) {
   1022 		if (curtype != TYPE_A)
   1023 			changetype(TYPE_A, 0);
   1024 	} else {
   1025 		if (curtype != type)
   1026 			changetype(type, 0);
   1027 		filesize = remotesize(remote, 0);
   1028 		if (code == 421 || code == -1)
   1029 			goto cleanuprecv;
   1030 	}
   1031 	if (initconn()) {
   1032 		code = -1;
   1033 		goto cleanuprecv;
   1034 	}
   1035 	if (sigsetjmp(xferabort, 1))
   1036 		goto abort;
   1037 	if (is_retr && restart_point &&
   1038 	    command("REST " LLF, (LLT) restart_point) != CONTINUE)
   1039 		goto cleanuprecv;
   1040 	if (! EMPTYSTRING(remote)) {
   1041 		if (command("%s %s", cmd, remote) != PRELIM)
   1042 			goto cleanuprecv;
   1043 	} else {
   1044 		if (command("%s", cmd) != PRELIM)
   1045 			goto cleanuprecv;
   1046 	}
   1047 	din = dataconn("r");
   1048 	if (din == NULL)
   1049 		goto abort;
   1050 	if (!ignorespecial && strcmp(local, "-") == 0) {
   1051 		fout = stdout;
   1052 		progress = 0;
   1053 		preserve = 0;
   1054 	} else if (!ignorespecial && *local == '|') {
   1055 		oldintp = xsignal(SIGPIPE, SIG_IGN);
   1056 		fout = popen(local + 1, "w");
   1057 		if (fout == NULL) {
   1058 			warn("%s", local+1);
   1059 			goto abort;
   1060 		}
   1061 		progress = 0;
   1062 		preserve = 0;
   1063 		closefunc = pclose;
   1064 	} else {
   1065 		fout = fopen(local, lmode);
   1066 		if (fout == NULL) {
   1067 			warn("local: %s", local);
   1068 			goto abort;
   1069 		}
   1070 		closefunc = fclose;
   1071 	}
   1072 
   1073 	if (fstat(fileno(fout), &st) != -1 && !S_ISREG(st.st_mode)) {
   1074 		progress = 0;
   1075 		preserve = 0;
   1076 	}
   1077 	if (rcvbuf_size > bufsize) {
   1078 		if (buf)
   1079 			(void)free(buf);
   1080 		bufsize = rcvbuf_size;
   1081 		buf = xmalloc(bufsize);
   1082 	}
   1083 
   1084 	progressmeter(-1);
   1085 
   1086 	switch (curtype) {
   1087 
   1088 	case TYPE_I:
   1089 	case TYPE_L:
   1090 		if (is_retr && restart_point &&
   1091 		    lseek(fileno(fout), restart_point, SEEK_SET) < 0) {
   1092 			warn("local: %s", local);
   1093 			goto cleanuprecv;
   1094 		}
   1095 		if (rate_get) {		/* rate limiting */
   1096 			while (1) {
   1097 				struct timeval then, now, td;
   1098 				off_t bufrem;
   1099 
   1100 				(void)gettimeofday(&then, NULL);
   1101 				errno = c = d = 0;
   1102 				for (bufrem = rate_get; bufrem > 0; ) {
   1103 					if ((c = read(fileno(din), buf,
   1104 					    MIN(bufsize, bufrem))) <= 0)
   1105 						goto recvdone;
   1106 					bytes += c;
   1107 					bufrem -=c;
   1108 					if ((d = write(fileno(fout), buf, c))
   1109 					    != c)
   1110 						goto recvdone;
   1111 					if (hash &&
   1112 					    (!progress || filesize < 0)) {
   1113 						while (bytes >= hashbytes) {
   1114 							(void)putc('#', ttyout);
   1115 							hashbytes += mark;
   1116 						}
   1117 						(void)fflush(ttyout);
   1118 					}
   1119 				}
   1120 					/* sleep until time is up */
   1121 				while (1) {
   1122 					(void)gettimeofday(&now, NULL);
   1123 					timersub(&now, &then, &td);
   1124 					if (td.tv_sec > 0)
   1125 						break;
   1126 					usleep(1000000 - td.tv_usec);
   1127 				}
   1128 			}
   1129 		} else {		/* faster code (no limiting) */
   1130 			while (1) {
   1131 				errno = c = d = 0;
   1132 				if ((c = read(fileno(din), buf, bufsize)) <= 0)
   1133 					goto recvdone;
   1134 				bytes += c;
   1135 				if ((d = write(fileno(fout), buf, c)) != c)
   1136 					goto recvdone;
   1137 				if (hash && (!progress || filesize < 0)) {
   1138 					while (bytes >= hashbytes) {
   1139 						(void)putc('#', ttyout);
   1140 						hashbytes += mark;
   1141 					}
   1142 					(void)fflush(ttyout);
   1143 				}
   1144 			}
   1145 		}
   1146  recvdone:
   1147 		if (hash && (!progress || filesize < 0) && bytes > 0) {
   1148 			if (bytes < mark)
   1149 				(void)putc('#', ttyout);
   1150 			(void)putc('\n', ttyout);
   1151 		}
   1152 		if (c < 0) {
   1153 			if (errno != EPIPE)
   1154 				warn("netin");
   1155 			bytes = -1;
   1156 		}
   1157 		if (d < c) {
   1158 			if (d < 0)
   1159 				warn("local: %s", local);
   1160 			else
   1161 				warnx("%s: short write", local);
   1162 		}
   1163 		break;
   1164 
   1165 	case TYPE_A:
   1166 		if (is_retr && restart_point) {
   1167 			int ch;
   1168 			long i, n;
   1169 
   1170 			if (fseek(fout, 0L, SEEK_SET) < 0)
   1171 				goto done;
   1172 			n = (long)restart_point;
   1173 			for (i = 0; i++ < n;) {
   1174 				if ((ch = getc(fout)) == EOF)
   1175 					goto done;
   1176 				if (ch == '\n')
   1177 					i++;
   1178 			}
   1179 			if (fseek(fout, 0L, SEEK_CUR) < 0) {
   1180  done:
   1181 				warn("local: %s", local);
   1182 				goto cleanuprecv;
   1183 			}
   1184 		}
   1185 		while ((c = getc(din)) != EOF) {
   1186 			if (c == '\n')
   1187 				bare_lfs++;
   1188 			while (c == '\r') {
   1189 				while (hash && (!progress || filesize < 0) &&
   1190 				    (bytes >= hashbytes)) {
   1191 					(void)putc('#', ttyout);
   1192 					(void)fflush(ttyout);
   1193 					hashbytes += mark;
   1194 				}
   1195 				bytes++;
   1196 				if ((c = getc(din)) != '\n' || tcrflag) {
   1197 					if (ferror(fout))
   1198 						goto break2;
   1199 					(void)putc('\r', fout);
   1200 					if (c == '\0') {
   1201 						bytes++;
   1202 						goto contin2;
   1203 					}
   1204 					if (c == EOF)
   1205 						goto contin2;
   1206 				}
   1207 			}
   1208 			(void)putc(c, fout);
   1209 			bytes++;
   1210 	contin2:	;
   1211 		}
   1212 break2:
   1213 		if (hash && (!progress || filesize < 0)) {
   1214 			if (bytes < hashbytes)
   1215 				(void)putc('#', ttyout);
   1216 			(void)putc('\n', ttyout);
   1217 		}
   1218 		if (ferror(din)) {
   1219 			if (errno != EPIPE)
   1220 				warn("netin");
   1221 			bytes = -1;
   1222 		}
   1223 		if (ferror(fout))
   1224 			warn("local: %s", local);
   1225 		break;
   1226 	}
   1227 
   1228 	progressmeter(1);
   1229 	if (closefunc != NULL) {
   1230 		(*closefunc)(fout);
   1231 		fout = NULL;
   1232 	}
   1233 	(void)fclose(din);
   1234 	din = NULL;
   1235 	(void)getreply(0);
   1236 	if (bare_lfs) {
   1237 		fprintf(ttyout,
   1238 		    "WARNING! %d bare linefeeds received in ASCII mode.\n",
   1239 		    bare_lfs);
   1240 		fputs("File may not have transferred correctly.\n", ttyout);
   1241 	}
   1242 	if (bytes >= 0 && is_retr) {
   1243 		if (bytes > 0)
   1244 			ptransfer(0);
   1245 		if (preserve && (closefunc == fclose)) {
   1246 			mtime = remotemodtime(remote, 0);
   1247 			if (mtime != -1) {
   1248 				(void)gettimeofday(&tval[0], NULL);
   1249 				tval[1].tv_sec = mtime;
   1250 				tval[1].tv_usec = 0;
   1251 				if (utimes(local, tval) == -1) {
   1252 					fprintf(ttyout,
   1253 				"Can't change modification time on %s to %s",
   1254 					    local, asctime(localtime(&mtime)));
   1255 				}
   1256 			}
   1257 		}
   1258 	}
   1259 	goto cleanuprecv;
   1260 
   1261  abort:
   1262 			/*
   1263 			 * abort using RFC 959 recommended IP,SYNC sequence
   1264 			 */
   1265 	if (! sigsetjmp(xferabort, 1)) {
   1266 			/* this is the first call */
   1267 		(void)xsignal(SIGINT, abort_squared);
   1268 		if (!cpend) {
   1269 			code = -1;
   1270 			goto cleanuprecv;
   1271 		}
   1272 		abort_remote(din);
   1273 	}
   1274 	code = -1;
   1275 	if (bytes > 0)
   1276 		ptransfer(0);
   1277 
   1278  cleanuprecv:
   1279 	if (oldintr)
   1280 		(void)xsignal(SIGINT, oldintr);
   1281 	if (oldintp)
   1282 		(void)xsignal(SIGPIPE, oldintp);
   1283 	if (data >= 0) {
   1284 		(void)close(data);
   1285 		data = -1;
   1286 	}
   1287 	if (closefunc != NULL && fout != NULL)
   1288 		(*closefunc)(fout);
   1289 	if (din)
   1290 		(void)fclose(din);
   1291 	progress = oprogress;
   1292 	preserve = opreserve;
   1293 	bytes = 0;
   1294 }
   1295 
   1296 /*
   1297  * Need to start a listen on the data channel before we send the command,
   1298  * otherwise the server's connect may fail.
   1299  */
   1300 int
   1301 initconn(void)
   1302 {
   1303 	char *p, *a;
   1304 	int result, len, tmpno = 0;
   1305 	int on = 1;
   1306 	int error;
   1307 	u_int addr[16], port[2];
   1308 	u_int af, hal, pal;
   1309 	char *pasvcmd = NULL;
   1310 
   1311 #ifdef INET6
   1312 	if (myctladdr.su_family == AF_INET6 && debug &&
   1313 	    (IN6_IS_ADDR_LINKLOCAL(&myctladdr.si_su.su_sin6.sin6_addr) ||
   1314 	     IN6_IS_ADDR_SITELOCAL(&myctladdr.si_su.su_sin6.sin6_addr))) {
   1315 		warnx("use of scoped address can be troublesome");
   1316 	}
   1317 #endif
   1318  reinit:
   1319 	if (passivemode) {
   1320 		data_addr = myctladdr;
   1321 		data = socket(data_addr.su_family, SOCK_STREAM, 0);
   1322 		if (data < 0) {
   1323 			warn("socket");
   1324 			return (1);
   1325 		}
   1326 		if ((options & SO_DEBUG) &&
   1327 		    setsockopt(data, SOL_SOCKET, SO_DEBUG, (char *)&on,
   1328 			       sizeof(on)) < 0)
   1329 			warn("setsockopt (ignored)");
   1330 		result = COMPLETE + 1;
   1331 		switch (data_addr.su_family) {
   1332 		case AF_INET:
   1333 			if (epsv4 && !epsv4bad) {
   1334 			  	pasvcmd = "EPSV";
   1335 				result = command("EPSV");
   1336 				if (!connected)
   1337 					return (1);
   1338 				/*
   1339 				 * this code is to be friendly with broken
   1340 				 * BSDI ftpd
   1341 				 */
   1342 				if (code / 10 == 22 && code != 229) {
   1343 					fputs(
   1344 "wrong server: return code must be 229\n",
   1345 						ttyout);
   1346 					result = COMPLETE + 1;
   1347 				}
   1348 				if (result != COMPLETE) {
   1349 					epsv4bad = 1;
   1350 					if (debug)
   1351 						fputs(
   1352 					"disabling epsv4 for this connection\n",
   1353 						    ttyout);
   1354 				}
   1355 			}
   1356 			if (result != COMPLETE) {
   1357 			  	pasvcmd = "PASV";
   1358 				result = command("PASV");
   1359 				if (!connected)
   1360 					return (1);
   1361 			}
   1362 			break;
   1363 #ifdef INET6
   1364 		case AF_INET6:
   1365 		  	pasvcmd = "EPSV";
   1366 			result = command("EPSV");
   1367 			if (!connected)
   1368 				return (1);
   1369 			/* this code is to be friendly with broken BSDI ftpd */
   1370 			if (code / 10 == 22 && code != 229) {
   1371 				fputs(
   1372 "wrong server: return code must be 229\n",
   1373 					ttyout);
   1374 				result = COMPLETE + 1;
   1375 			}
   1376 			if (result != COMPLETE) {
   1377 				pasvcmd = "LPSV";
   1378 				result = command("LPSV");
   1379 			}
   1380 			if (!connected)
   1381 				return (1);
   1382 			break;
   1383 #endif
   1384 		default:
   1385 			result = COMPLETE + 1;
   1386 			break;
   1387 		}
   1388 		if (result != COMPLETE) {
   1389 			if (activefallback) {
   1390 				(void)close(data);
   1391 				data = -1;
   1392 				passivemode = 0;
   1393 #if 0
   1394 				activefallback = 0;
   1395 #endif
   1396 				goto reinit;
   1397 			}
   1398 			fputs("Passive mode refused.\n", ttyout);
   1399 			goto bad;
   1400 		}
   1401 
   1402 #define	pack2(var, off) \
   1403 	(((var[(off) + 0] & 0xff) << 8) | ((var[(off) + 1] & 0xff) << 0))
   1404 #define	pack4(var, off) \
   1405 	(((var[(off) + 0] & 0xff) << 24) | ((var[(off) + 1] & 0xff) << 16) | \
   1406 	 ((var[(off) + 2] & 0xff) << 8) | ((var[(off) + 3] & 0xff) << 0))
   1407 #define	UC(b)	(((int)b)&0xff)
   1408 
   1409 		/*
   1410 		 * What we've got at this point is a string of comma separated
   1411 		 * one-byte unsigned integer values, separated by commas.
   1412 		 */
   1413 		if (strcmp(pasvcmd, "PASV") == 0) {
   1414 			if (data_addr.su_family != AF_INET) {
   1415 				fputs(
   1416     "Passive mode AF mismatch. Shouldn't happen!\n", ttyout);
   1417 				error = 1;
   1418 				goto bad;
   1419 			}
   1420 			if (code / 10 == 22 && code != 227) {
   1421 				fputs("wrong server: return code must be 227\n",
   1422 					ttyout);
   1423 				error = 1;
   1424 				goto bad;
   1425 			}
   1426 			error = sscanf(pasv, "%u,%u,%u,%u,%u,%u",
   1427 					&addr[0], &addr[1], &addr[2], &addr[3],
   1428 					&port[0], &port[1]);
   1429 			if (error != 6) {
   1430 				fputs(
   1431 "Passive mode address scan failure. Shouldn't happen!\n", ttyout);
   1432 				error = 1;
   1433 				goto bad;
   1434 			}
   1435 			error = 0;
   1436 			memset(&data_addr, 0, sizeof(data_addr));
   1437 			data_addr.su_family = AF_INET;
   1438 			data_addr.su_len = sizeof(struct sockaddr_in);
   1439 			data_addr.si_su.su_sin.sin_addr.s_addr =
   1440 			    htonl(pack4(addr, 0));
   1441 			data_addr.su_port = htons(pack2(port, 0));
   1442 		} else if (strcmp(pasvcmd, "LPSV") == 0) {
   1443 			if (code / 10 == 22 && code != 228) {
   1444 				fputs("wrong server: return code must be 228\n",
   1445 					ttyout);
   1446 				error = 1;
   1447 				goto bad;
   1448 			}
   1449 			switch (data_addr.su_family) {
   1450 			case AF_INET:
   1451 				error = sscanf(pasv,
   1452 "%u,%u,%u,%u,%u,%u,%u,%u,%u",
   1453 					&af, &hal,
   1454 					&addr[0], &addr[1], &addr[2], &addr[3],
   1455 					&pal, &port[0], &port[1]);
   1456 				if (error != 9) {
   1457 					fputs(
   1458 "Passive mode address scan failure. Shouldn't happen!\n", ttyout);
   1459 					error = 1;
   1460 					goto bad;
   1461 				}
   1462 				if (af != 4 || hal != 4 || pal != 2) {
   1463 					fputs(
   1464 "Passive mode AF mismatch. Shouldn't happen!\n", ttyout);
   1465 					error = 1;
   1466 					goto bad;
   1467 				}
   1468 
   1469 				error = 0;
   1470 				memset(&data_addr, 0, sizeof(data_addr));
   1471 				data_addr.su_family = AF_INET;
   1472 				data_addr.su_len = sizeof(struct sockaddr_in);
   1473 				data_addr.si_su.su_sin.sin_addr.s_addr =
   1474 				    htonl(pack4(addr, 0));
   1475 				data_addr.su_port = htons(pack2(port, 0));
   1476 				break;
   1477 #ifdef INET6
   1478 			case AF_INET6:
   1479 				error = sscanf(pasv,
   1480 "%u,%u,%u,%u,%u,%u,%u,%u,%u,%u,%u,%u,%u,%u,%u,%u,%u,%u,%u,%u,%u",
   1481 					&af, &hal,
   1482 					&addr[0], &addr[1], &addr[2], &addr[3],
   1483 					&addr[4], &addr[5], &addr[6], &addr[7],
   1484 					&addr[8], &addr[9], &addr[10],
   1485 					&addr[11], &addr[12], &addr[13],
   1486 					&addr[14], &addr[15],
   1487 					&pal, &port[0], &port[1]);
   1488 				if (error != 21) {
   1489 					fputs(
   1490 "Passive mode address scan failure. Shouldn't happen!\n", ttyout);
   1491 					error = 1;
   1492 					goto bad;
   1493 				}
   1494 				if (af != 6 || hal != 16 || pal != 2) {
   1495 					fputs(
   1496 "Passive mode AF mismatch. Shouldn't happen!\n", ttyout);
   1497 					error = 1;
   1498 					goto bad;
   1499 				}
   1500 
   1501 				error = 0;
   1502 				memset(&data_addr, 0, sizeof(data_addr));
   1503 				data_addr.su_family = AF_INET6;
   1504 				data_addr.su_len = sizeof(struct sockaddr_in6);
   1505 			    {
   1506 				int i;
   1507 				for (i = 0; i < sizeof(struct in6_addr); i++) {
   1508 					data_addr.si_su.su_sin6.sin6_addr.s6_addr[i] =
   1509 					    UC(addr[i]);
   1510 				}
   1511 			    }
   1512 				data_addr.su_port = htons(pack2(port, 0));
   1513 				break;
   1514 #endif
   1515 			default:
   1516 				error = 1;
   1517 			}
   1518 		} else if (strcmp(pasvcmd, "EPSV") == 0) {
   1519 			char delim[4];
   1520 
   1521 			port[0] = 0;
   1522 			if (code / 10 == 22 && code != 229) {
   1523 				fputs("wrong server: return code must be 229\n",
   1524 					ttyout);
   1525 				error = 1;
   1526 				goto bad;
   1527 			}
   1528 			if (sscanf(pasv, "%c%c%c%d%c", &delim[0],
   1529 					&delim[1], &delim[2], &port[1],
   1530 					&delim[3]) != 5) {
   1531 				fputs("parse error!\n", ttyout);
   1532 				error = 1;
   1533 				goto bad;
   1534 			}
   1535 			if (delim[0] != delim[1] || delim[0] != delim[2]
   1536 			 || delim[0] != delim[3]) {
   1537 				fputs("parse error!\n", ttyout);
   1538 				error = 1;
   1539 				goto bad;
   1540 			}
   1541 			data_addr = hisctladdr;
   1542 			data_addr.su_port = htons(port[1]);
   1543 		} else
   1544 			goto bad;
   1545 
   1546 		while (xconnect(data, (struct sockaddr *)&data_addr.si_su,
   1547 			    data_addr.su_len) < 0) {
   1548 			if (errno == EINTR)
   1549 				continue;
   1550 			if (activefallback) {
   1551 				(void)close(data);
   1552 				data = -1;
   1553 				passivemode = 0;
   1554 #if 0
   1555 				activefallback = 0;
   1556 #endif
   1557 				goto reinit;
   1558 			}
   1559 			warn("connect");
   1560 			goto bad;
   1561 		}
   1562 #ifdef IPTOS_THROUGHPUT
   1563 		if (data_addr.su_family == AF_INET) {
   1564 			on = IPTOS_THROUGHPUT;
   1565 			if (setsockopt(data, IPPROTO_IP, IP_TOS, (char *)&on,
   1566 				       sizeof(int)) < 0)
   1567 				warn("setsockopt TOS (ignored)");
   1568 		}
   1569 #endif
   1570 		return (0);
   1571 	}
   1572 
   1573  noport:
   1574 	data_addr = myctladdr;
   1575 	if (sendport)
   1576 		data_addr.su_port = 0;	/* let system pick one */
   1577 	if (data != -1)
   1578 		(void)close(data);
   1579 	data = socket(data_addr.su_family, SOCK_STREAM, 0);
   1580 	if (data < 0) {
   1581 		warn("socket");
   1582 		if (tmpno)
   1583 			sendport = 1;
   1584 		return (1);
   1585 	}
   1586 	if (!sendport)
   1587 		if (setsockopt(data, SOL_SOCKET, SO_REUSEADDR, (char *)&on,
   1588 				sizeof(on)) < 0) {
   1589 			warn("setsockopt (reuse address)");
   1590 			goto bad;
   1591 		}
   1592 	if (bind(data, (struct sockaddr *)&data_addr.si_su,
   1593 	    data_addr.su_len) < 0) {
   1594 		warn("bind");
   1595 		goto bad;
   1596 	}
   1597 	if (options & SO_DEBUG &&
   1598 	    setsockopt(data, SOL_SOCKET, SO_DEBUG, (char *)&on,
   1599 			sizeof(on)) < 0)
   1600 		warn("setsockopt (ignored)");
   1601 	len = sizeof(data_addr.si_su);
   1602 	memset((char *)&data_addr, 0, sizeof (data_addr));
   1603 	if (getsockname(data, (struct sockaddr *)&data_addr.si_su, &len) < 0) {
   1604 		warn("getsockname");
   1605 		goto bad;
   1606 	}
   1607 	data_addr.su_len = len;
   1608 	if (xlisten(data, 1) < 0)
   1609 		warn("listen");
   1610 
   1611 	if (sendport) {
   1612 #ifdef INET6
   1613 		char hname[INET6_ADDRSTRLEN];
   1614 		int af;
   1615 #endif
   1616 
   1617 		switch (data_addr.su_family) {
   1618 		case AF_INET:
   1619 			if (!epsv4 || epsv4bad) {
   1620 				result = COMPLETE + 1;
   1621 				break;
   1622 			}
   1623 			/* FALLTHROUGH */
   1624 #ifdef INET6
   1625 		case AF_INET6:
   1626 			af = (data_addr.su_family == AF_INET) ? 1 : 2;
   1627 			if (getnameinfo((struct sockaddr *)&data_addr.si_su,
   1628 			    data_addr.su_len, hname, sizeof(hname), NULL, 0,
   1629 			    NI_NUMERICHOST)) {
   1630 				result = ERROR;
   1631 			} else {
   1632 				result = command("EPRT |%d|%s|%d|", af, hname,
   1633 						ntohs(data_addr.su_port));
   1634 				if (!connected)
   1635 					return (1);
   1636 				if (result != COMPLETE) {
   1637 					epsv4bad = 1;
   1638 					if (debug)
   1639 						fputs(
   1640 					"disabling epsv4 for this connection\n",
   1641 						    ttyout);
   1642 				}
   1643 			}
   1644 			break;
   1645 #endif
   1646 		default:
   1647 			result = COMPLETE + 1;
   1648 			break;
   1649 		}
   1650 		if (result == COMPLETE)
   1651 			goto skip_port;
   1652 
   1653 		switch (data_addr.su_family) {
   1654 		case AF_INET:
   1655 			a = (char *)&data_addr.si_su.su_sin.sin_addr;
   1656 			p = (char *)&data_addr.su_port;
   1657 			result = command("PORT %d,%d,%d,%d,%d,%d",
   1658 				 UC(a[0]), UC(a[1]), UC(a[2]), UC(a[3]),
   1659 				 UC(p[0]), UC(p[1]));
   1660 			break;
   1661 #ifdef INET6
   1662 		case AF_INET6:
   1663 			a = (char *)&data_addr.si_su.su_sin6.sin6_addr;
   1664 			p = (char *)&data_addr.su_port;
   1665 			result = command(
   1666 	"LPRT %d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d",
   1667 				 6, 16,
   1668 				 UC(a[0]),UC(a[1]),UC(a[2]),UC(a[3]),
   1669 				 UC(a[4]),UC(a[5]),UC(a[6]),UC(a[7]),
   1670 				 UC(a[8]),UC(a[9]),UC(a[10]),UC(a[11]),
   1671 				 UC(a[12]),UC(a[13]),UC(a[14]),UC(a[15]),
   1672 				 2, UC(p[0]), UC(p[1]));
   1673 			break;
   1674 #endif
   1675 		default:
   1676 			result = COMPLETE + 1; /* xxx */
   1677 		}
   1678 		if (!connected)
   1679 			return (1);
   1680 	skip_port:
   1681 
   1682 		if (result == ERROR && sendport == -1) {
   1683 			sendport = 0;
   1684 			tmpno = 1;
   1685 			goto noport;
   1686 		}
   1687 		return (result != COMPLETE);
   1688 	}
   1689 	if (tmpno)
   1690 		sendport = 1;
   1691 #ifdef IPTOS_THROUGHPUT
   1692 	if (data_addr.su_family == AF_INET) {
   1693 		on = IPTOS_THROUGHPUT;
   1694 		if (setsockopt(data, IPPROTO_IP, IP_TOS, (char *)&on,
   1695 			       sizeof(int)) < 0)
   1696 			warn("setsockopt TOS (ignored)");
   1697 	}
   1698 #endif
   1699 	return (0);
   1700  bad:
   1701 	(void)close(data), data = -1;
   1702 	if (tmpno)
   1703 		sendport = 1;
   1704 	return (1);
   1705 }
   1706 
   1707 FILE *
   1708 dataconn(const char *lmode)
   1709 {
   1710 	struct sockinet from;
   1711 	int s, fromlen = myctladdr.su_len;
   1712 
   1713 	if (passivemode)
   1714 		return (fdopen(data, lmode));
   1715 
   1716 	s = accept(data, (struct sockaddr *) &from.si_su, &fromlen);
   1717 	if (s < 0) {
   1718 		warn("accept");
   1719 		(void)close(data), data = -1;
   1720 		return (NULL);
   1721 	}
   1722 	(void)close(data);
   1723 	data = s;
   1724 #ifdef IPTOS_THROUGHPUT
   1725 	if (from.su_family == AF_INET) {
   1726 		int tos = IPTOS_THROUGHPUT;
   1727 		if (setsockopt(s, IPPROTO_IP, IP_TOS, (char *)&tos,
   1728 				sizeof(int)) < 0) {
   1729 			warn("setsockopt TOS (ignored)");
   1730 		}
   1731 	}
   1732 #endif
   1733 	return (fdopen(data, lmode));
   1734 }
   1735 
   1736 void
   1737 psabort(int notused)
   1738 {
   1739 	int oerrno = errno;
   1740 
   1741 	alarmtimer(0);
   1742 	abrtflag++;
   1743 	errno = oerrno;
   1744 }
   1745 
   1746 void
   1747 pswitch(int flag)
   1748 {
   1749 	sigfunc oldintr;
   1750 	static struct comvars {
   1751 		int connect;
   1752 		char name[MAXHOSTNAMELEN];
   1753 		struct sockinet mctl;
   1754 		struct sockinet hctl;
   1755 		FILE *in;
   1756 		FILE *out;
   1757 		int tpe;
   1758 		int curtpe;
   1759 		int cpnd;
   1760 		int sunqe;
   1761 		int runqe;
   1762 		int mcse;
   1763 		int ntflg;
   1764 		char nti[17];
   1765 		char nto[17];
   1766 		int mapflg;
   1767 		char mi[MAXPATHLEN];
   1768 		char mo[MAXPATHLEN];
   1769 	} proxstruct, tmpstruct;
   1770 	struct comvars *ip, *op;
   1771 
   1772 	abrtflag = 0;
   1773 	oldintr = xsignal(SIGINT, psabort);
   1774 	if (flag) {
   1775 		if (proxy)
   1776 			return;
   1777 		ip = &tmpstruct;
   1778 		op = &proxstruct;
   1779 		proxy++;
   1780 	} else {
   1781 		if (!proxy)
   1782 			return;
   1783 		ip = &proxstruct;
   1784 		op = &tmpstruct;
   1785 		proxy = 0;
   1786 	}
   1787 	ip->connect = connected;
   1788 	connected = op->connect;
   1789 	if (hostname)
   1790 		(void)strlcpy(ip->name, hostname, sizeof(ip->name));
   1791 	else
   1792 		ip->name[0] = '\0';
   1793 	hostname = op->name;
   1794 	ip->hctl = hisctladdr;
   1795 	hisctladdr = op->hctl;
   1796 	ip->mctl = myctladdr;
   1797 	myctladdr = op->mctl;
   1798 	ip->in = cin;
   1799 	cin = op->in;
   1800 	ip->out = cout;
   1801 	cout = op->out;
   1802 	ip->tpe = type;
   1803 	type = op->tpe;
   1804 	ip->curtpe = curtype;
   1805 	curtype = op->curtpe;
   1806 	ip->cpnd = cpend;
   1807 	cpend = op->cpnd;
   1808 	ip->sunqe = sunique;
   1809 	sunique = op->sunqe;
   1810 	ip->runqe = runique;
   1811 	runique = op->runqe;
   1812 	ip->mcse = mcase;
   1813 	mcase = op->mcse;
   1814 	ip->ntflg = ntflag;
   1815 	ntflag = op->ntflg;
   1816 	(void)strlcpy(ip->nti, ntin, sizeof(ip->nti));
   1817 	(void)strlcpy(ntin, op->nti, sizeof(ntin));
   1818 	(void)strlcpy(ip->nto, ntout, sizeof(ip->nto));
   1819 	(void)strlcpy(ntout, op->nto, sizeof(ntout));
   1820 	ip->mapflg = mapflag;
   1821 	mapflag = op->mapflg;
   1822 	(void)strlcpy(ip->mi, mapin, sizeof(ip->mi));
   1823 	(void)strlcpy(mapin, op->mi, sizeof(mapin));
   1824 	(void)strlcpy(ip->mo, mapout, sizeof(ip->mo));
   1825 	(void)strlcpy(mapout, op->mo, sizeof(mapout));
   1826 	(void)xsignal(SIGINT, oldintr);
   1827 	if (abrtflag) {
   1828 		abrtflag = 0;
   1829 		(*oldintr)(SIGINT);
   1830 	}
   1831 }
   1832 
   1833 void
   1834 abortpt(int notused)
   1835 {
   1836 
   1837 	alarmtimer(0);
   1838 	if (fromatty)
   1839 		write(fileno(ttyout), "\n", 1);
   1840 	ptabflg++;
   1841 	mflag = 0;
   1842 	abrtflag = 0;
   1843 	siglongjmp(ptabort, 1);
   1844 }
   1845 
   1846 void
   1847 proxtrans(const char *cmd, const char *local, const char *remote)
   1848 {
   1849 	sigfunc oldintr;
   1850 	int prox_type, nfnd;
   1851 	volatile int secndflag;
   1852 	char *cmd2;
   1853 
   1854 #ifdef __GNUC__			/* to shut up gcc warnings */
   1855 	(void)&oldintr;
   1856 	(void)&cmd2;
   1857 #endif
   1858 
   1859 	oldintr = NULL;
   1860 	secndflag = 0;
   1861 	if (strcmp(cmd, "RETR"))
   1862 		cmd2 = "RETR";
   1863 	else
   1864 		cmd2 = runique ? "STOU" : "STOR";
   1865 	if ((prox_type = type) == 0) {
   1866 		if (unix_server && unix_proxy)
   1867 			prox_type = TYPE_I;
   1868 		else
   1869 			prox_type = TYPE_A;
   1870 	}
   1871 	if (curtype != prox_type)
   1872 		changetype(prox_type, 1);
   1873 	if (command("PASV") != COMPLETE) {
   1874 		fputs("proxy server does not support third party transfers.\n",
   1875 		    ttyout);
   1876 		return;
   1877 	}
   1878 	pswitch(0);
   1879 	if (!connected) {
   1880 		fputs("No primary connection.\n", ttyout);
   1881 		pswitch(1);
   1882 		code = -1;
   1883 		return;
   1884 	}
   1885 	if (curtype != prox_type)
   1886 		changetype(prox_type, 1);
   1887 	if (command("PORT %s", pasv) != COMPLETE) {
   1888 		pswitch(1);
   1889 		return;
   1890 	}
   1891 	if (sigsetjmp(ptabort, 1))
   1892 		goto abort;
   1893 	oldintr = xsignal(SIGINT, abortpt);
   1894 	if ((restart_point &&
   1895 	    (command("REST " LLF, (LLT) restart_point) != CONTINUE))
   1896 	    || (command("%s %s", cmd, remote) != PRELIM)) {
   1897 		(void)xsignal(SIGINT, oldintr);
   1898 		pswitch(1);
   1899 		return;
   1900 	}
   1901 	sleep(2);
   1902 	pswitch(1);
   1903 	secndflag++;
   1904 	if ((restart_point &&
   1905 	    (command("REST " LLF, (LLT) restart_point) != CONTINUE))
   1906 	    || (command("%s %s", cmd2, local) != PRELIM))
   1907 		goto abort;
   1908 	ptflag++;
   1909 	(void)getreply(0);
   1910 	pswitch(0);
   1911 	(void)getreply(0);
   1912 	(void)xsignal(SIGINT, oldintr);
   1913 	pswitch(1);
   1914 	ptflag = 0;
   1915 	fprintf(ttyout, "local: %s remote: %s\n", local, remote);
   1916 	return;
   1917  abort:
   1918 	if (sigsetjmp(xferabort, 1)) {
   1919 		(void)xsignal(SIGINT, oldintr);
   1920 		return;
   1921 	}
   1922 	(void)xsignal(SIGINT, abort_squared);
   1923 	ptflag = 0;
   1924 	if (strcmp(cmd, "RETR") && !proxy)
   1925 		pswitch(1);
   1926 	else if (!strcmp(cmd, "RETR") && proxy)
   1927 		pswitch(0);
   1928 	if (!cpend && !secndflag) {  /* only here if cmd = "STOR" (proxy=1) */
   1929 		if (command("%s %s", cmd2, local) != PRELIM) {
   1930 			pswitch(0);
   1931 			if (cpend)
   1932 				abort_remote(NULL);
   1933 		}
   1934 		pswitch(1);
   1935 		if (ptabflg)
   1936 			code = -1;
   1937 		(void)xsignal(SIGINT, oldintr);
   1938 		return;
   1939 	}
   1940 	if (cpend)
   1941 		abort_remote(NULL);
   1942 	pswitch(!proxy);
   1943 	if (!cpend && !secndflag) {  /* only if cmd = "RETR" (proxy=1) */
   1944 		if (command("%s %s", cmd2, local) != PRELIM) {
   1945 			pswitch(0);
   1946 			if (cpend)
   1947 				abort_remote(NULL);
   1948 			pswitch(1);
   1949 			if (ptabflg)
   1950 				code = -1;
   1951 			(void)xsignal(SIGINT, oldintr);
   1952 			return;
   1953 		}
   1954 	}
   1955 	if (cpend)
   1956 		abort_remote(NULL);
   1957 	pswitch(!proxy);
   1958 	if (cpend) {
   1959 		if ((nfnd = empty(cin, NULL, 10)) <= 0) {
   1960 			if (nfnd < 0)
   1961 				warn("abort");
   1962 			if (ptabflg)
   1963 				code = -1;
   1964 			lostpeer(0);
   1965 		}
   1966 		(void)getreply(0);
   1967 		(void)getreply(0);
   1968 	}
   1969 	if (proxy)
   1970 		pswitch(0);
   1971 	pswitch(1);
   1972 	if (ptabflg)
   1973 		code = -1;
   1974 	(void)xsignal(SIGINT, oldintr);
   1975 }
   1976 
   1977 void
   1978 reset(int argc, char *argv[])
   1979 {
   1980 	int nfnd = 1;
   1981 
   1982 	if (argc == 0 && argv != NULL) {
   1983 		fprintf(ttyout, "usage: %s\n", argv[0]);
   1984 		code = -1;
   1985 		return;
   1986 	}
   1987 	while (nfnd > 0) {
   1988 		if ((nfnd = empty(cin, NULL, 0)) < 0) {
   1989 			warn("reset");
   1990 			code = -1;
   1991 			lostpeer(0);
   1992 		} else if (nfnd)
   1993 			(void)getreply(0);
   1994 	}
   1995 }
   1996 
   1997 char *
   1998 gunique(const char *local)
   1999 {
   2000 	static char new[MAXPATHLEN];
   2001 	char *cp = strrchr(local, '/');
   2002 	int d, count=0, len;
   2003 	char ext = '1';
   2004 
   2005 	if (cp)
   2006 		*cp = '\0';
   2007 	d = access(cp == local ? "/" : cp ? local : ".", W_OK);
   2008 	if (cp)
   2009 		*cp = '/';
   2010 	if (d < 0) {
   2011 		warn("local: %s", local);
   2012 		return (NULL);
   2013 	}
   2014 	len = strlcpy(new, local, sizeof(new));
   2015 	cp = &new[len];
   2016 	*cp++ = '.';
   2017 	while (!d) {
   2018 		if (++count == 100) {
   2019 			fputs("runique: can't find unique file name.\n",
   2020 			    ttyout);
   2021 			return (NULL);
   2022 		}
   2023 		*cp++ = ext;
   2024 		*cp = '\0';
   2025 		if (ext == '9')
   2026 			ext = '0';
   2027 		else
   2028 			ext++;
   2029 		if ((d = access(new, F_OK)) < 0)
   2030 			break;
   2031 		if (ext != '0')
   2032 			cp--;
   2033 		else if (*(cp - 2) == '.')
   2034 			*(cp - 1) = '1';
   2035 		else {
   2036 			*(cp - 2) = *(cp - 2) + 1;
   2037 			cp--;
   2038 		}
   2039 	}
   2040 	return (new);
   2041 }
   2042 
   2043 /*
   2044  * abort_squared --
   2045  *	aborts abort_remote(). lostpeer() is called because if the user is
   2046  *	too impatient to wait or there's another problem then ftp really
   2047  *	needs to get back to a known state.
   2048  */
   2049 void
   2050 abort_squared(int dummy)
   2051 {
   2052 	char msgbuf[100];
   2053 	int len;
   2054 
   2055 	alarmtimer(0);
   2056 	len = strlcpy(msgbuf, "\nremote abort aborted; closing connection.\n",
   2057 	    sizeof(msgbuf));
   2058 	write(fileno(ttyout), msgbuf, len);
   2059 	lostpeer(0);
   2060 	siglongjmp(xferabort, 1);
   2061 }
   2062 
   2063 void
   2064 abort_remote(FILE *din)
   2065 {
   2066 	char buf[BUFSIZ];
   2067 	int nfnd;
   2068 
   2069 	if (cout == NULL) {
   2070 		warnx("Lost control connection for abort.");
   2071 		if (ptabflg)
   2072 			code = -1;
   2073 		lostpeer(0);
   2074 		return;
   2075 	}
   2076 	/*
   2077 	 * send IAC in urgent mode instead of DM because 4.3BSD places oob mark
   2078 	 * after urgent byte rather than before as is protocol now
   2079 	 */
   2080 	buf[0] = IAC;
   2081 	buf[1] = IP;
   2082 	buf[2] = IAC;
   2083 	if (send(fileno(cout), buf, 3, MSG_OOB) != 3)
   2084 		warn("abort");
   2085 	fprintf(cout, "%cABOR\r\n", DM);
   2086 	(void)fflush(cout);
   2087 	if ((nfnd = empty(cin, din, 10)) <= 0) {
   2088 		if (nfnd < 0)
   2089 			warn("abort");
   2090 		if (ptabflg)
   2091 			code = -1;
   2092 		lostpeer(0);
   2093 	}
   2094 	if (din && (nfnd & 2)) {
   2095 		while (read(fileno(din), buf, BUFSIZ) > 0)
   2096 			continue;
   2097 	}
   2098 	if (getreply(0) == ERROR && code == 552) {
   2099 		/* 552 needed for nic style abort */
   2100 		(void)getreply(0);
   2101 	}
   2102 	(void)getreply(0);
   2103 }
   2104 
   2105 void
   2106 ai_unmapped(struct addrinfo *ai)
   2107 {
   2108 #ifdef INET6
   2109 	struct sockaddr_in6 *sin6;
   2110 	struct sockaddr_in sin;
   2111 	int len;
   2112 
   2113 	if (ai->ai_family != AF_INET6)
   2114 		return;
   2115 	if (ai->ai_addrlen != sizeof(struct sockaddr_in6) ||
   2116 	    sizeof(sin) > ai->ai_addrlen)
   2117 		return;
   2118 	sin6 = (struct sockaddr_in6 *)ai->ai_addr;
   2119 	if (!IN6_IS_ADDR_V4MAPPED(&sin6->sin6_addr))
   2120 		return;
   2121 
   2122 	memset(&sin, 0, sizeof(sin));
   2123 	sin.sin_family = AF_INET;
   2124 	len = sizeof(struct sockaddr_in);
   2125 	memcpy(&sin.sin_addr, &sin6->sin6_addr.s6_addr[12],
   2126 	    sizeof(sin.sin_addr));
   2127 	sin.sin_port = sin6->sin6_port;
   2128 
   2129 	ai->ai_family = AF_INET;
   2130 #if HAVE_SOCKADDR_SA_LEN
   2131 	sin.sin_len = len;
   2132 #endif
   2133 	memcpy(ai->ai_addr, &sin, len);
   2134 	ai->ai_addrlen = len;
   2135 #endif
   2136 }
   2137