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