Home | History | Annotate | Line # | Download | only in ftp
util.c revision 1.77
      1 /*	$NetBSD: util.c,v 1.77 1999/10/12 06:05:01 lukem Exp $	*/
      2 
      3 /*-
      4  * Copyright (c) 1997-1999 The NetBSD Foundation, Inc.
      5  * All rights reserved.
      6  *
      7  * This code is derived from software contributed to The NetBSD Foundation
      8  * by Luke Mewburn.
      9  *
     10  * This code is derived from software contributed to The NetBSD Foundation
     11  * by Jason R. Thorpe of the Numerical Aerospace Simulation Facility,
     12  * NASA Ames Research Center.
     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.77 1999/10/12 06:05: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 
    108 /*
    109  * Connect to peer server and
    110  * auto-login, if possible.
    111  */
    112 void
    113 setpeer(argc, argv)
    114 	int argc;
    115 	char *argv[];
    116 {
    117 	char *host;
    118 	char *port;
    119 
    120 	if (connected) {
    121 		fprintf(ttyout, "Already connected to %s, use close first.\n",
    122 		    hostname);
    123 		code = -1;
    124 		return;
    125 	}
    126 	if (argc < 2)
    127 		(void)another(&argc, &argv, "to");
    128 	if (argc < 2 || argc > 3) {
    129 		fprintf(ttyout, "usage: %s host-name [port]\n", argv[0]);
    130 		code = -1;
    131 		return;
    132 	}
    133 	if (gatemode)
    134 		port = gateport;
    135 	else
    136 		port = ftpport;
    137 	if (argc > 2)
    138 		port = strdup(argv[2]);
    139 
    140 	if (gatemode) {
    141 		if (gateserver == NULL || *gateserver == '\0')
    142 			errx(1, "gateserver not defined (shouldn't happen)");
    143 		host = hookup(gateserver, port);
    144 	} else
    145 		host = hookup(argv[1], port);
    146 
    147 	if (host) {
    148 		int overbose;
    149 
    150 		if (gatemode && verbose) {
    151 			fprintf(ttyout,
    152 			    "Connecting via pass-through server %s\n",
    153 			    gateserver);
    154 		}
    155 
    156 		connected = 1;
    157 		/*
    158 		 * Set up defaults for FTP.
    159 		 */
    160 		(void)strlcpy(typename, "ascii", sizeof(typename));
    161 		type = TYPE_A;
    162 		curtype = TYPE_A;
    163 		(void)strlcpy(formname, "non-print", sizeof(formname));
    164 		form = FORM_N;
    165 		(void)strlcpy(modename, "stream", sizeof(modename));
    166 		mode = MODE_S;
    167 		(void)strlcpy(structname, "file", sizeof(structname));
    168 		stru = STRU_F;
    169 		(void)strlcpy(bytename, "8", sizeof(bytename));
    170 		bytesize = 8;
    171 		if (autologin)
    172 			(void)ftp_login(argv[1], NULL, NULL);
    173 
    174 		overbose = verbose;
    175 		if (debug == 0)
    176 			verbose = -1;
    177 		if (command("SYST") == COMPLETE && overbose) {
    178 			char *cp, c;
    179 			c = 0;
    180 			cp = strchr(reply_string + 4, ' ');
    181 			if (cp == NULL)
    182 				cp = strchr(reply_string + 4, '\r');
    183 			if (cp) {
    184 				if (cp[-1] == '.')
    185 					cp--;
    186 				c = *cp;
    187 				*cp = '\0';
    188 			}
    189 
    190 			fprintf(ttyout, "Remote system type is %s.\n",
    191 			    reply_string + 4);
    192 			if (cp)
    193 				*cp = c;
    194 		}
    195 		if (!strncmp(reply_string, "215 UNIX Type: L8", 17)) {
    196 			if (proxy)
    197 				unix_proxy = 1;
    198 			else
    199 				unix_server = 1;
    200 			/*
    201 			 * Set type to 0 (not specified by user),
    202 			 * meaning binary by default, but don't bother
    203 			 * telling server.  We can use binary
    204 			 * for text files unless changed by the user.
    205 			 */
    206 			type = 0;
    207 			(void)strlcpy(typename, "binary", sizeof(typename));
    208 			if (overbose)
    209 			    fprintf(ttyout,
    210 				"Using %s mode to transfer files.\n",
    211 				typename);
    212 		} else {
    213 			if (proxy)
    214 				unix_proxy = 0;
    215 			else
    216 				unix_server = 0;
    217 			if (overbose &&
    218 			    !strncmp(reply_string, "215 TOPS20", 10))
    219 				fputs(
    220 "Remember to set tenex mode when transferring binary files from this machine.\n",
    221 				    ttyout);
    222 		}
    223 		verbose = overbose;
    224 	}
    225 }
    226 
    227 /*
    228  * login to remote host, using given username & password if supplied
    229  */
    230 int
    231 ftp_login(host, user, pass)
    232 	const char *host;
    233 	const char *user, *pass;
    234 {
    235 	char tmp[80];
    236 	const char *acct;
    237 	struct passwd *pw;
    238 	int n, aflag, rval, freeuser, freepass, freeacct, len;
    239 
    240 	acct = NULL;
    241 	aflag = rval = freeuser = freepass = freeacct = 0;
    242 
    243 	/*
    244 	 * Set up arguments for an anonymous FTP session, if necessary.
    245 	 */
    246 	if (anonftp) {
    247 		/*
    248 		 * Set up anonymous login password.
    249 		 */
    250 		if ((pass = getenv("FTPANONPASS")) == NULL) {
    251 			char *anonpass;
    252 
    253 			if ((pass = getlogin()) == NULL) {
    254 				if ((pw = getpwuid(getuid())) == NULL)
    255 					pass = "anonymous";
    256 				else
    257 					pass = pw->pw_name;
    258 			}
    259 			/*
    260 			 * Every anonymous FTP server I've encountered
    261 			 * will accept the string "username@", and will
    262 			 * append the hostname itself.  We do this by default
    263 			 * since many servers are picky about not having
    264 			 * a FQDN in the anonymous password.
    265 			 * - thorpej (at) netbsd.org
    266 			 */
    267 			len = strlen(pass) + 2;
    268 			anonpass = xmalloc(len);
    269 			(void)strlcpy(anonpass, pass, len);
    270 			(void)strlcat(anonpass, "@",  len);
    271 			pass = anonpass;
    272 			freepass = 1;
    273 		}
    274 		user = "anonymous";	/* as per RFC 1635 */
    275 	}
    276 
    277 	if (user == NULL)
    278 		freeuser = 1;
    279 	if (pass == NULL)
    280 		freepass = 1;
    281 	freeacct = 1;
    282 	if (ruserpass(host, &user, &pass, &acct) < 0) {
    283 		code = -1;
    284 		goto cleanup_ftp_login;
    285 	}
    286 
    287 	while (user == NULL) {
    288 		const char *myname = getlogin();
    289 
    290 		if (myname == NULL && (pw = getpwuid(getuid())) != NULL)
    291 			myname = pw->pw_name;
    292 		if (myname)
    293 			fprintf(ttyout, "Name (%s:%s): ", host, myname);
    294 		else
    295 			fprintf(ttyout, "Name (%s): ", host);
    296 		*tmp = '\0';
    297 		if (fgets(tmp, sizeof(tmp) - 1, stdin) == NULL) {
    298 			fprintf(ttyout, "\nEOF received; login aborted.\n");
    299 			clearerr(stdin);
    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(0);
    389 	}
    390 	fprintf(ttyout, "(%s) ", prompt);
    391 	line[len++] = ' ';
    392 	if (fgets(&line[len], sizeof(line) - len, stdin) == NULL) {
    393 		clearerr(stdin);
    394 		intr(0);
    395 	}
    396 	len += strlen(&line[len]);
    397 	if (len > 0 && line[len - 1] == '\n')
    398 		line[len - 1] = '\0';
    399 	makeargv();
    400 	ret = margc > *pargc;
    401 	*pargc = margc;
    402 	*pargv = margv;
    403 	return (ret);
    404 }
    405 
    406 /*
    407  * glob files given in argv[] from the remote server.
    408  * if errbuf isn't NULL, store error messages there instead
    409  * of writing to the screen.
    410  */
    411 char *
    412 remglob(argv, doswitch, errbuf)
    413         char *argv[];
    414         int doswitch;
    415 	char **errbuf;
    416 {
    417         char temp[MAXPATHLEN];
    418         static char buf[MAXPATHLEN];
    419         static FILE *ftemp = NULL;
    420         static char **args;
    421         int oldverbose, oldhash, fd, len;
    422         char *cp, *mode;
    423 
    424         if (!mflag) {
    425                 if (!doglob)
    426                         args = NULL;
    427                 else {
    428                         if (ftemp) {
    429                                 (void)fclose(ftemp);
    430                                 ftemp = NULL;
    431                         }
    432                 }
    433                 return (NULL);
    434         }
    435         if (!doglob) {
    436                 if (args == NULL)
    437                         args = argv;
    438                 if ((cp = *++args) == NULL)
    439                         args = NULL;
    440                 return (cp);
    441         }
    442         if (ftemp == NULL) {
    443 		len = strlcpy(temp, tmpdir, sizeof(temp));
    444 		if (temp[len - 1] != '/')
    445 			(void)strlcat(temp, "/", sizeof(temp));
    446 		(void)strlcat(temp, TMPFILE, sizeof(temp));
    447                 if ((fd = mkstemp(temp)) < 0) {
    448                         warn("unable to create temporary file %s", temp);
    449                         return (NULL);
    450                 }
    451                 close(fd);
    452                 oldverbose = verbose;
    453 		verbose = (errbuf != NULL) ? -1 : 0;
    454                 oldhash = hash;
    455                 hash = 0;
    456                 if (doswitch)
    457                         pswitch(!proxy);
    458                 for (mode = "w"; *++argv != NULL; mode = "a")
    459                         recvrequest("NLST", temp, *argv, mode, 0, 0);
    460 		if ((code / 100) != COMPLETE) {
    461 			if (errbuf != NULL)
    462 				*errbuf = reply_string;
    463 		}
    464                 if (doswitch)
    465                         pswitch(!proxy);
    466                 verbose = oldverbose;
    467 		hash = oldhash;
    468                 ftemp = fopen(temp, "r");
    469                 (void)unlink(temp);
    470                 if (ftemp == NULL) {
    471 			if (errbuf == NULL)
    472 				fputs(
    473 				    "can't find list of remote files, oops.\n",
    474 				    ttyout);
    475 			else
    476 				*errbuf =
    477 				    "can't find list of remote files, oops.";
    478                         return (NULL);
    479                 }
    480         }
    481         if (fgets(buf, sizeof(buf), ftemp) == NULL) {
    482                 (void)fclose(ftemp);
    483 		ftemp = NULL;
    484                 return (NULL);
    485         }
    486         if ((cp = strchr(buf, '\n')) != NULL)
    487                 *cp = '\0';
    488         return (buf);
    489 }
    490 
    491 /*
    492  * Glob a local file name specification with the expectation of a single
    493  * return value. Can't control multiple values being expanded from the
    494  * expression, we return only the first.
    495  * Returns NULL on error, or a pointer to a buffer containing the filename
    496  * that's the caller's responsiblity to free(3) when finished with.
    497  */
    498 char *
    499 globulize(pattern)
    500 	const char *pattern;
    501 {
    502 	glob_t gl;
    503 	int flags;
    504 	char *p;
    505 
    506 	if (!doglob)
    507 		return (xstrdup(pattern));
    508 
    509 	flags = GLOB_BRACE|GLOB_NOCHECK|GLOB_TILDE;
    510 	memset(&gl, 0, sizeof(gl));
    511 	if (glob(pattern, flags, NULL, &gl) || gl.gl_pathc == 0) {
    512 		warnx("%s: not found", pattern);
    513 		globfree(&gl);
    514 		return (NULL);
    515 	}
    516 	p = xstrdup(gl.gl_pathv[0]);
    517 	globfree(&gl);
    518 	return (p);
    519 }
    520 
    521 /*
    522  * determine size of remote file
    523  */
    524 off_t
    525 remotesize(file, noisy)
    526 	const char *file;
    527 	int noisy;
    528 {
    529 	int overbose;
    530 	off_t size;
    531 
    532 	overbose = verbose;
    533 	size = -1;
    534 	if (debug == 0)
    535 		verbose = -1;
    536 	if (command("SIZE %s", file) == COMPLETE) {
    537 		char *cp, *ep;
    538 
    539 		cp = strchr(reply_string, ' ');
    540 		if (cp != NULL) {
    541 			cp++;
    542 #ifndef NO_QUAD
    543 			size = strtoq(cp, &ep, 10);
    544 #else
    545 			size = strtol(cp, &ep, 10);
    546 #endif
    547 			if (*ep != '\0' && !isspace((unsigned char)*ep))
    548 				size = -1;
    549 		}
    550 	} else if (noisy && debug == 0) {
    551 		fputs(reply_string, ttyout);
    552 		putc('\n', ttyout);
    553 	}
    554 	verbose = overbose;
    555 	return (size);
    556 }
    557 
    558 /*
    559  * determine last modification time (in GMT) of remote file
    560  */
    561 time_t
    562 remotemodtime(file, noisy)
    563 	const char *file;
    564 	int noisy;
    565 {
    566 	int overbose;
    567 	time_t rtime;
    568 	int ocode;
    569 
    570 	overbose = verbose;
    571 	ocode = code;
    572 	rtime = -1;
    573 	if (debug == 0)
    574 		verbose = -1;
    575 	if (command("MDTM %s", file) == COMPLETE) {
    576 		struct tm timebuf;
    577 		int yy, mo, day, hour, min, sec;
    578 		sscanf(reply_string, "%*s %04d%02d%02d%02d%02d%02d", &yy, &mo,
    579 			&day, &hour, &min, &sec);
    580 		memset(&timebuf, 0, sizeof(timebuf));
    581 		timebuf.tm_sec = sec;
    582 		timebuf.tm_min = min;
    583 		timebuf.tm_hour = hour;
    584 		timebuf.tm_mday = day;
    585 		timebuf.tm_mon = mo - 1;
    586 		timebuf.tm_year = yy - TM_YEAR_BASE;
    587 		timebuf.tm_isdst = -1;
    588 		rtime = timegm(&timebuf);
    589 		if (rtime == -1 && (noisy || debug != 0))
    590 			fprintf(ttyout, "Can't convert %s to a time.\n",
    591 			    reply_string);
    592 	} else if (noisy && debug == 0) {
    593 		fputs(reply_string, ttyout);
    594 		putc('\n', ttyout);
    595 	}
    596 	verbose = overbose;
    597 	if (rtime == -1)
    598 		code = ocode;
    599 	return (rtime);
    600 }
    601 
    602 #ifndef	NO_PROGRESS
    603 
    604 /*
    605  * return non-zero if we're the current foreground process
    606  */
    607 int
    608 foregroundproc()
    609 {
    610 	static pid_t pgrp = -1;
    611 
    612 	if (pgrp == -1)
    613 		pgrp = getpgrp();
    614 
    615 	return (tcgetpgrp(fileno(ttyout)) == pgrp);
    616 }
    617 
    618 
    619 static void updateprogressmeter __P((int));
    620 
    621 static void
    622 updateprogressmeter(dummy)
    623 	int dummy;
    624 {
    625 	int oerrno = errno;
    626 
    627 	progressmeter(0);
    628 	errno = oerrno;
    629 }
    630 #endif	/* NO_PROGRESS */
    631 
    632 
    633 /*
    634  * List of order of magnitude prefixes.
    635  * The last is `P', as 2^64 = 16384 Petabytes
    636  */
    637 static const char prefixes[] = " KMGTP";
    638 
    639 /*
    640  * Display a transfer progress bar if progress is non-zero.
    641  * SIGALRM is hijacked for use by this function.
    642  * - Before the transfer, set filesize to size of file (or -1 if unknown),
    643  *   and call with flag = -1. This starts the once per second timer,
    644  *   and a call to updateprogressmeter() upon SIGALRM.
    645  * - During the transfer, updateprogressmeter will call progressmeter
    646  *   with flag = 0
    647  * - After the transfer, call with flag = 1
    648  */
    649 static struct timeval start;
    650 static struct timeval lastupdate;
    651 
    652 #define BUFLEFT	(sizeof(buf) - len)
    653 
    654 void
    655 progressmeter(flag)
    656 	int flag;
    657 {
    658 	static off_t lastsize;
    659 #ifndef NO_PROGRESS
    660 	struct timeval now, td, wait;
    661 	off_t cursize, abbrevsize, bytespersec;
    662 	double elapsed;
    663 	int ratio, barlength, i, len, remaining;
    664 
    665 			/*
    666 			 * Work variables for progress bar.
    667 			 *
    668 			 * XXX:	if the format of the progress bar changes
    669 			 *	(especially the number of characters in the
    670 			 *	`static' portion of it), be sure to update
    671 			 *	these appropriately.
    672 			 */
    673 	char		buf[256];	/* workspace for progress bar */
    674 #define BAROVERHEAD	43		/* non `*' portion of progress bar */
    675 					/*
    676 					 * stars should contain at least
    677 					 * sizeof(buf) - BAROVERHEAD entries
    678 					 */
    679 	const char	stars[] =
    680 "*****************************************************************************"
    681 "*****************************************************************************"
    682 "*****************************************************************************";
    683 
    684 #endif
    685 
    686 	if (flag == -1) {
    687 		(void)gettimeofday(&start, NULL);
    688 		lastupdate = start;
    689 		lastsize = restart_point;
    690 	}
    691 #ifndef NO_PROGRESS
    692 	len = 0;
    693 	if (!progress || filesize <= 0)
    694 		return;
    695 
    696 	(void)gettimeofday(&now, NULL);
    697 	cursize = bytes + restart_point;
    698 	timersub(&now, &lastupdate, &wait);
    699 	if (cursize > lastsize) {
    700 		lastupdate = now;
    701 		lastsize = cursize;
    702 		wait.tv_sec = 0;
    703 	}
    704 
    705 	/*
    706 	 * print progress bar only if we are foreground process.
    707 	 */
    708 	if (! foregroundproc())
    709 		return;
    710 
    711 	ratio = (int)((double)cursize * 100.0 / (double)filesize);
    712 	ratio = MAX(ratio, 0);
    713 	ratio = MIN(ratio, 100);
    714 	len += snprintf(buf + len, BUFLEFT, "\r%3d%% ", ratio);
    715 
    716 			/*
    717 			 * calculate the length of the `*' bar, ensuring that
    718 			 * the number of stars won't exceed the buffer size
    719 			 */
    720 	barlength = MIN(sizeof(buf) - 1, ttywidth) - BAROVERHEAD;
    721 	if (barlength > 0) {
    722 		i = barlength * ratio / 100;
    723 		len += snprintf(buf + len, BUFLEFT,
    724 		    "|%.*s%*s|", i, stars, barlength - i, "");
    725 	}
    726 
    727 	abbrevsize = cursize;
    728 	for (i = 0; abbrevsize >= 100000 && i < sizeof(prefixes); i++)
    729 		abbrevsize >>= 10;
    730 	len += snprintf(buf + len, BUFLEFT,
    731 #ifndef NO_QUAD
    732 	    " %5lld %c%c ", (long long)abbrevsize,
    733 #else
    734 	    " %5ld %c%c ", (long)abbrevsize,
    735 #endif
    736 	    prefixes[i],
    737 	    i == 0 ? ' ' : 'B');
    738 
    739 	timersub(&now, &start, &td);
    740 	elapsed = td.tv_sec + (td.tv_usec / 1000000.0);
    741 
    742 	bytespersec = 0;
    743 	if (bytes > 0) {
    744 		bytespersec = bytes;
    745 		if (elapsed > 0.0)
    746 			bytespersec /= elapsed;
    747 	}
    748 	for (i = 1; bytespersec >= 1024000 && i < sizeof(prefixes); i++)
    749 		bytespersec >>= 10;
    750 	len += snprintf(buf + len, BUFLEFT,
    751 #ifndef NO_QUAD
    752 	    " %3lld.%02d %cB/s ", (long long)bytespersec / 1024,
    753 #else
    754 	    " %3ld.%02d %cB/s ", (long)bytespersec / 1024,
    755 #endif
    756 	    (int)((bytespersec % 1024) * 100 / 1024),
    757 	    prefixes[i]);
    758 
    759 	if (bytes <= 0 || elapsed <= 0.0 || cursize > filesize) {
    760 		len += snprintf(buf + len, BUFLEFT, "   --:-- ETA");
    761 	} else if (wait.tv_sec >= STALLTIME) {
    762 		len += snprintf(buf + len, BUFLEFT, " - stalled -");
    763 	} else {
    764 		remaining = (int)
    765 		    ((filesize - restart_point) / (bytes / elapsed) - elapsed);
    766 		if (remaining >= 100 * SECSPERHOUR)
    767 			len += snprintf(buf + len, BUFLEFT, "   --:-- ETA");
    768 		else {
    769 			i = remaining / SECSPERHOUR;
    770 			if (i)
    771 				len += snprintf(buf + len, BUFLEFT, "%2d:", i);
    772 			else
    773 				len += snprintf(buf + len, BUFLEFT, "   ");
    774 			i = remaining % SECSPERHOUR;
    775 			len += snprintf(buf + len, BUFLEFT,
    776 			    "%02d:%02d ETA", i / 60, i % 60);
    777 		}
    778 	}
    779 	if (flag == 1)
    780 		len += snprintf(buf + len, BUFLEFT, "\n");
    781 	(void)write(fileno(ttyout), buf, len);
    782 
    783 	if (flag == -1) {
    784 		(void)xsignal_restart(SIGALRM, updateprogressmeter, 1);
    785 		alarmtimer(1);		/* set alarm timer for 1 Hz */
    786 	} else if (flag == 1) {
    787 		(void)xsignal(SIGALRM, SIG_DFL);
    788 		alarmtimer(0);
    789 	}
    790 #endif	/* !NO_PROGRESS */
    791 }
    792 
    793 /*
    794  * Display transfer statistics.
    795  * Requires start to be initialised by progressmeter(-1),
    796  * direction to be defined by xfer routines, and filesize and bytes
    797  * to be updated by xfer routines
    798  * If siginfo is nonzero, an ETA is displayed, and the output goes to stderr
    799  * instead of ttyout.
    800  */
    801 void
    802 ptransfer(siginfo)
    803 	int siginfo;
    804 {
    805 	struct timeval now, td, wait;
    806 	double elapsed;
    807 	off_t bytespersec;
    808 	int remaining, hh, i, len;
    809 
    810 	char buf[256];		/* Work variable for transfer status. */
    811 
    812 	if (!verbose && !progress && !siginfo)
    813 		return;
    814 
    815 	(void)gettimeofday(&now, NULL);
    816 	timersub(&now, &start, &td);
    817 	elapsed = td.tv_sec + (td.tv_usec / 1000000.0);
    818 	bytespersec = 0;
    819 	if (bytes > 0) {
    820 		bytespersec = bytes;
    821 		if (elapsed > 0.0)
    822 			bytespersec /= elapsed;
    823 	}
    824 	len = 0;
    825 	len += snprintf(buf + len, BUFLEFT,
    826 #ifndef NO_QUAD
    827 	    "%lld byte%s %s in ", (long long)bytes,
    828 #else
    829 	    "%ld byte%s %s in ", (long)bytes,
    830 #endif
    831 	    bytes == 1 ? "" : "s", direction);
    832 	remaining = (int)elapsed;
    833 	if (remaining > SECSPERDAY) {
    834 		int days;
    835 
    836 		days = remaining / SECSPERDAY;
    837 		remaining %= SECSPERDAY;
    838 		len += snprintf(buf + len, BUFLEFT,
    839 		    "%d day%s ", days, days == 1 ? "" : "s");
    840 	}
    841 	hh = remaining / SECSPERHOUR;
    842 	remaining %= SECSPERHOUR;
    843 	if (hh)
    844 		len += snprintf(buf + len, BUFLEFT, "%2d:", hh);
    845 	len += snprintf(buf + len, BUFLEFT,
    846 	    "%02d:%02d ", remaining / 60, remaining % 60);
    847 
    848 	for (i = 1; bytespersec >= 1024000 && i < sizeof(prefixes); i++)
    849 		bytespersec >>= 10;
    850 	len += snprintf(buf + len, BUFLEFT,
    851 #ifndef NO_QUAD
    852 	    "(%lld.%02d %cB/s)", (long long)bytespersec / 1024,
    853 #else
    854 	    "(%ld.%02d %cB/s)", (long)bytespersec / 1024,
    855 #endif
    856 	    (int)((bytespersec % 1024) * 100 / 1024),
    857 	    prefixes[i]);
    858 
    859 	if (siginfo && bytes > 0 && elapsed > 0.0 && filesize >= 0
    860 	    && bytes + restart_point <= filesize) {
    861 		remaining = (int)((filesize - restart_point) /
    862 				  (bytes / elapsed) - elapsed);
    863 		hh = remaining / SECSPERHOUR;
    864 		remaining %= SECSPERHOUR;
    865 		len += snprintf(buf + len, BUFLEFT, "  ETA: ");
    866 		if (hh)
    867 			len += snprintf(buf + len, BUFLEFT, "%2d:", hh);
    868 		len += snprintf(buf + len, BUFLEFT, "%02d:%02d",
    869 		    remaining / 60, remaining % 60);
    870 		timersub(&now, &lastupdate, &wait);
    871 		if (wait.tv_sec >= STALLTIME)
    872 			len += snprintf(buf + len, BUFLEFT, "  (stalled)");
    873 	}
    874 	len += snprintf(buf + len, BUFLEFT, "\n");
    875 	(void)write(siginfo ? STDERR_FILENO : fileno(ttyout), buf, len);
    876 }
    877 
    878 /*
    879  * Print transfer stats if a transfer is in progress
    880  */
    881 void
    882 psummary(notused)
    883 	int notused;
    884 {
    885 	int oerrno = errno;
    886 
    887 	if (bytes > 0) {
    888 		if (fromatty)
    889 			write(fileno(ttyout), "\n", 1);
    890 		ptransfer(1);
    891 	}
    892 	errno = oerrno;
    893 }
    894 
    895 /*
    896  * List words in stringlist, vertically arranged
    897  */
    898 void
    899 list_vertical(sl)
    900 	StringList *sl;
    901 {
    902 	int i, j, w;
    903 	int columns, width, lines, items;
    904 	char *p;
    905 
    906 	width = items = 0;
    907 
    908 	for (i = 0 ; i < sl->sl_cur ; i++) {
    909 		w = strlen(sl->sl_str[i]);
    910 		if (w > width)
    911 			width = w;
    912 	}
    913 	width = (width + 8) &~ 7;
    914 
    915 	columns = ttywidth / width;
    916 	if (columns == 0)
    917 		columns = 1;
    918 	lines = (sl->sl_cur + columns - 1) / columns;
    919 	for (i = 0; i < lines; i++) {
    920 		for (j = 0; j < columns; j++) {
    921 			p = sl->sl_str[j * lines + i];
    922 			if (p)
    923 				fputs(p, ttyout);
    924 			if (j * lines + i + lines >= sl->sl_cur) {
    925 				putc('\n', ttyout);
    926 				break;
    927 			}
    928 			w = strlen(p);
    929 			while (w < width) {
    930 				w = (w + 8) &~ 7;
    931 				(void)putc('\t', ttyout);
    932 			}
    933 		}
    934 	}
    935 }
    936 
    937 /*
    938  * Update the global ttywidth value, using TIOCGWINSZ.
    939  */
    940 void
    941 setttywidth(a)
    942 	int a;
    943 {
    944 	struct winsize winsize;
    945 	int oerrno = errno;
    946 
    947 	if (ioctl(fileno(ttyout), TIOCGWINSZ, &winsize) != -1 &&
    948 	    winsize.ws_col != 0)
    949 		ttywidth = winsize.ws_col;
    950 	else
    951 		ttywidth = 80;
    952 	errno = oerrno;
    953 }
    954 
    955 /*
    956  * Change the rate limit up (SIGUSR1) or down (SIGUSR2)
    957  */
    958 void
    959 crankrate(sig)
    960 	int sig;
    961 {
    962 
    963 	switch (sig) {
    964 	case SIGUSR1:
    965 		if (rate_get)
    966 			rate_get += rate_get_incr;
    967 		if (rate_put)
    968 			rate_put += rate_put_incr;
    969 		break;
    970 	case SIGUSR2:
    971 		if (rate_get && rate_get > rate_get_incr)
    972 			rate_get -= rate_get_incr;
    973 		if (rate_put && rate_put > rate_put_incr)
    974 			rate_put -= rate_put_incr;
    975 		break;
    976 	default:
    977 		err(1, "crankrate invoked with unknown signal: %d", sig);
    978 	}
    979 }
    980 
    981 
    982 /*
    983  * Set the SIGALRM interval timer for wait seconds, 0 to disable.
    984  */
    985 void
    986 alarmtimer(wait)
    987 	int wait;
    988 {
    989 	struct itimerval itv;
    990 
    991 	itv.it_value.tv_sec = wait;
    992 	itv.it_value.tv_usec = 0;
    993 	itv.it_interval = itv.it_value;
    994 	setitimer(ITIMER_REAL, &itv, NULL);
    995 }
    996 
    997 /*
    998  * Setup or cleanup EditLine structures
    999  */
   1000 #ifndef NO_EDITCOMPLETE
   1001 void
   1002 controlediting()
   1003 {
   1004 	if (editing && el == NULL && hist == NULL) {
   1005 		HistEvent ev;
   1006 		int editmode;
   1007 
   1008 		el = el_init(__progname, stdin, ttyout, stderr);
   1009 		/* init editline */
   1010 		hist = history_init();		/* init the builtin history */
   1011 		history(hist, &ev, H_SETSIZE, 100);/* remember 100 events */
   1012 		el_set(el, EL_HIST, history, hist);	/* use history */
   1013 
   1014 		el_set(el, EL_EDITOR, "emacs");	/* default editor is emacs */
   1015 		el_set(el, EL_PROMPT, prompt);	/* set the prompt function */
   1016 
   1017 		/* add local file completion, bind to TAB */
   1018 		el_set(el, EL_ADDFN, "ftp-complete",
   1019 		    "Context sensitive argument completion",
   1020 		    complete);
   1021 		el_set(el, EL_BIND, "^I", "ftp-complete", NULL);
   1022 		el_source(el, NULL);	/* read ~/.editrc */
   1023 		if ((el_get(el, EL_EDITMODE, &editmode) != -1) && editmode == 0)
   1024 			editing = 0;	/* the user doesn't want editing,
   1025 					 * so disable, and let statement
   1026 					 * below cleanup */
   1027 		else
   1028 			el_set(el, EL_SIGNAL, 1);
   1029 	}
   1030 	if (!editing) {
   1031 		if (hist) {
   1032 			history_end(hist);
   1033 			hist = NULL;
   1034 		}
   1035 		if (el) {
   1036 			el_end(el);
   1037 			el = NULL;
   1038 		}
   1039 	}
   1040 }
   1041 #endif /* !NO_EDITCOMPLETE */
   1042 
   1043 /*
   1044  * Convert the string `arg' to an int, which may have an optional SI suffix
   1045  * (`b', `k', `m', `g'). Returns the number for success, -1 otherwise.
   1046  */
   1047 int
   1048 strsuftoi(arg)
   1049 	const char *arg;
   1050 {
   1051 	char *cp;
   1052 	long val;
   1053 
   1054 	if (!isdigit((unsigned char)arg[0]))
   1055 		return (-1);
   1056 
   1057 	val = strtol(arg, &cp, 10);
   1058 	if (cp != NULL) {
   1059 		if (cp[0] != '\0' && cp[1] != '\0')
   1060 			 return (-1);
   1061 		switch (tolower((unsigned char)cp[0])) {
   1062 		case '\0':
   1063 		case 'b':
   1064 			break;
   1065 		case 'k':
   1066 			val <<= 10;
   1067 			break;
   1068 		case 'm':
   1069 			val <<= 20;
   1070 			break;
   1071 		case 'g':
   1072 			val <<= 30;
   1073 			break;
   1074 		default:
   1075 			return (-1);
   1076 		}
   1077 	}
   1078 	if (val < 0 || val > INT_MAX)
   1079 		return (-1);
   1080 
   1081 	return (val);
   1082 }
   1083 
   1084 /*
   1085  * Set up socket buffer sizes before a connection is made.
   1086  */
   1087 void
   1088 setupsockbufsize(sock)
   1089 	int sock;
   1090 {
   1091 
   1092 	if (setsockopt(sock, SOL_SOCKET, SO_SNDBUF, (void *) &sndbuf_size,
   1093 	    sizeof(rcvbuf_size)) < 0)
   1094 		warn("unable to set sndbuf size %d", sndbuf_size);
   1095 
   1096 	if (setsockopt(sock, SOL_SOCKET, SO_RCVBUF, (void *) &rcvbuf_size,
   1097 	    sizeof(rcvbuf_size)) < 0)
   1098 		warn("unable to set rcvbuf size %d", rcvbuf_size);
   1099 }
   1100 
   1101 void
   1102 ftpvis(dst, dstlen, src, srclen)
   1103 	char		*dst;
   1104 	size_t		 dstlen;
   1105 	const char	*src;
   1106 	size_t		 srclen;
   1107 {
   1108 	int	di, si;
   1109 
   1110 	for (di = si = 0;
   1111 	    src[si] != '\0' && di < dstlen && si < srclen;
   1112 	    di++, si++) {
   1113 		switch (src[si]) {
   1114 		case '\\':
   1115 		case ' ':
   1116 		case '\t':
   1117 		case '\r':
   1118 		case '\n':
   1119 		case '"':
   1120 			dst[di++] = '\\';
   1121 			if (di >= dstlen)
   1122 				break;
   1123 			/* FALLTHROUGH */
   1124 		default:
   1125 			dst[di] = src[si];
   1126 		}
   1127 	}
   1128 	dst[di] = '\0';
   1129 }
   1130 
   1131 /*
   1132  * Determine if given string is an IPv6 address or not.
   1133  * Return 1 for yes, 0 for no
   1134  */
   1135 int
   1136 isipv6addr(addr)
   1137 	const char *addr;
   1138 {
   1139 	int rv = 0;
   1140 #ifdef INET6
   1141 	u_char buf[16];		/* XXX: sizeof(struct in_addr6) */
   1142 
   1143 	rv = inet_pton(AF_INET6, addr, &buf);
   1144 	if (debug)
   1145 		fprintf(ttyout, "isipv6addr: got %d for %s\n", rv, addr);
   1146 #endif
   1147 	return rv;
   1148 }
   1149 
   1150 
   1151 /*
   1152  * Internal version of connect(2); sets socket buffer sizes first.
   1153  */
   1154 int
   1155 xconnect(sock, name, namelen)
   1156 	int sock;
   1157 	const struct sockaddr *name;
   1158 	int namelen;
   1159 {
   1160 
   1161 	setupsockbufsize(sock);
   1162 	return (connect(sock, name, namelen));
   1163 }
   1164 
   1165 /*
   1166  * Internal version of listen(2); sets socket buffer sizes first.
   1167  */
   1168 int
   1169 xlisten(sock, backlog)
   1170 	int sock, backlog;
   1171 {
   1172 
   1173 	setupsockbufsize(sock);
   1174 	return (listen(sock, backlog));
   1175 }
   1176 
   1177 void *
   1178 xmalloc(size)
   1179 	size_t size;
   1180 {
   1181 	void *p;
   1182 
   1183 	p = malloc(size);
   1184 	if (p == NULL)
   1185 		err(1, "Unable to allocate %ld bytes of memory", (long)size);
   1186 	return (p);
   1187 }
   1188 
   1189 char *
   1190 xstrdup(str)
   1191 	const char *str;
   1192 {
   1193 	char *s;
   1194 
   1195 	if (str == NULL)
   1196 		errx(1, "xstrdup() called with NULL argument");
   1197 	s = strdup(str);
   1198 	if (s == NULL)
   1199 		err(1, "Unable to allocate memory for string copy");
   1200 	return (s);
   1201 }
   1202 
   1203 sig_t
   1204 xsignal_restart(sig, func, restartable)
   1205 	int sig;
   1206 	void (*func) __P((int));
   1207 	int restartable;
   1208 {
   1209 	struct sigaction act, oact;
   1210 	act.sa_handler = func;
   1211 
   1212 	sigemptyset(&act.sa_mask);
   1213 #if defined(SA_RESTART)			/* 4.4BSD, Posix(?), SVR4 */
   1214 	act.sa_flags = restartable ? SA_RESTART : 0;
   1215 #elif defined(SA_INTERRUPT)		/* SunOS 4.x */
   1216 	act.sa_flags = restartable ? 0 : SA_INTERRUPT;
   1217 #else
   1218 #error "system must have SA_RESTART or SA_INTERRUPT"
   1219 #endif
   1220 	if (sigaction(sig, &act, &oact) < 0)
   1221 		return (SIG_ERR);
   1222 	return (oact.sa_handler);
   1223 }
   1224 
   1225 sig_t
   1226 xsignal(sig, func)
   1227 	int sig;
   1228 	void (*func) __P((int));
   1229 {
   1230 	int restartable;
   1231 
   1232 	/*
   1233 	 * Some signals print output or change the state of the process.
   1234 	 * There should be restartable, so that reads and writes are
   1235 	 * not affected.  Some signals should cause program flow to change;
   1236 	 * these signals should not be restartable, so that the system call
   1237 	 * will return with EINTR, and the program will go do something
   1238 	 * different.  If the signal handler calls longjmp() or siglongjmp(),
   1239 	 * it doesn't matter if it's restartable.
   1240 	 */
   1241 
   1242 	switch(sig) {
   1243 #ifdef SIGINFO
   1244 	case SIGINFO:
   1245 #endif
   1246 	case SIGQUIT:
   1247 	case SIGUSR1:
   1248 	case SIGUSR2:
   1249 	case SIGWINCH:
   1250 		restartable = 1;
   1251 		break;
   1252 
   1253 	case SIGALRM:
   1254 	case SIGINT:
   1255 	case SIGPIPE:
   1256 		restartable = 0;
   1257 		break;
   1258 
   1259 	default:
   1260 		/*
   1261 		 * This is unpleasant, but I don't know what would be better.
   1262 		 * Right now, this "can't happen"
   1263 		 */
   1264 		errx(1, "xsignal_restart called with signal %d\n",
   1265 		sig);
   1266 	}
   1267 
   1268 	return(xsignal_restart(sig, func, restartable));
   1269 }
   1270