Imported Upstream version 3.6.0

Former-commit-id: da6be194a6b1221998fc28233f2503bd61dd9d14
This commit is contained in:
Jo Shields
2014-08-13 10:39:27 +01:00
commit a575963da9
50588 changed files with 8155799 additions and 0 deletions

View File

@ -0,0 +1,85 @@
// DeflaterConstants.cs
// Copyright (C) 2001 Mike Krueger
//
// This file was translated from java, it was part of the GNU Classpath
// Copyright (C) 2001 Free Software Foundation, Inc.
//
// 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., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
//
// Linking this library statically or dynamically with other modules is
// making a combined work based on this library. Thus, the terms and
// conditions of the GNU General Public License cover the whole
// combination.
//
// As a special exception, the copyright holders of this library give you
// permission to link this library with independent modules to produce an
// executable, regardless of the license terms of these independent
// modules, and to copy and distribute the resulting executable under
// terms of your choice, provided that you also meet, for each linked
// independent module, the terms and conditions of the license of that
// module. An independent module is a module which is not derived from
// or based on this library. If you modify this library, you may extend
// this exception to your version of the library, but you are not
// obligated to do so. If you do not wish to do so, delete this
// exception statement from your version.
using System;
namespace ICSharpCode.SharpZipLib.Zip.Compression
{
/// <summary>
/// This class contains constants used for the deflater.
/// </summary>
public class DeflaterConstants
{
public const bool DEBUGGING = false;
public const int STORED_BLOCK = 0;
public const int STATIC_TREES = 1;
public const int DYN_TREES = 2;
public const int PRESET_DICT = 0x20;
public const int DEFAULT_MEM_LEVEL = 8;
public const int MAX_MATCH = 258;
public const int MIN_MATCH = 3;
public const int MAX_WBITS = 15;
public const int WSIZE = 1 << MAX_WBITS;
public const int WMASK = WSIZE - 1;
public const int HASH_BITS = DEFAULT_MEM_LEVEL + 7;
public const int HASH_SIZE = 1 << HASH_BITS;
public const int HASH_MASK = HASH_SIZE - 1;
public const int HASH_SHIFT = (HASH_BITS + MIN_MATCH - 1) / MIN_MATCH;
public const int MIN_LOOKAHEAD = MAX_MATCH + MIN_MATCH + 1;
public const int MAX_DIST = WSIZE - MIN_LOOKAHEAD;
public const int PENDING_BUF_SIZE = 1 << (DEFAULT_MEM_LEVEL + 8);
public static int MAX_BLOCK_SIZE = Math.Min(65535, PENDING_BUF_SIZE-5);
public const int DEFLATE_STORED = 0;
public const int DEFLATE_FAST = 1;
public const int DEFLATE_SLOW = 2;
public static int[] GOOD_LENGTH = { 0, 4, 4, 4, 4, 8, 8, 8, 32, 32 };
public static int[] MAX_LAZY = { 0, 4, 5, 6, 4,16, 16, 32, 128, 258 };
public static int[] NICE_LENGTH = { 0, 8,16,32,16,32,128,128, 258, 258 };
public static int[] MAX_CHAIN = { 0, 4, 8,32,16,32,128,256,1024,4096 };
public static int[] COMPR_FUNC = { 0, 1, 1, 1, 1, 2, 2, 2, 2, 2 };
}
}

View File

@ -0,0 +1,52 @@
// DeflaterPending.cs
// Copyright (C) 2001 Mike Krueger
//
// This file was translated from java, it was part of the GNU Classpath
// Copyright (C) 2001 Free Software Foundation, Inc.
//
// 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., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
//
// Linking this library statically or dynamically with other modules is
// making a combined work based on this library. Thus, the terms and
// conditions of the GNU General Public License cover the whole
// combination.
//
// As a special exception, the copyright holders of this library give you
// permission to link this library with independent modules to produce an
// executable, regardless of the license terms of these independent
// modules, and to copy and distribute the resulting executable under
// terms of your choice, provided that you also meet, for each linked
// independent module, the terms and conditions of the license of that
// module. An independent module is a module which is not derived from
// or based on this library. If you modify this library, you may extend
// this exception to your version of the library, but you are not
// obligated to do so. If you do not wish to do so, delete this
// exception statement from your version.
namespace ICSharpCode.SharpZipLib.Zip.Compression
{
/// <summary>
/// This class stores the pending output of the Deflater.
///
/// author of the original java version : Jochen Hoenicke
/// </summary>
public class DeflaterPending : PendingBuffer
{
public DeflaterPending() : base(DeflaterConstants.PENDING_BUF_SIZE)
{
}
}
}

View File

@ -0,0 +1,207 @@
// InflaterDynHeader.cs
// Copyright (C) 2001 Mike Krueger
//
// This file was translated from java, it was part of the GNU Classpath
// Copyright (C) 2001 Free Software Foundation, Inc.
//
// 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., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
//
// Linking this library statically or dynamically with other modules is
// making a combined work based on this library. Thus, the terms and
// conditions of the GNU General Public License cover the whole
// combination.
//
// As a special exception, the copyright holders of this library give you
// permission to link this library with independent modules to produce an
// executable, regardless of the license terms of these independent
// modules, and to copy and distribute the resulting executable under
// terms of your choice, provided that you also meet, for each linked
// independent module, the terms and conditions of the license of that
// module. An independent module is a module which is not derived from
// or based on this library. If you modify this library, you may extend
// this exception to your version of the library, but you are not
// obligated to do so. If you do not wish to do so, delete this
// exception statement from your version.
using System;
using ICSharpCode.SharpZipLib.Zip.Compression.Streams;
namespace ICSharpCode.SharpZipLib.Zip.Compression
{
class InflaterDynHeader
{
const int LNUM = 0;
const int DNUM = 1;
const int BLNUM = 2;
const int BLLENS = 3;
const int LENS = 4;
const int REPS = 5;
static readonly int[] repMin = { 3, 3, 11 };
static readonly int[] repBits = { 2, 3, 7 };
byte[] blLens;
byte[] litdistLens;
InflaterHuffmanTree blTree;
int mode;
int lnum, dnum, blnum, num;
int repSymbol;
byte lastLen;
int ptr;
static readonly int[] BL_ORDER =
{ 16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15 };
public InflaterDynHeader()
{
}
public bool Decode(StreamManipulator input)
{
decode_loop:
for (;;) {
switch (mode) {
case LNUM:
lnum = input.PeekBits(5);
if (lnum < 0) {
return false;
}
lnum += 257;
input.DropBits(5);
// System.err.println("LNUM: "+lnum);
mode = DNUM;
goto case DNUM; // fall through
case DNUM:
dnum = input.PeekBits(5);
if (dnum < 0) {
return false;
}
dnum++;
input.DropBits(5);
// System.err.println("DNUM: "+dnum);
num = lnum+dnum;
litdistLens = new byte[num];
mode = BLNUM;
goto case BLNUM; // fall through
case BLNUM:
blnum = input.PeekBits(4);
if (blnum < 0) {
return false;
}
blnum += 4;
input.DropBits(4);
blLens = new byte[19];
ptr = 0;
// System.err.println("BLNUM: "+blnum);
mode = BLLENS;
goto case BLLENS; // fall through
case BLLENS:
while (ptr < blnum) {
int len = input.PeekBits(3);
if (len < 0) {
return false;
}
input.DropBits(3);
// System.err.println("blLens["+BL_ORDER[ptr]+"]: "+len);
blLens[BL_ORDER[ptr]] = (byte) len;
ptr++;
}
blTree = new InflaterHuffmanTree(blLens);
blLens = null;
ptr = 0;
mode = LENS;
goto case LENS; // fall through
case LENS:
{
int symbol;
while (((symbol = blTree.GetSymbol(input)) & ~15) == 0) {
/* Normal case: symbol in [0..15] */
// System.err.println("litdistLens["+ptr+"]: "+symbol);
litdistLens[ptr++] = lastLen = (byte)symbol;
if (ptr == num) {
/* Finished */
return true;
}
}
/* need more input ? */
if (symbol < 0) {
return false;
}
/* otherwise repeat code */
if (symbol >= 17) {
/* repeat zero */
// System.err.println("repeating zero");
lastLen = 0;
} else {
if (ptr == 0) {
throw new Exception();
}
}
repSymbol = symbol-16;
}
mode = REPS;
goto case REPS; // fall through
case REPS:
{
int bits = repBits[repSymbol];
int count = input.PeekBits(bits);
if (count < 0) {
return false;
}
input.DropBits(bits);
count += repMin[repSymbol];
// System.err.println("litdistLens repeated: "+count);
if (ptr + count > num) {
throw new Exception();
}
while (count-- > 0) {
litdistLens[ptr++] = lastLen;
}
if (ptr == num) {
/* Finished */
return true;
}
}
mode = LENS;
goto decode_loop;
}
}
}
public InflaterHuffmanTree BuildLitLenTree()
{
byte[] litlenLens = new byte[lnum];
Array.Copy(litdistLens, 0, litlenLens, 0, lnum);
return new InflaterHuffmanTree(litlenLens);
}
public InflaterHuffmanTree BuildDistTree()
{
byte[] distLens = new byte[dnum];
Array.Copy(litdistLens, lnum, distLens, 0, dnum);
return new InflaterHuffmanTree(distLens);
}
}
}

