Exemplo n.º 1
0
  @Test
  public void testSendingCookiesFromStore() throws Exception {
    MockWebServer server = new MockWebServer();
    server.enqueue(new MockResponse());
    server.play();

    CookieManager cookieManager = new CookieManager(null, ACCEPT_ORIGINAL_SERVER);
    HttpCookie cookieA = new HttpCookie("a", "android");
    cookieA.setDomain(server.getCookieDomain());
    cookieA.setPath("/");
    cookieManager.getCookieStore().add(server.getUrl("/").toURI(), cookieA);
    HttpCookie cookieB = new HttpCookie("b", "banana");
    cookieB.setDomain(server.getCookieDomain());
    cookieB.setPath("/");
    cookieManager.getCookieStore().add(server.getUrl("/").toURI(), cookieB);
    CookieHandler.setDefault(cookieManager);

    get(server, "/");
    RecordedRequest request = server.takeRequest();

    List<String> receivedHeaders = request.getHeaders();
    assertContains(
        receivedHeaders,
        "Cookie: $Version=\"1\"; "
            + "a=\"android\";$Path=\"/\";$Domain=\""
            + server.getCookieDomain()
            + "\"; "
            + "b=\"banana\";$Path=\"/\";$Domain=\""
            + server.getCookieDomain()
            + "\"");
  }
Exemplo n.º 2
0
  @Test
  public void testRedirectsDoNotIncludeTooManyCookies() throws Exception {
    MockWebServer redirectTarget = new MockWebServer();
    redirectTarget.enqueue(new MockResponse().setBody("A"));
    redirectTarget.start();

    MockWebServer redirectSource = new MockWebServer();
    redirectSource.enqueue(
        new MockResponse()
            .setResponseCode(HttpURLConnection.HTTP_MOVED_TEMP)
            .addHeader("Location: " + redirectTarget.url("/")));
    redirectSource.start();

    CookieManager cookieManager = new CookieManager(null, ACCEPT_ORIGINAL_SERVER);
    HttpCookie cookie = new HttpCookie("c", "cookie");
    cookie.setDomain(redirectSource.getHostName());
    cookie.setPath("/");
    String portList = Integer.toString(redirectSource.getPort());
    cookie.setPortlist(portList);
    cookieManager.getCookieStore().add(redirectSource.url("/").uri(), cookie);
    client.setCookieJar(new JavaNetCookieJar(cookieManager));

    get(redirectSource.url("/"));
    RecordedRequest request = redirectSource.takeRequest();

    assertEquals("c=cookie", request.getHeader("Cookie"));

    for (String header : redirectTarget.takeRequest().getHeaders().names()) {
      if (header.startsWith("Cookie")) {
        fail(header);
      }
    }
  }
  /**
   * Sets cookies according to uri and responseHeaders
   *
   * @param uri the specified uri
   * @param responseHeaders a list of request headers
   * @throws IOException if some error of I/O operation occurs
   */
  @Override
  public void put(URI uri, Map<String, List<String>> responseHeaders) throws IOException {
    if (uri == null || responseHeaders == null) {
      throw new IllegalArgumentException();
    }

    // parse and construct cookies according to the map
    List<HttpCookie> cookies = parseCookie(responseHeaders);
    for (HttpCookie cookie : cookies) {

      // if the cookie doesn't have a domain, set one. The policy will do validation.
      if (cookie.getDomain() == null) {
        cookie.setDomain(uri.getHost());
      }

      // if the cookie doesn't have a path, set one. If it does, validate it.
      if (cookie.getPath() == null) {
        cookie.setPath(pathToCookiePath(uri.getPath()));
      } else if (!HttpCookie.pathMatches(cookie, uri)) {
        continue;
      }

      // if the cookie has the placeholder port list "", set the port. Otherwise validate it.
      if ("".equals(cookie.getPortlist())) {
        cookie.setPortlist(Integer.toString(uri.getEffectivePort()));
      } else if (cookie.getPortlist() != null && !HttpCookie.portMatches(cookie, uri)) {
        continue;
      }

      // if the cookie conforms to the policy, add it into the store
      if (policy.shouldAccept(uri, cookie)) {
        store.add(uri, cookie);
      }
    }
  }
