} // DispatchExceptionOrRetry // called from StartRequest private static void ProcessGetRequestStreamCompletion(IAsyncResult iar) { // We've just received a request stream. AsyncHttpClientRequestState asyncRequestState = (AsyncHttpClientRequestState)iar.AsyncState; try { HttpWebRequest httpWebRequest = asyncRequestState.WebRequest; Stream sourceRequestStream = asyncRequestState.RequestStream; Stream webRequestStream = httpWebRequest.EndGetRequestStream(iar); StreamHelper.BeginAsyncCopyStream( sourceRequestStream, webRequestStream, false, true, // sync read, async write false, true, // leave source open, close target s_processAsyncCopyRequestStreamCompletionCallback, asyncRequestState); } catch (Exception e) { asyncRequestState.RetryOrDispatchException(e); } catch { asyncRequestState.RetryOrDispatchException(new Exception(CoreChannel.GetResourceString("Remoting_nonClsCompliantException"))); } } // ProcessGetRequestStreamCompletion
} // SendContinue public void SendResponse(Stream httpContentStream, String statusCode, String reasonPhrase, ITransportHeaders headers) { if (_responseStream != null) { _responseStream.Close(); if (_responseStream != httpContentStream) { throw new RemotingException( CoreChannel.GetResourceString("Remoting_Http_WrongResponseStream")); } // we are done with the response stream _responseStream = null; } else { if (headers == null) { headers = new TransportHeaders(); } String serverHeader = (String)headers["Server"]; if (serverHeader != null) { serverHeader = HttpServerTransportSink.ServerHeader + ", " + serverHeader; } else { serverHeader = HttpServerTransportSink.ServerHeader; } headers["Server"] = serverHeader; // Add length to response headers if necessary if (!AllowChunkedResponse && (httpContentStream != null)) { headers["Content-Length"] = httpContentStream.Length.ToString(CultureInfo.InvariantCulture); } else if (httpContentStream == null) { headers["Content-Length"] = "0"; } GetResponseStream(statusCode, reasonPhrase, headers); // write HTTP content if (httpContentStream != null) { StreamHelper.CopyStream(httpContentStream, _responseStream); _responseStream.Close(); httpContentStream.Close(); } // we are done with the response stream _responseStream = null; } } // SendResponse
internal TcpClientTransportSink(String channelURI, TcpClientChannel channel) { String objectURI; _channel = channel; String simpleChannelUri = TcpChannelHelper.ParseURL(channelURI, out objectURI); ClientSocketCache = new SocketCache(new SocketHandlerFactory(this.CreateSocketHandler), _socketCachePolicy, _socketCacheTimeout); // extract machine name and port Uri uri = new Uri(simpleChannelUri); if (uri.IsDefaultPort) { // If there is no colon, then there is no port number. throw new RemotingException( String.Format( CultureInfo.CurrentCulture, CoreChannel.GetResourceString( "Remoting_Tcp_UrlMustHavePort"), channelURI)); } m_machineName = uri.Host; m_port = uri.Port; _machineAndPort = m_machineName + ":" + m_port; } // TcpClientTransportSink
internal TcpClientTransportSink(String channelURI) { String objectURI; String simpleChannelUri = TcpChannelHelper.ParseURL(channelURI, out objectURI); // extract machine name and port int start = simpleChannelUri.IndexOf("://"); start += 3; int index = simpleChannelUri.IndexOf(':', start); if (index == -1) { // If there is no colon, then there is no port number. throw new RemotingException( String.Format( CoreChannel.GetResourceString( "Remoting_Tcp_UrlMustHavePort"), channelURI)); } m_machineName = simpleChannelUri.Substring(start, index - start); m_port = Int32.Parse(simpleChannelUri.Substring(index + 1)); _machineAndPort = m_machineName + ":" + m_port; } // TcpClientTransportSink
// constructor used by config file /// <include file='doc\TcpClientChannel.uex' path='docs/doc[@for="TcpClientChannel.TcpClientChannel2"]/*' /> public TcpClientChannel(IDictionary properties, IClientChannelSinkProvider sinkProvider) { if (properties != null) { foreach (DictionaryEntry entry in properties) { switch ((String)entry.Key) { case "name": _channelName = (String)entry.Value; break; case "priority": _channelPriority = Convert.ToInt32(entry.Value); break; default: throw new ArgumentException( String.Format( CoreChannel.GetResourceString( "Remoting_Channels_BadCtorArgs"), entry.Key)); } } } _sinkProvider = sinkProvider; SetupChannel(); } // TcpClientChannel
private void SetupChannel() { if (this.authSet && !this._secure) { throw new RemotingException(CoreChannel.GetResourceString("Remoting_Tcp_AuthenticationConfigServer")); } this._channelData = new ChannelDataStore(null); if (this._port > 0) { this._channelData.ChannelUris = new string[] { this.GetChannelUri() }; } if (this._sinkProvider == null) { this._sinkProvider = this.CreateDefaultServerProviderChain(); } CoreChannel.CollectChannelDataFromServerSinkProviders(this._channelData, this._sinkProvider); IServerChannelSink nextSink = ChannelServices.CreateServerChannelSinkChain(this._sinkProvider, this); this._transportSink = new TcpServerTransportSink(nextSink, this._impersonate); this._acceptSocketCallback = new AsyncCallback(this.AcceptSocketCallbackHelper); if (this._port >= 0) { this._tcpListener = new ExclusiveTcpListener(this._bindToAddr, this._port); this.StartListening(null); } }
} // CreateSocketHandler #if !FEATURE_PAL private Stream CreateAuthenticatedStream(Stream netStream, String machinePortAndSid) { //Check for explicitly set userName, and authenticate using it NetworkCredential credentials = null; NegotiateStream negoClient = null; if (_securityUserName != null) { credentials = new NetworkCredential(_securityUserName, _securityPassword, _securityDomain); } //else use default Credentials else { credentials = (NetworkCredential)CredentialCache.DefaultCredentials; } try { negoClient = new NegotiateStream(netStream); negoClient.AuthenticateAsClient(credentials, _spn, _protectionLevel, _tokenImpersonationLevel); } catch (IOException e) { throw new RemotingException( String.Format(CultureInfo.CurrentCulture, CoreChannel.GetResourceString("Remoting_Tcp_AuthenticationFailed")), e); } return(negoClient); }
private static string SetupUrlBashingForIisIfNecessaryWorker(string hostName) { string str = null; HttpContext current = HttpContext.Current; if (current == null) { return str; } HttpRequest request = current.Request; string str2 = null; if (request.IsSecureConnection) { str2 = "https"; } else { str2 = "http"; } int port = current.Request.Url.Port; StringBuilder builder = new StringBuilder(100); builder.Append(str2); builder.Append("://"); if (hostName != null) { builder.Append(hostName); } else { builder.Append(CoreChannel.GetMachineName()); } builder.Append(":"); builder.Append(port.ToString(CultureInfo.InvariantCulture)); return builder.ToString(); }
} // ProcessGetResponseCompletion // called from ProcessGetResponseCompletion private static void ProcessAsyncCopyResponseStreamCompletion(IAsyncResult iar) { // We've just finished copying the network response stream into a memory stream. AsyncHttpClientRequestState asyncRequestState = (AsyncHttpClientRequestState)iar.AsyncState; try { StreamHelper.EndAsyncCopyStream(iar); HttpWebResponse webResponse = asyncRequestState.WebResponse; Stream responseStream = asyncRequestState.ActualResponseStream; ITransportHeaders responseHeaders = CollectResponseHeaders(webResponse); // call down the sink chain asyncRequestState.SinkStack.AsyncProcessResponse(responseHeaders, responseStream); } catch (Exception e) { asyncRequestState.SinkStack.DispatchException(e); } catch { asyncRequestState.SinkStack.DispatchException(new Exception(CoreChannel.GetResourceString("Remoting_nonClsCompliantException"))); } } // ProcessAsyncResponseStreamCompletion
public override int Read(byte[] buffer, int offset, int count) { int num = 0; while (!this._bFoundEnd && (count > 0)) { if (this._bytesLeft == 0) { this._bytesLeft = this._inputStream.ReadInt32(); if (this._bytesLeft == 0) { this.ReadTrailer(); this._bFoundEnd = true; } } if (!this._bFoundEnd) { int num2 = Math.Min(this._bytesLeft, count); int num3 = this._inputStream.Read(buffer, offset, num2); if (num3 <= 0) { throw new RemotingException(CoreChannel.GetResourceString("Remoting_Tcp_ChunkedEncodingError")); } this._bytesLeft -= num3; count -= num3; offset += num3; num += num3; if (this._bytesLeft == 0) { this.ReadTrailer(); } } } return(num); }
} // OnInputStreamClosed public BaseTransportHeaders ReadHeaders() { BaseTransportHeaders headers = new BaseTransportHeaders(); UInt16 operation; ReadVersionAndOperation(out operation); // At this point, we're always expecting a Reply, so check for that. if (operation != TcpOperations.Reply) { throw new RemotingException( String.Format( CultureInfo.CurrentCulture, CoreChannel.GetResourceString("Remoting_Tcp_ExpectingReplyOp"), operation.ToString(CultureInfo.CurrentCulture))); } // content length must come next (may be chunked or a specific length) ReadContentLength(out _bChunked, out _contentLength); // read to end of headers ReadToEndOfHeaders(headers); return(headers); } // ReadHeaders
public void ProcessMessage(IMessage msg, ITransportHeaders requestHeaders, Stream requestStream, out ITransportHeaders responseHeaders, out Stream responseStream) { InternalRemotingServices.RemotingTrace("IpcClientChannel::ProcessMessage"); IpcPort port = null; // the call to SendRequest can block a func eval, so we want to notify the debugger that we're // about to call a blocking operation. System.Diagnostics.Debugger.NotifyOfCrossThreadDependency(); // The authentication config entries are only valid if secure is true if (authSet && !_channel.IsSecured) { throw new RemotingException(CoreChannel.GetResourceString( "Remoting_Ipc_AuthenticationConfig")); } port = portCache.GetConnection(_portName, _channel.IsSecured, _tokenImpersonationLevel, _timeout); IMethodCallMessage mcm = (IMethodCallMessage)msg; int requestLength = (int)requestStream.Length; Stream ipcStream = new PipeStream(port); IpcClientHandler handler = new IpcClientHandler(port, ipcStream, this); handler.SendRequest(msg, requestHeaders, requestStream); responseHeaders = handler.ReadHeaders(); responseStream = handler.GetResponseStream(); // The client port will be returned to the cache // when the response stream is closed. } // ProcessMessage
internal static IpcPort Create(string portName, CommonSecurityDescriptor securityDescriptor, bool exclusive) { SECURITY_ATTRIBUTES security_attributes; if (Environment.OSVersion.Platform != PlatformID.Win32NT) { throw new NotSupportedException(CoreChannel.GetResourceString("Remoting_Ipc_Win9x")); } PipeHandle handle = null; string lpName = @"\\.\pipe\" + portName; security_attributes = new SECURITY_ATTRIBUTES { nLength = Marshal.SizeOf(security_attributes) }; byte[] binaryForm = null; if (securityDescriptor == null) { securityDescriptor = s_securityDescriptor; } binaryForm = new byte[securityDescriptor.BinaryLength]; securityDescriptor.GetBinaryForm(binaryForm, 0); GCHandle handle2 = GCHandle.Alloc(binaryForm, GCHandleType.Pinned); security_attributes.lpSecurityDescriptor = Marshal.UnsafeAddrOfPinnedArrayElement(binaryForm, 0); handle = NativePipe.CreateNamedPipe(lpName, (uint)(0x40000003 | (exclusive ? 0x80000 : 0)), 0, 0xff, 0x2000, 0x2000, uint.MaxValue, security_attributes); handle2.Free(); if (handle.Handle.ToInt32() == -1) { int errorCode = Marshal.GetLastWin32Error(); throw new RemotingException(string.Format(CultureInfo.CurrentCulture, CoreChannel.GetResourceString("Remoting_Ipc_CreateIpcFailed"), new object[] { GetMessage(errorCode) })); } return(new IpcPort(portName, handle)); }
} // HttpClientChannel private void SetupChannel() { if (_sinkProvider != null) { CoreChannel.AppendProviderToClientProviderChain( _sinkProvider, new HttpClientTransportSinkProvider()); } else { _sinkProvider = CreateDefaultClientProviderChain(); } // proxy might have been created by setting proxyname/port in constructor with dictionary if (_proxyObject == null) { // In this case, try to use the default proxy settings. WebProxy defaultProxy = WebProxy.GetDefaultProxy(); if (defaultProxy != null) { Uri address = defaultProxy.Address; if (address != null) { _proxyName = address.Host; _proxyPort = address.Port; } } UpdateProxy(); } } // SetupChannel()
private void SetupChannel() { this._channelData = new ChannelDataStore(null); if (this._port > 0) { string channelUri = this.GetChannelUri(); this._channelData.ChannelUris = new string[] { channelUri }; this._wantsToListen = false; } if (this._sinkProvider == null) { this._sinkProvider = this.CreateDefaultServerProviderChain(); } CoreChannel.CollectChannelDataFromServerSinkProviders(this._channelData, this._sinkProvider); this._sinkChain = ChannelServices.CreateServerChannelSinkChain(this._sinkProvider, this); this._transportSink = new HttpServerTransportSink(this._sinkChain); base.SinksWithProperties = this._sinkChain; if (this._port >= 0) { this._tcpListener = new ExclusiveTcpListener(this._bindToAddr, this._port); ThreadStart start = new ThreadStart(this.Listen); this._listenerThread = new Thread(start); this._listenerThread.IsBackground = true; this.StartListening(null); } }
private void SetupMachineName() { if (this._forcedMachineName != null) { this._machineName = CoreChannel.DecodeMachineName(this._forcedMachineName); } else if (!this._bUseIpAddress) { this._machineName = CoreChannel.GetMachineName(); } else { if ((this._bindToAddr == IPAddress.Any) || (this._bindToAddr == IPAddress.IPv6Any)) { this._machineName = CoreChannel.GetMachineIp(); } else { this._machineName = this._bindToAddr.ToString(); } if (this._bindToAddr.AddressFamily == AddressFamily.InterNetworkV6) { this._machineName = "[" + this._machineName + "]"; } } }
private void ReadAndMatchPreamble() { if (!base.ReadAndMatchFourBytes(s_protocolPreamble)) { throw new RemotingException(CoreChannel.GetResourceString("Remoting_Tcp_ExpectingPreamble")); } }
/// <include file='doc\HttpServerChannel.uex' path='docs/doc[@for="HttpServerChannel.AddHookChannelUri"]/*' /> public void AddHookChannelUri(String channelUri) { if (_channelData.ChannelUris != null) { throw new RemotingException( CoreChannel.GetResourceString("Remoting_Http_LimitListenerOfOne")); } else { // replace machine name with explicitly configured // machine name or ip address if necessary if (_forcedMachineName != null) { channelUri = HttpChannelHelper.ReplaceMachineNameWithThisString(channelUri, _forcedMachineName); } else if (_bUseIpAddress) { channelUri = HttpChannelHelper.ReplaceMachineNameWithThisString(channelUri, CoreChannel.GetMachineIp()); } _channelData.ChannelUris = new String[] { channelUri }; _wantsToListen = false; _bHooked = true; } } // AddHookChannelUri
} // WriteCustomHeader protected String ReadCountedString() { // strings are formatted as follows // [string format (1-byte)][encoded-size (int32)][string value (encoded-size length in bytes)] byte strFormat = (byte)ReadByte(); int strDataSize = ReadInt32(); if (strDataSize > 0) { byte[] data = new byte[strDataSize]; // SocketHander::Read waits until it reads all requested data Read(data, 0, strDataSize); switch (strFormat) { case TcpStringFormat.Unicode: return(Encoding.Unicode.GetString(data)); case TcpStringFormat.UTF8: return(Encoding.UTF8.GetString(data)); default: throw new RemotingException( String.Format( CultureInfo.CurrentCulture, CoreChannel.GetResourceString("Remoting_Tcp_UnrecognizedStringFormat"), strFormat.ToString(CultureInfo.CurrentCulture))); } } else { return(null); } } // ReadCountedString
public virtual IMessageSink CreateMessageSink(string url, object remoteChannelData, out string objectURI) { objectURI = null; string str = null; if (url != null) { str = this.Parse(url, out objectURI); } else if ((remoteChannelData != null) && (remoteChannelData is IChannelDataStore)) { IChannelDataStore store = (IChannelDataStore)remoteChannelData; if (this.Parse(store.ChannelUris[0], out objectURI) != null) { str = store.ChannelUris[0]; } } if (str == null) { return(null); } if (url == null) { url = str; } IClientChannelSink sink = this._sinkProvider.CreateSink(this, url, remoteChannelData); IMessageSink sink2 = sink as IMessageSink; if ((sink != null) && (sink2 == null)) { throw new RemotingException(CoreChannel.GetResourceString("Remoting_Channels_ChannelSinkNotMsgSink")); } return(sink2); }
private void SetupMachineName() { if (_forcedMachineName != null) { // an explicitly configured machine name was used _machineName = CoreChannel.DecodeMachineName(_forcedMachineName); } else { if (!_bUseIpAddress) { _machineName = CoreChannel.GetMachineName(); } else { if (_bindToAddr == IPAddress.Any || _bindToAddr == IPAddress.IPv6Any) { _machineName = CoreChannel.GetMachineIp(); } else { _machineName = _bindToAddr.ToString(); } // Add [] around the ipadress for IPv6 if (_bindToAddr.AddressFamily == AddressFamily.InterNetworkV6) { _machineName = "[" + _machineName + "]"; } } } } // SetupMachineName
private WindowsIdentity Authenticate(ref Stream netStream, TcpServerSocketHandler streamManager) { // Use the identity for impersonation etc. NegotiateStream negoServer = null; try { negoServer = new NegotiateStream(netStream); // Block for authentication request TokenImpersonationLevel impLevel = TokenImpersonationLevel.Identification; if (_impersonate) { impLevel = TokenImpersonationLevel.Impersonation; } negoServer.AuthenticateAsServer((NetworkCredential)CredentialCache.DefaultCredentials, _protectionLevel, impLevel); netStream = negoServer; return((WindowsIdentity)negoServer.RemoteIdentity); } catch { streamManager.SendErrorResponse( String.Format(CultureInfo.CurrentCulture, CoreChannel.GetResourceString("Remoting_Tcp_ServerAuthenticationFailed")), false); if (negoServer != null) { negoServer.Close(); } throw; } }
} // AsyncProcessRequest private static void ProcessResponseException(WebException webException, out HttpWebResponse response) { // if a timeout occurred throw a RemotingTimeoutException if (webException.Status == WebExceptionStatus.Timeout) { throw new RemotingTimeoutException( CoreChannel.GetResourceString( "Remoting_Channels_RequestTimedOut"), webException); } response = webException.Response as HttpWebResponse; if ((response == null)) { throw webException; } // if server error (500-599 continue with processing the soap fault); // otherwise, rethrow the exception. int statusCode = (int)(response.StatusCode); if ((statusCode < 500) || (statusCode > 599)) { throw webException; } } // ProcessResponseException
public SdlChannelSinkProvider(IDictionary properties, ICollection providerData) { this._bMetadataEnabled = true; if (properties != null) { foreach (DictionaryEntry entry in properties) { string key = (string)entry.Key; if (key == null) { goto Label_0089; } if (!(key == "remoteApplicationMetadataEnabled")) { if (key == "metadataEnabled") { goto Label_0070; } goto Label_0089; } this._bRemoteApplicationMetadataEnabled = Convert.ToBoolean(entry.Value, CultureInfo.InvariantCulture); continue; Label_0070: this._bMetadataEnabled = Convert.ToBoolean(entry.Value, CultureInfo.InvariantCulture); continue; Label_0089: CoreChannel.ReportUnknownProviderConfigProperty(base.GetType().Name, (string)entry.Key); } } }
bool IsReceiver(ISmtpMessage smtpMessage, ref ISmtpOnArrival receiver) { bool fReceive = false; // Get the one and only receiver //BCLDebug.Assert(m_receiverGuid != Guid.Empty, "m_receiverGuid != Guid.Empty"); receiver = (ISmtpOnArrival)s_receiverTable[m_mailboxName]; if (null == receiver) { throw new Exception(CoreChannel.GetResourceString("Remoting_NoReceiverRegistered")); } if (receiver == this) { String mailbox = smtpMessage.To; // Only process those messages which are addressed to us InternalRemotingServices.RemotingTrace("mailbox " + m_mailboxName + " receiver " + mailbox); if ((null != m_mailboxName) && (-1 != CultureInfo.CurrentCulture.CompareInfo.IndexOf(mailbox, m_mailboxName, CompareOptions.IgnoreCase))) { InternalRemotingServices.RemotingTrace("Mailboxes match"); fReceive = true; } else { // We don't do anything with messages not addressed to us receiver = null; } } return(fReceive); }
} // HttpServerChannel private void SetupMachineName() { if (_forcedMachineName != null) { // an explicitly configured machine name was used _machineName = CoreChannel.DecodeMachineName(_forcedMachineName); } else { if (!_bUseIpAddress) { _machineName = CoreChannel.GetMachineName(); } else { if (_bindToAddr == IPAddress.Any) { _machineName = CoreChannel.GetMachineIp(); } else { _machineName = _bindToAddr.ToString(); } } } } // SetupMachineName
private string GetSid() { if (this._connectionGroupName != null) { return(this._connectionGroupName); } return(CoreChannel.GetCurrentSidString()); }
private string GenerateFaultString(HttpContext context, Exception e) { if (!CustomErrorsEnabled(context)) { return(e.ToString()); } return(CoreChannel.GetResourceString("Remoting_InternalError")); }
private string GenerateFaultString(Exception e) { if (!base.CustomErrorsEnabled()) { return(e.ToString()); } return(CoreChannel.GetResourceString("Remoting_InternalError")); }
} // TcpChannel /// <include file='doc\CombinedTcpChannel.uex' path='docs/doc[@for="TcpChannel.TcpChannel2"]/*' /> public TcpChannel(IDictionary properties, IClientChannelSinkProvider clientSinkProvider, IServerChannelSinkProvider serverSinkProvider) { Hashtable clientData = new Hashtable(); Hashtable serverData = new Hashtable(); bool portFound = false; // divide properties up for respective channels if (properties != null) { foreach (DictionaryEntry entry in properties) { switch ((String)entry.Key) { // general channel properties case "name": _channelName = (String)entry.Value; break; case "priority": _channelPriority = Convert.ToInt32((String)entry.Value); break; // client properties (none yet) // server properties case "bindTo": serverData["bindTo"] = entry.Value; break; case "machineName": serverData["machineName"] = entry.Value; break; case "port": { serverData["port"] = entry.Value; portFound = true; break; } case "rejectRemoteRequests": serverData["rejectRemoteRequests"] = entry.Value; break; case "suppressChannelData": serverData["suppressChannelData"] = entry.Value; break; case "useIpAddress": serverData["useIpAddress"] = entry.Value; break; default: throw new ArgumentException( String.Format( CoreChannel.GetResourceString( "Remoting_Channels_BadCtorArgs"), entry.Key)); } } } _clientChannel = new TcpClientChannel(clientData, clientSinkProvider); if (portFound) { _serverChannel = new TcpServerChannel(serverData, serverSinkProvider); } } // TcpChannel