View File

@ -0,0 +1,213 @@
// InflaterHuffmanTree.cs
// Copyright (C) 2001 Mike Krueger
//
// This file was translated from java, it was part of the GNU Classpath
// Copyright (C) 2001 Free Software Foundation, Inc.
//
// 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., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
//
// Linking this library statically or dynamically with other modules is
// making a combined work based on this library. Thus, the terms and
// conditions of the GNU General Public License cover the whole
// combination.
//
// As a special exception, the copyright holders of this library give you
// permission to link this library with independent modules to produce an
// executable, regardless of the license terms of these independent
// modules, and to copy and distribute the resulting executable under
// terms of your choice, provided that you also meet, for each linked
// independent module, the terms and conditions of the license of that
// module. An independent module is a module which is not derived from
// or based on this library. If you modify this library, you may extend
// this exception to your version of the library, but you are not
// obligated to do so. If you do not wish to do so, delete this
// exception statement from your version.
using System;
using ICSharpCode.SharpZipLib.Zip.Compression.Streams;
namespace ICSharpCode.SharpZipLib.Zip.Compression
{
public class InflaterHuffmanTree
{
private static int MAX_BITLEN = 15;
private short[] tree;
public static InflaterHuffmanTree defLitLenTree, defDistTree;
static InflaterHuffmanTree()
{
try {
byte[] codeLengths = new byte[288];
int i = 0;
while (i < 144) {
codeLengths[i++] = 8;
}
while (i < 256) {
codeLengths[i++] = 9;
}
while (i < 280) {
codeLengths[i++] = 7;
}
while (i < 288) {
codeLengths[i++] = 8;
}
defLitLenTree = new InflaterHuffmanTree(codeLengths);
codeLengths = new byte[32];
i = 0;
while (i < 32) {
codeLengths[i++] = 5;
}
defDistTree = new InflaterHuffmanTree(codeLengths);
} catch (Exception) {
throw new ApplicationException("InflaterHuffmanTree: static tree length illegal");
}
}
/// <summary>
/// Constructs a Huffman tree from the array of code lengths.
/// </summary>
/// <param name = "codeLengths">
/// the array of code lengths
/// </param>
public InflaterHuffmanTree(byte[] codeLengths)
{
BuildTree(codeLengths);
}
private void BuildTree(byte[] codeLengths)
{
int[] blCount = new int[MAX_BITLEN + 1];
int[] nextCode = new int[MAX_BITLEN + 1];
for (int i = 0; i < codeLengths.Length; i++) {
int bits = codeLengths[i];
if (bits > 0) {
blCount[bits]++;
}
}
int code = 0;
int treeSize = 512;
for (int bits = 1; bits <= MAX_BITLEN; bits++) {
nextCode[bits] = code;
code += blCount[bits] << (16 - bits);
if (bits >= 10) {
/* We need an extra table for bit lengths >= 10. */
int start = nextCode[bits] & 0x1ff80;
int end = code & 0x1ff80;
treeSize += (end - start) >> (16 - bits);
}
}
/* -jr comment this out! doesnt work for dynamic trees and pkzip 2.04g
if (code != 65536)
{
throw new Exception("Code lengths don't add up properly.");
}
*/
/* Now create and fill the extra tables from longest to shortest
* bit len. This way the sub trees will be aligned.
*/
tree = new short[treeSize];
int treePtr = 512;
for (int bits = MAX_BITLEN; bits >= 10; bits--) {
int end = code & 0x1ff80;
code -= blCount[bits] << (16 - bits);
int start = code & 0x1ff80;
for (int i = start; i < end; i += 1 << 7) {
tree[DeflaterHuffman.BitReverse(i)] = (short) ((-treePtr << 4) | bits);
treePtr += 1 << (bits-9);
}
}
for (int i = 0; i < codeLengths.Length; i++) {
int bits = codeLengths[i];
if (bits == 0) {
continue;
}
code = nextCode[bits];
int revcode = DeflaterHuffman.BitReverse(code);
if (bits <= 9) {
do {
tree[revcode] = (short) ((i << 4) | bits);
revcode += 1 << bits;
} while (revcode < 512);
} else {
int subTree = tree[revcode & 511];
int treeLen = 1 << (subTree & 15);
subTree = -(subTree >> 4);
do {
tree[subTree | (revcode >> 9)] = (short) ((i << 4) | bits);
revcode += 1 << bits;
} while (revcode < treeLen);
}
nextCode[bits] = code + (1 << (16 - bits));
}
}
/// <summary>
/// Reads the next symbol from input. The symbol is encoded using the
/// huffman tree.
/// </summary>
/// <param name="input">
/// input the input source.
/// </param>
/// <returns>
/// the next symbol, or -1 if not enough input is available.
/// </returns>
public int GetSymbol(StreamManipulator input)
{
int lookahead, symbol;
if ((lookahead = input.PeekBits(9)) >= 0) {
if ((symbol = tree[lookahead]) >= 0) {
input.DropBits(symbol & 15);
return symbol >> 4;
}
int subtree = -(symbol >> 4);
int bitlen = symbol & 15;
if ((lookahead = input.PeekBits(bitlen)) >= 0) {
symbol = tree[subtree | (lookahead >> 9)];
input.DropBits(symbol & 15);
return symbol >> 4;
} else {
int bits = input.AvailableBits;
lookahead = input.PeekBits(bits);
symbol = tree[subtree | (lookahead >> 9)];
if ((symbol & 15) <= bits) {
input.DropBits(symbol & 15);
return symbol >> 4;
} else {
return -1;
}
}
} else {
int bits = input.AvailableBits;
lookahead = input.PeekBits(bits);
symbol = tree[lookahead];
if (symbol >= 0 && (symbol & 15) <= bits) {
input.DropBits(symbol & 15);
return symbol >> 4;
} else {
return -1;
}
}
}
}
}

View File

@ -0,0 +1,210 @@
// PendingBuffer.cs
// Copyright (C) 2001 Mike Krueger
//
// This file was translated from java, it was part of the GNU Classpath
// Copyright (C) 2001 Free Software Foundation, Inc.
//
// 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., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
//
// Linking this library statically or dynamically with other modules is
// making a combined work based on this library. Thus, the terms and
// conditions of the GNU General Public License cover the whole
// combination.
//
// As a special exception, the copyright holders of this library give you
// permission to link this library with independent modules to produce an
// executable, regardless of the license terms of these independent
// modules, and to copy and distribute the resulting executable under
// terms of your choice, provided that you also meet, for each linked
// independent module, the terms and conditions of the license of that
// module. An independent module is a module which is not derived from
// or based on this library. If you modify this library, you may extend
// this exception to your version of the library, but you are not
// obligated to do so. If you do not wish to do so, delete this
// exception statement from your version.
using System;
namespace ICSharpCode.SharpZipLib.Zip.Compression
{
/// <summary>
/// This class is general purpose class for writing data to a buffer.
///
/// It allows you to write bits as well as bytes
/// Based on DeflaterPending.java
///
/// author of the original java version : Jochen Hoenicke
/// </summary>
public class PendingBuffer
{
protected byte[] buf;
int start;
int end;
uint bits;
int bitCount;
public PendingBuffer() : this( 4096 )
{
}
public PendingBuffer(int bufsize)
{
buf = new byte[bufsize];
}
public void Reset()
{
start = end = bitCount = 0;
}
public void WriteByte(int b)
{
if (DeflaterConstants.DEBUGGING && start != 0) {
throw new Exception();
}
buf[end++] = (byte) b;
}
public void WriteShort(int s)
{
if (DeflaterConstants.DEBUGGING && start != 0) {
throw new Exception();
}
buf[end++] = (byte) s;
buf[end++] = (byte) (s >> 8);
}
public void WriteInt(int s)
{
if (DeflaterConstants.DEBUGGING && start != 0) {
throw new Exception();
}
buf[end++] = (byte) s;
buf[end++] = (byte) (s >> 8);
buf[end++] = (byte) (s >> 16);
buf[end++] = (byte) (s >> 24);
}
public void WriteBlock(byte[] block, int offset, int len)
{
if (DeflaterConstants.DEBUGGING && start != 0) {
throw new Exception();
}
System.Array.Copy(block, offset, buf, end, len);
end += len;
}
public int BitCount {
get {
return bitCount;
}
}
public void AlignToByte()
{
if (DeflaterConstants.DEBUGGING && start != 0) {
throw new Exception();
}
if (bitCount > 0) {
buf[end++] = (byte) bits;
if (bitCount > 8) {
buf[end++] = (byte) (bits >> 8);
}
}
bits = 0;
bitCount = 0;
}
public void WriteBits(int b, int count)
{
if (DeflaterConstants.DEBUGGING && start != 0) {
throw new Exception();
}
// if (DeflaterConstants.DEBUGGING) {
// //Console.WriteLine("writeBits("+b+","+count+")");
// }
bits |= (uint)(b << bitCount);
bitCount += count;
if (bitCount >= 16) {
buf[end++] = (byte) bits;
buf[end++] = (byte) (bits >> 8);
bits >>= 16;
bitCount -= 16;
}
}
public void WriteShortMSB(int s)
{
if (DeflaterConstants.DEBUGGING && start != 0) {
throw new Exception();
}
buf[end++] = (byte) (s >> 8);
buf[end++] = (byte) s;
}
public bool IsFlushed {
get {
return end == 0;
}
}
/// <summary>
/// Flushes the pending buffer into the given output array. If the
/// output array is to small, only a partial flush is done.
/// </summary>
/// <param name="output">
/// the output array;
/// </param>
/// <param name="offset">
/// the offset into output array;
/// </param>
/// <param name="length">
/// length the maximum number of bytes to store;
/// </param>
/// <exception name="ArgumentOutOfRangeException">
/// IndexOutOfBoundsException if offset or length are invalid.
/// </exception>
public int Flush(byte[] output, int offset, int length)
{
if (bitCount >= 8) {
buf[end++] = (byte) bits;
bits >>= 8;
bitCount -= 8;
}
if (length > end - start) {
length = end - start;
System.Array.Copy(buf, start, output, offset, length);
start = 0;
end = 0;
} else {
System.Array.Copy(buf, start, output, offset, length);
start += length;
}
return length;
}
public byte[] ToByteArray()
{
byte[] ret = new byte[end - start];
System.Array.Copy(buf, start, ret, 0, ret.Length);
start = 0;
end = 0;
return ret;
}
}
}

