Home | History | Annotate | Line # | Download | only in ftp
util.c revision 1.160
      1 /*	$NetBSD: util.c,v 1.160 2019/06/22 23:40:53 christos Exp $	*/
      2 
      3 /*-
      4  * Copyright (c) 1997-2009 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  *
     23  * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
     24  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
     25  * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
     26  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
     27  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
     28  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
     29  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
     30  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
     31  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
     32  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
     33  * POSSIBILITY OF SUCH DAMAGE.
     34  */
     35 
     36 /*
     37  * Copyright (c) 1985, 1989, 1993, 1994
     38  *	The Regents of the University of California.  All rights reserved.
     39  *
     40  * Redistribution and use in source and binary forms, with or without
     41  * modification, are permitted provided that the following conditions
     42  * are met:
     43  * 1. Redistributions of source code must retain the above copyright
     44  *    notice, this list of conditions and the following disclaimer.
     45  * 2. Redistributions in binary form must reproduce the above copyright
     46  *    notice, this list of conditions and the following disclaimer in the
     47  *    documentation and/or other materials provided with the distribution.
     48  * 3. Neither the name of the University nor the names of its contributors
     49  *    may be used to endorse or promote products derived from this software
     50  *    without specific prior written permission.
     51  *
     52  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
     53  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
     54  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
     55  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
     56  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
     57  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
     58  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
     59  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
     60  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
     61  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
     62  * SUCH DAMAGE.
     63  */
     64 
     65 #include <sys/cdefs.h>
     66 #ifndef lint
     67 __RCSID("$NetBSD: util.c,v 1.160 2019/06/22 23:40:53 christos Exp $");
     68 #endif /* not lint */
     69 
     70 /*
     71  * FTP User Program -- Misc support routines
     72  */
     73 #include <sys/param.h>
     74 #include <sys/socket.h>
     75 #include <sys/ioctl.h>
     76 #include <sys/time.h>
     77 #include <netinet/in.h>
     78 #include <arpa/ftp.h>
     79 
     80 #include <ctype.h>
     81 #include <err.h>
     82 #include <errno.h>
     83 #include <fcntl.h>
     84 #include <glob.h>
     85 #include <signal.h>
     86 #include <libgen.h>
     87 #include <limits.h>
     88 #include <locale.h>
     89 #include <netdb.h>
     90 #include <stdio.h>
     91 #include <stdlib.h>
     92 #include <string.h>
     93 #include <termios.h>
     94 #include <time.h>
     95 #include <tzfile.h>
     96 #include <unistd.h>
     97 
     98 #include "ftp_var.h"
     99 
    100 /*
    101  * Connect to peer server and auto-login, if possible.
    102  */
    103 void
    104 setpeer(int argc, char *argv[])
    105 {
    106 	char *host;
    107 	const char *port;
    108 
    109 	if (argc == 0)
    110 		goto usage;
    111 	if (connected) {
    112 		fprintf(ttyout, "Already connected to %s, use close first.\n",
    113 		    hostname);
    114 		code = -1;
    115 		return;
    116 	}
    117 	if (argc < 2)
    118 		(void)another(&argc, &argv, "to");
    119 	if (argc < 2 || argc > 3) {
    120  usage:
    121 		UPRINTF("usage: %s host-name [port]\n", argv[0]);
    122 		code = -1;
    123 		return;
    124 	}
    125 	if (gatemode)
    126 		port = gateport;
    127 	else
    128 		port = ftpport;
    129 	if (argc > 2)
    130 		port = argv[2];
    131 
    132 	if (gatemode) {
    133 		if (gateserver == NULL || *gateserver == '\0')
    134 			errx(1, "main: gateserver not defined");
    135 		host = hookup(gateserver, port);
    136 	} else
    137 		host = hookup(argv[1], port);
    138 
    139 	if (host) {
    140 		if (gatemode && verbose) {
    141 			fprintf(ttyout,
    142 			    "Connecting via pass-through server %s\n",
    143 			    gateserver);
    144 		}
    145 
    146 		connected = 1;
    147 		/*
    148 		 * Set up defaults for FTP.
    149 		 */
    150 		(void)strlcpy(typename, "ascii", sizeof(typename));
    151 		type = TYPE_A;
    152 		curtype = TYPE_A;
    153 		(void)strlcpy(formname, "non-print", sizeof(formname));
    154 		form = FORM_N;
    155 		(void)strlcpy(modename, "stream", sizeof(modename));
    156 		mode = MODE_S;
    157 		(void)strlcpy(structname, "file", sizeof(structname));
    158 		stru = STRU_F;
    159 		(void)strlcpy(bytename, "8", sizeof(bytename));
    160 		bytesize = 8;
    161 		if (autologin)
    162 			(void)ftp_login(argv[1], NULL, NULL);
    163 	}
    164 }
    165 
    166 static void
    167 parse_feat(const char *fline)
    168 {
    169 
    170 			/*
    171 			 * work-around broken ProFTPd servers that can't
    172 			 * even obey RFC 2389.
    173 			 */
    174 	while (*fline && isspace((int)*fline))
    175 		fline++;
    176 
    177 	if (strcasecmp(fline, "MDTM") == 0)
    178 		features[FEAT_MDTM] = 1;
    179 	else if (strncasecmp(fline, "MLST", sizeof("MLST") - 1) == 0) {
    180 		features[FEAT_MLST] = 1;
    181 	} else if (strcasecmp(fline, "REST STREAM") == 0)
    182 		features[FEAT_REST_STREAM] = 1;
    183 	else if (strcasecmp(fline, "SIZE") == 0)
    184 		features[FEAT_SIZE] = 1;
    185 	else if (strcasecmp(fline, "TVFS") == 0)
    186 		features[FEAT_TVFS] = 1;
    187 }
    188 
    189 /*
    190  * Determine the remote system type (SYST) and features (FEAT).
    191  * Call after a successful login (i.e, connected = -1)
    192  */
    193 void
    194 getremoteinfo(void)
    195 {
    196 	int overbose, i;
    197 
    198 	overbose = verbose;
    199 	if (ftp_debug == 0)
    200 		verbose = -1;
    201 
    202 			/* determine remote system type */
    203 	if (command("SYST") == COMPLETE) {
    204 		if (overbose) {
    205 			int os_len = strcspn(reply_string + 4, " \r\n\t");
    206 			if (os_len > 1 && reply_string[4 + os_len - 1] == '.')
    207 				os_len--;
    208 			fprintf(ttyout, "Remote system type is %.*s.\n",
    209 			    os_len, reply_string + 4);
    210 		}
    211 		/*
    212 		 * Decide whether we should default to bninary.
    213 		 * Traditionally checked for "215 UNIX Type: L8", but
    214 		 * some printers report "Linux" ! so be more forgiving.
    215 		 * In reality we probably almost never want text any more.
    216 		 */
    217 		if (!strncasecmp(reply_string + 4, "unix", 4) ||
    218 		    !strncasecmp(reply_string + 4, "linux", 5)) {
    219 			if (proxy)
    220 				unix_proxy = 1;
    221 			else
    222 				unix_server = 1;
    223 			/*
    224 			 * Set type to 0 (not specified by user),
    225 			 * meaning binary by default, but don't bother
    226 			 * telling server.  We can use binary
    227 			 * for text files unless changed by the user.
    228 			 */
    229 			type = 0;
    230 			(void)strlcpy(typename, "binary", sizeof(typename));
    231 			if (overbose)
    232 			    fprintf(ttyout,
    233 				"Using %s mode to transfer files.\n",
    234 				typename);
    235 		} else {
    236 			if (proxy)
    237 				unix_proxy = 0;
    238 			else
    239 				unix_server = 0;
    240 			if (overbose &&
    241 			    !strncmp(reply_string, "215 TOPS20", 10))
    242 				fputs(
    243 "Remember to set tenex mode when transferring binary files from this machine.\n",
    244 				    ttyout);
    245 		}
    246 	}
    247 
    248 			/* determine features (if any) */
    249 	for (i = 0; i < FEAT_max; i++)
    250 		features[i] = -1;
    251 	reply_callback = parse_feat;
    252 	if (command("FEAT") == COMPLETE) {
    253 		for (i = 0; i < FEAT_max; i++) {
    254 			if (features[i] == -1)
    255 				features[i] = 0;
    256 		}
    257 		features[FEAT_FEAT] = 1;
    258 	} else
    259 		features[FEAT_FEAT] = 0;
    260 #ifndef NO_DEBUG
    261 	if (ftp_debug) {
    262 #define DEBUG_FEAT(x) fprintf(ttyout, "features[" #x "] = %d\n", features[(x)])
    263 		DEBUG_FEAT(FEAT_FEAT);
    264 		DEBUG_FEAT(FEAT_MDTM);
    265 		DEBUG_FEAT(FEAT_MLST);
    266 		DEBUG_FEAT(FEAT_REST_STREAM);
    267 		DEBUG_FEAT(FEAT_SIZE);
    268 		DEBUG_FEAT(FEAT_TVFS);
    269 #undef DEBUG_FEAT
    270 	}
    271 #endif
    272 	reply_callback = NULL;
    273 
    274 	verbose = overbose;
    275 }
    276 
    277 /*
    278  * Reset the various variables that indicate connection state back to
    279  * disconnected settings.
    280  * The caller is responsible for issuing any commands to the remote server
    281  * to perform a clean shutdown before this is invoked.
    282  */
    283 void
    284 cleanuppeer(void)
    285 {
    286 
    287 	if (cout)
    288 		(void)fclose(cout);
    289 	cout = NULL;
    290 	connected = 0;
    291 	unix_server = 0;
    292 	unix_proxy = 0;
    293 			/*
    294 			 * determine if anonftp was specifically set with -a
    295 			 * (1), or implicitly set by auto_fetch() (2). in the
    296 			 * latter case, disable after the current xfer
    297 			 */
    298 	if (anonftp == 2)
    299 		anonftp = 0;
    300 	data = -1;
    301 	epsv4bad = 0;
    302 	epsv6bad = 0;
    303 	if (username)
    304 		free(username);
    305 	username = NULL;
    306 	if (!proxy)
    307 		macnum = 0;
    308 }
    309 
    310 /*
    311  * Top-level signal handler for interrupted commands.
    312  */
    313 void
    314 intr(int signo)
    315 {
    316 
    317 	sigint_raised = 1;
    318 	alarmtimer(0);
    319 	if (fromatty)
    320 		write(fileno(ttyout), "\n", 1);
    321 	siglongjmp(toplevel, 1);
    322 }
    323 
    324 /*
    325  * Signal handler for lost connections; cleanup various elements of
    326  * the connection state, and call cleanuppeer() to finish it off.
    327  */
    328 void
    329 lostpeer(int dummy)
    330 {
    331 	int oerrno = errno;
    332 
    333 	alarmtimer(0);
    334 	if (connected) {
    335 		if (cout != NULL) {
    336 			(void)shutdown(fileno(cout), 1+1);
    337 			(void)fclose(cout);
    338 			cout = NULL;
    339 		}
    340 		if (data >= 0) {
    341 			(void)shutdown(data, 1+1);
    342 			(void)close(data);
    343 			data = -1;
    344 		}
    345 		connected = 0;
    346 	}
    347 	pswitch(1);
    348 	if (connected) {
    349 		if (cout != NULL) {
    350 			(void)shutdown(fileno(cout), 1+1);
    351 			(void)fclose(cout);
    352 			cout = NULL;
    353 		}
    354 		connected = 0;
    355 	}
    356 	proxflag = 0;
    357 	pswitch(0);
    358 	cleanuppeer();
    359 	errno = oerrno;
    360 }
    361 
    362 
    363 /*
    364  * Login to remote host, using given username & password if supplied.
    365  * Return non-zero if successful.
    366  */
    367 int
    368 ftp_login(const char *host, const char *luser, const char *lpass)
    369 {
    370 	char tmp[80];
    371 	char *fuser, *pass, *facct, *p;
    372 	char emptypass[] = "";
    373 	const char *errormsg;
    374 	int n, aflag, rval, nlen;
    375 
    376 	aflag = rval = 0;
    377 	fuser = pass = facct = NULL;
    378 	if (luser)
    379 		fuser = ftp_strdup(luser);
    380 	if (lpass)
    381 		pass = ftp_strdup(lpass);
    382 
    383 	DPRINTF("ftp_login: user `%s' pass `%s' host `%s'\n",
    384 	    STRorNULL(fuser), STRorNULL(pass), STRorNULL(host));
    385 
    386 	/*
    387 	 * Set up arguments for an anonymous FTP session, if necessary.
    388 	 */
    389 	if (anonftp) {
    390 		FREEPTR(fuser);
    391 		fuser = ftp_strdup("anonymous");	/* as per RFC 1635 */
    392 		FREEPTR(pass);
    393 		pass = ftp_strdup(getoptionvalue("anonpass"));
    394 	}
    395 
    396 	if (ruserpass(host, &fuser, &pass, &facct) < 0) {
    397 		code = -1;
    398 		goto cleanup_ftp_login;
    399 	}
    400 
    401 	while (fuser == NULL) {
    402 		if (localname)
    403 			fprintf(ttyout, "Name (%s:%s): ", host, localname);
    404 		else
    405 			fprintf(ttyout, "Name (%s): ", host);
    406 		errormsg = NULL;
    407 		nlen = get_line(stdin, tmp, sizeof(tmp), &errormsg);
    408 		if (nlen < 0) {
    409 			fprintf(ttyout, "%s; %s aborted.\n", errormsg, "login");
    410 			code = -1;
    411 			goto cleanup_ftp_login;
    412 		} else if (nlen == 0) {
    413 			fuser = ftp_strdup(localname);
    414 		} else {
    415 			fuser = ftp_strdup(tmp);
    416 		}
    417 	}
    418 
    419 	if (gatemode) {
    420 		char *nuser;
    421 		size_t len;
    422 
    423 		len = strlen(fuser) + 1 + strlen(host) + 1;
    424 		nuser = ftp_malloc(len);
    425 		(void)strlcpy(nuser, fuser, len);
    426 		(void)strlcat(nuser, "@",  len);
    427 		(void)strlcat(nuser, host, len);
    428 		FREEPTR(fuser);
    429 		fuser = nuser;
    430 	}
    431 
    432 	n = command("USER %s", fuser);
    433 	if (n == CONTINUE) {
    434 		if (pass == NULL) {
    435 			p = getpass("Password: ");
    436 			if (p == NULL)
    437 				p = emptypass;
    438 			pass = ftp_strdup(p);
    439 			memset(p, 0, strlen(p));
    440 		}
    441 		n = command("PASS %s", pass);
    442 		memset(pass, 0, strlen(pass));
    443 	}
    444 	if (n == CONTINUE) {
    445 		aflag++;
    446 		if (facct == NULL) {
    447 			p = getpass("Account: ");
    448 			if (p == NULL)
    449 				p = emptypass;
    450 			facct = ftp_strdup(p);
    451 			memset(p, 0, strlen(p));
    452 		}
    453 		if (facct[0] == '\0') {
    454 			warnx("Login failed");
    455 			goto cleanup_ftp_login;
    456 		}
    457 		n = command("ACCT %s", facct);
    458 		memset(facct, 0, strlen(facct));
    459 	}
    460 	if ((n != COMPLETE) ||
    461 	    (!aflag && facct != NULL && command("ACCT %s", facct) != COMPLETE)) {
    462 		warnx("Login failed");
    463 		goto cleanup_ftp_login;
    464 	}
    465 	rval = 1;
    466 	username = ftp_strdup(fuser);
    467 	if (proxy)
    468 		goto cleanup_ftp_login;
    469 
    470 	connected = -1;
    471 	getremoteinfo();
    472 	for (n = 0; n < macnum; ++n) {
    473 		if (!strcmp("init", macros[n].mac_name)) {
    474 			(void)strlcpy(line, "$init", sizeof(line));
    475 			makeargv();
    476 			domacro(margc, margv);
    477 			break;
    478 		}
    479 	}
    480 	updatelocalcwd();
    481 	remotecwd[0] = '\0';
    482 	remcwdvalid = 0;
    483 
    484  cleanup_ftp_login:
    485 	FREEPTR(fuser);
    486 	if (pass != NULL)
    487 		memset(pass, 0, strlen(pass));
    488 	FREEPTR(pass);
    489 	if (facct != NULL)
    490 		memset(facct, 0, strlen(facct));
    491 	FREEPTR(facct);
    492 	return (rval);
    493 }
    494 
    495 /*
    496  * `another' gets another argument, and stores the new argc and argv.
    497  * It reverts to the top level (via intr()) on EOF/error.
    498  *
    499  * Returns false if no new arguments have been added.
    500  */
    501 int
    502 another(int *pargc, char ***pargv, const char *aprompt)
    503 {
    504 	const char	*errormsg;
    505 	int		ret, nlen;
    506 	size_t		len;
    507 
    508 	len = strlen(line);
    509 	if (len >= sizeof(line) - 3) {
    510 		fputs("Sorry, arguments too long.\n", ttyout);
    511 		intr(0);
    512 	}
    513 	fprintf(ttyout, "(%s) ", aprompt);
    514 	line[len++] = ' ';
    515 	errormsg = NULL;
    516 	nlen = get_line(stdin, line + len, sizeof(line)-len, &errormsg);
    517 	if (nlen < 0) {
    518 		fprintf(ttyout, "%s; %s aborted.\n", errormsg, "operation");
    519 		intr(0);
    520 	}
    521 	len += nlen;
    522 	makeargv();
    523 	ret = margc > *pargc;
    524 	*pargc = margc;
    525 	*pargv = margv;
    526 	return (ret);
    527 }
    528 
    529 /*
    530  * glob files given in argv[] from the remote server.
    531  * if errbuf isn't NULL, store error messages there instead
    532  * of writing to the screen.
    533  */
    534 char *
    535 remglob(char *argv[], int doswitch, const char **errbuf)
    536 {
    537 	static char buf[MAXPATHLEN];
    538 	static FILE *ftemp = NULL;
    539 	static char **args;
    540 	char temp[MAXPATHLEN];
    541 	int oldverbose, oldhash, oldprogress, fd;
    542 	char *cp;
    543 	const char *rmode;
    544 	size_t len;
    545 
    546 	if (!mflag || !connected) {
    547 		if (!doglob)
    548 			args = NULL;
    549 		else {
    550 			if (ftemp) {
    551 				(void)fclose(ftemp);
    552 				ftemp = NULL;
    553 			}
    554 		}
    555 		return (NULL);
    556 	}
    557 	if (!doglob) {
    558 		if (args == NULL)
    559 			args = argv;
    560 		if ((cp = *++args) == NULL)
    561 			args = NULL;
    562 		return (cp);
    563 	}
    564 	if (ftemp == NULL) {
    565 		len = strlcpy(temp, tmpdir, sizeof(temp));
    566 		if (temp[len - 1] != '/')
    567 			(void)strlcat(temp, "/", sizeof(temp));
    568 		(void)strlcat(temp, TMPFILE, sizeof(temp));
    569 		if ((fd = mkstemp(temp)) < 0) {
    570 			warn("Unable to create temporary file `%s'", temp);
    571 			return (NULL);
    572 		}
    573 		close(fd);
    574 		oldverbose = verbose;
    575 		verbose = (errbuf != NULL) ? -1 : 0;
    576 		oldhash = hash;
    577 		oldprogress = progress;
    578 		hash = 0;
    579 		progress = 0;
    580 		if (doswitch)
    581 			pswitch(!proxy);
    582 		for (rmode = "w"; *++argv != NULL; rmode = "a")
    583 			recvrequest("NLST", temp, *argv, rmode, 0, 0);
    584 		if ((code / 100) != COMPLETE) {
    585 			if (errbuf != NULL)
    586 				*errbuf = reply_string;
    587 		}
    588 		if (doswitch)
    589 			pswitch(!proxy);
    590 		verbose = oldverbose;
    591 		hash = oldhash;
    592 		progress = oldprogress;
    593 		ftemp = fopen(temp, "r");
    594 		(void)unlink(temp);
    595 		if (ftemp == NULL) {
    596 			if (errbuf == NULL)
    597 				warnx("Can't find list of remote files");
    598 			else
    599 				*errbuf =
    600 				    "Can't find list of remote files";
    601 			return (NULL);
    602 		}
    603 	}
    604 	if (fgets(buf, sizeof(buf), ftemp) == NULL) {
    605 		(void)fclose(ftemp);
    606 		ftemp = NULL;
    607 		return (NULL);
    608 	}
    609 	if ((cp = strchr(buf, '\n')) != NULL)
    610 		*cp = '\0';
    611 	return (buf);
    612 }
    613 
    614 /*
    615  * Glob a local file name specification with the expectation of a single
    616  * return value. Can't control multiple values being expanded from the
    617  * expression, we return only the first.
    618  * Returns NULL on error, or a pointer to a buffer containing the filename
    619  * that's the caller's responsiblity to free(3) when finished with.
    620  */
    621 char *
    622 globulize(const char *pattern)
    623 {
    624 	glob_t gl;
    625 	int flags;
    626 	char *p;
    627 
    628 	if (!doglob)
    629 		return (ftp_strdup(pattern));
    630 
    631 	flags = GLOB_BRACE|GLOB_NOCHECK|GLOB_TILDE;
    632 	memset(&gl, 0, sizeof(gl));
    633 	if (glob(pattern, flags, NULL, &gl) || gl.gl_pathc == 0) {
    634 		warnx("Glob pattern `%s' not found", pattern);
    635 		globfree(&gl);
    636 		return (NULL);
    637 	}
    638 	p = ftp_strdup(gl.gl_pathv[0]);
    639 	globfree(&gl);
    640 	return (p);
    641 }
    642 
    643 /*
    644  * determine size of remote file
    645  */
    646 off_t
    647 remotesize(const char *file, int noisy)
    648 {
    649 	int overbose, r;
    650 	off_t size;
    651 
    652 	overbose = verbose;
    653 	size = -1;
    654 	if (ftp_debug == 0)
    655 		verbose = -1;
    656 	if (! features[FEAT_SIZE]) {
    657 		if (noisy)
    658 			fprintf(ttyout,
    659 			    "SIZE is not supported by remote server.\n");
    660 		goto cleanup_remotesize;
    661 	}
    662 	r = command("SIZE %s", file);
    663 	if (r == COMPLETE) {
    664 		char *cp, *ep;
    665 
    666 		cp = strchr(reply_string, ' ');
    667 		if (cp != NULL) {
    668 			cp++;
    669 			size = STRTOLL(cp, &ep, 10);
    670 			if (*ep != '\0' && !isspace((unsigned char)*ep))
    671 				size = -1;
    672 		}
    673 	} else {
    674 		if (r == ERROR && code == 500 && features[FEAT_SIZE] == -1)
    675 			features[FEAT_SIZE] = 0;
    676 		if (noisy && ftp_debug == 0) {
    677 			fputs(reply_string, ttyout);
    678 			putc('\n', ttyout);
    679 		}
    680 	}
    681  cleanup_remotesize:
    682 	verbose = overbose;
    683 	return (size);
    684 }
    685 
    686 /*
    687  * determine last modification time (in GMT) of remote file
    688  */
    689 time_t
    690 remotemodtime(const char *file, int noisy)
    691 {
    692 	int	overbose, ocode, r;
    693 	time_t	rtime;
    694 
    695 	overbose = verbose;
    696 	ocode = code;
    697 	rtime = -1;
    698 	if (ftp_debug == 0)
    699 		verbose = -1;
    700 	if (! features[FEAT_MDTM]) {
    701 		if (noisy)
    702 			fprintf(ttyout,
    703 			    "MDTM is not supported by remote server.\n");
    704 		goto cleanup_parse_time;
    705 	}
    706 	r = command("MDTM %s", file);
    707 	if (r == COMPLETE) {
    708 		struct tm timebuf;
    709 		char *timestr, *frac;
    710 
    711 		/*
    712 		 * time-val = 14DIGIT [ "." 1*DIGIT ]
    713 		 *		YYYYMMDDHHMMSS[.sss]
    714 		 * mdtm-response = "213" SP time-val CRLF / error-response
    715 		 */
    716 		timestr = reply_string + 4;
    717 
    718 					/*
    719 					 * parse fraction.
    720 					 * XXX: ignored for now
    721 					 */
    722 		frac = strchr(timestr, '\r');
    723 		if (frac != NULL)
    724 			*frac = '\0';
    725 		frac = strchr(timestr, '.');
    726 		if (frac != NULL)
    727 			*frac++ = '\0';
    728 		if (strlen(timestr) == 15 && strncmp(timestr, "191", 3) == 0) {
    729 			/*
    730 			 * XXX:	Workaround for lame ftpd's that return
    731 			 *	`19100' instead of `2000'
    732 			 */
    733 			fprintf(ttyout,
    734 	    "Y2K warning! Incorrect time-val `%s' received from server.\n",
    735 			    timestr);
    736 			timestr++;
    737 			timestr[0] = '2';
    738 			timestr[1] = '0';
    739 			fprintf(ttyout, "Converted to `%s'\n", timestr);
    740 		}
    741 		memset(&timebuf, 0, sizeof(timebuf));
    742 		if (strlen(timestr) != 14 ||
    743 		    (strptime(timestr, "%Y%m%d%H%M%S", &timebuf) == NULL)) {
    744  bad_parse_time:
    745 			fprintf(ttyout, "Can't parse time `%s'.\n", timestr);
    746 			goto cleanup_parse_time;
    747 		}
    748 		timebuf.tm_isdst = -1;
    749 		rtime = timegm(&timebuf);
    750 		if (rtime == -1) {
    751 			if (noisy || ftp_debug != 0)
    752 				goto bad_parse_time;
    753 			else
    754 				goto cleanup_parse_time;
    755 		} else {
    756 			DPRINTF("remotemodtime: parsed time `%s' as " LLF
    757 			    ", %s",
    758 			    timestr, (LLT)rtime,
    759 			    rfc2822time(localtime(&rtime)));
    760 		}
    761 	} else {
    762 		if (r == ERROR && code == 500 && features[FEAT_MDTM] == -1)
    763 			features[FEAT_MDTM] = 0;
    764 		if (noisy && ftp_debug == 0) {
    765 			fputs(reply_string, ttyout);
    766 			putc('\n', ttyout);
    767 		}
    768 	}
    769  cleanup_parse_time:
    770 	verbose = overbose;
    771 	if (rtime == -1)
    772 		code = ocode;
    773 	return (rtime);
    774 }
    775 
    776 /*
    777  * Format tm in an RFC 2822 compatible manner, with a trailing \n.
    778  * Returns a pointer to a static string containing the result.
    779  */
    780 const char *
    781 rfc2822time(const struct tm *tm)
    782 {
    783 	static char result[50];
    784 
    785 	if (strftime(result, sizeof(result),
    786 	    "%a, %d %b %Y %H:%M:%S %z\n", tm) == 0)
    787 		errx(1, "Can't convert RFC 2822 time: buffer too small");
    788 	return result;
    789 }
    790 
    791 /*
    792  * Parse HTTP-date as per RFC 2616.
    793  * Return a pointer to the next character of the consumed date string,
    794  * or NULL if failed.
    795  */
    796 const char *
    797 parse_rfc2616time(struct tm *parsed, const char *httpdate)
    798 {
    799 	const char *t;
    800 	const char *curlocale;
    801 
    802 	/* The representation of %a depends on the current locale. */
    803 	curlocale = setlocale(LC_TIME, NULL);
    804 	(void)setlocale(LC_TIME, "C");
    805 								/* RFC 1123 */
    806 	if ((t = strptime(httpdate, "%a, %d %b %Y %H:%M:%S GMT", parsed)) ||
    807 								/* RFC 850 */
    808 	    (t = strptime(httpdate, "%a, %d-%b-%y %H:%M:%S GMT", parsed)) ||
    809 								/* asctime */
    810 	    (t = strptime(httpdate, "%a, %b %d %H:%M:%S %Y", parsed))) {
    811 		;			/* do nothing */
    812 	}
    813 	(void)setlocale(LC_TIME, curlocale);
    814 	return t;
    815 }
    816 
    817 /*
    818  * Update global `localcwd', which contains the state of the local cwd
    819  */
    820 void
    821 updatelocalcwd(void)
    822 {
    823 
    824 	if (getcwd(localcwd, sizeof(localcwd)) == NULL)
    825 		localcwd[0] = '\0';
    826 	DPRINTF("updatelocalcwd: got `%s'\n", localcwd);
    827 }
    828 
    829 /*
    830  * Update global `remotecwd', which contains the state of the remote cwd
    831  */
    832 void
    833 updateremotecwd(void)
    834 {
    835 	int	 overbose, ocode;
    836 	size_t	 i;
    837 	char	*cp;
    838 
    839 	remcwdvalid = 1;	/* whether it works or not, we are done */
    840 	overbose = verbose;
    841 	ocode = code;
    842 	if (ftp_debug == 0)
    843 		verbose = -1;
    844 	if (command("PWD") != COMPLETE)
    845 		goto badremotecwd;
    846 	cp = strchr(reply_string, ' ');
    847 	if (cp == NULL || cp[0] == '\0' || cp[1] != '"')
    848 		goto badremotecwd;
    849 	cp += 2;
    850 	for (i = 0; *cp && i < sizeof(remotecwd) - 1; i++, cp++) {
    851 		if (cp[0] == '"') {
    852 			if (cp[1] == '"')
    853 				cp++;
    854 			else
    855 				break;
    856 		}
    857 		remotecwd[i] = *cp;
    858 	}
    859 	remotecwd[i] = '\0';
    860 	DPRINTF("updateremotecwd: got `%s'\n", remotecwd);
    861 	goto cleanupremotecwd;
    862  badremotecwd:
    863 	remotecwd[0]='\0';
    864  cleanupremotecwd:
    865 	verbose = overbose;
    866 	code = ocode;
    867 }
    868 
    869 /*
    870  * Ensure file is in or under dir.
    871  * Returns 1 if so, 0 if not (or an error occurred).
    872  */
    873 int
    874 fileindir(const char *file, const char *dir)
    875 {
    876 	char	parentdirbuf[PATH_MAX+1], *parentdir;
    877 	char	realdir[PATH_MAX+1];
    878 	size_t	dirlen;
    879 
    880 					/* determine parent directory of file */
    881 	(void)strlcpy(parentdirbuf, file, sizeof(parentdirbuf));
    882 	parentdir = dirname(parentdirbuf);
    883 	if (strcmp(parentdir, ".") == 0)
    884 		return 1;		/* current directory is ok */
    885 
    886 					/* find the directory */
    887 	if (realpath(parentdir, realdir) == NULL) {
    888 		warn("Unable to determine real path of `%s'", parentdir);
    889 		return 0;
    890 	}
    891 	if (realdir[0] != '/')		/* relative result is ok */
    892 		return 1;
    893 	dirlen = strlen(dir);
    894 	if (strncmp(realdir, dir, dirlen) == 0 &&
    895 	    (realdir[dirlen] == '/' || realdir[dirlen] == '\0'))
    896 		return 1;
    897 	return 0;
    898 }
    899 
    900 /*
    901  * List words in stringlist, vertically arranged
    902  */
    903 void
    904 list_vertical(StringList *sl)
    905 {
    906 	size_t i, j;
    907 	size_t columns, lines;
    908 	char *p;
    909 	size_t w, width;
    910 
    911 	width = 0;
    912 
    913 	for (i = 0 ; i < sl->sl_cur ; i++) {
    914 		w = strlen(sl->sl_str[i]);
    915 		if (w > width)
    916 			width = w;
    917 	}
    918 	width = (width + 8) &~ 7;
    919 
    920 	columns = ttywidth / width;
    921 	if (columns == 0)
    922 		columns = 1;
    923 	lines = (sl->sl_cur + columns - 1) / columns;
    924 	for (i = 0; i < lines; i++) {
    925 		for (j = 0; j < columns; j++) {
    926 			p = sl->sl_str[j * lines + i];
    927 			if (p)
    928 				fputs(p, ttyout);
    929 			if (j * lines + i + lines >= sl->sl_cur) {
    930 				putc('\n', ttyout);
    931 				break;
    932 			}
    933 			if (p) {
    934 				w = strlen(p);
    935 				while (w < width) {
    936 					w = (w + 8) &~ 7;
    937 					(void)putc('\t', ttyout);
    938 				}
    939 			}
    940 		}
    941 	}
    942 }
    943 
    944 /*
    945  * Update the global ttywidth value, using TIOCGWINSZ.
    946  */
    947 void
    948 setttywidth(int a)
    949 {
    950 	struct winsize winsize;
    951 	int oerrno = errno;
    952 
    953 	if (ioctl(fileno(ttyout), TIOCGWINSZ, &winsize) != -1 &&
    954 	    winsize.ws_col != 0)
    955 		ttywidth = winsize.ws_col;
    956 	else
    957 		ttywidth = 80;
    958 	errno = oerrno;
    959 }
    960 
    961 /*
    962  * Change the rate limit up (SIGUSR1) or down (SIGUSR2)
    963  */
    964 void
    965 crankrate(int sig)
    966 {
    967 
    968 	switch (sig) {
    969 	case SIGUSR1:
    970 		if (rate_get)
    971 			rate_get += rate_get_incr;
    972 		if (rate_put)
    973 			rate_put += rate_put_incr;
    974 		break;
    975 	case SIGUSR2:
    976 		if (rate_get && rate_get > rate_get_incr)
    977 			rate_get -= rate_get_incr;
    978 		if (rate_put && rate_put > rate_put_incr)
    979 			rate_put -= rate_put_incr;
    980 		break;
    981 	default:
    982 		err(1, "crankrate invoked with unknown signal: %d", sig);
    983 	}
    984 }
    985 
    986 
    987 /*
    988  * Setup or cleanup EditLine structures
    989  */
    990 #ifndef NO_EDITCOMPLETE
    991 void
    992 controlediting(void)
    993 {
    994 	if (editing && el == NULL && hist == NULL) {
    995 		HistEvent ev;
    996 		int editmode;
    997 
    998 		el = el_init(getprogname(), stdin, ttyout, stderr);
    999 		/* init editline */
   1000 		hist = history_init();		/* init the builtin history */
   1001 		history(hist, &ev, H_SETSIZE, 100);/* remember 100 events */
   1002 		el_set(el, EL_HIST, history, hist);	/* use history */
   1003 
   1004 		el_set(el, EL_EDITOR, "emacs");	/* default editor is emacs */
   1005 		el_set(el, EL_PROMPT, prompt);	/* set the prompt functions */
   1006 		el_set(el, EL_RPROMPT, rprompt);
   1007 
   1008 		/* add local file completion, bind to TAB */
   1009 		el_set(el, EL_ADDFN, "ftp-complete",
   1010 		    "Context sensitive argument completion",
   1011 		    complete);
   1012 		el_set(el, EL_BIND, "^I", "ftp-complete", NULL);
   1013 		el_source(el, NULL);	/* read ~/.editrc */
   1014 		if ((el_get(el, EL_EDITMODE, &editmode) != -1) && editmode == 0)
   1015 			editing = 0;	/* the user doesn't want editing,
   1016 					 * so disable, and let statement
   1017 					 * below cleanup */
   1018 		else
   1019 			el_set(el, EL_SIGNAL, 1);
   1020 	}
   1021 	if (!editing) {
   1022 		if (hist) {
   1023 			history_end(hist);
   1024 			hist = NULL;
   1025 		}
   1026 		if (el) {
   1027 			el_end(el);
   1028 			el = NULL;
   1029 		}
   1030 	}
   1031 }
   1032 #endif /* !NO_EDITCOMPLETE */
   1033 
   1034 /*
   1035  * Convert the string `arg' to an int, which may have an optional SI suffix
   1036  * (`b', `k', `m', `g'). Returns the number for success, -1 otherwise.
   1037  */
   1038 int
   1039 strsuftoi(const char *arg)
   1040 {
   1041 	char *cp;
   1042 	long val;
   1043 
   1044 	if (!isdigit((unsigned char)arg[0]))
   1045 		return (-1);
   1046 
   1047 	val = strtol(arg, &cp, 10);
   1048 	if (cp != NULL) {
   1049 		if (cp[0] != '\0' && cp[1] != '\0')
   1050 			 return (-1);
   1051 		switch (tolower((unsigned char)cp[0])) {
   1052 		case '\0':
   1053 		case 'b':
   1054 			break;
   1055 		case 'k':
   1056 			val <<= 10;
   1057 			break;
   1058 		case 'm':
   1059 			val <<= 20;
   1060 			break;
   1061 		case 'g':
   1062 			val <<= 30;
   1063 			break;
   1064 		default:
   1065 			return (-1);
   1066 		}
   1067 	}
   1068 	if (val < 0 || val > INT_MAX)
   1069 		return (-1);
   1070 
   1071 	return (val);
   1072 }
   1073 
   1074 /*
   1075  * Set up socket buffer sizes before a connection is made.
   1076  */
   1077 void
   1078 setupsockbufsize(int sock)
   1079 {
   1080 	socklen_t slen;
   1081 
   1082 	if (0 == rcvbuf_size) {
   1083 		slen = sizeof(rcvbuf_size);
   1084 		if (getsockopt(sock, SOL_SOCKET, SO_RCVBUF,
   1085 		    (void *)&rcvbuf_size, &slen) == -1)
   1086 			err(1, "Unable to determine rcvbuf size");
   1087 		if (rcvbuf_size <= 0)
   1088 			rcvbuf_size = 8 * 1024;
   1089 		if (rcvbuf_size > 8 * 1024 * 1024)
   1090 			rcvbuf_size = 8 * 1024 * 1024;
   1091 		DPRINTF("setupsockbufsize: rcvbuf_size determined as %d\n",
   1092 		    rcvbuf_size);
   1093 	}
   1094 	if (0 == sndbuf_size) {
   1095 		slen = sizeof(sndbuf_size);
   1096 		if (getsockopt(sock, SOL_SOCKET, SO_SNDBUF,
   1097 		    (void *)&sndbuf_size, &slen) == -1)
   1098 			err(1, "Unable to determine sndbuf size");
   1099 		if (sndbuf_size <= 0)
   1100 			sndbuf_size = 8 * 1024;
   1101 		if (sndbuf_size > 8 * 1024 * 1024)
   1102 			sndbuf_size = 8 * 1024 * 1024;
   1103 		DPRINTF("setupsockbufsize: sndbuf_size determined as %d\n",
   1104 		    sndbuf_size);
   1105 	}
   1106 
   1107 	if (setsockopt(sock, SOL_SOCKET, SO_SNDBUF,
   1108 	    (void *)&sndbuf_size, sizeof(sndbuf_size)) == -1)
   1109 		warn("Unable to set sndbuf size %d", sndbuf_size);
   1110 
   1111 	if (setsockopt(sock, SOL_SOCKET, SO_RCVBUF,
   1112 	    (void *)&rcvbuf_size, sizeof(rcvbuf_size)) == -1)
   1113 		warn("Unable to set rcvbuf size %d", rcvbuf_size);
   1114 }
   1115 
   1116 /*
   1117  * Copy characters from src into dst, \ quoting characters that require it
   1118  */
   1119 void
   1120 ftpvis(char *dst, size_t dstlen, const char *src, size_t srclen)
   1121 {
   1122 	size_t	di, si;
   1123 
   1124 	di = si = 0;
   1125 	while (src[si] != '\0' && di < dstlen && si < srclen) {
   1126 		switch (src[si]) {
   1127 		case '\\':
   1128 		case ' ':
   1129 		case '\t':
   1130 		case '\r':
   1131 		case '\n':
   1132 		case '"':
   1133 			/*
   1134 			 * Need room for two characters and NUL, avoiding
   1135 			 * incomplete escape sequences at end of dst.
   1136 			 */
   1137 			if (di >= dstlen - 3)
   1138 				break;
   1139 			dst[di++] = '\\';
   1140 			/* FALLTHROUGH */
   1141 		default:
   1142 			dst[di] = src[si++];
   1143 			if (di < dstlen)
   1144 				di++;
   1145 		}
   1146 	}
   1147 	dst[di] = '\0';
   1148 }
   1149 
   1150 /*
   1151  * Copy src into buf (which is len bytes long), expanding % sequences.
   1152  */
   1153 void
   1154 formatbuf(char *buf, size_t len, const char *src)
   1155 {
   1156 	const char	*p, *p2, *q;
   1157 	size_t		 i;
   1158 	int		 op, updirs, pdirs;
   1159 
   1160 #define ADDBUF(x) do { \
   1161 		if (i >= len - 1) \
   1162 			goto endbuf; \
   1163 		buf[i++] = (x); \
   1164 	} while (0)
   1165 
   1166 	p = src;
   1167 	for (i = 0; *p; p++) {
   1168 		if (*p != '%') {
   1169 			ADDBUF(*p);
   1170 			continue;
   1171 		}
   1172 		p++;
   1173 
   1174 		switch (op = *p) {
   1175 
   1176 		case '/':
   1177 		case '.':
   1178 		case 'c':
   1179 			if (connected && !remcwdvalid)
   1180 				updateremotecwd();
   1181 			p2 = connected ? remotecwd : "";
   1182 			updirs = pdirs = 0;
   1183 
   1184 			/* option to determine fixed # of dirs from path */
   1185 			if (op == '.' || op == 'c') {
   1186 				int skip;
   1187 
   1188 				q = p2;
   1189 				while (*p2)		/* calc # of /'s */
   1190 					if (*p2++ == '/')
   1191 						updirs++;
   1192 				if (p[1] == '0') {	/* print <x> or ... */
   1193 					pdirs = 1;
   1194 					p++;
   1195 				}
   1196 				if (p[1] >= '1' && p[1] <= '9') {
   1197 							/* calc # to skip  */
   1198 					skip = p[1] - '0';
   1199 					p++;
   1200 				} else
   1201 					skip = 1;
   1202 
   1203 				updirs -= skip;
   1204 				while (skip-- > 0) {
   1205 					while ((p2 > q) && (*p2 != '/'))
   1206 						p2--;	/* back up */
   1207 					if (skip && p2 > q)
   1208 						p2--;
   1209 				}
   1210 				if (*p2 == '/' && p2 != q)
   1211 					p2++;
   1212 			}
   1213 
   1214 			if (updirs > 0 && pdirs) {
   1215 				if (i >= len - 5)
   1216 					break;
   1217 				if (op == '.') {
   1218 					ADDBUF('.');
   1219 					ADDBUF('.');
   1220 					ADDBUF('.');
   1221 				} else {
   1222 					ADDBUF('/');
   1223 					ADDBUF('<');
   1224 					if (updirs > 9) {
   1225 						ADDBUF('9');
   1226 						ADDBUF('+');
   1227 					} else
   1228 						ADDBUF('0' + updirs);
   1229 					ADDBUF('>');
   1230 				}
   1231 			}
   1232 			for (; *p2; p2++)
   1233 				ADDBUF(*p2);
   1234 			break;
   1235 
   1236 		case 'M':
   1237 		case 'm':
   1238 			for (p2 = connected && hostname ? hostname : "-";
   1239 			    *p2 ; p2++) {
   1240 				if (op == 'm' && *p2 == '.')
   1241 					break;
   1242 				ADDBUF(*p2);
   1243 			}
   1244 			break;
   1245 
   1246 		case 'n':
   1247 			for (p2 = connected ? username : "-"; *p2 ; p2++)
   1248 				ADDBUF(*p2);
   1249 			break;
   1250 
   1251 		case '%':
   1252 			ADDBUF('%');
   1253 			break;
   1254 
   1255 		default:		/* display unknown codes literally */
   1256 			ADDBUF('%');
   1257 			ADDBUF(op);
   1258 			break;
   1259 
   1260 		}
   1261 	}
   1262  endbuf:
   1263 	buf[i] = '\0';
   1264 }
   1265 
   1266 /*
   1267  * Determine if given string is an IPv6 address or not.
   1268  * Return 1 for yes, 0 for no
   1269  */
   1270 int
   1271 isipv6addr(const char *addr)
   1272 {
   1273 	int rv = 0;
   1274 #ifdef INET6
   1275 	struct addrinfo hints, *res;
   1276 
   1277 	memset(&hints, 0, sizeof(hints));
   1278 	hints.ai_family = AF_INET6;
   1279 	hints.ai_socktype = SOCK_DGRAM;	/*dummy*/
   1280 	hints.ai_flags = AI_NUMERICHOST;
   1281 	if (getaddrinfo(addr, "0", &hints, &res) != 0)
   1282 		rv = 0;
   1283 	else {
   1284 		rv = 1;
   1285 		freeaddrinfo(res);
   1286 	}
   1287 	DPRINTF("isipv6addr: got %d for %s\n", rv, addr);
   1288 #endif
   1289 	return (rv == 1) ? 1 : 0;
   1290 }
   1291 
   1292 /*
   1293  * Read a line from the FILE stream into buf/buflen using fgets(), so up
   1294  * to buflen-1 chars will be read and the result will be NUL terminated.
   1295  * If the line has a trailing newline it will be removed.
   1296  * If the line is too long, excess characters will be read until
   1297  * newline/EOF/error.
   1298  * If EOF/error occurs or a too-long line is encountered and errormsg
   1299  * isn't NULL, it will be changed to a description of the problem.
   1300  * (The EOF message has a leading \n for cosmetic purposes).
   1301  * Returns:
   1302  *	>=0	length of line (excluding trailing newline) if all ok
   1303  *	-1	error occurred
   1304  *	-2	EOF encountered
   1305  *	-3	line was too long
   1306  */
   1307 int
   1308 get_line(FILE *stream, char *buf, size_t buflen, const char **errormsg)
   1309 {
   1310 	int	rv, ch;
   1311 	size_t	len;
   1312 
   1313 	if (fgets(buf, buflen, stream) == NULL) {
   1314 		if (feof(stream)) {	/* EOF */
   1315 			rv = -2;
   1316 			if (errormsg)
   1317 				*errormsg = "\nEOF received";
   1318 		} else  {		/* error */
   1319 			rv = -1;
   1320 			if (errormsg)
   1321 				*errormsg = "Error encountered";
   1322 		}
   1323 		clearerr(stream);
   1324 		return rv;
   1325 	}
   1326 	len = strlen(buf);
   1327 	if (buf[len-1] == '\n') {	/* clear any trailing newline */
   1328 		buf[--len] = '\0';
   1329 	} else if (len == buflen-1) {	/* line too long */
   1330 		while ((ch = getchar()) != '\n' && ch != EOF)
   1331 			continue;
   1332 		if (errormsg)
   1333 			*errormsg = "Input line is too long";
   1334 		clearerr(stream);
   1335 		return -3;
   1336 	}
   1337 	if (errormsg)
   1338 		*errormsg = NULL;
   1339 	return len;
   1340 }
   1341 
   1342 /*
   1343  * Internal version of connect(2); sets socket buffer sizes,
   1344  * binds to a specific local address (if set), and
   1345  * supports a connection timeout using a non-blocking connect(2) with
   1346  * a poll(2).
   1347  * Socket fcntl flags are temporarily updated to include O_NONBLOCK;
   1348  * these will not be reverted on connection failure.
   1349  * Returns 0 on success, or -1 upon failure (with an appropriate
   1350  * error message displayed.)
   1351  */
   1352 int
   1353 ftp_connect(int sock, const struct sockaddr *name, socklen_t namelen, int pe)
   1354 {
   1355 	int		flags, rv, timeout, error;
   1356 	socklen_t	slen;
   1357 	struct timeval	endtime, now, td;
   1358 	struct pollfd	pfd[1];
   1359 	char		hname[NI_MAXHOST];
   1360 	char		sname[NI_MAXSERV];
   1361 
   1362 	setupsockbufsize(sock);
   1363 	if (getnameinfo(name, namelen,
   1364 	    hname, sizeof(hname), sname, sizeof(sname),
   1365 	    NI_NUMERICHOST | NI_NUMERICSERV) != 0) {
   1366 		strlcpy(hname, "?", sizeof(hname));
   1367 		strlcpy(sname, "?", sizeof(sname));
   1368 	}
   1369 
   1370 	if (bindai != NULL) {			/* bind to specific addr */
   1371 		struct addrinfo *ai;
   1372 
   1373 		for (ai = bindai; ai != NULL; ai = ai->ai_next) {
   1374 			if (ai->ai_family == name->sa_family)
   1375 				break;
   1376 		}
   1377 		if (ai == NULL)
   1378 			ai = bindai;
   1379 		if (bind(sock, ai->ai_addr, ai->ai_addrlen) == -1) {
   1380 			char	bname[NI_MAXHOST];
   1381 			int	saveerr;
   1382 
   1383 			saveerr = errno;
   1384 			if (getnameinfo(ai->ai_addr, ai->ai_addrlen,
   1385 			    bname, sizeof(bname), NULL, 0, NI_NUMERICHOST) != 0)
   1386 				strlcpy(bname, "?", sizeof(bname));
   1387 			errno = saveerr;
   1388 			warn("Can't bind to `%s'", bname);
   1389 			return -1;
   1390 		}
   1391 	}
   1392 
   1393 						/* save current socket flags */
   1394 	if ((flags = fcntl(sock, F_GETFL, 0)) == -1) {
   1395 		warn("Can't %s socket flags for connect to `%s:%s'",
   1396 		    "save", hname, sname);
   1397 		return -1;
   1398 	}
   1399 						/* set non-blocking connect */
   1400 	if (fcntl(sock, F_SETFL, flags | O_NONBLOCK) == -1) {
   1401 		warn("Can't set socket non-blocking for connect to `%s:%s'",
   1402 		    hname, sname);
   1403 		return -1;
   1404 	}
   1405 
   1406 	/* NOTE: we now must restore socket flags on successful exit */
   1407 
   1408 	pfd[0].fd = sock;
   1409 	pfd[0].events = POLLIN|POLLOUT;
   1410 
   1411 	if (quit_time > 0) {			/* want a non default timeout */
   1412 		(void)gettimeofday(&endtime, NULL);
   1413 		endtime.tv_sec += quit_time;	/* determine end time */
   1414 	}
   1415 
   1416 	rv = connect(sock, name, namelen);	/* inititate the connection */
   1417 	if (rv == -1) {				/* connection error */
   1418 		if (errno != EINPROGRESS) {	/* error isn't "please wait" */
   1419 			if (pe || (errno != EHOSTUNREACH))
   1420  connecterror:
   1421 				warn("Can't connect to `%s:%s'", hname, sname);
   1422 			return -1;
   1423 		}
   1424 
   1425 						/* connect EINPROGRESS; wait */
   1426 		do {
   1427 			if (quit_time > 0) {	/* determine timeout */
   1428 				(void)gettimeofday(&now, NULL);
   1429 				timersub(&endtime, &now, &td);
   1430 				timeout = td.tv_sec * 1000 + td.tv_usec/1000;
   1431 				if (timeout < 0)
   1432 					timeout = 0;
   1433 			} else {
   1434 				timeout = INFTIM;
   1435 			}
   1436 			pfd[0].revents = 0;
   1437 			rv = ftp_poll(pfd, 1, timeout);
   1438 						/* loop until poll ! EINTR */
   1439 		} while (rv == -1 && errno == EINTR);
   1440 
   1441 		if (rv == 0) {			/* poll (connect) timed out */
   1442 			errno = ETIMEDOUT;
   1443 			goto connecterror;
   1444 		}
   1445 
   1446 		if (rv == -1) {			/* poll error */
   1447 			goto connecterror;
   1448 		} else if (pfd[0].revents & (POLLIN|POLLOUT)) {
   1449 			slen = sizeof(error);	/* OK, or pending error */
   1450 			if (getsockopt(sock, SOL_SOCKET, SO_ERROR,
   1451 			    &error, &slen) == -1) {
   1452 						/* Solaris pending error */
   1453 				goto connecterror;
   1454 			} else if (error != 0) {
   1455 				errno = error;	/* BSD pending error */
   1456 				goto connecterror;
   1457 			}
   1458 		} else {
   1459 			errno = EBADF;		/* this shouldn't happen ... */
   1460 			goto connecterror;
   1461 		}
   1462 	}
   1463 
   1464 	if (fcntl(sock, F_SETFL, flags) == -1) {
   1465 						/* restore socket flags */
   1466 		warn("Can't %s socket flags for connect to `%s:%s'",
   1467 		    "restore", hname, sname);
   1468 		return -1;
   1469 	}
   1470 	return 0;
   1471 }
   1472 
   1473 /*
   1474  * Internal version of listen(2); sets socket buffer sizes first.
   1475  */
   1476 int
   1477 ftp_listen(int sock, int backlog)
   1478 {
   1479 
   1480 	setupsockbufsize(sock);
   1481 	return (listen(sock, backlog));
   1482 }
   1483 
   1484 /*
   1485  * Internal version of poll(2), to allow reimplementation by select(2)
   1486  * on platforms without the former.
   1487  */
   1488 int
   1489 ftp_poll(struct pollfd *fds, int nfds, int timeout)
   1490 {
   1491 	return poll(fds, nfds, timeout);
   1492 }
   1493 
   1494 #ifndef SMALL
   1495 /*
   1496  * malloc() with inbuilt error checking
   1497  */
   1498 void *
   1499 ftp_malloc(size_t size)
   1500 {
   1501 	void *p;
   1502 
   1503 	p = malloc(size);
   1504 	if (p == NULL)
   1505 		err(1, "Unable to allocate %ld bytes of memory", (long)size);
   1506 	return (p);
   1507 }
   1508 
   1509 /*
   1510  * sl_init() with inbuilt error checking
   1511  */
   1512 StringList *
   1513 ftp_sl_init(void)
   1514 {
   1515 	StringList *p;
   1516 
   1517 	p = sl_init();
   1518 	if (p == NULL)
   1519 		err(1, "Unable to allocate memory for stringlist");
   1520 	return (p);
   1521 }
   1522 
   1523 /*
   1524  * sl_add() with inbuilt error checking
   1525  */
   1526 void
   1527 ftp_sl_add(StringList *sl, char *i)
   1528 {
   1529 
   1530 	if (sl_add(sl, i) == -1)
   1531 		err(1, "Unable to add `%s' to stringlist", i);
   1532 }
   1533 
   1534 /*
   1535  * strdup() with inbuilt error checking
   1536  */
   1537 char *
   1538 ftp_strdup(const char *str)
   1539 {
   1540 	char *s;
   1541 
   1542 	if (str == NULL)
   1543 		errx(1, "ftp_strdup: called with NULL argument");
   1544 	s = strdup(str);
   1545 	if (s == NULL)
   1546 		err(1, "Unable to allocate memory for string copy");
   1547 	return (s);
   1548 }
   1549 #endif
   1550