1 /*
   2  * Copyright (c) 2015, 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 jdk.nio.zipfs;
  27 
  28 import java.io.IOException;
  29 import java.io.InputStream;
  30 import java.nio.file.Path;
  31 import java.util.Arrays;
  32 import java.util.HashMap;
  33 import java.util.Map;
  34 import java.util.TreeMap;
  35 import java.util.function.Consumer;
  36 import java.util.function.Function;
  37 import java.util.jar.Attributes;
  38 import java.util.jar.Manifest;
  39 
  40 /**
  41  * Adds aliasing to ZipFileSystem to support multi-release jar files.  An alias map
  42  * is created by {@link JarFileSystem#createVersionedLinks(int)}.  The map is then
  43  * consulted when an entry is looked up in {@link JarFileSystem#getEntry(byte[])}
  44  * to determine if the entry has a corresponding versioned entry.  If so, the
  45  * versioned entry is returned.
  46  *
  47  * @author Steve Drach
  48  */
  49 
  50 class JarFileSystem extends ZipFileSystem {
  51     private Function<byte[],byte[]> lookup;
  52 
  53     @Override
  54     Entry getEntry(byte[] path) throws IOException {
  55         // check for an alias to a versioned entry
  56         byte[] versionedPath = lookup.apply(path);
  57         return versionedPath == null ? super.getEntry(path) : super.getEntry(versionedPath);
  58     }
  59 
  60     JarFileSystem(ZipFileSystemProvider provider, Path zfpath, Map<String,?> env)
  61             throws IOException {
  62         super(provider, zfpath, env);
  63         lookup = path -> path;  // lookup needs to be set before isMultiReleaseJar is called
  64                                 // because it eventually calls getEntry
  65         if (isMultiReleaseJar()) {
  66             int version;
  67             Object o = env.get("multi-release");
  68             if (o instanceof String) {
  69                 String s = (String)o;
  70                 if (s.equals("runtime")) {
  71                     version = sun.misc.Version.jdkMajorVersion();  // fixme waiting for jdk.util.Version
  72                 } else {
  73                     version = Integer.parseInt(s);
  74                 }
  75             } else if (o instanceof Integer) {
  76                 version = (Integer)o;
  77             } else if (false /*o instanceof Version*/) {  // fixme waiting for jdk.util.Version
  78 //                version = ((Version)o).major();
  79             } else {
  80                 throw new IllegalArgumentException("env parameter must be String, Integer, "
  81                         + "or Version");
  82             }
  83             lookup = createVersionedLinks(version < 0 ? 0 : version);
  84             setReadOnly();
  85         }
  86     }
  87 
  88     private boolean isMultiReleaseJar() {
  89         try (InputStream is = newInputStream(getBytes("META-INF/MANIFEST.MF"))) {
  90             return (new Manifest(is)).getMainAttributes()
  91                     .containsKey(new Attributes.Name("Multi-Release"));
  92             // fixme change line above after JarFile integration to contain Attributes.Name.MULTI_RELEASE
  93         } catch (IOException x) {
  94             return false;
  95         }
  96     }
  97 
  98     /**
  99      * create a map of aliases for versioned entries, for example:
 100      *   version/PackagePrivate.class -> META-INF/versions/9/version/PackagePrivate.class
 101      *   version/PackagePrivate.java -> META-INF/versions/9/version/PackagePrivate.java
 102      *   version/Version.class -> META-INF/versions/10/version/Version.class
 103      *   version/Version.java -> META-INF/versions/10/version/Version.java
 104      *
 105      * then wrap the map in a function that getEntry can use to override root
 106      * entry lookup for entries that have corresponding versioned entries
 107      */
 108     private Function<byte[],byte[]> createVersionedLinks(int version) {
 109         HashMap<IndexNode,byte[]> aliasMap = new HashMap<>();
 110         getVersionMap(version, getInode(getBytes("META-INF/versions"))).values()
 111                 .forEach(versionNode -> {   // for each META-INF/versions/{n} directory
 112                     // put all the leaf inodes, i.e. entries, into the alias map
 113                     // possibly shadowing lower versioned entries
 114                     walk(versionNode, entryNode -> {
 115                         byte[] rootName = getRootName(versionNode, entryNode);
 116                         if (rootName != null) {
 117                             IndexNode rootNode = getInode(rootName);
 118                             if (rootNode == null) { // no matching root node, make a virtual one
 119                                 rootNode = IndexNode.keyOf(rootName);
 120                             }
 121                             aliasMap.put(rootNode, entryNode.name);
 122                         }
 123                     });
 124                 });
 125         return path -> aliasMap.get(IndexNode.keyOf(path));
 126     }
 127 
 128     /**
 129      * create a sorted version map of version -> inode, for inodes <= max version
 130      *   9 -> META-INF/versions/9
 131      *  10 -> META-INF/versions/10
 132      */
 133     private TreeMap<Integer, IndexNode> getVersionMap(int version, IndexNode metaInfVersions) {
 134         TreeMap<Integer,IndexNode> map = new TreeMap<>();
 135         IndexNode child = metaInfVersions.child;
 136         while (child != null) {
 137             Integer key = getVersion(child.name, metaInfVersions.name.length);
 138             if (key != null && key <= version) {
 139                 map.put(key, child);
 140             }
 141             child = child.sibling;
 142         }
 143         return map;
 144     }
 145 
 146     /**
 147      * extract the integer version number -- META-INF/versions/9 returns 9
 148      */
 149     private Integer getVersion(byte[] name, int offset) {
 150         try {
 151             return Integer.parseInt(getString(Arrays.copyOfRange(name, offset, name.length-1)));
 152         } catch (NumberFormatException x) {
 153             // ignore this even though it might indicate issues with the JAR structure
 154             return null;
 155         }
 156     }
 157 
 158     /**
 159      * walk the IndexNode tree processing all leaf nodes
 160      */
 161     private void walk(IndexNode inode, Consumer<IndexNode> process) {
 162         if (inode == null) return;
 163         if (inode.isDir()) {
 164             walk(inode.child, process);
 165         } else {
 166             process.accept(inode);
 167             walk(inode.sibling, process);
 168         }
 169     }
 170 
 171     /**
 172      * extract the root name from a versioned entry name
 173      *   given inode for META-INF/versions/9/foo/bar.class
 174      *   and prefix META-INF/versions/9/
 175      *   returns foo/bar.class
 176      */
 177     private byte[] getRootName(IndexNode prefix, IndexNode inode) {
 178         int offset = prefix.name.length;
 179         byte[] fullName = inode.name;
 180         return Arrays.copyOfRange(fullName, offset, fullName.length);
 181     }
 182 }