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