undefect. CWE-407 — 63 sites patched across 27 ecosystems

Authors: russell@unturf.com · brackishbert@gmail.com · foxhop.net · TimeHexOn.com

Patches, unit tests, benchmarks, whitepaper, and outreach briefs.
Public domain — no copyright claimed. Use freely.
This commit is contained in:
russell@unturf.com 2026-03-26 17:11:57 -04:00
commit 0a580b313d
70422 changed files with 17213626 additions and 0 deletions

View file

@ -0,0 +1,60 @@
/*
* Copyright (c) 2005, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/*
* @test
* @summary Unit test for java.net.CookieManager API
* @bug 6277794
* @run main/othervm -ea B6277794
* @author Edward Wang
*/
import java.net.*;
import java.util.*;
import java.io.*;
public class B6277794 {
public static void main(String[] args) throws Exception {
testCookieStore();
}
private static void testCookieStore() throws Exception {
CookieManager cm = new CookieManager();
CookieStore cs = cm.getCookieStore();
HttpCookie c1 = new HttpCookie("COOKIE1", "COOKIE1");
HttpCookie c2 = new HttpCookie("COOKIE2", "COOKIE2");
cs.add(new URI("http://www.sun.com/solaris"), c1);
cs.add(new URI("http://www.sun.com/java"), c2);
List<URI> uris = cs.getURIs();
if (uris.size() != 1 ||
!uris.get(0).equals(new URI("http://www.sun.com"))) {
fail("CookieStore.getURIs() fail.");
}
}
private static void fail(String msg) throws Exception {
throw new RuntimeException(msg);
}
}

View file

@ -0,0 +1,212 @@
/*
* Copyright (c) 2008, 2025, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/*
* @test
* @bug 6644726 6873543
* @summary Cookie management issues
*/
import java.net.*;
import java.util.*;
public class B6644726 {
public static void main(String[] args) throws Exception {
testCookieStore();
}
private static void testCookieStore() throws Exception {
CookieManager cm = new CookieManager();
CookieStore cs = cm.getCookieStore();
URI uri = new URI("http://www.s1.sun.com/dir/foo/doc.html");
URI suri = new URI("https://www.s1.sun.com/dir/foo/index.html");
cm.setCookiePolicy(CookiePolicy.ACCEPT_ALL);
ArrayList<String> lst = new ArrayList<String>();
// Let's test the default path
lst.add("myCookie1=foo");
// Then some alternate expires format
lst.add("myCookie2=bar; path=/dir; expires=Fri, 19 Aug 4242 16:00:00 GMT");
lst.add("myCookie3=test; path=/dir; expires=Fri Aug 19 4242 16:00:00 GMT-0100");
// Then Netscape draft cookies and domains
lst.add("myCookie4=test; domain=.sun.com; path=/dir/foo");
HashMap<String, List<String>> map = new HashMap<String, List<String>>();
map.put("Set-Cookie", lst);
cm.put(uri, map);
map.clear();
lst.clear();
// Test for secure tag
lst.add("myCookie5=test; secure");
// Test for passing cookies between http and https
map.put("Set-Cookie", lst);
cm.put(suri, map);
List<HttpCookie> cookies = cs.getCookies();
// There should be 5 cookies if all dates parsed correctly
if (cookies.size() != 5) {
fail("unexpected cookies: " + cookies + ", should have 5 cookies. Got only "
+ cookies.size() + ", expires probably didn't parse correctly");
}
// Check Path for first Cookie
for (HttpCookie c : cookies) {
if (c.getName().equals("myCookie1")) {
if (!"/dir/foo/".equals(c.getPath())) {
fail("Default path for myCookie1 is " + c.getPath());
}
}
}
HashMap<String, List<String>> emptyMap = new HashMap<String, List<String>>();
// We should get 1 Cookie: MyCookie4, because of the domain
Map<String, List<String>>m = cm.get(new URI("http://www.s2.sun.com/dir/foo/doc2.html"),
emptyMap);
List<String> clst = m.get("Cookie");
if (clst.size() != 1) {
fail("We should have only 1 cookie, not " + clst.size());
} else {
if (!clst.get(0).startsWith("myCookie4")) {
fail("The cookie should be myCookie4, not " + clst.get(0));
}
}
// We should get 4 cookies for non secure URI, and 5 for the secure one
m = cm.get(suri, emptyMap);
clst = m.get("Cookie");
if (clst.size() != 5) {
fail("Cookies didn't cross from http to https. Got only " + clst.size());
}
m = cm.get(uri, emptyMap);
clst = m.get("Cookie");
if (clst.size() != 4) {
fail("We should have gotten only 4 cookies over http (non secure), got " +
clst.size());
}
if (isIn(clst, "myCookie5=")) {
// myCookie5 (the secure one) shouldn't be here
fail("Got the secure cookie over a non secure link");
}
// Let's check that empty path is treated correctly
uri = new URI("http://www.sun.com/");
lst.clear();
lst.add("myCookie6=foo");
map.clear();
map.put("Set-Cookie", lst);
cm.put(uri, map);
uri = new URI("http://www.sun.com");
m = cm.get(uri, emptyMap);
clst = m.get("Cookie");
if (clst.size() != 1) {
fail("Missing a cookie when using an empty path");
}
// And now, the other way around:
uri = new URI("http://www.sun.com");
lst.clear();
lst.add("myCookie7=foo");
map.clear();
map.put("Set-Cookie", lst);
cm.put(uri, map);
uri = new URI("http://www.sun.com/");
m = cm.get(uri, emptyMap);
clst = m.get("Cookie");
if (!isIn(clst, "myCookie7=")) {
fail("Missing a cookie when using an empty path");
}
// Let's make sure the 'Port' optional attributes is enforced
lst.clear();
lst.add("myCookie8=porttest; port");
lst.add("myCookie9=porttest; port=\"80,8000\"");
lst.add("myCookie10=porttest; port=\"8000\"");
map.clear();
map.put("Set-Cookie", lst);
uri = new URI("http://www.sun.com/");
cm.put(uri, map);
// myCookie10 should have been rejected
cookies = cs.getCookies();
for (HttpCookie c : cookies) {
if (c.getName().equals("myCookie10")) {
fail("A cookie with an invalid port list was accepted");
}
}
uri = new URI("http://www.sun.com:80/");
m = cm.get(uri, emptyMap);
clst = m.get("Cookie");
// We should find both myCookie8 and myCookie9 but not myCookie10
if (!isIn(clst, "myCookie8=") || !isIn(clst, "myCookie9=")) {
fail("Missing a cookie on port 80");
}
uri = new URI("http://www.sun.com:8000/");
m = cm.get(uri, emptyMap);
clst = m.get("Cookie");
// We should find only myCookie9
if (!isIn(clst, "myCookie9=")) {
fail("Missing a cookie on port 80");
}
if (isIn(clst, "myCookie8=")) {
fail("A cookie with an invalid port list was returned");
}
// Test httpOnly flag (CR# 6873543)
lst.clear();
map.clear();
cm.getCookieStore().removeAll();
lst.add("myCookie11=httpOnlyTest; httpOnly");
map.put("Set-Cookie", lst);
uri = new URI("http://www.sun.com/");
cm.put(uri, map);
m = cm.get(uri, emptyMap);
clst = m.get("Cookie");
// URI scheme was http: so we should get the cookie
if (!isIn(clst, "myCookie11=")) {
fail("Missing cookie with httpOnly flag");
}
uri = new URI("javascript://www.sun.com/");
m = cm.get(uri, emptyMap);
clst = m.get("Cookie");
// URI scheme was neither http or https so we shouldn't get the cookie
if (isIn(clst, "myCookie11=")) {
fail("Should get the cookie with httpOnly when scheme is javascript:");
}
}
private static boolean isIn(List<String> lst, String cookie) {
if (lst == null || lst.isEmpty()) {
return false;
}
for (String s : lst) {
if (s.startsWith(cookie))
return true;
}
return false;
}
private static void fail(String msg) throws Exception {
throw new RuntimeException(msg);
}
}

