Ejemplo n.º 1
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="a_stream"></param>
        /// <returns></returns>
        /// <remarks>Use this function only for VNC Version 3.7 or later.</remarks>
        public static HashSet <VncEnum.SecurityType> ReadSecurityTypes(Stream a_stream)
        {
            // Read number-of-security-types
            byte[] buffer = new byte[1];
            a_stream.ReadAll(buffer, 0, buffer.Length);
            int numberOfSecurityTypes = buffer[0];

            if (numberOfSecurityTypes == 0)
            {
                string str = readReasonString(a_stream);
                throw new SecurityException($"Number-of-security-types is zero. {str}");
            }

            // Read security-types
            byte[] securityTypesBuffer = new byte[numberOfSecurityTypes];
            a_stream.ReadAll(securityTypesBuffer, 0, numberOfSecurityTypes);

            // Create return value
            var securityTypes = new HashSet <VncEnum.SecurityType>();

            for (int i = 0; i < numberOfSecurityTypes; ++i)
            {
                securityTypes.Add((VncEnum.SecurityType)securityTypesBuffer[i]);
            }

            return(securityTypes);
        }
Ejemplo n.º 2
0
        private static string readReasonString(Stream a_stream)
        {
            byte[] reasonLength = new byte[4];
            a_stream.ReadAll(reasonLength, 0, reasonLength.Length);
            UInt32 len = BigEndianBitConverter.ToUInt32(reasonLength, 0);

            byte[] reasonString = new byte[len];
            a_stream.ReadAll(reasonString, 0, (int)len);
            string str = Encoding.ASCII.GetString(reasonString);

            return(str);
        }
Ejemplo n.º 3
0
        public void TrieConstructorTest()
        {
            Trie <TrieElement> trie = new Trie <TrieElement>();

            Stream stream = Assembly.GetExecutingAssembly().GetManifestResourceStream("VLUnitTests.Resources.TrieTest.txt");
            string text   = stream.ReadAll(); // read all data from testing file

            // add "references" that will be searched
            trie.Add("id.aliquam.lorem");
            trie.Add("a.b.c.d");
            trie.Add("x.y");
            trie.Add("eeee.eeee");

            // complete building the trie
            trie.CreatePredecessorsAndShortcuts();

            TrieElement   e          = trie.Root;
            List <string> foundWords = new List <string>();

            // create list of expeced results
            List <string> expectedWords = new List <string>();

            expectedWords.Add("id.aliquam.lorem");
            expectedWords.Add("id.aliquam.lorem");
            expectedWords.Add("eeee.eeee");
            expectedWords.Add("id.aliquam.lorem");
            expectedWords.Add("eeee.eeee");
            expectedWords.Add("eeee.eeee");
            expectedWords.Add("eeee.eeee");
            expectedWords.Add("a.b.c.d");
            expectedWords.Add("a.b.c.d");
            expectedWords.Add("a.b.c.d");
            expectedWords.Add("a.b.c.d");
            expectedWords.Add("a.b.c.d");

            // run the algorithm
            foreach (char c in text)
            {
                e = trie.Step(e, c);
                if (e.IsTerminal)
                {
                    foundWords.Add(e.Word);
                }
            }

            // compare with expected
            if (foundWords.Count == expectedWords.Count)
            {
                bool ok = true;
                for (int i = 0; i < foundWords.Count; i++)
                {
                    ok = ok && foundWords[i] == expectedWords[i];
                }
                Assert.IsTrue(ok);
            }
            else
            {
                Assert.Fail("Found and expected words count don't match.");
            }
        }
Ejemplo n.º 4
0
        // Struct
        public static T ReadStruct <T>(this Stream s)
        {
            byte[] bytes = new byte[BinaryUtils.StructSize <T>()];
            s.ReadAll(bytes, 0, bytes.Length);

            return(BinaryUtils.StructFromBytes <T>(bytes));
        }
