util.c revision 116424
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 <unistd.h>
105
106#include "ftp_var.h"
107
108#define TM_YEAR_BASE	1900
109
110/*
111 * Connect to peer server and auto-login, if possible.
112 */
113void
114setpeer(int argc, char *argv[])
115{
116	char *host;
117	char *port;
118
119	if (argc == 0)
120		goto usage;
121	if (connected) {
122		fprintf(ttyout, "Already connected to %s, use close first.\n",
123		    hostname);
124		code = -1;
125		return;
126	}
127	if (argc < 2)
128		(void)another(&argc, &argv, "to");
129	if (argc < 2 || argc > 3) {
130 usage:
131		fprintf(ttyout, "usage: %s host-name [port]\n", argv[0]);
132		code = -1;
133		return;
134	}
135	if (gatemode)
136		port = gateport;
137	else
138		port = ftpport;
139	if (argc > 2)
140		port = argv[2];
141
142	if (gatemode) {
143		if (gateserver == NULL || *gateserver == '\0')
144			errx(1, "gateserver not defined (shouldn't happen)");
145		host = hookup(gateserver, port);
146	} else
147		host = hookup(argv[1], port);
148
149	if (host) {
150		if (gatemode && verbose) {
151			fprintf(ttyout,
152			    "Connecting via pass-through server %s\n",
153			    gateserver);
154		}
155
156		connected = 1;
157		/*
158		 * Set up defaults for FTP.
159		 */
160		(void)strlcpy(typename, "ascii", sizeof(typename));
161		type = TYPE_A;
162		curtype = TYPE_A;
163		(void)strlcpy(formname, "non-print", sizeof(formname));
164		form = FORM_N;
165		(void)strlcpy(modename, "stream", sizeof(modename));
166		mode = MODE_S;
167		(void)strlcpy(structname, "file", sizeof(structname));
168		stru = STRU_F;
169		(void)strlcpy(bytename, "8", sizeof(bytename));
170		bytesize = 8;
171		if (autologin)
172			(void)ftp_login(argv[1], NULL, NULL);
173	}
174}
175
176static void
177parse_feat(const char *line)
178{
179
180	if (strcasecmp(line, " MDTM") == 0)
181		features[FEAT_MDTM] = 1;
182	else if (strncasecmp(line, " MLST", sizeof(" MLST") - 1) == 0) {
183		features[FEAT_MLST] = 1;
184	} else if (strcasecmp(line, " REST STREAM") == 0)
185		features[FEAT_REST_STREAM] = 1;
186	else if (strcasecmp(line, " SIZE") == 0)
187		features[FEAT_SIZE] = 1;
188	else if (strcasecmp(line, " TVFS") == 0)
189		features[FEAT_TVFS] = 1;
190}
191
192/*
193 * Determine the remote system type (SYST) and features (FEAT).
194 * Call after a successful login (i.e, connected = -1)
195 */
196void
197getremoteinfo(void)
198{
199	int overbose, i;
200
201	overbose = verbose;
202	if (debug == 0)
203		verbose = -1;
204
205			/* determine remote system type */
206	if (command("SYST") == COMPLETE) {
207		if (overbose) {
208			char *cp, c;
209
210			c = 0;
211			cp = strchr(reply_string + 4, ' ');
212			if (cp == NULL)
213				cp = strchr(reply_string + 4, '\r');
214			if (cp) {
215				if (cp[-1] == '.')
216					cp--;
217				c = *cp;
218				*cp = '\0';
219			}
220
221			fprintf(ttyout, "Remote system type is %s.\n",
222			    reply_string + 4);
223			if (cp)
224				*cp = c;
225		}
226		if (!strncmp(reply_string, "215 UNIX Type: L8", 17)) {
227			if (proxy)
228				unix_proxy = 1;
229			else
230				unix_server = 1;
231			/*
232			 * Set type to 0 (not specified by user),
233			 * meaning binary by default, but don't bother
234			 * telling server.  We can use binary
235			 * for text files unless changed by the user.
236			 */
237			type = 0;
238			(void)strlcpy(typename, "binary", sizeof(typename));
239			if (overbose)
240			    fprintf(ttyout,
241				"Using %s mode to transfer files.\n",
242				typename);
243		} else {
244			if (proxy)
245				unix_proxy = 0;
246			else
247				unix_server = 0;
248			if (overbose &&
249			    !strncmp(reply_string, "215 TOPS20", 10))
250				fputs(
251"Remember to set tenex mode when transferring binary files from this machine.\n",
252				    ttyout);
253		}
254	}
255
256			/* determine features (if any) */
257	for (i = 0; i < FEAT_max; i++)
258		features[i] = -1;
259	reply_callback = parse_feat;
260	if (command("FEAT") == COMPLETE) {
261		for (i = 0; i < FEAT_max; i++) {
262			if (features[i] == -1)
263				features[i] = 0;
264		}
265		features[FEAT_FEAT] = 1;
266	} else
267		features[FEAT_FEAT] = 0;
268	if (debug)
269		for (i = 0; i < FEAT_max; i++)
270			printf("features[%d] = %d\n", i, features[i]);
271	reply_callback = NULL;
272
273	verbose = overbose;
274}
275
276/*
277 * Reset the various variables that indicate connection state back to
278 * disconnected settings.
279 * The caller is responsible for issuing any commands to the remote server
280 * to perform a clean shutdown before this is invoked.
281 */
282void
283cleanuppeer(void)
284{
285
286	if (cout)
287		(void)fclose(cout);
288	cout = NULL;
289	connected = 0;
290	unix_server = 0;
291	unix_proxy = 0;
292			/*
293			 * determine if anonftp was specifically set with -a
294			 * (1), or implicitly set by auto_fetch() (2). in the
295			 * latter case, disable after the current xfer
296			 */
297	if (anonftp == 2)
298		anonftp = 0;
299	data = -1;
300	epsv4bad = 0;
301	if (username)
302		free(username);
303	username = NULL;
304	if (!proxy)
305		macnum = 0;
306}
307
308/*
309 * Top-level signal handler for interrupted commands.
310 */
311void
312intr(int dummy)
313{
314
315	alarmtimer(0);
316	if (fromatty)
317		write(fileno(ttyout), "\n", 1);
318	siglongjmp(toplevel, 1);
319}
320
321/*
322 * Signal handler for lost connections; cleanup various elements of
323 * the connection state, and call cleanuppeer() to finish it off.
324 */
325void
326lostpeer(int dummy)
327{
328	int oerrno = errno;
329
330	alarmtimer(0);
331	if (connected) {
332		if (cout != NULL) {
333			(void)shutdown(fileno(cout), 1+1);
334			(void)fclose(cout);
335			cout = NULL;
336		}
337		if (data >= 0) {
338			(void)shutdown(data, 1+1);
339			(void)close(data);
340			data = -1;
341		}
342		connected = 0;
343	}
344	pswitch(1);
345	if (connected) {
346		if (cout != NULL) {
347			(void)shutdown(fileno(cout), 1+1);
348			(void)fclose(cout);
349			cout = NULL;
350		}
351		connected = 0;
352	}
353	proxflag = 0;
354	pswitch(0);
355	cleanuppeer();
356	errno = oerrno;
357}
358
359
360/*
361 * Login to remote host, using given username & password if supplied.
362 * Return non-zero if successful.
363 */
364int
365ftp_login(const char *host, const char *user, const char *pass)
366{
367	char tmp[80];
368	const char *acct;
369	int n, aflag, rval, freeuser, freepass, freeacct;
370
371	acct = NULL;
372	aflag = rval = freeuser = freepass = freeacct = 0;
373
374	if (debug)
375		fprintf(ttyout, "ftp_login: user `%s' pass `%s' host `%s'\n",
376		    user ? user : "<null>", pass ? pass : "<null>",
377		    host ? host : "<null>");
378
379
380	/*
381	 * Set up arguments for an anonymous FTP session, if necessary.
382	 */
383	if (anonftp) {
384		user = "anonymous";	/* as per RFC 1635 */
385		pass = getoptionvalue("anonpass");
386	}
387
388	if (user == NULL)
389		freeuser = 1;
390	if (pass == NULL)
391		freepass = 1;
392	freeacct = 1;
393	if (ruserpass(host, &user, &pass, &acct) < 0) {
394		code = -1;
395		goto cleanup_ftp_login;
396	}
397
398	while (user == NULL) {
399		if (localname)
400			fprintf(ttyout, "Name (%s:%s): ", host, localname);
401		else
402			fprintf(ttyout, "Name (%s): ", host);
403		*tmp = '\0';
404		if (fgets(tmp, sizeof(tmp) - 1, stdin) == NULL) {
405			fprintf(ttyout, "\nEOF received; login aborted.\n");
406			clearerr(stdin);
407			code = -1;
408			goto cleanup_ftp_login;
409		}
410		tmp[strlen(tmp) - 1] = '\0';
411		freeuser = 0;
412		if (*tmp == '\0')
413			user = localname;
414		else
415			user = tmp;
416	}
417
418	if (gatemode) {
419		char *nuser;
420		int len;
421
422		len = strlen(user) + 1 + strlen(host) + 1;
423		nuser = xmalloc(len);
424		(void)strlcpy(nuser, user, len);
425		(void)strlcat(nuser, "@",  len);
426		(void)strlcat(nuser, host, len);
427		freeuser = 1;
428		user = nuser;
429	}
430
431	n = command("USER %s", user);
432	if (n == CONTINUE) {
433		if (pass == NULL) {
434			freepass = 0;
435			pass = getpass("Password:");
436		}
437		n = command("PASS %s", pass);
438	}
439	if (n == CONTINUE) {
440		aflag++;
441		if (acct == NULL) {
442			freeacct = 0;
443			acct = getpass("Account:");
444		}
445		if (acct[0] == '\0') {
446			warnx("Login failed.");
447			goto cleanup_ftp_login;
448		}
449		n = command("ACCT %s", acct);
450	}
451	if ((n != COMPLETE) ||
452	    (!aflag && acct != NULL && command("ACCT %s", acct) != COMPLETE)) {
453		warnx("Login failed.");
454		goto cleanup_ftp_login;
455	}
456	rval = 1;
457	username = xstrdup(user);
458	if (proxy)
459		goto cleanup_ftp_login;
460
461	connected = -1;
462	getremoteinfo();
463	for (n = 0; n < macnum; ++n) {
464		if (!strcmp("init", macros[n].mac_name)) {
465			(void)strlcpy(line, "$init", sizeof(line));
466			makeargv();
467			domacro(margc, margv);
468			break;
469		}
470	}
471	updateremotepwd();
472
473 cleanup_ftp_login:
474	if (user != NULL && freeuser)
475		free((char *)user);
476	if (pass != NULL && freepass)
477		free((char *)pass);
478	if (acct != NULL && freeacct)
479		free((char *)acct);
480	return (rval);
481}
482
483/*
484 * `another' gets another argument, and stores the new argc and argv.
485 * It reverts to the top level (via intr()) on EOF/error.
486 *
487 * Returns false if no new arguments have been added.
488 */
489int
490another(int *pargc, char ***pargv, const char *prompt)
491{
492	int len = strlen(line), ret;
493
494	if (len >= sizeof(line) - 3) {
495		fputs("sorry, arguments too long.\n", ttyout);
496		intr(0);
497	}
498	fprintf(ttyout, "(%s) ", prompt);
499	line[len++] = ' ';
500	if (fgets(&line[len], sizeof(line) - len, stdin) == NULL) {
501		clearerr(stdin);
502		intr(0);
503	}
504	len += strlen(&line[len]);
505	if (len > 0 && line[len - 1] == '\n')
506		line[len - 1] = '\0';
507	makeargv();
508	ret = margc > *pargc;
509	*pargc = margc;
510	*pargv = margv;
511	return (ret);
512}
513
514/*
515 * glob files given in argv[] from the remote server.
516 * if errbuf isn't NULL, store error messages there instead
517 * of writing to the screen.
518 */
519char *
520remglob(char *argv[], int doswitch, char **errbuf)
521{
522        char temp[MAXPATHLEN];
523        static char buf[MAXPATHLEN];
524        static FILE *ftemp = NULL;
525        static char **args;
526        int oldverbose, oldhash, oldprogress, fd, len;
527        char *cp, *mode;
528
529        if (!mflag || !connected) {
530                if (!doglob)
531                        args = NULL;
532                else {
533                        if (ftemp) {
534                                (void)fclose(ftemp);
535                                ftemp = NULL;
536                        }
537                }
538                return (NULL);
539        }
540        if (!doglob) {
541                if (args == NULL)
542                        args = argv;
543                if ((cp = *++args) == NULL)
544                        args = NULL;
545                return (cp);
546        }
547        if (ftemp == NULL) {
548		len = strlcpy(temp, tmpdir, sizeof(temp));
549		if (temp[len - 1] != '/')
550			(void)strlcat(temp, "/", sizeof(temp));
551		(void)strlcat(temp, TMPFILE, sizeof(temp));
552                if ((fd = mkstemp(temp)) < 0) {
553                        warn("unable to create temporary file %s", temp);
554                        return (NULL);
555                }
556                close(fd);
557                oldverbose = verbose;
558		verbose = (errbuf != NULL) ? -1 : 0;
559                oldhash = hash;
560		oldprogress = progress;
561                hash = 0;
562		progress = 0;
563                if (doswitch)
564                        pswitch(!proxy);
565                for (mode = "w"; *++argv != NULL; mode = "a")
566                        recvrequest("NLST", temp, *argv, mode, 0, 0);
567		if ((code / 100) != COMPLETE) {
568			if (errbuf != NULL)
569				*errbuf = reply_string;
570		}
571                if (doswitch)
572                        pswitch(!proxy);
573                verbose = oldverbose;
574		hash = oldhash;
575		progress = oldprogress;
576                ftemp = fopen(temp, "r");
577                (void)unlink(temp);
578                if (ftemp == NULL) {
579			if (errbuf == NULL)
580				fputs(
581				    "can't find list of remote files, oops.\n",
582				    ttyout);
583			else
584				*errbuf =
585				    "can't find list of remote files, oops.";
586                        return (NULL);
587                }
588        }
589        if (fgets(buf, sizeof(buf), ftemp) == NULL) {
590                (void)fclose(ftemp);
591		ftemp = NULL;
592                return (NULL);
593        }
594        if ((cp = strchr(buf, '\n')) != NULL)
595                *cp = '\0';
596        return (buf);
597}
598
599/*
600 * Glob a local file name specification with the expectation of a single
601 * return value. Can't control multiple values being expanded from the
602 * expression, we return only the first.
603 * Returns NULL on error, or a pointer to a buffer containing the filename
604 * that's the caller's responsiblity to free(3) when finished with.
605 */
606char *
607globulize(const char *pattern)
608{
609	glob_t gl;
610	int flags;
611	char *p;
612
613	if (!doglob)
614		return (xstrdup(pattern));
615
616	flags = GLOB_BRACE|GLOB_NOCHECK|GLOB_TILDE;
617	memset(&gl, 0, sizeof(gl));
618	if (glob(pattern, flags, NULL, &gl) || gl.gl_pathc == 0) {
619		warnx("%s: not found", pattern);
620		globfree(&gl);
621		return (NULL);
622	}
623	p = xstrdup(gl.gl_pathv[0]);
624	globfree(&gl);
625	return (p);
626}
627
628/*
629 * determine size of remote file
630 */
631off_t
632remotesize(const char *file, int noisy)
633{
634	int overbose, r;
635	off_t size;
636
637	overbose = verbose;
638	size = -1;
639	if (debug == 0)
640		verbose = -1;
641	if (! features[FEAT_SIZE]) {
642		if (noisy)
643			fprintf(ttyout,
644			    "SIZE is not supported by remote server.\n");
645		goto cleanup_remotesize;
646	}
647	r = command("SIZE %s", file);
648	if (r == COMPLETE) {
649		char *cp, *ep;
650
651		cp = strchr(reply_string, ' ');
652		if (cp != NULL) {
653			cp++;
654			size = STRTOLL(cp, &ep, 10);
655			if (*ep != '\0' && !isspace((unsigned char)*ep))
656				size = -1;
657		}
658	} else {
659		if (r == ERROR && code == 500 && features[FEAT_SIZE] == -1)
660			features[FEAT_SIZE] = 0;
661		if (noisy && debug == 0) {
662			fputs(reply_string, ttyout);
663			putc('\n', ttyout);
664		}
665	}
666 cleanup_remotesize:
667	verbose = overbose;
668	return (size);
669}
670
671/*
672 * determine last modification time (in GMT) of remote file
673 */
674time_t
675remotemodtime(const char *file, int noisy)
676{
677	int	overbose, ocode, r;
678	time_t	rtime;
679
680	overbose = verbose;
681	ocode = code;
682	rtime = -1;
683	if (debug == 0)
684		verbose = -1;
685	if (! features[FEAT_MDTM]) {
686		if (noisy)
687			fprintf(ttyout,
688			    "MDTM is not supported by remote server.\n");
689		goto cleanup_parse_time;
690	}
691	r = command("MDTM %s", file);
692	if (r == COMPLETE) {
693		struct tm timebuf;
694		char *timestr, *frac;
695		int yy, mo, day, hour, min, sec;
696
697		/*
698		 * time-val = 14DIGIT [ "." 1*DIGIT ]
699		 *		YYYYMMDDHHMMSS[.sss]
700		 * mdtm-response = "213" SP time-val CRLF / error-response
701		 */
702		timestr = reply_string + 4;
703
704					/*
705					 * parse fraction.
706					 * XXX: ignored for now
707					 */
708		frac = strchr(timestr, '\r');
709		if (frac != NULL)
710			*frac = '\0';
711		frac = strchr(timestr, '.');
712		if (frac != NULL)
713			*frac++ = '\0';
714		if (strlen(timestr) == 15 && strncmp(timestr, "191", 3) == 0) {
715			/*
716			 * XXX:	Workaround for lame ftpd's that return
717			 *	`19100' instead of `2000'
718			 */
719			fprintf(ttyout,
720	    "Y2K warning! Incorrect time-val `%s' received from server.\n",
721			    timestr);
722			timestr++;
723			timestr[0] = '2';
724			timestr[1] = '0';
725			fprintf(ttyout, "Converted to `%s'\n", timestr);
726		}
727		if (strlen(timestr) != 14 ||
728		    sscanf(timestr, "%04d%02d%02d%02d%02d%02d",
729			&yy, &mo, &day, &hour, &min, &sec) != 6) {
730 bad_parse_time:
731			fprintf(ttyout, "Can't parse time `%s'.\n", timestr);
732			goto cleanup_parse_time;
733		}
734		memset(&timebuf, 0, sizeof(timebuf));
735		timebuf.tm_sec = sec;
736		timebuf.tm_min = min;
737		timebuf.tm_hour = hour;
738		timebuf.tm_mday = day;
739		timebuf.tm_mon = mo - 1;
740		timebuf.tm_year = yy - TM_YEAR_BASE;
741		timebuf.tm_isdst = -1;
742		rtime = timegm(&timebuf);
743		if (rtime == -1) {
744			if (noisy || debug != 0)
745				goto bad_parse_time;
746			else
747				goto cleanup_parse_time;
748		} else if (debug)
749			fprintf(ttyout, "parsed date as: %s", ctime(&rtime));
750	} else {
751		if (r == ERROR && code == 500 && features[FEAT_MDTM] == -1)
752			features[FEAT_MDTM] = 0;
753		if (noisy && debug == 0) {
754			fputs(reply_string, ttyout);
755			putc('\n', ttyout);
756		}
757	}
758 cleanup_parse_time:
759	verbose = overbose;
760	if (rtime == -1)
761		code = ocode;
762	return (rtime);
763}
764
765/*
766 * update global `remotepwd', which contains the state of the remote cwd
767 */
768void
769updateremotepwd(void)
770{
771	int	 overbose, ocode, i;
772	char	*cp;
773
774	overbose = verbose;
775	ocode = code;
776	if (debug == 0)
777		verbose = -1;
778	if (command("PWD") != COMPLETE)
779		goto badremotepwd;
780	cp = strchr(reply_string, ' ');
781	if (cp == NULL || cp[0] == '\0' || cp[1] != '"')
782		goto badremotepwd;
783	cp += 2;
784	for (i = 0; *cp && i < sizeof(remotepwd) - 1; i++, cp++) {
785		if (cp[0] == '"') {
786			if (cp[1] == '"')
787				cp++;
788			else
789				break;
790		}
791		remotepwd[i] = *cp;
792	}
793	remotepwd[i] = '\0';
794	if (debug)
795		fprintf(ttyout, "got remotepwd as `%s'\n", remotepwd);
796	goto cleanupremotepwd;
797 badremotepwd:
798	remotepwd[0]='\0';
799 cleanupremotepwd:
800	verbose = overbose;
801	code = ocode;
802}
803
804
805/*
806 * List words in stringlist, vertically arranged
807 */
808void
809list_vertical(StringList *sl)
810{
811	int i, j, w;
812	int columns, width, lines;
813	char *p;
814
815	width = 0;
816
817	for (i = 0 ; i < sl->sl_cur ; i++) {
818		w = strlen(sl->sl_str[i]);
819		if (w > width)
820			width = w;
821	}
822	width = (width + 8) &~ 7;
823
824	columns = ttywidth / width;
825	if (columns == 0)
826		columns = 1;
827	lines = (sl->sl_cur + columns - 1) / columns;
828	for (i = 0; i < lines; i++) {
829		for (j = 0; j < columns; j++) {
830			p = sl->sl_str[j * lines + i];
831			if (p)
832				fputs(p, ttyout);
833			if (j * lines + i + lines >= sl->sl_cur) {
834				putc('\n', ttyout);
835				break;
836			}
837			w = strlen(p);
838			while (w < width) {
839				w = (w + 8) &~ 7;
840				(void)putc('\t', ttyout);
841			}
842		}
843	}
844}
845
846/*
847 * Update the global ttywidth value, using TIOCGWINSZ.
848 */
849void
850setttywidth(int a)
851{
852	struct winsize winsize;
853	int oerrno = errno;
854
855	if (ioctl(fileno(ttyout), TIOCGWINSZ, &winsize) != -1 &&
856	    winsize.ws_col != 0)
857		ttywidth = winsize.ws_col;
858	else
859		ttywidth = 80;
860	errno = oerrno;
861}
862
863/*
864 * Change the rate limit up (SIGUSR1) or down (SIGUSR2)
865 */
866void
867crankrate(int sig)
868{
869
870	switch (sig) {
871	case SIGUSR1:
872		if (rate_get)
873			rate_get += rate_get_incr;
874		if (rate_put)
875			rate_put += rate_put_incr;
876		break;
877	case SIGUSR2:
878		if (rate_get && rate_get > rate_get_incr)
879			rate_get -= rate_get_incr;
880		if (rate_put && rate_put > rate_put_incr)
881			rate_put -= rate_put_incr;
882		break;
883	default:
884		err(1, "crankrate invoked with unknown signal: %d", sig);
885	}
886}
887
888
889/*
890 * Setup or cleanup EditLine structures
891 */
892#ifndef NO_EDITCOMPLETE
893void
894controlediting(void)
895{
896	if (editing && el == NULL && hist == NULL) {
897		HistEvent ev;
898		int editmode;
899
900		el = el_init(getprogname(), stdin, ttyout, stderr);
901		/* init editline */
902		hist = history_init();		/* init the builtin history */
903		history(hist, &ev, H_SETSIZE, 100);/* remember 100 events */
904		el_set(el, EL_HIST, history, hist);	/* use history */
905
906		el_set(el, EL_EDITOR, "emacs");	/* default editor is emacs */
907		el_set(el, EL_PROMPT, prompt);	/* set the prompt functions */
908		el_set(el, EL_RPROMPT, rprompt);
909
910		/* add local file completion, bind to TAB */
911		el_set(el, EL_ADDFN, "ftp-complete",
912		    "Context sensitive argument completion",
913		    complete);
914		el_set(el, EL_BIND, "^I", "ftp-complete", NULL);
915		el_source(el, NULL);	/* read ~/.editrc */
916		if ((el_get(el, EL_EDITMODE, &editmode) != -1) && editmode == 0)
917			editing = 0;	/* the user doesn't want editing,
918					 * so disable, and let statement
919					 * below cleanup */
920		else
921			el_set(el, EL_SIGNAL, 1);
922	}
923	if (!editing) {
924		if (hist) {
925			history_end(hist);
926			hist = NULL;
927		}
928		if (el) {
929			el_end(el);
930			el = NULL;
931		}
932	}
933}
934#endif /* !NO_EDITCOMPLETE */
935
936/*
937 * Convert the string `arg' to an int, which may have an optional SI suffix
938 * (`b', `k', `m', `g'). Returns the number for success, -1 otherwise.
939 */
940int
941strsuftoi(const char *arg)
942{
943	char *cp;
944	long val;
945
946	if (!isdigit((unsigned char)arg[0]))
947		return (-1);
948
949	val = strtol(arg, &cp, 10);
950	if (cp != NULL) {
951		if (cp[0] != '\0' && cp[1] != '\0')
952			 return (-1);
953		switch (tolower((unsigned char)cp[0])) {
954		case '\0':
955		case 'b':
956			break;
957		case 'k':
958			val <<= 10;
959			break;
960		case 'm':
961			val <<= 20;
962			break;
963		case 'g':
964			val <<= 30;
965			break;
966		default:
967			return (-1);
968		}
969	}
970	if (val < 0 || val > INT_MAX)
971		return (-1);
972
973	return (val);
974}
975
976/*
977 * Set up socket buffer sizes before a connection is made.
978 */
979void
980setupsockbufsize(int sock)
981{
982
983	if (setsockopt(sock, SOL_SOCKET, SO_SNDBUF, (void *) &sndbuf_size,
984	    sizeof(rcvbuf_size)) < 0)
985		warn("unable to set sndbuf size %d", sndbuf_size);
986
987	if (setsockopt(sock, SOL_SOCKET, SO_RCVBUF, (void *) &rcvbuf_size,
988	    sizeof(rcvbuf_size)) < 0)
989		warn("unable to set rcvbuf size %d", rcvbuf_size);
990}
991
992/*
993 * Copy characters from src into dst, \ quoting characters that require it
994 */
995void
996ftpvis(char *dst, size_t dstlen, const char *src, size_t srclen)
997{
998	int	di, si;
999
1000	for (di = si = 0;
1001	    src[si] != '\0' && di < dstlen && si < srclen;
1002	    di++, si++) {
1003		switch (src[si]) {
1004		case '\\':
1005		case ' ':
1006		case '\t':
1007		case '\r':
1008		case '\n':
1009		case '"':
1010			dst[di++] = '\\';
1011			if (di >= dstlen)
1012				break;
1013			/* FALLTHROUGH */
1014		default:
1015			dst[di] = src[si];
1016		}
1017	}
1018	dst[di] = '\0';
1019}
1020
1021/*
1022 * Copy src into buf (which is len bytes long), expanding % sequences.
1023 */
1024void
1025formatbuf(char *buf, size_t len, const char *src)
1026{
1027	const char	*p;
1028	char		*p2, *q;
1029	int		 i, op, updirs, pdirs;
1030
1031#define ADDBUF(x) do { \
1032		if (i >= len - 1) \
1033			goto endbuf; \
1034		buf[i++] = (x); \
1035	} while (0)
1036
1037	p = src;
1038	for (i = 0; *p; p++) {
1039		if (*p != '%') {
1040			ADDBUF(*p);
1041			continue;
1042		}
1043		p++;
1044
1045		switch (op = *p) {
1046
1047		case '/':
1048		case '.':
1049		case 'c':
1050			p2 = connected ? remotepwd : "";
1051			updirs = pdirs = 0;
1052
1053			/* option to determine fixed # of dirs from path */
1054			if (op == '.' || op == 'c') {
1055				int skip;
1056
1057				q = p2;
1058				while (*p2)		/* calc # of /'s */
1059					if (*p2++ == '/')
1060						updirs++;
1061				if (p[1] == '0') {	/* print <x> or ... */
1062					pdirs = 1;
1063					p++;
1064				}
1065				if (p[1] >= '1' && p[1] <= '9') {
1066							/* calc # to skip  */
1067					skip = p[1] - '0';
1068					p++;
1069				} else
1070					skip = 1;
1071
1072				updirs -= skip;
1073				while (skip-- > 0) {
1074					while ((p2 > q) && (*p2 != '/'))
1075						p2--;	/* back up */
1076					if (skip && p2 > q)
1077						p2--;
1078				}
1079				if (*p2 == '/' && p2 != q)
1080					p2++;
1081			}
1082
1083			if (updirs > 0 && pdirs) {
1084				if (i >= len - 5)
1085					break;
1086				if (op == '.') {
1087					ADDBUF('.');
1088					ADDBUF('.');
1089					ADDBUF('.');
1090				} else {
1091					ADDBUF('/');
1092					ADDBUF('<');
1093					if (updirs > 9) {
1094						ADDBUF('9');
1095						ADDBUF('+');
1096					} else
1097						ADDBUF('0' + updirs);
1098					ADDBUF('>');
1099				}
1100			}
1101			for (; *p2; p2++)
1102				ADDBUF(*p2);
1103			break;
1104
1105		case 'M':
1106		case 'm':
1107			for (p2 = connected && username ? username : "-";
1108			    *p2 ; p2++) {
1109				if (op == 'm' && *p2 == '.')
1110					break;
1111				ADDBUF(*p2);
1112			}
1113			break;
1114
1115		case 'n':
1116			for (p2 = connected ? username : "-"; *p2 ; p2++)
1117				ADDBUF(*p2);
1118			break;
1119
1120		case '%':
1121			ADDBUF('%');
1122			break;
1123
1124		default:		/* display unknown codes literally */
1125			ADDBUF('%');
1126			ADDBUF(op);
1127			break;
1128
1129		}
1130	}
1131 endbuf:
1132	buf[i] = '\0';
1133}
1134
1135/*
1136 * Parse `port' into a TCP port number, defaulting to `defport' if `port' is
1137 * an unknown service name. If defport != -1, print a warning upon bad parse.
1138 */
1139int
1140parseport(const char *port, int defport)
1141{
1142	int	 rv;
1143	long	 nport;
1144	char	*p, *ep;
1145
1146	p = xstrdup(port);
1147	nport = strtol(p, &ep, 10);
1148	if (*ep != '\0' && ep == p) {
1149		struct servent	*svp;
1150
1151		svp = getservbyname(port, "tcp");
1152		if (svp == NULL) {
1153 badparseport:
1154			if (defport != -1)
1155				warnx("Unknown port `%s', using port %d",
1156				    port, defport);
1157			rv = defport;
1158		} else
1159			rv = ntohs(svp->s_port);
1160	} else if (nport < 1 || nport > MAX_IN_PORT_T || *ep != '\0')
1161		goto badparseport;
1162	else
1163		rv = nport;
1164	free(p);
1165	return (rv);
1166}
1167
1168/*
1169 * Determine if given string is an IPv6 address or not.
1170 * Return 1 for yes, 0 for no
1171 */
1172int
1173isipv6addr(const char *addr)
1174{
1175	int rv = 0;
1176#ifdef INET6
1177	struct addrinfo hints, *res;
1178
1179	memset(&hints, 0, sizeof(hints));
1180	hints.ai_family = PF_INET6;
1181	hints.ai_socktype = SOCK_DGRAM;	/*dummy*/
1182	hints.ai_flags = AI_NUMERICHOST;
1183	if (getaddrinfo(addr, "0", &hints, &res) != 0)
1184		rv = 0;
1185	else {
1186		rv = 1;
1187		freeaddrinfo(res);
1188	}
1189	if (debug)
1190		fprintf(ttyout, "isipv6addr: got %d for %s\n", rv, addr);
1191#endif
1192	return (rv == 1) ? 1 : 0;
1193}
1194
1195
1196/*
1197 * Internal version of connect(2); sets socket buffer sizes first.
1198 */
1199int
1200xconnect(int sock, const struct sockaddr *name, int namelen)
1201{
1202
1203	setupsockbufsize(sock);
1204	return (connect(sock, name, namelen));
1205}
1206
1207/*
1208 * Internal version of listen(2); sets socket buffer sizes first.
1209 */
1210int
1211xlisten(int sock, int backlog)
1212{
1213
1214	setupsockbufsize(sock);
1215	return (listen(sock, backlog));
1216}
1217
1218/*
1219 * malloc() with inbuilt error checking
1220 */
1221void *
1222xmalloc(size_t size)
1223{
1224	void *p;
1225
1226	p = malloc(size);
1227	if (p == NULL)
1228		err(1, "Unable to allocate %ld bytes of memory", (long)size);
1229	return (p);
1230}
1231
1232/*
1233 * sl_init() with inbuilt error checking
1234 */
1235StringList *
1236xsl_init(void)
1237{
1238	StringList *p;
1239
1240	p = sl_init();
1241	if (p == NULL)
1242		err(1, "Unable to allocate memory for stringlist");
1243	return (p);
1244}
1245
1246/*
1247 * sl_add() with inbuilt error checking
1248 */
1249void
1250xsl_add(StringList *sl, char *i)
1251{
1252
1253	if (sl_add(sl, i) == -1)
1254		err(1, "Unable to add `%s' to stringlist", i);
1255}
1256
1257/*
1258 * strdup() with inbuilt error checking
1259 */
1260char *
1261xstrdup(const char *str)
1262{
1263	char *s;
1264
1265	if (str == NULL)
1266		errx(1, "xstrdup() called with NULL argument");
1267	s = strdup(str);
1268	if (s == NULL)
1269		err(1, "Unable to allocate memory for string copy");
1270	return (s);
1271}
1272