Exemple #1
0
    static void Main(string[] args)
    {
        ChunkedMemoryStream cms = new ChunkedMemoryStream();

        Debug.Assert(cms.Length == 0);
        Debug.Assert(cms.Position == 0);
        cms.Position = 0;
        byte[] helloworld = Encoding.UTF8.GetBytes("hello world");
        cms.Write(helloworld, 0, 3);
        cms.Write(helloworld, 3, 3);
        cms.Write(helloworld, 6, 5);
        Debug.Assert(cms.Length == 11);
        Debug.Assert(cms.Position == 11);
        cms.Position = 0;
        byte[] b = new byte[20];
        cms.Read(b, 3, (int)cms.Length);
        Debug.Assert(b.Skip(3).Take(11).SequenceEqual(helloworld));
        cms.Position = 0;
        cms.Write(Encoding.UTF8.GetBytes("seeya"), 0, 5);
        Debug.Assert(cms.Length == 11);
        Debug.Assert(cms.Position == 5);
        cms.Position = 0;
        cms.Read(b, 0, (byte)cms.Length);
        Debug.Assert(b.Take(11).SequenceEqual(Encoding.UTF8.GetBytes("seeya world")));
        Debug.Assert(cms.Length == 11);
        Debug.Assert(cms.Position == 11);
        cms.Write(Encoding.UTF8.GetBytes(" again"), 0, 6);
        Debug.Assert(cms.Length == 17);
        Debug.Assert(cms.Position == 17);
        cms.Position = 0;
        cms.Read(b, 0, (byte)cms.Length);
        Debug.Assert(b.Take(17).SequenceEqual(Encoding.UTF8.GetBytes("seeya world again")));
    }
Exemple #2
0
        public void ChunkedMemoryStream_Write_CanWriteDataToFullInMultipleTimes()
        {
            var buffers = new[]
            {
                new byte[10],
                new byte[20]
            };

            var chunkedMemoryStream = new ChunkedMemoryStream(buffers, 0, 30);

            // Write the data partially in 2 times
            var inBuffer = new byte[10];

            for (int i = 0; i < 10; i++)
            {
                inBuffer[i] = (byte)i;
            }
            chunkedMemoryStream.Write(inBuffer, 0, 10);


            var inBuffer2 = new byte[10];

            for (int i = 0; i < 10; i++)
            {
                inBuffer2[i] = (byte)(i + 10);
            }
            chunkedMemoryStream.Write(inBuffer2, 0, 10);


            var inBuffer3 = new byte[10];

            for (int i = 0; i < 10; i++)
            {
                inBuffer3[i] = (byte)(i + 20);
            }
            chunkedMemoryStream.Write(inBuffer3, 0, 10);


            Assert.AreEqual(30, chunkedMemoryStream.Position);
            Assert.AreEqual(30, chunkedMemoryStream.Length);

            for (int i = 0; i < 10; i++)
            {
                Assert.AreEqual(inBuffer[i], buffers[0][i]);
            }

            for (int i = 0; i < 10; i++)
            {
                Assert.AreEqual(inBuffer2[i], buffers[1][i]);
            }

            for (int i = 0; i < 10; i++)
            {
                Assert.AreEqual(inBuffer3[i], buffers[1][i + 10]);
            }
        }
        static RestService()
        {
            var hwText = Encoding.UTF8.GetBytes("Hello, World!");

            HelloWorld.Write(hwText, 0, hwText.Length);
            HelloWorld.Position = 0;
        }
Exemple #4
0
        public void TestCreateTextDataFromStream()
        {
            var stream = new ChunkedMemoryStream();
              var str = Encoding.ASCII.GetBytes("string");

              stream.Write(str, 0, str.Length);
              stream.Position = 0L;

              var text = ImapData.CreateTextData(stream);

              Assert.AreEqual(ImapDataFormat.Text, text.Format);
              Assert.AreEqual(6, text.GetTextLength());
              Assert.AreEqual(Encoding.ASCII.GetBytes("string"), text.GetTextAsByteArray());
              Assert.AreEqual(new ByteString(str), text.GetTextAsByteString());
              Assert.AreEqual("string", text.GetTextAsString());

              Assert.AreSame(stream, text.GetTextAsStream());

              FileAssert.AreEqual(new MemoryStream(str, false), text.GetTextAsStream());

              var buffer = new byte[3];

              text.CopyText(buffer, 0, buffer.Length);

              Assert.AreEqual(str.Slice(0, 3), buffer);
        }