Ejemplo n.º 5
0
        private void CalculatePdbChecksumAndId(Stream pdbStream, out byte [] pdbChecksum, out byte [] pdbId)
        {
            // Get the offset of the PDB heap (this requires parsing several headers
            // so it's easier to use the ImageReader directly for this)
            Image image = ImageReader.ReadPortablePdb(new Disposable <Stream> (pdbStream, false), "test.pdb", out uint pdbHeapOffset);

            pdbId = new byte [20];
            Array.Copy(image.PdbHeap.data, 0, pdbId, 0, 20);

            pdbStream.Seek(0, SeekOrigin.Begin);
            byte [] rawBytes = pdbStream.ReadAll();

            var bytes = new byte [rawBytes.Length];

            Array.Copy(rawBytes, 0, bytes, 0, pdbHeapOffset);

            // Zero out the PDB ID (20 bytes)
            for (int i = 0; i < 20; bytes [i + pdbHeapOffset] = 0, i++)
            {
                ;
            }

            Array.Copy(rawBytes, pdbHeapOffset + 20, bytes, pdbHeapOffset + 20, rawBytes.Length - pdbHeapOffset - 20);

            var sha256 = SHA256.Create();

            pdbChecksum = sha256.ComputeHash(bytes);
        }
Ejemplo n.º 6
0
        public static byte[] ReadDataBlocks(Stream stream, bool discard)
        {
            byte[]       buffer2;
            MemoryStream stream2 = discard ? null : new MemoryStream();

            using (stream2)
            {
                while (true)
                {
                    int count = stream.ReadByte();
                    if (count <= 0)
                    {
                        buffer2 = stream2?.ToArray();
                        break;
                    }
                    byte[] buffer = new byte[count];
                    stream.ReadAll(buffer, 0, count);
                    if (stream2 != null)
                    {
                        stream2.Write(buffer, 0, count);
                    }
                }
            }
            return(buffer2);
        }
Ejemplo n.º 7
0
        public static byte[] ReadDataBlocks(Stream stream, bool discard)
        {
            MemoryStream ms = discard ? null : new MemoryStream();

            using (ms)
            {
                int len;

                while ((len = stream.ReadByte()) > 0)
                {
                    byte[] bytes = new byte[len];
                    stream.ReadAll(bytes, 0, len);

                    if (ms != null)
                    {
                        ms.Write(bytes, 0, len);
                    }
                }

                if (ms != null)
                {
                    return(ms.ToArray());
                }

                return(null);
            }
        }
Ejemplo n.º 8
0
        private void PlaySound(Stream sound)
        {
            DirectSound ds = new DirectSound();

            ds.SetCooperativeLevel(this.Handle, CooperativeLevel.Priority);


            WaveFormat format = WaveFormat.CreateCustomFormat(
                WaveFormatEncoding.Pcm,
                44100,
                2,
                4 * 44100,
                4,
                16
                );

            SoundBufferDescription primaryDesc = new SoundBufferDescription();

            primaryDesc.Format      = format;
            primaryDesc.Flags       = BufferFlags.GlobalFocus;
            primaryDesc.BufferBytes = 8 * 4 * 44100;
            PrimarySoundBuffer pBuffer = new PrimarySoundBuffer(ds, primaryDesc);

            SoundBufferDescription secondDesc = new SoundBufferDescription();

            secondDesc.Format      = format;
            secondDesc.Flags       = BufferFlags.GlobalFocus | BufferFlags.ControlPositionNotify | BufferFlags.GetCurrentPosition2;
            secondDesc.BufferBytes = 8 * 4 * 44100;

            SecondarySoundBuffer secondBuffer = new SecondarySoundBuffer(ds, secondDesc);

            secondBuffer.Write(sound.ReadAll(), 0, LockFlags.None);
            secondBuffer.Play(0, PlayFlags.None);
        }
Ejemplo n.º 9
0
        void ProcessAsyncResponse(IAsyncResult asyncRes)
        {
            lock (Lock)
            {
                var webRequest = asyncRes.AsyncState as HttpWebRequest;

                string status;
                try
                {
                    using (var response = webRequest.EndGetResponse(asyncRes))
                        using (Stream stream = response.GetResponseStream())
                            status = stream.ReadAll();
                }
                catch (WebException ex)
                {
                    Console.WriteLine("Web Exception: " + ex);
                    return;
                }

                try
                {
                    ProcessResponse(status);
                }
                catch (Exception ex)
                {
                    Console.WriteLine("Processing Exception: " + ex);
                    return;
                }
            }
        }
Ejemplo n.º 10
0
        internal static byte[] ReadKeyfile(Stream stream)
        {
            var bytes = stream.ReadAll();

            // If the file parses as XML and has the valid structure, then it's an XML keyfile.
            if (ReadXmlKeyfile(bytes) is {} xmlKeyfile)
            {
                return(xmlKeyfile);
            }

            // Legacy binary precomputed hash key file
            if (bytes.Length == 32)
            {
                return(bytes);
            }

            // Legacy hexadecimal precomputed hash key file
            if (bytes.Length == 64)
            {
                var text = bytes.ToUtf8();
                if (text.IsHex())
                {
                    return(text.DecodeHex());
                }
            }

            // Otherwise it's a generic binary key file which needs to be hashed
            return(Crypto.Sha256(bytes));
        }
