~ubuntu-branches/ubuntu/feisty/apache2/feisty

« back to all changes in this revision

Viewing changes to modules/proxy/mod_proxy_ftp.c

  • Committer: Bazaar Package Importer
  • Author(s): Andreas Barth
  • Date: 2006-12-09 21:05:45 UTC
  • mfrom: (0.6.1 upstream)
  • Revision ID: james.westby@ubuntu.com-20061209210545-h70s0xaqc2v8vqr2
Tags: 2.2.3-3.2
* Non-maintainer upload.
* 043_ajp_connection_reuse: Patch from upstream Bugzilla, fixing a critical
  issue with regard to connection reuse in mod_proxy_ajp.
  Closes: #396265

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
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
#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
                " </head>\n"
 
356
                " <body>\n  <h2>Directory of "
 
357
                "<a href=\"/\">%s</a>/%s",
 
358
                site, basedir, ap_escape_html(p, path),
 
359
                site, str);
 
360
 
 
361
        APR_BRIGADE_INSERT_TAIL(out, apr_bucket_pool_create(str, strlen(str),
 
362
                                                          p, c->bucket_alloc));
 
363
 
 
364
        for (dir = path+1; (dir = strchr(dir, '/')) != NULL; )
 
365
        {
 
366
            *dir = '\0';
 
367
            if ((reldir = strrchr(path+1, '/'))==NULL) {
 
368
                reldir = path+1;
 
369
            }
 
370
            else
 
371
                ++reldir;
 
372
            /* print "path/" component */
 
373
            str = apr_psprintf(p, "<a href=\"%s%s/\">%s</a>/", basedir,
 
374
                        ap_escape_uri(p, path),
 
375
                        ap_escape_html(p, reldir));
 
376
            *dir = '/';
 
377
            while (*dir == '/')
 
378
              ++dir;
 
379
            APR_BRIGADE_INSERT_TAIL(out, apr_bucket_pool_create(str,
 
380
                                                           strlen(str), p,
 
381
                                                           c->bucket_alloc));
 
382
        }
 
383
        if (wildcard != NULL) {
 
384
            APR_BRIGADE_INSERT_TAIL(out, apr_bucket_pool_create(wildcard,
 
385
                                                           strlen(wildcard), p,
 
386
                                                           c->bucket_alloc));
 
387
        }
 
388
 
 
389
        /* If the caller has determined the current directory, and it differs */
 
390
        /* from what the client requested, then show the real name */
 
391
        if (pwd == NULL || strncmp(pwd, path, strlen(pwd)) == 0) {
 
392
            str = apr_psprintf(p, "</h2>\n\n  <hr />\n\n<pre>");
 
393
        }
 
394
        else {
 
395
            str = apr_psprintf(p, "</h2>\n\n(%s)\n\n  <hr />\n\n<pre>",
 
396
                               ap_escape_html(p, pwd));
 
397
        }
 
398
        APR_BRIGADE_INSERT_TAIL(out, apr_bucket_pool_create(str, strlen(str),
 
399
                                                           p, c->bucket_alloc));
 
400
 
 
401
        /* print README */
 
402
        if (readme) {
 
403
            str = apr_psprintf(p, "%s\n</pre>\n\n<hr />\n\n<pre>\n",
 
404
                               ap_escape_html(p, readme));
 
405
 
 
406
            APR_BRIGADE_INSERT_TAIL(out, apr_bucket_pool_create(str,
 
407
                                                           strlen(str), p,
 
408
                                                           c->bucket_alloc));
 
409
        }
 
410
 
 
411
        /* make sure page intro gets sent out */
 
412
        APR_BRIGADE_INSERT_TAIL(out, apr_bucket_flush_create(c->bucket_alloc));
 
413
        if (APR_SUCCESS != (rv = ap_pass_brigade(f->next, out))) {
 
414
            return rv;
 
415
        }
 
416
        apr_brigade_cleanup(out);
 
417
 
 
418
        ctx->state = BODY;
 
419
    }
 
420
 
 
421
    /* loop through each line of directory */
 
422
    while (BODY == ctx->state) {
 
423
        char *filename;
 
424
        int found = 0;
 
425
        int eos = 0;
 
426
 
 
427
        ap_regex_t *re = NULL;
 
428
        ap_regmatch_t re_result[LS_REG_MATCH];
 
429
 
 
430
        /* Compile the output format of "ls -s1" as a fallback for non-unix ftp listings */
 
431
        re = ap_pregcomp(p, LS_REG_PATTERN, AP_REG_EXTENDED);
 
432
        ap_assert(re != NULL);
 
433
 
 
434
        /* get a complete line */
 
435
        /* if the buffer overruns - throw data away */
 
436
        while (!found && !APR_BRIGADE_EMPTY(ctx->in)) {
 
437
            char *pos, *response;
 
438
            apr_size_t len, max;
 
439
            apr_bucket *e;
 
440
 
 
441
            e = APR_BRIGADE_FIRST(ctx->in);
 
442
            if (APR_BUCKET_IS_EOS(e)) {
 
443
                eos = 1;
 
444
                break;
 
445
            }
 
446
            if (APR_SUCCESS != (rv = apr_bucket_read(e, (const char **)&response, &len, APR_BLOCK_READ))) {
 
447
                return rv;
 
448
            }
 
449
            pos = memchr(response, APR_ASCII_LF, len);
 
450
            if (pos != NULL) {
 
451
                if ((response + len) != (pos + 1)) {
 
452
                    len = pos - response + 1;
 
453
                    apr_bucket_split(e, pos - response + 1);
 
454
                }
 
455
                found = 1;
 
456
            }
 
457
            max = sizeof(ctx->buffer) - strlen(ctx->buffer) - 1;
 
458
            if (len > max) {
 
459
                len = max;
 
460
            }
 
461
 
 
462
            /* len+1 to leave space for the trailing nil char */
 
463
            apr_cpystrn(ctx->buffer+strlen(ctx->buffer), response, len+1);
 
464
 
 
465
            APR_BUCKET_REMOVE(e);
 
466
            apr_bucket_destroy(e);
 
467
        }
 
468
 
 
469
        /* EOS? jump to footer */
 
470
        if (eos) {
 
471
            ctx->state = FOOTER;
 
472
            break;
 
473
        }
 
474
 
 
475
        /* not complete? leave and try get some more */
 
476
        if (!found) {
 
477
            return APR_SUCCESS;
 
478
        }
 
479
 
 
480
        {
 
481
            apr_size_t n = strlen(ctx->buffer);
 
482
            if (ctx->buffer[n-1] == CRLF[1])  /* strip trailing '\n' */
 
483
                ctx->buffer[--n] = '\0';
 
484
            if (ctx->buffer[n-1] == CRLF[0])  /* strip trailing '\r' if present */
 
485
                ctx->buffer[--n] = '\0';
 
486
        }
 
487
 
 
488
        /* a symlink? */
 
489
        if (ctx->buffer[0] == 'l' && (filename = strstr(ctx->buffer, " -> ")) != NULL) {
 
490
            char *link_ptr = filename;
 
491
 
 
492
            do {
 
493
                filename--;
 
494
            } while (filename[0] != ' ' && filename > ctx->buffer);
 
495
            if (filename > ctx->buffer)
 
496
                *(filename++) = '\0';
 
497
            *(link_ptr++) = '\0';
 
498
            str = apr_psprintf(p, "%s <a href=\"%s\">%s %s</a>\n",
 
499
                               ap_escape_html(p, ctx->buffer),
 
500
                               ap_escape_uri(p, filename),
 
501
                               ap_escape_html(p, filename),
 
502
                               ap_escape_html(p, link_ptr));
 
503
        }
 
504
 
 
505
        /* a directory/file? */
 
506
        else if (ctx->buffer[0] == 'd' || ctx->buffer[0] == '-' || ctx->buffer[0] == 'l' || apr_isdigit(ctx->buffer[0])) {
 
507
            int searchidx = 0;
 
508
            char *searchptr = NULL;
 
509
            int firstfile = 1;
 
510
            if (apr_isdigit(ctx->buffer[0])) {  /* handle DOS dir */
 
511
                searchptr = strchr(ctx->buffer, '<');
 
512
                if (searchptr != NULL)
 
513
                    *searchptr = '[';
 
514
                searchptr = strchr(ctx->buffer, '>');
 
515
                if (searchptr != NULL)
 
516
                    *searchptr = ']';
 
517
            }
 
518
 
 
519
            filename = strrchr(ctx->buffer, ' ');
 
520
            *(filename++) = '\0';
 
521
 
 
522
            /* handle filenames with spaces in 'em */
 
523
            if (!strcmp(filename, ".") || !strcmp(filename, "..") || firstfile) {
 
524
                firstfile = 0;
 
525
                searchidx = filename - ctx->buffer;
 
526
            }
 
527
            else if (searchidx != 0 && ctx->buffer[searchidx] != 0) {
 
528
                *(--filename) = ' ';
 
529
                ctx->buffer[searchidx - 1] = '\0';
 
530
                filename = &ctx->buffer[searchidx];
 
531
            }
 
532
 
 
533
            /* Append a slash to the HREF link for directories */
 
534
            if (!strcmp(filename, ".") || !strcmp(filename, "..") || ctx->buffer[0] == 'd') {
 
535
                str = apr_psprintf(p, "%s <a href=\"%s/\">%s</a>\n",
 
536
                                   ap_escape_html(p, ctx->buffer),
 
537
                                   ap_escape_uri(p, filename),
 
538
                                   ap_escape_html(p, filename));
 
539
            }
 
540
            else {
 
541
                str = apr_psprintf(p, "%s <a href=\"%s\">%s</a>\n",
 
542
                                   ap_escape_html(p, ctx->buffer),
 
543
                                   ap_escape_uri(p, filename),
 
544
                                   ap_escape_html(p, filename));
 
545
            }
 
546
        }
 
547
        /* Try a fallback for listings in the format of "ls -s1" */
 
548
        else if (0 == ap_regexec(re, ctx->buffer, LS_REG_MATCH, re_result, 0)) {
 
549
 
 
550
            filename = apr_pstrndup(p, &ctx->buffer[re_result[2].rm_so], re_result[2].rm_eo - re_result[2].rm_so);
 
551
 
 
552
            str = apr_pstrcat(p, ap_escape_html(p, apr_pstrndup(p, ctx->buffer, re_result[2].rm_so)),
 
553
                              "<a href=\"", ap_escape_uri(p, filename), "\">",
 
554
                              ap_escape_html(p, filename), "</a>\n", NULL);
 
555
        }
 
556
        else {
 
557
            strcat(ctx->buffer, "\n"); /* re-append the newline */
 
558
            str = ap_escape_html(p, ctx->buffer);
 
559
        }
 
560
 
 
561
        /* erase buffer for next time around */
 
562
        ctx->buffer[0] = 0;
 
563
 
 
564
        APR_BRIGADE_INSERT_TAIL(out, apr_bucket_pool_create(str, strlen(str), p,
 
565
                                                            c->bucket_alloc));
 
566
        APR_BRIGADE_INSERT_TAIL(out, apr_bucket_flush_create(c->bucket_alloc));
 
567
        if (APR_SUCCESS != (rv = ap_pass_brigade(f->next, out))) {
 
568
            return rv;
 
569
        }
 
570
        apr_brigade_cleanup(out);
 
571
 
 
572
    }
 