View file

@ -0,0 +1,58 @@
/*
* Copyright (c) 2009, 2019, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/**
* @test
* @bug 6791927 8233886
* @summary Wrong Locale in HttpCookie::expiryDate2DeltaSeconds
* @run main/othervm B6791927
*/
import java.net.*;
import java.util.List;
import java.util.Locale;
public class B6791927 {
public static final void main(String[] aaParamters) throws Exception {
Locale reservedLocale = Locale.getDefault();
try {
// Forces a non US locale
Locale.setDefault(Locale.FRANCE);
List<HttpCookie> cookies = HttpCookie.parse("set-cookie:" +
" CUSTOMER=WILE_E_COYOTE;" +
" expires=Sat, 09-Nov-2041 23:12:40 GMT");
if (cookies == null || cookies.isEmpty()) {
throw new RuntimeException("No cookie found");
}
for (HttpCookie c : cookies) {
if (c.getMaxAge() == 0) {
throw new RuntimeException(
"Expiration date shouldn't be 0");
}
}
} finally {
// restore the reserved locale
Locale.setDefault(reservedLocale);
}
}
}

View file

@ -0,0 +1,149 @@
/*
* Copyright (c) 2003, 2019, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/* @test
* @summary Unit test for java.net.CookieHandler
* @bug 4696506
* @library /test/lib
* @run main/othervm CookieHandlerTest
* @run main/othervm -Djava.net.preferIPv6Addresses=true CookieHandlerTest
* @author Yingxian Wang
*/
// Run in othervm since a default cookier handler is set and this
// can effect other HTTP related tests.
import java.net.*;
import java.util.*;
import java.io.*;
import jdk.test.lib.net.URIBuilder;
public class CookieHandlerTest implements Runnable {
static Map<String,String> cookies;
ServerSocket ss;
/*
* Our "http" server to return a 404
*/
public void run() {
try {
Socket s = ss.accept();
// check request contains "Cookie"
InputStream is = s.getInputStream ();
BufferedReader r = new BufferedReader(new InputStreamReader(is));
boolean flag = false;
String x;
while ((x=r.readLine()) != null) {
if (x.length() ==0) {
break;
}
String header = "Cookie: ";
if (x.startsWith(header)) {
if (x.equals("Cookie: "+((String)cookies.get("Cookie")))) {
flag = true;
}
}
}
if (!flag) {
throw new RuntimeException("server should see cookie in request");
}
PrintStream out = new PrintStream(
new BufferedOutputStream(
s.getOutputStream() ));
/* send the header */
out.print("HTTP/1.1 200 OK\r\n");
out.print("Set-Cookie2: "+((String)cookies.get("Set-Cookie2")+"\r\n"));
out.print("Content-Type: text/html; charset=iso-8859-1\r\n");
out.print("Connection: close\r\n");
out.print("\r\n");
out.print("<HTML>");
out.print("<HEAD><TITLE>Testing cookie</TITLE></HEAD>");
out.print("<BODY>OK.</BODY>");
out.print("</HTML>");
out.flush();
s.close();
ss.close();
} catch (Exception e) {
e.printStackTrace();
}
}
CookieHandlerTest() throws Exception {
/* start the server */
InetAddress loopback = InetAddress.getLoopbackAddress();
ss = new ServerSocket();
ss.bind(new InetSocketAddress(loopback, 0));
(new Thread(this)).start();
/* establish http connection to server */
URL url = URIBuilder.newBuilder()
.scheme("http")
.loopback()
.port(ss.getLocalPort())
.toURL();
HttpURLConnection http = (HttpURLConnection)url.openConnection(Proxy.NO_PROXY);
int respCode = http.getResponseCode();
http.disconnect();
}
public static void main(String args[]) throws Exception {
cookies = new HashMap<String, String>();
cookies.put("Cookie", "$Version=\"1\"; Customer=\"WILE_E_COYOTE\"; $Path=\"/acme\"");
cookies.put("Set-Cookie2", "$Version=\"1\"; Part_Number=\"Riding_Rocket_0023\"; $Path=\"/acme/ammo\"; Part_Number=\"Rocket_Launcher_0001\"; $Path=\"/acme\"");
CookieHandler.setDefault(new MyCookieHandler());
new CookieHandlerTest();
}
static class MyCookieHandler extends CookieHandler {
public Map<String,List<String>>
get(URI uri, Map<String,List<String>> requestHeaders)
throws IOException {
// returns cookies[0]
// they will be include in request
Map<String,List<String>> map = new HashMap<String,List<String>>();
List<String> l = new ArrayList<String>();
l.add(cookies.get("Cookie"));
map.put("Cookie",l);
return Collections.unmodifiableMap(map);
}
public void
put(URI uri, Map<String,List<String>> responseHeaders)
throws IOException {
// check response has cookies[1]
List<String> l = responseHeaders.get("Set-Cookie2");
String value = l.get(0);
if (!value.equals(cookies.get("Set-Cookie2"))) {
throw new RuntimeException("cookie should be available for handle to put into cache");
}
}
}
}

