xref: /netbsd-src/external/bsd/fetch/dist/libfetch/ftp.c (revision 62a8debe1dc62962e18a1c918def78666141273b)
1 /*	$NetBSD: ftp.c,v 1.1.1.10 2010/01/30 21:26:13 joerg Exp $	*/
2 /*-
3  * Copyright (c) 1998-2004 Dag-Erling Co�dan Sm�rgrav
4  * Copyright (c) 2008, 2009, 2010 Joerg Sonnenberger <joerg@NetBSD.org>
5  * All rights reserved.
6  *
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions
9  * are met:
10  * 1. Redistributions of source code must retain the above copyright
11  *    notice, this list of conditions and the following disclaimer
12  *    in this position and unchanged.
13  * 2. Redistributions in binary form must reproduce the above copyright
14  *    notice, this list of conditions and the following disclaimer in the
15  *    documentation and/or other materials provided with the distribution.
16  * 3. The name of the author may not be used to endorse or promote products
17  *    derived from this software without specific prior written permission
18  *
19  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
20  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
21  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
22  * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
23  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
24  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
25  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
26  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
27  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
28  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
29  *
30  * $FreeBSD: ftp.c,v 1.101 2008/01/23 20:57:59 des Exp $
31  */
32 
33 /*
34  * Portions of this code were taken from or based on ftpio.c:
35  *
36  * ----------------------------------------------------------------------------
37  * "THE BEER-WARE LICENSE" (Revision 42):
38  * <phk@FreeBSD.org> wrote this file.  As long as you retain this notice you
39  * can do whatever you want with this stuff. If we meet some day, and you think
40  * this stuff is worth it, you can buy me a beer in return.   Poul-Henning Kamp
41  * ----------------------------------------------------------------------------
42  *
43  * Major Changelog:
44  *
45  * Dag-Erling Co�dan Sm�rgrav
46  * 9 Jun 1998
47  *
48  * Incorporated into libfetch
49  *
50  * Jordan K. Hubbard
51  * 17 Jan 1996
52  *
53  * Turned inside out. Now returns xfers as new file ids, not as a special
54  * `state' of FTP_t
55  *
56  * $ftpioId: ftpio.c,v 1.30 1998/04/11 07:28:53 phk Exp $
57  *
58  */
59 
60 #ifdef __linux__
61 /* Keep this down to Linux, it can create surprises else where. */
62 #define _GNU_SOURCE
63 #endif
64 
65 #if HAVE_CONFIG_H
66 #include "config.h"
67 #endif
68 #ifndef NETBSD
69 #include <nbcompat.h>
70 #endif
71 
72 #include <sys/types.h>
73 #include <sys/socket.h>
74 
75 #include <netinet/in.h>
76 #include <arpa/inet.h>
77 
78 #include <ctype.h>
79 #include <errno.h>
80 #include <fcntl.h>
81 #if defined(HAVE_INTTYPES_H) || defined(NETBSD)
82 #include <inttypes.h>
83 #endif
84 #include <stdarg.h>
85 #ifndef NETBSD
86 #include <nbcompat/netdb.h>
87 #include <nbcompat/stdio.h>
88 #else
89 #include <netdb.h>
90 #include <stdio.h>
91 #endif
92 #include <stdlib.h>
93 #include <string.h>
94 #include <time.h>
95 #include <unistd.h>
96 
97 #include "fetch.h"
98 #include "common.h"
99 #include "ftperr.h"
100 
101 #define FTP_ANONYMOUS_USER	"anonymous"
102 
103 #define FTP_CONNECTION_ALREADY_OPEN	125
104 #define FTP_OPEN_DATA_CONNECTION	150
105 #define FTP_OK				200
106 #define FTP_FILE_STATUS			213
107 #define FTP_SERVICE_READY		220
108 #define FTP_TRANSFER_COMPLETE		226
109 #define FTP_PASSIVE_MODE		227
110 #define FTP_LPASSIVE_MODE		228
111 #define FTP_EPASSIVE_MODE		229
112 #define FTP_LOGGED_IN			230
113 #define FTP_FILE_ACTION_OK		250
114 #define FTP_DIRECTORY_CREATED		257 /* multiple meanings */
115 #define FTP_FILE_CREATED		257 /* multiple meanings */
116 #define FTP_WORKING_DIRECTORY		257 /* multiple meanings */
117 #define FTP_NEED_PASSWORD		331
118 #define FTP_NEED_ACCOUNT		332
119 #define FTP_FILE_OK			350
120 #define FTP_SYNTAX_ERROR		500
121 #define FTP_PROTOCOL_ERROR		999
122 
123 #define isftpreply(foo)				\
124 	(isdigit((unsigned char)foo[0]) &&	\
125 	    isdigit((unsigned char)foo[1]) &&	\
126 	    isdigit((unsigned char)foo[2]) &&	\
127 	    (foo[3] == ' ' || foo[3] == '\0'))
128 #define isftpinfo(foo) \
129 	(isdigit((unsigned char)foo[0]) &&	\
130 	    isdigit((unsigned char)foo[1]) &&	\
131 	    isdigit((unsigned char)foo[2]) &&	\
132 	    foo[3] == '-')
133 
134 /*
135  * Translate IPv4 mapped IPv6 address to IPv4 address
136  */
137 static void
138 unmappedaddr(struct sockaddr_in6 *sin6, socklen_t *len)
139 {
140 	struct sockaddr_in *sin4;
141 	uint32_t addr;
142 	int port;
143 
144 	if (sin6->sin6_family != AF_INET6 ||
145 	    !IN6_IS_ADDR_V4MAPPED(&sin6->sin6_addr))
146 		return;
147 	sin4 = (struct sockaddr_in *)sin6;
148 	addr = *(uint32_t *)&sin6->sin6_addr.s6_addr[12];
149 	port = sin6->sin6_port;
150 	memset(sin4, 0, sizeof(struct sockaddr_in));
151 	sin4->sin_addr.s_addr = addr;
152 	sin4->sin_port = port;
153 	sin4->sin_family = AF_INET;
154 	*len = sizeof(struct sockaddr_in);
155 #ifdef HAVE_SA_LEN
156 	sin4->sin_len = sizeof(struct sockaddr_in);
157 #endif
158 }
159 
160 /*
161  * Get server response
162  */
163 static int
164 ftp_chkerr(conn_t *conn)
165 {
166 	if (fetch_getln(conn) == -1) {
167 		fetch_syserr();
168 		return (-1);
169 	}
170 	if (isftpinfo(conn->buf)) {
171 		while (conn->buflen && !isftpreply(conn->buf)) {
172 			if (fetch_getln(conn) == -1) {
173 				fetch_syserr();
174 				return (-1);
175 			}
176 		}
177 	}
178 
179 	while (conn->buflen &&
180 	    isspace((unsigned char)conn->buf[conn->buflen - 1]))
181 		conn->buflen--;
182 	conn->buf[conn->buflen] = '\0';
183 
184 	if (!isftpreply(conn->buf)) {
185 		ftp_seterr(FTP_PROTOCOL_ERROR);
186 		return (-1);
187 	}
188 
189 	conn->err = (conn->buf[0] - '0') * 100
190 	    + (conn->buf[1] - '0') * 10
191 	    + (conn->buf[2] - '0');
192 
193 	return (conn->err);
194 }
195 
196 /*
197  * Send a command and check reply
198  */
199 static int
200 ftp_cmd(conn_t *conn, const char *fmt, ...)
201 {
202 	va_list ap;
203 	size_t len;
204 	char *msg;
205 	int r;
206 
207 	va_start(ap, fmt);
208 	len = vasprintf(&msg, fmt, ap);
209 	va_end(ap);
210 
211 	if (msg == NULL) {
212 		errno = ENOMEM;
213 		fetch_syserr();
214 		return (-1);
215 	}
216 
217 	r = fetch_write(conn, msg, len);
218 	free(msg);
219 
220 	if (r == -1) {
221 		fetch_syserr();
222 		return (-1);
223 	}
224 
225 	return (ftp_chkerr(conn));
226 }
227 
228 /*
229  * Return a pointer to the filename part of a path
230  */
231 static const char *
232 ftp_filename(const char *file, int *len, int *type, int subdir)
233 {
234 	const char *s;
235 
236 	if ((s = strrchr(file, '/')) == NULL || subdir)
237 		s = file;
238 	else
239 		s = s + 1;
240 	*len = strlen(s);
241 	if (*len > 7 && strncmp(s + *len - 7, ";type=", 6) == 0) {
242 		*type = s[*len - 1];
243 		*len -= 7;
244 	} else {
245 		*type = '\0';
246 	}
247 	return (s);
248 }
249 
250 /*
251  * Get current working directory from the reply to a CWD, PWD or CDUP
252  * command.
253  */
254 static int
255 ftp_pwd(conn_t *conn, char *pwd, size_t pwdlen)
256 {
257 	char *src, *dst, *end;
258 	int q;
259 
260 	if (conn->err != FTP_WORKING_DIRECTORY &&
261 	    conn->err != FTP_FILE_ACTION_OK)
262 		return (FTP_PROTOCOL_ERROR);
263 	end = conn->buf + conn->buflen;
264 	src = conn->buf + 4;
265 	if (src >= end || *src++ != '"')
266 		return (FTP_PROTOCOL_ERROR);
267 	for (q = 0, dst = pwd; src < end && pwdlen--; ++src) {
268 		if (!q && *src == '"')
269 			q = 1;
270 		else if (q && *src != '"')
271 			break;
272 		else if (q)
273 			*dst++ = '"', q = 0;
274 		else
275 			*dst++ = *src;
276 	}
277 	if (!pwdlen)
278 		return (FTP_PROTOCOL_ERROR);
279 	*dst = '\0';
280 	return (FTP_OK);
281 }
282 
283 /*
284  * Change working directory to the directory that contains the specified
285  * file.
286  */
287 static int
288 ftp_cwd(conn_t *conn, const char *file, int subdir)
289 {
290 	const char *beg, *end;
291 	char pwd[PATH_MAX];
292 	int e, i, len;
293 
294 	/* If no slashes in name, no need to change dirs. */
295 	if (subdir)
296 		end = file + strlen(file);
297 	else if ((end = strrchr(file, '/')) == NULL)
298 		return (0);
299 	if ((e = ftp_cmd(conn, "PWD\r\n")) != FTP_WORKING_DIRECTORY ||
300 	    (e = ftp_pwd(conn, pwd, sizeof(pwd))) != FTP_OK) {
301 		ftp_seterr(e);
302 		return (-1);
303 	}
304 	for (;;) {
305 		len = strlen(pwd);
306 
307 		/* Look for a common prefix between PWD and dir to fetch. */
308 		for (i = 0; i <= len && i <= end - file; ++i)
309 			if (pwd[i] != file[i])
310 				break;
311 		/* Keep going up a dir until we have a matching prefix. */
312 		if (strcmp(pwd, "/") == 0)
313 			break;
314 		if (pwd[i] == '\0' && (file[i - 1] == '/' || file[i] == '/'))
315 			break;
316 		if ((e = ftp_cmd(conn, "CDUP\r\n")) != FTP_FILE_ACTION_OK ||
317 		    (e = ftp_cmd(conn, "PWD\r\n")) != FTP_WORKING_DIRECTORY ||
318 		    (e = ftp_pwd(conn, pwd, sizeof(pwd))) != FTP_OK) {
319 			ftp_seterr(e);
320 			return (-1);
321 		}
322 	}
323 
324 #ifdef FTP_COMBINE_CWDS
325 	/* Skip leading slashes, even "////". */
326 	for (beg = file + i; beg < end && *beg == '/'; ++beg, ++i)
327 		/* nothing */ ;
328 
329 	/* If there is no trailing dir, we're already there. */
330 	if (beg >= end)
331 		return (0);
332 
333 	/* Change to the directory all in one chunk (e.g., foo/bar/baz). */
334 	e = ftp_cmd(conn, "CWD %.*s\r\n", (int)(end - beg), beg);
335 	if (e == FTP_FILE_ACTION_OK)
336 		return (0);
337 #endif /* FTP_COMBINE_CWDS */
338 
339 	/* That didn't work so go back to legacy behavior (multiple CWDs). */
340 	for (beg = file + i; beg < end; beg = file + i + 1) {
341 		while (*beg == '/')
342 			++beg, ++i;
343 		for (++i; file + i < end && file[i] != '/'; ++i)
344 			/* nothing */ ;
345 		e = ftp_cmd(conn, "CWD %.*s\r\n", file + i - beg, beg);
346 		if (e != FTP_FILE_ACTION_OK) {
347 			ftp_seterr(e);
348 			return (-1);
349 		}
350 	}
351 	return (0);
352 }
353 
354 /*
355  * Set transfer mode and data type
356  */
357 static int
358 ftp_mode_type(conn_t *conn, int mode, int type)
359 {
360 	int e;
361 
362 	switch (mode) {
363 	case 0:
364 	case 's':
365 		mode = 'S';
366 	case 'S':
367 		break;
368 	default:
369 		return (FTP_PROTOCOL_ERROR);
370 	}
371 	if ((e = ftp_cmd(conn, "MODE %c\r\n", mode)) != FTP_OK) {
372 		if (mode == 'S') {
373 			/*
374 			 * Stream mode is supposed to be the default - so
375 			 * much so that some servers not only do not
376 			 * support any other mode, but do not support the
377 			 * MODE command at all.
378 			 *
379 			 * If "MODE S" fails, it is unlikely that we
380 			 * previously succeeded in setting a different
381 			 * mode.  Therefore, we simply hope that the
382 			 * server is already in the correct mode, and
383 			 * silently ignore the failure.
384 			 */
385 		} else {
386 			return (e);
387 		}
388 	}
389 
390 	switch (type) {
391 	case 0:
392 	case 'i':
393 		type = 'I';
394 	case 'I':
395 		break;
396 	case 'a':
397 		type = 'A';
398 	case 'A':
399 		break;
400 	case 'd':
401 		type = 'D';
402 	case 'D':
403 		/* can't handle yet */
404 	default:
405 		return (FTP_PROTOCOL_ERROR);
406 	}
407 	if ((e = ftp_cmd(conn, "TYPE %c\r\n", type)) != FTP_OK)
408 		return (e);
409 
410 	return (FTP_OK);
411 }
412 
413 /*
414  * Request and parse file stats
415  */
416 static int
417 ftp_stat(conn_t *conn, const char *file, struct url_stat *us)
418 {
419 	char *ln;
420 	const char *filename;
421 	int filenamelen, type;
422 	struct tm tm;
423 	time_t t;
424 	int e;
425 
426 	us->size = -1;
427 	us->atime = us->mtime = 0;
428 
429 	filename = ftp_filename(file, &filenamelen, &type, 0);
430 
431 	if ((e = ftp_mode_type(conn, 0, type)) != FTP_OK) {
432 		ftp_seterr(e);
433 		return (-1);
434 	}
435 
436 	e = ftp_cmd(conn, "SIZE %.*s\r\n", filenamelen, filename);
437 	if (e != FTP_FILE_STATUS) {
438 		ftp_seterr(e);
439 		return (-1);
440 	}
441 	for (ln = conn->buf + 4; *ln && isspace((unsigned char)*ln); ln++)
442 		/* nothing */ ;
443 	for (us->size = 0; *ln && isdigit((unsigned char)*ln); ln++)
444 		us->size = us->size * 10 + *ln - '0';
445 	if (*ln && !isspace((unsigned char)*ln)) {
446 		ftp_seterr(FTP_PROTOCOL_ERROR);
447 		us->size = -1;
448 		return (-1);
449 	}
450 	if (us->size == 0)
451 		us->size = -1;
452 
453 	e = ftp_cmd(conn, "MDTM %.*s\r\n", filenamelen, filename);
454 	if (e != FTP_FILE_STATUS) {
455 		ftp_seterr(e);
456 		return (-1);
457 	}
458 	for (ln = conn->buf + 4; *ln && isspace((unsigned char)*ln); ln++)
459 		/* nothing */ ;
460 	switch (strspn(ln, "0123456789")) {
461 	case 14:
462 		break;
463 	case 15:
464 		ln++;
465 		ln[0] = '2';
466 		ln[1] = '0';
467 		break;
468 	default:
469 		ftp_seterr(FTP_PROTOCOL_ERROR);
470 		return (-1);
471 	}
472 	if (sscanf(ln, "%04d%02d%02d%02d%02d%02d",
473 	    &tm.tm_year, &tm.tm_mon, &tm.tm_mday,
474 	    &tm.tm_hour, &tm.tm_min, &tm.tm_sec) != 6) {
475 		ftp_seterr(FTP_PROTOCOL_ERROR);
476 		return (-1);
477 	}
478 	tm.tm_mon--;
479 	tm.tm_year -= 1900;
480 	tm.tm_isdst = -1;
481 	t = timegm(&tm);
482 	if (t == (time_t)-1)
483 		t = time(NULL);
484 	us->mtime = t;
485 	us->atime = t;
486 
487 	return (0);
488 }
489 
490 /*
491  * I/O functions for FTP
492  */
493 struct ftpio {
494 	conn_t	*cconn;		/* Control connection */
495 	conn_t	*dconn;		/* Data connection */
496 	int	 dir;		/* Direction */
497 	int	 eof;		/* EOF reached */
498 	int	 err;		/* Error code */
499 };
500 
501 static ssize_t	 ftp_readfn(void *, void *, size_t);
502 static ssize_t	 ftp_writefn(void *, const void *, size_t);
503 static void	 ftp_closefn(void *);
504 
505 static ssize_t
506 ftp_readfn(void *v, void *buf, size_t len)
507 {
508 	struct ftpio *io;
509 	int r;
510 
511 	io = (struct ftpio *)v;
512 	if (io == NULL) {
513 		errno = EBADF;
514 		return (-1);
515 	}
516 	if (io->cconn == NULL || io->dconn == NULL || io->dir == O_WRONLY) {
517 		errno = EBADF;
518 		return (-1);
519 	}
520 	if (io->err) {
521 		errno = io->err;
522 		return (-1);
523 	}
524 	if (io->eof)
525 		return (0);
526 	r = fetch_read(io->dconn, buf, len);
527 	if (r > 0)
528 		return (r);
529 	if (r == 0) {
530 		io->eof = 1;
531 		return (0);
532 	}
533 	if (errno != EINTR)
534 		io->err = errno;
535 	return (-1);
536 }
537 
538 static ssize_t
539 ftp_writefn(void *v, const void *buf, size_t len)
540 {
541 	struct ftpio *io;
542 	int w;
543 
544 	io = (struct ftpio *)v;
545 	if (io == NULL) {
546 		errno = EBADF;
547 		return (-1);
548 	}
549 	if (io->cconn == NULL || io->dconn == NULL || io->dir == O_RDONLY) {
550 		errno = EBADF;
551 		return (-1);
552 	}
553 	if (io->err) {
554 		errno = io->err;
555 		return (-1);
556 	}
557 	w = fetch_write(io->dconn, buf, len);
558 	if (w >= 0)
559 		return (w);
560 	if (errno != EINTR)
561 		io->err = errno;
562 	return (-1);
563 }
564 
565 static int
566 ftp_disconnect(conn_t *conn)
567 {
568 	ftp_cmd(conn, "QUIT\r\n");
569 	return fetch_close(conn);
570 }
571 
572 static void
573 ftp_closefn(void *v)
574 {
575 	struct ftpio *io;
576 	int r;
577 
578 	io = (struct ftpio *)v;
579 	if (io == NULL) {
580 		errno = EBADF;
581 		return;
582 	}
583 	if (io->dir == -1)
584 		return;
585 	if (io->cconn == NULL || io->dconn == NULL) {
586 		errno = EBADF;
587 		return;
588 	}
589 	fetch_close(io->dconn);
590 	io->dconn = NULL;
591 	io->dir = -1;
592 	r = ftp_chkerr(io->cconn);
593 	fetch_cache_put(io->cconn, ftp_disconnect);
594 	free(io);
595 	return;
596 }
597 
598 static fetchIO *
599 ftp_setup(conn_t *cconn, conn_t *dconn, int mode)
600 {
601 	struct ftpio *io;
602 	fetchIO *f;
603 
604 	if (cconn == NULL || dconn == NULL)
605 		return (NULL);
606 	if ((io = malloc(sizeof(*io))) == NULL)
607 		return (NULL);
608 	io->cconn = cconn;
609 	io->dconn = dconn;
610 	io->dir = mode;
611 	io->eof = io->err = 0;
612 	f = fetchIO_unopen(io, ftp_readfn, ftp_writefn, ftp_closefn);
613 	if (f == NULL)
614 		free(io);
615 	return (f);
616 }
617 
618 /*
619  * Transfer file
620  */
621 static fetchIO *
622 ftp_transfer(conn_t *conn, const char *oper, const char *file, const char *op_arg,
623     int mode, off_t offset, const char *flags)
624 {
625 	union anonymous {
626 		struct sockaddr_storage ss;
627 		struct sockaddr sa;
628 		struct sockaddr_in6 sin6;
629 		struct sockaddr_in sin4;
630 	} u;
631 	const char *bindaddr;
632 	const char *filename;
633 	int filenamelen, type;
634 	int low, pasv, verbose;
635 	int e, sd = -1;
636 	socklen_t l;
637 	char *s;
638 	fetchIO *df;
639 
640 	/* check flags */
641 	low = CHECK_FLAG('l');
642 	pasv = !CHECK_FLAG('a');
643 	verbose = CHECK_FLAG('v');
644 
645 	/* passive mode */
646 	if (!pasv)
647 		pasv = ((s = getenv("FTP_PASSIVE_MODE")) != NULL &&
648 		    strncasecmp(s, "no", 2) != 0);
649 
650 	/* isolate filename */
651 	filename = ftp_filename(file, &filenamelen, &type, op_arg != NULL);
652 
653 	/* set transfer mode and data type */
654 	if ((e = ftp_mode_type(conn, 0, type)) != FTP_OK)
655 		goto ouch;
656 
657 	/* find our own address, bind, and listen */
658 	l = sizeof(u.ss);
659 	if (getsockname(conn->sd, &u.sa, &l) == -1)
660 		goto sysouch;
661 	if (u.ss.ss_family == AF_INET6)
662 		unmappedaddr(&u.sin6, &l);
663 
664 retry_mode:
665 
666 	/* open data socket */
667 	if ((sd = socket(u.ss.ss_family, SOCK_STREAM, IPPROTO_TCP)) == -1) {
668 		fetch_syserr();
669 		return (NULL);
670 	}
671 
672 	if (pasv) {
673 		unsigned char addr[64];
674 		char *ln, *p;
675 		unsigned int i;
676 		int port;
677 
678 		/* send PASV command */
679 		if (verbose)
680 			fetch_info("setting passive mode");
681 		switch (u.ss.ss_family) {
682 		case AF_INET:
683 			if ((e = ftp_cmd(conn, "PASV\r\n")) != FTP_PASSIVE_MODE)
684 				goto ouch;
685 			break;
686 		case AF_INET6:
687 			if ((e = ftp_cmd(conn, "EPSV\r\n")) != FTP_EPASSIVE_MODE) {
688 				if (e == -1)
689 					goto ouch;
690 				if ((e = ftp_cmd(conn, "LPSV\r\n")) !=
691 				    FTP_LPASSIVE_MODE)
692 					goto ouch;
693 			}
694 			break;
695 		default:
696 			e = FTP_PROTOCOL_ERROR; /* XXX: error code should be prepared */
697 			goto ouch;
698 		}
699 
700 		/*
701 		 * Find address and port number. The reply to the PASV command
702 		 * is IMHO the one and only weak point in the FTP protocol.
703 		 */
704 		ln = conn->buf;
705 		switch (e) {
706 		case FTP_PASSIVE_MODE:
707 		case FTP_LPASSIVE_MODE:
708 			for (p = ln + 3; *p && !isdigit((unsigned char)*p); p++)
709 				/* nothing */ ;
710 			if (!*p) {
711 				e = FTP_PROTOCOL_ERROR;
712 				goto ouch;
713 			}
714 			l = (e == FTP_PASSIVE_MODE ? 6 : 21);
715 			for (i = 0; *p && i < l; i++, p++)
716 				addr[i] = strtol(p, &p, 10);
717 			if (i < l) {
718 				e = FTP_PROTOCOL_ERROR;
719 				goto ouch;
720 			}
721 			break;
722 		case FTP_EPASSIVE_MODE:
723 			for (p = ln + 3; *p && *p != '('; p++)
724 				/* nothing */ ;
725 			if (!*p) {
726 				e = FTP_PROTOCOL_ERROR;
727 				goto ouch;
728 			}
729 			++p;
730 			if (sscanf(p, "%c%c%c%d%c", &addr[0], &addr[1], &addr[2],
731 				&port, &addr[3]) != 5 ||
732 			    addr[0] != addr[1] ||
733 			    addr[0] != addr[2] || addr[0] != addr[3]) {
734 				e = FTP_PROTOCOL_ERROR;
735 				goto ouch;
736 			}
737 			break;
738 		case FTP_SYNTAX_ERROR:
739 			if (verbose)
740 				fetch_info("passive mode failed");
741 			/* Close socket and retry with passive mode. */
742 			pasv = 0;
743 			close(sd);
744 			sd = -1;
745 			goto retry_mode;
746 		}
747 
748 		/* seek to required offset */
749 		if (offset)
750 			if (ftp_cmd(conn, "REST %lu\r\n", (unsigned long)offset) != FTP_FILE_OK)
751 				goto sysouch;
752 
753 		/* construct sockaddr for data socket */
754 		l = sizeof(u.ss);
755 		if (getpeername(conn->sd, &u.sa, &l) == -1)
756 			goto sysouch;
757 		if (u.ss.ss_family == AF_INET6)
758 			unmappedaddr(&u.sin6, &l);
759 		switch (u.ss.ss_family) {
760 		case AF_INET6:
761 			if (e == FTP_EPASSIVE_MODE)
762 				u.sin6.sin6_port = htons(port);
763 			else {
764 				memcpy(&u.sin6.sin6_addr, addr + 2, 16);
765 				memcpy(&u.sin6.sin6_port, addr + 19, 2);
766 			}
767 			break;
768 		case AF_INET:
769 			if (e == FTP_EPASSIVE_MODE)
770 				u.sin4.sin_port = htons(port);
771 			else {
772 				memcpy(&u.sin4.sin_addr, addr, 4);
773 				memcpy(&u.sin4.sin_port, addr + 4, 2);
774 			}
775 			break;
776 		default:
777 			e = FTP_PROTOCOL_ERROR; /* XXX: error code should be prepared */
778 			break;
779 		}
780 
781 		/* connect to data port */
782 		if (verbose)
783 			fetch_info("opening data connection");
784 		bindaddr = getenv("FETCH_BIND_ADDRESS");
785 		if (bindaddr != NULL && *bindaddr != '\0' &&
786 		    fetch_bind(sd, u.ss.ss_family, bindaddr) != 0)
787 			goto sysouch;
788 		if (connect(sd, &u.sa, l) == -1)
789 			goto sysouch;
790 
791 		/* make the server initiate the transfer */
792 		if (verbose)
793 			fetch_info("initiating transfer");
794 		if (op_arg)
795 			e = ftp_cmd(conn, "%s%s%s\r\n", oper, *op_arg ? " " : "", op_arg);
796 		else
797 			e = ftp_cmd(conn, "%s %.*s\r\n", oper,
798 			    filenamelen, filename);
799 		if (e != FTP_CONNECTION_ALREADY_OPEN && e != FTP_OPEN_DATA_CONNECTION)
800 			goto ouch;
801 
802 	} else {
803 		uint32_t a;
804 		uint16_t p;
805 #if defined(IPV6_PORTRANGE) || defined(IP_PORTRANGE)
806 		int arg;
807 #endif
808 		int d;
809 		char *ap;
810 		char hname[INET6_ADDRSTRLEN];
811 
812 		switch (u.ss.ss_family) {
813 		case AF_INET6:
814 			u.sin6.sin6_port = 0;
815 #ifdef IPV6_PORTRANGE
816 			arg = low ? IPV6_PORTRANGE_DEFAULT : IPV6_PORTRANGE_HIGH;
817 			if (setsockopt(sd, IPPROTO_IPV6, IPV6_PORTRANGE,
818 				(char *)&arg, sizeof(arg)) == -1)
819 				goto sysouch;
820 #endif
821 			break;
822 		case AF_INET:
823 			u.sin4.sin_port = 0;
824 #ifdef IP_PORTRANGE
825 			arg = low ? IP_PORTRANGE_DEFAULT : IP_PORTRANGE_HIGH;
826 			if (setsockopt(sd, IPPROTO_IP, IP_PORTRANGE,
827 				(char *)&arg, sizeof(arg)) == -1)
828 				goto sysouch;
829 #endif
830 			break;
831 		}
832 		if (verbose)
833 			fetch_info("binding data socket");
834 		if (bind(sd, &u.sa, l) == -1)
835 			goto sysouch;
836 		if (listen(sd, 1) == -1)
837 			goto sysouch;
838 
839 		/* find what port we're on and tell the server */
840 		if (getsockname(sd, &u.sa, &l) == -1)
841 			goto sysouch;
842 		switch (u.ss.ss_family) {
843 		case AF_INET:
844 			a = ntohl(u.sin4.sin_addr.s_addr);
845 			p = ntohs(u.sin4.sin_port);
846 			e = ftp_cmd(conn, "PORT %d,%d,%d,%d,%d,%d\r\n",
847 			    (a >> 24) & 0xff, (a >> 16) & 0xff,
848 			    (a >> 8) & 0xff, a & 0xff,
849 			    (p >> 8) & 0xff, p & 0xff);
850 			break;
851 		case AF_INET6:
852 #define UC(b)	(((int)b)&0xff)
853 			e = -1;
854 			u.sin6.sin6_scope_id = 0;
855 			if (getnameinfo(&u.sa, l,
856 				hname, sizeof(hname),
857 				NULL, 0, NI_NUMERICHOST) == 0) {
858 				e = ftp_cmd(conn, "EPRT |%d|%s|%d|\r\n", 2, hname,
859 				    htons(u.sin6.sin6_port));
860 				if (e == -1)
861 					goto ouch;
862 			}
863 			if (e != FTP_OK) {
864 				ap = (char *)&u.sin6.sin6_addr;
865 				e = ftp_cmd(conn,
866 				    "LPRT %d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d\r\n",
867 				    6, 16,
868 				    UC(ap[0]), UC(ap[1]), UC(ap[2]), UC(ap[3]),
869 				    UC(ap[4]), UC(ap[5]), UC(ap[6]), UC(ap[7]),
870 				    UC(ap[8]), UC(ap[9]), UC(ap[10]), UC(ap[11]),
871 				    UC(ap[12]), UC(ap[13]), UC(ap[14]), UC(ap[15]),
872 				    2,
873 				    (ntohs(u.sin6.sin6_port) >> 8) & 0xff,
874 				    ntohs(u.sin6.sin6_port)        & 0xff);
875 			}
876 			break;
877 		default:
878 			e = FTP_PROTOCOL_ERROR; /* XXX: error code should be prepared */
879 			goto ouch;
880 		}
881 		if (e != FTP_OK)
882 			goto ouch;
883 
884 		/* seek to required offset */
885 		if (offset)
886 			if (ftp_cmd(conn, "REST %llu\r\n", (unsigned long long)offset) != FTP_FILE_OK)
887 				goto sysouch;
888 
889 		/* make the server initiate the transfer */
890 		if (verbose)
891 			fetch_info("initiating transfer");
892 		if (op_arg)
893 			e = ftp_cmd(conn, "%s%s%s\r\n", oper, *op_arg ? " " : "", op_arg);
894 		else
895 			e = ftp_cmd(conn, "%s %.*s\r\n", oper,
896 			    filenamelen, filename);
897 		if (e != FTP_CONNECTION_ALREADY_OPEN && e != FTP_OPEN_DATA_CONNECTION)
898 			goto ouch;
899 
900 		/* accept the incoming connection and go to town */
901 		if ((d = accept(sd, NULL, NULL)) == -1)
902 			goto sysouch;
903 		close(sd);
904 		sd = d;
905 	}
906 
907 	if ((df = ftp_setup(conn, fetch_reopen(sd), mode)) == NULL)
908 		goto sysouch;
909 	return (df);
910 
911 sysouch:
912 	fetch_syserr();
913 	if (sd >= 0)
914 		close(sd);
915 	return (NULL);
916 
917 ouch:
918 	if (e != -1)
919 		ftp_seterr(e);
920 	if (sd >= 0)
921 		close(sd);
922 	return (NULL);
923 }
924 
925 /*
926  * Authenticate
927  */
928 static int
929 ftp_authenticate(conn_t *conn, struct url *url, struct url *purl)
930 {
931 	const char *user, *pwd, *login_name;
932 	char pbuf[URL_USERLEN + 1 + URL_HOSTLEN + 1];
933 	int e, len;
934 
935 	/* XXX FTP_AUTH, and maybe .netrc */
936 
937 	/* send user name and password */
938 	if (url->user[0] == '\0')
939 		fetch_netrc_auth(url);
940 	user = url->user;
941 	if (*user == '\0')
942 		user = getenv("FTP_LOGIN");
943 	if (user == NULL || *user == '\0')
944 		user = FTP_ANONYMOUS_USER;
945 	if (purl && url->port == fetch_default_port(url->scheme))
946 		e = ftp_cmd(conn, "USER %s@%s\r\n", user, url->host);
947 	else if (purl)
948 		e = ftp_cmd(conn, "USER %s@%s@%d\r\n", user, url->host, url->port);
949 	else
950 		e = ftp_cmd(conn, "USER %s\r\n", user);
951 
952 	/* did the server request a password? */
953 	if (e == FTP_NEED_PASSWORD) {
954 		pwd = url->pwd;
955 		if (*pwd == '\0')
956 			pwd = getenv("FTP_PASSWORD");
957 		if (pwd == NULL || *pwd == '\0') {
958 			if ((login_name = getlogin()) == 0)
959 				login_name = FTP_ANONYMOUS_USER;
960 			if ((len = snprintf(pbuf, URL_USERLEN + 2, "%s@", login_name)) < 0)
961 				len = 0;
962 			else if (len > URL_USERLEN + 1)
963 				len = URL_USERLEN + 1;
964 			gethostname(pbuf + len, sizeof(pbuf) - len);
965 			/* MAXHOSTNAMELEN can differ from URL_HOSTLEN + 1 */
966 			pbuf[sizeof(pbuf) - 1] = '\0';
967 			pwd = pbuf;
968 		}
969 		e = ftp_cmd(conn, "PASS %s\r\n", pwd);
970 	}
971 
972 	return (e);
973 }
974 
975 /*
976  * Log on to FTP server
977  */
978 static conn_t *
979 ftp_connect(struct url *url, struct url *purl, const char *flags)
980 {
981 	conn_t *conn;
982 	int e, direct, verbose;
983 #ifdef INET6
984 	int af = AF_UNSPEC;
985 #else
986 	int af = AF_INET;
987 #endif
988 
989 	direct = CHECK_FLAG('d');
990 	verbose = CHECK_FLAG('v');
991 	if (CHECK_FLAG('4'))
992 		af = AF_INET;
993 	else if (CHECK_FLAG('6'))
994 		af = AF_INET6;
995 
996 	if (direct)
997 		purl = NULL;
998 
999 	/* check for proxy */
1000 	if (purl) {
1001 		/* XXX proxy authentication! */
1002 		/* XXX connetion caching */
1003 		if (!purl->port)
1004 			purl->port = fetch_default_port(purl->scheme);
1005 
1006 		conn = fetch_connect(purl, af, verbose);
1007 	} else {
1008 		/* no proxy, go straight to target */
1009 		if (!url->port)
1010 			url->port = fetch_default_port(url->scheme);
1011 
1012 		while ((conn = fetch_cache_get(url, af)) != NULL) {
1013 			e = ftp_cmd(conn, "NOOP\r\n");
1014 			if (e == FTP_OK)
1015 				return conn;
1016 			fetch_close(conn);
1017 		}
1018 		conn = fetch_connect(url, af, verbose);
1019 		purl = NULL;
1020 	}
1021 
1022 	/* check connection */
1023 	if (conn == NULL)
1024 		/* fetch_connect() has already set an error code */
1025 		return (NULL);
1026 
1027 	/* expect welcome message */
1028 	if ((e = ftp_chkerr(conn)) != FTP_SERVICE_READY)
1029 		goto fouch;
1030 
1031 	/* authenticate */
1032 	if ((e = ftp_authenticate(conn, url, purl)) != FTP_LOGGED_IN)
1033 		goto fouch;
1034 
1035 	/* TODO: Request extended features supported, if any (RFC 3659). */
1036 
1037 	/* done */
1038 	return (conn);
1039 
1040 fouch:
1041 	if (e != -1)
1042 		ftp_seterr(e);
1043 	fetch_close(conn);
1044 	return (NULL);
1045 }
1046 
1047 /*
1048  * Check the proxy settings
1049  */
1050 static struct url *
1051 ftp_get_proxy(struct url * url, const char *flags)
1052 {
1053 	struct url *purl;
1054 	char *p;
1055 
1056 	if (flags != NULL && strchr(flags, 'd') != NULL)
1057 		return (NULL);
1058 	if (fetch_no_proxy_match(url->host))
1059 		return (NULL);
1060 	if (((p = getenv("FTP_PROXY")) || (p = getenv("ftp_proxy")) ||
1061 		(p = getenv("HTTP_PROXY")) || (p = getenv("http_proxy"))) &&
1062 	    *p && (purl = fetchParseURL(p)) != NULL) {
1063 		if (!*purl->scheme) {
1064 			if (getenv("FTP_PROXY") || getenv("ftp_proxy"))
1065 				strcpy(purl->scheme, SCHEME_FTP);
1066 			else
1067 				strcpy(purl->scheme, SCHEME_HTTP);
1068 		}
1069 		if (!purl->port)
1070 			purl->port = fetch_default_proxy_port(purl->scheme);
1071 		if (strcasecmp(purl->scheme, SCHEME_FTP) == 0 ||
1072 		    strcasecmp(purl->scheme, SCHEME_HTTP) == 0)
1073 			return (purl);
1074 		fetchFreeURL(purl);
1075 	}
1076 	return (NULL);
1077 }
1078 
1079 /*
1080  * Process an FTP request
1081  */
1082 fetchIO *
1083 ftp_request(struct url *url, const char *op, const char *op_arg,
1084     struct url_stat *us, struct url *purl, const char *flags)
1085 {
1086 	fetchIO *f;
1087 	char *path;
1088 	conn_t *conn;
1089 	int if_modified_since, oflag;
1090 	struct url_stat local_us;
1091 
1092 	/* check if we should use HTTP instead */
1093 	if (purl && strcasecmp(purl->scheme, SCHEME_HTTP) == 0) {
1094 		if (strcmp(op, "STAT") == 0)
1095 			return (http_request(url, "HEAD", us, purl, flags));
1096 		else if (strcmp(op, "RETR") == 0)
1097 			return (http_request(url, "GET", us, purl, flags));
1098 		/*
1099 		 * Our HTTP code doesn't support PUT requests yet, so try
1100 		 * a direct connection.
1101 		 */
1102 	}
1103 
1104 	/* connect to server */
1105 	conn = ftp_connect(url, purl, flags);
1106 	if (purl)
1107 		fetchFreeURL(purl);
1108 	if (conn == NULL)
1109 		return (NULL);
1110 
1111 	if ((path = fetchUnquotePath(url)) == NULL) {
1112 		fetch_syserr();
1113 		return NULL;
1114 	}
1115 
1116 	/* change directory */
1117 	if (ftp_cwd(conn, path, op_arg != NULL) == -1) {
1118 		free(path);
1119 		return (NULL);
1120 	}
1121 
1122 	if_modified_since = CHECK_FLAG('i');
1123 	if (if_modified_since && us == NULL)
1124 		us = &local_us;
1125 
1126 	/* stat file */
1127 	if (us && ftp_stat(conn, path, us) == -1
1128 	    && fetchLastErrCode != FETCH_PROTO
1129 	    && fetchLastErrCode != FETCH_UNAVAIL) {
1130 		free(path);
1131 		return (NULL);
1132 	}
1133 
1134 	if (if_modified_since && url->last_modified > 0 &&
1135 	    url->last_modified >= us->mtime) {
1136 		free(path);
1137 		fetchLastErrCode = FETCH_UNCHANGED;
1138 		snprintf(fetchLastErrString, MAXERRSTRING, "Unchanged");
1139 		return NULL;
1140 	}
1141 
1142 	/* just a stat */
1143 	if (strcmp(op, "STAT") == 0) {
1144 		free(path);
1145 		return fetchIO_unopen(NULL, NULL, NULL, NULL);
1146 	}
1147 	if (strcmp(op, "STOR") == 0 || strcmp(op, "APPE") == 0)
1148 		oflag = O_WRONLY;
1149 	else
1150 		oflag = O_RDONLY;
1151 
1152 	/* initiate the transfer */
1153 	f = (ftp_transfer(conn, op, path, op_arg, oflag, url->offset, flags));
1154 	free(path);
1155 	return f;
1156 }
1157 
1158 /*
1159  * Get and stat file
1160  */
1161 fetchIO *
1162 fetchXGetFTP(struct url *url, struct url_stat *us, const char *flags)
1163 {
1164 	return (ftp_request(url, "RETR", NULL, us, ftp_get_proxy(url, flags), flags));
1165 }
1166 
1167 /*
1168  * Get file
1169  */
1170 fetchIO *
1171 fetchGetFTP(struct url *url, const char *flags)
1172 {
1173 	return (fetchXGetFTP(url, NULL, flags));
1174 }
1175 
1176 /*
1177  * Put file
1178  */
1179 fetchIO *
1180 fetchPutFTP(struct url *url, const char *flags)
1181 {
1182 	return (ftp_request(url, CHECK_FLAG('a') ? "APPE" : "STOR", NULL, NULL,
1183 	    ftp_get_proxy(url, flags), flags));
1184 }
1185 
1186 /*
1187  * Get file stats
1188  */
1189 int
1190 fetchStatFTP(struct url *url, struct url_stat *us, const char *flags)
1191 {
1192 	fetchIO *f;
1193 
1194 	f = ftp_request(url, "STAT", NULL, us, ftp_get_proxy(url, flags), flags);
1195 	if (f == NULL)
1196 		return (-1);
1197 	fetchIO_close(f);
1198 	return (0);
1199 }
1200 
1201 /*
1202  * List a directory
1203  */
1204 int
1205 fetchListFTP(struct url_list *ue, struct url *url, const char *pattern, const char *flags)
1206 {
1207 	fetchIO *f;
1208 	char buf[2 * PATH_MAX], *eol, *eos;
1209 	ssize_t len;
1210 	size_t cur_off;
1211 	int ret;
1212 
1213 	/* XXX What about proxies? */
1214 	if (pattern == NULL || strcmp(pattern, "*") == 0)
1215 		pattern = "";
1216 	f = ftp_request(url, "NLST", pattern, NULL, ftp_get_proxy(url, flags), flags);
1217 	if (f == NULL)
1218 		return -1;
1219 
1220 	cur_off = 0;
1221 	ret = 0;
1222 
1223 	while ((len = fetchIO_read(f, buf + cur_off, sizeof(buf) - cur_off)) > 0) {
1224 		cur_off += len;
1225 		while ((eol = memchr(buf, '\n', cur_off)) != NULL) {
1226 			if (len == eol - buf)
1227 				break;
1228 			if (eol != buf) {
1229 				if (eol[-1] == '\r')
1230 					eos = eol - 1;
1231 				else
1232 					eos = eol;
1233 				*eos = '\0';
1234 				ret = fetch_add_entry(ue, url, buf, 0);
1235 				if (ret)
1236 					break;
1237 				cur_off -= eol - buf + 1;
1238 				memmove(buf, eol + 1, cur_off);
1239 			}
1240 		}
1241 		if (ret)
1242 			break;
1243 	}
1244 	if (cur_off != 0 || len < 0) {
1245 		/* Not RFC conform, bail out. */
1246 		fetchIO_close(f);
1247 		return -1;
1248 	}
1249 	fetchIO_close(f);
1250 	return ret;
1251 }
1252