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