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