573
 
 
574
    if (FOOTER == ctx->state) {
 
575
        str = apr_psprintf(p, "</pre>\n\n  <hr />\n\n  %s\n\n </body>\n</html>\n", ap_psignature("", r));
 
576
        APR_BRIGADE_INSERT_TAIL(out, apr_bucket_pool_create(str, strlen(str), p,
 
577
                                                            c->bucket_alloc));
 
578
        APR_BRIGADE_INSERT_TAIL(out, apr_bucket_flush_create(c->bucket_alloc));
 
579
        APR_BRIGADE_INSERT_TAIL(out, apr_bucket_eos_create(c->bucket_alloc));
 
580
        if (APR_SUCCESS != (rv = ap_pass_brigade(f->next, out))) {
 
581
            return rv;
 
582
        }
 
583
        apr_brigade_destroy(out);
 
584
    }
 
585
 
 
586
    return APR_SUCCESS;
 
587
}
 
588
 
 
589
/*
 
590
 * Generic "send FTP command to server" routine, using the control socket.
 
591
 * Returns the FTP returncode (3 digit code)
 
592
 * Allows for tracing the FTP protocol (in LogLevel debug)
 
593
 */
 
594
static int
 
595
proxy_ftp_command(const char *cmd, request_rec *r, conn_rec *ftp_ctrl,
 
596
                  apr_bucket_brigade *bb, char **pmessage)
 
597
{
 
598
    char *crlf;
 
599
    int rc;
 
600
    char message[HUGE_STRING_LEN];
 
601
 
 
602
    /* If cmd == NULL, we retrieve the next ftp response line */
 
603
    if (cmd != NULL) {
 
604
        conn_rec *c = r->connection;
 
605
        APR_BRIGADE_INSERT_TAIL(bb, apr_bucket_pool_create(cmd, strlen(cmd), r->pool, c->bucket_alloc));
 
606
        APR_BRIGADE_INSERT_TAIL(bb, apr_bucket_flush_create(c->bucket_alloc));
 
607
        ap_pass_brigade(ftp_ctrl->output_filters, bb);
 
608
 
 
609
        /* strip off the CRLF for logging */
 
610
        apr_cpystrn(message, cmd, sizeof(message));
 
611
        if ((crlf = strchr(message, '\r')) != NULL ||
 
612
            (crlf = strchr(message, '\n')) != NULL)
 
613
            *crlf = '\0';
 
614
        if (strncmp(message,"PASS ", 5) == 0)
 
615
            strcpy(&message[5], "****");
 
616
        ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, r->server,
 
617
                     "proxy:>FTP: %s", message);
 
618
    }
 
619
 
 
620
    rc = ftp_getrc_msg(ftp_ctrl, bb, message, sizeof message);
 
621
    if (rc == -1 || rc == 421)
 
622
        strcpy(message,"<unable to read result>");
 
623
    if ((crlf = strchr(message, '\r')) != NULL ||
 
624
        (crlf = strchr(message, '\n')) != NULL)
 
625
        *crlf = '\0';
 
626
    ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, r->server,
 
627
                 "proxy:<FTP: %3.3u %s", rc, message);
 
628
 
 
629
    if (pmessage != NULL)
 
630
        *pmessage = apr_pstrdup(r->pool, message);
 
631
 
 
632
    return rc;
 
633
}
 
634
 
 
635
/* Set ftp server to TYPE {A,I,E} before transfer of a directory or file */
 
636
static int ftp_set_TYPE(char xfer_type, request_rec *r, conn_rec *ftp_ctrl,
 
637
                  apr_bucket_brigade *bb, char **pmessage)
 
638
{
 
639
    char old_type[2] = { 'A', '\0' }; /* After logon, mode is ASCII */
 
640
    int ret = HTTP_OK;
 
641
    int rc;
 
642
 
 
643
    /* set desired type */
 
644
    old_type[0] = xfer_type;
 
645
 
 
646
    rc = proxy_ftp_command(apr_pstrcat(r->pool, "TYPE ", old_type, CRLF, NULL),
 
647
                           r, ftp_ctrl, bb, pmessage);
 
648
/* responses: 200, 421, 500, 501, 504, 530 */
 
649
    /* 200 Command okay. */
 
650
    /* 421 Service not available, closing control connection. */
 
651
    /* 500 Syntax error, command unrecognized. */
 
652
    /* 501 Syntax error in parameters or arguments. */
 
653
    /* 504 Command not implemented for that parameter. */
 
654
    /* 530 Not logged in. */
 
655
    if (rc == -1 || rc == 421) {
 
656
        ret = ap_proxyerror(r, HTTP_BAD_GATEWAY,
 
657
                             "Error reading from remote server");
 
658
    }
 
659
    else if (rc != 200 && rc != 504) {
 
660
        ret = ap_proxyerror(r, HTTP_BAD_GATEWAY,
 
661
                             "Unable to set transfer type");
 
662
    }
 
663
/* Allow not implemented */
 
664
    else if (rc == 504)
 
665
        /* ignore it silently */;
 
666
 
 
667
    return ret;
 
668
}
 
669
 
 
670
 
 
671
/* Return the current directory which we have selected on the FTP server, or NULL */
 
672
static char *ftp_get_PWD(request_rec *r, conn_rec *ftp_ctrl, apr_bucket_brigade *bb)
 
673
{
 
674
    char *cwd = NULL;
 
675
    char *ftpmessage = NULL;
 
676
 
 
677
    /* responses: 257, 500, 501, 502, 421, 550 */
 
678
    /* 257 "<directory-name>" <commentary> */
 
679
    /* 421 Service not available, closing control connection. */
 
680
    /* 500 Syntax error, command unrecognized. */
 
681
    /* 501 Syntax error in parameters or arguments. */
 
682
    /* 502 Command not implemented. */
 
683
    /* 550 Requested action not taken. */
 
684
    switch (proxy_ftp_command("PWD" CRLF, r, ftp_ctrl, bb, &ftpmessage)) {
 
685
        case -1:
 
686
        case 421:
 
687
        case 550:
 
688
            ap_proxyerror(r, HTTP_BAD_GATEWAY,
 
689
                             "Failed to read PWD on ftp server");
 
690
            break;
 
691
 
 
692
        case 257: {
 
693
            const char *dirp = ftpmessage;
 
694
            cwd = ap_getword_conf(r->pool, &dirp);
 
695
        }
 
696
    }
 
697
    return cwd;
 
698
}
 
699
 
 
700
 
 
701
/* Common routine for failed authorization (i.e., missing or wrong password)
 
702
 * to an ftp service. This causes most browsers to retry the request
 
703
 * with username and password (which was presumably queried from the user)
 
704
 * supplied in the Authorization: header.
 
705
 * Note that we "invent" a realm name which consists of the
 
706
 * ftp://user@host part of the reqest (sans password -if supplied but invalid-)
 
707
 */
 
708
static int ftp_unauthorized(request_rec *r, int log_it)
 
709
{
 
710
    r->proxyreq = PROXYREQ_NONE;
 
711
    /*
 
712
     * Log failed requests if they supplied a password (log username/password
 
713
     * guessing attempts)
 
714
     */
 
715
    if (log_it)
 
716
        ap_log_rerror(APLOG_MARK, APLOG_INFO, 0, r,
 
717
                      "proxy: missing or failed auth to %s",
 
718
                      apr_uri_unparse(r->pool,
 
719
                                 &r->parsed_uri, APR_URI_UNP_OMITPATHINFO));
 
720
 
 
721
    apr_table_setn(r->err_headers_out, "WWW-Authenticate",
 
722
                   apr_pstrcat(r->pool, "Basic realm=\"",
 
723
                               apr_uri_unparse(r->pool, &r->parsed_uri,
 
724
                       APR_URI_UNP_OMITPASSWORD | APR_URI_UNP_OMITPATHINFO),
 
725
                               "\"", NULL));
 
726
 
 
727
    return HTTP_UNAUTHORIZED;
 
728
}
 
729
 
 
730
static
 
731
apr_status_t proxy_ftp_cleanup(request_rec *r, proxy_conn_rec *backend)
 
732
{
 
733
 
 
734
    backend->close_on_recycle = 1;
 
735
    ap_set_module_config(r->connection->conn_config, &proxy_ftp_module, NULL);
 
736
    ap_proxy_release_connection("FTP", backend, r->server);
 
737
 
 
738
    return OK;
 
739
}
 
740
 
 
741
static
 
742
int ftp_proxyerror(request_rec *r, proxy_conn_rec *conn, int statuscode, const char *message)
 
