8216401: Allow "file:" URLs in Class-Path of local JARs
authorbchristi
Mon, 14 Jan 2019 11:22:32 -0800
changeset 53277 b002e4ee60b0
parent 53276 72fdf46a274e
child 53293 64049c8e7452
8216401: Allow "file:" URLs in Class-Path of local JARs Reviewed-by: alanb, mchung
src/java.base/share/classes/jdk/internal/loader/URLClassPath.java
test/jdk/jdk/internal/loader/URLClassPath/JarClassPathFileEntry.java
--- a/src/java.base/share/classes/jdk/internal/loader/URLClassPath.java	Mon Jan 14 12:51:45 2019 -0500
+++ b/src/java.base/share/classes/jdk/internal/loader/URLClassPath.java	Mon Jan 14 11:22:32 2019 -0800
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1997, 2018, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1997, 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
@@ -1092,10 +1092,15 @@
             int i = 0;
             while (st.hasMoreTokens()) {
                 String path = st.nextToken();
-                URL url = DISABLE_CP_URL_CHECK ? new URL(base, path) : safeResolve(base, path);
+                URL url = DISABLE_CP_URL_CHECK ? new URL(base, path) : tryResolve(base, path);
                 if (url != null) {
                     urls[i] = url;
                     i++;
+                } else {
+                    if (DEBUG_CP_URL_CHECK) {
+                        System.err.println("Class-Path entry: \"" + path
+                                           + "\" ignored in JAR file " + base);
+                    }
                 }
             }
             if (i == 0) {
@@ -1107,36 +1112,74 @@
             return urls;
         }
 
-        /*
-         * Return a URL for the given path resolved against the base URL, or
-         * null if the resulting URL is invalid.
+        static URL tryResolve(URL base, String input) throws MalformedURLException {
+            if ("file".equalsIgnoreCase(base.getProtocol())) {
+                return tryResolveFile(base, input);
+            } else {
+                return tryResolveNonFile(base, input);
+            }
+        }
+
+        /**
+         * Attempt to return a file URL by resolving input against a base file
+         * URL. The input is an absolute or relative file URL that encodes a
+         * file path.
+         *
+         * @apiNote Nonsensical input such as a Windows file path with a drive
+         * letter cannot be disambiguated from an absolute URL so will be rejected
+         * (by returning null) by this method.
+         *
+         * @return the resolved URL or null if the input is an absolute URL with
+         *         a scheme other than file (ignoring case)
+         * @throws MalformedURLException
          */
