public ServerProcessing ProcessMessage(IServerChannelSinkStack sinkStack, IMessage requestMsg,
                                           ITransportHeaders requestHeaders, Stream requestStream,
                                           out IMessage msg, out ITransportHeaders responseHeaders,
                                           out Stream responseStream)
    {
        sinkStack.Push(this, null);
        ServerProcessing processing =
            nextServerSink.ProcessMessage(sinkStack, requestMsg, requestHeaders, requestStream, out msg,
                                          out responseHeaders, out responseStream);

        switch (processing)
        {
        case ServerProcessing.Complete:
        {
            sinkStack.Pop(this);
            break;
        }

        case ServerProcessing.OneWay:
        {
            sinkStack.Pop(this);
            break;
        }

        case ServerProcessing.Async:
        {
            sinkStack.Store(this, null);
            break;
        }
        }
        return(processing);
    }
Example #2
0
        public ServerProcessing ProcessMessage(IServerChannelSinkStack sinkStack,
                                               IMessage requestMsg,
                                               ITransportHeaders requestHeaders,
                                               Stream requestStream,
                                               out IMessage responseMsg,
                                               out ITransportHeaders responseHeaders,
                                               out Stream responseStream
                                               )
        {
            if (bEnabled2)
            {
                Console.WriteLine("----------Request Headers-----------");
// <Snippet2>
                Console.WriteLine(CommonTransportKeys.IPAddress + ":" +
                                  requestHeaders[CommonTransportKeys.IPAddress]);
// </Snippet2>
// <Snippet3>
                Console.WriteLine(CommonTransportKeys.ConnectionId + ":" +
                                  requestHeaders[CommonTransportKeys.ConnectionId]);
// </Snippet3>
// <Snippet4>
                Console.WriteLine(CommonTransportKeys.RequestUri + ":" +
                                  requestHeaders[CommonTransportKeys.RequestUri]);
// </Snippet4>
            }
            sinkStack.Push(this, null);
            ServerProcessing processing =
                nextSink2.ProcessMessage(sinkStack, requestMsg, requestHeaders, requestStream, out responseMsg,
                                         out responseHeaders, out responseStream);

            switch (processing)
            {
            case ServerProcessing.Complete:
            {
                sinkStack.Pop(this);
                break;
            }

            case ServerProcessing.OneWay:
            {
                sinkStack.Pop(this);
                break;
            }

            case ServerProcessing.Async:
            {
                sinkStack.Store(this, null);
                break;
            }
            }
            return(processing);
        }
// <Snippet3>
        public ServerProcessing ProcessMessage(IServerChannelSinkStack myServerChannelSinkStack,
                                               IMessage requestMsg, ITransportHeaders requestHeaders, Stream requestStream,
                                               out IMessage msg, out ITransportHeaders responseHeaders,
                                               out Stream responseStream)
        {
            if (myBoolEnabled)
            {
                LoggingHelper.PrintRequest(myTextWriterOutput, requestHeaders, ref requestStream);
            }

            myServerChannelSinkStack.Push(this, null);
// <Snippet4>
// <Snippet5>
// <Snippet6>
            ServerProcessing myServerProcessing =
                myNewNextSink.ProcessMessage(myServerChannelSinkStack, requestMsg, requestHeaders, requestStream, out msg,
                                             out responseHeaders, out responseStream);

            Console.WriteLine("ServerProcessing.Complete value is:   " + ServerProcessing.Complete);
            Console.WriteLine("ServerProcessing.OneWay Value is:     " + ServerProcessing.OneWay);
            Console.WriteLine("ServerProcessing.Async value is:      " + ServerProcessing.Async);

            switch (myServerProcessing)
            {
            case ServerProcessing.Complete:
            {
                myServerChannelSinkStack.Pop(this);
                if (myBoolEnabled)
                {
                    LoggingHelper.PrintResponse(myTextWriterOutput, responseHeaders, ref responseStream);
                }
                break;
            }

            case ServerProcessing.OneWay:
            {
                myServerChannelSinkStack.Pop(this);
                break;
            }

            case ServerProcessing.Async:
            {
                myServerChannelSinkStack.Store(this, null);
                break;
            }
            }
            return(myServerProcessing);
// </Snippet6>
// </Snippet5>
// </Snippet4>
        }
Example #4
0
        public ServerProcessing ProcessMessage(IServerChannelSinkStack sinkStack, IMessage requestMsg, ITransportHeaders requestHeaders, Stream requestStream, out IMessage responseMsg, out ITransportHeaders responseHeaders, out Stream responseStream)
        {
            if (requestMsg != null)
            {
                return(_next.ProcessMessage(sinkStack, requestMsg, requestHeaders, requestStream, out responseMsg, out responseHeaders, out responseStream));
            }

            try
            {
                IPAddress IPAddr = (IPAddress)requestHeaders[CommonTransportKeys.IPAddress];
                //===================================
                //Console.WriteLine(IPAddr.ToString());
                //====================================
                CallContext.SetData("ClientIP", IPAddr);
                //IPHostEntry hostInfo = Dns.Resolve("");
                //string _hs = requestHeaders[CommonTransportKeys.RequestUri].ToString() ;
                //CallContext.SetData("ClientHost",_hs);
            }
            catch (Exception ex)
            {
                string errmsg = ex.Message;
            }

            requestStream = CompressSinkHelper.DecompressStream(requestHeaders, requestStream);
            sinkStack.Push(this, null);
            ServerProcessing processing = _next.ProcessMessage(sinkStack, null, requestHeaders, requestStream, out responseMsg, out responseHeaders, out responseStream);

            //	这样写是否有效还未验证, ???
            //			if (CompressSinkHelper.IsClientSupportCompress(requestHeaders))
            //				CompressSinkHelper.SetClientSupportCompressFlag(responseHeaders);

            switch (processing)
            {
            case ServerProcessing.Complete:
                sinkStack.Pop(this);
                if (CompressSinkHelper.IsClientSupportCompress(requestHeaders))
                {
                    responseStream = CompressSinkHelper.CompressStream(responseHeaders, responseStream);
                }
                break;

            case ServerProcessing.OneWay:
                sinkStack.Pop(this);
                break;

            case ServerProcessing.Async:
                sinkStack.Store(this, null);
                break;
            }
            return(processing);
        }
Example #5
0
        public ServerProcessing ProcessMessage(IServerChannelSinkStack sinkStack
                                               , IMessage requestMsg
                                               , ITransportHeaders requestHeaders
                                               , Stream requestStream
                                               , out IMessage responseMsg
                                               , out ITransportHeaders responseHeaders
                                               , out System.IO.Stream responseStream)
        {
            if (requestMsg != null)
            {
                return(this.NextChannelSink.ProcessMessage(sinkStack
                                                           , requestMsg
                                                           , requestHeaders
                                                           , requestStream
                                                           , out responseMsg
                                                           , out responseHeaders
                                                           , out responseStream));
            }

            requestMsg = DeserializeRequestMessage(requestHeaders, requestStream);

            sinkStack.Push(this, null);

            var result = this.NextChannelSink.ProcessMessage(sinkStack
                                                             , requestMsg
                                                             , requestHeaders
                                                             , null
                                                             , out responseMsg
                                                             , out responseHeaders
                                                             , out responseStream);

            switch (result)
            {
            case ServerProcessing.Complete:
                sinkStack.Pop(this);
                SerializeResponseMessage(sinkStack, responseMsg, ref responseHeaders, ref responseStream);
                break;

            case ServerProcessing.OneWay:
                sinkStack.Pop(this);
                break;

            case ServerProcessing.Async:
                sinkStack.Store(this, null);
                break;
            }

            return(result);
        }
Example #6
0
		/// <summary>
		/// Verarbeitet eine einzele Clientanfrage
		/// </summary>
		/// <param name="sinkStack">Aufrufstapel der Kanalsenken</param>
		/// <param name="requestMsg">Anfrage-nachricht</param>
		/// <param name="requestHeaders">Anfrage-Header</param>
		/// <param name="requestStream">Anfrage-Datenstrom</param>
		/// <param name="responseMsg">Antwort-Nachricht</param>
		/// <param name="responseHeaders">Antwort-Header</param>
		/// <param name="responseStream">Antwort-Datenstrom</param>
		/// <returns>Status serverseitigen Verarbeitung der Nachricht insgesamt</returns>
		public ServerProcessing ProcessMessage(IServerChannelSinkStack sinkStack, IMessage requestMsg, ITransportHeaders requestHeaders, Stream requestStream, out IMessage responseMsg, out ITransportHeaders responseHeaders, out Stream responseStream)
		{

			// Aktuelle Kanalsenke auf den Senkenstapel legen, damit AsyncProcessResponse später ggf. asynchron aufgerufen werden kann
			sinkStack.Push(this, null);

			//Threadsave
			lock (_lockObject)
			{
				//Verarbeite die Nachricht
				DoProcessMessageBefore(requestMsg, requestHeaders, requestStream);
			}

			// Variable für Verarbeitungsstatus
			ServerProcessing processingResult;

			// Nachricht gleich an die nächste Senke zur Weiterverarbeitung übergeben
			processingResult = _next.ProcessMessage(sinkStack, requestMsg, requestHeaders, requestStream, out responseMsg, out responseHeaders, out responseStream);

			//Threadsave
			lock (_lockObject)
			{
				//Verarbeite die Nachricht
				DoProcessMessageAfter(responseMsg, responseHeaders, responseStream, requestHeaders);
			}

			// Aktuelle Senke wieder vom Senkenstapel runternehmen
			sinkStack.Pop(this);

			return processingResult;
		}
        /// <summary>
        /// Requests message processing from the current sink.
        /// </summary>
        /// <param name="sinkStack">A stack of channel sinks that called the current sink.</param>
        /// <param name="requestMsg">The message that contains the request.</param>
        /// <param name="requestHeaders">Headers retrieved from the incoming message from the client.</param>
        /// <param name="requestStream">The stream that needs to be to processed and passed on to the deserialization sink.</param>
        /// <param name="responseMsg">When this method returns, contains a <see cref="T:System.Runtime.Remoting.Messaging.IMessage" /> that holds the response message. This parameter is passed uninitialized.</param>
        /// <param name="responseHeaders">When this method returns, contains a <see cref="T:System.Runtime.Remoting.Channels.ITransportHeaders" /> that holds the headers that are to be added to return message heading to the client. This parameter is passed uninitialized.</param>
        /// <param name="responseStream">When this method returns, contains a <see cref="T:System.IO.Stream" /> that is heading back to the transport sink. This parameter is passed uninitialized.</param>
        public ServerProcessing ProcessMessage(IServerChannelSinkStack sinkStack, IMessage requestMsg, ITransportHeaders requestHeaders, Stream requestStream, out IMessage responseMsg, out ITransportHeaders responseHeaders, out Stream responseStream)
        {
            // Read secure transaction identifier from request headers
            string strTransactID = (string)requestHeaders[CommonHeaderNames.SECURE_TRANSACTION_ID];
            Guid transactID = (strTransactID == null ? Guid.Empty : new Guid(strTransactID));

            // Read current transaction step and client IP address from request headers
            SecureTransactionStage transactionStage = (SecureTransactionStage)Convert.ToInt32((string)requestHeaders[CommonHeaderNames.SECURE_TRANSACTION_STATE]);
            IPAddress clientAddress = requestHeaders[CommonTransportKeys.IPAddress] as IPAddress;

            // Put current channel sink to the sink stack so AsyncProcessResponse can be called asynchronously if necessary order
            sinkStack.Push(this, null);
            ServerProcessing processingResult;

            try
            {
                switch (transactionStage)
                {
                    case SecureTransactionStage.SendingPublicKey: // Client sends the public key to the server

                        // Generate shared key and encrypt with the public key of the client
                        processingResult = MakeSharedKey(transactID, requestHeaders, out responseMsg, out responseHeaders, out responseStream);

                        break;

                    case SecureTransactionStage.SendingEncryptedMessage: // Client sends the encrypted request message to the server

                        if (IsExistingSecurityTransaction(transactID))
                            processingResult = ProcessEncryptedMessage(transactID, sinkStack, requestMsg, requestHeaders, requestStream, out responseMsg, out responseHeaders, out responseStream);
                        else
                            throw new CryptoRemotingException(string.Format(LanguageResource.CryptoRemotingException_InvalidClientRequest, SecureTransactionStage.UnknownTransactionID));

                        break;

                    case SecureTransactionStage.Uninitialized: // Uninitialized, nothing has happened

                        // Check if encryption is not required for this client address
                        if (!RequireEncryption(clientAddress))
                            processingResult = _next.ProcessMessage(sinkStack, requestMsg, requestHeaders, requestStream, out responseMsg, out responseHeaders, out responseStream);
                        else
                            throw new CryptoRemotingException(LanguageResource.CryptoRemotingException_ServerRequiresEncryption);

                        break;

                    default:

                        throw new CryptoRemotingException(string.Format(LanguageResource.CryptoRemotingException_InvalidClientRequest, transactionStage));
                }
            }
            catch (CryptoRemotingException)
            {
                processingResult = SendEmptyToClient(sinkStack, requestMsg, requestHeaders, requestStream,
                    transactionStage, out responseMsg, out responseHeaders, out responseStream);
                requestMsg = null;
            }

            // Pop the current sink from the sink stack
            sinkStack.Pop(this);
            return processingResult;
        }
Example #8
0
        public ServerProcessing ProcessMessage(IServerChannelSinkStack sinkStack, IMessage requestMsg, ITransportHeaders requestHeaders, Stream requestStream, out IMessage responseMsg, out ITransportHeaders responseHeaders, out Stream responseStream)
        {
            bool clientCompressed = false;

            // decompress the shits
            Stream decompressedStream;

            if (object.Equals(requestHeaders[CompressionHelper.CompressKey], CompressionHelper.CompressedFlag))
            {
                //Debug.WriteLine("client compressed");
                clientCompressed   = true;
                decompressedStream = CompressionHelper.DecompressStream(requestStream);
                // close the request stream
                requestStream.Close();
            }
            else
            {
                if (object.Equals(requestHeaders[CompressionHelper.CompressKey], CompressionHelper.CompressRequest))
                {
                    //Debug.WriteLine("client requesting compress");
                    clientCompressed = true;
                }

                decompressedStream = requestStream;
            }

            sinkStack.Push(this, new ClientState(clientCompressed));

            // send the decompressed message on through the sink chain
            ServerProcessing processingResult = _next.ProcessMessage(sinkStack, requestMsg, requestHeaders, decompressedStream, out responseMsg, out responseHeaders, out responseStream);

            // get the compressed stream
            if (clientCompressed && processingResult == ServerProcessing.Complete)
            {
                Stream compressedStream = CompressionHelper.CompressStream(responseStream);
                responseStream.Close();
                responseStream = compressedStream;
                responseHeaders[CompressionHelper.CompressKey] = CompressionHelper.CompressedFlag;
            }

            // Take us off the stack and return the result.
            if (processingResult == ServerProcessing.Async)
            {
                sinkStack.Store(this, new ClientState(clientCompressed));
            }
            else
            {
                sinkStack.Pop(this);
            }
            return(processingResult);
        }
        public ServerProcessing ProcessMessage(IServerChannelSinkStack sinkStack,
                                               IMessage requestMsg, ITransportHeaders requestHeaders, Stream requestStream,
                                               out IMessage responseMsg, out ITransportHeaders responseHeaders, out Stream responseStream)
        {
            IMethodCallMessage msg = (IMethodCallMessage)requestMsg;

//			Console.WriteLine ("MESSAGE: " + msg.TypeName + " - " + msg.MethodName);

            sinkStack.Push(this, null);

            if (Attribute.IsDefined(msg.MethodBase, typeof(NoGuiDispatchAttribute)))
            {
                ServerProcessing ret;
                try
                {
                    ret = nextSink.ProcessMessage(sinkStack,
                                                  requestMsg,
                                                  requestHeaders,
                                                  requestStream,
                                                  out responseMsg,
                                                  out responseHeaders,
                                                  out responseStream);
                }
                finally
                {
                    sinkStack.Pop(this);
                }
                return(ret);
            }
            else
            {
                Dispatcher d = new Dispatcher();
                d.nextSink       = nextSink;
                d.sinkStack      = sinkStack;
                d.requestMsg     = requestMsg;
                d.requestHeaders = requestHeaders;
                d.requestStream  = requestStream;

                Gtk.Application.Invoke(d.Dispatch);
                responseMsg     = null;
                responseHeaders = null;
                responseStream  = null;

                return(ServerProcessing.Async);
            }
        }
Example #10
0
 public ServerProcessing ProcessMessage(IServerChannelSinkStack sinkStack, IMessage requestMsg, ITransportHeaders requestHeaders, Stream requestStream, out IMessage responseMsg, out ITransportHeaders responseHeaders, out Stream responseStream)
 {
     sinkStack.Push(this, null);
     ServerProcessing serverProcessing = _nextSink.ProcessMessage(sinkStack, requestMsg, requestHeaders, requestStream, out responseMsg, out responseHeaders, out responseStream);
     switch (serverProcessing)
     {
         case ServerProcessing.Async:
             sinkStack.StoreAndDispatch(this, null);
             return serverProcessing;
         case ServerProcessing.OneWay:
         case ServerProcessing.Complete:
             sinkStack.Pop(this);
             return serverProcessing;
         default:
             return serverProcessing;
     }
 }