743
{
 
744
    proxy_ftp_cleanup(r, conn);
 
745
    return ap_proxyerror(r, statuscode, message);
 
746
}
 
747
/*
 
748
 * Handles direct access of ftp:// URLs
 
749
 * Original (Non-PASV) version from
 
750
 * Troy Morrison <spiffnet@zoom.com>
 
751
 * PASV added by Chuck
 
752
 * Filters by [Graham Leggett <minfrin@sharp.fm>]
 
753
 */
 
754
static int proxy_ftp_handler(request_rec *r, proxy_worker *worker,
 
755
                             proxy_server_conf *conf, char *url,
 
756
                             const char *proxyhost, apr_port_t proxyport)
 
757
{
 
758
    apr_pool_t *p = r->pool;
 
759
    conn_rec *c = r->connection;
 
760
    proxy_conn_rec *backend;
 
761
    apr_socket_t *sock, *local_sock, *data_sock = NULL;
 
762
    apr_sockaddr_t *connect_addr = NULL;
 
763
    apr_status_t rv;
 
764
    conn_rec *origin, *data = NULL;
 
765
    apr_status_t err = APR_SUCCESS;
 
766
    apr_bucket_brigade *bb = apr_brigade_create(p, c->bucket_alloc);
 
767
    char *buf, *connectname;
 
768
    apr_port_t connectport;
 
769
    char buffer[MAX_STRING_LEN];
 
770
    char *ftpmessage = NULL;
 
771
    char *path, *strp, *type_suffix, *cwd = NULL;
 
772
    apr_uri_t uri;
 
773
    char *user = NULL;
 
774
/*    char *account = NULL; how to supply an account in a URL? */
 
775
    const char *password = NULL;
 
776
    int len, rc;
 
777
    int one = 1;
 
778
    char *size = NULL;
 
779
    char xfer_type = 'A'; /* after ftp login, the default is ASCII */
 
780
    int  dirlisting = 0;
 
781
#if defined(USE_MDTM) && (defined(HAVE_TIMEGM) || defined(HAVE_GMTOFF))
 
782
    apr_time_t mtime = 0L;
 
783
#endif
 
784
 
 
785
    /* stuff for PASV mode */
 
786
    int connect = 0, use_port = 0;
 
787
    char dates[APR_RFC822_DATE_LEN];
 
788
    int status;
 
789
    apr_pool_t *address_pool;
 
790
 
 
791
    /* is this for us? */
 
792
    if (proxyhost) {
 
793
        ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, r->server,
 
794
                     "proxy: FTP: declining URL %s - proxyhost %s specified:", url, proxyhost);
 
795
        return DECLINED;        /* proxy connections are via HTTP */
 
796
    }
 
797
    if (strncasecmp(url, "ftp:", 4)) {
 
798
        ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, r->server,
 
799
                     "proxy: FTP: declining URL %s - not ftp:", url);
 
800
        return DECLINED;        /* only interested in FTP */
 
801
    }
 
802
    ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, r->server,
 
803
                 "proxy: FTP: serving URL %s", url);
 
804
 
 
805
 
 
806
    /*
 
807
     * I: Who Do I Connect To? -----------------------
 
808
     *
 
809
     * Break up the URL to determine the host to connect to
 
810
     */
 
811
 
 
812
    /* we only support GET and HEAD */
 
813
    if (r->method_number != M_GET)
 
814
        return HTTP_NOT_IMPLEMENTED;
 
815
 
 
816
    /* We break the URL into host, port, path-search */
 
817
    if (r->parsed_uri.hostname == NULL) {
 
818
        if (APR_SUCCESS != apr_uri_parse(p, url, &uri)) {
 
819
            return ap_proxyerror(r, HTTP_BAD_REQUEST,
 
820
                apr_psprintf(p, "URI cannot be parsed: %s", url));
 
821
        }
 
822
        connectname = uri.hostname;
 
823
        connectport = uri.port;
 
824
        path = apr_pstrdup(p, uri.path);
 
825
    }
 
826
    else {
 
827
        connectname = r->parsed_uri.hostname;
 
828
        connectport = r->parsed_uri.port;
 
829
        path = apr_pstrdup(p, r->parsed_uri.path);
 
830
    }
 
831
    if (connectport == 0) {
 
832
        connectport = apr_uri_port_of_scheme("ftp");
 
833
    }
 
834
    path = (path != NULL && path[0] != '\0') ? &path[1] : "";
 
835
 
 
836
    type_suffix = strchr(path, ';');
 
837
    if (type_suffix != NULL)
 
838
        *(type_suffix++) = '\0';
 
839
 
 
840
    if (type_suffix != NULL && strncmp(type_suffix, "type=", 5) == 0
 
841
        && apr_isalpha(type_suffix[5])) {
 
842
        /* "type=d" forces a dir listing.
 
843
         * The other types (i|a|e) are directly used for the ftp TYPE command
 
844
         */
 
845
        if ( ! (dirlisting = (apr_tolower(type_suffix[5]) == 'd')))
 
846
            xfer_type = apr_toupper(type_suffix[5]);
 
847
 
 
848
        /* Check valid types, rather than ignoring invalid types silently: */
 
849
        if (strchr("AEI", xfer_type) == NULL)
 
850
            return ap_proxyerror(r, HTTP_BAD_REQUEST, apr_pstrcat(r->pool,
 
851
                                    "ftp proxy supports only types 'a', 'i', or 'e': \"",
 
852
                                    type_suffix, "\" is invalid.", NULL));
 
853
    }
 
854
    else {
 
855
        /* make binary transfers the default */
 
856
        xfer_type = 'I';
 
857
    }
 
858
 
 
859
 
 
860
    /*
 
861
     * The "Authorization:" header must be checked first. We allow the user
 
862
     * to "override" the URL-coded user [ & password ] in the Browsers'
 
863
     * User&Password Dialog. NOTE that this is only marginally more secure
 
864
     * than having the password travel in plain as part of the URL, because
 
865
     * Basic Auth simply uuencodes the plain text password. But chances are
 
866
     * still smaller that the URL is logged regularly.
 
867
     */
 
868
    if ((password = apr_table_get(r->headers_in, "Authorization")) != NULL
 
869
        && strcasecmp(ap_getword(r->pool, &password, ' '), "Basic") == 0
 
870
        && (password = ap_pbase64decode(r->pool, password))[0] != ':') {
 
871
        /*
 
872
         * Note that this allocation has to be made from r->connection->pool
 
873
         * because it has the lifetime of the connection.  The other
 
874
         * allocations are temporary and can be tossed away any time.
 
875
         */
 
876
        user = ap_getword_nulls(r->connection->pool, &password, ':');
 
877
        r->ap_auth_type = "Basic";
 
878
        r->user = r->parsed_uri.user = user;
 
879
    }
 
880
    else if ((user = r->parsed_uri.user) != NULL) {
 
881
        user = apr_pstrdup(p, user);
 
882
        decodeenc(user);
 
883
        if ((password = r->parsed_uri.password) != NULL) {
 
884
            char *tmp = apr_pstrdup(p, password);
 
885
            decodeenc(tmp);
 
886
            password = tmp;
 
887
        }
 
888
    }
 
889
    else {
 
890
        user = "anonymous";
 
891
        password = "apache-proxy@";
 
892
    }
 
893
 
 
894
    ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, r->server,
 
895
       "proxy: FTP: connecting %s to %s:%d", url, connectname, connectport);
 
896
 
 
897
    if (worker->is_address_reusable) {
 
898
        if (!worker->cp->addr) {
 
899
            if ((err = PROXY_THREAD_LOCK(worker)) != APR_SUCCESS) {
 
900
                ap_log_error(APLOG_MARK, APLOG_ERR, err, r->server,
 
901
                             "proxy: FTP: lock");
 
902
                return HTTP_INTERNAL_SERVER_ERROR;
 
903
            }
 
904
        }
 
905
        connect_addr = worker->cp->addr;
 
906
        address_pool = worker->cp->pool;
 
907
    }
 
908
    else
 
909
        address_pool = r->pool;
 
910
 
 
911
    /* do a DNS lookup for the destination host */
 
912
    if (!connect_addr)
 
913
        err = apr_sockaddr_info_get(&(connect_addr),
 
914
                                    connectname, APR_UNSPEC,
 
915
                                    connectport, 0,
 
916
                                    address_pool);
 
917
    if (worker->is_address_reusable && !worker->cp->addr) {
 
918
        worker->cp->addr = connect_addr;
 
919
        PROXY_THREAD_UNLOCK(worker);
 
920
    }
 
921
    /*
 
922
     * get all the possible IP addresses for the destname and loop through
 
923
     * them until we get a successful connection
 
924
     */
 
925
    if (APR_SUCCESS != err) {
 
926
        return ap_proxyerror(r, HTTP_BAD_GATEWAY, apr_pstrcat(p,
 
927
                                                 "DNS lookup failure for: ",
 
928
                                                        connectname, NULL));
 
929
    }
 
930
 
 
931
    /* check if ProxyBlock directive on this host */
 
932
    if (OK != ap_proxy_checkproxyblock(r, conf, connect_addr)) {
 
933
        return ap_proxyerror(r, HTTP_FORBIDDEN,
 
934
                             "Connect to remote machine blocked");
 
935
    }
 
936
 
 
937
    /* create space for state information */
 
938
    backend = (proxy_conn_rec *) ap_get_module_config(c->conn_config, &proxy_ftp_module);
 
939
    if (!backend) {
 
940
        status = ap_proxy_acquire_connection("FTP", &backend, worker, r->server);
 
941
        if (status != OK) {
 
942
            if (backend) {
 
943
                backend->close_on_recycle = 1;
 
944
                ap_proxy_release_connection("FTP", backend, r->server);
 
945
            }
 
946
            return status;
 
947
        }
 
948
        /* TODO: see if ftp could use determine_connection */
 
949
        backend->addr = connect_addr;
 
950
        ap_set_module_config(c->conn_config, &proxy_ftp_module, backend);
 
951
    }
 
