internal static void CloseDuplexSessionChannel(ReliableChannelBinder <IDuplexSessionChannel> binder, IDuplexSessionChannel channel, TimeSpan timeout) { Message message; TimeoutHelper helper = new TimeoutHelper(timeout); channel.Session.CloseOutputSession(helper.RemainingTime()); binder.WaitForPendingOperations(helper.RemainingTime()); TimeSpan span = helper.RemainingTime(); bool flag = span == TimeSpan.Zero; Label_003B: message = null; bool flag2 = true; try { bool flag3 = channel.TryReceive(span, out message); flag2 = false; if (flag3 && (message == null)) { channel.Close(helper.RemainingTime()); return; } } catch (Exception exception) { if (Fx.IsFatal(exception)) { throw; } if (!flag2) { throw; } if (!MaskHandled(binder.DefaultMaskingMode) || !binder.IsHandleable(exception)) { throw; } flag2 = false; } finally { if (message != null) { message.Close(); } if (flag2) { channel.Abort(); } } if (!flag && (channel.State == CommunicationState.Opened)) { span = helper.RemainingTime(); flag = span == TimeSpan.Zero; goto Label_003B; } channel.Abort(); }
private static NetworkDetector.ConnectivityStatus CheckTcpConnectivity(Uri baseAddress, out Exception exception) { NetworkDetector.ConnectivityStatus connectivityStatu = NetworkDetector.ConnectivityStatus.Unavailable; exception = null; if (!RelayEnvironment.GetEnvironmentVariable("RELAYFORCEHTTP", false) && !RelayEnvironment.GetEnvironmentVariable("RELAYFORCEHTTPS", false)) { try { BinaryMessageEncodingBindingElement binaryMessageEncodingBindingElement = new BinaryMessageEncodingBindingElement(); TcpTransportBindingElement tcpTransportBindingElement = new TcpTransportBindingElement(); tcpTransportBindingElement.ConnectionPoolSettings.MaxOutboundConnectionsPerEndpoint = 100; tcpTransportBindingElement.MaxReceivedMessageSize = (long)65536; CustomBinding customBinding = new CustomBinding(); customBinding.Elements.Add(binaryMessageEncodingBindingElement); customBinding.Elements.Add(tcpTransportBindingElement); customBinding.OpenTimeout = TimeSpan.FromSeconds(10); customBinding.SendTimeout = TimeSpan.FromSeconds(10); customBinding.ReceiveTimeout = TimeSpan.MaxValue; int num = 9350; Uri uri = ServiceBusUriHelper.CreateServiceUri("net.tcp", string.Concat(baseAddress.DnsSafeHost, ":", num.ToString(CultureInfo.InvariantCulture)), "/"); IChannelFactory <IDuplexSessionChannel> channelFactory = null; IDuplexSessionChannel duplexSessionChannel = null; try { channelFactory = customBinding.BuildChannelFactory <IDuplexSessionChannel>(new object[0]); channelFactory.Open(); duplexSessionChannel = channelFactory.CreateChannel(new EndpointAddress(uri, new AddressHeader[0])); duplexSessionChannel.Open(); Message message = Message.CreateMessage(MessageVersion.Default, "http://schemas.microsoft.com/netservices/2009/05/servicebus/connect/OnewayPing", new OnewayPingMessage()); duplexSessionChannel.Send(message, customBinding.SendTimeout); duplexSessionChannel.Close(); duplexSessionChannel = null; channelFactory.Close(); channelFactory = null; } finally { if (duplexSessionChannel != null) { duplexSessionChannel.Abort(); } if (channelFactory != null) { channelFactory.Abort(); } } connectivityStatu = NetworkDetector.ConnectivityStatus.Available; } catch (CommunicationException communicationException) { exception = communicationException; } catch (TimeoutException timeoutException) { exception = timeoutException; } } NetworkDetector.LogResult(baseAddress, "Tcp", connectivityStatu); return(connectivityStatu); }
/// <summary> /// Try to begin receive messages /// </summary> /// <param name="ccs">indicating the channel and the client</param> /// <returns>if the operation completed synchronously</returns> protected override bool TryToBeginReceive(ChannelClientState ccs) { IDuplexSessionChannel channel = (IDuplexSessionChannel)ccs.Channel; BrokerClient client = ccs.Client; IAsyncResult ar = null; try { ar = channel.BeginReceive(this.receiveRequest, ccs); } catch (Exception e) { BrokerTracing.TraceEvent(TraceEventType.Information, 0, "[DuplexFrontEnd] Exception throwed while begin receive messages: {0}", e); // Channel must be in falted state lock (channel) { if (channel.State == CommunicationState.Faulted) { BrokerTracing.TraceEvent(TraceEventType.Information, 0, "[DuplexFrontEnd] About the channel."); this.FrontendDisconnect(channel, client); // About the falted channel channel.Abort(); } } return(false); } return(ar.CompletedSynchronously && channel.State == CommunicationState.Opened); }
private void HandleAcceptComplete(IDuplexSessionChannel channel) { Exception exception = null; bool flag = false; this.inputChannelAcceptor.PrepareChannel(channel); IAsyncResult result = null; try { result = channel.BeginOpen(this.idleTimeout, this.onOpenInnerChannel, channel); flag = true; } catch (CommunicationException exception2) { if (DiagnosticUtility.ShouldTraceInformation) { DiagnosticUtility.ExceptionUtility.TraceHandledException(exception2, TraceEventType.Information); } } catch (TimeoutException exception3) { if (DiagnosticUtility.ShouldTraceInformation) { DiagnosticUtility.ExceptionUtility.TraceHandledException(exception3, TraceEventType.Information); } } catch (Exception exception4) { if (Fx.IsFatal(exception4)) { throw; } exception = exception4; } finally { if (!flag && (channel != null)) { channel.Abort(); } } if (flag) { if (result.CompletedSynchronously) { this.CompleteOpen(channel, result); } } else if (exception != null) { this.inputChannelAcceptor.Enqueue(exception, null); } }
protected override void ProcessSequencedItem(IDuplexSessionChannel channel, Message message, ReliableInputSessionChannelOverDuplex reliableChannel, WsrmMessageInfo info, bool newChannel) { if (!newChannel && !reliableChannel.Binder.UseNewChannel(channel)) { message.Close(); channel.Abort(); } else { reliableChannel.ProcessDemuxedMessage(info); } }
public override Task WriteAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken) { if (channel.State != CommunicationState.Opened) { throw new InvalidOperationException(); } // local cancellation source dependent on outer token that nukes the channel // on abort. That renders the channel unusable for further operations while a // timeout expiry might not. using (var ct = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken)) { ct.Token.Register(() => channel.Abort()); // create and send message var msg = StreamMessageHelper.CreateMessage(MessageVersion.Default, string.Empty, new MemoryStream(buffer, offset, count)); msg.Headers.Action = null; return(Task.Factory.FromAsync(channel.BeginSend, channel.EndSend, msg, TimeSpan.FromMilliseconds(WriteTimeout), null)); } }
private void CleanupChannel(IDuplexSessionChannel channel, bool connectionStillGood, ChannelPoolKey key, bool isConnectionFromPool, ref TimeoutHelper timeoutHelper) { if (isConnectionFromPool) { this.channelPool.ReturnConnection(key, channel, connectionStillGood, timeoutHelper.RemainingTime()); } else if (connectionStillGood) { this.channelPool.AddConnection(key, channel, timeoutHelper.RemainingTime()); } else { channel.Abort(); } }
private void CompleteOpen(IDuplexSessionChannel channel, IAsyncResult result) { Exception exception = null; bool flag = false; try { channel.EndOpen(result); flag = true; } catch (CommunicationException exception2) { if (DiagnosticUtility.ShouldTraceInformation) { DiagnosticUtility.ExceptionUtility.TraceHandledException(exception2, TraceEventType.Information); } } catch (TimeoutException exception3) { if (DiagnosticUtility.ShouldTraceInformation) { DiagnosticUtility.ExceptionUtility.TraceHandledException(exception3, TraceEventType.Information); } } catch (Exception exception4) { if (Fx.IsFatal(exception4)) { throw; } exception = exception4; } finally { if (!flag) { channel.Abort(); } } if (flag) { this.inputChannelAcceptor.AcceptInnerChannel(this, channel); } else if (exception != null) { this.inputChannelAcceptor.Enqueue(exception, null); } }
private void OnReceive(IAsyncResult result) { IDuplexSessionChannel asyncState = (IDuplexSessionChannel)result.AsyncState; bool flag = false; try { Message message = asyncState.EndReceive(result); if (message == null) { asyncState.Close(this.channelPool.IdleTimeout); flag = true; } else { message.Close(); } } catch (CommunicationException exception) { if (DiagnosticUtility.ShouldTraceInformation) { DiagnosticUtility.ExceptionUtility.TraceHandledException(exception, TraceEventType.Information); } } catch (TimeoutException exception2) { if (DiagnosticUtility.ShouldTraceInformation) { DiagnosticUtility.ExceptionUtility.TraceHandledException(exception2, TraceEventType.Information); } } finally { if (!flag) { asyncState.Abort(); } } }
void OnReceive(IAsyncResult result) { IDuplexSessionChannel channel = (IDuplexSessionChannel)result.AsyncState; bool success = false; try { Message message = channel.EndReceive(result); if (message == null) { channel.Close(this.channelPool.IdleTimeout); success = true; } else { message.Close(); } } catch (CommunicationException e) { DiagnosticUtility.TraceHandledException(e, TraceEventType.Information); } catch (TimeoutException e) { if (TD.CloseTimeoutIsEnabled()) { TD.CloseTimeout(e.Message); } DiagnosticUtility.TraceHandledException(e, TraceEventType.Information); } finally { if (!success) { channel.Abort(); } } }
protected override void OnAbort() { innerChannel.Abort(); //we don't call base.OnAbort because it does nothing }
internal static void CloseDuplexSessionChannel(ReliableChannelBinder <IDuplexSessionChannel> binder, IDuplexSessionChannel channel, TimeSpan timeout) { TimeoutHelper timeoutHelper = new TimeoutHelper(timeout); channel.Session.CloseOutputSession(timeoutHelper.RemainingTime()); binder.WaitForPendingOperations(timeoutHelper.RemainingTime()); TimeSpan timeout1 = timeoutHelper.RemainingTime(); bool flag1 = timeout1 == TimeSpan.Zero; while (true) { Message message = (Message)null; bool flag2 = true; try { bool flag3 = channel.TryReceive(timeout1, out message); flag2 = false; if (flag3) { if (message == null) { channel.Close(timeoutHelper.RemainingTime()); return; } } } catch (Exception ex) { if (Fx.IsFatal(ex)) { throw; } else if (flag2) { if (!ReliableChannelBinderHelper.MaskHandled(binder.DefaultMaskingMode) || !binder.IsHandleable(ex)) { throw; } else { flag2 = false; } } else { throw; } } finally { if (message != null) { message.Close(); } if (flag2) { channel.Abort(); } } if (!flag1 && channel.State == CommunicationState.Opened) { timeout1 = timeoutHelper.RemainingTime(); flag1 = timeout1 == TimeSpan.Zero; } else { break; } } channel.Abort(); }
/// <summary> /// AsyncCallback for ReceiveRequest /// </summary> /// <param name="ar">async result</param> private void ReceiveRequest(IAsyncResult ar) { ChannelClientState state = (ChannelClientState)ar.AsyncState; IDuplexSessionChannel channel = (IDuplexSessionChannel)state.Channel; BrokerClient client = state.Client; Message requestMessage; try { requestMessage = channel.EndReceive(ar); } catch (Exception ce) { BrokerTracing.TraceEvent(TraceEventType.Warning, 0, "[DuplexFrontEnd] Exception while receiving requests: {0}", ce); this.FrontendDisconnect(channel, client); lock (channel) { if (channel.State == CommunicationState.Faulted) { BrokerTracing.TraceEvent(TraceEventType.Warning, 0, "[DuplexFrontEnd] Abort faulted channel."); channel.Abort(); return; } } // Retry receiving requests if (!ar.CompletedSynchronously) { this.TryToBeginReceiveMessagesWithThrottling(state); } return; } #region Debug Failure Test SimulateFailure.FailOperation(1); #endregion // After channel timeout, the request will be null if you call channel.Receive() // Need to end the channel at this time if (requestMessage == null) { // Indicate that the channel should be closed // Close the channel lock (channel) { if (channel.State == CommunicationState.Opened) { this.FrontendDisconnect(channel, client); try { channel.Close(); BrokerTracing.TraceEvent(TraceEventType.Information, 0, "[DuplexFrontEnd] Channel closed"); } catch (Exception ce) { BrokerTracing.TraceEvent(TraceEventType.Warning, 0, "[DuplexFrontEnd] Exception throwed while close the channel: {0}", ce); channel.Abort(); } } } return; } // Try to get the client id string callerSID; string userName = this.GetUserName(requestMessage, out callerSID); string clientId = GetClientId(requestMessage, callerSID); try { ParamCheckUtility.ThrowIfTooLong(clientId.Length, "clientId", Constant.MaxClientIdLength, SR.ClientIdTooLong); ParamCheckUtility.ThrowIfNotMatchRegex(ParamCheckUtility.ClientIdValid, clientId, "clientId", SR.InvalidClientId); } catch (ArgumentException) { BrokerTracing.EtwTrace.LogFrontEndRequestRejectedClientIdInvalid(this.SessionId, clientId, Utility.GetMessageIdFromMessage(requestMessage)); RequestContextBase requestContextToReject = new DuplexRequestContext(requestMessage, this.binding, channel, this.Observer); requestContextToReject.BeginReply(FrontEndFaultMessage.GenerateFaultMessage(requestMessage, requestMessage.Headers.MessageVersion, SOAFaultCode.Broker_InvalidClientIdOrTooLong, SR.InvalidClientIdOrTooLong), this.ReplySentCallback, requestContextToReject); return; } if (client == null) { if (!this.TryGetClientByChannel(channel, clientId, userName, requestMessage, out client)) { return; } state.Client = client; } // Receive new requests if (!ar.CompletedSynchronously) { this.TryToBeginReceiveMessagesWithThrottling(state); } // Reject if client id does not match if (String.Compare(clientId, client.ClientId, StringComparison.OrdinalIgnoreCase) != 0) { BrokerTracing.EtwTrace.LogFrontEndRequestRejectedClientIdNotMatch(this.SessionId, clientId, Utility.GetMessageIdFromMessage(requestMessage)); RequestContextBase requestContextToReject = new DuplexRequestContext(requestMessage, this.binding, channel, this.Observer); requestContextToReject.BeginReply(FrontEndFaultMessage.GenerateFaultMessage(requestMessage, requestMessage.Headers.MessageVersion, SOAFaultCode.Broker_ClientIdNotMatch, SR.ClientIdNotMatch), this.ReplySentCallback, requestContextToReject); return; } // Try to get the user info header bool userDataFlag = GetUserInfoHeader(requestMessage); // Create request context RequestContextBase requestContext; if (userDataFlag) { // Message that needs not to reply requestContext = DummyRequestContext.GetInstance(requestMessage.Version); } else { requestContext = new DuplexRequestContext(requestMessage, this.binding, channel, this.Observer, client); } // Check auth if (!this.CheckAuth(requestContext, requestMessage)) { return; } // remove security header for websocket TryRemoveSecurityHeaderForHttps(requestMessage); // Send the request to the broker client Task.Run(() => client.RequestReceived(requestContext, requestMessage, null)); }