Example #11
0
        /// <summary>
        /// Requests message processing from the current sink.
        /// </summary>
        /// <param name="sinkStack">A stack of channel sinks that called the current sink.</param>
        /// <param name="requestMsg">The message that contains the request.</param>
        /// <param name="requestHeaders">Headers retrieved from the incoming message from the client.</param>
        /// <param name="requestStream">The stream that needs to be to processed and passed on to the deserialization sink.</param>
        /// <param name="responseMsg">When this method returns, contains a <see cref="T:System.Runtime.Remoting.Messaging.IMessage"/> that holds the response message. This parameter is passed uninitialized.</param>
        /// <param name="responseHeaders">When this method returns, contains a <see cref="T:System.Runtime.Remoting.Channels.ITransportHeaders"/> that holds the headers that are to be added to return message heading to the client. This parameter is passed uninitialized.</param>
        /// <param name="responseStream">When this method returns, contains a <see cref="T:System.IO.Stream"/> that is heading back to the transport sink. This parameter is passed uninitialized.</param>
        /// <returns>
        /// A <see cref="T:System.Runtime.Remoting.Channels.ServerProcessing"/> status value that provides information about how message was processed.
        /// </returns>
        /// <exception cref="T:System.Security.SecurityException">The immediate caller does not have infrastructure permission. </exception>
        public ServerProcessing ProcessMessage(IServerChannelSinkStack sinkStack, IMessage requestMsg, ITransportHeaders requestHeaders, Stream requestStream, out IMessage responseMsg, out ITransportHeaders responseHeaders, out Stream responseStream)
        {
            // Push this onto the sink stack
            sinkStack.Push(this, null);

            // If the request has the compression flag, decompress the stream.
            if (requestHeaders[CommonHeaders.CompressionEnabled] != null)
            {
                // Determine compression method
                var method = CompressionMethod.Default;
                if (requestHeaders[CommonHeaders.CompressionMethod] != null)
                {
                    method = (CompressionMethod)Convert.ToInt32(requestHeaders[CommonHeaders.CompressionMethod]);
                }

                // Process the message and decompress it.
                requestStream = CompressionHelper.Decompress(requestStream, method);
            }

            // Retrieve the response from the server.
            var processingResult = _next.ProcessMessage(sinkStack, requestMsg, requestHeaders, requestStream,
                                                        out responseMsg, out responseHeaders, out responseStream);

            // If the response stream length is greater than the threshold,
            // message is not exempt from compression, and client supports compression,
            // compress the stream.
            if (processingResult == ServerProcessing.Complete &&
                _compressionThreshold > 0 &&
                responseStream.Length > _compressionThreshold &&
                !IsCompressionExempt(responseMsg) &&
                requestHeaders[CommonHeaders.CompressionSupported] != null)
            {
                // Process the message and compress it.
                responseStream = CompressionHelper.Compress(responseStream, _compressionMethod);

                // Send the compression flag to the client.
                responseHeaders[CommonHeaders.CompressionEnabled] = "true";
                responseHeaders[CommonHeaders.CompressionMethod]  = ((int)_compressionMethod).ToString();
            }

            // Take off the stack and return the result.
            sinkStack.Pop(this);
            return(processingResult);
        }
Example #12
0
        public ServerProcessing ProcessMessage(IServerChannelSinkStack sinkStack, IMessage requestMsg, ITransportHeaders requestHeaders, Stream requestStream, out IMessage responseMsg, out ITransportHeaders responseHeaders, out Stream responseStream)
        {
            sinkStack.Push(this, null);
            ServerProcessing serverProcessing = _nextSink.ProcessMessage(sinkStack, requestMsg, requestHeaders, requestStream, out responseMsg, out responseHeaders, out responseStream);

            switch (serverProcessing)
            {
            case ServerProcessing.Async:
                sinkStack.StoreAndDispatch(this, null);
                return(serverProcessing);

            case ServerProcessing.OneWay:
            case ServerProcessing.Complete:
                sinkStack.Pop(this);
                return(serverProcessing);

            default:
                return(serverProcessing);
            }
        }
		public ServerProcessing ProcessMessage (IServerChannelSinkStack sinkStack,
							IMessage requestMsg, ITransportHeaders requestHeaders, Stream requestStream,
							out IMessage responseMsg, out ITransportHeaders responseHeaders, out Stream responseStream)
		{
			IMethodCallMessage msg = (IMethodCallMessage) requestMsg;
//			Console.WriteLine ("MESSAGE: " + msg.TypeName + " - " + msg.MethodName);
			
			sinkStack.Push (this, null);

			if (Attribute.IsDefined (msg.MethodBase, typeof(NoGuiDispatchAttribute))) {
				ServerProcessing ret;
				try {
					ret = nextSink.ProcessMessage (sinkStack,
								 requestMsg,
								 requestHeaders,
								 requestStream,
								 out responseMsg,
								 out responseHeaders,
								 out responseStream);
				} finally {
					sinkStack.Pop (this);
				}
				return ret;
			}
			else
			{
				Dispatcher d = new Dispatcher ();
				d.nextSink = nextSink;
				d.sinkStack = sinkStack;
				d.requestMsg = requestMsg;
				d.requestHeaders = requestHeaders;
				d.requestStream = requestStream;
				
				Gtk.Application.Invoke (d.Dispatch);
				responseMsg = null;
				responseHeaders = null;
				responseStream = null;
				
				return ServerProcessing.Async;
			}
		}
        /// <summary>Requests message processing from the current sink.</summary>
        /// <param name="sinkStack">A stack of channel sinks</param>
        /// <param name="requestMsg">Request message.</param>
        /// <param name="requestHeaders">Headers sent by client.</param>
        /// <param name="requestStream">Stream to be processed..</param>
        /// <param name="responseMsg">Response message.</param>
        /// <param name="responseHeaders">Response headers.</param>
        /// <param name="responseStream">Response stream.</param>
        /// <returns>Status of the server message processing.</returns>
        public ServerProcessing ProcessMessage(
            IServerChannelSinkStack sinkStack, IMessage requestMsg, ITransportHeaders requestHeaders, Stream requestStream,
            out IMessage responseMsg, out ITransportHeaders responseHeaders, out Stream responseStream)
        {
            // Get header information about transaction
            string            strTransactID = (string)requestHeaders[CommonHeaders.ID];
            Guid              transactID    = (strTransactID == null ? Guid.Empty : new Guid(strTransactID));
            SecureTransaction transactType  = (SecureTransaction)Convert.ToInt32((string)requestHeaders[CommonHeaders.Transaction]);

            // For reference, find out who is connecting to us.  We can use this to filter
            // and to enforce security based on client identity.
            IPAddress clientAddress = requestHeaders[CommonTransportKeys.IPAddress] as IPAddress;

            // Set the IP address and port of our client
            CallContext.SetData("ClientIP", clientAddress);

            // Push this onto the sink stack
            sinkStack.Push(this, null);

            // Process the transaction based on its type (as stored in the CommonHeaders.Transaction header field)
            ServerProcessing processingResult;

            switch (transactType)
            {
            case SecureTransaction.SendingPublicKey:
                // We've received a request from a new client asking for a shared key (by sending us
                // his RSA public key).  Create a shared key, encrypt it, and send it back to him.
                processingResult = MakeSharedKey(transactID, requestHeaders, out responseMsg, out responseHeaders, out responseStream);
                System.Diagnostics.Debug.WriteLine("Connection added: " + transactID);
                break;

            case SecureTransaction.SendingEncryptedMessage:
                // We've received an encrypted message.  Decrypt it and send it along to the next sink.
                // But first make sure we have a record of the transaction.
                if (PreviousTransactionWithClient(transactID))
                {
                    processingResult = ProcessEncryptedMessage(
                        transactID, sinkStack,
                        requestMsg, requestHeaders, requestStream,
                        out responseMsg, out responseHeaders, out responseStream);
                }
                // Otherwise, let the client know that we don't recognize him.
                else
                {
                    processingResult = SendEmptyToClient(
                        SecureTransaction.UnknownIdentifier,
                        out responseMsg, out responseHeaders, out responseStream);
                    System.Diagnostics.Debug.WriteLine("Unknown connection: " + transactID);
                }
                break;

            case SecureTransaction.Uninitialized:
                // The transaction type did not match any known type, or wasn't specified.
                // So just pass on the message to the next sink.  This shouldn't happen
                // unless the client isn't using the SecureClientSink provider, in which
                // case this is the correct behavior.
                if (!RequireSecurity(clientAddress))
                {
                    processingResult = _next.ProcessMessage(
                        sinkStack, requestMsg, requestHeaders, requestStream,
                        out responseMsg, out responseHeaders, out responseStream);
                }
                // If the server has elected not to allow plaintext traffic, let the
                // client know that we're not happy.
                else
                {
                    throw new SecureRemotingException("Server requires a secure connection for this client");
                }
                break;

            default:
                // Houston, we have a problem!
                throw new SecureRemotingException("Invalid request from client: " + transactType + ".");
            }

            // Take us off the stack and return the result.
            sinkStack.Pop(this);
            return(processingResult);
        }
            public ServerProcessing ProcessMessage(IServerChannelSinkStack sinkStack
                , IMessage requestMsg
                , ITransportHeaders requestHeaders
                , Stream requestStream
                , out IMessage responseMsg
                , out ITransportHeaders responseHeaders
                , out Stream responseStream)
            {
                if (requestMsg != null)
                    return this.NextChannelSink.ProcessMessage(sinkStack
                        , requestMsg
                        , requestHeaders
                        , requestStream
                        , out responseMsg
                        , out responseHeaders
                        , out responseStream);

                requestMsg = DeserializeRequestMessage(requestHeaders, requestStream);

                sinkStack.Push(this, null);

                var result = this.NextChannelSink.ProcessMessage(sinkStack
                    , requestMsg
                    , requestHeaders
                    , null
                    , out responseMsg
                    , out responseHeaders
                    , out responseStream);

                switch (result)
                {
                    case ServerProcessing.Complete:
                        sinkStack.Pop(this);
                        SerializeResponseMessage(sinkStack, responseMsg, ref responseHeaders, ref responseStream);
                        break;
                    case ServerProcessing.OneWay:
                        sinkStack.Pop(this);
                        break;
                    case ServerProcessing.Async:
                        sinkStack.Store(this, null);
                        break;
                }

                return result;
            }
        public ServerProcessing ProcessMessage(IServerChannelSinkStack sinkStack, IMessage requestMsg, ITransportHeaders requestHeaders, Stream requestStream, out IMessage responseMsg, out ITransportHeaders responseHeaders, out Stream responseStream)
        {
            // reversed engineered from .NET framework class
            if (requestMsg != null)
            {
                return(nextSink.ProcessMessage(sinkStack, requestMsg, requestHeaders, requestStream, out responseMsg, out responseHeaders, out responseStream));
            }

            if (requestHeaders == null)
            {
                throw new ArgumentNullException("requestHeaders");
            }

            responseHeaders = null;
            responseStream  = null;
            responseMsg     = null;

            string contentType = (string)requestHeaders["Content-Type"];
            string requestVerb = (string)requestHeaders["__RequestVerb"];

            if (contentType != "application/octet-stream" || (requestVerb != "POST" && requestVerb != "M-POST"))
            {
                if (nextSink == null)
                {
                    responseHeaders = new TransportHeaders();
                    responseHeaders["__HttpStatusCode"]   = "400";
                    responseHeaders["__HttpReasonPhrase"] = "Bad Request";
                    return(ServerProcessing.Complete);
                }

                return(nextSink.ProcessMessage(sinkStack, null, requestHeaders, requestStream, out responseMsg, out responseHeaders, out responseStream));
            }

            object customErrors = requestHeaders["__CustomErrorsEnabled"];

            if (customErrors != null && customErrors is bool)
            {
                CallContext.SetData("__CustomErrorsEnabled", (bool)customErrors);
            }

            try
            {
                if (RemotingServices.GetServerTypeForUri((string)requestHeaders["__RequestUri"]) == null)
                {
                    throw new RemotingException("Remoting Channel Sink UriNotPublished");
                }

                requestMsg = DeserializeBinaryRequestMessage(requestStream, requestHeaders);

                if (requestMsg == null)
                {
                    throw new RemotingException("Remoting Deserialize Error");
                }
                sinkStack.Push(this, null);

                ServerProcessing processing = nextSink.ProcessMessage(sinkStack, requestMsg, requestHeaders, null, out responseMsg, out responseHeaders, out responseStream);

                if (responseStream != null)
                {
                    throw new RemotingException("Remoting_ChnlSink_WantNullResponseStream");
                }

                switch (processing)
                {
                case ServerProcessing.Complete:
                {
                    if (responseMsg == null)
                    {
                        throw new RemotingException("Remoting_DispatchMessage");
                    }
                    sinkStack.Pop(this);

                    SerializeResponse(sinkStack, responseMsg, ref responseHeaders, out responseStream);

                    return(processing);
                }

                case ServerProcessing.OneWay:
                {
                    sinkStack.Pop(this);
                    return(processing);
                }

                case ServerProcessing.Async:
                {
                    sinkStack.Store(this, null);
                    return(processing);
                }
                }

                return(processing);
            }
            catch (Exception ex)
            {
                responseMsg = new ReturnMessage(ex, requestMsg == null ? null : (IMethodCallMessage)requestMsg);

                CallContext.SetData("__ClientIsClr", 1);
                responseStream = new MemoryStream();
                CreateFormatter(true).Serialize(responseStream, responseMsg, null);
                CallContext.FreeNamedDataSlot("__ClientIsClr");
                responseStream.Position         = 0;
                responseHeaders                 = new TransportHeaders();
                responseHeaders["Content-Type"] = "application/octet-stream";
                return(ServerProcessing.Complete);
            }
            finally
            {
                CallContext.FreeNamedDataSlot("__CustomErrorsEnabled");
            }
        }
        public ServerProcessing ProcessMessage(IServerChannelSinkStack sinkStack, IMessage requestMsg, ITransportHeaders requestHeaders, Stream requestStream, out IMessage responseMsg, out ITransportHeaders responseHeaders, out Stream responseStream)
        {
            if (requestMsg != null)
            {
                // the message has already been deserialized so delegate to the next sink
                return(_nextSink.ProcessMessage(
                           sinkStack,
                           requestMsg, requestHeaders, requestStream,
                           out responseMsg, out responseHeaders, out responseStream));
            }

            // parameters validation
            if (sinkStack == null)
            {
                throw new ArgumentNullException("sinkStack");
            }
            if (requestHeaders == null)
            {
                throw new ArgumentNullException("requestHeaders");
            }
            if (requestStream == null)
            {
                throw new ArgumentNullException("requestStream");
            }

            // deserialize request
            IMethodCallMessage methodCall = _formatter.DeserializeRequest(requestHeaders, requestStream);

            requestStream.Close();

            // prepare stack for request processing
            sinkStack.Push(this, null);

            // process request
            ServerProcessing     processing;
            IMethodReturnMessage methodReturn = null;

            try
            {
                // call next sink to dispatch method call
                processing = _nextSink.ProcessMessage(
                    sinkStack,
                    methodCall, requestHeaders, null,
                    out responseMsg, out responseHeaders, out responseStream);

                if (processing == ServerProcessing.Complete)
                {
                    // response headers and stream must be null at this point!
                    if (responseHeaders != null)
                    {
                        throw new NotSupportedException();
                    }
                    if (responseStream != null)
                    {
                        throw new NotSupportedException();
                    }

                    // check response
                    methodReturn = responseMsg as IMethodReturnMessage;
                    if (methodReturn == null)
                    {
                        throw new NotSupportedException();
                    }
                }
            }
            catch (Exception ex)
            {
                processing   = ServerProcessing.Complete;
                methodReturn = new ReturnMessage(ex, methodCall);

                responseMsg     = methodReturn;
                responseHeaders = null;
                responseStream  = null;
            }

            // handle response
            switch (processing)
            {
            case ServerProcessing.Complete:
            {
                // call proceeded synchronously - serialize response
                sinkStack.Pop(this);
                SerializeResponse(sinkStack, methodReturn, out responseHeaders, out responseStream);
                break;
            }

            case ServerProcessing.OneWay:
            {
                // no response needed
                sinkStack.Pop(this);
                break;
            }

            case ServerProcessing.Async:
            {
                // call proceeded asynchronously
                sinkStack.Store(this, null);
                break;
            }

            default:
                throw new NotSupportedException();
            }

            return(processing);
        }