View file

@ -0,0 +1,383 @@
/*
* Copyright (c) 2005, 2019, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/*
* @test
* @summary Unit test for java.net.CookieManager
* @bug 6244040 7150552 7051862
* @modules jdk.httpserver
* java.logging
* @run main/othervm -ea -esa CookieManagerTest
* @author Edward Wang
*/
import com.sun.net.httpserver.*;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
import java.io.IOException;
import java.net.*;
import java.util.logging.Level;
import java.util.logging.Logger;
import static java.net.Proxy.NO_PROXY;
public class CookieManagerTest {
static CookieTransactionHandler httpTrans;
static HttpServer server;
static final String hostAddress = getAddr();
/** Returns an IP literal suitable for use by the test. */
static String getAddr() {
try {
InetAddress lh = InetAddress.getLocalHost();
System.out.println("Trying: " + lh);
if (lh.isReachable(5_000)) {
System.out.println("Using: " + lh);
return lh.getHostAddress();
}
} catch (IOException x) {
System.out.println("Debug: caught:" + x);
}
InetAddress loopback = InetAddress.getLoopbackAddress();
System.out.println("Using: \"" + loopback.getHostAddress() + "\"");
return loopback.getHostAddress();
}
public static void main(String[] args) throws Exception {
// logs everything...
Logger root = Logger.getLogger("");
root.setLevel(Level.ALL);
root.getHandlers()[0].setLevel(Level.ALL);
startHttpServer();
makeHttpCall();
if (httpTrans.badRequest) {
throw new RuntimeException("Test failed : bad cookie header");
}
checkCookiePolicy();
}
public static void startHttpServer() throws IOException {
httpTrans = new CookieTransactionHandler();
server = HttpServer.create(new InetSocketAddress(hostAddress, 0), 0);
server.createContext("/", httpTrans);
server.start();
}
/*
* Checks if CookiePolicy.ACCEPT_ORIGINAL_SERVER#shouldAccept()
* returns false for null arguments
*/
private static void checkCookiePolicy() throws Exception {
CookiePolicy cp = CookiePolicy.ACCEPT_ORIGINAL_SERVER;
boolean retVal;
retVal = cp.shouldAccept(null, null);
checkValue(retVal);
retVal = cp.shouldAccept(null, new HttpCookie("CookieName", "CookieVal"));
checkValue(retVal);
retVal = cp.shouldAccept((new URL("http", "localhost", 2345, "/")).toURI(),
null);
checkValue(retVal);
}
private static void checkValue(boolean val) {
if (val)
throw new RuntimeException("Return value is not false!");
}
public static void makeHttpCall() throws IOException {
try {
int port = server.getAddress().getPort();
System.out.println("http server listenining on: " + port);
// install CookieManager to use
CookieHandler.setDefault(new CookieManager());
for (int i = 0; i < CookieTransactionHandler.testCount; i++) {
System.out.println("====== CookieManager test " + (i+1)
+ " ======");
((CookieManager)CookieHandler.getDefault())
.setCookiePolicy(CookieTransactionHandler.testPolicies[i]);
((CookieManager)CookieHandler.getDefault())
.getCookieStore().removeAll();
URL url = new URL("http" ,
hostAddress,
server.getAddress().getPort(),
CookieTransactionHandler.testCases[i][0]
.serverPath);
System.out.println("Requesting " + url);
HttpURLConnection uc = (HttpURLConnection)url.openConnection(NO_PROXY);
uc.getResponseCode();
uc.disconnect();
}
} finally {
server.stop(0);
}
}
}
class CookieTransactionHandler implements HttpHandler {
private int testcaseDone = 0;
private int testDone = 0;
public static boolean badRequest = false;
// the main test control logic will also loop exactly this number
// to send http request
public static final int testCount = 6;
@Override
public void handle(HttpExchange exchange) throws IOException {
if (testDone < testCases[testcaseDone].length) {
// still have other tests to run,
// check the Cookie header and then redirect it
if (testDone > 0) checkRequest(exchange.getRequestHeaders());
exchange.getResponseHeaders().add("Location",
testCases[testcaseDone][testDone].serverPath);
exchange.getResponseHeaders()
.add(testCases[testcaseDone][testDone].headerToken,
testCases[testcaseDone][testDone].cookieToSend);
exchange.sendResponseHeaders(302, -1);
testDone++;
} else {
// the last test of this test case
if (testDone > 0) checkRequest(exchange.getRequestHeaders());
testcaseDone++;
testDone = 0;
exchange.sendResponseHeaders(200, -1);
}
exchange.close();
}
private static String trim(String s) {
StringBuilder sb = new StringBuilder();
for (int i=0; i<s.length(); i++) {
char c = s.charAt(i);
if (!Character.isWhitespace(c))
sb.append(c);
}
return sb.toString();
}
private static boolean cookieEquals(String s1, String s2) {
s1 = trim(s1);
s2 = trim(s2);
String[] s1a = s1.split(";");
String[] s2a = s2.split(";");
List<String> l1 = new LinkedList(List.of(s1a));
List<String> l2 = new LinkedList(List.of(s2a));
Collections.sort(l1);
Collections.sort(l2);
int i = 0;
for (String s : l1) {
if (!s.equals(l2.get(i++))) {
return false;
}
}
return true;
}
private void checkRequest(Headers hdrs) {
assert testDone > 0;
String cookieHeader = hdrs.getFirst("Cookie");
if (cookieHeader != null && cookieEquals(
cookieHeader, testCases[testcaseDone][testDone-1].cookieToRecv))
{
System.out.printf("%15s %s\n", "PASSED:", cookieHeader);
} else {
System.out.printf("%15s %s\n", "FAILED:", cookieHeader);
System.out.printf("%15s %s\n\n", "should be:",
testCases[testcaseDone][testDone-1].cookieToRecv);
badRequest = true;
}
}
// test cases
public static class CookieTestCase {
public String headerToken;
public String cookieToSend;
public String cookieToRecv;
public String serverPath;
public CookieTestCase(String h, String cts, String ctr, String sp) {
headerToken = h;
cookieToSend = cts;
cookieToRecv = ctr;
serverPath = sp;
}
};
/*
* these two must match each other,
* i.e. testCases.length == testPolicies.length
*/
// the test cases to run; each test case may contain multiple roundtrips
public static CookieTestCase[][] testCases = null;
// indicates what CookiePolicy to use with each test cases
public static CookiePolicy[] testPolicies = null;
CookieTransactionHandler() {
testCases = new CookieTestCase[testCount][];
testPolicies = new CookiePolicy[testCount];
String localHostAddr = CookieManagerTest.hostAddress;
int count = 0;
// an http session with Netscape cookies exchanged
testPolicies[count] = CookiePolicy.ACCEPT_ORIGINAL_SERVER;
testCases[count++] = new CookieTestCase[]{
new CookieTestCase("Set-Cookie",
"CUSTOMER=WILE:BOB; " +
"path=/; expires=Sat, 09-Nov-2030 23:12:40 GMT;" + "domain=." +
localHostAddr,
"CUSTOMER=WILE:BOB",
"/"
),
new CookieTestCase("Set-Cookie",
"PART_NUMBER=ROCKET_LAUNCHER_0001; path=/;" + "domain=." + localHostAddr,
"CUSTOMER=WILE:BOB; PART_NUMBER=ROCKET_LAUNCHER_0001",
"/"
),
new CookieTestCase("Set-Cookie",
"SHIPPING=FEDEX; path=/foo;" + "domain=." + localHostAddr,
"CUSTOMER=WILE:BOB; PART_NUMBER=ROCKET_LAUNCHER_0001",
"/"
),
new CookieTestCase("Set-Cookie",
"SHIPPING=FEDEX; path=/foo;" + "domain=." + localHostAddr,
"CUSTOMER=WILE:BOB; PART_NUMBER=ROCKET_LAUNCHER_0001; SHIPPING=FEDEX",
"/foo"
)
};
// check whether or not path rule is applied
testPolicies[count] = CookiePolicy.ACCEPT_ORIGINAL_SERVER;
testCases[count++] = new CookieTestCase[]{
new CookieTestCase("Set-Cookie",
"PART_NUMBER=ROCKET_LAUNCHER_0001; path=/;" + "domain=." + localHostAddr,
"PART_NUMBER=ROCKET_LAUNCHER_0001",
"/"
),
new CookieTestCase("Set-Cookie",
"PART_NUMBER=RIDING_ROCKET_0023; path=/ammo;" + "domain=." + localHostAddr,
"PART_NUMBER=RIDING_ROCKET_0023; PART_NUMBER=ROCKET_LAUNCHER_0001",
"/ammo"
)
};
// an http session with rfc2965 cookies exchanged
testPolicies[count] = CookiePolicy.ACCEPT_ORIGINAL_SERVER;
testCases[count++] = new CookieTestCase[]{
new CookieTestCase("Set-Cookie2",
"Customer=\"WILE_E_COYOTE\"; Version=\"1\"; Path=\"/acme\";" + "domain=." + localHostAddr,
"$Version=\"1\"; Customer=\"WILE_E_COYOTE\";$Path=\"/acme\";$Domain=\"." + localHostAddr + "\"",
"/acme/login"
),
new CookieTestCase("Set-Cookie2",
"Part_Number=\"Rocket_Launcher_0001\"; Version=\"1\";Path=\"/acme\";" + "domain=." + localHostAddr,
"$Version=\"1\"; Customer=\"WILE_E_COYOTE\";$Path=\"/acme\";" + "$Domain=\"." +
localHostAddr + "\"" + "; Part_Number=\"Rocket_Launcher_0001\";$Path=\"/acme\";"
+ "$Domain=\"." + localHostAddr + "\"",
"/acme/pickitem"
),
new CookieTestCase("Set-Cookie2",
"Shipping=\"FedEx\"; Version=\"1\"; Path=\"/acme\";" + "domain=." + localHostAddr,
"$Version=\"1\"; Customer=\"WILE_E_COYOTE\";$Path=\"/acme\";" + "$Domain=\"." + localHostAddr +
"\"" + "; Part_Number=\"Rocket_Launcher_0001\";$Path=\"/acme\";" + "$Domain=\"."
+ localHostAddr + "\"" + "; Shipping=\"FedEx\";$Path=\"/acme\";" +
"$Domain=\"." + localHostAddr + "\"",
"/acme/shipping"
)
};
// check whether or not the path rule is applied
testPolicies[count] = CookiePolicy.ACCEPT_ORIGINAL_SERVER;
testCases[count++] = new CookieTestCase[]{
new CookieTestCase("Set-Cookie2",
"Part_Number=\"Rocket_Launcher_0001\"; Version=\"1\"; Path=\"/acme\";" + "domain=." + localHostAddr,
"$Version=\"1\"; Part_Number=\"Rocket_Launcher_0001\";$Path=\"/acme\";$Domain=\"." + localHostAddr + "\"",
"/acme/ammo"
),
new CookieTestCase("Set-Cookie2",
"Part_Number=\"Riding_Rocket_0023\"; Version=\"1\"; Path=\"/acme/ammo\";" + "domain=."
+ localHostAddr,
"$Version=\"1\"; Part_Number=\"Riding_Rocket_0023\";$Path=\"/acme/ammo\";$Domain=\"."
+ localHostAddr + "\"" + "; Part_Number=\"Rocket_Launcher_0001\";$Path=\"/acme\";"
+ "$Domain=\"." + localHostAddr + "\"",
"/acme/ammo"
),
new CookieTestCase("",
"",
"$Version=\"1\"; Part_Number=\"Rocket_Launcher_0001\";$Path=\"/acme\";" + "$Domain=\"." + localHostAddr + "\"",
"/acme/parts"
)
};
// new cookie should overwrite old cookie
testPolicies[count] = CookiePolicy.ACCEPT_ORIGINAL_SERVER;
testCases[count++] = new CookieTestCase[]{
new CookieTestCase("Set-Cookie2",
"Part_Number=\"Rocket_Launcher_0001\"; Version=\"1\"; Path=\"/acme\";" + "domain=." + localHostAddr,
"$Version=\"1\"; Part_Number=\"Rocket_Launcher_0001\";$Path=\"/acme\";$Domain=\"." + localHostAddr + "\"",
"/acme"
),
new CookieTestCase("Set-Cookie2",
"Part_Number=\"Rocket_Launcher_2000\"; Version=\"1\"; Path=\"/acme\";" + "domain=." + localHostAddr,
"$Version=\"1\"; Part_Number=\"Rocket_Launcher_2000\";$Path=\"/acme\";$Domain=\"." + localHostAddr + "\"",
"/acme"
)
};
// cookies without domain attributes
// RFC 2965 states that domain should default to host
testPolicies[count] = CookiePolicy.ACCEPT_ALL;
testCases[count++] = new CookieTestCase[]{
new CookieTestCase("Set-Cookie2",
"Customer=\"WILE_E_COYOTE\"; Version=\"1\"; Path=\"/acme\"",
"$Version=\"1\"; Customer=\"WILE_E_COYOTE\";$Path=\"/acme\";$Domain=\""+localHostAddr+"\"",
"/acme/login"
),
new CookieTestCase("Set-Cookie2",
"Part_Number=\"Rocket_Launcher_0001\"; Version=\"1\";Path=\"/acme\"",
"$Version=\"1\"; Customer=\"WILE_E_COYOTE\";$Path=\"/acme\";$Domain=\""+localHostAddr+"\"" +
"; Part_Number=\"Rocket_Launcher_0001\";$Path=\"/acme\";$Domain=\""+localHostAddr+"\"",
"/acme/pickitem"
),
new CookieTestCase("Set-Cookie2",
"Shipping=\"FedEx\"; Version=\"1\"; Path=\"/acme\"",
"$Version=\"1\"; Customer=\"WILE_E_COYOTE\";$Path=\"/acme\";$Domain=\""+localHostAddr+"\"" +
"; Part_Number=\"Rocket_Launcher_0001\";$Path=\"/acme\";$Domain=\""+localHostAddr+"\"" +
"; Shipping=\"FedEx\";$Path=\"/acme\";$Domain=\""+localHostAddr+"\"",
"/acme/shipping"
)
};
assert count == testCount;
}
}

