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