initial checkin
[org.ibex.nanogoat.git] / src / org / ibex / util / CAB.java
1 // Copyright (C) 2003 Adam Megacz <adam@ibex.org> all rights reserved.
2 //
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
6 // relink clause")
7
8 package org.ibex.util;
9
10 import java.io.*;
11 import java.util.*;
12 import java.util.zip.*;
13
14 /** Reads a CAB file structure */
15 public class CAB {
16
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);
20     }
21
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();
25
26         while (skipHeaders > 0) { CFHEADER.seekMSCF(dis); skipHeaders--; }
27
28         try {
29          h.read(dis);
30         } catch (CFHEADER.BogusHeaderException bhe) {
31          throw new EOFException();
32         }
33
34         for(int i=0; i<h.folders.length; i++) {
35             CFFOLDER f = new CFFOLDER(h);
36             try {
37                f.read(dis);
38             } catch (CFFOLDER.UnsupportedCompressionTypeException ucte) {
39                throw ucte;
40             }
41         }
42
43         for(int i=0; i<h.files.length; i++) {
44             CFFILE f = new CFFILE(h);
45             f.read(dis);
46         }
47         
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];
54             }
55         }
56
57         return null;
58     }
59
60     private static class LimitStream extends FilterInputStream {
61         int limit;
62         public LimitStream(InputStream is, int limit) {
63             super(is);
64             this.limit = limit;
65         }
66         public int read() throws IOException {
67             if (limit == 0) return -1;
68             int ret = super.read();
69             if (ret != -1) limit--;
70             return ret;
71         }
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);
76             limit -= ret;
77             return ret;
78         }
79     }
80     
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
102
103         CFFOLDER[] folders = new CFFOLDER[0];
104         CFFILE[] files = new CFFILE[0];
105
106         int readCFFOLDERs = 0;                    // the number of folders read in so far
107         int readCFFILEs = 0;                      // the number of folders read in so far
108
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));
139             if (hasReserved) {
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) + " ");
145                     ps.println();
146                 }
147                 ps.println("    per folder  reserved area     = " + perCFFOLDERReservedSize + " bytes");
148                 ps.println("    per block   reserved area     = " + perDatablockReservedSize + " bytes");
149             }
150         }
151
152         public String toString() {
153             return
154                 "[ CAB CFFILE CFHEADER v" +
155                 ((int)versionMajor) + "." + ((int)versionMinor) + ", " +
156                 fileSize + " bytes, " +
157                 folders.length + " folders, " +
158                 files.length + " files] ";
159         }
160
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 {
163             seekMSCF(dis);
164             dis.readFully(reserved1);
165
166             byte[] headerHashable = new byte[28];
167             dis.readFully(headerHashable);
168             DataInputStream hhis = new DataInputStream(new ByteArrayInputStream(headerHashable));
169
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);
184
185             if (offsetOfFirstCFFILEEntry < 0 || fileSize < 0) {
186                throw new BogusHeaderException();
187             }
188
189             if (hasReserved) {
190                 perCabinetReservedArea = new byte[readLittleShort(dis)];
191                 perCFFOLDERReservedSize = dis.readByte();
192                 perDatablockReservedSize = dis.readByte();
193                 if (perCabinetReservedArea.length > 0)
194                     dis.readFully(perCabinetReservedArea);
195             }
196
197             try {
198                if (prevCAB) {
199                    previousCabinet = readZeroTerminatedString(dis);
200                    previousDisk = readZeroTerminatedString(dis);
201                }
202                if (nextCAB) {
203                    nextCabinet = readZeroTerminatedString(dis);
204                    nextDisk = readZeroTerminatedString(dis);
205                }
206             } catch (ArrayIndexOutOfBoundsException e) {
207                throw new BogusHeaderException();
208             }
209         }
210
211         public static void seekMSCF(DataInputStream dis) throws EOFException, IOException
212         {
213            int state;
214            // skip up to and including the 'MSCF' signature
215            state = 0;
216            while (state != 4) {
217               // M
218               while (state == 0 && dis.readByte() != 0x4D) { }
219               state = 1;
220               // S
221               switch (dis.readByte()) {
222                  case 0x53 : state = 2; break;
223                  case 0x4D : state = 1; continue;
224                  default :   state = 0; continue;
225               }
226               // C
227               if (dis.readByte() == 0x43) { state = 3; }
228               else { state = 0; continue; }
229               // F
230               if (dis.readByte() == 0x46) { state = 4; }
231               else { state = 0; }
232            }
233         }
234
235         public static class BogusHeaderException extends IOException {}
236     }
237
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;
244
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();
251
252         private CFHEADER header = null;
253
254         public CFFOLDER(CFHEADER header) { this.header = header; }
255
256         public String toString() {
257             return "[ CAB CFFOLDER, " + numBlocks + " data blocks, compression type " +
258                 compressionName(compressionType) +
259                 ", " + reservedArea.length + " bytes of reserved data ]";
260         }
261
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);
268             }
269             reservedArea = new byte[header.perCFFOLDERReservedSize];
270             if (reservedArea.length > 0) dis.readFully(reservedArea);
271             indexInCFHEADER = header.readCFFOLDERs++;
272             header.folders[indexInCFHEADER] = this;
273         }
274
275         public static String compressionName(int type) {
276             switch (type) {
277                case COMPRESSION_NONE:
278                   return "NONE";
279                case COMPRESSION_MSZIP:
280                   return "MSZIP";
281                case COMPRESSION_QUANTUM:
282                   return "QUANTUM";
283                case COMPRESSION_LZX:
284                   return "LZX";
285                default:
286                   return "<Unknown type " + type + ">";
287             }
288         }
289
290         public static class UnsupportedCompressionTypeException extends IOException {
291             private int compressionType;
292
293             UnsupportedCompressionTypeException(int type) {
294                compressionType = type;
295             }
296             public String toString() {
297                return "UnsupportedCompressionTypeException: no support for compression type " + compressionName(compressionType);
298             }
299         }
300     }
301
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;
319         File myFile;
320
321         public CFFILE(CFHEADER header) { this.header = header; }
322
323         public CFFILE(File f, String pathName) throws IOException {
324             fileSize = (int)f.length();
325             folderIndex = 0;
326             date = new java.util.Date(f.lastModified());
327             fileName = pathName;
328             myFile = f;
329         }
330
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 " : "") +
339                 "]";
340         }
341
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);
356
357             indexInCFHEADER = header.readCFFILEs++;
358             header.files[indexInCFHEADER] = this;
359             folder = header.folders[folderIndex];
360             folder.files.addElement(this);
361         }
362     }
363
364
365
366
367     // Compressing Input and Output Streams ///////////////////////////////////////////////
368
369     /** an InputStream that decodes CFDATA blocks belonging to a CFFOLDER */
370     private static class CFFOLDERInputStream extends InputStream {
371         CFFOLDER folder;
372         DataInputStream dis;
373         InputStream iis = null;
374
375         byte[] compressed = new byte[128 * 1024];
376         byte[] uncompressed = new byte[256 * 1024];
377
378         public CFFOLDERInputStream(CFFOLDER f, DataInputStream dis) {
379             this.folder = f;
380             this.dis = dis;
381         }
382
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");
390
391             dis.readFully(compressed, 0, compressedBytes - 2);
392
393             Inflater i = new Inflater(true);
394             i.setInput(compressed, 0, compressedBytes - 2);
395             
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());
401             }
402             return new ByteArrayInputStream(uncompressed, 0, unCompressedBytes);
403         }
404
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() { }
410
411         public long skip(long l) throws IOException {
412             if (iis == null) iis = readBlock();
413             int ret = 0;
414             while (l > ret) {
415                 long numread = iis.skip(l - ret);
416                 if (numread == 0 || numread == -1) iis = readBlock();
417                 else ret += numread;
418             }
419             return ret;
420         }
421         
422         public int read(byte[] b, int off, int len) throws IOException {
423             if (iis == null) iis = readBlock();
424             int ret = 0;
425             while (len > ret) {
426                 int numread = iis.read(b, off + ret, len - ret);
427                 if (numread == 0 || numread == -1) iis = readBlock();
428                 else ret += numread;
429             }
430             return ret;
431         }
432
433         public int read() throws IOException {
434             if (iis == null) iis = readBlock();
435             int ret = iis.read();
436             if (ret == -1) {
437                 iis = readBlock();
438                 ret = iis.read();
439             }
440             return ret;
441         }
442     }
443
444
445
446     // Misc Stuff //////////////////////////////////////////////////////////////
447
448     public static String readZeroTerminatedString(DataInputStream dis) throws IOException {
449         int numBytes = 0;
450         byte[] b = new byte[256];
451         while(true) {
452             byte next = dis.readByte();
453             if (next == 0x0) return new String(b, 0, numBytes);
454             b[numBytes++] = next;
455         }
456     }
457     
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;
464     }
465
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;
470     }
471
472     public static class CABException extends IOException {
473         public CABException(String s) { super(s); }
474     }
475
476
477     /** scratch space for isToByteArray() */
478     static byte[] workspace = new byte[16 * 1024];
479
480     /** Trivial method to completely read an InputStream */
481     public static synchronized byte[] isToByteArray(InputStream is) throws IOException {
482         int pos = 0;
483         while (true) {
484             int numread = is.read(workspace, pos, workspace.length - pos);
485             if (numread == -1) break;
486             else if (pos + numread < workspace.length) pos += numread;
487             else {
488                 pos += numread;
489                 byte[] temp = new byte[workspace.length * 2];
490                 System.arraycopy(workspace, 0, temp, 0, workspace.length);
491                 workspace = temp;
492             }
493         }
494         byte[] ret = new byte[pos];
495         System.arraycopy(workspace, 0, ret, 0, pos);
496         return ret;
497     }
498
499
500 }
501