Exemplo n.º 4
0
  @Test
  public void testSendingCookiesFromStore() throws Exception {
    MockWebServer server = new MockWebServer();
    server.enqueue(new MockResponse());
    server.start();

    CookieManager cookieManager = new CookieManager(null, ACCEPT_ORIGINAL_SERVER);
    HttpCookie cookieA = new HttpCookie("a", "android");
    cookieA.setDomain(server.getHostName());
    cookieA.setPath("/");
    cookieManager.getCookieStore().add(server.url("/").uri(), cookieA);
    HttpCookie cookieB = new HttpCookie("b", "banana");
    cookieB.setDomain(server.getHostName());
    cookieB.setPath("/");
    cookieManager.getCookieStore().add(server.url("/").uri(), cookieB);
    client.setCookieJar(new JavaNetCookieJar(cookieManager));

    get(server.url("/"));
    RecordedRequest request = server.takeRequest();

    assertEquals("a=android; b=banana", request.getHeader("Cookie"));
  }
 public HttpCookie toHttpCookie() {
   HttpCookie cookie = new HttpCookie(name, value);
   cookie.setComment(comment);
   cookie.setCommentURL(commentURL);
   cookie.setDiscard(discard);
   cookie.setDomain(domain);
   cookie.setMaxAge((expiry - System.currentTimeMillis()) / 1000L);
   cookie.setPath(path);
   cookie.setPortlist(portList);
   cookie.setSecure(secure);
   cookie.setVersion(version);
   return cookie;
 }
Exemplo n.º 6
0
  public static HttpCookie fromNewCookie(NewCookie c) {

    HttpCookie cookie = new HttpCookie(c.getName(), c.getValue());

    cookie.setComment(c.getComment());
    cookie.setCommentURL("not available");
    cookie.setDiscard(false);
    cookie.setDomain(c.getDomain());
    cookie.setMaxAge(c.getMaxAge());
    cookie.setPath(c.getPath());
    cookie.setPortlist("not available");
    cookie.setSecure(c.isSecure());
    cookie.setVersion(c.getVersion());
    cookie.setHttpOnly(c.isHttpOnly());

    return cookie;
  }
Exemplo n.º 7
0
  public HttpCookie toHttpCookie() {
    HttpCookie cookie = null;

    long expiration = 0;
    try {
      expiration = getExpiration();
    } catch (Exception e) {
    }

    String domain = getDomain();
    String path = getPath();

    int secureFlag = 0;
    try {
      secureFlag = getSecure();
    } catch (Exception e) {
    }

    // Currently no use or need to use the HTTP-only flag in cookies for now
    cookie = new HttpCookie(getName(), getValue());
    cookie.setVersion(0);

    long currentTimeInSeconds = Calendar.getInstance().getTimeInMillis() / 1000;
    if (currentTimeInSeconds < expiration) {
      long maxAge = expiration - currentTimeInSeconds;
      cookie.setMaxAge(maxAge);
    }

    if (secureFlag != 0) {
      cookie.setSecure(true);
    }

    if (domain != null && domain.length() > 0) {
      cookie.setDomain(domain);
      if (path != null && path.length() > 0) {
        cookie.setPath(path);
      } else {
        cookie.setPath("/");
      }
      return cookie;
    }
    return null;
  }
Exemplo n.º 8
0
  public void loadState(Activity a) {
    SharedPreferences prefs = a.getSharedPreferences("cookies", 0);
    String cookie = prefs.getString("RevTK", "no value");

    Log.v(DEBUG_TAG, "loaded RevTK cookie: " + cookie);

    HttpCookie revTKCookie = new HttpCookie("RevTK", cookie);
    revTKCookie.setVersion(0);
    revTKCookie.setDomain("kanji.koohii.com");

    try {
      if (!(cookie.equals("no value") || revTKCookie.hasExpired())) {
        cm.getCookieStore().add(new URI("http://kanji.koohii.com/"), revTKCookie);
        loggedIn = true;
      }
    } catch (URISyntaxException e) { // should not happen
      e.printStackTrace();
    }
  }
