public override int EndRead(IAsyncResult result)
                {
                    int num;

                    try
                    {
                        num = base.BaseStream.EndRead(result);
                    }
                    catch (IOException exception)
                    {
                        throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(HttpChannelUtilities.CreateResponseIOException(exception, TimeoutHelper.FromMilliseconds(this.ReadTimeout)));
                    }
                    catch (ObjectDisposedException exception2)
                    {
                        throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new CommunicationException(exception2.Message, exception2));
                    }
                    catch (WebException exception3)
                    {
                        throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(HttpChannelUtilities.CreateResponseWebException(exception3, this.webResponse));
                    }
                    return(num);
                }
                public override IAsyncResult BeginRead(byte[] buffer, int offset, int count, AsyncCallback callback, object state)
                {
                    IAsyncResult result;

                    try
                    {
                        result = base.BaseStream.BeginRead(buffer, offset, Math.Min(count, 0x10000), callback, state);
                    }
                    catch (IOException exception)
                    {
                        throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(HttpChannelUtilities.CreateResponseIOException(exception, TimeoutHelper.FromMilliseconds(this.ReadTimeout)));
                    }
                    catch (ObjectDisposedException exception2)
                    {
                        throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new CommunicationException(exception2.Message, exception2));
                    }
                    catch (WebException exception3)
                    {
                        throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(HttpChannelUtilities.CreateResponseWebException(exception3, this.webResponse));
                    }
                    return(result);
                }
Example #3
0
        protected override void OnEndOpen(IAsyncResult result)
        {
            bool            success  = false;
            HttpWebResponse response = null;

            try
            {
                response = (HttpWebResponse)this.httpWebRequest.EndGetResponse(result);
                this.HandleHttpWebResponse(this.httpWebRequest, response);
                this.RemoveIdentityMapping(false);
                success = true;

                if (TD.WebSocketConnectionRequestSendStopIsEnabled())
                {
                    TD.WebSocketConnectionRequestSendStop(
                        this.EventTraceActivity,
                        this.WebSocket != null ? this.WebSocket.GetHashCode() : -1);
                }
            }
            catch (WebException ex)
            {
                if (TD.WebSocketConnectionFailedIsEnabled())
                {
                    TD.WebSocketConnectionFailed(this.EventTraceActivity, ex.Message);
                }

                TryConvertAndThrow(ex);
                throw FxTrace.Exception.AsError(HttpChannelUtilities.CreateRequestWebException(ex, this.httpWebRequest, HttpAbortReason.None));
            }
            finally
            {
                this.CleanupTokenProviders();

                if (!success)
                {
                    this.CleanupOnError(this.httpWebRequest, response);
                }
            }
        }
Example #4
0
        internal static Exception ConvertAggregateExceptionToCommunicationException(AggregateException ex)
        {
            Exception          exception          = FxTrace.Exception.AsError <WebSocketException>(ex);
            WebSocketException webSocketException = exception as WebSocketException;

            if (webSocketException != null && webSocketException.InnerException != null)
            {
                HttpListenerException httpListenerException = webSocketException.InnerException as HttpListenerException;
                if (httpListenerException != null)
                {
                    return(HttpChannelUtilities.CreateCommunicationException(httpListenerException));
                }
            }

            ObjectDisposedException objectDisposedException = exception as ObjectDisposedException;

            if (objectDisposedException != null)
            {
                return(new CommunicationObjectAbortedException(exception.Message, exception));
            }

            return(new CommunicationException(exception.Message, exception));
        }
            void CompleteChannelModelIntegrationHandlerTask(Message replyMessage)
            {
                if (this.channelModelIntegrationHandlerTask != null)
                {
                    // If Service Model (or service instance) sent us null then we create a 202 HTTP response
                    HttpResponseMessage httpResponseMessage = null;
                    this.httpOutput = this.GetHttpOutput(replyMessage);

                    if (replyMessage != null)
                    {
                        httpResponseMessage = this.CreateHttpResponseMessage(replyMessage);
                    }
                    else
                    {
                        httpResponseMessage = new HttpResponseMessage(HttpStatusCode.Accepted);
                    }

                    Fx.Assert(httpResponseMessage != null, "httpResponse should not be null.");
                    if (httpResponseMessage.RequestMessage == null)
                    {
                        httpResponseMessage.RequestMessage = this.httpRequestMessage;
                        Fx.Assert(httpResponseMessage.RequestMessage != null, "httpResponseMessage.RequestMessage should never be null.");

                        if (replyMessage != null)
                        {
                            httpResponseMessage.CopyPropertiesFromMessage(replyMessage);
                        }
                    }

                    HttpChannelUtilities.EnsureHttpResponseMessageContentNotNull(httpResponseMessage);

                    this.cancellationTokenSource.CancelAfter(TimeoutHelper.ToMilliseconds(this.defaultSendTimeout));
                    this.channelModelIntegrationHandlerTask.TrySetResult(httpResponseMessage);
                }

                this.TraceProcessResponseStop();
            }
