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