2 // System.Net.WebRequest
5 // Lawrence Pit (loz@cable.a2000.nl)
9 // Permission is hereby granted, free of charge, to any person obtaining
10 // a copy of this software and associated documentation files (the
11 // "Software"), to deal in the Software without restriction, including
12 // without limitation the rights to use, copy, modify, merge, publish,
13 // distribute, sublicense, and/or sell copies of the Software, and to
14 // permit persons to whom the Software is furnished to do so, subject to
15 // the following conditions:
17 // The above copyright notice and this permission notice shall be
18 // included in all copies or substantial portions of the Software.
20 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
21 // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
22 // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
23 // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
24 // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
25 // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
26 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
30 using System.Collections;
31 using System.Collections.Specialized;
32 using System.Configuration;
34 using System.Reflection;
35 using System.Runtime.Serialization;
36 using System.Globalization;
38 using System.Net.Configuration;
39 using System.Net.Security;
40 using System.Net.Cache;
41 using System.Security.Principal;
45 using ConfigurationException = System.ArgumentException;
47 namespace System.Net.Configuration {
55 internal abstract class WebRequest : ISerializable {
58 public abstract class WebRequest : MarshalByRefObject, ISerializable {
60 static HybridDictionary prefixes = new HybridDictionary ();
62 static bool isDefaultWebProxySet;
63 static IWebProxy defaultWebProxy;
64 static RequestCachePolicy defaultCachePolicy;
65 static MethodInfo cfGetDefaultProxy;
72 if (Platform.IsMacOS) {
74 Type type = Type.GetType ("MonoTouch.CoreFoundation.CFNetwork, monotouch");
76 Type type = Type.GetType ("MonoMac.CoreFoundation.CFNetwork, monomac");
79 cfGetDefaultProxy = type.GetMethod ("GetDefaultProxy");
83 IWebRequestCreate http = new HttpRequestCreator ();
84 RegisterPrefix ("http", http);
85 RegisterPrefix ("https", http);
87 RegisterPrefix ("file", new FileWebRequestCreator ());
88 RegisterPrefix ("ftp", new FtpRequestCreator ());
92 defaultCachePolicy = new HttpRequestCachePolicy (HttpRequestCacheLevel.NoCacheNoStore);
94 #if NET_2_0 && CONFIGURATION_DEP
95 object cfg = ConfigurationManager.GetSection ("system.net/webRequestModules");
96 WebRequestModulesSection s = cfg as WebRequestModulesSection;
98 foreach (WebRequestModuleElement el in
100 AddPrefix (el.Prefix, el.Type);
104 ConfigurationSettings.GetConfig ("system.net/webRequestModules");
108 protected WebRequest ()
112 protected WebRequest (SerializationInfo serializationInfo, StreamingContext streamingContext)
115 throw GetMustImplement ();
119 static Exception GetMustImplement ()
121 return new NotImplementedException ("This method must be implemented in derived classes");
127 private AuthenticationLevel authentication_level = AuthenticationLevel.MutualAuthRequested;
129 public AuthenticationLevel AuthenticationLevel
132 return(authentication_level);
135 authentication_level = value;
139 [MonoTODO ("Implement the caching system. Currently always returns a policy with the NoCacheNoStore level")]
140 public virtual RequestCachePolicy CachePolicy
142 get { return DefaultCachePolicy; }
148 public virtual string ConnectionGroupName {
149 get { throw GetMustImplement (); }
150 set { throw GetMustImplement (); }
153 public virtual long ContentLength {
154 get { throw GetMustImplement (); }
155 set { throw GetMustImplement (); }
158 public virtual string ContentType {
159 get { throw GetMustImplement (); }
160 set { throw GetMustImplement (); }
163 public virtual ICredentials Credentials {
164 get { throw GetMustImplement (); }
165 set { throw GetMustImplement (); }
169 public static RequestCachePolicy DefaultCachePolicy
171 get { return defaultCachePolicy; }
173 throw GetMustImplement ();
178 public virtual WebHeaderCollection Headers {
179 get { throw GetMustImplement (); }
180 set { throw GetMustImplement (); }
183 #if NET_2_0 && !MOONLIGHT
184 public TokenImpersonationLevel ImpersonationLevel {
185 get { throw GetMustImplement (); }
186 set { throw GetMustImplement (); }
189 public virtual string Method {
190 get { throw GetMustImplement (); }
191 set { throw GetMustImplement (); }
194 public virtual bool PreAuthenticate {
195 get { throw GetMustImplement (); }
196 set { throw GetMustImplement (); }
199 public virtual IWebProxy Proxy {
200 get { throw GetMustImplement (); }
201 set { throw GetMustImplement (); }
204 public virtual Uri RequestUri {
205 get { throw GetMustImplement (); }
208 public virtual int Timeout {
209 get { throw GetMustImplement (); }
210 set { throw GetMustImplement (); }
214 public virtual bool UseDefaultCredentials
217 throw GetMustImplement ();
220 throw GetMustImplement ();
224 // volatile static IWebProxy proxy;
225 static readonly object lockobj = new object ();
227 public static IWebProxy DefaultWebProxy {
229 if (!isDefaultWebProxySet) {
231 if (defaultWebProxy == null)
232 defaultWebProxy = GetDefaultWebProxy ();
235 return defaultWebProxy;
238 /* MS documentation states that a null value would cause an ArgumentNullException
239 * but that's not the way it behaves:
240 * https://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=304724
242 defaultWebProxy = value;
243 isDefaultWebProxySet = true;
247 [MonoTODO("Needs to respect Module, Proxy.AutoDetect, and Proxy.ScriptLocation config settings")]
248 static IWebProxy GetDefaultWebProxy ()
252 #if CONFIGURATION_DEP
253 DefaultProxySection sec = ConfigurationManager.GetSection ("system.net/defaultProxy") as DefaultProxySection;
255 return GetSystemWebProxy ();
257 ProxyElement pe = sec.Proxy;
259 if ((pe.UseSystemDefault != ProxyElement.UseSystemDefaultValues.False) && (pe.ProxyAddress == null))
260 p = (WebProxy) GetSystemWebProxy ();
264 if (pe.ProxyAddress != null)
265 p.Address = pe.ProxyAddress;
267 if (pe.BypassOnLocal != ProxyElement.BypassOnLocalValues.Unspecified)
268 p.BypassProxyOnLocal = (pe.BypassOnLocal == ProxyElement.BypassOnLocalValues.True);
276 public virtual void Abort()
278 throw GetMustImplement ();
281 public virtual IAsyncResult BeginGetRequestStream (AsyncCallback callback, object state)
283 throw GetMustImplement ();
286 public virtual IAsyncResult BeginGetResponse (AsyncCallback callback, object state)
288 throw GetMustImplement ();
291 public static WebRequest Create (string requestUriString)
293 if (requestUriString == null)
294 throw new ArgumentNullException ("requestUriString");
295 return Create (new Uri (requestUriString));
298 public static WebRequest Create (Uri requestUri)
300 if (requestUri == null)
301 throw new ArgumentNullException ("requestUri");
302 return GetCreator (requestUri.AbsoluteUri).Create (requestUri);
305 public static WebRequest CreateDefault (Uri requestUri)
307 if (requestUri == null)
308 throw new ArgumentNullException ("requestUri");
309 return GetCreator (requestUri.Scheme).Create (requestUri);
312 public virtual Stream EndGetRequestStream (IAsyncResult asyncResult)
314 throw GetMustImplement ();
317 public virtual WebResponse EndGetResponse (IAsyncResult asyncResult)
319 throw GetMustImplement ();
322 public virtual Stream GetRequestStream()
324 throw GetMustImplement ();
327 public virtual WebResponse GetResponse()
329 throw GetMustImplement ();
333 [MonoTODO("Look in other places for proxy config info")]
334 public static IWebProxy GetSystemWebProxy ()
336 string address = Environment.GetEnvironmentVariable ("http_proxy");
338 address = Environment.GetEnvironmentVariable ("HTTP_PROXY");
340 if (address != null) {
342 if (!address.StartsWith ("http://"))
343 address = "http://" + address;
344 Uri uri = new Uri (address);
346 if (IPAddress.TryParse (uri.Host, out ip)) {
347 if (IPAddress.Any.Equals (ip)) {
348 UriBuilder builder = new UriBuilder (uri);
349 builder.Host = "127.0.0.1";
351 } else if (IPAddress.IPv6Any.Equals (ip)) {
352 UriBuilder builder = new UriBuilder (uri);
353 builder.Host = "[::1]";
357 return new WebProxy (uri);
358 } catch (UriFormatException) { }
361 if (cfGetDefaultProxy != null)
362 return (IWebProxy) cfGetDefaultProxy.Invoke (null, null);
364 return new WebProxy ();
368 void ISerializable.GetObjectData
369 (SerializationInfo serializationInfo,
370 StreamingContext streamingContext)
372 throw new NotSupportedException ();
377 protected virtual void GetObjectData (SerializationInfo serializationInfo, StreamingContext streamingContext)
379 throw GetMustImplement ();
383 public static bool RegisterPrefix (string prefix, IWebRequestCreate creator)
386 throw new ArgumentNullException ("prefix");
388 throw new ArgumentNullException ("creator");
390 lock (prefixes.SyncRoot) {
391 string lowerCasePrefix = prefix.ToLower (CultureInfo.InvariantCulture);
392 if (prefixes.Contains (lowerCasePrefix))
394 prefixes.Add (lowerCasePrefix, creator);
399 private static IWebRequestCreate GetCreator (string prefix)
401 int longestPrefix = -1;
402 IWebRequestCreate creator = null;
404 prefix = prefix.ToLower (CultureInfo.InvariantCulture);
406 IDictionaryEnumerator e = prefixes.GetEnumerator ();
407 while (e.MoveNext ()) {
408 string key = e.Key as string;
410 if (key.Length <= longestPrefix)
413 if (!prefix.StartsWith (key))
416 longestPrefix = key.Length;
417 creator = (IWebRequestCreate) e.Value;
421 throw new NotSupportedException (prefix);
426 internal static void ClearPrefixes ()
431 internal static void RemovePrefix (string prefix)
433 prefixes.Remove (prefix);
436 internal static void AddPrefix (string prefix, string typeName)
438 Type type = Type.GetType (typeName);
440 throw new ConfigurationException (String.Format ("Type {0} not found", typeName));
441 AddPrefix (prefix, type);
444 internal static void AddPrefix (string prefix, Type type)
446 object o = Activator.CreateInstance (type, true);
447 prefixes [prefix] = o;