Home | History | Annotate | Line # | Download | only in ftp
util.c revision 1.116
      1 /*	$NetBSD: util.c,v 1.116 2004/07/20 10:40:22 lukem Exp $	*/
      2 
      3 /*-
      4  * Copyright (c) 1997-2004 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. Neither the name of the University nor the names of its contributors
     56  *    may be used to endorse or promote products derived from this software
     57  *    without specific prior written permission.
     58  *
     59  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
     60  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
     61  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
     62  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
     63  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
     64  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
     65  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
     66  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
     67  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
     68  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
     69  * SUCH DAMAGE.
     70  */
     71 
     72 #include <sys/cdefs.h>
     73 #ifndef lint
     74 __RCSID("$NetBSD: util.c,v 1.116 2004/07/20 10:40:22 lukem Exp $");
     75 #endif /* not lint */
     76 
     77 /*
     78  * FTP User Program -- Misc support routines
     79  */
     80 #include <sys/types.h>
     81 #include <sys/socket.h>
     82 #include <sys/ioctl.h>
     83 #include <sys/time.h>
     84 #include <netinet/in.h>
     85 #include <arpa/ftp.h>
     86 
     87 #include <ctype.h>
     88 #include <err.h>
     89 #include <errno.h>
     90 #include <fcntl.h>
     91 #include <glob.h>
     92 #include <signal.h>
     93 #include <limits.h>
     94 #include <netdb.h>
     95 #include <stdio.h>
     96 #include <stdlib.h>
     97 #include <string.h>
     98 #include <termios.h>
     99 #include <time.h>
    100 #include <tzfile.h>
    101 #include <unistd.h>
    102 
    103 #include "ftp_var.h"
    104 
    105 /*
    106  * Connect to peer server and auto-login, if possible.
    107  */
    108 void
    109 setpeer(int argc, char *argv[])
    110 {
    111 	char *host;
    112 	char *port;
    113 
    114 	if (argc == 0)
    115 		goto usage;
    116 	if (connected) {
    117 		fprintf(ttyout, "Already connected to %s, use close first.\n",
    118 		    hostname);
    119 		code = -1;
    120 		return;
    121 	}
    122 	if (argc < 2)
    123 		(void)another(&argc, &argv, "to");
    124 	if (argc < 2 || argc > 3) {
    125  usage:
    126 		fprintf(ttyout, "usage: %s host-name [port]\n", argv[0]);
    127 		code = -1;
    128 		return;
    129 	}
    130 	if (gatemode)
    131 		port = gateport;
    132 	else
    133 		port = ftpport;
    134 	if (argc > 2)
    135 		port = argv[2];
    136 
    137 	if (gatemode) {
    138 		if (gateserver == NULL || *gateserver == '\0')
    139 			errx(1, "gateserver not defined (shouldn't happen)");
    140 		host = hookup(gateserver, port);
    141 	} else
    142 		host = hookup(argv[1], port);
    143 
    144 	if (host) {
    145 		if (gatemode && verbose) {
    146 			fprintf(ttyout,
    147 			    "Connecting via pass-through server %s\n",
    148 			    gateserver);
    149 		}
    150 
    151 		connected = 1;
    152 		/*
    153 		 * Set up defaults for FTP.
    154 		 */
    155 		(void)strlcpy(typename, "ascii", sizeof(typename));
    156 		type = TYPE_A;
    157 		curtype = TYPE_A;
    158 		(void)strlcpy(formname, "non-print", sizeof(formname));
    159 		form = FORM_N;
    160 		(void)strlcpy(modename, "stream", sizeof(modename));
    161 		mode = MODE_S;
    162 		(void)strlcpy(structname, "file", sizeof(structname));
    163 		stru = STRU_F;
    164 		(void)strlcpy(bytename, "8", sizeof(bytename));
    165 		bytesize = 8;
    166 		if (autologin)
    167 			(void)ftp_login(argv[1], NULL, NULL);
    168 	}
    169 }
    170 
    171 static void
    172 parse_feat(const char *line)
    173 {
    174 
    175 			/*
    176 			 * work-around broken ProFTPd servers that can't
    177 			 * even obey RFC 2389.
    178 			 */
    179 	while (*line && isspace((int)*line))
    180 		line++;
    181 
    182 	if (strcasecmp(line, "MDTM") == 0)
    183 		features[FEAT_MDTM] = 1;
    184 	else if (strncasecmp(line, "MLST", sizeof("MLST") - 1) == 0) {
    185 		features[FEAT_MLST] = 1;
    186 	} else if (strcasecmp(line, "REST STREAM") == 0)
    187 		features[FEAT_REST_STREAM] = 1;
    188 	else if (strcasecmp(line, "SIZE") == 0)
    189 		features[FEAT_SIZE] = 1;
    190 	else if (strcasecmp(line, "TVFS") == 0)
    191 		features[FEAT_TVFS] = 1;
    192 }
    193 
    194 /*
    195  * Determine the remote system type (SYST) and features (FEAT).
    196  * Call after a successful login (i.e, connected = -1)
    197  */
    198 void
    199 getremoteinfo(void)
    200 {
    201 	int overbose, i;
    202 
    203 	overbose = verbose;
    204 	if (debug == 0)
    205 		verbose = -1;
    206 
    207 			/* determine remote system type */
    208 	if (command("SYST") == COMPLETE) {
    209 		if (overbose) {
    210 			char *cp, c;
    211 
    212 			c = 0;
    213 			cp = strchr(reply_string + 4, ' ');
    214 			if (cp == NULL)
    215 				cp = strchr(reply_string + 4, '\r');
    216 			if (cp) {
    217 				if (cp[-1] == '.')
    218 					cp--;
    219 				c = *cp;
    220 				*cp = '\0';
    221 			}
    222 
    223 			fprintf(ttyout, "Remote system type is %s.\n",
    224 			    reply_string + 4);
    225 			if (cp)
    226 				*cp = c;
    227 		}
    228 		if (!strncmp(reply_string, "215 UNIX Type: L8", 17)) {
    229 			if (proxy)
    230 				unix_proxy = 1;
    231 			else
    232 				unix_server = 1;
    233 			/*
    234 			 * Set type to 0 (not specified by user),
    235 			 * meaning binary by default, but don't bother
    236 			 * telling server.  We can use binary
    237 			 * for text files unless changed by the user.
    238 			 */
    239 			type = 0;
    240 			(void)strlcpy(typename, "binary", sizeof(typename));
    241 			if (overbose)
    242 			    fprintf(ttyout,
    243 				"Using %s mode to transfer files.\n",
    244 				typename);
    245 		} else {
    246 			if (proxy)
    247 				unix_proxy = 0;
    248 			else
    249 				unix_server = 0;
    250 			if (overbose &&
    251 			    !strncmp(reply_string, "215 TOPS20", 10))
    252 				fputs(
    253 "Remember to set tenex mode when transferring binary files from this machine.\n",
    254 				    ttyout);
    255 		}
    256 	}
    257 
    258 			/* determine features (if any) */
    259 	for (i = 0; i < FEAT_max; i++)
    260 		features[i] = -1;
    261 	reply_callback = parse_feat;
    262 	if (command("FEAT") == COMPLETE) {
    263 		for (i = 0; i < FEAT_max; i++) {
    264 			if (features[i] == -1)
    265 				features[i] = 0;
    266 		}
    267 		features[FEAT_FEAT] = 1;
    268 	} else
    269 		features[FEAT_FEAT] = 0;
    270 	if (debug) {
    271 #define DEBUG_FEAT(x) fprintf(ttyout, "features[" #x "] = %d\n", features[(x)])
    272 		DEBUG_FEAT(FEAT_FEAT);
    273 		DEBUG_FEAT(FEAT_MDTM);
    274 		DEBUG_FEAT(FEAT_MLST);
    275 		DEBUG_FEAT(FEAT_REST_STREAM);
    276 		DEBUG_FEAT(FEAT_SIZE);
    277 		DEBUG_FEAT(FEAT_TVFS);
    278 #undef DEBUG_FEAT
    279 	}
    280 	reply_callback = NULL;
    281 
    282 	verbose = overbose;
    283 }
    284 
    285 /*
    286  * Reset the various variables that indicate connection state back to
    287  * disconnected settings.
    288  * The caller is responsible for issuing any commands to the remote server
    289  * to perform a clean shutdown before this is invoked.
    290  */
    291 void
    292 cleanuppeer(void)
    293 {
    294 
    295 	if (cout)
    296 		(void)fclose(cout);
    297 	cout = NULL;
    298 	connected = 0;
    299 	unix_server = 0;
    300 	unix_proxy = 0;
    301 			/*
    302 			 * determine if anonftp was specifically set with -a
    303 			 * (1), or implicitly set by auto_fetch() (2). in the
    304 			 * latter case, disable after the current xfer
    305 			 */
    306 	if (anonftp == 2)
    307 		anonftp = 0;
    308 	data = -1;
    309 	epsv4bad = 0;
    310 	if (username)
    311 		free(username);
    312 	username = NULL;
    313 	if (!proxy)
    314 		macnum = 0;
    315 }
    316 
    317 /*
    318  * Top-level signal handler for interrupted commands.
    319  */
    320 void
    321 intr(int signo)
    322 {
    323 
    324 	sigint_raised = 1;
    325 	alarmtimer(0);
    326 	if (fromatty)
    327 		write(fileno(ttyout), "\n", 1);
    328 	siglongjmp(toplevel, 1);
    329 }
    330 
    331 /*
    332  * Signal handler for lost connections; cleanup various elements of
    333  * the connection state, and call cleanuppeer() to finish it off.
    334  */
    335 void
    336 lostpeer(int dummy)
    337 {
    338 	int oerrno = errno;
    339 
    340 	alarmtimer(0);
    341 	if (connected) {
    342 		if (cout != NULL) {
    343 			(void)shutdown(fileno(cout), 1+1);
    344 			(void)fclose(cout);
    345 			cout = NULL;
    346 		}
    347 		if (data >= 0) {
    348 			(void)shutdown(data, 1+1);
    349 			(void)close(data);
    350 			data = -1;
    351 		}
    352 		connected = 0;
    353 	}
    354 	pswitch(1);
    355 	if (connected) {
    356 		if (cout != NULL) {
    357 			(void)shutdown(fileno(cout), 1+1);
    358 			(void)fclose(cout);
    359 			cout = NULL;
    360 		}
    361 		connected = 0;
    362 	}
    363 	proxflag = 0;
    364 	pswitch(0);
    365 	cleanuppeer();
    366 	errno = oerrno;
    367 }
    368 
    369 
    370 /*
    371  * Login to remote host, using given username & password if supplied.
    372  * Return non-zero if successful.
    373  */
    374 int
    375 ftp_login(const char *host, const char *user, const char *pass)
    376 {
    377 	char tmp[80];
    378 	const char *acct;
    379 	int n, aflag, rval, freeuser, freepass, freeacct;
    380 
    381 	acct = NULL;
    382 	aflag = rval = freeuser = freepass = freeacct = 0;
    383 
    384 	if (debug)
    385 		fprintf(ttyout, "ftp_login: user `%s' pass `%s' host `%s'\n",
    386 		    user ? user : "<null>", pass ? pass : "<null>",
    387 		    host ? host : "<null>");
    388 
    389 
    390 	/*
    391 	 * Set up arguments for an anonymous FTP session, if necessary.
    392 	 */
    393 	if (anonftp) {
    394 		user = "anonymous";	/* as per RFC 1635 */
    395 		pass = getoptionvalue("anonpass");
    396 	}
    397 
    398 	if (user == NULL)
    399 		freeuser = 1;
    400 	if (pass == NULL)
    401 		freepass = 1;
    402 	freeacct = 1;
    403 	if (ruserpass(host, &user, &pass, &acct) < 0) {
    404 		code = -1;
    405 		goto cleanup_ftp_login;
    406 	}
    407 
    408 	while (user == NULL) {
    409 		if (localname)
    410 			fprintf(ttyout, "Name (%s:%s): ", host, localname);
    411 		else
    412 			fprintf(ttyout, "Name (%s): ", host);
    413 		*tmp = '\0';
    414 		if (fgets(tmp, sizeof(tmp) - 1, stdin) == NULL) {
    415 			fprintf(ttyout, "\nEOF received; login aborted.\n");
    416 			clearerr(stdin);
    417 			code = -1;
    418 			goto cleanup_ftp_login;
    419 		}
    420 		tmp[strlen(tmp) - 1] = '\0';
    421 		freeuser = 0;
    422 		if (*tmp == '\0')
    423 			user = localname;
    424 		else
    425 			user = tmp;
    426 	}
    427 
    428 	if (gatemode) {
    429 		char *nuser;
    430 		int len;
    431 
    432 		len = strlen(user) + 1 + strlen(host) + 1;
    433 		nuser = xmalloc(len);
    434 		(void)strlcpy(nuser, user, len);
    435 		(void)strlcat(nuser, "@",  len);
    436 		(void)strlcat(nuser, host, len);
    437 		freeuser = 1;
    438 		user = nuser;
    439 	}
    440 
    441 	n = command("USER %s", user);
    442 	if (n == CONTINUE) {
    443 		if (pass == NULL) {
    444 			freepass = 0;
    445 			pass = getpass("Password:");
    446 		}
    447 		n = command("PASS %s", pass);
    448 	}
    449 	if (n == CONTINUE) {
    450 		aflag++;
    451 		if (acct == NULL) {
    452 			freeacct = 0;
    453 			acct = getpass("Account:");
    454 		}
    455 		if (acct[0] == '\0') {
    456 			warnx("Login failed.");
    457 			goto cleanup_ftp_login;
    458 		}
    459 		n = command("ACCT %s", acct);
    460 	}
    461 	if ((n != COMPLETE) ||
    462 	    (!aflag && acct != NULL && command("ACCT %s", acct) != COMPLETE)) {
    463 		warnx("Login failed.");
    464 		goto cleanup_ftp_login;
    465 	}
    466 	rval = 1;
    467 	username = xstrdup(user);
    468 	if (proxy)
    469 		goto cleanup_ftp_login;
    470 
    471 	connected = -1;
    472 	getremoteinfo();
    473 	for (n = 0; n < macnum; ++n) {
    474 		if (!strcmp("init", macros[n].mac_name)) {
    475 			(void)strlcpy(line, "$init", sizeof(line));
    476 			makeargv();
    477 			domacro(margc, margv);
    478 			break;
    479 		}
    480 	}
    481 	updateremotepwd();
    482 
    483  cleanup_ftp_login:
    484 	if (user != NULL && freeuser)
    485 		free((char *)user);
    486 	if (pass != NULL && freepass)
    487 		free((char *)pass);
    488 	if (acct != NULL && freeacct)
    489 		free((char *)acct);
    490 	return (rval);
    491 }
    492 
    493 /*
    494  * `another' gets another argument, and stores the new argc and argv.
    495  * It reverts to the top level (via intr()) on EOF/error.
    496  *
    497  * Returns false if no new arguments have been added.
    498  */
    499 int
    500 another(int *pargc, char ***pargv, const char *prompt)
    501 {
    502 	int len = strlen(line), ret;
    503 
    504 	if (len >= sizeof(line) - 3) {
    505 		fputs("sorry, arguments too long.\n", ttyout);
    506 		intr(0);
    507 	}
    508 	fprintf(ttyout, "(%s) ", prompt);
    509 	line[len++] = ' ';
    510 	if (fgets(&line[len], sizeof(line) - len, stdin) == NULL) {
    511 		clearerr(stdin);
    512 		intr(0);
    513 	}
    514 	len += strlen(&line[len]);
    515 	if (len > 0 && line[len - 1] == '\n')
    516 		line[len - 1] = '\0';
    517 	makeargv();
    518 	ret = margc > *pargc;
    519 	*pargc = margc;
    520 	*pargv = margv;
    521 	return (ret);
    522 }
    523 
    524 /*
    525  * glob files given in argv[] from the remote server.
    526  * if errbuf isn't NULL, store error messages there instead
    527  * of writing to the screen.
    528  */
    529 char *
    530 remglob(char *argv[], int doswitch, char **errbuf)
    531 {
    532         char temp[MAXPATHLEN];
    533         static char buf[MAXPATHLEN];
    534         static FILE *ftemp = NULL;
    535         static char **args;
    536         int oldverbose, oldhash, oldprogress, fd, len;
    537         char *cp, *mode;
    538 
    539         if (!mflag || !connected) {
    540                 if (!doglob)
    541                         args = NULL;
    542                 else {
    543                         if (ftemp) {
    544                                 (void)fclose(ftemp);
    545                                 ftemp = NULL;
    546                         }
    547                 }
    548                 return (NULL);
    549         }
    550         if (!doglob) {
    551                 if (args == NULL)
    552                         args = argv;
    553                 if ((cp = *++args) == NULL)
    554                         args = NULL;
    555                 return (cp);
    556         }
    557         if (ftemp == NULL) {
    558 		len = strlcpy(temp, tmpdir, sizeof(temp));
    559 		if (temp[len - 1] != '/')
    560 			(void)strlcat(temp, "/", sizeof(temp));
    561 		(void)strlcat(temp, TMPFILE, sizeof(temp));
    562                 if ((fd = mkstemp(temp)) < 0) {
    563                         warn("unable to create temporary file %s", temp);
    564                         return (NULL);
    565                 }
    566                 close(fd);
    567                 oldverbose = verbose;
    568 		verbose = (errbuf != NULL) ? -1 : 0;
    569                 oldhash = hash;
    570 		oldprogress = progress;
    571                 hash = 0;
    572 		progress = 0;
    573                 if (doswitch)
    574                         pswitch(!proxy);
    575                 for (mode = "w"; *++argv != NULL; mode = "a")
    576                         recvrequest("NLST", temp, *argv, mode, 0, 0);
    577 		if ((code / 100) != COMPLETE) {
    578 			if (errbuf != NULL)
    579 				*errbuf = reply_string;
    580 		}
    581                 if (doswitch)
    582                         pswitch(!proxy);
    583                 verbose = oldverbose;
    584 		hash = oldhash;
    585 		progress = oldprogress;
    586                 ftemp = fopen(temp, "r");
    587                 (void)unlink(temp);
    588                 if (ftemp == NULL) {
    589 			if (errbuf == NULL)
    590 				fputs(
    591 				    "can't find list of remote files, oops.\n",
    592 				    ttyout);
    593 			else
    594 				*errbuf =
    595 				    "can't find list of remote files, oops.";
    596                         return (NULL);
    597                 }
    598         }
    599         if (fgets(buf, sizeof(buf), ftemp) == NULL) {
    600                 (void)fclose(ftemp);
    601 		ftemp = NULL;
    602                 return (NULL);
    603         }
    604         if ((cp = strchr(buf, '\n')) != NULL)
    605                 *cp = '\0';
    606         return (buf);
    607 }
    608 
    609 /*
    610  * Glob a local file name specification with the expectation of a single
    611  * return value. Can't control multiple values being expanded from the
    612  * expression, we return only the first.
    613  * Returns NULL on error, or a pointer to a buffer containing the filename
    614  * that's the caller's responsiblity to free(3) when finished with.
    615  */
    616 char *
    617 globulize(const char *pattern)
    618 {
    619 	glob_t gl;
    620 	int flags;
    621 	char *p;
    622 
    623 	if (!doglob)
    624 		return (xstrdup(pattern));
    625 
    626 	flags = GLOB_BRACE|GLOB_NOCHECK|GLOB_TILDE;
    627 	memset(&gl, 0, sizeof(gl));
    628 	if (glob(pattern, flags, NULL, &gl) || gl.gl_pathc == 0) {
    629 		warnx("%s: not found", pattern);
    630 		globfree(&gl);
    631 		return (NULL);
    632 	}
    633 	p = xstrdup(gl.gl_pathv[0]);
    634 	globfree(&gl);
    635 	return (p);
    636 }
    637 
    638 /*
    639  * determine size of remote file
    640  */
    641 off_t
    642 remotesize(const char *file, int noisy)
    643 {
    644 	int overbose, r;
    645 	off_t size;
    646 
    647 	overbose = verbose;
    648 	size = -1;
    649 	if (debug == 0)
    650 		verbose = -1;
    651 	if (! features[FEAT_SIZE]) {
    652 		if (noisy)
    653 			fprintf(ttyout,
    654 			    "SIZE is not supported by remote server.\n");
    655 		goto cleanup_remotesize;
    656 	}
    657 	r = command("SIZE %s", file);
    658 	if (r == COMPLETE) {
    659 		char *cp, *ep;
    660 
    661 		cp = strchr(reply_string, ' ');
    662 		if (cp != NULL) {
    663 			cp++;
    664 			size = STRTOLL(cp, &ep, 10);
    665 			if (*ep != '\0' && !isspace((unsigned char)*ep))
    666 				size = -1;
    667 		}
    668 	} else {
    669 		if (r == ERROR && code == 500 && features[FEAT_SIZE] == -1)
    670 			features[FEAT_SIZE] = 0;
    671 		if (noisy && debug == 0) {
    672 			fputs(reply_string, ttyout);
    673 			putc('\n', ttyout);
    674 		}
    675 	}
    676  cleanup_remotesize:
    677 	verbose = overbose;
    678 	return (size);
    679 }
    680 
    681 /*
    682  * determine last modification time (in GMT) of remote file
    683  */
    684 time_t
    685 remotemodtime(const char *file, int noisy)
    686 {
    687 	int	overbose, ocode, r;
    688 	time_t	rtime;
    689 
    690 	overbose = verbose;
    691 	ocode = code;
    692 	rtime = -1;
    693 	if (debug == 0)
    694 		verbose = -1;
    695 	if (! features[FEAT_MDTM]) {
    696 		if (noisy)
    697 			fprintf(ttyout,
    698 			    "MDTM is not supported by remote server.\n");
    699 		goto cleanup_parse_time;
    700 	}
    701 	r = command("MDTM %s", file);
    702 	if (r == COMPLETE) {
    703 		struct tm timebuf;
    704 		char *timestr, *frac;
    705 		int yy, mo, day, hour, min, sec;
    706 
    707 		/*
    708 		 * time-val = 14DIGIT [ "." 1*DIGIT ]
    709 		 *		YYYYMMDDHHMMSS[.sss]
    710 		 * mdtm-response = "213" SP time-val CRLF / error-response
    711 		 */
    712 		timestr = reply_string + 4;
    713 
    714 					/*
    715 					 * parse fraction.
    716 					 * XXX: ignored for now
    717 					 */
    718 		frac = strchr(timestr, '\r');
    719 		if (frac != NULL)
    720 			*frac = '\0';
    721 		frac = strchr(timestr, '.');
    722 		if (frac != NULL)
    723 			*frac++ = '\0';
    724 		if (strlen(timestr) == 15 && strncmp(timestr, "191", 3) == 0) {
    725 			/*
    726 			 * XXX:	Workaround for lame ftpd's that return
    727 			 *	`19100' instead of `2000'
    728 			 */
    729 			fprintf(ttyout,
    730 	    "Y2K warning! Incorrect time-val `%s' received from server.\n",
    731 			    timestr);
    732 			timestr++;
    733 			timestr[0] = '2';
    734 			timestr[1] = '0';
    735 			fprintf(ttyout, "Converted to `%s'\n", timestr);
    736 		}
    737 		if (strlen(timestr) != 14 ||
    738 		    sscanf(timestr, "%04d%02d%02d%02d%02d%02d",
    739 			&yy, &mo, &day, &hour, &min, &sec) != 6) {
    740  bad_parse_time:
    741 			fprintf(ttyout, "Can't parse time `%s'.\n", timestr);
    742 			goto cleanup_parse_time;
    743 		}
    744 		memset(&timebuf, 0, sizeof(timebuf));
    745 		timebuf.tm_sec = sec;
    746 		timebuf.tm_min = min;
    747 		timebuf.tm_hour = hour;
    748 		timebuf.tm_mday = day;
    749 		timebuf.tm_mon = mo - 1;
    750 		timebuf.tm_year = yy - TM_YEAR_BASE;
    751 		timebuf.tm_isdst = -1;
    752 		rtime = timegm(&timebuf);
    753 		if (rtime == -1) {
    754 			if (noisy || debug != 0)
    755 				goto bad_parse_time;
    756 			else
    757 				goto cleanup_parse_time;
    758 		} else if (debug)
    759 			fprintf(ttyout, "parsed date as: %s", ctime(&rtime));
    760 	} else {
    761 		if (r == ERROR && code == 500 && features[FEAT_MDTM] == -1)
    762 			features[FEAT_MDTM] = 0;
    763 		if (noisy && debug == 0) {
    764 			fputs(reply_string, ttyout);
    765 			putc('\n', ttyout);
    766 		}
    767 	}
    768  cleanup_parse_time:
    769 	verbose = overbose;
    770 	if (rtime == -1)
    771 		code = ocode;
    772 	return (rtime);
    773 }
    774 
    775 /*
    776  * update global `remotepwd', which contains the state of the remote cwd
    777  */
    778 void
    779 updateremotepwd(void)
    780 {
    781 	int	 overbose, ocode, i;
    782 	char	*cp;
    783 
    784 	overbose = verbose;
    785 	ocode = code;
    786 	if (debug == 0)
    787 		verbose = -1;
    788 	if (command("PWD") != COMPLETE)
    789 		goto badremotepwd;
    790 	cp = strchr(reply_string, ' ');
    791 	if (cp == NULL || cp[0] == '\0' || cp[1] != '"')
    792 		goto badremotepwd;
    793 	cp += 2;
    794 	for (i = 0; *cp && i < sizeof(remotepwd) - 1; i++, cp++) {
    795 		if (cp[0] == '"') {
    796 			if (cp[1] == '"')
    797 				cp++;
    798 			else
    799 				break;
    800 		}
    801 		remotepwd[i] = *cp;
    802 	}
    803 	remotepwd[i] = '\0';
    804 	if (debug)
    805 		fprintf(ttyout, "got remotepwd as `%s'\n", remotepwd);
    806 	goto cleanupremotepwd;
    807  badremotepwd:
    808 	remotepwd[0]='\0';
    809  cleanupremotepwd:
    810 	verbose = overbose;
    811 	code = ocode;
    812 }
    813 
    814 
    815 /*
    816  * List words in stringlist, vertically arranged
    817  */
    818 void
    819 list_vertical(StringList *sl)
    820 {
    821 	int i, j, w;
    822 	int columns, width, lines;
    823 	char *p;
    824 
    825 	width = 0;
    826 
    827 	for (i = 0 ; i < sl->sl_cur ; i++) {
    828 		w = strlen(sl->sl_str[i]);
    829 		if (w > width)
    830 			width = w;
    831 	}
    832 	width = (width + 8) &~ 7;
    833 
    834 	columns = ttywidth / width;
    835 	if (columns == 0)
    836 		columns = 1;
    837 	lines = (sl->sl_cur + columns - 1) / columns;
    838 	for (i = 0; i < lines; i++) {
    839 		for (j = 0; j < columns; j++) {
    840 			p = sl->sl_str[j * lines + i];
    841 			if (p)
    842 				fputs(p, ttyout);
    843 			if (j * lines + i + lines >= sl->sl_cur) {
    844 				putc('\n', ttyout);
    845 				break;
    846 			}
    847 			w = strlen(p);
    848 			while (w < width) {
    849 				w = (w + 8) &~ 7;
    850 				(void)putc('\t', ttyout);
    851 			}
    852 		}
    853 	}
    854 }
    855 
    856 /*
    857  * Update the global ttywidth value, using TIOCGWINSZ.
    858  */
    859 void
    860 setttywidth(int a)
    861 {
    862 	struct winsize winsize;
    863 	int oerrno = errno;
    864 
    865 	if (ioctl(fileno(ttyout), TIOCGWINSZ, &winsize) != -1 &&
    866 	    winsize.ws_col != 0)
    867 		ttywidth = winsize.ws_col;
    868 	else
    869 		ttywidth = 80;
    870 	errno = oerrno;
    871 }
    872 
    873 /*
    874  * Change the rate limit up (SIGUSR1) or down (SIGUSR2)
    875  */
    876 void
    877 crankrate(int sig)
    878 {
    879 
    880 	switch (sig) {
    881 	case SIGUSR1:
    882 		if (rate_get)
    883 			rate_get += rate_get_incr;
    884 		if (rate_put)
    885 			rate_put += rate_put_incr;
    886 		break;
    887 	case SIGUSR2:
    888 		if (rate_get && rate_get > rate_get_incr)
    889 			rate_get -= rate_get_incr;
    890 		if (rate_put && rate_put > rate_put_incr)
    891 			rate_put -= rate_put_incr;
    892 		break;
    893 	default:
    894 		err(1, "crankrate invoked with unknown signal: %d", sig);
    895 	}
    896 }
    897 
    898 
    899 /*
    900  * Setup or cleanup EditLine structures
    901  */
    902 #ifndef NO_EDITCOMPLETE
    903 void
    904 controlediting(void)
    905 {
    906 	if (editing && el == NULL && hist == NULL) {
    907 		HistEvent ev;
    908 		int editmode;
    909 
    910 		el = el_init(getprogname(), stdin, ttyout, stderr);
    911 		/* init editline */
    912 		hist = history_init();		/* init the builtin history */
    913 		history(hist, &ev, H_SETSIZE, 100);/* remember 100 events */
    914 		el_set(el, EL_HIST, history, hist);	/* use history */
    915 
    916 		el_set(el, EL_EDITOR, "emacs");	/* default editor is emacs */
    917 		el_set(el, EL_PROMPT, prompt);	/* set the prompt functions */
    918 		el_set(el, EL_RPROMPT, rprompt);
    919 
    920 		/* add local file completion, bind to TAB */
    921 		el_set(el, EL_ADDFN, "ftp-complete",
    922 		    "Context sensitive argument completion",
    923 		    complete);
    924 		el_set(el, EL_BIND, "^I", "ftp-complete", NULL);
    925 		el_source(el, NULL);	/* read ~/.editrc */
    926 		if ((el_get(el, EL_EDITMODE, &editmode) != -1) && editmode == 0)
    927 			editing = 0;	/* the user doesn't want editing,
    928 					 * so disable, and let statement
    929 					 * below cleanup */
    930 		else
    931 			el_set(el, EL_SIGNAL, 1);
    932 	}
    933 	if (!editing) {
    934 		if (hist) {
    935 			history_end(hist);
    936 			hist = NULL;
    937 		}
    938 		if (el) {
    939 			el_end(el);
    940 			el = NULL;
    941 		}
    942 	}
    943 }
    944 #endif /* !NO_EDITCOMPLETE */
    945 
    946 /*
    947  * Convert the string `arg' to an int, which may have an optional SI suffix
    948  * (`b', `k', `m', `g'). Returns the number for success, -1 otherwise.
    949  */
    950 int
    951 strsuftoi(const char *arg)
    952 {
    953 	char *cp;
    954 	long val;
    955 
    956 	if (!isdigit((unsigned char)arg[0]))
    957 		return (-1);
    958 
    959 	val = strtol(arg, &cp, 10);
    960 	if (cp != NULL) {
    961 		if (cp[0] != '\0' && cp[1] != '\0')
    962 			 return (-1);
    963 		switch (tolower((unsigned char)cp[0])) {
    964 		case '\0':
    965 		case 'b':
    966 			break;
    967 		case 'k':
    968 			val <<= 10;
    969 			break;
    970 		case 'm':
    971 			val <<= 20;
    972 			break;
    973 		case 'g':
    974 			val <<= 30;
    975 			break;
    976 		default:
    977 			return (-1);
    978 		}
    979 	}
    980 	if (val < 0 || val > INT_MAX)
    981 		return (-1);
    982 
    983 	return (val);
    984 }
    985 
    986 /*
    987  * Set up socket buffer sizes before a connection is made.
    988  */
    989 void
    990 setupsockbufsize(int sock)
    991 {
    992 
    993 	if (setsockopt(sock, SOL_SOCKET, SO_SNDBUF, (void *) &sndbuf_size,
    994 	    sizeof(rcvbuf_size)) < 0)
    995 		warn("unable to set sndbuf size %d", sndbuf_size);
    996 
    997 	if (setsockopt(sock, SOL_SOCKET, SO_RCVBUF, (void *) &rcvbuf_size,
    998 	    sizeof(rcvbuf_size)) < 0)
    999 		warn("unable to set rcvbuf size %d", rcvbuf_size);
   1000 }
   1001 
   1002 /*
   1003  * Copy characters from src into dst, \ quoting characters that require it
   1004  */
   1005 void
   1006 ftpvis(char *dst, size_t dstlen, const char *src, size_t srclen)
   1007 {
   1008 	int	di, si;
   1009 
   1010 	for (di = si = 0;
   1011 	    src[si] != '\0' && di < dstlen && si < srclen;
   1012 	    di++, si++) {
   1013 		switch (src[si]) {
   1014 		case '\\':
   1015 		case ' ':
   1016 		case '\t':
   1017 		case '\r':
   1018 		case '\n':
   1019 		case '"':
   1020 			dst[di++] = '\\';
   1021 			if (di >= dstlen)
   1022 				break;
   1023 			/* FALLTHROUGH */
   1024 		default:
   1025 			dst[di] = src[si];
   1026 		}
   1027 	}
   1028 	dst[di] = '\0';
   1029 }
   1030 
   1031 /*
   1032  * Copy src into buf (which is len bytes long), expanding % sequences.
   1033  */
   1034 void
   1035 formatbuf(char *buf, size_t len, const char *src)
   1036 {
   1037 	const char	*p;
   1038 	char		*p2, *q;
   1039 	int		 i, op, updirs, pdirs;
   1040 
   1041 #define ADDBUF(x) do { \
   1042 		if (i >= len - 1) \
   1043 			goto endbuf; \
   1044 		buf[i++] = (x); \
   1045 	} while (0)
   1046 
   1047 	p = src;
   1048 	for (i = 0; *p; p++) {
   1049 		if (*p != '%') {
   1050 			ADDBUF(*p);
   1051 			continue;
   1052 		}
   1053 		p++;
   1054 
   1055 		switch (op = *p) {
   1056 
   1057 		case '/':
   1058 		case '.':
   1059 		case 'c':
   1060 			p2 = connected ? remotepwd : "";
   1061 			updirs = pdirs = 0;
   1062 
   1063 			/* option to determine fixed # of dirs from path */
   1064 			if (op == '.' || op == 'c') {
   1065 				int skip;
   1066 
   1067 				q = p2;
   1068 				while (*p2)		/* calc # of /'s */
   1069 					if (*p2++ == '/')
   1070 						updirs++;
   1071 				if (p[1] == '0') {	/* print <x> or ... */
   1072 					pdirs = 1;
   1073 					p++;
   1074 				}
   1075 				if (p[1] >= '1' && p[1] <= '9') {
   1076 							/* calc # to skip  */
   1077 					skip = p[1] - '0';
   1078 					p++;
   1079 				} else
   1080 					skip = 1;
   1081 
   1082 				updirs -= skip;
   1083 				while (skip-- > 0) {
   1084 					while ((p2 > q) && (*p2 != '/'))
   1085 						p2--;	/* back up */
   1086 					if (skip && p2 > q)
   1087 						p2--;
   1088 				}
   1089 				if (*p2 == '/' && p2 != q)
   1090 					p2++;
   1091 			}
   1092 
   1093 			if (updirs > 0 && pdirs) {
   1094 				if (i >= len - 5)
   1095 					break;
   1096 				if (op == '.') {
   1097 					ADDBUF('.');
   1098 					ADDBUF('.');
   1099 					ADDBUF('.');
   1100 				} else {
   1101 					ADDBUF('/');
   1102 					ADDBUF('<');
   1103 					if (updirs > 9) {
   1104 						ADDBUF('9');
   1105 						ADDBUF('+');
   1106 					} else
   1107 						ADDBUF('0' + updirs);
   1108 					ADDBUF('>');
   1109 				}
   1110 			}
   1111 			for (; *p2; p2++)
   1112 				ADDBUF(*p2);
   1113 			break;
   1114 
   1115 		case 'M':
   1116 		case 'm':
   1117 			for (p2 = connected && username ? username : "-";
   1118 			    *p2 ; p2++) {
   1119 				if (op == 'm' && *p2 == '.')
   1120 					break;
   1121 				ADDBUF(*p2);
   1122 			}
   1123 			break;
   1124 
   1125 		case 'n':
   1126 			for (p2 = connected ? username : "-"; *p2 ; p2++)
   1127 				ADDBUF(*p2);
   1128 			break;
   1129 
   1130 		case '%':
   1131 			ADDBUF('%');
   1132 			break;
   1133 
   1134 		default:		/* display unknown codes literally */
   1135 			ADDBUF('%');
   1136 			ADDBUF(op);
   1137 			break;
   1138 
   1139 		}
   1140 	}
   1141  endbuf:
   1142 	buf[i] = '\0';
   1143 }
   1144 
   1145 /*
   1146  * Parse `port' into a TCP port number, defaulting to `defport' if `port' is
   1147  * an unknown service name. If defport != -1, print a warning upon bad parse.
   1148  */
   1149 int
   1150 parseport(const char *port, int defport)
   1151 {
   1152 	int	 rv;
   1153 	long	 nport;
   1154 	char	*p, *ep;
   1155 
   1156 	p = xstrdup(port);
   1157 	nport = strtol(p, &ep, 10);
   1158 	if (*ep != '\0' && ep == p) {
   1159 		struct servent	*svp;
   1160 
   1161 		svp = getservbyname(port, "tcp");
   1162 		if (svp == NULL) {
   1163  badparseport:
   1164 			if (defport != -1)
   1165 				warnx("Unknown port `%s', using port %d",
   1166 				    port, defport);
   1167 			rv = defport;
   1168 		} else
   1169 			rv = ntohs(svp->s_port);
   1170 	} else if (nport < 1 || nport > MAX_IN_PORT_T || *ep != '\0')
   1171 		goto badparseport;
   1172 	else
   1173 		rv = nport;
   1174 	free(p);
   1175 	return (rv);
   1176 }
   1177 
   1178 /*
   1179  * Determine if given string is an IPv6 address or not.
   1180  * Return 1 for yes, 0 for no
   1181  */
   1182 int
   1183 isipv6addr(const char *addr)
   1184 {
   1185 	int rv = 0;
   1186 #ifdef INET6
   1187 	struct addrinfo hints, *res;
   1188 
   1189 	memset(&hints, 0, sizeof(hints));
   1190 	hints.ai_family = PF_INET6;
   1191 	hints.ai_socktype = SOCK_DGRAM;	/*dummy*/
   1192 	hints.ai_flags = AI_NUMERICHOST;
   1193 	if (getaddrinfo(addr, "0", &hints, &res) != 0)
   1194 		rv = 0;
   1195 	else {
   1196 		rv = 1;
   1197 		freeaddrinfo(res);
   1198 	}
   1199 	if (debug)
   1200 		fprintf(ttyout, "isipv6addr: got %d for %s\n", rv, addr);
   1201 #endif
   1202 	return (rv == 1) ? 1 : 0;
   1203 }
   1204 
   1205 
   1206 /*
   1207  * Internal version of connect(2); sets socket buffer sizes first and
   1208  * handles the syscall being interrupted.
   1209  * Returns -1 upon failure (with errno set to the problem), or 0 on success.
   1210  */
   1211 int
   1212 xconnect(int sock, const struct sockaddr *name, int namelen)
   1213 {
   1214 	int	rv;
   1215 
   1216 	setupsockbufsize(sock);
   1217 	rv = connect(sock, name, namelen);
   1218 	if (rv == -1 && errno == EINTR) {
   1219 		fd_set	connfd;
   1220 
   1221 		FD_ZERO(&connfd);
   1222 		FD_SET(sock, &connfd);
   1223 		do {
   1224 			rv = select(sock + 1, NULL, &connfd, NULL, NULL);
   1225 		} while (rv == -1 && errno == EINTR);
   1226 		if (rv > 0)
   1227 			rv = 0;
   1228 	}
   1229 	return (rv);
   1230 }
   1231 
   1232 /*
   1233  * Internal version of listen(2); sets socket buffer sizes first.
   1234  */
   1235 int
   1236 xlisten(int sock, int backlog)
   1237 {
   1238 
   1239 	setupsockbufsize(sock);
   1240 	return (listen(sock, backlog));
   1241 }
   1242 
   1243 /*
   1244  * malloc() with inbuilt error checking
   1245  */
   1246 void *
   1247 xmalloc(size_t size)
   1248 {
   1249 	void *p;
   1250 
   1251 	p = malloc(size);
   1252 	if (p == NULL)
   1253 		err(1, "Unable to allocate %ld bytes of memory", (long)size);
   1254 	return (p);
   1255 }
   1256 
   1257 /*
   1258  * sl_init() with inbuilt error checking
   1259  */
   1260 StringList *
   1261 xsl_init(void)
   1262 {
   1263 	StringList *p;
   1264 
   1265 	p = sl_init();
   1266 	if (p == NULL)
   1267 		err(1, "Unable to allocate memory for stringlist");
   1268 	return (p);
   1269 }
   1270 
   1271 /*
   1272  * sl_add() with inbuilt error checking
   1273  */
   1274 void
   1275 xsl_add(StringList *sl, char *i)
   1276 {
   1277 
   1278 	if (sl_add(sl, i) == -1)
   1279 		err(1, "Unable to add `%s' to stringlist", i);
   1280 }
   1281 
   1282 /*
   1283  * strdup() with inbuilt error checking
   1284  */
   1285 char *
   1286 xstrdup(const char *str)
   1287 {
   1288 	char *s;
   1289 
   1290 	if (str == NULL)
   1291 		errx(1, "xstrdup() called with NULL argument");
   1292 	s = strdup(str);
   1293 	if (s == NULL)
   1294 		err(1, "Unable to allocate memory for string copy");
   1295 	return (s);
   1296 }
   1297