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