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.HttpHeaders;
34 import org.apache.http.HttpRequest;
35 import org.apache.http.HttpResponse;
36 import org.apache.http.HttpStatus;
37 import org.apache.http.HttpVersion;
38 import org.apache.http.ParseException;
39 import org.apache.http.ProtocolVersion;
40 import org.apache.http.TokenIterator;
41 import org.apache.http.annotation.Contract;
42 import org.apache.http.annotation.ThreadingBehavior;
43 import org.apache.http.message.BasicTokenIterator;
44 import org.apache.http.protocol.HTTP;
45 import org.apache.http.protocol.HttpContext;
46 import org.apache.http.protocol.HttpCoreContext;
47 import org.apache.http.util.Args;
48
49 /**
50  * Default implementation of a strategy deciding about connection re-use.
51  * The default implementation first checks some basics, for example
52  * whether the connection is still open or whether the end of the
53  * request entity can be determined without closing the connection.
54  * If these checks pass, the tokens in the {@code Connection} header will
55  * be examined. In the absence of a {@code Connection} header, the
56  * non-standard but commonly used {@code Proxy-Connection} header takes
57  * it's role. A token {@code close} indicates that the connection cannot
58  * be reused. If there is no such token, a token {@code keep-alive}
59  * indicates that the connection should be re-used. If neither token is found,
60  * or if there are no {@code Connection} headers, the default policy for
61  * the HTTP version is applied. Since {@code HTTP/1.1}, connections are
62  * re-used by default. Up until {@code HTTP/1.0}, connections are not
63  * re-used by default.
64  *
65  * @since 4.0
66  */

