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.  *      https://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.charset = encoding;
  91.     }

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

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

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

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

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

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

  146.         return socket;
  147.     }

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

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

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

  165.         this.tunnelHost = host;
  166.         output.write(connectString.getBytes(charset));
  167.         output.write(CRLF);
  168.         output.write(hostString.getBytes(charset));
  169.         output.write(CRLF);

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

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

  179.         for (String line = reader.readLine(); line != null && !line.isEmpty(); line = reader.readLine()) {
  180.             response.add(line);
  181.         }

  182.         final int size = response.size();
  183.         if (size == 0) {
  184.             throw new IOException("No response from proxy");
  185.         }

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

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