-        static URL safeResolve(URL base, String path) {
-            String child = path.replace(File.separatorChar, '/');
-            try {
-                if (!URI.create(child).isAbsolute()) {
-                    URL url = new URL(base, child);
-                    if (base.getProtocol().equalsIgnoreCase("file")) {
-                        return url;
-                    } else {
-                        String bp = base.getPath();
-                        String urlp = url.getPath();
-                        int pos = bp.lastIndexOf('/');
-                        if (pos == -1) {
-                            pos = bp.length() - 1;
-                        }
-                        if (urlp.regionMatches(0, bp, 0, pos + 1)
-                            && urlp.indexOf("..", pos) == -1) {
-                            return url;
-                        }
-                    }
+        static URL tryResolveFile(URL base, String input) throws MalformedURLException {
+            int index = input.indexOf(':');
+            boolean isFile;
+            if (index >= 0) {
+                String scheme = input.substring(0, index);
+                isFile = "file".equalsIgnoreCase(scheme);
+            } else {
+                isFile = true;
+            }
+            return (isFile) ? new URL(base, input) : null;
+        }
+
+        /**
+         * Attempt to return a URL by resolving input against a base URL. Returns
+         * null if the resolved URL is not contained by the base URL.
+         *
+         * @return the resolved URL or null
+         * @throws MalformedURLException
+         */
+        static URL tryResolveNonFile(URL base, String input) throws MalformedURLException {
+            String child = input.replace(File.separatorChar, '/');
+            if (isRelative(child)) {
+                URL url = new URL(base, child);
+                String bp = base.getPath();
+                String urlp = url.getPath();
+                int pos = bp.lastIndexOf('/');
+                if (pos == -1) {
+                    pos = bp.length() - 1;
                 }
-            } catch (MalformedURLException | IllegalArgumentException e) {}
-            if (DEBUG_CP_URL_CHECK) {
-                System.err.println("Class-Path entry: \"" + path + "\" ignored in JAR file " + base);
+                if (urlp.regionMatches(0, bp, 0, pos + 1)
+                        && urlp.indexOf("..", pos) == -1) {
+                    return url;
+                }
             }
             return null;
         }
+
+        /**
+         * Returns true if the given input is a relative URI.
+         */
+        static boolean isRelative(String child) {
+            try {
+                return !URI.create(child).isAbsolute();
+            } catch (IllegalArgumentException e) {
+                return false;
+            }
+        }
     }
 
     /*
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/test/jdk/jdk/internal/loader/URLClassPath/JarClassPathFileEntry.java	Mon Jan 14 11:22:32 2019 -0800
@@ -0,0 +1,104 @@
+/*
+ * Copyright (c) 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 java.io.File;
+import java.net.URL;
+import java.net.URLClassLoader;
+import java.nio.file.Path;
+import java.nio.file.Paths;
+import java.util.jar.Attributes;
+import java.util.jar.Manifest;
+import jdk.test.lib.util.JarUtils;
+import jdk.test.lib.compiler.InMemoryJavaCompiler;
+
+/*
+ * @test
+ * @bug 8216401
+ * @summary Test loading of JAR Class-Path entry with file: scheme
+ * @library /test/lib
+ *
+ * @run main/othervm JarClassPathFileEntry
+ * @run main/othervm -Djdk.net.URLClassPath.disableClassPathURLCheck=true JarClassPathFileEntry
+ * @run main/othervm -Djdk.net.URLClassPath.disableClassPathURLCheck=false JarClassPathFileEntry
+ */
+
+public class JarClassPathFileEntry {
+    private final static boolean IS_WINDOWS = System.getProperty("os.name").startsWith("Windows");
+
+    private final static String TEST_CLASSES = System.getProperty("test.classes");
+    private final static String OTHER_DIR = TEST_CLASSES + "/OTHER/";
+
+    private final static Path OTHER_JAR_PATH = Paths.get(OTHER_DIR, "Other.jar");
+    private final static Path CONTEXT_JAR_PATH = Paths.get(TEST_CLASSES, "Context.jar");
+
+    public static void main(String[] args) throws Throwable {
+        // Create Other.class in OTHER_DIR, off the default classpath
+        byte klassbuf[] = InMemoryJavaCompiler.compile("Other",
+                                                       "public class Other {}");
+        ClassFileInstaller.writeClassToDisk("Other", klassbuf, OTHER_DIR);
+
+        // Create Other.jar in OTHER_DIR
+        JarUtils.createJarFile(OTHER_JAR_PATH,
+                               Paths.get(OTHER_DIR),
+                               Paths.get(OTHER_DIR, "Other.class"));
+
+        // Create Context.class
+        klassbuf = InMemoryJavaCompiler.compile("Context",
+                                                "public class Context {}");
+        ClassFileInstaller.writeClassToDisk("Context", klassbuf, TEST_CLASSES);
+
+        // Create Context.jar w/ "file:" entry for Other.jar
+        Manifest mf = new Manifest();
+        Attributes attrs = mf.getMainAttributes();
+        attrs.put(Attributes.Name.MANIFEST_VERSION, "1.0");
+
+        String classPathEntry = "file:" + (IS_WINDOWS ? toUnixPath(OTHER_JAR_PATH.toString())
+                                                      :            OTHER_JAR_PATH.toString());
+        attrs.put(Attributes.Name.CLASS_PATH, classPathEntry);
+
+        System.out.println("Creating Context.jar with Class-Path: " + classPathEntry);
+        JarUtils.createJarFile(CONTEXT_JAR_PATH, mf,
+                               Paths.get(TEST_CLASSES),
+                               Paths.get(TEST_CLASSES, "Context.class"));
+
+        // Use URLClassLoader w/ Context.jar to load Other.class, which will
+        // load via the Class-Path entry
+        URL url = CONTEXT_JAR_PATH.toUri().toURL();
+        URLClassLoader ucl = new URLClassLoader("TestURLClassLoader",
+                                                new URL[]{ url },
+                                                null); // don't delegate to App CL
+        Class<?> otherClass = Class.forName("Other", true, ucl); // ClassNotFoundException -> fail
+        System.out.println("Loaded: " + otherClass);
+    }
+
+    /* Convert a Windows path to a unix-style path, and remove any drive letter */
+    private static String toUnixPath(String orig) {
+        String retVal = new File(orig).toURI().getPath();
+        int colonAt = retVal.indexOf(':');
+
+        if (colonAt != -1 && colonAt < 3) {
+            retVal = retVal.substring(colonAt + 1); // Start after the drive letter
+        }
+        return retVal;
+    }
+}