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