Example #1
0
        protected override void SaveToStream(Stream stream)
        {
            if (Version==0 && 
                (_CreationTime > uint.MaxValue || 
                _ModificationTime > uint.MaxValue || 
                Duration > uint.MaxValue)) Version = 1;

            base.SaveToStream(stream);

            if (Version == 1)
            {
                stream.WriteBEUInt64(_CreationTime);
                stream.WriteBEUInt64(_ModificationTime);
                stream.WriteBEUInt32(TimeScale);
                stream.WriteBEUInt64(Duration);
            }
            else // if(Version == 0)
            {
                stream.WriteBEUInt32(checked((uint)_CreationTime));
                stream.WriteBEUInt32(checked((uint)_ModificationTime));
                stream.WriteBEUInt32(TimeScale);
                stream.WriteBEUInt32(checked((uint)Duration));
            }
            stream.WriteBEInt32(_Rate);
            stream.WriteBEInt16(_Volume);
            stream.WriteBytes(Reserved);
            for (int i = 0; i < 9; i++) stream.WriteBEInt32(Matrix[i]);
            stream.WriteBytes(PreDefined);
            stream.WriteBEUInt32(NextTrackID);
        }
Example #2
0
        protected override void SaveToStream(Stream stream)
        {
            base.SaveToStream(stream);
            stream.WriteBytes(MajorBrand.GetBytes());
            stream.WriteBEUInt32(MinorVersion);

            foreach (FourCC compatibleBrand in _CompatibleBrands)
            {
                stream.WriteBytes(compatibleBrand.GetBytes());
            }
        }
 public override void WriteToStream(Stream outputStream)
 {
     outputStream
         .WriteBytes((Byte)ASCIIBytes.p)
         .WriteInt32(4 + password.Length)
         .WriteBytes(password);
 }
Example #4
0
 public override void WriteToStream(Stream outputStream)
 {
     outputStream
         .WriteBytes((byte)FrontEndMessageCode.Describe)
         .WriteInt32(_messageLength)
         .WriteBytes((byte)_whatToDescribe)
         .WriteBytesNullTerminated(_bPortalName);
 }
Example #5
0
        public override void WriteToStream(Stream outputStream)
        {
            NpgsqlEventLog.LogMethodEnter(LogLevel.Debug, CLASSNAME, "WriteToStream");

            outputStream
                .WriteBytes((Byte)ASCIIBytes.p)
                .WriteInt32(4 + password.Length)
                .WriteBytes(password);
        }
Example #6
0
		private static void WriteBeginRequest(Stream Stream)
		{
			Stream.WriteBytes(new byte[]
			{
				1, // Version
				(byte)Fastcgi.PacketType.FCGI_BEGIN_REQUEST, // Type
				0, 1, // RequestId
				0, 8, // Content Length
				0,    // Padding Length
				0,    // Reserved
				1, 2, 3, 4, 5, 6, 7, 8, // Data
			});
		}
		public static void Encode(Image image, Stream stream)
		{
			stream.WriteString(image.Header);
			stream.WriteBytes(image.LogicalScreenDescriptor.ToBytes());

			if (image.LogicalScreenDescriptor.GlobalColorTableFlag)
			{
				stream.WriteBytes(image.GlobalColorTable);
			}

			foreach (var applicationExtension in image.ApplictionExtensions)
			{
				stream.WriteBytes(applicationExtension.ToBytes());
			}

			foreach (var commentExtension in image.CommentExtensions)
			{
				stream.WriteBytes(commentExtension.ToBytes());
			}

			WriteFrames(image.Frames, stream);
		}
		private static void WriteFrames(IEnumerable<ImageFrame> frames, Stream stream)
		{
			foreach (var frame in frames)
			{
				var frameBytes = new List<byte>();
				if (frame.GraphicControlExtension != null)
				{
					frameBytes.AddRange(frame.GraphicControlExtension.ToBytes());
				}

				frame.ImageDescriptor.SortFlag = false;
				frame.ImageDescriptor.InterlaceFlag = false;

				frameBytes.AddRange(frame.ImageDescriptor.ToBytes());
				if (frame.ImageDescriptor.LocalColorTableFlag)
				{
					frameBytes.AddRange(frame.LocalColorTable);
				}

				stream.WriteBytes(frameBytes.ToArray());

				var transparentColorIndex = -1;
				if (frame.GraphicControlExtension != null && frame.GraphicControlExtension.TransparentColorFlag)
				{
					transparentColorIndex = frame.GraphicControlExtension.TransparentColorIndex;
				}

				var imageData = GetImageData(frame.Bitmap, frame.LocalColorTable, transparentColorIndex);

				var lzwEncoder = new LzwEncoder(imageData, (byte) frame.ColorDepth);
				lzwEncoder.Encode(stream);

				stream.WriteByte(Const.BlockTerminator);
			}

			stream.WriteByte(Const.EndIntroducer);
		}