Example #6
0
        protected override IAsyncResult OnBeginOpen(TimeSpan timeout, AsyncCallback callback, object state)
        {
            bool success = false;

            try
            {
                if (TD.WebSocketConnectionRequestSendStartIsEnabled())
                {
                    TD.WebSocketConnectionRequestSendStart(
                        this.EventTraceActivity,
                        this.RemoteAddress != null ? this.RemoteAddress.ToString() : string.Empty);
                }

                this.httpWebRequest = this.CreateHttpWebRequest(timeout);
                IAsyncResult result = this.httpWebRequest.BeginGetResponse(callback, state);
                success = true;
                return(result);
            }
            catch (WebException ex)
            {
                if (TD.WebSocketConnectionFailedIsEnabled())
                {
                    TD.WebSocketConnectionFailed(this.EventTraceActivity, ex.Message);
                }

                TryConvertAndThrow(ex);
                throw FxTrace.Exception.AsError(HttpChannelUtilities.CreateRequestWebException(ex, this.httpWebRequest, HttpAbortReason.None));
            }
            finally
            {
                if (!success)
                {
                    this.CleanupTokenProviders();
                    this.CleanupOnError(this.httpWebRequest, null);
                }
            }
        }
Example #7
0
                    public override int ReadByte()
                    {
                        int num;

                        try
                        {
                            num = base.ReadByte();
                        }
                        catch (HttpListenerException exception)
                        {
                            throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(HttpChannelUtilities.CreateCommunicationException(exception));
                        }
                        return(num);
                    }
Example #8
0
                    public override int Read(byte[] buffer, int offset, int count)
                    {
                        int num;

                        try
                        {
                            num = base.Read(buffer, offset, count);
                        }
                        catch (HttpListenerException exception)
                        {
                            throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(HttpChannelUtilities.CreateCommunicationException(exception));
                        }
                        return(num);
                    }
Example #9
0
                    public override int EndRead(IAsyncResult result)
                    {
                        int num;

                        try
                        {
                            num = base.EndRead(result);
                        }
                        catch (HttpListenerException exception)
                        {
                            throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(HttpChannelUtilities.CreateCommunicationException(exception));
                        }
                        return(num);
                    }
Example #10
0
                    public override IAsyncResult BeginRead(byte[] buffer, int offset, int count, AsyncCallback callback, object state)
                    {
                        IAsyncResult result;

                        try
                        {
                            result = base.BeginRead(buffer, offset, count, callback, state);
                        }
                        catch (HttpListenerException exception)
                        {
                            throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(HttpChannelUtilities.CreateCommunicationException(exception));
                        }
                        return(result);
                    }
