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