1 /*
   2  * Copyright (c) 2003, 2013, 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 com.sun.java.util.jar.pack;
  27 
  28 import java.io.BufferedInputStream;
  29 import java.io.ByteArrayOutputStream;
  30 import java.io.File;
  31 import java.io.FileInputStream;
  32 import java.io.IOException;
  33 import java.io.InputStream;
  34 import java.io.OutputStream;
  35 import java.util.HashSet;
  36 import java.util.Set;
  37 import java.util.SortedMap;
  38 import java.util.TimeZone;
  39 import java.util.jar.JarEntry;
  40 import java.util.jar.JarInputStream;
  41 import java.util.jar.JarOutputStream;
  42 import java.util.jar.Pack200;
  43 import java.util.zip.CRC32;
  44 import java.util.zip.CheckedOutputStream;
  45 import java.util.zip.ZipEntry;
  46 
  47 /*
  48  * Implementation of the Pack provider.
  49  * </pre></blockquote>
  50  * @author John Rose
  51  * @author Kumar Srinivasan
  52  */
  53 
  54 
  55 public class UnpackerImpl extends TLGlobals implements Pack200.Unpacker {
  56 
  57     public UnpackerImpl() {}
  58 
  59 
  60 
  61     /**
  62      * Get the set of options for the pack and unpack engines.
  63      * @return A sorted association of option key strings to option values.
  64      */
  65     public SortedMap<String, String> properties() {
  66         return props;
  67     }
  68 
  69     // Back-pointer to NativeUnpacker, when active.
  70     Object _nunp;
  71 
  72 
  73     public String toString() {
  74         return Utils.getVersionString();
  75     }
  76 
  77     //Driver routines
  78 
  79     // The unpack worker...
  80     /**
  81      * Takes a packed-stream InputStream, and writes to a JarOutputStream. Internally
  82      * the entire buffer must be read, it may be more efficient to read the packed-stream
  83      * to a file and pass the File object, in the alternate method described below.
  84      * <p>
  85      * Closes its input but not its output.  (The output can accumulate more elements.)
  86      * @param in an InputStream.
  87      * @param out a JarOutputStream.
  88      * @exception IOException if an error is encountered.
  89      */
  90     public synchronized void unpack(InputStream in, JarOutputStream out) throws IOException {
  91         if (in == null) {
  92             throw new NullPointerException("null input");
  93         }
  94         if (out == null) {
  95             throw new NullPointerException("null output");
  96         }
  97         assert(Utils.currentInstance.get() == null);
  98         TimeZone tz = (props.getBoolean(Utils.PACK_DEFAULT_TIMEZONE))
  99                       ? null
 100                       : TimeZone.getDefault();
 101 
 102         try {
 103             Utils.currentInstance.set(this);
 104             if (tz != null) TimeZone.setDefault(TimeZone.getTimeZone("UTC"));
 105             final int verbose = props.getInteger(Utils.DEBUG_VERBOSE);
 106             BufferedInputStream in0 = new BufferedInputStream(in);
 107             if (Utils.isJarMagic(Utils.readMagic(in0))) {
 108                 if (verbose > 0)
 109                     Utils.log.info("Copying unpacked JAR file...");
 110                 Utils.copyJarFile(new JarInputStream(in0), out);
 111             } else if (props.getBoolean(Utils.DEBUG_DISABLE_NATIVE)) {
 112                 (new DoUnpack()).run(in0, out);
 113                 in0.close();
 114                 Utils.markJarFile(out);
 115             } else {
 116                 try {
 117                     (new NativeUnpack(this)).run(in0, out);
 118                 } catch (UnsatisfiedLinkError | NoClassDefFoundError ex) {
 119                     // failover to java implementation
 120                     (new DoUnpack()).run(in0, out);
 121                 }
 122                 in0.close();
 123                 Utils.markJarFile(out);
 124             }
 125         } finally {
 126             _nunp = null;
 127             Utils.currentInstance.set(null);
 128             if (tz != null) TimeZone.setDefault(tz);
 129         }
 130     }
 131 
 132     /**
 133      * Takes an input File containing the pack file, and generates a JarOutputStream.
 134      * <p>
 135      * Does not close its output.  (The output can accumulate more elements.)
 136      * @param in a File.
 137      * @param out a JarOutputStream.
 138      * @exception IOException if an error is encountered.
 139      */
 140     public synchronized void unpack(File in, JarOutputStream out) throws IOException {
 141         if (in == null) {
 142             throw new NullPointerException("null input");
 143         }
 144         if (out == null) {
 145             throw new NullPointerException("null output");
 146         }
 147         // Use the stream-based implementation.
 148         // %%% Reconsider if native unpacker learns to memory-map the file.
 149         try (FileInputStream instr = new FileInputStream(in)) {
 150             unpack(instr, out);
 151         }
 152         if (props.getBoolean(Utils.UNPACK_REMOVE_PACKFILE)) {
 153             in.delete();
 154         }
 155     }
 156 
 157     private class DoUnpack {
 158         final int verbose = props.getInteger(Utils.DEBUG_VERBOSE);
 159 
 160         {
 161             props.setInteger(Pack200.Unpacker.PROGRESS, 0);
 162         }
 163 
 164         // Here's where the bits are read from disk:
 165         final Package pkg = new Package();
 166 
 167         final boolean keepModtime
 168             = Pack200.Packer.KEEP.equals(
 169               props.getProperty(Utils.UNPACK_MODIFICATION_TIME, Pack200.Packer.KEEP));
 170         final boolean keepDeflateHint
 171             = Pack200.Packer.KEEP.equals(
 172               props.getProperty(Pack200.Unpacker.DEFLATE_HINT, Pack200.Packer.KEEP));
 173         final int modtime;
 174         final boolean deflateHint;
 175         {
 176             if (!keepModtime) {
 177                 modtime = props.getTime(Utils.UNPACK_MODIFICATION_TIME);
 178             } else {
 179                 modtime = pkg.default_modtime;
 180             }
 181 
 182             deflateHint = (keepDeflateHint) ? false :
 183                 props.getBoolean(java.util.jar.Pack200.Unpacker.DEFLATE_HINT);
 184         }
 185 
 186         // Checksum apparatus.
 187         final CRC32 crc = new CRC32();
 188         final ByteArrayOutputStream bufOut = new ByteArrayOutputStream();
 189         final OutputStream crcOut = new CheckedOutputStream(bufOut, crc);
 190 
 191         public void run(BufferedInputStream in, JarOutputStream out) throws IOException {
 192             if (verbose > 0) {
 193                 props.list(System.out);
 194             }
 195             for (int seg = 1; ; seg++) {
 196                 unpackSegment(in, out);
 197 
 198                 // Try to get another segment.
 199                 if (!Utils.isPackMagic(Utils.readMagic(in)))  break;
 200                 if (verbose > 0)
 201                     Utils.log.info("Finished segment #"+seg);
 202             }
 203         }
 204 
 205         private void unpackSegment(InputStream in, JarOutputStream out) throws IOException {
 206             props.setProperty(java.util.jar.Pack200.Unpacker.PROGRESS,"0");
 207             // Process the output directory or jar output.
 208             new PackageReader(pkg, in).read();
 209 
 210             if (props.getBoolean("unpack.strip.debug"))    pkg.stripAttributeKind("Debug");
 211             if (props.getBoolean("unpack.strip.compile"))  pkg.stripAttributeKind("Compile");
 212             props.setProperty(java.util.jar.Pack200.Unpacker.PROGRESS,"50");
 213             pkg.ensureAllClassFiles();
 214             // Now write out the files.
 215             Set<Package.Class> classesToWrite = new HashSet<>(pkg.getClasses());
 216             for (Package.File file : pkg.getFiles()) {
 217                 String name = file.nameString;
 218                 JarEntry je = new JarEntry(Utils.getJarEntryName(name));
 219                 boolean deflate;
 220 
 221                 deflate = (keepDeflateHint)
 222                           ? (((file.options & Constants.FO_DEFLATE_HINT) != 0) ||
 223                             ((pkg.default_options & Constants.AO_DEFLATE_HINT) != 0))
 224                           : deflateHint;
 225 
 226                 boolean needCRC = !deflate;  // STORE mode requires CRC
 227 
 228                 if (needCRC)  crc.reset();
 229                 bufOut.reset();
 230                 if (file.isClassStub()) {
 231                     Package.Class cls = file.getStubClass();
 232                     assert(cls != null);
 233                     new ClassWriter(cls, needCRC ? crcOut : bufOut).write();
 234                     classesToWrite.remove(cls);  // for an error check
 235                 } else {
 236                     // collect data & maybe CRC
 237                     file.writeTo(needCRC ? crcOut : bufOut);
 238                 }
 239                 je.setMethod(deflate ? JarEntry.DEFLATED : JarEntry.STORED);
 240                 if (needCRC) {
 241                     if (verbose > 0)
 242                         Utils.log.info("stored size="+bufOut.size()+" and crc="+crc.getValue());
 243 
 244                     je.setMethod(JarEntry.STORED);
 245                     je.setSize(bufOut.size());
 246                     je.setCrc(crc.getValue());
 247                 }
 248                 if (keepModtime) {
 249                     je.setTime(file.modtime);
 250                     // Convert back to milliseconds
 251                     je.setTime((long)file.modtime * 1000);
 252                 } else {
 253                     je.setTime((long)modtime * 1000);
 254                 }
 255                 out.putNextEntry(je);
 256                 bufOut.writeTo(out);
 257                 out.closeEntry();
 258                 if (verbose > 0)
 259                     Utils.log.info("Writing "+Utils.zeString((ZipEntry)je));
 260             }
 261             assert(classesToWrite.isEmpty());
 262             props.setProperty(java.util.jar.Pack200.Unpacker.PROGRESS,"100");
 263             pkg.reset();  // reset for the next segment, if any
 264         }
 265     }
 266 }