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