Sync usage with man page.
[netbsd-mini2440.git] / external / bsd / fetch / dist / libfetch / ftp.c
blob4745b5e16c6dcb3a2bfbee60f43f61964d4f21c5
1 /* $NetBSD: ftp.c,v 1.30 2009/10/15 12:36:57 joerg Exp $ */
2 /*-
3 * Copyright (c) 1998-2004 Dag-Erling Coïdan Smørgrav
4 * Copyright (c) 2008, 2009 Joerg Sonnenberger <joerg@NetBSD.org>
5 * All rights reserved.
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
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.
30 * $FreeBSD: ftp.c,v 1.101 2008/01/23 20:57:59 des Exp $
34 * Portions of this code were taken from or based on ftpio.c:
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 * ----------------------------------------------------------------------------
43 * Major Changelog:
45 * Dag-Erling Coïdan Smørgrav
46 * 9 Jun 1998
48 * Incorporated into libfetch
50 * Jordan K. Hubbard
51 * 17 Jan 1996
53 * Turned inside out. Now returns xfers as new file ids, not as a special
54 * `state' of FTP_t
56 * $ftpioId: ftpio.c,v 1.30 1998/04/11 07:28:53 phk Exp $
60 #ifdef __linux__
61 /* Keep this down to Linux, it can create surprises else where. */
62 #define _GNU_SOURCE
63 #endif
65 #if HAVE_CONFIG_H
66 #include "config.h"
67 #endif
68 #ifndef NETBSD
69 #include <nbcompat.h>
70 #endif
72 #include <sys/types.h>
73 #include <sys/socket.h>
75 #include <netinet/in.h>
76 #include <arpa/inet.h>
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>
97 #include "fetch.h"
98 #include "common.h"
99 #include "ftperr.h"
101 #define FTP_ANONYMOUS_USER "anonymous"
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
123 static struct url cached_host;
124 static conn_t *cached_connection;
126 #define isftpreply(foo) \
127 (isdigit((unsigned char)foo[0]) && \
128 isdigit((unsigned char)foo[1]) && \
129 isdigit((unsigned char)foo[2]) && \
130 (foo[3] == ' ' || foo[3] == '\0'))
131 #define isftpinfo(foo) \
132 (isdigit((unsigned char)foo[0]) && \
133 isdigit((unsigned char)foo[1]) && \
134 isdigit((unsigned char)foo[2]) && \
135 foo[3] == '-')
138 * Translate IPv4 mapped IPv6 address to IPv4 address
140 static void
141 unmappedaddr(struct sockaddr_in6 *sin6, socklen_t *len)
143 struct sockaddr_in *sin4;
144 uint32_t addr;
145 int port;
147 if (sin6->sin6_family != AF_INET6 ||
148 !IN6_IS_ADDR_V4MAPPED(&sin6->sin6_addr))
149 return;
150 sin4 = (struct sockaddr_in *)sin6;
151 addr = *(uint32_t *)&sin6->sin6_addr.s6_addr[12];
152 port = sin6->sin6_port;
153 memset(sin4, 0, sizeof(struct sockaddr_in));
154 sin4->sin_addr.s_addr = addr;
155 sin4->sin_port = port;
156 sin4->sin_family = AF_INET;
157 *len = sizeof(struct sockaddr_in);
158 #ifdef HAVE_SA_LEN
159 sin4->sin_len = sizeof(struct sockaddr_in);
160 #endif
164 * Get server response
166 static int
167 ftp_chkerr(conn_t *conn)
169 if (fetch_getln(conn) == -1) {
170 fetch_syserr();
171 return (-1);
173 if (isftpinfo(conn->buf)) {
174 while (conn->buflen && !isftpreply(conn->buf)) {
175 if (fetch_getln(conn) == -1) {
176 fetch_syserr();
177 return (-1);
182 while (conn->buflen &&
183 isspace((unsigned char)conn->buf[conn->buflen - 1]))
184 conn->buflen--;
185 conn->buf[conn->buflen] = '\0';
187 if (!isftpreply(conn->buf)) {
188 ftp_seterr(FTP_PROTOCOL_ERROR);
189 return (-1);
192 conn->err = (conn->buf[0] - '0') * 100
193 + (conn->buf[1] - '0') * 10
194 + (conn->buf[2] - '0');
196 return (conn->err);
200 * Send a command and check reply
202 static int
203 ftp_cmd(conn_t *conn, const char *fmt, ...)
205 va_list ap;
206 size_t len;
207 char *msg;
208 int r;
210 va_start(ap, fmt);
211 len = vasprintf(&msg, fmt, ap);
212 va_end(ap);
214 if (msg == NULL) {
215 errno = ENOMEM;
216 fetch_syserr();
217 return (-1);
220 r = fetch_putln(conn, msg, len);
221 free(msg);
223 if (r == -1) {
224 fetch_syserr();
225 return (-1);
228 return (ftp_chkerr(conn));
232 * Return a pointer to the filename part of a path
234 static const char *
235 ftp_filename(const char *file, int *len, int *type, int subdir)
237 const char *s;
239 if ((s = strrchr(file, '/')) == NULL || subdir)
240 s = file;
241 else
242 s = s + 1;
243 *len = strlen(s);
244 if (*len > 7 && strncmp(s + *len - 7, ";type=", 6) == 0) {
245 *type = s[*len - 1];
246 *len -= 7;
247 } else {
248 *type = '\0';
250 return (s);
254 * Get current working directory from the reply to a CWD, PWD or CDUP
255 * command.
257 static int
258 ftp_pwd(conn_t *conn, char *pwd, size_t pwdlen)
260 char *src, *dst, *end;
261 int q;
263 if (conn->err != FTP_WORKING_DIRECTORY &&
264 conn->err != FTP_FILE_ACTION_OK)
265 return (FTP_PROTOCOL_ERROR);
266 end = conn->buf + conn->buflen;
267 src = conn->buf + 4;
268 if (src >= end || *src++ != '"')
269 return (FTP_PROTOCOL_ERROR);
270 for (q = 0, dst = pwd; src < end && pwdlen--; ++src) {
271 if (!q && *src == '"')
272 q = 1;
273 else if (q && *src != '"')
274 break;
275 else if (q)
276 *dst++ = '"', q = 0;
277 else
278 *dst++ = *src;
280 if (!pwdlen)
281 return (FTP_PROTOCOL_ERROR);
282 *dst = '\0';
283 return (FTP_OK);
287 * Change working directory to the directory that contains the specified
288 * file.
290 static int
291 ftp_cwd(conn_t *conn, const char *file, int subdir)
293 const char *beg, *end;
294 char pwd[PATH_MAX];
295 int e, i, len;
297 /* If no slashes in name, no need to change dirs. */
298 if (subdir)
299 end = file + strlen(file);
300 else if ((end = strrchr(file, '/')) == NULL)
301 return (0);
302 if ((e = ftp_cmd(conn, "PWD")) != FTP_WORKING_DIRECTORY ||
303 (e = ftp_pwd(conn, pwd, sizeof(pwd))) != FTP_OK) {
304 ftp_seterr(e);
305 return (-1);
307 for (;;) {
308 len = strlen(pwd);
310 /* Look for a common prefix between PWD and dir to fetch. */
311 for (i = 0; i <= len && i <= end - file; ++i)
312 if (pwd[i] != file[i])
313 break;
314 /* Keep going up a dir until we have a matching prefix. */
315 if (strcmp(pwd, "/") == 0)
316 break;
317 if (pwd[i] == '\0' && (file[i - 1] == '/' || file[i] == '/'))
318 break;
319 if ((e = ftp_cmd(conn, "CDUP")) != FTP_FILE_ACTION_OK ||
320 (e = ftp_cmd(conn, "PWD")) != FTP_WORKING_DIRECTORY ||
321 (e = ftp_pwd(conn, pwd, sizeof(pwd))) != FTP_OK) {
322 ftp_seterr(e);
323 return (-1);
327 #ifdef FTP_COMBINE_CWDS
328 /* Skip leading slashes, even "////". */
329 for (beg = file + i; beg < end && *beg == '/'; ++beg, ++i)
330 /* nothing */ ;
332 /* If there is no trailing dir, we're already there. */
333 if (beg >= end)
334 return (0);
336 /* Change to the directory all in one chunk (e.g., foo/bar/baz). */
337 e = ftp_cmd(conn, "CWD %.*s", (int)(end - beg), beg);
338 if (e == FTP_FILE_ACTION_OK)
339 return (0);
340 #endif /* FTP_COMBINE_CWDS */
342 /* That didn't work so go back to legacy behavior (multiple CWDs). */
343 for (beg = file + i; beg < end; beg = file + i + 1) {
344 while (*beg == '/')
345 ++beg, ++i;
346 for (++i; file + i < end && file[i] != '/'; ++i)
347 /* nothing */ ;
348 e = ftp_cmd(conn, "CWD %.*s", file + i - beg, beg);
349 if (e != FTP_FILE_ACTION_OK) {
350 ftp_seterr(e);
351 return (-1);
354 return (0);
358 * Set transfer mode and data type
360 static int
361 ftp_mode_type(conn_t *conn, int mode, int type)
363 int e;
365 switch (mode) {
366 case 0:
367 case 's':
368 mode = 'S';
369 case 'S':
370 break;
371 default:
372 return (FTP_PROTOCOL_ERROR);
374 if ((e = ftp_cmd(conn, "MODE %c", mode)) != FTP_OK) {
375 if (mode == 'S') {
377 * Stream mode is supposed to be the default - so
378 * much so that some servers not only do not
379 * support any other mode, but do not support the
380 * MODE command at all.
382 * If "MODE S" fails, it is unlikely that we
383 * previously succeeded in setting a different
384 * mode. Therefore, we simply hope that the
385 * server is already in the correct mode, and
386 * silently ignore the failure.
388 } else {
389 return (e);
393 switch (type) {
394 case 0:
395 case 'i':
396 type = 'I';
397 case 'I':
398 break;
399 case 'a':
400 type = 'A';
401 case 'A':
402 break;
403 case 'd':
404 type = 'D';
405 case 'D':
406 /* can't handle yet */
407 default:
408 return (FTP_PROTOCOL_ERROR);
410 if ((e = ftp_cmd(conn, "TYPE %c", type)) != FTP_OK)
411 return (e);
413 return (FTP_OK);
417 * Request and parse file stats
419 static int
420 ftp_stat(conn_t *conn, const char *file, struct url_stat *us)
422 char *ln;
423 const char *filename;
424 int filenamelen, type;
425 struct tm tm;
426 time_t t;
427 int e;
429 us->size = -1;
430 us->atime = us->mtime = 0;
432 filename = ftp_filename(file, &filenamelen, &type, 0);
434 if ((e = ftp_mode_type(conn, 0, type)) != FTP_OK) {
435 ftp_seterr(e);
436 return (-1);
439 e = ftp_cmd(conn, "SIZE %.*s", filenamelen, filename);
440 if (e != FTP_FILE_STATUS) {
441 ftp_seterr(e);
442 return (-1);
444 for (ln = conn->buf + 4; *ln && isspace((unsigned char)*ln); ln++)
445 /* nothing */ ;
446 for (us->size = 0; *ln && isdigit((unsigned char)*ln); ln++)
447 us->size = us->size * 10 + *ln - '0';
448 if (*ln && !isspace((unsigned char)*ln)) {
449 ftp_seterr(FTP_PROTOCOL_ERROR);
450 us->size = -1;
451 return (-1);
453 if (us->size == 0)
454 us->size = -1;
456 e = ftp_cmd(conn, "MDTM %.*s", filenamelen, filename);
457 if (e != FTP_FILE_STATUS) {
458 ftp_seterr(e);
459 return (-1);
461 for (ln = conn->buf + 4; *ln && isspace((unsigned char)*ln); ln++)
462 /* nothing */ ;
463 switch (strspn(ln, "0123456789")) {
464 case 14:
465 break;
466 case 15:
467 ln++;
468 ln[0] = '2';
469 ln[1] = '0';
470 break;
471 default:
472 ftp_seterr(FTP_PROTOCOL_ERROR);
473 return (-1);
475 if (sscanf(ln, "%04d%02d%02d%02d%02d%02d",
476 &tm.tm_year, &tm.tm_mon, &tm.tm_mday,
477 &tm.tm_hour, &tm.tm_min, &tm.tm_sec) != 6) {
478 ftp_seterr(FTP_PROTOCOL_ERROR);
479 return (-1);
481 tm.tm_mon--;
482 tm.tm_year -= 1900;
483 tm.tm_isdst = -1;
484 t = timegm(&tm);
485 if (t == (time_t)-1)
486 t = time(NULL);
487 us->mtime = t;
488 us->atime = t;
490 return (0);
494 * I/O functions for FTP
496 struct ftpio {
497 conn_t *cconn; /* Control connection */
498 conn_t *dconn; /* Data connection */
499 int dir; /* Direction */
500 int eof; /* EOF reached */
501 int err; /* Error code */
504 static ssize_t ftp_readfn(void *, void *, size_t);
505 static ssize_t ftp_writefn(void *, const void *, size_t);
506 static void ftp_closefn(void *);
508 static ssize_t
509 ftp_readfn(void *v, void *buf, size_t len)
511 struct ftpio *io;
512 int r;
514 io = (struct ftpio *)v;
515 if (io == NULL) {
516 errno = EBADF;
517 return (-1);
519 if (io->cconn == NULL || io->dconn == NULL || io->dir == O_WRONLY) {
520 errno = EBADF;
521 return (-1);
523 if (io->err) {
524 errno = io->err;
525 return (-1);
527 if (io->eof)
528 return (0);
529 r = fetch_read(io->dconn, buf, len);
530 if (r > 0)
531 return (r);
532 if (r == 0) {
533 io->eof = 1;
534 return (0);
536 if (errno != EINTR)
537 io->err = errno;
538 return (-1);
541 static ssize_t
542 ftp_writefn(void *v, const void *buf, size_t len)
544 struct ftpio *io;
545 int w;
547 io = (struct ftpio *)v;
548 if (io == NULL) {
549 errno = EBADF;
550 return (-1);
552 if (io->cconn == NULL || io->dconn == NULL || io->dir == O_RDONLY) {
553 errno = EBADF;
554 return (-1);
556 if (io->err) {
557 errno = io->err;
558 return (-1);
560 w = fetch_write(io->dconn, buf, len);
561 if (w >= 0)
562 return (w);
563 if (errno != EINTR)
564 io->err = errno;
565 return (-1);
568 static void
569 ftp_closefn(void *v)
571 struct ftpio *io;
572 int r;
574 io = (struct ftpio *)v;
575 if (io == NULL) {
576 errno = EBADF;
577 return;
579 if (io->dir == -1)
580 return;
581 if (io->cconn == NULL || io->dconn == NULL) {
582 errno = EBADF;
583 return;
585 fetch_close(io->dconn);
586 io->dir = -1;
587 io->dconn->is_active = 0;
588 io->dconn = NULL;
589 r = ftp_chkerr(io->cconn);
590 if (io->cconn == cached_connection && io->cconn->ref == 1) {
591 free(cached_host.doc);
592 cached_connection = NULL;
594 fetch_close(io->cconn);
595 free(io);
596 return;
599 static fetchIO *
600 ftp_setup(conn_t *cconn, conn_t *dconn, int mode)
602 struct ftpio *io;
603 fetchIO *f;
605 if (cconn == NULL || dconn == NULL)
606 return (NULL);
607 if ((io = malloc(sizeof(*io))) == NULL)
608 return (NULL);
609 io->cconn = cconn;
610 io->dconn = dconn;
611 io->dir = mode;
612 io->eof = io->err = 0;
613 io->cconn->is_active = 1;
614 f = fetchIO_unopen(io, ftp_readfn, ftp_writefn, ftp_closefn);
615 if (f == NULL)
616 free(io);
617 return (f);
621 * Transfer file
623 static fetchIO *
624 ftp_transfer(conn_t *conn, const char *oper, const char *file, const char *op_arg,
625 int mode, off_t offset, const char *flags)
627 union anonymous {
628 struct sockaddr_storage ss;
629 struct sockaddr sa;
630 struct sockaddr_in6 sin6;
631 struct sockaddr_in sin4;
632 } u;
633 const char *bindaddr;
634 const char *filename;
635 int filenamelen, type;
636 int low, pasv, verbose;
637 int e, sd = -1;
638 socklen_t l;
639 char *s;
640 fetchIO *df;
642 /* check flags */
643 low = CHECK_FLAG('l');
644 pasv = !CHECK_FLAG('a');
645 verbose = CHECK_FLAG('v');
647 /* passive mode */
648 if (!pasv)
649 pasv = ((s = getenv("FTP_PASSIVE_MODE")) != NULL &&
650 strncasecmp(s, "no", 2) != 0);
652 /* isolate filename */
653 filename = ftp_filename(file, &filenamelen, &type, op_arg != NULL);
655 /* set transfer mode and data type */
656 if ((e = ftp_mode_type(conn, 0, type)) != FTP_OK)
657 goto ouch;
659 /* find our own address, bind, and listen */
660 l = sizeof(u.ss);
661 if (getsockname(conn->sd, &u.sa, &l) == -1)
662 goto sysouch;
663 if (u.ss.ss_family == AF_INET6)
664 unmappedaddr(&u.sin6, &l);
666 retry_mode:
668 /* open data socket */
669 if ((sd = socket(u.ss.ss_family, SOCK_STREAM, IPPROTO_TCP)) == -1) {
670 fetch_syserr();
671 return (NULL);
674 if (pasv) {
675 unsigned char addr[64];
676 char *ln, *p;
677 unsigned int i;
678 int port;
680 /* send PASV command */
681 if (verbose)
682 fetch_info("setting passive mode");
683 switch (u.ss.ss_family) {
684 case AF_INET:
685 if ((e = ftp_cmd(conn, "PASV")) != FTP_PASSIVE_MODE)
686 goto ouch;
687 break;
688 case AF_INET6:
689 if ((e = ftp_cmd(conn, "EPSV")) != FTP_EPASSIVE_MODE) {
690 if (e == -1)
691 goto ouch;
692 if ((e = ftp_cmd(conn, "LPSV")) !=
693 FTP_LPASSIVE_MODE)
694 goto ouch;
696 break;
697 default:
698 e = FTP_PROTOCOL_ERROR; /* XXX: error code should be prepared */
699 goto ouch;
703 * Find address and port number. The reply to the PASV command
704 * is IMHO the one and only weak point in the FTP protocol.
706 ln = conn->buf;
707 switch (e) {
708 case FTP_PASSIVE_MODE:
709 case FTP_LPASSIVE_MODE:
710 for (p = ln + 3; *p && !isdigit((unsigned char)*p); p++)
711 /* nothing */ ;
712 if (!*p) {
713 e = FTP_PROTOCOL_ERROR;
714 goto ouch;
716 l = (e == FTP_PASSIVE_MODE ? 6 : 21);
717 for (i = 0; *p && i < l; i++, p++)
718 addr[i] = strtol(p, &p, 10);
719 if (i < l) {
720 e = FTP_PROTOCOL_ERROR;
721 goto ouch;
723 break;
724 case FTP_EPASSIVE_MODE:
725 for (p = ln + 3; *p && *p != '('; p++)
726 /* nothing */ ;
727 if (!*p) {
728 e = FTP_PROTOCOL_ERROR;
729 goto ouch;
731 ++p;
732 if (sscanf(p, "%c%c%c%d%c", &addr[0], &addr[1], &addr[2],
733 &port, &addr[3]) != 5 ||
734 addr[0] != addr[1] ||
735 addr[0] != addr[2] || addr[0] != addr[3]) {
736 e = FTP_PROTOCOL_ERROR;
737 goto ouch;
739 break;
740 case FTP_SYNTAX_ERROR:
741 if (verbose)
742 fetch_info("passive mode failed");
743 /* Close socket and retry with passive mode. */
744 pasv = 0;
745 close(sd);
746 sd = -1;
747 goto retry_mode;
750 /* seek to required offset */
751 if (offset)
752 if (ftp_cmd(conn, "REST %lu", (unsigned long)offset) != FTP_FILE_OK)
753 goto sysouch;
755 /* construct sockaddr for data socket */
756 l = sizeof(u.ss);
757 if (getpeername(conn->sd, &u.sa, &l) == -1)
758 goto sysouch;
759 if (u.ss.ss_family == AF_INET6)
760 unmappedaddr(&u.sin6, &l);
761 switch (u.ss.ss_family) {
762 case AF_INET6:
763 if (e == FTP_EPASSIVE_MODE)
764 u.sin6.sin6_port = htons(port);
765 else {
766 memcpy(&u.sin6.sin6_addr, addr + 2, 16);
767 memcpy(&u.sin6.sin6_port, addr + 19, 2);
769 break;
770 case AF_INET:
771 if (e == FTP_EPASSIVE_MODE)
772 u.sin4.sin_port = htons(port);
773 else {
774 memcpy(&u.sin4.sin_addr, addr, 4);
775 memcpy(&u.sin4.sin_port, addr + 4, 2);
777 break;
778 default:
779 e = FTP_PROTOCOL_ERROR; /* XXX: error code should be prepared */
780 break;
783 /* connect to data port */
784 if (verbose)
785 fetch_info("opening data connection");
786 bindaddr = getenv("FETCH_BIND_ADDRESS");
787 if (bindaddr != NULL && *bindaddr != '\0' &&
788 fetch_bind(sd, u.ss.ss_family, bindaddr) != 0)
789 goto sysouch;
790 if (connect(sd, &u.sa, l) == -1)
791 goto sysouch;
793 /* make the server initiate the transfer */
794 if (verbose)
795 fetch_info("initiating transfer");
796 if (op_arg)
797 e = ftp_cmd(conn, "%s%s%s", oper, *op_arg ? " " : "", op_arg);
798 else
799 e = ftp_cmd(conn, "%s %.*s", oper,
800 filenamelen, filename);
801 if (e != FTP_CONNECTION_ALREADY_OPEN && e != FTP_OPEN_DATA_CONNECTION)
802 goto ouch;
804 } else {
805 uint32_t a;
806 uint16_t p;
807 #if defined(IPV6_PORTRANGE) || defined(IP_PORTRANGE)
808 int arg;
809 #endif
810 int d;
811 char *ap;
812 char hname[INET6_ADDRSTRLEN];
814 switch (u.ss.ss_family) {
815 case AF_INET6:
816 u.sin6.sin6_port = 0;
817 #ifdef IPV6_PORTRANGE
818 arg = low ? IPV6_PORTRANGE_DEFAULT : IPV6_PORTRANGE_HIGH;
819 if (setsockopt(sd, IPPROTO_IPV6, IPV6_PORTRANGE,
820 (char *)&arg, sizeof(arg)) == -1)
821 goto sysouch;
822 #endif
823 break;
824 case AF_INET:
825 u.sin4.sin_port = 0;
826 #ifdef IP_PORTRANGE
827 arg = low ? IP_PORTRANGE_DEFAULT : IP_PORTRANGE_HIGH;
828 if (setsockopt(sd, IPPROTO_IP, IP_PORTRANGE,
829 (char *)&arg, sizeof(arg)) == -1)
830 goto sysouch;
831 #endif
832 break;
834 if (verbose)
835 fetch_info("binding data socket");
836 if (bind(sd, &u.sa, l) == -1)
837 goto sysouch;
838 if (listen(sd, 1) == -1)
839 goto sysouch;
841 /* find what port we're on and tell the server */
842 if (getsockname(sd, &u.sa, &l) == -1)
843 goto sysouch;
844 switch (u.ss.ss_family) {
845 case AF_INET:
846 a = ntohl(u.sin4.sin_addr.s_addr);
847 p = ntohs(u.sin4.sin_port);
848 e = ftp_cmd(conn, "PORT %d,%d,%d,%d,%d,%d",
849 (a >> 24) & 0xff, (a >> 16) & 0xff,
850 (a >> 8) & 0xff, a & 0xff,
851 (p >> 8) & 0xff, p & 0xff);
852 break;
853 case AF_INET6:
854 #define UC(b) (((int)b)&0xff)
855 e = -1;
856 u.sin6.sin6_scope_id = 0;
857 if (getnameinfo(&u.sa, l,
858 hname, sizeof(hname),
859 NULL, 0, NI_NUMERICHOST) == 0) {
860 e = ftp_cmd(conn, "EPRT |%d|%s|%d|", 2, hname,
861 htons(u.sin6.sin6_port));
862 if (e == -1)
863 goto ouch;
865 if (e != FTP_OK) {
866 ap = (char *)&u.sin6.sin6_addr;
867 e = ftp_cmd(conn,
868 "LPRT %d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d",
869 6, 16,
870 UC(ap[0]), UC(ap[1]), UC(ap[2]), UC(ap[3]),
871 UC(ap[4]), UC(ap[5]), UC(ap[6]), UC(ap[7]),
872 UC(ap[8]), UC(ap[9]), UC(ap[10]), UC(ap[11]),
873 UC(ap[12]), UC(ap[13]), UC(ap[14]), UC(ap[15]),
875 (ntohs(u.sin6.sin6_port) >> 8) & 0xff,
876 ntohs(u.sin6.sin6_port) & 0xff);
878 break;
879 default:
880 e = FTP_PROTOCOL_ERROR; /* XXX: error code should be prepared */
881 goto ouch;
883 if (e != FTP_OK)
884 goto ouch;
886 /* seek to required offset */
887 if (offset)
888 if (ftp_cmd(conn, "REST %llu", (unsigned long long)offset) != FTP_FILE_OK)
889 goto sysouch;
891 /* make the server initiate the transfer */
892 if (verbose)
893 fetch_info("initiating transfer");
894 if (op_arg)
895 e = ftp_cmd(conn, "%s%s%s", oper, *op_arg ? " " : "", op_arg);
896 else
897 e = ftp_cmd(conn, "%s %.*s", oper,
898 filenamelen, filename);
899 if (e != FTP_CONNECTION_ALREADY_OPEN && e != FTP_OPEN_DATA_CONNECTION)
900 goto ouch;
902 /* accept the incoming connection and go to town */
903 if ((d = accept(sd, NULL, NULL)) == -1)
904 goto sysouch;
905 close(sd);
906 sd = d;
909 if ((df = ftp_setup(conn, fetch_reopen(sd), mode)) == NULL)
910 goto sysouch;
911 return (df);
913 sysouch:
914 fetch_syserr();
915 if (sd >= 0)
916 close(sd);
917 return (NULL);
919 ouch:
920 if (e != -1)
921 ftp_seterr(e);
922 if (sd >= 0)
923 close(sd);
924 return (NULL);
928 * Authenticate
930 static int
931 ftp_authenticate(conn_t *conn, struct url *url, struct url *purl)
933 const char *user, *pwd, *login_name;
934 char pbuf[URL_USERLEN + 1 + URL_HOSTLEN + 1];
935 int e, len;
937 /* XXX FTP_AUTH, and maybe .netrc */
939 /* send user name and password */
940 if (url->user[0] == '\0')
941 fetch_netrc_auth(url);
942 user = url->user;
943 if (*user == '\0')
944 user = getenv("FTP_LOGIN");
945 if (user == NULL || *user == '\0')
946 user = FTP_ANONYMOUS_USER;
947 if (purl && url->port == fetch_default_port(url->scheme))
948 e = ftp_cmd(conn, "USER %s@%s", user, url->host);
949 else if (purl)
950 e = ftp_cmd(conn, "USER %s@%s@%d", user, url->host, url->port);
951 else
952 e = ftp_cmd(conn, "USER %s", user);
954 /* did the server request a password? */
955 if (e == FTP_NEED_PASSWORD) {
956 pwd = url->pwd;
957 if (*pwd == '\0')
958 pwd = getenv("FTP_PASSWORD");
959 if (pwd == NULL || *pwd == '\0') {
960 if ((login_name = getlogin()) == 0)
961 login_name = FTP_ANONYMOUS_USER;
962 if ((len = snprintf(pbuf, URL_USERLEN + 2, "%s@", login_name)) < 0)
963 len = 0;
964 else if (len > URL_USERLEN + 1)
965 len = URL_USERLEN + 1;
966 gethostname(pbuf + len, sizeof(pbuf) - len);
967 /* MAXHOSTNAMELEN can differ from URL_HOSTLEN + 1 */
968 pbuf[sizeof(pbuf) - 1] = '\0';
969 pwd = pbuf;
971 e = ftp_cmd(conn, "PASS %s", pwd);
974 return (e);
978 * Log on to FTP server
980 static conn_t *
981 ftp_connect(struct url *url, struct url *purl, const char *flags)
983 conn_t *conn;
984 int e, direct, verbose;
985 #ifdef INET6
986 int af = AF_UNSPEC;
987 #else
988 int af = AF_INET;
989 #endif
991 direct = CHECK_FLAG('d');
992 verbose = CHECK_FLAG('v');
993 if (CHECK_FLAG('4'))
994 af = AF_INET;
995 else if (CHECK_FLAG('6'))
996 af = AF_INET6;
998 if (direct)
999 purl = NULL;
1001 /* check for proxy */
1002 if (purl) {
1003 /* XXX proxy authentication! */
1004 conn = fetch_connect(purl->host, purl->port, af, verbose);
1005 } else {
1006 /* no proxy, go straight to target */
1007 conn = fetch_connect(url->host, url->port, af, verbose);
1008 purl = NULL;
1011 /* check connection */
1012 if (conn == NULL)
1013 /* fetch_connect() has already set an error code */
1014 return (NULL);
1016 /* expect welcome message */
1017 if ((e = ftp_chkerr(conn)) != FTP_SERVICE_READY)
1018 goto fouch;
1020 /* authenticate */
1021 if ((e = ftp_authenticate(conn, url, purl)) != FTP_LOGGED_IN)
1022 goto fouch;
1024 /* TODO: Request extended features supported, if any (RFC 3659). */
1026 /* done */
1027 return (conn);
1029 fouch:
1030 if (e != -1)
1031 ftp_seterr(e);
1032 fetch_close(conn);
1033 return (NULL);
1037 * Disconnect from server
1039 static void
1040 ftp_disconnect(conn_t *conn)
1042 (void)ftp_cmd(conn, "QUIT");
1043 if (conn == cached_connection && conn->ref == 1) {
1044 free(cached_host.doc);
1045 cached_host.doc = NULL;
1046 cached_connection = NULL;
1048 fetch_close(conn);
1052 * Check if we're already connected
1054 static int
1055 ftp_isconnected(struct url *url)
1057 return (cached_connection
1058 && (cached_connection->is_active == 0)
1059 && (strcmp(url->host, cached_host.host) == 0)
1060 && (strcmp(url->user, cached_host.user) == 0)
1061 && (strcmp(url->pwd, cached_host.pwd) == 0)
1062 && (url->port == cached_host.port));
1066 * Check the cache, reconnect if no luck
1068 static conn_t *
1069 ftp_cached_connect(struct url *url, struct url *purl, const char *flags)
1071 char *doc;
1072 conn_t *conn;
1073 int e;
1075 /* set default port */
1076 if (!url->port)
1077 url->port = fetch_default_port(url->scheme);
1079 /* try to use previously cached connection */
1080 if (ftp_isconnected(url)) {
1081 e = ftp_cmd(cached_connection, "NOOP");
1082 if (e == FTP_OK || e == FTP_SYNTAX_ERROR)
1083 return (fetch_ref(cached_connection));
1086 /* connect to server */
1087 if ((conn = ftp_connect(url, purl, flags)) == NULL)
1088 return (NULL);
1089 doc = strdup(url->doc);
1090 if (doc != NULL) {
1091 if (cached_connection)
1092 ftp_disconnect(cached_connection);
1093 cached_connection = fetch_ref(conn);
1094 memcpy(&cached_host, url, sizeof(*url));
1095 cached_host.doc = doc;
1097 return (conn);
1101 * Check the proxy settings
1103 static struct url *
1104 ftp_get_proxy(struct url * url, const char *flags)
1106 struct url *purl;
1107 char *p;
1109 if (flags != NULL && strchr(flags, 'd') != NULL)
1110 return (NULL);
1111 if (fetch_no_proxy_match(url->host))
1112 return (NULL);
1113 if (((p = getenv("FTP_PROXY")) || (p = getenv("ftp_proxy")) ||
1114 (p = getenv("HTTP_PROXY")) || (p = getenv("http_proxy"))) &&
1115 *p && (purl = fetchParseURL(p)) != NULL) {
1116 if (!*purl->scheme) {
1117 if (getenv("FTP_PROXY") || getenv("ftp_proxy"))
1118 strcpy(purl->scheme, SCHEME_FTP);
1119 else
1120 strcpy(purl->scheme, SCHEME_HTTP);
1122 if (!purl->port)
1123 purl->port = fetch_default_proxy_port(purl->scheme);
1124 if (strcasecmp(purl->scheme, SCHEME_FTP) == 0 ||
1125 strcasecmp(purl->scheme, SCHEME_HTTP) == 0)
1126 return (purl);
1127 fetchFreeURL(purl);
1129 return (NULL);
1133 * Process an FTP request
1135 fetchIO *
1136 ftp_request(struct url *url, const char *op, const char *op_arg,
1137 struct url_stat *us, struct url *purl, const char *flags)
1139 fetchIO *f;
1140 char *path;
1141 conn_t *conn;
1142 int if_modified_since, oflag;
1143 struct url_stat local_us;
1145 /* check if we should use HTTP instead */
1146 if (purl && strcasecmp(purl->scheme, SCHEME_HTTP) == 0) {
1147 if (strcmp(op, "STAT") == 0)
1148 return (http_request(url, "HEAD", us, purl, flags));
1149 else if (strcmp(op, "RETR") == 0)
1150 return (http_request(url, "GET", us, purl, flags));
1152 * Our HTTP code doesn't support PUT requests yet, so try
1153 * a direct connection.
1157 /* connect to server */
1158 conn = ftp_cached_connect(url, purl, flags);
1159 if (purl)
1160 fetchFreeURL(purl);
1161 if (conn == NULL)
1162 return (NULL);
1164 if ((path = fetchUnquotePath(url)) == NULL) {
1165 fetch_syserr();
1166 return NULL;
1169 /* change directory */
1170 if (ftp_cwd(conn, path, op_arg != NULL) == -1) {
1171 free(path);
1172 return (NULL);
1175 if_modified_since = CHECK_FLAG('i');
1176 if (if_modified_since && us == NULL)
1177 us = &local_us;
1179 /* stat file */
1180 if (us && ftp_stat(conn, path, us) == -1
1181 && fetchLastErrCode != FETCH_PROTO
1182 && fetchLastErrCode != FETCH_UNAVAIL) {
1183 free(path);
1184 return (NULL);
1187 if (if_modified_since && url->last_modified > 0 &&
1188 url->last_modified >= us->mtime) {
1189 free(path);
1190 fetchLastErrCode = FETCH_UNCHANGED;
1191 snprintf(fetchLastErrString, MAXERRSTRING, "Unchanged");
1192 return NULL;
1195 /* just a stat */
1196 if (strcmp(op, "STAT") == 0) {
1197 free(path);
1198 return fetchIO_unopen(NULL, NULL, NULL, NULL);
1200 if (strcmp(op, "STOR") == 0 || strcmp(op, "APPE") == 0)
1201 oflag = O_WRONLY;
1202 else
1203 oflag = O_RDONLY;
1205 /* initiate the transfer */
1206 f = (ftp_transfer(conn, op, path, op_arg, oflag, url->offset, flags));
1207 free(path);
1208 return f;
1212 * Get and stat file
1214 fetchIO *
1215 fetchXGetFTP(struct url *url, struct url_stat *us, const char *flags)
1217 return (ftp_request(url, "RETR", NULL, us, ftp_get_proxy(url, flags), flags));
1221 * Get file
1223 fetchIO *
1224 fetchGetFTP(struct url *url, const char *flags)
1226 return (fetchXGetFTP(url, NULL, flags));
1230 * Put file
1232 fetchIO *
1233 fetchPutFTP(struct url *url, const char *flags)
1235 return (ftp_request(url, CHECK_FLAG('a') ? "APPE" : "STOR", NULL, NULL,
1236 ftp_get_proxy(url, flags), flags));
1240 * Get file stats
1243 fetchStatFTP(struct url *url, struct url_stat *us, const char *flags)
1245 fetchIO *f;
1247 f = ftp_request(url, "STAT", NULL, us, ftp_get_proxy(url, flags), flags);
1248 if (f == NULL)
1249 return (-1);
1250 fetchIO_close(f);
1251 return (0);
1255 * List a directory
1258 fetchListFTP(struct url_list *ue, struct url *url, const char *pattern, const char *flags)
1260 fetchIO *f;
1261 char buf[2 * PATH_MAX], *eol, *eos;
1262 ssize_t len;
1263 size_t cur_off;
1264 int ret;
1266 /* XXX What about proxies? */
1267 if (pattern == NULL || strcmp(pattern, "*") == 0)
1268 pattern = "";
1269 f = ftp_request(url, "NLST", pattern, NULL, ftp_get_proxy(url, flags), flags);
1270 if (f == NULL)
1271 return -1;
1273 cur_off = 0;
1274 ret = 0;
1276 while ((len = fetchIO_read(f, buf + cur_off, sizeof(buf) - cur_off)) > 0) {
1277 cur_off += len;
1278 while ((eol = memchr(buf, '\n', cur_off)) != NULL) {
1279 if (len == eol - buf)
1280 break;
1281 if (eol != buf) {
1282 if (eol[-1] == '\r')
1283 eos = eol - 1;
1284 else
1285 eos = eol;
1286 *eos = '\0';
1287 ret = fetch_add_entry(ue, url, buf, 0);
1288 if (ret)
1289 break;
1290 cur_off -= eol - buf + 1;
1291 memmove(buf, eol + 1, cur_off);
1294 if (ret)
1295 break;
1297 if (cur_off != 0 || len < 0) {
1298 /* Not RFC conform, bail out. */
1299 fetchIO_close(f);
1300 return -1;
1302 fetchIO_close(f);
1303 return ret;