void IPolicyExportExtension.ExportPolicy(MetadataExporter exporter, PolicyConversionContext context)
        {
            if (exporter == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("exporter");
            }

            if (context == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("context");
            }

            ICollection <XmlElement> policyAssertions = context.GetBindingAssertions();

            if (TransferModeHelper.IsRequestStreamed(this.TransferMode) ||
                TransferModeHelper.IsResponseStreamed(this.TransferMode))
            {
                policyAssertions.Add(new XmlDocument().CreateElement(TransportPolicyConstants.DotNetFramingPrefix,
                                                                     TransportPolicyConstants.StreamedName, TransportPolicyConstants.DotNetFramingNamespace));
            }

            bool createdNew;
            MessageEncodingBindingElement encodingBindingElement = FindMessageEncodingBindingElement(context.BindingElements, out createdNew);

            if (createdNew && encodingBindingElement is IPolicyExportExtension)
            {
                encodingBindingElement = new BinaryMessageEncodingBindingElement();
                ((IPolicyExportExtension)encodingBindingElement).ExportPolicy(exporter, context);
            }

            WsdlExporter.WSAddressingHelper.AddWSAddressingAssertion(exporter, context, encodingBindingElement.MessageVersion.Addressing);
        }
Example #2
0
        private bool PrepareReply(ref Message message)
        {
            if (message == null)
            {
                message = this.CreateAckMessage(HttpStatusCode.Accepted, string.Empty);
            }
            if (!this.listener.ManualAddressing)
            {
                if (message.Version.Addressing != AddressingVersion.WSAddressingAugust2004)
                {
                    if ((message.Version.Addressing != AddressingVersion.WSAddressing10) && (message.Version.Addressing != AddressingVersion.None))
                    {
                        throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ProtocolException(System.ServiceModel.SR.GetString("AddressingVersionNotSupported", new object[] { message.Version.Addressing })));
                    }
                    if ((message.Headers.To != null) && ((this.listener.AnonymousUriPrefixMatcher == null) || !this.listener.AnonymousUriPrefixMatcher.IsAnonymousUri(message.Headers.To)))
                    {
                        message.Headers.To = null;
                    }
                }
                else if (((message.Headers.To == null) || (this.listener.AnonymousUriPrefixMatcher == null)) || !this.listener.AnonymousUriPrefixMatcher.IsAnonymousUri(message.Headers.To))
                {
                    message.Headers.To = message.Version.Addressing.AnonymousUri;
                }
            }
            message.Properties.AllowOutputBatching = false;
            this.httpOutput = this.GetHttpOutput(message);
            HttpDelayedAcceptStream inputStream = this.HttpInput.InputStream as HttpDelayedAcceptStream;

            if (((inputStream != null) && TransferModeHelper.IsRequestStreamed(this.listener.TransferMode)) && inputStream.EnableDelayedAccept(this.httpOutput))
            {
                return(false);
            }
            return(true);
        }
Example #3
0
        bool PrepareReply(ref Message message)
        {
            bool closeOnReceivedEof = false;

            // null means we're done
            if (message == null)
            {
                // A null message means either a one-way request or that the service operation returned null and
                // hence we can close the HttpOutput. By default we keep the HttpOutput open to allow the writing to the output
                // even after the HttpInput EOF is received and the HttpOutput will be closed only on close of the HttpRequestContext.
                closeOnReceivedEof = true;
                message            = CreateAckMessage(HttpStatusCode.Accepted, string.Empty);
            }

            if (!listener.ManualAddressing)
            {
                if (message.Version.Addressing == AddressingVersion.WSAddressingAugust2004)
                {
                    if (message.Headers.To == null ||
                        listener.AnonymousUriPrefixMatcher == null ||
                        !listener.AnonymousUriPrefixMatcher.IsAnonymousUri(message.Headers.To))
                    {
                        message.Headers.To = message.Version.Addressing.AnonymousUri;
                    }
                }
                else if (message.Version.Addressing == AddressingVersion.WSAddressing10 ||
                         message.Version.Addressing == AddressingVersion.None)
                {
                    if (message.Headers.To != null &&
                        (listener.AnonymousUriPrefixMatcher == null ||
                         !listener.AnonymousUriPrefixMatcher.IsAnonymousUri(message.Headers.To)))
                    {
                        message.Headers.To = null;
                    }
                }
                else
                {
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
                              new ProtocolException(SR.GetString(SR.AddressingVersionNotSupported, message.Version.Addressing)));
                }
            }

            message.Properties.AllowOutputBatching = false;
            this.httpOutput = GetHttpOutputCore(message);

            // Reuse the HttpInput we got previously.
            HttpInput input = this.httpPipeline.HttpInput;

            if (input != null)
            {
                HttpDelayedAcceptStream requestStream = input.GetInputStream(false) as HttpDelayedAcceptStream;
                if (requestStream != null && TransferModeHelper.IsRequestStreamed(listener.TransferMode) &&
                    requestStream.EnableDelayedAccept(this.httpOutput, closeOnReceivedEof))
                {
                    return(false);
                }
            }

            return(true);
        }
