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