ftp.c revision 77238
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 * $FreeBSD: head/lib/libfetch/ftp.c 77238 2001-05-26 19:37:15Z des $
29 */
30
31/*
32 * Portions of this code were taken from or based on ftpio.c:
33 *
34 * ----------------------------------------------------------------------------
35 * "THE BEER-WARE LICENSE" (Revision 42):
36 * <phk@login.dknet.dk> wrote this file.  As long as you retain this notice you
37 * can do whatever you want with this stuff. If we meet some day, and you think
38 * this stuff is worth it, you can buy me a beer in return.   Poul-Henning Kamp
39 * ----------------------------------------------------------------------------
40 *
41 * Major Changelog:
42 *
43 * Dag-Erling Co�dan Sm�rgrav
44 * 9 Jun 1998
45 *
46 * Incorporated into libfetch
47 *
48 * Jordan K. Hubbard
49 * 17 Jan 1996
50 *
51 * Turned inside out. Now returns xfers as new file ids, not as a special
52 * `state' of FTP_t
53 *
54 * $ftpioId: ftpio.c,v 1.30 1998/04/11 07:28:53 phk Exp $
55 *
56 */
57
58#include <sys/param.h>
59#include <sys/socket.h>
60#include <netinet/in.h>
61
62#include <ctype.h>
63#include <err.h>
64#include <errno.h>
65#include <fcntl.h>
66#include <netdb.h>
67#include <stdarg.h>
68#include <stdio.h>
69#include <stdlib.h>
70#include <string.h>
71#include <time.h>
72#include <unistd.h>
73
74#include "fetch.h"
75#include "common.h"
76#include "ftperr.h"
77
78#define FTP_ANONYMOUS_USER	"anonymous"
79
80#define FTP_CONNECTION_ALREADY_OPEN	125
81#define FTP_OPEN_DATA_CONNECTION	150
82#define FTP_OK				200
83#define FTP_FILE_STATUS			213
84#define FTP_SERVICE_READY		220
85#define FTP_TRANSFER_COMPLETE		226
86#define FTP_PASSIVE_MODE		227
87#define FTP_LPASSIVE_MODE		228
88#define FTP_EPASSIVE_MODE		229
89#define FTP_LOGGED_IN			230
90#define FTP_FILE_ACTION_OK		250
91#define FTP_NEED_PASSWORD		331
92#define FTP_NEED_ACCOUNT		332
93#define FTP_FILE_OK			350
94#define FTP_SYNTAX_ERROR		500
95#define FTP_PROTOCOL_ERROR		999
96
97static struct url cached_host;
98static int cached_socket;
99
100static char *last_reply;
101static size_t lr_size, lr_length;
102static int last_code;
103
104#define isftpreply(foo) (isdigit(foo[0]) && isdigit(foo[1]) \
105			 && isdigit(foo[2]) \
106                         && (foo[3] == ' ' || foo[3] == '\0'))
107#define isftpinfo(foo) (isdigit(foo[0]) && isdigit(foo[1]) \
108			&& isdigit(foo[2]) && foo[3] == '-')
109
110/* translate IPv4 mapped IPv6 address to IPv4 address */
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(int cd)
136{
137    if (_fetch_getln(cd, &last_reply, &lr_size, &lr_length) == -1) {
138	_fetch_syserr();
139	return -1;
140    }
141    if (isftpinfo(last_reply)) {
142	while (lr_length && !isftpreply(last_reply)) {
143	    if (_fetch_getln(cd, &last_reply, &lr_size, &lr_length) == -1) {
144		_fetch_syserr();
145		return -1;
146	    }
147	}
148    }
149
150    while (lr_length && isspace(last_reply[lr_length-1]))
151	lr_length--;
152    last_reply[lr_length] = 0;
153
154    if (!isftpreply(last_reply)) {
155	_ftp_seterr(FTP_PROTOCOL_ERROR);
156	return -1;
157    }
158
159    last_code = (last_reply[0] - '0') * 100
160	+ (last_reply[1] - '0') * 10
161	+ (last_reply[2] - '0');
162
163    return last_code;
164}
165
166/*
167 * Send a command and check reply
168 */
169static int
170_ftp_cmd(int cd, 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(cd, msg, len);
188    free(msg);
189
190    if (r == -1) {
191	_fetch_syserr();
192	return -1;
193    }
194
195    return _ftp_chkerr(cd);
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
214 * specified file.
215 */
216static int
217_ftp_cwd(int cd, const char *file)
218{
219    char *s;
220    int e;
221
222    if ((s = strrchr(file, '/')) == NULL || s == file) {
223	e = _ftp_cmd(cd, "CWD /");
224    } else {
225	e = _ftp_cmd(cd, "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(int cd, 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(cd, "SIZE %s", s)) != FTP_FILE_STATUS) {
255	_ftp_seterr(e);
256	return -1;
257    }
258    for (ln = last_reply + 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: [\033[1m%lld\033[m]\n", us->size));
270
271    if ((e = _ftp_cmd(cd, "MDTM %s", s)) != FTP_FILE_STATUS) {
272	_ftp_seterr(e);
273	return -1;
274    }
275    for (ln = last_reply + 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, "last modified: [\033[1m%04d-%02d-%02d "
304		  "%02d:%02d:%02d\033[m]\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    int		 csd;		/* Control socket descriptor */
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->csd == -1 || 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 _ftp_closefn(v);
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->csd == -1 || 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, int whence)
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->csd == -1 || 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->csd);
422    close(io->csd);
423    free(io);
424    return (r == FTP_TRANSFER_COMPLETE) ? 0 : -1;
425}
426
427static FILE *
428_ftp_setup(int csd, 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->csd = dup(csd);
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(int cd, const char *oper, const char *file,
450	      int mode, off_t offset, const char *flags)
451{
452    struct sockaddr_storage sin;
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 sin;
473    if (getsockname(cd, (struct sockaddr *)&sin, &l) == -1)
474	goto sysouch;
475    if (sin.ss_family == AF_INET6)
476	unmappedaddr((struct sockaddr_in6 *)&sin);
477
478    /* open data socket */
479    if ((sd = socket(sin.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	int i;
488	int port;
489
490	/* send PASV command */
491	if (verbose)
492	    _fetch_info("setting passive mode");
493	switch (sin.ss_family) {
494	case AF_INET:
495	    if ((e = _ftp_cmd(cd, "PASV")) != FTP_PASSIVE_MODE)
496		goto ouch;
497	    break;
498	case AF_INET6:
499	    if ((e = _ftp_cmd(cd, "EPSV")) != FTP_EPASSIVE_MODE) {
500		if (e == -1)
501		    goto ouch;
502		if ((e = _ftp_cmd(cd, "LPSV")) != FTP_LPASSIVE_MODE)
503		    goto ouch;
504	    }
505	    break;
506	default:
507	    e = FTP_PROTOCOL_ERROR; /* XXX: error code should be prepared */
508	    goto ouch;
509	}
510
511	/*
512	 * Find address and port number. The reply to the PASV command
513         * is IMHO the one and only weak point in the FTP protocol.
514	 */
515	ln = last_reply;
516      	switch (e) {
517	case FTP_PASSIVE_MODE:
518	case FTP_LPASSIVE_MODE:
519	    for (p = ln + 3; *p && !isdigit(*p); p++)
520		/* nothing */ ;
521	    if (!*p) {
522		e = FTP_PROTOCOL_ERROR;
523		goto ouch;
524	    }
525	    l = (e == FTP_PASSIVE_MODE ? 6 : 21);
526	    for (i = 0; *p && i < l; i++, p++)
527		addr[i] = strtol(p, &p, 10);
528	    if (i < l) {
529		e = FTP_PROTOCOL_ERROR;
530		goto ouch;
531	    }
532	    break;
533	case FTP_EPASSIVE_MODE:
534	    for (p = ln + 3; *p && *p != '('; p++)
535		/* nothing */ ;
536	    if (!*p) {
537		e = FTP_PROTOCOL_ERROR;
538		goto ouch;
539	    }
540	    ++p;
541	    if (sscanf(p, "%c%c%c%d%c", &addr[0], &addr[1], &addr[2],
542		       &port, &addr[3]) != 5 ||
543		addr[0] != addr[1] ||
544		addr[0] != addr[2] || addr[0] != addr[3]) {
545		e = FTP_PROTOCOL_ERROR;
546		goto ouch;
547	    }
548	    break;
549	}
550
551	/* seek to required offset */
552	if (offset)
553	    if (_ftp_cmd(cd, "REST %lu", (u_long)offset) != FTP_FILE_OK)
554		goto sysouch;
555
556	/* construct sockaddr for data socket */
557	l = sizeof sin;
558	if (getpeername(cd, (struct sockaddr *)&sin, &l) == -1)
559	    goto sysouch;
560	if (sin.ss_family == AF_INET6)
561	    unmappedaddr((struct sockaddr_in6 *)&sin);
562	switch (sin.ss_family) {
563	case AF_INET6:
564	    sin6 = (struct sockaddr_in6 *)&sin;
565	    if (e == FTP_EPASSIVE_MODE)
566		sin6->sin6_port = htons(port);
567	    else {
568		bcopy(addr + 2, (char *)&sin6->sin6_addr, 16);
569		bcopy(addr + 19, (char *)&sin6->sin6_port, 2);
570	    }
571	    break;
572	case AF_INET:
573	    sin4 = (struct sockaddr_in *)&sin;
574	    if (e == FTP_EPASSIVE_MODE)
575		sin4->sin_port = htons(port);
576	    else {
577		bcopy(addr, (char *)&sin4->sin_addr, 4);
578		bcopy(addr + 4, (char *)&sin4->sin_port, 2);
579	    }
580	    break;
581	default:
582	    e = FTP_PROTOCOL_ERROR; /* XXX: error code should be prepared */
583	    break;
584	}
585
586	/* connect to data port */
587	if (verbose)
588	    _fetch_info("opening data connection");
589	if (connect(sd, (struct sockaddr *)&sin, sin.ss_len) == -1)
590	    goto sysouch;
591
592	/* make the server initiate the transfer */
593	if (verbose)
594	    _fetch_info("initiating transfer");
595	e = _ftp_cmd(cd, "%s %s", oper, _ftp_filename(file));
596	if (e != FTP_CONNECTION_ALREADY_OPEN && e != FTP_OPEN_DATA_CONNECTION)
597	    goto ouch;
598
599    } else {
600	u_int32_t a;
601	u_short p;
602	int arg, d;
603	char *ap;
604	char hname[INET6_ADDRSTRLEN];
605
606	switch (sin.ss_family) {
607	case AF_INET6:
608	    ((struct sockaddr_in6 *)&sin)->sin6_port = 0;
609#ifdef IPV6_PORTRANGE
610	    arg = low ? IPV6_PORTRANGE_DEFAULT : IPV6_PORTRANGE_HIGH;
611	    if (setsockopt(sd, IPPROTO_IPV6, IPV6_PORTRANGE,
612			   (char *)&arg, sizeof(arg)) == -1)
613		goto sysouch;
614#endif
615	    break;
616	case AF_INET:
617	    ((struct sockaddr_in *)&sin)->sin_port = 0;
618	    arg = low ? IP_PORTRANGE_DEFAULT : IP_PORTRANGE_HIGH;
619	    if (setsockopt(sd, IPPROTO_IP, IP_PORTRANGE,
620			   (char *)&arg, sizeof arg) == -1)
621		goto sysouch;
622	    break;
623	}
624	if (verbose)
625	    _fetch_info("binding data socket");
626	if (bind(sd, (struct sockaddr *)&sin, sin.ss_len) == -1)
627	    goto sysouch;
628	if (listen(sd, 1) == -1)
629	    goto sysouch;
630
631	/* find what port we're on and tell the server */
632	if (getsockname(sd, (struct sockaddr *)&sin, &l) == -1)
633	    goto sysouch;
634	switch (sin.ss_family) {
635	case AF_INET:
636	    sin4 = (struct sockaddr_in *)&sin;
637	    a = ntohl(sin4->sin_addr.s_addr);
638	    p = ntohs(sin4->sin_port);
639	    e = _ftp_cmd(cd, "PORT %d,%d,%d,%d,%d,%d",
640			 (a >> 24) & 0xff, (a >> 16) & 0xff,
641			 (a >> 8) & 0xff, a & 0xff,
642			 (p >> 8) & 0xff, p & 0xff);
643	    break;
644	case AF_INET6:
645#define UC(b)	(((int)b)&0xff)
646	    e = -1;
647	    sin6 = (struct sockaddr_in6 *)&sin;
648	    if (getnameinfo((struct sockaddr *)&sin, sin.ss_len,
649			    hname, sizeof(hname),
650			    NULL, 0, NI_NUMERICHOST) == 0) {
651		e = _ftp_cmd(cd, "EPRT |%d|%s|%d|", 2, hname,
652			     htons(sin6->sin6_port));
653		if (e == -1)
654		    goto ouch;
655	    }
656	    if (e != FTP_OK) {
657		ap = (char *)&sin6->sin6_addr;
658		e = _ftp_cmd(cd,
659     "LPRT %d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d",
660			     6, 16,
661			     UC(ap[0]), UC(ap[1]), UC(ap[2]), UC(ap[3]),
662			     UC(ap[4]), UC(ap[5]), UC(ap[6]), UC(ap[7]),
663			     UC(ap[8]), UC(ap[9]), UC(ap[10]), UC(ap[11]),
664			     UC(ap[12]), UC(ap[13]), UC(ap[14]), UC(ap[15]),
665			     2,
666			     (ntohs(sin6->sin6_port) >> 8) & 0xff,
667			     ntohs(sin6->sin6_port)        & 0xff);
668	    }
669	    break;
670	default:
671	    e = FTP_PROTOCOL_ERROR; /* XXX: error code should be prepared */
672	    goto ouch;
673	}
674	if (e != FTP_OK)
675	    goto ouch;
676
677	/* seek to required offset */
678	if (offset)
679	    if (_ftp_cmd(cd, "REST %lu", (u_long)offset) != FTP_FILE_OK)
680		goto sysouch;
681
682	/* make the server initiate the transfer */
683	if (verbose)
684	    _fetch_info("initiating transfer");
685	e = _ftp_cmd(cd, "%s %s", oper, _ftp_filename(file));
686	if (e != FTP_OPEN_DATA_CONNECTION)
687	    goto ouch;
688
689	/* accept the incoming connection and go to town */
690	if ((d = accept(sd, NULL, NULL)) == -1)
691	    goto sysouch;
692	close(sd);
693	sd = d;
694    }
695
696    if ((df = _ftp_setup(cd, sd, mode)) == NULL)
697	goto sysouch;
698    return df;
699
700sysouch:
701    _fetch_syserr();
702    if (sd >= 0)
703	close(sd);
704    return NULL;
705
706ouch:
707    if (e != -1)
708	_ftp_seterr(e);
709    if (sd >= 0)
710	close(sd);
711    return NULL;
712}
713
714/*
715 * Authenticate
716 */
717static int
718_ftp_authenticate(int cd, struct url *url, struct url *purl)
719{
720    char *user, *pwd, *logname;
721    char pbuf[MAXHOSTNAMELEN + MAXLOGNAME + 1];
722    int e, len;
723
724    /* XXX FTP_AUTH, and maybe .netrc */
725
726    /* send user name and password */
727    user = url->user;
728    if (!user || !*user)
729	user = getenv("FTP_LOGIN");
730    if (!user || !*user)
731	user = FTP_ANONYMOUS_USER;
732    if (purl && url->port == _fetch_default_port(url->scheme))
733	e = _ftp_cmd(cd, "USER %s@%s", user, url->host);
734    else if (purl)
735	e = _ftp_cmd(cd, "USER %s@%s@%d", user, url->host, url->port);
736    else
737	e = _ftp_cmd(cd, "USER %s", user);
738
739    /* did the server request a password? */
740    if (e == FTP_NEED_PASSWORD) {
741	pwd = url->pwd;
742	if (!pwd || !*pwd)
743	    pwd = getenv("FTP_PASSWORD");
744	if (!pwd || !*pwd) {
745	    if ((logname = getlogin()) == 0)
746		logname = FTP_ANONYMOUS_USER;
747	    len = snprintf(pbuf, MAXLOGNAME + 1, "%s@", logname);
748	    gethostname(pbuf + len, sizeof pbuf - len);
749	    pwd = pbuf;
750	}
751	e = _ftp_cmd(cd, "PASS %s", pwd);
752    }
753
754    return e;
755}
756
757/*
758 * Log on to FTP server
759 */
760static int
761_ftp_connect(struct url *url, struct url *purl, const char *flags)
762{
763    int cd, e, direct, verbose;
764#ifdef INET6
765    int af = AF_UNSPEC;
766#else
767    int af = AF_INET;
768#endif
769
770    direct = CHECK_FLAG('d');
771    verbose = CHECK_FLAG('v');
772    if (CHECK_FLAG('4'))
773	af = AF_INET;
774    else if (CHECK_FLAG('6'))
775	af = AF_INET6;
776
777    if (direct)
778	purl = NULL;
779
780    /* check for proxy */
781    if (purl) {
782	/* XXX proxy authentication! */
783	cd = _fetch_connect(purl->host, purl->port, af, verbose);
784    } else {
785	/* no proxy, go straight to target */
786	cd = _fetch_connect(url->host, url->port, af, verbose);
787	purl = NULL;
788    }
789
790    /* check connection */
791    if (cd == -1) {
792	_fetch_syserr();
793	return NULL;
794    }
795
796    /* expect welcome message */
797    if ((e = _ftp_chkerr(cd)) != FTP_SERVICE_READY)
798	goto fouch;
799
800    /* authenticate */
801    if ((e = _ftp_authenticate(cd, url, purl)) != FTP_LOGGED_IN)
802	goto fouch;
803
804    /* might as well select mode and type at once */
805#ifdef FTP_FORCE_STREAM_MODE
806    if ((e = _ftp_cmd(cd, "MODE S")) != FTP_OK) /* default is S */
807	goto fouch;
808#endif
809    if ((e = _ftp_cmd(cd, "TYPE I")) != FTP_OK) /* default is A */
810	goto fouch;
811
812    /* done */
813    return cd;
814
815fouch:
816    if (e != -1)
817	_ftp_seterr(e);
818    close(cd);
819    return NULL;
820}
821
822/*
823 * Disconnect from server
824 */
825static void
826_ftp_disconnect(int cd)
827{
828    (void)_ftp_cmd(cd, "QUIT");
829    close(cd);
830}
831
832/*
833 * Check if we're already connected
834 */
835static int
836_ftp_isconnected(struct url *url)
837{
838    return (cached_socket
839	    && (strcmp(url->host, cached_host.host) == 0)
840	    && (strcmp(url->user, cached_host.user) == 0)
841	    && (strcmp(url->pwd, cached_host.pwd) == 0)
842	    && (url->port == cached_host.port));
843}
844
845/*
846 * Check the cache, reconnect if no luck
847 */
848static int
849_ftp_cached_connect(struct url *url, struct url *purl, const char *flags)
850{
851    int e, cd;
852
853    cd = -1;
854
855    /* set default port */
856    if (!url->port)
857	url->port = _fetch_default_port(url->scheme);
858
859    /* try to use previously cached connection */
860    if (_ftp_isconnected(url)) {
861	e = _ftp_cmd(cached_socket, "NOOP");
862	if (e == FTP_OK || e == FTP_SYNTAX_ERROR)
863	    return cached_socket;
864    }
865
866    /* connect to server */
867    if ((cd = _ftp_connect(url, purl, flags)) == -1)
868	return -1;
869    if (cached_socket)
870	_ftp_disconnect(cached_socket);
871    cached_socket = cd;
872    memcpy(&cached_host, url, sizeof *url);
873    return cd;
874}
875
876/*
877 * Check the proxy settings
878 */
879static struct url *
880_ftp_get_proxy(void)
881{
882    struct url *purl;
883    char *p;
884
885    if (((p = getenv("FTP_PROXY")) || (p = getenv("ftp_proxy")) ||
886	 (p = getenv("HTTP_PROXY")) || (p = getenv("http_proxy"))) &&
887	*p && (purl = fetchParseURL(p)) != NULL) {
888	if (!*purl->scheme) {
889	    if (getenv("FTP_PROXY") || getenv("ftp_proxy"))
890		strcpy(purl->scheme, SCHEME_FTP);
891	    else
892		strcpy(purl->scheme, SCHEME_HTTP);
893	}
894	if (!purl->port)
895	    purl->port = _fetch_default_proxy_port(purl->scheme);
896	if (strcasecmp(purl->scheme, SCHEME_FTP) == 0 ||
897	    strcasecmp(purl->scheme, SCHEME_HTTP) == 0)
898	    return purl;
899	fetchFreeURL(purl);
900    }
901    return NULL;
902}
903
904/*
905 * Get and stat file
906 */
907FILE *
908fetchXGetFTP(struct url *url, struct url_stat *us, const char *flags)
909{
910    struct url *purl;
911    int cd;
912
913    /* get the proxy URL, and check if we should use HTTP instead */
914    if (!CHECK_FLAG('d') && (purl = _ftp_get_proxy()) != NULL) {
915	if (strcasecmp(purl->scheme, SCHEME_HTTP) == 0)
916	    return _http_request(url, "GET", us, purl, flags);
917    } else {
918	purl = NULL;
919    }
920
921    /* connect to server */
922    cd = _ftp_cached_connect(url, purl, flags);
923    if (purl)
924	fetchFreeURL(purl);
925    if (cd == NULL)
926	return NULL;
927
928    /* change directory */
929    if (_ftp_cwd(cd, url->doc) == -1)
930	return NULL;
931
932    /* stat file */
933    if (us && _ftp_stat(cd, url->doc, us) == -1
934	&& fetchLastErrCode != FETCH_PROTO
935	&& fetchLastErrCode != FETCH_UNAVAIL)
936	return NULL;
937
938    /* initiate the transfer */
939    return _ftp_transfer(cd, "RETR", url->doc, O_RDONLY, url->offset, flags);
940}
941
942/*
943 * Get file
944 */
945FILE *
946fetchGetFTP(struct url *url, const char *flags)
947{
948    return fetchXGetFTP(url, NULL, flags);
949}
950
951/*
952 * Put file
953 */
954FILE *
955fetchPutFTP(struct url *url, const char *flags)
956{
957    struct url *purl;
958    int cd;
959
960    /* get the proxy URL, and check if we should use HTTP instead */
961    if (!CHECK_FLAG('d') && (purl = _ftp_get_proxy()) != NULL) {
962	if (strcasecmp(purl->scheme, SCHEME_HTTP) == 0)
963	    /* XXX HTTP PUT is not implemented, so try without the proxy */
964	    purl = NULL;
965    } else {
966	purl = NULL;
967    }
968
969    /* connect to server */
970    cd = _ftp_cached_connect(url, purl, flags);
971    if (purl)
972	fetchFreeURL(purl);
973    if (cd == NULL)
974	return NULL;
975
976    /* change directory */
977    if (_ftp_cwd(cd, url->doc) == -1)
978	return NULL;
979
980    /* initiate the transfer */
981    return _ftp_transfer(cd, CHECK_FLAG('a') ? "APPE" : "STOR",
982			 url->doc, O_WRONLY, url->offset, flags);
983}
984
985/*
986 * Get file stats
987 */
988int
989fetchStatFTP(struct url *url, struct url_stat *us, const char *flags)
990{
991    struct url *purl;
992    int cd;
993
994    /* get the proxy URL, and check if we should use HTTP instead */
995    if (!CHECK_FLAG('d') && (purl = _ftp_get_proxy()) != NULL) {
996	if (strcasecmp(purl->scheme, SCHEME_HTTP) == 0) {
997	    FILE *f;
998
999	    if ((f = _http_request(url, "HEAD", us, purl, flags)) == NULL)
1000		return -1;
1001	    fclose(f);
1002	    return 0;
1003	}
1004    } else {
1005	purl = NULL;
1006    }
1007
1008    /* connect to server */
1009    cd = _ftp_cached_connect(url, purl, flags);
1010    if (purl)
1011	fetchFreeURL(purl);
1012    if (cd == NULL)
1013	return NULL;
1014
1015    /* change directory */
1016    if (_ftp_cwd(cd, url->doc) == -1)
1017	return -1;
1018
1019    /* stat file */
1020    return _ftp_stat(cd, url->doc, us);
1021}
1022
1023/*
1024 * List a directory
1025 */
1026struct url_ent *
1027fetchListFTP(struct url *url, const char *flags)
1028{
1029    warnx("fetchListFTP(): not implemented");
1030    return NULL;
1031}
1032