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