Example #9
0
        /// <summary>
        /// 
        /// </summary>
        /// <param name="IplData"></param>
        /// <param name="OutputStream"></param>
        /// <param name="ToMemoryAddress"></param>
        /// <returns></returns>
        public static IplInfo DecryptIplToMemory(byte[] IplData, Stream OutputStream, bool ToMemoryAddress = true)
        {
            var buffer = new byte[0x1000];
            var IplInfo = default(IplInfo);

            //ArrayUtils.HexDump(IplData);

            fixed (byte* IplPtr = IplData)
            fixed (byte* bufferPtr = buffer)
            {
                for (int n = 0; n < IplData.Length; n += 0x1000)
                {
                    var Ptr = IplPtr + n;

                    var Header = *(Kirk.AES128CMACHeader*)Ptr;
                    //Console.WriteLine(Header.DataSize);
                    var Kirk = new Kirk();
                    Kirk.kirk_init();
                    Kirk.kirk_CMD1(bufferPtr, Ptr, 0x1000, do_check: false);
                    var IplBlock = *(IplBlock*)bufferPtr;
                    //Console.WriteLine(IplBlock.ToStringDefault());
                    if (ToMemoryAddress)
                    {
                        OutputStream.Position = IplBlock.LoadAddress;
                        Console.WriteLine("IplBlock.LoadAddress: 0x{0:X8}", IplBlock.LoadAddress);
                    }
                    OutputStream.WriteBytes(PointerUtils.PointerToByteArray(&IplBlock.BlockData, (int)IplBlock.BlockSize));
                    if (IplBlock.EntryFunction != 0)
                    {
                        IplInfo.EntryFunction = IplBlock.EntryFunction;
                    }
                }
            }

            return IplInfo;
        }
		private void EncodeBits(Stream stream, BitEncoder bitEncoder, int suffix)
		{
			bitEncoder.Add(suffix);
			bitEncoder.Add(this.endCode);
			bitEncoder.End();

			if (bitEncoder.Length > 255)
			{
				var leftBuffer = new byte[bitEncoder.Length - 255];
				bitEncoder.CopyTo(255, leftBuffer, 0, leftBuffer.Length);
				bitEncoder.Clear();
				bitEncoder.AddRange(leftBuffer);
				stream.WriteByte((byte) leftBuffer.Length);
				stream.WriteBytes(leftBuffer);
			}
			else
			{
				stream.WriteByte((byte) (bitEncoder.Length));
				stream.WriteBytes(bitEncoder.ToArray());
				bitEncoder.Clear();
			}
		}
        private bool concatenateFragmentsInto(Stream destination)
        {
            while (true) {
            var frame = WebSocketFrame.Read (_stream, false);
            var msg = checkIfValidReceivedFrame (frame);
            if (msg != null)
              return processUnsupportedFrame (frame, CloseStatusCode.ProtocolError, msg);

            frame.Unmask ();
            if (frame.IsFinal) {
              /* FINAL */

              // CONT
              if (frame.IsContinuation) {
            destination.WriteBytes (frame.PayloadData.ApplicationData);
            break;
              }

              // PING
              if (frame.IsPing) {
            processPingFrame (frame);
            continue;
              }

              // PONG
              if (frame.IsPong) {
            processPongFrame (frame);
            continue;
              }

              // CLOSE
              if (frame.IsClose)
            return processCloseFrame (frame);
            }
            else {
              /* MORE */

              // CONT
              if (frame.IsContinuation) {
            destination.WriteBytes (frame.PayloadData.ApplicationData);
            continue;
              }
            }

            // ?
            return processUnsupportedFrame (
              frame,
              CloseStatusCode.UnsupportedData,
              "Unsupported data has been received while receiving the fragmented data.");
              }

              return true;
        }
Example #12
0
        protected override void SaveToStream(Stream stream)
        {
            base.SaveToStream(stream);

            stream.WriteBytes(Format.GetBytes());
        }