952
 
 
953
 
 
954
    /*
 
955
     * II: Make the Connection -----------------------
 
956
     *
 
957
     * We have determined who to connect to. Now make the connection.
 
958
     */
 
959
 
 
960
 
 
961
    if (ap_proxy_connect_backend("FTP", backend, worker, r->server)) {
 
962
        ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, r->server,
 
963
                     "proxy: FTP: an error occurred creating a new connection to %pI (%s)",
 
964
                     connect_addr, connectname);
 
965
        proxy_ftp_cleanup(r, backend);
 
966
        return HTTP_SERVICE_UNAVAILABLE;
 
967
    }
 
968
 
 
969
    if (!backend->connection) {
 
970
        status = ap_proxy_connection_create("FTP", backend, c, r->server);
 
971
        if (status != OK) {
 
972
            proxy_ftp_cleanup(r, backend);
 
973
            return status;
 
974
        }
 
975
    }
 
976
 
 
977
    /* Use old naming */
 
978
    origin = backend->connection;
 
979
    sock = backend->sock;
 
980
 
 
981
    ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, r->server,
 
982
                 "proxy: FTP: control connection complete");
 
983
 
 
984
 
 
985
    /*
 
986
     * III: Send Control Request -------------------------
 
987
     *
 
988
     * Log into the ftp server, send the username & password, change to the
 
989
     * correct directory...
 
990
     */
 
991
 
 
992
 
 
993
    /* possible results: */
 
994
    /* 120 Service ready in nnn minutes. */
 
995
    /* 220 Service ready for new user. */
 
996
    /* 421 Service not available, closing control connection. */
 
997
    rc = proxy_ftp_command(NULL, r, origin, bb, &ftpmessage);
 
998
    if (rc == -1 || rc == 421) {
 
999
        return ftp_proxyerror(r, backend, HTTP_BAD_GATEWAY, "Error reading from remote server");
 
1000
    }
 
1001
    if (rc == 120) {
 
1002
        /*
 
1003
         * RFC2616 states: 14.37 Retry-After
 
1004
         *
 
1005
         * The Retry-After response-header field can be used with a 503 (Service
 
1006
         * Unavailable) response to indicate how long the service is expected
 
1007
         * to be unavailable to the requesting client. [...] The value of
 
1008
         * this field can be either an HTTP-date or an integer number of
 
1009
         * seconds (in decimal) after the time of the response. Retry-After
 
1010
         * = "Retry-After" ":" ( HTTP-date | delta-seconds )
 
1011
         */
 
1012
        char *secs_str = ftpmessage;
 
1013
        time_t secs;
 
1014
 
 
1015
        /* Look for a number, preceded by whitespace */
 
1016
        while (*secs_str)
 
1017
            if ((secs_str==ftpmessage || apr_isspace(secs_str[-1])) &&
 
1018
                apr_isdigit(secs_str[0]))
 
1019
                break;
 
1020
        if (*secs_str != '\0') {
 
1021
            secs = atol(secs_str);
 
1022
            apr_table_add(r->headers_out, "Retry-After",
 
1023
                          apr_psprintf(p, "%lu", (unsigned long)(60 * secs)));
 
1024
        }
 
1025
        return ftp_proxyerror(r, backend, HTTP_SERVICE_UNAVAILABLE, ftpmessage);
 
1026
    }
 
1027
    if (rc != 220) {
 
1028
        return ftp_proxyerror(r, backend, HTTP_BAD_GATEWAY, ftpmessage);
 
1029
    }
 
1030
 
 
1031
    rc = proxy_ftp_command(apr_pstrcat(p, "USER ", user, CRLF, NULL),
 
1032
                           r, origin, bb, &ftpmessage);
 
1033
    /* possible results; 230, 331, 332, 421, 500, 501, 530 */
 
1034
    /* states: 1 - error, 2 - success; 3 - send password, 4,5 fail */
 
1035
    /* 230 User logged in, proceed. */
 
1036
    /* 331 User name okay, need password. */
 
1037
    /* 332 Need account for login. */
 
1038
    /* 421 Service not available, closing control connection. */
 
1039
    /* 500 Syntax error, command unrecognized. */
 
1040
    /* (This may include errors such as command line too long.) */
 
1041
    /* 501 Syntax error in parameters or arguments. */
 
1042
    /* 530 Not logged in. */
 
1043
    if (rc == -1 || rc == 421) {
 
1044
        return ftp_proxyerror(r, backend, HTTP_BAD_GATEWAY, "Error reading from remote server");
 
1045
    }
 
1046
    if (rc == 530) {
 
1047
        proxy_ftp_cleanup(r, backend);
 
1048
        return ftp_unauthorized(r, 1);  /* log it: user name guessing
 
1049
                                         * attempt? */
 
1050
    }
 
1051
    if (rc != 230 && rc != 331) {
 
1052
        return ftp_proxyerror(r, backend, HTTP_BAD_GATEWAY, ftpmessage);
 
1053
    }
 
1054
 
 
1055
    if (rc == 331) {            /* send password */
 
1056
        if (password == NULL) {
 
1057
            proxy_ftp_cleanup(r, backend);
 
1058
            return ftp_unauthorized(r, 0);
 
1059
        }
 
1060
 
 
1061
        rc = proxy_ftp_command(apr_pstrcat(p, "PASS ", password, CRLF, NULL),
 
1062
                           r, origin, bb, &ftpmessage);
 
1063
        /* possible results 202, 230, 332, 421, 500, 501, 503, 530 */
 
1064
        /* 230 User logged in, proceed. */
 
1065
        /* 332 Need account for login. */
 
1066
        /* 421 Service not available, closing control connection. */
 
1067
        /* 500 Syntax error, command unrecognized. */
 
1068
        /* 501 Syntax error in parameters or arguments. */
 
1069
        /* 503 Bad sequence of commands. */
 
1070
        /* 530 Not logged in. */
 
1071
        if (rc == -1 || rc == 421) {
 
1072
            return ftp_proxyerror(r, backend, HTTP_BAD_GATEWAY,
 
1073
                                  "Error reading from remote server");
 
1074
        }
 
1075
        if (rc == 332) {
 
1076
            return ftp_proxyerror(r, backend, HTTP_UNAUTHORIZED,
 
1077
                  apr_pstrcat(p, "Need account for login: ", ftpmessage, NULL));
 
1078
        }
 
1079
        /* @@@ questionable -- we might as well return a 403 Forbidden here */
 
1080
        if (rc == 530) {
 
1081
            proxy_ftp_cleanup(r, backend);
 
1082
            return ftp_unauthorized(r, 1);      /* log it: passwd guessing
 
1083
                                                 * attempt? */
 
1084
        }
 
1085
        if (rc != 230 && rc != 202) {
 
1086
            return ftp_proxyerror(r, backend, HTTP_BAD_GATEWAY, ftpmessage);
 
1087
        }
 
1088
    }
 
1089
    apr_table_set(r->notes, "Directory-README", ftpmessage);
 
1090
 
 
1091
 
 
1092
    /* Special handling for leading "%2f": this enforces a "cwd /"
 
1093
     * out of the $HOME directory which was the starting point after login
 
1094
     */
 
1095
    if (strncasecmp(path, "%2f", 3) == 0) {
 
1096
        path += 3;
 
1097
        while (*path == '/') /* skip leading '/' (after root %2f) */
 
1098
            ++path;
 
1099
 
 
1100
        rc = proxy_ftp_command("CWD /" CRLF, r, origin, bb, &ftpmessage);
 
1101
        if (rc == -1 || rc == 421)
 
1102
            return ftp_proxyerror(r, backend, HTTP_BAD_GATEWAY,
 
1103
                                  "Error reading from remote server");
 
1104
    }
 
1105
 
 
1106
    /*
 
1107
     * set the directory (walk directory component by component): this is
 
1108
     * what we must do if we don't know the OS type of the remote machine
 
1109
     */
 
1110
    for (;;) {
 
1111
        strp = strchr(path, '/');
 
1112
        if (strp == NULL)
 
1113
            break;
 
1114
        *strp = '\0';
 
1115
 
 
1116
        len = decodeenc(path); /* Note! This decodes a %2f -> "/" */
 
1117
 
 
1118
        if (strchr(path, '/')) { /* are there now any '/' characters? */
 
1119
            return ftp_proxyerror(r, backend, HTTP_BAD_REQUEST,
 
1120
                                  "Use of /%2f is only allowed at the base directory");
 
1121
        }
 
1122
 
 
1123
        /* NOTE: FTP servers do globbing on the path.
 
1124
         * So we need to escape the URI metacharacters.
 
1125
         * We use a special glob-escaping routine to escape globbing chars.
 
1126
         * We could also have extended gen_test_char.c with a special T_ESCAPE_FTP_PATH
 
1127
         */
 
1128
        rc = proxy_ftp_command(apr_pstrcat(p, "CWD ",
 
1129
                           ftp_escape_globbingchars(p, path), CRLF, NULL),
 
1130
                           r, origin, bb, &ftpmessage);
 
1131
        *strp = '/';
 
1132
        /* responses: 250, 421, 500, 501, 502, 530, 550 */
 
1133
        /* 250 Requested file action okay, completed. */
 
1134
        /* 421 Service not available, closing control connection. */
 
1135
        /* 500 Syntax error, command unrecognized. */
 
1136
        /* 501 Syntax error in parameters or arguments. */
 
1137
        /* 502 Command not implemented. */
 
1138
        /* 530 Not logged in. */
 
1139
        /* 550 Requested action not taken. */
 
1140
        if (rc == -1 || rc == 421) {
 
1141
            return ftp_proxyerror(r, backend, HTTP_BAD_GATEWAY,
 
1142
                                  "Error reading from remote server");
 
1143
        }
 
1144
        if (rc == 550) {
 
1145
            return ftp_proxyerror(r, backend, HTTP_NOT_FOUND, ftpmessage);
 
1146
        }
 
1147
        if (rc != 250) {
 
1148
            return ftp_proxyerror(r, backend, HTTP_BAD_GATEWAY, ftpmessage);
 
1149
        }
 
1150
 
 
1151
        path = strp + 1;
 
1152
    }
 
