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.UnsupportedEncodingException;
026import java.net.Inet6Address;
027import java.net.Socket;
028import java.net.SocketException;
029import java.util.ArrayList;
030import java.util.List;
031
032import org.apache.commons.net.util.Base64;
033
034/**
035 * Experimental attempt at FTP client that tunnels over an HTTP proxy connection.
036 *
037 * @since 2.2
038 */
039public class FTPHTTPClient extends FTPClient {
040    private final String proxyHost;
041    private final int proxyPort;
042    private final String proxyUsername;
043    private final String proxyPassword;
044
045    private static final byte[] CRLF={'\r', '\n'};
046    private final Base64 base64 = new Base64();
047
048    private String tunnelHost; // Save the host when setting up a tunnel (needed for EPSV)
049
050    public FTPHTTPClient(String proxyHost, int proxyPort, String proxyUser, String proxyPass) {
051        this.proxyHost = proxyHost;
052        this.proxyPort = proxyPort;
053        this.proxyUsername = proxyUser;
054        this.proxyPassword = proxyPass;
055        this.tunnelHost = null;
056    }
057
058    public FTPHTTPClient(String proxyHost, int proxyPort) {
059        this(proxyHost, proxyPort, null, null);
060    }
061
062
063    /**
064     * {@inheritDoc}
065     *
066     * @throws IllegalStateException if connection mode is not passive
067     * @deprecated (3.3) Use {@link #_openDataConnection_(FTPCmd, String)} instead
068     */
069    // Kept to maintain binary compatibility
070    // Not strictly necessary, but Clirr complains even though there is a super-impl
071    @Override
072    @Deprecated
073    protected Socket _openDataConnection_(int command, String arg)
074    throws IOException {
075        return super._openDataConnection_(command, arg);
076    }
077
078    /**
079     * {@inheritDoc}
080     *
081     * @throws IllegalStateException if connection mode is not passive
082     * @since 3.1
083     */
084    @Override
085    protected Socket _openDataConnection_(String command, String arg)
086    throws IOException {
087        //Force local passive mode, active mode not supported by through proxy
088        if (getDataConnectionMode() != PASSIVE_LOCAL_DATA_CONNECTION_MODE) {
089            throw new IllegalStateException("Only passive connection mode supported");
090        }
091
092        final boolean isInet6Address = getRemoteAddress() instanceof Inet6Address;
093        String passiveHost = null;
094
095        boolean attemptEPSV = isUseEPSVwithIPv4() || isInet6Address;
096        if (attemptEPSV && epsv() == FTPReply.ENTERING_EPSV_MODE) {
097            _parseExtendedPassiveModeReply(_replyLines.get(0));
098            passiveHost = this.tunnelHost;
099        } else {
100            if (isInet6Address) {
101                return null; // Must use EPSV for IPV6
102            }
103            // If EPSV failed on IPV4, revert to PASV
104            if (pasv() != FTPReply.ENTERING_PASSIVE_MODE) {
105                return null;
106            }
107            _parsePassiveModeReply(_replyLines.get(0));
108            passiveHost = this.getPassiveHost();
109        }
110
111        Socket socket = new Socket(proxyHost, proxyPort);
112        InputStream is = socket.getInputStream();
113        OutputStream os = socket.getOutputStream();
114        tunnelHandshake(passiveHost, this.getPassivePort(), is, os);
115        if ((getRestartOffset() > 0) && !restart(getRestartOffset())) {
116            socket.close();
117            return null;
118        }
119
120        if (!FTPReply.isPositivePreliminary(sendCommand(command, arg))) {
121            socket.close();
122            return null;
123        }
124
125        return socket;
126    }
127
128    @Override
129    public void connect(String host, int port) throws SocketException, IOException {
130
131        _socket_ = new Socket(proxyHost, proxyPort);
132        _input_ = _socket_.getInputStream();
133        _output_ = _socket_.getOutputStream();
134        try {
135            tunnelHandshake(host, port, _input_, _output_);
136        }
137        catch (Exception e) {
138            IOException ioe = new IOException("Could not connect to " + host+ " using port " + port);
139            ioe.initCause(e);
140            throw ioe;
141        }
142        super._connectAction_();
143    }
144
145    private void tunnelHandshake(String host, int port, InputStream input, OutputStream output) throws IOException,
146    UnsupportedEncodingException {
147        final String connectString = "CONNECT "  + host + ":" + port  + " HTTP/1.1";
148        final String hostString = "Host: " + host + ":" + port;
149
150        this.tunnelHost = host;
151        output.write(connectString.getBytes("UTF-8")); // TODO what is the correct encoding?
152        output.write(CRLF);
153        output.write(hostString.getBytes("UTF-8"));
154        output.write(CRLF);
155
156        if (proxyUsername != null && proxyPassword != null) {
157            final String auth = proxyUsername + ":" + proxyPassword;
158            final String header = "Proxy-Authorization: Basic "
159                + base64.encodeToString(auth.getBytes("UTF-8"));
160            output.write(header.getBytes("UTF-8"));
161        }
162        output.write(CRLF);
163
164        List<String> response = new ArrayList<String>();
165        BufferedReader reader = new BufferedReader(
166                new InputStreamReader(input, getCharsetName())); // Java 1.6 can use getCharset()
167
168        for (String line = reader.readLine(); line != null
169        && line.length() > 0; line = reader.readLine()) {
170            response.add(line);
171        }
172
173        int size = response.size();
174        if (size == 0) {
175            throw new IOException("No response from proxy");
176        }
177
178        String code = null;
179        String resp = response.get(0);
180        if (resp.startsWith("HTTP/") && resp.length() >= 12) {
181            code = resp.substring(9, 12);
182        } else {
183            throw new IOException("Invalid response from proxy: " + resp);
184        }
185
186        if (!"200".equals(code)) {
187            StringBuilder msg = new StringBuilder();
188            msg.append("HTTPTunnelConnector: connection failed\r\n");
189            msg.append("Response received from the proxy:\r\n");
190            for (String line : response) {
191                msg.append(line);
192                msg.append("\r\n");
193            }
194            throw new IOException(msg.toString());
195        }
196    }
197}
198
199