001 /*
002 * Copyright 1996-2006 Sun Microsystems, Inc. All Rights Reserved.
003 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
004 *
005 * This code is free software; you can redistribute it and/or modify it
006 * under the terms of the GNU General Public License version 2 only, as
007 * published by the Free Software Foundation. Sun designates this
008 * particular file as subject to the "Classpath" exception as provided
009 * by Sun in the LICENSE file that accompanied this code.
010 *
011 * This code is distributed in the hope that it will be useful, but WITHOUT
012 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
013 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
014 * version 2 for more details (a copy is included in the LICENSE file that
015 * accompanied this code).
016 *
017 * You should have received a copy of the GNU General Public License version
018 * 2 along with this work; if not, write to the Free Software Foundation,
019 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
020 *
021 * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
022 * CA 95054 USA or visit www.sun.com if you need additional information or
023 * have any questions.
024 */
025
026 package java.util.zip;
027
028 import java.io.InputStream;
029 import java.io.IOException;
030 import java.io.EOFException;
031 import java.io.PushbackInputStream;
032
033 /**
034 * This class implements an input stream filter for reading files in the
035 * ZIP file format. Includes support for both compressed and uncompressed
036 * entries.
037 *
038 * @author David Connelly
039 * @version 1.50, 05/05/07
040 */
041 public class ZipInputStream extends InflaterInputStream implements
042 ZipConstants {
043 private ZipEntry entry;
044 private int flag;
045 private CRC32 crc = new CRC32();
046 private long remaining;
047 private byte[] tmpbuf = new byte[512];
048
049 private static final int STORED = ZipEntry.STORED;
050 private static final int DEFLATED = ZipEntry.DEFLATED;
051
052 private boolean closed = false;
053 // this flag is set to true after EOF has reached for
054 // one entry
055 private boolean entryEOF = false;
056
057 /**
058 * Check to make sure that this stream has not been closed
059 */
060 private void ensureOpen() throws IOException {
061 if (closed) {
062 throw new IOException("Stream closed");
063 }
064 }
065
066 /**
067 * Creates a new ZIP input stream.
068 * @param in the actual input stream
069 */
070 public ZipInputStream(InputStream in) {
071 super (new PushbackInputStream(in, 512), new Inflater(true), 512);
072 usesDefaultInflater = true;
073 if (in == null) {
074 throw new NullPointerException("in is null");
075 }
076 }
077
078 /**
079 * Reads the next ZIP file entry and positions the stream at the
080 * beginning of the entry data.
081 * @return the next ZIP file entry, or null if there are no more entries
082 * @exception ZipException if a ZIP file error has occurred
083 * @exception IOException if an I/O error has occurred
084 */
085 public ZipEntry getNextEntry() throws IOException {
086 ensureOpen();
087 if (entry != null) {
088 closeEntry();
089 }
090 crc.reset();
091 inf.reset();
092 if ((entry = readLOC()) == null) {
093 return null;
094 }
095 if (entry.method == STORED) {
096 remaining = entry.size;
097 }
098 entryEOF = false;
099 return entry;
100 }
101
102 /**
103 * Closes the current ZIP entry and positions the stream for reading the
104 * next entry.
105 * @exception ZipException if a ZIP file error has occurred
106 * @exception IOException if an I/O error has occurred
107 */
108 public void closeEntry() throws IOException {
109 ensureOpen();
110 while (read(tmpbuf, 0, tmpbuf.length) != -1)
111 ;
112 entryEOF = true;
113 }
114
115 /**
116 * Returns 0 after EOF has reached for the current entry data,
117 * otherwise always return 1.
118 * <p>
119 * Programs should not count on this method to return the actual number
120 * of bytes that could be read without blocking.
121 *
122 * @return 1 before EOF and 0 after EOF has reached for current entry.
123 * @exception IOException if an I/O error occurs.
124 *
125 */
126 public int available() throws IOException {
127 ensureOpen();
128 if (entryEOF) {
129 return 0;
130 } else {
131 return 1;
132 }
133 }
134
135 /**
136 * Reads from the current ZIP entry into an array of bytes.
137 * If <code>len</code> is not zero, the method
138 * blocks until some input is available; otherwise, no
139 * bytes are read and <code>0</code> is returned.
140 * @param b the buffer into which the data is read
141 * @param off the start offset in the destination array <code>b</code>
142 * @param len the maximum number of bytes read
143 * @return the actual number of bytes read, or -1 if the end of the
144 * entry is reached
145 * @exception NullPointerException If <code>b</code> is <code>null</code>.
146 * @exception IndexOutOfBoundsException If <code>off</code> is negative,
147 * <code>len</code> is negative, or <code>len</code> is greater than
148 * <code>b.length - off</code>
149 * @exception ZipException if a ZIP file error has occurred
150 * @exception IOException if an I/O error has occurred
151 */
152 public int read(byte[] b, int off, int len) throws IOException {
153 ensureOpen();
154 if (off < 0 || len < 0 || off > b.length - len) {
155 throw new IndexOutOfBoundsException();
156 } else if (len == 0) {
157 return 0;
158 }
159
160 if (entry == null) {
161 return -1;
162 }
163 switch (entry.method) {
164 case DEFLATED:
165 len = super .read(b, off, len);
166 if (len == -1) {
167 readEnd(entry);
168 entryEOF = true;
169 entry = null;
170 } else {
171 crc.update(b, off, len);
172 }
173 return len;
174 case STORED:
175 if (remaining <= 0) {
176 entryEOF = true;
177 entry = null;
178 return -1;
179 }
180 if (len > remaining) {
181 len = (int) remaining;
182 }
183 len = in.read(b, off, len);
184 if (len == -1) {
185 throw new ZipException("unexpected EOF");
186 }
187 crc.update(b, off, len);
188 remaining -= len;
189 if (remaining == 0 && entry.crc != crc.getValue()) {
190 throw new ZipException("invalid entry CRC (expected 0x"
191 + Long.toHexString(entry.crc) + " but got 0x"
192 + Long.toHexString(crc.getValue()) + ")");
193 }
194 return len;
195 default:
196 throw new ZipException("invalid compression method");
197 }
198 }
199
200 /**
201 * Skips specified number of bytes in the current ZIP entry.
202 * @param n the number of bytes to skip
203 * @return the actual number of bytes skipped
204 * @exception ZipException if a ZIP file error has occurred
205 * @exception IOException if an I/O error has occurred
206 * @exception IllegalArgumentException if n < 0
207 */
208 public long skip(long n) throws IOException {
209 if (n < 0) {
210 throw new IllegalArgumentException("negative skip length");
211 }
212 ensureOpen();
213 int max = (int) Math.min(n, Integer.MAX_VALUE);
214 int total = 0;
215 while (total < max) {
216 int len = max - total;
217 if (len > tmpbuf.length) {
218 len = tmpbuf.length;
219 }
220 len = read(tmpbuf, 0, len);
221 if (len == -1) {
222 entryEOF = true;
223 break;
224 }
225 total += len;
226 }
227 return total;
228 }
229
230 /**
231 * Closes this input stream and releases any system resources associated
232 * with the stream.
233 * @exception IOException if an I/O error has occurred
234 */
235 public void close() throws IOException {
236 if (!closed) {
237 super .close();
238 closed = true;
239 }
240 }
241
242 private byte[] b = new byte[256];
243
244 /*
245 * Reads local file (LOC) header for next entry.
246 */
247 private ZipEntry readLOC() throws IOException {
248 try {
249 readFully(tmpbuf, 0, LOCHDR);
250 } catch (EOFException e) {
251 return null;
252 }
253 if (get32(tmpbuf, 0) != LOCSIG) {
254 return null;
255 }
256 // get the entry name and create the ZipEntry first
257 int len = get16(tmpbuf, LOCNAM);
258 int blen = b.length;
259 if (len > blen) {
260 do
261 blen = blen * 2;
262 while (len > blen);
263 b = new byte[blen];
264 }
265 readFully(b, 0, len);
266 ZipEntry e = createZipEntry(getUTF8String(b, 0, len));
267 // now get the remaining fields for the entry
268 flag = get16(tmpbuf, LOCFLG);
269 if ((flag & 1) == 1) {
270 throw new ZipException("encrypted ZIP entry not supported");
271 }
272 e.method = get16(tmpbuf, LOCHOW);
273 e.time = get32(tmpbuf, LOCTIM);
274 if ((flag & 8) == 8) {
275 /* "Data Descriptor" present */
276 if (e.method != DEFLATED) {
277 throw new ZipException(
278 "only DEFLATED entries can have EXT descriptor");
279 }
280 } else {
281 e.crc = get32(tmpbuf, LOCCRC);
282 e.csize = get32(tmpbuf, LOCSIZ);
283 e.size = get32(tmpbuf, LOCLEN);
284 }
285 len = get16(tmpbuf, LOCEXT);
286 if (len > 0) {
287 byte[] bb = new byte[len];
288 readFully(bb, 0, len);
289 e.setExtra(bb);
290 }
291 return e;
292 }
293
294 /*
295 * Fetches a UTF8-encoded String from the specified byte array.
296 */
297 private static String getUTF8String(byte[] b, int off, int len) {
298 // First, count the number of characters in the sequence
299 int count = 0;
300 int max = off + len;
301 int i = off;
302 while (i < max) {
303 int c = b[i++] & 0xff;
304 switch (c >> 4) {
305 case 0:
306 case 1:
307 case 2:
308 case 3:
309 case 4:
310 case 5:
311 case 6:
312 case 7:
313 // 0xxxxxxx
314 count++;
315 break;
316 case 12:
317 case 13:
318 // 110xxxxx 10xxxxxx
319 if ((int) (b[i++] & 0xc0) != 0x80) {
320 throw new IllegalArgumentException();
321 }
322 count++;
323 break;
324 case 14:
325 // 1110xxxx 10xxxxxx 10xxxxxx
326 if (((int) (b[i++] & 0xc0) != 0x80)
327 || ((int) (b[i++] & 0xc0) != 0x80)) {
328 throw new IllegalArgumentException();
329 }
330 count++;
331 break;
332 default:
333 // 10xxxxxx, 1111xxxx
334 throw new IllegalArgumentException();
335 }
336 }
337 if (i != max) {
338 throw new IllegalArgumentException();
339 }
340 // Now decode the characters...
341 char[] cs = new char[count];
342 i = 0;
343 while (off < max) {
344 int c = b[off++] & 0xff;
345 switch (c >> 4) {
346 case 0:
347 case 1:
348 case 2:
349 case 3:
350 case 4:
351 case 5:
352 case 6:
353 case 7:
354 // 0xxxxxxx
355 cs[i++] = (char) c;
356 break;
357 case 12:
358 case 13:
359 // 110xxxxx 10xxxxxx
360 cs[i++] = (char) (((c & 0x1f) << 6) | (b[off++] & 0x3f));
361 break;
362 case 14:
363 // 1110xxxx 10xxxxxx 10xxxxxx
364 int t = (b[off++] & 0x3f) << 6;
365 cs[i++] = (char) (((c & 0x0f) << 12) | t | (b[off++] & 0x3f));
366 break;
367 default:
368 // 10xxxxxx, 1111xxxx
369 throw new IllegalArgumentException();
370 }
371 }
372 return new String(cs, 0, count);
373 }
374
375 /**
376 * Creates a new <code>ZipEntry</code> object for the specified
377 * entry name.
378 *
379 * @param name the ZIP file entry name
380 * @return the ZipEntry just created
381 */
382 protected ZipEntry createZipEntry(String name) {
383 return new ZipEntry(name);
384 }
385
386 /*
387 * Reads end of deflated entry as well as EXT descriptor if present.
388 */
389 private void readEnd(ZipEntry e) throws IOException {
390 int n = inf.getRemaining();
391 if (n > 0) {
392 ((PushbackInputStream) in).unread(buf, len - n, n);
393 }
394 if ((flag & 8) == 8) {
395 /* "Data Descriptor" present */
396 readFully(tmpbuf, 0, EXTHDR);
397 long sig = get32(tmpbuf, 0);
398 if (sig != EXTSIG) { // no EXTSIG present
399 e.crc = sig;
400 e.csize = get32(tmpbuf, EXTSIZ - EXTCRC);
401 e.size = get32(tmpbuf, EXTLEN - EXTCRC);
402 ((PushbackInputStream) in).unread(tmpbuf, EXTHDR
403 - EXTCRC - 1, EXTCRC);
404 } else {
405 e.crc = get32(tmpbuf, EXTCRC);
406 e.csize = get32(tmpbuf, EXTSIZ);
407 e.size = get32(tmpbuf, EXTLEN);
408 }
409 }
410 if (e.size != inf.getBytesWritten()) {
411 throw new ZipException("invalid entry size (expected "
412 + e.size + " but got " + inf.getBytesWritten()
413 + " bytes)");
414 }
415 if (e.csize != inf.getBytesRead()) {
416 throw new ZipException(
417 "invalid entry compressed size (expected "
418 + e.csize + " but got "
419 + inf.getBytesRead() + " bytes)");
420 }
421 if (e.crc != crc.getValue()) {
422 throw new ZipException("invalid entry CRC (expected 0x"
423 + Long.toHexString(e.crc) + " but got 0x"
424 + Long.toHexString(crc.getValue()) + ")");
425 }
426 }
427
428 /*
429 * Reads bytes, blocking until all bytes are read.
430 */
431 private void readFully(byte[] b, int off, int len)
432 throws IOException {
433 while (len > 0) {
434 int n = in.read(b, off, len);
435 if (n == -1) {
436 throw new EOFException();
437 }
438 off += n;
439 len -= n;
440 }
441 }
442
443 /*
444 * Fetches unsigned 16-bit value from byte array at specified offset.
445 * The bytes are assumed to be in Intel (little-endian) byte order.
446 */
447 private static final int get16(byte b[], int off) {
448 return (b[off] & 0xff) | ((b[off + 1] & 0xff) << 8);
449 }
450
451 /*
452 * Fetches unsigned 32-bit value from byte array at specified offset.
453 * The bytes are assumed to be in Intel (little-endian) byte order.
454 */
455 private static final long get32(byte b[], int off) {
456 return get16(b, off) | ((long) get16(b, off + 2) << 16);
457 }
458 }
|