Ejemplo n.º 11
0
        public T Deserialize(Stream source)
        {
            var all = source.ReadAll();

            Array.Reverse(all);
            return(inner.deserialize(all));
        }
Ejemplo n.º 12
0
        void ProcessInventory(IAsyncResult res)
        {
            var webRequest = res.AsyncState as HttpWebRequest;

            string status;

            try
            {
                using (var response = webRequest.EndGetResponse(res))
                    using (Stream stream = response.GetResponseStream())
                        status = stream.ReadAll();
            }
            catch (WebException ex)
            {
                Console.WriteLine("Web Exception: " + ex);
                return;
            }

            var data = new JsonReader().Read(status) as IDictionary <string, object>;

            var success = data["success"] as bool?;

            if (success.HasValue && success.Value == false)
            {
                return;
            }

            Inventory = new Inventory();
            Inventory.TryParse(data);

            var @event = new TradeEvent();

            @event.type = ETradeEventType.InventoryLoaded;
            Events.Enqueue(@event);
        }
Ejemplo n.º 13
0
        static public void CreateCompression15File(Stream InputStream, Stream OutputStream, int FallbackCompression = 15)
        {
            var TempFile = Path.GetTempFileName();

            File.WriteAllBytes(TempFile, InputStream.ReadAll());
            CreateCompression15File(TempFile, OutputStream, FallbackCompression);
        }
