Home | History | Annotate | Line # | Download | only in ftp
util.c revision 1.68
      1 /*	$NetBSD: util.c,v 1.68 1999/09/29 00:44:01 lukem Exp $	*/
      2 
      3 /*-
      4  * Copyright (c) 1998, 1999 The NetBSD Foundation, Inc.
      5  * All rights reserved.
      6  *
      7  * This code is derived from software contributed to The NetBSD Foundation
      8  * by Jason R. Thorpe of the Numerical Aerospace Simulation Facility,
      9  * NASA Ames Research Center.
     10  *
     11  * This code is derived from software contributed to The NetBSD Foundation
     12  * by Luke Mewburn.
     13  *
     14  * Redistribution and use in source and binary forms, with or without
     15  * modification, are permitted provided that the following conditions
     16  * are met:
     17  * 1. Redistributions of source code must retain the above copyright
     18  *    notice, this list of conditions and the following disclaimer.
     19  * 2. Redistributions in binary form must reproduce the above copyright
     20  *    notice, this list of conditions and the following disclaimer in the
     21  *    documentation and/or other materials provided with the distribution.
     22  * 3. All advertising materials mentioning features or use of this software
     23  *    must display the following acknowledgement:
     24  *	This product includes software developed by the NetBSD
     25  *	Foundation, Inc. and its contributors.
     26  * 4. Neither the name of The NetBSD Foundation nor the names of its
     27  *    contributors may be used to endorse or promote products derived
     28  *    from this software without specific prior written permission.
     29  *
     30  * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
     31  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
     32  * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
     33  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
     34  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
     35  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
     36  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
     37  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
     38  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
     39  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
     40  * POSSIBILITY OF SUCH DAMAGE.
     41  */
     42 
     43 /*
     44  * Copyright (c) 1985, 1989, 1993, 1994
     45  *	The Regents of the University of California.  All rights reserved.
     46  *
     47  * Redistribution and use in source and binary forms, with or without
     48  * modification, are permitted provided that the following conditions
     49  * are met:
     50  * 1. Redistributions of source code must retain the above copyright
     51  *    notice, this list of conditions and the following disclaimer.
     52  * 2. Redistributions in binary form must reproduce the above copyright
     53  *    notice, this list of conditions and the following disclaimer in the
     54  *    documentation and/or other materials provided with the distribution.
     55  * 3. All advertising materials mentioning features or use of this software
     56  *    must display the following acknowledgement:
     57  *	This product includes software developed by the University of
     58  *	California, Berkeley and its contributors.
     59  * 4. Neither the name of the University nor the names of its contributors
     60  *    may be used to endorse or promote products derived from this software
     61  *    without specific prior written permission.
     62  *
     63  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
     64  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
     65  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
     66  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
     67  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
     68  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
     69  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
     70  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
     71  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
     72  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
     73  * SUCH DAMAGE.
     74  */
     75 
     76 #include <sys/cdefs.h>
     77 #ifndef lint
     78 __RCSID("$NetBSD: util.c,v 1.68 1999/09/29 00:44:01 lukem Exp $");
     79 #endif /* not lint */
     80 
     81 /*
     82  * FTP User Program -- Misc support routines
     83  */
     84 #include <sys/types.h>
     85 #include <sys/socket.h>
     86 #include <sys/ioctl.h>
     87 #include <sys/time.h>
     88 #include <arpa/ftp.h>
     89 
     90 #include <ctype.h>
     91 #include <err.h>
     92 #include <errno.h>
     93 #include <fcntl.h>
     94 #include <glob.h>
     95 #include <signal.h>
     96 #include <limits.h>
     97 #include <pwd.h>
     98 #include <stdio.h>
     99 #include <stdlib.h>
    100 #include <string.h>
    101 #include <termios.h>
    102 #include <time.h>
    103 #include <tzfile.h>
    104 #include <unistd.h>
    105 
    106 #include "ftp_var.h"
    107 #include "pathnames.h"
    108 
    109 /*
    110  * Connect to peer server and
    111  * auto-login, if possible.
    112  */
    113 void
    114 setpeer(argc, argv)
    115 	int argc;
    116 	char *argv[];
    117 {
    118 	char *host;
    119 	char *port;
    120 
    121 	if (connected) {
    122 		fprintf(ttyout, "Already connected to %s, use close first.\n",
    123 		    hostname);
    124 		code = -1;
    125 		return;
    126 	}
    127 	if (argc < 2)
    128 		(void)another(&argc, &argv, "to");
    129 	if (argc < 2 || argc > 3) {
    130 		fprintf(ttyout, "usage: %s host-name [port]\n", argv[0]);
    131 		code = -1;
    132 		return;
    133 	}
    134 	if (gatemode)
    135 		port = gateport;
    136 	else
    137 		port = ftpport;
    138 	if (argc > 2)
    139 		port = strdup(argv[2]);
    140 
    141 	if (gatemode) {
    142 		if (gateserver == NULL || *gateserver == '\0')
    143 			errx(1, "gateserver not defined (shouldn't happen)");
    144 		host = hookup(gateserver, port);
    145 	} else
    146 		host = hookup(argv[1], port);
    147 
    148 	if (host) {
    149 		int overbose;
    150 
    151 		if (gatemode && verbose) {
    152 			fprintf(ttyout,
    153 			    "Connecting via pass-through server %s\n",
    154 			    gateserver);
    155 		}
    156 
    157 		connected = 1;
    158 		/*
    159 		 * Set up defaults for FTP.
    160 		 */
    161 		(void)strlcpy(typename, "ascii", sizeof(typename));
    162 		type = TYPE_A;
    163 		curtype = TYPE_A;
    164 		(void)strlcpy(formname, "non-print", sizeof(formname));
    165 		form = FORM_N;
    166 		(void)strlcpy(modename, "stream", sizeof(modename));
    167 		mode = MODE_S;
    168 		(void)strlcpy(structname, "file", sizeof(structname));
    169 		stru = STRU_F;
    170 		(void)strlcpy(bytename, "8", sizeof(bytename));
    171 		bytesize = 8;
    172 		if (autologin)
    173 			(void)ftp_login(argv[1], NULL, NULL);
    174 
    175 		overbose = verbose;
    176 		if (debug == 0)
    177 			verbose = -1;
    178 		if (command("SYST") == COMPLETE && overbose) {
    179 			char *cp, c;
    180 			c = 0;
    181 			cp = strchr(reply_string + 4, ' ');
    182 			if (cp == NULL)
    183 				cp = strchr(reply_string + 4, '\r');
    184 			if (cp) {
    185 				if (cp[-1] == '.')
    186 					cp--;
    187 				c = *cp;
    188 				*cp = '\0';
    189 			}
    190 
    191 			fprintf(ttyout, "Remote system type is %s.\n",
    192 			    reply_string + 4);
    193 			if (cp)
    194 				*cp = c;
    195 		}
    196 		if (!strncmp(reply_string, "215 UNIX Type: L8", 17)) {
    197 			if (proxy)
    198 				unix_proxy = 1;
    199 			else
    200 				unix_server = 1;
    201 			/*
    202 			 * Set type to 0 (not specified by user),
    203 			 * meaning binary by default, but don't bother
    204 			 * telling server.  We can use binary
    205 			 * for text files unless changed by the user.
    206 			 */
    207 			type = 0;
    208 			(void)strlcpy(typename, "binary", sizeof(typename));
    209 			if (overbose)
    210 			    fprintf(ttyout,
    211 				"Using %s mode to transfer files.\n",
    212 				typename);
    213 		} else {
    214 			if (proxy)
    215 				unix_proxy = 0;
    216 			else
    217 				unix_server = 0;
    218 			if (overbose &&
    219 			    !strncmp(reply_string, "215 TOPS20", 10))
    220 				fputs(
    221 "Remember to set tenex mode when transferring binary files from this machine.\n",
    222 				    ttyout);
    223 		}
    224 		verbose = overbose;
    225 	}
    226 }
    227 
    228 /*
    229  * login to remote host, using given username & password if supplied
    230  */
    231 int
    232 ftp_login(host, user, pass)
    233 	const char *host;
    234 	const char *user, *pass;
    235 {
    236 	char tmp[80];
    237 	const char *acct;
    238 	struct passwd *pw;
    239 	int n, aflag, rval, freeuser, freepass, freeacct, len;
    240 
    241 	acct = NULL;
    242 	aflag = rval = freeuser = freepass = freeacct = 0;
    243 
    244 	/*
    245 	 * Set up arguments for an anonymous FTP session, if necessary.
    246 	 */
    247 	if (anonftp) {
    248 		/*
    249 		 * Set up anonymous login password.
    250 		 */
    251 		if ((pass = getenv("FTPANONPASS")) == NULL) {
    252 			char *anonpass;
    253 
    254 			if ((pass = getlogin()) == NULL) {
    255 				if ((pw = getpwuid(getuid())) == NULL)
    256 					pass = "anonymous";
    257 				else
    258 					pass = pw->pw_name;
    259 			}
    260 			/*
    261 			 * Every anonymous FTP server I've encountered
    262 			 * will accept the string "username@", and will
    263 			 * append the hostname itself.  We do this by default
    264 			 * since many servers are picky about not having
    265 			 * a FQDN in the anonymous password.
    266 			 * - thorpej (at) netbsd.org
    267 			 */
    268 			len = strlen(pass) + 2;
    269 			anonpass = xmalloc(len);
    270 			(void)strlcpy(anonpass, pass, len);
    271 			(void)strlcat(anonpass, "@",  len);
    272 			pass = anonpass;
    273 			freepass = 1;
    274 		}
    275 		user = "anonymous";	/* as per RFC 1635 */
    276 	}
    277 
    278 	if (user == NULL)
    279 		freeuser = 1;
    280 	if (pass == NULL)
    281 		freepass = 1;
    282 	freeacct = 1;
    283 	if (ruserpass(host, &user, &pass, &acct) < 0) {
    284 		code = -1;
    285 		goto cleanup_ftp_login;
    286 	}
    287 
    288 	while (user == NULL) {
    289 		const char *myname = getlogin();
    290 
    291 		if (myname == NULL && (pw = getpwuid(getuid())) != NULL)
    292 			myname = pw->pw_name;
    293 		if (myname)
    294 			fprintf(ttyout, "Name (%s:%s): ", host, myname);
    295 		else
    296 			fprintf(ttyout, "Name (%s): ", host);
    297 		*tmp = '\0';
    298 		if (fgets(tmp, sizeof(tmp) - 1, stdin) == NULL) {
    299 			fprintf(ttyout, "\nEOF received; login aborted.\n");
    300 			code = -1;
    301 			goto cleanup_ftp_login;
    302 		}
    303 		tmp[strlen(tmp) - 1] = '\0';
    304 		freeuser = 0;
    305 		if (*tmp == '\0')
    306 			user = myname;
    307 		else
    308 			user = tmp;
    309 	}
    310 
    311 	if (gatemode) {
    312 		char *nuser;
    313 		int len;
    314 
    315 		len = strlen(user) + 1 + strlen(host) + 1;
    316 		nuser = xmalloc(len);
    317 		(void)strlcpy(nuser, user, len);
    318 		(void)strlcat(nuser, "@",  len);
    319 		(void)strlcat(nuser, host, len);
    320 		freeuser = 1;
    321 		user = nuser;
    322 	}
    323 
    324 	n = command("USER %s", user);
    325 	if (n == CONTINUE) {
    326 		if (pass == NULL) {
    327 			freepass = 0;
    328 			pass = getpass("Password:");
    329 		}
    330 		n = command("PASS %s", pass);
    331 	}
    332 	if (n == CONTINUE) {
    333 		aflag++;
    334 		if (acct == NULL) {
    335 			freeacct = 0;
    336 			acct = getpass("Account:");
    337 		}
    338 		if (acct[0] == '\0') {
    339 			warnx("Login failed.");
    340 			goto cleanup_ftp_login;
    341 		}
    342 		n = command("ACCT %s", acct);
    343 	}
    344 	if ((n != COMPLETE) ||
    345 	    (!aflag && acct != NULL && command("ACCT %s", acct) != COMPLETE)) {
    346 		warnx("Login failed.");
    347 		goto cleanup_ftp_login;
    348 	}
    349 	rval = 1;
    350 	if (proxy)
    351 		goto cleanup_ftp_login;
    352 
    353 	connected = -1;
    354 	for (n = 0; n < macnum; ++n) {
    355 		if (!strcmp("init", macros[n].mac_name)) {
    356 			(void)strlcpy(line, "$init", sizeof(line));
    357 			makeargv();
    358 			domacro(margc, margv);
    359 			break;
    360 		}
    361 	}
    362 cleanup_ftp_login:
    363 	if (user != NULL && freeuser)
    364 		free((char *)user);
    365 	if (pass != NULL && freepass)
    366 		free((char *)pass);
    367 	if (acct != NULL && freeacct)
    368 		free((char *)acct);
    369 	return (rval);
    370 }
    371 
    372 /*
    373  * `another' gets another argument, and stores the new argc and argv.
    374  * It reverts to the top level (via main.c's intr()) on EOF/error.
    375  *
    376  * Returns false if no new arguments have been added.
    377  */
    378 int
    379 another(pargc, pargv, prompt)
    380 	int *pargc;
    381 	char ***pargv;
    382 	const char *prompt;
    383 {
    384 	int len = strlen(line), ret;
    385 
    386 	if (len >= sizeof(line) - 3) {
    387 		fputs("sorry, arguments too long.\n", ttyout);
    388 		intr();
    389 	}
    390 	fprintf(ttyout, "(%s) ", prompt);
    391 	line[len++] = ' ';
    392 	if (fgets(&line[len], sizeof(line) - len, stdin) == NULL)
    393 		intr();
    394 	len += strlen(&line[len]);
    395 	if (len > 0 && line[len - 1] == '\n')
    396 		line[len - 1] = '\0';
    397 	makeargv();
    398 	ret = margc > *pargc;
    399 	*pargc = margc;
    400 	*pargv = margv;
    401 	return (ret);
    402 }
    403 
    404 /*
    405  * glob files given in argv[] from the remote server.
    406  * if errbuf isn't NULL, store error messages there instead
    407  * of writing to the screen.
    408  */
    409 char *
    410 remglob(argv, doswitch, errbuf)
    411         char *argv[];
    412         int doswitch;
    413 	char **errbuf;
    414 {
    415         char temp[MAXPATHLEN];
    416         static char buf[MAXPATHLEN];
    417         static FILE *ftemp = NULL;
    418         static char **args;
    419         int oldverbose, oldhash, fd;
    420         char *cp, *mode;
    421 
    422         if (!mflag) {
    423                 if (!doglob)
    424                         args = NULL;
    425                 else {
    426                         if (ftemp) {
    427                                 (void)fclose(ftemp);
    428                                 ftemp = NULL;
    429                         }
    430                 }
    431                 return (NULL);
    432         }
    433         if (!doglob) {
    434                 if (args == NULL)
    435                         args = argv;
    436                 if ((cp = *++args) == NULL)
    437                         args = NULL;
    438                 return (cp);
    439         }
    440         if (ftemp == NULL) {
    441 		(void)strlcpy(temp, tmpdir,	sizeof(temp));
    442 		(void)strlcat(temp, "/",	sizeof(temp));
    443 		(void)strlcat(temp, TMPFILE,	sizeof(temp));
    444                 if ((fd = mkstemp(temp)) < 0) {
    445                         warn("unable to create temporary file %s", temp);
    446                         return (NULL);
    447                 }
    448                 close(fd);
    449                 oldverbose = verbose;
    450 		verbose = (errbuf != NULL) ? -1 : 0;
    451                 oldhash = hash;
    452                 hash = 0;
    453                 if (doswitch)
    454                         pswitch(!proxy);
    455                 for (mode = "w"; *++argv != NULL; mode = "a")
    456                         recvrequest("NLST", temp, *argv, mode, 0, 0);
    457 		if ((code / 100) != COMPLETE) {
    458 			if (errbuf != NULL)
    459 				*errbuf = reply_string;
    460 		}
    461                 if (doswitch)
    462                         pswitch(!proxy);
    463                 verbose = oldverbose;
    464 		hash = oldhash;
    465                 ftemp = fopen(temp, "r");
    466                 (void)unlink(temp);
    467                 if (ftemp == NULL) {
    468 			if (errbuf == NULL)
    469 				fputs(
    470 				    "can't find list of remote files, oops.\n",
    471 				    ttyout);
    472 			else
    473 				*errbuf =
    474 				    "can't find list of remote files, oops.";
    475                         return (NULL);
    476                 }
    477         }
    478         if (fgets(buf, sizeof(buf), ftemp) == NULL) {
    479                 (void)fclose(ftemp);
    480 		ftemp = NULL;
    481                 return (NULL);
    482         }
    483         if ((cp = strchr(buf, '\n')) != NULL)
    484                 *cp = '\0';
    485         return (buf);
    486 }
    487 
    488 int
    489 confirm(cmd, file)
    490 	const char *cmd, *file;
    491 {
    492 	char line[BUFSIZ];
    493 
    494 	if (!interactive || confirmrest)
    495 		return (1);
    496 	fprintf(ttyout, "%s %s? ", cmd, file);
    497 	(void)fflush(ttyout);
    498 	if (fgets(line, sizeof(line), stdin) == NULL)
    499 		return (0);
    500 	switch (tolower(*line)) {
    501 		case 'n':
    502 			return (0);
    503 		case 'p':
    504 			interactive = 0;
    505 			fputs("Interactive mode: off.\n", ttyout);
    506 			break;
    507 		case 'a':
    508 			confirmrest = 1;
    509 			fprintf(ttyout, "Prompting off for duration of %s.\n",
    510 			    cmd);
    511 			break;
    512 	}
    513 	return (1);
    514 }
    515 
    516 /*
    517  * Glob a local file name specification with the expectation of a single
    518  * return value. Can't control multiple values being expanded from the
    519  * expression, we return only the first.
    520  * Returns NULL on error, or a pointer to a buffer containing the filename
    521  * that's the caller's responsiblity to free(3) when finished with.
    522  */
    523 char *
    524 globulize(pattern)
    525 	const char *pattern;
    526 {
    527 	glob_t gl;
    528 	int flags;
    529 	char *p;
    530 
    531 	if (!doglob)
    532 		return (xstrdup(pattern));
    533 
    534 	flags = GLOB_BRACE|GLOB_NOCHECK|GLOB_TILDE;
    535 	memset(&gl, 0, sizeof(gl));
    536 	if (glob(pattern, flags, NULL, &gl) || gl.gl_pathc == 0) {
    537 		warnx("%s: not found", pattern);
    538 		globfree(&gl);
    539 		return (NULL);
    540 	}
    541 	p = xstrdup(gl.gl_pathv[0]);
    542 	globfree(&gl);
    543 	return (p);
    544 }
    545 
    546 /*
    547  * determine size of remote file
    548  */
    549 off_t
    550 remotesize(file, noisy)
    551 	const char *file;
    552 	int noisy;
    553 {
    554 	int overbose;
    555 	off_t size;
    556 
    557 	overbose = verbose;
    558 	size = -1;
    559 	if (debug == 0)
    560 		verbose = -1;
    561 	if (command("SIZE %s", file) == COMPLETE) {
    562 		char *cp, *ep;
    563 
    564 		cp = strchr(reply_string, ' ');
    565 		if (cp != NULL) {
    566 			cp++;
    567 #ifndef NO_QUAD
    568 			size = strtoq(cp, &ep, 10);
    569 #else
    570 			size = strtol(cp, &ep, 10);
    571 #endif
    572 			if (*ep != '\0' && !isspace((unsigned char)*ep))
    573 				size = -1;
    574 		}
    575 	} else if (noisy && debug == 0) {
    576 		fputs(reply_string, ttyout);
    577 		putc('\n', ttyout);
    578 	}
    579 	verbose = overbose;
    580 	return (size);
    581 }
    582 
    583 /*
    584  * determine last modification time (in GMT) of remote file
    585  */
    586 time_t
    587 remotemodtime(file, noisy)
    588 	const char *file;
    589 	int noisy;
    590 {
    591 	int overbose;
    592 	time_t rtime;
    593 	int ocode;
    594 
    595 	overbose = verbose;
    596 	ocode = code;
    597 	rtime = -1;
    598 	if (debug == 0)
    599 		verbose = -1;
    600 	if (command("MDTM %s", file) == COMPLETE) {
    601 		struct tm timebuf;
    602 		int yy, mo, day, hour, min, sec;
    603 		sscanf(reply_string, "%*s %04d%02d%02d%02d%02d%02d", &yy, &mo,
    604 			&day, &hour, &min, &sec);
    605 		memset(&timebuf, 0, sizeof(timebuf));
    606 		timebuf.tm_sec = sec;
    607 		timebuf.tm_min = min;
    608 		timebuf.tm_hour = hour;
    609 		timebuf.tm_mday = day;
    610 		timebuf.tm_mon = mo - 1;
    611 		timebuf.tm_year = yy - TM_YEAR_BASE;
    612 		timebuf.tm_isdst = -1;
    613 		rtime = timegm(&timebuf);
    614 		if (rtime == -1 && (noisy || debug != 0))
    615 			fprintf(ttyout, "Can't convert %s to a time.\n",
    616 			    reply_string);
    617 	} else if (noisy && debug == 0) {
    618 		fputs(reply_string, ttyout);
    619 		putc('\n', ttyout);
    620 	}
    621 	verbose = overbose;
    622 	if (rtime == -1)
    623 		code = ocode;
    624 	return (rtime);
    625 }
    626 
    627 #ifndef	NO_PROGRESS
    628 
    629 /*
    630  * return non-zero if we're the current foreground process
    631  */
    632 int
    633 foregroundproc()
    634 {
    635 	static pid_t pgrp = -1;
    636 
    637 	if (pgrp == -1)
    638 		pgrp = getpgrp();
    639 
    640 	return (tcgetpgrp(fileno(ttyout)) == pgrp);
    641 }
    642 
    643 
    644 static void updateprogressmeter __P((int));
    645 
    646 static void
    647 updateprogressmeter(dummy)
    648 	int dummy;
    649 {
    650 	int oerrno;
    651 
    652 	oerrno = errno;
    653 	progressmeter(0);
    654 	errno = oerrno;
    655 }
    656 #endif	/* NO_PROGRESS */
    657 
    658 
    659 /*
    660  * List of order of magnitude prefixes.
    661  * The last is `P', as 2^64 = 16384 Petabytes
    662  */
    663 static const char prefixes[] = " KMGTP";
    664 
    665 /*
    666  * Display a transfer progress bar if progress is non-zero.
    667  * SIGALRM is hijacked for use by this function.
    668  * - Before the transfer, set filesize to size of file (or -1 if unknown),
    669  *   and call with flag = -1. This starts the once per second timer,
    670  *   and a call to updateprogressmeter() upon SIGALRM.
    671  * - During the transfer, updateprogressmeter will call progressmeter
    672  *   with flag = 0
    673  * - After the transfer, call with flag = 1
    674  */
    675 static struct timeval start;
    676 static struct timeval lastupdate;
    677 
    678 void
    679 progressmeter(flag)
    680 	int flag;
    681 {
    682 	static off_t lastsize;
    683 #ifndef NO_PROGRESS
    684 	struct timeval now, td, wait;
    685 	off_t cursize, abbrevsize, bytespersec;
    686 	double elapsed;
    687 	int ratio, barlength, i, len, remaining;
    688 
    689 			/*
    690 			 * Work variables for progress bar.
    691 			 *
    692 			 * XXX:	if the format of the progress bar changes
    693 			 *	(especially the number of characters in the
    694 			 *	`static' portion of it), be sure to update
    695 			 *	these appropriately.
    696 			 */
    697 	char		buf[256];	/* workspace for progress bar */
    698 #define BAROVERHEAD	43		/* non `*' portion of progress bar */
    699 					/*
    700 					 * stars should contain at least
    701 					 * sizeof(buf) - BAROVERHEAD entries
    702 					 */
    703 	const char	stars[] =
    704 "*****************************************************************************"
    705 "*****************************************************************************"
    706 "*****************************************************************************";
    707 
    708 #endif
    709 
    710 	if (flag == -1) {
    711 		(void)gettimeofday(&start, NULL);
    712 		lastupdate = start;
    713 		lastsize = restart_point;
    714 	}
    715 #ifndef NO_PROGRESS
    716 	len = 0;
    717 	if (!progress || filesize <= 0)
    718 		return;
    719 
    720 	(void)gettimeofday(&now, NULL);
    721 	cursize = bytes + restart_point;
    722 	timersub(&now, &lastupdate, &wait);
    723 	if (cursize > lastsize) {
    724 		lastupdate = now;
    725 		lastsize = cursize;
    726 		wait.tv_sec = 0;
    727 	}
    728 
    729 	/*
    730 	 * print progress bar only if we are foreground process.
    731 	 */
    732 	if (! foregroundproc())
    733 		return;
    734 
    735 #define BUFLEFT	(sizeof(buf) - len)
    736 
    737 	ratio = (int)((double)cursize * 100.0 / (double)filesize);
    738 	ratio = MAX(ratio, 0);
    739 	ratio = MIN(ratio, 100);
    740 	len += snprintf(buf + len, BUFLEFT, "\r%3d%% ", ratio);
    741 
    742 			/*
    743 			 * calculate the length of the `*' bar, ensuring that
    744 			 * the number of stars won't exceed the buffer size
    745 			 */
    746 	barlength = MIN(sizeof(buf) - 1, ttywidth) - BAROVERHEAD;
    747 	if (barlength > 0) {
    748 		i = barlength * ratio / 100;
    749 		len += snprintf(buf + len, BUFLEFT,
    750 		    "|%.*s%*s|", i, stars, barlength - i, "");
    751 	}
    752 
    753 	abbrevsize = cursize;
    754 	for (i = 0; abbrevsize >= 100000 && i < sizeof(prefixes); i++)
    755 		abbrevsize >>= 10;
    756 	len += snprintf(buf + len, BUFLEFT,
    757 #ifndef NO_QUAD
    758 	    " %5lld %c%c ", (long long)abbrevsize,
    759 #else
    760 	    " %5ld %c%c ", (long)abbrevsize,
    761 #endif
    762 	    prefixes[i],
    763 	    i == 0 ? ' ' : 'B');
    764 
    765 	timersub(&now, &start, &td);
    766 	elapsed = td.tv_sec + (td.tv_usec / 1000000.0);
    767 
    768 	bytespersec = 0;
    769 	if (bytes > 0) {
    770 		bytespersec = bytes;
    771 		if (elapsed > 0.0)
    772 			bytespersec /= elapsed;
    773 	}
    774 	for (i = 1; bytespersec >= 1024000 && i < sizeof(prefixes); i++)
    775 		bytespersec >>= 10;
    776 	len += snprintf(buf + len, BUFLEFT,
    777 #ifndef NO_QUAD
    778 	    " %3lld.%02d %cB/s ", (long long)bytespersec / 1024,
    779 #else
    780 	    " %3ld.%02d %cB/s ", (long)bytespersec / 1024,
    781 #endif
    782 	    (int)((bytespersec % 1024) * 100 / 1024),
    783 	    prefixes[i]);
    784 
    785 	if (bytes <= 0 || elapsed <= 0.0 || cursize > filesize) {
    786 		len += snprintf(buf + len, BUFLEFT, "   --:-- ETA");
    787 	} else if (wait.tv_sec >= STALLTIME) {
    788 		len += snprintf(buf + len, BUFLEFT, " - stalled -");
    789 	} else {
    790 		remaining = (int)
    791 		    ((filesize - restart_point) / (bytes / elapsed) - elapsed);
    792 		if (remaining >= 100 * SECSPERHOUR)
    793 			len += snprintf(buf + len, BUFLEFT, "   --:-- ETA");
    794 		else {
    795 			i = remaining / SECSPERHOUR;
    796 			if (i)
    797 				len += snprintf(buf + len, BUFLEFT, "%2d:", i);
    798 			else
    799 				len += snprintf(buf + len, BUFLEFT, "   ");
    800 			i = remaining % SECSPERHOUR;
    801 			len += snprintf(buf + len, BUFLEFT,
    802 			    "%02d:%02d ETA", i / 60, i % 60);
    803 		}
    804 	}
    805 	if (flag == 1)
    806 		len += snprintf(buf + len, BUFLEFT, "\n");
    807 	(void)write(fileno(ttyout), buf, len);
    808 
    809 	if (flag == -1) {
    810 		(void)xsignal(SIGALRM, updateprogressmeter);
    811 		alarmtimer(1);		/* set alarm timer for 1 Hz */
    812 	} else if (flag == 1) {
    813 		(void)xsignal(SIGALRM, SIG_DFL);
    814 		alarmtimer(0);
    815 	}
    816 #endif	/* !NO_PROGRESS */
    817 }
    818 
    819 /*
    820  * Display transfer statistics.
    821  * Requires start to be initialised by progressmeter(-1),
    822  * direction to be defined by xfer routines, and filesize and bytes
    823  * to be updated by xfer routines
    824  * If siginfo is nonzero, an ETA is displayed, and the output goes to stderr
    825  * instead of ttyout.
    826  */
    827 void
    828 ptransfer(siginfo)
    829 	int siginfo;
    830 {
    831 	struct timeval now, td, wait;
    832 	double elapsed;
    833 	off_t bytespersec;
    834 	int remaining, hh, i, len;
    835 
    836 	char buf[256];		/* Work variable for transfer status. */
    837 
    838 	if (!verbose && !progress && !siginfo)
    839 		return;
    840 
    841 	(void)gettimeofday(&now, NULL);
    842 	timersub(&now, &start, &td);
    843 	elapsed = td.tv_sec + (td.tv_usec / 1000000.0);
    844 	bytespersec = 0;
    845 	if (bytes > 0) {
    846 		bytespersec = bytes;
    847 		if (elapsed > 0.0)
    848 			bytespersec /= elapsed;
    849 	}
    850 	len = 0;
    851 	len += snprintf(buf + len, BUFLEFT,
    852 #ifndef NO_QUAD
    853 	    "%lld byte%s %s in ", (long long)bytes,
    854 #else
    855 	    "%ld byte%s %s in ", (long)bytes,
    856 #endif
    857 	    bytes == 1 ? "" : "s", direction);
    858 	remaining = (int)elapsed;
    859 	if (remaining > SECSPERDAY) {
    860 		int days;
    861 
    862 		days = remaining / SECSPERDAY;
    863 		remaining %= SECSPERDAY;
    864 		len += snprintf(buf + len, BUFLEFT,
    865 		    "%d day%s ", days, days == 1 ? "" : "s");
    866 	}
    867 	hh = remaining / SECSPERHOUR;
    868 	remaining %= SECSPERHOUR;
    869 	if (hh)
    870 		len += snprintf(buf + len, BUFLEFT, "%2d:", hh);
    871 	len += snprintf(buf + len, BUFLEFT,
    872 	    "%02d:%02d ", remaining / 60, remaining % 60);
    873 
    874 	for (i = 1; bytespersec >= 1024000 && i < sizeof(prefixes); i++)
    875 		bytespersec >>= 10;
    876 	len += snprintf(buf + len, BUFLEFT,
    877 #ifndef NO_QUAD
    878 	    "(%lld.%02d %cB/s)", (long long)bytespersec / 1024,
    879 #else
    880 	    "(%ld.%02d %cB/s)", (long)bytespersec / 1024,
    881 #endif
    882 	    (int)((bytespersec % 1024) * 100 / 1024),
    883 	    prefixes[i]);
    884 
    885 	if (siginfo && bytes > 0 && elapsed > 0.0 && filesize >= 0
    886 	    && bytes + restart_point <= filesize) {
    887 		remaining = (int)((filesize - restart_point) /
    888 				  (bytes / elapsed) - elapsed);
    889 		hh = remaining / SECSPERHOUR;
    890 		remaining %= SECSPERHOUR;
    891 		len += snprintf(buf + len, BUFLEFT, "  ETA: ");
    892 		if (hh)
    893 			len += snprintf(buf + len, BUFLEFT, "%2d:", hh);
    894 		len += snprintf(buf + len, BUFLEFT, "%02d:%02d",
    895 		    remaining / 60, remaining % 60);
    896 		timersub(&now, &lastupdate, &wait);
    897 		if (wait.tv_sec >= STALLTIME)
    898 			len += snprintf(buf + len, BUFLEFT, "  (stalled)");
    899 	}
    900 	len += snprintf(buf + len, BUFLEFT, "\n");
    901 	(void)write(siginfo ? STDERR_FILENO : fileno(ttyout), buf, len);
    902 }
    903 
    904 /*
    905  * List words in stringlist, vertically arranged
    906  */
    907 void
    908 list_vertical(sl)
    909 	StringList *sl;
    910 {
    911 	int i, j, w;
    912 	int columns, width, lines, items;
    913 	char *p;
    914 
    915 	width = items = 0;
    916 
    917 	for (i = 0 ; i < sl->sl_cur ; i++) {
    918 		w = strlen(sl->sl_str[i]);
    919 		if (w > width)
    920 			width = w;
    921 	}
    922 	width = (width + 8) &~ 7;
    923 
    924 	columns = ttywidth / width;
    925 	if (columns == 0)
    926 		columns = 1;
    927 	lines = (sl->sl_cur + columns - 1) / columns;
    928 	for (i = 0; i < lines; i++) {
    929 		for (j = 0; j < columns; j++) {
    930 			p = sl->sl_str[j * lines + i];
    931 			if (p)
    932 				fputs(p, ttyout);
    933 			if (j * lines + i + lines >= sl->sl_cur) {
    934 				putc('\n', ttyout);
    935 				break;
    936 			}
    937 			w = strlen(p);
    938 			while (w < width) {
    939 				w = (w + 8) &~ 7;
    940 				(void)putc('\t', ttyout);
    941 			}
    942 		}
    943 	}
    944 }
    945 
    946 /*
    947  * Update the global ttywidth value, using TIOCGWINSZ.
    948  */
    949 void
    950 setttywidth(a)
    951 	int a;
    952 {
    953 	struct winsize winsize;
    954 	int oerrno;
    955 
    956 	oerrno = errno;
    957 	if (ioctl(fileno(ttyout), TIOCGWINSZ, &winsize) != -1 &&
    958 	    winsize.ws_col != 0)
    959 		ttywidth = winsize.ws_col;
    960 	else
    961 		ttywidth = 80;
    962 	errno = oerrno;
    963 }
    964 
    965 void
    966 crankrate(int sig)
    967 {
    968 
    969 	switch (sig) {
    970 	case SIGUSR1:
    971 		if (rate_get)
    972 			rate_get += rate_get_incr;
    973 		if (rate_put)
    974 			rate_put += rate_put_incr;
    975 		break;
    976 	case SIGUSR2:
    977 		if (rate_get && rate_get > rate_get_incr)
    978 			rate_get -= rate_get_incr;
    979 		if (rate_put && rate_put > rate_put_incr)
    980 			rate_put -= rate_put_incr;
    981 		break;
    982 	default:
    983 		err(1, "crankrate invoked with unknown signal: %d", sig);
    984 	}
    985 }
    986 
    987 
    988 /*
    989  * Set the SIGALRM interval timer for wait seconds, 0 to disable.
    990  */
    991 void
    992 alarmtimer(wait)
    993 	int wait;
    994 {
    995 	struct itimerval itv;
    996 
    997 	itv.it_value.tv_sec = wait;
    998 	itv.it_value.tv_usec = 0;
    999 	itv.it_interval = itv.it_value;
   1000 	setitimer(ITIMER_REAL, &itv, NULL);
   1001 }
   1002 
   1003 /*
   1004  * Setup or cleanup EditLine structures
   1005  */
   1006 #ifndef NO_EDITCOMPLETE
   1007 void
   1008 controlediting()
   1009 {
   1010 	if (editing && el == NULL && hist == NULL) {
   1011 		HistEvent ev;
   1012 		int editmode;
   1013 
   1014 		el = el_init(__progname, stdin, ttyout, stderr);
   1015 		/* init editline */
   1016 		hist = history_init();		/* init the builtin history */
   1017 		history(hist, &ev, H_SETSIZE, 100);/* remember 100 events */
   1018 		el_set(el, EL_HIST, history, hist);	/* use history */
   1019 
   1020 		el_set(el, EL_EDITOR, "emacs");	/* default editor is emacs */
   1021 		el_set(el, EL_PROMPT, prompt);	/* set the prompt function */
   1022 
   1023 		/* add local file completion, bind to TAB */
   1024 		el_set(el, EL_ADDFN, "ftp-complete",
   1025 		    "Context sensitive argument completion",
   1026 		    complete);
   1027 		el_set(el, EL_BIND, "^I", "ftp-complete", NULL);
   1028 		el_source(el, NULL);	/* read ~/.editrc */
   1029 		if ((el_get(el, EL_EDITMODE, &editmode) != -1) && editmode == 0)
   1030 			editing = 0;	/* the user doesn't want editing,
   1031 					 * so disable, and let statement
   1032 					 * below cleanup */
   1033 		else
   1034 			el_set(el, EL_SIGNAL, 1);
   1035 	}
   1036 	if (!editing) {
   1037 		if (hist) {
   1038 			history_end(hist);
   1039 			hist = NULL;
   1040 		}
   1041 		if (el) {
   1042 			el_end(el);
   1043 			el = NULL;
   1044 		}
   1045 	}
   1046 }
   1047 #endif /* !NO_EDITCOMPLETE */
   1048 
   1049 /*
   1050  * Convert the string `arg' to an int, which may have an optional SI suffix
   1051  * (`b', `k', `m', `g'). Returns the number for success, -1 otherwise.
   1052  */
   1053 int
   1054 strsuftoi(arg)
   1055 	const char *arg;
   1056 {
   1057 	char *cp;
   1058 	long val;
   1059 
   1060 	if (!isdigit((unsigned char)arg[0]))
   1061 		return (-1);
   1062 
   1063 	val = strtol(arg, &cp, 10);
   1064 	if (cp != NULL) {
   1065 		if (cp[0] != '\0' && cp[1] != '\0')
   1066 			 return (-1);
   1067 		switch (tolower((unsigned char)cp[0])) {
   1068 		case '\0':
   1069 		case 'b':
   1070 			break;
   1071 		case 'k':
   1072 			val <<= 10;
   1073 			break;
   1074 		case 'm':
   1075 			val <<= 20;
   1076 			break;
   1077 		case 'g':
   1078 			val <<= 30;
   1079 			break;
   1080 		default:
   1081 			return (-1);
   1082 		}
   1083 	}
   1084 	if (val < 0 || val > INT_MAX)
   1085 		return (-1);
   1086 
   1087 	return (val);
   1088 }
   1089 
   1090 /*
   1091  * Set up socket buffer sizes before a connection is made.
   1092  */
   1093 void
   1094 setupsockbufsize(sock)
   1095 	int sock;
   1096 {
   1097 
   1098 	if (setsockopt(sock, SOL_SOCKET, SO_SNDBUF, (void *) &sndbuf_size,
   1099 	    sizeof(rcvbuf_size)) < 0)
   1100 		warn("unable to set sndbuf size %d", sndbuf_size);
   1101 
   1102 	if (setsockopt(sock, SOL_SOCKET, SO_RCVBUF, (void *) &rcvbuf_size,
   1103 	    sizeof(rcvbuf_size)) < 0)
   1104 		warn("unable to set rcvbuf size %d", rcvbuf_size);
   1105 }
   1106 
   1107 void
   1108 ftpvis(dst, dstlen, src, srclen)
   1109 	char		*dst;
   1110 	size_t		 dstlen;
   1111 	const char	*src;
   1112 	size_t		 srclen;
   1113 {
   1114 	int	di, si;
   1115 
   1116 	for (di = si = 0;
   1117 	    src[si] != '\0' && di < dstlen && si < srclen;
   1118 	    di++, si++) {
   1119 		switch (src[si]) {
   1120 		case '\\':
   1121 		case ' ':
   1122 		case '\t':
   1123 		case '\r':
   1124 		case '\n':
   1125 		case '"':
   1126 			dst[di++] = '\\';
   1127 			if (di >= dstlen)
   1128 				break;
   1129 			/* FALLTHROUGH */
   1130 		default:
   1131 			dst[di] = src[si];
   1132 		}
   1133 	}
   1134 	dst[di] = '\0';
   1135 }
   1136 
   1137 /*
   1138  * Determine if given string is an IPv6 address or not.
   1139  * Return 1 for yes, 0 for no
   1140  */
   1141 int
   1142 isipv6addr(addr)
   1143 	const char *addr;
   1144 {
   1145 	int rv = 0;
   1146 #ifdef INET6
   1147 	u_char buf[16];		/* XXX: sizeof(struct in_addr6) */
   1148 
   1149 	rv = inet_pton(AF_INET6, addr, &buf);
   1150 	if (debug)
   1151 		fprintf(ttyout, "isipv6addr: got %d for %s\n", rv, addr);
   1152 #endif
   1153 	return rv;
   1154 }
   1155 
   1156 
   1157 /*
   1158  * Internal version of connect(2); sets socket buffer sizes first.
   1159  */
   1160 int
   1161 xconnect(sock, name, namelen)
   1162 	int sock;
   1163 	const struct sockaddr *name;
   1164 	int namelen;
   1165 {
   1166 
   1167 	setupsockbufsize(sock);
   1168 	return (connect(sock, name, namelen));
   1169 }
   1170 
   1171 /*
   1172  * Internal version of listen(2); sets socket buffer sizes first.
   1173  */
   1174 int
   1175 xlisten(sock, backlog)
   1176 	int sock, backlog;
   1177 {
   1178 
   1179 	setupsockbufsize(sock);
   1180 	return (listen(sock, backlog));
   1181 }
   1182 
   1183 void *
   1184 xmalloc(size)
   1185 	size_t size;
   1186 {
   1187 	void *p;
   1188 
   1189 	p = malloc(size);
   1190 	if (p == NULL)
   1191 		err(1, "Unable to allocate %ld bytes of memory", (long)size);
   1192 	return (p);
   1193 }
   1194 
   1195 char *
   1196 xstrdup(str)
   1197 	const char *str;
   1198 {
   1199 	char *s;
   1200 
   1201 	if (str == NULL)
   1202 		errx(1, "xstrdup() called with NULL argument");
   1203 	s = strdup(str);
   1204 	if (s == NULL)
   1205 		err(1, "Unable to allocate memory for string copy");
   1206 	return (s);
   1207 }
   1208 
   1209 sig_t
   1210 xsignal(sig, func)
   1211 	int sig;
   1212 	void (*func) __P((int));
   1213 {
   1214 	struct sigaction act, oact;
   1215 
   1216 	act.sa_handler = func;
   1217 	sigemptyset(&act.sa_mask);
   1218 #if defined(SA_RESTART)			/* 4.4BSD, Posix(?), SVR4 */
   1219 	act.sa_flags = SA_RESTART;
   1220 #elif defined(SA_INTERRUPT)		/* SunOS 4.x */
   1221 	act.sa_flags = 0;
   1222 #else
   1223 #error "system must have SA_RESTART or SA_INTERRUPT"
   1224 #endif
   1225 	if (sigaction(sig, &act, &oact) < 0)
   1226 		return (SIG_ERR);
   1227 	return (oact.sa_handler);
   1228 }
   1229