/// <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; }
/// <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; }
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); }
public ServerProcessing ProcessMessage(IServerChannelSinkStack sinkStack, IMessage requestMessage, ITransportHeaders requestHeaders, Stream requestStream, out IMessage responseMessage, out ITransportHeaders responseHeaders, out Stream responseStream) { // Hand off to the next sink for processing. sinkStack.Push(this, null); ServerProcessing status = nextSink.ProcessMessage( sinkStack, requestMessage, requestHeaders, requestStream, out responseMessage, out responseHeaders, out responseStream ); // Print the response message properties. Console.WriteLine("---- Message from the server ----"); IDictionary dictionary = responseMessage.Properties; foreach (Object key in dictionary.Keys) { Console.WriteLine("{0} = {1}", key, dictionary[key]); } Console.WriteLine("---------------------------------"); return(status); }
public ServerProcessing ProcessMessage( IServerChannelSinkStack stack, IMessage requestMsg, ITransportHeaders requestHeaders, Stream requestStream, out IMessage responseMsg, out ITransportHeaders responseHeaders, out Stream responseStream ) { stack.Push(this, null); #region Check request stream header hash string hash = requestHeaders[HashHelper.C_HASH_ITEM] as String; //Debug.WriteLine("Server Side : request stream hash is " + hash); bool check = HashHelper.CheckHash(ref requestStream, hash); if (!check) { throw new Exception("Server Side : request stream header checksum error"); } #endregion ServerProcessing result = _nextSink.ProcessMessage(stack, requestMsg, requestHeaders, requestStream, out responseMsg, out responseHeaders, out responseStream); #region Add hash to response stream heaer hash = HashHelper.GetHash(ref responseStream); responseHeaders[HashHelper.C_HASH_ITEM] = hash; //Debug.WriteLine("Server Side : response stream hash is " + hash); #endregion return(result); }
public ServerProcessing ProcessMessage(IServerChannelSinkStack sinkStack, IMessage requestMsg, ITransportHeaders requestHeaders, Stream requestStream, out IMessage responseMsg, out ITransportHeaders responseHeaders, out Stream responseStream) { // проверяем, задано ли имя серверного хоста или его адрес _serverHostNameOrIp = requestHeaders["serverHostNameOrIp"]; if (_serverHostNameOrIp != null) { // помещаем его в контекст вызова CallContext.SetData("serverHostNameOrIp", _serverHostNameOrIp); // протоколируем if (_eventLink != null) { _eventLink.Post(_eventSource, string.Format("Имя или IP-адрес сервера ЗАДАНО: [{0}]", _serverHostNameOrIp)); } } else { // очишаем значение, оставшееся от предыдущих вызовов CallContext.FreeNamedDataSlot("serverHostNameOrIp"); // протоколируем if (_eventLink != null) { _eventLink.Post(_eventSource, EventType.Warning, "Имя или IP-адрес сервера НЕ задано"); } } // перенаправляем обработку сообщения следующему приемнику в цепи sinkStack.Push(this, null); ServerProcessing status = _nextSink.ProcessMessage(sinkStack, requestMsg, requestHeaders, requestStream, out responseMsg, out responseHeaders, out responseStream); return(status); }
public ServerProcessing ProcessMessage( IServerChannelSinkStack sinkStack, IMessage requestMsg, ITransportHeaders requestHeaders, Stream requestStream, out IMessage responseMsg, out ITransportHeaders responseHeaders, out Stream responseStream ) { // use presence of SOAPAction header to determine if this is a SOAP // request - if so pass onto next sink in chain string soapAction = (string)requestHeaders["SOAPAction"]; if (soapAction != null) { return(m_next.ProcessMessage(sinkStack, requestMsg, requestHeaders, requestStream, out responseMsg, out responseHeaders, out responseStream)); } // for time being assume we have an XML-RPC request (need to improve // this in case there are other non-SOAP formatters in the chain) MethodCall mthdCall = DeserializeRequest(requestHeaders, requestStream); sinkStack.Push(this, mthdCall); // forward to next sink in chain - pass request stream as null to // indicate that we have deserialized the request m_next.ProcessMessage(sinkStack, mthdCall, requestHeaders, null, out responseMsg, out responseHeaders, out responseStream); SerializeResponse(responseMsg, ref responseHeaders, ref responseStream); return(ServerProcessing.Complete); }
public ServerProcessing ProcessMessage(IServerChannelSinkStack sinkStack, IMessage requestMsg, ITransportHeaders requestHeaders, Stream requestStream, out IMessage responseMsg, out ITransportHeaders responseHeaders, out Stream responseStream) { // uncompressing the request requestStream = CompressionHelper.getUncompressedStreamCopy(requestStream); // pushing onto stack and forwarding the call sinkStack.Push(this, null); ServerProcessing srvProc = _nextSink.ProcessMessage(sinkStack, requestMsg, requestHeaders, requestStream, out responseMsg, out responseHeaders, out responseStream); // compressing the response responseStream = CompressionHelper.getCompressedStreamCopy(responseStream); // returning status information return(srvProc); }
public ServerProcessing ProcessMessage(IServerChannelSinkStack sinkStack, IMessage requestMessage, ITransportHeaders requestHeaders, Stream requestStream, out IMessage responseMessage, out ITransportHeaders responseHeaders, out Stream responseStream) { requestStream = Zip.Decompress(requestStream); sinkStack.Push(this, null); ServerProcessing processing = this.m_NextSink.ProcessMessage(sinkStack, requestMessage, requestHeaders, requestStream, out responseMessage, out responseHeaders, out responseStream); responseStream = Zip.Compress(responseStream); return processing; }
public ServerProcessing ProcessMessage(IServerChannelSinkStack sinkStack, IMessage requestMsg, ITransportHeaders requestHeaders, Stream requestStream, out IMessage responseMsg, out ITransportHeaders responseHeaders, out Stream responseStream) { bool isEncrypted = false; //checking the headers if (requestHeaders["X-Encrypt"] != null && requestHeaders["X-Encrypt"].Equals("yes")) { isEncrypted = true; byte[] IV = Convert.FromBase64String( (String)requestHeaders["X-EncryptIV"]); // decrypt the request requestStream = EncryptionHelper.ProcessInboundStream( requestStream, _encryptionAlgorithm, _encryptionKey, IV); } // pushing onto stack and forwarding the call, // the flag "isEncrypted" will be used as state sinkStack.Push(this, isEncrypted); ServerProcessing srvProc = _nextSink.ProcessMessage(sinkStack, requestMsg, requestHeaders, requestStream, out responseMsg, out responseHeaders, out responseStream); if (isEncrypted) { // encrypting the response if necessary byte[] IV; responseStream = EncryptionHelper.ProcessOutboundStream(responseStream, _encryptionAlgorithm, _encryptionKey, out IV); responseHeaders["X-Encrypt"] = "yes"; responseHeaders["X-EncryptIV"] = Convert.ToBase64String(IV); } // returning status information return(srvProc); }
public ServerProcessing ProcessMessage( IServerChannelSinkStack sinkStack, IMessage requestMsg, ITransportHeaders requestHeaders, Stream requestStream, out IMessage responseMsg, out ITransportHeaders responseHeaders, out Stream responseStream) { // use presence of SOAPAction header to determine if this is a SOAP // request - if so pass onto next sink in chain string soapAction = (string)requestHeaders["SOAPAction"]; if (soapAction != null) { return(_next.ProcessMessage( sinkStack, requestMsg, requestHeaders, requestStream, out responseMsg, out responseHeaders, out responseStream)); } // for time being assume we have an XML-RPC request (need to improve // this in case there are other non-SOAP formatters in the chain) try { var mthdCall = DeserializeRequest(requestHeaders, requestStream); sinkStack.Push(this, mthdCall); // forward to next sink in chain - pass request stream as null to // indicate that we have deserialized the request _next.ProcessMessage( sinkStack, mthdCall, requestHeaders, null, out responseMsg, out responseHeaders, out responseStream); SerializeResponse(responseMsg, ref responseHeaders, ref responseStream); } catch (Exception ex) { responseMsg = new ReturnMessage(ex, (IMethodCallMessage)requestMsg); responseStream = new MemoryStream(); var fex = new XmlRpcFaultException(0, ex.Message); var serializer = new XmlRpcSerializer(); serializer.SerializeFaultResponse(responseStream, fex); responseHeaders = new TransportHeaders(); } return(ServerProcessing.Complete); }
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 = _nextSink.ProcessMessage(sinkStack, requestMsg, requestHeaders, requestStream, out responseMsg, out responseHeaders, out responseStream); responseHeaders["X-Cache"] = "60"; return(res); }
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); }
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); }
// <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> }
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); }
public ServerProcessing ProcessMessage(IServerChannelSinkStack sinkStack, IMessage requestMsg, ITransportHeaders requestHeaders, Stream requestStream, out IMessage responseMsg, out ITransportHeaders responseHeaders, out Stream responseStream) { LogicalCallContext lcc = (LogicalCallContext)requestMsg.Properties["__CallContext"]; // storing the current priority ThreadPriority oldprio = Thread.CurrentThread.Priority; // check if the logical call context contains "priority" if (lcc != null && lcc.GetData("priority") != null) { // fetch the priorty from the call context ThreadPriority priority = (ThreadPriority)lcc.GetData("priority"); Console.WriteLine(" -> Pre-execution priority change {0} to {1}", oldprio.ToString(), priority.ToString()); // set the priority Thread.CurrentThread.Priority = priority; } // push on the stack and pass the call to the next sink // the old priority will be used as "state" for the response sinkStack.Push(this, oldprio); ServerProcessing spres = _next.ProcessMessage(sinkStack, requestMsg, requestHeaders, requestStream, out responseMsg, out responseHeaders, out responseStream); //restore priority if call is not asynchronous if (spres != ServerProcessing.Async) { if (lcc != null && lcc.GetData("priority") != null) { Console.WriteLine(" -> Post-execution change back to {0}", oldprio); Thread.CurrentThread.Priority = oldprio; } } return(spres); }
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); }
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); } }
public ServerProcessing ProcessMessage(IServerChannelSinkStack sinkStack, IMessage requestMsg, ITransportHeaders requestHeaders, Stream requestStream, out IMessage responseMsg, out ITransportHeaders responseHeaders, out Stream responseStream) { bool isCompressed = false; // decompress the stream if necessary String xcompress = (String)requestHeaders["X-Compress"]; if (xcompress != null && xcompress == "yes") { requestStream = CompressionHelper.GetUncompressedStreamCopy(requestStream); isCompressed = true; } // Pushing onto stack and forwarding the call. // The state object contains true if the request has been compressed, // else false. sinkStack.Push(this, isCompressed); ServerProcessing srvProc = _nextSink.ProcessMessage(sinkStack, requestMsg, requestHeaders, requestStream, out responseMsg, out responseHeaders, out responseStream); if (srvProc == ServerProcessing.Complete) { // compressing the response if necessary if (isCompressed) { responseStream = CompressionHelper.GetCompressedStreamCopy(responseStream); responseHeaders["X-Compress"] = "yes"; } } // returning status information return(srvProc); }
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) { 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; }
/// <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); }
public ServerProcessing ProcessMessage(IServerChannelSinkStack sinkStack, IMessage requestMsg, ITransportHeaders requestHeaders, Stream requestStream, out IMessage responseMsg, out ITransportHeaders responseHeaders, out Stream responseStream) { object handback = ContextUtil.NotifyServerMessage(requestMsg, requestHeaders); sinkStack.Push(this, handback); ServerProcessing result = _nextSink.ProcessMessage(sinkStack, requestMsg, requestHeaders, requestStream, out responseMsg, out responseHeaders, out responseStream); if (result != ServerProcessing.Async) { ContextUtil.NotifyServerMessageResponse(responseMsg, responseHeaders, handback); } return result; }
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; } }
public ServerProcessing ProcessMessage(IServerChannelSinkStack sinkStack, IMessage requestMsg, ITransportHeaders requestHeaders, Stream requestStream, out IMessage responseMsg, out ITransportHeaders responseHeaders, out Stream responseStream) { if (requestHeaders["SOAPAction"] != null) { // pass to next sink if this is a SOAP request with SOAPAction header. return(NextChannelSink.ProcessMessage(sinkStack, requestMsg, requestHeaders, requestStream, out responseMsg, out responseHeaders, out responseStream)); } XmlRpcHttpRequestConfig requestConfig = GetConfig(requestHeaders); try { MethodCall call = DeserializeRequest(requestHeaders, requestStream, requestConfig); sinkStack.Push(this, call); // forward to next sink in chain - pass request stream as null to // indicate that we have deserialized the request NextChannelSink.ProcessMessage(sinkStack, call, requestHeaders, null, out responseMsg, out responseHeaders, out responseStream); SerializeResponse(responseMsg, ref responseHeaders, ref responseStream, requestConfig); } catch (Exception ex) { responseMsg = new ReturnMessage(ex, (IMethodCallMessage)requestMsg); responseStream = new MemoryStream(); XmlRpcResponseSerializer serializer = new XmlRpcResponseSerializer(); XmlRpcResponse faultResponse = new XmlRpcResponse(); faultResponse.Fault = new XmlRpcFault(0, ex.Message); serializer.WriteResponse(responseStream, faultResponse, requestConfig, TypeSerializerFactory); responseHeaders = new TransportHeaders(); responseHeaders["Content-Type"] = "text/xml; charset=\"utf-8\""; } return(ServerProcessing.Complete); }
public ServerProcessing ProcessMessage(IServerChannelSinkStack sinkStack, IMessage requestMsg, ITransportHeaders requestHeaders, Stream requestStream, out IMessage responseMsg, out ITransportHeaders responseHeaders, out Stream responseStream) { if (requestHeaders["SOAPAction"] != null) { // pass to next sink if this is a SOAP request with SOAPAction header. return NextChannelSink.ProcessMessage(sinkStack, requestMsg, requestHeaders, requestStream, out responseMsg, out responseHeaders, out responseStream); } XmlRpcHttpRequestConfig requestConfig = GetConfig(requestHeaders); try { MethodCall call = DeserializeRequest(requestHeaders, requestStream, requestConfig); sinkStack.Push(this, call); // forward to next sink in chain - pass request stream as null to // indicate that we have deserialized the request NextChannelSink.ProcessMessage(sinkStack, call, requestHeaders, null, out responseMsg, out responseHeaders, out responseStream); SerializeResponse(responseMsg, ref responseHeaders, ref responseStream, requestConfig); } catch (Exception ex) { responseMsg = new ReturnMessage(ex, (IMethodCallMessage)requestMsg); responseStream = new MemoryStream(); XmlRpcResponseSerializer serializer = new XmlRpcResponseSerializer(); XmlRpcResponse faultResponse = new XmlRpcResponse(); faultResponse.Fault = new XmlRpcFault(0, ex.Message); serializer.WriteResponse(responseStream, faultResponse, requestConfig, TypeSerializerFactory); responseHeaders = new TransportHeaders(); responseHeaders["Content-Type"] = "text/xml; charset=\"utf-8\""; } return ServerProcessing.Complete; }
/// <summary> /// Processes the message. /// </summary> /// <param name="sinkStack">The sink stack.</param> /// <param name="requestmessage">The request message.</param> /// <param name="requestHeaders">The request headers.</param> /// <param name="requestStream">The request stream.</param> /// <param name="responseMessage">The response message.</param> /// <param name="responseHeaders">The response headers.</param> /// <param name="responseStream">The response stream.</param> /// <returns></returns> public ServerProcessing ProcessMessage(IServerChannelSinkStack sinkStack, IMessage requestmessage, ITransportHeaders requestHeaders, System.IO.Stream requestStream, out IMessage responseMessage, out ITransportHeaders responseHeaders, out System.IO.Stream responseStream) { //get the client's ip address, and put it in the call context. This valuewill be //extracted later so we can determine the actual address of the client. try { IPAddress ipAddr = (IPAddress)requestHeaders[CommonTransportKeys.IPAddress]; CallContext.SetData("ClientIP", ipAddr); //GlobalDataStore.Logger.Debug(string.Format("Messagesink retrieved IP: {0}",ipAddr.ToString())); } catch (Exception) { //do nothing } //pushing onto stack and forwarding the call sinkStack.Push(this, null); ServerProcessing srvProc = _NextSink.ProcessMessage( sinkStack, requestmessage, requestHeaders, requestStream, out responseMessage, out responseHeaders, out responseStream); if (srvProc == ServerProcessing.Complete) { //TODO - implement post processing } return(srvProc); }
public ServerProcessing ProcessMessage( IServerChannelSinkStack stack, IMessage requestMsg, ITransportHeaders requestHeaders, Stream requestStream, out IMessage responseMsg, out ITransportHeaders responseHeaders, out Stream responseStream ) { stack.Push(this, null); #region CallContext if (requestHeaders[ChannelSinkCallContext.ChannelSinkCallContextHeader] != null) { string contextInfo = (string)(requestHeaders[ChannelSinkCallContext.ChannelSinkCallContextHeader]); ChannelSinkCallContext context = ChannelSinkCallContext.DeserializeCallContextFromString(contextInfo); Console.WriteLine(System.DateTime.Now.ToLocalTime() + " User : [" + context.UserName + "] is calling a request ..."); } #endregion ServerProcessing result = _nextSink.ProcessMessage(stack, requestMsg, requestHeaders, requestStream, out responseMsg, out responseHeaders, out responseStream); return(result); }
public ServerProcessing ProcessMessage(IServerChannelSinkStack sinkStack, IMessage requestMsg, ITransportHeaders requestHeaders, Stream requestStream, out IMessage responseMsg, out ITransportHeaders responseHeaders, out Stream responseStream) { // process request object state = null; string ClientGuid = ProcessRequest(requestHeaders, ref requestStream, ref state); sinkStack.Push(this, state); ServerProcessing processing = FNextSink.ProcessMessage(sinkStack, requestMsg, requestHeaders, requestStream, out responseMsg, out responseHeaders, out responseStream); if (processing == ServerProcessing.Complete) { ProcessResponse(responseHeaders, ref responseStream, state, ClientGuid); } return(processing); }
/// <summary> /// ProcessMessage decrypts the data stream and forward it the target /// server object and encrypts the return value /// </summary> /// <param name="sinkStack">channel sink object</param> /// <param name="requestMsg">IMessage object</param> /// <param name="transportHeaders">transport header object</param> /// <param name="targetStream">requrest stream</param> /// <param name="responseMsg">output parameters containing response message</param> /// <param name="responseHeaders">output parameter containing the response header</param> /// <param name="responseStream">output parameter containing the response stream</param> /// <returns></returns> public ServerProcessing ProcessMessage( IServerChannelSinkStack sinkStack, IMessage requestMsg, ITransportHeaders transportHeaders, Stream targetStream, out IMessage responseMsg, out ITransportHeaders responseHeaders, out Stream responseStream) { //extract the identity information from the header string identity = transportHeaders["Identity"].ToString(); LocalDataStoreSlot dataSlot = null; //create an thread data slot dataSlot = Thread.GetNamedDataSlot("Identity"); //add the identity informatioin to the data slot on the thread so that //server object can determine who made the request. Thread.SetData(dataSlot, identity); // Push this onto the sink stack sinkStack.Push(this, null); //decrypt the request stream Stream decryptedStream = helper.DecryptStream(identity, sinkType, transportHeaders, targetStream); ServerProcessing processingResult; //pass the decrypted request to next sink of the chain processingResult = next.ProcessMessage( sinkStack, requestMsg, transportHeaders, decryptedStream, out responseMsg, out responseHeaders, out responseStream); //encrypte the response stream. Stream encryptedStream = helper.EncryptStream(identity, sinkType, responseHeaders, responseStream); string serverIdentity = cc.GetServerSinkIndentity(); responseHeaders["Identity"] = serverIdentity; responseStream = encryptedStream; return(processingResult); }
public ServerProcessing ProcessMessage(IServerChannelSinkStack sinkStack, IMessage requestMsg, ITransportHeaders requestHeaders, Stream requestStream, out IMessage responseMsg, out ITransportHeaders responseHeaders, out Stream responseStream) { // проверяем, задано ли имя серверного хоста или его адрес _serverHostNameOrIp = requestHeaders["serverHostNameOrIp"]; if (_serverHostNameOrIp != null) { // помещаем его в контекст вызова CallContext.SetData("serverHostNameOrIp", _serverHostNameOrIp); // протоколируем if (_eventLink != null) { _eventLink.Post(_eventSource, String.Format("Имя или IP-адрес сервера ЗАДАНО: [{0}]", _serverHostNameOrIp)); } } else { // очишаем значение, оставшееся от предыдущих вызовов CallContext.FreeNamedDataSlot("serverHostNameOrIp"); // протоколируем if (_eventLink != null) { _eventLink.Post(_eventSource, EventType.Warning, "Имя или IP-адрес сервера НЕ задано"); } } // перенаправляем обработку сообщения следующему приемнику в цепи sinkStack.Push(this, null); ServerProcessing status = _nextSink.ProcessMessage(sinkStack, requestMsg, requestHeaders, requestStream, out responseMsg, out responseHeaders, out responseStream); return status; }
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) { // 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); }
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) { // process request object state = null; string ClientGuid = ProcessRequest(requestHeaders, ref requestStream, ref state); sinkStack.Push(this, state); ServerProcessing processing = FNextSink.ProcessMessage(sinkStack, requestMsg, requestHeaders, requestStream, out responseMsg, out responseHeaders, out responseStream); if (processing == ServerProcessing.Complete) { ProcessResponse(responseHeaders, ref responseStream, state, ClientGuid); } return processing; }
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; }
public ServerProcessing ProcessMessage( IServerChannelSinkStack sinkStack_in, IMessage requestMsg_in, ITransportHeaders requestHeaders_in, Stream requestStream_in, out IMessage responseMsg_out, out ITransportHeaders responseHeaders_out, out Stream responseStream_out ) { #if DEBUG Console.WriteLine("encryption sink: ProcessMessage"); #endif bool _isEncrypted = false; if (isHeaderEncrypted(requestHeaders_in)) { #region decrypt... requestStream_in = EncryptionHelper.Decrypt( requestStream_in, true, keyspath_, (string)requestHeaders_in[EncryptionHelper.X_CLIENTID] ); _isEncrypted = true; #endregion } else { if (mustdo_) { throw new Exception("\n\n\t\tyour activity is being logged!\n\n\t\tun-encrypted communications not allowed!\n\n"); } } sinkStack_in.Push( this, new StateStruct( _isEncrypted, _isEncrypted ? (string)requestHeaders_in[EncryptionHelper.X_CLIENTID] : "" ) ); ServerProcessing _output = nextchannelsink_.ProcessMessage( sinkStack_in, requestMsg_in, requestHeaders_in, requestStream_in, out responseMsg_out, out responseHeaders_out, out responseStream_out ); if (_output == ServerProcessing.Complete) { if (_isEncrypted) { #region encrypt... responseHeaders_out[EncryptionHelper.X_ENCRYPT] = "1"; responseStream_out = EncryptionHelper.Encrypt( responseStream_out, true, keyspath_, (string)requestHeaders_in[EncryptionHelper.X_CLIENTID] ); #endregion } //// previously checked! //else { // if (mustdo_) { // throw new Exception("\n\n\t\tyour activity is being logged!\n\n\t\tun-encrypted communications not allowed!\n\n"); // } //} } return _output; }
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; }
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; }
/// <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; }
ServerProcessing IServerChannelSink.ProcessMessage(IServerChannelSinkStack sinkStack, IMessage requestMsg, ITransportHeaders requestHeaders, System.IO.Stream requestStream, out IMessage responseMsg, out ITransportHeaders responseHeaders, out System.IO.Stream responseStream) { System.Net.IPAddress address = System.Net.IPAddress.Parse(requestHeaders[CommonTransportKeys.IPAddress].ToString()); if (!IsTrustedIP(address)) { Logger.Error("Client connection refused from " + address.ToString()); throw new SC.Interfaces.SCException("Connection refused from address " + address.ToString()); } if (ServerAuthenticationHelper.IsChallengeRequest(requestHeaders)) { Logger.Info("Client connection accepted from " + address.ToString()); ClientContext context = new ClientContext(); responseHeaders = new TransportHeaders(); responseStream = new System.IO.MemoryStream(); context.AuthHelper.Challenge(responseHeaders); responseMsg = requestMsg; lock (contexts) contexts[context.AuthHelper.Ticket] = context; return ServerProcessing.Complete; } if (!AuthenticationHelper.HasValidTicket(requestHeaders)) throw new SC.Interfaces.SCException("Protocol violation: No ticket"); Guid ticket = AuthenticationHelper.GetTicket(requestHeaders); ClientContext ctxt = null; lock (contexts) { if (contexts.ContainsKey(ticket)) ctxt = contexts[ticket]; } if (ctxt == null) { throw new SC.Interfaces.SCException("Protocol violation: issue a challenge request first."); } else if (ctxt.SessionExpired) { Logger.Info("Session for address " + address.ToString() + " expired."); throw new SC.Interfaces.SessionExpiredException(); } ctxt.AuthHelper.Authenticate(requestHeaders, ref requestStream); ServerProcessing result = nextSink.ProcessMessage(sinkStack, requestMsg, requestHeaders, requestStream, out responseMsg, out responseHeaders, out responseStream); if (result == ServerProcessing.Async) { sinkStack.Push(this, #if DEBUG System.Threading.Thread.CurrentThread #else null #endif ); } else ServerAuthenticationHelper.UnAuthenticate(); return result; }
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
/// <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); } // 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; }
} // 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) { 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</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) { // 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> /// 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 ) { // use presence of SOAPAction header to determine if this is a SOAP // request - if so pass onto next sink in chain string soapAction = (string) requestHeaders["SOAPAction"]; if (soapAction != null) { return m_next.ProcessMessage(sinkStack, requestMsg, requestHeaders, requestStream, out responseMsg, out responseHeaders, out responseStream); } // for time being assume we have an XML-RPC request (need to improve // this in case there are other non-SOAP formatters in the chain) try { MethodCall mthdCall = DeserializeRequest(requestHeaders, requestStream); sinkStack.Push(this, mthdCall); // forward to next sink in chain - pass request stream as null to // indicate that we have deserialized the request m_next.ProcessMessage(sinkStack, mthdCall, requestHeaders, null, out responseMsg, out responseHeaders, out responseStream); SerializeResponse(responseMsg, ref responseHeaders, ref responseStream); } catch (Exception ex) { responseMsg = new ReturnMessage(ex, (IMethodCallMessage)requestMsg); responseStream = new MemoryStream(); XmlRpcFaultException fex = new XmlRpcFaultException(0, ex.Message); XmlRpcSerializer serializer = new XmlRpcSerializer(); serializer.SerializeFaultResponse(responseStream, (XmlRpcFaultException)fex); responseHeaders = new TransportHeaders(); } return ServerProcessing.Complete; }
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) { 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) { 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
public ServerProcessing ProcessMessage( IServerChannelSinkStack sinkStack_in, IMessage requestMsg_in, ITransportHeaders requestHeaders_in, Stream requestStream_in, out IMessage responseMsg_out, out ITransportHeaders responseHeaders_out, out Stream responseStream_out ) { #if DEBUG Console.WriteLine("compression sink: ProcessMessage..."); #endif bool _isCompressed = false; if (isHeaderCompressed_(requestHeaders_in)) { #region uncompress... requestStream_in = CompressionHelper.GetUncompressedStreamCopy( requestStream_in ); _isCompressed = true; #endregion } else { if (this.mustdo_) { throw new Exception("\n\n\t\tyour activity is being logged!\n\n\t\tun-compressed communications not allowed!\n\n"); } } sinkStack_in.Push( this, _isCompressed ); ServerProcessing _output = this.nextchannelsink_.ProcessMessage( sinkStack_in, requestMsg_in, requestHeaders_in, requestStream_in, out responseMsg_out, out responseHeaders_out, out responseStream_out ); if (_output == ServerProcessing.Complete) { if (_isCompressed) { #region compress... responseHeaders_out[CompressionHelper.X_COMPRESS] = "1"; responseStream_out = CompressionHelper.GetCompressedStreamCopy( responseStream_out ); #endregion } } //// previously checked! //else { // if (mustdo_) { // throw new Exception("\n\n\t\tyour activity is being logged!\n\n\t\tun-compressed communications not allowed!\n\n"); // } //} return _output; }
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
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; }