Example #4
0
        void IPolicyExportExtension.ExportPolicy(MetadataExporter exporter, PolicyConversionContext context)
        {
            bool flag;

            if (exporter == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("exporter");
            }
            if (context == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("context");
            }
            ICollection <XmlElement> bindingAssertions = context.GetBindingAssertions();

            if (TransferModeHelper.IsRequestStreamed(this.TransferMode) || TransferModeHelper.IsResponseStreamed(this.TransferMode))
            {
                bindingAssertions.Add(new XmlDocument().CreateElement("msf", "Streamed", "http://schemas.microsoft.com/ws/2006/05/framing/policy"));
            }
            MessageEncodingBindingElement element = this.FindMessageEncodingBindingElement(context.BindingElements, out flag);

            if (flag && (element is IPolicyExportExtension))
            {
                element = new BinaryMessageEncodingBindingElement();
                ((IPolicyExportExtension)element).ExportPolicy(exporter, context);
            }
            WsdlExporter.WSAddressingHelper.AddWSAddressingAssertion(exporter, context, element.MessageVersion.Addressing);
        }
        internal void SetWebSocketInfo(WebSocketContext webSocketContext, RemoteEndpointMessageProperty remoteEndpointMessageProperty, SecurityMessageProperty handshakeSecurityMessageProperty, byte[] innerBuffer, bool shouldDisposeWebSocketAfterClosed, HttpRequestMessage requestMessage)
        {
            Fx.Assert(webSocketContext != null, "webSocketContext should not be null.");
            this.ShouldDisposeWebSocketAfterClosed = shouldDisposeWebSocketAfterClosed;
            this.webSocketContext = webSocketContext;
            this.WebSocket        = webSocketContext.WebSocket;
            this.InternalBuffer   = innerBuffer;

            if (handshakeSecurityMessageProperty != null)
            {
                this.RemoteSecurity = handshakeSecurityMessageProperty;
            }

            bool inputUseStreaming = TransferModeHelper.IsRequestStreamed(this.TransferMode);

            this.webSocketMessageSource = new WebSocketMessageSource(
                this,
                this.webSocketContext,
                inputUseStreaming,
                remoteEndpointMessageProperty,
                this,
                requestMessage);

            this.SetMessageSource(this.webSocketMessageSource);
        }
Example #6
0
        public static async Task WriteMessageAsync(Message message, FramingConnection connection, bool isRequest,
                                                   IDefaultCommunicationTimeouts settings, CancellationToken token)
        {
            byte[] endBytes = null;
            if (message != null)
            {
                MessageEncoder messageEncoder     = connection.MessageEncoderFactory.Encoder;
                byte[]         envelopeStartBytes = SingletonEncoder.EnvelopeStartBytes;

                bool writeStreamed;
                if (isRequest)
                {
                    endBytes      = SingletonEncoder.EnvelopeEndFramingEndBytes;
                    writeStreamed = TransferModeHelper.IsRequestStreamed(connection.TransferMode);
                }
                else
                {
                    endBytes      = SingletonEncoder.EnvelopeEndBytes;
                    writeStreamed = TransferModeHelper.IsResponseStreamed(connection.TransferMode);
                }

                if (writeStreamed)
                {
                    await connection.Output.WriteAsync(envelopeStartBytes, token);

                    Stream connectionStream = new StreamingOutputConnectionStream(connection, settings);
                    // TODO: Determine if timeout stream is needed as StreamingOutputConnectionStream implements some timeout functionality
                    //Stream writeTimeoutStream = new TimeoutStream(connectionStream, ref timeoutHelper);
                    await messageEncoder.WriteMessageAsync(message, connectionStream);

                    await connection.Output.FlushAsync();
                }
                else
                {
                    ArraySegment <byte> messageData = messageEncoder.WriteMessage(message,
                                                                                  int.MaxValue, connection.BufferManager, envelopeStartBytes.Length + IntEncoder.MaxEncodedSize);
                    messageData = SingletonEncoder.EncodeMessageFrame(messageData);
                    Buffer.BlockCopy(envelopeStartBytes, 0, messageData.Array, messageData.Offset - envelopeStartBytes.Length,
                                     envelopeStartBytes.Length);
                    await connection.Output.WriteAsync(new ArraySegment <byte>(messageData.Array, messageData.Offset - envelopeStartBytes.Length,
                                                                               messageData.Count + envelopeStartBytes.Length), token);

                    await connection.Output.FlushAsync();

                    connection.BufferManager.ReturnBuffer(messageData.Array);
                }
            }
            else if (isRequest) // context handles response end bytes
            {
                endBytes = SingletonEncoder.EndBytes;
            }

            if (endBytes != null)
            {
                await connection.Output.WriteAsync(endBytes, token);

                await connection.Output.FlushAsync();
            }
        }