Exemple #5
0
        public void ChunkedMemoryStream_Write_CanWriteDataPartiallyInOneTime()
        {
            var buffers = new[]
            {
                new byte[10],
                new byte[20]
            };

            var chunkedMemoryStream = new ChunkedMemoryStream(buffers, 0, 30);

            // Write the data partially in 1 time
            var inBuffer = new byte[20];

            for (int i = 0; i < 20; i++)
            {
                inBuffer[i] = (byte)i;
            }
            chunkedMemoryStream.Write(inBuffer, 0, 20);


            Assert.AreEqual(20, chunkedMemoryStream.Position);
            Assert.AreEqual(30, chunkedMemoryStream.Length);

            for (int i = 0; i < 10; i++)
            {
                Assert.AreEqual(inBuffer[i], buffers[0][i]);
            }

            for (int i = 0; i < 10; i++)
            {
                Assert.AreEqual(inBuffer[10 + i], buffers[1][i]);
            }
        }
 public void Write_100_bytes()
 {
     byte[] bytes = GetBytes(100);
     var stream = new ChunkedMemoryStream();
     stream.Write(bytes, 0, bytes.Length);
     Assert.AreEqual(100, stream.Length);
 }
        public void Write_199k_bytes()
        {
            byte[] bytes  = GetBytes(199 * 1024);
            var    stream = new ChunkedMemoryStream();

            stream.Write(bytes, 0, bytes.Length);
        }
        public void Write_100_bytes()
        {
            byte[] bytes  = GetBytes(100);
            var    stream = new ChunkedMemoryStream();

            stream.Write(bytes, 0, bytes.Length);
            Assert.AreEqual(100, stream.Length);
        }
        public void Write_fixed_buffer_with_offset_and_overflow()
        {
            var bytes        = GetBytes(100);
            var stream       = new ChunkedMemoryStream(bytes, 10, 9);
            var writtenBytes = GetBytes(10).Reverse().ToArray();

            stream.Write(writtenBytes, 0, writtenBytes.Length);
        }
 public void Write_100_bytes_100_times()
 {
     byte[] bytes = GetBytes(100);
     var stream = new ChunkedMemoryStream();
     for(int i = 0; i < 100; ++i) {
         stream.Write(bytes, 0, bytes.Length);
     }
 }
        public void Write_100_bytes_100_times()
        {
            byte[] bytes  = GetBytes(100);
            var    stream = new ChunkedMemoryStream();

            for (int i = 0; i < 100; ++i)
            {
                stream.Write(bytes, 0, bytes.Length);
            }
        }
Exemple #12
0
        static RestService()
        {
            var hwText = Encoding.UTF8.GetBytes("Hello, World!");

            HelloWorld.Write(hwText, 0, hwText.Length);
            HelloWorld.Position = 0;
            for (int i = 0; i < IDs.Length; i++)
            {
                IDs[i] = i.ToString();
            }
        }
Exemple #13
0
        public static Stream DeserializeStream(BufferedTextReader sr, int nextToken)
        {
            if (nextToken != '"')
            {
                throw new SerializationException("Expecting '\"' at position " + JsonSerialization.PositionInStream(sr) + ". Found " + (char)nextToken);
            }
            nextToken = sr.Read();
            if (nextToken == '"')
            {
                return(new MemoryStream());
            }
            //TODO: lazy init stream (more lightweight!?)
            var res    = new ChunkedMemoryStream();
            var base64 = sr.LargeTempBuffer;
            int i      = 1;

            base64[0] = (char)nextToken;
            int len;

            while ((len = sr.ReadUntil(base64, i, '"')) > 0)
            {
                i += len;
                if (i == base64.Length)
                {
                    var bytes = Convert.FromBase64CharArray(base64, 0, base64.Length);
                    res.Write(bytes, 0, bytes.Length);
                    i = 0;
                }
            }
            nextToken = sr.Read();
            if (i > 0)
            {
                var bytes = Convert.FromBase64CharArray(base64, 0, i);
                res.Write(bytes, 0, bytes.Length);
            }
            if (nextToken != '"')
            {
                throw new SerializationException("Expecting '\"' at position " + JsonSerialization.PositionInStream(sr) + ". Found end of stream.");
            }
            return(res);
        }
