CFNetworkHandler.cs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389
  1. //
  2. // CFNetworkHandler.cs
  3. //
  4. // Authors:
  5. // Marek Safar <[email protected]>
  6. //
  7. // Copyright (C) 2013 Xamarin Inc (http://www.xamarin.com)
  8. //
  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:
  16. //
  17. // The above copyright notice and this permission notice shall be
  18. // included in all copies or substantial portions of the Software.
  19. //
  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.
  27. //
  28. using System.Threading;
  29. using System.Net.Http.Headers;
  30. using System.Threading.Tasks;
  31. using System.IO;
  32. using System.Collections.Generic;
  33. using System.Net;
  34. #if XAMCORE_4_0
  35. using CFNetwork;
  36. using CoreFoundation;
  37. using CF=CoreFoundation;
  38. #elif XAMCORE_2_0
  39. using CoreServices;
  40. using CoreFoundation;
  41. using CF=CoreFoundation;
  42. #else
  43. using MonoTouch.CoreServices;
  44. using MonoTouch.CoreFoundation;
  45. using CF=MonoTouch.CoreFoundation;
  46. #endif
  47. namespace System.Net.Http
  48. {
  49. public class CFNetworkHandler : HttpMessageHandler
  50. {
  51. class StreamBucket
  52. {
  53. public TaskCompletionSource<HttpResponseMessage> Response;
  54. public HttpRequestMessage Request;
  55. public CancellationTokenRegistration CancellationTokenRegistration;
  56. public CFContentStream ContentStream;
  57. public bool StreamCanBeDisposed;
  58. public void Close ()
  59. {
  60. CancellationTokenRegistration.Dispose ();
  61. if (ContentStream != null) {
  62. // The Close method of the CFContentStream blocks as you can see:
  63. // public void Close ()
  64. // {
  65. // data_read_event.WaitOne (); // make sure there's no pending data
  66. //
  67. // data_mutex.WaitOne ();
  68. // data = null;
  69. // this.http_stream.ErrorEvent -= HandleErrorEvent;
  70. // data_mutex.ReleaseMutex ();
  71. //
  72. // data_event.Set ();
  73. // }
  74. // This means. that when we want to ignore the data of the content, which happens
  75. // in the first request of a redirect, if we want to close, ignoring the content
  76. // we will have a deadlock.
  77. // Dispose will clean all the data, without waiting for the read, which by design in the
  78. // CFContentStream, blocks the thread. This happens ONLY after the first request that gets
  79. // a redirect status code. All other cases should call close.
  80. if (StreamCanBeDisposed)
  81. ContentStream.Dispose ();
  82. else
  83. ContentStream.Close ();
  84. }
  85. }
  86. }
  87. bool allowAutoRedirect;
  88. bool sentRequest;
  89. bool useSystemProxy;
  90. CookieContainer cookies;
  91. Dictionary<IntPtr, StreamBucket> streamBuckets;
  92. public CFNetworkHandler ()
  93. {
  94. allowAutoRedirect = true;
  95. streamBuckets = new Dictionary<IntPtr, StreamBucket> ();
  96. }
  97. void EnsureModifiability ()
  98. {
  99. if (sentRequest)
  100. throw new InvalidOperationException (
  101. "This instance has already started one or more requests. " +
  102. "Properties can only be modified before sending the first request.");
  103. }
  104. public bool AllowAutoRedirect {
  105. get {
  106. return allowAutoRedirect;
  107. }
  108. set {
  109. EnsureModifiability ();
  110. allowAutoRedirect = value;
  111. }
  112. }
  113. public CookieContainer CookieContainer {
  114. get {
  115. return cookies ?? (cookies = new CookieContainer ());
  116. }
  117. set {
  118. EnsureModifiability ();
  119. cookies = value;
  120. }
  121. }
  122. public bool UseSystemProxy {
  123. get {
  124. return useSystemProxy;
  125. }
  126. set {
  127. EnsureModifiability ();
  128. useSystemProxy = value;
  129. }
  130. }
  131. // TODO: Add more properties
  132. protected override void Dispose (bool disposing)
  133. {
  134. // TODO: CloseStream remaining stream buckets if there are any
  135. base.Dispose (disposing);
  136. }
  137. CFHTTPMessage CreateWebRequestAsync (HttpRequestMessage request)
  138. {
  139. var req = CFHTTPMessage.CreateRequest (request.RequestUri, request.Method.Method, request.Version);
  140. // TODO:
  141. /*
  142. if (wr.ProtocolVersion == HttpVersion.Version10) {
  143. wr.KeepAlive = request.Headers.ConnectionKeepAlive;
  144. } else {
  145. wr.KeepAlive = request.Headers.ConnectionClose != true;
  146. }
  147. if (useDefaultCredentials) {
  148. wr.UseDefaultCredentials = true;
  149. } else {
  150. wr.Credentials = credentials;
  151. }
  152. if (useProxy) {
  153. wr.Proxy = proxy;
  154. }
  155. */
  156. if (cookies != null) {
  157. string cookieHeader = cookies.GetCookieHeader (request.RequestUri);
  158. if (cookieHeader != "")
  159. req.SetHeaderFieldValue ("Cookie", cookieHeader);
  160. }
  161. foreach (var header in request.Headers) {
  162. foreach (var value in header.Value) {
  163. req.SetHeaderFieldValue (header.Key, value);
  164. }
  165. }
  166. if (request.Content != null) {
  167. foreach (var header in request.Content.Headers) {
  168. foreach (var value in header.Value) {
  169. req.SetHeaderFieldValue (header.Key, value);
  170. }
  171. }
  172. }
  173. return req;
  174. }
  175. protected internal override async Task<HttpResponseMessage> SendAsync (HttpRequestMessage request, CancellationToken cancellationToken)
  176. {
  177. return await SendAsync (request, cancellationToken, true).ConfigureAwait (false);
  178. }
  179. internal async Task<HttpResponseMessage> SendAsync (HttpRequestMessage request, CancellationToken cancellationToken, bool isFirstRequest)
  180. {
  181. sentRequest = true;
  182. CFHTTPStream stream;
  183. using (var message = CreateWebRequestAsync (request))
  184. {
  185. if (request.Content != null) {
  186. var data = await request.Content.ReadAsByteArrayAsync ().ConfigureAwait (false);
  187. message.SetBody (data);
  188. }
  189. stream = CFHTTPStream.CreateForHTTPRequest (message);
  190. }
  191. if (useSystemProxy) {
  192. var proxies = CF.CFNetwork.GetSystemProxySettings ();
  193. if (proxies.HTTPEnable) {
  194. stream.SetProxy (proxies);
  195. }
  196. }
  197. if (!isFirstRequest && allowAutoRedirect)
  198. stream.ShouldAutoredirect = allowAutoRedirect;
  199. stream.HasBytesAvailableEvent += HandleHasBytesAvailableEvent;
  200. stream.ErrorEvent += HandleErrorEvent;
  201. stream.ClosedEvent += HandleClosedEvent;
  202. var response = new TaskCompletionSource<HttpResponseMessage> ();
  203. if (cancellationToken.IsCancellationRequested) {
  204. response.SetCanceled ();
  205. return await response.Task;
  206. }
  207. var bucket = new StreamBucket () {
  208. Request = request,
  209. Response = response,
  210. };
  211. streamBuckets.Add (stream.Handle, bucket);
  212. //
  213. // Always schedule stream events handling on main-loop. Due to ConfigureAwait (false) we may end up
  214. // on any thread-pool thread which may not have run-loop running
  215. //
  216. #if XAMCORE_2_0
  217. stream.EnableEvents (CF.CFRunLoop.Main, CF.CFRunLoop.ModeCommon);
  218. #else
  219. stream.EnableEvents (CF.CFRunLoop.Main, CF.CFRunLoop.CFRunLoopCommonModes);
  220. #endif
  221. stream.Open ();
  222. bucket.CancellationTokenRegistration = cancellationToken.Register (() => {
  223. StreamBucket bucket2;
  224. if (!streamBuckets.TryGetValue (stream.Handle, out bucket2))
  225. return;
  226. bucket2.Response.TrySetCanceled ();
  227. CloseStream (stream);
  228. });
  229. if (isFirstRequest) {
  230. var initialRequest = await response.Task;
  231. var status = initialRequest.StatusCode;
  232. if (IsRedirect (status) && allowAutoRedirect) {
  233. bucket.StreamCanBeDisposed = true;
  234. // remove headers in a redirect for Authentication.
  235. request.Headers.Authorization = null;
  236. return await SendAsync (request, cancellationToken, false).ConfigureAwait (false);
  237. }
  238. return initialRequest;
  239. }
  240. return await response.Task;
  241. }
  242. // Decide if we redirect or not, similar to what is done in the managed handler
  243. // https://github.com/mono/mono/blob/eca15996c7163f331c9f2cd0a17b63e8f92b1d55/mcs/class/referencesource/System/net/System/Net/HttpWebRequest.cs#L5681
  244. static bool IsRedirect (HttpStatusCode status)
  245. {
  246. return status == HttpStatusCode.Ambiguous || // 300
  247. status == HttpStatusCode.Moved || // 301
  248. status == HttpStatusCode.Redirect || // 302
  249. status == HttpStatusCode.RedirectMethod || // 303
  250. status == HttpStatusCode.RedirectKeepVerb; // 307
  251. }
  252. void HandleErrorEvent (object sender, CFStream.StreamEventArgs e)
  253. {
  254. var stream = (CFHTTPStream)sender;
  255. StreamBucket bucket;
  256. if (!streamBuckets.TryGetValue (stream.Handle, out bucket))
  257. return;
  258. bucket.Response.TrySetException (stream.GetError ());
  259. CloseStream (stream);
  260. }
  261. void HandleClosedEvent (object sender, CFStream.StreamEventArgs e)
  262. {
  263. var stream = (CFHTTPStream)sender;
  264. // might not have been called (e.g. no data) but initialize critical data
  265. HandleHasBytesAvailableEvent (sender, e);
  266. CloseStream (stream);
  267. }
  268. void CloseStream (CFHTTPStream stream)
  269. {
  270. lock (streamBuckets) {
  271. if (streamBuckets.TryGetValue (stream.Handle, out var bucket)) {
  272. bucket.Close ();
  273. streamBuckets.Remove (stream.Handle);
  274. }
  275. }
  276. stream.Close ();
  277. }
  278. void HandleHasBytesAvailableEvent (object sender, CFStream.StreamEventArgs e)
  279. {
  280. var stream = (CFHTTPStream) sender;
  281. StreamBucket bucket;
  282. if (!streamBuckets.TryGetValue (stream.Handle, out bucket))
  283. return;
  284. if (bucket.Response.Task.IsCompleted) {
  285. bucket.ContentStream.ReadStreamData ();
  286. return;
  287. }
  288. var header = stream.GetResponseHeader ();
  289. // Is this possible?
  290. if (!header.IsHeaderComplete)
  291. throw new NotImplementedException ();
  292. bucket.ContentStream = new CFContentStream (stream);
  293. var response_msg = new HttpResponseMessage (header.ResponseStatusCode);
  294. response_msg.RequestMessage = bucket.Request;
  295. response_msg.ReasonPhrase = header.ResponseStatusLine;
  296. response_msg.Content = bucket.ContentStream;
  297. var fields = header.GetAllHeaderFields ();
  298. if (fields != null) {
  299. foreach (var entry in fields) {
  300. if (entry.Key == null)
  301. continue;
  302. var key = entry.Key.ToString ();
  303. var value = entry.Value == null ? string.Empty : entry.Value.ToString ();
  304. HttpHeaders item_headers;
  305. if (HttpHeaders.GetKnownHeaderKind (key) == Headers.HttpHeaderKind.Content) {
  306. item_headers = response_msg.Content.Headers;
  307. } else {
  308. item_headers = response_msg.Headers;
  309. if (cookies != null && (key == "Set-Cookie" || key == "Set-Cookie2"))
  310. AddCookie (value, bucket.Request.RequestUri, key);
  311. }
  312. item_headers.TryAddWithoutValidation (key, value);
  313. }
  314. }
  315. // cancellation (CancellationTokenRegistration) can happen in parallel
  316. if (!bucket.Response.Task.IsCanceled) {
  317. bucket.Response.TrySetResult (response_msg);
  318. bucket.ContentStream.ReadStreamData ();
  319. }
  320. }
  321. void AddCookie (string value, Uri uri, string header)
  322. {
  323. CookieCollection cookies1 = null;
  324. try {
  325. cookies1 = cookies.CookieCutter (uri, header, value, false);
  326. } catch {
  327. }
  328. if (cookies1 != null && cookies1.Count != 0)
  329. cookies.Add (cookies1);
  330. }
  331. }
  332. }