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