1153
 
 
1154
    /*
 
1155
     * IV: Make Data Connection? -------------------------
 
1156
     *
 
1157
     * Try EPSV, if that fails... try PASV, if that fails... try PORT.
 
1158
     */
 
1159
/* this temporarily switches off EPSV/PASV */
 
1160
/*goto bypass;*/
 
1161
 
 
1162
    /* set up data connection - EPSV */
 
1163
    {
 
1164
        apr_sockaddr_t *data_addr;
 
1165
        char *data_ip;
 
1166
        apr_port_t data_port;
 
1167
 
 
1168
        /*
 
1169
         * The EPSV command replaces PASV where both IPV4 and IPV6 is
 
1170
         * supported. Only the port is returned, the IP address is always the
 
1171
         * same as that on the control connection. Example: Entering Extended
 
1172
         * Passive Mode (|||6446|)
 
1173
         */
 
1174
        rc = proxy_ftp_command("EPSV" CRLF,
 
1175
                           r, origin, bb, &ftpmessage);
 
1176
        /* possible results: 227, 421, 500, 501, 502, 530 */
 
1177
        /* 227 Entering Passive Mode (h1,h2,h3,h4,p1,p2). */
 
1178
        /* 421 Service not available, closing control connection. */
 
1179
        /* 500 Syntax error, command unrecognized. */
 
1180
        /* 501 Syntax error in parameters or arguments. */
 
1181
        /* 502 Command not implemented. */
 
1182
        /* 530 Not logged in. */
 
1183
        if (rc == -1 || rc == 421) {
 
1184
            return ftp_proxyerror(r, backend, HTTP_BAD_GATEWAY,
 
1185
                                  "Error reading from remote server");
 
1186
        }
 
1187
        if (rc != 229 && rc != 500 && rc != 501 && rc != 502) {
 
1188
            return ftp_proxyerror(r, backend, HTTP_BAD_GATEWAY, ftpmessage);
 
1189
        }
 
1190
        else if (rc == 229) {
 
1191
            char *pstr;
 
1192
            char *tok_cntx;
 
1193
 
 
1194
            pstr = ftpmessage;
 
1195
            pstr = apr_strtok(pstr, " ", &tok_cntx);    /* separate result code */
 
1196
            if (pstr != NULL) {
 
1197
                if (*(pstr + strlen(pstr) + 1) == '=') {
 
1198
                    pstr += strlen(pstr) + 2;
 
1199
                }
 
1200
                else {
 
1201
                    pstr = apr_strtok(NULL, "(", &tok_cntx);    /* separate address &
 
1202
                                                                 * port params */
 
1203
                    if (pstr != NULL)
 
1204
                        pstr = apr_strtok(NULL, ")", &tok_cntx);
 
1205
                }
 
1206
            }
 
1207
 
 
1208
            if (pstr) {
 
1209
                apr_sockaddr_t *epsv_addr;
 
1210
                data_port = atoi(pstr + 3);
 
1211
 
 
1212
                ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, r->server,
 
1213
                       "proxy: FTP: EPSV contacting remote host on port %d",
 
1214
                             data_port);
 
1215
 
 
1216
                if ((rv = apr_socket_create(&data_sock, connect_addr->family, SOCK_STREAM, 0, r->pool)) != APR_SUCCESS) {
 
1217
                    ap_log_rerror(APLOG_MARK, APLOG_ERR, rv, r,
 
1218
                                  "proxy: FTP: error creating EPSV socket");
 
1219
                    proxy_ftp_cleanup(r, backend);
 
1220
                    return HTTP_INTERNAL_SERVER_ERROR;
 
1221
                }
 
1222
 
 
1223
#if !defined (TPF) && !defined(BEOS)
 
1224
                if (conf->recv_buffer_size > 0
 
1225
                        && (rv = apr_socket_opt_set(data_sock, APR_SO_RCVBUF,
 
1226
                                                    conf->recv_buffer_size))) {
 
1227
                    ap_log_rerror(APLOG_MARK, APLOG_ERR, rv, r,
 
1228
                                  "proxy: FTP: apr_socket_opt_set(SO_RCVBUF): Failed to set ProxyReceiveBufferSize, using default");
 
1229
                }
 
1230
#endif
 
1231
 
 
1232
                /* make the connection */
 
1233
                apr_socket_addr_get(&data_addr, APR_REMOTE, sock);
 
1234
                apr_sockaddr_ip_get(&data_ip, data_addr);
 
1235
                apr_sockaddr_info_get(&epsv_addr, data_ip, connect_addr->family, data_port, 0, p);
 
1236
                rv = apr_socket_connect(data_sock, epsv_addr);
 
1237
                if (rv != APR_SUCCESS) {
 
1238
                    ap_log_error(APLOG_MARK, APLOG_ERR, rv, r->server,
 
1239
                                 "proxy: FTP: EPSV attempt to connect to %pI failed - Firewall/NAT?", epsv_addr);
 
1240
                    return ftp_proxyerror(r, backend, HTTP_BAD_GATEWAY, apr_psprintf(r->pool,
 
1241
                                                                           "EPSV attempt to connect to %pI failed - firewall/NAT?", epsv_addr));
 
1242
                }
 
1243
                else {
 
1244
                    connect = 1;
 
1245
                }
 
1246
            }
 
1247
            else {
 
1248
                /* and try the regular way */
 
1249
                apr_socket_close(data_sock);
 
1250
            }
 
1251
        }
 
1252
    }
 
1253
 
 
1254
    /* set up data connection - PASV */
 
1255
    if (!connect) {
 
1256
        rc = proxy_ftp_command("PASV" CRLF,
 
1257
                           r, origin, bb, &ftpmessage);
 
1258
        /* possible results: 227, 421, 500, 501, 502, 530 */
 
1259
        /* 227 Entering Passive Mode (h1,h2,h3,h4,p1,p2). */
 
1260
        /* 421 Service not available, closing control connection. */
 
1261
        /* 500 Syntax error, command unrecognized. */
 
1262
        /* 501 Syntax error in parameters or arguments. */
 
1263
        /* 502 Command not implemented. */
 
1264
        /* 530 Not logged in. */
 
1265
        if (rc == -1 || rc == 421) {
 
1266
            return ftp_proxyerror(r, backend, HTTP_BAD_GATEWAY,
 
1267
                                  "Error reading from remote server");
 
1268
        }
 
1269
        if (rc != 227 && rc != 502) {
 
1270
            return ftp_proxyerror(r, backend, HTTP_BAD_GATEWAY, ftpmessage);
 
1271
        }
 
1272
        else if (rc == 227) {
 
1273
            unsigned int h0, h1, h2, h3, p0, p1;
 
1274
            char *pstr;
 
1275
            char *tok_cntx;
 
1276
 
 
1277
/* FIXME: Check PASV against RFC1123 */
 
1278
 
 
1279
            pstr = ftpmessage;
 
1280
            pstr = apr_strtok(pstr, " ", &tok_cntx);    /* separate result code */
 
1281
            if (pstr != NULL) {
 
1282
                if (*(pstr + strlen(pstr) + 1) == '=') {
 
1283
                    pstr += strlen(pstr) + 2;
 
1284
                }
 
1285
                else {
 
1286
                    pstr = apr_strtok(NULL, "(", &tok_cntx);    /* separate address &
 
1287
                                                                 * port params */
 
1288
                    if (pstr != NULL)
 
1289
                        pstr = apr_strtok(NULL, ")", &tok_cntx);
 
1290
                }
 
1291
            }
 
1292
 
 
1293
/* FIXME: Only supports IPV4 - fix in RFC2428 */
 
1294
 
 
1295
            if (pstr != NULL && (sscanf(pstr,
 
1296
                 "%d,%d,%d,%d,%d,%d", &h3, &h2, &h1, &h0, &p1, &p0) == 6)) {
 
1297
 
 
1298
                apr_sockaddr_t *pasv_addr;
 
1299
                apr_port_t pasvport = (p1 << 8) + p0;
 
1300
                ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, r->server,
 
1301
                          "proxy: FTP: PASV contacting host %d.%d.%d.%d:%d",
 
1302
                             h3, h2, h1, h0, pasvport);
 
1303
 
 
1304
                if ((rv = apr_socket_create(&data_sock, connect_addr->family, SOCK_STREAM, 0, r->pool)) != APR_SUCCESS) {
 
1305
                    ap_log_rerror(APLOG_MARK, APLOG_ERR, rv, r,
 
1306
                                  "proxy: error creating PASV socket");
 
1307
                    proxy_ftp_cleanup(r, backend);
 
1308
                    return HTTP_INTERNAL_SERVER_ERROR;
 
1309
                }
 
1310
 
 
1311
#if !defined (TPF) && !defined(BEOS)
 
1312
                if (conf->recv_buffer_size > 0
 
1313
                        && (rv = apr_socket_opt_set(data_sock, APR_SO_RCVBUF,
 
1314
                                                    conf->recv_buffer_size))) {
 
1315
                    ap_log_rerror(APLOG_MARK, APLOG_ERR, rv, r,
 
1316
                                  "proxy: FTP: apr_socket_opt_set(SO_RCVBUF): Failed to set ProxyReceiveBufferSize, using default");
 
1317
                }
 
1318
#endif
 
1319
 
 
1320
                /* make the connection */
 
1321
                apr_sockaddr_info_get(&pasv_addr, apr_psprintf(p, "%d.%d.%d.%d", h3, h2, h1, h0), connect_addr->family, pasvport, 0, p);
 
1322
                rv = apr_socket_connect(data_sock, pasv_addr);
 
1323
                if (rv != APR_SUCCESS) {
 
1324
                    ap_log_error(APLOG_MARK, APLOG_ERR, rv, r->server,
 
1325
                                 "proxy: FTP: PASV attempt to connect to %pI failed - Firewall/NAT?", pasv_addr);
 
1326
                    return ftp_proxyerror(r, backend, HTTP_BAD_GATEWAY, apr_psprintf(r->pool,
 
1327
                                                                           "PASV attempt to connect to %pI failed - firewall/NAT?", pasv_addr));
 
1328
                }
 
1329
                else {
 
1330
                    connect = 1;
 
1331
                }
 
1332
            }
 
1333
            else {
 
1334
                /* and try the regular way */
 
1335
                apr_socket_close(data_sock);
 
1336
            }
 
1337
        }
 
