xref: /freebsd/lib/libfetch/ftp.c (revision 8ddb146abcdf061be9f2c0db7e391697dafad85c)
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 (*p == '\0' && i < l - 1)
710 					break;
711 			}
712 			if (i < l) {
713 				e = FTP_PROTOCOL_ERROR;
714 				goto ouch;
715 			}
716 			break;
717 		case FTP_EPASSIVE_MODE:
718 			for (p = ln + 3; *p && *p != '('; p++)
719 				/* nothing */ ;
720 			if (!*p) {
721 				e = FTP_PROTOCOL_ERROR;
722 				goto ouch;
723 			}
724 			++p;
725 			if (sscanf(p, "%c%c%c%d%c", &addr[0], &addr[1], &addr[2],
726 				&port, &addr[3]) != 5 ||
727 			    addr[0] != addr[1] ||
728 			    addr[0] != addr[2] || addr[0] != addr[3]) {
729 				e = FTP_PROTOCOL_ERROR;
730 				goto ouch;
731 			}
732 			break;
733 		}
734 
735 		/* seek to required offset */
736 		if (offset)
737 			if (ftp_cmd(conn, "REST %lu", (u_long)offset) != FTP_FILE_OK)
738 				goto sysouch;
739 
740 		/* construct sockaddr for data socket */
741 		l = sizeof(sa);
742 		if (getpeername(conn->sd, (struct sockaddr *)&sa, &l) == -1)
743 			goto sysouch;
744 		if (sa.ss_family == AF_INET6)
745 			unmappedaddr((struct sockaddr_in6 *)&sa);
746 		switch (sa.ss_family) {
747 		case AF_INET6:
748 			sin6 = (struct sockaddr_in6 *)&sa;
749 			if (e == FTP_EPASSIVE_MODE)
750 				sin6->sin6_port = htons(port);
751 			else {
752 				memcpy(&sin6->sin6_addr, addr + 2, 16);
753 				memcpy(&sin6->sin6_port, addr + 19, 2);
754 			}
755 			break;
756 		case AF_INET:
757 			sin4 = (struct sockaddr_in *)&sa;
758 			if (e == FTP_EPASSIVE_MODE)
759 				sin4->sin_port = htons(port);
760 			else {
761 				memcpy(&sin4->sin_addr, addr, 4);
762 				memcpy(&sin4->sin_port, addr + 4, 2);
763 			}
764 			break;
765 		default:
766 			e = FTP_PROTOCOL_ERROR; /* XXX: error code should be prepared */
767 			break;
768 		}
769 
770 		/* connect to data port */
771 		if (verbose)
772 			fetch_info("opening data connection");
773 		bindaddr = getenv("FETCH_BIND_ADDRESS");
774 		if (bindaddr != NULL && *bindaddr != '\0' &&
775 		    (e = fetch_bind(sd, sa.ss_family, bindaddr)) != 0)
776 			goto ouch;
777 		if (connect(sd, (struct sockaddr *)&sa, sa.ss_len) == -1)
778 			goto sysouch;
779 
780 		/* make the server initiate the transfer */
781 		if (verbose)
782 			fetch_info("initiating transfer");
783 		e = ftp_cmd(conn, "%s %.*s", oper, filenamelen, filename);
784 		if (e != FTP_CONNECTION_ALREADY_OPEN && e != FTP_OPEN_DATA_CONNECTION)
785 			goto ouch;
786 
787 	} else {
788 		u_int32_t a;
789 		u_short p;
790 		int arg, d;
791 		char *ap;
792 		char hname[INET6_ADDRSTRLEN];
793 
794 		switch (sa.ss_family) {
795 		case AF_INET6:
796 			((struct sockaddr_in6 *)&sa)->sin6_port = 0;
797 #ifdef IPV6_PORTRANGE
798 			arg = low ? IPV6_PORTRANGE_DEFAULT : IPV6_PORTRANGE_HIGH;
799 			if (setsockopt(sd, IPPROTO_IPV6, IPV6_PORTRANGE,
800 				(char *)&arg, sizeof(arg)) == -1)
801 				goto sysouch;
802 #endif
803 			break;
804 		case AF_INET:
805 			((struct sockaddr_in *)&sa)->sin_port = 0;
806 			arg = low ? IP_PORTRANGE_DEFAULT : IP_PORTRANGE_HIGH;
807 			if (setsockopt(sd, IPPROTO_IP, IP_PORTRANGE,
808 				(char *)&arg, sizeof(arg)) == -1)
809 				goto sysouch;
810 			break;
811 		}
812 		if (verbose)
813 			fetch_info("binding data socket");
814 		if (bind(sd, (struct sockaddr *)&sa, sa.ss_len) == -1)
815 			goto sysouch;
816 		if (listen(sd, 1) == -1)
817 			goto sysouch;
818 
819 		/* find what port we're on and tell the server */
820 		if (getsockname(sd, (struct sockaddr *)&sa, &l) == -1)
821 			goto sysouch;
822 		switch (sa.ss_family) {
823 		case AF_INET:
824 			sin4 = (struct sockaddr_in *)&sa;
825 			a = ntohl(sin4->sin_addr.s_addr);
826 			p = ntohs(sin4->sin_port);
827 			e = ftp_cmd(conn, "PORT %d,%d,%d,%d,%d,%d",
828 			    (a >> 24) & 0xff, (a >> 16) & 0xff,
829 			    (a >> 8) & 0xff, a & 0xff,
830 			    (p >> 8) & 0xff, p & 0xff);
831 			break;
832 		case AF_INET6:
833 #define UC(b)	(((int)b)&0xff)
834 			e = -1;
835 			sin6 = (struct sockaddr_in6 *)&sa;
836 			sin6->sin6_scope_id = 0;
837 			if (getnameinfo((struct sockaddr *)&sa, sa.ss_len,
838 				hname, sizeof(hname),
839 				NULL, 0, NI_NUMERICHOST) == 0) {
840 				e = ftp_cmd(conn, "EPRT |%d|%s|%d|", 2, hname,
841 				    htons(sin6->sin6_port));
842 				if (e == -1)
843 					goto ouch;
844 			}
845 			if (e != FTP_OK) {
846 				ap = (char *)&sin6->sin6_addr;
847 				e = ftp_cmd(conn,
848 				    "LPRT %d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d",
849 				    6, 16,
850 				    UC(ap[0]), UC(ap[1]), UC(ap[2]), UC(ap[3]),
851 				    UC(ap[4]), UC(ap[5]), UC(ap[6]), UC(ap[7]),
852 				    UC(ap[8]), UC(ap[9]), UC(ap[10]), UC(ap[11]),
853 				    UC(ap[12]), UC(ap[13]), UC(ap[14]), UC(ap[15]),
854 				    2,
855 				    (ntohs(sin6->sin6_port) >> 8) & 0xff,
856 				    ntohs(sin6->sin6_port)        & 0xff);
857 			}
858 			break;
859 		default:
860 			e = FTP_PROTOCOL_ERROR; /* XXX: error code should be prepared */
861 			goto ouch;
862 		}
863 		if (e != FTP_OK)
864 			goto ouch;
865 
866 		/* seek to required offset */
867 		if (offset)
868 			if (ftp_cmd(conn, "REST %ju", (uintmax_t)offset) != FTP_FILE_OK)
869 				goto sysouch;
870 
871 		/* make the server initiate the transfer */
872 		if (verbose)
873 			fetch_info("initiating transfer");
874 		e = ftp_cmd(conn, "%s %.*s", oper, filenamelen, filename);
875 		if (e != FTP_CONNECTION_ALREADY_OPEN && e != FTP_OPEN_DATA_CONNECTION)
876 			goto ouch;
877 
878 		/* accept the incoming connection and go to town */
879 		if ((d = accept(sd, NULL, NULL)) == -1)
880 			goto sysouch;
881 		close(sd);
882 		sd = d;
883 	}
884 
885 	if ((df = ftp_setup(conn, fetch_reopen(sd), mode)) == NULL)
886 		goto sysouch;
887 	return (df);
888 
889 sysouch:
890 	fetch_syserr();
891 	if (sd >= 0)
892 		close(sd);
893 	return (NULL);
894 
895 ouch:
896 	if (e != -1)
897 		ftp_seterr(e);
898 	if (sd >= 0)
899 		close(sd);
900 	return (NULL);
901 }
902 
903 /*
904  * Authenticate
905  */
906 static int
907 ftp_authenticate(conn_t *conn, struct url *url, struct url *purl)
908 {
909 	const char *user, *pwd, *logname;
910 	char pbuf[MAXHOSTNAMELEN + MAXLOGNAME + 1];
911 	int e, len;
912 
913 	/* XXX FTP_AUTH, and maybe .netrc */
914 
915 	/* send user name and password */
916 	if (url->user[0] == '\0')
917 		fetch_netrc_auth(url);
918 	user = url->user;
919 	if (*user == '\0')
920 		if ((user = getenv("FTP_LOGIN")) != NULL)
921 			DEBUGF("FTP_LOGIN=%s\n", user);
922 	if (user == NULL || *user == '\0')
923 		user = FTP_ANONYMOUS_USER;
924 	if (purl && url->port == fetch_default_port(url->scheme))
925 		e = ftp_cmd(conn, "USER %s@%s", user, url->host);
926 	else if (purl)
927 		e = ftp_cmd(conn, "USER %s@%s@%d", user, url->host, url->port);
928 	else
929 		e = ftp_cmd(conn, "USER %s", user);
930 
931 	/* did the server request a password? */
932 	if (e == FTP_NEED_PASSWORD) {
933 		pwd = url->pwd;
934 		if (*pwd == '\0')
935 			if ((pwd = getenv("FTP_PASSWORD")) != NULL)
936 				DEBUGF("FTP_PASSWORD=%s\n", pwd);
937 		if (pwd == NULL || *pwd == '\0') {
938 			if ((logname = getlogin()) == NULL)
939 				logname = FTP_ANONYMOUS_USER;
940 			if ((len = snprintf(pbuf, MAXLOGNAME + 1, "%s@", logname)) < 0)
941 				len = 0;
942 			else if (len > MAXLOGNAME)
943 				len = MAXLOGNAME;
944 			gethostname(pbuf + len, sizeof(pbuf) - len);
945 			pwd = pbuf;
946 		}
947 		e = ftp_cmd(conn, "PASS %s", pwd);
948 	}
949 
950 	return (e);
951 }
952 
953 /*
954  * Log on to FTP server
955  */
956 static conn_t *
957 ftp_connect(struct url *url, struct url *purl, const char *flags)
958 {
959 	conn_t *conn;
960 	int e, direct, verbose;
961 #ifdef INET6
962 	int af = AF_UNSPEC;
963 #else
964 	int af = AF_INET;
965 #endif
966 
967 	direct = CHECK_FLAG('d');
968 	verbose = CHECK_FLAG('v');
969 	if (CHECK_FLAG('4'))
970 		af = AF_INET;
971 	else if (CHECK_FLAG('6'))
972 		af = AF_INET6;
973 
974 	if (direct)
975 		purl = NULL;
976 
977 	/* check for proxy */
978 	if (purl) {
979 		/* XXX proxy authentication! */
980 		conn = fetch_connect(purl->host, purl->port, af, verbose);
981 	} else {
982 		/* no proxy, go straight to target */
983 		conn = fetch_connect(url->host, url->port, af, verbose);
984 		purl = NULL;
985 	}
986 
987 	/* check connection */
988 	if (conn == NULL)
989 		/* fetch_connect() has already set an error code */
990 		return (NULL);
991 
992 	/* expect welcome message */
993 	if ((e = ftp_chkerr(conn)) != FTP_SERVICE_READY)
994 		goto fouch;
995 
996 	/* authenticate */
997 	if ((e = ftp_authenticate(conn, url, purl)) != FTP_LOGGED_IN)
998 		goto fouch;
999 
1000 	/* TODO: Request extended features supported, if any (RFC 3659). */
1001 
1002 	/* done */
1003 	return (conn);
1004 
1005 fouch:
1006 	if (e != -1)
1007 		ftp_seterr(e);
1008 	fetch_close(conn);
1009 	return (NULL);
1010 }
1011 
1012 /*
1013  * Disconnect from server
1014  */
1015 static void
1016 ftp_disconnect(conn_t *conn)
1017 {
1018 	(void)ftp_cmd(conn, "QUIT");
1019 	if (conn == cached_connection && conn->ref == 1)
1020 		cached_connection = NULL;
1021 	fetch_close(conn);
1022 }
1023 
1024 /*
1025  * Check if we're already connected
1026  */
1027 static int
1028 ftp_isconnected(struct url *url)
1029 {
1030 	return (cached_connection
1031 	    && (strcmp(url->host, cached_host.host) == 0)
1032 	    && (strcmp(url->user, cached_host.user) == 0)
1033 	    && (strcmp(url->pwd, cached_host.pwd) == 0)
1034 	    && (url->port == cached_host.port));
1035 }
1036 
1037 /*
1038  * Check the cache, reconnect if no luck
1039  */
1040 static conn_t *
1041 ftp_cached_connect(struct url *url, struct url *purl, const char *flags)
1042 {
1043 	conn_t *conn;
1044 	int e;
1045 
1046 	/* set default port */
1047 	if (!url->port)
1048 		url->port = fetch_default_port(url->scheme);
1049 
1050 	/* try to use previously cached connection */
1051 	if (ftp_isconnected(url)) {
1052 		e = ftp_cmd(cached_connection, "NOOP");
1053 		if (e == FTP_OK || e == FTP_SYNTAX_ERROR)
1054 			return (fetch_ref(cached_connection));
1055 	}
1056 
1057 	/* connect to server */
1058 	if ((conn = ftp_connect(url, purl, flags)) == NULL)
1059 		return (NULL);
1060 	if (cached_connection)
1061 		ftp_disconnect(cached_connection);
1062 	cached_connection = fetch_ref(conn);
1063 	memcpy(&cached_host, url, sizeof(*url));
1064 	return (conn);
1065 }
1066 
1067 /*
1068  * Check the proxy settings
1069  */
1070 static struct url *
1071 ftp_get_proxy(struct url * url, const char *flags)
1072 {
1073 	struct url *purl;
1074 	char *p;
1075 
1076 	if (flags != NULL && strchr(flags, 'd') != NULL)
1077 		return (NULL);
1078 	if (fetch_no_proxy_match(url->host))
1079 		return (NULL);
1080 	if (((p = getenv("FTP_PROXY")) || (p = getenv("ftp_proxy")) ||
1081 		(p = getenv("HTTP_PROXY")) || (p = getenv("http_proxy"))) &&
1082 	    *p && (purl = fetchParseURL(p)) != NULL) {
1083 		if (!*purl->scheme) {
1084 			if (getenv("FTP_PROXY") || getenv("ftp_proxy"))
1085 				strcpy(purl->scheme, SCHEME_FTP);
1086 			else
1087 				strcpy(purl->scheme, SCHEME_HTTP);
1088 		}
1089 		if (!purl->port)
1090 			purl->port = fetch_default_proxy_port(purl->scheme);
1091 		if (strcmp(purl->scheme, SCHEME_FTP) == 0 ||
1092 		    strcmp(purl->scheme, SCHEME_HTTP) == 0)
1093 			return (purl);
1094 		fetchFreeURL(purl);
1095 	}
1096 	return (NULL);
1097 }
1098 
1099 /*
1100  * Process an FTP request
1101  */
1102 FILE *
1103 ftp_request(struct url *url, const char *op, struct url_stat *us,
1104     struct url *purl, const char *flags)
1105 {
1106 	conn_t *conn;
1107 	int oflag;
1108 
1109 	/* check if we should use HTTP instead */
1110 	if (purl && (strcmp(purl->scheme, SCHEME_HTTP) == 0 ||
1111 	    strcmp(purl->scheme, SCHEME_HTTPS) == 0)) {
1112 		if (strcmp(op, "STAT") == 0)
1113 			return (http_request(url, "HEAD", us, purl, flags));
1114 		else if (strcmp(op, "RETR") == 0)
1115 			return (http_request(url, "GET", us, purl, flags));
1116 		/*
1117 		 * Our HTTP code doesn't support PUT requests yet, so try
1118 		 * a direct connection.
1119 		 */
1120 	}
1121 
1122 	/* connect to server */
1123 	conn = ftp_cached_connect(url, purl, flags);
1124 	if (purl)
1125 		fetchFreeURL(purl);
1126 	if (conn == NULL)
1127 		return (NULL);
1128 
1129 	/* change directory */
1130 	if (ftp_cwd(conn, url->doc) == -1)
1131 		goto errsock;
1132 
1133 	/* stat file */
1134 	if (us && ftp_stat(conn, url->doc, us) == -1
1135 	    && fetchLastErrCode != FETCH_PROTO
1136 	    && fetchLastErrCode != FETCH_UNAVAIL)
1137 		goto errsock;
1138 
1139 	/* just a stat */
1140 	if (strcmp(op, "STAT") == 0) {
1141 		--conn->ref;
1142 		ftp_disconnect(conn);
1143 		return (FILE *)1; /* bogus return value */
1144 	}
1145 	if (strcmp(op, "STOR") == 0 || strcmp(op, "APPE") == 0)
1146 		oflag = O_WRONLY;
1147 	else
1148 		oflag = O_RDONLY;
1149 
1150 	/* initiate the transfer */
1151 	return (ftp_transfer(conn, op, url->doc, oflag, url->offset, flags));
1152 
1153 errsock:
1154 	ftp_disconnect(conn);
1155 	return (NULL);
1156 }
1157 
1158 /*
1159  * Get and stat file
1160  */
1161 FILE *
1162 fetchXGetFTP(struct url *url, struct url_stat *us, const char *flags)
1163 {
1164 	return (ftp_request(url, "RETR", us, ftp_get_proxy(url, flags), flags));
1165 }
1166 
1167 /*
1168  * Get file
1169  */
1170 FILE *
1171 fetchGetFTP(struct url *url, const char *flags)
1172 {
1173 	return (fetchXGetFTP(url, NULL, flags));
1174 }
1175 
1176 /*
1177  * Put file
1178  */
1179 FILE *
1180 fetchPutFTP(struct url *url, const char *flags)
1181 {
1182 	return (ftp_request(url, CHECK_FLAG('a') ? "APPE" : "STOR", 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 	FILE *f;
1193 
1194 	f = ftp_request(url, "STAT", us, ftp_get_proxy(url, flags), flags);
1195 	if (f == NULL)
1196 		return (-1);
1197 	/*
1198 	 * When op is "STAT", ftp_request() will return either NULL or
1199 	 * (FILE *)1, never a valid FILE *, so we mustn't fclose(f) before
1200 	 * returning, as it would cause a segfault.
1201 	 */
1202 	return (0);
1203 }
1204 
1205 /*
1206  * List a directory
1207  */
1208 struct url_ent *
1209 fetchListFTP(struct url *url __unused, const char *flags __unused)
1210 {
1211 	warnx("fetchListFTP(): not implemented");
1212 	return (NULL);
1213 }
1214