Example #7
0
        internal HttpChannelFactory(HttpTransportBindingElement bindingElement, BindingContext context)
            : base(bindingElement, context, HttpTransportDefaults.GetDefaultMessageEncoderFactory())
        {
            // validate setting interactions
            if (bindingElement.TransferMode == TransferMode.Buffered)
            {
                if (bindingElement.MaxReceivedMessageSize > int.MaxValue)
                {
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
                              new ArgumentOutOfRangeException("bindingElement.MaxReceivedMessageSize",
                                                              SR.MaxReceivedMessageSizeMustBeInIntegerRange));
                }

                if (bindingElement.MaxBufferSize != bindingElement.MaxReceivedMessageSize)
                {
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument("bindingElement",
                                                                                 SR.MaxBufferSizeMustMatchMaxReceivedMessageSize);
                }
            }
            else
            {
                if (bindingElement.MaxBufferSize > bindingElement.MaxReceivedMessageSize)
                {
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument("bindingElement",
                                                                                 SR.MaxBufferSizeMustNotExceedMaxReceivedMessageSize);
                }
            }

            if (TransferModeHelper.IsRequestStreamed(bindingElement.TransferMode) &&
                bindingElement.AuthenticationScheme != AuthenticationSchemes.Anonymous)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument("bindingElement",
                                                                             SR.HttpAuthDoesNotSupportRequestStreaming);
            }

            _allowCookies = bindingElement.AllowCookies;

            if (_allowCookies)
            {
                _httpCookieContainerManager = new HttpCookieContainerManager();
            }

            if (!bindingElement.AuthenticationScheme.IsSingleton())
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument("value", SR.Format(SR.HttpRequiresSingleAuthScheme,
                                                                                                bindingElement.AuthenticationScheme));
            }
            _authenticationScheme = bindingElement.AuthenticationScheme;
            _maxBufferSize        = bindingElement.MaxBufferSize;
            _transferMode         = bindingElement.TransferMode;
            _useDefaultWebProxy   = bindingElement.UseDefaultWebProxy;

            _channelCredentials   = context.BindingParameters.Find <SecurityCredentialsManager>();
            _securityCapabilities = bindingElement.GetProperty <ISecurityCapabilities>(context);
        }
Example #8
0
        public static async Task WriteMessageAsync(Message message, IConnection connection, bool isRequest,
                                                   IConnectionOrientedTransportFactorySettings settings, CancellationToken token)
        {
            // TODO: Switch to using the token as this is supposed to use remaining time
            var timeoutHelper = new TimeoutHelper(TimeoutHelper.GetOriginalTimeout(token));

            byte[] endBytes = null;
            if (message != null)
            {
                MessageEncoder messageEncoder     = settings.MessageEncoderFactory.Encoder;
                byte[]         envelopeStartBytes = SingletonEncoder.EnvelopeStartBytes;

                bool writeStreamed;
                if (isRequest)
                {
                    endBytes      = SingletonEncoder.EnvelopeEndFramingEndBytes;
                    writeStreamed = TransferModeHelper.IsRequestStreamed(settings.TransferMode);
                }
                else
                {
                    endBytes      = SingletonEncoder.EnvelopeEndBytes;
                    writeStreamed = TransferModeHelper.IsResponseStreamed(settings.TransferMode);
                }

                if (writeStreamed)
                {
                    await connection.WriteAsync(envelopeStartBytes, 0, envelopeStartBytes.Length, false, timeoutHelper.RemainingTime());

                    Stream connectionStream   = new StreamingOutputConnectionStream(connection, settings);
                    Stream writeTimeoutStream = new TimeoutStream(connectionStream, timeoutHelper.RemainingTime());
                    messageEncoder.WriteMessage(message, writeTimeoutStream);
                }
                else
                {
                    ArraySegment <byte> messageData = messageEncoder.WriteMessage(message,
                                                                                  int.MaxValue, settings.BufferManager, envelopeStartBytes.Length + IntEncoder.MaxEncodedSize);
                    messageData = SingletonEncoder.EncodeMessageFrame(messageData);
                    Buffer.BlockCopy(envelopeStartBytes, 0, messageData.Array, messageData.Offset - envelopeStartBytes.Length,
                                     envelopeStartBytes.Length);
                    await connection.WriteAsync(messageData.Array, messageData.Offset - envelopeStartBytes.Length,
                                                messageData.Count + envelopeStartBytes.Length, true, timeoutHelper.RemainingTime(), settings.BufferManager);
                }
            }
            else if (isRequest) // context handles response end bytes
            {
                endBytes = SingletonEncoder.EndBytes;
            }

            if (endBytes != null)
            {
                await connection.WriteAsync(endBytes, 0, endBytes.Length,
                                            true, timeoutHelper.RemainingTime());
            }
        }
