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