1 /*
   2  * Copyright (c) 2011, 2014, Oracle and/or its affiliates. All rights reserved.
   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.  Oracle designates this
   8  * particular file as subject to the "Classpath" exception as provided
   9  * by Oracle 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 Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  22  * or visit www.oracle.com if you need additional information or have any
  23  * questions.
  24  */
  25 
  26 package com.sun.webkit.network;
  27 
  28 import com.sun.javafx.logging.PlatformLogger;
  29 import com.sun.javafx.logging.PlatformLogger.Level;
  30 
  31 import java.net.CookieHandler;
  32 import java.net.URI;
  33 import java.util.Arrays;
  34 import java.util.Collections;
  35 import java.util.HashMap;
  36 import java.util.List;
  37 import java.util.ListIterator;
  38 import java.util.Map;
  39 
  40 /**
  41  * An RFC 6265-compliant cookie handler.
  42  */
  43 public final class CookieManager extends CookieHandler {
  44 
  45     private static final PlatformLogger logger =
  46             PlatformLogger.getLogger(CookieManager.class.getName());
  47 
  48 
  49     private final CookieStore store = new CookieStore();
  50 
  51 
  52     /**
  53      * Creates a new {@code CookieManager}.
  54      */
  55     public CookieManager() {
  56     }
  57 
  58 
  59     /**
  60      * {@inheritDoc}
  61      */
  62     @Override
  63     public Map<String,List<String>> get(URI uri,
  64             Map<String,List<String>> requestHeaders)
  65     {
  66         if (logger.isLoggable(Level.FINEST)) {
  67             logger.finest("uri: [{0}], requestHeaders: {1}",
  68                     new Object[] {uri, toLogString(requestHeaders)});
  69         }
  70 
  71         if (uri == null) {
  72             throw new IllegalArgumentException("uri is null");
  73         }
  74         if (requestHeaders == null) {
  75             throw new IllegalArgumentException("requestHeaders is null");
  76         }
  77 
  78         String cookieString = get(uri);
  79 
  80         Map<String,List<String>> result;
  81         if (cookieString != null) {
  82             result = new HashMap<String,List<String>>();
  83             result.put("Cookie", Arrays.asList(cookieString));
  84         } else {
  85             result = Collections.emptyMap();
  86         }
  87         if (logger.isLoggable(Level.FINEST)) {
  88             logger.finest("result: {0}", toLogString(result));
  89         }
  90         return result;
  91     }
  92 
  93     /**
  94      * Returns the cookie string for a given URI.
  95      */
  96     private String get(URI uri) {
  97         String host = uri.getHost();
  98         if (host == null || host.length() == 0) {
  99             logger.finest("Null or empty URI host, returning null");
 100             return null;
 101         }
 102         host = canonicalize(host);
 103 
 104         String scheme = uri.getScheme();
 105         boolean secureProtocol = "https".equalsIgnoreCase(scheme)
 106                 || "javascripts".equalsIgnoreCase(scheme);
 107         boolean httpApi = "http".equalsIgnoreCase(scheme)
 108                 || "https".equalsIgnoreCase(scheme);
 109 
 110         List<Cookie> cookieList;
 111         synchronized (store) {
 112             cookieList = store.get(host, uri.getPath(),
 113                     secureProtocol, httpApi);
 114         }
 115 
 116         StringBuilder sb = new StringBuilder();
 117         for (Cookie cookie : cookieList) {
 118             if (sb.length() > 0) {
 119                 sb.append("; ");
 120             }
 121             sb.append(cookie.getName());
 122             sb.append('=');
 123             sb.append(cookie.getValue());
 124         }
 125 
 126         return sb.length() > 0 ? sb.toString() : null;
 127     }
 128 
 129     /**
 130      * {@inheritDoc}
 131      */
 132     @Override
 133     public void put(URI uri, Map<String,List<String>> responseHeaders) {
 134         if (logger.isLoggable(Level.FINEST)) {
 135             logger.finest("uri: [{0}], responseHeaders: {1}",
 136                     new Object[] {uri, toLogString(responseHeaders)});
 137         }
 138 
 139         if (uri == null) {
 140             throw new IllegalArgumentException("uri is null");
 141         }
 142         if (responseHeaders == null) {
 143             throw new IllegalArgumentException("responseHeaders is null");
 144         }
 145 
 146         for (Map.Entry<String,List<String>> entry : responseHeaders.entrySet())
 147         {
 148             String key = entry.getKey();
 149             if (!"Set-Cookie".equalsIgnoreCase(key)) {
 150                 continue;
 151             }
 152             ExtendedTime currentTime = ExtendedTime.currentTime();
 153             // RT-15907: Process the list of headers in reverse order,
 154             // effectively restoring the order in which the headers were
 155             // received from the server. This is a temporary workaround for
 156             // http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=7059532
 157             ListIterator<String> it =
 158                     entry.getValue().listIterator(entry.getValue().size());
 159             while (it.hasPrevious()) {
 160                 Cookie cookie = Cookie.parse(it.previous(), currentTime);
 161                 if (cookie != null) {
 162                     put(uri, cookie);
 163                     currentTime = currentTime.incrementSubtime();
 164                 }
 165             }
 166         }
 167     }
 168 
 169     /**
 170      * Puts an individual cookie.
 171      */
 172     private void put(URI uri, Cookie cookie) {
 173         logger.finest("cookie: {0}", cookie);
 174 
 175         String host = uri.getHost();
 176         if (host == null || host.length() == 0) {
 177             logger.finest("Null or empty URI host, ignoring cookie");
 178             return;
 179         }
 180         host = canonicalize(host);
 181 
 182         if (PublicSuffixes.isPublicSuffix(cookie.getDomain())) {
 183             if (cookie.getDomain().equals(host)) {
 184                 cookie.setDomain("");
 185             } else {
 186                 logger.finest("Domain is public suffix, "
 187                         + "ignoring cookie");
 188                 return;
 189             }
 190         }
 191 
 192         if (cookie.getDomain().length() > 0) {
 193             if (!Cookie.domainMatches(host, cookie.getDomain())) {
 194                 logger.finest("Hostname does not match domain, "
 195                         + "ignoring cookie");
 196                 return;
 197             } else {
 198                 cookie.setHostOnly(false);
 199             }
 200         } else {
 201             cookie.setHostOnly(true);
 202             cookie.setDomain(host);
 203         }
 204 
 205         if (cookie.getPath() == null) {
 206             cookie.setPath(Cookie.defaultPath(uri));
 207         }
 208 
 209         boolean httpApi = "http".equalsIgnoreCase(uri.getScheme())
 210                 || "https".equalsIgnoreCase(uri.getScheme());
 211         if (cookie.getHttpOnly() && !httpApi) {
 212             logger.finest("HttpOnly cookie received from non-HTTP "
 213                     + "API, ignoring cookie");
 214             return;
 215         }
 216 
 217         synchronized (store) {
 218             Cookie oldCookie = store.get(cookie);
 219             if (oldCookie != null) {
 220                 if (oldCookie.getHttpOnly() && !httpApi) {
 221                     logger.finest("Non-HTTP API attempts to "
 222                             + "overwrite HttpOnly cookie, blocked");
 223                     return;
 224                 }
 225                 cookie.setCreationTime(oldCookie.getCreationTime());
 226             }
 227 
 228             store.put(cookie);
 229         }
 230 
 231         logger.finest("Stored: {0}", cookie);
 232     }
 233 
 234     /**
 235      * Converts a map of HTTP headers to a string suitable for displaying
 236      * in the log.
 237      */
 238     private static String toLogString(Map<String,List<String>> headers) {
 239         if (headers == null) {
 240             return null;
 241         }
 242         if (headers.isEmpty()) {
 243             return "{}";
 244         }
 245         StringBuilder sb = new StringBuilder();
 246         for (Map.Entry<String,List<String>> entry : headers.entrySet()) {
 247             String key = entry.getKey();
 248             for (String value : entry.getValue()) {
 249                 sb.append(String.format("%n    "));
 250                 sb.append(key);
 251                 sb.append(": ");
 252                 sb.append(value);
 253             }
 254         }
 255         return sb.toString();
 256     }
 257 
 258     /**
 259      * Canonicalizes a hostname as required by RFC 6265.
 260      */
 261     private static String canonicalize(String hostname) {
 262         // The hostname is already all-ASCII at this point
 263         return hostname.toLowerCase();
 264     }
 265 }