Import of CAB extractor for java

This commit is contained in:
nathan 2014-12-18 18:21:38 +01:00
commit b446e3b008
27 changed files with 3070 additions and 0 deletions

7
.classpath Normal file
View File

@ -0,0 +1,7 @@
<?xml version="1.0" encoding="UTF-8"?>
<classpath>
<classpathentry kind="src" path="src"/>
<classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER"/>
<classpathentry combineaccessrules="false" kind="src" path="/Dorkbox-Util"/>
<classpathentry kind="output" path="classes"/>
</classpath>

1
.gitignore vendored Normal file
View File

@ -0,0 +1 @@
/classes/

17
.project Normal file
View File

@ -0,0 +1,17 @@
<?xml version="1.0" encoding="UTF-8"?>
<projectDescription>
<name>CabExtractor</name>
<comment></comment>
<projects>
</projects>
<buildSpec>
<buildCommand>
<name>org.eclipse.jdt.core.javabuilder</name>
<arguments>
</arguments>
</buildCommand>
</buildSpec>
<natures>
<nature>org.eclipse.jdt.core.javanature</nature>
</natures>
</projectDescription>

13
LICENSE Normal file
View File

@ -0,0 +1,13 @@
- Dorkbox Cab Extractor - Apache 2.0 License
https://github.com/dorkbox
Copyright 2012, dorkbox, llc
- Dorkbox Utils - Apache 2.0 License
https://github.com/dorkbox
Copyright 2010, dorkbox, llc
- jOOU, Unsigned Numbers for Java - Apache 2.0 License
https://github.com/jOOQ/jOOU
Copyright 2011-2013, Lukas Eder, lukas.eder@gmail.com

218
LICENSE.Apachev2 Normal file
View File

@ -0,0 +1,218 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the "Software"),
to deal in the Software without restriction, including without limitation
the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included
in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

10
README.md Normal file
View File

@ -0,0 +1,10 @@
CAB Extractor
=============
Provides a means to parse and extract data from Microsoft CAB files, from Java.
Specifically, to extract files from within a .cab which are compressed via the LZX compression algorithm.
Microsoft CAB file format: http://msdn.microsoft.com/en-us/library/bb417343.aspx
- This is for cross-platform use, specifically - linux 32/64, mac 32/64, and windows 32/64. Java 6+

View File

