Home | History | Annotate | Line # | Download | only in ftp
ftp.c revision 1.18
      1 /*      $NetBSD: ftp.c,v 1.18 1996/12/25 16:02:06 christos Exp $      */
      2 
      3 /*
      4  * Copyright (c) 1985, 1989, 1993, 1994
      5  *	The Regents of the University of California.  All rights reserved.
      6  *
      7  * Redistribution and use in source and binary forms, with or without
      8  * modification, are permitted provided that the following conditions
      9  * are met:
     10  * 1. Redistributions of source code must retain the above copyright
     11  *    notice, this list of conditions and the following disclaimer.
     12  * 2. Redistributions in binary form must reproduce the above copyright
     13  *    notice, this list of conditions and the following disclaimer in the
     14  *    documentation and/or other materials provided with the distribution.
     15  * 3. All advertising materials mentioning features or use of this software
     16  *    must display the following acknowledgement:
     17  *	This product includes software developed by the University of
     18  *	California, Berkeley and its contributors.
     19  * 4. Neither the name of the University nor the names of its contributors
     20  *    may be used to endorse or promote products derived from this software
     21  *    without specific prior written permission.
     22  *
     23  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
     24  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
     25  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
     26  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
     27  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
     28  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
     29  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
     30  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
     31  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
     32  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
     33  * SUCH DAMAGE.
     34  */
     35 
     36 #ifndef lint
     37 #if 0
     38 static char sccsid[] = "@(#)ftp.c	8.6 (Berkeley) 10/27/94";
     39 #else
     40 static char rcsid[] = "$NetBSD: ftp.c,v 1.18 1996/12/25 16:02:06 christos Exp $";
     41 #endif
     42 #endif /* not lint */
     43 
     44 #include <sys/param.h>
     45 #include <sys/stat.h>
     46 #include <sys/ioctl.h>
     47 #include <sys/socket.h>
     48 #include <sys/time.h>
     49 #include <sys/file.h>
     50 
     51 #include <netinet/in.h>
     52 #include <netinet/in_systm.h>
     53 #include <netinet/ip.h>
     54 #include <arpa/inet.h>
     55 #include <arpa/ftp.h>
     56 #include <arpa/telnet.h>
     57 
     58 #include <ctype.h>
     59 #include <err.h>
     60 #include <errno.h>
     61 #include <fcntl.h>
     62 #include <netdb.h>
     63 #include <pwd.h>
     64 #include <signal.h>
     65 #include <stdio.h>
     66 #include <stdlib.h>
     67 #include <string.h>
     68 #include <unistd.h>
     69 #include <varargs.h>
     70 
     71 #include "ftp_var.h"
     72 
     73 extern int h_errno;
     74 
     75 struct	sockaddr_in hisctladdr;
     76 struct	sockaddr_in data_addr;
     77 int	data = -1;
     78 int	abrtflag = 0;
     79 jmp_buf	ptabort;
     80 int	ptabflg;
     81 int	ptflag = 0;
     82 struct	sockaddr_in myctladdr;
     83 off_t	restart_point = 0;
     84 char   *direction;
     85 struct	timeval start;
     86 off_t	bytes;
     87 off_t	filesize;
     88 
     89 
     90 FILE	*cin, *cout;
     91 
     92 char *
     93 hookup(host, port)
     94 	const char *host;
     95 	int port;
     96 {
     97 	struct hostent *hp = 0;
     98 	int s, len, tos;
     99 	static char hostnamebuf[MAXHOSTNAMELEN];
    100 
    101 	memset((char *)&hisctladdr, 0, sizeof (hisctladdr));
    102 	if (inet_aton(host, &hisctladdr.sin_addr) != 0) {
    103 		hisctladdr.sin_family = AF_INET;
    104 		(void) strncpy(hostnamebuf, host, sizeof(hostnamebuf));
    105 	} else {
    106 		hp = gethostbyname(host);
    107 		if (hp == NULL) {
    108 			warnx("%s: %s", host, hstrerror(h_errno));
    109 			code = -1;
    110 			return ((char *) 0);
    111 		}
    112 		hisctladdr.sin_family = hp->h_addrtype;
    113 		memmove((caddr_t)&hisctladdr.sin_addr,
    114 				hp->h_addr_list[0], hp->h_length);
    115 		memcpy(&hisctladdr.sin_addr, hp->h_addr, hp->h_length);
    116 		(void) strncpy(hostnamebuf, hp->h_name, sizeof(hostnamebuf));
    117 	}
    118 	hostname = hostnamebuf;
    119 	s = socket(hisctladdr.sin_family, SOCK_STREAM, 0);
    120 	if (s < 0) {
    121 		warn("socket");
    122 		code = -1;
    123 		return (0);
    124 	}
    125 	hisctladdr.sin_port = port;
    126 	while (connect(s, (struct sockaddr *)&hisctladdr,
    127 			sizeof (hisctladdr)) < 0) {
    128 		if (hp && hp->h_addr_list[1]) {
    129 			int oerrno = errno;
    130 			char *ia;
    131 
    132 			ia = inet_ntoa(hisctladdr.sin_addr);
    133 			errno = oerrno;
    134 			warn("connect to address %s", ia);
    135 			hp->h_addr_list++;
    136 			memmove((caddr_t)&hisctladdr.sin_addr,
    137 					hp->h_addr_list[0], hp->h_length);
    138 			fprintf(stdout, "Trying %s...\n",
    139 				inet_ntoa(hisctladdr.sin_addr));
    140 			(void) close(s);
    141 			s = socket(hisctladdr.sin_family, SOCK_STREAM, 0);
    142 			if (s < 0) {
    143 				warn("socket");
    144 				code = -1;
    145 				return (0);
    146 			}
    147 			continue;
    148 		}
    149 		warn("connect");
    150 		code = -1;
    151 		goto bad;
    152 	}
    153 	len = sizeof (myctladdr);
    154 	if (getsockname(s, (struct sockaddr *)&myctladdr, &len) < 0) {
    155 		warn("getsockname");
    156 		code = -1;
    157 		goto bad;
    158 	}
    159 #ifdef IP_TOS
    160 	tos = IPTOS_LOWDELAY;
    161 	if (setsockopt(s, IPPROTO_IP, IP_TOS, (char *)&tos, sizeof(int)) < 0)
    162 		warn("setsockopt TOS (ignored)");
    163 #endif
    164 	cin = fdopen(s, "r");
    165 	cout = fdopen(s, "w");
    166 	if (cin == NULL || cout == NULL) {
    167 		warnx("fdopen failed.");
    168 		if (cin)
    169 			(void) fclose(cin);
    170 		if (cout)
    171 			(void) fclose(cout);
    172 		code = -1;
    173 		goto bad;
    174 	}
    175 	if (verbose)
    176 		printf("Connected to %s.\n", hostname);
    177 	if (getreply(0) > 2) { 	/* read startup message from server */
    178 		if (cin)
    179 			(void) fclose(cin);
    180 		if (cout)
    181 			(void) fclose(cout);
    182 		code = -1;
    183 		goto bad;
    184 	}
    185 #ifdef SO_OOBINLINE
    186 	{
    187 	int on = 1;
    188 
    189 	if (setsockopt(s, SOL_SOCKET, SO_OOBINLINE, (char *)&on, sizeof(on))
    190 		< 0 && debug) {
    191 			warn("setsockopt");
    192 		}
    193 	}
    194 #endif /* SO_OOBINLINE */
    195 
    196 	return (hostname);
    197 bad:
    198 	(void) close(s);
    199 	return ((char *)0);
    200 }
    201 
    202 int
    203 login(host)
    204 	const char *host;
    205 {
    206 	char tmp[80];
    207 	char *user, *pass, *acct;
    208 	char anonpass[MAXLOGNAME + MAXHOSTNAMELEN + 2];	/* "user@hostname\0" */
    209 	char hostname[MAXHOSTNAMELEN + 1];
    210 	int n, aflag = 0;
    211 
    212 	user = pass = acct = NULL;
    213 	if (ruserpass(host, &user, &pass, &acct) < 0) {
    214 		code = -1;
    215 		return (0);
    216 	}
    217 
    218 	/*
    219 	 * Set up arguments for an anonymous FTP session, if necessary.
    220 	 */
    221 	if ((user == NULL || pass == NULL) && anonftp) {
    222 		memset(anonpass, 0, sizeof(anonpass));
    223 		memset(hostname, 0, sizeof(hostname));
    224 
    225 		/*
    226 		 * Set up anonymous login password.
    227 		 */
    228 		user = getlogin();
    229 		gethostname(hostname, MAXHOSTNAMELEN);
    230 #ifndef DONT_CHEAT_ANONPASS
    231 		/*
    232 		 * Every anonymous FTP server I've encountered
    233 		 * will accept the string "username@", and will
    234 		 * append the hostname itself.  We do this by default
    235 		 * since many servers are picky about not having
    236 		 * a FQDN in the anonymous password. - thorpej (at) netbsd.org
    237 		 */
    238 		snprintf(anonpass, sizeof(anonpass) - 1, "%s@",
    239 		    user);
    240 #else
    241 		snprintf(anonpass, sizeof(anonpass) - 1, "%s@%s",
    242 		    user, hp->h_name);
    243 #endif
    244 		pass = anonpass;
    245 		user = "anonymous";
    246 	}
    247 
    248 	while (user == NULL) {
    249 		char *myname = getlogin();
    250 
    251 		if (myname == NULL) {
    252 			struct passwd *pp = getpwuid(getuid());
    253 
    254 			if (pp != NULL)
    255 				myname = pp->pw_name;
    256 		}
    257 		if (myname)
    258 			printf("Name (%s:%s): ", host, myname);
    259 		else
    260 			printf("Name (%s): ", host);
    261 		(void) fgets(tmp, sizeof(tmp) - 1, stdin);
    262 		tmp[strlen(tmp) - 1] = '\0';
    263 		if (*tmp == '\0')
    264 			user = myname;
    265 		else
    266 			user = tmp;
    267 	}
    268 	n = command("USER %s", user);
    269 	if (n == CONTINUE) {
    270 		if (pass == NULL)
    271 			pass = getpass("Password:");
    272 		n = command("PASS %s", pass);
    273 	}
    274 	if (n == CONTINUE) {
    275 		aflag++;
    276 		acct = getpass("Account:");
    277 		n = command("ACCT %s", acct);
    278 	}
    279 	if (n != COMPLETE) {
    280 		warnx("Login failed.");
    281 		return (0);
    282 	}
    283 	if (!aflag && acct != NULL)
    284 		(void) command("ACCT %s", acct);
    285 	if (proxy)
    286 		return (1);
    287 	for (n = 0; n < macnum; ++n) {
    288 		if (!strcmp("init", macros[n].mac_name)) {
    289 			(void) strcpy(line, "$init");
    290 			makeargv();
    291 			domacro(margc, margv);
    292 			break;
    293 		}
    294 	}
    295 	return (1);
    296 }
    297 
    298 void
    299 cmdabort()
    300 {
    301 
    302 	printf("\n");
    303 	(void) fflush(stdout);
    304 	abrtflag++;
    305 	if (ptflag)
    306 		longjmp(ptabort, 1);
    307 }
    308 
    309 /*VARARGS*/
    310 int
    311 command(va_alist)
    312 va_dcl
    313 {
    314 	va_list ap;
    315 	char *fmt;
    316 	int r;
    317 	sig_t oldintr;
    318 
    319 	abrtflag = 0;
    320 	if (debug) {
    321 		printf("---> ");
    322 		va_start(ap);
    323 		fmt = va_arg(ap, char *);
    324 		if (strncmp("PASS ", fmt, 5) == 0)
    325 			printf("PASS XXXX");
    326 		else if (strncmp("ACCT ", fmt, 5) == 0)
    327 			printf("ACCT XXXX");
    328 		else
    329 			vfprintf(stdout, fmt, ap);
    330 		va_end(ap);
    331 		printf("\n");
    332 		(void) fflush(stdout);
    333 	}
    334 	if (cout == NULL) {
    335 		warn("No control connection for command");
    336 		code = -1;
    337 		return (0);
    338 	}
    339 	oldintr = signal(SIGINT, cmdabort);
    340 	va_start(ap);
    341 	fmt = va_arg(ap, char *);
    342 	vfprintf(cout, fmt, ap);
    343 	va_end(ap);
    344 	fprintf(cout, "\r\n");
    345 	(void) fflush(cout);
    346 	cpend = 1;
    347 	r = getreply(!strcmp(fmt, "QUIT"));
    348 	if (abrtflag && oldintr != SIG_IGN)
    349 		(*oldintr)(SIGINT);
    350 	(void) signal(SIGINT, oldintr);
    351 	return (r);
    352 }
    353 
    354 char reply_string[BUFSIZ];		/* first line of previous reply */
    355 
    356 int
    357 getreply(expecteof)
    358 	int expecteof;
    359 {
    360 	char current_line[BUFSIZ];	/* last line of previous reply */
    361 	int c, n, line;
    362 	int dig;
    363 	int originalcode = 0, continuation = 0;
    364 	sig_t oldintr;
    365 	int pflag = 0;
    366 	char *cp, *pt = pasv;
    367 
    368 	oldintr = signal(SIGINT, cmdabort);
    369 	for (line = 0 ;; line++) {
    370 		dig = n = code = 0;
    371 		cp = current_line;
    372 		while ((c = getc(cin)) != '\n') {
    373 			if (c == IAC) {     /* handle telnet commands */
    374 				switch (c = getc(cin)) {
    375 				case WILL:
    376 				case WONT:
    377 					c = getc(cin);
    378 					fprintf(cout, "%c%c%c", IAC, DONT, c);
    379 					(void) fflush(cout);
    380 					break;
    381 				case DO:
    382 				case DONT:
    383 					c = getc(cin);
    384 					fprintf(cout, "%c%c%c", IAC, WONT, c);
    385 					(void) fflush(cout);
    386 					break;
    387 				default:
    388 					break;
    389 				}
    390 				continue;
    391 			}
    392 			dig++;
    393 			if (c == EOF) {
    394 				if (expecteof) {
    395 					(void) signal(SIGINT, oldintr);
    396 					code = 221;
    397 					return (0);
    398 				}
    399 				lostpeer();
    400 				if (verbose) {
    401 					printf("421 Service not available, "
    402 					   "remote server has closed "
    403 					   "connection\n");
    404 					(void) fflush(stdout);
    405 				}
    406 				code = 421;
    407 				return (4);
    408 			}
    409 			if (c != '\r' && (verbose > 0 ||
    410 			    (verbose > -1 && n == '5' && dig > 4))) {
    411 				if (proxflag &&
    412 				   (dig == 1 || (dig == 5 && verbose == 0)))
    413 					printf("%s:", hostname);
    414 				(void) putchar(c);
    415 			}
    416 			if (dig < 4 && isdigit(c))
    417 				code = code * 10 + (c - '0');
    418 			if (!pflag && code == 227)
    419 				pflag = 1;
    420 			if (dig > 4 && pflag == 1 && isdigit(c))
    421 				pflag = 2;
    422 			if (pflag == 2) {
    423 				if (c != '\r' && c != ')')
    424 					*pt++ = c;
    425 				else {
    426 					*pt = '\0';
    427 					pflag = 3;
    428 				}
    429 			}
    430 			if (dig == 4 && c == '-') {
    431 				if (continuation)
    432 					code = 0;
    433 				continuation++;
    434 			}
    435 			if (n == 0)
    436 				n = c;
    437 			if (cp < &current_line[sizeof(current_line) - 1])
    438 				*cp++ = c;
    439 		}
    440 		if (verbose > 0 || (verbose > -1 && n == '5')) {
    441 			(void) putchar(c);
    442 			(void) fflush (stdout);
    443 		}
    444 		if (line == 0) {
    445 			size_t len = cp - current_line;
    446 
    447 			if (len > sizeof(reply_string))
    448 				len = sizeof(reply_string);
    449 
    450 			(void) strncpy(reply_string, current_line, len);
    451 			reply_string[len] = '\0';
    452 		}
    453 		if (continuation && code != originalcode) {
    454 			if (originalcode == 0)
    455 				originalcode = code;
    456 			continue;
    457 		}
    458 		*cp = '\0';
    459 		if (n != '1')
    460 			cpend = 0;
    461 		(void) signal(SIGINT, oldintr);
    462 		if (code == 421 || originalcode == 421)
    463 			lostpeer();
    464 		if (abrtflag && oldintr != cmdabort && oldintr != SIG_IGN)
    465 			(*oldintr)(SIGINT);
    466 		return (n - '0');
    467 	}
    468 }
    469 
    470 int
    471 empty(mask, sec)
    472 	struct fd_set *mask;
    473 	int sec;
    474 {
    475 	struct timeval t;
    476 
    477 	t.tv_sec = (long) sec;
    478 	t.tv_usec = 0;
    479 	return (select(32, mask, (struct fd_set *) 0, (struct fd_set *) 0, &t));
    480 }
    481 
    482 jmp_buf	sendabort;
    483 
    484 void
    485 abortsend()
    486 {
    487 
    488 	mflag = 0;
    489 	abrtflag = 0;
    490 	printf("\nsend aborted\nwaiting for remote to finish abort\n");
    491 	(void) fflush(stdout);
    492 	longjmp(sendabort, 1);
    493 }
    494 
    495 void
    496 sendrequest(cmd, local, remote, printnames)
    497 	const char *cmd, *local, *remote;
    498 	int printnames;
    499 {
    500 	struct stat st;
    501 	int c, d;
    502 	FILE *fin, *dout = 0;
    503 	int (*closefunc) __P((FILE *));
    504 	sig_t oldinti, oldintr, oldintp;
    505 	off_t hashbytes;
    506 	char *lmode, buf[BUFSIZ], *bufp;
    507 
    508 	hashbytes = mark;
    509 	direction = "sent";
    510 	bytes = 0;
    511 	filesize = -1;
    512 	if (verbose && printnames) {
    513 		if (local && *local != '-')
    514 			printf("local: %s ", local);
    515 		if (remote)
    516 			printf("remote: %s\n", remote);
    517 	}
    518 	if (proxy) {
    519 		proxtrans(cmd, local, remote);
    520 		return;
    521 	}
    522 	if (curtype != type)
    523 		changetype(type, 0);
    524 	closefunc = NULL;
    525 	oldintr = NULL;
    526 	oldintp = NULL;
    527 	oldinti = NULL;
    528 	lmode = "w";
    529 	if (setjmp(sendabort)) {
    530 		while (cpend) {
    531 			(void) getreply(0);
    532 		}
    533 		if (data >= 0) {
    534 			(void) close(data);
    535 			data = -1;
    536 		}
    537 		if (oldintr)
    538 			(void) signal(SIGINT, oldintr);
    539 		if (oldintp)
    540 			(void) signal(SIGPIPE, oldintp);
    541 		if (oldinti)
    542 			(void) signal(SIGINFO, oldinti);
    543 		code = -1;
    544 		return;
    545 	}
    546 	oldintr = signal(SIGINT, abortsend);
    547 	oldinti = signal(SIGINFO, psummary);
    548 	if (strcmp(local, "-") == 0)
    549 		fin = stdin;
    550 	else if (*local == '|') {
    551 		oldintp = signal(SIGPIPE, SIG_IGN);
    552 		fin = popen(local + 1, "r");
    553 		if (fin == NULL) {
    554 			warn("%s", local + 1);
    555 			(void) signal(SIGINT, oldintr);
    556 			(void) signal(SIGPIPE, oldintp);
    557 			(void) signal(SIGINFO, oldinti);
    558 			code = -1;
    559 			return;
    560 		}
    561 		closefunc = pclose;
    562 	} else {
    563 		fin = fopen(local, "r");
    564 		if (fin == NULL) {
    565 			warn("local: %s", local);
    566 			(void) signal(SIGINT, oldintr);
    567 			(void) signal(SIGINFO, oldinti);
    568 			code = -1;
    569 			return;
    570 		}
    571 		closefunc = fclose;
    572 		if (fstat(fileno(fin), &st) < 0 ||
    573 		    (st.st_mode&S_IFMT) != S_IFREG) {
    574 			fprintf(stdout, "%s: not a plain file.\n", local);
    575 			(void) signal(SIGINT, oldintr);
    576 			(void) signal(SIGINFO, oldinti);
    577 			fclose(fin);
    578 			code = -1;
    579 			return;
    580 		}
    581 		filesize = st.st_size;
    582 	}
    583 	if (initconn()) {
    584 		(void) signal(SIGINT, oldintr);
    585 		(void) signal(SIGINFO, oldinti);
    586 		if (oldintp)
    587 			(void) signal(SIGPIPE, oldintp);
    588 		code = -1;
    589 		if (closefunc != NULL)
    590 			(*closefunc)(fin);
    591 		return;
    592 	}
    593 	if (setjmp(sendabort))
    594 		goto abort;
    595 
    596 	if (restart_point &&
    597 	    (strcmp(cmd, "STOR") == 0 || strcmp(cmd, "APPE") == 0)) {
    598 		int rc;
    599 
    600 		switch (curtype) {
    601 		case TYPE_A:
    602 			rc = fseek(fin, (long) restart_point, SEEK_SET);
    603 			break;
    604 		case TYPE_I:
    605 		case TYPE_L:
    606 			rc = lseek(fileno(fin), restart_point, SEEK_SET);
    607 			break;
    608 		}
    609 		if (rc < 0) {
    610 			warn("local: %s", local);
    611 			restart_point = 0;
    612 			if (closefunc != NULL)
    613 				(*closefunc)(fin);
    614 			return;
    615 		}
    616 		if (command("REST %ld", (long) restart_point)
    617 			!= CONTINUE) {
    618 			restart_point = 0;
    619 			if (closefunc != NULL)
    620 				(*closefunc)(fin);
    621 			return;
    622 		}
    623 		restart_point = 0;
    624 		lmode = "r+w";
    625 	}
    626 	if (remote) {
    627 		if (command("%s %s", cmd, remote) != PRELIM) {
    628 			(void) signal(SIGINT, oldintr);
    629 			(void) signal(SIGINFO, oldinti);
    630 			if (oldintp)
    631 				(void) signal(SIGPIPE, oldintp);
    632 			if (closefunc != NULL)
    633 				(*closefunc)(fin);
    634 			return;
    635 		}
    636 	} else
    637 		if (command("%s", cmd) != PRELIM) {
    638 			(void) signal(SIGINT, oldintr);
    639 			(void) signal(SIGINFO, oldinti);
    640 			if (oldintp)
    641 				(void) signal(SIGPIPE, oldintp);
    642 			if (closefunc != NULL)
    643 				(*closefunc)(fin);
    644 			return;
    645 		}
    646 	dout = dataconn(lmode);
    647 	if (dout == NULL)
    648 		goto abort;
    649 	(void) gettimeofday(&start, (struct timezone *)0);
    650 	progressmeter(-1);
    651 	oldintp = signal(SIGPIPE, SIG_IGN);
    652 	switch (curtype) {
    653 
    654 	case TYPE_I:
    655 	case TYPE_L:
    656 		errno = d = 0;
    657 		while ((c = read(fileno(fin), buf, sizeof (buf))) > 0) {
    658 			bytes += c;
    659 			for (bufp = buf; c > 0; c -= d, bufp += d)
    660 				if ((d = write(fileno(dout), bufp, c)) <= 0)
    661 					break;
    662 			if (hash && !progress) {
    663 				while (bytes >= hashbytes) {
    664 					(void) putchar('#');
    665 					hashbytes += mark;
    666 				}
    667 				(void) fflush(stdout);
    668 			}
    669 			progressmeter(0);
    670 		}
    671 		if (hash && !progress && bytes > 0) {
    672 			if (bytes < mark)
    673 				(void) putchar('#');
    674 			(void) putchar('\n');
    675 			(void) fflush(stdout);
    676 		}
    677 		if (c < 0)
    678 			warn("local: %s", local);
    679 		if (d < 0) {
    680 			if (errno != EPIPE)
    681 				warn("netout");
    682 			bytes = -1;
    683 		}
    684 		break;
    685 
    686 	case TYPE_A:
    687 		while ((c = getc(fin)) != EOF) {
    688 			if (c == '\n') {
    689 				while (hash && !progress &&
    690 				    (bytes >= hashbytes)) {
    691 					(void) putchar('#');
    692 					(void) fflush(stdout);
    693 					hashbytes += mark;
    694 				}
    695 				if (ferror(dout))
    696 					break;
    697 				(void) putc('\r', dout);
    698 				bytes++;
    699 			}
    700 			(void) putc(c, dout);
    701 			bytes++;
    702 #if 0	/* this violates RFC */
    703 			if (c == '\r') {
    704 				(void)putc('\0', dout);
    705 				bytes++;
    706 			}
    707 #endif
    708 			progressmeter(0);
    709 		}
    710 		if (hash && !progress) {
    711 			if (bytes < hashbytes)
    712 				(void) putchar('#');
    713 			(void) putchar('\n');
    714 			(void) fflush(stdout);
    715 		}
    716 		if (ferror(fin))
    717 			warn("local: %s", local);
    718 		if (ferror(dout)) {
    719 			if (errno != EPIPE)
    720 				warn("netout");
    721 			bytes = -1;
    722 		}
    723 		break;
    724 	}
    725 	if (bytes > 0)
    726 		progressmeter(1);
    727 	if (closefunc != NULL)
    728 		(*closefunc)(fin);
    729 	(void) fclose(dout);
    730 	(void) getreply(0);
    731 	(void) signal(SIGINT, oldintr);
    732 	(void) signal(SIGINFO, oldinti);
    733 	if (oldintp)
    734 		(void) signal(SIGPIPE, oldintp);
    735 	if (bytes > 0)
    736 		ptransfer(0);
    737 	return;
    738 abort:
    739 	(void) signal(SIGINT, oldintr);
    740 	(void) signal(SIGINFO, oldinti);
    741 	if (oldintp)
    742 		(void) signal(SIGPIPE, oldintp);
    743 	if (!cpend) {
    744 		code = -1;
    745 		return;
    746 	}
    747 	if (data >= 0) {
    748 		(void) close(data);
    749 		data = -1;
    750 	}
    751 	if (dout)
    752 		(void) fclose(dout);
    753 	(void) getreply(0);
    754 	code = -1;
    755 	if (closefunc != NULL && fin != NULL)
    756 		(*closefunc)(fin);
    757 	if (bytes > 0)
    758 		ptransfer(0);
    759 }
    760 
    761 jmp_buf	recvabort;
    762 
    763 void
    764 abortrecv()
    765 {
    766 
    767 	mflag = 0;
    768 	abrtflag = 0;
    769 	printf("\nreceive aborted\nwaiting for remote to finish abort\n");
    770 	(void) fflush(stdout);
    771 	longjmp(recvabort, 1);
    772 }
    773 
    774 void
    775 recvrequest(cmd, local, remote, lmode, printnames)
    776 	const char *cmd, *local, *remote, *lmode;
    777 	int printnames;
    778 {
    779 	FILE *fout, *din = 0;
    780 	int (*closefunc) __P((FILE *));
    781 	sig_t oldinti, oldintr, oldintp;
    782 	int c, d, is_retr, tcrflag, bare_lfs = 0;
    783 	static int bufsize;
    784 	static char *buf;
    785 	off_t hashbytes;
    786 	struct stat st;
    787 	time_t mtime;
    788 	struct timeval tval[2];
    789 
    790 	hashbytes = mark;
    791 	direction = "received";
    792 	bytes = 0;
    793 	filesize = -1;
    794 	is_retr = strcmp(cmd, "RETR") == 0;
    795 	if (is_retr && verbose && printnames) {
    796 		if (local && *local != '-')
    797 			printf("local: %s ", local);
    798 		if (remote)
    799 			printf("remote: %s\n", remote);
    800 	}
    801 	if (proxy && is_retr) {
    802 		proxtrans(cmd, local, remote);
    803 		return;
    804 	}
    805 	closefunc = NULL;
    806 	oldintr = NULL;
    807 	oldintp = NULL;
    808 	tcrflag = !crflag && is_retr;
    809 	if (setjmp(recvabort)) {
    810 		while (cpend) {
    811 			(void) getreply(0);
    812 		}
    813 		if (data >= 0) {
    814 			(void) close(data);
    815 			data = -1;
    816 		}
    817 		if (oldintr)
    818 			(void) signal(SIGINT, oldintr);
    819 		if (oldinti)
    820 			(void) signal(SIGINFO, oldinti);
    821 		code = -1;
    822 		return;
    823 	}
    824 	oldintr = signal(SIGINT, abortrecv);
    825 	oldinti = signal(SIGINFO, psummary);
    826 	if (strcmp(local, "-") && *local != '|') {
    827 		if (access(local, 2) < 0) {
    828 			char *dir = strrchr(local, '/');
    829 
    830 			if (errno != ENOENT && errno != EACCES) {
    831 				warn("local: %s", local);
    832 				(void) signal(SIGINT, oldintr);
    833 				(void) signal(SIGINFO, oldinti);
    834 				code = -1;
    835 				return;
    836 			}
    837 			if (dir != NULL)
    838 				*dir = 0;
    839 			d = access(dir == local ? "/" : dir ? local : ".", 2);
    840 			if (dir != NULL)
    841 				*dir = '/';
    842 			if (d < 0) {
    843 				warn("local: %s", local);
    844 				(void) signal(SIGINT, oldintr);
    845 				(void) signal(SIGINFO, oldinti);
    846 				code = -1;
    847 				return;
    848 			}
    849 			if (!runique && errno == EACCES &&
    850 			    chmod(local, 0600) < 0) {
    851 				warn("local: %s", local);
    852 				(void) signal(SIGINT, oldintr);
    853 				(void) signal(SIGINFO, oldinti);
    854 				code = -1;
    855 				return;
    856 			}
    857 			if (runique && errno == EACCES &&
    858 			   (local = gunique(local)) == NULL) {
    859 				(void) signal(SIGINT, oldintr);
    860 				(void) signal(SIGINFO, oldinti);
    861 				code = -1;
    862 				return;
    863 			}
    864 		}
    865 		else if (runique && (local = gunique(local)) == NULL) {
    866 			(void) signal(SIGINT, oldintr);
    867 			(void) signal(SIGINFO, oldinti);
    868 			code = -1;
    869 			return;
    870 		}
    871 	}
    872 	if (!is_retr) {
    873 		if (curtype != TYPE_A)
    874 			changetype(TYPE_A, 0);
    875 	} else {
    876 		if (curtype != type)
    877 			changetype(type, 0);
    878 		filesize = remotesize(remote);
    879 	}
    880 	if (initconn()) {
    881 		(void) signal(SIGINT, oldintr);
    882 		(void) signal(SIGINFO, oldinti);
    883 		code = -1;
    884 		return;
    885 	}
    886 	if (setjmp(recvabort))
    887 		goto abort;
    888 	if (is_retr && restart_point &&
    889 	    command("REST %ld", (long) restart_point) != CONTINUE)
    890 		return;
    891 	if (remote) {
    892 		if (command("%s %s", cmd, remote) != PRELIM) {
    893 			(void) signal(SIGINT, oldintr);
    894 			(void) signal(SIGINFO, oldinti);
    895 			return;
    896 		}
    897 	} else {
    898 		if (command("%s", cmd) != PRELIM) {
    899 			(void) signal(SIGINT, oldintr);
    900 			(void) signal(SIGINFO, oldinti);
    901 			return;
    902 		}
    903 	}
    904 	din = dataconn("r");
    905 	if (din == NULL)
    906 		goto abort;
    907 	if (strcmp(local, "-") == 0)
    908 		fout = stdout;
    909 	else if (*local == '|') {
    910 		oldintp = signal(SIGPIPE, SIG_IGN);
    911 		fout = popen(local + 1, "w");
    912 		if (fout == NULL) {
    913 			warn("%s", local+1);
    914 			goto abort;
    915 		}
    916 		closefunc = pclose;
    917 	} else {
    918 		fout = fopen(local, lmode);
    919 		if (fout == NULL) {
    920 			warn("local: %s", local);
    921 			goto abort;
    922 		}
    923 		closefunc = fclose;
    924 	}
    925 	if (fstat(fileno(fout), &st) < 0 || st.st_blksize == 0)
    926 		st.st_blksize = BUFSIZ;
    927 	if (st.st_blksize > bufsize) {
    928 		if (buf)
    929 			(void) free(buf);
    930 		buf = malloc((unsigned)st.st_blksize);
    931 		if (buf == NULL) {
    932 			warn("malloc");
    933 			bufsize = 0;
    934 			goto abort;
    935 		}
    936 		bufsize = st.st_blksize;
    937 	}
    938 	(void) gettimeofday(&start, (struct timezone *)0);
    939 	progressmeter(-1);
    940 	switch (curtype) {
    941 
    942 	case TYPE_I:
    943 	case TYPE_L:
    944 		if (restart_point &&
    945 		    lseek(fileno(fout), restart_point, SEEK_SET) < 0) {
    946 			warn("local: %s", local);
    947 			if (closefunc != NULL)
    948 				(*closefunc)(fout);
    949 			return;
    950 		}
    951 		errno = d = 0;
    952 		while ((c = read(fileno(din), buf, bufsize)) > 0) {
    953 			if ((d = write(fileno(fout), buf, c)) != c)
    954 				break;
    955 			bytes += c;
    956 			if (hash && !progress) {
    957 				while (bytes >= hashbytes) {
    958 					(void) putchar('#');
    959 					hashbytes += mark;
    960 				}
    961 				(void) fflush(stdout);
    962 			}
    963 			progressmeter(0);
    964 		}
    965 		if (hash && !progress && bytes > 0) {
    966 			if (bytes < mark)
    967 				(void) putchar('#');
    968 			(void) putchar('\n');
    969 			(void) fflush(stdout);
    970 		}
    971 		if (c < 0) {
    972 			if (errno != EPIPE)
    973 				warn("netin");
    974 			bytes = -1;
    975 		}
    976 		if (d < c) {
    977 			if (d < 0)
    978 				warn("local: %s", local);
    979 			else
    980 				warnx("%s: short write", local);
    981 		}
    982 		break;
    983 
    984 	case TYPE_A:
    985 		if (restart_point) {
    986 			int i, n, ch;
    987 
    988 			if (fseek(fout, 0L, SEEK_SET) < 0)
    989 				goto done;
    990 			n = restart_point;
    991 			for (i = 0; i++ < n;) {
    992 				if ((ch = getc(fout)) == EOF)
    993 					goto done;
    994 				if (ch == '\n')
    995 					i++;
    996 			}
    997 			if (fseek(fout, 0L, SEEK_CUR) < 0) {
    998 done:
    999 				warn("local: %s", local);
   1000 				if (closefunc != NULL)
   1001 					(*closefunc)(fout);
   1002 				return;
   1003 			}
   1004 		}
   1005 		while ((c = getc(din)) != EOF) {
   1006 			if (c == '\n')
   1007 				bare_lfs++;
   1008 			while (c == '\r') {
   1009 				while (hash && !progress &&
   1010 				    (bytes >= hashbytes)) {
   1011 					(void) putchar('#');
   1012 					(void) fflush(stdout);
   1013 					hashbytes += mark;
   1014 				}
   1015 				bytes++;
   1016 				if ((c = getc(din)) != '\n' || tcrflag) {
   1017 					if (ferror(fout))
   1018 						goto break2;
   1019 					(void) putc('\r', fout);
   1020 					if (c == '\0') {
   1021 						bytes++;
   1022 						goto contin2;
   1023 					}
   1024 					if (c == EOF)
   1025 						goto contin2;
   1026 				}
   1027 			}
   1028 			(void) putc(c, fout);
   1029 			bytes++;
   1030 	contin2:	;
   1031 			progressmeter(0);
   1032 		}
   1033 break2:
   1034 		if (bare_lfs) {
   1035 			printf("WARNING! %d bare linefeeds received in ASCII "
   1036 			    "mode\n", bare_lfs);
   1037 			printf("File may not have transferred correctly.\n");
   1038 		}
   1039 		if (hash && !progress) {
   1040 			if (bytes < hashbytes)
   1041 				(void) putchar('#');
   1042 			(void) putchar('\n');
   1043 			(void) fflush(stdout);
   1044 		}
   1045 		if (ferror(din)) {
   1046 			if (errno != EPIPE)
   1047 				warn("netin");
   1048 			bytes = -1;
   1049 		}
   1050 		if (ferror(fout))
   1051 			warn("local: %s", local);
   1052 		break;
   1053 	}
   1054 	if (bytes > 0)
   1055 		progressmeter(1);
   1056 	if (closefunc != NULL)
   1057 		(*closefunc)(fout);
   1058 	(void) signal(SIGINT, oldintr);
   1059 	(void) signal(SIGINFO, oldinti);
   1060 	if (oldintp)
   1061 		(void) signal(SIGPIPE, oldintp);
   1062 	(void) fclose(din);
   1063 	(void) getreply(0);
   1064 	if (bytes > 0 && is_retr) {
   1065 		ptransfer(0);
   1066 		if (preserve && (closefunc == fclose)) {
   1067 			mtime = remotemodtime(remote);
   1068 			if (mtime != -1) {
   1069 				(void) gettimeofday(&tval[0],
   1070 				    (struct timezone *)0);
   1071 				tval[1].tv_sec = mtime;
   1072 				tval[1].tv_usec = 0;
   1073 				if (utimes(local, tval) == -1) {
   1074 					printf("Can't change modification time "
   1075 						"on %s to %s", local,
   1076 						asctime(localtime(&mtime)));
   1077 				}
   1078 			}
   1079 		}
   1080 	}
   1081 	return;
   1082 abort:
   1083 
   1084 /* abort using RFC959 recommended IP,SYNC sequence */
   1085 
   1086 	if (oldintp)
   1087 		(void) signal(SIGPIPE, oldintp);
   1088 	(void) signal(SIGINT, SIG_IGN);
   1089 	if (!cpend) {
   1090 		code = -1;
   1091 		(void) signal(SIGINT, oldintr);
   1092 		(void) signal(SIGINFO, oldinti);
   1093 		return;
   1094 	}
   1095 
   1096 	abort_remote(din);
   1097 	code = -1;
   1098 	if (data >= 0) {
   1099 		(void) close(data);
   1100 		data = -1;
   1101 	}
   1102 	if (closefunc != NULL && fout != NULL)
   1103 		(*closefunc)(fout);
   1104 	if (din)
   1105 		(void) fclose(din);
   1106 	if (bytes > 0)
   1107 		ptransfer(0);
   1108 	(void) signal(SIGINT, oldintr);
   1109 	(void) signal(SIGINFO, oldinti);
   1110 }
   1111 
   1112 /*
   1113  * Need to start a listen on the data channel before we send the command,
   1114  * otherwise the server's connect may fail.
   1115  */
   1116 int
   1117 initconn()
   1118 {
   1119 	char *p, *a;
   1120 	int result, len, tmpno = 0;
   1121 	int on = 1;
   1122 	int a0, a1, a2, a3, p0, p1;
   1123 
   1124 	if (passivemode) {
   1125 		data = socket(AF_INET, SOCK_STREAM, 0);
   1126 		if (data < 0) {
   1127 			perror("ftp: socket");
   1128 			return(1);
   1129 		}
   1130 		if ((options & SO_DEBUG) &&
   1131 		    setsockopt(data, SOL_SOCKET, SO_DEBUG, (char *)&on,
   1132 			       sizeof (on)) < 0)
   1133 			perror("ftp: setsockopt (ignored)");
   1134 		if (command("PASV") != COMPLETE) {
   1135 			printf("Passive mode refused.\n");
   1136 			goto bad;
   1137 		}
   1138 
   1139 		/*
   1140 		 * What we've got at this point is a string of comma
   1141 		 * separated one-byte unsigned integer values.
   1142 		 * The first four are the an IP address. The fifth is
   1143 		 * the MSB of the port number, the sixth is the LSB.
   1144 		 * From that we'll prepare a sockaddr_in.
   1145 		 */
   1146 
   1147 		if (sscanf(pasv, "%d,%d,%d,%d,%d,%d",
   1148 			   &a0, &a1, &a2, &a3, &p0, &p1) != 6) {
   1149 			printf("Passive mode address scan failure. "
   1150 			       "Shouldn't happen!\n");
   1151 			goto bad;
   1152 		}
   1153 
   1154 		memset(&data_addr, 0, sizeof(data_addr));
   1155 		data_addr.sin_family = AF_INET;
   1156 		a = (char *)&data_addr.sin_addr.s_addr;
   1157 		a[0] = a0 & 0xff;
   1158 		a[1] = a1 & 0xff;
   1159 		a[2] = a2 & 0xff;
   1160 		a[3] = a3 & 0xff;
   1161 		p = (char *)&data_addr.sin_port;
   1162 		p[0] = p0 & 0xff;
   1163 		p[1] = p1 & 0xff;
   1164 
   1165 		if (connect(data, (struct sockaddr *)&data_addr,
   1166 			    sizeof(data_addr)) < 0) {
   1167 			perror("ftp: connect");
   1168 			goto bad;
   1169 		}
   1170 #ifdef IP_TOS
   1171 		on = IPTOS_THROUGHPUT;
   1172 		if (setsockopt(data, IPPROTO_IP, IP_TOS, (char *)&on,
   1173 			       sizeof(int)) < 0)
   1174 			perror("ftp: setsockopt TOS (ignored)");
   1175 #endif
   1176 		return(0);
   1177 	}
   1178 
   1179 noport:
   1180 	data_addr = myctladdr;
   1181 	if (sendport)
   1182 		data_addr.sin_port = 0;	/* let system pick one */
   1183 	if (data != -1)
   1184 		(void) close(data);
   1185 	data = socket(AF_INET, SOCK_STREAM, 0);
   1186 	if (data < 0) {
   1187 		warn("socket");
   1188 		if (tmpno)
   1189 			sendport = 1;
   1190 		return (1);
   1191 	}
   1192 	if (!sendport)
   1193 		if (setsockopt(data, SOL_SOCKET, SO_REUSEADDR, (char *)&on,
   1194 				sizeof (on)) < 0) {
   1195 			warn("setsockopt (reuse address)");
   1196 			goto bad;
   1197 		}
   1198 	if (bind(data, (struct sockaddr *)&data_addr, sizeof (data_addr)) < 0) {
   1199 		warn("bind");
   1200 		goto bad;
   1201 	}
   1202 	if (options & SO_DEBUG &&
   1203 	    setsockopt(data, SOL_SOCKET, SO_DEBUG, (char *)&on,
   1204 			sizeof (on)) < 0)
   1205 		warn("setsockopt (ignored)");
   1206 	len = sizeof (data_addr);
   1207 	if (getsockname(data, (struct sockaddr *)&data_addr, &len) < 0) {
   1208 		warn("getsockname");
   1209 		goto bad;
   1210 	}
   1211 	if (listen(data, 1) < 0)
   1212 		warn("listen");
   1213 	if (sendport) {
   1214 		a = (char *)&data_addr.sin_addr;
   1215 		p = (char *)&data_addr.sin_port;
   1216 #define	UC(b)	(((int)b)&0xff)
   1217 		result =
   1218 		    command("PORT %d,%d,%d,%d,%d,%d",
   1219 		      UC(a[0]), UC(a[1]), UC(a[2]), UC(a[3]),
   1220 		      UC(p[0]), UC(p[1]));
   1221 		if (result == ERROR && sendport == -1) {
   1222 			sendport = 0;
   1223 			tmpno = 1;
   1224 			goto noport;
   1225 		}
   1226 		return (result != COMPLETE);
   1227 	}
   1228 	if (tmpno)
   1229 		sendport = 1;
   1230 #ifdef IP_TOS
   1231 	on = IPTOS_THROUGHPUT;
   1232 	if (setsockopt(data, IPPROTO_IP, IP_TOS, (char *)&on, sizeof(int)) < 0)
   1233 		warn("setsockopt TOS (ignored)");
   1234 #endif
   1235 	return (0);
   1236 bad:
   1237 	(void) close(data), data = -1;
   1238 	if (tmpno)
   1239 		sendport = 1;
   1240 	return (1);
   1241 }
   1242 
   1243 FILE *
   1244 dataconn(lmode)
   1245 	const char *lmode;
   1246 {
   1247 	struct sockaddr_in from;
   1248 	int s, fromlen = sizeof (from), tos;
   1249 
   1250 	if (passivemode)
   1251 		return (fdopen(data, lmode));
   1252 
   1253 	s = accept(data, (struct sockaddr *) &from, &fromlen);
   1254 	if (s < 0) {
   1255 		warn("accept");
   1256 		(void) close(data), data = -1;
   1257 		return (NULL);
   1258 	}
   1259 	(void) close(data);
   1260 	data = s;
   1261 #ifdef IP_TOS
   1262 	tos = IPTOS_THROUGHPUT;
   1263 	if (setsockopt(s, IPPROTO_IP, IP_TOS, (char *)&tos, sizeof(int)) < 0)
   1264 		warn("setsockopt TOS (ignored)");
   1265 #endif
   1266 	return (fdopen(data, lmode));
   1267 }
   1268 
   1269 /*
   1270  * Display a transfer progress bar if progress is non-zero.
   1271  * Initialise with flag < 0, run with flag = 0, and the
   1272  * finish with flag > 0.
   1273  */
   1274 void
   1275 progressmeter(flag)
   1276 	int flag;
   1277 {
   1278 	static struct timeval before;
   1279 	static int ttywidth;
   1280 	struct winsize winsize;
   1281 	struct timeval now, td;
   1282 	off_t cursize, abbrevsize;
   1283 	double elapsed;
   1284 	int ratio, barlength, i, remaining;
   1285 	char prefixes[] = " KMGTP";	/* `P' because 2^64 = 16384 Petabytes */
   1286 
   1287 	if (!progress || filesize < 0)
   1288 		return;
   1289 	if (flag < 0) {
   1290 		before.tv_sec = -1;
   1291 		if (ioctl(fileno(stdin), TIOCGWINSZ, &winsize) < 0)
   1292 			ttywidth = 80;
   1293 		else
   1294 			ttywidth = winsize.ws_col;
   1295 	} else if (flag == 0) {
   1296 		(void) gettimeofday(&now, (struct timezone *)0);
   1297 		if (now.tv_sec <= before.tv_sec)
   1298 			return;
   1299 	}
   1300 	before = now;
   1301 	cursize = bytes + restart_point;
   1302 
   1303 	ratio = cursize * 100 / filesize;
   1304 	ratio = MAX(ratio, 0);
   1305 	ratio = MIN(ratio, 100);
   1306 	printf("\r%3d%% 0 ", ratio);
   1307 
   1308 	barlength = ttywidth - 30;
   1309 	if (barlength > 0) {
   1310 		i = barlength * ratio / 100;
   1311 		printf("%.*s%*s", i,
   1312 "*****************************************************************************"
   1313 "*****************************************************************************",
   1314 		    barlength - i, "");
   1315 	}
   1316 
   1317 	i = 0;
   1318 	abbrevsize = cursize;
   1319 	while (abbrevsize >= 100000 && i < sizeof(prefixes)) {
   1320 		i++;
   1321 		abbrevsize >>= 10;
   1322 	}
   1323 	printf(" %5qd %c%c  ", abbrevsize, prefixes[i],
   1324 	    prefixes[i] == ' ' ? ' ' : 'B');
   1325 
   1326 	timersub(&now, &start, &td);
   1327 	elapsed = td.tv_sec + (td.tv_usec / 1000000.0);
   1328 	if (bytes <= 0 || elapsed <= 0.0) {
   1329 		printf("   --:--");
   1330 	} else {
   1331 		remaining = (int)((filesize - restart_point) /
   1332 				  (bytes / elapsed) - elapsed);
   1333 		i = remaining / 3600;
   1334 		if (i)
   1335 			printf("%2d:", i);
   1336 		else
   1337 			printf("   ");
   1338 		i = remaining % 3600;
   1339 		printf("%02d:%02d", i / 60, i % 60);
   1340 	}
   1341 	printf(" ETA");
   1342 
   1343 	if (flag > 0)
   1344 		(void) putchar('\n');
   1345 	fflush(stdout);
   1346 }
   1347 
   1348 void
   1349 ptransfer(siginfo)
   1350 	int siginfo;
   1351 {
   1352 	struct timeval now, td;
   1353 	double elapsed;
   1354 	off_t bs;
   1355 	int meg, remaining, hh;
   1356 	char buf[100];
   1357 
   1358 	if (!verbose && !siginfo)
   1359 		return;
   1360 
   1361 	(void) gettimeofday(&now, (struct timezone *)0);
   1362 	timersub(&now, &start, &td);
   1363 	elapsed = td.tv_sec + (td.tv_usec / 1000000.0);
   1364 	bs = bytes / (elapsed == 0.0 ? 1 : elapsed);
   1365 	meg = 0;
   1366 	if (bs > (1024 * 1024))
   1367 		meg = 1;
   1368 	(void)snprintf(buf, sizeof(buf),
   1369 	    "%qd byte%s %s in %.2f seconds (%.2f %sB/s)\n",
   1370 	    bytes, bytes == 1 ? "" : "s", direction, elapsed,
   1371 	    bs / (1024.0 * (meg ? 1024.0 : 1.0)), meg ? "M" : "K");
   1372 	if (siginfo && bytes > 0 && elapsed > 0.0) {
   1373 		remaining = (int)((filesize - restart_point) /
   1374 				  (bytes / elapsed) - elapsed);
   1375 		hh = remaining / 3600;
   1376 		remaining %= 3600;
   1377 		snprintf(buf + strlen(buf) - 1, sizeof(buf) - strlen(buf),
   1378 		    "  ETA: %02d:%02d:%02d\n", hh, remaining / 60,
   1379 		    remaining % 60);
   1380 	}
   1381 	(void)write(siginfo ? STDERR_FILENO : STDOUT_FILENO, buf, strlen(buf));
   1382 }
   1383 
   1384 void
   1385 psummary(notused)
   1386 	int notused;
   1387 {
   1388 
   1389 	if (bytes > 0)
   1390 		ptransfer(1);
   1391 }
   1392 
   1393 void
   1394 psabort()
   1395 {
   1396 
   1397 	abrtflag++;
   1398 }
   1399 
   1400 void
   1401 pswitch(flag)
   1402 	int flag;
   1403 {
   1404 	sig_t oldintr;
   1405 	static struct comvars {
   1406 		int connect;
   1407 		char name[MAXHOSTNAMELEN];
   1408 		struct sockaddr_in mctl;
   1409 		struct sockaddr_in hctl;
   1410 		FILE *in;
   1411 		FILE *out;
   1412 		int tpe;
   1413 		int curtpe;
   1414 		int cpnd;
   1415 		int sunqe;
   1416 		int runqe;
   1417 		int mcse;
   1418 		int ntflg;
   1419 		char nti[17];
   1420 		char nto[17];
   1421 		int mapflg;
   1422 		char mi[MAXPATHLEN];
   1423 		char mo[MAXPATHLEN];
   1424 	} proxstruct, tmpstruct;
   1425 	struct comvars *ip, *op;
   1426 
   1427 	abrtflag = 0;
   1428 	oldintr = signal(SIGINT, psabort);
   1429 	if (flag) {
   1430 		if (proxy)
   1431 			return;
   1432 		ip = &tmpstruct;
   1433 		op = &proxstruct;
   1434 		proxy++;
   1435 	} else {
   1436 		if (!proxy)
   1437 			return;
   1438 		ip = &proxstruct;
   1439 		op = &tmpstruct;
   1440 		proxy = 0;
   1441 	}
   1442 	ip->connect = connected;
   1443 	connected = op->connect;
   1444 	if (hostname) {
   1445 		(void) strncpy(ip->name, hostname, sizeof(ip->name) - 1);
   1446 		ip->name[strlen(ip->name)] = '\0';
   1447 	} else
   1448 		ip->name[0] = 0;
   1449 	hostname = op->name;
   1450 	ip->hctl = hisctladdr;
   1451 	hisctladdr = op->hctl;
   1452 	ip->mctl = myctladdr;
   1453 	myctladdr = op->mctl;
   1454 	ip->in = cin;
   1455 	cin = op->in;
   1456 	ip->out = cout;
   1457 	cout = op->out;
   1458 	ip->tpe = type;
   1459 	type = op->tpe;
   1460 	ip->curtpe = curtype;
   1461 	curtype = op->curtpe;
   1462 	ip->cpnd = cpend;
   1463 	cpend = op->cpnd;
   1464 	ip->sunqe = sunique;
   1465 	sunique = op->sunqe;
   1466 	ip->runqe = runique;
   1467 	runique = op->runqe;
   1468 	ip->mcse = mcase;
   1469 	mcase = op->mcse;
   1470 	ip->ntflg = ntflag;
   1471 	ntflag = op->ntflg;
   1472 	(void) strncpy(ip->nti, ntin, 16);
   1473 	(ip->nti)[strlen(ip->nti)] = '\0';
   1474 	(void) strcpy(ntin, op->nti);
   1475 	(void) strncpy(ip->nto, ntout, 16);
   1476 	(ip->nto)[strlen(ip->nto)] = '\0';
   1477 	(void) strcpy(ntout, op->nto);
   1478 	ip->mapflg = mapflag;
   1479 	mapflag = op->mapflg;
   1480 	(void) strncpy(ip->mi, mapin, MAXPATHLEN - 1);
   1481 	(ip->mi)[strlen(ip->mi)] = '\0';
   1482 	(void) strcpy(mapin, op->mi);
   1483 	(void) strncpy(ip->mo, mapout, MAXPATHLEN - 1);
   1484 	(ip->mo)[strlen(ip->mo)] = '\0';
   1485 	(void) strcpy(mapout, op->mo);
   1486 	(void) signal(SIGINT, oldintr);
   1487 	if (abrtflag) {
   1488 		abrtflag = 0;
   1489 		(*oldintr)(SIGINT);
   1490 	}
   1491 }
   1492 
   1493 void
   1494 abortpt()
   1495 {
   1496 
   1497 	printf("\n");
   1498 	(void) fflush(stdout);
   1499 	ptabflg++;
   1500 	mflag = 0;
   1501 	abrtflag = 0;
   1502 	longjmp(ptabort, 1);
   1503 }
   1504 
   1505 void
   1506 proxtrans(cmd, local, remote)
   1507 	const char *cmd, *local, *remote;
   1508 {
   1509 	sig_t oldintr;
   1510 	int secndflag = 0, prox_type, nfnd;
   1511 	char *cmd2;
   1512 	struct fd_set mask;
   1513 
   1514 	if (strcmp(cmd, "RETR"))
   1515 		cmd2 = "RETR";
   1516 	else
   1517 		cmd2 = runique ? "STOU" : "STOR";
   1518 	if ((prox_type = type) == 0) {
   1519 		if (unix_server && unix_proxy)
   1520 			prox_type = TYPE_I;
   1521 		else
   1522 			prox_type = TYPE_A;
   1523 	}
   1524 	if (curtype != prox_type)
   1525 		changetype(prox_type, 1);
   1526 	if (command("PASV") != COMPLETE) {
   1527 		printf("proxy server does not support third party "
   1528 		    "transfers.\n");
   1529 		return;
   1530 	}
   1531 	pswitch(0);
   1532 	if (!connected) {
   1533 		printf("No primary connection\n");
   1534 		pswitch(1);
   1535 		code = -1;
   1536 		return;
   1537 	}
   1538 	if (curtype != prox_type)
   1539 		changetype(prox_type, 1);
   1540 	if (command("PORT %s", pasv) != COMPLETE) {
   1541 		pswitch(1);
   1542 		return;
   1543 	}
   1544 	if (setjmp(ptabort))
   1545 		goto abort;
   1546 	oldintr = signal(SIGINT, abortpt);
   1547 	if (command("%s %s", cmd, remote) != PRELIM) {
   1548 		(void) signal(SIGINT, oldintr);
   1549 		pswitch(1);
   1550 		return;
   1551 	}
   1552 	sleep(2);
   1553 	pswitch(1);
   1554 	secndflag++;
   1555 	if (command("%s %s", cmd2, local) != PRELIM)
   1556 		goto abort;
   1557 	ptflag++;
   1558 	(void) getreply(0);
   1559 	pswitch(0);
   1560 	(void) getreply(0);
   1561 	(void) signal(SIGINT, oldintr);
   1562 	pswitch(1);
   1563 	ptflag = 0;
   1564 	printf("local: %s remote: %s\n", local, remote);
   1565 	return;
   1566 abort:
   1567 	(void) signal(SIGINT, SIG_IGN);
   1568 	ptflag = 0;
   1569 	if (strcmp(cmd, "RETR") && !proxy)
   1570 		pswitch(1);
   1571 	else if (!strcmp(cmd, "RETR") && proxy)
   1572 		pswitch(0);
   1573 	if (!cpend && !secndflag) {  /* only here if cmd = "STOR" (proxy=1) */
   1574 		if (command("%s %s", cmd2, local) != PRELIM) {
   1575 			pswitch(0);
   1576 			if (cpend)
   1577 				abort_remote((FILE *) NULL);
   1578 		}
   1579 		pswitch(1);
   1580 		if (ptabflg)
   1581 			code = -1;
   1582 		(void) signal(SIGINT, oldintr);
   1583 		return;
   1584 	}
   1585 	if (cpend)
   1586 		abort_remote((FILE *) NULL);
   1587 	pswitch(!proxy);
   1588 	if (!cpend && !secndflag) {  /* only if cmd = "RETR" (proxy=1) */
   1589 		if (command("%s %s", cmd2, local) != PRELIM) {
   1590 			pswitch(0);
   1591 			if (cpend)
   1592 				abort_remote((FILE *) NULL);
   1593 			pswitch(1);
   1594 			if (ptabflg)
   1595 				code = -1;
   1596 			(void) signal(SIGINT, oldintr);
   1597 			return;
   1598 		}
   1599 	}
   1600 	if (cpend)
   1601 		abort_remote((FILE *) NULL);
   1602 	pswitch(!proxy);
   1603 	if (cpend) {
   1604 		FD_ZERO(&mask);
   1605 		FD_SET(fileno(cin), &mask);
   1606 		if ((nfnd = empty(&mask, 10)) <= 0) {
   1607 			if (nfnd < 0) {
   1608 				warn("abort");
   1609 			}
   1610 			if (ptabflg)
   1611 				code = -1;
   1612 			lostpeer();
   1613 		}
   1614 		(void) getreply(0);
   1615 		(void) getreply(0);
   1616 	}
   1617 	if (proxy)
   1618 		pswitch(0);
   1619 	pswitch(1);
   1620 	if (ptabflg)
   1621 		code = -1;
   1622 	(void) signal(SIGINT, oldintr);
   1623 }
   1624 
   1625 void
   1626 reset(argc, argv)
   1627 	int argc;
   1628 	char *argv[];
   1629 {
   1630 	struct fd_set mask;
   1631 	int nfnd = 1;
   1632 
   1633 	FD_ZERO(&mask);
   1634 	while (nfnd > 0) {
   1635 		FD_SET(fileno(cin), &mask);
   1636 		if ((nfnd = empty(&mask, 0)) < 0) {
   1637 			warn("reset");
   1638 			code = -1;
   1639 			lostpeer();
   1640 		}
   1641 		else if (nfnd) {
   1642 			(void) getreply(0);
   1643 		}
   1644 	}
   1645 }
   1646 
   1647 char *
   1648 gunique(local)
   1649 	const char *local;
   1650 {
   1651 	static char new[MAXPATHLEN];
   1652 	char *cp = strrchr(local, '/');
   1653 	int d, count=0;
   1654 	char ext = '1';
   1655 
   1656 	if (cp)
   1657 		*cp = '\0';
   1658 	d = access(cp == local ? "/" : cp ? local : ".", 2);
   1659 	if (cp)
   1660 		*cp = '/';
   1661 	if (d < 0) {
   1662 		warn("local: %s", local);
   1663 		return ((char *) 0);
   1664 	}
   1665 	(void) strcpy(new, local);
   1666 	cp = new + strlen(new);
   1667 	*cp++ = '.';
   1668 	while (!d) {
   1669 		if (++count == 100) {
   1670 			printf("runique: can't find unique file name.\n");
   1671 			return ((char *) 0);
   1672 		}
   1673 		*cp++ = ext;
   1674 		*cp = '\0';
   1675 		if (ext == '9')
   1676 			ext = '0';
   1677 		else
   1678 			ext++;
   1679 		if ((d = access(new, 0)) < 0)
   1680 			break;
   1681 		if (ext != '0')
   1682 			cp--;
   1683 		else if (*(cp - 2) == '.')
   1684 			*(cp - 1) = '1';
   1685 		else {
   1686 			*(cp - 2) = *(cp - 2) + 1;
   1687 			cp--;
   1688 		}
   1689 	}
   1690 	return (new);
   1691 }
   1692 
   1693 void
   1694 abort_remote(din)
   1695 	FILE *din;
   1696 {
   1697 	char buf[BUFSIZ];
   1698 	int nfnd;
   1699 	struct fd_set mask;
   1700 
   1701 	/*
   1702 	 * send IAC in urgent mode instead of DM because 4.3BSD places oob mark
   1703 	 * after urgent byte rather than before as is protocol now
   1704 	 */
   1705 	sprintf(buf, "%c%c%c", IAC, IP, IAC);
   1706 	if (send(fileno(cout), buf, 3, MSG_OOB) != 3)
   1707 		warn("abort");
   1708 	fprintf(cout, "%cABOR\r\n", DM);
   1709 	(void) fflush(cout);
   1710 	FD_ZERO(&mask);
   1711 	FD_SET(fileno(cin), &mask);
   1712 	if (din) {
   1713 		FD_SET(fileno(din), &mask);
   1714 	}
   1715 	if ((nfnd = empty(&mask, 10)) <= 0) {
   1716 		if (nfnd < 0) {
   1717 			warn("abort");
   1718 		}
   1719 		if (ptabflg)
   1720 			code = -1;
   1721 		lostpeer();
   1722 	}
   1723 	if (din && FD_ISSET(fileno(din), &mask)) {
   1724 		while (read(fileno(din), buf, BUFSIZ) > 0)
   1725 			/* LOOP */;
   1726 	}
   1727 	if (getreply(0) == ERROR && code == 552) {
   1728 		/* 552 needed for nic style abort */
   1729 		(void) getreply(0);
   1730 	}
   1731 	(void) getreply(0);
   1732 }
   1733