Example #18
0
        } // StrictBinding



        /// <include file='doc\BinaryFormatterSinks.uex' path='docs/doc[@for="BinaryServerFormatterSink.ProcessMessage"]/*' />
        public ServerProcessing ProcessMessage(IServerChannelSinkStack sinkStack,
            IMessage requestMsg,
            ITransportHeaders requestHeaders, Stream requestStream,
            out IMessage responseMsg, out ITransportHeaders responseHeaders, 
            out Stream responseStream)
        {
            if (requestMsg != null)
            {
                // The message has already been deserialized so delegate to the next sink.
                return _nextSink.ProcessMessage(
                    sinkStack,
                    requestMsg, requestHeaders, requestStream, 
                    out responseMsg, out responseHeaders, out responseStream);
            }
        
            if (requestHeaders ==  null)
                throw new ArgumentNullException("requestHeaders");

            BaseTransportHeaders wkRequestHeaders = requestHeaders as BaseTransportHeaders;
        
            ServerProcessing processing;
        
            responseHeaders = null;
            responseStream = null;

            String verb = null;
            String contentType = null;

            bool bCanServiceRequest = true;

            // determine the content type
            String contentTypeHeader = null;
            if (wkRequestHeaders != null)
                contentTypeHeader = wkRequestHeaders.ContentType;
            else
                contentTypeHeader = requestHeaders["Content-Type"] as String;
            if (contentTypeHeader != null)
            {
                String charsetValue;
                HttpChannelHelper.ParseContentType(contentTypeHeader,
                                                   out contentType, out charsetValue);
            }

            // check to see if Content-Type matches
            if ((contentType != null) &&
                (String.CompareOrdinal(contentType, CoreChannel.BinaryMimeType) != 0))
            {
                bCanServiceRequest = false;                
            }

            // check for http specific verbs
            if (_protocol == Protocol.Http)
            {
                verb = (String)requestHeaders["__RequestVerb"];    
                if (!verb.Equals("POST") && !verb.Equals("M-POST"))
                    bCanServiceRequest = false;
            }

            // either delegate or return an error message if we can't service the request
            if (!bCanServiceRequest)
            {
                // delegate to next sink if available
                if (_nextSink != null)
                {
                    return _nextSink.ProcessMessage(sinkStack, null, requestHeaders, requestStream,   
                        out responseMsg, out responseHeaders, out responseStream);
                }
                else
                {
                    // send back an error message
                    if (_protocol == Protocol.Http)
                    {
                        // return a client bad request error     
                        responseHeaders = new TransportHeaders();
                        responseHeaders["__HttpStatusCode"] = "400";
                        responseHeaders["__HttpReasonPhrase"] = "Bad Request";
                        responseStream = null;
                        responseMsg = null;
                        return ServerProcessing.Complete;
                    }
                    else
                    {
                        // The transport sink will catch this and do something here.
                        throw new RemotingException(
                            CoreChannel.GetResourceString("Remoting_Channels_InvalidRequestFormat"));
                    }
                }
            }
            

            try
            {
                String objectUri = null;
                if (wkRequestHeaders != null)
                    objectUri = wkRequestHeaders.RequestUri;
                else
                    objectUri = (String)requestHeaders[CommonTransportKeys.RequestUri];              
            
                if (RemotingServices.GetServerTypeForUri(objectUri) == null)
                    throw new RemotingException(
                        CoreChannel.GetResourceString("Remoting_ChnlSink_UriNotPublished"));

                RemotingServices.LogRemotingStage(CoreChannel.SERVER_MSG_DESER);
                // Deserialize Request - Stream to IMessage
                requestMsg =
                    CoreChannel.DeserializeBinaryRequestMessage(objectUri, requestStream, _strictBinding);
                requestStream.Close();

                if(requestMsg == null)
                {
                    throw new RemotingException(CoreChannel.GetResourceString("Remoting_DeserializeMessage"));
                }
                

                // Dispatch Call
                sinkStack.Push(this, null);
                RemotingServices.LogRemotingStage(CoreChannel.SERVER_MSG_SINK_CHAIN);
                processing =                    
                    _nextSink.ProcessMessage(sinkStack, requestMsg, requestHeaders, null,
                        out responseMsg, out responseHeaders, out responseStream);
                // make sure that responseStream is null
                if (responseStream != null)
                {
                    throw new RemotingException(
                        CoreChannel.GetResourceString("Remoting_ChnlSink_WantNullResponseStream"));
                }
                
                switch (processing)
                {

                case ServerProcessing.Complete:
                {
                    if (responseMsg == null)
                        throw new RemotingException(CoreChannel.GetResourceString("Remoting_DispatchMessage"));

                    sinkStack.Pop(this);

                    RemotingServices.LogRemotingStage(CoreChannel.SERVER_RET_SER);
                    SerializeResponse(sinkStack, responseMsg, 
                                      ref responseHeaders, out responseStream);
                    break;
                } // case ServerProcessing.Complete

                case ServerProcessing.OneWay:
                {
                    sinkStack.Pop(this);
                    break;
                } // case ServerProcessing.OneWay:

                case ServerProcessing.Async:
                {
                    sinkStack.Store(this, null);
                    break;   
                } // case ServerProcessing.Async
                    
                } // switch (processing)                
            }
            catch(Exception e)
            {
                processing = ServerProcessing.Complete;
                responseMsg = new ReturnMessage(e, (IMethodCallMessage)(requestMsg==null?new ErrorMessage():requestMsg));
                responseStream = (MemoryStream)CoreChannel.SerializeBinaryMessage(responseMsg, _includeVersioning);
                responseStream.Position = 0;
                responseHeaders = new TransportHeaders();

                if (_protocol == Protocol.Http)
                {
                    responseHeaders["Content-Type"] = CoreChannel.BinaryMimeType;
                }
            }

            RemotingServices.LogRemotingStage(CoreChannel.SERVER_RET_SEND);
            return processing;
        } // ProcessMessage
        } // StrictBinding



        /// <include file='doc\BinaryFormatterSinks.uex' path='docs/doc[@for="BinaryServerFormatterSink.ProcessMessage"]/*' />
        public ServerProcessing ProcessMessage(IServerChannelSinkStack sinkStack,
                                               IMessage requestMsg,
                                               ITransportHeaders requestHeaders, Stream requestStream,
                                               out IMessage responseMsg, out ITransportHeaders responseHeaders,
                                               out Stream responseStream)
        {
            if (requestMsg != null)
            {
                // The message has already been deserialized so delegate to the next sink.
                return(_nextSink.ProcessMessage(
                           sinkStack,
                           requestMsg, requestHeaders, requestStream,
                           out responseMsg, out responseHeaders, out responseStream));
            }

            if (requestHeaders == null)
            {
                throw new ArgumentNullException("requestHeaders");
            }

            BaseTransportHeaders wkRequestHeaders = requestHeaders as BaseTransportHeaders;

            ServerProcessing processing;

            responseHeaders = null;
            responseStream  = null;

            String verb        = null;
            String contentType = null;

            bool bCanServiceRequest = true;

            // determine the content type
            String contentTypeHeader = null;

            if (wkRequestHeaders != null)
            {
                contentTypeHeader = wkRequestHeaders.ContentType;
            }
            else
            {
                contentTypeHeader = requestHeaders["Content-Type"] as String;
            }
            if (contentTypeHeader != null)
            {
                String charsetValue;
                HttpChannelHelper.ParseContentType(contentTypeHeader,
                                                   out contentType, out charsetValue);
            }

            // check to see if Content-Type matches
            if ((contentType != null) &&
                (String.CompareOrdinal(contentType, CoreChannel.BinaryMimeType) != 0))
            {
                bCanServiceRequest = false;
            }

            // check for http specific verbs
            if (_protocol == Protocol.Http)
            {
                verb = (String)requestHeaders["__RequestVerb"];
                if (!verb.Equals("POST") && !verb.Equals("M-POST"))
                {
                    bCanServiceRequest = false;
                }
            }

            // either delegate or return an error message if we can't service the request
            if (!bCanServiceRequest)
            {
                // delegate to next sink if available
                if (_nextSink != null)
                {
                    return(_nextSink.ProcessMessage(sinkStack, null, requestHeaders, requestStream,
                                                    out responseMsg, out responseHeaders, out responseStream));
                }
                else
                {
                    // send back an error message
                    if (_protocol == Protocol.Http)
                    {
                        // return a client bad request error
                        responseHeaders = new TransportHeaders();
                        responseHeaders["__HttpStatusCode"]   = "400";
                        responseHeaders["__HttpReasonPhrase"] = "Bad Request";
                        responseStream = null;
                        responseMsg    = null;
                        return(ServerProcessing.Complete);
                    }
                    else
                    {
                        // The transport sink will catch this and do something here.
                        throw new RemotingException(
                                  CoreChannel.GetResourceString("Remoting_Channels_InvalidRequestFormat"));
                    }
                }
            }


            try
            {
                String objectUri = null;
                if (wkRequestHeaders != null)
                {
                    objectUri = wkRequestHeaders.RequestUri;
                }
                else
                {
                    objectUri = (String)requestHeaders[CommonTransportKeys.RequestUri];
                }

                if (RemotingServices.GetServerTypeForUri(objectUri) == null)
                {
                    throw new RemotingException(
                              CoreChannel.GetResourceString("Remoting_ChnlSink_UriNotPublished"));
                }

                RemotingServices.LogRemotingStage(CoreChannel.SERVER_MSG_DESER);
                // Deserialize Request - Stream to IMessage
                requestMsg =
                    CoreChannel.DeserializeBinaryRequestMessage(objectUri, requestStream, _strictBinding);
                requestStream.Close();

                if (requestMsg == null)
                {
                    throw new RemotingException(CoreChannel.GetResourceString("Remoting_DeserializeMessage"));
                }


                // Dispatch Call
                sinkStack.Push(this, null);
                RemotingServices.LogRemotingStage(CoreChannel.SERVER_MSG_SINK_CHAIN);
                processing =
                    _nextSink.ProcessMessage(sinkStack, requestMsg, requestHeaders, null,
                                             out responseMsg, out responseHeaders, out responseStream);
                // make sure that responseStream is null
                if (responseStream != null)
                {
                    throw new RemotingException(
                              CoreChannel.GetResourceString("Remoting_ChnlSink_WantNullResponseStream"));
                }

                switch (processing)
                {
                case ServerProcessing.Complete:
                {
                    if (responseMsg == null)
                    {
                        throw new RemotingException(CoreChannel.GetResourceString("Remoting_DispatchMessage"));
                    }

                    sinkStack.Pop(this);

                    RemotingServices.LogRemotingStage(CoreChannel.SERVER_RET_SER);
                    SerializeResponse(sinkStack, responseMsg,
                                      ref responseHeaders, out responseStream);
                    break;
                } // case ServerProcessing.Complete

                case ServerProcessing.OneWay:
                {
                    sinkStack.Pop(this);
                    break;
                } // case ServerProcessing.OneWay:

                case ServerProcessing.Async:
                {
                    sinkStack.Store(this, null);
                    break;
                } // case ServerProcessing.Async
                } // switch (processing)
            }
            catch (Exception e)
            {
                processing              = ServerProcessing.Complete;
                responseMsg             = new ReturnMessage(e, (IMethodCallMessage)(requestMsg == null?new ErrorMessage():requestMsg));
                responseStream          = (MemoryStream)CoreChannel.SerializeBinaryMessage(responseMsg, _includeVersioning);
                responseStream.Position = 0;
                responseHeaders         = new TransportHeaders();

                if (_protocol == Protocol.Http)
                {
                    responseHeaders["Content-Type"] = CoreChannel.BinaryMimeType;
                }
            }

            RemotingServices.LogRemotingStage(CoreChannel.SERVER_RET_SEND);
            return(processing);
        } // ProcessMessage
		public ServerProcessing ProcessMessage (IServerChannelSinkStack sinkStack,
							IMessage requestMsg, ITransportHeaders requestHeaders, Stream requestStream,
							out IMessage responseMsg, out ITransportHeaders responseHeaders, out Stream responseStream)
		{
			// Check whether the request was already processed by another
			// formatter sink and pass the request to the next sink if so.
			if (requestMsg != null)
				return next_sink.ProcessMessage (sinkStack,
								 requestMsg,
								 requestHeaders,
								 requestStream,
								 out responseMsg,
								 out responseHeaders,
								 out responseStream);

			// Check whether the request is suitable for this formatter
			// and pass the request to the next sink if not.
			// Note that a null content-type is handled as suitable,
			// otherwise no other sink will be able to handle the request.
			string contentType = requestHeaders["Content-Type"] as string;
			if (contentType != null && contentType != "application/octet-stream") {
				try {
					return next_sink.ProcessMessage (sinkStack,
						requestMsg,
						requestHeaders,
						requestStream,
						out responseMsg,
						out responseHeaders,
						out responseStream);
				} catch {
					// Let this formatter handle the exception.
				}
			}

			sinkStack.Push (this, null);
			ServerProcessing res;

			try
			{
				string url = (string)requestHeaders[CommonTransportKeys.RequestUri];
				string uri;
				receiver.Parse (url, out uri);
				if (uri == null) uri = url;

				MethodCallHeaderHandler mhh = new MethodCallHeaderHandler(uri);
				requestMsg = (IMessage) _binaryCore.Deserializer.Deserialize (requestStream, new HeaderHandler(mhh.HandleHeaders));

				res = next_sink.ProcessMessage (sinkStack, requestMsg, requestHeaders, null, out responseMsg, out responseHeaders, out responseStream);
			}
			catch (Exception ex)
			{
				responseMsg = new ReturnMessage (ex, (IMethodCallMessage)requestMsg);
				res = ServerProcessing.Complete;
				responseHeaders = null;
				responseStream = null;
			}
			
			if (res == ServerProcessing.Complete)
			{
				for (int n=0; n<3; n++) {
					responseStream = null;
					responseHeaders = new TransportHeaders();

					if (sinkStack != null) responseStream = sinkStack.GetResponseStream (responseMsg, responseHeaders);
					if (responseStream == null) responseStream = new MemoryStream();

					try {
						_binaryCore.Serializer.Serialize (responseStream, responseMsg);
						break;
					} catch (Exception ex) {
						if (n == 2) throw ex;
						else responseMsg = new ReturnMessage (ex, (IMethodCallMessage)requestMsg);
					}
				}
				
				if (responseStream is MemoryStream) responseStream.Position = 0;
				

				sinkStack.Pop (this);
			}
			return res;
		}
Example #21
0
        public ServerProcessing ProcessMessage(IServerChannelSinkStack sinkStack,
                                               IMessage requestMsg, ITransportHeaders requestHeaders, Stream requestStream,
                                               out IMessage responseMsg, out ITransportHeaders responseHeaders, out Stream responseStream)
        {
            // Check whether the request was already processed by another
            // formatter sink and pass the request to the next sink if so.
            if (requestMsg != null)
            {
                return(next_sink.ProcessMessage(sinkStack,
                                                requestMsg,
                                                requestHeaders,
                                                requestStream,
                                                out responseMsg,
                                                out responseHeaders,
                                                out responseStream));
            }

            // Check whether the request is suitable for this formatter
            // and pass the request to the next sink if not.
            // Note that a null content-type is handled as suitable,
            // otherwise no other sink will be able to handle the request.
            string contentType = requestHeaders["Content-Type"] as string;

            if (contentType != null && contentType != "application/octet-stream")
            {
                try {
                    return(next_sink.ProcessMessage(sinkStack,
                                                    requestMsg,
                                                    requestHeaders,
                                                    requestStream,
                                                    out responseMsg,
                                                    out responseHeaders,
                                                    out responseStream));
                } catch {
                    // Let this formatter handle the exception.
                }
            }

            sinkStack.Push(this, null);
            ServerProcessing res;

            try
            {
                string url = (string)requestHeaders[CommonTransportKeys.RequestUri];
                string uri;
                receiver.Parse(url, out uri);
                if (uri == null)
                {
                    uri = url;
                }

                MethodCallHeaderHandler mhh = new MethodCallHeaderHandler(uri);
                requestMsg = (IMessage)_binaryCore.Deserializer.Deserialize(requestStream, new HeaderHandler(mhh.HandleHeaders));

                res = next_sink.ProcessMessage(sinkStack, requestMsg, requestHeaders, null, out responseMsg, out responseHeaders, out responseStream);
            }
            catch (Exception ex)
            {
                responseMsg     = new ReturnMessage(ex, (IMethodCallMessage)requestMsg);
                res             = ServerProcessing.Complete;
                responseHeaders = null;
                responseStream  = null;
            }

            if (res == ServerProcessing.Complete)
            {
                for (int n = 0; n < 3; n++)
                {
                    responseStream  = null;
                    responseHeaders = new TransportHeaders();

                    if (sinkStack != null)
                    {
                        responseStream = sinkStack.GetResponseStream(responseMsg, responseHeaders);
                    }
                    if (responseStream == null)
                    {
                        responseStream = new MemoryStream();
                    }

                    try {
                        _binaryCore.Serializer.Serialize(responseStream, responseMsg);
                        break;
                    } catch (Exception ex) {
                        if (n == 2)
                        {
                            throw ex;
                        }
                        else
                        {
                            responseMsg = new ReturnMessage(ex, (IMethodCallMessage)requestMsg);
                        }
                    }
                }

                if (responseStream is MemoryStream)
                {
                    responseStream.Position = 0;
                }


                sinkStack.Pop(this);
            }
            return(res);
        }
Example #22
0
        /// <summary>
        /// Verarbeitet eine einzele Clientanfrage
        /// </summary>
        /// <param name="sinkStack">Aufrufstapel der Kanalsenken</param>
        /// <param name="requestMsg">Anfrage-nachricht</param>
        /// <param name="requestHeaders">Anfrage-Header</param>
        /// <param name="requestStream">Anfrage-Datenstrom</param>
        /// <param name="responseMsg">Antwort-Nachricht</param>
        /// <param name="responseHeaders">Antwort-Header</param>
        /// <param name="responseStream">Antwort-Datenstrom</param>
        /// <returns>Status serverseitigen Verarbeitung der Nachricht insgesamt</returns>
        public ServerProcessing ProcessMessage(IServerChannelSinkStack sinkStack, IMessage requestMsg, ITransportHeaders requestHeaders, Stream requestStream, out IMessage responseMsg, out ITransportHeaders responseHeaders, out Stream responseStream)
        {
            // Sicherheitstransaktionskennung aus Anfrage-Header lesen
            string strTransactID = (string)requestHeaders[CommonHeaderNames.SECURE_TRANSACTION_ID];

            // In Guid umwandeln
            Guid transactID = (strTransactID == null ? Guid.Empty : new Guid(strTransactID));

            // Aktuellen Transaktionsschritt aus Anfrage-Header lesen
            SecureTransactionStage transactionStage = (SecureTransactionStage)Convert.ToInt32((string)requestHeaders[CommonHeaderNames.SECURE_TRANSACTION_STATE]);

            // IP-Adresse des Clients aus Anfrage-Header lesen
            IPAddress clientAddress = requestHeaders[CommonTransportKeys.IPAddress] as IPAddress;

            // Aktuelle Kanalsenke auf den Senkenstapel legen, damit AsyncProcessResponse später ggf. asynchron aufgerufen werden kann
            sinkStack.Push(this, null);

            // Variable für Verarbeitungsstatus
            ServerProcessing processingResult;

            // Aktuellen Transaktionsschritt auswerten
            switch (transactionStage)
            {
            case SecureTransactionStage.SendingPublicKey:                     // Client sendet den öffentlichen Schlüssel an den Server

                // Gemeinsamen Schlüssel erzeugen und mit dem öffentlichen Schlüssel des Clients verschlüsseln
                processingResult = MakeSharedKey(transactID, requestHeaders, out responseMsg, out responseHeaders, out responseStream);

                break;

            case SecureTransactionStage.SendingEncryptedMessage:                     // Client sendet die verschlüsselte Anfragenachricht an den Server

                // Wenn die Sicherheitstransaktionskennung des Clients bekannt ist ...
                if (IsExistingSecurityTransaction(transactID))
                {
                    // Verschlüsselte Nachricht verarbeiten
                    processingResult = ProcessEncryptedMessage(transactID, sinkStack, requestMsg, requestHeaders, requestStream, out responseMsg, out responseHeaders, out responseStream);
                }
                else
                {
                    // Leere Nachricht an den Client senden und Transaktionsschritt auf "Unbekannte Sicherheitstransaktionskennung". setzen.
                    processingResult = SendEmptyToClient(SecureTransactionStage.UnknownTransactionID, out responseMsg, out responseHeaders, out responseStream);
                }

                break;

            case SecureTransactionStage.Uninitialized:                     // Uninizialisiert, noch nichts geschehen

                // Wenn für diesen Client Verschlüsselung nicht zwingend notwendig ist ...
                if (!RequireEncryption(clientAddress))
                {
                    // Nachricht gleich an die nächste Senke zur Weiterverarbeitung übergeben
                    processingResult = _next.ProcessMessage(sinkStack, requestMsg, requestHeaders, requestStream, out responseMsg, out responseHeaders, out responseStream);
                }
                else
                {
                    // Ausnahme werfen
                    throw new CryptoRemotingException(LanguageResource.CryptoRemotingException_ServerRequiresEncryption);
                }

                break;

            default:

                // Ausnahme werfen
                throw new CryptoRemotingException(string.Format(LanguageResource.CryptoRemotingException_InvalidClientRequest, transactionStage));
            }
            // Aktuelle Senke wieder vom Senkenstapel runternehmen
            sinkStack.Pop(this);

            // Veratbeitungsstatus zurückgeben
            return(processingResult);
        }