Example #13
0
        public void Serialize(Stream output)
        {
            var endian = this.Endian;

            const uint headerSize = 32;
            output.WriteValueU32(0x42424947, endian);
            output.WriteValueU32(this.Version, endian);

            var keys = new List<string>() {""};

            int maxValueLength = 0;
            var blob = new StringBuilder();
            foreach (var file in this.Files)
            {
                keys.Add(file.Name);
                foreach (var section in file.Sections)
                {
                    keys.Add(section.Key);
                    foreach (var value in section.Value)
                    {
                        keys.Add(value.Key);
                        foreach (var item in value.Value)
                        {
                            if (item.Value != null)
                            {
                                blob.Append(item.Value + '\0');
                                maxValueLength = Math.Max(maxValueLength, item.Value.Length);
                            }
                        }
                    }
                }
            }

            var huffmanEncoder = new Huffman.Encoder();
            huffmanEncoder.Build(blob.ToString());

            keys = keys.Distinct().OrderBy(k => k.HashCrc32()).ToList();
            int maxKeyLength = keys.Max(k => k.Length);

            uint stringTableSize;
            using (var data = new MemoryStream())
            {
                data.Position = 4;
                data.WriteValueS32(keys.Count, endian);

                data.Position = 4 + 4 + (8 * keys.Count);
                var offsets = new List<KeyValuePair<uint, uint>>();
                foreach (var key in keys)
                {
                    var offset = (uint)data.Position;
                    data.WriteValueU16((ushort)key.Length, endian);
                    data.WriteString(key, Encoding.UTF8);
                    offsets.Add(new KeyValuePair<uint, uint>(key.HashCrc32(), offset));
                }

                data.Position = 8;
                foreach (var kv in offsets)
                {
                    data.WriteValueU32(kv.Key, endian);
                    data.WriteValueU32(kv.Value - 8, endian);
                }

                data.Position = 0;
                data.WriteValueU32((uint)data.Length, endian);

                data.Position = 0;
                stringTableSize = (uint)data.Length;

                output.Seek(headerSize, SeekOrigin.Begin);
                output.WriteFromStream(data, data.Length);
            }

            uint huffmanSize;
            using (var data = new MemoryStream())
            {
                var pairs = huffmanEncoder.GetPairs();
                data.WriteValueU16((ushort)pairs.Length, endian);
                foreach (var pair in pairs)
                {
                    data.WriteValueS32(pair.Left, endian);
                    data.WriteValueS32(pair.Right, endian);
                }

                data.Position = 0;
                huffmanSize = (uint)data.Length;

                output.Seek(headerSize + stringTableSize, SeekOrigin.Begin);
                output.WriteFromStream(data, data.Length);
            }

            var bits = new BitArray(huffmanEncoder.TotalBits);
            var bitOffset = 0;

            uint indexSize;
            using (var index = new MemoryStream())
            {
                var fileDataOffset = 2 + (this.Files.Count * 6);

                var files = new List<KeyValuePair<ushort, int>>();
                foreach (var file in this.Files.OrderBy(f => keys.IndexOf(f.Name)))
                {
                    files.Add(new KeyValuePair<ushort, int>(
                        (ushort)keys.IndexOf(file.Name), fileDataOffset));

                    var sectionDataOffset = 2 + (file.Sections.Count * 6);

                    var sections = new List<KeyValuePair<ushort, int>>();
                    foreach (var section in file.Sections.OrderBy(s => keys.IndexOf(s.Key)))
                    {
                        sections.Add(new KeyValuePair<ushort, int>(
                            (ushort)keys.IndexOf(section.Key), sectionDataOffset));

                        var valueDataOffset = 2 + (section.Value.Count * 6);

                        var values = new List<KeyValuePair<ushort, int>>();
                        foreach (var value in section.Value.OrderBy(v => keys.IndexOf(v.Key)))
                        {
                            index.Position = fileDataOffset + sectionDataOffset + valueDataOffset;

                            values.Add(new KeyValuePair<ushort, int>(
                                (ushort)keys.IndexOf(value.Key), valueDataOffset));

                            index.WriteValueU16((ushort)value.Value.Count, endian);
                            valueDataOffset += 2;

                            foreach (var item in value.Value)
                            {
                                if (item.Type == 1)
                                {
                                    index.WriteValueS32((1 << 29) | bitOffset, endian);
                                }
                                else if (item.Type == 0 || item.Type == 2 || item.Type == 3 || item.Type == 4)
                                {
                                    index.WriteValueS32((item.Type << 29) | bitOffset, endian);
                                    bitOffset += huffmanEncoder.Encode((item.Value ?? "") + '\0', bits, bitOffset);
                                }
                                valueDataOffset += 4;
                            }
                        }

                        index.Position = fileDataOffset + sectionDataOffset;
                        
                        index.WriteValueU16((ushort)values.Count, endian);
                        sectionDataOffset += 2;

                        foreach (var value in values)
                        {
                            index.WriteValueU16(value.Key, endian);
                            index.WriteValueS32(value.Value, endian);
                            sectionDataOffset += 6;
                        }

                        sectionDataOffset += valueDataOffset;
                    }

                    index.Position = fileDataOffset;

                    index.WriteValueU16((ushort)sections.Count, endian);
                    fileDataOffset += 2;

                    foreach (var section in sections)
                    {
                        index.WriteValueU16(section.Key, endian);
                        index.WriteValueS32(section.Value, endian);
                        fileDataOffset += 6;
                    }

                    fileDataOffset += sectionDataOffset;
                }

                index.Position = 0;

                index.WriteValueU16((ushort)files.Count, endian);
                foreach (var file in files)
                {
                    index.WriteValueU16(file.Key, endian);
                    index.WriteValueS32(file.Value, endian);
                }

                index.Position = 0;
                indexSize = (uint)index.Length;

                output.Seek(headerSize + stringTableSize + huffmanSize, SeekOrigin.Begin);
                output.WriteFromStream(index, index.Length);
            }

            output.Seek(headerSize + stringTableSize + huffmanSize + indexSize, SeekOrigin.Begin);
            output.WriteValueS32(bits.Length, endian);
            var bytes = new byte[(bits.Length - 1) / 8 + 1];
            bits.CopyTo(bytes, 0);
            output.WriteBytes(bytes);

            output.Seek(8, SeekOrigin.Begin);
            output.WriteValueS32(maxKeyLength, endian);
            output.WriteValueS32(maxValueLength, endian);
            output.WriteValueU32(stringTableSize, endian);
            output.WriteValueU32(huffmanSize, endian);
            output.WriteValueU32(indexSize, endian);
            output.WriteValueS32(bytes.Length, endian);

            output.Seek(0, SeekOrigin.Begin);
            output.WriteValueU32(0x666D726D, endian);
        }
        private void AppendParameterValue(Stream dest, NpgsqlParameter parameter)
        {
            byte[] serialised = parameter.TypeInfo.ConvertToBackend(parameter.NpgsqlValue, false, Connector.NativeToBackendTypeConverterOptions);

            // Add parentheses wrapping parameter value before the type cast to avoid problems with Int16.MinValue, Int32.MinValue and Int64.MinValue
            // See bug #1010543
            // Check if this parenthesis can be collapsed with the previous one about the array support. This way, we could use
            // only one pair of parentheses for the two purposes instead of two pairs.
            dest
                .WriteBytes((byte)ASCIIBytes.ParenLeft)
                .WriteBytes((byte)ASCIIBytes.ParenLeft)
                .WriteBytes(serialised)
                .WriteBytes((byte)ASCIIBytes.ParenRight);

            if (parameter.UseCast)
            {
                dest.WriteString("::{0}", parameter.TypeInfo.CastName);

                if (parameter.TypeInfo.UseSize && (parameter.Size > 0))
                {
                    dest.WriteString("({0})", parameter.Size);
                }
            }

            dest.WriteBytes((byte)ASCIIBytes.ParenRight);
        }
