CFNetworkHandler.cs 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334
  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 void Close ()
  58. {
  59. CancellationTokenRegistration.Dispose ();
  60. if (ContentStream != null) {
  61. ContentStream.Close ();
  62. }
  63. }
  64. }
  65. bool allowAutoRedirect;
  66. bool sentRequest;
  67. bool useSystemProxy;
  68. CookieContainer cookies;
  69. Dictionary<IntPtr, StreamBucket> streamBuckets;
  70. public CFNetworkHandler ()
  71. {
  72. allowAutoRedirect = true;
  73. streamBuckets = new Dictionary<IntPtr, StreamBucket> ();
  74. }
  75. void EnsureModifiability ()
  76. {
  77. if (sentRequest)
  78. throw new InvalidOperationException (
  79. "This instance has already started one or more requests. " +
  80. "Properties can only be modified before sending the first request.");
  81. }
  82. public bool AllowAutoRedirect {
  83. get {
  84. return allowAutoRedirect;
  85. }
  86. set {
  87. EnsureModifiability ();
  88. allowAutoRedirect = value;
  89. }
  90. }
  91. public CookieContainer CookieContainer {
  92. get {
  93. return cookies ?? (cookies = new CookieContainer ());
  94. }
  95. set {
  96. EnsureModifiability ();
  97. cookies = value;
  98. }
  99. }
  100. public bool UseSystemProxy {
  101. get {
  102. return useSystemProxy;
  103. }
  104. set {
  105. EnsureModifiability ();
  106. useSystemProxy = value;
  107. }
  108. }
  109. // TODO: Add more properties
  110. protected override void Dispose (bool disposing)
  111. {
  112. // TODO: CloseStream remaining stream buckets if there are any
  113. base.Dispose (disposing);
  114. }
  115. CFHTTPMessage CreateWebRequestAsync (HttpRequestMessage request)
  116. {
  117. var req = CFHTTPMessage.CreateRequest (request.RequestUri, request.Method.Method, request.Version);
  118. // TODO:
  119. /*
  120. if (wr.ProtocolVersion == HttpVersion.Version10) {
  121. wr.KeepAlive = request.Headers.ConnectionKeepAlive;
  122. } else {
  123. wr.KeepAlive = request.Headers.ConnectionClose != true;
  124. }
  125. if (useDefaultCredentials) {
  126. wr.UseDefaultCredentials = true;
  127. } else {
  128. wr.Credentials = credentials;
  129. }
  130. if (useProxy) {
  131. wr.Proxy = proxy;
  132. }
  133. */
  134. if (cookies != null) {
  135. string cookieHeader = cookies.GetCookieHeader (request.RequestUri);
  136. if (cookieHeader != "")
  137. req.SetHeaderFieldValue ("Cookie", cookieHeader);
  138. }
  139. foreach (var header in request.Headers) {
  140. foreach (var value in header.Value) {
  141. req.SetHeaderFieldValue (header.Key, value);
  142. }
  143. }
  144. if (request.Content != null) {
  145. foreach (var header in request.Content.Headers) {
  146. foreach (var value in header.Value) {
  147. req.SetHeaderFieldValue (header.Key, value);
  148. }
  149. }
  150. }
  151. return req;
  152. }
  153. protected internal override async Task<HttpResponseMessage> SendAsync (HttpRequestMessage request, CancellationToken cancellationToken)
  154. {
  155. sentRequest = true;
  156. CFHTTPStream stream;
  157. using (var message = CreateWebRequestAsync (request))
  158. {
  159. if (request.Content != null) {
  160. var data = await request.Content.ReadAsByteArrayAsync ().ConfigureAwait (false);
  161. message.SetBody (data);
  162. }
  163. stream = CFHTTPStream.CreateForHTTPRequest (message);
  164. }
  165. if (useSystemProxy) {
  166. var proxies = CF.CFNetwork.GetSystemProxySettings ();
  167. if (proxies.HTTPEnable) {
  168. stream.SetProxy (proxies);
  169. }
  170. }
  171. stream.ShouldAutoredirect = allowAutoRedirect;
  172. stream.HasBytesAvailableEvent += HandleHasBytesAvailableEvent;
  173. stream.ErrorEvent += HandleErrorEvent;
  174. stream.ClosedEvent += HandleClosedEvent;
  175. var response = new TaskCompletionSource<HttpResponseMessage> ();
  176. if (cancellationToken.IsCancellationRequested) {
  177. response.SetCanceled ();
  178. return await response.Task;
  179. }
  180. var bucket = new StreamBucket () {
  181. Request = request,
  182. Response = response,
  183. };
  184. streamBuckets.Add (stream.Handle, bucket);
  185. //
  186. // Always schedule stream events handling on main-loop. Due to ConfigureAwait (false) we may end up
  187. // on any thread-pool thread which may not have run-loop running
  188. //
  189. #if XAMCORE_2_0
  190. stream.EnableEvents (CF.CFRunLoop.Main, CF.CFRunLoop.ModeCommon);
  191. #else
  192. stream.EnableEvents (CF.CFRunLoop.Main, CF.CFRunLoop.CFRunLoopCommonModes);
  193. #endif
  194. stream.Open ();
  195. bucket.CancellationTokenRegistration = cancellationToken.Register (() => {
  196. StreamBucket bucket2;
  197. if (!streamBuckets.TryGetValue (stream.Handle, out bucket2))
  198. return;
  199. bucket2.Response.TrySetCanceled ();
  200. CloseStream (stream);
  201. });
  202. return await response.Task;
  203. }
  204. void HandleErrorEvent (object sender, CFStream.StreamEventArgs e)
  205. {
  206. var stream = (CFHTTPStream)sender;
  207. StreamBucket bucket;
  208. if (!streamBuckets.TryGetValue (stream.Handle, out bucket))
  209. return;
  210. bucket.Response.TrySetException (stream.GetError ());
  211. CloseStream (stream);
  212. }
  213. void HandleClosedEvent (object sender, CFStream.StreamEventArgs e)
  214. {
  215. var stream = (CFHTTPStream)sender;
  216. CloseStream (stream);
  217. }
  218. void CloseStream (CFHTTPStream stream)
  219. {
  220. StreamBucket bucket;
  221. if (streamBuckets.TryGetValue (stream.Handle, out bucket)) {
  222. bucket.Close ();
  223. streamBuckets.Remove (stream.Handle);
  224. }
  225. stream.Close ();
  226. }
  227. void HandleHasBytesAvailableEvent (object sender, CFStream.StreamEventArgs e)
  228. {
  229. var stream = (CFHTTPStream) sender;
  230. StreamBucket bucket;
  231. if (!streamBuckets.TryGetValue (stream.Handle, out bucket))
  232. return;
  233. if (bucket.Response.Task.IsCompleted) {
  234. bucket.ContentStream.ReadStreamData ();
  235. return;
  236. }
  237. var header = stream.GetResponseHeader ();
  238. // Is this possible?
  239. if (!header.IsHeaderComplete)
  240. throw new NotImplementedException ();
  241. bucket.ContentStream = new CFContentStream (stream);
  242. var response_msg = new HttpResponseMessage (header.ResponseStatusCode);
  243. response_msg.RequestMessage = bucket.Request;
  244. response_msg.ReasonPhrase = header.ResponseStatusLine;
  245. response_msg.Content = bucket.ContentStream;
  246. var fields = header.GetAllHeaderFields ();
  247. if (fields != null) {
  248. foreach (var entry in fields) {
  249. if (entry.Key == null)
  250. continue;
  251. var key = entry.Key.ToString ();
  252. var value = entry.Value == null ? string.Empty : entry.Value.ToString ();
  253. HttpHeaders item_headers;
  254. if (HttpHeaders.GetKnownHeaderKind (key) == Headers.HttpHeaderKind.Content) {
  255. item_headers = response_msg.Content.Headers;
  256. } else {
  257. item_headers = response_msg.Headers;
  258. if (cookies != null && (key == "Set-Cookie" || key == "Set-Cookie2"))
  259. AddCookie (value, bucket.Request.RequestUri, key);
  260. }
  261. item_headers.TryAddWithoutValidation (key, value);
  262. }
  263. }
  264. bucket.Response.TrySetResult (response_msg);
  265. bucket.ContentStream.ReadStreamData ();
  266. }
  267. void AddCookie (string value, Uri uri, string header)
  268. {
  269. CookieCollection cookies1 = null;
  270. try {
  271. cookies1 = cookies.CookieCutter (uri, header, value, false);
  272. } catch {
  273. }
  274. if (cookies1 != null && cookies1.Count != 0)
  275. cookies.Add (cookies1);
  276. }
  277. }
  278. }