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