View File

@ -0,0 +1,379 @@
// DeflaterOutputStream.cs
// Copyright (C) 2001 Mike Krueger
//
// This file was translated from java, it was part of the GNU Classpath
// Copyright (C) 2001 Free Software Foundation, Inc.
//
// 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., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
//
// Linking this library statically or dynamically with other modules is
// making a combined work based on this library. Thus, the terms and
// conditions of the GNU General Public License cover the whole
// combination.
//
// As a special exception, the copyright holders of this library give you
// permission to link this library with independent modules to produce an
// executable, regardless of the license terms of these independent
// modules, and to copy and distribute the resulting executable under
// terms of your choice, provided that you also meet, for each linked
// independent module, the terms and conditions of the license of that
// module. An independent module is a module which is not derived from
// or based on this library. If you modify this library, you may extend
// this exception to your version of the library, but you are not
// obligated to do so. If you do not wish to do so, delete this
// exception statement from your version.
using System;
using System.IO;
using ICSharpCode.SharpZipLib.Checksums;
using ICSharpCode.SharpZipLib.Zip.Compression;
namespace ICSharpCode.SharpZipLib.Zip.Compression.Streams
{
/// <summary>
/// This is a special FilterOutputStream deflating the bytes that are
/// written through it. It uses the Deflater for deflating.
///
/// authors of the original java version : Tom Tromey, Jochen Hoenicke
/// </summary>
public class DeflaterOutputStream : Stream
{
/// <summary>
/// This buffer is used temporarily to retrieve the bytes from the
/// deflater and write them to the underlying output stream.
/// </summary>
protected byte[] buf;
/// <summary>
/// The deflater which is used to deflate the stream.
/// </summary>
protected Deflater def;
/// <summary>
/// base stream the deflater depends on.
/// </summary>
protected Stream baseOutputStream;
/// <summary>
/// I needed to implement the abstract member.
/// </summary>
public override bool CanRead {
get {
return baseOutputStream.CanRead;
}
}
/// <summary>
/// I needed to implement the abstract member.
/// </summary>
public override bool CanSeek {
get {
return false;
// return baseOutputStream.CanSeek;
}
}
/// <summary>
/// I needed to implement the abstract member.
/// </summary>
public override bool CanWrite {
get {
return baseOutputStream.CanWrite;
}
}
/// <summary>
/// I needed to implement the abstract member.
/// </summary>
public override long Length {
get {
return baseOutputStream.Length;
}
}
/// <summary>
/// I needed to implement the abstract member.
/// </summary>
public override long Position {
get {
return baseOutputStream.Position;
}
set {
baseOutputStream.Position = value;
}
}
/// <summary>
/// I needed to implement the abstract member.
/// </summary>
public override long Seek(long offset, SeekOrigin origin)
{
throw new NotSupportedException("Seek not supported"); // -jr- 01-Dec-2003
// return baseOutputStream.Seek(offset, origin);
}
/// <summary>
/// I needed to implement the abstract member.
/// </summary>
public override void SetLength(long val)
{
baseOutputStream.SetLength(val);
}
/// <summary>
/// I needed to implement the abstract member.
/// </summary>
public override int ReadByte()
{
return baseOutputStream.ReadByte();
}
/// <summary>
/// I needed to implement the abstract member.
/// </summary>
public override int Read(byte[] b, int off, int len)
{
return baseOutputStream.Read(b, off, len);
}
// -jr- 01-Dec-2003
public override IAsyncResult BeginRead(byte[] buffer, int offset, int count, AsyncCallback callback, object state)
{
throw new NotSupportedException("Asynch read not currently supported");
}
// -jr- 01-Dec-2003
public override IAsyncResult BeginWrite(byte[] buffer, int offset, int count, AsyncCallback callback, object state)
{
throw new NotSupportedException("Asynch write not currently supported");
}
/// <summary>
/// Deflates everything in the def's input buffers. This will call
/// <code>def.deflate()</code> until all bytes from the input buffers
/// are processed.
/// </summary>
protected void Deflate()
{
while (!def.IsNeedingInput) {
int len = def.Deflate(buf, 0, buf.Length);
// System.err.println("DOS deflated " + len + " baseOutputStream of " + buf.length);
if (len <= 0) {
break;
}
baseOutputStream.Write(buf, 0, len);
}
if (!def.IsNeedingInput) {
throw new ApplicationException("Can't deflate all input?");
}
}
/// <summary>
/// Creates a new DeflaterOutputStream with a default Deflater and default buffer size.
/// </summary>
/// <param name="baseOutputStream">
/// the output stream where deflated output should be written.
/// </param>
public DeflaterOutputStream(Stream baseOutputStream) : this(baseOutputStream, new Deflater(), 512)
{
}
/// <summary>
/// Creates a new DeflaterOutputStream with the given Deflater and
/// default buffer size.
/// </summary>
/// <param name="baseOutputStream">
/// the output stream where deflated output should be written.
/// </param>
/// <param name="defl">
/// the underlying deflater.
/// </param>
public DeflaterOutputStream(Stream baseOutputStream, Deflater defl) :this(baseOutputStream, defl, 512)
{
}
/// <summary>
/// Creates a new DeflaterOutputStream with the given Deflater and
/// buffer size.
/// </summary>
/// <param name="baseOutputStream">
/// the output stream where deflated output should be written.
/// </param>
/// <param name="defl">
/// the underlying deflater.
/// </param>
/// <param name="bufsize">
/// the buffer size.
/// </param>
/// <exception cref="System.InvalidOperationException">
/// if bufsize isn't positive.
/// </exception>
public DeflaterOutputStream(Stream baseOutputStream, Deflater defl, int bufsize)
{
this.baseOutputStream = baseOutputStream;
if (bufsize <= 0) {
throw new InvalidOperationException("bufsize <= 0");
}
buf = new byte[bufsize];
def = defl;
}
/// <summary>
/// Flushes the stream by calling flush() on the deflater and then
/// on the underlying stream. This ensures that all bytes are
/// flushed.
/// </summary>
public override void Flush()
{
def.Flush();
Deflate();
baseOutputStream.Flush();
}
/// <summary>
/// Finishes the stream by calling finish() on the deflater.
/// </summary>
public virtual void Finish()
{
def.Finish();
while (!def.IsFinished) {
int len = def.Deflate(buf, 0, buf.Length);
if (len <= 0) {
break;
}
// kidnthrain encryption alteration
if (this.Password != null) {
// plain data has been deflated. Now encrypt result
this.EncryptBlock(buf, 0, len);
}
baseOutputStream.Write(buf, 0, len);
}
if (!def.IsFinished) {
throw new ApplicationException("Can't deflate all input?");
}
baseOutputStream.Flush();
}
/// <summary>
/// Calls finish () and closes the stream.
/// </summary>
public override void Close()
{
Finish();
baseOutputStream.Close();
}
/// <summary>
/// Writes a single byte to the compressed output stream.
/// </summary>
/// <param name="bval">
/// the byte value.
/// </param>
public override void WriteByte(byte bval)
{
byte[] b = new byte[1];
b[0] = (byte) bval;
Write(b, 0, 1);
}
/// <summary>
/// Writes a len bytes from an array to the compressed stream.
/// </summary>
/// <param name="buf">
/// the byte array.
/// </param>
/// <param name="off">
/// the offset into the byte array where to start.
/// </param>
/// <param name="len">
/// the number of bytes to write.
/// </param>
public override void Write(byte[] buf, int off, int len)
{
// System.err.println("DOS with off " + off + " and len " + len);
def.SetInput(buf, off, len);
Deflate();
}
#region Encryption
string password = null;
uint[] keys = null;
public string Password {
get {
return password;
}
set {
password = value;
}
}
//The beauty of xor-ing bits is that
//plain ^ key = enc
//and enc ^ key = plain
//accordingly, this is the exact same as the decrypt byte
//function in InflaterInputStream
protected byte EncryptByte()
{
uint temp = ((keys[2] & 0xFFFF) | 2);
return (byte)((temp * (temp ^ 1)) >> 8);
}
/// <summary>
/// Takes a buffer of data and uses the keys
/// that have been previously initialized from a
/// password and then updated via a random encryption header
/// to encrypt that data
/// </summary>
protected void EncryptBlock(byte[] buf, int off, int len)
{
for (int i = off; i < off + len; ++i) {
byte oldbyte = buf[i];
buf[i] ^= EncryptByte();
UpdateKeys(oldbyte);
}
}
/// <summary>
/// Initializes our encryption keys using a given password
/// </summary>
protected void InitializePassword(string password) {
keys = new uint[] {
0x12345678,
0x23456789,
0x34567890
};
for (int i = 0; i < password.Length; ++i) {
UpdateKeys((byte)password[i]);
}
}
protected void UpdateKeys(byte ch)
{
keys[0] = Crc32.ComputeCrc32(keys[0], ch);
keys[1] = keys[1] + (byte)keys[0];
keys[1] = keys[1] * 134775813 + 1;
keys[2] = Crc32.ComputeCrc32(keys[2], (byte)(keys[1] >> 24));
}
#endregion
}
}

