1
/* Licensed to the Apache Software Foundation (ASF) under one or more
2
* contributor license agreements. See the NOTICE file distributed with
3
* this work for additional information regarding copyright ownership.
4
* The ASF licenses this file to You under the Apache License, Version 2.0
5
* (the "License"); you may not use this file except in compliance with
6
* the License. You may obtain a copy of the License at
8
* http://www.apache.org/licenses/LICENSE-2.0
10
* Unless required by applicable law or agreed to in writing, software
11
* distributed under the License is distributed on an "AS IS" BASIS,
12
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
* See the License for the specific language governing permissions and
14
* limitations under the License.
17
/* FTP routines for Apache proxy */
19
#include "mod_proxy.h"
23
#include "apr_version.h"
25
#if (APR_MAJOR_VERSION < 1)
26
#undef apr_socket_create
27
#define apr_socket_create apr_socket_create_ex
30
#define AUTODETECT_PWD
31
/* Automatic timestamping (Last-Modified header) based on MDTM is used if:
32
* 1) the FTP server supports the MDTM command and
33
* 2) HAVE_TIMEGM (preferred) or HAVE_GMTOFF is available at compile time
38
module AP_MODULE_DECLARE_DATA proxy_ftp_module;
41
* Decodes a '%' escaped string, and returns the number of characters
43
static int decodeenc(char *x)
48
return 0; /* special case for no characters */
49
for (i = 0, j = 0; x[i] != '\0'; i++, j++) {
50
/* decode it if not already done */
52
if (ch == '%' && apr_isxdigit(x[i + 1]) && apr_isxdigit(x[i + 2])) {
53
ch = ap_proxy_hex2c(&x[i + 1]);
63
* Escape the globbing characters in a path used as argument to
64
* the FTP commands (SIZE, CWD, RETR, MDTM, ...).
65
* ftpd assumes '\\' as a quoting character to escape special characters.
66
* Returns: escaped string
68
#define FTP_GLOBBING_CHARS "*?[{~"
69
static char *ftp_escape_globbingchars(apr_pool_t *p, const char *path)
71
char *ret = apr_palloc(p, 2*strlen(path)+sizeof(""));
73
for (d = ret; *path; ++path) {
74
if (strchr(FTP_GLOBBING_CHARS, *path) != NULL)
83
* Check for globbing characters in a path used as argument to
84
* the FTP commands (SIZE, CWD, RETR, MDTM, ...).
85
* ftpd assumes '\\' as a quoting character to escape special characters.
86
* Returns: 0 (no globbing chars, or all globbing chars escaped), 1 (globbing chars)
88
static int ftp_check_globbingchars(const char *path)
90
for ( ; *path; ++path) {
93
if (*path != '\0' && strchr(FTP_GLOBBING_CHARS, *path) != NULL)
100
* checks an encoded ftp string for bad characters, namely, CR, LF or
101
* non-ascii character
103
static int ftp_check_string(const char *x)
106
#if APR_CHARSET_EBCDIC
110
for (i = 0; x[i] != '\0'; i++) {
112
if (ch == '%' && apr_isxdigit(x[i + 1]) && apr_isxdigit(x[i + 2])) {
113
ch = ap_proxy_hex2c(&x[i + 1]);
116
#if !APR_CHARSET_EBCDIC
117
if (ch == '\015' || ch == '\012' || (ch & 0x80))
118
#else /* APR_CHARSET_EBCDIC */
119
if (ch == '\r' || ch == '\n')
122
ap_xlate_proto_to_ascii(buf, 1);
124
#endif /* APR_CHARSET_EBCDIC */
131
* Canonicalise ftp URLs.
133
static int proxy_ftp_canon(request_rec *r, char *url)
135
char *user, *password, *host, *path, *parms, *strp, sport[7];
136
apr_pool_t *p = r->pool;
138
apr_port_t port, def_port;
141
if (strncasecmp(url, "ftp:", 4) == 0) {
147
def_port = apr_uri_port_of_scheme("ftp");
149
ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, r->server,
150
"proxy: FTP: canonicalising URL %s", url);
153
err = ap_proxy_canon_netloc(p, &url, &user, &password, &host, &port);
155
return HTTP_BAD_REQUEST;
156
if (user != NULL && !ftp_check_string(user))
157
return HTTP_BAD_REQUEST;
158
if (password != NULL && !ftp_check_string(password))
159
return HTTP_BAD_REQUEST;
161
/* now parse path/parameters args, according to rfc1738 */
163
* N.B. if this isn't a true proxy request, then the URL path (but not
164
* query args) has already been decoded. This gives rise to the problem
165
* of a ; being decoded into the path.
167
strp = strchr(url, ';');
170
parms = ap_proxy_canonenc(p, strp, strlen(strp), enc_parm, 0,
173
return HTTP_BAD_REQUEST;
178
path = ap_proxy_canonenc(p, url, strlen(url), enc_path, 0, r->proxyreq);
180
return HTTP_BAD_REQUEST;
181
if (!ftp_check_string(path))
182
return HTTP_BAD_REQUEST;
184
if (r->proxyreq && r->args != NULL) {
186
strp = ap_proxy_canonenc(p, r->args, strlen(r->args), enc_parm, 1, r->proxyreq);
188
return HTTP_BAD_REQUEST;
189
parms = apr_pstrcat(p, parms, "?", strp, NULL);
192
strp = ap_proxy_canonenc(p, r->args, strlen(r->args), enc_fpath, 1, r->proxyreq);
194
return HTTP_BAD_REQUEST;
195
path = apr_pstrcat(p, path, "?", strp, NULL);
200
/* now, rebuild URL */
202
if (port != def_port)
203
apr_snprintf(sport, sizeof(sport), ":%d", port);
207
if (ap_strchr_c(host, ':')) { /* if literal IPv6 address */
208
host = apr_pstrcat(p, "[", host, "]", NULL);
210
r->filename = apr_pstrcat(p, "proxy:ftp://", (user != NULL) ? user : "",
211
(password != NULL) ? ":" : "",
212
(password != NULL) ? password : "",
213
(user != NULL) ? "@" : "", host, sport, "/", path,
214
(parms[0] != '\0') ? ";" : "", parms, NULL);
219
/* we chop lines longer than 80 characters */
220
#define MAX_LINE_LEN 80
223
* Reads response lines, returns both the ftp status code and
224
* remembers the response message in the supplied buffer
226
static int ftp_getrc_msg(conn_rec *ftp_ctrl, apr_bucket_brigade *bb, char *msgbuf, int msglen)
229
char response[MAX_LINE_LEN];
231
char *mb = msgbuf, *me = &msgbuf[msglen];
235
if (APR_SUCCESS != (rv = ap_proxy_string_read(ftp_ctrl, bb, response, sizeof(response), &eos))) {
239
ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, NULL,
240
"proxy: <FTP: %s", response);
242
if (!apr_isdigit(response[0]) || !apr_isdigit(response[1]) ||
243
!apr_isdigit(response[2]) || (response[3] != ' ' && response[3] != '-'))
246
status = 100 * response[0] + 10 * response[1] + response[2] - 111 * '0';
248
mb = apr_cpystrn(mb, response + 4, me - mb);
250
if (response[3] == '-') {
251
memcpy(buff, response, 3);
254
if (APR_SUCCESS != (rv = ap_proxy_string_read(ftp_ctrl, bb, response, sizeof(response), &eos))) {
257
mb = apr_cpystrn(mb, response + (' ' == response[0] ? 1 : 4), me - mb);
258
} while (memcmp(response, buff, 4) != 0);
264
/* this is a filter that turns a raw ASCII directory listing into pretty HTML */
266
/* ideally, mod_proxy should simply send the raw directory list up the filter
267
* stack to mod_autoindex, which in theory should turn the raw ascii into
268
* pretty html along with all the bells and whistles it provides...
270
* all in good time...! :)
274
apr_bucket_brigade *in;
275
char buffer[MAX_STRING_LEN];
281
/* fallback regex for ls -s1; ($0..$2) == 3 */
282
#define LS_REG_PATTERN "^ *([0-9]+) +([^ ]+)$"
283
#define LS_REG_MATCH 3
285
static apr_status_t proxy_send_dir_filter(ap_filter_t *f,
286
apr_bucket_brigade *in)
288
request_rec *r = f->r;
289
conn_rec *c = r->connection;
290
apr_pool_t *p = r->pool;
291
apr_bucket_brigade *out = apr_brigade_create(p, c->bucket_alloc);
295
char *dir, *path, *reldir, *site, *str, *type;
297
const char *pwd = apr_table_get(r->notes, "Directory-PWD");
298
const char *readme = apr_table_get(r->notes, "Directory-README");
300
proxy_dir_ctx_t *ctx = f->ctx;
303
f->ctx = ctx = apr_pcalloc(p, sizeof(*ctx));
304
ctx->in = apr_brigade_create(p, c->bucket_alloc);
309
/* combine the stored and the new */
310
APR_BRIGADE_CONCAT(ctx->in, in);
312
if (HEADER == ctx->state) {
314
/* basedir is either "", or "/%2f" for the "squid %2f hack" */
315
const char *basedir = ""; /* By default, path is relative to the $HOME dir */
316
char *wildcard = NULL;
318
/* Save "scheme://site" prefix without password */
319
site = apr_uri_unparse(p, &f->r->parsed_uri, APR_URI_UNP_OMITPASSWORD | APR_URI_UNP_OMITPATHINFO);
320
/* ... and path without query args */
321
path = apr_uri_unparse(p, &f->r->parsed_uri, APR_URI_UNP_OMITSITEPART | APR_URI_UNP_OMITQUERY);
323
/* If path began with /%2f, change the basedir */
324
if (strncasecmp(path, "/%2f", 4) == 0) {
328
/* Strip off a type qualifier. It is ignored for dir listings */
329
if ((type = strstr(path, ";type=")) != NULL)
332
(void)decodeenc(path);
334
while (path[1] == '/') /* collapse multiple leading slashes to one */
337
reldir = strrchr(path, '/');
338
if (reldir != NULL && ftp_check_globbingchars(reldir)) {
339
wildcard = &reldir[1];
340
reldir[0] = '\0'; /* strip off the wildcard suffix */
343
/* Copy path, strip (all except the last) trailing slashes */
344
/* (the trailing slash is needed for the dir component loop below) */
345
path = dir = apr_pstrcat(p, path, "/", NULL);
346
for (n = strlen(path); n > 1 && path[n - 1] == '/' && path[n - 2] == '/'; --n)
349
/* Add a link to the root directory (if %2f hack was used) */
350
str = (basedir[0] != '\0') ? "<a href=\"/%2f/\">%2f</a>/" : "";
352
/* print "ftp://host/" */
353
str = apr_psprintf(p, DOCTYPE_HTML_3_2
354
"<html>\n <head>\n <title>%s%s%s</title>\n"
356
" <body>\n <h2>Directory of "
357
"<a href=\"/\">%s</a>/%s",
358
site, basedir, ap_escape_html(p, path),
361
APR_BRIGADE_INSERT_TAIL(out, apr_bucket_pool_create(str, strlen(str),
362
p, c->bucket_alloc));
364
for (dir = path+1; (dir = strchr(dir, '/')) != NULL; )
367
if ((reldir = strrchr(path+1, '/'))==NULL) {
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));
379
APR_BRIGADE_INSERT_TAIL(out, apr_bucket_pool_create(str,
383
if (wildcard != NULL) {
384
APR_BRIGADE_INSERT_TAIL(out, apr_bucket_pool_create(wildcard,
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>");
395
str = apr_psprintf(p, "</h2>\n\n(%s)\n\n <hr />\n\n<pre>",
396
ap_escape_html(p, pwd));
398
APR_BRIGADE_INSERT_TAIL(out, apr_bucket_pool_create(str, strlen(str),
399
p, c->bucket_alloc));
403
str = apr_psprintf(p, "%s\n</pre>\n\n<hr />\n\n<pre>\n",
404
ap_escape_html(p, readme));
406
APR_BRIGADE_INSERT_TAIL(out, apr_bucket_pool_create(str,
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))) {
416
apr_brigade_cleanup(out);
421
/* loop through each line of directory */
422
while (BODY == ctx->state) {
427
ap_regex_t *re = NULL;
428
ap_regmatch_t re_result[LS_REG_MATCH];
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);
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;
441
e = APR_BRIGADE_FIRST(ctx->in);
442
if (APR_BUCKET_IS_EOS(e)) {
446
if (APR_SUCCESS != (rv = apr_bucket_read(e, (const char **)&response, &len, APR_BLOCK_READ))) {
449
pos = memchr(response, APR_ASCII_LF, len);
451
if ((response + len) != (pos + 1)) {
452
len = pos - response + 1;
453
apr_bucket_split(e, pos - response + 1);
457
max = sizeof(ctx->buffer) - strlen(ctx->buffer) - 1;
462
/* len+1 to leave space for the trailing nil char */
463
apr_cpystrn(ctx->buffer+strlen(ctx->buffer), response, len+1);
465
APR_BUCKET_REMOVE(e);
466
apr_bucket_destroy(e);
469
/* EOS? jump to footer */
475
/* not complete? leave and try get some more */
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';
489
if (ctx->buffer[0] == 'l' && (filename = strstr(ctx->buffer, " -> ")) != NULL) {
490
char *link_ptr = 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));
505
/* a directory/file? */
506
else if (ctx->buffer[0] == 'd' || ctx->buffer[0] == '-' || ctx->buffer[0] == 'l' || apr_isdigit(ctx->buffer[0])) {
508
char *searchptr = NULL;
510
if (apr_isdigit(ctx->buffer[0])) { /* handle DOS dir */
511
searchptr = strchr(ctx->buffer, '<');
512
if (searchptr != NULL)
514
searchptr = strchr(ctx->buffer, '>');
515
if (searchptr != NULL)
519
filename = strrchr(ctx->buffer, ' ');
520
*(filename++) = '\0';
522
/* handle filenames with spaces in 'em */
523
if (!strcmp(filename, ".") || !strcmp(filename, "..") || firstfile) {
525
searchidx = filename - ctx->buffer;
527
else if (searchidx != 0 && ctx->buffer[searchidx] != 0) {
529
ctx->buffer[searchidx - 1] = '\0';
530
filename = &ctx->buffer[searchidx];
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));
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));
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)) {
550
filename = apr_pstrndup(p, &ctx->buffer[re_result[2].rm_so], re_result[2].rm_eo - re_result[2].rm_so);
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);
557
strcat(ctx->buffer, "\n"); /* re-append the newline */
558
str = ap_escape_html(p, ctx->buffer);
561
/* erase buffer for next time around */
564
APR_BRIGADE_INSERT_TAIL(out, apr_bucket_pool_create(str, strlen(str), p,
566
APR_BRIGADE_INSERT_TAIL(out, apr_bucket_flush_create(c->bucket_alloc));
567
if (APR_SUCCESS != (rv = ap_pass_brigade(f->next, out))) {
570
apr_brigade_cleanup(out);
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,
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))) {
583
apr_brigade_destroy(out);
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)
595
proxy_ftp_command(const char *cmd, request_rec *r, conn_rec *ftp_ctrl,
596
apr_bucket_brigade *bb, char **pmessage)
600
char message[HUGE_STRING_LEN];
602
/* If cmd == NULL, we retrieve the next ftp response line */
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);
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)
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);
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)
626
ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, r->server,
627
"proxy:<FTP: %3.3u %s", rc, message);
629
if (pmessage != NULL)
630
*pmessage = apr_pstrdup(r->pool, message);
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)
639
char old_type[2] = { 'A', '\0' }; /* After logon, mode is ASCII */
643
/* set desired type */
644
old_type[0] = xfer_type;
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");
659
else if (rc != 200 && rc != 504) {
660
ret = ap_proxyerror(r, HTTP_BAD_GATEWAY,
661
"Unable to set transfer type");
663
/* Allow not implemented */
665
/* ignore it silently */;
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)
675
char *ftpmessage = NULL;
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)) {
688
ap_proxyerror(r, HTTP_BAD_GATEWAY,
689
"Failed to read PWD on ftp server");
693
const char *dirp = ftpmessage;
694
cwd = ap_getword_conf(r->pool, &dirp);
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-)
708
static int ftp_unauthorized(request_rec *r, int log_it)
710
r->proxyreq = PROXYREQ_NONE;
712
* Log failed requests if they supplied a password (log username/password
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));
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),
727
return HTTP_UNAUTHORIZED;
731
apr_status_t proxy_ftp_cleanup(request_rec *r, proxy_conn_rec *backend)
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);
742
int ftp_proxyerror(request_rec *r, proxy_conn_rec *conn, int statuscode, const char *message)
744
proxy_ftp_cleanup(r, conn);
745
return ap_proxyerror(r, statuscode, message);
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>]
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)
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;
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;
774
/* char *account = NULL; how to supply an account in a URL? */
775
const char *password = NULL;
779
char xfer_type = 'A'; /* after ftp login, the default is ASCII */
781
#if defined(USE_MDTM) && (defined(HAVE_TIMEGM) || defined(HAVE_GMTOFF))
782
apr_time_t mtime = 0L;
785
/* stuff for PASV mode */
786
int connect = 0, use_port = 0;
787
char dates[APR_RFC822_DATE_LEN];
789
apr_pool_t *address_pool;
791
/* is this for us? */
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 */
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 */
802
ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, r->server,
803
"proxy: FTP: serving URL %s", url);
807
* I: Who Do I Connect To? -----------------------
809
* Break up the URL to determine the host to connect to
812
/* we only support GET and HEAD */
813
if (r->method_number != M_GET)
814
return HTTP_NOT_IMPLEMENTED;
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));
822
connectname = uri.hostname;
823
connectport = uri.port;
824
path = apr_pstrdup(p, uri.path);
827
connectname = r->parsed_uri.hostname;
828
connectport = r->parsed_uri.port;
829
path = apr_pstrdup(p, r->parsed_uri.path);
831
if (connectport == 0) {
832
connectport = apr_uri_port_of_scheme("ftp");
834
path = (path != NULL && path[0] != '\0') ? &path[1] : "";
836
type_suffix = strchr(path, ';');
837
if (type_suffix != NULL)
838
*(type_suffix++) = '\0';
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
845
if ( ! (dirlisting = (apr_tolower(type_suffix[5]) == 'd')))
846
xfer_type = apr_toupper(type_suffix[5]);
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));
855
/* make binary transfers the default */
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.
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] != ':') {
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.
876
user = ap_getword_nulls(r->connection->pool, &password, ':');
877
r->ap_auth_type = "Basic";
878
r->user = r->parsed_uri.user = user;
880
else if ((user = r->parsed_uri.user) != NULL) {
881
user = apr_pstrdup(p, user);
883
if ((password = r->parsed_uri.password) != NULL) {
884
char *tmp = apr_pstrdup(p, password);
891
password = "apache-proxy@";
894
ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, r->server,
895
"proxy: FTP: connecting %s to %s:%d", url, connectname, connectport);
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,
902
return HTTP_INTERNAL_SERVER_ERROR;
905
connect_addr = worker->cp->addr;
906
address_pool = worker->cp->pool;
909
address_pool = r->pool;
911
/* do a DNS lookup for the destination host */
913
err = apr_sockaddr_info_get(&(connect_addr),
914
connectname, APR_UNSPEC,
917
if (worker->is_address_reusable && !worker->cp->addr) {
918
worker->cp->addr = connect_addr;
919
PROXY_THREAD_UNLOCK(worker);
922
* get all the possible IP addresses for the destname and loop through
923
* them until we get a successful connection
925
if (APR_SUCCESS != err) {
926
return ap_proxyerror(r, HTTP_BAD_GATEWAY, apr_pstrcat(p,
927
"DNS lookup failure for: ",
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");
937
/* create space for state information */
938
backend = (proxy_conn_rec *) ap_get_module_config(c->conn_config, &proxy_ftp_module);
940
status = ap_proxy_acquire_connection("FTP", &backend, worker, r->server);
943
backend->close_on_recycle = 1;
944
ap_proxy_release_connection("FTP", backend, r->server);
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);
955
* II: Make the Connection -----------------------
957
* We have determined who to connect to. Now make the connection.
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;
969
if (!backend->connection) {
970
status = ap_proxy_connection_create("FTP", backend, c, r->server);
972
proxy_ftp_cleanup(r, backend);
978
origin = backend->connection;
979
sock = backend->sock;
981
ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, r->server,
982
"proxy: FTP: control connection complete");
986
* III: Send Control Request -------------------------
988
* Log into the ftp server, send the username & password, change to the
989
* correct directory...
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");
1003
* RFC2616 states: 14.37 Retry-After
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 )
1012
char *secs_str = ftpmessage;
1015
/* Look for a number, preceded by whitespace */
1017
if ((secs_str==ftpmessage || apr_isspace(secs_str[-1])) &&
1018
apr_isdigit(secs_str[0]))
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)));
1025
return ftp_proxyerror(r, backend, HTTP_SERVICE_UNAVAILABLE, ftpmessage);
1028
return ftp_proxyerror(r, backend, HTTP_BAD_GATEWAY, ftpmessage);
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");
1047
proxy_ftp_cleanup(r, backend);
1048
return ftp_unauthorized(r, 1); /* log it: user name guessing
1051
if (rc != 230 && rc != 331) {
1052
return ftp_proxyerror(r, backend, HTTP_BAD_GATEWAY, ftpmessage);
1055
if (rc == 331) { /* send password */
1056
if (password == NULL) {
1057
proxy_ftp_cleanup(r, backend);
1058
return ftp_unauthorized(r, 0);
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");
1076
return ftp_proxyerror(r, backend, HTTP_UNAUTHORIZED,
1077
apr_pstrcat(p, "Need account for login: ", ftpmessage, NULL));
1079
/* @@@ questionable -- we might as well return a 403 Forbidden here */
1081
proxy_ftp_cleanup(r, backend);
1082
return ftp_unauthorized(r, 1); /* log it: passwd guessing
1085
if (rc != 230 && rc != 202) {
1086
return ftp_proxyerror(r, backend, HTTP_BAD_GATEWAY, ftpmessage);
1089
apr_table_set(r->notes, "Directory-README", ftpmessage);
1092
/* Special handling for leading "%2f": this enforces a "cwd /"
1093
* out of the $HOME directory which was the starting point after login
1095
if (strncasecmp(path, "%2f", 3) == 0) {
1097
while (*path == '/') /* skip leading '/' (after root %2f) */
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");
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
1111
strp = strchr(path, '/');
1116
len = decodeenc(path); /* Note! This decodes a %2f -> "/" */
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");
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
1128
rc = proxy_ftp_command(apr_pstrcat(p, "CWD ",
1129
ftp_escape_globbingchars(p, path), CRLF, NULL),
1130
r, origin, bb, &ftpmessage);
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");
1145
return ftp_proxyerror(r, backend, HTTP_NOT_FOUND, ftpmessage);
1148
return ftp_proxyerror(r, backend, HTTP_BAD_GATEWAY, ftpmessage);
1155
* IV: Make Data Connection? -------------------------
1157
* Try EPSV, if that fails... try PASV, if that fails... try PORT.
1159
/* this temporarily switches off EPSV/PASV */
1162
/* set up data connection - EPSV */
1164
apr_sockaddr_t *data_addr;
1166
apr_port_t data_port;
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|)
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");
1187
if (rc != 229 && rc != 500 && rc != 501 && rc != 502) {
1188
return ftp_proxyerror(r, backend, HTTP_BAD_GATEWAY, ftpmessage);
1190
else if (rc == 229) {
1195
pstr = apr_strtok(pstr, " ", &tok_cntx); /* separate result code */
1197
if (*(pstr + strlen(pstr) + 1) == '=') {
1198
pstr += strlen(pstr) + 2;
1201
pstr = apr_strtok(NULL, "(", &tok_cntx); /* separate address &
1204
pstr = apr_strtok(NULL, ")", &tok_cntx);
1209
apr_sockaddr_t *epsv_addr;
1210
data_port = atoi(pstr + 3);
1212
ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, r->server,
1213
"proxy: FTP: EPSV contacting remote host on port %d",
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;
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");
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));
1248
/* and try the regular way */
1249
apr_socket_close(data_sock);
1254
/* set up data connection - PASV */
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");
1269
if (rc != 227 && rc != 502) {
1270
return ftp_proxyerror(r, backend, HTTP_BAD_GATEWAY, ftpmessage);
1272
else if (rc == 227) {
1273
unsigned int h0, h1, h2, h3, p0, p1;
1277
/* FIXME: Check PASV against RFC1123 */
1280
pstr = apr_strtok(pstr, " ", &tok_cntx); /* separate result code */
1282
if (*(pstr + strlen(pstr) + 1) == '=') {
1283
pstr += strlen(pstr) + 2;
1286
pstr = apr_strtok(NULL, "(", &tok_cntx); /* separate address &
1289
pstr = apr_strtok(NULL, ")", &tok_cntx);
1293
/* FIXME: Only supports IPV4 - fix in RFC2428 */
1295
if (pstr != NULL && (sscanf(pstr,
1296
"%d,%d,%d,%d,%d,%d", &h3, &h2, &h1, &h0, &p1, &p0) == 6)) {
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);
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;
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");
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));
1334
/* and try the regular way */
1335
apr_socket_close(data_sock);
1341
/* set up data connection - PORT */
1343
apr_sockaddr_t *local_addr;
1345
apr_port_t local_port;
1346
unsigned int h0, h1, h2, h3, p0, p1;
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;
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);
1358
if ((rv = apr_socket_opt_set(local_sock, APR_SO_REUSEADDR, one))
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 */
1368
apr_sockaddr_info_get(&local_addr, local_ip, APR_UNSPEC, local_port, 0, r->pool);
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;
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;
1385
/* FIXME: Sent PORT here */
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);
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");
1406
return ftp_proxyerror(r, backend, HTTP_BAD_GATEWAY, buffer);
1409
/* signal that we must use the EPRT/PORT loop */
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|
1419
return ftp_proxyerror(r, backend, HTTP_NOT_IMPLEMENTED,
1420
"Connect to IPV6 ftp server using EPRT not supported. Enable EPSV.");
1426
* V: Set The Headers -------------------
1428
* Get the size of the request, set up the environment for HTTP.
1431
/* set request; "path" holds last path component */
1432
len = decodeenc(path);
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");
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
1442
if (len == 0 || ftp_check_globbingchars(path)) {
1446
/* (from FreeBSD ftpd):
1447
* SIZE is not in RFC959, but Postel has blessed it and
1448
* it will be in the updated RFC.
1450
* Return size of file in a format suitable for
1451
* using with RESTART (we just count bytes).
1453
/* from draft-ietf-ftpext-mlst-14.txt:
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.
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");
1469
else if (rc == 213) {/* Size command ok */
1471
for (j = 0; apr_isdigit(ftpmessage[j]); j++)
1473
ftpmessage[j] = '\0';
1474
if (ftpmessage[0] != '\0')
1475
size = ftpmessage; /* already pstrdup'ed: no copy necessary */
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");
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");
1497
return ftp_proxyerror(r, backend, HTTP_NOT_FOUND, ftpmessage);
1500
return ftp_proxyerror(r, backend, HTTP_BAD_GATEWAY, ftpmessage);
1507
cwd = ftp_get_PWD(r, origin, bb);
1509
apr_table_set(r->notes, "Directory-PWD", cwd);
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.
1519
/* Note that we do not escape the path here, to allow for
1520
* queries like: ftp://user@host/apache/src/server/http_*.c
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);
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)
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). */
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)) {
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
1572
mtime = mktime(&tms);
1573
mtime += tms.tm_gmtoff;
1574
mtime *= APR_USEC_PER_SEC;
1580
#endif /* USE_MDTM */
1581
/* FIXME: Handle range requests - send REST */
1582
buf = apr_pstrcat(p, "RETR ", ftp_escape_globbingchars(p, path), CRLF, NULL);
1584
rc = proxy_ftp_command(buf, r, origin, bb, &ftpmessage);
1585
/* rc is an intermediate response for the LIST or RETR commands */
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,
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");
1611
ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, r->server,
1612
"proxy: FTP: RETR failed, trying LIST instead");
1614
/* Directory Listings should always be fetched in ASCII mode */
1616
ftp_set_TYPE('A', r, origin, bb, NULL);
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");
1634
return ftp_proxyerror(r, backend, HTTP_NOT_FOUND, ftpmessage);
1637
return ftp_proxyerror(r, backend, HTTP_BAD_GATEWAY, ftpmessage);
1640
/* Update current directory after CWD */
1641
cwd = ftp_get_PWD(r, origin, bb);
1643
apr_table_set(r->notes, "Directory-PWD", cwd);
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);
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");
1656
if (rc != 125 && rc != 150 && rc != 226 && rc != 250) {
1657
return ftp_proxyerror(r, backend, HTTP_BAD_GATEWAY, ftpmessage);
1660
r->status = HTTP_OK;
1661
r->status_line = "200 OK";
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());
1667
/* set content-type */
1669
ap_set_content_type(r, "text/html");
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);
1677
ap_set_content_type(r, ap_default_type(r));
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);
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);
1690
#if defined(USE_MDTM) && (defined(HAVE_TIMEGM) || defined(HAVE_GMTOFF))
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);
1698
#endif /* USE_MDTM */
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)
1704
if (dirlisting && r->content_encoding != NULL)
1705
r->content_encoding = NULL;
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);
1714
/* wait for connection */
1717
rv = apr_socket_accept(&data_sock, local_sock, r->pool);
1718
if (rv == APR_EINTR) {
1721
else if (rv == APR_SUCCESS) {
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;
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);
1738
* the peer reset the connection already; ap_run_create_connection() closed
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;
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)",
1754
proxy_ftp_cleanup(r, backend);
1759
* VI: Receive the Response ------------------------
1761
* Get response from the remote ftp socket, and pass it up the filter chain.
1768
/* insert directory filter */
1769
ap_add_output_filter("PROXY_SEND_DIR", NULL, r, r->connection);
1773
if (!r->header_only) {
1777
ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, r->server,
1778
"proxy: FTP: start body send");
1780
/* read the body, pass it to the output filters */
1781
while (ap_get_brigade(data->input_filters,
1785
conf->io_buffer_size) == APR_SUCCESS) {
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);
1796
if (APR_BRIGADE_EMPTY(bb)) {
1797
apr_brigade_cleanup(bb);
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
1808
ap_flush_conn(data);
1809
apr_socket_close(data_sock);
1811
ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, r->server,
1812
"proxy: FTP: data connection closed");
1813
/* signal that we must leave */
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);
1823
/* try send what we read */
1824
if (ap_pass_brigade(r->output_filters, bb) != APR_SUCCESS
1826
/* Ack! Phbtt! Die! User aborted! */
1830
/* make sure we always clean up after ourselves */
1831
apr_brigade_cleanup(bb);
1833
/* if we are done, leave */
1834
if (TRUE == finish) {
1838
ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, r->server,
1839
"proxy: FTP: end body send");
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");
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);
1854
* VII: Clean Up -------------
1856
* If there are no KeepAlives, or if the connection has been signalled to
1857
* close, close the socket and clean up
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);
1869
apr_brigade_destroy(bb);
1873
static void ap_proxy_ftp_register_hook(apr_pool_t *p)
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);
1879
ap_register_output_filter("PROXY_SEND_DIR", proxy_send_dir_filter,
1880
NULL, AP_FTYPE_RESOURCE);
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 */