public async Task TestReadLines_ShouldReturnResponse() { string expected = "GET /modules/testModule/sign?api-version=2018-06-28 HTTP/1.1\r\nHost: localhost:8081\r\nConnection: close\r\nContent-Type: application/json\r\nContent-Length: 100\r\n\r\n"; byte[] expectedBytes = Encoding.UTF8.GetBytes(expected); var memory = new MemoryStream(expectedBytes, true); IList <string> lines = new List <string>(); var buffered = new HttpBufferedStream(memory); System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken); string line = await buffered.ReadLineAsync(cancellationToken); while (!string.IsNullOrEmpty(line)) { lines.Add(line); line = await buffered.ReadLineAsync(cancellationToken); } Assert.AreEqual(5, lines.Count); Assert.AreEqual("GET /modules/testModule/sign?api-version=2018-06-28 HTTP/1.1", lines[0]); Assert.AreEqual("Host: localhost:8081", lines[1]); Assert.AreEqual("Connection: close", lines[2]); Assert.AreEqual("Content-Type: application/json", lines[3]); Assert.AreEqual("Content-Length: 100", lines[4]); }
async Task SetResponseStatusLine(HttpResponseMessage httpResponse, HttpBufferedStream bufferedStream, CancellationToken cancellationToken) { string statusLine = await bufferedStream.ReadLineAsync(cancellationToken).ConfigureAwait(false); if (string.IsNullOrWhiteSpace(statusLine)) { throw new HttpRequestException("Response is empty."); } string[] statusLineParts = statusLine.Split(new[] { SP }, 3); if (statusLineParts.Length < 3) { throw new HttpRequestException("Status line is not valid."); } string[] httpVersion = statusLineParts[0].Split(new[] { ProtocolVersionSeparator }, 2); if (httpVersion.Length < 2 || !Version.TryParse(httpVersion[1], out Version versionNumber)) { throw new HttpRequestException($"Version is not valid {statusLineParts[0]}."); } httpResponse.Version = versionNumber; if (!Enum.TryParse(statusLineParts[1], out HttpStatusCode statusCode)) { throw new HttpRequestException($"StatusCode is not valid {statusLineParts[1]}."); } httpResponse.StatusCode = statusCode; httpResponse.ReasonPhrase = statusLineParts[2]; }
public void TestDeserializeResponse_InvalidEndOfHeaders_ShouldThrow() { byte[] expected = Encoding.UTF8.GetBytes("HTTP/1.1 200 OK\r\nContent-length: 5\r\n"); var memory = new MemoryStream(expected, true); var stream = new HttpBufferedStream(memory); TestAssert.ThrowsAsync <IOException>(() => new HttpRequestResponseSerializer().DeserializeResponseAsync(stream, default)).Wait(); }
public void TestDeserializeResponse_InvalidHeaderSeparator_ShouldThrow() { byte[] expected = Encoding.UTF8.GetBytes("HTTP/1.1 200 OK\r\nContent-length=5\r\n\r\nMessage is longer"); var memory = new MemoryStream(expected, true); var stream = new HttpBufferedStream(memory); TestAssert.ThrowsAsync <HttpRequestException>(() => new HttpRequestResponseSerializer().DeserializeResponse(stream, default)).Wait(); }
public void TestDeserializeResponse_InvalidContentLength_ShouldThrow() { byte[] expected = Encoding.UTF8.GetBytes("HTTP/1.1 200 OK\r\nContent-length: 5\r\n\r\nMessage is longer"); var memory = new MemoryStream(expected, true); HttpBufferedStream stream = new HttpBufferedStream(memory); System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken); TestAssert.ThrowsAsync <HttpRequestException>(() => HttpRequestResponseSerializer.DeserializeResponseAsync(stream, cancellationToken)).Wait(); }
public void TestDeserializeResponse_InvalidProtocolVersionSeparator_ShouldThrow() { byte[] expected = Encoding.UTF8.GetBytes("HTTP-1.1 200 OK\r\n"); var memory = new MemoryStream(expected, true); HttpBufferedStream stream = new HttpBufferedStream(memory); System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken); Assert.ThrowsAsync <HttpRequestException>(() => new HttpRequestResponseSerializer().DeserializeResponse(stream, cancellationToken)); }
public void TestDeserializeResponse_InvalidEndOfStream_ShouldThrow() { byte[] expected = Encoding.UTF8.GetBytes("invalid"); var memory = new MemoryStream(expected, true); HttpBufferedStream stream = new HttpBufferedStream(memory); System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken); TestAssert.ThrowsAsync <IOException>(() => new HttpRequestResponseSerializer().DeserializeResponseAsync(stream, cancellationToken)).Wait(); }
public void TestDeserializeResponse_InvalidEndOfHeaders_ShouldThrow() { byte[] expected = Encoding.UTF8.GetBytes("HTTP/1.1 200 OK\r\nContent-length: 5\r\n"); var memory = new MemoryStream(expected, true); var stream = new HttpBufferedStream(memory); System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken); Assert.ThrowsAsync <HttpRequestException>(() => new HttpRequestResponseSerializer().DeserializeResponse(stream, cancellationToken)); }
public void TestDeserializeResponse_MissingReasonPhrase_ShouldThrow() { byte[] expected = Encoding.UTF8.GetBytes("HTTP/1.1 200\r\n"); var memory = new MemoryStream(expected, true); HttpBufferedStream stream = new HttpBufferedStream(memory); System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken); TestAssert.ThrowsAsync <HttpRequestException>(() => new HttpRequestResponseSerializer().DeserializeResponseAsync(stream, cancellationToken)).Wait(); }
public async Task TestDeserializeResponse_InvalidVersion_ShouldThrow() { byte[] expected = Encoding.UTF8.GetBytes("HTTP/11 200 OK\r\n"); var memory = new MemoryStream(expected, true); HttpBufferedStream stream = new HttpBufferedStream(memory); System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken); await TestAssert.ThrowsAsync <HttpRequestException>(() => HttpRequestResponseSerializer.DeserializeResponseAsync(stream, cancellationToken)); }
public async Task TestDeserializeResponse_InvalidEndOfStatusMessage_ShouldThrow() { byte[] expected = Encoding.UTF8.GetBytes("HTTP/1.1 200 OK \r\n"); var memory = new MemoryStream(expected, true); var stream = new HttpBufferedStream(memory); CancellationToken cancellationToken = default(CancellationToken); await Assert.ThrowsAsync <IOException>(() => new HttpRequestResponseSerializer().DeserializeResponse(stream, cancellationToken)); }
public void TestDeserializeResponse_InvalidStatusCode_ShouldThrow() { byte[] expected = Encoding.UTF8.GetBytes("HTTP/1.1 2000 OK\r\n"); var memory = new MemoryStream(expected, true); HttpBufferedStream stream = new HttpBufferedStream(memory); System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken); TestAssert.ThrowsAsync <ArgumentOutOfRangeException>(() => new HttpRequestResponseSerializer().DeserializeResponse(stream, cancellationToken)).Wait(); }
public async Task <HttpResponseMessage> DeserializeResponse(HttpBufferedStream bufferedStream, CancellationToken cancellationToken) { var httpResponse = new HttpResponseMessage(); await this.SetResponseStatusLine(httpResponse, bufferedStream, cancellationToken).ConfigureAwait(false); await this.SetHeadersAndContent(httpResponse, bufferedStream, cancellationToken).ConfigureAwait(false); return(httpResponse); }
public void TestDeserializeResponse_InvalidStatusLine_ShouldThrow() { byte[] expected = Encoding.UTF8.GetBytes("invalid\r\n"); var memory = new MemoryStream(expected, true); var stream = new HttpBufferedStream(memory); CancellationToken cancellationToken = default(CancellationToken); Assert.ThrowsAsync <HttpRequestException>(() => new HttpRequestResponseSerializer().DeserializeResponse(stream, cancellationToken)); }
public async Task TestDeserializeResponse_StatusLine_ShouldDeserialize() { byte[] expected = Encoding.UTF8.GetBytes("HTTP/1.1 200 OK\r\n\r\n"); var memory = new MemoryStream(expected, true); var stream = new HttpBufferedStream(memory); System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken); HttpResponseMessage response = await new HttpRequestResponseSerializer().DeserializeResponse(stream, cancellationToken); Assert.Equal(response.Version, Version.Parse("1.1")); Assert.Equal(response.StatusCode, System.Net.HttpStatusCode.OK); Assert.Equal(response.ReasonPhrase, "OK"); }
public async Task TestReadLines_ShouldReturnResponse() { string expected = "GET /modules/testModule/sign?api-version=2018-06-28 HTTP/1.1\r\nHost: localhost:8081\r\nConnection: close\r\nContent-Type: application/json\r\nContent-Length: 100\r\n\r\n"; byte[] expectedBytes = Encoding.UTF8.GetBytes(expected); var memory = new MemoryStream(expectedBytes, true); var buffered = new HttpBufferedStream(memory); var allLines = new List <string>(5); while (true) { string currentLine = await buffered.ReadLineAsync(default).ConfigureAwait(false);
public async Task TestDeserializeResponse_ValidContent_ShouldDeserialize() { byte[] expected = Encoding.UTF8.GetBytes("HTTP/1.1 200 OK\r\nContent-length: 4\r\n\r\nTest"); var memory = new MemoryStream(expected, true); var stream = new HttpBufferedStream(memory); CancellationToken cancellationToken = default(CancellationToken); HttpResponseMessage response = await new HttpRequestResponseSerializer().DeserializeResponse(stream, cancellationToken); Assert.Equal(response.Version, Version.Parse("1.1")); Assert.Equal(HttpStatusCode.OK, response.StatusCode); Assert.Equal("OK", response.ReasonPhrase); Assert.Equal(4, response.Content.Headers.ContentLength); Assert.Equal("Test", await response.Content.ReadAsStringAsync()); }
public async Task TestDeserializeResponse_InvalidHeader_ShouldDeserialize() { byte[] expected = Encoding.UTF8.GetBytes("HTTP/1.1 200 OK\r\nTest-header: 4\r\n\r\nTest"); var memory = new MemoryStream(expected, true); HttpBufferedStream stream = new HttpBufferedStream(memory); System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken); var response = await new HttpRequestResponseSerializer().DeserializeResponse(stream, cancellationToken); Assert.AreEqual(response.Version, Version.Parse("1.1")); Assert.AreEqual(response.StatusCode, System.Net.HttpStatusCode.OK); Assert.AreEqual(response.ReasonPhrase, "OK"); Assert.AreEqual(response.Content.Headers.ContentLength, 4); Assert.AreEqual(await response.Content.ReadAsStringAsync(), "Test"); }
public async Task TestDeserializeResponse_ValidContent_ShouldDeserialize() { byte[] expected = Encoding.UTF8.GetBytes("HTTP/1.1 200 OK\r\nContent-length: 4\r\n\r\nTest"); var memory = new MemoryStream(expected, true); var stream = new HttpBufferedStream(memory); var response = await new HttpRequestResponseSerializer().DeserializeResponseAsync(stream, default); Assert.AreEqual(response.Version, Version.Parse("1.1")); Assert.AreEqual(response.StatusCode, System.Net.HttpStatusCode.OK); Assert.AreEqual(response.ReasonPhrase, "OK"); #if !NETCOREAPP1_1 Assert.AreEqual(response.Content.Headers.ContentLength, 4); #endif Assert.AreEqual(await response.Content.ReadAsStringAsync(), "Test"); }
public async Task TestDeserializeResponse_InvalidHeader_ShouldDeserialize() { byte[] expected = Encoding.UTF8.GetBytes("HTTP/1.1 200 OK\r\nTest-header: 4\r\n\r\nTest"); var memory = new MemoryStream(expected, true); var stream = new HttpBufferedStream(memory); HttpResponseMessage response = await new HttpRequestResponseSerializer().DeserializeResponseAsync(stream, default).ConfigureAwait(false); Assert.AreEqual(Version.Parse("1.1"), response.Version); Assert.AreEqual(System.Net.HttpStatusCode.OK, response.StatusCode); Assert.AreEqual("OK", response.ReasonPhrase); #if !NETCOREAPP1_1 Assert.AreEqual(4, response.Content.Headers.ContentLength); #endif Assert.AreEqual("Test", await response.Content.ReadAsStringAsync()); }
static async Task <string> Signer(string base64String) { if (string.IsNullOrEmpty(base64String)) { return(null); } try { string IOTEDGE_MODULEID = Environment.GetEnvironmentVariable("IOTEDGE_MODULEID"); string IOTEDGE_MODULEGENERATIONID = Environment.GetEnvironmentVariable("IOTEDGE_MODULEGENERATIONID"); string IOTEDGE_WORKLOADURI = Environment.GetEnvironmentVariable("IOTEDGE_WORKLOADURI").Replace("unix://", ""); UnixEndPoint unixEndpoint = new UnixEndPoint(IOTEDGE_WORKLOADURI); Socket unixSocket = new Socket(AddressFamily.Unix, SocketType.Stream, ProtocolType.IP); unixSocket.Connect(unixEndpoint); string httpRequestURI = $"http://localhost/modules/{IOTEDGE_MODULEID}/genid/{IOTEDGE_MODULEGENERATIONID}/sign?api-version=2018-06-28"; string requestContent = "{\"keyId\": \"primary\", \"algo\": \"HMACSHA256\", \"data\": \"" + base64String + "\"}"; HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, httpRequestURI); request.Content = new StringContent(requestContent, Encoding.UTF8, "application/json"); HttpRequestResponseSerializer serializer = new HttpRequestResponseSerializer(); byte[] requestBytes = serializer.SerializeRequest(request); HttpBufferedStream stream = new HttpBufferedStream(new NetworkStream(unixSocket, true)); await stream.WriteAsync(requestBytes, 0, requestBytes.Length, CancellationToken.None).ConfigureAwait(false); if (request.Content != null) { await request.Content.CopyToAsync(stream).ConfigureAwait(false); } HttpResponseMessage response = await serializer.DeserializeResponse(stream, CancellationToken.None).ConfigureAwait(false); string responseString = await response.Content.ReadAsStringAsync(); var responseObject = Newtonsoft.Json.Linq.JObject.Parse(responseString); return(responseObject.Value <string>("digest")); } catch (System.Exception ex) { Console.WriteLine(ex.Message); return(null); } }
async Task SetHeadersAndContent(HttpResponseMessage httpResponse, HttpBufferedStream bufferedStream, CancellationToken cancellationToken) { IList <string> headers = new List <string>(); string line = await bufferedStream.ReadLineAsync(cancellationToken).ConfigureAwait(false); while (!string.IsNullOrWhiteSpace(line)) { headers.Add(line); line = await bufferedStream.ReadLineAsync(cancellationToken).ConfigureAwait(false); } httpResponse.Content = new StreamContent(bufferedStream); foreach (string header in headers) { if (string.IsNullOrWhiteSpace(header)) { // headers end break; } int headerSeparatorPosition = header.IndexOf(HeaderSeparator); if (headerSeparatorPosition <= 0) { throw new HttpRequestException($"Header is invalid {header}."); } string headerName = header.Substring(0, headerSeparatorPosition).Trim(); string headerValue = header.Substring(headerSeparatorPosition + 1).Trim(); bool headerAdded = httpResponse.Headers.TryAddWithoutValidation(headerName, headerValue); if (!headerAdded) { if (string.Equals(headerName, ContentLengthHeaderName, StringComparison.InvariantCultureIgnoreCase)) { if (!long.TryParse(headerValue, out long contentLength)) { throw new HttpRequestException($"Header value is invalid for {headerName}."); } await httpResponse.Content.LoadIntoBufferAsync(contentLength).ConfigureAwait(false); } httpResponse.Content.Headers.TryAddWithoutValidation(headerName, headerValue); } } }
public async Task TestDeserializeChunkedResponse_ValidContent_ShouldDeserialize_Sync() { var memory = new MemoryStream(ChunkedResponseBytes, true); var stream = new HttpBufferedStream(memory); CancellationToken cancellationToken = default(CancellationToken); HttpResponseMessage response = await new HttpRequestResponseSerializer().DeserializeResponse(stream, cancellationToken); Assert.Equal(response.Version, Version.Parse("1.1")); Assert.Equal(HttpStatusCode.OK, response.StatusCode); Assert.Equal("OK", response.ReasonPhrase); Assert.False(response.Content.Headers.ContentLength.HasValue); Stream responseStream = await response.Content.ReadAsStreamAsync(); byte[] responseBytes = ReadStreamSync(responseStream); string responseText = Encoding.UTF8.GetString(responseBytes); Assert.Equal(ChunkedResponseContentText, responseText); }