runtime icon indicating copy to clipboard operation
runtime copied to clipboard

Got System.IO.Exception When Expecting a Not-Found Response

Open shmao opened this issue 10 years ago • 20 comments

https://github.com/dotnet/wcf/issues/87 seems caused by an issue in System.Net. I have a repro for the issue. To repro the issue, you can add the following test in System.Net.Http.Functional.Tests and run the test.

        [Theory, MemberData("VerifyUploadServersStreamsAndExpectedData")]
        public async Task PostAsync_CallMethod_StreamContent_NotFound(Uri remoteServer, Stream requestContentStream, byte[] expectedData)
        {
            int contentLenght = 1000000;
            using (var client = new HttpClient())
            {
                // Ensure the service start
                HttpContent content = content = new StringContent(
                        "",
                        Encoding.UTF8,
                        "application/json");
                client.PutAsync("http://localhost:44283/resource/WcfService.TestResources.BasicHttpResource", content).GetAwaiter().GetResult();

                content = new StringContent(new string('a', contentLenght));
                content.Headers.ContentMD5 = TestHelper.ComputeMD5Hash(expectedData);

                using (HttpResponseMessage response = await client.PostAsync(new Uri("http://localhost:8081/BridgeAppDomain0/Basicnot-an-endpoint"), content))
                {
                    Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);
                }
            }
        }

Note that the test needs to use WCF's bridge service to repro the issue. The service is available on One Drive. To start the service, download the 'bridge folder', and run the script SetupWCFTestService.cmd in bridge\tools. You need to start the service on your machine before running the test.

Expect: the test passes. Actual: the test fails.

Please feel free to contact me if you have any questions. Thanks.

shmao avatar Dec 11 '15 01:12 shmao

@shmao What OS does this problem occur on? Windows? Linux? All OS's?

davidsh avatar Dec 11 '15 01:12 davidsh

I repro the issue on Windows. I didn't try it on Linux.

shmao avatar Dec 11 '15 02:12 shmao

I was able to repro this problem. First, I cleaned up the repro code a little bit since your test example was using a 'Theory' passing in arguments to the test method that weren't used at all.

Here is the updated code:

        [Fact]
        public async Task PostAsync_CallMethod_StringContent_NotFound()
        {
            int contentLength = 2000000;
            using (var client = new HttpClient())
            {
                // Ensure the service start
                var content = new StringContent(string.Empty, Encoding.UTF8, "application/json");
                client.PutAsync("http://localhost:44283/resource/WcfService.TestResources.BasicHttpResource", content).GetAwaiter().GetResult();

                // Post the big content
                content = new StringContent(new string('a', contentLength));
                string uri = "http://localhost:8081/BridgeAppDomain0/Basicnot-an-endpoint";
                using (HttpResponseMessage response = await client.PostAsync(new Uri(uri), content))
                {
                    Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);
                }
            }

I tried adjusting the value of the contentLength size and found it affected the repro at times.

The System.IOException that is being thrown is when the request body is being written out to the server. And inside that exception is a WinHttpException. That exception occurs on the very first call to WinHttpWriteData passing in the entire buffered request body. WinHTTP is returning back an error due to the server closing the socket abruptly with a TCP RST packet.

00000286 8:40:34 PM [24300] WinHttpCallback: handle=0x2184723389072, context=0x2184299679824, STATUS_REQUEST_ERROR
00000287 8:40:34 PM [24300] OnRequestError: api=API_WRITE_DATA, error=WINHTTP_CONNECTION_ERROR(12030) "The connection with the server was terminated abnormally"

Error 12030 is when the server closes the connection abruptly.

I don't understand fully the architecture of the server. However, if I try to post a very large content to one of our test server endpoints:

string uri = "http://corefx-networking.azurewebsites.net/Echo.ashx";

then I get no error at all.