Example #11
0
                public async Task SendRequestAsync(Message message, TimeoutHelper timeoutHelper)
                {
                    _timeoutHelper = timeoutHelper;
                    _factory.ApplyManualAddressing(ref _to, ref _via, message);
                    _httpRequestMessage = await _channel.GetHttpRequestMessageAsync(_to, _via, _timeoutHelper);

                    Message request = message;

                    try
                    {
                        if (_channel.State != CommunicationState.Opened)
                        {
                            // if we were aborted while getting our request or doing correlation,
                            // we need to abort the request and bail
                            Cleanup();
                            _channel.ThrowIfDisposedOrNotOpen();
                        }

                        bool suppressEntityBody = PrepareMessageHeaders(request);

                        if (!suppressEntityBody)
                        {
                            _httpRequestMessage.Content = MessageContent.Create(_factory, request, _timeoutHelper);
                        }

                        try
                        {
                            // There is a possibility that a HEAD pre-auth request might fail when the actual request
                            // will succeed. For example, when the web service refuses HEAD requests. We don't want
                            // to fail the actual request because of some subtlety which causes the HEAD request.
                            await SendPreauthenticationHeadRequestIfNeeded();
                        }
                        catch { /* ignored */ }

                        bool success = false;

                        try
                        {
                            _httpResponseMessage = await _httpClient.SendAsync(_httpRequestMessage, HttpCompletionOption.ResponseHeadersRead, _timeoutHelper.CancellationToken);

                            // As we have the response message and no exceptions have been thrown, the request message has completed it's job.
                            // Calling Dispose() on the request message to free up resources in HttpContent, but keeping the object around
                            // as we can still query properties once dispose'd.
                            _httpRequestMessage.Dispose();
                            success = true;
                        }
                        catch (HttpRequestException requestException)
                        {
                            HttpChannelUtilities.ProcessGetResponseWebException(requestException, _httpRequestMessage,
                                                                                _abortReason);
                        }
                        catch (OperationCanceledException)
                        {
                            if (_timeoutHelper.CancellationToken.IsCancellationRequested)
                            {
                                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new TimeoutException(SR.Format(
                                                                                                                   SR.HttpRequestTimedOut, _httpRequestMessage.RequestUri, _timeoutHelper.OriginalTimeout)));
                            }
                            else
                            {
                                // Cancellation came from somewhere other than timeoutCts and needs to be handled differently.
                                throw;
                            }
                        }
                        finally
                        {
                            if (!success)
                            {
                                Abort(_channel);
                            }
                        }
                    }
                    finally
                    {
                        if (!ReferenceEquals(request, message))
                        {
                            request.Close();
                        }
                    }
                }
