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