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