Example #12
0
        internal override void OnOpen()
        {
            listener = new HttpListener();

            string host;

            switch (HostNameComparisonMode)
            {
            case HostNameComparisonMode.Exact:
                // Uri.DnsSafeHost strips the [], but preserves the scopeid for IPV6 addresses.
                if (ListenUri.HostNameType == UriHostNameType.IPv6)
                {
                    host = string.Concat("[", ListenUri.DnsSafeHost, "]");
                }
                else
                {
                    host = ListenUri.NormalizedHost();
                }
                break;

            case HostNameComparisonMode.StrongWildcard:
                host = "+";
                break;

            case HostNameComparisonMode.WeakWildcard:
                host = "*";
                break;

            default:
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.GetString(SR.UnrecognizedHostNameComparisonMode, HostNameComparisonMode.ToString())));
            }

            string path = ListenUri.GetComponents(UriComponents.Path, UriFormat.Unescaped);

            if (!path.StartsWith("/", StringComparison.Ordinal))
            {
                path = "/" + path;
            }

            if (!path.EndsWith("/", StringComparison.Ordinal))
            {
                path = path + "/";
            }

            string httpListenUrl = string.Concat(Scheme, "://", host, ":", ListenUri.Port, path);

            listener.UnsafeConnectionNtlmAuthentication   = this.unsafeConnectionNtlmAuthentication;
            listener.AuthenticationSchemeSelectorDelegate =
                new AuthenticationSchemeSelector(SelectAuthenticationScheme);

            if (ExtendedProtectionPolicy.OSSupportsExtendedProtection)
            {
                //This API will throw if on an unsupported platform.
                listener.ExtendedProtectionSelectorDelegate =
                    new HttpListener.ExtendedProtectionSelector(SelectExtendedProtectionPolicy);
            }

            if (this.Realm != null)
            {
                listener.Realm = this.Realm;
            }

            bool success = false;

            try
            {
                listener.Prefixes.Add(httpListenUrl);
                listener.Start();

                bool startedListening = false;
                try
                {
                    if (Thread.CurrentThread.IsThreadPoolThread)
                    {
                        StartListening();
                    }
                    else
                    {
                        // If we're not on a threadpool thread, then we need to post a callback to start our accepting loop
                        // Otherwise if the calling thread aborts then the async I/O will get inadvertantly cancelled
                        listenStartedEvent = new ManualResetEvent(false);
                        ActionItem.Schedule(OnListening, null);
                        listenStartedEvent.WaitOne();
                        listenStartedEvent.Close();
                        listenStartedEvent = null;
                        if (listenStartedException != null)
                        {
                            throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(listenStartedException);
                        }
                    }
                    startedListening = true;
                }
                finally
                {
                    if (!startedListening)
                    {
                        listener.Stop();
                    }
                }

                success = true;
            }
            catch (HttpListenerException listenerException)
            {
                switch (listenerException.NativeErrorCode)
                {
                case UnsafeNativeMethods.ERROR_ALREADY_EXISTS:
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new AddressAlreadyInUseException(SR.GetString(SR.HttpRegistrationAlreadyExists, httpListenUrl), listenerException));

                case UnsafeNativeMethods.ERROR_SHARING_VIOLATION:
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new AddressAlreadyInUseException(SR.GetString(SR.HttpRegistrationPortInUse, httpListenUrl, ListenUri.Port), listenerException));

                case UnsafeNativeMethods.ERROR_ACCESS_DENIED:
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new AddressAccessDeniedException(SR.GetString(SR.HttpRegistrationAccessDenied, httpListenUrl), listenerException));

                case UnsafeNativeMethods.ERROR_ALLOTTED_SPACE_EXCEEDED:
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new CommunicationException(SR.GetString(SR.HttpRegistrationLimitExceeded, httpListenUrl), listenerException));

                case UnsafeNativeMethods.ERROR_INVALID_PARAMETER:
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.GetString(SR.HttpInvalidListenURI, ListenUri.OriginalString), listenerException));

                default:
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
                              HttpChannelUtilities.CreateCommunicationException(listenerException));
                }
            }
            finally
            {
                if (!success)
                {
                    listener.Abort();
                }
            }
        }
