2 // System.Net.WebRequest
5 // Lawrence Pit (loz@cable.a2000.nl)
6 // Marek Safar (marek.safar@gmail.com)
8 // Copyright 2011 Xamarin Inc.
10 // Permission is hereby granted, free of charge, to any person obtaining
11 // a copy of this software and associated documentation files (the
12 // "Software"), to deal in the Software without restriction, including
13 // without limitation the rights to use, copy, modify, merge, publish,
14 // distribute, sublicense, and/or sell copies of the Software, and to
15 // permit persons to whom the Software is furnished to do so, subject to
16 // the following conditions:
18 // The above copyright notice and this permission notice shall be
19 // included in all copies or substantial portions of the Software.
21 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
22 // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
23 // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
24 // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
25 // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
26 // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
27 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
31 using System.Collections;
32 using System.Collections.Specialized;
33 using System.Configuration;
35 using System.Reflection;
36 using System.Runtime.Serialization;
37 using System.Globalization;
38 using System.Net.Configuration;
39 using System.Net.Security;
40 using System.Net.Cache;
41 using System.Security.Principal;
42 using System.Threading.Tasks;
43 using System.Text.RegularExpressions;
47 using ConfigurationException = System.ArgumentException;
49 namespace System.Net.Configuration {
57 public abstract class WebRequest : MarshalByRefObject, ISerializable {
58 static HybridDictionary prefixes = new HybridDictionary ();
59 static bool isDefaultWebProxySet;
60 static IWebProxy defaultWebProxy;
61 static RequestCachePolicy defaultCachePolicy;
66 IWebRequestCreate http = new HttpRequestCreator ();
67 RegisterPrefix ("http", http);
68 RegisterPrefix ("https", http);
69 RegisterPrefix ("file", new FileWebRequestCreator ());
70 RegisterPrefix ("ftp", new FtpRequestCreator ());
73 object cfg = ConfigurationManager.GetSection ("system.net/webRequestModules");
74 WebRequestModulesSection s = cfg as WebRequestModulesSection;
76 foreach (WebRequestModuleElement el in
78 AddPrefix (el.Prefix, el.Type);
82 ConfigurationSettings.GetConfig ("system.net/webRequestModules");
86 protected WebRequest ()
90 protected WebRequest (SerializationInfo serializationInfo, StreamingContext streamingContext)
94 static Exception GetMustImplement ()
96 return new NotImplementedException ("This method must be implemented in derived classes");
101 private AuthenticationLevel authentication_level = AuthenticationLevel.MutualAuthRequested;
103 public AuthenticationLevel AuthenticationLevel
106 return(authentication_level);
109 authentication_level = value;
113 public virtual string ConnectionGroupName {
114 get { throw GetMustImplement (); }
115 set { throw GetMustImplement (); }
118 public virtual long ContentLength {
119 get { throw GetMustImplement (); }
120 set { throw GetMustImplement (); }
123 public virtual string ContentType {
124 get { throw GetMustImplement (); }
125 set { throw GetMustImplement (); }
128 public virtual ICredentials Credentials {
129 get { throw GetMustImplement (); }
130 set { throw GetMustImplement (); }
133 [MonoTODO ("Implement the caching system. Currently always returns a policy with the NoCacheNoStore level")]
134 public virtual RequestCachePolicy CachePolicy
136 get { return DefaultCachePolicy; }
141 public static RequestCachePolicy DefaultCachePolicy {
143 return defaultCachePolicy ?? (defaultCachePolicy = new HttpRequestCachePolicy (HttpRequestCacheLevel.NoCacheNoStore));
146 throw GetMustImplement ();
150 public virtual WebHeaderCollection Headers {
151 get { throw GetMustImplement (); }
152 set { throw GetMustImplement (); }
156 public virtual string Method {
157 get { throw GetMustImplement (); }
158 set { throw GetMustImplement (); }
161 public virtual bool PreAuthenticate {
162 get { throw GetMustImplement (); }
163 set { throw GetMustImplement (); }
166 public virtual IWebProxy Proxy {
167 get { throw GetMustImplement (); }
168 set { throw GetMustImplement (); }
171 public virtual Uri RequestUri {
172 get { throw GetMustImplement (); }
175 public virtual int Timeout {
176 get { throw GetMustImplement (); }
177 set { throw GetMustImplement (); }
180 public virtual bool UseDefaultCredentials
183 throw GetMustImplement ();
186 throw GetMustImplement ();
190 public TokenImpersonationLevel ImpersonationLevel { get; set; }
192 // volatile static IWebProxy proxy;
193 static readonly object lockobj = new object ();
195 public static IWebProxy DefaultWebProxy {
197 if (!isDefaultWebProxySet) {
199 if (defaultWebProxy == null)
200 defaultWebProxy = GetDefaultWebProxy ();
203 return defaultWebProxy;
206 /* MS documentation states that a null value would cause an ArgumentNullException
207 * but that's not the way it behaves:
208 * https://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=304724
210 defaultWebProxy = value;
211 isDefaultWebProxySet = true;
215 internal static IWebProxy InternalDefaultWebProxy {
217 return DefaultWebProxy;
222 [MonoTODO("Needs to respect Module, Proxy.AutoDetect, and Proxy.ScriptLocation config settings")]
223 static IWebProxy GetDefaultWebProxy ()
225 #if CONFIGURATION_DEP
226 DefaultProxySection sec = ConfigurationManager.GetSection ("system.net/defaultProxy") as DefaultProxySection;
230 return GetSystemWebProxy ();
232 ProxyElement pe = sec.Proxy;
234 if ((pe.UseSystemDefault != ProxyElement.UseSystemDefaultValues.False) && (pe.ProxyAddress == null)) {
235 IWebProxy proxy = GetSystemWebProxy ();
237 if (!(proxy is WebProxy))
240 p = (WebProxy) proxy;
244 if (pe.ProxyAddress != null)
245 p.Address = pe.ProxyAddress;
247 if (pe.BypassOnLocal != ProxyElement.BypassOnLocalValues.Unspecified)
248 p.BypassProxyOnLocal = (pe.BypassOnLocal == ProxyElement.BypassOnLocalValues.True);
250 foreach(BypassElement elem in sec.BypassList)
251 p.BypassArrayList.Add(elem.Address);
255 return GetSystemWebProxy ();
261 public virtual void Abort()
263 throw GetMustImplement ();
266 public virtual IAsyncResult BeginGetRequestStream (AsyncCallback callback, object state)
268 throw GetMustImplement ();
271 public virtual IAsyncResult BeginGetResponse (AsyncCallback callback, object state)
273 throw GetMustImplement ();
276 public static WebRequest Create (string requestUriString)
278 if (requestUriString == null)
279 throw new ArgumentNullException ("requestUriString");
280 return Create (new Uri (requestUriString));
283 public static WebRequest Create (Uri requestUri)
285 if (requestUri == null)
286 throw new ArgumentNullException ("requestUri");
287 return GetCreator (requestUri.AbsoluteUri).Create (requestUri);
290 public static WebRequest CreateDefault (Uri requestUri)
292 if (requestUri == null)
293 throw new ArgumentNullException ("requestUri");
294 return GetCreator (requestUri.Scheme).Create (requestUri);
296 static HttpWebRequest SharedCreateHttp (Uri uri)
298 if (uri.Scheme != "http" && uri.Scheme != "https")
299 throw new NotSupportedException ("The uri should start with http or https");
301 return new HttpWebRequest (uri);
304 public static HttpWebRequest CreateHttp (string requestUriString)
306 if (requestUriString == null)
307 throw new ArgumentNullException ("requestUriString");
308 return SharedCreateHttp (new Uri (requestUriString));
311 public static HttpWebRequest CreateHttp (Uri requestUri)
313 if (requestUri == null)
314 throw new ArgumentNullException ("requestUri");
315 return SharedCreateHttp (requestUri);
317 public virtual Stream EndGetRequestStream (IAsyncResult asyncResult)
319 throw GetMustImplement ();
322 public virtual WebResponse EndGetResponse (IAsyncResult asyncResult)
324 throw GetMustImplement ();
327 public virtual Stream GetRequestStream()
329 throw GetMustImplement ();
332 public virtual WebResponse GetResponse()
334 throw GetMustImplement ();
337 // Takes an ArrayList of fileglob-formatted strings and returns an array of Regex-formatted strings
338 private static string[] CreateBypassList (ArrayList al)
340 string[] result = al.ToArray (typeof (string)) as string[];
341 for (int c = 0; c < result.Length; c++)
344 Regex.Escape (result [c]).Replace (@"\*", ".*").Replace (@"\?", ".") +
350 [MonoTODO("Look in other places for proxy config info")]
351 public static IWebProxy GetSystemWebProxy ()
354 return CFNetwork.GetDefaultProxy ();
357 // Return the system web proxy. This only works for ICS+.
358 var androidProxy = AndroidPlatform.GetDefaultProxy ();
359 if (androidProxy != null)
364 int iProxyEnable = (int)Microsoft.Win32.Registry.GetValue ("HKEY_CURRENT_USER\\Software\\Microsoft\\Windows\\CurrentVersion\\Internet Settings", "ProxyEnable", 0);
366 if (iProxyEnable > 0) {
367 string strHttpProxy = "";
368 bool bBypassOnLocal = false;
369 ArrayList al = new ArrayList ();
371 string strProxyServer = (string)Microsoft.Win32.Registry.GetValue ("HKEY_CURRENT_USER\\Software\\Microsoft\\Windows\\CurrentVersion\\Internet Settings", "ProxyServer", null);
372 string strProxyOverrride = (string)Microsoft.Win32.Registry.GetValue ("HKEY_CURRENT_USER\\Software\\Microsoft\\Windows\\CurrentVersion\\Internet Settings", "ProxyOverride", null);
374 if (strProxyServer.Contains ("=")) {
375 foreach (string strEntry in strProxyServer.Split (new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries))
376 if (strEntry.StartsWith ("http=")) {
377 strHttpProxy = strEntry.Substring (5);
380 } else strHttpProxy = strProxyServer;
382 if (strProxyOverrride != null) {
383 string[] bypassList = strProxyOverrride.Split (new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries);
385 foreach (string str in bypassList) {
386 if (str != "<local>")
389 bBypassOnLocal = true;
393 return new WebProxy (strHttpProxy, bBypassOnLocal, CreateBypassList (al));
397 if (Platform.IsMacOS)
398 return CFNetwork.GetDefaultProxy ();
400 string address = Environment.GetEnvironmentVariable ("http_proxy");
403 address = Environment.GetEnvironmentVariable ("HTTP_PROXY");
405 if (address != null) {
407 if (!address.StartsWith ("http://"))
408 address = "http://" + address;
410 Uri uri = new Uri (address);
413 if (IPAddress.TryParse (uri.Host, out ip)) {
414 if (IPAddress.Any.Equals (ip)) {
415 UriBuilder builder = new UriBuilder (uri);
416 builder.Host = "127.0.0.1";
418 } else if (IPAddress.IPv6Any.Equals (ip)) {
419 UriBuilder builder = new UriBuilder (uri);
420 builder.Host = "[::1]";
425 bool bBypassOnLocal = false;
426 ArrayList al = new ArrayList ();
427 string bypass = Environment.GetEnvironmentVariable ("no_proxy");
430 bypass = Environment.GetEnvironmentVariable ("NO_PROXY");
432 if (bypass != null) {
433 string[] bypassList = bypass.Split (new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
435 foreach (string str in bypassList) {
436 if (str != "*.local")
439 bBypassOnLocal = true;
443 return new WebProxy (uri, bBypassOnLocal, CreateBypassList (al));
444 } catch (UriFormatException) {
451 return new WebProxy ();
455 void ISerializable.GetObjectData (SerializationInfo serializationInfo, StreamingContext streamingContext)
457 throw new NotSupportedException ();
460 protected virtual void GetObjectData (SerializationInfo serializationInfo, StreamingContext streamingContext)
462 throw GetMustImplement ();
465 public static bool RegisterPrefix (string prefix, IWebRequestCreate creator)
468 throw new ArgumentNullException ("prefix");
470 throw new ArgumentNullException ("creator");
472 lock (prefixes.SyncRoot) {
473 string lowerCasePrefix = prefix.ToLower (CultureInfo.InvariantCulture);
474 if (prefixes.Contains (lowerCasePrefix))
476 prefixes.Add (lowerCasePrefix, creator);
481 private static IWebRequestCreate GetCreator (string prefix)
483 int longestPrefix = -1;
484 IWebRequestCreate creator = null;
486 prefix = prefix.ToLower (CultureInfo.InvariantCulture);
488 IDictionaryEnumerator e = prefixes.GetEnumerator ();
489 while (e.MoveNext ()) {
490 string key = e.Key as string;
492 if (key.Length <= longestPrefix)
495 if (!prefix.StartsWith (key))
498 longestPrefix = key.Length;
499 creator = (IWebRequestCreate) e.Value;
503 throw new NotSupportedException (prefix);
508 internal static bool IsWindows ()
510 return (int) Environment.OSVersion.Platform < 4;
513 internal static void ClearPrefixes ()
518 internal static void RemovePrefix (string prefix)
520 prefixes.Remove (prefix);
523 internal static void AddPrefix (string prefix, string typeName)
525 Type type = Type.GetType (typeName);
527 throw new ConfigurationException (String.Format ("Type {0} not found", typeName));
528 AddPrefix (prefix, type);
531 internal static void AddPrefix (string prefix, Type type)
533 object o = Activator.CreateInstance (type, true);
534 prefixes [prefix] = o;
537 public virtual Task<Stream> GetRequestStreamAsync ()
539 return Task<Stream>.Factory.FromAsync (BeginGetRequestStream, EndGetRequestStream, null);
542 public virtual Task<WebResponse> GetResponseAsync ()
544 return Task<WebResponse>.Factory.FromAsync (BeginGetResponse, EndGetResponse, null);