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