Example #15
0
 public override void WriteToStream(Stream outputStream)
 {
     outputStream.WriteBytes(pgCommandBytes);
 }
Example #16
0
 public override void Pack(Stream stream)
 {
     stream.WriteInt32(Time);
     stream.WriteBoolean(DayTime);
     stream.WriteInt8(MoonPhase);
     stream.WriteBoolean(BloodMoon);
     stream.WriteBoolean(Eclipse);
     stream.WriteInt32(MaxTilesX);
     stream.WriteInt32(MaxTilesY);
     stream.WriteInt32(SpawnX);
     stream.WriteInt32(SpawnY);
     stream.WriteInt32(WorldSurface);
     stream.WriteInt32(RockLayer);
     stream.WriteInt32(WorldID);
     stream.WriteByte(MoonType);
     stream.WriteInt32(TreeX0);
     stream.WriteInt32(TreeX1);
     stream.WriteInt32(TreeX2);
     stream.WriteByte(TreeStyle0);
     stream.WriteByte(TreeStyle1);
     stream.WriteByte(TreeStyle2);
     stream.WriteByte(TreeStyle3);
     stream.WriteInt32(CaveBackX0);
     stream.WriteInt32(CaveBackX1);
     stream.WriteInt32(CaveBackX2);
     stream.WriteByte(CaveBackStyle0);
     stream.WriteByte(CaveBackStyle1);
     stream.WriteByte(CaveBackStyle2);
     stream.WriteByte(CaveBackStyle3);
     stream.WriteByte(SetBG0);
     stream.WriteByte(SetBG1);
     stream.WriteByte(SetBG2);
     stream.WriteByte(SetBG3);
     stream.WriteByte(SetBG4);
     stream.WriteByte(SetBG5);
     stream.WriteByte(SetBG6);
     stream.WriteByte(SetBG7);
     stream.WriteByte(IceBackStyle);
     stream.WriteByte(JungleBackStyle);
     stream.WriteByte(HellBackStyle);
     stream.WriteSingle(WindSpeed);
     stream.WriteByte(NumberOfClouds);
     stream.WriteInt8((byte)BossFlags);
     stream.WriteInt8((byte)BossFlags2);
     stream.WriteSingle(Rain);
     stream.WriteBytes(Encoding.UTF8.GetBytes(WorldName));
 }
