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;
68 IWebRequestCreate http = new HttpRequestCreator ();
69 RegisterPrefix ("http", http);
70 RegisterPrefix ("https", http);
72 RegisterPrefix ("file", new FileWebRequestCreator ());
73 RegisterPrefix ("ftp", new FtpRequestCreator ());
76 defaultCachePolicy = new HttpRequestCachePolicy (HttpRequestCacheLevel.NoCacheNoStore);
78 object cfg = ConfigurationManager.GetSection ("system.net/webRequestModules");
79 WebRequestModulesSection s = cfg as WebRequestModulesSection;
81 foreach (WebRequestModuleElement el in
83 AddPrefix (el.Prefix, el.Type);
87 ConfigurationSettings.GetConfig ("system.net/webRequestModules");
91 protected WebRequest ()
95 protected WebRequest (SerializationInfo serializationInfo, StreamingContext streamingContext)
99 static Exception GetMustImplement ()
101 return new NotImplementedException ("This method must be implemented in derived classes");
106 private AuthenticationLevel authentication_level = AuthenticationLevel.MutualAuthRequested;
108 public AuthenticationLevel AuthenticationLevel
111 return(authentication_level);
114 authentication_level = value;
118 [MonoTODO ("Implement the caching system. Currently always returns a policy with the NoCacheNoStore level")]
119 public virtual RequestCachePolicy CachePolicy
121 get { return DefaultCachePolicy; }
126 public virtual string ConnectionGroupName {
127 get { throw GetMustImplement (); }
128 set { throw GetMustImplement (); }
131 public virtual long ContentLength {
132 get { throw GetMustImplement (); }
133 set { throw GetMustImplement (); }
136 public virtual string ContentType {
137 get { throw GetMustImplement (); }
138 set { throw GetMustImplement (); }
141 public virtual ICredentials Credentials {
142 get { throw GetMustImplement (); }
143 set { throw GetMustImplement (); }
146 public static RequestCachePolicy DefaultCachePolicy
148 get { return defaultCachePolicy; }
150 throw GetMustImplement ();
154 public virtual WebHeaderCollection Headers {
155 get { throw GetMustImplement (); }
156 set { throw GetMustImplement (); }
159 public TokenImpersonationLevel ImpersonationLevel {
160 get { throw GetMustImplement (); }
161 set { throw GetMustImplement (); }
164 public virtual string Method {
165 get { throw GetMustImplement (); }
166 set { throw GetMustImplement (); }
169 public virtual bool PreAuthenticate {
170 get { throw GetMustImplement (); }
171 set { throw GetMustImplement (); }
174 public virtual IWebProxy Proxy {
175 get { throw GetMustImplement (); }
176 set { throw GetMustImplement (); }
179 public virtual Uri RequestUri {
180 get { throw GetMustImplement (); }
183 public virtual int Timeout {
184 get { throw GetMustImplement (); }
185 set { throw GetMustImplement (); }
188 public virtual bool UseDefaultCredentials
191 throw GetMustImplement ();
194 throw GetMustImplement ();
198 // volatile static IWebProxy proxy;
199 static readonly object lockobj = new object ();
201 public static IWebProxy DefaultWebProxy {
203 if (!isDefaultWebProxySet) {
205 if (defaultWebProxy == null)
206 defaultWebProxy = GetDefaultWebProxy ();
209 return defaultWebProxy;
212 /* MS documentation states that a null value would cause an ArgumentNullException
213 * but that's not the way it behaves:
214 * https://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=304724
216 defaultWebProxy = value;
217 isDefaultWebProxySet = true;
221 [MonoTODO("Needs to respect Module, Proxy.AutoDetect, and Proxy.ScriptLocation config settings")]
222 static IWebProxy GetDefaultWebProxy ()
224 #if CONFIGURATION_DEP
225 DefaultProxySection sec = ConfigurationManager.GetSection ("system.net/defaultProxy") as DefaultProxySection;
229 return GetSystemWebProxy ();
231 ProxyElement pe = sec.Proxy;
233 if ((pe.UseSystemDefault != ProxyElement.UseSystemDefaultValues.False) && (pe.ProxyAddress == null)) {
234 IWebProxy proxy = GetSystemWebProxy ();
236 if (!(proxy is WebProxy))
239 p = (WebProxy) proxy;
243 if (pe.ProxyAddress != null)
244 p.Address = pe.ProxyAddress;
246 if (pe.BypassOnLocal != ProxyElement.BypassOnLocalValues.Unspecified)
247 p.BypassProxyOnLocal = (pe.BypassOnLocal == ProxyElement.BypassOnLocalValues.True);
249 foreach(BypassElement elem in sec.BypassList)
250 p.BypassArrayList.Add(elem.Address);
254 return GetSystemWebProxy ();
260 public virtual void Abort()
262 throw GetMustImplement ();
265 public virtual IAsyncResult BeginGetRequestStream (AsyncCallback callback, object state)
267 throw GetMustImplement ();
270 public virtual IAsyncResult BeginGetResponse (AsyncCallback callback, object state)
272 throw GetMustImplement ();
275 public static WebRequest Create (string requestUriString)
277 if (requestUriString == null)
278 throw new ArgumentNullException ("requestUriString");
279 return Create (new Uri (requestUriString));
282 public static WebRequest Create (Uri requestUri)
284 if (requestUri == null)
285 throw new ArgumentNullException ("requestUri");
286 return GetCreator (requestUri.AbsoluteUri).Create (requestUri);
289 public static WebRequest CreateDefault (Uri requestUri)
291 if (requestUri == null)
292 throw new ArgumentNullException ("requestUri");
293 return GetCreator (requestUri.Scheme).Create (requestUri);
295 #if NET_4_5 || MOBILE
296 [MonoTODO ("for portable library support")]
297 public static HttpWebRequest CreateHttp (string requestUriString)
299 throw new NotImplementedException ();
302 [MonoTODO ("for portable library support")]
303 public static HttpWebRequest CreateHttp (Uri requestUri)
305 throw new NotImplementedException ();
308 public virtual Stream EndGetRequestStream (IAsyncResult asyncResult)
310 throw GetMustImplement ();
313 public virtual WebResponse EndGetResponse (IAsyncResult asyncResult)
315 throw GetMustImplement ();
318 public virtual Stream GetRequestStream()
320 throw GetMustImplement ();
323 public virtual WebResponse GetResponse()
325 throw GetMustImplement ();
328 [MonoTODO("Look in other places for proxy config info")]
329 public static IWebProxy GetSystemWebProxy ()
333 int iProxyEnable = (int)Microsoft.Win32.Registry.GetValue ("HKEY_CURRENT_USER\\Software\\Microsoft\\Windows\\CurrentVersion\\Internet Settings", "ProxyEnable", 0);
335 if (iProxyEnable > 0) {
336 string strHttpProxy = "";
337 bool bBypassOnLocal = false;
338 ArrayList al = new ArrayList ();
340 string strProxyServer = (string)Microsoft.Win32.Registry.GetValue ("HKEY_CURRENT_USER\\Software\\Microsoft\\Windows\\CurrentVersion\\Internet Settings", "ProxyServer", null);
341 string strProxyOverrride = (string)Microsoft.Win32.Registry.GetValue ("HKEY_CURRENT_USER\\Software\\Microsoft\\Windows\\CurrentVersion\\Internet Settings", "ProxyOverride", null);
343 if (strProxyServer.Contains ("=")) {
344 foreach (string strEntry in strProxyServer.Split (new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries))
345 if (strEntry.StartsWith ("http=")) {
346 strHttpProxy = strEntry.Substring (5);
349 } else strHttpProxy = strProxyServer;
351 if (strProxyOverrride != null) {
352 string[] bypassList = strProxyOverrride.Split (new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries);
354 foreach (string str in bypassList) {
355 if (str != "<local>")
358 bBypassOnLocal = true;
362 return new WebProxy (strHttpProxy, bBypassOnLocal, al.ToArray (typeof(string)) as string[]);
366 if (Platform.IsMacOS)
367 return CFNetwork.GetDefaultProxy ();
369 string address = Environment.GetEnvironmentVariable ("http_proxy");
372 address = Environment.GetEnvironmentVariable ("HTTP_PROXY");
374 if (address != null) {
376 if (!address.StartsWith ("http://"))
377 address = "http://" + address;
379 Uri uri = new Uri (address);
382 if (IPAddress.TryParse (uri.Host, out ip)) {
383 if (IPAddress.Any.Equals (ip)) {
384 UriBuilder builder = new UriBuilder (uri);
385 builder.Host = "127.0.0.1";
387 } else if (IPAddress.IPv6Any.Equals (ip)) {
388 UriBuilder builder = new UriBuilder (uri);
389 builder.Host = "[::1]";
394 bool bBypassOnLocal = false;
395 ArrayList al = new ArrayList ();
396 string bypass = Environment.GetEnvironmentVariable ("no_proxy");
399 bypass = Environment.GetEnvironmentVariable ("NO_PROXY");
401 if (bypass != null) {
402 string[] bypassList = bypass.Split (new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
404 foreach (string str in bypassList) {
405 if (str != "*.local")
408 bBypassOnLocal = true;
412 return new WebProxy (uri, bBypassOnLocal, al.ToArray (typeof(string)) as string[]);
413 } catch (UriFormatException) {
420 return new WebProxy ();
423 void ISerializable.GetObjectData (SerializationInfo serializationInfo, StreamingContext streamingContext)
425 throw new NotSupportedException ();
428 protected virtual void GetObjectData (SerializationInfo serializationInfo, StreamingContext streamingContext)
430 throw GetMustImplement ();
433 public static bool RegisterPrefix (string prefix, IWebRequestCreate creator)
436 throw new ArgumentNullException ("prefix");
438 throw new ArgumentNullException ("creator");
440 lock (prefixes.SyncRoot) {
441 string lowerCasePrefix = prefix.ToLower (CultureInfo.InvariantCulture);
442 if (prefixes.Contains (lowerCasePrefix))
444 prefixes.Add (lowerCasePrefix, creator);
449 private static IWebRequestCreate GetCreator (string prefix)
451 int longestPrefix = -1;
452 IWebRequestCreate creator = null;
454 prefix = prefix.ToLower (CultureInfo.InvariantCulture);
456 IDictionaryEnumerator e = prefixes.GetEnumerator ();
457 while (e.MoveNext ()) {
458 string key = e.Key as string;
460 if (key.Length <= longestPrefix)
463 if (!prefix.StartsWith (key))
466 longestPrefix = key.Length;
467 creator = (IWebRequestCreate) e.Value;
471 throw new NotSupportedException (prefix);
476 internal static bool IsWindows ()
478 return (int) Environment.OSVersion.Platform < 4;
481 internal static void ClearPrefixes ()
486 internal static void RemovePrefix (string prefix)
488 prefixes.Remove (prefix);
491 internal static void AddPrefix (string prefix, string typeName)
493 Type type = Type.GetType (typeName);
495 throw new ConfigurationException (String.Format ("Type {0} not found", typeName));
496 AddPrefix (prefix, type);
499 internal static void AddPrefix (string prefix, Type type)
501 object o = Activator.CreateInstance (type, true);
502 prefixes [prefix] = o;
506 public virtual Task<Stream> GetRequestStreamAsync ()
508 return Task<Stream>.Factory.FromAsync (BeginGetRequestStream, EndGetRequestStream, null);
511 public virtual Task<WebResponse> GetResponseAsync ()
513 return Task<WebResponse>.Factory.FromAsync (BeginGetResponse, EndGetResponse, null);