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