WebRequest.cs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431
  1. //
  2. // System.Net.WebRequest
  3. //
  4. // Authors:
  5. // Lawrence Pit ([email protected])
  6. //
  7. //
  8. // Permission is hereby granted, free of charge, to any person obtaining
  9. // a copy of this software and associated documentation files (the
  10. // "Software"), to deal in the Software without restriction, including
  11. // without limitation the rights to use, copy, modify, merge, publish,
  12. // distribute, sublicense, and/or sell copies of the Software, and to
  13. // permit persons to whom the Software is furnished to do so, subject to
  14. // the following conditions:
  15. //
  16. // The above copyright notice and this permission notice shall be
  17. // included in all copies or substantial portions of the Software.
  18. //
  19. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  20. // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  21. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
  22. // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
  23. // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
  24. // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
  25. // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  26. //
  27. using System;
  28. using System.Collections;
  29. using System.Collections.Specialized;
  30. using System.Configuration;
  31. using System.IO;
  32. using System.Reflection;
  33. using System.Runtime.Serialization;
  34. using System.Globalization;
  35. using System.Net.Configuration;
  36. using System.Net.Security;
  37. using System.Net.Cache;
  38. using System.Security.Principal;
  39. #if NET_2_1
  40. using ConfigurationException = System.ArgumentException;
  41. namespace System.Net.Configuration {
  42. class Dummy {}
  43. }
  44. #endif
  45. namespace System.Net
  46. {
  47. #if MOONLIGHT
  48. internal abstract class WebRequest : ISerializable {
  49. #else
  50. [Serializable]
  51. public abstract class WebRequest : MarshalByRefObject, ISerializable {
  52. #endif
  53. static HybridDictionary prefixes = new HybridDictionary ();
  54. static bool isDefaultWebProxySet;
  55. static IWebProxy defaultWebProxy;
  56. static RequestCachePolicy defaultCachePolicy;
  57. static MethodInfo cfGetDefaultProxy;
  58. // Constructors
  59. static WebRequest ()
  60. {
  61. if (Platform.IsMacOS) {
  62. #if MONOTOUCH
  63. Type type = Type.GetType ("MonoTouch.CoreFoundation.CFNetwork, monotouch");
  64. #else
  65. Type type = Type.GetType ("MonoMac.CoreFoundation.CFNetwork, monomac");
  66. #endif
  67. if (type != null)
  68. cfGetDefaultProxy = type.GetMethod ("GetDefaultProxy");
  69. }
  70. #if NET_2_1
  71. IWebRequestCreate http = new HttpRequestCreator ();
  72. RegisterPrefix ("http", http);
  73. RegisterPrefix ("https", http);
  74. #if MOBILE
  75. RegisterPrefix ("file", new FileWebRequestCreator ());
  76. RegisterPrefix ("ftp", new FtpRequestCreator ());
  77. #endif
  78. #else
  79. defaultCachePolicy = new HttpRequestCachePolicy (HttpRequestCacheLevel.NoCacheNoStore);
  80. #if CONFIGURATION_DEP
  81. object cfg = ConfigurationManager.GetSection ("system.net/webRequestModules");
  82. WebRequestModulesSection s = cfg as WebRequestModulesSection;
  83. if (s != null) {
  84. foreach (WebRequestModuleElement el in
  85. s.WebRequestModules)
  86. AddPrefix (el.Prefix, el.Type);
  87. return;
  88. }
  89. #endif
  90. ConfigurationSettings.GetConfig ("system.net/webRequestModules");
  91. #endif
  92. }
  93. protected WebRequest ()
  94. {
  95. }
  96. protected WebRequest (SerializationInfo serializationInfo, StreamingContext streamingContext)
  97. {
  98. }
  99. static Exception GetMustImplement ()
  100. {
  101. return new NotImplementedException ("This method must be implemented in derived classes");
  102. }
  103. // Properties
  104. private AuthenticationLevel authentication_level = AuthenticationLevel.MutualAuthRequested;
  105. public AuthenticationLevel AuthenticationLevel
  106. {
  107. get {
  108. return(authentication_level);
  109. }
  110. set {
  111. authentication_level = value;
  112. }
  113. }
  114. [MonoTODO ("Implement the caching system. Currently always returns a policy with the NoCacheNoStore level")]
  115. public virtual RequestCachePolicy CachePolicy
  116. {
  117. get { return DefaultCachePolicy; }
  118. set {
  119. }
  120. }
  121. public virtual string ConnectionGroupName {
  122. get { throw GetMustImplement (); }
  123. set { throw GetMustImplement (); }
  124. }
  125. public virtual long ContentLength {
  126. get { throw GetMustImplement (); }
  127. set { throw GetMustImplement (); }
  128. }
  129. public virtual string ContentType {
  130. get { throw GetMustImplement (); }
  131. set { throw GetMustImplement (); }
  132. }
  133. public virtual ICredentials Credentials {
  134. get { throw GetMustImplement (); }
  135. set { throw GetMustImplement (); }
  136. }
  137. public static RequestCachePolicy DefaultCachePolicy
  138. {
  139. get { return defaultCachePolicy; }
  140. set {
  141. throw GetMustImplement ();
  142. }
  143. }
  144. public virtual WebHeaderCollection Headers {
  145. get { throw GetMustImplement (); }
  146. set { throw GetMustImplement (); }
  147. }
  148. #if !MOONLIGHT
  149. public TokenImpersonationLevel ImpersonationLevel {
  150. get { throw GetMustImplement (); }
  151. set { throw GetMustImplement (); }
  152. }
  153. #endif
  154. public virtual string Method {
  155. get { throw GetMustImplement (); }
  156. set { throw GetMustImplement (); }
  157. }
  158. public virtual bool PreAuthenticate {
  159. get { throw GetMustImplement (); }
  160. set { throw GetMustImplement (); }
  161. }
  162. public virtual IWebProxy Proxy {
  163. get { throw GetMustImplement (); }
  164. set { throw GetMustImplement (); }
  165. }
  166. public virtual Uri RequestUri {
  167. get { throw GetMustImplement (); }
  168. }
  169. public virtual int Timeout {
  170. get { throw GetMustImplement (); }
  171. set { throw GetMustImplement (); }
  172. }
  173. public virtual bool UseDefaultCredentials
  174. {
  175. get {
  176. throw GetMustImplement ();
  177. }
  178. set {
  179. throw GetMustImplement ();
  180. }
  181. }
  182. // volatile static IWebProxy proxy;
  183. static readonly object lockobj = new object ();
  184. public static IWebProxy DefaultWebProxy {
  185. get {
  186. if (!isDefaultWebProxySet) {
  187. lock (lockobj) {
  188. if (defaultWebProxy == null)
  189. defaultWebProxy = GetDefaultWebProxy ();
  190. }
  191. }
  192. return defaultWebProxy;
  193. }
  194. set {
  195. /* MS documentation states that a null value would cause an ArgumentNullException
  196. * but that's not the way it behaves:
  197. * https://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=304724
  198. */
  199. defaultWebProxy = value;
  200. isDefaultWebProxySet = true;
  201. }
  202. }
  203. [MonoTODO("Needs to respect Module, Proxy.AutoDetect, and Proxy.ScriptLocation config settings")]
  204. static IWebProxy GetDefaultWebProxy ()
  205. {
  206. #if CONFIGURATION_DEP
  207. DefaultProxySection sec = ConfigurationManager.GetSection ("system.net/defaultProxy") as DefaultProxySection;
  208. WebProxy p;
  209. if (sec == null)
  210. return GetSystemWebProxy ();
  211. ProxyElement pe = sec.Proxy;
  212. if ((pe.UseSystemDefault != ProxyElement.UseSystemDefaultValues.False) && (pe.ProxyAddress == null))
  213. p = (WebProxy) GetSystemWebProxy ();
  214. else
  215. p = new WebProxy ();
  216. if (pe.ProxyAddress != null)
  217. p.Address = pe.ProxyAddress;
  218. if (pe.BypassOnLocal != ProxyElement.BypassOnLocalValues.Unspecified)
  219. p.BypassProxyOnLocal = (pe.BypassOnLocal == ProxyElement.BypassOnLocalValues.True);
  220. return p;
  221. #else
  222. return GetSystemWebProxy ();
  223. #endif
  224. }
  225. // Methods
  226. public virtual void Abort()
  227. {
  228. throw GetMustImplement ();
  229. }
  230. public virtual IAsyncResult BeginGetRequestStream (AsyncCallback callback, object state)
  231. {
  232. throw GetMustImplement ();
  233. }
  234. public virtual IAsyncResult BeginGetResponse (AsyncCallback callback, object state)
  235. {
  236. throw GetMustImplement ();
  237. }
  238. public static WebRequest Create (string requestUriString)
  239. {
  240. if (requestUriString == null)
  241. throw new ArgumentNullException ("requestUriString");
  242. return Create (new Uri (requestUriString));
  243. }
  244. public static WebRequest Create (Uri requestUri)
  245. {
  246. if (requestUri == null)
  247. throw new ArgumentNullException ("requestUri");
  248. return GetCreator (requestUri.AbsoluteUri).Create (requestUri);
  249. }
  250. public static WebRequest CreateDefault (Uri requestUri)
  251. {
  252. if (requestUri == null)
  253. throw new ArgumentNullException ("requestUri");
  254. return GetCreator (requestUri.Scheme).Create (requestUri);
  255. }
  256. public virtual Stream EndGetRequestStream (IAsyncResult asyncResult)
  257. {
  258. throw GetMustImplement ();
  259. }
  260. public virtual WebResponse EndGetResponse (IAsyncResult asyncResult)
  261. {
  262. throw GetMustImplement ();
  263. }
  264. public virtual Stream GetRequestStream()
  265. {
  266. throw GetMustImplement ();
  267. }
  268. public virtual WebResponse GetResponse()
  269. {
  270. throw GetMustImplement ();
  271. }
  272. [MonoTODO("Look in other places for proxy config info")]
  273. public static IWebProxy GetSystemWebProxy ()
  274. {
  275. string address = Environment.GetEnvironmentVariable ("http_proxy");
  276. if (address == null)
  277. address = Environment.GetEnvironmentVariable ("HTTP_PROXY");
  278. if (address != null) {
  279. try {
  280. if (!address.StartsWith ("http://"))
  281. address = "http://" + address;
  282. Uri uri = new Uri (address);
  283. IPAddress ip;
  284. if (IPAddress.TryParse (uri.Host, out ip)) {
  285. if (IPAddress.Any.Equals (ip)) {
  286. UriBuilder builder = new UriBuilder (uri);
  287. builder.Host = "127.0.0.1";
  288. uri = builder.Uri;
  289. } else if (IPAddress.IPv6Any.Equals (ip)) {
  290. UriBuilder builder = new UriBuilder (uri);
  291. builder.Host = "[::1]";
  292. uri = builder.Uri;
  293. }
  294. }
  295. return new WebProxy (uri);
  296. } catch (UriFormatException) { }
  297. }
  298. if (cfGetDefaultProxy != null)
  299. return (IWebProxy) cfGetDefaultProxy.Invoke (null, null);
  300. return new WebProxy ();
  301. }
  302. void ISerializable.GetObjectData (SerializationInfo serializationInfo, StreamingContext streamingContext)
  303. {
  304. throw new NotSupportedException ();
  305. }
  306. protected virtual void GetObjectData (SerializationInfo serializationInfo, StreamingContext streamingContext)
  307. {
  308. throw GetMustImplement ();
  309. }
  310. public static bool RegisterPrefix (string prefix, IWebRequestCreate creator)
  311. {
  312. if (prefix == null)
  313. throw new ArgumentNullException ("prefix");
  314. if (creator == null)
  315. throw new ArgumentNullException ("creator");
  316. lock (prefixes.SyncRoot) {
  317. string lowerCasePrefix = prefix.ToLower (CultureInfo.InvariantCulture);
  318. if (prefixes.Contains (lowerCasePrefix))
  319. return false;
  320. prefixes.Add (lowerCasePrefix, creator);
  321. }
  322. return true;
  323. }
  324. private static IWebRequestCreate GetCreator (string prefix)
  325. {
  326. int longestPrefix = -1;
  327. IWebRequestCreate creator = null;
  328. prefix = prefix.ToLower (CultureInfo.InvariantCulture);
  329. IDictionaryEnumerator e = prefixes.GetEnumerator ();
  330. while (e.MoveNext ()) {
  331. string key = e.Key as string;
  332. if (key.Length <= longestPrefix)
  333. continue;
  334. if (!prefix.StartsWith (key))
  335. continue;
  336. longestPrefix = key.Length;
  337. creator = (IWebRequestCreate) e.Value;
  338. }
  339. if (creator == null)
  340. throw new NotSupportedException (prefix);
  341. return creator;
  342. }
  343. internal static void ClearPrefixes ()
  344. {
  345. prefixes.Clear ();
  346. }
  347. internal static void RemovePrefix (string prefix)
  348. {
  349. prefixes.Remove (prefix);
  350. }
  351. internal static void AddPrefix (string prefix, string typeName)
  352. {
  353. Type type = Type.GetType (typeName);
  354. if (type == null)
  355. throw new ConfigurationException (String.Format ("Type {0} not found", typeName));
  356. AddPrefix (prefix, type);
  357. }
  358. internal static void AddPrefix (string prefix, Type type)
  359. {
  360. object o = Activator.CreateInstance (type, true);
  361. prefixes [prefix] = o;
  362. }
  363. }
  364. }