IIS 7.0 - HTTP 502.2 - Bad Gateway

Recently I got a couple of support cases where customers who migrated their CGI applications over to IIS 7.0 on Windows Server 2008 ran into the following error:

ERROR: HTTP Error 502.2 - Bad Gateway

The specified CGI application misbehaved by not returning a complete set of HTTP headers. The headers it did return are "".

CAUSE

We performed a live debug using Debugging tools for Windows and figured that the CGI module was failing with an error:

GetStdHandle(STD_INPUT_HANDLE) failed.
LastErrorValue: (Win32) 0x6 (6) - The handle is invalid.
LastStatusValue: (NTSTATUS) 0xc0000008 - An invalid HANDLE was specified.

We also figured that this is an issue specific to IIS 7.0. The GetStdHandle() call fails with invalid handle on IIS7 because IIS 7 expects the content length when you try to use STDIN handle. If you provide some content, then you may notice that you do not get this error.

RESOLUTION

Check for content length before calling STDIN. I am attaching a sample code provided by a colleague with this blog post that will demonstrate how to fix this problem.

SampleCode.txt