Example #23
0
        /// <summary>
        /// Requests message processing from the current sink.
        /// </summary>
        /// <param name="sinkStack">A stack of channel sinks that called the current sink.</param>
        /// <param name="requestMsg">The message that contains the request.</param>
        /// <param name="requestHeaders">Headers retrieved from the incoming message from the client.</param>
        /// <param name="requestStream">The stream that needs to be to processed and passed on to the deserialization sink.</param>
        /// <param name="responseMsg">When this method returns, contains a <see cref="T:System.Runtime.Remoting.Messaging.IMessage" /> that holds the response message. This parameter is passed uninitialized.</param>
        /// <param name="responseHeaders">When this method returns, contains a <see cref="T:System.Runtime.Remoting.Channels.ITransportHeaders" /> that holds the headers that are to be added to return message heading to the client. This parameter is passed uninitialized.</param>
        /// <param name="responseStream">When this method returns, contains a <see cref="T:System.IO.Stream" /> that is heading back to the transport sink. This parameter is passed uninitialized.</param>
        public ServerProcessing ProcessMessage(IServerChannelSinkStack sinkStack, IMessage requestMsg, ITransportHeaders requestHeaders, Stream requestStream, out IMessage responseMsg, out ITransportHeaders responseHeaders, out Stream responseStream)
        {
            // Read secure transaction identifier from request headers
            string strTransactID = (string)requestHeaders[CommonHeaderNames.SECURE_TRANSACTION_ID];
            Guid transactID = (strTransactID == null ? Guid.Empty : new Guid(strTransactID));

            // Read current transaction step and client IP address from request headers
            SecureTransactionStage transactionStage = (SecureTransactionStage)Convert.ToInt32((string)requestHeaders[CommonHeaderNames.SECURE_TRANSACTION_STATE]);
            IPAddress clientAddress = requestHeaders[CommonTransportKeys.IPAddress] as IPAddress;

            // Put current channel sink to the sink stack so AsyncProcessResponse can be called asynchronously if necessary order
            sinkStack.Push(this, null);
            ServerProcessing processingResult;

            try
            {
                switch (transactionStage)
                {
                    case SecureTransactionStage.SendingPublicKey: // Client sends the public key to the server

                        // Generate shared key and encrypt with the public key of the client
                        processingResult = MakeSharedKey(transactID, requestHeaders, out responseMsg, out responseHeaders, out responseStream);

                        break;

                    case SecureTransactionStage.SendingEncryptedMessage: // Client sends the encrypted request message to the server

                        if (IsExistingSecurityTransaction(transactID))
                            processingResult = ProcessEncryptedMessage(transactID, sinkStack, requestMsg, requestHeaders, requestStream, out responseMsg, out responseHeaders, out responseStream);
                        else
                            throw new CryptoRemotingException(string.Format(LanguageResource.CryptoRemotingException_InvalidClientRequest, SecureTransactionStage.UnknownTransactionID));

                        break;

                    case SecureTransactionStage.Uninitialized: // Uninitialized, nothing has happened

                        // Check if encryption is not required for this client address
                        if (!RequireEncryption(clientAddress))
                            processingResult = _next.ProcessMessage(sinkStack, requestMsg, requestHeaders, requestStream, out responseMsg, out responseHeaders, out responseStream);
                        else
                            throw new CryptoRemotingException(LanguageResource.CryptoRemotingException_ServerRequiresEncryption);

                        break;

                    default:

                        throw new CryptoRemotingException(string.Format(LanguageResource.CryptoRemotingException_InvalidClientRequest, transactionStage));
                }
            }
            catch (CryptoRemotingException)
            {
                processingResult = SendEmptyToClient(sinkStack, requestMsg, requestHeaders, requestStream,
                    transactionStage, out responseMsg, out responseHeaders, out responseStream);
                requestMsg = null;
            }

            // Pop the current sink from the sink stack
            sinkStack.Pop(this);
            return processingResult;
        }
        public ServerProcessing ProcessMessage(IServerChannelSinkStack sinkStack, IMessage requestMsg, ITransportHeaders requestHeaders, Stream requestStream, out IMessage responseMsg, out ITransportHeaders responseHeaders, out Stream responseStream)
        {
            ServerProcessing serverProcessing;
            string           str;

            sinkStack.Push(this, null);
            try
            {
                string item = (string)requestHeaders["__RequestUri"];
                this.receiver.Parse(item, out str);
                if (str == null)
                {
                    str = item;
                }
                MethodCallHeaderHandler methodCallHeaderHandler = new MethodCallHeaderHandler(str);
                requestMsg       = (IMessage)this._binaryCore.Deserializer.Deserialize(requestStream, new HeaderHandler(methodCallHeaderHandler.HandleHeaders));
                serverProcessing = this.next_sink.ProcessMessage(sinkStack, requestMsg, requestHeaders, null, out responseMsg, out responseHeaders, out responseStream);
            }
            catch (Exception exception)
            {
                responseMsg      = new ReturnMessage(exception, (IMethodCallMessage)requestMsg);
                serverProcessing = ServerProcessing.Complete;
                responseHeaders  = null;
                responseStream   = null;
            }
            if (serverProcessing == ServerProcessing.Complete)
            {
                for (int i = 0; i < 3; i++)
                {
                    responseStream  = null;
                    responseHeaders = new TransportHeaders();
                    if (sinkStack != null)
                    {
                        responseStream = sinkStack.GetResponseStream(responseMsg, responseHeaders);
                    }
                    if (responseStream == null)
                    {
                        responseStream = new MemoryStream();
                    }
                    try
                    {
                        this._binaryCore.Serializer.Serialize(responseStream, responseMsg);
                        break;
                    }
                    catch (Exception exception2)
                    {
                        Exception exception1 = exception2;
                        if (i == 2)
                        {
                            throw exception1;
                        }
                        responseMsg = new ReturnMessage(exception1, (IMethodCallMessage)requestMsg);
                    }
                }
                if (responseStream is MemoryStream)
                {
                    responseStream.Position = (long)0;
                }
                sinkStack.Pop(this);
            }
            return(serverProcessing);
        }
        public ServerProcessing ProcessMessage(IServerChannelSinkStack sinkStack, IMessage requestMsg, ITransportHeaders requestHeaders, Stream requestStream, out IMessage responseMsg, out ITransportHeaders responseHeaders, out Stream responseStream)
        {
            ServerProcessing complete;
            if (requestMsg != null)
            {
                return this._nextSink.ProcessMessage(sinkStack, requestMsg, requestHeaders, requestStream, out responseMsg, out responseHeaders, out responseStream);
            }
            if (requestHeaders == null)
            {
                throw new ArgumentNullException("requestHeaders");
            }
            BaseTransportHeaders headers = requestHeaders as BaseTransportHeaders;
            responseHeaders = null;
            responseStream = null;
            string str = null;
            string str2 = null;
            bool flag = true;
            string contentType = null;
            if (headers != null)
            {
                contentType = headers.ContentType;
            }
            else
            {
                contentType = requestHeaders["Content-Type"] as string;
            }
            if (contentType != null)
            {
                string str4;
                HttpChannelHelper.ParseContentType(contentType, out str2, out str4);
            }
            if ((str2 != null) && (string.Compare(str2, "text/xml", StringComparison.Ordinal) != 0))
            {
                flag = false;
            }
            if (this._protocol == Protocol.Http)
            {
                str = (string) requestHeaders["__RequestVerb"];
                if (!str.Equals("POST") && !str.Equals("M-POST"))
                {
                    flag = false;
                }
            }
            if (!flag)
            {
                if (this._nextSink != null)
                {
                    return this._nextSink.ProcessMessage(sinkStack, null, requestHeaders, requestStream, out responseMsg, out responseHeaders, out responseStream);
                }
                if (this._protocol != Protocol.Http)
                {
                    throw new RemotingException(CoreChannel.GetResourceString("Remoting_Channels_InvalidRequestFormat"));
                }
                responseHeaders = new TransportHeaders();
                responseHeaders["__HttpStatusCode"] = "400";
                responseHeaders["__HttpReasonPhrase"] = "Bad Request";
                responseStream = null;
                responseMsg = null;
                return ServerProcessing.Complete;
            }
            bool bClientIsClr = true;
            try
            {
                string str7;
                string uRI = null;
                if (headers != null)
                {
                    uRI = headers.RequestUri;
                }
                else
                {
                    uRI = (string) requestHeaders["__RequestUri"];
                }
                if (RemotingServices.GetServerTypeForUri(uRI) == null)
                {
                    throw new RemotingException(CoreChannel.GetResourceString("Remoting_ChnlSink_UriNotPublished"));
                }
                if (this._protocol == Protocol.Http)
                {
                    string str6 = (string) requestHeaders["User-Agent"];
                    if (str6 != null)
                    {
                        if (str6.IndexOf("MS .NET Remoting") == -1)
                        {
                            bClientIsClr = false;
                        }
                    }
                    else
                    {
                        bClientIsClr = false;
                    }
                }
                bool data = true;
                object obj2 = requestHeaders["__CustomErrorsEnabled"];
                if ((obj2 != null) && (obj2 is bool))
                {
                    data = (bool) obj2;
                }
                CallContext.SetData("__CustomErrorsEnabled", data);
                Header[] channelHeaders = this.GetChannelHeaders(requestHeaders, out str7);
                PermissionSet set = null;
                if (this.TypeFilterLevel != System.Runtime.Serialization.Formatters.TypeFilterLevel.Full)
                {
                    set = new PermissionSet(PermissionState.None);
                    set.SetPermission(new SecurityPermission(SecurityPermissionFlag.SerializationFormatter));
                }
                try
                {
                    if (set != null)
                    {
                        set.PermitOnly();
                    }
                    requestMsg = CoreChannel.DeserializeSoapRequestMessage(requestStream, channelHeaders, this._strictBinding, this.TypeFilterLevel);
                }
                finally
                {
                    if (set != null)
                    {
                        CodeAccessPermission.RevertPermitOnly();
                    }
                }
                requestStream.Close();
                if (requestMsg == null)
                {
                    throw new RemotingException(CoreChannel.GetResourceString("Remoting_DeserializeMessage"));
                }
                if ((str7 != null) && !SoapServices.IsSoapActionValidForMethodBase(str7, ((IMethodMessage) requestMsg).MethodBase))
                {
                    throw new RemotingException(string.Format(CultureInfo.CurrentCulture, CoreChannel.GetResourceString("Remoting_Soap_InvalidSoapAction"), new object[] { str7 }));
                }
                sinkStack.Push(this, null);
                complete = this._nextSink.ProcessMessage(sinkStack, requestMsg, requestHeaders, null, out responseMsg, out responseHeaders, out responseStream);
                if (responseStream != null)
                {
                    throw new RemotingException(CoreChannel.GetResourceString("Remoting_ChnlSink_WantNullResponseStream"));
                }
                switch (complete)
                {
                    case ServerProcessing.Complete:
                        if (responseMsg == null)
                        {
                            throw new RemotingException(CoreChannel.GetResourceString("Remoting_DispatchMessage"));
                        }
                        break;

                    case ServerProcessing.OneWay:
                        sinkStack.Pop(this);
                        return complete;

                    case ServerProcessing.Async:
                        sinkStack.Store(this, null);
                        return complete;

                    default:
                        return complete;
                }
                sinkStack.Pop(this);
                this.SerializeResponse(sinkStack, responseMsg, bClientIsClr, ref responseHeaders, out responseStream);
                return complete;
            }
            catch (Exception exception)
            {
                complete = ServerProcessing.Complete;
                responseMsg = new ReturnMessage(exception, (requestMsg == null) ? ((IMethodCallMessage) new System.Runtime.Remoting.Channels.Http.ErrorMessage()) : ((IMethodCallMessage) requestMsg));
                CallContext.SetData("__ClientIsClr", bClientIsClr);
                responseStream = (MemoryStream) CoreChannel.SerializeSoapMessage(responseMsg, this._includeVersioning);
                CallContext.FreeNamedDataSlot("__ClientIsClr");
                responseStream.Position = 0L;
                responseHeaders = new TransportHeaders();
                if (this._protocol == Protocol.Http)
                {
                    responseHeaders["__HttpStatusCode"] = "500";
                    responseHeaders["__HttpReasonPhrase"] = "Internal Server Error";
                    responseHeaders["Content-Type"] = "text/xml; charset=\"utf-8\"";
                }
            }
            finally
            {
                CallContext.FreeNamedDataSlot("__CustomErrorsEnabled");
            }
            return complete;
        }
        /// <summary>
        /// process a giop request message.
        /// </summary>
        private ServerProcessing ProcessRequestMessage(IServerChannelSinkStack sinkStack,
                                                       ITransportHeaders requestHeaders,
                                                       CdrMessageInputStream msgInput,
                                                       GiopServerConnection serverCon,
                                                       out IMessage responseMsg, out ITransportHeaders responseHeaders,
                                                       out Stream responseStream) {
            IMessage deserReqMsg = null;
            responseHeaders = null;
            try {
                try {
                    // deserialise the request
                    deserReqMsg = m_messageHandler.ParseIncomingRequestMessage(msgInput,
                                                       serverCon.ConDesc);
                } finally {
                    //request deserialised -> safe to read next request while processing request in servant
                    // (or sending request deserialisation exception)
                    try {
                        serverCon.NotifyDeserialiseRequestComplete();
                    } catch (Exception ne) {
                        // unexpected exception. Abort message processing, problem with transport.
                        throw new NotifyReadRequestException("Problem while trying to inform transport about request deserialistion.",
                                                             ne);
                    }
                }

                // processing may be done asynchronous, therefore push this sink on the stack to process a response async
                AsyncServerProcessingData asyncData =
                    new AsyncServerProcessingData(deserReqMsg, serverCon);
                sinkStack.Push(this, asyncData);
                ServerProcessing processingResult;
                try {
                    // forward the call to the next message handling sink
                    processingResult = m_nextSink.ProcessMessage(sinkStack, deserReqMsg,
                                                                 requestHeaders, null, out responseMsg,
                                                                 out responseHeaders, out responseStream);
                } catch (Exception) {
                    sinkStack.Pop(this);
                    throw;
                }
                switch (processingResult) {
                    case ServerProcessing.Complete:
                        sinkStack.Pop(this); // not async
                        // send the response
                        SerialiseResponse(sinkStack, deserReqMsg, serverCon, responseMsg,
                                          ref responseHeaders, out responseStream);
                        break;
                    case ServerProcessing.Async:
                        sinkStack.Store(this, asyncData); // this sink want's to process async response
                        break;
                    case ServerProcessing.OneWay:
                        // nothing to do, because no response expected
                        sinkStack.Pop(this);
                        break;
                }
                return processingResult;

            } catch (MessageHandling.RequestDeserializationException deserEx) {
                // exception from DeserialisRequest
                responseMsg = deserEx.ResponseMessage;
                // an exception was thrown during deserialization
                SerialiseExceptionResponse(sinkStack,
                                           deserEx.RequestMessage, serverCon, responseMsg,
                                           ref responseHeaders, out responseStream);
                return ServerProcessing.Complete;
            } catch (NotifyReadRequestException nrre) {
                Trace.WriteLine("Failed to inform transport about request deserialisation. Processing problem on server connection after unexpected exception: " + nrre.InnerException);
                throw nrre;
            } catch (Exception e) {
                // serialise an exception response
                if (deserReqMsg != null) {
                    if (deserReqMsg is IMethodCallMessage) {
                        responseMsg = new ReturnMessage(e, (IMethodCallMessage) deserReqMsg);
                    } else {
                        responseMsg = new ReturnMessage(e, null); // no usable information present
                    }
                    SerialiseExceptionResponse(sinkStack,
                                               deserReqMsg, serverCon, responseMsg,
                                               ref responseHeaders, out responseStream);
                } else {
                    throw e;
                }
                return ServerProcessing.Complete; // send back an error msg
            }
        }
		public ServerProcessing ProcessMessage (IServerChannelSinkStack sinkStack,
							IMessage requestMsg, ITransportHeaders requestHeaders, Stream requestStream,
							out IMessage responseMsg, out ITransportHeaders responseHeaders, out Stream responseStream)
		{
			sinkStack.Push (this, null);
			ServerProcessing res;

			try
			{
				string url = (string)requestHeaders["__RequestUri"];
				string uri;
				receiver.Parse (url, out uri);
				if (uri == null) uri = url;

				MethodCallHeaderHandler mhh = new MethodCallHeaderHandler(uri);
				requestMsg = (IMessage) _binaryCore.Deserializer.Deserialize (requestStream, new HeaderHandler(mhh.HandleHeaders));

				res = next_sink.ProcessMessage (sinkStack, requestMsg, requestHeaders, null, out responseMsg, out responseHeaders, out responseStream);
			}
			catch (Exception ex)
			{
				responseMsg = new ReturnMessage (ex, (IMethodCallMessage)requestMsg);
				res = ServerProcessing.Complete;
				responseHeaders = null;
				responseStream = null;
			}
			
			if (res == ServerProcessing.Complete)
			{
				for (int n=0; n<3; n++) {
					responseStream = null;
					responseHeaders = new TransportHeaders();

					if (sinkStack != null) responseStream = sinkStack.GetResponseStream (responseMsg, responseHeaders);
					if (responseStream == null) responseStream = new MemoryStream();

					try {
						_binaryCore.Serializer.Serialize (responseStream, responseMsg);
						break;
					} catch (Exception ex) {
						if (n == 2) throw ex;
						else responseMsg = new ReturnMessage (ex, (IMethodCallMessage)requestMsg);
					}
				}
				
				if (responseStream is MemoryStream) responseStream.Position = 0;
				

				sinkStack.Pop (this);
			}
			return res;
		}
        /// <summary>
        /// Requests message processing from the current sink.
        /// </summary>
        /// <param name="sinkStack">A stack of channel sinks that called the current sink.</param>
        /// <param name="requestMsg">The message that contains the request.</param>
        /// <param name="requestHeaders">Headers retrieved from the incoming message from the client.</param>
        /// <param name="requestStream">The stream that needs to be to processed and passed on to the deserialization sink.</param>
        /// <param name="responseMsg">When this method returns, contains a <see cref="T:System.Runtime.Remoting.Messaging.IMessage"/> that holds the response message. This parameter is passed uninitialized.</param>
        /// <param name="responseHeaders">When this method returns, contains a <see cref="T:System.Runtime.Remoting.Channels.ITransportHeaders"/> that holds the headers that are to be added to return message heading to the client. This parameter is passed uninitialized.</param>
        /// <param name="responseStream">When this method returns, contains a <see cref="T:System.IO.Stream"/> that is heading back to the transport sink. This parameter is passed uninitialized.</param>
        /// <returns>
        /// A <see cref="T:System.Runtime.Remoting.Channels.ServerProcessing"/> status value that provides information about how message was processed.
        /// </returns>
        /// <exception cref="T:System.Security.SecurityException">The immediate caller does not have infrastructure permission. </exception>
        public ServerProcessing ProcessMessage(IServerChannelSinkStack sinkStack, IMessage requestMsg, ITransportHeaders requestHeaders, Stream requestStream, out IMessage responseMsg, out ITransportHeaders responseHeaders, out Stream responseStream)
        {
            // Push this onto the sink stack
            sinkStack.Push(this, null);

            // If the request has the compression flag, decompress the stream.
            if (requestHeaders[CommonHeaders.CompressionEnabled] != null)
            {
                // Determine compression method
                var method = CompressionMethod.Default;
                if (requestHeaders[CommonHeaders.CompressionMethod] != null)
                {
                    method = (CompressionMethod)Convert.ToInt32(requestHeaders[CommonHeaders.CompressionMethod]);
                }

                // Process the message and decompress it.
                requestStream = CompressionHelper.Decompress(requestStream, method);
            }

            // Retrieve the response from the server.
            var processingResult = _next.ProcessMessage(sinkStack, requestMsg, requestHeaders, requestStream,
                out responseMsg, out responseHeaders, out responseStream);

            // If the response stream length is greater than the threshold,
            // message is not exempt from compression, and client supports compression,
            // compress the stream.
            if (processingResult == ServerProcessing.Complete
                && _compressionThreshold > 0
                && responseStream.Length > _compressionThreshold
                && !IsCompressionExempt(responseMsg)
                && requestHeaders[CommonHeaders.CompressionSupported] != null)
            {
                // Process the message and compress it.
                responseStream = CompressionHelper.Compress(responseStream, _compressionMethod);

                // Send the compression flag to the client.
                responseHeaders[CommonHeaders.CompressionEnabled] = "true";
                responseHeaders[CommonHeaders.CompressionMethod] = ((int)_compressionMethod).ToString();
            }

            // Take off the stack and return the result.
            sinkStack.Pop(this);
            return processingResult;
        }
