/// <summary> /// Main program function /// </summary> private void UpdateAwb() { try { Proxy = WebRequest.GetSystemWebProxy(); if (Proxy.IsBypassed(new Uri("http://en.wikipedia.org"))) { Proxy = null; } UpdateUI("Getting current AWB and Updater versions", true); AWBVersion(); if ((!UpdaterUpdate && !AWBUpdate) && string.IsNullOrEmpty(AWBWebAddress)) { ExitEarly(); } else { UpdateUI("Creating a temporary directory", true); CreateTempDir(); UpdateUI("Downloading AWB", true); GetAwbFromInternet(); UpdateUI("Unzipping AWB to the temporary directory", true); UnzipAwb(); UpdateUI("Making sure AWB is closed", true); CloseAwb(); UpdateUI("Copying AWB files from temp to AWB directory...", true); CopyFiles(); UpdateUI("Update successful", true); UpdateUI("Cleaning up from update", true); KillTempDir(); UpdateSucessful = true; ReadyToExit(); } } catch (AbortException) { ReadyToExit(); } catch (Exception ex) { ErrorHandler.Handle(ex); } }
public static bool IsEmpty(this IWebProxy proxy, Uri destination) { if (proxy is null) { return(true); } // Under .NET Framework, "GetProxy" returns the passed URI if it is not proxied. // Under .NET Core+, "GetProxy" returns null if the URI is not proxied. return(proxy.IsBypassed(destination) || (proxy.GetProxy(destination)?.Equals(destination) ?? true)); }
/// <summary> /// This function will connect a stream to a uri (host and port), /// negotiating proxies and SSL /// </summary> /// <param name="uri"></param> /// <param name="timeout_ms">Timeout, in ms. 0 for no timeout.</param> /// <returns></returns> public static Stream ConnectStream(Uri uri, IWebProxy proxy, bool nodelay, int timeout_ms) { IMockWebProxy mockProxy = proxy != null ? proxy as IMockWebProxy : null; if (mockProxy != null) { return(mockProxy.GetStream(uri)); } Stream stream; bool useProxy = proxy != null && !proxy.IsBypassed(uri); if (useProxy) { Uri proxyURI = proxy.GetProxy(uri); stream = ConnectSocket(proxyURI, nodelay, timeout_ms); } else { stream = ConnectSocket(uri, nodelay, timeout_ms); } try { if (useProxy) { string line = String.Format("CONNECT {0}:{1} HTTP/1.0", uri.Host, uri.Port); WriteLine(line, stream); WriteLine(stream); ReadHttpHeaders(ref stream, proxy, nodelay, timeout_ms); } if (UseSSL(uri)) { SslStream sslStream = new SslStream(stream, false, new RemoteCertificateValidationCallback(ValidateServerCertificate), null); sslStream.AuthenticateAsClient("", null, SslProtocols.Tls | SslProtocols.Tls11 | SslProtocols.Tls12, true); stream = sslStream; } return(stream); } catch { stream.Close(); throw; } }
/// <summary>Finds an existing <see cref="T:System.Net.ServicePoint" /> object or creates a new <see cref="T:System.Net.ServicePoint" /> object to manage communications with the specified <see cref="T:System.Uri" /> object.</summary> /// <returns>The <see cref="T:System.Net.ServicePoint" /> object that manages communications for the request.</returns> /// <param name="address">A <see cref="T:System.Uri" /> object that contains the address of the Internet resource to contact. </param> /// <param name="proxy">The proxy data for this request. </param> /// <exception cref="T:System.ArgumentNullException"> /// <paramref name="address" /> is null. </exception> /// <exception cref="T:System.InvalidOperationException">The maximum number of <see cref="T:System.Net.ServicePoint" /> objects defined in <see cref="P:System.Net.ServicePointManager.MaxServicePoints" /> has been reached. </exception> /// <PermissionSet> /// <IPermission class="System.Security.Permissions.FileIOPermission, mscorlib, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" version="1" Unrestricted="true" /> /// <IPermission class="System.Security.Permissions.SecurityPermission, mscorlib, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" version="1" Flags="ControlEvidence" /> /// </PermissionSet> public static ServicePoint FindServicePoint(System.Uri address, IWebProxy proxy) { if (address == null) { throw new ArgumentNullException("address"); } ServicePointManager.RecycleServicePoints(); bool usesProxy = false; bool flag = false; if (proxy != null && !proxy.IsBypassed(address)) { usesProxy = true; bool flag2 = address.Scheme == "https"; address = proxy.GetProxy(address); if (address.Scheme != "http" && !flag2) { throw new NotSupportedException("Proxy scheme not supported."); } if (flag2 && address.Scheme == "http") { flag = true; } } address = new System.Uri(address.Scheme + "://" + address.Authority); ServicePoint servicePoint = null; System.Collections.Specialized.HybridDictionary obj = ServicePointManager.servicePoints; lock (obj) { ServicePointManager.SPKey key = new ServicePointManager.SPKey(address, flag); servicePoint = (ServicePointManager.servicePoints[key] as ServicePoint); if (servicePoint != null) { return(servicePoint); } if (ServicePointManager.maxServicePoints > 0 && ServicePointManager.servicePoints.Count >= ServicePointManager.maxServicePoints) { throw new InvalidOperationException("maximum number of service points reached"); } string text = address.ToString(); int connectionLimit = ServicePointManager.defaultConnectionLimit; servicePoint = new ServicePoint(address, connectionLimit, ServicePointManager.maxServicePointIdleTime); servicePoint.Expect100Continue = ServicePointManager.expectContinue; servicePoint.UseNagleAlgorithm = ServicePointManager.useNagle; servicePoint.UsesProxy = usesProxy; servicePoint.UseConnect = flag; ServicePointManager.servicePoints.Add(key, servicePoint); } return(servicePoint); }
private Uri GetProxyUri() { // // going through a proxy ? // Uri u = null; if (m_Proxy != null && !m_Proxy.IsBypassed(m_RequestUri)) { u = m_Proxy.GetProxy(m_RequestUri); } return(u); }
/// <summary> /// Main program function /// </summary> private void UpdateAwb() { try { proxy = WebRequest.GetSystemWebProxy(); if (proxy.IsBypassed(new Uri("http://en.wikipedia.org"))) { proxy = null; } updateUI("Getting Current AWB and Updater Versions"); AWBversion(); if ((!updaterUpdate && !awbUpdate) && string.IsNullOrEmpty(AWBWebAddress)) { ExitEarly(); } else { updateUI("Creating a temporary directory"); CreateTempDir(); updateUI("Downloading AWB"); GetAwbFromInternet(); updateUI("Unzipping AWB to the temporary directory"); UnzipAwb(); updateUI("Making sure AWB is closed"); CloseAwb(); updateUI("Copying AWB files from temp to AWB directory"); CopyFiles(); MessageBox.Show("AWB Update Successful", "Update Successful"); updateUI("Starting AWB"); StartAwb(); updateUI("Cleaning up from Update"); KillTempDir(); Application.Exit(); } } catch (Exception ex) { ErrorHandler.Handle(ex); } }
private static Socket CreateTunnelThruProxy(string destIP, int destPort) { string destUriWithPort = $"{destIP}:{destPort}"; UriBuilder uriBuilder = new UriBuilder(destUriWithPort); Uri destUri = uriBuilder.Uri; IWebProxy webProxy = WebRequest.GetSystemWebProxy(); try { if (webProxy.IsBypassed(destUri)) { return(null); } } catch (PlatformNotSupportedException) { // .NET Core doesn't support IWebProxy.IsBypassed // (because .NET Core doesn't have access to Windows-specific services, of course) return(null); } Uri proxyUri = webProxy.GetProxy(destUri); IPAddress[] proxyEntry = Dns.GetHostAddresses(proxyUri.Host); int iPort = proxyUri.Port; IPAddress address = proxyEntry.First(a => a.AddressFamily == AddressFamily.InterNetwork); IPEndPoint proxyEndPoint = new IPEndPoint(address, iPort); Socket socketThruProxy = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); socketThruProxy.Connect(proxyEndPoint); string proxyMsg = $"CONNECT {destIP}:{destPort} HTTP/1.1 \n\n"; byte[] buffer = Encoding.ASCII.GetBytes(proxyMsg); byte[] buffer12 = new byte[500]; socketThruProxy.Send(buffer, buffer.Length, 0); int msg = socketThruProxy.Receive(buffer12, 500, 0); string data; data = Encoding.ASCII.GetString(buffer12); int index = data.IndexOf("200"); if (index < 0) { throw new ApplicationException( $"Connection failed to {destUriWithPort} through proxy server {proxyUri.ToString()}."); } return(socketThruProxy); }
/// <summary> /// Refreshs the system proxy. /// </summary> public static void RefreshProxy() { // no Internet Explorer available on Linux, so GetSystemWebProxy doesn't work, so disable to avoid 60-second timeouts when offline (unit tests etc.) if (Globals.UsingLinux) { return; } SystemProxy = WebRequest.GetSystemWebProxy(); if (SystemProxy.IsBypassed(new Uri(URL))) { SystemProxy = null; } }
/// <summary> /// Main program function /// </summary> private void UpdateAwb() { try { proxy = WebRequest.GetSystemWebProxy(); if (proxy.IsBypassed(new Uri("http://en.wikipedia.org"))) proxy = null; UpdateUI("Getting current AWB and Updater versions", true); AWBversion(); if ((!updaterUpdate && !awbUpdate) && string.IsNullOrEmpty(AWBWebAddress)) ExitEarly(); else { UpdateUI("Creating a temporary directory", true); CreateTempDir(); UpdateUI("Downloading AWB", true); GetAwbFromInternet(); UpdateUI("Unzipping AWB to the temporary directory", true); UnzipAwb(); UpdateUI("Making sure AWB is closed", true); CloseAwb(); UpdateUI("Copying AWB files from temp to AWB directory...", true); CopyFiles(); UpdateUI("Update successful", true); UpdateUI("Cleaning up from update", true); KillTempDir(); updateSucessful = true; ReadyToExit(); } } catch (AbortException) { ReadyToExit(); } catch (Exception ex) { ErrorHandler.Handle(ex); } }
/// <summary> /// Return true or false if connecting through a proxy server /// </summary> /// <param name="uri"></param> /// <returns></returns> static bool IsSystemProxySet(Uri uri) { CheckProxyConfigSettings(); CheckMacProxy(uri); Console.WriteLine("# Mono's WebRequest"); Console.WriteLine("WebRequest.GetSystemWebProxy().GetType: {0}", originalSystemProxy.GetType().FullName); var systemProxy = GetSystemProxy(uri); Console.WriteLine("WebRequest.GetSystemWebProxy().GetProxy() returned proxy Uri: '{0}'", systemProxy.Address); // The reason for not calling the GetSystemProxy is because the object // that will be returned is no longer going to be the proxy that is set by the settings // on the users machine only the Address is going to be the same. // Not sure why the .NET team did not want to expose all of the useful settings like // ByPass list and other settings that we can't get because of it. // Anyway the reason why we need the DefaultWebProxy is to see if the uri that we are // getting the proxy for to should be bypassed or not. If it should be bypassed then // return that we don't need a proxy and we should try to connect directly. IWebProxy proxy = WebRequest.DefaultWebProxy; if (proxy != null) { Console.WriteLine("WebRequest.DefaultWebProxy.GetType: {0}", proxy.GetType().FullName); Uri proxyAddress = new Uri(proxy.GetProxy(uri).AbsoluteUri); if (string.Equals(proxyAddress.AbsoluteUri, uri.AbsoluteUri)) { Console.WriteLine("ProxyAddress matches request uri. Ignoring proxy uri: '{0}'", proxyAddress); return(false); } if (proxy.IsBypassed(uri)) { Console.WriteLine("Proxy IsByPassed for '{0}'", uri); return(false); } } else { Console.WriteLine("WebRequest.DefaultWebProxy is null. Trying WebRequest.GetSystemWebProxy"); proxy = GetSystemProxy(uri); if (proxy == null) { Console.WriteLine("WebRequest.GetSystemWebProxy returned null"); } } return(proxy != null); }
public static void CheckProxySettings(String url) { try { bool customProxyUsed = NetworkSettings.CustomProxy != null; IWebProxy proxy = customProxyUsed ? NetworkSettings.CustomProxy : WebRequest.DefaultWebProxy; Uri uri = new Uri(url); var proxyUri = proxy.GetProxy(uri).Host; bool isByPassed = proxy.IsBypassed(uri); Log.Debug($"{(customProxyUsed ? "Custom" : "Default")} Proxy setting for URL: {url}; proxy host: {proxyUri}; isByPassed: {isByPassed}"); } catch (Exception e) { Log.Debug($"Failed to check proxy settings : {e.Message}"); } }
public CurlCmdArgumentsBuilder WithProxy(IWebProxy proxy, Uri requestUri = null) { // Argument should be of the following form: // -x, --proxy <[protocol://][user:password@]proxyhost[:port]> if (requestUri is null) { requestUri = uri; } if (!(proxy is null) && !proxy.IsBypassed(requestUri)) { AddArgument("--proxy", proxy.ToProxyString(requestUri)); } return(this); }
/// <summary> /// Main program function /// </summary> private void UpdateAwb() { try { proxy = WebRequest.GetSystemWebProxy(); if (proxy.IsBypassed(new Uri("http://en.wikipedia.org"))) proxy = null; updateUI("Getting Current AWB and Updater Versions"); AWBversion(); if ((!updaterUpdate && !awbUpdate) && string.IsNullOrEmpty(AWBWebAddress)) ExitEarly(); else { updateUI("Creating a temporary directory"); CreateTempDir(); updateUI("Downloading AWB"); GetAwbFromInternet(); updateUI("Unzipping AWB to the temporary directory"); UnzipAwb(); updateUI("Making sure AWB is closed"); CloseAwb(); updateUI("Copying AWB files from temp to AWB directory"); CopyFiles(); MessageBox.Show("AWB Update Successful", "Update Successful"); updateUI("Starting AWB"); StartAwb(); updateUI("Cleaning up from Update"); KillTempDir(); Application.Exit(); } } catch (Exception ex) { ErrorHandler.Handle(ex); } }
/// <summary> /// Provides the MQTT client options to create an authenticated MQTT /// over WebSocket connection to an AWS IoT Device Gateway endpoint. /// </summary> /// <param name="client">The authenticated AWS IoT Device Gateway client.</param> /// <param name="iotEndpointAddress">The AWS account-specific AWS IoT endpoint address.</param> /// <param name="cancelToken">A cancellation token that can be used by other objects or threads to receive notice of cancellation.</param> public static async Task <IMqttClientOptions> CreateMqttWebSocketClientOptionsAsync(this AmazonIoTDeviceGatewayClient client, string iotEndpointAddress, CancellationToken cancelToken = default) { if (client is null) { throw new ArgumentNullException(nameof(client)); } var uriDetails = await client.CreateMqttWebSocketUriAsync(new Model.CreateMqttWebSocketUriRequest { EndpointAddress = iotEndpointAddress }, cancelToken).ConfigureAwait(continueOnCapturedContext: false); var optionsBuilder = new MqttClientOptionsBuilder(); optionsBuilder = optionsBuilder.WithTls(); optionsBuilder = optionsBuilder.WithWebSocketServer(uriDetails.RequestUri?.ToString()); IWebProxy iProxy = client.Config.GetWebProxy(); if (!(iProxy is null)) { Uri proxyUri; if (iProxy is Amazon.Runtime.Internal.Util.WebProxy awssdkProxy) { proxyUri = awssdkProxy.ProxyUri; } else { proxyUri = new Uri("http://" + client.Config.ProxyHost + ":" + client.Config.ProxyPort); } var iCreds = iProxy.Credentials ?? client.Config.ProxyCredentials; var netCreds = iCreds?.GetCredential(proxyUri, default); optionsBuilder = optionsBuilder.WithProxy(proxyUri.ToString(), username: netCreds?.UserName, password: netCreds?.Password, domain: netCreds?.Domain, bypassOnLocal: iProxy.IsBypassed(localhostUri) ); } var options = optionsBuilder.Build(); if (options.ChannelOptions is MqttClientWebSocketOptions webSocketOptions) { webSocketOptions.RequestHeaders = uriDetails.Headers; } return(options); }
internal static ServicePoint FindServicePoint(Uri address, IWebProxy proxy, out ProxyChain chain, ref HttpAbortDelegate abortDelegate, ref int abortState) { if (address == null) { throw new ArgumentNullException("address"); } bool isProxyServicePoint = false; chain = null; Uri current = null; if ((proxy != null) && !address.IsLoopback) { IAutoWebProxy proxy2 = proxy as IAutoWebProxy; if (proxy2 != null) { chain = proxy2.GetProxies(address); abortDelegate = chain.HttpAbortDelegate; try { Thread.MemoryBarrier(); if (abortState != 0) { Exception exception = new WebException(NetRes.GetWebStatusString(WebExceptionStatus.RequestCanceled), WebExceptionStatus.RequestCanceled); throw exception; } chain.Enumerator.MoveNext(); current = chain.Enumerator.Current; } finally { abortDelegate = null; } } else if (!proxy.IsBypassed(address)) { current = proxy.GetProxy(address); } if (current != null) { address = current; isProxyServicePoint = true; } } return(FindServicePointHelper(address, isProxyServicePoint)); }
public static int SetProxySettings(string szFileName) { StringBuilder szTmp = new StringBuilder(256); GetPrivateProfileString("base", "URL", myBaseURL, szTmp, szTmp.Capacity, myIniFile); string szURLBase = szTmp.ToString(); string szURL = szURLBase + szFileName; UriBuilder myUri = new UriBuilder(szURL); IWebProxy myProxy = WebRequest.GetSystemWebProxy(); Uri myProxyURI = myProxy.GetProxy(myUri.Uri); string myHost = myProxyURI.Host; int myPort = myProxyURI.Port; string szProxy = myProxyURI.ToString(); bool isBypassed = myProxy.IsBypassed(myUri.Uri); return(0); }
void DoPreAuthenticate() { webHeaders.RemoveInternal("Proxy-Authorization"); webHeaders.RemoveInternal("Authorization"); bool isProxy = (proxy != null && !proxy.IsBypassed(actualUri)); ICredentials creds = (!isProxy || credentials != null) ? credentials : proxy.Credentials; Authorization auth = AuthenticationManager.PreAuthenticate(this, creds); if (auth == null) { return; } string authHeader = (isProxy && credentials == null) ? "Proxy-Authorization" : "Authorization"; webHeaders [authHeader] = auth.Message; usedPreAuth = true; }
public static bool UpdateProxySettings(IWebProxy systemProxy, string remoteAddress, string keyEnable, string keyHost, string keyPort) { Uri uri = new Uri(remoteAddress); if (systemProxy.IsBypassed(uri)) { SEBSettings.proxiesData[keyEnable] = (object)false; Logger.AddInformation(string.Format("Disabled proxy for {0}", (object)uri.Scheme), (object)null, (Exception)null, (string)null); return(false); } Uri proxy = systemProxy.GetProxy(uri); Logger.AddInformation(string.Format("Enabled proxy for {0}: {1}:{2}", (object)uri.Scheme, (object)proxy.Host, (object)proxy.Port), (object)null, (Exception)null, (string)null); SEBSettings.proxiesData[keyEnable] = (object)true; SEBSettings.proxiesData[keyHost] = (object)proxy.Host; SEBSettings.proxiesData[keyPort] = (object)proxy.Port; return(true); }
public static Stream ConnectStream(Uri uri, IWebProxy proxy, bool nodelay, int timeout_ms) { Stream stream; Stream stream3; IMockWebProxy proxy2 = (proxy != null) ? (proxy as IMockWebProxy) : null; if (proxy2 != null) { return(proxy2.GetStream(uri)); } bool flag = (proxy != null) && !proxy.IsBypassed(uri); if (flag) { stream = ConnectSocket(proxy.GetProxy(uri), nodelay, timeout_ms); } else { stream = ConnectSocket(uri, nodelay, timeout_ms); } try { if (flag) { WriteLine(string.Format("CONNECT {0}:{1} HTTP/1.0", uri.Host, uri.Port), stream); WriteLine(stream); ReadHttpHeaders(ref stream, proxy, nodelay, timeout_ms); } if (UseSSL(uri)) { SslStream stream2 = new SslStream(stream, false, new RemoteCertificateValidationCallback(HTTP.ValidateServerCertificate), null); stream2.AuthenticateAsClient(""); stream = stream2; } stream3 = stream; } catch { stream.Close(); throw; } return(stream3); }
/// <summary> /// Method responsible for checking the proxy and proxy authentication type and setting the /// appropriate credentials. If the NTLM authentication is used then /// if the username and password are not provided then we use null values. For /// all other authentication schemes we need a username and password. /// </summary> /// <param name="backgroundCopyJob">BackgroundJob on which we need to set the credentials.</param> /// <param name="task">DownloadTask. Provides the infos about download credentials</param> private static void VerifyAndSetBackgroundCopyJobProxy(IBackgroundCopyJob backgroundCopyJob, DownloadTask task) { // Specify the proxy URL // see also http://msdn.microsoft.com/library/en-us/bits/bits/ibackgroundcopyjob_setproxysettings.asp try { IWebProxy proxy = task.DownloadItem.Proxy; var sourceUri = new Uri(task.DownloadItem.File.Source); Uri proxyUri = proxy.GetProxy(sourceUri); //trim trailing '/' because it causes BITS to throw an exception string proxyUriStr = proxyUri.ToString().TrimEnd('/'); if (!proxy.IsBypassed(proxyUri)) { backgroundCopyJob.SetProxySettings(BG_JOB_PROXY_USAGE.BG_JOB_PROXY_USAGE_OVERRIDE, proxyUriStr, null); } //specify proxy credentials if (proxy.Credentials != null) { ICredentials creds = proxy.Credentials; var copyJob = (IBackgroundCopyJob2)backgroundCopyJob; var credentials = new BG_AUTH_CREDENTIALS(); credentials.Credentials.Basic.UserName = string.IsNullOrEmpty(creds.GetCredential(sourceUri, "NTLM").Domain) ? creds.GetCredential(sourceUri, "NTLM").UserName : creds.GetCredential(sourceUri, "NTLM").Domain + "\\" + creds.GetCredential(sourceUri, "NTLM").UserName; credentials.Credentials.Basic.Password = creds.GetCredential(sourceUri, "NTLM").Password; credentials.Scheme = BG_AUTH_SCHEME.BG_AUTH_SCHEME_NTLM; credentials.Target = BG_AUTH_TARGET.BG_AUTH_TARGET_PROXY; copyJob.SetCredentials(ref credentials); } } catch (Exception e) { Logger.Error("Error in VerifyAndSetBackgroundCopyJobProxy():", e); } }
/// <summary> /// Returns an ICredentials instance that the consumer would need in order /// to properly authenticate to the given Uri. /// </summary> public ICredentials GetCredentials(Uri uri, IWebProxy proxy, CredentialType credentialType, bool retrying) { if (uri == null) { throw new ArgumentNullException("uri"); } // Capture the original proxy before we do anything // so that we can re-set it once we get the credentials for the given Uri. IWebProxy originalProxy = null; if (proxy != null) { // If the current Uri should be bypassed then don't try to get the specific // proxy but simply capture the one that is given to us if (proxy.IsBypassed(uri)) { originalProxy = proxy; } // If the current Uri is not bypassed then get a valid proxy for the Uri // and make sure that we have the credentials also. else { originalProxy = new WebProxy(proxy.GetProxy(uri)); originalProxy.Credentials = proxy.Credentials == null ? null : proxy.Credentials.GetCredential(uri, null); } } try { // The cached credentials that we found are not valid so let's ask the user // until they abort or give us valid credentials. InitializeCredentialProxy(uri, originalProxy); return(PromptForCredentials(uri)); } finally { // Reset the original WebRequest.DefaultWebProxy to what it was when we started credential discovery. WebRequest.DefaultWebProxy = originalProxy; } }
public static NetProxy GetDefaultProxy() { IWebProxy proxy = WebRequest.DefaultWebProxy; Uri testUri = new Uri("https://www.google.com/"); if (proxy.IsBypassed(testUri)) { return(null); //no proxy configured } Uri proxyAddress = proxy.GetProxy(testUri); if (proxyAddress.Equals(testUri)) { return(null); //no proxy configured } return(new NetProxy(new WebProxyEx(proxyAddress) { Credentials = proxy.Credentials })); }
/// <summary> /// Create a IWebProxy Object which can be used to access the Internet /// This method will check the configuration if the proxy is allowed to be used. /// Usages can be found in the DownloadFavIcon or Jira and Confluence plugins /// </summary> /// <param name="uri"></param> /// <returns>IWebProxy filled with all the proxy details or null if none is set/wanted</returns> public static IWebProxy CreateProxy(Uri uri) { if (!Config.UseProxy) { return(null); } IWebProxy proxyToUse = WebRequest.DefaultWebProxy; if (proxyToUse != null) { proxyToUse.Credentials = CredentialCache.DefaultCredentials; if (!Log.IsDebugEnabled()) { return(proxyToUse); } // check the proxy for the Uri if (!proxyToUse.IsBypassed(uri)) { var proxyUri = proxyToUse.GetProxy(uri); if (proxyUri != null) { Log.Debug().WriteLine("Using proxy: " + proxyUri + " for " + uri); } else { Log.Debug().WriteLine("No proxy found!"); } } else { Log.Debug().WriteLine("Proxy bypass for: " + uri); } } else { Log.Debug().WriteLine("No proxy found!"); } return(proxyToUse); }
/// <summary> /// Returns an ICredentials instance that the consumer would need in order /// to properly authenticate to the given Uri. /// </summary> public ICredentials GetCredentials(Uri uri, IWebProxy proxy, CredentialType credentialType, bool retrying) { if (uri == null) { throw new ArgumentNullException("uri"); } // Capture the original proxy before we do anything // so that we can re-set it once we get the credentials for the given Uri. IWebProxy originalProxy = null; if (proxy != null) { // If the current Uri should be bypassed then don't try to get the specific // proxy but simply capture the one that is given to us if (proxy.IsBypassed(uri)) { originalProxy = proxy; } // If the current Uri is not bypassed then get a valid proxy for the Uri // and make sure that we have the credentials also. else { originalProxy = new WebProxy(proxy.GetProxy(uri)); originalProxy.Credentials = proxy.Credentials == null ? null : proxy.Credentials.GetCredential(uri, null); } } try { // The cached credentials that we found are not valid so let's ask the user // until they abort or give us valid credentials. InitializeCredentialProxy(uri, originalProxy); return PromptForCredentials(uri); } finally { // Reset the original WebRequest.DefaultWebProxy to what it was when we started credential discovery. WebRequest.DefaultWebProxy = originalProxy; } }
WebClient CreateWebClient(Uri uri) { WebClient newWebClient = new WebClient(); newWebClient.DownloadFileCompleted += DownloadFileCompleted; newWebClient.DownloadStringCompleted += DownloadStringCompleted; newWebClient.DownloadDataCompleted += DownloadDataCompleted; newWebClient.DownloadProgressChanged += DownloadProgressChanged; WebProxy finalProxySettings = null; if (_proxyAddress != null) { finalProxySettings = new WebProxy(_proxyAddress, false); } else { var proxyUriForUri = _systemProxy.GetProxy(uri); if (!_systemProxy.IsBypassed(uri)) { finalProxySettings = new WebProxy(proxyUriForUri, false); } } if (finalProxySettings != null) { Console.Write("Using proxy at " + finalProxySettings.Address.ToString()); if (_proxyUsername != null) { finalProxySettings.Credentials = new NetworkCredential(_proxyUsername, _proxyPassword); Console.WriteLine(" using provided credentials."); } else { finalProxySettings.UseDefaultCredentials = true; Console.WriteLine(" using default credentials."); } newWebClient.Proxy = finalProxySettings; } return(newWebClient); }
protected internal override Task <HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) { Uri proxyUri = null; try { if (!_proxy.IsBypassed(request.RequestUri)) { proxyUri = _proxy.GetProxy(request.RequestUri); } } catch (Exception) { // Eat any exception from the IWebProxy and just treat it as no proxy. // TODO #21452: This seems a bit questionable, but it's what the tests expect } return(proxyUri == null? _innerHandler.SendAsync(request, cancellationToken) : SendWithProxyAsync(proxyUri, request, cancellationToken)); }
protected internal override Task <HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) { Uri proxyUri = null; try { if (!_proxy.IsBypassed(request.RequestUri)) { proxyUri = _proxy.GetProxy(request.RequestUri); } } catch (Exception) { // Eat any exception from the IWebProxy and just treat it as no proxy. // This matches the behavior of other handlers. } return(proxyUri == null? _innerHandler.SendAsync(request, cancellationToken) : SendWithProxyAsync(proxyUri, request, cancellationToken)); }
public static NetProxy CreateSystemHttpProxy() { IWebProxy proxy = WebRequest.DefaultWebProxy; if (proxy == null) { return(null); //no proxy configured } Uri testUri = new Uri("https://www.google.com/"); if (proxy.IsBypassed(testUri)) { return(null); //no proxy configured } Uri proxyAddress = proxy.GetProxy(testUri); if (proxyAddress.Equals(testUri)) { return(null); //no proxy configured } return(new HttpProxy(EndPointExtension.GetEndPoint(proxyAddress.Host, proxyAddress.Port), proxy.Credentials.GetCredential(proxyAddress, "BASIC"))); }
/// <summary> /// Create a IWebProxy Object which can be used to access the Internet /// This method will check the configuration if the proxy is allowed to be used. /// Usages can be found in the DownloadFavIcon or Jira and Confluence plugins /// </summary> /// <param name="url"></param> /// <returns>IWebProxy filled with all the proxy details or null if none is set/wanted</returns> public static IWebProxy CreateProxy(Uri uri) { IWebProxy proxyToUse = null; if (config.UseProxy) { proxyToUse = WebRequest.DefaultWebProxy; if (proxyToUse != null) { proxyToUse.Credentials = CredentialCache.DefaultCredentials; if (LOG.IsDebugEnabled) { // check the proxy for the Uri if (!proxyToUse.IsBypassed(uri)) { Uri proxyUri = proxyToUse.GetProxy(uri); if (proxyUri != null) { LOG.Debug("Using proxy: " + proxyUri.ToString() + " for " + uri.ToString()); } else { LOG.Debug("No proxy found!"); } } else { LOG.Debug("Proxy bypass for: " + uri.ToString()); } } } else { LOG.Debug("No proxy found!"); } } return(proxyToUse); }
private static bool IsSystemProxySet(Uri uri) { IWebProxy defaultWebProxy = WebRequest.DefaultWebProxy; if (defaultWebProxy != null) { Uri proxy = defaultWebProxy.GetProxy(uri); if (proxy != null) { Uri address = new Uri(proxy.AbsoluteUri); if (string.Equals(address.AbsoluteUri, uri.AbsoluteUri)) { return(false); } if (defaultWebProxy.IsBypassed(uri)) { return(false); } defaultWebProxy = new WebProxy(address); } } return(defaultWebProxy != null); }
static ProxyInfo GetProxy(Uri requestUri) { IWebProxy systemProxy = WebRequest.GetSystemWebProxy(); Uri proxyUri = systemProxy.GetProxy(requestUri); var proxyAddress = new Uri(proxyUri.AbsoluteUri); if (string.Equals(proxyAddress.AbsoluteUri, requestUri.AbsoluteUri)) { return(null); } if (systemProxy.IsBypassed(requestUri)) { return(null); } var proxyType = GetProxyType(requestUri); return(new ProxyInfo { Port = proxyAddress.Port, ProxyType = GetProxyType(requestUri), HostName = proxyAddress.Host }); }
public override ch.cyberduck.core.proxy.Proxy find(Host host) { if (!PreferencesFactory.get().getBoolean("connection.proxy.enable")) { return(ch.cyberduck.core.proxy.Proxy.DIRECT); } Uri target; try { target = new Uri(new ProxyHostUrlProvider().get(host)); } catch (UriFormatException) { return(ch.cyberduck.core.proxy.Proxy.DIRECT); } if (_system.IsBypassed(target)) { return(ch.cyberduck.core.proxy.Proxy.DIRECT); } Uri proxy = _system.GetProxy(target); return(new ch.cyberduck.core.proxy.Proxy(ch.cyberduck.core.proxy.Proxy.Type.valueOf(proxy.Scheme.ToUpper()), proxy.Host, proxy.Port, proxy.UserInfo)); }
/// <summary> /// Gets the the Default Or System proxy in use. Will return null if no Default/System proxy is in use. /// </summary> /// <returns>System.Net.IWebProxy.</returns> public static IWebProxy GetWebProxy() { IWebProxy webProxy = null; // See if end user has forced to use a System.Net.WebRequest.GetSystemWebProxy() if (AceQLConnection.GetDefaultWebProxy() != null) { webProxy = AceQLConnection.GetDefaultWebProxy(); } else { webProxy = System.Net.WebRequest.DefaultWebProxy; } // Test the secret URL, if it is bypassed, there is no Default/System proxy set, so we will return null: if (webProxy.IsBypassed(new Uri(HttpClientHandlerBuilderNew.SECRET_URL))) { return(null); } else { return(webProxy); } }
public static void RefreshProxy() { SystemProxy = WebRequest.GetSystemWebProxy(); if (SystemProxy.IsBypassed(new Uri(URL))) { SystemProxy = null; } }
public static ServicePoint FindServicePoint (Uri address, IWebProxy proxy) { if (address == null) throw new ArgumentNullException ("address"); RecycleServicePoints (); bool usesProxy = false; bool useConnect = false; if (proxy != null && !proxy.IsBypassed(address)) { usesProxy = true; bool isSecure = address.Scheme == "https"; address = proxy.GetProxy (address); if (address.Scheme != "http" && !isSecure) throw new NotSupportedException ("Proxy scheme not supported."); if (isSecure && address.Scheme == "http") useConnect = true; } address = new Uri (address.Scheme + "://" + address.Authority); ServicePoint sp = null; lock (servicePoints) { SPKey key = new SPKey (address, useConnect); sp = servicePoints [key] as ServicePoint; if (sp != null) return sp; if (maxServicePoints > 0 && servicePoints.Count >= maxServicePoints) throw new InvalidOperationException ("maximum number of service points reached"); string addr = address.ToString (); #if NET_2_1 int limit = defaultConnectionLimit; #else int limit = (int) manager.GetMaxConnections (addr); #endif sp = new ServicePoint (address, limit, maxServicePointIdleTime); sp.Expect100Continue = expectContinue; sp.UseNagleAlgorithm = useNagle; sp.UsesProxy = usesProxy; sp.UseConnect = useConnect; sp.SetTcpKeepAlive (tcp_keepalive, tcp_keepalive_time, tcp_keepalive_interval); servicePoints.Add (key, sp); } return sp; }
/// <summary> /// This function will connect a stream to a uri (host and port), /// negotiating proxies and SSL /// </summary> /// <param name="uri"></param> /// <param name="timeout_ms">Timeout, in ms. 0 for no timeout.</param> /// <returns></returns> public static Stream ConnectStream(Uri uri, IWebProxy proxy, bool nodelay, int timeout_ms) { IMockWebProxy mockProxy = proxy != null ? proxy as IMockWebProxy : null; if (mockProxy != null) return mockProxy.GetStream(uri); Stream stream; bool useProxy = proxy != null && !proxy.IsBypassed(uri); if (useProxy) { Uri proxyURI = proxy.GetProxy(uri); stream = ConnectSocket(proxyURI, nodelay, timeout_ms); } else { stream = ConnectSocket(uri, nodelay, timeout_ms); } try { if (useProxy) { string line = String.Format("CONNECT {0}:{1} HTTP/1.0", uri.Host, uri.Port); WriteLine(line, stream); WriteLine(stream); ReadHttpHeaders(ref stream, proxy, nodelay, timeout_ms); } if (UseSSL(uri)) { SslStream sslStream = new SslStream(stream, false, new RemoteCertificateValidationCallback(ValidateServerCertificate), null); sslStream.AuthenticateAsClient(""); stream = sslStream; } return stream; } catch { stream.Close(); throw; } }
/// <summary> /// Initializes a new instance of the <see cref="ApiEdit" /> class. /// </summary> /// <param name="url">Path to scripts on server</param> /// <param name="usePHP5">Whether a .php5 extension is to be used</param> public ApiEdit(string url, bool usePHP5) : this() { if (string.IsNullOrEmpty(url)) throw new ArgumentException("Invalid URL specified", "url"); //if (!url.StartsWith("http://")) throw new NotSupportedException("Only editing via HTTP is currently supported"); URL = url; PHP5 = usePHP5; ApiURL = URL + "api.php" + (PHP5 ? "5" : ""); Maxlag = 5; IWebProxy proxy; if (ProxyCache.TryGetValue(url, out proxy)) { ProxySettings = proxy; } // GetSystemWebProxy doesn't work under Linux (no IE settings to find) and can cause 60-second timeout, so skip proxy lookup under Linux else if(!Globals.UsingLinux) { ProxySettings = WebRequest.GetSystemWebProxy(); if (ProxySettings.IsBypassed(new Uri(url))) { ProxySettings = null; } ProxyCache.Add(url, ProxySettings); } }
/// <summary> /// Refreshs the system proxy. /// </summary> public static void RefreshProxy() { // no Internet Explorer available on Linux, so GetSystemWebProxy doesn't work, so disable to avoid 60-second timeouts when offline (unit tests etc.) if(Globals.UsingLinux) return; SystemProxy = WebRequest.GetSystemWebProxy(); if (SystemProxy.IsBypassed(new Uri(URL))) { SystemProxy = null; } }
// If abortState becomes non-zero, the attempt to find a service point has been aborted. internal static ServicePoint FindServicePoint(Uri address, IWebProxy proxy, out ProxyChain chain, ref HttpAbortDelegate abortDelegate, ref int abortState) { if (address==null) { throw new ArgumentNullException("address"); } GlobalLog.Enter("ServicePointManager::FindServicePoint() address:" + address.ToString()); bool isProxyServicePoint = false; chain = null; // // find proxy info, and then switch on proxy // Uri proxyAddress = null; if (proxy!=null && !address.IsLoopback) { IAutoWebProxy autoProxy = proxy as IAutoWebProxy; if (autoProxy != null) { chain = autoProxy.GetProxies(address); // Set up our ability to abort this MoveNext call. Note that the current implementations of ProxyChain will only // take time on the first call, so this is the only place we do this. If a new ProxyChain takes time in later // calls, this logic should be copied to other places MoveNext is called. GlobalLog.Assert(abortDelegate == null, "ServicePointManager::FindServicePoint()|AbortDelegate already set."); abortDelegate = chain.HttpAbortDelegate; try { Thread.MemoryBarrier(); if (abortState != 0) { Exception exception = new WebException(NetRes.GetWebStatusString(WebExceptionStatus.RequestCanceled), WebExceptionStatus.RequestCanceled); GlobalLog.LeaveException("ServicePointManager::FindServicePoint() Request aborted before proxy lookup.", exception); throw exception; } if (!chain.Enumerator.MoveNext()) { GlobalLog.Assert("ServicePointManager::FindServicePoint()|GetProxies() returned zero proxies."); /* Exception exception = new WebException(NetRes.GetWebStatusString(WebExceptionStatus.RequestProhibitedByProxy), WebExceptionStatus.RequestProhibitedByProxy); GlobalLog.LeaveException("ServicePointManager::FindServicePoint() Proxy prevented request.", exception); throw exception; */ } proxyAddress = chain.Enumerator.Current; } finally { abortDelegate = null; } } else if (!proxy.IsBypassed(address)) { // use proxy support // rework address proxyAddress = proxy.GetProxy(address); } // null means DIRECT if (proxyAddress!=null) { address = proxyAddress; isProxyServicePoint = true; } } ServicePoint servicePoint = FindServicePointHelper(address, isProxyServicePoint); GlobalLog.Leave("ServicePointManager::FindServicePoint() servicePoint#" + ValidationHelper.HashString(servicePoint)); return servicePoint; }
internal static ServicePoint FindServicePoint(Uri address, IWebProxy proxy, out ProxyChain chain, ref HttpAbortDelegate abortDelegate, ref int abortState) { if (address == null) { throw new ArgumentNullException("address"); } bool isProxyServicePoint = false; chain = null; Uri current = null; if ((proxy != null) && !address.IsLoopback) { IAutoWebProxy proxy2 = proxy as IAutoWebProxy; if (proxy2 != null) { chain = proxy2.GetProxies(address); abortDelegate = chain.HttpAbortDelegate; try { Thread.MemoryBarrier(); if (abortState != 0) { Exception exception = new WebException(NetRes.GetWebStatusString(WebExceptionStatus.RequestCanceled), WebExceptionStatus.RequestCanceled); throw exception; } chain.Enumerator.MoveNext(); current = chain.Enumerator.Current; } finally { abortDelegate = null; } } else if (!proxy.IsBypassed(address)) { current = proxy.GetProxy(address); } if (current != null) { address = current; isProxyServicePoint = true; } } return FindServicePointHelper(address, isProxyServicePoint); }
/// <summary> /// Creates a new instance of the ApiEdit class /// </summary> /// <param name="url">Path to scripts on server</param> /// <param name="usePHP5">Whether a .php5 extension is to be used</param> public ApiEdit(string url, bool usePHP5) : this() { if (string.IsNullOrEmpty(url)) throw new ArgumentException("Invalid URL specified", "url"); if (!url.StartsWith("http://")) throw new NotSupportedException("Only editing via HTTP is currently supported"); URL = url; PHP5 = usePHP5; ApiURL = URL + "api.php" + (PHP5 ? "5" : ""); Maxlag = 5; IWebProxy proxy; if (ProxyCache.TryGetValue(url, out proxy)) { ProxySettings = proxy; } else { ProxySettings = WebRequest.GetSystemWebProxy(); if (ProxySettings.IsBypassed(new Uri(url))) { ProxySettings = null; } ProxyCache.Add(url, ProxySettings); } }
// // FindServicePoint - Query using an Uri for a given server point // /// <include file='doc\ServicePointManager.uex' path='docs/doc[@for="ServicePointManager.FindServicePoint2"]/*' /> /// <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> public static ServicePoint FindServicePoint(Uri address, IWebProxy proxy) { if (address==null) { throw new ArgumentNullException("address"); } GlobalLog.Enter("ServicePointManager::FindServicePoint() address:" + address.ToString()); string tempEntry; bool isProxyServicePoint = false; ScavengeIdleServicePoints(); // // find proxy info, and then switch on proxy // if (proxy!=null && !proxy.IsBypassed(address)) { // use proxy support // rework address Uri proxyAddress = proxy.GetProxy(address); if (proxyAddress.Scheme != Uri.UriSchemeHttps && proxyAddress.Scheme != Uri.UriSchemeHttp) { Exception exception = new NotSupportedException(SR.GetString(SR.net_proxyschemenotsupported, proxyAddress.Scheme)); GlobalLog.LeaveException("ServicePointManager::FindServicePoint() proxy has unsupported scheme:" + proxyAddress.Scheme.ToString(), exception); throw exception; } address = proxyAddress; isProxyServicePoint = true; // // Search for the correct proxy host, // then match its acutal host by using ConnectionGroups // which are located on the actual ServicePoint. // tempEntry = MakeQueryString(proxyAddress); } else { // // Typical Host lookup // tempEntry = MakeQueryString(address); } // // lookup service point in the table // ServicePoint servicePoint = null; lock (s_ServicePointTable) { // // once we grab the lock, check if it wasn't already added // WeakReference servicePointReference = (WeakReference) s_ServicePointTable[tempEntry]; if ( servicePointReference != null ) { servicePoint = (ServicePoint)servicePointReference.Target; } 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); if (ConfigTable.ContainsKey(schemeHostPort) ) { connectionLimit = (int) ConfigTable[schemeHostPort]; } // Note: we don't check permissions to access proxy. // Rather, we should protect proxy property from being changed servicePoint = new ServicePoint(address, s_MaxServicePointIdleTime, connectionLimit); servicePointReference = new WeakReference(servicePoint); // only set this when created, donates a proxy, statt Server servicePoint.InternalProxyServicePoint = isProxyServicePoint; s_ServicePointTable[tempEntry] = servicePointReference; } 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; } } } // lock GlobalLog.Leave("ServicePointManager::FindServicePoint() servicePoint#" + ValidationHelper.HashString(servicePoint)); return servicePoint; }
public static ServicePoint FindServicePoint(Uri address, IWebProxy proxy) { if (address == null) { throw new ArgumentNullException("address"); } var usesProxy = false; if (proxy != null && !proxy.IsBypassed(address)) { usesProxy = true; var isSecure = address.Scheme == Uri.UriSchemeHttps; address = proxy.GetProxy(address); if (address.Scheme != Uri.UriSchemeHttp && !isSecure) { throw new NotSupportedException("Proxy scheme not supported."); } } var key = MakeQueryString(address, usesProxy); return _servicePoints.GetOrAdd(key, new Lazy<ServicePoint>(() => { if (_maxServicePoints > 0 && _servicePoints.Count >= _maxServicePoints) { throw new InvalidOperationException("maximum number of service points reached"); } return new ServicePoint(address, _defaultConnectionLimit, key, usesProxy); }, false)).Value; }