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