    001/*
    002 * Licensed to the Apache Software Foundation (ASF) under one or more
    003 * contributor license agreements.  See the NOTICE file distributed with
    004 * this work for additional information regarding copyright ownership.
    005 * The ASF licenses this file to You under the Apache License, Version 2.0
    006 * (the "License"); you may not use this file except in compliance with
    007 * the License.  You may obtain a copy of the License at
    008 *
    009 *      http://www.apache.org/licenses/LICENSE-2.0
    010 *
    011 * Unless required by applicable law or agreed to in writing, software
    012 * distributed under the License is distributed on an "AS IS" BASIS,
    013 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    014 * See the License for the specific language governing permissions and
    015 * limitations under the License.
    016 */
    017
    018package org.apache.commons.net.ftp;
    019
    020import java.io.BufferedReader;
    021import java.io.IOException;
    022import java.io.InputStream;
    023import java.io.InputStreamReader;
    024import java.io.OutputStream;
    025import java.io.Reader;
    026import java.io.UnsupportedEncodingException;
    027import java.net.Inet6Address;
    028import java.net.Socket;
    029import java.net.SocketException;
    030import java.nio.charset.Charset;
    031import java.util.ArrayList;
    032import java.util.List;
    033
    034import org.apache.commons.net.util.Base64;
    035
    036/**
    037 * Experimental attempt at FTP client that tunnels over an HTTP proxy connection.
    038 *
    039 * @since 2.2
    040 */
    041public class FTPHTTPClient extends FTPClient {
    042    private final String proxyHost;
    043    private final int proxyPort;
    044    private final String proxyUsername;
    045    private final String proxyPassword;
    046    private final Charset charset;
    047
    048    private static final byte[] CRLF={'\r', '\n'};
    049    private final Base64 base64 = new Base64();
    050
    051    private String tunnelHost; // Save the host when setting up a tunnel (needed for EPSV)
    052
    053    /**
    054     * Create an instance with the specified encoding
    055     *
    056     * @param proxyHost the hostname to use
    057     * @param proxyPort the port to use
    058     * @param proxyUser the user name for the proxy
    059     * @param proxyPass the password for the proxy
    060     * @param encoding the encoding to use
    061     */
    062    public FTPHTTPClient(final String proxyHost, final int proxyPort, final String proxyUser, final String proxyPass,
    063            final Charset encoding) {
    064        this.proxyHost = proxyHost;
    065        this.proxyPort = proxyPort;
    066        this.proxyUsername = proxyUser;
    067        this.proxyPassword = proxyPass;
    068        this.tunnelHost = null;
    069        this.charset = encoding;
    070    }
    071
    072    /**
    073     * Create an instance using the UTF-8 encoding
    074     *
    075     * @param proxyHost the hostname to use
    076     * @param proxyPort the port to use
    077     * @param proxyUser the user name for the proxy
    078     * @param proxyPass the password for the proxy
    079     */
    080    public FTPHTTPClient(final String proxyHost, final int proxyPort, final String proxyUser, final String proxyPass) {
    081        this(proxyHost, proxyPort, proxyUser, proxyPass, Charset.forName("UTF-8"));
    082    }
    083
    084    /**
    085     * Create an instance using the UTF-8 encoding, with no proxy credentials.
    086     *
    087     * @param proxyHost the hostname to use
    088     * @param proxyPort the port to use
    089     */
    090    public FTPHTTPClient(final String proxyHost, final int proxyPort) {
    091        this(proxyHost, proxyPort, null, null);
    092    }
    093
    094
    095    /**
    096     * Create an instance using the specified encoding, with no proxy credentials.
    097     *
    098     * @param proxyHost the hostname to use
    099     * @param proxyPort the port to use
    100     * @param encoding the encoding to use
    101     */
    102    public FTPHTTPClient(final String proxyHost, final int proxyPort, final Charset encoding) {
    103        this(proxyHost, proxyPort, null, null, encoding);
    104    }
    105
    106
    107    /**
    108     * {@inheritDoc}
    109     *
    110     * @throws IllegalStateException if connection mode is not passive
    111     * @deprecated (3.3) Use {@link FTPClient#_openDataConnection_(FTPCmd, String)} instead
    112     */
    113    // Kept to maintain binary compatibility
    114    // Not strictly necessary, but Clirr complains even though there is a super-impl
    115    @Override
    116    @Deprecated
    117    protected Socket _openDataConnection_(final int command, final String arg)
    118    throws IOException {
    119        return super._openDataConnection_(command, arg);
    120    }
    121
    122    /**
    123     * {@inheritDoc}
    124     *
    125     * @throws IllegalStateException if connection mode is not passive
    126     * @since 3.1
    127     */
    128    @Override
    129    protected Socket _openDataConnection_(final String command, final String arg)
    130    throws IOException {
    131        //Force local passive mode, active mode not supported by through proxy
    132        if (getDataConnectionMode() != PASSIVE_LOCAL_DATA_CONNECTION_MODE) {
    133            throw new IllegalStateException("Only passive connection mode supported");
    134        }
    135
    136        final boolean isInet6Address = getRemoteAddress() instanceof Inet6Address;
    137        String passiveHost = null;
    138
    139        final boolean attemptEPSV = isUseEPSVwithIPv4() || isInet6Address;
    140        if (attemptEPSV && epsv() == FTPReply.ENTERING_EPSV_MODE) {
    141            _parseExtendedPassiveModeReply(_replyLines.get(0));
    142            passiveHost = this.tunnelHost;
    143        } else {
    144            if (isInet6Address) {
    145                return null; // Must use EPSV for IPV6
    146            }
    147            // If EPSV failed on IPV4, revert to PASV
    148            if (pasv() != FTPReply.ENTERING_PASSIVE_MODE) {
    149                return null;
    150            }
    151            _parsePassiveModeReply(_replyLines.get(0));
    152            passiveHost = this.getPassiveHost();
    153        }
    154
    155        final Socket socket = _socketFactory_.createSocket(proxyHost, proxyPort);
    156        final InputStream is = socket.getInputStream();
    157        final OutputStream os = socket.getOutputStream();
    158        tunnelHandshake(passiveHost, this.getPassivePort(), is, os);
    159        if (getRestartOffset() > 0 && !restart(getRestartOffset())) {
    160            socket.close();
    161            return null;
    162        }
    163
    164        if (!FTPReply.isPositivePreliminary(sendCommand(command, arg))) {
    165            socket.close();
    166            return null;
    167        }
    168
    169        return socket;
    170    }
    171
    172    @Override
    173    public void connect(final String host, final int port) throws SocketException, IOException {
    174
    175        _socket_ = _socketFactory_.createSocket(proxyHost, proxyPort);
    176        _input_ = _socket_.getInputStream();
    177        _output_ = _socket_.getOutputStream();
    178        Reader socketIsReader;
    179        try {
    180            socketIsReader = tunnelHandshake(host, port, _input_, _output_);
    181        }
    182        catch (final Exception e) {
    183            final IOException ioe = new IOException("Could not connect to " + host + " using port " + port);
    184            ioe.initCause(e);
    185            throw ioe;
    186        }
    187        super._connectAction_(socketIsReader);
    188    }
    189
    190    private BufferedReader tunnelHandshake(final String host, final int port, final InputStream input,
    191            final OutputStream output) throws IOException, UnsupportedEncodingException {
    192        final String connectString = "CONNECT " + host + ":" + port + " HTTP/1.1";
    193        final String hostString = "Host: " + host + ":" + port;
    194
    195        this.tunnelHost = host;
    196        output.write(connectString.getBytes(charset));
    197        output.write(CRLF);
    198        output.write(hostString.getBytes(charset));
    199        output.write(CRLF);
    200
    201        if (proxyUsername != null && proxyPassword != null) {
    202            final String auth = proxyUsername + ":" + proxyPassword;
    203            final String header = "Proxy-Authorization: Basic " + base64.encodeToString(auth.getBytes(charset));
    204            output.write(header.getBytes(charset));
    205        }
    206        output.write(CRLF);
    207
    208        final List<String> response = new ArrayList<>();
    209        final BufferedReader reader = new BufferedReader(new InputStreamReader(input, getCharset()));
    210
    211        for (String line = reader.readLine(); line != null && line.length() > 0; line = reader.readLine()) {
    212            response.add(line);
    213        }
    214
    215        final int size = response.size();
    216        if (size == 0) {
    217            throw new IOException("No response from proxy");
    218        }
    219
    220        String code = null;
    221        final String resp = response.get(0);
    222        if (resp.startsWith("HTTP/") && resp.length() >= 12) {
    223            code = resp.substring(9, 12);
    224        } else {
    225            throw new IOException("Invalid response from proxy: " + resp);
    226        }
    227
    228        if (!"200".equals(code)) {
    229            final StringBuilder msg = new StringBuilder();
    230            msg.append("HTTPTunnelConnector: connection failed\r\n");
    231            msg.append("Response received from the proxy:\r\n");
    232            for (final String line : response) {
    233                msg.append(line);
    234                msg.append("\r\n");
    235            }
    236            throw new IOException(msg.toString());
    237        }
    238        return reader;
    239    }
    240}
    241
    242