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