Exemple #14
0
 public ResourceContentBE(string value, MimeType mimeType)
     : this(true) {
     if(value == null) {
         throw new ArgumentNullException("value");
     }
     if(mimeType == null) {
         throw new ArgumentNullException("mimeType");
     }
     _mimeType = mimeType;
     _stream = new ChunkedMemoryStream();
     _stream.Write(mimeType.CharSet, value);
     _size = (uint)_stream.Length;
 }
        public void Write_fixed_buffer_with_offset()
        {
            var bytes        = GetBytes(100);
            var stream       = new ChunkedMemoryStream(bytes, 10, 10);
            var writtenBytes = GetBytes(10).Reverse().ToArray();

            stream.Write(writtenBytes, 0, writtenBytes.Length);

            stream.Position = 0;
            var readBytes = new byte[10];

            stream.Read(readBytes, 0, readBytes.Length);
            Assert.AreEqual(writtenBytes, readBytes);
        }
Exemple #16
0
 public ResourceContentBE(string value, MimeType mimeType)
     : this(true) {
     if (value == null)
     {
         throw new ArgumentNullException("value");
     }
     if (mimeType == null)
     {
         throw new ArgumentNullException("mimeType");
     }
     _mimeType = mimeType;
     _stream   = new ChunkedMemoryStream();
     _stream.Write(mimeType.CharSet, value);
     _size = (uint)_stream.Length;
 }
        public void Write_100_bytes_Read_100_bytes()
        {
            byte[] bytes  = GetBytes(100);
            var    stream = new ChunkedMemoryStream();

            stream.Write(bytes, 0, bytes.Length);
            stream.Position = 0;

            byte[] buffer = new byte[bytes.Length];
            int    read   = stream.Read(buffer, 0, buffer.Length);

            Assert.AreEqual(buffer.Length, read);
            Assert.AreEqual(bytes, buffer);
            Assert.AreEqual(0, stream.Read(buffer, 0, buffer.Length));
        }
