Example #1
0
        private byte[] SendBinaryReturnCommand(string commandxml)
        {
            UDPClientFull udpClient = new UDPClientFull(_ip, _port);

            MemoryStream ms = new MemoryStream();

            ICSharpCode.SharpZipLib.Zip.Compression.Streams.DeflaterOutputStream zips = new ICSharpCode.SharpZipLib.Zip.Compression.Streams.DeflaterOutputStream(ms);
            byte[] bytData = System.Text.Encoding.UTF8.GetBytes(commandxml);
            zips.Write(bytData, 0, bytData.Length);
            zips.Close();
            byte[] compressedData = (byte[])ms.ToArray();

            if (udpClient.Send(compressedData, compressedData.Length) == 0)
            {
                throw new Exception("Send Data failed");
            }

            try
            {
                if (!udpClient.Poll(5000000 * 10, SelectMode.SelectRead))
                {
                    throw new Exception("in 5 second no response");
                }

                byte[]     recvbuf    = new byte[2 * 64 * 1024];
                IPEndPoint otherpoint = new IPEndPoint(IPAddress.Any, 0);
                recvbuf = udpClient.Receive(ref otherpoint);
                return(recvbuf);
            }
            catch (Exception)
            {
                //throw new Exception("failed in waiting for response");
                throw;
            }
        }
Example #2
0
        /// <summary>
        /// 压缩字符串
        /// </summary>
        /// <param name="pBytes"></param>
        /// <returns></returns>
        public byte[] Compress(byte[] pBytes)
        {
            MemoryStream mMemory   = new MemoryStream();
            Deflater     mDeflater = new Deflater(ICSharpCode.SharpZipLib.Zip.Compression.Deflater.BEST_COMPRESSION);

            ICSharpCode.SharpZipLib.Zip.Compression.Streams.DeflaterOutputStream mStream = new ICSharpCode.SharpZipLib.Zip.Compression.Streams.DeflaterOutputStream(mMemory, mDeflater, 131072);
            mStream.Write(pBytes, 0, pBytes.Length);
            mStream.Close();
            return(mMemory.ToArray());
        }
