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