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