proxy_ftp.c revision 066877f1a045103acfdd376d48cdd473c33f409b
/* ====================================================================
* The Apache Software License, Version 1.1
*
* Copyright (c) 2000 The Apache Software Foundation. All rights
* reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* distribution.
*
* 3. The end-user documentation included with the redistribution,
* if any, must include the following acknowledgment:
* "This product includes software developed by the
* Apache Software Foundation (http://www.apache.org/)."
* Alternately, this acknowledgment may appear in the software itself,
* if and wherever such third-party acknowledgments normally appear.
*
* 4. The names "Apache" and "Apache Software Foundation" must
* not be used to endorse or promote products derived from this
* software without prior written permission. For written
* permission, please contact apache@apache.org.
*
* 5. Products derived from this software may not be called "Apache",
* nor may "Apache" appear in their name, without prior written
* permission of the Apache Software Foundation.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
* USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
*
* Portions of this software are based upon public domain software
* originally written at the National Center for Supercomputing Applications,
* University of Illinois, Urbana-Champaign.
*/
/* FTP routines for Apache proxy */
#include "mod_proxy.h"
#include "http_main.h"
#include "http_log.h"
#include "http_core.h"
#define AUTODETECT_PWD
{
char c;
do
{
} while(c != '\n');
}
/*
* 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;
}
/*
* 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;
for (i = 0; x[i] != '\0'; i++) {
ch = x[i];
i += 2;
}
#if !APR_CHARSET_EBCDIC
#else /*APR_CHARSET_EBCDIC*/
#endif /*APR_CHARSET_EBCDIC*/
return 0;
}
return 1;
}
/*
* Canonicalise ftp URLs.
*/
{
apr_pool_t *p = r->pool;
const char *err;
int port;
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 */
if (port != DEFAULT_FTP_PORT)
else
sport[0] = '\0';
return OK;
}
/*
* Returns the ftp status code;
* or -1 on I/O error, 0 on data error
*/
{
if (len == -1)
return -1;
/* check format */
status = 0;
else
skiplf(f);
}
/* skip continuation lines */
do {
if (len == -1)
return -1;
skiplf(f);
}
}
return status;
}
/*
* Like ftp_getrc but returns both the ftp status code and
* remembers the response message in the supplied buffer
*/
{
if (len == -1)
return -1;
status = 0;
else
skiplf(f);
do {
if (len == -1)
return -1;
skiplf(f);
}
}
return status;
}
{
char *filename;
int searchidx = 0;
int firstfile = 1;
unsigned long total_bytes_sent = 0;
register int n, o, w;
if(c) ap_cache_el_data(c, &cachefp);
/* Save "scheme://site" prefix without password */
/* ... and path without query args */
/* Copy path, strip (all except the last) trailing slashes */
/* print "ftp://host/" */
"<HTML><HEAD><TITLE>%s%s</TITLE>\n"
"<BASE HREF=\"%s%s\"></HEAD>\n"
"<BODY><H2>Directory of "
"<A HREF=\"/\">%s</A>/",
{
*dir = '\0';
else
++reldir;
/* print "path/" component */
*dir = '/';
}
/* If the caller has determined the current directory, and it differs */
/* from what the client requested, then show the real name */
} else {
}
if (n == -1) { /* input error */
if (c != NULL) {
"proxy: error reading from cache");
ap_proxy_cache_error(&c);
}
break;
}
if (n == 0)
break; /* EOF */
do {
filename--;
} while (filename[0] != ' ');
*(filename++) = '\0';
*(link_ptr++) = '\0';
apr_snprintf(buf2, sizeof(buf2), "%s <A HREF=\"%s\">%s %s</A>\n", buf, filename, filename, link_ptr);
}
*searchptr = '[';
*searchptr = ']';
}
*(filename++) = 0;
/* handle filenames with spaces in 'em */
firstfile = 0;
}
*(--filename) = ' ';
}
/* Special handling for '.' and '..' */
}
else {
}
}
o = 0;
total_bytes_sent += n;
cntr = n;
"proxy: error writing to cache");
ap_proxy_cache_error(&c);
}
while (n && !r->connection->aborted) {
cntr = n;
if (w <= 0)
break;
n -= w;
o += w;
}
}
/* Flushing the actual socket doesn't make much sense, because we don't
* buffer it yet.
ap_flush(con->client);
*/
return total_bytes_sent;
}
/* 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 = 0;
/* Log failed requests if they supplied a password
*/
if (log_it)
"proxy: missing or failed auth to %s",
&r->parsed_uri, UNP_OMITPATHINFO));
"\"", NULL));
return HTTP_UNAUTHORIZED;
}
/*
* Handles direct access of ftp:// URLs
* Original (Non-PASV) version from
* Troy Morrison <spiffnet@zoom.com>
* PASV added by Chuck
*/
{
/* char *account = NULL; how to supply an account in a URL? */
BUFF *f;
apr_pool_t *p = r->pool;
int one = 1;
const long int zero = 0L;
/* stuff for PASV mode */
unsigned short pport;
int pasvmode = 0;
char pasv[64];
char *npaddr;
/* stuff for responses */
char resp[MAX_STRING_LEN];
/* 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 */
? r->parsed_uri.port
/* 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.
*/
/* 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@";
}
/* check if ProxyBlock directive on this host */
return ap_proxyerror(r, HTTP_FORBIDDEN,
"Connect to remote machine blocked");
}
*(parms++) = '\0';
"proxy: error creating socket");
return HTTP_INTERNAL_SERVER_ERROR;
}
if (conf->recv_buffer_size > 0
conf->recv_buffer_size)) {
"setsockopt(SO_RCVBUF): Failed to set ProxyReceiveBufferSize, using default");
}
#endif
#ifndef _OSD_POSIX /* BS2000 has this option "always on" */
"proxy: error setting reuseaddr option: setsockopt(SO_REUSEADDR)");
return HTTP_INTERNAL_SERVER_ERROR;
#endif /*_OSD_POSIX*/
}
"Could not connect to remote machine: ",
}
f = ap_bcreate(p, B_RDWR);
ap_bpush_socket(f, sock);
/* shouldn't we implement telnet control options here? */
#endif /*APR_CHARSET_EBCDIC*/
/* possible results: */
/* 120 Service ready in nnn minutes. */
/* 220 Service ready for new user. */
/* 421 Service not available, closing control connection. */
"FTP: returned status %d", i);
if (i == -1) {
return ap_proxyerror(r, HTTP_BAD_GATEWAY,
"Error reading from remote server");
}
#if 0
if (i == 120) {
/* RFC2068 states:
* 14.38 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 )
*/
}
#endif
if (i != 220) {
}
"FTP: connected.");
ap_bflush(f); /* capture any errors */
"FTP: USER %s", user);
/* 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. */
i = ftp_getrc(f);
"FTP: returned status %d", i);
if (i == -1) {
return ap_proxyerror(r, HTTP_BAD_GATEWAY,
"Error reading from remote server");
}
if (i == 530) {
}
if (i != 230 && i != 331) {
return HTTP_BAD_GATEWAY;
}
if (i == 331) { /* send password */
return ftp_unauthorized (r, 0);
}
ap_bflush(f);
"FTP: PASS %s", password);
/* 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. */
i = ftp_getrc(f);
"FTP: returned status %d", i);
if (i == -1) {
return ap_proxyerror(r, HTTP_BAD_GATEWAY,
"Error reading from remote server");
}
if (i == 332) {
return ap_proxyerror(r, HTTP_UNAUTHORIZED,
"Need account for login");
}
/* @@@ questionable -- we might as well return a 403 Forbidden here */
if (i == 530) {
}
if (i != 230 && i != 202) {
return HTTP_BAD_GATEWAY;
}
}
/* 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';
ap_bflush(f);
"FTP: CWD %s", 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. */
i = ftp_getrc(f);
"FTP: returned status %d", i);
if (i == -1) {
return ap_proxyerror(r, HTTP_BAD_GATEWAY,
"Error reading from remote server");
}
if (i == 550) {
return HTTP_NOT_FOUND;
}
if (i != 250) {
return HTTP_BAD_GATEWAY;
}
}
parms += 5;
parms = "";
}
else
parms = "";
/* changed to make binary transfers the default */
if (parms[0] != 'a') {
/* set type to image */
/* TM - Added CRLF to the end of TYPE I, otherwise it hangs the
connection */
ap_bflush(f);
"FTP: TYPE I");
/* 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. */
i = ftp_getrc(f);
"FTP: returned status %d", i);
if (i == -1) {
return ap_proxyerror(r, HTTP_BAD_GATEWAY,
"Error reading from remote server");
}
if (i != 200 && i != 504) {
return HTTP_BAD_GATEWAY;
}
/* Allow not implemented */
if (i == 504)
parms[0] = '\0';
}
/* try to set up PASV data connection first */
"proxy: error creating PASV socket");
ap_bclose(f);
return HTTP_INTERNAL_SERVER_ERROR;
}
conf->recv_buffer_size)) {
"setsockopt(SO_RCVBUF): Failed to set ProxyReceiveBufferSize, using default");
}
#endif
ap_bflush(f);
"FTP: PASV command issued");
/* 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. */
if (i == -1) {
"PASV: control connection is toast");
ap_bclose(f);
return HTTP_INTERNAL_SERVER_ERROR;
}
else {
else
{
}
}
else
"FTP: returned status %d", presult);
/* pardon the parens, but it makes gcc happy */
"FTP: contacting host %d.%d.%d.%d:%d",
/* scary */
return ap_proxyerror(r, HTTP_BAD_GATEWAY,
apr_pstrcat(r->pool,
"Could not connect to remote machine: ",
}
else {
pasvmode = 1;
}
}
else
}
if (!pasvmode) { /* set up data connection */
"proxy: error creating socket");
ap_bclose(f);
return HTTP_INTERNAL_SERVER_ERROR;
}
#ifndef _OSD_POSIX /* BS2000 has this option "always on" */
"proxy: error setting reuseaddr option");
ap_bclose(f);
return HTTP_INTERNAL_SERVER_ERROR;
#endif /*_OSD_POSIX*/
}
!= APR_SUCCESS) {
"proxy: error creating local socket address");
ap_bclose(f);
return HTTP_INTERNAL_SERVER_ERROR;
}
char buff[22];
"proxy: error binding to ftp data socket %s", buff);
ap_bclose(f);
return HTTP_INTERNAL_SERVER_ERROR;
}
}
/* set request; "path" holds last path component */
/* TM - if len == 0 then it must be a directory (you can't RETR nothing) */
if (len == 0) {
parms = "d";
}
else {
ap_bflush(f);
"FTP: SIZE %s", path);
"FTP: returned status %d with response %s", i, resp);
if (i != 500) { /* Size command not recognized */
if (i == 550) { /* Not a regular file */
"FTP: SIZE shows this is a directory");
parms = "d";
ap_bflush(f);
"FTP: CWD %s", path);
i = ftp_getrc(f);
/* 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. */
"FTP: returned status %d", i);
if (i == -1) {
return ap_proxyerror(r, HTTP_BAD_GATEWAY,
"Error reading from remote server");
}
if (i == 550) {
return HTTP_NOT_FOUND;
}
if (i != 250) {
return HTTP_BAD_GATEWAY;
}
path = "";
len = 0;
}
else if (i == 213) { /* Size command ok */
;
resp[j] = '\0';
if (resp[0] != '\0')
}
}
}
#ifdef AUTODETECT_PWD
ap_bflush(f);
"FTP: PWD");
/* 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. */
"FTP: PWD returned status %d", i);
if (i == -1 || i == 421) {
return ap_proxyerror(r, HTTP_BAD_GATEWAY,
"Error reading from remote server");
}
if (i == 550) {
return HTTP_NOT_FOUND;
}
if (i == 257) {
}
#endif /*AUTODETECT_PWD*/
if (parms[0] == 'd') {
if (len != 0)
else
}
else {
"FTP: RETR %s", path);
}
ap_bflush(f);
/* 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. */
"FTP: returned status %d", rc);
if (rc == -1) {
return ap_proxyerror(r, HTTP_BAD_GATEWAY,
"Error reading from remote server");
}
if (rc == 550) {
"FTP: RETR failed, trying LIST instead");
parms = "d";
ap_bflush(f);
"FTP: CWD %s", path);
/* 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. */
"FTP: returned status %d", rc);
if (rc == -1) {
return ap_proxyerror(r, HTTP_BAD_GATEWAY,
"Error reading from remote server");
}
if (rc == 550) {
return HTTP_NOT_FOUND;
}
if (rc != 250) {
return HTTP_BAD_GATEWAY;
}
#ifdef AUTODETECT_PWD
ap_bflush(f);
"FTP: PWD");
/* 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. */
"FTP: PWD returned status %d", i);
if (i == -1 || i == 421) {
return ap_proxyerror(r, HTTP_BAD_GATEWAY,
"Error reading from remote server");
}
if (i == 550) {
return HTTP_NOT_FOUND;
}
if (i == 257) {
}
#endif /*AUTODETECT_PWD*/
ap_bflush(f);
"FTP: LIST -lag");
"FTP: returned status %d", rc);
if (rc == -1)
return ap_proxyerror(r, HTTP_BAD_GATEWAY,
"Error reading from remote server");
}
return HTTP_BAD_GATEWAY;
r->status_line = "200 OK";
if (parms[0] == 'd')
else {
if (r->content_type != NULL) {
"FTP: Content-Type set to %s", r->content_type);
}
else {
}
/* We "trust" the ftp server to really serve (size) bytes... */
"FTP: Content-Length set to %s", size);
}
}
"FTP: Content-Encoding set to %s", r->content_encoding);
}
/* check if NoCache directive on this host */
nocache = 1;
}
#if 0
if (i != DECLINED) {
ap_pclosesocket(p, dsock);
ap_bclose(f);
return i;
}
#endif
ap_proxy_cache_error(&c);
else
ap_cache_el_data(c, &cachefp);
if (!pasvmode) { /* wait for connection */
for(;;)
{
{
case APR_EINTR:
continue;
case APR_SUCCESS:
break;
default:
"proxy: failed to accept data connection");
ap_bclose(f);
if (c != NULL) ap_proxy_cache_error(&c);
return HTTP_BAD_GATEWAY;
}
}
ap_bpush_socket(f, csd);
}
else {
}
/* send response */
/* write status line */
if (!r->assbackwards)
"proxy: error writing CRLF to cache");
ap_proxy_cache_error(&c);
}
/* send headers */
if (!r->assbackwards)
"proxy: error writing CRLF to cache");
ap_proxy_cache_error(&c);
}
/* This is done by a filter now, so this can probably be removed cleanly.
ap_bsetopt(r->connection->client, BO_BYTECT, &zero);
*/
r->sent_bodyct = 1;
/* send body */
if (!r->header_only) {
if (parms[0] != 'd') {
} else
/* XXX: we checked for 125||150||226||250 above. This is redundant. */
/* XXX: we no longer log an "error writing to c->tempfile" - should we? */
ap_proxy_cache_error(&c);
}
else {
/* abort the transfer */
ap_bflush(f);
if (!pasvmode)
"FTP: ABOR");
/* responses: 225, 226, 421, 500, 501, 502 */
/* 225 Data connection open; no transfer in progress. */
/* 226 Closing data connection. */
/* 421 Service not available, closing control connection. */
/* 500 Syntax error, command unrecognized. */
/* 501 Syntax error in parameters or arguments. */
/* 502 Command not implemented. */
i = ftp_getrc(f);
"FTP: returned status %d", i);
}
/* finish */
ap_bflush(f);
"FTP: QUIT");
/* responses: 221, 500 */
/* 221 Service closing control connection. */
/* 500 Syntax error, command unrecognized. */
i = ftp_getrc(f);
"FTP: QUIT: status %d", i);
if (pasvmode)
ap_bclose(f);
ap_rflush(r); /* flush before garbage collection */
if(c) ap_proxy_cache_update(c);
return OK;
}