Edited mcs/class/System/System.Net/WebRequest.cs via GitHub
[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                         string address = Environment.GetEnvironmentVariable ("http_proxy");
331                         if (address == null)
332                                 address = Environment.GetEnvironmentVariable ("HTTP_PROXY");
333
334                         if (address != null) {
335                                 try {
336                                         if (!address.StartsWith ("http://"))
337                                                 address = "http://" + address;
338                                         Uri uri = new Uri (address);
339                                         IPAddress ip;
340                                         if (IPAddress.TryParse (uri.Host, out ip)) {
341                                                 if (IPAddress.Any.Equals (ip)) {
342                                                         UriBuilder builder = new UriBuilder (uri);
343                                                         builder.Host = "127.0.0.1";
344                                                         uri = builder.Uri;
345                                                 } else if (IPAddress.IPv6Any.Equals (ip)) {
346                                                         UriBuilder builder = new UriBuilder (uri);
347                                                         builder.Host = "[::1]";
348                                                         uri = builder.Uri;
349                                                 }
350                                         }
351                                         return new WebProxy (uri);
352                                 } catch (UriFormatException) { }
353                         }
354                         
355                         if (cfGetDefaultProxy != null)
356                                 return (IWebProxy) cfGetDefaultProxy.Invoke (null, null);
357                         
358                         return new WebProxy ();
359                 }
360
361                 void ISerializable.GetObjectData (SerializationInfo serializationInfo, StreamingContext streamingContext)
362                 {
363                         throw new NotSupportedException ();
364                 }
365
366                 protected virtual void GetObjectData (SerializationInfo serializationInfo, StreamingContext streamingContext)
367                 {
368                         throw GetMustImplement ();
369                 }
370
371                 public static bool RegisterPrefix (string prefix, IWebRequestCreate creator)
372                 {
373                         if (prefix == null)
374                                 throw new ArgumentNullException ("prefix");
375                         if (creator == null)
376                                 throw new ArgumentNullException ("creator");
377                         
378                         lock (prefixes.SyncRoot) {
379                                 string lowerCasePrefix = prefix.ToLower (CultureInfo.InvariantCulture);
380                                 if (prefixes.Contains (lowerCasePrefix))
381                                         return false;
382                                 prefixes.Add (lowerCasePrefix, creator);
383                         }
384                         return true;
385                 }
386                 
387                 private static IWebRequestCreate GetCreator (string prefix)
388                 {
389                         int longestPrefix = -1;
390                         IWebRequestCreate creator = null;
391
392                         prefix = prefix.ToLower (CultureInfo.InvariantCulture);
393
394                         IDictionaryEnumerator e = prefixes.GetEnumerator ();
395                         while (e.MoveNext ()) {
396                                 string key = e.Key as string;
397
398                                 if (key.Length <= longestPrefix) 
399                                         continue;
400                                 
401                                 if (!prefix.StartsWith (key))
402                                         continue;
403                                         
404                                 longestPrefix = key.Length;
405                                 creator = (IWebRequestCreate) e.Value;
406                         }
407                         
408                         if (creator == null) 
409                                 throw new NotSupportedException (prefix);
410                                 
411                         return creator;
412                 }
413
414                 internal static void ClearPrefixes ()
415                 {
416                         prefixes.Clear ();
417                 }
418
419                 internal static void RemovePrefix (string prefix)
420                 {
421                         prefixes.Remove (prefix);
422                 }
423
424                 internal static void AddPrefix (string prefix, string typeName)
425                 {
426                         Type type = Type.GetType (typeName);
427                         if (type == null)
428                                 throw new ConfigurationException (String.Format ("Type {0} not found", typeName));
429                         AddPrefix (prefix, type);
430                 }
431
432                 internal static void AddPrefix (string prefix, Type type)
433                 {
434                         object o = Activator.CreateInstance (type, true);
435                         prefixes [prefix] = o;
436                 }
437
438 #if NET_4_5
439                 public virtual Task<Stream> GetRequestStreamAsync ()
440                 {
441                         return Task<Stream>.Factory.FromAsync (BeginGetRequestStream, EndGetRequestStream, null);
442                 }
443
444                 public virtual Task<WebResponse> GetResponseAsync ()
445                 {
446                         return Task<WebResponse>.Factory.FromAsync (BeginGetResponse, EndGetResponse, null);
447                 }
448 #endif
449
450         }
451 }