Example #17
0
        /// <summary>
        /// Append a region of a source command text to an output command, performing parameter token
        /// substitutions.
        /// </summary>
        /// <param name="dest">Stream to which to append output.</param>
        /// <param name="src">Command text.</param>
        /// <param name="begin">Starting index within src.</param>
        /// <param name="length">Length of region to be processed.</param>
        /// <param name="prepare"></param>
        /// <param name="forExtendedQuery"></param>
        private void AppendCommandReplacingParameterValues(Stream dest, string src, int begin, int length, bool prepare, bool forExtendedQuery)
        {
            char lastChar = '\0';
            TokenType currTokenType = TokenType.None;
            char paramMarker = '\0';
            int currTokenBeg = begin;
            int currTokenLen = 0;
            Dictionary<NpgsqlParameter, int> paramOrdinalMap = null;

            if (prepare)
            {
                paramOrdinalMap = new Dictionary<NpgsqlParameter, int>();

                for (int i = 0 ; i < parameters.Count ; i++)
                {
                    paramOrdinalMap[parameters[i]] = i + 1;
                }
            }

            for (int currCharOfs = begin ; currCharOfs < begin + length ; currCharOfs++)
            {
                char ch = src[currCharOfs];

                // goto label for character re-evaluation:
                ProcessCharacter:

                switch (currTokenType)
                {
                    case TokenType.None :
                        switch (ch)
                        {
                            case '\'':
                                if (currTokenLen > 0)
                                {
                                    dest.WriteString(src.Substring(currTokenBeg, currTokenLen));
                                }

                                currTokenType = TokenType.Quoted;

                                currTokenBeg = currCharOfs;
                                currTokenLen = 1;

                                break;

                            case ':':
                                {
                                    dest.WriteString(src.Substring(currTokenBeg, currTokenLen));
                                }

                                currTokenType = TokenType.Colon;

                                currTokenBeg = currCharOfs;
                                currTokenLen = 1;

                                break;

                            case '@':
                                {
                                    dest.WriteString(src.Substring(currTokenBeg, currTokenLen));
                                }

                                currTokenType = TokenType.Param;

                                currTokenBeg = currCharOfs + 1;
                                currTokenLen = 0;
                                paramMarker = '@';

                                break;

                            default:
                                currTokenLen++;

                                break;

                        }

                        break;

                    case TokenType.Param :
                        if (IsParamNameChar(ch))
                        {
                            currTokenLen++;
                        }
                        else
                        {
                            if (currTokenLen == 0)
                            {
                                dest.WriteBytes((byte)ASCIIBytes.Colon);
                            }
                            else
                            {
                                string paramName = src.Substring(currTokenBeg, currTokenLen);
                                NpgsqlParameter parameter;
                                bool wroteParam = false;

                                if (parameters.TryGetValue(paramName, out parameter))
                                {
                                    if (
                                        (parameter.Direction == ParameterDirection.Input) ||
                                        (parameter.Direction == ParameterDirection.InputOutput)
                                    )
                                    {
                                        if (prepare)
                                        {
                                            AppendParameterPlaceHolder(dest, parameter, paramOrdinalMap[parameter]);
                                        }
                                        else
                                        {
                                            AppendParameterValue(dest, parameter);
                                        }
                                    }

                                    wroteParam = true;
                                }

                                if (! wroteParam)
                                {
                                    dest.WriteString("{0}{1}", paramMarker, paramName);
                                }
                            }

                            currTokenType = TokenType.None;
                            currTokenBeg = currCharOfs;
                            currTokenLen = 0;

                            // Re-evaluate this character
                            goto ProcessCharacter;
                        }

                        break;

                    case TokenType.Quoted :
                        switch (ch)
                        {
                            case '\'':
                                currTokenLen++;

                                break;

                            default:
                                if (currTokenLen > 1 && lastChar == '\'')
                                {
                                    dest.WriteString(src.Substring(currTokenBeg, currTokenLen));

                                    currTokenType = TokenType.None;
                                    currTokenBeg = currCharOfs;
                                    currTokenLen = 0;

                                    // Re-evaluate this character
                                    goto ProcessCharacter;
                                }
                                else
                                {
                                    currTokenLen++;
                                }

                                break;

                        }

                        break;

                    case TokenType.Colon :
                        switch (ch)
                        {
                            case ':':
                                currTokenLen++;

                                break;

                            default:
                                if (currTokenLen == 1)
                                {
                                    currTokenType = TokenType.Param;

                                    currTokenBeg = currCharOfs;
                                    currTokenLen = 0;
                                    paramMarker = ':';
                                }
                                else
                                {
                                    dest.WriteString(src.Substring(currTokenBeg, currTokenLen));

                                    currTokenType = TokenType.None;

                                    currTokenBeg = currCharOfs;
                                    currTokenLen = 0;
                                }

                                // Re-evaluate this character
                                goto ProcessCharacter;

                        }

                        break;

                }

                lastChar = ch;
            }

            switch (currTokenType)
            {
                case TokenType.Param :
                    if (currTokenLen == 0)
                    {
                        dest.WriteBytes((byte)ASCIIBytes.Colon);
                    }
                    else
                    {
                        string paramName = src.Substring(currTokenBeg, currTokenLen);
                        NpgsqlParameter parameter;
                        bool wroteParam = false;

                        if (parameters.TryGetValue(paramName, out parameter))
                        {
                            if (
                                (parameter.Direction == ParameterDirection.Input) ||
                                (parameter.Direction == ParameterDirection.InputOutput)
                            )
                            {
                                if (prepare)
                                {
                                    AppendParameterPlaceHolder(dest, parameter, paramOrdinalMap[parameter]);
                                }
                                else
                                {
                                    AppendParameterValue(dest, parameter);
                                }
                            }

                            wroteParam = true;
                        }

                        if (! wroteParam)
                        {
                            dest.WriteString("{0}{1}", paramMarker, paramName);
                        }
                    }

                    break;

                default :
                    if (currTokenLen > 0)
                    {
                        dest.WriteString(src.Substring(currTokenBeg, currTokenLen));
                    }

                    break;

            }
        }
        public void Serialize(Stream output)
        {
            var saveGame = this.SaveGame;

            byte[] innerUncompressedBytes;
            using (var innerUncompressedData = new MemoryStream())
            {
                saveGame.Compose();
                try
                {
                    ProtoBuf.Serializer.Serialize(innerUncompressedData, saveGame);
                }
                finally
                {
                    saveGame.Decompose();
                }
                innerUncompressedData.Position = 0;
                innerUncompressedBytes = innerUncompressedData.ReadBytes((uint)innerUncompressedData.Length);
            }

            byte[] innerCompressedBytes;
            using (var innerCompressedData = new MemoryStream())
            {
                var endian = this.Endian;

                innerCompressedData.WriteValueS32(0, Endian.Big);
                innerCompressedData.WriteString("WSG");
                innerCompressedData.WriteValueU32(2, endian);
                innerCompressedData.WriteValueU32(CRC32.Hash(innerUncompressedBytes, 0, innerUncompressedBytes.Length),
                                                  endian); // crc32
                innerCompressedData.WriteValueS32(innerUncompressedBytes.Length, endian);

                var encoder = new Huffman.Encoder();
                encoder.Build(innerUncompressedBytes);
                innerCompressedData.WriteBytes(encoder.Encode(innerUncompressedBytes));

                innerCompressedData.Position = 0;
                innerCompressedData.WriteValueU32((uint)(innerCompressedData.Length - 4), Endian.Big);

                innerCompressedData.Position = 0;
                innerCompressedBytes = innerCompressedData.ReadBytes((uint)innerCompressedData.Length);
            }

            byte[] compressedBytes;

            if (innerCompressedBytes.Length <= BlockSize)
            {
                compressedBytes = new byte[innerCompressedBytes.Length +
                                           (innerCompressedBytes.Length / 16) + 64 + 3];
                var actualCompressedSize = compressedBytes.Length;

                var result = LZO.Compress(innerCompressedBytes,
                                          0,
                                          innerCompressedBytes.Length,
                                          compressedBytes,
                                          0,
                                          ref actualCompressedSize);
                if (result != LZO.ErrorCode.Success)
                {
                    throw new SaveCorruptionException(string.Format("LZO compression failure ({0})", result));
                }

                Array.Resize(ref compressedBytes, actualCompressedSize);
            }
            else
            {
                int innerCompressedOffset = 0;
                int innerCompressedSizeLeft = innerCompressedBytes.Length;

                using (var blockData = new MemoryStream())
                {
                    var blockCount = (innerCompressedSizeLeft + BlockSize) / BlockSize;
                    blockData.WriteValueS32(blockCount, Endian.Big);

                    blockData.Position = 4 + (blockCount * 8);

                    var blockInfos = new List<Tuple<uint, uint>>();
                    while (innerCompressedSizeLeft > 0)
                    {
                        var blockUncompressedSize = Math.Min(BlockSize, innerCompressedSizeLeft);

                        compressedBytes = new byte[blockUncompressedSize +
                                                   (blockUncompressedSize / 16) + 64 + 3];
                        var actualCompressedSize = compressedBytes.Length;

                        var result = LZO.Compress(innerCompressedBytes,
                                                  innerCompressedOffset,
                                                  blockUncompressedSize,
                                                  compressedBytes,
                                                  0,
                                                  ref actualCompressedSize);
                        if (result != LZO.ErrorCode.Success)
                        {
                            throw new SaveCorruptionException(string.Format("LZO compression failure ({0})", result));
                        }

                        blockData.Write(compressedBytes, 0, actualCompressedSize);
                        blockInfos.Add(new Tuple<uint, uint>((uint)actualCompressedSize, BlockSize));

                        innerCompressedOffset += blockUncompressedSize;
                        innerCompressedSizeLeft -= blockUncompressedSize;
                    }

                    blockData.Position = 4;
                    foreach (var blockInfo in blockInfos)
                    {
                        blockData.WriteValueU32(blockInfo.Item1, Endian.Big);
                        blockData.WriteValueU32(blockInfo.Item2, Endian.Big);
                    }

                    blockData.Position = 0;
                    compressedBytes = blockData.ReadBytes((uint)blockData.Length);
                }
            }

            byte[] uncompressedBytes;
            using (var uncompressedData = new MemoryStream())
            {
                uncompressedData.WriteValueS32(innerCompressedBytes.Length, Endian.Big);
                uncompressedData.WriteBytes(compressedBytes);
                uncompressedData.Position = 0;
                uncompressedBytes = uncompressedData.ReadBytes((uint)uncompressedData.Length);
            }

            byte[] computedHash;
            using (var sha1 = new System.Security.Cryptography.SHA1Managed())
            {
                computedHash = sha1.ComputeHash(uncompressedBytes);
            }

            output.WriteBytes(computedHash);
            output.WriteBytes(uncompressedBytes);
        }
