xref: /netbsd-src/usr.bin/ftp/util.c (revision e4d7c2e329d54c97e0c0bd3016bbe74f550c3d5e)
1 /*	$NetBSD: util.c,v 1.91 2000/01/31 22:01:05 lukem Exp $	*/
2 
3 /*-
4  * Copyright (c) 1997-1999 The NetBSD Foundation, Inc.
5  * All rights reserved.
6  *
7  * This code is derived from software contributed to The NetBSD Foundation
8  * by Luke Mewburn.
9  *
10  * This code is derived from software contributed to The NetBSD Foundation
11  * by Jason R. Thorpe of the Numerical Aerospace Simulation Facility,
12  * NASA Ames Research Center.
13  *
14  * Redistribution and use in source and binary forms, with or without
15  * modification, are permitted provided that the following conditions
16  * are met:
17  * 1. Redistributions of source code must retain the above copyright
18  *    notice, this list of conditions and the following disclaimer.
19  * 2. Redistributions in binary form must reproduce the above copyright
20  *    notice, this list of conditions and the following disclaimer in the
21  *    documentation and/or other materials provided with the distribution.
22  * 3. All advertising materials mentioning features or use of this software
23  *    must display the following acknowledgement:
24  *	This product includes software developed by the NetBSD
25  *	Foundation, Inc. and its contributors.
26  * 4. Neither the name of The NetBSD Foundation nor the names of its
27  *    contributors may be used to endorse or promote products derived
28  *    from this software without specific prior written permission.
29  *
30  * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
31  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
32  * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
33  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
34  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
35  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
36  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
37  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
38  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
39  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
40  * POSSIBILITY OF SUCH DAMAGE.
41  */
42 
43 /*
44  * Copyright (c) 1985, 1989, 1993, 1994
45  *	The Regents of the University of California.  All rights reserved.
46  *
47  * Redistribution and use in source and binary forms, with or without
48  * modification, are permitted provided that the following conditions
49  * are met:
50  * 1. Redistributions of source code must retain the above copyright
51  *    notice, this list of conditions and the following disclaimer.
52  * 2. Redistributions in binary form must reproduce the above copyright
53  *    notice, this list of conditions and the following disclaimer in the
54  *    documentation and/or other materials provided with the distribution.
55  * 3. All advertising materials mentioning features or use of this software
56  *    must display the following acknowledgement:
57  *	This product includes software developed by the University of
58  *	California, Berkeley and its contributors.
59  * 4. Neither the name of the University nor the names of its contributors
60  *    may be used to endorse or promote products derived from this software
61  *    without specific prior written permission.
62  *
63  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
64  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
65  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
66  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
67  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
68  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
69  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
70  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
71  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
72  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
73  * SUCH DAMAGE.
74  */
75 
76 #include <sys/cdefs.h>
77 #ifndef lint
78 __RCSID("$NetBSD: util.c,v 1.91 2000/01/31 22:01:05 lukem Exp $");
79 #endif /* not lint */
80 
81 /*
82  * FTP User Program -- Misc support routines
83  */
84 #include <sys/types.h>
85 #include <sys/socket.h>
86 #include <sys/ioctl.h>
87 #include <sys/time.h>
88 #include <netinet/in.h>
89 #include <arpa/ftp.h>
90 
91 #include <ctype.h>
92 #include <err.h>
93 #include <errno.h>
94 #include <fcntl.h>
95 #include <glob.h>
96 #include <signal.h>
97 #include <limits.h>
98 #include <pwd.h>
99 #include <stdio.h>
100 #include <stdlib.h>
101 #include <string.h>
102 #include <termios.h>
103 #include <time.h>
104 #include <tzfile.h>
105 #include <unistd.h>
106 
107 #include "ftp_var.h"
108 
109 /*
110  * Connect to peer server and
111  * auto-login, if possible.
112  */
113 void
114 setpeer(argc, argv)
115 	int argc;
116 	char *argv[];
117 {
118 	char *host;
119 	char *port;
120 
121 	if (argc == 0)
122 		goto usage;
123 	if (connected) {
124 		fprintf(ttyout, "Already connected to %s, use close first.\n",
125 		    hostname);
126 		code = -1;
127 		return;
128 	}
129 	if (argc < 2)
130 		(void)another(&argc, &argv, "to");
131 	if (argc < 2 || argc > 3) {
132  usage:
133 		fprintf(ttyout, "usage: %s host-name [port]\n", argv[0]);
134 		code = -1;
135 		return;
136 	}
137 	if (gatemode)
138 		port = gateport;
139 	else
140 		port = ftpport;
141 	if (argc > 2)
142 		port = argv[2];
143 
144 	if (gatemode) {
145 		if (gateserver == NULL || *gateserver == '\0')
146 			errx(1, "gateserver not defined (shouldn't happen)");
147 		host = hookup(gateserver, port);
148 	} else
149 		host = hookup(argv[1], port);
150 
151 	if (host) {
152 		int overbose;
153 
154 		if (gatemode && verbose) {
155 			fprintf(ttyout,
156 			    "Connecting via pass-through server %s\n",
157 			    gateserver);
158 		}
159 
160 		connected = 1;
161 		/*
162 		 * Set up defaults for FTP.
163 		 */
164 		(void)strlcpy(typename, "ascii", sizeof(typename));
165 		type = TYPE_A;
166 		curtype = TYPE_A;
167 		(void)strlcpy(formname, "non-print", sizeof(formname));
168 		form = FORM_N;
169 		(void)strlcpy(modename, "stream", sizeof(modename));
170 		mode = MODE_S;
171 		(void)strlcpy(structname, "file", sizeof(structname));
172 		stru = STRU_F;
173 		(void)strlcpy(bytename, "8", sizeof(bytename));
174 		bytesize = 8;
175 		if (autologin)
176 			(void)ftp_login(argv[1], NULL, NULL);
177 
178 		overbose = verbose;
179 		if (debug == 0)
180 			verbose = -1;
181 		if (command("SYST") == COMPLETE && overbose) {
182 			char *cp, c;
183 			c = 0;
184 			cp = strchr(reply_string + 4, ' ');
185 			if (cp == NULL)
186 				cp = strchr(reply_string + 4, '\r');
187 			if (cp) {
188 				if (cp[-1] == '.')
189 					cp--;
190 				c = *cp;
191 				*cp = '\0';
192 			}
193 
194 			fprintf(ttyout, "Remote system type is %s.\n",
195 			    reply_string + 4);
196 			if (cp)
197 				*cp = c;
198 		}
199 		if (!strncmp(reply_string, "215 UNIX Type: L8", 17)) {
200 			if (proxy)
201 				unix_proxy = 1;
202 			else
203 				unix_server = 1;
204 			/*
205 			 * Set type to 0 (not specified by user),
206 			 * meaning binary by default, but don't bother
207 			 * telling server.  We can use binary
208 			 * for text files unless changed by the user.
209 			 */
210 			type = 0;
211 			(void)strlcpy(typename, "binary", sizeof(typename));
212 			if (overbose)
213 			    fprintf(ttyout,
214 				"Using %s mode to transfer files.\n",
215 				typename);
216 		} else {
217 			if (proxy)
218 				unix_proxy = 0;
219 			else
220 				unix_server = 0;
221 			if (overbose &&
222 			    !strncmp(reply_string, "215 TOPS20", 10))
223 				fputs(
224 "Remember to set tenex mode when transferring binary files from this machine.\n",
225 				    ttyout);
226 		}
227 		verbose = overbose;
228 	}
229 }
230 
231 /*
232  * Reset the various variables that indicate connection state back to
233  * disconnected settings.
234  * The caller is responsible for issuing any commands to the remote server
235  * to perform a clean shutdown before this is invoked.
236  */
237 void
238 cleanuppeer()
239 {
240 
241 	if (cout)
242 		(void)fclose(cout);
243 	cout = NULL;
244 	connected = 0;
245 			/*
246 			 * determine if anonftp was specifically set with -a
247 			 * (1), or implicitly set by auto_fetch() (2). in the
248 			 * latter case, disable after the current xfer
249 			 */
250 	if (anonftp == 2)
251 		anonftp = 0;
252 	data = -1;
253 	epsv4bad = 0;
254 	if (username)
255 		free(username);
256 	username = NULL;
257 	if (!proxy)
258 		macnum = 0;
259 }
260 
261 /*
262  * Top-level signal handler for interrupted commands.
263  */
264 void
265 intr(dummy)
266 	int dummy;
267 {
268 
269 	alarmtimer(0);
270 	if (fromatty)
271 		write(fileno(ttyout), "\n", 1);
272 	siglongjmp(toplevel, 1);
273 }
274 
275 /*
276  * Signal handler for lost connections; cleanup various elements of
277  * the connection state, and call cleanuppeer() to finish it off.
278  */
279 void
280 lostpeer(dummy)
281 	int dummy;
282 {
283 	int oerrno = errno;
284 
285 	alarmtimer(0);
286 	if (connected) {
287 		if (cout != NULL) {
288 			(void)shutdown(fileno(cout), 1+1);
289 			(void)fclose(cout);
290 			cout = NULL;
291 		}
292 		if (data >= 0) {
293 			(void)shutdown(data, 1+1);
294 			(void)close(data);
295 			data = -1;
296 		}
297 		connected = 0;
298 	}
299 	pswitch(1);
300 	if (connected) {
301 		if (cout != NULL) {
302 			(void)shutdown(fileno(cout), 1+1);
303 			(void)fclose(cout);
304 			cout = NULL;
305 		}
306 		connected = 0;
307 	}
308 	proxflag = 0;
309 	pswitch(0);
310 	cleanuppeer();
311 	errno = oerrno;
312 }
313 
314 
315 /*
316  * login to remote host, using given username & password if supplied
317  */
318 int
319 ftp_login(host, user, pass)
320 	const char *host;
321 	const char *user, *pass;
322 {
323 	char tmp[80];
324 	const char *acct;
325 	struct passwd *pw;
326 	int n, aflag, rval, freeuser, freepass, freeacct;
327 
328 	acct = NULL;
329 	aflag = rval = freeuser = freepass = freeacct = 0;
330 
331 	if (debug)
332 		fprintf(ttyout, "ftp_login: user `%s' pass `%s' host `%s'\n",
333 		    user ? user : "<null>", pass ? pass : "<null>",
334 		    host ? host : "<null>");
335 
336 
337 	/*
338 	 * Set up arguments for an anonymous FTP session, if necessary.
339 	 */
340 	if (anonftp) {
341 		user = "anonymous";	/* as per RFC 1635 */
342 		pass = getoptionvalue("anonpass");
343 	}
344 
345 	if (user == NULL)
346 		freeuser = 1;
347 	if (pass == NULL)
348 		freepass = 1;
349 	freeacct = 1;
350 	if (ruserpass(host, &user, &pass, &acct) < 0) {
351 		code = -1;
352 		goto cleanup_ftp_login;
353 	}
354 
355 	while (user == NULL) {
356 		const char *myname = getlogin();
357 
358 		if (myname == NULL && (pw = getpwuid(getuid())) != NULL)
359 			myname = pw->pw_name;
360 		if (myname)
361 			fprintf(ttyout, "Name (%s:%s): ", host, myname);
362 		else
363 			fprintf(ttyout, "Name (%s): ", host);
364 		*tmp = '\0';
365 		if (fgets(tmp, sizeof(tmp) - 1, stdin) == NULL) {
366 			fprintf(ttyout, "\nEOF received; login aborted.\n");
367 			clearerr(stdin);
368 			code = -1;
369 			goto cleanup_ftp_login;
370 		}
371 		tmp[strlen(tmp) - 1] = '\0';
372 		freeuser = 0;
373 		if (*tmp == '\0')
374 			user = myname;
375 		else
376 			user = tmp;
377 	}
378 
379 	if (gatemode) {
380 		char *nuser;
381 		int len;
382 
383 		len = strlen(user) + 1 + strlen(host) + 1;
384 		nuser = xmalloc(len);
385 		(void)strlcpy(nuser, user, len);
386 		(void)strlcat(nuser, "@",  len);
387 		(void)strlcat(nuser, host, len);
388 		freeuser = 1;
389 		user = nuser;
390 	}
391 
392 	n = command("USER %s", user);
393 	if (n == CONTINUE) {
394 		if (pass == NULL) {
395 			freepass = 0;
396 			pass = getpass("Password:");
397 		}
398 		n = command("PASS %s", pass);
399 	}
400 	if (n == CONTINUE) {
401 		aflag++;
402 		if (acct == NULL) {
403 			freeacct = 0;
404 			acct = getpass("Account:");
405 		}
406 		if (acct[0] == '\0') {
407 			warnx("Login failed.");
408 			goto cleanup_ftp_login;
409 		}
410 		n = command("ACCT %s", acct);
411 	}
412 	if ((n != COMPLETE) ||
413 	    (!aflag && acct != NULL && command("ACCT %s", acct) != COMPLETE)) {
414 		warnx("Login failed.");
415 		goto cleanup_ftp_login;
416 	}
417 	rval = 1;
418 	username = xstrdup(user);
419 	if (proxy)
420 		goto cleanup_ftp_login;
421 
422 	connected = -1;
423 	for (n = 0; n < macnum; ++n) {
424 		if (!strcmp("init", macros[n].mac_name)) {
425 			(void)strlcpy(line, "$init", sizeof(line));
426 			makeargv();
427 			domacro(margc, margv);
428 			break;
429 		}
430 	}
431 	updateremotepwd();
432 
433 cleanup_ftp_login:
434 	if (user != NULL && freeuser)
435 		free((char *)user);
436 	if (pass != NULL && freepass)
437 		free((char *)pass);
438 	if (acct != NULL && freeacct)
439 		free((char *)acct);
440 	return (rval);
441 }
442 
443 /*
444  * `another' gets another argument, and stores the new argc and argv.
445  * It reverts to the top level (via intr()) on EOF/error.
446  *
447  * Returns false if no new arguments have been added.
448  */
449 int
450 another(pargc, pargv, prompt)
451 	int *pargc;
452 	char ***pargv;
453 	const char *prompt;
454 {
455 	int len = strlen(line), ret;
456 
457 	if (len >= sizeof(line) - 3) {
458 		fputs("sorry, arguments too long.\n", ttyout);
459 		intr(0);
460 	}
461 	fprintf(ttyout, "(%s) ", prompt);
462 	line[len++] = ' ';
463 	if (fgets(&line[len], sizeof(line) - len, stdin) == NULL) {
464 		clearerr(stdin);
465 		intr(0);
466 	}
467 	len += strlen(&line[len]);
468 	if (len > 0 && line[len - 1] == '\n')
469 		line[len - 1] = '\0';
470 	makeargv();
471 	ret = margc > *pargc;
472 	*pargc = margc;
473 	*pargv = margv;
474 	return (ret);
475 }
476 
477 /*
478  * glob files given in argv[] from the remote server.
479  * if errbuf isn't NULL, store error messages there instead
480  * of writing to the screen.
481  */
482 char *
483 remglob(argv, doswitch, errbuf)
484         char *argv[];
485         int doswitch;
486 	char **errbuf;
487 {
488         char temp[MAXPATHLEN];
489         static char buf[MAXPATHLEN];
490         static FILE *ftemp = NULL;
491         static char **args;
492         int oldverbose, oldhash, fd, len;
493         char *cp, *mode;
494 
495         if (!mflag || !connected) {
496                 if (!doglob)
497                         args = NULL;
498                 else {
499                         if (ftemp) {
500                                 (void)fclose(ftemp);
501                                 ftemp = NULL;
502                         }
503                 }
504                 return (NULL);
505         }
506         if (!doglob) {
507                 if (args == NULL)
508                         args = argv;
509                 if ((cp = *++args) == NULL)
510                         args = NULL;
511                 return (cp);
512         }
513         if (ftemp == NULL) {
514 		len = strlcpy(temp, tmpdir, sizeof(temp));
515 		if (temp[len - 1] != '/')
516 			(void)strlcat(temp, "/", sizeof(temp));
517 		(void)strlcat(temp, TMPFILE, sizeof(temp));
518                 if ((fd = mkstemp(temp)) < 0) {
519                         warn("unable to create temporary file %s", temp);
520                         return (NULL);
521                 }
522                 close(fd);
523                 oldverbose = verbose;
524 		verbose = (errbuf != NULL) ? -1 : 0;
525                 oldhash = hash;
526                 hash = 0;
527                 if (doswitch)
528                         pswitch(!proxy);
529                 for (mode = "w"; *++argv != NULL; mode = "a")
530                         recvrequest("NLST", temp, *argv, mode, 0, 0);
531 		if ((code / 100) != COMPLETE) {
532 			if (errbuf != NULL)
533 				*errbuf = reply_string;
534 		}
535                 if (doswitch)
536                         pswitch(!proxy);
537                 verbose = oldverbose;
538 		hash = oldhash;
539                 ftemp = fopen(temp, "r");
540                 (void)unlink(temp);
541                 if (ftemp == NULL) {
542 			if (errbuf == NULL)
543 				fputs(
544 				    "can't find list of remote files, oops.\n",
545 				    ttyout);
546 			else
547 				*errbuf =
548 				    "can't find list of remote files, oops.";
549                         return (NULL);
550                 }
551         }
552         if (fgets(buf, sizeof(buf), ftemp) == NULL) {
553                 (void)fclose(ftemp);
554 		ftemp = NULL;
555                 return (NULL);
556         }
557         if ((cp = strchr(buf, '\n')) != NULL)
558                 *cp = '\0';
559         return (buf);
560 }
561 
562 /*
563  * Glob a local file name specification with the expectation of a single
564  * return value. Can't control multiple values being expanded from the
565  * expression, we return only the first.
566  * Returns NULL on error, or a pointer to a buffer containing the filename
567  * that's the caller's responsiblity to free(3) when finished with.
568  */
569 char *
570 globulize(pattern)
571 	const char *pattern;
572 {
573 	glob_t gl;
574 	int flags;
575 	char *p;
576 
577 	if (!doglob)
578 		return (xstrdup(pattern));
579 
580 	flags = GLOB_BRACE|GLOB_NOCHECK|GLOB_TILDE;
581 	memset(&gl, 0, sizeof(gl));
582 	if (glob(pattern, flags, NULL, &gl) || gl.gl_pathc == 0) {
583 		warnx("%s: not found", pattern);
584 		globfree(&gl);
585 		return (NULL);
586 	}
587 	p = xstrdup(gl.gl_pathv[0]);
588 	globfree(&gl);
589 	return (p);
590 }
591 
592 /*
593  * determine size of remote file
594  */
595 off_t
596 remotesize(file, noisy)
597 	const char *file;
598 	int noisy;
599 {
600 	int overbose;
601 	off_t size;
602 
603 	overbose = verbose;
604 	size = -1;
605 	if (debug == 0)
606 		verbose = -1;
607 	if (command("SIZE %s", file) == COMPLETE) {
608 		char *cp, *ep;
609 
610 		cp = strchr(reply_string, ' ');
611 		if (cp != NULL) {
612 			cp++;
613 #ifndef NO_QUAD
614 			size = strtoq(cp, &ep, 10);
615 #else
616 			size = strtol(cp, &ep, 10);
617 #endif
618 			if (*ep != '\0' && !isspace((unsigned char)*ep))
619 				size = -1;
620 		}
621 	} else if (noisy && debug == 0) {
622 		fputs(reply_string, ttyout);
623 		putc('\n', ttyout);
624 	}
625 	verbose = overbose;
626 	return (size);
627 }
628 
629 /*
630  * determine last modification time (in GMT) of remote file
631  */
632 time_t
633 remotemodtime(file, noisy)
634 	const char *file;
635 	int noisy;
636 {
637 	int overbose;
638 	time_t rtime;
639 	int ocode;
640 
641 	overbose = verbose;
642 	ocode = code;
643 	rtime = -1;
644 	if (debug == 0)
645 		verbose = -1;
646 	if (command("MDTM %s", file) == COMPLETE) {
647 		struct tm timebuf;
648 		char *timestr, *frac;
649 		int yy, mo, day, hour, min, sec;
650 
651 		/*
652 		 * time-val = 14DIGIT [ "." 1*DIGIT ]
653 		 *		YYYYMMDDHHMMSS[.sss]
654 		 * mdtm-response = "213" SP time-val CRLF / error-response
655 		 */
656 		timestr = reply_string + 4;
657 
658 					/*
659 					 * parse fraction.
660 					 * XXX: ignored for now
661 					 */
662 		frac = strchr(timestr, '\r');
663 		if (frac != NULL)
664 			*frac = '\0';
665 		frac = strchr(timestr, '.');
666 		if (frac != NULL)
667 			*frac++ = '\0';
668 		if (strlen(timestr) == 15 && strncmp(timestr, "191", 3) == 0) {
669 			/*
670 			 * XXX:	Workaround for lame ftpd's that return
671 			 *	`19100' instead of `2000'
672 			 */
673 			fprintf(ttyout,
674 	    "Y2K warning! Incorrect time-val `%s' received from server.\n",
675 			    timestr);
676 			timestr++;
677 			timestr[0] = '2';
678 			timestr[1] = '0';
679 			fprintf(ttyout, "Converted to `%s'\n", timestr);
680 		}
681 		if (strlen(timestr) != 14 ||
682 		    sscanf(timestr, "%04d%02d%02d%02d%02d%02d",
683 			&yy, &mo, &day, &hour, &min, &sec) != 6) {
684  bad_parse_time:
685 			fprintf(ttyout, "Can't parse time `%s'.\n", timestr);
686 			goto cleanup_parse_time;
687 		}
688 		memset(&timebuf, 0, sizeof(timebuf));
689 		timebuf.tm_sec = sec;
690 		timebuf.tm_min = min;
691 		timebuf.tm_hour = hour;
692 		timebuf.tm_mday = day;
693 		timebuf.tm_mon = mo - 1;
694 		timebuf.tm_year = yy - TM_YEAR_BASE;
695 		timebuf.tm_isdst = -1;
696 		rtime = timegm(&timebuf);
697 		if (rtime == -1) {
698 			if (noisy || debug != 0)
699 				goto bad_parse_time;
700 			else
701 				goto cleanup_parse_time;
702 		} else if (debug)
703 			fprintf(ttyout, "parsed date as: %s", ctime(&rtime));
704 	} else if (noisy && debug == 0) {
705 		fputs(reply_string, ttyout);
706 		putc('\n', ttyout);
707 	}
708  cleanup_parse_time:
709 	verbose = overbose;
710 	if (rtime == -1)
711 		code = ocode;
712 	return (rtime);
713 }
714 
715 /*
716  * update global `remotepwd', which contains the state of the remote cwd
717  */
718 void
719 updateremotepwd()
720 {
721 	int	 overbose, ocode, i;
722 	char	*cp;
723 
724 	overbose = verbose;
725 	ocode = code;
726 	if (debug == 0)
727 		verbose = -1;
728 	if (command("PWD") != COMPLETE)
729 		goto badremotepwd;
730 	cp = strchr(reply_string, ' ');
731 	if (cp == NULL || cp[0] == '\0' || cp[1] != '"')
732 		goto badremotepwd;
733 	cp += 2;
734 	for (i = 0; *cp && i < sizeof(remotepwd) - 1; i++, cp++) {
735 		if (cp[0] == '"') {
736 			if (cp[1] == '"')
737 				cp++;
738 			else
739 				break;
740 		}
741 		remotepwd[i] = *cp;
742 	}
743 	remotepwd[i] = '\0';
744 	if (debug)
745 		fprintf(ttyout, "got remotepwd as `%s'\n", remotepwd);
746 	goto cleanupremotepwd;
747  badremotepwd:
748 	remotepwd[0]='\0';
749  cleanupremotepwd:
750 	verbose = overbose;
751 	code = ocode;
752 }
753 
754 #ifndef	NO_PROGRESS
755 
756 /*
757  * return non-zero if we're the current foreground process
758  */
759 int
760 foregroundproc()
761 {
762 	static pid_t pgrp = -1;
763 
764 	if (pgrp == -1)
765 		pgrp = getpgrp();
766 
767 	return (tcgetpgrp(fileno(ttyout)) == pgrp);
768 }
769 
770 
771 static void updateprogressmeter __P((int));
772 
773 /*
774  * SIGALRM handler to update the progress meter
775  */
776 static void
777 updateprogressmeter(dummy)
778 	int dummy;
779 {
780 	int oerrno = errno;
781 
782 	progressmeter(0);
783 	errno = oerrno;
784 }
785 #endif	/* NO_PROGRESS */
786 
787 
788 /*
789  * List of order of magnitude prefixes.
790  * The last is `P', as 2^64 = 16384 Petabytes
791  */
792 static const char prefixes[] = " KMGTP";
793 
794 /*
795  * Display a transfer progress bar if progress is non-zero.
796  * SIGALRM is hijacked for use by this function.
797  * - Before the transfer, set filesize to size of file (or -1 if unknown),
798  *   and call with flag = -1. This starts the once per second timer,
799  *   and a call to updateprogressmeter() upon SIGALRM.
800  * - During the transfer, updateprogressmeter will call progressmeter
801  *   with flag = 0
802  * - After the transfer, call with flag = 1
803  */
804 static struct timeval start;
805 static struct timeval lastupdate;
806 
807 #define	BUFLEFT	(sizeof(buf) - len)
808 
809 void
810 progressmeter(flag)
811 	int flag;
812 {
813 	static off_t lastsize;
814 #ifndef NO_PROGRESS
815 	struct timeval now, td, wait;
816 	off_t cursize, abbrevsize, bytespersec;
817 	double elapsed;
818 	int ratio, barlength, i, len, remaining;
819 
820 			/*
821 			 * Work variables for progress bar.
822 			 *
823 			 * XXX:	if the format of the progress bar changes
824 			 *	(especially the number of characters in the
825 			 *	`static' portion of it), be sure to update
826 			 *	these appropriately.
827 			 */
828 	char		buf[256];	/* workspace for progress bar */
829 #define	BAROVERHEAD	43		/* non `*' portion of progress bar */
830 					/*
831 					 * stars should contain at least
832 					 * sizeof(buf) - BAROVERHEAD entries
833 					 */
834 	const char	stars[] =
835 "*****************************************************************************"
836 "*****************************************************************************"
837 "*****************************************************************************";
838 
839 #endif
840 
841 	if (flag == -1) {
842 		(void)gettimeofday(&start, NULL);
843 		lastupdate = start;
844 		lastsize = restart_point;
845 	}
846 #ifndef NO_PROGRESS
847 	len = 0;
848 	if (!progress || filesize <= 0)
849 		return;
850 
851 	(void)gettimeofday(&now, NULL);
852 	cursize = bytes + restart_point;
853 	timersub(&now, &lastupdate, &wait);
854 	if (cursize > lastsize) {
855 		lastupdate = now;
856 		lastsize = cursize;
857 		wait.tv_sec = 0;
858 	}
859 
860 	/*
861 	 * print progress bar only if we are foreground process.
862 	 */
863 	if (! foregroundproc())
864 		return;
865 
866 	ratio = (int)((double)cursize * 100.0 / (double)filesize);
867 	ratio = MAX(ratio, 0);
868 	ratio = MIN(ratio, 100);
869 	len += snprintf(buf + len, BUFLEFT, "\r%3d%% ", ratio);
870 
871 			/*
872 			 * calculate the length of the `*' bar, ensuring that
873 			 * the number of stars won't exceed the buffer size
874 			 */
875 	barlength = MIN(sizeof(buf) - 1, ttywidth) - BAROVERHEAD;
876 	if (barlength > 0) {
877 		i = barlength * ratio / 100;
878 		len += snprintf(buf + len, BUFLEFT,
879 		    "|%.*s%*s|", i, stars, barlength - i, "");
880 	}
881 
882 	abbrevsize = cursize;
883 	for (i = 0; abbrevsize >= 100000 && i < sizeof(prefixes); i++)
884 		abbrevsize >>= 10;
885 	len += snprintf(buf + len, BUFLEFT,
886 #ifndef NO_QUAD
887 	    " %5lld %c%c ", (long long)abbrevsize,
888 #else
889 	    " %5ld %c%c ", (long)abbrevsize,
890 #endif
891 	    prefixes[i],
892 	    i == 0 ? ' ' : 'B');
893 
894 	timersub(&now, &start, &td);
895 	elapsed = td.tv_sec + (td.tv_usec / 1000000.0);
896 
897 	bytespersec = 0;
898 	if (bytes > 0) {
899 		bytespersec = bytes;
900 		if (elapsed > 0.0)
901 			bytespersec /= elapsed;
902 	}
903 	for (i = 1; bytespersec >= 1024000 && i < sizeof(prefixes); i++)
904 		bytespersec >>= 10;
905 	len += snprintf(buf + len, BUFLEFT,
906 #ifndef NO_QUAD
907 	    " %3lld.%02d %cB/s ", (long long)bytespersec / 1024,
908 #else
909 	    " %3ld.%02d %cB/s ", (long)bytespersec / 1024,
910 #endif
911 	    (int)((bytespersec % 1024) * 100 / 1024),
912 	    prefixes[i]);
913 
914 	if (bytes <= 0 || elapsed <= 0.0 || cursize > filesize) {
915 		len += snprintf(buf + len, BUFLEFT, "   --:-- ETA");
916 	} else if (wait.tv_sec >= STALLTIME) {
917 		len += snprintf(buf + len, BUFLEFT, " - stalled -");
918 	} else {
919 		remaining = (int)
920 		    ((filesize - restart_point) / (bytes / elapsed) - elapsed);
921 		if (remaining >= 100 * SECSPERHOUR)
922 			len += snprintf(buf + len, BUFLEFT, "   --:-- ETA");
923 		else {
924 			i = remaining / SECSPERHOUR;
925 			if (i)
926 				len += snprintf(buf + len, BUFLEFT, "%2d:", i);
927 			else
928 				len += snprintf(buf + len, BUFLEFT, "   ");
929 			i = remaining % SECSPERHOUR;
930 			len += snprintf(buf + len, BUFLEFT,
931 			    "%02d:%02d ETA", i / 60, i % 60);
932 		}
933 	}
934 	if (flag == 1)
935 		len += snprintf(buf + len, BUFLEFT, "\n");
936 	(void)write(fileno(ttyout), buf, len);
937 
938 	if (flag == -1) {
939 		(void)xsignal_restart(SIGALRM, updateprogressmeter, 1);
940 		alarmtimer(1);		/* set alarm timer for 1 Hz */
941 	} else if (flag == 1) {
942 		(void)xsignal(SIGALRM, SIG_DFL);
943 		alarmtimer(0);
944 	}
945 #endif	/* !NO_PROGRESS */
946 }
947 
948 /*
949  * Display transfer statistics.
950  * Requires start to be initialised by progressmeter(-1),
951  * direction to be defined by xfer routines, and filesize and bytes
952  * to be updated by xfer routines
953  * If siginfo is nonzero, an ETA is displayed, and the output goes to stderr
954  * instead of ttyout.
955  */
956 void
957 ptransfer(siginfo)
958 	int siginfo;
959 {
960 	struct timeval now, td, wait;
961 	double elapsed;
962 	off_t bytespersec;
963 	int remaining, hh, i, len;
964 
965 	char buf[256];		/* Work variable for transfer status. */
966 
967 	if (!verbose && !progress && !siginfo)
968 		return;
969 
970 	(void)gettimeofday(&now, NULL);
971 	timersub(&now, &start, &td);
972 	elapsed = td.tv_sec + (td.tv_usec / 1000000.0);
973 	bytespersec = 0;
974 	if (bytes > 0) {
975 		bytespersec = bytes;
976 		if (elapsed > 0.0)
977 			bytespersec /= elapsed;
978 	}
979 	len = 0;
980 	len += snprintf(buf + len, BUFLEFT,
981 #ifndef NO_QUAD
982 	    "%lld byte%s %s in ", (long long)bytes,
983 #else
984 	    "%ld byte%s %s in ", (long)bytes,
985 #endif
986 	    bytes == 1 ? "" : "s", direction);
987 	remaining = (int)elapsed;
988 	if (remaining > SECSPERDAY) {
989 		int days;
990 
991 		days = remaining / SECSPERDAY;
992 		remaining %= SECSPERDAY;
993 		len += snprintf(buf + len, BUFLEFT,
994 		    "%d day%s ", days, days == 1 ? "" : "s");
995 	}
996 	hh = remaining / SECSPERHOUR;
997 	remaining %= SECSPERHOUR;
998 	if (hh)
999 		len += snprintf(buf + len, BUFLEFT, "%2d:", hh);
1000 	len += snprintf(buf + len, BUFLEFT,
1001 	    "%02d:%02d ", remaining / 60, remaining % 60);
1002 
1003 	for (i = 1; bytespersec >= 1024000 && i < sizeof(prefixes); i++)
1004 		bytespersec >>= 10;
1005 	len += snprintf(buf + len, BUFLEFT,
1006 #ifndef NO_QUAD
1007 	    "(%lld.%02d %cB/s)", (long long)bytespersec / 1024,
1008 #else
1009 	    "(%ld.%02d %cB/s)", (long)bytespersec / 1024,
1010 #endif
1011 	    (int)((bytespersec % 1024) * 100 / 1024),
1012 	    prefixes[i]);
1013 
1014 	if (siginfo && bytes > 0 && elapsed > 0.0 && filesize >= 0
1015 	    && bytes + restart_point <= filesize) {
1016 		remaining = (int)((filesize - restart_point) /
1017 				  (bytes / elapsed) - elapsed);
1018 		hh = remaining / SECSPERHOUR;
1019 		remaining %= SECSPERHOUR;
1020 		len += snprintf(buf + len, BUFLEFT, "  ETA: ");
1021 		if (hh)
1022 			len += snprintf(buf + len, BUFLEFT, "%2d:", hh);
1023 		len += snprintf(buf + len, BUFLEFT, "%02d:%02d",
1024 		    remaining / 60, remaining % 60);
1025 		timersub(&now, &lastupdate, &wait);
1026 		if (wait.tv_sec >= STALLTIME)
1027 			len += snprintf(buf + len, BUFLEFT, "  (stalled)");
1028 	}
1029 	len += snprintf(buf + len, BUFLEFT, "\n");
1030 	(void)write(siginfo ? STDERR_FILENO : fileno(ttyout), buf, len);
1031 }
1032 
1033 /*
1034  * SIG{INFO,QUIT} handler to print transfer stats if a transfer is in progress
1035  */
1036 void
1037 psummary(notused)
1038 	int notused;
1039 {
1040 	int oerrno = errno;
1041 
1042 	if (bytes > 0) {
1043 		if (fromatty)
1044 			write(fileno(ttyout), "\n", 1);
1045 		ptransfer(1);
1046 	}
1047 	errno = oerrno;
1048 }
1049 
1050 /*
1051  * List words in stringlist, vertically arranged
1052  */
1053 void
1054 list_vertical(sl)
1055 	StringList *sl;
1056 {
1057 	int i, j, w;
1058 	int columns, width, lines, items;
1059 	char *p;
1060 
1061 	width = items = 0;
1062 
1063 	for (i = 0 ; i < sl->sl_cur ; i++) {
1064 		w = strlen(sl->sl_str[i]);
1065 		if (w > width)
1066 			width = w;
1067 	}
1068 	width = (width + 8) &~ 7;
1069 
1070 	columns = ttywidth / width;
1071 	if (columns == 0)
1072 		columns = 1;
1073 	lines = (sl->sl_cur + columns - 1) / columns;
1074 	for (i = 0; i < lines; i++) {
1075 		for (j = 0; j < columns; j++) {
1076 			p = sl->sl_str[j * lines + i];
1077 			if (p)
1078 				fputs(p, ttyout);
1079 			if (j * lines + i + lines >= sl->sl_cur) {
1080 				putc('\n', ttyout);
1081 				break;
1082 			}
1083 			w = strlen(p);
1084 			while (w < width) {
1085 				w = (w + 8) &~ 7;
1086 				(void)putc('\t', ttyout);
1087 			}
1088 		}
1089 	}
1090 }
1091 
1092 /*
1093  * Update the global ttywidth value, using TIOCGWINSZ.
1094  */
1095 void
1096 setttywidth(a)
1097 	int a;
1098 {
1099 	struct winsize winsize;
1100 	int oerrno = errno;
1101 
1102 	if (ioctl(fileno(ttyout), TIOCGWINSZ, &winsize) != -1 &&
1103 	    winsize.ws_col != 0)
1104 		ttywidth = winsize.ws_col;
1105 	else
1106 		ttywidth = 80;
1107 	errno = oerrno;
1108 }
1109 
1110 /*
1111  * Change the rate limit up (SIGUSR1) or down (SIGUSR2)
1112  */
1113 void
1114 crankrate(sig)
1115 	int sig;
1116 {
1117 
1118 	switch (sig) {
1119 	case SIGUSR1:
1120 		if (rate_get)
1121 			rate_get += rate_get_incr;
1122 		if (rate_put)
1123 			rate_put += rate_put_incr;
1124 		break;
1125 	case SIGUSR2:
1126 		if (rate_get && rate_get > rate_get_incr)
1127 			rate_get -= rate_get_incr;
1128 		if (rate_put && rate_put > rate_put_incr)
1129 			rate_put -= rate_put_incr;
1130 		break;
1131 	default:
1132 		err(1, "crankrate invoked with unknown signal: %d", sig);
1133 	}
1134 }
1135 
1136 
1137 /*
1138  * Set the SIGALRM interval timer for wait seconds, 0 to disable.
1139  */
1140 void
1141 alarmtimer(wait)
1142 	int wait;
1143 {
1144 	struct itimerval itv;
1145 
1146 	itv.it_value.tv_sec = wait;
1147 	itv.it_value.tv_usec = 0;
1148 	itv.it_interval = itv.it_value;
1149 	setitimer(ITIMER_REAL, &itv, NULL);
1150 }
1151 
1152 /*
1153  * Setup or cleanup EditLine structures
1154  */
1155 #ifndef NO_EDITCOMPLETE
1156 void
1157 controlediting()
1158 {
1159 	if (editing && el == NULL && hist == NULL) {
1160 		HistEvent ev;
1161 		int editmode;
1162 
1163 		el = el_init(__progname, stdin, ttyout, stderr);
1164 		/* init editline */
1165 		hist = history_init();		/* init the builtin history */
1166 		history(hist, &ev, H_SETSIZE, 100);/* remember 100 events */
1167 		el_set(el, EL_HIST, history, hist);	/* use history */
1168 
1169 		el_set(el, EL_EDITOR, "emacs");	/* default editor is emacs */
1170 		el_set(el, EL_PROMPT, prompt);	/* set the prompt functions */
1171 		el_set(el, EL_RPROMPT, rprompt);
1172 
1173 		/* add local file completion, bind to TAB */
1174 		el_set(el, EL_ADDFN, "ftp-complete",
1175 		    "Context sensitive argument completion",
1176 		    complete);
1177 		el_set(el, EL_BIND, "^I", "ftp-complete", NULL);
1178 		el_source(el, NULL);	/* read ~/.editrc */
1179 		if ((el_get(el, EL_EDITMODE, &editmode) != -1) && editmode == 0)
1180 			editing = 0;	/* the user doesn't want editing,
1181 					 * so disable, and let statement
1182 					 * below cleanup */
1183 		else
1184 			el_set(el, EL_SIGNAL, 1);
1185 	}
1186 	if (!editing) {
1187 		if (hist) {
1188 			history_end(hist);
1189 			hist = NULL;
1190 		}
1191 		if (el) {
1192 			el_end(el);
1193 			el = NULL;
1194 		}
1195 	}
1196 }
1197 #endif /* !NO_EDITCOMPLETE */
1198 
1199 /*
1200  * Convert the string `arg' to an int, which may have an optional SI suffix
1201  * (`b', `k', `m', `g'). Returns the number for success, -1 otherwise.
1202  */
1203 int
1204 strsuftoi(arg)
1205 	const char *arg;
1206 {
1207 	char *cp;
1208 	long val;
1209 
1210 	if (!isdigit((unsigned char)arg[0]))
1211 		return (-1);
1212 
1213 	val = strtol(arg, &cp, 10);
1214 	if (cp != NULL) {
1215 		if (cp[0] != '\0' && cp[1] != '\0')
1216 			 return (-1);
1217 		switch (tolower((unsigned char)cp[0])) {
1218 		case '\0':
1219 		case 'b':
1220 			break;
1221 		case 'k':
1222 			val <<= 10;
1223 			break;
1224 		case 'm':
1225 			val <<= 20;
1226 			break;
1227 		case 'g':
1228 			val <<= 30;
1229 			break;
1230 		default:
1231 			return (-1);
1232 		}
1233 	}
1234 	if (val < 0 || val > INT_MAX)
1235 		return (-1);
1236 
1237 	return (val);
1238 }
1239 
1240 /*
1241  * Set up socket buffer sizes before a connection is made.
1242  */
1243 void
1244 setupsockbufsize(sock)
1245 	int sock;
1246 {
1247 
1248 	if (setsockopt(sock, SOL_SOCKET, SO_SNDBUF, (void *) &sndbuf_size,
1249 	    sizeof(rcvbuf_size)) < 0)
1250 		warn("unable to set sndbuf size %d", sndbuf_size);
1251 
1252 	if (setsockopt(sock, SOL_SOCKET, SO_RCVBUF, (void *) &rcvbuf_size,
1253 	    sizeof(rcvbuf_size)) < 0)
1254 		warn("unable to set rcvbuf size %d", rcvbuf_size);
1255 }
1256 
1257 /*
1258  * Copy characters from src into dst, \ quoting characters that require it
1259  */
1260 void
1261 ftpvis(dst, dstlen, src, srclen)
1262 	char		*dst;
1263 	size_t		 dstlen;
1264 	const char	*src;
1265 	size_t		 srclen;
1266 {
1267 	int	di, si;
1268 
1269 	for (di = si = 0;
1270 	    src[si] != '\0' && di < dstlen && si < srclen;
1271 	    di++, si++) {
1272 		switch (src[si]) {
1273 		case '\\':
1274 		case ' ':
1275 		case '\t':
1276 		case '\r':
1277 		case '\n':
1278 		case '"':
1279 			dst[di++] = '\\';
1280 			if (di >= dstlen)
1281 				break;
1282 			/* FALLTHROUGH */
1283 		default:
1284 			dst[di] = src[si];
1285 		}
1286 	}
1287 	dst[di] = '\0';
1288 }
1289 
1290 /*
1291  * Copy src into buf (which is len bytes long), expanding % sequences.
1292  */
1293 void
1294 formatbuf(buf, len, src)
1295 	char		*buf;
1296 	size_t		 len;
1297 	const char	*src;
1298 {
1299 	const char	*p;
1300 	char		*p2, *q;
1301 	int		 i, op, updirs, pdirs;
1302 
1303 #define ADDBUF(x) do { \
1304 		if (i >= len - 1) \
1305 			goto endbuf; \
1306 		buf[i++] = (x); \
1307 	} while (0)
1308 
1309 	p = src;
1310 	for (i = 0; *p; p++) {
1311 		if (*p != '%') {
1312 			ADDBUF(*p);
1313 			continue;
1314 		}
1315 		p++;
1316 
1317 		switch (op = *p) {
1318 
1319 		case '/':
1320 		case '.':
1321 		case 'c':
1322 			p2 = connected ? remotepwd : "";
1323 			updirs = pdirs = 0;
1324 
1325 			/* option to determine fixed # of dirs from path */
1326 			if (op == '.' || op == 'c') {
1327 				int skip;
1328 
1329 				q = p2;
1330 				while (*p2)		/* calc # of /'s */
1331 					if (*p2++ == '/')
1332 						updirs++;
1333 				if (p[1] == '0') {	/* print <x> or ... */
1334 					pdirs = 1;
1335 					p++;
1336 				}
1337 				if (p[1] >= '1' && p[1] <= '9') {
1338 							/* calc # to skip  */
1339 					skip = p[1] - '0';
1340 					p++;
1341 				} else
1342 					skip = 1;
1343 
1344 				updirs -= skip;
1345 				while (skip-- > 0) {
1346 					while ((p2 > q) && (*p2 != '/'))
1347 						p2--;	/* back up */
1348 					if (skip && p2 > q)
1349 						p2--;
1350 				}
1351 				if (*p2 == '/' && p2 != q)
1352 					p2++;
1353 			}
1354 
1355 			if (updirs > 0 && pdirs) {
1356 				if (i >= len - 5)
1357 					break;
1358 				if (op == '.') {
1359 					ADDBUF('.');
1360 					ADDBUF('.');
1361 					ADDBUF('.');
1362 				} else {
1363 					ADDBUF('/');
1364 					ADDBUF('<');
1365 					if (updirs > 9) {
1366 						ADDBUF('9');
1367 						ADDBUF('+');
1368 					} else
1369 						ADDBUF('0' + updirs);
1370 					ADDBUF('>');
1371 				}
1372 			}
1373 			for (; *p2; p2++)
1374 				ADDBUF(*p2);
1375 			break;
1376 
1377 		case 'M':
1378 		case 'm':
1379 			for (p2 = connected ? hostname : "-"; *p2; p2++) {
1380 				if (op == 'm' && *p2 == '.')
1381 					break;
1382 				ADDBUF(*p2);
1383 			}
1384 			break;
1385 
1386 		case 'n':
1387 			for (p2 = connected ? username : "-"; *p2 ; p2++)
1388 				ADDBUF(*p2);
1389 			break;
1390 
1391 		case '%':
1392 			ADDBUF('%');
1393 			break;
1394 
1395 		default:		/* display unknown codes literally */
1396 			ADDBUF('%');
1397 			ADDBUF(op);
1398 			break;
1399 
1400 		}
1401 	}
1402  endbuf:
1403 	buf[i] = '\0';
1404 }
1405 
1406 /*
1407  * Determine if given string is an IPv6 address or not.
1408  * Return 1 for yes, 0 for no
1409  */
1410 int
1411 isipv6addr(addr)
1412 	const char *addr;
1413 {
1414 	int rv = 0;
1415 #ifdef INET6
1416 	struct sockaddr_in6 su_sin6;
1417 
1418 	rv = inet_pton(AF_INET6, addr, &su_sin6.sin6_addr);
1419 	if (debug)
1420 		fprintf(ttyout, "isipv6addr: got %d for %s\n", rv, addr);
1421 #endif
1422 	return (rv == 1) ? 1 : 0;
1423 }
1424 
1425 
1426 /*
1427  * Internal version of connect(2); sets socket buffer sizes first.
1428  */
1429 int
1430 xconnect(sock, name, namelen)
1431 	int sock;
1432 	const struct sockaddr *name;
1433 	int namelen;
1434 {
1435 
1436 	setupsockbufsize(sock);
1437 	return (connect(sock, name, namelen));
1438 }
1439 
1440 /*
1441  * Internal version of listen(2); sets socket buffer sizes first.
1442  */
1443 int
1444 xlisten(sock, backlog)
1445 	int sock, backlog;
1446 {
1447 
1448 	setupsockbufsize(sock);
1449 	return (listen(sock, backlog));
1450 }
1451 
1452 /*
1453  * malloc() with inbuilt error checking
1454  */
1455 void *
1456 xmalloc(size)
1457 	size_t size;
1458 {
1459 	void *p;
1460 
1461 	p = malloc(size);
1462 	if (p == NULL)
1463 		err(1, "Unable to allocate %ld bytes of memory", (long)size);
1464 	return (p);
1465 }
1466 
1467 /*
1468  * sl_init() with inbuilt error checking
1469  */
1470 StringList *
1471 xsl_init()
1472 {
1473 	StringList *p;
1474 
1475 	p = sl_init();
1476 	if (p == NULL)
1477 		err(1, "Unable to allocate memory for stringlist");
1478 	return (p);
1479 }
1480 
1481 /*
1482  * sl_add() with inbuilt error checking
1483  */
1484 void
1485 xsl_add(sl, i)
1486 	StringList	*sl;
1487 	char		*i;
1488 {
1489 
1490 	if (sl_add(sl, i) == -1)
1491 		err(1, "Unable to add `%s' to stringlist", i);
1492 }
1493 
1494 /*
1495  * strdup() with inbuilt error checking
1496  */
1497 char *
1498 xstrdup(str)
1499 	const char *str;
1500 {
1501 	char *s;
1502 
1503 	if (str == NULL)
1504 		errx(1, "xstrdup() called with NULL argument");
1505 	s = strdup(str);
1506 	if (s == NULL)
1507 		err(1, "Unable to allocate memory for string copy");
1508 	return (s);
1509 }
1510 
1511 /*
1512  * Install a POSIX signal handler, allowing the invoker to set whether
1513  * the signal should be restartable or not
1514  */
1515 sigfunc
1516 xsignal_restart(sig, func, restartable)
1517 	int sig;
1518 	sigfunc func;
1519 	int restartable;
1520 {
1521 	struct sigaction act, oact;
1522 	act.sa_handler = func;
1523 
1524 	sigemptyset(&act.sa_mask);
1525 #if defined(SA_RESTART)			/* 4.4BSD, Posix(?), SVR4 */
1526 	act.sa_flags = restartable ? SA_RESTART : 0;
1527 #elif defined(SA_INTERRUPT)		/* SunOS 4.x */
1528 	act.sa_flags = restartable ? 0 : SA_INTERRUPT;
1529 #else
1530 #error "system must have SA_RESTART or SA_INTERRUPT"
1531 #endif
1532 	if (sigaction(sig, &act, &oact) < 0)
1533 		return (SIG_ERR);
1534 	return (oact.sa_handler);
1535 }
1536 
1537 /*
1538  * Install a signal handler with the `restartable' flag set dependent upon
1539  * which signal is being set. (This is a wrapper to xsignal_restart())
1540  */
1541 sigfunc
1542 xsignal(sig, func)
1543 	int sig;
1544 	sigfunc func;
1545 {
1546 	int restartable;
1547 
1548 	/*
1549 	 * Some signals print output or change the state of the process.
1550 	 * There should be restartable, so that reads and writes are
1551 	 * not affected.  Some signals should cause program flow to change;
1552 	 * these signals should not be restartable, so that the system call
1553 	 * will return with EINTR, and the program will go do something
1554 	 * different.  If the signal handler calls longjmp() or siglongjmp(),
1555 	 * it doesn't matter if it's restartable.
1556 	 */
1557 
1558 	switch(sig) {
1559 #ifdef SIGINFO
1560 	case SIGINFO:
1561 #endif
1562 	case SIGQUIT:
1563 	case SIGUSR1:
1564 	case SIGUSR2:
1565 	case SIGWINCH:
1566 		restartable = 1;
1567 		break;
1568 
1569 	case SIGALRM:
1570 	case SIGINT:
1571 	case SIGPIPE:
1572 		restartable = 0;
1573 		break;
1574 
1575 	default:
1576 		/*
1577 		 * This is unpleasant, but I don't know what would be better.
1578 		 * Right now, this "can't happen"
1579 		 */
1580 		errx(1, "xsignal_restart called with signal %d", sig);
1581 	}
1582 
1583 	return(xsignal_restart(sig, func, restartable));
1584 }
1585