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;
43 using System.Threading.Tasks;
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 (); }
155 public TokenImpersonationLevel ImpersonationLevel {
156 get { throw GetMustImplement (); }
157 set { throw GetMustImplement (); }
160 public virtual string Method {
161 get { throw GetMustImplement (); }
162 set { throw GetMustImplement (); }
165 public virtual bool PreAuthenticate {
166 get { throw GetMustImplement (); }
167 set { throw GetMustImplement (); }
170 public virtual IWebProxy Proxy {
171 get { throw GetMustImplement (); }
172 set { throw GetMustImplement (); }
175 public virtual Uri RequestUri {
176 get { throw GetMustImplement (); }
179 public virtual int Timeout {
180 get { throw GetMustImplement (); }
181 set { throw GetMustImplement (); }
184 public virtual bool UseDefaultCredentials
187 throw GetMustImplement ();
190 throw GetMustImplement ();
194 // volatile static IWebProxy proxy;
195 static readonly object lockobj = new object ();
197 public static IWebProxy DefaultWebProxy {
199 if (!isDefaultWebProxySet) {
201 if (defaultWebProxy == null)
202 defaultWebProxy = GetDefaultWebProxy ();
205 return defaultWebProxy;
208 /* MS documentation states that a null value would cause an ArgumentNullException
209 * but that's not the way it behaves:
210 * https://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=304724
212 defaultWebProxy = value;
213 isDefaultWebProxySet = true;
217 [MonoTODO("Needs to respect Module, Proxy.AutoDetect, and Proxy.ScriptLocation config settings")]
218 static IWebProxy GetDefaultWebProxy ()
220 #if CONFIGURATION_DEP
221 DefaultProxySection sec = ConfigurationManager.GetSection ("system.net/defaultProxy") as DefaultProxySection;
225 return GetSystemWebProxy ();
227 ProxyElement pe = sec.Proxy;
229 if ((pe.UseSystemDefault != ProxyElement.UseSystemDefaultValues.False) && (pe.ProxyAddress == null)) {
230 IWebProxy proxy = GetSystemWebProxy ();
232 if (!(proxy is WebProxy))
235 p = (WebProxy) proxy;
239 if (pe.ProxyAddress != null)
240 p.Address = pe.ProxyAddress;
242 if (pe.BypassOnLocal != ProxyElement.BypassOnLocalValues.Unspecified)
243 p.BypassProxyOnLocal = (pe.BypassOnLocal == ProxyElement.BypassOnLocalValues.True);
245 foreach(BypassElement elem in sec.BypassList)
246 p.BypassArrayList.Add(elem.Address);
250 return GetSystemWebProxy ();
256 public virtual void Abort()
258 throw GetMustImplement ();
261 public virtual IAsyncResult BeginGetRequestStream (AsyncCallback callback, object state)
263 throw GetMustImplement ();
266 public virtual IAsyncResult BeginGetResponse (AsyncCallback callback, object state)
268 throw GetMustImplement ();
271 public static WebRequest Create (string requestUriString)
273 if (requestUriString == null)
274 throw new ArgumentNullException ("requestUriString");
275 return Create (new Uri (requestUriString));
278 public static WebRequest Create (Uri requestUri)
280 if (requestUri == null)
281 throw new ArgumentNullException ("requestUri");
282 return GetCreator (requestUri.AbsoluteUri).Create (requestUri);
285 public static WebRequest CreateDefault (Uri requestUri)
287 if (requestUri == null)
288 throw new ArgumentNullException ("requestUri");
289 return GetCreator (requestUri.Scheme).Create (requestUri);
292 [MonoTODO ("for portable library support")]
293 public static HttpWebRequest CreateHttp (string requestUriString)
295 throw new NotImplementedException ();
298 [MonoTODO ("for portable library support")]
299 public static HttpWebRequest CreateHttp (Uri requestUri)
301 throw new NotImplementedException ();
304 public virtual Stream EndGetRequestStream (IAsyncResult asyncResult)
306 throw GetMustImplement ();
309 public virtual WebResponse EndGetResponse (IAsyncResult asyncResult)
311 throw GetMustImplement ();
314 public virtual Stream GetRequestStream()
316 throw GetMustImplement ();
319 public virtual WebResponse GetResponse()
321 throw GetMustImplement ();
324 [MonoTODO("Look in other places for proxy config info")]
325 public static IWebProxy GetSystemWebProxy ()
328 return CFNetwork.GetDefaultProxy ();
331 // Return the system web proxy. This only works for ICS+.
332 var androidProxy = AndroidPlatform.GetDefaultProxy ();
333 if (androidProxy != null)
338 int iProxyEnable = (int)Microsoft.Win32.Registry.GetValue ("HKEY_CURRENT_USER\\Software\\Microsoft\\Windows\\CurrentVersion\\Internet Settings", "ProxyEnable", 0);
340 if (iProxyEnable > 0) {
341 string strHttpProxy = "";
342 bool bBypassOnLocal = false;
343 ArrayList al = new ArrayList ();
345 string strProxyServer = (string)Microsoft.Win32.Registry.GetValue ("HKEY_CURRENT_USER\\Software\\Microsoft\\Windows\\CurrentVersion\\Internet Settings", "ProxyServer", null);
346 string strProxyOverrride = (string)Microsoft.Win32.Registry.GetValue ("HKEY_CURRENT_USER\\Software\\Microsoft\\Windows\\CurrentVersion\\Internet Settings", "ProxyOverride", null);
348 if (strProxyServer.Contains ("=")) {
349 foreach (string strEntry in strProxyServer.Split (new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries))
350 if (strEntry.StartsWith ("http=")) {
351 strHttpProxy = strEntry.Substring (5);
354 } else strHttpProxy = strProxyServer;
356 if (strProxyOverrride != null) {
357 string[] bypassList = strProxyOverrride.Split (new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries);
359 foreach (string str in bypassList) {
360 if (str != "<local>")
363 bBypassOnLocal = true;
367 return new WebProxy (strHttpProxy, bBypassOnLocal, al.ToArray (typeof(string)) as string[]);
371 if (Platform.IsMacOS)
372 return CFNetwork.GetDefaultProxy ();
374 string address = Environment.GetEnvironmentVariable ("http_proxy");
377 address = Environment.GetEnvironmentVariable ("HTTP_PROXY");
379 if (address != null) {
381 if (!address.StartsWith ("http://"))
382 address = "http://" + address;
384 Uri uri = new Uri (address);
387 if (IPAddress.TryParse (uri.Host, out ip)) {
388 if (IPAddress.Any.Equals (ip)) {
389 UriBuilder builder = new UriBuilder (uri);
390 builder.Host = "127.0.0.1";
392 } else if (IPAddress.IPv6Any.Equals (ip)) {
393 UriBuilder builder = new UriBuilder (uri);
394 builder.Host = "[::1]";
399 bool bBypassOnLocal = false;
400 ArrayList al = new ArrayList ();
401 string bypass = Environment.GetEnvironmentVariable ("no_proxy");
404 bypass = Environment.GetEnvironmentVariable ("NO_PROXY");
406 if (bypass != null) {
407 string[] bypassList = bypass.Split (new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
409 foreach (string str in bypassList) {
410 if (str != "*.local")
413 bBypassOnLocal = true;
417 return new WebProxy (uri, bBypassOnLocal, al.ToArray (typeof(string)) as string[]);
418 } catch (UriFormatException) {
425 return new WebProxy ();
429 void ISerializable.GetObjectData (SerializationInfo serializationInfo, StreamingContext streamingContext)
431 throw new NotSupportedException ();
434 protected virtual void GetObjectData (SerializationInfo serializationInfo, StreamingContext streamingContext)
436 throw GetMustImplement ();
439 public static bool RegisterPrefix (string prefix, IWebRequestCreate creator)
442 throw new ArgumentNullException ("prefix");
444 throw new ArgumentNullException ("creator");
446 lock (prefixes.SyncRoot) {
447 string lowerCasePrefix = prefix.ToLower (CultureInfo.InvariantCulture);
448 if (prefixes.Contains (lowerCasePrefix))
450 prefixes.Add (lowerCasePrefix, creator);
455 private static IWebRequestCreate GetCreator (string prefix)
457 int longestPrefix = -1;
458 IWebRequestCreate creator = null;
460 prefix = prefix.ToLower (CultureInfo.InvariantCulture);
462 IDictionaryEnumerator e = prefixes.GetEnumerator ();
463 while (e.MoveNext ()) {
464 string key = e.Key as string;
466 if (key.Length <= longestPrefix)
469 if (!prefix.StartsWith (key))
472 longestPrefix = key.Length;
473 creator = (IWebRequestCreate) e.Value;
477 throw new NotSupportedException (prefix);
482 internal static bool IsWindows ()
484 return (int) Environment.OSVersion.Platform < 4;
487 internal static void ClearPrefixes ()
492 internal static void RemovePrefix (string prefix)
494 prefixes.Remove (prefix);
497 internal static void AddPrefix (string prefix, string typeName)
499 Type type = Type.GetType (typeName);
501 throw new ConfigurationException (String.Format ("Type {0} not found", typeName));
502 AddPrefix (prefix, type);
505 internal static void AddPrefix (string prefix, Type type)
507 object o = Activator.CreateInstance (type, true);
508 prefixes [prefix] = o;
512 public virtual Task<Stream> GetRequestStreamAsync ()
514 return Task<Stream>.Factory.FromAsync (BeginGetRequestStream, EndGetRequestStream, null);
517 public virtual Task<WebResponse> GetResponseAsync ()
519 return Task<WebResponse>.Factory.FromAsync (BeginGetResponse, EndGetResponse, null);