View file

@ -0,0 +1,105 @@
/*
* Copyright (c) 2013, 2019, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/*
* @test
* @bug 8015799
* @modules jdk.httpserver
* @summary HttpURLConnection.getHeaderFields() throws IllegalArgumentException
* @library /test/lib
* @run main EmptyCookieHeader
* @run main/othervm -Djava.net.preferIPv6Addresses=true EmptyCookieHeader
*/
import com.sun.net.httpserver.*;
import java.io.IOException;
import java.io.OutputStream;
import java.net.*;
import java.util.*;
import jdk.test.lib.net.URIBuilder;
public class EmptyCookieHeader {
public static void main(String[] args) throws Exception {
new EmptyCookieHeader().runTest();
}
public void runTest() throws Exception {
final CookieHandler oldHandler = CookieHandler.getDefault();
CookieHandler.setDefault(new TestCookieHandler());
InetAddress loopback = InetAddress.getLoopbackAddress();
HttpServer s = HttpServer.create(new InetSocketAddress(loopback, 0), 0);
try {
startServer(s);
URL url = URIBuilder.newBuilder()
.scheme("http")
.loopback()
.port(s.getAddress().getPort())
.path("/")
.toURL();
HttpURLConnection c = (HttpURLConnection)url.openConnection(Proxy.NO_PROXY);
c.getHeaderFields();
} finally {
CookieHandler.setDefault(oldHandler);
s.stop(0);
}
}
static void startServer(HttpServer server) throws IOException {
server.createContext("/", new EmptyCookieHandler());
server.start();
}
static class EmptyCookieHandler implements HttpHandler {
@Override
public void handle(HttpExchange exchange) throws IOException {
String requestMethod = exchange.getRequestMethod();
if (requestMethod.equalsIgnoreCase("GET")) {
Headers responseHeaders = exchange.getResponseHeaders();
responseHeaders.set("Content-Type", "text/plain");
responseHeaders.set("Date", "June 13th 2012");
// No domain value set
responseHeaders.set("Set-Cookie2", "name=value");
responseHeaders.set("Set-Cookie2", "");
exchange.sendResponseHeaders(200, 0);
try (OutputStream os = exchange.getResponseBody()) {
String str = "This is what the server sent!";
os.write(str.getBytes());
}
}
}
}
class TestCookieHandler extends CookieHandler {
@Override
public Map<String,List<String>> get(URI uri,
Map<String,List<String>> respH) {
return new HashMap<>();
}
@Override
public void put(URI uri, Map<String,List<String >> respH) { }
}
}

