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         if (isMultiReleaseJar()) {
  64             int version;
  65             Object o = env.get("multi-release");
  66             if (o instanceof String) {
  67                 String s = (String)o;
  68                 if (s.equals("runtime")) {
  69                     version = Runtime.version().feature();
  70                 } else {
  71                     version = Integer.parseInt(s);
  72                 }
  73             } else if (o instanceof Integer) {
  74                 version = (Integer)o;
  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     private boolean isMultiReleaseJar() throws IOException {
  87         try (InputStream is = newInputStream(getBytes("/META-INF/MANIFEST.MF"))) {
  88             String multiRelease = new Manifest(is).getMainAttributes()
  89                 .getValue(Attributes.Name.MULTI_RELEASE);
  90             return "true".equalsIgnoreCase(multiRelease);
  91         } catch (NoSuchFileException x) {
  92             return false;
  93         }
  94     }
  95 
  96     /**
  97      * create a map of aliases for versioned entries, for example:
  98      *   version/PackagePrivate.class -> META-INF/versions/9/version/PackagePrivate.class
  99      *   version/PackagePrivate.java -> META-INF/versions/9/version/PackagePrivate.java
 100      *   version/Version.class -> META-INF/versions/10/version/Version.class
 101      *   version/Version.java -> META-INF/versions/10/version/Version.java
 102      *
 103      * then wrap the map in a function that getEntry can use to override root
 104      * entry lookup for entries that have corresponding versioned entries
 105      */
 106     private void createVersionedLinks(int version) {
 107         IndexNode verdir = getInode(getBytes("/META-INF/versions"));
 108         // nothing to do, if no /META-INF/versions
 109         if (verdir == null) {
 110             return;
 111         }
 112         // otherwise, create a map and for each META-INF/versions/{n} directory
 113         // put all the leaf inodes, i.e. entries, into the alias map
 114         // possibly shadowing lower versioned entries
 115         HashMap<IndexNode, byte[]> aliasMap = new HashMap<>();
 116         getVersionMap(version, verdir).values().forEach(versionNode ->
 117             walk(versionNode.child, entryNode ->
 118                 aliasMap.put(
 119                     getOrCreateInode(getRootName(entryNode, versionNode), entryNode.isdir),
 120                     entryNode.name))
 121         );
 122         lookup = path -> {
 123             byte[] entry = aliasMap.get(IndexNode.keyOf(path));
 124             return entry == null ? path : entry;
 125         };
 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, metaInfVersions);
 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(IndexNode inode, IndexNode metaInfVersions) {
 150         try {
 151             byte[] fullName = inode.name;
 152             return Integer.parseInt(getString(Arrays
 153                 .copyOfRange(fullName, metaInfVersions.name.length + 1, fullName.length)));
 154         } catch (NumberFormatException x) {
 155             // ignore this even though it might indicate issues with the JAR structure
 156             return null;
 157         }
 158     }
 159 
 160     /**
 161      * walk the IndexNode tree processing all leaf nodes
 162      */
 163     private void walk(IndexNode inode, Consumer<IndexNode> consumer) {
 164         if (inode == null) return;
 165         if (inode.isDir()) {
 166             walk(inode.child, consumer);
 167         } else {
 168             consumer.accept(inode);
 169         }
 170         walk(inode.sibling, consumer);
 171     }
 172 
 173     /**
 174      * extract the root name from a versioned entry name
 175      *   given inode for META-INF/versions/9/foo/bar.class
 176      *   and prefix META-INF/versions/9/
 177      *   returns foo/bar.class
 178      */
 179     private byte[] getRootName(IndexNode inode, IndexNode prefix) {
 180         byte[] fullName = inode.name;
 181         return Arrays.copyOfRange(fullName, prefix.name.length, fullName.length);
 182     }
 183 }