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.client.protocol;
29  
30  import java.io.IOException;
31  import java.net.URI;
32  import java.net.URISyntaxException;
33  import java.util.ArrayList;
34  import java.util.Date;
35  import java.util.List;
36  
37  import org.apache.commons.logging.Log;
38  import org.apache.commons.logging.LogFactory;
39  import org.apache.http.Header;
40  import org.apache.http.HttpException;
41  import org.apache.http.HttpHost;
42  import org.apache.http.HttpRequest;
43  import org.apache.http.HttpRequestInterceptor;
44  import org.apache.http.annotation.Immutable;
45  import org.apache.http.client.CookieStore;
46  import org.apache.http.client.config.CookieSpecs;
47  import org.apache.http.client.config.RequestConfig;
48  import org.apache.http.client.methods.HttpUriRequest;
49  import org.apache.http.config.Lookup;
50  import org.apache.http.conn.routing.RouteInfo;
51  import org.apache.http.cookie.Cookie;
52  import org.apache.http.cookie.CookieOrigin;
53  import org.apache.http.cookie.CookieSpec;
54  import org.apache.http.cookie.CookieSpecProvider;
55  import org.apache.http.protocol.HttpContext;
56  import org.apache.http.util.Args;
57  import org.apache.http.util.TextUtils;
58  
59  /**
60   * Request interceptor that matches cookies available in the current
61   * {@link CookieStore} to the request being executed and generates
62   * corresponding {@code Cookie} request headers.
63   *
64   * @since 4.0
65   */
66  @Immutable
67  public class RequestAddCookies implements HttpRequestInterceptor {
68  
69      private final Log log = LogFactory.getLog(getClass());
70  
71      public RequestAddCookies() {
72          super();
73      }
74  
75      @Override
76      public void process(final HttpRequest request, final HttpContext context)
77              throws HttpException, IOException {
78          Args.notNull(request, "HTTP request");
79          Args.notNull(context, "HTTP context");
80  
81          final String method = request.getRequestLine().getMethod();
82          if (method.equalsIgnoreCase("CONNECT")) {
83              return;
84          }
85  
86          final HttpClientContext clientContext = HttpClientContext.adapt(context);
87  
88          // Obtain cookie store
89          final CookieStore cookieStore = clientContext.getCookieStore();
90          if (cookieStore == null) {
91              this.log.debug("Cookie store not specified in HTTP context");
92              return;
93          }
94  
95          // Obtain the registry of cookie specs
96          final Lookup<CookieSpecProvider> registry = clientContext.getCookieSpecRegistry();
97          if (registry == null) {
98              this.log.debug("CookieSpec registry not specified in HTTP context");
99              return;
100         }
101 
102         // Obtain the target host, possibly virtual (required)
103         final HttpHost targetHost = clientContext.getTargetHost();
104         if (targetHost == null) {
105             this.log.debug("Target host not set in the context");
106             return;
107         }
108 
109         // Obtain the route (required)
110         final RouteInfo route = clientContext.getHttpRoute();
111         if (route == null) {
112             this.log.debug("Connection route not set in the context");
113             return;
114         }
115 
116         final RequestConfig config = clientContext.getRequestConfig();
117         String policy = config.getCookieSpec();
118         if (policy == null) {
119             policy = CookieSpecs.DEFAULT;
120         }
121         if (this.log.isDebugEnabled()) {
122             this.log.debug("CookieSpec selected: " + policy);
123         }
124 
125         URI requestURI = null;
126         if (request instanceof HttpUriRequest) {
127             requestURI = ((HttpUriRequest) request).getURI();
128         } else {
129             try {
130                 requestURI = new URI(request.getRequestLine().getUri());
131             } catch (final URISyntaxException ignore) {
132             }
133         }
134         final String path = requestURI != null ? requestURI.getPath() : null;
135         final String hostName = targetHost.getHostName();
136         int port = targetHost.getPort();
137         if (port < 0) {
138             port = route.getTargetHost().getPort();
139         }
140 
141         final CookieOrigin cookieOrigin = new CookieOrigin(
142                 hostName,
143                 port >= 0 ? port : 0,
144                 !TextUtils.isEmpty(path) ? path : "/",
145                 route.isSecure());
146 
147         // Get an instance of the selected cookie policy
148         final CookieSpecProvider provider = registry.lookup(policy);
149         if (provider == null) {
150             if (this.log.isDebugEnabled()) {
151                 this.log.debug("Unsupported cookie policy: " + policy);
152             }
153 
154             return;
155         }
156         final CookieSpec cookieSpec = provider.create(clientContext);
157         // Get all cookies available in the HTTP state
158         final List<Cookie> cookies = cookieStore.getCookies();
159         // Find cookies matching the given origin
160         final List<Cookie> matchedCookies = new ArrayList<Cookie>();
161         final Date now = new Date();
162         boolean expired = false;
163         for (final Cookie cookie : cookies) {
164             if (!cookie.isExpired(now)) {
165                 if (cookieSpec.match(cookie, cookieOrigin)) {
166                     if (this.log.isDebugEnabled()) {
167                         this.log.debug("Cookie " + cookie + " match " + cookieOrigin);
168                     }
169                     matchedCookies.add(cookie);
170                 }
171             } else {
172                 if (this.log.isDebugEnabled()) {
173                     this.log.debug("Cookie " + cookie + " expired");
174                 }
175                 expired = true;
176             }
177         }
178         // Per RFC 6265, 5.3
179         // The user agent must evict all expired cookies if, at any time, an expired cookie
180         // exists in the cookie store
181         if (expired) {
182             cookieStore.clearExpired(now);
183         }
184         // Generate Cookie request headers
185         if (!matchedCookies.isEmpty()) {
186             final List<Header> headers = cookieSpec.formatCookies(matchedCookies);
187             for (final Header header : headers) {
188                 request.addHeader(header);
189             }
190         }
191 
192         final int ver = cookieSpec.getVersion();
193         if (ver > 0) {
194             final Header header = cookieSpec.getVersionHeader();
195             if (header != null) {
196                 // Advertise cookie version support
197                 request.addHeader(header);
198             }
199         }
200 
201         // Stick the CookieSpec and CookieOrigin instances to the HTTP context
202         // so they could be obtained by the response interceptor
203         context.setAttribute(HttpClientContext.COOKIE_SPEC, cookieSpec);
204         context.setAttribute(HttpClientContext.COOKIE_ORIGIN, cookieOrigin);
205     }
206 
207 }