View file

@ -0,0 +1,131 @@
/*
* Copyright (c) 2013, 2019, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
import com.sun.net.httpserver.*;
import java.io.IOException;
import java.io.OutputStream;
import java.net.*;
import java.util.List;
import java.util.Map;
import static java.net.Proxy.NO_PROXY;
/*
* @test
* @bug 7169142
* @key intermittent
* @modules jdk.httpserver
* @summary CookieHandler does not work with localhost. This requires
* binding to the wildcard address and might fail intermittently
* due to port reuse issues.
* @run main/othervm LocalHostCookie
*/
public class LocalHostCookie {
public static void main(String[] args) throws Exception {
new LocalHostCookie().runTest();
}
public void runTest() throws Exception {
Server s = null;
try {
s = new Server();
s.startServer();
URL url = new URL("http","localhost", s.getPort(), "/");
HttpURLConnection urlConnection = (HttpURLConnection)url.openConnection(NO_PROXY);
urlConnection.setRequestMethod("GET");
urlConnection.setDoOutput(true);
urlConnection.connect();
urlConnection.getInputStream();
CookieHandler cookieHandler = CookieHandler.getDefault();
if (cookieHandler == null) {
cookieHandler = new java.net.CookieManager();
CookieHandler.setDefault(cookieHandler);
}
cookieHandler.put(urlConnection.getURL().toURI(),
urlConnection.getHeaderFields());
Map<String, List<String>> map =
cookieHandler.get(urlConnection.getURL().toURI(),
urlConnection.getHeaderFields());
if (map.containsKey("Cookie")) {
List<String> list = map.get("Cookie");
// name-value list will be empty if ".local" is not appended
if (list == null || list.size() == 0) {
throw new RuntimeException("Test failed!");
}
}
} finally {
if (s != null) {
s.stopServer();
}
}
}
class Server {
HttpServer server;
public void startServer() {
InetSocketAddress addr = new InetSocketAddress(0);
try {
server = HttpServer.create(addr, 0);
} catch (IOException ioe) {
throw new RuntimeException("Server could not be created");
}
server.createContext("/", new MyCookieHandler());
server.start();
}
public int getPort() {
return server.getAddress().getPort();
}
public void stopServer() {
if (server != null) {
server.stop(0);
}
}
}
class MyCookieHandler implements HttpHandler {
@Override
public void handle(HttpExchange exchange) throws IOException {
String requestMethod = exchange.getRequestMethod();
if (requestMethod.equalsIgnoreCase("GET")){
Headers responseHeaders = exchange.getResponseHeaders();
responseHeaders.set("Content-Type", "text/plain");
responseHeaders.set("Date", "June 13th 2012");
// No domain value set
responseHeaders.set("Set-Cookie2", "name=value");
exchange.sendResponseHeaders(200, 0);
OutputStream os = exchange.getResponseBody();
String str = "This is what the server sent!";
os.write(str.getBytes());
os.flush();
os.close();
}
}
}
}