Example #29
0
		public ServerProcessing ProcessMessage (IServerChannelSinkStack sinkStack,
							IMessage requestMsg, ITransportHeaders requestHeaders, Stream requestStream,
							out IMessage responseMsg, out ITransportHeaders responseHeaders, out Stream responseStream)
		{
			// Check whether the request was already processed by another
			// formatter sink and pass the request to the next sink if so.
			if (requestMsg != null)
				return next_sink.ProcessMessage (sinkStack,
								 requestMsg,
								 requestHeaders,
								 requestStream,
								 out responseMsg,
								 out responseHeaders,
								 out responseStream);

			// Check whether the request is suitable for this formatter
			// and pass the request to the next sink if not.
			// Note that a null content-type is handled as suitable,
			// otherwise no other sink will be able to handle the request.
			string contentType = requestHeaders["Content-Type"] as string;
			if (contentType == null || !contentType.StartsWith ("text/xml") || requestHeaders["SOAPAction"] == null) {
				return next_sink.ProcessMessage (sinkStack,
					requestMsg,
					requestHeaders,
					requestStream,
					out responseMsg,
					out responseHeaders,
					out responseStream);
			}

			responseMsg = null;
			responseHeaders = null;
			responseStream = null;

			ServerProcessing sp;
			SoapMessageFormatter soapMsgFormatter = new SoapMessageFormatter();
			sinkStack.Push(this, soapMsgFormatter);

			try {
				string url = (string)requestHeaders[CommonTransportKeys.RequestUri];
				string uri;
				_receiver.Parse(url, out uri);
				if(uri == null)	uri = url;
				Type serverType = RemotingServices.GetServerTypeForUri(uri);
				if (serverType == null) throw new RemotingException ("No receiver for uri " + uri);
			
				SoapFormatter fm = _soapCore.GetSafeDeserializer ();
				SoapMessage soapMessage = soapMsgFormatter.CreateSoapMessage (true);
				fm.TopObject = soapMessage;
				fm.Deserialize(requestStream);

				requestMsg = soapMsgFormatter.BuildMethodCallFromSoapMessage(soapMessage, uri);
				
				sp = next_sink.ProcessMessage(sinkStack, requestMsg, requestHeaders, null, out responseMsg, out responseHeaders, out responseStream);
				
				if(sp == ServerProcessing.Complete) {
					if(responseMsg != null && responseStream == null) {

						object rtnMessageObject = soapMsgFormatter.BuildSoapMessageFromMethodResponse((IMethodReturnMessage) responseMsg, out responseHeaders);
						responseStream = new MemoryStream();
						_soapCore.Serializer.Serialize(responseStream, rtnMessageObject);
						responseStream.Position = 0;
					}
				}
			}
			catch(Exception e)
			{
				responseMsg = (IMethodReturnMessage)new ReturnMessage(e, (IMethodCallMessage)requestMsg);
				object rtnMessageObject = soapMsgFormatter.BuildSoapMessageFromMethodResponse((IMethodReturnMessage) responseMsg, out responseHeaders);
				responseStream = new MemoryStream();
				_soapCore.Serializer.Serialize(responseStream, rtnMessageObject);
				responseStream.Position = 0;
				sp = ServerProcessing.Complete;
			}

			if (sp == ServerProcessing.Complete)
				sinkStack.Pop(this);

			return sp;
			
		}
		public ServerProcessing ProcessMessage (IServerChannelSinkStack sinkStack,
							IMessage requestMsg, ITransportHeaders requestHeaders, Stream requestStream,
							out IMessage responseMsg, out ITransportHeaders responseHeaders, out Stream responseStream)
		{
			responseMsg = null;
			responseHeaders = null;
			responseStream = null;

			ServerProcessing sp;
			SoapMessageFormatter soapMsgFormatter = new SoapMessageFormatter();
			sinkStack.Push(this, soapMsgFormatter);

			try {
				string url = (string)requestHeaders[CommonTransportKeys.RequestUri];
				string uri;
				_receiver.Parse(url, out uri);
				if(uri == null)	uri = url;
				Type serverType = RemotingServices.GetServerTypeForUri(uri);
				if (serverType == null) throw new RemotingException ("No receiver for uri " + uri);
			
				SoapFormatter fm = _soapCore.GetSafeDeserializer ();
				SoapMessage soapMessage = soapMsgFormatter.CreateSoapMessage (true);
				fm.TopObject = soapMessage;
				requestStream.Position = 0;
				fm.Deserialize(requestStream);

				requestMsg = soapMsgFormatter.BuildMethodCallFromSoapMessage(soapMessage, uri);
				
				sp = next_sink.ProcessMessage(sinkStack, requestMsg, requestHeaders, null, out responseMsg, out responseHeaders, out responseStream);
				
				if(sp == ServerProcessing.Complete) {
					if(responseMsg != null && responseStream == null) {

						object rtnMessageObject = soapMsgFormatter.BuildSoapMessageFromMethodResponse((IMethodReturnMessage) responseMsg, out responseHeaders);
						responseStream = new MemoryStream();
						_soapCore.Serializer.Serialize(responseStream, rtnMessageObject);
					}
				}
			}
			catch(Exception e)
			{
				responseMsg = (IMethodReturnMessage)new ReturnMessage(e, (IMethodCallMessage)requestMsg);
				object rtnMessageObject = soapMsgFormatter.BuildSoapMessageFromMethodResponse((IMethodReturnMessage) responseMsg, out responseHeaders);
				responseStream = new MemoryStream();
				_soapCore.Serializer.Serialize(responseStream, rtnMessageObject);
				sp = ServerProcessing.Complete;
			}

			if (sp == ServerProcessing.Complete)
				sinkStack.Pop(this);

			return sp;
			
		}
        public ServerProcessing ProcessMessage(IServerChannelSinkStack sinkStack,
                                               IMessage requestMsg, ITransportHeaders requestHeaders, Stream requestStream,
                                               out IMessage responseMsg, out ITransportHeaders responseHeaders, out Stream responseStream)
        {
            // Check whether the request was already processed by another
            // formatter sink and pass the request to the next sink if so.
            if (requestMsg != null)
            {
                return(next_sink.ProcessMessage(sinkStack,
                                                requestMsg,
                                                requestHeaders,
                                                requestStream,
                                                out responseMsg,
                                                out responseHeaders,
                                                out responseStream));
            }

            // Check whether the request is suitable for this formatter
            // and pass the request to the next sink if not.
            // Note that a null content-type is handled as suitable,
            // otherwise no other sink will be able to handle the request.
            string contentType = requestHeaders["Content-Type"] as string;

            if (contentType == null || !contentType.StartsWith("text/xml") || requestHeaders["SOAPAction"] == null)
            {
                return(next_sink.ProcessMessage(sinkStack,
                                                requestMsg,
                                                requestHeaders,
                                                requestStream,
                                                out responseMsg,
                                                out responseHeaders,
                                                out responseStream));
            }

            responseMsg     = null;
            responseHeaders = null;
            responseStream  = null;

            ServerProcessing     sp;
            SoapMessageFormatter soapMsgFormatter = new SoapMessageFormatter();

            sinkStack.Push(this, soapMsgFormatter);

            try {
                string url = (string)requestHeaders[CommonTransportKeys.RequestUri];
                string uri;
                _receiver.Parse(url, out uri);
                if (uri == null)
                {
                    uri = url;
                }
                Type serverType = RemotingServices.GetServerTypeForUri(uri);
                if (serverType == null)
                {
                    throw new RemotingException("No receiver for uri " + uri);
                }

                SoapFormatter fm          = _soapCore.GetSafeDeserializer();
                SoapMessage   soapMessage = soapMsgFormatter.CreateSoapMessage(true);
                fm.TopObject = soapMessage;
                fm.Deserialize(requestStream);

                requestMsg = soapMsgFormatter.BuildMethodCallFromSoapMessage(soapMessage, uri);

                sp = next_sink.ProcessMessage(sinkStack, requestMsg, requestHeaders, null, out responseMsg, out responseHeaders, out responseStream);

                if (sp == ServerProcessing.Complete)
                {
                    if (responseMsg != null && responseStream == null)
                    {
                        object rtnMessageObject = soapMsgFormatter.BuildSoapMessageFromMethodResponse((IMethodReturnMessage)responseMsg, out responseHeaders);
                        responseStream = new MemoryStream();
                        _soapCore.Serializer.Serialize(responseStream, rtnMessageObject);
                        responseStream.Position = 0;
                    }
                }
            }
            catch (Exception e)
            {
                responseMsg = (IMethodReturnMessage) new ReturnMessage(e, (IMethodCallMessage)requestMsg);
                object rtnMessageObject = soapMsgFormatter.BuildSoapMessageFromMethodResponse((IMethodReturnMessage)responseMsg, out responseHeaders);
                responseStream = new MemoryStream();
                _soapCore.Serializer.Serialize(responseStream, rtnMessageObject);
                responseStream.Position = 0;
                sp = ServerProcessing.Complete;
            }

            if (sp == ServerProcessing.Complete)
            {
                sinkStack.Pop(this);
            }

            return(sp);
        }
        /// <summary>Requests message processing from the current sink.</summary>
        /// <param name="sinkStack">A stack of channel sinks</param>
        /// <param name="requestMsg">Request message.</param>
        /// <param name="requestHeaders">Headers sent by client.</param>
        /// <param name="requestStream">Stream to be processed..</param>
        /// <param name="responseMsg">Response message.</param>
        /// <param name="responseHeaders">Response headers.</param>
        /// <param name="responseStream">Response stream.</param>
        /// <returns>Status of the server message processing.</returns>
        public ServerProcessing ProcessMessage(
			IServerChannelSinkStack sinkStack, IMessage requestMsg, ITransportHeaders requestHeaders, Stream requestStream, 
			out IMessage responseMsg, out ITransportHeaders responseHeaders, out Stream responseStream)
        {
            // Get header information about transaction
            string strTransactID = (string)requestHeaders[CommonHeaders.ID];
            Guid transactID = (strTransactID == null ? Guid.Empty : new Guid(strTransactID));
            SecureTransaction transactType = (SecureTransaction)Convert.ToInt32((string)requestHeaders[CommonHeaders.Transaction]);

            // For reference, find out who is connecting to us.  We can use this to filter
            // and to enforce security based on client identity.
            IPAddress clientAddress = requestHeaders[CommonTransportKeys.IPAddress] as IPAddress;

            // Set the IP address and port of our client
            CallContext.SetData("ClientIP", clientAddress);

            // Push this onto the sink stack
            sinkStack.Push(this, null);

            // Process the transaction based on its type (as stored in the CommonHeaders.Transaction header field)
            ServerProcessing processingResult;
            switch(transactType)
            {
                case SecureTransaction.SendingPublicKey:
                    // We've received a request from a new client asking for a shared key (by sending us
                    // his RSA public key).  Create a shared key, encrypt it, and send it back to him.
                    processingResult = MakeSharedKey(transactID, requestHeaders, out responseMsg, out responseHeaders, out responseStream);
                    System.Diagnostics.Debug.WriteLine("Connection added: " + transactID);
                    break;

                case SecureTransaction.SendingEncryptedMessage:
                    // We've received an encrypted message.  Decrypt it and send it along to the next sink.
                    // But first make sure we have a record of the transaction.
                    if (PreviousTransactionWithClient(transactID))
                    {
                        processingResult = ProcessEncryptedMessage(
                            transactID, sinkStack,
                            requestMsg, requestHeaders, requestStream,
                            out responseMsg, out responseHeaders, out responseStream);
                    }
                        // Otherwise, let the client know that we don't recognize him.
                    else
                    {
                        processingResult = SendEmptyToClient(
                            SecureTransaction.UnknownIdentifier,
                            out responseMsg, out responseHeaders, out responseStream);
                        System.Diagnostics.Debug.WriteLine("Unknown connection: " + transactID);
                    }
                    break;

                case SecureTransaction.Uninitialized:
                    // The transaction type did not match any known type, or wasn't specified.
                    // So just pass on the message to the next sink.  This shouldn't happen
                    // unless the client isn't using the SecureClientSink provider, in which
                    // case this is the correct behavior.
                    if (!RequireSecurity(clientAddress))
                    {
                        processingResult = _next.ProcessMessage(
                            sinkStack, requestMsg, requestHeaders, requestStream,
                            out responseMsg, out responseHeaders, out responseStream);
                    }
                        // If the server has elected not to allow plaintext traffic, let the
                        // client know that we're not happy.
                    else throw new SecureRemotingException("Server requires a secure connection for this client");
                    break;

                default:
                    // Houston, we have a problem!
                    throw new SecureRemotingException("Invalid request from client: " + transactType + ".");
            }

            // Take us off the stack and return the result.
            sinkStack.Pop(this);
            return processingResult;
        }