1338
    }
 
1339
/*bypass:*/
 
1340
 
 
1341
    /* set up data connection - PORT */
 
1342
    if (!connect) {
 
1343
        apr_sockaddr_t *local_addr;
 
1344
        char *local_ip;
 
1345
        apr_port_t local_port;
 
1346
        unsigned int h0, h1, h2, h3, p0, p1;
 
1347
 
 
1348
        if ((rv = apr_socket_create(&local_sock, connect_addr->family, SOCK_STREAM, 0, r->pool)) != APR_SUCCESS) {
 
1349
            ap_log_rerror(APLOG_MARK, APLOG_ERR, rv, r,
 
1350
                          "proxy: FTP: error creating local socket");
 
1351
            proxy_ftp_cleanup(r, backend);
 
1352
            return HTTP_INTERNAL_SERVER_ERROR;
 
1353
        }
 
1354
        apr_socket_addr_get(&local_addr, APR_LOCAL, sock);
 
1355
        local_port = local_addr->port;
 
1356
        apr_sockaddr_ip_get(&local_ip, local_addr);
 
1357
 
 
1358
        if ((rv = apr_socket_opt_set(local_sock, APR_SO_REUSEADDR, one))
 
1359
                != APR_SUCCESS) {
 
1360
#ifndef _OSD_POSIX              /* BS2000 has this option "always on" */
 
1361
            ap_log_rerror(APLOG_MARK, APLOG_ERR, rv, r,
 
1362
                          "proxy: FTP: error setting reuseaddr option");
 
1363
            proxy_ftp_cleanup(r, backend);
 
1364
            return HTTP_INTERNAL_SERVER_ERROR;
 
1365
#endif                          /* _OSD_POSIX */
 
1366
        }
 
1367
 
 
1368
        apr_sockaddr_info_get(&local_addr, local_ip, APR_UNSPEC, local_port, 0, r->pool);
 
1369
 
 
1370
        if ((rv = apr_socket_bind(local_sock, local_addr)) != APR_SUCCESS) {
 
1371
            ap_log_rerror(APLOG_MARK, APLOG_ERR, rv, r,
 
1372
            "proxy: FTP: error binding to ftp data socket %pI", local_addr);
 
1373
            proxy_ftp_cleanup(r, backend);
 
1374
            return HTTP_INTERNAL_SERVER_ERROR;
 
1375
        }
 
1376
 
 
1377
        /* only need a short queue */
 
1378
        if ((rv = apr_socket_listen(local_sock, 2)) != APR_SUCCESS) {
 
1379
            ap_log_rerror(APLOG_MARK, APLOG_ERR, rv, r,
 
1380
                          "proxy: FTP: error listening to ftp data socket %pI", local_addr);
 
1381
            proxy_ftp_cleanup(r, backend);
 
1382
            return HTTP_INTERNAL_SERVER_ERROR;
 
1383
        }
 
1384
 
 
1385
/* FIXME: Sent PORT here */
 
1386
 
 
1387
        if (local_ip && (sscanf(local_ip,
 
1388
                                "%d.%d.%d.%d", &h3, &h2, &h1, &h0) == 4)) {
 
1389
            p1 = (local_port >> 8);
 
1390
            p0 = (local_port & 0xFF);
 
1391
 
 
1392
            rc = proxy_ftp_command(apr_psprintf(p, "PORT %d,%d,%d,%d,%d,%d" CRLF, h3, h2, h1, h0, p1, p0),
 
1393
                           r, origin, bb, &ftpmessage);
 
1394
            /* possible results: 200, 421, 500, 501, 502, 530 */
 
1395
            /* 200 Command okay. */
 
1396
            /* 421 Service not available, closing control connection. */
 
1397
            /* 500 Syntax error, command unrecognized. */
 
1398
            /* 501 Syntax error in parameters or arguments. */
 
1399
            /* 502 Command not implemented. */
 
1400
            /* 530 Not logged in. */
 
1401
            if (rc == -1 || rc == 421) {
 
1402
                return ftp_proxyerror(r, backend, HTTP_BAD_GATEWAY,
 
1403
                                      "Error reading from remote server");
 
1404
            }
 
1405
            if (rc != 200) {
 
1406
                return ftp_proxyerror(r, backend, HTTP_BAD_GATEWAY, buffer);
 
1407
            }
 
1408
 
 
1409
            /* signal that we must use the EPRT/PORT loop */
 
1410
            use_port = 1;
 
1411
        }
 
1412
        else {
 
1413
/* IPV6 FIXME:
 
1414
 * The EPRT command replaces PORT where both IPV4 and IPV6 is supported. The first
 
1415
 * number (1,2) indicates the protocol type. Examples:
 
1416
 *   EPRT |1|132.235.1.2|6275|
 
1417
 *   EPRT |2|1080::8:800:200C:417A|5282|
 
1418
 */
 
1419
            return ftp_proxyerror(r, backend, HTTP_NOT_IMPLEMENTED,
 
1420
                                  "Connect to IPV6 ftp server using EPRT not supported. Enable EPSV.");
 
1421
        }
 
1422
    }
 
1423
 
 
1424
 
 
1425
    /*
 
1426
     * V: Set The Headers -------------------
 
1427
     *
 
1428
     * Get the size of the request, set up the environment for HTTP.
 
1429
     */
 
1430
 
 
1431
    /* set request; "path" holds last path component */
 
1432
    len = decodeenc(path);
 
1433
 
 
1434
    if (strchr(path, '/')) { /* are there now any '/' characters? */
 
1435
       return ftp_proxyerror(r, backend, HTTP_BAD_REQUEST,
 
1436
                             "Use of /%2f is only allowed at the base directory");
 
1437
    }
 
1438
 
 
1439
    /* If len == 0 then it must be a directory (you can't RETR nothing)
 
1440
     * Also, don't allow to RETR by wildcard. Instead, create a dirlisting
 
1441
     */
 
1442
    if (len == 0 || ftp_check_globbingchars(path)) {
 
1443
        dirlisting = 1;
 
1444
    }
 
1445
    else {
 
1446
        /* (from FreeBSD ftpd):
 
1447
         * SIZE is not in RFC959, but Postel has blessed it and
 
1448
         * it will be in the updated RFC.
 
1449
         *
 
1450
         * Return size of file in a format suitable for
 
1451
         * using with RESTART (we just count bytes).
 
1452
         */
 
1453
        /* from draft-ietf-ftpext-mlst-14.txt:
 
1454
         * This value will
 
1455
         * change depending on the current STRUcture, MODE and TYPE of the data
 
1456
         * connection, or a data connection which would be created were one
 
1457
         * created now.  Thus, the result of the SIZE command is dependent on
 
1458
         * the currently established STRU, MODE and TYPE parameters.
 
1459
         */
 
1460
        /* Therefore: switch to binary if the user did not specify ";type=a" */
 
1461
        ftp_set_TYPE(xfer_type, r, origin, bb, &ftpmessage);
 
1462
        rc = proxy_ftp_command(apr_pstrcat(p, "SIZE ",
 
1463
                           ftp_escape_globbingchars(p, path), CRLF, NULL),
 
1464
                           r, origin, bb, &ftpmessage);
 
1465
        if (rc == -1 || rc == 421) {
 
1466
            return ftp_proxyerror(r, backend, HTTP_BAD_GATEWAY,
 
1467
                                  "Error reading from remote server");
 
1468
        }
 
1469
        else if (rc == 213) {/* Size command ok */
 
1470
            int j;
 
1471
            for (j = 0; apr_isdigit(ftpmessage[j]); j++)
 
1472
                ;
 
1473
            ftpmessage[j] = '\0';
 
1474
            if (ftpmessage[0] != '\0')
 
1475
                 size = ftpmessage; /* already pstrdup'ed: no copy necessary */
 
1476
        }
 
1477
        else if (rc == 550) {    /* Not a regular file */
 
1478
            ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, r->server,
 
1479
                             "proxy: FTP: SIZE shows this is a directory");
 
1480
            dirlisting = 1;
 
1481
            rc = proxy_ftp_command(apr_pstrcat(p, "CWD ",
 
1482
                           ftp_escape_globbingchars(p, path), CRLF, NULL),
 
1483
                           r, origin, bb, &ftpmessage);
 
1484
            /* possible results: 250, 421, 500, 501, 502, 530, 550 */
 
1485
            /* 250 Requested file action okay, completed. */
 
1486
            /* 421 Service not available, closing control connection. */
 
1487
            /* 500 Syntax error, command unrecognized. */
 
1488
            /* 501 Syntax error in parameters or arguments. */
 
1489
            /* 502 Command not implemented. */
 
1490
            /* 530 Not logged in. */
 
1491
            /* 550 Requested action not taken. */
 
1492
            if (rc == -1 || rc == 421) {
 
1493
                return ftp_proxyerror(r, backend, HTTP_BAD_GATEWAY,
 
1494
                                      "Error reading from remote server");
 
1495
            }
 
1496
            if (rc == 550) {
 
1497
                return ftp_proxyerror(r, backend, HTTP_NOT_FOUND, ftpmessage);
 
1498
            }
 
1499
            if (rc != 250) {
 
1500
                return ftp_proxyerror(r, backend, HTTP_BAD_GATEWAY, ftpmessage);
 
1501
            }
 
1502
            path = "";
 
1503
            len = 0;
 
1504
        }
 
