public ClientWebSocketTransportDuplexSessionChannel(HttpChannelFactory <IDuplexSessionChannel> channelFactory, ClientWebSocketFactory connectionFactory, EndpointAddress remoteAddresss, Uri via)
     : base(channelFactory, remoteAddresss, via)
 {
     Contract.Assert(channelFactory != null, "connection factory must be set");
     _channelFactory    = channelFactory;
     _connectionFactory = connectionFactory;
 }
예제 #2
0
 public HttpClientChannelAsyncRequest(HttpClientRequestChannel channel)
 {
     _channel = channel;
     _to      = channel.RemoteAddress;
     _via     = channel.Via;
     _factory = channel.Factory;
 }
예제 #3
0
        protected override void ValidateCreateChannelParameters(EndpointAddress remoteAddress, Uri via)
        {
            if (remoteAddress.Identity != null)
            {
                X509CertificateEndpointIdentity certificateIdentity =
                    remoteAddress.Identity as X509CertificateEndpointIdentity;
                if (certificateIdentity != null)
                {
                    if (certificateIdentity.Certificates.Count > 1)
                    {
                        throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument("remoteAddress", SR.GetString(
                                                                                         SR.HttpsIdentityMultipleCerts, remoteAddress.Uri));
                    }
                }

                EndpointIdentity identity      = remoteAddress.Identity;
                bool             validIdentity = (certificateIdentity != null) ||
                                                 ClaimTypes.Spn.Equals(identity.IdentityClaim.ClaimType) ||
                                                 ClaimTypes.Upn.Equals(identity.IdentityClaim.ClaimType) ||
                                                 ClaimTypes.Dns.Equals(identity.IdentityClaim.ClaimType);

                if (!HttpChannelFactory <TChannel> .IsWindowsAuth(this.AuthenticationScheme) &&
                    !validIdentity)
                {
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument("remoteAddress", SR.GetString(
                                                                                     SR.HttpsExplicitIdentity));
                }
            }
            base.ValidateCreateChannelParameters(remoteAddress, via);
        }
예제 #4
0
 public HttpClientChannelAsyncRequest(HttpClientRequestChannel channel)
 {
     _channel     = channel;
     _to          = channel.RemoteAddress;
     _via         = channel.Via;
     _factory     = channel.Factory;
     _httpClient  = _factory.GetHttpClient();
     _httpSendCts = new CancellationTokenSource();
 }
        public static void AddReplySecurityProperty(HttpChannelFactory factory, HttpWebRequest webRequest, HttpWebResponse webResponse, Message replyMessage)
        {
            SecurityMessageProperty property = factory.CreateReplySecurityProperty(webRequest, webResponse);

            if (property != null)
            {
                replyMessage.Properties.Security = property;
            }
        }
예제 #6
0
 public HttpResponseMessageHelper(HttpResponseMessage httpResponseMessage, HttpChannelFactory <IRequestChannel> factory)
 {
     Contract.Assert(httpResponseMessage != null);
     Contract.Assert(httpResponseMessage.RequestMessage != null);
     Contract.Assert(factory != null);
     _httpResponseMessage = httpResponseMessage;
     _httpRequestMessage  = httpResponseMessage.RequestMessage;
     _factory             = factory;
     _encoder             = factory.MessageEncoderFactory.Encoder;
 }
예제 #7
0
 internal static HttpContent Create(HttpChannelFactory <IRequestChannel> factory, Message request, TimeoutHelper _timeoutHelper)
 {
     if (TransferModeHelper.IsRequestStreamed(factory.TransferMode))
     {
         return(new StreamedMessageContent(request, factory.MessageEncoderFactory.Encoder));
     }
     else
     {
         return(new BufferedMessageContent(request, factory.MessageEncoderFactory.Encoder, factory.BufferManager));
     }
 }