Example #9
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));
     }
 }
Example #10
0
        public static void WriteMessage(Message message, IConnection connection, bool isRequest,
                                        IConnectionOrientedTransportFactorySettings settings, ref TimeoutHelper timeoutHelper)
        {
            byte[] endBytes = null;
            if (message != null)
            {
                MessageEncoder messageEncoder     = settings.MessageEncoderFactory.Encoder;
                byte[]         envelopeStartBytes = SingletonEncoder.EnvelopeStartBytes;

                bool writeStreamed;
                if (isRequest)
                {
                    endBytes      = SingletonEncoder.EnvelopeEndFramingEndBytes;
                    writeStreamed = TransferModeHelper.IsRequestStreamed(settings.TransferMode);
                }
                else
                {
                    endBytes      = SingletonEncoder.EnvelopeEndBytes;
                    writeStreamed = TransferModeHelper.IsResponseStreamed(settings.TransferMode);
                }

                if (writeStreamed)
                {
                    connection.Write(envelopeStartBytes, 0, envelopeStartBytes.Length, false, timeoutHelper.RemainingTime());
                    Stream connectionStream   = new StreamingOutputConnectionStream(connection, settings);
                    Stream writeTimeoutStream = new TimeoutStream(connectionStream, timeoutHelper.RemainingTime());
                    messageEncoder.WriteMessage(message, writeTimeoutStream);
                }
                else
                {
                    ArraySegment <byte> messageData = messageEncoder.WriteMessage(message,
                                                                                  int.MaxValue, settings.BufferManager, envelopeStartBytes.Length + IntEncoder.MaxEncodedSize);
                    messageData = SingletonEncoder.EncodeMessageFrame(messageData);
                    Buffer.BlockCopy(envelopeStartBytes, 0, messageData.Array, messageData.Offset - envelopeStartBytes.Length,
                                     envelopeStartBytes.Length);
                    connection.Write(messageData.Array, messageData.Offset - envelopeStartBytes.Length,
                                     messageData.Count + envelopeStartBytes.Length, true, timeoutHelper.RemainingTime(), settings.BufferManager);
                }
            }
            else if (isRequest) // context handles response end bytes
            {
                endBytes = SingletonEncoder.EndBytes;
            }

            if (endBytes != null)
            {
                connection.Write(endBytes, 0, endBytes.Length,
                                 true, timeoutHelper.RemainingTime());
            }
        }
Example #11
0
        internal HttpRequestMessage GetHttpRequestMessage(EndpointAddress to, Uri via)
        {
            Uri httpRequestUri = via;

            HttpRequestMessage requestMessage = null;

            requestMessage = new HttpRequestMessage(HttpMethod.Post, httpRequestUri);
            if (TransferModeHelper.IsRequestStreamed(TransferMode))
            {
                requestMessage.Headers.TransferEncodingChunked = true;
            }

            requestMessage.Headers.CacheControl = s_requestCacheHeader;
            return(requestMessage);
        }
        private Task <Message> ReadStreamAsMessageAsync()
        {
            var           content           = _httpResponseMessage.Content;
            Task <Stream> contentStreamTask = GetStreamAsync();

            if (TransferModeHelper.IsResponseStreamed(_factory.TransferMode))
            {
                return(ReadStreamedMessageAsync(contentStreamTask));
            }
            if (!content.Headers.ContentLength.HasValue)
            {
                return(ReadChunkedBufferedMessageAsync(contentStreamTask));
            }
            return(ReadBufferedMessageAsync(contentStreamTask));
        }
 public HostedRequestHttpOutput(HostedHttpRequestAsyncResult result, IHttpTransportFactorySettings settings, Message message, HostedHttpContext context) : base(settings, message, false, false)
 {
     this.result  = result;
     this.context = context;
     if (TransferModeHelper.IsResponseStreamed(settings.TransferMode))
     {
         result.SetTransferModeToStreaming();
     }
     if (message.IsFault)
     {
         this.statusCode = 500;
     }
     else
     {
         this.statusCode = 200;
     }
 }
 protected HttpInput(IHttpTransportFactorySettings settings, bool isRequest, bool enableChannelBinding)
 {
     this.settings             = settings;
     this.bufferManager        = settings.BufferManager;
     this.messageEncoder       = settings.MessageEncoderFactory.Encoder;
     this.webException         = null;
     this.isRequest            = isRequest;
     this.inputStream          = null;
     this.enableChannelBinding = enableChannelBinding;
     if (isRequest)
     {
         this.streamed = TransferModeHelper.IsRequestStreamed(settings.TransferMode);
     }
     else
     {
         this.streamed = TransferModeHelper.IsResponseStreamed(settings.TransferMode);
     }
 }
