2 * Copyright (c) 1998-2004 Dag-Erling Coïdan Smørgrav
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions
8 * 1. Redistributions of source code must retain the above copyright
9 * notice, this list of conditions and the following disclaimer
10 * in this position and unchanged.
11 * 2. Redistributions in binary form must reproduce the above copyright
12 * notice, this list of conditions and the following disclaimer in the
13 * documentation and/or other materials provided with the distribution.
14 * 3. The name of the author may not be used to endorse or promote products
15 * derived from this software without specific prior written permission
17 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
18 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
19 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
20 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
21 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
22 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
23 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
24 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
25 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
26 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
28 * $FreeBSD: src/lib/libfetch/ftp.c,v 1.102 2008/02/08 09:48:48 des Exp $
29 * $DragonFly: src/lib/libfetch/ftp.c,v 1.4 2007/08/05 21:48:12 swildner Exp $
33 * Portions of this code were taken from or based on ftpio.c:
35 * ----------------------------------------------------------------------------
36 * "THE BEER-WARE LICENSE" (Revision 42):
37 * <phk@FreeBSD.org> wrote this file. As long as you retain this notice you
38 * can do whatever you want with this stuff. If we meet some day, and you think
39 * this stuff is worth it, you can buy me a beer in return. Poul-Henning Kamp
40 * ----------------------------------------------------------------------------
44 * Dag-Erling Coïdan Smørgrav
47 * Incorporated into libfetch
52 * Turned inside out. Now returns xfers as new file ids, not as a special
55 * $ftpioId: ftpio.c,v 1.30 1998/04/11 07:28:53 phk Exp $
59 #include <sys/param.h>
60 #include <sys/socket.h>
61 #include <netinet/in.h>
80 #define FTP_ANONYMOUS_USER "anonymous"
82 #define FTP_CONNECTION_ALREADY_OPEN 125
83 #define FTP_OPEN_DATA_CONNECTION 150
85 #define FTP_FILE_STATUS 213
86 #define FTP_SERVICE_READY 220
87 #define FTP_TRANSFER_COMPLETE 226
88 #define FTP_PASSIVE_MODE 227
89 #define FTP_LPASSIVE_MODE 228
90 #define FTP_EPASSIVE_MODE 229
91 #define FTP_LOGGED_IN 230
92 #define FTP_FILE_ACTION_OK 250
93 #define FTP_DIRECTORY_CREATED 257 /* multiple meanings */
94 #define FTP_FILE_CREATED 257 /* multiple meanings */
95 #define FTP_WORKING_DIRECTORY 257 /* multiple meanings */
96 #define FTP_NEED_PASSWORD 331
97 #define FTP_NEED_ACCOUNT 332
98 #define FTP_FILE_OK 350
99 #define FTP_SYNTAX_ERROR 500
100 #define FTP_PROTOCOL_ERROR 999
102 static int ftp_cmd(conn_t *, const char *, ...) __printflike(2, 3);
103 static struct url cached_host;
104 static conn_t *cached_connection;
106 #define isftpreply(foo) \
107 (isdigit((unsigned char)foo[0]) && \
108 isdigit((unsigned char)foo[1]) && \
109 isdigit((unsigned char)foo[2]) && \
110 (foo[3] == ' ' || foo[3] == '\0'))
111 #define isftpinfo(foo) \
112 (isdigit((unsigned char)foo[0]) && \
113 isdigit((unsigned char)foo[1]) && \
114 isdigit((unsigned char)foo[2]) && \
118 * Translate IPv4 mapped IPv6 address to IPv4 address
121 unmappedaddr(struct sockaddr_in6 *sin6)
123 struct sockaddr_in *sin4;
127 if (sin6->sin6_family != AF_INET6 ||
128 !IN6_IS_ADDR_V4MAPPED(&sin6->sin6_addr))
130 sin4 = (struct sockaddr_in *)sin6;
131 addr = *(u_int32_t *)&sin6->sin6_addr.s6_addr[12];
132 port = sin6->sin6_port;
133 memset(sin4, 0, sizeof(struct sockaddr_in));
134 sin4->sin_addr.s_addr = addr;
135 sin4->sin_port = port;
136 sin4->sin_family = AF_INET;
137 sin4->sin_len = sizeof(struct sockaddr_in);
141 * Get server response
144 ftp_chkerr(conn_t *conn)
146 if (fetch_getln(conn) == -1) {
150 if (isftpinfo(conn->buf)) {
151 while (conn->buflen && !isftpreply(conn->buf)) {
152 if (fetch_getln(conn) == -1) {
159 while (conn->buflen &&
160 isspace((unsigned char)conn->buf[conn->buflen - 1]))
162 conn->buf[conn->buflen] = '\0';
164 if (!isftpreply(conn->buf)) {
165 ftp_seterr(FTP_PROTOCOL_ERROR);
169 conn->err = (conn->buf[0] - '0') * 100
170 + (conn->buf[1] - '0') * 10
171 + (conn->buf[2] - '0');
177 * Send a command and check reply
180 ftp_cmd(conn_t *conn, const char *fmt, ...)
188 len = vasprintf(&msg, fmt, ap);
197 r = fetch_putln(conn, msg, len);
205 return (ftp_chkerr(conn));
209 * Return a pointer to the filename part of a path
212 ftp_filename(const char *file, int *len, int *type)
216 if ((s = strrchr(file, '/')) == NULL)
221 if (*len > 7 && strncmp(s + *len - 7, ";type=", 6) == 0) {
231 * Get current working directory from the reply to a CWD, PWD or CDUP
235 ftp_pwd(conn_t *conn, char *pwd, size_t pwdlen)
237 char *src, *dst, *end;
240 if (conn->err != FTP_WORKING_DIRECTORY &&
241 conn->err != FTP_FILE_ACTION_OK)
242 return (FTP_PROTOCOL_ERROR);
243 end = conn->buf + conn->buflen;
245 if (src >= end || *src++ != '"')
246 return (FTP_PROTOCOL_ERROR);
247 for (q = 0, dst = pwd; src < end && pwdlen--; ++src) {
248 if (!q && *src == '"')
250 else if (q && *src != '"')
258 return (FTP_PROTOCOL_ERROR);
261 DEBUG(fprintf(stderr, "pwd: [%s]\n", pwd));
267 * Change working directory to the directory that contains the specified
271 ftp_cwd(conn_t *conn, const char *file)
273 const char *beg, *end;
277 /* If no slashes in name, no need to change dirs. */
278 if ((end = strrchr(file, '/')) == NULL)
280 if ((e = ftp_cmd(conn, "PWD")) != FTP_WORKING_DIRECTORY ||
281 (e = ftp_pwd(conn, pwd, sizeof(pwd))) != FTP_OK) {
288 /* Look for a common prefix between PWD and dir to fetch. */
289 for (i = 0; i <= len && i <= end - file; ++i)
290 if (pwd[i] != file[i])
293 DEBUG(fprintf(stderr, "have: [%.*s|%s]\n", i, pwd, pwd + i));
294 DEBUG(fprintf(stderr, "want: [%.*s|%s]\n", i, file, file + i));
296 /* Keep going up a dir until we have a matching prefix. */
297 if (pwd[i] == '\0' && (file[i - 1] == '/' || file[i] == '/'))
299 if ((e = ftp_cmd(conn, "CDUP")) != FTP_FILE_ACTION_OK ||
300 (e = ftp_cmd(conn, "PWD")) != FTP_WORKING_DIRECTORY ||
301 (e = ftp_pwd(conn, pwd, sizeof(pwd))) != FTP_OK) {
307 #ifdef FTP_COMBINE_CWDS
308 /* Skip leading slashes, even "////". */
309 for (beg = file + i; beg < end && *beg == '/'; ++beg, ++i)
312 /* If there is no trailing dir, we're already there. */
316 /* Change to the directory all in one chunk (e.g., foo/bar/baz). */
317 e = ftp_cmd(conn, "CWD %.*s", (int)(end - beg), beg);
318 if (e == FTP_FILE_ACTION_OK)
320 #endif /* FTP_COMBINE_CWDS */
322 /* That didn't work so go back to legacy behavior (multiple CWDs). */
323 for (beg = file + i; beg < end; beg = file + i + 1) {
326 for (++i; file + i < end && file[i] != '/'; ++i)
328 e = ftp_cmd(conn, "CWD %.*s", (int)(file + i - beg), beg);
329 if (e != FTP_FILE_ACTION_OK) {
338 * Set transfer mode and data type
341 ftp_mode_type(conn_t *conn, int mode, int type)
352 return (FTP_PROTOCOL_ERROR);
354 if ((e = ftp_cmd(conn, "MODE %c", mode)) != FTP_OK) {
357 * Stream mode is supposed to be the default - so
358 * much so that some servers not only do not
359 * support any other mode, but do not support the
360 * MODE command at all.
362 * If "MODE S" fails, it is unlikely that we
363 * previously succeeded in setting a different
364 * mode. Therefore, we simply hope that the
365 * server is already in the correct mode, and
366 * silently ignore the failure.
386 /* can't handle yet */
388 return (FTP_PROTOCOL_ERROR);
390 if ((e = ftp_cmd(conn, "TYPE %c", type)) != FTP_OK)
397 * Request and parse file stats
400 ftp_stat(conn_t *conn, const char *file, struct url_stat *us)
403 const char *filename;
404 int filenamelen, type;
410 us->atime = us->mtime = 0;
412 filename = ftp_filename(file, &filenamelen, &type);
414 if ((e = ftp_mode_type(conn, 0, type)) != FTP_OK) {
419 e = ftp_cmd(conn, "SIZE %.*s", filenamelen, filename);
420 if (e != FTP_FILE_STATUS) {
424 for (ln = conn->buf + 4; *ln && isspace((unsigned char)*ln); ln++)
426 for (us->size = 0; *ln && isdigit((unsigned char)*ln); ln++)
427 us->size = us->size * 10 + *ln - '0';
428 if (*ln && !isspace((unsigned char)*ln)) {
429 ftp_seterr(FTP_PROTOCOL_ERROR);
435 DEBUG(fprintf(stderr, "size: [%lld]\n", (long long)us->size));
437 e = ftp_cmd(conn, "MDTM %.*s", filenamelen, filename);
438 if (e != FTP_FILE_STATUS) {
442 for (ln = conn->buf + 4; *ln && isspace((unsigned char)*ln); ln++)
444 switch (strspn(ln, "0123456789")) {
453 ftp_seterr(FTP_PROTOCOL_ERROR);
456 if (sscanf(ln, "%04d%02d%02d%02d%02d%02d",
457 &tm.tm_year, &tm.tm_mon, &tm.tm_mday,
458 &tm.tm_hour, &tm.tm_min, &tm.tm_sec) != 6) {
459 ftp_seterr(FTP_PROTOCOL_ERROR);
470 DEBUG(fprintf(stderr,
471 "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));
478 * I/O functions for FTP
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 */
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 *);
494 ftp_readfn(void *v, char *buf, int len)
499 io = (struct ftpio *)v;
504 if (io->cconn == NULL || io->dconn == NULL || io->dir == O_WRONLY) {
514 r = fetch_read(io->dconn, buf, len);
527 ftp_writefn(void *v, const char *buf, int len)
532 io = (struct ftpio *)v;
537 if (io->cconn == NULL || io->dconn == NULL || io->dir == O_RDONLY) {
545 w = fetch_write(io->dconn, buf, len);
554 ftp_seekfn(void *v, fpos_t pos __unused, int whence __unused)
558 io = (struct ftpio *)v;
573 io = (struct ftpio *)v;
580 if (io->cconn == NULL || io->dconn == NULL) {
584 fetch_close(io->dconn);
587 DEBUG(fprintf(stderr, "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);
593 return (r == FTP_TRANSFER_COMPLETE) ? 0 : -1;
597 ftp_setup(conn_t *cconn, conn_t *dconn, int mode)
602 if (cconn == NULL || dconn == NULL)
604 if ((io = malloc(sizeof(*io))) == NULL)
609 io->eof = io->err = 0;
610 f = funopen(io, ftp_readfn, ftp_writefn, ftp_seekfn, ftp_closefn);
620 ftp_transfer(conn_t *conn, const char *oper, const char *file,
621 int mode, off_t offset, const char *flags)
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;
636 low = CHECK_FLAG('l');
637 pasv = CHECK_FLAG('p');
638 verbose = CHECK_FLAG('v');
642 pasv = ((s = getenv("FTP_PASSIVE_MODE")) != NULL &&
643 strncasecmp(s, "no", 2) != 0);
645 /* isolate filename */
646 filename = ftp_filename(file, &filenamelen, &type);
648 /* set transfer mode and data type */
649 if ((e = ftp_mode_type(conn, 0, type)) != FTP_OK)
652 /* find our own address, bind, and listen */
654 if (getsockname(conn->sd, (struct sockaddr *)&sa, &l) == -1)
656 if (sa.ss_family == AF_INET6)
657 unmappedaddr((struct sockaddr_in6 *)&sa);
659 /* open data socket */
660 if ((sd = socket(sa.ss_family, SOCK_STREAM, IPPROTO_TCP)) == -1) {
671 /* send PASV command */
673 fetch_info("setting passive mode");
674 switch (sa.ss_family) {
676 if ((e = ftp_cmd(conn, "PASV")) != FTP_PASSIVE_MODE)
680 if ((e = ftp_cmd(conn, "EPSV")) != FTP_EPASSIVE_MODE) {
683 if ((e = ftp_cmd(conn, "LPSV")) !=
689 e = FTP_PROTOCOL_ERROR; /* XXX: error code should be prepared */
694 * Find address and port number. The reply to the PASV command
695 * is IMHO the one and only weak point in the FTP protocol.
699 case FTP_PASSIVE_MODE:
700 case FTP_LPASSIVE_MODE:
701 for (p = ln + 3; *p && !isdigit((unsigned char)*p); p++)
704 e = FTP_PROTOCOL_ERROR;
707 l = (e == FTP_PASSIVE_MODE ? 6 : 21);
708 for (i = 0; *p && i < l; i++, p++)
709 addr[i] = strtol(p, &p, 10);
711 e = FTP_PROTOCOL_ERROR;
715 case FTP_EPASSIVE_MODE:
716 for (p = ln + 3; *p && *p != '('; p++)
719 e = FTP_PROTOCOL_ERROR;
723 if (sscanf(p, "%c%c%c%d%c", &addr[0], &addr[1], &addr[2],
724 &port, &addr[3]) != 5 ||
725 addr[0] != addr[1] ||
726 addr[0] != addr[2] || addr[0] != addr[3]) {
727 e = FTP_PROTOCOL_ERROR;
733 /* seek to required offset */
735 if (ftp_cmd(conn, "REST %lu", (u_long)offset) != FTP_FILE_OK)
738 /* construct sockaddr for data socket */
740 if (getpeername(conn->sd, (struct sockaddr *)&sa, &l) == -1)
742 if (sa.ss_family == AF_INET6)
743 unmappedaddr((struct sockaddr_in6 *)&sa);
744 switch (sa.ss_family) {
746 sin6 = (struct sockaddr_in6 *)&sa;
747 if (e == FTP_EPASSIVE_MODE)
748 sin6->sin6_port = htons(port);
750 memcpy(&sin6->sin6_addr, addr + 2, 16);
751 memcpy(&sin6->sin6_port, addr + 19, 2);
755 sin4 = (struct sockaddr_in *)&sa;
756 if (e == FTP_EPASSIVE_MODE)
757 sin4->sin_port = htons(port);
759 memcpy(&sin4->sin_addr, addr, 4);
760 memcpy(&sin4->sin_port, addr + 4, 2);
764 e = FTP_PROTOCOL_ERROR; /* XXX: error code should be prepared */
768 /* connect to data port */
770 fetch_info("opening data connection");
771 bindaddr = getenv("FETCH_BIND_ADDRESS");
772 if (bindaddr != NULL && *bindaddr != '\0' &&
773 fetch_bind(sd, sa.ss_family, bindaddr) != 0)
775 if (connect(sd, (struct sockaddr *)&sa, sa.ss_len) == -1)
778 /* make the server initiate the transfer */
780 fetch_info("initiating transfer");
781 e = ftp_cmd(conn, "%s %.*s", oper, filenamelen, filename);
782 if (e != FTP_CONNECTION_ALREADY_OPEN && e != FTP_OPEN_DATA_CONNECTION)
790 char hname[INET6_ADDRSTRLEN];
792 switch (sa.ss_family) {
794 ((struct sockaddr_in6 *)&sa)->sin6_port = 0;
795 #ifdef IPV6_PORTRANGE
796 arg = low ? IPV6_PORTRANGE_DEFAULT : IPV6_PORTRANGE_HIGH;
797 if (setsockopt(sd, IPPROTO_IPV6, IPV6_PORTRANGE,
798 (char *)&arg, sizeof(arg)) == -1)
803 ((struct sockaddr_in *)&sa)->sin_port = 0;
804 arg = low ? IP_PORTRANGE_DEFAULT : IP_PORTRANGE_HIGH;
805 if (setsockopt(sd, IPPROTO_IP, IP_PORTRANGE,
806 (char *)&arg, sizeof(arg)) == -1)
811 fetch_info("binding data socket");
812 if (bind(sd, (struct sockaddr *)&sa, sa.ss_len) == -1)
814 if (listen(sd, 1) == -1)
817 /* find what port we're on and tell the server */
818 if (getsockname(sd, (struct sockaddr *)&sa, &l) == -1)
820 switch (sa.ss_family) {
822 sin4 = (struct sockaddr_in *)&sa;
823 a = ntohl(sin4->sin_addr.s_addr);
824 p = ntohs(sin4->sin_port);
825 e = ftp_cmd(conn, "PORT %d,%d,%d,%d,%d,%d",
826 (a >> 24) & 0xff, (a >> 16) & 0xff,
827 (a >> 8) & 0xff, a & 0xff,
828 (p >> 8) & 0xff, p & 0xff);
831 #define UC(b) (((int)b)&0xff)
833 sin6 = (struct sockaddr_in6 *)&sa;
834 sin6->sin6_scope_id = 0;
835 if (getnameinfo((struct sockaddr *)&sa, sa.ss_len,
836 hname, sizeof(hname),
837 NULL, 0, NI_NUMERICHOST) == 0) {
838 e = ftp_cmd(conn, "EPRT |%d|%s|%d|", 2, hname,
839 htons(sin6->sin6_port));
844 ap = (char *)&sin6->sin6_addr;
846 "LPRT %d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d",
848 UC(ap[0]), UC(ap[1]), UC(ap[2]), UC(ap[3]),
849 UC(ap[4]), UC(ap[5]), UC(ap[6]), UC(ap[7]),
850 UC(ap[8]), UC(ap[9]), UC(ap[10]), UC(ap[11]),
851 UC(ap[12]), UC(ap[13]), UC(ap[14]), UC(ap[15]),
853 (ntohs(sin6->sin6_port) >> 8) & 0xff,
854 ntohs(sin6->sin6_port) & 0xff);
858 e = FTP_PROTOCOL_ERROR; /* XXX: error code should be prepared */
864 /* seek to required offset */
866 if (ftp_cmd(conn, "REST %ju", (uintmax_t)offset) != FTP_FILE_OK)
869 /* make the server initiate the transfer */
871 fetch_info("initiating transfer");
872 e = ftp_cmd(conn, "%s %.*s", oper, filenamelen, filename);
873 if (e != FTP_CONNECTION_ALREADY_OPEN && e != FTP_OPEN_DATA_CONNECTION)
876 /* accept the incoming connection and go to town */
877 if ((d = accept(sd, NULL, NULL)) == -1)
883 if ((df = ftp_setup(conn, fetch_reopen(sd), mode)) == NULL)
905 ftp_authenticate(conn_t *conn, struct url *url, struct url *purl)
907 const char *user, *pwd, *logname;
908 char pbuf[MAXHOSTNAMELEN + MAXLOGNAME + 1];
911 /* XXX FTP_AUTH, and maybe .netrc */
913 /* send user name and password */
914 if (url->user[0] == '\0')
915 fetch_netrc_auth(url);
918 user = getenv("FTP_LOGIN");
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);
924 e = ftp_cmd(conn, "USER %s@%s@%d", user, url->host, url->port);
926 e = ftp_cmd(conn, "USER %s", user);
928 /* did the server request a password? */
929 if (e == FTP_NEED_PASSWORD) {
932 pwd = getenv("FTP_PASSWORD");
933 if (pwd == NULL || *pwd == '\0') {
934 if ((logname = getlogin()) == 0)
935 logname = FTP_ANONYMOUS_USER;
936 if ((len = snprintf(pbuf, MAXLOGNAME + 1, "%s@", logname)) < 0)
938 else if (len > MAXLOGNAME)
940 gethostname(pbuf + len, sizeof(pbuf) - len);
943 e = ftp_cmd(conn, "PASS %s", pwd);
950 * Log on to FTP server
953 ftp_connect(struct url *url, struct url *purl, const char *flags)
956 int e, direct, verbose;
963 direct = CHECK_FLAG('d');
964 verbose = CHECK_FLAG('v');
967 else if (CHECK_FLAG('6'))
973 /* check for proxy */
975 /* XXX proxy authentication! */
976 conn = fetch_connect(purl->host, purl->port, af, verbose);
978 /* no proxy, go straight to target */
979 conn = fetch_connect(url->host, url->port, af, verbose);
983 /* check connection */
985 /* fetch_connect() has already set an error code */
988 /* expect welcome message */
989 if ((e = ftp_chkerr(conn)) != FTP_SERVICE_READY)
993 if ((e = ftp_authenticate(conn, url, purl)) != FTP_LOGGED_IN)
996 /* TODO: Request extended features supported, if any (RFC 3659). */
1009 * Disconnect from server
1012 ftp_disconnect(conn_t *conn)
1014 (void)ftp_cmd(conn, "QUIT");
1015 if (conn == cached_connection && conn->ref == 1)
1016 cached_connection = NULL;
1021 * Check if we're already connected
1024 ftp_isconnected(struct url *url)
1026 return (cached_connection
1027 && (strcmp(url->host, cached_host.host) == 0)
1028 && (strcmp(url->user, cached_host.user) == 0)
1029 && (strcmp(url->pwd, cached_host.pwd) == 0)
1030 && (url->port == cached_host.port));
1034 * Check the cache, reconnect if no luck
1037 ftp_cached_connect(struct url *url, struct url *purl, const char *flags)
1042 /* set default port */
1044 url->port = fetch_default_port(url->scheme);
1046 /* try to use previously cached connection */
1047 if (ftp_isconnected(url)) {
1048 e = ftp_cmd(cached_connection, "NOOP");
1049 if (e == FTP_OK || e == FTP_SYNTAX_ERROR)
1050 return (fetch_ref(cached_connection));
1053 /* connect to server */
1054 if ((conn = ftp_connect(url, purl, flags)) == NULL)
1056 if (cached_connection)
1057 ftp_disconnect(cached_connection);
1058 cached_connection = fetch_ref(conn);
1059 memcpy(&cached_host, url, sizeof(*url));
1064 * Check the proxy settings
1067 ftp_get_proxy(struct url * url, const char *flags)
1072 if (flags != NULL && strchr(flags, 'd') != NULL)
1074 if (fetch_no_proxy_match(url->host))
1076 if (((p = getenv("FTP_PROXY")) || (p = getenv("ftp_proxy")) ||
1077 (p = getenv("HTTP_PROXY")) || (p = getenv("http_proxy"))) &&
1078 *p && (purl = fetchParseURL(p)) != NULL) {
1079 if (!*purl->scheme) {
1080 if (getenv("FTP_PROXY") || getenv("ftp_proxy"))
1081 strcpy(purl->scheme, SCHEME_FTP);
1083 strcpy(purl->scheme, SCHEME_HTTP);
1086 purl->port = fetch_default_proxy_port(purl->scheme);
1087 if (strcasecmp(purl->scheme, SCHEME_FTP) == 0 ||
1088 strcasecmp(purl->scheme, SCHEME_HTTP) == 0)
1096 * Process an FTP request
1099 ftp_request(struct url *url, const char *op, struct url_stat *us,
1100 struct url *purl, const char *flags)
1105 /* check if we should use HTTP instead */
1106 if (purl && strcasecmp(purl->scheme, SCHEME_HTTP) == 0) {
1107 if (strcmp(op, "STAT") == 0)
1108 return (http_request(url, "HEAD", us, purl, flags));
1109 else if (strcmp(op, "RETR") == 0)
1110 return (http_request(url, "GET", us, purl, flags));
1112 * Our HTTP code doesn't support PUT requests yet, so try
1113 * a direct connection.
1117 /* connect to server */
1118 conn = ftp_cached_connect(url, purl, flags);
1124 /* change directory */
1125 if (ftp_cwd(conn, url->doc) == -1)
1129 if (us && ftp_stat(conn, url->doc, us) == -1
1130 && fetchLastErrCode != FETCH_PROTO
1131 && fetchLastErrCode != FETCH_UNAVAIL)
1135 if (strcmp(op, "STAT") == 0)
1136 return (FILE *)1; /* bogus return value */
1137 if (strcmp(op, "STOR") == 0 || strcmp(op, "APPE") == 0)
1142 /* initiate the transfer */
1143 return (ftp_transfer(conn, op, url->doc, oflag, url->offset, flags));
1150 fetchXGetFTP(struct url *url, struct url_stat *us, const char *flags)
1152 return (ftp_request(url, "RETR", us, ftp_get_proxy(url, flags), flags));
1159 fetchGetFTP(struct url *url, const char *flags)
1161 return (fetchXGetFTP(url, NULL, flags));
1168 fetchPutFTP(struct url *url, const char *flags)
1170 return (ftp_request(url, CHECK_FLAG('a') ? "APPE" : "STOR", NULL,
1171 ftp_get_proxy(url, flags), flags));
1178 fetchStatFTP(struct url *url, struct url_stat *us, const char *flags)
1182 f = ftp_request(url, "STAT", us, ftp_get_proxy(url, flags), flags);
1186 * When op is "STAT", ftp_request() will return either NULL or
1187 * (FILE *)1, never a valid FILE *, so we mustn't fclose(f) before
1188 * returning, as it would cause a segfault.
1197 fetchListFTP(struct url *url __unused, const char *flags __unused)
1199 warnx("fetchListFTP(): not implemented");