mod_proxy_ftp.c revision 23a31b10f869a72c9197b5f153f4f3e1a4c68f28
/* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/* FTP routines for Apache proxy */
#include "mod_proxy.h"
#if APR_HAVE_TIME_H
#include <time.h>
#endif
#include "apr_version.h"
#if (APR_MAJOR_VERSION < 1)
#endif
#define AUTODETECT_PWD
/* Automatic timestamping (Last-Modified header) based on MDTM is used if:
* 1) the FTP server supports the MDTM command and
* 2) HAVE_TIMEGM (preferred) or HAVE_GMTOFF is available at compile time
*/
#define USE_MDTM
typedef struct {
int ftp_list_on_wildcard;
int ftp_escape_wildcards;
const char *ftp_directory_charset;
{
/* Put these in the dir config so they work inside <Location> */
return (void *) new;
}
{
/* Put these in the dir config so they work inside <Location> */
1 :
1 :
return new;
}
int flag)
{
return NULL;
}
int flag)
{
return NULL;
}
const char *arg)
{
return NULL;
}
/*
* Decodes a '%' escaped string, and returns the number of characters
*/
static int decodeenc(char *x)
{
int i, j, ch;
if (x[0] == '\0')
return 0; /* special case for no characters */
for (i = 0, j = 0; x[i] != '\0'; i++, j++) {
/* decode it if not already done */
ch = x[i];
i += 2;
}
x[j] = ch;
}
x[j] = '\0';
return j;
}
/*
* Escape the globbing characters in a path used as argument to
* the FTP commands (SIZE, CWD, RETR, MDTM, ...).
* ftpd assumes '\\' as a quoting character to escape special characters.
* Just returns the original string if ProxyFtpEscapeWildcards has been
* configured "off".
* Returns: escaped string
*/
#define FTP_GLOBBING_CHARS "*?[{~"
static const char *ftp_escape_globbingchars(apr_pool_t *p, const char *path, proxy_ftp_dir_conf *dconf)
{
char *ret;
char *d;
if (!dconf->ftp_escape_wildcards) {
return path;
}
*d++ = '\\';
*d++ = *path;
}
*d = '\0';
return ret;
}
/*
* Check for globbing characters in a path used as argument to
* the FTP commands (SIZE, CWD, RETR, MDTM, ...).
* ftpd assumes '\\' as a quoting character to escape special characters.
* Returns: 0 (no globbing chars, or all globbing chars escaped), 1 (globbing chars)
*/
static int ftp_check_globbingchars(const char *path)
{
if (*path == '\\')
++path;
return TRUE;
}
return FALSE;
}
/*
* checks an encoded ftp string for bad characters, namely, CR, LF or
* non-ascii character
*/
static int ftp_check_string(const char *x)
{
int i, ch = 0;
char buf[1];
#endif
for (i = 0; x[i] != '\0'; i++) {
ch = x[i];
i += 2;
}
#if !APR_CHARSET_EBCDIC
#else /* APR_CHARSET_EBCDIC */
return 0;
if (buf[0] & 0x80)
#endif /* APR_CHARSET_EBCDIC */
return 0;
}
return 1;
}
/*
* Canonicalise ftp URLs.
*/
{
apr_pool_t *p = r->pool;
const char *err;
/* */
url += 4;
}
else {
return DECLINED;
}
"proxy: FTP: canonicalising URL %s", url);
if (err)
return HTTP_BAD_REQUEST;
return HTTP_BAD_REQUEST;
return HTTP_BAD_REQUEST;
/* now parse path/parameters args, according to rfc1738 */
/*
* N.B. if this isn't a true proxy request, then the URL path (but not
* query args) has already been decoded. This gives rise to the problem
* of a ; being decoded into the path.
*/
*(strp++) = '\0';
r->proxyreq);
return HTTP_BAD_REQUEST;
}
else
parms = "";
return HTTP_BAD_REQUEST;
if (!ftp_check_string(path))
return HTTP_BAD_REQUEST;
return HTTP_BAD_REQUEST;
}
else {
return HTTP_BAD_REQUEST;
}
}
/* now, rebuild URL */
else
sport[0] = '\0';
}
return OK;
}
/* we chop lines longer than 80 characters */
#define MAX_LINE_LEN 80
/*
* Reads response lines, returns both the ftp status code and
* remembers the response message in the supplied buffer
*/
{
int status;
char response[MAX_LINE_LEN];
char buff[5];
int eos;
return -1;
}
/*
ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, NULL,
"proxy: <FTP: %s", response);
*/
status = 0;
else
do {
return -1;
}
}
return status;
}
/* this is a filter that turns a raw ASCII directory listing into pretty HTML */
/* ideally, mod_proxy should simply send the raw directory list up the filter
* stack to mod_autoindex, which in theory should turn the raw ascii into
* pretty html along with all the bells and whistles it provides...
*
* all in good time...! :)
*/
typedef struct {
char buffer[MAX_STRING_LEN];
enum {
} state;
/* fallback regex for ls -s1; ($0..$2) == 3 */
#define LS_REG_PATTERN "^ *([0-9]+) +([^ ]+)$"
#define LS_REG_MATCH 3
{
request_rec *r = f->r;
conn_rec *c = r->connection;
apr_pool_t *p = r->pool;
register int n;
if (!ctx) {
}
/* combine the stored and the new */
/* basedir is either "", or "/%2f" for the "squid %2f hack" */
const char *escpath;
/*
* In the reverse proxy case we need to construct our site string
* via ap_construct_url. For non anonymous sites apr_uri_unparse would
* only supply us with 'username@' which leads to the construction of
* an invalid base href later on. Losing the username part of the URL
* is no problem in the reverse proxy case as the browser sents the
* credentials anyway once entered.
*/
if (r->proxyreq == PROXYREQ_REVERSE) {
}
else {
/* Save "scheme://site" prefix without password */
}
/* ... and path without query args */
/* If path began with /%2f, change the basedir */
basedir = "/%2f";
}
/* Strip off a type qualifier. It is ignored for dir listings */
*type++ = '\0';
++path;
}
/* Copy path, strip (all except the last) trailing slashes */
/* (the trailing slash is needed for the dir component loop below) */
/* Add a link to the root directory (if %2f hack was used) */
/* print "ftp://host/" */
"<html>\n <head>\n <title>%s%s%s</title>\n"
"<base href=\"%s%s%s\">\n"
" </head>\n"
" <body>\n <h2>Directory of "
"<a href=\"/\">%s</a>/%s",
p, c->bucket_alloc));
{
*dir = '\0';
}
else
++reldir;
/* print "path/" component */
ap_escape_uri(p, path),
ap_escape_html(p, reldir));
*dir = '/';
while (*dir == '/')
++dir;
c->bucket_alloc));
}
c->bucket_alloc));
}
/* If the caller has determined the current directory, and it differs */
/* from what the client requested, then show the real name */
}
else {
ap_escape_html(p, pwd));
}
p, c->bucket_alloc));
/* print README */
if (readme) {
ap_escape_html(p, readme));
c->bucket_alloc));
}
/* make sure page intro gets sent out */
return rv;
}
}
/* loop through each line of directory */
char *filename;
int found = 0;
int eos = 0;
/* Compile the output format of "ls -s1" as a fallback for non-unix ftp listings */
/* get a complete line */
/* if the buffer overruns - throw data away */
apr_bucket *e;
if (APR_BUCKET_IS_EOS(e)) {
eos = 1;
break;
}
return rv;
}
}
found = 1;
}
}
/* len+1 to leave space for the trailing nil char */
}
/* EOS? jump to footer */
if (eos) {
break;
}
/* not complete? leave and try get some more */
if (!found) {
return APR_SUCCESS;
}
{
}
/* a symlink? */
do {
filename--;
*(filename++) = '\0';
*(link_ptr++) = '\0';
ap_escape_uri(p, filename),
ap_escape_html(p, filename),
ap_escape_html(p, link_ptr));
}
else if (ctx->buffer[0] == 'd' || ctx->buffer[0] == '-' || ctx->buffer[0] == 'l' || apr_isdigit(ctx->buffer[0])) {
int searchidx = 0;
int firstfile = 1;
*searchptr = '[';
*searchptr = ']';
}
/* Line is broken. Ignore it. */
/* erase buffer for next time around */
continue; /* while state is BODY */
}
*(filename++) = '\0';
/* handle filenames with spaces in 'em */
firstfile = 0;
}
*(--filename) = ' ';
}
/* Append a slash to the HREF link for directories */
ap_escape_uri(p, filename),
ap_escape_html(p, filename));
}
else {
ap_escape_uri(p, filename),
ap_escape_html(p, filename));
}
}
/* Try a fallback for listings in the format of "ls -s1" */
filename = apr_pstrndup(p, &ctx->buffer[re_result[2].rm_so], re_result[2].rm_eo - re_result[2].rm_so);
}
else {
}
/* erase buffer for next time around */
c->bucket_alloc));
return rv;
}
}
c->bucket_alloc));
return rv;
}
}
return APR_SUCCESS;
}
/* Parse EPSV reply and return port, or zero on error. */
{
const char *p;
char *ep;
long port;
/* Reply syntax per RFC 2428: "229 blah blah (|||port|)" where '|'
* can be any character in ASCII from 33-126, obscurely. Verify
* the syntax. */
|| p[4] == p[1]) {
return 0;
}
errno = 0;
return 0;
}
return (apr_port_t)port;
}
/*
* Generic "send FTP command to server" routine, using the control socket.
* Returns the FTP returncode (3 digit code)
* Allows for tracing the FTP protocol (in LogLevel debug)
*/
static int
{
char *crlf;
int rc;
char message[HUGE_STRING_LEN];
/* If cmd == NULL, we retrieve the next ftp response line */
conn_rec *c = r->connection;
/* strip off the CRLF for logging */
*crlf = '\0';
"proxy:>FTP: %s", message);
}
*crlf = '\0';
return rc;
}
/* Set ftp server to TYPE {A,I,E} before transfer of a directory or file */
{
int rc;
/* set desired type */
/* responses: 200, 421, 500, 501, 504, 530 */
/* 200 Command okay. */
/* 421 Service not available, closing control connection. */
/* 500 Syntax error, command unrecognized. */
/* 501 Syntax error in parameters or arguments. */
/* 504 Command not implemented for that parameter. */
/* 530 Not logged in. */
"Error reading from remote server");
}
"Unable to set transfer type");
}
/* Allow not implemented */
else if (rc == 504) {
/* ignore it silently */
}
return ret;
}
/* Return the current directory which we have selected on the FTP server, or NULL */
{
char *ftpmessage = NULL;
/* responses: 257, 500, 501, 502, 421, 550 */
/* 257 "<directory-name>" <commentary> */
/* 421 Service not available, closing control connection. */
/* 500 Syntax error, command unrecognized. */
/* 501 Syntax error in parameters or arguments. */
/* 502 Command not implemented. */
/* 550 Requested action not taken. */
case -1:
case 421:
case 550:
"Failed to read PWD on ftp server");
break;
case 257: {
const char *dirp = ftpmessage;
}
}
return cwd;
}
/* Common routine for failed authorization (i.e., missing or wrong password)
* to an ftp service. This causes most browsers to retry the request
* with username and password (which was presumably queried from the user)
* supplied in the Authorization: header.
* Note that we "invent" a realm name which consists of the
* ftp://user@host part of the reqest (sans password -if supplied but invalid-)
*/
{
r->proxyreq = PROXYREQ_NONE;
/*
* guessing attempts)
*/
if (log_it)
"proxy: missing or failed auth to %s",
apr_uri_unparse(r->pool,
&r->parsed_uri, APR_URI_UNP_OMITPATHINFO));
"\"", NULL));
return HTTP_UNAUTHORIZED;
}
static
{
return OK;
}
static
{
proxy_ftp_cleanup(r, conn);
}
/*
* Handles direct access of ftp:// URLs
* Original (Non-PASV) version from
* Troy Morrison <spiffnet@zoom.com>
* PASV added by Chuck
* Filters by [Graham Leggett <minfrin@sharp.fm>]
*/
{
apr_pool_t *p = r->pool;
conn_rec *c = r->connection;
char *buf, *connectname;
char buffer[MAX_STRING_LEN];
char *ftpmessage = NULL;
/* char *account = NULL; how to supply an account in a URL? */
int one = 1;
int dirlisting = 0;
apr_time_t mtime = 0L;
#endif
/* stuff for PASV mode */
char dates[APR_RFC822_DATE_LEN];
int status;
/* is this for us? */
if (proxyhost) {
return DECLINED; /* proxy connections are via HTTP */
}
"proxy: FTP: declining URL %s - not ftp:", url);
return DECLINED; /* only interested in FTP */
}
"proxy: FTP: serving URL %s", url);
/*
* I: Who Do I Connect To? -----------------------
*
* Break up the URL to determine the host to connect to
*/
/* we only support GET and HEAD */
if (r->method_number != M_GET)
return HTTP_NOT_IMPLEMENTED;
/* We break the URL into host, port, path-search */
return ap_proxyerror(r, HTTP_BAD_REQUEST,
}
}
else {
}
if (connectport == 0) {
}
if (type_suffix != NULL)
*(type_suffix++) = '\0';
/* "type=d" forces a dir listing.
* The other types (i|a|e) are directly used for the ftp TYPE command
*/
/* Check valid types, rather than ignoring invalid types silently: */
"ftp proxy supports only types 'a', 'i', or 'e': \"",
}
else {
/* make binary transfers the default */
xfer_type = 'I';
}
/*
* The "Authorization:" header must be checked first. We allow the user
* to "override" the URL-coded user [ & password ] in the Browsers'
* User&Password Dialog. NOTE that this is only marginally more secure
* than having the password travel in plain as part of the URL, because
* Basic Auth simply uuencodes the plain text password. But chances are
* still smaller that the URL is logged regularly.
*/
/* Check the decoded string for special characters. */
if (!ftp_check_string(password)) {
return ap_proxyerror(r, HTTP_BAD_REQUEST,
"user credentials contained invalid character");
}
/*
* Note that this allocation has to be made from r->connection->pool
* because it has the lifetime of the connection. The other
* allocations are temporary and can be tossed away any time.
*/
r->ap_auth_type = "Basic";
}
}
}
else {
user = "anonymous";
password = "apache-proxy@";
}
if (worker->s->is_address_reusable) {
"proxy: FTP: lock");
return HTTP_INTERNAL_SERVER_ERROR;
}
}
}
else
address_pool = r->pool;
/* do a DNS lookup for the destination host */
if (!connect_addr)
connectport, 0,
"proxy: FTP: unlock");
}
}
/*
* get all the possible IP addresses for the destname and loop through
* them until we get a successful connection
*/
if (APR_SUCCESS != err) {
"DNS lookup failure for: ",
connectname, NULL));
}
/* check if ProxyBlock directive on this host */
return ap_proxyerror(r, HTTP_FORBIDDEN,
"Connect to remote machine blocked");
}
/* create space for state information */
if (!backend) {
if (backend) {
}
return status;
}
/* TODO: see if ftp could use determine_connection */
}
/*
* II: Make the Connection -----------------------
*
* We have determined who to connect to. Now make the connection.
*/
"proxy: FTP: an error occurred creating a new connection to %pI (%s)",
proxy_ftp_cleanup(r, backend);
return HTTP_SERVICE_UNAVAILABLE;
}
if (!backend->connection) {
proxy_ftp_cleanup(r, backend);
return status;
}
}
/* Use old naming */
"proxy: FTP: control connection complete");
/*
* III: Send Control Request -------------------------
*
* Log into the ftp server, send the username & password, change to the
* correct directory...
*/
/* possible results: */
/* 120 Service ready in nnn minutes. */
/* 220 Service ready for new user. */
/* 421 Service not available, closing control connection. */
}
if (rc == 120) {
/*
* RFC2616 states: 14.37 Retry-After
*
* The Retry-After response-header field can be used with a 503 (Service
* Unavailable) response to indicate how long the service is expected
* to be unavailable to the requesting client. [...] The value of
* this field can be either an HTTP-date or an integer number of
* seconds (in decimal) after the time of the response. Retry-After
* = "Retry-After" ":" ( HTTP-date | delta-seconds )
*/
char *secs_str = ftpmessage;
/* Look for a number, preceded by whitespace */
while (*secs_str)
apr_isdigit(secs_str[0]))
break;
if (*secs_str != '\0') {
}
}
if (rc != 220) {
}
/* possible results; 230, 331, 332, 421, 500, 501, 530 */
/* states: 1 - error, 2 - success; 3 - send password, 4,5 fail */
/* 230 User logged in, proceed. */
/* 331 User name okay, need password. */
/* 332 Need account for login. */
/* 421 Service not available, closing control connection. */
/* 500 Syntax error, command unrecognized. */
/* (This may include errors such as command line too long.) */
/* 501 Syntax error in parameters or arguments. */
/* 530 Not logged in. */
}
if (rc == 530) {
proxy_ftp_cleanup(r, backend);
* attempt? */
}
}
proxy_ftp_cleanup(r, backend);
return ftp_unauthorized(r, 0);
}
/* possible results 202, 230, 332, 421, 500, 501, 503, 530 */
/* 230 User logged in, proceed. */
/* 332 Need account for login. */
/* 421 Service not available, closing control connection. */
/* 500 Syntax error, command unrecognized. */
/* 501 Syntax error in parameters or arguments. */
/* 503 Bad sequence of commands. */
/* 530 Not logged in. */
"Error reading from remote server");
}
if (rc == 332) {
}
/* @@@ questionable -- we might as well return a 403 Forbidden here */
if (rc == 530) {
proxy_ftp_cleanup(r, backend);
* attempt? */
}
}
}
/* Special handling for leading "%2f": this enforces a "cwd /"
* out of the $HOME directory which was the starting point after login
*/
path += 3;
++path;
"Error reading from remote server");
}
/*
* set the directory (walk directory component by component): this is
* what we must do if we don't know the OS type of the remote machine
*/
for (;;) {
break;
*strp = '\0';
"Use of /%2f is only allowed at the base directory");
}
/* NOTE: FTP servers do globbing on the path.
* So we need to escape the URI metacharacters.
* We use a special glob-escaping routine to escape globbing chars.
* We could also have extended gen_test_char.c with a special T_ESCAPE_FTP_PATH
*/
*strp = '/';
/* responses: 250, 421, 500, 501, 502, 530, 550 */
/* 250 Requested file action okay, completed. */
/* 421 Service not available, closing control connection. */
/* 500 Syntax error, command unrecognized. */
/* 501 Syntax error in parameters or arguments. */
/* 502 Command not implemented. */
/* 530 Not logged in. */
/* 550 Requested action not taken. */
"Error reading from remote server");
}
if (rc == 550) {
}
if (rc != 250) {
}
}
/*
* IV: Make Data Connection? -------------------------
*
* Try EPSV, if that fails... try PASV, if that fails... try PORT.
*/
/*goto bypass;*/
/* set up data connection - EPSV */
{
char *data_ip;
/*
* The EPSV command replaces PASV where both IPV4 and IPV6 is
* supported. Only the port is returned, the IP address is always the
* same as that on the control connection. Example: Entering Extended
* Passive Mode (|||6446|)
*/
/* possible results: 227, 421, 500, 501, 502, 530 */
/* 227 Entering Passive Mode (h1,h2,h3,h4,p1,p2). */
/* 421 Service not available, closing control connection. */
/* 500 Syntax error, command unrecognized. */
/* 501 Syntax error in parameters or arguments. */
/* 502 Command not implemented. */
/* 530 Not logged in. */
"Error reading from remote server");
}
}
else if (rc == 229) {
/* Parse the port out of the EPSV reply. */
if (data_port) {
"proxy: FTP: EPSV contacting remote host on port %d",
if ((rv = apr_socket_create(&data_sock, connect_addr->family, SOCK_STREAM, 0, r->pool)) != APR_SUCCESS) {
"proxy: FTP: error creating EPSV socket");
proxy_ftp_cleanup(r, backend);
return HTTP_INTERNAL_SERVER_ERROR;
}
if (conf->recv_buffer_size > 0
conf->recv_buffer_size))) {
"proxy: FTP: apr_socket_opt_set(SO_RCVBUF): Failed to set ProxyReceiveBufferSize, using default");
}
"apr_socket_opt_set(APR_TCP_NODELAY): Failed to set");
}
/* make the connection */
if (rv != APR_SUCCESS) {
}
else {
connect = 1;
}
}
}
}
/* set up data connection - PASV */
if (!connect) {
/* possible results: 227, 421, 500, 501, 502, 530 */
/* 227 Entering Passive Mode (h1,h2,h3,h4,p1,p2). */
/* 421 Service not available, closing control connection. */
/* 500 Syntax error, command unrecognized. */
/* 501 Syntax error in parameters or arguments. */
/* 502 Command not implemented. */
/* 530 Not logged in. */
"Error reading from remote server");
}
}
else if (rc == 227) {
char *pstr;
char *tok_cntx;
/* FIXME: Check PASV against RFC1123 */
pstr = ftpmessage;
}
else {
* port params */
}
}
/* FIXME: Only supports IPV4 - fix in RFC2428 */
"proxy: FTP: PASV contacting host %d.%d.%d.%d:%d",
if ((rv = apr_socket_create(&data_sock, connect_addr->family, SOCK_STREAM, 0, r->pool)) != APR_SUCCESS) {
"proxy: error creating PASV socket");
proxy_ftp_cleanup(r, backend);
return HTTP_INTERNAL_SERVER_ERROR;
}
if (conf->recv_buffer_size > 0
conf->recv_buffer_size))) {
"proxy: FTP: apr_socket_opt_set(SO_RCVBUF): Failed to set ProxyReceiveBufferSize, using default");
}
"apr_socket_opt_set(APR_TCP_NODELAY): Failed to set");
}
/* make the connection */
apr_sockaddr_info_get(&pasv_addr, apr_psprintf(p, "%d.%d.%d.%d", h3, h2, h1, h0), connect_addr->family, pasvport, 0, p);
if (rv != APR_SUCCESS) {
}
else {
connect = 1;
}
}
}
}
/*bypass:*/
/* set up data connection - PORT */
if (!connect) {
char *local_ip;
if ((rv = apr_socket_create(&local_sock, connect_addr->family, SOCK_STREAM, 0, r->pool)) != APR_SUCCESS) {
"proxy: FTP: error creating local socket");
proxy_ftp_cleanup(r, backend);
return HTTP_INTERNAL_SERVER_ERROR;
}
!= APR_SUCCESS) {
#ifndef _OSD_POSIX /* BS2000 has this option "always on" */
"proxy: FTP: error setting reuseaddr option");
proxy_ftp_cleanup(r, backend);
return HTTP_INTERNAL_SERVER_ERROR;
#endif /* _OSD_POSIX */
}
"proxy: FTP: error binding to ftp data socket %pI", local_addr);
proxy_ftp_cleanup(r, backend);
return HTTP_INTERNAL_SERVER_ERROR;
}
/* only need a short queue */
"proxy: FTP: error listening to ftp data socket %pI", local_addr);
proxy_ftp_cleanup(r, backend);
return HTTP_INTERNAL_SERVER_ERROR;
}
/* FIXME: Sent PORT here */
/* possible results: 200, 421, 500, 501, 502, 530 */
/* 200 Command okay. */
/* 421 Service not available, closing control connection. */
/* 500 Syntax error, command unrecognized. */
/* 501 Syntax error in parameters or arguments. */
/* 502 Command not implemented. */
/* 530 Not logged in. */
"Error reading from remote server");
}
if (rc != 200) {
}
use_port = 1;
}
else {
/* IPV6 FIXME:
* The EPRT command replaces PORT where both IPV4 and IPV6 is supported. The first
* number (1,2) indicates the protocol type. Examples:
* EPRT |1|132.235.1.2|6275|
* EPRT |2|1080::8:800:200C:417A|5282|
*/
"Connect to IPV6 ftp server using EPRT not supported. Enable EPSV.");
}
}
/*
* V: Set The Headers -------------------
*
* Get the size of the request, set up the environment for HTTP.
*/
/* set request; "path" holds last path component */
"Use of /%2f is only allowed at the base directory");
}
/* If len == 0 then it must be a directory (you can't RETR nothing)
* Also, don't allow to RETR by wildcard. Instead, create a dirlisting,
* unless ProxyFtpListOnWildcard is off.
*/
dirlisting = 1;
}
else {
/* (from FreeBSD ftpd):
* SIZE is not in RFC959, but Postel has blessed it and
* it will be in the updated RFC.
*
* Return size of file in a format suitable for
* using with RESTART (we just count bytes).
*/
/* from draft-ietf-ftpext-mlst-14.txt:
* This value will
* change depending on the current STRUcture, MODE and TYPE of the data
* connection, or a data connection which would be created were one
* created now. Thus, the result of the SIZE command is dependent on
* the currently established STRU, MODE and TYPE parameters.
*/
/* Therefore: switch to binary if the user did not specify ";type=a" */
"Error reading from remote server");
}
int j;
for (j = 0; apr_isdigit(ftpmessage[j]); j++)
;
ftpmessage[j] = '\0';
if (ftpmessage[0] != '\0')
}
"proxy: FTP: SIZE shows this is a directory");
dirlisting = 1;
/* possible results: 250, 421, 500, 501, 502, 530, 550 */
/* 250 Requested file action okay, completed. */
/* 421 Service not available, closing control connection. */
/* 500 Syntax error, command unrecognized. */
/* 501 Syntax error in parameters or arguments. */
/* 502 Command not implemented. */
/* 530 Not logged in. */
/* 550 Requested action not taken. */
"Error reading from remote server");
}
if (rc == 550) {
}
if (rc != 250) {
}
path = "";
len = 0;
}
}
}
if (dirlisting) {
/* If the current directory contains no slash, we are talking to
* a non-unix ftp system. Try LIST instead of "LIST -lag", it
* should return a long listing anyway (unlike NLST).
* Some exotic FTP servers might choke on the "-lag" switch.
*/
/* Note that we do not escape the path here, to allow for
* queries like: ftp://user@host/apache/src/server/http_*.c
*/
if (len != 0)
else
}
else {
/* switch to binary if the user did not specify ";type=a" */
/* from draft-ietf-ftpext-mlst-14.txt:
* The FTP command, MODIFICATION TIME (MDTM), can be used to determine
* when a file in the server NVFS was last modified. <..>
* The syntax of a time value is:
* time-val = 14DIGIT [ "." 1*DIGIT ] <..>
* Symbolically, a time-val may be viewed as
* YYYYMMDDHHMMSS.sss
* The "." and subsequent digits ("sss") are optional. <..>
* Time values are always represented in UTC (GMT)
*/
rc = proxy_ftp_command(apr_pstrcat(p, "MDTM ", ftp_escape_globbingchars(p, path, fdconf), CRLF, NULL),
/* then extract the Last-Modified time from it (YYYYMMDDhhmmss or YYYYMMDDhhmmss.xxx GMT). */
if (rc == 213) {
struct {
} time_val;
#ifdef HAVE_TIMEGM /* Does system have timegm()? */
/* mktime will subtract the local timezone, which is not what we want.
* Add it again because the MDTM string is GMT
*/
#else
mtime = 0L;
#endif
}
}
#endif /* USE_MDTM */
/* FIXME: Handle range requests - send REST */
}
/* rc is an intermediate response for the LIST or RETR commands */
/*
* RETR: 110, 125, 150, 226, 250, 421, 425, 426, 450, 451, 500, 501, 530,
* 550 NLST: 125, 150, 226, 250, 421, 425, 426, 450, 451, 500, 501, 502,
* 530
*/
/* 110 Restart marker reply. */
/* 125 Data connection already open; transfer starting. */
/* 150 File status okay; about to open data connection. */
/* 226 Closing data connection. */
/* 250 Requested file action okay, completed. */
/* 421 Service not available, closing control connection. */
/* 425 Can't open data connection. */
/* 426 Connection closed; transfer aborted. */
/* 450 Requested file action not taken. */
/* 451 Requested action aborted. Local error in processing. */
/* 500 Syntax error, command unrecognized. */
/* 501 Syntax error in parameters or arguments. */
/* 530 Not logged in. */
/* 550 Requested action not taken. */
"Error reading from remote server");
}
if (rc == 550) {
"proxy: FTP: RETR failed, trying LIST instead");
/* Directory Listings should always be fetched in ASCII mode */
dirlisting = 1;
/* possible results: 250, 421, 500, 501, 502, 530, 550 */
/* 250 Requested file action okay, completed. */
/* 421 Service not available, closing control connection. */
/* 500 Syntax error, command unrecognized. */
/* 501 Syntax error in parameters or arguments. */
/* 502 Command not implemented. */
/* 530 Not logged in. */
/* 550 Requested action not taken. */
"Error reading from remote server");
}
if (rc == 550) {
}
if (rc != 250) {
}
/* Update current directory after CWD */
}
/* See above for the "LIST" vs. "LIST -lag" discussion. */
/* rc is an intermediate response for the LIST command (125 transfer starting, 150 opening data connection) */
"Error reading from remote server");
}
}
r->status_line = "200 OK";
/* set content-type */
if (dirlisting) {
"ISO-8859-1", NULL));
}
else {
/* We "trust" the ftp server to really serve (size) bytes... */
"proxy: FTP: Content-Length set to %s", size);
}
}
if (r->content_type) {
"proxy: FTP: Content-Type set to %s", r->content_type);
}
if (mtime != 0L) {
char datestr[APR_RFC822_DATE_LEN];
"proxy: FTP: Last-Modified set to %s", datestr);
}
#endif /* USE_MDTM */
/* If an encoding has been set by mistake, delete it.
* @@@ FIXME (e.g., for ftp://user@host/file*.tar.gz,
* @@@ the encoding is currently set to x-gzip)
*/
r->content_encoding = NULL;
/* set content-encoding (not for dir listings, they are uncompressed)*/
"proxy: FTP: Content-Encoding set to %s",
r->content_encoding);
}
/* wait for connection */
if (use_port) {
for (;;) {
continue;
}
else if (rv == APR_SUCCESS) {
break;
}
else {
"proxy: FTP: failed to accept data connection");
proxy_ftp_cleanup(r, backend);
return HTTP_BAD_GATEWAY;
}
}
}
/* the transfer socket is now open, create a new connection */
if (!data) {
/*
* the peer reset the connection already; ap_run_create_connection() closed
* the socket
*/
"proxy: FTP: an error occurred creating the transfer connection");
proxy_ftp_cleanup(r, backend);
return HTTP_INTERNAL_SERVER_ERROR;
}
/*
* We do not do SSL over the data connection, even if the virtual host we
* are in might have SSL enabled
*/
/* set up the connection filters */
"proxy: FTP: pre_connection setup failed (%d)",
rc);
proxy_ftp_cleanup(r, backend);
return rc;
}
/*
* VI: Receive the Response ------------------------
*
* Get response from the remote ftp socket, and pass it up the filter chain.
*/
/* send response */
r->sent_bodyct = 1;
if (dirlisting) {
/* insert directory filter */
}
/* send body */
if (!r->header_only) {
apr_bucket *e;
"proxy: FTP: start body send");
/* read the body, pass it to the output filters */
bb,
#if DEBUGGING
{
r->server, "proxy (PID %d): readbytes: %#x",
}
#endif
/* sanity check */
if (APR_BRIGADE_EMPTY(bb)) {
break;
}
/* found the last brigade? */
/* if this is the last brigade, cleanup the
* backend connection first to prevent the
* backend server from hanging around waiting
* for a slow client to eat these bytes
*/
if (data_sock) {
}
"proxy: FTP: data connection closed");
/* signal that we must leave */
}
/* if no EOS yet, then we must flush */
e = apr_bucket_flush_create(c->bucket_alloc);
}
/* try send what we read */
|| c->aborted) {
/* Ack! Phbtt! Die! User aborted! */
}
/* make sure we always clean up after ourselves */
/* if we are done, leave */
break;
}
}
"proxy: FTP: end body send");
}
if (data_sock) {
"proxy: FTP: data connection closed");
}
/* Retrieve the final response for the RETR or LIST commands */
/*
* VII: Clean Up -------------
*
* If there are no KeepAlives, or if the connection has been signalled to
* close, close the socket and clean up
*/
/* finish */
/* responses: 221, 500 */
/* 221 Service closing control connection. */
/* 500 Syntax error, command unrecognized. */
proxy_ftp_cleanup(r, backend);
return OK;
}
static void ap_proxy_ftp_register_hook(apr_pool_t *p)
{
/* hooks */
/* filters */
}
static const command_rec proxy_ftp_cmds[] =
{
RSRC_CONF|ACCESS_CONF, "Whether wildcard characters in a path cause mod_proxy_ftp to list the files instead of trying to get them. Defaults to on."),
RSRC_CONF|ACCESS_CONF, "Whether the proxy should escape wildcards in paths before sending them to the FTP server. Defaults to on, but most FTP servers will need it turned off if you need to manage paths that contain wildcard characters."),
{NULL}
};
create_proxy_ftp_dir_config,/* create per-directory config structure */
merge_proxy_ftp_dir_config, /* merge per-directory config structures */
NULL, /* create per-server config structure */
NULL, /* merge per-server config structures */
proxy_ftp_cmds, /* command apr_table_t */
ap_proxy_ftp_register_hook /* register hooks */
};