예제 #8
0
        HttpWebRequest CreateHttpWebRequest(TimeSpan timeout)
        {
            TimeoutHelper helper = new TimeoutHelper(timeout);
            ChannelParameterCollection channelParameterCollection = new ChannelParameterCollection();

            HttpWebRequest request;

            if (HttpChannelFactory <IDuplexSessionChannel> .MapIdentity(this.RemoteAddress, this.channelFactory.AuthenticationScheme))
            {
                lock (ThisLock)
                {
                    this.cleanupIdentity = HttpTransportSecurityHelpers.AddIdentityMapping(Via, RemoteAddress);
                }
            }

            this.channelFactory.CreateAndOpenTokenProviders(
                this.RemoteAddress,
                this.Via,
                channelParameterCollection,
                helper.RemainingTime(),
                out this.webRequestTokenProvider,
                out this.webRequestProxyTokenProvider);

            SecurityTokenContainer clientCertificateToken = null;
            HttpsChannelFactory <IDuplexSessionChannel> httpsChannelFactory = this.channelFactory as HttpsChannelFactory <IDuplexSessionChannel>;

            if (httpsChannelFactory != null && httpsChannelFactory.RequireClientCertificate)
            {
                SecurityTokenProvider certificateProvider = httpsChannelFactory.CreateAndOpenCertificateTokenProvider(this.RemoteAddress, this.Via, channelParameterCollection, helper.RemainingTime());
                clientCertificateToken = httpsChannelFactory.GetCertificateSecurityToken(certificateProvider, this.RemoteAddress, this.Via, channelParameterCollection, ref helper);
            }

            request = this.channelFactory.GetWebRequest(this.RemoteAddress, this.Via, this.webRequestTokenProvider, this.webRequestProxyTokenProvider, clientCertificateToken, helper.RemainingTime(), true);

            // If a web socket connection factory is specified (for example, when using web sockets on pre-Win8 OS),
            // we're going to use the protocol version from it. At the moment, on pre-Win8 OS, the HttpWebRequest
            // created above doesn't have the version header specified.
            if (this.connectionFactory != null)
            {
                this.UseWebSocketVersionFromFactory(request);
            }

            this.webSocketKey = request.Headers[WebSocketHelper.SecWebSocketKey];
            this.ConfigureHttpWebRequestHeader(request);
            request.Timeout = (int)helper.RemainingTime().TotalMilliseconds;
            return(request);
        }
예제 #9
0
        // Constructor

        public HttpRequestChannel(HttpChannelFactory <IRequestChannel> factory,
                                  EndpointAddress address, Uri via)
            : base(factory, address, via)
        {
            this.source = factory;
        }
        protected internal override async Task OnOpenAsync(TimeSpan timeout)
        {
            TimeoutHelper helper = new TimeoutHelper(timeout);

            bool success = false;

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

                ChannelParameterCollection channelParameterCollection = new ChannelParameterCollection();

                if (HttpChannelFactory <IDuplexSessionChannel> .MapIdentity(this.RemoteAddress, _channelFactory.AuthenticationScheme))
                {
                    lock (ThisLock)
                    {
                        _cleanupIdentity = HttpTransportSecurityHelpers.AddIdentityMapping(Via, RemoteAddress);
                    }
                }

                X509Certificate2 clientCertificate = null;
                HttpsChannelFactory <IDuplexSessionChannel> httpsChannelFactory = _channelFactory as HttpsChannelFactory <IDuplexSessionChannel>;
                if (httpsChannelFactory != null && httpsChannelFactory.RequireClientCertificate)
                {
                    var certificateProvider    = httpsChannelFactory.CreateAndOpenCertificateTokenProvider(RemoteAddress, Via, channelParameterCollection, helper.RemainingTime());
                    var clientCertificateToken = httpsChannelFactory.GetCertificateSecurityToken(certificateProvider, RemoteAddress, Via, channelParameterCollection, ref helper);
                    var x509Token = (X509SecurityToken)clientCertificateToken.Token;
                    clientCertificate = x509Token.Certificate;
                }

                try
                {
                    WebSocket = await CreateWebSocketWithFactoryAsync(clientCertificate, helper);
                }
                finally
                {
                    if (WebSocket != null && _cleanupStarted)
                    {
                        WebSocket.Abort();
                        CommunicationObjectAbortedException communicationObjectAbortedException = new CommunicationObjectAbortedException(
                            new WebSocketException(WebSocketError.ConnectionClosedPrematurely).Message);
                        FxTrace.Exception.AsWarning(communicationObjectAbortedException);
                        throw communicationObjectAbortedException;
                    }
                }

                bool inputUseStreaming = TransferModeHelper.IsResponseStreamed(TransferMode);

                SetMessageSource(new WebSocketMessageSource(
                                     this,
                                     WebSocket,
                                     inputUseStreaming,
                                     this));

                success = true;

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

                TryConvertAndThrow(ex);
            }
            finally
            {
                CleanupTokenProviders();
                if (!success)
                {
                    CleanupOnError();
                }
            }
        }
