Home | History | Annotate | Line # | Download | only in ftp
util.c revision 1.26
      1 /*	$NetBSD: util.c,v 1.26 1998/07/06 06:50:49 mrg 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 #include <sys/cdefs.h>
     37 #ifndef lint
     38 __RCSID("$NetBSD: util.c,v 1.26 1998/07/06 06:50:49 mrg Exp $");
     39 #endif /* not lint */
     40 
     41 /*
     42  * FTP User Program -- Misc support routines
     43  */
     44 #include <sys/ioctl.h>
     45 #include <sys/time.h>
     46 #include <arpa/ftp.h>
     47 
     48 #include <ctype.h>
     49 #include <err.h>
     50 #include <fcntl.h>
     51 #include <glob.h>
     52 #include <termios.h>
     53 #include <signal.h>
     54 #include <limits.h>
     55 #include <pwd.h>
     56 #include <stdio.h>
     57 #include <stdlib.h>
     58 #include <string.h>
     59 #include <time.h>
     60 #include <tzfile.h>
     61 #include <unistd.h>
     62 
     63 #include "ftp_var.h"
     64 #include "pathnames.h"
     65 
     66 /*
     67  * Connect to peer server and
     68  * auto-login, if possible.
     69  */
     70 void
     71 setpeer(argc, argv)
     72 	int argc;
     73 	char *argv[];
     74 {
     75 	char *host;
     76 	in_port_t port;
     77 
     78 	if (connected) {
     79 		fprintf(ttyout, "Already connected to %s, use close first.\n",
     80 		    hostname);
     81 		code = -1;
     82 		return;
     83 	}
     84 	if (argc < 2)
     85 		(void)another(&argc, &argv, "to");
     86 	if (argc < 2 || argc > 3) {
     87 		fprintf(ttyout, "usage: %s host-name [port]\n", argv[0]);
     88 		code = -1;
     89 		return;
     90 	}
     91 	if (gatemode)
     92 		port = gateport;
     93 	else
     94 		port = ftpport;
     95 	if (argc > 2) {
     96 		char *ep;
     97 		long nport;
     98 
     99 		nport = strtol(argv[2], &ep, 10);
    100 		if (nport < 1 || nport > MAX_IN_PORT_T || *ep != '\0') {
    101 			fprintf(ttyout, "%s: bad port number '%s'.\n",
    102 			    argv[1], argv[2]);
    103 			fprintf(ttyout, "usage: %s host-name [port]\n",
    104 			    argv[0]);
    105 			code = -1;
    106 			return;
    107 		}
    108 		port = htons((in_port_t)nport);
    109 	}
    110 
    111 	if (gatemode) {
    112 		if (gateserver == NULL || *gateserver == '\0')
    113 			errx(1, "gateserver not defined (shouldn't happen)");
    114 		host = hookup(gateserver, port);
    115 	} else
    116 		host = hookup(argv[1], port);
    117 
    118 	if (host) {
    119 		int overbose;
    120 
    121 		if (gatemode) {
    122 			if (command("PASSERVE %s", argv[1]) != COMPLETE)
    123 				return;
    124 			if (verbose)
    125 				fprintf(ttyout,
    126 				    "Connected via pass-through server %s\n",
    127 				    gateserver);
    128 		}
    129 
    130 		connected = 1;
    131 		/*
    132 		 * Set up defaults for FTP.
    133 		 */
    134 		(void)strcpy(typename, "ascii"), type = TYPE_A;
    135 		curtype = TYPE_A;
    136 		(void)strcpy(formname, "non-print"), form = FORM_N;
    137 		(void)strcpy(modename, "stream"), mode = MODE_S;
    138 		(void)strcpy(structname, "file"), stru = STRU_F;
    139 		(void)strcpy(bytename, "8"), bytesize = 8;
    140 		if (autologin)
    141 			(void)login(argv[1], NULL, NULL);
    142 
    143 		overbose = verbose;
    144 		if (debug == 0)
    145 			verbose = -1;
    146 		if (command("SYST") == COMPLETE && overbose) {
    147 			char *cp, c;
    148 			c = 0;
    149 			cp = strchr(reply_string + 4, ' ');
    150 			if (cp == NULL)
    151 				cp = strchr(reply_string + 4, '\r');
    152 			if (cp) {
    153 				if (cp[-1] == '.')
    154 					cp--;
    155 				c = *cp;
    156 				*cp = '\0';
    157 			}
    158 
    159 			fprintf(ttyout, "Remote system type is %s.\n",
    160 			    reply_string + 4);
    161 			if (cp)
    162 				*cp = c;
    163 		}
    164 		if (!strncmp(reply_string, "215 UNIX Type: L8", 17)) {
    165 			if (proxy)
    166 				unix_proxy = 1;
    167 			else
    168 				unix_server = 1;
    169 			/*
    170 			 * Set type to 0 (not specified by user),
    171 			 * meaning binary by default, but don't bother
    172 			 * telling server.  We can use binary
    173 			 * for text files unless changed by the user.
    174 			 */
    175 			type = 0;
    176 			(void)strcpy(typename, "binary");
    177 			if (overbose)
    178 			    fprintf(ttyout,
    179 				"Using %s mode to transfer files.\n",
    180 				typename);
    181 		} else {
    182 			if (proxy)
    183 				unix_proxy = 0;
    184 			else
    185 				unix_server = 0;
    186 			if (overbose &&
    187 			    !strncmp(reply_string, "215 TOPS20", 10))
    188 				fputs(
    189 "Remember to set tenex mode when transferring binary files from this machine.\n",
    190 				    ttyout);
    191 		}
    192 		verbose = overbose;
    193 	}
    194 }
    195 
    196 /*
    197  * login to remote host, using given username & password if supplied
    198  */
    199 int
    200 login(host, user, pass)
    201 	const char *host;
    202 	char *user, *pass;
    203 {
    204 	char tmp[80];
    205 	char *acct;
    206 	char anonpass[MAXLOGNAME + 1 + MAXHOSTNAMELEN + 1]; /* user@hostname */
    207 	char hostname[MAXHOSTNAMELEN + 1];
    208 	struct passwd *pw;
    209 	int n, aflag = 0;
    210 
    211 	acct = NULL;
    212 	if (user == NULL) {
    213 		if (ruserpass(host, &user, &pass, &acct) < 0) {
    214 			code = -1;
    215 			return (0);
    216 		}
    217 	}
    218 
    219 	/*
    220 	 * Set up arguments for an anonymous FTP session, if necessary.
    221 	 */
    222 	if ((user == NULL || pass == NULL) && anonftp) {
    223 		memset(anonpass, 0, sizeof(anonpass));
    224 		memset(hostname, 0, sizeof(hostname));
    225 
    226 		/*
    227 		 * Set up anonymous login password.
    228 		 */
    229 		if ((user = getlogin()) == NULL) {
    230 			if ((pw = getpwuid(getuid())) == NULL)
    231 				user = "anonymous";
    232 			else
    233 				user = pw->pw_name;
    234 		}
    235 		gethostname(hostname, MAXHOSTNAMELEN);
    236 		hostname[sizeof(hostname) - 1] = '\0';
    237 #ifndef DONT_CHEAT_ANONPASS
    238 		/*
    239 		 * Every anonymous FTP server I've encountered
    240 		 * will accept the string "username@", and will
    241 		 * append the hostname itself.  We do this by default
    242 		 * since many servers are picky about not having
    243 		 * a FQDN in the anonymous password. - thorpej (at) netbsd.org
    244 		 */
    245 		snprintf(anonpass, sizeof(anonpass) - 1, "%s@",
    246 		    user);
    247 #else
    248 		snprintf(anonpass, sizeof(anonpass) - 1, "%s@%s",
    249 		    user, hp->h_name);
    250 #endif
    251 		pass = anonpass;
    252 		user = "anonymous";	/* as per RFC 1635 */
    253 	}
    254 
    255 	while (user == NULL) {
    256 		char *myname = getlogin();
    257 
    258 		if (myname == NULL && (pw = getpwuid(getuid())) != NULL)
    259 			myname = pw->pw_name;
    260 		if (myname)
    261 			fprintf(ttyout, "Name (%s:%s): ", host, myname);
    262 		else
    263 			fprintf(ttyout, "Name (%s): ", host);
    264 		*tmp = '\0';
    265 		(void)fgets(tmp, sizeof(tmp) - 1, stdin);
    266 		tmp[strlen(tmp) - 1] = '\0';
    267 		if (*tmp == '\0')
    268 			user = myname;
    269 		else
    270 			user = tmp;
    271 	}
    272 	n = command("USER %s", user);
    273 	if (n == CONTINUE) {
    274 		if (pass == NULL)
    275 			pass = getpass("Password:");
    276 		n = command("PASS %s", pass);
    277 	}
    278 	if (n == CONTINUE) {
    279 		aflag++;
    280 		if (acct == NULL)
    281 			acct = getpass("Account:");
    282 		n = command("ACCT %s", acct);
    283 	}
    284 	if ((n != COMPLETE) ||
    285 	    (!aflag && acct != NULL && command("ACCT %s", acct) != COMPLETE)) {
    286 		warnx("Login failed.");
    287 		return (0);
    288 	}
    289 	if (proxy)
    290 		return (1);
    291 	connected = -1;
    292 	for (n = 0; n < macnum; ++n) {
    293 		if (!strcmp("init", macros[n].mac_name)) {
    294 			(void)strcpy(line, "$init");
    295 			makeargv();
    296 			domacro(margc, margv);
    297 			break;
    298 		}
    299 	}
    300 	return (1);
    301 }
    302 
    303 /*
    304  * `another' gets another argument, and stores the new argc and argv.
    305  * It reverts to the top level (via main.c's intr()) on EOF/error.
    306  *
    307  * Returns false if no new arguments have been added.
    308  */
    309 int
    310 another(pargc, pargv, prompt)
    311 	int *pargc;
    312 	char ***pargv;
    313 	const char *prompt;
    314 {
    315 	int len = strlen(line), ret;
    316 
    317 	if (len >= sizeof(line) - 3) {
    318 		fputs("sorry, arguments too long.\n", ttyout);
    319 		intr();
    320 	}
    321 	fprintf(ttyout, "(%s) ", prompt);
    322 	line[len++] = ' ';
    323 	if (fgets(&line[len], sizeof(line) - len, stdin) == NULL)
    324 		intr();
    325 	len += strlen(&line[len]);
    326 	if (len > 0 && line[len - 1] == '\n')
    327 		line[len - 1] = '\0';
    328 	makeargv();
    329 	ret = margc > *pargc;
    330 	*pargc = margc;
    331 	*pargv = margv;
    332 	return (ret);
    333 }
    334 
    335 /*
    336  * glob files given in argv[] from the remote server.
    337  * if errbuf isn't NULL, store error messages there instead
    338  * of writing to the screen.
    339  */
    340 char *
    341 remglob(argv, doswitch, errbuf)
    342         char *argv[];
    343         int doswitch;
    344 	char **errbuf;
    345 {
    346         char temp[MAXPATHLEN];
    347         static char buf[MAXPATHLEN];
    348         static FILE *ftemp = NULL;
    349         static char **args;
    350         int oldverbose, oldhash, fd;
    351         char *cp, *mode;
    352 
    353         if (!mflag) {
    354                 if (!doglob)
    355                         args = NULL;
    356                 else {
    357                         if (ftemp) {
    358                                 (void)fclose(ftemp);
    359                                 ftemp = NULL;
    360                         }
    361                 }
    362                 return (NULL);
    363         }
    364         if (!doglob) {
    365                 if (args == NULL)
    366                         args = argv;
    367                 if ((cp = *++args) == NULL)
    368                         args = NULL;
    369                 return (cp);
    370         }
    371         if (ftemp == NULL) {
    372                 (void)snprintf(temp, sizeof(temp), "%s/%s", tmpdir, TMPFILE);
    373                 if ((fd = mkstemp(temp)) < 0) {
    374                         warn("unable to create temporary file %s", temp);
    375                         return (NULL);
    376                 }
    377                 close(fd);
    378                 oldverbose = verbose;
    379 		verbose = (errbuf != NULL) ? -1 : 0;
    380                 oldhash = hash;
    381                 hash = 0;
    382                 if (doswitch)
    383                         pswitch(!proxy);
    384                 for (mode = "w"; *++argv != NULL; mode = "a")
    385                         recvrequest("NLST", temp, *argv, mode, 0, 0);
    386 		if ((code / 100) != COMPLETE) {
    387 			if (errbuf != NULL)
    388 				*errbuf = reply_string;
    389 		}
    390                 if (doswitch)
    391                         pswitch(!proxy);
    392                 verbose = oldverbose;
    393 		hash = oldhash;
    394                 ftemp = fopen(temp, "r");
    395                 (void)unlink(temp);
    396                 if (ftemp == NULL) {
    397 			if (errbuf == NULL)
    398 				fputs(
    399 				    "can't find list of remote files, oops.\n",
    400 				    ttyout);
    401 			else
    402 				*errbuf =
    403 				    "can't find list of remote files, oops.";
    404                         return (NULL);
    405                 }
    406         }
    407         if (fgets(buf, sizeof(buf), ftemp) == NULL) {
    408                 (void)fclose(ftemp);
    409 		ftemp = NULL;
    410                 return (NULL);
    411         }
    412         if ((cp = strchr(buf, '\n')) != NULL)
    413                 *cp = '\0';
    414         return (buf);
    415 }
    416 
    417 int
    418 confirm(cmd, file)
    419 	const char *cmd, *file;
    420 {
    421 	char line[BUFSIZ];
    422 
    423 	if (!interactive || confirmrest)
    424 		return (1);
    425 	fprintf(ttyout, "%s %s? ", cmd, file);
    426 	(void)fflush(ttyout);
    427 	if (fgets(line, sizeof(line), stdin) == NULL)
    428 		return (0);
    429 	switch (tolower(*line)) {
    430 		case 'n':
    431 			return (0);
    432 		case 'p':
    433 			interactive = 0;
    434 			fputs("Interactive mode: off.\n", ttyout);
    435 			break;
    436 		case 'a':
    437 			confirmrest = 1;
    438 			fprintf(ttyout, "Prompting off for duration of %s.\n",
    439 			    cmd);
    440 			break;
    441 	}
    442 	return (1);
    443 }
    444 
    445 /*
    446  * Glob a local file name specification with
    447  * the expectation of a single return value.
    448  * Can't control multiple values being expanded
    449  * from the expression, we return only the first.
    450  */
    451 int
    452 globulize(cpp)
    453 	char **cpp;
    454 {
    455 	glob_t gl;
    456 	int flags;
    457 
    458 	if (!doglob)
    459 		return (1);
    460 
    461 	flags = GLOB_BRACE|GLOB_NOCHECK|GLOB_TILDE;
    462 	memset(&gl, 0, sizeof(gl));
    463 	if (glob(*cpp, flags, NULL, &gl) ||
    464 	    gl.gl_pathc == 0) {
    465 		warnx("%s: not found", *cpp);
    466 		globfree(&gl);
    467 		return (0);
    468 	}
    469 		/* XXX: caller should check if *cpp changed, and
    470 		 *	free(*cpp) if that is the case
    471 		 */
    472 	*cpp = strdup(gl.gl_pathv[0]);
    473 	globfree(&gl);
    474 	return (1);
    475 }
    476 
    477 /*
    478  * determine size of remote file
    479  */
    480 off_t
    481 remotesize(file, noisy)
    482 	const char *file;
    483 	int noisy;
    484 {
    485 	int overbose;
    486 	off_t size;
    487 
    488 	overbose = verbose;
    489 	size = -1;
    490 	if (debug == 0)
    491 		verbose = -1;
    492 	if (command("SIZE %s", file) == COMPLETE) {
    493 		char *cp, *ep;
    494 
    495 		cp = strchr(reply_string, ' ');
    496 		if (cp != NULL) {
    497 			cp++;
    498 #ifdef NO_QUAD
    499 			size = strtol(cp, &ep, 10);
    500 #else
    501 			size = strtoq(cp, &ep, 10);
    502 #endif
    503 			if (*ep != '\0' && !isspace((unsigned char)*ep))
    504 				size = -1;
    505 		}
    506 	} else if (noisy && debug == 0) {
    507 		fputs(reply_string, ttyout);
    508 		putc('\n', ttyout);
    509 	}
    510 	verbose = overbose;
    511 	return (size);
    512 }
    513 
    514 /*
    515  * determine last modification time (in GMT) of remote file
    516  */
    517 time_t
    518 remotemodtime(file, noisy)
    519 	const char *file;
    520 	int noisy;
    521 {
    522 	int overbose;
    523 	time_t rtime;
    524 	int ocode;
    525 
    526 	overbose = verbose;
    527 	ocode = code;
    528 	rtime = -1;
    529 	if (debug == 0)
    530 		verbose = -1;
    531 	if (command("MDTM %s", file) == COMPLETE) {
    532 		struct tm timebuf;
    533 		int yy, mo, day, hour, min, sec;
    534 		sscanf(reply_string, "%*s %04d%02d%02d%02d%02d%02d", &yy, &mo,
    535 			&day, &hour, &min, &sec);
    536 		memset(&timebuf, 0, sizeof(timebuf));
    537 		timebuf.tm_sec = sec;
    538 		timebuf.tm_min = min;
    539 		timebuf.tm_hour = hour;
    540 		timebuf.tm_mday = day;
    541 		timebuf.tm_mon = mo - 1;
    542 		timebuf.tm_year = yy - TM_YEAR_BASE;
    543 		timebuf.tm_isdst = -1;
    544 		rtime = mktime(&timebuf);
    545 		if (rtime == -1 && (noisy || debug != 0))
    546 			fprintf(ttyout, "Can't convert %s to a time.\n",
    547 			    reply_string);
    548 		else
    549 #ifndef __SVR4
    550 			rtime += timebuf.tm_gmtoff;	/* conv. local -> GMT */
    551 #else
    552 			rtime -= timezone;
    553 #endif
    554 	} else if (noisy && debug == 0) {
    555 		fputs(reply_string, ttyout);
    556 		putc('\n', ttyout);
    557 	}
    558 	verbose = overbose;
    559 	if (rtime == -1)
    560 		code = ocode;
    561 	return (rtime);
    562 }
    563 
    564 #ifndef	SMALL
    565 
    566 /*
    567  * return non-zero if we're the current foreground process
    568  */
    569 int
    570 foregroundproc()
    571 {
    572 	static pid_t pgrp = -1;
    573 	int ctty_pgrp;
    574 
    575 	if (pgrp == -1)
    576 		pgrp = getpgrp();
    577 
    578 	return ((ioctl(fileno(ttyout), TIOCGPGRP, &ctty_pgrp) != -1 &&
    579 	    ctty_pgrp == (int)pgrp));
    580 }
    581 
    582 
    583 static void updateprogressmeter __P((int));
    584 
    585 static void
    586 updateprogressmeter(dummy)
    587 	int dummy;
    588 {
    589 
    590 	/*
    591 	 * print progress bar only if we are foreground process.
    592 	 */
    593 	if (foregroundproc())
    594 		progressmeter(0);
    595 }
    596 #endif	/* SMALL */
    597 
    598 /*
    599  * Display a transfer progress bar if progress is non-zero.
    600  * SIGALRM is hijacked for use by this function.
    601  * - Before the transfer, set filesize to size of file (or -1 if unknown),
    602  *   and call with flag = -1. This starts the once per second timer,
    603  *   and a call to updateprogressmeter() upon SIGALRM.
    604  * - During the transfer, updateprogressmeter will call progressmeter
    605  *   with flag = 0
    606  * - After the transfer, call with flag = 1
    607  */
    608 static struct timeval start;
    609 static struct timeval lastupdate;
    610 
    611 void
    612 progressmeter(flag)
    613 	int flag;
    614 {
    615 #ifndef	SMALL
    616 	/*
    617 	 * List of order of magnitude prefixes.
    618 	 * The last is `P', as 2^64 = 16384 Petabytes
    619 	 */
    620 	static const char prefixes[] = " KMGTP";
    621 
    622 	static off_t lastsize;
    623 	struct timeval now, td, wait;
    624 	off_t cursize, abbrevsize;
    625 	double elapsed;
    626 	int ratio, barlength, i, len, remaining;
    627 	char buf[256];
    628 
    629 	len = 0;
    630 
    631 	if (flag == -1) {
    632 		(void)gettimeofday(&start, NULL);
    633 		lastupdate = start;
    634 		lastsize = restart_point;
    635 	}
    636 	(void)gettimeofday(&now, NULL);
    637 	if (!progress || filesize <= 0)
    638 		return;
    639 	cursize = bytes + restart_point;
    640 
    641 	ratio = cursize * 100 / filesize;
    642 	ratio = MAX(ratio, 0);
    643 	ratio = MIN(ratio, 100);
    644 	len += snprintf(buf + len, sizeof(buf) - len, "\r%3d%% ", ratio);
    645 
    646 	barlength = ttywidth - 30;
    647 	if (barlength > 0) {
    648 		i = barlength * ratio / 100;
    649 		len += snprintf(buf + len, sizeof(buf) - len,
    650 		    "|%.*s%*s|", i,
    651 "*****************************************************************************"
    652 "*****************************************************************************",
    653 		    barlength - i, "");
    654 	}
    655 
    656 	i = 0;
    657 	abbrevsize = cursize;
    658 	while (abbrevsize >= 100000 && i < sizeof(prefixes)) {
    659 		i++;
    660 		abbrevsize >>= 10;
    661 	}
    662 	len += snprintf(buf + len, sizeof(buf) - len,
    663 	    " %5qd %c%c ", (long long)abbrevsize, prefixes[i],
    664 	    prefixes[i] == ' ' ? ' ' : 'B');
    665 
    666 	timersub(&now, &lastupdate, &wait);
    667 	if (cursize > lastsize) {
    668 		lastupdate = now;
    669 		lastsize = cursize;
    670 		if (wait.tv_sec >= STALLTIME) {	/* fudge out stalled time */
    671 			start.tv_sec += wait.tv_sec;
    672 			start.tv_usec += wait.tv_usec;
    673 		}
    674 		wait.tv_sec = 0;
    675 	}
    676 
    677 	timersub(&now, &start, &td);
    678 	elapsed = td.tv_sec + (td.tv_usec / 1000000.0);
    679 
    680 	if (bytes <= 0 || elapsed <= 0.0 || cursize > filesize) {
    681 		len += snprintf(buf + len, sizeof(buf) - len,
    682 		    "   --:-- ETA");
    683 	} else if (wait.tv_sec >= STALLTIME) {
    684 		len += snprintf(buf + len, sizeof(buf) - len,
    685 		    " - stalled -");
    686 	} else {
    687 		remaining = (int)
    688 		    ((filesize - restart_point) / (bytes / elapsed) - elapsed);
    689 		if (remaining >= 100 * SECSPERHOUR)
    690 			len += snprintf(buf + len, sizeof(buf) - len,
    691 			    "   --:-- ETA");
    692 		else {
    693 			i = remaining / SECSPERHOUR;
    694 			if (i)
    695 				len += snprintf(buf + len, sizeof(buf) - len,
    696 				    "%2d:", i);
    697 			else
    698 				len += snprintf(buf + len, sizeof(buf) - len,
    699 				    "   ");
    700 			i = remaining % SECSPERHOUR;
    701 			len += snprintf(buf + len, sizeof(buf) - len,
    702 			    "%02d:%02d ETA", i / 60, i % 60);
    703 		}
    704 	}
    705 	(void)write(fileno(ttyout), buf, len);
    706 
    707 	if (flag == -1) {
    708 		(void)signal(SIGALRM, updateprogressmeter);
    709 		alarmtimer(1);		/* set alarm timer for 1 Hz */
    710 	} else if (flag == 1) {
    711 		alarmtimer(0);
    712 		(void)putc('\n', ttyout);
    713 	}
    714 	fflush(ttyout);
    715 #endif	/* SMALL */
    716 }
    717 
    718 /*
    719  * Display transfer statistics.
    720  * Requires start to be initialised by progressmeter(-1),
    721  * direction to be defined by xfer routines, and filesize and bytes
    722  * to be updated by xfer routines
    723  * If siginfo is nonzero, an ETA is displayed, and the output goes to stderr
    724  * instead of ttyout.
    725  */
    726 void
    727 ptransfer(siginfo)
    728 	int siginfo;
    729 {
    730 #ifndef	SMALL
    731 	struct timeval now, td, wait;
    732 	double elapsed;
    733 	off_t bs;
    734 	int meg, remaining, hh, len;
    735 	char buf[100];
    736 
    737 	if (!verbose && !siginfo)
    738 		return;
    739 
    740 	(void)gettimeofday(&now, NULL);
    741 	timersub(&now, &start, &td);
    742 	elapsed = td.tv_sec + (td.tv_usec / 1000000.0);
    743 	bs = bytes / (elapsed == 0.0 ? 1 : elapsed);
    744 	meg = 0;
    745 	if (bs > (1024 * 1024))
    746 		meg = 1;
    747 	len = 0;
    748 	len += snprintf(buf + len, sizeof(buf) - len,
    749 #ifndef NO_QUAD
    750 	    "%qd byte%s %s in ", (long long)bytes,
    751 #else
    752 	    "%ld byte%s %s in ", (long)bytes,
    753 #endif
    754 	    bytes == 1 ? "" : "s", direction);
    755 	remaining = (int)elapsed;
    756 	if (remaining > SECSPERDAY) {
    757 		int days;
    758 
    759 		days = remaining / SECSPERDAY;
    760 		remaining %= SECSPERDAY;
    761 		len += snprintf(buf + len, sizeof(buf) - len,
    762 		    "%d day%s ", days, days == 1 ? "" : "s");
    763 	}
    764 	hh = remaining / SECSPERHOUR;
    765 	remaining %= SECSPERHOUR;
    766 	if (hh)
    767 		len += snprintf(buf + len, sizeof(buf) - len, "%2d:", hh);
    768 	len += snprintf(buf + len, sizeof(buf) - len,
    769 	    "%02d:%02d (%.2f %sB/s)", remaining / 60, remaining % 60,
    770 	    bs / (1024.0 * (meg ? 1024.0 : 1.0)),
    771 	    meg ? "M" : "K");
    772 
    773 	if (siginfo && bytes > 0 && elapsed > 0.0 && filesize >= 0
    774 	    && bytes + restart_point <= filesize) {
    775 		remaining = (int)((filesize - restart_point) /
    776 				  (bytes / elapsed) - elapsed);
    777 		hh = remaining / SECSPERHOUR;
    778 		remaining %= SECSPERHOUR;
    779 		len += snprintf(buf + len, sizeof(buf) - len, "  ETA: ");
    780 		if (hh)
    781 			len += snprintf(buf + len, sizeof(buf) - len, "%2d:",
    782 			    hh);
    783 		len += snprintf(buf + len, sizeof(buf) - len,
    784 		    "%02d:%02d", remaining / 60, remaining % 60);
    785 		timersub(&now, &lastupdate, &wait);
    786 		if (wait.tv_sec >= STALLTIME)
    787 			len += snprintf(buf + len, sizeof(buf) - len,
    788 			    "  (stalled)");
    789 	}
    790 	len += snprintf(buf + len, sizeof(buf) - len, "\n");
    791 	(void)write(siginfo ? STDERR_FILENO : fileno(ttyout), buf, len);
    792 #endif	/* SMALL */
    793 }
    794 
    795 /*
    796  * List words in stringlist, vertically arranged
    797  */
    798 void
    799 list_vertical(sl)
    800 	StringList *sl;
    801 {
    802 	int i, j, w;
    803 	int columns, width, lines, items;
    804 	char *p;
    805 
    806 	width = items = 0;
    807 
    808 	for (i = 0 ; i < sl->sl_cur ; i++) {
    809 		w = strlen(sl->sl_str[i]);
    810 		if (w > width)
    811 			width = w;
    812 	}
    813 	width = (width + 8) &~ 7;
    814 
    815 	columns = ttywidth / width;
    816 	if (columns == 0)
    817 		columns = 1;
    818 	lines = (sl->sl_cur + columns - 1) / columns;
    819 	for (i = 0; i < lines; i++) {
    820 		for (j = 0; j < columns; j++) {
    821 			p = sl->sl_str[j * lines + i];
    822 			if (p)
    823 				fputs(p, ttyout);
    824 			if (j * lines + i + lines >= sl->sl_cur) {
    825 				putc('\n', ttyout);
    826 				break;
    827 			}
    828 			w = strlen(p);
    829 			while (w < width) {
    830 				w = (w + 8) &~ 7;
    831 				(void)putc('\t', ttyout);
    832 			}
    833 		}
    834 	}
    835 }
    836 
    837 /*
    838  * Update the global ttywidth value, using TIOCGWINSZ.
    839  */
    840 void
    841 setttywidth(a)
    842 	int a;
    843 {
    844 	struct winsize winsize;
    845 
    846 	if (ioctl(fileno(ttyout), TIOCGWINSZ, &winsize) != -1)
    847 		ttywidth = winsize.ws_col;
    848 	else
    849 		ttywidth = 80;
    850 }
    851 
    852 /*
    853  * Set the SIGALRM interval timer for wait seconds, 0 to disable.
    854  */
    855 void
    856 alarmtimer(wait)
    857 	int wait;
    858 {
    859 	struct itimerval itv;
    860 
    861 	itv.it_value.tv_sec = wait;
    862 	itv.it_value.tv_usec = 0;
    863 	itv.it_interval = itv.it_value;
    864 	setitimer(ITIMER_REAL, &itv, NULL);
    865 }
    866 
    867 /*
    868  * Setup or cleanup EditLine structures
    869  */
    870 #ifndef SMALL
    871 void
    872 controlediting()
    873 {
    874 	if (editing && el == NULL && hist == NULL) {
    875 		HistEvent ev;
    876 
    877 		el = el_init(__progname, stdin, ttyout, stderr);
    878 		/* init editline */
    879 		hist = history_init();		/* init the builtin history */
    880 		history(hist, &ev, H_SETSIZE, 100);/* remember 100 events */
    881 		el_set(el, EL_HIST, history, hist);	/* use history */
    882 
    883 		el_set(el, EL_EDITOR, "emacs");	/* default editor is emacs */
    884 		el_set(el, EL_PROMPT, prompt);	/* set the prompt function */
    885 
    886 		/* add local file completion, bind to TAB */
    887 		el_set(el, EL_ADDFN, "ftp-complete",
    888 		    "Context sensitive argument completion",
    889 		    complete);
    890 		el_set(el, EL_BIND, "^I", "ftp-complete", NULL);
    891 
    892 		el_source(el, NULL);	/* read ~/.editrc */
    893 		el_set(el, EL_SIGNAL, 1);
    894 	} else if (!editing) {
    895 		if (hist) {
    896 			history_end(hist);
    897 			hist = NULL;
    898 		}
    899 		if (el) {
    900 			el_end(el);
    901 			el = NULL;
    902 		}
    903 	}
    904 }
    905 #endif /* !SMALL */
    906