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