Home | History | Annotate | Line # | Download | only in ftp
util.c revision 1.75
      1 /*	$NetBSD: util.c,v 1.75 1999/10/09 03:00:56 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.75 1999/10/09 03:00:56 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 			code = -1;
    300 			goto cleanup_ftp_login;
    301 		}
    302 		tmp[strlen(tmp) - 1] = '\0';
    303 		freeuser = 0;
    304 		if (*tmp == '\0')
    305 			user = myname;
    306 		else
    307 			user = tmp;
    308 	}
    309 
    310 	if (gatemode) {
    311 		char *nuser;
    312 		int len;
    313 
    314 		len = strlen(user) + 1 + strlen(host) + 1;
    315 		nuser = xmalloc(len);
    316 		(void)strlcpy(nuser, user, len);
    317 		(void)strlcat(nuser, "@",  len);
    318 		(void)strlcat(nuser, host, len);
    319 		freeuser = 1;
    320 		user = nuser;
    321 	}
    322 
    323 	n = command("USER %s", user);
    324 	if (n == CONTINUE) {
    325 		if (pass == NULL) {
    326 			freepass = 0;
    327 			pass = getpass("Password:");
    328 		}
    329 		n = command("PASS %s", pass);
    330 	}
    331 	if (n == CONTINUE) {
    332 		aflag++;
    333 		if (acct == NULL) {
    334 			freeacct = 0;
    335 			acct = getpass("Account:");
    336 		}
    337 		if (acct[0] == '\0') {
    338 			warnx("Login failed.");
    339 			goto cleanup_ftp_login;
    340 		}
    341 		n = command("ACCT %s", acct);
    342 	}
    343 	if ((n != COMPLETE) ||
    344 	    (!aflag && acct != NULL && command("ACCT %s", acct) != COMPLETE)) {
    345 		warnx("Login failed.");
    346 		goto cleanup_ftp_login;
    347 	}
    348 	rval = 1;
    349 	if (proxy)
    350 		goto cleanup_ftp_login;
    351 
    352 	connected = -1;
    353 	for (n = 0; n < macnum; ++n) {
    354 		if (!strcmp("init", macros[n].mac_name)) {
    355 			(void)strlcpy(line, "$init", sizeof(line));
    356 			makeargv();
    357 			domacro(margc, margv);
    358 			break;
    359 		}
    360 	}
    361 cleanup_ftp_login:
    362 	if (user != NULL && freeuser)
    363 		free((char *)user);
    364 	if (pass != NULL && freepass)
    365 		free((char *)pass);
    366 	if (acct != NULL && freeacct)
    367 		free((char *)acct);
    368 	return (rval);
    369 }
    370 
    371 /*
    372  * `another' gets another argument, and stores the new argc and argv.
    373  * It reverts to the top level (via main.c's intr()) on EOF/error.
    374  *
    375  * Returns false if no new arguments have been added.
    376  */
    377 int
    378 another(pargc, pargv, prompt)
    379 	int *pargc;
    380 	char ***pargv;
    381 	const char *prompt;
    382 {
    383 	int len = strlen(line), ret;
    384 
    385 	if (len >= sizeof(line) - 3) {
    386 		fputs("sorry, arguments too long.\n", ttyout);
    387 		intr(0);
    388 	}
    389 	fprintf(ttyout, "(%s) ", prompt);
    390 	line[len++] = ' ';
    391 	if (fgets(&line[len], sizeof(line) - len, stdin) == NULL)
    392 		intr(0);
    393 	len += strlen(&line[len]);
    394 	if (len > 0 && line[len - 1] == '\n')
    395 		line[len - 1] = '\0';
    396 	makeargv();
    397 	ret = margc > *pargc;
    398 	*pargc = margc;
    399 	*pargv = margv;
    400 	return (ret);
    401 }
    402 
    403 /*
    404  * glob files given in argv[] from the remote server.
    405  * if errbuf isn't NULL, store error messages there instead
    406  * of writing to the screen.
    407  */
    408 char *
    409 remglob(argv, doswitch, errbuf)
    410         char *argv[];
    411         int doswitch;
    412 	char **errbuf;
    413 {
    414         char temp[MAXPATHLEN];
    415         static char buf[MAXPATHLEN];
    416         static FILE *ftemp = NULL;
    417         static char **args;
    418         int oldverbose, oldhash, fd, len;
    419         char *cp, *mode;
    420 
    421         if (!mflag) {
    422                 if (!doglob)
    423                         args = NULL;
    424                 else {
    425                         if (ftemp) {
    426                                 (void)fclose(ftemp);
    427                                 ftemp = NULL;
    428                         }
    429                 }
    430                 return (NULL);
    431         }
    432         if (!doglob) {
    433                 if (args == NULL)
    434                         args = argv;
    435                 if ((cp = *++args) == NULL)
    436                         args = NULL;
    437                 return (cp);
    438         }
    439         if (ftemp == NULL) {
    440 		len = strlcpy(temp, tmpdir, sizeof(temp));
    441 		if (temp[len - 1] != '/')
    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 = errno;
    651 
    652 	progressmeter(0);
    653 	errno = oerrno;
    654 }
    655 #endif	/* NO_PROGRESS */
    656 
    657 
    658 /*
    659  * List of order of magnitude prefixes.
    660  * The last is `P', as 2^64 = 16384 Petabytes
    661  */
    662 static const char prefixes[] = " KMGTP";
    663 
    664 /*
    665  * Display a transfer progress bar if progress is non-zero.
    666  * SIGALRM is hijacked for use by this function.
    667  * - Before the transfer, set filesize to size of file (or -1 if unknown),
    668  *   and call with flag = -1. This starts the once per second timer,
    669  *   and a call to updateprogressmeter() upon SIGALRM.
    670  * - During the transfer, updateprogressmeter will call progressmeter
    671  *   with flag = 0
    672  * - After the transfer, call with flag = 1
    673  */
    674 static struct timeval start;
    675 static struct timeval lastupdate;
    676 
    677 #define BUFLEFT	(sizeof(buf) - len)
    678 
    679 void
    680 progressmeter(flag)
    681 	int flag;
    682 {
    683 	static off_t lastsize;
    684 #ifndef NO_PROGRESS
    685 	struct timeval now, td, wait;
    686 	off_t cursize, abbrevsize, bytespersec;
    687 	double elapsed;
    688 	int ratio, barlength, i, len, remaining;
    689 
    690 			/*
    691 			 * Work variables for progress bar.
    692 			 *
    693 			 * XXX:	if the format of the progress bar changes
    694 			 *	(especially the number of characters in the
    695 			 *	`static' portion of it), be sure to update
    696 			 *	these appropriately.
    697 			 */
    698 	char		buf[256];	/* workspace for progress bar */
    699 #define BAROVERHEAD	43		/* non `*' portion of progress bar */
    700 					/*
    701 					 * stars should contain at least
    702 					 * sizeof(buf) - BAROVERHEAD entries
    703 					 */
    704 	const char	stars[] =
    705 "*****************************************************************************"
    706 "*****************************************************************************"
    707 "*****************************************************************************";
    708 
    709 #endif
    710 
    711 	if (flag == -1) {
    712 		(void)gettimeofday(&start, NULL);
    713 		lastupdate = start;
    714 		lastsize = restart_point;
    715 	}
    716 #ifndef NO_PROGRESS
    717 	len = 0;
    718 	if (!progress || filesize <= 0)
    719 		return;
    720 
    721 	(void)gettimeofday(&now, NULL);
    722 	cursize = bytes + restart_point;
    723 	timersub(&now, &lastupdate, &wait);
    724 	if (cursize > lastsize) {
    725 		lastupdate = now;
    726 		lastsize = cursize;
    727 		wait.tv_sec = 0;
    728 	}
    729 
    730 	/*
    731 	 * print progress bar only if we are foreground process.
    732 	 */
    733 	if (! foregroundproc())
    734 		return;
    735 
    736 	ratio = (int)((double)cursize * 100.0 / (double)filesize);
    737 	ratio = MAX(ratio, 0);
    738 	ratio = MIN(ratio, 100);
    739 	len += snprintf(buf + len, BUFLEFT, "\r%3d%% ", ratio);
    740 
    741 			/*
    742 			 * calculate the length of the `*' bar, ensuring that
    743 			 * the number of stars won't exceed the buffer size
    744 			 */
    745 	barlength = MIN(sizeof(buf) - 1, ttywidth) - BAROVERHEAD;
    746 	if (barlength > 0) {
    747 		i = barlength * ratio / 100;
    748 		len += snprintf(buf + len, BUFLEFT,
    749 		    "|%.*s%*s|", i, stars, barlength - i, "");
    750 	}
    751 
    752 	abbrevsize = cursize;
    753 	for (i = 0; abbrevsize >= 100000 && i < sizeof(prefixes); i++)
    754 		abbrevsize >>= 10;
    755 	len += snprintf(buf + len, BUFLEFT,
    756 #ifndef NO_QUAD
    757 	    " %5lld %c%c ", (long long)abbrevsize,
    758 #else
    759 	    " %5ld %c%c ", (long)abbrevsize,
    760 #endif
    761 	    prefixes[i],
    762 	    i == 0 ? ' ' : 'B');
    763 
    764 	timersub(&now, &start, &td);
    765 	elapsed = td.tv_sec + (td.tv_usec / 1000000.0);
    766 
    767 	bytespersec = 0;
    768 	if (bytes > 0) {
    769 		bytespersec = bytes;
    770 		if (elapsed > 0.0)
    771 			bytespersec /= elapsed;
    772 	}
    773 	for (i = 1; bytespersec >= 1024000 && i < sizeof(prefixes); i++)
    774 		bytespersec >>= 10;
    775 	len += snprintf(buf + len, BUFLEFT,
    776 #ifndef NO_QUAD
    777 	    " %3lld.%02d %cB/s ", (long long)bytespersec / 1024,
    778 #else
    779 	    " %3ld.%02d %cB/s ", (long)bytespersec / 1024,
    780 #endif
    781 	    (int)((bytespersec % 1024) * 100 / 1024),
    782 	    prefixes[i]);
    783 
    784 	if (bytes <= 0 || elapsed <= 0.0 || cursize > filesize) {
    785 		len += snprintf(buf + len, BUFLEFT, "   --:-- ETA");
    786 	} else if (wait.tv_sec >= STALLTIME) {
    787 		len += snprintf(buf + len, BUFLEFT, " - stalled -");
    788 	} else {
    789 		remaining = (int)
    790 		    ((filesize - restart_point) / (bytes / elapsed) - elapsed);
    791 		if (remaining >= 100 * SECSPERHOUR)
    792 			len += snprintf(buf + len, BUFLEFT, "   --:-- ETA");
    793 		else {
    794 			i = remaining / SECSPERHOUR;
    795 			if (i)
    796 				len += snprintf(buf + len, BUFLEFT, "%2d:", i);
    797 			else
    798 				len += snprintf(buf + len, BUFLEFT, "   ");
    799 			i = remaining % SECSPERHOUR;
    800 			len += snprintf(buf + len, BUFLEFT,
    801 			    "%02d:%02d ETA", i / 60, i % 60);
    802 		}
    803 	}
    804 	if (flag == 1)
    805 		len += snprintf(buf + len, BUFLEFT, "\n");
    806 	(void)write(fileno(ttyout), buf, len);
    807 
    808 	if (flag == -1) {
    809 		(void)xsignal_restart(SIGALRM, updateprogressmeter, 1);
    810 		alarmtimer(1);		/* set alarm timer for 1 Hz */
    811 	} else if (flag == 1) {
    812 		(void)xsignal(SIGALRM, SIG_DFL);
    813 		alarmtimer(0);
    814 	}
    815 #endif	/* !NO_PROGRESS */
    816 }
    817 
    818 /*
    819  * Display transfer statistics.
    820  * Requires start to be initialised by progressmeter(-1),
    821  * direction to be defined by xfer routines, and filesize and bytes
    822  * to be updated by xfer routines
    823  * If siginfo is nonzero, an ETA is displayed, and the output goes to stderr
    824  * instead of ttyout.
    825  */
    826 void
    827 ptransfer(siginfo)
    828 	int siginfo;
    829 {
    830 	struct timeval now, td, wait;
    831 	double elapsed;
    832 	off_t bytespersec;
    833 	int remaining, hh, i, len;
    834 
    835 	char buf[256];		/* Work variable for transfer status. */
    836 
    837 	if (!verbose && !progress && !siginfo)
    838 		return;
    839 
    840 	(void)gettimeofday(&now, NULL);
    841 	timersub(&now, &start, &td);
    842 	elapsed = td.tv_sec + (td.tv_usec / 1000000.0);
    843 	bytespersec = 0;
    844 	if (bytes > 0) {
    845 		bytespersec = bytes;
    846 		if (elapsed > 0.0)
    847 			bytespersec /= elapsed;
    848 	}
    849 	len = 0;
    850 	len += snprintf(buf + len, BUFLEFT,
    851 #ifndef NO_QUAD
    852 	    "%lld byte%s %s in ", (long long)bytes,
    853 #else
    854 	    "%ld byte%s %s in ", (long)bytes,
    855 #endif
    856 	    bytes == 1 ? "" : "s", direction);
    857 	remaining = (int)elapsed;
    858 	if (remaining > SECSPERDAY) {
    859 		int days;
    860 
    861 		days = remaining / SECSPERDAY;
    862 		remaining %= SECSPERDAY;
    863 		len += snprintf(buf + len, BUFLEFT,
    864 		    "%d day%s ", days, days == 1 ? "" : "s");
    865 	}
    866 	hh = remaining / SECSPERHOUR;
    867 	remaining %= SECSPERHOUR;
    868 	if (hh)
    869 		len += snprintf(buf + len, BUFLEFT, "%2d:", hh);
    870 	len += snprintf(buf + len, BUFLEFT,
    871 	    "%02d:%02d ", remaining / 60, remaining % 60);
    872 
    873 	for (i = 1; bytespersec >= 1024000 && i < sizeof(prefixes); i++)
    874 		bytespersec >>= 10;
    875 	len += snprintf(buf + len, BUFLEFT,
    876 #ifndef NO_QUAD
    877 	    "(%lld.%02d %cB/s)", (long long)bytespersec / 1024,
    878 #else
    879 	    "(%ld.%02d %cB/s)", (long)bytespersec / 1024,
    880 #endif
    881 	    (int)((bytespersec % 1024) * 100 / 1024),
    882 	    prefixes[i]);
    883 
    884 	if (siginfo && bytes > 0 && elapsed > 0.0 && filesize >= 0
    885 	    && bytes + restart_point <= filesize) {
    886 		remaining = (int)((filesize - restart_point) /
    887 				  (bytes / elapsed) - elapsed);
    888 		hh = remaining / SECSPERHOUR;
    889 		remaining %= SECSPERHOUR;
    890 		len += snprintf(buf + len, BUFLEFT, "  ETA: ");
    891 		if (hh)
    892 			len += snprintf(buf + len, BUFLEFT, "%2d:", hh);
    893 		len += snprintf(buf + len, BUFLEFT, "%02d:%02d",
    894 		    remaining / 60, remaining % 60);
    895 		timersub(&now, &lastupdate, &wait);
    896 		if (wait.tv_sec >= STALLTIME)
    897 			len += snprintf(buf + len, BUFLEFT, "  (stalled)");
    898 	}
    899 	len += snprintf(buf + len, BUFLEFT, "\n");
    900 	(void)write(siginfo ? STDERR_FILENO : fileno(ttyout), buf, len);
    901 }
    902 
    903 /*
    904  * Print transfer stats if a transfer is in progress
    905  */
    906 void
    907 psummary(notused)
    908 	int notused;
    909 {
    910 	int oerrno = errno;
    911 
    912 	if (bytes > 0)
    913 		ptransfer(1);
    914 	errno = oerrno;
    915 }
    916 
    917 /*
    918  * List words in stringlist, vertically arranged
    919  */
    920 void
    921 list_vertical(sl)
    922 	StringList *sl;
    923 {
    924 	int i, j, w;
    925 	int columns, width, lines, items;
    926 	char *p;
    927 
    928 	width = items = 0;
    929 
    930 	for (i = 0 ; i < sl->sl_cur ; i++) {
    931 		w = strlen(sl->sl_str[i]);
    932 		if (w > width)
    933 			width = w;
    934 	}
    935 	width = (width + 8) &~ 7;
    936 
    937 	columns = ttywidth / width;
    938 	if (columns == 0)
    939 		columns = 1;
    940 	lines = (sl->sl_cur + columns - 1) / columns;
    941 	for (i = 0; i < lines; i++) {
    942 		for (j = 0; j < columns; j++) {
    943 			p = sl->sl_str[j * lines + i];
    944 			if (p)
    945 				fputs(p, ttyout);
    946 			if (j * lines + i + lines >= sl->sl_cur) {
    947 				putc('\n', ttyout);
    948 				break;
    949 			}
    950 			w = strlen(p);
    951 			while (w < width) {
    952 				w = (w + 8) &~ 7;
    953 				(void)putc('\t', ttyout);
    954 			}
    955 		}
    956 	}
    957 }
    958 
    959 /*
    960  * Update the global ttywidth value, using TIOCGWINSZ.
    961  */
    962 void
    963 setttywidth(a)
    964 	int a;
    965 {
    966 	struct winsize winsize;
    967 	int oerrno = errno;
    968 
    969 	if (ioctl(fileno(ttyout), TIOCGWINSZ, &winsize) != -1 &&
    970 	    winsize.ws_col != 0)
    971 		ttywidth = winsize.ws_col;
    972 	else
    973 		ttywidth = 80;
    974 	errno = oerrno;
    975 }
    976 
    977 /*
    978  * Change the rate limit up (SIGUSR1) or down (SIGUSR2)
    979  */
    980 void
    981 crankrate(int sig)
    982 {
    983 
    984 	switch (sig) {
    985 	case SIGUSR1:
    986 		if (rate_get)
    987 			rate_get += rate_get_incr;
    988 		if (rate_put)
    989 			rate_put += rate_put_incr;
    990 		break;
    991 	case SIGUSR2:
    992 		if (rate_get && rate_get > rate_get_incr)
    993 			rate_get -= rate_get_incr;
    994 		if (rate_put && rate_put > rate_put_incr)
    995 			rate_put -= rate_put_incr;
    996 		break;
    997 	default:
    998 		err(1, "crankrate invoked with unknown signal: %d", sig);
    999 	}
   1000 }
   1001 
   1002 
   1003 /*
   1004  * Set the SIGALRM interval timer for wait seconds, 0 to disable.
   1005  */
   1006 void
   1007 alarmtimer(wait)
   1008 	int wait;
   1009 {
   1010 	struct itimerval itv;
   1011 
   1012 	itv.it_value.tv_sec = wait;
   1013 	itv.it_value.tv_usec = 0;
   1014 	itv.it_interval = itv.it_value;
   1015 	setitimer(ITIMER_REAL, &itv, NULL);
   1016 }
   1017 
   1018 /*
   1019  * Setup or cleanup EditLine structures
   1020  */
   1021 #ifndef NO_EDITCOMPLETE
   1022 void
   1023 controlediting()
   1024 {
   1025 	if (editing && el == NULL && hist == NULL) {
   1026 		HistEvent ev;
   1027 		int editmode;
   1028 
   1029 		el = el_init(__progname, stdin, ttyout, stderr);
   1030 		/* init editline */
   1031 		hist = history_init();		/* init the builtin history */
   1032 		history(hist, &ev, H_SETSIZE, 100);/* remember 100 events */
   1033 		el_set(el, EL_HIST, history, hist);	/* use history */
   1034 
   1035 		el_set(el, EL_EDITOR, "emacs");	/* default editor is emacs */
   1036 		el_set(el, EL_PROMPT, prompt);	/* set the prompt function */
   1037 
   1038 		/* add local file completion, bind to TAB */
   1039 		el_set(el, EL_ADDFN, "ftp-complete",
   1040 		    "Context sensitive argument completion",
   1041 		    complete);
   1042 		el_set(el, EL_BIND, "^I", "ftp-complete", NULL);
   1043 		el_source(el, NULL);	/* read ~/.editrc */
   1044 		if ((el_get(el, EL_EDITMODE, &editmode) != -1) && editmode == 0)
   1045 			editing = 0;	/* the user doesn't want editing,
   1046 					 * so disable, and let statement
   1047 					 * below cleanup */
   1048 		else
   1049 			el_set(el, EL_SIGNAL, 1);
   1050 	}
   1051 	if (!editing) {
   1052 		if (hist) {
   1053 			history_end(hist);
   1054 			hist = NULL;
   1055 		}
   1056 		if (el) {
   1057 			el_end(el);
   1058 			el = NULL;
   1059 		}
   1060 	}
   1061 }
   1062 #endif /* !NO_EDITCOMPLETE */
   1063 
   1064 /*
   1065  * Convert the string `arg' to an int, which may have an optional SI suffix
   1066  * (`b', `k', `m', `g'). Returns the number for success, -1 otherwise.
   1067  */
   1068 int
   1069 strsuftoi(arg)
   1070 	const char *arg;
   1071 {
   1072 	char *cp;
   1073 	long val;
   1074 
   1075 	if (!isdigit((unsigned char)arg[0]))
   1076 		return (-1);
   1077 
   1078 	val = strtol(arg, &cp, 10);
   1079 	if (cp != NULL) {
   1080 		if (cp[0] != '\0' && cp[1] != '\0')
   1081 			 return (-1);
   1082 		switch (tolower((unsigned char)cp[0])) {
   1083 		case '\0':
   1084 		case 'b':
   1085 			break;
   1086 		case 'k':
   1087 			val <<= 10;
   1088 			break;
   1089 		case 'm':
   1090 			val <<= 20;
   1091 			break;
   1092 		case 'g':
   1093 			val <<= 30;
   1094 			break;
   1095 		default:
   1096 			return (-1);
   1097 		}
   1098 	}
   1099 	if (val < 0 || val > INT_MAX)
   1100 		return (-1);
   1101 
   1102 	return (val);
   1103 }
   1104 
   1105 /*
   1106  * Set up socket buffer sizes before a connection is made.
   1107  */
   1108 void
   1109 setupsockbufsize(sock)
   1110 	int sock;
   1111 {
   1112 
   1113 	if (setsockopt(sock, SOL_SOCKET, SO_SNDBUF, (void *) &sndbuf_size,
   1114 	    sizeof(rcvbuf_size)) < 0)
   1115 		warn("unable to set sndbuf size %d", sndbuf_size);
   1116 
   1117 	if (setsockopt(sock, SOL_SOCKET, SO_RCVBUF, (void *) &rcvbuf_size,
   1118 	    sizeof(rcvbuf_size)) < 0)
   1119 		warn("unable to set rcvbuf size %d", rcvbuf_size);
   1120 }
   1121 
   1122 void
   1123 ftpvis(dst, dstlen, src, srclen)
   1124 	char		*dst;
   1125 	size_t		 dstlen;
   1126 	const char	*src;
   1127 	size_t		 srclen;
   1128 {
   1129 	int	di, si;
   1130 
   1131 	for (di = si = 0;
   1132 	    src[si] != '\0' && di < dstlen && si < srclen;
   1133 	    di++, si++) {
   1134 		switch (src[si]) {
   1135 		case '\\':
   1136 		case ' ':
   1137 		case '\t':
   1138 		case '\r':
   1139 		case '\n':
   1140 		case '"':
   1141 			dst[di++] = '\\';
   1142 			if (di >= dstlen)
   1143 				break;
   1144 			/* FALLTHROUGH */
   1145 		default:
   1146 			dst[di] = src[si];
   1147 		}
   1148 	}
   1149 	dst[di] = '\0';
   1150 }
   1151 
   1152 /*
   1153  * Determine if given string is an IPv6 address or not.
   1154  * Return 1 for yes, 0 for no
   1155  */
   1156 int
   1157 isipv6addr(addr)
   1158 	const char *addr;
   1159 {
   1160 	int rv = 0;
   1161 #ifdef INET6
   1162 	u_char buf[16];		/* XXX: sizeof(struct in_addr6) */
   1163 
   1164 	rv = inet_pton(AF_INET6, addr, &buf);
   1165 	if (debug)
   1166 		fprintf(ttyout, "isipv6addr: got %d for %s\n", rv, addr);
   1167 #endif
   1168 	return rv;
   1169 }
   1170 
   1171 
   1172 /*
   1173  * Internal version of connect(2); sets socket buffer sizes first.
   1174  */
   1175 int
   1176 xconnect(sock, name, namelen)
   1177 	int sock;
   1178 	const struct sockaddr *name;
   1179 	int namelen;
   1180 {
   1181 
   1182 	setupsockbufsize(sock);
   1183 	return (connect(sock, name, namelen));
   1184 }
   1185 
   1186 /*
   1187  * Internal version of listen(2); sets socket buffer sizes first.
   1188  */
   1189 int
   1190 xlisten(sock, backlog)
   1191 	int sock, backlog;
   1192 {
   1193 
   1194 	setupsockbufsize(sock);
   1195 	return (listen(sock, backlog));
   1196 }
   1197 
   1198 void *
   1199 xmalloc(size)
   1200 	size_t size;
   1201 {
   1202 	void *p;
   1203 
   1204 	p = malloc(size);
   1205 	if (p == NULL)
   1206 		err(1, "Unable to allocate %ld bytes of memory", (long)size);
   1207 	return (p);
   1208 }
   1209 
   1210 char *
   1211 xstrdup(str)
   1212 	const char *str;
   1213 {
   1214 	char *s;
   1215 
   1216 	if (str == NULL)
   1217 		errx(1, "xstrdup() called with NULL argument");
   1218 	s = strdup(str);
   1219 	if (s == NULL)
   1220 		err(1, "Unable to allocate memory for string copy");
   1221 	return (s);
   1222 }
   1223 
   1224 sig_t
   1225 xsignal_restart(sig, func, restartable)
   1226 	int sig;
   1227 	void (*func) __P((int));
   1228 	int restartable;
   1229 {
   1230 	struct sigaction act, oact;
   1231 	act.sa_handler = func;
   1232 
   1233 	sigemptyset(&act.sa_mask);
   1234 #if defined(SA_RESTART)			/* 4.4BSD, Posix(?), SVR4 */
   1235 	act.sa_flags = restartable ? SA_RESTART : 0;
   1236 #elif defined(SA_INTERRUPT)		/* SunOS 4.x */
   1237 	act.sa_flags = restartable ? 0 : SA_INTERRUPT;
   1238 #else
   1239 #error "system must have SA_RESTART or SA_INTERRUPT"
   1240 #endif
   1241 	if (sigaction(sig, &act, &oact) < 0)
   1242 		return (SIG_ERR);
   1243 	return (oact.sa_handler);
   1244 }
   1245 
   1246 sig_t
   1247 xsignal(sig, func)
   1248 	int sig;
   1249 	void (*func) __P((int));
   1250 {
   1251 	int restartable;
   1252 
   1253 	/*
   1254 	 * Some signals print output or change the state of the process.
   1255 	 * There should be restartable, so that reads and writes are
   1256 	 * not affected.  Some signals should cause program flow to change;
   1257 	 * these signals should not be restartable, so that the system call
   1258 	 * will return with EINTR, and the program will go do something
   1259 	 * different.  If the signal handler calls longjmp() or siglongjmp(),
   1260 	 * it doesn't matter if it's restartable.
   1261 	 */
   1262 
   1263 	switch(sig) {
   1264 #ifdef SIGINFO
   1265 	case SIGINFO:
   1266 #endif
   1267 	case SIGQUIT:
   1268 	case SIGUSR1:
   1269 	case SIGUSR2:
   1270 	case SIGWINCH:
   1271 		restartable = 1;
   1272 		break;
   1273 
   1274 	case SIGALRM:
   1275 	case SIGINT:
   1276 	case SIGPIPE:
   1277 		restartable = 0;
   1278 		break;
   1279 
   1280 	default:
   1281 		/*
   1282 		 * This is unpleasant, but I don't know what would be better.
   1283 		 * Right now, this "can't happen"
   1284 		 */
   1285 		errx(1, "xsignal_restart called with signal %d\n",
   1286 		sig);
   1287 	}
   1288 
   1289 	return(xsignal_restart(sig, func, restartable));
   1290 }
   1291