67 @Contract(threading = ThreadingBehavior.IMMUTABLE)
68 public class DefaultConnectionReuseStrategy implements ConnectionReuseStrategy {
69
70     public static final DefaultConnectionReuseStrategy INSTANCE = new DefaultConnectionReuseStrategy();
71
72     public DefaultConnectionReuseStrategy() {
73         super();
74     }
75
76     // see interface ConnectionReuseStrategy
77     @Override
78     public boolean keepAlive(final HttpResponse response,
79                              final HttpContext context) {
80         Args.notNull(response, "HTTP response");
81         Args.notNull(context, "HTTP context");
82
83         // If a HTTP 204 No Content response contains a Content-length with value > 0 or Transfer-Encoding,
84         // don't reuse the connection. This is to avoid getting out-of-sync if a misbehaved HTTP server
85         // returns content as part of a HTTP 204 response.
86         if (response.getStatusLine().getStatusCode() == HttpStatus.SC_NO_CONTENT) {
87             final Header clh = response.getFirstHeader(HTTP.CONTENT_LEN);
88             if (clh != null) {
89                 try {
90                     final int contentLen = Integer.parseInt(clh.getValue());
91                     if (contentLen > 0) {
92                         return false;
93                     }
94                 } catch (final NumberFormatException ex) {
95                     // fall through
96                 }
97             }
98
99             final Header teh = response.getFirstHeader(HTTP.TRANSFER_ENCODING);
100             if (teh != null) {
101                 return false;
102             }
103         }
104
105         final HttpRequest request = (HttpRequest) context.getAttribute(HttpCoreContext.HTTP_REQUEST);
106         if (request != null) {
107             try {
108                 final TokenIterator ti = new BasicTokenIterator(request.headerIterator(HttpHeaders.CONNECTION));
109                 while (ti.hasNext()) {
110                     final String token = ti.nextToken();
111                     if (HTTP.CONN_CLOSE.equalsIgnoreCase(token)) {
112                         return false;
113                     }
114                 }
115             } catch (final ParseException px) {
116                 // invalid connection header. do not re-use
117                 return false;
118             }
119         }
120
121         // Check for a self-terminating entity. If the end of the entity will
122         // be indicated by closing the connection, there is no keep-alive.
123         final ProtocolVersion ver = response.getStatusLine().getProtocolVersion();
124         final Header teh = response.getFirstHeader(HTTP.TRANSFER_ENCODING);
125         if (teh != null) {
126             if (!HTTP.CHUNK_CODING.equalsIgnoreCase(teh.getValue())) {
127                 return false;
128             }
129         } else {
130             if (canResponseHaveBody(request, response)) {
131                 final Header[] clhs = response.getHeaders(HTTP.CONTENT_LEN);
132                 // Do not reuse if not properly content-length delimited
133                 if (clhs.length == 1) {
134                     final Header clh = clhs[0];
135                     try {
136                         final long contentLen = Long.parseLong(clh.getValue());
137                         if (contentLen < 0) {
138                             return false;
139                         }
140                     } catch (final NumberFormatException ex) {
141                         return false;
142                     }
143                 } else {
144                     return false;
145                 }
146             }
147         }
148
149         // Check for the "Connection" header. If that is absent, check for
150         // the "Proxy-Connection" header. The latter is an unspecified and
151         // broken but unfortunately common extension of HTTP.
152         HeaderIterator headerIterator = response.headerIterator(HTTP.CONN_DIRECTIVE);
153         if (!headerIterator.hasNext()) {
154             headerIterator = response.headerIterator("Proxy-Connection");
155         }
156
157         // Experimental usage of the "Connection" header in HTTP/1.0 is
158         // documented in RFC 2068, section 19.7.1. A token "keep-alive" is
159         // used to indicate that the connection should be persistent.
160         // Note that the final specification of HTTP/1.1 in RFC 2616 does not
161         // include this information. Neither is the "Connection" header
162         // mentioned in RFC 1945, which informally describes HTTP/1.0.
163         //
164         // RFC 2616 specifies "close" as the only connection token with a
165         // specific meaning: it disables persistent connections.
166         //
167         // The "Proxy-Connection" header is not formally specified anywhere,
168         // but is commonly used to carry one token, "close" or "keep-alive".
169         // The "Connection" header, on the other hand, is defined as a
170         // sequence of tokens, where each token is a header name, and the
171         // token "close" has the above-mentioned additional meaning.
172         //
173         // To get through this mess, we treat the "Proxy-Connection" header
174         // in exactly the same way as the "Connection" header, but only if
175         // the latter is missing. We scan the sequence of tokens for both
176         // "close" and "keep-alive". As "close" is specified by RFC 2068,
177         // it takes precedence and indicates a non-persistent connection.
178         // If there is no "close" but a "keep-alive", we take the hint.
179
180         if (headerIterator.hasNext()) {
181             try {
182                 final TokenIterator ti = new BasicTokenIterator(headerIterator);
183                 boolean keepalive = false;
184                 while (ti.hasNext()) {
185                     final String token = ti.nextToken();
186                     if (HTTP.CONN_CLOSE.equalsIgnoreCase(token)) {
187                         return false;
188                     } else if (HTTP.CONN_KEEP_ALIVE.equalsIgnoreCase(token)) {
189                         // continue the loop, there may be a "close" afterwards
190                         keepalive = true;
191                     }
192                 }
193                 if (keepalive) {
194                     return true;
195                 // neither "close" nor "keep-alive", use default policy
196                 }
197
198             } catch (final ParseException px) {
199                 // invalid connection header. do not re-use
200                 return false;
201             }
202         }
203
204         // default since HTTP/1.1 is persistent, before it was non-persistent
205         return !ver.lessEquals(HttpVersion.HTTP_1_0);
206     }
207
208
209     /**
210      * Creates a token iterator from a header iterator.
211      * This method can be overridden to replace the implementation of
212      * the token iterator.
213      *
214      * @param hit       the header iterator
215      *
216      * @return  the token iterator
217      */

218     protected TokenIterator createTokenIterator(final HeaderIterator hit) {
219         return new BasicTokenIterator(hit);
220     }
221
222     private boolean canResponseHaveBody(final HttpRequest request, final HttpResponse response) {
223         if (request != null && request.getRequestLine().getMethod().equalsIgnoreCase("HEAD")) {
224             return false;
225         }
226         final int status = response.getStatusLine().getStatusCode();
227         return status >= HttpStatus.SC_OK
228             && status != HttpStatus.SC_NO_CONTENT
229             && status != HttpStatus.SC_NOT_MODIFIED
230             && status != HttpStatus.SC_RESET_CONTENT;
231     }
232
233 }
234