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