View File

@ -0,0 +1,386 @@
// InflaterInputStream.cs
// Copyright (C) 2001 Mike Krueger
//
// This file was translated from java, it was part of the GNU Classpath
// Copyright (C) 2001 Free Software Foundation, Inc.
//
// 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., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
//
// Linking this library statically or dynamically with other modules is
// making a combined work based on this library. Thus, the terms and
// conditions of the GNU General Public License cover the whole
// combination.
//
// As a special exception, the copyright holders of this library give you
// permission to link this library with independent modules to produce an
// executable, regardless of the license terms of these independent
// modules, and to copy and distribute the resulting executable under
// terms of your choice, provided that you also meet, for each linked
// independent module, the terms and conditions of the license of that
// module. An independent module is a module which is not derived from
// or based on this library. If you modify this library, you may extend
// this exception to your version of the library, but you are not
// obligated to do so. If you do not wish to do so, delete this
// exception statement from your version.
using System;
using System.IO;
using ICSharpCode.SharpZipLib.Zip.Compression;
using ICSharpCode.SharpZipLib.Checksums;
namespace ICSharpCode.SharpZipLib.Zip.Compression.Streams
{
/// <summary>
/// This filter stream is used to decompress data compressed baseInputStream the "deflate"
/// format. The "deflate" format is described baseInputStream RFC 1951.
///
/// This stream may form the basis for other decompression filters, such
/// as the <code>GzipInputStream</code>.
///
/// author of the original java version : John Leuner
/// </summary>
public class InflaterInputStream : Stream
{
//Variables
/// <summary>
/// Decompressor for this filter
/// </summary>
protected Inflater inf;
/// <summary>
/// Byte array used as a buffer
/// </summary>
protected byte[] buf;
/// <summary>
/// Size of buffer
/// </summary>
protected int len;
//We just use this if we are decoding one byte at a time with the read() call
private byte[] onebytebuffer = new byte[1];
/// <summary>
/// base stream the inflater depends on.
/// </summary>
protected Stream baseInputStream;
protected long csize;
/// <summary>
/// I needed to implement the abstract member.
/// </summary>
public override bool CanRead {
get {
return baseInputStream.CanRead;
}
}
/// <summary>
/// I needed to implement the abstract member.
/// </summary>
public override bool CanSeek {
get {
return false;
// return baseInputStream.CanSeek;
}
}
/// <summary>
/// I needed to implement the abstract member.
/// </summary>
public override bool CanWrite {
get {
return baseInputStream.CanWrite;
}
}
/// <summary>
/// I needed to implement the abstract member.
/// </summary>
public override long Length {
get {
return len;
}
}
/// <summary>
/// I needed to implement the abstract member.
/// </summary>
public override long Position {
get {
return baseInputStream.Position;
}
set {
baseInputStream.Position = value;
}
}
/// <summary>
/// Flushes the baseInputStream
/// </summary>
public override void Flush()
{
baseInputStream.Flush();
}
/// <summary>
/// I needed to implement the abstract member.
/// </summary>
public override long Seek(long offset, SeekOrigin origin)
{
throw new NotSupportedException("Seek not supported"); // -jr- 01-Dec-2003
}
/// <summary>
/// I needed to implement the abstract member.
/// </summary>
public override void SetLength(long val)
{
baseInputStream.SetLength(val);
}
/// <summary>
/// I needed to implement the abstract member.
/// </summary>
public override void Write(byte[] array, int offset, int count)
{
baseInputStream.Write(array, offset, count);
}
/// <summary>
/// I needed to implement the abstract member.
/// </summary>
public override void WriteByte(byte val)
{
baseInputStream.WriteByte(val);
}
// -jr- 01-Dec-2003 This may be flawed for some base streams? Depends on implementation of BeginWrite
public override IAsyncResult BeginWrite(byte[] buffer, int offset, int count, AsyncCallback callback, object state)
{
throw new NotSupportedException("Asynch write not currently supported");
}
//Constructors
/// <summary>
/// Create an InflaterInputStream with the default decompresseor
/// and a default buffer size.
/// </summary>
/// <param name = "baseInputStream">
/// the InputStream to read bytes from
/// </param>
public InflaterInputStream(Stream baseInputStream) : this(baseInputStream, new Inflater(), 4096)
{
}
/// <summary>
/// Create an InflaterInputStream with the specified decompresseor
/// and a default buffer size.
/// </summary>
/// <param name = "baseInputStream">
/// the InputStream to read bytes from
/// </param>
/// <param name = "inf">
/// the decompressor used to decompress data read from baseInputStream
/// </param>
public InflaterInputStream(Stream baseInputStream, Inflater inf) : this(baseInputStream, inf, 4096)
{
}
/// <summary>
/// Create an InflaterInputStream with the specified decompresseor
/// and a specified buffer size.
/// </summary>
/// <param name = "baseInputStream">
/// the InputStream to read bytes from
/// </param>
/// <param name = "inf">
/// the decompressor used to decompress data read from baseInputStream
/// </param>
/// <param name = "size">
/// size of the buffer to use
/// </param>
public InflaterInputStream(Stream baseInputStream, Inflater inf, int size)
{
this.baseInputStream = baseInputStream;
this.inf = inf;
try {
this.len = (int)baseInputStream.Length;
} catch (Exception) {
// the stream may not support .Length
this.len = 0;
}
if (size <= 0) {
throw new ArgumentOutOfRangeException("size <= 0");
}
buf = new byte[size]; //Create the buffer
}
//Methods
/// <summary>
/// Returns 0 once the end of the stream (EOF) has been reached.
/// Otherwise returns 1.
/// </summary>
public virtual int Available {
get {
return inf.IsFinished ? 0 : 1;
}
}
/// <summary>
/// Closes the input stream
/// </summary>
public override void Close()
{
baseInputStream.Close();
}
/// <summary>
/// Fills the buffer with more data to decompress.
/// </summary>
protected void Fill()
{
len = baseInputStream.Read(buf, 0, buf.Length);
// decrypting crypted data
if (cryptbuffer != null) {
DecryptBlock(buf, 0, System.Math.Min((int)(csize - inf.TotalIn), buf.Length));
}
if (len <= 0) {
throw new ApplicationException("Deflated stream ends early.");
}
inf.SetInput(buf, 0, len);
}
/// <summary>
/// Reads one byte of decompressed data.
///
/// The byte is baseInputStream the lower 8 bits of the int.
/// </summary>
public override int ReadByte()
{
int nread = Read(onebytebuffer, 0, 1); //read one byte
if (nread > 0) {
return onebytebuffer[0] & 0xff;
}
return -1; // ok
}
/// <summary>
/// Decompresses data into the byte array
/// </summary>
/// <param name ="b">
/// the array to read and decompress data into
/// </param>
/// <param name ="off">
/// the offset indicating where the data should be placed
/// </param>
/// <param name ="len">
/// the number of bytes to decompress
/// </param>
public override int Read(byte[] b, int off, int len)
{
for (;;) {
int count;
try {
count = inf.Inflate(b, off, len);
} catch (Exception e) {
throw new ZipException(e.ToString());
}
if (count > 0) {
return count;
}
if (inf.IsNeedingDictionary) {
throw new ZipException("Need a dictionary");
} else if (inf.IsFinished) {
return 0;
} else if (inf.IsNeedingInput) {
Fill();
} else {
throw new InvalidOperationException("Don't know what to do");
}
}
}
/// <summary>
/// Skip specified number of bytes of uncompressed data
/// </summary>
/// <param name ="n">
/// number of bytes to skip
/// </param>
public long Skip(long n)
{
if (n < 0) {
throw new ArgumentOutOfRangeException("n");
}
int len = 2048;
if (n < len) {
len = (int) n;
}
byte[] tmp = new byte[len];
return (long)baseInputStream.Read(tmp, 0, tmp.Length);
}
#region Encryption stuff
protected byte[] cryptbuffer = null;
uint[] keys = null;
protected byte DecryptByte()
{
uint temp = ((keys[2] & 0xFFFF) | 2);
return (byte)((temp * (temp ^ 1)) >> 8);
}
protected void DecryptBlock(byte[] buf, int off, int len)
{
for (int i = off; i < off + len; ++i) {
buf[i] ^= DecryptByte();
UpdateKeys(buf[i]);
}
}
protected void InitializePassword(string password)
{
keys = new uint[] {
0x12345678,
0x23456789,
0x34567890
};
for (int i = 0; i < password.Length; ++i) {
UpdateKeys((byte)password[i]);
}
}
protected void UpdateKeys(byte ch)
{
keys[0] = Crc32.ComputeCrc32(keys[0], ch);
keys[1] = keys[1] + (byte)keys[0];
keys[1] = keys[1] * 134775813 + 1;
keys[2] = Crc32.ComputeCrc32(keys[2], (byte)(keys[1] >> 24));
}
#endregion
}
}

