WebRequest.cs 11 KB

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