View file

@ -0,0 +1,86 @@
/*
* Copyright (c) 2011, 2012, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/*
* @test
* @bug 6953455 7045655
* @summary CookieStore.add() cannot handle null URI parameter
* and An empty InMemoryCookieStore should not return true for removeAll
*/
import java.net.CookieManager;
import java.net.CookieStore;
import java.net.HttpCookie;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.List;
public class NullUriCookieTest {
static boolean fail = false;
public static void main(String[] args) throws Exception {
checkCookieNullUri();
}
static void checkCookieNullUri() throws Exception {
//get a cookie store implementation and add a cookie to the store with null URI
CookieStore cookieStore = (new CookieManager()).getCookieStore();
//Check if removeAll() retrurns false on an empty CookieStore
if (cookieStore.removeAll()) {
fail = true;
}
checkFail("removeAll on empty store should return false");
HttpCookie cookie = new HttpCookie("MY_COOKIE", "MY_COOKIE_VALUE");
cookie.setDomain("foo.com");
cookieStore.add(null, cookie);
//Retrieve added cookie
URI uri = new URI("http://foo.com");
List<HttpCookie> addedCookieList = cookieStore.get(uri);
//Verify CookieStore behaves well
if (addedCookieList.size() != 1) {
fail = true;
}
checkFail("Abnormal size of cookie jar");
for (HttpCookie chip : addedCookieList) {
if (!chip.equals(cookie)) {
fail = true;
}
}
checkFail("Cookie not retrieved from Cookie Jar");
boolean ret = cookieStore.remove(null,cookie);
if (!ret) {
fail = true;
}
checkFail("Abnormal removal behaviour from Cookie Jar");
}
static void checkFail(String exp) {
if (fail) {
throw new RuntimeException(exp);
}
}
}

View file

