Home | History | Annotate | Line # | Download | only in ftp
util.c revision 1.127
      1 /*	$NetBSD: util.c,v 1.127 2005/05/26 02:59:34 lukem Exp $	*/
      2 
      3 /*-
      4  * Copyright (c) 1997-2005 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.127 2005/05/26 02:59:34 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 		fprintf(ttyout, "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 (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 	if (debug) {
    272 #define DEBUG_FEAT(x) fprintf(ttyout, "features[" #x "] = %d\n", features[(x)])
    273 		DEBUG_FEAT(FEAT_FEAT);
    274 		DEBUG_FEAT(FEAT_MDTM);
    275 		DEBUG_FEAT(FEAT_MLST);
    276 		DEBUG_FEAT(FEAT_REST_STREAM);
    277 		DEBUG_FEAT(FEAT_SIZE);
    278 		DEBUG_FEAT(FEAT_TVFS);
    279 #undef DEBUG_FEAT
    280 	}
    281 	reply_callback = NULL;
    282 
    283 	verbose = overbose;
    284 }
    285 
    286 /*
    287  * Reset the various variables that indicate connection state back to
    288  * disconnected settings.
    289  * The caller is responsible for issuing any commands to the remote server
    290  * to perform a clean shutdown before this is invoked.
    291  */
    292 void
    293 cleanuppeer(void)
    294 {
    295 
    296 	if (cout)
    297 		(void)fclose(cout);
    298 	cout = NULL;
    299 	connected = 0;
    300 	unix_server = 0;
    301 	unix_proxy = 0;
    302 			/*
    303 			 * determine if anonftp was specifically set with -a
    304 			 * (1), or implicitly set by auto_fetch() (2). in the
    305 			 * latter case, disable after the current xfer
    306 			 */
    307 	if (anonftp == 2)
    308 		anonftp = 0;
    309 	data = -1;
    310 	epsv4bad = 0;
    311 	if (username)
    312 		free(username);
    313 	username = NULL;
    314 	if (!proxy)
    315 		macnum = 0;
    316 }
    317 
    318 /*
    319  * Top-level signal handler for interrupted commands.
    320  */
    321 void
    322 intr(int signo)
    323 {
    324 
    325 	sigint_raised = 1;
    326 	alarmtimer(0);
    327 	if (fromatty)
    328 		write(fileno(ttyout), "\n", 1);
    329 	siglongjmp(toplevel, 1);
    330 }
    331 
    332 /*
    333  * Signal handler for lost connections; cleanup various elements of
    334  * the connection state, and call cleanuppeer() to finish it off.
    335  */
    336 void
    337 lostpeer(int dummy)
    338 {
    339 	int oerrno = errno;
    340 
    341 	alarmtimer(0);
    342 	if (connected) {
    343 		if (cout != NULL) {
    344 			(void)shutdown(fileno(cout), 1+1);
    345 			(void)fclose(cout);
    346 			cout = NULL;
    347 		}
    348 		if (data >= 0) {
    349 			(void)shutdown(data, 1+1);
    350 			(void)close(data);
    351 			data = -1;
    352 		}
    353 		connected = 0;
    354 	}
    355 	pswitch(1);
    356 	if (connected) {
    357 		if (cout != NULL) {
    358 			(void)shutdown(fileno(cout), 1+1);
    359 			(void)fclose(cout);
    360 			cout = NULL;
    361 		}
    362 		connected = 0;
    363 	}
    364 	proxflag = 0;
    365 	pswitch(0);
    366 	cleanuppeer();
    367 	errno = oerrno;
    368 }
    369 
    370 
    371 /*
    372  * Login to remote host, using given username & password if supplied.
    373  * Return non-zero if successful.
    374  */
    375 int
    376 ftp_login(const char *host, const char *user, const char *pass)
    377 {
    378 	char tmp[80];
    379 	const char *acct;
    380 	int n, aflag, rval, freeuser, freepass, freeacct;
    381 
    382 	acct = NULL;
    383 	aflag = rval = freeuser = freepass = freeacct = 0;
    384 
    385 	if (debug)
    386 		fprintf(ttyout, "ftp_login: user `%s' pass `%s' host `%s'\n",
    387 		    user ? user : "<null>", pass ? pass : "<null>",
    388 		    host ? host : "<null>");
    389 
    390 
    391 	/*
    392 	 * Set up arguments for an anonymous FTP session, if necessary.
    393 	 */
    394 	if (anonftp) {
    395 		user = "anonymous";	/* as per RFC 1635 */
    396 		pass = getoptionvalue("anonpass");
    397 	}
    398 
    399 	if (user == NULL)
    400 		freeuser = 1;
    401 	if (pass == NULL)
    402 		freepass = 1;
    403 	freeacct = 1;
    404 	if (ruserpass(host, &user, &pass, &acct) < 0) {
    405 		code = -1;
    406 		goto cleanup_ftp_login;
    407 	}
    408 
    409 	while (user == NULL) {
    410 		if (localname)
    411 			fprintf(ttyout, "Name (%s:%s): ", host, localname);
    412 		else
    413 			fprintf(ttyout, "Name (%s): ", host);
    414 		*tmp = '\0';
    415 		if (fgets(tmp, sizeof(tmp) - 1, stdin) == NULL) {
    416 			fprintf(ttyout, "\nEOF received; login aborted.\n");
    417 			clearerr(stdin);
    418 			code = -1;
    419 			goto cleanup_ftp_login;
    420 		}
    421 		tmp[strlen(tmp) - 1] = '\0';
    422 		freeuser = 0;
    423 		if (*tmp == '\0')
    424 			user = localname;
    425 		else
    426 			user = tmp;
    427 	}
    428 
    429 	if (gatemode) {
    430 		char *nuser;
    431 		size_t len;
    432 
    433 		len = strlen(user) + 1 + strlen(host) + 1;
    434 		nuser = xmalloc(len);
    435 		(void)strlcpy(nuser, user, len);
    436 		(void)strlcat(nuser, "@",  len);
    437 		(void)strlcat(nuser, host, len);
    438 		freeuser = 1;
    439 		user = nuser;
    440 	}
    441 
    442 	n = command("USER %s", user);
    443 	if (n == CONTINUE) {
    444 		if (pass == NULL) {
    445 			freepass = 0;
    446 			pass = getpass("Password:");
    447 		}
    448 		n = command("PASS %s", pass);
    449 	}
    450 	if (n == CONTINUE) {
    451 		aflag++;
    452 		if (acct == NULL) {
    453 			freeacct = 0;
    454 			acct = getpass("Account:");
    455 		}
    456 		if (acct[0] == '\0') {
    457 			warnx("Login failed.");
    458 			goto cleanup_ftp_login;
    459 		}
    460 		n = command("ACCT %s", acct);
    461 	}
    462 	if ((n != COMPLETE) ||
    463 	    (!aflag && acct != NULL && command("ACCT %s", acct) != COMPLETE)) {
    464 		warnx("Login failed.");
    465 		goto cleanup_ftp_login;
    466 	}
    467 	rval = 1;
    468 	username = xstrdup(user);
    469 	if (proxy)
    470 		goto cleanup_ftp_login;
    471 
    472 	connected = -1;
    473 	getremoteinfo();
    474 	for (n = 0; n < macnum; ++n) {
    475 		if (!strcmp("init", macros[n].mac_name)) {
    476 			(void)strlcpy(line, "$init", sizeof(line));
    477 			makeargv();
    478 			domacro(margc, margv);
    479 			break;
    480 		}
    481 	}
    482 	updatelocalcwd();
    483 	updateremotecwd();
    484 
    485  cleanup_ftp_login:
    486 	if (user != NULL && freeuser)
    487 		free((char *)user);
    488 	if (pass != NULL && freepass)
    489 		free((char *)pass);
    490 	if (acct != NULL && freeacct)
    491 		free((char *)acct);
    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 *prompt)
    503 {
    504 	int	ret;
    505 	size_t	len;
    506 
    507 	len = strlen(line);
    508 	if (len >= sizeof(line) - 3) {
    509 		fputs("sorry, arguments too long.\n", ttyout);
    510 		intr(0);
    511 	}
    512 	fprintf(ttyout, "(%s) ", prompt);
    513 	line[len++] = ' ';
    514 	if (fgets(&line[len], sizeof(line) - len, stdin) == NULL) {
    515 		clearerr(stdin);
    516 		intr(0);
    517 	}
    518 	len += strlen(&line[len]);
    519 	if (len > 0 && line[len - 1] == '\n')
    520 		line[len - 1] = '\0';
    521 	makeargv();
    522 	ret = margc > *pargc;
    523 	*pargc = margc;
    524 	*pargv = margv;
    525 	return (ret);
    526 }
    527 
    528 /*
    529  * glob files given in argv[] from the remote server.
    530  * if errbuf isn't NULL, store error messages there instead
    531  * of writing to the screen.
    532  */
    533 char *
    534 remglob(char *argv[], int doswitch, const char **errbuf)
    535 {
    536 	static char buf[MAXPATHLEN];
    537 	static FILE *ftemp = NULL;
    538 	static char **args;
    539 	char temp[MAXPATHLEN];
    540 	int oldverbose, oldhash, oldprogress, fd;
    541 	char *cp, *mode;
    542 	size_t len;
    543 
    544 	if (!mflag || !connected) {
    545 		if (!doglob)
    546 			args = NULL;
    547 		else {
    548 			if (ftemp) {
    549 				(void)fclose(ftemp);
    550 				ftemp = NULL;
    551 			}
    552 		}
    553 		return (NULL);
    554 	}
    555 	if (!doglob) {
    556 		if (args == NULL)
    557 			args = argv;
    558 		if ((cp = *++args) == NULL)
    559 			args = NULL;
    560 		return (cp);
    561 	}
    562 	if (ftemp == NULL) {
    563 		len = strlcpy(temp, tmpdir, sizeof(temp));
    564 		if (temp[len - 1] != '/')
    565 			(void)strlcat(temp, "/", sizeof(temp));
    566 		(void)strlcat(temp, TMPFILE, sizeof(temp));
    567 		if ((fd = mkstemp(temp)) < 0) {
    568 			warn("unable to create temporary file %s", temp);
    569 			return (NULL);
    570 		}
    571 		close(fd);
    572 		oldverbose = verbose;
    573 		verbose = (errbuf != NULL) ? -1 : 0;
    574 		oldhash = hash;
    575 		oldprogress = progress;
    576 		hash = 0;
    577 		progress = 0;
    578 		if (doswitch)
    579 			pswitch(!proxy);
    580 		for (mode = "w"; *++argv != NULL; mode = "a")
    581 			recvrequest("NLST", temp, *argv, mode, 0, 0);
    582 		if ((code / 100) != COMPLETE) {
    583 			if (errbuf != NULL)
    584 				*errbuf = reply_string;
    585 		}
    586 		if (doswitch)
    587 			pswitch(!proxy);
    588 		verbose = oldverbose;
    589 		hash = oldhash;
    590 		progress = oldprogress;
    591 		ftemp = fopen(temp, "r");
    592 		(void)unlink(temp);
    593 		if (ftemp == NULL) {
    594 			if (errbuf == NULL)
    595 				fputs(
    596 				    "can't find list of remote files, oops.\n",
    597 				    ttyout);
    598 			else
    599 				*errbuf =
    600 				    "can't find list of remote files, oops.";
    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 (xstrdup(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("%s: not found", pattern);
    635 		globfree(&gl);
    636 		return (NULL);
    637 	}
    638 	p = xstrdup(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 (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 && 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 (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 		int yy, mo, day, hour, min, sec;
    711 
    712 		/*
    713 		 * time-val = 14DIGIT [ "." 1*DIGIT ]
    714 		 *		YYYYMMDDHHMMSS[.sss]
    715 		 * mdtm-response = "213" SP time-val CRLF / error-response
    716 		 */
    717 		timestr = reply_string + 4;
    718 
    719 					/*
    720 					 * parse fraction.
    721 					 * XXX: ignored for now
    722 					 */
    723 		frac = strchr(timestr, '\r');
    724 		if (frac != NULL)
    725 			*frac = '\0';
    726 		frac = strchr(timestr, '.');
    727 		if (frac != NULL)
    728 			*frac++ = '\0';
    729 		if (strlen(timestr) == 15 && strncmp(timestr, "191", 3) == 0) {
    730 			/*
    731 			 * XXX:	Workaround for lame ftpd's that return
    732 			 *	`19100' instead of `2000'
    733 			 */
    734 			fprintf(ttyout,
    735 	    "Y2K warning! Incorrect time-val `%s' received from server.\n",
    736 			    timestr);
    737 			timestr++;
    738 			timestr[0] = '2';
    739 			timestr[1] = '0';
    740 			fprintf(ttyout, "Converted to `%s'\n", timestr);
    741 		}
    742 		if (strlen(timestr) != 14 ||
    743 		    sscanf(timestr, "%04d%02d%02d%02d%02d%02d",
    744 			&yy, &mo, &day, &hour, &min, &sec) != 6) {
    745  bad_parse_time:
    746 			fprintf(ttyout, "Can't parse time `%s'.\n", timestr);
    747 			goto cleanup_parse_time;
    748 		}
    749 		memset(&timebuf, 0, sizeof(timebuf));
    750 		timebuf.tm_sec = sec;
    751 		timebuf.tm_min = min;
    752 		timebuf.tm_hour = hour;
    753 		timebuf.tm_mday = day;
    754 		timebuf.tm_mon = mo - 1;
    755 		timebuf.tm_year = yy - TM_YEAR_BASE;
    756 		timebuf.tm_isdst = -1;
    757 		rtime = timegm(&timebuf);
    758 		if (rtime == -1) {
    759 			if (noisy || debug != 0)
    760 				goto bad_parse_time;
    761 			else
    762 				goto cleanup_parse_time;
    763 		} else if (debug)
    764 			fprintf(ttyout, "parsed date as: %s", ctime(&rtime));
    765 	} else {
    766 		if (r == ERROR && code == 500 && features[FEAT_MDTM] == -1)
    767 			features[FEAT_MDTM] = 0;
    768 		if (noisy && debug == 0) {
    769 			fputs(reply_string, ttyout);
    770 			putc('\n', ttyout);
    771 		}
    772 	}
    773  cleanup_parse_time:
    774 	verbose = overbose;
    775 	if (rtime == -1)
    776 		code = ocode;
    777 	return (rtime);
    778 }
    779 
    780 /*
    781  * Update global `localcwd', which contains the state of the local cwd
    782  */
    783 void
    784 updatelocalcwd(void)
    785 {
    786 
    787 	if (getcwd(localcwd, sizeof(localcwd)) == NULL)
    788 		localcwd[0] = '\0';
    789 	if (debug)
    790 		fprintf(ttyout, "got localcwd as `%s'\n", localcwd);
    791 }
    792 
    793 /*
    794  * Update global `remotecwd', which contains the state of the remote cwd
    795  */
    796 void
    797 updateremotecwd(void)
    798 {
    799 	int	 overbose, ocode, i;
    800 	char	*cp;
    801 
    802 	overbose = verbose;
    803 	ocode = code;
    804 	if (debug == 0)
    805 		verbose = -1;
    806 	if (command("PWD") != COMPLETE)
    807 		goto badremotecwd;
    808 	cp = strchr(reply_string, ' ');
    809 	if (cp == NULL || cp[0] == '\0' || cp[1] != '"')
    810 		goto badremotecwd;
    811 	cp += 2;
    812 	for (i = 0; *cp && i < sizeof(remotecwd) - 1; i++, cp++) {
    813 		if (cp[0] == '"') {
    814 			if (cp[1] == '"')
    815 				cp++;
    816 			else
    817 				break;
    818 		}
    819 		remotecwd[i] = *cp;
    820 	}
    821 	remotecwd[i] = '\0';
    822 	if (debug)
    823 		fprintf(ttyout, "got remotecwd as `%s'\n", remotecwd);
    824 	goto cleanupremotecwd;
    825  badremotecwd:
    826 	remotecwd[0]='\0';
    827  cleanupremotecwd:
    828 	verbose = overbose;
    829 	code = ocode;
    830 }
    831 
    832 /*
    833  * Ensure file is in or under dir.
    834  * Returns 1 if so, 0 if not (or an error occurred).
    835  */
    836 int
    837 fileindir(const char *file, const char *dir)
    838 {
    839 	char	parentdirbuf[PATH_MAX+1], *parentdir;
    840 	char	realdir[PATH_MAX+1];
    841 	size_t	dirlen;
    842 
    843 		 			/* determine parent directory of file */
    844 	(void)strlcpy(parentdirbuf, file, sizeof(parentdirbuf));
    845 	parentdir = dirname(parentdirbuf);
    846 	if (strcmp(parentdir, ".") == 0)
    847 		return 1;		/* current directory is ok */
    848 
    849 					/* find the directory */
    850 	if (realpath(parentdir, realdir) == NULL) {
    851 		warn("Unable to determine real path of `%s'", parentdir);
    852 		return 0;
    853 	}
    854 	if (realdir[0] != '/')		/* relative result is ok */
    855 		return 1;
    856 	dirlen = strlen(dir);
    857 #if 0
    858 printf("file %s parent %s realdir %s dir %s [%d]\n",
    859     file, parentdir, realdir, dir, dirlen);
    860 #endif
    861 	if (strncmp(realdir, dir, dirlen) == 0 &&
    862 	    (realdir[dirlen] == '/' || realdir[dirlen] == '\0'))
    863 		return 1;
    864 	return 0;
    865 }
    866 
    867 /*
    868  * List words in stringlist, vertically arranged
    869  */
    870 void
    871 list_vertical(StringList *sl)
    872 {
    873 	int i, j;
    874 	int columns, lines;
    875 	char *p;
    876 	size_t w, width;
    877 
    878 	width = 0;
    879 
    880 	for (i = 0 ; i < sl->sl_cur ; i++) {
    881 		w = strlen(sl->sl_str[i]);
    882 		if (w > width)
    883 			width = w;
    884 	}
    885 	width = (width + 8) &~ 7;
    886 
    887 	columns = ttywidth / width;
    888 	if (columns == 0)
    889 		columns = 1;
    890 	lines = (sl->sl_cur + columns - 1) / columns;
    891 	for (i = 0; i < lines; i++) {
    892 		for (j = 0; j < columns; j++) {
    893 			p = sl->sl_str[j * lines + i];
    894 			if (p)
    895 				fputs(p, ttyout);
    896 			if (j * lines + i + lines >= sl->sl_cur) {
    897 				putc('\n', ttyout);
    898 				break;
    899 			}
    900 			w = strlen(p);
    901 			while (w < width) {
    902 				w = (w + 8) &~ 7;
    903 				(void)putc('\t', ttyout);
    904 			}
    905 		}
    906 	}
    907 }
    908 
    909 /*
    910  * Update the global ttywidth value, using TIOCGWINSZ.
    911  */
    912 void
    913 setttywidth(int a)
    914 {
    915 	struct winsize winsize;
    916 	int oerrno = errno;
    917 
    918 	if (ioctl(fileno(ttyout), TIOCGWINSZ, &winsize) != -1 &&
    919 	    winsize.ws_col != 0)
    920 		ttywidth = winsize.ws_col;
    921 	else
    922 		ttywidth = 80;
    923 	errno = oerrno;
    924 }
    925 
    926 /*
    927  * Change the rate limit up (SIGUSR1) or down (SIGUSR2)
    928  */
    929 void
    930 crankrate(int sig)
    931 {
    932 
    933 	switch (sig) {
    934 	case SIGUSR1:
    935 		if (rate_get)
    936 			rate_get += rate_get_incr;
    937 		if (rate_put)
    938 			rate_put += rate_put_incr;
    939 		break;
    940 	case SIGUSR2:
    941 		if (rate_get && rate_get > rate_get_incr)
    942 			rate_get -= rate_get_incr;
    943 		if (rate_put && rate_put > rate_put_incr)
    944 			rate_put -= rate_put_incr;
    945 		break;
    946 	default:
    947 		err(1, "crankrate invoked with unknown signal: %d", sig);
    948 	}
    949 }
    950 
    951 
    952 /*
    953  * Setup or cleanup EditLine structures
    954  */
    955 #ifndef NO_EDITCOMPLETE
    956 void
    957 controlediting(void)
    958 {
    959 	if (editing && el == NULL && hist == NULL) {
    960 		HistEvent ev;
    961 		int editmode;
    962 
    963 		el = el_init(getprogname(), stdin, ttyout, stderr);
    964 		/* init editline */
    965 		hist = history_init();		/* init the builtin history */
    966 		history(hist, &ev, H_SETSIZE, 100);/* remember 100 events */
    967 		el_set(el, EL_HIST, history, hist);	/* use history */
    968 
    969 		el_set(el, EL_EDITOR, "emacs");	/* default editor is emacs */
    970 		el_set(el, EL_PROMPT, prompt);	/* set the prompt functions */
    971 		el_set(el, EL_RPROMPT, rprompt);
    972 
    973 		/* add local file completion, bind to TAB */
    974 		el_set(el, EL_ADDFN, "ftp-complete",
    975 		    "Context sensitive argument completion",
    976 		    complete);
    977 		el_set(el, EL_BIND, "^I", "ftp-complete", NULL);
    978 		el_source(el, NULL);	/* read ~/.editrc */
    979 		if ((el_get(el, EL_EDITMODE, &editmode) != -1) && editmode == 0)
    980 			editing = 0;	/* the user doesn't want editing,
    981 					 * so disable, and let statement
    982 					 * below cleanup */
    983 		else
    984 			el_set(el, EL_SIGNAL, 1);
    985 	}
    986 	if (!editing) {
    987 		if (hist) {
    988 			history_end(hist);
    989 			hist = NULL;
    990 		}
    991 		if (el) {
    992 			el_end(el);
    993 			el = NULL;
    994 		}
    995 	}
    996 }
    997 #endif /* !NO_EDITCOMPLETE */
    998 
    999 /*
   1000  * Convert the string `arg' to an int, which may have an optional SI suffix
   1001  * (`b', `k', `m', `g'). Returns the number for success, -1 otherwise.
   1002  */
   1003 int
   1004 strsuftoi(const char *arg)
   1005 {
   1006 	char *cp;
   1007 	long val;
   1008 
   1009 	if (!isdigit((unsigned char)arg[0]))
   1010 		return (-1);
   1011 
   1012 	val = strtol(arg, &cp, 10);
   1013 	if (cp != NULL) {
   1014 		if (cp[0] != '\0' && cp[1] != '\0')
   1015 			 return (-1);
   1016 		switch (tolower((unsigned char)cp[0])) {
   1017 		case '\0':
   1018 		case 'b':
   1019 			break;
   1020 		case 'k':
   1021 			val <<= 10;
   1022 			break;
   1023 		case 'm':
   1024 			val <<= 20;
   1025 			break;
   1026 		case 'g':
   1027 			val <<= 30;
   1028 			break;
   1029 		default:
   1030 			return (-1);
   1031 		}
   1032 	}
   1033 	if (val < 0 || val > INT_MAX)
   1034 		return (-1);
   1035 
   1036 	return (val);
   1037 }
   1038 
   1039 /*
   1040  * Set up socket buffer sizes before a connection is made.
   1041  */
   1042 void
   1043 setupsockbufsize(int sock)
   1044 {
   1045 
   1046 	if (setsockopt(sock, SOL_SOCKET, SO_SNDBUF,
   1047 	    (void *)&sndbuf_size, sizeof(sndbuf_size)) == -1)
   1048 		warn("unable to set sndbuf size %d", sndbuf_size);
   1049 
   1050 	if (setsockopt(sock, SOL_SOCKET, SO_RCVBUF,
   1051 	    (void *)&rcvbuf_size, sizeof(rcvbuf_size)) == -1)
   1052 		warn("unable to set rcvbuf size %d", rcvbuf_size);
   1053 }
   1054 
   1055 /*
   1056  * Copy characters from src into dst, \ quoting characters that require it
   1057  */
   1058 void
   1059 ftpvis(char *dst, size_t dstlen, const char *src, size_t srclen)
   1060 {
   1061 	int	di, si;
   1062 
   1063 	for (di = si = 0;
   1064 	    src[si] != '\0' && di < dstlen && si < srclen;
   1065 	    di++, si++) {
   1066 		switch (src[si]) {
   1067 		case '\\':
   1068 		case ' ':
   1069 		case '\t':
   1070 		case '\r':
   1071 		case '\n':
   1072 		case '"':
   1073 			dst[di++] = '\\';
   1074 			if (di >= dstlen)
   1075 				break;
   1076 			/* FALLTHROUGH */
   1077 		default:
   1078 			dst[di] = src[si];
   1079 		}
   1080 	}
   1081 	dst[di] = '\0';
   1082 }
   1083 
   1084 /*
   1085  * Copy src into buf (which is len bytes long), expanding % sequences.
   1086  */
   1087 void
   1088 formatbuf(char *buf, size_t len, const char *src)
   1089 {
   1090 	const char	*p;
   1091 	char		*p2, *q;
   1092 	int		 i, op, updirs, pdirs;
   1093 
   1094 #define ADDBUF(x) do { \
   1095 		if (i >= len - 1) \
   1096 			goto endbuf; \
   1097 		buf[i++] = (x); \
   1098 	} while (0)
   1099 
   1100 	p = src;
   1101 	for (i = 0; *p; p++) {
   1102 		if (*p != '%') {
   1103 			ADDBUF(*p);
   1104 			continue;
   1105 		}
   1106 		p++;
   1107 
   1108 		switch (op = *p) {
   1109 
   1110 		case '/':
   1111 		case '.':
   1112 		case 'c':
   1113 			p2 = connected ? remotecwd : "";
   1114 			updirs = pdirs = 0;
   1115 
   1116 			/* option to determine fixed # of dirs from path */
   1117 			if (op == '.' || op == 'c') {
   1118 				int skip;
   1119 
   1120 				q = p2;
   1121 				while (*p2)		/* calc # of /'s */
   1122 					if (*p2++ == '/')
   1123 						updirs++;
   1124 				if (p[1] == '0') {	/* print <x> or ... */
   1125 					pdirs = 1;
   1126 					p++;
   1127 				}
   1128 				if (p[1] >= '1' && p[1] <= '9') {
   1129 							/* calc # to skip  */
   1130 					skip = p[1] - '0';
   1131 					p++;
   1132 				} else
   1133 					skip = 1;
   1134 
   1135 				updirs -= skip;
   1136 				while (skip-- > 0) {
   1137 					while ((p2 > q) && (*p2 != '/'))
   1138 						p2--;	/* back up */
   1139 					if (skip && p2 > q)
   1140 						p2--;
   1141 				}
   1142 				if (*p2 == '/' && p2 != q)
   1143 					p2++;
   1144 			}
   1145 
   1146 			if (updirs > 0 && pdirs) {
   1147 				if (i >= len - 5)
   1148 					break;
   1149 				if (op == '.') {
   1150 					ADDBUF('.');
   1151 					ADDBUF('.');
   1152 					ADDBUF('.');
   1153 				} else {
   1154 					ADDBUF('/');
   1155 					ADDBUF('<');
   1156 					if (updirs > 9) {
   1157 						ADDBUF('9');
   1158 						ADDBUF('+');
   1159 					} else
   1160 						ADDBUF('0' + updirs);
   1161 					ADDBUF('>');
   1162 				}
   1163 			}
   1164 			for (; *p2; p2++)
   1165 				ADDBUF(*p2);
   1166 			break;
   1167 
   1168 		case 'M':
   1169 		case 'm':
   1170 			for (p2 = connected && username ? username : "-";
   1171 			    *p2 ; p2++) {
   1172 				if (op == 'm' && *p2 == '.')
   1173 					break;
   1174 				ADDBUF(*p2);
   1175 			}
   1176 			break;
   1177 
   1178 		case 'n':
   1179 			for (p2 = connected ? username : "-"; *p2 ; p2++)
   1180 				ADDBUF(*p2);
   1181 			break;
   1182 
   1183 		case '%':
   1184 			ADDBUF('%');
   1185 			break;
   1186 
   1187 		default:		/* display unknown codes literally */
   1188 			ADDBUF('%');
   1189 			ADDBUF(op);
   1190 			break;
   1191 
   1192 		}
   1193 	}
   1194  endbuf:
   1195 	buf[i] = '\0';
   1196 }
   1197 
   1198 /*
   1199  * Parse `port' into a TCP port number, defaulting to `defport' if `port' is
   1200  * an unknown service name. If defport != -1, print a warning upon bad parse.
   1201  */
   1202 int
   1203 parseport(const char *port, int defport)
   1204 {
   1205 	int	 rv;
   1206 	long	 nport;
   1207 	char	*p, *ep;
   1208 
   1209 	p = xstrdup(port);
   1210 	nport = strtol(p, &ep, 10);
   1211 	if (*ep != '\0' && ep == p) {
   1212 		struct servent	*svp;
   1213 
   1214 		svp = getservbyname(port, "tcp");
   1215 		if (svp == NULL) {
   1216  badparseport:
   1217 			if (defport != -1)
   1218 				warnx("Unknown port `%s', using port %d",
   1219 				    port, defport);
   1220 			rv = defport;
   1221 		} else
   1222 			rv = ntohs(svp->s_port);
   1223 	} else if (nport < 1 || nport > MAX_IN_PORT_T || *ep != '\0')
   1224 		goto badparseport;
   1225 	else
   1226 		rv = nport;
   1227 	free(p);
   1228 	return (rv);
   1229 }
   1230 
   1231 /*
   1232  * Determine if given string is an IPv6 address or not.
   1233  * Return 1 for yes, 0 for no
   1234  */
   1235 int
   1236 isipv6addr(const char *addr)
   1237 {
   1238 	int rv = 0;
   1239 #ifdef INET6
   1240 	struct addrinfo hints, *res;
   1241 
   1242 	memset(&hints, 0, sizeof(hints));
   1243 	hints.ai_family = PF_INET6;
   1244 	hints.ai_socktype = SOCK_DGRAM;	/*dummy*/
   1245 	hints.ai_flags = AI_NUMERICHOST;
   1246 	if (getaddrinfo(addr, "0", &hints, &res) != 0)
   1247 		rv = 0;
   1248 	else {
   1249 		rv = 1;
   1250 		freeaddrinfo(res);
   1251 	}
   1252 	if (debug)
   1253 		fprintf(ttyout, "isipv6addr: got %d for %s\n", rv, addr);
   1254 #endif
   1255 	return (rv == 1) ? 1 : 0;
   1256 }
   1257 
   1258 
   1259 /*
   1260  * Internal version of connect(2); sets socket buffer sizes first and
   1261  * supports a connection timeout using a non-blocking connect(2) with
   1262  * a poll(2).
   1263  * Socket fcntl flags are temporarily updated to include O_NONBLOCK;
   1264  * these will not be reverted on connection failure.
   1265  * Returns -1 upon failure (with errno set to the problem), or 0 on success.
   1266  */
   1267 int
   1268 xconnect(int sock, const struct sockaddr *name, socklen_t namelen)
   1269 {
   1270 	int		flags, rv, timeout, error;
   1271 	socklen_t	slen;
   1272 	struct timeval	endtime, now, td;
   1273 	struct pollfd	pfd[1];
   1274 
   1275 	setupsockbufsize(sock);
   1276 
   1277 	if ((flags = fcntl(sock, F_GETFL, 0)) == -1)
   1278 		return -1;			/* get current socket flags  */
   1279 	if (fcntl(sock, F_SETFL, flags | O_NONBLOCK) == -1)
   1280 		return -1;			/* set non-blocking connect */
   1281 
   1282 	/* NOTE: we now must restore socket flags on successful exit */
   1283 
   1284 	pfd[0].fd = sock;
   1285 	pfd[0].events = POLLIN|POLLOUT;
   1286 
   1287 	if (quit_time > 0) {			/* want a non default timeout */
   1288 		(void)gettimeofday(&endtime, NULL);
   1289 		endtime.tv_sec += quit_time;	/* determine end time */
   1290 	}
   1291 
   1292 	rv = connect(sock, name, namelen);	/* inititate the connection */
   1293 	if (rv == -1) {				/* connection error */
   1294 		if (errno != EINPROGRESS)	/* error isn't "please wait" */
   1295 			return -1;
   1296 
   1297 						/* connect EINPROGRESS; wait */
   1298 		do {
   1299 			if (quit_time > 0) {	/* determine timeout */
   1300 				(void)gettimeofday(&now, NULL);
   1301 				timersub(&endtime, &now, &td);
   1302 				timeout = td.tv_sec * 1000 + td.tv_usec/1000;
   1303 				if (timeout < 0)
   1304 					timeout = 0;
   1305 			} else {
   1306 				timeout = INFTIM;
   1307 			}
   1308 			pfd[0].revents = 0;
   1309 			rv = xpoll(pfd, 1, timeout);
   1310 						/* loop until poll ! EINTR */
   1311 		} while (rv == -1 && errno == EINTR);
   1312 
   1313 		if (rv == 0) {			/* poll (connect) timed out */
   1314 			errno = ETIMEDOUT;
   1315 			return -1;
   1316 		}
   1317 
   1318 		if (rv == -1) {			/* poll error */
   1319 			return -1;
   1320 		} else if (pfd[0].revents & (POLLIN|POLLOUT)) {
   1321 			slen = sizeof(error);	/* OK, or pending error */
   1322 			if (getsockopt(sock, SOL_SOCKET, SO_ERROR,
   1323 			    &error, &slen) == -1)
   1324 				return -1;	/* Solaris pending error */
   1325 			if (error != 0) {
   1326 				errno = error;	/* BSD pending error */
   1327 				return -1;
   1328 			}
   1329 		} else {
   1330 			errno = EBADF;		/* this shouldn't happen ... */
   1331 			return -1;
   1332 		}
   1333 	}
   1334 
   1335 	if (fcntl(sock, F_SETFL, flags) == -1)	/* restore socket flags */
   1336 		return -1;
   1337 	return 0;
   1338 }
   1339 
   1340 /*
   1341  * Internal version of listen(2); sets socket buffer sizes first.
   1342  */
   1343 int
   1344 xlisten(int sock, int backlog)
   1345 {
   1346 
   1347 	setupsockbufsize(sock);
   1348 	return (listen(sock, backlog));
   1349 }
   1350 
   1351 /*
   1352  * Internal version of poll(2), to allow reimplementation by select(2)
   1353  * on platforms without the former.
   1354  */
   1355 int
   1356 xpoll(struct pollfd *fds, int nfds, int timeout)
   1357 {
   1358 	return poll(fds, nfds, timeout);
   1359 }
   1360 
   1361 /*
   1362  * malloc() with inbuilt error checking
   1363  */
   1364 void *
   1365 xmalloc(size_t size)
   1366 {
   1367 	void *p;
   1368 
   1369 	p = malloc(size);
   1370 	if (p == NULL)
   1371 		err(1, "Unable to allocate %ld bytes of memory", (long)size);
   1372 	return (p);
   1373 }
   1374 
   1375 /*
   1376  * sl_init() with inbuilt error checking
   1377  */
   1378 StringList *
   1379 xsl_init(void)
   1380 {
   1381 	StringList *p;
   1382 
   1383 	p = sl_init();
   1384 	if (p == NULL)
   1385 		err(1, "Unable to allocate memory for stringlist");
   1386 	return (p);
   1387 }
   1388 
   1389 /*
   1390  * sl_add() with inbuilt error checking
   1391  */
   1392 void
   1393 xsl_add(StringList *sl, char *i)
   1394 {
   1395 
   1396 	if (sl_add(sl, i) == -1)
   1397 		err(1, "Unable to add `%s' to stringlist", i);
   1398 }
   1399 
   1400 /*
   1401  * strdup() with inbuilt error checking
   1402  */
   1403 char *
   1404 xstrdup(const char *str)
   1405 {
   1406 	char *s;
   1407 
   1408 	if (str == NULL)
   1409 		errx(1, "xstrdup() called with NULL argument");
   1410 	s = strdup(str);
   1411 	if (s == NULL)
   1412 		err(1, "Unable to allocate memory for string copy");
   1413 	return (s);
   1414 }
   1415