Example #15
0
        private async Task <Stream> GetStreamAsync(TimeoutHelper timeoutHelper)
        {
            var    content       = _httpResponseMessage.Content;
            Stream contentStream = null;

            _contentLength = -1;
            if (content != null)
            {
                contentStream = await content.ReadAsStreamAsync();

                _contentLength = content.Headers.ContentLength.HasValue ? content.Headers.ContentLength.Value : -1;
                var cancellationToken = await timeoutHelper.GetCancellationTokenAsync();

                if (_contentLength <= 0)
                {
                    var preReadBuffer = new byte[1];
                    if (await contentStream.ReadAsync(preReadBuffer, 0, 1, cancellationToken) == 0)
                    {
                        contentStream.Dispose();
                        contentStream = null;
                    }
                    else
                    {
                        var bufferedStream = new BufferedReadStream(contentStream, _factory.BufferManager);
                        await bufferedStream.PreReadBufferAsync(preReadBuffer[0], cancellationToken);

                        contentStream = bufferedStream;
                    }
                }
                else if (TransferModeHelper.IsResponseStreamed(_factory.TransferMode))
                {
                    // If _contentLength > 0, then the message was sent buffered but we might still
                    // be receiving it streamed. In which case we need a buffered reading stream.
                    var bufferedStream = new BufferedReadStream(contentStream, _factory.BufferManager);
                    await bufferedStream.PreReadBufferAsync(cancellationToken);

                    contentStream = bufferedStream;
                }
            }

            return(contentStream);
        }
        private async Task <Message> ReadStreamAsMessageAsync()
        {
            var     content       = _httpResponseMessage.Content;
            Message message       = null;
            Stream  contentStream = await GetStreamAsync();

            if (TransferModeHelper.IsResponseStreamed(_factory.TransferMode))
            {
                message = ReadStreamedMessage(contentStream);
            }
            else if (!content.Headers.ContentLength.HasValue)
            {
                message = ReadChunkedBufferedMessage(contentStream);
            }
            else
            {
                message = await ReadBufferedMessageAsync(contentStream);
            }
            return(message);
        }
 public static void WriteMessage(Message message, IConnection connection, bool isRequest, IConnectionOrientedTransportFactorySettings settings, ref TimeoutHelper timeoutHelper)
 {
     byte[] envelopeEndFramingEndBytes = null;
     if (message != null)
     {
         bool           flag;
         MessageEncoder encoder            = settings.MessageEncoderFactory.Encoder;
         byte[]         envelopeStartBytes = SingletonEncoder.EnvelopeStartBytes;
         if (isRequest)
         {
             envelopeEndFramingEndBytes = SingletonEncoder.EnvelopeEndFramingEndBytes;
             flag = TransferModeHelper.IsRequestStreamed(settings.TransferMode);
         }
         else
         {
             envelopeEndFramingEndBytes = SingletonEncoder.EnvelopeEndBytes;
             flag = TransferModeHelper.IsResponseStreamed(settings.TransferMode);
         }
         if (flag)
         {
             connection.Write(envelopeStartBytes, 0, envelopeStartBytes.Length, false, timeoutHelper.RemainingTime());
             Stream stream  = new StreamingOutputConnectionStream(connection, settings);
             Stream stream2 = new TimeoutStream(stream, ref timeoutHelper);
             encoder.WriteMessage(message, stream2);
         }
         else
         {
             ArraySegment <byte> segment = SingletonEncoder.EncodeMessageFrame(encoder.WriteMessage(message, 0x7fffffff, settings.BufferManager, envelopeStartBytes.Length + 5));
             Buffer.BlockCopy(envelopeStartBytes, 0, segment.Array, segment.Offset - envelopeStartBytes.Length, envelopeStartBytes.Length);
             connection.Write(segment.Array, segment.Offset - envelopeStartBytes.Length, segment.Count + envelopeStartBytes.Length, true, timeoutHelper.RemainingTime(), settings.BufferManager);
         }
     }
     else if (isRequest)
     {
         envelopeEndFramingEndBytes = SingletonEncoder.EndBytes;
     }
     if (envelopeEndFramingEndBytes != null)
     {
         connection.Write(envelopeEndFramingEndBytes, 0, envelopeEndFramingEndBytes.Length, true, timeoutHelper.RemainingTime());
     }
 }