View File

@ -0,0 +1,176 @@
// OutputWindow.cs
// Copyright (C) 2001 Mike Krueger
//
// This file was translated from java, it was part of the GNU Classpath
// Copyright (C) 2001 Free Software Foundation, Inc.
//
// 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., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
//
// Linking this library statically or dynamically with other modules is
// making a combined work based on this library. Thus, the terms and
// conditions of the GNU General Public License cover the whole
// combination.
//
// As a special exception, the copyright holders of this library give you
// permission to link this library with independent modules to produce an
// executable, regardless of the license terms of these independent
// modules, and to copy and distribute the resulting executable under
// terms of your choice, provided that you also meet, for each linked
// independent module, the terms and conditions of the license of that
// module. An independent module is a module which is not derived from
// or based on this library. If you modify this library, you may extend
// this exception to your version of the library, but you are not
// obligated to do so. If you do not wish to do so, delete this
// exception statement from your version.
using System;
namespace ICSharpCode.SharpZipLib.Zip.Compression.Streams
{
/// <summary>
/// Contains the output from the Inflation process.
/// We need to have a window so that we can refer backwards into the output stream
/// to repeat stuff.
///
/// author of the original java version : John Leuner
/// </summary>
public class OutputWindow
{
private static int WINDOW_SIZE = 1 << 15;
private static int WINDOW_MASK = WINDOW_SIZE - 1;
private byte[] window = new byte[WINDOW_SIZE]; //The window is 2^15 bytes
private int windowEnd = 0;
private int windowFilled = 0;
public void Write(int abyte)
{
if (windowFilled++ == WINDOW_SIZE) {
throw new InvalidOperationException("Window full");
}
window[windowEnd++] = (byte) abyte;
windowEnd &= WINDOW_MASK;
}
private void SlowRepeat(int repStart, int len, int dist)
{
while (len-- > 0) {
window[windowEnd++] = window[repStart++];
windowEnd &= WINDOW_MASK;
repStart &= WINDOW_MASK;
}
}
public void Repeat(int len, int dist)
{
if ((windowFilled += len) > WINDOW_SIZE) {
throw new InvalidOperationException("Window full");
}
int rep_start = (windowEnd - dist) & WINDOW_MASK;
int border = WINDOW_SIZE - len;
if (rep_start <= border && windowEnd < border) {
if (len <= dist) {
System.Array.Copy(window, rep_start, window, windowEnd, len);
windowEnd += len;
} else {
/* We have to copy manually, since the repeat pattern overlaps.
*/
while (len-- > 0) {
window[windowEnd++] = window[rep_start++];
}
}
} else {
SlowRepeat(rep_start, len, dist);
}
}
public int CopyStored(StreamManipulator input, int len)
{
len = Math.Min(Math.Min(len, WINDOW_SIZE - windowFilled), input.AvailableBytes);
int copied;
int tailLen = WINDOW_SIZE - windowEnd;
if (len > tailLen) {
copied = input.CopyBytes(window, windowEnd, tailLen);
if (copied == tailLen) {
copied += input.CopyBytes(window, 0, len - tailLen);
}
} else {
copied = input.CopyBytes(window, windowEnd, len);
}
windowEnd = (windowEnd + copied) & WINDOW_MASK;
windowFilled += copied;
return copied;
}
public void CopyDict(byte[] dict, int offset, int len)
{
if (windowFilled > 0) {
throw new InvalidOperationException();
}
if (len > WINDOW_SIZE) {
offset += len - WINDOW_SIZE;
len = WINDOW_SIZE;
}
System.Array.Copy(dict, offset, window, 0, len);
windowEnd = len & WINDOW_MASK;
}
public int GetFreeSpace()
{
return WINDOW_SIZE - windowFilled;
}
public int GetAvailable()
{
return windowFilled;
}
public int CopyOutput(byte[] output, int offset, int len)
{
int copy_end = windowEnd;
if (len > windowFilled) {
len = windowFilled;
} else {
copy_end = (windowEnd - windowFilled + len) & WINDOW_MASK;
}
int copied = len;
int tailLen = len - copy_end;
if (tailLen > 0) {
System.Array.Copy(window, WINDOW_SIZE - tailLen, output, offset, tailLen);
offset += tailLen;
len = copy_end;
}
System.Array.Copy(window, copy_end - len, output, offset, len);
windowFilled -= copied;
if (windowFilled < 0) {
throw new InvalidOperationException();
}
return copied;
}
public void Reset()
{
windowFilled = windowEnd = 0;
}
}
}

View File

@ -0,0 +1,245 @@
// StreamManipulator.cs
// Copyright (C) 2001 Mike Krueger
//
// This file was translated from java, it was part of the GNU Classpath
// Copyright (C) 2001 Free Software Foundation, Inc.
//
// 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., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
//
// Linking this library statically or dynamically with other modules is
// making a combined work based on this library. Thus, the terms and
// conditions of the GNU General Public License cover the whole
// combination.
//
// As a special exception, the copyright holders of this library give you
// permission to link this library with independent modules to produce an
// executable, regardless of the license terms of these independent
// modules, and to copy and distribute the resulting executable under
// terms of your choice, provided that you also meet, for each linked
// independent module, the terms and conditions of the license of that
// module. An independent module is a module which is not derived from
// or based on this library. If you modify this library, you may extend
// this exception to your version of the library, but you are not
// obligated to do so. If you do not wish to do so, delete this
// exception statement from your version.
using System;
namespace ICSharpCode.SharpZipLib.Zip.Compression.Streams
{
/// <summary>
/// This class allows us to retrieve a specified amount of bits from
/// the input buffer, as well as copy big byte blocks.
///
/// It uses an int buffer to store up to 31 bits for direct
/// manipulation. This guarantees that we can get at least 16 bits,
/// but we only need at most 15, so this is all safe.
///
/// There are some optimizations in this class, for example, you must
/// never peek more then 8 bits more than needed, and you must first
/// peek bits before you may drop them. This is not a general purpose
/// class but optimized for the behaviour of the Inflater.
///
/// authors of the original java version : John Leuner, Jochen Hoenicke
/// </summary>
public class StreamManipulator
{
private byte[] window;
private int window_start = 0;
private int window_end = 0;
private uint buffer = 0;
private int bits_in_buffer = 0;
/// <summary>
/// Get the next n bits but don't increase input pointer. n must be
/// less or equal 16 and if you if this call succeeds, you must drop
/// at least n-8 bits in the next call.
/// </summary>
/// <returns>
/// the value of the bits, or -1 if not enough bits available. */
/// </returns>
public int PeekBits(int n)
{
if (bits_in_buffer < n) {
if (window_start == window_end) {
return -1; // ok
}
buffer |= (uint)((window[window_start++] & 0xff |
(window[window_start++] & 0xff) << 8) << bits_in_buffer);
bits_in_buffer += 16;
}
return (int)(buffer & ((1 << n) - 1));
}
/// <summary>
/// Drops the next n bits from the input. You should have called peekBits
/// with a bigger or equal n before, to make sure that enough bits are in
/// the bit buffer.
/// </summary>
public void DropBits(int n)
{
buffer >>= n;
bits_in_buffer -= n;
}
/// <summary>
/// Gets the next n bits and increases input pointer. This is equivalent
/// to peekBits followed by dropBits, except for correct error handling.
/// </summary>
/// <returns>
/// the value of the bits, or -1 if not enough bits available.
/// </returns>
public int GetBits(int n)
{
int bits = PeekBits(n);
if (bits >= 0) {
DropBits(n);
}
return bits;
}
/// <summary>
/// Gets the number of bits available in the bit buffer. This must be
/// only called when a previous peekBits() returned -1.
/// </summary>
/// <returns>
/// the number of bits available.
/// </returns>
public int AvailableBits {
get {
return bits_in_buffer;
}
}
/// <summary>
/// Gets the number of bytes available.
/// </summary>
/// <returns>
/// the number of bytes available.
/// </returns>
public int AvailableBytes {
get {
return window_end - window_start + (bits_in_buffer >> 3);
}
}
/// <summary>
/// Skips to the next byte boundary.
/// </summary>
public void SkipToByteBoundary()
{
buffer >>= (bits_in_buffer & 7);
bits_in_buffer &= ~7;
}
public bool IsNeedingInput {
get {
return window_start == window_end;
}
}
/// <summary>
/// Copies length bytes from input buffer to output buffer starting
/// at output[offset]. You have to make sure, that the buffer is
/// byte aligned. If not enough bytes are available, copies fewer
/// bytes.
/// </summary>
/// <param name="output">
/// the buffer.
/// </param>
/// <param name="offset">
/// the offset in the buffer.
/// </param>
/// <param name="length">
/// the length to copy, 0 is allowed.
/// </param>
/// <returns>
/// the number of bytes copied, 0 if no byte is available.
/// </returns>
public int CopyBytes(byte[] output, int offset, int length)
{
if (length < 0) {
throw new ArgumentOutOfRangeException("length negative");
}
if ((bits_in_buffer & 7) != 0) {
/* bits_in_buffer may only be 0 or 8 */
throw new InvalidOperationException("Bit buffer is not aligned!");
}
int count = 0;
while (bits_in_buffer > 0 && length > 0) {
output[offset++] = (byte) buffer;
buffer >>= 8;
bits_in_buffer -= 8;
length--;
count++;
}
if (length == 0) {
return count;
}
int avail = window_end - window_start;
if (length > avail) {
length = avail;
}
System.Array.Copy(window, window_start, output, offset, length);
window_start += length;
if (((window_start - window_end) & 1) != 0) {
/* We always want an even number of bytes in input, see peekBits */
buffer = (uint)(window[window_start++] & 0xff);
bits_in_buffer = 8;
}
return count + length;
}
public StreamManipulator()
{
}
public void Reset()
{
buffer = (uint)(window_start = window_end = bits_in_buffer = 0);
}
public void SetInput(byte[] buf, int off, int len)
{
if (window_start < window_end) {
throw new InvalidOperationException("Old input was not completely processed");
}
int end = off + len;
/* We want to throw an ArrayIndexOutOfBoundsException early. The
* check is very tricky: it also handles integer wrap around.
*/
if (0 > off || off > end || end > buf.Length) {
throw new ArgumentOutOfRangeException();
}
if ((len & 1) != 0) {
/* We always want an even number of bytes in input, see peekBits */
buffer |= (uint)((buf[off++] & 0xff) << bits_in_buffer);
bits_in_buffer += 8;
}
window = buf;
window_start = off;
window_end = end;
}
}
}

