Esempio n. 1
0
        public ImapReplayCommand(string command, string resource)
        {
            string tag = null;

            Command = command;

            if (command.StartsWith("A00000", StringComparison.Ordinal))
            {
                tag = command.Substring(0, 9);
            }

            using (var stream = GetType().Assembly.GetManifestResourceStream("UnitTests.Net.Imap.Resources." + resource)) {
                using (var memory = new MemoryBlockStream()) {
                    using (var filtered = new FilteredStream(memory)) {
                        if (tag != null)
                        {
                            filtered.Add(new ImapReplayFilter("A########", tag));
                        }

                        filtered.Add(new Unix2DosFilter());
                        stream.CopyTo(filtered, 4096);
                        filtered.Flush();
                    }

                    Response = memory.ToArray();
                }
            }
        }
Esempio n. 2
0
        public ImapReplayCommand(string tag, string command, string resource, bool compressed = false)
        {
            CommandBuffer = Latin1.GetBytes(command);
            Compressed    = compressed;
            Command       = command;

            using (var stream = GetType().Assembly.GetManifestResourceStream("UnitTests.Net.Imap.Resources." + resource)) {
                using (var memory = new MemoryBlockStream()) {
                    using (Stream compress = new CompressedStream(memory)) {
                        using (var filtered = new FilteredStream(compressed ? compress : memory)) {
                            filtered.Add(new ImapReplayFilter("A########", tag));
                            filtered.Add(new Unix2DosFilter());
                            stream.CopyTo(filtered, 4096);
                            filtered.Flush();
                        }

                        Response = memory.ToArray();
                    }
                }
            }

            if (compressed)
            {
                using (var memory = new MemoryStream()) {
                    using (var compress = new CompressedStream(memory)) {
                        compress.Write(CommandBuffer, 0, CommandBuffer.Length);
                        compress.Flush();

                        CommandBuffer = memory.ToArray();
                    }
                }
            }
        }
Esempio n. 3
0
        /// <summary>
        /// Parses a MimeEntity and returns as lambda to caller.
        /// </summary>
        /// <param name="node">Node containing the MIME message as value,
        /// and also where the lambda structure representing the parsed message will be placed.</param>
        /// <param name="entity">MimeEntity to parse.</param>
        public static void Parse(Node node, MimeEntity entity)
        {
            node.Value = entity.ContentType.MimeType;
            ProcessHeaders(node, entity);

            if (entity is Multipart multi)
            {
                // Multipart content.
                foreach (var idx in multi)
                {
                    var idxNode = new Node("entity");
                    Parse(idxNode, idx);
                    node.Add(idxNode);
                }
            }
            else if (entity is TextPart text)
            {
                // Test type of entity.
                node.Add(new Node("content", text.GetText(out var _)));
            }
            else if (entity is MimePart part)
            {
                using (var stream = new MemoryBlockStream())
                {
                    // Decoding content to memory.
                    part.Content.DecodeTo(stream);

                    // Resetting position and setting up a buffer object to hold content.
                    stream.Position = 0;

                    // Putting content into return node for MimeEntity.
                    node.Add(new Node("content", stream.ToArray()));
                }
            }
        }
