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