ftp.c revision 90267
1/*-
2 * Copyright (c) 1998 Dag-Erling Co�dan Sm�rgrav
3 * All rights reserved.
4 *
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions
7 * are met:
8 * 1. Redistributions of source code must retain the above copyright
9 *    notice, this list of conditions and the following disclaimer
10 *    in this position and unchanged.
11 * 2. Redistributions in binary form must reproduce the above copyright
12 *    notice, this list of conditions and the following disclaimer in the
13 *    documentation and/or other materials provided with the distribution.
14 * 3. The name of the author may not be used to endorse or promote products
15 *    derived from this software without specific prior written permission
16 *
17 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
18 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
19 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
20 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
21 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
22 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
23 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
24 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
25 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
26 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
27 */
28
29#include <sys/cdefs.h>
30__FBSDID("$FreeBSD: head/lib/libfetch/ftp.c 90267 2002-02-05 22:13:51Z des $");
31
32/*
33 * Portions of this code were taken from or based on ftpio.c:
34 *
35 * ----------------------------------------------------------------------------
36 * "THE BEER-WARE LICENSE" (Revision 42):
37 * <phk@login.dknet.dk> wrote this file.  As long as you retain this notice you
38 * can do whatever you want with this stuff. If we meet some day, and you think
39 * this stuff is worth it, you can buy me a beer in return.   Poul-Henning Kamp
40 * ----------------------------------------------------------------------------
41 *
42 * Major Changelog:
43 *
44 * Dag-Erling Co�dan Sm�rgrav
45 * 9 Jun 1998
46 *
47 * Incorporated into libfetch
48 *
49 * Jordan K. Hubbard
50 * 17 Jan 1996
51 *
52 * Turned inside out. Now returns xfers as new file ids, not as a special
53 * `state' of FTP_t
54 *
55 * $ftpioId: ftpio.c,v 1.30 1998/04/11 07:28:53 phk Exp $
56 *
57 */
58
59#include <sys/param.h>
60#include <sys/socket.h>
61#include <netinet/in.h>
62
63#include <ctype.h>
64#include <err.h>
65#include <errno.h>
66#include <fcntl.h>
67#include <netdb.h>
68#include <stdarg.h>
69#include <stdio.h>
70#include <stdlib.h>
71#include <string.h>
72#include <time.h>
73#include <unistd.h>
74
75#include "fetch.h"
76#include "common.h"
77#include "ftperr.h"
78
79#define FTP_ANONYMOUS_USER	"anonymous"
80
81#define FTP_CONNECTION_ALREADY_OPEN	125
82#define FTP_OPEN_DATA_CONNECTION	150
83#define FTP_OK				200
84#define FTP_FILE_STATUS			213
85#define FTP_SERVICE_READY		220
86#define FTP_TRANSFER_COMPLETE		226
87#define FTP_PASSIVE_MODE		227
88#define FTP_LPASSIVE_MODE		228
89#define FTP_EPASSIVE_MODE		229
90#define FTP_LOGGED_IN			230
91#define FTP_FILE_ACTION_OK		250
92#define FTP_NEED_PASSWORD		331
93#define FTP_NEED_ACCOUNT		332
94#define FTP_FILE_OK			350
95#define FTP_SYNTAX_ERROR		500
96#define FTP_PROTOCOL_ERROR		999
97
98static struct url cached_host;
99static int	 cached_socket;
100
101static char	*last_reply;
102static size_t	 lr_size;
103static size_t	 lr_length;
104static int	 last_code;
105
106#define isftpreply(foo) (isdigit(foo[0]) && isdigit(foo[1]) \
107			 && isdigit(foo[2]) \
108			 && (foo[3] == ' ' || foo[3] == '\0'))
109#define isftpinfo(foo) (isdigit(foo[0]) && isdigit(foo[1]) \
110			&& isdigit(foo[2]) && foo[3] == '-')
111
112/*
113 * Translate IPv4 mapped IPv6 address to IPv4 address
114 */
115static void
116unmappedaddr(struct sockaddr_in6 *sin6)
117{
118	struct sockaddr_in *sin4;
119	u_int32_t addr;
120	int port;
121
122	if (sin6->sin6_family != AF_INET6 ||
123	    !IN6_IS_ADDR_V4MAPPED(&sin6->sin6_addr))
124		return;
125	sin4 = (struct sockaddr_in *)sin6;
126	addr = *(u_int32_t *)&sin6->sin6_addr.s6_addr[12];
127	port = sin6->sin6_port;
128	memset(sin4, 0, sizeof(struct sockaddr_in));
129	sin4->sin_addr.s_addr = addr;
130	sin4->sin_port = port;
131	sin4->sin_family = AF_INET;
132	sin4->sin_len = sizeof(struct sockaddr_in);
133}
134
135/*
136 * Get server response
137 */
138static int
139_ftp_chkerr(int cd)
140{
141	if (_fetch_getln(cd, &last_reply, &lr_size, &lr_length) == -1) {
142		_fetch_syserr();
143		return (-1);
144	}
145	if (isftpinfo(last_reply)) {
146		while (lr_length && !isftpreply(last_reply)) {
147			if (_fetch_getln(cd, &last_reply,
148			    &lr_size, &lr_length) == -1) {
149				_fetch_syserr();
150				return (-1);
151			}
152		}
153	}
154
155	while (lr_length && isspace(last_reply[lr_length-1]))
156		lr_length--;
157	last_reply[lr_length] = 0;
158
159	if (!isftpreply(last_reply)) {
160		_ftp_seterr(FTP_PROTOCOL_ERROR);
161		return (-1);
162	}
163
164	last_code = (last_reply[0] - '0') * 100
165	    + (last_reply[1] - '0') * 10
166	    + (last_reply[2] - '0');
167
168	return (last_code);
169}
170
171/*
172 * Send a command and check reply
173 */
174static int
175_ftp_cmd(int cd, const char *fmt, ...)
176{
177	va_list ap;
178	size_t len;
179	char *msg;
180	int r;
181
182	va_start(ap, fmt);
183	len = vasprintf(&msg, fmt, ap);
184	va_end(ap);
185
186	if (msg == NULL) {
187		errno = ENOMEM;
188		_fetch_syserr();
189		return (-1);
190	}
191
192	r = _fetch_putln(cd, msg, len);
193	free(msg);
194
195	if (r == -1) {
196		_fetch_syserr();
197		return (-1);
198	}
199
200	return (_ftp_chkerr(cd));
201}
202
203/*
204 * Return a pointer to the filename part of a path
205 */
206static const char *
207_ftp_filename(const char *file)
208{
209	char *s;
210
211	if ((s = strrchr(file, '/')) == NULL)
212		return (file);
213	else
214		return (s + 1);
215}
216
217/*
218 * Change working directory to the directory that contains the specified
219 * file.
220 */
221static int
222_ftp_cwd(int cd, const char *file)
223{
224	char *s;
225	int e;
226
227	if ((s = strrchr(file, '/')) == NULL || s == file) {
228		e = _ftp_cmd(cd, "CWD /");
229	} else {
230		e = _ftp_cmd(cd, "CWD %.*s", s - file, file);
231	}
232	if (e != FTP_FILE_ACTION_OK) {
233		_ftp_seterr(e);
234		return (-1);
235	}
236	return (0);
237}
238
239/*
240 * Request and parse file stats
241 */
242static int
243_ftp_stat(int cd, const char *file, struct url_stat *us)
244{
245	char *ln;
246	const char *s;
247	struct tm tm;
248	time_t t;
249	int e;
250
251	us->size = -1;
252	us->atime = us->mtime = 0;
253
254	if ((s = strrchr(file, '/')) == NULL)
255		s = file;
256	else
257		++s;
258
259	if ((e = _ftp_cmd(cd, "SIZE %s", s)) != FTP_FILE_STATUS) {
260		_ftp_seterr(e);
261		return (-1);
262	}
263	for (ln = last_reply + 4; *ln && isspace(*ln); ln++)
264		/* nothing */ ;
265	for (us->size = 0; *ln && isdigit(*ln); ln++)
266		us->size = us->size * 10 + *ln - '0';
267	if (*ln && !isspace(*ln)) {
268		_ftp_seterr(FTP_PROTOCOL_ERROR);
269		us->size = -1;
270		return (-1);
271	}
272	if (us->size == 0)
273		us->size = -1;
274	DEBUG(fprintf(stderr, "size: [%lld]\n", (long long)us->size));
275
276	if ((e = _ftp_cmd(cd, "MDTM %s", s)) != FTP_FILE_STATUS) {
277		_ftp_seterr(e);
278		return (-1);
279	}
280	for (ln = last_reply + 4; *ln && isspace(*ln); ln++)
281		/* nothing */ ;
282	switch (strspn(ln, "0123456789")) {
283	case 14:
284		break;
285	case 15:
286		ln++;
287		ln[0] = '2';
288		ln[1] = '0';
289		break;
290	default:
291		_ftp_seterr(FTP_PROTOCOL_ERROR);
292		return (-1);
293	}
294	if (sscanf(ln, "%04d%02d%02d%02d%02d%02d",
295	    &tm.tm_year, &tm.tm_mon, &tm.tm_mday,
296	    &tm.tm_hour, &tm.tm_min, &tm.tm_sec) != 6) {
297		_ftp_seterr(FTP_PROTOCOL_ERROR);
298		return (-1);
299	}
300	tm.tm_mon--;
301	tm.tm_year -= 1900;
302	tm.tm_isdst = -1;
303	t = timegm(&tm);
304	if (t == (time_t)-1)
305		t = time(NULL);
306	us->mtime = t;
307	us->atime = t;
308	DEBUG(fprintf(stderr,
309	    "last modified: [%04d-%02d-%02d %02d:%02d:%02d]\n",
310	    tm.tm_year + 1900, tm.tm_mon + 1, tm.tm_mday,
311	    tm.tm_hour, tm.tm_min, tm.tm_sec));
312	return (0);
313}
314
315/*
316 * I/O functions for FTP
317 */
318struct ftpio {
319	int	 csd;		/* Control socket descriptor */
320	int	 dsd;		/* Data socket descriptor */
321	int	 dir;		/* Direction */
322	int	 eof;		/* EOF reached */
323	int	 err;		/* Error code */
324};
325
326static int	 _ftp_readfn(void *, char *, int);
327static int	 _ftp_writefn(void *, const char *, int);
328static fpos_t	 _ftp_seekfn(void *, fpos_t, int);
329static int	 _ftp_closefn(void *);
330
331static int
332_ftp_readfn(void *v, char *buf, int len)
333{
334	struct ftpio *io;
335	int r;
336
337	io = (struct ftpio *)v;
338	if (io == NULL) {
339		errno = EBADF;
340		return (-1);
341	}
342	if (io->csd == -1 || io->dsd == -1 || io->dir == O_WRONLY) {
343		errno = EBADF;
344		return (-1);
345	}
346	if (io->err) {
347		errno = io->err;
348		return (-1);
349	}
350	if (io->eof)
351		return (0);
352	r = read(io->dsd, buf, len);
353	if (r > 0)
354		return (r);
355	if (r == 0) {
356		io->eof = 1;
357		return (0);
358	}
359	if (errno != EINTR)
360		io->err = errno;
361	return (-1);
362}
363
364static int
365_ftp_writefn(void *v, const char *buf, int len)
366{
367	struct ftpio *io;
368	int w;
369
370	io = (struct ftpio *)v;
371	if (io == NULL) {
372		errno = EBADF;
373		return (-1);
374	}
375	if (io->csd == -1 || io->dsd == -1 || io->dir == O_RDONLY) {
376		errno = EBADF;
377		return (-1);
378	}
379	if (io->err) {
380		errno = io->err;
381		return (-1);
382	}
383	w = write(io->dsd, buf, len);
384	if (w >= 0)
385		return (w);
386	if (errno != EINTR)
387		io->err = errno;
388	return (-1);
389}
390
391static fpos_t
392_ftp_seekfn(void *v, fpos_t pos __unused, int whence __unused)
393{
394	struct ftpio *io;
395
396	io = (struct ftpio *)v;
397	if (io == NULL) {
398		errno = EBADF;
399		return (-1);
400	}
401	errno = ESPIPE;
402	return (-1);
403}
404
405static int
406_ftp_closefn(void *v)
407{
408	struct ftpio *io;
409	int r;
410
411	io = (struct ftpio *)v;
412	if (io == NULL) {
413		errno = EBADF;
414		return (-1);
415	}
416	if (io->dir == -1)
417		return (0);
418	if (io->csd == -1 || io->dsd == -1) {
419		errno = EBADF;
420		return (-1);
421	}
422	close(io->dsd);
423	io->dir = -1;
424	io->dsd = -1;
425	DEBUG(fprintf(stderr, "Waiting for final status\n"));
426	r = _ftp_chkerr(io->csd);
427	close(io->csd);
428	free(io);
429	return (r == FTP_TRANSFER_COMPLETE) ? 0 : -1;
430}
431
432static FILE *
433_ftp_setup(int csd, int dsd, int mode)
434{
435	struct ftpio *io;
436	FILE *f;
437
438	if ((io = malloc(sizeof *io)) == NULL)
439		return (NULL);
440	io->csd = dup(csd);
441	io->dsd = dsd;
442	io->dir = mode;
443	io->eof = io->err = 0;
444	f = funopen(io, _ftp_readfn, _ftp_writefn, _ftp_seekfn, _ftp_closefn);
445	if (f == NULL)
446		free(io);
447	return (f);
448}
449
450/*
451 * Transfer file
452 */
453static FILE *
454_ftp_transfer(int cd, const char *oper, const char *file,
455    int mode, off_t offset, const char *flags)
456{
457	struct sockaddr_storage sa;
458	struct sockaddr_in6 *sin6;
459	struct sockaddr_in *sin4;
460	int low, pasv, verbose;
461	int e, sd = -1;
462	socklen_t l;
463	char *s;
464	FILE *df;
465
466	/* check flags */
467	low = CHECK_FLAG('l');
468	pasv = CHECK_FLAG('p');
469	verbose = CHECK_FLAG('v');
470
471	/* passive mode */
472	if (!pasv)
473		pasv = ((s = getenv("FTP_PASSIVE_MODE")) != NULL &&
474		    strncasecmp(s, "no", 2) != 0);
475
476	/* find our own address, bind, and listen */
477	l = sizeof sa;
478	if (getsockname(cd, (struct sockaddr *)&sa, &l) == -1)
479		goto sysouch;
480	if (sa.ss_family == AF_INET6)
481		unmappedaddr((struct sockaddr_in6 *)&sa);
482
483	/* open data socket */
484	if ((sd = socket(sa.ss_family, SOCK_STREAM, IPPROTO_TCP)) == -1) {
485		_fetch_syserr();
486		return (NULL);
487	}
488
489	if (pasv) {
490		u_char addr[64];
491		char *ln, *p;
492		unsigned int i;
493		int port;
494
495		/* send PASV command */
496		if (verbose)
497			_fetch_info("setting passive mode");
498		switch (sa.ss_family) {
499		case AF_INET:
500			if ((e = _ftp_cmd(cd, "PASV")) != FTP_PASSIVE_MODE)
501				goto ouch;
502			break;
503		case AF_INET6:
504			if ((e = _ftp_cmd(cd, "EPSV")) != FTP_EPASSIVE_MODE) {
505				if (e == -1)
506					goto ouch;
507				if ((e = _ftp_cmd(cd, "LPSV")) != FTP_LPASSIVE_MODE)
508					goto ouch;
509			}
510			break;
511		default:
512			e = FTP_PROTOCOL_ERROR; /* XXX: error code should be prepared */
513			goto ouch;
514		}
515
516		/*
517		 * Find address and port number. The reply to the PASV command
518		 * is IMHO the one and only weak point in the FTP protocol.
519		 */
520		ln = last_reply;
521		switch (e) {
522		case FTP_PASSIVE_MODE:
523		case FTP_LPASSIVE_MODE:
524			for (p = ln + 3; *p && !isdigit(*p); p++)
525				/* nothing */ ;
526			if (!*p) {
527				e = FTP_PROTOCOL_ERROR;
528				goto ouch;
529			}
530			l = (e == FTP_PASSIVE_MODE ? 6 : 21);
531			for (i = 0; *p && i < l; i++, p++)
532				addr[i] = strtol(p, &p, 10);
533			if (i < l) {
534				e = FTP_PROTOCOL_ERROR;
535				goto ouch;
536			}
537			break;
538		case FTP_EPASSIVE_MODE:
539			for (p = ln + 3; *p && *p != '('; p++)
540				/* nothing */ ;
541			if (!*p) {
542				e = FTP_PROTOCOL_ERROR;
543				goto ouch;
544			}
545			++p;
546			if (sscanf(p, "%c%c%c%d%c", &addr[0], &addr[1], &addr[2],
547				&port, &addr[3]) != 5 ||
548			    addr[0] != addr[1] ||
549			    addr[0] != addr[2] || addr[0] != addr[3]) {
550				e = FTP_PROTOCOL_ERROR;
551				goto ouch;
552			}
553			break;
554		}
555
556		/* seek to required offset */
557		if (offset)
558			if (_ftp_cmd(cd, "REST %lu", (u_long)offset) != FTP_FILE_OK)
559				goto sysouch;
560
561		/* construct sockaddr for data socket */
562		l = sizeof sa;
563		if (getpeername(cd, (struct sockaddr *)&sa, &l) == -1)
564			goto sysouch;
565		if (sa.ss_family == AF_INET6)
566			unmappedaddr((struct sockaddr_in6 *)&sa);
567		switch (sa.ss_family) {
568		case AF_INET6:
569			sin6 = (struct sockaddr_in6 *)&sa;
570			if (e == FTP_EPASSIVE_MODE)
571				sin6->sin6_port = htons(port);
572			else {
573				bcopy(addr + 2, (char *)&sin6->sin6_addr, 16);
574				bcopy(addr + 19, (char *)&sin6->sin6_port, 2);
575			}
576			break;
577		case AF_INET:
578			sin4 = (struct sockaddr_in *)&sa;
579			if (e == FTP_EPASSIVE_MODE)
580				sin4->sin_port = htons(port);
581			else {
582				bcopy(addr, (char *)&sin4->sin_addr, 4);
583				bcopy(addr + 4, (char *)&sin4->sin_port, 2);
584			}
585			break;
586		default:
587			e = FTP_PROTOCOL_ERROR; /* XXX: error code should be prepared */
588			break;
589		}
590
591		/* connect to data port */
592		if (verbose)
593			_fetch_info("opening data connection");
594		if (connect(sd, (struct sockaddr *)&sa, sa.ss_len) == -1)
595			goto sysouch;
596
597		/* make the server initiate the transfer */
598		if (verbose)
599			_fetch_info("initiating transfer");
600		e = _ftp_cmd(cd, "%s %s", oper, _ftp_filename(file));
601		if (e != FTP_CONNECTION_ALREADY_OPEN && e != FTP_OPEN_DATA_CONNECTION)
602			goto ouch;
603
604	} else {
605		u_int32_t a;
606		u_short p;
607		int arg, d;
608		char *ap;
609		char hname[INET6_ADDRSTRLEN];
610
611		switch (sa.ss_family) {
612		case AF_INET6:
613			((struct sockaddr_in6 *)&sa)->sin6_port = 0;
614#ifdef IPV6_PORTRANGE
615			arg = low ? IPV6_PORTRANGE_DEFAULT : IPV6_PORTRANGE_HIGH;
616			if (setsockopt(sd, IPPROTO_IPV6, IPV6_PORTRANGE,
617				(char *)&arg, sizeof(arg)) == -1)
618				goto sysouch;
619#endif
620			break;
621		case AF_INET:
622			((struct sockaddr_in *)&sa)->sin_port = 0;
623			arg = low ? IP_PORTRANGE_DEFAULT : IP_PORTRANGE_HIGH;
624			if (setsockopt(sd, IPPROTO_IP, IP_PORTRANGE,
625				(char *)&arg, sizeof arg) == -1)
626				goto sysouch;
627			break;
628		}
629		if (verbose)
630			_fetch_info("binding data socket");
631		if (bind(sd, (struct sockaddr *)&sa, sa.ss_len) == -1)
632			goto sysouch;
633		if (listen(sd, 1) == -1)
634			goto sysouch;
635
636		/* find what port we're on and tell the server */
637		if (getsockname(sd, (struct sockaddr *)&sa, &l) == -1)
638			goto sysouch;
639		switch (sa.ss_family) {
640		case AF_INET:
641			sin4 = (struct sockaddr_in *)&sa;
642			a = ntohl(sin4->sin_addr.s_addr);
643			p = ntohs(sin4->sin_port);
644			e = _ftp_cmd(cd, "PORT %d,%d,%d,%d,%d,%d",
645			    (a >> 24) & 0xff, (a >> 16) & 0xff,
646			    (a >> 8) & 0xff, a & 0xff,
647			    (p >> 8) & 0xff, p & 0xff);
648			break;
649		case AF_INET6:
650#define UC(b)	(((int)b)&0xff)
651			e = -1;
652			sin6 = (struct sockaddr_in6 *)&sa;
653			if (getnameinfo((struct sockaddr *)&sa, sa.ss_len,
654				hname, sizeof(hname),
655				NULL, 0, NI_NUMERICHOST) == 0) {
656				e = _ftp_cmd(cd, "EPRT |%d|%s|%d|", 2, hname,
657				    htons(sin6->sin6_port));
658				if (e == -1)
659					goto ouch;
660			}
661			if (e != FTP_OK) {
662				ap = (char *)&sin6->sin6_addr;
663				e = _ftp_cmd(cd,
664				    "LPRT %d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d",
665				    6, 16,
666				    UC(ap[0]), UC(ap[1]), UC(ap[2]), UC(ap[3]),
667				    UC(ap[4]), UC(ap[5]), UC(ap[6]), UC(ap[7]),
668				    UC(ap[8]), UC(ap[9]), UC(ap[10]), UC(ap[11]),
669				    UC(ap[12]), UC(ap[13]), UC(ap[14]), UC(ap[15]),
670				    2,
671				    (ntohs(sin6->sin6_port) >> 8) & 0xff,
672				    ntohs(sin6->sin6_port)        & 0xff);
673			}
674			break;
675		default:
676			e = FTP_PROTOCOL_ERROR; /* XXX: error code should be prepared */
677			goto ouch;
678		}
679		if (e != FTP_OK)
680			goto ouch;
681
682		/* seek to required offset */
683		if (offset)
684			if (_ftp_cmd(cd, "REST %lu", (u_long)offset) != FTP_FILE_OK)
685				goto sysouch;
686
687		/* make the server initiate the transfer */
688		if (verbose)
689			_fetch_info("initiating transfer");
690		e = _ftp_cmd(cd, "%s %s", oper, _ftp_filename(file));
691		if (e != FTP_OPEN_DATA_CONNECTION)
692			goto ouch;
693
694		/* accept the incoming connection and go to town */
695		if ((d = accept(sd, NULL, NULL)) == -1)
696			goto sysouch;
697		close(sd);
698		sd = d;
699	}
700
701	if ((df = _ftp_setup(cd, sd, mode)) == NULL)
702		goto sysouch;
703	return (df);
704
705sysouch:
706	_fetch_syserr();
707	if (sd >= 0)
708		close(sd);
709	return (NULL);
710
711ouch:
712	if (e != -1)
713		_ftp_seterr(e);
714	if (sd >= 0)
715		close(sd);
716	return (NULL);
717}
718
719/*
720 * Authenticate
721 */
722static int
723_ftp_authenticate(int cd, struct url *url, struct url *purl)
724{
725	const char *user, *pwd, *logname;
726	char pbuf[MAXHOSTNAMELEN + MAXLOGNAME + 1];
727	int e, len;
728
729	/* XXX FTP_AUTH, and maybe .netrc */
730
731	/* send user name and password */
732	user = url->user;
733	if (!user || !*user)
734		user = getenv("FTP_LOGIN");
735	if (!user || !*user)
736		user = FTP_ANONYMOUS_USER;
737	if (purl && url->port == _fetch_default_port(url->scheme))
738		e = _ftp_cmd(cd, "USER %s@%s", user, url->host);
739	else if (purl)
740		e = _ftp_cmd(cd, "USER %s@%s@%d", user, url->host, url->port);
741	else
742		e = _ftp_cmd(cd, "USER %s", user);
743
744	/* did the server request a password? */
745	if (e == FTP_NEED_PASSWORD) {
746		pwd = url->pwd;
747		if (!pwd || !*pwd)
748			pwd = getenv("FTP_PASSWORD");
749		if (!pwd || !*pwd) {
750			if ((logname = getlogin()) == 0)
751				logname = FTP_ANONYMOUS_USER;
752			if ((len = snprintf(pbuf, MAXLOGNAME + 1, "%s@", logname)) < 0)
753				len = 0;
754			else if (len > MAXLOGNAME)
755				len = MAXLOGNAME;
756			gethostname(pbuf + len, sizeof pbuf - len);
757			pwd = pbuf;
758		}
759		e = _ftp_cmd(cd, "PASS %s", pwd);
760	}
761
762	return (e);
763}
764
765/*
766 * Log on to FTP server
767 */
768static int
769_ftp_connect(struct url *url, struct url *purl, const char *flags)
770{
771	int cd, e, direct, verbose;
772#ifdef INET6
773	int af = AF_UNSPEC;
774#else
775	int af = AF_INET;
776#endif
777
778	direct = CHECK_FLAG('d');
779	verbose = CHECK_FLAG('v');
780	if (CHECK_FLAG('4'))
781		af = AF_INET;
782	else if (CHECK_FLAG('6'))
783		af = AF_INET6;
784
785	if (direct)
786		purl = NULL;
787
788	/* check for proxy */
789	if (purl) {
790		/* XXX proxy authentication! */
791		cd = _fetch_connect(purl->host, purl->port, af, verbose);
792	} else {
793		/* no proxy, go straight to target */
794		cd = _fetch_connect(url->host, url->port, af, verbose);
795		purl = NULL;
796	}
797
798	/* check connection */
799	if (cd == -1) {
800		_fetch_syserr();
801		return (NULL);
802	}
803
804	/* expect welcome message */
805	if ((e = _ftp_chkerr(cd)) != FTP_SERVICE_READY)
806		goto fouch;
807
808	/* authenticate */
809	if ((e = _ftp_authenticate(cd, url, purl)) != FTP_LOGGED_IN)
810		goto fouch;
811
812	/* might as well select mode and type at once */
813#ifdef FTP_FORCE_STREAM_MODE
814	if ((e = _ftp_cmd(cd, "MODE S")) != FTP_OK) /* default is S */
815		goto fouch;
816#endif
817	if ((e = _ftp_cmd(cd, "TYPE I")) != FTP_OK) /* default is A */
818		goto fouch;
819
820	/* done */
821	return (cd);
822
823fouch:
824	if (e != -1)
825		_ftp_seterr(e);
826	close(cd);
827	return (NULL);
828}
829
830/*
831 * Disconnect from server
832 */
833static void
834_ftp_disconnect(int cd)
835{
836	(void)_ftp_cmd(cd, "QUIT");
837	close(cd);
838}
839
840/*
841 * Check if we're already connected
842 */
843static int
844_ftp_isconnected(struct url *url)
845{
846	return (cached_socket
847	    && (strcmp(url->host, cached_host.host) == 0)
848	    && (strcmp(url->user, cached_host.user) == 0)
849	    && (strcmp(url->pwd, cached_host.pwd) == 0)
850	    && (url->port == cached_host.port));
851}
852
853/*
854 * Check the cache, reconnect if no luck
855 */
856static int
857_ftp_cached_connect(struct url *url, struct url *purl, const char *flags)
858{
859	int e, cd;
860
861	cd = -1;
862
863	/* set default port */
864	if (!url->port)
865		url->port = _fetch_default_port(url->scheme);
866
867	/* try to use previously cached connection */
868	if (_ftp_isconnected(url)) {
869		e = _ftp_cmd(cached_socket, "NOOP");
870		if (e == FTP_OK || e == FTP_SYNTAX_ERROR)
871			return (cached_socket);
872	}
873
874	/* connect to server */
875	if ((cd = _ftp_connect(url, purl, flags)) == -1)
876		return (-1);
877	if (cached_socket)
878		_ftp_disconnect(cached_socket);
879	cached_socket = cd;
880	memcpy(&cached_host, url, sizeof *url);
881	return (cd);
882}
883
884/*
885 * Check the proxy settings
886 */
887static struct url *
888_ftp_get_proxy(void)
889{
890	struct url *purl;
891	char *p;
892
893	if (((p = getenv("FTP_PROXY")) || (p = getenv("ftp_proxy")) ||
894		(p = getenv("HTTP_PROXY")) || (p = getenv("http_proxy"))) &&
895	    *p && (purl = fetchParseURL(p)) != NULL) {
896		if (!*purl->scheme) {
897			if (getenv("FTP_PROXY") || getenv("ftp_proxy"))
898				strcpy(purl->scheme, SCHEME_FTP);
899			else
900				strcpy(purl->scheme, SCHEME_HTTP);
901		}
902		if (!purl->port)
903			purl->port = _fetch_default_proxy_port(purl->scheme);
904		if (strcasecmp(purl->scheme, SCHEME_FTP) == 0 ||
905		    strcasecmp(purl->scheme, SCHEME_HTTP) == 0)
906			return (purl);
907		fetchFreeURL(purl);
908	}
909	return (NULL);
910}
911
912/*
913 * Process an FTP request
914 */
915FILE *
916_ftp_request(struct url *url, const char *op, struct url_stat *us,
917    struct url *purl, const char *flags)
918{
919	int cd, oflag;
920
921	/* check if we should use HTTP instead */
922	if (purl && strcasecmp(purl->scheme, SCHEME_HTTP) == 0) {
923		if (strcmp(op, "STAT") == 0)
924			return (_http_request(url, "HEAD", us, purl, flags));
925		else if (strcmp(op, "RETR") == 0)
926			return (_http_request(url, "GET", us, purl, flags));
927		/*
928		 * Our HTTP code doesn't support PUT requests yet, so try
929		 * a direct connection.
930		 */
931	}
932
933	/* connect to server */
934	cd = _ftp_cached_connect(url, purl, flags);
935	if (purl)
936		fetchFreeURL(purl);
937	if (cd == NULL)
938		return (NULL);
939
940	/* change directory */
941	if (_ftp_cwd(cd, url->doc) == -1)
942		return (NULL);
943
944	/* stat file */
945	if (us && _ftp_stat(cd, url->doc, us) == -1
946	    && fetchLastErrCode != FETCH_PROTO
947	    && fetchLastErrCode != FETCH_UNAVAIL)
948		return (NULL);
949
950	/* just a stat */
951	if (strcmp(op, "STAT") == 0)
952		return (FILE *)1; /* bogus return value */
953	if (strcmp(op, "STOR") == 0 || strcmp(op, "APPE") == 0)
954		oflag = O_WRONLY;
955	else
956		oflag = O_RDONLY;
957
958	/* initiate the transfer */
959	return (_ftp_transfer(cd, op, url->doc, oflag, url->offset, flags));
960}
961
962/*
963 * Get and stat file
964 */
965FILE *
966fetchXGetFTP(struct url *url, struct url_stat *us, const char *flags)
967{
968	return (_ftp_request(url, "RETR", us, _ftp_get_proxy(), flags));
969}
970
971/*
972 * Get file
973 */
974FILE *
975fetchGetFTP(struct url *url, const char *flags)
976{
977	return (fetchXGetFTP(url, NULL, flags));
978}
979
980/*
981 * Put file
982 */
983FILE *
984fetchPutFTP(struct url *url, const char *flags)
985{
986
987	return _ftp_request(url, CHECK_FLAG('a') ? "APPE" : "STOR", NULL,
988	    _ftp_get_proxy(), flags);
989}
990
991/*
992 * Get file stats
993 */
994int
995fetchStatFTP(struct url *url, struct url_stat *us, const char *flags)
996{
997
998	if (_ftp_request(url, "STAT", us, _ftp_get_proxy(), flags) == NULL)
999		return (-1);
1000	return (0);
1001}
1002
1003/*
1004 * List a directory
1005 */
1006struct url_ent *
1007fetchListFTP(struct url *url __unused, const char *flags __unused)
1008{
1009	warnx("fetchListFTP(): not implemented");
1010	return (NULL);
1011}
1012