Esempio n. 4
0
        private static void ParseImplementation(Node node, MimeEntity entity)
        {
            var tmp = new Node("entity", entity.ContentType.MimeType);

            ProcessHeaders(tmp, entity);

            if (entity is MultipartSigned signed)
            {
                // Multipart content.
                var signatures = new Node("signatures");
                foreach (var idx in signed.Verify())
                {
                    if (!idx.Verify())
                    {
                        throw new SecurityException("Signature of MIME message was not valid");
                    }
                    signatures.Add(new Node("fingerprint", idx.SignerCertificate.Fingerprint.ToLower()));
                }
                tmp.Add(signatures);

                // Then traversing content of multipart/signed message.
                foreach (var idx in signed)
                {
                    ParseImplementation(tmp, idx);
                }
            }
            else if (entity is MultipartEncrypted)
            {
                throw new ArgumentException("Magic currently does not support decrypting MIME messages");
            }
            else if (entity is Multipart multi)
            {
                // Multipart content.
                foreach (var idx in multi)
                {
                    ParseImplementation(tmp, idx);
                }
            }
            else if (entity is TextPart text)
            {
                // Singular content type.
                // Notice! We don't really care about the encoding the text was encoded with.
                tmp.Add(new Node("content", text.GetText(out var encoding)));
            }
            else if (entity is MimePart part)
            {
                using (var stream = new MemoryBlockStream())
                {
                    // Decoding content to memory.
                    part.Content.DecodeTo(stream);

                    // Resetting position and setting up a buffer object to hold content.
                    stream.Position = 0;

                    // Putting content into return node for MimeEntity.
                    tmp.Add(new Node("content", stream.ToArray()));
                }
            }
            node.Add(tmp);
        }
Esempio n. 5
0
        private void CompareState(MemoryStream ms, MemoryBlockStream ms2)
        {
            // Compare byte content.
            byte[] buff1 = ms.ToArray();
            byte[] buff2 = ms2.ToArray();

            // Compare read/write position.
            Assert.Equal(buff1, buff2);
            Assert.Equal(ms.Position, ms2.Position);
        }
Esempio n. 6
0
        /*
         * Returns a MimePart as inline content to caller.
         */
        void ProcessMimePartInline(MimePart part, Node entityNode)
        {
            // Checking if MIME entity is a simple "text" part.
            var txtPart = part as TextPart;

            if (txtPart != null)
            {
                // Part is text part.
                entityNode.Add("content", txtPart.Text);
            }
            else if (part.ContentType.MediaType == "application" && part.ContentType.MediaSubtype == "x-hyperlambda")
            {
                /*
                 * Current part is inline Hyperlambda content.
                 *
                 * Creating a stream to decode our entity to.
                 */
                using (var stream = new MemoryBlockStream()) {
                    // Decoding content to memory.
                    part.Content.DecodeTo(stream);

                    // Resetting position and setting up a buffer object to hold content.
                    stream.Position = 0;

                    // Getting content as text.
                    using (var reader = new StreamReader(stream)) {
                        // Reading content is string.
                        var content = reader.ReadToEnd();

                        // Putting content into return node for MimeEntity.
                        entityNode.Add("content").LastChild.AddRange(_context.RaiseEvent("hyper2lambda", new Node("", content)).Children);
                    }
                }
            }
            else
            {
                /*
                 * Part is not text part, and is not Hyperlambda content, hence we
                 * make sure we add it to returned [content] node as binary data.
                 *
                 * First creating a stream to decode our entity to.
                 */
                using (var stream = new MemoryBlockStream()) {
                    // Decoding content to memory.
                    part.Content.DecodeTo(stream);

                    // Resetting position and setting up a buffer object to hold content.
                    stream.Position = 0;

                    // Putting content into return node for MimeEntity.
                    entityNode.Add("content", stream.ToArray());
                }
            }
        }
        public void TestToArray()
        {
            var masterArray = master.ToArray();
            var array       = blocks.ToArray();

            Assert.AreEqual(masterArray.Length, array.Length, "ToArray() length does not match");

            for (int i = 0; i < array.Length; i++)
            {
                Assert.AreEqual(masterArray[i], array[i], "The bytes do not match");
            }
        }
Esempio n. 8
0
		static byte[] ReadAllBytes (Stream stream)
		{
			if (stream is MemoryBlockStream)
				return ((MemoryBlockStream) stream).ToArray ();

			if (stream is MemoryStream)
				return ((MemoryStream) stream).ToArray ();

			using (var memory = new MemoryBlockStream ()) {
				stream.CopyTo (memory, 4096);
				return memory.ToArray ();
			}
		}