View File

@ -0,0 +1,146 @@
// ZipConstants.cs
// Copyright (C) 2001 Mike Krueger
//
// This file was translated from java, it was part of the GNU Classpath
// Copyright (C) 2001 Free Software Foundation, Inc.
//
// 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., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
//
// Linking this library statically or dynamically with other modules is
// making a combined work based on this library. Thus, the terms and
// conditions of the GNU General Public License cover the whole
// combination.
//
// As a special exception, the copyright holders of this library give you
// permission to link this library with independent modules to produce an
// executable, regardless of the license terms of these independent
// modules, and to copy and distribute the resulting executable under
// terms of your choice, provided that you also meet, for each linked
// independent module, the terms and conditions of the license of that
// module. An independent module is a module which is not derived from
// or based on this library. If you modify this library, you may extend
// this exception to your version of the library, but you are not
// obligated to do so. If you do not wish to do so, delete this
// exception statement from your version.
using System.Text;
namespace ICSharpCode.SharpZipLib.Zip
{
/// <summary>
/// This class contains constants used for zip.
/// </summary>
public sealed class ZipConstants
{
/* The local file header */
public const int LOCHDR = 30;
public const int LOCSIG = 'P' | ('K' << 8) | (3 << 16) | (4 << 24);
public const int LOCVER = 4;
public const int LOCFLG = 6;
public const int LOCHOW = 8;
public const int LOCTIM = 10;
public const int LOCCRC = 14;
public const int LOCSIZ = 18;
public const int LOCLEN = 22;
public const int LOCNAM = 26;
public const int LOCEXT = 28;
public const int SPANNINGSIG = 'P' | ('K' << 8) | (7 << 16) | (8 << 24);
public const int SPANTEMPSIG = 'P' | ('K' << 8) | ('0' << 16) | ('0' << 24);
/* The Data descriptor */
public const int EXTSIG = 'P' | ('K' << 8) | (7 << 16) | (8 << 24);
public const int EXTHDR = 16;
public const int EXTCRC = 4;
public const int EXTSIZ = 8;
public const int EXTLEN = 12;
/* The central directory file header */
public const int CENSIG = 'P' | ('K' << 8) | (1 << 16) | (2 << 24);
/* The central directory file header for 64bit ZIP*/
public const int CENSIG64 = 'P' | ('K' << 8) | (6 << 16) | (6 << 24);
public const int CENHDR = 46;
public const int CENVEM = 4;
public const int CENVER = 6;
public const int CENFLG = 8;
public const int CENHOW = 10;
public const int CENTIM = 12;
public const int CENCRC = 16;
public const int CENSIZ = 20;
public const int CENLEN = 24;
public const int CENNAM = 28;
public const int CENEXT = 30;
public const int CENCOM = 32;
public const int CENDSK = 34;
public const int CENATT = 36;
public const int CENATX = 38;
public const int CENOFF = 42;
/* The entries in the end of central directory */
public const int ENDSIG = 'P' | ('K' << 8) | (5 << 16) | (6 << 24);
public const int ENDHDR = 22;
public const int HDRDIGITALSIG = 'P' | ('K' << 8) | (5 << 16) | (5 << 24);
public const int CENDIGITALSIG = 'P' | ('K' << 8) | (5 << 16) | (5 << 24);
/* The following two fields are missing in SUN JDK */
public const int ENDNRD = 4;
public const int ENDDCD = 6;
public const int ENDSUB = 8;
public const int ENDTOT = 10;
public const int ENDSIZ = 12;
public const int ENDOFF = 16;
public const int ENDCOM = 20;
static int defaultCodePage = 0; // 0 gives default code page, set it to whatever you like or alternatively alter it via property at runtime for more flexibility
// Some care for compatability purposes is required as you can specify unicode code pages here.... if this way of working seems ok
// then some protection may be added to make the interface a bit more robust perhaps.
public static int DefaultCodePage {
get {
return defaultCodePage;
}
set {
defaultCodePage = value;
}
}
public static string ConvertToString(byte[] data)
{
#if COMACT_FRAMEWORK
return Encoding.ASCII.GetString(data,0, data.Length);
#else
return Encoding.GetEncoding(DefaultCodePage).GetString(data, 0, data.Length);
#endif
}
public static byte[] ConvertToArray(string str)
{
#if COMACT_FRAMEWORK
return Encoding.ASCII.GetBytes(str);
#else
return Encoding.GetEncoding(DefaultCodePage).GetBytes(str);
#endif
}
}
}

View File

