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