1 /* Copyright 1999-2005 The Apache Software Foundation or its licensors, as
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
8 * http://www.apache.org/licenses/LICENSE-2.0
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
17 /* FTP routines for Apache proxy */
19 #include "mod_proxy.h"
23 #include "apr_version.h"
25 #if (APR_MAJOR_VERSION < 1)
26 #undef apr_socket_create
27 #define apr_socket_create apr_socket_create_ex
30 #define AUTODETECT_PWD
31 /* Automatic timestamping (Last-Modified header) based on MDTM is used if:
32 * 1) the FTP server supports the MDTM command and
33 * 2) HAVE_TIMEGM (preferred) or HAVE_GMTOFF is available at compile time
38 module AP_MODULE_DECLARE_DATA proxy_ftp_module;
41 * Decodes a '%' escaped string, and returns the number of characters
43 static int decodeenc(char *x)
48 return 0; /* special case for no characters */
49 for (i = 0, j = 0; x[i] != '\0'; i++, j++) {
50 /* decode it if not already done */
52 if (ch == '%' && apr_isxdigit(x[i + 1]) && apr_isxdigit(x[i + 2])) {
53 ch = ap_proxy_hex2c(&x[i + 1]);
63 * Escape the globbing characters in a path used as argument to
64 * the FTP commands (SIZE, CWD, RETR, MDTM, ...).
65 * ftpd assumes '\\' as a quoting character to escape special characters.
66 * Returns: escaped string
68 #define FTP_GLOBBING_CHARS "*?[{~"
69 static char *ftp_escape_globbingchars(apr_pool_t *p, const char *path)
71 char *ret = apr_palloc(p, 2*strlen(path)+sizeof(""));
73 for (d = ret; *path; ++path) {
74 if (strchr(FTP_GLOBBING_CHARS, *path) != NULL)
83 * Check for globbing characters in a path used as argument to
84 * the FTP commands (SIZE, CWD, RETR, MDTM, ...).
85 * ftpd assumes '\\' as a quoting character to escape special characters.
86 * Returns: 0 (no globbing chars, or all globbing chars escaped), 1 (globbing chars)
88 static int ftp_check_globbingchars(const char *path)
90 for ( ; *path; ++path) {
93 if (path != '\0' && strchr(FTP_GLOBBING_CHARS, *path) != NULL)
100 * checks an encoded ftp string for bad characters, namely, CR, LF or
101 * non-ascii character
103 static int ftp_check_string(const char *x)
106 #if APR_CHARSET_EBCDIC
110 for (i = 0; x[i] != '\0'; i++) {
112 if (ch == '%' && apr_isxdigit(x[i + 1]) && apr_isxdigit(x[i + 2])) {
113 ch = ap_proxy_hex2c(&x[i + 1]);
116 #if !APR_CHARSET_EBCDIC
117 if (ch == '\015' || ch == '\012' || (ch & 0x80))
118 #else /* APR_CHARSET_EBCDIC */
119 if (ch == '\r' || ch == '\n')
122 ap_xlate_proto_to_ascii(buf, 1);
124 #endif /* APR_CHARSET_EBCDIC */
131 * Canonicalise ftp URLs.
133 static int proxy_ftp_canon(request_rec *r, char *url)
135 char *user, *password, *host, *path, *parms, *strp, sport[7];
136 apr_pool_t *p = r->pool;
138 apr_port_t port, def_port;
141 if (strncasecmp(url, "ftp:", 4) == 0) {
147 def_port = apr_uri_port_of_scheme("ftp");
149 ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, r->server,
150 "proxy: FTP: canonicalising URL %s", url);
153 err = ap_proxy_canon_netloc(p, &url, &user, &password, &host, &port);
155 return HTTP_BAD_REQUEST;
156 if (user != NULL && !ftp_check_string(user))
157 return HTTP_BAD_REQUEST;
158 if (password != NULL && !ftp_check_string(password))
159 return HTTP_BAD_REQUEST;
161 /* now parse path/parameters args, according to rfc1738 */
163 * N.B. if this isn't a true proxy request, then the URL path (but not
164 * query args) has already been decoded. This gives rise to the problem
165 * of a ; being decoded into the path.
167 strp = strchr(url, ';');
170 parms = ap_proxy_canonenc(p, strp, strlen(strp), enc_parm, 0,
173 return HTTP_BAD_REQUEST;
178 path = ap_proxy_canonenc(p, url, strlen(url), enc_path, 0, r->proxyreq);
180 return HTTP_BAD_REQUEST;
181 if (!ftp_check_string(path))
182 return HTTP_BAD_REQUEST;
184 if (r->proxyreq && r->args != NULL) {
186 strp = ap_proxy_canonenc(p, r->args, strlen(r->args), enc_parm, 1, r->proxyreq);
188 return HTTP_BAD_REQUEST;
189 parms = apr_pstrcat(p, parms, "?", strp, NULL);
192 strp = ap_proxy_canonenc(p, r->args, strlen(r->args), enc_fpath, 1, r->proxyreq);
194 return HTTP_BAD_REQUEST;
195 path = apr_pstrcat(p, path, "?", strp, NULL);
200 /* now, rebuild URL */
202 if (port != def_port)
203 apr_snprintf(sport, sizeof(sport), ":%d", port);
207 if (ap_strchr_c(host, ':')) { /* if literal IPv6 address */
208 host = apr_pstrcat(p, "[", host, "]", NULL);
210 r->filename = apr_pstrcat(p, "proxy:ftp://", (user != NULL) ? user : "",
211 (password != NULL) ? ":" : "",
212 (password != NULL) ? password : "",
213 (user != NULL) ? "@" : "", host, sport, "/", path,
214 (parms[0] != '\0') ? ";" : "", parms, NULL);
219 /* we chop lines longer than 80 characters */
220 #define MAX_LINE_LEN 80
223 * Reads response lines, returns both the ftp status code and
224 * remembers the response message in the supplied buffer
226 static int ftp_getrc_msg(conn_rec *ftp_ctrl, apr_bucket_brigade *bb, char *msgbuf, int msglen)
229 char response[MAX_LINE_LEN];
231 char *mb = msgbuf, *me = &msgbuf[msglen];
235 if (APR_SUCCESS != (rv = ap_proxy_string_read(ftp_ctrl, bb, response, sizeof(response), &eos))) {
239 ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, NULL,
240 "proxy: <FTP: %s", response);
242 if (!apr_isdigit(response[0]) || !apr_isdigit(response[1]) ||
243 !apr_isdigit(response[2]) || (response[3] != ' ' && response[3] != '-'))
246 status = 100 * response[0] + 10 * response[1] + response[2] - 111 * '0';
248 mb = apr_cpystrn(mb, response + 4, me - mb);
250 if (response[3] == '-') {
251 memcpy(buff, response, 3);
254 if (APR_SUCCESS != (rv = ap_proxy_string_read(ftp_ctrl, bb, response, sizeof(response), &eos))) {
257 mb = apr_cpystrn(mb, response + (' ' == response[0] ? 1 : 4), me - mb);
258 } while (memcmp(response, buff, 4) != 0);
264 /* this is a filter that turns a raw ASCII directory listing into pretty HTML */
266 /* ideally, mod_proxy should simply send the raw directory list up the filter
267 * stack to mod_autoindex, which in theory should turn the raw ascii into
268 * pretty html along with all the bells and whistles it provides...
270 * all in good time...! :)
274 apr_bucket_brigade *in;
275 char buffer[MAX_STRING_LEN];
281 /* fallback regex for ls -s1; ($0..$2) == 3 */
282 #define LS_REG_PATTERN "^ *([0-9]+) +([^ ]+)$"
283 #define LS_REG_MATCH 3
285 static apr_status_t proxy_send_dir_filter(ap_filter_t *f,
286 apr_bucket_brigade *in)
288 request_rec *r = f->r;
289 conn_rec *c = r->connection;
290 apr_pool_t *p = r->pool;
291 apr_bucket_brigade *out = apr_brigade_create(p, c->bucket_alloc);
295 char *dir, *path, *reldir, *site, *str, *type;
297 const char *pwd = apr_table_get(r->notes, "Directory-PWD");
298 const char *readme = apr_table_get(r->notes, "Directory-README");
300 proxy_dir_ctx_t *ctx = f->ctx;
303 f->ctx = ctx = apr_pcalloc(p, sizeof(*ctx));
304 ctx->in = apr_brigade_create(p, c->bucket_alloc);
309 /* combine the stored and the new */
310 APR_BRIGADE_CONCAT(ctx->in, in);
312 if (HEADER == ctx->state) {
314 /* basedir is either "", or "/%2f" for the "squid %2f hack" */
315 const char *basedir = ""; /* By default, path is relative to the $HOME dir */
316 char *wildcard = NULL;
318 /* Save "scheme://site" prefix without password */
319 site = apr_uri_unparse(p, &f->r->parsed_uri, APR_URI_UNP_OMITPASSWORD | APR_URI_UNP_OMITPATHINFO);
320 /* ... and path without query args */
321 path = apr_uri_unparse(p, &f->r->parsed_uri, APR_URI_UNP_OMITSITEPART | APR_URI_UNP_OMITQUERY);
323 /* If path began with /%2f, change the basedir */
324 if (strncasecmp(path, "/%2f", 4) == 0) {
328 /* Strip off a type qualifier. It is ignored for dir listings */
329 if ((type = strstr(path, ";type=")) != NULL)
332 (void)decodeenc(path);
334 while (path[1] == '/') /* collapse multiple leading slashes to one */
337 reldir = strrchr(path, '/');
338 if (reldir != NULL && ftp_check_globbingchars(reldir)) {
339 wildcard = &reldir[1];
340 reldir[0] = '\0'; /* strip off the wildcard suffix */
343 /* Copy path, strip (all except the last) trailing slashes */
344 /* (the trailing slash is needed for the dir component loop below) */
345 path = dir = apr_pstrcat(p, path, "/", NULL);
346 for (n = strlen(path); n > 1 && path[n - 1] == '/' && path[n - 2] == '/'; --n)
349 /* Add a link to the root directory (if %2f hack was used) */
350 str = (basedir[0] != '\0') ? "<a href=\"/%2f/\">%2f</a>/" : "";
352 /* print "ftp://host/" */
353 str = apr_psprintf(p, DOCTYPE_HTML_3_2
354 "<html>\n <head>\n <title>%s%s%s</title>\n"
355 " <base href=\"%s%s%s\">\n </head>\n"
356 " <body>\n <h2>Directory of "
357 "<a href=\"/\">%s</a>/%s",
358 site, basedir, ap_escape_html(p, path),
359 site, basedir, ap_escape_uri(p, path),
362 APR_BRIGADE_INSERT_TAIL(out, apr_bucket_pool_create(str, strlen(str),
363 p, c->bucket_alloc));
365 for (dir = path+1; (dir = strchr(dir, '/')) != NULL; )
368 if ((reldir = strrchr(path+1, '/'))==NULL) {
373 /* print "path/" component */
374 str = apr_psprintf(p, "<a href=\"%s%s/\">%s</a>/", basedir,
375 ap_escape_uri(p, path),
376 ap_escape_html(p, reldir));
380 APR_BRIGADE_INSERT_TAIL(out, apr_bucket_pool_create(str,
384 if (wildcard != NULL) {
385 APR_BRIGADE_INSERT_TAIL(out, apr_bucket_pool_create(wildcard,
390 /* If the caller has determined the current directory, and it differs */
391 /* from what the client requested, then show the real name */
392 if (pwd == NULL || strncmp(pwd, path, strlen(pwd)) == 0) {
393 str = apr_psprintf(p, "</h2>\n\n <hr />\n\n<pre>");
396 str = apr_psprintf(p, "</h2>\n\n(%s)\n\n <hr />\n\n<pre>",
397 ap_escape_html(p, pwd));
399 APR_BRIGADE_INSERT_TAIL(out, apr_bucket_pool_create(str, strlen(str),
400 p, c->bucket_alloc));
404 str = apr_psprintf(p, "%s\n</pre>\n\n<hr />\n\n<pre>\n",
405 ap_escape_html(p, readme));
407 APR_BRIGADE_INSERT_TAIL(out, apr_bucket_pool_create(str,
412 /* make sure page intro gets sent out */
413 APR_BRIGADE_INSERT_TAIL(out, apr_bucket_flush_create(c->bucket_alloc));
414 if (APR_SUCCESS != (rv = ap_pass_brigade(f->next, out))) {
417 apr_brigade_cleanup(out);
422 /* loop through each line of directory */
423 while (BODY == ctx->state) {
428 ap_regex_t *re = NULL;
429 ap_regmatch_t re_result[LS_REG_MATCH];
431 /* Compile the output format of "ls -s1" as a fallback for non-unix ftp listings */
432 re = ap_pregcomp(p, LS_REG_PATTERN, AP_REG_EXTENDED);
433 ap_assert(re != NULL);
435 /* get a complete line */
436 /* if the buffer overruns - throw data away */
437 while (!found && !APR_BRIGADE_EMPTY(ctx->in)) {
438 char *pos, *response;
442 e = APR_BRIGADE_FIRST(ctx->in);
443 if (APR_BUCKET_IS_EOS(e)) {
447 if (APR_SUCCESS != (rv = apr_bucket_read(e, (const char **)&response, &len, APR_BLOCK_READ))) {
450 pos = memchr(response, APR_ASCII_LF, len);
452 if ((response + len) != (pos + 1)) {
453 len = pos - response + 1;
454 apr_bucket_split(e, pos - response + 1);
458 max = sizeof(ctx->buffer) - strlen(ctx->buffer) - 1;
463 /* len+1 to leave space for the trailing nil char */
464 apr_cpystrn(ctx->buffer+strlen(ctx->buffer), response, len+1);
466 APR_BUCKET_REMOVE(e);
467 apr_bucket_destroy(e);
470 /* EOS? jump to footer */
476 /* not complete? leave and try get some more */
482 apr_size_t n = strlen(ctx->buffer);
483 if (ctx->buffer[n-1] == CRLF[1]) /* strip trailing '\n' */
484 ctx->buffer[--n] = '\0';
485 if (ctx->buffer[n-1] == CRLF[0]) /* strip trailing '\r' if present */
486 ctx->buffer[--n] = '\0';
490 if (ctx->buffer[0] == 'l' && (filename = strstr(ctx->buffer, " -> ")) != NULL) {
491 char *link_ptr = filename;
495 } while (filename[0] != ' ' && filename > ctx->buffer);
496 if (filename > ctx->buffer)
497 *(filename++) = '\0';
498 *(link_ptr++) = '\0';
499 str = apr_psprintf(p, "%s <a href=\"%s\">%s %s</a>\n",
500 ap_escape_html(p, ctx->buffer),
501 ap_escape_uri(p, filename),
502 ap_escape_html(p, filename),
503 ap_escape_html(p, link_ptr));
506 /* a directory/file? */
507 else if (ctx->buffer[0] == 'd' || ctx->buffer[0] == '-' || ctx->buffer[0] == 'l' || apr_isdigit(ctx->buffer[0])) {
509 char *searchptr = NULL;
511 if (apr_isdigit(ctx->buffer[0])) { /* handle DOS dir */
512 searchptr = strchr(ctx->buffer, '<');
513 if (searchptr != NULL)
515 searchptr = strchr(ctx->buffer, '>');
516 if (searchptr != NULL)
520 filename = strrchr(ctx->buffer, ' ');
521 *(filename++) = '\0';
523 /* handle filenames with spaces in 'em */
524 if (!strcmp(filename, ".") || !strcmp(filename, "..") || firstfile) {
526 searchidx = filename - ctx->buffer;
528 else if (searchidx != 0 && ctx->buffer[searchidx] != 0) {
530 ctx->buffer[searchidx - 1] = '\0';
531 filename = &ctx->buffer[searchidx];
534 /* Append a slash to the HREF link for directories */
535 if (!strcmp(filename, ".") || !strcmp(filename, "..") || ctx->buffer[0] == 'd') {
536 str = apr_psprintf(p, "%s <a href=\"%s/\">%s</a>\n",
537 ap_escape_html(p, ctx->buffer),
538 ap_escape_uri(p, filename),
539 ap_escape_html(p, filename));
542 str = apr_psprintf(p, "%s <a href=\"%s\">%s</a>\n",
543 ap_escape_html(p, ctx->buffer),
544 ap_escape_uri(p, filename),
545 ap_escape_html(p, filename));
548 /* Try a fallback for listings in the format of "ls -s1" */
549 else if (0 == ap_regexec(re, ctx->buffer, LS_REG_MATCH, re_result, 0)) {
551 filename = apr_pstrndup(p, &ctx->buffer[re_result[2].rm_so], re_result[2].rm_eo - re_result[2].rm_so);
553 str = apr_pstrcat(p, ap_escape_html(p, apr_pstrndup(p, ctx->buffer, re_result[2].rm_so)),
554 "<a href=\"", ap_escape_uri(p, filename), "\">",
555 ap_escape_html(p, filename), "</a>\n", NULL);
558 strcat(ctx->buffer, "\n"); /* re-append the newline */
559 str = ap_escape_html(p, ctx->buffer);
562 /* erase buffer for next time around */
565 APR_BRIGADE_INSERT_TAIL(out, apr_bucket_pool_create(str, strlen(str), p,
567 APR_BRIGADE_INSERT_TAIL(out, apr_bucket_flush_create(c->bucket_alloc));
568 if (APR_SUCCESS != (rv = ap_pass_brigade(f->next, out))) {
571 apr_brigade_cleanup(out);
575 if (FOOTER == ctx->state) {
576 str = apr_psprintf(p, "</pre>\n\n <hr />\n\n %s\n\n </body>\n</html>\n", ap_psignature("", r));
577 APR_BRIGADE_INSERT_TAIL(out, apr_bucket_pool_create(str, strlen(str), p,
579 APR_BRIGADE_INSERT_TAIL(out, apr_bucket_flush_create(c->bucket_alloc));
580 APR_BRIGADE_INSERT_TAIL(out, apr_bucket_eos_create(c->bucket_alloc));
581 if (APR_SUCCESS != (rv = ap_pass_brigade(f->next, out))) {
584 apr_brigade_destroy(out);
591 * Generic "send FTP command to server" routine, using the control socket.
592 * Returns the FTP returncode (3 digit code)
593 * Allows for tracing the FTP protocol (in LogLevel debug)
596 proxy_ftp_command(const char *cmd, request_rec *r, conn_rec *ftp_ctrl,
597 apr_bucket_brigade *bb, char **pmessage)
601 char message[HUGE_STRING_LEN];
603 /* If cmd == NULL, we retrieve the next ftp response line */
605 conn_rec *c = r->connection;
606 APR_BRIGADE_INSERT_TAIL(bb, apr_bucket_pool_create(cmd, strlen(cmd), r->pool, c->bucket_alloc));
607 APR_BRIGADE_INSERT_TAIL(bb, apr_bucket_flush_create(c->bucket_alloc));
608 ap_pass_brigade(ftp_ctrl->output_filters, bb);
610 /* strip off the CRLF for logging */
611 apr_cpystrn(message, cmd, sizeof(message));
612 if ((crlf = strchr(message, '\r')) != NULL ||
613 (crlf = strchr(message, '\n')) != NULL)
615 if (strncmp(message,"PASS ", 5) == 0)
616 strcpy(&message[5], "****");
617 ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, r->server,
618 "proxy:>FTP: %s", message);
621 rc = ftp_getrc_msg(ftp_ctrl, bb, message, sizeof message);
622 if (rc == -1 || rc == 421)
623 strcpy(message,"<unable to read result>");
624 if ((crlf = strchr(message, '\r')) != NULL ||
625 (crlf = strchr(message, '\n')) != NULL)
627 ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, r->server,
628 "proxy:<FTP: %3.3u %s", rc, message);
630 if (pmessage != NULL)
631 *pmessage = apr_pstrdup(r->pool, message);
636 /* Set ftp server to TYPE {A,I,E} before transfer of a directory or file */
637 static int ftp_set_TYPE(char xfer_type, request_rec *r, conn_rec *ftp_ctrl,
638 apr_bucket_brigade *bb, char **pmessage)
640 char old_type[2] = { 'A', '\0' }; /* After logon, mode is ASCII */
644 /* set desired type */
645 old_type[0] = xfer_type;
647 rc = proxy_ftp_command(apr_pstrcat(r->pool, "TYPE ", old_type, CRLF, NULL),
648 r, ftp_ctrl, bb, pmessage);
649 /* responses: 200, 421, 500, 501, 504, 530 */
650 /* 200 Command okay. */
651 /* 421 Service not available, closing control connection. */
652 /* 500 Syntax error, command unrecognized. */
653 /* 501 Syntax error in parameters or arguments. */
654 /* 504 Command not implemented for that parameter. */
655 /* 530 Not logged in. */
656 if (rc == -1 || rc == 421) {
657 ret = ap_proxyerror(r, HTTP_BAD_GATEWAY,
658 "Error reading from remote server");
660 else if (rc != 200 && rc != 504) {
661 ret = ap_proxyerror(r, HTTP_BAD_GATEWAY,
662 "Unable to set transfer type");
664 /* Allow not implemented */
666 /* ignore it silently */;
672 /* Return the current directory which we have selected on the FTP server, or NULL */
673 static char *ftp_get_PWD(request_rec *r, conn_rec *ftp_ctrl, apr_bucket_brigade *bb)
676 char *ftpmessage = NULL;
678 /* responses: 257, 500, 501, 502, 421, 550 */
679 /* 257 "<directory-name>" <commentary> */
680 /* 421 Service not available, closing control connection. */
681 /* 500 Syntax error, command unrecognized. */
682 /* 501 Syntax error in parameters or arguments. */
683 /* 502 Command not implemented. */
684 /* 550 Requested action not taken. */
685 switch (proxy_ftp_command("PWD" CRLF, r, ftp_ctrl, bb, &ftpmessage)) {
689 ap_proxyerror(r, HTTP_BAD_GATEWAY,
690 "Failed to read PWD on ftp server");
694 const char *dirp = ftpmessage;
695 cwd = ap_getword_conf(r->pool, &dirp);
702 /* Common routine for failed authorization (i.e., missing or wrong password)
703 * to an ftp service. This causes most browsers to retry the request
704 * with username and password (which was presumably queried from the user)
705 * supplied in the Authorization: header.
706 * Note that we "invent" a realm name which consists of the
707 * ftp://user@host part of the reqest (sans password -if supplied but invalid-)
709 static int ftp_unauthorized(request_rec *r, int log_it)
711 r->proxyreq = PROXYREQ_NONE;
713 * Log failed requests if they supplied a password (log username/password
717 ap_log_rerror(APLOG_MARK, APLOG_INFO, 0, r,
718 "proxy: missing or failed auth to %s",
719 apr_uri_unparse(r->pool,
720 &r->parsed_uri, APR_URI_UNP_OMITPATHINFO));
722 apr_table_setn(r->err_headers_out, "WWW-Authenticate",
723 apr_pstrcat(r->pool, "Basic realm=\"",
724 apr_uri_unparse(r->pool, &r->parsed_uri,
725 APR_URI_UNP_OMITPASSWORD | APR_URI_UNP_OMITPATHINFO),
728 return HTTP_UNAUTHORIZED;
732 apr_status_t proxy_ftp_cleanup(request_rec *r, proxy_conn_rec *backend)
735 backend->close_on_recycle = 1;
736 ap_set_module_config(r->connection->conn_config, &proxy_ftp_module, NULL);
737 ap_proxy_release_connection("FTP", backend, r->server);
743 int ftp_proxyerror(request_rec *r, proxy_conn_rec *conn, int statuscode, const char *message)
745 proxy_ftp_cleanup(r, conn);
746 return ap_proxyerror(r, statuscode, message);
749 * Handles direct access of ftp:// URLs
750 * Original (Non-PASV) version from
751 * Troy Morrison <spiffnet@zoom.com>
752 * PASV added by Chuck
753 * Filters by [Graham Leggett <minfrin@sharp.fm>]
755 static int proxy_ftp_handler(request_rec *r, proxy_worker *worker,
756 proxy_server_conf *conf, char *url,
757 const char *proxyhost, apr_port_t proxyport)
759 apr_pool_t *p = r->pool;
760 conn_rec *c = r->connection;
761 proxy_conn_rec *backend;
762 apr_socket_t *sock, *local_sock, *data_sock = NULL;
763 apr_sockaddr_t *connect_addr = NULL;
765 conn_rec *origin, *data = NULL;
766 apr_status_t err = APR_SUCCESS;
767 apr_bucket_brigade *bb = apr_brigade_create(p, c->bucket_alloc);
768 char *buf, *connectname;
769 apr_port_t connectport;
770 char buffer[MAX_STRING_LEN];
771 char *ftpmessage = NULL;
772 char *path, *strp, *type_suffix, *cwd = NULL;
775 /* char *account = NULL; how to supply an account in a URL? */
776 const char *password = NULL;
780 char xfer_type = 'A'; /* after ftp login, the default is ASCII */
782 #if defined(USE_MDTM) && (defined(HAVE_TIMEGM) || defined(HAVE_GMTOFF))
783 apr_time_t mtime = 0L;
786 /* stuff for PASV mode */
787 int connect = 0, use_port = 0;
788 char dates[APR_RFC822_DATE_LEN];
790 apr_pool_t *address_pool;
792 /* is this for us? */
794 ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, r->server,
795 "proxy: FTP: declining URL %s - proxyhost %s specified:", url, proxyhost);
796 return DECLINED; /* proxy connections are via HTTP */
798 if (strncasecmp(url, "ftp:", 4)) {
799 ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, r->server,
800 "proxy: FTP: declining URL %s - not ftp:", url);
801 return DECLINED; /* only interested in FTP */
803 ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, r->server,
804 "proxy: FTP: serving URL %s", url);
808 * I: Who Do I Connect To? -----------------------
810 * Break up the URL to determine the host to connect to
813 /* we only support GET and HEAD */
814 if (r->method_number != M_GET)
815 return HTTP_NOT_IMPLEMENTED;
817 /* We break the URL into host, port, path-search */
818 if (r->parsed_uri.hostname == NULL) {
819 if (APR_SUCCESS != apr_uri_parse(p, url, &uri)) {
820 return ap_proxyerror(r, HTTP_BAD_REQUEST,
821 apr_psprintf(p, "URI cannot be parsed: %s", url));
823 connectname = uri.hostname;
824 connectport = uri.port;
825 path = apr_pstrdup(p, uri.path);
828 connectname = r->parsed_uri.hostname;
829 connectport = r->parsed_uri.port;
830 path = apr_pstrdup(p, r->parsed_uri.path);
832 if (connectport == 0) {
833 connectport = apr_uri_port_of_scheme("ftp");
835 path = (path != NULL && path[0] != '\0') ? &path[1] : "";
837 type_suffix = strchr(path, ';');
838 if (type_suffix != NULL)
839 *(type_suffix++) = '\0';
841 if (type_suffix != NULL && strncmp(type_suffix, "type=", 5) == 0
842 && apr_isalpha(type_suffix[5])) {
843 /* "type=d" forces a dir listing.
844 * The other types (i|a|e) are directly used for the ftp TYPE command
846 if ( ! (dirlisting = (apr_tolower(type_suffix[5]) == 'd')))
847 xfer_type = apr_toupper(type_suffix[5]);
849 /* Check valid types, rather than ignoring invalid types silently: */
850 if (strchr("AEI", xfer_type) == NULL)
851 return ap_proxyerror(r, HTTP_BAD_REQUEST, apr_pstrcat(r->pool,
852 "ftp proxy supports only types 'a', 'i', or 'e': \"",
853 type_suffix, "\" is invalid.", NULL));
856 /* make binary transfers the default */
862 * The "Authorization:" header must be checked first. We allow the user
863 * to "override" the URL-coded user [ & password ] in the Browsers'
864 * User&Password Dialog. NOTE that this is only marginally more secure
865 * than having the password travel in plain as part of the URL, because
866 * Basic Auth simply uuencodes the plain text password. But chances are
867 * still smaller that the URL is logged regularly.
869 if ((password = apr_table_get(r->headers_in, "Authorization")) != NULL
870 && strcasecmp(ap_getword(r->pool, &password, ' '), "Basic") == 0
871 && (password = ap_pbase64decode(r->pool, password))[0] != ':') {
873 * Note that this allocation has to be made from r->connection->pool
874 * because it has the lifetime of the connection. The other
875 * allocations are temporary and can be tossed away any time.
877 user = ap_getword_nulls(r->connection->pool, &password, ':');
878 r->ap_auth_type = "Basic";
879 r->user = r->parsed_uri.user = user;
881 else if ((user = r->parsed_uri.user) != NULL) {
882 user = apr_pstrdup(p, user);
884 if ((password = r->parsed_uri.password) != NULL) {
885 char *tmp = apr_pstrdup(p, password);
892 password = "apache-proxy@";
895 ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, r->server,
896 "proxy: FTP: connecting %s to %s:%d", url, connectname, connectport);
898 if (worker->is_address_reusable) {
899 if (!worker->cp->addr) {
900 if ((err = PROXY_THREAD_LOCK(worker)) != APR_SUCCESS) {
901 ap_log_error(APLOG_MARK, APLOG_ERR, err, r->server,
903 return HTTP_INTERNAL_SERVER_ERROR;
906 connect_addr = worker->cp->addr;
907 address_pool = worker->cp->pool;
910 address_pool = r->pool;
912 /* do a DNS lookup for the destination host */
914 err = apr_sockaddr_info_get(&(connect_addr),
915 connectname, APR_UNSPEC,
918 if (worker->is_address_reusable && !worker->cp->addr) {
919 worker->cp->addr = connect_addr;
920 PROXY_THREAD_UNLOCK(worker);
923 * get all the possible IP addresses for the destname and loop through
924 * them until we get a successful connection
926 if (APR_SUCCESS != err) {
927 return ap_proxyerror(r, HTTP_BAD_GATEWAY, apr_pstrcat(p,
928 "DNS lookup failure for: ",
932 /* check if ProxyBlock directive on this host */
933 if (OK != ap_proxy_checkproxyblock(r, conf, connect_addr)) {
934 return ap_proxyerror(r, HTTP_FORBIDDEN,
935 "Connect to remote machine blocked");
938 /* create space for state information */
939 backend = (proxy_conn_rec *) ap_get_module_config(c->conn_config, &proxy_ftp_module);
941 status = ap_proxy_acquire_connection("FTP", &backend, worker, r->server);
944 backend->close_on_recycle = 1;
945 ap_proxy_release_connection("FTP", backend, r->server);
949 /* TODO: see if ftp could use determine_connection */
950 backend->addr = connect_addr;
951 ap_set_module_config(c->conn_config, &proxy_ftp_module, backend);
956 * II: Make the Connection -----------------------
958 * We have determined who to connect to. Now make the connection.
962 if (ap_proxy_connect_backend("FTP", backend, worker, r->server)) {
963 ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, r->server,
964 "proxy: FTP: an error occurred creating a new connection to %pI (%s)",
965 connect_addr, connectname);
966 proxy_ftp_cleanup(r, backend);
967 return HTTP_SERVICE_UNAVAILABLE;
970 if (!backend->connection) {
971 status = ap_proxy_connection_create("FTP", backend, c, r->server);
973 proxy_ftp_cleanup(r, backend);
979 origin = backend->connection;
980 sock = backend->sock;
982 ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, r->server,
983 "proxy: FTP: control connection complete");
987 * III: Send Control Request -------------------------
989 * Log into the ftp server, send the username & password, change to the
990 * correct directory...
994 /* possible results: */
995 /* 120 Service ready in nnn minutes. */
996 /* 220 Service ready for new user. */
997 /* 421 Service not available, closing control connection. */
998 rc = proxy_ftp_command(NULL, r, origin, bb, &ftpmessage);
999 if (rc == -1 || rc == 421) {
1000 return ftp_proxyerror(r, backend, HTTP_BAD_GATEWAY, "Error reading from remote server");
1004 * RFC2616 states: 14.37 Retry-After
1006 * The Retry-After response-header field can be used with a 503 (Service
1007 * Unavailable) response to indicate how long the service is expected
1008 * to be unavailable to the requesting client. [...] The value of
1009 * this field can be either an HTTP-date or an integer number of
1010 * seconds (in decimal) after the time of the response. Retry-After
1011 * = "Retry-After" ":" ( HTTP-date | delta-seconds )
1013 char *secs_str = ftpmessage;
1016 /* Look for a number, preceded by whitespace */
1018 if ((secs_str==ftpmessage || apr_isspace(secs_str[-1])) &&
1019 apr_isdigit(secs_str[0]))
1021 if (*secs_str != '\0') {
1022 secs = atol(secs_str);
1023 apr_table_add(r->headers_out, "Retry-After",
1024 apr_psprintf(p, "%lu", (unsigned long)(60 * secs)));
1026 return ftp_proxyerror(r, backend, HTTP_SERVICE_UNAVAILABLE, ftpmessage);
1029 return ftp_proxyerror(r, backend, HTTP_BAD_GATEWAY, ftpmessage);
1032 rc = proxy_ftp_command(apr_pstrcat(p, "USER ", user, CRLF, NULL),
1033 r, origin, bb, &ftpmessage);
1034 /* possible results; 230, 331, 332, 421, 500, 501, 530 */
1035 /* states: 1 - error, 2 - success; 3 - send password, 4,5 fail */
1036 /* 230 User logged in, proceed. */
1037 /* 331 User name okay, need password. */
1038 /* 332 Need account for login. */
1039 /* 421 Service not available, closing control connection. */
1040 /* 500 Syntax error, command unrecognized. */
1041 /* (This may include errors such as command line too long.) */
1042 /* 501 Syntax error in parameters or arguments. */
1043 /* 530 Not logged in. */
1044 if (rc == -1 || rc == 421) {
1045 return ftp_proxyerror(r, backend, HTTP_BAD_GATEWAY, "Error reading from remote server");
1048 proxy_ftp_cleanup(r, backend);
1049 return ftp_unauthorized(r, 1); /* log it: user name guessing
1052 if (rc != 230 && rc != 331) {
1053 return ftp_proxyerror(r, backend, HTTP_BAD_GATEWAY, ftpmessage);
1056 if (rc == 331) { /* send password */
1057 if (password == NULL) {
1058 proxy_ftp_cleanup(r, backend);
1059 return ftp_unauthorized(r, 0);
1062 rc = proxy_ftp_command(apr_pstrcat(p, "PASS ", password, CRLF, NULL),
1063 r, origin, bb, &ftpmessage);
1064 /* possible results 202, 230, 332, 421, 500, 501, 503, 530 */
1065 /* 230 User logged in, proceed. */
1066 /* 332 Need account for login. */
1067 /* 421 Service not available, closing control connection. */
1068 /* 500 Syntax error, command unrecognized. */
1069 /* 501 Syntax error in parameters or arguments. */
1070 /* 503 Bad sequence of commands. */
1071 /* 530 Not logged in. */
1072 if (rc == -1 || rc == 421) {
1073 return ftp_proxyerror(r, backend, HTTP_BAD_GATEWAY,
1074 "Error reading from remote server");
1077 return ftp_proxyerror(r, backend, HTTP_UNAUTHORIZED,
1078 apr_pstrcat(p, "Need account for login: ", ftpmessage, NULL));
1080 /* @@@ questionable -- we might as well return a 403 Forbidden here */
1082 proxy_ftp_cleanup(r, backend);
1083 return ftp_unauthorized(r, 1); /* log it: passwd guessing
1086 if (rc != 230 && rc != 202) {
1087 return ftp_proxyerror(r, backend, HTTP_BAD_GATEWAY, ftpmessage);
1090 apr_table_set(r->notes, "Directory-README", ftpmessage);
1093 /* Special handling for leading "%2f": this enforces a "cwd /"
1094 * out of the $HOME directory which was the starting point after login
1096 if (strncasecmp(path, "%2f", 3) == 0) {
1098 while (*path == '/') /* skip leading '/' (after root %2f) */
1101 rc = proxy_ftp_command("CWD /" CRLF, r, origin, bb, &ftpmessage);
1102 if (rc == -1 || rc == 421)
1103 return ftp_proxyerror(r, backend, HTTP_BAD_GATEWAY,
1104 "Error reading from remote server");
1108 * set the directory (walk directory component by component): this is
1109 * what we must do if we don't know the OS type of the remote machine
1112 strp = strchr(path, '/');
1117 len = decodeenc(path); /* Note! This decodes a %2f -> "/" */
1119 if (strchr(path, '/')) { /* are there now any '/' characters? */
1120 return ftp_proxyerror(r, backend, HTTP_BAD_REQUEST,
1121 "Use of /%2f is only allowed at the base directory");
1124 /* NOTE: FTP servers do globbing on the path.
1125 * So we need to escape the URI metacharacters.
1126 * We use a special glob-escaping routine to escape globbing chars.
1127 * We could also have extended gen_test_char.c with a special T_ESCAPE_FTP_PATH
1129 rc = proxy_ftp_command(apr_pstrcat(p, "CWD ",
1130 ftp_escape_globbingchars(p, path), CRLF, NULL),
1131 r, origin, bb, &ftpmessage);
1133 /* responses: 250, 421, 500, 501, 502, 530, 550 */
1134 /* 250 Requested file action okay, completed. */
1135 /* 421 Service not available, closing control connection. */
1136 /* 500 Syntax error, command unrecognized. */
1137 /* 501 Syntax error in parameters or arguments. */
1138 /* 502 Command not implemented. */
1139 /* 530 Not logged in. */
1140 /* 550 Requested action not taken. */
1141 if (rc == -1 || rc == 421) {
1142 return ftp_proxyerror(r, backend, HTTP_BAD_GATEWAY,
1143 "Error reading from remote server");
1146 return ftp_proxyerror(r, backend, HTTP_NOT_FOUND, ftpmessage);
1149 return ftp_proxyerror(r, backend, HTTP_BAD_GATEWAY, ftpmessage);
1156 * IV: Make Data Connection? -------------------------
1158 * Try EPSV, if that fails... try PASV, if that fails... try PORT.
1160 /* this temporarily switches off EPSV/PASV */
1163 /* set up data connection - EPSV */
1165 apr_sockaddr_t *data_addr;
1167 apr_port_t data_port;
1170 * The EPSV command replaces PASV where both IPV4 and IPV6 is
1171 * supported. Only the port is returned, the IP address is always the
1172 * same as that on the control connection. Example: Entering Extended
1173 * Passive Mode (|||6446|)
1175 rc = proxy_ftp_command("EPSV" CRLF,
1176 r, origin, bb, &ftpmessage);
1177 /* possible results: 227, 421, 500, 501, 502, 530 */
1178 /* 227 Entering Passive Mode (h1,h2,h3,h4,p1,p2). */
1179 /* 421 Service not available, closing control connection. */
1180 /* 500 Syntax error, command unrecognized. */
1181 /* 501 Syntax error in parameters or arguments. */
1182 /* 502 Command not implemented. */
1183 /* 530 Not logged in. */
1184 if (rc == -1 || rc == 421) {
1185 return ftp_proxyerror(r, backend, HTTP_BAD_GATEWAY,
1186 "Error reading from remote server");
1188 if (rc != 229 && rc != 500 && rc != 501 && rc != 502) {
1189 return ftp_proxyerror(r, backend, HTTP_BAD_GATEWAY, ftpmessage);
1191 else if (rc == 229) {
1196 pstr = apr_strtok(pstr, " ", &tok_cntx); /* separate result code */
1198 if (*(pstr + strlen(pstr) + 1) == '=') {
1199 pstr += strlen(pstr) + 2;
1202 pstr = apr_strtok(NULL, "(", &tok_cntx); /* separate address &
1205 pstr = apr_strtok(NULL, ")", &tok_cntx);
1210 apr_sockaddr_t *epsv_addr;
1211 data_port = atoi(pstr + 3);
1213 ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, r->server,
1214 "proxy: FTP: EPSV contacting remote host on port %d",
1217 if ((rv = apr_socket_create(&data_sock, connect_addr->family, SOCK_STREAM, 0, r->pool)) != APR_SUCCESS) {
1218 ap_log_rerror(APLOG_MARK, APLOG_ERR, rv, r,
1219 "proxy: FTP: error creating EPSV socket");
1220 proxy_ftp_cleanup(r, backend);
1221 return HTTP_INTERNAL_SERVER_ERROR;
1224 #if !defined (TPF) && !defined(BEOS)
1225 if (conf->recv_buffer_size > 0
1226 && (rv = apr_socket_opt_set(data_sock, APR_SO_RCVBUF,
1227 conf->recv_buffer_size))) {
1228 ap_log_rerror(APLOG_MARK, APLOG_ERR, rv, r,
1229 "proxy: FTP: apr_socket_opt_set(SO_RCVBUF): Failed to set ProxyReceiveBufferSize, using default");
1233 /* make the connection */
1234 apr_socket_addr_get(&data_addr, APR_REMOTE, sock);
1235 apr_sockaddr_ip_get(&data_ip, data_addr);
1236 apr_sockaddr_info_get(&epsv_addr, data_ip, connect_addr->family, data_port, 0, p);
1237 rv = apr_socket_connect(data_sock, epsv_addr);
1238 if (rv != APR_SUCCESS) {
1239 ap_log_error(APLOG_MARK, APLOG_ERR, rv, r->server,
1240 "proxy: FTP: EPSV attempt to connect to %pI failed - Firewall/NAT?", epsv_addr);
1241 return ftp_proxyerror(r, backend, HTTP_BAD_GATEWAY, apr_psprintf(r->pool,
1242 "EPSV attempt to connect to %pI failed - firewall/NAT?", epsv_addr));
1249 /* and try the regular way */
1250 apr_socket_close(data_sock);
1255 /* set up data connection - PASV */
1257 rc = proxy_ftp_command("PASV" CRLF,
1258 r, origin, bb, &ftpmessage);
1259 /* possible results: 227, 421, 500, 501, 502, 530 */
1260 /* 227 Entering Passive Mode (h1,h2,h3,h4,p1,p2). */
1261 /* 421 Service not available, closing control connection. */
1262 /* 500 Syntax error, command unrecognized. */
1263 /* 501 Syntax error in parameters or arguments. */
1264 /* 502 Command not implemented. */
1265 /* 530 Not logged in. */
1266 if (rc == -1 || rc == 421) {
1267 return ftp_proxyerror(r, backend, HTTP_BAD_GATEWAY,
1268 "Error reading from remote server");
1270 if (rc != 227 && rc != 502) {
1271 return ftp_proxyerror(r, backend, HTTP_BAD_GATEWAY, ftpmessage);
1273 else if (rc == 227) {
1274 unsigned int h0, h1, h2, h3, p0, p1;
1278 /* FIXME: Check PASV against RFC1123 */
1281 pstr = apr_strtok(pstr, " ", &tok_cntx); /* separate result code */
1283 if (*(pstr + strlen(pstr) + 1) == '=') {
1284 pstr += strlen(pstr) + 2;
1287 pstr = apr_strtok(NULL, "(", &tok_cntx); /* separate address &
1290 pstr = apr_strtok(NULL, ")", &tok_cntx);
1294 /* FIXME: Only supports IPV4 - fix in RFC2428 */
1296 if (pstr != NULL && (sscanf(pstr,
1297 "%d,%d,%d,%d,%d,%d", &h3, &h2, &h1, &h0, &p1, &p0) == 6)) {
1299 apr_sockaddr_t *pasv_addr;
1300 apr_port_t pasvport = (p1 << 8) + p0;
1301 ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, r->server,
1302 "proxy: FTP: PASV contacting host %d.%d.%d.%d:%d",
1303 h3, h2, h1, h0, pasvport);
1305 if ((rv = apr_socket_create(&data_sock, connect_addr->family, SOCK_STREAM, 0, r->pool)) != APR_SUCCESS) {
1306 ap_log_rerror(APLOG_MARK, APLOG_ERR, rv, r,
1307 "proxy: error creating PASV socket");
1308 proxy_ftp_cleanup(r, backend);
1309 return HTTP_INTERNAL_SERVER_ERROR;
1312 #if !defined (TPF) && !defined(BEOS)
1313 if (conf->recv_buffer_size > 0
1314 && (rv = apr_socket_opt_set(data_sock, APR_SO_RCVBUF,
1315 conf->recv_buffer_size))) {
1316 ap_log_rerror(APLOG_MARK, APLOG_ERR, rv, r,
1317 "proxy: FTP: apr_socket_opt_set(SO_RCVBUF): Failed to set ProxyReceiveBufferSize, using default");
1321 /* make the connection */
1322 apr_sockaddr_info_get(&pasv_addr, apr_psprintf(p, "%d.%d.%d.%d", h3, h2, h1, h0), connect_addr->family, pasvport, 0, p);
1323 rv = apr_socket_connect(data_sock, pasv_addr);
1324 if (rv != APR_SUCCESS) {
1325 ap_log_error(APLOG_MARK, APLOG_ERR, rv, r->server,
1326 "proxy: FTP: PASV attempt to connect to %pI failed - Firewall/NAT?", pasv_addr);
1327 return ftp_proxyerror(r, backend, HTTP_BAD_GATEWAY, apr_psprintf(r->pool,
1328 "PASV attempt to connect to %pI failed - firewall/NAT?", pasv_addr));
1335 /* and try the regular way */
1336 apr_socket_close(data_sock);
1342 /* set up data connection - PORT */
1344 apr_sockaddr_t *local_addr;
1346 apr_port_t local_port;
1347 unsigned int h0, h1, h2, h3, p0, p1;
1349 if ((rv = apr_socket_create(&local_sock, connect_addr->family, SOCK_STREAM, 0, r->pool)) != APR_SUCCESS) {
1350 ap_log_rerror(APLOG_MARK, APLOG_ERR, rv, r,
1351 "proxy: FTP: error creating local socket");
1352 proxy_ftp_cleanup(r, backend);
1353 return HTTP_INTERNAL_SERVER_ERROR;
1355 apr_socket_addr_get(&local_addr, APR_LOCAL, sock);
1356 local_port = local_addr->port;
1357 apr_sockaddr_ip_get(&local_ip, local_addr);
1359 if ((rv = apr_socket_opt_set(local_sock, APR_SO_REUSEADDR, one))
1361 #ifndef _OSD_POSIX /* BS2000 has this option "always on" */
1362 ap_log_rerror(APLOG_MARK, APLOG_ERR, rv, r,
1363 "proxy: FTP: error setting reuseaddr option");
1364 proxy_ftp_cleanup(r, backend);
1365 return HTTP_INTERNAL_SERVER_ERROR;
1366 #endif /* _OSD_POSIX */
1369 apr_sockaddr_info_get(&local_addr, local_ip, APR_UNSPEC, local_port, 0, r->pool);
1371 if ((rv = apr_socket_bind(local_sock, local_addr)) != APR_SUCCESS) {
1372 ap_log_rerror(APLOG_MARK, APLOG_ERR, rv, r,
1373 "proxy: FTP: error binding to ftp data socket %pI", local_addr);
1374 proxy_ftp_cleanup(r, backend);
1375 return HTTP_INTERNAL_SERVER_ERROR;
1378 /* only need a short queue */
1379 if ((rv = apr_socket_listen(local_sock, 2)) != APR_SUCCESS) {
1380 ap_log_rerror(APLOG_MARK, APLOG_ERR, rv, r,
1381 "proxy: FTP: error listening to ftp data socket %pI", local_addr);
1382 proxy_ftp_cleanup(r, backend);
1383 return HTTP_INTERNAL_SERVER_ERROR;
1386 /* FIXME: Sent PORT here */
1388 if (local_ip && (sscanf(local_ip,
1389 "%d.%d.%d.%d", &h3, &h2, &h1, &h0) == 4)) {
1390 p1 = (local_port >> 8);
1391 p0 = (local_port & 0xFF);
1393 rc = proxy_ftp_command(apr_psprintf(p, "PORT %d,%d,%d,%d,%d,%d" CRLF, h3, h2, h1, h0, p1, p0),
1394 r, origin, bb, &ftpmessage);
1395 /* possible results: 200, 421, 500, 501, 502, 530 */
1396 /* 200 Command okay. */
1397 /* 421 Service not available, closing control connection. */
1398 /* 500 Syntax error, command unrecognized. */
1399 /* 501 Syntax error in parameters or arguments. */
1400 /* 502 Command not implemented. */
1401 /* 530 Not logged in. */
1402 if (rc == -1 || rc == 421) {
1403 return ftp_proxyerror(r, backend, HTTP_BAD_GATEWAY,
1404 "Error reading from remote server");
1407 return ftp_proxyerror(r, backend, HTTP_BAD_GATEWAY, buffer);
1410 /* signal that we must use the EPRT/PORT loop */
1415 * The EPRT command replaces PORT where both IPV4 and IPV6 is supported. The first
1416 * number (1,2) indicates the protocol type. Examples:
1417 * EPRT |1|132.235.1.2|6275|
1418 * EPRT |2|1080::8:800:200C:417A|5282|
1420 return ftp_proxyerror(r, backend, HTTP_NOT_IMPLEMENTED,
1421 "Connect to IPV6 ftp server using EPRT not supported. Enable EPSV.");
1427 * V: Set The Headers -------------------
1429 * Get the size of the request, set up the environment for HTTP.
1432 /* set request; "path" holds last path component */
1433 len = decodeenc(path);
1435 if (strchr(path, '/')) { /* are there now any '/' characters? */
1436 return ftp_proxyerror(r, backend, HTTP_BAD_REQUEST,
1437 "Use of /%2f is only allowed at the base directory");
1440 /* If len == 0 then it must be a directory (you can't RETR nothing)
1441 * Also, don't allow to RETR by wildcard. Instead, create a dirlisting
1443 if (len == 0 || ftp_check_globbingchars(path)) {
1447 /* (from FreeBSD ftpd):
1448 * SIZE is not in RFC959, but Postel has blessed it and
1449 * it will be in the updated RFC.
1451 * Return size of file in a format suitable for
1452 * using with RESTART (we just count bytes).
1454 /* from draft-ietf-ftpext-mlst-14.txt:
1456 * change depending on the current STRUcture, MODE and TYPE of the data
1457 * connection, or a data connection which would be created were one
1458 * created now. Thus, the result of the SIZE command is dependent on
1459 * the currently established STRU, MODE and TYPE parameters.
1461 /* Therefore: switch to binary if the user did not specify ";type=a" */
1462 ftp_set_TYPE(xfer_type, r, origin, bb, &ftpmessage);
1463 rc = proxy_ftp_command(apr_pstrcat(p, "SIZE ",
1464 ftp_escape_globbingchars(p, path), CRLF, NULL),
1465 r, origin, bb, &ftpmessage);
1466 if (rc == -1 || rc == 421) {
1467 return ftp_proxyerror(r, backend, HTTP_BAD_GATEWAY,
1468 "Error reading from remote server");
1470 else if (rc == 213) {/* Size command ok */
1472 for (j = 0; apr_isdigit(ftpmessage[j]); j++)
1474 ftpmessage[j] = '\0';
1475 if (ftpmessage[0] != '\0')
1476 size = ftpmessage; /* already pstrdup'ed: no copy necessary */
1478 else if (rc == 550) { /* Not a regular file */
1479 ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, r->server,
1480 "proxy: FTP: SIZE shows this is a directory");
1482 rc = proxy_ftp_command(apr_pstrcat(p, "CWD ",
1483 ftp_escape_globbingchars(p, path), CRLF, NULL),
1484 r, origin, bb, &ftpmessage);
1485 /* possible results: 250, 421, 500, 501, 502, 530, 550 */
1486 /* 250 Requested file action okay, completed. */
1487 /* 421 Service not available, closing control connection. */
1488 /* 500 Syntax error, command unrecognized. */
1489 /* 501 Syntax error in parameters or arguments. */
1490 /* 502 Command not implemented. */
1491 /* 530 Not logged in. */
1492 /* 550 Requested action not taken. */
1493 if (rc == -1 || rc == 421) {
1494 return ftp_proxyerror(r, backend, HTTP_BAD_GATEWAY,
1495 "Error reading from remote server");
1498 return ftp_proxyerror(r, backend, HTTP_NOT_FOUND, ftpmessage);
1501 return ftp_proxyerror(r, backend, HTTP_BAD_GATEWAY, ftpmessage);
1508 cwd = ftp_get_PWD(r, origin, bb);
1510 apr_table_set(r->notes, "Directory-PWD", cwd);
1514 ftp_set_TYPE('A', r, origin, bb, NULL);
1515 /* If the current directory contains no slash, we are talking to
1516 * a non-unix ftp system. Try LIST instead of "LIST -lag", it
1517 * should return a long listing anyway (unlike NLST).
1518 * Some exotic FTP servers might choke on the "-lag" switch.
1520 /* Note that we do not escape the path here, to allow for
1521 * queries like: ftp://user@host/apache/src/server/http_*.c
1524 buf = apr_pstrcat(p, "LIST ", path, CRLF, NULL);
1525 else if (cwd == NULL || strchr(cwd, '/') != NULL)
1526 buf = apr_pstrcat(p, "LIST -lag", CRLF, NULL);
1531 /* switch to binary if the user did not specify ";type=a" */
1532 ftp_set_TYPE(xfer_type, r, origin, bb, &ftpmessage);
1533 #if defined(USE_MDTM) && (defined(HAVE_TIMEGM) || defined(HAVE_GMTOFF))
1534 /* from draft-ietf-ftpext-mlst-14.txt:
1535 * The FTP command, MODIFICATION TIME (MDTM), can be used to determine
1536 * when a file in the server NVFS was last modified. <..>
1537 * The syntax of a time value is:
1538 * time-val = 14DIGIT [ "." 1*DIGIT ] <..>
1539 * Symbolically, a time-val may be viewed as
1540 * YYYYMMDDHHMMSS.sss
1541 * The "." and subsequent digits ("sss") are optional. <..>
1542 * Time values are always represented in UTC (GMT)
1544 rc = proxy_ftp_command(apr_pstrcat(p, "MDTM ", ftp_escape_globbingchars(p, path), CRLF, NULL),
1545 r, origin, bb, &ftpmessage);
1546 /* then extract the Last-Modified time from it (YYYYMMDDhhmmss or YYYYMMDDhhmmss.xxx GMT). */
1556 if (6 == sscanf(ftpmessage, "%4[0-9]%2[0-9]%2[0-9]%2[0-9]%2[0-9]%2[0-9]",
1557 time_val.YYYY, time_val.MM, time_val.DD, time_val.hh, time_val.mm, time_val.ss)) {
1559 memset (&tms, '\0', sizeof tms);
1560 tms.tm_year = atoi(time_val.YYYY) - 1900;
1561 tms.tm_mon = atoi(time_val.MM) - 1;
1562 tms.tm_mday = atoi(time_val.DD);
1563 tms.tm_hour = atoi(time_val.hh);
1564 tms.tm_min = atoi(time_val.mm);
1565 tms.tm_sec = atoi(time_val.ss);
1566 #ifdef HAVE_TIMEGM /* Does system have timegm()? */
1567 mtime = timegm(&tms);
1568 mtime *= APR_USEC_PER_SEC;
1569 #elif HAVE_GMTOFF /* does struct tm have a member tm_gmtoff? */
1570 /* mktime will subtract the local timezone, which is not what we want.
1571 * Add it again because the MDTM string is GMT
1573 mtime = mktime(&tms);
1574 mtime += tms.tm_gmtoff;
1575 mtime *= APR_USEC_PER_SEC;
1581 #endif /* USE_MDTM */
1582 /* FIXME: Handle range requests - send REST */
1583 buf = apr_pstrcat(p, "RETR ", ftp_escape_globbingchars(p, path), CRLF, NULL);
1585 rc = proxy_ftp_command(buf, r, origin, bb, &ftpmessage);
1586 /* rc is an intermediate response for the LIST or RETR commands */
1589 * RETR: 110, 125, 150, 226, 250, 421, 425, 426, 450, 451, 500, 501, 530,
1590 * 550 NLST: 125, 150, 226, 250, 421, 425, 426, 450, 451, 500, 501, 502,
1593 /* 110 Restart marker reply. */
1594 /* 125 Data connection already open; transfer starting. */
1595 /* 150 File status okay; about to open data connection. */
1596 /* 226 Closing data connection. */
1597 /* 250 Requested file action okay, completed. */
1598 /* 421 Service not available, closing control connection. */
1599 /* 425 Can't open data connection. */
1600 /* 426 Connection closed; transfer aborted. */
1601 /* 450 Requested file action not taken. */
1602 /* 451 Requested action aborted. Local error in processing. */
1603 /* 500 Syntax error, command unrecognized. */
1604 /* 501 Syntax error in parameters or arguments. */
1605 /* 530 Not logged in. */
1606 /* 550 Requested action not taken. */
1607 if (rc == -1 || rc == 421) {
1608 return ftp_proxyerror(r, backend, HTTP_BAD_GATEWAY,
1609 "Error reading from remote server");
1612 ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, r->server,
1613 "proxy: FTP: RETR failed, trying LIST instead");
1615 /* Directory Listings should always be fetched in ASCII mode */
1617 ftp_set_TYPE('A', r, origin, bb, NULL);
1619 rc = proxy_ftp_command(apr_pstrcat(p, "CWD ",
1620 ftp_escape_globbingchars(p, path), CRLF, NULL),
1621 r, origin, bb, &ftpmessage);
1622 /* possible results: 250, 421, 500, 501, 502, 530, 550 */
1623 /* 250 Requested file action okay, completed. */
1624 /* 421 Service not available, closing control connection. */
1625 /* 500 Syntax error, command unrecognized. */
1626 /* 501 Syntax error in parameters or arguments. */
1627 /* 502 Command not implemented. */
1628 /* 530 Not logged in. */
1629 /* 550 Requested action not taken. */
1630 if (rc == -1 || rc == 421) {
1631 return ftp_proxyerror(r, backend, HTTP_BAD_GATEWAY,
1632 "Error reading from remote server");
1635 return ftp_proxyerror(r, backend, HTTP_NOT_FOUND, ftpmessage);
1638 return ftp_proxyerror(r, backend, HTTP_BAD_GATEWAY, ftpmessage);
1641 /* Update current directory after CWD */
1642 cwd = ftp_get_PWD(r, origin, bb);
1644 apr_table_set(r->notes, "Directory-PWD", cwd);
1647 /* See above for the "LIST" vs. "LIST -lag" discussion. */
1648 rc = proxy_ftp_command((cwd == NULL || strchr(cwd, '/') != NULL)
1649 ? "LIST -lag" CRLF : "LIST" CRLF,
1650 r, origin, bb, &ftpmessage);
1652 /* rc is an intermediate response for the LIST command (125 transfer starting, 150 opening data connection) */
1653 if (rc == -1 || rc == 421)
1654 return ftp_proxyerror(r, backend, HTTP_BAD_GATEWAY,
1655 "Error reading from remote server");
1657 if (rc != 125 && rc != 150 && rc != 226 && rc != 250) {
1658 return ftp_proxyerror(r, backend, HTTP_BAD_GATEWAY, ftpmessage);
1661 r->status = HTTP_OK;
1662 r->status_line = "200 OK";
1664 apr_rfc822_date(dates, r->request_time);
1665 apr_table_setn(r->headers_out, "Date", dates);
1666 apr_table_setn(r->headers_out, "Server", ap_get_server_version());
1668 /* set content-type */
1670 ap_set_content_type(r, "text/html");
1673 if (r->content_type) {
1674 ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, r->server,
1675 "proxy: FTP: Content-Type set to %s", r->content_type);
1678 ap_set_content_type(r, ap_default_type(r));
1680 if (xfer_type != 'A' && size != NULL) {
1681 /* We "trust" the ftp server to really serve (size) bytes... */
1682 apr_table_setn(r->headers_out, "Content-Length", size);
1683 ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, r->server,
1684 "proxy: FTP: Content-Length set to %s", size);
1687 apr_table_setn(r->headers_out, "Content-Type", r->content_type);
1688 ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, r->server,
1689 "proxy: FTP: Content-Type set to %s", r->content_type);
1691 #if defined(USE_MDTM) && (defined(HAVE_TIMEGM) || defined(HAVE_GMTOFF))
1693 char datestr[APR_RFC822_DATE_LEN];
1694 apr_rfc822_date(datestr, mtime);
1695 apr_table_set(r->headers_out, "Last-Modified", datestr);
1696 ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, r->server,
1697 "proxy: FTP: Last-Modified set to %s", datestr);
1699 #endif /* USE_MDTM */
1701 /* If an encoding has been set by mistake, delete it.
1702 * @@@ FIXME (e.g., for ftp://user@host/file*.tar.gz,
1703 * @@@ the encoding is currently set to x-gzip)
1705 if (dirlisting && r->content_encoding != NULL)
1706 r->content_encoding = NULL;
1708 /* set content-encoding (not for dir listings, they are uncompressed)*/
1709 if (r->content_encoding != NULL && r->content_encoding[0] != '\0') {
1710 ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, r->server,
1711 "proxy: FTP: Content-Encoding set to %s", r->content_encoding);
1712 apr_table_setn(r->headers_out, "Content-Encoding", r->content_encoding);
1715 /* wait for connection */
1718 rv = apr_socket_accept(&data_sock, local_sock, r->pool);
1719 if (rv == APR_EINTR) {
1722 else if (rv == APR_SUCCESS) {
1726 ap_log_rerror(APLOG_MARK, APLOG_ERR, rv, r,
1727 "proxy: FTP: failed to accept data connection");
1728 proxy_ftp_cleanup(r, backend);
1729 return HTTP_BAD_GATEWAY;
1734 /* the transfer socket is now open, create a new connection */
1735 data = ap_run_create_connection(p, r->server, data_sock, r->connection->id,
1736 r->connection->sbh, c->bucket_alloc);
1739 * the peer reset the connection already; ap_run_create_connection() closed
1742 ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, r->server,
1743 "proxy: FTP: an error occurred creating the transfer connection");
1744 proxy_ftp_cleanup(r, backend);
1745 return HTTP_INTERNAL_SERVER_ERROR;
1748 /* set up the connection filters */
1749 rc = ap_run_pre_connection(data, data_sock);
1750 if (rc != OK && rc != DONE) {
1751 ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, r->server,
1752 "proxy: FTP: pre_connection setup failed (%d)",
1755 proxy_ftp_cleanup(r, backend);
1760 * VI: Receive the Response ------------------------
1762 * Get response from the remote ftp socket, and pass it up the filter chain.
1769 /* insert directory filter */
1770 ap_add_output_filter("PROXY_SEND_DIR", NULL, r, r->connection);
1774 if (!r->header_only) {
1778 ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, r->server,
1779 "proxy: FTP: start body send");
1781 /* read the body, pass it to the output filters */
1782 while (ap_get_brigade(data->input_filters,
1786 conf->io_buffer_size) == APR_SUCCESS) {
1789 apr_off_t readbytes;
1790 apr_brigade_length(bb, 0, &readbytes);
1791 ap_log_error(APLOG_MARK, APLOG_DEBUG, 0,
1792 r->server, "proxy (PID %d): readbytes: %#x",
1793 getpid(), readbytes);
1797 if (APR_BRIGADE_EMPTY(bb)) {
1798 apr_brigade_cleanup(bb);
1802 /* found the last brigade? */
1803 if (APR_BUCKET_IS_EOS(APR_BRIGADE_LAST(bb))) {
1804 /* if this is the last brigade, cleanup the
1805 * backend connection first to prevent the
1806 * backend server from hanging around waiting
1807 * for a slow client to eat these bytes
1809 ap_flush_conn(data);
1810 apr_socket_close(data_sock);
1812 ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, r->server,
1813 "proxy: FTP: data connection closed");
1814 /* signal that we must leave */
1818 /* if no EOS yet, then we must flush */
1819 if (FALSE == finish) {
1820 e = apr_bucket_flush_create(c->bucket_alloc);
1821 APR_BRIGADE_INSERT_TAIL(bb, e);
1824 /* try send what we read */
1825 if (ap_pass_brigade(r->output_filters, bb) != APR_SUCCESS
1827 /* Ack! Phbtt! Die! User aborted! */
1831 /* make sure we always clean up after ourselves */
1832 apr_brigade_cleanup(bb);
1834 /* if we are done, leave */
1835 if (TRUE == finish) {
1839 ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, r->server,
1840 "proxy: FTP: end body send");
1844 ap_flush_conn(data);
1845 apr_socket_close(data_sock);
1846 ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, r->server,
1847 "proxy: FTP: data connection closed");
1850 /* Retrieve the final response for the RETR or LIST commands */
1851 rc = proxy_ftp_command(NULL, r, origin, bb, &ftpmessage);
1852 apr_brigade_cleanup(bb);
1855 * VII: Clean Up -------------
1857 * If there are no KeepAlives, or if the connection has been signalled to
1858 * close, close the socket and clean up
1862 rc = proxy_ftp_command("QUIT" CRLF,
1863 r, origin, bb, &ftpmessage);
1864 /* responses: 221, 500 */
1865 /* 221 Service closing control connection. */
1866 /* 500 Syntax error, command unrecognized. */
1867 ap_flush_conn(origin);
1868 proxy_ftp_cleanup(r, backend);
1870 apr_brigade_destroy(bb);
1874 static void ap_proxy_ftp_register_hook(apr_pool_t *p)
1877 proxy_hook_scheme_handler(proxy_ftp_handler, NULL, NULL, APR_HOOK_MIDDLE);
1878 proxy_hook_canon_handler(proxy_ftp_canon, NULL, NULL, APR_HOOK_MIDDLE);
1880 ap_register_output_filter("PROXY_SEND_DIR", proxy_send_dir_filter,
1881 NULL, AP_FTYPE_RESOURCE);
1884 module AP_MODULE_DECLARE_DATA proxy_ftp_module = {
1885 STANDARD20_MODULE_STUFF,
1886 NULL, /* create per-directory config structure */
1887 NULL, /* merge per-directory config structures */
1888 NULL, /* create per-server config structure */
1889 NULL, /* merge per-server config structures */
1890 NULL, /* command apr_table_t */
1891 ap_proxy_ftp_register_hook /* register hooks */