Exemple #18
0
        public void MemoryStream_WriteToTests_Negative()
        {
            using var ms2 = new ChunkedMemoryStream(this.allocator);
            Assert.Throws <ArgumentNullException>(() => ms2.WriteTo(null));

            ms2.Write(new byte[] { 1 }, 0, 1);
            var readonlyStream = new MemoryStream(new byte[1028], false);

            Assert.Throws <NotSupportedException>(() => ms2.WriteTo(readonlyStream));

            readonlyStream.Dispose();

            // [] Pass in a closed stream
            Assert.Throws <ObjectDisposedException>(() => ms2.WriteTo(readonlyStream));
        }
        public void Write_64k_bytes_Truncate_17k_Read_64k()
        {
            byte[] bytes  = GetBytes(64 * 1024);
            var    stream = new ChunkedMemoryStream();

            stream.Write(bytes, 0, bytes.Length);
            stream.SetLength(17 * 1024);
            stream.Position = 0;

            byte[] buffer = new byte[bytes.Length];
            int    read   = stream.Read(buffer, 0, buffer.Length);

            Assert.AreEqual(17 * 1024, read);
            Assert.AreEqual(bytes.Take(17 * 1024).ToArray(), buffer.Take(17 * 1024).ToArray());
            Assert.AreEqual(0, stream.Read(buffer, 0, buffer.Length));
        }
        public void Write_100_bytes_100_times_Read_10000_bytes()
        {
            byte[] bytes = GetBytes(100);
            byte[][] arrays = new byte[100][];
            var stream = new ChunkedMemoryStream();
            for(int i = 0; i < 100; ++i) {
                stream.Write(bytes, 0, bytes.Length);
                arrays[i] = bytes;
            }
            stream.Position = 0;

            byte[] buffer = new byte[100 * bytes.Length];
            int read = stream.Read(buffer, 0, buffer.Length);
            Assert.AreEqual(buffer.Length, read);
            Assert.AreEqual(ArrayUtil.Concat(arrays), buffer);
            Assert.AreEqual(0, stream.Read(buffer, 0, buffer.Length));
        }
        public static void MemoryStream_WriteToTests()
        {
            using (var ms2 = new ChunkedMemoryStream())
            {
                byte[] bytArrRet;
                byte[] bytArr = new byte[] { byte.MinValue, byte.MaxValue, 1, 2, 3, 4, 5, 6, 128, 250 };

                // [] Write to FileStream, check the filestream
                ms2.Write(bytArr, 0, bytArr.Length);

                using (var readonlyStream = new ChunkedMemoryStream())
                {
                    ms2.WriteTo(readonlyStream);
                    readonlyStream.Flush();
                    readonlyStream.Position = 0;
                    bytArrRet = new byte[(int)readonlyStream.Length];
                    readonlyStream.Read(bytArrRet, 0, (int)readonlyStream.Length);
                    for (int i = 0; i < bytArr.Length; i++)
                    {
                        Assert.Equal(bytArr[i], bytArrRet[i]);
                    }
                }
            }

            // [] Write to memoryStream, check the memoryStream
            using (var ms2 = new ChunkedMemoryStream())
                using (var ms3 = new ChunkedMemoryStream())
                {
                    byte[] bytArrRet;
                    byte[] bytArr = new byte[] { byte.MinValue, byte.MaxValue, 1, 2, 3, 4, 5, 6, 128, 250 };

                    ms2.Write(bytArr, 0, bytArr.Length);
                    ms2.WriteTo(ms3);
                    ms3.Position = 0;
                    bytArrRet    = new byte[(int)ms3.Length];
                    ms3.Read(bytArrRet, 0, (int)ms3.Length);
                    for (int i = 0; i < bytArr.Length; i++)
                    {
                        Assert.Equal(bytArr[i], bytArrRet[i]);
                    }
                }
        }
        public void Write_100_bytes_100_times_Read_10000_bytes()
        {
            byte[]   bytes  = GetBytes(100);
            byte[][] arrays = new byte[100][];
            var      stream = new ChunkedMemoryStream();

            for (int i = 0; i < 100; ++i)
            {
                stream.Write(bytes, 0, bytes.Length);
                arrays[i] = bytes;
            }
            stream.Position = 0;

            byte[] buffer = new byte[100 * bytes.Length];
            int    read   = stream.Read(buffer, 0, buffer.Length);

            Assert.AreEqual(buffer.Length, read);
            Assert.AreEqual(ArrayUtil.Concat(arrays), buffer);
            Assert.AreEqual(0, stream.Read(buffer, 0, buffer.Length));
        }
Exemple #23
0
        private static bool ReCalculateFileMD5(string path)
        {
            if (!XLPack.IsFileExist(path))
            {
                return(false);
            }

            var       position = XLPack.FOpen(path, "r");
            long      fileSize = XLPack.FSize(position);
            const int bufSize  = 0x4000;

            byte[] buffer = new byte[bufSize];
            IntPtr bufPtr = Marshal.UnsafeAddrOfPinnedArrayElement(buffer, 0);
            // TODO: Do this without reading the entire file into memory to calculate the MD5
            //       Maybe try to use the XLPack.DLL's MD5Init, MD5Update and MD5 Finalize functions ?
            // Using ChunkedMemoryStream instead of MemoryStream to hopefully avoid outofmemory errors on large files
            ChunkedMemoryStream ms = new ChunkedMemoryStream();
            long readTotalSize     = 0;

            while (readTotalSize < fileSize)
            {
                long readSize = fileSize - readTotalSize;
                if (readSize > bufSize)
                {
                    readSize = bufSize;
                }
                XLPack.FRead(position, bufPtr, readSize);
                ms.Write(buffer, 0, (int)readSize); // readSize should never be out of int range, so it's safe to cast it
                readTotalSize += readSize;
            }
            XLPack.FClose(ref position);
            ms.Position = 0;
            MD5    md5Hash   = MD5.Create();
            string md5String = GetMd5Hash(md5Hash, ms).Replace("-", "").ToLower();

            ms.Dispose();
            var res = SetFileMD5(path, md5String);

            return(res);
        }
