xref: /netbsd-src/usr.bin/ftp/util.c (revision d710132b4b8ce7f7cccaaf660cb16aa16b4077a0)
1 /*	$NetBSD: util.c,v 1.112 2003/06/15 13:49:46 lukem Exp $	*/
2 
3 /*-
4  * Copyright (c) 1997-2003 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.112 2003/06/15 13:49:46 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 <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 
804 /*
805  * List words in stringlist, vertically arranged
806  */
807 void
808 list_vertical(StringList *sl)
809 {
810 	int i, j, w;
811 	int columns, width, lines;
812 	char *p;
813 
814 	width = 0;
815 
816 	for (i = 0 ; i < sl->sl_cur ; i++) {
817 		w = strlen(sl->sl_str[i]);
818 		if (w > width)
819 			width = w;
820 	}
821 	width = (width + 8) &~ 7;
822 
823 	columns = ttywidth / width;
824 	if (columns == 0)
825 		columns = 1;
826 	lines = (sl->sl_cur + columns - 1) / columns;
827 	for (i = 0; i < lines; i++) {
828 		for (j = 0; j < columns; j++) {
829 			p = sl->sl_str[j * lines + i];
830 			if (p)
831 				fputs(p, ttyout);
832 			if (j * lines + i + lines >= sl->sl_cur) {
833 				putc('\n', ttyout);
834 				break;
835 			}
836 			w = strlen(p);
837 			while (w < width) {
838 				w = (w + 8) &~ 7;
839 				(void)putc('\t', ttyout);
840 			}
841 		}
842 	}
843 }
844 
845 /*
846  * Update the global ttywidth value, using TIOCGWINSZ.
847  */
848 void
849 setttywidth(int a)
850 {
851 	struct winsize winsize;
852 	int oerrno = errno;
853 
854 	if (ioctl(fileno(ttyout), TIOCGWINSZ, &winsize) != -1 &&
855 	    winsize.ws_col != 0)
856 		ttywidth = winsize.ws_col;
857 	else
858 		ttywidth = 80;
859 	errno = oerrno;
860 }
861 
862 /*
863  * Change the rate limit up (SIGUSR1) or down (SIGUSR2)
864  */
865 void
866 crankrate(int sig)
867 {
868 
869 	switch (sig) {
870 	case SIGUSR1:
871 		if (rate_get)
872 			rate_get += rate_get_incr;
873 		if (rate_put)
874 			rate_put += rate_put_incr;
875 		break;
876 	case SIGUSR2:
877 		if (rate_get && rate_get > rate_get_incr)
878 			rate_get -= rate_get_incr;
879 		if (rate_put && rate_put > rate_put_incr)
880 			rate_put -= rate_put_incr;
881 		break;
882 	default:
883 		err(1, "crankrate invoked with unknown signal: %d", sig);
884 	}
885 }
886 
887 
888 /*
889  * Setup or cleanup EditLine structures
890  */
891 #ifndef NO_EDITCOMPLETE
892 void
893 controlediting(void)
894 {
895 	if (editing && el == NULL && hist == NULL) {
896 		HistEvent ev;
897 		int editmode;
898 
899 		el = el_init(getprogname(), stdin, ttyout, stderr);
900 		/* init editline */
901 		hist = history_init();		/* init the builtin history */
902 		history(hist, &ev, H_SETSIZE, 100);/* remember 100 events */
903 		el_set(el, EL_HIST, history, hist);	/* use history */
904 
905 		el_set(el, EL_EDITOR, "emacs");	/* default editor is emacs */
906 		el_set(el, EL_PROMPT, prompt);	/* set the prompt functions */
907 		el_set(el, EL_RPROMPT, rprompt);
908 
909 		/* add local file completion, bind to TAB */
910 		el_set(el, EL_ADDFN, "ftp-complete",
911 		    "Context sensitive argument completion",
912 		    complete);
913 		el_set(el, EL_BIND, "^I", "ftp-complete", NULL);
914 		el_source(el, NULL);	/* read ~/.editrc */
915 		if ((el_get(el, EL_EDITMODE, &editmode) != -1) && editmode == 0)
916 			editing = 0;	/* the user doesn't want editing,
917 					 * so disable, and let statement
918 					 * below cleanup */
919 		else
920 			el_set(el, EL_SIGNAL, 1);
921 	}
922 	if (!editing) {
923 		if (hist) {
924 			history_end(hist);
925 			hist = NULL;
926 		}
927 		if (el) {
928 			el_end(el);
929 			el = NULL;
930 		}
931 	}
932 }
933 #endif /* !NO_EDITCOMPLETE */
934 
935 /*
936  * Convert the string `arg' to an int, which may have an optional SI suffix
937  * (`b', `k', `m', `g'). Returns the number for success, -1 otherwise.
938  */
939 int
940 strsuftoi(const char *arg)
941 {
942 	char *cp;
943 	long val;
944 
945 	if (!isdigit((unsigned char)arg[0]))
946 		return (-1);
947 
948 	val = strtol(arg, &cp, 10);
949 	if (cp != NULL) {
950 		if (cp[0] != '\0' && cp[1] != '\0')
951 			 return (-1);
952 		switch (tolower((unsigned char)cp[0])) {
953 		case '\0':
954 		case 'b':
955 			break;
956 		case 'k':
957 			val <<= 10;
958 			break;
959 		case 'm':
960 			val <<= 20;
961 			break;
962 		case 'g':
963 			val <<= 30;
964 			break;
965 		default:
966 			return (-1);
967 		}
968 	}
969 	if (val < 0 || val > INT_MAX)
970 		return (-1);
971 
972 	return (val);
973 }
974 
975 /*
976  * Set up socket buffer sizes before a connection is made.
977  */
978 void
979 setupsockbufsize(int sock)
980 {
981 
982 	if (setsockopt(sock, SOL_SOCKET, SO_SNDBUF, (void *) &sndbuf_size,
983 	    sizeof(rcvbuf_size)) < 0)
984 		warn("unable to set sndbuf size %d", sndbuf_size);
985 
986 	if (setsockopt(sock, SOL_SOCKET, SO_RCVBUF, (void *) &rcvbuf_size,
987 	    sizeof(rcvbuf_size)) < 0)
988 		warn("unable to set rcvbuf size %d", rcvbuf_size);
989 }
990 
991 /*
992  * Copy characters from src into dst, \ quoting characters that require it
993  */
994 void
995 ftpvis(char *dst, size_t dstlen, const char *src, size_t srclen)
996 {
997 	int	di, si;
998 
999 	for (di = si = 0;
1000 	    src[si] != '\0' && di < dstlen && si < srclen;
1001 	    di++, si++) {
1002 		switch (src[si]) {
1003 		case '\\':
1004 		case ' ':
1005 		case '\t':
1006 		case '\r':
1007 		case '\n':
1008 		case '"':
1009 			dst[di++] = '\\';
1010 			if (di >= dstlen)
1011 				break;
1012 			/* FALLTHROUGH */
1013 		default:
1014 			dst[di] = src[si];
1015 		}
1016 	}
1017 	dst[di] = '\0';
1018 }
1019 
1020 /*
1021  * Copy src into buf (which is len bytes long), expanding % sequences.
1022  */
1023 void
1024 formatbuf(char *buf, size_t len, const char *src)
1025 {
1026 	const char	*p;
1027 	char		*p2, *q;
1028 	int		 i, op, updirs, pdirs;
1029 
1030 #define ADDBUF(x) do { \
1031 		if (i >= len - 1) \
1032 			goto endbuf; \
1033 		buf[i++] = (x); \
1034 	} while (0)
1035 
1036 	p = src;
1037 	for (i = 0; *p; p++) {
1038 		if (*p != '%') {
1039 			ADDBUF(*p);
1040 			continue;
1041 		}
1042 		p++;
1043 
1044 		switch (op = *p) {
1045 
1046 		case '/':
1047 		case '.':
1048 		case 'c':
1049 			p2 = connected ? remotepwd : "";
1050 			updirs = pdirs = 0;
1051 
1052 			/* option to determine fixed # of dirs from path */
1053 			if (op == '.' || op == 'c') {
1054 				int skip;
1055 
1056 				q = p2;
1057 				while (*p2)		/* calc # of /'s */
1058 					if (*p2++ == '/')
1059 						updirs++;
1060 				if (p[1] == '0') {	/* print <x> or ... */
1061 					pdirs = 1;
1062 					p++;
1063 				}
1064 				if (p[1] >= '1' && p[1] <= '9') {
1065 							/* calc # to skip  */
1066 					skip = p[1] - '0';
1067 					p++;
1068 				} else
1069 					skip = 1;
1070 
1071 				updirs -= skip;
1072 				while (skip-- > 0) {
1073 					while ((p2 > q) && (*p2 != '/'))
1074 						p2--;	/* back up */
1075 					if (skip && p2 > q)
1076 						p2--;
1077 				}
1078 				if (*p2 == '/' && p2 != q)
1079 					p2++;
1080 			}
1081 
1082 			if (updirs > 0 && pdirs) {
1083 				if (i >= len - 5)
1084 					break;
1085 				if (op == '.') {
1086 					ADDBUF('.');
1087 					ADDBUF('.');
1088 					ADDBUF('.');
1089 				} else {
1090 					ADDBUF('/');
1091 					ADDBUF('<');
1092 					if (updirs > 9) {
1093 						ADDBUF('9');
1094 						ADDBUF('+');
1095 					} else
1096 						ADDBUF('0' + updirs);
1097 					ADDBUF('>');
1098 				}
1099 			}
1100 			for (; *p2; p2++)
1101 				ADDBUF(*p2);
1102 			break;
1103 
1104 		case 'M':
1105 		case 'm':
1106 			for (p2 = connected && username ? username : "-";
1107 			    *p2 ; p2++) {
1108 				if (op == 'm' && *p2 == '.')
1109 					break;
1110 				ADDBUF(*p2);
1111 			}
1112 			break;
1113 
1114 		case 'n':
1115 			for (p2 = connected ? username : "-"; *p2 ; p2++)
1116 				ADDBUF(*p2);
1117 			break;
1118 
1119 		case '%':
1120 			ADDBUF('%');
1121 			break;
1122 
1123 		default:		/* display unknown codes literally */
1124 			ADDBUF('%');
1125 			ADDBUF(op);
1126 			break;
1127 
1128 		}
1129 	}
1130  endbuf:
1131 	buf[i] = '\0';
1132 }
1133 
1134 /*
1135  * Parse `port' into a TCP port number, defaulting to `defport' if `port' is
1136  * an unknown service name. If defport != -1, print a warning upon bad parse.
1137  */
1138 int
1139 parseport(const char *port, int defport)
1140 {
1141 	int	 rv;
1142 	long	 nport;
1143 	char	*p, *ep;
1144 
1145 	p = xstrdup(port);
1146 	nport = strtol(p, &ep, 10);
1147 	if (*ep != '\0' && ep == p) {
1148 		struct servent	*svp;
1149 
1150 		svp = getservbyname(port, "tcp");
1151 		if (svp == NULL) {
1152  badparseport:
1153 			if (defport != -1)
1154 				warnx("Unknown port `%s', using port %d",
1155 				    port, defport);
1156 			rv = defport;
1157 		} else
1158 			rv = ntohs(svp->s_port);
1159 	} else if (nport < 1 || nport > MAX_IN_PORT_T || *ep != '\0')
1160 		goto badparseport;
1161 	else
1162 		rv = nport;
1163 	free(p);
1164 	return (rv);
1165 }
1166 
1167 /*
1168  * Determine if given string is an IPv6 address or not.
1169  * Return 1 for yes, 0 for no
1170  */
1171 int
1172 isipv6addr(const char *addr)
1173 {
1174 	int rv = 0;
1175 #ifdef INET6
1176 	struct addrinfo hints, *res;
1177 
1178 	memset(&hints, 0, sizeof(hints));
1179 	hints.ai_family = PF_INET6;
1180 	hints.ai_socktype = SOCK_DGRAM;	/*dummy*/
1181 	hints.ai_flags = AI_NUMERICHOST;
1182 	if (getaddrinfo(addr, "0", &hints, &res) != 0)
1183 		rv = 0;
1184 	else {
1185 		rv = 1;
1186 		freeaddrinfo(res);
1187 	}
1188 	if (debug)
1189 		fprintf(ttyout, "isipv6addr: got %d for %s\n", rv, addr);
1190 #endif
1191 	return (rv == 1) ? 1 : 0;
1192 }
1193 
1194 
1195 /*
1196  * Internal version of connect(2); sets socket buffer sizes first.
1197  */
1198 int
1199 xconnect(int sock, const struct sockaddr *name, int namelen)
1200 {
1201 
1202 	setupsockbufsize(sock);
1203 	return (connect(sock, name, namelen));
1204 }
1205 
1206 /*
1207  * Internal version of listen(2); sets socket buffer sizes first.
1208  */
1209 int
1210 xlisten(int sock, int backlog)
1211 {
1212 
1213 	setupsockbufsize(sock);
1214 	return (listen(sock, backlog));
1215 }
1216 
1217 /*
1218  * malloc() with inbuilt error checking
1219  */
1220 void *
1221 xmalloc(size_t size)
1222 {
1223 	void *p;
1224 
1225 	p = malloc(size);
1226 	if (p == NULL)
1227 		err(1, "Unable to allocate %ld bytes of memory", (long)size);
1228 	return (p);
1229 }
1230 
1231 /*
1232  * sl_init() with inbuilt error checking
1233  */
1234 StringList *
1235 xsl_init(void)
1236 {
1237 	StringList *p;
1238 
1239 	p = sl_init();
1240 	if (p == NULL)
1241 		err(1, "Unable to allocate memory for stringlist");
1242 	return (p);
1243 }
1244 
1245 /*
1246  * sl_add() with inbuilt error checking
1247  */
1248 void
1249 xsl_add(StringList *sl, char *i)
1250 {
1251 
1252 	if (sl_add(sl, i) == -1)
1253 		err(1, "Unable to add `%s' to stringlist", i);
1254 }
1255 
1256 /*
1257  * strdup() with inbuilt error checking
1258  */
1259 char *
1260 xstrdup(const char *str)
1261 {
1262 	char *s;
1263 
1264 	if (str == NULL)
1265 		errx(1, "xstrdup() called with NULL argument");
1266 	s = strdup(str);
1267 	if (s == NULL)
1268 		err(1, "Unable to allocate memory for string copy");
1269 	return (s);
1270 }
1271