Home | History | Annotate | Line # | Download | only in ftp
util.c revision 1.56
      1 /*	$NetBSD: util.c,v 1.56 1999/09/21 11:18:27 lukem Exp $	*/
      2 
      3 /*-
      4  * Copyright (c) 1998, 1999 The NetBSD Foundation, Inc.
      5  * All rights reserved.
      6  *
      7  * This code is derived from software contributed to The NetBSD Foundation
      8  * by Jason R. Thorpe of the Numerical Aerospace Simulation Facility,
      9  * NASA Ames Research Center.
     10  *
     11  * This code is derived from software contributed to The NetBSD Foundation
     12  * by Luke Mewburn.
     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.56 1999/09/21 11:18:27 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 <arpa/ftp.h>
     89 
     90 #include <ctype.h>
     91 #include <err.h>
     92 #include <errno.h>
     93 #include <fcntl.h>
     94 #include <glob.h>
     95 #include <termios.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 <time.h>
    103 #include <tzfile.h>
    104 #include <unistd.h>
    105 
    106 #include "ftp_var.h"
    107 #include "pathnames.h"
    108 
    109 #ifndef HAVE_TIMEGM
    110 static time_t	sub_mkgmt __P((struct tm *tm));
    111 #endif
    112 
    113 /*
    114  * Connect to peer server and
    115  * auto-login, if possible.
    116  */
    117 void
    118 setpeer(argc, argv)
    119 	int argc;
    120 	char *argv[];
    121 {
    122 	char *host;
    123 	char *port;
    124 
    125 	if (connected) {
    126 		fprintf(ttyout, "Already connected to %s, use close first.\n",
    127 		    hostname);
    128 		code = -1;
    129 		return;
    130 	}
    131 	if (argc < 2)
    132 		(void)another(&argc, &argv, "to");
    133 	if (argc < 2 || argc > 3) {
    134 		fprintf(ttyout, "usage: %s host-name [port]\n", argv[0]);
    135 		code = -1;
    136 		return;
    137 	}
    138 	if (gatemode)
    139 		port = gateport;
    140 	else
    141 		port = ftpport;
    142 #if 0
    143 	if (argc > 2) {
    144 		char *ep;
    145 		long nport;
    146 
    147 		nport = strtol(argv[2], &ep, 10);
    148 		if (nport < 1 || nport > MAX_IN_PORT_T || *ep != '\0') {
    149 			fprintf(ttyout, "%s: bad port number '%s'.\n",
    150 			    argv[1], argv[2]);
    151 			fprintf(ttyout, "usage: %s host-name [port]\n",
    152 			    argv[0]);
    153 			code = -1;
    154 			return;
    155 		}
    156 		port = htons((in_port_t)nport);
    157 	}
    158 #else
    159 	if (argc > 2)
    160 		port = strdup(argv[2]);
    161 #endif
    162 
    163 	if (gatemode) {
    164 		if (gateserver == NULL || *gateserver == '\0')
    165 			errx(1, "gateserver not defined (shouldn't happen)");
    166 		host = hookup(gateserver, port);
    167 	} else
    168 		host = hookup(argv[1], port);
    169 
    170 	if (host) {
    171 		int overbose;
    172 
    173 		if (gatemode && verbose) {
    174 			fprintf(ttyout,
    175 			    "Connecting via pass-through server %s\n",
    176 			    gateserver);
    177 		}
    178 
    179 		connected = 1;
    180 		/*
    181 		 * Set up defaults for FTP.
    182 		 */
    183 		(void)strcpy(typename, "ascii"), type = TYPE_A;
    184 		curtype = TYPE_A;
    185 		(void)strcpy(formname, "non-print"), form = FORM_N;
    186 		(void)strcpy(modename, "stream"), mode = MODE_S;
    187 		(void)strcpy(structname, "file"), stru = STRU_F;
    188 		(void)strcpy(bytename, "8"), bytesize = 8;
    189 		if (autologin)
    190 			(void)ftp_login(argv[1], NULL, NULL);
    191 
    192 		overbose = verbose;
    193 		if (debug == 0)
    194 			verbose = -1;
    195 		if (command("SYST") == COMPLETE && overbose) {
    196 			char *cp, c;
    197 			c = 0;
    198 			cp = strchr(reply_string + 4, ' ');
    199 			if (cp == NULL)
    200 				cp = strchr(reply_string + 4, '\r');
    201 			if (cp) {
    202 				if (cp[-1] == '.')
    203 					cp--;
    204 				c = *cp;
    205 				*cp = '\0';
    206 			}
    207 
    208 			fprintf(ttyout, "Remote system type is %s.\n",
    209 			    reply_string + 4);
    210 			if (cp)
    211 				*cp = c;
    212 		}
    213 		if (!strncmp(reply_string, "215 UNIX Type: L8", 17)) {
    214 			if (proxy)
    215 				unix_proxy = 1;
    216 			else
    217 				unix_server = 1;
    218 			/*
    219 			 * Set type to 0 (not specified by user),
    220 			 * meaning binary by default, but don't bother
    221 			 * telling server.  We can use binary
    222 			 * for text files unless changed by the user.
    223 			 */
    224 			type = 0;
    225 			(void)strcpy(typename, "binary");
    226 			if (overbose)
    227 			    fprintf(ttyout,
    228 				"Using %s mode to transfer files.\n",
    229 				typename);
    230 		} else {
    231 			if (proxy)
    232 				unix_proxy = 0;
    233 			else
    234 				unix_server = 0;
    235 			if (overbose &&
    236 			    !strncmp(reply_string, "215 TOPS20", 10))
    237 				fputs(
    238 "Remember to set tenex mode when transferring binary files from this machine.\n",
    239 				    ttyout);
    240 		}
    241 		verbose = overbose;
    242 	}
    243 }
    244 
    245 /*
    246  * login to remote host, using given username & password if supplied
    247  */
    248 int
    249 ftp_login(host, user, pass)
    250 	const char *host;
    251 	const char *user, *pass;
    252 {
    253 	char tmp[80];
    254 	const char *acct;
    255 	struct passwd *pw;
    256 	int n, aflag, rval, freeuser, freepass, freeacct, len;
    257 
    258 	acct = NULL;
    259 	aflag = rval = freeuser = freepass = freeacct = 0;
    260 
    261 	/*
    262 	 * Set up arguments for an anonymous FTP session, if necessary.
    263 	 */
    264 	if (anonftp) {
    265 		/*
    266 		 * Set up anonymous login password.
    267 		 */
    268 		if ((pass = getenv("FTPANONPASS")) == NULL) {
    269 			char *anonpass;
    270 
    271 			if ((pass = getlogin()) == NULL) {
    272 				if ((pw = getpwuid(getuid())) == NULL)
    273 					pass = "anonymous";
    274 				else
    275 					pass = pw->pw_name;
    276 			}
    277 			/*
    278 			 * Every anonymous FTP server I've encountered
    279 			 * will accept the string "username@", and will
    280 			 * append the hostname itself.  We do this by default
    281 			 * since many servers are picky about not having
    282 			 * a FQDN in the anonymous password.
    283 			 * - thorpej (at) netbsd.org
    284 			 */
    285 			len = strlen(pass) + 2;
    286 			anonpass = xmalloc(len);
    287 			snprintf(anonpass, len, "%s@", pass);
    288 			pass = anonpass;
    289 			freepass = 1;
    290 		}
    291 		user = "anonymous";	/* as per RFC 1635 */
    292 	}
    293 
    294 	if (user == NULL)
    295 		freeuser = 1;
    296 	if (pass == NULL)
    297 		freepass = 1;
    298 	freeacct = 1;
    299 	if (ruserpass(host, &user, &pass, &acct) < 0) {
    300 		code = -1;
    301 		goto cleanup_ftp_login;
    302 	}
    303 
    304 	while (user == NULL) {
    305 		const char *myname = getlogin();
    306 
    307 		if (myname == NULL && (pw = getpwuid(getuid())) != NULL)
    308 			myname = pw->pw_name;
    309 		if (myname)
    310 			fprintf(ttyout, "Name (%s:%s): ", host, myname);
    311 		else
    312 			fprintf(ttyout, "Name (%s): ", host);
    313 		*tmp = '\0';
    314 		if (fgets(tmp, sizeof(tmp) - 1, stdin) == NULL) {
    315 			fprintf(ttyout, "\nEOF received; login aborted.\n");
    316 			code = -1;
    317 			goto cleanup_ftp_login;
    318 		}
    319 		tmp[strlen(tmp) - 1] = '\0';
    320 		freeuser = 0;
    321 		if (*tmp == '\0')
    322 			user = myname;
    323 		else
    324 			user = tmp;
    325 	}
    326 
    327 	if (gatemode) {
    328 		char *nuser;
    329 		int len;
    330 
    331 		len = strlen(user) + 1 + strlen(host) + 1;
    332 		nuser = xmalloc(len);
    333 		snprintf(nuser, len, "%s@%s", user, host);
    334 		freeuser = 1;
    335 		user = nuser;
    336 	}
    337 
    338 	n = command("USER %s", user);
    339 	if (n == CONTINUE) {
    340 		if (pass == NULL) {
    341 			freepass = 0;
    342 			pass = getpass("Password:");
    343 		}
    344 		n = command("PASS %s", pass);
    345 	}
    346 	if (n == CONTINUE) {
    347 		aflag++;
    348 		if (acct == NULL) {
    349 			freeacct = 0;
    350 			acct = getpass("Account:");
    351 		}
    352 		if (acct[0] == '\0') {
    353 			warnx("Login failed.");
    354 			goto cleanup_ftp_login;
    355 		}
    356 		n = command("ACCT %s", acct);
    357 	}
    358 	if ((n != COMPLETE) ||
    359 	    (!aflag && acct != NULL && command("ACCT %s", acct) != COMPLETE)) {
    360 		warnx("Login failed.");
    361 		goto cleanup_ftp_login;
    362 	}
    363 	rval = 1;
    364 	if (proxy)
    365 		goto cleanup_ftp_login;
    366 
    367 	connected = -1;
    368 	for (n = 0; n < macnum; ++n) {
    369 		if (!strcmp("init", macros[n].mac_name)) {
    370 			(void)strcpy(line, "$init");
    371 			makeargv();
    372 			domacro(margc, margv);
    373 			break;
    374 		}
    375 	}
    376 cleanup_ftp_login:
    377 	if (user != NULL && freeuser)
    378 		free((char *)user);
    379 	if (pass != NULL && freepass)
    380 		free((char *)pass);
    381 	if (acct != NULL && freeacct)
    382 		free((char *)acct);
    383 	return (rval);
    384 }
    385 
    386 /*
    387  * `another' gets another argument, and stores the new argc and argv.
    388  * It reverts to the top level (via main.c's intr()) on EOF/error.
    389  *
    390  * Returns false if no new arguments have been added.
    391  */
    392 int
    393 another(pargc, pargv, prompt)
    394 	int *pargc;
    395 	char ***pargv;
    396 	const char *prompt;
    397 {
    398 	int len = strlen(line), ret;
    399 
    400 	if (len >= sizeof(line) - 3) {
    401 		fputs("sorry, arguments too long.\n", ttyout);
    402 		intr();
    403 	}
    404 	fprintf(ttyout, "(%s) ", prompt);
    405 	line[len++] = ' ';
    406 	if (fgets(&line[len], sizeof(line) - len, stdin) == NULL)
    407 		intr();
    408 	len += strlen(&line[len]);
    409 	if (len > 0 && line[len - 1] == '\n')
    410 		line[len - 1] = '\0';
    411 	makeargv();
    412 	ret = margc > *pargc;
    413 	*pargc = margc;
    414 	*pargv = margv;
    415 	return (ret);
    416 }
    417 
    418 /*
    419  * glob files given in argv[] from the remote server.
    420  * if errbuf isn't NULL, store error messages there instead
    421  * of writing to the screen.
    422  */
    423 char *
    424 remglob(argv, doswitch, errbuf)
    425         char *argv[];
    426         int doswitch;
    427 	char **errbuf;
    428 {
    429         char temp[MAXPATHLEN];
    430         static char buf[MAXPATHLEN];
    431         static FILE *ftemp = NULL;
    432         static char **args;
    433         int oldverbose, oldhash, fd;
    434         char *cp, *mode;
    435 
    436         if (!mflag) {
    437                 if (!doglob)
    438                         args = NULL;
    439                 else {
    440                         if (ftemp) {
    441                                 (void)fclose(ftemp);
    442                                 ftemp = NULL;
    443                         }
    444                 }
    445                 return (NULL);
    446         }
    447         if (!doglob) {
    448                 if (args == NULL)
    449                         args = argv;
    450                 if ((cp = *++args) == NULL)
    451                         args = NULL;
    452                 return (cp);
    453         }
    454         if (ftemp == NULL) {
    455                 (void)snprintf(temp, sizeof(temp), "%s/%s", tmpdir, TMPFILE);
    456                 if ((fd = mkstemp(temp)) < 0) {
    457                         warn("unable to create temporary file %s", temp);
    458                         return (NULL);
    459                 }
    460                 close(fd);
    461                 oldverbose = verbose;
    462 		verbose = (errbuf != NULL) ? -1 : 0;
    463                 oldhash = hash;
    464                 hash = 0;
    465                 if (doswitch)
    466                         pswitch(!proxy);
    467                 for (mode = "w"; *++argv != NULL; mode = "a")
    468                         recvrequest("NLST", temp, *argv, mode, 0, 0);
    469 		if ((code / 100) != COMPLETE) {
    470 			if (errbuf != NULL)
    471 				*errbuf = reply_string;
    472 		}
    473                 if (doswitch)
    474                         pswitch(!proxy);
    475                 verbose = oldverbose;
    476 		hash = oldhash;
    477                 ftemp = fopen(temp, "r");
    478                 (void)unlink(temp);
    479                 if (ftemp == NULL) {
    480 			if (errbuf == NULL)
    481 				fputs(
    482 				    "can't find list of remote files, oops.\n",
    483 				    ttyout);
    484 			else
    485 				*errbuf =
    486 				    "can't find list of remote files, oops.";
    487                         return (NULL);
    488                 }
    489         }
    490         if (fgets(buf, sizeof(buf), ftemp) == NULL) {
    491                 (void)fclose(ftemp);
    492 		ftemp = NULL;
    493                 return (NULL);
    494         }
    495         if ((cp = strchr(buf, '\n')) != NULL)
    496                 *cp = '\0';
    497         return (buf);
    498 }
    499 
    500 int
    501 confirm(cmd, file)
    502 	const char *cmd, *file;
    503 {
    504 	char line[BUFSIZ];
    505 
    506 	if (!interactive || confirmrest)
    507 		return (1);
    508 	fprintf(ttyout, "%s %s? ", cmd, file);
    509 	(void)fflush(ttyout);
    510 	if (fgets(line, sizeof(line), stdin) == NULL)
    511 		return (0);
    512 	switch (tolower(*line)) {
    513 		case 'n':
    514 			return (0);
    515 		case 'p':
    516 			interactive = 0;
    517 			fputs("Interactive mode: off.\n", ttyout);
    518 			break;
    519 		case 'a':
    520 			confirmrest = 1;
    521 			fprintf(ttyout, "Prompting off for duration of %s.\n",
    522 			    cmd);
    523 			break;
    524 	}
    525 	return (1);
    526 }
    527 
    528 /*
    529  * Glob a local file name specification with
    530  * the expectation of a single return value.
    531  * Can't control multiple values being expanded
    532  * from the expression, we return only the first.
    533  */
    534 int
    535 globulize(cpp)
    536 	char **cpp;
    537 {
    538 	glob_t gl;
    539 	int flags;
    540 
    541 	if (!doglob)
    542 		return (1);
    543 
    544 	flags = GLOB_BRACE|GLOB_NOCHECK|GLOB_TILDE;
    545 	memset(&gl, 0, sizeof(gl));
    546 	if (glob(*cpp, flags, NULL, &gl) || gl.gl_pathc == 0) {
    547 		warnx("%s: not found", *cpp);
    548 		globfree(&gl);
    549 		return (0);
    550 	}
    551 		/* XXX: caller should check if *cpp changed, and
    552 		 *	free(*cpp) if that is the case
    553 		 */
    554 	*cpp = xstrdup(gl.gl_pathv[0]);
    555 	globfree(&gl);
    556 	return (1);
    557 }
    558 
    559 /*
    560  * determine size of remote file
    561  */
    562 off_t
    563 remotesize(file, noisy)
    564 	const char *file;
    565 	int noisy;
    566 {
    567 	int overbose;
    568 	off_t size;
    569 
    570 	overbose = verbose;
    571 	size = -1;
    572 	if (debug == 0)
    573 		verbose = -1;
    574 	if (command("SIZE %s", file) == COMPLETE) {
    575 		char *cp, *ep;
    576 
    577 		cp = strchr(reply_string, ' ');
    578 		if (cp != NULL) {
    579 			cp++;
    580 #ifndef NO_QUAD
    581 			size = strtoq(cp, &ep, 10);
    582 #else
    583 			size = strtol(cp, &ep, 10);
    584 #endif
    585 			if (*ep != '\0' && !isspace((unsigned char)*ep))
    586 				size = -1;
    587 		}
    588 	} else if (noisy && debug == 0) {
    589 		fputs(reply_string, ttyout);
    590 		putc('\n', ttyout);
    591 	}
    592 	verbose = overbose;
    593 	return (size);
    594 }
    595 
    596 /*
    597  * determine last modification time (in GMT) of remote file
    598  */
    599 time_t
    600 remotemodtime(file, noisy)
    601 	const char *file;
    602 	int noisy;
    603 {
    604 	int overbose;
    605 	time_t rtime;
    606 	int ocode;
    607 
    608 	overbose = verbose;
    609 	ocode = code;
    610 	rtime = -1;
    611 	if (debug == 0)
    612 		verbose = -1;
    613 	if (command("MDTM %s", file) == COMPLETE) {
    614 		struct tm timebuf;
    615 		int yy, mo, day, hour, min, sec;
    616 		sscanf(reply_string, "%*s %04d%02d%02d%02d%02d%02d", &yy, &mo,
    617 			&day, &hour, &min, &sec);
    618 		memset(&timebuf, 0, sizeof(timebuf));
    619 		timebuf.tm_sec = sec;
    620 		timebuf.tm_min = min;
    621 		timebuf.tm_hour = hour;
    622 		timebuf.tm_mday = day;
    623 		timebuf.tm_mon = mo - 1;
    624 		timebuf.tm_year = yy - TM_YEAR_BASE;
    625 		timebuf.tm_isdst = -1;
    626 		rtime = mkgmtime(&timebuf);
    627 		if (rtime == -1 && (noisy || debug != 0))
    628 			fprintf(ttyout, "Can't convert %s to a time.\n",
    629 			    reply_string);
    630 	} else if (noisy && debug == 0) {
    631 		fputs(reply_string, ttyout);
    632 		putc('\n', ttyout);
    633 	}
    634 	verbose = overbose;
    635 	if (rtime == -1)
    636 		code = ocode;
    637 	return (rtime);
    638 }
    639 
    640 /*
    641  * UTC version of mktime(3)
    642  */
    643 #ifdef HAVE_TIMEGM
    644 time_t
    645 mkgmtime(tm)
    646 	struct tm *tm;
    647 {
    648 
    649 	/* This is very clean, but not portable at all. */
    650 	return (timegm(tm));
    651 }
    652 
    653 #else	/* not HAVE_TIMEGM */
    654 
    655 /*
    656  * This code is not portable, but works on most Unix-like systems.
    657  * If the local timezone has no summer time, using mktime(3) function
    658  * and adjusting offset would be usable (adjusting leap seconds
    659  * is still required, though), but the assumption is not always true.
    660  *
    661  * Anyway, no portable and correct implementation of UTC to time_t
    662  * conversion exists....
    663  */
    664 
    665 static time_t
    666 sub_mkgmt(tm)
    667 	struct tm *tm;
    668 {
    669 	int y, nleapdays;
    670 	time_t t;
    671 	/* days before the month */
    672 	static const unsigned short moff[12] = {
    673 		0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334
    674 	};
    675 
    676 	/*
    677 	 * XXX This code assumes the given time to be normalized.
    678 	 * Normalizing here is impossible in case the given time is a leap
    679 	 * second but the local time library is ignorant of leap seconds.
    680 	 */
    681 
    682 	/* minimal sanity checking not to access outside of the array */
    683 	if ((unsigned) tm->tm_mon >= 12)
    684 		return (time_t) -1;
    685 	if (tm->tm_year < EPOCH_YEAR - TM_YEAR_BASE)
    686 		return (time_t) -1;
    687 
    688 	y = tm->tm_year + TM_YEAR_BASE - (tm->tm_mon < 2);
    689 	nleapdays = y / 4 - y / 100 + y / 400 -
    690 	    ((EPOCH_YEAR-1) / 4 - (EPOCH_YEAR-1) / 100 + (EPOCH_YEAR-1) / 400);
    691 	t = ((((time_t) (tm->tm_year - (EPOCH_YEAR - TM_YEAR_BASE)) * 365 +
    692 			moff[tm->tm_mon] + tm->tm_mday - 1 + nleapdays) * 24 +
    693 		tm->tm_hour) * 60 + tm->tm_min) * 60 + tm->tm_sec;
    694 
    695 	return (t < 0 ? (time_t) -1 : t);
    696 }
    697 
    698 time_t
    699 mkgmtime(tm)
    700 	struct tm *tm;
    701 {
    702 	time_t t, t2;
    703 	struct tm *tm2;
    704 	int sec;
    705 
    706 	/* Do the first guess. */
    707 	if ((t = sub_mkgmt(tm)) == (time_t) -1)
    708 		return (time_t) -1;
    709 
    710 	/* save value in case *tm is overwritten by gmtime() */
    711 	sec = tm->tm_sec;
    712 
    713 	tm2 = gmtime(&t);
    714 	if ((t2 = sub_mkgmt(tm2)) == (time_t) -1)
    715 		return (time_t) -1;
    716 
    717 	if (t2 < t || tm2->tm_sec != sec) {
    718 		/*
    719 		 * Adjust for leap seconds.
    720 		 *
    721 		 *     real time_t time
    722 		 *           |
    723 		 *          tm
    724 		 *         /	... (a) first sub_mkgmt() conversion
    725 		 *       t
    726 		 *       |
    727 		 *      tm2
    728 		 *     /	... (b) second sub_mkgmt() conversion
    729 		 *   t2
    730 		 *			--->time
    731 		 */
    732 		/*
    733 		 * Do the second guess, assuming (a) and (b) are almost equal.
    734 		 */
    735 		t += t - t2;
    736 		tm2 = gmtime(&t);
    737 
    738 		/*
    739 		 * Either (a) or (b), may include one or two extra
    740 		 * leap seconds.  Try t, t + 2, t - 2, t + 1, and t - 1.
    741 		 */
    742 		if (tm2->tm_sec == sec
    743 		    || (t += 2, tm2 = gmtime(&t), tm2->tm_sec == sec)
    744 		    || (t -= 4, tm2 = gmtime(&t), tm2->tm_sec == sec)
    745 		    || (t += 3, tm2 = gmtime(&t), tm2->tm_sec == sec)
    746 		    || (t -= 2, tm2 = gmtime(&t), tm2->tm_sec == sec))
    747 			;	/* found */
    748 		else {
    749 			/*
    750 			 * Not found.
    751 			 */
    752 			if (sec >= 60)
    753 				/*
    754 				 * The given time is a leap second
    755 				 * (sec 60 or 61), but the time library
    756 				 * is ignorant of the leap second.
    757 				 */
    758 				;	/* treat sec 60 as 59,
    759 					   sec 61 as 0 of the next minute */
    760 			else
    761 				/* The given time may not be normalized. */
    762 				t++;	/* restore t */
    763 		}
    764 	}
    765 
    766 	return (t < 0 ? (time_t) -1 : t);
    767 }
    768 #endif	/* not HAVE_TIMEGM */
    769 
    770 #ifndef	NO_PROGRESS
    771 
    772 /*
    773  * return non-zero if we're the current foreground process
    774  */
    775 int
    776 foregroundproc()
    777 {
    778 	static pid_t pgrp = -1;
    779 	int ctty_pgrp;
    780 
    781 	if (pgrp == -1)
    782 		pgrp = getpgrp();
    783 
    784 	return ((ioctl(fileno(ttyout), TIOCGPGRP, &ctty_pgrp) != -1 &&
    785 	    ctty_pgrp == (int)pgrp));
    786 }
    787 
    788 
    789 static void updateprogressmeter __P((int));
    790 
    791 static void
    792 updateprogressmeter(dummy)
    793 	int dummy;
    794 {
    795 	int oerrno;
    796 
    797 	oerrno = errno;
    798 	progressmeter(0);
    799 	errno = oerrno;
    800 }
    801 #endif	/* NO_PROGRESS */
    802 
    803 
    804 /*
    805  * List of order of magnitude prefixes.
    806  * The last is `P', as 2^64 = 16384 Petabytes
    807  */
    808 static const char prefixes[] = " KMGTP";
    809 
    810 /*
    811  * Display a transfer progress bar if progress is non-zero.
    812  * SIGALRM is hijacked for use by this function.
    813  * - Before the transfer, set filesize to size of file (or -1 if unknown),
    814  *   and call with flag = -1. This starts the once per second timer,
    815  *   and a call to updateprogressmeter() upon SIGALRM.
    816  * - During the transfer, updateprogressmeter will call progressmeter
    817  *   with flag = 0
    818  * - After the transfer, call with flag = 1
    819  */
    820 static struct timeval start;
    821 static struct timeval lastupdate;
    822 
    823 void
    824 progressmeter(flag)
    825 	int flag;
    826 {
    827 	static off_t lastsize;
    828 #ifndef NO_PROGRESS
    829 	struct timeval now, td, wait;
    830 	off_t cursize, abbrevsize, bytespersec;
    831 	double elapsed;
    832 	int ratio, barlength, i, len, remaining;
    833 	char buf[256];
    834 #endif
    835 
    836 	if (flag == -1) {
    837 		(void)gettimeofday(&start, NULL);
    838 		lastupdate = start;
    839 		lastsize = restart_point;
    840 	}
    841 #ifndef NO_PROGRESS
    842 	len = 0;
    843 	if (!progress || filesize <= 0)
    844 		return;
    845 
    846 	(void)gettimeofday(&now, NULL);
    847 	cursize = bytes + restart_point;
    848 	timersub(&now, &lastupdate, &wait);
    849 	if (cursize > lastsize) {
    850 		lastupdate = now;
    851 		lastsize = cursize;
    852 		if (wait.tv_sec >= STALLTIME) {	/* fudge out stalled time */
    853 			start.tv_sec += wait.tv_sec;
    854 			start.tv_usec += wait.tv_usec;
    855 		}
    856 		wait.tv_sec = 0;
    857 	}
    858 
    859 	/*
    860 	 * print progress bar only if we are foreground process.
    861 	 */
    862 	if (! foregroundproc())
    863 		return;
    864 
    865 	ratio = (int)((double)cursize * 100.0 / (double)filesize);
    866 	ratio = MAX(ratio, 0);
    867 	ratio = MIN(ratio, 100);
    868 	len += snprintf(buf + len, sizeof(buf) - len, "\r%3d%% ", ratio);
    869 
    870 	barlength = ttywidth - 43;
    871 	if (barlength > 0) {
    872 		i = barlength * ratio / 100;
    873 		len += snprintf(buf + len, sizeof(buf) - len,
    874 		    "|%.*s%*s|", i,
    875 "*****************************************************************************"
    876 "*****************************************************************************",
    877 		    barlength - i, "");
    878 	}
    879 
    880 	abbrevsize = cursize;
    881 	for (i = 0; abbrevsize >= 100000 && i < sizeof(prefixes); i++)
    882 		abbrevsize >>= 10;
    883 	len += snprintf(buf + len, sizeof(buf) - len,
    884 #ifndef NO_QUAD
    885 	    " %5qd %c%c ", (long long)abbrevsize,
    886 #else
    887 	    " %5ld %c%c ", (long)abbrevsize,
    888 #endif
    889 	    prefixes[i],
    890 	    i == 0 ? ' ' : 'B');
    891 
    892 	timersub(&now, &start, &td);
    893 	elapsed = td.tv_sec + (td.tv_usec / 1000000.0);
    894 
    895 	bytespersec = 0;
    896 	if (bytes > 0) {
    897 		bytespersec = bytes;
    898 		if (elapsed > 0.0)
    899 			bytespersec /= elapsed;
    900 	}
    901 	for (i = 1; bytespersec >= 1024000 && i < sizeof(prefixes); i++)
    902 		bytespersec >>= 10;
    903 	len += snprintf(buf + len, sizeof(buf) - len,
    904 #ifndef NO_QUAD
    905 	    " %3qd.%02d %cB/s ", (long long)bytespersec / 1024,
    906 #else
    907 	    " %3ld.%02d %cB/s ", (long)bytespersec / 1024,
    908 #endif
    909 	    (int)((bytespersec % 1024) * 100 / 1024),
    910 	    prefixes[i]);
    911 
    912 	if (bytes <= 0 || elapsed <= 0.0 || cursize > filesize) {
    913 		len += snprintf(buf + len, sizeof(buf) - len,
    914 		    "   --:-- ETA");
    915 	} else if (wait.tv_sec >= STALLTIME) {
    916 		len += snprintf(buf + len, sizeof(buf) - len,
    917 		    " - stalled -");
    918 	} else {
    919 		remaining = (int)
    920 		    ((filesize - restart_point) / (bytes / elapsed) - elapsed);
    921 		if (remaining >= 100 * SECSPERHOUR)
    922 			len += snprintf(buf + len, sizeof(buf) - len,
    923 			    "   --:-- ETA");
    924 		else {
    925 			i = remaining / SECSPERHOUR;
    926 			if (i)
    927 				len += snprintf(buf + len, sizeof(buf) - len,
    928 				    "%2d:", i);
    929 			else
    930 				len += snprintf(buf + len, sizeof(buf) - len,
    931 				    "   ");
    932 			i = remaining % SECSPERHOUR;
    933 			len += snprintf(buf + len, sizeof(buf) - len,
    934 			    "%02d:%02d ETA", i / 60, i % 60);
    935 		}
    936 	}
    937 	(void)write(fileno(ttyout), buf, len);
    938 
    939 	if (flag == -1) {
    940 		(void)xsignal(SIGALRM, updateprogressmeter);
    941 		alarmtimer(1);		/* set alarm timer for 1 Hz */
    942 	} else if (flag == 1) {
    943 		(void)xsignal(SIGALRM, SIG_DFL);
    944 		alarmtimer(0);
    945 		(void)putc('\n', ttyout);
    946 	}
    947 	fflush(ttyout);
    948 #endif	/* !NO_PROGRESS */
    949 }
    950 
    951 /*
    952  * Display transfer statistics.
    953  * Requires start to be initialised by progressmeter(-1),
    954  * direction to be defined by xfer routines, and filesize and bytes
    955  * to be updated by xfer routines
    956  * If siginfo is nonzero, an ETA is displayed, and the output goes to stderr
    957  * instead of ttyout.
    958  */
    959 void
    960 ptransfer(siginfo)
    961 	int siginfo;
    962 {
    963 	struct timeval now, td, wait;
    964 	double elapsed;
    965 	off_t bytespersec;
    966 	int remaining, hh, i, len;
    967 	char buf[100];
    968 
    969 	if (!verbose && !progress && !siginfo)
    970 		return;
    971 
    972 	(void)gettimeofday(&now, NULL);
    973 	timersub(&now, &start, &td);
    974 	elapsed = td.tv_sec + (td.tv_usec / 1000000.0);
    975 	bytespersec = 0;
    976 	if (bytes > 0) {
    977 		bytespersec = bytes;
    978 		if (elapsed > 0.0)
    979 			bytespersec /= elapsed;
    980 	}
    981 	len = 0;
    982 	len += snprintf(buf + len, sizeof(buf) - len,
    983 #ifndef NO_QUAD
    984 	    "%qd byte%s %s in ", (long long)bytes,
    985 #else
    986 	    "%ld byte%s %s in ", (long)bytes,
    987 #endif
    988 	    bytes == 1 ? "" : "s", direction);
    989 	remaining = (int)elapsed;
    990 	if (remaining > SECSPERDAY) {
    991 		int days;
    992 
    993 		days = remaining / SECSPERDAY;
    994 		remaining %= SECSPERDAY;
    995 		len += snprintf(buf + len, sizeof(buf) - len,
    996 		    "%d day%s ", days, days == 1 ? "" : "s");
    997 	}
    998 	hh = remaining / SECSPERHOUR;
    999 	remaining %= SECSPERHOUR;
   1000 	if (hh)
   1001 		len += snprintf(buf + len, sizeof(buf) - len, "%2d:", hh);
   1002 	len += snprintf(buf + len, sizeof(buf) - len,
   1003 	    "%02d:%02d ", remaining / 60, remaining % 60);
   1004 
   1005 	for (i = 1; bytespersec >= 1024000 && i < sizeof(prefixes); i++)
   1006 		bytespersec >>= 10;
   1007 	len += snprintf(buf + len, sizeof(buf) - len,
   1008 #ifndef NO_QUAD
   1009 	    "(%qd.%02d %cB/s)", (long long)bytespersec / 1024,
   1010 #else
   1011 	    "(%ld.%02d %cB/s)", (long)bytespersec / 1024,
   1012 #endif
   1013 	    (int)((bytespersec % 1024) * 100 / 1024),
   1014 	    prefixes[i]);
   1015 
   1016 	if (siginfo && bytes > 0 && elapsed > 0.0 && filesize >= 0
   1017 	    && bytes + restart_point <= filesize) {
   1018 		remaining = (int)((filesize - restart_point) /
   1019 				  (bytes / elapsed) - elapsed);
   1020 		hh = remaining / SECSPERHOUR;
   1021 		remaining %= SECSPERHOUR;
   1022 		len += snprintf(buf + len, sizeof(buf) - len, "  ETA: ");
   1023 		if (hh)
   1024 			len += snprintf(buf + len, sizeof(buf) - len, "%2d:",
   1025 			    hh);
   1026 		len += snprintf(buf + len, sizeof(buf) - len,
   1027 		    "%02d:%02d", remaining / 60, remaining % 60);
   1028 		timersub(&now, &lastupdate, &wait);
   1029 		if (wait.tv_sec >= STALLTIME)
   1030 			len += snprintf(buf + len, sizeof(buf) - len,
   1031 			    "  (stalled)");
   1032 	}
   1033 	len += snprintf(buf + len, sizeof(buf) - len, "\n");
   1034 	(void)write(siginfo ? STDERR_FILENO : fileno(ttyout), buf, len);
   1035 }
   1036 
   1037 /*
   1038  * List words in stringlist, vertically arranged
   1039  */
   1040 void
   1041 list_vertical(sl)
   1042 	StringList *sl;
   1043 {
   1044 	int i, j, w;
   1045 	int columns, width, lines, items;
   1046 	char *p;
   1047 
   1048 	width = items = 0;
   1049 
   1050 	for (i = 0 ; i < sl->sl_cur ; i++) {
   1051 		w = strlen(sl->sl_str[i]);
   1052 		if (w > width)
   1053 			width = w;
   1054 	}
   1055 	width = (width + 8) &~ 7;
   1056 
   1057 	columns = ttywidth / width;
   1058 	if (columns == 0)
   1059 		columns = 1;
   1060 	lines = (sl->sl_cur + columns - 1) / columns;
   1061 	for (i = 0; i < lines; i++) {
   1062 		for (j = 0; j < columns; j++) {
   1063 			p = sl->sl_str[j * lines + i];
   1064 			if (p)
   1065 				fputs(p, ttyout);
   1066 			if (j * lines + i + lines >= sl->sl_cur) {
   1067 				putc('\n', ttyout);
   1068 				break;
   1069 			}
   1070 			w = strlen(p);
   1071 			while (w < width) {
   1072 				w = (w + 8) &~ 7;
   1073 				(void)putc('\t', ttyout);
   1074 			}
   1075 		}
   1076 	}
   1077 }
   1078 
   1079 /*
   1080  * Update the global ttywidth value, using TIOCGWINSZ.
   1081  */
   1082 void
   1083 setttywidth(a)
   1084 	int a;
   1085 {
   1086 	struct winsize winsize;
   1087 	int oerrno;
   1088 
   1089 	oerrno = errno;
   1090 	if (ioctl(fileno(ttyout), TIOCGWINSZ, &winsize) != -1 &&
   1091 	    winsize.ws_col != 0)
   1092 		ttywidth = winsize.ws_col;
   1093 	else
   1094 		ttywidth = 80;
   1095 	errno = oerrno;
   1096 }
   1097 
   1098 void
   1099 crankrate(int sig)
   1100 {
   1101 
   1102 	switch (sig) {
   1103 	case SIGUSR1:
   1104 		if (rate_get)
   1105 			rate_get += rate_get_incr;
   1106 		if (rate_put)
   1107 			rate_put += rate_put_incr;
   1108 		break;
   1109 	case SIGUSR2:
   1110 		if (rate_get && rate_get > rate_get_incr)
   1111 			rate_get -= rate_get_incr;
   1112 		if (rate_put && rate_put > rate_put_incr)
   1113 			rate_put -= rate_put_incr;
   1114 		break;
   1115 	default:
   1116 		err(1, "crankrate invoked with unknown signal: %d", sig);
   1117 	}
   1118 }
   1119 
   1120 
   1121 /*
   1122  * Set the SIGALRM interval timer for wait seconds, 0 to disable.
   1123  */
   1124 void
   1125 alarmtimer(wait)
   1126 	int wait;
   1127 {
   1128 	struct itimerval itv;
   1129 
   1130 	itv.it_value.tv_sec = wait;
   1131 	itv.it_value.tv_usec = 0;
   1132 	itv.it_interval = itv.it_value;
   1133 	setitimer(ITIMER_REAL, &itv, NULL);
   1134 }
   1135 
   1136 /*
   1137  * Setup or cleanup EditLine structures
   1138  */
   1139 #ifndef NO_EDITCOMPLETE
   1140 void
   1141 controlediting()
   1142 {
   1143 	if (editing && el == NULL && hist == NULL) {
   1144 		HistEvent ev;
   1145 		int editmode;
   1146 
   1147 		el = el_init(__progname, stdin, ttyout, stderr);
   1148 		/* init editline */
   1149 		hist = history_init();		/* init the builtin history */
   1150 		history(hist, &ev, H_SETSIZE, 100);/* remember 100 events */
   1151 		el_set(el, EL_HIST, history, hist);	/* use history */
   1152 
   1153 		el_set(el, EL_EDITOR, "emacs");	/* default editor is emacs */
   1154 		el_set(el, EL_PROMPT, prompt);	/* set the prompt function */
   1155 
   1156 		/* add local file completion, bind to TAB */
   1157 		el_set(el, EL_ADDFN, "ftp-complete",
   1158 		    "Context sensitive argument completion",
   1159 		    complete);
   1160 		el_set(el, EL_BIND, "^I", "ftp-complete", NULL);
   1161 		el_source(el, NULL);	/* read ~/.editrc */
   1162 		if ((el_get(el, EL_EDITMODE, &editmode) != -1) && editmode == 0)
   1163 			editing = 0;	/* the user doesn't want editing,
   1164 					 * so disable, and let statement
   1165 					 * below cleanup */
   1166 		else
   1167 			el_set(el, EL_SIGNAL, 1);
   1168 	}
   1169 	if (!editing) {
   1170 		if (hist) {
   1171 			history_end(hist);
   1172 			hist = NULL;
   1173 		}
   1174 		if (el) {
   1175 			el_end(el);
   1176 			el = NULL;
   1177 		}
   1178 	}
   1179 }
   1180 #endif /* !NO_EDITCOMPLETE */
   1181 
   1182 /*
   1183  * Convert the string `arg' to an int, which may have an optional SI suffix
   1184  * (`b', `k', `m', `g'). Returns the number for success, -1 otherwise.
   1185  */
   1186 int
   1187 strsuftoi(arg)
   1188 	const char *arg;
   1189 {
   1190 	char *cp;
   1191 	long val;
   1192 
   1193 	if (!isdigit((unsigned char)arg[0]))
   1194 		return (-1);
   1195 
   1196 	val = strtol(arg, &cp, 10);
   1197 	if (cp != NULL) {
   1198 		if (cp[0] != '\0' && cp[1] != '\0')
   1199 			 return (-1);
   1200 		switch (tolower((unsigned char)cp[0])) {
   1201 		case '\0':
   1202 		case 'b':
   1203 			break;
   1204 		case 'k':
   1205 			val <<= 10;
   1206 			break;
   1207 		case 'm':
   1208 			val <<= 20;
   1209 			break;
   1210 		case 'g':
   1211 			val <<= 30;
   1212 			break;
   1213 		default:
   1214 			return (-1);
   1215 		}
   1216 	}
   1217 	if (val < 0 || val > INT_MAX)
   1218 		return (-1);
   1219 
   1220 	return (val);
   1221 }
   1222 
   1223 /*
   1224  * Set up socket buffer sizes before a connection is made.
   1225  */
   1226 void
   1227 setupsockbufsize(sock)
   1228 	int sock;
   1229 {
   1230 	static int sndbuf_default, rcvbuf_default;
   1231 	int len, size;
   1232 
   1233 	/*
   1234 	 * Get the default socket buffer sizes if we don't already
   1235 	 * have them.  It doesn't matter which socket we do this
   1236 	 * to, because on the first call no socket buffer sizes
   1237 	 * will have been modified, so we are guaranteed to get
   1238 	 * the system defaults.
   1239 	 */
   1240 	if (sndbuf_default == 0) {
   1241 		len = sizeof(sndbuf_default);
   1242 		if (getsockopt(sock, SOL_SOCKET, SO_SNDBUF,
   1243 		    (void *) &sndbuf_default, &len) < 0)
   1244 			err(1, "unable to get default sndbuf size");
   1245 		len = sizeof(rcvbuf_default);
   1246 		if (getsockopt(sock, SOL_SOCKET, SO_RCVBUF,
   1247 		    (void *) &rcvbuf_default, &len) < 0)
   1248 			err(1, "unable to get default rcvbuf size");
   1249 
   1250 	}
   1251 
   1252 	size = sndbuf_size ? sndbuf_size : sndbuf_default;
   1253 	if (setsockopt(sock, SOL_SOCKET, SO_SNDBUF, (void *) &size,
   1254 	    sizeof(size)) < 0)
   1255 		warn("unable to set sndbuf size %d", size);
   1256 
   1257 	size = rcvbuf_size ? rcvbuf_size : rcvbuf_default;
   1258 	if (setsockopt(sock, SOL_SOCKET, SO_RCVBUF, (void *) &size,
   1259 	    sizeof(size)) < 0)
   1260 		warn("unable to set rcvbuf size %d", size);
   1261 }
   1262 
   1263 /*
   1264  * If the socket buffer sizes were not set manually (i.e. came from a
   1265  * configuration file), reset them so the right thing will happen on
   1266  * subsequent connections.
   1267  */
   1268 void
   1269 resetsockbufsize()
   1270 {
   1271 
   1272 	if (sndbuf_manual == 0)
   1273 		sndbuf_size = 0;
   1274 	if (rcvbuf_manual == 0)
   1275 		rcvbuf_size = 0;
   1276 }
   1277 
   1278 void
   1279 ftpvis(dst, dstlen, src, srclen)
   1280 	char		*dst;
   1281 	size_t		 dstlen;
   1282 	const char	*src;
   1283 	size_t		 srclen;
   1284 {
   1285 	int	di, si;
   1286 
   1287 	for (di = si = 0;
   1288 	    src[si] != '\0' && di < dstlen && si < srclen;
   1289 	    di++, si++) {
   1290 		switch (src[si]) {
   1291 		case '\\':
   1292 		case ' ':
   1293 		case '\t':
   1294 		case '\r':
   1295 		case '\n':
   1296 		case '"':
   1297 			dst[di++] = '\\';
   1298 			if (di >= dstlen)
   1299 				break;
   1300 			/* FALLTHROUGH */
   1301 		default:
   1302 			dst[di] = src[si];
   1303 		}
   1304 	}
   1305 	dst[di] = '\0';
   1306 }
   1307 
   1308 /*
   1309  * Determine if given string is an IPv6 address or not.
   1310  * Return 1 for yes, 0 for no
   1311  */
   1312 int
   1313 isipv6addr(addr)
   1314 	const char *addr;
   1315 {
   1316 	int rv = 0;
   1317 #ifdef INET6
   1318 	u_char buf[16];		/* XXX: sizeof(struct in_addr6) */
   1319 
   1320 	rv = inet_pton(AF_INET6, addr, &buf);
   1321 	if (debug)
   1322 		fprintf(ttyout, "isipv6addr: got %d for %s\n", rv, addr);
   1323 #endif
   1324 	return rv;
   1325 }
   1326 
   1327 
   1328 /*
   1329  * Internal version of connect(2); sets socket buffer sizes first.
   1330  */
   1331 int
   1332 xconnect(sock, name, namelen)
   1333 	int sock;
   1334 	const struct sockaddr *name;
   1335 	int namelen;
   1336 {
   1337 
   1338 	setupsockbufsize(sock);
   1339 	return (connect(sock, name, namelen));
   1340 }
   1341 
   1342 /*
   1343  * Internal version of listen(2); sets socket buffer sizes first.
   1344  */
   1345 int
   1346 xlisten(sock, backlog)
   1347 	int sock, backlog;
   1348 {
   1349 
   1350 	setupsockbufsize(sock);
   1351 	return (listen(sock, backlog));
   1352 }
   1353 
   1354 void *
   1355 xmalloc(size)
   1356 	size_t size;
   1357 {
   1358 	void *p;
   1359 
   1360 	p = malloc(size);
   1361 	if (p == NULL)
   1362 		err(1, "Unable to allocate %ld bytes of memory", (long)size);
   1363 	return (p);
   1364 }
   1365 
   1366 char *
   1367 xstrdup(str)
   1368 	const char *str;
   1369 {
   1370 	char *s;
   1371 
   1372 	if (str == NULL)
   1373 		errx(1, "xstrdup() called with NULL argument");
   1374 	s = strdup(str);
   1375 	if (s == NULL)
   1376 		err(1, "Unable to allocate memory for string copy");
   1377 	return (s);
   1378 }
   1379 
   1380 sig_t
   1381 xsignal(sig, func)
   1382 	int sig;
   1383 	void (*func) __P((int));
   1384 {
   1385 	struct sigaction act, oact;
   1386 
   1387 	act.sa_handler = func;
   1388 	sigemptyset(&act.sa_mask);
   1389 	act.sa_flags = SA_RESTART;
   1390 	if (sigaction(sig, &act, &oact) < 0)
   1391 		return (SIG_ERR);
   1392 	return (oact.sa_handler);
   1393 }
   1394