internal string FindProxyForURL(string url, string host) { if (url == null || host == null) { throw new ArgumentNullException(url == null ? "url" : "host"); } if (closed != 0) { throw new ObjectDisposedException(GetType().Name); } EXCEPINFO exceptionInfo = new EXCEPINFO(); object result = null; jscript.GetCurrentScriptThreadID(out interruptThreadId); TimerThread.Timer timer = s_TimerQueue.CreateTimer(s_InterruptCallback, this); activeTimer = timer; try { GlobalLog.Print("AutoWebProxyScriptWrapper#" + ValidationHelper.HashString(this) + "::FindProxyForURL() Calling url:" + url + " host:" + host); result = script.FindProxyForURL(url, host); } 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) + "::FindProxyForURL() Script error:[" + this.host.ExceptionMessage == null ? "" : this.host.ExceptionMessage + "]"); } catch { GlobalLog.Print("AutoWebProxyScriptWrapper#" + ValidationHelper.HashString(this) + "::FindProxyForURL() Script error:[Non-CLS Compliant Exception]"); throw; } finally { activeTimer = null; timer.Cancel(); } string proxy = result as string; if (proxy != null) { GlobalLog.Print("AutoWebProxyScriptWrapper#" + ValidationHelper.HashString(this) + "::FindProxyForURL() found:" + proxy); return(proxy); } GlobalLog.Print("AutoWebProxyScriptWrapper#" + ValidationHelper.HashString(this) + "::FindProxyForURL() Returning null. result:" + ValidationHelper.ToString(exceptionInfo.bstrDescription) + " result:" + ValidationHelper.ToString(result) + " error:" + ValidationHelper.ToString(exceptionInfo.bstrDescription)); return(null); }
public override int EndRead(IAsyncResult asyncResult) { if (asyncResult == null) { throw new ArgumentNullException("asyncResult"); } try{ return(base.EndRead(asyncResult)); } catch (Exception e) { try{ if (NclUtilities.IsFatal(e)) { throw; } if (e is System.IO.InvalidDataException || e is InvalidOperationException || e is IndexOutOfRangeException) { Close(); } } catch { } throw e; } }
public override int Read(byte[] buffer, int offset, int size) { if (buffer == null) { throw new ArgumentNullException("buffer"); } if (offset < 0 || offset > buffer.Length) { throw new ArgumentOutOfRangeException("offset"); } if (size < 0 || size > buffer.Length - offset) { throw new ArgumentOutOfRangeException("size"); } try{ return(base.Read(buffer, offset, size)); } catch (Exception e) { try{ if (NclUtilities.IsFatal(e)) { throw; } if (e is System.IO.InvalidDataException || e is InvalidOperationException || e is IndexOutOfRangeException) { Close(); } } catch { } throw e; } }
private static void InterruptCallback(TimerThread.Timer timer, int timeNoticed, object context) { AutoWebProxyScriptWrapper pThis = (AutoWebProxyScriptWrapper)context; GlobalLog.Print("AutoWebProxyScriptWrapper#" + ValidationHelper.HashString(pThis) + "::InterruptCallback()"); if (!object.ReferenceEquals(timer, pThis.activeTimer)) { GlobalLog.Print("AutoWebProxyScriptWrapper#" + ValidationHelper.HashString(pThis) + "::InterruptCallback() Spurious - returning."); return; } EXCEPINFO exceptionInfo; try { pThis.jscript.InterruptScriptThread(pThis.interruptThreadId, out exceptionInfo, 0); } catch (Exception ex) { if (NclUtilities.IsFatal(ex)) { throw; } GlobalLog.Print("AutoWebProxyScriptWrapper#" + ValidationHelper.HashString(pThis) + "::InterruptCallback() InterruptScriptThread() threw:" + ValidationHelper.ToString(ex)); } catch { GlobalLog.Print("AutoWebProxyScriptWrapper#" + ValidationHelper.HashString(pThis) + "::InterruptCallback() InterruptScriptThread() threw: Non-CLS Compliant Exception"); } }
private static void CloseAppDomainCallback(TimerThread.Timer timer, int timeNoticed, object context) { try { AppDomain domain = context as AppDomain; if (domain == null) { CloseAppDomain((int)context); } else { if (object.ReferenceEquals(domain, s_ExcessAppDomain)) { try { AppDomain.Unload(domain); } catch (AppDomainUnloadedException) { } s_ExcessAppDomain = null; } } } catch (Exception exception) { if (NclUtilities.IsFatal(exception)) { throw; } } }
internal void ClearSession(HttpWebRequest httpWebRequest) { PrepareState(httpWebRequest); ISessionAuthenticationModule myModule = Module as ISessionAuthenticationModule; Module = null; if (myModule != null) { try { myModule.ClearSession(httpWebRequest); } catch (Exception exception) { if (NclUtilities.IsFatal(exception)) { throw; } GlobalLog.Print("AuthenticationState#" + ValidationHelper.HashString(this) + "::ClearSession() " + myModule.ToString() + ".Update() caught exception:" + exception.Message); } catch { GlobalLog.Print("AuthenticationState#" + ValidationHelper.HashString(this) + "::ClearSession() " + myModule.ToString() + ".Update() caught exception: Non-CLS Compliant Exception"); } } }
public override int EndRead(IAsyncResult asyncResult) { int num; if (asyncResult == null) { throw new ArgumentNullException("asyncResult"); } try { num = base.EndRead(asyncResult); } catch (Exception exception) { try { if (NclUtilities.IsFatal(exception)) { throw; } if (((exception is InvalidDataException) || (exception is InvalidOperationException)) || (exception is IndexOutOfRangeException)) { this.Close(); } } catch { } throw exception; } return(num); }
public override IAsyncResult BeginRead(byte[] buffer, int offset, int size, AsyncCallback callback, Object state) { if (buffer==null) { throw new ArgumentNullException("buffer"); } if (offset<0 || offset>buffer.Length) { throw new ArgumentOutOfRangeException("offset"); } if (size<0 || size>buffer.Length-offset) { throw new ArgumentOutOfRangeException("size"); } try{ return base.BeginRead(buffer, offset, size, callback, state); } catch(Exception e){ try{ if (NclUtilities.IsFatal(e)) throw; if(e is System.IO.InvalidDataException || e is InvalidOperationException || e is IndexOutOfRangeException){ Close(); } } catch{ } throw e; } }
// // this method runs in the context of the user Begin call . // private static void WrappedGetRequestStreamCallback(object state) { GlobalLog.Enter("FileWebRequest::GetRequestStreamCallback"); ContextAwareResult asyncResult = (ContextAwareResult)state; FileWebRequest request = (FileWebRequest)asyncResult.AsyncObject; try { if (request.m_stream == null) { request.m_stream = new FileWebStream(request, request.m_uri.LocalPath, FileMode.Create, FileAccess.Write, FileShare.Read); request.m_fileAccess = FileAccess.Write; request.m_writing = true; asyncResult.InvokeCallback(request.m_stream); GlobalLog.Leave("FileWebRequest::GetRequestStreamCallback"); } } catch (Exception e) { if (asyncResult.IsCompleted || NclUtilities.IsFatal(e)) { throw; } Exception ex = new WebException(e.Message, e); GlobalLog.LeaveException("FileWebRequest::GetRequestStreamCallback", ex); asyncResult.InvokeCallback(ex); } }
// // // internal string GetComputeSpn(HttpWebRequest httpWebRequest) { if (ChallengedSpn != null) { return(ChallengedSpn); } string spnKey = httpWebRequest.ChallengedUri.GetParts(UriComponents.Scheme | UriComponents.Host | UriComponents.Port | UriComponents.Path, UriFormat.SafeUnescaped); string spn = AuthenticationManager.SpnDictionary.InternalGet(spnKey); if (spn == null) { if (!IsProxyAuth && httpWebRequest.ServicePoint.InternalProxyServicePoint) { // Here the NT-Security folks need us to attempt a DNS lookup to figure out // the FQDN. only do the lookup for short names (no IP addresses or DNS names) // // Initialize a backup value spn = httpWebRequest.ChallengedUri.Host; if (httpWebRequest.ChallengedUri.HostNameType != UriHostNameType.IPv6 && httpWebRequest.ChallengedUri.HostNameType != UriHostNameType.IPv4 && spn.IndexOf('.') == -1) { try { // spn = Dns.InternalGetHostByName(spn).HostName; GlobalLog.Print("AuthenticationState#" + ValidationHelper.HashString(this) + "::GetComputeSpn() Dns returned host:" + ValidationHelper.ToString(spn)); } catch (Exception exception) { if (NclUtilities.IsFatal(exception)) { throw; } GlobalLog.Print("AuthenticationState#" + ValidationHelper.HashString(this) + "::GetComputeSpn() GetHostByName(host) failed:" + ValidationHelper.ToString(exception)); } } } else { // For this cases we already did a DNS lookup // spn = httpWebRequest.ServicePoint.Hostname; } spn = "HTTP/" + spn; spnKey = httpWebRequest.ChallengedUri.GetParts(UriComponents.SchemeAndServer, UriFormat.SafeUnescaped) + "/"; AuthenticationManager.SpnDictionary.InternalSet(spnKey, spn); } return(ChallengedSpn = spn); }
private void ListenForRegistryHelper(ref SafeRegistryHandle key, ref AutoResetEvent changeEvent, IntPtr baseKey, string subKey) { uint num = 0; if ((key == null) || key.IsInvalid) { if (baseKey == IntPtr.Zero) { if (this.hkcu != null) { num = this.hkcu.RegOpenKeyEx(subKey, 0, 0x20019, out key); } else { num = 0x490; } } else { num = SafeRegistryHandle.RegOpenKeyEx(baseKey, subKey, 0, 0x20019, out key); } if (num == 0) { changeEvent = new AutoResetEvent(false); } } if (num == 0) { num = key.RegNotifyChangeKeyValue(true, 4, changeEvent.SafeWaitHandle, true); } if (num != 0) { if ((key != null) && !key.IsInvalid) { try { num = key.RegCloseKey(); } catch (Exception exception) { if (NclUtilities.IsFatal(exception)) { throw; } } } key = null; if (changeEvent != null) { changeEvent.Close(); changeEvent = null; } } }
private static bool IsAddressListLoopback(IPAddress[] addressList) { IPAddress[] localAddresses = null; try { localAddresses = NclUtilities.LocalAddresses; } catch (Exception exception) { if (NclUtilities.IsFatal(exception)) { throw; } if (Logging.On) { Logging.PrintError(Logging.Web, SR.GetString("net_log_retrieving_localhost_exception", new object[] { exception })); Logging.PrintWarning(Logging.Web, SR.GetString("net_log_resolved_servicepoint_may_not_be_remote_server")); } } int index = 0; while (index < addressList.Length) { if (!IPAddress.IsLoopback(addressList[index])) { if (localAddresses == null) { break; } int num2 = 0; while (num2 < localAddresses.Length) { if (addressList[index].Equals(localAddresses[num2])) { break; } num2++; } if (num2 >= localAddresses.Length) { break; } } index++; } return(index == addressList.Length); }
internal bool Fire() { if (this.m_TimerState == TimerState.Ready) { int tickCount = Environment.TickCount; if (TimerThread.IsTickBetween(base.StartTime, base.Expiration, tickCount)) { return(false); } bool flag = false; lock (this.m_QueueLock) { if (this.m_TimerState == TimerState.Ready) { this.m_TimerState = TimerState.Fired; this.Next.Prev = this.Prev; this.Prev.Next = this.Next; this.Next = null; this.Prev = null; flag = this.m_Callback != null; } } if (flag) { try { TimerThread.Callback callback = this.m_Callback; object context = this.m_Context; this.m_Callback = null; this.m_Context = null; callback(this, tickCount, context); } catch (Exception exception) { if (NclUtilities.IsFatal(exception)) { throw; } if (Logging.On) { Logging.PrintError(Logging.Web, "TimerThreadTimer#" + base.StartTime.ToString(NumberFormatInfo.InvariantInfo) + "::Fire() - " + SR.GetString("net_log_exception_in_callback", new object[] { exception })); } } } } return(true); }
// // this method runs in the context of the user Begin call . // private static void WrappedGetResponseCallback(object state) { GlobalLog.Enter("FileWebRequest::GetResponseCallback"); ContextAwareResult asyncResult = (ContextAwareResult)state; FileWebRequest request = (FileWebRequest)asyncResult.AsyncObject; if (request.m_writePending || request.m_writing) { lock (request) { if (request.m_writePending || request.m_writing) { request.m_readerEvent = new ManualResetEvent(false); } } } if (request.m_readerEvent != null) { request.m_readerEvent.WaitOne(); } try { if (request.m_response == null) { request.m_response = new FileWebResponse(request, request.m_uri, request.m_fileAccess, !request.m_syncHint); } GlobalLog.Leave("FileWebRequest::GetResponseCallback"); asyncResult.InvokeCallback(request.m_response); } catch (Exception e) { if (asyncResult.IsCompleted || NclUtilities.IsFatal(e)) { throw; } Exception ex = new WebException(e.Message, e); GlobalLog.LeaveException("FileWebRequest::GetResponseCallback", ex); asyncResult.InvokeCallback(ex); } }
private static T TryInitialize <T>(Func <T, T> loadConfiguration, T fallbackDefault) { T ret; try { ret = loadConfiguration(fallbackDefault); } catch (Exception e) { if (NclUtilities.IsFatal(e)) { throw; } Debug.Fail("ServicePointManager.TryInitialize failed with exception", e.ToString()); ret = fallbackDefault; } return(ret); }
internal void ClearSession(HttpWebRequest httpWebRequest) { this.PrepareState(httpWebRequest); ISessionAuthenticationModule module = this.Module as ISessionAuthenticationModule; this.Module = null; if (module != null) { try { module.ClearSession(httpWebRequest); } catch (Exception exception) { if (NclUtilities.IsFatal(exception)) { throw; } } } }
internal virtual void ConnectionCallback(object owningObject, Exception e, Socket socket, IPAddress address) { GlobalLog.Assert(owningObject == Owner || Owner == null, "PooledStream::ConnectionCallback|Owner is not the same as expected."); object result = null; if (e != null) { m_Initalizing = false; result = e; } else { try { if (Logging.On) { Logging.PrintInfo(Logging.Web, this, SR.GetString(SR.net_log_socket_connected, socket.LocalEndPoint, socket.RemoteEndPoint)); } m_NetworkStream.InitNetworkStream(socket, FileAccess.ReadWrite); result = this; } catch (Exception ex) { if (NclUtilities.IsFatal(ex)) { throw; } result = ex; } m_ServerAddress = address; m_Initalizing = false; m_JustConnected = true; } if (m_AsyncCallback != null) { m_AsyncCallback(owningObject, result); } m_AbortSocket = null; m_AbortSocket6 = null; }
public override int Read(byte[] buffer, int offset, int size) { int num; if (buffer == null) { throw new ArgumentNullException("buffer"); } if ((offset < 0) || (offset > buffer.Length)) { throw new ArgumentOutOfRangeException("offset"); } if ((size < 0) || (size > (buffer.Length - offset))) { throw new ArgumentOutOfRangeException("size"); } try { num = base.Read(buffer, offset, size); } catch (Exception exception) { try { if (NclUtilities.IsFatal(exception)) { throw; } if (((exception is InvalidDataException) || (exception is InvalidOperationException)) || (exception is IndexOutOfRangeException)) { this.Close(); } } catch { } throw exception; } return(num); }
public override IAsyncResult BeginRead(byte[] buffer, int offset, int size, AsyncCallback callback, object state) { IAsyncResult result; if (buffer == null) { throw new ArgumentNullException("buffer"); } if ((offset < 0) || (offset > buffer.Length)) { throw new ArgumentOutOfRangeException("offset"); } if ((size < 0) || (size > (buffer.Length - offset))) { throw new ArgumentOutOfRangeException("size"); } try { result = base.BeginRead(buffer, offset, size, callback, state); } catch (Exception exception) { try { if (NclUtilities.IsFatal(exception)) { throw; } if (((exception is InvalidDataException) || (exception is InvalidOperationException)) || (exception is IndexOutOfRangeException)) { this.Close(); } } catch { } throw exception; } return(result); }
internal virtual void ConnectionCallback(object owningObject, Exception e, System.Net.Sockets.Socket socket, IPAddress address) { object state = null; if (e != null) { this.m_Initalizing = false; state = e; } else { try { if (Logging.On) { Logging.PrintInfo(Logging.Web, this, SR.GetString("net_log_socket_connected", new object[] { socket.LocalEndPoint, socket.RemoteEndPoint })); } this.m_NetworkStream.InitNetworkStream(socket, FileAccess.ReadWrite); state = this; } catch (Exception exception) { if (NclUtilities.IsFatal(exception)) { throw; } state = exception; } this.m_ServerAddress = address; this.m_Initalizing = false; this.m_JustConnected = true; } if (this.m_AsyncCallback != null) { this.m_AsyncCallback(owningObject, state); } this.m_AbortSocket = null; this.m_AbortSocket6 = null; }
internal string GetComputeSpn(HttpWebRequest httpWebRequest) { if (this.ChallengedSpn != null) { return(this.ChallengedSpn); } string parts = httpWebRequest.ChallengedUri.GetParts(UriComponents.Path | UriComponents.SchemeAndServer, UriFormat.SafeUnescaped); string hostName = AuthenticationManager.SpnDictionary.InternalGet(parts); if (hostName == null) { if (!this.IsProxyAuth && (httpWebRequest.ServicePoint.InternalProxyServicePoint || httpWebRequest.UseCustomHost)) { hostName = httpWebRequest.ChallengedUri.Host; if (((httpWebRequest.ChallengedUri.HostNameType != UriHostNameType.IPv6) && (httpWebRequest.ChallengedUri.HostNameType != UriHostNameType.IPv4)) && (hostName.IndexOf('.') == -1)) { try { hostName = Dns.InternalGetHostByName(hostName).HostName; } catch (Exception exception) { if (NclUtilities.IsFatal(exception)) { throw; } } } } else { hostName = httpWebRequest.ServicePoint.Hostname; } hostName = "HTTP/" + hostName; parts = httpWebRequest.ChallengedUri.GetParts(UriComponents.SchemeAndServer, UriFormat.SafeUnescaped) + "/"; AuthenticationManager.SpnDictionary.InternalSet(parts, hostName); } return(this.ChallengedSpn = hostName); }
internal void CloseAsIs() { RuntimeHelpers.PrepareConstrainedRegions(); try { } finally { #if DEBUG // If this throws it could be very bad. try { #endif InnerSafeCloseSocket innerSocket = m_InnerSocket == null ? null : Interlocked.Exchange <InnerSafeCloseSocket>(ref m_InnerSocket, null); Close(); if (innerSocket != null) { // Wait until it's safe. while (!m_Released) { Thread.SpinWait(1); } // Now free it with blocking. innerSocket.BlockingRelease(); } #if DEBUG } catch (Exception exception) { if (!NclUtilities.IsFatal(exception)) { GlobalLog.Assert("SafeCloseSocket::CloseAsIs(handle:" + handle.ToString("x") + ")", exception.Message); } throw; } #endif } }
// This method is implicitly reliable and called from a CER. protected override bool ReleaseHandle() { bool ret = false; #if DEBUG try { #endif GlobalLog.Print("SafeCloseSocket::ReleaseHandle(handle:" + handle.ToString("x") + ")"); SocketError errorCode; // If m_Blockable was set in BlockingRelease, it's safe to block here, which means // we can honor the linger options set on the socket. It also means closesocket() might return WSAEWOULDBLOCK, in which // case we need to do some recovery. if (m_Blockable) { GlobalLog.Print("SafeCloseSocket::ReleaseHandle(handle:" + handle.ToString("x") + ") Following 'blockable' branch."); errorCode = UnsafeNclNativeMethods.SafeNetHandles.closesocket(handle); #if DEBUG m_CloseSocketHandle = handle; m_CloseSocketResult = errorCode; #endif if (errorCode == SocketError.SocketError) { errorCode = (SocketError)Marshal.GetLastWin32Error(); } GlobalLog.Print("SafeCloseSocket::ReleaseHandle(handle:" + handle.ToString("x") + ") closesocket()#1:" + errorCode.ToString()); // If it's not WSAEWOULDBLOCK, there's no more recourse - we either succeeded or failed. if (errorCode != SocketError.WouldBlock) { return(ret = errorCode == SocketError.Success); } // The socket must be non-blocking with a linger timeout set. // We have to set the socket to blocking. int nonBlockCmd = 0; errorCode = UnsafeNclNativeMethods.SafeNetHandles.ioctlsocket( handle, IoctlSocketConstants.FIONBIO, ref nonBlockCmd); if (errorCode == SocketError.SocketError) { errorCode = (SocketError)Marshal.GetLastWin32Error(); } GlobalLog.Print("SafeCloseSocket::ReleaseHandle(handle:" + handle.ToString("x") + ") ioctlsocket()#1:" + errorCode.ToString()); // This can fail if there's a pending WSAEventSelect. Try canceling it. if (errorCode == SocketError.InvalidArgument) { errorCode = UnsafeNclNativeMethods.SafeNetHandles.WSAEventSelect( handle, IntPtr.Zero, AsyncEventBits.FdNone); GlobalLog.Print("SafeCloseSocket::ReleaseHandle(handle:" + handle.ToString("x") + ") WSAEventSelect():" + (errorCode == SocketError.SocketError ? (SocketError)Marshal.GetLastWin32Error() : errorCode).ToString()); // Now retry the ioctl. errorCode = UnsafeNclNativeMethods.SafeNetHandles.ioctlsocket( handle, IoctlSocketConstants.FIONBIO, ref nonBlockCmd); GlobalLog.Print("SafeCloseSocket::ReleaseHandle(handle:" + handle.ToString("x") + ") ioctlsocket#2():" + (errorCode == SocketError.SocketError ? (SocketError)Marshal.GetLastWin32Error() : errorCode).ToString()); } // If that succeeded, try again. if (errorCode == SocketError.Success) { errorCode = UnsafeNclNativeMethods.SafeNetHandles.closesocket(handle); #if DEBUG m_CloseSocketHandle = handle; m_CloseSocketResult = errorCode; #endif if (errorCode == SocketError.SocketError) { errorCode = (SocketError)Marshal.GetLastWin32Error(); } GlobalLog.Print("SafeCloseSocket::ReleaseHandle(handle:" + handle.ToString("x") + ") closesocket#2():" + errorCode.ToString()); // If it's not WSAEWOULDBLOCK, there's no more recourse - we either succeeded or failed. if (errorCode != SocketError.WouldBlock) { return(ret = errorCode == SocketError.Success); } } // It failed. Fall through to the regular abortive close. } // By default or if CloseAsIs() path failed, set linger timeout to zero to get an abortive close (RST). Linger lingerStruct; lingerStruct.OnOff = 1; lingerStruct.Time = (short)0; errorCode = UnsafeNclNativeMethods.SafeNetHandles.setsockopt( handle, SocketOptionLevel.Socket, SocketOptionName.Linger, ref lingerStruct, Linger.Size); #if DEBUG m_CloseSocketLinger = errorCode; #endif if (errorCode == SocketError.SocketError) { errorCode = (SocketError)Marshal.GetLastWin32Error(); } GlobalLog.Print("SafeCloseSocket::ReleaseHandle(handle:" + handle.ToString("x") + ") setsockopt():" + errorCode.ToString()); if (errorCode != SocketError.Success && errorCode != SocketError.InvalidArgument && errorCode != SocketError.ProtocolOption) { // Too dangerous to try closesocket() - it might block! return(ret = false); } errorCode = UnsafeNclNativeMethods.SafeNetHandles.closesocket(handle); #if DEBUG m_CloseSocketHandle = handle; m_CloseSocketResult = errorCode; #endif GlobalLog.Print("SafeCloseSocket::ReleaseHandle(handle:" + handle.ToString("x") + ") closesocket#3():" + (errorCode == SocketError.SocketError ? (SocketError)Marshal.GetLastWin32Error() : errorCode).ToString()); return(ret = errorCode == SocketError.Success); #if DEBUG } catch (Exception exception) { if (!NclUtilities.IsFatal(exception)) { GlobalLog.Assert("SafeCloseSocket::ReleaseHandle(handle:" + handle.ToString("x") + ")", exception.Message); } ret = true; // Avoid a second assert. throw; } finally { m_CloseSocketThread = Thread.CurrentThread.ManagedThreadId; m_CloseSocketTick = Environment.TickCount; GlobalLog.Assert(ret, "SafeCloseSocket::ReleaseHandle(handle:{0:x})|ReleaseHandle failed.", handle); } #endif }
private static unsafe void WaitCallback(uint errorCode, uint numBytes, NativeOverlapped *nativeOverlapped) { ListenerAsyncResult asyncResult = (ListenerAsyncResult)Overlapped.Unpack(nativeOverlapped).AsyncResult; object result = null; try { if ((errorCode != 0) && (errorCode != 0xea)) { asyncResult.ErrorCode = (int)errorCode; result = new HttpListenerException((int)errorCode); } else { HttpListener asyncObject = asyncResult.AsyncObject as HttpListener; if (errorCode == 0) { bool stoleBlob = false; try { result = asyncObject.HandleAuthentication(asyncResult.m_RequestContext, out stoleBlob); } finally { if (stoleBlob) { asyncResult.m_RequestContext = (result == null) ? new AsyncRequestContext(asyncResult) : null; } else { asyncResult.m_RequestContext.Reset(0L, 0); } } } else { asyncResult.m_RequestContext.Reset(asyncResult.m_RequestContext.RequestBlob.RequestId, numBytes); } if (result == null) { uint num = asyncResult.QueueBeginGetContext(); if ((num != 0) && (num != 0x3e5)) { result = new HttpListenerException((int)num); } } if (result == null) { return; } } } catch (Exception exception) { if (NclUtilities.IsFatal(exception)) { throw; } result = exception; } asyncResult.InvokeCallback(result); }
private bool ReadRegSettings() { SafeRegistryHandle key = null; RegistryKey lmKey = null; try { bool isPerUser = true; lmKey = Registry.LocalMachine.OpenSubKey(PolicyKey); if (lmKey != null) { object perUser = lmKey.GetValue(ProxySettingsPerUser); if (perUser != null && perUser.GetType() == typeof(int) && 0 == (int)perUser) { isPerUser = false; } } uint errorCode; if (isPerUser) { if (m_Registry != null) { errorCode = m_Registry.RegOpenKeyEx(ProxyKey, 0, UnsafeNclNativeMethods.RegistryHelper.KEY_READ, out key); } else { errorCode = UnsafeNclNativeMethods.ErrorCodes.ERROR_NOT_FOUND; } } else { errorCode = SafeRegistryHandle.RegOpenKeyEx(UnsafeNclNativeMethods.RegistryHelper.HKEY_LOCAL_MACHINE, ProxyKey, 0, UnsafeNclNativeMethods.RegistryHelper.KEY_READ, out key); } if (errorCode != UnsafeNclNativeMethods.ErrorCodes.ERROR_SUCCESS) { key = null; } if (key != null) { // When reading settings from the registry, if connectoid key is missing, the connectoid // was never configured. In this case we have no settings (this is equivalent to always go direct). object data; errorCode = key.QueryValue(m_Connectoid != null ? m_Connectoid : DefaultConnectionSettings, out data); if (errorCode == UnsafeNclNativeMethods.ErrorCodes.ERROR_SUCCESS) { m_RegistryBytes = (byte[])data; } } } catch (Exception exception) { if (NclUtilities.IsFatal(exception)) { throw; } } finally { if (lmKey != null) { lmKey.Close(); } if (key != null) { key.RegCloseKey(); } } return(m_RegistryBytes != null); }
/// <summary> /// <para>Thread for the timer. Swallows 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 }
/// <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); }
private IPAddress[] GetIPAddressInfoList(out int currentIndex, IPAddress[] addresses, int timeout, out bool timedOut) { IPHostEntry ipHostEntry = null; currentIndex = 0; bool flag = false; bool flag2 = false; timedOut = false; lock (this) { if (((addresses != null) && !this.m_ConnectedSinceDns) && (!this.m_AddressListFailed && (addresses == this.m_IPAddressInfoList))) { return(null); } if (((this.m_IPAddressInfoList == null) || this.m_AddressListFailed) || ((addresses == this.m_IPAddressInfoList) || this.HasTimedOut)) { this.m_CurrentAddressInfoIndex = 0; this.m_ConnectedSinceDns = false; this.m_AddressListFailed = false; this.m_LastDnsResolve = DateTime.UtcNow; flag = true; } } if (flag) { try { ipHostEntry = Dns.InternalResolveFast(this.m_Host, timeout, out timedOut); if (timedOut) { flag2 = true; } } catch (Exception exception) { if (NclUtilities.IsFatal(exception)) { throw; } flag2 = true; } } lock (this) { if (flag) { this.m_IPAddressInfoList = null; if ((!flag2 && (ipHostEntry != null)) && ((ipHostEntry.AddressList != null) && (ipHostEntry.AddressList.Length > 0))) { this.SetAddressList(ipHostEntry); } } if ((this.m_IPAddressInfoList != null) && (this.m_IPAddressInfoList.Length > 0)) { currentIndex = this.m_CurrentAddressInfoIndex; if (ServicePointManager.EnableDnsRoundRobin) { this.m_CurrentAddressInfoIndex++; if (this.m_CurrentAddressInfoIndex >= this.m_IPAddressInfoList.Length) { this.m_CurrentAddressInfoIndex = 0; } } return(this.m_IPAddressInfoList); } } return(null); }
// // // internal SpnToken GetComputeSpn(HttpWebRequest httpWebRequest) { if (ChallengedSpn != null) { return(ChallengedSpn); } bool trustNewHost = true; // Assume trusted unless proven otherwise string spnKey = httpWebRequest.ChallengedUri.GetParts(UriComponents.Scheme | UriComponents.Host | UriComponents.Port | UriComponents.Path, UriFormat.SafeUnescaped); SpnToken spnToken = AuthenticationManager.SpnDictionary.InternalGet(spnKey); if (spnToken == null || spnToken.Spn == null) { string host; if (!IsProxyAuth && (httpWebRequest.ServicePoint.InternalProxyServicePoint || httpWebRequest.UseCustomHost)) { // Here the NT-Security folks need us to attempt a DNS lookup to figure out // the FQDN. only do the lookup for short names (no IP addresses or DNS names) // // Initialize a backup value host = httpWebRequest.ChallengedUri.Host; // This host comes from the request/user, assume Trusted unless proven otherwise. if (httpWebRequest.ChallengedUri.HostNameType != UriHostNameType.IPv6 && httpWebRequest.ChallengedUri.HostNameType != UriHostNameType.IPv4 && host.IndexOf('.') == -1) { try { // IPHostEntry result; if (Dns.TryInternalResolve(host, out result)) { host = result.HostName; trustNewHost &= result.isTrustedHost; // Can only lose trust } } catch (Exception exception) { if (NclUtilities.IsFatal(exception)) { throw; } GlobalLog.Print("AuthenticationState#" + ValidationHelper.HashString(this) + "::GetComputeSpn() GetHostByName(host) failed:" + ValidationHelper.ToString(exception)); } } } else { // For this cases we already did a DNS lookup // host = httpWebRequest.ServicePoint.Hostname; trustNewHost &= httpWebRequest.ServicePoint.IsTrustedHost; // Can only lose trust } string spn = "HTTP/" + host; spnKey = httpWebRequest.ChallengedUri.GetParts(UriComponents.SchemeAndServer, UriFormat.SafeUnescaped) + "/"; spnToken = new SpnToken(spn, trustNewHost); AuthenticationManager.SpnDictionary.InternalSet(spnKey, spnToken); } ChallengedSpn = spnToken; return(ChallengedSpn); }
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); }