1/*
2 * $HeadURL: http://svn.apache.org/repos/asf/httpcomponents/httpcore/trunk/module-main/src/main/java/org/apache/http/impl/DefaultConnectionReuseStrategy.java $
3 * $Revision: 602537 $
4 * $Date: 2007-12-08 11:42:06 -0800 (Sat, 08 Dec 2007) $
5 *
6 * ====================================================================
7 * Licensed to the Apache Software Foundation (ASF) under one
8 * or more contributor license agreements.  See the NOTICE file
9 * distributed with this work for additional information
10 * regarding copyright ownership.  The ASF licenses this file
11 * to you under the Apache License, Version 2.0 (the
12 * "License"); you may not use this file except in compliance
13 * with the License.  You may obtain a copy of the License at
14 *
15 *   http://www.apache.org/licenses/LICENSE-2.0
16 *
17 * Unless required by applicable law or agreed to in writing,
18 * software distributed under the License is distributed on an
19 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
20 * KIND, either express or implied.  See the License for the
21 * specific language governing permissions and limitations
22 * under the License.
23 * ====================================================================
24 *
25 * This software consists of voluntary contributions made by many
26 * individuals on behalf of the Apache Software Foundation.  For more
27 * information on the Apache Software Foundation, please see
28 * <http://www.apache.org/>.
29 *
30 */
31
32package org.apache.http.impl;
33
34import org.apache.http.ConnectionReuseStrategy;
35import org.apache.http.HttpConnection;
36import org.apache.http.HeaderIterator;
37import org.apache.http.HttpEntity;
38import org.apache.http.HttpResponse;
39import org.apache.http.HttpVersion;
40import org.apache.http.ParseException;
41import org.apache.http.ProtocolVersion;
42import org.apache.http.protocol.HTTP;
43import org.apache.http.protocol.HttpContext;
44import org.apache.http.protocol.ExecutionContext;
45import org.apache.http.TokenIterator;
46import org.apache.http.message.BasicTokenIterator;
47
48/**
49 * Default implementation of a strategy deciding about connection re-use.
50 * The default implementation first checks some basics, for example
51 * whether the connection is still open or whether the end of the
52 * request entity can be determined without closing the connection.
53 * If these checks pass, the tokens in the "Connection" header will
54 * be examined. In the absence of a "Connection" header, the
55 * non-standard but commonly used "Proxy-Connection" header takes
56 * it's role. A token "close" indicates that the connection cannot
57 * be reused. If there is no such token, a token "keep-alive" indicates
58 * that the connection should be re-used. If neither token is found,
59 * or if there are no "Connection" headers, the default policy for
60 * the HTTP version is applied. Since HTTP/1.1, connections are re-used
61 * by default. Up until HTTP/1.0, connections are not re-used by default.
62 *
63 * @author <a href="mailto:oleg at ural.ru">Oleg Kalnichevski</a>
64 * @author <a href="mailto:rolandw at apache.org">Roland Weber</a>
65 *
66 * @version $Revision: 602537 $
67 *
68 * @since 4.0
69 */
70public class DefaultConnectionReuseStrategy
71    implements ConnectionReuseStrategy {
72
73    public DefaultConnectionReuseStrategy() {
74        super();
75    }
76
77    // see interface ConnectionReuseStrategy
78    public boolean keepAlive(final HttpResponse response,
79                             final HttpContext context) {
80        if (response == null) {
81            throw new IllegalArgumentException
82                ("HTTP response may not be null.");
83        }
84        if (context == null) {
85            throw new IllegalArgumentException
86                ("HTTP context may not be null.");
87        }
88
89        HttpConnection conn = (HttpConnection)
90            context.getAttribute(ExecutionContext.HTTP_CONNECTION);
91
92        if (conn != null && !conn.isOpen())
93            return false;
94        // do NOT check for stale connection, that is an expensive operation
95
96        // Check for a self-terminating entity. If the end of the entity will
97        // be indicated by closing the connection, there is no keep-alive.
98        HttpEntity entity = response.getEntity();
99        ProtocolVersion ver = response.getStatusLine().getProtocolVersion();
100        if (entity != null) {
101            if (entity.getContentLength() < 0) {
102                if (!entity.isChunked() ||
103                    ver.lessEquals(HttpVersion.HTTP_1_0)) {
104                    // if the content length is not known and is not chunk
105                    // encoded, the connection cannot be reused
106                    return false;
107                }
108            }
109        }
110
111        // Check for the "Connection" header. If that is absent, check for
112        // the "Proxy-Connection" header. The latter is an unspecified and
113        // broken but unfortunately common extension of HTTP.
114        HeaderIterator hit = response.headerIterator(HTTP.CONN_DIRECTIVE);
115        if (!hit.hasNext())
116            hit = response.headerIterator("Proxy-Connection");
117
118        // Experimental usage of the "Connection" header in HTTP/1.0 is
119        // documented in RFC 2068, section 19.7.1. A token "keep-alive" is
120        // used to indicate that the connection should be persistent.
121        // Note that the final specification of HTTP/1.1 in RFC 2616 does not
122        // include this information. Neither is the "Connection" header
123        // mentioned in RFC 1945, which informally describes HTTP/1.0.
124        //
125        // RFC 2616 specifies "close" as the only connection token with a
126        // specific meaning: it disables persistent connections.
127        //
128        // The "Proxy-Connection" header is not formally specified anywhere,
129        // but is commonly used to carry one token, "close" or "keep-alive".
130        // The "Connection" header, on the other hand, is defined as a
131        // sequence of tokens, where each token is a header name, and the
132        // token "close" has the above-mentioned additional meaning.
133        //
134        // To get through this mess, we treat the "Proxy-Connection" header
135        // in exactly the same way as the "Connection" header, but only if
136        // the latter is missing. We scan the sequence of tokens for both
137        // "close" and "keep-alive". As "close" is specified by RFC 2068,
138        // it takes precedence and indicates a non-persistent connection.
139        // If there is no "close" but a "keep-alive", we take the hint.
140
141        if (hit.hasNext()) {
142            try {
143                TokenIterator ti = createTokenIterator(hit);
144                boolean keepalive = false;
145                while (ti.hasNext()) {
146                    final String token = ti.nextToken();
147                    if (HTTP.CONN_CLOSE.equalsIgnoreCase(token)) {
148                        return false;
149                    } else if (HTTP.CONN_KEEP_ALIVE.equalsIgnoreCase(token)) {
150                        // continue the loop, there may be a "close" afterwards
151                        keepalive = true;
152                    }
153                }
154                if (keepalive)
155                    return true;
156                // neither "close" nor "keep-alive", use default policy
157
158            } catch (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(HeaderIterator hit) {
180        return new BasicTokenIterator(hit);
181    }
182}
183