ftp.c revision 105903
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 105903 2002-10-25 01:17:32Z njl $");
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	*cconn;		/* Control connection */
315	conn_t	*dconn;		/* Data connection */
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->cconn == NULL || io->dconn == NULL || 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 = _fetch_read(io->dconn, 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->cconn == NULL || io->dconn == NULL || 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 = _fetch_write(io->dconn, 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->cconn == NULL || io->dconn == NULL) {
414		errno = EBADF;
415		return (-1);
416	}
417	_fetch_close(io->dconn);
418	io->dir = -1;
419	io->dconn = NULL;
420	DEBUG(fprintf(stderr, "Waiting for final status\n"));
421	r = _ftp_chkerr(io->cconn);
422	if (io->cconn == cached_connection && io->cconn->ref == 1)
423		cached_connection = NULL;
424	_fetch_close(io->cconn);
425	free(io);
426	return (r == FTP_TRANSFER_COMPLETE) ? 0 : -1;
427}
428
429static FILE *
430_ftp_setup(conn_t *cconn, conn_t *dconn, int mode)
431{
432	struct ftpio *io;
433	FILE *f;
434
435	if (cconn == NULL || dconn == NULL)
436		return (NULL);
437	if ((io = malloc(sizeof *io)) == NULL)
438		return (NULL);
439	io->cconn = cconn;
440	io->dconn = dconn;
441	io->dir = mode;
442	io->eof = io->err = 0;
443	f = funopen(io, _ftp_readfn, _ftp_writefn, _ftp_seekfn, _ftp_closefn);
444	if (f == NULL)
445		free(io);
446	return (f);
447}
448
449/*
450 * Transfer file
451 */
452static FILE *
453_ftp_transfer(conn_t *conn, const char *oper, const char *file,
454    int mode, off_t offset, const char *flags)
455{
456	struct sockaddr_storage sa;
457	struct sockaddr_in6 *sin6;
458	struct sockaddr_in *sin4;
459	int low, pasv, verbose;
460	int e, sd = -1;
461	socklen_t l;
462	char *s;
463	FILE *df;
464
465	/* check flags */
466	low = CHECK_FLAG('l');
467	pasv = CHECK_FLAG('p');
468	verbose = CHECK_FLAG('v');
469
470	/* passive mode */
471	if (!pasv)
472		pasv = ((s = getenv("FTP_PASSIVE_MODE")) != NULL &&
473		    strncasecmp(s, "no", 2) != 0);
474
475	/* find our own address, bind, and listen */
476	l = sizeof sa;
477	if (getsockname(conn->sd, (struct sockaddr *)&sa, &l) == -1)
478		goto sysouch;
479	if (sa.ss_family == AF_INET6)
480		unmappedaddr((struct sockaddr_in6 *)&sa);
481
482	/* open data socket */
483	if ((sd = socket(sa.ss_family, SOCK_STREAM, IPPROTO_TCP)) == -1) {
484		_fetch_syserr();
485		return (NULL);
486	}
487
488	if (pasv) {
489		u_char addr[64];
490		char *ln, *p;
491		unsigned int i;
492		int port;
493
494		/* send PASV command */
495		if (verbose)
496			_fetch_info("setting passive mode");
497		switch (sa.ss_family) {
498		case AF_INET:
499			if ((e = _ftp_cmd(conn, "PASV")) != FTP_PASSIVE_MODE)
500				goto ouch;
501			break;
502		case AF_INET6:
503			if ((e = _ftp_cmd(conn, "EPSV")) != FTP_EPASSIVE_MODE) {
504				if (e == -1)
505					goto ouch;
506				if ((e = _ftp_cmd(conn, "LPSV")) !=
507				    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 = conn->buf;
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(conn, "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(conn->sd, (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(conn, "%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(conn, "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			sin6->sin6_scope_id = 0;
654			if (getnameinfo((struct sockaddr *)&sa, sa.ss_len,
655				hname, sizeof(hname),
656				NULL, 0, NI_NUMERICHOST) == 0) {
657				e = _ftp_cmd(conn, "EPRT |%d|%s|%d|", 2, hname,
658				    htons(sin6->sin6_port));
659				if (e == -1)
660					goto ouch;
661			}
662			if (e != FTP_OK) {
663				ap = (char *)&sin6->sin6_addr;
664				e = _ftp_cmd(conn,
665				    "LPRT %d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d",
666				    6, 16,
667				    UC(ap[0]), UC(ap[1]), UC(ap[2]), UC(ap[3]),
668				    UC(ap[4]), UC(ap[5]), UC(ap[6]), UC(ap[7]),
669				    UC(ap[8]), UC(ap[9]), UC(ap[10]), UC(ap[11]),
670				    UC(ap[12]), UC(ap[13]), UC(ap[14]), UC(ap[15]),
671				    2,
672				    (ntohs(sin6->sin6_port) >> 8) & 0xff,
673				    ntohs(sin6->sin6_port)        & 0xff);
674			}
675			break;
676		default:
677			e = FTP_PROTOCOL_ERROR; /* XXX: error code should be prepared */
678			goto ouch;
679		}
680		if (e != FTP_OK)
681			goto ouch;
682
683		/* seek to required offset */
684		if (offset)
685			if (_ftp_cmd(conn, "REST %ju", (uintmax_t)offset) != FTP_FILE_OK)
686				goto sysouch;
687
688		/* make the server initiate the transfer */
689		if (verbose)
690			_fetch_info("initiating transfer");
691		e = _ftp_cmd(conn, "%s %s", oper, _ftp_filename(file));
692		if (e != FTP_OPEN_DATA_CONNECTION)
693			goto ouch;
694
695		/* accept the incoming connection and go to town */
696		if ((d = accept(sd, NULL, NULL)) == -1)
697			goto sysouch;
698		close(sd);
699		sd = d;
700	}
701
702	if ((df = _ftp_setup(conn, _fetch_reopen(sd), mode)) == NULL)
703		goto sysouch;
704	return (df);
705
706sysouch:
707	_fetch_syserr();
708	if (sd >= 0)
709		close(sd);
710	return (NULL);
711
712ouch:
713	if (e != -1)
714		_ftp_seterr(e);
715	if (sd >= 0)
716		close(sd);
717	return (NULL);
718}
719
720/*
721 * Authenticate
722 */
723static int
724_ftp_authenticate(conn_t *conn, struct url *url, struct url *purl)
725{
726	const char *user, *pwd, *logname;
727	char pbuf[MAXHOSTNAMELEN + MAXLOGNAME + 1];
728	int e, len;
729
730	/* XXX FTP_AUTH, and maybe .netrc */
731
732	/* send user name and password */
733	user = url->user;
734	if (!user || !*user)
735		user = getenv("FTP_LOGIN");
736	if (!user || !*user)
737		user = FTP_ANONYMOUS_USER;
738	if (purl && url->port == _fetch_default_port(url->scheme))
739		e = _ftp_cmd(conn, "USER %s@%s", user, url->host);
740	else if (purl)
741		e = _ftp_cmd(conn, "USER %s@%s@%d", user, url->host, url->port);
742	else
743		e = _ftp_cmd(conn, "USER %s", user);
744
745	/* did the server request a password? */
746	if (e == FTP_NEED_PASSWORD) {
747		pwd = url->pwd;
748		if (!pwd || !*pwd)
749			pwd = getenv("FTP_PASSWORD");
750		if (!pwd || !*pwd) {
751			if ((logname = getlogin()) == 0)
752				logname = FTP_ANONYMOUS_USER;
753			if ((len = snprintf(pbuf, MAXLOGNAME + 1, "%s@", logname)) < 0)
754				len = 0;
755			else if (len > MAXLOGNAME)
756				len = MAXLOGNAME;
757			gethostname(pbuf + len, sizeof pbuf - len);
758			pwd = pbuf;
759		}
760		e = _ftp_cmd(conn, "PASS %s", pwd);
761	}
762
763	return (e);
764}
765
766/*
767 * Log on to FTP server
768 */
769static conn_t *
770_ftp_connect(struct url *url, struct url *purl, const char *flags)
771{
772	conn_t *conn;
773	int e, direct, verbose;
774#ifdef INET6
775	int af = AF_UNSPEC;
776#else
777	int af = AF_INET;
778#endif
779
780	direct = CHECK_FLAG('d');
781	verbose = CHECK_FLAG('v');
782	if (CHECK_FLAG('4'))
783		af = AF_INET;
784	else if (CHECK_FLAG('6'))
785		af = AF_INET6;
786
787	if (direct)
788		purl = NULL;
789
790	/* check for proxy */
791	if (purl) {
792		/* XXX proxy authentication! */
793		conn = _fetch_connect(purl->host, purl->port, af, verbose);
794	} else {
795		/* no proxy, go straight to target */
796		conn = _fetch_connect(url->host, url->port, af, verbose);
797		purl = NULL;
798	}
799
800	/* check connection */
801	if (conn == NULL)
802		/* _fetch_connect() has already set an error code */
803		return (NULL);
804
805	/* expect welcome message */
806	if ((e = _ftp_chkerr(conn)) != FTP_SERVICE_READY)
807		goto fouch;
808
809	/* authenticate */
810	if ((e = _ftp_authenticate(conn, url, purl)) != FTP_LOGGED_IN)
811		goto fouch;
812
813	/* might as well select mode and type at once */
814#ifdef FTP_FORCE_STREAM_MODE
815	if ((e = _ftp_cmd(conn, "MODE S")) != FTP_OK) /* default is S */
816		goto fouch;
817#endif
818	if ((e = _ftp_cmd(conn, "TYPE I")) != FTP_OK) /* default is A */
819		goto fouch;
820
821	/* done */
822	return (conn);
823
824fouch:
825	if (e != -1)
826		_ftp_seterr(e);
827	_fetch_close(conn);
828	return (NULL);
829}
830
831/*
832 * Disconnect from server
833 */
834static void
835_ftp_disconnect(conn_t *conn)
836{
837	(void)_ftp_cmd(conn, "QUIT");
838	if (conn == cached_connection && conn->ref == 1)
839		cached_connection = NULL;
840	_fetch_close(conn);
841}
842
843/*
844 * Check if we're already connected
845 */
846static int
847_ftp_isconnected(struct url *url)
848{
849	return (cached_connection
850	    && (strcmp(url->host, cached_host.host) == 0)
851	    && (strcmp(url->user, cached_host.user) == 0)
852	    && (strcmp(url->pwd, cached_host.pwd) == 0)
853	    && (url->port == cached_host.port));
854}
855
856/*
857 * Check the cache, reconnect if no luck
858 */
859static conn_t *
860_ftp_cached_connect(struct url *url, struct url *purl, const char *flags)
861{
862	conn_t *conn;
863	int e;
864
865	/* set default port */
866	if (!url->port)
867		url->port = _fetch_default_port(url->scheme);
868
869	/* try to use previously cached connection */
870	if (_ftp_isconnected(url)) {
871		e = _ftp_cmd(cached_connection, "NOOP");
872		if (e == FTP_OK || e == FTP_SYNTAX_ERROR)
873			return (_fetch_ref(cached_connection));
874	}
875
876	/* connect to server */
877	if ((conn = _ftp_connect(url, purl, flags)) == NULL)
878		return (NULL);
879	if (cached_connection)
880		_ftp_disconnect(cached_connection);
881	cached_connection = _fetch_ref(conn);
882	memcpy(&cached_host, url, sizeof *url);
883	return (conn);
884}
885
886/*
887 * Check the proxy settings
888 */
889static struct url *
890_ftp_get_proxy(void)
891{
892	struct url *purl;
893	char *p;
894
895	if (((p = getenv("FTP_PROXY")) || (p = getenv("ftp_proxy")) ||
896		(p = getenv("HTTP_PROXY")) || (p = getenv("http_proxy"))) &&
897	    *p && (purl = fetchParseURL(p)) != NULL) {
898		if (!*purl->scheme) {
899			if (getenv("FTP_PROXY") || getenv("ftp_proxy"))
900				strcpy(purl->scheme, SCHEME_FTP);
901			else
902				strcpy(purl->scheme, SCHEME_HTTP);
903		}
904		if (!purl->port)
905			purl->port = _fetch_default_proxy_port(purl->scheme);
906		if (strcasecmp(purl->scheme, SCHEME_FTP) == 0 ||
907		    strcasecmp(purl->scheme, SCHEME_HTTP) == 0)
908			return (purl);
909		fetchFreeURL(purl);
910	}
911	return (NULL);
912}
913
914/*
915 * Process an FTP request
916 */
917FILE *
918_ftp_request(struct url *url, const char *op, struct url_stat *us,
919    struct url *purl, const char *flags)
920{
921	conn_t *conn;
922	int oflag;
923
924	/* check if we should use HTTP instead */
925	if (purl && strcasecmp(purl->scheme, SCHEME_HTTP) == 0) {
926		if (strcmp(op, "STAT") == 0)
927			return (_http_request(url, "HEAD", us, purl, flags));
928		else if (strcmp(op, "RETR") == 0)
929			return (_http_request(url, "GET", us, purl, flags));
930		/*
931		 * Our HTTP code doesn't support PUT requests yet, so try
932		 * a direct connection.
933		 */
934	}
935
936	/* connect to server */
937	conn = _ftp_cached_connect(url, purl, flags);
938	if (purl)
939		fetchFreeURL(purl);
940	if (conn == NULL)
941		return (NULL);
942
943	/* change directory */
944	if (_ftp_cwd(conn, url->doc) == -1)
945		return (NULL);
946
947	/* stat file */
948	if (us && _ftp_stat(conn, url->doc, us) == -1
949	    && fetchLastErrCode != FETCH_PROTO
950	    && fetchLastErrCode != FETCH_UNAVAIL)
951		return (NULL);
952
953	/* just a stat */
954	if (strcmp(op, "STAT") == 0)
955		return (FILE *)1; /* bogus return value */
956	if (strcmp(op, "STOR") == 0 || strcmp(op, "APPE") == 0)
957		oflag = O_WRONLY;
958	else
959		oflag = O_RDONLY;
960
961	/* initiate the transfer */
962	return (_ftp_transfer(conn, op, url->doc, oflag, url->offset, flags));
963}
964
965/*
966 * Get and stat file
967 */
968FILE *
969fetchXGetFTP(struct url *url, struct url_stat *us, const char *flags)
970{
971	return (_ftp_request(url, "RETR", us, _ftp_get_proxy(), flags));
972}
973
974/*
975 * Get file
976 */
977FILE *
978fetchGetFTP(struct url *url, const char *flags)
979{
980	return (fetchXGetFTP(url, NULL, flags));
981}
982
983/*
984 * Put file
985 */
986FILE *
987fetchPutFTP(struct url *url, const char *flags)
988{
989
990	return _ftp_request(url, CHECK_FLAG('a') ? "APPE" : "STOR", NULL,
991	    _ftp_get_proxy(), flags);
992}
993
994/*
995 * Get file stats
996 */
997int
998fetchStatFTP(struct url *url, struct url_stat *us, const char *flags)
999{
1000
1001	if (_ftp_request(url, "STAT", us, _ftp_get_proxy(), flags) == NULL)
1002		return (-1);
1003	return (0);
1004}
1005
1006/*
1007 * List a directory
1008 */
1009struct url_ent *
1010fetchListFTP(struct url *url __unused, const char *flags __unused)
1011{
1012	warnx("fetchListFTP(): not implemented");
1013	return (NULL);
1014}
1015