Example #19
0
        public override void WriteToStream(Stream outputStream)
        {
            NpgsqlEventLog.LogMethodEnter(LogLevel.Debug, CLASSNAME, "WriteToStream");

            switch (protocolVersion)
            {
                case ProtocolVersion.Version2:
                    // Write the size of the packet.
                    // 4 + (passwordlength + 1) -> Int32 + NULL terminated string.
                    // output_stream.Write(BitConverter.GetBytes(IPAddress.HostToNetworkOrder(4 + (password.Length + 1))), 0, 4);
                    outputStream
                        .WriteInt32(4 + password.Length + 1)
                        .WriteBytesNullTerminated(password);

                    break;

                case ProtocolVersion.Version3:
                    outputStream
                        .WriteBytes((Byte)ASCIIBytes.p)
                        .WriteInt32(4 + password.Length + 1)
                        .WriteBytesNullTerminated(password);

                    break;
            }
        }
Example #20
0
        public override void WriteToStream(Stream outputStream)
        {
            if (NpgsqlEventLog.Level >= LogLevel.Debug)
            {
                // Log the string being sent.
                // If (this) was constructed with a byte[], then commandText has to be
                // initialized before the first Log call.
                if (commandText == null)
                {
                    commandText = BackendEncoding.UTF8Encoding.GetString(commandBytes);
                    commandBytes = null;
                }

                PGUtil.LogStringWritten(commandText);
            }

            outputStream.WriteBytes(pgCommandBytes);
        }