Example #18
0
            public HostedRequestHttpOutput(HostedHttpRequestAsyncResult result, IHttpTransportFactorySettings settings,
                                           Message message, HostedHttpContext context)
                : base(settings, message, false, false)
            {
                AspNetPartialTrustHelpers.FailIfInPartialTrustOutsideAspNet();

                this.result  = result;
                this.context = context;

                if (TransferModeHelper.IsResponseStreamed(settings.TransferMode))
                {
                    result.SetTransferModeToStreaming();
                }

                if (message.IsFault)
                {
                    this.statusCode = (int)HttpStatusCode.InternalServerError;
                }
                else
                {
                    this.statusCode = (int)HttpStatusCode.OK;
                }
            }
Example #19
0
        internal void SetWebSocketInfo(WebSocketContext webSocketContext, RemoteEndpointMessageProperty remoteEndpointMessageProperty, SecurityMessageProperty handshakeSecurityMessageProperty, bool shouldDisposeWebSocketAfterClosed, HttpContext httpContext)
        {
            Fx.Assert(webSocketContext != null, "webSocketContext should not be null.");
            ShouldDisposeWebSocketAfterClosed = shouldDisposeWebSocketAfterClosed;
            _webSocketContext = webSocketContext;
            WebSocket         = webSocketContext.WebSocket;

            if (handshakeSecurityMessageProperty != null)
            {
                RemoteSecurity = handshakeSecurityMessageProperty;
            }

            bool inputUseStreaming = TransferModeHelper.IsRequestStreamed(TransferMode);

            _webSocketMessageSource = new WebSocketMessageSource(
                this,
                _webSocketContext,
                inputUseStreaming,
                remoteEndpointMessageProperty,
                this,
                httpContext);

            SetMessageSource(_webSocketMessageSource);
        }
Example #20
0
        internal HttpRequestMessage GetHttpRequestMessage(EndpointAddress to, Uri via, CancellationToken cancelToken, bool isWebSocketRequest)
        {
            Uri httpWebRequestUri = via;

            HttpRequestMessage requestMessage = null;

            if (!isWebSocketRequest)
            {
                requestMessage = new HttpRequestMessage(HttpMethod.Post, httpWebRequestUri);
                if (TransferModeHelper.IsRequestStreamed(TransferMode))
                {
                    requestMessage.Headers.TransferEncodingChunked = true;
                }
            }
            else
            {
                requestMessage = new HttpRequestMessage(HttpMethod.Get, httpWebRequestUri);
            }

            requestMessage.Headers.CacheControl = s_requestCacheHeader;


            return(requestMessage);
        }
        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();
                }
            }
        }
