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