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