1505
    }
 
1506
 
 
1507
    cwd = ftp_get_PWD(r, origin, bb);
 
1508
    if (cwd != NULL) {
 
1509
        apr_table_set(r->notes, "Directory-PWD", cwd);
 
1510
    }
 
1511
 
 
1512
    if (dirlisting) {
 
1513
        ftp_set_TYPE('A', r, origin, bb, NULL);
 
1514
        /* If the current directory contains no slash, we are talking to
 
1515
         * a non-unix ftp system. Try LIST instead of "LIST -lag", it
 
1516
         * should return a long listing anyway (unlike NLST).
 
1517
         * Some exotic FTP servers might choke on the "-lag" switch.
 
1518
         */
 
1519
        /* Note that we do not escape the path here, to allow for
 
1520
         * queries like: ftp://user@host/apache/src/server/http_*.c
 
1521
         */
 
1522
        if (len != 0)
 
1523
            buf = apr_pstrcat(p, "LIST ", path, CRLF, NULL);
 
1524
        else if (cwd == NULL || strchr(cwd, '/') != NULL)
 
1525
            buf = apr_pstrcat(p, "LIST -lag", CRLF, NULL);
 
1526
        else
 
1527
            buf = "LIST" CRLF;
 
1528
    }
 
1529
    else {
 
1530
        /* switch to binary if the user did not specify ";type=a" */
 
1531
        ftp_set_TYPE(xfer_type, r, origin, bb, &ftpmessage);
 
1532
#if defined(USE_MDTM) && (defined(HAVE_TIMEGM) || defined(HAVE_GMTOFF))
 
1533
        /* from draft-ietf-ftpext-mlst-14.txt:
 
1534
         *   The FTP command, MODIFICATION TIME (MDTM), can be used to determine
 
1535
         *   when a file in the server NVFS was last modified.     <..>
 
1536
         *   The syntax of a time value is:
 
1537
         *           time-val       = 14DIGIT [ "." 1*DIGIT ]      <..>
 
1538
         *     Symbolically, a time-val may be viewed as
 
1539
         *           YYYYMMDDHHMMSS.sss
 
1540
         *     The "." and subsequent digits ("sss") are optional. <..>
 
1541
         *     Time values are always represented in UTC (GMT)
 
1542
         */
 
1543
        rc = proxy_ftp_command(apr_pstrcat(p, "MDTM ", ftp_escape_globbingchars(p, path), CRLF, NULL),
 
1544
                               r, origin, bb, &ftpmessage);
 
1545
        /* then extract the Last-Modified time from it (YYYYMMDDhhmmss or YYYYMMDDhhmmss.xxx GMT). */
 
1546
        if (rc == 213) {
 
1547
        struct {
 
1548
            char YYYY[4+1];
 
1549
        char MM[2+1];
 
1550
        char DD[2+1];
 
1551
        char hh[2+1];
 
1552
        char mm[2+1];
 
1553
        char ss[2+1];
 
1554
        } time_val;
 
1555
        if (6 == sscanf(ftpmessage, "%4[0-9]%2[0-9]%2[0-9]%2[0-9]%2[0-9]%2[0-9]",
 
1556
            time_val.YYYY, time_val.MM, time_val.DD, time_val.hh, time_val.mm, time_val.ss)) {
 
1557
                struct tm tms;
 
1558
        memset (&tms, '\0', sizeof tms);
 
1559
        tms.tm_year = atoi(time_val.YYYY) - 1900;
 
1560
        tms.tm_mon  = atoi(time_val.MM)   - 1;
 
1561
        tms.tm_mday = atoi(time_val.DD);
 
1562
        tms.tm_hour = atoi(time_val.hh);
 
1563
        tms.tm_min  = atoi(time_val.mm);
 
1564
        tms.tm_sec  = atoi(time_val.ss);
 
1565
#ifdef HAVE_TIMEGM /* Does system have timegm()? */
 
1566
        mtime = timegm(&tms);
 
1567
        mtime *= APR_USEC_PER_SEC;
 
1568
#elif HAVE_GMTOFF /* does struct tm have a member tm_gmtoff? */
 
1569
                /* mktime will subtract the local timezone, which is not what we want.
 
1570
         * Add it again because the MDTM string is GMT
 
1571
         */
 
1572
        mtime = mktime(&tms);
 
1573
        mtime += tms.tm_gmtoff;
 
1574
        mtime *= APR_USEC_PER_SEC;
 
1575
#else
 
1576
        mtime = 0L;
 
1577
#endif
 
1578
            }
 
1579
    }
 
1580
#endif /* USE_MDTM */
 
1581
/* FIXME: Handle range requests - send REST */
 
1582
        buf = apr_pstrcat(p, "RETR ", ftp_escape_globbingchars(p, path), CRLF, NULL);
 
1583
    }
 
1584
    rc = proxy_ftp_command(buf, r, origin, bb, &ftpmessage);
 
1585
    /* rc is an intermediate response for the LIST or RETR commands */
 
1586
 
 
1587
    /*
 
1588
     * RETR: 110, 125, 150, 226, 250, 421, 425, 426, 450, 451, 500, 501, 530,
 
1589
     * 550 NLST: 125, 150, 226, 250, 421, 425, 426, 450, 451, 500, 501, 502,
 
1590
     * 530
 
1591
     */
 
1592
    /* 110 Restart marker reply. */
 
1593
    /* 125 Data connection already open; transfer starting. */
 
1594
    /* 150 File status okay; about to open data connection. */
 
1595
    /* 226 Closing data connection. */
 
1596
    /* 250 Requested file action okay, completed. */
 
1597
    /* 421 Service not available, closing control connection. */
 
1598
    /* 425 Can't open data connection. */
 
1599
    /* 426 Connection closed; transfer aborted. */
 
1600
    /* 450 Requested file action not taken. */
 
1601
    /* 451 Requested action aborted. Local error in processing. */
 
1602
    /* 500 Syntax error, command unrecognized. */
 
1603
    /* 501 Syntax error in parameters or arguments. */
 
1604
    /* 530 Not logged in. */
 
1605
    /* 550 Requested action not taken. */
 
1606
    if (rc == -1 || rc == 421) {
 
1607
        return ftp_proxyerror(r, backend, HTTP_BAD_GATEWAY,
 
1608
                              "Error reading from remote server");
 
1609
    }
 
1610
    if (rc == 550) {
 
1611
        ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, r->server,
 
1612
                     "proxy: FTP: RETR failed, trying LIST instead");
 
1613
 
 
1614
        /* Directory Listings should always be fetched in ASCII mode */
 
1615
        dirlisting = 1;
 
1616
        ftp_set_TYPE('A', r, origin, bb, NULL);
 
1617
 
 
1618
        rc = proxy_ftp_command(apr_pstrcat(p, "CWD ",
 
1619
                               ftp_escape_globbingchars(p, path), CRLF, NULL),
 
1620
                               r, origin, bb, &ftpmessage);
 
1621
        /* possible results: 250, 421, 500, 501, 502, 530, 550 */
 
1622
        /* 250 Requested file action okay, completed. */
 
1623
        /* 421 Service not available, closing control connection. */
 
1624
        /* 500 Syntax error, command unrecognized. */
 
1625
        /* 501 Syntax error in parameters or arguments. */
 
1626
        /* 502 Command not implemented. */
 
1627
        /* 530 Not logged in. */
 
1628
        /* 550 Requested action not taken. */
 
1629
        if (rc == -1 || rc == 421) {
 
1630
            return ftp_proxyerror(r, backend, HTTP_BAD_GATEWAY,
 
1631
                                  "Error reading from remote server");
 
1632
        }
 
1633
        if (rc == 550) {
 
1634
            return ftp_proxyerror(r, backend, HTTP_NOT_FOUND, ftpmessage);
 
1635
        }
 
1636
        if (rc != 250) {
 
1637
            return ftp_proxyerror(r, backend, HTTP_BAD_GATEWAY, ftpmessage);
 
1638
        }
 
1639
 
 
1640
        /* Update current directory after CWD */
 
1641
        cwd = ftp_get_PWD(r, origin, bb);
 
1642
        if (cwd != NULL) {
 
1643
            apr_table_set(r->notes, "Directory-PWD", cwd);
 
1644
        }
 
1645
 
 
1646
        /* See above for the "LIST" vs. "LIST -lag" discussion. */
 
1647
        rc = proxy_ftp_command((cwd == NULL || strchr(cwd, '/') != NULL)
 
1648
                               ? "LIST -lag" CRLF : "LIST" CRLF,
 
1649
                               r, origin, bb, &ftpmessage);
 
1650
 
 
1651
        /* rc is an intermediate response for the LIST command (125 transfer starting, 150 opening data connection) */
 
1652
        if (rc == -1 || rc == 421)
 
1653
            return ftp_proxyerror(r, backend, HTTP_BAD_GATEWAY,
 
1654
                                  "Error reading from remote server");
 
1655
    }
 
1656
    if (rc != 125 && rc != 150 && rc != 226 && rc != 250) {
 
1657
        return ftp_proxyerror(r, backend, HTTP_BAD_GATEWAY, ftpmessage);
 
1658
    }
 
1659
 
 
1660
    r->status = HTTP_OK;
 
1661
    r->status_line = "200 OK";
 
1662
 
 
1663
    apr_rfc822_date(dates, r->request_time);
 
1664
    apr_table_setn(r->headers_out, "Date", dates);
 
1665
    apr_table_setn(r->headers_out, "Server", ap_get_server_version());
 
1666
 
 
1667
    /* set content-type */
 
1668
    if (dirlisting) {
 
1669
        ap_set_content_type(r, "text/html");
 
1670
    }
 
1671
    else {
 
1672
        if (r->content_type) {
 
1673
            ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, r->server,
 
1674
                     "proxy: FTP: Content-Type set to %s", r->content_type);
 
1675
        }
 