@ -0,0 +1,167 @@
/*
* Copyright 2012 dorkbox, llc
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package dorkbox.util.cab;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Enumeration;
import dorkbox.util.cab.decompress.CabDecompressor;
import dorkbox.util.cab.structure.CabEnumerator;
import dorkbox.util.cab.structure.CabFileEntry;
import dorkbox.util.cab.structure.CabFolderEntry;
import dorkbox.util.cab.structure.CabHeader;
public final class CabDecoder {
private CabInputStream cabInputStream;
private CabStreamSaver streamSaver;
private ByteArrayOutputStream outputStream = null;
public CabHeader header;
public CabFolderEntry[] folders;
public CabFileEntry[] files;
public CabDecoder(InputStream inputStream, final String fileNameToExtract) throws CabException, IOException {
if (fileNameToExtract == null || fileNameToExtract.isEmpty()) {
throw new IllegalArgumentException("Filename must be valid!");
}
this.cabInputStream = new CabInputStream(inputStream);
this.streamSaver = new CabStreamSaver() {
@Override
public boolean saveReservedAreaData(byte[] data, int dataLength) {
return false;
}
@Override
public OutputStream openOutputStream(CabFileEntry cabFile) {
String name = cabFile.getName();
if (fileNameToExtract.equalsIgnoreCase(name)) {
CabDecoder.this.outputStream = new ByteArrayOutputStream((int) cabFile.getSize());
return CabDecoder.this.outputStream;
} else {
return null;
}
}
@Override
public void closeOutputStream(OutputStream outputStream, CabFileEntry cabFile) {
if (outputStream != null) {
try {
outputStream.close();
} catch (IOException e) {
}
}
}
};
readData();
}
public CabDecoder(InputStream inputStream, CabStreamSaver streamSaver) throws CabException, IOException {
this.streamSaver = streamSaver;
this.cabInputStream = new CabInputStream(inputStream);
readData();
}
public Enumeration<Object> entries() {
return new CabEnumerator(this, false);
}
public Enumeration<Object> entries(boolean b) {
return new CabEnumerator(this, b);
}
private void readData() throws CabException, IOException {
this.header = new CabHeader(this.streamSaver);
this.header.read(this.cabInputStream);
if (this.header.cbCabinet <= 2147483647L) {
this.cabInputStream.mark((int) this.header.cbCabinet);
}
this.folders = new CabFolderEntry[this.header.cFolders];
for (int i = 0; i < this.header.cFolders; i++) {
this.folders[i] = new CabFolderEntry();
this.folders[i].read(this.cabInputStream);
}
this.files = new CabFileEntry[this.header.cFiles];
this.cabInputStream.seek(this.header.coffFiles);
for (int i = 0; i < this.header.cFiles; i++) {
this.files[i] = new CabFileEntry();
this.files[i].read(this.cabInputStream);
}
if (this.header.cbCabinet <= 2147483647L) {
this.cabInputStream.mark((int) this.header.cbCabinet);
}
}
public ByteArrayOutputStream extractStream() throws CabException, IOException {
int folderCount = -1;
int currentCount = 0;
int totalCount = 0;
boolean init = true;
CabDecompressor extractor = new CabDecompressor(this.cabInputStream, this.header.cbCFData);
for (int fileIndex = 0; fileIndex < this.header.cFiles; fileIndex++) {
CabFileEntry entry = this.files[fileIndex];
if (entry.iFolder != folderCount) {
if (folderCount + 1 >= this.header.cFolders) {
throw new CorruptCabException();
}
folderCount++;
init = true;
currentCount = 0;
totalCount = 0;
}
OutputStream localOutputStream = this.streamSaver.openOutputStream(entry);
if (localOutputStream != null) {
if (init) {
CabFolderEntry cabFolderEntry = this.folders[folderCount];
this.cabInputStream.seek(cabFolderEntry.coffCabStart);
extractor.initialize(cabFolderEntry.compressionMethod);
init = false;
}
if (currentCount != totalCount) {
extractor.read(totalCount - currentCount, new NullOutputStream());
currentCount = totalCount;
}
extractor.read(entry.cbFile, localOutputStream);
this.streamSaver.closeOutputStream(localOutputStream, entry);
currentCount = (int) (currentCount + entry.cbFile);
}
totalCount = (int) (totalCount + entry.cbFile);
}
return this.outputStream;
}
}

View File

@ -0,0 +1,27 @@
/*
* Copyright 2012 dorkbox, llc
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package dorkbox.util.cab;
public class CabException extends Exception {
private static final long serialVersionUID = 1L;
public CabException(String errorMessage) {
super(errorMessage);
}
public CabException() {
}
}

View File

@ -0,0 +1,116 @@
/*
* Copyright 2012 dorkbox, llc
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package dorkbox.util.cab;
import java.io.IOException;
import java.io.InputStream;
final class CabInputStream extends InputStream {
private InputStream inputStream;
private long position;
private long a;
private boolean markSupported;
@Override
public void close() throws IOException {
this.inputStream.close();
}
@Override
public synchronized void reset() throws IOException {
if (this.markSupported) {
this.inputStream.reset();
this.position = this.a;
return;
}
throw new IOException();
}
CabInputStream(InputStream inputStream) {
this.inputStream = inputStream;
this.position = 0L;
this.markSupported = this.inputStream.markSupported();
}
@Override
public int read() throws IOException {
int i = this.inputStream.read();
if (i >= 0) {
this.position += 1L;
}
return i;
}
@Override
public int read(byte[] bytes) throws IOException {
int i = this.inputStream.read(bytes);
if (i > 0) {
this.position += i;
}
return i;
}
@Override
public int read(byte[] bytes, int offset, int length) throws IOException {
int i = this.inputStream.read(bytes, offset, length);
if (i > 0) {
this.position += i;
}
return i;
}
@Override
public int available() throws IOException {
throw new IOException();
}
@Override
public synchronized void mark(int paramInt) {
if (this.markSupported) {
this.a = this.position;
this.inputStream.mark(paramInt);
}
}
public long getCurrentPosition() {
return this.position;
}
@Override
public boolean markSupported() {
return this.markSupported;
}
public void seek(long location) throws IOException {
if (location < this.position) {
throw new IOException("Cannot seek backwards");
}
if (location > this.position) {
skip(location - this.position);
}
}
@Override
public long skip(long ammount) throws IOException {
long l = this.inputStream.skip(ammount);
this.position += (int) l;
return l;
}
}

View File

@ -0,0 +1,26 @@
/*
* Copyright 2012 dorkbox, llc
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package dorkbox.util.cab;
import java.io.OutputStream;
import dorkbox.util.cab.structure.CabFileEntry;
public interface CabStreamSaver {
public abstract OutputStream openOutputStream(CabFileEntry entry);
public abstract void closeOutputStream(OutputStream outputStream, CabFileEntry entry);
public abstract boolean saveReservedAreaData(byte[] data, int dataLength);
}

View File

@ -0,0 +1,45 @@
/*
* Copyright 2012 dorkbox, llc
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package dorkbox.util.cab;
public final class Checksum {
@SuppressWarnings("fallthrough")
public static int calculate(byte[] bytes, int currentBlock, int seed) {
int c1 = (byte) (seed & 0xFF);
int c2 = (byte) (seed >>> 8 & 0xFF);
int c3 = (byte) (seed >>> 16 & 0xFF);
int c4 = (byte) (seed >>> 24 & 0xFF);
int j = 0;
int sizeOfBlock = currentBlock >>> 2;
while (sizeOfBlock-- > 0) {
c1 = (byte) (c1 ^ bytes[j++]);
c2 = (byte) (c2 ^ bytes[j++]);
c3 = (byte) (c3 ^ bytes[j++]);
c4 = (byte) (c4 ^ bytes[j++]);
}
switch (currentBlock & 0x3) {
case 3 :
c3 = (byte) (c3 ^ bytes[j++]);
case 2 :
c2 = (byte) (c2 ^ bytes[j++]);
case 1 :
c1 = (byte) (c1 ^ bytes[j++]);
}
return c1 & 0xFF | (c2 & 0xFF) << 8 | (c3 & 0xFF) << 16 | (c4 & 0xFF) << 24;
}
}

View File

@ -0,0 +1,28 @@
/*
* Copyright 2012 dorkbox, llc
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package dorkbox.util.cab;
public final class CorruptCabException extends CabException {
private static final long serialVersionUID = 1L;
public CorruptCabException(String errorMessage) {
super(errorMessage);
}
public CorruptCabException() {
}
}

View File

@ -0,0 +1,35 @@
/*
* Copyright 2012 dorkbox, llc
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package dorkbox.util.cab;
import java.io.OutputStream;
final class NullOutputStream extends OutputStream {
@Override
public void close() {}
@Override
public void write(byte[] b) {}
@Override
public void write(byte[] b, int off, int len) {}
@Override
public void write(int b) {}
@Override
public void flush() {}
}

View File

@ -0,0 +1,122 @@
/*
* Copyright 2012 dorkbox, llc
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package dorkbox.util.cab.decompress;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import dorkbox.util.cab.CabException;
import dorkbox.util.cab.CorruptCabException;
import dorkbox.util.cab.decompress.lzx.DecompressLzx;
import dorkbox.util.cab.decompress.none.DecompressNone;
import dorkbox.util.cab.decompress.zip.DecompressZip;
import dorkbox.util.cab.structure.CabConstants;
import dorkbox.util.cab.structure.CfDataRecord;
public final class CabDecompressor implements CabConstants {
private byte[] readBuffer;
private byte[] bytes;
private long uncompressedDataSize;
private int outputOffset;
private int compressionMethod;
private InputStream inputStream;
private Decompressor decompressor;
private CfDataRecord cfDataRecord;
public CabDecompressor(InputStream paramInputStream, int sizeOfBlockData) {
this.inputStream = paramInputStream;
this.uncompressedDataSize = 0L;
this.outputOffset = 0;
this.compressionMethod = -1;
this.bytes = new byte[33028];
this.cfDataRecord = new CfDataRecord(sizeOfBlockData);
}
public void read(long size, OutputStream outputStream) throws IOException, CabException {
if (this.uncompressedDataSize >= size) {
outputStream.write(this.bytes, this.outputOffset, (int) size);
this.uncompressedDataSize -= size;
this.outputOffset = (int) (this.outputOffset + size);
return;
}
if (this.uncompressedDataSize > 0L) {
outputStream.write(this.bytes, this.outputOffset, (int) this.uncompressedDataSize);
}
size -= this.uncompressedDataSize;
this.outputOffset = 0;
this.uncompressedDataSize = 0L;
while (size > 0L) {
this.cfDataRecord.read(this.inputStream, this.readBuffer);
if (!this.cfDataRecord.validateCheckSum(this.readBuffer)) {
throw new CorruptCabException("Invalid CFDATA checksum");
}
this.decompressor.decompress(this.readBuffer, this.bytes, this.cfDataRecord.cbData, this.cfDataRecord.cbUncomp);
this.uncompressedDataSize = this.cfDataRecord.cbUncomp;
this.outputOffset = 0;
if (this.uncompressedDataSize >= size) {
outputStream.write(this.bytes, this.outputOffset, (int) size);
this.outputOffset = (int) (this.outputOffset + size);
this.uncompressedDataSize -= size;
size = 0L;
} else {
outputStream.write(this.bytes, this.outputOffset, (int) this.uncompressedDataSize);
size -= this.uncompressedDataSize;
this.outputOffset = 0;
this.uncompressedDataSize = 0L;
}
}
}
public void initialize(int compressionMethod) throws CabException {
int type = compressionMethod & 0xF;
int windowBits = (compressionMethod & 0x1F00) >>> 8;
if (compressionMethod == this.compressionMethod) {
this.decompressor.reset(windowBits);
return;
}
switch (type) {
case COMPRESSION_TYPE_NONE :
this.decompressor = new DecompressNone();
break;
case COMPRESSION_TYPE_MSZIP :
this.decompressor = new DecompressZip();
break;
case COMPRESSION_TYPE_LZX :
this.decompressor = new DecompressLzx();
break;
case COMPRESSION_TYPE_QUANTUM :
default :
throw new CabException("Unknown compression type " + type);
}
this.readBuffer = new byte[CabConstants.CAB_BLOCK_SIZE + this.decompressor.getMaxGrowth()];
this.decompressor.init(windowBits);
this.compressionMethod = compressionMethod;
}
}

View File

@ -0,0 +1,27 @@
/*
* Copyright 2012 dorkbox, llc
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package dorkbox.util.cab.decompress;
import dorkbox.util.cab.CabException;
import dorkbox.util.cab.structure.CabConstants;
public interface Decompressor extends CabConstants {
public abstract void init(int windowBits) throws CabException;
public abstract void decompress(byte[] inputBytes, byte[] outputBytes, int inputLength, int outputLength) throws CabException;
public abstract int getMaxGrowth();
public abstract void reset(int windowBits) throws CabException;
}

View File

@ -0,0 +1,608 @@
/*
* Copyright 2012 dorkbox, llc
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package dorkbox.util.cab.decompress.lzx;
import dorkbox.util.cab.CabException;
import dorkbox.util.cab.CorruptCabException;
import dorkbox.util.cab.decompress.Decompressor;
public final class DecompressLzx implements Decompressor, LZXConstants {
private int[] extraBits = new int[51];
private int[] positionBase = new int[51];
private DecompressLzxTree mainTree;
private DecompressLzxTree lengthTree;
private DecompressLzxTree alignedTree;
private DecompressLzxTree preTree;
private int wndSize;
private int windowMask;
private int mainElements;
private int blocksRemaining;
private int blockType;
private int blockRemaining;
private int blockLength;
private int windowPosition;
private int R0;
private int R1;
private int R2;
private byte[] localWindow;
private int windowSize;
private boolean readHeader;
private int outputPosition;
private int index;
private int length;
private byte[] inputBytes;
private boolean abort;
int bitsLeft;
private int blockAlignOffset;
private int intelFileSize;
private int intelCursorPos;
private byte[] savedBytes = new byte[6];
private boolean intelStarted;
private int framesRead;
public DecompressLzx() {
int i = 4;
int j = 1;
do {
this.extraBits[i] = j;
this.extraBits[i + 1] = j;
i += 2;
j++;
} while (j <= 16);
do {
this.extraBits[i++] = 17;
} while (i < 51);
i = -2;
for (j = 0; j < this.extraBits.length; j++) {
this.positionBase[j] = i;
i += 1 << this.extraBits[j];
}
this.windowSize = -1;
}
@Override
public void init(int windowBits) throws CabException {
this.wndSize = 1 << windowBits;
this.windowMask = this.wndSize - 1;
reset(windowBits);
}
@Override
public void decompress(byte[] inputBytes, byte[] outputBytes, int inputLength, int outputLength) throws CabException {
this.abort = false;
this.index = 0;
this.inputBytes = inputBytes;
this.length = inputBytes.length;
initBitStream();
int decompressedOutputLength = decompressLoop(outputLength);
System.arraycopy(this.localWindow, this.outputPosition, outputBytes, 0, decompressedOutputLength);
if (this.framesRead++ < LZXConstants.E8_DISABLE_THRESHOLD && this.intelFileSize != 0) {
decodeIntelBlock(outputBytes, decompressedOutputLength);
}
}
@Override
public int getMaxGrowth() {
return LZXConstants.MAX_GROWTH;
}
@Override
public void reset(int windowBits) throws CabException {
if (this.windowSize == windowBits) {
this.mainTree.reset();
this.lengthTree.reset();
this.alignedTree.reset();
}
else {
maybeReset();
int i = NUM_CHARS + this.mainElements * ALIGNED_NUM_ELEMENTS;
this.localWindow = new byte[this.wndSize + 261];
this.preTree = new DecompressLzxTree(PRETREE_NUM_ELEMENTS, ALIGNED_NUM_ELEMENTS, this, null);
this.mainTree = new DecompressLzxTree(i, 9, this, this.preTree);
this.lengthTree = new DecompressLzxTree(SECONDARY_NUM_ELEMENTS, 6, this, this.preTree);
this.alignedTree = new DecompressLzxTree(ALIGNED_NUM_ELEMENTS, NUM_PRIMARY_LENGTHS, this, this.preTree);
}
this.windowSize = windowBits;
this.R0 = this.R1 = this.R2 = 1;
this.blocksRemaining = 0;
this.windowPosition = 0;
this.intelCursorPos = 0;
this.readHeader = true;
this.intelStarted = false;
this.framesRead = 0;
this.blockType = BLOCKTYPE_INVALID;
}
private int decompressLoop(int bytesToRead) throws CabException {
int i = bytesToRead;
int lastWindowPosition = 0;
int k;
int m;
if (this.readHeader == true) {
// read header
if (readBits(1) == 1) {
k = readBits(16);
m = readBits(16);
this.intelFileSize = k << 16 | m;
} else {
this.intelFileSize = 0;
}
this.readHeader = false;
}
lastWindowPosition = 0;
while (bytesToRead > 0) {
if (this.blocksRemaining == 0) {
if (this.blockType == BLOCKTYPE_UNCOMPRESSED) {
if ((this.blockLength & 0x1) != 0 && /* realign bitstream to word */
this.index < this.length) {
this.index++;
}
this.blockType = BLOCKTYPE_INVALID;
initBitStream();
}
this.blockType = readBits(3);
k = readBits(8);
m = readBits(8);
int n = readBits(8);
if (this.abort) {
break;
}
this.blockRemaining = this.blockLength = (k << 16) + (m << 8) + n;
if (this.blockType == BLOCKTYPE_ALIGNED) {
this.alignedTree.readLengths();
this.alignedTree.buildTable();
// rest of aligned header is same as verbatim
}
if (this.blockType == BLOCKTYPE_ALIGNED || this.blockType == BLOCKTYPE_VERBATIM) {
this.mainTree.read();
this.lengthTree.read();
this.mainTree.readLengths(0, NUM_CHARS);
this.mainTree.readLengths(NUM_CHARS, NUM_CHARS + this.mainElements * ALIGNED_NUM_ELEMENTS);
this.mainTree.buildTable();
if (this.mainTree.LENS[0xE8] != 0) {
this.intelStarted = true;
}
this.lengthTree.readLengths(0, SECONDARY_NUM_ELEMENTS);
this.lengthTree.buildTable();
}
else if (this.blockType == BLOCKTYPE_UNCOMPRESSED) {
// because we can't assume otherwise
this.intelStarted = true;
this.index -= 2; // align the bitstream
if (this.index < 0 || this.index + 12 >= this.length) {
throw new CorruptCabException();
}
this.R0 = readInt();
this.R1 = readInt();
this.R2 = readInt();
}
else {
throw new CorruptCabException();
}
}
this.blocksRemaining = 1;
while (this.blockRemaining > 0 && bytesToRead > 0) {
if (this.blockRemaining < bytesToRead) {
k = this.blockRemaining;
} else {
k = bytesToRead;
}
decompressBlockActions(k);
this.blockRemaining -= k;
bytesToRead -= k;
lastWindowPosition += k;
}
if (this.blockRemaining == 0) {
this.blocksRemaining = 0;
}
if (bytesToRead == 0 && this.blockAlignOffset != 16) {
readNumberBits(this.blockAlignOffset);
}
}
if (lastWindowPosition != i) {
throw new CorruptCabException();
}
if (this.windowPosition == 0) {
this.outputPosition = this.wndSize - lastWindowPosition;
} else {
this.outputPosition = this.windowPosition - lastWindowPosition;
}
return lastWindowPosition;
}
private void decodeIntelBlock(byte[] bytes, int outLength) {
if (outLength <= 6 || !this.intelStarted) {
this.intelCursorPos += outLength;
return;
}
int cursorPos = this.intelCursorPos;
int fileSize = this.intelFileSize;
int abs_off = 0;
int adjustedOutLength = outLength - 6;
// save bytes
while (abs_off < 6) {
this.savedBytes[abs_off] = bytes[adjustedOutLength + abs_off];
bytes[adjustedOutLength + abs_off] = -24;
abs_off++;
}
int dataIndex = 0;
int cursor_pos = cursorPos + adjustedOutLength;
while (cursorPos < cursor_pos) {
while (bytes[dataIndex++] == -24) {
if (cursorPos >= cursor_pos) {
break;
}
abs_off = bytes[dataIndex] & 0xFF |
(bytes[dataIndex + 1] & 0xFF) << 8 |
(bytes[dataIndex + 2] & 0xFF) << 16 |
(bytes[dataIndex + 3] & 0xFF) << 24;
if (abs_off >= 0) {
if (abs_off < fileSize) {
int rel_off = abs_off - cursorPos;
bytes[dataIndex] = (byte) (rel_off & 0xFF);
bytes[dataIndex + 1] = (byte) (rel_off >>> 8 & 0xFF);
bytes[dataIndex + 2] = (byte) (rel_off >>> 16 & 0xFF);
bytes[dataIndex + 3] = (byte) (rel_off >>> 24);
}
}
else if (abs_off >= -cursorPos) {
int rel_off = abs_off + this.intelFileSize;
bytes[dataIndex] = (byte) (rel_off & 0xFF);
bytes[dataIndex + 1] = (byte) (rel_off >>> 8 & 0xFF);
bytes[dataIndex + 2] = (byte) (rel_off >>> 16 & 0xFF);
bytes[dataIndex + 3] = (byte) (rel_off >>> 24);
}
dataIndex += 4;
cursorPos += 5;
}
cursorPos++;
}
this.intelCursorPos = cursor_pos + 6;
// restore saved bytes
abs_off = 0;
while (abs_off < 6) {
bytes[adjustedOutLength + abs_off] = this.savedBytes[abs_off];
abs_off++;
}
}
private void decompressBlockActions(int bytesToRead) throws CabException {
this.windowPosition &= this.windowMask;
if (this.windowPosition + bytesToRead > this.wndSize) {
throw new CabException();
}
switch (this.blockType) {
case BLOCKTYPE_UNCOMPRESSED :
uncompressedAlgo(bytesToRead);
return;
case BLOCKTYPE_ALIGNED :
alignedAlgo(bytesToRead);
return;
case BLOCKTYPE_VERBATIM :
verbatimAlgo(bytesToRead);
return;
default :
throw new CorruptCabException();
}
}
void readNumberBits(int numBits) {
this.bitsLeft <<= numBits;
this.blockAlignOffset -= numBits;
if (this.blockAlignOffset <= 0) {
this.bitsLeft |= readShort() << -this.blockAlignOffset;
this.blockAlignOffset += 16;
}
}
private void initBitStream() {
if (this.blockType != BLOCKTYPE_UNCOMPRESSED) {
this.bitsLeft = readShort() << 16 | readShort();
this.blockAlignOffset = 16;
}
}
private void maybeReset() {
this.mainElements = 4;
int i = 4;
do {
i += 1 << this.extraBits[this.mainElements];
this.mainElements++;
} while (i < this.wndSize);
}
private void verbatimAlgo(int this_run) throws CorruptCabException {
int i = this.windowPosition;
int mask = this.windowMask;
byte[] windowPosition = this.localWindow;
int r0 = this.R0;
int r1 = this.R1;
int r2 = this.R2;
int[] arrayOfInt1 = this.extraBits;
int[] arrayOfInt2 = this.positionBase;
DecompressLzxTree mainTree = this.mainTree;
DecompressLzxTree lengthTree = this.lengthTree;
while (this_run > 0) {
int main_element = mainTree.decodeElement();
if (main_element < NUM_CHARS) {
windowPosition[i++] = (byte) main_element;
this_run--;
}
/* is a match */
else {
main_element -= NUM_CHARS;
int match_length = main_element & NUM_PRIMARY_LENGTHS;
if (match_length == NUM_PRIMARY_LENGTHS) {
match_length += lengthTree.decodeElement();
}
int matchOffset = main_element >>> 3;
/* check for repeated offsets (positions 0,1,2) */
if (matchOffset == 0) {
matchOffset = r0;
}
else if (matchOffset == 1) {
matchOffset = r1;
r1 = r0;
r0 = matchOffset;
}
else if (matchOffset > 2) {
// not repeated offset
if (matchOffset > 3) {
matchOffset = verbatimAlgo2(arrayOfInt1[matchOffset]) + arrayOfInt2[matchOffset];
} else {
matchOffset = 1;
}
r2 = r1;
r1 = r0;
r0 = matchOffset;
} else {
matchOffset = r2;
r2 = r0;
r0 = matchOffset;
}
match_length += MIN_MATCH;
this_run -= match_length;
while (match_length > 0) {
windowPosition[i] = windowPosition[i - matchOffset & mask];
i++;
match_length--;
}
}
}
if (this_run != 0) {
throw new CorruptCabException();
}
this.R0 = r0;
this.R1 = r1;
this.R2 = r2;
this.windowPosition = i;
}
private int verbatimAlgo2(int position) {
int i = this.bitsLeft >>> 32 - position;
this.bitsLeft <<= position;
this.blockAlignOffset -= position;
if (this.blockAlignOffset <= 0) {
this.bitsLeft |= readShort() << -this.blockAlignOffset;
this.blockAlignOffset += 16;
if (this.blockAlignOffset <= 0) {
this.bitsLeft |= readShort() << -this.blockAlignOffset;
this.blockAlignOffset += 16;
}
}
return i;
}
private void alignedAlgo(int this_run) throws CorruptCabException {
int windowPos = this.windowPosition;
int mask = this.windowMask;
byte[] window = this.localWindow;
int r0 = this.R0;
int r1 = this.R1;
int r2 = this.R2;
while (this_run > 0) {
int mainElement = this.mainTree.decodeElement();
if (mainElement < NUM_CHARS) {
window[windowPos] = (byte) mainElement;
windowPos = windowPos + 1 & mask;
this_run--;
}
/* is a match */
else {
mainElement -= NUM_CHARS;
int matchLength = mainElement & NUM_PRIMARY_LENGTHS;
if (matchLength == NUM_PRIMARY_LENGTHS) {