Moved apache code into a folder to help prepare for packaging where we dont want...
[httpd-crcsyncproxy.git] / apache / modules / proxy / mod_proxy_ftp.c
blob028d766db2d6a70243469dda1bc34780d18cda6c
1 /* Licensed to the Apache Software Foundation (ASF) under one or more
2 * contributor license agreements. See the NOTICE file distributed with
3 * this work for additional information regarding copyright ownership.
4 * The ASF licenses this file to You under the Apache License, Version 2.0
5 * (the "License"); you may not use this file except in compliance with
6 * the License. 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"
20 #if APR_HAVE_TIME_H
21 #include <time.h>
22 #endif
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
28 #endif
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
35 #define USE_MDTM
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)
45 int i, j, ch;
47 if (x[0] == '\0')
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 */
51 ch = x[i];
52 if (ch == '%' && apr_isxdigit(x[i + 1]) && apr_isxdigit(x[i + 2])) {
53 ch = ap_proxy_hex2c(&x[i + 1]);
54 i += 2;
56 x[j] = ch;
58 x[j] = '\0';
59 return j;
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(""));
72 char *d;
73 for (d = ret; *path; ++path) {
74 if (strchr(FTP_GLOBBING_CHARS, *path) != NULL)
75 *d++ = '\\';
76 *d++ = *path;
78 *d = '\0';
79 return ret;
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) {
91 if (*path == '\\')
92 ++path;
93 if (*path != '\0' && strchr(FTP_GLOBBING_CHARS, *path) != NULL)
94 return TRUE;
96 return FALSE;
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)
105 int i, ch = 0;
106 #if APR_CHARSET_EBCDIC
107 char buf[1];
108 #endif
110 for (i = 0; x[i] != '\0'; i++) {
111 ch = x[i];
112 if (ch == '%' && apr_isxdigit(x[i + 1]) && apr_isxdigit(x[i + 2])) {
113 ch = ap_proxy_hex2c(&x[i + 1]);
114 i += 2;
116 #if !APR_CHARSET_EBCDIC
117 if (ch == '\015' || ch == '\012' || (ch & 0x80))
118 #else /* APR_CHARSET_EBCDIC */
119 if (ch == '\r' || ch == '\n')
120 return 0;
121 buf[0] = ch;
122 ap_xlate_proto_to_ascii(buf, 1);
123 if (buf[0] & 0x80)
124 #endif /* APR_CHARSET_EBCDIC */
125 return 0;
127 return 1;
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;
137 const char *err;
138 apr_port_t port, def_port;
140 /* */
141 if (strncasecmp(url, "ftp:", 4) == 0) {
142 url += 4;
144 else {
145 return DECLINED;
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);
152 port = def_port;
153 err = ap_proxy_canon_netloc(p, &url, &user, &password, &host, &port);
154 if (err)
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, ';');
168 if (strp != NULL) {
169 *(strp++) = '\0';
170 parms = ap_proxy_canonenc(p, strp, strlen(strp), enc_parm, 0,
171 r->proxyreq);
172 if (parms == NULL)
173 return HTTP_BAD_REQUEST;
175 else
176 parms = "";
178 path = ap_proxy_canonenc(p, url, strlen(url), enc_path, 0, r->proxyreq);
179 if (path == NULL)
180 return HTTP_BAD_REQUEST;
181 if (!ftp_check_string(path))
182 return HTTP_BAD_REQUEST;
184 if (r->proxyreq && r->args != NULL) {
185 if (strp != NULL) {
186 strp = ap_proxy_canonenc(p, r->args, strlen(r->args), enc_parm, 1, r->proxyreq);
187 if (strp == NULL)
188 return HTTP_BAD_REQUEST;
189 parms = apr_pstrcat(p, parms, "?", strp, NULL);
191 else {
192 strp = ap_proxy_canonenc(p, r->args, strlen(r->args), enc_fpath, 1, r->proxyreq);
193 if (strp == NULL)
194 return HTTP_BAD_REQUEST;
195 path = apr_pstrcat(p, path, "?", strp, NULL);
197 r->args = NULL;
200 /* now, rebuild URL */
202 if (port != def_port)
203 apr_snprintf(sport, sizeof(sport), ":%d", port);
204 else
205 sport[0] = '\0';
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);
216 return OK;
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)
228 int status;
229 char response[MAX_LINE_LEN];
230 char buff[5];
231 char *mb = msgbuf, *me = &msgbuf[msglen];
232 apr_status_t rv;
233 int eos;
235 if (APR_SUCCESS != (rv = ap_proxy_string_read(ftp_ctrl, bb, response, sizeof(response), &eos))) {
236 return -1;
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] != '-'))
244 status = 0;
245 else
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);
252 buff[3] = ' ';
253 do {
254 if (APR_SUCCESS != (rv = ap_proxy_string_read(ftp_ctrl, bb, response, sizeof(response), &eos))) {
255 return -1;
257 mb = apr_cpystrn(mb, response + (' ' == response[0] ? 1 : 4), me - mb);
258 } while (memcmp(response, buff, 4) != 0);
261 return status;
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...! :)
273 typedef struct {
274 apr_bucket_brigade *in;
275 char buffer[MAX_STRING_LEN];
276 enum {
277 HEADER, BODY, FOOTER
278 } state;
279 } proxy_dir_ctx_t;
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);
292 apr_status_t rv;
294 register int n;
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;
302 if (!ctx) {
303 f->ctx = ctx = apr_pcalloc(p, sizeof(*ctx));
304 ctx->in = apr_brigade_create(p, c->bucket_alloc);
305 ctx->buffer[0] = 0;
306 ctx->state = HEADER;
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;
317 const char *escpath;
320 * In the reverse proxy case we need to construct our site string
321 * via ap_construct_url. For non anonymous sites apr_uri_unparse would
322 * only supply us with 'username@' which leads to the construction of
323 * an invalid base href later on. Losing the username part of the URL
324 * is no problem in the reverse proxy case as the browser sents the
325 * credentials anyway once entered.
327 if (r->proxyreq == PROXYREQ_REVERSE) {
328 site = ap_construct_url(p, "", r);
330 else {
331 /* Save "scheme://site" prefix without password */
332 site = apr_uri_unparse(p, &f->r->parsed_uri,
333 APR_URI_UNP_OMITPASSWORD |
334 APR_URI_UNP_OMITPATHINFO);
337 /* ... and path without query args */
338 path = apr_uri_unparse(p, &f->r->parsed_uri, APR_URI_UNP_OMITSITEPART | APR_URI_UNP_OMITQUERY);
340 /* If path began with /%2f, change the basedir */
341 if (strncasecmp(path, "/%2f", 4) == 0) {
342 basedir = "/%2f";
345 /* Strip off a type qualifier. It is ignored for dir listings */
346 if ((type = strstr(path, ";type=")) != NULL)
347 *type++ = '\0';
349 (void)decodeenc(path);
351 while (path[1] == '/') /* collapse multiple leading slashes to one */
352 ++path;
354 reldir = strrchr(path, '/');
355 if (reldir != NULL && ftp_check_globbingchars(reldir)) {
356 wildcard = &reldir[1];
357 reldir[0] = '\0'; /* strip off the wildcard suffix */
360 /* Copy path, strip (all except the last) trailing slashes */
361 /* (the trailing slash is needed for the dir component loop below) */
362 path = dir = apr_pstrcat(p, path, "/", NULL);
363 for (n = strlen(path); n > 1 && path[n - 1] == '/' && path[n - 2] == '/'; --n)
364 path[n - 1] = '\0';
366 /* Add a link to the root directory (if %2f hack was used) */
367 str = (basedir[0] != '\0') ? "<a href=\"/%2f/\">%2f</a>/" : "";
369 /* print "ftp://host/" */
370 escpath = ap_escape_html(p, path);
371 str = apr_psprintf(p, DOCTYPE_HTML_3_2
372 "<html>\n <head>\n <title>%s%s%s</title>\n"
373 "<base href=\"%s%s%s\">\n"
374 " </head>\n"
375 " <body>\n <h2>Directory of "
376 "<a href=\"/\">%s</a>/%s",
377 site, basedir, escpath, site, basedir, escpath, site, str);
379 APR_BRIGADE_INSERT_TAIL(out, apr_bucket_pool_create(str, strlen(str),
380 p, c->bucket_alloc));
382 for (dir = path+1; (dir = strchr(dir, '/')) != NULL; )
384 *dir = '\0';
385 if ((reldir = strrchr(path+1, '/'))==NULL) {
386 reldir = path+1;
388 else
389 ++reldir;
390 /* print "path/" component */
391 str = apr_psprintf(p, "<a href=\"%s%s/\">%s</a>/", basedir,
392 ap_escape_uri(p, path),
393 ap_escape_html(p, reldir));
394 *dir = '/';
395 while (*dir == '/')
396 ++dir;
397 APR_BRIGADE_INSERT_TAIL(out, apr_bucket_pool_create(str,
398 strlen(str), p,
399 c->bucket_alloc));
401 if (wildcard != NULL) {
402 wildcard = ap_escape_html(p, wildcard);
403 APR_BRIGADE_INSERT_TAIL(out, apr_bucket_pool_create(wildcard,
404 strlen(wildcard), p,
405 c->bucket_alloc));
408 /* If the caller has determined the current directory, and it differs */
409 /* from what the client requested, then show the real name */
410 if (pwd == NULL || strncmp(pwd, path, strlen(pwd)) == 0) {
411 str = apr_psprintf(p, "</h2>\n\n <hr />\n\n<pre>");
413 else {
414 str = apr_psprintf(p, "</h2>\n\n(%s)\n\n <hr />\n\n<pre>",
415 ap_escape_html(p, pwd));
417 APR_BRIGADE_INSERT_TAIL(out, apr_bucket_pool_create(str, strlen(str),
418 p, c->bucket_alloc));
420 /* print README */
421 if (readme) {
422 str = apr_psprintf(p, "%s\n</pre>\n\n<hr />\n\n<pre>\n",
423 ap_escape_html(p, readme));
425 APR_BRIGADE_INSERT_TAIL(out, apr_bucket_pool_create(str,
426 strlen(str), p,
427 c->bucket_alloc));
430 /* make sure page intro gets sent out */
431 APR_BRIGADE_INSERT_TAIL(out, apr_bucket_flush_create(c->bucket_alloc));
432 if (APR_SUCCESS != (rv = ap_pass_brigade(f->next, out))) {
433 return rv;
435 apr_brigade_cleanup(out);
437 ctx->state = BODY;
440 /* loop through each line of directory */
441 while (BODY == ctx->state) {
442 char *filename;
443 int found = 0;
444 int eos = 0;
446 ap_regex_t *re = NULL;
447 ap_regmatch_t re_result[LS_REG_MATCH];
449 /* Compile the output format of "ls -s1" as a fallback for non-unix ftp listings */
450 re = ap_pregcomp(p, LS_REG_PATTERN, AP_REG_EXTENDED);
451 ap_assert(re != NULL);
453 /* get a complete line */
454 /* if the buffer overruns - throw data away */
455 while (!found && !APR_BRIGADE_EMPTY(ctx->in)) {
456 char *pos, *response;
457 apr_size_t len, max;
458 apr_bucket *e;
460 e = APR_BRIGADE_FIRST(ctx->in);
461 if (APR_BUCKET_IS_EOS(e)) {
462 eos = 1;
463 break;
465 if (APR_SUCCESS != (rv = apr_bucket_read(e, (const char **)&response, &len, APR_BLOCK_READ))) {
466 return rv;
468 pos = memchr(response, APR_ASCII_LF, len);
469 if (pos != NULL) {
470 if ((response + len) != (pos + 1)) {
471 len = pos - response + 1;
472 apr_bucket_split(e, pos - response + 1);
474 found = 1;
476 max = sizeof(ctx->buffer) - strlen(ctx->buffer) - 1;
477 if (len > max) {
478 len = max;
481 /* len+1 to leave space for the trailing nil char */
482 apr_cpystrn(ctx->buffer+strlen(ctx->buffer), response, len+1);
484 APR_BUCKET_REMOVE(e);
485 apr_bucket_destroy(e);
488 /* EOS? jump to footer */
489 if (eos) {
490 ctx->state = FOOTER;
491 break;
494 /* not complete? leave and try get some more */
495 if (!found) {
496 return APR_SUCCESS;
500 apr_size_t n = strlen(ctx->buffer);
501 if (ctx->buffer[n-1] == CRLF[1]) /* strip trailing '\n' */
502 ctx->buffer[--n] = '\0';
503 if (ctx->buffer[n-1] == CRLF[0]) /* strip trailing '\r' if present */
504 ctx->buffer[--n] = '\0';
507 /* a symlink? */
508 if (ctx->buffer[0] == 'l' && (filename = strstr(ctx->buffer, " -> ")) != NULL) {
509 char *link_ptr = filename;
511 do {
512 filename--;
513 } while (filename[0] != ' ' && filename > ctx->buffer);
514 if (filename > ctx->buffer)
515 *(filename++) = '\0';
516 *(link_ptr++) = '\0';
517 str = apr_psprintf(p, "%s <a href=\"%s\">%s %s</a>\n",
518 ap_escape_html(p, ctx->buffer),
519 ap_escape_uri(p, filename),
520 ap_escape_html(p, filename),
521 ap_escape_html(p, link_ptr));
524 /* a directory/file? */
525 else if (ctx->buffer[0] == 'd' || ctx->buffer[0] == '-' || ctx->buffer[0] == 'l' || apr_isdigit(ctx->buffer[0])) {
526 int searchidx = 0;
527 char *searchptr = NULL;
528 int firstfile = 1;
529 if (apr_isdigit(ctx->buffer[0])) { /* handle DOS dir */
530 searchptr = strchr(ctx->buffer, '<');
531 if (searchptr != NULL)
532 *searchptr = '[';
533 searchptr = strchr(ctx->buffer, '>');
534 if (searchptr != NULL)
535 *searchptr = ']';
538 filename = strrchr(ctx->buffer, ' ');
539 if (filename == NULL) {
540 /* Line is broken. Ignore it. */
541 ap_log_error(APLOG_MARK, APLOG_WARNING, 0, r->server,
542 "proxy_ftp: could not parse line %s", ctx->buffer);
543 /* erase buffer for next time around */
544 ctx->buffer[0] = 0;
545 continue; /* while state is BODY */
547 *(filename++) = '\0';
549 /* handle filenames with spaces in 'em */
550 if (!strcmp(filename, ".") || !strcmp(filename, "..") || firstfile) {
551 firstfile = 0;
552 searchidx = filename - ctx->buffer;
554 else if (searchidx != 0 && ctx->buffer[searchidx] != 0) {
555 *(--filename) = ' ';
556 ctx->buffer[searchidx - 1] = '\0';
557 filename = &ctx->buffer[searchidx];
560 /* Append a slash to the HREF link for directories */
561 if (!strcmp(filename, ".") || !strcmp(filename, "..") || ctx->buffer[0] == 'd') {
562 str = apr_psprintf(p, "%s <a href=\"%s/\">%s</a>\n",
563 ap_escape_html(p, ctx->buffer),
564 ap_escape_uri(p, filename),
565 ap_escape_html(p, filename));
567 else {
568 str = apr_psprintf(p, "%s <a href=\"%s\">%s</a>\n",
569 ap_escape_html(p, ctx->buffer),
570 ap_escape_uri(p, filename),
571 ap_escape_html(p, filename));
574 /* Try a fallback for listings in the format of "ls -s1" */
575 else if (0 == ap_regexec(re, ctx->buffer, LS_REG_MATCH, re_result, 0)) {
577 filename = apr_pstrndup(p, &ctx->buffer[re_result[2].rm_so], re_result[2].rm_eo - re_result[2].rm_so);
579 str = apr_pstrcat(p, ap_escape_html(p, apr_pstrndup(p, ctx->buffer, re_result[2].rm_so)),
580 "<a href=\"", ap_escape_uri(p, filename), "\">",
581 ap_escape_html(p, filename), "</a>\n", NULL);
583 else {
584 strcat(ctx->buffer, "\n"); /* re-append the newline */
585 str = ap_escape_html(p, ctx->buffer);
588 /* erase buffer for next time around */
589 ctx->buffer[0] = 0;
591 APR_BRIGADE_INSERT_TAIL(out, apr_bucket_pool_create(str, strlen(str), p,
592 c->bucket_alloc));
593 APR_BRIGADE_INSERT_TAIL(out, apr_bucket_flush_create(c->bucket_alloc));
594 if (APR_SUCCESS != (rv = ap_pass_brigade(f->next, out))) {
595 return rv;
597 apr_brigade_cleanup(out);
601 if (FOOTER == ctx->state) {
602 str = apr_psprintf(p, "</pre>\n\n <hr />\n\n %s\n\n </body>\n</html>\n", ap_psignature("", r));
603 APR_BRIGADE_INSERT_TAIL(out, apr_bucket_pool_create(str, strlen(str), p,
604 c->bucket_alloc));
605 APR_BRIGADE_INSERT_TAIL(out, apr_bucket_flush_create(c->bucket_alloc));
606 APR_BRIGADE_INSERT_TAIL(out, apr_bucket_eos_create(c->bucket_alloc));
607 if (APR_SUCCESS != (rv = ap_pass_brigade(f->next, out))) {
608 return rv;
610 apr_brigade_destroy(out);
613 return APR_SUCCESS;
617 * Generic "send FTP command to server" routine, using the control socket.
618 * Returns the FTP returncode (3 digit code)
619 * Allows for tracing the FTP protocol (in LogLevel debug)
621 static int
622 proxy_ftp_command(const char *cmd, request_rec *r, conn_rec *ftp_ctrl,
623 apr_bucket_brigade *bb, char **pmessage)
625 char *crlf;
626 int rc;
627 char message[HUGE_STRING_LEN];
629 /* If cmd == NULL, we retrieve the next ftp response line */
630 if (cmd != NULL) {
631 conn_rec *c = r->connection;
632 APR_BRIGADE_INSERT_TAIL(bb, apr_bucket_pool_create(cmd, strlen(cmd), r->pool, c->bucket_alloc));
633 APR_BRIGADE_INSERT_TAIL(bb, apr_bucket_flush_create(c->bucket_alloc));
634 ap_pass_brigade(ftp_ctrl->output_filters, bb);
636 /* strip off the CRLF for logging */
637 apr_cpystrn(message, cmd, sizeof(message));
638 if ((crlf = strchr(message, '\r')) != NULL ||
639 (crlf = strchr(message, '\n')) != NULL)
640 *crlf = '\0';
641 if (strncmp(message,"PASS ", 5) == 0)
642 strcpy(&message[5], "****");
643 ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, r->server,
644 "proxy:>FTP: %s", message);
647 rc = ftp_getrc_msg(ftp_ctrl, bb, message, sizeof message);
648 if (rc == -1 || rc == 421)
649 strcpy(message,"<unable to read result>");
650 if ((crlf = strchr(message, '\r')) != NULL ||
651 (crlf = strchr(message, '\n')) != NULL)
652 *crlf = '\0';
653 ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, r->server,
654 "proxy:<FTP: %3.3u %s", rc, message);
656 if (pmessage != NULL)
657 *pmessage = apr_pstrdup(r->pool, message);
659 return rc;
662 /* Set ftp server to TYPE {A,I,E} before transfer of a directory or file */
663 static int ftp_set_TYPE(char xfer_type, request_rec *r, conn_rec *ftp_ctrl,
664 apr_bucket_brigade *bb, char **pmessage)
666 char old_type[2] = { 'A', '\0' }; /* After logon, mode is ASCII */
667 int ret = HTTP_OK;
668 int rc;
670 /* set desired type */
671 old_type[0] = xfer_type;
673 rc = proxy_ftp_command(apr_pstrcat(r->pool, "TYPE ", old_type, CRLF, NULL),
674 r, ftp_ctrl, bb, pmessage);
675 /* responses: 200, 421, 500, 501, 504, 530 */
676 /* 200 Command okay. */
677 /* 421 Service not available, closing control connection. */
678 /* 500 Syntax error, command unrecognized. */
679 /* 501 Syntax error in parameters or arguments. */
680 /* 504 Command not implemented for that parameter. */
681 /* 530 Not logged in. */
682 if (rc == -1 || rc == 421) {
683 ret = ap_proxyerror(r, HTTP_BAD_GATEWAY,
684 "Error reading from remote server");
686 else if (rc != 200 && rc != 504) {
687 ret = ap_proxyerror(r, HTTP_BAD_GATEWAY,
688 "Unable to set transfer type");
690 /* Allow not implemented */
691 else if (rc == 504)
692 /* ignore it silently */;
694 return ret;
698 /* Return the current directory which we have selected on the FTP server, or NULL */
699 static char *ftp_get_PWD(request_rec *r, conn_rec *ftp_ctrl, apr_bucket_brigade *bb)
701 char *cwd = NULL;
702 char *ftpmessage = NULL;
704 /* responses: 257, 500, 501, 502, 421, 550 */
705 /* 257 "<directory-name>" <commentary> */
706 /* 421 Service not available, closing control connection. */
707 /* 500 Syntax error, command unrecognized. */
708 /* 501 Syntax error in parameters or arguments. */
709 /* 502 Command not implemented. */
710 /* 550 Requested action not taken. */
711 switch (proxy_ftp_command("PWD" CRLF, r, ftp_ctrl, bb, &ftpmessage)) {
712 case -1:
713 case 421:
714 case 550:
715 ap_proxyerror(r, HTTP_BAD_GATEWAY,
716 "Failed to read PWD on ftp server");
717 break;
719 case 257: {
720 const char *dirp = ftpmessage;
721 cwd = ap_getword_conf(r->pool, &dirp);
724 return cwd;
728 /* Common routine for failed authorization (i.e., missing or wrong password)
729 * to an ftp service. This causes most browsers to retry the request
730 * with username and password (which was presumably queried from the user)
731 * supplied in the Authorization: header.
732 * Note that we "invent" a realm name which consists of the
733 * ftp://user@host part of the reqest (sans password -if supplied but invalid-)
735 static int ftp_unauthorized(request_rec *r, int log_it)
737 r->proxyreq = PROXYREQ_NONE;
739 * Log failed requests if they supplied a password (log username/password
740 * guessing attempts)
742 if (log_it)
743 ap_log_rerror(APLOG_MARK, APLOG_INFO, 0, r,
744 "proxy: missing or failed auth to %s",
745 apr_uri_unparse(r->pool,
746 &r->parsed_uri, APR_URI_UNP_OMITPATHINFO));
748 apr_table_setn(r->err_headers_out, "WWW-Authenticate",
749 apr_pstrcat(r->pool, "Basic realm=\"",
750 apr_uri_unparse(r->pool, &r->parsed_uri,
751 APR_URI_UNP_OMITPASSWORD | APR_URI_UNP_OMITPATHINFO),
752 "\"", NULL));
754 return HTTP_UNAUTHORIZED;
757 static
758 apr_status_t proxy_ftp_cleanup(request_rec *r, proxy_conn_rec *backend)
761 backend->close = 1;
762 ap_set_module_config(r->connection->conn_config, &proxy_ftp_module, NULL);
763 ap_proxy_release_connection("FTP", backend, r->server);
765 return OK;
768 static
769 int ftp_proxyerror(request_rec *r, proxy_conn_rec *conn, int statuscode, const char *message)
771 proxy_ftp_cleanup(r, conn);
772 return ap_proxyerror(r, statuscode, message);
775 * Handles direct access of ftp:// URLs
776 * Original (Non-PASV) version from
777 * Troy Morrison <spiffnet@zoom.com>
778 * PASV added by Chuck
779 * Filters by [Graham Leggett <minfrin@sharp.fm>]
781 static int proxy_ftp_handler(request_rec *r, proxy_worker *worker,
782 proxy_server_conf *conf, char *url,
783 const char *proxyhost, apr_port_t proxyport)
785 apr_pool_t *p = r->pool;
786 conn_rec *c = r->connection;
787 proxy_conn_rec *backend;
788 apr_socket_t *sock, *local_sock, *data_sock = NULL;
789 apr_sockaddr_t *connect_addr = NULL;
790 apr_status_t rv;
791 conn_rec *origin, *data = NULL;
792 apr_status_t err = APR_SUCCESS;
793 apr_status_t uerr = APR_SUCCESS;
794 apr_bucket_brigade *bb = apr_brigade_create(p, c->bucket_alloc);
795 char *buf, *connectname;
796 apr_port_t connectport;
797 char buffer[MAX_STRING_LEN];
798 char *ftpmessage = NULL;
799 char *path, *strp, *type_suffix, *cwd = NULL;
800 apr_uri_t uri;
801 char *user = NULL;
802 /* char *account = NULL; how to supply an account in a URL? */
803 const char *password = NULL;
804 int len, rc;
805 int one = 1;
806 char *size = NULL;
807 char xfer_type = 'A'; /* after ftp login, the default is ASCII */
808 int dirlisting = 0;
809 #if defined(USE_MDTM) && (defined(HAVE_TIMEGM) || defined(HAVE_GMTOFF))
810 apr_time_t mtime = 0L;
811 #endif
813 /* stuff for PASV mode */
814 int connect = 0, use_port = 0;
815 char dates[APR_RFC822_DATE_LEN];
816 int status;
817 apr_pool_t *address_pool;
819 /* is this for us? */
820 if (proxyhost) {
821 ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, r->server,
822 "proxy: FTP: declining URL %s - proxyhost %s specified:", url, proxyhost);
823 return DECLINED; /* proxy connections are via HTTP */
825 if (strncasecmp(url, "ftp:", 4)) {
826 ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, r->server,
827 "proxy: FTP: declining URL %s - not ftp:", url);
828 return DECLINED; /* only interested in FTP */
830 ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, r->server,
831 "proxy: FTP: serving URL %s", url);
835 * I: Who Do I Connect To? -----------------------
837 * Break up the URL to determine the host to connect to
840 /* we only support GET and HEAD */
841 if (r->method_number != M_GET)
842 return HTTP_NOT_IMPLEMENTED;
844 /* We break the URL into host, port, path-search */
845 if (r->parsed_uri.hostname == NULL) {
846 if (APR_SUCCESS != apr_uri_parse(p, url, &uri)) {
847 return ap_proxyerror(r, HTTP_BAD_REQUEST,
848 apr_psprintf(p, "URI cannot be parsed: %s", url));
850 connectname = uri.hostname;
851 connectport = uri.port;
852 path = apr_pstrdup(p, uri.path);
854 else {
855 connectname = r->parsed_uri.hostname;
856 connectport = r->parsed_uri.port;
857 path = apr_pstrdup(p, r->parsed_uri.path);
859 if (connectport == 0) {
860 connectport = apr_uri_port_of_scheme("ftp");
862 path = (path != NULL && path[0] != '\0') ? &path[1] : "";
864 type_suffix = strchr(path, ';');
865 if (type_suffix != NULL)
866 *(type_suffix++) = '\0';
868 if (type_suffix != NULL && strncmp(type_suffix, "type=", 5) == 0
869 && apr_isalpha(type_suffix[5])) {
870 /* "type=d" forces a dir listing.
871 * The other types (i|a|e) are directly used for the ftp TYPE command
873 if ( ! (dirlisting = (apr_tolower(type_suffix[5]) == 'd')))
874 xfer_type = apr_toupper(type_suffix[5]);
876 /* Check valid types, rather than ignoring invalid types silently: */
877 if (strchr("AEI", xfer_type) == NULL)
878 return ap_proxyerror(r, HTTP_BAD_REQUEST, apr_pstrcat(r->pool,
879 "ftp proxy supports only types 'a', 'i', or 'e': \"",
880 type_suffix, "\" is invalid.", NULL));
882 else {
883 /* make binary transfers the default */
884 xfer_type = 'I';
889 * The "Authorization:" header must be checked first. We allow the user
890 * to "override" the URL-coded user [ & password ] in the Browsers'
891 * User&Password Dialog. NOTE that this is only marginally more secure
892 * than having the password travel in plain as part of the URL, because
893 * Basic Auth simply uuencodes the plain text password. But chances are
894 * still smaller that the URL is logged regularly.
896 if ((password = apr_table_get(r->headers_in, "Authorization")) != NULL
897 && strcasecmp(ap_getword(r->pool, &password, ' '), "Basic") == 0
898 && (password = ap_pbase64decode(r->pool, password))[0] != ':') {
900 * Note that this allocation has to be made from r->connection->pool
901 * because it has the lifetime of the connection. The other
902 * allocations are temporary and can be tossed away any time.
904 user = ap_getword_nulls(r->connection->pool, &password, ':');
905 r->ap_auth_type = "Basic";
906 r->user = r->parsed_uri.user = user;
908 else if ((user = r->parsed_uri.user) != NULL) {
909 user = apr_pstrdup(p, user);
910 decodeenc(user);
911 if ((password = r->parsed_uri.password) != NULL) {
912 char *tmp = apr_pstrdup(p, password);
913 decodeenc(tmp);
914 password = tmp;
917 else {
918 user = "anonymous";
919 password = "apache-proxy@";
922 ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, r->server,
923 "proxy: FTP: connecting %s to %s:%d", url, connectname, connectport);
925 if (worker->is_address_reusable) {
926 if (!worker->cp->addr) {
927 if ((err = PROXY_THREAD_LOCK(worker)) != APR_SUCCESS) {
928 ap_log_error(APLOG_MARK, APLOG_ERR, err, r->server,
929 "proxy: FTP: lock");
930 return HTTP_INTERNAL_SERVER_ERROR;
933 connect_addr = worker->cp->addr;
934 address_pool = worker->cp->pool;
936 else
937 address_pool = r->pool;
939 /* do a DNS lookup for the destination host */
940 if (!connect_addr)
941 err = apr_sockaddr_info_get(&(connect_addr),
942 connectname, APR_UNSPEC,
943 connectport, 0,
944 address_pool);
945 if (worker->is_address_reusable && !worker->cp->addr) {
946 worker->cp->addr = connect_addr;
947 if ((uerr = PROXY_THREAD_UNLOCK(worker)) != APR_SUCCESS) {
948 ap_log_error(APLOG_MARK, APLOG_ERR, uerr, r->server,
949 "proxy: FTP: unlock");
953 * get all the possible IP addresses for the destname and loop through
954 * them until we get a successful connection
956 if (APR_SUCCESS != err) {
957 return ap_proxyerror(r, HTTP_BAD_GATEWAY, apr_pstrcat(p,
958 "DNS lookup failure for: ",
959 connectname, NULL));
962 /* check if ProxyBlock directive on this host */
963 if (OK != ap_proxy_checkproxyblock(r, conf, connect_addr)) {
964 return ap_proxyerror(r, HTTP_FORBIDDEN,
965 "Connect to remote machine blocked");
968 /* create space for state information */
969 backend = (proxy_conn_rec *) ap_get_module_config(c->conn_config, &proxy_ftp_module);
970 if (!backend) {
971 status = ap_proxy_acquire_connection("FTP", &backend, worker, r->server);
972 if (status != OK) {
973 if (backend) {
974 backend->close = 1;
975 ap_proxy_release_connection("FTP", backend, r->server);
977 return status;
979 /* TODO: see if ftp could use determine_connection */
980 backend->addr = connect_addr;
981 ap_set_module_config(c->conn_config, &proxy_ftp_module, backend);
986 * II: Make the Connection -----------------------
988 * We have determined who to connect to. Now make the connection.
992 if (ap_proxy_connect_backend("FTP", backend, worker, r->server)) {
993 ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, r->server,
994 "proxy: FTP: an error occurred creating a new connection to %pI (%s)",
995 connect_addr, connectname);
996 proxy_ftp_cleanup(r, backend);
997 return HTTP_SERVICE_UNAVAILABLE;
1000 if (!backend->connection) {
1001 status = ap_proxy_connection_create("FTP", backend, c, r->server);
1002 if (status != OK) {
1003 proxy_ftp_cleanup(r, backend);
1004 return status;
1008 /* Use old naming */
1009 origin = backend->connection;
1010 sock = backend->sock;
1012 ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, r->server,
1013 "proxy: FTP: control connection complete");
1017 * III: Send Control Request -------------------------
1019 * Log into the ftp server, send the username & password, change to the
1020 * correct directory...
1024 /* possible results: */
1025 /* 120 Service ready in nnn minutes. */
1026 /* 220 Service ready for new user. */
1027 /* 421 Service not available, closing control connection. */
1028 rc = proxy_ftp_command(NULL, r, origin, bb, &ftpmessage);
1029 if (rc == -1 || rc == 421) {
1030 return ftp_proxyerror(r, backend, HTTP_BAD_GATEWAY, "Error reading from remote server");
1032 if (rc == 120) {
1034 * RFC2616 states: 14.37 Retry-After
1036 * The Retry-After response-header field can be used with a 503 (Service
1037 * Unavailable) response to indicate how long the service is expected
1038 * to be unavailable to the requesting client. [...] The value of
1039 * this field can be either an HTTP-date or an integer number of
1040 * seconds (in decimal) after the time of the response. Retry-After
1041 * = "Retry-After" ":" ( HTTP-date | delta-seconds )
1043 char *secs_str = ftpmessage;
1044 time_t secs;
1046 /* Look for a number, preceded by whitespace */
1047 while (*secs_str)
1048 if ((secs_str==ftpmessage || apr_isspace(secs_str[-1])) &&
1049 apr_isdigit(secs_str[0]))
1050 break;
1051 if (*secs_str != '\0') {
1052 secs = atol(secs_str);
1053 apr_table_add(r->headers_out, "Retry-After",
1054 apr_psprintf(p, "%lu", (unsigned long)(60 * secs)));
1056 return ftp_proxyerror(r, backend, HTTP_SERVICE_UNAVAILABLE, ftpmessage);
1058 if (rc != 220) {
1059 return ftp_proxyerror(r, backend, HTTP_BAD_GATEWAY, ftpmessage);
1062 rc = proxy_ftp_command(apr_pstrcat(p, "USER ", user, CRLF, NULL),
1063 r, origin, bb, &ftpmessage);
1064 /* possible results; 230, 331, 332, 421, 500, 501, 530 */
1065 /* states: 1 - error, 2 - success; 3 - send password, 4,5 fail */
1066 /* 230 User logged in, proceed. */
1067 /* 331 User name okay, need password. */
1068 /* 332 Need account for login. */
1069 /* 421 Service not available, closing control connection. */
1070 /* 500 Syntax error, command unrecognized. */
1071 /* (This may include errors such as command line too long.) */
1072 /* 501 Syntax error in parameters or arguments. */
1073 /* 530 Not logged in. */
1074 if (rc == -1 || rc == 421) {
1075 return ftp_proxyerror(r, backend, HTTP_BAD_GATEWAY, "Error reading from remote server");
1077 if (rc == 530) {
1078 proxy_ftp_cleanup(r, backend);
1079 return ftp_unauthorized(r, 1); /* log it: user name guessing
1080 * attempt? */
1082 if (rc != 230 && rc != 331) {
1083 return ftp_proxyerror(r, backend, HTTP_BAD_GATEWAY, ftpmessage);
1086 if (rc == 331) { /* send password */
1087 if (password == NULL) {
1088 proxy_ftp_cleanup(r, backend);
1089 return ftp_unauthorized(r, 0);
1092 rc = proxy_ftp_command(apr_pstrcat(p, "PASS ", password, CRLF, NULL),
1093 r, origin, bb, &ftpmessage);
1094 /* possible results 202, 230, 332, 421, 500, 501, 503, 530 */
1095 /* 230 User logged in, proceed. */
1096 /* 332 Need account for login. */
1097 /* 421 Service not available, closing control connection. */
1098 /* 500 Syntax error, command unrecognized. */
1099 /* 501 Syntax error in parameters or arguments. */
1100 /* 503 Bad sequence of commands. */
1101 /* 530 Not logged in. */
1102 if (rc == -1 || rc == 421) {
1103 return ftp_proxyerror(r, backend, HTTP_BAD_GATEWAY,
1104 "Error reading from remote server");
1106 if (rc == 332) {
1107 return ftp_proxyerror(r, backend, HTTP_UNAUTHORIZED,
1108 apr_pstrcat(p, "Need account for login: ", ftpmessage, NULL));
1110 /* @@@ questionable -- we might as well return a 403 Forbidden here */
1111 if (rc == 530) {
1112 proxy_ftp_cleanup(r, backend);
1113 return ftp_unauthorized(r, 1); /* log it: passwd guessing
1114 * attempt? */
1116 if (rc != 230 && rc != 202) {
1117 return ftp_proxyerror(r, backend, HTTP_BAD_GATEWAY, ftpmessage);
1120 apr_table_set(r->notes, "Directory-README", ftpmessage);
1123 /* Special handling for leading "%2f": this enforces a "cwd /"
1124 * out of the $HOME directory which was the starting point after login
1126 if (strncasecmp(path, "%2f", 3) == 0) {
1127 path += 3;
1128 while (*path == '/') /* skip leading '/' (after root %2f) */
1129 ++path;
1131 rc = proxy_ftp_command("CWD /" CRLF, r, origin, bb, &ftpmessage);
1132 if (rc == -1 || rc == 421)
1133 return ftp_proxyerror(r, backend, HTTP_BAD_GATEWAY,
1134 "Error reading from remote server");
1138 * set the directory (walk directory component by component): this is
1139 * what we must do if we don't know the OS type of the remote machine
1141 for (;;) {
1142 strp = strchr(path, '/');
1143 if (strp == NULL)
1144 break;
1145 *strp = '\0';
1147 len = decodeenc(path); /* Note! This decodes a %2f -> "/" */
1149 if (strchr(path, '/')) { /* are there now any '/' characters? */
1150 return ftp_proxyerror(r, backend, HTTP_BAD_REQUEST,
1151 "Use of /%2f is only allowed at the base directory");
1154 /* NOTE: FTP servers do globbing on the path.
1155 * So we need to escape the URI metacharacters.
1156 * We use a special glob-escaping routine to escape globbing chars.
1157 * We could also have extended gen_test_char.c with a special T_ESCAPE_FTP_PATH
1159 rc = proxy_ftp_command(apr_pstrcat(p, "CWD ",
1160 ftp_escape_globbingchars(p, path), CRLF, NULL),
1161 r, origin, bb, &ftpmessage);
1162 *strp = '/';
1163 /* responses: 250, 421, 500, 501, 502, 530, 550 */
1164 /* 250 Requested file action okay, completed. */
1165 /* 421 Service not available, closing control connection. */
1166 /* 500 Syntax error, command unrecognized. */
1167 /* 501 Syntax error in parameters or arguments. */
1168 /* 502 Command not implemented. */
1169 /* 530 Not logged in. */
1170 /* 550 Requested action not taken. */
1171 if (rc == -1 || rc == 421) {
1172 return ftp_proxyerror(r, backend, HTTP_BAD_GATEWAY,
1173 "Error reading from remote server");
1175 if (rc == 550) {
1176 return ftp_proxyerror(r, backend, HTTP_NOT_FOUND, ftpmessage);
1178 if (rc != 250) {
1179 return ftp_proxyerror(r, backend, HTTP_BAD_GATEWAY, ftpmessage);
1182 path = strp + 1;
1186 * IV: Make Data Connection? -------------------------
1188 * Try EPSV, if that fails... try PASV, if that fails... try PORT.
1190 /* this temporarily switches off EPSV/PASV */
1191 /*goto bypass;*/
1193 /* set up data connection - EPSV */
1195 apr_sockaddr_t *data_addr;
1196 char *data_ip;
1197 apr_port_t data_port;
1200 * The EPSV command replaces PASV where both IPV4 and IPV6 is
1201 * supported. Only the port is returned, the IP address is always the
1202 * same as that on the control connection. Example: Entering Extended
1203 * Passive Mode (|||6446|)
1205 rc = proxy_ftp_command("EPSV" CRLF,
1206 r, origin, bb, &ftpmessage);
1207 /* possible results: 227, 421, 500, 501, 502, 530 */
1208 /* 227 Entering Passive Mode (h1,h2,h3,h4,p1,p2). */
1209 /* 421 Service not available, closing control connection. */
1210 /* 500 Syntax error, command unrecognized. */
1211 /* 501 Syntax error in parameters or arguments. */
1212 /* 502 Command not implemented. */
1213 /* 530 Not logged in. */
1214 if (rc == -1 || rc == 421) {
1215 return ftp_proxyerror(r, backend, HTTP_BAD_GATEWAY,
1216 "Error reading from remote server");
1218 if (rc != 229 && rc != 500 && rc != 501 && rc != 502) {
1219 return ftp_proxyerror(r, backend, HTTP_BAD_GATEWAY, ftpmessage);
1221 else if (rc == 229) {
1222 char *pstr;
1223 char *tok_cntx;
1225 pstr = ftpmessage;
1226 pstr = apr_strtok(pstr, " ", &tok_cntx); /* separate result code */
1227 if (pstr != NULL) {
1228 if (*(pstr + strlen(pstr) + 1) == '=') {
1229 pstr += strlen(pstr) + 2;
1231 else {
1232 pstr = apr_strtok(NULL, "(", &tok_cntx); /* separate address &
1233 * port params */
1234 if (pstr != NULL)
1235 pstr = apr_strtok(NULL, ")", &tok_cntx);
1239 if (pstr) {
1240 apr_sockaddr_t *epsv_addr;
1241 data_port = atoi(pstr + 3);
1243 ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, r->server,
1244 "proxy: FTP: EPSV contacting remote host on port %d",
1245 data_port);
1247 if ((rv = apr_socket_create(&data_sock, connect_addr->family, SOCK_STREAM, 0, r->pool)) != APR_SUCCESS) {
1248 ap_log_rerror(APLOG_MARK, APLOG_ERR, rv, r,
1249 "proxy: FTP: error creating EPSV socket");
1250 proxy_ftp_cleanup(r, backend);
1251 return HTTP_INTERNAL_SERVER_ERROR;
1254 #if !defined (TPF) && !defined(BEOS)
1255 if (conf->recv_buffer_size > 0
1256 && (rv = apr_socket_opt_set(data_sock, APR_SO_RCVBUF,
1257 conf->recv_buffer_size))) {
1258 ap_log_rerror(APLOG_MARK, APLOG_ERR, rv, r,
1259 "proxy: FTP: apr_socket_opt_set(SO_RCVBUF): Failed to set ProxyReceiveBufferSize, using default");
1261 #endif
1263 rv = apr_socket_opt_set(data_sock, APR_TCP_NODELAY, 1);
1264 if (rv != APR_SUCCESS && rv != APR_ENOTIMPL) {
1265 ap_log_rerror(APLOG_MARK, APLOG_ERR, rv, r,
1266 "apr_socket_opt_set(APR_TCP_NODELAY): Failed to set");
1269 /* make the connection */
1270 apr_socket_addr_get(&data_addr, APR_REMOTE, sock);
1271 apr_sockaddr_ip_get(&data_ip, data_addr);
1272 apr_sockaddr_info_get(&epsv_addr, data_ip, connect_addr->family, data_port, 0, p);
1273 rv = apr_socket_connect(data_sock, epsv_addr);
1274 if (rv != APR_SUCCESS) {
1275 ap_log_error(APLOG_MARK, APLOG_ERR, rv, r->server,
1276 "proxy: FTP: EPSV attempt to connect to %pI failed - Firewall/NAT?", epsv_addr);
1277 return ftp_proxyerror(r, backend, HTTP_BAD_GATEWAY, apr_psprintf(r->pool,
1278 "EPSV attempt to connect to %pI failed - firewall/NAT?", epsv_addr));
1280 else {
1281 connect = 1;
1284 else {
1285 /* and try the regular way */
1286 apr_socket_close(data_sock);
1291 /* set up data connection - PASV */
1292 if (!connect) {
1293 rc = proxy_ftp_command("PASV" CRLF,
1294 r, origin, bb, &ftpmessage);
1295 /* possible results: 227, 421, 500, 501, 502, 530 */
1296 /* 227 Entering Passive Mode (h1,h2,h3,h4,p1,p2). */
1297 /* 421 Service not available, closing control connection. */
1298 /* 500 Syntax error, command unrecognized. */
1299 /* 501 Syntax error in parameters or arguments. */
1300 /* 502 Command not implemented. */
1301 /* 530 Not logged in. */
1302 if (rc == -1 || rc == 421) {
1303 return ftp_proxyerror(r, backend, HTTP_BAD_GATEWAY,
1304 "Error reading from remote server");
1306 if (rc != 227 && rc != 502) {
1307 return ftp_proxyerror(r, backend, HTTP_BAD_GATEWAY, ftpmessage);
1309 else if (rc == 227) {
1310 unsigned int h0, h1, h2, h3, p0, p1;
1311 char *pstr;
1312 char *tok_cntx;
1314 /* FIXME: Check PASV against RFC1123 */
1316 pstr = ftpmessage;
1317 pstr = apr_strtok(pstr, " ", &tok_cntx); /* separate result code */
1318 if (pstr != NULL) {
1319 if (*(pstr + strlen(pstr) + 1) == '=') {
1320 pstr += strlen(pstr) + 2;
1322 else {
1323 pstr = apr_strtok(NULL, "(", &tok_cntx); /* separate address &
1324 * port params */
1325 if (pstr != NULL)
1326 pstr = apr_strtok(NULL, ")", &tok_cntx);
1330 /* FIXME: Only supports IPV4 - fix in RFC2428 */
1332 if (pstr != NULL && (sscanf(pstr,
1333 "%d,%d,%d,%d,%d,%d", &h3, &h2, &h1, &h0, &p1, &p0) == 6)) {
1335 apr_sockaddr_t *pasv_addr;
1336 apr_port_t pasvport = (p1 << 8) + p0;
1337 ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, r->server,
1338 "proxy: FTP: PASV contacting host %d.%d.%d.%d:%d",
1339 h3, h2, h1, h0, pasvport);
1341 if ((rv = apr_socket_create(&data_sock, connect_addr->family, SOCK_STREAM, 0, r->pool)) != APR_SUCCESS) {
1342 ap_log_rerror(APLOG_MARK, APLOG_ERR, rv, r,
1343 "proxy: error creating PASV socket");
1344 proxy_ftp_cleanup(r, backend);
1345 return HTTP_INTERNAL_SERVER_ERROR;
1348 #if !defined (TPF) && !defined(BEOS)
1349 if (conf->recv_buffer_size > 0
1350 && (rv = apr_socket_opt_set(data_sock, APR_SO_RCVBUF,
1351 conf->recv_buffer_size))) {
1352 ap_log_rerror(APLOG_MARK, APLOG_ERR, rv, r,
1353 "proxy: FTP: apr_socket_opt_set(SO_RCVBUF): Failed to set ProxyReceiveBufferSize, using default");
1355 #endif
1357 rv = apr_socket_opt_set(data_sock, APR_TCP_NODELAY, 1);
1358 if (rv != APR_SUCCESS && rv != APR_ENOTIMPL) {
1359 ap_log_rerror(APLOG_MARK, APLOG_ERR, rv, r,
1360 "apr_socket_opt_set(APR_TCP_NODELAY): Failed to set");
1363 /* make the connection */
1364 apr_sockaddr_info_get(&pasv_addr, apr_psprintf(p, "%d.%d.%d.%d", h3, h2, h1, h0), connect_addr->family, pasvport, 0, p);
1365 rv = apr_socket_connect(data_sock, pasv_addr);
1366 if (rv != APR_SUCCESS) {
1367 ap_log_error(APLOG_MARK, APLOG_ERR, rv, r->server,
1368 "proxy: FTP: PASV attempt to connect to %pI failed - Firewall/NAT?", pasv_addr);
1369 return ftp_proxyerror(r, backend, HTTP_BAD_GATEWAY, apr_psprintf(r->pool,
1370 "PASV attempt to connect to %pI failed - firewall/NAT?", pasv_addr));
1372 else {
1373 connect = 1;
1376 else {
1377 /* and try the regular way */
1378 apr_socket_close(data_sock);
1382 /*bypass:*/
1384 /* set up data connection - PORT */
1385 if (!connect) {
1386 apr_sockaddr_t *local_addr;
1387 char *local_ip;
1388 apr_port_t local_port;
1389 unsigned int h0, h1, h2, h3, p0, p1;
1391 if ((rv = apr_socket_create(&local_sock, connect_addr->family, SOCK_STREAM, 0, r->pool)) != APR_SUCCESS) {
1392 ap_log_rerror(APLOG_MARK, APLOG_ERR, rv, r,
1393 "proxy: FTP: error creating local socket");
1394 proxy_ftp_cleanup(r, backend);
1395 return HTTP_INTERNAL_SERVER_ERROR;
1397 apr_socket_addr_get(&local_addr, APR_LOCAL, sock);
1398 local_port = local_addr->port;
1399 apr_sockaddr_ip_get(&local_ip, local_addr);
1401 if ((rv = apr_socket_opt_set(local_sock, APR_SO_REUSEADDR, one))
1402 != APR_SUCCESS) {
1403 #ifndef _OSD_POSIX /* BS2000 has this option "always on" */
1404 ap_log_rerror(APLOG_MARK, APLOG_ERR, rv, r,
1405 "proxy: FTP: error setting reuseaddr option");
1406 proxy_ftp_cleanup(r, backend);
1407 return HTTP_INTERNAL_SERVER_ERROR;
1408 #endif /* _OSD_POSIX */
1411 apr_sockaddr_info_get(&local_addr, local_ip, APR_UNSPEC, local_port, 0, r->pool);
1413 if ((rv = apr_socket_bind(local_sock, local_addr)) != APR_SUCCESS) {
1414 ap_log_rerror(APLOG_MARK, APLOG_ERR, rv, r,
1415 "proxy: FTP: error binding to ftp data socket %pI", local_addr);
1416 proxy_ftp_cleanup(r, backend);
1417 return HTTP_INTERNAL_SERVER_ERROR;
1420 /* only need a short queue */
1421 if ((rv = apr_socket_listen(local_sock, 2)) != APR_SUCCESS) {
1422 ap_log_rerror(APLOG_MARK, APLOG_ERR, rv, r,
1423 "proxy: FTP: error listening to ftp data socket %pI", local_addr);
1424 proxy_ftp_cleanup(r, backend);
1425 return HTTP_INTERNAL_SERVER_ERROR;
1428 /* FIXME: Sent PORT here */
1430 if (local_ip && (sscanf(local_ip,
1431 "%d.%d.%d.%d", &h3, &h2, &h1, &h0) == 4)) {
1432 p1 = (local_port >> 8);
1433 p0 = (local_port & 0xFF);
1435 rc = proxy_ftp_command(apr_psprintf(p, "PORT %d,%d,%d,%d,%d,%d" CRLF, h3, h2, h1, h0, p1, p0),
1436 r, origin, bb, &ftpmessage);
1437 /* possible results: 200, 421, 500, 501, 502, 530 */
1438 /* 200 Command okay. */
1439 /* 421 Service not available, closing control connection. */
1440 /* 500 Syntax error, command unrecognized. */
1441 /* 501 Syntax error in parameters or arguments. */
1442 /* 502 Command not implemented. */
1443 /* 530 Not logged in. */
1444 if (rc == -1 || rc == 421) {
1445 return ftp_proxyerror(r, backend, HTTP_BAD_GATEWAY,
1446 "Error reading from remote server");
1448 if (rc != 200) {
1449 return ftp_proxyerror(r, backend, HTTP_BAD_GATEWAY, buffer);
1452 /* signal that we must use the EPRT/PORT loop */
1453 use_port = 1;
1455 else {
1456 /* IPV6 FIXME:
1457 * The EPRT command replaces PORT where both IPV4 and IPV6 is supported. The first
1458 * number (1,2) indicates the protocol type. Examples:
1459 * EPRT |1|132.235.1.2|6275|
1460 * EPRT |2|1080::8:800:200C:417A|5282|
1462 return ftp_proxyerror(r, backend, HTTP_NOT_IMPLEMENTED,
1463 "Connect to IPV6 ftp server using EPRT not supported. Enable EPSV.");
1469 * V: Set The Headers -------------------
1471 * Get the size of the request, set up the environment for HTTP.
1474 /* set request; "path" holds last path component */
1475 len = decodeenc(path);
1477 if (strchr(path, '/')) { /* are there now any '/' characters? */
1478 return ftp_proxyerror(r, backend, HTTP_BAD_REQUEST,
1479 "Use of /%2f is only allowed at the base directory");
1482 /* If len == 0 then it must be a directory (you can't RETR nothing)
1483 * Also, don't allow to RETR by wildcard. Instead, create a dirlisting
1485 if (len == 0 || ftp_check_globbingchars(path)) {
1486 dirlisting = 1;
1488 else {
1489 /* (from FreeBSD ftpd):
1490 * SIZE is not in RFC959, but Postel has blessed it and
1491 * it will be in the updated RFC.
1493 * Return size of file in a format suitable for
1494 * using with RESTART (we just count bytes).
1496 /* from draft-ietf-ftpext-mlst-14.txt:
1497 * This value will
1498 * change depending on the current STRUcture, MODE and TYPE of the data
1499 * connection, or a data connection which would be created were one
1500 * created now. Thus, the result of the SIZE command is dependent on
1501 * the currently established STRU, MODE and TYPE parameters.
1503 /* Therefore: switch to binary if the user did not specify ";type=a" */
1504 ftp_set_TYPE(xfer_type, r, origin, bb, &ftpmessage);
1505 rc = proxy_ftp_command(apr_pstrcat(p, "SIZE ",
1506 ftp_escape_globbingchars(p, path), CRLF, NULL),
1507 r, origin, bb, &ftpmessage);
1508 if (rc == -1 || rc == 421) {
1509 return ftp_proxyerror(r, backend, HTTP_BAD_GATEWAY,
1510 "Error reading from remote server");
1512 else if (rc == 213) {/* Size command ok */
1513 int j;
1514 for (j = 0; apr_isdigit(ftpmessage[j]); j++)
1516 ftpmessage[j] = '\0';
1517 if (ftpmessage[0] != '\0')
1518 size = ftpmessage; /* already pstrdup'ed: no copy necessary */
1520 else if (rc == 550) { /* Not a regular file */
1521 ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, r->server,
1522 "proxy: FTP: SIZE shows this is a directory");
1523 dirlisting = 1;
1524 rc = proxy_ftp_command(apr_pstrcat(p, "CWD ",
1525 ftp_escape_globbingchars(p, path), CRLF, NULL),
1526 r, origin, bb, &ftpmessage);
1527 /* possible results: 250, 421, 500, 501, 502, 530, 550 */
1528 /* 250 Requested file action okay, completed. */
1529 /* 421 Service not available, closing control connection. */
1530 /* 500 Syntax error, command unrecognized. */
1531 /* 501 Syntax error in parameters or arguments. */
1532 /* 502 Command not implemented. */
1533 /* 530 Not logged in. */
1534 /* 550 Requested action not taken. */
1535 if (rc == -1 || rc == 421) {
1536 return ftp_proxyerror(r, backend, HTTP_BAD_GATEWAY,
1537 "Error reading from remote server");
1539 if (rc == 550) {
1540 return ftp_proxyerror(r, backend, HTTP_NOT_FOUND, ftpmessage);
1542 if (rc != 250) {
1543 return ftp_proxyerror(r, backend, HTTP_BAD_GATEWAY, ftpmessage);
1545 path = "";
1546 len = 0;
1550 cwd = ftp_get_PWD(r, origin, bb);
1551 if (cwd != NULL) {
1552 apr_table_set(r->notes, "Directory-PWD", cwd);
1555 if (dirlisting) {
1556 ftp_set_TYPE('A', r, origin, bb, NULL);
1557 /* If the current directory contains no slash, we are talking to
1558 * a non-unix ftp system. Try LIST instead of "LIST -lag", it
1559 * should return a long listing anyway (unlike NLST).
1560 * Some exotic FTP servers might choke on the "-lag" switch.
1562 /* Note that we do not escape the path here, to allow for
1563 * queries like: ftp://user@host/apache/src/server/http_*.c
1565 if (len != 0)
1566 buf = apr_pstrcat(p, "LIST ", path, CRLF, NULL);
1567 else if (cwd == NULL || strchr(cwd, '/') != NULL)
1568 buf = apr_pstrcat(p, "LIST -lag", CRLF, NULL);
1569 else
1570 buf = "LIST" CRLF;
1572 else {
1573 /* switch to binary if the user did not specify ";type=a" */
1574 ftp_set_TYPE(xfer_type, r, origin, bb, &ftpmessage);
1575 #if defined(USE_MDTM) && (defined(HAVE_TIMEGM) || defined(HAVE_GMTOFF))
1576 /* from draft-ietf-ftpext-mlst-14.txt:
1577 * The FTP command, MODIFICATION TIME (MDTM), can be used to determine
1578 * when a file in the server NVFS was last modified. <..>
1579 * The syntax of a time value is:
1580 * time-val = 14DIGIT [ "." 1*DIGIT ] <..>
1581 * Symbolically, a time-val may be viewed as
1582 * YYYYMMDDHHMMSS.sss
1583 * The "." and subsequent digits ("sss") are optional. <..>
1584 * Time values are always represented in UTC (GMT)
1586 rc = proxy_ftp_command(apr_pstrcat(p, "MDTM ", ftp_escape_globbingchars(p, path), CRLF, NULL),
1587 r, origin, bb, &ftpmessage);
1588 /* then extract the Last-Modified time from it (YYYYMMDDhhmmss or YYYYMMDDhhmmss.xxx GMT). */
1589 if (rc == 213) {
1590 struct {
1591 char YYYY[4+1];
1592 char MM[2+1];
1593 char DD[2+1];
1594 char hh[2+1];
1595 char mm[2+1];
1596 char ss[2+1];
1597 } time_val;
1598 if (6 == sscanf(ftpmessage, "%4[0-9]%2[0-9]%2[0-9]%2[0-9]%2[0-9]%2[0-9]",
1599 time_val.YYYY, time_val.MM, time_val.DD, time_val.hh, time_val.mm, time_val.ss)) {
1600 struct tm tms;
1601 memset (&tms, '\0', sizeof tms);
1602 tms.tm_year = atoi(time_val.YYYY) - 1900;
1603 tms.tm_mon = atoi(time_val.MM) - 1;
1604 tms.tm_mday = atoi(time_val.DD);
1605 tms.tm_hour = atoi(time_val.hh);
1606 tms.tm_min = atoi(time_val.mm);
1607 tms.tm_sec = atoi(time_val.ss);
1608 #ifdef HAVE_TIMEGM /* Does system have timegm()? */
1609 mtime = timegm(&tms);
1610 mtime *= APR_USEC_PER_SEC;
1611 #elif HAVE_GMTOFF /* does struct tm have a member tm_gmtoff? */
1612 /* mktime will subtract the local timezone, which is not what we want.
1613 * Add it again because the MDTM string is GMT
1615 mtime = mktime(&tms);
1616 mtime += tms.tm_gmtoff;
1617 mtime *= APR_USEC_PER_SEC;
1618 #else
1619 mtime = 0L;
1620 #endif
1623 #endif /* USE_MDTM */
1624 /* FIXME: Handle range requests - send REST */
1625 buf = apr_pstrcat(p, "RETR ", ftp_escape_globbingchars(p, path), CRLF, NULL);
1627 rc = proxy_ftp_command(buf, r, origin, bb, &ftpmessage);
1628 /* rc is an intermediate response for the LIST or RETR commands */
1631 * RETR: 110, 125, 150, 226, 250, 421, 425, 426, 450, 451, 500, 501, 530,
1632 * 550 NLST: 125, 150, 226, 250, 421, 425, 426, 450, 451, 500, 501, 502,
1633 * 530
1635 /* 110 Restart marker reply. */
1636 /* 125 Data connection already open; transfer starting. */
1637 /* 150 File status okay; about to open data connection. */
1638 /* 226 Closing data connection. */
1639 /* 250 Requested file action okay, completed. */
1640 /* 421 Service not available, closing control connection. */
1641 /* 425 Can't open data connection. */
1642 /* 426 Connection closed; transfer aborted. */
1643 /* 450 Requested file action not taken. */
1644 /* 451 Requested action aborted. Local error in processing. */
1645 /* 500 Syntax error, command unrecognized. */
1646 /* 501 Syntax error in parameters or arguments. */
1647 /* 530 Not logged in. */
1648 /* 550 Requested action not taken. */
1649 if (rc == -1 || rc == 421) {
1650 return ftp_proxyerror(r, backend, HTTP_BAD_GATEWAY,
1651 "Error reading from remote server");
1653 if (rc == 550) {
1654 ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, r->server,
1655 "proxy: FTP: RETR failed, trying LIST instead");
1657 /* Directory Listings should always be fetched in ASCII mode */
1658 dirlisting = 1;
1659 ftp_set_TYPE('A', r, origin, bb, NULL);
1661 rc = proxy_ftp_command(apr_pstrcat(p, "CWD ",
1662 ftp_escape_globbingchars(p, path), CRLF, NULL),
1663 r, origin, bb, &ftpmessage);
1664 /* possible results: 250, 421, 500, 501, 502, 530, 550 */
1665 /* 250 Requested file action okay, completed. */
1666 /* 421 Service not available, closing control connection. */
1667 /* 500 Syntax error, command unrecognized. */
1668 /* 501 Syntax error in parameters or arguments. */
1669 /* 502 Command not implemented. */
1670 /* 530 Not logged in. */
1671 /* 550 Requested action not taken. */
1672 if (rc == -1 || rc == 421) {
1673 return ftp_proxyerror(r, backend, HTTP_BAD_GATEWAY,
1674 "Error reading from remote server");
1676 if (rc == 550) {
1677 return ftp_proxyerror(r, backend, HTTP_NOT_FOUND, ftpmessage);
1679 if (rc != 250) {
1680 return ftp_proxyerror(r, backend, HTTP_BAD_GATEWAY, ftpmessage);
1683 /* Update current directory after CWD */
1684 cwd = ftp_get_PWD(r, origin, bb);
1685 if (cwd != NULL) {
1686 apr_table_set(r->notes, "Directory-PWD", cwd);
1689 /* See above for the "LIST" vs. "LIST -lag" discussion. */
1690 rc = proxy_ftp_command((cwd == NULL || strchr(cwd, '/') != NULL)
1691 ? "LIST -lag" CRLF : "LIST" CRLF,
1692 r, origin, bb, &ftpmessage);
1694 /* rc is an intermediate response for the LIST command (125 transfer starting, 150 opening data connection) */
1695 if (rc == -1 || rc == 421)
1696 return ftp_proxyerror(r, backend, HTTP_BAD_GATEWAY,
1697 "Error reading from remote server");
1699 if (rc != 125 && rc != 150 && rc != 226 && rc != 250) {
1700 return ftp_proxyerror(r, backend, HTTP_BAD_GATEWAY, ftpmessage);
1703 r->status = HTTP_OK;
1704 r->status_line = "200 OK";
1706 apr_rfc822_date(dates, r->request_time);
1707 apr_table_setn(r->headers_out, "Date", dates);
1708 apr_table_setn(r->headers_out, "Server", ap_get_server_banner());
1710 /* set content-type */
1711 if (dirlisting) {
1712 proxy_dir_conf *dconf = ap_get_module_config(r->per_dir_config,
1713 &proxy_module);
1715 ap_set_content_type(r, apr_pstrcat(p, "text/html;charset=",
1716 dconf->ftp_directory_charset ?
1717 dconf->ftp_directory_charset :
1718 "ISO-8859-1", NULL));
1720 else {
1721 if (xfer_type != 'A' && size != NULL) {
1722 /* We "trust" the ftp server to really serve (size) bytes... */
1723 apr_table_setn(r->headers_out, "Content-Length", size);
1724 ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, r->server,
1725 "proxy: FTP: Content-Length set to %s", size);
1728 if (r->content_type) {
1729 apr_table_setn(r->headers_out, "Content-Type", r->content_type);
1730 ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, r->server,
1731 "proxy: FTP: Content-Type set to %s", r->content_type);
1734 #if defined(USE_MDTM) && (defined(HAVE_TIMEGM) || defined(HAVE_GMTOFF))
1735 if (mtime != 0L) {
1736 char datestr[APR_RFC822_DATE_LEN];
1737 apr_rfc822_date(datestr, mtime);
1738 apr_table_set(r->headers_out, "Last-Modified", datestr);
1739 ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, r->server,
1740 "proxy: FTP: Last-Modified set to %s", datestr);
1742 #endif /* USE_MDTM */
1744 /* If an encoding has been set by mistake, delete it.
1745 * @@@ FIXME (e.g., for ftp://user@host/file*.tar.gz,
1746 * @@@ the encoding is currently set to x-gzip)
1748 if (dirlisting && r->content_encoding != NULL)
1749 r->content_encoding = NULL;
1751 /* set content-encoding (not for dir listings, they are uncompressed)*/
1752 if (r->content_encoding != NULL && r->content_encoding[0] != '\0') {
1753 ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, r->server,
1754 "proxy: FTP: Content-Encoding set to %s", r->content_encoding);
1755 apr_table_setn(r->headers_out, "Content-Encoding", r->content_encoding);
1758 /* wait for connection */
1759 if (use_port) {
1760 for (;;) {
1761 rv = apr_socket_accept(&data_sock, local_sock, r->pool);
1762 if (rv == APR_EINTR) {
1763 continue;
1765 else if (rv == APR_SUCCESS) {
1766 break;
1768 else {
1769 ap_log_rerror(APLOG_MARK, APLOG_ERR, rv, r,
1770 "proxy: FTP: failed to accept data connection");
1771 proxy_ftp_cleanup(r, backend);
1772 return HTTP_BAD_GATEWAY;
1777 /* the transfer socket is now open, create a new connection */
1778 data = ap_run_create_connection(p, r->server, data_sock, r->connection->id,
1779 r->connection->sbh, c->bucket_alloc);
1780 if (!data) {
1782 * the peer reset the connection already; ap_run_create_connection() closed
1783 * the socket
1785 ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, r->server,
1786 "proxy: FTP: an error occurred creating the transfer connection");
1787 proxy_ftp_cleanup(r, backend);
1788 return HTTP_INTERNAL_SERVER_ERROR;
1792 * We do not do SSL over the data connection, even if the virtual host we
1793 * are in might have SSL enabled
1795 ap_proxy_ssl_disable(data);
1796 /* set up the connection filters */
1797 rc = ap_run_pre_connection(data, data_sock);
1798 if (rc != OK && rc != DONE) {
1799 ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, r->server,
1800 "proxy: FTP: pre_connection setup failed (%d)",
1801 rc);
1802 data->aborted = 1;
1803 proxy_ftp_cleanup(r, backend);
1804 return rc;
1808 * VI: Receive the Response ------------------------
1810 * Get response from the remote ftp socket, and pass it up the filter chain.
1813 /* send response */
1814 r->sent_bodyct = 1;
1816 if (dirlisting) {
1817 /* insert directory filter */
1818 ap_add_output_filter("PROXY_SEND_DIR", NULL, r, r->connection);
1821 /* send body */
1822 if (!r->header_only) {
1823 apr_bucket *e;
1824 int finish = FALSE;
1826 ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, r->server,
1827 "proxy: FTP: start body send");
1829 /* read the body, pass it to the output filters */
1830 while (ap_get_brigade(data->input_filters,
1832 AP_MODE_READBYTES,
1833 APR_BLOCK_READ,
1834 conf->io_buffer_size) == APR_SUCCESS) {
1835 #if DEBUGGING
1837 apr_off_t readbytes;
1838 apr_brigade_length(bb, 0, &readbytes);
1839 ap_log_error(APLOG_MARK, APLOG_DEBUG, 0,
1840 r->server, "proxy (PID %d): readbytes: %#x",
1841 getpid(), readbytes);
1843 #endif
1844 /* sanity check */
1845 if (APR_BRIGADE_EMPTY(bb)) {
1846 apr_brigade_cleanup(bb);
1847 break;
1850 /* found the last brigade? */
1851 if (APR_BUCKET_IS_EOS(APR_BRIGADE_LAST(bb))) {
1852 /* if this is the last brigade, cleanup the
1853 * backend connection first to prevent the
1854 * backend server from hanging around waiting
1855 * for a slow client to eat these bytes
1857 ap_flush_conn(data);
1858 apr_socket_close(data_sock);
1859 data_sock = NULL;
1860 ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, r->server,
1861 "proxy: FTP: data connection closed");
1862 /* signal that we must leave */
1863 finish = TRUE;
1866 /* if no EOS yet, then we must flush */
1867 if (FALSE == finish) {
1868 e = apr_bucket_flush_create(c->bucket_alloc);
1869 APR_BRIGADE_INSERT_TAIL(bb, e);
1872 /* try send what we read */
1873 if (ap_pass_brigade(r->output_filters, bb) != APR_SUCCESS
1874 || c->aborted) {
1875 /* Ack! Phbtt! Die! User aborted! */
1876 finish = TRUE;
1879 /* make sure we always clean up after ourselves */
1880 apr_brigade_cleanup(bb);
1882 /* if we are done, leave */
1883 if (TRUE == finish) {
1884 break;
1887 ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, r->server,
1888 "proxy: FTP: end body send");
1891 if (data_sock) {
1892 ap_flush_conn(data);
1893 apr_socket_close(data_sock);
1894 ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, r->server,
1895 "proxy: FTP: data connection closed");
1898 /* Retrieve the final response for the RETR or LIST commands */
1899 rc = proxy_ftp_command(NULL, r, origin, bb, &ftpmessage);
1900 apr_brigade_cleanup(bb);
1903 * VII: Clean Up -------------
1905 * If there are no KeepAlives, or if the connection has been signalled to
1906 * close, close the socket and clean up
1909 /* finish */
1910 rc = proxy_ftp_command("QUIT" CRLF,
1911 r, origin, bb, &ftpmessage);
1912 /* responses: 221, 500 */
1913 /* 221 Service closing control connection. */
1914 /* 500 Syntax error, command unrecognized. */
1915 ap_flush_conn(origin);
1916 proxy_ftp_cleanup(r, backend);
1918 apr_brigade_destroy(bb);
1919 return OK;
1922 static void ap_proxy_ftp_register_hook(apr_pool_t *p)
1924 /* hooks */
1925 proxy_hook_scheme_handler(proxy_ftp_handler, NULL, NULL, APR_HOOK_MIDDLE);
1926 proxy_hook_canon_handler(proxy_ftp_canon, NULL, NULL, APR_HOOK_MIDDLE);
1927 /* filters */
1928 ap_register_output_filter("PROXY_SEND_DIR", proxy_send_dir_filter,
1929 NULL, AP_FTYPE_RESOURCE);
1932 module AP_MODULE_DECLARE_DATA proxy_ftp_module = {
1933 STANDARD20_MODULE_STUFF,
1934 NULL, /* create per-directory config structure */
1935 NULL, /* merge per-directory config structures */
1936 NULL, /* create per-server config structure */
1937 NULL, /* merge per-server config structures */
1938 NULL, /* command apr_table_t */
1939 ap_proxy_ftp_register_hook /* register hooks */