byte [] GetHeaders() { var basicHeaders = new StringBuilder(); basicHeaders.Append(protocol); if (statusCode == 200) { basicHeaders.Append(" 200 "); } else { basicHeaders.Append(' '); basicHeaders.Append(statusCode.ToString(CultureInfo.InvariantCulture)); basicHeaders.Append(' '); } basicHeaders.Append(statusDescription); basicHeaders.Append("\r\nDate: "); basicHeaders.Append(DateTime.UtcNow.ToString("r", CultureInfo.InvariantCulture)); basicHeaders.Append(serverHeader); responseHeaders.Insert(0, basicHeaders.ToString()); if (!sentConnection) { if (!haveContentLength) { keepAlive = false; } AddConnectionHeader(); } responseHeaders.Append("\r\n"); return(HeaderEncoding.GetBytes(responseHeaders.ToString())); }
private void EnsureHeadersSent() { if (headers != null) { headers.Append("\r\n"); string str = headers.ToString(); byte[] data = HeaderEncoding.GetBytes(str); transport.SendOutput(requestId, requestNumber, data, data.Length); headers = null; } }
/*++ * * ToByteArray() - * * Routine Description: * * Generates a byte array representation of the headers, that is ready to be sent. * So it Serializes our headers into a byte array suitable for sending over the net. * * the format looks like: * * Header-Name1: Header-Value1\r\n * Header-Name2: Header-Value2\r\n * ... * Header-NameN: Header-ValueN\r\n * \r\n * * Uses the ToString() method to generate, and then performs conversion. * * Performance Note: Why are we not doing a single copy/covert run? * As the code before used to know the size of the output! * Because according to Demitry, its cheaper to copy the headers twice, * then it is to call the UNICODE to ANSI conversion code many times. * * Arguments: * * None. * * Return Value: * * byte [] - array of bytes values * * --*/ /// <include file='doc\WebHeaders.uex' path='docs/doc[@for="WebHeaderCollection.ToByteArray"]/*' /> /// <internalonly/> /// <devdoc> /// <para> /// Obsolete. /// </para> /// </devdoc> public byte[] ToByteArray() { // Make sure the buffer is big enough. string tempStr = ToString(); // // Use the string of headers, convert to Char Array, // then convert to Bytes, // serializing finally into the buffer, along the way. // byte[] buffer = HeaderEncoding.GetBytes(tempStr); return(buffer); }
byte [] GetHeaders() { responseHeaders.Insert(0, status); if (!sentConnection) { if (!haveContentLength) { keepAlive = false; } AddConnectionHeader(); } responseHeaders.Append("\r\n"); return(HeaderEncoding.GetBytes(responseHeaders.ToString())); }
/// <summary> /// Get message body /// </summary> /// <returns></returns> public List <byte> GetBody() { var builder = new List <byte>(1024); // headers builder.AddRange(header.Encode(headerEncoding)); // delimeter builder.AddRange(HeaderEncoding.GetBytes(Util.CRLF)); if (IsMultipart) { builder.AddRange( Encoding.GetBytes("This is a multi-part message in MIME format." + Util.CRLF + Util.CRLF)); } builder.AddRange(GetBodyContent()); return(builder); }
internal unsafe void SendError(ulong requestId, int httpStatusCode, IList <string>?authChallenges = null) { HttpApiTypes.HTTP_RESPONSE_V2 httpResponse = new HttpApiTypes.HTTP_RESPONSE_V2(); httpResponse.Response_V1.Version = new HttpApiTypes.HTTP_VERSION(); httpResponse.Response_V1.Version.MajorVersion = (ushort)1; httpResponse.Response_V1.Version.MinorVersion = (ushort)1; List <GCHandle>?pinnedHeaders = null; GCHandle gcHandle; try { // Copied from the multi-value headers section of SerializeHeaders if (authChallenges != null && authChallenges.Count > 0) { pinnedHeaders = new List <GCHandle>(authChallenges.Count + 3); HttpApiTypes.HTTP_RESPONSE_INFO[] knownHeaderInfo = new HttpApiTypes.HTTP_RESPONSE_INFO[1]; gcHandle = GCHandle.Alloc(knownHeaderInfo, GCHandleType.Pinned); pinnedHeaders.Add(gcHandle); httpResponse.pResponseInfo = (HttpApiTypes.HTTP_RESPONSE_INFO *)gcHandle.AddrOfPinnedObject(); knownHeaderInfo[httpResponse.ResponseInfoCount].Type = HttpApiTypes.HTTP_RESPONSE_INFO_TYPE.HttpResponseInfoTypeMultipleKnownHeaders; knownHeaderInfo[httpResponse.ResponseInfoCount].Length = (uint)Marshal.SizeOf <HttpApiTypes.HTTP_MULTIPLE_KNOWN_HEADERS>(); HttpApiTypes.HTTP_MULTIPLE_KNOWN_HEADERS header = new HttpApiTypes.HTTP_MULTIPLE_KNOWN_HEADERS(); header.HeaderId = HttpApiTypes.HTTP_RESPONSE_HEADER_ID.Enum.HttpHeaderWwwAuthenticate; header.Flags = HttpApiTypes.HTTP_RESPONSE_INFO_FLAGS.PreserveOrder; // The docs say this is for www-auth only. HttpApiTypes.HTTP_KNOWN_HEADER[] nativeHeaderValues = new HttpApiTypes.HTTP_KNOWN_HEADER[authChallenges.Count]; gcHandle = GCHandle.Alloc(nativeHeaderValues, GCHandleType.Pinned); pinnedHeaders.Add(gcHandle); header.KnownHeaders = (HttpApiTypes.HTTP_KNOWN_HEADER *)gcHandle.AddrOfPinnedObject(); for (int headerValueIndex = 0; headerValueIndex < authChallenges.Count; headerValueIndex++) { // Add Value string headerValue = authChallenges[headerValueIndex]; byte[] bytes = HeaderEncoding.GetBytes(headerValue); nativeHeaderValues[header.KnownHeaderCount].RawValueLength = (ushort)bytes.Length; gcHandle = GCHandle.Alloc(bytes, GCHandleType.Pinned); pinnedHeaders.Add(gcHandle); nativeHeaderValues[header.KnownHeaderCount].pRawValue = (byte *)gcHandle.AddrOfPinnedObject(); header.KnownHeaderCount++; } // This type is a struct, not an object, so pinning it causes a boxed copy to be created. We can't do that until after all the fields are set. gcHandle = GCHandle.Alloc(header, GCHandleType.Pinned); pinnedHeaders.Add(gcHandle); knownHeaderInfo[0].pInfo = (HttpApiTypes.HTTP_MULTIPLE_KNOWN_HEADERS *)gcHandle.AddrOfPinnedObject(); httpResponse.ResponseInfoCount = 1; } httpResponse.Response_V1.StatusCode = (ushort)httpStatusCode; string?statusDescription = HttpReasonPhrase.Get(httpStatusCode); uint dataWritten = 0; uint statusCode; byte[] byteReason = statusDescription != null?HeaderEncoding.GetBytes(statusDescription) : Array.Empty <byte>(); fixed(byte *pReason = byteReason) { httpResponse.Response_V1.pReason = (byte *)pReason; httpResponse.Response_V1.ReasonLength = (ushort)byteReason.Length; byte[] byteContentLength = new byte[] { (byte)'0' }; fixed(byte *pContentLength = byteContentLength) { (&httpResponse.Response_V1.Headers.KnownHeaders)[(int)HttpSysResponseHeader.ContentLength].pRawValue = (byte *)pContentLength; (&httpResponse.Response_V1.Headers.KnownHeaders)[(int)HttpSysResponseHeader.ContentLength].RawValueLength = (ushort)byteContentLength.Length; httpResponse.Response_V1.Headers.UnknownHeaderCount = 0; statusCode = HttpApi.HttpSendHttpResponse( _requestQueue.Handle, requestId, 0, &httpResponse, null, &dataWritten, IntPtr.Zero, 0, SafeNativeOverlapped.Zero, IntPtr.Zero); } } if (statusCode != UnsafeNclNativeMethods.ErrorCodes.ERROR_SUCCESS) { // if we fail to send a 401 something's seriously wrong, abort the request HttpApi.HttpCancelHttpRequest(_requestQueue.Handle, requestId, IntPtr.Zero); } } finally { if (pinnedHeaders != null) { foreach (GCHandle handle in pinnedHeaders) { if (handle.IsAllocated) { handle.Free(); } } } } }
internal unsafe void SerializeTrailers(HttpApiTypes.HTTP_DATA_CHUNK[] dataChunks, int currentChunk, List <GCHandle> pins) { Debug.Assert(currentChunk == dataChunks.Length - 1); Debug.Assert(HasTrailers); MakeTrailersReadOnly(); var trailerCount = 0; foreach (var trailerPair in Trailers) { trailerCount += trailerPair.Value.Count; } var pinnedHeaders = new List <GCHandle>(); var unknownHeaders = new HttpApiTypes.HTTP_UNKNOWN_HEADER[trailerCount]; var gcHandle = GCHandle.Alloc(unknownHeaders, GCHandleType.Pinned); pinnedHeaders.Add(gcHandle); dataChunks[currentChunk].DataChunkType = HttpApiTypes.HTTP_DATA_CHUNK_TYPE.HttpDataChunkTrailers; dataChunks[currentChunk].trailers.trailerCount = (ushort)trailerCount; dataChunks[currentChunk].trailers.pTrailers = gcHandle.AddrOfPinnedObject(); try { var unknownHeadersOffset = 0; foreach (var headerPair in Trailers) { if (headerPair.Value.Count == 0) { continue; } var headerName = headerPair.Key; var headerValues = headerPair.Value; for (int headerValueIndex = 0; headerValueIndex < headerValues.Count; headerValueIndex++) { // Add Name var bytes = HeaderEncoding.GetBytes(headerName); unknownHeaders[unknownHeadersOffset].NameLength = (ushort)bytes.Length; gcHandle = GCHandle.Alloc(bytes, GCHandleType.Pinned); pinnedHeaders.Add(gcHandle); unknownHeaders[unknownHeadersOffset].pName = (byte *)gcHandle.AddrOfPinnedObject(); // Add Value var headerValue = headerValues[headerValueIndex] ?? string.Empty; bytes = HeaderEncoding.GetBytes(headerValue); unknownHeaders[unknownHeadersOffset].RawValueLength = (ushort)bytes.Length; gcHandle = GCHandle.Alloc(bytes, GCHandleType.Pinned); pinnedHeaders.Add(gcHandle); unknownHeaders[unknownHeadersOffset].pRawValue = (byte *)gcHandle.AddrOfPinnedObject(); unknownHeadersOffset++; } } Debug.Assert(unknownHeadersOffset == trailerCount); } catch { FreePinnedHeaders(pinnedHeaders); throw; } // Success, keep the pins. pins.AddRange(pinnedHeaders); }
private unsafe List <GCHandle>?SerializeHeaders(bool isOpaqueUpgrade) { Headers.IsReadOnly = true; // Prohibit further modifications. HttpApiTypes.HTTP_UNKNOWN_HEADER[]? unknownHeaders = null; HttpApiTypes.HTTP_RESPONSE_INFO[]? knownHeaderInfo = null; List <GCHandle> pinnedHeaders; GCHandle gcHandle; if (Headers.Count == 0) { return(null); } string headerName; string headerValue; int lookup; byte[]? bytes = null; pinnedHeaders = new List <GCHandle>(); int numUnknownHeaders = 0; int numKnownMultiHeaders = 0; foreach (var headerPair in Headers) { if (headerPair.Value.Count == 0) { continue; } // See if this is an unknown header lookup = HttpApiTypes.HTTP_RESPONSE_HEADER_ID.IndexOfKnownHeader(headerPair.Key); // Http.Sys doesn't let us send the Connection: Upgrade header as a Known header. if (lookup == -1 || (isOpaqueUpgrade && lookup == (int)HttpApiTypes.HTTP_RESPONSE_HEADER_ID.Enum.HttpHeaderConnection)) { numUnknownHeaders += headerPair.Value.Count; } else if (headerPair.Value.Count > 1) { numKnownMultiHeaders++; } // else known single-value header. } try { fixed(HttpApiTypes.HTTP_KNOWN_HEADER *pKnownHeaders = &_nativeResponse.Response_V1.Headers.KnownHeaders) { foreach (var headerPair in Headers) { if (headerPair.Value.Count == 0) { continue; } headerName = headerPair.Key; StringValues headerValues = headerPair.Value; lookup = HttpApiTypes.HTTP_RESPONSE_HEADER_ID.IndexOfKnownHeader(headerName); // Http.Sys doesn't let us send the Connection: Upgrade header as a Known header. if (lookup == -1 || (isOpaqueUpgrade && lookup == (int)HttpApiTypes.HTTP_RESPONSE_HEADER_ID.Enum.HttpHeaderConnection)) { if (unknownHeaders == null) { unknownHeaders = new HttpApiTypes.HTTP_UNKNOWN_HEADER[numUnknownHeaders]; gcHandle = GCHandle.Alloc(unknownHeaders, GCHandleType.Pinned); pinnedHeaders.Add(gcHandle); _nativeResponse.Response_V1.Headers.pUnknownHeaders = (HttpApiTypes.HTTP_UNKNOWN_HEADER *)gcHandle.AddrOfPinnedObject(); } for (int headerValueIndex = 0; headerValueIndex < headerValues.Count; headerValueIndex++) { // Add Name bytes = HeaderEncoding.GetBytes(headerName); unknownHeaders[_nativeResponse.Response_V1.Headers.UnknownHeaderCount].NameLength = (ushort)bytes.Length; gcHandle = GCHandle.Alloc(bytes, GCHandleType.Pinned); pinnedHeaders.Add(gcHandle); unknownHeaders[_nativeResponse.Response_V1.Headers.UnknownHeaderCount].pName = (byte *)gcHandle.AddrOfPinnedObject(); // Add Value headerValue = headerValues[headerValueIndex] ?? string.Empty; bytes = HeaderEncoding.GetBytes(headerValue); unknownHeaders[_nativeResponse.Response_V1.Headers.UnknownHeaderCount].RawValueLength = (ushort)bytes.Length; gcHandle = GCHandle.Alloc(bytes, GCHandleType.Pinned); pinnedHeaders.Add(gcHandle); unknownHeaders[_nativeResponse.Response_V1.Headers.UnknownHeaderCount].pRawValue = (byte *)gcHandle.AddrOfPinnedObject(); _nativeResponse.Response_V1.Headers.UnknownHeaderCount++; } } else if (headerPair.Value.Count == 1) { headerValue = headerValues[0] ?? string.Empty; bytes = HeaderEncoding.GetBytes(headerValue); pKnownHeaders[lookup].RawValueLength = (ushort)bytes.Length; gcHandle = GCHandle.Alloc(bytes, GCHandleType.Pinned); pinnedHeaders.Add(gcHandle); pKnownHeaders[lookup].pRawValue = (byte *)gcHandle.AddrOfPinnedObject(); } else { if (knownHeaderInfo == null) { knownHeaderInfo = new HttpApiTypes.HTTP_RESPONSE_INFO[numKnownMultiHeaders]; gcHandle = GCHandle.Alloc(knownHeaderInfo, GCHandleType.Pinned); pinnedHeaders.Add(gcHandle); _nativeResponse.pResponseInfo = (HttpApiTypes.HTTP_RESPONSE_INFO *)gcHandle.AddrOfPinnedObject(); } knownHeaderInfo[_nativeResponse.ResponseInfoCount].Type = HttpApiTypes.HTTP_RESPONSE_INFO_TYPE.HttpResponseInfoTypeMultipleKnownHeaders; knownHeaderInfo[_nativeResponse.ResponseInfoCount].Length = (uint)Marshal.SizeOf <HttpApiTypes.HTTP_MULTIPLE_KNOWN_HEADERS>(); HttpApiTypes.HTTP_MULTIPLE_KNOWN_HEADERS header = new HttpApiTypes.HTTP_MULTIPLE_KNOWN_HEADERS(); header.HeaderId = (HttpApiTypes.HTTP_RESPONSE_HEADER_ID.Enum)lookup; header.Flags = HttpApiTypes.HTTP_RESPONSE_INFO_FLAGS.PreserveOrder; // TODO: The docs say this is for www-auth only. HttpApiTypes.HTTP_KNOWN_HEADER[] nativeHeaderValues = new HttpApiTypes.HTTP_KNOWN_HEADER[headerValues.Count]; gcHandle = GCHandle.Alloc(nativeHeaderValues, GCHandleType.Pinned); pinnedHeaders.Add(gcHandle); header.KnownHeaders = (HttpApiTypes.HTTP_KNOWN_HEADER *)gcHandle.AddrOfPinnedObject(); for (int headerValueIndex = 0; headerValueIndex < headerValues.Count; headerValueIndex++) { // Add Value headerValue = headerValues[headerValueIndex] ?? string.Empty; bytes = HeaderEncoding.GetBytes(headerValue); nativeHeaderValues[header.KnownHeaderCount].RawValueLength = (ushort)bytes.Length; gcHandle = GCHandle.Alloc(bytes, GCHandleType.Pinned); pinnedHeaders.Add(gcHandle); nativeHeaderValues[header.KnownHeaderCount].pRawValue = (byte *)gcHandle.AddrOfPinnedObject(); header.KnownHeaderCount++; } // This type is a struct, not an object, so pinning it causes a boxed copy to be created. We can't do that until after all the fields are set. gcHandle = GCHandle.Alloc(header, GCHandleType.Pinned); pinnedHeaders.Add(gcHandle); knownHeaderInfo[_nativeResponse.ResponseInfoCount].pInfo = (HttpApiTypes.HTTP_MULTIPLE_KNOWN_HEADERS *)gcHandle.AddrOfPinnedObject(); _nativeResponse.ResponseInfoCount++; } } } } catch { FreePinnedHeaders(pinnedHeaders); throw; } return(pinnedHeaders); }
/* * 12.3 * HttpSendHttpResponse() and HttpSendResponseEntityBody() Flag Values. * The following flags can be used on calls to HttpSendHttpResponse() and HttpSendResponseEntityBody() API calls: * #define HTTP_SEND_RESPONSE_FLAG_DISCONNECT 0x00000001 #define HTTP_SEND_RESPONSE_FLAG_MORE_DATA 0x00000002 #define HTTP_SEND_RESPONSE_FLAG_RAW_HEADER 0x00000004 #define HTTP_SEND_RESPONSE_FLAG_VALID 0x00000007 * * HTTP_SEND_RESPONSE_FLAG_DISCONNECT: * specifies that the network connection should be disconnected immediately after * sending the response, overriding the HTTP protocol's persistent connection features. * HTTP_SEND_RESPONSE_FLAG_MORE_DATA: * specifies that additional entity body data will be sent by the caller. Thus, * the last call HttpSendResponseEntityBody for a RequestId, will have this flag reset. * HTTP_SEND_RESPONSE_RAW_HEADER: * specifies that a caller of HttpSendResponseEntityBody() is intentionally omitting * a call to HttpSendHttpResponse() in order to bypass normal header processing. The * actual HTTP header will be generated by the application and sent as entity body. * This flag should be passed on the first call to HttpSendResponseEntityBody, and * not after. Thus, flag is not applicable to HttpSendHttpResponse. */ // TODO: Consider using HTTP_SEND_RESPONSE_RAW_HEADER with HttpSendResponseEntityBody instead of calling HttpSendHttpResponse. // This will give us more control of the bytes that hit the wire, including encodings, HTTP 1.0, etc.. // It may also be faster to do this work in managed code and then pass down only one buffer. // What would we loose by bypassing HttpSendHttpResponse? // // TODO: Consider using the HTTP_SEND_RESPONSE_FLAG_BUFFER_DATA flag for most/all responses rather than just Opaque. internal unsafe uint SendHeaders(HttpApiTypes.HTTP_DATA_CHUNK[]?dataChunks, ResponseStreamAsyncResult?asyncResult, HttpApiTypes.HTTP_FLAGS flags, bool isOpaqueUpgrade) { Debug.Assert(!HasStarted, "HttpListenerResponse::SendHeaders()|SentHeaders is true."); _responseState = ResponseState.Started; var reasonPhrase = GetReasonPhrase(StatusCode); uint statusCode; uint bytesSent; List <GCHandle>?pinnedHeaders = SerializeHeaders(isOpaqueUpgrade); try { if (dataChunks != null) { if (pinnedHeaders == null) { pinnedHeaders = new List <GCHandle>(); } var handle = GCHandle.Alloc(dataChunks, GCHandleType.Pinned); pinnedHeaders.Add(handle); _nativeResponse.Response_V1.EntityChunkCount = (ushort)dataChunks.Length; _nativeResponse.Response_V1.pEntityChunks = (HttpApiTypes.HTTP_DATA_CHUNK *)handle.AddrOfPinnedObject(); } else if (asyncResult != null && asyncResult.DataChunks != null) { _nativeResponse.Response_V1.EntityChunkCount = asyncResult.DataChunkCount; _nativeResponse.Response_V1.pEntityChunks = asyncResult.DataChunks; } else { _nativeResponse.Response_V1.EntityChunkCount = 0; _nativeResponse.Response_V1.pEntityChunks = null; } var cachePolicy = new HttpApiTypes.HTTP_CACHE_POLICY(); if (_cacheTtl.HasValue && _cacheTtl.Value > TimeSpan.Zero) { cachePolicy.Policy = HttpApiTypes.HTTP_CACHE_POLICY_TYPE.HttpCachePolicyTimeToLive; cachePolicy.SecondsToLive = (uint)Math.Min(_cacheTtl.Value.Ticks / TimeSpan.TicksPerSecond, Int32.MaxValue); } byte[] reasonPhraseBytes = HeaderEncoding.GetBytes(reasonPhrase); fixed(byte *pReasonPhrase = reasonPhraseBytes) { _nativeResponse.Response_V1.ReasonLength = (ushort)reasonPhraseBytes.Length; _nativeResponse.Response_V1.pReason = (byte *)pReasonPhrase; fixed(HttpApiTypes.HTTP_RESPONSE_V2 *pResponse = &_nativeResponse) { statusCode = HttpApi.HttpSendHttpResponse( RequestContext.Server.RequestQueue.Handle, Request.RequestId, (uint)flags, pResponse, &cachePolicy, &bytesSent, IntPtr.Zero, 0, asyncResult == null ? SafeNativeOverlapped.Zero : asyncResult.NativeOverlapped !, IntPtr.Zero); // GoAway is only supported on later versions. Retry. if (statusCode == ErrorCodes.ERROR_INVALID_PARAMETER && (flags & HttpApiTypes.HTTP_FLAGS.HTTP_SEND_RESPONSE_FLAG_GOAWAY) != 0) { flags &= ~HttpApiTypes.HTTP_FLAGS.HTTP_SEND_RESPONSE_FLAG_GOAWAY; statusCode = HttpApi.HttpSendHttpResponse( RequestContext.Server.RequestQueue.Handle, Request.RequestId, (uint)flags, pResponse, &cachePolicy, &bytesSent, IntPtr.Zero, 0, asyncResult == null ? SafeNativeOverlapped.Zero : asyncResult.NativeOverlapped !, IntPtr.Zero); // Succeeded without GoAway, disable them. if (statusCode != ErrorCodes.ERROR_INVALID_PARAMETER) { SupportsGoAway = false; } } if (asyncResult != null && statusCode == ErrorCodes.ERROR_SUCCESS && HttpSysListener.SkipIOCPCallbackOnSuccess) { asyncResult.BytesSent = bytesSent; // The caller will invoke IOCompleted } } } } finally { FreePinnedHeaders(pinnedHeaders); } return(statusCode); }
// From HttpSys, except does not write to response private unsafe List <GCHandle> SerializeHeaders(HttpApiTypes.HTTP_RESPONSE_V2 *pHttpResponse) { HttpResponseHeaders.IsReadOnly = true; HttpApiTypes.HTTP_UNKNOWN_HEADER[] unknownHeaders = null; HttpApiTypes.HTTP_RESPONSE_INFO[] knownHeaderInfo = null; var pinnedHeaders = new List <GCHandle>(); GCHandle gcHandle; if (HttpResponseHeaders.Count == 0) { return(null); } string headerName; string headerValue; int lookup; var numUnknownHeaders = 0; int numKnownMultiHeaders = 0; byte[] bytes = null; foreach (var headerPair in HttpResponseHeaders) { if (headerPair.Value.Count == 0) { continue; } lookup = HttpApiTypes.HTTP_RESPONSE_HEADER_ID.IndexOfKnownHeader(headerPair.Key); if (lookup == -1) // TODO handle opaque stream upgrade? { numUnknownHeaders++; } else if (headerPair.Value.Count > 1) { numKnownMultiHeaders++; } } try { var pKnownHeaders = &pHttpResponse->Response_V1.Headers.KnownHeaders; foreach (var headerPair in HttpResponseHeaders) { if (headerPair.Value.Count == 0) { continue; } headerName = headerPair.Key; StringValues headerValues = headerPair.Value; lookup = HttpApiTypes.HTTP_RESPONSE_HEADER_ID.IndexOfKnownHeader(headerName); if (lookup == -1) { if (unknownHeaders == null) { unknownHeaders = new HttpApiTypes.HTTP_UNKNOWN_HEADER[numUnknownHeaders]; gcHandle = GCHandle.Alloc(unknownHeaders, GCHandleType.Pinned); pinnedHeaders.Add(gcHandle); pHttpResponse->Response_V1.Headers.pUnknownHeaders = (HttpApiTypes.HTTP_UNKNOWN_HEADER *)gcHandle.AddrOfPinnedObject(); pHttpResponse->Response_V1.Headers.UnknownHeaderCount = 0; // to remove the iis header for server=... } for (var headerValueIndex = 0; headerValueIndex < headerValues.Count; headerValueIndex++) { // Add Name bytes = HeaderEncoding.GetBytes(headerName); unknownHeaders[pHttpResponse->Response_V1.Headers.UnknownHeaderCount].NameLength = (ushort)bytes.Length; gcHandle = GCHandle.Alloc(bytes, GCHandleType.Pinned); pinnedHeaders.Add(gcHandle); unknownHeaders[pHttpResponse->Response_V1.Headers.UnknownHeaderCount].pName = (byte *)gcHandle.AddrOfPinnedObject(); // Add Value headerValue = headerValues[headerValueIndex] ?? string.Empty; bytes = HeaderEncoding.GetBytes(headerValue); unknownHeaders[pHttpResponse->Response_V1.Headers.UnknownHeaderCount].RawValueLength = (ushort)bytes.Length; gcHandle = GCHandle.Alloc(bytes, GCHandleType.Pinned); pinnedHeaders.Add(gcHandle); unknownHeaders[pHttpResponse->Response_V1.Headers.UnknownHeaderCount].pRawValue = (byte *)gcHandle.AddrOfPinnedObject(); pHttpResponse->Response_V1.Headers.UnknownHeaderCount++; } } else if (headerPair.Value.Count == 1) { headerValue = headerValues[0] ?? string.Empty; bytes = HeaderEncoding.GetBytes(headerValue); pKnownHeaders[lookup].RawValueLength = (ushort)bytes.Length; gcHandle = GCHandle.Alloc(bytes, GCHandleType.Pinned); pinnedHeaders.Add(gcHandle); pKnownHeaders[lookup].pRawValue = (byte *)gcHandle.AddrOfPinnedObject(); } else { if (knownHeaderInfo == null) { knownHeaderInfo = new HttpApiTypes.HTTP_RESPONSE_INFO[numKnownMultiHeaders]; gcHandle = GCHandle.Alloc(knownHeaderInfo, GCHandleType.Pinned); pinnedHeaders.Add(gcHandle); pHttpResponse->pResponseInfo = (HttpApiTypes.HTTP_RESPONSE_INFO *)gcHandle.AddrOfPinnedObject(); } knownHeaderInfo[pHttpResponse->ResponseInfoCount].Type = HttpApiTypes.HTTP_RESPONSE_INFO_TYPE.HttpResponseInfoTypeMultipleKnownHeaders; knownHeaderInfo[pHttpResponse->ResponseInfoCount].Length = (uint)Marshal.SizeOf <HttpApiTypes.HTTP_MULTIPLE_KNOWN_HEADERS>(); var header = new HttpApiTypes.HTTP_MULTIPLE_KNOWN_HEADERS(); header.HeaderId = (HttpApiTypes.HTTP_RESPONSE_HEADER_ID.Enum)lookup; header.Flags = HttpApiTypes.HTTP_RESPONSE_INFO_FLAGS.PreserveOrder; // TODO: The docs say this is for www-auth only. var nativeHeaderValues = new HttpApiTypes.HTTP_KNOWN_HEADER[headerValues.Count]; gcHandle = GCHandle.Alloc(nativeHeaderValues, GCHandleType.Pinned); pinnedHeaders.Add(gcHandle); header.KnownHeaders = (HttpApiTypes.HTTP_KNOWN_HEADER *)gcHandle.AddrOfPinnedObject(); for (int headerValueIndex = 0; headerValueIndex < headerValues.Count; headerValueIndex++) { // Add Value headerValue = headerValues[headerValueIndex] ?? string.Empty; bytes = HeaderEncoding.GetBytes(headerValue); nativeHeaderValues[header.KnownHeaderCount].RawValueLength = (ushort)bytes.Length; gcHandle = GCHandle.Alloc(bytes, GCHandleType.Pinned); pinnedHeaders.Add(gcHandle); nativeHeaderValues[header.KnownHeaderCount].pRawValue = (byte *)gcHandle.AddrOfPinnedObject(); header.KnownHeaderCount++; } // This type is a struct, not an object, so pinning it causes a boxed copy to be created. We can't do that until after all the fields are set. gcHandle = GCHandle.Alloc(header, GCHandleType.Pinned); pinnedHeaders.Add(gcHandle); knownHeaderInfo[pHttpResponse->ResponseInfoCount].pInfo = (HttpApiTypes.HTTP_MULTIPLE_KNOWN_HEADERS *)gcHandle.AddrOfPinnedObject(); pHttpResponse->ResponseInfoCount++; } } } catch (Exception) { FreePinnedHeaders(pinnedHeaders); throw; } return(pinnedHeaders); }