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