src/java.net.http/share/classes/java/net/http/internal/HttpRequestImpl.java
branchhttp-client-branch
changeset 56089 42208b2f224e
parent 56079 d23b02f37fce
equal deleted inserted replaced
56088:38fac6d0521d 56089:42208b2f224e
       
     1 /*
       
     2  * Copyright (c) 2015, 2018, Oracle and/or its affiliates. All rights reserved.
       
     3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
       
     4  *
       
     5  * This code is free software; you can redistribute it and/or modify it
       
     6  * under the terms of the GNU General Public License version 2 only, as
       
     7  * published by the Free Software Foundation.  Oracle designates this
       
     8  * particular file as subject to the "Classpath" exception as provided
       
     9  * by Oracle in the LICENSE file that accompanied this code.
       
    10  *
       
    11  * This code is distributed in the hope that it will be useful, but WITHOUT
       
    12  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
       
    13  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
       
    14  * version 2 for more details (a copy is included in the LICENSE file that
       
    15  * accompanied this code).
       
    16  *
       
    17  * You should have received a copy of the GNU General Public License version
       
    18  * 2 along with this work; if not, write to the Free Software Foundation,
       
    19  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
       
    20  *
       
    21  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
       
    22  * or visit www.oracle.com if you need additional information or have any
       
    23  * questions.
       
    24  */
       
    25 
       
    26 package java.net.http.internal;
       
    27 
       
    28 import java.io.IOException;
       
    29 import java.net.InetSocketAddress;
       
    30 import java.net.Proxy;
       
    31 import java.net.ProxySelector;
       
    32 import java.net.URI;
       
    33 import java.security.AccessControlContext;
       
    34 import java.security.AccessController;
       
    35 import java.security.PrivilegedAction;
       
    36 import java.time.Duration;
       
    37 import java.util.List;
       
    38 import java.util.Locale;
       
    39 import java.util.Optional;
       
    40 import java.net.http.HttpClient;
       
    41 import java.net.http.HttpHeaders;
       
    42 import java.net.http.HttpRequest;
       
    43 import java.net.http.internal.common.HttpHeadersImpl;
       
    44 import java.net.http.internal.websocket.WebSocketRequest;
       
    45 
       
    46 import static java.net.http.internal.common.Utils.ALLOWED_HEADERS;
       
    47 
       
    48 class HttpRequestImpl extends HttpRequest implements WebSocketRequest {
       
    49 
       
    50     private final HttpHeaders userHeaders;
       
    51     private final HttpHeadersImpl systemHeaders;
       
    52     private final URI uri;
       
    53     private volatile Proxy proxy; // ensure safe publishing
       
    54     private final InetSocketAddress authority; // only used when URI not specified
       
    55     private final String method;
       
    56     final BodyPublisher requestPublisher;
       
    57     final boolean secure;
       
    58     final boolean expectContinue;
       
    59     private volatile boolean isWebSocket;
       
    60     private volatile AccessControlContext acc;
       
    61     private final Duration timeout;  // may be null
       
    62     private final Optional<HttpClient.Version> version;
       
    63 
       
    64     private static String userAgent() {
       
    65         PrivilegedAction<String> pa = () -> System.getProperty("java.version");
       
    66         String version = AccessController.doPrivileged(pa);
       
    67         return "Java-http-client/" + version;
       
    68     }
       
    69 
       
    70     /** The value of the User-Agent header for all requests sent by the client. */
       
    71     public static final String USER_AGENT = userAgent();
       
    72 
       
    73     /**
       
    74      * Creates an HttpRequestImpl from the given builder.
       
    75      */
       
    76     public HttpRequestImpl(HttpRequestBuilderImpl builder) {
       
    77         String method = builder.method();
       
    78         this.method = method == null ? "GET" : method;
       
    79         this.userHeaders = ImmutableHeaders.of(builder.headers().map(), ALLOWED_HEADERS);
       
    80         this.systemHeaders = new HttpHeadersImpl();
       
    81         this.uri = builder.uri();
       
    82         assert uri != null;
       
    83         this.proxy = null;
       
    84         this.expectContinue = builder.expectContinue();
       
    85         this.secure = uri.getScheme().toLowerCase(Locale.US).equals("https");
       
    86         this.requestPublisher = builder.bodyPublisher();  // may be null
       
    87         this.timeout = builder.timeout();
       
    88         this.version = builder.version();
       
    89         this.authority = null;
       
    90     }
       
    91 
       
    92     /**
       
    93      * Creates an HttpRequestImpl from the given request.
       
    94      */
       
    95     public HttpRequestImpl(HttpRequest request, ProxySelector ps, AccessControlContext acc) {
       
    96         String method = request.method();
       
    97         this.method = method == null ? "GET" : method;
       
    98         this.userHeaders = request.headers();
       
    99         if (request instanceof HttpRequestImpl) {
       
   100             this.systemHeaders = ((HttpRequestImpl) request).systemHeaders;
       
   101             this.isWebSocket = ((HttpRequestImpl) request).isWebSocket;
       
   102         } else {
       
   103             this.systemHeaders = new HttpHeadersImpl();
       
   104         }
       
   105         this.systemHeaders.setHeader("User-Agent", USER_AGENT);
       
   106         this.uri = request.uri();
       
   107         if (isWebSocket) {
       
   108             // WebSocket determines and sets the proxy itself
       
   109             this.proxy = ((HttpRequestImpl) request).proxy;
       
   110         } else {
       
   111             if (ps != null)
       
   112                 this.proxy = retrieveProxy(ps, uri);
       
   113             else
       
   114                 this.proxy = null;
       
   115         }
       
   116         this.expectContinue = request.expectContinue();
       
   117         this.secure = uri.getScheme().toLowerCase(Locale.US).equals("https");
       
   118         this.requestPublisher = request.bodyPublisher().orElse(null);
       
   119         if (acc != null && requestPublisher instanceof RequestPublishers.FilePublisher) {
       
   120             // Restricts the file publisher with the senders ACC, if any
       
   121             ((RequestPublishers.FilePublisher)requestPublisher).setAccessControlContext(acc);
       
   122         }
       
   123         this.timeout = request.timeout().orElse(null);
       
   124         this.version = request.version();
       
   125         this.authority = null;
       
   126     }
       
   127 
       
   128     /** Creates a HttpRequestImpl using fields of an existing request impl. */
       
   129     public HttpRequestImpl(URI uri,
       
   130                            String method,
       
   131                            HttpRequestImpl other) {
       
   132         this.method = method == null? "GET" : method;
       
   133         this.userHeaders = other.userHeaders;
       
   134         this.isWebSocket = other.isWebSocket;
       
   135         this.systemHeaders = other.systemHeaders;
       
   136         this.uri = uri;
       
   137         this.proxy = other.proxy;
       
   138         this.expectContinue = other.expectContinue;
       
   139         this.secure = uri.getScheme().toLowerCase(Locale.US).equals("https");
       
   140         this.requestPublisher = other.requestPublisher;  // may be null
       
   141         this.acc = other.acc;
       
   142         this.timeout = other.timeout;
       
   143         this.version = other.version();
       
   144         this.authority = null;
       
   145     }
       
   146 
       
   147     /* used for creating CONNECT requests  */
       
   148     HttpRequestImpl(String method, InetSocketAddress authority, HttpHeaders headers) {
       
   149         // TODO: isWebSocket flag is not specified, but the assumption is that
       
   150         // such a request will never be made on a connection that will be returned
       
   151         // to the connection pool (we might need to revisit this constructor later)
       
   152         assert "CONNECT".equalsIgnoreCase(method);
       
   153         this.method = method;
       
   154         this.systemHeaders = new HttpHeadersImpl();
       
   155         this.userHeaders = ImmutableHeaders.of(headers);
       
   156         this.uri = URI.create("socket://" + authority.getHostString() + ":"
       
   157                               + Integer.toString(authority.getPort()) + "/");
       
   158         this.proxy = null;
       
   159         this.requestPublisher = null;
       
   160         this.authority = authority;
       
   161         this.secure = false;
       
   162         this.expectContinue = false;
       
   163         this.timeout = null;
       
   164         // The CONNECT request sent for tunneling is only used in two cases:
       
   165         //   1. websocket, which only supports HTTP/1.1
       
   166         //   2. SSL tunneling through a HTTP/1.1 proxy
       
   167         // In either case we do not want to upgrade the connection to the proxy.
       
   168         // What we want to possibly upgrade is the tunneled connection to the
       
   169         // target server (so not the CONNECT request itself)
       
   170         this.version = Optional.of(HttpClient.Version.HTTP_1_1);
       
   171     }
       
   172 
       
   173     final boolean isConnect() {
       
   174         return "CONNECT".equalsIgnoreCase(method);
       
   175     }
       
   176 
       
   177     /**
       
   178      * Creates a HttpRequestImpl from the given set of Headers and the associated
       
   179      * "parent" request. Fields not taken from the headers are taken from the
       
   180      * parent.
       
   181      */
       
   182     static HttpRequestImpl createPushRequest(HttpRequestImpl parent,
       
   183                                              HttpHeadersImpl headers)
       
   184         throws IOException
       
   185     {
       
   186         return new HttpRequestImpl(parent, headers);
       
   187     }
       
   188 
       
   189     // only used for push requests
       
   190     private HttpRequestImpl(HttpRequestImpl parent, HttpHeadersImpl headers)
       
   191         throws IOException
       
   192     {
       
   193         this.method = headers.firstValue(":method")
       
   194                 .orElseThrow(() -> new IOException("No method in Push Promise"));
       
   195         String path = headers.firstValue(":path")
       
   196                 .orElseThrow(() -> new IOException("No path in Push Promise"));
       
   197         String scheme = headers.firstValue(":scheme")
       
   198                 .orElseThrow(() -> new IOException("No scheme in Push Promise"));
       
   199         String authority = headers.firstValue(":authority")
       
   200                 .orElseThrow(() -> new IOException("No authority in Push Promise"));
       
   201         StringBuilder sb = new StringBuilder();
       
   202         sb.append(scheme).append("://").append(authority).append(path);
       
   203         this.uri = URI.create(sb.toString());
       
   204         this.proxy = null;
       
   205         this.userHeaders = ImmutableHeaders.of(headers.map(), ALLOWED_HEADERS);
       
   206         this.systemHeaders = parent.systemHeaders;
       
   207         this.expectContinue = parent.expectContinue;
       
   208         this.secure = parent.secure;
       
   209         this.requestPublisher = parent.requestPublisher;
       
   210         this.acc = parent.acc;
       
   211         this.timeout = parent.timeout;
       
   212         this.version = parent.version;
       
   213         this.authority = null;
       
   214     }
       
   215 
       
   216     @Override
       
   217     public String toString() {
       
   218         return (uri == null ? "" : uri.toString()) + " " + method;
       
   219     }
       
   220 
       
   221     @Override
       
   222     public HttpHeaders headers() {
       
   223         return userHeaders;
       
   224     }
       
   225 
       
   226     InetSocketAddress authority() { return authority; }
       
   227 
       
   228     void setH2Upgrade(Http2ClientImpl h2client) {
       
   229         systemHeaders.setHeader("Connection", "Upgrade, HTTP2-Settings");
       
   230         systemHeaders.setHeader("Upgrade", "h2c");
       
   231         systemHeaders.setHeader("HTTP2-Settings", h2client.getSettingsString());
       
   232     }
       
   233 
       
   234     @Override
       
   235     public boolean expectContinue() { return expectContinue; }
       
   236 
       
   237     /** Retrieves the proxy, from the given ProxySelector, if there is one. */
       
   238     private static Proxy retrieveProxy(ProxySelector ps, URI uri) {
       
   239         Proxy proxy = null;
       
   240         List<Proxy> pl = ps.select(uri);
       
   241         if (!pl.isEmpty()) {
       
   242             Proxy p = pl.get(0);
       
   243             if (p.type() == Proxy.Type.HTTP)
       
   244                 proxy = p;
       
   245         }
       
   246         return proxy;
       
   247     }
       
   248 
       
   249     InetSocketAddress proxy() {
       
   250         if (proxy == null || proxy.type() != Proxy.Type.HTTP
       
   251                 || method.equalsIgnoreCase("CONNECT")) {
       
   252             return null;
       
   253         }
       
   254         return (InetSocketAddress)proxy.address();
       
   255     }
       
   256 
       
   257     boolean secure() { return secure; }
       
   258 
       
   259     @Override
       
   260     public void setProxy(Proxy proxy) {
       
   261         assert isWebSocket;
       
   262         this.proxy = proxy;
       
   263     }
       
   264 
       
   265     @Override
       
   266     public void isWebSocket(boolean is) {
       
   267         isWebSocket = is;
       
   268     }
       
   269 
       
   270     boolean isWebSocket() {
       
   271         return isWebSocket;
       
   272     }
       
   273 
       
   274     @Override
       
   275     public Optional<BodyPublisher> bodyPublisher() {
       
   276         return requestPublisher == null ? Optional.empty()
       
   277                                         : Optional.of(requestPublisher);
       
   278     }
       
   279 
       
   280     /**
       
   281      * Returns the request method for this request. If not set explicitly,
       
   282      * the default method for any request is "GET".
       
   283      */
       
   284     @Override
       
   285     public String method() { return method; }
       
   286 
       
   287     @Override
       
   288     public URI uri() { return uri; }
       
   289 
       
   290     @Override
       
   291     public Optional<Duration> timeout() {
       
   292         return timeout == null ? Optional.empty() : Optional.of(timeout);
       
   293     }
       
   294 
       
   295     HttpHeaders getUserHeaders() { return userHeaders; }
       
   296 
       
   297     HttpHeadersImpl getSystemHeaders() { return systemHeaders; }
       
   298 
       
   299     @Override
       
   300     public Optional<HttpClient.Version> version() { return version; }
       
   301 
       
   302     void addSystemHeader(String name, String value) {
       
   303         systemHeaders.addHeader(name, value);
       
   304     }
       
   305 
       
   306     @Override
       
   307     public void setSystemHeader(String name, String value) {
       
   308         systemHeaders.setHeader(name, value);
       
   309     }
       
   310 
       
   311     InetSocketAddress getAddress() {
       
   312         URI uri = uri();
       
   313         if (uri == null) {
       
   314             return authority();
       
   315         }
       
   316         int p = uri.getPort();
       
   317         if (p == -1) {
       
   318             if (uri.getScheme().equalsIgnoreCase("https")) {
       
   319                 p = 443;
       
   320             } else {
       
   321                 p = 80;
       
   322             }
       
   323         }
       
   324         final String host = uri.getHost();
       
   325         final int port = p;
       
   326         if (proxy() == null) {
       
   327             PrivilegedAction<InetSocketAddress> pa = () -> new InetSocketAddress(host, port);
       
   328             return AccessController.doPrivileged(pa);
       
   329         } else {
       
   330             return InetSocketAddress.createUnresolved(host, port);
       
   331         }
       
   332     }
       
   333 }