@ -0,0 +1,398 @@
/*
* Copyright (c) 2005, 2013, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/**
* @test
* @summary Unit test for java.net.HttpCookie
* @bug 6244040 6277796 6277801 6277808 6294071 6692802 6790677 6901170 8020758
* @author Edward Wang
*/
import java.net.HttpCookie;
import java.util.List;
public class TestHttpCookie {
private static int testCount = 0;
private String cHeader = null;
private List<HttpCookie> cookies = null;
// test case here expressed as a string, which represents
// the header string to be parsed into HttpCookie instance.
// A TestHttpCookie instance will be created to hold such a HttpCookie
// object, and TestHttpCookie class has utility methods to check equality
// between HttpCookie's real property and expected property.
static TestHttpCookie test(String cookieHeader) {
testCount++;
return new TestHttpCookie(cookieHeader);
}
TestHttpCookie(String cHeader) {
this.cHeader = cHeader;
try {
List<HttpCookie> cookies = HttpCookie.parse(cHeader);
this.cookies = cookies;
} catch (IllegalArgumentException ignored) {
cookies = null;
}
}
// check name
TestHttpCookie n(int index, String n) {
HttpCookie cookie = cookies.get(index);
if (cookie == null || !n.equalsIgnoreCase(cookie.getName())) {
raiseError("name", cookie.getName(), n);
}
return this;
}
TestHttpCookie n(String n) { return n(0, n); }
// check value
TestHttpCookie v(int index, String v) {
HttpCookie cookie = cookies.get(index);
if (cookie == null || !v.equals(cookie.getValue())) {
raiseError("value", cookie.getValue(), v);
}
return this;
}
TestHttpCookie v(String v) { return v(0, v); }
// check version
TestHttpCookie ver(int index, int ver) {
HttpCookie cookie = cookies.get(index);
if (cookie == null || (ver != cookie.getVersion())) {
raiseError("version", Integer.toString(cookie.getVersion()), Integer.toString(ver));
}
return this;
}
TestHttpCookie ver(int ver) { return ver(0, ver); }
// check path
TestHttpCookie p(int index, String p) {
HttpCookie cookie = cookies.get(index);
if (cookie == null || !p.equals(cookie.getPath())) {
raiseError("path", cookie.getPath(), p);
}
return this;
}
TestHttpCookie p(String p) { return p(0, p); }
// check null-ability
TestHttpCookie nil() {
if (cookies != null) {
raiseError("Check null-ability fail");
}
return this;
}
// check comment
TestHttpCookie c(int index, String c) {
HttpCookie cookie = cookies.get(index);
if (cookie == null || !c.equals(cookie.getComment())) {
raiseError("comment", cookie.getComment(), c);
}
return this;
}
TestHttpCookie c(String c) { return c(0, c); }
// check comment url
TestHttpCookie cu(int index, String cu) {
HttpCookie cookie = cookies.get(index);
if (cookie == null || !cu.equals(cookie.getCommentURL())) {
raiseError("comment url", cookie.getCommentURL(), cu);
}
return this;
}
TestHttpCookie cu(String cu) { return cu(0, cu); }
// check discard
TestHttpCookie dsc(int index, boolean dsc) {
HttpCookie cookie = cookies.get(index);
if (cookie == null || (dsc != cookie.getDiscard())) {
raiseError("discard", Boolean.toString(cookie.getDiscard()), Boolean.toString(dsc));
}
return this;
}
TestHttpCookie dsc(boolean dsc) { return dsc(0, dsc); }
// check domain
TestHttpCookie d(int index, String d) {
HttpCookie cookie = cookies.get(index);
if (cookie == null || !d.equalsIgnoreCase(cookie.getDomain())) {
raiseError("domain", cookie.getDomain(), d);
}
return this;
}
TestHttpCookie d(String d) { return d(0, d); }
// check max-age
TestHttpCookie a(int index, long a) {
HttpCookie cookie = cookies.get(index);
if (cookie == null || (a != cookie.getMaxAge())) {
raiseError("max-age", Long.toString(cookie.getMaxAge()), Long.toString(a));
}
return this;
}
TestHttpCookie a(long a) { return a(0, a); }
// check port list
TestHttpCookie port(int index, String p) {
HttpCookie cookie = cookies.get(index);
if (cookie == null || !p.equals(cookie.getPortlist())) {
raiseError("portlist", cookie.getPortlist(), p);
}
return this;
}
TestHttpCookie port(String p) { return port(0, p); }
// check http only
TestHttpCookie httpOnly(int index, boolean b) {
HttpCookie cookie = cookies.get(index);
if (cookie == null || b != cookie.isHttpOnly()) {
raiseError("HttpOnly", String.valueOf(cookie.isHttpOnly()), String.valueOf(b));
}
return this;
}
TestHttpCookie httpOnly(boolean b) {
return httpOnly(0, b);
}
// check equality
static void eq(HttpCookie ck1, HttpCookie ck2, boolean same) {
testCount++;
if (ck1.equals(ck2) != same) {
raiseError("Comparison inconsistent: " + ck1 + " " + ck2
+ " should " + (same ? "equal" : "not equal"));
}
int h1 = ck1.hashCode();
int h2 = ck2.hashCode();
if ((h1 == h2) != same) {
raiseError("Comparison inconsistent: hashCode for " + ck1 + " " + ck2
+ " should " + (same ? "equal" : "not equal"));
}
}
// check domainMatches()
static void dm(String domain, String host, boolean matches) {
testCount++;
if (HttpCookie.domainMatches(domain, host) != matches) {
raiseError("Host " + host + (matches?" should ":" should not ") +
"domain-match with domain " + domain);
}
}
void raiseError(String attr, String realValue, String expectedValue) {
StringBuilder sb = new StringBuilder();
sb.append("Cookie ").append(attr).append(" is ").append(realValue).
append(", should be ").append(expectedValue).
append(" (").append(cHeader).append(")");
throw new RuntimeException(sb.toString());
}
static void raiseError(String prompt) {
throw new RuntimeException(prompt);
}
static void runTests() {
rfc2965();
netscape();
misc();
}
static void rfc2965() {
header("Test using rfc 2965 syntax");
test("set-cookie2: Customer=\"WILE_E_COYOTE\"; Version=\"1\"; Path=\"/acme\"")
.n("Customer").v("WILE_E_COYOTE").ver(1).p("/acme");
// whitespace between attr and = sign
test("set-cookie2: Customer = \"WILE_E_COYOTE\"; Version = \"1\"; Path = \"/acme\"")
.n("Customer").v("WILE_E_COYOTE").ver(1).p("/acme");
// $NAME is reserved; result should be null
test("set-cookie2: $Customer = \"WILE_E_COYOTE\"; Version = \"1\"; Path = \"/acme\"")
.nil();
// a 'full' cookie
test("set-cookie2: Customer=\"WILE_E_COYOTE\"" +
";Version=\"1\"" +
";Path=\"/acme\"" +
";Comment=\"this is a coyote\"" +
";CommentURL=\"http://www.coyote.org\"" +
";Discard" +
";Domain=\".coyote.org\"" +
";Max-Age=\"3600\"" +
";Port=\"80\"" +
";Secure")
.n("Customer").v("WILE_E_COYOTE").ver(1).p("/acme")
.c("this is a coyote").cu("http://www.coyote.org").dsc(true)
.d(".coyote.org").a(3600).port("80");
// a 'full' cookie, without leading set-cookie2 token
test("Customer=\"WILE_E_COYOTE\"" +
";Version=\"1\"" +
";Path=\"/acme\"" +
";Comment=\"this is a coyote\"" +
";CommentURL=\"http://www.coyote.org\"" +
";Discard" +
";Domain=\".coyote.org\"" +
";Max-Age=\"3600\"" +
";Port=\"80\"" +
";Secure")
.n("Customer").v("WILE_E_COYOTE").ver(1).p("/acme")
.c("this is a coyote").cu("http://www.coyote.org").dsc(true)
.d(".coyote.org").a(3600).port("80");
// empty set-cookie string
test("").nil();
// NullPointerException expected
try {
test(null);
} catch (NullPointerException ignored) {
// no-op
}
// bug 6277796
test("Set-Cookie2:Customer=\"dtftest\"; Discard; Secure; Domain=\".sun.com\"; Max-Age=\"100\"; Version=\"1\"; path=\"/www\"; Port=\"80\"")
.n("Customer").v("dtftest").ver(1).d(".sun.com").p("/www").port("80").dsc(true).a(100);
// bug 6277801
test("Set-Cookie2:Customer=\"dtftest\"; Discard; Secure; Domain=\".sun.com\"; Max-Age=\"100\"; Version=\"1\"; path=\"/www\"; Port=\"80\"" +
";Domain=\".java.sun.com\"; Max-Age=\"200\"; path=\"/javadoc\"; Port=\"8080\"")
.n("Customer").v("dtftest").ver(1).d(".sun.com").p("/www").port("80").dsc(true).a(100);
// bug 6294071
test("Set-Cookie2:Customer=\"dtftest\";Discard; Secure; Domain=\"sun.com\"; Max-Age=\"100\";Version=\"1\"; Path=\"/www\"; Port=\"80,8080\"")
.n("Customer").v("dtftest").ver(1).d("sun.com").p("/www").port("80,8080").dsc(true).a(100);
test("Set-Cookie2:Customer=\"developer\";Domain=\"sun.com\";Max-Age=\"100\";Path=\"/www\";Port=\"80,8080\";CommentURL=\"http://www.sun.com/java1,000,000.html\"")
.n("Customer").v("developer").d("sun.com").p("/www").port("80,8080").a(100).cu("http://www.sun.com/java1,000,000.html");
// a header string contains 2 cookies
test("Set-Cookie2:C1=\"V1\";Domain=\".sun1.com\";path=\"/www1\";Max-Age=\"100\",C2=\"V2\";Domain=\".sun2.com\";path=\"/www2\";Max-Age=\"200\"")
.n(0, "C1").v(0, "V1").p(0, "/www1").a(0, 100).d(0, ".sun1.com")
.n(1, "C2").v(1, "V2").p(1, "/www2").a(1, 200).d(1, ".sun2.com");
// Bug 6790677: Should ignore bogus attributes
test("Set-Cookie2:C1=\"V1\";foobar").n(0, "C1").v(0, "V1");
}
static void netscape() {
header("Test using netscape cookie syntax");
test("set-cookie: CUSTOMER=WILE_E_COYOTE; path=/; expires=Wednesday, 09-Nov-99 23:12:40 GMT")
.n("CUSTOMER").v("WILE_E_COYOTE").p("/").ver(0);
// a Netscape cookie, without set-cookie leading token
test("CUSTOMER=WILE_E_COYOTE; path=/; expires=Wednesday, 09-Nov-99 23:12:40 GMT")
.n("CUSTOMER").v("WILE_E_COYOTE").p("/").ver(0);
// a 'google' cookie
test("Set-Cookie: PREF=ID=1eda537de48ac25d:CR=1:TM=1112868587:LM=1112868587:S=t3FPA-mT9lTR3bxU;" +
"expires=Sun, 17-Jan-2038 19:14:07 GMT; path=/; domain=.google.com")
.n("PREF").v("ID=1eda537de48ac25d:CR=1:TM=1112868587:LM=1112868587:S=t3FPA-mT9lTR3bxU")
.p("/").d(".google.com").ver(0);
// bug 6277796
test("set-cookie: CUSTOMER=WILE_E_COYOTE; path=/; expires=Wednesday, 09-Nov-99 23:12:40 GMT; Secure")
.n("CUSTOMER").v("WILE_E_COYOTE").p("/").ver(0);
// bug 6277801
test("set-cookie: CUSTOMER=WILE_E_COYOTE; path=/; expires=Wednesday, 09-Nov-99 23:12:40 GMT; path=\"/acme\"")
.n("CUSTOMER").v("WILE_E_COYOTE").p("/").ver(0);
// bug 6901170
test("set-cookie: CUSTOMER=WILE_E_COYOTE; version='1'").ver(1);
}
static void misc() {
header("Test equals()");
// test equals()
HttpCookie c1 = new HttpCookie("Customer", "WILE_E_COYOTE");
c1.setDomain(".coyote.org");
c1.setPath("/acme");
HttpCookie c2 = (HttpCookie)c1.clone();
eq(c1, c2, true);
// test equals() when domain and path are null
c1 = new HttpCookie("Customer", "WILE_E_COYOTE");
c2 = new HttpCookie("CUSTOMER", "WILE_E_COYOTE");
eq(c1, c2, true);
// path is case-sensitive
c1 = new HttpCookie("Customer", "WILE_E_COYOTE");
c2 = new HttpCookie("CUSTOMER", "WILE_E_COYOTE");
c1.setPath("/acme");
c2.setPath("/ACME");
eq(c1, c2, false);
header("Test domainMatches()");
dm(".foo.com", "y.x.foo.com", false);
dm(".foo.com", "x.foo.com", true);
dm(".com", "whatever.com", false);
dm(".com.", "whatever.com", false);
dm(".ajax.com", "ajax.com", true);
dm(".local", "example.local", true);
dm("example.local", "example", true);
// bug 6277808
testCount++;
try {
c1 = new HttpCookie("", "whatever");
} catch (IllegalArgumentException ignored) {
// expected exception; no-op
}
// CR 6692802: HttpOnly flag
test("set-cookie: CUSTOMER=WILE_E_COYOTE;HttpOnly").httpOnly(true);
test("set-cookie: CUSTOMER=WILE_E_COYOTE").httpOnly(false);
// space disallowed in name (both Netscape and RFC2965)
test("set-cookie: CUST OMER=WILE_E_COYOTE").nil();
}
static void header(String prompt) {
System.out.println("== " + prompt + " ==");
}
public static void main(String[] args) {
runTests();
System.out.println("Succeeded in running " + testCount + " tests.");
}
}