예제 #11
0
 public HttpClientRequestChannel(HttpChannelFactory <IRequestChannel> factory, EndpointAddress to, Uri via, bool manualAddressing)
     : base(factory, to, via, manualAddressing)
 {
     _factory = factory;
 }
예제 #12
0
        private async Task <WebSocket> CreateWebSocketWithFactoryAsync(X509Certificate2 certificate, TimeoutHelper timeoutHelper)
        {
            Contract.Assert(_connectionFactory != null, "Invalid call: CreateWebSocketWithFactory.");

            if (WcfEventSource.Instance.WebSocketCreateClientWebSocketWithFactoryIsEnabled())
            {
                WcfEventSource.Instance.WebSocketCreateClientWebSocketWithFactory(EventTraceActivity, _connectionFactory.GetType().FullName);
            }

            // Create the client WebSocket with the factory.
            WebSocket ws;

            try
            {
                if (certificate != null)
                {
                    throw ExceptionHelper.PlatformNotSupported("client certificates not supported yet");
                }
                var headers = new WebHeaderCollection();
                headers[WebSocketTransportSettings.SoapContentTypeHeader] = _channelFactory.WebSocketSoapContentType;
                if (_channelFactory.MessageEncoderFactory is BinaryMessageEncoderFactory)
                {
                    headers[WebSocketTransportSettings.BinaryEncoderTransferModeHeader] = _channelFactory.TransferMode.ToString();
                }
                if (HttpChannelFactory <IDuplexSessionChannel> .MapIdentity(RemoteAddress, _channelFactory.AuthenticationScheme))
                {
                    headers[HttpRequestHeader.Host] = HttpTransportSecurityHelpers.GeIdentityHostHeader(RemoteAddress);
                }

                var credentials = _channelFactory.GetCredentials();
                ws = await _connectionFactory.CreateWebSocketAsync(Via, headers, credentials, WebSocketSettings.Clone(), timeoutHelper);
            }
            catch (Exception e)
            {
                if (Fx.IsFatal(e))
                {
                    throw;
                }

                throw FxTrace.Exception.AsError(new InvalidOperationException(SR.Format(SR.ClientWebSocketFactory_CreateWebSocketFailed, _connectionFactory.GetType().Name), e));
            }

            // The returned WebSocket should be valid (non-null), in an opened state and with the same SubProtocol that we requested.
            if (ws == null)
            {
                throw FxTrace.Exception.AsError(new InvalidOperationException(SR.Format(SR.ClientWebSocketFactory_InvalidWebSocket, _connectionFactory.GetType().Name)));
            }

            if (ws.State != WebSocketState.Open)
            {
                ws.Dispose();
                throw FxTrace.Exception.AsError(new InvalidOperationException(SR.Format(SR.ClientWebSocketFactory_InvalidWebSocket, _connectionFactory.GetType().Name)));
            }

            string requested = WebSocketSettings.SubProtocol;
            string obtained  = ws.SubProtocol;

            if (!(requested == null ? string.IsNullOrWhiteSpace(obtained) : requested.Equals(obtained, StringComparison.OrdinalIgnoreCase)))
            {
                ws.Dispose();
                throw FxTrace.Exception.AsError(new InvalidOperationException(SR.Format(SR.ClientWebSocketFactory_InvalidSubProtocol, _connectionFactory.GetType().Name, obtained, requested)));
            }

            return(ws);
        }
        public static HttpInput ValidateRequestReplyResponse(HttpWebRequest request, HttpWebResponse response, HttpChannelFactory factory, WebException responseException, ChannelBinding channelBinding)
        {
            ValidateAuthentication(request, response, responseException, factory);
            HttpInput input = null;

            if (((HttpStatusCode.OK > response.StatusCode) || (response.StatusCode >= HttpStatusCode.MultipleChoices)) && (response.StatusCode != HttpStatusCode.InternalServerError))
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(CreateUnexpectedResponseException(responseException, response));
            }
            if ((response.StatusCode == HttpStatusCode.InternalServerError) && (string.Compare(response.StatusDescription, "System.ServiceModel.ServiceActivationException", StringComparison.OrdinalIgnoreCase) == 0))
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ServiceActivationException(System.ServiceModel.SR.GetString("Hosting_ServiceActivationFailed", new object[] { request.RequestUri })));
            }
            if (string.IsNullOrEmpty(response.ContentType))
            {
                if (!ValidateEmptyContent(response))
                {
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(TraceResponseException(new ProtocolException(System.ServiceModel.SR.GetString("HttpContentTypeHeaderRequired"), responseException)));
                }
            }
            else if (response.ContentLength != 0L)
            {
                MessageEncoder encoder = factory.MessageEncoderFactory.Encoder;
                if (!encoder.IsContentTypeSupported(response.ContentType))
                {
                    int    num;
                    string responseStreamString = GetResponseStreamString(response, out num);
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(TraceResponseException(new ProtocolException(System.ServiceModel.SR.GetString("ResponseContentTypeMismatch", new object[] { response.ContentType, encoder.ContentType, num, responseStreamString }), responseException)));
                }
                input = HttpInput.CreateHttpInput(response, factory, channelBinding);
                input.WebException = responseException;
            }
            if ((input == null) && (factory.MessageEncoderFactory.MessageVersion == MessageVersion.None))
            {
                input = HttpInput.CreateHttpInput(response, factory, channelBinding);
                input.WebException = responseException;
            }
            return(input);
        }
 private static void ValidateAuthentication(HttpWebRequest request, HttpWebResponse response, WebException responseException, HttpChannelFactory factory)
 {
     if (response.StatusCode == HttpStatusCode.Unauthorized)
     {
         string message = System.ServiceModel.SR.GetString("HttpAuthorizationFailed", new object[] { factory.AuthenticationScheme, response.Headers[HttpResponseHeader.WwwAuthenticate] });
         throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(TraceResponseException(new MessageSecurityException(message, responseException)));
     }
     if (response.StatusCode == HttpStatusCode.Forbidden)
     {
         string str2 = System.ServiceModel.SR.GetString("HttpAuthorizationForbidden", new object[] { factory.AuthenticationScheme });
         throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(TraceResponseException(new MessageSecurityException(str2, responseException)));
     }
     if ((request.AuthenticationLevel == AuthenticationLevel.MutualAuthRequired) && !response.IsMutuallyAuthenticated)
     {
         throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(TraceResponseException(new SecurityNegotiationException(System.ServiceModel.SR.GetString("HttpMutualAuthNotSatisfied"), responseException)));
     }
 }
예제 #15
0
 public ClientWebSocketTransportDuplexSessionChannel(HttpChannelFactory <IDuplexSessionChannel> channelFactory, ClientWebSocketFactory connectionFactory, EndpointAddress remoteAddresss, Uri via, ConnectionBufferPool bufferPool)
     : base(channelFactory, remoteAddresss, via, bufferPool)
 {
     this.channelFactory    = channelFactory;
     this.connectionFactory = connectionFactory;
 }