WebRequest.cs 14 KB

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