Exemple #24
0
        public bool Parse(Socket socket, out RouteMatch?match, out RouteHandler route)
        {
            positionInTmp = 0;
            Pipeline      = false;
            var methodEnd = ReadUntil(socket, Space, 0);

            if (methodEnd == -1)
            {
                match = null;
                route = null;
                if (!socket.Connected)
                {
                    offsetInOutput = 0;
                    return(false);
                }
                else if (positionInTmp == 0)
                {
                    if (offsetInOutput != 0)
                    {
                        socket.Send(OutputTemp, offsetInOutput, SocketFlags.None);
                        offsetInOutput = 0;
                        socket.Close();
                        return(false);
                    }
                    else
                    {
                        return(ReturnError(socket, 408));
                    }
                }
                else
                {
                    return(ReturnError(socket, 505));
                }
            }
            HttpMethod = ReadMethod(methodEnd, InputTemp);
            var rowEnd = ReadUntil(socket, LF, methodEnd + 1);

            if (rowEnd == -1 || rowEnd < 12)
            {
                match = null;
                route = null;
                return(ReturnError(socket, 505));
            }
            RequestHeadersLength  = 0;
            ResponseHeadersLength = 0;
            HttpProtocolVersion   = ReadProtocol(rowEnd - 2);
            if (HttpProtocolVersion == null)
            {
                match = null;
                route = null;
                ReturnError(socket, 505, "Only HTTP/1.1 and HTTP/1.0 supported (partially)", false);
                return(false);
            }
            match = ReadUrl(rowEnd, out route);
            if (route == null)
            {
                var unknownRoute = "Unknown route " + RawUrl + " on method " + HttpMethod;
                ReturnError(socket, 404, unknownRoute, false);
                return(false);
            }
            ResponseStatus           = HttpStatusCode.OK;
            ResponseLength           = null;
            ResponseContentType      = null;
            TemplateMatch            = null;
            ResponseIsJson           = false;
            ContentTypeResponseIndex = -1;
            do
            {
                var start = rowEnd + 1;
                rowEnd = ReadUntil(socket, CR, start);
                if (rowEnd == start)
                {
                    break;
                }
                else if (rowEnd == -1)
                {
                    return(ReturnError(socket, 414));
                }
                else
                {
                    int i = start;
                    for (; i < rowEnd; i++)
                    {
                        if (InputTemp[i] == ':')
                        {
                            break;
                        }
                    }
                    if (i == rowEnd)
                    {
                        return(ReturnError(socket, 414));
                    }
                    var nameBuf = TmpCharBuf;
                    for (int x = start; x < i; x++)
                    {
                        nameBuf[x - start] = Lower[InputTemp[x]];
                    }
                    var name = KeyCache.Get(nameBuf, i - start);
                    if (InputTemp[i + 1] == 32)
                    {
                        i++;
                    }
                    for (int x = i + 1; x < rowEnd; x++)
                    {
                        nameBuf[x - i - 1] = (char)InputTemp[x];
                    }
                    var value = ValueCache.Get(nameBuf, rowEnd - i - 1);
                    if (RequestHeadersLength == RequestHeaders.Length)
                    {
                        var newHeaders = new HeaderPair[RequestHeaders.Length * 2];
                        Array.Copy(RequestHeaders, newHeaders, RequestHeaders.Length);
                        RequestHeaders = newHeaders;
                    }
                    RequestHeaders[RequestHeadersLength++] = new HeaderPair(name, value);
                }
                rowEnd++;
            } while (positionInTmp <= InputTemp.Length);
            rowEnd += 2;
            if (HttpMethod == "POST" || HttpMethod == "PUT")
            {
                int len = 0;
                var ct  = GetRequestHeader("content-length");
                if (ct != null)
                {
                    if (!int.TryParse(ct, out len))
                    {
                        return(ReturnError(socket, 411));
                    }
                    if (len > Limit)
                    {
                        return(ReturnError(socket, 413));
                    }
                }
                else
                {
                    return(ReturnError(socket, 411));
                }
                InputStream.Reset();
                var size = totalBytes - rowEnd;
                InputStream.Write(InputTemp, rowEnd, size);
                len -= size;
                var oldTimeout = socket.ReceiveTimeout;
                socket.ReceiveTimeout = 10000;
                while (len > 0)
                {
                    size = socket.Receive(InputTemp, Math.Min(len, InputTemp.Length), SocketFlags.None);
                    if (size < 1)
                    {
                        return(ReturnError(socket, 408));
                    }
                    InputStream.Write(InputTemp, 0, size);
                    len -= size;
                }
                socket.ReceiveTimeout = oldTimeout;
                InputStream.Position  = 0;
                rowEnd     = totalBytes;
                totalBytes = 0;
            }
            else
            {
                Pipeline = rowEnd < totalBytes;
                if (Pipeline)
                {
                    Buffer.BlockCopy(InputTemp, rowEnd, InputTemp, 0, totalBytes - rowEnd);
                    totalBytes -= rowEnd;
                }
                else
                {
                    totalBytes = 0;
                }
            }
            return(true);
        }