Example #3
0
        static public byte[] CompressAndEncrypt(byte[] input, byte XORKey)
        {
            MemoryStream input_stream = new MemoryStream();

            var output_stream = new ICSharpCode.SharpZipLib.Zip.Compression.Streams.DeflaterOutputStream(input_stream);

            output_stream.Write(input, 0, input.Length);
            output_stream.Close();

            byte[] output = input_stream.ToArray();

            for (int i = 0; i < output.Length; i++)
            {
                output[i] ^= XORKey;
            }

            return(output);
        }
        /// <summary>
        /// 壓縮處理的byte陣列
        /// </summary>
        /// <param name="bytes">傳入要處理的byte陣列</param>
        /// <returns>回傳位元陣列</returns>
        public static byte[] Compress(byte[] bytes)
        {
            //開起記憶體空間資料流
            MemoryStream memory = new MemoryStream();

            //使用壓縮輸出資料流(stream),
            //並將輸出結果放入memory
            //預設開設使用128K bytes
            ZipProc.Streams.DeflaterOutputStream stream = new ZipProc.Streams.DeflaterOutputStream(memory,
              new ZipProc.Deflater(ZipProc.Deflater.BEST_SPEED),
              (128 * 1024));

            //將要處理的byte陣列 輸出到 壓縮輸出資料流
            stream.Write(bytes, 0, bytes.Length);

            //關閉壓縮輸出資料流
            stream.Close();

            //回傳記憶體資料流內的陣列
            return memory.ToArray();
        }
        void PatchPck(string pckFilename, string filename, byte[] data)
        {
            FileStream fs = new FileStream(FwInstallPath+pckFilename, FileMode.OpenOrCreate, FileAccess.ReadWrite);
            BinaryWriter bw = new BinaryWriter(fs);
            BinaryReader br = new BinaryReader(fs);

            fs.Seek(-8,SeekOrigin.End);
            int entryCount = br.ReadInt32();

            fs.Seek(-272,SeekOrigin.End);
            int fileTableOffset = br.ReadInt32() ^ KEY_1;
            fs.Seek(fileTableOffset,SeekOrigin.Begin);

            int entrySize;
            fileTableEntry[] fileTable = new fileTableEntry[entryCount];
            bool[] toEdit = new bool[entryCount];
            int t = 0;
            int editedFiles = 0;
            for (int i = 0; i < entryCount; i++) {
                entrySize = br.ReadInt32() ^ KEY_1;
                entrySize = br.ReadInt32() ^ KEY_2;

                byte[] hdata = br.ReadBytes(entrySize);
               //
                if(entrySize < 276)
                {
                    fileTable[i] = readTableEntry(hdata, entrySize, true);
                    t++;
                }
                // no zlib
                else
                {
                    fileTable[i] = readTableEntry(hdata, entrySize, false);
                }

            }

            textBox1.Text += entryCount.ToString()+"\r\n";

            fs.Seek(fileTableOffset,SeekOrigin.Begin); // useless ??

            int lastEntryPosition = fileTableOffset;

            //int filesCount = (int)files.Length;

            for (int i = 0; i < entryCount; i++) {
                if ( fileTable[i].filePath != filename ) continue;
                nb++;
                int newFileDataDecompressedSize = (int)data.Length;

                MemoryStream ms = new MemoryStream();
                ICSharpCode.SharpZipLib.Zip.Compression.Deflater defl = new ICSharpCode.SharpZipLib.Zip.Compression.Deflater(1,false);
                Stream s = new ICSharpCode.SharpZipLib.Zip.Compression.Streams.DeflaterOutputStream(ms,defl);
                s.Write(data, 0, data.Length);
                s.Close();
                byte[] dataComp = (byte[])ms.ToArray();
                ms.Close();
                int newFileDataCompressedSize = (int)dataComp.Length;

                // test de remplacer un gros png par un truc tout petit incompresible

                if ( newFileDataCompressedSize <= fileTable[i].fileDataCompressedSize ){

                    fs.Seek(fileTable[i].fileDataOffset,SeekOrigin.Begin);
                    bw.Write(dataComp);
                    textBox1.Text += fileTable[i].filePath+" Replaced\r\n";
                }
                else {
                    fileTable[i].fileDataOffset = lastEntryPosition;
                    fs.Seek(fileTable[i].fileDataOffset,SeekOrigin.Begin);
                    bw.Write(dataComp);
                    lastEntryPosition = (int)fs.Position;
                    textBox1.Text += fileTable[i].filePath+" Moved to end\r\n";
                }
                fileTable[i].fileDataCompressedSize = newFileDataCompressedSize;
                fileTable[i].fileDataDecompressedSize = newFileDataDecompressedSize;

                //ShowProgress(entryCount, i+1);

            }

            fs.Seek(lastEntryPosition,SeekOrigin.Begin);

            fileTableOffset = (int)fs.Position;

            for (int i = 0; i < entryCount; i++) {

                data = new byte[276];
                byte[] name = System.Text.Encoding.GetEncoding(936).GetBytes(fileTable[i].filePath);
                Array.Copy(name, data, name.Length);
                BitConverter.GetBytes(Convert.ToInt32(fileTable[i].fileDataOffset)).CopyTo(data, 260);
                BitConverter.GetBytes(Convert.ToInt32(fileTable[i].fileDataDecompressedSize)).CopyTo(data, 264);
                BitConverter.GetBytes(Convert.ToInt32(fileTable[i].fileDataCompressedSize)).CopyTo(data, 268);

                MemoryStream ms = new MemoryStream();
                ICSharpCode.SharpZipLib.Zip.Compression.Deflater defl = new ICSharpCode.SharpZipLib.Zip.Compression.Deflater(1,false);
                Stream s = new ICSharpCode.SharpZipLib.Zip.Compression.Streams.DeflaterOutputStream(ms,defl);
                s.Write(data, 0, data.Length);
                s.Close();
                byte[] dataComp = (byte[])ms.ToArray();
                entrySize = (int)dataComp.Length;

                bw.Write(entrySize ^ KEY_1);
                bw.Write(entrySize ^ KEY_2);

                bw.Write(dataComp);

                //ShowProgress(entryCount, i+1);
            }

            bw.Write((int)-1526153788);
            bw.Write((short)2);
            bw.Write((short)2);
            bw.Write(fileTableOffset ^ KEY_1);
            bw.Write((int)0);
            bw.Write(System.Text.Encoding.GetEncoding(936).GetBytes("Angelica File Package, Perfect World."));
            for (int i = 0; i < 215; i++) {
                bw.Write((byte)0);
            }
            bw.Write((int)-2060097592);
            bw.Write((int)entryCount);
            bw.Write((short)2);
            bw.Write((short)2);
            fs.SetLength(fs.Position);
            int fileSize = (int)fs.Position;
            fs.Seek(4, SeekOrigin.Begin);
            bw.Write(fileSize);

            br.Close();
            bw.Close();
            fs.Close();

            //textBox1.Text += editedFiles.ToString()+" File(s) patched";
            //label4.Text = filesCount.ToString()+" file(s) patched";
        }
