internal void End() { int priorState = Interlocked.Exchange(ref _requestState, Completed); if (priorState == RequestInProgress) { // Premature ending, must be an error. // If the response has not started yet then we can send an error response before closing it. _context.Response.StatusCode = 500; _context.Response.ContentLength = 0; _context.Response.Headers.Clear(); try { //_context.Response.Close(); _context.Dispose(); } catch (HttpListenerException) { // TODO: Trace } } else if (priorState == ResponseInProgress) { _context.Abort(); } else { Contract.Requires(priorState == Completed); // Clean up after exceptions in the shutdown process. No-op if Response.Close() succeeded. _context.Abort(); } }
Task ReceiveMessage(RequestContext context) { return RunWorkerTask(async state => { try { if (aggregateUrls.Any(x => x.IsMatch(context.Request.Path))) { await DistributeToSecondaries(context); } else { await ForwardToPrimary(context); } } catch (OperationCanceledException) { // Intentionally ignored } catch (Exception ex) { context.Abort(); } }, this); }
/// <summary> /// Cancels all outstanding requests. /// </summary> private void InternalClose(object state) { TcpAsyncOperation <int> operation = (TcpAsyncOperation <int>)state; try { lock (m_lock) { while (m_requestQueue.Count > 0) { RequestContext context = m_requestQueue.Dequeue();; // Utils.Trace("Request Aborted: ChannelId={0}, RequestId={1}", this.m_channel.Id, context.RequestId); context.Abort(); } while (m_operationQueue.Count > 0) { TcpAsyncOperation <RequestContext> receiveOperation = m_operationQueue.Dequeue(); receiveOperation.Complete(null); } } operation.Complete(0); } catch (Exception e) { operation.Fault(e, StatusCodes.BadInternalError, "Could not close a UA TCP reply channel."); } }
/// <summary cref="CommunicationObject.OnAbort" /> protected override void OnAbort() { try { lock (m_lock) { while (m_requestQueue.Count > 0) { RequestContext context = m_requestQueue.Dequeue(); // Utils.Trace("Request Aborted: ChannelId={0}, RequestId={1}", this.m_channel.Id, context.RequestId); context.Abort(); } while (m_operationQueue.Count > 0) { TcpAsyncOperation <RequestContext> receiveOperation = m_operationQueue.Dequeue(); receiveOperation.Complete(null); } } } catch (Exception) { // ignore exceptions on abort. } }
void AbortRequestContext(RequestContext requestContext) { try { requestContext.Abort(); ReceiveContextRPCFacet receiveContext = this.ReceiveContext; if (receiveContext != null) { this.ReceiveContext = null; IAsyncResult result = receiveContext.BeginAbandon( TimeSpan.MaxValue, handleEndAbandon, new CallbackState { ReceiveContext = receiveContext, ChannelHandler = this.channelHandler }); if (result.CompletedSynchronously) { receiveContext.EndAbandon(result); } } } catch (Exception e) { if (Fx.IsFatal(e)) { throw; } this.channelHandler.HandleError(e); } }
private async Task <bool> TryRetrievingInstanceContextAsync(RequestContext request, RequestInfo requestInfo) { try { return(await TryRetrievingInstanceContextCoreAsync(request, requestInfo)); } catch (Exception ex) { if (Fx.IsFatal(ex)) { throw; } DiagnosticUtility.TraceHandledException(ex, TraceEventType.Error); try { await request.CloseAsync(); } catch (Exception e) { if (Fx.IsFatal(e)) { throw; } request.Abort(); } return(false); } }
RequestContext WrapInner(RequestContext requestContext) { if (requestContext == null) { return(null); } for (int i = 0; i < this.interceptors.Count; ++i) { RequestContext original = requestContext; bool dispose = true; try { this.interceptors[i].ProcessRequest(ref requestContext); dispose = false; } finally { if (dispose) { original.Abort(); } } if (requestContext == null) { return(null); } } return(requestContext); }
private void SendFaultIfRequired(Exception e, RequestContext innerContext, TimeSpan timeout) { if (!_sendUnsecuredFaults) { return; } MessageFault fault = SecurityUtils.CreateSecurityMessageFault(e, SecurityProtocol.SecurityProtocolFactory.StandardsManager); if (fault == null) { return; } Message requestMessage = innerContext.RequestMessage; Message faultMessage = Message.CreateMessage(requestMessage.Version, fault, requestMessage.Version.Addressing.DefaultFaultAction); try { TimeoutHelper timeoutHelper = new TimeoutHelper(timeout); innerContext.ReplyAsync(faultMessage); innerContext.CloseAsync(timeoutHelper.GetCancellationToken()); } catch (Exception ex) { if (Fx.IsFatal(ex)) { throw; } } finally { faultMessage.Close(); innerContext.Abort(); } }
string GetHttpSessionId(RequestContext requestContext) { object httpRequestProperty; if (!requestContext.RequestMessage.Properties.TryGetValue( HttpRequestMessageProperty.Name, out httpRequestProperty)) { requestContext.Abort(); throw new CommunicationException("Message received without an HttpRequestMessageProperty. HttpCookieReplySession requires a conformant Http transport to function properly."); } return(((HttpRequestMessageProperty)httpRequestProperty).Headers[HttpRequestHeader.Cookie]); }
private void AbortRequestContext(RequestContext requestContext) { try { requestContext.Abort(); } catch (Exception e) { if (Fx.IsFatal(e)) { throw; } this.channelHandler.HandleError(e); } }
void ProcessRequestCallback(IAsyncResult result) { if (result.CompletedSynchronously) { return; } bool completeSelf = false; Exception completionException = null; try { RequestContext original = this.context; bool dispose = true; try { this.context = this.interceptors[this.index].EndProcessRequest(result); dispose = false; } finally { if (dispose) { original.Abort(); } } if (this.context == null) { completeSelf = true; } else { ++this.index; completeSelf = this.RunInterceptors(); } } catch (Exception e) { completeSelf = true; completionException = e; } if (completeSelf) { Complete(false, completionException); } }
bool RunInterceptors() { while (this.index < this.interceptors.Count) { RequestContext original = this.context; bool dispose = true; RequestInterceptor interceptor = this.interceptors[this.index]; try { if (interceptor.IsSynchronous) { interceptor.ProcessRequest(ref this.context); dispose = false; } else { IAsyncResult result = interceptor.BeginProcessRequest(this.context, this.ProcessRequestCallback, null); if (!result.CompletedSynchronously) { dispose = false; return(false); } else { this.context = interceptor.EndProcessRequest(result); dispose = false; } } } finally { if (dispose) { original.Abort(); } } if (this.context == null) { return(true); } ++this.index; } return(true); }
bool HandleRequest(IReplyChannel channel, RequestContext context) { if (context == null) { channel.Close(); return(false); } try { serviceManager.HandleRequest(context); } catch (CommunicationException) { context.Abort(); } finally { context.Close(); } return(true); }
private bool HandleErrorContinuation(Exception e, RequestContext request, ServiceChannel channel, ref ErrorHandlerFaultInfo faultInfo, bool replied) { if (replied) { try { request.Close(); } catch (Exception e1) { if (Fx.IsFatal(e1)) { throw; } this.HandleError(e1); } } else { request.Abort(); } if (!this.HandleError(e, ref faultInfo) && _hasSession) { if (channel != null) { if (replied) { TimeoutHelper timeoutHelper = new TimeoutHelper(CloseAfterFaultTimeout); try { channel.Close(timeoutHelper.RemainingTime()); } catch (Exception e2) { if (Fx.IsFatal(e2)) { throw; } this.HandleError(e2); } try { _binder.CloseAfterFault(timeoutHelper.RemainingTime()); } catch (Exception e3) { if (Fx.IsFatal(e3)) { throw; } this.HandleError(e3); } } else { channel.Abort(); _binder.Abort(); } } else { if (replied) { try { _binder.CloseAfterFault(CloseAfterFaultTimeout); } catch (Exception e4) { if (Fx.IsFatal(e4)) { throw; } this.HandleError(e4); } } else { _binder.Abort(); } } } return(true); }
public override void Abort() { _innerContext.Abort(); }
public override void Abort() { source.Abort(); }
void IHttpRequestLifetimeFeature.Abort() { _requestContext.Abort(); }
private async Task handleClient <TWebSocketBehavior>(RequestContext requestContext, Func <TWebSocketBehavior> behaviorBuilder, CancellationToken token) where TWebSocketBehavior : WebListenerWebSocketServerBehavior { Guid connectionId; WebSocket webSocket = null; WebListenerWebSocketServerBehavior behavior = null; try { int statusCode = 500; var statusDescription = "BadContext"; behavior = behaviorBuilder(); if (!behavior.OnValidateContext(requestContext, ref statusCode, ref statusDescription)) { requestContext.Response.ReasonPhrase = statusDescription; requestContext.Response.StatusCode = statusCode; requestContext.Abort(); _logError($"Failed to validate client context. Closing connection. Status: {statusCode}. Description: {statusDescription}."); return; } connectionId = Guid.NewGuid(); webSocket = await requestContext.AcceptWebSocketAsync(null, _keepAlivePingInterval); bool clientAdded = _clients.TryAdd(connectionId, webSocket); if (!clientAdded) { throw new ArgumentException($"Attempted to add a new web socket connection to server for connection id '{connectionId}' that already exists."); } Interlocked.Increment(ref _connectedClientCount); _logInfo($"Connection id '{connectionId}' accepted; there are now {_connectedClientCount} total clients."); var safeconnected = MakeSafe <Guid, RequestContext>(behavior.OnConnectionEstablished, "behavior.OnClientConnected"); safeconnected(connectionId, requestContext); } catch (Exception e) { _logError($"Client handler exception: {e}"); requestContext.Response.StatusCode = 500; requestContext.Abort(); requestContext.Dispose(); return; } var stringBehavior = MakeSafe <StringMessageReceivedEventArgs>(behavior.OnStringMessage, "behavior.OnStringMessage"); var binaryBehavior = MakeSafe <BinaryMessageReceivedEventArgs>(behavior.OnBinaryMessage, "behavior.OnBinaryMessage"); bool single = false; var closeBehavior = MakeSafe <WebSocketReceivedResultEventArgs>((r) => { if (!single) { behavior.OnClose(new WebSocketClosedEventArgs(connectionId, r)); } single = true; }, "behavior.OnClose"); try { using (webSocket) { await webSocket.ProcessIncomingMessages(_messageQueue, connectionId, stringBehavior, binaryBehavior, closeBehavior, _logInfo, token); } } finally { Interlocked.Decrement(ref _connectedClientCount); _logInfo($"Connection id '{connectionId}' disconnected; there are now {_connectedClientCount} total clients."); webSocket?.CleanupSendMutex(); requestContext.Dispose(); bool clientRemoved = _clients.TryRemove(connectionId, out webSocket); if (clientRemoved) { closeBehavior(new WebSocketReceivedResultEventArgs(closeStatus: WebSocketCloseStatus.EndpointUnavailable, closeStatDesc: "Removing Client Due to other error")); } else { _logError($"Attempted to remove an existing web socket connection to server for connection id '{connectionId}' that no longer exists."); } _logInfo($"Completed HandleClient task for connection id '{connectionId}'."); } }
public override void Abort() { innerRequestContext.Abort(); }
protected override void OnAbort() { _innerContext.Abort(); }
public override void Abort() { src.Abort(); }
public override void Abort() { Cleanup(); _innerContext.Abort(); }
/// <summary> /// Aborts processing the request associated with the context /// </summary> public override void Abort() { WCFLogger.Write(TraceEventType.Verbose, "InterceptorRequestContext abort"); _innerContext.Abort(); }