Exemple #25
0
		public static Stream DeserializeStream(BufferedTextReader sr, int nextToken)
		{
			if (nextToken != '"') throw new SerializationException("Expecting '\"' at position " + JsonSerialization.PositionInStream(sr) + ". Found " + (char)nextToken);
			nextToken = sr.Read();
			if (nextToken == '"') return new MemoryStream();
			//TODO: lazy init stream (more lightweight!?)
			var res = new ChunkedMemoryStream();
			var base64 = sr.LargeTempBuffer;
			int i = 1;
			base64[0] = (char)nextToken;
			int len;
			while ((len = sr.ReadUntil(base64, i, '"')) > 0)
			{
				i += len;
				if (i == base64.Length)
				{
					var bytes = Convert.FromBase64CharArray(base64, 0, base64.Length);
					res.Write(bytes, 0, bytes.Length);
					i = 0;
				}
			}
			nextToken = sr.Read();
			if (i > 0)
			{
				var bytes = Convert.FromBase64CharArray(base64, 0, i);
				res.Write(bytes, 0, bytes.Length);
			}
			if (nextToken != '"') throw new SerializationException("Expecting '\"' at position " + JsonSerialization.PositionInStream(sr) + ". Found end of stream.");
			return res;
		}
 public void Write_fixed_buffer_with_offset_and_overflow()
 {
     var bytes = GetBytes(100);
     var stream = new ChunkedMemoryStream(bytes, 10, 9);
     var writtenBytes = GetBytes(10).Reverse().ToArray();
     stream.Write(writtenBytes, 0, writtenBytes.Length);
 }
        public void Write_fixed_buffer_with_offset()
        {
            var bytes = GetBytes(100);
            var stream = new ChunkedMemoryStream(bytes, 10, 10);
            var writtenBytes = GetBytes(10).Reverse().ToArray();
            stream.Write(writtenBytes, 0, writtenBytes.Length);

            stream.Position = 0;
            var readBytes = new byte[10];
            stream.Read(readBytes, 0, readBytes.Length);
            Assert.AreEqual(writtenBytes, readBytes);
        }
        public void Write_64k_bytes_Truncate_17k_Read_64k()
        {
            byte[] bytes = GetBytes(64 * 1024);
            var stream = new ChunkedMemoryStream();
            stream.Write(bytes, 0, bytes.Length);
            stream.SetLength(17 * 1024);
            stream.Position = 0;

            byte[] buffer = new byte[bytes.Length];
            int read = stream.Read(buffer, 0, buffer.Length);
            Assert.AreEqual(17 * 1024, read);
            Assert.AreEqual(bytes.Take(17 * 1024).ToArray(), buffer.Take(17 * 1024).ToArray());
            Assert.AreEqual(0, stream.Read(buffer, 0, buffer.Length));
        }
        public void Write_64k_bytes_Read_64k_bytes()
        {
            byte[] bytes = GetBytes(64 * 1024);
            var stream = new ChunkedMemoryStream();
            stream.Write(bytes, 0, bytes.Length);
            stream.Position = 0;

            byte[] buffer = new byte[bytes.Length];
            int read = stream.Read(buffer, 0, buffer.Length);
            Assert.AreEqual(buffer.Length, read);
            Assert.AreEqual(bytes, buffer);
            Assert.AreEqual(0, stream.Read(buffer, 0, buffer.Length));
        }
 public void Write_64k_bytes()
 {
     byte[] bytes = GetBytes(64 * 1024);
     var stream = new ChunkedMemoryStream();
     stream.Write(bytes, 0, bytes.Length);
 }
        public void TestSeekInternalStateNotChanged2()
        {
            using (var stream = new ChunkedMemoryStream()) {
            Assert.AreEqual(0L, stream.Position);
            Assert.AreEqual(0L, stream.Length);

            stream.Position = 0L;

            Assert.AreEqual(0L, stream.Position);
            Assert.AreEqual(0L, stream.Length);

            stream.Write(new byte[] {0x00, 0x01, 0x02, 0x03}, 0, 4);

            Assert.AreEqual(4L, stream.Position);
            Assert.AreEqual(4L, stream.Length);
              }
        }
        public void TestWrite()
        {
            using (var stream = new ChunkedMemoryStream(8)) {
            Assert.AreEqual(0L, stream.Position);
            Assert.AreEqual(0L, stream.Length);

            stream.Write(new byte[] {0x00}, 0, 1);
            Assert.AreEqual(1L, stream.Position);
            Assert.AreEqual(1L, stream.Length);

            stream.Write(new byte[] {0x01, 0x02, 0x03}, 0, 3);
            Assert.AreEqual(4L, stream.Position);
            Assert.AreEqual(4L, stream.Length);

            stream.Write(new byte[] {0x04, 0x05, 0x06, 0x07}, 0, 4);
            Assert.AreEqual(8L, stream.Position);
            Assert.AreEqual(8L, stream.Length);

            stream.Write(new byte[] {0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e}, 0, 7);
            Assert.AreEqual(15L, stream.Position);
            Assert.AreEqual(15L, stream.Length);

            stream.Write(new byte[] {0x0f, 0x10}, 0, 2);
            Assert.AreEqual(17L, stream.Position);
            Assert.AreEqual(17L, stream.Length);

            stream.Write(new byte[] {0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f}, 0, 15);
            Assert.AreEqual(32L, stream.Position);
            Assert.AreEqual(32L, stream.Length);

            Assert.AreEqual(new byte[] {
              0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
              0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f,
            }, stream.ToArray());
              }
        }
        public void Write_100_bytes_100_times_Read_100_bytes_100_times()
        {
            byte[] bytes = GetBytes(100);
            var stream = new ChunkedMemoryStream();
            for(int i = 0; i < 100; ++i) {
                stream.Write(bytes, 0, bytes.Length);
            }
            stream.Position = 0;

            byte[] buffer = new byte[bytes.Length];
            for(int i = 0; i < 100; ++i) {
                int read = stream.Read(buffer, 0, buffer.Length);
                Assert.AreEqual(buffer.Length, read);
                Assert.AreEqual(bytes, buffer);
            }
            Assert.AreEqual(0, stream.Read(buffer, 0, buffer.Length));
        }