Example #33
0
        public ServerProcessing ProcessMessage(IServerChannelSinkStack sinkStack,
            IMessage requestMsg,
            ITransportHeaders requestHeaders, Stream requestStream,
            out IMessage responseMsg, out ITransportHeaders responseHeaders, 
            out Stream responseStream)
        {
            if (requestMsg != null)
            {
                // The message has already been deserialized so delegate to the next sink.
                return _nextSink.ProcessMessage(
                    sinkStack,
                    requestMsg, requestHeaders, requestStream, 
                    out responseMsg, out responseHeaders, out responseStream);
            }
        
            if (requestHeaders ==  null)
                throw new ArgumentNullException("requestHeaders");
            BaseTransportHeaders wkRequestHeaders = requestHeaders as BaseTransportHeaders;
        
            ServerProcessing processing;        

            responseHeaders = null;
            responseStream = null;

            String verb = null;
            String contentType = null;

            bool bCanServiceRequest = true;

            // determine the content type
            String contentTypeHeader = null;
            if (wkRequestHeaders != null)
                contentTypeHeader = wkRequestHeaders.ContentType;
            else
                contentTypeHeader = requestHeaders["Content-Type"] as String;
            if (contentTypeHeader != null)
            {
            String charsetValue;
            HttpChannelHelper.ParseContentType(contentTypeHeader,
                                               out contentType, out charsetValue);
            }
            
            // check to see if Content-Type matches
            if ((contentType != null) &&
                (String.Compare(contentType, CoreChannel.SOAPMimeType, StringComparison.Ordinal) != 0))
            {
                bCanServiceRequest = false;                
            }

            // check for http specific verbs
            if (_protocol == Protocol.Http)
            {                
                verb = (String)requestHeaders["__RequestVerb"];
                if (!verb.Equals("POST") && !verb.Equals("M-POST"))
                    bCanServiceRequest = false;
            }

            // either delegate or return an error message if we can't service the request
            if (!bCanServiceRequest)
                {
                    // delegate to next sink if available
                    if (_nextSink != null)
                    {
                        return _nextSink.ProcessMessage(sinkStack, null, requestHeaders, requestStream,   
                            out responseMsg, out responseHeaders, out responseStream);
                    }
                    else
                    {
                    // send back an error message
                    if (_protocol == Protocol.Http)
                    {
                        // return a client bad request error     
                        responseHeaders = new TransportHeaders();
                        responseHeaders["__HttpStatusCode"] = "400";
                        responseHeaders["__HttpReasonPhrase"] = "Bad Request";
                        responseStream = null;
                        responseMsg = null;
                        return ServerProcessing.Complete;
                    }
                    else
                    {
                        // The transport sink will catch this and do something here.
                        throw new RemotingException(
                            CoreChannel.GetResourceString("Remoting_Channels_InvalidRequestFormat"));
                    }
                }
            }
            
            bool bClientIsClr = true;
            try            
            {
                String objectUri = null;
                if (wkRequestHeaders != null)
                    objectUri = wkRequestHeaders.RequestUri;
                else
                    objectUri = (String)requestHeaders[CommonTransportKeys.RequestUri];              
                
                if (RemotingServices.GetServerTypeForUri(objectUri) == null)
                    throw new RemotingException(
                        CoreChannel.GetResourceString("Remoting_ChnlSink_UriNotPublished"));

                if (_protocol == Protocol.Http)
                {
                    String userAgent = (String)requestHeaders["User-Agent"];
                    if (userAgent != null)
                    {                       
                        if (userAgent.IndexOf("MS .NET Remoting") == -1)
                        {
                            // user agent string did not contain ".NET Remoting", so it is someone else
                            bClientIsClr = false;
                        }
                    }
                    else
                    {
                        bClientIsClr = false;
                    }
                }

                bool bIsCustomErrorEnabled = true;
                object oIsCustomErrorEnabled = requestHeaders["__CustomErrorsEnabled"];
                if (oIsCustomErrorEnabled != null && oIsCustomErrorEnabled is bool){
                    bIsCustomErrorEnabled = (bool)oIsCustomErrorEnabled;
                }
                CallContext.SetData("__CustomErrorsEnabled", bIsCustomErrorEnabled);
                
                String soapActionToVerify;
                Header[] h = GetChannelHeaders(requestHeaders, out soapActionToVerify);

                PermissionSet currentPermissionSet = null;
                if (this.TypeFilterLevel != TypeFilterLevel.Full) {
                    currentPermissionSet = new PermissionSet(PermissionState.None);                
                    currentPermissionSet.SetPermission(new SecurityPermission(SecurityPermissionFlag.SerializationFormatter));                    
                }
                                    
                try {
                    if (currentPermissionSet != null) 
                        currentPermissionSet.PermitOnly();                                                                    

                    // Deserialize Request - Stream to IMessage                                        
                    requestMsg = CoreChannel.DeserializeSoapRequestMessage(requestStream, h, _strictBinding, this.TypeFilterLevel);
                }
                finally {
                    if (currentPermissionSet != null)
                        CodeAccessPermission.RevertPermitOnly();
                }
                
                requestStream.Close();

                if(requestMsg == null)
                {
                    throw new RemotingException(CoreChannel.GetResourceString("Remoting_DeserializeMessage"));
                }

                // verify soap action if necessary
                if ((soapActionToVerify != null) &&
                    (!SoapServices.IsSoapActionValidForMethodBase(
                        soapActionToVerify, ((IMethodMessage)requestMsg).MethodBase)))
                {
                    throw new RemotingException(
                        String.Format(
                            CultureInfo.CurrentCulture, CoreChannel.GetResourceString("Remoting_Soap_InvalidSoapAction"),
                            soapActionToVerify)
                        );
                }                
             
                // Dispatch Call
                sinkStack.Push(this, null);
                processing = 
                    _nextSink.ProcessMessage(sinkStack, requestMsg, requestHeaders, null,
                        out responseMsg, out responseHeaders, out responseStream);
                // make sure that responseStream is null
                if (responseStream != null)
                {
                    throw new RemotingException(
                        CoreChannel.GetResourceString("Remoting_ChnlSink_WantNullResponseStream"));
                }
                
                switch (processing)
                {

                case ServerProcessing.Complete:
                {
                    if (responseMsg == null)
                        throw new RemotingException(CoreChannel.GetResourceString("Remoting_DispatchMessage"));

                    sinkStack.Pop(this);

                    SerializeResponse(sinkStack, responseMsg, bClientIsClr,
                                      ref responseHeaders, out responseStream);
                    break;
                } // case ServerProcessing.Complete

                case ServerProcessing.OneWay:
                {
                    sinkStack.Pop(this);
                    break;
                } // case ServerProcessing.OneWay:

                case ServerProcessing.Async:
                {
                    sinkStack.Store(this, null);
                    break;   
                } // case ServerProcessing.Async
                    
                } // switch (processing)                
            }
            catch(Exception e)
            {
                processing = ServerProcessing.Complete;
                responseMsg = new ReturnMessage(e, (IMethodCallMessage)(requestMsg==null?new ErrorMessage():requestMsg));
                //
                CallContext.SetData("__ClientIsClr", bClientIsClr);
                responseStream = (MemoryStream)CoreChannel.SerializeSoapMessage(responseMsg, _includeVersioning);
                CallContext.FreeNamedDataSlot("__ClientIsClr");
                responseStream.Position = 0;
                responseHeaders = new TransportHeaders();

                if (_protocol == Protocol.Http)
                {
                    responseHeaders["__HttpStatusCode"] = "500";
                    responseHeaders["__HttpReasonPhrase"] = "Internal Server Error";
                    responseHeaders["Content-Type"] = CoreChannel.SOAPContentType;
                }
            }
            finally{
                CallContext.FreeNamedDataSlot("__CustomErrorsEnabled");
            }

            return processing;
        } // ProcessMessage
        public ServerProcessing ProcessMessage(IServerChannelSinkStack sinkStack, IMessage requestMsg, ITransportHeaders requestHeaders, Stream requestStream, out IMessage responseMsg, out ITransportHeaders responseHeaders, out Stream responseStream)
        {
            responseHeaders = null;

            string strTransactID = (string)requestHeaders[CommonHeaders.ID];
            Guid transactID = (strTransactID == null ? Guid.Empty : new Guid(strTransactID));
            SecureTransaction transactType = (SecureTransaction)Convert.ToInt32((string)requestHeaders[CommonHeaders.Transaction]);

            IPAddress clientAddress = requestHeaders[CommonTransportKeys.IPAddress] as IPAddress;

            sinkStack.Push(this, null);

            ServerProcessing processingResult;

            switch (transactType)
            {
                case SecureTransaction.SendingPublicKey:
                    {
                        processingResult = MakeSharedKey(transactID, requestHeaders, out responseMsg, out responseHeaders, out responseStream);
                        System.Diagnostics.Debug.WriteLine("Connection added: " + transactID);
                        break;
                    }
                case SecureTransaction.SendingEncryptedMessage:
                    {
                        ClientConnectionInfo cci = (ClientConnectionInfo)_connections[transactID.ToString()];
                        string customerID = requestHeaders[CommonHeaders.CustomerID].ToString();
                        string password = requestHeaders[CommonHeaders.Password].ToString();
                        string extensionNumber = requestHeaders[CommonHeaders.ExtensionNumber].ToString();

                        if (PreviousTransactionWithClient(transactID))
                        {
                            if (RequireSecurity == true)
                            {
                                Authenticate(cci,customerID, extensionNumber, password);
                            }

                            processingResult = ProcessEncryptedMessage(transactID, sinkStack, requestMsg, requestHeaders, requestStream, out responseMsg, out responseHeaders, out responseStream);

                            if (clientAddress != null && cci != null)
                            {
                                CheckForManagementAllowed(cci, clientAddress.ToString(), extensionNumber);
                            }

                        }
                        else
                        {
                            processingResult = SendEmptyToClient(SecureTransaction.UnknownIdentifier, out responseMsg, out responseHeaders, out responseStream);
                        }

                        break;
                    }
                case SecureTransaction.Uninitialized:
                    {
                        if (!RequireSecurity)
                        {
                            processingResult = _next.ProcessMessage(sinkStack, requestMsg, requestHeaders, requestStream, out responseMsg, out responseHeaders, out responseStream);
                        }
                        else
                        {
                            throw new SecureRemotingException("Server requires a secure connection for this client");
                        }
                        break;
                    }
                default:
                    {
                        // Houston, we have a problem!
                        throw new SecureRemotingException("Invalid request from client: " + transactType + ".");
                    }
            }

            sinkStack.Pop(this);
            return processingResult;
        }
Example #35
0
        } // StrictBinding



        /// <include file='doc\SoapFormatterSinks.uex' path='docs/doc[@for="SoapServerFormatterSink.ProcessMessage"]/*' />
        public ServerProcessing ProcessMessage(IServerChannelSinkStack sinkStack,
                                               IMessage requestMsg,
                                               ITransportHeaders requestHeaders, Stream requestStream,
                                               out IMessage responseMsg, out ITransportHeaders responseHeaders,
                                               out Stream responseStream)
        {
            if (requestMsg != null)
            {
                // The message has already been deserialized so delegate to the next sink.
                return(_nextSink.ProcessMessage(
                           sinkStack,
                           requestMsg, requestHeaders, requestStream,
                           out responseMsg, out responseHeaders, out responseStream));
            }

            if (requestHeaders == null)
            {
                throw new ArgumentNullException("requestHeaders");
            }

            BaseTransportHeaders wkRequestHeaders = requestHeaders as BaseTransportHeaders;

            ServerProcessing processing;

            responseHeaders = null;
            responseStream  = null;

            String verb        = null;
            String contentType = null;

            bool bCanServiceRequest = true;

            // determine the content type
            String contentTypeHeader = null;

            if (wkRequestHeaders != null)
            {
                contentTypeHeader = wkRequestHeaders.ContentType;
            }
            else
            {
                contentTypeHeader = requestHeaders["Content-Type"] as String;
            }
            if (contentTypeHeader != null)
            {
                String charsetValue;
                HttpChannelHelper.ParseContentType(contentTypeHeader,
                                                   out contentType, out charsetValue);
            }

            // check to see if Content-Type matches
            if ((contentType != null) &&
                (String.Compare(contentType, CoreChannel.SOAPMimeType, false, CultureInfo.InvariantCulture) != 0))
            {
                bCanServiceRequest = false;
            }

            // check for http specific verbs
            if (_protocol == Protocol.Http)
            {
                verb = (String)requestHeaders["__RequestVerb"];
                if (!verb.Equals("POST") && !verb.Equals("M-POST"))
                {
                    bCanServiceRequest = false;
                }
            }

            // either delegate or return an error message if we can't service the request
            if (!bCanServiceRequest)
            {
                // delegate to next sink if available
                if (_nextSink != null)
                {
                    return(_nextSink.ProcessMessage(sinkStack, null, requestHeaders, requestStream,
                                                    out responseMsg, out responseHeaders, out responseStream));
                }
                else
                {
                    // send back an error message
                    if (_protocol == Protocol.Http)
                    {
                        // return a client bad request error
                        responseHeaders = new TransportHeaders();
                        responseHeaders["__HttpStatusCode"]   = "400";
                        responseHeaders["__HttpReasonPhrase"] = "Bad Request";
                        responseStream = null;
                        responseMsg    = null;
                        return(ServerProcessing.Complete);
                    }
                    else
                    {
                        // The transport sink will catch this and do something here.
                        throw new RemotingException(
                                  CoreChannel.GetResourceString("Remoting_Channels_InvalidRequestFormat"));
                    }
                }
            }

            bool bClientIsClr = true;

            try
            {
                String objectUri = null;
                if (wkRequestHeaders != null)
                {
                    objectUri = wkRequestHeaders.RequestUri;
                }
                else
                {
                    objectUri = (String)requestHeaders[CommonTransportKeys.RequestUri];
                }

                if (RemotingServices.GetServerTypeForUri(objectUri) == null)
                {
                    throw new RemotingException(
                              CoreChannel.GetResourceString("Remoting_ChnlSink_UriNotPublished"));
                }


                if (_protocol == Protocol.Http)
                {
                    String userAgent = (String)requestHeaders["User-Agent"];
                    if (userAgent != null)
                    {
                        if (userAgent.IndexOf("MS .NET Remoting") == -1)
                        {
                            // user agent string did not contain ".NET Remoting", so it is someone else
                            bClientIsClr = false;
                        }
                    }
                    else
                    {
                        bClientIsClr = false;
                    }
                }



                // Deserialize Request - Stream to IMessage
                String   soapActionToVerify;
                Header[] h = GetChannelHeaders(requestHeaders, out soapActionToVerify);

                requestMsg = CoreChannel.DeserializeSoapRequestMessage(requestStream, h, _strictBinding);
                requestStream.Close();

                if (requestMsg == null)
                {
                    throw new RemotingException(CoreChannel.GetResourceString("Remoting_DeserializeMessage"));
                }

                // verify soap action if necessary
                if ((soapActionToVerify != null) &&
                    (!SoapServices.IsSoapActionValidForMethodBase(
                         soapActionToVerify, ((IMethodMessage)requestMsg).MethodBase)))
                {
                    throw new RemotingException(
                              String.Format(
                                  CoreChannel.GetResourceString("Remoting_Soap_InvalidSoapAction"),
                                  soapActionToVerify)
                              );
                }

                // Dispatch Call
                sinkStack.Push(this, null);
                processing =
                    _nextSink.ProcessMessage(sinkStack, requestMsg, requestHeaders, null,
                                             out responseMsg, out responseHeaders, out responseStream);
                // make sure that responseStream is null
                if (responseStream != null)
                {
                    throw new RemotingException(
                              CoreChannel.GetResourceString("Remoting_ChnlSink_WantNullResponseStream"));
                }

                switch (processing)
                {
                case ServerProcessing.Complete:
                {
                    if (responseMsg == null)
                    {
                        throw new RemotingException(CoreChannel.GetResourceString("Remoting_DispatchMessage"));
                    }

                    sinkStack.Pop(this);

                    SerializeResponse(sinkStack, responseMsg, bClientIsClr,
                                      ref responseHeaders, out responseStream);
                    break;
                } // case ServerProcessing.Complete

                case ServerProcessing.OneWay:
                {
                    sinkStack.Pop(this);
                    break;
                } // case ServerProcessing.OneWay:

                case ServerProcessing.Async:
                {
                    sinkStack.Store(this, null);
                    break;
                } // case ServerProcessing.Async
                } // switch (processing)
            }
            catch (Exception e)
            {
                processing  = ServerProcessing.Complete;
                responseMsg = new ReturnMessage(e, (IMethodCallMessage)(requestMsg == null?new ErrorMessage():requestMsg));
                CallContext.SetData("__ClientIsClr", bClientIsClr);
                responseStream = (MemoryStream)CoreChannel.SerializeSoapMessage(responseMsg, _includeVersioning);
                CallContext.FreeNamedDataSlot("__ClientIsClr");
                responseStream.Position = 0;
                responseHeaders         = new TransportHeaders();

                if (_protocol == Protocol.Http)
                {
                    responseHeaders["__HttpStatusCode"]   = "500";
                    responseHeaders["__HttpReasonPhrase"] = "Internal Server Error";
                    responseHeaders["Content-Type"]       = CoreChannel.SOAPContentType;
                }
            }

            return(processing);
        } // ProcessMessage
        public ServerProcessing ProcessMessage(IServerChannelSinkStack sinkStack, IMessage requestMsg, ITransportHeaders requestHeaders, Stream requestStream, out IMessage responseMsg, out ITransportHeaders responseHeaders, out Stream responseStream)
        {
            if (requestMsg != null)
            {
                // the message has already been deserialized so delegate to the next sink
                return _nextSink.ProcessMessage(
                    sinkStack,
                    requestMsg, requestHeaders, requestStream,
                    out responseMsg, out responseHeaders, out responseStream);
            }

            // parameters validation
            if (sinkStack == null)
                throw new ArgumentNullException("sinkStack");
            if (requestHeaders == null)
                throw new ArgumentNullException("requestHeaders");
            if (requestStream == null)
                throw new ArgumentNullException("requestStream");

            // deserialize request
            IMethodCallMessage methodCall = _formatter.DeserializeRequest(requestHeaders, requestStream);
            requestStream.Close();

            // prepare stack for request processing
            sinkStack.Push(this, null);

            // process request
            ServerProcessing processing;
            IMethodReturnMessage methodReturn = null;

            try
            {
                // call next sink to dispatch method call
                processing = _nextSink.ProcessMessage(
                    sinkStack,
                    methodCall, requestHeaders, null,
                    out responseMsg, out responseHeaders, out responseStream);

                if (processing == ServerProcessing.Complete)
                {
                    // response headers and stream must be null at this point!
                    if (responseHeaders != null)
                        throw new NotSupportedException();
                    if (responseStream != null)
                        throw new NotSupportedException();

                    // check response
                    methodReturn = responseMsg as IMethodReturnMessage;
                    if (methodReturn == null)
                        throw new NotSupportedException();
                }
            }
            catch (Exception ex)
            {
                processing = ServerProcessing.Complete;
                methodReturn = new ReturnMessage(ex, methodCall);

                responseMsg = methodReturn;
                responseHeaders = null;
                responseStream = null;
            }

            // handle response
            switch (processing)
            {
                case ServerProcessing.Complete:
                    {
                        // call proceeded synchronously - serialize response
                        sinkStack.Pop(this);
                        SerializeResponse(sinkStack, methodReturn, out responseHeaders, out responseStream);
                        break;
                    }
                case ServerProcessing.OneWay:
                    {
                        // no response needed
                        sinkStack.Pop(this);
                        break;
                    }
                case ServerProcessing.Async:
                    {
                        // call proceeded asynchronously
                        sinkStack.Store(this, null);
                        break;
                    }
                default:
                    throw new NotSupportedException();
            }

            return processing;
        }
        public ServerProcessing ProcessMessage(IServerChannelSinkStack sinkStack, IMessage requestMsg, ITransportHeaders requestHeaders, Stream requestStream, out IMessage responseMsg, out ITransportHeaders responseHeaders, out Stream responseStream)
        {
            bool clientCompressed = false;

            // decompress the shits
            Stream decompressedStream;
            if (object.Equals(requestHeaders[CompressionHelper.CompressKey], CompressionHelper.CompressedFlag)) {
                //Debug.WriteLine("client compressed");
                clientCompressed = true;
                decompressedStream = CompressionHelper.DecompressStream(requestStream);
                // close the request stream
                requestStream.Close();
            }
            else {
                if (object.Equals(requestHeaders[CompressionHelper.CompressKey], CompressionHelper.CompressRequest)) {
                    //Debug.WriteLine("client requesting compress");
                    clientCompressed = true;
                }

                decompressedStream = requestStream;
            }

            sinkStack.Push(this, new ClientState(clientCompressed));

            // send the decompressed message on through the sink chain
            ServerProcessing processingResult = _next.ProcessMessage(sinkStack, requestMsg, requestHeaders, decompressedStream, out responseMsg, out responseHeaders, out responseStream);

            // get the compressed stream
            if (clientCompressed && processingResult == ServerProcessing.Complete) {
                Stream compressedStream = CompressionHelper.CompressStream(responseStream);
                responseStream.Close();
                responseStream = compressedStream;
                responseHeaders[CompressionHelper.CompressKey] = CompressionHelper.CompressedFlag;
            }

            // Take us off the stack and return the result.
            if (processingResult == ServerProcessing.Async) {
                sinkStack.Store(this, new ClientState(clientCompressed));
            }
            else {
                sinkStack.Pop(this);
            }
            return processingResult;
        }
Example #38
0
        /// <summary>
        /// Verarbeitet eine einzele Clientanfrage
        /// </summary>
        /// <param name="sinkStack">Aufrufstapel der Kanalsenken</param>
        /// <param name="requestMsg">Anfrage-nachricht</param>
        /// <param name="requestHeaders">Anfrage-Header</param>
        /// <param name="requestStream">Anfrage-Datenstrom</param>
        /// <param name="responseMsg">Antwort-Nachricht</param>
        /// <param name="responseHeaders">Antwort-Header</param>
        /// <param name="responseStream">Antwort-Datenstrom</param>
        /// <returns>Status serverseitigen Verarbeitung der Nachricht insgesamt</returns>
        public ServerProcessing ProcessMessage(IServerChannelSinkStack sinkStack, IMessage requestMsg, ITransportHeaders requestHeaders, Stream requestStream, out IMessage responseMsg, out ITransportHeaders responseHeaders, out Stream responseStream)
        {
            // Aktuelle Kanalsenke auf den Senkenstapel legen, damit AsyncProcessResponse später ggf. asynchron aufgerufen werden kann
            sinkStack.Push(this, null);

            //Threadsave
            lock (_lockObject)
            {
                //Verarbeite die Nachricht
                DoProcessMessageBefore(requestMsg, requestHeaders, requestStream);
            }

            // Variable für Verarbeitungsstatus
            ServerProcessing processingResult;

            // Nachricht gleich an die nächste Senke zur Weiterverarbeitung übergeben
            processingResult = _next.ProcessMessage(sinkStack, requestMsg, requestHeaders, requestStream, out responseMsg, out responseHeaders, out responseStream);

            //Threadsave
            lock (_lockObject)
            {
                //Verarbeite die Nachricht
                DoProcessMessageAfter(responseMsg, responseHeaders, responseStream, requestHeaders);
            }

            // Aktuelle Senke wieder vom Senkenstapel runternehmen
            sinkStack.Pop(this);

            return processingResult;
        }
