1/*
2 * Copyright (c) 2015, 2017, 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
26package jdk.nio.zipfs;
27
28import java.io.IOException;
29import java.io.InputStream;
30import java.lang.Runtime.Version;
31import java.nio.file.NoSuchFileException;
32import java.nio.file.Path;
33import java.util.Arrays;
34import java.util.HashMap;
35import java.util.Map;
36import java.util.TreeMap;
37import java.util.function.Consumer;
38import java.util.function.Function;
39import java.util.jar.Attributes;
40import 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#getEntry(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
52class JarFileSystem extends ZipFileSystem {
53    private Function<byte[],byte[]> lookup;
54
55    @Override
56    IndexNode getInode(byte[] path) {
57        // check for an alias to a versioned entry
58        byte[] versionedPath = lookup.apply(path);
59        return versionedPath == null ? super.getInode(path) : super.getInode(versionedPath);
60    }
61
62    JarFileSystem(ZipFileSystemProvider provider, Path zfpath, Map<String,?> env)
63            throws IOException {
64        super(provider, zfpath, env);
65        lookup = path -> path;  // lookup needs to be set before isMultiReleaseJar is called
66                                // because it eventually calls getEntry
67        if (isMultiReleaseJar()) {
68            int version;
69            Object o = env.get("multi-release");
70            if (o instanceof String) {
71                String s = (String)o;
72                if (s.equals("runtime")) {
73                    version = Runtime.version().major();
74                } else {
75                    version = Integer.parseInt(s);
76                }
77            } else if (o instanceof Integer) {
78                version = (Integer)o;
79            } else if (o instanceof Version) {
80                version = ((Version)o).major();
81            } else {
82                throw new IllegalArgumentException("env parameter must be String, Integer, "
83                        + "or Version");
84            }
85            lookup = createVersionedLinks(version < 0 ? 0 : version);
86            setReadOnly();
87        }
88    }
89
90    private boolean isMultiReleaseJar() throws IOException {
91        try (InputStream is = newInputStream(getBytes("/META-INF/MANIFEST.MF"))) {
92            String multiRelease = new Manifest(is).getMainAttributes()
93                    .getValue(Attributes.Name.MULTI_RELEASE);
94            return "true".equalsIgnoreCase(multiRelease);
95        } catch (NoSuchFileException x) {
96            return false;
97        }
98    }
99
100    /**
101     * create a map of aliases for versioned entries, for example:
102     *   version/PackagePrivate.class -> META-INF/versions/9/version/PackagePrivate.class
103     *   version/PackagePrivate.java -> META-INF/versions/9/version/PackagePrivate.java
104     *   version/Version.class -> META-INF/versions/10/version/Version.class
105     *   version/Version.java -> META-INF/versions/10/version/Version.java
106     *
107     * then wrap the map in a function that getEntry can use to override root
108     * entry lookup for entries that have corresponding versioned entries
109     */
110    private Function<byte[],byte[]> createVersionedLinks(int version) {
111        HashMap<IndexNode,byte[]> aliasMap = new HashMap<>();
112        getVersionMap(version, getInode(getBytes("/META-INF/versions"))).values()
113                .forEach(versionNode -> {   // for each META-INF/versions/{n} directory
114                    // put all the leaf inodes, i.e. entries, into the alias map
115                    // possibly shadowing lower versioned entries
116                    walk(versionNode, entryNode -> {
117                        byte[] rootName = getRootName(versionNode, entryNode);
118                        if (rootName != null) {
119                            IndexNode rootNode = getInode(rootName);
120                            if (rootNode == null) { // no matching root node, make a virtual one
121                                rootNode = IndexNode.keyOf(rootName);
122                            }
123                            aliasMap.put(rootNode, entryNode.name);
124                        }
125                    });
126                });
127        return path -> aliasMap.get(IndexNode.keyOf(path));
128    }
129
130    /**
131     * create a sorted version map of version -> inode, for inodes <= max version
132     *   9 -> META-INF/versions/9
133     *  10 -> META-INF/versions/10
134     */
135    private TreeMap<Integer, IndexNode> getVersionMap(int version, IndexNode metaInfVersions) {
136        TreeMap<Integer,IndexNode> map = new TreeMap<>();
137        IndexNode child = metaInfVersions.child;
138        while (child != null) {
139            Integer key = getVersion(child.name, metaInfVersions.name.length + 1);
140            if (key != null && key <= version) {
141                map.put(key, child);
142            }
143            child = child.sibling;
144        }
145        return map;
146    }
147
148    /**
149     * extract the integer version number -- META-INF/versions/9 returns 9
150     */
151    private Integer getVersion(byte[] name, int offset) {
152        try {
153            return Integer.parseInt(getString(Arrays.copyOfRange(name, offset, name.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> process) {
164        if (inode == null) return;
165        if (inode.isDir()) {
166            walk(inode.child, process);
167        } else {
168            process.accept(inode);
169        }
170        walk(inode.sibling, process);
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 prefix, IndexNode inode) {
180        int offset = prefix.name.length;
181        byte[] fullName = inode.name;
182        return Arrays.copyOfRange(fullName, offset, fullName.length);
183    }
184}
185