Home | History | Annotate | Line # | Download | only in ftp
ftp.c revision 1.141
      1 /*	$NetBSD: ftp.c,v 1.141 2006/10/07 10:49:14 elad Exp $	*/
      2 
      3 /*-
      4  * Copyright (c) 1996-2005 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.141 2006/10/07 10:49:14 elad 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 int
    386 getreply(int expecteof)
    387 {
    388 	char current_line[BUFSIZ];	/* last line of previous reply */
    389 	int c, n, line;
    390 	int dig;
    391 	int originalcode = 0, continuation = 0;
    392 	sigfunc oldsigint, oldsigalrm;
    393 	int pflag = 0;
    394 	char *cp, *pt = pasv;
    395 
    396 	abrtflag = 0;
    397 	timeoutflag = 0;
    398 
    399 	oldsigint = xsignal(SIGINT, cmdabort);
    400 	oldsigalrm = xsignal(SIGALRM, cmdtimeout);
    401 
    402 	for (line = 0 ;; line++) {
    403 		dig = n = code = 0;
    404 		cp = current_line;
    405 		while (alarmtimer(quit_time ? quit_time : 60),
    406 		       ((c = getc(cin)) != '\n')) {
    407 			if (c == IAC) {     /* handle telnet commands */
    408 				switch (c = getc(cin)) {
    409 				case WILL:
    410 				case WONT:
    411 					c = getc(cin);
    412 					fprintf(cout, "%c%c%c", IAC, DONT, c);
    413 					(void)fflush(cout);
    414 					break;
    415 				case DO:
    416 				case DONT:
    417 					c = getc(cin);
    418 					fprintf(cout, "%c%c%c", IAC, WONT, c);
    419 					(void)fflush(cout);
    420 					break;
    421 				default:
    422 					break;
    423 				}
    424 				continue;
    425 			}
    426 			dig++;
    427 			if (c == EOF) {
    428 				/*
    429 				 * these will get trashed by pswitch()
    430 				 * in lostpeer()
    431 				 */
    432 				int reply_timeoutflag = timeoutflag;
    433 				int reply_abrtflag = abrtflag;
    434 
    435 				alarmtimer(0);
    436 				if (expecteof && feof(cin)) {
    437 					(void)xsignal(SIGINT, oldsigint);
    438 					(void)xsignal(SIGALRM, oldsigalrm);
    439 					code = 221;
    440 					return (0);
    441 				}
    442 				cpend = 0;
    443 				lostpeer(0);
    444 				if (verbose) {
    445 					if (reply_timeoutflag)
    446 						fputs(
    447     "421 Service not available, remote server timed out. Connection closed\n",
    448 						    ttyout);
    449 					else if (reply_abrtflag)
    450 						fputs(
    451     "421 Service not available, user interrupt. Connection closed.\n",
    452 						    ttyout);
    453 					else
    454 						fputs(
    455     "421 Service not available, remote server has closed connection.\n",
    456 						    ttyout);
    457 					(void)fflush(ttyout);
    458 				}
    459 				code = 421;
    460 				(void)xsignal(SIGINT, oldsigint);
    461 				(void)xsignal(SIGALRM, oldsigalrm);
    462 				return (4);
    463 			}
    464 			if (c != '\r' && (verbose > 0 ||
    465 			    ((verbose > -1 && n == '5' && dig > 4) &&
    466 			    (((!n && c < '5') || (n && n < '5'))
    467 			     || !retry_connect)))) {
    468 				if (proxflag &&
    469 				   (dig == 1 || (dig == 5 && verbose == 0)))
    470 					fprintf(ttyout, "%s:", hostname);
    471 				(void)putc(c, ttyout);
    472 			}
    473 			if (dig < 4 && isdigit(c))
    474 				code = code * 10 + (c - '0');
    475 			if (!pflag && (code == 227 || code == 228))
    476 				pflag = 1;
    477 			else if (!pflag && code == 229)
    478 				pflag = 100;
    479 			if (dig > 4 && pflag == 1 && isdigit(c))
    480 				pflag = 2;
    481 			if (pflag == 2) {
    482 				if (c != '\r' && c != ')') {
    483 					if (pt < &pasv[sizeof(pasv) - 1])
    484 						*pt++ = c;
    485 				} else {
    486 					*pt = '\0';
    487 					pflag = 3;
    488 				}
    489 			}
    490 			if (pflag == 100 && c == '(')
    491 				pflag = 2;
    492 			if (dig == 4 && c == '-') {
    493 				if (continuation)
    494 					code = 0;
    495 				continuation++;
    496 			}
    497 			if (n == 0)
    498 				n = c;
    499 			if (cp < &current_line[sizeof(current_line) - 1])
    500 				*cp++ = c;
    501 		}
    502 		if (verbose > 0 || ((verbose > -1 && n == '5') &&
    503 		    (n < '5' || !retry_connect))) {
    504 			(void)putc(c, ttyout);
    505 			(void)fflush (ttyout);
    506 		}
    507 		if (cp[-1] == '\r')
    508 			cp[-1] = '\0';
    509 		*cp = '\0';
    510 		if (line == 0)
    511 			(void)strlcpy(reply_string, current_line,
    512 			    sizeof(reply_string));
    513 		if (line > 0 && code == 0 && reply_callback != NULL)
    514 			(*reply_callback)(current_line);
    515 		if (continuation && code != originalcode) {
    516 			if (originalcode == 0)
    517 				originalcode = code;
    518 			continue;
    519 		}
    520 		if (n != '1')
    521 			cpend = 0;
    522 		alarmtimer(0);
    523 		(void)xsignal(SIGINT, oldsigint);
    524 		(void)xsignal(SIGALRM, oldsigalrm);
    525 		if (code == 421 || originalcode == 421)
    526 			lostpeer(0);
    527 		if (abrtflag && oldsigint != cmdabort && oldsigint != SIG_IGN)
    528 			(*oldsigint)(SIGINT);
    529 		if (timeoutflag && oldsigalrm != cmdtimeout &&
    530 		    oldsigalrm != SIG_IGN)
    531 			(*oldsigalrm)(SIGINT);
    532 		return (n - '0');
    533 	}
    534 }
    535 
    536 static int
    537 empty(FILE *cin, FILE *din, int sec)
    538 {
    539 	int		nr, nfd;
    540 	struct pollfd	pfd[2];
    541 
    542 	nfd = 0;
    543 	if (cin) {
    544 		pfd[nfd].fd = fileno(cin);
    545 		pfd[nfd++].events = POLLIN;
    546 	}
    547 
    548 	if (din) {
    549 		pfd[nfd].fd = fileno(din);
    550 		pfd[nfd++].events = POLLIN;
    551 	}
    552 
    553 	if ((nr = ftp_poll(pfd, nfd, sec * 1000)) <= 0)
    554 		return nr;
    555 
    556 	nr = 0;
    557 	nfd = 0;
    558 	if (cin)
    559 		nr |= (pfd[nfd++].revents & POLLIN) ? 1 : 0;
    560 	if (din)
    561 		nr |= (pfd[nfd++].revents & POLLIN) ? 2 : 0;
    562 	return nr;
    563 }
    564 
    565 sigjmp_buf	xferabort;
    566 
    567 void
    568 abortxfer(int notused)
    569 {
    570 	char msgbuf[100];
    571 	size_t len;
    572 
    573 	sigint_raised = 1;
    574 	alarmtimer(0);
    575 	mflag = 0;
    576 	abrtflag = 0;
    577 	switch (direction[0]) {
    578 	case 'r':
    579 		strlcpy(msgbuf, "\nreceive", sizeof(msgbuf));
    580 		break;
    581 	case 's':
    582 		strlcpy(msgbuf, "\nsend", sizeof(msgbuf));
    583 		break;
    584 	default:
    585 		errx(1, "abortxfer called with unknown direction `%s'",
    586 		    direction);
    587 	}
    588 	len = strlcat(msgbuf, " aborted. Waiting for remote to finish abort.\n",
    589 	    sizeof(msgbuf));
    590 	write(fileno(ttyout), msgbuf, len);
    591 	siglongjmp(xferabort, 1);
    592 }
    593 
    594 void
    595 sendrequest(const char *cmd, const char *local, const char *remote,
    596 	    int printnames)
    597 {
    598 	struct stat st;
    599 	int c, d;
    600 	FILE *fin, *dout;
    601 	int (*closefunc)(FILE *);
    602 	sigfunc oldintr, oldintp;
    603 	volatile off_t hashbytes;
    604 	char *lmode, *bufp;
    605 	static size_t bufsize;
    606 	static char *buf;
    607 	int oprogress;
    608 
    609 #ifdef __GNUC__			/* to shut up gcc warnings */
    610 	(void)&fin;
    611 	(void)&dout;
    612 	(void)&closefunc;
    613 	(void)&oldintr;
    614 	(void)&oldintp;
    615 	(void)&lmode;
    616 	fin = NULL;	/* XXX gcc4 */
    617 #endif
    618 
    619 	hashbytes = mark;
    620 	direction = "sent";
    621 	dout = NULL;
    622 	bytes = 0;
    623 	filesize = -1;
    624 	oprogress = progress;
    625 	if (verbose && printnames) {
    626 		if (*local != '-')
    627 			fprintf(ttyout, "local: %s ", local);
    628 		if (remote)
    629 			fprintf(ttyout, "remote: %s\n", remote);
    630 	}
    631 	if (proxy) {
    632 		proxtrans(cmd, local, remote);
    633 		return;
    634 	}
    635 	if (curtype != type)
    636 		changetype(type, 0);
    637 	closefunc = NULL;
    638 	oldintr = NULL;
    639 	oldintp = NULL;
    640 	lmode = "w";
    641 	if (sigsetjmp(xferabort, 1)) {
    642 		while (cpend)
    643 			(void)getreply(0);
    644 		code = -1;
    645 		goto cleanupsend;
    646 	}
    647 	(void)xsignal(SIGQUIT, psummary);
    648 	oldintr = xsignal(SIGINT, abortxfer);
    649 	if (strcmp(local, "-") == 0) {
    650 		fin = stdin;
    651 		progress = 0;
    652 	} else if (*local == '|') {
    653 		oldintp = xsignal(SIGPIPE, SIG_IGN);
    654 		fin = popen(local + 1, "r");
    655 		if (fin == NULL) {
    656 			warn("%s", local + 1);
    657 			code = -1;
    658 			goto cleanupsend;
    659 		}
    660 		progress = 0;
    661 		closefunc = pclose;
    662 	} else {
    663 		fin = fopen(local, "r");
    664 		if (fin == NULL) {
    665 			warn("local: %s", local);
    666 			code = -1;
    667 			goto cleanupsend;
    668 		}
    669 		closefunc = fclose;
    670 		if (fstat(fileno(fin), &st) < 0 || !S_ISREG(st.st_mode)) {
    671 			fprintf(ttyout, "%s: not a plain file.\n", local);
    672 			code = -1;
    673 			goto cleanupsend;
    674 		}
    675 		filesize = st.st_size;
    676 	}
    677 	if (initconn()) {
    678 		code = -1;
    679 		goto cleanupsend;
    680 	}
    681 	if (sigsetjmp(xferabort, 1))
    682 		goto abort;
    683 
    684 	if (restart_point &&
    685 	    (strcmp(cmd, "STOR") == 0 || strcmp(cmd, "APPE") == 0)) {
    686 		int rc;
    687 
    688 		rc = -1;
    689 		switch (curtype) {
    690 		case TYPE_A:
    691 			rc = fseeko(fin, restart_point, SEEK_SET);
    692 			break;
    693 		case TYPE_I:
    694 		case TYPE_L:
    695 			rc = lseek(fileno(fin), restart_point, SEEK_SET);
    696 			break;
    697 		}
    698 		if (rc < 0) {
    699 			warn("local: %s", local);
    700 			goto cleanupsend;
    701 		}
    702 		if (command("REST " LLF, (LLT)restart_point) != CONTINUE)
    703 			goto cleanupsend;
    704 		lmode = "r+";
    705 	}
    706 	if (remote) {
    707 		if (command("%s %s", cmd, remote) != PRELIM)
    708 			goto cleanupsend;
    709 	} else {
    710 		if (command("%s", cmd) != PRELIM)
    711 			goto cleanupsend;
    712 	}
    713 	dirchange = 1;
    714 	dout = dataconn(lmode);
    715 	if (dout == NULL)
    716 		goto abort;
    717 
    718 	if (sndbuf_size > bufsize) {
    719 		if (buf)
    720 			(void)free(buf);
    721 		bufsize = sndbuf_size;
    722 		buf = ftp_malloc(bufsize);
    723 	}
    724 
    725 	progressmeter(-1);
    726 	oldintp = xsignal(SIGPIPE, SIG_IGN);
    727 
    728 	switch (curtype) {
    729 
    730 	case TYPE_I:
    731 	case TYPE_L:
    732 		if (rate_put) {		/* rate limited */
    733 			while (1) {
    734 				struct timeval then, now, td;
    735 				off_t bufrem;
    736 
    737 				(void)gettimeofday(&then, NULL);
    738 				errno = c = d = 0;
    739 				bufrem = rate_put;
    740 				while (bufrem > 0) {
    741 					if ((c = read(fileno(fin), buf,
    742 					    MIN(bufsize, bufrem))) <= 0)
    743 						goto senddone;
    744 					bytes += c;
    745 					bufrem -= c;
    746 					for (bufp = buf; c > 0;
    747 					    c -= d, bufp += d)
    748 						if ((d = write(fileno(dout),
    749 						    bufp, c)) <= 0)
    750 							break;
    751 					if (d < 0)
    752 						goto senddone;
    753 					if (hash &&
    754 					    (!progress || filesize < 0) ) {
    755 						while (bytes >= hashbytes) {
    756 							(void)putc('#', ttyout);
    757 							hashbytes += mark;
    758 						}
    759 						(void)fflush(ttyout);
    760 					}
    761 				}
    762 				while (1) {
    763 					(void)gettimeofday(&now, NULL);
    764 					timersub(&now, &then, &td);
    765 					if (td.tv_sec > 0)
    766 						break;
    767 					usleep(1000000 - td.tv_usec);
    768 				}
    769 			}
    770 		} else {		/* simpler/faster; no rate limit */
    771 			while (1) {
    772 				errno = c = d = 0;
    773 				if ((c = read(fileno(fin), buf, bufsize)) <= 0)
    774 					goto senddone;
    775 				bytes += c;
    776 				for (bufp = buf; c > 0; c -= d, bufp += d)
    777 					if ((d = write(fileno(dout), bufp, c))
    778 					    <= 0)
    779 						break;
    780 				if (d < 0)
    781 					goto senddone;
    782 				if (hash && (!progress || filesize < 0) ) {
    783 					while (bytes >= hashbytes) {
    784 						(void)putc('#', ttyout);
    785 						hashbytes += mark;
    786 					}
    787 					(void)fflush(ttyout);
    788 				}
    789 			}
    790 		}
    791  senddone:
    792 		if (hash && (!progress || filesize < 0) && bytes > 0) {
    793 			if (bytes < mark)
    794 				(void)putc('#', ttyout);
    795 			(void)putc('\n', ttyout);
    796 		}
    797 		if (c < 0)
    798 			warn("local: %s", local);
    799 		if (d < 0) {
    800 			if (errno != EPIPE)
    801 				warn("netout");
    802 			bytes = -1;
    803 		}
    804 		break;
    805 
    806 	case TYPE_A:
    807 		while ((c = getc(fin)) != EOF) {
    808 			if (c == '\n') {
    809 				while (hash && (!progress || filesize < 0) &&
    810 				    (bytes >= hashbytes)) {
    811 					(void)putc('#', ttyout);
    812 					(void)fflush(ttyout);
    813 					hashbytes += mark;
    814 				}
    815 				if (ferror(dout))
    816 					break;
    817 				(void)putc('\r', dout);
    818 				bytes++;
    819 			}
    820 			(void)putc(c, dout);
    821 			bytes++;
    822 #if 0	/* this violates RFC */
    823 			if (c == '\r') {
    824 				(void)putc('\0', dout);
    825 				bytes++;
    826 			}
    827 #endif
    828 		}
    829 		if (hash && (!progress || filesize < 0)) {
    830 			if (bytes < hashbytes)
    831 				(void)putc('#', ttyout);
    832 			(void)putc('\n', ttyout);
    833 		}
    834 		if (ferror(fin))
    835 			warn("local: %s", local);
    836 		if (ferror(dout)) {
    837 			if (errno != EPIPE)
    838 				warn("netout");
    839 			bytes = -1;
    840 		}
    841 		break;
    842 	}
    843 
    844 	progressmeter(1);
    845 	if (closefunc != NULL) {
    846 		(*closefunc)(fin);
    847 		fin = NULL;
    848 	}
    849 	(void)fclose(dout);
    850 	dout = NULL;
    851 	(void)getreply(0);
    852 	if (bytes > 0)
    853 		ptransfer(0);
    854 	goto cleanupsend;
    855 
    856  abort:
    857 	(void)xsignal(SIGINT, oldintr);
    858 	oldintr = NULL;
    859 	if (!cpend) {
    860 		code = -1;
    861 		goto cleanupsend;
    862 	}
    863 	if (data >= 0) {
    864 		(void)close(data);
    865 		data = -1;
    866 	}
    867 	if (dout) {
    868 		(void)fclose(dout);
    869 		dout = NULL;
    870 	}
    871 	(void)getreply(0);
    872 	code = -1;
    873 	if (bytes > 0)
    874 		ptransfer(0);
    875 
    876  cleanupsend:
    877 	if (oldintr)
    878 		(void)xsignal(SIGINT, oldintr);
    879 	if (oldintp)
    880 		(void)xsignal(SIGPIPE, oldintp);
    881 	if (data >= 0) {
    882 		(void)close(data);
    883 		data = -1;
    884 	}
    885 	if (closefunc != NULL && fin != NULL)
    886 		(*closefunc)(fin);
    887 	if (dout)
    888 		(void)fclose(dout);
    889 	progress = oprogress;
    890 	restart_point = 0;
    891 	bytes = 0;
    892 }
    893 
    894 void
    895 recvrequest(const char *cmd, const char *local, const char *remote,
    896 	    const char *lmode, int printnames, int ignorespecial)
    897 {
    898 	FILE *fout, *din;
    899 	int (*closefunc)(FILE *);
    900 	sigfunc oldintr, oldintp;
    901 	int c, d;
    902 	volatile int is_retr, tcrflag, bare_lfs;
    903 	static size_t bufsize;
    904 	static char *buf;
    905 	volatile off_t hashbytes;
    906 	struct stat st;
    907 	time_t mtime;
    908 	struct timeval tval[2];
    909 	int oprogress;
    910 	int opreserve;
    911 
    912 #ifdef __GNUC__			/* to shut up gcc warnings */
    913 	(void)&local;
    914 	(void)&fout;
    915 	(void)&din;
    916 	(void)&closefunc;
    917 	(void)&oldintr;
    918 	(void)&oldintp;
    919 #endif
    920 
    921 	fout = NULL;
    922 	din = NULL;
    923 	hashbytes = mark;
    924 	direction = "received";
    925 	bytes = 0;
    926 	bare_lfs = 0;
    927 	filesize = -1;
    928 	oprogress = progress;
    929 	opreserve = preserve;
    930 	is_retr = (strcmp(cmd, "RETR") == 0);
    931 	if (is_retr && verbose && printnames) {
    932 		if (ignorespecial || *local != '-')
    933 			fprintf(ttyout, "local: %s ", local);
    934 		if (remote)
    935 			fprintf(ttyout, "remote: %s\n", remote);
    936 	}
    937 	if (proxy && is_retr) {
    938 		proxtrans(cmd, local, remote);
    939 		return;
    940 	}
    941 	closefunc = NULL;
    942 	oldintr = NULL;
    943 	oldintp = NULL;
    944 	tcrflag = !crflag && is_retr;
    945 	if (sigsetjmp(xferabort, 1)) {
    946 		while (cpend)
    947 			(void)getreply(0);
    948 		code = -1;
    949 		goto cleanuprecv;
    950 	}
    951 	(void)xsignal(SIGQUIT, psummary);
    952 	oldintr = xsignal(SIGINT, abortxfer);
    953 	if (ignorespecial || (strcmp(local, "-") && *local != '|')) {
    954 		if (access(local, W_OK) < 0) {
    955 			char *dir = strrchr(local, '/');
    956 
    957 			if (errno != ENOENT && errno != EACCES) {
    958 				warn("local: %s", local);
    959 				code = -1;
    960 				goto cleanuprecv;
    961 			}
    962 			if (dir != NULL)
    963 				*dir = 0;
    964 			d = access(dir == local ? "/" :
    965 			    dir ? local : ".", W_OK);
    966 			if (dir != NULL)
    967 				*dir = '/';
    968 			if (d < 0) {
    969 				warn("local: %s", local);
    970 				code = -1;
    971 				goto cleanuprecv;
    972 			}
    973 			if (!runique && errno == EACCES &&
    974 			    chmod(local, (S_IRUSR|S_IWUSR)) < 0) {
    975 				warn("local: %s", local);
    976 				code = -1;
    977 				goto cleanuprecv;
    978 			}
    979 			if (runique && errno == EACCES &&
    980 			   (local = gunique(local)) == NULL) {
    981 				code = -1;
    982 				goto cleanuprecv;
    983 			}
    984 		}
    985 		else if (runique && (local = gunique(local)) == NULL) {
    986 			code = -1;
    987 			goto cleanuprecv;
    988 		}
    989 	}
    990 	if (!is_retr) {
    991 		if (curtype != TYPE_A)
    992 			changetype(TYPE_A, 0);
    993 	} else {
    994 		if (curtype != type)
    995 			changetype(type, 0);
    996 		filesize = remotesize(remote, 0);
    997 		if (code == 421 || code == -1)
    998 			goto cleanuprecv;
    999 	}
   1000 	if (initconn()) {
   1001 		code = -1;
   1002 		goto cleanuprecv;
   1003 	}
   1004 	if (sigsetjmp(xferabort, 1))
   1005 		goto abort;
   1006 	if (is_retr && restart_point &&
   1007 	    command("REST " LLF, (LLT) restart_point) != CONTINUE)
   1008 		goto cleanuprecv;
   1009 	if (! EMPTYSTRING(remote)) {
   1010 		if (command("%s %s", cmd, remote) != PRELIM)
   1011 			goto cleanuprecv;
   1012 	} else {
   1013 		if (command("%s", cmd) != PRELIM)
   1014 			goto cleanuprecv;
   1015 	}
   1016 	din = dataconn("r");
   1017 	if (din == NULL)
   1018 		goto abort;
   1019 	if (!ignorespecial && strcmp(local, "-") == 0) {
   1020 		fout = stdout;
   1021 		progress = 0;
   1022 		preserve = 0;
   1023 	} else if (!ignorespecial && *local == '|') {
   1024 		oldintp = xsignal(SIGPIPE, SIG_IGN);
   1025 		fout = popen(local + 1, "w");
   1026 		if (fout == NULL) {
   1027 			warn("%s", local+1);
   1028 			goto abort;
   1029 		}
   1030 		progress = 0;
   1031 		preserve = 0;
   1032 		closefunc = pclose;
   1033 	} else {
   1034 		fout = fopen(local, lmode);
   1035 		if (fout == NULL) {
   1036 			warn("local: %s", local);
   1037 			goto abort;
   1038 		}
   1039 		closefunc = fclose;
   1040 	}
   1041 
   1042 	if (fstat(fileno(fout), &st) != -1 && !S_ISREG(st.st_mode)) {
   1043 		progress = 0;
   1044 		preserve = 0;
   1045 	}
   1046 	if (rcvbuf_size > bufsize) {
   1047 		if (buf)
   1048 			(void)free(buf);
   1049 		bufsize = rcvbuf_size;
   1050 		buf = ftp_malloc(bufsize);
   1051 	}
   1052 
   1053 	progressmeter(-1);
   1054 
   1055 	switch (curtype) {
   1056 
   1057 	case TYPE_I:
   1058 	case TYPE_L:
   1059 		if (is_retr && restart_point &&
   1060 		    lseek(fileno(fout), restart_point, SEEK_SET) < 0) {
   1061 			warn("local: %s", local);
   1062 			goto cleanuprecv;
   1063 		}
   1064 		if (rate_get) {		/* rate limiting */
   1065 			while (1) {
   1066 				struct timeval then, now, td;
   1067 				off_t bufrem;
   1068 
   1069 				(void)gettimeofday(&then, NULL);
   1070 				errno = c = d = 0;
   1071 				for (bufrem = rate_get; bufrem > 0; ) {
   1072 					if ((c = read(fileno(din), buf,
   1073 					    MIN(bufsize, bufrem))) <= 0)
   1074 						goto recvdone;
   1075 					bytes += c;
   1076 					bufrem -=c;
   1077 					if ((d = write(fileno(fout), buf, c))
   1078 					    != c)
   1079 						goto recvdone;
   1080 					if (hash &&
   1081 					    (!progress || filesize < 0)) {
   1082 						while (bytes >= hashbytes) {
   1083 							(void)putc('#', ttyout);
   1084 							hashbytes += mark;
   1085 						}
   1086 						(void)fflush(ttyout);
   1087 					}
   1088 				}
   1089 					/* sleep until time is up */
   1090 				while (1) {
   1091 					(void)gettimeofday(&now, NULL);
   1092 					timersub(&now, &then, &td);
   1093 					if (td.tv_sec > 0)
   1094 						break;
   1095 					usleep(1000000 - td.tv_usec);
   1096 				}
   1097 			}
   1098 		} else {		/* faster code (no limiting) */
   1099 			while (1) {
   1100 				errno = c = d = 0;
   1101 				if ((c = read(fileno(din), buf, bufsize)) <= 0)
   1102 					goto recvdone;
   1103 				bytes += c;
   1104 				if ((d = write(fileno(fout), buf, c)) != c)
   1105 					goto recvdone;
   1106 				if (hash && (!progress || filesize < 0)) {
   1107 					while (bytes >= hashbytes) {
   1108 						(void)putc('#', ttyout);
   1109 						hashbytes += mark;
   1110 					}
   1111 					(void)fflush(ttyout);
   1112 				}
   1113 			}
   1114 		}
   1115  recvdone:
   1116 		if (hash && (!progress || filesize < 0) && bytes > 0) {
   1117 			if (bytes < mark)
   1118 				(void)putc('#', ttyout);
   1119 			(void)putc('\n', ttyout);
   1120 		}
   1121 		if (c < 0) {
   1122 			if (errno != EPIPE)
   1123 				warn("netin");
   1124 			bytes = -1;
   1125 		}
   1126 		if (d < c) {
   1127 			if (d < 0)
   1128 				warn("local: %s", local);
   1129 			else
   1130 				warnx("%s: short write", local);
   1131 		}
   1132 		break;
   1133 
   1134 	case TYPE_A:
   1135 		if (is_retr && restart_point) {
   1136 			int ch;
   1137 			off_t i;
   1138 
   1139 			if (fseeko(fout, (off_t)0, SEEK_SET) < 0)
   1140 				goto done;
   1141 			for (i = 0; i++ < restart_point;) {
   1142 				if ((ch = getc(fout)) == EOF)
   1143 					goto done;
   1144 				if (ch == '\n')
   1145 					i++;
   1146 			}
   1147 			if (fseeko(fout, (off_t)0, SEEK_CUR) < 0) {
   1148  done:
   1149 				warn("local: %s", local);
   1150 				goto cleanuprecv;
   1151 			}
   1152 		}
   1153 		while ((c = getc(din)) != EOF) {
   1154 			if (c == '\n')
   1155 				bare_lfs++;
   1156 			while (c == '\r') {
   1157 				while (hash && (!progress || filesize < 0) &&
   1158 				    (bytes >= hashbytes)) {
   1159 					(void)putc('#', ttyout);
   1160 					(void)fflush(ttyout);
   1161 					hashbytes += mark;
   1162 				}
   1163 				bytes++;
   1164 				if ((c = getc(din)) != '\n' || tcrflag) {
   1165 					if (ferror(fout))
   1166 						goto break2;
   1167 					(void)putc('\r', fout);
   1168 					if (c == '\0') {
   1169 						bytes++;
   1170 						goto contin2;
   1171 					}
   1172 					if (c == EOF)
   1173 						goto contin2;
   1174 				}
   1175 			}
   1176 			(void)putc(c, fout);
   1177 			bytes++;
   1178 	contin2:	;
   1179 		}
   1180  break2:
   1181 		if (hash && (!progress || filesize < 0)) {
   1182 			if (bytes < hashbytes)
   1183 				(void)putc('#', ttyout);
   1184 			(void)putc('\n', ttyout);
   1185 		}
   1186 		if (ferror(din)) {
   1187 			if (errno != EPIPE)
   1188 				warn("netin");
   1189 			bytes = -1;
   1190 		}
   1191 		if (ferror(fout))
   1192 			warn("local: %s", local);
   1193 		break;
   1194 	}
   1195 
   1196 	progressmeter(1);
   1197 	if (closefunc != NULL) {
   1198 		(*closefunc)(fout);
   1199 		fout = NULL;
   1200 	}
   1201 	(void)fclose(din);
   1202 	din = NULL;
   1203 	(void)getreply(0);
   1204 	if (bare_lfs) {
   1205 		fprintf(ttyout,
   1206 		    "WARNING! %d bare linefeeds received in ASCII mode.\n",
   1207 		    bare_lfs);
   1208 		fputs("File may not have transferred correctly.\n", ttyout);
   1209 	}
   1210 	if (bytes >= 0 && is_retr) {
   1211 		if (bytes > 0)
   1212 			ptransfer(0);
   1213 		if (preserve && (closefunc == fclose)) {
   1214 			mtime = remotemodtime(remote, 0);
   1215 			if (mtime != -1) {
   1216 				(void)gettimeofday(&tval[0], NULL);
   1217 				tval[1].tv_sec = mtime;
   1218 				tval[1].tv_usec = 0;
   1219 				if (utimes(local, tval) == -1) {
   1220 					fprintf(ttyout,
   1221 				"Can't change modification time on %s to %s",
   1222 					    local, asctime(localtime(&mtime)));
   1223 				}
   1224 			}
   1225 		}
   1226 	}
   1227 	goto cleanuprecv;
   1228 
   1229  abort:
   1230 			/*
   1231 			 * abort using RFC 959 recommended IP,SYNC sequence
   1232 			 */
   1233 	if (! sigsetjmp(xferabort, 1)) {
   1234 			/* this is the first call */
   1235 		(void)xsignal(SIGINT, abort_squared);
   1236 		if (!cpend) {
   1237 			code = -1;
   1238 			goto cleanuprecv;
   1239 		}
   1240 		abort_remote(din);
   1241 	}
   1242 	code = -1;
   1243 	if (bytes > 0)
   1244 		ptransfer(0);
   1245 
   1246  cleanuprecv:
   1247 	if (oldintr)
   1248 		(void)xsignal(SIGINT, oldintr);
   1249 	if (oldintp)
   1250 		(void)xsignal(SIGPIPE, oldintp);
   1251 	if (data >= 0) {
   1252 		(void)close(data);
   1253 		data = -1;
   1254 	}
   1255 	if (closefunc != NULL && fout != NULL)
   1256 		(*closefunc)(fout);
   1257 	if (din)
   1258 		(void)fclose(din);
   1259 	progress = oprogress;
   1260 	preserve = opreserve;
   1261 	bytes = 0;
   1262 }
   1263 
   1264 /*
   1265  * Need to start a listen on the data channel before we send the command,
   1266  * otherwise the server's connect may fail.
   1267  */
   1268 int
   1269 initconn(void)
   1270 {
   1271 	char *p, *a;
   1272 	int result, tmpno = 0;
   1273 	int on = 1;
   1274 	int error;
   1275 	unsigned int addr[16], port[2];
   1276 	unsigned int af, hal, pal;
   1277 	socklen_t len;
   1278 	char *pasvcmd = NULL;
   1279 
   1280 #ifdef INET6
   1281 #ifndef NO_DEBUG
   1282 	if (myctladdr.su_family == AF_INET6 && ftp_debug &&
   1283 	    (IN6_IS_ADDR_LINKLOCAL(&myctladdr.si_su.su_sin6.sin6_addr) ||
   1284 	     IN6_IS_ADDR_SITELOCAL(&myctladdr.si_su.su_sin6.sin6_addr))) {
   1285 		warnx("use of scoped address can be troublesome");
   1286 	}
   1287 #endif
   1288 #endif
   1289  reinit:
   1290 	if (passivemode) {
   1291 		data_addr = myctladdr;
   1292 		data = socket(data_addr.su_family, SOCK_STREAM, 0);
   1293 		if (data < 0) {
   1294 			warn("socket");
   1295 			return (1);
   1296 		}
   1297 		if ((options & SO_DEBUG) &&
   1298 		    setsockopt(data, SOL_SOCKET, SO_DEBUG,
   1299 				(void *)&on, sizeof(on)) == -1) {
   1300 			DWARN("setsockopt %s (ignored)", "SO_DEBUG");
   1301 		}
   1302 		result = COMPLETE + 1;
   1303 		switch (data_addr.su_family) {
   1304 		case AF_INET:
   1305 			if (epsv4 && !epsv4bad) {
   1306 				pasvcmd = "EPSV";
   1307 				result = command("EPSV");
   1308 				if (!connected)
   1309 					return (1);
   1310 				/*
   1311 				 * this code is to be friendly with broken
   1312 				 * BSDI ftpd
   1313 				 */
   1314 				if (code / 10 == 22 && code != 229) {
   1315 					fputs(
   1316 "wrong server: return code must be 229\n",
   1317 						ttyout);
   1318 					result = COMPLETE + 1;
   1319 				}
   1320 				if (result != COMPLETE) {
   1321 					epsv4bad = 1;
   1322 					DPRINTF("disabling epsv4 for this "
   1323 					    "connection\n");
   1324 				}
   1325 			}
   1326 			if (result != COMPLETE) {
   1327 				pasvcmd = "PASV";
   1328 				result = command("PASV");
   1329 				if (!connected)
   1330 					return (1);
   1331 			}
   1332 			break;
   1333 #ifdef INET6
   1334 		case AF_INET6:
   1335 			pasvcmd = "EPSV";
   1336 			result = command("EPSV");
   1337 			if (!connected)
   1338 				return (1);
   1339 			/* this code is to be friendly with broken BSDI ftpd */
   1340 			if (code / 10 == 22 && code != 229) {
   1341 				fputs(
   1342 "wrong server: return code must be 229\n",
   1343 					ttyout);
   1344 				result = COMPLETE + 1;
   1345 			}
   1346 			if (result != COMPLETE) {
   1347 				pasvcmd = "LPSV";
   1348 				result = command("LPSV");
   1349 			}
   1350 			if (!connected)
   1351 				return (1);
   1352 			break;
   1353 #endif
   1354 		default:
   1355 			result = COMPLETE + 1;
   1356 			break;
   1357 		}
   1358 		if (result != COMPLETE) {
   1359 			if (activefallback) {
   1360 				(void)close(data);
   1361 				data = -1;
   1362 				passivemode = 0;
   1363 #if 0
   1364 				activefallback = 0;
   1365 #endif
   1366 				goto reinit;
   1367 			}
   1368 			fputs("Passive mode refused.\n", ttyout);
   1369 			goto bad;
   1370 		}
   1371 
   1372 #define	pack2(var, off) \
   1373 	(((var[(off) + 0] & 0xff) << 8) | ((var[(off) + 1] & 0xff) << 0))
   1374 #define	pack4(var, off) \
   1375 	(((var[(off) + 0] & 0xff) << 24) | ((var[(off) + 1] & 0xff) << 16) | \
   1376 	 ((var[(off) + 2] & 0xff) << 8) | ((var[(off) + 3] & 0xff) << 0))
   1377 #define	UC(b)	(((int)b)&0xff)
   1378 
   1379 		/*
   1380 		 * What we've got at this point is a string of comma separated
   1381 		 * one-byte unsigned integer values, separated by commas.
   1382 		 */
   1383 		if (strcmp(pasvcmd, "PASV") == 0) {
   1384 			if (data_addr.su_family != AF_INET) {
   1385 				fputs(
   1386     "Passive mode AF mismatch. Shouldn't happen!\n", ttyout);
   1387 				error = 1;
   1388 				goto bad;
   1389 			}
   1390 			if (code / 10 == 22 && code != 227) {
   1391 				fputs("wrong server: return code must be 227\n",
   1392 					ttyout);
   1393 				error = 1;
   1394 				goto bad;
   1395 			}
   1396 			error = sscanf(pasv, "%u,%u,%u,%u,%u,%u",
   1397 					&addr[0], &addr[1], &addr[2], &addr[3],
   1398 					&port[0], &port[1]);
   1399 			if (error != 6) {
   1400 				fputs(
   1401 "Passive mode address scan failure. Shouldn't happen!\n", ttyout);
   1402 				error = 1;
   1403 				goto bad;
   1404 			}
   1405 			error = 0;
   1406 			memset(&data_addr, 0, sizeof(data_addr));
   1407 			data_addr.su_family = AF_INET;
   1408 			data_addr.su_len = sizeof(struct sockaddr_in);
   1409 			data_addr.si_su.su_sin.sin_addr.s_addr =
   1410 			    htonl(pack4(addr, 0));
   1411 			data_addr.su_port = htons(pack2(port, 0));
   1412 		} else if (strcmp(pasvcmd, "LPSV") == 0) {
   1413 			if (code / 10 == 22 && code != 228) {
   1414 				fputs("wrong server: return code must be 228\n",
   1415 					ttyout);
   1416 				error = 1;
   1417 				goto bad;
   1418 			}
   1419 			switch (data_addr.su_family) {
   1420 			case AF_INET:
   1421 				error = sscanf(pasv,
   1422 "%u,%u,%u,%u,%u,%u,%u,%u,%u",
   1423 					&af, &hal,
   1424 					&addr[0], &addr[1], &addr[2], &addr[3],
   1425 					&pal, &port[0], &port[1]);
   1426 				if (error != 9) {
   1427 					fputs(
   1428 "Passive mode address scan failure. Shouldn't happen!\n", ttyout);
   1429 					error = 1;
   1430 					goto bad;
   1431 				}
   1432 				if (af != 4 || hal != 4 || pal != 2) {
   1433 					fputs(
   1434 "Passive mode AF mismatch. Shouldn't happen!\n", ttyout);
   1435 					error = 1;
   1436 					goto bad;
   1437 				}
   1438 
   1439 				error = 0;
   1440 				memset(&data_addr, 0, sizeof(data_addr));
   1441 				data_addr.su_family = AF_INET;
   1442 				data_addr.su_len = sizeof(struct sockaddr_in);
   1443 				data_addr.si_su.su_sin.sin_addr.s_addr =
   1444 				    htonl(pack4(addr, 0));
   1445 				data_addr.su_port = htons(pack2(port, 0));
   1446 				break;
   1447 #ifdef INET6
   1448 			case AF_INET6:
   1449 				error = sscanf(pasv,
   1450 "%u,%u,%u,%u,%u,%u,%u,%u,%u,%u,%u,%u,%u,%u,%u,%u,%u,%u,%u,%u,%u",
   1451 					&af, &hal,
   1452 					&addr[0], &addr[1], &addr[2], &addr[3],
   1453 					&addr[4], &addr[5], &addr[6], &addr[7],
   1454 					&addr[8], &addr[9], &addr[10],
   1455 					&addr[11], &addr[12], &addr[13],
   1456 					&addr[14], &addr[15],
   1457 					&pal, &port[0], &port[1]);
   1458 				if (error != 21) {
   1459 					fputs(
   1460 "Passive mode address scan failure. Shouldn't happen!\n", ttyout);
   1461 					error = 1;
   1462 					goto bad;
   1463 				}
   1464 				if (af != 6 || hal != 16 || pal != 2) {
   1465 					fputs(
   1466 "Passive mode AF mismatch. Shouldn't happen!\n", ttyout);
   1467 					error = 1;
   1468 					goto bad;
   1469 				}
   1470 
   1471 				error = 0;
   1472 				memset(&data_addr, 0, sizeof(data_addr));
   1473 				data_addr.su_family = AF_INET6;
   1474 				data_addr.su_len = sizeof(struct sockaddr_in6);
   1475 			    {
   1476 				int i;
   1477 				for (i = 0; i < sizeof(struct in6_addr); i++) {
   1478 					data_addr.si_su.su_sin6.sin6_addr.s6_addr[i] =
   1479 					    UC(addr[i]);
   1480 				}
   1481 			    }
   1482 				data_addr.su_port = htons(pack2(port, 0));
   1483 				break;
   1484 #endif
   1485 			default:
   1486 				error = 1;
   1487 			}
   1488 		} else if (strcmp(pasvcmd, "EPSV") == 0) {
   1489 			char delim[4];
   1490 
   1491 			port[0] = 0;
   1492 			if (code / 10 == 22 && code != 229) {
   1493 				fputs("wrong server: return code must be 229\n",
   1494 					ttyout);
   1495 				error = 1;
   1496 				goto bad;
   1497 			}
   1498 			if (sscanf(pasv, "%c%c%c%d%c", &delim[0],
   1499 					&delim[1], &delim[2], &port[1],
   1500 					&delim[3]) != 5) {
   1501 				fputs("parse error!\n", ttyout);
   1502 				error = 1;
   1503 				goto bad;
   1504 			}
   1505 			if (delim[0] != delim[1] || delim[0] != delim[2]
   1506 			 || delim[0] != delim[3]) {
   1507 				fputs("parse error!\n", ttyout);
   1508 				error = 1;
   1509 				goto bad;
   1510 			}
   1511 			data_addr = hisctladdr;
   1512 			data_addr.su_port = htons(port[1]);
   1513 		} else
   1514 			goto bad;
   1515 
   1516 		while (ftp_connect(data, (struct sockaddr *)&data_addr.si_su,
   1517 			    data_addr.su_len) < 0) {
   1518 			if (activefallback) {
   1519 				(void)close(data);
   1520 				data = -1;
   1521 				passivemode = 0;
   1522 #if 0
   1523 				activefallback = 0;
   1524 #endif
   1525 				goto reinit;
   1526 			}
   1527 			warn("connect for data channel");
   1528 			goto bad;
   1529 		}
   1530 #ifdef IPTOS_THROUGHPUT
   1531 		if (data_addr.su_family == AF_INET) {
   1532 			on = IPTOS_THROUGHPUT;
   1533 			if (setsockopt(data, IPPROTO_IP, IP_TOS,
   1534 					(void *)&on, sizeof(on)) == -1) {
   1535 				DWARN("setsockopt %s (ignored)",
   1536 				    "IPTOS_THROUGHPUT");
   1537 			}
   1538 		}
   1539 #endif
   1540 		return (0);
   1541 	}
   1542 
   1543  noport:
   1544 	data_addr = myctladdr;
   1545 	if (sendport)
   1546 		data_addr.su_port = 0;	/* let system pick one */
   1547 	if (data != -1)
   1548 		(void)close(data);
   1549 	data = socket(data_addr.su_family, SOCK_STREAM, 0);
   1550 	if (data < 0) {
   1551 		warn("socket");
   1552 		if (tmpno)
   1553 			sendport = 1;
   1554 		return (1);
   1555 	}
   1556 	if (!sendport)
   1557 		if (setsockopt(data, SOL_SOCKET, SO_REUSEADDR,
   1558 				(void *)&on, sizeof(on)) == -1) {
   1559 			warn("setsockopt %s", "SO_REUSEADDR");
   1560 			goto bad;
   1561 		}
   1562 	if (bind(data, (struct sockaddr *)&data_addr.si_su,
   1563 	    data_addr.su_len) < 0) {
   1564 		warn("bind");
   1565 		goto bad;
   1566 	}
   1567 	if ((options & SO_DEBUG) &&
   1568 	    setsockopt(data, SOL_SOCKET, SO_DEBUG,
   1569 			(void *)&on, sizeof(on)) == -1) {
   1570 		DWARN("setsockopt %s (ignored)", "SO_DEBUG");
   1571 	}
   1572 	len = sizeof(data_addr.si_su);
   1573 	memset((char *)&data_addr, 0, sizeof (data_addr));
   1574 	if (getsockname(data, (struct sockaddr *)&data_addr.si_su, &len) == -1) {
   1575 		warn("getsockname");
   1576 		goto bad;
   1577 	}
   1578 	data_addr.su_len = len;
   1579 	if (ftp_listen(data, 1) < 0)
   1580 		warn("listen");
   1581 
   1582 	if (sendport) {
   1583 		char hname[NI_MAXHOST], sname[NI_MAXSERV];
   1584 		int af;
   1585 		struct sockinet tmp;
   1586 
   1587 		switch (data_addr.su_family) {
   1588 		case AF_INET:
   1589 			if (!epsv4 || epsv4bad) {
   1590 				result = COMPLETE + 1;
   1591 				break;
   1592 			}
   1593 			/* FALLTHROUGH */
   1594 #ifdef INET6
   1595 		case AF_INET6:
   1596 #endif
   1597 			af = (data_addr.su_family == AF_INET) ? 1 : 2;
   1598 			tmp = data_addr;
   1599 #ifdef INET6
   1600 			if (tmp.su_family == AF_INET6)
   1601 				tmp.si_su.su_sin6.sin6_scope_id = 0;
   1602 #endif
   1603 			if (getnameinfo((struct sockaddr *)&tmp.si_su,
   1604 			    tmp.su_len, hname, sizeof(hname), sname,
   1605 			    sizeof(sname), NI_NUMERICHOST | NI_NUMERICSERV)) {
   1606 				result = ERROR;
   1607 			} else {
   1608 				result = command("EPRT |%d|%s|%s|", af, hname,
   1609 				    sname);
   1610 				if (!connected)
   1611 					return (1);
   1612 				if (result != COMPLETE) {
   1613 					epsv4bad = 1;
   1614 					DPRINTF("disabling epsv4 for this "
   1615 					    "connection\n");
   1616 				}
   1617 			}
   1618 			break;
   1619 		default:
   1620 			result = COMPLETE + 1;
   1621 			break;
   1622 		}
   1623 		if (result == COMPLETE)
   1624 			goto skip_port;
   1625 
   1626 		switch (data_addr.su_family) {
   1627 		case AF_INET:
   1628 			a = (char *)&data_addr.si_su.su_sin.sin_addr;
   1629 			p = (char *)&data_addr.su_port;
   1630 			result = command("PORT %d,%d,%d,%d,%d,%d",
   1631 				 UC(a[0]), UC(a[1]), UC(a[2]), UC(a[3]),
   1632 				 UC(p[0]), UC(p[1]));
   1633 			break;
   1634 #ifdef INET6
   1635 		case AF_INET6:
   1636 			a = (char *)&data_addr.si_su.su_sin6.sin6_addr;
   1637 			p = (char *)&data_addr.su_port;
   1638 			result = command(
   1639 	"LPRT %d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d",
   1640 				 6, 16,
   1641 				 UC(a[0]),UC(a[1]),UC(a[2]),UC(a[3]),
   1642 				 UC(a[4]),UC(a[5]),UC(a[6]),UC(a[7]),
   1643 				 UC(a[8]),UC(a[9]),UC(a[10]),UC(a[11]),
   1644 				 UC(a[12]),UC(a[13]),UC(a[14]),UC(a[15]),
   1645 				 2, UC(p[0]), UC(p[1]));
   1646 			break;
   1647 #endif
   1648 		default:
   1649 			result = COMPLETE + 1; /* xxx */
   1650 		}
   1651 		if (!connected)
   1652 			return (1);
   1653 	skip_port:
   1654 
   1655 		if (result == ERROR && sendport == -1) {
   1656 			sendport = 0;
   1657 			tmpno = 1;
   1658 			goto noport;
   1659 		}
   1660 		return (result != COMPLETE);
   1661 	}
   1662 	if (tmpno)
   1663 		sendport = 1;
   1664 #ifdef IPTOS_THROUGHPUT
   1665 	if (data_addr.su_family == AF_INET) {
   1666 		on = IPTOS_THROUGHPUT;
   1667 		if (setsockopt(data, IPPROTO_IP, IP_TOS,
   1668 				(void *)&on, sizeof(on)) == -1)
   1669 			DWARN("setsockopt %s (ignored)", "IPTOS_THROUGHPUT");
   1670 	}
   1671 #endif
   1672 	return (0);
   1673  bad:
   1674 	(void)close(data);
   1675 	data = -1;
   1676 	if (tmpno)
   1677 		sendport = 1;
   1678 	return (1);
   1679 }
   1680 
   1681 FILE *
   1682 dataconn(const char *lmode)
   1683 {
   1684 	struct sockinet	from;
   1685 	int		s, flags, rv, timeout;
   1686 	struct timeval	endtime, now, td;
   1687 	struct pollfd	pfd[1];
   1688 	socklen_t	fromlen;
   1689 
   1690 	if (passivemode)	/* passive data connection */
   1691 		return (fdopen(data, lmode));
   1692 
   1693 				/* active mode data connection */
   1694 
   1695 	if ((flags = fcntl(data, F_GETFL, 0)) == -1)
   1696 		goto dataconn_failed;		/* get current socket flags  */
   1697 	if (fcntl(data, F_SETFL, flags | O_NONBLOCK) == -1)
   1698 		goto dataconn_failed;		/* set non-blocking connect */
   1699 
   1700 		/* NOTE: we now must restore socket flags on successful exit */
   1701 
   1702 				/* limit time waiting on listening socket */
   1703 	pfd[0].fd = data;
   1704 	pfd[0].events = POLLIN;
   1705 	(void)gettimeofday(&endtime, NULL);	/* determine end time */
   1706 	endtime.tv_sec += (quit_time > 0) ? quit_time: 60;
   1707 						/* without -q, default to 60s */
   1708 	do {
   1709 		(void)gettimeofday(&now, NULL);
   1710 		timersub(&endtime, &now, &td);
   1711 		timeout = td.tv_sec * 1000 + td.tv_usec/1000;
   1712 		if (timeout < 0)
   1713 			timeout = 0;
   1714 		rv = ftp_poll(pfd, 1, timeout);
   1715 	} while (rv == -1 && errno == EINTR);	/* loop until poll ! EINTR */
   1716 	if (rv == -1) {
   1717 		warn("poll waiting before accept");
   1718 		goto dataconn_failed;
   1719 	}
   1720 	if (rv == 0) {
   1721 		warn("poll timeout waiting before accept");
   1722 		goto dataconn_failed;
   1723 	}
   1724 
   1725 				/* (non-blocking) accept the connection */
   1726 	fromlen = myctladdr.su_len;
   1727 	do {
   1728 		s = accept(data, (struct sockaddr *) &from.si_su, &fromlen);
   1729 	} while (s == -1 && errno == EINTR);	/* loop until accept ! EINTR */
   1730 	if (s == -1) {
   1731 		warn("accept");
   1732 		goto dataconn_failed;
   1733 	}
   1734 
   1735 	(void)close(data);
   1736 	data = s;
   1737 	if (fcntl(data, F_SETFL, flags) == -1)	/* restore socket flags */
   1738 		goto dataconn_failed;
   1739 
   1740 #ifdef IPTOS_THROUGHPUT
   1741 	if (from.su_family == AF_INET) {
   1742 		int tos = IPTOS_THROUGHPUT;
   1743 		if (setsockopt(s, IPPROTO_IP, IP_TOS,
   1744 				(void *)&tos, sizeof(tos)) == -1) {
   1745 			DWARN("setsockopt %s (ignored)", "IPTOS_THROUGHPUT");
   1746 		}
   1747 	}
   1748 #endif
   1749 	return (fdopen(data, lmode));
   1750 
   1751  dataconn_failed:
   1752 	(void)close(data);
   1753 	data = -1;
   1754 	return (NULL);
   1755 }
   1756 
   1757 void
   1758 psabort(int notused)
   1759 {
   1760 	int oerrno = errno;
   1761 
   1762 	sigint_raised = 1;
   1763 	alarmtimer(0);
   1764 	abrtflag++;
   1765 	errno = oerrno;
   1766 }
   1767 
   1768 void
   1769 pswitch(int flag)
   1770 {
   1771 	sigfunc oldintr;
   1772 	static struct comvars {
   1773 		int connect;
   1774 		char name[MAXHOSTNAMELEN];
   1775 		struct sockinet mctl;
   1776 		struct sockinet hctl;
   1777 		FILE *in;
   1778 		FILE *out;
   1779 		int tpe;
   1780 		int curtpe;
   1781 		int cpnd;
   1782 		int sunqe;
   1783 		int runqe;
   1784 		int mcse;
   1785 		int ntflg;
   1786 		char nti[17];
   1787 		char nto[17];
   1788 		int mapflg;
   1789 		char mi[MAXPATHLEN];
   1790 		char mo[MAXPATHLEN];
   1791 	} proxstruct, tmpstruct;
   1792 	struct comvars *ip, *op;
   1793 
   1794 	abrtflag = 0;
   1795 	oldintr = xsignal(SIGINT, psabort);
   1796 	if (flag) {
   1797 		if (proxy)
   1798 			return;
   1799 		ip = &tmpstruct;
   1800 		op = &proxstruct;
   1801 		proxy++;
   1802 	} else {
   1803 		if (!proxy)
   1804 			return;
   1805 		ip = &proxstruct;
   1806 		op = &tmpstruct;
   1807 		proxy = 0;
   1808 	}
   1809 	ip->connect = connected;
   1810 	connected = op->connect;
   1811 	if (hostname)
   1812 		(void)strlcpy(ip->name, hostname, sizeof(ip->name));
   1813 	else
   1814 		ip->name[0] = '\0';
   1815 	hostname = op->name;
   1816 	ip->hctl = hisctladdr;
   1817 	hisctladdr = op->hctl;
   1818 	ip->mctl = myctladdr;
   1819 	myctladdr = op->mctl;
   1820 	ip->in = cin;
   1821 	cin = op->in;
   1822 	ip->out = cout;
   1823 	cout = op->out;
   1824 	ip->tpe = type;
   1825 	type = op->tpe;
   1826 	ip->curtpe = curtype;
   1827 	curtype = op->curtpe;
   1828 	ip->cpnd = cpend;
   1829 	cpend = op->cpnd;
   1830 	ip->sunqe = sunique;
   1831 	sunique = op->sunqe;
   1832 	ip->runqe = runique;
   1833 	runique = op->runqe;
   1834 	ip->mcse = mcase;
   1835 	mcase = op->mcse;
   1836 	ip->ntflg = ntflag;
   1837 	ntflag = op->ntflg;
   1838 	(void)strlcpy(ip->nti, ntin, sizeof(ip->nti));
   1839 	(void)strlcpy(ntin, op->nti, sizeof(ntin));
   1840 	(void)strlcpy(ip->nto, ntout, sizeof(ip->nto));
   1841 	(void)strlcpy(ntout, op->nto, sizeof(ntout));
   1842 	ip->mapflg = mapflag;
   1843 	mapflag = op->mapflg;
   1844 	(void)strlcpy(ip->mi, mapin, sizeof(ip->mi));
   1845 	(void)strlcpy(mapin, op->mi, sizeof(mapin));
   1846 	(void)strlcpy(ip->mo, mapout, sizeof(ip->mo));
   1847 	(void)strlcpy(mapout, op->mo, sizeof(mapout));
   1848 	(void)xsignal(SIGINT, oldintr);
   1849 	if (abrtflag) {
   1850 		abrtflag = 0;
   1851 		(*oldintr)(SIGINT);
   1852 	}
   1853 }
   1854 
   1855 void
   1856 abortpt(int notused)
   1857 {
   1858 
   1859 	sigint_raised = 1;
   1860 	alarmtimer(0);
   1861 	if (fromatty)
   1862 		write(fileno(ttyout), "\n", 1);
   1863 	ptabflg++;
   1864 	mflag = 0;
   1865 	abrtflag = 0;
   1866 	siglongjmp(ptabort, 1);
   1867 }
   1868 
   1869 void
   1870 proxtrans(const char *cmd, const char *local, const char *remote)
   1871 {
   1872 	sigfunc oldintr;
   1873 	int prox_type, nfnd;
   1874 	volatile int secndflag;
   1875 	char *cmd2;
   1876 
   1877 #ifdef __GNUC__			/* to shut up gcc warnings */
   1878 	(void)&oldintr;
   1879 	(void)&cmd2;
   1880 #endif
   1881 
   1882 	oldintr = NULL;
   1883 	secndflag = 0;
   1884 	if (strcmp(cmd, "RETR"))
   1885 		cmd2 = "RETR";
   1886 	else
   1887 		cmd2 = runique ? "STOU" : "STOR";
   1888 	if ((prox_type = type) == 0) {
   1889 		if (unix_server && unix_proxy)
   1890 			prox_type = TYPE_I;
   1891 		else
   1892 			prox_type = TYPE_A;
   1893 	}
   1894 	if (curtype != prox_type)
   1895 		changetype(prox_type, 1);
   1896 	if (command("PASV") != COMPLETE) {
   1897 		fputs("proxy server does not support third party transfers.\n",
   1898 		    ttyout);
   1899 		return;
   1900 	}
   1901 	pswitch(0);
   1902 	if (!connected) {
   1903 		fputs("No primary connection.\n", ttyout);
   1904 		pswitch(1);
   1905 		code = -1;
   1906 		return;
   1907 	}
   1908 	if (curtype != prox_type)
   1909 		changetype(prox_type, 1);
   1910 	if (command("PORT %s", pasv) != COMPLETE) {
   1911 		pswitch(1);
   1912 		return;
   1913 	}
   1914 	if (sigsetjmp(ptabort, 1))
   1915 		goto abort;
   1916 	oldintr = xsignal(SIGINT, abortpt);
   1917 	if ((restart_point &&
   1918 	    (command("REST " LLF, (LLT) restart_point) != CONTINUE))
   1919 	    || (command("%s %s", cmd, remote) != PRELIM)) {
   1920 		(void)xsignal(SIGINT, oldintr);
   1921 		pswitch(1);
   1922 		return;
   1923 	}
   1924 	sleep(2);
   1925 	pswitch(1);
   1926 	secndflag++;
   1927 	if ((restart_point &&
   1928 	    (command("REST " LLF, (LLT) restart_point) != CONTINUE))
   1929 	    || (command("%s %s", cmd2, local) != PRELIM))
   1930 		goto abort;
   1931 	ptflag++;
   1932 	(void)getreply(0);
   1933 	pswitch(0);
   1934 	(void)getreply(0);
   1935 	(void)xsignal(SIGINT, oldintr);
   1936 	pswitch(1);
   1937 	ptflag = 0;
   1938 	fprintf(ttyout, "local: %s remote: %s\n", local, remote);
   1939 	return;
   1940  abort:
   1941 	if (sigsetjmp(xferabort, 1)) {
   1942 		(void)xsignal(SIGINT, oldintr);
   1943 		return;
   1944 	}
   1945 	(void)xsignal(SIGINT, abort_squared);
   1946 	ptflag = 0;
   1947 	if (strcmp(cmd, "RETR") && !proxy)
   1948 		pswitch(1);
   1949 	else if (!strcmp(cmd, "RETR") && proxy)
   1950 		pswitch(0);
   1951 	if (!cpend && !secndflag) {  /* only here if cmd = "STOR" (proxy=1) */
   1952 		if (command("%s %s", cmd2, local) != PRELIM) {
   1953 			pswitch(0);
   1954 			if (cpend)
   1955 				abort_remote(NULL);
   1956 		}
   1957 		pswitch(1);
   1958 		if (ptabflg)
   1959 			code = -1;
   1960 		(void)xsignal(SIGINT, oldintr);
   1961 		return;
   1962 	}
   1963 	if (cpend)
   1964 		abort_remote(NULL);
   1965 	pswitch(!proxy);
   1966 	if (!cpend && !secndflag) {  /* only if cmd = "RETR" (proxy=1) */
   1967 		if (command("%s %s", cmd2, local) != PRELIM) {
   1968 			pswitch(0);
   1969 			if (cpend)
   1970 				abort_remote(NULL);
   1971 			pswitch(1);
   1972 			if (ptabflg)
   1973 				code = -1;
   1974 			(void)xsignal(SIGINT, oldintr);
   1975 			return;
   1976 		}
   1977 	}
   1978 	if (cpend)
   1979 		abort_remote(NULL);
   1980 	pswitch(!proxy);
   1981 	if (cpend) {
   1982 		if ((nfnd = empty(cin, NULL, 10)) <= 0) {
   1983 			if (nfnd < 0)
   1984 				warn("abort");
   1985 			if (ptabflg)
   1986 				code = -1;
   1987 			lostpeer(0);
   1988 		}
   1989 		(void)getreply(0);
   1990 		(void)getreply(0);
   1991 	}
   1992 	if (proxy)
   1993 		pswitch(0);
   1994 	pswitch(1);
   1995 	if (ptabflg)
   1996 		code = -1;
   1997 	(void)xsignal(SIGINT, oldintr);
   1998 }
   1999 
   2000 void
   2001 reset(int argc, char *argv[])
   2002 {
   2003 	int nfnd = 1;
   2004 
   2005 	if (argc == 0 && argv != NULL) {
   2006 		UPRINTF("usage: %s\n", argv[0]);
   2007 		code = -1;
   2008 		return;
   2009 	}
   2010 	while (nfnd > 0) {
   2011 		if ((nfnd = empty(cin, NULL, 0)) < 0) {
   2012 			warn("reset");
   2013 			code = -1;
   2014 			lostpeer(0);
   2015 		} else if (nfnd)
   2016 			(void)getreply(0);
   2017 	}
   2018 }
   2019 
   2020 char *
   2021 gunique(const char *local)
   2022 {
   2023 	static char new[MAXPATHLEN];
   2024 	char *cp = strrchr(local, '/');
   2025 	int d, count=0, len;
   2026 	char ext = '1';
   2027 
   2028 	if (cp)
   2029 		*cp = '\0';
   2030 	d = access(cp == local ? "/" : cp ? local : ".", W_OK);
   2031 	if (cp)
   2032 		*cp = '/';
   2033 	if (d < 0) {
   2034 		warn("local: %s", local);
   2035 		return (NULL);
   2036 	}
   2037 	len = strlcpy(new, local, sizeof(new));
   2038 	cp = &new[len];
   2039 	*cp++ = '.';
   2040 	while (!d) {
   2041 		if (++count == 100) {
   2042 			fputs("runique: can't find unique file name.\n",
   2043 			    ttyout);
   2044 			return (NULL);
   2045 		}
   2046 		*cp++ = ext;
   2047 		*cp = '\0';
   2048 		if (ext == '9')
   2049 			ext = '0';
   2050 		else
   2051 			ext++;
   2052 		if ((d = access(new, F_OK)) < 0)
   2053 			break;
   2054 		if (ext != '0')
   2055 			cp--;
   2056 		else if (*(cp - 2) == '.')
   2057 			*(cp - 1) = '1';
   2058 		else {
   2059 			*(cp - 2) = *(cp - 2) + 1;
   2060 			cp--;
   2061 		}
   2062 	}
   2063 	return (new);
   2064 }
   2065 
   2066 /*
   2067  * abort_squared --
   2068  *	aborts abort_remote(). lostpeer() is called because if the user is
   2069  *	too impatient to wait or there's another problem then ftp really
   2070  *	needs to get back to a known state.
   2071  */
   2072 void
   2073 abort_squared(int dummy)
   2074 {
   2075 	char msgbuf[100];
   2076 	size_t len;
   2077 
   2078 	sigint_raised = 1;
   2079 	alarmtimer(0);
   2080 	len = strlcpy(msgbuf, "\nremote abort aborted; closing connection.\n",
   2081 	    sizeof(msgbuf));
   2082 	write(fileno(ttyout), msgbuf, len);
   2083 	lostpeer(0);
   2084 	siglongjmp(xferabort, 1);
   2085 }
   2086 
   2087 void
   2088 abort_remote(FILE *din)
   2089 {
   2090 	char buf[BUFSIZ];
   2091 	int nfnd;
   2092 
   2093 	if (cout == NULL) {
   2094 		warnx("Lost control connection for abort.");
   2095 		if (ptabflg)
   2096 			code = -1;
   2097 		lostpeer(0);
   2098 		return;
   2099 	}
   2100 	/*
   2101 	 * send IAC in urgent mode instead of DM because 4.3BSD places oob mark
   2102 	 * after urgent byte rather than before as is protocol now
   2103 	 */
   2104 	buf[0] = IAC;
   2105 	buf[1] = IP;
   2106 	buf[2] = IAC;
   2107 	if (send(fileno(cout), buf, 3, MSG_OOB) != 3)
   2108 		warn("abort");
   2109 	fprintf(cout, "%cABOR\r\n", DM);
   2110 	(void)fflush(cout);
   2111 	if ((nfnd = empty(cin, din, 10)) <= 0) {
   2112 		if (nfnd < 0)
   2113 			warn("abort");
   2114 		if (ptabflg)
   2115 			code = -1;
   2116 		lostpeer(0);
   2117 	}
   2118 	if (din && (nfnd & 2)) {
   2119 		while (read(fileno(din), buf, BUFSIZ) > 0)
   2120 			continue;
   2121 	}
   2122 	if (getreply(0) == ERROR && code == 552) {
   2123 		/* 552 needed for nic style abort */
   2124 		(void)getreply(0);
   2125 	}
   2126 	(void)getreply(0);
   2127 }
   2128 
   2129 void
   2130 ai_unmapped(struct addrinfo *ai)
   2131 {
   2132 #ifdef INET6
   2133 	struct sockaddr_in6 *sin6;
   2134 	struct sockaddr_in sin;
   2135 	socklen_t len;
   2136 
   2137 	if (ai->ai_family != AF_INET6)
   2138 		return;
   2139 	if (ai->ai_addrlen != sizeof(struct sockaddr_in6) ||
   2140 	    sizeof(sin) > ai->ai_addrlen)
   2141 		return;
   2142 	sin6 = (struct sockaddr_in6 *)ai->ai_addr;
   2143 	if (!IN6_IS_ADDR_V4MAPPED(&sin6->sin6_addr))
   2144 		return;
   2145 
   2146 	memset(&sin, 0, sizeof(sin));
   2147 	sin.sin_family = AF_INET;
   2148 	len = sizeof(struct sockaddr_in);
   2149 	memcpy(&sin.sin_addr, &sin6->sin6_addr.s6_addr[12],
   2150 	    sizeof(sin.sin_addr));
   2151 	sin.sin_port = sin6->sin6_port;
   2152 
   2153 	ai->ai_family = AF_INET;
   2154 #if HAVE_SOCKADDR_SA_LEN
   2155 	sin.sin_len = len;
   2156 #endif
   2157 	memcpy(ai->ai_addr, &sin, len);
   2158 	ai->ai_addrlen = len;
   2159 #endif
   2160 }
   2161 
   2162 #ifdef NO_USAGE
   2163 void
   2164 xusage(void)
   2165 {
   2166 	fputs("Usage error\n", ttyout);
   2167 }
   2168 #endif
   2169