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