Example #39
0
        /// <summary>
        /// Verarbeitet eine einzele Clientanfrage
        /// </summary>
        /// <param name="sinkStack">Aufrufstapel der Kanalsenken</param>
        /// <param name="requestMsg">Anfrage-nachricht</param>
        /// <param name="requestHeaders">Anfrage-Header</param>
        /// <param name="requestStream">Anfrage-Datenstrom</param>
        /// <param name="responseMsg">Antwort-Nachricht</param>
        /// <param name="responseHeaders">Antwort-Header</param>
        /// <param name="responseStream">Antwort-Datenstrom</param>
        /// <returns>Status serverseitigen Verarbeitung der Nachricht insgesamt</returns>
        public ServerProcessing ProcessMessage(IServerChannelSinkStack sinkStack, IMessage requestMsg, ITransportHeaders requestHeaders, Stream requestStream, out IMessage responseMsg, out ITransportHeaders responseHeaders, out Stream responseStream)
        {
            // Sicherheitstransaktionskennung aus Anfrage-Header lesen
            string strTransactID = (string)requestHeaders[CommonHeaderNames.SECURE_TRANSACTION_ID];

            // In Guid umwandeln
            Guid transactID = (strTransactID == null ? Guid.Empty : new Guid(strTransactID));

            // Aktuellen Transaktionsschritt aus Anfrage-Header lesen
            SecureTransactionStage transactionStage = (SecureTransactionStage)Convert.ToInt32((string)requestHeaders[CommonHeaderNames.SECURE_TRANSACTION_STATE]);

            // IP-Adresse des Clients aus Anfrage-Header lesen
            IPAddress clientAddress = requestHeaders[CommonTransportKeys.IPAddress] as IPAddress;

            // Aktuelle Kanalsenke auf den Senkenstapel legen, damit AsyncProcessResponse später ggf. asynchron aufgerufen werden kann
            sinkStack.Push(this, null);

            // Variable für Verarbeitungsstatus
            ServerProcessing processingResult;

            // Aktuellen Transaktionsschritt auswerten
            switch (transactionStage)
            {
                case SecureTransactionStage.SendingPublicKey: // Client sendet den öffentlichen Schlüssel an den Server

                    // Gemeinsamen Schlüssel erzeugen und mit dem öffentlichen Schlüssel des Clients verschlüsseln
                    processingResult = MakeSharedKey(transactID, requestHeaders, out responseMsg, out responseHeaders, out responseStream);

                    break;

                case SecureTransactionStage.SendingEncryptedMessage: // Client sendet die verschlüsselte Anfragenachricht an den Server

                    // Wenn die Sicherheitstransaktionskennung des Clients bekannt ist ...
                    if (IsExistingSecurityTransaction(transactID))
                        // Verschlüsselte Nachricht verarbeiten
                        processingResult = ProcessEncryptedMessage(transactID, sinkStack, requestMsg, requestHeaders, requestStream, out responseMsg, out responseHeaders, out responseStream);
                    else
                        // Leere Nachricht an den Client senden und Transaktionsschritt auf "Unbekannte Sicherheitstransaktionskennung". setzen.
                        processingResult = SendEmptyToClient(SecureTransactionStage.UnknownTransactionID, out responseMsg, out responseHeaders, out responseStream);

                    break;

                case SecureTransactionStage.Uninitialized: // Uninizialisiert, noch nichts geschehen

                    // Wenn für diesen Client Verschlüsselung nicht zwingend notwendig ist ...
                    if (!RequireEncryption(clientAddress))
                        // Nachricht gleich an die nächste Senke zur Weiterverarbeitung übergeben
                        processingResult = _next.ProcessMessage(sinkStack, requestMsg, requestHeaders, requestStream, out responseMsg, out responseHeaders, out responseStream);
                    else
                        // Ausnahme werfen
                        throw new CryptoRemotingException(LanguageResource.CryptoRemotingException_ServerRequiresEncryption);

                    break;

                default:

                    // Ausnahme werfen
                    throw new CryptoRemotingException(string.Format(LanguageResource.CryptoRemotingException_InvalidClientRequest, transactionStage));
            }
            // Aktuelle Senke wieder vom Senkenstapel runternehmen
            sinkStack.Pop(this);

            // Veratbeitungsstatus zurückgeben
            return processingResult;
        }
        public ServerProcessing ProcessMessage(IServerChannelSinkStack sinkStack, IMessage requestMsg, ITransportHeaders requestHeaders, Stream requestStream, out IMessage responseMsg, out ITransportHeaders responseHeaders, out Stream responseStream)
        {
            ServerProcessing complete;

            if (requestMsg != null)
            {
                return(this._nextSink.ProcessMessage(sinkStack, requestMsg, requestHeaders, requestStream, out responseMsg, out responseHeaders, out responseStream));
            }
            if (requestHeaders == null)
            {
                throw new ArgumentNullException("requestHeaders");
            }
            BaseTransportHeaders headers = requestHeaders as BaseTransportHeaders;

            responseHeaders = null;
            responseStream  = null;
            string str         = null;
            string str2        = null;
            bool   flag        = true;
            string contentType = null;

            if (headers != null)
            {
                contentType = headers.ContentType;
            }
            else
            {
                contentType = requestHeaders["Content-Type"] as string;
            }
            if (contentType != null)
            {
                string str4;
                HttpChannelHelper.ParseContentType(contentType, out str2, out str4);
            }
            if ((str2 != null) && (string.Compare(str2, "text/xml", StringComparison.Ordinal) != 0))
            {
                flag = false;
            }
            if (this._protocol == Protocol.Http)
            {
                str = (string)requestHeaders["__RequestVerb"];
                if (!str.Equals("POST") && !str.Equals("M-POST"))
                {
                    flag = false;
                }
            }
            if (!flag)
            {
                if (this._nextSink != null)
                {
                    return(this._nextSink.ProcessMessage(sinkStack, null, requestHeaders, requestStream, out responseMsg, out responseHeaders, out responseStream));
                }
                if (this._protocol != Protocol.Http)
                {
                    throw new RemotingException(CoreChannel.GetResourceString("Remoting_Channels_InvalidRequestFormat"));
                }
                responseHeaders = new TransportHeaders();
                responseHeaders["__HttpStatusCode"]   = "400";
                responseHeaders["__HttpReasonPhrase"] = "Bad Request";
                responseStream = null;
                responseMsg    = null;
                return(ServerProcessing.Complete);
            }
            bool bClientIsClr = true;

            try
            {
                string str7;
                string uRI = null;
                if (headers != null)
                {
                    uRI = headers.RequestUri;
                }
                else
                {
                    uRI = (string)requestHeaders["__RequestUri"];
                }
                if (RemotingServices.GetServerTypeForUri(uRI) == null)
                {
                    throw new RemotingException(CoreChannel.GetResourceString("Remoting_ChnlSink_UriNotPublished"));
                }
                if (this._protocol == Protocol.Http)
                {
                    string str6 = (string)requestHeaders["User-Agent"];
                    if (str6 != null)
                    {
                        if (str6.IndexOf("MS .NET Remoting") == -1)
                        {
                            bClientIsClr = false;
                        }
                    }
                    else
                    {
                        bClientIsClr = false;
                    }
                }
                bool   data = true;
                object obj2 = requestHeaders["__CustomErrorsEnabled"];
                if ((obj2 != null) && (obj2 is bool))
                {
                    data = (bool)obj2;
                }
                CallContext.SetData("__CustomErrorsEnabled", data);
                Header[]      channelHeaders = this.GetChannelHeaders(requestHeaders, out str7);
                PermissionSet set            = null;
                if (this.TypeFilterLevel != System.Runtime.Serialization.Formatters.TypeFilterLevel.Full)
                {
                    set = new PermissionSet(PermissionState.None);
                    set.SetPermission(new SecurityPermission(SecurityPermissionFlag.SerializationFormatter));
                }
                try
                {
                    if (set != null)
                    {
                        set.PermitOnly();
                    }
                    requestMsg = CoreChannel.DeserializeSoapRequestMessage(requestStream, channelHeaders, this._strictBinding, this.TypeFilterLevel);
                }
                finally
                {
                    if (set != null)
                    {
                        CodeAccessPermission.RevertPermitOnly();
                    }
                }
                requestStream.Close();
                if (requestMsg == null)
                {
                    throw new RemotingException(CoreChannel.GetResourceString("Remoting_DeserializeMessage"));
                }
                if ((str7 != null) && !SoapServices.IsSoapActionValidForMethodBase(str7, ((IMethodMessage)requestMsg).MethodBase))
                {
                    throw new RemotingException(string.Format(CultureInfo.CurrentCulture, CoreChannel.GetResourceString("Remoting_Soap_InvalidSoapAction"), new object[] { str7 }));
                }
                sinkStack.Push(this, null);
                complete = this._nextSink.ProcessMessage(sinkStack, requestMsg, requestHeaders, null, out responseMsg, out responseHeaders, out responseStream);
                if (responseStream != null)
                {
                    throw new RemotingException(CoreChannel.GetResourceString("Remoting_ChnlSink_WantNullResponseStream"));
                }
                switch (complete)
                {
                case ServerProcessing.Complete:
                    if (responseMsg == null)
                    {
                        throw new RemotingException(CoreChannel.GetResourceString("Remoting_DispatchMessage"));
                    }
                    break;

                case ServerProcessing.OneWay:
                    sinkStack.Pop(this);
                    return(complete);

                case ServerProcessing.Async:
                    sinkStack.Store(this, null);
                    return(complete);

                default:
                    return(complete);
                }
                sinkStack.Pop(this);
                this.SerializeResponse(sinkStack, responseMsg, bClientIsClr, ref responseHeaders, out responseStream);
                return(complete);
            }
            catch (Exception exception)
            {
                complete    = ServerProcessing.Complete;
                responseMsg = new ReturnMessage(exception, (requestMsg == null) ? ((IMethodCallMessage) new System.Runtime.Remoting.Channels.Http.ErrorMessage()) : ((IMethodCallMessage)requestMsg));
                CallContext.SetData("__ClientIsClr", bClientIsClr);
                responseStream = (MemoryStream)CoreChannel.SerializeSoapMessage(responseMsg, this._includeVersioning);
                CallContext.FreeNamedDataSlot("__ClientIsClr");
                responseStream.Position = 0L;
                responseHeaders         = new TransportHeaders();
                if (this._protocol == Protocol.Http)
                {
                    responseHeaders["__HttpStatusCode"]   = "500";
                    responseHeaders["__HttpReasonPhrase"] = "Internal Server Error";
                    responseHeaders["Content-Type"]       = "text/xml; charset=\"utf-8\"";
                }
            }
            finally
            {
                CallContext.FreeNamedDataSlot("__CustomErrorsEnabled");
            }
            return(complete);
        }
Example #41
0
        public ServerProcessing ProcessMessage(IServerChannelSinkStack sinkStack,
                                               IMessage requestMsg, ITransportHeaders requestHeaders, Stream requestStream,
                                               out IMessage responseMsg, out ITransportHeaders responseHeaders, out Stream responseStream)
        {
            sinkStack.Push(this, null);
            ServerProcessing res;

            try
            {
                string url = (string)requestHeaders["__RequestUri"];
                string uri;
                receiver.Parse(url, out uri);
                if (uri == null)
                {
                    uri = url;
                }

                MethodCallHeaderHandler mhh = new MethodCallHeaderHandler(uri);
                requestMsg = (IMessage)_binaryCore.Deserializer.Deserialize(requestStream, new HeaderHandler(mhh.HandleHeaders));

                res = next_sink.ProcessMessage(sinkStack, requestMsg, requestHeaders, null, out responseMsg, out responseHeaders, out responseStream);
            }
            catch (Exception ex)
            {
                responseMsg     = new ReturnMessage(ex, (IMethodCallMessage)requestMsg);
                res             = ServerProcessing.Complete;
                responseHeaders = null;
                responseStream  = null;
            }

            if (res == ServerProcessing.Complete)
            {
                for (int n = 0; n < 3; n++)
                {
                    responseStream  = null;
                    responseHeaders = new TransportHeaders();

                    if (sinkStack != null)
                    {
                        responseStream = sinkStack.GetResponseStream(responseMsg, responseHeaders);
                    }
                    if (responseStream == null)
                    {
                        responseStream = new MemoryStream();
                    }

                    try {
                        _binaryCore.Serializer.Serialize(responseStream, responseMsg);
                        break;
                    } catch (Exception ex) {
                        if (n == 2)
                        {
                            throw ex;
                        }
                        else
                        {
                            responseMsg = new ReturnMessage(ex, (IMethodCallMessage)requestMsg);
                        }
                    }
                }

                if (responseStream is MemoryStream)
                {
                    responseStream.Position = 0;
                }


                sinkStack.Pop(this);
            }
            return(res);
        }
        public ServerProcessing ProcessMessage(IServerChannelSinkStack sinkStack, IMessage requestMsg, ITransportHeaders requestHeaders, Stream requestStream, out IMessage responseMsg, out ITransportHeaders responseHeaders, out Stream responseStream)
        {
            responseHeaders = null;

            string            strTransactID = (string)requestHeaders[CommonHeaders.ID];
            Guid              transactID    = (strTransactID == null ? Guid.Empty : new Guid(strTransactID));
            SecureTransaction transactType  = (SecureTransaction)Convert.ToInt32((string)requestHeaders[CommonHeaders.Transaction]);

            IPAddress clientAddress = requestHeaders[CommonTransportKeys.IPAddress] as IPAddress;

            sinkStack.Push(this, null);

            ServerProcessing processingResult;

            switch (transactType)
            {
            case SecureTransaction.SendingPublicKey:
            {
                processingResult = MakeSharedKey(transactID, requestHeaders, out responseMsg, out responseHeaders, out responseStream);
                System.Diagnostics.Debug.WriteLine("Connection added: " + transactID);
                break;
            }

            case SecureTransaction.SendingEncryptedMessage:
            {
                ClientConnectionInfo cci = (ClientConnectionInfo)_connections[transactID.ToString()];
                string customerID        = requestHeaders[CommonHeaders.CustomerID].ToString();
                string password          = requestHeaders[CommonHeaders.Password].ToString();
                string extensionNumber   = requestHeaders[CommonHeaders.ExtensionNumber].ToString();


                if (PreviousTransactionWithClient(transactID))
                {
                    if (RequireSecurity == true)
                    {
                        Authenticate(cci, customerID, extensionNumber, password);
                    }

                    processingResult = ProcessEncryptedMessage(transactID, sinkStack, requestMsg, requestHeaders, requestStream, out responseMsg, out responseHeaders, out responseStream);

                    if (clientAddress != null && cci != null)
                    {
                        CheckForManagementAllowed(cci, clientAddress.ToString(), extensionNumber);
                    }
                }
                else
                {
                    processingResult = SendEmptyToClient(SecureTransaction.UnknownIdentifier, out responseMsg, out responseHeaders, out responseStream);
                }


                break;
            }

            case SecureTransaction.Uninitialized:
            {
                if (!RequireSecurity)
                {
                    processingResult = _next.ProcessMessage(sinkStack, requestMsg, requestHeaders, requestStream, out responseMsg, out responseHeaders, out responseStream);
                }
                else
                {
                    throw new SecureRemotingException("Server requires a secure connection for this client");
                }
                break;
            }

            default:
            {
                // Houston, we have a problem!
                throw new SecureRemotingException("Invalid request from client: " + transactType + ".");
            }
            }

            sinkStack.Pop(this);
            return(processingResult);
        }
        public ServerProcessing ProcessMessage(IServerChannelSinkStack sinkStack,
                                               IMessage requestMsg,
                                               ITransportHeaders requestHeaders, Stream requestStream,
                                               out IMessage responseMsg, out ITransportHeaders responseHeaders,
                                               out Stream responseStream)
        {
            if (requestMsg != null)
            {
                // The message has already been deserialized so delegate to the next sink.
                return(_nextSink.ProcessMessage(
                           sinkStack,
                           requestMsg, requestHeaders, requestStream,
                           out responseMsg, out responseHeaders, out responseStream));
            }

            if (requestHeaders == null)
            {
                throw new ArgumentNullException("requestHeaders");
            }

            BaseTransportHeaders wkRequestHeaders = requestHeaders as BaseTransportHeaders;

            ServerProcessing processing;

            responseHeaders = null;
            responseStream  = null;

            String verb        = null;
            String contentType = null;

            bool bCanServiceRequest = true;

            // determine the content type
            String contentTypeHeader = null;

            if (wkRequestHeaders != null)
            {
                contentTypeHeader = wkRequestHeaders.ContentType;
            }
            else
            {
                contentTypeHeader = requestHeaders["Content-Type"] as String;
            }
            if (contentTypeHeader != null)
            {
                String charsetValue;
                HttpChannelHelper.ParseContentType(contentTypeHeader,
                                                   out contentType, out charsetValue);
            }

            // check to see if Content-Type matches
            if ((contentType != null) &&
                (String.CompareOrdinal(contentType, CoreChannel.BinaryMimeType) != 0))
            {
                bCanServiceRequest = false;
            }

            // check for http specific verbs
            if (_protocol == Protocol.Http)
            {
                verb = (String)requestHeaders["__RequestVerb"];
                if (!verb.Equals("POST") && !verb.Equals("M-POST"))
                {
                    bCanServiceRequest = false;
                }
            }

            // either delegate or return an error message if we can't service the request
            if (!bCanServiceRequest)
            {
                // delegate to next sink if available
                if (_nextSink != null)
                {
                    return(_nextSink.ProcessMessage(sinkStack, null, requestHeaders, requestStream,
                                                    out responseMsg, out responseHeaders, out responseStream));
                }
                else
                {
                    // send back an error message
                    if (_protocol == Protocol.Http)
                    {
                        // return a client bad request error
                        responseHeaders = new TransportHeaders();
                        responseHeaders["__HttpStatusCode"]   = "400";
                        responseHeaders["__HttpReasonPhrase"] = "Bad Request";
                        responseStream = null;
                        responseMsg    = null;
                        return(ServerProcessing.Complete);
                    }
                    else
                    {
                        // The transport sink will catch this and do something here.
                        throw new RemotingException(
                                  CoreChannel.GetResourceString("Remoting_Channels_InvalidRequestFormat"));
                    }
                }
            }


            try
            {
                String objectUri = null;

                bool   bIsCustomErrorEnabled = true;
                object oIsCustomErrorEnabled = requestHeaders["__CustomErrorsEnabled"];
                if (oIsCustomErrorEnabled != null && oIsCustomErrorEnabled is bool)
                {
                    bIsCustomErrorEnabled = (bool)oIsCustomErrorEnabled;
                }
                CallContext.SetData("__CustomErrorsEnabled", bIsCustomErrorEnabled);

                if (wkRequestHeaders != null)
                {
                    objectUri = wkRequestHeaders.RequestUri;
                }
                else
                {
                    objectUri = (String)requestHeaders[CommonTransportKeys.RequestUri];
                }

                if (objectUri != lastUri && RemotingServices.GetServerTypeForUri(objectUri) == null)
                {
                    throw new RemotingException(
                              CoreChannel.GetResourceString("Remoting_ChnlSink_UriNotPublished"));
                }
                else
                {
                    lastUri = objectUri;
                }

                PermissionSet currentPermissionSet = null;
                if (this.TypeFilterLevel != TypeFilterLevel.Full)
                {
                    currentPermissionSet = new PermissionSet(PermissionState.None);
                    currentPermissionSet.SetPermission(new SecurityPermission(SecurityPermissionFlag.SerializationFormatter));
                }

                try {
                    if (currentPermissionSet != null)
                    {
                        currentPermissionSet.PermitOnly();
                    }

                    // Deserialize Request - Stream to IMessage
                    requestMsg = CoreChannel.DeserializeBinaryRequestMessage(objectUri, requestStream, _strictBinding, this.TypeFilterLevel);
                }
                finally {
                    if (currentPermissionSet != null)
                    {
                        CodeAccessPermission.RevertPermitOnly();
                    }
                }
                requestStream.Close();

                if (requestMsg == null)
                {
                    throw new RemotingException(CoreChannel.GetResourceString("Remoting_DeserializeMessage"));
                }


                // Dispatch Call
                sinkStack.Push(this, null);
                processing =
                    _nextSink.ProcessMessage(sinkStack, requestMsg, requestHeaders, null,
                                             out responseMsg, out responseHeaders, out responseStream);
                // make sure that responseStream is null
                if (responseStream != null)
                {
                    throw new RemotingException(
                              CoreChannel.GetResourceString("Remoting_ChnlSink_WantNullResponseStream"));
                }

                switch (processing)
                {
                case ServerProcessing.Complete:
                {
                    if (responseMsg == null)
                    {
                        throw new RemotingException(CoreChannel.GetResourceString("Remoting_DispatchMessage"));
                    }

                    sinkStack.Pop(this);

                    SerializeResponse(sinkStack, responseMsg,
                                      ref responseHeaders, out responseStream);
                    break;
                } // case ServerProcessing.Complete

                case ServerProcessing.OneWay:
                {
                    sinkStack.Pop(this);
                    break;
                } // case ServerProcessing.OneWay:

                case ServerProcessing.Async:
                {
                    sinkStack.Store(this, null);
                    break;
                } // case ServerProcessing.Async
                } // switch (processing)
            }
            catch (Exception e)
            {
                processing  = ServerProcessing.Complete;
                responseMsg = new ReturnMessage(e, (IMethodCallMessage)(requestMsg == null?new ErrorMessage():requestMsg));
                //

                CallContext.SetData("__ClientIsClr", true);
                responseStream = (MemoryStream)CoreChannel.SerializeBinaryMessage(responseMsg, _includeVersioning);
                CallContext.FreeNamedDataSlot("__ClientIsClr");
                responseStream.Position = 0;
                responseHeaders         = new TransportHeaders();

                if (_protocol == Protocol.Http)
                {
                    responseHeaders["Content-Type"] = CoreChannel.BinaryMimeType;
                }
            }
            finally{
                CallContext.FreeNamedDataSlot("__CustomErrorsEnabled");
            }

            return(processing);
        } // ProcessMessage