Example #21
0
        private bool concatenateFragments(Stream dest)
        {
            Func<WsFrame, bool> processContinuation = contFrame =>
              {
            if (!contFrame.IsContinuation)
              return false;

            dest.WriteBytes (contFrame.PayloadData.ApplicationData);
            return true;
              };

              while (true)
              {
            var frame = _stream.ReadFrame ();
            if (processAbnormal (frame))
              return false;

            if (!frame.IsFinal)
            {
              // MORE & CONT
              if (processContinuation (frame))
            continue;
            }
            else
            {
              // FINAL & CONT
              if (processContinuation (frame))
            break;

              // FINAL & PING
              if (processPing (frame))
            continue;

              // FINAL & PONG
              if (processPong (frame))
            continue;

              // FINAL & CLOSE
              if (processClose (frame))
            return false;
            }

            // ?
            processIncorrectFrame ();
            return false;
              }

              return true;
        }
Example #22
0
 public override void WriteToStream(Stream outputStream)
 {
     outputStream
         .WriteBytes(_messageData)
         .Flush();
 }
Example #23
0
 public override void Pack(Stream stream)
 {
     stream.WriteBytes(Encoding.ASCII.GetBytes(Reason));
 }
        private void AppendParameterPlaceHolder(Stream dest, NpgsqlParameter parameter, int paramNumber)
        {
            string parameterSize = "";

            dest.WriteBytes((byte)ASCIIBytes.ParenLeft);

            if (parameter.TypeInfo.UseSize && (parameter.Size > 0))
            {
                parameterSize = string.Format("({0})", parameter.Size);
            }

            if (parameter.UseCast)
            {
                dest.WriteString("${0}::{1}{2}", paramNumber, parameter.TypeInfo.CastName, parameterSize);
            }
            else
            {
                dest.WriteString("${0}{1}", paramNumber, parameterSize);
            }

            dest.WriteBytes((byte)ASCIIBytes.ParenRight);
        }
Example #25
0
 public override void Pack(Stream stream)
 {
     stream.WriteInt32(Time);
     stream.WriteBoolean(DayTime);
     stream.WriteInt8(MoonPhase);
     stream.WriteBoolean(BloodMoon);
     stream.WriteInt32(MaxTilesX);
     stream.WriteInt32(MaxTilesY);
     stream.WriteInt32(SpawnX);
     stream.WriteInt32(SpawnY);
     stream.WriteInt32(WorldSurface);
     stream.WriteInt32(RockLayer);
     stream.WriteInt32(WorldID);
     stream.WriteInt8((byte) WorldFlags);
     stream.WriteBytes(Encoding.UTF8.GetBytes(WorldName));
 }