Example #22
0
        void HandleHttpWebResponse(HttpWebRequest request, HttpWebResponse response)
        {
            this.ValidateHttpWebResponse(response);
            this.connection = response.GetResponseStream();
            WebSocket clientWebSocket = null;

            try
            {
                if (this.connectionFactory != null)
                {
                    this.WebSocket = clientWebSocket = this.CreateWebSocketWithFactory();
                }
                else
                {
                    byte[] internalBuffer = this.TakeBuffer();
                    try
                    {
                        this.WebSocket = clientWebSocket = WebSocket.CreateClientWebSocket(
                            this.connection,
                            this.WebSocketSettings.SubProtocol,
                            WebSocketHelper.GetReceiveBufferSize(this.channelFactory.MaxReceivedMessageSize),
                            WebSocketDefaults.BufferSize,
                            this.WebSocketSettings.GetEffectiveKeepAliveInterval(),
                            this.WebSocketSettings.DisablePayloadMasking,
                            new ArraySegment <byte>(internalBuffer));
                    }
                    finally
                    {
                        // even when setting this.InternalBuffer in the finally block
                        // there is still a potential race condition, which could result
                        // in not returning 'internalBuffer' to the pool.
                        // This is acceptable since it is extremely unlikely, only for
                        // the error case and there is no big harm if the buffers are
                        // occasionally not returned to the pool. WebSocketBufferPool.Take()
                        // will just allocate new buffers;
                        this.InternalBuffer = internalBuffer;
                    }
                }
            }
            finally
            {
                // There is a race condition betwene OnCleanup and OnOpen that
                // can result in cleaning up while the clientWebSocket instance is
                // created. In this case OnCleanup won't be called anymore and would
                // not clean up the WebSocket instance immediately - only GC would
                // cleanup during finalization.
                // To avoid this we abort the WebSocket (and implicitly this.connection)
                if (clientWebSocket != null && this.cleanupStarted)
                {
                    clientWebSocket.Abort();
                    CommunicationObjectAbortedException communicationObjectAbortedException = new CommunicationObjectAbortedException(
                        new WebSocketException(WebSocketError.ConnectionClosedPrematurely).Message);
                    FxTrace.Exception.AsWarning(communicationObjectAbortedException);
                    throw communicationObjectAbortedException;
                }
            }

            bool inputUseStreaming = TransferModeHelper.IsResponseStreamed(this.TransferMode);

            SecurityMessageProperty handshakeReplySecurityMessageProperty = this.channelFactory.CreateReplySecurityProperty(request, response);

            if (handshakeReplySecurityMessageProperty != null)
            {
                this.RemoteSecurity = handshakeReplySecurityMessageProperty;
            }

            this.SetMessageSource(new WebSocketMessageSource(
                                      this,
                                      this.WebSocket,
                                      inputUseStreaming,
                                      this));
        }
        void ITransportPolicyImport.ImportPolicy(MetadataImporter importer, PolicyConversionContext policyContext)
        {
            ICollection <XmlElement> bindingAssertions  = policyContext.GetBindingAssertions();
            List <XmlElement>        httpAuthAssertions = new List <XmlElement>();

            bool foundAssertion = false;

            foreach (XmlElement assertion in bindingAssertions)
            {
                if (assertion.NamespaceURI != TransportPolicyConstants.HttpTransportNamespace)
                {
                    continue;
                }

                switch (assertion.LocalName)
                {
                case TransportPolicyConstants.BasicHttpAuthenticationName:
                    this.AuthenticationScheme = AuthenticationSchemes.Basic;
                    break;

                case TransportPolicyConstants.DigestHttpAuthenticationName:
                    this.AuthenticationScheme = AuthenticationSchemes.Digest;
                    break;

                case TransportPolicyConstants.NegotiateHttpAuthenticationName:
                    this.AuthenticationScheme = AuthenticationSchemes.Negotiate;
                    break;

                case TransportPolicyConstants.NtlmHttpAuthenticationName:
                    this.AuthenticationScheme = AuthenticationSchemes.Ntlm;
                    break;

                default:
                    continue;
                }

                if (foundAssertion)
                {
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException(
                                                                                  string.Format(SRServiceModel.HttpTransportCannotHaveMultipleAuthenticationSchemes, policyContext.Contract.Namespace, policyContext.Contract.Name)));
                }

                foundAssertion = true;
                httpAuthAssertions.Add(assertion);
            }
            httpAuthAssertions.ForEach(delegate(XmlElement element) { bindingAssertions.Remove(element); });

            // This code is being used when we are generating the client configration. Before that, we should already set TransportUsage as Always if the server
            // is using WebSocket.
            if (this.WebSocketSettings.TransportUsage == WebSocketTransportUsage.Always)
            {
                foreach (XmlElement assertion in bindingAssertions)
                {
                    if (assertion.NamespaceURI != TransportPolicyConstants.WebSocketPolicyNamespace)
                    {
                        continue;
                    }

                    string       transferMode = assertion.LocalName;
                    TransferMode result;
                    if (!Enum.TryParse <TransferMode>(transferMode, true, out result) || !TransferModeHelper.IsDefined(result) || result == TransferMode.Buffered)
                    {
                        throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException(string.Format(
                                                                                                                SRServiceModel.WebSocketTransportPolicyAssertionInvalid,
                                                                                                                policyContext.Contract.Namespace,
                                                                                                                policyContext.Contract.Name,
                                                                                                                transferMode,
                                                                                                                TransferMode.Streamed,
                                                                                                                TransferMode.StreamedRequest,
                                                                                                                TransferMode.StreamedResponse)));
                    }

                    this.TransferMode = result;
                    bindingAssertions.Remove(assertion);
                    break;
                }
            }

            OnImportPolicy(importer, policyContext);
        }
