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