Example #13
0
                public async Task <Message> ReceiveReplyAsync(TimeoutHelper timeoutHelper)
                {
                    _timeoutHelper = timeoutHelper;
                    HttpResponseMessage  httpResponse      = null;
                    HttpRequestException responseException = null;

                    try
                    {
                        httpResponse = await _httpResponseMessageTask;
                    }
                    catch (HttpRequestException requestException)
                    {
                        responseException = requestException;
                        httpResponse      = HttpChannelUtilities.ProcessGetResponseWebException(responseException, _httpRequestMessage,
                                                                                                _abortReason);
                    }
                    catch (OperationCanceledException)
                    {
                        if (_timeoutHelper.CancellationToken.IsCancellationRequested)
                        {
                            throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new TimeoutException(SR.Format(
                                                                                                               SR.HttpRequestTimedOut, _httpRequestMessage.RequestUri, _timeoutHelper.OriginalTimeout)));
                        }
                        else
                        {
                            // Cancellation came from somewhere other than timeoutCts and needs to be handled differently.
                            throw;
                        }
                    }

                    try
                    {
                        HttpInput httpInput = HttpChannelUtilities.ValidateRequestReplyResponse(_httpRequestMessage, httpResponse,
                                                                                                _factory, responseException);

                        Message replyMessage = null;
                        if (httpInput != null)
                        {
                            var outException = new OutWrapper <Exception>();
                            replyMessage = await httpInput.ParseIncomingMessageAsync(outException);

                            Exception exception = outException;
                            Contract.Assert(exception == null, "ParseIncomingMessage should not set an exception after parsing a response message.");
                        }

                        this.TryCompleteHttpRequest(_httpRequestMessage);
                        return(replyMessage);
                    }
                    catch (OperationCanceledException)
                    {
                        if (_timeoutHelper.CancellationToken.IsCancellationRequested)
                        {
                            throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new TimeoutException(SR.Format(
                                                                                                               SR.HttpResponseTimedOut, _httpRequestMessage.RequestUri, timeoutHelper.OriginalTimeout)));
                        }
                        else
                        {
                            // Cancellation came from somewhere other than timeoutCts and needs to be handled differently.
                            throw;
                        }
                    }
                }
        internal override void OnOpen()
        {
            string dnsSafeHost;

            this.listener = new HttpListener();
            switch (base.HostNameComparisonMode)
            {
            case HostNameComparisonMode.StrongWildcard:
                dnsSafeHost = "+";
                break;

            case HostNameComparisonMode.Exact:
                if (base.ListenUri.HostNameType != UriHostNameType.IPv6)
                {
                    dnsSafeHost = base.ListenUri.DnsSafeHost;
                    break;
                }
                dnsSafeHost = "[" + base.ListenUri.DnsSafeHost + "]";
                break;

            case HostNameComparisonMode.WeakWildcard:
                dnsSafeHost = "*";
                break;

            default:
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(System.ServiceModel.SR.GetString("UnrecognizedHostNameComparisonMode", new object[] { base.HostNameComparisonMode.ToString() })));
            }
            string components = base.ListenUri.GetComponents(UriComponents.Path, UriFormat.Unescaped);

            if (!components.StartsWith("/", StringComparison.Ordinal))
            {
                components = "/" + components;
            }
            if (!components.EndsWith("/", StringComparison.Ordinal))
            {
                components = components + "/";
            }
            string uriPrefix = string.Concat(new object[] { this.Scheme, "://", dnsSafeHost, ":", base.ListenUri.Port, components });

            this.listener.UnsafeConnectionNtlmAuthentication   = this.unsafeConnectionNtlmAuthentication;
            this.listener.AuthenticationSchemeSelectorDelegate = new AuthenticationSchemeSelector(this.SelectAuthenticationScheme);
            if (ExtendedProtectionPolicy.OSSupportsExtendedProtection)
            {
                this.listener.ExtendedProtectionSelectorDelegate = new HttpListener.ExtendedProtectionSelector(this.SelectExtendedProtectionPolicy);
            }
            if (base.Realm != null)
            {
                this.listener.Realm = base.Realm;
            }
            bool flag = false;

            try
            {
                this.listener.Prefixes.Add(uriPrefix);
                this.listener.Start();
                bool flag2 = false;
                try
                {
                    if (Thread.CurrentThread.IsThreadPoolThread)
                    {
                        this.StartListening();
                    }
                    else
                    {
                        this.listenStartedEvent = new ManualResetEvent(false);
                        ActionItem.Schedule(new Action <object>(this.OnListening), null);
                        this.listenStartedEvent.WaitOne();
                        this.listenStartedEvent.Close();
                        this.listenStartedEvent = null;
                        if (this.listenStartedException != null)
                        {
                            throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(this.listenStartedException);
                        }
                    }
                    flag2 = true;
                }
                finally
                {
                    if (!flag2)
                    {
                        this.listener.Stop();
                    }
                }
                flag = true;
            }
            catch (HttpListenerException exception)
            {
                switch (exception.NativeErrorCode)
                {
                case 0x57:
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(System.ServiceModel.SR.GetString("HttpInvalidListenURI", new object[] { base.ListenUri.OriginalString }), exception));

                case 0xb7:
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new AddressAlreadyInUseException(System.ServiceModel.SR.GetString("HttpRegistrationAlreadyExists", new object[] { uriPrefix }), exception));

                case 0x540:
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new CommunicationException(System.ServiceModel.SR.GetString("HttpRegistrationLimitExceeded", new object[] { uriPrefix }), exception));

                case 5:
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new AddressAccessDeniedException(System.ServiceModel.SR.GetString("HttpRegistrationAccessDenied", new object[] { uriPrefix }), exception));

                case 0x20:
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new AddressAlreadyInUseException(System.ServiceModel.SR.GetString("HttpRegistrationPortInUse", new object[] { uriPrefix, base.ListenUri.Port }), exception));
                }
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(HttpChannelUtilities.CreateCommunicationException(exception));
            }
            finally
            {
                if (!flag)
                {
                    this.listener.Abort();
                }
            }
        }