View Javadoc
1   /*
2    * ====================================================================
3    * Licensed to the Apache Software Foundation (ASF) under one
4    * or more contributor license agreements.  See the NOTICE file
5    * distributed with this work for additional information
6    * regarding copyright ownership.  The ASF licenses this file
7    * to you under the Apache License, Version 2.0 (the
8    * "License"); you may not use this file except in compliance
9    * with the License.  You may obtain a copy of the License at
10   *
11   *   http://www.apache.org/licenses/LICENSE-2.0
12   *
13   * Unless required by applicable law or agreed to in writing,
14   * software distributed under the License is distributed on an
15   * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
16   * KIND, either express or implied.  See the License for the
17   * specific language governing permissions and limitations
18   * under the License.
19   * ====================================================================
20   *
21   * This software consists of voluntary contributions made by many
22   * individuals on behalf of the Apache Software Foundation.  For more
23   * information on the Apache Software Foundation, please see
24   * <http://www.apache.org/>.
25   *
26   */
27  
28  package org.apache.hc.core5.http.impl;
29  
30  import java.util.Iterator;
31  
32  import org.apache.hc.core5.annotation.Contract;
33  import org.apache.hc.core5.annotation.ThreadingBehavior;
34  import org.apache.hc.core5.http.ConnectionReuseStrategy;
35  import org.apache.hc.core5.http.Header;
36  import org.apache.hc.core5.http.HeaderElements;
37  import org.apache.hc.core5.http.HttpHeaders;
38  import org.apache.hc.core5.http.HttpRequest;
39  import org.apache.hc.core5.http.HttpResponse;
40  import org.apache.hc.core5.http.HttpStatus;
41  import org.apache.hc.core5.http.HttpVersion;
42  import org.apache.hc.core5.http.ProtocolVersion;
43  import org.apache.hc.core5.http.message.BasicTokenIterator;
44  import org.apache.hc.core5.http.message.MessageSupport;
45  import org.apache.hc.core5.http.protocol.HttpContext;
46  import org.apache.hc.core5.util.Args;
47  
48  /**
49   * Default implementation of a strategy deciding about connection re-use. The strategy
50   * determines whether a connection is persistent or not based on the message’s protocol
51   * version and {@code Connection} header field if present. Connections will not be
52   * re-used and will close if any of these conditions is met
53   * <ul>
54   *     <li>the {@code close} connection option is present in the request message</li>
55   *     <li>the response message content body is incorrectly or ambiguously delineated</li>
56   *     <li>the {@code close} connection option is present in the response message</li>
57   *     <li>If the received protocol is {@code HTTP/1.0} (or earlier) and {@code keep-alive}
58   *     connection option is not present</li>
59   * </ul>
60   * In the absence of a {@code Connection} header field, the non-standard but commonly used
61   * {@code Proxy-Connection} header field will be used instead. If no connection options are
62   * explicitly given the default policy for the HTTP version is applied. {@code HTTP/1.1}
63   * (or later) connections are re-used by default. {@code HTTP/1.0} (or earlier) connections
64   * are not re-used by default.
65   *
66   * @since 4.0
67   */
68  @Contract(threading = ThreadingBehavior.IMMUTABLE)
69  public class DefaultConnectionReuseStrategy implements ConnectionReuseStrategy {
70  
71      public static final DefaultConnectionReuseStrategy INSTANCE = new DefaultConnectionReuseStrategy();
72  
73      public DefaultConnectionReuseStrategy() {
74          super();
75      }
76  
77      // see interface ConnectionReuseStrategy
78      @Override
79      public boolean keepAlive(
80              final HttpRequest request, final HttpResponse response, final HttpContext context) {
81          Args.notNull(response, "HTTP response");
82  
83          if (request != null) {
84              final Iterator<String> ti = new BasicTokenIterator(request.headerIterator(HttpHeaders.CONNECTION));
85              while (ti.hasNext()) {
86                  final String token = ti.next();
87                  if (HeaderElements.CLOSE.equalsIgnoreCase(token)) {
88                      return false;
89                  }
90              }
91          }
92  
93          // If a HTTP 204 No Content response contains a Content-length with value > 0 or Transfer-Encoding header,
94          // don't reuse the connection. This is to avoid getting out-of-sync if a misbehaved HTTP server
95          // returns content as part of a HTTP 204 response.
96          if (response.getCode() == HttpStatus.SC_NO_CONTENT) {
97              final Header clh = response.getFirstHeader(HttpHeaders.CONTENT_LENGTH);
98              if (clh != null) {
99                  try {
100                     final int contentLen = Integer.parseInt(clh.getValue());
101                     if (contentLen > 0) {
102                         return false;
103                     }
104                 } catch (final NumberFormatException ex) {
105                     // fall through
106                 }
107             }
108             if (response.containsHeader(HttpHeaders.TRANSFER_ENCODING)) {
109                 return false;
110             }
111         }
112 
113         // Check for a self-terminating entity. If the end of the entity will
114         // be indicated by closing the connection, there is no keep-alive.
115         final Header teh = response.getFirstHeader(HttpHeaders.TRANSFER_ENCODING);
116         if (teh != null) {
117             if (!HeaderElements.CHUNKED_ENCODING.equalsIgnoreCase(teh.getValue())) {
118                 return false;
119             }
120         } else {
121             final String method = request != null ? request.getMethod() : null;
122             if (MessageSupport.canResponseHaveBody(method, response)
123                     && response.containsHeaders(HttpHeaders.CONTENT_LENGTH) != 1) {
124                 return false;
125             }
126         }
127 
128         // Check for the "Connection" header. If that is absent, check for
129         // the "Proxy-Connection" header. The latter is an unspecified and
130         // broken but unfortunately common extension of HTTP.
131         Iterator<Header> headerIterator = response.headerIterator(HttpHeaders.CONNECTION);
132         if (!headerIterator.hasNext()) {
133             headerIterator = response.headerIterator("Proxy-Connection");
134         }
135 
136         final ProtocolVersion ver = context.getProtocolVersion();
137         if (headerIterator.hasNext()) {
138             if (ver.greaterEquals(HttpVersion.HTTP_1_1)) {
139                 final Iterator<String> it = new BasicTokenIterator(headerIterator);
140                 while (it.hasNext()) {
141                     final String token = it.next();
142                     if (HeaderElements.CLOSE.equalsIgnoreCase(token)) {
143                         return false;
144                     }
145                 }
146                 return true;
147             }
148             final Iterator<String> it = new BasicTokenIterator(headerIterator);
149             while (it.hasNext()) {
150                 final String token = it.next();
151                 if (HeaderElements.KEEP_ALIVE.equalsIgnoreCase(token)) {
152                     return true;
153                 }
154             }
155             return false;
156         }
157         return ver.greaterEquals(HttpVersion.HTTP_1_1);
158     }
159 
160 }