So, I suspect that the server is the problem here and not the client. I would suggest looking at various traces in the server. Also, does this repro when you use a different server program? Or even, run this "bridge" server on a different machine rather than localhost.

davidsh avatar Dec 11 '15 17:12 davidsh

Since this is a server problem, I am going to close this issue for now. Feel free add more comments and/or re-open the issue if you have more information that this is a client issue. Thx.

davidsh avatar Dec 11 '15 17:12 davidsh

cc: @roncain

davidsh avatar Dec 11 '15 17:12 davidsh

cc: @mconnew

shmao avatar Dec 11 '15 17:12 shmao

@davidsh Thanks for the investigation. I wasn't able to repro the issue with any other server program either. I, however, couldn't repro the issue with the desktop version HttpClient. Therefore I thought this may be still related to the netcore HttpClient.

Here is the code I used for desktop.

    while (true)
    {
        int contentLenght = 10000000;
        using (var client = new HttpClient())
        {
            // Ensure the service start
            HttpContent content = content = new StringContent(
                    "",
                    Encoding.UTF8,
                    "application/json");
            client.PutAsync("http://localhost:44283/resource/WcfService.TestResources.BasicHttpResource", content).GetAwaiter().GetResult();

            content = new StringContent(new string('a', contentLenght));
            content.Headers.ContentMD5 = new byte[] {1,2,3,4 };


            using (HttpResponseMessage response = client.PostAsync(new Uri("http://localhost:8081/BridgeAppDomain0/Basicnot-an-endpoint"), content).Result)
            {
                Console.WriteLine(response.StatusCode);
            }
        }
    }

shmao avatar Dec 11 '15 18:12 shmao

I suspect that the variability in getting a repro is a timing/race condition issue. The .NET Desktop HTTP stack is very different and the timings will be different. I noticed, for example, that if I left the bridge server running a long time and then re-tried to repro the problem, I could not at times.

I think the best thing to do is to turn on all possible traces in this server. It is sometimes difficult to use NetMon/WireShark when dealing with localhost servers. So, it would be best if you could place the bridge server on another machine and repro the problem. I suggest you take WireShark traces on the server and then you can see more details about the TCP packets it is sending back to the client.

davidsh avatar Dec 11 '15 18:12 davidsh

I collected the server side traces (see attached) using Message Analyzer.

The test was to make the above repro code to send a string to a not-found address of the above mentioned bridge server. The expected result was the client getting Not-Found as response; in the error case, the result was the client getting IO exception.

There are two trace files in the attached, one for the success case and the other for the error case. In the success case, the client was able to send the whole content to the server; while in the error case, the client didn't send out the actual content.

@davidsh can you please have a look at the traces? Can we make the client handle this case?

MessageAnalyzer_Traces.zip (Note: applying filter 'tcp.Port=8081' would show you the related messages)

shmao avatar Jan 06 '16 22:01 shmao

@davidsh can you please have a look at the traces? Can we make the client handle this case?

What are you expecting the client to do in order to "handle this case"? We can't turn an IO exception into a valid HTTP response. The client is simply reacting to the network interruption and thus passing up the IO exception up the stack.

So, what exactly is the error case you want the client (HttpClient) to do better at?

davidsh avatar Jan 06 '16 22:01 davidsh

I did the test with the client of the desktop version, and it didn't throw the IO exception. I know "the .NET Desktop HTTP stack is very different and the timings will be different". However, from the trace, the desktop client seems able to handle similar sequence of messages that occurred in the error case.

DesktopClient_BridgeServer.zip

shmao avatar Jan 06 '16 22:01 shmao

I don't see any errors in the NotFound_Error trace. The _Error trace is smaller than the _Success trace. But both traces show an HTTP request and response (NOTFOUND).

davidsh avatar Jan 06 '16 22:01 davidsh

Right, there is no error in the _Error trace and both traces show NOTFOUND response. But the client threw IO exception when I collected the _Error trace.

shmao avatar Jan 06 '16 22:01 shmao