Exemplo n.º 9
0
  @Test
  public void testRedirectsDoNotIncludeTooManyCookies() throws Exception {
    MockWebServer redirectTarget = new MockWebServer();
    redirectTarget.enqueue(new MockResponse().setBody("A"));
    redirectTarget.play();

    MockWebServer redirectSource = new MockWebServer();
    redirectSource.enqueue(
        new MockResponse()
            .setResponseCode(HttpURLConnection.HTTP_MOVED_TEMP)
            .addHeader("Location: " + redirectTarget.getUrl("/")));
    redirectSource.play();

    CookieManager cookieManager = new CookieManager(null, ACCEPT_ORIGINAL_SERVER);
    HttpCookie cookie = new HttpCookie("c", "cookie");
    cookie.setDomain(redirectSource.getCookieDomain());
    cookie.setPath("/");
    String portList = Integer.toString(redirectSource.getPort());
    cookie.setPortlist(portList);
    cookieManager.getCookieStore().add(redirectSource.getUrl("/").toURI(), cookie);
    CookieHandler.setDefault(cookieManager);

    get(redirectSource, "/");
    RecordedRequest request = redirectSource.takeRequest();

    assertContains(
        request.getHeaders(),
        "Cookie: $Version=\"1\"; "
            + "c=\"cookie\";$Path=\"/\";$Domain=\""
            + redirectSource.getCookieDomain()
            + "\";$Port=\""
            + portList
            + "\"");

    for (String header : redirectTarget.takeRequest().getHeaders()) {
      if (header.startsWith("Cookie")) {
        fail(header);
      }
    }
  }
Exemplo n.º 10
0
  public void put(URI uri, Map<String, List<String>> responseHeaders) throws IOException {
    // pre-condition check
    if (uri == null || responseHeaders == null) {
      throw new IllegalArgumentException("Argument is null");
    }

    // if there's no default CookieStore, no need to remember any cookie
    if (cookieJar == null) return;

    PlatformLogger logger = PlatformLogger.getLogger("java.net.CookieManager");
    for (String headerKey : responseHeaders.keySet()) {
      // RFC 2965 3.2.2, key must be 'Set-Cookie2'
      // we also accept 'Set-Cookie' here for backward compatibility
      if (headerKey == null
          || !(headerKey.equalsIgnoreCase("Set-Cookie2")
              || headerKey.equalsIgnoreCase("Set-Cookie"))) {
        continue;
      }

      for (String headerValue : responseHeaders.get(headerKey)) {
        try {
          List<HttpCookie> cookies;
          try {
            cookies = HttpCookie.parse(headerValue);
          } catch (IllegalArgumentException e) {
            // Bogus header, make an empty list and log the error
            cookies = java.util.Collections.EMPTY_LIST;
            if (logger.isLoggable(PlatformLogger.SEVERE)) {
              logger.severe("Invalid cookie for " + uri + ": " + headerValue);
            }
          }
          for (HttpCookie cookie : cookies) {
            if (cookie.getPath() == null) {
              // If no path is specified, then by default
              // the path is the directory of the page/doc
              String path = uri.getPath();
              if (!path.endsWith("/")) {
                int i = path.lastIndexOf("/");
                if (i > 0) {
                  path = path.substring(0, i + 1);
                } else {
                  path = "/";
                }
              }
              cookie.setPath(path);
            }

            // As per RFC 2965, section 3.3.1:
            // Domain  Defaults to the effective request-host.  (Note that because
            // there is no dot at the beginning of effective request-host,
            // the default Domain can only domain-match itself.)
            if (cookie.getDomain() == null) {
              cookie.setDomain(uri.getHost());
            }
            String ports = cookie.getPortlist();
            if (ports != null) {
              int port = uri.getPort();
              if (port == -1) {
                port = "https".equals(uri.getScheme()) ? 443 : 80;
              }
              if (ports.isEmpty()) {
                // Empty port list means this should be restricted
                // to the incoming URI port
                cookie.setPortlist("" + port);
                if (shouldAcceptInternal(uri, cookie)) {
                  cookieJar.add(uri, cookie);
                }
              } else {
                // Only store cookies with a port list
                // IF the URI port is in that list, as per
                // RFC 2965 section 3.3.2
                if (isInPortList(ports, port) && shouldAcceptInternal(uri, cookie)) {
                  cookieJar.add(uri, cookie);
                }
              }
            } else {
              if (shouldAcceptInternal(uri, cookie)) {
                cookieJar.add(uri, cookie);
              }
            }
          }
        } catch (IllegalArgumentException e) {
          // invalid set-cookie header string
          // no-op
        }
      }
    }
  }