Example #44
0
        /// <summary>
        /// process a giop request message.
        /// </summary>
        private ServerProcessing ProcessRequestMessage(IServerChannelSinkStack sinkStack,
                                                       ITransportHeaders requestHeaders,
                                                       CdrMessageInputStream msgInput,
                                                       GiopServerConnection serverCon,
                                                       out IMessage responseMsg, out ITransportHeaders responseHeaders,
                                                       out Stream responseStream)
        {
            IMessage deserReqMsg = null;

            responseHeaders = null;
            try {
                try {
                    // deserialise the request
                    deserReqMsg = m_messageHandler.ParseIncomingRequestMessage(msgInput,
                                                                               serverCon.ConDesc);
                } finally {
                    //request deserialised -> safe to read next request while processing request in servant
                    // (or sending request deserialisation exception)
                    try {
                        serverCon.NotifyDeserialiseRequestComplete();
                    } catch (Exception ne) {
                        // unexpected exception. Abort message processing, problem with transport.
                        throw new NotifyReadRequestException("Problem while trying to inform transport about request deserialistion.",
                                                             ne);
                    }
                }

                // processing may be done asynchronous, therefore push this sink on the stack to process a response async
                AsyncServerProcessingData asyncData =
                    new AsyncServerProcessingData(deserReqMsg, serverCon);
                sinkStack.Push(this, asyncData);
                ServerProcessing processingResult;
                try {
                    // forward the call to the next message handling sink
                    processingResult = m_nextSink.ProcessMessage(sinkStack, deserReqMsg,
                                                                 requestHeaders, null, out responseMsg,
                                                                 out responseHeaders, out responseStream);
                } catch (Exception) {
                    sinkStack.Pop(this);
                    throw;
                }
                switch (processingResult)
                {
                case ServerProcessing.Complete:
                    sinkStack.Pop(this);     // not async
                    // send the response
                    SerialiseResponse(sinkStack, deserReqMsg, serverCon, responseMsg,
                                      ref responseHeaders, out responseStream);
                    break;

                case ServerProcessing.Async:
                    sinkStack.Store(this, asyncData);     // this sink want's to process async response
                    break;

                case ServerProcessing.OneWay:
                    // nothing to do, because no response expected
                    sinkStack.Pop(this);
                    break;
                }
                return(processingResult);
            } catch (MessageHandling.RequestDeserializationException deserEx) {
                // exception from DeserialisRequest
                responseMsg = deserEx.ResponseMessage;
                // an exception was thrown during deserialization
                SerialiseExceptionResponse(sinkStack,
                                           deserEx.RequestMessage, serverCon, responseMsg,
                                           ref responseHeaders, out responseStream);
                return(ServerProcessing.Complete);
            } catch (NotifyReadRequestException nrre) {
                Trace.WriteLine("Failed to inform transport about request deserialisation. Processing problem on server connection after unexpected exception: " + nrre.InnerException);
                throw nrre;
            } catch (Exception e) {
                // serialise an exception response
                if (deserReqMsg != null)
                {
                    if (deserReqMsg is IMethodCallMessage)
                    {
                        responseMsg = new ReturnMessage(e, (IMethodCallMessage)deserReqMsg);
                    }
                    else
                    {
                        responseMsg = new ReturnMessage(e, null); // no usable information present
                    }
                    SerialiseExceptionResponse(sinkStack,
                                               deserReqMsg, serverCon, responseMsg,
                                               ref responseHeaders, out responseStream);
                }
                else
                {
                    throw e;
                }
                return(ServerProcessing.Complete); // send back an error msg
            }
        }
        public ServerProcessing ProcessMessage(IServerChannelSinkStack sinkStack,
            IMessage requestMsg,
            ITransportHeaders requestHeaders, Stream requestStream,
            out IMessage responseMsg, out ITransportHeaders responseHeaders, 
            out Stream responseStream)
        {
            if (requestMsg != null)
            {
                // The message has already been deserialized so delegate to the next sink.
                return _nextSink.ProcessMessage(
                    sinkStack,
                    requestMsg, requestHeaders, requestStream, 
                    out responseMsg, out responseHeaders, out responseStream);
            }
        
            if (requestHeaders ==  null)
                throw new ArgumentNullException("requestHeaders");

            BaseTransportHeaders wkRequestHeaders = requestHeaders as BaseTransportHeaders;
        
            ServerProcessing processing;
        
            responseHeaders = null;
            responseStream = null;

            String verb = null;
            String contentType = null;

            bool bCanServiceRequest = true;

            // determine the content type
            String contentTypeHeader = null;
            if (wkRequestHeaders != null)
                contentTypeHeader = wkRequestHeaders.ContentType;
            else
                contentTypeHeader = requestHeaders["Content-Type"] as String;
            if (contentTypeHeader != null)
            {
                String charsetValue;
                HttpChannelHelper.ParseContentType(contentTypeHeader,
                                                   out contentType, out charsetValue);
            }

            // check to see if Content-Type matches
            if ((contentType != null) &&
                (String.CompareOrdinal(contentType, CoreChannel.BinaryMimeType) != 0))
            {
                bCanServiceRequest = false;                
            }

            // check for http specific verbs
            if (_protocol == Protocol.Http)
            {
                verb = (String)requestHeaders["__RequestVerb"];    
                if (!verb.Equals("POST") && !verb.Equals("M-POST"))
                    bCanServiceRequest = false;
            }

            // either delegate or return an error message if we can't service the request
            if (!bCanServiceRequest)
            {
                // delegate to next sink if available
                if (_nextSink != null)
                {
                    return _nextSink.ProcessMessage(sinkStack, null, requestHeaders, requestStream,   
                        out responseMsg, out responseHeaders, out responseStream);
                }
                else
                {
                    // send back an error message
                    if (_protocol == Protocol.Http)
                    {
                        // return a client bad request error     
                        responseHeaders = new TransportHeaders();
                        responseHeaders["__HttpStatusCode"] = "400";
                        responseHeaders["__HttpReasonPhrase"] = "Bad Request";
                        responseStream = null;
                        responseMsg = null;
                        return ServerProcessing.Complete;
                    }
                    else
                    {
                        // The transport sink will catch this and do something here.
                        throw new RemotingException(
                            CoreChannel.GetResourceString("Remoting_Channels_InvalidRequestFormat"));
                    }
                }
            }
            

            try
            {
                String objectUri = null;

                bool bIsCustomErrorEnabled = true;
                object oIsCustomErrorEnabled = requestHeaders["__CustomErrorsEnabled"];
                if (oIsCustomErrorEnabled != null && oIsCustomErrorEnabled is bool){
                    bIsCustomErrorEnabled = (bool)oIsCustomErrorEnabled;
                }
                CallContext.SetData("__CustomErrorsEnabled", bIsCustomErrorEnabled);
              
                if (wkRequestHeaders != null)
                    objectUri = wkRequestHeaders.RequestUri;
                else
                    objectUri = (String)requestHeaders[CommonTransportKeys.RequestUri];              
            
                if (objectUri != lastUri && RemotingServices.GetServerTypeForUri(objectUri) == null)
                    throw new RemotingException(
                        CoreChannel.GetResourceString("Remoting_ChnlSink_UriNotPublished"));
                else
                    lastUri = objectUri;
            
                PermissionSet currentPermissionSet = null;                  
                if (this.TypeFilterLevel != TypeFilterLevel.Full) {                    
                    currentPermissionSet = new PermissionSet(PermissionState.None);                
                    currentPermissionSet.SetPermission(new SecurityPermission(SecurityPermissionFlag.SerializationFormatter));                    
                }
                                    
                try {
                    if (currentPermissionSet != null)
                        currentPermissionSet.PermitOnly();
                        
                    // Deserialize Request - Stream to IMessage
                    requestMsg = CoreChannel.DeserializeBinaryRequestMessage(objectUri, requestStream, _strictBinding, this.TypeFilterLevel);                    
                }
                finally {
                    if (currentPermissionSet != null)
                        CodeAccessPermission.RevertPermitOnly();
                }                                    
                requestStream.Close();

                if(requestMsg == null)
                {
                    throw new RemotingException(CoreChannel.GetResourceString("Remoting_DeserializeMessage"));
                }

                // Transparent proxy IMessages are allowed conditionally by AppSettings
                if (RemotingServices.IsTransparentProxy(requestMsg) && !AppSettings.AllowTransparentProxyMessage)
                {
                    // Null request to prevent calling transparent proxy methods in catch below.
                    // Fwlink is provided to explain why it is not supported.  Inner exceptions propagate back to sender.
                    requestMsg = null;
                    throw new RemotingException(CoreChannel.GetResourceString("Remoting_DeserializeMessage"), 
                                                new NotSupportedException(AppSettings.AllowTransparentProxyMessageFwLink));
                }

                // Dispatch Call
                sinkStack.Push(this, null);
                processing =                    
                    _nextSink.ProcessMessage(sinkStack, requestMsg, requestHeaders, null,
                        out responseMsg, out responseHeaders, out responseStream);
                // make sure that responseStream is null
                if (responseStream != null)
                {
                    throw new RemotingException(
                        CoreChannel.GetResourceString("Remoting_ChnlSink_WantNullResponseStream"));
                }
                
                switch (processing)
                {

                case ServerProcessing.Complete:
                {
                    if (responseMsg == null)
                        throw new RemotingException(CoreChannel.GetResourceString("Remoting_DispatchMessage"));

                    sinkStack.Pop(this);

                    SerializeResponse(sinkStack, responseMsg,
                                      ref responseHeaders, out responseStream);
                    break;
                } // case ServerProcessing.Complete

                case ServerProcessing.OneWay:
                {
                    sinkStack.Pop(this);
                    break;
                } // case ServerProcessing.OneWay:

                case ServerProcessing.Async:
                {
                    sinkStack.Store(this, null);
                    break;   
                } // case ServerProcessing.Async
                    
                } // switch (processing)                
            }
            catch(Exception e)
            {
                processing = ServerProcessing.Complete;
                responseMsg = new ReturnMessage(e, (IMethodCallMessage)(requestMsg==null?new ErrorMessage():requestMsg));
                //

                CallContext.SetData("__ClientIsClr", true);
                responseStream = (MemoryStream)CoreChannel.SerializeBinaryMessage(responseMsg, _includeVersioning);
                CallContext.FreeNamedDataSlot("__ClientIsClr");                
                responseStream.Position = 0;
                responseHeaders = new TransportHeaders();

                if (_protocol == Protocol.Http)
                {
                    responseHeaders["Content-Type"] = CoreChannel.BinaryMimeType;
                }
            }
            finally{
                CallContext.FreeNamedDataSlot("__CustomErrorsEnabled");
            }

            return processing;
        } // ProcessMessage
Example #46
0
        public ServerProcessing ProcessMessage(IServerChannelSinkStack sinkStack,
            IMessage requestMsg, ITransportHeaders requestHeaders, Stream requestStream,
            out IMessage responseMsg, out ITransportHeaders responseHeaders,
            out Stream responseStream)
        {
            responseHeaders = null;
            responseStream = null;
            responseMsg = null;

            //Get Session ID from request Headers
            string SID = (string)requestHeaders[ChannelSinkHeaders.SID_HEADER];
            ServerSecurityContext context = null;

            //if no SID received
            if (SID == null)
            {
                //try to get login and password from request headers
                string userName = (string)requestHeaders[ChannelSinkHeaders.USER_NAME_HEADER];
                string password = (string)requestHeaders[ChannelSinkHeaders.PASSWORD_HEADER];
                bool useSessions = Boolean.Parse(
                    requestHeaders[ChannelSinkHeaders.USE_SESSIONS_HEADER] != null
                    ? (string) requestHeaders[ChannelSinkHeaders.USE_SESSIONS_HEADER]
                    : "false"
                    );

                if (password == null) password = "";

                AuthenticationStates authResult = AuthenticationStates.NotAuthenticated;

                //if password and login found
                if ((userName != null) && (password != null))
                {
                    //try to authenticate user
                    string[] roles;
                    //Call authentication handler
                    authResult = Authenticate(userName, password, out roles);

                    switch (authResult)
                    {
                        case AuthenticationStates.Authenticated:
                            context = new ServerSecurityContext(userName, password, roles);
                            context.SetAuthState(AuthenticationStates.Authenticated);

                            if (useSessions)
                                SecurityContextContainer.GetInstance()[context.SessionID] = context;

                            break;
                        default:
                            //throw new System.Security.SecurityException("Authentication failed");
                            break;
                    }
                }
            }
            else
            {
                //Try to get user's session by SID
                context = (ServerSecurityContext)SecurityContextContainer.GetInstance()[SID];
                if (context == null)
                {
                    throw new System.Security.SecurityException("Authentication failed.");
                }
                else
                {
                    ServerSecurityContext.Current = context;
                }
            }

            System.Security.Principal.IPrincipal originalPrincipal = Thread.CurrentPrincipal;

            if (ServerSecurityContext.Current != null)
            {
                Thread.CurrentPrincipal = ServerSecurityContext.Current.Principal;
            }

            sinkStack.Push(this, null);
            ServerProcessing processing;
            processing = _nextSink.ProcessMessage(
                sinkStack,
                requestMsg,
                requestHeaders,
                requestStream,
                out responseMsg,
                out responseHeaders,
                out responseStream
                );
            // pop us off the stack
            sinkStack.Pop(this);

            //Rollback thread ptincipal
            Thread.CurrentPrincipal = originalPrincipal;

            AuthenticationStates serverAuthState =  AuthenticationStates.NotAuthenticated;

            if (ServerSecurityContext.Current != null)
                serverAuthState = context.AuthState;

            responseHeaders = new TransportHeaders();

            switch (serverAuthState)
            {
                case AuthenticationStates.Authenticated:
                    responseHeaders[ChannelSinkHeaders.AUTH_STATE_HEADER] = AuthenticationStates.Authenticated;
                    responseHeaders[ChannelSinkHeaders.SID_HEADER] = ServerSecurityContext.Current.SessionID;
                    responseHeaders[ChannelSinkHeaders.ROLES_HEADER] = ServerSecurityContext.Current.Roles;
                    break;
                default :
                    responseHeaders[ChannelSinkHeaders.AUTH_STATE_HEADER] = serverAuthState;
                    break;
            }

            //Clear current user security context.
            ServerSecurityContext.Current = null;

            // check for errors
            if (processing != ServerProcessing.Complete)
                throw new Exception("SecurityServerChannelSink: ProcessRequest: Did not get ServerProcessing.Complete from next message sink");
            return ServerProcessing.Complete;
        }