I looked at the traces.

It appears that your server is violating the RFCs for HTTP. In the "Success" case, the entire HTTP response is sent back (headers and HTML 'not-found page' payload) as one 492 byte TCP packet. However, the server appears to keep sending data and the data is "garbage" (lots of 'a' characters).

The .NET Desktop HTTP stack apparently is not as strict for checking this sort of thing. But in the "Error" case trace, the 492 byte TCP packet payload comes back fine and then after a few TCP FIN/ACK packets, the traces stop. The traces stop because the low level HTTP stack (native WinHTTP) detects a violation of the HTTP RFC, i.e. the server is continuing to send data back...more data than the 'Content-Length' of the HTTP response says should be there.

What are all the 'a' characters of payload that the server is sending back? This seems like a bug in your server. And actually, you could say we have a bug in .NET Desktop because we aren't strict enough to check for violations like that.

davidsh avatar Jan 06 '16 23:01 davidsh

The 'a' characters is the StringContent sent by the client to the server.

content = new StringContent(new string('a', contentLenght));

It's that the client keep sending the content to the server after the server already sent the NOTFOUND response.

(port 8081 is the server side port.)

shmao avatar Jan 06 '16 23:01 shmao

ok. Thx for the clarifications and sorry for the confusion. I've reviewed the TCP traces with some WinHTTP folks and it appears that we do need to fix a bug here.

In both .NET Framework (Desktop) and CoreFx, the server is sending back a valid HTTP response quickly. However, the POST data is being transmitted still even though the server has sent back a response and closed the TCP connection.

In the .NET Framework (Desktop) case, the HTTP stack receives the TCP FIN from the server but it DOES NOT send back a TCP FIN to close its side of the connection until it has finished sending all of the POST data payload. In some ways, you could say this is a performance problem for the Desktop stack. After the payload has been sent to the server (which probably ignores it), the client side sends its TCP FIN and closes the connection.

In the CoreFx case, the TCP connection logic is in the native WinHTTP layer. And it is very fast in terms of what it does when it receives the HTTP response and subsequent TCP FIN (connection close) from the server. It sends back the TCP FIN from the client and fully closes the connection.

Meanwhile, our .NET layer (WinHttpHandler) is still trying to send the POST data and hasn't even had a chance to read the HTTP response itself yet. Sending the POST data fails with IOException because the connection has been closed.

So, bottom line, we do need to ignore this IOException in some way while writing out the POST data and treat the HTTP request/response as Success because we received a valid HTTP response (headers and payload) from the server.

We will investigate a fix.

davidsh avatar Jan 06 '16 23:01 davidsh

Sounds good. Thanks for the investigation, David.

shmao avatar Jan 06 '16 23:01 shmao

@davidsh, another interesting point about .Net on Desktop is WCF wouldn't see this happen even if HttpWebRequest had the same behavior as WinHTTP. On Desktop, WCF makes use of Expect: 100-Continue so wouldn't even try to send the payload as it would get the 404 response before attempting to send the request body. As the Expect 100 behavior is turned on by default with HttpWebRequest, the performance problem you mentioned isn't an issue in many cases.

mconnew avatar Jan 06 '16 23:01 mconnew

It has been determined by the WinHTTP team that the IOException is being caused by a bug/race condition in native WinHTTP. There is no current workaround. Even ignoring the error from WinHttpWriteData() will not allow a subsequent WinHttpReceiveResponse() to work, despite the response headers actually being transmitted on the wire from the server to the client.

So, the fix for this will require a Windows OS fix in a future Windows 10 update

davidsh avatar Feb 21 '16 03:02 davidsh

@shmao

The WinHTTP team has fixed this bug in the native WinHTTP layer. The fix will be available in the Windows 10 update released later this year. You can try out the public flights of Windows 10 to confirm that your scenario is fixed.

Closing this issue.

davidsh avatar Jun 02 '16 16:06 davidsh