bottleneck testcase based on rubbos
[bottlenecks.git] / rubbos / app / httpd-2.0.64 / modules / proxy / proxy_ftp.c
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
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
24 #define AUTODETECT_PWD
25 /* Automatic timestamping (Last-Modified header) based on MDTM is used if:
26  * 1) the FTP server supports the MDTM command and
27  * 2) HAVE_TIMEGM (preferred) or HAVE_GMTOFF is available at compile time
28  */
29 #define USE_MDTM
30
31
32 module AP_MODULE_DECLARE_DATA proxy_ftp_module;
33
34 int ap_proxy_ftp_canon(request_rec *r, char *url);
35 int ap_proxy_ftp_handler(request_rec *r, proxy_server_conf *conf,
36                              char *url, const char *proxyhost,
37                              apr_port_t proxyport);
38 apr_status_t ap_proxy_send_dir_filter(ap_filter_t * f,
39                                                    apr_bucket_brigade *bb);
40
41
42 /*
43  * Decodes a '%' escaped string, and returns the number of characters
44  */
45 static int decodeenc(char *x)
46 {
47     int i, j, ch;
48
49     if (x[0] == '\0')
50         return 0;               /* special case for no characters */
51     for (i = 0, j = 0; x[i] != '\0'; i++, j++) {
52         /* decode it if not already done */
53         ch = x[i];
54         if (ch == '%' && apr_isxdigit(x[i + 1]) && apr_isxdigit(x[i + 2])) {
55             ch = ap_proxy_hex2c(&x[i + 1]);
56             i += 2;
57         }
58         x[j] = ch;
59     }
60     x[j] = '\0';
61     return j;
62 }
63
64 /*
65  * Escape the globbing characters in a path used as argument to
66  * the FTP commands (SIZE, CWD, RETR, MDTM, ...).
67  * ftpd assumes '\\' as a quoting character to escape special characters.
68  * Returns: escaped string
69  */
70 #define FTP_GLOBBING_CHARS "*?[{~"
71 static char *ftp_escape_globbingchars(apr_pool_t *p, const char *path)
72 {
73     char *ret = apr_palloc(p, 2*strlen(path)+sizeof(""));
74     char *d;
75     for (d = ret; *path; ++path) {
76         if (strchr(FTP_GLOBBING_CHARS, *path) != NULL)
77             *d++ = '\\';
78         *d++ = *path;
79     }
80     *d = '\0';
81     return ret;
82 }
83
84 /*
85  * Check for globbing characters in a path used as argument to
86  * the FTP commands (SIZE, CWD, RETR, MDTM, ...).
87  * ftpd assumes '\\' as a quoting character to escape special characters.
88  * Returns: 0 (no globbing chars, or all globbing chars escaped), 1 (globbing chars)
89  */
90 static int ftp_check_globbingchars(const char *path)
91 {
92     for ( ; *path; ++path) {
93         if (*path == '\\')
94             ++path;
95         if (*path != '\0' && strchr(FTP_GLOBBING_CHARS, *path) != NULL)
96             return TRUE;
97     }
98     return FALSE;
99 }
100
101 /*
102  * checks an encoded ftp string for bad characters, namely, CR, LF or
103  * non-ascii character
104  */
105 static int ftp_check_string(const char *x)
106 {
107     int i, ch = 0;
108 #if APR_CHARSET_EBCDIC
109     char buf[1];
110 #endif
111
112     for (i = 0; x[i] != '\0'; i++) {
113         ch = x[i];
114         if (ch == '%' && apr_isxdigit(x[i + 1]) && apr_isxdigit(x[i + 2])) {
115             ch = ap_proxy_hex2c(&x[i + 1]);
116             i += 2;
117         }
118 #if !APR_CHARSET_EBCDIC
119         if (ch == '\015' || ch == '\012' || (ch & 0x80))
120 #else                           /* APR_CHARSET_EBCDIC */
121         if (ch == '\r' || ch == '\n')
122             return 0;
123         buf[0] = ch;
124         ap_xlate_proto_to_ascii(buf, 1);
125         if (buf[0] & 0x80)
126 #endif                          /* APR_CHARSET_EBCDIC */
127             return 0;
128     }
129     return 1;
130 }
131
132 /*
133  * Canonicalise ftp URLs.
134  */
135 int ap_proxy_ftp_canon(request_rec *r, char *url)
136 {
137     char *user, *password, *host, *path, *parms, *strp, sport[7];
138     apr_pool_t *p = r->pool;
139     const char *err;
140     apr_port_t port, def_port;
141
142     /* */
143     if (strncasecmp(url, "ftp:", 4) == 0) {
144         url += 4;
145     }
146     else {
147         return DECLINED;
148     }
149     def_port = apr_uri_port_of_scheme("ftp");
150
151     ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, r->server,
152                  "proxy: FTP: canonicalising URL %s", url);
153
154     port = def_port;
155     err = ap_proxy_canon_netloc(p, &url, &user, &password, &host, &port);
156     if (err)
157         return HTTP_BAD_REQUEST;
158     if (user != NULL && !ftp_check_string(user))
159         return HTTP_BAD_REQUEST;
160     if (password != NULL && !ftp_check_string(password))
161         return HTTP_BAD_REQUEST;
162
163     /* now parse path/parameters args, according to rfc1738 */
164     /*
165      * N.B. if this isn't a true proxy request, then the URL path (but not
166      * query args) has already been decoded. This gives rise to the problem
167      * of a ; being decoded into the path.
168      */
169     strp = strchr(url, ';');
170     if (strp != NULL) {
171         *(strp++) = '\0';
172         parms = ap_proxy_canonenc(p, strp, strlen(strp), enc_parm,
173                                   r->proxyreq);
174         if (parms == NULL)
175             return HTTP_BAD_REQUEST;
176     }
177     else
178         parms = "";
179
180     path = ap_proxy_canonenc(p, url, strlen(url), enc_path, r->proxyreq);
181     if (path == NULL)
182         return HTTP_BAD_REQUEST;
183     if (!ftp_check_string(path))
184         return HTTP_BAD_REQUEST;
185
186     if (r->proxyreq && r->args != NULL) {
187         if (strp != NULL) {
188             strp = ap_proxy_canonenc(p, r->args, strlen(r->args), enc_parm, 1);
189             if (strp == NULL)
190                 return HTTP_BAD_REQUEST;
191             parms = apr_pstrcat(p, parms, "?", strp, NULL);
192         }
193         else {
194             strp = ap_proxy_canonenc(p, r->args, strlen(r->args), enc_fpath, 1);
195             if (strp == NULL)
196                 return HTTP_BAD_REQUEST;
197             path = apr_pstrcat(p, path, "?", strp, NULL);
198         }
199         r->args = NULL;
200     }
201
202 /* now, rebuild URL */
203
204     if (port != def_port)
205         apr_snprintf(sport, sizeof(sport), ":%d", port);
206     else
207         sport[0] = '\0';
208
209     if (ap_strchr_c(host, ':')) { /* if literal IPv6 address */
210         host = apr_pstrcat(p, "[", host, "]", NULL);
211     }
212     r->filename = apr_pstrcat(p, "proxy:ftp://", (user != NULL) ? user : "",
213                               (password != NULL) ? ":" : "",
214                               (password != NULL) ? password : "",
215                           (user != NULL) ? "@" : "", host, sport, "/", path,
216                               (parms[0] != '\0') ? ";" : "", parms, NULL);
217
218     return OK;
219 }
220
221 /* we chop lines longer than 80 characters */
222 #define MAX_LINE_LEN 80
223
224 /*
225  * Reads response lines, returns both the ftp status code and
226  * remembers the response message in the supplied buffer
227  */
228 static int ftp_getrc_msg(conn_rec *ftp_ctrl, apr_bucket_brigade *bb, char *msgbuf, int msglen)
229 {
230     int status;
231     char response[MAX_LINE_LEN];
232     char buff[5];
233     char *mb = msgbuf, *me = &msgbuf[msglen];
234     apr_status_t rv;
235     int eos;
236
237     if (APR_SUCCESS != (rv = ap_proxy_string_read(ftp_ctrl, bb, response, sizeof(response), &eos))) {
238         return -1;
239     }
240 /*
241     ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, NULL,
242                  "proxy: <FTP: %s", response);
243 */
244     if (!apr_isdigit(response[0]) || !apr_isdigit(response[1]) ||
245     !apr_isdigit(response[2]) || (response[3] != ' ' && response[3] != '-'))
246         status = 0;
247     else
248         status = 100 * response[0] + 10 * response[1] + response[2] - 111 * '0';
249
250     mb = apr_cpystrn(mb, response + 4, me - mb);
251
252     if (response[3] == '-') {
253         memcpy(buff, response, 3);
254         buff[3] = ' ';
255         do {
256             if (APR_SUCCESS != (rv = ap_proxy_string_read(ftp_ctrl, bb, response, sizeof(response), &eos))) {
257                 return -1;
258             }
259             mb = apr_cpystrn(mb, response + (' ' == response[0] ? 1 : 4), me - mb);
260         } while (memcmp(response, buff, 4) != 0);
261     }
262
263     return status;
264 }
265
266 /* this is a filter that turns a raw ASCII directory listing into pretty HTML */
267
268 /* ideally, mod_proxy should simply send the raw directory list up the filter
269  * stack to mod_autoindex, which in theory should turn the raw ascii into
270  * pretty html along with all the bells and whistles it provides...
271  *
272  * all in good time...! :)
273  */
274
275 typedef struct {
276     apr_bucket_brigade *in;
277     char buffer[MAX_STRING_LEN];
278     enum {
279         HEADER, BODY, FOOTER
280     }    state;
281 }      proxy_dir_ctx_t;
282
283 /* fallback regex for ls -s1;  ($0..$2) == 3 */
284 #define LS_REG_PATTERN "^ *([0-9]+) +([^ ]+)$"
285 #define LS_REG_MATCH   3
286
287 apr_status_t ap_proxy_send_dir_filter(ap_filter_t *f, apr_bucket_brigade *in)
288 {
289     request_rec *r = f->r;
290     conn_rec *c = r->connection;
291     apr_pool_t *p = r->pool;
292     apr_bucket_brigade *out = apr_brigade_create(p, c->bucket_alloc);
293     apr_status_t rv;
294
295     register int n;
296     char *dir, *path, *reldir, *site, *str, *type;
297
298     const char *pwd = apr_table_get(r->notes, "Directory-PWD");
299     const char *readme = apr_table_get(r->notes, "Directory-README");
300
301     proxy_dir_ctx_t *ctx = f->ctx;
302
303     if (!ctx) {
304         f->ctx = ctx = apr_pcalloc(p, sizeof(*ctx));
305         ctx->in = apr_brigade_create(p, c->bucket_alloc);
306         ctx->buffer[0] = 0;
307         ctx->state = HEADER;
308     }
309
310     /* combine the stored and the new */
311     APR_BRIGADE_CONCAT(ctx->in, in);
312
313     if (HEADER == ctx->state) {
314
315         /* basedir is either "", or "/%2f" for the "squid %2f hack" */
316         const char *basedir = "";  /* By default, path is relative to the $HOME dir */
317         char *wildcard = NULL;
318
319         /* Save "scheme://site" prefix without password */
320         site = apr_uri_unparse(p, &f->r->parsed_uri, APR_URI_UNP_OMITPASSWORD | APR_URI_UNP_OMITPATHINFO);
321         /* ... and path without query args */
322         path = apr_uri_unparse(p, &f->r->parsed_uri, APR_URI_UNP_OMITSITEPART | APR_URI_UNP_OMITQUERY);
323
324         /* If path began with /%2f, change the basedir */
325         if (strncasecmp(path, "/%2f", 4) == 0) {
326             basedir = "/%2f";
327         }
328
329         /* Strip off a type qualifier. It is ignored for dir listings */
330         if ((type = strstr(path, ";type=")) != NULL)
331             *type++ = '\0';
332
333         (void)decodeenc(path);
334
335         while (path[1] == '/') /* collapse multiple leading slashes to one */
336             ++path;
337
338         reldir = strrchr(path, '/');
339         if (reldir != NULL && ftp_check_globbingchars(reldir)) {
340             wildcard = &reldir[1];
341             reldir[0] = '\0'; /* strip off the wildcard suffix */
342         }
343
344         /* Copy path, strip (all except the last) trailing slashes */
345         /* (the trailing slash is needed for the dir component loop below) */
346         path = dir = apr_pstrcat(p, path, "/", NULL);
347         for (n = strlen(path); n > 1 && path[n - 1] == '/' && path[n - 2] == '/'; --n)
348             path[n - 1] = '\0';
349
350         /* Add a link to the root directory (if %2f hack was used) */
351         str = (basedir[0] != '\0') ? "<a href=\"/%2f/\">%2f</a>/" : "";
352
353         /* print "ftp://host/" */
354         str = apr_psprintf(p, DOCTYPE_HTML_3_2
355                 "<html>\n <head>\n  <title>%s%s%s</title>\n"
356                 " </head>\n"
357                 " <body>\n  <h2>Directory of "
358                 "<a href=\"/\">%s</a>/%s",
359                 site, basedir, ap_escape_html(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             wildcard = ap_escape_html(p, wildcard);
386             APR_BRIGADE_INSERT_TAIL(out, apr_bucket_pool_create(wildcard,
387                                                            strlen(wildcard), p,
388                                                            c->bucket_alloc));
389         }
390
391         /* If the caller has determined the current directory, and it differs */
392         /* from what the client requested, then show the real name */
393         if (pwd == NULL || strncmp(pwd, path, strlen(pwd)) == 0) {
394             str = apr_psprintf(p, "</h2>\n\n  <hr />\n\n<pre>");
395         }
396         else {
397             str = apr_psprintf(p, "</h2>\n\n(%s)\n\n  <hr />\n\n<pre>",
398                                ap_escape_html(p, pwd));
399         }
400         APR_BRIGADE_INSERT_TAIL(out, apr_bucket_pool_create(str, strlen(str),
401                                                            p, c->bucket_alloc));
402
403         /* print README */
404         if (readme) {
405             str = apr_psprintf(p, "%s\n</pre>\n\n<hr />\n\n<pre>\n",
406                                ap_escape_html(p, readme));
407
408             APR_BRIGADE_INSERT_TAIL(out, apr_bucket_pool_create(str,
409                                                            strlen(str), p,
410                                                            c->bucket_alloc));
411         }
412
413         /* make sure page intro gets sent out */
414         APR_BRIGADE_INSERT_TAIL(out, apr_bucket_flush_create(c->bucket_alloc));
415         if (APR_SUCCESS != (rv = ap_pass_brigade(f->next, out))) {
416             return rv;
417         }
418         apr_brigade_cleanup(out);
419
420         ctx->state = BODY;
421     }
422
423     /* loop through each line of directory */
424     while (BODY == ctx->state) {
425         char *filename;
426         int found = 0;
427         int eos = 0;
428
429         regex_t *re = NULL;
430         regmatch_t re_result[LS_REG_MATCH];
431
432         /* Compile the output format of "ls -s1" as a fallback for non-unix ftp listings */
433         re = ap_pregcomp(p, LS_REG_PATTERN, REG_EXTENDED);
434         ap_assert(re != NULL);
435
436         /* get a complete line */
437         /* if the buffer overruns - throw data away */
438         while (!found && !APR_BRIGADE_EMPTY(ctx->in)) {
439             char *pos, *response;
440             apr_size_t len, max;
441             apr_bucket *e;
442
443             e = APR_BRIGADE_FIRST(ctx->in);
444             if (APR_BUCKET_IS_EOS(e)) {
445                 eos = 1;
446                 break;
447             }
448             if (APR_SUCCESS != (rv = apr_bucket_read(e, (const char **)&response, &len, APR_BLOCK_READ))) {
449                 return rv;
450             }
451             pos = memchr(response, APR_ASCII_LF, len);
452             if (pos != NULL) {
453                 if ((response + len) != (pos + 1)) {
454                     len = pos - response + 1;
455                     apr_bucket_split(e, pos - response + 1);
456                 }
457                 found = 1;
458             }
459             max = sizeof(ctx->buffer) - strlen(ctx->buffer) - 1;
460             if (len > max) {
461                 len = max;
462             }
463
464             /* len+1 to leave space for the trailing nil char */
465             apr_cpystrn(ctx->buffer+strlen(ctx->buffer), response, len+1);
466
467             APR_BUCKET_REMOVE(e);
468             apr_bucket_destroy(e);
469         }
470
471         /* EOS? jump to footer */
472         if (eos) {
473             ctx->state = FOOTER;
474             break;
475         }
476
477         /* not complete? leave and try get some more */
478         if (!found) {
479             return APR_SUCCESS;
480         }
481
482         {
483             apr_size_t n = strlen(ctx->buffer);
484             if (ctx->buffer[n-1] == CRLF[1])  /* strip trailing '\n' */
485                 ctx->buffer[--n] = '\0';
486             if (ctx->buffer[n-1] == CRLF[0])  /* strip trailing '\r' if present */
487                 ctx->buffer[--n] = '\0';
488         }
489
490         /* a symlink? */
491         if (ctx->buffer[0] == 'l' && (filename = strstr(ctx->buffer, " -> ")) != NULL) {
492             char *link_ptr = filename;
493
494             do {
495                 filename--;
496             } while (filename[0] != ' ' && filename > ctx->buffer);
497             if (filename > ctx->buffer)
498                 *(filename++) = '\0';
499             *(link_ptr++) = '\0';
500             str = apr_psprintf(p, "%s <a href=\"%s\">%s %s</a>\n",
501                                ap_escape_html(p, ctx->buffer),
502                                ap_escape_uri(p, filename),
503                                ap_escape_html(p, filename),
504                                ap_escape_html(p, link_ptr));
505         }
506
507         /* a directory/file? */
508         else if (ctx->buffer[0] == 'd' || ctx->buffer[0] == '-' || ctx->buffer[0] == 'l' || apr_isdigit(ctx->buffer[0])) {
509             int searchidx = 0;
510             char *searchptr = NULL;
511             int firstfile = 1;
512             if (apr_isdigit(ctx->buffer[0])) {  /* handle DOS dir */
513                 searchptr = strchr(ctx->buffer, '<');
514                 if (searchptr != NULL)
515                     *searchptr = '[';
516                 searchptr = strchr(ctx->buffer, '>');
517                 if (searchptr != NULL)
518                     *searchptr = ']';
519             }
520
521             filename = strrchr(ctx->buffer, ' ');
522             *(filename++) = '\0';
523
524             /* handle filenames with spaces in 'em */
525             if (!strcmp(filename, ".") || !strcmp(filename, "..") || firstfile) {
526                 firstfile = 0;
527                 searchidx = filename - ctx->buffer;
528             }
529             else if (searchidx != 0 && ctx->buffer[searchidx] != 0) {
530                 *(--filename) = ' ';
531                 ctx->buffer[searchidx - 1] = '\0';
532                 filename = &ctx->buffer[searchidx];
533             }
534
535             /* Append a slash to the HREF link for directories */
536             if (!strcmp(filename, ".") || !strcmp(filename, "..") || ctx->buffer[0] == 'd') {
537                 str = apr_psprintf(p, "%s <a href=\"%s/\">%s</a>\n",
538                                    ap_escape_html(p, ctx->buffer),
539                                    ap_escape_uri(p, filename),
540                                    ap_escape_html(p, filename));
541             }
542             else {
543                 str = apr_psprintf(p, "%s <a href=\"%s\">%s</a>\n",
544                                    ap_escape_html(p, ctx->buffer),
545                                    ap_escape_uri(p, filename),
546                                    ap_escape_html(p, filename));
547             }
548         }
549         /* Try a fallback for listings in the format of "ls -s1" */
550         else if (0 == ap_regexec(re, ctx->buffer, LS_REG_MATCH, re_result, 0)) {
551
552             filename = apr_pstrndup(p, &ctx->buffer[re_result[2].rm_so], re_result[2].rm_eo - re_result[2].rm_so);
553
554             str = apr_pstrcat(p, ap_escape_html(p, apr_pstrndup(p, ctx->buffer, re_result[2].rm_so)),
555                               "<a href=\"", ap_escape_uri(p, filename), "\">",
556                               ap_escape_html(p, filename), "</a>\n", NULL);
557         }
558         else {
559             strcat(ctx->buffer, "\n"); /* re-append the newline */
560             str = ap_escape_html(p, ctx->buffer);
561         }
562
563         /* erase buffer for next time around */
564         ctx->buffer[0] = 0;
565
566         APR_BRIGADE_INSERT_TAIL(out, apr_bucket_pool_create(str, strlen(str), p,
567                                                             c->bucket_alloc));
568         APR_BRIGADE_INSERT_TAIL(out, apr_bucket_flush_create(c->bucket_alloc));
569         if (APR_SUCCESS != (rv = ap_pass_brigade(f->next, out))) {
570             return rv;
571         }
572         apr_brigade_cleanup(out);
573
574     }
575
576     if (FOOTER == ctx->state) {
577         str = apr_psprintf(p, "</pre>\n\n  <hr />\n\n  %s\n\n </body>\n</html>\n", ap_psignature("", r));
578         APR_BRIGADE_INSERT_TAIL(out, apr_bucket_pool_create(str, strlen(str), p,
579                                                             c->bucket_alloc));
580         APR_BRIGADE_INSERT_TAIL(out, apr_bucket_flush_create(c->bucket_alloc));
581         APR_BRIGADE_INSERT_TAIL(out, apr_bucket_eos_create(c->bucket_alloc));
582         if (APR_SUCCESS != (rv = ap_pass_brigade(f->next, out))) {
583             return rv;
584         }
585         apr_brigade_destroy(out);
586     }
587
588     return APR_SUCCESS;
589 }
590
591 /* Parse EPSV reply and return port, or zero on error. */
592 static apr_port_t parse_epsv_reply(const char *reply)
593 {
594     const char *p;
595     char *ep;
596     long port;
597
598     /* Reply syntax per RFC 2428: "229 blah blah (|||port|)" where '|'
599      * can be any character in ASCII from 33-126, obscurely.  Verify
600      * the syntax. */
601     p = ap_strchr_c(reply, '(');
602     if (p == NULL || !p[1] || p[1] != p[2] || p[1] != p[3]
603         || p[4] == p[1]) {
604         return 0;
605     }
606
607     errno = 0;
608     port = strtol(p + 4, &ep, 10);
609     if (errno || port < 1 || port > 65535 || ep[0] != p[1] || ep[1] != ')') {
610         return 0;
611     }
612
613     return (apr_port_t)port;
614 }
615
616 /*
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)
620  */
621 static int
622 proxy_ftp_command(const char *cmd, request_rec *r, conn_rec *ftp_ctrl,
623                   apr_bucket_brigade *bb, char **pmessage)
624 {
625     char *crlf;
626     int rc;
627     char message[HUGE_STRING_LEN];
628
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);
635
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);
645     }
646
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);
655
656     if (pmessage != NULL)
657         *pmessage = apr_pstrdup(r->pool, message);
658
659     return rc;
660 }
661
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)
665 {
666     char old_type[2] = { 'A', '\0' }; /* After logon, mode is ASCII */
667     int ret = HTTP_OK;
668     int rc;
669
670     /* set desired type */
671     old_type[0] = xfer_type;
672
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");
685     }
686     else if (rc != 200 && rc != 504) {
687         ret = ap_proxyerror(r, HTTP_BAD_GATEWAY,
688                              "Unable to set transfer type");
689     }
690 /* Allow not implemented */
691     else if (rc == 504)
692         /* ignore it silently */;
693
694     return ret;
695 }
696
697
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)
700 {
701     char *cwd = NULL;
702     char *ftpmessage = NULL;
703
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;
718
719         case 257: {
720             const char *dirp = ftpmessage;
721             cwd = ap_getword_conf(r->pool, &dirp);
722         }
723     }
724     return cwd;
725 }
726
727
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-)
734  */
735 static int ftp_unauthorized(request_rec *r, int log_it)
736 {
737     r->proxyreq = PROXYREQ_NONE;
738     /*
739      * Log failed requests if they supplied a password (log username/password
740      * guessing attempts)
741      */
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));
747
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));
753
754     return HTTP_UNAUTHORIZED;
755 }
756
757
758 /*
759  * Handles direct access of ftp:// URLs
760  * Original (Non-PASV) version from
761  * Troy Morrison <spiffnet@zoom.com>
762  * PASV added by Chuck
763  * Filters by [Graham Leggett <minfrin@sharp.fm>]
764  */
765 int ap_proxy_ftp_handler(request_rec *r, proxy_server_conf *conf,
766                              char *url, const char *proxyhost,
767                              apr_port_t proxyport)
768 {
769     apr_pool_t *p = r->pool;
770     conn_rec *c = r->connection;
771     proxy_conn_rec *backend;
772     apr_socket_t *sock, *local_sock, *data_sock = NULL;
773     apr_sockaddr_t *connect_addr;
774     apr_status_t rv;
775     conn_rec *origin, *data = NULL;
776     int err;
777     apr_bucket_brigade *bb = apr_brigade_create(p, c->bucket_alloc);
778     char *buf, *connectname;
779     apr_port_t connectport;
780     char buffer[MAX_STRING_LEN];
781     char *ftpmessage = NULL;
782     char *path, *strp, *type_suffix, *cwd = NULL;
783     apr_uri_t uri; 
784     char *user = NULL;
785 /*    char *account = NULL; how to supply an account in a URL? */
786     const char *password = NULL;
787     int len, rc;
788     int one = 1;
789     char *size = NULL;
790     apr_socket_t *origin_sock = NULL;
791     char xfer_type = 'A'; /* after ftp login, the default is ASCII */
792     int  dirlisting = 0;
793 #if defined(USE_MDTM) && (defined(HAVE_TIMEGM) || defined(HAVE_GMTOFF))
794     apr_time_t mtime = 0L;
795 #endif
796
797     /* stuff for PASV mode */
798     int connect = 0, use_port = 0;
799     char dates[APR_RFC822_DATE_LEN];
800
801     /* is this for us? */
802     if (proxyhost) {
803         ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, r->server,
804                      "proxy: FTP: declining URL %s - proxyhost %s specified:", url, proxyhost);
805         return DECLINED;        /* proxy connections are via HTTP */
806     }
807     if (strncasecmp(url, "ftp:", 4)) {
808         ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, r->server,
809                      "proxy: FTP: declining URL %s - not ftp:", url);
810         return DECLINED;        /* only interested in FTP */
811     }
812     ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, r->server,
813                  "proxy: FTP: serving URL %s", url);
814
815     /* create space for state information */
816     backend = (proxy_conn_rec *) ap_get_module_config(c->conn_config, &proxy_ftp_module);
817     if (!backend) {
818         backend = apr_pcalloc(c->pool, sizeof(proxy_conn_rec));
819         backend->connection = NULL;
820         backend->hostname = NULL;
821         backend->port = 0;
822         ap_set_module_config(c->conn_config, &proxy_ftp_module, backend);
823     }
824     if (backend->connection)
825         origin_sock = ap_get_module_config(backend->connection->conn_config, &core_module);
826
827
828     /*
829      * I: Who Do I Connect To? -----------------------
830      *
831      * Break up the URL to determine the host to connect to
832      */
833
834     /* we only support GET and HEAD */
835     if (r->method_number != M_GET)
836         return HTTP_NOT_IMPLEMENTED;
837
838     /* We break the URL into host, port, path-search */
839     if (r->parsed_uri.hostname == NULL) {
840         if (APR_SUCCESS != apr_uri_parse(p, url, &uri)) {
841             return ap_proxyerror(r, HTTP_BAD_REQUEST,
842                 apr_psprintf(p, "URI cannot be parsed: %s", url));
843         }
844         connectname = uri.hostname;
845         connectport = uri.port;
846         path = apr_pstrdup(p, uri.path);
847     }
848     else {
849         connectname = r->parsed_uri.hostname;
850         connectport = r->parsed_uri.port;
851         path = apr_pstrdup(p, r->parsed_uri.path);
852     }
853     if (connectport == 0) {
854         connectport = apr_uri_port_of_scheme("ftp");
855     }
856     path = (path != NULL && path[0] != '\0') ? &path[1] : "";
857
858     type_suffix = strchr(path, ';');
859     if (type_suffix != NULL)
860         *(type_suffix++) = '\0';
861
862     if (type_suffix != NULL && strncmp(type_suffix, "type=", 5) == 0
863         && apr_isalpha(type_suffix[5])) {
864         /* "type=d" forces a dir listing.
865          * The other types (i|a|e) are directly used for the ftp TYPE command
866          */
867         if ( ! (dirlisting = (apr_tolower(type_suffix[5]) == 'd')))
868             xfer_type = apr_toupper(type_suffix[5]);
869
870         /* Check valid types, rather than ignoring invalid types silently: */
871         if (strchr("AEI", xfer_type) == NULL)
872             return ap_proxyerror(r, HTTP_BAD_REQUEST, apr_pstrcat(r->pool,
873                                     "ftp proxy supports only types 'a', 'i', or 'e': \"",
874                                     type_suffix, "\" is invalid.", NULL));
875     }
876     else {
877         /* make binary transfers the default */
878         xfer_type = 'I';
879     }
880
881
882     /*
883      * The "Authorization:" header must be checked first. We allow the user
884      * to "override" the URL-coded user [ & password ] in the Browsers'
885      * User&Password Dialog. NOTE that this is only marginally more secure
886      * than having the password travel in plain as part of the URL, because
887      * Basic Auth simply uuencodes the plain text password. But chances are
888      * still smaller that the URL is logged regularly.
889      */
890     if ((password = apr_table_get(r->headers_in, "Authorization")) != NULL
891         && strcasecmp(ap_getword(r->pool, &password, ' '), "Basic") == 0
892         && (password = ap_pbase64decode(r->pool, password))[0] != ':') {
893         /* Check the decoded string for special characters. */
894         if (!ftp_check_string(password)) {
895             return ap_proxyerror(r, HTTP_BAD_REQUEST, 
896                                  "user credentials contained invalid character");
897         } 
898         /*
899          * Note that this allocation has to be made from r->connection->pool
900          * because it has the lifetime of the connection.  The other
901          * allocations are temporary and can be tossed away any time.
902          */
903         user = ap_getword_nulls(r->connection->pool, &password, ':');
904         r->ap_auth_type = "Basic";
905         r->user = r->parsed_uri.user = user;
906     }
907     else if ((user = r->parsed_uri.user) != NULL) {
908         user = apr_pstrdup(p, user);
909         decodeenc(user);
910         if ((password = r->parsed_uri.password) != NULL) {
911             char *tmp = apr_pstrdup(p, password);
912             decodeenc(tmp);
913             password = tmp;
914         }
915     }
916     else {
917         user = "anonymous";
918         password = "apache-proxy@";
919     }
920
921     ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, r->server,
922        "proxy: FTP: connecting %s to %s:%d", url, connectname, connectport);
923
924     /* do a DNS lookup for the destination host */
925     err = apr_sockaddr_info_get(&connect_addr, connectname, APR_UNSPEC, connectport, 0, p);
926
927     /* check if ProxyBlock directive on this host */
928     if (OK != ap_proxy_checkproxyblock(r, conf, connect_addr)) {
929         return ap_proxyerror(r, HTTP_FORBIDDEN,
930                              "Connect to remote machine blocked");
931     }
932
933
934     /*
935      * II: Make the Connection -----------------------
936      *
937      * We have determined who to connect to. Now make the connection.
938      */
939
940     /*
941      * get all the possible IP addresses for the destname and loop through
942      * them until we get a successful connection
943      */
944     if (APR_SUCCESS != err) {
945         return ap_proxyerror(r, HTTP_BAD_GATEWAY, apr_pstrcat(p,
946                                                  "DNS lookup failure for: ",
947                                                         connectname, NULL));
948     }
949
950     /*
951      * At this point we have a list of one or more IP addresses of the
952      * machine to connect to. If configured, reorder this list so that the
953      * "best candidate" is first try. "best candidate" could mean the least
954      * loaded server, the fastest responding server, whatever.
955      *
956      * For now we do nothing, ie we get DNS round robin. XXX FIXME
957      */
958
959
960     /* try each IP address until we connect successfully */
961     {
962         int failed = 1;
963         while (connect_addr) {
964
965             if ((rv = apr_socket_create(&sock, connect_addr->family, SOCK_STREAM, r->pool)) != APR_SUCCESS) {
966                 ap_log_rerror(APLOG_MARK, APLOG_ERR, rv, r,
967                               "proxy: FTP: error creating socket");
968                 connect_addr = connect_addr->next;
969                 continue;
970             }
971
972 #if !defined(TPF) && !defined(BEOS)
973             if (conf->recv_buffer_size > 0
974                 && (rv = apr_socket_opt_set(sock, APR_SO_RCVBUF,
975                                             conf->recv_buffer_size))) {
976                 ap_log_rerror(APLOG_MARK, APLOG_ERR, rv, r,
977                               "apr_socket_opt_set(APR_SO_RCVBUF): Failed to set ProxyReceiveBufferSize, using default");
978             }
979 #endif
980
981             if (APR_SUCCESS != (rv = apr_socket_opt_set(sock, APR_SO_REUSEADDR, one))) {
982                 apr_socket_close(sock);
983 #ifndef _OSD_POSIX              /* BS2000 has this option "always on" */
984                 ap_log_rerror(APLOG_MARK, APLOG_ERR, rv, r,
985                               "proxy: FTP: error setting reuseaddr option: apr_socket_opt_set(APR_SO_REUSEADDR)");
986                 connect_addr = connect_addr->next;
987                 continue;
988 #endif                          /* _OSD_POSIX */
989             }
990
991             /* Set a timeout on the socket */
992             if (conf->timeout_set == 1) {
993                 apr_socket_timeout_set(sock, conf->timeout);
994             }
995             else {
996                 apr_socket_timeout_set(sock, r->server->timeout);
997             }
998
999             ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, r->server,
1000                          "proxy: FTP: fam %d socket created, trying to connect to %pI (%s)...", 
1001                          connect_addr->family, connect_addr, connectname);
1002
1003             /* make the connection out of the socket */
1004             rv = apr_connect(sock, connect_addr);
1005
1006             /* if an error occurred, loop round and try again */
1007             if (rv != APR_SUCCESS) {
1008                 apr_socket_close(sock);
1009                 ap_log_error(APLOG_MARK, APLOG_ERR, rv, r->server,
1010                              "proxy: FTP: attempt to connect to %pI (%s) failed", connect_addr, connectname);
1011                 connect_addr = connect_addr->next;
1012                 continue;
1013             }
1014
1015             /* if we get here, all is well */
1016             failed = 0;
1017             break;
1018         }
1019
1020         /* handle a permanent error from the above loop */
1021         if (failed) {
1022             return ap_proxyerror(r, HTTP_BAD_GATEWAY, apr_psprintf(r->pool,
1023                           "Could not connect to remote machine: %s port %d",
1024                                                  connectname, connectport));
1025         }
1026     }
1027
1028     /* the socket is now open, create a new connection */
1029     origin = ap_run_create_connection(p, r->server, sock, r->connection->id,
1030                                       r->connection->sbh, c->bucket_alloc);
1031     if (!origin) {
1032         /*
1033          * the peer reset the connection already; ap_run_create_connection() closed
1034          * the socket
1035          */
1036         ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, r->server,
1037                      "proxy: FTP: an error occurred creating a new connection to %pI (%s)", connect_addr, connectname);
1038         return HTTP_INTERNAL_SERVER_ERROR;
1039     }
1040
1041     /* if a keepalive connection is floating around, close it first! */
1042     /* we might support ftp keepalives later, but not now... */
1043     if (backend->connection) {
1044         apr_socket_close(origin_sock);
1045         backend->connection = NULL;
1046         origin_sock = NULL;
1047     }
1048
1049     ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, r->server,
1050                  "proxy: FTP: control connection complete");
1051
1052
1053     /*
1054      * III: Send Control Request -------------------------
1055      *
1056      * Log into the ftp server, send the username & password, change to the
1057      * correct directory...
1058      */
1059
1060     /* set up the connection filters */
1061     rc = ap_run_pre_connection(origin, sock);
1062     if (rc != OK && rc != DONE) {
1063         origin->aborted = 1;
1064         ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, r->server,
1065                      "proxy: FTP: pre_connection setup failed (%d)",
1066                      rc);
1067         return rc;
1068     }
1069
1070     /* possible results: */
1071     /* 120 Service ready in nnn minutes. */
1072     /* 220 Service ready for new user. */
1073     /* 421 Service not available, closing control connection. */
1074     rc = proxy_ftp_command(NULL, r, origin, bb, &ftpmessage);
1075     if (rc == -1 || rc == 421) {
1076         return ap_proxyerror(r, HTTP_BAD_GATEWAY, "Error reading from remote server");
1077     }
1078     if (rc == 120) {
1079         /*
1080          * RFC2616 states: 14.37 Retry-After
1081          *
1082          * The Retry-After response-header field can be used with a 503 (Service
1083          * Unavailable) response to indicate how long the service is expected
1084          * to be unavailable to the requesting client. [...] The value of
1085          * this field can be either an HTTP-date or an integer number of
1086          * seconds (in decimal) after the time of the response. Retry-After
1087          * = "Retry-After" ":" ( HTTP-date | delta-seconds )
1088          */
1089         char *secs_str = ftpmessage;
1090         time_t secs;
1091
1092         /* Look for a number, preceded by whitespace */
1093         while (*secs_str)
1094             if ((secs_str==ftpmessage || apr_isspace(secs_str[-1])) &&
1095                 apr_isdigit(secs_str[0]))
1096                 break;
1097         if (*secs_str != '\0') {
1098             secs = atol(secs_str);
1099             apr_table_add(r->headers_out, "Retry-After",
1100                           apr_psprintf(p, "%lu", (unsigned long)(60 * secs)));
1101         }
1102         return ap_proxyerror(r, HTTP_SERVICE_UNAVAILABLE, ftpmessage);
1103     }
1104     if (rc != 220) {
1105         return ap_proxyerror(r, HTTP_BAD_GATEWAY, ftpmessage);
1106     }
1107
1108     rc = proxy_ftp_command(apr_pstrcat(p, "USER ", user, CRLF, NULL),
1109                            r, origin, bb, &ftpmessage);
1110     /* possible results; 230, 331, 332, 421, 500, 501, 530 */
1111     /* states: 1 - error, 2 - success; 3 - send password, 4,5 fail */
1112     /* 230 User logged in, proceed. */
1113     /* 331 User name okay, need password. */
1114     /* 332 Need account for login. */
1115     /* 421 Service not available, closing control connection. */
1116     /* 500 Syntax error, command unrecognized. */
1117     /* (This may include errors such as command line too long.) */
1118     /* 501 Syntax error in parameters or arguments. */
1119     /* 530 Not logged in. */
1120     if (rc == -1 || rc == 421) {
1121         return ap_proxyerror(r, HTTP_BAD_GATEWAY, "Error reading from remote server");
1122     }
1123     if (rc == 530) {
1124         return ftp_unauthorized(r, 1);  /* log it: user name guessing
1125                                          * attempt? */
1126     }
1127     if (rc != 230 && rc != 331) {
1128         return ap_proxyerror(r, HTTP_BAD_GATEWAY, ftpmessage);
1129     }
1130
1131     if (rc == 331) {            /* send password */
1132         if (password == NULL) {
1133             return ftp_unauthorized(r, 0);
1134         }
1135
1136         rc = proxy_ftp_command(apr_pstrcat(p, "PASS ", password, CRLF, NULL),
1137                            r, origin, bb, &ftpmessage);
1138         /* possible results 202, 230, 332, 421, 500, 501, 503, 530 */
1139         /* 230 User logged in, proceed. */
1140         /* 332 Need account for login. */
1141         /* 421 Service not available, closing control connection. */
1142         /* 500 Syntax error, command unrecognized. */
1143         /* 501 Syntax error in parameters or arguments. */
1144         /* 503 Bad sequence of commands. */
1145         /* 530 Not logged in. */
1146         if (rc == -1 || rc == 421) {
1147             return ap_proxyerror(r, HTTP_BAD_GATEWAY,
1148                                  "Error reading from remote server");
1149         }
1150         if (rc == 332) {
1151             return ap_proxyerror(r, HTTP_UNAUTHORIZED,
1152                   apr_pstrcat(p, "Need account for login: ", ftpmessage, NULL));
1153         }
1154         /* @@@ questionable -- we might as well return a 403 Forbidden here */
1155         if (rc == 530) {
1156             return ftp_unauthorized(r, 1);      /* log it: passwd guessing
1157                                                  * attempt? */
1158         }
1159         if (rc != 230 && rc != 202) {
1160             return ap_proxyerror(r, HTTP_BAD_GATEWAY, ftpmessage);
1161         }
1162     }
1163     apr_table_set(r->notes, "Directory-README", ftpmessage);
1164
1165
1166     /* Special handling for leading "%2f": this enforces a "cwd /"
1167      * out of the $HOME directory which was the starting point after login
1168      */
1169     if (strncasecmp(path, "%2f", 3) == 0) {
1170         path += 3;
1171         while (*path == '/') /* skip leading '/' (after root %2f) */
1172             ++path;
1173
1174         rc = proxy_ftp_command("CWD /" CRLF, r, origin, bb, &ftpmessage);
1175         if (rc == -1 || rc == 421)
1176             return ap_proxyerror(r, HTTP_BAD_GATEWAY,
1177                                  "Error reading from remote server");
1178     }
1179
1180     /*
1181      * set the directory (walk directory component by component): this is
1182      * what we must do if we don't know the OS type of the remote machine
1183      */
1184     for (;;) {
1185         strp = strchr(path, '/');
1186         if (strp == NULL)
1187             break;
1188         *strp = '\0';
1189
1190         len = decodeenc(path); /* Note! This decodes a %2f -> "/" */
1191
1192         if (strchr(path, '/')) { /* are there now any '/' characters? */
1193             return ap_proxyerror(r, HTTP_BAD_REQUEST,
1194                                  "Use of /%2f is only allowed at the base directory");
1195         }
1196
1197         /* NOTE: FTP servers do globbing on the path.
1198          * So we need to escape the URI metacharacters.
1199          * We use a special glob-escaping routine to escape globbing chars.
1200          * We could also have extended gen_test_char.c with a special T_ESCAPE_FTP_PATH
1201          */
1202         rc = proxy_ftp_command(apr_pstrcat(p, "CWD ",
1203                            ftp_escape_globbingchars(p, path), CRLF, NULL),
1204                            r, origin, bb, &ftpmessage);
1205         *strp = '/';
1206         /* responses: 250, 421, 500, 501, 502, 530, 550 */
1207         /* 250 Requested file action okay, completed. */
1208         /* 421 Service not available, closing control connection. */
1209         /* 500 Syntax error, command unrecognized. */
1210         /* 501 Syntax error in parameters or arguments. */
1211         /* 502 Command not implemented. */
1212         /* 530 Not logged in. */
1213         /* 550 Requested action not taken. */
1214         if (rc == -1 || rc == 421) {
1215             return ap_proxyerror(r, HTTP_BAD_GATEWAY,
1216                                  "Error reading from remote server");
1217         }
1218         if (rc == 550) {
1219             return ap_proxyerror(r, HTTP_NOT_FOUND, ftpmessage);
1220         }
1221         if (rc != 250) {
1222             return ap_proxyerror(r, HTTP_BAD_GATEWAY, ftpmessage);
1223         }
1224
1225         path = strp + 1;
1226     }
1227
1228     /*
1229      * IV: Make Data Connection? -------------------------
1230      *
1231      * Try EPSV, if that fails... try PASV, if that fails... try PORT.
1232      */
1233 /* this temporarily switches off EPSV/PASV */
1234 /*goto bypass;*/
1235
1236     /* set up data connection - EPSV */
1237     {
1238         apr_sockaddr_t *data_addr;
1239         char *data_ip;
1240         apr_port_t data_port;
1241
1242         /*
1243          * The EPSV command replaces PASV where both IPV4 and IPV6 is
1244          * supported. Only the port is returned, the IP address is always the
1245          * same as that on the control connection. Example: Entering Extended
1246          * Passive Mode (|||6446|)
1247          */
1248         rc = proxy_ftp_command("EPSV" CRLF,
1249                            r, origin, bb, &ftpmessage);
1250         /* possible results: 227, 421, 500, 501, 502, 530 */
1251         /* 227 Entering Passive Mode (h1,h2,h3,h4,p1,p2). */
1252         /* 421 Service not available, closing control connection. */
1253         /* 500 Syntax error, command unrecognized. */
1254         /* 501 Syntax error in parameters or arguments. */
1255         /* 502 Command not implemented. */
1256         /* 530 Not logged in. */
1257         if (rc == -1 || rc == 421) {
1258             return ap_proxyerror(r, HTTP_BAD_GATEWAY,
1259                                  "Error reading from remote server");
1260         }
1261         if (rc != 229 && rc != 500 && rc != 501 && rc != 502) {
1262             return ap_proxyerror(r, HTTP_BAD_GATEWAY, ftpmessage);
1263         }
1264         else if (rc == 229) {
1265             /* Parse the port out of the EPSV reply. */
1266             data_port = parse_epsv_reply(ftpmessage);
1267
1268             if (data_port) {
1269                 apr_sockaddr_t *epsv_addr;
1270
1271                 ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, r->server,
1272                        "proxy: FTP: EPSV contacting remote host on port %d",
1273                              data_port);
1274
1275                 if ((rv = apr_socket_create(&data_sock, connect_addr->family, SOCK_STREAM, r->pool)) != APR_SUCCESS) {
1276                     ap_log_rerror(APLOG_MARK, APLOG_ERR, rv, r,
1277                                   "proxy: FTP: error creating EPSV socket");
1278                     return HTTP_INTERNAL_SERVER_ERROR;
1279                 }
1280
1281 #if !defined (TPF) && !defined(BEOS)
1282                 if (conf->recv_buffer_size > 0 
1283                         && (rv = apr_socket_opt_set(data_sock, APR_SO_RCVBUF,
1284                                                     conf->recv_buffer_size))) {
1285                     ap_log_rerror(APLOG_MARK, APLOG_ERR, rv, r,
1286                                   "proxy: FTP: apr_socket_opt_set(SO_RCVBUF): Failed to set ProxyReceiveBufferSize, using default");
1287                 }
1288 #endif
1289
1290                 /* make the connection */
1291                 apr_socket_addr_get(&data_addr, APR_REMOTE, sock);
1292                 apr_sockaddr_ip_get(&data_ip, data_addr);
1293                 apr_sockaddr_info_get(&epsv_addr, data_ip, connect_addr->family, data_port, 0, p);
1294                 rv = apr_connect(data_sock, epsv_addr);
1295                 if (rv != APR_SUCCESS) {
1296                     ap_log_error(APLOG_MARK, APLOG_ERR, rv, r->server,
1297                                  "proxy: FTP: EPSV attempt to connect to %pI failed - Firewall/NAT?", epsv_addr);
1298                     return ap_proxyerror(r, HTTP_BAD_GATEWAY, apr_psprintf(r->pool,
1299                                                                            "EPSV attempt to connect to %pI failed - firewall/NAT?", epsv_addr));
1300                 }
1301                 else {
1302                     connect = 1;
1303                 }
1304             }
1305         }
1306     }
1307
1308     /* set up data connection - PASV */
1309     if (!connect) {
1310         rc = proxy_ftp_command("PASV" CRLF,
1311                            r, origin, bb, &ftpmessage);
1312         /* possible results: 227, 421, 500, 501, 502, 530 */
1313         /* 227 Entering Passive Mode (h1,h2,h3,h4,p1,p2). */
1314         /* 421 Service not available, closing control connection. */
1315         /* 500 Syntax error, command unrecognized. */
1316         /* 501 Syntax error in parameters or arguments. */
1317         /* 502 Command not implemented. */
1318         /* 530 Not logged in. */
1319         if (rc == -1 || rc == 421) {
1320             return ap_proxyerror(r, HTTP_BAD_GATEWAY,
1321                                  "Error reading from remote server");
1322         }
1323         if (rc != 227 && rc != 502) {
1324             return ap_proxyerror(r, HTTP_BAD_GATEWAY, ftpmessage);
1325         }
1326         else if (rc == 227) {
1327             unsigned int h0, h1, h2, h3, p0, p1;
1328             char *pstr;
1329             char *tok_cntx;
1330
1331 /* FIXME: Check PASV against RFC1123 */
1332
1333             pstr = ftpmessage;
1334             pstr = apr_strtok(pstr, " ", &tok_cntx);    /* separate result code */
1335             if (pstr != NULL) {
1336                 if (*(pstr + strlen(pstr) + 1) == '=') {
1337                     pstr += strlen(pstr) + 2;
1338                 }
1339                 else {
1340                     pstr = apr_strtok(NULL, "(", &tok_cntx);    /* separate address &
1341                                                                  * port params */
1342                     if (pstr != NULL)
1343                         pstr = apr_strtok(NULL, ")", &tok_cntx);
1344                 }
1345             }
1346
1347 /* FIXME: Only supports IPV4 - fix in RFC2428 */
1348
1349             if (pstr != NULL && (sscanf(pstr,
1350                  "%d,%d,%d,%d,%d,%d", &h3, &h2, &h1, &h0, &p1, &p0) == 6)) {
1351
1352                 apr_sockaddr_t *pasv_addr;
1353                 apr_port_t pasvport = (p1 << 8) + p0;
1354                 ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, r->server,
1355                           "proxy: FTP: PASV contacting host %d.%d.%d.%d:%d",
1356                              h3, h2, h1, h0, pasvport);
1357
1358                 if ((rv = apr_socket_create(&data_sock, connect_addr->family, SOCK_STREAM, r->pool)) != APR_SUCCESS) {
1359                     ap_log_rerror(APLOG_MARK, APLOG_ERR, rv, r,
1360                                   "proxy: error creating PASV socket");
1361                     return HTTP_INTERNAL_SERVER_ERROR;
1362                 }
1363
1364 #if !defined (TPF) && !defined(BEOS)
1365                 if (conf->recv_buffer_size > 0 
1366                         && (rv = apr_socket_opt_set(data_sock, APR_SO_RCVBUF,
1367                                                     conf->recv_buffer_size))) {
1368                     ap_log_rerror(APLOG_MARK, APLOG_ERR, rv, r,
1369                                   "proxy: FTP: apr_socket_opt_set(SO_RCVBUF): Failed to set ProxyReceiveBufferSize, using default");
1370                 }
1371 #endif
1372
1373                 /* make the connection */
1374                 apr_sockaddr_info_get(&pasv_addr, apr_psprintf(p, "%d.%d.%d.%d", h3, h2, h1, h0), connect_addr->family, pasvport, 0, p);
1375                 rv = apr_connect(data_sock, pasv_addr);
1376                 if (rv != APR_SUCCESS) {
1377                     ap_log_error(APLOG_MARK, APLOG_ERR, rv, r->server,
1378                                  "proxy: FTP: PASV attempt to connect to %pI failed - Firewall/NAT?", pasv_addr);
1379                     return ap_proxyerror(r, HTTP_BAD_GATEWAY, apr_psprintf(r->pool,
1380                                                                            "PASV attempt to connect to %pI failed - firewall/NAT?", pasv_addr));
1381                 }
1382                 else {
1383                     connect = 1;
1384                 }
1385             }
1386         }
1387     }
1388 /*bypass:*/
1389
1390     /* set up data connection - PORT */
1391     if (!connect) {
1392         apr_sockaddr_t *local_addr;
1393         char *local_ip;
1394         apr_port_t local_port;
1395         unsigned int h0, h1, h2, h3, p0, p1;
1396
1397         if ((rv = apr_socket_create(&local_sock, connect_addr->family, SOCK_STREAM, r->pool)) != APR_SUCCESS) {
1398             ap_log_rerror(APLOG_MARK, APLOG_ERR, rv, r,
1399                           "proxy: FTP: error creating local socket");
1400             return HTTP_INTERNAL_SERVER_ERROR;
1401         }
1402         apr_socket_addr_get(&local_addr, APR_LOCAL, sock);
1403         apr_sockaddr_port_get(&local_port, local_addr);
1404         apr_sockaddr_ip_get(&local_ip, local_addr);
1405
1406         if ((rv = apr_socket_opt_set(local_sock, APR_SO_REUSEADDR, one)) 
1407                 != APR_SUCCESS) {
1408 #ifndef _OSD_POSIX              /* BS2000 has this option "always on" */
1409             ap_log_rerror(APLOG_MARK, APLOG_ERR, rv, r,
1410                           "proxy: FTP: error setting reuseaddr option");
1411             return HTTP_INTERNAL_SERVER_ERROR;
1412 #endif                          /* _OSD_POSIX */
1413         }
1414
1415         apr_sockaddr_info_get(&local_addr, local_ip, APR_UNSPEC, local_port, 0, r->pool);
1416
1417         if ((rv = apr_bind(local_sock, local_addr)) != APR_SUCCESS) {
1418             ap_log_rerror(APLOG_MARK, APLOG_ERR, rv, r,
1419             "proxy: FTP: error binding to ftp data socket %pI", local_addr);
1420             return HTTP_INTERNAL_SERVER_ERROR;
1421         }
1422
1423         /* only need a short queue */
1424         if ((rv = apr_listen(local_sock, 2)) != APR_SUCCESS) {
1425             ap_log_rerror(APLOG_MARK, APLOG_ERR, rv, r,
1426                           "proxy: FTP: error listening to ftp data socket %pI", local_addr);
1427             return HTTP_INTERNAL_SERVER_ERROR;
1428         }
1429
1430 /* FIXME: Sent PORT here */
1431
1432         if (local_ip && (sscanf(local_ip,
1433                                 "%d.%d.%d.%d", &h3, &h2, &h1, &h0) == 4)) {
1434             p1 = (local_port >> 8);
1435             p0 = (local_port & 0xFF);
1436
1437             rc = proxy_ftp_command(apr_psprintf(p, "PORT %d,%d,%d,%d,%d,%d" CRLF, h3, h2, h1, h0, p1, p0),
1438                            r, origin, bb, &ftpmessage);
1439             /* possible results: 200, 421, 500, 501, 502, 530 */
1440             /* 200 Command okay. */
1441             /* 421 Service not available, closing control connection. */
1442             /* 500 Syntax error, command unrecognized. */
1443             /* 501 Syntax error in parameters or arguments. */
1444             /* 502 Command not implemented. */
1445             /* 530 Not logged in. */
1446             if (rc == -1 || rc == 421) {
1447                 return ap_proxyerror(r, HTTP_BAD_GATEWAY,
1448                                      "Error reading from remote server");
1449             }
1450             if (rc != 200) {
1451                 return ap_proxyerror(r, HTTP_BAD_GATEWAY, buffer);
1452             }
1453
1454             /* signal that we must use the EPRT/PORT loop */
1455             use_port = 1;
1456         }
1457         else {
1458 /* IPV6 FIXME:
1459  * The EPRT command replaces PORT where both IPV4 and IPV6 is supported. The first
1460  * number (1,2) indicates the protocol type. Examples:
1461  *   EPRT |1|132.235.1.2|6275|
1462  *   EPRT |2|1080::8:800:200C:417A|5282|
1463  */
1464             return ap_proxyerror(r, HTTP_NOT_IMPLEMENTED, "Connect to IPV6 ftp server using EPRT not supported. Enable EPSV.");
1465         }
1466     }
1467
1468
1469     /*
1470      * V: Set The Headers -------------------
1471      *
1472      * Get the size of the request, set up the environment for HTTP.
1473      */
1474
1475     /* set request; "path" holds last path component */
1476     len = decodeenc(path);
1477
1478     if (strchr(path, '/')) { /* are there now any '/' characters? */
1479        return ap_proxyerror(r, HTTP_BAD_REQUEST,
1480                             "Use of /%2f is only allowed at the base directory");
1481     }
1482
1483     /* If len == 0 then it must be a directory (you can't RETR nothing)
1484      * Also, don't allow to RETR by wildcard. Instead, create a dirlisting
1485      */
1486     if (len == 0 || ftp_check_globbingchars(path)) {
1487         dirlisting = 1;
1488     }
1489     else {
1490         /* (from FreeBSD ftpd):
1491          * SIZE is not in RFC959, but Postel has blessed it and
1492          * it will be in the updated RFC.
1493          *
1494          * Return size of file in a format suitable for
1495          * using with RESTART (we just count bytes).
1496          */
1497         /* from draft-ietf-ftpext-mlst-14.txt:
1498          * This value will
1499          * change depending on the current STRUcture, MODE and TYPE of the data
1500          * connection, or a data connection which would be created were one
1501          * created now.  Thus, the result of the SIZE command is dependent on
1502          * the currently established STRU, MODE and TYPE parameters.
1503          */
1504         /* Therefore: switch to binary if the user did not specify ";type=a" */
1505         ftp_set_TYPE(xfer_type, r, origin, bb, &ftpmessage);
1506         rc = proxy_ftp_command(apr_pstrcat(p, "SIZE ",
1507                            ftp_escape_globbingchars(p, path), CRLF, NULL),
1508                            r, origin, bb, &ftpmessage);
1509         if (rc == -1 || rc == 421) {
1510             return ap_proxyerror(r, HTTP_BAD_GATEWAY,
1511                                  "Error reading from remote server");
1512         }
1513         else if (rc == 213) {/* Size command ok */
1514             int j;
1515             for (j = 0; apr_isdigit(ftpmessage[j]); j++)
1516                 ;
1517             ftpmessage[j] = '\0';
1518             if (ftpmessage[0] != '\0')
1519                  size = ftpmessage; /* already pstrdup'ed: no copy necessary */
1520         }
1521         else if (rc == 550) {    /* Not a regular file */
1522             ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, r->server,
1523                              "proxy: FTP: SIZE shows this is a directory");
1524             dirlisting = 1;
1525             rc = proxy_ftp_command(apr_pstrcat(p, "CWD ", 
1526                            ftp_escape_globbingchars(p, path), CRLF, NULL),
1527                            r, origin, bb, &ftpmessage);
1528             /* possible results: 250, 421, 500, 501, 502, 530, 550 */
1529             /* 250 Requested file action okay, completed. */
1530             /* 421 Service not available, closing control connection. */
1531             /* 500 Syntax error, command unrecognized. */
1532             /* 501 Syntax error in parameters or arguments. */
1533             /* 502 Command not implemented. */
1534             /* 530 Not logged in. */
1535             /* 550 Requested action not taken. */
1536             if (rc == -1 || rc == 421) {
1537                 return ap_proxyerror(r, HTTP_BAD_GATEWAY,
1538                                      "Error reading from remote server");
1539             }
1540             if (rc == 550) {
1541                 return ap_proxyerror(r, HTTP_NOT_FOUND, ftpmessage);
1542             }
1543             if (rc != 250) {
1544                 return ap_proxyerror(r, HTTP_BAD_GATEWAY, ftpmessage);
1545             }
1546             path = "";
1547             len = 0;
1548         }
1549     }
1550
1551     cwd = ftp_get_PWD(r, origin, bb);
1552     if (cwd != NULL) {
1553         apr_table_set(r->notes, "Directory-PWD", cwd);
1554     }
1555
1556     if (dirlisting) {
1557         ftp_set_TYPE('A', r, origin, bb, NULL);
1558         /* If the current directory contains no slash, we are talking to
1559          * a non-unix ftp system. Try LIST instead of "LIST -lag", it
1560          * should return a long listing anyway (unlike NLST).
1561          * Some exotic FTP servers might choke on the "-lag" switch.
1562          */
1563         /* Note that we do not escape the path here, to allow for
1564          * queries like: ftp://user@host/apache/src/server/http_*.c
1565          */
1566         if (len != 0)
1567             buf = apr_pstrcat(p, "LIST ", path, CRLF, NULL);
1568         else if (cwd == NULL || strchr(cwd, '/') != NULL)
1569             buf = apr_pstrcat(p, "LIST -lag", CRLF, NULL);
1570         else
1571             buf = "LIST" CRLF;
1572     }
1573     else {
1574         /* switch to binary if the user did not specify ";type=a" */
1575         ftp_set_TYPE(xfer_type, r, origin, bb, &ftpmessage);
1576 #if defined(USE_MDTM) && (defined(HAVE_TIMEGM) || defined(HAVE_GMTOFF))
1577         /* from draft-ietf-ftpext-mlst-14.txt:
1578          *   The FTP command, MODIFICATION TIME (MDTM), can be used to determine
1579          *   when a file in the server NVFS was last modified.     <..>
1580          *   The syntax of a time value is:
1581          *           time-val       = 14DIGIT [ "." 1*DIGIT ]      <..>
1582          *     Symbolically, a time-val may be viewed as
1583          *           YYYYMMDDHHMMSS.sss
1584          *     The "." and subsequent digits ("sss") are optional. <..>
1585          *     Time values are always represented in UTC (GMT)
1586          */
1587         rc = proxy_ftp_command(apr_pstrcat(p, "MDTM ", ftp_escape_globbingchars(p, path), CRLF, NULL),
1588                                r, origin, bb, &ftpmessage);
1589         /* then extract the Last-Modified time from it (YYYYMMDDhhmmss or YYYYMMDDhhmmss.xxx GMT). */
1590         if (rc == 213) {
1591             struct {
1592                 char YYYY[4+1];
1593                 char MM[2+1];
1594                 char DD[2+1];
1595                 char hh[2+1];
1596                 char mm[2+1];
1597                 char ss[2+1];
1598             } time_val;
1599             if (6 == sscanf(ftpmessage, "%4[0-9]%2[0-9]%2[0-9]%2[0-9]%2[0-9]%2[0-9]",
1600                 time_val.YYYY, time_val.MM, time_val.DD, time_val.hh, time_val.mm, time_val.ss)) {
1601                 struct tm tms;
1602                 memset (&tms, '\0', sizeof tms);
1603                 tms.tm_year = atoi(time_val.YYYY) - 1900;
1604                 tms.tm_mon  = atoi(time_val.MM)   - 1;
1605                 tms.tm_mday = atoi(time_val.DD);
1606                 tms.tm_hour = atoi(time_val.hh);
1607                 tms.tm_min  = atoi(time_val.mm);
1608                 tms.tm_sec  = atoi(time_val.ss);
1609 #ifdef HAVE_TIMEGM /* Does system have timegm()? */
1610                 mtime = timegm(&tms);
1611                 mtime *= APR_USEC_PER_SEC;
1612 #elif HAVE_GMTOFF /* does struct tm have a member tm_gmtoff? */
1613                 /* mktime will subtract the local timezone, which is not what we want.
1614                  * Add it again because the MDTM string is GMT
1615                  */
1616                 mtime = mktime(&tms);
1617                 mtime += tms.tm_gmtoff;
1618                 mtime *= APR_USEC_PER_SEC;
1619 #else
1620                 mtime = 0L;
1621 #endif
1622             }
1623         }
1624 #endif /* USE_MDTM */
1625 /* FIXME: Handle range requests - send REST */
1626         buf = apr_pstrcat(p, "RETR ", ftp_escape_globbingchars(p, path), CRLF, NULL);
1627     }
1628     rc = proxy_ftp_command(buf, r, origin, bb, &ftpmessage);
1629     /* rc is an intermediate response for the LIST or RETR commands */
1630
1631     /*
1632      * RETR: 110, 125, 150, 226, 250, 421, 425, 426, 450, 451, 500, 501, 530,
1633      * 550 NLST: 125, 150, 226, 250, 421, 425, 426, 450, 451, 500, 501, 502,
1634      * 530
1635      */
1636     /* 110 Restart marker reply. */
1637     /* 125 Data connection already open; transfer starting. */
1638     /* 150 File status okay; about to open data connection. */
1639     /* 226 Closing data connection. */
1640     /* 250 Requested file action okay, completed. */
1641     /* 421 Service not available, closing control connection. */
1642     /* 425 Can't open data connection. */
1643     /* 426 Connection closed; transfer aborted. */
1644     /* 450 Requested file action not taken. */
1645     /* 451 Requested action aborted. Local error in processing. */
1646     /* 500 Syntax error, command unrecognized. */
1647     /* 501 Syntax error in parameters or arguments. */
1648     /* 530 Not logged in. */
1649     /* 550 Requested action not taken. */
1650     if (rc == -1 || rc == 421) {
1651         return ap_proxyerror(r, HTTP_BAD_GATEWAY,
1652                              "Error reading from remote server");
1653     }
1654     if (rc == 550) {
1655         ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, r->server,
1656                      "proxy: FTP: RETR failed, trying LIST instead");
1657
1658         /* Directory Listings should always be fetched in ASCII mode */
1659         dirlisting = 1;
1660         ftp_set_TYPE('A', r, origin, bb, NULL);
1661
1662         rc = proxy_ftp_command(apr_pstrcat(p, "CWD ",
1663                                ftp_escape_globbingchars(p, path), CRLF, NULL),
1664                                r, origin, bb, &ftpmessage);
1665         /* possible results: 250, 421, 500, 501, 502, 530, 550 */
1666         /* 250 Requested file action okay, completed. */
1667         /* 421 Service not available, closing control connection. */
1668         /* 500 Syntax error, command unrecognized. */
1669         /* 501 Syntax error in parameters or arguments. */
1670         /* 502 Command not implemented. */
1671         /* 530 Not logged in. */
1672         /* 550 Requested action not taken. */
1673         if (rc == -1 || rc == 421) {
1674             return ap_proxyerror(r, HTTP_BAD_GATEWAY,
1675                                  "Error reading from remote server");
1676         }
1677         if (rc == 550) {
1678             return ap_proxyerror(r, HTTP_NOT_FOUND, ftpmessage);
1679         }
1680         if (rc != 250) {
1681             return ap_proxyerror(r, HTTP_BAD_GATEWAY, ftpmessage);
1682         }
1683
1684         /* Update current directory after CWD */
1685         cwd = ftp_get_PWD(r, origin, bb);
1686         if (cwd != NULL) {
1687             apr_table_set(r->notes, "Directory-PWD", cwd);
1688         }
1689
1690         /* See above for the "LIST" vs. "LIST -lag" discussion. */
1691         rc = proxy_ftp_command((cwd == NULL || strchr(cwd, '/') != NULL)
1692                                ? "LIST -lag" CRLF : "LIST" CRLF,
1693                                r, origin, bb, &ftpmessage);
1694
1695         /* rc is an intermediate response for the LIST command (125 transfer starting, 150 opening data connection) */
1696         if (rc == -1 || rc == 421)
1697             return ap_proxyerror(r, HTTP_BAD_GATEWAY,
1698                                  "Error reading from remote server");
1699     }
1700     if (rc != 125 && rc != 150 && rc != 226 && rc != 250) {
1701         return ap_proxyerror(r, HTTP_BAD_GATEWAY, ftpmessage);
1702     }
1703
1704     r->status = HTTP_OK;
1705     r->status_line = "200 OK";
1706
1707     apr_rfc822_date(dates, r->request_time);
1708     apr_table_setn(r->headers_out, "Date", dates);
1709     apr_table_setn(r->headers_out, "Server", ap_get_server_version());
1710
1711     /* set content-type */
1712     if (dirlisting) {
1713         ap_set_content_type(r, "text/html; charset=ISO-8859-1");
1714     }
1715     else {
1716         if (r->content_type) {
1717             ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, r->server,
1718                      "proxy: FTP: Content-Type set to %s", r->content_type);
1719         }
1720         else {
1721             ap_set_content_type(r, ap_default_type(r));
1722         }
1723         if (xfer_type != 'A' && size != NULL) {
1724             /* We "trust" the ftp server to really serve (size) bytes... */
1725             apr_table_setn(r->headers_out, "Content-Length", size);
1726             ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, r->server,
1727                          "proxy: FTP: Content-Length set to %s", size);
1728         }
1729     }
1730     apr_table_setn(r->headers_out, "Content-Type", r->content_type);
1731     ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, r->server,
1732                  "proxy: FTP: Content-Type set to %s", r->content_type);
1733
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);
1741     }
1742 #endif /* USE_MDTM */
1743
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)
1747      */
1748     if (dirlisting && r->content_encoding != NULL)
1749         r->content_encoding = NULL;
1750
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);
1756     }
1757
1758     /* wait for connection */
1759     if (use_port) {
1760         for (;;) {
1761             rv = apr_accept(&data_sock, local_sock, r->pool);
1762             if (rv == APR_EINTR) {
1763                 continue;
1764             }
1765             else if (rv == APR_SUCCESS) {
1766                 break;
1767             }
1768             else {
1769                 ap_log_rerror(APLOG_MARK, APLOG_ERR, rv, r,
1770                             "proxy: FTP: failed to accept data connection");
1771                 return HTTP_BAD_GATEWAY;
1772             }
1773         }
1774     }
1775
1776     /* the transfer socket is now open, create a new connection */
1777     data = ap_run_create_connection(p, r->server, data_sock, r->connection->id,
1778                                     r->connection->sbh, c->bucket_alloc);
1779     if (!data) {
1780         /*
1781          * the peer reset the connection already; ap_run_create_connection() closed
1782          * the socket
1783          */
1784         ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, r->server,
1785           "proxy: FTP: an error occurred creating the transfer connection");
1786         return HTTP_INTERNAL_SERVER_ERROR;
1787     }
1788
1789     /* set up the connection filters */
1790     rc = ap_run_pre_connection(data, data_sock);
1791     if (rc != OK && rc != DONE) {
1792         data->aborted = 1;
1793         ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, r->server,
1794                      "proxy: FTP: pre_connection setup failed (%d)",
1795                      rc);
1796         return rc;
1797     }
1798
1799     /*
1800      * VI: Receive the Response ------------------------
1801      *
1802      * Get response from the remote ftp socket, and pass it up the filter chain.
1803      */
1804
1805     /* send response */
1806     r->sent_bodyct = 1;
1807
1808     if (dirlisting) {
1809         /* insert directory filter */
1810         ap_add_output_filter("PROXY_SEND_DIR", NULL, r, r->connection);
1811     }
1812
1813     /* send body */
1814     if (!r->header_only) {
1815         apr_bucket *e;
1816         int finish = FALSE;
1817
1818         ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, r->server,
1819                      "proxy: FTP: start body send");
1820
1821         /* read the body, pass it to the output filters */
1822         while (ap_get_brigade(data->input_filters, 
1823                               bb, 
1824                               AP_MODE_READBYTES, 
1825                               APR_BLOCK_READ, 
1826                               conf->io_buffer_size) == APR_SUCCESS) {
1827 #if DEBUGGING
1828             {
1829                 apr_off_t readbytes;
1830                 apr_brigade_length(bb, 0, &readbytes);
1831                 ap_log_error(APLOG_MARK, APLOG_DEBUG, 0,
1832                              r->server, "proxy (PID %d): readbytes: %#x",
1833                              getpid(), readbytes);
1834             }
1835 #endif
1836             /* sanity check */
1837             if (APR_BRIGADE_EMPTY(bb)) {
1838                 apr_brigade_cleanup(bb);
1839                 break;
1840             }
1841
1842             /* found the last brigade? */
1843             if (APR_BUCKET_IS_EOS(APR_BRIGADE_LAST(bb))) {
1844                 /* if this is the last brigade, cleanup the
1845                  * backend connection first to prevent the
1846                  * backend server from hanging around waiting
1847                  * for a slow client to eat these bytes
1848                  */
1849                 ap_flush_conn(data);
1850                 if (data_sock) {
1851                     apr_socket_close(data_sock);
1852                 }
1853                 data_sock = NULL;
1854                 ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, r->server,
1855                              "proxy: FTP: data connection closed");
1856                 /* signal that we must leave */
1857                 finish = TRUE;
1858             }
1859
1860             /* if no EOS yet, then we must flush */
1861             if (FALSE == finish) {
1862                 e = apr_bucket_flush_create(c->bucket_alloc);
1863                 APR_BRIGADE_INSERT_TAIL(bb, e);
1864             }
1865
1866             /* try send what we read */
1867             if (ap_pass_brigade(r->output_filters, bb) != APR_SUCCESS
1868                 || c->aborted) {
1869                 /* Ack! Phbtt! Die! User aborted! */
1870                 finish = TRUE;
1871             }
1872
1873             /* make sure we always clean up after ourselves */
1874             apr_brigade_cleanup(bb);
1875
1876             /* if we are done, leave */
1877             if (TRUE == finish) {
1878                 break;
1879             }
1880         }
1881         ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, r->server,
1882                      "proxy: FTP: end body send");
1883
1884     }
1885     if (data_sock) {
1886         ap_flush_conn(data);
1887         apr_socket_close(data_sock);
1888         ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, r->server,
1889                      "proxy: FTP: data connection closed");
1890     }
1891
1892     /* Retrieve the final response for the RETR or LIST commands */
1893     rc = proxy_ftp_command(NULL, r, origin, bb, &ftpmessage);
1894     apr_brigade_cleanup(bb);
1895
1896     /*
1897      * VII: Clean Up -------------
1898      *
1899      * If there are no KeepAlives, or if the connection has been signalled to
1900      * close, close the socket and clean up
1901      */
1902
1903     /* finish */
1904     rc = proxy_ftp_command("QUIT" CRLF,
1905                            r, origin, bb, &ftpmessage);
1906     /* responses: 221, 500 */
1907     /* 221 Service closing control connection. */
1908     /* 500 Syntax error, command unrecognized. */
1909     ap_flush_conn(origin);
1910     if (origin_sock) {
1911         apr_socket_close(origin_sock);
1912         origin_sock = NULL;
1913     }
1914     apr_brigade_destroy(bb);
1915     return OK;
1916 }
1917
1918 static void ap_proxy_ftp_register_hook(apr_pool_t *p)
1919 {
1920     /* hooks */
1921     proxy_hook_scheme_handler(ap_proxy_ftp_handler, NULL, NULL, APR_HOOK_MIDDLE);
1922     proxy_hook_canon_handler(ap_proxy_ftp_canon, NULL, NULL, APR_HOOK_MIDDLE);
1923     /* filters */
1924     ap_register_output_filter("PROXY_SEND_DIR", ap_proxy_send_dir_filter,
1925                               NULL, AP_FTYPE_RESOURCE);
1926 }
1927
1928 module AP_MODULE_DECLARE_DATA proxy_ftp_module = {
1929     STANDARD20_MODULE_STUFF,
1930     NULL,                       /* create per-directory config structure */
1931     NULL,                       /* merge per-directory config structures */
1932     NULL,                       /* create per-server config structure */
1933     NULL,                       /* merge per-server config structures */
1934     NULL,                       /* command apr_table_t */
1935     ap_proxy_ftp_register_hook  /* register hooks */
1936 };