FTPHTTPClient.java

  1. /*
  2.  * Licensed to the Apache Software Foundation (ASF) under one or more
  3.  * contributor license agreements.  See the NOTICE file distributed with
  4.  * this work for additional information regarding copyright ownership.
  5.  * The ASF licenses this file to You under the Apache License, Version 2.0
  6.  * (the "License"); you may not use this file except in compliance with
  7.  * the License.  You may obtain a copy of the License at
  8.  *
  9.  *      http://www.apache.org/licenses/LICENSE-2.0
  10.  *
  11.  * Unless required by applicable law or agreed to in writing, software
  12.  * distributed under the License is distributed on an "AS IS" BASIS,
  13.  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14.  * See the License for the specific language governing permissions and
  15.  * limitations under the License.
  16.  */

  17. package org.apache.commons.net.ftp;

  18. import java.io.BufferedReader;
  19. import java.io.IOException;
  20. import java.io.InputStream;
  21. import java.io.InputStreamReader;
  22. import java.io.OutputStream;
  23. import java.io.Reader;
  24. import java.io.UnsupportedEncodingException;
  25. import java.net.Inet6Address;
  26. import java.net.Socket;
  27. import java.net.SocketException;
  28. import java.nio.charset.Charset;
  29. import java.nio.charset.StandardCharsets;
  30. import java.util.ArrayList;
  31. import java.util.Base64;
  32. import java.util.List;

  33. /**
  34.  * Experimental attempt at FTP client that tunnels over an HTTP proxy connection.
  35.  *
  36.  * @since 2.2
  37.  */
  38. public class FTPHTTPClient extends FTPClient {

  39.     private static final byte[] CRLF = { '\r', '\n' };
  40.     private final String proxyHost;
  41.     private final int proxyPort;
  42.     private final String proxyUserName;
  43.     private final String proxyPassword;
  44.     private final Charset charset;
  45.     private String tunnelHost; // Save the host when setting up a tunnel (needed for EPSV)

  46.     /**
  47.      * Create an instance using the UTF-8 encoding, with no proxy credentials.
  48.      *
  49.      * @param proxyHost the hostname to use
  50.      * @param proxyPort the port to use
  51.      */
  52.     public FTPHTTPClient(final String proxyHost, final int proxyPort) {
  53.         this(proxyHost, proxyPort, null, null);
  54.     }

  55.     /**
  56.      * Create an instance using the specified encoding, with no proxy credentials.
  57.      *
  58.      * @param proxyHost the hostname to use
  59.      * @param proxyPort the port to use
  60.      * @param encoding  the encoding to use
  61.      */
  62.     public FTPHTTPClient(final String proxyHost, final int proxyPort, final Charset encoding) {
  63.         this(proxyHost, proxyPort, null, null, encoding);
  64.     }

  65.     /**
  66.      * Create an instance using the UTF-8 encoding
  67.      *
  68.      * @param proxyHost the hostname to use
  69.      * @param proxyPort the port to use
  70.      * @param proxyUser the user name for the proxy
  71.      * @param proxyPass the password for the proxy
  72.      */
  73.     public FTPHTTPClient(final String proxyHost, final int proxyPort, final String proxyUser, final String proxyPass) {
  74.         this(proxyHost, proxyPort, proxyUser, proxyPass, StandardCharsets.UTF_8);
  75.     }

  76.     /**
  77.      * Create an instance with the specified encoding
  78.      *
  79.      * @param proxyHost the hostname to use
  80.      * @param proxyPort the port to use
  81.      * @param proxyUser the user name for the proxy
  82.      * @param proxyPass the password for the proxy
  83.      * @param encoding  the encoding to use
  84.      */
  85.     public FTPHTTPClient(final String proxyHost, final int proxyPort, final String proxyUser, final String proxyPass, final Charset encoding) {
  86.         this.proxyHost = proxyHost;
  87.         this.proxyPort = proxyPort;
  88.         this.proxyUserName = proxyUser;
  89.         this.proxyPassword = proxyPass;
  90.         this.tunnelHost = null;
  91.         this.charset = encoding;
  92.     }

  93.     /**
  94.      * {@inheritDoc}
  95.      *
  96.      * @throws IllegalStateException if connection mode is not passive
  97.      * @deprecated (3.3) Use {@link FTPClient#_openDataConnection_(FTPCmd, String)} instead
  98.      */
  99.     // Kept to maintain binary compatibility
  100.     // Not strictly necessary, but Clirr complains even though there is a super-impl
  101.     @Override
  102.     @Deprecated
  103.     protected Socket _openDataConnection_(final int command, final String arg) throws IOException {
  104.         return super._openDataConnection_(command, arg);
  105.     }

  106.     /**
  107.      * {@inheritDoc}
  108.      *
  109.      * @throws IllegalStateException if connection mode is not passive
  110.      * @since 3.1
  111.      */
  112.     @Override
  113.     protected Socket _openDataConnection_(final String command, final String arg) throws IOException {
  114.         // Force local passive mode, active mode not supported by through proxy
  115.         if (getDataConnectionMode() != PASSIVE_LOCAL_DATA_CONNECTION_MODE) {
  116.             throw new IllegalStateException("Only passive connection mode supported");
  117.         }

  118.         final boolean isInet6Address = getRemoteAddress() instanceof Inet6Address;
  119.         String passiveHost;

  120.         final boolean attemptEPSV = isUseEPSVwithIPv4() || isInet6Address;
  121.         if (attemptEPSV && epsv() == FTPReply.ENTERING_EPSV_MODE) {
  122.             _parseExtendedPassiveModeReply(_replyLines.get(0));
  123.             passiveHost = this.tunnelHost;
  124.         } else {
  125.             if (isInet6Address) {
  126.                 return null; // Must use EPSV for IPV6
  127.             }
  128.             // If EPSV failed on IPV4, revert to PASV
  129.             if (pasv() != FTPReply.ENTERING_PASSIVE_MODE) {
  130.                 return null;
  131.             }
  132.             _parsePassiveModeReply(_replyLines.get(0));
  133.             passiveHost = getPassiveHost();
  134.         }

  135.         final Socket socket = _socketFactory_.createSocket(proxyHost, proxyPort);
  136.         final InputStream is = socket.getInputStream();
  137.         final OutputStream os = socket.getOutputStream();
  138.         tunnelHandshake(passiveHost, getPassivePort(), is, os);
  139.         if (getRestartOffset() > 0 && !restart(getRestartOffset())) {
  140.             socket.close();
  141.             return null;
  142.         }

  143.         if (!FTPReply.isPositivePreliminary(sendCommand(command, arg))) {
  144.             socket.close();
  145.             return null;
  146.         }

  147.         return socket;
  148.     }

  149.     @Override
  150.     public void connect(final String host, final int port) throws SocketException, IOException {

  151.         _socket_ = _socketFactory_.createSocket(proxyHost, proxyPort);
  152.         _input_ = _socket_.getInputStream();
  153.         _output_ = _socket_.getOutputStream();
  154.         final Reader socketIsReader;
  155.         try {
  156.             socketIsReader = tunnelHandshake(host, port, _input_, _output_);
  157.         } catch (final Exception e) {
  158.             final IOException ioe = new IOException("Could not connect to " + host + " using port " + port);
  159.             ioe.initCause(e);
  160.             throw ioe;
  161.         }
  162.         super._connectAction_(socketIsReader);
  163.     }

  164.     private BufferedReader tunnelHandshake(final String host, final int port, final InputStream input, final OutputStream output)
  165.             throws IOException, UnsupportedEncodingException {
  166.         final String connectString = "CONNECT " + host + ":" + port + " HTTP/1.1";
  167.         final String hostString = "Host: " + host + ":" + port;

  168.         this.tunnelHost = host;
  169.         output.write(connectString.getBytes(charset));
  170.         output.write(CRLF);
  171.         output.write(hostString.getBytes(charset));
  172.         output.write(CRLF);

  173.         if (proxyUserName != null && proxyPassword != null) {
  174.             final String auth = proxyUserName + ":" + proxyPassword;
  175.             final String header = "Proxy-Authorization: Basic " + Base64.getEncoder().encodeToString(auth.getBytes(charset));
  176.             output.write(header.getBytes(charset));
  177.             output.write(CRLF);
  178.         }
  179.         output.write(CRLF);

  180.         final List<String> response = new ArrayList<>();
  181.         final BufferedReader reader = new BufferedReader(new InputStreamReader(input, getCharset()));

  182.         for (String line = reader.readLine(); line != null && !line.isEmpty(); line = reader.readLine()) {
  183.             response.add(line);
  184.         }

  185.         final int size = response.size();
  186.         if (size == 0) {
  187.             throw new IOException("No response from proxy");
  188.         }

  189.         String code;
  190.         final String resp = response.get(0);
  191.         if (!resp.startsWith("HTTP/") || resp.length() < 12) {
  192.             throw new IOException("Invalid response from proxy: " + resp);
  193.         }
  194.         code = resp.substring(9, 12);

  195.         if (!"200".equals(code)) {
  196.             final StringBuilder msg = new StringBuilder();
  197.             msg.append("HTTPTunnelConnector: connection failed\r\n");
  198.             msg.append("Response received from the proxy:\r\n");
  199.             for (final String line : response) {
  200.                 msg.append(line);
  201.                 msg.append("\r\n");
  202.             }
  203.             throw new IOException(msg.toString());
  204.         }
  205.         return reader;
  206.     }
  207. }