Ejemplo n.º 14
0
        /// <inheritdoc />
        public void ReadMessage(ITransport transport, CancellationToken cancellationToken = default)
        {
            if (transport == null)
            {
                throw new ArgumentNullException(nameof(transport));
            }

            cancellationToken.ThrowIfCancellationRequested();

            // Did we just learn that the server supports fences?
            if (!_state.ServerSupportsFences)
            {
                _logger.LogDebug("Server supports the fences extension.");

                // Mark the encoding and message type as used
                _state.EnsureEncodingTypeIsMarkedAsUsed <IPseudoEncodingType>(null, (int)WellKnownEncodingType.Fence);
                _state.EnsureMessageTypeIsMarkedAsUsed <IOutgoingMessageType>(null, (byte)WellKnownOutgoingMessageType.ClientFence);

                _state.ServerSupportsFences = true;
            }

            Stream transportStream = transport.Stream;

            // Read 8 header bytes (first 3 bytes are padding)
            Span <byte> header = stackalloc byte[8];

            transportStream.ReadAll(header, cancellationToken);
            var  flags         = (FenceFlags)BinaryPrimitives.ReadUInt32BigEndian(header[3..]);
Ejemplo n.º 15
0
        /// <summary>
        /// Reads the content.
        /// </summary>
        /// <param name="stream">The stream.</param>
        /// <returns></returns>
        public byte[] ReadContent(Stream stream)
        {
            int?           contentLength = null;
            IList <string> literalContentLength;

            if (Headers.TryGetValue("Content-Length", out literalContentLength))
            {
                int fContentLength;
                if (int.TryParse(literalContentLength.First(), out fContentLength))
                {
                    contentLength = fContentLength;
                }
            }

            if (!contentLength.HasValue)
            {
                using (var memoryStream = new MemoryStream())
                {
                    stream.CopyTo(memoryStream);
                    return(memoryStream.ToArray());
                }
            }

            var contentBytes = new byte[contentLength.Value];

            stream.ReadAll(contentBytes, 0, contentBytes.Length);
            return(contentBytes);
        }
Ejemplo n.º 16
0
        public static VncEnum.Version ReadProtocolVersion(Stream a_stream, VncEnum.Version a_forceVersion)
        {
            byte[] buffer = new byte[12];
            a_stream.ReadAll(buffer, 0, buffer.Length);
            if (buffer.SequenceEqual(Encoding.ASCII.GetBytes("RFB 003.003\n")) ||
                buffer.SequenceEqual(Encoding.ASCII.GetBytes("RFB 003.005\n")))
            {
                return(VncEnum.Version.Version33);
            }
            else if (buffer.SequenceEqual(Encoding.ASCII.GetBytes("RFB 003.007\n")))
            {
                return(VncEnum.Version.Version37);
            }
            else if (buffer.SequenceEqual(Encoding.ASCII.GetBytes("RFB 003.008\n")))
            {
                return(VncEnum.Version.Version38);
            }

            // In rare cases, it may be a strange response, so if a_forceVersion is not Invalid, it is permitted if the beginning matches.
            if (a_forceVersion != VncEnum.Version.None)
            {
                if (Encoding.ASCII.GetString(buffer).Contains("RFB 003"))
                {
                    return(a_forceVersion);
                }
            }

            throw new InvalidDataException($"Unknown version. Length = {buffer.Length} Text = [{Encoding.ASCII.GetString(buffer)}]");
        }
Ejemplo n.º 17
0
        public static string ReadString(Stream stream, int length)
        {
            var bytes = new byte[length];

            stream.ReadAll(bytes, 0, length);
            return(Encoding.ASCII.GetString(bytes));
        }
Ejemplo n.º 18
0
 public byte[] ReadBytes()
 {
     using (Stream stream = Open())
     {
         return(stream.ReadAll());
     }
 }
Ejemplo n.º 19
0
        public static byte[] ReadVncChallange(Stream a_stream)
        {
            byte[] buffer = new byte[16];
            a_stream.ReadAll(buffer, 0, buffer.Length);

            return(buffer);
        }
Ejemplo n.º 20
0
        /// <summary>
        /// Reads the specified stream.
        /// </summary>
        /// <param name="stream">The stream.</param>
        /// <returns>The file</returns>
        public override IGenericFile Read(Stream stream)
        {
            if (stream is null)
            {
                return(new GenericFile("", "", ""));
            }
            try
            {
                var Content = stream.ReadAll();
                var doc     = new HtmlAgilityPack.HtmlDocument();
                doc.LoadHtml(Content);
                var Title = doc.DocumentNode.SelectSingleNode("//head//title")?.InnerText ?? string.Empty;
                var Meta  = new Regex(@"<meta\s*name=[""']description[""']\s*content=[""'](?<Content>[^""']*)[""']\s*/>", RegexOptions.IgnoreCase).Match(Content).Groups["Content"].Value;
                Meta += new Regex(@"<meta\s*name=[""']keywords[""']\s*content=[""'](?<Content>[^""']*)[""']\s*/>", RegexOptions.IgnoreCase).Match(Content).Groups["Content"].Value;
                doc.DocumentNode.SelectSingleNode("//body")
                .Descendants("style")
                .ToList()
                .ForEach(x => x.Remove());

                doc.DocumentNode.SelectSingleNode("//body")
                .Descendants("script")
                .ToList()
                .ForEach(x => x.Remove());
                Content = doc.DocumentNode.SelectSingleNode("//body").InnerHtml;
                Content = StripHTML(Content);
                Content = Content.Replace("&amp;", "&").Replace("&rsquo;", "'");
                var RemoveSpaces = new Regex(@"\s+", RegexOptions.None);
                return(new GenericFile(RemoveSpaces.Replace(Content, " ").Trim(), Title, Meta));
            }
            catch
            {
                return(new GenericFile("", "", ""));
            }
        }
Ejemplo n.º 21
0
    private void Read(Stream stream, IEnumerable <GifExtension> controlExtensions, bool metadataOnly)
    {
        //Note: at this point, the label (0x01) has already been read
        var bytes = new byte[13];

        stream.ReadAll(bytes, 0, bytes.Length);

        BlockSize = bytes[0];

        if (BlockSize != 12)
        {
            throw GifHelpers.InvalidBlockSizeException("Plain Text Extension", 12, BlockSize);
        }

        Left                 = BitConverter.ToUInt16(bytes, 1);
        Top                  = BitConverter.ToUInt16(bytes, 3);
        Width                = BitConverter.ToUInt16(bytes, 5);
        Height               = BitConverter.ToUInt16(bytes, 7);
        CellWidth            = bytes[9];
        CellHeight           = bytes[10];
        ForegroundColorIndex = bytes[11];
        BackgroundColorIndex = bytes[12];

        var dataBytes = GifHelpers.ReadDataBlocks(stream, metadataOnly);

        Text       = Encoding.ASCII.GetString(dataBytes);
        Extensions = controlExtensions.ToList().AsReadOnly();
    }
Ejemplo n.º 22
0
 internal ExperimentalPacket(
     PacketTag tag,
     Stream bcpgIn)
 {
     this.tag      = tag;
     this.contents = bcpgIn.ReadAll();
 }
Ejemplo n.º 23
0
    /// <summary>
    /// Adds a Base64 signature to a feed or catalog stream.
    /// </summary>
    /// <param name="stream">The feed or catalog to sign.</param>
    /// <param name="secretKey">The secret key to use for signing the file.</param>
    /// <param name="passphrase">The passphrase to use to unlock the key.</param>
    /// <param name="openPgp">The OpenPGP-compatible system used to create signatures.</param>
    /// <exception cref="IOException">The file could not be read or written.</exception>
    /// <exception cref="UnauthorizedAccessException">Read or write access to the file is not permitted.</exception>
    /// <exception cref="KeyNotFoundException">The specified <paramref name="secretKey"/> could not be found on the system.</exception>
    /// <exception cref="WrongPassphraseException"><paramref name="passphrase"/> was incorrect.</exception>
    /// <remarks>
    /// The file is not parsed before signing; invalid XML files are signed as well.
    /// The existing file must end with a line break.
    /// Old signatures are not removed.
    /// </remarks>
    public static void SignFeed(Stream stream, OpenPgpSecretKey secretKey, string?passphrase, IOpenPgp openPgp)
    {
        #region Sanity checks
        if (stream == null)
        {
            throw new ArgumentNullException(nameof(stream));
        }
        if (secretKey == null)
        {
            throw new ArgumentNullException(nameof(secretKey));
        }
        if (openPgp == null)
        {
            throw new ArgumentNullException(nameof(openPgp));
        }
        #endregion

        // Calculate the signature in-memory
        var signature = openPgp.Sign(stream.ReadAll(), secretKey, passphrase);

        // Add the signature to the end of the file
        var writer = new StreamWriter(stream, EncodingUtils.Utf8)
        {
            NewLine = "\n"
        };
        writer.Write(StoreFeedUtils.SignatureBlockStart);
        writer.WriteLine(Convert.ToBase64String(signature));
        writer.Write(StoreFeedUtils.SignatureBlockEnd);
        writer.Flush();
    }
Ejemplo n.º 24
0
        //todo 修改为不抛出异常,失败时返回null

        public T Deserialize <T>(Stream stream)
        {
            JavaScriptSerializer serializer = new JavaScriptSerializer();
            T obj = serializer.Deserialize <T>(stream.ReadAll().ToString());

            return(obj);
        }
Ejemplo n.º 25
0
 static public String ReadAllContentsAsString(this Stream Stream, Encoding Encoding = null, bool FromStart = true)
 {
     if (Encoding == null)
     {
         Encoding = Encoding.UTF8;
     }
     return(Encoding.GetString(Stream.ReadAll(FromStart)));
 }
Ejemplo n.º 26
0
 public override int Read(byte[] buffer, int offset, int count)
 {
     if (!CanRead)
     {
         throw new InvalidOperationException();
     }
     return(_pipeStream.ReadAll(buffer, offset, count));
 }
Ejemplo n.º 27
0
 /// <summary>
 /// Gets the content.
 /// </summary>
 /// <param name="stream">The stream.</param>
 /// <returns>The content in the stream.</returns>
 private static string GetContent(Stream stream)
 {
     try
     {
         return(stream.ReadAll());
     }
     catch { return(""); }
 }
Ejemplo n.º 28
0
        public static object ReadReference(Stream stream)
        {
            Span <byte> reference = stackalloc byte[(int)stream.Length];

            stream.ReadAll(reference);

            return(ReadReference(reference));
        }
Ejemplo n.º 29
0
        private static List <byte[]> readServerCutText(Stream a_stream)
        {
            var readDataList = new List <byte[]>();

            // Read padding(3) - length(4)
            byte[] head = new byte[7];
            a_stream.ReadAll(head, 0, head.Length);
            readDataList.Add(head);

            UInt16 length = BigEndianBitConverter.ToUInt16(head, 3);

            // Read text(length)
            byte[] textBuffer = new byte[length];
            a_stream.ReadAll(textBuffer, 0, textBuffer.Length);
            readDataList.Add(textBuffer);

            return(readDataList);
        }
Ejemplo n.º 30
0
        public static VncServerInitBody ReadServerInit(Stream a_stream)
        {
            // Read head for name-length
            byte[] buffer = new byte[24];
            a_stream.ReadAll(buffer, 0, buffer.Length);

            int len = (int)BigEndianBitConverter.ToUInt32(buffer, 20);

            // Read name-string
            byte[] str = new byte[len];
            a_stream.ReadAll(str, 0, len);

            // Create VncServerInitBody
            Array.Resize(ref buffer, 24 + len);
            Array.Copy(str, 0, buffer, 24, len);

            return(new VncServerInitBody(buffer));
        }
        public void LoadFromStream(Stream stream)
        {
            int lengthToFill = (int)(stream.Length - stream.Position);

            while (m_buffer.Data.Length < lengthToFill)
               m_buffer.Grow();

            m_buffer.Position = 0;
            m_length = lengthToFill;
            stream.ReadAll(m_buffer.Data, 0, lengthToFill);

            Reset();
        }
Ejemplo n.º 32
0
 private void Read(Stream stream)
 {
     byte[] bytes = new byte[9];
     stream.ReadAll(bytes, 0, bytes.Length);
     Left = BitConverter.ToUInt16(bytes, 0);
     Top = BitConverter.ToUInt16(bytes, 2);
     Width = BitConverter.ToUInt16(bytes, 4);
     Height = BitConverter.ToUInt16(bytes, 6);
     byte packedFields = bytes[8];
     HasLocalColorTable = (packedFields & 0x80) != 0;
     Interlace = (packedFields & 0x40) != 0;
     IsLocalColorTableSorted = (packedFields & 0x20) != 0;
     LocalColorTableSize = 1 << ((packedFields & 0x07) + 1);
 }
Ejemplo n.º 33
0
 public static GifColor[] ReadColorTable(Stream stream, int size)
 {
     int length = 3 * size;
     byte[] bytes = new byte[length];
     stream.ReadAll(bytes, 0, length);
     GifColor[] colorTable = new GifColor[size];
     for (int i = 0; i < size; i++)
     {
         byte r = bytes[3 * i];
         byte g = bytes[3 * i + 1];
         byte b = bytes[3 * i + 2];
         colorTable[i] = new GifColor(r, g, b);
     }
     return colorTable;
 }
Ejemplo n.º 34
0
 public static GifColor[] ReadColorTable(Stream stream, int size)
 {
     var length = 3*size;
     var bytes = new byte[length];
     stream.ReadAll(bytes, 0, length);
     var colorTable = new GifColor[size];
     for (var i = 0; i < size; i++)
     {
         var r = bytes[3*i];
         var g = bytes[3*i + 1];
         var b = bytes[3*i + 2];
         colorTable[i] = new GifColor(r, g, b);
     }
     return colorTable;
 }
        private void Read(Stream stream)
        {
            // Note: at this point, the label (0xFF) has already been read

            byte[] bytes = new byte[12];
            stream.ReadAll(bytes, 0, bytes.Length);
            BlockSize = bytes[0]; // should always be 11
            if (BlockSize != 11)
                throw GifHelpers.InvalidBlockSizeException("Application Extension", 11, BlockSize);

            ApplicationIdentifier = Encoding.ASCII.GetString(bytes, 1, 8);
            byte[] authCode = new byte[3];
            Array.Copy(bytes, 9, authCode, 0, 3);
            AuthenticationCode = authCode;
            Data = GifHelpers.ReadDataBlocks(stream, false);
        }
        private void Read(Stream stream)
        {
            // Note: at this point, the label (0xF9) has already been read

            byte[] bytes = new byte[6];
            stream.ReadAll(bytes, 0, bytes.Length);
            BlockSize = bytes[0]; // should always be 4
            if (BlockSize != 4)
                throw GifHelpers.InvalidBlockSizeException("Graphic Control Extension", 4, BlockSize);
            byte packedFields = bytes[1];
            DisposalMethod = (packedFields & 0x1C) >> 2;
            UserInput = (packedFields & 0x02) != 0;
            HasTransparency = (packedFields & 0x01) != 0;
            Delay = BitConverter.ToUInt16(bytes, 2) * 10; // milliseconds
            TransparencyIndex = bytes[4];
        }
Ejemplo n.º 37
0
        public virtual void Load(Stream FileStream)
        {
            FileStream = new MemoryStream(FileStream.ReadAll());

            this.FileStream = FileStream;

            this.Header = FileStream.ReadStruct<Elf.HeaderStruct>();
            if (this.Header.Magic != Elf.HeaderStruct.MagicEnum.ExpectedValue)
            {
                throw(new InvalidProgramException("Not an ELF File"));
            }

            if (this.Header.Machine != Elf.HeaderStruct.MachineEnum.ALLEGREX)
            {
                throw (new InvalidProgramException("Invalid Elf.Header.Machine"));
            }

            this.ProgramHeaders = FileStream.ReadStructVectorAt<Elf.ProgramHeader>(Header.ProgramHeaderOffset, Header.ProgramHeaderCount, Header.ProgramHeaderEntrySize);
            this.SectionHeaders = FileStream.ReadStructVectorAt<Elf.SectionHeader>(Header.SectionHeaderOffset, Header.SectionHeaderCount, Header.SectionHeaderEntrySize);

            this.NamesSectionHeader = this.SectionHeaders[Header.SectionHeaderStringTable];
            this.StringTable = FileStream.SliceWithLength(this.NamesSectionHeader.Offset, this.NamesSectionHeader.Size).ReadAll();

            this.SectionHeadersByName = new Dictionary<string, Elf.SectionHeader>();
            foreach (var SectionHeader in this.SectionHeaders)
            {
                var SectionHeaderName = GetStringFromStringTable(SectionHeader.Name);
                this.SectionHeadersByName[SectionHeaderName] = SectionHeader;
            }

            Console.WriteLine("ProgramHeaders:{0}", this.ProgramHeaders.Length);
            foreach (var ProgramHeader in ProgramHeaders)
            {
                Console.WriteLine("{0}", ProgramHeader.ToStringDefault());
            }

            Console.WriteLine("SectionHeaders:{0}", this.SectionHeaders.Length);
            foreach (var SectionHeader in SectionHeaders)
            {
                Console.WriteLine("{0}:{1}", GetStringFromStringTable(SectionHeader.Name), SectionHeader.ToStringDefault());
            }

            if (NeedsRelocation && this.ProgramHeaders.Length > 1)
            {
                //throw (new NotImplementedException("Not implemented several ProgramHeaders yet using relocation"));
            }
        }
Ejemplo n.º 38
0
 public static byte[] ReadDataBlocks(Stream stream, bool discard)
 {
     MemoryStream ms = discard ? null : new MemoryStream();
     using (ms)
     {
         int len;
         while ((len = stream.ReadByte()) > 0)
         {
             byte[] bytes = new byte[len];
             stream.ReadAll(bytes, 0, len);
             if (ms != null)
                 ms.Write(bytes, 0, len);
         }
         if (ms != null)
             return ms.ToArray();
         return null;
     }
 }
        private void Read(Stream stream)
        {
            byte[] bytes = new byte[7];
            stream.ReadAll(bytes, 0, bytes.Length);

            Width = BitConverter.ToUInt16(bytes, 0);
            Height = BitConverter.ToUInt16(bytes, 2);
            byte packedFields = bytes[4];
            HasGlobalColorTable = (packedFields & 0x80) != 0;
            ColorResolution = ((packedFields & 0x70) >> 4) + 1;
            IsGlobalColorTableSorted = (packedFields & 0x08) != 0;
            GlobalColorTableSize = 1 << ((packedFields & 0x07) + 1);
            BackgroundColorIndex = bytes[5];
            PixelAspectRatio =
                bytes[5] == 0
                    ? 0.0
                    : (15 + bytes[5]) / 64.0;
        }
        private void Read(Stream stream, IEnumerable<GifExtension> controlExtensions, bool metadataOnly)
        {
            // Note: at this point, the label (0x01) has already been read

            byte[] bytes = new byte[13];
            stream.ReadAll(bytes,0, bytes.Length);

            BlockSize = bytes[0];
            if (BlockSize != 12)
                throw GifHelpers.InvalidBlockSizeException("Plain Text Extension", 12, BlockSize);

            Left = BitConverter.ToUInt16(bytes, 1);
            Top = BitConverter.ToUInt16(bytes, 3);
            Width = BitConverter.ToUInt16(bytes, 5);
            Height = BitConverter.ToUInt16(bytes, 7);
            CellWidth = bytes[9];
            CellHeight = bytes[10];
            ForegroundColorIndex = bytes[11];
            BackgroundColorIndex = bytes[12];

            var dataBytes = GifHelpers.ReadDataBlocks(stream, metadataOnly);
            Text = Encoding.ASCII.GetString(dataBytes);
            Extensions = controlExtensions.ToList().AsReadOnly();
        }
Ejemplo n.º 41
0
        /// <summary>
        /// Reads the content.
        /// </summary>
        /// <param name="stream">The stream.</param>
        /// <returns></returns>
        public byte[] ReadContent(Stream stream)
        {
            int? contentLength = null;
            IList<string> literalContentLength;
            if (Headers.TryGetValue("Content-Length", out literalContentLength))
            {
                int fContentLength;
                if (int.TryParse(literalContentLength.First(), out fContentLength))
                    contentLength = fContentLength;
            }

            if (!contentLength.HasValue)
            {
                using (var memoryStream = new MemoryStream())
                {
                    stream.CopyTo(memoryStream);
                    return memoryStream.ToArray();
                }
            }

            var contentBytes = new byte[contentLength.Value];
            stream.ReadAll(contentBytes, 0, contentBytes.Length);
            return contentBytes;
        }
Ejemplo n.º 42
0
 public static string ReadString(Stream stream, int length)
 {
     byte[] bytes = new byte[length];
     stream.ReadAll(bytes, 0, length);
     return Encoding.ASCII.GetString(bytes);
 }
Ejemplo n.º 43
0
        public HleModuleGuest LoadModule(Stream FileStream, Stream MemoryStream, MemoryPartition MemoryPartition, HleModuleManager ModuleManager, String GameTitle, string ModuleName, bool IsMainModule)
        {
            this.HleModuleGuest = new HleModuleGuest(PspEmulatorContext);

            this.ElfLoader = new ElfLoader();
            this.ModuleManager = ModuleManager;

            var Magic = FileStream.SliceWithLength(0, 4).ReadString(4);
            Logger.Info("Magic: '{0}'", Magic);
            if (Magic == "~PSP")
            {
                try
                {
                    var DecryptedData = new EncryptedPrx().Decrypt(FileStream.ReadAll(), true);
                    File.WriteAllBytes("last_decoded_prx.bin", DecryptedData);
                    FileStream = new MemoryStream(DecryptedData);
                }
                catch (Exception Exception)
                {
                    Logger.Error(Exception);
                    throw (Exception);
                }
            }

            this.ElfLoader.Load(FileStream, ModuleName);

            PspEmulatorContext.PspConfig.InfoExeHasRelocation = this.ElfLoader.NeedsRelocation;

            if (this.ElfLoader.NeedsRelocation)
            {
                var DummyPartition = MemoryPartition.Allocate(
                    0x4000,
                    Name: "Dummy"
                );
                BaseAddress = MemoryPartition.ChildPartitions.OrderByDescending(Partition => Partition.Size).First().Low;
                Logger.Info("BASE ADDRESS (Try    ): 0x{0:X}", BaseAddress);
                BaseAddress = MathUtils.NextAligned(BaseAddress, 0x1000);
                Logger.Info("BASE ADDRESS (Aligned): 0x{0:X}", BaseAddress);
            }
            else
            {
                BaseAddress = 0;
            }

            PspEmulatorContext.PspConfig.RelocatedBaseAddress = BaseAddress;
            PspEmulatorContext.PspConfig.GameTitle = GameTitle;

            this.ElfLoader.AllocateAndWrite(MemoryStream, MemoryPartition, BaseAddress);

            if (this.ElfLoader.NeedsRelocation)
            {
                RelocateFromHeaders();
            }

            if (!ElfLoader.SectionHeadersByName.ContainsKey(".rodata.sceModuleInfo"))
            {
                throw(new Exception("Can't find segment '.rodata.sceModuleInfo'"));
            }

            HleModuleGuest.ModuleInfo = ElfLoader.SectionHeaderFileStream(ElfLoader.SectionHeadersByName[".rodata.sceModuleInfo"]).ReadStruct<ElfPsp.ModuleInfo>(); ;

            //Console.WriteLine(this.ModuleInfo.ToStringDefault());

            HleModuleGuest.InitInfo = new InitInfoStruct()
            {
                PC = ElfLoader.Header.EntryPoint + BaseAddress,
                GP = HleModuleGuest.ModuleInfo.GP + BaseAddress,
            };

            UpdateModuleImports();
            UpdateModuleExports();

            ModuleManager.LoadedGuestModules.Add(HleModuleGuest);

            return HleModuleGuest;
        }
Ejemplo n.º 44
0
 /// <summary>
 /// Builds a FormData from the specified input stream, 
 /// which is assumed to be in x-www-form-urlencoded format.
 /// </summary>
 /// <param name="stream">the input stream</param>
 /// <returns>a populated FormData object</returns>
 public static Task<FormData> ParseUrlEncoded(Stream stream) {
     var form = new FormData();
     string input = stream.ReadAll();
     var pairs = input.Split(UrlSplitTokens, StringSplitOptions.RemoveEmptyEntries);
     foreach (var pair in pairs) {
         var nameValue = pair.Split('=');
         form[nameValue[0]] = UrlHelper.Decode(nameValue[1]);
     }
     return TaskHelper.Completed(form);
 }