1 // Copyright (C) 2003 Adam Megacz <adam@ibex.org> all rights reserved.
3 // You may modify, copy, and redistribute this code under the terms of
4 // the GNU Library Public License version 2.1, with the exception of
5 // the portion of clause 6a after the semicolon (aka the "obnoxious
12 import java.util.zip.*;
14 /** Reads a CAB file structure */
17 /** reads a CAB file, parses it, and returns an InputStream representing the named file */
18 public static InputStream getFileInputStream(InputStream is, String fileName) throws IOException, EOFException {
19 return getFileInputStream(is, 0, fileName);
22 public static InputStream getFileInputStream(InputStream is, int skipHeaders, String fileName) throws IOException, EOFException {
23 DataInputStream dis = new DataInputStream(is);
24 CFHEADER h = new CFHEADER();
26 while (skipHeaders > 0) { CFHEADER.seekMSCF(dis); skipHeaders--; }
30 } catch (CFHEADER.BogusHeaderException bhe) {
31 throw new EOFException();
34 for(int i=0; i<h.folders.length; i++) {
35 CFFOLDER f = new CFFOLDER(h);
38 } catch (CFFOLDER.UnsupportedCompressionTypeException ucte) {
43 for(int i=0; i<h.files.length; i++) {
44 CFFILE f = new CFFILE(h);
48 for(int i=0; i<h.folders.length; i++) {
49 InputStream is2 = new CFFOLDERInputStream(h.folders[i], dis);
50 for(int j=0; j<h.folders[i].files.size(); j++) {
51 CFFILE file = (CFFILE)h.folders[i].files.elementAt(j);
52 if (file.fileName.equals(fileName)) return new LimitStream(is2, file.fileSize);
53 byte[] b = new byte[file.fileSize];
60 private static class LimitStream extends FilterInputStream {
62 public LimitStream(InputStream is, int limit) {
66 public int read() throws IOException {
67 if (limit == 0) return -1;
68 int ret = super.read();
69 if (ret != -1) limit--;
72 public int read(byte[] b, int off, int len) throws IOException {
73 if (len > limit) len = limit;
74 if (limit == 0) return -1;
75 int ret = super.read(b, off, len);
81 /** Encapsulates a CFHEADER entry */
82 public static class CFHEADER {
83 byte[] reserved1 = new byte[4]; // reserved
84 int fileSize = 0; // size of this cabinet file in bytes
85 byte[] reserved2 = new byte[4]; // reserved
86 int offsetOfFirstCFFILEEntry; // offset of the first CFFILE entry
87 byte[] reserved3 = new byte[4]; // reserved
88 byte versionMinor = 3; // cabinet file format version, minor
89 byte versionMajor = 1; // cabinet file format version, major
90 boolean prevCAB = false; // true iff there is a cabinet before this one in a sequence
91 boolean nextCAB = false; // true iff there is a cabinet after this one in a sequence
92 boolean hasReserved = false; // true iff the cab has per-{cabinet, folder, block} reserved areas
93 int setID = 0; // must be the same for all cabinets in a set
94 int indexInCabinetSet = 0; // number of this cabinet file in a set
95 byte perCFFOLDERReservedSize = 0; // (optional) size of per-folder reserved area
96 byte perDatablockReservedSize = 0; // (optional) size of per-datablock reserved area
97 byte[] perCabinetReservedArea = null; // per-cabinet reserved area
98 String previousCabinet = null; // name of previous cabinet file in a set
99 String previousDisk = null; // name of previous disk in a set
100 String nextCabinet = null; // name of next cabinet in a set
101 String nextDisk = null; // name of next disk in a set
103 CFFOLDER[] folders = new CFFOLDER[0];
104 CFFILE[] files = new CFFILE[0];
106 int readCFFOLDERs = 0; // the number of folders read in so far
107 int readCFFILEs = 0; // the number of folders read in so far
109 public void print(PrintStream ps) {
110 ps.println("CAB CFFILE CFHEADER v" + ((int)versionMajor) + "." + ((int)versionMinor));
111 ps.println(" total file size = " + fileSize);
112 ps.println(" offset of first file = " + offsetOfFirstCFFILEEntry);
113 ps.println(" total folders = " + folders.length);
114 ps.println(" total files = " + files.length);
115 ps.println(" flags = 0x" +
116 Integer.toString((prevCAB ? 0x1 : 0x0) |
117 (nextCAB ? 0x2 : 0x0) |
118 (hasReserved ? 0x4 : 0x0), 16) + " [ " +
119 (prevCAB ? "prev " : "") +
120 (nextCAB ? "next " : "") +
121 (hasReserved ? "reserve_present " : "") + "]");
122 ps.println(" set id = " + setID);
123 ps.println(" index in set = " + indexInCabinetSet);
124 ps.println(" header reserved area #1 =" +
125 " 0x" + Integer.toString(reserved1[0], 16) +
126 " 0x" + Integer.toString(reserved1[1], 16) +
127 " 0x" + Integer.toString(reserved1[2], 16) +
128 " 0x" + Integer.toString(reserved1[3], 16));
129 ps.println(" header reserved area #2 =" +
130 " 0x" + Integer.toString(reserved2[0], 16) +
131 " 0x" + Integer.toString(reserved2[1], 16) +
132 " 0x" + Integer.toString(reserved2[2], 16) +
133 " 0x" + Integer.toString(reserved2[3], 16));
134 ps.println(" header reserved area #3 =" +
135 " 0x" + Integer.toString(reserved3[0], 16) +
136 " 0x" + Integer.toString(reserved3[1], 16) +
137 " 0x" + Integer.toString(reserved3[2], 16) +
138 " 0x" + Integer.toString(reserved3[3], 16));
140 if (perCabinetReservedArea != null) {
141 ps.print(" per-cabinet reserved area = ");
142 for(int i=0; i<perCabinetReservedArea.length; i++)
143 ps.print(((perCabinetReservedArea[i] & 0xff) < 16 ? "0" : "") +
144 Integer.toString(perCabinetReservedArea[i] & 0xff, 16) + " ");
147 ps.println(" per folder reserved area = " + perCFFOLDERReservedSize + " bytes");
148 ps.println(" per block reserved area = " + perDatablockReservedSize + " bytes");
152 public String toString() {
154 "[ CAB CFFILE CFHEADER v" +
155 ((int)versionMajor) + "." + ((int)versionMinor) + ", " +
156 fileSize + " bytes, " +
157 folders.length + " folders, " +
158 files.length + " files] ";
161 /** fills in all fields in the header and positions the stream at the first folder */
162 public void read(DataInputStream dis) throws IOException, BogusHeaderException {
164 dis.readFully(reserved1);
166 byte[] headerHashable = new byte[28];
167 dis.readFully(headerHashable);
168 DataInputStream hhis = new DataInputStream(new ByteArrayInputStream(headerHashable));
170 fileSize = readLittleInt(hhis);
171 hhis.readFully(reserved2);
172 offsetOfFirstCFFILEEntry = readLittleInt(hhis);
173 hhis.readFully(reserved3);
174 versionMinor = hhis.readByte();
175 versionMajor = hhis.readByte();
176 folders = new CFFOLDER[readLittleShort(hhis)];
177 files = new CFFILE[readLittleShort(hhis)];
178 int flags = readLittleShort(hhis);
179 prevCAB = (flags & 0x0001) != 0;
180 nextCAB = (flags & 0x0002) != 0;
181 hasReserved = (flags & 0x0004) != 0;
182 setID = readLittleShort(hhis);
183 indexInCabinetSet = readLittleShort(hhis);
185 if (offsetOfFirstCFFILEEntry < 0 || fileSize < 0) {
186 throw new BogusHeaderException();
190 perCabinetReservedArea = new byte[readLittleShort(dis)];
191 perCFFOLDERReservedSize = dis.readByte();
192 perDatablockReservedSize = dis.readByte();
193 if (perCabinetReservedArea.length > 0)
194 dis.readFully(perCabinetReservedArea);
199 previousCabinet = readZeroTerminatedString(dis);
200 previousDisk = readZeroTerminatedString(dis);
203 nextCabinet = readZeroTerminatedString(dis);
204 nextDisk = readZeroTerminatedString(dis);
206 } catch (ArrayIndexOutOfBoundsException e) {
207 throw new BogusHeaderException();
211 public static void seekMSCF(DataInputStream dis) throws EOFException, IOException
214 // skip up to and including the 'MSCF' signature
218 while (state == 0 && dis.readByte() != 0x4D) { }
221 switch (dis.readByte()) {
222 case 0x53 : state = 2; break;
223 case 0x4D : state = 1; continue;
224 default : state = 0; continue;
227 if (dis.readByte() == 0x43) { state = 3; }
228 else { state = 0; continue; }
230 if (dis.readByte() == 0x46) { state = 4; }
235 public static class BogusHeaderException extends IOException {}
238 /** Encapsulates a CFFOLDER entry */
239 public static class CFFOLDER {
240 public static final int COMPRESSION_NONE = 0;
241 public static final int COMPRESSION_MSZIP = 1;
242 public static final int COMPRESSION_QUANTUM = 2;
243 public static final int COMPRESSION_LZX = 3;
245 int firstBlockOffset = 0; // offset of first data block within this folder
246 int numBlocks = 0; // number of data blocks
247 int compressionType = 0; // compression type for this folder
248 byte[] reservedArea = null; // per-folder reserved area
249 int indexInCFHEADER = 0; // our index in CFHEADER.folders
250 Vector files = new Vector();
252 private CFHEADER header = null;
254 public CFFOLDER(CFHEADER header) { this.header = header; }
256 public String toString() {
257 return "[ CAB CFFOLDER, " + numBlocks + " data blocks, compression type " +
258 compressionName(compressionType) +
259 ", " + reservedArea.length + " bytes of reserved data ]";
262 public void read(DataInputStream dis) throws IOException, UnsupportedCompressionTypeException {
263 firstBlockOffset = readLittleInt(dis);
264 numBlocks = readLittleShort(dis);
265 compressionType = readLittleShort(dis) & 0x000F;
266 if (compressionType != COMPRESSION_MSZIP) {
267 throw new UnsupportedCompressionTypeException(compressionType);
269 reservedArea = new byte[header.perCFFOLDERReservedSize];
270 if (reservedArea.length > 0) dis.readFully(reservedArea);
271 indexInCFHEADER = header.readCFFOLDERs++;
272 header.folders[indexInCFHEADER] = this;
275 public static String compressionName(int type) {
277 case COMPRESSION_NONE:
279 case COMPRESSION_MSZIP:
281 case COMPRESSION_QUANTUM:
283 case COMPRESSION_LZX:
286 return "<Unknown type " + type + ">";
290 public static class UnsupportedCompressionTypeException extends IOException {
291 private int compressionType;
293 UnsupportedCompressionTypeException(int type) {
294 compressionType = type;
296 public String toString() {
297 return "UnsupportedCompressionTypeException: no support for compression type " + compressionName(compressionType);
302 /** Encapsulates a CFFILE entry */
303 public static class CFFILE {
304 int fileSize = 0; // size of this file
305 int uncompressedOffsetInCFFOLDER = 0; // offset of this file within the folder, not accounting for compression
306 int folderIndex = 0; // index of the CFFOLDER we belong to
307 Date date = null; // modification date
308 int attrs = 0; // attrs
309 boolean readOnly = false; // read-only flag
310 boolean hidden = false; // hidden flag
311 boolean system = false; // system flag
312 boolean arch = false; // archive flag
313 boolean runAfterExec = false; // true if file should be run during extraction
314 boolean UTFfileName = false; // true if filename is UTF-encoded
315 String fileName = null; // filename
316 int indexInCFHEADER = 0; // our index in CFHEADER.files
317 CFFOLDER folder = null; // the folder we belong to
318 private CFHEADER header = null;
321 public CFFILE(CFHEADER header) { this.header = header; }
323 public CFFILE(File f, String pathName) throws IOException {
324 fileSize = (int)f.length();
326 date = new java.util.Date(f.lastModified());
331 public String toString() {
332 return "[ CAB CFFILE: " + fileName + ", " + fileSize + " bytes [ " +
333 (readOnly ? "readonly " : "") +
334 (system ? "system " : "") +
335 (hidden ? "hidden " : "") +
336 (arch ? "arch " : "") +
337 (runAfterExec ? "run_after_exec " : "") +
338 (UTFfileName ? "UTF_filename " : "") +
342 public void read(DataInputStream dis) throws IOException {
343 fileSize = readLittleInt(dis);
344 uncompressedOffsetInCFFOLDER = readLittleInt(dis);
345 folderIndex = readLittleShort(dis);
346 readLittleShort(dis); // date
347 readLittleShort(dis); // time
348 attrs = readLittleShort(dis);
349 readOnly = (attrs & 0x1) != 0;
350 hidden = (attrs & 0x2) != 0;
351 system = (attrs & 0x4) != 0;
352 arch = (attrs & 0x20) != 0;
353 runAfterExec = (attrs & 0x40) != 0;
354 UTFfileName = (attrs & 0x80) != 0;
355 fileName = readZeroTerminatedString(dis);
357 indexInCFHEADER = header.readCFFILEs++;
358 header.files[indexInCFHEADER] = this;
359 folder = header.folders[folderIndex];
360 folder.files.addElement(this);
367 // Compressing Input and Output Streams ///////////////////////////////////////////////
369 /** an InputStream that decodes CFDATA blocks belonging to a CFFOLDER */
370 private static class CFFOLDERInputStream extends InputStream {
373 InputStream iis = null;
375 byte[] compressed = new byte[128 * 1024];
376 byte[] uncompressed = new byte[256 * 1024];
378 public CFFOLDERInputStream(CFFOLDER f, DataInputStream dis) {
383 InputStream readBlock() throws IOException {
384 int compressedBytes = readLittleShort(dis);
385 int unCompressedBytes = readLittleShort(dis);
386 byte[] reserved = new byte[/*folder.header.perDatablockReservedSize*/0];
387 if (reserved.length > 0) dis.readFully(reserved);
388 if (dis.readByte() != 0x43) throw new CABException("malformed block header");
389 if (dis.readByte() != 0x4B) throw new CABException("malformed block header");
391 dis.readFully(compressed, 0, compressedBytes - 2);
393 Inflater i = new Inflater(true);
394 i.setInput(compressed, 0, compressedBytes - 2);
396 if (unCompressedBytes > uncompressed.length) uncompressed = new byte[unCompressedBytes];
397 try { i.inflate(uncompressed, 0, uncompressed.length);
398 } catch (DataFormatException dfe) {
399 dfe.printStackTrace();
400 throw new CABException(dfe.toString());
402 return new ByteArrayInputStream(uncompressed, 0, unCompressedBytes);
405 public int available() throws IOException { return iis == null ? 0 : iis.available(); }
406 public void close() throws IOException { iis.close(); }
407 public void mark(int i) { }
408 public boolean markSupported() { return false; }
409 public void reset() { }
411 public long skip(long l) throws IOException {
412 if (iis == null) iis = readBlock();
415 long numread = iis.skip(l - ret);
416 if (numread == 0 || numread == -1) iis = readBlock();
422 public int read(byte[] b, int off, int len) throws IOException {
423 if (iis == null) iis = readBlock();
426 int numread = iis.read(b, off + ret, len - ret);
427 if (numread == 0 || numread == -1) iis = readBlock();
433 public int read() throws IOException {
434 if (iis == null) iis = readBlock();
435 int ret = iis.read();
446 // Misc Stuff //////////////////////////////////////////////////////////////
448 public static String readZeroTerminatedString(DataInputStream dis) throws IOException {
450 byte[] b = new byte[256];
452 byte next = dis.readByte();
453 if (next == 0x0) return new String(b, 0, numBytes);
454 b[numBytes++] = next;
458 public static int readLittleInt(DataInputStream dis) throws IOException {
459 int lowest = (int)(dis.readByte() & 0xff);
460 int low = (int)(dis.readByte() & 0xff);
461 int high = (int)(dis.readByte() & 0xff);
462 int highest = (int)(dis.readByte() & 0xff);
463 return (highest << 24) | (high << 16) | (low << 8) | lowest;
466 public static int readLittleShort(DataInputStream dis) throws IOException {
467 int low = (int)(dis.readByte() & 0xff);
468 int high = (int)(dis.readByte() & 0xff);
469 return (high << 8) | low;
472 public static class CABException extends IOException {
473 public CABException(String s) { super(s); }
477 /** scratch space for isToByteArray() */
478 static byte[] workspace = new byte[16 * 1024];
480 /** Trivial method to completely read an InputStream */
481 public static synchronized byte[] isToByteArray(InputStream is) throws IOException {
484 int numread = is.read(workspace, pos, workspace.length - pos);
485 if (numread == -1) break;
486 else if (pos + numread < workspace.length) pos += numread;
489 byte[] temp = new byte[workspace.length * 2];
490 System.arraycopy(workspace, 0, temp, 0, workspace.length);
494 byte[] ret = new byte[pos];
495 System.arraycopy(workspace, 0, ret, 0, pos);