[bcl] Remove NET_4_0 defines from class libs.
[mono.git] / mcs / class / System / System.Net / WebRequest.cs
1 //
2 // System.Net.WebRequest
3 //
4 // Authors:
5 //  Lawrence Pit (loz@cable.a2000.nl)
6 //      Marek Safar (marek.safar@gmail.com)
7 //
8 // Copyright 2011 Xamarin Inc.
9 //
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:
17 // 
18 // The above copyright notice and this permission notice shall be
19 // included in all copies or substantial portions of the Software.
20 // 
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.
28 //
29
30 using System;
31 using System.Collections;
32 using System.Collections.Specialized;
33 using System.Configuration;
34 using System.IO;
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 #if NET_4_5
43 using System.Threading.Tasks;
44 #endif
45
46 #if NET_2_1
47 using ConfigurationException = System.ArgumentException;
48
49 namespace System.Net.Configuration {
50         class Dummy {}
51 }
52 #endif
53
54 namespace System.Net 
55 {
56         [Serializable]
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;
62
63                 static WebRequest ()
64                 {
65 #if MOBILE
66                         IWebRequestCreate http = new HttpRequestCreator ();
67                         RegisterPrefix ("http", http);
68                         RegisterPrefix ("https", http);
69                         RegisterPrefix ("file", new FileWebRequestCreator ());
70                         RegisterPrefix ("ftp", new FtpRequestCreator ());
71 #else
72         #if CONFIGURATION_DEP
73                         object cfg = ConfigurationManager.GetSection ("system.net/webRequestModules");
74                         WebRequestModulesSection s = cfg as WebRequestModulesSection;
75                         if (s != null) {
76                                 foreach (WebRequestModuleElement el in
77                                          s.WebRequestModules)
78                                         AddPrefix (el.Prefix, el.Type);
79                                 return;
80                         }
81         #endif
82                         ConfigurationSettings.GetConfig ("system.net/webRequestModules");
83 #endif
84                 }
85                 
86                 protected WebRequest () 
87                 {
88                 }
89                 
90                 protected WebRequest (SerializationInfo serializationInfo, StreamingContext streamingContext) 
91                 {
92                 }
93
94                 static Exception GetMustImplement ()
95                 {
96                         return new NotImplementedException ("This method must be implemented in derived classes");
97                 }
98                 
99                 // Properties
100
101                 private AuthenticationLevel authentication_level = AuthenticationLevel.MutualAuthRequested;
102                 
103                 public AuthenticationLevel AuthenticationLevel
104                 {
105                         get {
106                                 return(authentication_level);
107                         }
108                         set {
109                                 authentication_level = value;
110                         }
111                 }
112                 
113                 public virtual string ConnectionGroupName {
114                         get { throw GetMustImplement (); }
115                         set { throw GetMustImplement (); }
116                 }
117                 
118                 public virtual long ContentLength { 
119                         get { throw GetMustImplement (); }
120                         set { throw GetMustImplement (); }
121                 }
122                 
123                 public virtual string ContentType { 
124                         get { throw GetMustImplement (); }
125                         set { throw GetMustImplement (); }
126                 }
127                 
128                 public virtual ICredentials Credentials { 
129                         get { throw GetMustImplement (); }
130                         set { throw GetMustImplement (); }
131                 }
132
133                 [MonoTODO ("Implement the caching system. Currently always returns a policy with the NoCacheNoStore level")]
134                 public virtual RequestCachePolicy CachePolicy
135                 {
136                         get { return DefaultCachePolicy; }
137                         set {
138                         }
139                 }
140                 
141                 public static RequestCachePolicy DefaultCachePolicy {
142                         get {
143                                 return defaultCachePolicy ?? (defaultCachePolicy = new HttpRequestCachePolicy (HttpRequestCacheLevel.NoCacheNoStore));
144                         }
145                         set {
146                                 throw GetMustImplement ();
147                         }
148                 }
149                 
150                 public virtual WebHeaderCollection Headers { 
151                         get { throw GetMustImplement (); }
152                         set { throw GetMustImplement (); }
153                 }
154                 
155
156                 public virtual string Method { 
157                         get { throw GetMustImplement (); }
158                         set { throw GetMustImplement (); }
159                 }
160                 
161                 public virtual bool PreAuthenticate { 
162                         get { throw GetMustImplement (); }
163                         set { throw GetMustImplement (); }
164                 }
165                 
166                 public virtual IWebProxy Proxy { 
167                         get { throw GetMustImplement (); }
168                         set { throw GetMustImplement (); }
169                 }
170                 
171                 public virtual Uri RequestUri { 
172                         get { throw GetMustImplement (); }
173                 }
174                 
175                 public virtual int Timeout { 
176                         get { throw GetMustImplement (); }
177                         set { throw GetMustImplement (); }
178                 }
179                 
180                 public virtual bool UseDefaultCredentials
181                 {
182                         get {
183                                 throw GetMustImplement ();
184                         }
185                         set {
186                                 throw GetMustImplement ();
187                         }
188                 }
189
190                 public TokenImpersonationLevel ImpersonationLevel { get; set; }
191
192 //              volatile static IWebProxy proxy;
193                 static readonly object lockobj = new object ();
194                 
195                 public static IWebProxy DefaultWebProxy {
196                         get {
197                                 if (!isDefaultWebProxySet) {
198                                         lock (lockobj) {
199                                                 if (defaultWebProxy == null)
200                                                         defaultWebProxy = GetDefaultWebProxy ();
201                                         }
202                                 }
203                                 return defaultWebProxy;
204                         }
205                         set {
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
209                                  */
210                                 defaultWebProxy = value;
211                                 isDefaultWebProxySet = true;
212                         }
213                 }
214                 
215                 [MonoTODO("Needs to respect Module, Proxy.AutoDetect, and Proxy.ScriptLocation config settings")]
216                 static IWebProxy GetDefaultWebProxy ()
217                 {
218 #if CONFIGURATION_DEP
219                         DefaultProxySection sec = ConfigurationManager.GetSection ("system.net/defaultProxy") as DefaultProxySection;
220                         WebProxy p;
221                         
222                         if (sec == null)
223                                 return GetSystemWebProxy ();
224                         
225                         ProxyElement pe = sec.Proxy;
226                         
227                         if ((pe.UseSystemDefault != ProxyElement.UseSystemDefaultValues.False) && (pe.ProxyAddress == null)) {
228                                 IWebProxy proxy = GetSystemWebProxy ();
229                                 
230                                 if (!(proxy is WebProxy))
231                                         return proxy;
232                                 
233                                 p = (WebProxy) proxy;
234                         } else
235                                 p = new WebProxy ();
236                         
237                         if (pe.ProxyAddress != null)
238                                 p.Address = pe.ProxyAddress;
239                         
240                         if (pe.BypassOnLocal != ProxyElement.BypassOnLocalValues.Unspecified)
241                                 p.BypassProxyOnLocal = (pe.BypassOnLocal == ProxyElement.BypassOnLocalValues.True);
242                                 
243                         foreach(BypassElement elem in sec.BypassList)
244                                 p.BypassArrayList.Add(elem.Address);
245                         
246                         return p;
247 #else
248                         return GetSystemWebProxy ();
249 #endif
250                 }
251
252                 // Methods
253                 
254                 public virtual void Abort()
255                 {
256                         throw GetMustImplement ();
257                 }
258                 
259                 public virtual IAsyncResult BeginGetRequestStream (AsyncCallback callback, object state) 
260                 {
261                         throw GetMustImplement ();
262                 }
263                 
264                 public virtual IAsyncResult BeginGetResponse (AsyncCallback callback, object state)
265                 {
266                         throw GetMustImplement ();
267                 }
268
269                 public static WebRequest Create (string requestUriString) 
270                 {
271                         if (requestUriString == null)
272                                 throw new ArgumentNullException ("requestUriString");
273                         return Create (new Uri (requestUriString));
274                 }
275                                 
276                 public static WebRequest Create (Uri requestUri) 
277                 {
278                         if (requestUri == null)
279                                 throw new ArgumentNullException ("requestUri");
280                         return GetCreator (requestUri.AbsoluteUri).Create (requestUri);
281                 }
282                 
283                 public static WebRequest CreateDefault (Uri requestUri)
284                 {
285                         if (requestUri == null)
286                                 throw new ArgumentNullException ("requestUri");
287                         return GetCreator (requestUri.Scheme).Create (requestUri);
288                 }
289                 static HttpWebRequest SharedCreateHttp (Uri uri)
290                 {
291                         if (uri.Scheme != "http" && uri.Scheme != "https")
292                                 throw new NotSupportedException ("The uri should start with http or https");
293
294                         return new HttpWebRequest (uri);
295                 }
296
297                 public static HttpWebRequest CreateHttp (string requestUriString)
298                 {
299                         if (requestUriString == null)
300                                 throw new ArgumentNullException ("requestUriString");
301                         return SharedCreateHttp (new Uri (requestUriString));
302                 }
303                         
304                 public static HttpWebRequest CreateHttp (Uri requestUri)
305                 {
306                         if (requestUri == null)
307                                 throw new ArgumentNullException ("requestUri");
308                         return SharedCreateHttp (requestUri);
309                 }
310                 public virtual Stream EndGetRequestStream (IAsyncResult asyncResult)
311                 {
312                         throw GetMustImplement ();
313                 }
314                 
315                 public virtual WebResponse EndGetResponse (IAsyncResult asyncResult)
316                 {
317                         throw GetMustImplement ();
318                 }
319                 
320                 public virtual Stream GetRequestStream()
321                 {
322                         throw GetMustImplement ();
323                 }
324                 
325                 public virtual WebResponse GetResponse()
326                 {
327                         throw GetMustImplement ();
328                 }
329                 
330                 [MonoTODO("Look in other places for proxy config info")]
331                 public static IWebProxy GetSystemWebProxy ()
332                 {
333 #if MONOTOUCH
334                         return CFNetwork.GetDefaultProxy ();
335 #else
336 #if MONODROID
337                         // Return the system web proxy.  This only works for ICS+.
338                         var androidProxy = AndroidPlatform.GetDefaultProxy ();
339                         if (androidProxy != null)
340                                 return androidProxy;
341 #endif
342 #if !NET_2_1
343                         if (IsWindows ()) {
344                                 int iProxyEnable = (int)Microsoft.Win32.Registry.GetValue ("HKEY_CURRENT_USER\\Software\\Microsoft\\Windows\\CurrentVersion\\Internet Settings", "ProxyEnable", 0);
345
346                                 if (iProxyEnable > 0) {
347                                         string strHttpProxy = "";                                       
348                                         bool bBypassOnLocal = false;
349                                         ArrayList al = new ArrayList ();
350                                         
351                                         string strProxyServer = (string)Microsoft.Win32.Registry.GetValue ("HKEY_CURRENT_USER\\Software\\Microsoft\\Windows\\CurrentVersion\\Internet Settings", "ProxyServer", null);
352                                         string strProxyOverrride = (string)Microsoft.Win32.Registry.GetValue ("HKEY_CURRENT_USER\\Software\\Microsoft\\Windows\\CurrentVersion\\Internet Settings", "ProxyOverride", null);
353                                         
354                                         if (strProxyServer.Contains ("=")) {
355                                                 foreach (string strEntry in strProxyServer.Split (new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries))
356                                                         if (strEntry.StartsWith ("http=")) {
357                                                                 strHttpProxy = strEntry.Substring (5);
358                                                                 break;
359                                                         }
360                                         } else strHttpProxy = strProxyServer;
361                                         
362                                         if (strProxyOverrride != null) {                                                
363                                                 string[] bypassList = strProxyOverrride.Split (new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries);
364                                         
365                                                 foreach (string str in bypassList) {
366                                                         if (str != "<local>")
367                                                                 al.Add (str);
368                                                         else
369                                                                 bBypassOnLocal = true;
370                                                 }
371                                         }
372                                         
373                                         return new WebProxy (strHttpProxy, bBypassOnLocal, al.ToArray (typeof(string)) as string[]);
374                                 }
375                         } else {
376 #endif
377                                 if (Platform.IsMacOS)
378                                         return CFNetwork.GetDefaultProxy ();
379                                 
380                                 string address = Environment.GetEnvironmentVariable ("http_proxy");
381
382                                 if (address == null)
383                                         address = Environment.GetEnvironmentVariable ("HTTP_PROXY");
384                                 
385                                 if (address != null) {
386                                         try {
387                                                 if (!address.StartsWith ("http://"))
388                                                         address = "http://" + address;
389
390                                                 Uri uri = new Uri (address);
391                                                 IPAddress ip;
392                                                 
393                                                 if (IPAddress.TryParse (uri.Host, out ip)) {
394                                                         if (IPAddress.Any.Equals (ip)) {
395                                                                 UriBuilder builder = new UriBuilder (uri);
396                                                                 builder.Host = "127.0.0.1";
397                                                                 uri = builder.Uri;
398                                                         } else if (IPAddress.IPv6Any.Equals (ip)) {
399                                                                 UriBuilder builder = new UriBuilder (uri);
400                                                                 builder.Host = "[::1]";
401                                                                 uri = builder.Uri;
402                                                         }
403                                                 }
404                                                 
405                                                 bool bBypassOnLocal = false;                                            
406                                                 ArrayList al = new ArrayList ();
407                                                 string bypass = Environment.GetEnvironmentVariable ("no_proxy");
408                                                 
409                                                 if (bypass == null)
410                                                         bypass = Environment.GetEnvironmentVariable ("NO_PROXY");
411                                                 
412                                                 if (bypass != null) {
413                                                         string[] bypassList = bypass.Split (new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
414                                                 
415                                                         foreach (string str in bypassList) {
416                                                                 if (str != "*.local")
417                                                                         al.Add (str);
418                                                                 else
419                                                                         bBypassOnLocal = true;
420                                                         }
421                                                 }
422                                                 
423                                                 return new WebProxy (uri, bBypassOnLocal, al.ToArray (typeof(string)) as string[]);
424                                         } catch (UriFormatException) {
425                                         }
426                                 }
427 #if !NET_2_1
428                         }
429 #endif
430                         
431                         return new WebProxy ();
432 #endif // MONOTOUCH
433                 }
434
435                 void ISerializable.GetObjectData (SerializationInfo serializationInfo, StreamingContext streamingContext)
436                 {
437                         throw new NotSupportedException ();
438                 }
439
440                 protected virtual void GetObjectData (SerializationInfo serializationInfo, StreamingContext streamingContext)
441                 {
442                         throw GetMustImplement ();
443                 }
444
445                 public static bool RegisterPrefix (string prefix, IWebRequestCreate creator)
446                 {
447                         if (prefix == null)
448                                 throw new ArgumentNullException ("prefix");
449                         if (creator == null)
450                                 throw new ArgumentNullException ("creator");
451                         
452                         lock (prefixes.SyncRoot) {
453                                 string lowerCasePrefix = prefix.ToLower (CultureInfo.InvariantCulture);
454                                 if (prefixes.Contains (lowerCasePrefix))
455                                         return false;
456                                 prefixes.Add (lowerCasePrefix, creator);
457                         }
458                         return true;
459                 }
460                 
461                 private static IWebRequestCreate GetCreator (string prefix)
462                 {
463                         int longestPrefix = -1;
464                         IWebRequestCreate creator = null;
465
466                         prefix = prefix.ToLower (CultureInfo.InvariantCulture);
467
468                         IDictionaryEnumerator e = prefixes.GetEnumerator ();
469                         while (e.MoveNext ()) {
470                                 string key = e.Key as string;
471
472                                 if (key.Length <= longestPrefix) 
473                                         continue;
474                                 
475                                 if (!prefix.StartsWith (key))
476                                         continue;
477                                         
478                                 longestPrefix = key.Length;
479                                 creator = (IWebRequestCreate) e.Value;
480                         }
481                         
482                         if (creator == null) 
483                                 throw new NotSupportedException (prefix);
484                                 
485                         return creator;
486                 }
487                 
488                 internal static bool IsWindows ()
489                 {
490                         return (int) Environment.OSVersion.Platform < 4;
491                 }
492
493                 internal static void ClearPrefixes ()
494                 {
495                         prefixes.Clear ();
496                 }
497
498                 internal static void RemovePrefix (string prefix)
499                 {
500                         prefixes.Remove (prefix);
501                 }
502
503                 internal static void AddPrefix (string prefix, string typeName)
504                 {
505                         Type type = Type.GetType (typeName);
506                         if (type == null)
507                                 throw new ConfigurationException (String.Format ("Type {0} not found", typeName));
508                         AddPrefix (prefix, type);
509                 }
510
511                 internal static void AddPrefix (string prefix, Type type)
512                 {
513                         object o = Activator.CreateInstance (type, true);
514                         prefixes [prefix] = o;
515                 }
516
517 #if NET_4_5
518                 public virtual Task<Stream> GetRequestStreamAsync ()
519                 {
520                         return Task<Stream>.Factory.FromAsync (BeginGetRequestStream, EndGetRequestStream, null);
521                 }
522
523                 public virtual Task<WebResponse> GetResponseAsync ()
524                 {
525                         return Task<WebResponse>.Factory.FromAsync (BeginGetResponse, EndGetResponse, null);
526                 }
527 #endif
528
529         }
530 }