]> granicus.if.org Git - apache/blob - modules/proxy/mod_proxy_ftp.c
Move the POSIX reg* implementations into the ap_* namespace;
[apache] / modules / proxy / mod_proxy_ftp.c
1 /* Copyright 1999-2005 The Apache Software Foundation or its licensors, as
2  * applicable.
3  *
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
7  *
8  *     http://www.apache.org/licenses/LICENSE-2.0
9  *
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.
15  */
16
17 /* FTP routines for Apache proxy */
18
19 #include "mod_proxy.h"
20 #if APR_HAVE_TIME_H
21 #include <time.h>
22 #endif
23 #include "apr_version.h"
24
25 #if (APR_MAJOR_VERSION < 1)
26 #undef apr_socket_create
27 #define apr_socket_create apr_socket_create_ex
28 #endif
29
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
34  */
35 #define USE_MDTM
36
37
38 module AP_MODULE_DECLARE_DATA proxy_ftp_module;
39
40 /*
41  * Decodes a '%' escaped string, and returns the number of characters
42  */
43 static int decodeenc(char *x)
44 {
45     int i, j, ch;
46
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;
55         }
56         x[j] = ch;
57     }
58     x[j] = '\0';
59     return j;
60 }
61
62 /*
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
67  */
68 #define FTP_GLOBBING_CHARS "*?[{~"
69 static char *ftp_escape_globbingchars(apr_pool_t *p, const char *path)
70 {
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;
77     }
78     *d = '\0';
79     return ret;
80 }
81
82 /*
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)
87  */
88 static int ftp_check_globbingchars(const char *path)
89 {
90     for ( ; *path; ++path) {
91         if (*path == '\\')
92         ++path;
93         if (path != '\0' && strchr(FTP_GLOBBING_CHARS, *path) != NULL)
94             return TRUE;
95     }
96     return FALSE;
97 }
98
99 /*
100  * checks an encoded ftp string for bad characters, namely, CR, LF or
101  * non-ascii character
102  */
103 static int ftp_check_string(const char *x)
104 {
105     int i, ch = 0;
106 #if APR_CHARSET_EBCDIC
107     char buf[1];
108 #endif
109
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;
115         }
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;
126     }
127     return 1;
128 }
129
130 /*
131  * Canonicalise ftp URLs.
132  */
133 static int proxy_ftp_canon(request_rec *r, char *url)
134 {
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;
139
140     /* */
141     if (strncasecmp(url, "ftp:", 4) == 0) {
142         url += 4;
143     }
144     else {
145         return DECLINED;
146     }
147     def_port = apr_uri_port_of_scheme("ftp");
148
149     ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, r->server,
150                  "proxy: FTP: canonicalising URL %s", url);
151
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;
160
161     /* now parse path/parameters args, according to rfc1738 */
162     /*
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.
166      */
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;
174     }
175     else
176         parms = "";
177
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;
183
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);
190         }
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);
196         }
197         r->args = NULL;
198     }
199
200 /* now, rebuild URL */
201
202     if (port != def_port)
203         apr_snprintf(sport, sizeof(sport), ":%d", port);
204     else
205         sport[0] = '\0';
206
207     if (ap_strchr_c(host, ':')) { /* if literal IPv6 address */
208         host = apr_pstrcat(p, "[", host, "]", NULL);
209     }
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);
215
216     return OK;
217 }
218
219 /* we chop lines longer than 80 characters */
220 #define MAX_LINE_LEN 80
221
222 /*
223  * Reads response lines, returns both the ftp status code and
224  * remembers the response message in the supplied buffer
225  */
226 static int ftp_getrc_msg(conn_rec *ftp_ctrl, apr_bucket_brigade *bb, char *msgbuf, int msglen)
227 {
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;
234
235     if (APR_SUCCESS != (rv = ap_proxy_string_read(ftp_ctrl, bb, response, sizeof(response), &eos))) {
236         return -1;
237     }
238 /*
239     ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, NULL,
240                  "proxy: <FTP: %s", response);
241 */
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';
247
248     mb = apr_cpystrn(mb, response + 4, me - mb);
249
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;
256             }
257             mb = apr_cpystrn(mb, response + (' ' == response[0] ? 1 : 4), me - mb);
258         } while (memcmp(response, buff, 4) != 0);
259     }
260
261     return status;
262 }
263
264 /* this is a filter that turns a raw ASCII directory listing into pretty HTML */
265
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...
269  *
270  * all in good time...! :)
271  */
272
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;
280
281 /* fallback regex for ls -s1;  ($0..$2) == 3 */
282 #define LS_REG_PATTERN "^ *([0-9]+) +([^ ]+)$"
283 #define LS_REG_MATCH   3
284
285 static apr_status_t proxy_send_dir_filter(ap_filter_t *f,
286                                           apr_bucket_brigade *in)
287 {
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;
293
294     register int n;
295     char *dir, *path, *reldir, *site, *str, *type;
296
297     const char *pwd = apr_table_get(r->notes, "Directory-PWD");
298     const char *readme = apr_table_get(r->notes, "Directory-README");
299
300     proxy_dir_ctx_t *ctx = f->ctx;
301
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;
307     }
308
309     /* combine the stored and the new */
310     APR_BRIGADE_CONCAT(ctx->in, in);
311
312     if (HEADER == ctx->state) {
313
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
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);
322
323         /* If path began with /%2f, change the basedir */
324         if (strncasecmp(path, "/%2f", 4) == 0) {
325             basedir = "/%2f";
326         }
327
328         /* Strip off a type qualifier. It is ignored for dir listings */
329         if ((type = strstr(path, ";type=")) != NULL)
330             *type++ = '\0';
331
332         (void)decodeenc(path);
333
334         while (path[1] == '/') /* collapse multiple leading slashes to one */
335             ++path;
336
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 */
341         }
342
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)
347             path[n - 1] = '\0';
348
349         /* Add a link to the root directory (if %2f hack was used) */
350         str = (basedir[0] != '\0') ? "<a href=\"/%2f/\">%2f</a>/" : "";
351
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),
360                 site, str);
361
362         APR_BRIGADE_INSERT_TAIL(out, apr_bucket_pool_create(str, strlen(str),
363                                                           p, c->bucket_alloc));
364
365         for (dir = path+1; (dir = strchr(dir, '/')) != NULL; )
366         {
367             *dir = '\0';
368             if ((reldir = strrchr(path+1, '/'))==NULL) {
369                 reldir = path+1;
370             }
371             else
372                 ++reldir;
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));
377             *dir = '/';
378             while (*dir == '/')
379               ++dir;
380             APR_BRIGADE_INSERT_TAIL(out, apr_bucket_pool_create(str,
381                                                            strlen(str), p,
382                                                            c->bucket_alloc));
383         }
384         if (wildcard != NULL) {
385             APR_BRIGADE_INSERT_TAIL(out, apr_bucket_pool_create(wildcard,
386                                                            strlen(wildcard), p,
387                                                            c->bucket_alloc));
388         }
389
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>");
394         }
395         else {
396             str = apr_psprintf(p, "</h2>\n\n(%s)\n\n  <hr />\n\n<pre>",
397                                ap_escape_html(p, pwd));
398         }
399         APR_BRIGADE_INSERT_TAIL(out, apr_bucket_pool_create(str, strlen(str),
400                                                            p, c->bucket_alloc));
401
402         /* print README */
403         if (readme) {
404             str = apr_psprintf(p, "%s\n</pre>\n\n<hr />\n\n<pre>\n",
405                                ap_escape_html(p, readme));
406
407             APR_BRIGADE_INSERT_TAIL(out, apr_bucket_pool_create(str,
408                                                            strlen(str), p,
409                                                            c->bucket_alloc));
410         }
411
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))) {
415             return rv;
416         }
417         apr_brigade_cleanup(out);
418
419         ctx->state = BODY;
420     }
421
422     /* loop through each line of directory */
423     while (BODY == ctx->state) {
424         char *filename;
425         int found = 0;
426         int eos = 0;
427
428         ap_regex_t *re = NULL;
429         ap_regmatch_t re_result[LS_REG_MATCH];
430
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);
434
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;
439             apr_size_t len, max;
440             apr_bucket *e;
441
442             e = APR_BRIGADE_FIRST(ctx->in);
443             if (APR_BUCKET_IS_EOS(e)) {
444                 eos = 1;
445                 break;
446             }
447             if (APR_SUCCESS != (rv = apr_bucket_read(e, (const char **)&response, &len, APR_BLOCK_READ))) {
448                 return rv;
449             }
450             pos = memchr(response, APR_ASCII_LF, len);
451             if (pos != NULL) {
452                 if ((response + len) != (pos + 1)) {
453                     len = pos - response + 1;
454                     apr_bucket_split(e, pos - response + 1);
455                 }
456                 found = 1;
457             }
458             max = sizeof(ctx->buffer) - strlen(ctx->buffer) - 1;
459             if (len > max) {
460                 len = max;
461             }
462
463             /* len+1 to leave space for the trailing nil char */
464             apr_cpystrn(ctx->buffer+strlen(ctx->buffer), response, len+1);
465
466             APR_BUCKET_REMOVE(e);
467             apr_bucket_destroy(e);
468         }
469
470         /* EOS? jump to footer */
471         if (eos) {
472             ctx->state = FOOTER;
473             break;
474         }
475
476         /* not complete? leave and try get some more */
477         if (!found) {
478             return APR_SUCCESS;
479         }
480
481         {
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';
487         }
488
489         /* a symlink? */
490         if (ctx->buffer[0] == 'l' && (filename = strstr(ctx->buffer, " -> ")) != NULL) {
491             char *link_ptr = filename;
492
493             do {
494                 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));
504         }
505
506         /* a directory/file? */
507         else if (ctx->buffer[0] == 'd' || ctx->buffer[0] == '-' || ctx->buffer[0] == 'l' || apr_isdigit(ctx->buffer[0])) {
508             int searchidx = 0;
509             char *searchptr = NULL;
510             int firstfile = 1;
511             if (apr_isdigit(ctx->buffer[0])) {  /* handle DOS dir */
512                 searchptr = strchr(ctx->buffer, '<');
513                 if (searchptr != NULL)
514                     *searchptr = '[';
515                 searchptr = strchr(ctx->buffer, '>');
516                 if (searchptr != NULL)
517                     *searchptr = ']';
518             }
519
520             filename = strrchr(ctx->buffer, ' ');
521             *(filename++) = '\0';
522
523             /* handle filenames with spaces in 'em */
524             if (!strcmp(filename, ".") || !strcmp(filename, "..") || firstfile) {
525                 firstfile = 0;
526                 searchidx = filename - ctx->buffer;
527             }
528             else if (searchidx != 0 && ctx->buffer[searchidx] != 0) {
529                 *(--filename) = ' ';
530                 ctx->buffer[searchidx - 1] = '\0';
531                 filename = &ctx->buffer[searchidx];
532             }
533
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));
540             }
541             else {
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));
546             }
547         }
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)) {
550
551             filename = apr_pstrndup(p, &ctx->buffer[re_result[2].rm_so], re_result[2].rm_eo - re_result[2].rm_so);
552
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);
556         }
557         else {
558             strcat(ctx->buffer, "\n"); /* re-append the newline */
559             str = ap_escape_html(p, ctx->buffer);
560         }
561
562         /* erase buffer for next time around */
563         ctx->buffer[0] = 0;
564
565         APR_BRIGADE_INSERT_TAIL(out, apr_bucket_pool_create(str, strlen(str), p,
566                                                             c->bucket_alloc));
567         APR_BRIGADE_INSERT_TAIL(out, apr_bucket_flush_create(c->bucket_alloc));
568         if (APR_SUCCESS != (rv = ap_pass_brigade(f->next, out))) {
569             return rv;
570         }
571         apr_brigade_cleanup(out);
572
573     }
574
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,
578                                                             c->bucket_alloc));
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))) {
582             return rv;
583         }
584         apr_brigade_destroy(out);
585     }
586
587     return APR_SUCCESS;
588 }
589
590 /*
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)
594  */
595 static int
596 proxy_ftp_command(const char *cmd, request_rec *r, conn_rec *ftp_ctrl,
597                   apr_bucket_brigade *bb, char **pmessage)
598 {
599     char *crlf;
600     int rc;
601     char message[HUGE_STRING_LEN];
602
603     /* If cmd == NULL, we retrieve the next ftp response line */
604     if (cmd != NULL) {
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);
609
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)
614             *crlf = '\0';
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);
619     }
620
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)
626         *crlf = '\0';
627     ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, r->server,
628                  "proxy:<FTP: %3.3u %s", rc, message);
629
630     if (pmessage != NULL)
631         *pmessage = apr_pstrdup(r->pool, message);
632
633     return rc;
634 }
635
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)
639 {
640     char old_type[2] = { 'A', '\0' }; /* After logon, mode is ASCII */
641     int ret = HTTP_OK;
642     int rc;
643
644     /* set desired type */
645     old_type[0] = xfer_type;
646
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");
659     }
660     else if (rc != 200 && rc != 504) {
661         ret = ap_proxyerror(r, HTTP_BAD_GATEWAY,
662                              "Unable to set transfer type");
663     }
664 /* Allow not implemented */
665     else if (rc == 504)
666         /* ignore it silently */;
667
668     return ret;
669 }
670
671
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)
674 {
675     char *cwd = NULL;
676     char *ftpmessage = NULL;
677
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)) {
686         case -1:
687         case 421:
688         case 550:
689             ap_proxyerror(r, HTTP_BAD_GATEWAY,
690                              "Failed to read PWD on ftp server");
691             break;
692
693         case 257: {
694             const char *dirp = ftpmessage;
695             cwd = ap_getword_conf(r->pool, &dirp);
696         }
697     }
698     return cwd;
699 }
700
701
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-)
708  */
709 static int ftp_unauthorized(request_rec *r, int log_it)
710 {
711     r->proxyreq = PROXYREQ_NONE;
712     /*
713      * Log failed requests if they supplied a password (log username/password
714      * guessing attempts)
715      */
716     if (log_it)
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));
721
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),
726                                "\"", NULL));
727
728     return HTTP_UNAUTHORIZED;
729 }
730
731 static
732 apr_status_t proxy_ftp_cleanup(request_rec *r, proxy_conn_rec *backend)
733 {
734
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);    
738
739     return OK;
740 }
741
742 static
743 int ftp_proxyerror(request_rec *r, proxy_conn_rec *conn, int statuscode, const char *message)
744 {
745     proxy_ftp_cleanup(r, conn);
746     return ap_proxyerror(r, statuscode, message);
747 }
748 /*
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>]
754  */
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)
758 {
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;
764     apr_status_t rv;
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;
773     apr_uri_t uri; 
774     char *user = NULL;
775 /*    char *account = NULL; how to supply an account in a URL? */
776     const char *password = NULL;
777     int len, rc;
778     int one = 1;
779     char *size = NULL;
780     char xfer_type = 'A'; /* after ftp login, the default is ASCII */
781     int  dirlisting = 0;
782 #if defined(USE_MDTM) && (defined(HAVE_TIMEGM) || defined(HAVE_GMTOFF))
783     apr_time_t mtime = 0L;
784 #endif
785
786     /* stuff for PASV mode */
787     int connect = 0, use_port = 0;
788     char dates[APR_RFC822_DATE_LEN];
789     int status;
790     apr_pool_t *address_pool;
791
792     /* is this for us? */
793     if (proxyhost) {
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 */
797     }
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 */
802     }
803     ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, r->server,
804                  "proxy: FTP: serving URL %s", url);
805
806
807     /*
808      * I: Who Do I Connect To? -----------------------
809      *
810      * Break up the URL to determine the host to connect to
811      */
812
813     /* we only support GET and HEAD */
814     if (r->method_number != M_GET)
815         return HTTP_NOT_IMPLEMENTED;
816
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));
822         }
823         connectname = uri.hostname;
824         connectport = uri.port;
825         path = apr_pstrdup(p, uri.path);
826     }
827     else {
828         connectname = r->parsed_uri.hostname;
829         connectport = r->parsed_uri.port;
830         path = apr_pstrdup(p, r->parsed_uri.path);
831     }
832     if (connectport == 0) {
833         connectport = apr_uri_port_of_scheme("ftp");
834     }
835     path = (path != NULL && path[0] != '\0') ? &path[1] : "";
836
837     type_suffix = strchr(path, ';');
838     if (type_suffix != NULL)
839         *(type_suffix++) = '\0';
840
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
845          */
846         if ( ! (dirlisting = (apr_tolower(type_suffix[5]) == 'd')))
847             xfer_type = apr_toupper(type_suffix[5]);
848
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));
854     }
855     else {
856         /* make binary transfers the default */
857         xfer_type = 'I';
858     }
859
860
861     /*
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.
868      */
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] != ':') {
872         /*
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.
876          */
877         user = ap_getword_nulls(r->connection->pool, &password, ':');
878         r->ap_auth_type = "Basic";
879         r->user = r->parsed_uri.user = user;
880     }
881     else if ((user = r->parsed_uri.user) != NULL) {
882         user = apr_pstrdup(p, user);
883         decodeenc(user);
884         if ((password = r->parsed_uri.password) != NULL) {
885             char *tmp = apr_pstrdup(p, password);
886             decodeenc(tmp);
887             password = tmp;
888         }
889     }
890     else {
891         user = "anonymous";
892         password = "apache-proxy@";
893     }
894
895     ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, r->server,
896        "proxy: FTP: connecting %s to %s:%d", url, connectname, connectport);
897
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,
902                              "proxy: FTP: lock");
903                 return HTTP_INTERNAL_SERVER_ERROR;
904             }
905         }
906         connect_addr = worker->cp->addr;
907         address_pool = worker->cp->pool;
908     }
909     else
910         address_pool = r->pool;
911
912     /* do a DNS lookup for the destination host */
913     if (!connect_addr)
914         err = apr_sockaddr_info_get(&(connect_addr),
915                                     connectname, APR_UNSPEC,
916                                     connectport, 0,
917                                     address_pool);
918     if (worker->is_address_reusable && !worker->cp->addr) {        
919         worker->cp->addr = connect_addr;            
920         PROXY_THREAD_UNLOCK(worker);
921     }
922     /*
923      * get all the possible IP addresses for the destname and loop through
924      * them until we get a successful connection
925      */
926     if (APR_SUCCESS != err) {
927         return ap_proxyerror(r, HTTP_BAD_GATEWAY, apr_pstrcat(p,
928                                                  "DNS lookup failure for: ",
929                                                         connectname, NULL));
930     }
931
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");
936     }
937
938     /* create space for state information */
939     backend = (proxy_conn_rec *) ap_get_module_config(c->conn_config, &proxy_ftp_module);
940     if (!backend) {
941         status = ap_proxy_acquire_connection("FTP", &backend, worker, r->server);
942         if (status != OK) {
943             if (backend) {
944                 backend->close_on_recycle = 1;
945                 ap_proxy_release_connection("FTP", backend, r->server);
946             }
947             return status;
948         }
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);        
952     }
953
954
955     /*
956      * II: Make the Connection -----------------------
957      *
958      * We have determined who to connect to. Now make the connection.
959      */
960
961
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;
968     }
969
970     if (!backend->connection) {
971         status = ap_proxy_connection_create("FTP", backend, c, r->server);
972         if (status != OK) {
973             proxy_ftp_cleanup(r, backend);
974             return status;
975         }
976     }
977
978     /* Use old naming */
979     origin = backend->connection;
980     sock = backend->sock;
981
982     ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, r->server,
983                  "proxy: FTP: control connection complete");
984
985
986     /*
987      * III: Send Control Request -------------------------
988      *
989      * Log into the ftp server, send the username & password, change to the
990      * correct directory...
991      */
992
993
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");
1001     }
1002     if (rc == 120) {
1003         /*
1004          * RFC2616 states: 14.37 Retry-After
1005          *
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 )
1012          */
1013         char *secs_str = ftpmessage;
1014         time_t secs;
1015
1016         /* Look for a number, preceded by whitespace */
1017         while (*secs_str)
1018             if ((secs_str==ftpmessage || apr_isspace(secs_str[-1])) &&
1019                 apr_isdigit(secs_str[0]))
1020                 break;
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)));
1025         }
1026         return ftp_proxyerror(r, backend, HTTP_SERVICE_UNAVAILABLE, ftpmessage);
1027     }
1028     if (rc != 220) {
1029         return ftp_proxyerror(r, backend, HTTP_BAD_GATEWAY, ftpmessage);
1030     }
1031
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");
1046     }
1047     if (rc == 530) {
1048         proxy_ftp_cleanup(r, backend);
1049         return ftp_unauthorized(r, 1);  /* log it: user name guessing
1050                                          * attempt? */
1051     }
1052     if (rc != 230 && rc != 331) {
1053         return ftp_proxyerror(r, backend, HTTP_BAD_GATEWAY, ftpmessage);
1054     }
1055
1056     if (rc == 331) {            /* send password */
1057         if (password == NULL) {
1058             proxy_ftp_cleanup(r, backend);
1059             return ftp_unauthorized(r, 0);
1060         }
1061
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");
1075         }
1076         if (rc == 332) {
1077             return ftp_proxyerror(r, backend, HTTP_UNAUTHORIZED,
1078                   apr_pstrcat(p, "Need account for login: ", ftpmessage, NULL));
1079         }
1080         /* @@@ questionable -- we might as well return a 403 Forbidden here */
1081         if (rc == 530) {
1082             proxy_ftp_cleanup(r, backend);
1083             return ftp_unauthorized(r, 1);      /* log it: passwd guessing
1084                                                  * attempt? */
1085         }
1086         if (rc != 230 && rc != 202) {
1087             return ftp_proxyerror(r, backend, HTTP_BAD_GATEWAY, ftpmessage);
1088         }
1089     }
1090     apr_table_set(r->notes, "Directory-README", ftpmessage);
1091
1092
1093     /* Special handling for leading "%2f": this enforces a "cwd /"
1094      * out of the $HOME directory which was the starting point after login
1095      */
1096     if (strncasecmp(path, "%2f", 3) == 0) {
1097         path += 3;
1098         while (*path == '/') /* skip leading '/' (after root %2f) */
1099             ++path;
1100
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");
1105     }
1106
1107     /*
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
1110      */
1111     for (;;) {
1112         strp = strchr(path, '/');
1113         if (strp == NULL)
1114             break;
1115         *strp = '\0';
1116
1117         len = decodeenc(path); /* Note! This decodes a %2f -> "/" */
1118
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");
1122         }
1123
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
1128          */
1129         rc = proxy_ftp_command(apr_pstrcat(p, "CWD ",
1130                            ftp_escape_globbingchars(p, path), CRLF, NULL),
1131                            r, origin, bb, &ftpmessage);
1132         *strp = '/';
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");
1144         }
1145         if (rc == 550) {
1146             return ftp_proxyerror(r, backend, HTTP_NOT_FOUND, ftpmessage);
1147         }
1148         if (rc != 250) {
1149             return ftp_proxyerror(r, backend, HTTP_BAD_GATEWAY, ftpmessage);
1150         }
1151
1152         path = strp + 1;
1153     }
1154
1155     /*
1156      * IV: Make Data Connection? -------------------------
1157      *
1158      * Try EPSV, if that fails... try PASV, if that fails... try PORT.
1159      */
1160 /* this temporarily switches off EPSV/PASV */
1161 /*goto bypass;*/
1162
1163     /* set up data connection - EPSV */
1164     {
1165         apr_sockaddr_t *data_addr;
1166         char *data_ip;
1167         apr_port_t data_port;
1168
1169         /*
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|)
1174          */
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");
1187         }
1188         if (rc != 229 && rc != 500 && rc != 501 && rc != 502) {
1189             return ftp_proxyerror(r, backend, HTTP_BAD_GATEWAY, ftpmessage);
1190         }
1191         else if (rc == 229) {
1192             char *pstr;
1193             char *tok_cntx;
1194
1195             pstr = ftpmessage;
1196             pstr = apr_strtok(pstr, " ", &tok_cntx);    /* separate result code */
1197             if (pstr != NULL) {
1198                 if (*(pstr + strlen(pstr) + 1) == '=') {
1199                     pstr += strlen(pstr) + 2;
1200                 }
1201                 else {
1202                     pstr = apr_strtok(NULL, "(", &tok_cntx);    /* separate address &
1203                                                                  * port params */
1204                     if (pstr != NULL)
1205                         pstr = apr_strtok(NULL, ")", &tok_cntx);
1206                 }
1207             }
1208
1209             if (pstr) {
1210                 apr_sockaddr_t *epsv_addr;
1211                 data_port = atoi(pstr + 3);
1212
1213                 ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, r->server,
1214                        "proxy: FTP: EPSV contacting remote host on port %d",
1215                              data_port);
1216
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;
1222                 }
1223
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");
1230                 }
1231 #endif
1232
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));
1243                 }
1244                 else {
1245                     connect = 1;
1246                 }
1247             }
1248             else {
1249                 /* and try the regular way */
1250                 apr_socket_close(data_sock);
1251             }
1252         }
1253     }
1254
1255     /* set up data connection - PASV */
1256     if (!connect) {
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");
1269         }
1270         if (rc != 227 && rc != 502) {
1271             return ftp_proxyerror(r, backend, HTTP_BAD_GATEWAY, ftpmessage);
1272         }
1273         else if (rc == 227) {
1274             unsigned int h0, h1, h2, h3, p0, p1;
1275             char *pstr;
1276             char *tok_cntx;
1277
1278 /* FIXME: Check PASV against RFC1123 */
1279
1280             pstr = ftpmessage;
1281             pstr = apr_strtok(pstr, " ", &tok_cntx);    /* separate result code */
1282             if (pstr != NULL) {
1283                 if (*(pstr + strlen(pstr) + 1) == '=') {
1284                     pstr += strlen(pstr) + 2;
1285                 }
1286                 else {
1287                     pstr = apr_strtok(NULL, "(", &tok_cntx);    /* separate address &
1288                                                                  * port params */
1289                     if (pstr != NULL)
1290                         pstr = apr_strtok(NULL, ")", &tok_cntx);
1291                 }
1292             }
1293
1294 /* FIXME: Only supports IPV4 - fix in RFC2428 */
1295
1296             if (pstr != NULL && (sscanf(pstr,
1297                  "%d,%d,%d,%d,%d,%d", &h3, &h2, &h1, &h0, &p1, &p0) == 6)) {
1298
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);
1304
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;
1310                 }
1311
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");
1318                 }
1319 #endif
1320
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));
1329                 }
1330                 else {
1331                     connect = 1;
1332                 }
1333             }
1334             else {
1335                 /* and try the regular way */
1336                 apr_socket_close(data_sock);
1337             }
1338         }
1339     }
1340 /*bypass:*/
1341
1342     /* set up data connection - PORT */
1343     if (!connect) {
1344         apr_sockaddr_t *local_addr;
1345         char *local_ip;
1346         apr_port_t local_port;
1347         unsigned int h0, h1, h2, h3, p0, p1;
1348
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;
1354         }
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);
1358
1359         if ((rv = apr_socket_opt_set(local_sock, APR_SO_REUSEADDR, one)) 
1360                 != APR_SUCCESS) {
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 */
1367         }
1368
1369         apr_sockaddr_info_get(&local_addr, local_ip, APR_UNSPEC, local_port, 0, r->pool);
1370
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;
1376         }
1377
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;
1384         }
1385
1386 /* FIXME: Sent PORT here */
1387
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);
1392
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");
1405             }
1406             if (rc != 200) {
1407                 return ftp_proxyerror(r, backend, HTTP_BAD_GATEWAY, buffer);
1408             }
1409
1410             /* signal that we must use the EPRT/PORT loop */
1411             use_port = 1;
1412         }
1413         else {
1414 /* IPV6 FIXME:
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|
1419  */
1420             return ftp_proxyerror(r, backend, HTTP_NOT_IMPLEMENTED,
1421                                   "Connect to IPV6 ftp server using EPRT not supported. Enable EPSV.");
1422         }
1423     }
1424
1425
1426     /*
1427      * V: Set The Headers -------------------
1428      *
1429      * Get the size of the request, set up the environment for HTTP.
1430      */
1431
1432     /* set request; "path" holds last path component */
1433     len = decodeenc(path);
1434
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");
1438     }
1439
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
1442      */
1443     if (len == 0 || ftp_check_globbingchars(path)) {
1444         dirlisting = 1;
1445     }
1446     else {
1447         /* (from FreeBSD ftpd):
1448          * SIZE is not in RFC959, but Postel has blessed it and
1449          * it will be in the updated RFC.
1450          *
1451          * Return size of file in a format suitable for
1452          * using with RESTART (we just count bytes).
1453          */
1454         /* from draft-ietf-ftpext-mlst-14.txt:
1455          * This value will
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.
1460          */
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");
1469         }
1470         else if (rc == 213) {/* Size command ok */
1471             int j;
1472             for (j = 0; apr_isdigit(ftpmessage[j]); j++)
1473                 ;
1474             ftpmessage[j] = '\0';
1475             if (ftpmessage[0] != '\0')
1476                  size = ftpmessage; /* already pstrdup'ed: no copy necessary */
1477         }
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");
1481             dirlisting = 1;
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");
1496             }
1497             if (rc == 550) {
1498                 return ftp_proxyerror(r, backend, HTTP_NOT_FOUND, ftpmessage);
1499             }
1500             if (rc != 250) {
1501                 return ftp_proxyerror(r, backend, HTTP_BAD_GATEWAY, ftpmessage);
1502             }
1503             path = "";
1504             len = 0;
1505         }
1506     }
1507
1508     cwd = ftp_get_PWD(r, origin, bb);
1509     if (cwd != NULL) {
1510         apr_table_set(r->notes, "Directory-PWD", cwd);
1511     }
1512
1513     if (dirlisting) {
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.
1519          */
1520         /* Note that we do not escape the path here, to allow for
1521          * queries like: ftp://user@host/apache/src/server/http_*.c
1522          */
1523         if (len != 0)
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);
1527         else
1528             buf = "LIST" CRLF;
1529     }
1530     else {
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)
1543          */
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). */
1547         if (rc == 213) {
1548         struct {
1549             char YYYY[4+1];
1550         char MM[2+1];
1551         char DD[2+1];
1552         char hh[2+1];
1553         char mm[2+1];
1554         char ss[2+1];
1555         } time_val;
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)) {
1558                 struct tm tms;
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
1572          */
1573         mtime = mktime(&tms);
1574         mtime += tms.tm_gmtoff;
1575         mtime *= APR_USEC_PER_SEC;
1576 #else
1577         mtime = 0L;
1578 #endif
1579             }
1580     }
1581 #endif /* USE_MDTM */
1582 /* FIXME: Handle range requests - send REST */
1583         buf = apr_pstrcat(p, "RETR ", ftp_escape_globbingchars(p, path), CRLF, NULL);
1584     }
1585     rc = proxy_ftp_command(buf, r, origin, bb, &ftpmessage);
1586     /* rc is an intermediate response for the LIST or RETR commands */
1587
1588     /*
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,
1591      * 530
1592      */
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");
1610     }
1611     if (rc == 550) {
1612         ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, r->server,
1613                      "proxy: FTP: RETR failed, trying LIST instead");
1614
1615         /* Directory Listings should always be fetched in ASCII mode */
1616         dirlisting = 1;
1617         ftp_set_TYPE('A', r, origin, bb, NULL);
1618
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");
1633         }
1634         if (rc == 550) {
1635             return ftp_proxyerror(r, backend, HTTP_NOT_FOUND, ftpmessage);
1636         }
1637         if (rc != 250) {
1638             return ftp_proxyerror(r, backend, HTTP_BAD_GATEWAY, ftpmessage);
1639         }
1640
1641         /* Update current directory after CWD */
1642         cwd = ftp_get_PWD(r, origin, bb);
1643         if (cwd != NULL) {
1644             apr_table_set(r->notes, "Directory-PWD", cwd);
1645         }
1646
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);
1651
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");
1656     }
1657     if (rc != 125 && rc != 150 && rc != 226 && rc != 250) {
1658         return ftp_proxyerror(r, backend, HTTP_BAD_GATEWAY, ftpmessage);
1659     }
1660
1661     r->status = HTTP_OK;
1662     r->status_line = "200 OK";
1663
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());
1667
1668     /* set content-type */
1669     if (dirlisting) {
1670         ap_set_content_type(r, "text/html");
1671     }
1672     else {
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);
1676         }
1677         else {
1678             ap_set_content_type(r, ap_default_type(r));
1679         }
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);
1685         }
1686     }
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);
1690
1691 #if defined(USE_MDTM) && (defined(HAVE_TIMEGM) || defined(HAVE_GMTOFF))
1692     if (mtime != 0L) {
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);
1698     }
1699 #endif /* USE_MDTM */
1700
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)
1704      */
1705     if (dirlisting && r->content_encoding != NULL)
1706         r->content_encoding = NULL;
1707
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);
1713     }
1714
1715     /* wait for connection */
1716     if (use_port) {
1717         for (;;) {
1718             rv = apr_socket_accept(&data_sock, local_sock, r->pool);
1719             if (rv == APR_EINTR) {
1720                 continue;
1721             }
1722             else if (rv == APR_SUCCESS) {
1723                 break;
1724             }
1725             else {
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;
1730             }
1731         }
1732     }
1733
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);
1737     if (!data) {
1738         /*
1739          * the peer reset the connection already; ap_run_create_connection() closed
1740          * the socket
1741          */
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;
1746     }
1747
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)",
1753                      rc);
1754         data->aborted = 1;
1755         proxy_ftp_cleanup(r, backend);
1756         return rc;
1757     }
1758
1759     /*
1760      * VI: Receive the Response ------------------------
1761      *
1762      * Get response from the remote ftp socket, and pass it up the filter chain.
1763      */
1764
1765     /* send response */
1766     r->sent_bodyct = 1;
1767
1768     if (dirlisting) {
1769         /* insert directory filter */
1770         ap_add_output_filter("PROXY_SEND_DIR", NULL, r, r->connection);
1771     }
1772
1773     /* send body */
1774     if (!r->header_only) {
1775         apr_bucket *e;
1776         int finish = FALSE;
1777
1778         ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, r->server,
1779                      "proxy: FTP: start body send");
1780
1781         /* read the body, pass it to the output filters */
1782         while (ap_get_brigade(data->input_filters, 
1783                               bb, 
1784                               AP_MODE_READBYTES, 
1785                               APR_BLOCK_READ, 
1786                               conf->io_buffer_size) == APR_SUCCESS) {
1787 #if DEBUGGING
1788             {
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);
1794             }
1795 #endif
1796             /* sanity check */
1797             if (APR_BRIGADE_EMPTY(bb)) {
1798                 apr_brigade_cleanup(bb);
1799                 break;
1800             }
1801
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
1808                  */
1809                 ap_flush_conn(data);
1810                 apr_socket_close(data_sock);
1811                 data_sock = NULL;
1812                 ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, r->server,
1813                              "proxy: FTP: data connection closed");
1814                 /* signal that we must leave */
1815                 finish = TRUE;
1816             }
1817
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);
1822             }
1823
1824             /* try send what we read */
1825             if (ap_pass_brigade(r->output_filters, bb) != APR_SUCCESS
1826                 || c->aborted) {
1827                 /* Ack! Phbtt! Die! User aborted! */
1828                 finish = TRUE;
1829             }
1830
1831             /* make sure we always clean up after ourselves */
1832             apr_brigade_cleanup(bb);
1833
1834             /* if we are done, leave */
1835             if (TRUE == finish) {
1836                 break;
1837             }
1838         }
1839         ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, r->server,
1840                      "proxy: FTP: end body send");
1841
1842     }
1843     if (data_sock) {
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");
1848     }
1849
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);
1853
1854     /*
1855      * VII: Clean Up -------------
1856      *
1857      * If there are no KeepAlives, or if the connection has been signalled to
1858      * close, close the socket and clean up
1859      */
1860
1861     /* finish */
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);
1869
1870     apr_brigade_destroy(bb);
1871     return OK;
1872 }
1873
1874 static void ap_proxy_ftp_register_hook(apr_pool_t *p)
1875 {
1876     /* hooks */
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);
1879     /* filters */
1880     ap_register_output_filter("PROXY_SEND_DIR", proxy_send_dir_filter,
1881                               NULL, AP_FTYPE_RESOURCE);
1882 }
1883
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 */
1892 };