summaryrefslogtreecommitdiff
path: root/src
diff options
context:
space:
mode:
Diffstat (limited to 'src')
-rw-r--r--src/com/github/junrar/Archive.java583
-rw-r--r--src/com/github/junrar/MVTest.java56
-rw-r--r--src/com/github/junrar/UnrarCallback.java21
-rw-r--r--src/com/github/junrar/Volume.java44
-rw-r--r--src/com/github/junrar/VolumeManager.java28
-rw-r--r--src/com/github/junrar/crc/RarCRC.java145
-rw-r--r--src/com/github/junrar/crypt/Rijndael.java27
-rw-r--r--src/com/github/junrar/exception/RarException.java73
-rw-r--r--src/com/github/junrar/impl/FileVolume.java65
-rw-r--r--src/com/github/junrar/impl/FileVolumeManager.java54
-rw-r--r--src/com/github/junrar/io/IReadOnlyAccess.java61
-rw-r--r--src/com/github/junrar/io/InputStreamReadOnlyAccessFile.java59
-rw-r--r--src/com/github/junrar/io/RandomAccessStream.java203
-rw-r--r--src/com/github/junrar/io/Raw.java305
-rw-r--r--src/com/github/junrar/io/ReadOnlyAccessByteArray.java90
-rw-r--r--src/com/github/junrar/io/ReadOnlyAccessFile.java55
-rw-r--r--src/com/github/junrar/io/ReadOnlyAccessInputStream.java81
-rw-r--r--src/com/github/junrar/rarfile/AVHeader.java66
-rw-r--r--src/com/github/junrar/rarfile/BaseBlock.java179
-rw-r--r--src/com/github/junrar/rarfile/BlockHeader.java70
-rw-r--r--src/com/github/junrar/rarfile/CommentHeader.java70
-rw-r--r--src/com/github/junrar/rarfile/EAHeader.java90
-rw-r--r--src/com/github/junrar/rarfile/EndArcHeader.java63
-rw-r--r--src/com/github/junrar/rarfile/FileHeader.java421
-rw-r--r--src/com/github/junrar/rarfile/FileNameDecoder.java76
-rw-r--r--src/com/github/junrar/rarfile/HostSystem.java72
-rw-r--r--src/com/github/junrar/rarfile/MacInfoHeader.java81
-rw-r--r--src/com/github/junrar/rarfile/MainHeader.java141
-rw-r--r--src/com/github/junrar/rarfile/MarkHeader.java84
-rw-r--r--src/com/github/junrar/rarfile/NewSubHeaderType.java89
-rw-r--r--src/com/github/junrar/rarfile/ProtectHeader.java71
-rw-r--r--src/com/github/junrar/rarfile/SignHeader.java60
-rw-r--r--src/com/github/junrar/rarfile/SubBlockHeader.java70
-rw-r--r--src/com/github/junrar/rarfile/SubBlockHeaderType.java77
-rw-r--r--src/com/github/junrar/rarfile/UnixOwnersHeader.java93
-rw-r--r--src/com/github/junrar/rarfile/UnrarHeadertype.java164
-rw-r--r--src/com/github/junrar/unpack/ComprDataIO.java362
-rw-r--r--src/com/github/junrar/unpack/Unpack.java1051
-rw-r--r--src/com/github/junrar/unpack/Unpack15.java620
-rw-r--r--src/com/github/junrar/unpack/Unpack20.java597
-rw-r--r--src/com/github/junrar/unpack/UnpackFilter.java94
-rw-r--r--src/com/github/junrar/unpack/decode/AudioVariables.java144
-rw-r--r--src/com/github/junrar/unpack/decode/BitDecode.java35
-rw-r--r--src/com/github/junrar/unpack/decode/CodeType.java29
-rw-r--r--src/com/github/junrar/unpack/decode/Compress.java45
-rw-r--r--src/com/github/junrar/unpack/decode/Decode.java81
-rw-r--r--src/com/github/junrar/unpack/decode/DistDecode.java37
-rw-r--r--src/com/github/junrar/unpack/decode/FilterType.java30
-rw-r--r--src/com/github/junrar/unpack/decode/LitDecode.java36
-rw-r--r--src/com/github/junrar/unpack/decode/LowDistDecode.java37
-rw-r--r--src/com/github/junrar/unpack/decode/MultDecode.java37
-rw-r--r--src/com/github/junrar/unpack/decode/RepDecode.java36
-rw-r--r--src/com/github/junrar/unpack/ppm/AnalyzeHeapDump.java94
-rw-r--r--src/com/github/junrar/unpack/ppm/BlockTypes.java58
-rw-r--r--src/com/github/junrar/unpack/ppm/FreqData.java87
-rw-r--r--src/com/github/junrar/unpack/ppm/ModelPPM.java696
-rw-r--r--src/com/github/junrar/unpack/ppm/PPMContext.java477
-rw-r--r--src/com/github/junrar/unpack/ppm/Pointer.java59
-rw-r--r--src/com/github/junrar/unpack/ppm/RangeCoder.java177
-rw-r--r--src/com/github/junrar/unpack/ppm/RarMemBlock.java139
-rw-r--r--src/com/github/junrar/unpack/ppm/RarNode.java69
-rw-r--r--src/com/github/junrar/unpack/ppm/SEE2Context.java102
-rw-r--r--src/com/github/junrar/unpack/ppm/State.java119
-rw-r--r--src/com/github/junrar/unpack/ppm/StateRef.java92
-rw-r--r--src/com/github/junrar/unpack/ppm/SubAllocator.java427
-rw-r--r--src/com/github/junrar/unpack/vm/BitInput.java108
-rw-r--r--src/com/github/junrar/unpack/vm/RarVM.java1221
-rw-r--r--src/com/github/junrar/unpack/vm/VMCmdFlags.java81
-rw-r--r--src/com/github/junrar/unpack/vm/VMCommands.java226
-rw-r--r--src/com/github/junrar/unpack/vm/VMFlags.java79
-rw-r--r--src/com/github/junrar/unpack/vm/VMOpType.java66
-rw-r--r--src/com/github/junrar/unpack/vm/VMPreparedCommand.java57
-rw-r--r--src/com/github/junrar/unpack/vm/VMPreparedOperand.java58
-rw-r--r--src/com/github/junrar/unpack/vm/VMPreparedProgram.java127
-rw-r--r--src/com/github/junrar/unpack/vm/VMStandardFilterSignature.java64
-rw-r--r--src/com/github/junrar/unpack/vm/VMStandardFilters.java79
-rw-r--r--src/com/github/junrar/unsigned/UnsignedByte.java68
-rw-r--r--src/com/github/junrar/unsigned/UnsignedInteger.java29
-rw-r--r--src/com/github/junrar/unsigned/UnsignedLong.java29
-rw-r--r--src/com/github/junrar/unsigned/UnsignedShort.java29
-rw-r--r--src/com/github/junrar/util/VolumeHelper.java101
-rw-r--r--src/org/catacombae/.cvsignore5
-rw-r--r--src/org/catacombae/io/.cvsignore5
-rw-r--r--src/org/catacombae/io/RandomAccessFileStream.java66
-rw-r--r--src/org/catacombae/io/RandomAccessStream.java54
-rw-r--r--src/org/catacombae/rar/.cvsignore5
-rw-r--r--src/org/catacombae/rar/RARFile.java32
-rw-r--r--src/org/catacombae/rarx/.cvsignore5
-rw-r--r--src/org/catacombae/rarx/CommentHeader.java54
-rw-r--r--src/org/catacombae/rarx/DecompressionCode.java1715
-rw-r--r--src/org/catacombae/rarx/FileAttributes.java29
-rw-r--r--src/org/catacombae/rarx/InvalidDataException.java29
-rw-r--r--src/org/catacombae/rarx/Leaf.java7
-rw-r--r--src/org/catacombae/rarx/ListArchiveContents.java438
-rw-r--r--src/org/catacombae/rarx/ListFilesInArchive.java173
-rw-r--r--src/org/catacombae/rarx/ListRecursive.java92
-rw-r--r--src/org/catacombae/rarx/MarkHeader.java48
-rw-r--r--src/org/catacombae/rarx/NewFileHeader.java428
-rw-r--r--src/org/catacombae/rarx/NewMainArchiveHeader.java94
-rw-r--r--src/org/catacombae/rarx/ProtectedHeader.java67
-rw-r--r--src/org/catacombae/rarx/RARFile.java248
-rw-r--r--src/org/catacombae/rarx/RARFile2.java29
-rw-r--r--src/org/catacombae/rarx/RARFileEntry.java76
-rw-r--r--src/org/catacombae/rarx/RARFileEntryStream.java550
-rw-r--r--src/org/catacombae/rarx/RARHeader.java121
-rw-r--r--src/org/catacombae/rarx/README.txt10
-rw-r--r--src/org/catacombae/rarx/TestRAFProperties.java32
-rw-r--r--src/org/catacombae/rarx/Tree.java55
-rw-r--r--src/org/catacombae/rarx/TreeNode.java17
-rw-r--r--src/org/catacombae/rarx/UNIXFileAttributes.java66
-rw-r--r--src/org/catacombae/rarx/UnknownHeader.java54
-rw-r--r--src/org/catacombae/rarx/Util.java305
-rw-r--r--src/org/catacombae/rarx/Win32FileAttributes.java68
-rw-r--r--src/org/fox/ttcomics/CbrComicArchive.java64
-rw-r--r--src/org/fox/ttcomics/ComicListFragment.java12
-rw-r--r--src/org/fox/ttcomics/ComicPager.java11
116 files changed, 12331 insertions, 5009 deletions
diff --git a/src/com/github/junrar/Archive.java b/src/com/github/junrar/Archive.java
new file mode 100644
index 0000000..23ca39b
--- /dev/null
+++ b/src/com/github/junrar/Archive.java
@@ -0,0 +1,583 @@
+/*
+ * Copyright (c) 2007 innoSysTec (R) GmbH, Germany. All rights reserved.
+ * Original author: Edmund Wagner
+ * Creation date: 22.05.2007
+ *
+ * Source: $HeadURL$
+ * Last changed: $LastChangedDate$
+ *
+ * the unrar licence applies to all junrar source and binary distributions
+ * you are not allowed to use this source to re-create the RAR compression
+ * algorithm
+ *
+ * Here some html entities which can be used for escaping javadoc tags:
+ * "&": "&" or "&"
+ * "<": "&#060;" or "&lt;"
+ * ">": "&#062;" or "&gt;"
+ * "@": "&#064;"
+ */
+package com.github.junrar;
+
+import java.io.Closeable;
+import java.io.File;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.OutputStream;
+import java.io.PipedInputStream;
+import java.io.PipedOutputStream;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.logging.Level;
+import java.util.logging.Logger;
+
+import com.github.junrar.exception.RarException;
+import com.github.junrar.exception.RarException.RarExceptionType;
+import com.github.junrar.impl.FileVolumeManager;
+import com.github.junrar.io.IReadOnlyAccess;
+import com.github.junrar.rarfile.AVHeader;
+import com.github.junrar.rarfile.BaseBlock;
+import com.github.junrar.rarfile.BlockHeader;
+import com.github.junrar.rarfile.CommentHeader;
+import com.github.junrar.rarfile.EAHeader;
+import com.github.junrar.rarfile.EndArcHeader;
+import com.github.junrar.rarfile.FileHeader;
+import com.github.junrar.rarfile.MacInfoHeader;
+import com.github.junrar.rarfile.MainHeader;
+import com.github.junrar.rarfile.MarkHeader;
+import com.github.junrar.rarfile.ProtectHeader;
+import com.github.junrar.rarfile.SignHeader;
+import com.github.junrar.rarfile.SubBlockHeader;
+import com.github.junrar.rarfile.UnixOwnersHeader;
+import com.github.junrar.rarfile.UnrarHeadertype;
+import com.github.junrar.unpack.ComprDataIO;
+import com.github.junrar.unpack.Unpack;
+
+
+/**
+ * The Main Rar Class; represents a rar Archive
+ *
+ * @author $LastChangedBy$
+ * @version $LastChangedRevision$
+ */
+public class Archive implements Closeable {
+ private static Logger logger = Logger.getLogger(Archive.class.getName());
+
+ private IReadOnlyAccess rof;
+
+ private final UnrarCallback unrarCallback;
+
+ private final ComprDataIO dataIO;
+
+ private final List<BaseBlock> headers = new ArrayList<BaseBlock>();
+
+ private MarkHeader markHead = null;
+
+ private MainHeader newMhd = null;
+
+ private Unpack unpack;
+
+ private int currentHeaderIndex;
+
+ /** Size of packed data in current file. */
+ private long totalPackedSize = 0L;
+
+ /** Number of bytes of compressed data read from current file. */
+ private long totalPackedRead = 0L;
+
+ private VolumeManager volumeManager;
+ private Volume volume;
+
+ public Archive(VolumeManager volumeManager) throws RarException,
+ IOException {
+ this(volumeManager, null);
+ }
+
+ /**
+ * create a new archive object using the given {@link VolumeManager}
+ *
+ * @param volumeManager
+ * the the {@link VolumeManager} that will provide volume stream
+ * data
+ * @throws RarException
+ */
+ public Archive(VolumeManager volumeManager, UnrarCallback unrarCallback)
+ throws RarException, IOException {
+ this.volumeManager = volumeManager;
+ this.unrarCallback = unrarCallback;
+
+ setVolume(this.volumeManager.nextArchive(this, null));
+ dataIO = new ComprDataIO(this);
+ }
+
+ public Archive(File firstVolume) throws RarException, IOException {
+ this(new FileVolumeManager(firstVolume), null);
+ }
+
+ public Archive(File firstVolume, UnrarCallback unrarCallback)
+ throws RarException, IOException {
+ this(new FileVolumeManager(firstVolume), unrarCallback);
+ }
+
+ // public File getFile() {
+ // return file;
+ // }
+ //
+ // void setFile(File file) throws IOException {
+ // this.file = file;
+ // setFile(new ReadOnlyAccessFile(file), file.length());
+ // }
+
+ private void setFile(IReadOnlyAccess file, long length) throws IOException {
+ totalPackedSize = 0L;
+ totalPackedRead = 0L;
+ close();
+ rof = file;
+ try {
+ readHeaders(length);
+ } catch (Exception e) {
+ logger.log(Level.WARNING,
+ "exception in archive constructor maybe file is encrypted "
+ + "or currupt", e);
+ // ignore exceptions to allow exraction of working files in
+ // corrupt archive
+ }
+ // Calculate size of packed data
+ for (BaseBlock block : headers) {
+ if (block.getHeaderType() == UnrarHeadertype.FileHeader) {
+ totalPackedSize += ((FileHeader) block).getFullPackSize();
+ }
+ }
+ if (unrarCallback != null) {
+ unrarCallback.volumeProgressChanged(totalPackedRead,
+ totalPackedSize);
+ }
+ }
+
+ public void bytesReadRead(int count) {
+ if (count > 0) {
+ totalPackedRead += count;
+ if (unrarCallback != null) {
+ unrarCallback.volumeProgressChanged(totalPackedRead,
+ totalPackedSize);
+ }
+ }
+ }
+
+ public IReadOnlyAccess getRof() {
+ return rof;
+ }
+
+ /**
+ * @return returns all file headers of the archive
+ */
+ public List<FileHeader> getFileHeaders() {
+ List<FileHeader> list = new ArrayList<FileHeader>();
+ for (BaseBlock block : headers) {
+ if (block.getHeaderType().equals(UnrarHeadertype.FileHeader)) {
+ list.add((FileHeader) block);
+ }
+ }
+ return list;
+ }
+
+ public FileHeader nextFileHeader() {
+ int n = headers.size();
+ while (currentHeaderIndex < n) {
+ BaseBlock block = headers.get(currentHeaderIndex++);
+ if (block.getHeaderType() == UnrarHeadertype.FileHeader) {
+ return (FileHeader) block;
+ }
+ }
+ return null;
+ }
+
+ public UnrarCallback getUnrarCallback() {
+ return unrarCallback;
+ }
+
+ /**
+ *
+ * @return whether the archive is encrypted
+ */
+ public boolean isEncrypted() {
+ if (newMhd != null) {
+ return newMhd.isEncrypted();
+ } else {
+ throw new NullPointerException("mainheader is null");
+ }
+ }
+
+ /**
+ * Read the headers of the archive
+ *
+ * @param fileLength
+ * Length of file.
+ * @throws RarException
+ */
+ private void readHeaders(long fileLength) throws IOException, RarException {
+ markHead = null;
+ newMhd = null;
+ headers.clear();
+ currentHeaderIndex = 0;
+ int toRead = 0;
+
+ while (true) {
+ int size = 0;
+ long newpos = 0;
+ byte[] baseBlockBuffer = new byte[BaseBlock.BaseBlockSize];
+
+ long position = rof.getPosition();
+
+ // Weird, but is trying to read beyond the end of the file
+ if (position >= fileLength) {
+ break;
+ }
+
+ // logger.info("\n--------reading header--------");
+ size = rof.readFully(baseBlockBuffer, BaseBlock.BaseBlockSize);
+ if (size == 0) {
+ break;
+ }
+ BaseBlock block = new BaseBlock(baseBlockBuffer);
+
+ block.setPositionInFile(position);
+
+ switch (block.getHeaderType()) {
+
+ case MarkHeader:
+ markHead = new MarkHeader(block);
+ if (!markHead.isSignature()) {
+ throw new RarException(
+ RarException.RarExceptionType.badRarArchive);
+ }
+ headers.add(markHead);
+ // markHead.print();
+ break;
+
+ case MainHeader:
+ toRead = block.hasEncryptVersion() ? MainHeader.mainHeaderSizeWithEnc
+ : MainHeader.mainHeaderSize;
+ byte[] mainbuff = new byte[toRead];
+ rof.readFully(mainbuff, toRead);
+ MainHeader mainhead = new MainHeader(block, mainbuff);
+ headers.add(mainhead);
+ this.newMhd = mainhead;
+ if (newMhd.isEncrypted()) {
+ throw new RarException(
+ RarExceptionType.rarEncryptedException);
+ }
+ // mainhead.print();
+ break;
+
+ case SignHeader:
+ toRead = SignHeader.signHeaderSize;
+ byte[] signBuff = new byte[toRead];
+ rof.readFully(signBuff, toRead);
+ SignHeader signHead = new SignHeader(block, signBuff);
+ headers.add(signHead);
+ // logger.info("HeaderType: SignHeader");
+
+ break;
+
+ case AvHeader:
+ toRead = AVHeader.avHeaderSize;
+ byte[] avBuff = new byte[toRead];
+ rof.readFully(avBuff, toRead);
+ AVHeader avHead = new AVHeader(block, avBuff);
+ headers.add(avHead);
+ // logger.info("headertype: AVHeader");
+ break;
+
+ case CommHeader:
+ toRead = CommentHeader.commentHeaderSize;
+ byte[] commBuff = new byte[toRead];
+ rof.readFully(commBuff, toRead);
+ CommentHeader commHead = new CommentHeader(block, commBuff);
+ headers.add(commHead);
+ // logger.info("method: "+commHead.getUnpMethod()+"; 0x"+
+ // Integer.toHexString(commHead.getUnpMethod()));
+ newpos = commHead.getPositionInFile()
+ + commHead.getHeaderSize();
+ rof.setPosition(newpos);
+
+ break;
+ case EndArcHeader:
+
+ toRead = 0;
+ if (block.hasArchiveDataCRC()) {
+ toRead += EndArcHeader.endArcArchiveDataCrcSize;
+ }
+ if (block.hasVolumeNumber()) {
+ toRead += EndArcHeader.endArcVolumeNumberSize;
+ }
+ EndArcHeader endArcHead;
+ if (toRead > 0) {
+ byte[] endArchBuff = new byte[toRead];
+ rof.readFully(endArchBuff, toRead);
+ endArcHead = new EndArcHeader(block, endArchBuff);
+ // logger.info("HeaderType: endarch\ndatacrc:"+
+ // endArcHead.getArchiveDataCRC());
+ } else {
+ // logger.info("HeaderType: endarch - no Data");
+ endArcHead = new EndArcHeader(block, null);
+ }
+ headers.add(endArcHead);
+ // logger.info("\n--------end header--------");
+ return;
+
+ default:
+ byte[] blockHeaderBuffer = new byte[BlockHeader.blockHeaderSize];
+ rof.readFully(blockHeaderBuffer, BlockHeader.blockHeaderSize);
+ BlockHeader blockHead = new BlockHeader(block,
+ blockHeaderBuffer);
+
+ switch (blockHead.getHeaderType()) {
+ case NewSubHeader:
+ case FileHeader:
+ toRead = blockHead.getHeaderSize()
+ - BlockHeader.BaseBlockSize
+ - BlockHeader.blockHeaderSize;
+ byte[] fileHeaderBuffer = new byte[toRead];
+ rof.readFully(fileHeaderBuffer, toRead);
+
+ FileHeader fh = new FileHeader(blockHead, fileHeaderBuffer);
+ headers.add(fh);
+ newpos = fh.getPositionInFile() + fh.getHeaderSize()
+ + fh.getFullPackSize();
+ rof.setPosition(newpos);
+ break;
+
+ case ProtectHeader:
+ toRead = blockHead.getHeaderSize()
+ - BlockHeader.BaseBlockSize
+ - BlockHeader.blockHeaderSize;
+ byte[] protectHeaderBuffer = new byte[toRead];
+ rof.readFully(protectHeaderBuffer, toRead);
+ ProtectHeader ph = new ProtectHeader(blockHead,
+ protectHeaderBuffer);
+
+ newpos = ph.getPositionInFile() + ph.getHeaderSize()
+ + ph.getDataSize();
+ rof.setPosition(newpos);
+ break;
+
+ case SubHeader: {
+ byte[] subHeadbuffer = new byte[SubBlockHeader.SubBlockHeaderSize];
+ rof.readFully(subHeadbuffer,
+ SubBlockHeader.SubBlockHeaderSize);
+ SubBlockHeader subHead = new SubBlockHeader(blockHead,
+ subHeadbuffer);
+ subHead.print();
+ switch (subHead.getSubType()) {
+ case MAC_HEAD: {
+ byte[] macHeaderbuffer = new byte[MacInfoHeader.MacInfoHeaderSize];
+ rof.readFully(macHeaderbuffer,
+ MacInfoHeader.MacInfoHeaderSize);
+ MacInfoHeader macHeader = new MacInfoHeader(subHead,
+ macHeaderbuffer);
+ macHeader.print();
+ headers.add(macHeader);
+
+ break;
+ }
+ // TODO implement other subheaders
+ case BEEA_HEAD:
+ break;
+ case EA_HEAD: {
+ byte[] eaHeaderBuffer = new byte[EAHeader.EAHeaderSize];
+ rof.readFully(eaHeaderBuffer, EAHeader.EAHeaderSize);
+ EAHeader eaHeader = new EAHeader(subHead,
+ eaHeaderBuffer);
+ eaHeader.print();
+ headers.add(eaHeader);
+
+ break;
+ }
+ case NTACL_HEAD:
+ break;
+ case STREAM_HEAD:
+ break;
+ case UO_HEAD:
+ toRead = subHead.getHeaderSize();
+ toRead -= BaseBlock.BaseBlockSize;
+ toRead -= BlockHeader.blockHeaderSize;
+ toRead -= SubBlockHeader.SubBlockHeaderSize;
+ byte[] uoHeaderBuffer = new byte[toRead];
+ rof.readFully(uoHeaderBuffer, toRead);
+ UnixOwnersHeader uoHeader = new UnixOwnersHeader(
+ subHead, uoHeaderBuffer);
+ uoHeader.print();
+ headers.add(uoHeader);
+ break;
+ default:
+ break;
+ }
+
+ break;
+ }
+ default:
+ logger.warning("Unknown Header");
+ throw new RarException(RarExceptionType.notRarArchive);
+
+ }
+ }
+ // logger.info("\n--------end header--------");
+ }
+ }
+
+ /**
+ * Extract the file specified by the given header and write it to the
+ * supplied output stream
+ *
+ * @param header
+ * the header to be extracted
+ * @param os
+ * the outputstream
+ * @throws RarException
+ */
+ public void extractFile(FileHeader hd, OutputStream os) throws RarException {
+ if (!headers.contains(hd)) {
+ throw new RarException(RarExceptionType.headerNotInArchive);
+ }
+ try {
+ doExtractFile(hd, os);
+ } catch (Exception e) {
+ if (e instanceof RarException) {
+ throw (RarException) e;
+ } else {
+ throw new RarException(e);
+ }
+ }
+ }
+
+ /**
+ * Returns an {@link InputStream} that will allow to read the file and
+ * stream it. Please note that this method will create a new Thread and an a
+ * pair of Pipe streams.
+ *
+ * @param header
+ * the header to be extracted
+ * @throws RarException
+ * @throws IOException
+ * if any IO error occur
+ */
+ public InputStream getInputStream(final FileHeader hd) throws RarException,
+ IOException {
+ final PipedInputStream in = new PipedInputStream(32 * 1024);
+ final PipedOutputStream out = new PipedOutputStream(in);
+
+ // creates a new thread that will write data to the pipe. Data will be
+ // available in another InputStream, connected to the OutputStream.
+ new Thread(new Runnable() {
+ public void run() {
+ try {
+ extractFile(hd, out);
+ } catch (RarException e) {
+ } finally {
+ try {
+ out.close();
+ } catch (IOException e) {
+ }
+ }
+ }
+ }).start();
+
+ return in;
+ }
+
+ private void doExtractFile(FileHeader hd, OutputStream os)
+ throws RarException, IOException {
+ dataIO.init(os);
+ dataIO.init(hd);
+ dataIO.setUnpFileCRC(this.isOldFormat() ? 0 : 0xffFFffFF);
+ if (unpack == null) {
+ unpack = new Unpack(dataIO);
+ }
+ if (!hd.isSolid()) {
+ unpack.init(null);
+ }
+ unpack.setDestSize(hd.getFullUnpackSize());
+ try {
+ unpack.doUnpack(hd.getUnpVersion(), hd.isSolid());
+ // Verify file CRC
+ hd = dataIO.getSubHeader();
+ long actualCRC = hd.isSplitAfter() ? ~dataIO.getPackedCRC()
+ : ~dataIO.getUnpFileCRC();
+ int expectedCRC = hd.getFileCRC();
+ if (actualCRC != expectedCRC) {
+ throw new RarException(RarExceptionType.crcError);
+ }
+ // if (!hd.isSplitAfter()) {
+ // // Verify file CRC
+ // if(~dataIO.getUnpFileCRC() != hd.getFileCRC()){
+ // throw new RarException(RarExceptionType.crcError);
+ // }
+ // }
+ } catch (Exception e) {
+ unpack.cleanUp();
+ if (e instanceof RarException) {
+ // throw new RarException((RarException)e);
+ throw (RarException) e;
+ } else {
+ throw new RarException(e);
+ }
+ }
+ }
+
+ /**
+ * @return returns the main header of this archive
+ */
+ public MainHeader getMainHeader() {
+ return newMhd;
+ }
+
+ /**
+ * @return whether the archive is old format
+ */
+ public boolean isOldFormat() {
+ return markHead.isOldFormat();
+ }
+
+ /** Close the underlying compressed file. */
+ public void close() throws IOException {
+ if (rof != null) {
+ rof.close();
+ rof = null;
+ }
+ if (unpack != null) {
+ unpack.cleanUp();
+ }
+ }
+
+ /**
+ * @return the volumeManager
+ */
+ public VolumeManager getVolumeManager() {
+ return volumeManager;
+ }
+
+ /**
+ * @param volumeManager
+ * the volumeManager to set
+ */
+ public void setVolumeManager(VolumeManager volumeManager) {
+ this.volumeManager = volumeManager;
+ }
+
+ /**
+ * @return the volume
+ */
+ public Volume getVolume() {
+ return volume;
+ }
+
+ /**
+ * @param volume
+ * the volume to set
+ * @throws IOException
+ */
+ public void setVolume(Volume volume) throws IOException {
+ this.volume = volume;
+ setFile(volume.getReadOnlyAccess(), volume.getLength());
+ }
+}
diff --git a/src/com/github/junrar/MVTest.java b/src/com/github/junrar/MVTest.java
new file mode 100644
index 0000000..36c33c8
--- /dev/null
+++ b/src/com/github/junrar/MVTest.java
@@ -0,0 +1,56 @@
+package com.github.junrar;
+
+import java.io.File;
+import java.io.FileNotFoundException;
+import java.io.FileOutputStream;
+import java.io.IOException;
+
+import com.github.junrar.exception.RarException;
+import com.github.junrar.impl.FileVolumeManager;
+import com.github.junrar.rarfile.FileHeader;
+
+
+public class MVTest {
+
+ /**
+ * @param args
+ */
+ public static void main(String[] args) {
+ String filename = "/home/rogiel/fs/home/ae721273-eade-45e7-8112-d14115ebae56/Village People - Y.M.C.A.mp3.part1.rar";
+ File f = new File(filename);
+ Archive a = null;
+ try {
+ a = new Archive(new FileVolumeManager(f));
+ } catch (RarException e) {
+ // TODO Auto-generated catch block
+ e.printStackTrace();
+ } catch (IOException e) {
+ // TODO Auto-generated catch block
+ e.printStackTrace();
+ }
+ if (a != null) {
+ a.getMainHeader().print();
+ FileHeader fh = a.nextFileHeader();
+ while (fh != null) {
+ try {
+ File out = new File("/home/rogiel/fs/test/"
+ + fh.getFileNameString().trim());
+ System.out.println(out.getAbsolutePath());
+ FileOutputStream os = new FileOutputStream(out);
+ a.extractFile(fh, os);
+ os.close();
+ } catch (FileNotFoundException e) {
+ // TODO Auto-generated catch block
+ e.printStackTrace();
+ } catch (RarException e) {
+ // TODO Auto-generated catch block
+ e.printStackTrace();
+ } catch (IOException e) {
+ // TODO Auto-generated catch block
+ e.printStackTrace();
+ }
+ fh = a.nextFileHeader();
+ }
+ }
+ }
+}
diff --git a/src/com/github/junrar/UnrarCallback.java b/src/com/github/junrar/UnrarCallback.java
new file mode 100644
index 0000000..06bc088
--- /dev/null
+++ b/src/com/github/junrar/UnrarCallback.java
@@ -0,0 +1,21 @@
+package com.github.junrar;
+
+
+/**
+ *
+ * @author alban
+ */
+public interface UnrarCallback {
+
+ /**
+ * Return <tt>true</tt> if the next volume is ready to be processed,
+ * <tt>false</tt> otherwise.
+ */
+ boolean isNextVolumeReady(Volume nextVolume);
+
+ /**
+ * This method is invoked each time the progress of the current
+ * volume changes.
+ */
+ void volumeProgressChanged(long current, long total);
+}
diff --git a/src/com/github/junrar/Volume.java b/src/com/github/junrar/Volume.java
new file mode 100644
index 0000000..edc17ae
--- /dev/null
+++ b/src/com/github/junrar/Volume.java
@@ -0,0 +1,44 @@
+/*
+ * This file is part of seedbox <github.com/seedbox>.
+ *
+ * seedbox is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * seedbox is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with seedbox. If not, see <http://www.gnu.org/licenses/>.
+ */
+package com.github.junrar;
+
+import java.io.IOException;
+
+import com.github.junrar.io.IReadOnlyAccess;
+
+
+/**
+ * @author <a href="http://www.rogiel.com">Rogiel</a>
+ *
+ */
+public interface Volume {
+ /**
+ * @return the access
+ * @throws IOException
+ */
+ IReadOnlyAccess getReadOnlyAccess() throws IOException;
+
+ /**
+ * @return the data length
+ */
+ long getLength();
+
+ /**
+ * @return the archive this volume belongs to
+ */
+ Archive getArchive();
+}
diff --git a/src/com/github/junrar/VolumeManager.java b/src/com/github/junrar/VolumeManager.java
new file mode 100644
index 0000000..3e96530
--- /dev/null
+++ b/src/com/github/junrar/VolumeManager.java
@@ -0,0 +1,28 @@
+/*
+ * This file is part of seedbox <github.com/seedbox>.
+ *
+ * seedbox is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * seedbox is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with seedbox. If not, see <http://www.gnu.org/licenses/>.
+ */
+package com.github.junrar;
+
+import java.io.IOException;
+
+/**
+ * @author <a href="http://www.rogiel.com">Rogiel</a>
+ *
+ */
+public interface VolumeManager {
+ public Volume nextArchive(Archive archive, Volume lastVolume)
+ throws IOException;
+}
diff --git a/src/com/github/junrar/crc/RarCRC.java b/src/com/github/junrar/crc/RarCRC.java
new file mode 100644
index 0000000..8a778ed
--- /dev/null
+++ b/src/com/github/junrar/crc/RarCRC.java
@@ -0,0 +1,145 @@
+/*
+ * Copyright (c) 2007 innoSysTec (R) GmbH, Germany. All rights reserved.
+ * Original author: Edmund Wagner
+ * Creation date: 29.05.2007
+ *
+ * Source: $HeadURL$
+ * Last changed: $LastChangedDate$
+ *
+ * the unrar licence applies to all junrar source and binary distributions
+ * you are not allowed to use this source to re-create the RAR compression algorithm
+ *
+ * Here some html entities which can be used for escaping javadoc tags:
+ * "&": "&#038;" or "&amp;"
+ * "<": "&#060;" or "&lt;"
+ * ">": "&#062;" or "&gt;"
+ * "@": "&#064;"
+ */
+package com.github.junrar.crc;
+
+
+/**
+ * DOCUMENT ME
+ *
+ * @author $LastChangedBy$
+ * @version $LastChangedRevision$
+ */
+public class RarCRC {
+
+ private final static int crcTab[];
+ static {
+ crcTab = new int[256];
+ for (int i = 0; i < 256; i++) {
+ int c = i;
+ for (int j = 0; j < 8; j++){
+ if ((c & 1) !=0) {
+ c >>>= 1;
+ c ^= 0xEDB88320;
+ }
+ else{
+ c >>>= 1;
+ }
+ }
+ crcTab[i] = c;
+ }
+ }
+
+ private RarCRC() {
+ }
+
+ public static int checkCrc(int startCrc, byte[] data, int offset,
+ int count) {
+ int size = Math.min(data.length-offset,count);
+ // #if defined(LITTLE_ENDIAN) && defined(PRESENT_INT32) &&
+ // defined(ALLOW_NOT_ALIGNED_INT)
+ /*
+ for (int i = 0; (0 < size) && i < data.length - 8
+ && ((data[i + 8] & 7) != 0); i++) {
+ startCrc = crcTab[(short) (startCrc ^ data[i]) & 0x00FF] ^ (startCrc >>> 8);
+ size--;
+ }
+
+ for (int i = 0; size >= 8; i += 8) {
+ startCrc ^= data[i + 0] << 24;
+ startCrc ^= data[i + 1] << 16;
+ startCrc ^= data[i + 2] << 8;
+ startCrc ^= data[i + 3];
+
+ startCrc = crcTab[(short) startCrc & 0x00FF] ^ (startCrc >>> 8);
+ startCrc = crcTab[(short) startCrc & 0x00FF] ^ (startCrc >>> 8);
+ startCrc = crcTab[(short) startCrc & 0x00FF] ^ (startCrc >>> 8);
+ startCrc = crcTab[(short) startCrc & 0x00FF] ^ (startCrc >>> 8);
+
+ startCrc ^= data[i + 4] << 24;
+ startCrc ^= data[i + 5] << 16;
+ startCrc ^= data[i + 6] << 8;
+ startCrc ^= data[i + 7];
+ startCrc = crcTab[(short) startCrc & 0x00FF] ^ (startCrc >>> 8);
+ startCrc = crcTab[(short) startCrc & 0x00FF] ^ (startCrc >>> 8);
+ startCrc = crcTab[(short) startCrc & 0x00FF] ^ (startCrc >>> 8);
+ startCrc = crcTab[(short) startCrc & 0x00FF] ^ (startCrc >>> 8);
+ size -= 8;
+ }*/
+
+ for (int i = 0; i < size; i++)
+ {
+/*
+ // (byte)(StartCRC^Data[I])
+ int pos = 0; // pos=0x00000000
+ pos |= startCrc; // pos=ffffffff
+
+ pos ^= data[i]; // data[0]=0x73=115dec --> pos=140
+ System.out.println(Integer.toHexString(pos));
+
+ // Only last 8 bit because CRCtab has length 256
+ pos = pos & 0x000000FF;
+ System.out.println("pos:"+pos);
+ //startCrc >>>= 8;
+
+
+ //StartCRC>>8
+ int temp =0;
+ temp|=startCrc;
+ temp >>>= 8;
+ System.out.println("temp:"+Integer.toHexString(temp));
+
+
+ startCrc = (crcTab[pos]^temp);
+ System.out.println("--"+Integer.toHexString(startCrc));*/
+
+ startCrc=(crcTab[((int)((int)startCrc ^
+ (int)data[offset+i]))&0xff]^(startCrc>>>8));
+
+ //System.out.println(Integer.toHexString(startCrc));
+
+ // Original code:
+ //StartCRC=CRCTab[(byte)(StartCRC^Data[I])]^(StartCRC>>8);
+ }
+ return (startCrc);
+ }
+
+ public static short checkOldCrc(short startCrc, byte[] data, int count) {
+ int n = Math.min(data.length, count);
+ for (int i = 0; i < n; i++) {
+ startCrc = (short) ((short) (startCrc + (short) (data[i]&0x00ff)) & -1);
+ startCrc = (short) (((startCrc << 1) | (startCrc >>> 15)) & -1);
+ }
+ return (startCrc);
+ }
+
+// public static void main(String[] args)
+// {
+// RarCRC rc = new RarCRC();
+// //byte[] data = { 0x72, 0x21, 0x1A, 0x07, 0x00};
+//
+// byte[] data = {0x73 ,0x00 ,0x00 ,0x0D ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00};
+//
+// int crc = 0x90CF;
+//
+//
+// int result = rc.checkCrc(0xFFFFffff, data,0,data.length);
+// System.out.println("3: "+Integer.toHexString(~result&0xffff));
+//
+// }
+
+}
diff --git a/src/com/github/junrar/crypt/Rijndael.java b/src/com/github/junrar/crypt/Rijndael.java
new file mode 100644
index 0000000..a1cf7c7
--- /dev/null
+++ b/src/com/github/junrar/crypt/Rijndael.java
@@ -0,0 +1,27 @@
+/*
+ * Copyright (c) 2007 innoSysTec (R) GmbH, Germany. All rights reserved.
+ * Original author: Edmund Wagner
+ * Creation date: 31.05.2007
+ *
+ * the unrar licence applies to all junrar source and binary distributions
+ * you are not allowed to use this source to re-create the RAR compression algorithm
+ * Source: $HeadURL$
+ * Last changed: $LastChangedDate$
+ *
+ * Here some html entities which can be used for escaping javadoc tags:
+ * "&": "&#038;" or "&amp;"
+ * "<": "&#060;" or "&lt;"
+ * ">": "&#062;" or "&gt;"
+ * "@": "&#064;"
+ */
+package com.github.junrar.crypt;
+
+/**
+ * DOCUMENT ME
+ *
+ * @author $LastChangedBy$
+ * @version $LastChangedRevision$
+ */
+public class Rijndael {
+
+}
diff --git a/src/com/github/junrar/exception/RarException.java b/src/com/github/junrar/exception/RarException.java
new file mode 100644
index 0000000..a0b969f
--- /dev/null
+++ b/src/com/github/junrar/exception/RarException.java
@@ -0,0 +1,73 @@
+/*
+ * Copyright (c) 2007 innoSysTec (R) GmbH, Germany. All rights reserved.
+ * Original author: Edmund Wagner
+ * Creation date: 30.07.2007
+ *
+ * Source: $HeadURL$
+ * Last changed: $LastChangedDate$
+ *
+ * the unrar licence applies to all junrar source and binary distributions
+ * you are not allowed to use this source to re-create the RAR compression algorithm
+ *
+ * Here some html entities which can be used for escaping javadoc tags:
+ * "&": "&#038;" or "&amp;"
+ * "<": "&#060;" or "&lt;"
+ * ">": "&#062;" or "&gt;"
+ * "@": "&#064;"
+ */
+package com.github.junrar.exception;
+
+/**
+ * DOCUMENT ME
+ *
+ * @author $LastChangedBy$
+ * @version $LastChangedRevision$
+ */
+public class RarException extends Exception
+{
+ private static final long serialVersionUID = 1L;
+ private RarExceptionType type;
+
+ public RarException(Exception e){
+ super(RarExceptionType.unkownError.name(),e);
+ this.type = RarExceptionType.unkownError;
+ }
+
+ public RarException(RarException e)
+ {
+
+ super(e.getMessage(),e);
+ this.type = e.getType();
+ }
+
+ public RarException(RarExceptionType type){
+ super(type.name());
+ this.type = type;
+ }
+
+
+
+ public enum RarExceptionType{
+ notImplementedYet,
+ crcError,
+ notRarArchive,
+ badRarArchive,
+ unkownError,
+ headerNotInArchive,
+ wrongHeaderType,
+ ioError,
+ rarEncryptedException ;
+ }
+
+
+
+ public RarExceptionType getType()
+ {
+ return type;
+ }
+
+ public void setType(RarExceptionType type)
+ {
+ this.type = type;
+ }
+}
diff --git a/src/com/github/junrar/impl/FileVolume.java b/src/com/github/junrar/impl/FileVolume.java
new file mode 100644
index 0000000..eba4da9
--- /dev/null
+++ b/src/com/github/junrar/impl/FileVolume.java
@@ -0,0 +1,65 @@
+/*
+ * This file is part of seedbox <github.com/seedbox>.
+ *
+ * seedbox is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * seedbox is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with seedbox. If not, see <http://www.gnu.org/licenses/>.
+ */
+package com.github.junrar.impl;
+
+import java.io.File;
+import java.io.IOException;
+
+import com.github.junrar.Archive;
+import com.github.junrar.Volume;
+import com.github.junrar.io.IReadOnlyAccess;
+import com.github.junrar.io.ReadOnlyAccessFile;
+
+
+/**
+ * @author <a href="http://www.rogiel.com">Rogiel</a>
+ *
+ */
+public class FileVolume implements Volume {
+ private final Archive archive;
+ private final File file;
+
+ /**
+ * @param file
+ */
+ public FileVolume(Archive archive, File file) {
+ this.archive = archive;
+ this.file = file;
+ }
+
+ @Override
+ public IReadOnlyAccess getReadOnlyAccess() throws IOException {
+ return new ReadOnlyAccessFile(file);
+ }
+
+ @Override
+ public long getLength() {
+ return file.length();
+ }
+
+ @Override
+ public Archive getArchive() {
+ return archive;
+ }
+
+ /**
+ * @return the file
+ */
+ public File getFile() {
+ return file;
+ }
+}
diff --git a/src/com/github/junrar/impl/FileVolumeManager.java b/src/com/github/junrar/impl/FileVolumeManager.java
new file mode 100644
index 0000000..3552248
--- /dev/null
+++ b/src/com/github/junrar/impl/FileVolumeManager.java
@@ -0,0 +1,54 @@
+/*
+ * This file is part of seedbox <github.com/seedbox>.
+ *
+ * seedbox is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * seedbox is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with seedbox. If not, see <http://www.gnu.org/licenses/>.
+ */
+package com.github.junrar.impl;
+
+import java.io.File;
+import java.io.IOException;
+
+import com.github.junrar.Archive;
+import com.github.junrar.Volume;
+import com.github.junrar.VolumeManager;
+import com.github.junrar.util.VolumeHelper;
+
+
+/**
+ * @author <a href="http://www.rogiel.com">Rogiel</a>
+ *
+ */
+public class FileVolumeManager implements VolumeManager {
+ private final File firstVolume;
+
+ public FileVolumeManager(File firstVolume) {
+ this.firstVolume = firstVolume;
+ }
+
+ @Override
+ public Volume nextArchive(Archive archive, Volume last)
+ throws IOException {
+ if (last == null)
+ return new FileVolume(archive, firstVolume);
+
+ FileVolume lastFileVolume = (FileVolume) last;
+ boolean oldNumbering = !archive.getMainHeader().isNewNumbering()
+ || archive.isOldFormat();
+ String nextName = VolumeHelper.nextVolumeName(lastFileVolume.getFile()
+ .getAbsolutePath(), oldNumbering);
+ File nextVolume = new File(nextName);
+
+ return new FileVolume(archive, nextVolume);
+ }
+}
diff --git a/src/com/github/junrar/io/IReadOnlyAccess.java b/src/com/github/junrar/io/IReadOnlyAccess.java
new file mode 100644
index 0000000..e0cde6e
--- /dev/null
+++ b/src/com/github/junrar/io/IReadOnlyAccess.java
@@ -0,0 +1,61 @@
+/*
+ * Copyright (c) 2007 innoSysTec (R) GmbH, Germany. All rights reserved.
+ * Original author: Edmund Wagner
+ * Creation date: 23.05.2007
+ *
+ * Source: $HeadURL$
+ * Last changed: $LastChangedDate$
+ *
+ * the unrar licence applies to all junrar source and binary distributions
+ * you are not allowed to use this source to re-create the RAR compression algorithm
+ *
+ * Here some html entities which can be used for escaping javadoc tags:
+ * "&": "&#038;" or "&amp;"
+ * "<": "&#060;" or "&lt;"
+ * ">": "&#062;" or "&gt;"
+ * "@": "&#064;"
+ */
+package com.github.junrar.io;
+
+import java.io.IOException;
+
+
+/**
+ * DOCUMENT ME
+ *
+ * @author $LastChangedBy$
+ * @version $LastChangedRevision$
+ */
+public interface IReadOnlyAccess {
+
+ /**
+ * @return the current position in the file
+ */
+ public long getPosition() throws IOException;
+
+ /**
+ * @param pos the position in the file
+ * @return success ? true : false
+ */
+ public void setPosition(long pos) throws IOException;
+
+ /** Read a single byte of data. */
+ public int read() throws IOException;
+
+ /**
+ * Read up to <tt>count</tt> bytes to the specified buffer.
+ */
+ public int read(byte[] buffer, int off, int count) throws IOException;
+
+ /**
+ * Read exactly <tt>count</tt> bytes to the specified buffer.
+ *
+ * @param buffer where to store the read data
+ * @param count how many bytes to read
+ * @return bytes read || -1 if IO problem
+ */
+ public int readFully(byte[] buffer, int count) throws IOException;
+
+ /** Close this file. */
+ public void close() throws IOException;
+}
diff --git a/src/com/github/junrar/io/InputStreamReadOnlyAccessFile.java b/src/com/github/junrar/io/InputStreamReadOnlyAccessFile.java
new file mode 100644
index 0000000..3c7eedd
--- /dev/null
+++ b/src/com/github/junrar/io/InputStreamReadOnlyAccessFile.java
@@ -0,0 +1,59 @@
+package com.github.junrar.io;
+
+import java.io.BufferedInputStream;
+import java.io.IOException;
+import java.io.InputStream;
+
+
+
+
+/**
+ * InputStream based implementation of the <code>IReadOnlyAccess</code> interface.
+ *
+ * @see http://rsbweb.nih.gov/ij/
+ * @author martinr
+ */
+public class InputStreamReadOnlyAccessFile implements IReadOnlyAccess {
+ private RandomAccessStream is;
+
+ /**
+ * Create new instance.
+ *
+ * @param is The input stream to wrap.
+ */
+ public InputStreamReadOnlyAccessFile(final InputStream is) {
+ this.is = new RandomAccessStream(new BufferedInputStream(is));
+ }
+
+ @Override
+ public long getPosition() throws IOException {
+ return is.getLongFilePointer();
+ }
+
+ @Override
+ public void setPosition(long pos) throws IOException {
+ is.seek(pos);
+ }
+
+ @Override
+ public int read() throws IOException {
+ return is.read();
+ }
+
+ @Override
+ public int read(byte[] buffer, int off, int count) throws IOException {
+ return is.read(buffer, off, count);
+ }
+
+ @Override
+ public int readFully(byte[] buffer, int count) throws IOException {
+ is.readFully(buffer, count);
+ return count;
+ }
+
+ @Override
+ public void close() throws IOException {
+ is.close();
+ }
+
+}
diff --git a/src/com/github/junrar/io/RandomAccessStream.java b/src/com/github/junrar/io/RandomAccessStream.java
new file mode 100644
index 0000000..49442bf
--- /dev/null
+++ b/src/com/github/junrar/io/RandomAccessStream.java
@@ -0,0 +1,203 @@
+/*
+ * public domain as of http://rsbweb.nih.gov/ij/disclaimer.html
+ */
+package com.github.junrar.io;
+
+import java.io.*;
+import java.util.Vector;
+
+/**
+ * This is a class that uses a memory cache to allow seeking within an
+ * InputStream. Based on the JAI MemoryCacheSeekableStream class. Can also be
+ * constructed from a RandomAccessFile, which uses less memory since the memory
+ * cache is not required.
+ */
+@SuppressWarnings("rawtypes")
+public final class RandomAccessStream extends InputStream {
+
+ private static final int BLOCK_SIZE = 512;
+ private static final int BLOCK_MASK = 511;
+ private static final int BLOCK_SHIFT = 9;
+
+ private InputStream src;
+ private RandomAccessFile ras;
+ private long pointer;
+ private Vector data;
+ private int length;
+ private boolean foundEOS;
+
+ /**
+ * Constructs a RandomAccessStream from an InputStream. Seeking backwards is
+ * supported using a memory cache.
+ */
+ public RandomAccessStream(InputStream inputstream) {
+ pointer = 0L;
+ data = new Vector();
+ length = 0;
+ foundEOS = false;
+ src = inputstream;
+ }
+
+ /** Constructs a RandomAccessStream from an RandomAccessFile. */
+ public RandomAccessStream(RandomAccessFile ras) {
+ this.ras = ras;
+ }
+
+ public int getFilePointer() throws IOException {
+ if (ras != null)
+ return (int) ras.getFilePointer();
+ else
+ return (int) pointer;
+ }
+
+ public long getLongFilePointer() throws IOException {
+ if (ras != null)
+ return ras.getFilePointer();
+ else
+ return pointer;
+ }
+
+ public int read() throws IOException {
+ if (ras != null)
+ return ras.read();
+ long l = pointer + 1L;
+ long l1 = readUntil(l);
+ if (l1 >= l) {
+ byte abyte0[] = (byte[]) data
+ .elementAt((int) (pointer >> BLOCK_SHIFT));
+ return abyte0[(int) (pointer++ & BLOCK_MASK)] & 0xff;
+ } else
+ return -1;
+ }
+
+ public int read(byte[] bytes, int off, int len) throws IOException {
+ if (bytes == null)
+ throw new NullPointerException();
+ if (ras != null)
+ return ras.read(bytes, off, len);
+ if (off < 0 || len < 0 || off + len > bytes.length)
+ throw new IndexOutOfBoundsException();
+ if (len == 0)
+ return 0;
+ long l = readUntil(pointer + len);
+ if (l <= pointer)
+ return -1;
+ else {
+ byte abyte1[] = (byte[]) data
+ .elementAt((int) (pointer >> BLOCK_SHIFT));
+ int k = Math.min(len, BLOCK_SIZE - (int) (pointer & BLOCK_MASK));
+ System.arraycopy(abyte1, (int) (pointer & BLOCK_MASK), bytes, off,
+ k);
+ pointer += k;
+ return k;
+ }
+ }
+
+ public final void readFully(byte[] bytes) throws IOException {
+ readFully(bytes, bytes.length);
+ }
+
+ public final void readFully(byte[] bytes, int len) throws IOException {
+ int read = 0;
+ do {
+ int l = read(bytes, read, len - read);
+ if (l < 0)
+ break;
+ read += l;
+ } while (read < len);
+ }
+
+ @SuppressWarnings("unchecked")
+ private long readUntil(long l) throws IOException {
+ if (l < length)
+ return l;
+ if (foundEOS)
+ return length;
+ int i = (int) (l >> BLOCK_SHIFT);
+ int j = length >> BLOCK_SHIFT;
+ for (int k = j; k <= i; k++) {
+ byte abyte0[] = new byte[BLOCK_SIZE];
+ data.addElement(abyte0);
+ int i1 = BLOCK_SIZE;
+ int j1 = 0;
+ while (i1 > 0) {
+ int k1 = src.read(abyte0, j1, i1);
+ if (k1 == -1) {
+ foundEOS = true;
+ return length;
+ }
+ j1 += k1;
+ i1 -= k1;
+ length += k1;
+ }
+
+ }
+
+ return length;
+ }
+
+ public void seek(long loc) throws IOException {
+ if (ras != null) {
+ ras.seek(loc);
+ return;
+ }
+ if (loc < 0L)
+ pointer = 0L;
+ else
+ pointer = loc;
+ }
+
+ public void seek(int loc) throws IOException {
+ long lloc = ((long) loc) & 0xffffffffL;
+ if (ras != null) {
+ ras.seek(lloc);
+ return;
+ }
+ if (lloc < 0L)
+ pointer = 0L;
+ else
+ pointer = lloc;
+ }
+
+ public final int readInt() throws IOException {
+ int i = read();
+ int j = read();
+ int k = read();
+ int l = read();
+ if ((i | j | k | l) < 0)
+ throw new EOFException();
+ else
+ return (i << 24) + (j << 16) + (k << 8) + l;
+ }
+
+ public final long readLong() throws IOException {
+ return ((long) readInt() << 32) + ((long) readInt() & 0xffffffffL);
+ }
+
+ public final double readDouble() throws IOException {
+ return Double.longBitsToDouble(readLong());
+ }
+
+ public final short readShort() throws IOException {
+ int i = read();
+ int j = read();
+ if ((i | j) < 0)
+ throw new EOFException();
+ else
+ return (short) ((i << 8) + j);
+ }
+
+ public final float readFloat() throws IOException {
+ return Float.intBitsToFloat(readInt());
+ }
+
+ public void close() throws IOException {
+ if (ras != null)
+ ras.close();
+ else {
+ data.removeAllElements();
+ src.close();
+ }
+ }
+
+} \ No newline at end of file
diff --git a/src/com/github/junrar/io/Raw.java b/src/com/github/junrar/io/Raw.java
new file mode 100644
index 0000000..87affda
--- /dev/null
+++ b/src/com/github/junrar/io/Raw.java
@@ -0,0 +1,305 @@
+/*
+ * Copyright (c) 2007 innoSysTec (R) GmbH, Germany. All rights reserved.
+ * Original author: Edmund Wagner
+ * Creation date: 18.06.2007
+ *
+ * Source: $HeadURL$
+ * Last changed: $LastChangedDate$
+ *
+ * the unrar licence applies to all junrar source and binary distributions
+ * you are not allowed to use this source to re-create the RAR compression algorithm
+ *
+ * Here some html entities which can be used for escaping javadoc tags:
+ * "&": "&#038;" or "&amp;"
+ * "<": "&#060;" or "&lt;"
+ * ">": "&#062;" or "&gt;"
+ * "@": "&#064;"
+ */
+package com.github.junrar.io;
+
+/**
+ * Read / write numbers to a byte[] regarding the endianness of the array
+ *
+ * @author $LastChangedBy$
+ * @version $LastChangedRevision$
+ */
+public class Raw {
+ /**
+ * Read a short value from the byte array at the given position (Big Endian)
+ *
+ * @param array
+ * the array to read from
+ * @param pos
+ * the position
+ * @return the value
+ */
+ public static final short readShortBigEndian(byte[] array, int pos) {
+ short temp = 0;
+ temp |= array[pos] & 0xff;
+ temp <<= 8;
+ temp |= array[pos + 1] & 0xff;
+ return temp;
+ }
+
+ /**
+ * Read a int value from the byte array at the given position (Big Endian)
+ *
+ * @param array
+ * the array to read from
+ * @param pos
+ * the offset
+ * @return the value
+ */
+ public static final int readIntBigEndian(byte[] array, int pos) {
+ int temp = 0;
+ temp |= array[pos] & 0xff;
+ temp <<= 8;
+ temp |= array[pos + 1] & 0xff;
+ temp <<= 8;
+ temp |= array[pos + 2] & 0xff;
+ temp <<= 8;
+ temp |= array[pos + 3] & 0xff;
+ return temp;
+ }
+
+ /**
+ * Read a long value from the byte array at the given position (Big Endian)
+ *
+ * @param array
+ * the array to read from
+ * @param pos
+ * the offset
+ * @return the value
+ */
+ public static final long readLongBigEndian(byte[] array, int pos) {
+ int temp = 0;
+ temp |= array[pos] & 0xff;
+ temp <<= 8;
+ temp |= array[pos + 1] & 0xff;
+ temp <<= 8;
+ temp |= array[pos + 2] & 0xff;
+ temp <<= 8;
+ temp |= array[pos + 3] & 0xff;
+ temp <<= 8;
+ temp |= array[pos + 4] & 0xff;
+ temp <<= 8;
+ temp |= array[pos + 5] & 0xff;
+ temp <<= 8;
+ temp |= array[pos + 6] & 0xff;
+ temp <<= 8;
+ temp |= array[pos + 7] & 0xff;
+ return temp;
+ }
+
+ /**
+ * Read a short value from the byte array at the given position (little
+ * Endian)
+ *
+ * @param array
+ * the array to read from
+ * @param pos
+ * the offset
+ * @return the value
+ */
+ public static final short readShortLittleEndian(byte[] array, int pos) {
+ short result = 0;
+ result += array[pos + 1] & 0xff;
+ result <<= 8;
+ result += array[pos] & 0xff;
+ return result;
+ }
+
+ /**
+ * Read an int value from the byte array at the given position (little
+ * Endian)
+ *
+ * @param array
+ * the array to read from
+ * @param pos
+ * the offset
+ * @return the value
+ */
+ public static final int readIntLittleEndian(byte[] array, int pos) {
+ return ((array[pos + 3] & 0xff) << 24)
+ | ((array[pos + 2] & 0xff) << 16)
+ | ((array[pos + 1] & 0xff) << 8) | ((array[pos] & 0xff));
+ }
+
+ /**
+ * Read an long value(unsigned int) from the byte array at the given
+ * position (little Endian)
+ *
+ * @param array
+ * @param pos
+ * @return
+ */
+ public static final long readIntLittleEndianAsLong(byte[] array, int pos) {
+ return (((long) array[pos + 3] & 0xff) << 24)
+ | (((long) array[pos + 2] & 0xff) << 16)
+ | (((long) array[pos + 1] & 0xff) << 8)
+ | (((long) array[pos] & 0xff));
+ }
+
+ /**
+ * Read a long value from the byte array at the given position (little
+ * Endian)
+ *
+ * @param array
+ * the array to read from
+ * @param pos
+ * the offset
+ * @return the value
+ */
+ public static final long readLongLittleEndian(byte[] array, int pos) {
+ int temp = 0;
+ temp |= array[pos + 7] & 0xff;
+ temp <<= 8;
+ temp |= array[pos + 6] & 0xff;
+ temp <<= 8;
+ temp |= array[pos + 5] & 0xff;
+ temp <<= 8;
+ temp |= array[pos + 4] & 0xff;
+ temp <<= 8;
+ temp |= array[pos + 3] & 0xff;
+ temp <<= 8;
+ temp |= array[pos + 2] & 0xff;
+ temp <<= 8;
+ temp |= array[pos + 1] & 0xff;
+ temp <<= 8;
+ temp |= array[pos];
+ return temp;
+ }
+
+ /**
+ * Write a short value into the byte array at the given position (Big
+ * endian)
+ *
+ * @param array
+ * the array
+ * @param pos
+ * the offset
+ * @param value
+ * the value to write
+ */
+ public static final void writeShortBigEndian(byte[] array, int pos,
+ short value) {
+ array[pos] = (byte) (value >>> 8);
+ array[pos + 1] = (byte) (value & 0xFF);
+
+ }
+
+ /**
+ * Write an int value into the byte array at the given position (Big endian)
+ *
+ * @param array
+ * the array
+ * @param pos
+ * the offset
+ * @param value
+ * the value to write
+ */
+ public static final void writeIntBigEndian(byte[] array, int pos, int value) {
+ array[pos] = (byte) ((value >>> 24) & 0xff);
+ array[pos + 1] = (byte) ((value >>> 16) & 0xff);
+ array[pos + 2] = (byte) ((value >>> 8) & 0xff);
+ array[pos + 3] = (byte) ((value) & 0xff);
+
+ }
+
+ /**
+ * Write a long value into the byte array at the given position (Big endian)
+ *
+ * @param array
+ * the array
+ * @param pos
+ * the offset
+ * @param value
+ * the value to write
+ */
+ public static final void writeLongBigEndian(byte[] array, int pos,
+ long value) {
+ array[pos] = (byte) (value >>> 56);
+ array[pos + 1] = (byte) (value >>> 48);
+ array[pos + 2] = (byte) (value >>> 40);
+ array[pos + 3] = (byte) (value >>> 32);
+ array[pos + 4] = (byte) (value >>> 24);
+ array[pos + 5] = (byte) (value >>> 16);
+ array[pos + 6] = (byte) (value >>> 8);
+ array[pos + 7] = (byte) (value & 0xFF);
+
+ }
+
+ /**
+ * Write a short value into the byte array at the given position (little
+ * endian)
+ *
+ * @param array
+ * the array
+ * @param pos
+ * the offset
+ * @param value
+ * the value to write
+ */
+ public static final void writeShortLittleEndian(byte[] array, int pos,
+ short value) {
+ array[pos + 1] = (byte) (value >>> 8);
+ array[pos] = (byte) (value & 0xFF);
+
+ }
+
+ /**
+ * Increment a short value at the specified position by the specified amount
+ * (little endian).
+ */
+ public static final void incShortLittleEndian(byte[] array, int pos, int dv) {
+ int c = ((array[pos] & 0xff) + (dv & 0xff)) >>> 8;
+ array[pos] += dv & 0xff;
+ if ((c > 0) || ((dv & 0xff00) != 0)) {
+ array[pos + 1] += ((dv >>> 8) & 0xff) + c;
+ }
+ }
+
+ /**
+ * Write an int value into the byte array at the given position (little
+ * endian)
+ *
+ * @param array
+ * the array
+ * @param pos
+ * the offset
+ * @param value
+ * the value to write
+ */
+ public static final void writeIntLittleEndian(byte[] array, int pos,
+ int value) {
+ array[pos + 3] = (byte) (value >>> 24);
+ array[pos + 2] = (byte) (value >>> 16);
+ array[pos + 1] = (byte) (value >>> 8);
+ array[pos] = (byte) (value & 0xFF);
+
+ }
+
+ /**
+ * Write a long value into the byte array at the given position (little
+ * endian)
+ *
+ * @param array
+ * the array
+ * @param pos
+ * the offset
+ * @param value
+ * the value to write
+ */
+ public static final void writeLongLittleEndian(byte[] array, int pos,
+ long value) {
+ array[pos + 7] = (byte) (value >>> 56);
+ array[pos + 6] = (byte) (value >>> 48);
+ array[pos + 5] = (byte) (value >>> 40);
+ array[pos + 4] = (byte) (value >>> 32);
+ array[pos + 3] = (byte) (value >>> 24);
+ array[pos + 2] = (byte) (value >>> 16);
+ array[pos + 1] = (byte) (value >>> 8);
+ array[pos] = (byte) (value & 0xFF);
+
+ }
+}
diff --git a/src/com/github/junrar/io/ReadOnlyAccessByteArray.java b/src/com/github/junrar/io/ReadOnlyAccessByteArray.java
new file mode 100644
index 0000000..bbdb687
--- /dev/null
+++ b/src/com/github/junrar/io/ReadOnlyAccessByteArray.java
@@ -0,0 +1,90 @@
+/*
+ * Copyright (c) 2007 innoSysTec (R) GmbH, Germany. All rights reserved.
+ * Original author: Edmund Wagner
+ * Creation date: 30.05.2007
+ *
+ * Source: $HeadURL$
+ * Last changed: $LastChangedDate$
+ *
+ * the unrar licence applies to all junrar source and binary distributions
+ * you are not allowed to use this source to re-create the RAR compression algorithm
+ *
+ * Here some html entities which can be used for escaping javadoc tags:
+ * "&": "&#038;" or "&amp;"
+ * "<": "&#060;" or "&lt;"
+ * ">": "&#062;" or "&gt;"
+ * "@": "&#064;"
+ */
+package com.github.junrar.io;
+
+import java.io.EOFException;
+import java.io.IOException;
+
+/**
+ * A File like access to a byte array.
+ * (seek and read certain number of bytes)
+ *
+ * @author $LastChangedBy$
+ * @version $LastChangedRevision$
+ */
+public class ReadOnlyAccessByteArray implements IReadOnlyAccess{
+
+ private int positionInFile;
+ private byte[] file;
+
+ /**
+ * Initialize with byte[ ]
+ * @param file the file given as byte array
+ */
+ public ReadOnlyAccessByteArray(byte[] file){
+ if(file == null){
+ throw new NullPointerException("file must not be null!!");
+ }
+ this.file = file;
+ this.positionInFile = 0;
+ }
+
+ public long getPosition() throws IOException {
+ return positionInFile;
+ }
+
+ public void setPosition(long pos) throws IOException {
+ if (pos < file.length && pos >= 0){
+ this.positionInFile = (int)pos;
+ }
+ else{
+ throw new EOFException();
+ }
+ }
+
+ /** Read a single byte of data. */
+ public int read() throws IOException {
+ return file[positionInFile++];
+ }
+
+ /**
+ * Read up to <tt>count</tt> bytes to the specified buffer.
+ */
+ public int read(byte[] buffer, int off, int count) throws IOException {
+ int read = Math.min(count, file.length-positionInFile);
+ System.arraycopy(file, positionInFile, buffer, off, read);
+ positionInFile += read;
+ return read;
+ }
+
+ public int readFully(byte[] buffer, int count) throws IOException {
+ if(buffer == null ){
+ throw new NullPointerException("buffer must not be null");
+ }
+ if(count == 0){
+ throw new IllegalArgumentException("cannot read 0 bytes ;-)");
+ }
+ int read = Math.min(count, file.length-(int)positionInFile-1);
+ System.arraycopy(file, (int)positionInFile, buffer, 0, read );
+ positionInFile+=read;
+ return read;
+ }
+
+ public void close() throws IOException {
+ }
+}
diff --git a/src/com/github/junrar/io/ReadOnlyAccessFile.java b/src/com/github/junrar/io/ReadOnlyAccessFile.java
new file mode 100644
index 0000000..77ad35a
--- /dev/null
+++ b/src/com/github/junrar/io/ReadOnlyAccessFile.java
@@ -0,0 +1,55 @@
+/*
+ * Copyright (c) 2007 innoSysTec (R) GmbH, Germany. All rights reserved.
+ * Original author: Edmund Wagner
+ * Creation date: 23.05.2007
+ *
+ * Source: $HeadURL$
+ * Last changed: $LastChangedDate$
+ *
+ * the unrar licence applies to all junrar source and binary distributions
+ * you are not allowed to use this source to re-create the RAR compression algorithm
+ *
+ * Here some html entities which can be used for escaping javadoc tags:
+ * "&": "&#038;" or "&amp;"
+ * "<": "&#060;" or "&lt;"
+ * ">": "&#062;" or "&gt;"
+ * "@": "&#064;"
+ */
+package com.github.junrar.io;
+
+import java.io.File;
+import java.io.FileNotFoundException;
+import java.io.IOException;
+import java.io.RandomAccessFile;
+
+/**
+ * DOCUMENT ME
+ *
+ * @author $LastChangedBy$
+ * @version $LastChangedRevision$
+ */
+public class ReadOnlyAccessFile extends RandomAccessFile
+ implements IReadOnlyAccess{
+
+ /**
+ * @param file the file
+ * @throws FileNotFoundException
+ */
+ public ReadOnlyAccessFile(File file) throws FileNotFoundException {
+ super(file, "r");
+ }
+
+ public int readFully(byte[] buffer, int count) throws IOException {
+ assert (count > 0) : count;
+ this.readFully(buffer, 0, count);
+ return count;
+ }
+
+ public long getPosition() throws IOException {
+ return this.getFilePointer();
+ }
+
+ public void setPosition(long pos) throws IOException {
+ this.seek(pos);
+ }
+}
diff --git a/src/com/github/junrar/io/ReadOnlyAccessInputStream.java b/src/com/github/junrar/io/ReadOnlyAccessInputStream.java
new file mode 100644
index 0000000..80c022e
--- /dev/null
+++ b/src/com/github/junrar/io/ReadOnlyAccessInputStream.java
@@ -0,0 +1,81 @@
+/*
+ * Copyright (c) 2007 innoSysTec (R) GmbH, Germany. All rights reserved.
+ * Original author: Edmund Wagner
+ * Creation date: 26.06.2007
+ *
+ * Source: $HeadURL$
+ * Last changed: $LastChangedDate$
+ *
+ * the unrar licence applies to all junrar source and binary distributions
+ * you are not allowed to use this source to re-create the RAR compression
+ * algorithm
+ *
+ * Here some html entities which can be used for escaping javadoc tags:
+ * "&": "&#038;" or "&amp;"
+ * "<": "&#060;" or "&lt;"
+ * ">": "&#062;" or "&gt;"
+ * "@": "&#064;"
+ */
+package com.github.junrar.io;
+
+import java.io.IOException;
+import java.io.InputStream;
+
+/**
+ * DOCUMENT ME
+ *
+ * @author $LastChangedBy$
+ * @version $LastChangedRevision$
+ */
+public class ReadOnlyAccessInputStream extends InputStream {
+ private IReadOnlyAccess file;
+
+ private long curPos;
+ private final long startPos;
+ private final long endPos;
+
+ public ReadOnlyAccessInputStream(IReadOnlyAccess file, long startPos,
+ long endPos) throws IOException {
+ super();
+ this.file = file;
+ this.startPos = startPos;
+ curPos = startPos;
+ this.endPos = endPos;
+ file.setPosition(curPos);
+ }
+
+ @Override
+ public int read() throws IOException {
+ if (curPos == endPos) {
+ return -1;
+ }
+ else {
+ int b = file.read();
+ curPos++;
+ return b;
+ }
+ }
+
+ @Override
+ public int read(byte[] b, int off, int len) throws IOException {
+ if (len == 0) {
+ return 0;
+ }
+ if (curPos == endPos) {
+ return -1;
+ }
+ int bytesRead = file.read(b, off,
+ (int)Math.min(len, endPos - curPos));
+ curPos += bytesRead;
+ return bytesRead;
+ }
+
+ @Override
+ public int read(byte[] b) throws IOException {
+ return read(b, 0, b.length);
+ }
+//
+// public void close() throws IOException {
+// file.close();
+// }
+}
diff --git a/src/com/github/junrar/rarfile/AVHeader.java b/src/com/github/junrar/rarfile/AVHeader.java
new file mode 100644
index 0000000..66e9dbb
--- /dev/null
+++ b/src/com/github/junrar/rarfile/AVHeader.java
@@ -0,0 +1,66 @@
+/*
+ * Copyright (c) 2007 innoSysTec (R) GmbH, Germany. All rights reserved.
+ * Original author: Edmund Wagner
+ * Creation date: 24.05.2007
+ *
+ * Source: $HeadURL$
+ * Last changed: $LastChangedDate$
+ *
+ *
+ * the unrar licence applies to all junrar source and binary distributions
+ * you are not allowed to use this source to re-create the RAR compression algorithm
+ *
+ * Here some html entities which can be used for escaping javadoc tags:
+ * "&": "&#038;" or "&amp;"
+ * "<": "&#060;" or "&lt;"
+ * ">": "&#062;" or "&gt;"
+ * "@": "&#064;"
+ */
+package com.github.junrar.rarfile;
+
+import com.github.junrar.io.Raw;
+
+/**
+ * extended version info header
+ *
+ * @author $LastChangedBy$
+ * @version $LastChangedRevision$
+ */
+public class AVHeader extends BaseBlock {
+
+ public static final int avHeaderSize = 7;
+
+ private byte unpackVersion;
+ private byte method;
+ private byte avVersion;
+ private int avInfoCRC;
+
+ public AVHeader(BaseBlock bb, byte[] avHeader){
+ super(bb);
+
+ int pos =0;
+ unpackVersion |= avHeader[pos]&0xff;
+ pos++;
+ method |= avHeader[pos]&0xff;
+ pos++;
+ avVersion |= avHeader[pos]&0xff;
+ pos++;
+ avInfoCRC = Raw.readIntLittleEndian(avHeader, pos);
+ }
+
+ public int getAvInfoCRC() {
+ return avInfoCRC;
+ }
+
+ public byte getAvVersion() {
+ return avVersion;
+ }
+
+ public byte getMethod() {
+ return method;
+ }
+
+ public byte getUnpackVersion() {
+ return unpackVersion;
+ }
+}
diff --git a/src/com/github/junrar/rarfile/BaseBlock.java b/src/com/github/junrar/rarfile/BaseBlock.java
new file mode 100644
index 0000000..68c2d94
--- /dev/null
+++ b/src/com/github/junrar/rarfile/BaseBlock.java
@@ -0,0 +1,179 @@
+/*
+ * Copyright (c) 2007 innoSysTec (R) GmbH, Germany. All rights reserved.
+ * Original author: Edmund Wagner
+ * Creation date: 22.05.2007
+ *
+ * Source: $HeadURL$
+ * Last changed: $LastChangedDate$
+ *
+ *
+ * the unrar licence applies to all junrar source and binary distributions
+ * you are not allowed to use this source to re-create the RAR compression algorithm
+ *
+ * Here some html entities which can be used for escaping javadoc tags:
+ * "&": "&#038;" or "&amp;"
+ * "<": "&#060;" or "&lt;"
+ * ">": "&#062;" or "&gt;"
+ * "@": "&#064;"
+ */
+package com.github.junrar.rarfile;
+
+import com.github.junrar.io.Raw;
+
+
+
+/**
+ * Base class of all rar headers
+ *
+ * @author $LastChangedBy$
+ * @version $LastChangedRevision$
+ */
+public class BaseBlock{
+
+ //Log //logger = LogFactory.getLog(BaseBlock.class.getName());
+
+ public static final short BaseBlockSize = 7;
+
+ //TODO move somewhere else
+
+ public static final short MHD_VOLUME = 0x0001;
+ public static final short MHD_COMMENT = 0x0002;
+ public static final short MHD_LOCK = 0x0004;
+ public static final short MHD_SOLID = 0x0008;
+ public static final short MHD_PACK_COMMENT = 0x0010;
+ public static final short MHD_NEWNUMBERING = 0x0010;
+ public static final short MHD_AV = 0x0020;
+ public static final short MHD_PROTECT = 0x0040;
+ public static final short MHD_PASSWORD = 0x0080;
+ public static final short MHD_FIRSTVOLUME = 0x0100;
+ public static final short MHD_ENCRYPTVER = 0x0200;
+
+
+ public static final short LHD_SPLIT_BEFORE = 0x0001;
+ public static final short LHD_SPLIT_AFTER = 0x0002;
+ public static final short LHD_PASSWORD = 0x0004;
+ public static final short LHD_COMMENT = 0x0008;
+ public static final short LHD_SOLID = 0x0010;
+
+ public static final short LHD_WINDOWMASK = 0x00e0;
+ public static final short LHD_WINDOW64 = 0x0000;
+ public static final short LHD_WINDOW128 = 0x0020;
+ public static final short LHD_WINDOW256 = 0x0040;
+ public static final short LHD_WINDOW512 = 0x0060;
+ public static final short LHD_WINDOW1024 = 0x0080;
+ public static final short LHD_WINDOW2048 = 0x00a0;
+ public static final short LHD_WINDOW4096 = 0x00c0;
+ public static final short LHD_DIRECTORY = 0x00e0;
+
+ public static final short LHD_LARGE = 0x0100;
+ public static final short LHD_UNICODE = 0x0200;
+ public static final short LHD_SALT = 0x0400;
+ public static final short LHD_VERSION = 0x0800;
+ public static final short LHD_EXTTIME = 0x1000;
+ public static final short LHD_EXTFLAGS = 0x2000;
+
+ public static final short SKIP_IF_UNKNOWN = 0x4000;
+ public static final short LONG_BLOCK = -0x8000;
+
+ public static final short EARC_NEXT_VOLUME = 0x0001;
+ public static final short EARC_DATACRC = 0x0002;
+ public static final short EARC_REVSPACE = 0x0004;
+ public static final short EARC_VOLNUMBER = 0x0008;
+
+
+ protected long positionInFile;
+
+ protected short headCRC = 0;
+ protected byte headerType = 0;
+ protected short flags = 0;
+ protected short headerSize = 0 ;
+
+ /**
+ *
+ */
+ public BaseBlock(){
+
+ }
+
+ public BaseBlock(BaseBlock bb){
+ this.flags = bb.getFlags();
+ this.headCRC = bb.getHeadCRC();
+ this.headerType = bb.getHeaderType().getHeaderByte();
+ this.headerSize = bb.getHeaderSize();
+ this.positionInFile = bb.getPositionInFile();
+ }
+ public BaseBlock(byte[] baseBlockHeader){
+
+ int pos = 0;
+ this.headCRC = Raw.readShortLittleEndian(baseBlockHeader, pos);
+ pos+=2;
+ this.headerType |= baseBlockHeader[pos]&0xff;
+ pos++;
+ this.flags = Raw.readShortLittleEndian(baseBlockHeader, pos);
+ pos+=2;
+ this.headerSize = Raw.readShortLittleEndian(baseBlockHeader, pos);
+ }
+
+
+ public boolean hasArchiveDataCRC(){
+ return (this.flags & EARC_DATACRC)!=0;
+ }
+
+ public boolean hasVolumeNumber(){
+ return (this.flags & EARC_VOLNUMBER)!=0;
+ }
+
+ public boolean hasEncryptVersion(){
+ return (flags & MHD_ENCRYPTVER)!=0;
+ }
+
+ /**
+ * @return is it a sub block
+ */
+ public boolean isSubBlock()
+ {
+ if (UnrarHeadertype.SubHeader.equals(headerType)){
+ return(true);
+ }
+ if (UnrarHeadertype.NewSubHeader.equals(headerType) && (flags & LHD_SOLID)!=0)
+ {
+ return(true);
+ }
+ return(false);
+
+ }
+
+ public long getPositionInFile() {
+ return positionInFile;
+ }
+
+ public short getFlags() {
+ return flags;
+ }
+
+ public short getHeadCRC() {
+ return headCRC;
+ }
+
+ public short getHeaderSize() {
+ return headerSize;
+ }
+
+ public UnrarHeadertype getHeaderType() {
+ return UnrarHeadertype.findType(headerType);
+ }
+
+ public void setPositionInFile(long positionInFile) {
+ this.positionInFile = positionInFile;
+ }
+
+ public void print(){
+ StringBuilder str =new StringBuilder();
+ str.append("HeaderType: " + getHeaderType());
+ str.append("\nHeadCRC: "+Integer.toHexString(getHeadCRC()));
+ str.append("\nFlags: "+Integer.toHexString(getFlags()));
+ str.append("\nHeaderSize: "+getHeaderSize());
+ str.append("\nPosition in file: "+getPositionInFile());
+ //logger.info(str.toString());
+ }
+}
diff --git a/src/com/github/junrar/rarfile/BlockHeader.java b/src/com/github/junrar/rarfile/BlockHeader.java
new file mode 100644
index 0000000..78fe955
--- /dev/null
+++ b/src/com/github/junrar/rarfile/BlockHeader.java
@@ -0,0 +1,70 @@
+/*
+ * Copyright (c) 2007 innoSysTec (R) GmbH, Germany. All rights reserved.
+ * Original author: Edmund Wagner
+ * Creation date: 22.05.2007
+ *
+ * Source: $HeadURL$
+ * Last changed: $LastChangedDate$
+ *
+ *
+ * the unrar licence applies to all junrar source and binary distributions
+ * you are not allowed to use this source to re-create the RAR compression algorithm
+ *
+ * Here some html entities which can be used for escaping javadoc tags:
+ * "&": "&#038;" or "&amp;"
+ * "<": "&#060;" or "&lt;"
+ * ">": "&#062;" or "&gt;"
+ * "@": "&#064;"
+ */
+package com.github.junrar.rarfile;
+
+import com.github.junrar.io.Raw;
+
+
+/**
+ * Base class of headers that contain data
+ *
+ * @author $LastChangedBy$
+ * @version $LastChangedRevision$
+ */
+public class BlockHeader extends BaseBlock{
+ public static final short blockHeaderSize = 4;
+
+ //private Log //logger = LogFactory.getLog(BlockHeader.class.getName());
+
+ private int dataSize;
+ private int packSize;
+
+ public BlockHeader(){
+
+ }
+
+ public BlockHeader(BlockHeader bh){
+ super(bh);
+ this.packSize = bh.getDataSize();
+ this.dataSize = packSize;
+ this.positionInFile = bh.getPositionInFile();
+ }
+
+ public BlockHeader(BaseBlock bb, byte[] blockHeader)
+ {
+ super(bb);
+
+ this.packSize = Raw.readIntLittleEndian(blockHeader, 0);
+ this.dataSize = this.packSize;
+ }
+
+ public int getDataSize() {
+ return dataSize;
+ }
+
+ public int getPackSize() {
+ return packSize;
+ }
+
+ public void print(){
+ super.print();
+ String s = "DataSize: "+getDataSize()+" packSize: "+getPackSize();
+ //logger.info(s);
+ }
+}
diff --git a/src/com/github/junrar/rarfile/CommentHeader.java b/src/com/github/junrar/rarfile/CommentHeader.java
new file mode 100644
index 0000000..2664330
--- /dev/null
+++ b/src/com/github/junrar/rarfile/CommentHeader.java
@@ -0,0 +1,70 @@
+/*
+ * Copyright (c) 2007 innoSysTec (R) GmbH, Germany. All rights reserved.
+ * Original author: Edmund Wagner
+ * Creation date: 23.05.2007
+ *
+ * Source: $HeadURL$
+ * Last changed: $LastChangedDate$
+ *
+ *
+ * the unrar licence applies to all junrar source and binary distributions
+ * you are not allowed to use this source to re-create the RAR compression algorithm
+ *
+ * Here some html entities which can be used for escaping javadoc tags:
+ * "&": "&#038;" or "&amp;"
+ * "<": "&#060;" or "&lt;"
+ * ">": "&#062;" or "&gt;"
+ * "@": "&#064;"
+ */
+
+package com.github.junrar.rarfile;
+
+import com.github.junrar.io.Raw;
+
+/**
+ * Comment header
+ *
+ * @author $LastChangedBy$
+ * @version $LastChangedRevision$
+ */
+public class CommentHeader extends BaseBlock {
+
+ public static final short commentHeaderSize = 6;
+
+ private short unpSize;
+ private byte unpVersion;
+ private byte unpMethod;
+ private short commCRC;
+
+
+ public CommentHeader(BaseBlock bb, byte[] commentHeader){
+ super(bb);
+
+ int pos =0;
+ unpSize = Raw.readShortLittleEndian(commentHeader, pos);
+ pos += 2;
+ unpVersion |= commentHeader[pos]&0xff;
+ pos++;
+
+ unpMethod |= commentHeader[pos]&0xff;
+ pos++;
+ commCRC =Raw.readShortLittleEndian(commentHeader, pos);
+
+ }
+
+ public short getCommCRC() {
+ return commCRC;
+ }
+
+ public byte getUnpMethod() {
+ return unpMethod;
+ }
+
+ public short getUnpSize() {
+ return unpSize;
+ }
+
+ public byte getUnpVersion() {
+ return unpVersion;
+ }
+}
diff --git a/src/com/github/junrar/rarfile/EAHeader.java b/src/com/github/junrar/rarfile/EAHeader.java
new file mode 100644
index 0000000..762e644
--- /dev/null
+++ b/src/com/github/junrar/rarfile/EAHeader.java
@@ -0,0 +1,90 @@
+/*
+ * Copyright (c) 2007 innoSysTec (R) GmbH, Germany. All rights reserved.
+ * Original author: Edmund Wagner
+ * Creation date: 27.11.2007
+ *
+ * Source: $HeadURL$
+ * Last changed: $LastChangedDate$
+ *
+ *
+ * the unrar licence applies to all junrar source and binary distributions
+ * you are not allowed to use this source to re-create the RAR compression algorithm
+ *
+ * Here some html entities which can be used for escaping javadoc tags:
+ * "&": "&#038;" or "&amp;"
+ * "<": "&#060;" or "&lt;"
+ * ">": "&#062;" or "&gt;"
+ * "@": "&#064;"
+ */
+package com.github.junrar.rarfile;
+
+import com.github.junrar.io.Raw;
+
+
+/**
+ * extended archive CRC header
+ *
+ */
+public class EAHeader
+extends SubBlockHeader
+{
+ //private Log //logger = LogFactory.getLog(getClass());
+
+ public static final short EAHeaderSize = 10;
+
+ private int unpSize;
+ private byte unpVer;
+ private byte method;
+ private int EACRC;
+
+ public EAHeader(SubBlockHeader sb, byte[] eahead)
+ {
+ super(sb);
+ int pos = 0;
+ unpSize = Raw.readIntLittleEndian(eahead, pos);
+ pos+=4;
+ unpVer |= eahead[pos]&0xff;
+ pos++;
+ method |= eahead[pos]&0xff;
+ pos++;
+ EACRC = Raw.readIntLittleEndian(eahead, pos);
+ }
+
+ /**
+ * @return the eACRC
+ */
+ public int getEACRC() {
+ return EACRC;
+ }
+
+ /**
+ * @return the method
+ */
+ public byte getMethod() {
+ return method;
+ }
+
+ /**
+ * @return the unpSize
+ */
+ public int getUnpSize() {
+ return unpSize;
+ }
+
+ /**
+ * @return the unpVer
+ */
+ public byte getUnpVer() {
+ return unpVer;
+ }
+
+ public void print()
+ {
+ super.print();
+ //logger.info("unpSize: "+unpSize);
+ //logger.info("unpVersion: " + unpVer);
+ //logger.info("method: "+method);
+ //logger.info("EACRC:" + EACRC);
+ }
+}
+
diff --git a/src/com/github/junrar/rarfile/EndArcHeader.java b/src/com/github/junrar/rarfile/EndArcHeader.java
new file mode 100644
index 0000000..5a9be5e
--- /dev/null
+++ b/src/com/github/junrar/rarfile/EndArcHeader.java
@@ -0,0 +1,63 @@
+/*
+ * Copyright (c) 2007 innoSysTec (R) GmbH, Germany. All rights reserved.
+ * Original author: Edmund Wagner
+ * Creation date: 24.05.2007
+ *
+ * Source: $HeadURL$
+ * Last changed: $LastChangedDate$
+ *
+ *
+ * the unrar licence applies to all junrar source and binary distributions
+ * you are not allowed to use this source to re-create the RAR compression algorithm
+ *
+ * Here some html entities which can be used for escaping javadoc tags:
+ * "&": "&#038;" or "&amp;"
+ * "<": "&#060;" or "&lt;"
+ * ">": "&#062;" or "&gt;"
+ * "@": "&#064;"
+ */
+package com.github.junrar.rarfile;
+
+import com.github.junrar.io.Raw;
+
+/**
+ *
+ * the optional End header
+ *
+ */
+public class EndArcHeader extends BaseBlock{
+
+ private static final short EARC_NEXT_VOLUME = 0x0001;
+ private static final short EARC_DATACRC = 0x0002;
+ private static final short EARC_REVSPACE = 0x0004;
+ private static final short EARC_VOLNUMBER = 0x0008;
+
+ private static final short endArcHeaderSize = 6;
+ public static final short endArcArchiveDataCrcSize = 4;
+ public static final short endArcVolumeNumberSize = 2;
+
+ private int archiveDataCRC;
+ private short volumeNumber;
+
+
+ public EndArcHeader(BaseBlock bb, byte[] endArcHeader){
+ super(bb);
+
+ int pos = 0;
+ if(hasArchiveDataCRC()){
+ archiveDataCRC =Raw.readIntLittleEndian(endArcHeader, pos);
+ pos+=4;
+ }
+ if(hasVolumeNumber()){
+ volumeNumber = Raw.readShortLittleEndian(endArcHeader, pos);
+ }
+ }
+
+ public int getArchiveDataCRC() {
+ return archiveDataCRC;
+ }
+
+ public short getVolumeNumber() {
+ return volumeNumber;
+ }
+}
diff --git a/src/com/github/junrar/rarfile/FileHeader.java b/src/com/github/junrar/rarfile/FileHeader.java
new file mode 100644
index 0000000..84dce5e
--- /dev/null
+++ b/src/com/github/junrar/rarfile/FileHeader.java
@@ -0,0 +1,421 @@
+/*
+ * Copyright (c) 2007 innoSysTec (R) GmbH, Germany. All rights reserved.
+ * Original author: Edmund Wagner
+ * Creation date: 22.05.2007
+ *
+ * Source: $HeadURL$
+ * Last changed: $LastChangedDate$
+ *
+ *
+ * the unrar licence applies to all junrar source and binary distributions
+ * you are not allowed to use this source to re-create the RAR compression algorithm
+ *
+ * Here some html entities which can be used for escaping javadoc tags:
+ * "&": "&#038;" or "&amp;"
+ * "<": "&#060;" or "&lt;"
+ * ">": "&#062;" or "&gt;"
+ * "@": "&#064;"
+ */
+package com.github.junrar.rarfile;
+
+import java.util.Calendar;
+import java.util.Date;
+
+import org.apache.commons.logging.Log;
+
+import com.github.junrar.io.Raw;
+
+
+/**
+ * DOCUMENT ME
+ *
+ * @author $LastChangedBy$
+ * @version $LastChangedRevision$
+ */
+public class FileHeader extends BlockHeader {
+
+ //private final Log //logger = LogFactory.getLog(FileHeader.class.getName());
+
+ private static final byte SALT_SIZE = 8;
+
+ private static final byte NEWLHD_SIZE = 32;
+
+ private long unpSize;
+
+ private final HostSystem hostOS;
+
+ private final int fileCRC;
+
+ private final int fileTime;
+
+ private byte unpVersion;
+
+ private byte unpMethod;
+
+ private short nameSize;
+
+ private int highPackSize;
+
+ private int highUnpackSize;
+
+ private final byte[] fileNameBytes;
+
+ private String fileName;
+ private String fileNameW;
+
+ private byte[] subData;
+
+ private final byte[] salt = new byte[SALT_SIZE];
+
+ private Date mTime;
+
+ private Date cTime;
+
+ private Date aTime;
+
+ private Date arcTime;
+
+ private long fullPackSize;
+
+ private long fullUnpackSize;
+
+ private int fileAttr;
+
+ private int subFlags; // same as fileAttr (in header)
+
+ private int recoverySectors = -1;
+
+ public FileHeader(BlockHeader bh, byte[] fileHeader) {
+ super(bh);
+
+ int position = 0;
+ unpSize = Raw.readIntLittleEndianAsLong(fileHeader, position);
+ position += 4;
+ hostOS = HostSystem.findHostSystem(fileHeader[4]);
+ position++;
+
+ fileCRC = Raw.readIntLittleEndian(fileHeader, position);
+ position += 4;
+
+ fileTime = Raw.readIntLittleEndian(fileHeader, position);
+ position += 4;
+
+ unpVersion |= fileHeader[13] & 0xff;
+ position++;
+ unpMethod |= fileHeader[14] & 0xff;
+ position++;
+ nameSize = Raw.readShortLittleEndian(fileHeader, position);
+ position += 2;
+
+ fileAttr = Raw.readIntLittleEndian(fileHeader, position);
+ position += 4;
+ if (isLargeBlock()) {
+ highPackSize = Raw.readIntLittleEndian(fileHeader, position);
+ position += 4;
+
+ highUnpackSize = Raw.readIntLittleEndian(fileHeader, position);
+ position += 4;
+ } else {
+ highPackSize = 0;
+ highUnpackSize = 0;
+ if (unpSize == 0xffffffff) {
+
+ unpSize = 0xffffffff;
+ highUnpackSize = Integer.MAX_VALUE;
+ }
+
+ }
+ fullPackSize |= highPackSize;
+ fullPackSize <<= 32;
+ fullPackSize |= getPackSize();
+
+ fullUnpackSize |= highUnpackSize;
+ fullUnpackSize <<= 32;
+ fullUnpackSize += unpSize;
+
+ nameSize = nameSize > 4 * 1024 ? 4 * 1024 : nameSize;
+
+ fileNameBytes = new byte[nameSize];
+ for (int i = 0; i < nameSize; i++) {
+ fileNameBytes[i] = fileHeader[position];
+ position++;
+ }
+
+ if (isFileHeader()) {
+ if (isUnicode()) {
+ int length = 0;
+ fileName = "";
+ fileNameW = "";
+ while (length < fileNameBytes.length
+ && fileNameBytes[length] != 0) {
+ length++;
+ }
+ byte[] name = new byte[length];
+ System.arraycopy(fileNameBytes, 0, name, 0, name.length);
+ fileName = new String(name);
+ if (length != nameSize) {
+ length++;
+ fileNameW = FileNameDecoder.decode(fileNameBytes, length);
+ }
+ } else {
+ fileName = new String(fileNameBytes);
+ fileNameW = "";
+ }
+ }
+
+ if (UnrarHeadertype.NewSubHeader.equals(headerType)) {
+ int datasize = headerSize - NEWLHD_SIZE - nameSize;
+ if (hasSalt()) {
+ datasize -= SALT_SIZE;
+ }
+ if (datasize > 0) {
+ subData = new byte[datasize];
+ for (int i = 0; i < datasize; i++) {
+ subData[i] = (fileHeader[position]);
+ position++;
+ }
+ }
+
+ if (NewSubHeaderType.SUBHEAD_TYPE_RR.byteEquals(fileNameBytes)) {
+ recoverySectors = subData[8] + (subData[9] << 8)
+ + (subData[10] << 16) + (subData[11] << 24);
+ }
+ }
+
+ if (hasSalt()) {
+ for (int i = 0; i < SALT_SIZE; i++) {
+ salt[i] = fileHeader[position];
+ position++;
+ }
+ }
+ mTime = getDateDos(fileTime);
+ // TODO rartime -> extended
+
+ }
+
+ @Override
+ public void print() {
+ super.print();
+ StringBuilder str = new StringBuilder();
+ str.append("unpSize: " + getUnpSize());
+ str.append("\nHostOS: " + hostOS.name());
+ str.append("\nMDate: " + mTime);
+ str.append("\nFileName: " + getFileNameString());
+ str.append("\nunpMethod: " + Integer.toHexString(getUnpMethod()));
+ str.append("\nunpVersion: " + Integer.toHexString(getUnpVersion()));
+ str.append("\nfullpackedsize: " + getFullPackSize());
+ str.append("\nfullunpackedsize: " + getFullUnpackSize());
+ str.append("\nisEncrypted: " + isEncrypted());
+ str.append("\nisfileHeader: " + isFileHeader());
+ str.append("\nisSolid: " + isSolid());
+ str.append("\nisSplitafter: " + isSplitAfter());
+ str.append("\nisSplitBefore:" + isSplitBefore());
+ str.append("\nunpSize: " + getUnpSize());
+ str.append("\ndataSize: " + getDataSize());
+ str.append("\nisUnicode: " + isUnicode());
+ str.append("\nhasVolumeNumber: " + hasVolumeNumber());
+ str.append("\nhasArchiveDataCRC: " + hasArchiveDataCRC());
+ str.append("\nhasSalt: " + hasSalt());
+ str.append("\nhasEncryptVersions: " + hasEncryptVersion());
+ str.append("\nisSubBlock: " + isSubBlock());
+ //logger.info(str.toString());
+ }
+
+ private Date getDateDos(int time) {
+ Calendar cal = Calendar.getInstance();
+ cal.set(Calendar.YEAR, (time >>> 25) + 1980);
+ cal.set(Calendar.MONTH, ((time >>> 21) & 0x0f) - 1);
+ cal.set(Calendar.DAY_OF_MONTH, (time >>> 16) & 0x1f);
+ cal.set(Calendar.HOUR_OF_DAY, (time >>> 11) & 0x1f);
+ cal.set(Calendar.MINUTE, (time >>> 5) & 0x3f);
+ cal.set(Calendar.SECOND, (time & 0x1f) * 2);
+ return cal.getTime();
+ }
+
+ public Date getArcTime() {
+ return arcTime;
+ }
+
+ public void setArcTime(Date arcTime) {
+ this.arcTime = arcTime;
+ }
+
+ public Date getATime() {
+ return aTime;
+ }
+
+ public void setATime(Date time) {
+ aTime = time;
+ }
+
+ public Date getCTime() {
+ return cTime;
+ }
+
+ public void setCTime(Date time) {
+ cTime = time;
+ }
+
+ public int getFileAttr() {
+ return fileAttr;
+ }
+
+ public void setFileAttr(int fileAttr) {
+ this.fileAttr = fileAttr;
+ }
+
+ public int getFileCRC() {
+ return fileCRC;
+ }
+
+ public byte[] getFileNameByteArray() {
+ return fileNameBytes;
+ }
+
+ public String getFileNameString() {
+ return fileName;
+ }
+
+ public void setFileName(String fileName) {
+ this.fileName = fileName;
+ }
+
+ public String getFileNameW() {
+ return fileNameW;
+ }
+
+ public void setFileNameW(String fileNameW) {
+ this.fileNameW = fileNameW;
+ }
+
+ public int getHighPackSize() {
+ return highPackSize;
+ }
+
+ public int getHighUnpackSize() {
+ return highUnpackSize;
+ }
+
+ public HostSystem getHostOS() {
+ return hostOS;
+ }
+
+ public Date getMTime() {
+ return mTime;
+ }
+
+ public void setMTime(Date time) {
+ mTime = time;
+ }
+
+ public short getNameSize() {
+ return nameSize;
+ }
+
+ public int getRecoverySectors() {
+ return recoverySectors;
+ }
+
+ public byte[] getSalt() {
+ return salt;
+ }
+
+ public byte[] getSubData() {
+ return subData;
+ }
+
+ public int getSubFlags() {
+ return subFlags;
+ }
+
+ public byte getUnpMethod() {
+ return unpMethod;
+ }
+
+ public long getUnpSize() {
+ return unpSize;
+ }
+
+ public byte getUnpVersion() {
+ return unpVersion;
+ }
+
+ public long getFullPackSize() {
+ return fullPackSize;
+ }
+
+ public long getFullUnpackSize() {
+ return fullUnpackSize;
+ }
+
+ @Override
+ public String toString() {
+ return super.toString();
+ }
+
+ /**
+ * the file will be continued in the next archive part
+ *
+ * @return
+ */
+ public boolean isSplitAfter() {
+ return (this.flags & BlockHeader.LHD_SPLIT_AFTER) != 0;
+ }
+
+ /**
+ * the file is continued in this archive
+ *
+ * @return
+ */
+ public boolean isSplitBefore() {
+ return (this.flags & LHD_SPLIT_BEFORE) != 0;
+ }
+
+ /**
+ * this file is compressed as solid (all files handeled as one)
+ *
+ * @return
+ */
+ public boolean isSolid() {
+ return (this.flags & LHD_SOLID) != 0;
+ }
+
+ /**
+ * the file is encrypted
+ *
+ * @return
+ */
+ public boolean isEncrypted() {
+ return (this.flags & BlockHeader.LHD_PASSWORD) != 0;
+ }
+
+ /**
+ * the filename is also present in unicode
+ *
+ * @return
+ */
+ public boolean isUnicode() {
+ return (flags & LHD_UNICODE) != 0;
+ }
+
+ public boolean isFileHeader() {
+ return UnrarHeadertype.FileHeader.equals(headerType);
+ }
+
+ public boolean hasSalt() {
+ return (flags & LHD_SALT) != 0;
+ }
+
+ public boolean isLargeBlock() {
+ return (flags & LHD_LARGE) != 0;
+ }
+
+ /**
+ * whether this fileheader represents a directory
+ *
+ * @return
+ */
+ public boolean isDirectory() {
+ return (flags & LHD_WINDOWMASK) == LHD_DIRECTORY;
+ }
+}
diff --git a/src/com/github/junrar/rarfile/FileNameDecoder.java b/src/com/github/junrar/rarfile/FileNameDecoder.java
new file mode 100644
index 0000000..aee1179
--- /dev/null
+++ b/src/com/github/junrar/rarfile/FileNameDecoder.java
@@ -0,0 +1,76 @@
+/*
+ *
+ * Original author: alpha_lam
+ * Creation date: ?
+ *
+ * Source: $HeadURL$
+ * Last changed: $LastChangedDate$
+ *
+ *
+ * the unrar licence applies to all junrar source and binary distributions
+ * you are not allowed to use this source to re-create the RAR compression algorithm
+ *
+ * Here some html entities which can be used for escaping javadoc tags:
+ * "&": "&#038;" or "&amp;"
+ * "<": "&#060;" or "&lt;"
+ * ">": "&#062;" or "&gt;"
+ * "@": "&#064;"
+ */
+package com.github.junrar.rarfile;
+
+public class FileNameDecoder {
+ public static int getChar(byte [] name,int pos){
+ return name[pos]&0xff;
+ }
+
+ public static String decode(byte [] name,int encPos){
+ int decPos = 0;
+ int flags = 0;
+ int flagBits = 0;
+
+ int low = 0;
+ int high = 0;
+ int highByte = getChar(name,encPos++);
+ StringBuffer buf = new StringBuffer();
+ while(encPos < name.length){
+ if(flagBits == 0){
+ flags = getChar(name,encPos++);
+ flagBits = 8;
+ }
+ switch(flags >> 6){
+ case 0:
+ buf.append((char)(getChar(name,encPos++)));
+ ++decPos;
+ break;
+ case 1:
+ buf.append((char)(getChar(name,encPos++)+(highByte<<8)));
+ ++decPos;
+ break;
+ case 2:
+ low = getChar(name,encPos);
+ high = getChar(name,encPos+1);
+ buf.append((char)((high << 8) + low));
+ ++decPos;
+ encPos += 2;
+ break;
+ case 3:
+ int length = getChar(name,encPos++);
+ if((length&0x80)!=0){
+ int correction = getChar(name,encPos++);
+ for(length=(length&0x7f)+2;length>0&&decPos<name.length;length--,decPos++){
+ low = (getChar(name,decPos) + correction)&0xff;
+ buf.append((char)((highByte << 8) + low));
+ }
+ }else{
+ for(length+=2;length>0&&decPos<name.length;length--,decPos++){
+ buf.append((char)(getChar(name,decPos)));
+ }
+ }
+ break;
+ }
+ flags = (flags << 2) & 0xff;
+ flagBits -= 2;
+ }
+ return buf.toString();
+ }
+}
diff --git a/src/com/github/junrar/rarfile/HostSystem.java b/src/com/github/junrar/rarfile/HostSystem.java
new file mode 100644
index 0000000..7970fef
--- /dev/null
+++ b/src/com/github/junrar/rarfile/HostSystem.java
@@ -0,0 +1,72 @@
+/*
+ * Copyright (c) 2007 innoSysTec (R) GmbH, Germany. All rights reserved.
+ * Original author: Edmund Wagner
+ * Creation date: 22.05.2007
+ *
+ * Source: $HeadURL$
+ * Last changed: $LastChangedDate$
+ *
+ *
+ * the unrar licence applies to all junrar source and binary distributions
+ * you are not allowed to use this source to re-create the RAR compression algorithm
+ *
+ * Here some html entities which can be used for escaping javadoc tags:
+ * "&": "&#038;" or "&amp;"
+ * "<": "&#060;" or "&lt;"
+ * ">": "&#062;" or "&gt;"
+ * "@": "&#064;"
+ */
+package com.github.junrar.rarfile;
+
+/**
+ * DOCUMENT ME
+ *
+ * @author $LastChangedBy$
+ * @version $LastChangedRevision$
+ */
+public enum HostSystem {
+ msdos ((byte)0),
+ os2 ((byte)1),
+ win32 ((byte)2),
+ unix ((byte)3),
+ macos ((byte)4),
+ beos ((byte)5);
+
+ private byte hostByte;
+
+ public static HostSystem findHostSystem(byte hostByte){
+ if(HostSystem.msdos.equals(hostByte)){
+ return HostSystem.msdos;
+ }
+ if(HostSystem.os2.equals(hostByte)){
+ return HostSystem.os2;
+ }
+ if(HostSystem.win32.equals(hostByte)){
+ return HostSystem.win32;
+ }
+ if(HostSystem.unix.equals(hostByte)){
+ return HostSystem.unix;
+ }
+ if(HostSystem.macos.equals(hostByte)){
+ return HostSystem.macos;
+ }
+ if(HostSystem.beos.equals(hostByte)){
+ return HostSystem.beos;
+ }
+ return null;
+ }
+
+
+ private HostSystem(byte hostByte){
+ this.hostByte = hostByte;
+ }
+
+ public boolean equals(byte hostByte){
+ return this.hostByte == hostByte;
+ }
+
+ public byte getHostByte(){
+ return hostByte;
+ }
+ //???? public static final byte max = 6;
+}
diff --git a/src/com/github/junrar/rarfile/MacInfoHeader.java b/src/com/github/junrar/rarfile/MacInfoHeader.java
new file mode 100644
index 0000000..e94521d
--- /dev/null
+++ b/src/com/github/junrar/rarfile/MacInfoHeader.java
@@ -0,0 +1,81 @@
+/*
+ * Copyright (c) 2007 innoSysTec (R) GmbH, Germany. All rights reserved.
+ * Original author: Edmund Wagner
+ * Creation date: 26.11.2007
+ *
+ * Source: $HeadURL$
+ * Last changed: $LastChangedDate$
+ *
+ *
+ * the unrar licence applies to all junrar source and binary distributions
+ * you are not allowed to use this source to re-create the RAR compression algorithm
+ *
+ * Here some html entities which can be used for escaping javadoc tags:
+ * "&": "&#038;" or "&amp;"
+ * "<": "&#060;" or "&lt;"
+ * ">": "&#062;" or "&gt;"
+ * "@": "&#064;"
+ */
+package com.github.junrar.rarfile;
+
+import com.github.junrar.io.Raw;
+
+
+/**
+ * Mac File attribute header
+ *
+ */
+public class MacInfoHeader
+extends SubBlockHeader
+{
+ //private Log //logger = LogFactory.getLog(getClass());
+
+ public static final short MacInfoHeaderSize = 8;
+
+ private int fileType;
+ private int fileCreator;
+
+ public MacInfoHeader(SubBlockHeader sb, byte[] macHeader)
+ {
+ super(sb);
+ int pos = 0;
+ fileType = Raw.readIntLittleEndian(macHeader, pos);
+ pos+=4;
+ fileCreator = Raw.readIntLittleEndian(macHeader, pos);
+ }
+
+ /**
+ * @return the fileCreator
+ */
+ public int getFileCreator() {
+ return fileCreator;
+ }
+
+ /**
+ * @param fileCreator the fileCreator to set
+ */
+ public void setFileCreator(int fileCreator) {
+ this.fileCreator = fileCreator;
+ }
+
+ /**
+ * @return the fileType
+ */
+ public int getFileType() {
+ return fileType;
+ }
+
+ /**
+ * @param fileType the fileType to set
+ */
+ public void setFileType(int fileType) {
+ this.fileType = fileType;
+ }
+
+ public void print(){
+ super.print();
+ //logger.info("filetype: "+fileType);
+ //logger.info("creator :"+fileCreator);
+ }
+
+}
diff --git a/src/com/github/junrar/rarfile/MainHeader.java b/src/com/github/junrar/rarfile/MainHeader.java
new file mode 100644
index 0000000..8c3e89f
--- /dev/null
+++ b/src/com/github/junrar/rarfile/MainHeader.java
@@ -0,0 +1,141 @@
+/*
+ * Copyright (c) 2007 innoSysTec (R) GmbH, Germany. All rights reserved.
+ * Original author: Edmund Wagner
+ * Creation date: 22.05.2007
+ *
+ * Source: $HeadURL$
+ * Last changed: $LastChangedDate$
+ *
+ *
+ * the unrar licence applies to all junrar source and binary distributions
+ * you are not allowed to use this source to re-create the RAR compression algorithm
+ *
+ * Here some html entities which can be used for escaping javadoc tags:
+ * "&": "&#038;" or "&amp;"
+ * "<": "&#060;" or "&lt;"
+ * ">": "&#062;" or "&gt;"
+ * "@": "&#064;"
+ */
+package com.github.junrar.rarfile;
+
+import com.github.junrar.io.Raw;
+
+
+/**
+ * The main header of an rar archive. holds information concerning the whole archive (solid, encrypted etc).
+ *
+ * @author $LastChangedBy$
+ * @version $LastChangedRevision$
+ */
+public class MainHeader extends BaseBlock {
+ //private Log //logger = LogFactory.getLog(MainHeader.class.getName());
+ public static final short mainHeaderSizeWithEnc = 7;
+ public static final short mainHeaderSize = 6;
+ private short highPosAv;
+ private int posAv;
+ private byte encryptVersion;
+
+ public MainHeader(BaseBlock bb, byte[] mainHeader) {
+ super(bb);
+ int pos = 0;
+ highPosAv = Raw.readShortLittleEndian(mainHeader, pos);
+ pos += 2;
+ posAv = Raw.readIntLittleEndian(mainHeader, pos);
+ pos+=4;
+
+ if(hasEncryptVersion()){
+ encryptVersion |= mainHeader[pos]&0xff;
+ }
+ }
+
+ /**
+ * old cmt block is present
+ * @return true if has cmt block
+ */
+ public boolean hasArchCmt(){
+ return (this.flags & BaseBlock.MHD_COMMENT)!=0;
+ }
+ /**
+ * the version the the encryption
+ * @return
+ */
+ public byte getEncryptVersion() {
+ return encryptVersion;
+ }
+
+ public short getHighPosAv() {
+ return highPosAv;
+ }
+
+ public int getPosAv() {
+ return posAv;
+ }
+
+ /**
+ * returns whether the archive is encrypted
+ * @return
+ */
+ public boolean isEncrypted(){
+ return (this.flags & BaseBlock.MHD_PASSWORD)!=0;
+ }
+
+ /**
+ * return whether the archive is a multivolume archive
+ * @return
+ */
+ public boolean isMultiVolume(){
+ return (this.flags & BaseBlock.MHD_VOLUME)!=0;
+ }
+
+ /**
+ * if the archive is a multivolume archive this method returns whether this instance is the first part of the multivolume archive
+ * @return
+ */
+ public boolean isFirstVolume(){
+ return (this.flags & BaseBlock.MHD_FIRSTVOLUME)!=0;
+ }
+
+ public void print(){
+ super.print();
+ StringBuilder str=new StringBuilder();
+ str.append("posav: "+getPosAv());
+ str.append("\nhighposav: "+getHighPosAv());
+ str.append("\nhasencversion: "+hasEncryptVersion()+(hasEncryptVersion()?getEncryptVersion():""));
+ str.append("\nhasarchcmt: "+hasArchCmt());
+ str.append("\nisEncrypted: "+isEncrypted());
+ str.append("\nisMultivolume: "+isMultiVolume());
+ str.append("\nisFirstvolume: "+isFirstVolume());
+ str.append("\nisSolid: "+isSolid());
+ str.append("\nisLocked: "+isLocked());
+ str.append("\nisProtected: "+isProtected());
+ str.append("\nisAV: "+isAV());
+ //logger.info(str.toString());
+ }
+
+ /**
+ * returns whether this archive is solid. in this case you can only extract all file at once
+ * @return
+ */
+ public boolean isSolid(){
+ return (this.flags&MHD_SOLID)!=0;
+ }
+
+ public boolean isLocked(){
+ return (this.flags&MHD_LOCK)!=0;
+ }
+
+ public boolean isProtected(){
+ return (this.flags&MHD_PROTECT)!=0;
+ }
+
+ public boolean isAV(){
+ return (this.flags&MHD_AV)!=0;
+ }
+ /**
+ * the numbering format a multivolume archive
+ * @return
+ */
+ public boolean isNewNumbering(){
+ return (this.flags&MHD_NEWNUMBERING)!=0;
+ }
+}
diff --git a/src/com/github/junrar/rarfile/MarkHeader.java b/src/com/github/junrar/rarfile/MarkHeader.java
new file mode 100644
index 0000000..1673306
--- /dev/null
+++ b/src/com/github/junrar/rarfile/MarkHeader.java
@@ -0,0 +1,84 @@
+/*
+ * Copyright (c) 2007 innoSysTec (R) GmbH, Germany. All rights reserved.
+ * Original author: Edmund Wagner
+ * Creation date: 24.05.2007
+ *
+ * Source: $HeadURL$
+ * Last changed: $LastChangedDate$
+ *
+ *
+ * the unrar licence applies to all junrar source and binary distributions
+ * you are not allowed to use this source to re-create the RAR compression algorithm
+ *
+ * Here some html entities which can be used for escaping javadoc tags:
+ * "&": "&#038;" or "&amp;"
+ * "<": "&#060;" or "&lt;"
+ * ">": "&#062;" or "&gt;"
+ * "@": "&#064;"
+ */
+package com.github.junrar.rarfile;
+
+import com.github.junrar.io.Raw;
+
+
+/**
+ * the header to recognize a file to be a rar archive
+ *
+ * @author $LastChangedBy$
+ * @version $LastChangedRevision$
+ */
+public class MarkHeader extends BaseBlock {
+
+ //private Log //logger = LogFactory.getLog(MarkHeader.class.getName());
+ private boolean oldFormat = false;
+
+ public MarkHeader(BaseBlock bb){
+ super(bb);
+ }
+ public boolean isValid(){
+ if(!(getHeadCRC() == 0x6152)){
+ return false;
+ }
+ if(!(getHeaderType() == UnrarHeadertype.MarkHeader)){
+ return false;
+ }
+ if(!(getFlags() == 0x1a21)){
+ return false;
+ }
+ if(!(getHeaderSize() == BaseBlockSize)){
+ return false;
+ }
+ return true;
+ }
+
+ public boolean isSignature() {
+ boolean valid=false;
+ byte[] d = new byte[BaseBlock.BaseBlockSize];
+ Raw.writeShortLittleEndian(d, 0, headCRC);
+ d[2] = headerType;
+ Raw.writeShortLittleEndian(d, 3, flags);
+ Raw.writeShortLittleEndian(d, 5, headerSize);
+
+ if (d[0] == 0x52) {
+ if (d[1]==0x45 && d[2]==0x7e && d[3]==0x5e) {
+ oldFormat=true;
+ valid=true;
+ }
+ else if (d[1]==0x61 && d[2]==0x72 && d[3]==0x21 && d[4]==0x1a &&
+ d[5]==0x07 && d[6]==0x00) {
+ oldFormat=false;
+ valid=true;
+ }
+ }
+ return valid;
+ }
+
+ public boolean isOldFormat() {
+ return oldFormat;
+ }
+
+ public void print(){
+ super.print();
+ //logger.info("valid: "+isValid());
+ }
+}
diff --git a/src/com/github/junrar/rarfile/NewSubHeaderType.java b/src/com/github/junrar/rarfile/NewSubHeaderType.java
new file mode 100644
index 0000000..e0096f7
--- /dev/null
+++ b/src/com/github/junrar/rarfile/NewSubHeaderType.java
@@ -0,0 +1,89 @@
+/*
+ * Copyright (c) 2007 innoSysTec (R) GmbH, Germany. All rights reserved.
+ * Original author: Edmund Wagner
+ * Creation date: 24.05.2007
+ *
+ * Source: $HeadURL$
+ * Last changed: $LastChangedDate$
+ *
+ *
+ * the unrar licence applies to all junrar source and binary distributions
+ * you are not allowed to use this source to re-create the RAR compression algorithm
+ *
+ * Here some html entities which can be used for escaping javadoc tags:
+ * "&": "&#038;" or "&amp;"
+ * "<": "&#060;" or "&lt;"
+ * ">": "&#062;" or "&gt;"
+ * "@": "&#064;"
+ */
+package com.github.junrar.rarfile;
+
+import java.util.Arrays;
+
+/**
+ * subheaders new version of the info headers
+ *
+ * @author $LastChangedBy$
+ * @version $LastChangedRevision$
+ */
+public class NewSubHeaderType {
+
+ /**
+ * comment subheader
+ */
+ public static final NewSubHeaderType SUBHEAD_TYPE_CMT = new NewSubHeaderType(new byte[]{'C','M','T'});
+ /**
+ *
+ */
+ public static final NewSubHeaderType SUBHEAD_TYPE_ACL = new NewSubHeaderType(new byte[]{'A','C','L'});
+ /**
+ *
+ */
+ public static final NewSubHeaderType SUBHEAD_TYPE_STREAM = new NewSubHeaderType(new byte[]{'S','T','M'});
+ /**
+ *
+ */
+ public static final NewSubHeaderType SUBHEAD_TYPE_UOWNER = new NewSubHeaderType(new byte[]{'U','O','W'});
+ /**
+ *
+ */
+ public static final NewSubHeaderType SUBHEAD_TYPE_AV = new NewSubHeaderType(new byte[]{'A','V'});
+ /**
+ * recovery record subheader
+ */
+ public static final NewSubHeaderType SUBHEAD_TYPE_RR = new NewSubHeaderType(new byte[]{'R','R'});
+ /**
+ *
+ */
+ public static final NewSubHeaderType SUBHEAD_TYPE_OS2EA = new NewSubHeaderType(new byte[]{'E','A','2'});
+ /**
+ *
+ */
+ public static final NewSubHeaderType SUBHEAD_TYPE_BEOSEA = new NewSubHeaderType(new byte[]{'E','A','B','E'});
+
+ private byte[] headerTypes;
+
+ /**
+ * Private constructor
+ * @param headerTypes
+ */
+ private NewSubHeaderType(byte[] headerTypes)
+ {
+ this.headerTypes = headerTypes;
+ }
+
+ /**
+ * @param toCompare
+ * @return Returns true if the given byte array matches to the internal byte array of this header.
+ */
+ public boolean byteEquals(byte[] toCompare)
+ {
+ return Arrays.equals(this.headerTypes, toCompare);
+ }
+
+ @Override
+ public String toString()
+ {
+ return new String(this.headerTypes);
+ }
+}
diff --git a/src/com/github/junrar/rarfile/ProtectHeader.java b/src/com/github/junrar/rarfile/ProtectHeader.java
new file mode 100644
index 0000000..348b25b
--- /dev/null
+++ b/src/com/github/junrar/rarfile/ProtectHeader.java
@@ -0,0 +1,71 @@
+/*
+ * Copyright (c) 2007 innoSysTec (R) GmbH, Germany. All rights reserved.
+ * Original author: Edmund Wagner
+ * Creation date: 24.05.2007
+ *
+ * Source: $HeadURL$
+ * Last changed: $LastChangedDate$
+ *
+ *
+ * the unrar licence applies to all junrar source and binary distributions
+ * you are not allowed to use this source to re-create the RAR compression algorithm
+ *
+ * Here some html entities which can be used for escaping javadoc tags:
+ * "&": "&#038;" or "&amp;"
+ * "<": "&#060;" or "&lt;"
+ * ">": "&#062;" or "&gt;"
+ * "@": "&#064;"
+ */
+package com.github.junrar.rarfile;
+
+import com.github.junrar.io.Raw;
+
+/**
+ * recovery header
+ *
+ * @author $LastChangedBy$
+ * @version $LastChangedRevision$
+ */
+public class ProtectHeader extends BlockHeader {
+
+ /**
+ * the header size
+ */
+ public static final int protectHeaderSize = 8;
+
+ private byte version;
+ private short recSectors;
+ private int totalBlocks;
+ private byte mark;
+
+
+ public ProtectHeader(BlockHeader bh, byte[] protectHeader){
+ super(bh);
+
+ int pos = 0;
+ version |= protectHeader[pos]&0xff;
+
+ recSectors = Raw.readShortLittleEndian(protectHeader, pos);
+ pos += 2;
+ totalBlocks = Raw.readIntLittleEndian(protectHeader, pos);
+ pos += 4;
+ mark |= protectHeader[pos]&0xff;
+ }
+
+
+ public byte getMark() {
+ return mark;
+ }
+
+ public short getRecSectors() {
+ return recSectors;
+ }
+
+ public int getTotalBlocks() {
+ return totalBlocks;
+ }
+
+ public byte getVersion() {
+ return version;
+ }
+}
diff --git a/src/com/github/junrar/rarfile/SignHeader.java b/src/com/github/junrar/rarfile/SignHeader.java
new file mode 100644
index 0000000..e78d4a3
--- /dev/null
+++ b/src/com/github/junrar/rarfile/SignHeader.java
@@ -0,0 +1,60 @@
+/*
+ * Copyright (c) 2007 innoSysTec (R) GmbH, Germany. All rights reserved.
+ * Original author: Edmund Wagner
+ * Creation date: 24.05.2007
+ *
+ * Source: $HeadURL$
+ * Last changed: $LastChangedDate$
+ *
+ *
+ * the unrar licence applies to all junrar source and binary distributions
+ * you are not allowed to use this source to re-create the RAR compression algorithm
+ *
+ * Here some html entities which can be used for escaping javadoc tags:
+ * "&": "&#038;" or "&amp;"
+ * "<": "&#060;" or "&lt;"
+ * ">": "&#062;" or "&gt;"
+ * "@": "&#064;"
+ */
+package com.github.junrar.rarfile;
+
+import com.github.junrar.io.Raw;
+
+/**
+ * sign header
+ *
+ * @author $LastChangedBy$
+ * @version $LastChangedRevision$
+ */
+public class SignHeader extends BaseBlock {
+
+ public static final short signHeaderSize = 8;
+
+ private int creationTime=0;
+ private short arcNameSize=0;
+ private short userNameSize=0;
+
+
+ public SignHeader(BaseBlock bb, byte[] signHeader){
+ super(bb);
+
+ int pos = 0;
+ creationTime = Raw.readIntLittleEndian(signHeader, pos);
+ pos +=4;
+ arcNameSize = Raw.readShortLittleEndian(signHeader, pos);
+ pos+=2;
+ userNameSize = Raw.readShortLittleEndian(signHeader, pos);
+ }
+
+ public short getArcNameSize() {
+ return arcNameSize;
+ }
+
+ public int getCreationTime() {
+ return creationTime;
+ }
+
+ public short getUserNameSize() {
+ return userNameSize;
+ }
+}
diff --git a/src/com/github/junrar/rarfile/SubBlockHeader.java b/src/com/github/junrar/rarfile/SubBlockHeader.java
new file mode 100644
index 0000000..d0e0eed
--- /dev/null
+++ b/src/com/github/junrar/rarfile/SubBlockHeader.java
@@ -0,0 +1,70 @@
+/*
+ * Copyright (c) 2007 innoSysTec (R) GmbH, Germany. All rights reserved.
+ * Original author: Edmund Wagner
+ * Creation date: 21.11.2007
+ *
+ * Source: $HeadURL$
+ * Last changed: $LastChangedDate$
+ *
+ *
+ * the unrar licence applies to all junrar source and binary distributions
+ * you are not allowed to use this source to re-create the RAR compression algorithm
+ *
+ * Here some html entities which can be used for escaping javadoc tags:
+ * "&": "&#038;" or "&amp;"
+ * "<": "&#060;" or "&lt;"
+ * ">": "&#062;" or "&gt;"
+ * "@": "&#064;"
+ */
+package com.github.junrar.rarfile;
+
+import com.github.junrar.io.Raw;
+
+
+public class SubBlockHeader
+extends BlockHeader
+{
+ //private Log //logger = LogFactory.getLog(getClass());
+
+ public static final short SubBlockHeaderSize = 3;
+
+ private short subType;
+ private byte level;
+
+ public SubBlockHeader(SubBlockHeader sb)
+ {
+ super(sb);
+ subType = sb.getSubType().getSubblocktype();
+ level = sb.getLevel();
+ }
+
+ public SubBlockHeader(BlockHeader bh, byte[] subblock)
+ {
+ super(bh);
+ int position = 0;
+ subType = Raw.readShortLittleEndian(subblock, position);
+ position +=2;
+ level |= subblock[position]&0xff;
+ }
+
+ /**
+ * @return
+ */
+ public byte getLevel() {
+ return level;
+ }
+
+ /**
+ * @return
+ */
+ public SubBlockHeaderType getSubType() {
+ return SubBlockHeaderType.findSubblockHeaderType(subType);
+ }
+
+ public void print()
+ {
+ super.print();
+ //logger.info("subtype: "+getSubType());
+ //logger.info("level: "+level);
+ }
+}
diff --git a/src/com/github/junrar/rarfile/SubBlockHeaderType.java b/src/com/github/junrar/rarfile/SubBlockHeaderType.java
new file mode 100644
index 0000000..000f24d
--- /dev/null
+++ b/src/com/github/junrar/rarfile/SubBlockHeaderType.java
@@ -0,0 +1,77 @@
+/*
+ * Copyright (c) 2007 innoSysTec (R) GmbH, Germany. All rights reserved.
+ * Original author: Edmund Wagner
+ * Creation date: 20.11.2007
+ *
+ * Source: $HeadURL$
+ * Last changed: $LastChangedDate$
+ *
+ *
+ * the unrar licence applies to all junrar source and binary distributions
+ * you are not allowed to use this source to re-create the RAR compression algorithm
+ *
+ * Here some html entities which can be used for escaping javadoc tags:
+ * "&": "&#038;" or "&amp;"
+ * "<": "&#060;" or "&lt;"
+ * ">": "&#062;" or "&gt;"
+ * "@": "&#064;"
+ */
+
+package com.github.junrar.rarfile;
+
+public enum SubBlockHeaderType
+{
+ EA_HEAD ((short)0x100),
+ UO_HEAD ((short)0x101),
+ MAC_HEAD ((short)0x102),
+ BEEA_HEAD ((short)0x103),
+ NTACL_HEAD ((short)0x104),
+ STREAM_HEAD ((short)0x105);
+
+ private short subblocktype;
+
+ private SubBlockHeaderType(short subblocktype)
+ {
+ this.subblocktype = subblocktype;
+ }
+
+ /**
+ * Return true if the given value is equal to the enum's value
+ * @param subblocktype
+ * @return true if the given value is equal to the enum's value
+ */
+ public boolean equals(short subblocktype)
+ {
+ return this.subblocktype == subblocktype;
+ }
+
+ /**
+ * find the header type for the given short value
+ * @param SubType the short value
+ * @return the correspo nding enum or null
+ */
+ public static SubBlockHeaderType findSubblockHeaderType(short subType)
+ {
+ if(EA_HEAD.equals(subType)){
+ return EA_HEAD;
+ }else if(UO_HEAD.equals(subType)){
+ return UO_HEAD;
+ }else if(MAC_HEAD.equals(subType)){
+ return MAC_HEAD;
+ }else if(BEEA_HEAD.equals(subType)){
+ return BEEA_HEAD;
+ }else if(NTACL_HEAD.equals(subType)){
+ return NTACL_HEAD;
+ }else if(STREAM_HEAD.equals(subType)){
+ return STREAM_HEAD;
+ }
+ return null;
+ }
+
+ /**
+ * @return the short representation of this enum
+ */
+ public short getSubblocktype() {
+ return subblocktype;
+ }
+}
diff --git a/src/com/github/junrar/rarfile/UnixOwnersHeader.java b/src/com/github/junrar/rarfile/UnixOwnersHeader.java
new file mode 100644
index 0000000..192ba7a
--- /dev/null
+++ b/src/com/github/junrar/rarfile/UnixOwnersHeader.java
@@ -0,0 +1,93 @@
+package com.github.junrar.rarfile;
+
+import com.github.junrar.io.Raw;
+
+
+public class UnixOwnersHeader
+extends SubBlockHeader
+{
+ //private Log //logger = LogFactory.getLog(UnixOwnersHeader.class);
+ private int ownerNameSize;
+ private int groupNameSize;
+ private String owner;
+ private String group;
+
+ public UnixOwnersHeader(SubBlockHeader sb, byte[] uoHeader) {
+ super(sb);
+ int pos = 0;
+ ownerNameSize = Raw.readShortLittleEndian(uoHeader, pos)&0xFFFF;
+ pos+=2;
+ groupNameSize = Raw.readShortLittleEndian(uoHeader, pos)&0xFFFF;
+ pos+=2;
+ if(pos+ownerNameSize<uoHeader.length){
+ byte[] ownerBuffer = new byte[ownerNameSize];
+ System.arraycopy(uoHeader, pos, ownerBuffer, 0, ownerNameSize);
+ owner = new String(ownerBuffer);
+ }
+ pos+=ownerNameSize;
+ if(pos+groupNameSize<uoHeader.length){
+ byte[] groupBuffer = new byte[groupNameSize];
+ System.arraycopy(uoHeader, pos, groupBuffer, 0, groupNameSize);
+ group = new String(groupBuffer);
+ }
+ }
+ /**
+ * @return the group
+ */
+ public String getGroup() {
+ return group;
+ }
+ /**
+ * @param group the group to set
+ */
+ public void setGroup(String group) {
+ this.group = group;
+ }
+ /**
+ * @return the groupNameSize
+ */
+ public int getGroupNameSize() {
+ return groupNameSize;
+ }
+ /**
+ * @param groupNameSize the groupNameSize to set
+ */
+ public void setGroupNameSize(int groupNameSize) {
+ this.groupNameSize = groupNameSize;
+ }
+ /**
+ * @return the owner
+ */
+ public String getOwner() {
+ return owner;
+ }
+ /**
+ * @param owner the owner to set
+ */
+ public void setOwner(String owner) {
+ this.owner = owner;
+ }
+ /**
+ * @return the ownerNameSize
+ */
+ public int getOwnerNameSize() {
+ return ownerNameSize;
+ }
+ /**
+ * @param ownerNameSize the ownerNameSize to set
+ */
+ public void setOwnerNameSize(int ownerNameSize) {
+ this.ownerNameSize = ownerNameSize;
+ }
+
+ /* (non-Javadoc)
+ * @see de.innosystec.unrar.rarfile.SubBlockHeader#print()
+ */
+ public void print(){
+ super.print();
+ //logger.info("ownerNameSize: "+ownerNameSize);
+ //logger.info("owner: "+owner);
+ //logger.info("groupNameSize: "+groupNameSize);
+ //logger.info("group: "+group);
+ }
+}
diff --git a/src/com/github/junrar/rarfile/UnrarHeadertype.java b/src/com/github/junrar/rarfile/UnrarHeadertype.java
new file mode 100644
index 0000000..9214759
--- /dev/null
+++ b/src/com/github/junrar/rarfile/UnrarHeadertype.java
@@ -0,0 +1,164 @@
+/*
+ * Copyright (c) 2007 innoSysTec (R) GmbH, Germany. All rights reserved.
+ * Original author: Edmund Wagner
+ * Creation date: 22.05.2007
+ *
+ * Source: $HeadURL$
+ * Last changed: $LastChangedDate$
+ *
+ *
+ * the unrar licence applies to all junrar source and binary distributions
+ * you are not allowed to use this source to re-create the RAR compression algorithm
+ *
+ * Here some html entities which can be used for escaping javadoc tags:
+ * "&": "&#038;" or "&amp;"
+ * "<": "&#060;" or "&lt;"
+ * ">": "&#062;" or "&gt;"
+ * "@": "&#064;"
+ */
+package com.github.junrar.rarfile;
+
+/**
+ * DOCUMENT ME
+ *
+ * @author $LastChangedBy$
+ * @version $LastChangedRevision$
+ */
+public enum UnrarHeadertype {
+
+
+ /**
+ *
+ */
+ MainHeader ((byte)0x73),
+
+ /**
+ *
+ */
+ MarkHeader ((byte)0x72),
+
+ /**
+ *
+ */
+ FileHeader ((byte) 0x74),
+
+ /**
+ *
+ */
+ CommHeader ((byte) 0x75),
+
+ /**
+ *
+ */
+ AvHeader ((byte) 0x76),
+
+ /**
+ *
+ */
+ SubHeader ((byte) 0x77),
+
+ /**
+ *
+ */
+ ProtectHeader ((byte) 0x78),
+
+ /**
+ *
+ */
+ SignHeader ((byte) 0x79),
+
+ /**
+ *
+ */
+ NewSubHeader ((byte) 0x7a),
+
+ /**
+ *
+ */
+ EndArcHeader ((byte) 0x7b);
+
+ /**
+ * Returns the enum according to the given byte or null
+ * @param headerType the headerbyte
+ * @return the enum or null
+ */
+ public static UnrarHeadertype findType(byte headerType)
+ {
+ if(UnrarHeadertype.MarkHeader.equals(headerType)){
+ return UnrarHeadertype.MarkHeader;
+ }
+ if(UnrarHeadertype.MainHeader.equals(headerType)){
+ return UnrarHeadertype.MainHeader;
+ }
+ if(UnrarHeadertype.FileHeader.equals(headerType)){
+ return UnrarHeadertype.FileHeader;
+ }
+ if(UnrarHeadertype.EndArcHeader.equals(headerType)){
+ return UnrarHeadertype.EndArcHeader;
+ }
+ if(UnrarHeadertype.NewSubHeader.equals(headerType)){
+ return UnrarHeadertype.NewSubHeader;
+ }
+ if(UnrarHeadertype.SubHeader.equals(headerType)){
+ return UnrarHeadertype.SubHeader;
+ }
+ if(UnrarHeadertype.SignHeader.equals(headerType)){
+ return UnrarHeadertype.SignHeader;
+ }
+ if(UnrarHeadertype.ProtectHeader.equals(headerType)){
+ return UnrarHeadertype.ProtectHeader;
+ }
+ if(UnrarHeadertype.MarkHeader.equals(headerType)){
+ return UnrarHeadertype.MarkHeader;
+ }
+ if(UnrarHeadertype.MainHeader.equals(headerType)){
+ return UnrarHeadertype.MainHeader;
+ }
+ if(UnrarHeadertype.FileHeader.equals(headerType)){
+ return UnrarHeadertype.FileHeader;
+ }
+ if(UnrarHeadertype.EndArcHeader.equals(headerType)){
+ return UnrarHeadertype.EndArcHeader;
+ }
+ if(UnrarHeadertype.CommHeader.equals(headerType)){
+ return UnrarHeadertype.CommHeader;
+ }
+ if(UnrarHeadertype.AvHeader.equals(headerType)){
+ return UnrarHeadertype.AvHeader;
+ }
+ return null;
+ }
+
+
+
+ private byte headerByte;
+
+ private UnrarHeadertype(byte headerByte)
+ {
+ this.headerByte = headerByte;
+ }
+
+
+ /**
+ * Return true if the given byte is equal to the enum's byte
+ * @param header
+ * @return true if the given byte is equal to the enum's byte
+ */
+ public boolean equals(byte header)
+ {
+ return headerByte == header;
+ }
+
+
+ /**
+ * the header byte of this enum
+ * @return the header byte of this enum
+ */
+ public byte getHeaderByte() {
+ return headerByte;
+ }
+
+
+
+
+}
diff --git a/src/com/github/junrar/unpack/ComprDataIO.java b/src/com/github/junrar/unpack/ComprDataIO.java
new file mode 100644
index 0000000..8791b09
--- /dev/null
+++ b/src/com/github/junrar/unpack/ComprDataIO.java
@@ -0,0 +1,362 @@
+/*
+ * Copyright (c) 2007 innoSysTec (R) GmbH, Germany. All rights reserved.
+ * Original author: Edmund Wagner
+ * Creation date: 31.05.2007
+ *
+ * Source: $HeadURL$
+ * Last changed: $LastChangedDate$
+ *
+ * the unrar licence applies to all junrar source and binary distributions
+ * you are not allowed to use this source to re-create the RAR compression algorithm
+ *
+ * Here some html entities which can be used for escaping javadoc tags:
+ * "&": "&#038;" or "&amp;"
+ * "<": "&#060;" or "&lt;"
+ * ">": "&#062;" or "&gt;"
+ * "@": "&#064;"
+ */
+package com.github.junrar.unpack;
+
+import java.io.EOFException;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.OutputStream;
+
+import com.github.junrar.Archive;
+import com.github.junrar.UnrarCallback;
+import com.github.junrar.Volume;
+import com.github.junrar.crc.RarCRC;
+import com.github.junrar.exception.RarException;
+import com.github.junrar.exception.RarException.RarExceptionType;
+import com.github.junrar.io.ReadOnlyAccessInputStream;
+import com.github.junrar.rarfile.FileHeader;
+
+
+/**
+ * DOCUMENT ME
+ *
+ * @author $LastChangedBy$
+ * @version $LastChangedRevision$
+ */
+public class ComprDataIO {
+
+ private final Archive archive;
+
+ private long unpPackedSize;
+
+ private boolean testMode;
+
+ private boolean skipUnpCRC;
+
+ private InputStream inputStream;
+
+ private OutputStream outputStream;
+
+ private FileHeader subHead;
+
+ // cryptData Crypt;
+ // cryptData Decrypt;
+ private boolean packVolume;
+
+ private boolean unpVolume;
+
+ private boolean nextVolumeMissing;
+
+ private long totalPackRead;
+
+ private long unpArcSize;
+
+ private long curPackRead, curPackWrite, curUnpRead, curUnpWrite;
+
+ private long processedArcSize, totalArcSize;
+
+ private long packFileCRC, unpFileCRC, packedCRC;
+
+ private int encryption;
+
+ private int decryption;
+
+ private int lastPercent;
+
+ private char currentCommand;
+
+ public ComprDataIO(Archive arc) {
+ this.archive = arc;
+ }
+
+ public void init(OutputStream outputStream) {
+ this.outputStream = outputStream;
+ unpPackedSize = 0;
+ testMode = false;
+ skipUnpCRC = false;
+ packVolume = false;
+ unpVolume = false;
+ nextVolumeMissing = false;
+ // command = null;
+ encryption = 0;
+ decryption = 0;
+ totalPackRead = 0;
+ curPackRead = curPackWrite = curUnpRead = curUnpWrite = 0;
+ packFileCRC = unpFileCRC = packedCRC = 0xffffffff;
+ lastPercent = -1;
+ subHead = null;
+
+ currentCommand = 0;
+ processedArcSize = totalArcSize = 0;
+ }
+
+ public void init(FileHeader hd) throws IOException {
+ long startPos = hd.getPositionInFile() + hd.getHeaderSize();
+ unpPackedSize = hd.getFullPackSize();
+ inputStream = new ReadOnlyAccessInputStream(archive.getRof(), startPos,
+ startPos + unpPackedSize);
+ subHead = hd;
+ curUnpRead = 0;
+ curPackWrite = 0;
+ packedCRC = 0xFFffFFff;
+ }
+
+ public int unpRead(byte[] addr, int offset, int count) throws IOException,
+ RarException {
+ int retCode = 0, totalRead = 0;
+ while (count > 0) {
+ int readSize = (count > unpPackedSize) ? (int) unpPackedSize
+ : count;
+ retCode = inputStream.read(addr, offset, readSize);
+ if (retCode < 0) {
+ throw new EOFException();
+ }
+ if (subHead.isSplitAfter()) {
+ packedCRC = RarCRC.checkCrc((int) packedCRC, addr, offset,
+ retCode);
+ }
+
+ curUnpRead += retCode;
+ totalRead += retCode;
+ offset += retCode;
+ count -= retCode;
+ unpPackedSize -= retCode;
+ archive.bytesReadRead(retCode);
+ if (unpPackedSize == 0 && subHead.isSplitAfter()) {
+ Volume nextVolume = archive.getVolumeManager().nextArchive(
+ archive, archive.getVolume());
+ if (nextVolume == null) {
+ nextVolumeMissing = true;
+ return -1;
+ }
+
+ FileHeader hd = this.getSubHeader();
+ if (hd.getUnpVersion() >= 20 && hd.getFileCRC() != 0xffffffff
+ && this.getPackedCRC() != ~hd.getFileCRC()) {
+ throw new RarException(RarExceptionType.crcError);
+ }
+ UnrarCallback callback = archive.getUnrarCallback();
+ if ((callback != null)
+ && !callback.isNextVolumeReady(nextVolume)) {
+ return -1;
+ }
+ archive.setVolume(nextVolume);
+ hd = archive.nextFileHeader();
+ if (hd == null) {
+ return -1;
+ }
+ this.init(hd);
+ } else {
+ break;
+ }
+ }
+
+ if (retCode != -1) {
+ retCode = totalRead;
+ }
+ return retCode;
+
+ }
+
+ public void unpWrite(byte[] addr, int offset, int count) throws IOException {
+ if (!testMode) {
+ // DestFile->Write(Addr,Count);
+ outputStream.write(addr, offset, count);
+ }
+
+ curUnpWrite += count;
+
+ if (!skipUnpCRC) {
+ if (archive.isOldFormat()) {
+ unpFileCRC = RarCRC
+ .checkOldCrc((short) unpFileCRC, addr, count);
+ } else {
+ unpFileCRC = RarCRC.checkCrc((int) unpFileCRC, addr, offset,
+ count);
+ }
+ }
+ // if (!skipArcCRC) {
+ // archive.updateDataCRC(Addr, offset, ReadSize);
+ // }
+ }
+
+ public void setPackedSizeToRead(long size) {
+ unpPackedSize = size;
+ }
+
+ public void setTestMode(boolean mode) {
+ testMode = mode;
+ }
+
+ public void setSkipUnpCRC(boolean skip) {
+ skipUnpCRC = skip;
+ }
+
+ public void setSubHeader(FileHeader hd) {
+ subHead = hd;
+
+ }
+
+ public long getCurPackRead() {
+ return curPackRead;
+ }
+
+ public void setCurPackRead(long curPackRead) {
+ this.curPackRead = curPackRead;
+ }
+
+ public long getCurPackWrite() {
+ return curPackWrite;
+ }
+
+ public void setCurPackWrite(long curPackWrite) {
+ this.curPackWrite = curPackWrite;
+ }
+
+ public long getCurUnpRead() {
+ return curUnpRead;
+ }
+
+ public void setCurUnpRead(long curUnpRead) {
+ this.curUnpRead = curUnpRead;
+ }
+
+ public long getCurUnpWrite() {
+ return curUnpWrite;
+ }
+
+ public void setCurUnpWrite(long curUnpWrite) {
+ this.curUnpWrite = curUnpWrite;
+ }
+
+ public int getDecryption() {
+ return decryption;
+ }
+
+ public void setDecryption(int decryption) {
+ this.decryption = decryption;
+ }
+
+ public int getEncryption() {
+ return encryption;
+ }
+
+ public void setEncryption(int encryption) {
+ this.encryption = encryption;
+ }
+
+ public boolean isNextVolumeMissing() {
+ return nextVolumeMissing;
+ }
+
+ public void setNextVolumeMissing(boolean nextVolumeMissing) {
+ this.nextVolumeMissing = nextVolumeMissing;
+ }
+
+ public long getPackedCRC() {
+ return packedCRC;
+ }
+
+ public void setPackedCRC(long packedCRC) {
+ this.packedCRC = packedCRC;
+ }
+
+ public long getPackFileCRC() {
+ return packFileCRC;
+ }
+
+ public void setPackFileCRC(long packFileCRC) {
+ this.packFileCRC = packFileCRC;
+ }
+
+ public boolean isPackVolume() {
+ return packVolume;
+ }
+
+ public void setPackVolume(boolean packVolume) {
+ this.packVolume = packVolume;
+ }
+
+ public long getProcessedArcSize() {
+ return processedArcSize;
+ }
+
+ public void setProcessedArcSize(long processedArcSize) {
+ this.processedArcSize = processedArcSize;
+ }
+
+ public long getTotalArcSize() {
+ return totalArcSize;
+ }
+
+ public void setTotalArcSize(long totalArcSize) {
+ this.totalArcSize = totalArcSize;
+ }
+
+ public long getTotalPackRead() {
+ return totalPackRead;
+ }
+
+ public void setTotalPackRead(long totalPackRead) {
+ this.totalPackRead = totalPackRead;
+ }
+
+ public long getUnpArcSize() {
+ return unpArcSize;
+ }
+
+ public void setUnpArcSize(long unpArcSize) {
+ this.unpArcSize = unpArcSize;
+ }
+
+ public long getUnpFileCRC() {
+ return unpFileCRC;
+ }
+
+ public void setUnpFileCRC(long unpFileCRC) {
+ this.unpFileCRC = unpFileCRC;
+ }
+
+ public boolean isUnpVolume() {
+ return unpVolume;
+ }
+
+ public void setUnpVolume(boolean unpVolume) {
+ this.unpVolume = unpVolume;
+ }
+
+ public FileHeader getSubHeader() {
+ return subHead;
+ }
+
+ // public void setEncryption(int method, char[] Password, byte[] Salt,
+ // boolean encrypt, boolean handsOffHash)
+ // {
+ //
+ // }
+ //
+ // public void setAV15Encryption()
+ // {
+ //
+ // }
+ //
+ // public void setCmt13Encryption()
+ // {
+ //
+ // }
+}
diff --git a/src/com/github/junrar/unpack/Unpack.java b/src/com/github/junrar/unpack/Unpack.java
new file mode 100644
index 0000000..fdf5eb4
--- /dev/null
+++ b/src/com/github/junrar/unpack/Unpack.java
@@ -0,0 +1,1051 @@
+/*
+ * Copyright (c) 2007 innoSysTec (R) GmbH, Germany. All rights reserved.
+ * Original author: Edmund Wagner
+ * Creation date: 31.05.2007
+ *
+ * Source: $HeadURL$
+ * Last changed: $LastChangedDate$
+ *
+ * the unrar licence applies to all junrar source and binary distributions
+ * you are not allowed to use this source to re-create the RAR compression algorithm
+ *
+ * Here some html entities which can be used for escaping javadoc tags:
+ * "&": "&#038;" or "&amp;"
+ * "<": "&#060;" or "&lt;"
+ * ">": "&#062;" or "&gt;"
+ * "@": "&#064;"
+ */
+package com.github.junrar.unpack;
+
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.List;
+import java.util.Vector;
+
+import com.github.junrar.exception.RarException;
+import com.github.junrar.unpack.decode.Compress;
+import com.github.junrar.unpack.ppm.BlockTypes;
+import com.github.junrar.unpack.ppm.ModelPPM;
+import com.github.junrar.unpack.ppm.SubAllocator;
+import com.github.junrar.unpack.vm.BitInput;
+import com.github.junrar.unpack.vm.RarVM;
+import com.github.junrar.unpack.vm.VMPreparedProgram;
+
+
+/**
+ * DOCUMENT ME
+ *
+ * @author $LastChangedBy$
+ * @version $LastChangedRevision$
+ */
+public final class Unpack extends Unpack20 {
+
+ private final ModelPPM ppm = new ModelPPM();
+
+ private int ppmEscChar;
+
+ private RarVM rarVM = new RarVM();
+
+ /* Filters code, one entry per filter */
+ private List<UnpackFilter> filters = new ArrayList<UnpackFilter>();
+
+ /* Filters stack, several entrances of same filter are possible */
+ private List<UnpackFilter> prgStack = new ArrayList<UnpackFilter>();
+
+ /*
+ * lengths of preceding blocks, one length per filter. Used to reduce size
+ * required to write block length if lengths are repeating
+ */
+ private List<Integer> oldFilterLengths = new ArrayList<Integer>();
+
+ private int lastFilter;
+
+ private boolean tablesRead;
+
+ private byte[] unpOldTable = new byte[Compress.HUFF_TABLE_SIZE];
+
+ private BlockTypes unpBlockType;
+
+ private boolean externalWindow;
+
+ private long writtenFileSize;
+
+ private boolean fileExtracted;
+
+ private boolean ppmError;
+
+ private int prevLowDist;
+
+ private int lowDistRepCount;
+
+ public static int[] DBitLengthCounts = { 4, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
+ 2, 2, 2, 2, 2, 14, 0, 12 };
+
+ public Unpack(ComprDataIO DataIO) {
+ unpIO = DataIO;
+ window = null;
+ externalWindow = false;
+ suspended = false;
+ unpAllBuf = false;
+ unpSomeRead = false;
+ }
+
+ public void init(byte[] window) {
+ if (window == null) {
+ this.window = new byte[Compress.MAXWINSIZE];
+ } else {
+ this.window = window;
+ externalWindow = true;
+ }
+ inAddr = 0;
+ unpInitData(false);
+ }
+
+ public void doUnpack(int method, boolean solid) throws IOException,
+ RarException {
+ if (unpIO.getSubHeader().getUnpMethod() == 0x30) {
+ unstoreFile();
+ }
+ switch (method) {
+ case 15: // rar 1.5 compression
+ unpack15(solid);
+ break;
+ case 20: // rar 2.x compression
+ case 26: // files larger than 2GB
+ unpack20(solid);
+ break;
+ case 29: // rar 3.x compression
+ case 36: // alternative hash
+ unpack29(solid);
+ break;
+ }
+ }
+
+ private void unstoreFile() throws IOException, RarException {
+ byte[] buffer = new byte[0x10000];
+ while (true) {
+ int code = unpIO.unpRead(buffer, 0, (int) Math.min(buffer.length,
+ destUnpSize));
+ if (code == 0 || code == -1)
+ break;
+ code = code < destUnpSize ? code : (int) destUnpSize;
+ unpIO.unpWrite(buffer, 0, code);
+ if (destUnpSize >= 0)
+ destUnpSize -= code;
+ }
+
+ }
+
+ private void unpack29(boolean solid) throws IOException, RarException {
+
+ int[] DDecode = new int[Compress.DC];
+ byte[] DBits = new byte[Compress.DC];
+
+ int Bits;
+
+ if (DDecode[1] == 0) {
+ int Dist = 0, BitLength = 0, Slot = 0;
+ for (int I = 0; I < DBitLengthCounts.length; I++, BitLength++) {
+ int count = DBitLengthCounts[I];
+ for (int J = 0; J < count; J++, Slot++, Dist += (1 << BitLength)) {
+ DDecode[Slot] = Dist;
+ DBits[Slot] = (byte) BitLength;
+ }
+ }
+ }
+
+ fileExtracted = true;
+
+ if (!suspended) {
+ unpInitData(solid);
+ if (!unpReadBuf()) {
+ return;
+ }
+ if ((!solid || !tablesRead) && !readTables()) {
+ return;
+ }
+ }
+
+ if (ppmError) {
+ return;
+ }
+
+ while (true) {
+ unpPtr &= Compress.MAXWINMASK;
+
+ if (inAddr > readBorder) {
+ if (!unpReadBuf()) {
+ break;
+ }
+ }
+ // System.out.println(((wrPtr - unpPtr) &
+ // Compress.MAXWINMASK)+":"+wrPtr+":"+unpPtr);
+ if (((wrPtr - unpPtr) & Compress.MAXWINMASK) < 260
+ && wrPtr != unpPtr) {
+
+ UnpWriteBuf();
+ if (writtenFileSize > destUnpSize) {
+ return;
+ }
+ if (suspended) {
+ fileExtracted = false;
+ return;
+ }
+ }
+ if (unpBlockType == BlockTypes.BLOCK_PPM) {
+ int Ch = ppm.decodeChar();
+ if (Ch == -1) {
+ ppmError = true;
+ break;
+ }
+ if (Ch == ppmEscChar) {
+ int NextCh = ppm.decodeChar();
+ if (NextCh == 0) {
+ if (!readTables()) {
+ break;
+ }
+ continue;
+ }
+ if (NextCh == 2 || NextCh == -1) {
+ break;
+ }
+ if (NextCh == 3) {
+ if (!readVMCodePPM()) {
+ break;
+ }
+ continue;
+ }
+ if (NextCh == 4) {
+ int Distance = 0, Length = 0;
+ boolean failed = false;
+ for (int I = 0; I < 4 && !failed; I++) {
+ int ch = ppm.decodeChar();
+ if (ch == -1) {
+ failed = true;
+ } else {
+ if (I == 3) {
+ // Bug fixed
+ Length = ch & 0xff;
+ } else {
+ // Bug fixed
+ Distance = (Distance << 8) + (ch & 0xff);
+ }
+ }
+ }
+ if (failed) {
+ break;
+ }
+ copyString(Length + 32, Distance + 2);
+ continue;
+ }
+ if (NextCh == 5) {
+ int Length = ppm.decodeChar();
+ if (Length == -1) {
+ break;
+ }
+ copyString(Length + 4, 1);
+ continue;
+ }
+ }
+ window[unpPtr++] = (byte) Ch;
+ continue;
+ }
+
+ int Number = decodeNumber(LD);
+ if (Number < 256) {
+ window[unpPtr++] = (byte) Number;
+ continue;
+ }
+ if (Number >= 271) {
+ int Length = LDecode[Number -= 271] + 3;
+ if ((Bits = LBits[Number]) > 0) {
+ Length += getbits() >>> (16 - Bits);
+ addbits(Bits);
+ }
+
+ int DistNumber = decodeNumber(DD);
+ int Distance = DDecode[DistNumber] + 1;
+ if ((Bits = DBits[DistNumber]) > 0) {
+ if (DistNumber > 9) {
+ if (Bits > 4) {
+ Distance += ((getbits() >>> (20 - Bits)) << 4);
+ addbits(Bits - 4);
+ }
+ if (lowDistRepCount > 0) {
+ lowDistRepCount--;
+ Distance += prevLowDist;
+ } else {
+ int LowDist = decodeNumber(LDD);
+ if (LowDist == 16) {
+ lowDistRepCount = Compress.LOW_DIST_REP_COUNT - 1;
+ Distance += prevLowDist;
+ } else {
+ Distance += LowDist;
+ prevLowDist = LowDist;
+ }
+ }
+ } else {
+ Distance += getbits() >>> (16 - Bits);
+ addbits(Bits);
+ }
+ }
+
+ if (Distance >= 0x2000) {
+ Length++;
+ if (Distance >= 0x40000L) {
+ Length++;
+ }
+ }
+
+ insertOldDist(Distance);
+ insertLastMatch(Length, Distance);
+
+ copyString(Length, Distance);
+ continue;
+ }
+ if (Number == 256) {
+ if (!readEndOfBlock()) {
+ break;
+ }
+ continue;
+ }
+ if (Number == 257) {
+ if (!readVMCode()) {
+ break;
+ }
+ continue;
+ }
+ if (Number == 258) {
+ if (lastLength != 0) {
+ copyString(lastLength, lastDist);
+ }
+ continue;
+ }
+ if (Number < 263) {
+ int DistNum = Number - 259;
+ int Distance = oldDist[DistNum];
+ for (int I = DistNum; I > 0; I--) {
+ oldDist[I] = oldDist[I - 1];
+ }
+ oldDist[0] = Distance;
+
+ int LengthNumber = decodeNumber(RD);
+ int Length = LDecode[LengthNumber] + 2;
+ if ((Bits = LBits[LengthNumber]) > 0) {
+ Length += getbits() >>> (16 - Bits);
+ addbits(Bits);
+ }
+ insertLastMatch(Length, Distance);
+ copyString(Length, Distance);
+ continue;
+ }
+ if (Number < 272) {
+ int Distance = SDDecode[Number -= 263] + 1;
+ if ((Bits = SDBits[Number]) > 0) {
+ Distance += getbits() >>> (16 - Bits);
+ addbits(Bits);
+ }
+ insertOldDist(Distance);
+ insertLastMatch(2, Distance);
+ copyString(2, Distance);
+ continue;
+ }
+ }
+ UnpWriteBuf();
+
+ }
+
+ private void UnpWriteBuf() throws IOException {
+ int WrittenBorder = wrPtr;
+ int WriteSize = (unpPtr - WrittenBorder) & Compress.MAXWINMASK;
+ for (int I = 0; I < prgStack.size(); I++) {
+ UnpackFilter flt = prgStack.get(I);
+ if (flt == null) {
+ continue;
+ }
+ if (flt.isNextWindow()) {
+ flt.setNextWindow(false);// ->NextWindow=false;
+ continue;
+ }
+ int BlockStart = flt.getBlockStart();// ->BlockStart;
+ int BlockLength = flt.getBlockLength();// ->BlockLength;
+ if (((BlockStart - WrittenBorder) & Compress.MAXWINMASK) < WriteSize) {
+ if (WrittenBorder != BlockStart) {
+ UnpWriteArea(WrittenBorder, BlockStart);
+ WrittenBorder = BlockStart;
+ WriteSize = (unpPtr - WrittenBorder) & Compress.MAXWINMASK;
+ }
+ if (BlockLength <= WriteSize) {
+ int BlockEnd = (BlockStart + BlockLength)
+ & Compress.MAXWINMASK;
+ if (BlockStart < BlockEnd || BlockEnd == 0) {
+ // VM.SetMemory(0,Window+BlockStart,BlockLength);
+ rarVM.setMemory(0, window, BlockStart, BlockLength);
+ } else {
+ int FirstPartLength = Compress.MAXWINSIZE - BlockStart;
+ // VM.SetMemory(0,Window+BlockStart,FirstPartLength);
+ rarVM.setMemory(0, window, BlockStart, FirstPartLength);
+ // VM.SetMemory(FirstPartLength,Window,BlockEnd);
+ rarVM.setMemory(FirstPartLength, window, 0, BlockEnd);
+
+ }
+
+ VMPreparedProgram ParentPrg = filters.get(
+ flt.getParentFilter()).getPrg();
+ VMPreparedProgram Prg = flt.getPrg();
+
+ if (ParentPrg.getGlobalData().size() > RarVM.VM_FIXEDGLOBALSIZE) {
+ // copy global data from previous script execution if
+ // any
+ // Prg->GlobalData.Alloc(ParentPrg->GlobalData.Size());
+ // memcpy(&Prg->GlobalData[VM_FIXEDGLOBALSIZE],&ParentPrg->GlobalData[VM_FIXEDGLOBALSIZE],ParentPrg->GlobalData.Size()-VM_FIXEDGLOBALSIZE);
+ Prg.getGlobalData().setSize(
+ ParentPrg.getGlobalData().size());
+ for (int i = 0; i < ParentPrg.getGlobalData().size()
+ - RarVM.VM_FIXEDGLOBALSIZE; i++) {
+ Prg.getGlobalData().set(
+ RarVM.VM_FIXEDGLOBALSIZE + i,
+ ParentPrg.getGlobalData().get(
+ RarVM.VM_FIXEDGLOBALSIZE + i));
+ }
+ }
+
+ ExecuteCode(Prg);
+
+ if (Prg.getGlobalData().size() > RarVM.VM_FIXEDGLOBALSIZE) {
+ // save global data for next script execution
+ if (ParentPrg.getGlobalData().size() < Prg
+ .getGlobalData().size()) {
+ ParentPrg.getGlobalData().setSize(
+ Prg.getGlobalData().size());// ->GlobalData.Alloc(Prg->GlobalData.Size());
+ }
+ // memcpy(&ParentPrg->GlobalData[VM_FIXEDGLOBALSIZE],&Prg->GlobalData[VM_FIXEDGLOBALSIZE],Prg->GlobalData.Size()-VM_FIXEDGLOBALSIZE);
+ for (int i = 0; i < Prg.getGlobalData().size()
+ - RarVM.VM_FIXEDGLOBALSIZE; i++) {
+ ParentPrg.getGlobalData().set(
+ RarVM.VM_FIXEDGLOBALSIZE + i,
+ Prg.getGlobalData().get(
+ RarVM.VM_FIXEDGLOBALSIZE + i));
+ }
+ } else {
+ ParentPrg.getGlobalData().clear();
+ }
+
+ int FilteredDataOffset = Prg.getFilteredDataOffset();
+ int FilteredDataSize = Prg.getFilteredDataSize();
+ byte[] FilteredData = new byte[FilteredDataSize];
+
+ for (int i = 0; i < FilteredDataSize; i++) {
+ FilteredData[i] = rarVM.getMem()[FilteredDataOffset + i];// Prg.getGlobalData().get(FilteredDataOffset
+ // +
+ // i);
+ }
+
+ prgStack.set(I, null);
+ while (I + 1 < prgStack.size()) {
+ UnpackFilter NextFilter = prgStack.get(I + 1);
+ if (NextFilter == null
+ || NextFilter.getBlockStart() != BlockStart
+ || NextFilter.getBlockLength() != FilteredDataSize
+ || NextFilter.isNextWindow()) {
+ break;
+ }
+ // apply several filters to same data block
+
+ rarVM.setMemory(0, FilteredData, 0, FilteredDataSize);// .SetMemory(0,FilteredData,FilteredDataSize);
+
+ VMPreparedProgram pPrg = filters.get(
+ NextFilter.getParentFilter()).getPrg();
+ VMPreparedProgram NextPrg = NextFilter.getPrg();
+
+ if (pPrg.getGlobalData().size() > RarVM.VM_FIXEDGLOBALSIZE) {
+ // copy global data from previous script execution
+ // if any
+ // NextPrg->GlobalData.Alloc(ParentPrg->GlobalData.Size());
+ NextPrg.getGlobalData().setSize(
+ pPrg.getGlobalData().size());
+ // memcpy(&NextPrg->GlobalData[VM_FIXEDGLOBALSIZE],&ParentPrg->GlobalData[VM_FIXEDGLOBALSIZE],ParentPrg->GlobalData.Size()-VM_FIXEDGLOBALSIZE);
+ for (int i = 0; i < pPrg.getGlobalData().size()
+ - RarVM.VM_FIXEDGLOBALSIZE; i++) {
+ NextPrg.getGlobalData().set(
+ RarVM.VM_FIXEDGLOBALSIZE + i,
+ pPrg.getGlobalData().get(
+ RarVM.VM_FIXEDGLOBALSIZE + i));
+ }
+ }
+
+ ExecuteCode(NextPrg);
+
+ if (NextPrg.getGlobalData().size() > RarVM.VM_FIXEDGLOBALSIZE) {
+ // save global data for next script execution
+ if (pPrg.getGlobalData().size() < NextPrg
+ .getGlobalData().size()) {
+ pPrg.getGlobalData().setSize(
+ NextPrg.getGlobalData().size());
+ }
+ // memcpy(&ParentPrg->GlobalData[VM_FIXEDGLOBALSIZE],&NextPrg->GlobalData[VM_FIXEDGLOBALSIZE],NextPrg->GlobalData.Size()-VM_FIXEDGLOBALSIZE);
+ for (int i = 0; i < NextPrg.getGlobalData().size()
+ - RarVM.VM_FIXEDGLOBALSIZE; i++) {
+ pPrg.getGlobalData().set(
+ RarVM.VM_FIXEDGLOBALSIZE + i,
+ NextPrg.getGlobalData().get(
+ RarVM.VM_FIXEDGLOBALSIZE + i));
+ }
+ } else {
+ pPrg.getGlobalData().clear();
+ }
+ FilteredDataOffset = NextPrg.getFilteredDataOffset();
+ FilteredDataSize = NextPrg.getFilteredDataSize();
+
+ FilteredData = new byte[FilteredDataSize];
+ for (int i = 0; i < FilteredDataSize; i++) {
+ FilteredData[i] = NextPrg.getGlobalData().get(
+ FilteredDataOffset + i);
+ }
+
+ I++;
+ prgStack.set(I, null);
+ }
+ unpIO.unpWrite(FilteredData, 0, FilteredDataSize);
+ unpSomeRead = true;
+ writtenFileSize += FilteredDataSize;
+ WrittenBorder = BlockEnd;
+ WriteSize = (unpPtr - WrittenBorder) & Compress.MAXWINMASK;
+ } else {
+ for (int J = I; J < prgStack.size(); J++) {
+ UnpackFilter filt = prgStack.get(J);
+ if (filt != null && filt.isNextWindow()) {
+ filt.setNextWindow(false);
+ }
+ }
+ wrPtr = WrittenBorder;
+ return;
+ }
+ }
+ }
+
+ UnpWriteArea(WrittenBorder, unpPtr);
+ wrPtr = unpPtr;
+
+ }
+
+ private void UnpWriteArea(int startPtr, int endPtr) throws IOException {
+ if (endPtr != startPtr) {
+ unpSomeRead = true;
+ }
+ if (endPtr < startPtr) {
+ UnpWriteData(window, startPtr, -startPtr & Compress.MAXWINMASK);
+ UnpWriteData(window, 0, endPtr);
+ unpAllBuf = true;
+ } else {
+ UnpWriteData(window, startPtr, endPtr - startPtr);
+ }
+ }
+
+ private void UnpWriteData(byte[] data, int offset, int size)
+ throws IOException {
+ if (writtenFileSize >= destUnpSize) {
+ return;
+ }
+ int writeSize = size;
+ long leftToWrite = destUnpSize - writtenFileSize;
+ if (writeSize > leftToWrite) {
+ writeSize = (int) leftToWrite;
+ }
+ unpIO.unpWrite(data, offset, writeSize);
+
+ writtenFileSize += size;
+
+ }
+
+ private void insertOldDist(int distance) {
+ oldDist[3] = oldDist[2];
+ oldDist[2] = oldDist[1];
+ oldDist[1] = oldDist[0];
+ oldDist[0] = distance;
+ }
+
+ private void insertLastMatch(int length, int distance) {
+ lastDist = distance;
+ lastLength = length;
+ }
+
+ private void copyString(int length, int distance) {
+ // System.out.println("copyString(" + length + ", " + distance + ")");
+
+ int destPtr = unpPtr - distance;
+ // System.out.println(unpPtr+":"+distance);
+ if (destPtr >= 0 && destPtr < Compress.MAXWINSIZE - 260
+ && unpPtr < Compress.MAXWINSIZE - 260) {
+
+ window[unpPtr++] = window[destPtr++];
+
+ while (--length > 0)
+
+ window[unpPtr++] = window[destPtr++];
+ } else
+ while (length-- != 0) {
+ window[unpPtr] = window[destPtr++ & Compress.MAXWINMASK];
+ unpPtr = (unpPtr + 1) & Compress.MAXWINMASK;
+ }
+ }
+
+ protected void unpInitData(boolean solid) {
+ if (!solid) {
+ tablesRead = false;
+ Arrays.fill(oldDist, 0); // memset(oldDist,0,sizeof(OldDist));
+
+ oldDistPtr = 0;
+ lastDist = 0;
+ lastLength = 0;
+
+ Arrays.fill(unpOldTable, (byte) 0);// memset(UnpOldTable,0,sizeof(UnpOldTable));
+
+ unpPtr = 0;
+ wrPtr = 0;
+ ppmEscChar = 2;
+
+ initFilters();
+ }
+ InitBitInput();
+ ppmError = false;
+ writtenFileSize = 0;
+ readTop = 0;
+ readBorder = 0;
+ unpInitData20(solid);
+ }
+
+ private void initFilters() {
+ oldFilterLengths.clear();
+ lastFilter = 0;
+
+ filters.clear();
+
+ prgStack.clear();
+ }
+
+ private boolean readEndOfBlock() throws IOException, RarException {
+ int BitField = getbits();
+ boolean NewTable, NewFile = false;
+ if ((BitField & 0x8000) != 0) {
+ NewTable = true;
+ addbits(1);
+ } else {
+ NewFile = true;
+ NewTable = (BitField & 0x4000) != 0 ? true : false;
+ addbits(2);
+ }
+ tablesRead = !NewTable;
+ return !(NewFile || NewTable && !readTables());
+ }
+
+ private boolean readTables() throws IOException, RarException {
+ byte[] bitLength = new byte[Compress.BC];
+
+ byte[] table = new byte[Compress.HUFF_TABLE_SIZE];
+ if (inAddr > readTop - 25) {
+ if (!unpReadBuf()) {
+ return (false);
+ }
+ }
+ faddbits((8 - inBit) & 7);
+ long bitField = fgetbits() & 0xffFFffFF;
+ if ((bitField & 0x8000) != 0) {
+ unpBlockType = BlockTypes.BLOCK_PPM;
+ return (ppm.decodeInit(this, ppmEscChar));
+ }
+ unpBlockType = BlockTypes.BLOCK_LZ;
+
+ prevLowDist = 0;
+ lowDistRepCount = 0;
+
+ if ((bitField & 0x4000) == 0) {
+ Arrays.fill(unpOldTable, (byte) 0);// memset(UnpOldTable,0,sizeof(UnpOldTable));
+ }
+ faddbits(2);
+
+ for (int i = 0; i < Compress.BC; i++) {
+ int length = (fgetbits() >>> 12) & 0xFF;
+ faddbits(4);
+ if (length == 15) {
+ int zeroCount = (fgetbits() >>> 12) & 0xFF;
+ faddbits(4);
+ if (zeroCount == 0) {
+ bitLength[i] = 15;
+ } else {
+ zeroCount += 2;
+ while (zeroCount-- > 0 && i < bitLength.length) {
+ bitLength[i++] = 0;
+ }
+ i--;
+ }
+ } else {
+ bitLength[i] = (byte) length;
+ }
+ }
+
+ makeDecodeTables(bitLength, 0, BD, Compress.BC);
+
+ int TableSize = Compress.HUFF_TABLE_SIZE;
+
+ for (int i = 0; i < TableSize;) {
+ if (inAddr > readTop - 5) {
+ if (!unpReadBuf()) {
+ return (false);
+ }
+ }
+ int Number = decodeNumber(BD);
+ if (Number < 16) {
+ table[i] = (byte) ((Number + unpOldTable[i]) & 0xf);
+ i++;
+ } else if (Number < 18) {
+ int N;
+ if (Number == 16) {
+ N = (fgetbits() >>> 13) + 3;
+ faddbits(3);
+ } else {
+ N = (fgetbits() >>> 9) + 11;
+ faddbits(7);
+ }
+ while (N-- > 0 && i < TableSize) {
+ table[i] = table[i - 1];
+ i++;
+ }
+ } else {
+ int N;
+ if (Number == 18) {
+ N = (fgetbits() >>> 13) + 3;
+ faddbits(3);
+ } else {
+ N = (fgetbits() >>> 9) + 11;
+ faddbits(7);
+ }
+ while (N-- > 0 && i < TableSize) {
+ table[i++] = 0;
+ }
+ }
+ }
+ tablesRead = true;
+ if (inAddr > readTop) {
+ return (false);
+ }
+ makeDecodeTables(table, 0, LD, Compress.NC);
+ makeDecodeTables(table, Compress.NC, DD, Compress.DC);
+ makeDecodeTables(table, Compress.NC + Compress.DC, LDD, Compress.LDC);
+ makeDecodeTables(table, Compress.NC + Compress.DC + Compress.LDC, RD,
+ Compress.RC);
+
+ // memcpy(unpOldTable,table,sizeof(unpOldTable));
+ for (int i = 0; i < unpOldTable.length; i++) {
+ unpOldTable[i] = table[i];
+ }
+ return (true);
+
+ }
+
+ private boolean readVMCode() throws IOException, RarException {
+ int FirstByte = getbits() >> 8;
+ addbits(8);
+ int Length = (FirstByte & 7) + 1;
+ if (Length == 7) {
+ Length = (getbits() >> 8) + 7;
+ addbits(8);
+ } else if (Length == 8) {
+ Length = getbits();
+ addbits(16);
+ }
+ List<Byte> vmCode = new ArrayList<Byte>();
+ for (int I = 0; I < Length; I++) {
+ if (inAddr >= readTop - 1 && !unpReadBuf() && I < Length - 1) {
+ return (false);
+ }
+ vmCode.add(Byte.valueOf((byte) (getbits() >> 8)));
+ addbits(8);
+ }
+ return (addVMCode(FirstByte, vmCode, Length));
+ }
+
+ private boolean readVMCodePPM() throws IOException, RarException {
+ int FirstByte = ppm.decodeChar();
+ if ((int) FirstByte == -1) {
+ return (false);
+ }
+ int Length = (FirstByte & 7) + 1;
+ if (Length == 7) {
+ int B1 = ppm.decodeChar();
+ if (B1 == -1) {
+ return (false);
+ }
+ Length = B1 + 7;
+ } else if (Length == 8) {
+ int B1 = ppm.decodeChar();
+ if (B1 == -1) {
+ return (false);
+ }
+ int B2 = ppm.decodeChar();
+ if (B2 == -1) {
+ return (false);
+ }
+ Length = B1 * 256 + B2;
+ }
+ List<Byte> vmCode = new ArrayList<Byte>();
+ for (int I = 0; I < Length; I++) {
+ int Ch = ppm.decodeChar();
+ if (Ch == -1) {
+ return (false);
+ }
+ vmCode.add(Byte.valueOf((byte) Ch));// VMCode[I]=Ch;
+ }
+ return (addVMCode(FirstByte, vmCode, Length));
+ }
+
+ private boolean addVMCode(int firstByte, List<Byte> vmCode, int length) {
+ BitInput Inp = new BitInput();
+ Inp.InitBitInput();
+ // memcpy(Inp.InBuf,Code,Min(BitInput::MAX_SIZE,CodeSize));
+ for (int i = 0; i < Math.min(BitInput.MAX_SIZE, vmCode.size()); i++) {
+ Inp.getInBuf()[i] = vmCode.get(i);
+ }
+ rarVM.init();
+
+ int FiltPos;
+ if ((firstByte & 0x80) != 0) {
+ FiltPos = RarVM.ReadData(Inp);
+ if (FiltPos == 0) {
+ initFilters();
+ } else {
+ FiltPos--;
+ }
+ } else
+ FiltPos = lastFilter; // use the same filter as last time
+
+ if (FiltPos > filters.size() || FiltPos > oldFilterLengths.size()) {
+ return (false);
+ }
+ lastFilter = FiltPos;
+ boolean NewFilter = (FiltPos == filters.size());
+
+ UnpackFilter StackFilter = new UnpackFilter(); // new filter for
+ // PrgStack
+
+ UnpackFilter Filter;
+ if (NewFilter) // new filter code, never used before since VM reset
+ {
+ // too many different filters, corrupt archive
+ if (FiltPos > 1024) {
+ return (false);
+ }
+
+ // Filters[Filters.Size()-1]=Filter=new UnpackFilter;
+ Filter = new UnpackFilter();
+ filters.add(Filter);
+ StackFilter.setParentFilter(filters.size() - 1);
+ oldFilterLengths.add(0);
+ Filter.setExecCount(0);
+ } else // filter was used in the past
+ {
+ Filter = filters.get(FiltPos);
+ StackFilter.setParentFilter(FiltPos);
+ Filter.setExecCount(Filter.getExecCount() + 1);// ->ExecCount++;
+ }
+
+ prgStack.add(StackFilter);
+ StackFilter.setExecCount(Filter.getExecCount());// ->ExecCount;
+
+ int BlockStart = RarVM.ReadData(Inp);
+ if ((firstByte & 0x40) != 0) {
+ BlockStart += 258;
+ }
+ StackFilter.setBlockStart((BlockStart + unpPtr) & Compress.MAXWINMASK);
+ if ((firstByte & 0x20) != 0) {
+ StackFilter.setBlockLength(RarVM.ReadData(Inp));
+ } else {
+ StackFilter
+ .setBlockLength(FiltPos < oldFilterLengths.size() ? oldFilterLengths
+ .get(FiltPos)
+ : 0);
+ }
+ StackFilter.setNextWindow((wrPtr != unpPtr)
+ && ((wrPtr - unpPtr) & Compress.MAXWINMASK) <= BlockStart);
+
+ // DebugLog("\nNextWindow: UnpPtr=%08x WrPtr=%08x
+ // BlockStart=%08x",UnpPtr,WrPtr,BlockStart);
+
+ oldFilterLengths.set(FiltPos, StackFilter.getBlockLength());
+
+ // memset(StackFilter->Prg.InitR,0,sizeof(StackFilter->Prg.InitR));
+ Arrays.fill(StackFilter.getPrg().getInitR(), 0);
+ StackFilter.getPrg().getInitR()[3] = RarVM.VM_GLOBALMEMADDR;// StackFilter->Prg.InitR[3]=VM_GLOBALMEMADDR;
+ StackFilter.getPrg().getInitR()[4] = StackFilter.getBlockLength();// StackFilter->Prg.InitR[4]=StackFilter->BlockLength;
+ StackFilter.getPrg().getInitR()[5] = StackFilter.getExecCount();// StackFilter->Prg.InitR[5]=StackFilter->ExecCount;
+
+ if ((firstByte & 0x10) != 0) // set registers to optional parameters
+ // if any
+ {
+ int InitMask = Inp.fgetbits() >>> 9;
+ Inp.faddbits(7);
+ for (int I = 0; I < 7; I++) {
+ if ((InitMask & (1 << I)) != 0) {
+ // StackFilter->Prg.InitR[I]=RarVM::ReadData(Inp);
+ StackFilter.getPrg().getInitR()[I] = RarVM.ReadData(Inp);
+ }
+ }
+ }
+
+ if (NewFilter) {
+ int VMCodeSize = RarVM.ReadData(Inp);
+ if (VMCodeSize >= 0x10000 || VMCodeSize == 0) {
+ return (false);
+ }
+ byte[] VMCode = new byte[VMCodeSize];
+ for (int I = 0; I < VMCodeSize; I++) {
+ if (Inp.Overflow(3)) {
+ return (false);
+ }
+ VMCode[I] = (byte) (Inp.fgetbits() >> 8);
+ Inp.faddbits(8);
+ }
+ // VM.Prepare(&VMCode[0],VMCodeSize,&Filter->Prg);
+ rarVM.prepare(VMCode, VMCodeSize, Filter.getPrg());
+ }
+ StackFilter.getPrg().setAltCmd(Filter.getPrg().getCmd());// StackFilter->Prg.AltCmd=&Filter->Prg.Cmd[0];
+ StackFilter.getPrg().setCmdCount(Filter.getPrg().getCmdCount());// StackFilter->Prg.CmdCount=Filter->Prg.CmdCount;
+
+ int StaticDataSize = Filter.getPrg().getStaticData().size();
+ if (StaticDataSize > 0 && StaticDataSize < RarVM.VM_GLOBALMEMSIZE) {
+ // read statically defined data contained in DB commands
+ // StackFilter->Prg.StaticData.Add(StaticDataSize);
+ StackFilter.getPrg().setStaticData(Filter.getPrg().getStaticData());
+ // memcpy(&StackFilter->Prg.StaticData[0],&Filter->Prg.StaticData[0],StaticDataSize);
+ }
+
+ if (StackFilter.getPrg().getGlobalData().size() < RarVM.VM_FIXEDGLOBALSIZE) {
+ // StackFilter->Prg.GlobalData.Reset();
+ // StackFilter->Prg.GlobalData.Add(VM_FIXEDGLOBALSIZE);
+ StackFilter.getPrg().getGlobalData().clear();
+ StackFilter.getPrg().getGlobalData().setSize(
+ RarVM.VM_FIXEDGLOBALSIZE);
+ }
+
+ // byte *GlobalData=&StackFilter->Prg.GlobalData[0];
+ Vector<Byte> globalData = StackFilter.getPrg().getGlobalData();
+ for (int I = 0; I < 7; I++) {
+ rarVM.setLowEndianValue(globalData, I * 4, StackFilter.getPrg()
+ .getInitR()[I]);
+ }
+
+ // VM.SetLowEndianValue((uint
+ // *)&GlobalData[0x1c],StackFilter->BlockLength);
+ rarVM.setLowEndianValue(globalData, 0x1c, StackFilter.getBlockLength());
+ // VM.SetLowEndianValue((uint *)&GlobalData[0x20],0);
+ rarVM.setLowEndianValue(globalData, 0x20, 0);
+ rarVM.setLowEndianValue(globalData, 0x24, 0);
+ rarVM.setLowEndianValue(globalData, 0x28, 0);
+
+ // VM.SetLowEndianValue((uint
+ // *)&GlobalData[0x2c],StackFilter->ExecCount);
+ rarVM.setLowEndianValue(globalData, 0x2c, StackFilter.getExecCount());
+ // memset(&GlobalData[0x30],0,16);
+ for (int i = 0; i < 16; i++) {
+ globalData.set(0x30 + i, Byte.valueOf((byte) (0)));
+ }
+ if ((firstByte & 8) != 0) // put data block passed as parameter if any
+ {
+ if (Inp.Overflow(3)) {
+ return (false);
+ }
+ int DataSize = RarVM.ReadData(Inp);
+ if (DataSize > RarVM.VM_GLOBALMEMSIZE - RarVM.VM_FIXEDGLOBALSIZE) {
+ return (false);
+ }
+ int CurSize = StackFilter.getPrg().getGlobalData().size();
+ if (CurSize < DataSize + RarVM.VM_FIXEDGLOBALSIZE) {
+ // StackFilter->Prg.GlobalData.Add(DataSize+VM_FIXEDGLOBALSIZE-CurSize);
+ StackFilter.getPrg().getGlobalData().setSize(
+ DataSize + RarVM.VM_FIXEDGLOBALSIZE - CurSize);
+ }
+ int offset = RarVM.VM_FIXEDGLOBALSIZE;
+ globalData = StackFilter.getPrg().getGlobalData();
+ for (int I = 0; I < DataSize; I++) {
+ if (Inp.Overflow(3)) {
+ return (false);
+ }
+ globalData.set(offset + I, Byte
+ .valueOf((byte) (Inp.fgetbits() >>> 8)));
+ Inp.faddbits(8);
+ }
+ }
+ return (true);
+ }
+
+ private void ExecuteCode(VMPreparedProgram Prg) {
+ if (Prg.getGlobalData().size() > 0) {
+ // Prg->InitR[6]=int64to32(WrittenFileSize);
+ Prg.getInitR()[6] = (int) (writtenFileSize);
+ // rarVM.SetLowEndianValue((uint
+ // *)&Prg->GlobalData[0x24],int64to32(WrittenFileSize));
+ rarVM.setLowEndianValue(Prg.getGlobalData(), 0x24,
+ (int) writtenFileSize);
+ // rarVM.SetLowEndianValue((uint
+ // *)&Prg->GlobalData[0x28],int64to32(WrittenFileSize>>32));
+ rarVM.setLowEndianValue(Prg.getGlobalData(), 0x28,
+ (int) (writtenFileSize >>> 32));
+ rarVM.execute(Prg);
+ }
+ }
+
+ // Duplicate method
+ // private boolean ReadEndOfBlock() throws IOException, RarException
+ // {
+ // int BitField = getbits();
+ // boolean NewTable, NewFile = false;
+ // if ((BitField & 0x8000) != 0) {
+ // NewTable = true;
+ // addbits(1);
+ // } else {
+ // NewFile = true;
+ // NewTable = (BitField & 0x4000) != 0;
+ // addbits(2);
+ // }
+ // tablesRead = !NewTable;
+ // return !(NewFile || NewTable && !readTables());
+ // }
+
+ public boolean isFileExtracted() {
+ return fileExtracted;
+ }
+
+ public void setDestSize(long destSize) {
+ this.destUnpSize = destSize;
+ this.fileExtracted = false;
+ }
+
+ public void setSuspended(boolean suspended) {
+ this.suspended = suspended;
+ }
+
+ public int getChar() throws IOException, RarException {
+ if (inAddr > BitInput.MAX_SIZE - 30) {
+ unpReadBuf();
+ }
+ return (inBuf[inAddr++] & 0xff);
+ }
+
+ public int getPpmEscChar() {
+ return ppmEscChar;
+ }
+
+ public void setPpmEscChar(int ppmEscChar) {
+ this.ppmEscChar = ppmEscChar;
+ }
+
+ public void cleanUp() {
+ if (ppm != null) {
+ SubAllocator allocator = ppm.getSubAlloc();
+ if (allocator != null) {
+ allocator.stopSubAllocator();
+ }
+ }
+ }
+}
diff --git a/src/com/github/junrar/unpack/Unpack15.java b/src/com/github/junrar/unpack/Unpack15.java
new file mode 100644
index 0000000..d365cc6
--- /dev/null
+++ b/src/com/github/junrar/unpack/Unpack15.java
@@ -0,0 +1,620 @@
+/*
+ * Copyright (c) 2007 innoSysTec (R) GmbH, Germany. All rights reserved.
+ * Original author: Edmund Wagner
+ * Creation date: 21.06.2007
+ *
+ * Source: $HeadURL$
+ * Last changed: $LastChangedDate$
+ *
+ * the unrar licence applies to all junrar source and binary distributions
+ * you are not allowed to use this source to re-create the RAR compression algorithm
+ *
+ * Here some html entities which can be used for escaping javadoc tags:
+ * "&": "&#038;" or "&amp;"
+ * "<": "&#060;" or "&lt;"
+ * ">": "&#062;" or "&gt;"
+ * "@": "&#064;"
+ */
+package com.github.junrar.unpack;
+
+import java.io.IOException;
+import java.util.Arrays;
+
+import com.github.junrar.exception.RarException;
+import com.github.junrar.unpack.decode.Compress;
+import com.github.junrar.unpack.vm.BitInput;
+
+
+/**
+ * DOCUMENT ME
+ *
+ * @author $LastChangedBy$
+ * @version $LastChangedRevision$
+ */
+public abstract class Unpack15 extends BitInput
+{
+
+ protected int readBorder;
+
+ protected boolean suspended;
+
+ protected boolean unpAllBuf;
+
+ protected ComprDataIO unpIO;
+
+ protected boolean unpSomeRead;
+
+ protected int readTop;
+
+ protected long destUnpSize;
+
+ protected byte[] window;
+
+ protected int[] oldDist = new int[4];
+
+ protected int unpPtr, wrPtr;
+
+ protected int oldDistPtr;
+
+ protected int[] ChSet = new int[256], ChSetA = new int[256],
+ ChSetB = new int[256], ChSetC = new int[256];
+
+ protected int[] Place = new int[256], PlaceA = new int[256],
+ PlaceB = new int[256], PlaceC = new int[256];
+
+ protected int[] NToPl = new int[256], NToPlB = new int[256],
+ NToPlC = new int[256];
+
+ protected int FlagBuf, AvrPlc, AvrPlcB, AvrLn1, AvrLn2, AvrLn3;
+
+ protected int Buf60, NumHuf, StMode, LCount, FlagsCnt;
+
+ protected int Nhfb, Nlzb, MaxDist3;
+
+ protected int lastDist, lastLength;
+
+ private static final int STARTL1 = 2;
+
+ private static int DecL1[] = { 0x8000, 0xa000, 0xc000, 0xd000, 0xe000,
+ 0xea00, 0xee00, 0xf000, 0xf200, 0xf200, 0xffff };
+
+ private static int PosL1[] = { 0, 0, 0, 2, 3, 5, 7, 11, 16, 20, 24, 32, 32 };
+
+ private static final int STARTL2 = 3;
+
+ private static int DecL2[] = { 0xa000, 0xc000, 0xd000, 0xe000, 0xea00,
+ 0xee00, 0xf000, 0xf200, 0xf240, 0xffff };
+
+ private static int PosL2[] = { 0, 0, 0, 0, 5, 7, 9, 13, 18, 22, 26, 34, 36 };
+
+ private static final int STARTHF0 = 4;
+
+ private static int DecHf0[] = { 0x8000, 0xc000, 0xe000, 0xf200, 0xf200,
+ 0xf200, 0xf200, 0xf200, 0xffff };
+
+ private static int PosHf0[] = { 0, 0, 0, 0, 0, 8, 16, 24, 33, 33, 33, 33,
+ 33 };
+
+ private static final int STARTHF1 = 5;
+
+ private static int DecHf1[] = { 0x2000, 0xc000, 0xe000, 0xf000, 0xf200,
+ 0xf200, 0xf7e0, 0xffff };
+
+ private static int PosHf1[] = { 0, 0, 0, 0, 0, 0, 4, 44, 60, 76, 80, 80,
+ 127 };
+
+ private static final int STARTHF2 = 5;
+
+ private static int DecHf2[] = { 0x1000, 0x2400, 0x8000, 0xc000, 0xfa00,
+ 0xffff, 0xffff, 0xffff };
+
+ private static int PosHf2[] = { 0, 0, 0, 0, 0, 0, 2, 7, 53, 117, 233, 0, 0 };
+
+ private static final int STARTHF3 = 6;
+
+ private static int DecHf3[] = { 0x800, 0x2400, 0xee00, 0xfe80, 0xffff,
+ 0xffff, 0xffff };
+
+ private static int PosHf3[] = { 0, 0, 0, 0, 0, 0, 0, 2, 16, 218, 251, 0, 0 };
+
+ private static final int STARTHF4 = 8;
+
+ private static int DecHf4[] = { 0xff00, 0xffff, 0xffff, 0xffff, 0xffff,
+ 0xffff };
+
+ private static int PosHf4[] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 255, 0, 0, 0 };
+
+ static int ShortLen1[] = { 1, 3, 4, 4, 5, 6, 7, 8, 8, 4, 4, 5, 6, 6, 4, 0 };
+
+ static int ShortXor1[] = { 0, 0xa0, 0xd0, 0xe0, 0xf0, 0xf8, 0xfc, 0xfe,
+ 0xff, 0xc0, 0x80, 0x90, 0x98, 0x9c, 0xb0 };
+
+ static int ShortLen2[] = { 2, 3, 3, 3, 4, 4, 5, 6, 6, 4, 4, 5, 6, 6, 4, 0 };
+
+ static int ShortXor2[] = { 0, 0x40, 0x60, 0xa0, 0xd0, 0xe0, 0xf0, 0xf8,
+ 0xfc, 0xc0, 0x80, 0x90, 0x98, 0x9c, 0xb0 };
+
+ protected abstract void unpInitData(boolean solid);
+
+ protected void unpack15(boolean solid) throws IOException, RarException
+ {
+ if (suspended) {
+ unpPtr = wrPtr;
+ } else {
+ unpInitData(solid);
+ oldUnpInitData(solid);
+ unpReadBuf();
+ if (!solid) {
+ initHuff();
+ unpPtr = 0;
+ } else {
+ unpPtr = wrPtr;
+ }
+ --destUnpSize;
+ }
+ if (destUnpSize >= 0) {
+ getFlagsBuf();
+ FlagsCnt = 8;
+ }
+
+ while (destUnpSize >= 0) {
+ unpPtr &= Compress.MAXWINMASK;
+
+ if (inAddr > readTop - 30 && !unpReadBuf()) {
+ break;
+ }
+ if (((wrPtr - unpPtr) & Compress.MAXWINMASK) < 270
+ && wrPtr != unpPtr) {
+ oldUnpWriteBuf();
+ if (suspended) {
+ return;
+ }
+ }
+ if (StMode != 0) {
+ huffDecode();
+ continue;
+ }
+
+ if (--FlagsCnt < 0) {
+ getFlagsBuf();
+ FlagsCnt = 7;
+ }
+
+ if ((FlagBuf & 0x80) != 0) {
+ FlagBuf <<= 1;
+ if (Nlzb > Nhfb) {
+ longLZ();
+ } else {
+ huffDecode();
+ }
+ } else {
+ FlagBuf <<= 1;
+ if (--FlagsCnt < 0) {
+ getFlagsBuf();
+ FlagsCnt = 7;
+ }
+ if ((FlagBuf & 0x80) != 0) {
+ FlagBuf <<= 1;
+ if (Nlzb > Nhfb) {
+ huffDecode();
+ } else {
+ longLZ();
+ }
+ } else {
+ FlagBuf <<= 1;
+ shortLZ();
+ }
+ }
+ }
+ oldUnpWriteBuf();
+ }
+
+
+
+ protected boolean unpReadBuf() throws IOException, RarException
+ {
+ int dataSize=readTop-inAddr;
+ if (dataSize<0){
+ return(false);
+ }
+ if (inAddr>BitInput.MAX_SIZE/2) {
+ if (dataSize>0){
+ //memmove(InBuf,InBuf+InAddr,DataSize);
+// for (int i = 0; i < dataSize; i++) {
+// inBuf[i] = inBuf[inAddr + i];
+// }
+ System.arraycopy(inBuf, inAddr, inBuf, 0, dataSize);
+ }
+ inAddr=0;
+ readTop=dataSize;
+ }
+ else{
+ dataSize=readTop;
+ }
+ //int readCode=UnpIO->UnpRead(InBuf+DataSize,(BitInput::MAX_SIZE-DataSize)&~0xf);
+ int readCode=unpIO.unpRead(inBuf, dataSize, (BitInput.MAX_SIZE-dataSize)&~0xf);
+ if (readCode>0){
+ readTop+=readCode;
+ }
+ readBorder=readTop-30;
+ return(readCode!=-1);
+ }
+
+ private int getShortLen1(int pos)
+ {
+ return pos == 1 ? Buf60 + 3 : ShortLen1[pos];
+ }
+
+ private int getShortLen2(int pos)
+ {
+ return pos == 3 ? Buf60 + 3 : ShortLen2[pos];
+ }
+
+ protected void shortLZ()
+ {
+ int Length, SaveLength;
+ int LastDistance;
+ int Distance;
+ int DistancePlace;
+ NumHuf = 0;
+
+ int BitField = fgetbits();
+ if (LCount == 2) {
+ faddbits(1);
+ if (BitField >= 0x8000) {
+ oldCopyString(lastDist, lastLength);
+ return;
+ }
+ BitField <<= 1;
+ LCount = 0;
+ }
+ BitField >>>= 8;
+ if (AvrLn1 < 37) {
+ for (Length = 0;; Length++) {
+ if (((BitField ^ ShortXor1[Length]) & (~(0xff >>> getShortLen1(Length)))) == 0) {
+ break;
+ }
+ }
+ faddbits(getShortLen1(Length));
+ } else {
+ for (Length = 0;; Length++) {
+ if (((BitField ^ ShortXor2[Length]) & (~(0xff >> getShortLen2(Length)))) == 0) {
+ break;
+ }
+ }
+ faddbits(getShortLen2(Length));
+ }
+
+ if (Length >= 9) {
+ if (Length == 9) {
+ LCount++;
+ oldCopyString(lastDist, lastLength);
+ return;
+ }
+ if (Length == 14) {
+ LCount = 0;
+ Length = decodeNum(fgetbits(), STARTL2, DecL2, PosL2) + 5;
+ Distance = (fgetbits() >> 1) | 0x8000;
+ faddbits(15);
+ lastLength = Length;
+ lastDist = Distance;
+ oldCopyString(Distance, Length);
+ return;
+ }
+
+ LCount = 0;
+ SaveLength = Length;
+ Distance = oldDist[(oldDistPtr - (Length - 9)) & 3];
+ Length = decodeNum(fgetbits(), STARTL1, DecL1, PosL1) + 2;
+ if (Length == 0x101 && SaveLength == 10) {
+ Buf60 ^= 1;
+ return;
+ }
+ if (Distance > 256)
+ Length++;
+ if (Distance >= MaxDist3)
+ Length++;
+
+ oldDist[oldDistPtr++] = Distance;
+ oldDistPtr = oldDistPtr & 3;
+ lastLength = Length;
+ lastDist = Distance;
+ oldCopyString(Distance, Length);
+ return;
+ }
+
+ LCount = 0;
+ AvrLn1 += Length;
+ AvrLn1 -= AvrLn1 >> 4;
+
+ DistancePlace = decodeNum(fgetbits(), STARTHF2, DecHf2, PosHf2) & 0xff;
+ Distance = ChSetA[DistancePlace];
+ if (--DistancePlace != -1) {
+ PlaceA[Distance]--;
+ LastDistance = ChSetA[DistancePlace];
+ PlaceA[LastDistance]++;
+ ChSetA[DistancePlace + 1] = LastDistance;
+ ChSetA[DistancePlace] = Distance;
+ }
+ Length += 2;
+ oldDist[oldDistPtr++] = ++Distance;
+ oldDistPtr = oldDistPtr & 3;
+ lastLength = Length;
+ lastDist = Distance;
+ oldCopyString(Distance, Length);
+ }
+
+ protected void longLZ()
+ {
+ int Length;
+ int Distance;
+ int DistancePlace, NewDistancePlace;
+ int OldAvr2, OldAvr3;
+
+ NumHuf = 0;
+ Nlzb += 16;
+ if (Nlzb > 0xff) {
+ Nlzb = 0x90;
+ Nhfb >>>= 1;
+ }
+ OldAvr2 = AvrLn2;
+
+ int BitField = fgetbits();
+ if (AvrLn2 >= 122) {
+ Length = decodeNum(BitField, STARTL2, DecL2, PosL2);
+ } else {
+ if (AvrLn2 >= 64) {
+ Length = decodeNum(BitField, STARTL1, DecL1, PosL1);
+ } else {
+ if (BitField < 0x100) {
+ Length = BitField;
+ faddbits(16);
+ } else {
+ for (Length = 0; ((BitField << Length) & 0x8000) == 0; Length++) {
+ ;
+ }
+ faddbits(Length + 1);
+ }
+ }
+ }
+ AvrLn2 += Length;
+ AvrLn2 -= AvrLn2 >>> 5;
+
+ BitField = fgetbits();
+ if (AvrPlcB > 0x28ff) {
+ DistancePlace = decodeNum(BitField, STARTHF2, DecHf2, PosHf2);
+ } else {
+ if (AvrPlcB > 0x6ff) {
+ DistancePlace = decodeNum(BitField, STARTHF1, DecHf1, PosHf1);
+ } else {
+ DistancePlace = decodeNum(BitField, STARTHF0, DecHf0, PosHf0);
+ }
+ }
+ AvrPlcB += DistancePlace;
+ AvrPlcB -= AvrPlcB >> 8;
+ while (true) {
+ Distance = ChSetB[DistancePlace & 0xff];
+ NewDistancePlace = NToPlB[Distance++ & 0xff]++;
+ if ((Distance & 0xff) == 0) {
+ corrHuff(ChSetB, NToPlB);
+ } else {
+ break;
+ }
+ }
+
+ ChSetB[DistancePlace] = ChSetB[NewDistancePlace];
+ ChSetB[NewDistancePlace] = Distance;
+
+ Distance = ((Distance & 0xff00) | (fgetbits() >>> 8)) >>> 1;
+ faddbits(7);
+
+ OldAvr3 = AvrLn3;
+ if (Length != 1 && Length != 4) {
+ if (Length == 0 && Distance <= MaxDist3) {
+ AvrLn3++;
+ AvrLn3 -= AvrLn3 >> 8;
+ } else {
+ if (AvrLn3 > 0) {
+ AvrLn3--;
+ }
+ }
+ }
+ Length += 3;
+ if (Distance >= MaxDist3) {
+ Length++;
+ }
+ if (Distance <= 256) {
+ Length += 8;
+ }
+ if (OldAvr3 > 0xb0 || AvrPlc >= 0x2a00 && OldAvr2 < 0x40) {
+ MaxDist3 = 0x7f00;
+ } else {
+ MaxDist3 = 0x2001;
+ }
+ oldDist[oldDistPtr++] = Distance;
+ oldDistPtr = oldDistPtr & 3;
+ lastLength = Length;
+ lastDist = Distance;
+ oldCopyString(Distance, Length);
+ }
+
+ protected void huffDecode()
+ {
+ int CurByte, NewBytePlace;
+ int Length;
+ int Distance;
+ int BytePlace;
+
+ int BitField = fgetbits();
+
+ if (AvrPlc > 0x75ff) {
+ BytePlace = decodeNum(BitField, STARTHF4, DecHf4, PosHf4);
+ } else {
+ if (AvrPlc > 0x5dff) {
+ BytePlace = decodeNum(BitField, STARTHF3, DecHf3, PosHf3);
+ } else {
+ if (AvrPlc > 0x35ff) {
+ BytePlace = decodeNum(BitField, STARTHF2, DecHf2, PosHf2);
+ } else {
+ if (AvrPlc > 0x0dff) {
+ BytePlace = decodeNum(BitField, STARTHF1, DecHf1,
+ PosHf1);
+ } else {
+ BytePlace = decodeNum(BitField, STARTHF0, DecHf0,
+ PosHf0);
+ }
+ }
+ }
+ }
+ BytePlace &= 0xff;
+ if (StMode != 0) {
+ if (BytePlace == 0 && BitField > 0xfff) {
+ BytePlace = 0x100;
+ }
+ if (--BytePlace == -1) {
+ BitField = fgetbits();
+ faddbits(1);
+ if ((BitField & 0x8000) != 0) {
+ NumHuf = StMode = 0;
+ return;
+ } else {
+ Length = (BitField & 0x4000) != 0 ? 4 : 3;
+ faddbits(1);
+ Distance = decodeNum(fgetbits(), STARTHF2, DecHf2, PosHf2);
+ Distance = (Distance << 5) | (fgetbits() >>> 11);
+ faddbits(5);
+ oldCopyString(Distance, Length);
+ return;
+ }
+ }
+ } else {
+ if (NumHuf++ >= 16 && FlagsCnt == 0) {
+ StMode = 1;
+ }
+ }
+ AvrPlc += BytePlace;
+ AvrPlc -= AvrPlc >>> 8;
+ Nhfb += 16;
+ if (Nhfb > 0xff) {
+ Nhfb = 0x90;
+ Nlzb >>>= 1;
+ }
+
+ window[unpPtr++] = (byte) (ChSet[BytePlace] >>> 8);
+ --destUnpSize;
+
+ while (true) {
+ CurByte = ChSet[BytePlace];
+ NewBytePlace = NToPl[CurByte++ & 0xff]++;
+ if ((CurByte & 0xff) > 0xa1) {
+ corrHuff(ChSet, NToPl);
+ } else {
+ break;
+ }
+ }
+
+ ChSet[BytePlace] = ChSet[NewBytePlace];
+ ChSet[NewBytePlace] = CurByte;
+ }
+
+ protected void getFlagsBuf()
+ {
+ int Flags, NewFlagsPlace;
+ int FlagsPlace = decodeNum(fgetbits(), STARTHF2, DecHf2, PosHf2);
+
+ while (true) {
+ Flags = ChSetC[FlagsPlace];
+ FlagBuf = Flags >>> 8;
+ NewFlagsPlace = NToPlC[Flags++ & 0xff]++;
+ if ((Flags & 0xff) != 0) {
+ break;
+ }
+ corrHuff(ChSetC, NToPlC);
+ }
+
+ ChSetC[FlagsPlace] = ChSetC[NewFlagsPlace];
+ ChSetC[NewFlagsPlace] = Flags;
+ }
+
+ protected void oldUnpInitData(boolean Solid)
+ {
+ if (!Solid ) {
+ AvrPlcB = AvrLn1 = AvrLn2 = AvrLn3 = NumHuf = Buf60 = 0;
+ AvrPlc = 0x3500;
+ MaxDist3 = 0x2001;
+ Nhfb = Nlzb = 0x80;
+ }
+ FlagsCnt = 0;
+ FlagBuf = 0;
+ StMode = 0;
+ LCount = 0;
+ readTop = 0;
+ }
+
+ protected void initHuff()
+ {
+ for (int I = 0; I < 256; I++) {
+ Place[I] = PlaceA[I] = PlaceB[I] = I;
+ PlaceC[I] = (~I + 1) & 0xff;
+ ChSet[I] = ChSetB[I] = I << 8;
+ ChSetA[I] = I;
+ ChSetC[I] = ((~I + 1) & 0xff) << 8;
+ }
+
+ Arrays.fill(NToPl, 0);// memset(NToPl,0,sizeof(NToPl));
+ Arrays.fill(NToPlB, 0); // memset(NToPlB,0,sizeof(NToPlB));
+ Arrays.fill(NToPlC, 0); // memset(NToPlC,0,sizeof(NToPlC));
+ corrHuff(ChSetB, NToPlB);
+ }
+
+ protected void corrHuff(int[] CharSet, int[] NumToPlace)
+ {
+ int I, J, pos = 0;
+ for (I = 7; I >= 0; I--) {
+ for (J = 0; J < 32; J++, pos++) {
+ CharSet[pos] = ((CharSet[pos] & ~0xff) | I);// *CharSet=(*CharSet
+ // & ~0xff) | I;
+ }
+ }
+ Arrays.fill(NumToPlace, 0);// memset(NumToPlace,0,sizeof(NToPl));
+ for (I = 6; I >= 0; I--) {
+ NumToPlace[I] = (7 - I) * 32;
+ }
+ }
+
+ protected void oldCopyString(int Distance, int Length)
+ {
+ destUnpSize -= Length;
+ while ((Length--) != 0) {
+ window[unpPtr] = window[(unpPtr - Distance) & Compress.MAXWINMASK];
+ unpPtr = (unpPtr + 1) & Compress.MAXWINMASK;
+ }
+ }
+
+ protected int decodeNum(int Num, int StartPos, int[] DecTab, int[] PosTab)
+ {
+ int I;
+ for (Num &= 0xfff0, I = 0; DecTab[I] <= Num; I++) {
+ StartPos++;
+ }
+ faddbits(StartPos);
+ return (((Num - (I != 0 ? DecTab[I - 1] : 0)) >>> (16 - StartPos)) + PosTab[StartPos]);
+ }
+
+ protected void oldUnpWriteBuf() throws IOException
+ {
+ if (unpPtr != wrPtr) {
+ unpSomeRead = true;
+ }
+ if (unpPtr < wrPtr) {
+ unpIO.unpWrite(window, wrPtr, -wrPtr & Compress.MAXWINMASK);
+ unpIO.unpWrite(window, 0, unpPtr);
+ unpAllBuf = true;
+ } else {
+ unpIO.unpWrite(window, wrPtr, unpPtr - wrPtr);
+ }
+ wrPtr = unpPtr;
+ }
+
+
+}
diff --git a/src/com/github/junrar/unpack/Unpack20.java b/src/com/github/junrar/unpack/Unpack20.java
new file mode 100644
index 0000000..a9138cc
--- /dev/null
+++ b/src/com/github/junrar/unpack/Unpack20.java
@@ -0,0 +1,597 @@
+/*
+ * Copyright (c) 2007 innoSysTec (R) GmbH, Germany. All rights reserved.
+ * Original author: Edmund Wagner
+ * Creation date: 21.06.2007
+ *
+ * Source: $HeadURL$
+ * Last changed: $LastChangedDate$
+ *
+ * the unrar licence applies to all junrar source and binary distributions
+ * you are not allowed to use this source to re-create the RAR compression algorithm
+ *
+ * Here some html entities which can be used for escaping javadoc tags:
+ * "&": "&#038;" or "&amp;"
+ * "<": "&#060;" or "&lt;"
+ * ">": "&#062;" or "&gt;"
+ * "@": "&#064;"
+ */
+package com.github.junrar.unpack;
+
+import java.io.IOException;
+import java.util.Arrays;
+
+import com.github.junrar.exception.RarException;
+import com.github.junrar.unpack.decode.AudioVariables;
+import com.github.junrar.unpack.decode.BitDecode;
+import com.github.junrar.unpack.decode.Compress;
+import com.github.junrar.unpack.decode.Decode;
+import com.github.junrar.unpack.decode.DistDecode;
+import com.github.junrar.unpack.decode.LitDecode;
+import com.github.junrar.unpack.decode.LowDistDecode;
+import com.github.junrar.unpack.decode.MultDecode;
+import com.github.junrar.unpack.decode.RepDecode;
+
+
+
+/**
+ * DOCUMENT ME
+ *
+ * @author $LastChangedBy$
+ * @version $LastChangedRevision$
+ */
+public abstract class Unpack20 extends Unpack15
+{
+
+ protected MultDecode[] MD = new MultDecode[4];
+
+ protected byte[] UnpOldTable20 = new byte[Compress.MC20 * 4];
+
+ protected int UnpAudioBlock, UnpChannels, UnpCurChannel, UnpChannelDelta;
+
+ protected AudioVariables[] AudV = new AudioVariables[4];
+
+ protected LitDecode LD = new LitDecode();
+
+ protected DistDecode DD = new DistDecode();
+
+ protected LowDistDecode LDD = new LowDistDecode();
+
+ protected RepDecode RD = new RepDecode();
+
+ protected BitDecode BD = new BitDecode();
+
+ public static final int[] LDecode = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 10, 12,
+ 14, 16, 20, 24, 28, 32, 40, 48, 56, 64, 80, 96, 112, 128, 160, 192,
+ 224 };
+
+ public static final byte[] LBits = { 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 2,
+ 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5 };
+
+ public static final int[] DDecode = { 0, 1, 2, 3, 4, 6, 8, 12, 16, 24, 32,
+ 48, 64, 96, 128, 192, 256, 384, 512, 768, 1024, 1536, 2048, 3072,
+ 4096, 6144, 8192, 12288, 16384, 24576, 32768, 49152, 65536, 98304,
+ 131072, 196608, 262144, 327680, 393216, 458752, 524288, 589824,
+ 655360, 720896, 786432, 851968, 917504, 983040 };
+
+ public static final int[] DBits = { 0, 0, 0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5,
+ 5, 6, 6, 7, 7, 8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 13, 13, 14, 14,
+ 15, 15, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16 };
+
+ public static final int[] SDDecode = { 0, 4, 8, 16, 32, 64, 128, 192 };
+
+ public static final int[] SDBits = { 2, 2, 3, 4, 5, 6, 6, 6 };
+
+ protected void unpack20(boolean solid) throws IOException, RarException
+ {
+
+ int Bits;
+
+ if (suspended) {
+ unpPtr = wrPtr;
+ } else {
+ unpInitData(solid);
+ if (!unpReadBuf()) {
+ return;
+ }
+ if (!solid) {
+ if (!ReadTables20()) {
+ return;
+ }
+ }
+ --destUnpSize;
+ }
+
+ while (destUnpSize >= 0) {
+ unpPtr &= Compress.MAXWINMASK;
+
+ if (inAddr > readTop - 30)
+ if (!unpReadBuf())
+ break;
+ if (((wrPtr - unpPtr) & Compress.MAXWINMASK) < 270
+ && wrPtr != unpPtr) {
+ oldUnpWriteBuf();
+ if (suspended)
+ return;
+ }
+ if (UnpAudioBlock != 0) {
+ int AudioNumber = decodeNumber(MD[UnpCurChannel]);
+
+ if (AudioNumber == 256) {
+ if (!ReadTables20())
+ break;
+ continue;
+ }
+ window[unpPtr++] = DecodeAudio(AudioNumber);
+ if (++UnpCurChannel == UnpChannels)
+ UnpCurChannel = 0;
+ --destUnpSize;
+ continue;
+ }
+
+ int Number = decodeNumber(LD);
+ if (Number < 256) {
+ window[unpPtr++] = (byte) Number;
+ --destUnpSize;
+ continue;
+ }
+ if (Number > 269) {
+ int Length = LDecode[Number -= 270] + 3;
+ if ((Bits = LBits[Number]) > 0) {
+ Length += getbits() >>> (16 - Bits);
+ addbits(Bits);
+ }
+
+ int DistNumber = decodeNumber(DD);
+ int Distance = DDecode[DistNumber] + 1;
+ if ((Bits = DBits[DistNumber]) > 0) {
+ Distance += getbits() >>> (16 - Bits);
+ addbits(Bits);
+ }
+
+ if (Distance >= 0x2000) {
+ Length++;
+ if (Distance >= 0x40000L)
+ Length++;
+ }
+
+ CopyString20(Length, Distance);
+ continue;
+ }
+ if (Number == 269) {
+ if (!ReadTables20())
+ break;
+ continue;
+ }
+ if (Number == 256) {
+ CopyString20(lastLength, lastDist);
+ continue;
+ }
+ if (Number < 261) {
+ int Distance = oldDist[(oldDistPtr - (Number - 256)) & 3];
+ int LengthNumber = decodeNumber(RD);
+ int Length = LDecode[LengthNumber] + 2;
+ if ((Bits = LBits[LengthNumber]) > 0) {
+ Length += getbits() >>> (16 - Bits);
+ addbits(Bits);
+ }
+ if (Distance >= 0x101) {
+ Length++;
+ if (Distance >= 0x2000) {
+ Length++;
+ if (Distance >= 0x40000)
+ Length++;
+ }
+ }
+ CopyString20(Length, Distance);
+ continue;
+ }
+ if (Number < 270) {
+ int Distance = SDDecode[Number -= 261] + 1;
+ if ((Bits = SDBits[Number]) > 0) {
+ Distance += getbits() >>> (16 - Bits);
+ addbits(Bits);
+ }
+ CopyString20(2, Distance);
+ continue;
+ }
+ }
+ ReadLastTables();
+ oldUnpWriteBuf();
+
+ }
+
+ protected void CopyString20(int Length, int Distance)
+ {
+ lastDist = oldDist[oldDistPtr++ & 3] = Distance;
+ lastLength = Length;
+ destUnpSize -= Length;
+
+ int DestPtr = unpPtr - Distance;
+ if (DestPtr < Compress.MAXWINSIZE - 300
+ && unpPtr < Compress.MAXWINSIZE - 300) {
+ window[unpPtr++] = window[DestPtr++];
+ window[unpPtr++] = window[DestPtr++];
+ while (Length > 2) {
+ Length--;
+ window[unpPtr++] = window[DestPtr++];
+ }
+ } else {
+ while ((Length--) != 0) {
+ window[unpPtr] = window[DestPtr++ & Compress.MAXWINMASK];
+ unpPtr = (unpPtr + 1) & Compress.MAXWINMASK;
+ }
+ }
+ }
+
+ protected void makeDecodeTables(byte[] lenTab, int offset, Decode dec,
+ int size)
+ {
+ int[] lenCount = new int[16];
+ int[] tmpPos = new int[16];
+ int i;
+ long M, N;
+
+ Arrays.fill(lenCount, 0);// memset(LenCount,0,sizeof(LenCount));
+
+ Arrays.fill(dec.getDecodeNum(), 0);// memset(Dec->DecodeNum,0,Size*sizeof(*Dec->DecodeNum));
+
+ for (i = 0; i < size; i++) {
+ lenCount[(int) (lenTab[offset + i] & 0xF)]++;
+ }
+ lenCount[0] = 0;
+ for (tmpPos[0] = 0, dec.getDecodePos()[0] = 0, dec.getDecodeLen()[0] = 0, N = 0, i = 1; i < 16; i++) {
+ N = 2 * (N + lenCount[i]);
+ M = N << (15 - i);
+ if (M > 0xFFFF) {
+ M = 0xFFFF;
+ }
+ dec.getDecodeLen()[i] = (int) M;
+ tmpPos[i] = dec.getDecodePos()[i] = dec.getDecodePos()[i - 1]
+ + lenCount[i - 1];
+ }
+
+ for (i = 0; i < size; i++) {
+ if (lenTab[offset + i] != 0) {
+ dec.getDecodeNum()[tmpPos[lenTab[offset + i] & 0xF]++] = i;
+ }
+ }
+ dec.setMaxNum(size);
+ }
+
+ protected int decodeNumber(Decode dec)
+ {
+ int bits;
+ long bitField = getbits() & 0xfffe;
+// if (bitField < dec.getDecodeLen()[8]) {
+// if (bitField < dec.getDecodeLen()[4]) {
+// if (bitField < dec.getDecodeLen()[2]) {
+// if (bitField < dec.getDecodeLen()[1]) {
+// bits = 1;
+// } else {
+// bits = 2;
+// }
+// } else {
+// if (bitField < dec.getDecodeLen()[3]) {
+// bits = 3;
+// } else {
+// bits = 4;
+// }
+// }
+// } else {
+// if (bitField < dec.getDecodeLen()[6]) {
+// if (bitField < dec.getDecodeLen()[5])
+// bits = 5;
+// else
+// bits = 6;
+// } else {
+// if (bitField < dec.getDecodeLen()[7]) {
+// bits = 7;
+// } else {
+// bits = 8;
+// }
+// }
+// }
+// } else {
+// if (bitField < dec.getDecodeLen()[12]) {
+// if (bitField < dec.getDecodeLen()[10])
+// if (bitField < dec.getDecodeLen()[9])
+// bits = 9;
+// else
+// bits = 10;
+// else if (bitField < dec.getDecodeLen()[11])
+// bits = 11;
+// else
+// bits = 12;
+// } else {
+// if (bitField < dec.getDecodeLen()[14]) {
+// if (bitField < dec.getDecodeLen()[13]) {
+// bits = 13;
+// } else {
+// bits = 14;
+// }
+// } else {
+// bits = 15;
+// }
+// }
+// }
+// addbits(bits);
+// int N = dec.getDecodePos()[bits]
+// + (((int) bitField - dec.getDecodeLen()[bits - 1]) >>> (16 - bits));
+// if (N >= dec.getMaxNum()) {
+// N = 0;
+// }
+// return (dec.getDecodeNum()[N]);
+ int[] decodeLen = dec.getDecodeLen();
+ if (bitField < decodeLen[8]) {
+ if (bitField < decodeLen[4]) {
+ if (bitField < decodeLen[2]) {
+ if (bitField < decodeLen[1]) {
+ bits = 1;
+ } else {
+ bits = 2;
+ }
+ } else {
+ if (bitField < decodeLen[3]) {
+ bits = 3;
+ } else {
+ bits = 4;
+ }
+ }
+ } else {
+ if (bitField < decodeLen[6]) {
+ if (bitField < decodeLen[5])
+ bits = 5;
+ else
+ bits = 6;
+ } else {
+ if (bitField < decodeLen[7]) {
+ bits = 7;
+ } else {
+ bits = 8;
+ }
+ }
+ }
+ } else {
+ if (bitField < decodeLen[12]) {
+ if (bitField < decodeLen[10])
+ if (bitField < decodeLen[9])
+ bits = 9;
+ else
+ bits = 10;
+ else if (bitField < decodeLen[11])
+ bits = 11;
+ else
+ bits = 12;
+ } else {
+ if (bitField < decodeLen[14]) {
+ if (bitField < decodeLen[13]) {
+ bits = 13;
+ } else {
+ bits = 14;
+ }
+ } else {
+ bits = 15;
+ }
+ }
+ }
+ addbits(bits);
+ int N = dec.getDecodePos()[bits]
+ + (((int) bitField - decodeLen[bits - 1]) >>> (16 - bits));
+ if (N >= dec.getMaxNum()) {
+ N = 0;
+ }
+ return (dec.getDecodeNum()[N]);
+ }
+
+ protected boolean ReadTables20() throws IOException, RarException
+ {
+ byte[] BitLength = new byte[Compress.BC20];
+ byte[] Table = new byte[Compress.MC20 * 4];
+ int TableSize, N, I;
+ if (inAddr > readTop - 25) {
+ if (!unpReadBuf()) {
+ return (false);
+ }
+ }
+ int BitField = getbits();
+ UnpAudioBlock = (BitField & 0x8000);
+
+ if (0 == (BitField & 0x4000)) {
+ // memset(UnpOldTable20,0,sizeof(UnpOldTable20));
+ Arrays.fill(UnpOldTable20, (byte) 0);
+ }
+ addbits(2);
+
+ if (UnpAudioBlock != 0) {
+ UnpChannels = ((BitField >>> 12) & 3) + 1;
+ if (UnpCurChannel >= UnpChannels) {
+ UnpCurChannel = 0;
+ }
+ addbits(2);
+ TableSize = Compress.MC20 * UnpChannels;
+ } else {
+ TableSize = Compress.NC20 + Compress.DC20 + Compress.RC20;
+ }
+ for (I = 0; I < Compress.BC20; I++) {
+ BitLength[I] = (byte) (getbits() >>> 12);
+ addbits(4);
+ }
+ makeDecodeTables(BitLength, 0, BD, Compress.BC20);
+ I = 0;
+ while (I < TableSize) {
+ if (inAddr > readTop - 5) {
+ if (!unpReadBuf()) {
+ return (false);
+ }
+ }
+ int Number = decodeNumber(BD);
+ if (Number < 16) {
+ Table[I] = (byte) ((Number + UnpOldTable20[I]) & 0xf);
+ I++;
+ } else if (Number == 16) {
+ N = (getbits() >>> 14) + 3;
+ addbits(2);
+ while (N-- > 0 && I < TableSize) {
+ Table[I] = Table[I - 1];
+ I++;
+ }
+ } else {
+ if (Number == 17) {
+ N = (getbits() >>> 13) + 3;
+ addbits(3);
+ } else {
+ N = (getbits() >>> 9) + 11;
+ addbits(7);
+ }
+ while (N-- > 0 && I < TableSize)
+ Table[I++] = 0;
+ }
+ }
+ if (inAddr > readTop) {
+ return (true);
+ }
+ if (UnpAudioBlock != 0)
+ for (I = 0; I < UnpChannels; I++)
+ makeDecodeTables(Table, I * Compress.MC20, MD[I], Compress.MC20);
+ else {
+ makeDecodeTables(Table, 0, LD, Compress.NC20);
+ makeDecodeTables(Table, Compress.NC20, DD, Compress.DC20);
+ makeDecodeTables(Table, Compress.NC20 + Compress.DC20, RD,
+ Compress.RC20);
+ }
+ // memcpy(UnpOldTable20,Table,sizeof(UnpOldTable20));
+ for (int i = 0; i < UnpOldTable20.length; i++) {
+ UnpOldTable20[i] = Table[i];
+ }
+ return (true);
+ }
+
+ protected void unpInitData20(boolean Solid)
+ {
+ if (!Solid) {
+ UnpChannelDelta = UnpCurChannel = 0;
+ UnpChannels = 1;
+ // memset(AudV,0,sizeof(AudV));
+ Arrays.fill(AudV, new AudioVariables());
+ // memset(UnpOldTable20,0,sizeof(UnpOldTable20));
+ Arrays.fill(UnpOldTable20, (byte) 0);
+ }
+ }
+
+ protected void ReadLastTables() throws IOException, RarException
+ {
+ if (readTop >= inAddr + 5) {
+ if (UnpAudioBlock != 0) {
+ if (decodeNumber(MD[UnpCurChannel]) == 256) {
+ ReadTables20();
+ }
+ } else {
+ if (decodeNumber(LD) == 269) {
+ ReadTables20();
+ }
+ }
+ }
+ }
+
+ protected byte DecodeAudio(int Delta)
+ {
+ AudioVariables v = AudV[UnpCurChannel];
+ v.setByteCount(v.getByteCount() + 1);
+ v.setD4(v.getD3());
+ v.setD3(v.getD2());// ->D3=V->D2;
+ v.setD2(v.getLastDelta() - v.getD1());// ->D2=V->LastDelta-V->D1;
+ v.setD1(v.getLastDelta());// V->D1=V->LastDelta;
+ // int PCh=8*V->LastChar+V->K1*V->D1 +V->K2*V->D2 +V->K3*V->D3
+ // +V->K4*V->D4+ V->K5*UnpChannelDelta;
+ int PCh = 8 * v.getLastChar() + v.getK1() * v.getD1();
+ PCh += v.getK2() * v.getD2() + v.getK3() * v.getD3();
+ PCh += v.getK4() * v.getD4() + v.getK5() * UnpChannelDelta;
+ PCh = (PCh >>> 3) & 0xFF;
+
+ int Ch = PCh - Delta;
+
+ int D = ((byte) Delta) << 3;
+
+ v.getDif()[0] += Math.abs(D);// V->Dif[0]+=abs(D);
+ v.getDif()[1] += Math.abs(D - v.getD1());// V->Dif[1]+=abs(D-V->D1);
+ v.getDif()[2] += Math.abs(D + v.getD1());// V->Dif[2]+=abs(D+V->D1);
+ v.getDif()[3] += Math.abs(D - v.getD2());// V->Dif[3]+=abs(D-V->D2);
+ v.getDif()[4] += Math.abs(D + v.getD2());// V->Dif[4]+=abs(D+V->D2);
+ v.getDif()[5] += Math.abs(D - v.getD3());// V->Dif[5]+=abs(D-V->D3);
+ v.getDif()[6] += Math.abs(D + v.getD3());// V->Dif[6]+=abs(D+V->D3);
+ v.getDif()[7] += Math.abs(D - v.getD4());// V->Dif[7]+=abs(D-V->D4);
+ v.getDif()[8] += Math.abs(D + v.getD4());// V->Dif[8]+=abs(D+V->D4);
+ v.getDif()[9] += Math.abs(D - UnpChannelDelta);// V->Dif[9]+=abs(D-UnpChannelDelta);
+ v.getDif()[10] += Math.abs(D + UnpChannelDelta);// V->Dif[10]+=abs(D+UnpChannelDelta);
+
+ v.setLastDelta((byte) (Ch - v.getLastChar()));
+ UnpChannelDelta = v.getLastDelta();
+ v.setLastChar(Ch);// V->LastChar=Ch;
+
+ if ((v.getByteCount() & 0x1F) == 0) {
+ int MinDif = v.getDif()[0], NumMinDif = 0;
+ v.getDif()[0] = 0;// ->Dif[0]=0;
+ for (int I = 1; I < v.getDif().length; I++) {
+ if (v.getDif()[I] < MinDif) {
+ MinDif = v.getDif()[I];
+ NumMinDif = I;
+ }
+ v.getDif()[I] = 0;
+ }
+ switch (NumMinDif) {
+ case 1:
+ if (v.getK1() >= -16) {
+ v.setK1(v.getK1() - 1);// V->K1--;
+ }
+ break;
+ case 2:
+ if (v.getK1() < 16) {
+ v.setK1(v.getK1() + 1);// V->K1++;
+ }
+ break;
+ case 3:
+ if (v.getK2() >= -16) {
+ v.setK2(v.getK2() - 1);// V->K2--;
+ }
+ break;
+ case 4:
+ if (v.getK2() < 16) {
+ v.setK2(v.getK2() + 1);// V->K2++;
+ }
+ break;
+ case 5:
+ if (v.getK3() >= -16) {
+ v.setK3(v.getK3() - 1);
+ }
+ break;
+ case 6:
+ if (v.getK3() < 16) {
+ v.setK3(v.getK3() + 1);
+ }
+ break;
+ case 7:
+ if (v.getK4() >= -16) {
+ v.setK4(v.getK4() - 1);
+ }
+ break;
+ case 8:
+ if (v.getK4() < 16) {
+ v.setK4(v.getK4() + 1);
+ }
+ break;
+ case 9:
+ if (v.getK5() >= -16) {
+ v.setK5(v.getK5() - 1);
+ }
+ break;
+ case 10:
+ if (v.getK5() < 16) {
+ v.setK5(v.getK5() + 1);
+ }
+ break;
+ }
+ }
+ return ((byte) Ch);
+ }
+
+}
diff --git a/src/com/github/junrar/unpack/UnpackFilter.java b/src/com/github/junrar/unpack/UnpackFilter.java
new file mode 100644
index 0000000..29ed99a
--- /dev/null
+++ b/src/com/github/junrar/unpack/UnpackFilter.java
@@ -0,0 +1,94 @@
+/*
+ * Copyright (c) 2007 innoSysTec (R) GmbH, Germany. All rights reserved.
+ * Original author: Edmund Wagner
+ * Creation date: 01.06.2007
+ *
+ * Source: $HeadURL$
+ * Last changed: $LastChangedDate$
+ *
+ * the unrar licence applies to all junrar source and binary distributions
+ * you are not allowed to use this source to re-create the RAR compression algorithm
+ *
+ * Here some html entities which can be used for escaping javadoc tags:
+ * "&": "&#038;" or "&amp;"
+ * "<": "&#060;" or "&lt;"
+ * ">": "&#062;" or "&gt;"
+ * "@": "&#064;"
+ */
+package com.github.junrar.unpack;
+
+import com.github.junrar.unpack.vm.VMPreparedProgram;
+
+/**
+ * DOCUMENT ME
+ *
+ * @author $LastChangedBy$
+ * @version $LastChangedRevision$
+ */
+public class UnpackFilter {
+
+ private int BlockStart;
+
+ private int BlockLength;
+
+ private int ExecCount;
+
+ private boolean NextWindow;
+
+ // position of parent filter in Filters array used as prototype for filter
+ // in PrgStack array. Not defined for filters in Filters array.
+ private int ParentFilter;
+
+ private VMPreparedProgram Prg = new VMPreparedProgram();
+
+ public int getBlockLength() {
+ return BlockLength;
+ }
+
+ public void setBlockLength(int blockLength) {
+ BlockLength = blockLength;
+ }
+
+ public int getBlockStart() {
+ return BlockStart;
+ }
+
+ public void setBlockStart(int blockStart) {
+ BlockStart = blockStart;
+ }
+
+ public int getExecCount() {
+ return ExecCount;
+ }
+
+ public void setExecCount(int execCount) {
+ ExecCount = execCount;
+ }
+
+ public boolean isNextWindow() {
+ return NextWindow;
+ }
+
+ public void setNextWindow(boolean nextWindow) {
+ NextWindow = nextWindow;
+ }
+
+ public int getParentFilter() {
+ return ParentFilter;
+ }
+
+ public void setParentFilter(int parentFilter) {
+ ParentFilter = parentFilter;
+ }
+
+ public VMPreparedProgram getPrg() {
+ return Prg;
+ }
+
+ public void setPrg(VMPreparedProgram prg) {
+ Prg = prg;
+ }
+
+
+
+}
diff --git a/src/com/github/junrar/unpack/decode/AudioVariables.java b/src/com/github/junrar/unpack/decode/AudioVariables.java
new file mode 100644
index 0000000..7310663
--- /dev/null
+++ b/src/com/github/junrar/unpack/decode/AudioVariables.java
@@ -0,0 +1,144 @@
+/*
+ * Copyright (c) 2007 innoSysTec (R) GmbH, Germany. All rights reserved.
+ * Original author: Edmund Wagner
+ * Creation date: 01.06.2007
+ *
+ * Source: $HeadURL$
+ * Last changed: $LastChangedDate$
+ *
+ * the unrar licence applies to all junrar source and binary distributions
+ * you are not allowed to use this source to re-create the RAR compression algorithm
+ *
+ * Here some html entities which can be used for escaping javadoc tags:
+ * "&": "&#038;" or "&amp;"
+ * "<": "&#060;" or "&lt;"
+ * ">": "&#062;" or "&gt;"
+ * "@": "&#064;"
+ */
+package com.github.junrar.unpack.decode;
+
+/**
+ * DOCUMENT ME
+ *
+ * @author $LastChangedBy$
+ * @version $LastChangedRevision$
+ */
+public class AudioVariables {
+ int k1, k2, k3, k4, k5;
+
+ int d1, d2, d3, d4;
+
+ int lastDelta;
+
+ int dif[] = new int[11];
+
+ int byteCount;
+
+ int lastChar;
+
+ public int getByteCount() {
+ return byteCount;
+ }
+
+ public void setByteCount(int byteCount) {
+ this.byteCount = byteCount;
+ }
+
+ public int getD1() {
+ return d1;
+ }
+
+ public void setD1(int d1) {
+ this.d1 = d1;
+ }
+
+ public int getD2() {
+ return d2;
+ }
+
+ public void setD2(int d2) {
+ this.d2 = d2;
+ }
+
+ public int getD3() {
+ return d3;
+ }
+
+ public void setD3(int d3) {
+ this.d3 = d3;
+ }
+
+ public int getD4() {
+ return d4;
+ }
+
+ public void setD4(int d4) {
+ this.d4 = d4;
+ }
+
+ public int[] getDif() {
+ return dif;
+ }
+
+ public void setDif(int[] dif) {
+ this.dif = dif;
+ }
+
+ public int getK1() {
+ return k1;
+ }
+
+ public void setK1(int k1) {
+ this.k1 = k1;
+ }
+
+ public int getK2() {
+ return k2;
+ }
+
+ public void setK2(int k2) {
+ this.k2 = k2;
+ }
+
+ public int getK3() {
+ return k3;
+ }
+
+ public void setK3(int k3) {
+ this.k3 = k3;
+ }
+
+ public int getK4() {
+ return k4;
+ }
+
+ public void setK4(int k4) {
+ this.k4 = k4;
+ }
+
+ public int getK5() {
+ return k5;
+ }
+
+ public void setK5(int k5) {
+ this.k5 = k5;
+ }
+
+ public int getLastChar() {
+ return lastChar;
+ }
+
+ public void setLastChar(int lastChar) {
+ this.lastChar = lastChar;
+ }
+
+ public int getLastDelta() {
+ return lastDelta;
+ }
+
+ public void setLastDelta(int lastDelta) {
+ this.lastDelta = lastDelta;
+ }
+
+
+}
diff --git a/src/com/github/junrar/unpack/decode/BitDecode.java b/src/com/github/junrar/unpack/decode/BitDecode.java
new file mode 100644
index 0000000..453d90a
--- /dev/null
+++ b/src/com/github/junrar/unpack/decode/BitDecode.java
@@ -0,0 +1,35 @@
+/*
+ * Copyright (c) 2007 innoSysTec (R) GmbH, Germany. All rights reserved.
+ * Original author: Edmund Wagner
+ * Creation date: 01.06.2007
+ *
+ * Source: $HeadURL$
+ * Last changed: $LastChangedDate$
+ *
+ * the unrar licence applies to all junrar source and binary distributions
+ * you are not allowed to use this source to re-create the RAR compression algorithm
+ *
+ * Here some html entities which can be used for escaping javadoc tags:
+ * "&": "&#038;" or "&amp;"
+ * "<": "&#060;" or "&lt;"
+ * ">": "&#062;" or "&gt;"
+ * "@": "&#064;"
+ */
+package com.github.junrar.unpack.decode;
+
+/**
+ * DOCUMENT ME
+ *
+ * @author $LastChangedBy$
+ * @version $LastChangedRevision$
+ */
+public class BitDecode extends Decode
+{
+ /**
+ *
+ */
+ public BitDecode()
+ {
+ decodeNum = new int[Compress.BC];
+ }
+}
diff --git a/src/com/github/junrar/unpack/decode/CodeType.java b/src/com/github/junrar/unpack/decode/CodeType.java
new file mode 100644
index 0000000..047dc0c
--- /dev/null
+++ b/src/com/github/junrar/unpack/decode/CodeType.java
@@ -0,0 +1,29 @@
+/*
+ * Copyright (c) 2007 innoSysTec (R) GmbH, Germany. All rights reserved.
+ * Original author: Edmund Wagner
+ * Creation date: 01.06.2007
+ *
+ * Source: $HeadURL$
+ * Last changed: $LastChangedDate$
+ *
+ * Here some html entities which can be used for escaping javadoc tags:
+ * "&": "&#038;" or "&amp;"
+ * "<": "&#060;" or "&lt;"
+ * ">": "&#062;" or "&gt;"
+ * "@": "&#064;"
+ */
+package com.github.junrar.unpack.decode;
+
+/**
+ * DOCUMENT ME
+ *
+ * the unrar licence applies to all junrar source and binary distributions
+ * you are not allowed to use this source to re-create the RAR compression algorithm
+ *
+ * @author $LastChangedBy$
+ * @version $LastChangedRevision$
+ */
+public enum CodeType {
+ CODE_HUFFMAN,CODE_LZ,CODE_LZ2,CODE_REPEATLZ,CODE_CACHELZ,
+ CODE_STARTFILE,CODE_ENDFILE,CODE_VM,CODE_VMDATA;
+}
diff --git a/src/com/github/junrar/unpack/decode/Compress.java b/src/com/github/junrar/unpack/decode/Compress.java
new file mode 100644
index 0000000..12bf342
--- /dev/null
+++ b/src/com/github/junrar/unpack/decode/Compress.java
@@ -0,0 +1,45 @@
+/*
+ * Copyright (c) 2007 innoSysTec (R) GmbH, Germany. All rights reserved.
+ * Original author: Edmund Wagner
+ * Creation date: 01.06.2007
+ *
+ * Source: $HeadURL$
+ * Last changed: $LastChangedDate$
+ *
+ * the unrar licence applies to all junrar source and binary distributions
+ * you are not allowed to use this source to re-create the RAR compression algorithm
+ *
+ * Here some html entities which can be used for escaping javadoc tags:
+ * "&": "&#038;" or "&amp;"
+ * "<": "&#060;" or "&lt;"
+ * ">": "&#062;" or "&gt;"
+ * "@": "&#064;"
+ */
+package com.github.junrar.unpack.decode;
+
+/**
+ * DOCUMENT ME
+ *
+ * @author $LastChangedBy$
+ * @version $LastChangedRevision$
+ */
+public class Compress {
+ public static final int CODEBUFSIZE = 0x4000;
+ public static final int MAXWINSIZE = 0x400000;
+ public static final int MAXWINMASK = (MAXWINSIZE-1);
+
+ public static final int LOW_DIST_REP_COUNT = 16;
+
+ public static final int NC = 299; /* alphabet = {0, 1, 2, ..., NC - 1} */
+ public static final int DC = 60;
+ public static final int LDC = 17;
+ public static final int RC = 28;
+ public static final int HUFF_TABLE_SIZE = (NC+DC+RC+LDC);
+ public static final int BC = 20;
+
+ public static final int NC20 = 298; /* alphabet = {0, 1, 2, ..., NC - 1} */
+ public static final int DC20 = 48;
+ public static final int RC20 = 28;
+ public static final int BC20 = 19;
+ public static final int MC20 = 257;
+}
diff --git a/src/com/github/junrar/unpack/decode/Decode.java b/src/com/github/junrar/unpack/decode/Decode.java
new file mode 100644
index 0000000..2d1b9b6
--- /dev/null
+++ b/src/com/github/junrar/unpack/decode/Decode.java
@@ -0,0 +1,81 @@
+/*
+ * Copyright (c) 2007 innoSysTec (R) GmbH, Germany. All rights reserved.
+ * Original author: Edmund Wagner
+ * Creation date: 01.06.2007
+ *
+ * Source: $HeadURL$
+ * Last changed: $LastChangedDate$
+ *
+ * the unrar licence applies to all junrar source and binary distributions
+ * you are not allowed to use this source to re-create the RAR compression algorithm
+ *
+ * Here some html entities which can be used for escaping javadoc tags:
+ * "&": "&#038;" or "&amp;"
+ * "<": "&#060;" or "&lt;"
+ * ">": "&#062;" or "&gt;"
+ * "@": "&#064;"
+ */
+package com.github.junrar.unpack.decode;
+
+/**
+ * Used to store information for lz decoding
+ *
+ * @author $LastChangedBy$
+ * @version $LastChangedRevision$
+ */
+public class Decode
+{
+ private int maxNum;
+
+ private final int[] decodeLen = new int[16];
+
+ private final int[] decodePos = new int[16];
+
+ protected int[] decodeNum = new int[2];
+
+ /**
+ * returns the decode Length array
+ * @return decodeLength
+ */
+ public int[] getDecodeLen()
+ {
+ return decodeLen;
+ }
+
+ /**
+ * returns the decode num array
+ * @return decodeNum
+ */
+ public int[] getDecodeNum()
+ {
+ return decodeNum;
+ }
+
+ /**
+ * returns the decodePos array
+ * @return decodePos
+ */
+ public int[] getDecodePos()
+ {
+ return decodePos;
+ }
+
+ /**
+ * returns the max num
+ * @return maxNum
+ */
+ public int getMaxNum()
+ {
+ return maxNum;
+ }
+
+ /**
+ * sets the max num
+ * @param maxNum to be set to maxNum
+ */
+ public void setMaxNum(int maxNum)
+ {
+ this.maxNum = maxNum;
+ }
+
+}
diff --git a/src/com/github/junrar/unpack/decode/DistDecode.java b/src/com/github/junrar/unpack/decode/DistDecode.java
new file mode 100644
index 0000000..d52d767
--- /dev/null
+++ b/src/com/github/junrar/unpack/decode/DistDecode.java
@@ -0,0 +1,37 @@
+/*
+ * Copyright (c) 2007 innoSysTec (R) GmbH, Germany. All rights reserved.
+ * Original author: Edmund Wagner
+ * Creation date: 01.06.2007
+ *
+ * Source: $HeadURL$
+ * Last changed: $LastChangedDate$
+ *
+ * the unrar licence applies to all junrar source and binary distributions
+ * you are not allowed to use this source to re-create the RAR compression algorithm
+ *
+ * Here some html entities which can be used for escaping javadoc tags:
+ * "&": "&#038;" or "&amp;"
+ * "<": "&#060;" or "&lt;"
+ * ">": "&#062;" or "&gt;"
+ * "@": "&#064;"
+ */
+package com.github.junrar.unpack.decode;
+
+/**
+ * DOCUMENT ME
+ *
+ * @author $LastChangedBy$
+ * @version $LastChangedRevision$
+ */
+public class DistDecode extends Decode
+{
+
+ /**
+ *
+ */
+ public DistDecode()
+ {
+ decodeNum = new int[Compress.DC];
+ }
+
+}
diff --git a/src/com/github/junrar/unpack/decode/FilterType.java b/src/com/github/junrar/unpack/decode/FilterType.java
new file mode 100644
index 0000000..d0cbfcc
--- /dev/null
+++ b/src/com/github/junrar/unpack/decode/FilterType.java
@@ -0,0 +1,30 @@
+/*
+ * Copyright (c) 2007 innoSysTec (R) GmbH, Germany. All rights reserved.
+ * Original author: Edmund Wagner
+ * Creation date: 01.06.2007
+ *
+ * Source: $HeadURL$
+ * Last changed: $LastChangedDate$
+ *
+ * the unrar licence applies to all junrar source and binary distributions
+ * you are not allowed to use this source to re-create the RAR compression algorithm
+ *
+ * Here some html entities which can be used for escaping javadoc tags:
+ * "&": "&#038;" or "&amp;"
+ * "<": "&#060;" or "&lt;"
+ * ">": "&#062;" or "&gt;"
+ * "@": "&#064;"
+ */
+package com.github.junrar.unpack.decode;
+
+/**
+ * DOCUMENT ME
+ *
+ * @author $LastChangedBy$
+ * @version $LastChangedRevision$
+ */
+public enum FilterType {
+ FILTER_NONE, FILTER_PPM /*dummy*/, FILTER_E8, FILTER_E8E9,
+ FILTER_UPCASETOLOW, FILTER_AUDIO, FILTER_RGB, FILTER_DELTA,
+ FILTER_ITANIUM, FILTER_E8E9V2;
+}
diff --git a/src/com/github/junrar/unpack/decode/LitDecode.java b/src/com/github/junrar/unpack/decode/LitDecode.java
new file mode 100644
index 0000000..563566f
--- /dev/null
+++ b/src/com/github/junrar/unpack/decode/LitDecode.java
@@ -0,0 +1,36 @@
+/*
+ * Copyright (c) 2007 innoSysTec (R) GmbH, Germany. All rights reserved.
+ * Original author: Edmund Wagner
+ * Creation date: 01.06.2007
+ *
+ * Source: $HeadURL$
+ * Last changed: $LastChangedDate$
+ *
+ * the unrar licence applies to all junrar source and binary distributions
+ * you are not allowed to use this source to re-create the RAR compression algorithm
+ *
+ * Here some html entities which can be used for escaping javadoc tags:
+ * "&": "&#038;" or "&amp;"
+ * "<": "&#060;" or "&lt;"
+ * ">": "&#062;" or "&gt;"
+ * "@": "&#064;"
+ */
+package com.github.junrar.unpack.decode;
+
+/**
+ * DOCUMENT ME
+ *
+ * @author $LastChangedBy$
+ * @version $LastChangedRevision$
+ */
+public class LitDecode extends Decode
+{
+ /**
+ *
+ */
+ public LitDecode()
+ {
+ decodeNum = new int[Compress.NC];
+ }
+
+}
diff --git a/src/com/github/junrar/unpack/decode/LowDistDecode.java b/src/com/github/junrar/unpack/decode/LowDistDecode.java
new file mode 100644
index 0000000..837eb77
--- /dev/null
+++ b/src/com/github/junrar/unpack/decode/LowDistDecode.java
@@ -0,0 +1,37 @@
+/*
+ * Copyright (c) 2007 innoSysTec (R) GmbH, Germany. All rights reserved.
+ * Original author: Edmund Wagner
+ * Creation date: 01.06.2007
+ *
+ * Source: $HeadURL$
+ * Last changed: $LastChangedDate$
+ *
+ * the unrar licence applies to all junrar source and binary distributions
+ * you are not allowed to use this source to re-create the RAR compression algorithm
+ *
+ * Here some html entities which can be used for escaping javadoc tags:
+ * "&": "&#038;" or "&amp;"
+ * "<": "&#060;" or "&lt;"
+ * ">": "&#062;" or "&gt;"
+ * "@": "&#064;"
+ */
+package com.github.junrar.unpack.decode;
+
+/**
+ * DOCUMENT ME
+ *
+ * @author $LastChangedBy$
+ * @version $LastChangedRevision$
+ */
+public class LowDistDecode extends Decode
+{
+
+ /**
+ *
+ */
+ public LowDistDecode()
+ {
+ decodeNum = new int[Compress.LDC];
+ }
+
+}
diff --git a/src/com/github/junrar/unpack/decode/MultDecode.java b/src/com/github/junrar/unpack/decode/MultDecode.java
new file mode 100644
index 0000000..95db9cf
--- /dev/null
+++ b/src/com/github/junrar/unpack/decode/MultDecode.java
@@ -0,0 +1,37 @@
+/*
+ * Copyright (c) 2007 innoSysTec (R) GmbH, Germany. All rights reserved.
+ * Original author: Edmund Wagner
+ * Creation date: 01.06.2007
+ *
+ * Source: $HeadURL$
+ * Last changed: $LastChangedDate$
+ *
+ * the unrar licence applies to all junrar source and binary distributions
+ * you are not allowed to use this source to re-create the RAR compression algorithm
+ *
+ * Here some html entities which can be used for escaping javadoc tags:
+ * "&": "&#038;" or "&amp;"
+ * "<": "&#060;" or "&lt;"
+ * ">": "&#062;" or "&gt;"
+ * "@": "&#064;"
+ */
+package com.github.junrar.unpack.decode;
+
+/**
+ * DOCUMENT ME
+ *
+ * @author $LastChangedBy$
+ * @version $LastChangedRevision$
+ */
+public class MultDecode extends Decode
+{
+
+ /**
+ *
+ */
+ public MultDecode()
+ {
+ decodeNum = new int[Compress.MC20];
+ }
+
+}
diff --git a/src/com/github/junrar/unpack/decode/RepDecode.java b/src/com/github/junrar/unpack/decode/RepDecode.java
new file mode 100644
index 0000000..02f7ef4
--- /dev/null
+++ b/src/com/github/junrar/unpack/decode/RepDecode.java
@@ -0,0 +1,36 @@
+/*
+ * Copyright (c) 2007 innoSysTec (R) GmbH, Germany. All rights reserved.
+ * Original author: Edmund Wagner
+ * Creation date: 01.06.2007
+ *
+ * Source: $HeadURL$
+ * Last changed: $LastChangedDate$
+ *
+ * the unrar licence applies to all junrar source and binary distributions
+ * you are not allowed to use this source to re-create the RAR compression algorithm
+ *
+ * Here some html entities which can be used for escaping javadoc tags:
+ * "&": "&#038;" or "&amp;"
+ * "<": "&#060;" or "&lt;"
+ * ">": "&#062;" or "&gt;"
+ * "@": "&#064;"
+ */
+package com.github.junrar.unpack.decode;
+
+/**
+ * DOCUMENT ME
+ *
+ * @author $LastChangedBy$
+ * @version $LastChangedRevision$
+ */
+public class RepDecode extends Decode
+{
+ /**
+ *
+ */
+ public RepDecode()
+ {
+ decodeNum = new int[Compress.RC];
+ }
+
+}
diff --git a/src/com/github/junrar/unpack/ppm/AnalyzeHeapDump.java b/src/com/github/junrar/unpack/ppm/AnalyzeHeapDump.java
new file mode 100644
index 0000000..634fc92
--- /dev/null
+++ b/src/com/github/junrar/unpack/ppm/AnalyzeHeapDump.java
@@ -0,0 +1,94 @@
+package com.github.junrar.unpack.ppm;
+
+import java.io.BufferedInputStream;
+import java.io.File;
+import java.io.FileInputStream;
+import java.io.IOException;
+import java.io.InputStream;
+
+/**
+ * For debugging purposes only.
+ *
+ * @author alban
+ */
+public class AnalyzeHeapDump {
+
+ /** Creates a new instance of AnalyzeHeapDump */
+ public AnalyzeHeapDump() {
+ }
+
+ public static void main(String[] argv) {
+ File cfile = new File("P:\\test\\heapdumpc");
+ File jfile = new File("P:\\test\\heapdumpj");
+ if (!cfile.exists()) {
+ System.err.println("File not found: " + cfile.getAbsolutePath());
+ return;
+ }
+ if (!jfile.exists()) {
+ System.err.println("File not found: " + jfile.getAbsolutePath());
+ return;
+ }
+ long clen = cfile.length();
+ long jlen = jfile.length();
+ if (clen != jlen) {
+ System.out.println("File size mismatch");
+ System.out.println("clen = " + clen);
+ System.out.println("jlen = " + jlen);
+ }
+ // Do byte comparison
+ long len = Math.min(clen, jlen);
+ InputStream cin = null;
+ InputStream jin = null;
+ int bufferLen = 256*1024;
+ try {
+ cin = new BufferedInputStream(
+ new FileInputStream(cfile), bufferLen);
+ jin = new BufferedInputStream(
+ new FileInputStream(jfile), bufferLen);
+ boolean matching = true;
+ boolean mismatchFound = false;
+ long startOff = 0L;
+ long off = 0L;
+ while (off < len) {
+ if (cin.read() != jin.read()) {
+ if (matching) {
+ startOff = off;
+ matching = false;
+ mismatchFound = true;
+ }
+ }
+ else { // match
+ if (!matching) {
+ printMismatch(startOff, off);
+ matching = true;
+ }
+ }
+ off++;
+ }
+ if (!matching) {
+ printMismatch(startOff, off);
+ }
+ if (!mismatchFound) {
+ System.out.println("Files are identical");
+ }
+ System.out.println("Done");
+ }
+ catch (IOException e) {
+ e.printStackTrace();
+ }
+ finally {
+ try {
+ cin.close();
+ jin.close();
+ } catch (IOException e) {
+ e.printStackTrace();
+ }
+ }
+ }
+
+ private static void printMismatch(long startOff, long bytesRead) {
+ System.out.println("Mismatch: off=" + startOff +
+ "(0x" + Long.toHexString(startOff) +
+ "), len=" + (bytesRead - startOff));
+ }
+}
diff --git a/src/com/github/junrar/unpack/ppm/BlockTypes.java b/src/com/github/junrar/unpack/ppm/BlockTypes.java
new file mode 100644
index 0000000..ffe7c61
--- /dev/null
+++ b/src/com/github/junrar/unpack/ppm/BlockTypes.java
@@ -0,0 +1,58 @@
+/*
+ * Copyright (c) 2007 innoSysTec (R) GmbH, Germany. All rights reserved.
+ * Original author: Edmund Wagner
+ * Creation date: 01.06.2007
+ *
+ * Source: $HeadURL$
+ * Last changed: $LastChangedDate$
+ *
+ * the unrar licence applies to all junrar source and binary distributions
+ * you are not allowed to use this source to re-create the RAR compression algorithm
+ *
+ * Here some html entities which can be used for escaping javadoc tags:
+ * "&": "&#038;" or "&amp;"
+ * "<": "&#060;" or "&lt;"
+ * ">": "&#062;" or "&gt;"
+ * "@": "&#064;"
+ */
+package com.github.junrar.unpack.ppm;
+
+
+/**
+ * DOCUMENT ME
+ *
+ * @author $LastChangedBy$
+ * @version $LastChangedRevision$
+ */
+public enum BlockTypes
+{
+ BLOCK_LZ(0), BLOCK_PPM(1);
+
+ private int blockType;
+
+ private BlockTypes(int blockType)
+ {
+ this.blockType = blockType;
+ }
+
+ public int getBlockType()
+ {
+ return blockType;
+ }
+
+ public boolean equals(int blockType)
+ {
+ return this.blockType == blockType;
+ }
+
+ public static BlockTypes findBlockType(int blockType)
+ {
+ if (BLOCK_LZ.equals(blockType)) {
+ return BLOCK_LZ;
+ }
+ if (BLOCK_PPM.equals(blockType)) {
+ return BLOCK_PPM;
+ }
+ return null;
+ }
+}
diff --git a/src/com/github/junrar/unpack/ppm/FreqData.java b/src/com/github/junrar/unpack/ppm/FreqData.java
new file mode 100644
index 0000000..4308a85
--- /dev/null
+++ b/src/com/github/junrar/unpack/ppm/FreqData.java
@@ -0,0 +1,87 @@
+/*
+ * Copyright (c) 2007 innoSysTec (R) GmbH, Germany. All rights reserved.
+ * Original author: Edmund Wagner
+ * Creation date: 04.06.2007
+ *
+ * Source: $HeadURL$
+ * Last changed: $LastChangedDate$
+ *
+ * the unrar licence applies to all junrar source and binary distributions
+ * you are not allowed to use this source to re-create the RAR compression algorithm
+ *
+ * Here some html entities which can be used for escaping javadoc tags:
+ * "&": "&#038;" or "&amp;"
+ * "<": "&#060;" or "&lt;"
+ * ">": "&#062;" or "&gt;"
+ * "@": "&#064;"
+ */
+package com.github.junrar.unpack.ppm;
+
+import com.github.junrar.io.Raw;
+
+/**
+ * DOCUMENT ME
+ *
+ * @author $LastChangedBy$
+ * @version $LastChangedRevision$
+ */
+public class FreqData extends Pointer{
+
+ public static final int size = 6;
+
+// struct FreqData
+// {
+// ushort SummFreq;
+// STATE _PACK_ATTR * Stats;
+// };
+
+ public FreqData(byte[]mem){
+ super(mem);
+ }
+
+ public FreqData init(byte[] mem) {
+ this.mem = mem;
+ pos = 0;
+ return this;
+ }
+
+ public int getSummFreq() {
+ return Raw.readShortLittleEndian(mem, pos)&0xffff;
+ }
+
+ public void setSummFreq(int summFreq) {
+ Raw.writeShortLittleEndian(mem, pos, (short)summFreq);
+ }
+
+ public void incSummFreq(int dSummFreq) {
+ Raw.incShortLittleEndian(mem, pos, dSummFreq);
+ }
+
+ public int getStats() {
+ return Raw.readIntLittleEndian(mem, pos+2);
+ }
+
+ public void setStats(State state) {
+ setStats(state.getAddress());
+ }
+
+ public void setStats(int state) {
+ Raw.writeIntLittleEndian(mem, pos+2, state);
+ }
+
+ public String toString() {
+ StringBuilder buffer = new StringBuilder();
+ buffer.append("FreqData[");
+ buffer.append("\n pos=");
+ buffer.append(pos);
+ buffer.append("\n size=");
+ buffer.append(size);
+ buffer.append("\n summFreq=");
+ buffer.append(getSummFreq());
+ buffer.append("\n stats=");
+ buffer.append(getStats());
+ buffer.append("\n]");
+ return buffer.toString();
+ }
+
+}
diff --git a/src/com/github/junrar/unpack/ppm/ModelPPM.java b/src/com/github/junrar/unpack/ppm/ModelPPM.java
new file mode 100644
index 0000000..25e20bb
--- /dev/null
+++ b/src/com/github/junrar/unpack/ppm/ModelPPM.java
@@ -0,0 +1,696 @@
+/*
+ * Copyright (c) 2007 innoSysTec (R) GmbH, Germany. All rights reserved.
+ * Original author: Edmund Wagner
+ * Creation date: 31.05.2007
+ *
+ * Source: $HeadURL$
+ * Last changed: $LastChangedDate$
+ *
+ * the unrar licence applies to all junrar source and binary distributions
+ * you are not allowed to use this source to re-create the RAR compression algorithm
+ *
+ * Here some html entities which can be used for escaping javadoc tags:
+ * "&": "&#038;" or "&amp;"
+ * "<": "&#060;" or "&lt;"
+ * ">": "&#062;" or "&gt;"
+ * "@": "&#064;"
+ */
+package com.github.junrar.unpack.ppm;
+
+import java.io.IOException;
+import java.util.Arrays;
+
+import com.github.junrar.exception.RarException;
+import com.github.junrar.unpack.Unpack;
+
+
+/**
+ * DOCUMENT ME
+ *
+ * @author $LastChangedBy$
+ * @version $LastChangedRevision$
+ */
+public class ModelPPM
+{
+ public static final int MAX_O = 64; /* maximum allowed model order */
+
+ public static final int INT_BITS = 7;
+
+ public static final int PERIOD_BITS = 7;
+
+ public static final int TOT_BITS = INT_BITS + PERIOD_BITS;
+
+ public static final int INTERVAL = 1 << INT_BITS;
+
+ public static final int BIN_SCALE = 1 << TOT_BITS;
+
+ public static final int MAX_FREQ = 124;
+
+ private SEE2Context[][] SEE2Cont = new SEE2Context[25][16];
+
+ private SEE2Context dummySEE2Cont;
+
+ private PPMContext minContext, medContext, maxContext;
+
+ private State foundState; // found next state transition
+
+ private int numMasked, initEsc, orderFall, maxOrder, runLength, initRL;
+
+ private int[] charMask = new int[256];
+
+ private int[] NS2Indx = new int[256];
+
+ private int[] NS2BSIndx = new int[256];
+
+ private int[] HB2Flag = new int[256];
+
+ // byte EscCount, PrevSuccess, HiBitsFlag;
+ private int escCount, prevSuccess, hiBitsFlag;
+
+ private int[][] binSumm = new int[128][64]; // binary SEE-contexts
+
+ private RangeCoder coder = new RangeCoder();
+
+ private SubAllocator subAlloc = new SubAllocator();
+
+ private static int InitBinEsc[] = { 0x3CDD, 0x1F3F, 0x59BF, 0x48F3,
+ 0x64A1, 0x5ABC, 0x6632, 0x6051 };
+
+ // Temp fields
+ private final State tempState1 = new State(null);
+ private final State tempState2 = new State(null);
+ private final State tempState3 = new State(null);
+ private final State tempState4 = new State(null);
+ private final StateRef tempStateRef1 = new StateRef();
+ private final StateRef tempStateRef2 = new StateRef();
+ private final PPMContext tempPPMContext1 = new PPMContext(null);
+ private final PPMContext tempPPMContext2 = new PPMContext(null);
+ private final PPMContext tempPPMContext3 = new PPMContext(null);
+ private final PPMContext tempPPMContext4 = new PPMContext(null);
+ private final int[] ps = new int[MAX_O];
+
+ public ModelPPM()
+ {
+ minContext = null;
+ maxContext = null;
+ medContext = null;
+ }
+
+ public SubAllocator getSubAlloc()
+ {
+ return subAlloc;
+ }
+
+ private void restartModelRare()
+ {
+ Arrays.fill(charMask, 0);
+ subAlloc.initSubAllocator();
+ initRL = -(maxOrder < 12 ? maxOrder : 12) - 1;
+ int addr = subAlloc.allocContext();
+ minContext.setAddress(addr);
+ maxContext.setAddress(addr);
+ minContext.setSuffix(0);
+ orderFall = maxOrder;
+ minContext.setNumStats(256);
+ minContext.getFreqData().setSummFreq(minContext.getNumStats()+1);
+
+ addr = subAlloc.allocUnits(256 / 2);
+ foundState.setAddress(addr);
+ minContext.getFreqData().setStats(addr);
+
+ State state = new State(subAlloc.getHeap());
+ addr = minContext.getFreqData().getStats();
+ runLength = initRL;
+ prevSuccess = 0;
+ for (int i = 0; i < 256; i++) {
+ state.setAddress(addr + i * State.size);
+ state.setSymbol(i);
+ state.setFreq(1);
+ state.setSuccessor(0);
+ }
+
+ for (int i = 0; i < 128; i++) {
+ for (int k = 0; k < 8; k++) {
+ for (int m = 0; m < 64; m += 8) {
+ binSumm[i][k + m] = BIN_SCALE - InitBinEsc[k] / (i + 2);
+ }
+ }
+ }
+ for (int i = 0; i < 25; i++) {
+ for (int k = 0; k < 16; k++) {
+ SEE2Cont[i][k].init(5 * i + 10);
+ }
+ }
+ }
+
+ private void startModelRare(int MaxOrder)
+ {
+ int i, k, m, Step;
+ escCount = 1;
+ this.maxOrder = MaxOrder;
+ restartModelRare();
+ // Bug Fixed
+ NS2BSIndx[0] = 0;
+ NS2BSIndx[1] = 2;
+ for (int j = 0; j < 9; j++) {
+ NS2BSIndx[2 + j] = 4;
+ }
+ for (int j = 0; j < 256 - 11; j++) {
+ NS2BSIndx[11 + j] = 6;
+ }
+ for (i = 0; i < 3; i++) {
+ NS2Indx[i] = i;
+ }
+ for (m = i, k = 1, Step = 1; i < 256; i++) {
+ NS2Indx[i] = m;
+ if ((--k) == 0) {
+ k = ++Step;
+ m++;
+ }
+ }
+ for (int j = 0; j < 0x40; j++) {
+ HB2Flag[j] = 0;
+ }
+ for (int j = 0; j < 0x100 - 0x40; j++) {
+ HB2Flag[0x40 + j] = 0x08;
+ }
+ dummySEE2Cont.setShift(PERIOD_BITS);
+
+ }
+
+ private void clearMask()
+ {
+ escCount = 1;
+ Arrays.fill(charMask, 0);
+ }
+
+ public boolean decodeInit(Unpack unpackRead, int escChar/* ref */)
+ throws IOException, RarException
+ {
+
+ int MaxOrder = unpackRead.getChar() & 0xff;
+ boolean reset = ((MaxOrder & 0x20) != 0);
+
+ int MaxMB = 0;
+ if (reset) {
+ MaxMB = unpackRead.getChar();
+ } else {
+ if (subAlloc.GetAllocatedMemory() == 0) {
+ return (false);
+ }
+ }
+ if ((MaxOrder & 0x40) != 0) {
+ escChar = unpackRead.getChar();
+ unpackRead.setPpmEscChar(escChar);
+ }
+ coder.initDecoder(unpackRead);
+ if (reset) {
+ MaxOrder = (MaxOrder & 0x1f) + 1;
+ if (MaxOrder > 16) {
+ MaxOrder = 16 + (MaxOrder - 16) * 3;
+ }
+ if (MaxOrder == 1) {
+ subAlloc.stopSubAllocator();
+ return (false);
+ }
+ subAlloc.startSubAllocator(MaxMB + 1);
+ minContext = new PPMContext(getHeap());
+ medContext = new PPMContext(getHeap());
+ maxContext = new PPMContext(getHeap());
+ foundState = new State(getHeap());
+ dummySEE2Cont = new SEE2Context();
+ for (int i = 0; i < 25; i++) {
+ for (int j = 0; j < 16; j++) {
+ SEE2Cont[i][j] = new SEE2Context();
+ }
+ }
+ startModelRare(MaxOrder);
+ }
+ return (minContext.getAddress() != 0);
+ }
+
+ public int decodeChar() throws IOException, RarException
+ {
+ // Debug
+ //subAlloc.dumpHeap();
+
+ if (minContext.getAddress() <= subAlloc.getPText()
+ || minContext.getAddress() > subAlloc.getHeapEnd()) {
+ return (-1);
+ }
+
+ if (minContext.getNumStats() != 1) {
+ if (minContext.getFreqData().getStats() <= subAlloc.getPText()
+ || minContext.getFreqData().getStats() > subAlloc.getHeapEnd()) {
+ return (-1);
+ }
+ if (!minContext.decodeSymbol1(this)) {
+ return (-1);
+ }
+ } else {
+ minContext.decodeBinSymbol(this);
+ }
+ coder.decode();
+ while (foundState.getAddress() == 0) {
+ coder.ariDecNormalize();
+ do {
+ orderFall++;
+ minContext.setAddress(minContext.getSuffix());// =MinContext->Suffix;
+ if (minContext.getAddress() <= subAlloc.getPText()
+ || minContext.getAddress() > subAlloc.getHeapEnd()) {
+ return (-1);
+ }
+ } while (minContext.getNumStats() == numMasked);
+ if (!minContext.decodeSymbol2(this)) {
+ return (-1);
+ }
+ coder.decode();
+ }
+ int Symbol = foundState.getSymbol();
+ if ((orderFall == 0) && foundState.getSuccessor() > subAlloc.getPText()) {
+ // MinContext=MaxContext=FoundState->Successor;
+ int addr = foundState.getSuccessor();
+ minContext.setAddress(addr);
+ maxContext.setAddress(addr);
+ } else {
+ updateModel();
+ //this.foundState.setAddress(foundState.getAddress());//TODO just 4 debugging
+ if (escCount == 0) {
+ clearMask();
+ }
+ }
+ coder.ariDecNormalize();// ARI_DEC_NORMALIZE(Coder.code,Coder.low,Coder.range,Coder.UnpackRead);
+ return (Symbol);
+ }
+
+ public SEE2Context[][] getSEE2Cont()
+ {
+ return SEE2Cont;
+ }
+
+ public SEE2Context getDummySEE2Cont()
+ {
+ return dummySEE2Cont;
+ }
+
+ public int getInitRL()
+ {
+ return initRL;
+ }
+
+ public void setEscCount(int escCount)
+ {
+ this.escCount = escCount&0xff;
+ }
+
+ public int getEscCount()
+ {
+ return escCount;
+ }
+
+ public void incEscCount(int dEscCount) {
+ setEscCount(getEscCount() + dEscCount);
+ }
+
+ public int[] getCharMask()
+ {
+ return charMask;
+ }
+
+ public int getNumMasked()
+ {
+ return numMasked;
+ }
+
+ public void setNumMasked(int numMasked)
+ {
+ this.numMasked = numMasked;
+ }
+
+ public void setPrevSuccess(int prevSuccess)
+ {
+ this.prevSuccess = prevSuccess&0xff;
+ }
+
+ public int getInitEsc()
+ {
+ return initEsc;
+ }
+
+ public void setInitEsc(int initEsc)
+ {
+ this.initEsc = initEsc;
+ }
+
+ public void setRunLength(int runLength)
+ {
+ this.runLength = runLength;
+ }
+
+ public int getRunLength()
+ {
+ return runLength;
+ }
+
+ public void incRunLength(int dRunLength) {
+ setRunLength(getRunLength() + dRunLength);
+ }
+
+ public int getPrevSuccess()
+ {
+ return prevSuccess;
+ }
+
+ public int getHiBitsFlag()
+ {
+ return hiBitsFlag;
+ }
+
+ public void setHiBitsFlag(int hiBitsFlag)
+ {
+ this.hiBitsFlag = hiBitsFlag&0xff;
+ }
+
+ public int[][] getBinSumm()
+ {
+ return binSumm;
+ }
+
+ public RangeCoder getCoder()
+ {
+ return coder;
+ }
+
+ public int[] getHB2Flag()
+ {
+ return HB2Flag;
+ }
+
+ public int[] getNS2BSIndx()
+ {
+ return NS2BSIndx;
+ }
+
+ public int[] getNS2Indx()
+ {
+ return NS2Indx;
+ }
+
+ public State getFoundState()
+ {
+ return foundState;
+ }
+
+ public byte[] getHeap()
+ {
+ return subAlloc.getHeap();
+ }
+
+ public int getOrderFall()
+ {
+ return orderFall;
+ }
+
+ private int /* ppmcontext ptr */createSuccessors(boolean Skip,
+ State p1 /* state ptr */) {
+ //State upState = tempState1.init(null);
+ StateRef upState = tempStateRef2;
+ State tempState = tempState1.init(getHeap());
+
+ // PPM_CONTEXT* pc=MinContext, * UpBranch=FoundState->Successor;
+ PPMContext pc = tempPPMContext1.init(getHeap());
+ pc.setAddress(minContext.getAddress());
+ PPMContext upBranch = tempPPMContext2.init(getHeap());
+ upBranch.setAddress(foundState.getSuccessor());
+
+ // STATE * p, * ps[MAX_O], ** pps=ps;
+ State p = tempState2.init(getHeap());
+ int pps = 0;
+
+ boolean noLoop = false;
+
+ if (!Skip) {
+ ps[pps++] = foundState.getAddress();// *pps++ = FoundState;
+ if (pc.getSuffix() == 0) {
+ noLoop = true;
+ }
+ }
+ if (!noLoop) {
+ boolean loopEntry = false;
+ if (p1.getAddress() != 0) {
+ p.setAddress(p1.getAddress());
+ pc.setAddress(pc.getSuffix());// =pc->Suffix;
+ loopEntry = true;
+ }
+ do {
+ if (!loopEntry) {
+ pc.setAddress(pc.getSuffix());// pc=pc->Suffix;
+ if (pc.getNumStats() != 1) {
+ p.setAddress(pc.getFreqData().getStats());// p=pc->U.Stats
+ if (p.getSymbol() != foundState.getSymbol()) {
+ do {
+ p.incAddress();
+ } while (p.getSymbol() != foundState.getSymbol());
+ }
+ } else {
+ p.setAddress(pc.getOneState().getAddress());// p=&(pc->OneState);
+ }
+ }// LOOP_ENTRY:
+ loopEntry = false;
+ if (p.getSuccessor() != upBranch.getAddress()) {
+ pc.setAddress(p.getSuccessor());// =p->Successor;
+ break;
+ }
+ ps[pps++] = p.getAddress();
+ } while (pc.getSuffix() != 0);
+
+ } // NO_LOOP:
+ if (pps == 0) {
+ return pc.getAddress();
+ }
+ upState.setSymbol(getHeap()[upBranch.getAddress()]);// UpState.Symbol=*(byte*)
+ // UpBranch;
+ // UpState.Successor=(PPM_CONTEXT*) (((byte*) UpBranch)+1);
+ upState.setSuccessor(upBranch.getAddress() + 1); //TODO check if +1 necessary
+ if (pc.getNumStats() != 1) {
+ if (pc.getAddress() <= subAlloc.getPText()) {
+ return (0);
+ }
+ p.setAddress(pc.getFreqData().getStats());
+ if (p.getSymbol() != upState.getSymbol()) {
+ do {
+ p.incAddress();
+ } while (p.getSymbol() != upState.getSymbol());
+ }
+ int cf = p.getFreq() - 1;
+ int s0 = pc.getFreqData().getSummFreq() - pc.getNumStats() - cf;
+ // UpState.Freq=1+((2*cf <= s0)?(5*cf > s0):((2*cf+3*s0-1)/(2*s0)));
+ upState.setFreq(1 + ((2 * cf <= s0) ? (5 * cf > s0 ? 1 : 0) :
+ ((2 * cf + 3 * s0 - 1) / (2 * s0))));
+ } else {
+ upState.setFreq(pc.getOneState().getFreq());// UpState.Freq=pc->OneState.Freq;
+ }
+ do {
+ // pc = pc->createChild(this,*--pps,UpState);
+ tempState.setAddress(ps[--pps]);
+ pc.setAddress(pc.createChild(this, tempState, upState));
+ if (pc.getAddress() == 0) {
+ return 0;
+ }
+ } while (pps != 0);
+ return pc.getAddress();
+ }
+
+ private void updateModelRestart()
+ {
+ restartModelRare();
+ escCount = 0;
+ }
+
+ private void updateModel()
+ {
+ //System.out.println("ModelPPM.updateModel()");
+ // STATE fs = *FoundState, *p = NULL;
+ StateRef fs = tempStateRef1;
+ fs.setValues(foundState);
+ State p = tempState3.init(getHeap());
+ State tempState = tempState4.init(getHeap());
+
+ PPMContext pc = tempPPMContext3.init(getHeap());
+ PPMContext successor = tempPPMContext4.init(getHeap());
+
+ int ns1, ns, cf, sf, s0;
+ pc.setAddress(minContext.getSuffix());
+ if (fs.getFreq() < MAX_FREQ / 4 && pc.getAddress() != 0) {
+ if (pc.getNumStats() != 1) {
+ p.setAddress(pc.getFreqData().getStats());
+ if (p.getSymbol() != fs.getSymbol()) {
+ do {
+ p.incAddress();
+ } while (p.getSymbol() != fs.getSymbol());
+ tempState.setAddress(p.getAddress() - State.size);
+ if (p.getFreq() >= tempState.getFreq()) {
+ State.ppmdSwap(p, tempState);
+ p.decAddress();
+ }
+ }
+ if (p.getFreq() < MAX_FREQ - 9) {
+ p.incFreq(2);
+ pc.getFreqData().incSummFreq(2);
+ }
+ } else {
+ p.setAddress(pc.getOneState().getAddress());
+ if (p.getFreq() < 32) {
+ p.incFreq(1);
+ }
+ }
+ }
+ if (orderFall == 0) {
+ foundState.setSuccessor(createSuccessors(true, p));
+ minContext.setAddress(foundState.getSuccessor());
+ maxContext.setAddress(foundState.getSuccessor());
+ if (minContext.getAddress() == 0) {
+ updateModelRestart();
+ return;
+ }
+ return;
+ }
+ subAlloc.getHeap()[subAlloc.getPText()] = (byte)fs.getSymbol();
+ subAlloc.incPText();
+ successor.setAddress(subAlloc.getPText());
+ if (subAlloc.getPText() >= subAlloc.getFakeUnitsStart()) {
+ updateModelRestart();
+ return;
+ }
+// // Debug
+// subAlloc.dumpHeap();
+ if (fs.getSuccessor() != 0) {
+ if (fs.getSuccessor() <= subAlloc.getPText()) {
+ fs.setSuccessor(createSuccessors(false, p));
+ if (fs.getSuccessor() == 0) {
+ updateModelRestart();
+ return;
+ }
+ }
+ if (--orderFall == 0) {
+ successor.setAddress(fs.getSuccessor());
+ if (maxContext.getAddress() != minContext.getAddress()) {
+ subAlloc.decPText(1);
+ }
+ }
+ }
+ else {
+ foundState.setSuccessor(successor.getAddress());
+ fs.setSuccessor(minContext);
+ }
+// // Debug
+// subAlloc.dumpHeap();
+ ns = minContext.getNumStats();
+ s0 = minContext.getFreqData().getSummFreq() - (ns) - (fs.getFreq() - 1);
+ for (pc.setAddress(maxContext.getAddress());
+ pc.getAddress() != minContext.getAddress();
+ pc.setAddress(pc.getSuffix())) {
+ if ((ns1 = pc.getNumStats()) != 1) {
+ if ((ns1 & 1) == 0) {
+ //System.out.println(ns1);
+ pc.getFreqData().setStats(
+ subAlloc.expandUnits(pc.getFreqData().getStats(),
+ ns1 >>> 1));
+ if (pc.getFreqData().getStats() == 0) {
+ updateModelRestart();
+ return;
+ }
+ }
+ // bug fixed
+// int sum = ((2 * ns1 < ns) ? 1 : 0) +
+// 2 * ((4 * ((ns1 <= ns) ? 1 : 0)) & ((pc.getFreqData()
+// .getSummFreq() <= 8 * ns1) ? 1 : 0));
+ int sum = ((2 * ns1 < ns) ? 1 : 0) + 2 * (
+ ((4 * ns1 <= ns) ? 1 : 0) &
+ ((pc.getFreqData().getSummFreq() <= 8 * ns1) ? 1 : 0)
+ );
+ pc.getFreqData().incSummFreq(sum);
+ }
+ else {
+ p.setAddress(subAlloc.allocUnits(1));
+ if (p.getAddress() == 0) {
+ updateModelRestart();
+ return;
+ }
+ p.setValues(pc.getOneState());
+ pc.getFreqData().setStats(p);
+ if (p.getFreq() < MAX_FREQ / 4 - 1) {
+ p.incFreq(p.getFreq());
+ }
+ else {
+ p.setFreq(MAX_FREQ - 4);
+ }
+ pc.getFreqData().setSummFreq(
+ (p.getFreq() + initEsc + (ns > 3 ? 1 : 0)));
+ }
+ cf = 2 * fs.getFreq() * (pc.getFreqData().getSummFreq() + 6);
+ sf = s0 + pc.getFreqData().getSummFreq();
+ if (cf < 6 * sf) {
+ cf = 1 + (cf > sf ? 1 : 0) + (cf >= 4 * sf ? 1 : 0);
+ pc.getFreqData().incSummFreq(3);
+ }
+ else {
+ cf = 4 + (cf >= 9 * sf ? 1 : 0) + (cf >= 12 * sf ? 1 : 0) +
+ (cf >= 15 * sf ? 1 : 0);
+ pc.getFreqData().incSummFreq(cf);
+ }
+ p.setAddress(pc.getFreqData().getStats() + ns1*State.size);
+ p.setSuccessor(successor);
+ p.setSymbol(fs.getSymbol());
+ p.setFreq(cf);
+ pc.setNumStats(++ns1);
+ }
+
+ int address = fs.getSuccessor();
+ maxContext.setAddress(address);
+ minContext.setAddress(address);
+ //TODO-----debug
+// int pos = minContext.getFreqData().getStats();
+// State a = new State(getHeap());
+// a.setAddress(pos);
+// pos+=State.size;
+// a.setAddress(pos);
+ //--dbg end
+ return;
+ }
+
+ // Debug
+ public String toString() {
+ StringBuilder buffer = new StringBuilder();
+ buffer.append("ModelPPM[");
+ buffer.append("\n numMasked=");
+ buffer.append(numMasked);
+ buffer.append("\n initEsc=");
+ buffer.append(initEsc);
+ buffer.append("\n orderFall=");
+ buffer.append(orderFall);
+ buffer.append("\n maxOrder=");
+ buffer.append(maxOrder);
+ buffer.append("\n runLength=");
+ buffer.append(runLength);
+ buffer.append("\n initRL=");
+ buffer.append(initRL);
+ buffer.append("\n escCount=");
+ buffer.append(escCount);
+ buffer.append("\n prevSuccess=");
+ buffer.append(prevSuccess);
+ buffer.append("\n foundState=");
+ buffer.append(foundState);
+ buffer.append("\n coder=");
+ buffer.append(coder);
+ buffer.append("\n subAlloc=");
+ buffer.append(subAlloc);
+ buffer.append("\n]");
+ return buffer.toString();
+ }
+
+ // Debug
+// public void dumpHeap() {
+// subAlloc.dumpHeap();
+// }
+}
diff --git a/src/com/github/junrar/unpack/ppm/PPMContext.java b/src/com/github/junrar/unpack/ppm/PPMContext.java
new file mode 100644
index 0000000..f6e5d67
--- /dev/null
+++ b/src/com/github/junrar/unpack/ppm/PPMContext.java
@@ -0,0 +1,477 @@
+/*
+ * Copyright (c) 2007 innoSysTec (R) GmbH, Germany. All rights reserved.
+ * Original author: Edmund Wagner
+ * Creation date: 31.05.2007
+ *
+ * Source: $HeadURL$
+ * Last changed: $LastChangedDate$
+ *
+ * the unrar licence applies to all junrar source and binary distributions
+ * you are not allowed to use this source to re-create the RAR compression algorithm
+ *
+ * Here some html entities which can be used for escaping javadoc tags:
+ * "&": "&#038;" or "&amp;"
+ * "<": "&#060;" or "&lt;"
+ * ">": "&#062;" or "&gt;"
+ * "@": "&#064;"
+ */
+package com.github.junrar.unpack.ppm;
+
+import com.github.junrar.io.Raw;
+
+/**
+ * DOCUMENT ME
+ *
+ * @author $LastChangedBy$
+ * @version $LastChangedRevision$
+ */
+public class PPMContext extends Pointer
+{
+
+ private static final int unionSize = Math.max(FreqData.size, State.size);
+
+ public static final int size = 2 + unionSize + 4; // 12
+
+ // ushort NumStats;
+ private int numStats; // determines if feqData or onstate is used
+
+ // (1==onestate)
+
+ private final FreqData freqData; // -\
+
+ // |-> union
+ private final State oneState; // -/
+
+ private int suffix; // pointer ppmcontext
+
+ public final static int[] ExpEscape =
+ { 25, 14, 9, 7, 5, 5, 4, 4, 4, 3, 3, 3, 2, 2, 2, 2 };
+
+ // Temp fields
+ private final State tempState1 = new State(null);
+ private final State tempState2 = new State(null);
+ private final State tempState3 = new State(null);
+ private final State tempState4 = new State(null);
+ private final State tempState5 = new State(null);
+ private PPMContext tempPPMContext = null;
+ private final int[] ps = new int[256];
+
+ public PPMContext(byte[] mem)
+ {
+ super(mem);
+ oneState = new State(mem);
+ freqData = new FreqData(mem);
+ }
+
+ public PPMContext init(byte[] mem) {
+ this.mem = mem;
+ pos = 0;
+ oneState.init(mem);
+ freqData.init(mem);
+ return this;
+ }
+
+ public FreqData getFreqData()
+ {
+ return freqData;
+ }
+
+ public void setFreqData(FreqData freqData)
+ {
+ this.freqData.setSummFreq(freqData.getSummFreq());
+ this.freqData.setStats(freqData.getStats());
+ }
+
+ public final int getNumStats()
+ {
+ if (mem!=null){
+ numStats = Raw.readShortLittleEndian(mem, pos)&0xffff;
+ }
+ return numStats;
+ }
+
+ public final void setNumStats(int numStats)
+ {
+ this.numStats = numStats&0xffff;
+ if (mem != null) {
+ Raw.writeShortLittleEndian(mem, pos, (short)numStats);
+ }
+ }
+
+ public State getOneState()
+ {
+ return oneState;
+ }
+
+ public void setOneState(StateRef oneState)
+ {
+ this.oneState.setValues(oneState);
+ }
+
+ public int getSuffix()
+ {
+ if(mem!=null){
+ suffix = Raw.readIntLittleEndian(mem, pos+8);
+ }
+ return suffix;
+ }
+
+ public void setSuffix(PPMContext suffix)
+ {
+ setSuffix(suffix.getAddress());
+ }
+
+ public void setSuffix(int suffix)
+ {
+ this.suffix = suffix;
+ if (mem != null) {
+ Raw.writeIntLittleEndian(mem, pos + 8, suffix);
+ }
+ }
+
+ @Override
+ public void setAddress(int pos)
+ {
+ super.setAddress(pos);
+ oneState.setAddress(pos+2);
+ freqData.setAddress(pos+2);
+ }
+
+ private PPMContext getTempPPMContext(byte[] mem) {
+ if (tempPPMContext == null) {
+ tempPPMContext = new PPMContext(null);
+ }
+ return tempPPMContext.init(mem);
+ }
+
+ public int createChild(ModelPPM model, State pStats/* ptr */,
+ StateRef firstState /* ref */)
+ {
+ PPMContext pc = getTempPPMContext(model.getSubAlloc().getHeap());
+ pc.setAddress(model.getSubAlloc().allocContext());
+ if (pc != null) {
+ pc.setNumStats(1);
+ pc.setOneState(firstState);
+ pc.setSuffix(this);
+ pStats.setSuccessor(pc);
+ }
+ return pc.getAddress();
+ }
+
+ public void rescale(ModelPPM model)
+ {
+ int OldNS = getNumStats(), i = getNumStats() - 1, Adder, EscFreq;
+ // STATE* p1, * p;
+ State p1 = new State(model.getHeap());
+ State p = new State(model.getHeap());
+ State temp = new State(model.getHeap());
+
+ for (p.setAddress(model.getFoundState().getAddress());
+ p.getAddress() != freqData.getStats();
+ p.decAddress()) {
+ temp.setAddress(p.getAddress() - State.size);
+ State.ppmdSwap(p, temp);
+ }
+ temp.setAddress(freqData.getStats());
+ temp.incFreq(4);
+ freqData.incSummFreq(4);
+ EscFreq = freqData.getSummFreq() - p.getFreq();
+ Adder = (model.getOrderFall() != 0) ? 1 : 0;
+ p.setFreq((p.getFreq() + Adder) >>> 1);
+ freqData.setSummFreq(p.getFreq());
+ do {
+ p.incAddress();
+ EscFreq -= p.getFreq();
+ p.setFreq((p.getFreq() + Adder) >>> 1);
+ freqData.incSummFreq(p.getFreq());
+ temp.setAddress(p.getAddress() - State.size);
+ if (p.getFreq() > temp.getFreq()) {
+ p1.setAddress(p.getAddress());
+ StateRef tmp = new StateRef();
+ tmp.setValues(p1);
+ State temp2 = new State(model.getHeap());
+ State temp3 = new State(model.getHeap());
+ do {
+ // p1[0]=p1[-1];
+ temp2.setAddress(p1.getAddress() - State.size);
+ p1.setValues(temp2);
+ p1.decAddress();
+ temp3.setAddress(p1.getAddress() - State.size);
+ } while (p1.getAddress() != freqData.getStats() && tmp.getFreq() > temp3.getFreq());
+ p1.setValues(tmp);
+ }
+ } while (--i != 0);
+ if (p.getFreq() == 0) {
+ do {
+ i++;
+ p.decAddress();
+ } while (p.getFreq() == 0);
+ EscFreq += i;
+ setNumStats(getNumStats() - i);
+ if (getNumStats() == 1) {
+ StateRef tmp = new StateRef();
+ temp.setAddress(freqData.getStats());
+ tmp.setValues(temp);
+ // STATE tmp=*U.Stats;
+ do {
+ // tmp.Freq-=(tmp.Freq >> 1)
+ tmp.decFreq(tmp.getFreq() >>> 1);
+ EscFreq >>>= 1;
+ } while (EscFreq > 1);
+ model.getSubAlloc().freeUnits(freqData.getStats(),(OldNS + 1) >>> 1);
+ oneState.setValues(tmp);
+ model.getFoundState().setAddress(oneState.getAddress());
+ return;
+ }
+ }
+ EscFreq -= EscFreq >>> 1;
+ freqData.incSummFreq(EscFreq);
+ int n0 = (OldNS + 1) >>> 1, n1 = (getNumStats() + 1) >>> 1;
+ if (n0 != n1) {
+ freqData.setStats(model.getSubAlloc().shrinkUnits(freqData.getStats(), n0, n1));
+ }
+ model.getFoundState().setAddress(freqData.getStats());
+ }
+
+ private int getArrayIndex(ModelPPM Model, State rs)
+ {
+ PPMContext tempSuffix = getTempPPMContext(Model.getSubAlloc().getHeap());
+ tempSuffix.setAddress(getSuffix());
+ int ret = 0;
+ ret += Model.getPrevSuccess();
+ ret += Model.getNS2BSIndx()[tempSuffix.getNumStats() - 1];
+ ret += Model.getHiBitsFlag() + 2* Model.getHB2Flag()[rs.getSymbol()];
+ ret += ((Model.getRunLength() >>> 26) & 0x20);
+ return ret;
+ }
+
+ public int getMean(int summ, int shift, int round)
+ {
+ return ( (summ + (1 << (shift - round) ) ) >>> (shift) );
+ }
+
+ public void decodeBinSymbol(ModelPPM model)
+ {
+ State rs = tempState1.init(model.getHeap());
+ rs.setAddress(oneState.getAddress());// State&
+ model.setHiBitsFlag(model.getHB2Flag()[model.getFoundState().getSymbol()]);
+ int off1 = rs.getFreq() - 1;
+ int off2 = getArrayIndex(model, rs);
+ int bs = model.getBinSumm()[off1][off2];
+ if (model.getCoder().getCurrentShiftCount(ModelPPM.TOT_BITS) < bs) {
+ model.getFoundState().setAddress(rs.getAddress());
+ rs.incFreq((rs.getFreq() < 128) ? 1 : 0);
+ model.getCoder().getSubRange().setLowCount(0);
+ model.getCoder().getSubRange().setHighCount(bs);
+ bs = ((bs + ModelPPM.INTERVAL - getMean(bs, ModelPPM.PERIOD_BITS, 2)) & 0xffff);
+ model.getBinSumm()[off1][off2] = bs;
+ model.setPrevSuccess(1);
+ model.incRunLength(1);
+ } else {
+ model.getCoder().getSubRange().setLowCount(bs);
+ bs = (bs - getMean(bs, ModelPPM.PERIOD_BITS, 2)) & 0xFFFF;
+ model.getBinSumm()[off1][off2] = bs;
+ model.getCoder().getSubRange().setHighCount(ModelPPM.BIN_SCALE);
+ model.setInitEsc(ExpEscape[bs >>> 10]);
+ model.setNumMasked(1);
+ model.getCharMask()[rs.getSymbol()] = model.getEscCount();
+ model.setPrevSuccess(0);
+ model.getFoundState().setAddress(0);
+ }
+ //int a = 0;//TODO just 4 debugging
+ }
+
+// public static void ppmdSwap(ModelPPM model, StatePtr state1, StatePtr state2)
+// {
+// byte[] bytes = model.getSubAlloc().getHeap();
+// int p1 = state1.getAddress();
+// int p2 = state2.getAddress();
+//
+// for (int i = 0; i < StatePtr.size; i++) {
+// byte temp = bytes[p1+i];
+// bytes[p1+i] = bytes[p2+i];
+// bytes[p2+i] = temp;
+// }
+// state1.setAddress(p1);
+// state2.setAddress(p2);
+// }
+
+ public void update1(ModelPPM model, int p/* ptr */)
+ {
+ model.getFoundState().setAddress(p);
+ model.getFoundState().incFreq(4);
+ freqData.incSummFreq(4);
+ State p0 = tempState3.init(model.getHeap());
+ State p1 = tempState4.init(model.getHeap());
+ p0.setAddress(p);
+ p1.setAddress(p - State.size);
+ if (p0.getFreq() > p1.getFreq()) {
+ State.ppmdSwap(p0, p1);
+ model.getFoundState().setAddress(p1.getAddress());
+ if (p1.getFreq() > ModelPPM.MAX_FREQ)
+ rescale(model);
+ }
+ }
+
+ public boolean decodeSymbol2(ModelPPM model)
+ {
+ long count;
+ int hiCnt, i = getNumStats() - model.getNumMasked();
+ SEE2Context psee2c = makeEscFreq2(model, i);
+ RangeCoder coder = model.getCoder();
+ // STATE* ps[256], ** pps=ps, * p=U.Stats-1;
+ State p = tempState1.init(model.getHeap());
+ State temp = tempState2.init(model.getHeap());
+ p.setAddress(freqData.getStats() - State.size);
+ int pps = 0;
+ hiCnt = 0;
+
+ do {
+ do {
+ p.incAddress();// p++;
+ } while (model.getCharMask()[p.getSymbol()] == model.getEscCount());
+ hiCnt += p.getFreq();
+ ps[pps++] = p.getAddress();
+ } while (--i != 0);
+ coder.getSubRange().incScale(hiCnt);
+ count = coder.getCurrentCount();
+ if (count >= coder.getSubRange().getScale()) {
+ return false;
+ }
+ pps = 0;
+ p.setAddress(ps[pps]);
+ if (count < hiCnt) {
+ hiCnt = 0;
+ while ((hiCnt += p.getFreq()) <= count) {
+ p.setAddress(ps[++pps]);// p=*++pps;
+ }
+ coder.getSubRange().setHighCount(hiCnt);
+ coder.getSubRange().setLowCount(hiCnt - p.getFreq());
+ psee2c.update();
+ update2(model, p.getAddress());
+ } else {
+ coder.getSubRange().setLowCount(hiCnt);
+ coder.getSubRange().setHighCount(coder.getSubRange().getScale());
+ i = getNumStats() - model.getNumMasked();// ->NumMasked;
+ pps--;
+ do {
+ temp.setAddress(ps[++pps]);// (*++pps)
+ model.getCharMask()[temp.getSymbol()] = model.getEscCount();
+ } while (--i != 0);
+ psee2c.incSumm((int)coder.getSubRange().getScale());
+ model.setNumMasked(getNumStats());
+ }
+ return (true);
+ }
+
+ public void update2(ModelPPM model, int p/* state ptr */)
+ {
+ State temp = tempState5.init(model.getHeap());
+ temp.setAddress(p);
+ model.getFoundState().setAddress(p);
+ model.getFoundState().incFreq(4);
+ freqData.incSummFreq(4);
+ if (temp.getFreq() > ModelPPM.MAX_FREQ) {
+ rescale(model);
+ }
+ model.incEscCount(1);
+ model.setRunLength(model.getInitRL());
+ }
+
+ private SEE2Context makeEscFreq2(ModelPPM model, int Diff)
+ {
+ SEE2Context psee2c;
+ int numStats = getNumStats();
+ if (numStats != 256) {
+ PPMContext suff = getTempPPMContext(model.getHeap());
+ suff.setAddress(getSuffix());
+ int idx1 = model.getNS2Indx()[Diff - 1];
+ int idx2 = 0;
+ idx2 += (Diff < suff.getNumStats() - numStats) ? 1 : 0;
+ idx2 += 2 * ((freqData.getSummFreq() < 11 * numStats) ? 1 : 0);
+ idx2 += 4 * ((model.getNumMasked() > Diff) ? 1 : 0);
+ idx2 += model.getHiBitsFlag();
+ psee2c = model.getSEE2Cont()[idx1][idx2];
+ model.getCoder().getSubRange().setScale(psee2c.getMean());
+ } else {
+ psee2c = model.getDummySEE2Cont();
+ model.getCoder().getSubRange().setScale(1);
+ }
+ return psee2c;
+ }
+
+ public boolean decodeSymbol1(ModelPPM model)
+ {
+
+ RangeCoder coder = model.getCoder();
+ coder.getSubRange().setScale(freqData.getSummFreq());
+ State p = new State(model.getHeap());
+ p.setAddress(freqData.getStats());
+ int i, HiCnt;
+ long count = coder.getCurrentCount();
+ if (count >= coder.getSubRange().getScale()) {
+ return false;
+ }
+ if (count < (HiCnt = p.getFreq())) {
+ coder.getSubRange().setHighCount(HiCnt);
+ model.setPrevSuccess((2 * HiCnt > coder.getSubRange().getScale()) ? 1 : 0);
+ model.incRunLength(model.getPrevSuccess());
+ HiCnt += 4;
+ model.getFoundState().setAddress(p.getAddress());
+ model.getFoundState().setFreq(HiCnt);
+ freqData.incSummFreq(4);
+ if (HiCnt > ModelPPM.MAX_FREQ) {
+ rescale(model);
+ }
+ coder.getSubRange().setLowCount(0);
+ return true;
+ } else {
+ if (model.getFoundState().getAddress() == 0) {
+ return (false);
+ }
+ }
+ model.setPrevSuccess(0);
+ int numStats = getNumStats();
+ i = numStats - 1;
+ while ((HiCnt += p.incAddress().getFreq()) <= count)
+ {
+ if (--i == 0) {
+ model.setHiBitsFlag(model.getHB2Flag()[model.getFoundState().getSymbol()]);
+ coder.getSubRange().setLowCount(HiCnt);
+ model.getCharMask()[p.getSymbol()] = model.getEscCount();
+ model.setNumMasked(numStats);
+ i = numStats - 1;
+ model.getFoundState().setAddress(0);
+ do {
+ model.getCharMask()[p.decAddress().getSymbol()] = model.getEscCount();
+ } while (--i != 0);
+ coder.getSubRange().setHighCount(coder.getSubRange().getScale());
+ return (true);
+ }
+ }
+ coder.getSubRange().setLowCount(HiCnt-p.getFreq());
+ coder.getSubRange().setHighCount(HiCnt);
+ update1(model, p.getAddress());
+ return (true);
+ }
+
+ public String toString() {
+ StringBuilder buffer = new StringBuilder();
+ buffer.append("PPMContext[");
+ buffer.append("\n pos=");
+ buffer.append(pos);
+ buffer.append("\n size=");
+ buffer.append(size);
+ buffer.append("\n numStats=");
+ buffer.append(getNumStats());
+ buffer.append("\n Suffix=");
+ buffer.append(getSuffix());
+ buffer.append("\n freqData=");
+ buffer.append(freqData);
+ buffer.append("\n oneState=");
+ buffer.append(oneState);
+ buffer.append("\n]");
+ return buffer.toString();
+ }
+
+}
diff --git a/src/com/github/junrar/unpack/ppm/Pointer.java b/src/com/github/junrar/unpack/ppm/Pointer.java
new file mode 100644
index 0000000..c206b9d
--- /dev/null
+++ b/src/com/github/junrar/unpack/ppm/Pointer.java
@@ -0,0 +1,59 @@
+/*
+ * Copyright (c) 2007 innoSysTec (R) GmbH, Germany. All rights reserved.
+ * Original author: Edmund Wagner
+ * Creation date: 14.06.2007
+ *
+ * Source: $HeadURL$
+ * Last changed: $LastChangedDate$
+ *
+ * the unrar licence applies to all junrar source and binary distributions
+ * you are not allowed to use this source to re-create the RAR compression algorithm
+ *
+ * Here some html entities which can be used for escaping javadoc tags:
+ * "&": "&#038;" or "&amp;"
+ * "<": "&#060;" or "&lt;"
+ * ">": "&#062;" or "&gt;"
+ * "@": "&#064;"
+ */
+package com.github.junrar.unpack.ppm;
+
+/**
+ * Simulates Pointers on a single mem block as a byte[]
+ *
+ * @author $LastChangedBy$
+ * @version $LastChangedRevision$
+ */
+public abstract class Pointer
+{
+ protected byte[] mem;
+ protected int pos;
+
+ /**
+ * Initialize the object with the array (may be null)
+ * @param mem the byte array
+ */
+ public Pointer(byte[] mem){
+ this.mem = mem;
+ }
+ /**
+ * returns the position of this object in the byte[]
+ * @return the address of this object
+ */
+ public int getAddress(){
+ assert (mem != null);
+ return pos;
+ }
+
+ /**
+ * needs to set the fields of this object to the values in the byte[]
+ * at the given position.
+ * be aware of the byte order
+ * @param pos the position this object should point to
+ * @return true if the address could be set
+ */
+ public void setAddress(int pos) {
+ assert (mem != null);
+ assert (pos >= 0) && (pos < mem.length) : pos;
+ this.pos = pos;
+ }
+}
diff --git a/src/com/github/junrar/unpack/ppm/RangeCoder.java b/src/com/github/junrar/unpack/ppm/RangeCoder.java
new file mode 100644
index 0000000..734813f
--- /dev/null
+++ b/src/com/github/junrar/unpack/ppm/RangeCoder.java
@@ -0,0 +1,177 @@
+/*
+ * Copyright (c) 2007 innoSysTec (R) GmbH, Germany. All rights reserved.
+ * Original author: Edmund Wagner
+ * Creation date: 31.05.2007
+ *
+ * Source: $HeadURL$
+ * Last changed: $LastChangedDate$
+ *
+ * the unrar licence applies to all junrar source and binary distributions
+ * you are not allowed to use this source to re-create the RAR compression algorithm
+ *
+ * Here some html entities which can be used for escaping javadoc tags:
+ * "&": "&#038;" or "&amp;"
+ * "<": "&#060;" or "&lt;"
+ * ">": "&#062;" or "&gt;"
+ * "@": "&#064;"
+ */
+package com.github.junrar.unpack.ppm;
+
+import java.io.IOException;
+
+import com.github.junrar.exception.RarException;
+import com.github.junrar.unpack.Unpack;
+
+
+/**
+ * DOCUMENT ME
+ *
+ * @author $LastChangedBy$
+ * @version $LastChangedRevision$
+ */
+public class RangeCoder
+{
+ public static final int TOP = 1 << 24;
+
+ public static final int BOT = 1 << 15;
+
+ private static final long uintMask = 0xFFFFffffL;
+
+ // uint low, code, range;
+ private long low, code, range;
+
+ private final SubRange subRange = new SubRange();
+
+ private Unpack unpackRead;
+
+ public SubRange getSubRange()
+ {
+ return subRange;
+ }
+
+ public void initDecoder(Unpack unpackRead) throws IOException, RarException
+ {
+ this.unpackRead = unpackRead;
+
+ low = code = 0L;
+ range = 0xFFFFffffL;
+ for (int i = 0; i < 4; i++) {
+ code = ((code << 8) | getChar())&uintMask;
+ }
+ }
+
+ public int getCurrentCount()
+ {
+ range = (range / subRange.getScale())&uintMask;
+ return (int)((code - low) / (range));
+ }
+
+ public long getCurrentShiftCount(int SHIFT)
+ {
+ range = range >>>SHIFT;
+ return ((code - low) / (range))&uintMask;
+ }
+
+ public void decode()
+ {
+ low = (low + (range * subRange.getLowCount()))&uintMask;
+ range = (range * (subRange.getHighCount() - subRange.getLowCount()))&uintMask;
+ }
+
+ private int getChar() throws IOException, RarException
+ {
+ return (unpackRead.getChar());
+ }
+
+ public void ariDecNormalize() throws IOException, RarException
+ {
+// while ((low ^ (low + range)) < TOP || range < BOT && ((range = -low & (BOT - 1)) != 0 ? true : true))
+// {
+// code = ((code << 8) | unpackRead.getChar()&0xff)&uintMask;
+// range = (range << 8)&uintMask;
+// low = (low << 8)&uintMask;
+// }
+
+ // Rewrote for clarity
+ boolean c2 = false;
+ while ((low ^ (low + range)) < TOP || (c2 = range < BOT)) {
+ if (c2) {
+ range = (-low & (BOT - 1))&uintMask;
+ c2 = false;
+ }
+ code = ((code << 8) | getChar())&uintMask;
+ range = (range << 8)&uintMask;
+ low = (low << 8)&uintMask;
+ }
+ }
+
+ // Debug
+ public String toString() {
+ StringBuilder buffer = new StringBuilder();
+ buffer.append("RangeCoder[");
+ buffer.append("\n low=");
+ buffer.append(low);
+ buffer.append("\n code=");
+ buffer.append(code);
+ buffer.append("\n range=");
+ buffer.append(range);
+ buffer.append("\n subrange=");
+ buffer.append(subRange);
+ buffer.append("]");
+ return buffer.toString();
+ }
+
+ public static class SubRange
+ {
+ // uint LowCount, HighCount, scale;
+ private long lowCount, highCount, scale;
+
+ public long getHighCount()
+ {
+ return highCount;
+ }
+
+ public void setHighCount(long highCount)
+ {
+ this.highCount = highCount&uintMask;
+ }
+
+ public long getLowCount()
+ {
+ return lowCount&uintMask;
+ }
+
+ public void setLowCount(long lowCount)
+ {
+ this.lowCount = lowCount&uintMask;
+ }
+
+ public long getScale()
+ {
+ return scale;
+ }
+
+ public void setScale(long scale)
+ {
+ this.scale = scale&uintMask;
+ }
+
+ public void incScale(int dScale) {
+ setScale(getScale() + dScale);
+ }
+
+ // Debug
+ public String toString() {
+ StringBuilder buffer = new StringBuilder();
+ buffer.append("SubRange[");
+ buffer.append("\n lowCount=");
+ buffer.append(lowCount);
+ buffer.append("\n highCount=");
+ buffer.append(highCount);
+ buffer.append("\n scale=");
+ buffer.append(scale);
+ buffer.append("]");
+ return buffer.toString();
+ }
+ }
+}
diff --git a/src/com/github/junrar/unpack/ppm/RarMemBlock.java b/src/com/github/junrar/unpack/ppm/RarMemBlock.java
new file mode 100644
index 0000000..1b5e7cc
--- /dev/null
+++ b/src/com/github/junrar/unpack/ppm/RarMemBlock.java
@@ -0,0 +1,139 @@
+/*
+ * Copyright (c) 2007 innoSysTec (R) GmbH, Germany. All rights reserved.
+ * Original author: Edmund Wagner
+ * Creation date: 05.06.2007
+ *
+ * Source: $HeadURL$
+ * Last changed: $LastChangedDate$
+ *
+ * the unrar licence applies to all junrar source and binary distributions
+ * you are not allowed to use this source to re-create the RAR compression algorithm
+ *
+ * Here some html entities which can be used for escaping javadoc tags:
+ * "&": "&#038;" or "&amp;"
+ * "<": "&#060;" or "&lt;"
+ * ">": "&#062;" or "&gt;"
+ * "@": "&#064;"
+ */
+package com.github.junrar.unpack.ppm;
+
+import com.github.junrar.io.Raw;
+
+
+
+/**
+ * DOCUMENT ME
+ *
+ * @author $LastChangedBy$
+ * @version $LastChangedRevision$
+ */
+public class RarMemBlock extends Pointer
+{
+
+ public static final int size = 12;
+
+ private int stamp, NU;
+
+ private int next, prev; // Pointer RarMemBlock
+
+ public RarMemBlock(byte[] mem)
+ {
+ super(mem);
+ }
+
+ public void insertAt(RarMemBlock p)
+ {
+ RarMemBlock temp = new RarMemBlock(mem);
+ setPrev(p.getAddress());
+ temp.setAddress(getPrev());
+ setNext(temp.getNext());// prev.getNext();
+ temp.setNext(this);// prev.setNext(this);
+ temp.setAddress(getNext());
+ temp.setPrev(this);// next.setPrev(this);
+ }
+
+ public void remove()
+ {
+ RarMemBlock temp = new RarMemBlock(mem);
+ temp.setAddress(getPrev());
+ temp.setNext(getNext());// prev.setNext(next);
+ temp.setAddress(getNext());
+ temp.setPrev(getPrev());// next.setPrev(prev);
+// next = -1;
+// prev = -1;
+ }
+
+ public int getNext()
+ {
+ if(mem!=null){
+ next = Raw.readIntLittleEndian(mem, pos+4);
+ }
+ return next;
+ }
+
+ public void setNext(RarMemBlock next)
+ {
+ setNext(next.getAddress());
+ }
+
+ public void setNext(int next)
+ {
+ this.next = next;
+ if (mem != null) {
+ Raw.writeIntLittleEndian(mem, pos + 4, next);
+ }
+ }
+
+ public int getNU()
+ {
+ if(mem!=null){
+ NU = Raw.readShortLittleEndian(mem, pos+2)&0xffff;
+ }
+ return NU;
+ }
+
+ public void setNU(int nu)
+ {
+ NU = nu&0xffff;
+ if (mem != null) {
+ Raw.writeShortLittleEndian(mem, pos + 2, (short)nu);
+ }
+ }
+
+ public int getPrev()
+ {
+ if(mem!=null){
+ prev = Raw.readIntLittleEndian(mem, pos+8);
+ }
+ return prev;
+ }
+
+ public void setPrev(RarMemBlock prev)
+ {
+ setPrev(prev.getAddress());
+ }
+
+ public void setPrev(int prev)
+ {
+ this.prev = prev;
+ if (mem != null) {
+ Raw.writeIntLittleEndian(mem, pos + 8, prev);
+ }
+ }
+
+ public int getStamp()
+ {
+ if(mem!=null){
+ stamp = Raw.readShortLittleEndian(mem, pos)&0xffff;
+ }
+ return stamp;
+ }
+
+ public void setStamp(int stamp)
+ {
+ this.stamp = stamp;
+ if (mem != null) {
+ Raw.writeShortLittleEndian(mem, pos, (short)stamp);
+ }
+ }
+}
diff --git a/src/com/github/junrar/unpack/ppm/RarNode.java b/src/com/github/junrar/unpack/ppm/RarNode.java
new file mode 100644
index 0000000..a9353cb
--- /dev/null
+++ b/src/com/github/junrar/unpack/ppm/RarNode.java
@@ -0,0 +1,69 @@
+/*
+ * Copyright (c) 2007 innoSysTec (R) GmbH, Germany. All rights reserved.
+ * Original author: Edmund Wagner
+ * Creation date: 05.06.2007
+ *
+ * Source: $HeadURL$
+ * Last changed: $LastChangedDate$
+ *
+ * the unrar licence applies to all junrar source and binary distributions
+ * you are not allowed to use this source to re-create the RAR compression algorithm
+ *
+ * Here some html entities which can be used for escaping javadoc tags:
+ * "&": "&#038;" or "&amp;"
+ * "<": "&#060;" or "&lt;"
+ * ">": "&#062;" or "&gt;"
+ * "@": "&#064;"
+ */
+package com.github.junrar.unpack.ppm;
+
+import com.github.junrar.io.Raw;
+
+
+
+/**
+ * DOCUMENT ME
+ *
+ * @author $LastChangedBy$
+ * @version $LastChangedRevision$
+ */
+public class RarNode extends Pointer{
+ private int next; //rarnode pointer
+
+ public static final int size = 4;
+
+ public RarNode(byte[] mem){
+ super(mem);
+ }
+
+ public int getNext() {
+ if(mem!=null){
+ next = Raw.readIntLittleEndian(mem, pos);
+ }
+ return next;
+ }
+
+ public void setNext(RarNode next) {
+ setNext(next.getAddress());
+ }
+
+ public void setNext(int next) {
+ this.next = next;
+ if(mem!=null){
+ Raw.writeIntLittleEndian(mem, pos, next);
+ }
+ }
+
+ public String toString() {
+ StringBuilder buffer = new StringBuilder();
+ buffer.append("State[");
+ buffer.append("\n pos=");
+ buffer.append(pos);
+ buffer.append("\n size=");
+ buffer.append(size);
+ buffer.append("\n next=");
+ buffer.append(getNext());
+ buffer.append("\n]");
+ return buffer.toString();
+ }
+}
diff --git a/src/com/github/junrar/unpack/ppm/SEE2Context.java b/src/com/github/junrar/unpack/ppm/SEE2Context.java
new file mode 100644
index 0000000..1f42419
--- /dev/null
+++ b/src/com/github/junrar/unpack/ppm/SEE2Context.java
@@ -0,0 +1,102 @@
+/*
+ * Copyright (c) 2007 innoSysTec (R) GmbH, Germany. All rights reserved.
+ * Original author: Edmund Wagner
+ * Creation date: 31.05.2007
+ *
+ * Source: $HeadURL$
+ * Last changed: $LastChangedDate$
+ *
+ * the unrar licence applies to all junrar source and binary distributions
+ * you are not allowed to use this source to re-create the RAR compression algorithm
+ *
+ * Here some html entities which can be used for escaping javadoc tags:
+ * "&": "&#038;" or "&amp;"
+ * "<": "&#060;" or "&lt;"
+ * ">": "&#062;" or "&gt;"
+ * "@": "&#064;"
+ */
+package com.github.junrar.unpack.ppm;
+
+/**
+ * DOCUMENT ME
+ *
+ * @author $LastChangedBy$
+ * @version $LastChangedRevision$
+ */
+public class SEE2Context {
+ public static final int size = 4;
+
+ // ushort Summ;
+ private int summ;
+
+ // byte Shift;
+ private int shift;
+
+ // byte Count;
+ private int count;
+
+ public void init(int initVal) {
+ shift = (ModelPPM.PERIOD_BITS - 4)&0xff;
+ summ = (initVal << shift)&0xffff;
+ count = 4;
+ }
+
+ public int getMean() {
+ int retVal = summ >>> shift;
+ summ -= retVal;
+ return retVal + ((retVal == 0) ? 1 : 0);
+ }
+
+ public void update() {
+ if (shift < ModelPPM.PERIOD_BITS && --count == 0) {
+ summ += summ;
+ count = (3 << shift++);
+ }
+ summ &= 0xffff;
+ count &= 0xff;
+ shift &= 0xff;
+ }
+
+ public int getCount() {
+ return count;
+ }
+
+ public void setCount(int count) {
+ this.count = count&0xff;
+ }
+
+ public int getShift() {
+ return shift;
+ }
+
+ public void setShift(int shift) {
+ this.shift = shift&0xff;
+ }
+
+ public int getSumm() {
+ return summ;
+ }
+
+ public void setSumm(int summ) {
+ this.summ = summ&0xffff;
+ }
+
+ public void incSumm(int dSumm) {
+ setSumm(getSumm() + dSumm);
+ }
+
+ public String toString() {
+ StringBuilder buffer = new StringBuilder();
+ buffer.append("SEE2Context[");
+ buffer.append("\n size=");
+ buffer.append(size);
+ buffer.append("\n summ=");
+ buffer.append(summ);
+ buffer.append("\n shift=");
+ buffer.append(shift);
+ buffer.append("\n count=");
+ buffer.append(count);
+ buffer.append("\n]");
+ return buffer.toString();
+ }
+}
diff --git a/src/com/github/junrar/unpack/ppm/State.java b/src/com/github/junrar/unpack/ppm/State.java
new file mode 100644
index 0000000..812fb40
--- /dev/null
+++ b/src/com/github/junrar/unpack/ppm/State.java
@@ -0,0 +1,119 @@
+/*
+ * Copyright (c) 2007 innoSysTec (R) GmbH, Germany. All rights reserved.
+ * Original author: Edmund Wagner
+ * Creation date: 01.06.2007
+ *
+ * Source: $HeadURL$
+ * Last changed: $LastChangedDate$
+ *
+ * the unrar licence applies to all junrar source and binary distributions
+ * you are not allowed to use this source to re-create the RAR compression algorithm
+ *
+ * Here some html entities which can be used for escaping javadoc tags:
+ * "&": "&#038;" or "&amp;"
+ * "<": "&#060;" or "&lt;"
+ * ">": "&#062;" or "&gt;"
+ * "@": "&#064;"
+ */
+package com.github.junrar.unpack.ppm;
+
+import com.github.junrar.io.Raw;
+
+/**
+ * DOCUMENT ME
+ *
+ * @author $LastChangedBy$
+ * @version $LastChangedRevision$
+ */
+public class State extends Pointer {
+
+ public static final int size = 6;
+
+ public State(byte[] mem) {
+ super(mem);
+ }
+
+ public State init(byte[] mem) {
+ this.mem = mem;
+ pos = 0;
+ return this;
+ }
+
+ public int getSymbol() {
+ return mem[pos]&0xff;
+ }
+
+ public void setSymbol(int symbol) {
+ mem[pos] = (byte)symbol;
+ }
+
+ public int getFreq() {
+ return mem[pos+1]&0xff;
+ }
+
+ public void setFreq(int freq) {
+ mem[pos + 1] = (byte)freq;
+ }
+
+ public void incFreq(int dFreq) {
+ mem[pos + 1] += dFreq;
+ }
+
+ public int getSuccessor() {
+ return Raw.readIntLittleEndian(mem, pos+2);
+ }
+
+ public void setSuccessor(PPMContext successor) {
+ setSuccessor(successor.getAddress());
+ }
+
+ public void setSuccessor(int successor) {
+ Raw.writeIntLittleEndian(mem, pos + 2, successor);
+ }
+
+ public void setValues(StateRef state){
+ setSymbol(state.getSymbol());
+ setFreq(state.getFreq());
+ setSuccessor(state.getSuccessor());
+ }
+
+ public void setValues(State ptr){
+ System.arraycopy(ptr.mem, ptr.pos, mem, pos, size);
+ }
+
+ public State decAddress(){
+ setAddress(pos-size);
+ return this;
+ }
+
+ public State incAddress(){
+ setAddress(pos+size);
+ return this;
+ }
+
+ public static void ppmdSwap(State ptr1, State ptr2) {
+ byte[] mem1=ptr1.mem, mem2=ptr2.mem;
+ for (int i=0, pos1=ptr1.pos, pos2=ptr2.pos; i < size; i++, pos1++, pos2++) {
+ byte temp = mem1[pos1];
+ mem1[pos1] = mem2[pos2];
+ mem2[pos2] = temp;
+ }
+ }
+
+ public String toString() {
+ StringBuilder buffer = new StringBuilder();
+ buffer.append("State[");
+ buffer.append("\n pos=");
+ buffer.append(pos);
+ buffer.append("\n size=");
+ buffer.append(size);
+ buffer.append("\n symbol=");
+ buffer.append(getSymbol());
+ buffer.append("\n freq=");
+ buffer.append(getFreq());
+ buffer.append("\n successor=");
+ buffer.append(getSuccessor());
+ buffer.append("\n]");
+ return buffer.toString();
+ }
+}
diff --git a/src/com/github/junrar/unpack/ppm/StateRef.java b/src/com/github/junrar/unpack/ppm/StateRef.java
new file mode 100644
index 0000000..39195e0
--- /dev/null
+++ b/src/com/github/junrar/unpack/ppm/StateRef.java
@@ -0,0 +1,92 @@
+/*
+ * Copyright (c) 2007 innoSysTec (R) GmbH, Germany. All rights reserved.
+ * Original author: Edmund Wagner
+ * Creation date: 01.06.2007
+ *
+ * Source: $HeadURL$
+ * Last changed: $LastChangedDate$
+ *
+ * the unrar licence applies to all junrar source and binary distributions
+ * you are not allowed to use this source to re-create the RAR compression algorithm
+ *
+ * Here some html entities which can be used for escaping javadoc tags:
+ * "&": "&#038;" or "&amp;"
+ * "<": "&#060;" or "&lt;"
+ * ">": "&#062;" or "&gt;"
+ * "@": "&#064;"
+ */
+package com.github.junrar.unpack.ppm;
+
+
+/**
+ * DOCUMENT ME
+ *
+ * @author $LastChangedBy$
+ * @version $LastChangedRevision$
+ */
+public class StateRef {
+
+ private int symbol;
+
+ private int freq;
+
+ private int successor; // pointer ppmcontext
+
+ public StateRef() {
+ }
+
+ public int getSymbol() {
+ return symbol;
+ }
+
+ public void setSymbol(int symbol) {
+ this.symbol = symbol&0xff;
+ }
+
+ public int getFreq() {
+ return freq;
+ }
+
+ public void setFreq(int freq) {
+ this.freq = freq&0xff;
+ }
+
+ public void incFreq(int dFreq) {
+ freq = (freq + dFreq)&0xff;
+ }
+
+ public void decFreq(int dFreq) {
+ freq = (freq - dFreq)&0xff;
+ }
+
+ public void setValues(State statePtr){
+ setFreq(statePtr.getFreq());
+ setSuccessor(statePtr.getSuccessor());
+ setSymbol(statePtr.getSymbol());
+ }
+
+ public int getSuccessor() {
+ return successor;
+ }
+
+ public void setSuccessor(PPMContext successor) {
+ setSuccessor(successor.getAddress());
+ }
+
+ public void setSuccessor(int successor) {
+ this.successor = successor;
+ }
+
+ public String toString() {
+ StringBuilder buffer = new StringBuilder();
+ buffer.append("State[");
+ buffer.append("\n symbol=");
+ buffer.append(getSymbol());
+ buffer.append("\n freq=");
+ buffer.append(getFreq());
+ buffer.append("\n successor=");
+ buffer.append(getSuccessor());
+ buffer.append("\n]");
+ return buffer.toString();
+ }
+}
diff --git a/src/com/github/junrar/unpack/ppm/SubAllocator.java b/src/com/github/junrar/unpack/ppm/SubAllocator.java
new file mode 100644
index 0000000..8844736
--- /dev/null
+++ b/src/com/github/junrar/unpack/ppm/SubAllocator.java
@@ -0,0 +1,427 @@
+/*
+ * Copyright (c) 2007 innoSysTec (R) GmbH, Germany. All rights reserved.
+ * Original author: Edmund Wagner
+ * Creation date: 31.05.2007
+ *
+ * Source: $HeadURL$
+ * Last changed: $LastChangedDate$
+ *
+ * the unrar licence applies to all junrar source and binary distributions
+ * you are not allowed to use this source to re-create the RAR compression algorithm
+ *
+ * Here some html entities which can be used for escaping javadoc tags:
+ * "&": "&#038;" or "&amp;"
+ * "<": "&#060;" or "&lt;"
+ * ">": "&#062;" or "&gt;"
+ * "@": "&#064;"
+ */
+package com.github.junrar.unpack.ppm;
+
+import java.util.Arrays;
+
+/**
+ * DOCUMENT ME
+ *
+ * @author $LastChangedBy$
+ * @version $LastChangedRevision$
+ */
+public class SubAllocator {
+ public static final int N1 = 4, N2 = 4, N3 = 4, N4 = (128 + 3 - 1 * N1 - 2
+ * N2 - 3 * N3) / 4;
+
+ public static final int N_INDEXES = N1 + N2 + N3 + N4;
+
+ public static final int UNIT_SIZE = Math.max(PPMContext.size,
+ RarMemBlock.size);
+
+ public static final int FIXED_UNIT_SIZE = 12;
+
+ private int subAllocatorSize;
+
+ // byte Indx2Units[N_INDEXES], Units2Indx[128], GlueCount;
+ private int[] indx2Units = new int[N_INDEXES];
+ private int[] units2Indx = new int[128];
+ private int glueCount;
+
+ // byte *HeapStart,*LoUnit, *HiUnit;
+ private int heapStart, loUnit, hiUnit;
+
+ private final RarNode[] freeList = new RarNode[N_INDEXES];
+
+ // byte *pText, *UnitsStart,*HeapEnd,*FakeUnitsStart;
+ private int pText, unitsStart, heapEnd, fakeUnitsStart;
+
+ private byte[] heap;
+
+ private int freeListPos;
+
+ private int tempMemBlockPos;
+
+ // Temp fields
+ private RarNode tempRarNode = null;
+ private RarMemBlock tempRarMemBlock1 = null;
+ private RarMemBlock tempRarMemBlock2 = null;
+ private RarMemBlock tempRarMemBlock3 = null;
+
+ public SubAllocator() {
+ clean();
+ }
+
+ public void clean() {
+ subAllocatorSize = 0;
+ }
+
+ private void insertNode(int p/* rarnode ptr */, int indx) {
+ RarNode temp = tempRarNode;
+ temp.setAddress(p);
+ temp.setNext(freeList[indx].getNext());
+ freeList[indx].setNext(temp);
+ }
+
+ public void incPText() {
+ pText++;
+ }
+
+ private int removeNode(int indx) {
+ int retVal = freeList[indx].getNext();
+ RarNode temp = tempRarNode;
+ temp.setAddress(retVal);
+ freeList[indx].setNext(temp.getNext());
+ return retVal;
+ }
+
+ private int U2B(int NU) {
+ return /* 8*NU+4*NU */UNIT_SIZE * NU;
+ }
+
+ /* memblockptr */
+ private int MBPtr(int BasePtr, int Items) {
+ return (BasePtr + U2B(Items));
+ }
+
+ private void splitBlock(int pv/* ptr */, int oldIndx, int newIndx) {
+ int i, uDiff = indx2Units[oldIndx] - indx2Units[newIndx];
+ int p = pv + U2B(indx2Units[newIndx]);
+ if (indx2Units[i = units2Indx[uDiff - 1]] != uDiff) {
+ insertNode(p, --i);
+ p += U2B(i = indx2Units[i]);
+ uDiff -= i;
+ }
+ insertNode(p, units2Indx[uDiff - 1]);
+ }
+
+ public void stopSubAllocator() {
+ if (subAllocatorSize != 0) {
+ subAllocatorSize = 0;
+ heap = null;
+ heapStart = 1;
+ // rarfree(HeapStart);
+ // Free temp fields
+ tempRarNode = null;
+ tempRarMemBlock1 = null;
+ tempRarMemBlock2 = null;
+ tempRarMemBlock3 = null;
+ }
+ }
+
+ public int GetAllocatedMemory() {
+ return subAllocatorSize;
+ };
+
+ public boolean startSubAllocator(int SASize) {
+ int t = SASize << 20;
+ if (subAllocatorSize == t) {
+ return true;
+ }
+ stopSubAllocator();
+ int allocSize = t / FIXED_UNIT_SIZE * UNIT_SIZE + UNIT_SIZE;
+
+ // adding space for freelist (needed for poiters)
+ // 1+ for null pointer
+ int realAllocSize = 1 + allocSize + 4 * N_INDEXES;
+ // adding space for an additional memblock
+ tempMemBlockPos = realAllocSize;
+ realAllocSize += RarMemBlock.size;
+
+ heap = new byte[realAllocSize];
+ heapStart = 1;
+ heapEnd = heapStart + allocSize - UNIT_SIZE;
+ subAllocatorSize = t;
+ // Bug fixed
+ freeListPos = heapStart + allocSize;
+ assert (realAllocSize - tempMemBlockPos == RarMemBlock.size) : realAllocSize
+ + " " + tempMemBlockPos + " " + RarMemBlock.size;
+
+ // Init freeList
+ for (int i = 0, pos = freeListPos; i < freeList.length; i++, pos += RarNode.size) {
+ freeList[i] = new RarNode(heap);
+ freeList[i].setAddress(pos);
+ }
+
+ // Init temp fields
+ tempRarNode = new RarNode(heap);
+ tempRarMemBlock1 = new RarMemBlock(heap);
+ tempRarMemBlock2 = new RarMemBlock(heap);
+ tempRarMemBlock3 = new RarMemBlock(heap);
+
+ return true;
+ }
+
+ private void glueFreeBlocks() {
+ RarMemBlock s0 = tempRarMemBlock1;
+ s0.setAddress(tempMemBlockPos);
+ RarMemBlock p = tempRarMemBlock2;
+ RarMemBlock p1 = tempRarMemBlock3;
+ int i, k, sz;
+ if (loUnit != hiUnit) {
+ heap[loUnit] = 0;
+ }
+ for (i = 0, s0.setPrev(s0), s0.setNext(s0); i < N_INDEXES; i++) {
+ while (freeList[i].getNext() != 0) {
+ p.setAddress(removeNode(i));// =(RAR_MEM_BLK*)RemoveNode(i);
+ p.insertAt(s0);// p->insertAt(&s0);
+ p.setStamp(0xFFFF);// p->Stamp=0xFFFF;
+ p.setNU(indx2Units[i]);// p->NU=Indx2Units[i];
+ }
+ }
+ for (p.setAddress(s0.getNext()); p.getAddress() != s0.getAddress(); p
+ .setAddress(p.getNext())) {
+ // while ((p1=MBPtr(p,p->NU))->Stamp == 0xFFFF && int(p->NU)+p1->NU
+ // < 0x10000)
+ // Bug fixed
+ p1.setAddress(MBPtr(p.getAddress(), p.getNU()));
+ while (p1.getStamp() == 0xFFFF && p.getNU() + p1.getNU() < 0x10000) {
+ p1.remove();
+ p.setNU(p.getNU() + p1.getNU());// ->NU += p1->NU;
+ p1.setAddress(MBPtr(p.getAddress(), p.getNU()));
+ }
+ }
+ // while ((p=s0.next) != &s0)
+ // Bug fixed
+ p.setAddress(s0.getNext());
+ while (p.getAddress() != s0.getAddress()) {
+ for (p.remove(), sz = p.getNU(); sz > 128; sz -= 128, p
+ .setAddress(MBPtr(p.getAddress(), 128))) {
+ insertNode(p.getAddress(), N_INDEXES - 1);
+ }
+ if (indx2Units[i = units2Indx[sz - 1]] != sz) {
+ k = sz - indx2Units[--i];
+ insertNode(MBPtr(p.getAddress(), sz - k), k - 1);
+ }
+ insertNode(p.getAddress(), i);
+ p.setAddress(s0.getNext());
+ }
+ }
+
+ private int allocUnitsRare(int indx) {
+ if (glueCount == 0) {
+ glueCount = 255;
+ glueFreeBlocks();
+ if (freeList[indx].getNext() != 0) {
+ return removeNode(indx);
+ }
+ }
+ int i = indx;
+ do {
+ if (++i == N_INDEXES) {
+ glueCount--;
+ i = U2B(indx2Units[indx]);
+ int j = FIXED_UNIT_SIZE * indx2Units[indx];
+ if (fakeUnitsStart - pText > j) {
+ fakeUnitsStart -= j;
+ unitsStart -= i;
+ return unitsStart;
+ }
+ return (0);
+ }
+ } while (freeList[i].getNext() == 0);
+ int retVal = removeNode(i);
+ splitBlock(retVal, i, indx);
+ return retVal;
+ }
+
+ public int allocUnits(int NU) {
+ int indx = units2Indx[NU - 1];
+ if (freeList[indx].getNext() != 0) {
+ return removeNode(indx);
+ }
+ int retVal = loUnit;
+ loUnit += U2B(indx2Units[indx]);
+ if (loUnit <= hiUnit) {
+ return retVal;
+ }
+ loUnit -= U2B(indx2Units[indx]);
+ return allocUnitsRare(indx);
+ }
+
+ public int allocContext() {
+ if (hiUnit != loUnit)
+ return (hiUnit -= UNIT_SIZE);
+ if (freeList[0].getNext() != 0) {
+ return removeNode(0);
+ }
+ return allocUnitsRare(0);
+ }
+
+ public int expandUnits(int oldPtr, int OldNU) {
+ int i0 = units2Indx[OldNU - 1];
+ int i1 = units2Indx[OldNU - 1 + 1];
+ if (i0 == i1) {
+ return oldPtr;
+ }
+ int ptr = allocUnits(OldNU + 1);
+ if (ptr != 0) {
+ // memcpy(ptr,OldPtr,U2B(OldNU));
+ System.arraycopy(heap, oldPtr, heap, ptr, U2B(OldNU));
+ insertNode(oldPtr, i0);
+ }
+ return ptr;
+ }
+
+ public int shrinkUnits(int oldPtr, int oldNU, int newNU) {
+ // System.out.println("SubAllocator.shrinkUnits(" + OldPtr + ", " +
+ // OldNU + ", " + NewNU + ")");
+ int i0 = units2Indx[oldNU - 1];
+ int i1 = units2Indx[newNU - 1];
+ if (i0 == i1) {
+ return oldPtr;
+ }
+ if (freeList[i1].getNext() != 0) {
+ int ptr = removeNode(i1);
+ // memcpy(ptr,OldPtr,U2B(NewNU));
+ // for (int i = 0; i < U2B(NewNU); i++) {
+ // heap[ptr + i] = heap[OldPtr + i];
+ // }
+ System.arraycopy(heap, oldPtr, heap, ptr, U2B(newNU));
+ insertNode(oldPtr, i0);
+ return ptr;
+ } else {
+ splitBlock(oldPtr, i0, i1);
+ return oldPtr;
+ }
+ }
+
+ public void freeUnits(int ptr, int OldNU) {
+ insertNode(ptr, units2Indx[OldNU - 1]);
+ }
+
+ public int getFakeUnitsStart() {
+ return fakeUnitsStart;
+ }
+
+ public void setFakeUnitsStart(int fakeUnitsStart) {
+ this.fakeUnitsStart = fakeUnitsStart;
+ }
+
+ public int getHeapEnd() {
+ return heapEnd;
+ }
+
+ public int getPText() {
+ return pText;
+ }
+
+ public void setPText(int text) {
+ pText = text;
+ }
+
+ public void decPText(int dPText) {
+ setPText(getPText() - dPText);
+ }
+
+ public int getUnitsStart() {
+ return unitsStart;
+ }
+
+ public void setUnitsStart(int unitsStart) {
+ this.unitsStart = unitsStart;
+ }
+
+ public void initSubAllocator() {
+ int i, k;
+ Arrays
+ .fill(heap, freeListPos, freeListPos + sizeOfFreeList(),
+ (byte) 0);
+
+ pText = heapStart;
+
+ int size2 = FIXED_UNIT_SIZE
+ * (subAllocatorSize / 8 / FIXED_UNIT_SIZE * 7);
+ int realSize2 = size2 / FIXED_UNIT_SIZE * UNIT_SIZE;
+ int size1 = subAllocatorSize - size2;
+ int realSize1 = size1 / FIXED_UNIT_SIZE * UNIT_SIZE + size1
+ % FIXED_UNIT_SIZE;
+ hiUnit = heapStart + subAllocatorSize;
+ loUnit = unitsStart = heapStart + realSize1;
+ fakeUnitsStart = heapStart + size1;
+ hiUnit = loUnit + realSize2;
+
+ for (i = 0, k = 1; i < N1; i++, k += 1) {
+ indx2Units[i] = k & 0xff;
+ }
+ for (k++; i < N1 + N2; i++, k += 2) {
+ indx2Units[i] = k & 0xff;
+ }
+ for (k++; i < N1 + N2 + N3; i++, k += 3) {
+ indx2Units[i] = k & 0xff;
+ }
+ for (k++; i < (N1 + N2 + N3 + N4); i++, k += 4) {
+ indx2Units[i] = k & 0xff;
+ }
+
+ for (glueCount = 0, k = 0, i = 0; k < 128; k++) {
+ i += ((indx2Units[i] < (k + 1)) ? 1 : 0);
+ units2Indx[k] = i & 0xff;
+ }
+
+ }
+
+ private int sizeOfFreeList() {
+ return freeList.length * RarNode.size;
+ }
+
+ public byte[] getHeap() {
+ return heap;
+ }
+
+ // Debug
+ // public void dumpHeap() {
+ // File file = new File("P:\\test\\heapdumpj");
+ // OutputStream out = null;
+ // try {
+ // out = new FileOutputStream(file);
+ // out.write(heap, heapStart, heapEnd - heapStart);
+ // out.flush();
+ // System.out.println("Heap dumped to " + file.getAbsolutePath());
+ // }
+ // catch (IOException e) {
+ // e.printStackTrace();
+ // }
+ // finally {
+ // FileUtil.close(out);
+ // }
+ // }
+
+ // Debug
+ public String toString() {
+ StringBuilder buffer = new StringBuilder();
+ buffer.append("SubAllocator[");
+ buffer.append("\n subAllocatorSize=");
+ buffer.append(subAllocatorSize);
+ buffer.append("\n glueCount=");
+ buffer.append(glueCount);
+ buffer.append("\n heapStart=");
+ buffer.append(heapStart);
+ buffer.append("\n loUnit=");
+ buffer.append(loUnit);
+ buffer.append("\n hiUnit=");
+ buffer.append(hiUnit);
+ buffer.append("\n pText=");
+ buffer.append(pText);
+ buffer.append("\n unitsStart=");
+ buffer.append(unitsStart);
+ buffer.append("\n]");
+ return buffer.toString();
+ }
+
+}
diff --git a/src/com/github/junrar/unpack/vm/BitInput.java b/src/com/github/junrar/unpack/vm/BitInput.java
new file mode 100644
index 0000000..603cb77
--- /dev/null
+++ b/src/com/github/junrar/unpack/vm/BitInput.java
@@ -0,0 +1,108 @@
+/*
+ * Copyright (c) 2007 innoSysTec (R) GmbH, Germany. All rights reserved.
+ * Original author: Edmund Wagner
+ * Creation date: 31.05.2007
+ *
+ * Source: $HeadURL$
+ * Last changed: $LastChangedDate$
+ *
+ * the unrar licence applies to all junrar source and binary distributions
+ * you are not allowed to use this source to re-create the RAR compression algorithm
+ *
+ * Here some html entities which can be used for escaping javadoc tags:
+ * "&": "&#038;" or "&amp;"
+ * "<": "&#060;" or "&lt;"
+ * ">": "&#062;" or "&gt;"
+ * "@": "&#064;"
+ */
+package com.github.junrar.unpack.vm;
+
+/**
+ * DOCUMENT ME
+ *
+ * @author $LastChangedBy$
+ * @version $LastChangedRevision$
+ */
+public class BitInput {
+ /**
+ * the max size of the input
+ */
+ public static final int MAX_SIZE = 0x8000;
+ protected int inAddr;
+ protected int inBit;
+ protected byte[] inBuf;
+
+ /**
+ *
+ */
+ public void InitBitInput()
+ {
+ inAddr=0;
+ inBit=0;
+ }
+ /**
+ * @param Bits
+ */
+ public void addbits(int Bits)
+ {
+ Bits+=inBit;
+ inAddr+=Bits>>3;
+ inBit=Bits&7;
+ }
+
+ /**
+ * @return the bits (unsigned short)
+ */
+ public int getbits()
+ {
+// int BitField=0;
+// BitField|=(int)(inBuf[inAddr] << 16)&0xFF0000;
+// BitField|=(int)(inBuf[inAddr+1] << 8)&0xff00;
+// BitField|=(int)(inBuf[inAddr+2])&0xFF;
+// BitField >>>= (8-inBit);
+// return (BitField & 0xffff);
+ return (((((inBuf[inAddr] & 0xff) << 16) +
+ ((inBuf[inAddr+1] & 0xff) << 8) +
+ ((inBuf[inAddr+2] & 0xff))) >>> (8-inBit)) & 0xffff);
+ }
+
+ /**
+ *
+ */
+ public BitInput()
+ {
+ inBuf=new byte[MAX_SIZE];
+ }
+
+ /**
+ * @param Bits add the bits
+ */
+ public void faddbits(int Bits)
+ {
+ addbits(Bits);
+ }
+
+
+ /**
+ * @return get the bits
+ */
+ public int fgetbits()
+ {
+ return(getbits());
+ }
+
+ /**
+ * Indicates an Overfow
+ * @param IncPtr how many bytes to inc
+ * @return true if an Oververflow would occur
+ */
+ public boolean Overflow(int IncPtr) {
+ return(inAddr+IncPtr>=MAX_SIZE);
+ }
+ public byte[] getInBuf()
+ {
+ return inBuf;
+ }
+
+
+}
diff --git a/src/com/github/junrar/unpack/vm/RarVM.java b/src/com/github/junrar/unpack/vm/RarVM.java
new file mode 100644
index 0000000..e6e6a01
--- /dev/null
+++ b/src/com/github/junrar/unpack/vm/RarVM.java
@@ -0,0 +1,1221 @@
+/*
+ * Copyright (c) 2007 innoSysTec (R) GmbH, Germany. All rights reserved.
+ * Original author: Edmund Wagner
+ * Creation date: 31.05.2007
+ *
+ * Source: $HeadURL$
+ * Last changed: $LastChangedDate$
+ *
+ * the unrar licence applies to all junrar source and binary distributions
+ * you are not allowed to use this source to re-create the RAR compression algorithm
+ *
+ * Here some html entities which can be used for escaping javadoc tags:
+ * "&": "&#038;" or "&amp;"
+ * "<": "&#060;" or "&lt;"
+ * ">": "&#062;" or "&gt;"
+ * "@": "&#064;"
+ */
+package com.github.junrar.unpack.vm;
+
+import java.util.List;
+import java.util.Vector;
+
+import com.github.junrar.crc.RarCRC;
+import com.github.junrar.io.Raw;
+
+
+/**
+ * DOCUMENT ME
+ *
+ * @author $LastChangedBy$
+ * @version $LastChangedRevision$
+ */
+public class RarVM extends BitInput {
+
+ public static final int VM_MEMSIZE = 0x40000;
+
+ public static final int VM_MEMMASK = (VM_MEMSIZE - 1);
+
+ public static final int VM_GLOBALMEMADDR = 0x3C000;
+
+ public static final int VM_GLOBALMEMSIZE = 0x2000;
+
+ public static final int VM_FIXEDGLOBALSIZE = 64;
+
+ private static final int regCount = 8;
+
+ private static final long UINT_MASK = 0xffffFFFF;//((long)2*(long)Integer.MAX_VALUE);
+
+ private byte[] mem;
+
+ private int[] R = new int[regCount];
+
+ private int flags;
+
+ private int maxOpCount = 25000000;
+
+ private int codeSize;
+
+ private int IP;
+
+ public RarVM() {
+ mem = null;
+ }
+
+ public void init() {
+ if (mem == null) {
+ mem = new byte[VM_MEMSIZE + 4];
+ }
+ }
+
+ private boolean isVMMem(byte[] mem) {
+ return this.mem == mem;
+ }
+
+ private int getValue(boolean byteMode, byte[] mem, int offset) {
+ if (byteMode) {
+ if (isVMMem(mem)) {
+ return (mem[offset]);
+ } else {
+ return (mem[offset] & 0xff);
+ }
+ } else {
+ if (isVMMem(mem)) {
+ //little
+ return Raw.readIntLittleEndian(mem, offset);
+ } else
+ //big endian
+ return Raw.readIntBigEndian(mem, offset);
+ }
+ }
+
+ private void setValue(boolean byteMode, byte[] mem, int offset, int value) {
+ if (byteMode) {
+ if (isVMMem(mem)) {
+ mem[offset] = (byte) value;
+ } else {
+ mem[offset] = (byte) ((mem[offset] & 0x00) | (byte) (value & 0xff));
+ }
+ } else {
+ if (isVMMem(mem)) {
+ Raw.writeIntLittleEndian(mem, offset, value);
+// mem[offset + 0] = (byte) value;
+// mem[offset + 1] = (byte) (value >>> 8);
+// mem[offset + 2] = (byte) (value >>> 16);
+// mem[offset + 3] = (byte) (value >>> 24);
+ } else {
+ Raw.writeIntBigEndian(mem, offset, value);
+// mem[offset + 3] = (byte) value;
+// mem[offset + 2] = (byte) (value >>> 8);
+// mem[offset + 1] = (byte) (value >>> 16);
+// mem[offset + 0] = (byte) (value >>> 24);
+ }
+
+ }
+ // #define SET_VALUE(ByteMode,Addr,Value) SetValue(ByteMode,(uint
+ // *)Addr,Value)
+ }
+
+ public void setLowEndianValue(byte[] mem, int offset, int value) {
+ Raw.writeIntLittleEndian(mem, offset, value);
+// mem[offset + 0] = (byte) (value&0xff);
+// mem[offset + 1] = (byte) ((value >>> 8)&0xff);
+// mem[offset + 2] = (byte) ((value >>> 16)&0xff);
+// mem[offset + 3] = (byte) ((value >>> 24)&0xff);
+ }
+ public void setLowEndianValue(Vector<Byte> mem, int offset, int value) {
+ mem.set(offset + 0, Byte.valueOf((byte) (value&0xff))) ;
+ mem.set(offset + 1, Byte.valueOf((byte) ((value >>> 8)&0xff)));
+ mem.set(offset + 2, Byte.valueOf((byte) ((value >>> 16)&0xff) ));
+ mem.set(offset + 3, Byte.valueOf((byte) ((value >>> 24)&0xff))) ;
+ }
+ private int getOperand(VMPreparedOperand cmdOp) {
+ int ret = 0;
+ if (cmdOp.getType() == VMOpType.VM_OPREGMEM) {
+ int pos = (cmdOp.getOffset() + cmdOp.getBase()) & VM_MEMMASK;
+ ret = Raw.readIntLittleEndian(mem, pos);
+ } else {
+ int pos = cmdOp.getOffset();
+ ret = Raw.readIntLittleEndian(mem, pos);
+ }
+ return ret;
+ }
+
+ public void execute(VMPreparedProgram prg) {
+ for (int i = 0; i < prg.getInitR().length; i++) // memcpy(R,Prg->InitR,sizeof(Prg->InitR));
+ {
+ R[i] = prg.getInitR()[i];
+ }
+
+ long globalSize = Math
+ .min(prg.getGlobalData().size(), VM_GLOBALMEMSIZE) & 0xffFFffFF;
+ if (globalSize != 0) {
+ for (int i = 0; i < globalSize; i++) // memcpy(Mem+VM_GLOBALMEMADDR,&Prg->GlobalData[0],GlobalSize);
+ {
+ mem[VM_GLOBALMEMADDR + i] = prg.getGlobalData().get(i);
+ }
+
+ }
+ long staticSize = Math.min(prg.getStaticData().size(), VM_GLOBALMEMSIZE
+ - globalSize) & 0xffFFffFF;
+ if (staticSize != 0) {
+ for (int i = 0; i < staticSize; i++) // memcpy(Mem+VM_GLOBALMEMADDR+GlobalSize,&Prg->StaticData[0],StaticSize);
+ {
+ mem[VM_GLOBALMEMADDR + (int) globalSize + i] = prg
+ .getStaticData().get(i);
+ }
+
+ }
+ R[7] = VM_MEMSIZE;
+ flags = 0;
+
+ List<VMPreparedCommand> preparedCode = prg.getAltCmd().size() != 0 ? prg
+ .getAltCmd()
+ : prg.getCmd();
+
+ if (!ExecuteCode(preparedCode, prg.getCmdCount())) {
+ preparedCode.get(0).setOpCode(VMCommands.VM_RET);
+ }
+ int newBlockPos = getValue(false, mem, VM_GLOBALMEMADDR + 0x20)
+ & VM_MEMMASK;
+ int newBlockSize = getValue(false, mem, VM_GLOBALMEMADDR + 0x1c)
+ & VM_MEMMASK;
+ if ((newBlockPos + newBlockSize) >= VM_MEMSIZE) {
+ newBlockPos = 0;
+ newBlockSize = 0;
+ }
+
+ prg.setFilteredDataOffset(newBlockPos);
+ prg.setFilteredDataSize(newBlockSize);
+
+ prg.getGlobalData().clear();
+
+ int dataSize = Math.min(getValue(false, mem, VM_GLOBALMEMADDR + 0x30),
+ VM_GLOBALMEMSIZE - VM_FIXEDGLOBALSIZE);
+ if (dataSize != 0) {
+ prg.getGlobalData().setSize(dataSize + VM_FIXEDGLOBALSIZE);
+ // ->GlobalData.Add(dataSize+VM_FIXEDGLOBALSIZE);
+
+ for (int i = 0; i < dataSize + VM_FIXEDGLOBALSIZE; i++) // memcpy(&Prg->GlobalData[0],&Mem[VM_GLOBALMEMADDR],DataSize+VM_FIXEDGLOBALSIZE);
+ {
+ prg.getGlobalData().set(i, mem[VM_GLOBALMEMADDR + i]);
+ }
+ }
+ }
+
+ public byte[] getMem()
+ {
+ return mem;
+ }
+
+ private boolean setIP(int ip) {
+ if ((ip) >= codeSize) {
+ return (true);
+ }
+
+ if (--maxOpCount <= 0) {
+ return (false);
+ }
+
+ IP = ip;
+ return true;
+ }
+
+ private boolean ExecuteCode(List<VMPreparedCommand> preparedCode,
+ int cmdCount) {
+
+ maxOpCount = 25000000;
+ this.codeSize = cmdCount;
+ this.IP = 0;
+
+ while (true) {
+ VMPreparedCommand cmd = preparedCode.get(IP);
+ int op1 = getOperand(cmd.getOp1());
+ int op2 = getOperand(cmd.getOp2());
+ switch (cmd.getOpCode()) {
+ case VM_MOV:
+ setValue(cmd.isByteMode(), mem, op1, getValue(cmd.isByteMode(),
+ mem, op2)); // SET_VALUE(Cmd->ByteMode,Op1,GET_VALUE(Cmd->ByteMode,Op2));
+ break;
+ case VM_MOVB:
+ setValue(true, mem, op1, getValue(true, mem, op2));
+ break;
+ case VM_MOVD:
+ setValue(false, mem, op1, getValue(false, mem, op2));
+ break;
+
+ case VM_CMP: {
+ int value1 = getValue(cmd.isByteMode(), mem, op1);
+ int result = value1 - getValue(cmd.isByteMode(), mem, op2);
+
+ if (result == 0) {
+ flags = VMFlags.VM_FZ.getFlag();
+ } else {
+ flags = (result > value1) ? 1 : 0 | (result & VMFlags.VM_FS
+ .getFlag());
+ }
+ }
+ break;
+
+ case VM_CMPB: {
+ int value1 = getValue(true, mem, op1);
+ int result = value1 - getValue(true, mem, op2);
+ if (result == 0) {
+ flags = VMFlags.VM_FZ.getFlag();
+ } else {
+ flags = (result > value1) ? 1 : 0 | (result & VMFlags.VM_FS
+ .getFlag());
+ }
+ }
+ break;
+ case VM_CMPD: {
+ int value1 = getValue(false, mem, op1);
+ int result = value1 - getValue(false, mem, op2);
+ if (result == 0) {
+ flags = VMFlags.VM_FZ.getFlag();
+ } else {
+ flags = (result > value1) ? 1 : 0 | (result & VMFlags.VM_FS
+ .getFlag());
+ }
+ }
+ break;
+
+ case VM_ADD: {
+ int value1 = getValue(cmd.isByteMode(), mem, op1);
+ int result = (int) ((((long) value1 + (long) getValue(cmd
+ .isByteMode(), mem, op2))) & 0xffffffff);
+ if (cmd.isByteMode()) {
+ result &= 0xff;
+ flags = (result < value1) ? 1
+ : 0 | (result == 0 ? VMFlags.VM_FZ.getFlag()
+ : ((result & 0x80) != 0) ? VMFlags.VM_FS
+ .getFlag() : 0);
+ // Flags=(Result<Value1)|(Result==0 ? VM_FZ:((Result&0x80) ?
+ // VM_FS:0));
+ } else
+ flags = (result < value1) ? 1
+ : 0 | (result == 0 ? VMFlags.VM_FZ.getFlag()
+ : (result & VMFlags.VM_FS.getFlag()));
+ setValue(cmd.isByteMode(), mem, op1, result);
+ }
+ break;
+
+ case VM_ADDB:
+ setValue(true, mem, op1,
+ (int) ((long) getValue(true, mem, op1) & 0xFFffFFff
+ + (long) getValue(true, mem, op2) & 0xFFffFFff));
+ break;
+ case VM_ADDD:
+ setValue(
+ false,
+ mem,
+ op1,
+ (int) ((long) getValue(false, mem, op1) & 0xFFffFFff
+ + (long) getValue(false, mem, op2) & 0xFFffFFff));
+ break;
+
+ case VM_SUB: {
+ int value1 = getValue(cmd.isByteMode(), mem, op1);
+ int result = (int) ((long) value1 & 0xffFFffFF
+ - (long) getValue(cmd.isByteMode(), mem, op2) & 0xFFffFFff);
+ flags = (result == 0) ? VMFlags.VM_FZ.getFlag()
+ : (result > value1) ? 1 : 0 | (result & VMFlags.VM_FS
+ .getFlag());
+ setValue(cmd.isByteMode(), mem, op1, result);// (Cmd->ByteMode,Op1,Result);
+ }
+ break;
+
+ case VM_SUBB:
+ setValue(true, mem, op1,
+ (int) ((long) getValue(true, mem, op1) & 0xFFffFFff
+ - (long) getValue(true, mem, op2) & 0xFFffFFff));
+ break;
+ case VM_SUBD:
+ setValue(
+ false,
+ mem,
+ op1,
+ (int) ((long) getValue(false, mem, op1) & 0xFFffFFff
+ - (long) getValue(false, mem, op2) & 0xFFffFFff));
+ break;
+
+ case VM_JZ:
+ if ((flags & VMFlags.VM_FZ.getFlag()) != 0) {
+ setIP(getValue(false, mem, op1));
+ continue;
+ }
+ break;
+ case VM_JNZ:
+ if ((flags & VMFlags.VM_FZ.getFlag()) == 0) {
+ setIP(getValue(false, mem, op1));
+ continue;
+ }
+ break;
+ case VM_INC: {
+ int result = (int) ((long) getValue(cmd.isByteMode(), mem, op1) & 0xFFffFFff + 1);
+ if (cmd.isByteMode()) {
+ result &= 0xff;
+ }
+
+ setValue(cmd.isByteMode(), mem, op1, result);
+ flags = result == 0 ? VMFlags.VM_FZ.getFlag() : result
+ & VMFlags.VM_FS.getFlag();
+ }
+ break;
+
+ case VM_INCB:
+ setValue(
+ true,
+ mem,
+ op1,
+ (int) ((long) getValue(true, mem, op1) & 0xFFffFFff + 1));
+ break;
+ case VM_INCD:
+ setValue(false, mem, op1, (int) ((long) getValue(false, mem,
+ op1) & 0xFFffFFff + 1));
+ break;
+
+ case VM_DEC: {
+ int result = (int) ((long) getValue(cmd.isByteMode(), mem, op1) & 0xFFffFFff - 1);
+ setValue(cmd.isByteMode(), mem, op1, result);
+ flags = result == 0 ? VMFlags.VM_FZ.getFlag() : result
+ & VMFlags.VM_FS.getFlag();
+ }
+ break;
+
+ case VM_DECB:
+ setValue(
+ true,
+ mem,
+ op1,
+ (int) ((long) getValue(true, mem, op1) & 0xFFffFFff - 1));
+ break;
+ case VM_DECD:
+ setValue(false, mem, op1, (int) ((long) getValue(false, mem,
+ op1) & 0xFFffFFff - 1));
+ break;
+
+ case VM_JMP:
+ setIP(getValue(false, mem, op1));
+ continue;
+ case VM_XOR: {
+ int result = getValue(cmd.isByteMode(), mem, op1)
+ ^ getValue(cmd.isByteMode(), mem, op2);
+ flags = result == 0 ? VMFlags.VM_FZ.getFlag() : result
+ & VMFlags.VM_FS.getFlag();
+ setValue(cmd.isByteMode(), mem, op1, result);
+ }
+ break;
+ case VM_AND: {
+ int result = getValue(cmd.isByteMode(), mem, op1)
+ & getValue(cmd.isByteMode(), mem, op2);
+ flags = result == 0 ? VMFlags.VM_FZ.getFlag() : result
+ & VMFlags.VM_FS.getFlag();
+ setValue(cmd.isByteMode(), mem, op1, result);
+ }
+ break;
+ case VM_OR: {
+ int result = getValue(cmd.isByteMode(), mem, op1)
+ | getValue(cmd.isByteMode(), mem, op2);
+ flags = result == 0 ? VMFlags.VM_FZ.getFlag() : result
+ & VMFlags.VM_FS.getFlag();
+ setValue(cmd.isByteMode(), mem, op1, result);
+ }
+ break;
+ case VM_TEST: {
+ int result = getValue(cmd.isByteMode(), mem, op1)
+ & getValue(cmd.isByteMode(), mem, op2);
+ flags = result == 0 ? VMFlags.VM_FZ.getFlag() : result
+ & VMFlags.VM_FS.getFlag();
+ }
+ break;
+ case VM_JS:
+ if ((flags & VMFlags.VM_FS.getFlag()) != 0) {
+ setIP(getValue(false, mem, op1));
+ continue;
+ }
+ break;
+ case VM_JNS:
+ if ((flags & VMFlags.VM_FS.getFlag()) == 0) {
+ setIP(getValue(false, mem, op1));
+ continue;
+ }
+ break;
+ case VM_JB:
+ if ((flags & VMFlags.VM_FC.getFlag()) != 0) {
+ setIP(getValue(false, mem, op1));
+ continue;
+ }
+ break;
+ case VM_JBE:
+ if ((flags & (VMFlags.VM_FC.getFlag() | VMFlags.VM_FZ.getFlag())) != 0) {
+ setIP(getValue(false, mem, op1));
+ continue;
+ }
+ break;
+ case VM_JA:
+ if ((flags & (VMFlags.VM_FC.getFlag() | VMFlags.VM_FZ.getFlag())) == 0) {
+ setIP(getValue(false, mem, op1));
+ continue;
+ }
+ break;
+ case VM_JAE:
+ if ((flags & VMFlags.VM_FC.getFlag()) == 0) {
+ setIP(getValue(false, mem, op1));
+ continue;
+ }
+ break;
+ case VM_PUSH:
+ R[7] -= 4;
+ setValue(false, mem, R[7] & VM_MEMMASK, getValue(false, mem,
+ op1));
+ break;
+ case VM_POP:
+ setValue(false, mem, op1, getValue(false, mem, R[7]
+ & VM_MEMMASK));
+ R[7] += 4;
+ break;
+ case VM_CALL:
+ R[7] -= 4;
+ setValue(false, mem, R[7] & VM_MEMMASK, IP + 1);
+ setIP(getValue(false, mem, op1));
+ continue;
+ case VM_NOT:
+ setValue(cmd.isByteMode(), mem, op1, ~getValue(
+ cmd.isByteMode(), mem, op1));
+ break;
+ case VM_SHL: {
+ int value1 = getValue(cmd.isByteMode(), mem, op1);
+ int value2 = getValue(cmd.isByteMode(), mem, op2);
+ int result = value1 << value2;
+ flags = (result == 0 ? VMFlags.VM_FZ.getFlag()
+ : (result & VMFlags.VM_FS.getFlag()))
+ | (((value1 << (value2 - 1)) & 0x80000000) != 0 ? VMFlags.VM_FC
+ .getFlag()
+ : 0);
+ setValue(cmd.isByteMode(), mem, op1, result);
+ }
+ break;
+ case VM_SHR: {
+ int value1 = getValue(cmd.isByteMode(), mem, op1);
+ int value2 = getValue(cmd.isByteMode(), mem, op2);
+ int result = value1 >>> value2;
+ flags = (result == 0 ? VMFlags.VM_FZ.getFlag()
+ : (result & VMFlags.VM_FS.getFlag()))
+ | ((value1 >>> (value2 - 1)) & VMFlags.VM_FC.getFlag());
+ setValue(cmd.isByteMode(), mem, op1, result);
+ }
+ break;
+ case VM_SAR: {
+ int value1 = getValue(cmd.isByteMode(), mem, op1);
+ int value2 = getValue(cmd.isByteMode(), mem, op2);
+ int result = ((int) value1) >> value2;
+ flags = (result == 0 ? VMFlags.VM_FZ.getFlag()
+ : (result & VMFlags.VM_FS.getFlag()))
+ | ((value1 >> (value2 - 1)) & VMFlags.VM_FC.getFlag());
+ setValue(cmd.isByteMode(), mem, op1, result);
+ }
+ break;
+ case VM_NEG: {
+ int result = -getValue(cmd.isByteMode(), mem, op1);
+ flags = result == 0 ? VMFlags.VM_FZ.getFlag() : VMFlags.VM_FC
+ .getFlag()
+ | (result & VMFlags.VM_FS.getFlag());
+ setValue(cmd.isByteMode(), mem, op1, result);
+ }
+ break;
+
+ case VM_NEGB:
+ setValue(true, mem, op1, -getValue(true, mem, op1));
+ break;
+ case VM_NEGD:
+ setValue(false, mem, op1, -getValue(false, mem, op1));
+ break;
+ case VM_PUSHA: {
+ for (int i = 0, SP = R[7] - 4; i < regCount; i++, SP -= 4) {
+ setValue(false, mem, SP & VM_MEMMASK, R[i]);
+ }
+ R[7] -= regCount * 4;
+ }
+ break;
+ case VM_POPA: {
+ for (int i = 0, SP = R[7]; i < regCount; i++, SP += 4)
+ R[7 - i] = getValue(false, mem, SP & VM_MEMMASK);
+ }
+ break;
+ case VM_PUSHF:
+ R[7] -= 4;
+ setValue(false, mem, R[7] & VM_MEMMASK, flags);
+ break;
+ case VM_POPF:
+ flags = getValue(false, mem, R[7] & VM_MEMMASK);
+ R[7] += 4;
+ break;
+ case VM_MOVZX:
+ setValue(false, mem, op1, getValue(true, mem, op2));
+ break;
+ case VM_MOVSX:
+ setValue(false, mem, op1, (byte) getValue(true, mem, op2));
+ break;
+ case VM_XCHG: {
+ int value1 = getValue(cmd.isByteMode(), mem, op1);
+ setValue(cmd.isByteMode(), mem, op1, getValue(cmd.isByteMode(),
+ mem, op2));
+ setValue(cmd.isByteMode(), mem, op2, value1);
+ }
+ break;
+ case VM_MUL: {
+ int result = (int) (((long) getValue(cmd.isByteMode(), mem, op1)
+ & 0xFFffFFff
+ * (long) getValue(cmd.isByteMode(), mem, op2) & 0xFFffFFff) & 0xFFffFFff);
+ setValue(cmd.isByteMode(), mem, op1, result);
+ }
+ break;
+ case VM_DIV: {
+ int divider = getValue(cmd.isByteMode(), mem, op2);
+ if (divider != 0) {
+ int result = getValue(cmd.isByteMode(), mem, op1) / divider;
+ setValue(cmd.isByteMode(), mem, op1, result);
+ }
+ }
+ break;
+ case VM_ADC: {
+ int value1 = getValue(cmd.isByteMode(), mem, op1);
+ int FC = (flags & VMFlags.VM_FC.getFlag());
+ int result = (int) ((long) value1 & 0xFFffFFff
+ + (long) getValue(cmd.isByteMode(), mem, op2)
+ & 0xFFffFFff + (long) FC & 0xFFffFFff);
+ if (cmd.isByteMode()) {
+ result &= 0xff;
+ }
+
+ flags = (result < value1 || result == value1 && FC != 0) ? 1
+ : 0 | (result == 0 ? VMFlags.VM_FZ.getFlag()
+ : (result & VMFlags.VM_FS.getFlag()));
+ setValue(cmd.isByteMode(), mem, op1, result);
+ }
+ break;
+ case VM_SBB: {
+ int value1 = getValue(cmd.isByteMode(), mem, op1);
+ int FC = (flags & VMFlags.VM_FC.getFlag());
+ int result = (int) ((long) value1 & 0xFFffFFff
+ - (long) getValue(cmd.isByteMode(), mem, op2)
+ & 0xFFffFFff - (long) FC & 0xFFffFFff);
+ if (cmd.isByteMode()) {
+ result &= 0xff;
+ }
+ flags = (result > value1 || result == value1 && FC != 0) ? 1
+ : 0 | (result == 0 ? VMFlags.VM_FZ.getFlag()
+ : (result & VMFlags.VM_FS.getFlag()));
+ setValue(cmd.isByteMode(), mem, op1, result);
+ }
+ break;
+
+ case VM_RET:
+ if (R[7] >= VM_MEMSIZE) {
+ return (true);
+ }
+ setIP(getValue(false, mem, R[7] & VM_MEMMASK));
+ R[7] += 4;
+ continue;
+
+ case VM_STANDARD:
+ ExecuteStandardFilter(VMStandardFilters.findFilter(cmd.getOp1()
+ .getData()));
+ break;
+ case VM_PRINT:
+ break;
+ }
+ IP++;
+ --maxOpCount;
+ }
+ }
+
+ public void prepare(byte[] code, int codeSize, VMPreparedProgram prg) {
+ InitBitInput();
+ int cpLength = Math.min(MAX_SIZE, codeSize);
+ for (int i = 0; i < cpLength; i++) // memcpy(inBuf,Code,Min(CodeSize,BitInput::MAX_SIZE));
+ {
+ inBuf[i] |= code[i];
+ }
+
+ byte xorSum = 0;
+ for (int i = 1; i < codeSize; i++) {
+ xorSum ^= code[i];
+ }
+
+ faddbits(8);
+
+ prg.setCmdCount(0);
+ if (xorSum == code[0]) {
+ VMStandardFilters filterType = IsStandardFilter(code, codeSize);
+ if (filterType != VMStandardFilters.VMSF_NONE) {
+
+ VMPreparedCommand curCmd = new VMPreparedCommand();
+ curCmd.setOpCode(VMCommands.VM_STANDARD);
+ curCmd.getOp1().setData(filterType.getFilter());
+ curCmd.getOp1().setType(VMOpType.VM_OPNONE);
+ curCmd.getOp2().setType(VMOpType.VM_OPNONE);
+ codeSize = 0;
+ prg.getCmd().add(curCmd);
+ prg.setCmdCount(prg.getCmdCount()+1);
+ // TODO
+ // curCmd->Op1.Data=FilterType;
+ // >>>>>> CurCmd->Op1.Addr=&CurCmd->Op1.Data; <<<<<<<<<< not set
+ // do i need to ?
+ // >>>>>> CurCmd->Op2.Addr=&CurCmd->Op2.Data; <<<<<<<<<< "
+ // CurCmd->Op1.Type=CurCmd->Op2.Type=VM_OPNONE;
+ // CodeSize=0;
+ }
+ int dataFlag = fgetbits();
+ faddbits(1);
+
+ // Read static data contained in DB operators. This data cannot be
+ // changed,
+ // it is a part of VM code, not a filter parameter.
+
+ if ((dataFlag & 0x8000) != 0) {
+ long dataSize = (long) ((long) ReadData(this) & 0xffFFffFF + 1);
+ for (int i = 0; inAddr < codeSize && i < dataSize; i++) {
+ prg.getStaticData().add(
+ Byte.valueOf((byte) (fgetbits() >> 8)));
+ faddbits(8);
+ }
+ }
+
+ while (inAddr < codeSize) {
+ VMPreparedCommand curCmd = new VMPreparedCommand();
+ int data = fgetbits();
+ if ((data & 0x8000) == 0) {
+ curCmd.setOpCode(VMCommands.findVMCommand((data >> 12)));
+ faddbits(4);
+ } else {
+ curCmd.setOpCode(VMCommands
+ .findVMCommand((data >> 10) - 24));
+ faddbits(6);
+ }
+ if ((VMCmdFlags.VM_CmdFlags[curCmd.getOpCode().getVMCommand()] & VMCmdFlags.VMCF_BYTEMODE) != 0) {
+ curCmd.setByteMode((fgetbits() >> 15) == 1 ? true : false);
+ faddbits(1);
+ } else {
+ curCmd.setByteMode(false);
+ }
+ curCmd.getOp1().setType(VMOpType.VM_OPNONE);
+ curCmd.getOp2().setType(VMOpType.VM_OPNONE);
+
+ int opNum = (VMCmdFlags.VM_CmdFlags[curCmd.getOpCode()
+ .getVMCommand()] & VMCmdFlags.VMCF_OPMASK);
+ // TODO >>> CurCmd->Op1.Addr=CurCmd->Op2.Addr=NULL; <<<???
+ if (opNum > 0) {
+ decodeArg(curCmd.getOp1(), curCmd.isByteMode());
+ if (opNum == 2)
+ decodeArg(curCmd.getOp2(), curCmd.isByteMode());
+ else {
+ if (curCmd.getOp1().getType() == VMOpType.VM_OPINT
+ && (VMCmdFlags.VM_CmdFlags[curCmd.getOpCode()
+ .getVMCommand()] & (VMCmdFlags.VMCF_JUMP | VMCmdFlags.VMCF_PROC)) != 0) {
+ int distance = curCmd.getOp1().getData();
+ if (distance >= 256)
+ distance -= 256;
+ else {
+ if (distance >= 136) {
+ distance -= 264;
+ } else {
+ if (distance >= 16) {
+ distance -= 8;
+ } else {
+ if (distance >= 8) {
+ distance -= 16;
+ }
+ }
+ }
+ distance += prg.getCmdCount();
+ }
+ curCmd.getOp1().setData(distance);
+ }
+ }
+ }
+ prg.setCmdCount(prg.getCmdCount() + 1);
+ prg.getCmd().add(curCmd);
+ }
+ }
+ VMPreparedCommand curCmd = new VMPreparedCommand();
+ curCmd.setOpCode(VMCommands.VM_RET);
+ // TODO CurCmd->Op1.Addr=&CurCmd->Op1.Data;
+ // CurCmd->Op2.Addr=&CurCmd->Op2.Data;
+ curCmd.getOp1().setType(VMOpType.VM_OPNONE);
+ curCmd.getOp2().setType(VMOpType.VM_OPNONE);
+
+ // for (int i=0;i<prg.getCmdCount();i++)
+ // {
+ // VM_PreparedCommand *Cmd=&Prg->Cmd[I];
+ // if (Cmd->Op1.Addr==NULL)
+ // Cmd->Op1.Addr=&Cmd->Op1.Data;
+ // if (Cmd->Op2.Addr==NULL)
+ // Cmd->Op2.Addr=&Cmd->Op2.Data;
+ // }
+
+ prg.getCmd().add(curCmd);
+ prg.setCmdCount(prg.getCmdCount()+1);
+ // #ifdef VM_OPTIMIZE
+ if (codeSize != 0) {
+ optimize(prg);
+ }
+ }
+
+ private void decodeArg(VMPreparedOperand op, boolean byteMode) {
+ int data = fgetbits();
+ if ((data & 0x8000) != 0) {
+ op.setType(VMOpType.VM_OPREG);
+ op.setData((data >> 12) & 7);
+ op.setOffset(op.getData());
+ faddbits(4);
+ } else {
+ if ((data & 0xc000) == 0) {
+ op.setType(VMOpType.VM_OPINT);
+ if (byteMode) {
+ op.setData((data >> 6) & 0xff);
+ faddbits(10);
+ } else {
+ faddbits(2);
+ op.setData(ReadData(this));
+ }
+ } else {
+ op.setType(VMOpType.VM_OPREGMEM);
+ if ((data & 0x2000) == 0) {
+ op.setData((data >> 10) & 7);
+ op.setOffset(op.getData());
+ op.setBase(0);
+ faddbits(6);
+ } else {
+ if ((data & 0x1000) == 0) {
+ op.setData((data >> 9) & 7);
+ op.setOffset(op.getData());
+ faddbits(7);
+ } else {
+ op.setData(0);
+ faddbits(4);
+ }
+ op.setBase(ReadData(this));
+ }
+ }
+ }
+
+ }
+
+ private void optimize(VMPreparedProgram prg) {
+ List<VMPreparedCommand> commands = prg.getCmd();
+
+ for (VMPreparedCommand cmd : commands) {
+ switch (cmd.getOpCode()) {
+ case VM_MOV:
+ cmd.setOpCode(cmd.isByteMode() ? VMCommands.VM_MOVB
+ : VMCommands.VM_MOVD);
+ continue;
+ case VM_CMP:
+ cmd.setOpCode(cmd.isByteMode() ? VMCommands.VM_CMPB
+ : VMCommands.VM_CMPD);
+ continue;
+ }
+ if ((VMCmdFlags.VM_CmdFlags[cmd.getOpCode().getVMCommand()] & VMCmdFlags.VMCF_CHFLAGS) == 0) {
+ continue;
+ }
+ boolean flagsRequired = false;
+
+ for (int i = commands.indexOf(cmd) + 1; i < commands.size(); i++) {
+ int flags = VMCmdFlags.VM_CmdFlags[commands.get(i).getOpCode()
+ .getVMCommand()];
+ if ((flags & (VMCmdFlags.VMCF_JUMP | VMCmdFlags.VMCF_PROC | VMCmdFlags.VMCF_USEFLAGS)) != 0) {
+ flagsRequired = true;
+ break;
+ }
+ if ((flags & VMCmdFlags.VMCF_CHFLAGS) != 0) {
+ break;
+ }
+ }
+ if (flagsRequired) {
+ continue;
+ }
+ switch (cmd.getOpCode()) {
+ case VM_ADD:
+ cmd.setOpCode(cmd.isByteMode() ? VMCommands.VM_ADDB
+ : VMCommands.VM_ADDD);
+ continue;
+ case VM_SUB:
+ cmd.setOpCode(cmd.isByteMode() ? VMCommands.VM_SUBB
+ : VMCommands.VM_SUBD);
+ continue;
+ case VM_INC:
+ cmd.setOpCode(cmd.isByteMode() ? VMCommands.VM_INCB
+ : VMCommands.VM_INCD);
+ continue;
+ case VM_DEC:
+ cmd.setOpCode(cmd.isByteMode() ? VMCommands.VM_DECB
+ : VMCommands.VM_DECD);
+ continue;
+ case VM_NEG:
+ cmd.setOpCode(cmd.isByteMode() ? VMCommands.VM_NEGB
+ : VMCommands.VM_NEGD);
+ continue;
+ }
+ }
+
+ }
+
+ public static int ReadData(BitInput rarVM) {
+ int data = rarVM.fgetbits();
+ switch (data & 0xc000) {
+ case 0:
+ rarVM.faddbits(6);
+ return ((data >> 10) & 0xf);
+ case 0x4000:
+ if ((data & 0x3c00) == 0) {
+ data = 0xffffff00 | ((data >> 2) & 0xff);
+ rarVM.faddbits(14);
+ } else {
+ data = (data >> 6) & 0xff;
+ rarVM.faddbits(10);
+ }
+ return (data);
+ case 0x8000:
+ rarVM.faddbits(2);
+ data = rarVM.fgetbits();
+ rarVM.faddbits(16);
+ return (data);
+ default:
+ rarVM.faddbits(2);
+ data = (rarVM.fgetbits() << 16);
+ rarVM.faddbits(16);
+ data |= rarVM.fgetbits();
+ rarVM.faddbits(16);
+ return (data);
+ }
+ }
+
+ private VMStandardFilters IsStandardFilter(byte[] code, int codeSize) {
+ VMStandardFilterSignature stdList[]={
+ new VMStandardFilterSignature(53, 0xad576887, VMStandardFilters.VMSF_E8),
+ new VMStandardFilterSignature(57, 0x3cd7e57e, VMStandardFilters.VMSF_E8E9),
+ new VMStandardFilterSignature(120, 0x3769893f, VMStandardFilters.VMSF_ITANIUM),
+ new VMStandardFilterSignature(29, 0x0e06077d, VMStandardFilters.VMSF_DELTA),
+ new VMStandardFilterSignature(149, 0x1c2c5dc8, VMStandardFilters.VMSF_RGB),
+ new VMStandardFilterSignature(216, 0xbc85e701, VMStandardFilters.VMSF_AUDIO),
+ new VMStandardFilterSignature(40, 0x46b9c560, VMStandardFilters.VMSF_UPCASE)
+ };
+ int CodeCRC = RarCRC.checkCrc(0xffffffff,code,0,code.length)^0xffffffff;
+ for (int i=0;i<stdList.length;i++){
+ if (stdList[i].getCRC()==CodeCRC && stdList[i].getLength()==code.length){
+ return(stdList[i].getType());
+ }
+
+ }
+ return(VMStandardFilters.VMSF_NONE);
+ }
+
+ private void ExecuteStandardFilter(VMStandardFilters filterType) {
+ switch(filterType)
+ {
+ case VMSF_E8:
+ case VMSF_E8E9:
+ {
+ int dataSize=R[4];
+ long fileOffset=R[6]&0xFFffFFff;
+
+ if (dataSize>=VM_GLOBALMEMADDR){
+ break;
+ }
+ int fileSize=0x1000000;
+ byte cmpByte2=(byte) ((filterType==VMStandardFilters.VMSF_E8E9) ? 0xe9:0xe8);
+ for (int curPos=0;curPos<dataSize-4;)
+ {
+ byte curByte=mem[curPos++];
+ if (curByte==0xe8 || curByte==cmpByte2)
+ {
+// #ifdef PRESENT_INT32
+// sint32 Offset=CurPos+FileOffset;
+// sint32 Addr=GET_VALUE(false,Data);
+// if (Addr<0)
+// {
+// if (Addr+Offset>=0)
+// SET_VALUE(false,Data,Addr+FileSize);
+// }
+// else
+// if (Addr<FileSize)
+// SET_VALUE(false,Data,Addr-Offset);
+// #else
+ long offset=curPos+fileOffset;
+ long Addr=getValue(false,mem,curPos);
+ if ((Addr & 0x80000000)!=0)
+ {
+ if (((Addr+offset) & 0x80000000)==0)
+ setValue(false,mem,curPos,(int)Addr+fileSize);
+ }
+ else {
+ if (((Addr-fileSize) & 0x80000000)!=0){
+ setValue(false,mem,curPos,(int)(Addr-offset));
+ }
+ }
+// #endif
+ curPos+=4;
+ }
+ }
+ }
+ break;
+ case VMSF_ITANIUM:
+ {
+
+ int dataSize=R[4];
+ long fileOffset=R[6]&0xFFffFFff;
+
+ if (dataSize>=VM_GLOBALMEMADDR){
+ break;
+ }
+ int curPos=0;
+ final byte Masks[]={4,4,6,6,0,0,7,7,4,4,0,0,4,4,0,0};
+ fileOffset>>>=4;
+
+ while (curPos<dataSize-21)
+ {
+ int Byte=(mem[curPos]&0x1f)-0x10;
+ if (Byte>=0)
+ {
+
+ byte cmdMask=Masks[Byte];
+ if (cmdMask!=0)
+ for (int i=0;i<=2;i++)
+ if ((cmdMask & (1<<i))!=0)
+ {
+ int startPos=i*41+5;
+ int opType=filterItanium_GetBits(curPos,startPos+37,4);
+ if (opType==5)
+ {
+ int offset=filterItanium_GetBits(curPos,startPos+13,20);
+ filterItanium_SetBits(curPos,(int)(offset-fileOffset)&0xfffff,startPos+13,20);
+ }
+ }
+ }
+ curPos+=16;
+ fileOffset++;
+ }
+ }
+ break;
+ case VMSF_DELTA:
+ {
+ int dataSize=R[4]&0xFFffFFff;
+ int channels=R[0]&0xFFffFFff;
+ int srcPos=0;
+ int border=(dataSize*2) &0xFFffFFff;
+ setValue(false,mem,VM_GLOBALMEMADDR+0x20,(int)dataSize);
+ if (dataSize>=VM_GLOBALMEMADDR/2){
+ break;
+ }
+// bytes from same channels are grouped to continual data blocks,
+// so we need to place them back to their interleaving positions
+
+ for (int curChannel=0;curChannel<channels;curChannel++)
+ {
+ byte PrevByte=0;
+ for (int destPos=dataSize+curChannel;destPos<border;destPos+=channels){
+ mem[destPos]=(PrevByte-=mem[srcPos++]);
+ }
+
+ }
+ }
+ break;
+ case VMSF_RGB:
+ {
+ // byte *SrcData=Mem,*DestData=SrcData+DataSize;
+ int dataSize=R[4],width=R[0]-3,posR=R[1];
+ int channels=3;
+ int srcPos = 0;
+ int destDataPos = dataSize;
+ setValue(false,mem,VM_GLOBALMEMADDR+0x20,dataSize);
+ if (dataSize>=VM_GLOBALMEMADDR/2 || posR<0){
+ break;
+ }
+ for (int curChannel=0;curChannel<channels;curChannel++)
+ {
+ long prevByte=0;
+
+ for (int i=curChannel;i<dataSize;i+=channels)
+ {
+ long predicted;
+ int upperPos=i-width;
+ if (upperPos>=3)
+ {
+ int upperDataPos=destDataPos+upperPos;
+ int upperByte=mem[(int)upperDataPos]&0xff;
+ int upperLeftByte=mem[upperDataPos-3]&0xff;
+ predicted=prevByte+upperByte-upperLeftByte;
+ int pa=Math.abs((int)(predicted-prevByte));
+ int pb=Math.abs((int)(predicted-upperByte));
+ int pc=Math.abs((int)(predicted-upperLeftByte));
+ if (pa<=pb && pa<=pc){
+ predicted=prevByte;
+ }
+ else{
+ if (pb<=pc){
+ predicted=upperByte;
+ }
+ else{
+ predicted=upperLeftByte;
+ }
+ }
+ }
+ else{
+ predicted=prevByte;
+ }
+
+ prevByte=(predicted-mem[srcPos++]&0xff)&0xff;
+ mem[destDataPos+i]=(byte)(prevByte&0xff);
+
+ }
+ }
+ for (int i=posR,border=dataSize-2;i<border;i+=3)
+ {
+ byte G=mem[destDataPos+i+1];
+ mem[destDataPos+i]+=G;
+ mem[destDataPos+i+2]+=G;
+ }
+ }
+ break;
+ case VMSF_AUDIO:
+ {
+ int dataSize=R[4],channels=R[0];
+ int srcPos = 0;
+ int destDataPos = dataSize;
+ //byte *SrcData=Mem,*DestData=SrcData+DataSize;
+ setValue(false,mem,VM_GLOBALMEMADDR+0x20,dataSize);
+ if (dataSize>=VM_GLOBALMEMADDR/2){
+ break;
+ }
+ for (int curChannel=0;curChannel<channels;curChannel++)
+ {
+ long prevByte=0;
+ long prevDelta=0;
+ long Dif[] = new long[7];
+ int D1=0,D2=0,D3;
+ int K1=0,K2=0,K3=0;
+
+ for (int i=curChannel,byteCount=0;i<dataSize;i+=channels,byteCount++)
+ {
+ D3=D2;
+ D2=(int)prevDelta-D1;
+ D1=(int)prevDelta;
+
+ long predicted=8*prevByte+K1*D1+K2*D2+K3*D3;
+ predicted=(predicted>>>3) & 0xff;
+
+ long curByte=mem[srcPos++]&0xff;
+
+ predicted = (predicted - curByte)&UINT_MASK;
+ mem[destDataPos+i]=(byte)predicted;
+ prevDelta=(byte)(predicted-prevByte);
+ prevByte=predicted;
+
+ int D=((byte)curByte)<<3;
+
+ Dif[0]+=Math.abs(D);
+ Dif[1]+=Math.abs(D-D1);
+ Dif[2]+=Math.abs(D+D1);
+ Dif[3]+=Math.abs(D-D2);
+ Dif[4]+=Math.abs(D+D2);
+ Dif[5]+=Math.abs(D-D3);
+ Dif[6]+=Math.abs(D+D3);
+
+ if ((byteCount & 0x1f)==0)
+ {
+ long minDif=Dif[0], numMinDif=0;
+ Dif[0]=0;
+ for (int j=1;j<Dif.length;j++)
+ {
+ if (Dif[j]<minDif)
+ {
+ minDif=Dif[j];
+ numMinDif=j;
+ }
+ Dif[j]=0;
+ }
+ switch((int)numMinDif)
+ {
+ case 1: if (K1>=-16) K1--; break;
+ case 2: if (K1 < 16) K1++; break;
+ case 3: if (K2>=-16) K2--; break;
+ case 4: if (K2 < 16) K2++; break;
+ case 5: if (K3>=-16) K3--; break;
+ case 6: if (K3 < 16) K3++; break;
+ }
+ }
+ }
+ }
+ }
+ break;
+ case VMSF_UPCASE:
+ {
+ int dataSize=R[4],srcPos=0,destPos=dataSize;
+ if (dataSize>=VM_GLOBALMEMADDR/2){
+ break;
+ }
+ while (srcPos<dataSize)
+ {
+ byte curByte=mem[srcPos++];
+ if (curByte==2 && (curByte=mem[srcPos++])!=2){
+ curByte-=32;
+ }
+ mem[destPos++]=curByte;
+ }
+ setValue(false,mem,VM_GLOBALMEMADDR+0x1c,destPos-dataSize);
+ setValue(false,mem,VM_GLOBALMEMADDR+0x20,dataSize);
+ }
+ break;
+ }
+
+ }
+
+ private void filterItanium_SetBits(int curPos, int bitField, int bitPos, int bitCount) {
+ int inAddr=bitPos/8;
+ int inBit=bitPos&7;
+ int andMask=0xffffffff>>>(32-bitCount);
+ andMask=~(andMask<<inBit);
+
+ bitField<<=inBit;
+
+ for (int i=0;i<4;i++)
+ {
+ mem[curPos+inAddr+i]&=andMask;
+ mem[curPos+inAddr+i]|=bitField;
+ andMask=(andMask>>>8)|0xff000000;
+ bitField>>>=8;
+ }
+
+ }
+
+ private int filterItanium_GetBits(int curPos, int bitPos, int bitCount) {
+ int inAddr=bitPos/8;
+ int inBit=bitPos&7;
+ int bitField=(int)(mem[curPos+inAddr++]&0xff);
+ bitField|=(int) ((mem[curPos+inAddr++]&0xff) << 8);
+ bitField|=(int) ((mem[curPos+inAddr++]&0xff) << 16);
+ bitField|=(int) ((mem[curPos+inAddr]&0xff) << 24);
+ bitField >>>= inBit;
+ return(bitField & (0xffffffff>>>(32-bitCount)));
+ }
+
+
+ public void setMemory(int pos,byte[] data,int offset,int dataSize)
+ {
+ if (pos<VM_MEMSIZE){ //&& data!=Mem+Pos)
+ //memmove(Mem+Pos,Data,Min(DataSize,VM_MEMSIZE-Pos));
+ for (int i = 0; i < Math.min(data.length-offset,dataSize); i++) {
+ if((VM_MEMSIZE-pos)<i){
+ break;
+ }
+ mem[pos+i] = data[offset+i];
+ }
+ }
+ }
+
+
+}
+
+// \ No newline at end of file
diff --git a/src/com/github/junrar/unpack/vm/VMCmdFlags.java b/src/com/github/junrar/unpack/vm/VMCmdFlags.java
new file mode 100644
index 0000000..2ccfa46
--- /dev/null
+++ b/src/com/github/junrar/unpack/vm/VMCmdFlags.java
@@ -0,0 +1,81 @@
+/*
+ * Copyright (c) 2007 innoSysTec (R) GmbH, Germany. All rights reserved.
+ * Original author: Edmund Wagner
+ * Creation date: 01.06.2007
+ *
+ * Source: $HeadURL$
+ * Last changed: $LastChangedDate$
+ *
+ * the unrar licence applies to all junrar source and binary distributions
+ * you are not allowed to use this source to re-create the RAR compression algorithm
+ *
+ * Here some html entities which can be used for escaping javadoc tags:
+ * "&": "&#038;" or "&amp;"
+ * "<": "&#060;" or "&lt;"
+ * ">": "&#062;" or "&gt;"
+ * "@": "&#064;"
+ */
+package com.github.junrar.unpack.vm;
+
+/**
+ * DOCUMENT ME
+ *
+ * @author $LastChangedBy$
+ * @version $LastChangedRevision$
+ */
+public class VMCmdFlags {
+ public static final byte VMCF_OP0 = 0;
+ public static final byte VMCF_OP1 = 1;
+ public static final byte VMCF_OP2 = 2;
+ public static final byte VMCF_OPMASK = 3;
+ public static final byte VMCF_BYTEMODE = 4;
+ public static final byte VMCF_JUMP = 8;
+ public static final byte VMCF_PROC = 16;
+ public static final byte VMCF_USEFLAGS = 32;
+ public static final byte VMCF_CHFLAGS = 64;
+
+ public static byte VM_CmdFlags[]=
+ {
+ /* VM_MOV */ VMCF_OP2 | VMCF_BYTEMODE ,
+ /* VM_CMP */ VMCF_OP2 | VMCF_BYTEMODE | VMCF_CHFLAGS ,
+ /* VM_ADD */ VMCF_OP2 | VMCF_BYTEMODE | VMCF_CHFLAGS ,
+ /* VM_SUB */ VMCF_OP2 | VMCF_BYTEMODE | VMCF_CHFLAGS ,
+ /* VM_JZ */ VMCF_OP1 | VMCF_JUMP | VMCF_USEFLAGS ,
+ /* VM_JNZ */ VMCF_OP1 | VMCF_JUMP | VMCF_USEFLAGS ,
+ /* VM_INC */ VMCF_OP1 | VMCF_BYTEMODE | VMCF_CHFLAGS ,
+ /* VM_DEC */ VMCF_OP1 | VMCF_BYTEMODE | VMCF_CHFLAGS ,
+ /* VM_JMP */ VMCF_OP1 | VMCF_JUMP ,
+ /* VM_XOR */ VMCF_OP2 | VMCF_BYTEMODE | VMCF_CHFLAGS ,
+ /* VM_AND */ VMCF_OP2 | VMCF_BYTEMODE | VMCF_CHFLAGS ,
+ /* VM_OR */ VMCF_OP2 | VMCF_BYTEMODE | VMCF_CHFLAGS ,
+ /* VM_TEST */ VMCF_OP2 | VMCF_BYTEMODE | VMCF_CHFLAGS ,
+ /* VM_JS */ VMCF_OP1 | VMCF_JUMP | VMCF_USEFLAGS ,
+ /* VM_JNS */ VMCF_OP1 | VMCF_JUMP | VMCF_USEFLAGS ,
+ /* VM_JB */ VMCF_OP1 | VMCF_JUMP | VMCF_USEFLAGS ,
+ /* VM_JBE */ VMCF_OP1 | VMCF_JUMP | VMCF_USEFLAGS ,
+ /* VM_JA */ VMCF_OP1 | VMCF_JUMP | VMCF_USEFLAGS ,
+ /* VM_JAE */ VMCF_OP1 | VMCF_JUMP | VMCF_USEFLAGS ,
+ /* VM_PUSH */ VMCF_OP1 ,
+ /* VM_POP */ VMCF_OP1 ,
+ /* VM_CALL */ VMCF_OP1 | VMCF_PROC ,
+ /* VM_RET */ VMCF_OP0 | VMCF_PROC ,
+ /* VM_NOT */ VMCF_OP1 | VMCF_BYTEMODE ,
+ /* VM_SHL */ VMCF_OP2 | VMCF_BYTEMODE | VMCF_CHFLAGS ,
+ /* VM_SHR */ VMCF_OP2 | VMCF_BYTEMODE | VMCF_CHFLAGS ,
+ /* VM_SAR */ VMCF_OP2 | VMCF_BYTEMODE | VMCF_CHFLAGS ,
+ /* VM_NEG */ VMCF_OP1 | VMCF_BYTEMODE | VMCF_CHFLAGS ,
+ /* VM_PUSHA */ VMCF_OP0 ,
+ /* VM_POPA */ VMCF_OP0 ,
+ /* VM_PUSHF */ VMCF_OP0 | VMCF_USEFLAGS ,
+ /* VM_POPF */ VMCF_OP0 | VMCF_CHFLAGS ,
+ /* VM_MOVZX */ VMCF_OP2 ,
+ /* VM_MOVSX */ VMCF_OP2 ,
+ /* VM_XCHG */ VMCF_OP2 | VMCF_BYTEMODE ,
+ /* VM_MUL */ VMCF_OP2 | VMCF_BYTEMODE ,
+ /* VM_DIV */ VMCF_OP2 | VMCF_BYTEMODE ,
+ /* VM_ADC */ VMCF_OP2 | VMCF_BYTEMODE | VMCF_USEFLAGS | VMCF_CHFLAGS ,
+ /* VM_SBB */ VMCF_OP2 | VMCF_BYTEMODE | VMCF_USEFLAGS | VMCF_CHFLAGS ,
+ /* VM_PRINT */ VMCF_OP0
+ };
+
+}
diff --git a/src/com/github/junrar/unpack/vm/VMCommands.java b/src/com/github/junrar/unpack/vm/VMCommands.java
new file mode 100644
index 0000000..e52911a
--- /dev/null
+++ b/src/com/github/junrar/unpack/vm/VMCommands.java
@@ -0,0 +1,226 @@
+/*
+ * Copyright (c) 2007 innoSysTec (R) GmbH, Germany. All rights reserved.
+ * Original author: Edmund Wagner
+ * Creation date: 31.05.2007
+ *
+ * Source: $HeadURL$
+ * Last changed: $LastChangedDate$
+ *
+ * the unrar licence applies to all junrar source and binary distributions
+ * you are not allowed to use this source to re-create the RAR compression algorithm
+ *
+ * Here some html entities which can be used for escaping javadoc tags:
+ * "&": "&#038;" or "&amp;"
+ * "<": "&#060;" or "&lt;"
+ * ">": "&#062;" or "&gt;"
+ * "@": "&#064;"
+ */
+package com.github.junrar.unpack.vm;
+
+/**
+ * DOCUMENT ME
+ *
+ * @author $LastChangedBy$
+ * @version $LastChangedRevision$
+ */
+public enum VMCommands {
+ VM_MOV(0), VM_CMP(1), VM_ADD(2), VM_SUB(3), VM_JZ(4), VM_JNZ(5), VM_INC(6), VM_DEC(
+ 7), VM_JMP(8), VM_XOR(9), VM_AND(10), VM_OR(11), VM_TEST(12), VM_JS(
+ 13), VM_JNS(14), VM_JB(15), VM_JBE(16), VM_JA(17), VM_JAE(18), VM_PUSH(
+ 19), VM_POP(20), VM_CALL(21), VM_RET(22), VM_NOT(23), VM_SHL(24), VM_SHR(
+ 25), VM_SAR(26), VM_NEG(27), VM_PUSHA(28), VM_POPA(29), VM_PUSHF(30), VM_POPF(
+ 31), VM_MOVZX(32), VM_MOVSX(33), VM_XCHG(34), VM_MUL(35), VM_DIV(36), VM_ADC(
+ 37), VM_SBB(38), VM_PRINT(39),
+
+ // #ifdef VM_OPTIMIZE
+ VM_MOVB(40), VM_MOVD(41), VM_CMPB(42), VM_CMPD(43),
+
+ VM_ADDB(44), VM_ADDD(45), VM_SUBB(46), VM_SUBD(47), VM_INCB(48), VM_INCD(49), VM_DECB(
+ 50), VM_DECD(51), VM_NEGB(52), VM_NEGD(53),
+ // #endif*/
+
+ VM_STANDARD(54);
+
+ private int vmCommand;
+
+ private VMCommands(int vmCommand) {
+ this.vmCommand = vmCommand;
+ }
+
+ public int getVMCommand() {
+ return vmCommand;
+ }
+
+ public boolean equals(int vmCommand) {
+ return this.vmCommand == vmCommand;
+ }
+
+ public static VMCommands findVMCommand(int vmCommand) {
+ if (VM_MOV.equals(vmCommand)) {
+ return VM_MOV;
+ }
+ if (VM_CMP.equals(vmCommand)) {
+ return VM_CMP;
+ }
+ if (VM_ADD.equals(vmCommand)) {
+ return VM_ADD;
+ }
+ if (VM_SUB.equals(vmCommand)) {
+ return VM_SUB;
+ }
+ if (VM_JZ.equals(vmCommand)) {
+ return VM_JZ;
+ }
+ if (VM_JNZ.equals(vmCommand)) {
+ return VM_JNZ;
+ }
+ if (VM_INC.equals(vmCommand)) {
+ return VM_INC;
+ }
+ if (VM_DEC.equals(vmCommand)) {
+ return VM_DEC;
+ }
+ if (VM_JMP.equals(vmCommand)) {
+ return VM_JMP;
+ }
+ if (VM_XOR.equals(vmCommand)) {
+ return VM_XOR;
+ }
+ if (VM_AND.equals(vmCommand)) {
+ return VM_AND;
+ }
+ if (VM_OR.equals(vmCommand)) {
+ return VM_OR;
+ }
+ if (VM_TEST.equals(vmCommand)) {
+ return VM_TEST;
+ }
+ if (VM_JS.equals(vmCommand)) {
+ return VM_JS;
+ }
+ if (VM_JNS.equals(vmCommand)) {
+ return VM_JNS;
+ }
+ if (VM_JB.equals(vmCommand)) {
+ return VM_JB;
+ }
+ if (VM_JBE.equals(vmCommand)) {
+ return VM_JBE;
+ }
+ if (VM_JA.equals(vmCommand)) {
+ return VM_JA;
+ }
+ if (VM_JAE.equals(vmCommand)) {
+ return VM_JAE;
+ }
+ if (VM_PUSH.equals(vmCommand)) {
+ return VM_PUSH;
+ }
+ if (VM_POP.equals(vmCommand)) {
+ return VM_POP;
+ }
+ if (VM_CALL.equals(vmCommand)) {
+ return VM_CALL;
+ }
+ if (VM_RET.equals(vmCommand)) {
+ return VM_RET;
+ }
+ if (VM_NOT.equals(vmCommand)) {
+ return VM_NOT;
+ }
+ if (VM_SHL.equals(vmCommand)) {
+ return VM_SHL;
+ }
+ if (VM_SHR.equals(vmCommand)) {
+ return VM_SHR;
+ }
+ if (VM_SAR.equals(vmCommand)) {
+ return VM_SAR;
+ }
+ if (VM_NEG.equals(vmCommand)) {
+ return VM_NEG;
+ }
+ if (VM_PUSHA.equals(vmCommand)) {
+ return VM_PUSHA;
+ }
+ if (VM_POPA.equals(vmCommand)) {
+ return VM_POPA;
+ }
+ if (VM_PUSHF.equals(vmCommand)) {
+ return VM_PUSHF;
+ }
+ if (VM_POPF.equals(vmCommand)) {
+ return VM_POPF;
+ }
+ if (VM_MOVZX.equals(vmCommand)) {
+ return VM_MOVZX;
+ }
+ if (VM_MOVSX.equals(vmCommand)) {
+ return VM_MOVSX;
+ }
+ if (VM_XCHG.equals(vmCommand)) {
+ return VM_XCHG;
+ }
+ if (VM_MUL.equals(vmCommand)) {
+ return VM_MUL;
+ }
+ if (VM_DIV.equals(vmCommand)) {
+ return VM_DIV;
+ }
+ if (VM_ADC.equals(vmCommand)) {
+ return VM_ADC;
+ }
+ if (VM_SBB.equals(vmCommand)) {
+ return VM_SBB;
+ }
+ if (VM_PRINT.equals(vmCommand)) {
+ return VM_PRINT;
+ }
+ if (VM_MOVB.equals(vmCommand)) {
+ return VM_MOVB;
+ }
+ if (VM_MOVD.equals(vmCommand)) {
+ return VM_MOVD;
+ }
+ if (VM_CMPB.equals(vmCommand)) {
+ return VM_CMPB;
+ }
+ if (VM_CMPD.equals(vmCommand)) {
+ return VM_CMPD;
+ }
+ if (VM_ADDB.equals(vmCommand)) {
+ return VM_ADDB;
+ }
+ if (VM_ADDD.equals(vmCommand)) {
+ return VM_ADDD;
+ }
+ if (VM_SUBB.equals(vmCommand)) {
+ return VM_SUBB;
+ }
+ if (VM_SUBD.equals(vmCommand)) {
+ return VM_SUBD;
+ }
+ if (VM_INCB.equals(vmCommand)) {
+ return VM_INCB;
+ }
+ if (VM_INCD.equals(vmCommand)) {
+ return VM_INCD;
+ }
+ if (VM_DECB.equals(vmCommand)) {
+ return VM_DECB;
+ }
+ if (VM_DECD.equals(vmCommand)) {
+ return VM_DECD;
+ }
+ if (VM_NEGB.equals(vmCommand)) {
+ return VM_NEGB;
+ }
+ if (VM_NEGD.equals(vmCommand)) {
+ return VM_NEGD;
+ }
+ if (VM_STANDARD.equals(vmCommand)) {
+ return VM_STANDARD;
+ }
+ return null;
+ }
+}
diff --git a/src/com/github/junrar/unpack/vm/VMFlags.java b/src/com/github/junrar/unpack/vm/VMFlags.java
new file mode 100644
index 0000000..d2b997b
--- /dev/null
+++ b/src/com/github/junrar/unpack/vm/VMFlags.java
@@ -0,0 +1,79 @@
+/*
+ * Copyright (c) 2007 innoSysTec (R) GmbH, Germany. All rights reserved.
+ * Original author: Edmund Wagner
+ * Creation date: 31.05.2007
+ *
+ * Source: $HeadURL$
+ * Last changed: $LastChangedDate$
+ *
+ * the unrar licence applies to all junrar source and binary distributions
+ * you are not allowed to use this source to re-create the RAR compression algorithm
+ *
+ * Here some html entities which can be used for escaping javadoc tags:
+ * "&": "&#038;" or "&amp;"
+ * "<": "&#060;" or "&lt;"
+ * ">": "&#062;" or "&gt;"
+ * "@": "&#064;"
+ */
+package com.github.junrar.unpack.vm;
+
+/**
+ * DOCUMENT ME
+ *
+ * @author $LastChangedBy$
+ * @version $LastChangedRevision$
+ */
+public enum VMFlags {
+ /**
+ *
+ */
+ VM_FC (1),
+ /**
+ *
+ */
+ VM_FZ (2),
+ /**
+ *
+ */
+ VM_FS (0x80000000);
+
+ private int flag;
+
+ private VMFlags(int flag){
+ this.flag = flag;
+ }
+
+ /**
+ * Returns the VMFlags Type of the given int or null
+ * @param flag as int
+ * @return VMFlag of the int value
+ */
+ public static VMFlags findFlag(int flag){
+ if(VM_FC.equals(flag)){
+ return VM_FC;
+ }
+ if(VM_FS.equals(flag)){
+ return VM_FS;
+ }
+ if(VM_FZ.equals(flag)){
+ return VM_FZ;
+ }
+ return null;
+ }
+
+ /**
+ * Returns true if the flag provided as int is equal to the enum
+ * @param flag
+ * @return returns true if the flag is equal to the enum
+ */
+ public boolean equals(int flag){
+ return this.flag == flag;
+ }
+ /**
+ * @return the flag as int
+ */
+ public int getFlag() {
+ return flag;
+ }
+
+}
diff --git a/src/com/github/junrar/unpack/vm/VMOpType.java b/src/com/github/junrar/unpack/vm/VMOpType.java
new file mode 100644
index 0000000..1b8bc97
--- /dev/null
+++ b/src/com/github/junrar/unpack/vm/VMOpType.java
@@ -0,0 +1,66 @@
+/*
+ * Copyright (c) 2007 innoSysTec (R) GmbH, Germany. All rights reserved.
+ * Original author: Edmund Wagner
+ * Creation date: 31.05.2007
+ *
+ * Source: $HeadURL$
+ * Last changed: $LastChangedDate$
+ *
+ * the unrar licence applies to all junrar source and binary distributions
+ * you are not allowed to use this source to re-create the RAR compression algorithm
+ *
+ * Here some html entities which can be used for escaping javadoc tags:
+ * "&": "&#038;" or "&amp;"
+ * "<": "&#060;" or "&lt;"
+ * ">": "&#062;" or "&gt;"
+ * "@": "&#064;"
+ */
+package com.github.junrar.unpack.vm;
+
+/**
+ * DOCUMENT ME
+ *
+ * @author $LastChangedBy$
+ * @version $LastChangedRevision$
+ */
+public enum VMOpType {
+ VM_OPREG (0),
+ VM_OPINT (1),
+ VM_OPREGMEM (2),
+ VM_OPNONE (3);
+
+ private int opType;
+
+ private VMOpType(int opType){
+ this.opType=opType;
+ }
+
+ public int getOpType() {
+ return opType;
+ }
+
+
+ public boolean equals(int opType){
+ return this.opType == opType;
+ }
+ public static VMOpType findOpType(int opType){
+
+ if (VM_OPREG.equals(opType)) {
+ return VM_OPREG;
+ }
+
+
+ if (VM_OPINT.equals(opType)) {
+ return VM_OPINT;
+ }
+
+ if (VM_OPREGMEM.equals(opType)) {
+ return VM_OPREGMEM;
+ }
+
+ if (VM_OPNONE.equals(opType)) {
+ return VM_OPNONE;
+ }
+ return null;
+ }
+}
diff --git a/src/com/github/junrar/unpack/vm/VMPreparedCommand.java b/src/com/github/junrar/unpack/vm/VMPreparedCommand.java
new file mode 100644
index 0000000..74cc86d
--- /dev/null
+++ b/src/com/github/junrar/unpack/vm/VMPreparedCommand.java
@@ -0,0 +1,57 @@
+/*
+ * Copyright (c) 2007 innoSysTec (R) GmbH, Germany. All rights reserved.
+ * Original author: Edmund Wagner
+ * Creation date: 31.05.2007
+ *
+ * Source: $HeadURL$
+ * Last changed: $LastChangedDate$
+ *
+ * the unrar licence applies to all junrar source and binary distributions
+ * you are not allowed to use this source to re-create the RAR compression algorithm
+ *
+ * Here some html entities which can be used for escaping javadoc tags:
+ * "&": "&#038;" or "&amp;"
+ * "<": "&#060;" or "&lt;"
+ * ">": "&#062;" or "&gt;"
+ * "@": "&#064;"
+ */
+package com.github.junrar.unpack.vm;
+
+/**
+ * DOCUMENT ME
+ *
+ * @author $LastChangedBy$
+ * @version $LastChangedRevision$
+ */
+public class VMPreparedCommand {
+ private VMCommands OpCode;
+ private boolean ByteMode;
+ private VMPreparedOperand Op1 = new VMPreparedOperand();
+ private VMPreparedOperand Op2 = new VMPreparedOperand();
+
+ public boolean isByteMode() {
+ return ByteMode;
+ }
+ public void setByteMode(boolean byteMode) {
+ ByteMode = byteMode;
+ }
+ public VMPreparedOperand getOp1() {
+ return Op1;
+ }
+ public void setOp1(VMPreparedOperand op1) {
+ Op1 = op1;
+ }
+ public VMPreparedOperand getOp2() {
+ return Op2;
+ }
+ public void setOp2(VMPreparedOperand op2) {
+ Op2 = op2;
+ }
+ public VMCommands getOpCode() {
+ return OpCode;
+ }
+ public void setOpCode(VMCommands opCode) {
+ OpCode = opCode;
+ }
+
+}
diff --git a/src/com/github/junrar/unpack/vm/VMPreparedOperand.java b/src/com/github/junrar/unpack/vm/VMPreparedOperand.java
new file mode 100644
index 0000000..f6aeff4
--- /dev/null
+++ b/src/com/github/junrar/unpack/vm/VMPreparedOperand.java
@@ -0,0 +1,58 @@
+/*
+ * Copyright (c) 2007 innoSysTec (R) GmbH, Germany. All rights reserved.
+ * Original author: Edmund Wagner
+ * Creation date: 31.05.2007
+ *
+ * Source: $HeadURL$
+ * Last changed: $LastChangedDate$
+ *
+ * the unrar licence applies to all junrar source and binary distributions
+ * you are not allowed to use this source to re-create the RAR compression algorithm
+ *
+ * Here some html entities which can be used for escaping javadoc tags:
+ * "&": "&#038;" or "&amp;"
+ * "<": "&#060;" or "&lt;"
+ * ">": "&#062;" or "&gt;"
+ * "@": "&#064;"
+ */
+package com.github.junrar.unpack.vm;
+
+/**
+ * DOCUMENT ME
+ *
+ * @author $LastChangedBy$
+ * @version $LastChangedRevision$
+ */
+public class VMPreparedOperand {
+ private VMOpType Type;
+ private int Data;
+ private int Base;
+ private int offset;
+
+
+ public int getBase() {
+ return Base;
+ }
+ public void setBase(int base) {
+ Base = base;
+ }
+ public int getData() {
+ return Data;
+ }
+ public void setData(int data) {
+ Data = data;
+ }
+ public VMOpType getType() {
+ return Type;
+ }
+ public void setType(VMOpType type) {
+ Type = type;
+ }
+ public int getOffset() {
+ return offset;
+ }
+ public void setOffset(int offset) {
+ this.offset = offset;
+ }
+
+}
diff --git a/src/com/github/junrar/unpack/vm/VMPreparedProgram.java b/src/com/github/junrar/unpack/vm/VMPreparedProgram.java
new file mode 100644
index 0000000..497b4a9
--- /dev/null
+++ b/src/com/github/junrar/unpack/vm/VMPreparedProgram.java
@@ -0,0 +1,127 @@
+/*
+ * Copyright (c) 2007 innoSysTec (R) GmbH, Germany. All rights reserved.
+ * Original author: Edmund Wagner
+ * Creation date: 31.05.2007
+ *
+ * Source: $HeadURL$
+ * Last changed: $LastChangedDate$
+ *
+ * the unrar licence applies to all junrar source and binary distributions
+ * you are not allowed to use this source to re-create the RAR compression algorithm
+ *
+ * Here some html entities which can be used for escaping javadoc tags:
+ * "&": "&#038;" or "&amp;"
+ * "<": "&#060;" or "&lt;"
+ * ">": "&#062;" or "&gt;"
+ * "@": "&#064;"
+ */
+package com.github.junrar.unpack.vm;
+
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Vector;
+
+/**
+ * DOCUMENT ME
+ *
+ * @author $LastChangedBy$
+ * @version $LastChangedRevision$
+ */
+public class VMPreparedProgram
+{
+ private List<VMPreparedCommand> Cmd = new ArrayList<VMPreparedCommand>();
+ private List<VMPreparedCommand> AltCmd =new ArrayList<VMPreparedCommand>();
+ private int CmdCount;
+
+
+
+ private Vector<Byte> GlobalData = new Vector<Byte>();
+ private Vector<Byte> StaticData = new Vector<Byte>(); // static data contained in DB operators
+ private int InitR[] = new int[7];
+
+ private int FilteredDataOffset;
+ private int FilteredDataSize;
+
+ public VMPreparedProgram()
+ {
+ AltCmd=null;
+ }
+
+
+
+ public List<VMPreparedCommand> getAltCmd() {
+ return AltCmd;
+ }
+
+
+
+ public void setAltCmd(List<VMPreparedCommand> altCmd) {
+ AltCmd = altCmd;
+ }
+
+
+
+ public List<VMPreparedCommand> getCmd() {
+ return Cmd;
+ }
+
+ public void setCmd(List<VMPreparedCommand> cmd) {
+ Cmd = cmd;
+ }
+
+ public int getCmdCount() {
+ return CmdCount;
+ }
+
+ public void setCmdCount(int cmdCount) {
+ CmdCount = cmdCount;
+ }
+
+
+
+ public int getFilteredDataOffset() {
+ return FilteredDataOffset;
+ }
+
+
+
+ public void setFilteredDataOffset(int filteredDataOffset) {
+ FilteredDataOffset = filteredDataOffset;
+ }
+
+
+
+ public int getFilteredDataSize() {
+ return FilteredDataSize;
+ }
+
+ public void setFilteredDataSize(int filteredDataSize) {
+ FilteredDataSize = filteredDataSize;
+ }
+
+ public Vector<Byte> getGlobalData() {
+ return GlobalData;
+ }
+
+ public void setGlobalData(Vector<Byte> globalData) {
+ GlobalData = globalData;
+ }
+
+ public int[] getInitR() {
+ return InitR;
+ }
+
+ public void setInitR(int[] initR) {
+ InitR = initR;
+ }
+
+ public Vector<Byte> getStaticData() {
+ return StaticData;
+ }
+
+ public void setStaticData(Vector<Byte> staticData) {
+ StaticData = staticData;
+ }
+
+
+}
diff --git a/src/com/github/junrar/unpack/vm/VMStandardFilterSignature.java b/src/com/github/junrar/unpack/vm/VMStandardFilterSignature.java
new file mode 100644
index 0000000..ca7ab73
--- /dev/null
+++ b/src/com/github/junrar/unpack/vm/VMStandardFilterSignature.java
@@ -0,0 +1,64 @@
+/*
+ * Copyright (c) 2007 innoSysTec (R) GmbH, Germany. All rights reserved.
+ * Original author: Edmund Wagner
+ * Creation date: 04.06.2007
+ *
+ * Source: $HeadURL$
+ * Last changed: $LastChangedDate$
+ *
+ * the unrar licence applies to all junrar source and binary distributions
+ * you are not allowed to use this source to re-create the RAR compression algorithm
+ *
+ * Here some html entities which can be used for escaping javadoc tags:
+ * "&": "&#038;" or "&amp;"
+ * "<": "&#060;" or "&lt;"
+ * ">": "&#062;" or "&gt;"
+ * "@": "&#064;"
+ */
+package com.github.junrar.unpack.vm;
+
+/**
+ * DOCUMENT ME
+ *
+ * @author $LastChangedBy$
+ * @version $LastChangedRevision$
+ */
+public class VMStandardFilterSignature {
+ private int length;
+
+ private int CRC;
+
+ private VMStandardFilters type;
+
+ public VMStandardFilterSignature(int length, int crc, VMStandardFilters type) {
+ super();
+ this.length = length;
+ CRC = crc;
+ this.type = type;
+ }
+
+ public int getCRC() {
+ return CRC;
+ }
+
+ public void setCRC(int crc) {
+ CRC = crc;
+ }
+
+ public int getLength() {
+ return length;
+ }
+
+ public void setLength(int length) {
+ this.length = length;
+ }
+
+ public VMStandardFilters getType() {
+ return type;
+ }
+
+ public void setType(VMStandardFilters type) {
+ this.type = type;
+ }
+
+}
diff --git a/src/com/github/junrar/unpack/vm/VMStandardFilters.java b/src/com/github/junrar/unpack/vm/VMStandardFilters.java
new file mode 100644
index 0000000..ceff170
--- /dev/null
+++ b/src/com/github/junrar/unpack/vm/VMStandardFilters.java
@@ -0,0 +1,79 @@
+/*
+ * Copyright (c) 2007 innoSysTec (R) GmbH, Germany. All rights reserved.
+ * Original author: Edmund Wagner
+ * Creation date: 31.05.2007
+ *
+ * Source: $HeadURL$
+ * Last changed: $LastChangedDate$
+ *
+ * the unrar licence applies to all junrar source and binary distributions
+ * you are not allowed to use this source to re-create the RAR compression algorithm
+ *
+ * Here some html entities which can be used for escaping javadoc tags:
+ * "&": "&#038;" or "&amp;"
+ * "<": "&#060;" or "&lt;"
+ * ">": "&#062;" or "&gt;"
+ * "@": "&#064;"
+ */
+package com.github.junrar.unpack.vm;
+
+/**
+ * DOCUMENT ME
+ *
+ * @author $LastChangedBy$
+ * @version $LastChangedRevision$
+ */
+public enum VMStandardFilters {
+ VMSF_NONE ((int)0),
+ VMSF_E8 ((int)1),
+ VMSF_E8E9 ((int)2),
+ VMSF_ITANIUM( (int)3),
+ VMSF_RGB ((int)4),
+ VMSF_AUDIO ((int)5),
+ VMSF_DELTA ((int)6),
+ VMSF_UPCASE ((int)7);
+
+ private int filter;
+
+ private VMStandardFilters(int filter){
+ this.filter=filter;
+ }
+
+ public int getFilter() {
+ return filter;
+ }
+
+ public boolean equals(int filter){
+ return this.filter == filter;
+ }
+
+ public static VMStandardFilters findFilter(int filter){
+ if (VMSF_NONE.equals(filter)) {
+ return VMSF_NONE;
+ }
+
+ if (VMSF_E8.equals(filter)) {
+ return VMSF_E8;
+ }
+
+ if (VMSF_E8E9.equals(filter)) {
+ return VMSF_E8E9;
+ }
+ if (VMSF_ITANIUM.equals(filter)) {
+ return VMSF_ITANIUM;
+ }
+
+ if (VMSF_RGB.equals(filter)) {
+ return VMSF_RGB;
+ }
+
+ if (VMSF_AUDIO.equals(filter)) {
+ return VMSF_AUDIO;
+ }
+ if (VMSF_DELTA.equals(filter)) {
+ return VMSF_DELTA;
+ }
+ return null;
+ }
+
+}
diff --git a/src/com/github/junrar/unsigned/UnsignedByte.java b/src/com/github/junrar/unsigned/UnsignedByte.java
new file mode 100644
index 0000000..f59ce96
--- /dev/null
+++ b/src/com/github/junrar/unsigned/UnsignedByte.java
@@ -0,0 +1,68 @@
+/*
+ * Copyright (c) 2007 innoSysTec (R) GmbH, Germany. All rights reserved.
+ * Original author: Edmund Wagner
+ * Creation date: 04.06.2007
+ *
+ * Source: $HeadURL$
+ * Last changed: $LastChangedDate$
+ *
+ *
+ * the unrar licence applies to all junrar source and binary distributions
+ * you are not allowed to use this source to re-create the RAR compression algorithm
+ *
+ * Here some html entities which can be used for escaping javadoc tags:
+ * "&": "&#038;" or "&amp;"
+ * "<": "&#060;" or "&lt;"
+ * ">": "&#062;" or "&gt;"
+ * "@": "&#064;"
+ */
+package com.github.junrar.unsigned;
+
+import com.github.junrar.crc.RarCRC;
+
+/**
+ * DOCUMENT ME
+ *
+ * @author $LastChangedBy$
+ * @version $LastChangedRevision$
+ */
+public class UnsignedByte {
+
+ public static byte longToByte(long unsignedByte1){
+ return (byte) (unsignedByte1&0xff);
+ }
+ public static byte intToByte(int unsignedByte1){
+ return (byte) (unsignedByte1&0xff);
+ }
+ public static byte shortToByte(short unsignedByte1){
+ return (byte) (unsignedByte1&0xff);
+ }
+
+
+ public static short add(byte unsignedByte1, byte unsignedByte2){
+ return (short) (unsignedByte1 + unsignedByte2);
+ }
+
+ public static short sub(byte unsignedByte1, byte unsignedByte2){
+
+ return (short) (unsignedByte1 - unsignedByte2);
+ }
+
+
+ public static void main(String[] args)
+ {
+ //tests unsigned (signed)
+ //add
+ System.out.println(add((byte)0xfe,(byte)0x01)); //255 (-1)
+ System.out.println(add((byte)0xff,(byte)0x01)); //0 (0)
+ System.out.println(add((byte)0x7f,(byte)0x01)); //128 (-128)
+ System.out.println(add((byte)0xff,(byte)0xff)); //254 (-2)
+
+ //sub
+ System.out.println(sub((byte)0xfe,(byte)0x01)); //253 (-3)
+ System.out.println(sub((byte)0x00,(byte)0x01)); //255 (-1)
+ System.out.println(sub((byte)0x80,(byte)0x01)); //127 (127)
+ //mul
+ System.out.println((byte)-1*(byte)-1);
+ }
+}
diff --git a/src/com/github/junrar/unsigned/UnsignedInteger.java b/src/com/github/junrar/unsigned/UnsignedInteger.java
new file mode 100644
index 0000000..0f12c5c
--- /dev/null
+++ b/src/com/github/junrar/unsigned/UnsignedInteger.java
@@ -0,0 +1,29 @@
+/*
+ * Copyright (c) 2007 innoSysTec (R) GmbH, Germany. All rights reserved.
+ * Original author: Edmund Wagner
+ * Creation date: 04.06.2007
+ *
+ * Source: $HeadURL$
+ * Last changed: $LastChangedDate$
+ *
+ *
+ * the unrar licence applies to all junrar source and binary distributions
+ * you are not allowed to use this source to re-create the RAR compression algorithm
+ *
+ * Here some html entities which can be used for escaping javadoc tags:
+ * "&": "&#038;" or "&amp;"
+ * "<": "&#060;" or "&lt;"
+ * ">": "&#062;" or "&gt;"
+ * "@": "&#064;"
+ */
+package com.github.junrar.unsigned;
+
+/**
+ * DOCUMENT ME
+ *
+ * @author $LastChangedBy$
+ * @version $LastChangedRevision$
+ */
+public class UnsignedInteger {
+
+}
diff --git a/src/com/github/junrar/unsigned/UnsignedLong.java b/src/com/github/junrar/unsigned/UnsignedLong.java
new file mode 100644
index 0000000..a859929
--- /dev/null
+++ b/src/com/github/junrar/unsigned/UnsignedLong.java
@@ -0,0 +1,29 @@
+/*
+ * Copyright (c) 2007 innoSysTec (R) GmbH, Germany. All rights reserved.
+ * Original author: Edmund Wagner
+ * Creation date: 04.06.2007
+ *
+ * Source: $HeadURL$
+ * Last changed: $LastChangedDate$
+ *
+ *
+ * the unrar licence applies to all junrar source and binary distributions
+ * you are not allowed to use this source to re-create the RAR compression algorithm
+ *
+ * Here some html entities which can be used for escaping javadoc tags:
+ * "&": "&#038;" or "&amp;"
+ * "<": "&#060;" or "&lt;"
+ * ">": "&#062;" or "&gt;"
+ * "@": "&#064;"
+ */
+package com.github.junrar.unsigned;
+
+/**
+ * DOCUMENT ME
+ *
+ * @author $LastChangedBy$
+ * @version $LastChangedRevision$
+ */
+public class UnsignedLong {
+
+}
diff --git a/src/com/github/junrar/unsigned/UnsignedShort.java b/src/com/github/junrar/unsigned/UnsignedShort.java
new file mode 100644
index 0000000..e9131e9
--- /dev/null
+++ b/src/com/github/junrar/unsigned/UnsignedShort.java
@@ -0,0 +1,29 @@
+/*
+ * Copyright (c) 2007 innoSysTec (R) GmbH, Germany. All rights reserved.
+ * Original author: Edmund Wagner
+ * Creation date: 04.06.2007
+ *
+ * Source: $HeadURL$
+ * Last changed: $LastChangedDate$
+ *
+ *
+ * the unrar licence applies to all junrar source and binary distributions
+ * you are not allowed to use this source to re-create the RAR compression algorithm
+ *
+ * Here some html entities which can be used for escaping javadoc tags:
+ * "&": "&#038;" or "&amp;"
+ * "<": "&#060;" or "&lt;"
+ * ">": "&#062;" or "&gt;"
+ * "@": "&#064;"
+ */
+package com.github.junrar.unsigned;
+
+/**
+ * DOCUMENT ME
+ *
+ * @author $LastChangedBy$
+ * @version $LastChangedRevision$
+ */
+public class UnsignedShort {
+
+}
diff --git a/src/com/github/junrar/util/VolumeHelper.java b/src/com/github/junrar/util/VolumeHelper.java
new file mode 100644
index 0000000..4238051
--- /dev/null
+++ b/src/com/github/junrar/util/VolumeHelper.java
@@ -0,0 +1,101 @@
+package com.github.junrar.util;
+
+/**
+ *
+ * @author alban
+ */
+public class VolumeHelper {
+ private VolumeHelper() {
+ }
+
+ // public static boolean mergeArchive(Archive archive, ComprDataIO dataIO)
+ // throws IOException {
+ // FileHeader hd = dataIO.getSubHeader();
+ // if (hd.getUnpVersion() >= 20 && hd.getFileCRC() != 0xffffffff
+ // && dataIO.getPackedCRC() != ~hd.getFileCRC()) {
+ // System.err.println("Data Bad CRC");
+ // }
+ //
+ // boolean oldNumbering = !archive.getMainHeader().isNewNumbering()
+ // || archive.isOldFormat();
+ // String nextName = nextVolumeName(archive.getFile().getAbsolutePath(),
+ // oldNumbering);
+ // File nextVolume = new File(nextName);
+ // UnrarCallback callback = archive.getUnrarCallback();
+ // if ((callback != null) && !callback.isNextVolumeReady(nextVolume)) {
+ // return false;
+ // }
+ // if (!nextVolume.exists()) {
+ // return false;
+ // }
+ // archive.setFile(nextVolume);
+ // hd = archive.nextFileHeader();
+ // if (hd == null) {
+ // return false;
+ // }
+ // dataIO.init(hd);
+ // return true;
+ // }
+
+ public static String nextVolumeName(String arcName, boolean oldNumbering) {
+ if (!oldNumbering) {
+ // part1.rar, part2.rar, ...
+ int len = arcName.length();
+ int indexR = len - 1;
+ while ((indexR >= 0) && !isDigit(arcName.charAt(indexR))) {
+ indexR--;
+ }
+ int index = indexR + 1;
+ int indexL = indexR - 1;
+ while ((indexL >= 0) && isDigit(arcName.charAt(indexL))) {
+ indexL--;
+ }
+ if (indexL < 0) {
+ return null;
+ }
+ indexL++;
+ StringBuilder buffer = new StringBuilder(len);
+ buffer.append(arcName, 0, indexL);
+ char[] digits = new char[indexR - indexL + 1];
+ arcName.getChars(indexL, indexR + 1, digits, 0);
+ indexR = digits.length - 1;
+ while ((indexR >= 0) && (++digits[indexR]) == '9' + 1) {
+ digits[indexR] = '0';
+ indexR--;
+ }
+ if (indexR < 0) {
+ buffer.append('1');
+ }
+ buffer.append(digits);
+ buffer.append(arcName, index, len);
+ return buffer.toString();
+ } else {
+ // .rar, .r00, .r01, ...
+ int len = arcName.length();
+ if ((len <= 4) || (arcName.charAt(len - 4) != '.')) {
+ return null;
+ }
+ StringBuilder buffer = new StringBuilder();
+ int off = len - 3;
+ buffer.append(arcName, 0, off);
+ if (!isDigit(arcName.charAt(off + 1))
+ || !isDigit(arcName.charAt(off + 2))) {
+ buffer.append("r00");
+ } else {
+ char[] ext = new char[3];
+ arcName.getChars(off, len, ext, 0);
+ int i = ext.length - 1;
+ while ((++ext[i]) == '9' + 1) {
+ ext[i] = '0';
+ i--;
+ }
+ buffer.append(ext);
+ }
+ return buffer.toString();
+ }
+ }
+
+ private static boolean isDigit(char c) {
+ return (c >= '0') && (c <= '9');
+ }
+}
diff --git a/src/org/catacombae/.cvsignore b/src/org/catacombae/.cvsignore
deleted file mode 100644
index 0de89ca..0000000
--- a/src/org/catacombae/.cvsignore
+++ /dev/null
@@ -1,5 +0,0 @@
-*~
-*#
-*.class
-.DS_Store
-Thumbs.db
diff --git a/src/org/catacombae/io/.cvsignore b/src/org/catacombae/io/.cvsignore
deleted file mode 100644
index 0de89ca..0000000
--- a/src/org/catacombae/io/.cvsignore
+++ /dev/null
@@ -1,5 +0,0 @@
-*~
-*#
-*.class
-.DS_Store
-Thumbs.db
diff --git a/src/org/catacombae/io/RandomAccessFileStream.java b/src/org/catacombae/io/RandomAccessFileStream.java
deleted file mode 100644
index 137bde2..0000000
--- a/src/org/catacombae/io/RandomAccessFileStream.java
+++ /dev/null
@@ -1,66 +0,0 @@
-/*-
- * Copyright (C) 2006 Erik Larsson
- *
- * All rights reserved.
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software
- * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA
- */
-
-package org.catacombae.io;
-
-import java.io.*;
-
-public class RandomAccessFileStream implements RandomAccessStream {
- private RandomAccessFile raf;
-
- public RandomAccessFileStream(RandomAccessFile raf) throws FileNotFoundException {
- this.raf = raf;
- }
-
- /** @see java.io.RandomAccessFile */
- public void close() throws IOException {
- raf.close();
- }
-
- /** @see java.io.RandomAccessFile */
- public long getFilePointer() throws IOException {
- return raf.getFilePointer();
- }
-
- /** @see java.io.RandomAccessFile */
- public long length() throws IOException {
- return raf.length();
- }
-
- /** @see java.io.RandomAccessFile */
- public int read() throws IOException {
- return raf.read();
- }
-
- /** @see java.io.RandomAccessFile */
- public int read(byte[] b) throws IOException {
- return raf.read(b);
- }
-
- /** @see java.io.RandomAccessFile */
- public int read(byte[] b, int off, int len) throws IOException {
- return raf.read(b, off, len);
- }
-
- /** @see java.io.RandomAccessFile */
- public void seek(long pos) throws IOException {
- raf.seek(pos);
- }
-}
diff --git a/src/org/catacombae/io/RandomAccessStream.java b/src/org/catacombae/io/RandomAccessStream.java
deleted file mode 100644
index 3d6f708..0000000
--- a/src/org/catacombae/io/RandomAccessStream.java
+++ /dev/null
@@ -1,54 +0,0 @@
-/*-
- * Copyright (C) 2006 Erik Larsson
- *
- * All rights reserved.
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software
- * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA
- */
-
-package org.catacombae.io;
-
-import java.io.*;
-
-/**
- * Designed to mimic RandomAccessFile but removing the limitation that
- * all data has to be stored in one physical file on the disk. The
- * stream may be composed of multiple files, be read from memory etc.
- * It's all implementation dependent. The stream must however be
- * seekable, and have a known limited length.
- */
-public interface RandomAccessStream {
-
- /** @see java.io.RandomAccessFile */
- public void close() throws IOException;
-
- /** @see java.io.RandomAccessFile */
- public long getFilePointer() throws IOException;
-
- /** @see java.io.RandomAccessFile */
- public long length() throws IOException;
-
- /** @see java.io.RandomAccessFile */
- public int read() throws IOException;
-
- /** @see java.io.RandomAccessFile */
- public int read(byte[] b) throws IOException;
-
- /** @see java.io.RandomAccessFile */
- public int read(byte[] b, int off, int len) throws IOException;
-
- /** @see java.io.RandomAccessFile */
- public void seek(long pos) throws IOException;
-}
diff --git a/src/org/catacombae/rar/.cvsignore b/src/org/catacombae/rar/.cvsignore
deleted file mode 100644
index 0de89ca..0000000
--- a/src/org/catacombae/rar/.cvsignore
+++ /dev/null
@@ -1,5 +0,0 @@
-*~
-*#
-*.class
-.DS_Store
-Thumbs.db
diff --git a/src/org/catacombae/rar/RARFile.java b/src/org/catacombae/rar/RARFile.java
deleted file mode 100644
index 838e886..0000000
--- a/src/org/catacombae/rar/RARFile.java
+++ /dev/null
@@ -1,32 +0,0 @@
-/*-
- * Copyright (C) 2006 Erik Larsson
- *
- * All rights reserved.
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software
- * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA
- */
-
-package org.catacombae.rar;
-
-import org.catacombae.rarx.*;
-
-public class RARFile {
- public RARHeader[] readHeaders() {
- return null;
- }
- public RARFileEntryStream getData(NewFileHeader nfh) {
- return null;
- }
-}
diff --git a/src/org/catacombae/rarx/.cvsignore b/src/org/catacombae/rarx/.cvsignore
deleted file mode 100644
index 0de89ca..0000000
--- a/src/org/catacombae/rarx/.cvsignore
+++ /dev/null
@@ -1,5 +0,0 @@
-*~
-*#
-*.class
-.DS_Store
-Thumbs.db
diff --git a/src/org/catacombae/rarx/CommentHeader.java b/src/org/catacombae/rarx/CommentHeader.java
deleted file mode 100644
index e3c080c..0000000
--- a/src/org/catacombae/rarx/CommentHeader.java
+++ /dev/null
@@ -1,54 +0,0 @@
-/*-
- * Copyright (C) 2006 Erik Larsson
- *
- * All rights reserved.
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software
- * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA
- */
-
-package org.catacombae.rarx;
-
-import java.io.PrintStream;
-
-public class CommentHeader extends NewFileHeader {
- // This file header type is observed under UnpVer 0x1d (RAR 2.9)
- // This file header type is actually an archive comment!
- /* This type of header has a structure extactly like the NewFileHeader, but
- with a different head type (0x7a). The filename is probably always "CMT"
- (for "Comment"), and the data found when extracting it is the archive
- comment. */
-
- public CommentHeader(byte[] data, int offset) {
- super(data, offset);
- //super.super.validateData();
- }
-
- protected void validateData() {
- //print(System.out, "");
- //super.super.validateData(); //arvsproblem...
- if(getHeadType() != COMMENT_HEAD)
- throw new InvalidDataException("Incorrect head type! (headType=" + getHeadType() + ")");
- if(getHeadSize() < getStaticSize())
- throw new InvalidDataException("Invalid size! (size=" + getHeadSize() + ")");
- if(getHostOSAsString() == null)
- throw new InvalidDataException("Host OS value invalid.");
-
- }
-
- public void print(PrintStream ps, String prefix) {
- ps.println(prefix + "CommentHeader: ");
- printFields(ps, prefix);
- }
-}
diff --git a/src/org/catacombae/rarx/DecompressionCode.java b/src/org/catacombae/rarx/DecompressionCode.java
deleted file mode 100644
index 20f79f2..0000000
--- a/src/org/catacombae/rarx/DecompressionCode.java
+++ /dev/null
@@ -1,1715 +0,0 @@
-/*-
- * Copyright (C) 2006 Erik Larsson
- *
- * All rights reserved.
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software
- * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA
- */
-
-package org.catacombae.rarx;
-
-//import org.catacombae.rarx.*;
-import java.math.BigInteger;
-import java.io.FileInputStream;
-import java.io.InputStream;
-import java.io.OutputStream;
-import java.io.IOException;
-import java.util.zip.CRC32;
-
-public class DecompressionCode {
- private static final int MAXWINSIZE = 0x100000;
- private static final int MAXWINMASK = (MAXWINSIZE-1);
- private static final int UNP_MEMORY = MAXWINSIZE;
-
- public static final short NC = 298; /* alphabet = {0,1,2, .,NC - 1} */
- public static final short DC = 48;
- public static final short RC = 28;
- public static final short BC = 19;
- public static final short MC = 257;
-
- public static final int CODE_HUFFMAN = 0;
- public static final int CODE_LZ = 1;
- public static final int CODE_LZ2 = 2;
- public static final int CODE_REPEATLZ = 3;
- public static final int CODE_CACHELZ = 4;
- public static final int CODE_STARTFILE = 5;
- public static final int CODE_ENDFILE = 6;
- public static final int CODE_ENDMM = 7;
- public static final int CODE_STARTMM = 8;
- public static final int CODE_MMDELTA = 9;
-
- public static final int LHD_SPLIT_BEFORE = 1; //flag bit 0
- public static final int LHD_SPLIT_AFTER = 2; //flag bit 1
- public static final int LHD_PASSWORD = 4; //flag bit 2
- public static final int LHD_COMMENT = 8; //flag bit 3
- public static final int LHD_SOLID = 16; //flag bit 4
-
- public static final int LHD_WINDOWMASK = 0x00e0;
- public static final int LHD_WINDOW64 = 0;
- public static final int LHD_WINDOW128 = 32;
- public static final int LHD_WINDOW256 = 64;
- public static final int LHD_WINDOW512 = 96;
- public static final int LHD_WINDOW1024 = 128;
- public static final int LHD_DIRECTORY = 0x00e0;
-
- public static final int NROUNDS = 32;
-
- /* Static variables belonging to the function Unpack. */
- private static final short[] LDecode = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 10, 12, 14, 16, 20,
- 24, 28, 32, 40, 48, 56, 64, 80, 96,112,128,160,192,224}; //unsigned char[14]
- private static final byte[] LBits = {0,0,0,0,0,0,0,0,1,1,1,1,2,2, //unsigned char[14]
- 2,2,3,3,3,3,4,4,4,4,5,5,5,5};
- private static final int[] DDecode = {0, 1, 2, 3, 4, 6, 8, 12, 16, 24,
- 32, 48, 64, 96, 128, 192, 256, 384, 512, 768,
- 1024, 1536, 2048, 3072, 4096, 6144, 8192, 12288, 16384, 24576,
- 32768, 49152, 65536, 98304, 131072,196608,262144,327680,393216,458752,
- 524288,589824,655360,720896,786432,851968,917504,983040}; //int[48]
- private static final byte[] DBits = { 0, 0, 0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6,
- 7, 7, 8, 8, 9, 9, 10,10,11,11,12,12,13,13,14,14,
- 15,15,16,16,16,16,16,16,16,16,16,16,16,16,16,16}; //unsigned char[48]
- private static final short[] SDDecode = {0,4,8,16,32,64,128,192}; //unsigned char[8]
- private static final byte[] SDBits = {2,2,3,4,5,6,6,6}; //unsigned char[8]
-
- public static final /*UBYTE*/ short[] InitSubstTable = {
- 215, 19,149, 35, 73,197,192,205,249, 28, 16,119, 48,221, 2, 42
- ,232, 1,177,233, 14, 88,219, 25,223,195,244, 90, 87,239,153,137
- ,255,199,147, 70, 92, 66,246, 13,216, 40, 62, 29,217,230, 86, 6
- , 71, 24,171,196,101,113,218,123, 93, 91,163,178,202, 67, 44,235
- ,107,250, 75,234, 49,167,125,211, 83,114,157,144, 32,193,143, 36
- ,158,124,247,187, 89,214,141, 47,121,228, 61,130,213,194,174,251
- , 97,110, 54,229,115, 57,152, 94,105,243,212, 55,209,245, 63, 11
- ,164,200, 31,156, 81,176,227, 21, 76, 99,139,188,127, 17,248, 51
- ,207,120,189,210, 8,226, 41, 72,183,203,135,165,166, 60, 98, 7
- ,122, 38,155,170, 69,172,252,238, 39,134, 59,128,236, 27,240, 80
- ,131, 3, 85,206,145, 79,154,142,159,220,201,133, 74, 64, 20,129
- ,224,185,138,103,173,182, 43, 34,254, 82,198,151,231,180, 58, 10
- ,118, 26,102, 12, 50,132, 22,191,136,111,162,179, 45, 4,148,108
- ,161, 56, 78,126,242,222, 15,175,146, 23, 33,241,181,190, 77,225
- , 0, 46,169,186, 68, 95,237, 65, 53,208,253,168, 9, 18,100, 52
- ,116,184,160, 96,109, 37, 30,106,140,104,150, 5,204,117,112, 84
- }; // UBYTE[256]
- public static final /*UDWORD*/ int[] CRCTab = new int[256]; // Initialized in static constructor
-
- static {
- // Perform initialization of static structures and variables.
- //CRCTab = new int[256];
- InitCRC(CRCTab);
- }
-
- private CRC32 crc = new CRC32();
-
- public final /*UBYTE*/ short[] SubstTable = new short[256];
-
- private /*unsigned*/ byte PN1, PN2, PN3;
-
- /* Note: temp_output_buffer is allocated when a file is about to be
- extracted. It is allocated to NewLhd.UnpSize, which can be quite
- large. The assumption that the unpacked file can be stored in
- memory is awkward and must immediately be replaced with an output
- stream. */
- private /* unsigned char* */ byte[] temp_output_buffer; /* extract files to this pointer*/
- private /* unsigned long* */ int temp_output_buffer_offset; /* size of temp. extract buffer */
- //private /*unsigned int*/ int UnpPtr,WrPtr;
- private final /*unsigned short*/ short[] OldKey = new short[4];
-
- private static class Decode {
- public int MaxNum; // unsigned int
- public final int[] DecodeLen = new int[16]; // unsigned int[16]
- public final int[] DecodePos = new int[16]; // unsigned int[16]
- public final int[] DecodeNum; // unsigned int[]
-
- public Decode() {
- this(2);
- }
-
- protected Decode(int decodeNumSize) { DecodeNum = new int[decodeNumSize]; }
- }
- private static class LitDecode extends Decode {
- public LitDecode() { super(NC); }
- }
- private static class DistDecode extends Decode {
- public DistDecode() { super(DC); }
- }
- private static class RepDecode extends Decode {
- public RepDecode() { super(RC); }
- }
- private static class MultDecode extends Decode {
- public MultDecode() { super(MC); }
- }
- private static class BitDecode extends Decode {
- public BitDecode() { super(BC); }
- }
-
- private final LitDecode LD = new LitDecode();
- private final DistDecode DD = new DistDecode();
- private final RepDecode RD = new RepDecode();
- private final MultDecode[] MD = { new MultDecode(), new MultDecode(),
- new MultDecode(), new MultDecode() }; //new MultDecode[4];
- private final BitDecode BD = new BitDecode();
-
- private final MultDecode[] MDPtr = { MD[0], MD[1], MD[2], MD[3] };
-
-
- /* *****************************
- * ** unpack stored RAR files **
- * *****************************/
-
-// BOOL UnstoreFile(void)
-// {
-// if ((long)(*temp_output_buffer_offset=UnpRead(temp_output_buffer,
-// NewLhd.UnpSize))==-1)
-// {
-// debug_log("Read error of stored file!");
-// return FALSE;
-// }
-// return TRUE;
-// }
-
-
-
-
- /* ****************************************
- * ** RAR decompression code starts here **
- * ****************************************/
-
- /* #define statements */
- public static class AudioVariables {
- public int K1,K2,K3,K4,K5; // Should be short...?
- public int D1,D2,D3,D4;
- public int LastDelta;
- public final int[] Dif = new int[11]; //unsigned
- public int ByteCount; //unsigned
- public int LastChar;
-
- public void zero() {
- K1 = 0;
- K2 = 0;
- K3 = 0;
- K4 = 0;
- K5 = 0;
- D1 = 0;
- D2 = 0;
- D3 = 0;
- D4 = 0;
- LastDelta = 0;
- Util.zero(Dif);
- ByteCount = 0;
- LastChar = 0;
- }
- }
-
- public AudioVariables[] AudV = { new AudioVariables(), new AudioVariables(),
- new AudioVariables(), new AudioVariables() };
-
- /*
-#define GetBits() \
- BitField = ( ( ( (UDWORD)InBuf[InAddr] << 16 ) | \
- ( (UWORD) InBuf[InAddr+1] << 8 ) | \
- ( InBuf[InAddr+2] ) ) \
- >> (8-InBit) ) & 0xffff;
- */
- private static int GetBits(byte[] inBuf, int inAddr, int inBit) {
- return ( ( ( (int) (inBuf[inAddr]&0xFF) << 16 ) |
- ( (short) (inBuf[inAddr+1]&0xFF) << 8 ) |
- ( (inBuf[inAddr+2]&0xFF) ) )
- >>> (8-unsign(inBit)) ) & 0xffff;
- }
-
- /*
-#define AddBits(Bits) \
- InAddr += ( InBit + (Bits) ) >> 3; \
- InBit = ( InBit + (Bits) ) & 7;
- */
-
- /**
- * Adds <code>Bits</code> to the address specifiers.
- * InAddr is the high 32 bits of the 35-bit address (?) while InBit is the low 3 bits (?).
- * Modifies: InAddr, InBit
- * @param Bits the bits to add (interpreted as unsigned int)
- */
- private void AddBits(int Bits) {
- InAddr += (int)(( unsign(InBit) + unsign(Bits) ) >>> 3); // (InBit + Bits) / 8
- InBit = (int)(( unsign(InBit) + unsign(Bits) ) & 7);
- }
-
- public static int unsign(byte i) {
- return i & 0xFF;
- }
- public static int unsign(short i) {
- return i & 0xFFFF;
- }
- public static long unsign(int i) {
- return i & 0xFFFFFFFFL;
- }
- public static BigInteger unsign(long i) {
- return new BigInteger(1, Util.toByteArrayBE(i));
- }
-
- private static class Struct_NewFileHeader {
- short HeadCRC;
- byte HeadType;
- short Flags;
- short HeadSize;
- int PackSize;
- int UnpSize;
- byte HostOS;
- int FileCRC;
- int FileTime;
- byte UnpVer;
- byte Method;
- short NameSize;
- int FileAttr;
- };
- private NewFileHeader NewLhd;// = new NewFileHeader();
-
- private RARFileEntryStream ArcPtr = null;
- private int Encryption;
- private long UnpPackedSize;
- private /*unsigned long*/ int CurUnpRead, CurUnpWrite;
-
- //private byte[] UnpBuf;
- private int BitField; //unsigned int
- //private int Number; //unsigned int
-
- public final byte[] InBuf = new byte[8192]; /* input read buffer */
-
- public final byte[] UnpOldTable = new byte[MC*4];
-
- public int InAddr,InBit,ReadTop; //unsigned int
-
- //public int LastDist,LastLength; //unsigned int
- //private int Length,Distance; //unsigned int
-
- //public final int[] OldDist = new int[4]; //unsigned int
- //public int OldDistPtr; //unsigned int
-
-
- public int UnpAudioBlock;
- public int UnpChannels;
- public int CurChannel;
- public int ChannelDelta;
- private boolean FileFound;
-
-
- /* *** 38.3% of all CPU time is spent within this function!!! */
- /**
- * Unpacks stuff.<p>
- *
- * <pre>
- * Global read set (constants):
- * DBits (final byte[48])
- * DDecode (final int[48])
- * LBits (final byte[14])
- * LDecode (final short[14])
- * LHD_SOLID (final int)
- * MAXWINMASK (final int)
- * MDPtr (final {@link MultDecode}[4])
- * SDBits (final byte[8])
- * SDDecode (final short[8])
- *
- * Global read set (variables):
- * FileFound (boolean)
- * NewLhd ({@link Struct_NewFileHeader})
- *
- * Global modify set:
- * BitField (int)
- * CurChannel (int)
- * DD (final {@link DistDecode})
- * InAddr (int)
- * InBit (int)
- * InBuf (final byte[8192])
- * LD (final {@link LitDecode})
- * temp_output_buffer (byte[])
- * temp_output_buffer_offset (int)
- * UnpAudioBlock (int)
- * UnpChannels (int)
- *
- * Local use set:
- * Bits (int)
- * (in) DestUnpSize (long)
- * Distance (int)
- * LastDist (int)
- * LastLength (int)
- * Length (int)
- * Number (int)
- * OldDist (final int[4])
- * OldDistPtr (int)
- * (in) UnpAddr (byte[])
- * UnpBuf (byte[])
- * UnpPtr (int)
- * WrPtr (int)
- *
- * Call set:
- * {@link #UnpInitData}
- * {@link #UnpReadBuf}
- * {@link #ReadTables}
- * {@link #debug_log}
- * {@link System#arraycopy}
- * {@link #DecodeNumber}
- * {@link #DecodeAudio}
- * {@link #GetBits}
- * {@link #AddBits}
- * {@link #ReadLastTables}
- * </pre>
- */
- public void Unpack(/*unsigned char*/ byte[] UnpAddr, /*long DestUnpSize, */RARFileEntryStream i_ArcPtr, OutputStream dataOut, NewFileHeader i_NewLhd) throws IOException {
- // catacombae
- ArcPtr = i_ArcPtr;
- NewLhd = i_NewLhd;
- long DestUnpSize = NewLhd.getUnpSize();
- UnpPackedSize = NewLhd.getPackSize();
- FileFound = true; //Otherwise no data will be written, just uncompressed and skipped (for the purpose of extracting solid archives).
- Encryption = 0;
- CurUnpRead = CurUnpWrite = 0;
- // /catacombae
-
- int Bits; // unsigned int
-
- byte[] UnpBuf=UnpAddr; /* UnpAddr is a pointer to the unpack buffer */
- int UnpPtr = 0; // Pointer to where in the buffer we are at present
- int WrPtr = 0; // Pointer to where in the buffer UnpBuf we were at the last write
- int Length = 0;
- int Distance = 0;
- int LastDist = 0;
- int LastLength = 0;
- int Number = 0;
- final int[] OldDist = new int[4];
- int OldDistPtr = 0;
-
- System.out.println("UnpInitData");
- UnpInitData(UnpBuf);
- System.out.println("UnpReadBuf");
- UnpReadBuf(true);
- if((NewLhd.getFlags() & LHD_SOLID) == 0) {
- System.out.println("ReadTables");
- ReadTables();
- }
-
- DestUnpSize--;
-
- int l256 = 0, g269 = 0, e269 = 0, e256 = 0, l261 = 0, l270 = 0; // debug / understanding
- while(DestUnpSize>=0) {
- System.out.println("Looping (DestUnpSize=" + DestUnpSize + ")");
- UnpPtr &= MAXWINMASK;
-
- if(unsign(InAddr) > InBuf.length-30)
- UnpReadBuf(false);
- if(((WrPtr-UnpPtr) & MAXWINMASK)<270 && WrPtr!=UnpPtr) {
- System.out.println("YO");
- if(FileFound) {
- // Flush extracted data to file
- if(!writeData(UnpBuf, UnpPtr, WrPtr, dataOut))
- DestUnpSize = -1;
- }
- WrPtr=UnpPtr;
- }
- else {
- //System.out.println("((" + WrPtr + "-" + UnpPtr + ") & MAXWINMASK) >= 270");
- //System.out.println(((WrPtr-UnpPtr) & MAXWINMASK) + "<270");
- }
-
- if(UnpAudioBlock != 0) {
- Number = DecodeNumber(MDPtr[CurChannel]);
- if (Number==256) {
- ReadTables();
- }
- else {
- UnpBuf[UnpPtr++]=DecodeAudio(Number);
- if (++CurChannel==UnpChannels)
- CurChannel=0;
- DestUnpSize--;
- }
- //continue;
- }
- else {
- Number = DecodeNumber(LD);
- if(Number<256) { // stored
- System.out.println(Number);
- ++l256;
- UnpBuf[UnpPtr++]=(byte)Number;
- DestUnpSize--;
- //continue;
- }
- else if(Number>269) {
- ++g269;
- Length = LDecode[Number-=270]+3;
- if ((Bits=LBits[Number])>0) {
- BitField = GetBits(InBuf, InAddr, InBit);
- Length+=BitField>>>(16-Bits);
- AddBits(Bits);
- }
-
- Number = DecodeNumber(DD);
- Distance = DDecode[Number]+1;
- if ((Bits=DBits[Number])>0) {
- BitField = GetBits(InBuf, InAddr, InBit);
- Distance += BitField >>> (16-Bits);
- AddBits(Bits);
- }
-
- if (Distance>=0x40000)
- Length++;
-
- if (Distance>=0x2000)
- Length++;
-
- LastDist=OldDist[OldDistPtr++ & 3]=Distance;
- DestUnpSize-=(LastLength=Length);
- while (Length-- != 0) {
- UnpBuf[UnpPtr]=UnpBuf[(UnpPtr-Distance) & MAXWINMASK];
- UnpPtr=(UnpPtr+1) & MAXWINMASK;
- }
-
- //continue;
- }
- else if(Number==269) {
- ++e269;
- ReadTables();
- //continue;
- }
- else if(Number==256) {
- ++e256;
- Length = LastLength;
- Distance = LastDist;
- LastDist = OldDist[OldDistPtr++ & 3] = Distance;
- DestUnpSize -= (LastLength=Length);
- while(Length-- != 0) {
- UnpBuf[UnpPtr] = UnpBuf[(UnpPtr-Distance) & MAXWINMASK];
- UnpPtr = (UnpPtr+1) & MAXWINMASK;
- }
- //continue;
- }
- else if(Number<261) {
- ++l261;
- Distance=OldDist[(OldDistPtr-(Number-256)) & 3];
- Number = DecodeNumber(RD);
- Length=LDecode[Number]+2;
- if ((Bits=LBits[Number])>0) {
- BitField = GetBits(InBuf, InAddr, InBit);
- Length+=BitField>>>(16-Bits);
- AddBits(Bits);
- }
- if (Distance>=0x40000)
- Length++;
- if (Distance>=0x2000)
- Length++;
- if (Distance>=0x101)
- Length++;
- LastDist=OldDist[OldDistPtr++ & 3]=Distance;
- DestUnpSize-=(LastLength=Length);
- while (Length-- != 0) {
- UnpBuf[UnpPtr]=UnpBuf[(UnpPtr-Distance) & MAXWINMASK];
- UnpPtr=(UnpPtr+1) & MAXWINMASK;
- }
- //continue;
- }
- else if(Number<270) {
- ++l270;
- Distance=SDDecode[Number-=261]+1;
- if ((Bits=SDBits[Number])>0) {
- BitField = GetBits(InBuf, InAddr, InBit);
- Distance+=BitField>>>(16-Bits);
- AddBits(Bits);
- }
- Length=2;
- LastDist=OldDist[OldDistPtr++ & 3]=Distance;
- DestUnpSize-=(LastLength=Length);
- while (Length-- != 0) {
- UnpBuf[UnpPtr]=UnpBuf[(UnpPtr-Distance) & MAXWINMASK];
- UnpPtr=(UnpPtr+1) & MAXWINMASK;
- }
- //continue;
- }
- else
- debug_log("This message will NEVER be printed. If it is printed anyway, kick the programmer.");
- }
- }
- System.out.println("x < 256: " + l256);
- System.out.println("x > 269: " + g269);
- System.out.println("x = 269: " + e269);
- System.out.println("x = 256: " + e256);
- System.out.println("x < 261: " + l261);
- System.out.println("x < 270: " + l270);
- System.out.println("Total: " + (l256+g269+e269+e256+l261+l270));
- System.out.println("LD.DecodeLen: 0x" + Util.toHexStringBE(LD.DecodeLen));
- System.out.println("LD.DecodeNum: 0x" + Util.toHexStringBE(LD.DecodeNum));
- System.out.println("LD.DecodePos: 0x" + Util.toHexStringBE(LD.DecodePos));
- System.out.println("LD.MaxNum: 0x" + Util.toHexStringBE(LD.MaxNum));
- ReadLastTables();
-
- if (FileFound) { /* flush buffer */
- // Flush extracted data to file
- if(!writeData(UnpBuf, UnpPtr, WrPtr, dataOut))
- DestUnpSize = -1;
- }
-
- WrPtr=UnpPtr;
- }
-
- /**
- * Writes the data in <code>UnpBuf</code> to <code>dataOut</code> according to some rules.<p>
- * <pre>
- * Global read set:
- * {@link #NewLhd} ({@link NewFileHeader})
- *
- * Global modify set:
- * *temp_output_buffer (byte[])
- * temp_output_buffer_offset (int)
- *
- * Local use set:
- * (in) UnpBuf (byte[])
- * </pre>
- */
- private boolean writeData(byte[] UnpBuf, int UnpPtr, int WrPtr, OutputStream dataOut) throws IOException {
- if (UnpPtr<WrPtr) {
- debug_log("UnpPtr<WrPtr (" + UnpPtr + "<" + WrPtr + ")");
- if((temp_output_buffer_offset + UnpPtr) > NewLhd.getUnpSize()) {
- debug_log("Fatal! Buffer overrun during decompression!");
- return false; //DestUnpSize=-1;
- } else if(true) {
- int firstOutLengthOld = (0-WrPtr) & MAXWINMASK; // Don't understand...
- int firstOutLength = (UnpBuf.length-1) - WrPtr; //This should be equivalent to the above
- if(firstOutLengthOld != firstOutLength)
- debug_log("Assumption broken for firstOutLength :(");
-
- dataOut.write(UnpBuf, WrPtr, firstOutLength);
- dataOut.write(UnpBuf, 0, UnpPtr);
- temp_output_buffer_offset += firstOutLength+UnpPtr;
- } else {
- int firstOutLength = (0-WrPtr) & MAXWINMASK; // Don't understand...
- /* copy extracted data to output buffer */
- System.arraycopy(UnpBuf, WrPtr, temp_output_buffer, temp_output_buffer_offset, firstOutLength);
- /* update offset within buffer */
- temp_output_buffer_offset += firstOutLength;
- /* copy extracted data to output buffer */
- System.arraycopy(UnpBuf, 0, temp_output_buffer, temp_output_buffer_offset, UnpPtr);
- /* update offset within buffer */
- temp_output_buffer_offset += UnpPtr;
- }
- } else {
- debug_log("UnpPtr>WrPtr (" + UnpPtr + ">" + WrPtr + ")");
-
- if((temp_output_buffer_offset + (UnpPtr-WrPtr)) > NewLhd.getUnpSize()) {
- debug_log("Fatal! Buffer overrun during decompression!");
- //DestUnpSize=-1;
- return false;
- } else if(true) {
- dataOut.write(UnpBuf, WrPtr, UnpPtr-WrPtr);
- temp_output_buffer_offset += UnpPtr-WrPtr;
- } else {
- /* copy extracted data to output buffer */
- System.arraycopy(UnpBuf, WrPtr, temp_output_buffer, temp_output_buffer_offset, UnpPtr-WrPtr);
- temp_output_buffer_offset+=UnpPtr-WrPtr; /* update offset within buffer */
- }
- }
- return true;
- }
- /**
- * Reads into the buffer <code>InBuf</code> from the archive stream. If the flag FirstBuf
- * is set, the method preserves the last 32 bytes of InBuf and copies them to the front
- * of the buffer, filling the buffer with only <code>InBuf.length-32</code> bytes.<p>
- * <pre>
- * Global modify set:
- * ReadTop (int)
- * InAddr (int)
- * Through UnpRead:
- * UnpPackedSize (int)
- * CurUnpRead (int)
- *
- * Global read set:
- * InBuf (byte[]) (contents modified in UnpRead)
- *
- * Local use set:
- * (in) FirstBuf (boolean)
- * RetCode (int)
- *
- * Call set:
- * {@link UnpRead}
- * </pre>
- * @param FirstBuf flag indicating whether or not we will treat this read as the first read
- * to the buffer, thus destroying any previous content
- */
- private void UnpReadBuf(boolean FirstBuf) {
- int RetCode;
- if(FirstBuf) {
- ReadTop = UnpRead(InBuf, 0, InBuf.length);
- InAddr = 0;
- }
- else {
- System.arraycopy(InBuf, InBuf.length-32, InBuf, 0, 32);
- InAddr &= 0x1f; // discard all but the five least significant bytes... is this modulo 32? think so.
- RetCode = UnpRead(InBuf, 32, InBuf.length-32);
- if(RetCode > 0)
- ReadTop=RetCode+32;
- else
- ReadTop=InAddr;
- }
- }
-
- /**
- * Reads <code>Count</code> bytes from the stream <code>ArcPtr</code> into
- * the buffer <code>Addr</code> at position <code>offset</code>. If the
- * data is encrypted, it is automatically decrypted. (The variable
- * <code>Encryption</code> tells the function whether is shall consider
- * the data to be encrypted.)<p>
- * <pre>
- * Global read set:
- * ArcPtr ({@link java.io.InputStream})
- * Encryption (int)
- *
- * Global modify set:
- * UnpPackedSize (int)
- * CurUnpRead (int)
- *
- * Local use set:
- * (in) Addr (byte[])
- * (in) offset (int)
- * (in) Count (int)
- * RetCode (int)
- * I (int)
- * ReadSize (int)
- * TotalRead (int)
- * ReadAddr (byte[])
- * readAddrPointer (int)
- *
- * Call set:
- * tread(File, byte[], int, int)
- * debug_log(String)
- * DecryptBlock(byte[], int, int)
- * </pre>
- * @return the number of bytes read, or -1 if an error occurred.
- */
- private /*unsigned int*/ int UnpRead(/*unsigned char **/ byte[] Addr, int offset, /*unsigned int*/ int Count) {
- int RetCode=0;
- /*unsigned int*/ int I,ReadSize,TotalRead=0;
- /*unsigned char **/ byte[] ReadAddr;
- int readAddrPointer = offset; // catacombae
- ReadAddr=Addr;
- while(Count > 0) {
- ReadSize=(/*unsigned int*/ int)((Count>(/*unsigned long*/ int)UnpPackedSize) ?
- UnpPackedSize : Count);
- if (ArcPtr==null)
- return(0);
- RetCode=tread(ArcPtr,ReadAddr,readAddrPointer,ReadSize);
- debug_log("Read " + RetCode + " from file.");
-
- CurUnpRead+=RetCode;
- readAddrPointer+=RetCode;
- TotalRead+=RetCode;
- Count-=RetCode;
- UnpPackedSize-=RetCode;
- break; // Why the while-loop? if would work just as well.
- }
- if (RetCode!= -1) {
- RetCode=TotalRead;
- if (Encryption != 0) {
- if (Encryption<20) {
- debug_log("Old Crypt() not supported!");
- }
- else {
- for (I=0;I<(/*unsigned int*/ short)RetCode;I+=16)
- DecryptBlock(/*&Addr[I]*/Addr, I);
- }
- }
- }
- return(RetCode);
- }
-
-
- /**
- * Reads and initializes the decompression tables.<p>
- * <pre>
- * Global read set (constants):
- * BC (final short)
- * DC (final short)
- * MC (final short)
- * NC (final short)
- * RC (final short)
- *
- * Global read set (variables):
- *
- * Global modify set:
- * BD (BitDecode)
- * BitField (int)
- * CurChannel (int)
- * DD (DistDecode)
- * InAddr (int)
- * InBit (int) (through AddBits)
- * InBuf (final byte[8192])
- * MDPtr (final MultDecode[4])
- * RD (RepDecode)
- * UnpAudioBlock (int)
- * UnpChannels (int)
- * UnpOldTable (final byte[MC*4])
- *
- *
- * Local use set:
- * BitLength (final byte[BC])
- * Table (final byte[MC*4])
- * TableSize (int)
- * N (int)
- * I (int)
- *
- * Call set:
- * UnpReadBuf
- * GetBits
- * Util.zero
- * AddBits
- * MakeDecodeTables
- * DecodeNumber
- * System.arraycopy
- * </pre>
- */
- private void ReadTables() {
- System.out.println("ReadTables():");
- final /*UBYTE*/ byte[] BitLength = new byte[BC];
- final /*unsigned char*/ byte[] Table = new byte[MC*4];
- /*int*/ int TableSize,N,I;
-
- if(InAddr>InBuf.length-25) {
- System.out.println("InAddr == " + InAddr);
- UnpReadBuf(false);
- }
- BitField = GetBits(InBuf, InAddr, InBit);
- UnpAudioBlock = (BitField & 0x8000);
-
- if((BitField & 0x4000) == 0)
- Util.zero(UnpOldTable);
- AddBits(2);
-
-
- if(UnpAudioBlock != 0) {
- UnpChannels=((BitField >>> 12) & 3)+1;
- debug_log("WARNING: UnpChannels = " + UnpChannels);
- if (CurChannel>=UnpChannels)
- CurChannel=0;
- AddBits(2);
- TableSize=(short)(MC*UnpChannels);
- }
- else
- TableSize=NC+DC+RC;
-
-
- for (I=0;I<BC;I++) {
- BitField = GetBits(InBuf, InAddr, InBit);
- BitLength[I]=(/*UBYTE*/byte)(BitField >>> 12);
- AddBits(4);
- }
- MakeDecodeTables(BitLength, BD, 0, BC);
-
- I=0;
- while(I<TableSize) {
- if(InAddr>InBuf.length-5)
- UnpReadBuf(false);
- int number = DecodeNumber(BD);
- if(number<16)
- Table[I++]=(byte)((number+UnpOldTable[I]) & 0xf);
- else
- if(number==16) {
- BitField = GetBits(InBuf, InAddr, InBit);
- N=((BitField >>> 14)+3);
- AddBits(2);
- while(N-- > 0 && I<TableSize) {
- Table[I]=Table[I-1];
- I++;
- }
- }
- else {
- if(number==17) {
- BitField = GetBits(InBuf, InAddr, InBit);
- N=((BitField >>> 13)+3);
- AddBits(3);
- }
- else {
- BitField = GetBits(InBuf, InAddr, InBit);
- N=((BitField >>> 9)+11);
- AddBits(7);
- }
- while(N-- > 0 && I<TableSize)
- Table[I++]=0;
- }
- }
- if(UnpAudioBlock != 0)
- for(I=0; I<UnpChannels; I++)
- MakeDecodeTables(Table, MDPtr[I], (I*MC), MC);
- else {
- MakeDecodeTables(Table, LD, 0, NC);
- MakeDecodeTables(Table, DD, NC, DC);
- MakeDecodeTables(Table, RD, (NC+DC), RC);
- }
-
- System.arraycopy(Table, 0, UnpOldTable, 0, UnpOldTable.length);
- }
-
-
- private void ReadLastTables() {
- if (ReadTop>=InAddr+5) {
- if (UnpAudioBlock != 0) {
- int number = DecodeNumber(MDPtr[CurChannel]);
- if (number==256)
- ReadTables();
- }
- else {
- int number = DecodeNumber(LD);
- if (number==269)
- ReadTables();
- }
- }
- }
-
- /**
- * Modifies the <code>Decode</code> object <code>Dec</code> supplied as parameter
- * according to the data in <code>LenTab</code>. Initializes <code>Dec</code> for
- * further use in decompression.<p>
- * <pre>
- * Global modify set:
- * <empty>
- *
- * Global read set:
- * <empty>
- *
- * Local use set:
- * (in) LenTab (byte[])
- * (i/o) Dec ({@link Decode})
- * (in) offset (int)
- * (in) Size (int)
- * LenCount (final int[16])
- * TmpPos (final int[16])
- * I (int)
- * M (int)
- * N (int)
- * </pre>
- */
- private void MakeDecodeTables(/*unsigned char **/ byte[] LenTab,
- Decode Dec,
- int offset,
- int Size) {
- final /*int*/int[] LenCount = new int[16];
- final /*int*/int[] TmpPos = new int[16];
- /*int*/int I;
- /*long*/int M, N;
- //memset(LenCount,0,sizeof(LenCount)); // Java does this automatically
- for(I=offset; I<offset+Size; I++)
- LenCount[LenTab[I] & 0xF]++;
-
- LenCount[0]=0;
- for(TmpPos[0]=Dec.DecodePos[0]=Dec.DecodeLen[0]=0,N=0,I=1; I<16; I++) {
- N = 2*(N+LenCount[I]);
- M = N << (15-I);
- if(M>0xFFFF)
- M=0xFFFF;
- Dec.DecodeLen[I]=(/*unsigned int*/int)M;
- TmpPos[I]=Dec.DecodePos[I]=((Dec.DecodePos[I-1] & 0xFFFF)+LenCount[I-1]);
- }
-
- for(I=offset; I<offset+Size; I++)
- if(LenTab[I]!=0)
- Dec.DecodeNum[TmpPos[LenTab[I] & 0xF]++]=I;
- Dec.MaxNum=Size;
- }
-
-
- /* *** 52.6% of all CPU time is spent within this function!!! */
- /**
- * Decodes a number from the supplied <code>Decode</code> object.<p>
- * <pre>
- * Global modify set:
- * BitField (int)
- * In AddBits:
- * InAddr (int)
- * InBit (int)
- *
- * Local use set:
- * (in) Deco ({@link Decode})
- * I (int)
- * N (int)
- *
- * Call set:
- * GetBits
- * AddBits
- * </pre>
- *
- * @return the decoded number...?
- */
- private int DecodeNumber(Decode Deco) {
- /*unsigned int*/ int I;
- /*register unsigned int*/ int N;
- System.out.println("GetBits(" + InBuf + ", " + InAddr + ", " + InBit + ");");
- BitField = GetBits(InBuf, InAddr, InBit);
-
- N=(BitField & 0xFFFE);
- System.out.println("(1) N == " + N + " (BitField == " + BitField + ")");
- if(N<Deco.DecodeLen[8]) {
- if(N<Deco.DecodeLen[4]) {
- if(N<Deco.DecodeLen[2]) {
- if(N<Deco.DecodeLen[1])
- I=1;
- else
- I=2;
- } else {
- if(N<Deco.DecodeLen[3])
- I=3;
- else
- I=4;
- }
- } else {
- if(N<Deco.DecodeLen[6]) {
- if(N<Deco.DecodeLen[5])
- I=5;
- else
- I=6;
- } else {
- if(N<Deco.DecodeLen[7])
- I=7;
- else
- I=8;
- }
- }
- } else {
- if(N<Deco.DecodeLen[12]) {
- if(N<Deco.DecodeLen[10]) {
- if(N<Deco.DecodeLen[9])
- I=9;
- else
- I=10;
- } else {
- if(N<Deco.DecodeLen[11])
- I=11;
- else
- I=12;
- }
- } else {
- if(N<Deco.DecodeLen[14]) {
- if(N<Deco.DecodeLen[13])
- I=13;
- else
- I=14;
-
- } else {
- I=15;
- }
- }
-
- }
-
- AddBits(I);
- N = Deco.DecodePos[I] + ((N-Deco.DecodeLen[I-1]) >>> (16-I));
- System.out.println("(2) N == " + N);
- if(N >= Deco.MaxNum)
- N=0;
- System.out.println("(3) N == " + N);
-
- System.out.println("Deco.DecodeNum[" + N + "] == " + Deco.DecodeNum[N]);
- return Deco.DecodeNum[N];
- }
-
- /**
- * Intializes data for the unpack process by setting the variables <code>InAddr</code> and <code>InBit</code> to 0.<br>
- * If the archive is a solid archive the method also does the following:<br>
- * <ul>
- * <li>Set <code>ChannelDelta</code> and <code>CurChannel</code> to 0.</li>
- * <li>Zero all <code>AudioVariables</code> objects in <code>AudV</code> through {@link AudioVariables#zero}.</li>
- * <li>Zero the arrays <code>unpBuf</code> and <code>UnpOldTable</code>.</li>
- * </ul><p>
- * <pre>
- * Global read set:
- * NewLhd ({@link Struct_NewFileHeader})
- * LHD_SOLID (final int)
- * MAXWINSIZE (final int)
- *
- * Global modify set:
- * InAddr (int)
- * InBit (int)
- * ChannelDelta (int)
- * CurChannel (int)
- * AudV ({@link AudioVariables})
- *
- * Local use set:
- * (in) unpBuf (byte[])
- * </pre>
- */
- private void UnpInitData(byte[] unpBuf) {
- InAddr=InBit=0;
- if(!((NewLhd.getFlags() & LHD_SOLID) != 0)) {
- System.out.println("1");
- ChannelDelta=CurChannel=0;
-
- //memset(AudV,0,sizeof(AudV));
- System.out.println("2");
- for(AudioVariables av : AudV)
- av.zero();
- //memset(OldDist,0,sizeof(OldDist));
- //Util.zero(OldDist);
- //OldDistPtr=0;
- //LastDist=LastLength=0;
- //memset(UnpBuf,0,MAXWINSIZE);
- System.out.println("3");
- Util.zero(unpBuf, 0, MAXWINSIZE);
- //memset(UnpOldTable,0,sizeof(UnpOldTable));
- System.out.println("4");
- Util.zero(UnpOldTable);
- //UnpPtr=WrPtr=0;
- }
- }
-
- /**
- * Does some kind of audio decoding that I'm not familiar with conceptually.<p>
- * <pre>
- * Global read set:
- * CurChannel (int)
- *
- * Global modify set:
- * AudV ({@link AudioVariables}[])
- * ChannelDelta (int)
- *
- * Local use set:
- * (in) Delta (int)
- * V ({@link AudioVariables})
- * Ch (int)
- * NumMinDif (int)
- * MinDif (int)
- * PCh (int)
- * I (int)
- * </pre>
- */
- private /*UBYTE*/ byte DecodeAudio(int Delta) {
- AudioVariables V;
- /*unsigned */int Ch;
- /*unsigned */int NumMinDif,MinDif;
- int PCh,I;
-
- V=AudV[CurChannel];
- V.ByteCount++;
- V.D4=V.D3;
- V.D3=V.D2;
- V.D2=V.LastDelta-V.D1;
- V.D1=V.LastDelta;
- PCh=8*V.LastChar+V.K1*V.D1+V.K2*V.D2+
- V.K3*V.D3+V.K4*V.D4+V.K5*ChannelDelta;
- PCh=(PCh>>3) & 0xFF;
-
- Ch=PCh-Delta;
-
- I=((/*signed char*/byte)Delta)<<3;
-
- V.Dif[0]+=Math.abs(I);
- V.Dif[1]+=Math.abs(I-V.D1);
- V.Dif[2]+=Math.abs(I+V.D1);
- V.Dif[3]+=Math.abs(I-V.D2);
- V.Dif[4]+=Math.abs(I+V.D2);
- V.Dif[5]+=Math.abs(I-V.D3);
- V.Dif[6]+=Math.abs(I+V.D3);
- V.Dif[7]+=Math.abs(I-V.D4);
- V.Dif[8]+=Math.abs(I+V.D4);
- V.Dif[9]+=Math.abs(I-ChannelDelta);
- V.Dif[10]+=Math.abs(I+ChannelDelta);
-
- ChannelDelta=V.LastDelta=(/*signed char*/byte)(Ch-V.LastChar);
- V.LastChar=Ch;
-
- if((V.ByteCount & 0x1F)==0) {
- MinDif=V.Dif[0];
- NumMinDif=0;
- V.Dif[0]=0;
- for (I=1;(/*unsigned */int)I<V.Dif.length;I++) {
- if(V.Dif[I]<MinDif) {
- MinDif=V.Dif[I];
- NumMinDif=I;
- }
- V.Dif[I]=0;
- }
- switch(NumMinDif) {
- case 1:
- if(V.K1>=-16)
- V.K1--;
- break;
- case 2:
- if(V.K1<16)
- V.K1++;
- break;
- case 3:
- if(V.K2>=-16)
- V.K2--;
- break;
- case 4:
- if(V.K2<16)
- V.K2++;
- break;
- case 5:
- if(V.K3>=-16)
- V.K3--;
- break;
- case 6:
- if(V.K3<16)
- V.K3++;
- break;
- case 7:
- if(V.K4>=-16)
- V.K4--;
- break;
- case 8:
- if(V.K4<16)
- V.K4++;
- break;
- case 9:
- if(V.K5>=-16)
- V.K5--;
- break;
- case 10:
- if(V.K5<16)
- V.K5++;
- break;
- }
- }
- return((/*UBYTE*/byte)Ch);
- }
-
-
-
-
-
-
-
- /* ***************************************************
- * ** CRCCrypt Code - decryption engine starts here **
- * ***************************************************/
-
-
-
-/* #define rol(x,n) (((x)<<(n)) | ((x)>>(8*sizeof(x)-(n)))) */
- /** Rotate left. Pure functional behavior, no side effects. */
- private static byte rol(byte value, int shift) {
- return (byte) (((value)<<(shift)) | ((value)>>>(8*1-(shift))));
- }
- /** @see #rol(byte,int) */
- private static short rol(short value, int shift) {
- return (short)(((value)<<(shift)) | ((value)>>>(8*2-(shift))));
- }
- /** @see #rol(byte,int) */
- private static int rol(int value, int shift) {
- return (((value)<<(shift)) | ((value)>>>(8*4-(shift))));
- }
- /** @see #rol(byte,int) */
- private static long rol(long value, int shift) {
- return (((value)<<(shift)) | ((value)>>>(8*8-(shift))));
- }
-
-/* #define ror(x,n) (((x)>>(n)) | ((x)<<(8*sizeof(x)-(n)))) */
- /** Rotate right. Pure functional behavior, no side effects. */
- private static byte ror(byte value, int shift) {
- return (byte) (((value)>>>(shift)) | ((value)<<(8*1-(shift))));
- }
- /** @see #ror(byte,int) */
- private static short ror(short value, int shift) {
- return (short)(((value)>>>(shift)) | ((value)<<(8*2-(shift))));
- }
- /** @see #ror(byte,int) */
- private static int ror(int value, int shift) {
- return (((value)>>>(shift)) | ((value)<<(8*4-(shift))));
- }
- /** @see #ror(byte,int) */
- private static long ror(long value, int shift) {
- return (((value)>>>(shift)) | ((value)<<(8*8-(shift))));
- }
-
-/*
-#define substLong(t) ( (UDWORD)SubstTable[(int)t&255] | \
- ((UDWORD)SubstTable[(int)(t>> 8)&255]<< 8) | \
- ((UDWORD)SubstTable[(int)(t>>16)&255]<<16) | \
- ((UDWORD)SubstTable[(int)(t>>24)&255]<<24) )
-*/
- private int substLong(int t) {
- return ( ((/*UDWORD*/int)SubstTable[(int)(t>> 0)&255]<< 0) |
- ((/*UDWORD*/int)SubstTable[(int)(t>> 8)&255]<< 8) |
- ((/*UDWORD*/int)SubstTable[(int)(t>>16)&255]<<16) |
- ((/*UDWORD*/int)SubstTable[(int)(t>>24)&255]<<24) );
- }
-
- // public static final /*UDWORD*/ int[] CRCTab = new int[256]; // Initialized in static constructor
-
-
- public /*UDWORD*/ int[] Key = new int[4];
-
-
- public void EncryptBlock(/*UBYTE*/byte[] Buf) {
- //int I;
-
- int /*UDWORD*/ A,B,C,D,T,TA,TB;
-// #ifdef NON_INTEL_BYTE_ORDER
- if(true) {
- A = ((0xFF & Buf[0] ) | ((0xFF & Buf[1] )<<8) | ((0xFF & Buf[2] )<<16) | ((0xFF & Buf[3] )<<24))^Key[0];
- B = ((0xFF & Buf[4] ) | ((0xFF & Buf[5] )<<8) | ((0xFF & Buf[6] )<<16) | ((0xFF & Buf[7] )<<24))^Key[1];
- C = ((0xFF & Buf[8] ) | ((0xFF & Buf[9] )<<8) | ((0xFF & Buf[10])<<16) | ((0xFF & Buf[11])<<24))^Key[2];
- D = ((0xFF & Buf[12]) | ((0xFF & Buf[13])<<8) | ((0xFF & Buf[14])<<16) | ((0xFF & Buf[15])<<24))^Key[3];
- }
- else { // The above code should yield the same result as these lines. Test this assumption.
- A = Util.readIntLE(Buf, 0 )^Key[0];
- B = Util.readIntLE(Buf, 4 )^Key[1];
- C = Util.readIntLE(Buf, 8 )^Key[2];
- D = Util.readIntLE(Buf, 12)^Key[3];
- }
-// #else
-// UDWORD *BufPtr;
-// BufPtr=(UDWORD *)Buf;
-// A=BufPtr[0]^Key[0];
-// B=BufPtr[1]^Key[1];
-// C=BufPtr[2]^Key[2];
-// D=BufPtr[3]^Key[3];
-// #endif
- for(int I=0;I<NROUNDS;I++) {
- T=((C+rol(D,11))^Key[I&3]);
- TA=A^substLong(T);
- T=((D^rol(C,17))+Key[I&3]);
- TB=B^substLong(T);
- A=C;
- B=D;
- C=TA;
- D=TB;
- }
-// #ifdef NON_INTEL_BYTE_ORDER
- if(true) {
- C ^= Key[0];
- Buf[0]=(byte)(0xFF & C);
- Buf[1]=(byte)(0xFF & (C>>>8));
- Buf[2]=(byte)(0xFF & (C>>>16));
- Buf[3]=(byte)(0xFF & (C>>>24));
- D ^= Key[1];
- Buf[4]=(byte)(0xFF & D);
- Buf[5]=(byte)(0xFF & (D>>>8));
- Buf[6]=(byte)(0xFF & (D>>>16));
- Buf[7]=(byte)(0xFF & (D>>>24));
- A ^= Key[2];
- Buf[8]=(byte)(0xFF & A);
- Buf[9]=(byte)(0xFF & (A>>>8));
- Buf[10]=(byte)(0xFF & (A>>>16));
- Buf[11]=(byte)(0xFF & (A>>>24));
- B ^= Key[3];
- Buf[12]=(byte)(0xFF & B);
- Buf[13]=(byte)(0xFF & (B>>>8));
- Buf[14]=(byte)(0xFF & (B>>>16));
- Buf[15]=(byte)(0xFF & (B>>>24));
- }
- else {
- System.arraycopy(Util.toByteArrayLE(C^Key[0]), 0, Buf, 0, 4);
- System.arraycopy(Util.toByteArrayLE(D^Key[1]), 4, Buf, 0, 4);
- System.arraycopy(Util.toByteArrayLE(A^Key[2]), 8, Buf, 0, 4);
- System.arraycopy(Util.toByteArrayLE(B^Key[3]), 12, Buf, 0, 4);
- }
-// #else
-// BufPtr[0]=C^Key[0];
-// BufPtr[1]=D^Key[1];
-// BufPtr[2]=A^Key[2];
-// BufPtr[3]=B^Key[3];
-// #endif
- UpdKeys(Buf);
-}
-
-
- /**
- * Decrypts a 16 byte block in the buffer <code>Buf</code> at position <code>offset</code>.
- * The decrypted data is stored at the same place in <code>Buf</code>, thus overwriting the
- * encrypted contents.<p>
- * <pre>
- * Global read set:
- *
- * Global modify set:
- * In UpdKeys:
- * Key (final int[4])
- *
- * Local use set:
- * (in) Buf (byte[])
- * (in) offset (int)
- * InBuf (byte[])
- * A (int)
- * B (int)
- * C (int)
- * D (int)
- * T (int)
- * TA (int)
- * TB (int)
- * </pre>
- */
- public void DecryptBlock(/*UBYTE*/byte[] Buf, int offset) {
- //int I;
- final int n = offset;
- byte[] /*UBYTE*/ InBuf = new byte[16];
- int /*UDWORD*/ A,B,C,D,T,TA,TB;
- System.arraycopy(Buf, n, InBuf, 0, InBuf.length); // memcpy(InBuf,Buf,sizeof(InBuf));
-
- // Swap all bytes since data is stored in little endian format.
-// if(true) {
- A = ((0xFF & Buf[n+0] ) | ((0xFF & Buf[n+1] )<<8) | ((0xFF & Buf[n+2] )<<16) | ((0xFF & Buf[n+3] )<<24))^Key[0];
- B = ((0xFF & Buf[n+4] ) | ((0xFF & Buf[n+5] )<<8) | ((0xFF & Buf[n+6] )<<16) | ((0xFF & Buf[n+7] )<<24))^Key[1];
- C = ((0xFF & Buf[n+8] ) | ((0xFF & Buf[n+9] )<<8) | ((0xFF & Buf[n+10])<<16) | ((0xFF & Buf[n+11])<<24))^Key[2];
- D = ((0xFF & Buf[n+12]) | ((0xFF & Buf[n+13])<<8) | ((0xFF & Buf[n+14])<<16) | ((0xFF & Buf[n+15])<<24))^Key[3];
-// }
-// else { // The above code should yield the same result as these lines. Test this assumption.
- int A2 = Util.readIntLE(Buf, n+0 )^Key[0];
- int B2 = Util.readIntLE(Buf, n+4 )^Key[1];
- int C2 = Util.readIntLE(Buf, n+8 )^Key[2];
- int D2 = Util.readIntLE(Buf, n+12)^Key[3];
-// }
-
- if(A != A2 || B != B2 || C != C2 || D != D2) {
- System.out.println("Assumption broken!");
- System.out.println(" A: 0x" + Util.toHexStringBE(A) + " A2: 0x" + Util.toHexStringBE(A2));
- System.out.println(" B: 0x" + Util.toHexStringBE(B) + " B2: 0x" + Util.toHexStringBE(B2));
- System.out.println(" C: 0x" + Util.toHexStringBE(C) + " C2: 0x" + Util.toHexStringBE(C2));
- System.out.println(" D: 0x" + Util.toHexStringBE(D) + " D2: 0x" + Util.toHexStringBE(D2));
- }
- else
- System.out.println("Assumption correct!");
-
- for(int I=NROUNDS-1; I>=0; I--) {
- T=((C+rol(D,11))^Key[I&3]);
- TA=A^substLong(T);
- T=((D^rol(C,17))+Key[I&3]);
- TB=B^substLong(T);
- A=C;
- B=D;
- C=TA;
- D=TB;
- }
-
- if(true) {
- C ^= Key[0];
- Buf[n+0 ]=(byte)(0xFF & C);
- Buf[n+1 ]=(byte)(0xFF & (C>>>8));
- Buf[n+2 ]=(byte)(0xFF & (C>>>16));
- Buf[n+3 ]=(byte)(0xFF & (C>>>24));
- D ^= Key[1];
- Buf[n+4 ]=(byte)(0xFF & D);
- Buf[n+5 ]=(byte)(0xFF & (D>>>8));
- Buf[n+6 ]=(byte)(0xFF & (D>>>16));
- Buf[n+7 ]=(byte)(0xFF & (D>>>24));
- A ^= Key[2];
- Buf[n+8 ]=(byte)(0xFF & A);
- Buf[n+9 ]=(byte)(0xFF & (A>>>8));
- Buf[n+10]=(byte)(0xFF & (A>>>16));
- Buf[n+11]=(byte)(0xFF & (A>>>24));
- B ^= Key[3];
- Buf[n+12]=(byte)(0xFF & B);
- Buf[n+13]=(byte)(0xFF & (B>>>8));
- Buf[n+14]=(byte)(0xFF & (B>>>16));
- Buf[n+15]=(byte)(0xFF & (B>>>24));
- }
- else {
- System.arraycopy(Util.toByteArrayLE(C^Key[0]), 0, Buf, n+0 , 4);
- System.arraycopy(Util.toByteArrayLE(D^Key[1]), 0, Buf, n+4 , 4);
- System.arraycopy(Util.toByteArrayLE(A^Key[2]), 0, Buf, n+8 , 4);
- System.arraycopy(Util.toByteArrayLE(B^Key[3]), 0, Buf, n+12, 4);
- }
-
- UpdKeys(InBuf);
- }
-
-
- /*
- * As we can't use unsigned data types in Java, we'll have to unsign the data
- * every time we use it. Modifications: unsign the usage of Buf[I] by "& 0xFF".
- */
- /**
- * Updates keys. ;)
- * <pre>
- * Global modify set:
- * Key (int[4])
- * Global read set:
- * CRCTab (int[256])
- * Local use set:
- * (in) Buf (byte[])
- * I (int)
- * </pre>
- */
- public void UpdKeys(byte[]/*UBYTE*/ Buf) {
- for(int I=0; I<16; I+=4) {
- Key[0]^=CRCTab[Buf[I] & 0xFF]; /* xxx may be I'll rewrite this */
- Key[1]^=CRCTab[Buf[I+1] & 0xFF]; /* in asm for speedup */
- Key[2]^=CRCTab[Buf[I+2] & 0xFF];
- Key[3]^=CRCTab[Buf[I+3] & 0xFF];
- }
- }
-
- /* Password is supposed to be trimmed to the actual password length and not zero-terminated. */
- /**
- * Sets crypt keys. ;)<br>
- * <code>Password</code> is supposed to be trimmed to the actual
- * password length and not zero-terminated.<p>
- * <pre>
- * Global read set:
- * InitSubstTable (final short[256])
- * CRCTab
- *
- * Global modify set:
- * Key (final int[4])
- * SubstTable (final short[256])
- * In SetOldKeys:
- * OldKey (final short[4])
- * PN1 (byte)
- * PN2 (byte)
- * PN3 (byte)
- *
- * Local use set:
- * Password (byte[])
- * I (int)
- * J (int)
- * K (int)
- * N1 (short)
- * N2 (short)
- * Psw (final byte[256])
- * Ch (short)
- *
- * Call set:
- * SetOldKeys
- * System.arraycopy
- * EncryptBlock
- * </pre>
- */
- public void SetCryptKeys(byte[] Password) {
- /*unsigned int*/ int I,J,K, PswLength;
- /*unsigned char*/ short N1,N2;
- final /*unsigned char*/ byte[] Psw = new byte[256];
-
- /*UBYTE*/ short Ch;
-
- SetOldKeys(Password);
-
- Key[0]=0xD3A3B879; // Removed the L at the end (indicates 32 bits in C, 64 in Java)
- Key[1]=0x3F6D12F7; // -||-
- Key[2]=0x7515A235; // -||-
- Key[3]=0xA4E7F123; // -||-
- //memset(Psw,0,sizeof(Psw)); // Arrays are automatically initialized to 0 in Java.
- System.arraycopy(Password, 0, Psw, 0, (Password.length<Psw.length?Password.length:Psw.length));
- PswLength = Password.length;//strlen(Password);
- System.arraycopy(InitSubstTable, 0, SubstTable, 0, SubstTable.length); // memcpy(SubstTable,InitSubstTable,sizeof(SubstTable));
-
- for (J=0;J<256;J++) {
- for (I=0;I<PswLength;I+=2) {
- N2=/*(unsigned char)*/(byte)CRCTab[((Psw[I+1]&0xFF)+J)&0xFF];
- for (K=1, N1=/*(unsigned char)*/(byte)CRCTab[((Psw[I]&0xFF)-J)&0xFF]; /* I had to add "&& (N1 < 256)", */
- (N1!=N2) && (N1 < 256); /* because the system crashed with */
- N1++, K++) { /* encrypted RARs */
- /* Swap(&SubstTable[N1],&SubstTable[(N1+I+K)&0xFF]); */
- Ch=SubstTable[N1];
- SubstTable[N1]=SubstTable[(N1+I+K)&0xFF];
- SubstTable[(N1+I+K)&0xFF]=Ch;
- }
- }
- }
- byte[] currentPswBuf = new byte[16];
- for (I=0;I<PswLength;I+=16) {
- System.arraycopy(Psw, I, currentPswBuf, 0, 16);
- EncryptBlock(currentPswBuf);
- }
- }
-
- /**
- * Sets old keys. ;)
- * <pre>
- * Global read set:
- * CRCTab (final int[256])
- *
- * Global modify set:
- * OldKey (final short[4])
- * PN1 (byte)
- * PN2 (byte)
- * PN3 (byte)
- *
- * Local use set:
- * (in) Password (byte[])
- * PswCRC (int)
- * Ch (byte)
- *
- * Call set:
- * //CalcCRC32
- * rol
- * </pre>
- */
- private void SetOldKeys(/*char **/byte[] Password) {
- /*UDWORD*/int PswCRC;
- /*UBYTE*/byte Ch;
- crc.reset();
- crc.update(Password);
- PswCRC=(int)crc.getValue();//CalcCRC32(0xFFFFFFFF,/*(UBYTE*)*/Password,0,Util.strlen(Password));
- OldKey[0]=(/*UWORD*/short)PswCRC;
- OldKey[1]=(/*UWORD*/short)(PswCRC>>>16);
- OldKey[2]=OldKey[3]=0;
- PN1=PN2=PN3=0;
- //while ((Ch=*Password)!=0) {
- for(int i = 0; (Ch=Password[i])!=0; ++i) {
- PN1+=Ch;
- PN2^=Ch;
- PN3+=Ch;
- PN3=(/*UBYTE*/byte)rol(PN3,1);
- OldKey[2]^=((/*UWORD*/short)(Ch^CRCTab[Ch]));
- OldKey[3]+=((/*UWORD*/short)(Ch+(CRCTab[Ch]>>>16)));
- //Password++;
- }
- }
-
- /**
- * Initializes the CRC table <code>crcTab</code>, which has to have a length of 256 elements.
- * @param crcTab the array where the initialized CRC table is to be stored
- * @return the same array that was given as input parameter (for convenience)
- */
- static int[] InitCRC(int[] crcTab) {
- int I, J;
- /*UDWORD*/int C;
- for (I=0;I<256;I++) {
- for (C=I,J=0;J<8;J++)
- C=(C & 1)!=0 ? (C>>>1)^0xEDB88320 : (C>>>1);
- crcTab[I]=C;
- }
- return crcTab;
- }
-
-
- /**
- * Calculates the CRC32 checksum from its arguments.
- * <pre>
- * Global read set:
- * CRCTab ([256])
- *
- * Local use set:
- * (in) StartCRC (int)
- * (in) Addr (byte[])
- * (in) offset (int)
- * (in) Size (int)
- * I (int)
- *
- * Purely functional behavior, no side effects.
- * </pre>
- * @return the updated sum
- */
- static int CalcCRC32(int StartCRC, byte[] Addr, int offset, int Size) {
- /*unsigned */int I;
- for (I=offset; I<Size; I++)
- StartCRC = CRCTab[(byte)StartCRC ^ Addr[I]] ^ (StartCRC >>> 8);
- return(StartCRC);
- }
-
- /* No side effects. */
- private static void debug_log(String s) {
- System.err.println("DEBUG: " + s);
- }
-
- /** No side effects (except position in f increasing). */
- private static int tread(RARFileEntryStream f, byte[] buffer, int offset, int length) {
- try {
- return f.read(buffer, offset, length);
- } catch(Exception e) { e.printStackTrace(); return -1; }
- }
-}
-
-/* **************************************************************************
- ****************************************************************************
- ****************************************************************************
- ************************************************************************** */
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-/* **************************************************************************
- ****************************************************************************
- ****************************************************************************
- ****************************************************************************
- ******* *******
- ******* *******
- ******* *******
- ******* D E B U G F U N C T I O N S *******
- ******* *******
- ******* *******
- ******* *******
- ****************************************************************************
- ****************************************************************************
- ****************************************************************************
- ************************************************************************** */
-// #ifdef _DEBUG_LOG
-
-
-// /* -- global stuff -------------------------------------------------------- */
-// char log_file_name[256]; /* file name for the log file */
-// DWORD debug_start_time; /* starttime of debug */
-// BOOL debug_started = FALSE; /* debug_log writes only if */
-// /* this is TRUE */
-// /* ------------------------------------------------------------------------ */
-
-
-// /* -- global functions ---------------------------------------------------- */
-// void debug_init_proc(char *file_name)
-// /* Create/Rewrite a log file */
-// {
-// FILE *fp;
-// char date[] = __DATE__;
-// char time[] = __TIME__;
-
-// debug_start_time = GetTickCount(); /* get start time */
-// strcpy(log_file_name, file_name); /* save file name */
-
-// if((fp = fopen(log_file_name, CREATETEXT)) != NULL)
-// {
-// debug_started = TRUE; /* enable debug */
-// fprintf(fp, "Debug log of UniquE's RARFileLib\n"\
-// "~^~~~~~~~~~~~~~~~~~~~~~~~~~~~~^~\n");
-// fprintf(fp, "(executable compiled on %s at %s)\n\n", date, time);
-// fclose(fp);
-// }
-// }
-
-
-// void debug_log_proc(char *text, char *sourcefile, int sourceline)
-// /* add a line to the log file */
-// {
-// FILE *fp;
-
-// if(debug_started == FALSE) return; /* exit if not initialized */
-
-// if((fp = fopen(log_file_name, APPENDTEXT)) != NULL) /* append to logfile */
-
-// {
-// fprintf(fp, " %8u ms (line %u in %s):\n - %s\n",
-// (/*unsigned */int)(GetTickCount() - debug_start_time),
-// sourceline, sourcefile, text);
-// fclose(fp);
-// }
-// }
-
-// /* ------------------------------------------------------------------------ */
-// #endif
-/* **************************************************************************
- ****************************************************************************
- ****************************************************************************
- ************************************************************************** */
-
diff --git a/src/org/catacombae/rarx/FileAttributes.java b/src/org/catacombae/rarx/FileAttributes.java
deleted file mode 100644
index 8e20f2f..0000000
--- a/src/org/catacombae/rarx/FileAttributes.java
+++ /dev/null
@@ -1,29 +0,0 @@
-/*-
- * Copyright (C) 2006 Erik Larsson
- *
- * All rights reserved.
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software
- * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA
- */
-
-package org.catacombae.rarx;
-
-import java.io.PrintStream;
-
-public interface FileAttributes {
- public boolean isDirectory();
- public void print(PrintStream ps, String prefix);
- public void printFields(PrintStream ps, String prefix);
-}
diff --git a/src/org/catacombae/rarx/InvalidDataException.java b/src/org/catacombae/rarx/InvalidDataException.java
deleted file mode 100644
index ad0e029..0000000
--- a/src/org/catacombae/rarx/InvalidDataException.java
+++ /dev/null
@@ -1,29 +0,0 @@
-/*-
- * Copyright (C) 2006 Erik Larsson
- *
- * All rights reserved.
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software
- * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA
- */
-
-package org.catacombae.rarx;
-
-public class InvalidDataException extends RuntimeException {
- private static final long serialVersionUID = 0x2F49A29E49173487L;
- public InvalidDataException(String message) {
- super(message);
- }
-}
-
diff --git a/src/org/catacombae/rarx/Leaf.java b/src/org/catacombae/rarx/Leaf.java
deleted file mode 100644
index 87d7f49..0000000
--- a/src/org/catacombae/rarx/Leaf.java
+++ /dev/null
@@ -1,7 +0,0 @@
-package org.catacombae.rarx;
-
-public class Leaf<A> extends TreeNode<A> {
- public Leaf(A value) { super(value); }
- public Leaf() { super(); }
-}
-
diff --git a/src/org/catacombae/rarx/ListArchiveContents.java b/src/org/catacombae/rarx/ListArchiveContents.java
deleted file mode 100644
index 7fac0f1..0000000
--- a/src/org/catacombae/rarx/ListArchiveContents.java
+++ /dev/null
@@ -1,438 +0,0 @@
-/*-
- * Copyright (C) 2006 Erik Larsson
- *
- * All rights reserved.
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software
- * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA
- */
-
-package org.catacombae.rarx;
-
-import java.util.*;
-import java.io.*;
-import java.security.MessageDigest;
-import java.util.zip.CRC32;
-
-public class ListArchiveContents {
-
- /*
- * Konceptuellt: Vi har en buffer |E4F91...|A81984B....|
- * ^--------^ <- 32 (0x20) bytes,
- */
-
- //public static final byte[] entrySignature = { 0x7C, 0x30, 0x14, 0x30 };
- public static final String BACKSPACE79 = "\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b";
- public static final BufferedReader stdin = new BufferedReader(new InputStreamReader(System.in));
- public static final short ENTRY_TYPE_DIR = 0x0010;
- public static final short ENTRY_TYPE_FILE = 0x0020;
- public static void main(String[] args) throws IOException {
- boolean deleteOnError = true; // Change this to be decided by a command line parameter.
- RandomAccessFile raf = new RandomAccessFile(args[0], "r");
- File outDir = null;
- if(args.length > 1)
- outDir = new File(args[1]);
- byte[] buffer = new byte[4096];
- byte[] pre = new byte[0x16];
- byte[] signature = new byte[0x4];
- byte[] post = new byte[0x6];
- byte[] postString = new byte[0x5];
- byte[] staticEntryData = new byte[pre.length+signature.length+
- post.length+postString.length];
- for(int i = 0; i < staticEntryData.length; ++i)
- staticEntryData[i] = 0;
- ArrayList<byte[]> savedEntries = new ArrayList<byte[]>();
- ArrayList<byte[]> dirEntries = new ArrayList<byte[]>();
- ArrayList<byte[]> fileEntries = new ArrayList<byte[]>();
- LinkedList<String> extractedFiles = new LinkedList<String>();
- LinkedList<String> badFiles = new LinkedList<String>();
- LinkedList<String> createErrorFiles = new LinkedList<String>();
- LinkedList<String> badFilesizeFiles = new LinkedList<String>();
- int signatureCount = 0;
- int readAhead = pre.length+4+post.length;
- int bytesRead = raf.read(buffer);//, readAhead, buffer.length-readAhead);
- long totalBytesRead = bytesRead;
- int lastReadPos = bytesRead;
- //bytesRead += readAhead;
- while(raf.getFilePointer() < raf.length()) {
- for(int i = pre.length; i < lastReadPos-(signature.length+post.length); ++i) {
- if(buffer[i+(0x18-0x16)] == 0x14 &&
- //buffer[i+(0x19-0x16)] == 0x30 && // This one is not really common for all rars.
- //buffer[i+(0x16-0x16)] == 0x7c && buffer[i+(0x17-0x16)] == 0x30
- buffer[i+(0x1b-0x16)] == 0 &&
- (buffer[i+(0x1c-0x16)] == 0x20 || buffer[i+(0x1c-0x16)] == 0x10) &&
- buffer[i+(0x1d-0x16)] == 0 &&
- buffer[i+(0x1e-0x16)] == 0 &&
- buffer[i+(0x1f-0x16)] == 0 //&&
- //buffer[i+(0x20-0x16)] == 0
- ) {
-// System.out.println("buffer[i+(0x1b-0x16)] == " + buffer[i+(0x1b-0x16)]);
-// System.out.println("buffer[i+(0x1c-0x16)] == " + buffer[i+(0x1c-0x16)]);
-// System.out.println("buffer[i+(0x1d-0x16)] == " + buffer[i+(0x1d-0x16)]);
-// System.out.println("buffer[i+(0x1e-0x16)] == " + buffer[i+(0x1e-0x16)]);
-// System.out.println("buffer[i+(0x1f-0x16)] == " + buffer[i+(0x1f-0x16)]);
- ++signatureCount;
- System.out.println("File found at position " + ((raf.getFilePointer()-lastReadPos)+i));
- int fileSize = Util.readIntLE(buffer, i-0xf);
- System.out.println(" Size: " + fileSize + " bytes (0x" + Util.toHexStringBE(fileSize) + ")");
- int crc = Util.readIntLE(buffer, i-6);
- System.out.println(" CRC32: 0x" + Util.toHexStringBE(crc));
- int stringSize = Util.readShortLE(buffer, i+4) & 0xFFFF;
- System.out.println(" String size: " + stringSize);
- short fileType = Util.readShortLE(buffer, i+6);
- System.out.println(" Some type: 0x" + Util.toHexStringBE(fileType));
- int difference = i+signature.length+post.length+stringSize+postString.length-lastReadPos;
-
- if(difference > 0) {
- System.out.println("Beginning of string: " + new String(buffer, i+signature.length+post.length, stringSize-(difference-postString.length), "US-ASCII"));
-// System.out.println(" i=" + i + " post.length=" + post.length + " bytesRead=" + bytesRead);
-// System.out.println(" String size: " + Util.toHexStringBE(stringSize) + " Difference: " + Util.toHexStringBE(difference));
- byte[] diffArray = new byte[difference];
- int tempBytesRead = raf.read(diffArray);
-// System.out.println(" Contents of diffarray: " + new String(diffArray, "US-ASCII"));
- if(tempBytesRead != diffArray.length)
- throw new RuntimeException("Read error."); // Orka..
- totalBytesRead += tempBytesRead;
-
- System.arraycopy(buffer, difference, buffer, 0, lastReadPos-difference);
- System.arraycopy(diffArray, 0, buffer, lastReadPos-difference, diffArray.length);
- i -= difference;
-// System.out.println(" After stringshift: " + new String(buffer, i+4+post.length, stringSize-difference, "US-ASCII"));
-// System.out.println(" " + new String(buffer, i+4+post.length, stringSize, "US-ASCII"));
- }
-
- // Save the data for future analysis
- byte[] data = new byte[staticEntryData.length];
- System.arraycopy(buffer, i-pre.length, data, 0, pre.length+signature.length+post.length);
- System.arraycopy(buffer, i+signature.length+post.length+stringSize, data, pre.length+signature.length+post.length, postString.length);
- savedEntries.add(data);
-
- try {
- /*
- javax.swing.JFrame jf = new javax.swing.JFrame();
- javax.swing.JTextArea tf = new javax.swing.JTextArea(80, 50);
- tf.setFont(new java.awt.Font("Monospaced", java.awt.Font.PLAIN, 12));
- jf.add(new javax.swing.JScrollPane(tf));
- jf.pack();
- jf.setVisible(true);
- for(String charset : java.nio.charset.Charset.availableCharsets().keySet())
- tf.append("Name: \"" + new String(buffer, i+4+post.length, stringSize, charset) + "\" in charset: " + charset + "\n");
- if(true)
- return;
- */
-
- String fullFilename = new String(buffer, i+4+post.length, stringSize, "IBM437");
- String[] filenameComponents = fullFilename.split("\0");
- String filename = filenameComponents[0];
- System.out.println(" Name: \"" + filename + "\"");
- //stdin.readLine();
- System.out.println(" In hex: 0x" + Util.byteArrayToHexString(buffer, i+4+post.length, stringSize));
- if(fileType == ENTRY_TYPE_DIR) {
- System.err.println("Assuming to be dir: " + filename);
- dirEntries.add(data);
- }
-// else if(fileSize == 0 || crc == 0 || filename.split("\\.").length == 2) {
-// System.err.println("Suspicious non-10 dir found: " + filename);
-// System.err.println(" fileSize=" + fileSize);
-// System.err.println(" crc=" + crc);
-// System.err.println(" dots in name: " + (filename.split("\\.").length-1));
-// }
- if(fileType == ENTRY_TYPE_FILE)
- fileEntries.add(data);
-
- if(fileType != ENTRY_TYPE_DIR && fileType != ENTRY_TYPE_FILE) {
- System.err.println("NEW fileType FOUND: 0x" + Util.toHexStringBE(fileType));
- stdin.readLine();
- }
- //System.err.println(" " + filename.split("\\.").length);
- if(difference > 0)
- System.out.println(" (array extended)");
- else
- System.out.println();
-
- if(fileType == ENTRY_TYPE_FILE && outDir != null && fileSize != 0 && crc != 0) {
- File outFile = new File(outDir, filename);
- File outParent = outFile.getParentFile();
- if(outParent != null && ((outParent.exists() && outParent.isDirectory()) ||
- outParent.mkdirs())) {
- int seekIndexInBuffer = i+signature.length+post.length+stringSize+0x5;
- long seekPosition = (raf.getFilePointer()-lastReadPos)+seekIndexInBuffer;
- if(seekPosition+fileSize > raf.length()) {
- System.out.println("ERROR: Invalid file size for \"" + filename + "\" (" + fileSize + " bytes)");
- badFilesizeFiles.add(filename);
- }
- else {
- RandomAccessFile outRaf = new RandomAccessFile(outFile, "rw");
- System.out.println("input.getFilePointer() = " + raf.getFilePointer());
- System.out.println("readAhead = " + (readAhead));
- System.out.println("bytesRead = "+ bytesRead);
- System.out.println("lastReadPos = "+ lastReadPos);
- System.out.println("i = " + i);
- byte[] mycrc32 = copyData(raf, seekPosition, outRaf, 0, fileSize);
- outRaf.close();
- System.out.println("Their digest: 0x" + Util.toHexStringBE(crc));
- System.out.println("My digest : 0x" + Util.byteArrayToHexString(mycrc32));
- //stdin.readLine();
- if(Util.arraysEqual(Util.toByteArrayBE(crc), mycrc32)) {
- System.out.println("Digests are equal.");
- extractedFiles.addLast(filename);
- /* H�r b�r vi flytta fram filpekaren till precis efter den extraherade filen,
- f�r att undvika att titta i rar filer som �r lagrade inuti andra rar-filer,
- samt f�r att snabba upp extraheringen. */
- long oldFilePointer = raf.getFilePointer();
- long newFilePointer = seekPosition+fileSize-readAhead;
- if(newFilePointer > oldFilePointer) {
- raf.seek(newFilePointer);
- bytesRead = raf.read(buffer);
- lastReadPos = bytesRead;
- totalBytesRead += (raf.getFilePointer() - oldFilePointer);
- i = pre.length;
- }
- else {
- System.out.print("Situation where newFilePointer <= oldFilePointer har occurred!");
- //stdin.readLine();
- }
- }
- else {
- System.out.println("NOT EQUAL! :(:(:(:(");
- if(deleteOnError) {
- while(!outFile.delete()) {
- System.out.print("Could not delete file \"" + outFile + "\" try again (y/n)? ");
- String answer = stdin.readLine();
- while(!(answer.trim().equalsIgnoreCase("y") || answer.trim().equalsIgnoreCase("n"))) {
- System.out.print("Ivalid answer. Answer again: (y/n)? ");
- answer = stdin.readLine();
- }
-
- if(answer.trim().equalsIgnoreCase("n"))
- break;
- }
- }
- badFiles.addLast(filename);
- //stdin.readLine();
- }
- }
- //stdin.readLine();
- }
- else {
- System.out.println("Failed to create \"" + outFile + "\"");
- createErrorFiles.addLast(filename);
- }
- }
- } catch(Exception e) {
- e.printStackTrace();
- String answer;
- do {
- System.out.print("Do you want to continue (y/n)? ");
- answer = stdin.readLine();
- } while(!(answer.trim().equalsIgnoreCase("y") || answer.trim().equalsIgnoreCase("n")));
-
- if(answer.trim().equalsIgnoreCase("n"))
- System.exit(0);
- }
- }
- }
- /* Vi vill nu flytta (readAhead) bytes data fr�n slutet av den fyllda delen av arrayen till b�rjan. */
- System.arraycopy(buffer, lastReadPos-readAhead, buffer, 0, readAhead);
-
- /* L�s in nya data i arrayen, men skriv inte �ver dess inledande (readAhead) bytes */
- bytesRead = raf.read(buffer, readAhead, buffer.length-readAhead);
- totalBytesRead += bytesRead;
- lastReadPos = readAhead+bytesRead;
- }
- System.out.println();
- System.err.println("Found " + signatureCount + " signatures.");
- System.err.println("Found " + savedEntries.size() + " entries.");
- if(savedEntries.size() > 0) {
- System.err.println("Running analysis on all entries...");
- Region[] similarRegions = findSimilarities(savedEntries);
- byte[] entry = savedEntries.get(0);
- System.out.println("First entry: 0x" + Util.byteArrayToHexString(entry));
- LinkedList<byte[]> regionData = new LinkedList<byte[]>();
- for(Region r : similarRegions) {
- byte[] currentRegion = new byte[(int)((r.endOffset+1)-r.startOffset)];
- System.arraycopy(entry, (int)r.startOffset, currentRegion, 0, currentRegion.length);
- System.out.println(r + ": 0x" + Util.byteArrayToHexString(currentRegion));
- regionData.addLast(currentRegion);
- }
- }
- if(dirEntries.size() > 0) {
- System.err.println("Running analysis on directories only...");
- Region[] similarRegions = findSimilarities(dirEntries);
- byte[] entry = dirEntries.get(0);
- LinkedList<byte[]> regionData = new LinkedList<byte[]>();
- for(Region r : similarRegions) {
- byte[] currentRegion = new byte[(int)((r.endOffset+1)-r.startOffset)];
- System.arraycopy(entry, (int)r.startOffset, currentRegion, 0, currentRegion.length);
- System.out.println(r + ": 0x" + Util.byteArrayToHexString(currentRegion));
- regionData.addLast(currentRegion);
- }
- }
- if(fileEntries.size() > 0) {
- System.err.println("Running analysis on files only...");
- Region[] similarRegions = findSimilarities(fileEntries);
- byte[] entry = fileEntries.get(0);
- LinkedList<byte[]> regionData = new LinkedList<byte[]>();
- for(Region r : similarRegions) {
- byte[] currentRegion = new byte[(int)((r.endOffset+1)-r.startOffset)];
- System.arraycopy(entry, (int)r.startOffset, currentRegion, 0, currentRegion.length);
- System.out.println(r + ": 0x" + Util.byteArrayToHexString(currentRegion));
- regionData.addLast(currentRegion);
- }
- }
-
- if(badFiles.size() > 0) {
- System.out.println("The following " + badFiles.size() + " files failed the CRC-32 checksum test" + (deleteOnError?" and were not extracted":"") + ":");
- for(String filename : badFiles)
- System.out.println(" \"" + filename + "\"");
- }
- if(badFilesizeFiles.size() > 0) {
- System.out.println("The following " + badFilesizeFiles.size() + " files could not be extracted due to incorrectly specified file size:");
- for(String filename : badFilesizeFiles)
- System.out.println(" \"" + filename + "\"");
- }
- if(createErrorFiles.size() > 0) {
- System.out.println("The following " + createErrorFiles.size() + " files could not be created:");
- for(String filename : createErrorFiles)
- System.out.println(" \"" + filename + "\"");
- }
-
- System.out.println("Read " + totalBytesRead + " bytes from input file.");
- }
-
- /** Returns the calculated CRC-32 checksum of the copied data. */
- public static byte[] copyData(RandomAccessFile input, long inputPos, RandomAccessFile output, long outputPos, long fileSize) throws IOException {
- CRC32 crc32Digest = new CRC32();//MessageDigest.getInstance("CRC32");
- long oldFilePointer = input.getFilePointer();
- byte[] otherBuffer = new byte[4096];
- input.seek(inputPos);
- System.out.println("Seeking to " + input.getFilePointer() + ".");
- int totalBytesRead2 = 0;
- System.out.println("otherBuffer.length="+otherBuffer.length+" fileSize="+fileSize+" totalBytesRead2="+totalBytesRead2);
- System.out.println("input.read("+otherBuffer+", "+0+", " + (totalBytesRead2+otherBuffer.length<fileSize?otherBuffer.length:fileSize-totalBytesRead2) + ");");
- int bytesRead2 = input.read(otherBuffer, 0, (totalBytesRead2+otherBuffer.length<fileSize?otherBuffer.length:(int)(fileSize-totalBytesRead2)));
- totalBytesRead2 += bytesRead2;
- while(totalBytesRead2 < fileSize) {
- crc32Digest.update(otherBuffer, 0, bytesRead2);
- output.write(otherBuffer, 0, bytesRead2);
- bytesRead2 = input.read(otherBuffer, 0, (totalBytesRead2+otherBuffer.length<fileSize?otherBuffer.length:(int)(fileSize-totalBytesRead2)));
- totalBytesRead2 += bytesRead2;
- }
-
- crc32Digest.update(otherBuffer, 0, bytesRead2);
- output.write(otherBuffer, 0, bytesRead2);
- System.out.println("Extracted contents!");// Check them and press enter...");
- input.seek(oldFilePointer);
- return Util.toByteArrayBE((int)(crc32Digest.getValue() & 0xFFFFFFFF));
- }
- public static Region[] findSimilarities(List<byte[]> arrays) throws IOException {
- if(arrays.size() < 1)
- return new Region[0];
-
- long minLength = Long.MAX_VALUE;
- boolean differentLengths = false;
- for(byte[] currentData : arrays) {
- if(currentData.length < minLength) {
- if(minLength != Long.MAX_VALUE)
- differentLengths = true;
- minLength = currentData.length;
- }
- }
- if(differentLengths)
- System.err.println("WARNING: Input arrays are not of equal length...");
-
- LinkedList<Region> regions = new LinkedList<Region>();
-
- long regionStart = -1;
- for(int i = 0; i < minLength; ++i) {
- int lastByte = -1;
- int[] values = new int[arrays.size()];
- for(int j = 0; j < arrays.size(); ++j)
- values[j] = arrays.get(j)[i];//files[j].read();
-
- for(int currentByte : values) {
- //System.out.print("0x" + Integer.toHexString(currentByte) + " == ");
- if(lastByte == -1)
- lastByte = currentByte;
- else if(currentByte != lastByte) {
- lastByte = -1;
- //System.out.println("FALSE");
- break;
- }
- }
-// if(lastByte != -1)
-// System.out.println("TRUE");
- if(lastByte == -1 && regionStart != -1) {
- //System.out.println("Region concluded at 0x" + Long.toHexString(i));
- regions.add(new Region(regionStart, i-1));
- regionStart = -1;
- }
- else if(lastByte != -1 && regionStart == -1) {
- //System.out.println("New region started at 0x" + Long.toHexString(i));
- regionStart = i;
- }
- }
-
- System.out.println("Found " + regions.size() + " similar regions.");
- long totalSimilarBytes = 0;
- for(Region r : regions) {
- long regionLength = r.endOffset-r.startOffset+1;
- System.out.println(" 0x" + Long.toHexString(r.startOffset) + "-0x" + Long.toHexString(r.endOffset) + " (" + regionLength + " B)");
- totalSimilarBytes += regionLength;
- }
- System.out.println("Total matching bytes: " + totalSimilarBytes);
- return regions.toArray(new Region[regions.size()]);
- }
-
- private static class Region {
- public long startOffset;
- public long endOffset;
-
- public Region(long startOffset, long endOffset) {
- this.startOffset = startOffset;
- this.endOffset = endOffset;
- }
- }
-}
-
-class TestModel {
- public static void main(String[] args) {
- byte[] buffer = new byte[4096];
- int readAhead = 32;
- fill(buffer);
- while(true) {
- for(int i = 0; i < buffer.length-readAhead; ++i) {
-
- }
-
- // Vi har g�tt igenom buffer fr�n 0 till n-readAhead
- // Kopiera d� readAhead bytes fr�n slutet till b�rjan och fyll
- System.arraycopy(buffer, buffer.length-readAhead, buffer, 0, readAhead);
- fill(buffer, readAhead, buffer.length-readAhead);
- }
- }
-
- public static int alternate(byte[] buffer) {
- fill(buffer);
- while(true) {
- for(int i = 0; i < buffer.length; ++i)
- dosomething(buffer[i]);
- fill(buffer);
- }
- }
-
- public static void fill(byte[] buffer) {}
- public static void fill(byte[] buffer, int i, int j) {}
- public static void dosomething(byte b) {}
-}
diff --git a/src/org/catacombae/rarx/ListFilesInArchive.java b/src/org/catacombae/rarx/ListFilesInArchive.java
deleted file mode 100644
index 1f04825..0000000
--- a/src/org/catacombae/rarx/ListFilesInArchive.java
+++ /dev/null
@@ -1,173 +0,0 @@
-/*-
- * Copyright (C) 2006 Erik Larsson
- *
- * All rights reserved.
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software
- * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA
- */
-
-package org.catacombae.rarx;
-
-import java.util.*;
-import java.io.*;
-
-public class ListFilesInArchive {
- public static void main(String[] args) {
- try {
- File f = new File(args[0]);
- RARFileEntry[] entries = listFiles(f);
- for(RARFileEntry entry : entries) {
- NewFileHeader nfh = entry.getHeader(0);
- System.out.println(nfh.getFilenameAsString());
- }
- } catch(InvalidDataException e) {
- System.out.println("Invalid RAR-file. Message: " + e.getMessage());
- System.out.println("File: \"" + args[0] + "\"");
- } catch(IOException ioe) {
- ioe.printStackTrace();
- }
- }
-
- public static Tree<RARFileEntry> listFilesAsTree(File rarFile) throws IOException, InvalidDataException {
- return listFilesAsTree(rarFile, false);
- }
- public static Tree<RARFileEntry> listFilesAsTree(File rarFile, boolean includeComments) throws IOException, InvalidDataException {
- RARFileEntry[] contents = listFiles(rarFile, includeComments);
-
- // Create the empty directory tree
- Tree<RARFileEntry> rarTree = new Tree<RARFileEntry>();
- for(RARFileEntry currentEntry : contents) {
- NewFileHeader nfh = currentEntry.getHeader(0);
-
- String[] filenameComponents = nfh.getFilenameAsString().split("\\" + NewFileHeader.PATH_SEPARATOR);
- Tree<RARFileEntry> currentNode = rarTree;
-
- // Loop through the first n-1 components and create tree entries when needed
- for(int i = 0; i < filenameComponents.length-1; ++i) {
- TreeNode<RARFileEntry> childNode = currentNode.get(filenameComponents[i]);
- if(childNode == null) {
- childNode = new Tree<RARFileEntry>();
- currentNode.put(filenameComponents[i], childNode);
- }
-
- if(childNode instanceof Tree)
- currentNode = (Tree<RARFileEntry>)childNode;
- else
- throw new RuntimeException("Duplicate entries in RAR file");
- }
-
- // The last component is mapped to the current RARFileEntry
- TreeNode<RARFileEntry> childNode = currentNode.get(filenameComponents[filenameComponents.length-1]);
- if(childNode == null) {
- if(nfh.getFileAttributesStructured().isDirectory())
- childNode = new Tree<RARFileEntry>(currentEntry);
- else
- childNode = new Leaf<RARFileEntry>(currentEntry);
- currentNode.put(filenameComponents[filenameComponents.length-1], childNode);
- }
- else if(nfh.getFileAttributesStructured().isDirectory()) {
- if(childNode.getValue() == null)
- childNode.setValue(currentEntry);
- else
- throw new RuntimeException("Duplicate entries in RAR file");
- }
- else
- throw new RuntimeException("Duplicate entries in RAR file");
- }
-
- // Should probably check that the directory structure is complete before passing it on
-
- return rarTree;
- }
-
-
- public static RARFileEntry[] listFiles(File rarFile) throws IOException, InvalidDataException {
- return listFiles(rarFile, false);
- }
- public static RARFileEntry[] listFiles(File rarFile, boolean includeComments) throws IOException, InvalidDataException {
- LinkedList<RARFileEntry> entries = new LinkedList<RARFileEntry>();
- RARFileEntry outgoingEntry = null;
- mainLoop:
- do {
- //outgoingEntry = null;
- RandomAccessFile raf = new RandomAccessFile(rarFile, "r");
-
- RARFile.readMarkHeader(raf);
- //NewMainArchiveHeader nmah = RARFile.readNewMainArchiveHeader(raf);
- //nmah.print(System.out, "");
- long offset = raf.getFilePointer();
- RARHeader rh = RARFile.readHeader(raf);
- while(rh != null) {
- try {
- if(rh instanceof NewFileHeader && (includeComments || !(rh instanceof CommentHeader))) {
- NewFileHeader nfh = (NewFileHeader)rh;
- if(!nfh.hasIncomingData()) {
- RARFileEntry rfe = new RARFileEntry(rarFile, offset, nfh);
- if(outgoingEntry != null && nfh.hasOutgoingData()) {
- throw new RuntimeException("Found two outgoing files in the same archive!");
- }
- else if(nfh.hasOutgoingData())
- outgoingEntry = rfe;
-
- entries.add(rfe);
- }
- else {
- if(outgoingEntry != null) {
- outgoingEntry.addPart(rarFile, offset, nfh);
- if(!nfh.hasOutgoingData())
- outgoingEntry = null;
- }
- else {
- // Reading incomplete entry.
- RARFileEntry rfe = new RARFileEntry(rarFile, offset, nfh);
- entries.add(rfe);
- if(nfh.hasOutgoingData())
- outgoingEntry = rfe;
- }
- }
- /*
- if(!nfh.hasIncomingData())
- entries.add(nfh);
- if(nfh.hasOutgoingData()) {
- if(outgoingEntry == null)
- outgoingEntry = nfh;
- else
- throw new RuntimeException("Found two outgoing files in the same archive!");
- }
- */
- //nfh.print(System.out, "");
- }
- offset = raf.getFilePointer();
- rh = RARFile.readHeader(raf);
- } catch(IOException ioe) {
- ioe.printStackTrace();
- break mainLoop;
- }
- }
- if(outgoingEntry != null) {
- File oldRarFile = rarFile;
- rarFile = RARFileEntryStream.getNextFile(rarFile);
- if(rarFile == null)
- throw new FileNotFoundException("Could not find successor to \"" + oldRarFile + "\"");
-// long posInNextFile = RARFileEntryStream.getMatchingPosInFile(nextFile, nfh);
-// if(posInNextFile == -1)
-// throw new FileNotFoundException();
-// getSegments(nextFile, posInNextFile, list, true);
- }
- } while(outgoingEntry != null);
-
- return entries.toArray(new RARFileEntry[entries.size()]);
- }
-}
diff --git a/src/org/catacombae/rarx/ListRecursive.java b/src/org/catacombae/rarx/ListRecursive.java
deleted file mode 100644
index a0d34d8..0000000
--- a/src/org/catacombae/rarx/ListRecursive.java
+++ /dev/null
@@ -1,92 +0,0 @@
-/*-
- * Copyright (C) 2006 Erik Larsson
- *
- * All rights reserved.
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software
- * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA
- */
-
-package org.catacombae.rarx;
-
-import java.io.*;
-import java.util.regex.Pattern;
-
-public class ListRecursive {
- public static class RegexpFileFilter implements FileFilter {
- private String pattern;
- public RegexpFileFilter(String pattern) {
- this.pattern = pattern;
- }
- public boolean accept(File f) {
- return Pattern.matches(pattern, f.getName());
- }
- }
-
- public static void main(String[] args) throws IOException {
- File rootDir = null;
- String pattern = null;
- File outFile = null;
- System.out.println("args.length=" + args.length);
- if(args.length > 2) {
- rootDir = new File(args[0]);
- pattern = args[1];
- outFile = new File(args[2]);
- System.out.println("Writing to file " + outFile.getCanonicalPath());
- }
- else if(args.length > 1) {
- rootDir = new File(args[0]);
- pattern = args[1];
- }
- else if(args.length > 0)
- pattern = args[0];
- else {
- System.out.println("Could not parse arguments.");
- return;
- }
-
- if(rootDir == null)
- rootDir = new File(System.getProperty("user.dir"));
-
- FileFilter fnf;
- if(pattern == null)
- fnf = null;
- else
- fnf = new RegexpFileFilter(pattern);
-
- if(outFile == null)
- listRecursive(rootDir, fnf, System.out);
- else
- listRecursive(rootDir, fnf, new PrintStream(new FileOutputStream(outFile), false, "UTF-8"));
- }
-
- public static void listRecursive(File rootDir, FileFilter fnf, PrintStream ps) {
- File[] allChildren = rootDir.listFiles();
- File[] matchingChildren;
- if(fnf == null)
- matchingChildren = allChildren;
- else
- matchingChildren = rootDir.listFiles(fnf);
-
- if(matchingChildren != null) {
- for(File child : matchingChildren)
- ps.println(child);
- }
-
- if(allChildren != null) {
- for(File child : allChildren)
- listRecursive(child, fnf, ps);
- }
- }
-}
diff --git a/src/org/catacombae/rarx/MarkHeader.java b/src/org/catacombae/rarx/MarkHeader.java
deleted file mode 100644
index 76c17ef..0000000
--- a/src/org/catacombae/rarx/MarkHeader.java
+++ /dev/null
@@ -1,48 +0,0 @@
-/*-
- * Copyright (C) 2006 Erik Larsson
- *
- * All rights reserved.
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software
- * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA
- */
-
-package org.catacombae.rarx;
-
-public class MarkHeader extends RARHeader {
- private static final byte[] oldRarHeader = { 0x52, 0x45, 0x7e, 0x5e };
- private static final byte[] rar2Header = { 0x52, 0x61, 0x72, 0x21, 0x1a, 0x07, 0x00 };
- private static final byte[] uniqueHeader = { 0x55, 0x6e, 0x69, 0x71, 0x75, 0x45, 0x21 }; // "UniquE!" in ASCII
-
- public MarkHeader(byte[] data, int offset) {
- super(data, offset);
- validateData();
- }
-
- protected void validateData() {
- byte[] mark = getHeaderData();
- if(Util.arraysEqual(Util.createCopy(mark, 0, 4), oldRarHeader)) {
- throw new InvalidDataException("An older, unsupported RAR format was detected.");
- }
- else {
- /* original RAR v2.0 */
- if(Util.arraysEqual(mark, rar2Header) ||
- Util.arraysEqual(mark, uniqueHeader)) {
-
- }
- else
- throw new InvalidDataException("Not a RAR file.");
- }
- }
-}
diff --git a/src/org/catacombae/rarx/NewFileHeader.java b/src/org/catacombae/rarx/NewFileHeader.java
deleted file mode 100644
index 104bed1..0000000
--- a/src/org/catacombae/rarx/NewFileHeader.java
+++ /dev/null
@@ -1,428 +0,0 @@
-/*-
- * Copyright (C) 2006 Erik Larsson
- *
- * All rights reserved.
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software
- * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA
- */
-
-package org.catacombae.rarx;
-
-import java.util.LinkedList;
-import java.util.Iterator;
-import java.util.Calendar;
-import java.util.Date;
-import java.io.PrintStream;
-import java.io.UnsupportedEncodingException;
-
-public class NewFileHeader extends RARHeader {
- /*
- * struct NewFileHeader
- * size: 32 bytes
- *
- * BP Size Description
- * 0 2 HeadCRC
- * 2 1 HeadType
- * 3 2 Flags
- * 5 2 HeadSize
- * 7 4 PackSize
- * 11 4 UnpSize
- * 15 1 HostOS
- * 16 4 FileCRC
- * 20 4 FileTime
- * 24 1 UnpVer
- * 25 1 Method
- * 26 2 NameSize
- * 28 4 FileAttr
- */
-
- // Possible values for the hostOS field in NewFileHeader, and possibly elsewhere...
- public static final int HOSTOS_MS_DOS = 0;
- public static final int HOSTOS_OS2 = 1;
- public static final int HOSTOS_WIN_32 = 2;
- public static final int HOSTOS_UNIX = 3;
- public static final String[] hostOSStrings = { "MS-DOS", "OS/2", "Win32", "UNIX" };
-
- public static final int FM_NORMAL = 0x00;
- public static final int FM_RDONLY = 0x01;
- public static final int FM_HIDDEN = 0x02;
- public static final int FM_SYSTEM = 0x04;
- public static final int FM_LABEL = 0x08;
- public static final int FM_DIREC = 0x10;
- public static final int FM_ARCH = 0x20;
-
- public static final String PATH_SEPARATOR = "\\";
-
- private final byte[] packSize = new byte[4];
- private final byte[] unpSize = new byte[4];
- private final byte[] hostOS = new byte[1];
- private final byte[] fileCRC = new byte[4];
- private final byte[] fileTime = new byte[4];
- private final byte[] unpVer = new byte[1];
- private final byte[] method = new byte[1];
- private final byte[] nameSize = new byte[2];
- private final byte[] fileAttr = new byte[4];
- private final byte[] packSizeExtended;
- private final byte[] unpSizeExtended;
- private final byte[] filename;
- private final byte[] trailingData;
-
- public NewFileHeader(byte[] data, int offset) {
- super(data, offset);
- System.arraycopy(data, offset+7, packSize, 0, 4);
- System.arraycopy(data, offset+11, unpSize, 0, 4);
- System.arraycopy(data, offset+15, hostOS, 0, 1);
- System.arraycopy(data, offset+16, fileCRC, 0, 4);
- System.arraycopy(data, offset+20, fileTime, 0, 4);
- System.arraycopy(data, offset+24, unpVer, 0, 1);
- System.arraycopy(data, offset+25, method, 0, 1);
- System.arraycopy(data, offset+26, nameSize, 0, 2);
- System.arraycopy(data, offset+28, fileAttr, 0, 4);
- if(hasExtendedHeader()) {
- packSizeExtended = new byte[4];
- unpSizeExtended = new byte[4];
- System.arraycopy(data, offset+32, packSizeExtended, 0, 4);
- System.arraycopy(data, offset+36, unpSizeExtended, 0, 4);
- }
- else {
- packSizeExtended = new byte[0];
- unpSizeExtended = new byte[0];
- }
- final int extSize = packSizeExtended.length + unpSizeExtended.length;
- filename = new byte[getNameSize()];
- trailingData = new byte[getHeadSize()-(getStaticSize()+extSize+filename.length)];
- System.arraycopy(data, offset+32+extSize, filename, 0, filename.length);
- System.arraycopy(data, offset+32+extSize+filename.length, trailingData, 0, trailingData.length);
- validateData();
- }
-
- public static int getStaticSize() { return 32; }
- public int getSize() { return _getSize(); }
- private int _getSize() { return getHeadSize(); }
-
- protected void validateData() {
- //print(System.out, "");
- super.validateData();
- if(getHeadType() != FILE_HEAD)
- throw new InvalidDataException("Incorrect head type! (headType=" + getHeadType() + ")");
- if(getHeadSize() < getStaticSize())
- throw new InvalidDataException("Invalid size! (size=" + getHeadSize() + ")");
- if(getHostOSAsString() == null)
- throw new InvalidDataException("Host OS value invalid.");
- }
-
- public long getPackSize() {
- long result = Util.readIntLE(packSize) & 0xFFFFFFFFL;
- if(packSizeExtended.length == 4)
- result |= (Util.readIntLE(packSizeExtended) & 0xFFFFFFFFL) << 32;
- return result;
- }
- public long getUnpSize() {
- long result = Util.readIntLE(unpSize) & 0xFFFFFFFFL;
- if(unpSizeExtended.length == 4)
- result |= (Util.readIntLE(unpSizeExtended) & 0xFFFFFFFFL) << 32;
- return result;
-// if(unpSizeExtended.length == 4) {
-// return Util.readIntLE(unpSize);
- }
- public byte getHostOS() { return Util.readByteLE(hostOS); }
- public int getFileCRC() { return Util.readIntLE(fileCRC); }
- public int getFileTime() { return Util.readIntLE(fileTime); }
- public byte getUnpVer() { return Util.readByteLE(unpVer); }
- public byte getMethod() { return Util.readByteLE(method); }
- public short getNameSize() { return Util.readShortLE(nameSize); }
- public int getFileAttr() { return Util.readIntLE(fileAttr); }
- public byte[] getFilename() { return Util.createCopy(filename); }
- public byte[] getTrailingData() { return Util.createCopy(trailingData); }
-
- public byte[] getHeaderData() {
- byte[] data = new byte[_getSize()];
- System.arraycopy(super.getHeaderData(), 0, data, 0, super.getSize());
- System.arraycopy(packSize, 0, data, 7, packSize.length);
- System.arraycopy(unpSize, 0, data, 11, unpSize.length);
- System.arraycopy(hostOS, 0, data, 15, hostOS.length);
- System.arraycopy(fileCRC, 0, data, 16, fileCRC.length);
- System.arraycopy(fileTime, 0, data, 20, fileTime.length);
- System.arraycopy(unpVer, 0, data, 24, unpVer.length);
- System.arraycopy(method, 0, data, 25, method.length);
- System.arraycopy(nameSize, 0, data, 26, nameSize.length);
- System.arraycopy(fileAttr, 0, data, 28, fileAttr.length);
- if(hasExtendedHeader()) {
- System.arraycopy(packSizeExtended, 0, data, 32, 4);
- System.arraycopy(unpSizeExtended, 0, data, 36, 4);
- }
- final int extSize = packSizeExtended.length + unpSizeExtended.length;
- System.arraycopy(filename, 0, data, 32+extSize, filename.length);
- System.arraycopy(trailingData, 0, data, 32+extSize+filename.length, trailingData.length);
- return data;
- }
-
- /**
- * true if the header is 40 bytes long, false if it is 32 bytes long
- * The 40 byte header exists to accommodate filesizes > 2^32
- */
- public boolean hasExtendedHeader() {
- return getFlag(8);
- }
-
- /**
- * true if this file is a continuation of a previous file (split archive)
- */
- public boolean hasIncomingData() {
- return getFlag(0);
- }
-
- /**
- * true if this file continues in another file (split archive)
- */
- public boolean hasOutgoingData() {
- return getFlag(1);
- }
-
- public Date getFileTimeAsDate() {
- int data = getFileTime();
- int year = 1980 + ((data >> (4+5+5+6+5)) & 0x7F);
- int month = ((data >> (5+5+6+5)) & 0xF)-1;
- int day = (data >> (5+6+5)) & 0x1F;
- int hour = (data >> (6+5)) & 0x1F;
- int minute = (data >> (5)) & 0x3F;
- int doublesecond = data & 0x1F; // the archive format only supports 2-second precision (probably due to simpler design)
-
-// System.out.println("year = " + year);
-// System.out.println("month = " + month);
-// System.out.println("day = " + day);
-// System.out.println("hour = " + hour);
-// System.out.println("minute = " + minute);
-// System.out.println("doublesecond = " + doublesecond);
-
- Calendar c = Calendar.getInstance();
- c.setTime(new Date(0));
- c.set(Calendar.YEAR, year);
- c.set(Calendar.MONTH, month);
- c.set(Calendar.DAY_OF_MONTH, day);
- c.set(Calendar.HOUR, hour);
- c.set(Calendar.MINUTE, minute);
- c.set(Calendar.SECOND, doublesecond*2);
- return c.getTime();
- }
-
- public FileAttributes getFileAttributesStructured() {
- byte hostOS = getHostOS();
- if(hostOS == HOSTOS_WIN_32)
- return new Win32FileAttributes(getFileAttr());
- else if(hostOS == HOSTOS_UNIX)
- return new UNIXFileAttributes(getFileAttr());
- else if(hostOS == HOSTOS_MS_DOS || hostOS == HOSTOS_OS2)
- return new Win32FileAttributes(getFileAttr()); // Win, DOS and OS/2 seems to have a lot in common, but I don't really know what the file attributes will look like under DOS and OS/2. Hopefully something like the Win32-attributes (:
- else
- throw new RuntimeException("Unknown OS type!");
- }
-
-// public boolean isFile() {
-// return getFlag(getFileAttr(), 13);
-// }
-
- public String getHostOSAsString() {
- return hostOSToString(getHostOS());
- }
-
- public String getUnpackVersionAsString() {
- byte unpVer = getUnpVer();
- return (unpVer/10) + "." + (unpVer%10);
- }
-
- public String getFilenameAsString() {
- String result = getUnicodeFilenameAsString();
- if(result == null)
- result = getLegacyFilenameAsString();
- return result;
- }
- public String getLegacyFilenameAsString() {
- /* After testing, it seems that one of the old MS-DOS charsets
- are used to store the file name in this structure. If
- different charsets are supported, I don't know how to detect
- which charset will be used yet. Code Page 850 is used for now. */
- try {
- return new String(filename, /*"IBM437"*/"iso-8859-1").split("\0")[0];
- } catch(UnsupportedEncodingException uee) {
- throw new RuntimeException(uee);
- }
- }
-
- public String getUnicodeFilenameAsString() {
- /* To cope with characters outside the old IBM charset originally
- used for filenames, RAR embeds extra data after the area
- containing the IBM charset filename. The old style filename is
- terminated by null, and after that follows the characters that
- could not be encoded properly with the IBM charset. */
- boolean debug = false;
- if(debug) System.out.println("getExtendedCharsetFilenameAsString();");
- char[] legacyFilename = getLegacyFilenameAsString().toCharArray();
- char[] unicodeFilename = new char[legacyFilename.length];
- int unicodeFilenamePointer = 0;
- //LinkedList<Character> codeUnitList = new LinkedList<Character>();
-
- // Find the index at which the extended filename characters begin (first occurrence of 0x00).
- int zeroIndex = 0;
- for(; zeroIndex < filename.length; ++zeroIndex)
- if(filename[zeroIndex] == 0)
- break;
-
- int codeUnitsRead = 0;;
-
- int extendedDataPointer = zeroIndex+1;
- if(extendedDataPointer+2 >= filename.length) // Must have compressedLSB (1 bytes) and at least one byte
- return null;
- byte compressedLSB = Util.readByteLE(filename, extendedDataPointer++);
-
- mainLoop:
- while(extendedDataPointer < filename.length) {
- if(debug) System.out.println(" Reading 4 bytes... (found " + codeUnitsRead +
- " code points, extendedDataPointer=" + extendedDataPointer + ")");
- byte groupDescriptor = Util.readByteLE(filename, extendedDataPointer++);
- for(int i = 0; (i < 4) && (extendedDataPointer < filename.length); ++i) {
- byte current = (byte)((groupDescriptor >>> ((3-i)*2)) & 0x3); // 0b11
- if(current == 0x0) { // 0b00
- //if(extendedDataPointer >= filename.length) break;
- char codeUnit = (char)(Util.readByteLE(filename, extendedDataPointer++) & 0xFF);
- if(debug) System.out.println(" Encountered 8-bit character: 0x" + Util.toHexStringBE(codeUnit));
- //codeUnitList.add(codeUnit);
- unicodeFilename[unicodeFilenamePointer++] = codeUnit;
- ++codeUnitsRead;
- }
- else if(current == 0x1) {
- //if(extendedDataPointer >= filename.length) break;
- char codeUnit = (char)(((compressedLSB & 0xFF) << 8) |
- (Util.readByteLE(filename, extendedDataPointer++) & 0xFF));
- if(debug) System.out.println(" Encountered compressed 16-bit character: 0x" +
- Util.toHexStringBE(codeUnit));
- //codeUnitList.add(codeUnit);
- unicodeFilename[unicodeFilenamePointer++] = codeUnit;
- ++codeUnitsRead;
- }
- else if(current == 0x2) { // 0b10
- //if(extendedDataPointer+1 >= filename.length) break;
- char codeUnit = (char)Util.readShortLE(filename, extendedDataPointer);
- extendedDataPointer += 2;
- if(debug) System.out.println(" Encountered 16-bit character: 0x" + Util.toHexStringBE(codeUnit));
- //codeUnitList.add(codeUnit);
- unicodeFilename[unicodeFilenamePointer++] = codeUnit;
- ++codeUnitsRead;
- }
- else if(current == 0x3) {
- //if(extendedDataPointer >= filename.length) break;
- byte indicator = Util.readByteLE(filename, extendedDataPointer++);
-
- /* Detta �r bullshit. Det �r INTE en indikator utan ett "skip"-kommando.
- * Ex. skip(0x02) => Spola f�rbi 4 characters dvs. ".txt" (n�stan alla test*+.rar)
- * skip(0x05) => Spola f�rbi 7 characters ex. "bok.txt" (ctest6.rar)
- * skip(0x01) => Spola f�rbi 3 characters ex. "Hej" (ctest16.rar)
- * skip(0x03) => Spola f�rbi 5 characters ex. "laban" (ctest16.rar)
- * Specialfall:
- * - Man kan som minst spola f�rbi 2 characters (skip(0x00)). Om str�ngen inleds med
- * en ASCII-character med Unicode-char direkt f�ljande s� kodas ASCII-charactern ner
- * som Unicode.
- * - P� samma s�tt kan man inte spola f�rbi 131 characters, utan �r tvungen att koda
- * skip(0x7F)... eller n�t. iaf skitsamma. orka.
- */
-
- if((indicator & 0xFF) > 0x7F)
- System.out.println(" Encountered unexpected skip value! 0x" + Util.toHexStringBE(indicator));
- if(debug) System.out.println(" Skipping " + (indicator+2) + " bytes.");
-
- System.arraycopy(legacyFilename, unicodeFilenamePointer, unicodeFilename, unicodeFilenamePointer, (indicator+2));
- unicodeFilenamePointer += (indicator+2);
- }
- }
- }
- if(unicodeFilenamePointer != legacyFilename.length)
- if(debug) System.out.println(" ERROR! Did not read enough characters. Read " + unicodeFilenamePointer + " characters while legacyFilename.length==" + legacyFilename.length + ".");
- else
- if(debug) System.out.println(" Read " + unicodeFilenamePointer + " characters.");
- return new String(unicodeFilename);
- }
-
- public byte[] getTrailingFilenameData() {
- for(int i = 0; i < filename.length; ++i) {
- if(filename[i] == 0)
- return Util.createCopy(filename, i, filename.length-i);
- }
- return new byte[0];
- }
-
- public static String hostOSToString(byte hostOS) {
- if(hostOS >= 0 && hostOS <= hostOSStrings.length)
- return hostOSStrings[hostOS];
- else
- return null;
- }
-
- /* // An attempt at porting the CRC-function from unrarlib to Java. Seems to work poorly.
- private static class MyCRC32 {
- private final int[] CRCTab = new int[256];
- private int currentCRC = 0xFFFFFFFF;
- public MyCRC32() {
- short I, J;
- int C;
- for(I=0;(I&0xFFFF)<256;I++) {
- for(C=I,J=0;J<8;J++)
- C=((C & 1) != 0)? (C>>1)^0xEDB88320 : (C>>1);
- CRCTab[I&0xFFFF]=C;
- }
- }
-
- public void update(byte[] data) {
- currentCRC = CalcCRC32(currentCRC, data);
- }
-
- public int getValue() {
- return currentCRC;
- }
-
- private int CalcCRC32(int StartCRC, byte[] Addr) {
- short I;
- for(I=0; I<Addr.length; I++)
- StartCRC = CRCTab[((byte)StartCRC ^ Addr[I])&0xFF] ^ (StartCRC >> 8);
- return(StartCRC);
- }
- }
- */
-
-
- protected void printFields(PrintStream ps, String prefix) {
- super.printFields(ps, prefix);
- ps.println(prefix + " PackSize: " + getPackSize() + " bytes");
- ps.println(prefix + " UnpSize: " + getUnpSize() + " bytes");
- ps.println(prefix + " HostOS: \"" + getHostOSAsString() + "\"");
- ps.println(prefix + " FileCRC: 0x" + Util.toHexStringBE(getFileCRC()));
- ps.println(prefix + " FileTime: " + getFileTimeAsDate() + " (0x" + Util.toHexStringBE(getFileTime()) + ")");
- ps.println(prefix + " UnpVer: \"" + getUnpackVersionAsString() + "\"");
- ps.println(prefix + " Method: 0x" + Util.toHexStringBE(getMethod()));
- ps.println(prefix + " NameSize: " + getNameSize() + " bytes");
- ps.println(prefix + " FileAttr: 0x" + Util.toHexStringBE(getFileAttr()));
- ps.println(prefix + " Structured file attributes:");
- getFileAttributesStructured().print(ps, prefix + " ");
- ps.println(prefix + " Filename: \"" + getFilenameAsString() + "\"");
- byte[] trailingFilenameData = getTrailingFilenameData();
- if(trailingFilenameData.length > 0)
- ps.println(prefix + " (Trailing filename data: 0x" + Util.byteArrayToHexString(trailingFilenameData) + ")");
- ps.println(prefix + " Trailing data: 0x" + Util.byteArrayToHexString(getTrailingData()));
- }
-
- public void print(PrintStream ps, String prefix) {
- ps.println(prefix + "NewFileHeader: ");
- printFields(ps, prefix);
- }
-}
diff --git a/src/org/catacombae/rarx/NewMainArchiveHeader.java b/src/org/catacombae/rarx/NewMainArchiveHeader.java
deleted file mode 100644
index caf09db..0000000
--- a/src/org/catacombae/rarx/NewMainArchiveHeader.java
+++ /dev/null
@@ -1,94 +0,0 @@
-/*-
- * Copyright (C) 2006 Erik Larsson
- *
- * All rights reserved.
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software
- * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA
- */
-
-package org.catacombae.rarx;
-
-import java.io.PrintStream;
-
-public class NewMainArchiveHeader extends RARHeader {
- /*
- * struct NewMainArchiveHeader
- * size: 13 bytes
- *
- * BP Size Description
- * 0 2 HeadCRC
- * 2 1 HeadType
- * 3 2 Flags
- * 5 2 HeadSize
- * 7 2 Reserved
- * 9 4 Reserved1
- */
-
- private final byte[] reserved = new byte[2];
- private final byte[] reserved1 = new byte[4];
-
- public NewMainArchiveHeader(byte[] data, int offset) {
- super(data, offset);
- System.arraycopy(data, offset+7, reserved, 0, 2);
- System.arraycopy(data, offset+9, reserved1, 0, 4);
- validateData();
- }
-
- public int getSize() { return _getSize(); }
- private int _getSize() { return getHeadSize();/*13;*/ }
-
- protected void validateData() {
- super.validateData();
- if(getHeadType() != MAIN_HEAD)
- throw new InvalidDataException("Incorrect head type! (headType=" + getHeadType() + ")");
-// if(getHeadSize() != getSize())
-// throw new InvalidDataException("Wrong size! (size=" + getHeadSize() + ")");
- }
-
- public short getReserved() { return Util.readShortLE(reserved); }
- public int getReserved1() { return Util.readIntLE(reserved1); }
-
- public byte[] getHeaderData() {
- byte[] data = new byte[_getSize()];
- System.arraycopy(super.getHeaderData(), 0, data, 0, super.getSize());
- System.arraycopy(reserved, 0, data, 7, 2);
- System.arraycopy(reserved1, 0, data, 9, 4);
- return data;
- }
-// public short calculateHeadCRC() {
-// CRC32 crc = new CRC32();
-// //MyCRC32 crc = new MyCRC32();
-// // crc.update(headCRC);
-// crc.update(headType);
-// crc.update(flags);
-// crc.update(headSize);
-// crc.update(reserved);
-// crc.update(reserved1);
-// //crc.(trailingData);
-// return (short)(crc.getValue());
-// }
-
- protected void printFields(PrintStream ps, String prefix) {
- super.printFields(ps, prefix);
- ps.println(prefix + " Reserved: " + Util.toHexStringBE(getReserved()));
- ps.println(prefix + " Reserved1: " + Util.toHexStringBE(getReserved1()));
- }
-
-
- public void print(PrintStream ps, String prefix) {
- ps.println(prefix + "NewMainArchiveHeader: ");
- printFields(ps, prefix);
- }
-}
diff --git a/src/org/catacombae/rarx/ProtectedHeader.java b/src/org/catacombae/rarx/ProtectedHeader.java
deleted file mode 100644
index 0f7df6d..0000000
--- a/src/org/catacombae/rarx/ProtectedHeader.java
+++ /dev/null
@@ -1,67 +0,0 @@
-/*-
- * Copyright (C) 2006 Erik Larsson
- *
- * All rights reserved.
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software
- * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA
- */
-
-package org.catacombae.rarx;
-
-import java.io.PrintStream;
-
-public class ProtectedHeader extends RARHeader {
- private final byte[] dataSize = new byte[4];
- private final byte[] unknownData;
- public ProtectedHeader(byte[] data, int offset) {
- super(data, offset);
- System.arraycopy(data, super.getSize(), dataSize, 0, 4);
- unknownData = new byte[getHeadSize()-(super.getSize()+4)];
- System.arraycopy(data, super.getSize()+4, unknownData, 0, unknownData.length);
- validateData();
- }
-
- public int getSize() {
- return _getSize();
- }
-
- private int _getSize() {
- return super.getSize()+dataSize.length+unknownData.length;
- }
-
- public void validateData() {
- super.validateData();
- if(getHeadType() != PROTECT_HEAD)
- throw new InvalidDataException("Incorrect head type! (headType=" + getHeadType() + ")");
- }
-
- public byte[] getHeaderData() {
- byte[] outData = new byte[_getSize()];
- byte[] superData = super.getHeaderData();
- System.arraycopy(superData, 0, outData, 0, superData.length);
- System.arraycopy(dataSize, 0, outData, superData.length, dataSize.length);
- System.arraycopy(unknownData, 0, outData, superData.length+dataSize.length, unknownData.length);
- return outData;
- }
-
- public long getDataSize() {
- return Util.readIntLE(dataSize, 0) & 0xFFFFFFFFL;
- }
-
- public void print(PrintStream ps, String prefix) {
- System.out.println("Protected header:");
- printFields(ps, prefix);
- }
-}
diff --git a/src/org/catacombae/rarx/RARFile.java b/src/org/catacombae/rarx/RARFile.java
deleted file mode 100644
index 3c63a22..0000000
--- a/src/org/catacombae/rarx/RARFile.java
+++ /dev/null
@@ -1,248 +0,0 @@
-/*-
- * Copyright (C) 2006 Erik Larsson
- *
- * All rights reserved.
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software
- * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA
- */
-
-package org.catacombae.rarx;
-
-import java.util.Vector;
-import java.io.*;
-import java.util.zip.CRC32;
-
-public class RARFile {
- public static final int SIZEOF_MARKHEAD = 7;
- public static final int SIZEOF_OLDMHD = 7;
- public static final int SIZEOF_NEWMHD = 13;
- public static final int SIZEOF_OLDLHD = 21;
- public static final int SIZEOF_NEWLHD = 32;
- public static final int SIZEOF_SHORTBLOCKHEAD = 7;
- public static final int SIZEOF_LONGBLOCKHEAD = 11;
- public static final int SIZEOF_COMMHEAD = 13;
- public static final int SIZEOF_PROTECTHEAD = 26;
-
- private static BufferedReader stdin = new BufferedReader(new InputStreamReader(System.in));
-
- public static void main(String[] args) throws IOException {
- File fileListFile = new File(args[0]);
- BufferedReader fileListIn = new BufferedReader(new InputStreamReader(new FileInputStream(fileListFile), "UTF-8"));
- String currentRar = fileListIn.readLine();
- while(currentRar != null) {
- if(true) {
- System.out.println("Processing file " + currentRar + "...");
- try {
- RARFileEntry[] entries = ListFilesInArchive.listFiles(new File(currentRar));
- for(RARFileEntry entry : entries) {
- NewFileHeader nfh = entry.getHeader(0);
- if(nfh instanceof CommentHeader)
- continue;
- //if(nfh.hasOutgoingData())
- System.out.print((nfh.hasIncomingData()?"<--":" ") + nfh.getFilenameAsString() + (nfh.hasOutgoingData()?"-->":""));
- if(nfh.getFileAttributesStructured().isDirectory())
- System.out.print(" (Dir)");
- else
- System.out.print(" (File)");
- System.out.println();
- }
- } catch(InvalidDataException ide) {
- System.out.println("Invalid RAR-file. Message: " + ide.getMessage());
- System.out.println("File: \"" + currentRar + "\"");
- }
- }
- else {
- RandomAccessFile raf = new RandomAccessFile(currentRar, "r");
- try {
- readMarkHeader(raf);
- NewMainArchiveHeader nmah = readNewMainArchiveHeader(raf);
- NewFileHeader nfh = readNewFileHeader(raf);
- } catch(InvalidDataException e) {
- System.out.println("Invalid RAR-file. Message: " + e.getMessage());
- System.out.println("File: \"" + currentRar + "\"");
- //System.exit(1);
- }
- }
- System.out.print("Press enter to continue...");
- stdin.readLine();
- System.out.println();
- currentRar = fileListIn.readLine();
- }
- }
- public static void main2(String[] args) throws IOException {
- RandomAccessFile raf = new RandomAccessFile(args[0], "r");
- try {
- readMarkHeader(raf);
- } catch(InvalidDataException e) {
- System.out.println("Invalid RAR-file. Message: " + e.getMessage());
- System.exit(1);
- }
-
- NewMainArchiveHeader nmah = readNewMainArchiveHeader(raf);
- nmah.print(System.out, "");
- NewFileHeader nfh = readNewFileHeader(raf);
- nfh.print(System.out, "");
- }
-
- public static Vector list(String path, boolean fullPath) throws IOException {
- RandomAccessFile raf = new RandomAccessFile(path, "r");
- raf.seek(7);
- NewMainArchiveHeader nmah = readNewMainArchiveHeader(raf);
- return null;
- }
-
- public static boolean isRAR(RandomAccessFile raf) throws IOException {
- long oldFilePointer = raf.getFilePointer();
- raf.seek(0);
- byte[] rarHeader = new byte[7];
- raf.read(rarHeader);
- /* Old archive => error */
- if(rarHeader[0]==0x52 && rarHeader[1]==0x45 &&
- rarHeader[2]==0x7e && rarHeader[3]==0x5e) {
- //debug_log("Attention: format as OLD detected! Can't handle archive!");
- }
- else {
- /* original RAR v2.0 */
- if((rarHeader[0]==0x52 && rarHeader[1]==0x61 && /* original */
- rarHeader[2]==0x72 && rarHeader[3]==0x21 && /* RAR header*/
- rarHeader[4]==0x1a && rarHeader[5]==0x07 &&
- rarHeader[6]==0x00) ||
- /* "UniquE!" - header */
- (rarHeader[0]=='U' && rarHeader[1]=='n' && /* "UniquE!" */
- rarHeader[2]=='i' && rarHeader[3]=='q' && /* header */
- rarHeader[4]=='u' && rarHeader[5]=='E' &&
- rarHeader[6]=='!')) {
- if(readNewMainArchiveHeader(raf) != null)
- return true;
- } else {
- // Skriv ut n�t felmedd...
- }
- }
- return false;
- }
-
- public static MarkHeader readMarkHeader(RandomAccessFile raf) throws IOException {
- byte[] header = new byte[7];
- raf.read(header);
- MarkHeader nfh = new MarkHeader(header, 0);
- return nfh;
- }
- public static NewMainArchiveHeader readNewMainArchiveHeader(RandomAccessFile raf) throws IOException {
- byte[] mainHeader = new byte[13];
- raf.read(mainHeader);
- NewMainArchiveHeader nmah = new NewMainArchiveHeader(mainHeader, 0);
- return nmah;
- }
-
- public static NewFileHeader readNewFileHeader(RandomAccessFile raf) throws IOException {
- byte[] header = new byte[32];
- raf.read(header);
- int headerSize = Util.readShortLE(header, 5);
- byte[] fullHeader = new byte[headerSize];
- System.arraycopy(header, 0, fullHeader, 0, header.length);
- raf.read(fullHeader, header.length, fullHeader.length-header.length);
- NewFileHeader nfh = new NewFileHeader(fullHeader, 0);
- byte[] reconstruction = nfh.getHeaderData();
- if(!Util.arraysEqual(fullHeader, reconstruction))
- System.out.println("ERROR: Data after reconstruction has changed!");
- return nfh;
- }
-
- public static RARHeader readHeader(RandomAccessFile raf) throws IOException {
- byte[] header = new byte[7];
- if(raf.read(header) == -1)
- return null;
- int headerSize = Util.readShortLE(header, 5);
- byte headerType = Util.readByteLE(header, 2);
- try {
- byte[] fullHeader = new byte[headerSize];
- System.arraycopy(header, 0, fullHeader, 0, header.length);
- raf.read(fullHeader, header.length, fullHeader.length-header.length);
- //System.out.println("Reading... headerSize=" + headerSize + " headerType=" + headerType);
- if(headerType == RARHeader.FILE_HEAD) {
- NewFileHeader nfh = new NewFileHeader(fullHeader, 0);
- raf.seek(raf.getFilePointer()+nfh.getPackSize());
- return nfh;
- }
- else if(headerType == RARHeader.MAIN_HEAD)
- return new NewMainArchiveHeader(fullHeader, 0);
- else if(headerType == RARHeader.COMMENT_HEAD) {
- CommentHeader ch = new CommentHeader(fullHeader, 0);
- raf.seek(raf.getFilePointer()+ch.getPackSize());
- return ch;
- }
- else if(headerType == RARHeader.PROTECT_HEAD) {
- ProtectedHeader ph = new ProtectedHeader(fullHeader, 0);
- raf.seek(raf.getFilePointer()+ph.getDataSize());
- return ph;
- }
- else if(headerType == RARHeader.EOF_HEAD)
- return null;
- else {
- System.out.println("UNRECOGNIZED HEADER TYPE: 0x" + Util.toHexStringBE(headerType) + " for header at 0x" + Util.toHexStringBE(raf.getFilePointer()-headerSize));
- UnknownHeader uh = new UnknownHeader(fullHeader, 0);
- uh.print(System.out, "");
- return uh;
- }
- } catch(ArrayIndexOutOfBoundsException aioobe) {
- aioobe.printStackTrace();
- System.err.println("headerSize=" + headerSize);
- System.err.println("headerType=" + headerType);
- System.err.println("filePointer: " + raf.getFilePointer());
- return null;
- }
- }
-
- public static long findEntry(String entryName, RandomAccessFile rarFile) throws IOException {
- readMarkHeader(rarFile);
- RARHeader currentHeader = readHeader(rarFile);
- while(currentHeader != null) {
- if(currentHeader instanceof NewFileHeader &&
- !(currentHeader instanceof CommentHeader)) {
- NewFileHeader nfh = (NewFileHeader)currentHeader;
- if(nfh.getFilenameAsString().equals(entryName)) {
- return rarFile.getFilePointer() - (nfh.getHeadSize()+nfh.getPackSize());
- }
- }
- currentHeader = readHeader(rarFile);
- }
- return -1;
- }
-
- // Utility methods
-
-// public static int readIntLE(byte[] data) {
-// return readIntLE(data, 0);
-// }
-// public static int readIntLE(byte[] data, int offset) {
-// return ((data[offset+3] & 0xFF) << 24 |
-// (data[offset+2] & 0xFF) << 16 |
-// (data[offset+1] & 0xFF) << 8 |
-// (data[offset+0] & 0xFF) << 0);
-// }
-// public static short readShortLE(byte[] data) {
-// return readShortLE(data, 0);
-// }
-// public static short readShortLE(byte[] data, int offset) {
-// return (short) ((data[offset+1] & 0xFF) << 8 |
-// (data[offset+0] & 0xFF) << 0);
-// }
-// public static byte readByteLE(byte[] data) {
-// return readByteLE(data, 0);
-// }
-// public static byte readByteLE(byte[] data, int offset) {
-// return data[offset];
-// }
-}
diff --git a/src/org/catacombae/rarx/RARFile2.java b/src/org/catacombae/rarx/RARFile2.java
deleted file mode 100644
index df7f706..0000000
--- a/src/org/catacombae/rarx/RARFile2.java
+++ /dev/null
@@ -1,29 +0,0 @@
-/*-
- * Copyright (C) 2006 Erik Larsson
- *
- * All rights reserved.
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software
- * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA
- */
-
-package org.catacombae.rarx;
-
-import java.io.IOException;
-
-public class RARFile2 {
- public static void main(String[] args) throws IOException {
- RARFile.main2(args);
- }
-}
diff --git a/src/org/catacombae/rarx/RARFileEntry.java b/src/org/catacombae/rarx/RARFileEntry.java
deleted file mode 100644
index ff8410d..0000000
--- a/src/org/catacombae/rarx/RARFileEntry.java
+++ /dev/null
@@ -1,76 +0,0 @@
-/*-
- * Copyright (C) 2006 Erik Larsson
- *
- * All rights reserved.
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software
- * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA
- */
-
-package org.catacombae.rarx;
-
-import java.util.ArrayList;
-import java.io.File;
-
-public class RARFileEntry {
- public static class RARFileEntryPart {
- public File f;
- public long offset;
- public NewFileHeader header;
-
- public RARFileEntryPart(File f, long offset, NewFileHeader header) {
- this.f = f;
- this.offset = offset;
- this.header = header;
- }
- }
-
- private ArrayList<RARFileEntryPart> parts = new ArrayList<RARFileEntryPart>();
-
- public RARFileEntry(File f, long offset, NewFileHeader header) {
- RARFileEntryPart firstPart = new RARFileEntryPart(f, offset, header);
- parts.add(firstPart);
- }
-
- public void addPart(File f, long offset, NewFileHeader header) {
- parts.add(new RARFileEntryPart(f, offset, header));
- }
-
- public int getPartCount() { return parts.size(); }
- public long getPackedSize() {
- long size = 0;
- for(RARFileEntryPart current : parts)
- size += current.header.getPackSize();
- return size;
- }
-
- public boolean hasIncomingData() {
- return parts.get(0).header.hasIncomingData();
- }
- public boolean hasOutgoingData() {
- return parts.get(parts.size()-1).header.hasOutgoingData();
- }
-
- public boolean isComplete() {
- return (!parts.get(0).header.hasIncomingData() && !parts.get(parts.size()-1).header.hasOutgoingData());
- }
-
- public int getFinalFileCRC() {
- return parts.get(parts.size()-1).header.getFileCRC();
- }
-
- public File getFile(int partNumber) { return parts.get(partNumber).f; }
- public long getOffset(int partNumber) { return parts.get(partNumber).offset; }
- public NewFileHeader getHeader(int partNumber) { return parts.get(partNumber).header; }
-}
diff --git a/src/org/catacombae/rarx/RARFileEntryStream.java b/src/org/catacombae/rarx/RARFileEntryStream.java
deleted file mode 100644
index c632900..0000000
--- a/src/org/catacombae/rarx/RARFileEntryStream.java
+++ /dev/null
@@ -1,550 +0,0 @@
-/*-
- * Copyright (C) 2006 Erik Larsson
- *
- * All rights reserved.
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software
- * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA
- */
-
-package org.catacombae.rarx;
-
-import org.catacombae.io.*;
-import java.io.*;
-import java.util.LinkedList;
-import java.util.regex.Pattern;
-
-public class RARFileEntryStream implements RandomAccessStream {
- public static class InvalidRARFilenameException extends RuntimeException {
- private static final long serialVersionUID = 0x2F49329E49173487L;
-
- public InvalidRARFilenameException(String message) {
- super(message);
- }
- }
-
- public static class RAREntrySegment {
- public File file;
- public RandomAccessFile raf;
- public long headerPos;
- public long headerLength;
- public long dataPos;
- public long dataLength;
- public RAREntrySegment nextSegment = null;
-
- public RAREntrySegment(File file, RandomAccessFile raf, long headerPos, long headerLength, long dataPos, long dataLength/*, RAREntrySegment nextSegment*/) {
- this.file = file;
- this.raf = raf;
- this.headerPos = headerPos;
- this.headerLength = headerLength;
- this.dataPos = dataPos;
- this.dataLength = dataLength;
- //this.nextSegment = nextSegment;
- }
- }
-
- public class Interval {
- public RAREntrySegment segment;
- public long startOffset;
- public long endOffset;
-
- public Interval(RAREntrySegment segment, long startOffset, long endOffset) {
- this.segment = segment;
- this.startOffset = startOffset;
- this.endOffset = endOffset;
- }
- }
-
- public class IntervalStructure {
- private LinkedList<Interval> intervals = new LinkedList<Interval>();
-
- public void addSegment(RAREntrySegment res, long startOffset, long endOffset) {
- Interval newInterval = new Interval(res, startOffset, endOffset);
- if(intervals.size() > 0) {
- Interval previous = intervals.getLast();
- previous.segment.nextSegment = newInterval.segment;
- }
- intervals.addLast(newInterval);
- }
-
- public RAREntrySegment getSegment(long offset) {
- for(Interval i : intervals)
- if(offset >= i.startOffset && offset < i.endOffset)
- return i.segment;
- return null;
- }
-
- public Interval getInterval(long offset) {
- for(Interval i : intervals)
- if(offset >= i.startOffset && offset < i.endOffset)
- return i;
- return null;
- }
-
- public RAREntrySegment[] getAllSegmentsUnordered() {
- RAREntrySegment[] result = new RAREntrySegment[intervals.size()];
- int j = 0;
- for(Interval i : intervals)
- result[j++] = i.segment;
- return result;
- }
- }
-
- public static boolean debug = false;
- private IntervalStructure intervalStructure;
- private RAREntrySegment currentSegment;
- private boolean closed = false;
- private long seekPointer;
- private long globalPointer = 0;
- private long segmentPointer = 0;
- private final long length;
-
- public RARFileEntryStream(RARFileEntry entry) throws FileNotFoundException, IOException {
- this(entry.getFile(0), entry.getOffset(0));
- }
-
- public RARFileEntryStream(File startFile, long pos) throws FileNotFoundException, IOException {
- //this.startFile = startFile;
- //this.pos = pos;
-
- LinkedList<RAREntrySegment> entrySegments = getSegments(startFile, pos, new LinkedList<RAREntrySegment>(), false);
-// for(RAREntrySegment res : entrySegments)
-// res.raf.seek(0);
- if(entrySegments == null || entrySegments.size() < 1)
- throw new FileNotFoundException();
- this.currentSegment = entrySegments.getFirst();
-
- long currentPos = 0;
- this.intervalStructure = new IntervalStructure();
- for(RAREntrySegment res : entrySegments) {
- if(debug) System.out.println("Adding \"" + res.file + "\" at " + currentPos);
- intervalStructure.addSegment(res, currentPos, currentPos+res.dataLength);
- currentPos += res.dataLength;
- }
- length = currentPos;
- if(debug) System.out.println("Length of entry: " + length + " bytes");
-
- seekPointer = -2;
- updateSeekPosition();
- }
-
- /** @see java.io.RandomAccessFile */
- public synchronized void close() throws IOException {
- if(debug) System.out.println("RARFileEntryStream.close()");
- if(closed) throw new IOException("Stream closed.");
-
- closed = true;
- for(RAREntrySegment res : intervalStructure.getAllSegmentsUnordered())
- res.raf.close();
- }
-
- /** @see java.io.RandomAccessFile */
- public synchronized long getFilePointer() throws IOException {
- return ((seekPointer == -1)?globalPointer:seekPointer);
- }
-
- /** @see java.io.RandomAccessFile */
- public synchronized long length() throws IOException {
- return length;
- }
-
- /** @see java.io.RandomAccessFile */
- public synchronized int read() throws IOException {
- if(closed) throw new IOException("Stream closed.");
- byte[] b = new byte[1];
- read(b, 0, 1);
- return b[0] & 0xFF;
- }
-
- /** @see java.io.RandomAccessFile */
- public synchronized int read(byte[] b) throws IOException {
- if(closed) throw new IOException("Stream closed.");
- return read(b, 0, b.length);
- }
-
- /** @see java.io.RandomAccessFile */
- public synchronized int read(byte[] b, int off, int len) throws IOException {
-// boolean debug = true;
- if(debug) System.out.print("RARFileEntryStream.read(b, " + off + ", " + len + ") = ");
-// System.out.println();
-// System.out.println("(1)currentSegment.raf.getFilePointer()=" + currentSegment.raf.getFilePointer());
-// System.out.println("(1)=seekPointer=" + seekPointer);
- if(closed) throw new IOException("Stream closed.");
- try {
- updateSeekPosition();
- } catch(IOException ioe) {
- if(debug) System.out.println("-1 (Couldn't update seek position)");
- return -1;
- }
-
- long bytesRemainingInSegment = currentSegment.dataLength - segmentPointer;
- while(bytesRemainingInSegment == 0) {
- if(nextSegment())
- bytesRemainingInSegment = currentSegment.dataLength - segmentPointer;
- else {
- if(debug) System.out.println("-1 (Nothing to read)");
- return -1; // Nothing to read!
- }
- }
- int bytesRead = 0;
- mainLoop:
- while(bytesRead < len) {
- int remainingBytes = len-bytesRead;
- int bytesToRead = (remainingBytes < bytesRemainingInSegment)?remainingBytes:(int)bytesRemainingInSegment;
-
-// System.out.println("(2)currentSegment.raf.getFilePointer()=" + currentSegment.raf.getFilePointer());
- int currentBytesRead = currentSegment.raf.read(b, off+bytesRead, bytesToRead);
- if(currentBytesRead == -1)
- throw new IOException("Reached end of file unexpectedly for file \"" + currentSegment.file + "\"! (segmentPointer=" + segmentPointer + " globalPointer=" + globalPointer + " bytesRemainingInSegment=" + bytesRemainingInSegment + " bytesRead=" + bytesRead + " bytesToRead=" + bytesToRead + " currentSegment.raf.getFilePointer()=" + currentSegment.raf.getFilePointer() + " currentSegment.dataLength=" + currentSegment.dataLength + ")");
-
- bytesRead += currentBytesRead;
- segmentPointer += currentBytesRead;
- globalPointer += currentBytesRead;
- //seekPointer += currentBytesRead;
-
- bytesRemainingInSegment = currentSegment.dataLength - segmentPointer;
- while(bytesRemainingInSegment == 0) {
- if(nextSegment())
- bytesRemainingInSegment = currentSegment.dataLength - segmentPointer;
- else
- break mainLoop; // No more bytes to read;
- }
- }
- if(debug) System.out.println(bytesRead);
- return bytesRead;
- }
-
- /** @see java.io.RandomAccessFile */
- public synchronized void seek(long pos) throws IOException {
- if(debug) System.out.println("RARFileEntryStream.seek(" + pos + ")");
- if(closed) throw new IOException("Stream closed.");
- if(pos < 0) throw new IOException("Invalid position.");
- seekPointer = pos;
- }
-
- private synchronized void updateSeekPosition() throws IOException {
- if(debug) System.out.println("updateSeekPosition()");
-// System.out.println("seekPointer=" + seekPointer);
-// System.out.println("globalPointer=" + globalPointer);
-// System.out.println("segmentPointer=" + segmentPointer);
- if(seekPointer == globalPointer)
- seekPointer = -1;
- else if(seekPointer != -1) {
- //if(seekPointer > length) seek(length-1);
- if(seekPointer == -2)
- seekPointer = 0;
-
- long posDiff = seekPointer-globalPointer;
- long newSegmentPointer = segmentPointer + posDiff;
- if(newSegmentPointer >= 0 &&
- newSegmentPointer < currentSegment.dataLength) {
- if(debug) System.out.println(" Pointer is within segment.");
- globalPointer += posDiff;
- segmentPointer += posDiff;
- if(debug) System.out.println(" Seeking to " + (currentSegment.dataPos + segmentPointer) +".");
- currentSegment.raf.seek(currentSegment.dataPos + segmentPointer);
- if(debug) System.out.println(" Done.");
- }
- else {
- if(debug) System.out.println(" Pointer is OUTSIDE segment. We need to get a new one.");
- Interval newInterval = intervalStructure.getInterval(seekPointer);
- if(newInterval == null)
- throw new IOException("No more data to read.");
- RAREntrySegment newSegment = newInterval.segment;
- newSegmentPointer = (seekPointer-newInterval.startOffset);
- if(debug) System.out.println(" Seeking to " + (currentSegment.dataPos + segmentPointer) +".");
- newSegment.raf.seek(newSegment.dataPos + newSegmentPointer);
- if(debug) System.out.println(" Done.");
-
- // If we got here, all is well.
- globalPointer = seekPointer;
- segmentPointer = newSegmentPointer;
- currentSegment = newSegment;
- }
- seekPointer = -1;
- }
- }
-
- public synchronized boolean isClosed() {
- return closed;
- }
-
- public synchronized boolean reopen() {
- if(debug) System.out.println("RARFileEntryStream.reopen()");
- if(closed) {
- try {
- for(RAREntrySegment res : intervalStructure.getAllSegmentsUnordered())
- res.raf = new RandomAccessFile(res.file, "r");
- closed = false;
- seekPointer = -2;
- updateSeekPosition();
- //seek(0);
- return true;
- } catch(Exception e) {}
- }
- return false;
- }
-
- /**
- * Changes forward to the next segment and sets the pointers.
- */
- private boolean nextSegment() throws IOException {
- if(debug) System.out.println("RARFileEntryStream.nextSegment()");
- RAREntrySegment nextSegment = currentSegment.nextSegment;
- if(nextSegment != null) {
- if(debug) System.out.println(" nextSegment != null");
- if(debug) System.out.println(" currentSegment: " + currentSegment);
- if(debug) System.out.println(" file: " + currentSegment.file);
- if(debug) System.out.println(" headerPos: " + currentSegment.headerPos);
- if(debug) System.out.println(" headerLength: " + currentSegment.headerLength);
- if(debug) System.out.println(" dataPos: " + currentSegment.dataPos);
- if(debug) System.out.println(" dataLength: " + currentSegment.dataLength);
- if(debug) System.out.println(" nextSegment: " + nextSegment);
- if(debug) System.out.println(" file: " + nextSegment.file);
- if(debug) System.out.println(" headerPos: " + nextSegment.headerPos);
- if(debug) System.out.println(" headerLength: " + nextSegment.headerLength);
- if(debug) System.out.println(" dataPos: " + nextSegment.dataPos);
- if(debug) System.out.println(" dataLength: " + nextSegment.dataLength);
- globalPointer += currentSegment.dataLength - segmentPointer;
- segmentPointer = 0;
- nextSegment.raf.seek(nextSegment.dataPos);
- currentSegment = nextSegment;
- return true;
- }
- else {
- if(debug) System.out.println(" nextSegment == null");
- return false;
- }
- }
-
- private static LinkedList<RAREntrySegment> getSegments(File file, long position, LinkedList<RAREntrySegment> list, boolean needsIncoming) throws IOException, FileNotFoundException {
- if(debug) System.out.println("Getting new entry segment: " + file);
- RandomAccessFile raf = new RandomAccessFile(file, "r");
- raf.seek(position);
- RARHeader rh = RARFile.readHeader(raf);
- if(rh instanceof NewFileHeader) {
- NewFileHeader nfh = (NewFileHeader)rh;
- if(//nfh.getMethod() == RARHeader.METHOD_UNCOMPRESSED &&
- (needsIncoming?nfh.hasIncomingData():!nfh.hasIncomingData()) &&
- !(nfh instanceof CommentHeader)) {
- RAREntrySegment res = new RAREntrySegment(file, raf, position, nfh.getSize(), position+nfh.getSize(), nfh.getPackSize());
- list.addLast(res);
- if(nfh.hasOutgoingData()) {
- File nextFile = getNextFile(file);
- if(nextFile == null)
- throw new FileNotFoundException();
- long posInNextFile = getMatchingPosInFile(nextFile, nfh);
- if(posInNextFile == -1)
- throw new FileNotFoundException();
- getSegments(nextFile, posInNextFile, list, true);
- }
- }
- }
- return list;
- }
-
- protected static File getNextFile(File rarFile) {
- String filename = rarFile.getName();
- String newFilename;
- if(Pattern.matches(".+\\.[P|p]art\\d+\\.rar", filename)) {
- String numberString = "";
- long partNumber = 0; // I'm not serious... (:
- int charstep = 0;
- while(true) {
- String currentNumber = filename.substring(filename.length()-5-charstep, filename.length()-4-charstep);
- try {
- partNumber += Integer.parseInt(currentNumber)*Util.pow(10, charstep);
- } catch(NumberFormatException nfe) {
- break;
- }
- ++charstep;
- }
- int numberLength = charstep;
- String newPartNumberString = "" + (partNumber + 1);
-
- // Add leading zeroes
- while(newPartNumberString.length() < numberLength)
- newPartNumberString = "0" + newPartNumberString;
-
- newFilename = filename.substring(0, filename.length()-4-numberLength) + newPartNumberString + ".rar";
- }
- else if(Pattern.matches(".+\\.r((ar)|(\\d\\d)){1}", filename)) {
- String lastTwo = filename.substring(filename.length()-2, filename.length());
- String newLastTwo = "";
- if(lastTwo.equals("ar"))
- newLastTwo = "00";
- else {
- try {
- int archiveNumber = Integer.parseInt(lastTwo);
- newLastTwo = "" + (archiveNumber+1);
- if(newLastTwo.length() < 2)
- newLastTwo = "0" + newLastTwo;
- } catch(NumberFormatException nfe) {
- throw new RuntimeException(nfe);
- }
- }
- if(newLastTwo.length() != 2)
- throw new InvalidRARFilenameException("Incremented filename invalid.");
-
- newFilename = filename.substring(0, filename.length()-2) + newLastTwo;
- }
- else if(Pattern.matches(".+\\.\\d\\d\\d", filename)) {
- String lastThree = filename.substring(filename.length()-3, filename.length());
- String newLastThree = "";
- try {
- int archiveNumber = Integer.parseInt(lastThree);
- newLastThree = "" + (archiveNumber+1);
- while(newLastThree.length() < 3)
- newLastThree = "0" + newLastThree;
- } catch(NumberFormatException nfe) {
- throw new RuntimeException(nfe);
- }
- if(newLastThree.length() != 3)
- throw new InvalidRARFilenameException("Incremented filename invalid.");
-
- newFilename = filename.substring(0, filename.length()-3) + newLastThree;
- }
- else
- throw new InvalidRARFilenameException("Filename in argument invalid for a RAR-file.");
-
- File newFile = new File(rarFile.getParent(), newFilename);
- if(newFile.exists())
- return newFile;
- else {
- if(debug) System.out.println("Couldn't find \"" + newFile + "\"");
- return null;
- }
- }
-
- private static long getMatchingPosInFile(File f, NewFileHeader currentHeader) {
- try {
- RandomAccessFile raf = new RandomAccessFile(f, "r");
- RARFile.readMarkHeader(raf);
- RARHeader rh = RARFile.readHeader(raf);
- while(rh != null) {
- if(rh instanceof NewFileHeader) {
- NewFileHeader nextHeader = (NewFileHeader)rh;
- if(nextHeader.getFilenameAsString().equals(currentHeader.getFilenameAsString()) &&
- nextHeader.getUnpSize() == currentHeader.getUnpSize()) {
- long pos = raf.getFilePointer()-nextHeader.getPackSize()-nextHeader.getHeadSize();
- raf.close();
- return pos;
- }
- }
- rh = RARFile.readHeader(raf);
- }
- raf.close();
- } catch(IOException ioe) {
- ioe.printStackTrace();
- }
- return -1;
- }
-
- /** Testcode */
- public static void main(String[] args) throws IOException {
- if(args.length != 3)
- System.out.println("RARFileEntryStream self test needs exactly 3 arguments...");
- String rarFilename = args[0];
- String entryName = args[1];
- String referenceFilename = args[2];
-
- System.out.println("Initiating self test of RARFileEntryStream...");
- System.out.println(" RAR file: " + rarFilename);
- System.out.println(" Entry name: " + entryName);
- System.out.println(" Reference file: " + referenceFilename);
-
- File rarFile = new File(rarFilename);
- File referenceFile = new File(referenceFilename);
-
- long position = RARFile.findEntry(entryName, new RandomAccessFile(rarFile, "r"));
- RARFileEntryStream stream = new RARFileEntryStream(rarFile, position);
- RandomAccessFile ref = new RandomAccessFile(referenceFile, "r");
- byte[] buffer1 = new byte[4096];
- byte[] buffer2 = new byte[4096];
- int bytesRead1;
- int bytesRead2;
- long totalBytesRead1;
- long totalBytesRead2;
-
- System.out.println("1. Deterministic tests...");
- if(stream.length() != ref.length())
- System.out.println("Lengths not equal! stream: " + stream.length() + " reference file: " + ref.length());
-
- // Testing reading from the beginning
- ref.seek(0);
- stream.seek(0);
- if(ref.getFilePointer() != stream.getFilePointer()) throw new RuntimeException("File pointers not equal! ref: " + ref.getFilePointer() + " stream: " + stream.getFilePointer());
- bytesRead1 = ref.read(buffer1);
- bytesRead2 = stream.read(buffer2);
- if(ref.getFilePointer() != stream.getFilePointer()) throw new RuntimeException("File pointers not equal! ref: " + ref.getFilePointer() + " stream: " + stream.getFilePointer());
- if(bytesRead1 != bytesRead2) throw new RuntimeException("Did not read equal amount of bytes. (bytesRead1="+bytesRead1+" bytesRead2="+bytesRead2+")");
- if(!Util.arraysEqual(buffer1, buffer2)) throw new RuntimeException("Arrays not equal!");
-
- // Going to the middle of the file
- ref.seek(ref.length()/2);
- stream.seek(stream.length()/2);
- if(ref.getFilePointer() != stream.getFilePointer()) throw new RuntimeException("File pointers not equal! ref: " + ref.getFilePointer() + " stream: " + stream.getFilePointer());
- bytesRead1 = ref.read(buffer1);
- bytesRead2 = stream.read(buffer2);
- if(ref.getFilePointer() != stream.getFilePointer()) throw new RuntimeException("File pointers not equal! ref: " + ref.getFilePointer() + " stream: " + stream.getFilePointer());
- if(bytesRead1 != bytesRead2) throw new RuntimeException("Did not read equal amount of bytes. (bytesRead1="+bytesRead1+" bytesRead2="+bytesRead2+")");
- if(!Util.arraysEqual(buffer1, buffer2)) throw new RuntimeException("Arrays not equal!");
-
- // Going to the end of the file
- ref.seek(ref.length());
- stream.seek(stream.length());
- if(ref.getFilePointer() != stream.getFilePointer()) throw new RuntimeException("File pointers not equal! ref: " + ref.getFilePointer() + " stream: " + stream.getFilePointer());
- bytesRead1 = ref.read(buffer1);
- bytesRead2 = stream.read(buffer2);
- if(ref.getFilePointer() != stream.getFilePointer()) throw new RuntimeException("File pointers not equal! ref: " + ref.getFilePointer() + " stream: " + stream.getFilePointer());
- if(bytesRead1 != bytesRead2) throw new RuntimeException("Did not read equal amount of bytes. (bytesRead1="+bytesRead1+" bytesRead2="+bytesRead2+")");
- if(!Util.arraysEqual(buffer1, buffer2)) throw new RuntimeException("Arrays not equal!");
-
- // Going beyond the end of the file
- ref.seek(ref.length()*2);
- stream.seek(stream.length()*2);
- if(ref.getFilePointer() != stream.getFilePointer()) throw new RuntimeException("File pointers not equal! ref: " + ref.getFilePointer() + " stream: " + stream.getFilePointer());
- bytesRead1 = ref.read(buffer1);
- bytesRead2 = stream.read(buffer2);
- if(ref.getFilePointer() != stream.getFilePointer()) throw new RuntimeException("File pointers not equal! ref: " + ref.getFilePointer() + " stream: " + stream.getFilePointer());
- if(bytesRead1 != bytesRead2) throw new RuntimeException("Did not read equal amount of bytes. (bytesRead1="+bytesRead1+" bytesRead2="+bytesRead2+")");
- if(!Util.arraysEqual(buffer1, buffer2)) throw new RuntimeException("Arrays not equal!");
-
- // Comparing files byte for byte
- System.out.println("Comparing file data...");
- ref.seek(0);
- stream.seek(0);
- if(ref.getFilePointer() != stream.getFilePointer()) throw new RuntimeException("File pointers not equal! ref: " + ref.getFilePointer() + " stream: " + stream.getFilePointer());
- totalBytesRead1 = 0;
- totalBytesRead2 = 0;
- while(totalBytesRead1 < ref.length() && totalBytesRead2 < stream.length()) {
- System.out.print("\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b");
- System.out.print(" " + totalBytesRead1 + " bytes processed");
- long bytesRemaining1 = ref.length()-totalBytesRead1;
- long bytesRemaining2 = ref.length()-totalBytesRead2;
- bytesRead1 = ref.read(buffer1, 0, (bytesRemaining1 < buffer1.length?(int)bytesRemaining1:buffer1.length));
- bytesRead2 = stream.read(buffer2, 0, (bytesRemaining2 < buffer2.length?(int)bytesRemaining2:buffer2.length));
- if(bytesRead1 != bytesRead2) throw new RuntimeException("Have not read equal amount of bytes. (bytesRead1="+bytesRead1+" bytesRead2="+bytesRead2+")");
- if(bytesRead1 == -1)
- break;
- totalBytesRead1 += bytesRead1;
- totalBytesRead2 += bytesRead2;
- if(ref.getFilePointer() != stream.getFilePointer()) throw new RuntimeException("File pointers not equal! ref: " + ref.getFilePointer() + " stream: " + stream.getFilePointer());
- if(totalBytesRead1 != totalBytesRead2) throw new RuntimeException("Have not read equal amount of bytes. (totalBytesRead1="+totalBytesRead1+" totalBytesRead2="+totalBytesRead2+")");
- if(!Util.arraysEqual(buffer1, buffer2)) throw new RuntimeException("Arrays not equal!");
- }
- System.out.print("\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b");
- System.out.print(" " + totalBytesRead1 + " bytes processed");
- }
-}
diff --git a/src/org/catacombae/rarx/RARHeader.java b/src/org/catacombae/rarx/RARHeader.java
deleted file mode 100644
index c631f5f..0000000
--- a/src/org/catacombae/rarx/RARHeader.java
+++ /dev/null
@@ -1,121 +0,0 @@
-/*-
- * Copyright (C) 2006 Erik Larsson
- *
- * All rights reserved.
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software
- * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA
- */
-
-package org.catacombae.rarx;
-
-import java.io.PrintStream;
-import java.util.zip.CRC32;
-
-public abstract class RARHeader {
- /*
- * Common fields for all RAR headers
- * size: 7 bytes
- *
- * BP Size Description
- * 0 2 HeadCRC
- * 2 1 HeadType
- * 3 2 Flags
- * 5 2 HeadSize
- */
- // Possible values for the fields headType in various classes
- //public static final int ALL_HEAD = 0;
- public static final int MARK_HEAD = 0x72; // 0x69 for UniquE! ones..? However, this field isn't really needed.
- public static final int MAIN_HEAD = 0x73;
- public static final int FILE_HEAD = 0x74;
- public static final int COMM_HEAD = 0x75;
- public static final int AV_HEAD = 0x76;
- public static final int SUB_HEAD = 0x77;
- public static final int PROTECT_HEAD = 0x78;
- public static final int COMMENT_HEAD = 0x7a;
- public static final int EOF_HEAD = 0x7b;
-
- /* The versioning seems very simple. version 2.0 is represented
- by the value 20 (0x14), 2.6 by the value 26 (0x1a) etc. */
- public static final int UNPACK_VERSION_2_0 = 0x14;
- public static final int UNPACK_VERSION_2_6 = 0x1a; // efterlyst-bfc.rar
- public static final int UNPACK_VERSION_2_9 = 0x1d;
-
- public static final int METHOD_UNCOMPRESSED = 0x30; // Observerad i 2.0, 2.9
- public static final int METHOD_COMPRESSION_1 = 0x35; // Observerad i 2.0, 2.9
- public static final int METHOD_COMPRESSION_2 = 0x33; // Observerad i 2.0 (flera g�nger, men ovanligt), 2.9
-
- /* Hypotes: de tv� minst signifikanta bitarna i Flags indikerar om en fil
- forts�tter p� nytt medium. Om bit 0 �r satt �r den aktuella filen en
- forts�ttning p� en tidigare fil. Om bit 1 �r satt forts�tter den
- aktuella filen p� ytterligare nya media.
- Hypotes bekr�ftad. */
-
-
- private final byte[] headCRC = new byte[2];
- private final byte[] headType = new byte[1];
- private final byte[] flags = new byte[2];
- private final byte[] headSize = new byte[2];
- private final CRC32 crc = new CRC32();
-
- public RARHeader(byte[] data, int offset) {
- System.arraycopy(data, offset+0, headCRC, 0, 2);
- System.arraycopy(data, offset+2, headType, 0, 1);
- System.arraycopy(data, offset+3, flags, 0, 2);
- System.arraycopy(data, offset+5, headSize, 0, 2);
- }
-
- public int getSize() { return _getSize(); }
- private int _getSize() { return 7; }
-
- protected void validateData() {
- if(calculateHeadCRC() != getHeadCRC())
- throw new InvalidDataException("Incorrect header CRC!");
- }
-
- public short getHeadCRC() { return Util.readShortLE(headCRC); }
- public byte getHeadType() { return Util.readByteLE(headType); }
- public short getFlags() { return Util.readShortLE(flags); }
- public short getHeadSize() { return Util.readShortLE(headSize); }
-
- public boolean getFlag(int bitNumber) {
- return Util.getBit(getFlags(), bitNumber);//((getFlags() >> byteNumber) & 0x1) == 0x1;
- }
-
-
- public byte[] getHeaderData() {
- byte[] data = new byte[_getSize()];
- System.arraycopy(headCRC, 0, data, 0, headCRC.length);
- System.arraycopy(headType, 0, data, 2, headType.length);
- System.arraycopy(flags, 0, data, 3, flags.length);
- System.arraycopy(headSize, 0, data, 5, headSize.length);
- return data;
- }
-
- public short calculateHeadCRC() {
- crc.reset();
- crc.update(getHeaderData(), 2, getSize()-2);
- return (short)(crc.getValue());
- }
- protected void printFields(PrintStream ps, String prefix) {
- ps.println(prefix + " HeadCRC: " + Util.toHexStringBE(getHeadCRC()));
- if(calculateHeadCRC() != getHeadCRC())
- ps.println(prefix + " CHECKSUMS NOT MATCHING! (0x" +
- Util.toHexStringBE(getHeadCRC()) + " != 0x" +
- Util.toHexStringBE(calculateHeadCRC()) + "))");
- ps.println(prefix + " HeadType: " + Util.toHexStringBE(getHeadType()));
- ps.println(prefix + " Flags: " + Util.toHexStringBE(getFlags()));
- ps.println(prefix + " HeadSize: " + getHeadSize() + " bytes");
- }
-}
diff --git a/src/org/catacombae/rarx/README.txt b/src/org/catacombae/rarx/README.txt
deleted file mode 100644
index 5e70dfd..0000000
--- a/src/org/catacombae/rarx/README.txt
+++ /dev/null
@@ -1,10 +0,0 @@
-Acknowledgements
-----------------
-
-This code has been written with the UniquE RAR File Library v0.4.0 as a reference.
-Thus the author of this library should have a lot of credit for enabling me to write this code.
-I have not attributed him in the source files, as they have been written by myself in Java after
-studying the details of the UniquE implementation (in C), but here's a more general attribution;
-This would not have been possible without the GPL:d work of Christian Scheurer!
-
- Erik Larsson, 2007
diff --git a/src/org/catacombae/rarx/TestRAFProperties.java b/src/org/catacombae/rarx/TestRAFProperties.java
deleted file mode 100644
index ffbb955..0000000
--- a/src/org/catacombae/rarx/TestRAFProperties.java
+++ /dev/null
@@ -1,32 +0,0 @@
-/*-
- * Copyright (C) 2006 Erik Larsson
- *
- * All rights reserved.
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software
- * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA
- */
-
-package org.catacombae.rarx;
-
-public class TestRAFProperties {
- public static void main(String[] args) {
- //723152686 32768
- int number = 30197;
- System.out.println(number + " (0x" + Util.toHexStringBE(number) + ")");
- System.out.println((0-number) + " (0x" + Util.toHexStringBE((0-number)) + ")");
- System.out.println(((0-number) & 0xFFFFF) + " (0x" + Util.toHexStringBE(((0-number) & 0xFFFFF)) + ")");
- System.out.println((0xFFFFF-number) + " (0x" + Util.toHexStringBE((0xFFFFF-number)) + ")");
- }
-}
diff --git a/src/org/catacombae/rarx/Tree.java b/src/org/catacombae/rarx/Tree.java
deleted file mode 100644
index 1ec9eb0..0000000
--- a/src/org/catacombae/rarx/Tree.java
+++ /dev/null
@@ -1,55 +0,0 @@
-package org.catacombae.rarx;
-import java.util.LinkedList;
-
-public class Tree<A> extends TreeNode<A> {
- public Tree(A value) { super(value); }
- public Tree() { super(); }
-
- private LinkedList<Pair<String, TreeNode<A>>> children = new LinkedList<Pair<String, TreeNode<A>>>();
-
- private static class Pair<A, B> {
- public A a;
- public B b;
- public Pair(A a, B b) {
- this.a = a;
- this.b = b;
- }
- }
-
- public void put(String entryName, TreeNode<A> tn) {
- children.addLast(new Pair<String, TreeNode<A>>(entryName, tn));
- }
- public TreeNode<A> get(String entryName) {
- for(Pair<String, TreeNode<A>> p : children) {
- if(p.a.equals(entryName))
- return p.b;
- }
- return null;
- }
-
- public int childCount() {
- return children.size();
- }
-
- public String[] listChildrenNames() {
- String[] targetArray = new String[children.size()];
- int i = 0;
- for(Pair<String, TreeNode<A>> p : children)
- targetArray[i++] = p.a;
-
- return targetArray;
-
- }
-
- public A[] listChildren(A[] targetArray) {
- if(targetArray.length != children.size())
- throw new IllegalArgumentException("target array not matching number of children");
- else {
- int i = 0;
- for(Pair<String, TreeNode<A>> p : children) {
- targetArray[i++] = p.b.getValue();
- }
- return targetArray;
- }
- }
-}
diff --git a/src/org/catacombae/rarx/TreeNode.java b/src/org/catacombae/rarx/TreeNode.java
deleted file mode 100644
index 1da80c9..0000000
--- a/src/org/catacombae/rarx/TreeNode.java
+++ /dev/null
@@ -1,17 +0,0 @@
-package org.catacombae.rarx;
-
-public abstract class TreeNode<A> {
- private A value;
- public TreeNode(A value) {
- this.value = value;
- }
- public TreeNode() {
- this.value = null;
- }
- public A getValue() {
- return value;
- }
- public void setValue(A a) {
- value = a;
- }
-}
diff --git a/src/org/catacombae/rarx/UNIXFileAttributes.java b/src/org/catacombae/rarx/UNIXFileAttributes.java
deleted file mode 100644
index 175e8d2..0000000
--- a/src/org/catacombae/rarx/UNIXFileAttributes.java
+++ /dev/null
@@ -1,66 +0,0 @@
-/*-
- * Copyright (C) 2006 Erik Larsson
- *
- * All rights reserved.
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software
- * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA
- */
-
-package org.catacombae.rarx;
-
-import java.io.PrintStream;
-
-public class UNIXFileAttributes implements FileAttributes {
- private int attributes;
-
- public UNIXFileAttributes(int attributes) {
- this.attributes = attributes;
- }
-
- public boolean isDirectory() { return isDirectoryFlagSet(); }
-
- public boolean isFileFlagSet() { return Util.getBit(attributes, 15); }
- public boolean isDirectoryFlagSet() { return Util.getBit(attributes, 14); }
- public boolean isSpecialFileFlagSet() { return Util.getBit(attributes, 13); }
- public boolean isOwnerReadFlagSet() { return Util.getBit(attributes, 8); }
- public boolean isOwnerWriteFlagSet() { return Util.getBit(attributes, 7); }
- public boolean isOwnerExecuteFlagSet() { return Util.getBit(attributes, 6); }
- public boolean isGroupReadFlagSet() { return Util.getBit(attributes, 5); }
- public boolean isGroupWriteFlagSet() { return Util.getBit(attributes, 4); }
- public boolean isGroupExecuteFlagSet() { return Util.getBit(attributes, 3); }
- public boolean isOthersReadFlagSet() { return Util.getBit(attributes, 2); }
- public boolean isOthersWriteFlagSet() { return Util.getBit(attributes, 1); }
- public boolean isOthersExecuteFlagSet() { return Util.getBit(attributes, 0); }
-
- public void print(PrintStream ps, String prefix) {
- ps.println(prefix + "UNIXFileAttributes:");
- printFields(ps, prefix);
- }
- public void printFields(PrintStream ps, String prefix) {
- ps.println(prefix + " isFileFlagSet: " + isFileFlagSet());
- ps.println(prefix + " isDirectoryFlagSet: " + isDirectoryFlagSet());
- ps.println(prefix + " isSpecialFileFlagSet: " + isSpecialFileFlagSet());
- ps.println(prefix + " isOwnerReadFlagSet: " + isOwnerReadFlagSet());
- ps.println(prefix + " isOwnerWriteFlagSet: " + isOwnerWriteFlagSet());
- ps.println(prefix + " isOwnerExecuteFlagSet: " + isOwnerExecuteFlagSet());
- ps.println(prefix + " isGroupReadFlagSet: " + isGroupReadFlagSet());
- ps.println(prefix + " isGroupWriteFlagSet: " + isGroupWriteFlagSet());
- ps.println(prefix + " isGroupExecuteFlagSet: " + isGroupExecuteFlagSet());
- ps.println(prefix + " isOthersReadFlagSet: " + isOthersReadFlagSet());
- ps.println(prefix + " isOthersWriteFlagSet: " + isOthersWriteFlagSet());
- ps.println(prefix + " isOthersExecuteFlagSet: " + isOthersExecuteFlagSet());
-// ps.println(prefix + " isFlagSet: " + isFlagSet());
- }
-}
diff --git a/src/org/catacombae/rarx/UnknownHeader.java b/src/org/catacombae/rarx/UnknownHeader.java
deleted file mode 100644
index 857ba4d..0000000
--- a/src/org/catacombae/rarx/UnknownHeader.java
+++ /dev/null
@@ -1,54 +0,0 @@
-/*-
- * Copyright (C) 2006 Erik Larsson
- *
- * All rights reserved.
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software
- * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA
- */
-
-package org.catacombae.rarx;
-
-import java.io.PrintStream;
-
-public class UnknownHeader extends RARHeader {
- private final byte[] data;
-
- public UnknownHeader(byte[] inData, int offset) {
- super(inData, offset);
- data = new byte[getHeadSize()-super.getSize()];
- System.arraycopy(inData, super.getSize(), data, 0, data.length);
- super.validateData();
- }
-
- public int getSize() {
- return _getSize();
- }
- private int _getSize() {
- return super.getSize()+data.length;
- }
-
- public byte[] getHeaderData() {
- byte[] outData = new byte[_getSize()];
- byte[] superData = super.getHeaderData();
- System.arraycopy(superData, 0, outData, 0, superData.length);
- System.arraycopy(data, 0, outData, superData.length, data.length);
- return outData;
- }
-
- public void print(PrintStream ps, String prefix) {
- System.out.println("Unknown header:");
- printFields(ps, prefix);
- }
-}
diff --git a/src/org/catacombae/rarx/Util.java b/src/org/catacombae/rarx/Util.java
deleted file mode 100644
index 80cb47b..0000000
--- a/src/org/catacombae/rarx/Util.java
+++ /dev/null
@@ -1,305 +0,0 @@
-/*-
- * Copyright (C) 2006 Erik Larsson
- *
- * All rights reserved.
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software
- * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA
- */
-
-package org.catacombae.rarx;
-
-public class Util {
- public static int sectorSize = 0x800;
-
- public static String byteArrayToHexString(byte[] array) {
- return byteArrayToHexString(array, 0, array.length);
- }
- public static String byteArrayToHexString(byte[] array, int offset, int length) {
- String result = "";
- for(int i = offset; i < (offset+length); ++i) {
- byte b = array[i];
- String currentHexString = Integer.toHexString(b & 0xFF);
- if(currentHexString.length() == 1)
- currentHexString = "0" + currentHexString;
- result += currentHexString;
- }
- return result;
- }
- public static String toHexStringBE(int[] array) {
- return toHexStringBE(array, 0, array.length);
- }
- public static String toHexStringBE(int[] array, int offset, int length) {
- StringBuilder result = new StringBuilder();
- for(int i : array)
- result.append(toHexStringBE(i));
- return result.toString();
- }
-
- public static String toHexStringLE(byte n) { return byteArrayToHexString(toByteArrayLE(n)); }
- public static String toHexStringLE(short n) { return byteArrayToHexString(toByteArrayLE(n)); }
- public static String toHexStringLE(int n) { return byteArrayToHexString(toByteArrayLE(n)); }
- public static String toHexStringLE(long n) { return byteArrayToHexString(toByteArrayLE(n)); }
- public static String toHexStringBE(byte n) { return byteArrayToHexString(toByteArrayBE(n)); }
- public static String toHexStringBE(short n) { return byteArrayToHexString(toByteArrayBE(n)); }
- public static String toHexStringBE(int n) { return byteArrayToHexString(toByteArrayBE(n)); }
- public static String toHexStringBE(long n) { return byteArrayToHexString(toByteArrayBE(n)); }
-
- public static byte[] invert(byte[] array) {
- byte[] newArray = new byte[array.length];
- for(int i = 0; i < array.length; ++i)
- newArray[newArray.length-i-1] = array[i];
- return newArray;
- }
-
- public static int readIntLE(byte[] data) {
- return readIntLE(data, 0);
- }
- public static int readIntLE(byte[] data, int offset) {
- return ((data[offset+3] & 0xFF) << 24 |
- (data[offset+2] & 0xFF) << 16 |
- (data[offset+1] & 0xFF) << 8 |
- (data[offset+0] & 0xFF) << 0);
- }
- public static short readShortLE(byte[] data) {
- return readShortLE(data, 0);
- }
- public static short readShortLE(byte[] data, int offset) {
- return (short) ((data[offset+1] & 0xFF) << 8 |
- (data[offset+0] & 0xFF) << 0);
- }
- public static byte readByteLE(byte[] data) {
- return readByteLE(data, 0);
- }
- public static byte readByteLE(byte[] data, int offset) {
- return data[offset];
- }
-
- public static byte[] toByteArrayLE(byte b) {
- byte[] result = new byte[1];
- result[0] = b;
- return result;
- }
- public static byte[] toByteArrayLE(short s) {
- byte[] result = new byte[2];
- result[0] = (byte) ((s >> 0) & 0xFF);
- result[1] = (byte) ((s >> 8) & 0xFF);
- return result;
- }
- public static byte[] toByteArrayLE(int i) {
- byte[] result = new byte[4];
- result[0] = (byte) ((i >> 0) & 0xFF);
- result[1] = (byte) ((i >> 8) & 0xFF);
- result[2] = (byte) ((i >> 16) & 0xFF);
- result[3] = (byte) ((i >> 24) & 0xFF);
- return result;
- }
- public static byte[] toByteArrayLE(long l) {
- byte[] result = new byte[8];
- result[0] = (byte) ((l >> 0) & 0xFF);
- result[1] = (byte) ((l >> 8) & 0xFF);
- result[2] = (byte) ((l >> 16) & 0xFF);
- result[3] = (byte) ((l >> 24) & 0xFF);
- result[4] = (byte) ((l >> 32) & 0xFF);
- result[5] = (byte) ((l >> 40) & 0xFF);
- result[6] = (byte) ((l >> 48) & 0xFF);
- result[7] = (byte) ((l >> 56) & 0xFF);
- return result;
- }
- public static byte[] toByteArrayBE(byte b) {
- byte[] result = new byte[1];
- result[0] = b;
- return result;
- }
- public static byte[] toByteArrayBE(short s) {
- byte[] result = new byte[2];
- result[0] = (byte) ((s >> 8) & 0xFF);
- result[1] = (byte) ((s >> 0) & 0xFF);
- return result;
- }
- public static byte[] toByteArrayBE(int i) {
- byte[] result = new byte[4];
- result[0] = (byte) ((i >> 24) & 0xFF);
- result[1] = (byte) ((i >> 16) & 0xFF);
- result[2] = (byte) ((i >> 8) & 0xFF);
- result[3] = (byte) ((i >> 0) & 0xFF);
- return result;
- }
- public static byte[] toByteArrayBE(long l) {
- byte[] result = new byte[8];
- result[0] = (byte) ((l >> 56) & 0xFF);
- result[1] = (byte) ((l >> 48) & 0xFF);
- result[2] = (byte) ((l >> 40) & 0xFF);
- result[3] = (byte) ((l >> 32) & 0xFF);
- result[4] = (byte) ((l >> 24) & 0xFF);
- result[5] = (byte) ((l >> 16) & 0xFF);
- result[6] = (byte) ((l >> 8) & 0xFF);
- result[7] = (byte) ((l >> 0) & 0xFF);
- return result;
- }
-
- public static boolean zeroed(byte[] ba) {
- for(byte b : ba)
- if(b != 0)
- return false;
- return true;
- }
-
- public static void zero(byte[] ba) {
- set(ba, 0, ba.length, (byte)0);
- }
- public static void zero(byte[] ba, int offset, int length) {
- set(ba, offset, length, (byte)0);
- }
- public static void zero(short[] ba) {
- set(ba, 0, ba.length, (short)0);
- }
- public static void zero(short[] ba, int offset, int length) {
- set(ba, offset, length, (short)0);
- }
- public static void zero(int[] ba) {
- set(ba, 0, ba.length, (int)0);
- }
- public static void zero(int[] ba, int offset, int length) {
- set(ba, offset, length, (int)0);
- }
- public static void zero(long[] ba) {
- set(ba, 0, ba.length, (long)0);
- }
- public static void zero(long[] ba, int offset, int length) {
- set(ba, offset, length, (long)0);
- }
-
- public static void set(byte[] ba, int offset, int length, byte value) {
- for(int i = offset; i < length; ++i)
- ba[i] = value;
- }
- public static void set(short[] ba, int offset, int length, short value) {
- for(int i = offset; i < length; ++i)
- ba[i] = value;
- }
- public static void set(int[] ba, int offset, int length, int value) {
- for(int i = offset; i < length; ++i)
- ba[i] = value;
- }
- public static void set(long[] ba, int offset, int length, long value) {
- for(int i = offset; i < length; ++i)
- ba[i] = value;
- }
-
- public static byte[] createCopy(byte[] data) {
- return createCopy(data, 0, data.length);
- }
-
- public static byte[] createCopy(byte[] data, int offset, int length) {
- byte[] copy = new byte[length];
- System.arraycopy(data, offset, copy, 0, length);
- return copy;
- }
-
- public static boolean arraysEqual(boolean[] a, boolean[] b) {
- if(a.length != b.length)
- return false;
- else {
- for(int i = 0; i < a.length; ++i)
- if(a[i] != b[i])
- return false;
- return true;
- }
- }
- public static boolean arraysEqual(byte[] a, byte[] b) {
- if(a.length != b.length)
- return false;
- else {
- for(int i = 0; i < a.length; ++i)
- if(a[i] != b[i])
- return false;
- return true;
- }
- }
- public static boolean arraysEqual(char[] a, char[] b) {
- if(a.length != b.length)
- return false;
- else {
- for(int i = 0; i < a.length; ++i)
- if(a[i] != b[i])
- return false;
- return true;
- }
- }
- public static boolean arraysEqual(short[] a, short[] b) {
- if(a.length != b.length)
- return false;
- else {
- for(int i = 0; i < a.length; ++i)
- if(a[i] != b[i])
- return false;
- return true;
- }
- }
- public static boolean arraysEqual(int[] a, int[] b) {
- if(a.length != b.length)
- return false;
- else {
- for(int i = 0; i < a.length; ++i)
- if(a[i] != b[i])
- return false;
- return true;
- }
- }
- public static boolean arraysEqual(long[] a, long[] b) {
- if(a.length != b.length)
- return false;
- else {
- for(int i = 0; i < a.length; ++i)
- if(a[i] != b[i])
- return false;
- return true;
- }
- }
- public static boolean arraysEqual(Object[] a, Object[] b) {
- if(a.length != b.length)
- return false;
- else {
- for(int i = 0; i < a.length; ++i)
- if(!a[i].equals(b[i]))
- return false;
- return true;
- }
- }
-
- public static long pow(long a, long b) {
- if(b < 0) throw new IllegalArgumentException("b can not be negative");
-
- long result = 1;
- for(long i = 0; i < b; ++i)
- result *= a;
- return result;
- }
-
- public static int strlen(byte[] data) {
- int length = 0;
- for(byte b : data) {
- if(b == 0)
- break;
- else
- ++length;
- }
- return length;
- }
-
- public static boolean getBit(long data, int bitNumber) {
- return ((data >>> bitNumber) & 0x1) == 0x1;
- }
-}
diff --git a/src/org/catacombae/rarx/Win32FileAttributes.java b/src/org/catacombae/rarx/Win32FileAttributes.java
deleted file mode 100644
index 957f40a..0000000
--- a/src/org/catacombae/rarx/Win32FileAttributes.java
+++ /dev/null
@@ -1,68 +0,0 @@
-/*-
- * Copyright (C) 2006 Erik Larsson
- *
- * All rights reserved.
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software
- * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA
- */
-
-package org.catacombae.rarx;
-
-import java.io.PrintStream;
-
-public class Win32FileAttributes implements FileAttributes {
- private int attributes;
-
- public Win32FileAttributes(int attributes) {
- this.attributes = attributes;
- }
-
- // Inteface methods
- public boolean isDirectory() {
- return isDirectoryFlagSet();
- }
-
- public boolean isReadOnlyFlagSet() {
- return Util.getBit(attributes, 0);
- }
- public boolean isHiddenFlagSet() {
- return Util.getBit(attributes, 1);
- }
- public boolean isSystemFlagSet() {
- return Util.getBit(attributes, 2);
- }
- public boolean isLabelFlagSet() {
- return Util.getBit(attributes, 3);
- }
- public boolean isDirectoryFlagSet() {
- return Util.getBit(attributes, 4);
- }
- public boolean isArchiveFlagSet() {
- return Util.getBit(attributes, 5);
- }
-
- public void print(PrintStream ps, String prefix) {
- ps.println(prefix + "Win32FileAttributes:");
- printFields(ps, prefix);
- }
- public void printFields(PrintStream ps, String prefix) {
- ps.println(prefix + " isReadOnlyFlagSet: " + isReadOnlyFlagSet());
- ps.println(prefix + " isHiddenFlagSet: " + isHiddenFlagSet());
- ps.println(prefix + " isSystemFlagSet: " + isSystemFlagSet());
- ps.println(prefix + " isLabelFlagSet: " + isLabelFlagSet());
- ps.println(prefix + " isDirectoryFlagSet: " + isDirectoryFlagSet());
- ps.println(prefix + " isArchiveFlagSet: " + isArchiveFlagSet());
- }
-}
diff --git a/src/org/fox/ttcomics/CbrComicArchive.java b/src/org/fox/ttcomics/CbrComicArchive.java
index 059e070..c9cf689 100644
--- a/src/org/fox/ttcomics/CbrComicArchive.java
+++ b/src/org/fox/ttcomics/CbrComicArchive.java
@@ -1,25 +1,24 @@
package org.fox.ttcomics;
-import java.io.ByteArrayInputStream;
-import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
+import java.util.Collections;
+import java.util.Comparator;
import java.util.zip.ZipFile;
-import org.catacombae.rarx.ListFilesInArchive;
-import org.catacombae.rarx.NewFileHeader;
-import org.catacombae.rarx.RARFileEntry;
-import org.catacombae.rarx.RARFileEntryStream;
+import com.github.junrar.Archive;
+import com.github.junrar.exception.RarException;
+import com.github.junrar.rarfile.FileHeader;
import android.util.Log;
public class CbrComicArchive extends ComicArchive {
private final String TAG = this.getClass().getSimpleName();
- private ZipFile m_zipFile;
- private ArrayList<RARFileEntry> m_entries = new ArrayList<RARFileEntry>();
+ private Archive m_archive;
+ private ArrayList<FileHeader> m_entries = new ArrayList<FileHeader>();
@Override
public int getCount() {
@@ -28,19 +27,19 @@ public class CbrComicArchive extends ComicArchive {
@Override
public InputStream getItem(int index) throws IOException {
- //return m_zipFile.getInputStream(m_entries.get(index));
- RARFileEntryStream rfes = new RARFileEntryStream(m_entries.get(index));
-
- ByteArrayOutputStream baos = new ByteArrayOutputStream();
-
-
-
- return new ByteArrayInputStream(baos.toByteArray());
+ try {
+ return m_archive.getInputStream(m_entries.get(index));
+ } catch (RarException e) {
+ e.printStackTrace();
+ return null;
+ }
}
- public CbrComicArchive(String fileName) throws IOException {
+ public CbrComicArchive(String fileName) throws IOException, RarException {
Log.d(TAG, "CbrComicArchive: " + fileName);
+ m_archive = new Archive(new File(fileName));
+
/* m_zipFile = new ZipFile(fileName);
Enumeration<? extends ZipEntry> e = m_zipFile.entries();
@@ -53,21 +52,30 @@ public class CbrComicArchive extends ComicArchive {
}
}
- Collections.sort(m_entries, new Comparator<ZipEntry>() {
- public int compare(ZipEntry a, ZipEntry b) {
- return a.getName().compareTo(b.getName());
- }
- }); */
+ */
- File file = new File(fileName);
+ FileHeader header = m_archive.nextFileHeader();
- for (RARFileEntry entry : ListFilesInArchive.listFiles(file)) {
- NewFileHeader header = entry.getHeader(0);
-
- if (header.getFilenameAsString().toLowerCase().matches(".*\\.(jpg|bmp|gif)$")) {
- m_entries.add(entry);
+ while (header != null) {
+ if (!header.isDirectory()) {
+ String name = header.isUnicode() ? header.getFileNameW() : header.getFileNameString();
+
+ if (name.toLowerCase().matches(".*\\.(jpg|bmp|gif)$")) {
+ m_entries.add(header);
+ }
}
+
+ header = m_archive.nextFileHeader();
}
+
+ Collections.sort(m_entries, new Comparator<FileHeader>() {
+ public int compare(FileHeader a, FileHeader b) {
+ String nameA = a.isUnicode() ? a.getFileNameW() : a.getFileNameString();
+ String nameB = b.isUnicode() ? b.getFileNameW() : b.getFileNameString();
+
+ return nameA.compareTo(nameB);
+ }
+ });
}
diff --git a/src/org/fox/ttcomics/ComicListFragment.java b/src/org/fox/ttcomics/ComicListFragment.java
index 407e96d..4b6b924 100644
--- a/src/org/fox/ttcomics/ComicListFragment.java
+++ b/src/org/fox/ttcomics/ComicListFragment.java
@@ -6,6 +6,8 @@ import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
+import com.github.junrar.exception.RarException;
+
import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
@@ -302,15 +304,19 @@ public class ComicListFragment extends Fragment implements OnItemClickListener {
if (size == -1 || fullRescan) {
- ComicArchive cba;
+ ComicArchive cba = null;
if (archive.getName().toLowerCase().matches(".*\\.(cbz|zip)")) {
cba = new CbzComicArchive(filePath);
} else {
- cba = new CbrComicArchive(filePath);
+ try {
+ cba = new CbrComicArchive(filePath);
+ } catch (RarException e) {
+ e.printStackTrace();
+ }
}
- if (cba.getCount() > 0) {
+ if (cba != null && cba.getCount() > 0) {
// Get cover
try {
diff --git a/src/org/fox/ttcomics/ComicPager.java b/src/org/fox/ttcomics/ComicPager.java
index a171d3e..ab40936 100644
--- a/src/org/fox/ttcomics/ComicPager.java
+++ b/src/org/fox/ttcomics/ComicPager.java
@@ -2,6 +2,8 @@ package org.fox.ttcomics;
import java.io.IOException;
+import com.github.junrar.exception.RarException;
+
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.SharedPreferences;
@@ -99,7 +101,11 @@ public class ComicPager extends Fragment {
}
try {
- m_archive = new CbzComicArchive(m_fileName);
+ if (m_fileName.toLowerCase().matches(".*\\.(cbz|zip)")) {
+ m_archive = new CbzComicArchive(m_fileName);
+ } else {
+ m_archive = new CbrComicArchive(m_fileName);
+ }
int position = m_activity.getLastPosition(m_fileName);
@@ -112,6 +118,9 @@ public class ComicPager extends Fragment {
} catch (IOException e) {
m_activity.toast(R.string.error_could_not_open_comic_archive);
e.printStackTrace();
+ } catch (RarException e) {
+ m_activity.toast(R.string.error_could_not_open_comic_archive);
+ e.printStackTrace();
}
pager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {