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.96 2007/04/22 22:33:29 njl 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 struct url cached_host;
103 static conn_t *cached_connection;
105 #define isftpreply(foo) (isdigit(foo[0]) && isdigit(foo[1]) \
107 && (foo[3] == ' ' || foo[3] == '\0'))
108 #define isftpinfo(foo) (isdigit(foo[0]) && isdigit(foo[1]) \
109 && isdigit(foo[2]) && foo[3] == '-')
112 * Translate IPv4 mapped IPv6 address to IPv4 address
115 unmappedaddr(struct sockaddr_in6 *sin6)
117 struct sockaddr_in *sin4;
121 if (sin6->sin6_family != AF_INET6 ||
122 !IN6_IS_ADDR_V4MAPPED(&sin6->sin6_addr))
124 sin4 = (struct sockaddr_in *)sin6;
125 addr = *(u_int32_t *)&sin6->sin6_addr.s6_addr[12];
126 port = sin6->sin6_port;
127 memset(sin4, 0, sizeof(struct sockaddr_in));
128 sin4->sin_addr.s_addr = addr;
129 sin4->sin_port = port;
130 sin4->sin_family = AF_INET;
131 sin4->sin_len = sizeof(struct sockaddr_in);
135 * Get server response
138 _ftp_chkerr(conn_t *conn)
140 if (_fetch_getln(conn) == -1) {
144 if (isftpinfo(conn->buf)) {
145 while (conn->buflen && !isftpreply(conn->buf)) {
146 if (_fetch_getln(conn) == -1) {
153 while (conn->buflen && isspace(conn->buf[conn->buflen - 1]))
155 conn->buf[conn->buflen] = '\0';
157 if (!isftpreply(conn->buf)) {
158 _ftp_seterr(FTP_PROTOCOL_ERROR);
162 conn->err = (conn->buf[0] - '0') * 100
163 + (conn->buf[1] - '0') * 10
164 + (conn->buf[2] - '0');
170 * Send a command and check reply
173 _ftp_cmd(conn_t *conn, const char *fmt, ...)
181 len = vasprintf(&msg, fmt, ap);
190 r = _fetch_putln(conn, msg, len);
198 return (_ftp_chkerr(conn));
202 * Return a pointer to the filename part of a path
205 _ftp_filename(const char *file, int *len, int *type)
209 if ((s = strrchr(file, '/')) == NULL)
214 if (*len > 7 && strncmp(s + *len - 7, ";type=", 6) == 0) {
224 * Get current working directory from the reply to a CWD, PWD or CDUP
228 _ftp_pwd(conn_t *conn, char *pwd, size_t pwdlen)
230 char *src, *dst, *end;
233 if (conn->err != FTP_WORKING_DIRECTORY &&
234 conn->err != FTP_FILE_ACTION_OK)
235 return (FTP_PROTOCOL_ERROR);
236 end = conn->buf + conn->buflen;
238 if (src >= end || *src++ != '"')
239 return (FTP_PROTOCOL_ERROR);
240 for (q = 0, dst = pwd; src < end && pwdlen--; ++src) {
241 if (!q && *src == '"')
243 else if (q && *src != '"')
251 return (FTP_PROTOCOL_ERROR);
254 DEBUG(fprintf(stderr, "pwd: [%s]\n", pwd));
260 * Change working directory to the directory that contains the specified
264 _ftp_cwd(conn_t *conn, const char *file)
266 const char *beg, *end;
270 /* If no slashes in name, no need to change dirs. */
271 if ((end = strrchr(file, '/')) == NULL)
273 if ((e = _ftp_cmd(conn, "PWD")) != FTP_WORKING_DIRECTORY ||
274 (e = _ftp_pwd(conn, pwd, sizeof(pwd))) != FTP_OK) {
281 /* Look for a common prefix between PWD and dir to fetch. */
282 for (i = 0; i <= len && i <= end - file; ++i)
283 if (pwd[i] != file[i])
286 DEBUG(fprintf(stderr, "have: [%.*s|%s]\n", i, pwd, pwd + i));
287 DEBUG(fprintf(stderr, "want: [%.*s|%s]\n", i, file, file + i));
289 /* Keep going up a dir until we have a matching prefix. */
290 if (pwd[i] == '\0' && (file[i - 1] == '/' || file[i] == '/'))
292 if ((e = _ftp_cmd(conn, "CDUP")) != FTP_FILE_ACTION_OK ||
293 (e = _ftp_cmd(conn, "PWD")) != FTP_WORKING_DIRECTORY ||
294 (e = _ftp_pwd(conn, pwd, sizeof(pwd))) != FTP_OK) {
300 #ifdef FTP_COMBINE_CWDS
301 /* Skip leading slashes, even "////". */
302 for (beg = file + i; beg < end && *beg == '/'; ++beg, ++i)
305 /* If there is no trailing dir, we're already there. */
309 /* Change to the directory all in one chunk (e.g., foo/bar/baz). */
310 e = _ftp_cmd(conn, "CWD %.*s", (int)(end - beg), beg);
311 if (e == FTP_FILE_ACTION_OK)
313 #endif /* FTP_COMBINE_CWDS */
315 /* That didn't work so go back to legacy behavior (multiple CWDs). */
316 for (beg = file + i; beg < end; beg = file + i + 1) {
319 for (++i; file + i < end && file[i] != '/'; ++i)
321 e = _ftp_cmd(conn, "CWD %.*s", file + i - beg, beg);
322 if (e != FTP_FILE_ACTION_OK) {
331 * Set transfer mode and data type
334 _ftp_mode_type(conn_t *conn, int mode, int type)
345 return (FTP_PROTOCOL_ERROR);
347 if ((e = _ftp_cmd(conn, "MODE %c", mode)) != FTP_OK) {
350 * Stream mode is supposed to be the default - so
351 * much so that some servers not only do not
352 * support any other mode, but do not support the
353 * MODE command at all.
355 * If "MODE S" fails, it is unlikely that we
356 * previously succeeded in setting a different
357 * mode. Therefore, we simply hope that the
358 * server is already in the correct mode, and
359 * silently ignore the failure.
379 /* can't handle yet */
381 return (FTP_PROTOCOL_ERROR);
383 if ((e = _ftp_cmd(conn, "TYPE %c", type)) != FTP_OK)
390 * Request and parse file stats
393 _ftp_stat(conn_t *conn, const char *file, struct url_stat *us)
396 const char *filename;
397 int filenamelen, type;
403 us->atime = us->mtime = 0;
405 filename = _ftp_filename(file, &filenamelen, &type);
407 if ((e = _ftp_mode_type(conn, 0, type)) != FTP_OK) {
412 e = _ftp_cmd(conn, "SIZE %.*s", filenamelen, filename);
413 if (e != FTP_FILE_STATUS) {
417 for (ln = conn->buf + 4; *ln && isspace(*ln); ln++)
419 for (us->size = 0; *ln && isdigit(*ln); ln++)
420 us->size = us->size * 10 + *ln - '0';
421 if (*ln && !isspace(*ln)) {
422 _ftp_seterr(FTP_PROTOCOL_ERROR);
428 DEBUG(fprintf(stderr, "size: [%lld]\n", (long long)us->size));
430 e = _ftp_cmd(conn, "MDTM %.*s", filenamelen, filename);
431 if (e != FTP_FILE_STATUS) {
435 for (ln = conn->buf + 4; *ln && isspace(*ln); ln++)
437 switch (strspn(ln, "0123456789")) {
446 _ftp_seterr(FTP_PROTOCOL_ERROR);
449 if (sscanf(ln, "%04d%02d%02d%02d%02d%02d",
450 &tm.tm_year, &tm.tm_mon, &tm.tm_mday,
451 &tm.tm_hour, &tm.tm_min, &tm.tm_sec) != 6) {
452 _ftp_seterr(FTP_PROTOCOL_ERROR);
463 DEBUG(fprintf(stderr,
464 "last modified: [%04d-%02d-%02d %02d:%02d:%02d]\n",
465 tm.tm_year + 1900, tm.tm_mon + 1, tm.tm_mday,
466 tm.tm_hour, tm.tm_min, tm.tm_sec));
471 * I/O functions for FTP
474 conn_t *cconn; /* Control connection */
475 conn_t *dconn; /* Data connection */
476 int dir; /* Direction */
477 int eof; /* EOF reached */
478 int err; /* Error code */
481 static int _ftp_readfn(void *, char *, int);
482 static int _ftp_writefn(void *, const char *, int);
483 static fpos_t _ftp_seekfn(void *, fpos_t, int);
484 static int _ftp_closefn(void *);
487 _ftp_readfn(void *v, char *buf, int len)
492 io = (struct ftpio *)v;
497 if (io->cconn == NULL || io->dconn == NULL || io->dir == O_WRONLY) {
507 r = _fetch_read(io->dconn, buf, len);
520 _ftp_writefn(void *v, const char *buf, int len)
525 io = (struct ftpio *)v;
530 if (io->cconn == NULL || io->dconn == NULL || io->dir == O_RDONLY) {
538 w = _fetch_write(io->dconn, buf, len);
547 _ftp_seekfn(void *v, fpos_t pos __unused, int whence __unused)
551 io = (struct ftpio *)v;
561 _ftp_closefn(void *v)
566 io = (struct ftpio *)v;
573 if (io->cconn == NULL || io->dconn == NULL) {
577 _fetch_close(io->dconn);
580 DEBUG(fprintf(stderr, "Waiting for final status\n"));
581 r = _ftp_chkerr(io->cconn);
582 if (io->cconn == cached_connection && io->cconn->ref == 1)
583 cached_connection = NULL;
584 _fetch_close(io->cconn);
586 return (r == FTP_TRANSFER_COMPLETE) ? 0 : -1;
590 _ftp_setup(conn_t *cconn, conn_t *dconn, int mode)
595 if (cconn == NULL || dconn == NULL)
597 if ((io = malloc(sizeof(*io))) == NULL)
602 io->eof = io->err = 0;
603 f = funopen(io, _ftp_readfn, _ftp_writefn, _ftp_seekfn, _ftp_closefn);
613 _ftp_transfer(conn_t *conn, const char *oper, const char *file,
614 int mode, off_t offset, const char *flags)
616 struct sockaddr_storage sa;
617 struct sockaddr_in6 *sin6;
618 struct sockaddr_in *sin4;
619 const char *bindaddr;
620 const char *filename;
621 int filenamelen, type;
622 int low, pasv, verbose;
629 low = CHECK_FLAG('l');
630 pasv = CHECK_FLAG('p');
631 verbose = CHECK_FLAG('v');
635 pasv = ((s = getenv("FTP_PASSIVE_MODE")) != NULL &&
636 strncasecmp(s, "no", 2) != 0);
638 /* isolate filename */
639 filename = _ftp_filename(file, &filenamelen, &type);
641 /* set transfer mode and data type */
642 if ((e = _ftp_mode_type(conn, 0, type)) != FTP_OK)
645 /* find our own address, bind, and listen */
647 if (getsockname(conn->sd, (struct sockaddr *)&sa, &l) == -1)
649 if (sa.ss_family == AF_INET6)
650 unmappedaddr((struct sockaddr_in6 *)&sa);
652 /* open data socket */
653 if ((sd = socket(sa.ss_family, SOCK_STREAM, IPPROTO_TCP)) == -1) {
664 /* send PASV command */
666 _fetch_info("setting passive mode");
667 switch (sa.ss_family) {
669 if ((e = _ftp_cmd(conn, "PASV")) != FTP_PASSIVE_MODE)
673 if ((e = _ftp_cmd(conn, "EPSV")) != FTP_EPASSIVE_MODE) {
676 if ((e = _ftp_cmd(conn, "LPSV")) !=
682 e = FTP_PROTOCOL_ERROR; /* XXX: error code should be prepared */
687 * Find address and port number. The reply to the PASV command
688 * is IMHO the one and only weak point in the FTP protocol.
692 case FTP_PASSIVE_MODE:
693 case FTP_LPASSIVE_MODE:
694 for (p = ln + 3; *p && !isdigit(*p); p++)
697 e = FTP_PROTOCOL_ERROR;
700 l = (e == FTP_PASSIVE_MODE ? 6 : 21);
701 for (i = 0; *p && i < l; i++, p++)
702 addr[i] = strtol(p, &p, 10);
704 e = FTP_PROTOCOL_ERROR;
708 case FTP_EPASSIVE_MODE:
709 for (p = ln + 3; *p && *p != '('; p++)
712 e = FTP_PROTOCOL_ERROR;
716 if (sscanf(p, "%c%c%c%d%c", &addr[0], &addr[1], &addr[2],
717 &port, &addr[3]) != 5 ||
718 addr[0] != addr[1] ||
719 addr[0] != addr[2] || addr[0] != addr[3]) {
720 e = FTP_PROTOCOL_ERROR;
726 /* seek to required offset */
728 if (_ftp_cmd(conn, "REST %lu", (u_long)offset) != FTP_FILE_OK)
731 /* construct sockaddr for data socket */
733 if (getpeername(conn->sd, (struct sockaddr *)&sa, &l) == -1)
735 if (sa.ss_family == AF_INET6)
736 unmappedaddr((struct sockaddr_in6 *)&sa);
737 switch (sa.ss_family) {
739 sin6 = (struct sockaddr_in6 *)&sa;
740 if (e == FTP_EPASSIVE_MODE)
741 sin6->sin6_port = htons(port);
743 bcopy(addr + 2, (char *)&sin6->sin6_addr, 16);
744 bcopy(addr + 19, (char *)&sin6->sin6_port, 2);
748 sin4 = (struct sockaddr_in *)&sa;
749 if (e == FTP_EPASSIVE_MODE)
750 sin4->sin_port = htons(port);
752 bcopy(addr, (char *)&sin4->sin_addr, 4);
753 bcopy(addr + 4, (char *)&sin4->sin_port, 2);
757 e = FTP_PROTOCOL_ERROR; /* XXX: error code should be prepared */
761 /* connect to data port */
763 _fetch_info("opening data connection");
764 bindaddr = getenv("FETCH_BIND_ADDRESS");
765 if (bindaddr != NULL && *bindaddr != '\0' &&
766 _fetch_bind(sd, sa.ss_family, bindaddr) != 0)
768 if (connect(sd, (struct sockaddr *)&sa, sa.ss_len) == -1)
771 /* make the server initiate the transfer */
773 _fetch_info("initiating transfer");
774 e = _ftp_cmd(conn, "%s %.*s", oper, filenamelen, filename);
775 if (e != FTP_CONNECTION_ALREADY_OPEN && e != FTP_OPEN_DATA_CONNECTION)
783 char hname[INET6_ADDRSTRLEN];
785 switch (sa.ss_family) {
787 ((struct sockaddr_in6 *)&sa)->sin6_port = 0;
788 #ifdef IPV6_PORTRANGE
789 arg = low ? IPV6_PORTRANGE_DEFAULT : IPV6_PORTRANGE_HIGH;
790 if (setsockopt(sd, IPPROTO_IPV6, IPV6_PORTRANGE,
791 (char *)&arg, sizeof(arg)) == -1)
796 ((struct sockaddr_in *)&sa)->sin_port = 0;
797 arg = low ? IP_PORTRANGE_DEFAULT : IP_PORTRANGE_HIGH;
798 if (setsockopt(sd, IPPROTO_IP, IP_PORTRANGE,
799 (char *)&arg, sizeof(arg)) == -1)
804 _fetch_info("binding data socket");
805 if (bind(sd, (struct sockaddr *)&sa, sa.ss_len) == -1)
807 if (listen(sd, 1) == -1)
810 /* find what port we're on and tell the server */
811 if (getsockname(sd, (struct sockaddr *)&sa, &l) == -1)
813 switch (sa.ss_family) {
815 sin4 = (struct sockaddr_in *)&sa;
816 a = ntohl(sin4->sin_addr.s_addr);
817 p = ntohs(sin4->sin_port);
818 e = _ftp_cmd(conn, "PORT %d,%d,%d,%d,%d,%d",
819 (a >> 24) & 0xff, (a >> 16) & 0xff,
820 (a >> 8) & 0xff, a & 0xff,
821 (p >> 8) & 0xff, p & 0xff);
824 #define UC(b) (((int)b)&0xff)
826 sin6 = (struct sockaddr_in6 *)&sa;
827 sin6->sin6_scope_id = 0;
828 if (getnameinfo((struct sockaddr *)&sa, sa.ss_len,
829 hname, sizeof(hname),
830 NULL, 0, NI_NUMERICHOST) == 0) {
831 e = _ftp_cmd(conn, "EPRT |%d|%s|%d|", 2, hname,
832 htons(sin6->sin6_port));
837 ap = (char *)&sin6->sin6_addr;
839 "LPRT %d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d",
841 UC(ap[0]), UC(ap[1]), UC(ap[2]), UC(ap[3]),
842 UC(ap[4]), UC(ap[5]), UC(ap[6]), UC(ap[7]),
843 UC(ap[8]), UC(ap[9]), UC(ap[10]), UC(ap[11]),
844 UC(ap[12]), UC(ap[13]), UC(ap[14]), UC(ap[15]),
846 (ntohs(sin6->sin6_port) >> 8) & 0xff,
847 ntohs(sin6->sin6_port) & 0xff);
851 e = FTP_PROTOCOL_ERROR; /* XXX: error code should be prepared */
857 /* seek to required offset */
859 if (_ftp_cmd(conn, "REST %ju", (uintmax_t)offset) != FTP_FILE_OK)
862 /* make the server initiate the transfer */
864 _fetch_info("initiating transfer");
865 e = _ftp_cmd(conn, "%s %.*s", oper, filenamelen, filename);
866 if (e != FTP_CONNECTION_ALREADY_OPEN && e != FTP_OPEN_DATA_CONNECTION)
869 /* accept the incoming connection and go to town */
870 if ((d = accept(sd, NULL, NULL)) == -1)
876 if ((df = _ftp_setup(conn, _fetch_reopen(sd), mode)) == NULL)
898 _ftp_authenticate(conn_t *conn, struct url *url, struct url *purl)
900 const char *user, *pwd, *logname;
901 char pbuf[MAXHOSTNAMELEN + MAXLOGNAME + 1];
904 /* XXX FTP_AUTH, and maybe .netrc */
906 /* send user name and password */
907 if (url->user[0] == '\0')
908 _fetch_netrc_auth(url);
911 user = getenv("FTP_LOGIN");
912 if (user == NULL || *user == '\0')
913 user = FTP_ANONYMOUS_USER;
914 if (purl && url->port == _fetch_default_port(url->scheme))
915 e = _ftp_cmd(conn, "USER %s@%s", user, url->host);
917 e = _ftp_cmd(conn, "USER %s@%s@%d", user, url->host, url->port);
919 e = _ftp_cmd(conn, "USER %s", user);
921 /* did the server request a password? */
922 if (e == FTP_NEED_PASSWORD) {
925 pwd = getenv("FTP_PASSWORD");
926 if (pwd == NULL || *pwd == '\0') {
927 if ((logname = getlogin()) == 0)
928 logname = FTP_ANONYMOUS_USER;
929 if ((len = snprintf(pbuf, MAXLOGNAME + 1, "%s@", logname)) < 0)
931 else if (len > MAXLOGNAME)
933 gethostname(pbuf + len, sizeof(pbuf) - len);
936 e = _ftp_cmd(conn, "PASS %s", pwd);
943 * Log on to FTP server
946 _ftp_connect(struct url *url, struct url *purl, const char *flags)
949 int e, direct, verbose;
956 direct = CHECK_FLAG('d');
957 verbose = CHECK_FLAG('v');
960 else if (CHECK_FLAG('6'))
966 /* check for proxy */
968 /* XXX proxy authentication! */
969 conn = _fetch_connect(purl->host, purl->port, af, verbose);
971 /* no proxy, go straight to target */
972 conn = _fetch_connect(url->host, url->port, af, verbose);
976 /* check connection */
978 /* _fetch_connect() has already set an error code */
981 /* expect welcome message */
982 if ((e = _ftp_chkerr(conn)) != FTP_SERVICE_READY)
986 if ((e = _ftp_authenticate(conn, url, purl)) != FTP_LOGGED_IN)
989 /* TODO: Request extended features supported, if any (RFC 3659). */
1002 * Disconnect from server
1005 _ftp_disconnect(conn_t *conn)
1007 (void)_ftp_cmd(conn, "QUIT");
1008 if (conn == cached_connection && conn->ref == 1)
1009 cached_connection = NULL;
1014 * Check if we're already connected
1017 _ftp_isconnected(struct url *url)
1019 return (cached_connection
1020 && (strcmp(url->host, cached_host.host) == 0)
1021 && (strcmp(url->user, cached_host.user) == 0)
1022 && (strcmp(url->pwd, cached_host.pwd) == 0)
1023 && (url->port == cached_host.port));
1027 * Check the cache, reconnect if no luck
1030 _ftp_cached_connect(struct url *url, struct url *purl, const char *flags)
1035 /* set default port */
1037 url->port = _fetch_default_port(url->scheme);
1039 /* try to use previously cached connection */
1040 if (_ftp_isconnected(url)) {
1041 e = _ftp_cmd(cached_connection, "NOOP");
1042 if (e == FTP_OK || e == FTP_SYNTAX_ERROR)
1043 return (_fetch_ref(cached_connection));
1046 /* connect to server */
1047 if ((conn = _ftp_connect(url, purl, flags)) == NULL)
1049 if (cached_connection)
1050 _ftp_disconnect(cached_connection);
1051 cached_connection = _fetch_ref(conn);
1052 memcpy(&cached_host, url, sizeof(*url));
1057 * Check the proxy settings
1060 _ftp_get_proxy(const char *flags)
1065 if (flags != NULL && strchr(flags, 'd') != NULL)
1067 if (((p = getenv("FTP_PROXY")) || (p = getenv("ftp_proxy")) ||
1068 (p = getenv("HTTP_PROXY")) || (p = getenv("http_proxy"))) &&
1069 *p && (purl = fetchParseURL(p)) != NULL) {
1070 if (!*purl->scheme) {
1071 if (getenv("FTP_PROXY") || getenv("ftp_proxy"))
1072 strcpy(purl->scheme, SCHEME_FTP);
1074 strcpy(purl->scheme, SCHEME_HTTP);
1077 purl->port = _fetch_default_proxy_port(purl->scheme);
1078 if (strcasecmp(purl->scheme, SCHEME_FTP) == 0 ||
1079 strcasecmp(purl->scheme, SCHEME_HTTP) == 0)
1087 * Process an FTP request
1090 _ftp_request(struct url *url, const char *op, struct url_stat *us,
1091 struct url *purl, const char *flags)
1096 /* check if we should use HTTP instead */
1097 if (purl && strcasecmp(purl->scheme, SCHEME_HTTP) == 0) {
1098 if (strcmp(op, "STAT") == 0)
1099 return (_http_request(url, "HEAD", us, purl, flags));
1100 else if (strcmp(op, "RETR") == 0)
1101 return (_http_request(url, "GET", us, purl, flags));
1103 * Our HTTP code doesn't support PUT requests yet, so try
1104 * a direct connection.
1108 /* connect to server */
1109 conn = _ftp_cached_connect(url, purl, flags);
1115 /* change directory */
1116 if (_ftp_cwd(conn, url->doc) == -1)
1120 if (us && _ftp_stat(conn, url->doc, us) == -1
1121 && fetchLastErrCode != FETCH_PROTO
1122 && fetchLastErrCode != FETCH_UNAVAIL)
1126 if (strcmp(op, "STAT") == 0)
1127 return (FILE *)1; /* bogus return value */
1128 if (strcmp(op, "STOR") == 0 || strcmp(op, "APPE") == 0)
1133 /* initiate the transfer */
1134 return (_ftp_transfer(conn, op, url->doc, oflag, url->offset, flags));
1141 fetchXGetFTP(struct url *url, struct url_stat *us, const char *flags)
1143 return (_ftp_request(url, "RETR", us, _ftp_get_proxy(flags), flags));
1150 fetchGetFTP(struct url *url, const char *flags)
1152 return (fetchXGetFTP(url, NULL, flags));
1159 fetchPutFTP(struct url *url, const char *flags)
1162 return (_ftp_request(url, CHECK_FLAG('a') ? "APPE" : "STOR", NULL,
1163 _ftp_get_proxy(flags), flags));
1170 fetchStatFTP(struct url *url, struct url_stat *us, const char *flags)
1174 f = _ftp_request(url, "STAT", us, _ftp_get_proxy(flags), flags);
1184 fetchListFTP(struct url *url __unused, const char *flags __unused)
1186 warnx("fetchListFTP(): not implemented");