Example #6
0
        /// <summary>
        /// Writes the specified dictionary as a slob file. Text is encoded as UTF8, and compression is zlib.
        /// </summary>
        /// <param name="dict">The dictionary to write.</param>
        /// <param name="mimeContentType">MIME content type of the values of the dictionary.</param>
        public void Write(Dictionary <string, string> dict, string mimeContentType)
        {
            // for format details see
            // https://github.com/itkach/slob


            KeyValuePair <string, string>[] listDict = dict.ToArray();
            CompareInfo myComp_enUS = new CultureInfo("en-US", false).CompareInfo;

            SortKey[] sortKeys = listDict.Select(x => myComp_enUS.GetSortKey(x.Key)).ToArray();
            Array.Sort(sortKeys, listDict, new UnicodeStringSorter());

            using (_stream = new FileStream(_fileName, FileMode.Create, FileAccess.Write, FileShare.Read))
            {
                System.Text.Encoding encoding = System.Text.UTF8Encoding.UTF8;

                BigEndianBitConverter.WriteUInt64(SupposedMagic, _stream);

                BigEndianBitConverter.WriteUInt64(SupposedVersionHi, _stream);

                BigEndianBitConverter.WriteUInt64(SupposedVersionLo, _stream);

                BigEndianBitConverter.WriteTinyText("utf-8", _stream, encoding);

                BigEndianBitConverter.WriteTinyText("zlib", _stream, encoding);

                // Tag count
                _stream.WriteByte(0);

                // char-sized sequence of content types
                _stream.WriteByte(1); // there is only one content type here
                BigEndianBitConverter.WriteText(mimeContentType, _stream, encoding);



                // Blobcount
                long posBlobCount = _stream.Position;
                BigEndianBitConverter.WriteUInt32(0, _stream); // PlaceHolder for BlobCount

                // Store offset
                long posStoreOffset = _stream.Position;
                BigEndianBitConverter.WriteUInt64(0, _stream);

                // Size
                long posSize = _stream.Position;
                BigEndianBitConverter.WriteUInt64(0, _stream);

                // list of long-positioned refs
                BigEndianBitConverter.WriteUInt32((uint)listDict.Length, _stream);
                long posRefTablePositions = _stream.Position;



                long posRefTableBegin = _stream.Position + 8 * listDict.Length;
                _stream.Seek(posRefTableBegin, SeekOrigin.Begin);

                int        i                 = -1;
                int        binIndex          = 0;
                int        itemIndex         = 0;
                int        contentLength     = 0;
                List <int> listOfEntryCounts = new List <int>(); // for every store item, this list contains the number of elements stored into it

                foreach (KeyValuePair <string, string> entry in listDict)
                {
                    ++i;
                    // Store current stream position in refTable
                    {
                        long currentPos = _stream.Position;
                        _stream.Seek(posRefTablePositions + i * 8, SeekOrigin.Begin);
                        BigEndianBitConverter.WriteUInt64((ulong)(currentPos - posRefTableBegin), _stream);
                        _stream.Seek(currentPos, SeekOrigin.Begin);
                    }

                    BigEndianBitConverter.WriteText(entry.Key, _stream, encoding);

                    BigEndianBitConverter.WriteUInt32((uint)binIndex, _stream);
                    BigEndianBitConverter.WriteUInt16((ushort)itemIndex, _stream);
                    BigEndianBitConverter.WriteTinyText(string.Empty, _stream, encoding);


                    ++itemIndex;
                    contentLength += entry.Value.Length;
                    if (itemIndex >= 32768 || contentLength > 320 * 1024) // limit one store item to 32767 entries or a maximum length of 320 kB
                    {
                        listOfEntryCounts.Add(itemIndex);
                        contentLength = 0;
                        itemIndex     = 0;
                        ++binIndex;
                    }
                }
                if (itemIndex != 0)
                {
                    listOfEntryCounts.Add(itemIndex);
                }

                // Write the blob count and store offset
                {
                    long currentPos = _stream.Position;
                    _stream.Seek(posBlobCount, SeekOrigin.Begin);
                    BigEndianBitConverter.WriteUInt32((uint)listOfEntryCounts.Count, _stream); // Blob-Count

                    // Write the store offset
                    BigEndianBitConverter.WriteUInt64((ulong)currentPos, _stream);

                    _stream.Seek(currentPos, SeekOrigin.Begin);
                }

                // list of long-positioned store items
                BigEndianBitConverter.WriteUInt32((uint)listOfEntryCounts.Count, _stream); // Store count

                long posStoreOffsetTable = _stream.Position;
                _stream.Seek(posStoreOffsetTable + 8 * listOfEntryCounts.Count, SeekOrigin.Begin);
                long posStoreBegin = _stream.Position;

                int itemIndexOffset = 0;
                for (binIndex = 0; binIndex < listOfEntryCounts.Count; ++binIndex)
                {
                    {
                        long currentPos = _stream.Position;
                        _stream.Seek(posStoreOffsetTable + 8 * binIndex, SeekOrigin.Begin);
                        BigEndianBitConverter.WriteUInt64((ulong)(currentPos - posStoreBegin), _stream);
                        _stream.Seek(currentPos, SeekOrigin.Begin);
                    }

                    BigEndianBitConverter.WriteUInt32((uint)listOfEntryCounts[binIndex], _stream);
                    for (int j = 0; j < listOfEntryCounts[binIndex]; ++j)
                    {
                        _stream.WriteByte(0); // Table with content ids
                    }

                    long posContentLength = _stream.Position;
                    BigEndianBitConverter.WriteUInt32(0, _stream); // Placeholder for content length
                                                                   // compressStream = new System.IO.Compression.DeflateStream(_stream, System.IO.Compression.CompressionLevel.Optimal, true);
                    using (ICSharpCode.SharpZipLib.Zip.Compression.Streams.DeflaterOutputStream compressStream = new ICSharpCode.SharpZipLib.Zip.Compression.Streams.DeflaterOutputStream(_stream, new ICSharpCode.SharpZipLib.Zip.Compression.Deflater(), 1024 * 1024)
                    {
                        IsStreamOwner = false
                    })
                    {
                        // now write the content

                        // First list of item offsets (without count)
                        int itemPositionOffset = 0;
                        for (int k = 0; k < listOfEntryCounts[binIndex]; ++k)
                        {
                            BigEndianBitConverter.WriteUInt32((uint)itemPositionOffset, compressStream);
                            itemPositionOffset += 4 + encoding.GetByteCount(listDict[itemIndexOffset + k].Value);
                        }

                        // now the content itself
                        for (int k = 0; k < listOfEntryCounts[binIndex]; ++k)
                        {
                            BigEndianBitConverter.WriteBigText(listDict[itemIndexOffset + k].Value, compressStream, encoding);
                        }

                        itemIndexOffset += listOfEntryCounts[binIndex];

                        compressStream.Flush();
                        compressStream.Close();
                    }

                    {
                        // Write content length
                        long currentPosition = _stream.Position;
                        _stream.Seek(posContentLength, SeekOrigin.Begin);
                        BigEndianBitConverter.WriteUInt32((uint)(currentPosition - posContentLength - 4), _stream);
                        _stream.Seek(currentPosition, SeekOrigin.Begin);
                    }
                }
            }
        }
        /// <summary>
        /// Compresses File Content
        /// </summary>
        /// <param name="ds">File Content to be compressed.</param>
        /// <returns>Byte array.</returns>
        public static byte[] CompressFileContent(byte[] blobContent)
        {

            MemoryStream ms2 = new MemoryStream(blobContent);
            StreamReader reader = new StreamReader(ms2);
            MemoryStream ms3 = new MemoryStream();
            
            
            string str = reader.ReadToEnd(); 

            ICSharpCode.SharpZipLib.Zip.Compression.Deflater defl = new ICSharpCode.SharpZipLib.Zip.Compression.Deflater(9 , false);
            ms2.Position = 0;
            Stream s = new ICSharpCode.SharpZipLib.Zip.Compression.Streams.DeflaterOutputStream(ms3, defl);
            
            
            s.Write(ms2.ToArray(), 0,(int) ms2.Length);
            s.Close();
            
            
            return (byte[])ms3.ToArray();

        }
		/// <summary>
		/// Compresses a DataSet.
		/// </summary>
		/// <param name="ds">DataSet to be compressed.</param>
		/// <param name="schemaOnly">If TRUE, compresses only the schema.</param>
		/// <param name="diffGram"></param>
		/// <returns>Byte array.</returns>
		private static byte[] CompressDataSet(DataSet ds, bool schemaOnly, bool diffGram)
		{
			SetNeutralDataTable(ds);
			MemoryStream ms2 = new MemoryStream();
			ICSharpCode.SharpZipLib.Zip.Compression.Deflater defl = new ICSharpCode.SharpZipLib.Zip.Compression.Deflater(9, false);
			Stream s = new ICSharpCode.SharpZipLib.Zip.Compression.Streams.DeflaterOutputStream(ms2, defl);
			MemoryStream ms3 = new MemoryStream();
			if (schemaOnly)
			{
				ds.WriteXmlSchema(ms3);
			}
			else
			{
				ds.WriteXml(ms3, (diffGram) ? XmlWriteMode.DiffGram : XmlWriteMode.WriteSchema);
			}
			s.Write(ms3.ToArray(), 0, (int)ms3.Length);
			s.Close();
            
			return (byte[])ms2.ToArray();

		}
