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