1 /*
   2  * Copyright (c) 2003, 2012, 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 
  27 package com.sun.java.util.jar.pack;
  28 
  29 import java.io.BufferedInputStream;
  30 import java.io.File;
  31 import java.io.FileInputStream;
  32 import java.io.IOException;
  33 import java.io.InputStream;
  34 import java.nio.ByteBuffer;
  35 import java.util.jar.JarOutputStream;
  36 import java.util.jar.Pack200;
  37 import java.util.zip.CRC32;
  38 import java.util.zip.Deflater;
  39 import java.util.zip.ZipEntry;
  40 import java.util.zip.ZipOutputStream;
  41 
  42 class NativeUnpack {
  43     // Pointer to the native unpacker obj
  44     private long unpackerPtr;
  45 
  46     // Input stream.
  47     private BufferedInputStream in;
  48 
  49     private static synchronized native void initIDs();
  50 
  51     // Starts processing at the indicated position in the buffer.
  52     // If the buffer is null, the readInputFn callback is used to get bytes.
  53     // Returns (s<<32|f), the number of following segments and files.
  54     private synchronized native long start(ByteBuffer buf, long offset);
  55 
  56     // Returns true if there's another, and fills in the parts.
  57     private synchronized native boolean getNextFile(Object[] parts);
  58 
  59     private synchronized native ByteBuffer getUnusedInput();
  60 
  61     // Resets the engine and frees all resources.
  62     // Returns total number of bytes consumed by the engine.
  63     private synchronized native long finish();
  64 
  65     // Setting state in the unpacker.
  66     protected  synchronized native boolean setOption(String opt, String value);
  67     protected  synchronized native String getOption(String opt);
  68 
  69     private  int _verbose;
  70 
  71     // State for progress bar:
  72     private  long _byteCount;      // bytes read in current segment
  73     private  int  _segCount;       // number of segs scanned
  74     private  int  _fileCount;      // number of files written
  75     private  long _estByteLimit;   // estimate of eventual total
  76     private  int  _estSegLimit;    // ditto
  77     private  int  _estFileLimit;   // ditto
  78     private  int  _prevPercent = -1; // for monotonicity
  79 
  80     private final CRC32   _crc32 = new CRC32();
  81     private       byte[]  _buf   = new byte[1<<14];
  82 
  83     private  UnpackerImpl _p200;
  84     private  PropMap _props;
  85 
  86     static {
  87         // If loading from stand alone build uncomment this.
  88         // System.loadLibrary("unpack");
  89         java.security.AccessController.doPrivileged(
  90                 new sun.security.action.LoadLibraryAction("unpack"));
  91         initIDs();
  92     }
  93 
  94     NativeUnpack(UnpackerImpl p200) {
  95         super();
  96         _p200  = p200;
  97         _props = p200.props;
  98         p200._nunp = this;
  99     }
 100 
 101     // for JNI callbacks
 102     static private Object currentInstance() {
 103         UnpackerImpl p200 = (UnpackerImpl) Utils.getTLGlobals();
 104         return (p200 == null)? null: p200._nunp;
 105     }
 106 
 107     private synchronized long getUnpackerPtr() {
 108         return unpackerPtr;
 109     }
 110 
 111     // Callback from the unpacker engine to get more data.
 112     private long readInputFn(ByteBuffer pbuf, long minlen) throws IOException {
 113         if (in == null)  return 0;  // nothing is readable
 114         long maxlen = pbuf.capacity() - pbuf.position();
 115         assert(minlen <= maxlen);  // don't talk nonsense
 116         long numread = 0;
 117         int steps = 0;
 118         while (numread < minlen) {
 119             steps++;
 120             // read available input, up to buf.length or maxlen
 121             int readlen = _buf.length;
 122             if (readlen > (maxlen - numread))
 123                 readlen = (int)(maxlen - numread);
 124             int nr = in.read(_buf, 0, readlen);
 125             if (nr <= 0)  break;
 126             numread += nr;
 127             assert(numread <= maxlen);
 128             // %%% get rid of this extra copy by using nio?
 129             pbuf.put(_buf, 0, nr);
 130         }
 131         if (_verbose > 1)
 132             Utils.log.fine("readInputFn("+minlen+","+maxlen+") => "+numread+" steps="+steps);
 133         if (maxlen > 100) {
 134             _estByteLimit = _byteCount + maxlen;
 135         } else {
 136             _estByteLimit = (_byteCount + numread) * 20;
 137         }
 138         _byteCount += numread;
 139         updateProgress();
 140         return numread;
 141     }
 142 
 143     private void updateProgress() {
 144         // Progress is a combination of segment reading and file writing.
 145         final double READ_WT  = 0.33;
 146         final double WRITE_WT = 0.67;
 147         double readProgress = _segCount;
 148         if (_estByteLimit > 0 && _byteCount > 0)
 149             readProgress += (double)_byteCount / _estByteLimit;
 150         double writeProgress = _fileCount;
 151         double scaledProgress
 152             = READ_WT  * readProgress  / Math.max(_estSegLimit,1)
 153             + WRITE_WT * writeProgress / Math.max(_estFileLimit,1);
 154         int percent = (int) Math.round(100*scaledProgress);
 155         if (percent > 100)  percent = 100;
 156         if (percent > _prevPercent) {
 157             _prevPercent = percent;
 158             _props.setInteger(Pack200.Unpacker.PROGRESS, percent);
 159             if (_verbose > 0)
 160                 Utils.log.info("progress = "+percent);
 161         }
 162     }
 163 
 164     private void copyInOption(String opt) {
 165         String val = _props.getProperty(opt);
 166         if (_verbose > 0)
 167             Utils.log.info("set "+opt+"="+val);
 168         if (val != null) {
 169             boolean set = setOption(opt, val);
 170             if (!set)
 171                 Utils.log.warning("Invalid option "+opt+"="+val);
 172         }
 173     }
 174 
 175     void run(InputStream inRaw, JarOutputStream jstream,
 176              ByteBuffer presetInput) throws IOException {
 177         BufferedInputStream in0 = new BufferedInputStream(inRaw);
 178         this.in = in0;    // for readInputFn to see
 179         _verbose = _props.getInteger(Utils.DEBUG_VERBOSE);
 180         // Fix for BugId: 4902477, -unpack.modification.time = 1059010598000
 181         // TODO eliminate and fix in unpack.cpp
 182 
 183         final int modtime = Pack200.Packer.KEEP.equals(_props.getProperty(Utils.UNPACK_MODIFICATION_TIME, "0")) ?
 184                 Constants.NO_MODTIME : _props.getTime(Utils.UNPACK_MODIFICATION_TIME);
 185 
 186         copyInOption(Utils.DEBUG_VERBOSE);
 187         copyInOption(Pack200.Unpacker.DEFLATE_HINT);
 188         if (modtime == Constants.NO_MODTIME)  // Dont pass KEEP && NOW
 189             copyInOption(Utils.UNPACK_MODIFICATION_TIME);
 190         updateProgress();  // reset progress bar
 191         for (;;) {
 192             // Read the packed bits.
 193             long counts = start(presetInput, 0);
 194             _byteCount = _estByteLimit = 0;  // reset partial scan counts
 195             ++_segCount;  // just finished scanning a whole segment...
 196             int nextSeg  = (int)( counts >>> 32 );
 197             int nextFile = (int)( counts >>>  0 );
 198 
 199             // Estimate eventual total number of segments and files.
 200             _estSegLimit = _segCount + nextSeg;
 201             double filesAfterThisSeg = _fileCount + nextFile;
 202             _estFileLimit = (int)( (filesAfterThisSeg *
 203                                     _estSegLimit) / _segCount );
 204 
 205             // Write the files.
 206             int[] intParts = { 0,0, 0, 0 };
 207             //    intParts = {size.hi/lo, mod, defl}
 208             Object[] parts = { intParts, null, null, null };
 209             //       parts = { {intParts}, name, data0/1 }
 210             while (getNextFile(parts)) {
 211                 //BandStructure.printArrayTo(System.out, intParts, 0, parts.length);
 212                 String name = (String) parts[1];
 213                 long   size = ( (long)intParts[0] << 32)
 214                             + (((long)intParts[1] << 32) >>> 32);
 215 
 216                 long   mtime = (modtime != Constants.NO_MODTIME ) ?
 217                                 modtime : intParts[2] ;
 218                 boolean deflateHint = (intParts[3] != 0);
 219                 ByteBuffer data0 = (ByteBuffer) parts[2];
 220                 ByteBuffer data1 = (ByteBuffer) parts[3];
 221                 writeEntry(jstream, name, mtime, size, deflateHint,
 222                            data0, data1);
 223                 ++_fileCount;
 224                 updateProgress();
 225             }
 226             presetInput = getUnusedInput();
 227             long consumed = finish();
 228             if (_verbose > 0)
 229                 Utils.log.info("bytes consumed = "+consumed);
 230             if (presetInput == null &&
 231                 !Utils.isPackMagic(Utils.readMagic(in0))) {
 232                 break;
 233             }
 234             if (_verbose > 0 ) {
 235                 if (presetInput != null)
 236                     Utils.log.info("unused input = "+presetInput);
 237             }
 238         }
 239     }
 240 
 241     void run(InputStream in, JarOutputStream jstream) throws IOException {
 242         run(in, jstream, null);
 243     }
 244 
 245     void run(File inFile, JarOutputStream jstream) throws IOException {
 246         // %%% maybe memory-map the file, and pass it straight into unpacker
 247         ByteBuffer mappedFile = null;
 248         try (FileInputStream fis = new FileInputStream(inFile)) {
 249             run(fis, jstream, mappedFile);
 250         }
 251         // Note:  caller is responsible to finish with jstream.
 252     }
 253 
 254     private void writeEntry(JarOutputStream j, String name,
 255                             long mtime, long lsize, boolean deflateHint,
 256                             ByteBuffer data0, ByteBuffer data1) throws IOException {
 257         int size = (int)lsize;
 258         if (size != lsize)
 259             throw new IOException("file too large: "+lsize);
 260 
 261         CRC32 crc32 = _crc32;
 262 
 263         if (_verbose > 1)
 264             Utils.log.fine("Writing entry: "+name+" size="+size
 265                              +(deflateHint?" deflated":""));
 266 
 267         if (_buf.length < size) {
 268             int newSize = size;
 269             while (newSize < _buf.length) {
 270                 newSize <<= 1;
 271                 if (newSize <= 0) {
 272                     newSize = size;
 273                     break;
 274                 }
 275             }
 276             _buf = new byte[newSize];
 277         }
 278         assert(_buf.length >= size);
 279 
 280         int fillp = 0;
 281         if (data0 != null) {
 282             int size0 = data0.capacity();
 283             data0.get(_buf, fillp, size0);
 284             fillp += size0;
 285         }
 286         if (data1 != null) {
 287             int size1 = data1.capacity();
 288             data1.get(_buf, fillp, size1);
 289             fillp += size1;
 290         }
 291         while (fillp < size) {
 292             // Fill in rest of data from the stream itself.
 293             int nr = in.read(_buf, fillp, size - fillp);
 294             if (nr <= 0)  throw new IOException("EOF at end of archive");
 295             fillp += nr;
 296         }
 297 
 298         ZipEntry z = new ZipEntry(name);
 299         z.setTime( (long)mtime * 1000);
 300 
 301         if (size == 0) {
 302             z.setMethod(ZipOutputStream.STORED);
 303             z.setSize(0);
 304             z.setCrc(0);
 305             z.setCompressedSize(0);
 306         } else if (!deflateHint) {
 307             z.setMethod(ZipOutputStream.STORED);
 308             z.setSize(size);
 309             z.setCompressedSize(size);
 310             crc32.reset();
 311             crc32.update(_buf, 0, size);
 312             z.setCrc(crc32.getValue());
 313         } else {
 314             z.setMethod(Deflater.DEFLATED);
 315             z.setSize(size);
 316         }
 317 
 318         j.putNextEntry(z);
 319 
 320         if (size > 0)
 321             j.write(_buf, 0, size);
 322 
 323         j.closeEntry();
 324         if (_verbose > 0) Utils.log.info("Writing " + Utils.zeString(z));
 325     }
 326 }