Exemple #34
0
        public bool Parse(Socket socket)
        {
            positionInTmp = 0;
            Pipeline      = false;
            var methodEnd = ReadUntil(socket, Space, 0);

            if (methodEnd == -1)
            {
                return(ReturnError(socket, 505));
            }
            HttpMethod = ReadMethod(methodEnd, InputTemp);
            var rowEnd = ReadUntil(socket, LF, methodEnd + 1);

            if (rowEnd == -1 || rowEnd < 12)
            {
                return(ReturnError(socket, 505));
            }
            RequestHeadersLength  = 0;
            ResponseHeadersLength = 0;
            HttpProtocolVersion   = ReadProtocol(rowEnd - 2);
            if (HttpProtocolVersion == null)
            {
                ReturnError(socket, 505, "Only HTTP/1.1 and HTTP/1.0 supported (partially)", false);
                return(false);
            }
            ReadUrl(rowEnd);
            int askSign = RawUrl.IndexOf('?');

            AbsolutePath             = askSign == -1 ? RawUrl : RawUrl.Substring(0, askSign);
            ResponseStatus           = HttpStatusCode.OK;
            ResponseLength           = null;
            ResponseContentType      = null;
            TemplateMatch            = null;
            ResponseIsJson           = false;
            ContentTypeResponseIndex = -1;
            do
            {
                var start = rowEnd + 1;
                rowEnd = ReadUntil(socket, CR, start);
                if (rowEnd == start)
                {
                    break;
                }
                else if (rowEnd == -1)
                {
                    return(ReturnError(socket, 414));
                }
                else
                {
                    int i = start;
                    for (; i < rowEnd; i++)
                    {
                        if (InputTemp[i] == ':')
                        {
                            break;
                        }
                    }
                    if (i == rowEnd)
                    {
                        return(ReturnError(socket, 414));
                    }
                    var nameBuf = TmpCharBuf;
                    for (int x = start; x < i; x++)
                    {
                        nameBuf[x - start] = Lower[InputTemp[x]];
                    }
                    string name = new string(nameBuf, 0, i - start);
                    if (InputTemp[i + 1] == 32)
                    {
                        i++;
                    }
                    for (int x = i + 1; x < rowEnd; x++)
                    {
                        nameBuf[x - i - 1] = (char)InputTemp[x];
                    }
                    string value = new string(nameBuf, 0, rowEnd - i - 1);
                    if (RequestHeadersLength == RequestHeaders.Length)
                    {
                        var newHeaders = new HeaderPair[RequestHeaders.Length * 2];
                        Array.Copy(RequestHeaders, newHeaders, RequestHeaders.Length);
                        RequestHeaders = newHeaders;
                    }
                    RequestHeaders[RequestHeadersLength++] = new HeaderPair(name, value);
                }
                rowEnd++;
            } while (positionInTmp <= InputTemp.Length);
            rowEnd += 2;
            if (HttpMethod == "POST" || HttpMethod == "PUT")
            {
                int len = 0;
                var ct  = GetRequestHeader("content-length");
                if (ct != null)
                {
                    if (!int.TryParse(ct, out len))
                    {
                        return(ReturnError(socket, 411));
                    }
                    if (len > Limit)
                    {
                        return(ReturnError(socket, 413));
                    }
                }
                else
                {
                    return(ReturnError(socket, 411));
                }
                InputStream.Reset();
                var size = totalBytes - rowEnd;
                InputStream.Write(InputTemp, rowEnd, size);
                len -= size;
                while (len > 0)
                {
                    size = socket.Receive(InputTemp, Math.Min(len, InputTemp.Length), SocketFlags.None);
                    if (size < 1)
                    {
                        return(ReturnError(socket, 408));
                    }
                    InputStream.Write(InputTemp, 0, size);
                    len -= size;
                }
                InputStream.Position = 0;
                rowEnd     = totalBytes;
                totalBytes = 0;
            }
            else
            {
                Pipeline = rowEnd < totalBytes;
                if (Pipeline)
                {
                    Buffer.BlockCopy(InputTemp, rowEnd, InputTemp, 0, totalBytes - rowEnd);
                    totalBytes -= rowEnd;
                }
                else
                {
                    totalBytes = 0;
                }
            }
            return(true);
        }