xref: /freebsd/lib/libfetch/ftp.c (revision ce4946daa5ce852d28008dac492029500ab2ee95)
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$
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 
97 static struct url cached_host;
98 static int cached_socket;
99 
100 static char *last_reply;
101 static size_t lr_size, lr_length;
102 static 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 */
111 static void
112 unmappedaddr(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  */
134 static 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  */
169 static 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  */
201 static 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  */
216 static 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  */
237 static 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  */
313 struct 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 
321 static int	_ftp_readfn(void *, char *, int);
322 static int	_ftp_writefn(void *, const char *, int);
323 static fpos_t	_ftp_seekfn(void *, fpos_t, int);
324 static int	_ftp_closefn(void *);
325 
326 static 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 
359 static 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 
386 static 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 
400 static 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     if ((r = _ftp_chkerr(io->csd)) != FTP_TRANSFER_COMPLETE)
422 	io->err = r;
423     else
424 	io->err = 0;
425     close(io->csd);
426     io->csd = -1;
427     return io->err ? -1 : 0;
428 }
429 
430 static FILE *
431 _ftp_setup(int csd, int dsd, int mode)
432 {
433     struct ftpio *io;
434     FILE *f;
435 
436     if ((io = malloc(sizeof *io)) == NULL)
437 	return NULL;
438     io->csd = dup(csd);
439     io->dsd = dsd;
440     io->dir = mode;
441     io->eof = io->err = 0;
442     f = funopen(io, _ftp_readfn, _ftp_writefn, _ftp_seekfn, _ftp_closefn);
443     if (f == NULL)
444 	free(io);
445     return f;
446 }
447 
448 /*
449  * Transfer file
450  */
451 static FILE *
452 _ftp_transfer(int cd, const char *oper, const char *file,
453 	      int mode, off_t offset, const char *flags)
454 {
455     struct sockaddr_storage sin;
456     struct sockaddr_in6 *sin6;
457     struct sockaddr_in *sin4;
458     int low, pasv, verbose;
459     int e, sd = -1;
460     socklen_t l;
461     char *s;
462     FILE *df;
463 
464     /* check flags */
465     low = CHECK_FLAG('l');
466     pasv = CHECK_FLAG('p');
467     verbose = CHECK_FLAG('v');
468 
469     /* passive mode */
470     if (!pasv)
471 	pasv = ((s = getenv("FTP_PASSIVE_MODE")) != NULL &&
472 		strncasecmp(s, "no", 2) != 0);
473 
474     /* find our own address, bind, and listen */
475     l = sizeof sin;
476     if (getsockname(cd, (struct sockaddr *)&sin, &l) == -1)
477 	goto sysouch;
478     if (sin.ss_family == AF_INET6)
479 	unmappedaddr((struct sockaddr_in6 *)&sin);
480 
481     /* open data socket */
482     if ((sd = socket(sin.ss_family, SOCK_STREAM, IPPROTO_TCP)) == -1) {
483 	_fetch_syserr();
484 	return NULL;
485     }
486 
487     if (pasv) {
488 	u_char addr[64];
489 	char *ln, *p;
490 	int i;
491 	int port;
492 
493 	/* send PASV command */
494 	if (verbose)
495 	    _fetch_info("setting passive mode");
496 	switch (sin.ss_family) {
497 	case AF_INET:
498 	    if ((e = _ftp_cmd(cd, "PASV")) != FTP_PASSIVE_MODE)
499 		goto ouch;
500 	    break;
501 	case AF_INET6:
502 	    if ((e = _ftp_cmd(cd, "EPSV")) != FTP_EPASSIVE_MODE) {
503 		if (e == -1)
504 		    goto ouch;
505 		if ((e = _ftp_cmd(cd, "LPSV")) != FTP_LPASSIVE_MODE)
506 		    goto ouch;
507 	    }
508 	    break;
509 	default:
510 	    e = FTP_PROTOCOL_ERROR; /* XXX: error code should be prepared */
511 	    goto ouch;
512 	}
513 
514 	/*
515 	 * Find address and port number. The reply to the PASV command
516          * is IMHO the one and only weak point in the FTP protocol.
517 	 */
518 	ln = last_reply;
519       	switch (e) {
520 	case FTP_PASSIVE_MODE:
521 	case FTP_LPASSIVE_MODE:
522 	    for (p = ln + 3; *p && !isdigit(*p); p++)
523 		/* nothing */ ;
524 	    if (!*p) {
525 		e = FTP_PROTOCOL_ERROR;
526 		goto ouch;
527 	    }
528 	    l = (e == FTP_PASSIVE_MODE ? 6 : 21);
529 	    for (i = 0; *p && i < l; i++, p++)
530 		addr[i] = strtol(p, &p, 10);
531 	    if (i < l) {
532 		e = FTP_PROTOCOL_ERROR;
533 		goto ouch;
534 	    }
535 	    break;
536 	case FTP_EPASSIVE_MODE:
537 	    for (p = ln + 3; *p && *p != '('; p++)
538 		/* nothing */ ;
539 	    if (!*p) {
540 		e = FTP_PROTOCOL_ERROR;
541 		goto ouch;
542 	    }
543 	    ++p;
544 	    if (sscanf(p, "%c%c%c%d%c", &addr[0], &addr[1], &addr[2],
545 		       &port, &addr[3]) != 5 ||
546 		addr[0] != addr[1] ||
547 		addr[0] != addr[2] || addr[0] != addr[3]) {
548 		e = FTP_PROTOCOL_ERROR;
549 		goto ouch;
550 	    }
551 	    break;
552 	}
553 
554 	/* seek to required offset */
555 	if (offset)
556 	    if (_ftp_cmd(cd, "REST %lu", (u_long)offset) != FTP_FILE_OK)
557 		goto sysouch;
558 
559 	/* construct sockaddr for data socket */
560 	l = sizeof sin;
561 	if (getpeername(cd, (struct sockaddr *)&sin, &l) == -1)
562 	    goto sysouch;
563 	if (sin.ss_family == AF_INET6)
564 	    unmappedaddr((struct sockaddr_in6 *)&sin);
565 	switch (sin.ss_family) {
566 	case AF_INET6:
567 	    sin6 = (struct sockaddr_in6 *)&sin;
568 	    if (e == FTP_EPASSIVE_MODE)
569 		sin6->sin6_port = htons(port);
570 	    else {
571 		bcopy(addr + 2, (char *)&sin6->sin6_addr, 16);
572 		bcopy(addr + 19, (char *)&sin6->sin6_port, 2);
573 	    }
574 	    break;
575 	case AF_INET:
576 	    sin4 = (struct sockaddr_in *)&sin;
577 	    if (e == FTP_EPASSIVE_MODE)
578 		sin4->sin_port = htons(port);
579 	    else {
580 		bcopy(addr, (char *)&sin4->sin_addr, 4);
581 		bcopy(addr + 4, (char *)&sin4->sin_port, 2);
582 	    }
583 	    break;
584 	default:
585 	    e = FTP_PROTOCOL_ERROR; /* XXX: error code should be prepared */
586 	    break;
587 	}
588 
589 	/* connect to data port */
590 	if (verbose)
591 	    _fetch_info("opening data connection");
592 	if (connect(sd, (struct sockaddr *)&sin, sin.ss_len) == -1)
593 	    goto sysouch;
594 
595 	/* make the server initiate the transfer */
596 	if (verbose)
597 	    _fetch_info("initiating transfer");
598 	e = _ftp_cmd(cd, "%s %s", oper, _ftp_filename(file));
599 	if (e != FTP_CONNECTION_ALREADY_OPEN && e != FTP_OPEN_DATA_CONNECTION)
600 	    goto ouch;
601 
602     } else {
603 	u_int32_t a;
604 	u_short p;
605 	int arg, d;
606 	char *ap;
607 	char hname[INET6_ADDRSTRLEN];
608 
609 	switch (sin.ss_family) {
610 	case AF_INET6:
611 	    ((struct sockaddr_in6 *)&sin)->sin6_port = 0;
612 #ifdef IPV6_PORTRANGE
613 	    arg = low ? IPV6_PORTRANGE_DEFAULT : IPV6_PORTRANGE_HIGH;
614 	    if (setsockopt(sd, IPPROTO_IPV6, IPV6_PORTRANGE,
615 			   (char *)&arg, sizeof(arg)) == -1)
616 		goto sysouch;
617 #endif
618 	    break;
619 	case AF_INET:
620 	    ((struct sockaddr_in *)&sin)->sin_port = 0;
621 	    arg = low ? IP_PORTRANGE_DEFAULT : IP_PORTRANGE_HIGH;
622 	    if (setsockopt(sd, IPPROTO_IP, IP_PORTRANGE,
623 			   (char *)&arg, sizeof arg) == -1)
624 		goto sysouch;
625 	    break;
626 	}
627 	if (verbose)
628 	    _fetch_info("binding data socket");
629 	if (bind(sd, (struct sockaddr *)&sin, sin.ss_len) == -1)
630 	    goto sysouch;
631 	if (listen(sd, 1) == -1)
632 	    goto sysouch;
633 
634 	/* find what port we're on and tell the server */
635 	if (getsockname(sd, (struct sockaddr *)&sin, &l) == -1)
636 	    goto sysouch;
637 	switch (sin.ss_family) {
638 	case AF_INET:
639 	    sin4 = (struct sockaddr_in *)&sin;
640 	    a = ntohl(sin4->sin_addr.s_addr);
641 	    p = ntohs(sin4->sin_port);
642 	    e = _ftp_cmd(cd, "PORT %d,%d,%d,%d,%d,%d",
643 			 (a >> 24) & 0xff, (a >> 16) & 0xff,
644 			 (a >> 8) & 0xff, a & 0xff,
645 			 (p >> 8) & 0xff, p & 0xff);
646 	    break;
647 	case AF_INET6:
648 #define UC(b)	(((int)b)&0xff)
649 	    e = -1;
650 	    sin6 = (struct sockaddr_in6 *)&sin;
651 	    if (getnameinfo((struct sockaddr *)&sin, sin.ss_len,
652 			    hname, sizeof(hname),
653 			    NULL, 0, NI_NUMERICHOST) == 0) {
654 		e = _ftp_cmd(cd, "EPRT |%d|%s|%d|", 2, hname,
655 			     htons(sin6->sin6_port));
656 		if (e == -1)
657 		    goto ouch;
658 	    }
659 	    if (e != FTP_OK) {
660 		ap = (char *)&sin6->sin6_addr;
661 		e = _ftp_cmd(cd,
662      "LPRT %d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d",
663 			     6, 16,
664 			     UC(ap[0]), UC(ap[1]), UC(ap[2]), UC(ap[3]),
665 			     UC(ap[4]), UC(ap[5]), UC(ap[6]), UC(ap[7]),
666 			     UC(ap[8]), UC(ap[9]), UC(ap[10]), UC(ap[11]),
667 			     UC(ap[12]), UC(ap[13]), UC(ap[14]), UC(ap[15]),
668 			     2,
669 			     (ntohs(sin6->sin6_port) >> 8) & 0xff,
670 			     ntohs(sin6->sin6_port)        & 0xff);
671 	    }
672 	    break;
673 	default:
674 	    e = FTP_PROTOCOL_ERROR; /* XXX: error code should be prepared */
675 	    goto ouch;
676 	}
677 	if (e != FTP_OK)
678 	    goto ouch;
679 
680 	/* seek to required offset */
681 	if (offset)
682 	    if (_ftp_cmd(cd, "REST %lu", (u_long)offset) != FTP_FILE_OK)
683 		goto sysouch;
684 
685 	/* make the server initiate the transfer */
686 	if (verbose)
687 	    _fetch_info("initiating transfer");
688 	e = _ftp_cmd(cd, "%s %s", oper, _ftp_filename(file));
689 	if (e != FTP_OPEN_DATA_CONNECTION)
690 	    goto ouch;
691 
692 	/* accept the incoming connection and go to town */
693 	if ((d = accept(sd, NULL, NULL)) == -1)
694 	    goto sysouch;
695 	close(sd);
696 	sd = d;
697     }
698 
699     if ((df = _ftp_setup(cd, sd, mode)) == NULL)
700 	goto sysouch;
701     return df;
702 
703 sysouch:
704     _fetch_syserr();
705     if (sd >= 0)
706 	close(sd);
707     return NULL;
708 
709 ouch:
710     if (e != -1)
711 	_ftp_seterr(e);
712     if (sd >= 0)
713 	close(sd);
714     return NULL;
715 }
716 
717 /*
718  * Log on to FTP server
719  */
720 static int
721 _ftp_connect(struct url *url, struct url *purl, const char *flags)
722 {
723     int cd, e, direct, verbose;
724 #ifdef INET6
725     int af = AF_UNSPEC;
726 #else
727     int af = AF_INET;
728 #endif
729     const char *logname;
730     const char *user;
731     const char *pwd;
732     char localhost[MAXHOSTNAMELEN];
733     char pbuf[MAXHOSTNAMELEN + MAXLOGNAME + 1];
734 
735     direct = CHECK_FLAG('d');
736     verbose = CHECK_FLAG('v');
737     if (CHECK_FLAG('4'))
738 	af = AF_INET;
739     else if (CHECK_FLAG('6'))
740 	af = AF_INET6;
741 
742     if (direct)
743 	purl = NULL;
744 
745     /* check for proxy */
746     if (purl) {
747 	/* XXX proxy authentication! */
748 	cd = _fetch_connect(purl->host, purl->port, af, verbose);
749     } else {
750 	/* no proxy, go straight to target */
751 	cd = _fetch_connect(url->host, url->port, af, verbose);
752 	purl = NULL;
753     }
754 
755     /* check connection */
756     if (cd == -1) {
757 	_fetch_syserr();
758 	return NULL;
759     }
760 
761     /* expect welcome message */
762     if ((e = _ftp_chkerr(cd)) != FTP_SERVICE_READY)
763 	goto fouch;
764 
765     /* XXX FTP_AUTH, and maybe .netrc */
766 
767     /* send user name and password */
768     user = url->user;
769     if (!user || !*user)
770 	user = getenv("FTP_LOGIN");
771     if (!user || !*user)
772 	user = FTP_ANONYMOUS_USER;
773     if (purl && url->port == _fetch_default_port(url->scheme))
774 	e = _ftp_cmd(cd, "USER %s@%s", user, url->host);
775     else if (purl)
776 	e = _ftp_cmd(cd, "USER %s@%s@%d", user, url->host, url->port);
777     else
778 	e = _ftp_cmd(cd, "USER %s", user);
779 
780     /* did the server request a password? */
781     if (e == FTP_NEED_PASSWORD) {
782 	pwd = url->pwd;
783 	if (!pwd || !*pwd)
784 	    pwd = getenv("FTP_PASSWORD");
785 	if (!pwd || !*pwd) {
786 	    if ((logname = getlogin()) == 0)
787 		logname = FTP_ANONYMOUS_USER;
788 	    gethostname(localhost, sizeof localhost);
789 	    snprintf(pbuf, sizeof pbuf, "%s@%s", logname, localhost);
790 	    pwd = pbuf;
791 	}
792 	e = _ftp_cmd(cd, "PASS %s", pwd);
793     }
794 
795     /* did the server request an account? */
796     if (e == FTP_NEED_ACCOUNT)
797 	goto fouch;
798 
799     /* we should be done by now */
800     if (e != FTP_LOGGED_IN)
801 	goto fouch;
802 
803     /* might as well select mode and type at once */
804 #ifdef FTP_FORCE_STREAM_MODE
805     if ((e = _ftp_cmd(cd, "MODE S")) != FTP_OK) /* default is S */
806 	goto fouch;
807 #endif
808     if ((e = _ftp_cmd(cd, "TYPE I")) != FTP_OK) /* default is A */
809 	goto fouch;
810 
811     /* done */
812     return cd;
813 
814 fouch:
815     if (e != -1)
816 	_ftp_seterr(e);
817     close(cd);
818     return NULL;
819 }
820 
821 /*
822  * Disconnect from server
823  */
824 static void
825 _ftp_disconnect(int cd)
826 {
827     (void)_ftp_cmd(cd, "QUIT");
828     close(cd);
829 }
830 
831 /*
832  * Check if we're already connected
833  */
834 static int
835 _ftp_isconnected(struct url *url)
836 {
837     return (cached_socket
838 	    && (strcmp(url->host, cached_host.host) == 0)
839 	    && (strcmp(url->user, cached_host.user) == 0)
840 	    && (strcmp(url->pwd, cached_host.pwd) == 0)
841 	    && (url->port == cached_host.port));
842 }
843 
844 /*
845  * Check the cache, reconnect if no luck
846  */
847 static int
848 _ftp_cached_connect(struct url *url, struct url *purl, const char *flags)
849 {
850     int e, cd;
851 
852     cd = -1;
853 
854     /* set default port */
855     if (!url->port)
856 	url->port = _fetch_default_port(url->scheme);
857 
858     /* try to use previously cached connection */
859     if (_ftp_isconnected(url)) {
860 	e = _ftp_cmd(cached_socket, "NOOP");
861 	if (e == FTP_OK || e == FTP_SYNTAX_ERROR)
862 	    return cached_socket;
863     }
864 
865     /* connect to server */
866     if ((cd = _ftp_connect(url, purl, flags)) == -1)
867 	return -1;
868     if (cached_socket)
869 	_ftp_disconnect(cached_socket);
870     cached_socket = cd;
871     memcpy(&cached_host, url, sizeof *url);
872     return cd;
873 }
874 
875 /*
876  * Check the proxy settings
877  */
878 static struct url *
879 _ftp_get_proxy(void)
880 {
881     struct url *purl;
882     char *p;
883 
884     if (((p = getenv("FTP_PROXY")) || (p = getenv("ftp_proxy")) ||
885 	 (p = getenv("HTTP_PROXY")) || (p = getenv("http_proxy"))) &&
886 	*p && (purl = fetchParseURL(p)) != NULL) {
887 	if (!*purl->scheme) {
888 	    if (getenv("FTP_PROXY") || getenv("ftp_proxy"))
889 		strcpy(purl->scheme, SCHEME_FTP);
890 	    else
891 		strcpy(purl->scheme, SCHEME_HTTP);
892 	}
893 	if (!purl->port)
894 	    purl->port = _fetch_default_proxy_port(purl->scheme);
895 	if (strcasecmp(purl->scheme, SCHEME_FTP) == 0 ||
896 	    strcasecmp(purl->scheme, SCHEME_HTTP) == 0)
897 	    return purl;
898 	fetchFreeURL(purl);
899     }
900     return NULL;
901 }
902 
903 /*
904  * Get and stat file
905  */
906 FILE *
907 fetchXGetFTP(struct url *url, struct url_stat *us, const char *flags)
908 {
909     struct url *purl;
910     int cd;
911 
912     /* get the proxy URL, and check if we should use HTTP instead */
913     if (!CHECK_FLAG('d') && (purl = _ftp_get_proxy()) != NULL) {
914 	if (strcasecmp(purl->scheme, SCHEME_HTTP) == 0)
915 	    return _http_request(url, "GET", us, purl, flags);
916     } else {
917 	purl = NULL;
918     }
919 
920     /* connect to server */
921     cd = _ftp_cached_connect(url, purl, flags);
922     if (purl)
923 	fetchFreeURL(purl);
924     if (cd == NULL)
925 	return NULL;
926 
927     /* change directory */
928     if (_ftp_cwd(cd, url->doc) == -1)
929 	return NULL;
930 
931     /* stat file */
932     if (us && _ftp_stat(cd, url->doc, us) == -1
933 	&& fetchLastErrCode != FETCH_PROTO
934 	&& fetchLastErrCode != FETCH_UNAVAIL)
935 	return NULL;
936 
937     /* initiate the transfer */
938     return _ftp_transfer(cd, "RETR", url->doc, O_RDONLY, url->offset, flags);
939 }
940 
941 /*
942  * Get file
943  */
944 FILE *
945 fetchGetFTP(struct url *url, const char *flags)
946 {
947     return fetchXGetFTP(url, NULL, flags);
948 }
949 
950 /*
951  * Put file
952  */
953 FILE *
954 fetchPutFTP(struct url *url, const char *flags)
955 {
956     struct url *purl;
957     int cd;
958 
959     /* get the proxy URL, and check if we should use HTTP instead */
960     if (!CHECK_FLAG('d') && (purl = _ftp_get_proxy()) != NULL) {
961 	if (strcasecmp(purl->scheme, SCHEME_HTTP) == 0)
962 	    /* XXX HTTP PUT is not implemented, so try without the proxy */
963 	    purl = NULL;
964     } else {
965 	purl = NULL;
966     }
967 
968     /* connect to server */
969     cd = _ftp_cached_connect(url, purl, flags);
970     if (purl)
971 	fetchFreeURL(purl);
972     if (cd == NULL)
973 	return NULL;
974 
975     /* change directory */
976     if (_ftp_cwd(cd, url->doc) == -1)
977 	return NULL;
978 
979     /* initiate the transfer */
980     return _ftp_transfer(cd, CHECK_FLAG('a') ? "APPE" : "STOR",
981 			 url->doc, O_WRONLY, url->offset, flags);
982 }
983 
984 /*
985  * Get file stats
986  */
987 int
988 fetchStatFTP(struct url *url, struct url_stat *us, const char *flags)
989 {
990     struct url *purl;
991     int cd;
992 
993     /* get the proxy URL, and check if we should use HTTP instead */
994     if (!CHECK_FLAG('d') && (purl = _ftp_get_proxy()) != NULL) {
995 	if (strcasecmp(purl->scheme, SCHEME_HTTP) == 0) {
996 	    FILE *f;
997 
998 	    if ((f = _http_request(url, "HEAD", us, purl, flags)) == NULL)
999 		return -1;
1000 	    fclose(f);
1001 	    return 0;
1002 	}
1003     } else {
1004 	purl = NULL;
1005     }
1006 
1007     /* connect to server */
1008     cd = _ftp_cached_connect(url, purl, flags);
1009     if (purl)
1010 	fetchFreeURL(purl);
1011     if (cd == NULL)
1012 	return NULL;
1013 
1014     /* change directory */
1015     if (_ftp_cwd(cd, url->doc) == -1)
1016 	return -1;
1017 
1018     /* stat file */
1019     return _ftp_stat(cd, url->doc, us);
1020 }
1021 
1022 /*
1023  * List a directory
1024  */
1025 struct url_ent *
1026 fetchListFTP(struct url *url, const char *flags)
1027 {
1028     warnx("fetchListFTP(): not implemented");
1029     return NULL;
1030 }
1031