1676
        else {
 
1677
            ap_set_content_type(r, ap_default_type(r));
 
1678
        }
 
1679
        if (xfer_type != 'A' && size != NULL) {
 
1680
            /* We "trust" the ftp server to really serve (size) bytes... */
 
1681
            apr_table_setn(r->headers_out, "Content-Length", size);
 
1682
            ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, r->server,
 
1683
                         "proxy: FTP: Content-Length set to %s", size);
 
1684
        }
 
1685
    }
 
1686
    apr_table_setn(r->headers_out, "Content-Type", r->content_type);
 
1687
    ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, r->server,
 
1688
                 "proxy: FTP: Content-Type set to %s", r->content_type);
 
1689
 
 
1690
#if defined(USE_MDTM) && (defined(HAVE_TIMEGM) || defined(HAVE_GMTOFF))
 
1691
    if (mtime != 0L) {
 
1692
        char datestr[APR_RFC822_DATE_LEN];
 
1693
        apr_rfc822_date(datestr, mtime);
 
1694
        apr_table_set(r->headers_out, "Last-Modified", datestr);
 
1695
        ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, r->server,
 
1696
                 "proxy: FTP: Last-Modified set to %s", datestr);
 
1697
    }
 
1698
#endif /* USE_MDTM */
 
1699
 
 
1700
    /* If an encoding has been set by mistake, delete it.
 
1701
     * @@@ FIXME (e.g., for ftp://user@host/file*.tar.gz,
 
1702
     * @@@        the encoding is currently set to x-gzip)
 
1703
     */
 
1704
    if (dirlisting && r->content_encoding != NULL)
 
1705
        r->content_encoding = NULL;
 
1706
 
 
1707
    /* set content-encoding (not for dir listings, they are uncompressed)*/
 
1708
    if (r->content_encoding != NULL && r->content_encoding[0] != '\0') {
 
1709
        ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, r->server,
 
1710
             "proxy: FTP: Content-Encoding set to %s", r->content_encoding);
 
1711
        apr_table_setn(r->headers_out, "Content-Encoding", r->content_encoding);
 
1712
    }
 
1713
 
 
1714
    /* wait for connection */
 
1715
    if (use_port) {
 
1716
        for (;;) {
 
1717
            rv = apr_socket_accept(&data_sock, local_sock, r->pool);
 
1718
            if (rv == APR_EINTR) {
 
1719
                continue;
 
1720
            }
 
1721
            else if (rv == APR_SUCCESS) {
 
1722
                break;
 
1723
            }
 
1724
            else {
 
1725
                ap_log_rerror(APLOG_MARK, APLOG_ERR, rv, r,
 
1726
                            "proxy: FTP: failed to accept data connection");
 
1727
                proxy_ftp_cleanup(r, backend);
 
1728
                return HTTP_BAD_GATEWAY;
 
1729
            }
 
1730
        }
 
1731
    }
 
1732
 
 
1733
    /* the transfer socket is now open, create a new connection */
 
1734
    data = ap_run_create_connection(p, r->server, data_sock, r->connection->id,
 
1735
                                    r->connection->sbh, c->bucket_alloc);
 
1736
    if (!data) {
 
1737
        /*
 
1738
         * the peer reset the connection already; ap_run_create_connection() closed
 
1739
         * the socket
 
1740
         */
 
1741
        ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, r->server,
 
1742
          "proxy: FTP: an error occurred creating the transfer connection");
 
1743
        proxy_ftp_cleanup(r, backend);
 
1744
        return HTTP_INTERNAL_SERVER_ERROR;
 
1745
    }
 
1746
 
 
1747
    /* set up the connection filters */
 
1748
    rc = ap_run_pre_connection(data, data_sock);
 
1749
    if (rc != OK && rc != DONE) {
 
1750
        ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, r->server,
 
1751
                     "proxy: FTP: pre_connection setup failed (%d)",
 
1752
                     rc);
 
1753
        data->aborted = 1;
 
1754
        proxy_ftp_cleanup(r, backend);
 
1755
        return rc;
 
1756
    }
 
1757
 
 
1758
    /*
 
1759
     * VI: Receive the Response ------------------------
 
1760
     *
 
1761
     * Get response from the remote ftp socket, and pass it up the filter chain.
 
1762
     */
 
1763
 
 
1764
    /* send response */
 
1765
    r->sent_bodyct = 1;
 
1766
 
 
1767
    if (dirlisting) {
 
1768
        /* insert directory filter */
 
1769
        ap_add_output_filter("PROXY_SEND_DIR", NULL, r, r->connection);
 
1770
    }
 
1771
 
 
1772
    /* send body */
 
1773
    if (!r->header_only) {
 
1774
        apr_bucket *e;
 
1775
        int finish = FALSE;
 
1776
 
 
1777
        ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, r->server,
 
1778
                     "proxy: FTP: start body send");
 
1779
 
 
1780
        /* read the body, pass it to the output filters */
 
1781
        while (ap_get_brigade(data->input_filters,
 
1782
                              bb,
 
1783
                              AP_MODE_READBYTES,
 
1784
                              APR_BLOCK_READ,
 
1785
                              conf->io_buffer_size) == APR_SUCCESS) {
 
1786
#if DEBUGGING
 
1787
            {
 
1788
                apr_off_t readbytes;
 
1789
                apr_brigade_length(bb, 0, &readbytes);
 
1790
                ap_log_error(APLOG_MARK, APLOG_DEBUG, 0,
 
1791
                             r->server, "proxy (PID %d): readbytes: %#x",
 
1792
                             getpid(), readbytes);
 
1793
            }
 
1794
#endif
 
1795
            /* sanity check */
 
1796
            if (APR_BRIGADE_EMPTY(bb)) {
 
1797
                apr_brigade_cleanup(bb);
 
1798
                break;
 
1799
            }
 
1800
 
 
1801
            /* found the last brigade? */
 
1802
            if (APR_BUCKET_IS_EOS(APR_BRIGADE_LAST(bb))) {
 
1803
                /* if this is the last brigade, cleanup the
 
1804
                 * backend connection first to prevent the
 
1805
                 * backend server from hanging around waiting
 
1806
                 * for a slow client to eat these bytes
 
1807
                 */
 
1808
                ap_flush_conn(data);
 
1809
                apr_socket_close(data_sock);
 
1810
                data_sock = NULL;
 
1811
                ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, r->server,
 
1812
                             "proxy: FTP: data connection closed");
 
1813
                /* signal that we must leave */
 
1814
                finish = TRUE;
 
1815
            }
 
1816
 
 
1817
            /* if no EOS yet, then we must flush */
 
1818
            if (FALSE == finish) {
 
1819
                e = apr_bucket_flush_create(c->bucket_alloc);
 
1820
                APR_BRIGADE_INSERT_TAIL(bb, e);
 
1821
            }
 
1822
 
 
1823
            /* try send what we read */
 
1824
            if (ap_pass_brigade(r->output_filters, bb) != APR_SUCCESS
 
1825
                || c->aborted) {
 
1826
                /* Ack! Phbtt! Die! User aborted! */
 
1827
                finish = TRUE;
 
1828
            }
 
1829
 
 
1830
            /* make sure we always clean up after ourselves */
 
1831
            apr_brigade_cleanup(bb);
 
1832
 
 
1833
            /* if we are done, leave */
 
1834
            if (TRUE == finish) {
 
1835
                break;
 
1836
            }
 
1837
        }
 
1838
        ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, r->server,
 
1839
                     "proxy: FTP: end body send");
 
1840
 
 
1841
    }
 
1842
    if (data_sock) {
 
1843
        ap_flush_conn(data);
 
1844
        apr_socket_close(data_sock);
 
1845
        ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, r->server,
 
1846
                     "proxy: FTP: data connection closed");
 
1847
    }
 
1848
 
 
1849
    /* Retrieve the final response for the RETR or LIST commands */
 
1850
    rc = proxy_ftp_command(NULL, r, origin, bb, &ftpmessage);
 
1851
    apr_brigade_cleanup(bb);
 
1852
 
 
1853
    /*
 
1854
     * VII: Clean Up -------------
 
1855
     *
 
1856
     * If there are no KeepAlives, or if the connection has been signalled to
 
1857
     * close, close the socket and clean up
 
1858
     */
 
1859
 
 
1860
    /* finish */
 
1861
    rc = proxy_ftp_command("QUIT" CRLF,
 
1862
                           r, origin, bb, &ftpmessage);
 
1863
    /* responses: 221, 500 */
 
1864
    /* 221 Service closing control connection. */
 
1865
    /* 500 Syntax error, command unrecognized. */
 
1866
    ap_flush_conn(origin);
 
1867
    proxy_ftp_cleanup(r, backend);
 
1868
 
 
1869
    apr_brigade_destroy(bb);
 
1870
    return OK;
 
1871
}
 
1872
 
 
1873
static void ap_proxy_ftp_register_hook(apr_pool_t *p)
 
1874
{
 
1875
    /* hooks */
 
1876
    proxy_hook_scheme_handler(proxy_ftp_handler, NULL, NULL, APR_HOOK_MIDDLE);
 
1877
    proxy_hook_canon_handler(proxy_ftp_canon, NULL, NULL, APR_HOOK_MIDDLE);
 
1878
    /* filters */
 
1879
    ap_register_output_filter("PROXY_SEND_DIR", proxy_send_dir_filter,
 
1880
                              NULL, AP_FTYPE_RESOURCE);
 
1881
}
 
1882
 
 
1883
module AP_MODULE_DECLARE_DATA proxy_ftp_module = {
 
1884
    STANDARD20_MODULE_STUFF,
 
1885
    NULL,                       /* create per-directory config structure */
 
1886
    NULL,                       /* merge per-directory config structures */
 
1887
    NULL,                       /* create per-server config structure */
 
1888
    NULL,                       /* merge per-server config structures */
 
1889
    NULL,                       /* command apr_table_t */
 
1890
    ap_proxy_ftp_register_hook  /* register hooks */
 
1891
};