WebRequest.cs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434
  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.Runtime.Serialization;
  33. using System.Globalization;
  34. #if NET_2_0
  35. using System.Net.Configuration;
  36. using System.Net.Security;
  37. using System.Net.Cache;
  38. using System.Security.Principal;
  39. #endif
  40. #if NET_2_1
  41. using ConfigurationException = System.ArgumentException;
  42. namespace System.Net.Configuration {
  43. class Dummy {}
  44. }
  45. #endif
  46. namespace System.Net
  47. {
  48. #if MOONLIGHT
  49. internal abstract class WebRequest : ISerializable {
  50. #else
  51. [Serializable]
  52. public abstract class WebRequest : MarshalByRefObject, ISerializable {
  53. #endif
  54. static HybridDictionary prefixes = new HybridDictionary ();
  55. #if NET_2_0
  56. static bool isDefaultWebProxySet;
  57. static IWebProxy defaultWebProxy;
  58. static RequestCachePolicy defaultCachePolicy;
  59. #endif
  60. // Constructors
  61. static WebRequest ()
  62. {
  63. #if NET_2_1
  64. AddPrefix ("http", typeof (HttpRequestCreator));
  65. AddPrefix ("https", typeof (HttpRequestCreator));
  66. #if MOBILE
  67. AddPrefix ("file", typeof (FileWebRequestCreator));
  68. AddPrefix ("ftp", typeof (FtpRequestCreator));
  69. #endif
  70. #else
  71. #if NET_2_0
  72. defaultCachePolicy = new HttpRequestCachePolicy (HttpRequestCacheLevel.NoCacheNoStore);
  73. #endif
  74. #if NET_2_0 && CONFIGURATION_DEP
  75. object cfg = ConfigurationManager.GetSection ("system.net/webRequestModules");
  76. WebRequestModulesSection s = cfg as WebRequestModulesSection;
  77. if (s != null) {
  78. foreach (WebRequestModuleElement el in
  79. s.WebRequestModules)
  80. AddPrefix (el.Prefix, el.Type);
  81. return;
  82. }
  83. #endif
  84. ConfigurationSettings.GetConfig ("system.net/webRequestModules");
  85. #endif
  86. }
  87. protected WebRequest ()
  88. {
  89. }
  90. protected WebRequest (SerializationInfo serializationInfo, StreamingContext streamingContext)
  91. {
  92. #if ONLY_1_1
  93. throw GetMustImplement ();
  94. #endif
  95. }
  96. static Exception GetMustImplement ()
  97. {
  98. return new NotImplementedException ("This method must be implemented in derived classes");
  99. }
  100. // Properties
  101. #if NET_2_0
  102. private AuthenticationLevel authentication_level = AuthenticationLevel.MutualAuthRequested;
  103. public AuthenticationLevel AuthenticationLevel
  104. {
  105. get {
  106. return(authentication_level);
  107. }
  108. set {
  109. authentication_level = value;
  110. }
  111. }
  112. [MonoTODO ("Implement the caching system. Currently always returns a policy with the NoCacheNoStore level")]
  113. public virtual RequestCachePolicy CachePolicy
  114. {
  115. get { return DefaultCachePolicy; }
  116. set {
  117. }
  118. }
  119. #endif
  120. public virtual string ConnectionGroupName {
  121. get { throw GetMustImplement (); }
  122. set { throw GetMustImplement (); }
  123. }
  124. public virtual long ContentLength {
  125. get { throw GetMustImplement (); }
  126. set { throw GetMustImplement (); }
  127. }
  128. public virtual string ContentType {
  129. get { throw GetMustImplement (); }
  130. set { throw GetMustImplement (); }
  131. }
  132. public virtual ICredentials Credentials {
  133. get { throw GetMustImplement (); }
  134. set { throw GetMustImplement (); }
  135. }
  136. #if NET_2_0
  137. public static RequestCachePolicy DefaultCachePolicy
  138. {
  139. get { return defaultCachePolicy; }
  140. set {
  141. throw GetMustImplement ();
  142. }
  143. }
  144. #endif
  145. public virtual WebHeaderCollection Headers {
  146. get { throw GetMustImplement (); }
  147. set { throw GetMustImplement (); }
  148. }
  149. #if NET_2_0 && !MOONLIGHT
  150. public TokenImpersonationLevel ImpersonationLevel {
  151. get { throw GetMustImplement (); }
  152. set { throw GetMustImplement (); }
  153. }
  154. #endif
  155. public virtual string Method {
  156. get { throw GetMustImplement (); }
  157. set { throw GetMustImplement (); }
  158. }
  159. public virtual bool PreAuthenticate {
  160. get { throw GetMustImplement (); }
  161. set { throw GetMustImplement (); }
  162. }
  163. public virtual IWebProxy Proxy {
  164. get { throw GetMustImplement (); }
  165. set { throw GetMustImplement (); }
  166. }
  167. public virtual Uri RequestUri {
  168. get { throw GetMustImplement (); }
  169. }
  170. public virtual int Timeout {
  171. get { throw GetMustImplement (); }
  172. set { throw GetMustImplement (); }
  173. }
  174. #if NET_2_0
  175. public virtual bool UseDefaultCredentials
  176. {
  177. get {
  178. throw GetMustImplement ();
  179. }
  180. set {
  181. throw GetMustImplement ();
  182. }
  183. }
  184. // volatile static IWebProxy proxy;
  185. static readonly object lockobj = new object ();
  186. public static IWebProxy DefaultWebProxy {
  187. get {
  188. if (!isDefaultWebProxySet) {
  189. lock (lockobj) {
  190. if (defaultWebProxy == null)
  191. defaultWebProxy = GetDefaultWebProxy ();
  192. }
  193. }
  194. return defaultWebProxy;
  195. }
  196. set {
  197. /* MS documentation states that a null value would cause an ArgumentNullException
  198. * but that's not the way it behaves:
  199. * https://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=304724
  200. */
  201. defaultWebProxy = value;
  202. isDefaultWebProxySet = true;
  203. }
  204. }
  205. [MonoTODO("Needs to respect Module, Proxy.AutoDetect, and Proxy.ScriptLocation config settings")]
  206. static IWebProxy GetDefaultWebProxy ()
  207. {
  208. WebProxy p = null;
  209. #if CONFIGURATION_DEP
  210. DefaultProxySection sec = ConfigurationManager.GetSection ("system.net/defaultProxy") as DefaultProxySection;
  211. if (sec == null)
  212. return GetSystemWebProxy ();
  213. ProxyElement pe = sec.Proxy;
  214. if ((pe.UseSystemDefault != ProxyElement.UseSystemDefaultValues.False) && (pe.ProxyAddress == null))
  215. p = (WebProxy) GetSystemWebProxy ();
  216. else
  217. p = new WebProxy ();
  218. if (pe.ProxyAddress != null)
  219. p.Address = pe.ProxyAddress;
  220. if (pe.BypassOnLocal != ProxyElement.BypassOnLocalValues.Unspecified)
  221. p.BypassProxyOnLocal = (pe.BypassOnLocal == ProxyElement.BypassOnLocalValues.True);
  222. #endif
  223. return p;
  224. }
  225. #endif
  226. // Methods
  227. public virtual void Abort()
  228. {
  229. throw GetMustImplement ();
  230. }
  231. public virtual IAsyncResult BeginGetRequestStream (AsyncCallback callback, object state)
  232. {
  233. throw GetMustImplement ();
  234. }
  235. public virtual IAsyncResult BeginGetResponse (AsyncCallback callback, object state)
  236. {
  237. throw GetMustImplement ();
  238. }
  239. public static WebRequest Create (string requestUriString)
  240. {
  241. if (requestUriString == null)
  242. throw new ArgumentNullException ("requestUriString");
  243. return Create (new Uri (requestUriString));
  244. }
  245. public static WebRequest Create (Uri requestUri)
  246. {
  247. if (requestUri == null)
  248. throw new ArgumentNullException ("requestUri");
  249. return GetCreator (requestUri.Scheme).Create (requestUri);
  250. }
  251. public static WebRequest CreateDefault (Uri requestUri)
  252. {
  253. if (requestUri == null)
  254. throw new ArgumentNullException ("requestUri");
  255. return GetCreator (requestUri.Scheme).Create (requestUri);
  256. }
  257. public virtual Stream EndGetRequestStream (IAsyncResult asyncResult)
  258. {
  259. throw GetMustImplement ();
  260. }
  261. public virtual WebResponse EndGetResponse (IAsyncResult asyncResult)
  262. {
  263. throw GetMustImplement ();
  264. }
  265. public virtual Stream GetRequestStream()
  266. {
  267. throw GetMustImplement ();
  268. }
  269. public virtual WebResponse GetResponse()
  270. {
  271. throw GetMustImplement ();
  272. }
  273. #if NET_2_0
  274. [MonoTODO("Look in other places for proxy config info")]
  275. public static IWebProxy GetSystemWebProxy ()
  276. {
  277. string address = Environment.GetEnvironmentVariable ("http_proxy");
  278. if (address == null)
  279. address = Environment.GetEnvironmentVariable ("HTTP_PROXY");
  280. if (address != null) {
  281. try {
  282. if (!address.StartsWith ("http://"))
  283. address = "http://" + address;
  284. Uri uri = new Uri (address);
  285. IPAddress ip;
  286. if (IPAddress.TryParse (uri.Host, out ip)) {
  287. if (IPAddress.Any.Equals (ip)) {
  288. UriBuilder builder = new UriBuilder (uri);
  289. builder.Host = "127.0.0.1";
  290. uri = builder.Uri;
  291. } else if (IPAddress.IPv6Any.Equals (ip)) {
  292. UriBuilder builder = new UriBuilder (uri);
  293. builder.Host = "[::1]";
  294. uri = builder.Uri;
  295. }
  296. }
  297. return new WebProxy (uri);
  298. } catch (UriFormatException) { }
  299. }
  300. return new WebProxy ();
  301. }
  302. #endif
  303. void ISerializable.GetObjectData
  304. (SerializationInfo serializationInfo,
  305. StreamingContext streamingContext)
  306. {
  307. throw new NotSupportedException ();
  308. }
  309. #if NET_2_0
  310. protected virtual void GetObjectData (SerializationInfo serializationInfo, StreamingContext streamingContext)
  311. {
  312. throw GetMustImplement ();
  313. }
  314. #endif
  315. public static bool RegisterPrefix (string prefix, IWebRequestCreate creator)
  316. {
  317. if (prefix == null)
  318. throw new ArgumentNullException ("prefix");
  319. if (creator == null)
  320. throw new ArgumentNullException ("creator");
  321. lock (prefixes.SyncRoot) {
  322. string lowerCasePrefix = prefix.ToLower (CultureInfo.InvariantCulture);
  323. if (prefixes.Contains (lowerCasePrefix))
  324. return false;
  325. prefixes.Add (lowerCasePrefix, creator);
  326. }
  327. return true;
  328. }
  329. private static IWebRequestCreate GetCreator (string prefix)
  330. {
  331. int longestPrefix = -1;
  332. IWebRequestCreate creator = null;
  333. prefix = prefix.ToLower (CultureInfo.InvariantCulture);
  334. IDictionaryEnumerator e = prefixes.GetEnumerator ();
  335. while (e.MoveNext ()) {
  336. string key = e.Key as string;
  337. if (key.Length <= longestPrefix)
  338. continue;
  339. if (!prefix.StartsWith (key))
  340. continue;
  341. longestPrefix = key.Length;
  342. creator = (IWebRequestCreate) e.Value;
  343. }
  344. if (creator == null)
  345. throw new NotSupportedException (prefix);
  346. return creator;
  347. }
  348. internal static void ClearPrefixes ()
  349. {
  350. prefixes.Clear ();
  351. }
  352. internal static void RemovePrefix (string prefix)
  353. {
  354. prefixes.Remove (prefix);
  355. }
  356. internal static void AddPrefix (string prefix, string typeName)
  357. {
  358. Type type = Type.GetType (typeName);
  359. if (type == null)
  360. throw new ConfigurationException (String.Format ("Type {0} not found", typeName));
  361. AddPrefix (prefix, type);
  362. }
  363. internal static void AddPrefix (string prefix, Type type)
  364. {
  365. object o = Activator.CreateInstance (type, true);
  366. prefixes [prefix] = o;
  367. }
  368. }
  369. }