Add async methods to System.Net
[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                         return p;
261 #else
262                         return GetSystemWebProxy ();
263 #endif
264                 }
265
266                 // Methods
267                 
268                 public virtual void Abort()
269                 {
270                         throw GetMustImplement ();
271                 }
272                 
273                 public virtual IAsyncResult BeginGetRequestStream (AsyncCallback callback, object state) 
274                 {
275                         throw GetMustImplement ();
276                 }
277                 
278                 public virtual IAsyncResult BeginGetResponse (AsyncCallback callback, object state)
279                 {
280                         throw GetMustImplement ();
281                 }
282
283                 public static WebRequest Create (string requestUriString) 
284                 {
285                         if (requestUriString == null)
286                                 throw new ArgumentNullException ("requestUriString");
287                         return Create (new Uri (requestUriString));
288                 }
289                                 
290                 public static WebRequest Create (Uri requestUri) 
291                 {
292                         if (requestUri == null)
293                                 throw new ArgumentNullException ("requestUri");
294                         return GetCreator (requestUri.AbsoluteUri).Create (requestUri);
295                 }
296                 
297                 public static WebRequest CreateDefault (Uri requestUri)
298                 {
299                         if (requestUri == null)
300                                 throw new ArgumentNullException ("requestUri");
301                         return GetCreator (requestUri.Scheme).Create (requestUri);
302                 }
303
304                 public virtual Stream EndGetRequestStream (IAsyncResult asyncResult)
305                 {
306                         throw GetMustImplement ();
307                 }
308                 
309                 public virtual WebResponse EndGetResponse (IAsyncResult asyncResult)
310                 {
311                         throw GetMustImplement ();
312                 }
313                 
314                 public virtual Stream GetRequestStream()
315                 {
316                         throw GetMustImplement ();
317                 }
318                 
319                 public virtual WebResponse GetResponse()
320                 {
321                         throw GetMustImplement ();
322                 }
323                 
324                 [MonoTODO("Look in other places for proxy config info")]
325                 public static IWebProxy GetSystemWebProxy ()
326                 {
327                         string address = Environment.GetEnvironmentVariable ("http_proxy");
328                         if (address == null)
329                                 address = Environment.GetEnvironmentVariable ("HTTP_PROXY");
330
331                         if (address != null) {
332                                 try {
333                                         if (!address.StartsWith ("http://"))
334                                                 address = "http://" + address;
335                                         Uri uri = new Uri (address);
336                                         IPAddress ip;
337                                         if (IPAddress.TryParse (uri.Host, out ip)) {
338                                                 if (IPAddress.Any.Equals (ip)) {
339                                                         UriBuilder builder = new UriBuilder (uri);
340                                                         builder.Host = "127.0.0.1";
341                                                         uri = builder.Uri;
342                                                 } else if (IPAddress.IPv6Any.Equals (ip)) {
343                                                         UriBuilder builder = new UriBuilder (uri);
344                                                         builder.Host = "[::1]";
345                                                         uri = builder.Uri;
346                                                 }
347                                         }
348                                         return new WebProxy (uri);
349                                 } catch (UriFormatException) { }
350                         }
351                         
352                         if (cfGetDefaultProxy != null)
353                                 return (IWebProxy) cfGetDefaultProxy.Invoke (null, null);
354                         
355                         return new WebProxy ();
356                 }
357
358                 void ISerializable.GetObjectData (SerializationInfo serializationInfo, StreamingContext streamingContext)
359                 {
360                         throw new NotSupportedException ();
361                 }
362
363                 protected virtual void GetObjectData (SerializationInfo serializationInfo, StreamingContext streamingContext)
364                 {
365                         throw GetMustImplement ();
366                 }
367
368                 public static bool RegisterPrefix (string prefix, IWebRequestCreate creator)
369                 {
370                         if (prefix == null)
371                                 throw new ArgumentNullException ("prefix");
372                         if (creator == null)
373                                 throw new ArgumentNullException ("creator");
374                         
375                         lock (prefixes.SyncRoot) {
376                                 string lowerCasePrefix = prefix.ToLower (CultureInfo.InvariantCulture);
377                                 if (prefixes.Contains (lowerCasePrefix))
378                                         return false;
379                                 prefixes.Add (lowerCasePrefix, creator);
380                         }
381                         return true;
382                 }
383                 
384                 private static IWebRequestCreate GetCreator (string prefix)
385                 {
386                         int longestPrefix = -1;
387                         IWebRequestCreate creator = null;
388
389                         prefix = prefix.ToLower (CultureInfo.InvariantCulture);
390
391                         IDictionaryEnumerator e = prefixes.GetEnumerator ();
392                         while (e.MoveNext ()) {
393                                 string key = e.Key as string;
394
395                                 if (key.Length <= longestPrefix) 
396                                         continue;
397                                 
398                                 if (!prefix.StartsWith (key))
399                                         continue;
400                                         
401                                 longestPrefix = key.Length;
402                                 creator = (IWebRequestCreate) e.Value;
403                         }
404                         
405                         if (creator == null) 
406                                 throw new NotSupportedException (prefix);
407                                 
408                         return creator;
409                 }
410
411                 internal static void ClearPrefixes ()
412                 {
413                         prefixes.Clear ();
414                 }
415
416                 internal static void RemovePrefix (string prefix)
417                 {
418                         prefixes.Remove (prefix);
419                 }
420
421                 internal static void AddPrefix (string prefix, string typeName)
422                 {
423                         Type type = Type.GetType (typeName);
424                         if (type == null)
425                                 throw new ConfigurationException (String.Format ("Type {0} not found", typeName));
426                         AddPrefix (prefix, type);
427                 }
428
429                 internal static void AddPrefix (string prefix, Type type)
430                 {
431                         object o = Activator.CreateInstance (type, true);
432                         prefixes [prefix] = o;
433                 }
434
435 #if NET_4_5
436                 public virtual Task<Stream> GetRequestStreamAsync ()
437                 {
438                         return Task<Stream>.Factory.FromAsync (BeginGetRequestStream, EndGetRequestStream, null);
439                 }
440
441                 public virtual Task<WebResponse> GetResponseAsync ()
442                 {
443                         return Task<WebResponse>.Factory.FromAsync (BeginGetResponse, EndGetResponse, null);
444                 }
445 #endif
446
447         }
448 }