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