@ -0,0 +1,428 @@
// ZipEntry.cs
// Copyright (C) 2001 Mike Krueger
//
// This file was translated from java, it was part of the GNU Classpath
// Copyright (C) 2001 Free Software Foundation, Inc.
//
// 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., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
//
// Linking this library statically or dynamically with other modules is
// making a combined work based on this library. Thus, the terms and
// conditions of the GNU General Public License cover the whole
// combination.
//
// As a special exception, the copyright holders of this library give you
// permission to link this library with independent modules to produce an
// executable, regardless of the license terms of these independent
// modules, and to copy and distribute the resulting executable under
// terms of your choice, provided that you also meet, for each linked
// independent module, the terms and conditions of the license of that
// module. An independent module is a module which is not derived from
// or based on this library. If you modify this library, you may extend
// this exception to your version of the library, but you are not
// obligated to do so. If you do not wish to do so, delete this
// exception statement from your version.
using System;
namespace ICSharpCode.SharpZipLib.Zip
{
public enum CompressionMethod
{
Stored = 0,
Deflated = 8,
}
/// <summary>
/// This class represents a member of a zip archive. ZipFile and
/// ZipInputStream will give you instances of this class as information
/// about the members in an archive. On the other hand ZipOutputStream
/// needs an instance of this class to create a new member.
///
/// author of the original java version : Jochen Hoenicke
/// </summary>
public class ZipEntry : ICloneable
{
static int KNOWN_SIZE = 1;
static int KNOWN_CSIZE = 2;
static int KNOWN_CRC = 4;
static int KNOWN_TIME = 8;
string name;
uint size;
ushort version;
uint compressedSize;
uint crc;
uint dosTime;
ushort known = 0;
CompressionMethod method = CompressionMethod.Deflated;
byte[] extra = null;
string comment = null;
bool isCrypted;
int zipFileIndex = -1; /* used by ZipFile */
int flags; /* used by ZipOutputStream */
int offset; /* used by ZipFile and ZipOutputStream */
public bool IsEncrypted {
get {
return (flags & 1) != 0;
}
set {
if (value) {
flags |= 1;
} else {
flags &= ~1;
}
}
}
public int ZipFileIndex {
get {
return zipFileIndex;
}
set {
zipFileIndex = value;
}
}
public int Offset {
get {
return offset;
}
set {
offset = value;
}
}
public int Flags { // Stops having two things represent same concept in class (flag isCrypted removed)
get {
return flags;
}
set {
flags = value;
}
}
/// <summary>
/// Creates a zip entry with the given name.
/// </summary>
/// <param name="name">
/// the name. May include directory components separated by '/'.
/// </param>
public ZipEntry(string name)
{
if (name == null) {
throw new System.ArgumentNullException("name");
}
this.DateTime = System.DateTime.Now;
this.name = name;
}
/// <summary>
/// Creates a copy of the given zip entry.
/// </summary>
/// <param name="e">
/// the entry to copy.
/// </param>
public ZipEntry(ZipEntry e)
{
name = e.name;
known = e.known;
size = e.size;
compressedSize = e.compressedSize;
crc = e.crc;
dosTime = e.dosTime;
method = e.method;
extra = e.extra;
comment = e.comment;
}
public int Version {
get {
return version;
}
set {
version = (ushort)value;
}
}
public long DosTime {
get {
if ((known & KNOWN_TIME) == 0) {
return 0;
} else {
return dosTime;
}
}
set {
this.dosTime = (uint)value;
known |= (ushort)KNOWN_TIME;
}
}
/// <summary>
/// Gets/Sets the time of last modification of the entry.
/// </summary>
public DateTime DateTime {
get {
uint sec = 2 * (dosTime & 0x1f);
uint min = (dosTime >> 5) & 0x3f;
uint hrs = (dosTime >> 11) & 0x1f;
uint day = (dosTime >> 16) & 0x1f;
uint mon = ((dosTime >> 21) & 0xf);
uint year = ((dosTime >> 25) & 0x7f) + 1980; /* since 1900 */
return new System.DateTime((int)year, (int)mon, (int)day, (int)hrs, (int)min, (int)sec);
}
set {
DosTime = ((uint)value.Year - 1980 & 0x7f) << 25 |
((uint)value.Month) << 21 |
((uint)value.Day) << 16 |
((uint)value.Hour) << 11 |
((uint)value.Minute) << 5 |
((uint)value.Second) >> 1;
}
}
/// <summary>
/// Returns the entry name. The path components in the entry are
/// always separated by slashes ('/').
/// </summary>
public string Name {
get {
return name;
}
}
// /// <summary>
// /// Gets/Sets the time of last modification of the entry.
// /// </summary>
// /// <returns>
// /// the time of last modification of the entry, or -1 if unknown.
// /// </returns>
// public long Time {
// get {
// return (known & KNOWN_TIME) != 0 ? time * 1000L : -1;
// }
// set {
// this.time = (int) (value / 1000L);
// this.known |= (ushort)KNOWN_TIME;
// }
// }
/// <summary>
/// Gets/Sets the size of the uncompressed data.
/// </summary>
/// <exception cref="System.ArgumentOutOfRangeException">
/// if size is not in 0..0xffffffffL
/// </exception>
/// <returns>
/// the size or -1 if unknown.
/// </returns>
public long Size {
get {
return (known & KNOWN_SIZE) != 0 ? (long)size : -1L;
}
set {
if (((ulong)value & 0xFFFFFFFF00000000L) != 0) {
throw new ArgumentOutOfRangeException("size");
}
this.size = (uint)value;
this.known |= (ushort)KNOWN_SIZE;
}
}
/// <summary>
/// Gets/Sets the size of the compressed data.
/// </summary>
/// <exception cref="System.ArgumentOutOfRangeException">
/// if csize is not in 0..0xffffffffL
/// </exception>
/// <returns>
/// the size or -1 if unknown.
/// </returns>
public long CompressedSize {
get {
return (known & KNOWN_CSIZE) != 0 ? (long)compressedSize : -1L;
}
set {
if (((ulong)value & 0xffffffff00000000L) != 0) {
throw new ArgumentOutOfRangeException();
}
this.compressedSize = (uint)value;
this.known |= (ushort)KNOWN_CSIZE;
}
}
/// <summary>
/// Gets/Sets the crc of the uncompressed data.
/// </summary>
/// <exception cref="System.ArgumentOutOfRangeException">
/// if crc is not in 0..0xffffffffL
/// </exception>
/// <returns>
/// the crc or -1 if unknown.
/// </returns>
public long Crc {
get {
return (known & KNOWN_CRC) != 0 ? crc & 0xffffffffL : -1L;
}
set {
if (((ulong)crc & 0xffffffff00000000L) != 0)
{
throw new Exception();
}
this.crc = (uint)value;
this.known |= (ushort)KNOWN_CRC;
}
}
/// <summary>
/// Gets/Sets the compression method. Only DEFLATED and STORED are supported.
/// </summary>
/// <exception cref="System.ArgumentOutOfRangeException">
/// if method is not supported.
/// </exception>
/// <returns>
/// the compression method or -1 if unknown.
/// </returns>
/// <see cref="ZipOutputStream.DEFLATED"/>
/// <see cref="ZipOutputStream.STORED"/>
public CompressionMethod CompressionMethod {
get {
return method;
}
set {
this.method = value;
}
}
/// <summary>
/// Gets/Sets the extra data.
/// </summary>
/// <exception cref="System.ArgumentOutOfRangeException">
/// if extra is longer than 0xffff bytes.
/// </exception>
/// <returns>
/// the extra data or null if not set.
/// </returns>
public byte[] ExtraData {
get {
return extra;
}
set {
if (value == null) {
this.extra = null;
return;
}
if (value.Length > 0xffff) {
throw new System.ArgumentOutOfRangeException();
}
this.extra = value;
try {
int pos = 0;
while (pos < extra.Length) {
int sig = (extra[pos++] & 0xff) | (extra[pos++] & 0xff) << 8;
int len = (extra[pos++] & 0xff) | (extra[pos++] & 0xff) << 8;
if (sig == 0x5455) {
/* extended time stamp, unix format by Rainer Prem <Rainer@Prem.de> */
int flags = extra[pos];
if ((flags & 1) != 0) {
int iTime = ((extra[pos+1] & 0xff) |
(extra[pos+2] & 0xff) << 8 |
(extra[pos+3] & 0xff) << 16 |
(extra[pos+4] & 0xff) << 24);
DateTime = (new DateTime ( 1970, 1, 1, 0, 0, 0 ) + new TimeSpan ( 0, 0, 0, iTime, 0 )).ToLocalTime ();
known |= (ushort)KNOWN_TIME;
}
}
pos += len;
}
} catch (Exception) {
/* be lenient */
return;
}
}
}
/// <summary>
/// Gets/Sets the entry comment.
/// </summary>
/// <exception cref="System.ArgumentOutOfRangeException">
/// if comment is longer than 0xffff.
/// </exception>
/// <returns>
/// the comment or null if not set.
/// </returns>
public string Comment {
get {
return comment;
}
set {
if (value.Length > 0xffff)
{
throw new ArgumentOutOfRangeException();
}
this.comment = value;
}
}
/// <summary>
/// Gets true, if the entry is a directory. This is solely
/// determined by the name, a trailing slash '/' marks a directory.
/// </summary>
public bool IsDirectory {
get {
int nlen = name.Length;
return nlen > 0 && name[nlen - 1] == '/';
}
}
/// <value>
/// True, if the entry is encrypted.
/// </value>
public bool IsCrypted {
get {
return isCrypted;
}
set {
isCrypted = value;
}
}
/// <summary>
/// Creates a copy of this zip entry.
/// </summary>
public object Clone()
{
return this.MemberwiseClone();
}
/// <summary>
/// Gets the string representation of this ZipEntry. This is just
/// the name as returned by getName().
/// </summary>
public override string ToString()
{
return name;
}
}
}

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,488 @@
// ZipInputStream.cs
// Copyright (C) 2001 Mike Krueger
//
// This file was translated from java, it was part of the GNU Classpath
// Copyright (C) 2001 Free Software Foundation, Inc.
//
// 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., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
//
// Linking this library statically or dynamically with other modules is
// making a combined work based on this library. Thus, the terms and
// conditions of the GNU General Public License cover the whole
// combination.
//
// As a special exception, the copyright holders of this library give you
// permission to link this library with independent modules to produce an
// executable, regardless of the license terms of these independent
// modules, and to copy and distribute the resulting executable under
// terms of your choice, provided that you also meet, for each linked
// independent module, the terms and conditions of the license of that
// module. An independent module is a module which is not derived from
// or based on this library. If you modify this library, you may extend
// this exception to your version of the library, but you are not
// obligated to do so. If you do not wish to do so, delete this
// exception statement from your version.
using System;
using System.Text;
using System.IO;
using ICSharpCode.SharpZipLib.Checksums;
using ICSharpCode.SharpZipLib.Zip.Compression;
using ICSharpCode.SharpZipLib.Zip.Compression.Streams;
namespace ICSharpCode.SharpZipLib.Zip
{
/// <summary>
/// This is a FilterInputStream that reads the files baseInputStream an zip archive
/// one after another. It has a special method to get the zip entry of
/// the next file. The zip entry contains information about the file name
/// size, compressed size, CRC, etc.
/// It includes support for STORED and DEFLATED entries.
///
/// author of the original java version : Jochen Hoenicke
/// </summary>
/// <example> This sample shows how to read a zip file
/// <code lang="C#">
/// using System;
/// using System.Text;
/// using System.IO;
///
/// using NZlib.Zip;
///
/// class MainClass
/// {
/// public static void Main(string[] args)
/// {
/// ZipInputStream s = new ZipInputStream(File.OpenRead(args[0]));
///
/// ZipEntry theEntry;
/// while ((theEntry = s.GetNextEntry()) != null) {
/// int size = 2048;
/// byte[] data = new byte[2048];
///
/// Console.Write("Show contents (y/n) ?");
/// if (Console.ReadLine() == "y") {
/// while (true) {
/// size = s.Read(data, 0, data.Length);
/// if (size > 0) {
/// Console.Write(new ASCIIEncoding().GetString(data, 0, size));
/// } else {
/// break;
/// }
/// }
/// }
/// }
/// s.Close();
/// }
/// }
/// </code>
/// </example>
public class ZipInputStream : InflaterInputStream
{
Crc32 crc = new Crc32();
ZipEntry entry = null;
long size;
int method;
int flags;
long avail;
string password = null;
public string Password {
get {
return password;
}
set {
password = value;
}
}
/// <summary>
/// Creates a new Zip input stream, reading a zip archive.
/// </summary>
public ZipInputStream(Stream baseInputStream) : base(baseInputStream, new Inflater(true))
{
}
void FillBuf()
{
avail = len = baseInputStream.Read(buf, 0, buf.Length);
}
int ReadBuf(byte[] outBuf, int offset, int length)
{
if (avail <= 0) {
FillBuf();
if (avail <= 0) {
return 0;
}
}
if (length > avail) {
length = (int)avail;
}
System.Array.Copy(buf, len - (int)avail, outBuf, offset, length);
avail -= length;
return length;
}
void ReadFully(byte[] outBuf)
{
int off = 0;
int len = outBuf.Length;
while (len > 0) {
int count = ReadBuf(outBuf, off, len);
if (count == -1) {
throw new Exception();
}
off += count;
len -= count;
}
}
int ReadLeByte()
{
if (avail <= 0) {
FillBuf();
if (avail <= 0) {
throw new ZipException("EOF in header");
}
}
return buf[len - avail--] & 0xff;
}
/// <summary>
/// Read an unsigned short baseInputStream little endian byte order.
/// </summary>
int ReadLeShort()
{
return ReadLeByte() | (ReadLeByte() << 8);
}
/// <summary>
/// Read an int baseInputStream little endian byte order.
/// </summary>
int ReadLeInt()
{
return ReadLeShort() | (ReadLeShort() << 16);
}
/// <summary>
/// Read an int baseInputStream little endian byte order.
/// </summary>
long ReadLeLong()
{
return ReadLeInt() | (ReadLeInt() << 32);
}
/// <summary>
/// Open the next entry from the zip archive, and return its description.
/// If the previous entry wasn't closed, this method will close it.
/// </summary>
public ZipEntry GetNextEntry()
{
if (crc == null) {
throw new InvalidOperationException("Closed.");
}
if (entry != null) {
CloseEntry();
}
if (this.cryptbuffer != null) {
if (avail == 0 && inf.RemainingInput != 0) {
avail = inf.RemainingInput - 16;
inf.Reset();
}
baseInputStream.Position -= this.len;
baseInputStream.Read(this.buf, 0, this.len);
}
int header = ReadLeInt();
// -jr- added end sig for empty zip files, Zip64 end sig and digital sig for files that have them...
if (header == ZipConstants.CENSIG ||
header == ZipConstants.ENDSIG ||
header == ZipConstants.CENDIGITALSIG ||
header == ZipConstants.CENSIG64) {
// Central Header reached or end of empty zip file
Close();
return null;
}
// -jr- 07-Dec-2003 ignore spanning temporary signatures if found
// SPANNINGSIG is same as descriptor signature and is untested as yet.
if (header == ZipConstants.SPANTEMPSIG || header == ZipConstants.SPANNINGSIG) {
header = ReadLeInt();
}
if (header != ZipConstants.LOCSIG) {
throw new ZipException("Wrong Local header signature: 0x" + String.Format("{0:X}", header));
}
short version = (short)ReadLeShort();
flags = ReadLeShort();
method = ReadLeShort();
uint dostime = (uint)ReadLeInt();
int crc2 = ReadLeInt();
csize = ReadLeInt();
size = ReadLeInt();
int nameLen = ReadLeShort();
int extraLen = ReadLeShort();
bool isCrypted = (flags & 1) == 1;
if (method == ZipOutputStream.STORED && (!isCrypted && csize != size || (isCrypted && csize - 12 != size))) {
throw new ZipException("Stored, but compressed != uncompressed");
}
byte[] buffer = new byte[nameLen];
ReadFully(buffer);
string name = ZipConstants.ConvertToString(buffer);
entry = new ZipEntry(name);
entry.IsCrypted = isCrypted;
entry.Version = (ushort)version;
if (method != 0 && method != 8) {
throw new ZipException("unknown compression method " + method);
}
entry.CompressionMethod = (CompressionMethod)method;
if ((flags & 8) == 0) {
entry.Crc = crc2 & 0xFFFFFFFFL;
entry.Size = size & 0xFFFFFFFFL;
entry.CompressedSize = csize & 0xFFFFFFFFL;
}
entry.DosTime = dostime;
if (extraLen > 0) {
byte[] extra = new byte[extraLen];
ReadFully(extra);
entry.ExtraData = extra;
}
// test for encryption
if (isCrypted) {
if (password == null) {
throw new ZipException("No password set.");
}
InitializePassword(password);
cryptbuffer = new byte[12];
ReadFully(cryptbuffer);
DecryptBlock(cryptbuffer, 0, cryptbuffer.Length);
if ((flags & 8) == 0) {// -jr- 10-Feb-2004 Dont yet know correct size here....
csize -= 12;
}
} else {
cryptbuffer = null;
}
if (method == ZipOutputStream.DEFLATED && avail > 0) {
System.Array.Copy(buf, len - (int)avail, buf, 0, (int)avail);
len = (int)avail;
avail = 0;
if (isCrypted) {
DecryptBlock(buf, 0, Math.Min((int)csize, len));
}
inf.SetInput(buf, 0, len);
}
return entry;
}
private void ReadDataDescr()
{
if (ReadLeInt() != ZipConstants.EXTSIG) {
throw new ZipException("Data descriptor signature not found");
}
entry.Crc = ReadLeInt() & 0xFFFFFFFFL;
csize = ReadLeInt();
size = ReadLeInt();
entry.Size = size & 0xFFFFFFFFL;
entry.CompressedSize = csize & 0xFFFFFFFFL;
}
/// <summary>
/// Closes the current zip entry and moves to the next one.
/// </summary>
public void CloseEntry()
{
if (crc == null) {
throw new InvalidOperationException("Closed.");
}
if (entry == null) {
return;
}
if (method == ZipOutputStream.DEFLATED) {
if ((flags & 8) != 0) {
/* We don't know how much we must skip, read until end. */
byte[] tmp = new byte[2048];
while (Read(tmp, 0, tmp.Length) > 0)
;
/* read will close this entry */
return;
}
csize -= inf.TotalIn;
avail = inf.RemainingInput;
}
if (avail > csize && csize >= 0) {
avail -= csize;
} else {
csize -= avail;
avail = 0;
while (csize != 0) {
int skipped = (int)base.Skip(csize & 0xFFFFFFFFL);
if (skipped <= 0) {
throw new ZipException("zip archive ends early.");
}
csize -= skipped;
}
}
size = 0;
crc.Reset();
if (method == ZipOutputStream.DEFLATED) {
inf.Reset();
}
entry = null;
}
public override int Available {
get {
return entry != null ? 1 : 0;
}
}
/// <summary>
/// Reads a byte from the current zip entry.
/// </summary>
/// <returns>
/// the byte or -1 on EOF.
/// </returns>
/// <exception name="System.IO.IOException">
/// IOException if a i/o error occured.
/// </exception>
/// <exception name="ICSharpCode.SharpZipLib.ZipException">
/// ZipException if the deflated stream is corrupted.
/// </exception>
public override int ReadByte()
{
byte[] b = new byte[1];
if (Read(b, 0, 1) <= 0) {
return -1; // ok
}
return b[0] & 0xff;
}
/// <summary>
/// Reads a block of bytes from the current zip entry.
/// </summary>
/// <returns>
/// the number of bytes read (may be smaller, even before EOF), or -1 on EOF.
/// </returns>
/// <exception name="Exception">
/// IOException if a i/o error occured.
/// ZipException if the deflated stream is corrupted.
/// </exception>
public override int Read(byte[] b, int off, int len)
{
if (crc == null) {
throw new InvalidOperationException("Closed.");
}
if (entry == null) {
return 0;
}
bool finished = false;
switch (method) {
case ZipOutputStream.DEFLATED:
len = base.Read(b, off, len);
if (len <= 0) { // TODO BUG1 -jr- Check this was < 0 but avail was not adjusted causing failure in later calls
if (!inf.IsFinished) {
throw new ZipException("Inflater not finished!?");
}
avail = inf.RemainingInput;
// BUG1 -jr- With bit 3 set you dont yet know the size
if ((flags & 8) == 0 && (inf.TotalIn != csize || inf.TotalOut != size)) {
throw new ZipException("size mismatch: " + csize + ";" + size + " <-> " + inf.TotalIn + ";" + inf.TotalOut);
}
inf.Reset();
finished = true;
}
break;
case ZipOutputStream.STORED:
if (len > csize && csize >= 0) {
len = (int)csize;
}
len = ReadBuf(b, off, len);
if (len > 0) {
csize -= len;
size -= len;
}
if (csize == 0) {
finished = true;
} else {
if (len < 0) {
throw new ZipException("EOF in stored block");
}
}
// decrypting crypted data
if (cryptbuffer != null) {
DecryptBlock(b, off, len);
}
break;
}
if (len > 0) {
crc.Update(b, off, len);
}
if (finished) {
if ((flags & 8) != 0) {
ReadDataDescr();
}
if ((crc.Value & 0xFFFFFFFFL) != entry.Crc && entry.Crc != -1) {
throw new ZipException("CRC mismatch");
}
crc.Reset();
entry = null;
}
return len;
}
/// <summary>
/// Closes the zip file.
/// </summary>
/// <exception name="Exception">
/// if a i/o error occured.
/// </exception>
public override void Close()
{
base.Close();
crc = null;
entry = null;
}
}
}