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;
63 static RequestCachePolicy defaultCachePolicy;
70 IWebRequestCreate http = new HttpRequestCreator ();
71 RegisterPrefix ("http", http);
72 RegisterPrefix ("https", http);
74 RegisterPrefix ("file", new FileWebRequestCreator ());
75 RegisterPrefix ("ftp", new FtpRequestCreator ());
78 defaultCachePolicy = new HttpRequestCachePolicy (HttpRequestCacheLevel.NoCacheNoStore);
80 object cfg = ConfigurationManager.GetSection ("system.net/webRequestModules");
81 WebRequestModulesSection s = cfg as WebRequestModulesSection;
83 foreach (WebRequestModuleElement el in
85 AddPrefix (el.Prefix, el.Type);
89 ConfigurationSettings.GetConfig ("system.net/webRequestModules");
93 protected WebRequest ()
97 protected WebRequest (SerializationInfo serializationInfo, StreamingContext streamingContext)
101 static Exception GetMustImplement ()
103 return new NotImplementedException ("This method must be implemented in derived classes");
108 private AuthenticationLevel authentication_level = AuthenticationLevel.MutualAuthRequested;
110 public AuthenticationLevel AuthenticationLevel
113 return(authentication_level);
116 authentication_level = value;
120 public virtual string ConnectionGroupName {
121 get { throw GetMustImplement (); }
122 set { throw GetMustImplement (); }
125 public virtual long ContentLength {
126 get { throw GetMustImplement (); }
127 set { throw GetMustImplement (); }
130 public virtual string ContentType {
131 get { throw GetMustImplement (); }
132 set { throw GetMustImplement (); }
135 public virtual ICredentials Credentials {
136 get { throw GetMustImplement (); }
137 set { throw GetMustImplement (); }
141 [MonoTODO ("Implement the caching system. Currently always returns a policy with the NoCacheNoStore level")]
142 public virtual RequestCachePolicy CachePolicy
144 get { return DefaultCachePolicy; }
149 public static RequestCachePolicy DefaultCachePolicy
151 get { return defaultCachePolicy; }
153 throw GetMustImplement ();
158 public virtual WebHeaderCollection Headers {
159 get { throw GetMustImplement (); }
160 set { throw GetMustImplement (); }
163 public TokenImpersonationLevel ImpersonationLevel {
164 get { throw GetMustImplement (); }
165 set { throw GetMustImplement (); }
168 public virtual string Method {
169 get { throw GetMustImplement (); }
170 set { throw GetMustImplement (); }
173 public virtual bool PreAuthenticate {
174 get { throw GetMustImplement (); }
175 set { throw GetMustImplement (); }
178 public virtual IWebProxy Proxy {
179 get { throw GetMustImplement (); }
180 set { throw GetMustImplement (); }
183 public virtual Uri RequestUri {
184 get { throw GetMustImplement (); }
187 public virtual int Timeout {
188 get { throw GetMustImplement (); }
189 set { throw GetMustImplement (); }
192 public virtual bool UseDefaultCredentials
195 throw GetMustImplement ();
198 throw GetMustImplement ();
202 // volatile static IWebProxy proxy;
203 static readonly object lockobj = new object ();
205 public static IWebProxy DefaultWebProxy {
207 if (!isDefaultWebProxySet) {
209 if (defaultWebProxy == null)
210 defaultWebProxy = GetDefaultWebProxy ();
213 return defaultWebProxy;
216 /* MS documentation states that a null value would cause an ArgumentNullException
217 * but that's not the way it behaves:
218 * https://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=304724
220 defaultWebProxy = value;
221 isDefaultWebProxySet = true;
225 [MonoTODO("Needs to respect Module, Proxy.AutoDetect, and Proxy.ScriptLocation config settings")]
226 static IWebProxy GetDefaultWebProxy ()
228 #if CONFIGURATION_DEP
229 DefaultProxySection sec = ConfigurationManager.GetSection ("system.net/defaultProxy") as DefaultProxySection;
233 return GetSystemWebProxy ();
235 ProxyElement pe = sec.Proxy;
237 if ((pe.UseSystemDefault != ProxyElement.UseSystemDefaultValues.False) && (pe.ProxyAddress == null)) {
238 IWebProxy proxy = GetSystemWebProxy ();
240 if (!(proxy is WebProxy))
243 p = (WebProxy) proxy;
247 if (pe.ProxyAddress != null)
248 p.Address = pe.ProxyAddress;
250 if (pe.BypassOnLocal != ProxyElement.BypassOnLocalValues.Unspecified)
251 p.BypassProxyOnLocal = (pe.BypassOnLocal == ProxyElement.BypassOnLocalValues.True);
253 foreach(BypassElement elem in sec.BypassList)
254 p.BypassArrayList.Add(elem.Address);
258 return GetSystemWebProxy ();
264 public virtual void Abort()
266 throw GetMustImplement ();
269 public virtual IAsyncResult BeginGetRequestStream (AsyncCallback callback, object state)
271 throw GetMustImplement ();
274 public virtual IAsyncResult BeginGetResponse (AsyncCallback callback, object state)
276 throw GetMustImplement ();
279 public static WebRequest Create (string requestUriString)
281 if (requestUriString == null)
282 throw new ArgumentNullException ("requestUriString");
283 return Create (new Uri (requestUriString));
286 public static WebRequest Create (Uri requestUri)
288 if (requestUri == null)
289 throw new ArgumentNullException ("requestUri");
290 return GetCreator (requestUri.AbsoluteUri).Create (requestUri);
293 public static WebRequest CreateDefault (Uri requestUri)
295 if (requestUri == null)
296 throw new ArgumentNullException ("requestUri");
297 return GetCreator (requestUri.Scheme).Create (requestUri);
300 [MonoTODO ("for portable library support")]
301 public static HttpWebRequest CreateHttp (string requestUriString)
303 throw new NotImplementedException ();
306 [MonoTODO ("for portable library support")]
307 public static HttpWebRequest CreateHttp (Uri requestUri)
309 throw new NotImplementedException ();
312 public virtual Stream EndGetRequestStream (IAsyncResult asyncResult)
314 throw GetMustImplement ();
317 public virtual WebResponse EndGetResponse (IAsyncResult asyncResult)
319 throw GetMustImplement ();
322 public virtual Stream GetRequestStream()
324 throw GetMustImplement ();
327 public virtual WebResponse GetResponse()
329 throw GetMustImplement ();
332 [MonoTODO("Look in other places for proxy config info")]
333 public static IWebProxy GetSystemWebProxy ()
336 return CFNetwork.GetDefaultProxy ();
340 int iProxyEnable = (int)Microsoft.Win32.Registry.GetValue ("HKEY_CURRENT_USER\\Software\\Microsoft\\Windows\\CurrentVersion\\Internet Settings", "ProxyEnable", 0);
342 if (iProxyEnable > 0) {
343 string strHttpProxy = "";
344 bool bBypassOnLocal = false;
345 ArrayList al = new ArrayList ();
347 string strProxyServer = (string)Microsoft.Win32.Registry.GetValue ("HKEY_CURRENT_USER\\Software\\Microsoft\\Windows\\CurrentVersion\\Internet Settings", "ProxyServer", null);
348 string strProxyOverrride = (string)Microsoft.Win32.Registry.GetValue ("HKEY_CURRENT_USER\\Software\\Microsoft\\Windows\\CurrentVersion\\Internet Settings", "ProxyOverride", null);
350 if (strProxyServer.Contains ("=")) {
351 foreach (string strEntry in strProxyServer.Split (new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries))
352 if (strEntry.StartsWith ("http=")) {
353 strHttpProxy = strEntry.Substring (5);
356 } else strHttpProxy = strProxyServer;
358 if (strProxyOverrride != null) {
359 string[] bypassList = strProxyOverrride.Split (new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries);
361 foreach (string str in bypassList) {
362 if (str != "<local>")
365 bBypassOnLocal = true;
369 return new WebProxy (strHttpProxy, bBypassOnLocal, al.ToArray (typeof(string)) as string[]);
373 if (Platform.IsMacOS)
374 return CFNetwork.GetDefaultProxy ();
376 string address = Environment.GetEnvironmentVariable ("http_proxy");
379 address = Environment.GetEnvironmentVariable ("HTTP_PROXY");
381 if (address != null) {
383 if (!address.StartsWith ("http://"))
384 address = "http://" + address;
386 Uri uri = new Uri (address);
389 if (IPAddress.TryParse (uri.Host, out ip)) {
390 if (IPAddress.Any.Equals (ip)) {
391 UriBuilder builder = new UriBuilder (uri);
392 builder.Host = "127.0.0.1";
394 } else if (IPAddress.IPv6Any.Equals (ip)) {
395 UriBuilder builder = new UriBuilder (uri);
396 builder.Host = "[::1]";
401 bool bBypassOnLocal = false;
402 ArrayList al = new ArrayList ();
403 string bypass = Environment.GetEnvironmentVariable ("no_proxy");
406 bypass = Environment.GetEnvironmentVariable ("NO_PROXY");
408 if (bypass != null) {
409 string[] bypassList = bypass.Split (new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
411 foreach (string str in bypassList) {
412 if (str != "*.local")
415 bBypassOnLocal = true;
419 return new WebProxy (uri, bBypassOnLocal, al.ToArray (typeof(string)) as string[]);
420 } catch (UriFormatException) {
427 return new WebProxy ();
431 void ISerializable.GetObjectData (SerializationInfo serializationInfo, StreamingContext streamingContext)
433 throw new NotSupportedException ();
436 protected virtual void GetObjectData (SerializationInfo serializationInfo, StreamingContext streamingContext)
438 throw GetMustImplement ();
441 public static bool RegisterPrefix (string prefix, IWebRequestCreate creator)
444 throw new ArgumentNullException ("prefix");
446 throw new ArgumentNullException ("creator");
448 lock (prefixes.SyncRoot) {
449 string lowerCasePrefix = prefix.ToLower (CultureInfo.InvariantCulture);
450 if (prefixes.Contains (lowerCasePrefix))
452 prefixes.Add (lowerCasePrefix, creator);
457 private static IWebRequestCreate GetCreator (string prefix)
459 int longestPrefix = -1;
460 IWebRequestCreate creator = null;
462 prefix = prefix.ToLower (CultureInfo.InvariantCulture);
464 IDictionaryEnumerator e = prefixes.GetEnumerator ();
465 while (e.MoveNext ()) {
466 string key = e.Key as string;
468 if (key.Length <= longestPrefix)
471 if (!prefix.StartsWith (key))
474 longestPrefix = key.Length;
475 creator = (IWebRequestCreate) e.Value;
479 throw new NotSupportedException (prefix);
484 internal static bool IsWindows ()
486 return (int) Environment.OSVersion.Platform < 4;
489 internal static void ClearPrefixes ()
494 internal static void RemovePrefix (string prefix)
496 prefixes.Remove (prefix);
499 internal static void AddPrefix (string prefix, string typeName)
501 Type type = Type.GetType (typeName);
503 throw new ConfigurationException (String.Format ("Type {0} not found", typeName));
504 AddPrefix (prefix, type);
507 internal static void AddPrefix (string prefix, Type type)
509 object o = Activator.CreateInstance (type, true);
510 prefixes [prefix] = o;
514 public virtual Task<Stream> GetRequestStreamAsync ()
516 return Task<Stream>.Factory.FromAsync (BeginGetRequestStream, EndGetRequestStream, null);
519 public virtual Task<WebResponse> GetResponseAsync ()
521 return Task<WebResponse>.Factory.FromAsync (BeginGetResponse, EndGetResponse, null);