Home | History | Annotate | Line # | Download | only in ftp
util.c revision 1.85
      1 /*	$NetBSD: util.c,v 1.85 1999/11/28 06:32:05 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.85 1999/11/28 06:32:05 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 		int yy, mo, day, hour, min, sec;
    649 		sscanf(reply_string, "%*s %04d%02d%02d%02d%02d%02d", &yy, &mo,
    650 			&day, &hour, &min, &sec);
    651 		memset(&timebuf, 0, sizeof(timebuf));
    652 		timebuf.tm_sec = sec;
    653 		timebuf.tm_min = min;
    654 		timebuf.tm_hour = hour;
    655 		timebuf.tm_mday = day;
    656 		timebuf.tm_mon = mo - 1;
    657 		timebuf.tm_year = yy - TM_YEAR_BASE;
    658 		timebuf.tm_isdst = -1;
    659 		rtime = timegm(&timebuf);
    660 		if (rtime == -1 && (noisy || debug != 0))
    661 			fprintf(ttyout, "Can't convert %s to a time.\n",
    662 			    reply_string);
    663 	} else if (noisy && debug == 0) {
    664 		fputs(reply_string, ttyout);
    665 		putc('\n', ttyout);
    666 	}
    667 	verbose = overbose;
    668 	if (rtime == -1)
    669 		code = ocode;
    670 	return (rtime);
    671 }
    672 
    673 /*
    674  * update global `remotepwd', which contains the state of the remote cwd
    675  */
    676 void
    677 updateremotepwd()
    678 {
    679 	int	 overbose, ocode, i;
    680 	char	*cp;
    681 
    682 	overbose = verbose;
    683 	ocode = code;
    684 	if (debug == 0)
    685 		verbose = -1;
    686 	if (command("PWD") != COMPLETE)
    687 		goto badremotepwd;
    688 	cp = strchr(reply_string, ' ');
    689 	if (cp == NULL || cp[0] == '\0' || cp[1] != '"')
    690 		goto badremotepwd;
    691 	cp += 2;
    692 	for (i = 0; *cp && i < sizeof(remotepwd) - 1; i++, cp++) {
    693 		if (cp[0] == '"') {
    694 			if (cp[1] == '"')
    695 				cp++;
    696 			else
    697 				break;
    698 		}
    699 		remotepwd[i] = *cp;
    700 	}
    701 	remotepwd[i] = '\0';
    702 	if (debug)
    703 		fprintf(ttyout, "got remotepwd as `%s'\n", remotepwd);
    704 	goto cleanupremotepwd;
    705  badremotepwd:
    706 	remotepwd[0]='\0';
    707  cleanupremotepwd:
    708 	verbose = overbose;
    709 	code = ocode;
    710 }
    711 
    712 #ifndef	NO_PROGRESS
    713 
    714 /*
    715  * return non-zero if we're the current foreground process
    716  */
    717 int
    718 foregroundproc()
    719 {
    720 	static pid_t pgrp = -1;
    721 
    722 	if (pgrp == -1)
    723 		pgrp = getpgrp();
    724 
    725 	return (tcgetpgrp(fileno(ttyout)) == pgrp);
    726 }
    727 
    728 
    729 static void updateprogressmeter __P((int));
    730 
    731 /*
    732  * SIGALRM handler to update the progress meter
    733  */
    734 static void
    735 updateprogressmeter(dummy)
    736 	int dummy;
    737 {
    738 	int oerrno = errno;
    739 
    740 	progressmeter(0);
    741 	errno = oerrno;
    742 }
    743 #endif	/* NO_PROGRESS */
    744 
    745 
    746 /*
    747  * List of order of magnitude prefixes.
    748  * The last is `P', as 2^64 = 16384 Petabytes
    749  */
    750 static const char prefixes[] = " KMGTP";
    751 
    752 /*
    753  * Display a transfer progress bar if progress is non-zero.
    754  * SIGALRM is hijacked for use by this function.
    755  * - Before the transfer, set filesize to size of file (or -1 if unknown),
    756  *   and call with flag = -1. This starts the once per second timer,
    757  *   and a call to updateprogressmeter() upon SIGALRM.
    758  * - During the transfer, updateprogressmeter will call progressmeter
    759  *   with flag = 0
    760  * - After the transfer, call with flag = 1
    761  */
    762 static struct timeval start;
    763 static struct timeval lastupdate;
    764 
    765 #define	BUFLEFT	(sizeof(buf) - len)
    766 
    767 void
    768 progressmeter(flag)
    769 	int flag;
    770 {
    771 	static off_t lastsize;
    772 #ifndef NO_PROGRESS
    773 	struct timeval now, td, wait;
    774 	off_t cursize, abbrevsize, bytespersec;
    775 	double elapsed;
    776 	int ratio, barlength, i, len, remaining;
    777 
    778 			/*
    779 			 * Work variables for progress bar.
    780 			 *
    781 			 * XXX:	if the format of the progress bar changes
    782 			 *	(especially the number of characters in the
    783 			 *	`static' portion of it), be sure to update
    784 			 *	these appropriately.
    785 			 */
    786 	char		buf[256];	/* workspace for progress bar */
    787 #define	BAROVERHEAD	43		/* non `*' portion of progress bar */
    788 					/*
    789 					 * stars should contain at least
    790 					 * sizeof(buf) - BAROVERHEAD entries
    791 					 */
    792 	const char	stars[] =
    793 "*****************************************************************************"
    794 "*****************************************************************************"
    795 "*****************************************************************************";
    796 
    797 #endif
    798 
    799 	if (flag == -1) {
    800 		(void)gettimeofday(&start, NULL);
    801 		lastupdate = start;
    802 		lastsize = restart_point;
    803 	}
    804 #ifndef NO_PROGRESS
    805 	len = 0;
    806 	if (!progress || filesize <= 0)
    807 		return;
    808 
    809 	(void)gettimeofday(&now, NULL);
    810 	cursize = bytes + restart_point;
    811 	timersub(&now, &lastupdate, &wait);
    812 	if (cursize > lastsize) {
    813 		lastupdate = now;
    814 		lastsize = cursize;
    815 		wait.tv_sec = 0;
    816 	}
    817 
    818 	/*
    819 	 * print progress bar only if we are foreground process.
    820 	 */
    821 	if (! foregroundproc())
    822 		return;
    823 
    824 	ratio = (int)((double)cursize * 100.0 / (double)filesize);
    825 	ratio = MAX(ratio, 0);
    826 	ratio = MIN(ratio, 100);
    827 	len += snprintf(buf + len, BUFLEFT, "\r%3d%% ", ratio);
    828 
    829 			/*
    830 			 * calculate the length of the `*' bar, ensuring that
    831 			 * the number of stars won't exceed the buffer size
    832 			 */
    833 	barlength = MIN(sizeof(buf) - 1, ttywidth) - BAROVERHEAD;
    834 	if (barlength > 0) {
    835 		i = barlength * ratio / 100;
    836 		len += snprintf(buf + len, BUFLEFT,
    837 		    "|%.*s%*s|", i, stars, barlength - i, "");
    838 	}
    839 
    840 	abbrevsize = cursize;
    841 	for (i = 0; abbrevsize >= 100000 && i < sizeof(prefixes); i++)
    842 		abbrevsize >>= 10;
    843 	len += snprintf(buf + len, BUFLEFT,
    844 #ifndef NO_QUAD
    845 	    " %5lld %c%c ", (long long)abbrevsize,
    846 #else
    847 	    " %5ld %c%c ", (long)abbrevsize,
    848 #endif
    849 	    prefixes[i],
    850 	    i == 0 ? ' ' : 'B');
    851 
    852 	timersub(&now, &start, &td);
    853 	elapsed = td.tv_sec + (td.tv_usec / 1000000.0);
    854 
    855 	bytespersec = 0;
    856 	if (bytes > 0) {
    857 		bytespersec = bytes;
    858 		if (elapsed > 0.0)
    859 			bytespersec /= elapsed;
    860 	}
    861 	for (i = 1; bytespersec >= 1024000 && i < sizeof(prefixes); i++)
    862 		bytespersec >>= 10;
    863 	len += snprintf(buf + len, BUFLEFT,
    864 #ifndef NO_QUAD
    865 	    " %3lld.%02d %cB/s ", (long long)bytespersec / 1024,
    866 #else
    867 	    " %3ld.%02d %cB/s ", (long)bytespersec / 1024,
    868 #endif
    869 	    (int)((bytespersec % 1024) * 100 / 1024),
    870 	    prefixes[i]);
    871 
    872 	if (bytes <= 0 || elapsed <= 0.0 || cursize > filesize) {
    873 		len += snprintf(buf + len, BUFLEFT, "   --:-- ETA");
    874 	} else if (wait.tv_sec >= STALLTIME) {
    875 		len += snprintf(buf + len, BUFLEFT, " - stalled -");
    876 	} else {
    877 		remaining = (int)
    878 		    ((filesize - restart_point) / (bytes / elapsed) - elapsed);
    879 		if (remaining >= 100 * SECSPERHOUR)
    880 			len += snprintf(buf + len, BUFLEFT, "   --:-- ETA");
    881 		else {
    882 			i = remaining / SECSPERHOUR;
    883 			if (i)
    884 				len += snprintf(buf + len, BUFLEFT, "%2d:", i);
    885 			else
    886 				len += snprintf(buf + len, BUFLEFT, "   ");
    887 			i = remaining % SECSPERHOUR;
    888 			len += snprintf(buf + len, BUFLEFT,
    889 			    "%02d:%02d ETA", i / 60, i % 60);
    890 		}
    891 	}
    892 	if (flag == 1)
    893 		len += snprintf(buf + len, BUFLEFT, "\n");
    894 	(void)write(fileno(ttyout), buf, len);
    895 
    896 	if (flag == -1) {
    897 		(void)xsignal_restart(SIGALRM, updateprogressmeter, 1);
    898 		alarmtimer(1);		/* set alarm timer for 1 Hz */
    899 	} else if (flag == 1) {
    900 		(void)xsignal(SIGALRM, SIG_DFL);
    901 		alarmtimer(0);
    902 	}
    903 #endif	/* !NO_PROGRESS */
    904 }
    905 
    906 /*
    907  * Display transfer statistics.
    908  * Requires start to be initialised by progressmeter(-1),
    909  * direction to be defined by xfer routines, and filesize and bytes
    910  * to be updated by xfer routines
    911  * If siginfo is nonzero, an ETA is displayed, and the output goes to stderr
    912  * instead of ttyout.
    913  */
    914 void
    915 ptransfer(siginfo)
    916 	int siginfo;
    917 {
    918 	struct timeval now, td, wait;
    919 	double elapsed;
    920 	off_t bytespersec;
    921 	int remaining, hh, i, len;
    922 
    923 	char buf[256];		/* Work variable for transfer status. */
    924 
    925 	if (!verbose && !progress && !siginfo)
    926 		return;
    927 
    928 	(void)gettimeofday(&now, NULL);
    929 	timersub(&now, &start, &td);
    930 	elapsed = td.tv_sec + (td.tv_usec / 1000000.0);
    931 	bytespersec = 0;
    932 	if (bytes > 0) {
    933 		bytespersec = bytes;
    934 		if (elapsed > 0.0)
    935 			bytespersec /= elapsed;
    936 	}
    937 	len = 0;
    938 	len += snprintf(buf + len, BUFLEFT,
    939 #ifndef NO_QUAD
    940 	    "%lld byte%s %s in ", (long long)bytes,
    941 #else
    942 	    "%ld byte%s %s in ", (long)bytes,
    943 #endif
    944 	    bytes == 1 ? "" : "s", direction);
    945 	remaining = (int)elapsed;
    946 	if (remaining > SECSPERDAY) {
    947 		int days;
    948 
    949 		days = remaining / SECSPERDAY;
    950 		remaining %= SECSPERDAY;
    951 		len += snprintf(buf + len, BUFLEFT,
    952 		    "%d day%s ", days, days == 1 ? "" : "s");
    953 	}
    954 	hh = remaining / SECSPERHOUR;
    955 	remaining %= SECSPERHOUR;
    956 	if (hh)
    957 		len += snprintf(buf + len, BUFLEFT, "%2d:", hh);
    958 	len += snprintf(buf + len, BUFLEFT,
    959 	    "%02d:%02d ", remaining / 60, remaining % 60);
    960 
    961 	for (i = 1; bytespersec >= 1024000 && i < sizeof(prefixes); i++)
    962 		bytespersec >>= 10;
    963 	len += snprintf(buf + len, BUFLEFT,
    964 #ifndef NO_QUAD
    965 	    "(%lld.%02d %cB/s)", (long long)bytespersec / 1024,
    966 #else
    967 	    "(%ld.%02d %cB/s)", (long)bytespersec / 1024,
    968 #endif
    969 	    (int)((bytespersec % 1024) * 100 / 1024),
    970 	    prefixes[i]);
    971 
    972 	if (siginfo && bytes > 0 && elapsed > 0.0 && filesize >= 0
    973 	    && bytes + restart_point <= filesize) {
    974 		remaining = (int)((filesize - restart_point) /
    975 				  (bytes / elapsed) - elapsed);
    976 		hh = remaining / SECSPERHOUR;
    977 		remaining %= SECSPERHOUR;
    978 		len += snprintf(buf + len, BUFLEFT, "  ETA: ");
    979 		if (hh)
    980 			len += snprintf(buf + len, BUFLEFT, "%2d:", hh);
    981 		len += snprintf(buf + len, BUFLEFT, "%02d:%02d",
    982 		    remaining / 60, remaining % 60);
    983 		timersub(&now, &lastupdate, &wait);
    984 		if (wait.tv_sec >= STALLTIME)
    985 			len += snprintf(buf + len, BUFLEFT, "  (stalled)");
    986 	}
    987 	len += snprintf(buf + len, BUFLEFT, "\n");
    988 	(void)write(siginfo ? STDERR_FILENO : fileno(ttyout), buf, len);
    989 }
    990 
    991 /*
    992  * SIG{INFO,QUIT} handler to print transfer stats if a transfer is in progress
    993  */
    994 void
    995 psummary(notused)
    996 	int notused;
    997 {
    998 	int oerrno = errno;
    999 
   1000 	if (bytes > 0) {
   1001 		if (fromatty)
   1002 			write(fileno(ttyout), "\n", 1);
   1003 		ptransfer(1);
   1004 	}
   1005 	errno = oerrno;
   1006 }
   1007 
   1008 /*
   1009  * List words in stringlist, vertically arranged
   1010  */
   1011 void
   1012 list_vertical(sl)
   1013 	StringList *sl;
   1014 {
   1015 	int i, j, w;
   1016 	int columns, width, lines, items;
   1017 	char *p;
   1018 
   1019 	width = items = 0;
   1020 
   1021 	for (i = 0 ; i < sl->sl_cur ; i++) {
   1022 		w = strlen(sl->sl_str[i]);
   1023 		if (w > width)
   1024 			width = w;
   1025 	}
   1026 	width = (width + 8) &~ 7;
   1027 
   1028 	columns = ttywidth / width;
   1029 	if (columns == 0)
   1030 		columns = 1;
   1031 	lines = (sl->sl_cur + columns - 1) / columns;
   1032 	for (i = 0; i < lines; i++) {
   1033 		for (j = 0; j < columns; j++) {
   1034 			p = sl->sl_str[j * lines + i];
   1035 			if (p)
   1036 				fputs(p, ttyout);
   1037 			if (j * lines + i + lines >= sl->sl_cur) {
   1038 				putc('\n', ttyout);
   1039 				break;
   1040 			}
   1041 			w = strlen(p);
   1042 			while (w < width) {
   1043 				w = (w + 8) &~ 7;
   1044 				(void)putc('\t', ttyout);
   1045 			}
   1046 		}
   1047 	}
   1048 }
   1049 
   1050 /*
   1051  * Update the global ttywidth value, using TIOCGWINSZ.
   1052  */
   1053 void
   1054 setttywidth(a)
   1055 	int a;
   1056 {
   1057 	struct winsize winsize;
   1058 	int oerrno = errno;
   1059 
   1060 	if (ioctl(fileno(ttyout), TIOCGWINSZ, &winsize) != -1 &&
   1061 	    winsize.ws_col != 0)
   1062 		ttywidth = winsize.ws_col;
   1063 	else
   1064 		ttywidth = 80;
   1065 	errno = oerrno;
   1066 }
   1067 
   1068 /*
   1069  * Change the rate limit up (SIGUSR1) or down (SIGUSR2)
   1070  */
   1071 void
   1072 crankrate(sig)
   1073 	int sig;
   1074 {
   1075 
   1076 	switch (sig) {
   1077 	case SIGUSR1:
   1078 		if (rate_get)
   1079 			rate_get += rate_get_incr;
   1080 		if (rate_put)
   1081 			rate_put += rate_put_incr;
   1082 		break;
   1083 	case SIGUSR2:
   1084 		if (rate_get && rate_get > rate_get_incr)
   1085 			rate_get -= rate_get_incr;
   1086 		if (rate_put && rate_put > rate_put_incr)
   1087 			rate_put -= rate_put_incr;
   1088 		break;
   1089 	default:
   1090 		err(1, "crankrate invoked with unknown signal: %d", sig);
   1091 	}
   1092 }
   1093 
   1094 
   1095 /*
   1096  * Set the SIGALRM interval timer for wait seconds, 0 to disable.
   1097  */
   1098 void
   1099 alarmtimer(wait)
   1100 	int wait;
   1101 {
   1102 	struct itimerval itv;
   1103 
   1104 	itv.it_value.tv_sec = wait;
   1105 	itv.it_value.tv_usec = 0;
   1106 	itv.it_interval = itv.it_value;
   1107 	setitimer(ITIMER_REAL, &itv, NULL);
   1108 }
   1109 
   1110 /*
   1111  * Setup or cleanup EditLine structures
   1112  */
   1113 #ifndef NO_EDITCOMPLETE
   1114 void
   1115 controlediting()
   1116 {
   1117 	if (editing && el == NULL && hist == NULL) {
   1118 		HistEvent ev;
   1119 		int editmode;
   1120 
   1121 		el = el_init(__progname, stdin, ttyout, stderr);
   1122 		/* init editline */
   1123 		hist = history_init();		/* init the builtin history */
   1124 		history(hist, &ev, H_SETSIZE, 100);/* remember 100 events */
   1125 		el_set(el, EL_HIST, history, hist);	/* use history */
   1126 
   1127 		el_set(el, EL_EDITOR, "emacs");	/* default editor is emacs */
   1128 		el_set(el, EL_PROMPT, prompt);	/* set the prompt functions */
   1129 		el_set(el, EL_RPROMPT, rprompt);
   1130 
   1131 		/* add local file completion, bind to TAB */
   1132 		el_set(el, EL_ADDFN, "ftp-complete",
   1133 		    "Context sensitive argument completion",
   1134 		    complete);
   1135 		el_set(el, EL_BIND, "^I", "ftp-complete", NULL);
   1136 		el_source(el, NULL);	/* read ~/.editrc */
   1137 		if ((el_get(el, EL_EDITMODE, &editmode) != -1) && editmode == 0)
   1138 			editing = 0;	/* the user doesn't want editing,
   1139 					 * so disable, and let statement
   1140 					 * below cleanup */
   1141 		else
   1142 			el_set(el, EL_SIGNAL, 1);
   1143 	}
   1144 	if (!editing) {
   1145 		if (hist) {
   1146 			history_end(hist);
   1147 			hist = NULL;
   1148 		}
   1149 		if (el) {
   1150 			el_end(el);
   1151 			el = NULL;
   1152 		}
   1153 	}
   1154 }
   1155 #endif /* !NO_EDITCOMPLETE */
   1156 
   1157 /*
   1158  * Convert the string `arg' to an int, which may have an optional SI suffix
   1159  * (`b', `k', `m', `g'). Returns the number for success, -1 otherwise.
   1160  */
   1161 int
   1162 strsuftoi(arg)
   1163 	const char *arg;
   1164 {
   1165 	char *cp;
   1166 	long val;
   1167 
   1168 	if (!isdigit((unsigned char)arg[0]))
   1169 		return (-1);
   1170 
   1171 	val = strtol(arg, &cp, 10);
   1172 	if (cp != NULL) {
   1173 		if (cp[0] != '\0' && cp[1] != '\0')
   1174 			 return (-1);
   1175 		switch (tolower((unsigned char)cp[0])) {
   1176 		case '\0':
   1177 		case 'b':
   1178 			break;
   1179 		case 'k':
   1180 			val <<= 10;
   1181 			break;
   1182 		case 'm':
   1183 			val <<= 20;
   1184 			break;
   1185 		case 'g':
   1186 			val <<= 30;
   1187 			break;
   1188 		default:
   1189 			return (-1);
   1190 		}
   1191 	}
   1192 	if (val < 0 || val > INT_MAX)
   1193 		return (-1);
   1194 
   1195 	return (val);
   1196 }
   1197 
   1198 /*
   1199  * Set up socket buffer sizes before a connection is made.
   1200  */
   1201 void
   1202 setupsockbufsize(sock)
   1203 	int sock;
   1204 {
   1205 
   1206 	if (setsockopt(sock, SOL_SOCKET, SO_SNDBUF, (void *) &sndbuf_size,
   1207 	    sizeof(rcvbuf_size)) < 0)
   1208 		warn("unable to set sndbuf size %d", sndbuf_size);
   1209 
   1210 	if (setsockopt(sock, SOL_SOCKET, SO_RCVBUF, (void *) &rcvbuf_size,
   1211 	    sizeof(rcvbuf_size)) < 0)
   1212 		warn("unable to set rcvbuf size %d", rcvbuf_size);
   1213 }
   1214 
   1215 /*
   1216  * Copy characters from src into dst, \ quoting characters that require it
   1217  */
   1218 void
   1219 ftpvis(dst, dstlen, src, srclen)
   1220 	char		*dst;
   1221 	size_t		 dstlen;
   1222 	const char	*src;
   1223 	size_t		 srclen;
   1224 {
   1225 	int	di, si;
   1226 
   1227 	for (di = si = 0;
   1228 	    src[si] != '\0' && di < dstlen && si < srclen;
   1229 	    di++, si++) {
   1230 		switch (src[si]) {
   1231 		case '\\':
   1232 		case ' ':
   1233 		case '\t':
   1234 		case '\r':
   1235 		case '\n':
   1236 		case '"':
   1237 			dst[di++] = '\\';
   1238 			if (di >= dstlen)
   1239 				break;
   1240 			/* FALLTHROUGH */
   1241 		default:
   1242 			dst[di] = src[si];
   1243 		}
   1244 	}
   1245 	dst[di] = '\0';
   1246 }
   1247 
   1248 /*
   1249  * Copy src into buf (which is len bytes long), expanding % sequences.
   1250  */
   1251 void
   1252 formatbuf(buf, len, src)
   1253 	char		*buf;
   1254 	size_t		 len;
   1255 	const char	*src;
   1256 {
   1257 	const char	*p;
   1258 	char		*p2, *q;
   1259 	int		 i, op, updirs, pdirs;
   1260 
   1261 #define ADDBUF(x) do { \
   1262 		if (i >= len - 1) \
   1263 			goto endbuf; \
   1264 		buf[i++] = (x); \
   1265 	} while (0)
   1266 
   1267 	p = src;
   1268 	for (i = 0; *p; p++) {
   1269 		if (*p != '%') {
   1270 			ADDBUF(*p);
   1271 			continue;
   1272 		}
   1273 		p++;
   1274 
   1275 		switch (op = *p) {
   1276 
   1277 		case '/':
   1278 		case '.':
   1279 		case 'c':
   1280 			p2 = connected ? remotepwd : "";
   1281 			updirs = pdirs = 0;
   1282 
   1283 			/* option to determine fixed # of dirs from path */
   1284 			if (op == '.' || op == 'c') {
   1285 				int skip;
   1286 
   1287 				q = p2;
   1288 				while (*p2)		/* calc # of /'s */
   1289 					if (*p2++ == '/')
   1290 						updirs++;
   1291 				if (p[1] == '0') {	/* print <x> or ... */
   1292 					pdirs = 1;
   1293 					p++;
   1294 				}
   1295 				if (p[1] >= '1' && p[1] <= '9') {
   1296 							/* calc # to skip  */
   1297 					skip = p[1] - '0';
   1298 					p++;
   1299 				} else
   1300 					skip = 1;
   1301 
   1302 				updirs -= skip;
   1303 				while (skip-- > 0) {
   1304 					while ((p2 > q) && (*p2 != '/'))
   1305 						p2--;	/* back up */
   1306 					if (skip && p2 > q)
   1307 						p2--;
   1308 				}
   1309 				if (*p2 == '/' && p2 != q)
   1310 					p2++;
   1311 			}
   1312 
   1313 			if (updirs > 0 && pdirs) {
   1314 				if (i >= len - 5)
   1315 					break;
   1316 				if (op == '.') {
   1317 					ADDBUF('.');
   1318 					ADDBUF('.');
   1319 					ADDBUF('.');
   1320 				} else {
   1321 					ADDBUF('/');
   1322 					ADDBUF('<');
   1323 					if (updirs > 9) {
   1324 						ADDBUF('9');
   1325 						ADDBUF('+');
   1326 					} else
   1327 						ADDBUF('0' + updirs);
   1328 					ADDBUF('>');
   1329 				}
   1330 			}
   1331 			for (; *p2; p2++)
   1332 				ADDBUF(*p2);
   1333 			break;
   1334 
   1335 		case 'M':
   1336 		case 'm':
   1337 			for (p2 = connected ? hostname : "-"; *p2; p2++) {
   1338 				if (op == 'm' && *p2 == '.')
   1339 					break;
   1340 				ADDBUF(*p2);
   1341 			}
   1342 			break;
   1343 
   1344 		case 'n':
   1345 			for (p2 = connected ? username : "-"; *p2 ; p2++)
   1346 				ADDBUF(*p2);
   1347 			break;
   1348 
   1349 		case '%':
   1350 			ADDBUF('%');
   1351 			break;
   1352 
   1353 		default:		/* display unknown codes literally */
   1354 			ADDBUF('%');
   1355 			ADDBUF(op);
   1356 			break;
   1357 
   1358 		}
   1359 	}
   1360  endbuf:
   1361 	buf[i] = '\0';
   1362 }
   1363 
   1364 /*
   1365  * Determine if given string is an IPv6 address or not.
   1366  * Return 1 for yes, 0 for no
   1367  */
   1368 int
   1369 isipv6addr(addr)
   1370 	const char *addr;
   1371 {
   1372 	int rv = 0;
   1373 #ifdef INET6
   1374 	struct sockaddr_in6 su_sin6;
   1375 
   1376 	rv = inet_pton(AF_INET6, addr, &su_sin6.sin6_addr);
   1377 	if (debug)
   1378 		fprintf(ttyout, "isipv6addr: got %d for %s\n", rv, addr);
   1379 #endif
   1380 	return rv;
   1381 }
   1382 
   1383 
   1384 /*
   1385  * Internal version of connect(2); sets socket buffer sizes first.
   1386  */
   1387 int
   1388 xconnect(sock, name, namelen)
   1389 	int sock;
   1390 	const struct sockaddr *name;
   1391 	int namelen;
   1392 {
   1393 
   1394 	setupsockbufsize(sock);
   1395 	return (connect(sock, name, namelen));
   1396 }
   1397 
   1398 /*
   1399  * Internal version of listen(2); sets socket buffer sizes first.
   1400  */
   1401 int
   1402 xlisten(sock, backlog)
   1403 	int sock, backlog;
   1404 {
   1405 
   1406 	setupsockbufsize(sock);
   1407 	return (listen(sock, backlog));
   1408 }
   1409 
   1410 /*
   1411  * malloc() with inbuilt error checking
   1412  */
   1413 void *
   1414 xmalloc(size)
   1415 	size_t size;
   1416 {
   1417 	void *p;
   1418 
   1419 	p = malloc(size);
   1420 	if (p == NULL)
   1421 		err(1, "Unable to allocate %ld bytes of memory", (long)size);
   1422 	return (p);
   1423 }
   1424 
   1425 /*
   1426  * sl_init() with inbuilt error checking
   1427  */
   1428 StringList *
   1429 xsl_init()
   1430 {
   1431 	StringList *p;
   1432 
   1433 	p = sl_init();
   1434 	if (p == NULL)
   1435 		err(1, "Unable to allocate memory for stringlist");
   1436 	return (p);
   1437 }
   1438 
   1439 /*
   1440  * sl_add() with inbuilt error checking
   1441  */
   1442 void
   1443 xsl_add(sl, i)
   1444 	StringList	*sl;
   1445 	char		*i;
   1446 {
   1447 
   1448 	if (sl_add(sl, i) == -1)
   1449 		err(1, "Unable to add `%s' to stringlist", i);
   1450 }
   1451 
   1452 /*
   1453  * strdup() with inbuilt error checking
   1454  */
   1455 char *
   1456 xstrdup(str)
   1457 	const char *str;
   1458 {
   1459 	char *s;
   1460 
   1461 	if (str == NULL)
   1462 		errx(1, "xstrdup() called with NULL argument");
   1463 	s = strdup(str);
   1464 	if (s == NULL)
   1465 		err(1, "Unable to allocate memory for string copy");
   1466 	return (s);
   1467 }
   1468 
   1469 /*
   1470  * Install a POSIX signal handler, allowing the invoker to set whether
   1471  * the signal should be restartable or not
   1472  */
   1473 sig_t
   1474 xsignal_restart(sig, func, restartable)
   1475 	int sig;
   1476 	void (*func) __P((int));
   1477 	int restartable;
   1478 {
   1479 	struct sigaction act, oact;
   1480 	act.sa_handler = func;
   1481 
   1482 	sigemptyset(&act.sa_mask);
   1483 #if defined(SA_RESTART)			/* 4.4BSD, Posix(?), SVR4 */
   1484 	act.sa_flags = restartable ? SA_RESTART : 0;
   1485 #elif defined(SA_INTERRUPT)		/* SunOS 4.x */
   1486 	act.sa_flags = restartable ? 0 : SA_INTERRUPT;
   1487 #else
   1488 #error "system must have SA_RESTART or SA_INTERRUPT"
   1489 #endif
   1490 	if (sigaction(sig, &act, &oact) < 0)
   1491 		return (SIG_ERR);
   1492 	return (oact.sa_handler);
   1493 }
   1494 
   1495 /*
   1496  * Install a signal handler with the `restartable' flag set dependent upon
   1497  * which signal is being set. (This is a wrapper to xsignal_restart())
   1498  */
   1499 sig_t
   1500 xsignal(sig, func)
   1501 	int sig;
   1502 	void (*func) __P((int));
   1503 {
   1504 	int restartable;
   1505 
   1506 	/*
   1507 	 * Some signals print output or change the state of the process.
   1508 	 * There should be restartable, so that reads and writes are
   1509 	 * not affected.  Some signals should cause program flow to change;
   1510 	 * these signals should not be restartable, so that the system call
   1511 	 * will return with EINTR, and the program will go do something
   1512 	 * different.  If the signal handler calls longjmp() or siglongjmp(),
   1513 	 * it doesn't matter if it's restartable.
   1514 	 */
   1515 
   1516 	switch(sig) {
   1517 #ifdef SIGINFO
   1518 	case SIGINFO:
   1519 #endif
   1520 	case SIGQUIT:
   1521 	case SIGUSR1:
   1522 	case SIGUSR2:
   1523 	case SIGWINCH:
   1524 		restartable = 1;
   1525 		break;
   1526 
   1527 	case SIGALRM:
   1528 	case SIGINT:
   1529 	case SIGPIPE:
   1530 		restartable = 0;
   1531 		break;
   1532 
   1533 	default:
   1534 		/*
   1535 		 * This is unpleasant, but I don't know what would be better.
   1536 		 * Right now, this "can't happen"
   1537 		 */
   1538 		errx(1, "xsignal_restart called with signal %d", sig);
   1539 	}
   1540 
   1541 	return(xsignal_restart(sig, func, restartable));
   1542 }
   1543