/// <include file='doc\IPAddress.uex' path='docs/doc[@for="IPAddress.Parse"]/*' /> /// <devdoc> /// <para>Converts an IP address string to an <see cref='System.Net.IPAddress'/> /// instance.</para> /// </devdoc> public static IPAddress Parse(string ipString) { if (ipString == null) { throw new ArgumentNullException("ipString"); } // // IPv6 Changes: Detect probable IPv6 addresses and use separate // parse method. // if (ipString.IndexOf(':') != -1) { // // If the address string contains the colon character // then it can only be an IPv6 address. Use a separate // parse method to unpick it all. Note: we don't support // port specification at the end of address and so can // make this decision. // // We need to make sure that Socket is initialized for this // call ! // bool ipv6 = Socket.SupportsIPv6; SocketAddress saddr = new SocketAddress(AddressFamily.InterNetworkV6, 28); int errorCode = UnsafeNclNativeMethods.OSSOCK.WSAStringToAddress( ipString, AddressFamily.InterNetworkV6, IntPtr.Zero, saddr.m_Buffer, ref saddr.m_Size); if (errorCode != SocketErrors.Success) { GlobalLog.Print("IPAddress::Parse() IPv6 ipString:[" + ValidationHelper.ToString(ipString) + "] errorCode: " + errorCode.ToString()); throw new FormatException(SR.GetString(SR.dns_bad_ip_address), new SocketException()); } // // We have to set up the address by hand now, to avoid initialization // recursion problems that we get if we use IPEndPoint.Create. // byte[] bytes = new byte[16]; long scope = 0; for (int i = 0; i < 16; i++) { bytes[i] = saddr[i + 8]; } // // Scope // scope = (long)((saddr[27] << 24) + (saddr[26] << 16) + (saddr[25] << 8) + (saddr[24])); return(new IPAddress(bytes, scope));; } else { // // Cannot be an IPv6 address, so use the IPv4 routines to // parse the string representation. // int address = UnsafeNclNativeMethods.OSSOCK.inet_addr(ipString); GlobalLog.Print("IPAddress::Parse() ipString:" + ValidationHelper.ToString(ipString) + " inet_addr() returned address:" + address.ToString()); if (address == -1 && string.Compare(ipString, InaddrNoneString, false, CultureInfo.InvariantCulture) != 0 && string.Compare(ipString, InaddrNoneStringHex, true, CultureInfo.InvariantCulture) != 0 && string.Compare(ipString, InaddrNoneStringOct, false, CultureInfo.InvariantCulture) != 0) { throw new FormatException(SR.GetString(SR.dns_bad_ip_address)); } IPAddress returnValue = new IPAddress(address); return(returnValue); } } // Parse
} // Position // // write a chunk of data to ul // public override void Write( byte[] buffer, int offset, int count) { GlobalLog.Print("ListenerResponseStream.WriteCore() offset: " + Convert.ToString(offset) + " count:" + Convert.ToString(count)); if (m_ContentLength != -1 && m_ContentLength < count) { // // user can't send more data than specified in the ContentLength // throw new ProtocolViolationException(SR.GetString(SR.net_entitytoobig)); } int DataToWrite = count; GCHandle PinnedBuffer = new GCHandle(); IntPtr AddrOfPinnedBuffer = IntPtr.Zero; if (m_SendChunked) { string ChunkHeader = "0x" + Convert.ToString(count, 16); DataToWrite += ChunkHeader.Length + 4; AddrOfPinnedBuffer = Marshal.AllocHGlobal(DataToWrite); Marshal.Copy(ChunkHeader.ToCharArray(), 0, AddrOfPinnedBuffer, ChunkHeader.Length); Marshal.WriteInt16(AddrOfPinnedBuffer, ChunkHeader.Length, 0x0A0D); Marshal.Copy((byte[])buffer, offset, IntPtrHelper.Add(AddrOfPinnedBuffer, ChunkHeader.Length + 2), count); Marshal.WriteInt16(AddrOfPinnedBuffer, DataToWrite - 2, 0x0A0D); } else { // // pin the buffer and make an unmanaged call to the driver to // write more entity body // PinnedBuffer = GCHandle.Alloc(buffer, GCHandleType.Pinned); AddrOfPinnedBuffer = PinnedBuffer.AddrOfPinnedObject(); } // // set up a UL_DATA_CHUNK structure to pass down to UL with pointers // to data to be written // IntPtr AddrOfPinnedEntityChunks = Marshal.AllocHGlobal(32); // // AddrOfPinnedBuffer and count go into a pEntityChunks structure // Marshal.WriteInt64(AddrOfPinnedEntityChunks, 0, 0); Marshal.WriteIntPtr(AddrOfPinnedEntityChunks, 8, AddrOfPinnedBuffer); Marshal.WriteInt32(AddrOfPinnedEntityChunks, 12, DataToWrite); Marshal.WriteInt64(AddrOfPinnedEntityChunks, 16, 0); Marshal.WriteInt64(AddrOfPinnedEntityChunks, 24, 0); GlobalLog.Print("Calling UlSendHttpResponseEntityBody: AddrOfPinnedEntityChunks:" + Convert.ToString(AddrOfPinnedEntityChunks) + " AddrOfPinnedBuffer:" + Convert.ToString(AddrOfPinnedBuffer) + " DataToWrite:" + Convert.ToString(DataToWrite)); // // issue unmanaged blocking call // int DataWritten = 0; int result = ComNetOS.IsWinNt ? UlSysApi.UlSendEntityBody( m_AppPoolHandle, m_RequestId, UlConstants.UL_SEND_RESPONSE_FLAG_MORE_DATA, 1, AddrOfPinnedEntityChunks, ref DataWritten, IntPtr.Zero) : UlVxdApi.UlSendHttpResponseEntityBody( m_AppPoolHandle, m_RequestId, 0, 1, AddrOfPinnedEntityChunks, ref DataWritten, IntPtr.Zero); if (m_SendChunked) { // // data was copied into an unmanaged buffer, free it // Marshal.FreeHGlobal(AddrOfPinnedBuffer); } else { // // data wasn't copied unpin the pinned buffer // PinnedBuffer.Free(); } Marshal.FreeHGlobal(AddrOfPinnedEntityChunks); GlobalLog.Print("UlSendHttpResponseEntityBody() DataWritten:" + Convert.ToString(DataWritten) + " DataToWrite:" + Convert.ToString(DataToWrite)); if (result != NativeMethods.ERROR_SUCCESS) //Win32.ERROR_CANCELLED || Win32.ERROR_BAD_COMMAND || NativeMethods.ERROR_INVALID_PARAMETER { throw new ProtocolViolationException(SR.GetString(SR.net_connclosed) + Convert.ToString(result)); } // // double check the number of bytes written // if (DataWritten != DataToWrite) { throw new InvalidOperationException("sync UlSendHttpResponseEntityBody() failed to write all the data" + " count:" + Convert.ToString(count) + " DataWritten:" + Convert.ToString(DataWritten) + " DataToWrite:" + Convert.ToString(DataToWrite) + " m_AppPoolHandle:" + Convert.ToString(m_AppPoolHandle) + " m_RequestId:" + Convert.ToString(m_RequestId) + " err#" + Convert.ToString(result)); } if (result != NativeMethods.ERROR_SUCCESS && result != NativeMethods.ERROR_HANDLE_EOF) { // // Consider: move all Exception string to system.txt for localization // throw new InvalidOperationException("sync UlSendHttpResponseEntityBody() failed, err#" + Convert.ToString(result)); } if (m_ContentLength != -1) { // // keep track of the data transferred // m_ContentLength -= count; if (m_ContentLength == 0) { // // I should be able to call Close() at this point // } } return; // DataToWrite; } // Write()
public HttpListenerException() : base(Marshal.GetLastWin32Error()) { GlobalLog.Print("HttpListenerException::.ctor() " + NativeErrorCode.ToString() + ":" + Message); }
private void ListenForRegistryHelper(ref SafeRegistryHandle key, ref AutoResetEvent changeEvent, IntPtr baseKey, string subKey) { uint errorCode = 0; // First time through? if (key == null || key.IsInvalid) { if (baseKey == IntPtr.Zero) { // Impersonation requires extra effort. GlobalLog.Print("AutoWebProxyScriptEngine#" + ValidationHelper.HashString(this) + "::ListenForRegistry() RegOpenCurrentUser() using hkcu:" + hkcu.DangerousGetHandle().ToString("x")); if (hkcu != null) { errorCode = hkcu.RegOpenKeyEx(subKey, 0, UnsafeNclNativeMethods.RegistryHelper.KEY_READ, out key); GlobalLog.Print("AutoWebProxyScriptEngine#" + ValidationHelper.HashString(this) + "::ListenForRegistry() RegOpenKeyEx() returned errorCode:" + errorCode + " key:" + key.DangerousGetHandle().ToString("x")); } else { errorCode = UnsafeNclNativeMethods.ErrorCodes.ERROR_NOT_FOUND; } } else { errorCode = SafeRegistryHandle.RegOpenKeyEx(baseKey, subKey, 0, UnsafeNclNativeMethods.RegistryHelper.KEY_READ, out key); //GlobalLog.Print("AutoWebProxyScriptEngine#" + ValidationHelper.HashString(this) + "::ListenForRegistry() RegOpenKeyEx() returned errorCode:" + errorCode + " key:" + key.DangerousGetHandle().ToString("x")); } if (errorCode == 0) { changeEvent = new AutoResetEvent(false); } } if (errorCode == 0) { // accessing Handle is protected by a link demand, OK for System.dll errorCode = key.RegNotifyChangeKeyValue(true, UnsafeNclNativeMethods.RegistryHelper.REG_NOTIFY_CHANGE_LAST_SET, changeEvent.SafeWaitHandle, true); GlobalLog.Print("AutoWebProxyScriptEngine#" + ValidationHelper.HashString(this) + "::ListenForRegistry() RegNotifyChangeKeyValue() returned errorCode:" + errorCode); } if (errorCode != 0) { if (key != null && !key.IsInvalid) { try { errorCode = key.RegCloseKey(); } catch (Exception exception) { if (NclUtilities.IsFatal(exception)) { throw; } } GlobalLog.Print("AutoWebProxyScriptEngine#" + ValidationHelper.HashString(this) + "::ListenForRegistry() RegCloseKey() returned errorCode:" + errorCode); } key = null; if (changeEvent != null) { changeEvent.Close(); changeEvent = null; } } }
/// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public override SocketAddress Serialize() { if (m_Address.AddressFamily == AddressFamily.InterNetworkV6) { // // IPv6 Changes: create a new SocketAddress that is large enough for an // IPv6 address and then pack the address into it. // SocketAddress socketAddress = new SocketAddress(this.AddressFamily, SocketAddress.IPv6AddressSize); // // populate it // int port = this.Port; socketAddress[2] = (byte)(port >> 8); socketAddress[3] = (byte)port; // // Note: No handling for Flow Information // socketAddress[4] = (byte)0; socketAddress[5] = (byte)0; socketAddress[6] = (byte)0; socketAddress[7] = (byte)0; // // Scope serialization // long scope = this.Address.ScopeId; socketAddress[24] = (byte)scope; socketAddress[25] = (byte)(scope >> 8); socketAddress[26] = (byte)(scope >> 16); socketAddress[27] = (byte)(scope >> 24); // // Address serialization // byte[] addressBytes = this.Address.GetAddressBytes(); for (int i = 0; i < addressBytes.Length; i++) { socketAddress[8 + i] = addressBytes[i]; } GlobalLog.Print("IPEndPoint::Serialize(IPv6): " + this.ToString()); // // return it // return(socketAddress); } else { // // create a new SocketAddress // SocketAddress socketAddress = new SocketAddress(m_Address.AddressFamily, SocketAddress.IPv4AddressSize); // // populate it // socketAddress[2] = unchecked ((byte)(this.Port >> 8)); socketAddress[3] = unchecked ((byte)(this.Port)); socketAddress[4] = unchecked ((byte)(this.Address.m_Address)); socketAddress[5] = unchecked ((byte)(this.Address.m_Address >> 8)); socketAddress[6] = unchecked ((byte)(this.Address.m_Address >> 16)); socketAddress[7] = unchecked ((byte)(this.Address.m_Address >> 24)); GlobalLog.Print("IPEndPoint::Serialize: " + this.ToString()); // // return it // return(socketAddress); } }
// // FindServicePoint - Query using an Uri for a given server point // /// <devdoc> /// <para>Findes an existing <see cref='System.Net.ServicePoint'/> or creates a new <see cref='System.Net.ServicePoint'/> to manage communications to the specified <see cref='System.Uri'/> /// instance.</para> /// </devdoc> internal static ServicePoint FindServicePoint(string host, int port) { if (host == null) { throw new ArgumentNullException("address"); } GlobalLog.Enter("ServicePointManager::FindServicePoint() host:" + host.ToString()); string tempEntry = null; bool isProxyServicePoint = false; // // Search for the correct proxy host, // then match its acutal host by using ConnectionGroups // which are located on the actual ServicePoint. // tempEntry = "ByHost:" + host + ":" + port.ToString(CultureInfo.InvariantCulture); // lookup service point in the table ServicePoint servicePoint = null; GlobalLog.Print("ServicePointManager::FindServicePoint() locking and looking up tempEntry:[" + tempEntry.ToString() + "]"); lock (s_ServicePointTable) { // once we grab the lock, check if it wasn't already added WeakReference servicePointReference = s_ServicePointTable[tempEntry] as WeakReference; GlobalLog.Print("ServicePointManager::FindServicePoint() lookup returned WeakReference#" + ValidationHelper.HashString(servicePointReference)); if (servicePointReference != null) { servicePoint = (ServicePoint)servicePointReference.Target; GlobalLog.Print("ServicePointManager::FindServicePoint() successfull lookup returned ServicePoint#" + ValidationHelper.HashString(servicePoint)); } if (servicePoint == null) { // lookup failure or timeout, we need to create a new ServicePoint if (s_MaxServicePoints <= 0 || s_ServicePointTable.Count < s_MaxServicePoints) { // Determine Connection Limit int connectionLimit = InternalConnectionLimit; bool userDefined = s_UserChangedLimit; string schemeHostPort = host + ":" + port.ToString(CultureInfo.InvariantCulture); if (ConfigTable.ContainsKey(schemeHostPort)) { connectionLimit = (int)ConfigTable[schemeHostPort]; userDefined = true; } servicePoint = new ServicePoint(host, port, s_ServicePointIdlingQueue, connectionLimit, tempEntry, userDefined, isProxyServicePoint); GlobalLog.Print("ServicePointManager::FindServicePoint() created ServicePoint#" + ValidationHelper.HashString(servicePoint)); servicePointReference = new WeakReference(servicePoint); s_ServicePointTable[tempEntry] = servicePointReference; GlobalLog.Print("ServicePointManager::FindServicePoint() adding entry WeakReference#" + ValidationHelper.HashString(servicePointReference) + " key:[" + tempEntry + "]"); } else { Exception exception = new InvalidOperationException(SR.GetString(SR.net_maxsrvpoints)); GlobalLog.LeaveException("ServicePointManager::FindServicePoint() reached the limit count:" + s_ServicePointTable.Count.ToString() + " limit:" + s_MaxServicePoints.ToString(), exception); throw exception; } } } GlobalLog.Leave("ServicePointManager::FindServicePoint() servicePoint#" + ValidationHelper.HashString(servicePoint)); return(servicePoint); }
/// <summary> /// <para>Fires the timer if it is still active and has expired. Returns /// true if it can be deleted, or false if it is still timing.</para> /// </summary> internal bool Fire() { GlobalLog.Assert(m_TimerState != TimerState.Sentinel, "TimerThread#{0}::Fire()|TimerQueue tried to Fire a Sentinel.", Thread.CurrentThread.ManagedThreadId.ToString()); if (m_TimerState != TimerState.Ready) { return(true); } // Must get the current tick count within this method so it is guaranteed not to be before // StartTime, which is set in the constructor. int nowMilliseconds = Environment.TickCount; if (IsTickBetween(StartTime, Expiration, nowMilliseconds)) { GlobalLog.Print("TimerThreadTimer#" + StartTime + "::Fire() Not firing (" + StartTime + " <= " + nowMilliseconds + " < " + Expiration + ")"); return(false); } bool needCallback = false; lock (m_QueueLock) { if (m_TimerState == TimerState.Ready) { GlobalLog.Print("TimerThreadTimer#" + StartTime + "::Fire() Firing (" + StartTime + " <= " + nowMilliseconds + " >= " + Expiration + ")"); m_TimerState = TimerState.Fired; // Remove it from the list. Next.Prev = Prev; Prev.Next = Next; // Doesn't need to be in the lock but is easier to have here. Next = null; Prev = null; needCallback = m_Callback != null; } } if (needCallback) { try { Callback callback = m_Callback; object context = m_Context; m_Callback = null; m_Context = null; callback(this, nowMilliseconds, context); } catch (Exception exception) { if (NclUtilities.IsFatal(exception)) { throw; } if (Logging.On) { Logging.PrintError(Logging.Web, "TimerThreadTimer#" + StartTime.ToString(NumberFormatInfo.InvariantInfo) + "::Fire() - " + SR.GetString(SR.net_log_exception_in_callback, exception)); } GlobalLog.Print("TimerThreadTimer#" + StartTime + "::Fire() exception in callback: " + exception); // This thread is not allowed to go into user code, so we should never get an exception here. // So, in debug, throw it up, killing the AppDomain. In release, we'll just ignore it. #if DEBUG throw; #endif } } return(true); }
public void GetDocVersionString(out string version) { GlobalLog.Print("AutoWebProxyScriptWrapper.ScriptHost#" + ValidationHelper.HashString(this) + "::GetDocVersionString()"); throw new NotImplementedException(); }
public void OnScriptTerminate(object result, EXCEPINFO exceptionInfo) { GlobalLog.Print("AutoWebProxyScriptWrapper.ScriptHost#" + ValidationHelper.HashString(this) + "::OnScriptTerminate() result:" + ValidationHelper.ToString(result) + " error:" + ValidationHelper.ToString(exceptionInfo.bstrDescription)); }
internal AutoWebProxyState Compile(Uri engineScriptLocation, string scriptBody, byte[] buffer) { if (closed != 0) { throw new ObjectDisposedException(GetType().Name); } if (jscriptObject != null) { jscript.Close(); } scriptText = null; scriptBytes = null; jscriptObject = new JScriptEngine(); jscript = (IActiveScript)jscriptObject; host = new ScriptHost(); GlobalLog.Print("AutoWebProxyScriptWrapper#" + ValidationHelper.HashString(this) + "::Compile() Binding to ScriptHost#" + ValidationHelper.HashString(this)); jscriptParser = new ActiveScriptParseWrapper(jscriptObject); jscriptParser.InitNew(); jscript.SetScriptSite(host); jscript.SetScriptState(ScriptState.Initialized); // // Inform the script engine that this host implements the IInternetHostSecurityManager interface, which // is used to prevent the script code from using any ActiveX objects. // IObjectSafety objSafety = jscript as IObjectSafety; if (objSafety != null) { Guid guid = Guid.Empty; GlobalLog.Print("AutoWebProxyScriptWrapper#" + ValidationHelper.HashString(this) + "::Compile() Setting up IInternetHostSecurityManager"); objSafety.SetInterfaceSafetyOptions(ref guid, ComConstants.INTERFACE_USES_SECURITY_MANAGER, ComConstants.INTERFACE_USES_SECURITY_MANAGER); objSafety = null; } EXCEPINFO exceptionInfo = new EXCEPINFO(); object result = null; try { jscriptParser.ParseScriptText(scriptBody, null, null, null, IntPtr.Zero, 0, ScriptText.IsPersistent | ScriptText.IsVisible, out result, out exceptionInfo); GlobalLog.Print("AutoWebProxyScriptWrapper#" + ValidationHelper.HashString(this) + "::Compile() ParseScriptText() success:" + ValidationHelper.ToString(exceptionInfo.bstrDescription) + " result:" + ValidationHelper.ToString(result)); } catch (Exception exception) { if (NclUtilities.IsFatal(exception)) { throw; } if (exception is TargetInvocationException) { exception = exception.InnerException; } COMException comException = exception as COMException; if (comException == null || comException.ErrorCode != (int)HRESULT.SCRIPT_E_REPORTED) { throw; } GlobalLog.Print("AutoWebProxyScriptWrapper#" + ValidationHelper.HashString(this) + "::Compile() Script load error:[" + host.ExceptionMessage == null ? "" : host.ExceptionMessage + "]"); throw new COMException(SR.GetString(SR.net_jscript_load, host.ExceptionMessage), comException.ErrorCode); } catch { GlobalLog.Print("AutoWebProxyScriptWrapper#" + ValidationHelper.HashString(this) + "::Compile() Script load error:[Non-CLS Compliant Exception]"); throw; } jscript.AddNamedItem(c_ScriptHelperName, ScriptItem.GlobalMembers | ScriptItem.IsPersistent | ScriptItem.IsVisible); // This part can run global code - time it out if necessary. jscript.GetCurrentScriptThreadID(out interruptThreadId); TimerThread.Timer timer = s_TimerQueue.CreateTimer(s_InterruptCallback, this); activeTimer = timer; try { jscript.SetScriptState(ScriptState.Started); jscript.SetScriptState(ScriptState.Connected); } finally { activeTimer = null; timer.Cancel(); } jscript.GetScriptDispatch(null, out script); GlobalLog.Print("AutoWebProxyScriptWrapper#" + ValidationHelper.HashString(this) + "::Compile() Got IDispatch:" + ValidationHelper.ToString(dispatch)); scriptText = scriptBody; scriptBytes = buffer; return(AutoWebProxyState.CompilationSuccess); }
// // IActiveScriptSite // public void GetLCID(out int lcid) { GlobalLog.Print("AutoWebProxyScriptWrapper.ScriptHost#" + ValidationHelper.HashString(this) + "::GetLCID()"); lcid = Thread.CurrentThread.CurrentCulture.LCID; }
} // GetHostByName // Does internal IPAddress reverse and then forward lookups (for Legacy and current public methods). internal static IPHostEntry InternalGetHostByAddress(IPAddress address, bool includeIPv6) { if (GlobalLog.IsEnabled) { GlobalLog.Print("Dns.InternalGetHostByAddress: " + address.ToString()); } // // IPv6 Changes: We need to use the new getnameinfo / getaddrinfo functions // for resolution of IPv6 addresses. // if (SocketProtocolSupportPal.OSSupportsIPv6 || includeIPv6) { // // Try to get the data for the host from it's address // // We need to call getnameinfo first, because getaddrinfo w/ the ipaddress string // will only return that address and not the full list. // Do a reverse lookup to get the host name. SocketError errorCode; int nativeErrorCode; string name = NameResolutionPal.TryGetNameInfo(address, out errorCode, out nativeErrorCode); if (errorCode == SocketError.Success) { // Do the forward lookup to get the IPs for that host name IPHostEntry hostEntry; errorCode = NameResolutionPal.TryGetAddrInfo(name, out hostEntry, out nativeErrorCode); if (errorCode == SocketError.Success) { return(hostEntry); } if (NetEventSource.Log.IsEnabled()) { NetEventSource.Exception(NetEventSource.ComponentType.Socket, "DNS", "InternalGetHostByAddress", new InternalSocketException(errorCode, nativeErrorCode)); } // One of two things happened: // 1. There was a ptr record in dns, but not a corollary A/AAA record. // 2. The IP was a local (non-loopback) IP that resolved to a connection specific dns suffix. // - Workaround, Check "Use this connection's dns suffix in dns registration" on that network // adapter's advanced dns settings. // Just return the resolved host name and no IPs. return(hostEntry); } throw new InternalSocketException(errorCode, nativeErrorCode); } // // If IPv6 is not enabled (maybe config switch) but we've been // given an IPv6 address then we need to bail out now. // else { if (address.AddressFamily == AddressFamily.InterNetworkV6) { // // Protocol not supported // throw new SocketException((int)SocketError.ProtocolNotSupported); } // // Use gethostbyaddr() to try to resolve the IP address // // End IPv6 Changes // return(NameResolutionPal.GetHostByAddr(address)); } } // InternalGetHostByAddress
internal static IPHostEntry InternalGetHostByName(string hostName, bool includeIPv6) { if (NetEventSource.Log.IsEnabled()) { NetEventSource.Enter(NetEventSource.ComponentType.Socket, "DNS", "GetHostByName", hostName); } IPHostEntry ipHostEntry = null; if (GlobalLog.IsEnabled) { GlobalLog.Print("Dns.GetHostByName: " + hostName); } NameResolutionPal.EnsureSocketsAreInitialized(); if (hostName.Length > MaxHostName || // If 255 chars, the last one must be a dot. hostName.Length == MaxHostName && hostName[MaxHostName - 1] != '.') { throw new ArgumentOutOfRangeException("hostName", SR.Format(SR.net_toolong, "hostName", MaxHostName.ToString(NumberFormatInfo.CurrentInfo))); } // // IPv6 Changes: IPv6 requires the use of getaddrinfo() rather // than the traditional IPv4 gethostbyaddr() / gethostbyname(). // getaddrinfo() is also protocol independant in that it will also // resolve IPv4 names / addresses. As a result, it is the preferred // resolution mechanism on platforms that support it (Windows 5.1+). // If getaddrinfo() is unsupported, IPv6 resolution does not work. // // Consider : If IPv6 is disabled, we could detect IPv6 addresses // and throw an unsupported platform exception. // // Note : Whilst getaddrinfo is available on WinXP+, we only // use it if IPv6 is enabled (platform is part of that // decision). This is done to minimize the number of // possible tests that are needed. // if (includeIPv6 || SocketProtocolSupportPal.OSSupportsIPv6) { // // IPv6 enabled: use getaddrinfo() to obtain DNS information. // int nativeErrorCode; SocketError errorCode = NameResolutionPal.TryGetAddrInfo(hostName, out ipHostEntry, out nativeErrorCode); if (errorCode != SocketError.Success) { throw new InternalSocketException(errorCode, nativeErrorCode); } } else { ipHostEntry = NameResolutionPal.GetHostByName(hostName); } if (NetEventSource.Log.IsEnabled()) { NetEventSource.Exit(NetEventSource.ComponentType.Socket, "DNS", "GetHostByName", ipHostEntry); } return(ipHostEntry); } // GetHostByName
private object WaitForCompletion(bool snap) { ManualResetEvent waitHandle = null; bool createdByMe = false; bool complete = snap ? IsCompleted : InternalPeekCompleted; if (!complete) { // Not done yet, so wait: waitHandle = (ManualResetEvent)_event; if (waitHandle == null) { createdByMe = LazilyCreateEvent(out waitHandle); } } if (waitHandle != null) { try { if (GlobalLog.IsEnabled) { GlobalLog.Print("LazyAsyncResult#" + LoggingHash.HashString(this) + "::InternalWaitForCompletion() Waiting for completion _event#" + LoggingHash.HashString(waitHandle)); } waitHandle.WaitOne(Timeout.Infinite); } catch (ObjectDisposedException) { // This can occur if this method is called from two different threads. // This possibility is the trade-off for not locking. } finally { // We also want to dispose the event although we can't unless we did wait on it here. if (createdByMe && !_userEvent) { // Does _userEvent need to be volatile (or _event set via Interlocked) in order // to avoid giving a user a disposed event? ManualResetEvent oldEvent = (ManualResetEvent)_event; _event = null; if (!_userEvent) { oldEvent.Dispose(); } } } } // A race condition exists because InvokeCallback sets _intCompleted before _result (so that _result // can benefit from the synchronization of _intCompleted). That means you can get here before _result got // set (although rarely - once every eight hours of stress). Handle that case with a spin-lock. SpinWait sw = new SpinWait(); while (_result == DBNull.Value) { sw.SpinOnce(); } if (GlobalLog.IsEnabled) { GlobalLog.Print("LazyAsyncResult#" + LoggingHash.HashString(this) + "::InternalWaitForCompletion() done: " + (_result is Exception ? ((Exception)_result).Message : _result == null ? "<null>" : _result.ToString())); } return(_result); }
/// <devdoc> /// <para> /// Used by the ServicePoint to find a free or new Connection /// for use in making Requests, this is done with the cavet, /// that once a Connection is "locked" it can only be used /// by a specific request. /// /// NOTE: For Whidbey: try to integrate this code into FindConnection() /// </para> /// </devdoc> private Connection FindConnectionAuthenticationGroup(HttpWebRequest request, string connName) { Connection leastBusyConnection = null; GlobalLog.Print("ConnectionGroup::FindConnectionAuthenticationGroup [" + connName + "] for request#" + request.GetHashCode() + ", m_ConnectionList.Count:" + m_ConnectionList.Count.ToString()); // // First try and find a free Connection (i.e. one not busy with Authentication handshake) // or try to find a Request that has already locked a specific Connection, // if a matching Connection is found, then we're done // lock (m_ConnectionList) { Connection matchingConnection; matchingConnection = FindMatchingConnection(request, connName, out leastBusyConnection); if (matchingConnection != null) { matchingConnection.MarkAsReserved(); return(matchingConnection); } if (AuthenticationRequestQueue.Count == 0) { if (leastBusyConnection != null) { if (request.LockConnection) { m_NtlmNegGroup = true; m_IISVersion = leastBusyConnection.IISVersion; } if (request.LockConnection || (m_NtlmNegGroup && !request.Pipelined && request.UnsafeOrProxyAuthenticatedConnectionSharing && m_IISVersion >= 6)) { GlobalLog.Print("Assigning New Locked Request#" + request.GetHashCode().ToString()); leastBusyConnection.LockedRequest = request; } leastBusyConnection.MarkAsReserved(); return(leastBusyConnection); } } else if (leastBusyConnection != null) { AsyncWaitHandle.Set(); } AuthenticationRequestQueue.Enqueue(request); } // // If all the Connections are busy, then we queue ourselves and need to wait. As soon as // one of the Connections are free, we grab the lock, and see if we find ourselves // at the head of the queue. If not, we loop backaround. // Care is taken to examine the request when we wakeup, in case the request is aborted. // while (true) { GlobalLog.Print("waiting"); request.AbortDelegate = m_AbortDelegate; if (!request.Aborted) { AsyncWaitHandle.WaitOne(); } GlobalLog.Print("wait up"); lock (m_ConnectionList) { if (request.Aborted) { PruneAbortedRequests(); // Note that request is not on any connection and it will not be submitted return(null); } FindMatchingConnection(request, connName, out leastBusyConnection); if (AuthenticationRequestQueue.Peek() == request) { GlobalLog.Print("dequeue"); AuthenticationRequestQueue.Dequeue(); if (leastBusyConnection != null) { if (request.LockConnection) { m_NtlmNegGroup = true; m_IISVersion = leastBusyConnection.IISVersion; } if (request.LockConnection || (m_NtlmNegGroup && !request.Pipelined && request.UnsafeOrProxyAuthenticatedConnectionSharing && m_IISVersion >= 6)) { leastBusyConnection.LockedRequest = request; } leastBusyConnection.MarkAsReserved(); return(leastBusyConnection); } AuthenticationRequestQueue.Enqueue(request); } if (leastBusyConnection == null) { AsyncWaitHandle.Reset(); } } } }
public void OnLeaveScript() { GlobalLog.Print("AutoWebProxyScriptWrapper.ScriptHost#" + ValidationHelper.HashString(this) + "::OnLeaveScript()"); }
/// <devdoc> /// <para> /// Used by the ServicePoint to find a free or new Connection /// for use in making Requests. Under NTLM and Negotiate requests, /// this function deprecates itself and switches the object over to /// using a new code path (see FindConnectionAuthenticationGroup). /// </para> /// </devdoc> internal Connection FindConnection(HttpWebRequest request, string connName, out bool forcedsubmit) { Connection leastbusyConnection = null; Connection newConnection = null; bool freeConnectionsAvail = false; ArrayList closedConnections = new ArrayList(); forcedsubmit = false; if (m_AuthenticationGroup || request.LockConnection) { m_AuthenticationGroup = true; return(FindConnectionAuthenticationGroup(request, connName)); } GlobalLog.Print("ConnectionGroup::FindConnection [" + connName + "] m_ConnectionList.Count:" + m_ConnectionList.Count.ToString()); lock (m_ConnectionList) { // // go through the list of open connections to this service point and pick the connection as follows: // - free connection // - if there is no free connection and if we are under connection limit, create new connection // - pick the least busy connection which does not have non-keep alive request pipelined // - pick the least busy connection which may have non-keep alive request pipelined // If we pick the connection with non keep-alive request pipelined on it, we set forcedsubmit to true. // This will make sure that we don't start the request immediately and it gets queued on the connection. // int minBusyCount = Int32.MaxValue; bool foundLiveConnection = false; foreach (Connection currentConnection in m_ConnectionList) { GlobalLog.Print("ConnectionGroup::FindConnection currentConnection.BusyCount:" + currentConnection.BusyCount.ToString()); bool useThisConnection = false; if (!currentConnection.IsInitalizing && !currentConnection.NetworkStream.Connected) { // This is a closed connection probably due to a previous Abort(). Remove it // from the list of eligible connections. closedConnections.Add(currentConnection); } else { if (foundLiveConnection) { useThisConnection = (!currentConnection.NonKeepAliveRequestPipelined && minBusyCount > currentConnection.BusyCount); } else { useThisConnection = (!currentConnection.NonKeepAliveRequestPipelined || minBusyCount > currentConnection.BusyCount); } } if (useThisConnection) { leastbusyConnection = currentConnection; minBusyCount = currentConnection.BusyCount; if (!foundLiveConnection) { foundLiveConnection = !currentConnection.NonKeepAliveRequestPipelined; } else { GlobalLog.Assert(!currentConnection.NonKeepAliveRequestPipelined, "Connection.NonKeepAliveRequestPipelined == false|Non keep-alive request has been pipelined on this connection."); } if (foundLiveConnection && minBusyCount == 0) { freeConnectionsAvail = true; break; } } } // // Remove closed connections. // GlobalLog.Print("ConnectionGroup::FindConnection, closed connections to remove: " + closedConnections.Count.ToString()); foreach (Connection closedConnection in closedConnections) { closedConnection.RemoveFromConnectionList(); } // // If there is NOT a Connection free, then we allocate a new Connection // if (!freeConnectionsAvail && CurrentConnections < ConnectionLimit) { // // If we can create a new connection, then do it, // this may have complications in pipeling because // we may wish to optimize this case by actually // using existing connections, rather than creating new ones // // Note: this implicitly results in a this.Associate() being called. // GlobalLog.Print("ConnectionGroup::FindConnection [returning new Connection] freeConnectionsAvail:" + freeConnectionsAvail.ToString() + " CurrentConnections:" + CurrentConnections.ToString() + " ConnectionLimit:" + ConnectionLimit.ToString()); newConnection = new Connection(this); forcedsubmit = false; } else { // // All connections are busy, use the least busy one // GlobalLog.Print("ConnectionGroup::FindConnection [returning leastbusyConnection] freeConnectionsAvail:" + freeConnectionsAvail.ToString() + " CurrentConnections:" + CurrentConnections.ToString() + " ConnectionLimit:" + ConnectionLimit.ToString()); GlobalLog.Assert(leastbusyConnection != null, "Connect.leastbusyConnection != null|All connections have BusyCount equal to Int32.MaxValue."); newConnection = leastbusyConnection; forcedsubmit = !foundLiveConnection; } newConnection.MarkAsReserved(); } return(newConnection); }
// IInternetHostSecurityManager methods. // Implementation based on inetcore\wininet\autoconf\cscpsite.cpp // The current implementation disallows all ActiveX control activation from script. public int GetSecurityId(byte[] pbSecurityId, ref IntPtr pcbSecurityId, IntPtr dwReserved) { GlobalLog.Print("AutoWebProxyScriptWrapper.ScriptHost#" + ValidationHelper.HashString(this) + "::GetSecurityId()"); return((int)HRESULT.E_NOTIMPL); }
private static ServicePoint FindServicePointHelper(Uri address, bool isProxyServicePoint) { GlobalLog.Enter("ServicePointManager::FindServicePointHelper() address:" + address.ToString()); if (isProxyServicePoint) { if (address.Scheme != Uri.UriSchemeHttp) { // < Exception exception = new NotSupportedException(SR.GetString(SR.net_proxyschemenotsupported, address.Scheme)); GlobalLog.LeaveException("ServicePointManager::FindServicePointHelper() proxy has unsupported scheme:" + address.Scheme.ToString(), exception); throw exception; } } // // Search for the correct proxy host, // then match its acutal host by using ConnectionGroups // which are located on the actual ServicePoint. // string tempEntry = MakeQueryString(address, isProxyServicePoint); // lookup service point in the table ServicePoint servicePoint = null; GlobalLog.Print("ServicePointManager::FindServicePointHelper() locking and looking up tempEntry:[" + tempEntry.ToString() + "]"); lock (s_ServicePointTable) { // once we grab the lock, check if it wasn't already added WeakReference servicePointReference = s_ServicePointTable[tempEntry] as WeakReference; GlobalLog.Print("ServicePointManager::FindServicePointHelper() lookup returned WeakReference#" + ValidationHelper.HashString(servicePointReference)); if (servicePointReference != null) { servicePoint = (ServicePoint)servicePointReference.Target; GlobalLog.Print("ServicePointManager::FindServicePointHelper() successful lookup returned ServicePoint#" + ValidationHelper.HashString(servicePoint)); } if (servicePoint == null) { // lookup failure or timeout, we need to create a new ServicePoint if (s_MaxServicePoints <= 0 || s_ServicePointTable.Count < s_MaxServicePoints) { // Determine Connection Limit int connectionLimit = InternalConnectionLimit; string schemeHostPort = MakeQueryString(address); bool userDefined = s_UserChangedLimit; if (ConfigTable.ContainsKey(schemeHostPort)) { connectionLimit = (int)ConfigTable[schemeHostPort]; userDefined = true; } servicePoint = new ServicePoint(address, s_ServicePointIdlingQueue, connectionLimit, tempEntry, userDefined, isProxyServicePoint); GlobalLog.Print("ServicePointManager::FindServicePointHelper() created ServicePoint#" + ValidationHelper.HashString(servicePoint)); servicePointReference = new WeakReference(servicePoint); s_ServicePointTable[tempEntry] = servicePointReference; GlobalLog.Print("ServicePointManager::FindServicePointHelper() adding entry WeakReference#" + ValidationHelper.HashString(servicePointReference) + " key:[" + tempEntry + "]"); } else { Exception exception = new InvalidOperationException(SR.GetString(SR.net_maxsrvpoints)); GlobalLog.LeaveException("ServicePointManager::FindServicePointHelper() reached the limit count:" + s_ServicePointTable.Count.ToString() + " limit:" + s_MaxServicePoints.ToString(), exception); throw exception; } } } GlobalLog.Leave("ServicePointManager::FindServicePointHelper() servicePoint#" + ValidationHelper.HashString(servicePoint)); return(servicePoint); }
internal AutoWebProxyScriptWrapper() { GlobalLog.Print("AutoWebProxyScriptWrapper::.ctor() Creating AppDomain: " + c_appDomainName); Exception exception = null; if (s_ProxyScriptHelperLoadError == null && s_ProxyScriptHelperType == null) { lock (s_ProxyScriptHelperLock) { if (s_ProxyScriptHelperLoadError == null && s_ProxyScriptHelperType == null) { // Try to load the type late-bound out of Microsoft.JScript. try { s_ProxyScriptHelperType = Type.GetType("System.Net.VsaWebProxyScript, Microsoft.JScript, Version=8.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a", true); } catch (Exception ex) { exception = ex; } if (s_ProxyScriptHelperType == null) { s_ProxyScriptHelperLoadError = exception == null ? new InternalException() : exception; } } } } if (s_ProxyScriptHelperLoadError != null) { throw new TypeLoadException(SR.GetString(SR.net_cannot_load_proxy_helper), s_ProxyScriptHelperLoadError is InternalException ? null : s_ProxyScriptHelperLoadError); } CreateAppDomain(); exception = null; try { GlobalLog.Print("AutoWebProxyScriptWrapper::CreateInstance() Creating Object. type.Assembly.FullName: [" + s_ProxyScriptHelperType.Assembly.FullName + "] type.FullName: [" + s_ProxyScriptHelperType.FullName + "]"); ObjectHandle handle = Activator.CreateInstance(scriptDomain, s_ProxyScriptHelperType.Assembly.FullName, s_ProxyScriptHelperType.FullName, false, BindingFlags.CreateInstance | BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.InvokeMethod, null, null, null, null, null); if (handle != null) { site = (IWebProxyScript)handle.Unwrap(); } GlobalLog.Print("AutoWebProxyScriptWrapper::CreateInstance() Create script site:" + ValidationHelper.HashString(site)); } catch (Exception ex) { exception = ex; } if (site == null) { lock (s_ProxyScriptHelperLock) { if (s_ProxyScriptHelperLoadError == null) { s_ProxyScriptHelperLoadError = exception == null ? new InternalException() : exception; } } throw new TypeLoadException(SR.GetString(SR.net_cannot_load_proxy_helper), s_ProxyScriptHelperLoadError is InternalException ? null : s_ProxyScriptHelperLoadError); } }
/// <summary> /// <para>Thread for the timer. Ignores all exceptions except ThreadAbort. If no activity occurs for a while, /// the thread will shut down.</para> /// </summary> private static void ThreadProc() { #if DEBUG GlobalLog.SetThreadSource(ThreadKinds.Timer); using (GlobalLog.SetThreadKind(ThreadKinds.System | ThreadKinds.Async)) { #endif GlobalLog.Print("TimerThread#" + Thread.CurrentThread.ManagedThreadId.ToString() + "::ThreadProc() Start"); // t_IsTimerThread = true; -- Not used anywhere. // Set this thread as a background thread. On AppDomain/Process shutdown, the thread will just be killed. Thread.CurrentThread.IsBackground = true; // Keep a permanent lock on s_Queues. This lets for example Shutdown() know when this thread isn't running. lock (s_Queues) { // If shutdown was recently called, abort here. if (Interlocked.CompareExchange(ref s_ThreadState, (int)TimerThreadState.Running, (int)TimerThreadState.Running) != (int)TimerThreadState.Running) { return; } bool running = true; while (running) { try { s_ThreadReadyEvent.Reset(); while (true) { // Copy all the new queues to the real queues. Since only this thread modifies the real queues, it doesn't have to lock it. if (s_NewQueues.Count > 0) { lock (s_NewQueues) { for (LinkedListNode <WeakReference> node = s_NewQueues.First; node != null; node = s_NewQueues.First) { s_NewQueues.Remove(node); s_Queues.AddLast(node); } } } int now = Environment.TickCount; int nextTick = 0; bool haveNextTick = false; for (LinkedListNode <WeakReference> node = s_Queues.First; node != null; /* node = node.Next must be done in the body */) { TimerQueue queue = (TimerQueue)node.Value.Target; if (queue == null) { LinkedListNode <WeakReference> next = node.Next; s_Queues.Remove(node); node = next; continue; } // Fire() will always return values that should be interpreted as later than 'now' (that is, even if 'now' is // returned, it is 0x100000000 milliseconds in the future). There's also a chance that Fire() will return a value // intended as > 0x100000000 milliseconds from 'now'. Either case will just cause an extra scan through the timers. int nextTickInstance; if (queue.Fire(out nextTickInstance) && (!haveNextTick || IsTickBetween(now, nextTick, nextTickInstance))) { nextTick = nextTickInstance; haveNextTick = true; } node = node.Next; } // Figure out how long to wait, taking into account how long the loop took. // Add 15 ms to compensate for poor TickCount resolution (want to guarantee a firing). int newNow = Environment.TickCount; int waitDuration = haveNextTick ? (int)(IsTickBetween(now, nextTick, newNow) ? Math.Min(unchecked ((uint)(nextTick - newNow)), (uint)(Int32.MaxValue - c_TickCountResolution)) + c_TickCountResolution : 0) : c_ThreadIdleTimeoutMilliseconds; GlobalLog.Print("TimerThread#" + Thread.CurrentThread.ManagedThreadId.ToString() + "::ThreadProc() Waiting for " + waitDuration + "ms"); int waitResult = WaitHandle.WaitAny(s_ThreadEvents, waitDuration, false); // 0 is s_ThreadShutdownEvent - die. if (waitResult == 0) { GlobalLog.Print("TimerThread#" + Thread.CurrentThread.ManagedThreadId.ToString() + "::ThreadProc() Awoke, cause: Shutdown"); running = false; break; } GlobalLog.Print("TimerThread#" + Thread.CurrentThread.ManagedThreadId.ToString() + "::ThreadProc() Awoke, cause: " + (waitResult == WaitHandle.WaitTimeout ? "Timeout" : "Prod")); // If we timed out with nothing to do, shut down. if (waitResult == WaitHandle.WaitTimeout && !haveNextTick) { Interlocked.CompareExchange(ref s_ThreadState, (int)TimerThreadState.Idle, (int)TimerThreadState.Running); // There could have been one more prod between the wait and the exchange. Check, and abort if necessary. if (s_ThreadReadyEvent.WaitOne(0, false)) { if (Interlocked.CompareExchange(ref s_ThreadState, (int)TimerThreadState.Running, (int)TimerThreadState.Idle) == (int)TimerThreadState.Idle) { continue; } } running = false; break; } } } catch (Exception exception) { if (NclUtilities.IsFatal(exception)) { throw; } if (Logging.On) { Logging.PrintError(Logging.Web, "TimerThread#" + Thread.CurrentThread.ManagedThreadId.ToString(NumberFormatInfo.InvariantInfo) + "::ThreadProc() - Exception:" + exception.ToString()); } GlobalLog.Print("TimerThread#" + Thread.CurrentThread.ManagedThreadId.ToString() + "::ThreadProc() exception: " + exception); // The only options are to continue processing and likely enter an error-loop, // shut down timers for this AppDomain, or shut down the AppDomain. Go with shutting // down the AppDomain in debug, and going into a loop in retail, but try to make the // loop somewhat slow. Note that in retail, this can only be triggered by OutOfMemory or StackOverflow, // or an thrown within TimerThread - the rest are caught in Fire(). #if !DEBUG Thread.Sleep(1000); #else throw; #endif } } } GlobalLog.Print("TimerThread#" + Thread.CurrentThread.ManagedThreadId.ToString() + "::ThreadProc() Stop"); #if DEBUG } #endif }
// Forward these to the site. internal string FindProxyForURL(string url, string host) { GlobalLog.Print("AutoWebProxyScriptWrapper::FindProxyForURL() Calling JScript for url:" + url.ToString() + " host:" + host.ToString()); return(site.Run(url, host)); }
internal CookieCollection CookieCutter(Uri uri, string headerName, string setCookieHeader, bool isThrow) { GlobalLog.Print("CookieContainer#" + ValidationHelper.HashString(this) + "::CookieCutter() uri:" + uri + " headerName:" + headerName + " setCookieHeader:" + setCookieHeader + " isThrow:" + isThrow); CookieCollection cookies = new CookieCollection(); CookieVariant variant = CookieVariant.Unknown; if (headerName == null) { variant = CookieVariant.Default; } else { for (int i = 0; i < HeaderInfo.Length; ++i) { if ((String.Compare(headerName, HeaderInfo[i].Name, StringComparison.OrdinalIgnoreCase) == 0)) { variant = HeaderInfo[i].Variant; } } } bool isLocalDomain = IsLocalDomain(uri.Host); try { CookieParser parser = new CookieParser(setCookieHeader); do { Cookie cookie = parser.Get(); GlobalLog.Print("CookieContainer#" + ValidationHelper.HashString(this) + "::CookieCutter() CookieParser returned cookie:" + ValidationHelper.ToString(cookie)); if (cookie == null) { if (parser.EndofHeader()) { break; } continue; } //Parser marks invalid cookies this way if (ValidationHelper.IsBlankString(cookie.Name)) { if (isThrow) { throw new CookieException(SR.GetString(SR.net_cookie_format)); } //Otherwise, ignore (reject) cookie continue; } // this will set the default values from the response URI // AND will check for cookie validity if (!cookie.VerifySetDefaults(variant, uri, isLocalDomain, m_fqdnMyDomain, true, isThrow)) { continue; } // If many same cookies arrive we collapse them into just one, hence setting // parameter isStrict = true below cookies.InternalAdd(cookie, true); } while (true); } catch (Exception e) { if (e is ThreadAbortException || e is StackOverflowException || e is OutOfMemoryException) { throw; } if (isThrow) { throw new CookieException(SR.GetString(SR.net_cookie_parse_header, uri.AbsoluteUri), e); } } foreach (Cookie c in cookies) { Add(c, isThrow); } return(cookies); }
// methods /*++ * * FindConnectionGroup - * * Searches for the a Group object that actually holds the connections * that we want to peak at. * * * Input: * request - Request that's being submitted. * connName - Connection Name if needed * * Returns: * ConnectionGroup * * --*/ internal ConnectionGroup FindConnectionGroup(string connName) { string lookupStr = ConnectionGroup.MakeQueryStr(connName); GlobalLog.Print("ServicePoint#" + ValidationHelper.HashString(this) + "::FindConnectionGroup() lookupStr:[" + ValidationHelper.ToString(connName) + "]"); ConnectionGroup entry = m_ConnectionGroupList[lookupStr] as ConnectionGroup; if (entry == null) { IPAddressInfo RemoteInfo = GetCurrentIPAddressInfo(); IPAddress RemoteAddress = null; int ConnLimit; if (RemoteInfo == null) { GlobalLog.Print("ServicePoint#" + ValidationHelper.HashString(this) + "::FindConnectionGroup() RemoteAddress:[(null)] m_UserChangedLimit:" + m_UserChangedLimit.ToString() + " m_ConnectionLimit:" + m_ConnectionLimit.ToString()); // // If we don't have any information about the remote IP address, // limit ourself to one connection until the address is resolved. // ConnLimit = 1; // ServicePointManager.DefaultConnectionLimit; // // if this is a user given number, then // make sure to propagte this value // if (m_UserChangedLimit) { ConnLimit = m_ConnectionLimit; } } else { RemoteAddress = RemoteInfo.Address; if (!RemoteInfo.IsLoopback) { ConnLimit = m_ConnectionLimit; } else { ConnLimit = LoopbackConnectionLimit; } GlobalLog.Print("ServicePoint#" + ValidationHelper.HashString(this) + "::FindConnectionGroup() RemoteAddress:[" + RemoteAddress.ToString() + "] ConnLimit:" + ConnLimit.ToString() + " m_ConnectionLimit:" + m_ConnectionLimit.ToString()); } GlobalLog.Print("ServicePoint#" + ValidationHelper.HashString(this) + "::FindConnectionGroup() creating ConnectionGroup ConnLimit:" + ConnLimit.ToString()); entry = new ConnectionGroup(this, RemoteAddress, ConnLimit, connName); GlobalLog.Print("ServicePoint#" + ValidationHelper.HashString(this) + "::FindConnectionGroup() adding ConnectionGroup lookupStr:[" + lookupStr + "]"); m_ConnectionGroupList[lookupStr] = entry; } else { GlobalLog.Print("ServicePoint#" + ValidationHelper.HashString(this) + "::FindConnectionGroup() using existing ConnectionGroup"); } GlobalLog.Print("ServicePoint#" + ValidationHelper.HashString(this) + "::FindConnectionGroup() ConnectionGroup.ConnLimit:" + entry.ConnectionLimit.ToString()); return(entry); }
/// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public override EndPoint Create(SocketAddress socketAddress) { // // validate SocketAddress // if (socketAddress.Family != this.AddressFamily) { throw new ArgumentException(SR.GetString(SR.net_InvalidAddressFamily, socketAddress.Family.ToString(), this.GetType().FullName, this.AddressFamily.ToString()), "socketAddress"); } if (socketAddress.Size < 8) { throw new ArgumentException(SR.GetString(SR.net_InvalidSocketAddressSize, socketAddress.GetType().FullName, this.GetType().FullName), "socketAddress"); } if (this.AddressFamily == AddressFamily.InterNetworkV6) { // // IPv6 Changes: Extract the IPv6 Address information from the socket address // byte[] addr = new byte[IPAddress.IPv6AddressBytes]; for (int i = 0; i < addr.Length; i++) { addr[i] = socketAddress[i + 8]; } // // Port // int port = (int)((socketAddress[2] << 8 & 0xFF00) | (socketAddress[3])); // // Scope // long scope = (long)((socketAddress[27] << 24) + (socketAddress[26] << 16) + (socketAddress[25] << 8) + (socketAddress[24])); IPEndPoint created = new IPEndPoint(new IPAddress(addr, scope), port); GlobalLog.Print("IPEndPoint::Create IPv6: " + this.ToString() + " -> " + created.ToString()); return(created); } else { // // strip out of SocketAddress information on the EndPoint // int port = (int)( (socketAddress[2] << 8 & 0xFF00) | (socketAddress[3]) ); long address = (long)( (socketAddress[4] & 0x000000FF) | (socketAddress[5] << 8 & 0x0000FF00) | (socketAddress[6] << 16 & 0x00FF0000) | (socketAddress[7] << 24) ) & 0x00000000FFFFFFFF; IPEndPoint created = new IPEndPoint(address, port); GlobalLog.Print("IPEndPoint::Create: " + this.ToString() + " -> " + created.ToString()); // // return it // return(created); } }
/*++ * * SetAddressList - Set the list of IP addresses for this service point. * * This is a method called when the underlying code has resolved the * destination to a list of IP addressess. We actually maintain some * information about the viable IP addresses for this service point, * like whether or not they're loopback, etc. So we walk through the * list and set up an array of structures corresponding to the IP * addresses. * * Note that it's possible to have some IP addresses be loopbacked * and some not. This can happen if a server name maps to multiple * physical servers and we're one of those servers. * * Input: * addressList - Array of resolved IP addresses. * * Returns: Nothing. * * --*/ private IPHostEntryInfo SetAddressList(IPHostEntry ipHostEntry) { GlobalLog.Print("SetAddressList(" + ipHostEntry.HostName + ")"); // // Create an array of IPAddressInfo of the appropriate size, then // get a list of our local addresses. Walk through the input // address list. Copy each address in the address list into // our array, and if the address is a loopback address, mark it as // such. // IPAddress[] addressList = ipHostEntry.AddressList; IPAddressInfo[] TempInfo = new IPAddressInfo[addressList.Length]; // // Walk through each member of the input list, copying it into our temp array. // int i, k; IPHostEntry ipLocalHostEntry = Dns.LocalHost; for (i = 0; i < addressList.Length; i++) { TempInfo[i] = new IPAddressInfo(addressList[i]); // First, check to see if the current address is a loopback // address. if (IPAddress.IsLoopback(TempInfo[i].Address)) { TempInfo[i].IsLoopback = true; continue; } // See if the current IP address is a local address, and if // so mark it as such. for (k = 0; k < ipLocalHostEntry.AddressList.Length; k++) { if (TempInfo[i].Address.Address == ipLocalHostEntry.AddressList[k].Address) { TempInfo[i].IsLoopback = true; break; } } } // // now look for connection group objects that don't have // an IP address associated with them. When it finds one, it updates // the IP address and tries to update the connection limit. // lock (this) { // Walk through the connection groups on this service // point, and update the ones we need to with an IP // address. // IDictionaryEnumerator CGEnumerator; CGEnumerator = m_ConnectionGroupList.GetEnumerator(); while (CGEnumerator.MoveNext()) { ConnectionGroup CurrentCG = (ConnectionGroup)CGEnumerator.Value; // If this connection group doesn't have an IP address // assigned to it, give it one. if (CurrentCG.RemoteIPAddress == null) { GlobalLog.Print("ServicePoint::UpdateConnectionGroupAddresses null CurrentCG.RemoteIPAddress"); // Update the address. CurrentCG.RemoteIPAddress = TempInfo[0].Address; // Now update the connection limit based on what we know. CurrentCG.InternalConnectionLimit = TempInfo[0].IsLoopback ? LoopbackConnectionLimit : m_ConnectionLimit; GlobalLog.Print("ServicePoint::UpdateConnectionGroupAddresses CurrentCG.InternalConnectionLimit:" + CurrentCG.InternalConnectionLimit.ToString()); } GlobalLog.Print("ServicePoint::UpdateConnectionGroupAddresses CurrentCG.RemoteIPAddress:" + CurrentCG.RemoteIPAddress.ToString()); } } IPHostEntryInfo ipAddressInfoList = new IPHostEntryInfo(TempInfo, ipHostEntry.HostName); return(ipAddressInfoList); }
public override void Close() { if (m_Closed) { return; } m_Closed = true; // // we need to flush ul in order to tell it that we have no more data // to send in the entity body, and if we're chunk-encoding we need to // send the trailer chunk // if (m_SendChunked == true) { // // send the trailer // } int DataWritten = 0; int result = ComNetOS.IsWinNt ? UlSysApi.UlSendEntityBody( m_AppPoolHandle, m_RequestId, 0, 0, IntPtr.Zero, ref DataWritten, IntPtr.Zero) : UlVxdApi.UlSendHttpResponseEntityBody( m_AppPoolHandle, m_RequestId, 0, 0, IntPtr.Zero, ref DataWritten, IntPtr.Zero); GlobalLog.Print("UlSendHttpResponseEntityBody(0) DataWritten: " + Convert.ToString(DataWritten)); // // ignore return value??? // if (result != NativeMethods.ERROR_SUCCESS && result != NativeMethods.ERROR_HANDLE_EOF) { GlobalLog.Print("sync UlSendHttpResponseEntityBody(0) failed, err#" + Convert.ToString(result)); // throw new InvalidOperationException( "UlSendHttpResponseEntityBody() failed, err#" + Convert.ToString( result ) ); } return; } // Close()
internal WebExceptionStatus ConnectSocket(Socket socket) { // // so, here we are: we have the EndPoint we need to connect to, all we // need to do is call into winsock and try to connect to this HTTP server. // // this is how we do it: // we'll keep trying to Connect() until either: // (1) Connect() succeeds (on which we increment the number of connections opened) or // (2) we can't get any new address for this host. // // (1) is pretty easy, here's how we do (2): // we decide that (2) is happening when, after a brand new DNS query, // all IPAddress fail to connect. to do so we keep count of how many // connections have been successfull to any of the addresses in the list // returned by DNS (if the host is an IPAddress we'll have a single address // in the list so if that fails the algorithm will still work). // // when we're out of addresses we call again (or for the first time) into DNS. // on DNS failure, of course, we will error out. // otherwise, after getting the list of addresses, as a result of our DNS query, // we reset the number of connections opened // using the last DNS query to 0. after that we start using all addresses // // // we need this for the call to connect() // // SECURITY: // Since we are doing WebRequest, we don't require SocketPermissions // (asserting them) // new SocketPermission(PermissionState.Unrestricted).Assert(); IPEndPoint ipEndPoint; IPAddressInfo ipAddressInfo = GetCurrentIPAddressInfo(); bool connectFailure = false; for (;;) { if (ipAddressInfo != null) { try { ipEndPoint = new IPEndPoint(ipAddressInfo.Address, m_Address.Port); GlobalLog.Print("ServicePoint::ConnectSocket() calling Connect() to:" + ipEndPoint.ToString()); socket.Connect(ipEndPoint); Interlocked.Increment(ref m_ConnectionsSinceDns); return(WebExceptionStatus.Success); } catch { connectFailure = true; } } // // on failure jump to the next available IPAddressInfo. if it's null // there has been a DNS failure or all connections failed. // ipAddressInfo = GetNextIPAddressInfo(); if (ipAddressInfo == null) { if (!connectFailure) { GlobalLog.Assert( !connectFailure, "connectFailure", ""); return(InternalProxyServicePoint ? WebExceptionStatus.ProxyNameResolutionFailure : WebExceptionStatus.NameResolutionFailure); } return(WebExceptionStatus.ConnectFailure); } } }
public HttpListenerException(int errorCode, string message) : base(errorCode, message) { GlobalLog.Print("HttpListenerException::.ctor(int) " + NativeErrorCode.ToString() + ":" + Message); }
private static bool Initialize() { // // on Win9x you have no PerfCounters // on NT4 PerfCounters are not writable // if (ComNetOS.IsWin9x || ComNetOS.IsWinNt4) { return(false); } // // this is an internal class, we need to update performance counters // on behalf of the user to log perf data on network activity // // Consider V.Next: Change to declarative form (10x faster) but // PerformanceCounterPermission must be moved out of System.dll PerformanceCounterPermission perfCounterPermission = new PerformanceCounterPermission(PermissionState.Unrestricted); perfCounterPermission.Assert(); bool successStatus = false; try { // // create the counters, this will check for the right permissions (false) // means the counter is not readonly (it's read/write) and cache them while // we're under the Assert(), which will be reverted in the finally below. // GlobalConnectionsEstablished = new PerformanceCounter(CategoryName, ConnectionsEstablishedName, Global, false); // // if I created the first counter succesfully, then I'll return // true. otherwise I'll return false, since none of the counters will // be created, hence non of them should be updated. // successStatus = true; GlobalBytesReceived = new PerformanceCounter(CategoryName, BytesReceivedName, Global, false); GlobalBytesSent = new PerformanceCounter(CategoryName, BytesSentName, Global, false); GlobalDatagramsReceived = new PerformanceCounter(CategoryName, DatagramsReceivedName, Global, false); GlobalDatagramsSent = new PerformanceCounter(CategoryName, DatagramsSentName, Global, false); ConnectionsEstablished = new PerformanceCounter(CategoryName, ConnectionsEstablishedName, false); BytesReceived = new PerformanceCounter(CategoryName, BytesReceivedName, false); BytesSent = new PerformanceCounter(CategoryName, BytesSentName, false); DatagramsReceived = new PerformanceCounter(CategoryName, DatagramsReceivedName, false); DatagramsSent = new PerformanceCounter(CategoryName, DatagramsSentName, false); #if COMNET_HTTPPERFCOUNTER // jruiz: If you need to use this counters, you will have to change the files // _NetworkingPerfCounters.ini // _NetworkingPerfCounters.h GlobalHttpWebRequestCreated = new PerformanceCounter(CategoryName, HttpWebRequestCreatedName, false); GlobalHttpWebRequestCollected = new PerformanceCounter(CategoryName, HttpWebRequestCollectedName, Global, false); HttpWebRequestCreated = new PerformanceCounter(CategoryName, HttpWebRequestCreatedName, false); HttpWebRequestCollected = new PerformanceCounter(CategoryName, HttpWebRequestCollectedName, Global, false); #endif // COMNET_HTTPPERFCOUNTER } catch (Exception exception) { GlobalLog.Print("NetworkingPerfCounters::NetworkingPerfCounters() instantiation failure:" + exception.Message); } finally { PerformanceCounterPermission.RevertAssert(); } // // we will return false if none of the counters was created. true // if at least the first one was, ignoring subsequent failures. // we don't expect the counters to fail individually, if the first // one fails we'd expect all of them to fails, if the first one // succeeds, wed' expect all of them to succeed. // return(successStatus); }