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.http.impl;
29  
30  import org.apache.http.ConnectionReuseStrategy;
31  import org.apache.http.Header;
32  import org.apache.http.HeaderIterator;
33  import org.apache.http.HttpResponse;
34  import org.apache.http.HttpStatus;
35  import org.apache.http.HttpVersion;
36  import org.apache.http.ParseException;
37  import org.apache.http.ProtocolVersion;
38  import org.apache.http.TokenIterator;
39  import org.apache.http.annotation.ThreadingBehavior;
40  import org.apache.http.annotation.Contract;
41  import org.apache.http.message.BasicHeaderIterator;
42  import org.apache.http.message.BasicTokenIterator;
43  import org.apache.http.protocol.HTTP;
44  import org.apache.http.protocol.HttpContext;
45  import org.apache.http.util.Args;
46  
47  /**
48   * Default implementation of a strategy deciding about connection re-use.
49   * The default implementation first checks some basics, for example
50   * whether the connection is still open or whether the end of the
51   * request entity can be determined without closing the connection.
52   * If these checks pass, the tokens in the {@code Connection} header will
53   * be examined. In the absence of a {@code Connection} header, the
54   * non-standard but commonly used {@code Proxy-Connection} header takes
55   * it's role. A token {@code close} indicates that the connection cannot
56   * be reused. If there is no such token, a token {@code keep-alive}
57   * indicates that the connection should be re-used. If neither token is found,
58   * or if there are no {@code Connection} headers, the default policy for
59   * the HTTP version is applied. Since {@code HTTP/1.1}, connections are
60   * re-used by default. Up until {@code HTTP/1.0}, connections are not
61   * re-used by default.
62   *
63   * @since 4.0
64   */
65  @Contract(threading = ThreadingBehavior.IMMUTABLE)
66  public class DefaultConnectionReuseStrategy implements ConnectionReuseStrategy {
67  
68      public static final DefaultConnectionReuseStrategy INSTANCE = new DefaultConnectionReuseStrategy();
69  
70      public DefaultConnectionReuseStrategy() {
71          super();
72      }
73  
74      // see interface ConnectionReuseStrategy
75      @Override
76      public boolean keepAlive(final HttpResponse response,
77                               final HttpContext context) {
78          Args.notNull(response, "HTTP response");
79          Args.notNull(context, "HTTP context");
80  
81          // Check for a self-terminating entity. If the end of the entity will
82          // be indicated by closing the connection, there is no keep-alive.
83          final ProtocolVersion ver = response.getStatusLine().getProtocolVersion();
84          final Header teh = response.getFirstHeader(HTTP.TRANSFER_ENCODING);
85          if (teh != null) {
86              if (!HTTP.CHUNK_CODING.equalsIgnoreCase(teh.getValue())) {
87                  return false;
88              }
89          } else {
90              if (canResponseHaveBody(response)) {
91                  final Header[] clhs = response.getHeaders(HTTP.CONTENT_LEN);
92                  // Do not reuse if not properly content-length delimited
93                  if (clhs.length == 1) {
94                      final Header clh = clhs[0];
95                      try {
96                          final int contentLen = Integer.parseInt(clh.getValue());
97                          if (contentLen < 0) {
98                              return false;
99                          }
100                     } catch (final NumberFormatException ex) {
101                         return false;
102                     }
103                 } else {
104                     return false;
105                 }
106             }
107         }
108 
109         // Check for the "Connection" header. If that is absent, check for
110         // the "Proxy-Connection" header. The latter is an unspecified and
111         // broken but unfortunately common extension of HTTP.
112         Header[] connHeaders = response.getHeaders(HTTP.CONN_DIRECTIVE);
113         if (connHeaders.length == 0) {
114             connHeaders = response.getHeaders("Proxy-Connection");
115         }
116 
117         // Experimental usage of the "Connection" header in HTTP/1.0 is
118         // documented in RFC 2068, section 19.7.1. A token "keep-alive" is
119         // used to indicate that the connection should be persistent.
120         // Note that the final specification of HTTP/1.1 in RFC 2616 does not
121         // include this information. Neither is the "Connection" header
122         // mentioned in RFC 1945, which informally describes HTTP/1.0.
123         //
124         // RFC 2616 specifies "close" as the only connection token with a
125         // specific meaning: it disables persistent connections.
126         //
127         // The "Proxy-Connection" header is not formally specified anywhere,
128         // but is commonly used to carry one token, "close" or "keep-alive".
129         // The "Connection" header, on the other hand, is defined as a
130         // sequence of tokens, where each token is a header name, and the
131         // token "close" has the above-mentioned additional meaning.
132         //
133         // To get through this mess, we treat the "Proxy-Connection" header
134         // in exactly the same way as the "Connection" header, but only if
135         // the latter is missing. We scan the sequence of tokens for both
136         // "close" and "keep-alive". As "close" is specified by RFC 2068,
137         // it takes precedence and indicates a non-persistent connection.
138         // If there is no "close" but a "keep-alive", we take the hint.
139 
140         if (connHeaders.length != 0) {
141             try {
142                 final TokenIterator ti = new BasicTokenIterator(new BasicHeaderIterator(connHeaders, null));
143                 boolean keepalive = false;
144                 while (ti.hasNext()) {
145                     final String token = ti.nextToken();
146                     if (HTTP.CONN_CLOSE.equalsIgnoreCase(token)) {
147                         return false;
148                     } else if (HTTP.CONN_KEEP_ALIVE.equalsIgnoreCase(token)) {
149                         // continue the loop, there may be a "close" afterwards
150                         keepalive = true;
151                     }
152                 }
153                 if (keepalive) {
154                     return true;
155                 // neither "close" nor "keep-alive", use default policy
156                 }
157 
158             } catch (final ParseException px) {
159                 // invalid connection header means no persistent connection
160                 // we don't have logging in HttpCore, so the exception is lost
161                 return false;
162             }
163         }
164 
165         // default since HTTP/1.1 is persistent, before it was non-persistent
166         return !ver.lessEquals(HttpVersion.HTTP_1_0);
167     }
168 
169 
170     /**
171      * Creates a token iterator from a header iterator.
172      * This method can be overridden to replace the implementation of
173      * the token iterator.
174      *
175      * @param hit       the header iterator
176      *
177      * @return  the token iterator
178      */
179     protected TokenIterator createTokenIterator(final HeaderIterator hit) {
180         return new BasicTokenIterator(hit);
181     }
182 
183     private boolean canResponseHaveBody(final HttpResponse response) {
184         final int status = response.getStatusLine().getStatusCode();
185         return status >= HttpStatus.SC_OK
186             && status != HttpStatus.SC_NO_CONTENT
187             && status != HttpStatus.SC_NOT_MODIFIED
188             && status != HttpStatus.SC_RESET_CONTENT;
189     }
190 
191 }