2
|
1 |
/*
|
715
|
2 |
* Copyright 2005-2008 Sun Microsystems, Inc. All Rights Reserved.
|
2
|
3 |
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
|
|
4 |
*
|
|
5 |
* This code is free software; you can redistribute it and/or modify it
|
|
6 |
* under the terms of the GNU General Public License version 2 only, as
|
|
7 |
* published by the Free Software Foundation. Sun designates this
|
|
8 |
* particular file as subject to the "Classpath" exception as provided
|
|
9 |
* by Sun in the LICENSE file that accompanied this code.
|
|
10 |
*
|
|
11 |
* This code is distributed in the hope that it will be useful, but WITHOUT
|
|
12 |
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
|
|
13 |
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
|
|
14 |
* version 2 for more details (a copy is included in the LICENSE file that
|
|
15 |
* accompanied this code).
|
|
16 |
*
|
|
17 |
* You should have received a copy of the GNU General Public License version
|
|
18 |
* 2 along with this work; if not, write to the Free Software Foundation,
|
|
19 |
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
|
|
20 |
*
|
|
21 |
* Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
|
|
22 |
* CA 95054 USA or visit www.sun.com if you need additional information or
|
|
23 |
* have any questions.
|
|
24 |
*/
|
|
25 |
|
|
26 |
package java.net;
|
|
27 |
|
|
28 |
import java.util.Map;
|
|
29 |
import java.util.List;
|
|
30 |
import java.util.Collections;
|
|
31 |
import java.util.Comparator;
|
|
32 |
import java.io.IOException;
|
|
33 |
|
|
34 |
/**
|
|
35 |
* CookieManager provides a concrete implementation of {@link CookieHandler},
|
|
36 |
* which separates the storage of cookies from the policy surrounding accepting
|
|
37 |
* and rejecting cookies. A CookieManager is initialized with a {@link CookieStore}
|
|
38 |
* which manages storage, and a {@link CookiePolicy} object, which makes
|
|
39 |
* policy decisions on cookie acceptance/rejection.
|
|
40 |
*
|
|
41 |
* <p> The HTTP cookie management in java.net package looks like:
|
|
42 |
* <blockquote>
|
|
43 |
* <pre>
|
|
44 |
* use
|
|
45 |
* CookieHandler <------- HttpURLConnection
|
|
46 |
* ^
|
|
47 |
* | impl
|
|
48 |
* | use
|
|
49 |
* CookieManager -------> CookiePolicy
|
|
50 |
* | use
|
|
51 |
* |--------> HttpCookie
|
|
52 |
* | ^
|
|
53 |
* | | use
|
|
54 |
* | use |
|
|
55 |
* |--------> CookieStore
|
|
56 |
* ^
|
|
57 |
* | impl
|
|
58 |
* |
|
|
59 |
* Internal in-memory implementation
|
|
60 |
* </pre>
|
|
61 |
* <ul>
|
|
62 |
* <li>
|
|
63 |
* CookieHandler is at the core of cookie management. User can call
|
|
64 |
* CookieHandler.setDefault to set a concrete CookieHanlder implementation
|
|
65 |
* to be used.
|
|
66 |
* </li>
|
|
67 |
* <li>
|
|
68 |
* CookiePolicy.shouldAccept will be called by CookieManager.put to see whether
|
|
69 |
* or not one cookie should be accepted and put into cookie store. User can use
|
|
70 |
* any of three pre-defined CookiePolicy, namely ACCEPT_ALL, ACCEPT_NONE and
|
|
71 |
* ACCEPT_ORIGINAL_SERVER, or user can define his own CookiePolicy implementation
|
|
72 |
* and tell CookieManager to use it.
|
|
73 |
* </li>
|
|
74 |
* <li>
|
|
75 |
* CookieStore is the place where any accepted HTTP cookie is stored in.
|
|
76 |
* If not specified when created, a CookieManager instance will use an internal
|
|
77 |
* in-memory implementation. Or user can implements one and tell CookieManager
|
|
78 |
* to use it.
|
|
79 |
* </li>
|
|
80 |
* <li>
|
|
81 |
* Currently, only CookieStore.add(URI, HttpCookie) and CookieStore.get(URI)
|
|
82 |
* are used by CookieManager. Others are for completeness and might be needed
|
|
83 |
* by a more sophisticated CookieStore implementation, e.g. a NetscapeCookieSotre.
|
|
84 |
* </li>
|
|
85 |
* </ul>
|
|
86 |
* </blockquote>
|
|
87 |
*
|
|
88 |
* <p>There're various ways user can hook up his own HTTP cookie management behavior, e.g.
|
|
89 |
* <blockquote>
|
|
90 |
* <ul>
|
|
91 |
* <li>Use CookieHandler.setDefault to set a brand new {@link CookieHandler} implementation
|
|
92 |
* <li>Let CookieManager be the default {@link CookieHandler} implementation,
|
|
93 |
* but implement user's own {@link CookieStore} and {@link CookiePolicy}
|
|
94 |
* and tell default CookieManager to use them:
|
|
95 |
* <blockquote><pre>
|
|
96 |
* // this should be done at the beginning of an HTTP session
|
|
97 |
* CookieHandler.setDefault(new CookieManager(new MyCookieStore(), new MyCookiePolicy()));
|
|
98 |
* </pre></blockquote>
|
|
99 |
* <li>Let CookieManager be the default {@link CookieHandler} implementation, but
|
|
100 |
* use customized {@link CookiePolicy}:
|
|
101 |
* <blockquote><pre>
|
|
102 |
* // this should be done at the beginning of an HTTP session
|
|
103 |
* CookieHandler.setDefault(new CookieManager());
|
|
104 |
* // this can be done at any point of an HTTP session
|
|
105 |
* ((CookieManager)CookieHandler.getDefault()).setCookiePolicy(new MyCookiePolicy());
|
|
106 |
* </pre></blockquote>
|
|
107 |
* </ul>
|
|
108 |
* </blockquote>
|
|
109 |
*
|
|
110 |
* <p>The implementation conforms to RFC 2965, section 3.3.
|
|
111 |
*
|
|
112 |
* @author Edward Wang
|
|
113 |
* @since 1.6
|
|
114 |
*/
|
|
115 |
public class CookieManager extends CookieHandler
|
|
116 |
{
|
|
117 |
/* ---------------- Fields -------------- */
|
|
118 |
|
|
119 |
private CookiePolicy policyCallback;
|
|
120 |
|
|
121 |
|
|
122 |
private CookieStore cookieJar = null;
|
|
123 |
|
|
124 |
|
|
125 |
/* ---------------- Ctors -------------- */
|
|
126 |
|
|
127 |
/**
|
|
128 |
* Create a new cookie manager.
|
|
129 |
*
|
|
130 |
* <p>This constructor will create new cookie manager with default
|
|
131 |
* cookie store and accept policy. The effect is same as
|
|
132 |
* <tt>CookieManager(null, null)</tt>.
|
|
133 |
*/
|
|
134 |
public CookieManager() {
|
|
135 |
this(null, null);
|
|
136 |
}
|
|
137 |
|
|
138 |
|
|
139 |
/**
|
|
140 |
* Create a new cookie manager with specified cookie store and cookie policy.
|
|
141 |
*
|
|
142 |
* @param store a <tt>CookieStore</tt> to be used by cookie manager.
|
|
143 |
* if <tt>null</tt>, cookie manager will use a default one,
|
|
144 |
* which is an in-memory CookieStore implmentation.
|
|
145 |
* @param cookiePolicy a <tt>CookiePolicy</tt> instance
|
|
146 |
* to be used by cookie manager as policy callback.
|
|
147 |
* if <tt>null</tt>, ACCEPT_ORIGINAL_SERVER will
|
|
148 |
* be used.
|
|
149 |
*/
|
|
150 |
public CookieManager(CookieStore store,
|
|
151 |
CookiePolicy cookiePolicy)
|
|
152 |
{
|
|
153 |
// use default cookie policy if not specify one
|
|
154 |
policyCallback = (cookiePolicy == null) ? CookiePolicy.ACCEPT_ORIGINAL_SERVER
|
|
155 |
: cookiePolicy;
|
|
156 |
|
|
157 |
// if not specify CookieStore to use, use default one
|
|
158 |
if (store == null) {
|
|
159 |
cookieJar = new sun.net.www.protocol.http.InMemoryCookieStore();
|
|
160 |
} else {
|
|
161 |
cookieJar = store;
|
|
162 |
}
|
|
163 |
}
|
|
164 |
|
|
165 |
|
|
166 |
/* ---------------- Public operations -------------- */
|
|
167 |
|
|
168 |
/**
|
|
169 |
* To set the cookie policy of this cookie manager.
|
|
170 |
*
|
|
171 |
* <p> A instance of <tt>CookieManager</tt> will have
|
|
172 |
* cookie policy ACCEPT_ORIGINAL_SERVER by default. Users always
|
|
173 |
* can call this method to set another cookie policy.
|
|
174 |
*
|
|
175 |
* @param cookiePolicy the cookie policy. Can be <tt>null</tt>, which
|
|
176 |
* has no effects on current cookie policy.
|
|
177 |
*/
|
|
178 |
public void setCookiePolicy(CookiePolicy cookiePolicy) {
|
|
179 |
if (cookiePolicy != null) policyCallback = cookiePolicy;
|
|
180 |
}
|
|
181 |
|
|
182 |
|
|
183 |
/**
|
|
184 |
* To retrieve current cookie store.
|
|
185 |
*
|
|
186 |
* @return the cookie store currently used by cookie manager.
|
|
187 |
*/
|
|
188 |
public CookieStore getCookieStore() {
|
|
189 |
return cookieJar;
|
|
190 |
}
|
|
191 |
|
|
192 |
|
|
193 |
public Map<String, List<String>>
|
|
194 |
get(URI uri, Map<String, List<String>> requestHeaders)
|
|
195 |
throws IOException
|
|
196 |
{
|
|
197 |
// pre-condition check
|
|
198 |
if (uri == null || requestHeaders == null) {
|
|
199 |
throw new IllegalArgumentException("Argument is null");
|
|
200 |
}
|
|
201 |
|
|
202 |
Map<String, List<String>> cookieMap =
|
|
203 |
new java.util.HashMap<String, List<String>>();
|
|
204 |
// if there's no default CookieStore, no way for us to get any cookie
|
|
205 |
if (cookieJar == null)
|
|
206 |
return Collections.unmodifiableMap(cookieMap);
|
|
207 |
|
480
|
208 |
boolean secureLink = "https".equalsIgnoreCase(uri.getScheme());
|
2
|
209 |
List<HttpCookie> cookies = new java.util.ArrayList<HttpCookie>();
|
480
|
210 |
String path = uri.getPath();
|
|
211 |
if (path == null || path.isEmpty()) {
|
|
212 |
path = "/";
|
|
213 |
}
|
2
|
214 |
for (HttpCookie cookie : cookieJar.get(uri)) {
|
|
215 |
// apply path-matches rule (RFC 2965 sec. 3.3.4)
|
480
|
216 |
// and check for the possible "secure" tag (i.e. don't send
|
|
217 |
// 'secure' cookies over unsecure links)
|
|
218 |
if (pathMatches(path, cookie.getPath()) &&
|
|
219 |
(secureLink || !cookie.getSecure())) {
|
|
220 |
// Let's check the authorize port list if it exists
|
|
221 |
String ports = cookie.getPortlist();
|
|
222 |
if (ports != null && !ports.isEmpty()) {
|
|
223 |
int port = uri.getPort();
|
|
224 |
if (port == -1) {
|
|
225 |
port = "https".equals(uri.getScheme()) ? 443 : 80;
|
|
226 |
}
|
|
227 |
if (isInPortList(ports, port)) {
|
|
228 |
cookies.add(cookie);
|
|
229 |
}
|
|
230 |
} else {
|
|
231 |
cookies.add(cookie);
|
|
232 |
}
|
2
|
233 |
}
|
|
234 |
}
|
|
235 |
|
|
236 |
// apply sort rule (RFC 2965 sec. 3.3.4)
|
|
237 |
List<String> cookieHeader = sortByPath(cookies);
|
|
238 |
|
|
239 |
cookieMap.put("Cookie", cookieHeader);
|
|
240 |
return Collections.unmodifiableMap(cookieMap);
|
|
241 |
}
|
|
242 |
|
|
243 |
|
|
244 |
public void
|
|
245 |
put(URI uri, Map<String, List<String>> responseHeaders)
|
|
246 |
throws IOException
|
|
247 |
{
|
|
248 |
// pre-condition check
|
|
249 |
if (uri == null || responseHeaders == null) {
|
|
250 |
throw new IllegalArgumentException("Argument is null");
|
|
251 |
}
|
|
252 |
|
|
253 |
|
|
254 |
// if there's no default CookieStore, no need to remember any cookie
|
|
255 |
if (cookieJar == null)
|
|
256 |
return;
|
|
257 |
|
|
258 |
for (String headerKey : responseHeaders.keySet()) {
|
|
259 |
// RFC 2965 3.2.2, key must be 'Set-Cookie2'
|
|
260 |
// we also accept 'Set-Cookie' here for backward compatibility
|
|
261 |
if (headerKey == null
|
|
262 |
|| !(headerKey.equalsIgnoreCase("Set-Cookie2")
|
|
263 |
|| headerKey.equalsIgnoreCase("Set-Cookie")
|
|
264 |
)
|
|
265 |
)
|
|
266 |
{
|
|
267 |
continue;
|
|
268 |
}
|
|
269 |
|
|
270 |
for (String headerValue : responseHeaders.get(headerKey)) {
|
|
271 |
try {
|
|
272 |
List<HttpCookie> cookies = HttpCookie.parse(headerValue);
|
|
273 |
for (HttpCookie cookie : cookies) {
|
480
|
274 |
if (cookie.getPath() == null) {
|
|
275 |
// If no path is specified, then by default
|
|
276 |
// the path is the directory of the page/doc
|
|
277 |
String path = uri.getPath();
|
|
278 |
if (!path.endsWith("/")) {
|
|
279 |
int i = path.lastIndexOf("/");
|
|
280 |
if (i > 0) {
|
|
281 |
path = path.substring(0, i + 1);
|
|
282 |
} else {
|
|
283 |
path = "/";
|
|
284 |
}
|
|
285 |
}
|
|
286 |
cookie.setPath(path);
|
|
287 |
}
|
|
288 |
String ports = cookie.getPortlist();
|
|
289 |
if (ports != null) {
|
|
290 |
int port = uri.getPort();
|
|
291 |
if (port == -1) {
|
|
292 |
port = "https".equals(uri.getScheme()) ? 443 : 80;
|
|
293 |
}
|
|
294 |
if (ports.isEmpty()) {
|
|
295 |
// Empty port list means this should be restricted
|
|
296 |
// to the incoming URI port
|
|
297 |
cookie.setPortlist("" + port );
|
|
298 |
if (shouldAcceptInternal(uri, cookie)) {
|
|
299 |
cookieJar.add(uri, cookie);
|
|
300 |
}
|
|
301 |
} else {
|
|
302 |
// Only store cookies with a port list
|
|
303 |
// IF the URI port is in that list, as per
|
|
304 |
// RFC 2965 section 3.3.2
|
|
305 |
if (isInPortList(ports, port) &&
|
|
306 |
shouldAcceptInternal(uri, cookie)) {
|
|
307 |
cookieJar.add(uri, cookie);
|
|
308 |
}
|
|
309 |
}
|
|
310 |
} else {
|
|
311 |
if (shouldAcceptInternal(uri, cookie)) {
|
|
312 |
cookieJar.add(uri, cookie);
|
|
313 |
}
|
2
|
314 |
}
|
|
315 |
}
|
|
316 |
} catch (IllegalArgumentException e) {
|
|
317 |
// invalid set-cookie header string
|
|
318 |
// no-op
|
|
319 |
}
|
|
320 |
}
|
|
321 |
}
|
|
322 |
}
|
|
323 |
|
|
324 |
|
|
325 |
/* ---------------- Private operations -------------- */
|
|
326 |
|
|
327 |
// to determine whether or not accept this cookie
|
|
328 |
private boolean shouldAcceptInternal(URI uri, HttpCookie cookie) {
|
|
329 |
try {
|
|
330 |
return policyCallback.shouldAccept(uri, cookie);
|
|
331 |
} catch (Exception ignored) { // pretect against malicious callback
|
|
332 |
return false;
|
|
333 |
}
|
|
334 |
}
|
|
335 |
|
|
336 |
|
480
|
337 |
static private boolean isInPortList(String lst, int port) {
|
|
338 |
int i = lst.indexOf(",");
|
|
339 |
int val = -1;
|
|
340 |
while (i > 0) {
|
|
341 |
try {
|
|
342 |
val = Integer.parseInt(lst.substring(0, i));
|
|
343 |
if (val == port) {
|
|
344 |
return true;
|
|
345 |
}
|
|
346 |
} catch (NumberFormatException numberFormatException) {
|
|
347 |
}
|
|
348 |
lst = lst.substring(i+1);
|
|
349 |
i = lst.indexOf(",");
|
|
350 |
}
|
|
351 |
if (!lst.isEmpty()) {
|
|
352 |
try {
|
|
353 |
val = Integer.parseInt(lst);
|
|
354 |
if (val == port) {
|
|
355 |
return true;
|
|
356 |
}
|
|
357 |
} catch (NumberFormatException numberFormatException) {
|
|
358 |
}
|
|
359 |
}
|
|
360 |
return false;
|
|
361 |
}
|
|
362 |
|
2
|
363 |
/*
|
|
364 |
* path-matches algorithm, as defined by RFC 2965
|
|
365 |
*/
|
|
366 |
private boolean pathMatches(String path, String pathToMatchWith) {
|
|
367 |
if (path == pathToMatchWith)
|
|
368 |
return true;
|
|
369 |
if (path == null || pathToMatchWith == null)
|
|
370 |
return false;
|
|
371 |
if (path.startsWith(pathToMatchWith))
|
|
372 |
return true;
|
|
373 |
|
|
374 |
return false;
|
|
375 |
}
|
|
376 |
|
|
377 |
|
|
378 |
/*
|
|
379 |
* sort cookies with respect to their path: those with more specific Path attributes
|
|
380 |
* precede those with less specific, as defined in RFC 2965 sec. 3.3.4
|
|
381 |
*/
|
|
382 |
private List<String> sortByPath(List<HttpCookie> cookies) {
|
|
383 |
Collections.sort(cookies, new CookiePathComparator());
|
|
384 |
|
|
385 |
List<String> cookieHeader = new java.util.ArrayList<String>();
|
|
386 |
for (HttpCookie cookie : cookies) {
|
|
387 |
// Netscape cookie spec and RFC 2965 have different format of Cookie
|
|
388 |
// header; RFC 2965 requires a leading $Version="1" string while Netscape
|
|
389 |
// does not.
|
|
390 |
// The workaround here is to add a $Version="1" string in advance
|
|
391 |
if (cookies.indexOf(cookie) == 0 && cookie.getVersion() > 0) {
|
|
392 |
cookieHeader.add("$Version=\"1\"");
|
|
393 |
}
|
|
394 |
|
|
395 |
cookieHeader.add(cookie.toString());
|
|
396 |
}
|
|
397 |
return cookieHeader;
|
|
398 |
}
|
|
399 |
|
|
400 |
|
|
401 |
static class CookiePathComparator implements Comparator<HttpCookie> {
|
|
402 |
public int compare(HttpCookie c1, HttpCookie c2) {
|
|
403 |
if (c1 == c2) return 0;
|
|
404 |
if (c1 == null) return -1;
|
|
405 |
if (c2 == null) return 1;
|
|
406 |
|
|
407 |
// path rule only applies to the cookies with same name
|
|
408 |
if (!c1.getName().equals(c2.getName())) return 0;
|
|
409 |
|
|
410 |
// those with more specific Path attributes precede those with less specific
|
|
411 |
if (c1.getPath().startsWith(c2.getPath()))
|
|
412 |
return -1;
|
|
413 |
else if (c2.getPath().startsWith(c1.getPath()))
|
|
414 |
return 1;
|
|
415 |
else
|
|
416 |
return 0;
|
|
417 |
}
|
|
418 |
}
|
|
419 |
}
|