Example #26
0
        private bool concatenateFragmentsInto(Stream dest)
        {
            while (true) {
            var frame = _stream.ReadFrame ();

            if (frame.IsFinal) {
              // FINAL

              // CONT
              if (frame.IsContinuation) {
            dest.WriteBytes (frame.PayloadData.ApplicationData);
            break;
              }

              // PING
              if (frame.IsPing) {
            acceptPingFrame (frame);
            continue;
              }

              // PONG
              if (frame.IsPong) {
            acceptPongFrame (frame);
            continue;
              }

              // CLOSE
              if (frame.IsClose)
            return acceptCloseFrame (frame);
            }
            else {
              // MORE

              // CONT
              if (frame.IsContinuation) {
            dest.WriteBytes (frame.PayloadData.ApplicationData);
            continue;
              }
            }

            // ?
            return acceptUnsupportedFrame (
              frame,
              CloseStatusCode.IncorrectData,
              "An incorrect data has been received while receiving fragmented data.");
              }

              return true;
        }
Example #27
0
        public override void WriteToStream(Stream outputStream)
        {
            if (_messageLength == 0)
            {
                _messageLength =
                    4 + // Message length (32 bits)
                    _bPortalName.Length + 1 + // Portal name + null terminator
                    _bPreparedStatementName.Length + 1 + // Statement name + null terminator
                    2 + // Parameter format code array length (16 bits)
                    _parameterFormatCodes.Length * 2 + // Parameter format code array (16 bits per code)
                    2; // Parameter va;ue array length (16 bits)

                if (_parameterValues != null)
                {
                    for (int i = 0; i < _parameterValues.Length; i++)
                    {
                        _messageLength += 4; // Parameter value length (32 bits)

                        if (_parameterValues[i] != null)
                        {
                            _messageLength += _parameterValues[i].Length; // Parameter value
                        }
                    }
                }

                _messageLength +=
                    2 + // Result format code array length (16 bits)
                    _resultFormatCodes.Length * 2; // Result format code array (16 bits per code)
            }

            outputStream
                .WriteBytes((byte)FrontEndMessageCode.Bind)
                .WriteInt32(_messageLength)
                .WriteBytesNullTerminated(_bPortalName)
                .WriteBytesNullTerminated(_bPreparedStatementName)
                .WriteInt16((Int16)_parameterFormatCodes.Length);

            foreach (short code in _parameterFormatCodes)
            {
                outputStream.WriteInt16(code);
            }

            if (_parameterValues != null)
            {
                outputStream.WriteInt16((Int16)_parameterValues.Length);

                for (int i = 0 ; i < _parameterValues.Length ; i++)
                {
                    Byte[] parameterValue = _parameterValues[i];

                    if (parameterValue == null)
                    {
                        outputStream.WriteInt32(-1);
                    }
                    else
                    {
                        outputStream
                            .WriteInt32(parameterValue.Length)
                            .WriteBytes(parameterValue);
                    }
                }
            }
            else
            {
                outputStream.WriteInt16(0);
            }

            outputStream.WriteInt16((Int16)_resultFormatCodes.Length);

            foreach (short code in  _resultFormatCodes)
            {
                outputStream.WriteInt16(code);
            }
        }
Example #28
0
        private bool concatenateFragmentsInto(Stream dest)
        {
            while (true)
              {
            var frame = _stream.ReadFrame ();

            // MORE & CONT
            if (!frame.IsFinal && frame.IsContinuation)
            {
              dest.WriteBytes (frame.PayloadData.ApplicationData);
              continue;
            }

            // FINAL & CONT
            if (frame.IsFinal && frame.IsContinuation)
            {
              dest.WriteBytes (frame.PayloadData.ApplicationData);
              break;
            }

            // FINAL & PING
            if (frame.IsFinal && frame.IsPing)
            {
              processPingFrame (frame);
              continue;
            }

            // FINAL & PONG
            if (frame.IsFinal && frame.IsPong)
            {
              processPongFrame ();
              continue;
            }

            // FINAL & CLOSE
            if (frame.IsFinal && frame.IsClose)
              return processCloseFrame (frame);

            // ?
            return processUnsupportedFrame (frame, CloseStatusCode.INCORRECT_DATA, null);
              }

              return true;
        }
Example #29
0
 public void Pack(Stream stream)
 {
     stream.WriteInt8(Field6);
     stream.WriteInt16(Field7);
     stream.WriteInt32(Field8);
     stream.WriteBytes(Field9);
     stream.WriteString(Field10);
 }