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