Example #24
0
        internal HttpChannelFactory(HttpTransportBindingElement bindingElement, BindingContext context)
            : base(bindingElement, context, HttpTransportDefaults.GetDefaultMessageEncoderFactory())
        {
            // validate setting interactions
            if (bindingElement.TransferMode == TransferMode.Buffered)
            {
                if (bindingElement.MaxReceivedMessageSize > int.MaxValue)
                {
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
                              new ArgumentOutOfRangeException("bindingElement.MaxReceivedMessageSize",
                                                              SR.MaxReceivedMessageSizeMustBeInIntegerRange));
                }

                if (bindingElement.MaxBufferSize != bindingElement.MaxReceivedMessageSize)
                {
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument("bindingElement",
                                                                                 SR.MaxBufferSizeMustMatchMaxReceivedMessageSize);
                }
            }
            else
            {
                if (bindingElement.MaxBufferSize > bindingElement.MaxReceivedMessageSize)
                {
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument("bindingElement",
                                                                                 SR.MaxBufferSizeMustNotExceedMaxReceivedMessageSize);
                }
            }

            if (TransferModeHelper.IsRequestStreamed(bindingElement.TransferMode) &&
                bindingElement.AuthenticationScheme != AuthenticationSchemes.Anonymous)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument("bindingElement",
                                                                             SR.HttpAuthDoesNotSupportRequestStreaming);
            }

            _allowCookies = bindingElement.AllowCookies;

            if (_allowCookies)
            {
                _httpCookieContainerManager = new HttpCookieContainerManager();
            }

            if (!bindingElement.AuthenticationScheme.IsSingleton())
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument("value", SR.Format(SR.HttpRequiresSingleAuthScheme,
                                                                                                bindingElement.AuthenticationScheme));
            }
            _authenticationScheme = bindingElement.AuthenticationScheme;
            _maxBufferSize        = bindingElement.MaxBufferSize;
            _transferMode         = bindingElement.TransferMode;
            _useDefaultWebProxy   = bindingElement.UseDefaultWebProxy;

            _channelCredentials   = context.BindingParameters.Find <SecurityCredentialsManager>();
            _securityCapabilities = bindingElement.GetProperty <ISecurityCapabilities>(context);

            _webSocketSettings = WebSocketHelper.GetRuntimeWebSocketSettings(bindingElement.WebSocketSettings);
            int webSocketBufferSize = WebSocketHelper.ComputeClientBufferSize(MaxReceivedMessageSize);

            _bufferPool               = new ConnectionBufferPool(webSocketBufferSize);
            _clientWebSocketFactory   = ClientWebSocketFactory.GetFactory();
            _webSocketSoapContentType = new Lazy <string>(() => MessageEncoderFactory.CreateSessionEncoder().ContentType, LazyThreadSafetyMode.ExecutionAndPublication);
        }
            public WriteMessageAsyncResult(Message message, IConnection connection, bool isRequest, IConnectionOrientedTransportFactorySettings settings, ref TimeoutHelper timeoutHelper, AsyncCallback callback, object state) : base(callback, state)
            {
                this.connection    = connection;
                this.encoder       = settings.MessageEncoderFactory.Encoder;
                this.bufferManager = settings.BufferManager;
                this.timeoutHelper = timeoutHelper;
                this.message       = message;
                this.settings      = settings;
                bool flag  = true;
                bool flag2 = false;

                if (message == null)
                {
                    if (isRequest)
                    {
                        this.endBytes = SingletonEncoder.EndBytes;
                    }
                    flag2 = this.WriteEndBytes();
                }
                else
                {
                    try
                    {
                        bool   flag3;
                        byte[] envelopeStartBytes = SingletonEncoder.EnvelopeStartBytes;
                        if (isRequest)
                        {
                            this.endBytes = SingletonEncoder.EnvelopeEndFramingEndBytes;
                            flag3         = TransferModeHelper.IsRequestStreamed(settings.TransferMode);
                        }
                        else
                        {
                            this.endBytes = SingletonEncoder.EnvelopeEndBytes;
                            flag3         = TransferModeHelper.IsResponseStreamed(settings.TransferMode);
                        }
                        if (flag3)
                        {
                            if (onWriteStartBytes == null)
                            {
                                onWriteStartBytes = Fx.ThunkCallback(new AsyncCallback(StreamingConnectionHelper.WriteMessageAsyncResult.OnWriteStartBytes));
                            }
                            IAsyncResult result = connection.BeginWrite(envelopeStartBytes, 0, envelopeStartBytes.Length, true, timeoutHelper.RemainingTime(), onWriteStartBytes, this);
                            if (result.CompletedSynchronously)
                            {
                                if (onWriteStartBytesScheduled == null)
                                {
                                    onWriteStartBytesScheduled = new Action <object>(StreamingConnectionHelper.WriteMessageAsyncResult.OnWriteStartBytesScheduled);
                                }
                                ActionItem.Schedule(onWriteStartBytesScheduled, result);
                            }
                        }
                        else
                        {
                            ArraySegment <byte> segment = SingletonEncoder.EncodeMessageFrame(settings.MessageEncoderFactory.Encoder.WriteMessage(message, 0x7fffffff, this.bufferManager, envelopeStartBytes.Length + 5));
                            this.bufferToFree = segment.Array;
                            Buffer.BlockCopy(envelopeStartBytes, 0, segment.Array, segment.Offset - envelopeStartBytes.Length, envelopeStartBytes.Length);
                            if (onWriteBufferedMessage == null)
                            {
                                onWriteBufferedMessage = Fx.ThunkCallback(new AsyncCallback(StreamingConnectionHelper.WriteMessageAsyncResult.OnWriteBufferedMessage));
                            }
                            IAsyncResult result2 = connection.BeginWrite(segment.Array, segment.Offset - envelopeStartBytes.Length, segment.Count + envelopeStartBytes.Length, true, timeoutHelper.RemainingTime(), onWriteBufferedMessage, this);
                            if (result2.CompletedSynchronously)
                            {
                                flag2 = this.HandleWriteBufferedMessage(result2);
                            }
                        }
                        flag = false;
                    }
                    finally
                    {
                        if (flag)
                        {
                            this.Cleanup();
                        }
                    }
                }
                if (flag2)
                {
                    base.Complete(true);
                }
            }