Esempio n. 9
0
        public ImapReplayCommand(string command, string resource)
        {
            Command = command;

            using (var stream = GetType().Assembly.GetManifestResourceStream("UnitTests.Net.Imap.Resources." + resource)) {
                var memory = new MemoryBlockStream();

                using (var filtered = new FilteredStream(memory)) {
                    filtered.Add(new Unix2DosFilter());
                    stream.CopyTo(filtered, 4096);
                }

                Response = memory.ToArray();
            }
        }
Esempio n. 10
0
        public void WriteZeroBytes()
        {
            byte[] buf = Array.Empty<byte>();
            MemoryBlockStream ms = new MemoryBlockStream();
            ms.Write(buf, 0, 0);
            Assert.Equal(0, ms.Length);

            IRandomSource rng = RandomDefaults.CreateRandomSource(1234567);
            byte[] buf2 = new byte[100];
            rng.NextBytes(buf2);
            ms.Write(buf2);

            Assert.Equal(ms.ToArray(), buf2);

            ms.Write(buf, 0, 0);
            Assert.Equal(ms.Length, buf2.Length);
        }
Esempio n. 11
0
        private void CompareState(MemoryStream ms, MemoryBlockStream ms2)
        {
            // Compare byte content.
            byte[] buff1 = ms.ToArray();
            byte[] buff2 = ms2.ToArray();

            if (!Utils.AreEqual(buff1, buff2))
            {
                throw new Exception("State mismatch");
            }

            // Compare read/write position.
            if (ms.Position != ms2.Position)
            {
                throw new Exception("Position mismatch");
            }
        }
Esempio n. 12
0
        public ImapReplayCommand(Encoding encoding, string command, string resource, bool compressed = false)
        {
            string tag = null;

            CommandBuffer = encoding.GetBytes(command);
            Compressed    = compressed;
            Encoding      = encoding;
            Command       = command;

            if (command.StartsWith("A00000", StringComparison.Ordinal))
            {
                tag = command.Substring(0, 9);
            }

            using (var stream = GetType().Assembly.GetManifestResourceStream("UnitTests.Net.Imap.Resources." + resource)) {
                using (var memory = new MemoryBlockStream()) {
                    using (Stream compress = new CompressedStream(memory)) {
                        using (var filtered = new FilteredStream(compressed ? compress : memory)) {
                            if (tag != null)
                            {
                                filtered.Add(new ImapReplayFilter("A########", tag));
                            }

                            filtered.Add(new Unix2DosFilter());
                            stream.CopyTo(filtered, 4096);
                            filtered.Flush();
                        }

                        Response = memory.ToArray();
                    }
                }
            }

            if (compressed)
            {
                using (var memory = new MemoryStream()) {
                    using (var compress = new CompressedStream(memory)) {
                        compress.Write(CommandBuffer, 0, CommandBuffer.Length);
                        compress.Flush();

                        CommandBuffer = memory.ToArray();
                    }
                }
            }
        }
Esempio n. 13
0
        static async Task <byte[]> ReadAllBytesAsync(Stream stream, CancellationToken cancellationToken)
        {
            if (stream is MemoryBlockStream)
            {
                return(((MemoryBlockStream)stream).ToArray());
            }

            if (stream is MemoryStream)
            {
                return(((MemoryStream)stream).ToArray());
            }

            using (var memory = new MemoryBlockStream()) {
                await stream.CopyToAsync(memory, 4096, cancellationToken).ConfigureAwait(false);

                return(memory.ToArray());
            }
        }
Esempio n. 14
0
        public void TestWriteZeroBytes()
        {
            byte[]            buf = new byte[0];
            MemoryBlockStream ms  = new MemoryBlockStream();

            ms.Write(buf, 0, 0);
            Assert.AreEqual(ms.Length, 0);

            XorShiftRandom rng = new XorShiftRandom(1234567);

            byte[] buf2 = new byte[100];
            rng.NextBytes(buf2);
            ms.Write(buf2, 0, buf2.Length);

            if (!Utils.AreEqual(ms.ToArray(), buf2))
            {
                Assert.Fail();
            }

            ms.Write(buf, 0, 0);
            Assert.AreEqual(ms.Length, buf2.Length);
        }
