private static async Task OnRequestInterceptedAsync(RequestInterceptedEventArgs e) { Task interceptedTask = RequestInterceptedAsync?.Invoke(null, e); if (interceptedTask != null) { await interceptedTask; } }
private static async Task HandleClientAsync(TcpClient client) { using (var local = new EavesNode(Certifier, client)) { WebRequest request = await local.ReadRequestAsync().ConfigureAwait(false); if (request == null) { return; } HttpContent requestContent = null; var requestArgs = new RequestInterceptedEventArgs(request); try { requestArgs.Content = requestContent = await local.ReadRequestContentAsync(request).ConfigureAwait(false); await OnRequestInterceptedAsync(requestArgs).ConfigureAwait(false); if (requestArgs.Cancel) { return; } request = requestArgs.Request; if (requestArgs.Content != null) { await local.WriteRequestContentAsync(request, requestArgs.Content).ConfigureAwait(false); } } finally { requestContent?.Dispose(); requestArgs.Content?.Dispose(); } WebResponse response = null; try { response = await request.GetResponseAsync().ConfigureAwait(false); } catch (WebException ex) { response = ex.Response; } catch (ProtocolViolationException) { response?.Dispose(); response = null; } if (response == null) { return; } if (request is FileWebRequest) { // Ensure this response is accepted by the client. response.Headers["access-control-allow-origin"] = "*"; } HttpContent responseContent = null; var responseArgs = new ResponseInterceptedEventArgs(request, response); try { responseArgs.Content = responseContent = EavesNode.ReadResponseContent(response); await OnResponseInterceptedAsync(responseArgs).ConfigureAwait(false); if (responseArgs.Cancel) { return; } await local.SendResponseAsync(responseArgs.Response, responseArgs.Content).ConfigureAwait(false); } finally { response.Dispose(); responseArgs.Response.Dispose(); responseContent?.Dispose(); responseArgs.Content?.Dispose(); } } }