Example #9
0
        void Button3Click(object sender, EventArgs e)
        {
            byte[] data = System.Text.Encoding.GetEncoding(936).GetBytes("abcdefghijklmnopqrstyhdzayhdzaydhazudzaduvwxyz");
            int dataSize = data.Length;
            MemoryStream ms = new MemoryStream();
            ICSharpCode.SharpZipLib.Zip.Compression.Deflater defl = new ICSharpCode.SharpZipLib.Zip.Compression.Deflater(9,false);
            Stream s = new ICSharpCode.SharpZipLib.Zip.Compression.Streams.DeflaterOutputStream(ms,defl);
            s.Write(data, 0, data.Length);
            s.Close();

            byte[] dataComp = (byte[])ms.ToArray();

            MemoryStream msb = new MemoryStream(dataComp,0,dataComp.Length);
            Stream s2 = new ICSharpCode.SharpZipLib.Zip.Compression.Streams.InflaterInputStream(msb);
            byte[] dataDec = new byte[dataSize];
            s2.Read(dataDec,0,dataSize);

            string res = Encoding.GetEncoding(936).GetString(dataDec);
            textBox1.Text = dataComp.Length.ToString();
        }
Example #10
0
        void CompressPck()
        {
            string pckFile = textBox2.Text;

            string pckFolder = textBox3.Text + "\\";
            int pckFolderLength = pckFolder.Length;
            //string[] files = Directory.GetFiles("C:\\fw\\", "*.*", SearchOption.AllDirectories);
            string[] files = Directory.GetFiles(pckFolder, "*.*", SearchOption.AllDirectories);

            int entryCount = files.Length;
            int fileTableOffset;
            fileTableEntry[] fileTable = new fileTableEntry[entryCount];
            int entrySize;

            FileStream BinaryFile = new FileStream(pckFile, FileMode.Create, FileAccess.ReadWrite);
            BinaryWriter bw = new BinaryWriter(BinaryFile);
            bw.Write(1305093103);
            bw.Write((int)0); // placeholder for filesize
            bw.Write(1453361591);

            for (int i = 0; i < entryCount; i++) {

                fileTable[i].filePath = files[i].Substring(pckFolderLength);
                fileTable[i].fileDataOffset = (int)BinaryFile.Position;

                FileStream  fs = File.OpenRead(pckFolder+fileTable[i].filePath);
                BinaryReader br = new BinaryReader(fs);

                fileTable[i].fileDataDecompressedSize = (int)fs.Length;
                //textBox1.Text += "\r\n__"+fileTable[i].fileDataDecompressedSize.ToString();
                byte[] data = br.ReadBytes(fileTable[i].fileDataDecompressedSize);

                //byte[] bytData = System.Text.Encoding.UTF8.GetBytes(strInput);
                MemoryStream ms = new MemoryStream();
                ICSharpCode.SharpZipLib.Zip.Compression.Deflater defl = new ICSharpCode.SharpZipLib.Zip.Compression.Deflater(1,false);
                Stream s = new ICSharpCode.SharpZipLib.Zip.Compression.Streams.DeflaterOutputStream(ms,defl);
                s.Write(data, 0, data.Length);
                s.Close();
                byte[] dataComp = (byte[])ms.ToArray();

                fileTable[i].fileDataCompressedSize = (int)dataComp.Length;

                if(fileTable[i].fileDataCompressedSize < fileTable[i].fileDataDecompressedSize)
                {
                    bw.Write(dataComp);
                    if ( i == 0){
                        //textBox1.Text += "\r\n--"+BitConverter.ToString(dataComp);
                    }
                }
                // no zlib
                else
                {
                    bw.Write(data);
                }

                br.Close();
                fs.Close();

                for (int m = 0; m < 215; m++) {
                    bw.Write((byte)0);
                }

                ShowProgress(entryCount, i+1);

            }

            fileTableOffset = (int)BinaryFile.Position;

            for (int i = 0; i < entryCount; i++) {

                byte[] data = new byte[276];
                byte[] name = System.Text.Encoding.GetEncoding(936).GetBytes(fileTable[i].filePath);
                Array.Copy(name, data, name.Length);
                BitConverter.GetBytes(Convert.ToInt32(fileTable[i].fileDataOffset)).CopyTo(data, 260);
                BitConverter.GetBytes(Convert.ToInt32(fileTable[i].fileDataDecompressedSize)).CopyTo(data, 264);
                BitConverter.GetBytes(Convert.ToInt32(fileTable[i].fileDataCompressedSize)).CopyTo(data, 268);

                MemoryStream ms = new MemoryStream();
                ICSharpCode.SharpZipLib.Zip.Compression.Deflater defl = new ICSharpCode.SharpZipLib.Zip.Compression.Deflater(1,false);
                Stream s = new ICSharpCode.SharpZipLib.Zip.Compression.Streams.DeflaterOutputStream(ms,defl);
                s.Write(data, 0, data.Length);
                s.Close();
                byte[] dataComp = (byte[])ms.ToArray();
                if ( dataComp.Length >= data.Length )
                    dataComp = data;
                entrySize = (int)dataComp.Length;

                bw.Write(entrySize ^ KEY_1);
                bw.Write(entrySize ^ KEY_2);

                bw.Write(dataComp);

                ShowProgress(entryCount, i+1);
            }

            bw.Write((int)-1526153788);
            bw.Write((short)2);
            bw.Write((short)2);
            bw.Write(fileTableOffset ^ KEY_1);
            bw.Write((int)0);
            bw.Write(System.Text.Encoding.GetEncoding(936).GetBytes("Angelica File Package, Perfect World."));
            for (int i = 0; i < 215; i++) {
                bw.Write((byte)0);
            }
            bw.Write((int)-2060097592);
            bw.Write((int)entryCount);
            bw.Write((short)2);
            bw.Write((short)2);

            int fileSize = (int)BinaryFile.Position;
            BinaryFile.Seek(4, SeekOrigin.Begin);
            bw.Write(fileSize);

            //textBox1.Text += "\r\n__"+BinaryFile.Position.ToString();
            bw.Close();
            BinaryFile.Close();

            label4.Text = entryCount.ToString()+" file(s) compressed";
        }