Esempio n. 15
0
        public void TestWriteZeroBytes()
        {
            byte[]            buf = new byte[0];
            MemoryBlockStream ms  = new MemoryBlockStream();

            ms.Write(buf, 0, 0);
            Assert.AreEqual(ms.Length, 0);

            IRandomSource rng = RandomDefaults.CreateRandomSource(1234567);

            byte[] buf2 = new byte[100];
            rng.NextBytes(buf2);
            ms.Write(buf2, 0, buf2.Length);

            if (!Utils.AreEqual(ms.ToArray(), buf2))
            {
                Assert.Fail();
            }

            ms.Write(buf, 0, 0);
            Assert.AreEqual(ms.Length, buf2.Length);
        }
Esempio n. 16
0
        public void Validate(YEncHeader header, MemoryBlockStream decodedPartStream)
        {
            if (!MatchesPart(header))
            {
                throw new YEncException($"Part mismatch. Expected {header.Part}, but got {Part}.");
            }

            if (Size != decodedPartStream.Length)
            {
                throw new YEncException($"Size mismatch. Expected {Size}, but got {decodedPartStream.Length}.");
            }

            var crc32 = Crc33 ?? PartCrc32;

            if (crc32.HasValue)
            {
                var calculatedCrc32 = Crc32.CalculateChecksum(decodedPartStream.ToArray());
                if (calculatedCrc32 != crc32.Value)
                {
                    throw new YEncException($"Checksum mismatch. Expected {crc32.Value}, but got {calculatedCrc32}.");
                }
            }
        }
Esempio n. 17
0
        public string ReadText(int MaxLength, TextEncodings TEncoding, ref int ReadedLength, bool DetectEncoding)
        {
            if (MaxLength <= 0)
            {
                return("");
            }
            long Pos = this.FS.Position; // store current position

            MemoryBlockStream MStream = new MemoryBlockStream();

            if (DetectEncoding && MaxLength >= 3)
            {
                byte[] Buffer = new byte[3];
                FS.Read(Buffer, 0, Buffer.Length);
                if (Buffer[0] == 0xFF && Buffer[1] == 0xFE)
                {                                     // FF FE
                    TEncoding = TextEncodings.UTF_16; // UTF-16 (LE)
                    this.FS.Position--;
                    MaxLength -= 2;
                }
                else if (Buffer[0] == 0xFE && Buffer[1] == 0xFF)
                {   // FE FF
                    TEncoding = TextEncodings.UTF_16BE;
                    this.FS.Position--;
                    MaxLength -= 2;
                }
                else if (Buffer[0] == 0xEF && Buffer[1] == 0xBB && Buffer[2] == 0xBF)
                {
                    // EF BB BF
                    TEncoding  = TextEncodings.UTF8;
                    MaxLength -= 3;
                }
                else
                {
                    this.FS.Position -= 3;
                }
            }
            // Indicate text seprator type for current string encoding
            bool Is2ByteSeprator = (TEncoding == TextEncodings.UTF_16 || TEncoding == TextEncodings.UTF_16BE);

            byte Buf, Buf2;

            while (MaxLength > 0)
            {
                if (Is2ByteSeprator)
                {
                    Buf  = ReadByte(FS);
                    Buf2 = ReadByte(FS);

                    if (Buf == 0 && Buf2 == 0)
                    {
                        break;
                    }
                    else
                    {
                        MStream.WriteByte(Buf);
                        MStream.WriteByte(Buf2);
                    }

                    MaxLength--;
                }
                else
                {
                    Buf = ReadByte(FS); // Read First/Next byte from stream

                    if (Buf == 0)
                    {
                        break;
                    }
                    else
                    {
                        MStream.WriteByte(Buf);
                    }
                }

                MaxLength--;
            }

            if (MaxLength < 0)
            {
                this.FS.Position += MaxLength;
            }

            ReadedLength -= Convert.ToInt32(this.FS.Position - Pos);

            return(StaticMethods.GetEncoding(TEncoding).GetString(MStream.ToArray()));
        }