ClientWebSocket.cs 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394
  1. //
  2. // ClientWebSocket.cs
  3. //
  4. // Authors:
  5. // Jérémie Laval <jeremie dot laval at xamarin dot com>
  6. //
  7. // Copyright 2013 Xamarin Inc (http://www.xamarin.com).
  8. //
  9. // Lightly inspired from WebSocket4Net distributed under the Apache License 2.0
  10. //
  11. // Permission is hereby granted, free of charge, to any person obtaining a copy
  12. // of this software and associated documentation files (the "Software"), to deal
  13. // in the Software without restriction, including without limitation the rights
  14. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  15. // copies of the Software, and to permit persons to whom the Software is
  16. // furnished to do so, subject to the following conditions:
  17. //
  18. // The above copyright notice and this permission notice shall be included in
  19. // all copies or substantial portions of the Software.
  20. //
  21. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  22. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  23. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  24. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  25. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  26. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  27. // THE SOFTWARE.
  28. #if NET_4_5
  29. using System;
  30. using System.Net;
  31. using System.Net.Sockets;
  32. using System.Security.Principal;
  33. using System.Security.Cryptography.X509Certificates;
  34. using System.Runtime.CompilerServices;
  35. using System.Collections.Generic;
  36. using System.Threading;
  37. using System.Threading.Tasks;
  38. using System.Globalization;
  39. using System.Text;
  40. using System.Security.Cryptography;
  41. namespace System.Net.WebSockets
  42. {
  43. public class ClientWebSocket : WebSocket, IDisposable
  44. {
  45. const string Magic = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
  46. const string VersionTag = "13";
  47. ClientWebSocketOptions options;
  48. WebSocketState state;
  49. string subProtocol;
  50. HttpWebRequest req;
  51. WebConnection connection;
  52. Socket underlyingSocket;
  53. Random random = new Random ();
  54. const int HeaderMaxLength = 14;
  55. byte[] headerBuffer;
  56. byte[] sendBuffer;
  57. long remaining;
  58. WebSocketMessageType currentMessageType;
  59. public ClientWebSocket ()
  60. {
  61. options = new ClientWebSocketOptions ();
  62. state = WebSocketState.None;
  63. headerBuffer = new byte[HeaderMaxLength];
  64. }
  65. public override void Dispose ()
  66. {
  67. if (connection != null)
  68. connection.Close (false);
  69. }
  70. [MonoTODO]
  71. public override void Abort ()
  72. {
  73. throw new NotImplementedException ();
  74. }
  75. public ClientWebSocketOptions Options {
  76. get {
  77. return options;
  78. }
  79. }
  80. public override WebSocketState State {
  81. get {
  82. return state;
  83. }
  84. }
  85. public override WebSocketCloseStatus? CloseStatus {
  86. get {
  87. if (state != WebSocketState.Closed)
  88. return (WebSocketCloseStatus?)null;
  89. return WebSocketCloseStatus.Empty;
  90. }
  91. }
  92. public override string CloseStatusDescription {
  93. get {
  94. return null;
  95. }
  96. }
  97. public override string SubProtocol {
  98. get {
  99. return subProtocol;
  100. }
  101. }
  102. public async Task ConnectAsync (Uri uri, CancellationToken cancellationToken)
  103. {
  104. state = WebSocketState.Connecting;
  105. var httpUri = new UriBuilder (uri);
  106. if (uri.Scheme == "wss")
  107. httpUri.Scheme = "https";
  108. else
  109. httpUri.Scheme = "http";
  110. req = (HttpWebRequest)WebRequest.Create (httpUri.Uri);
  111. req.ReuseConnection = true;
  112. if (options.Cookies != null)
  113. req.CookieContainer = options.Cookies;
  114. if (options.CustomRequestHeaders.Count > 0) {
  115. foreach (var header in options.CustomRequestHeaders)
  116. req.Headers[header.Key] = header.Value;
  117. }
  118. var secKey = Convert.ToBase64String (Encoding.ASCII.GetBytes (Guid.NewGuid ().ToString ().Substring (0, 16)));
  119. string expectedAccept = Convert.ToBase64String (SHA1.Create ().ComputeHash (Encoding.ASCII.GetBytes (secKey + Magic)));
  120. req.Headers["Upgrade"] = "WebSocket";
  121. req.Headers["Sec-WebSocket-Version"] = VersionTag;
  122. req.Headers["Sec-WebSocket-Key"] = secKey;
  123. req.Headers["Sec-WebSocket-Origin"] = uri.Host;
  124. if (options.SubProtocols.Count > 0)
  125. req.Headers["Sec-WebSocket-Protocol"] = string.Join (",", options.SubProtocols);
  126. if (options.Credentials != null)
  127. req.Credentials = options.Credentials;
  128. if (options.ClientCertificates != null)
  129. req.ClientCertificates = options.ClientCertificates;
  130. if (options.Proxy != null)
  131. req.Proxy = options.Proxy;
  132. req.UseDefaultCredentials = options.UseDefaultCredentials;
  133. req.Connection = "Upgrade";
  134. HttpWebResponse resp = null;
  135. try {
  136. resp = (HttpWebResponse)(await req.GetResponseAsync ().ConfigureAwait (false));
  137. } catch (Exception e) {
  138. throw new WebSocketException (WebSocketError.Success, e);
  139. }
  140. connection = req.StoredConnection;
  141. underlyingSocket = connection.socket;
  142. if (resp.StatusCode != HttpStatusCode.SwitchingProtocols)
  143. throw new WebSocketException ("The server returned status code '" + (int)resp.StatusCode + "' when status code '101' was expected");
  144. if (!string.Equals (resp.Headers["Upgrade"], "WebSocket", StringComparison.OrdinalIgnoreCase)
  145. || !string.Equals (resp.Headers["Connection"], "Upgrade", StringComparison.OrdinalIgnoreCase)
  146. || !string.Equals (resp.Headers["Sec-WebSocket-Accept"], expectedAccept))
  147. throw new WebSocketException ("HTTP header error during handshake");
  148. if (resp.Headers["Sec-WebSocket-Protocol"] != null) {
  149. if (!options.SubProtocols.Contains (resp.Headers["Sec-WebSocket-Protocol"]))
  150. throw new WebSocketException (WebSocketError.UnsupportedProtocol);
  151. subProtocol = resp.Headers["Sec-WebSocket-Protocol"];
  152. }
  153. state = WebSocketState.Open;
  154. }
  155. public override Task SendAsync (ArraySegment<byte> buffer, WebSocketMessageType messageType, bool endOfMessage, CancellationToken cancellationToken)
  156. {
  157. EnsureWebSocketConnected ();
  158. ValidateArraySegment (buffer);
  159. if (connection == null)
  160. throw new WebSocketException (WebSocketError.Faulted);
  161. var count = Math.Max (options.SendBufferSize, buffer.Count) + HeaderMaxLength;
  162. if (sendBuffer == null || sendBuffer.Length != count)
  163. sendBuffer = new byte[count];
  164. return Task.Run (() => {
  165. EnsureWebSocketState (WebSocketState.Open, WebSocketState.CloseReceived);
  166. var maskOffset = WriteHeader (messageType, buffer, endOfMessage);
  167. if (buffer.Count > 0)
  168. MaskData (buffer, maskOffset);
  169. //underlyingSocket.Send (headerBuffer, 0, maskOffset + 4, SocketFlags.None);
  170. var headerLength = maskOffset + 4;
  171. Array.Copy (headerBuffer, sendBuffer, headerLength);
  172. underlyingSocket.Send (sendBuffer, 0, buffer.Count + headerLength, SocketFlags.None);
  173. });
  174. }
  175. const int messageTypeContinuation = 0;
  176. const int messageTypeText = 1;
  177. const int messageTypeBinary = 2;
  178. const int messageTypeClose = 8;
  179. WebSocketMessageType WireToMessageType (byte msgType)
  180. {
  181. if (msgType == messageTypeContinuation)
  182. return currentMessageType;
  183. if (msgType == messageTypeText)
  184. return WebSocketMessageType.Text;
  185. if (msgType == messageTypeBinary)
  186. return WebSocketMessageType.Binary;
  187. return WebSocketMessageType.Close;
  188. }
  189. static byte MessageTypeToWire (WebSocketMessageType type)
  190. {
  191. if (type == WebSocketMessageType.Text)
  192. return messageTypeText;
  193. if (type == WebSocketMessageType.Binary)
  194. return messageTypeBinary;
  195. return messageTypeClose;
  196. }
  197. public override Task<WebSocketReceiveResult> ReceiveAsync (ArraySegment<byte> buffer, CancellationToken cancellationToken)
  198. {
  199. EnsureWebSocketConnected ();
  200. ValidateArraySegment (buffer);
  201. return Task.Run (() => {
  202. EnsureWebSocketState (WebSocketState.Open, WebSocketState.CloseSent);
  203. bool isLast;
  204. long length;
  205. if (remaining == 0) {
  206. // First read the two first bytes to know what we are doing next
  207. connection.Read (req, headerBuffer, 0, 2);
  208. isLast = (headerBuffer[0] >> 7) > 0;
  209. var isMasked = (headerBuffer[1] >> 7) > 0;
  210. int mask = 0;
  211. currentMessageType = WireToMessageType ((byte)(headerBuffer[0] & 0xF));
  212. length = headerBuffer[1] & 0x7F;
  213. int offset = 0;
  214. if (length == 126) {
  215. offset = 2;
  216. connection.Read (req, headerBuffer, 2, offset);
  217. length = (headerBuffer[2] << 8) | headerBuffer[3];
  218. } else if (length == 127) {
  219. offset = 8;
  220. connection.Read (req, headerBuffer, 2, offset);
  221. length = 0;
  222. for (int i = 2; i <= 9; i++)
  223. length = (length << 8) | headerBuffer[i];
  224. }
  225. if (isMasked) {
  226. connection.Read (req, headerBuffer, 2 + offset, 4);
  227. for (int i = 0; i < 4; i++) {
  228. var pos = i + offset + 2;
  229. mask = (mask << 8) | headerBuffer[pos];
  230. }
  231. }
  232. } else {
  233. isLast = (headerBuffer[0] >> 7) > 0;
  234. currentMessageType = WireToMessageType ((byte)(headerBuffer[0] & 0xF));
  235. length = remaining;
  236. }
  237. if (currentMessageType == WebSocketMessageType.Close) {
  238. state = WebSocketState.Closed;
  239. var tmpBuffer = new byte[length];
  240. connection.Read (req, tmpBuffer, 0, tmpBuffer.Length);
  241. var closeStatus = (WebSocketCloseStatus)(tmpBuffer[0] << 8 | tmpBuffer[1]);
  242. var closeDesc = tmpBuffer.Length > 2 ? Encoding.UTF8.GetString (tmpBuffer, 2, tmpBuffer.Length - 2) : string.Empty;
  243. return new WebSocketReceiveResult ((int)length, currentMessageType, isLast, closeStatus, closeDesc);
  244. } else {
  245. var readLength = (int)(buffer.Count < length ? buffer.Count : length);
  246. connection.Read (req, buffer.Array, buffer.Offset, readLength);
  247. remaining = length - readLength;
  248. return new WebSocketReceiveResult ((int)readLength, currentMessageType, isLast && remaining == 0);
  249. }
  250. });
  251. }
  252. // The damn difference between those two methods is that CloseAsync will wait for server acknowledgement before completing
  253. // while CloseOutputAsync will send the close packet and simply complete.
  254. public async override Task CloseAsync (WebSocketCloseStatus closeStatus, string statusDescription, CancellationToken cancellationToken)
  255. {
  256. EnsureWebSocketConnected ();
  257. await SendCloseFrame (closeStatus, statusDescription, cancellationToken).ConfigureAwait (false);
  258. state = WebSocketState.CloseSent;
  259. // TODO: figure what's exceptions are thrown if the server returns something faulty here
  260. await ReceiveAsync (new ArraySegment<byte> (new byte[0]), cancellationToken).ConfigureAwait (false);
  261. state = WebSocketState.Closed;
  262. }
  263. public async override Task CloseOutputAsync (WebSocketCloseStatus closeStatus, string statusDescription, CancellationToken cancellationToken)
  264. {
  265. EnsureWebSocketConnected ();
  266. await SendCloseFrame (closeStatus, statusDescription, cancellationToken).ConfigureAwait (false);
  267. state = WebSocketState.CloseSent;
  268. }
  269. async Task SendCloseFrame (WebSocketCloseStatus closeStatus, string statusDescription, CancellationToken cancellationToken)
  270. {
  271. var statusDescBuffer = string.IsNullOrEmpty (statusDescription) ? new byte[2] : new byte[2 + Encoding.UTF8.GetByteCount (statusDescription)];
  272. statusDescBuffer[0] = (byte)(((ushort)closeStatus) >> 8);
  273. statusDescBuffer[1] = (byte)(((ushort)closeStatus) & 0xFF);
  274. if (!string.IsNullOrEmpty (statusDescription))
  275. Encoding.UTF8.GetBytes (statusDescription, 0, statusDescription.Length, statusDescBuffer, 2);
  276. await SendAsync (new ArraySegment<byte> (statusDescBuffer), WebSocketMessageType.Close, true, cancellationToken).ConfigureAwait (false);
  277. }
  278. int WriteHeader (WebSocketMessageType type, ArraySegment<byte> buffer, bool endOfMessage)
  279. {
  280. var opCode = MessageTypeToWire (type);
  281. var length = buffer.Count;
  282. headerBuffer[0] = (byte)(opCode | (endOfMessage ? 0 : 0x80));
  283. if (length < 126) {
  284. headerBuffer[1] = (byte)length;
  285. } else if (length <= ushort.MaxValue) {
  286. headerBuffer[1] = (byte)126;
  287. headerBuffer[2] = (byte)(length / 256);
  288. headerBuffer[3] = (byte)(length % 256);
  289. } else {
  290. headerBuffer[1] = (byte)127;
  291. int left = length;
  292. int unit = 256;
  293. for (int i = 9; i > 1; i--) {
  294. headerBuffer[i] = (byte)(left % unit);
  295. left = left / unit;
  296. }
  297. }
  298. var l = Math.Max (0, headerBuffer[1] - 125);
  299. var maskOffset = 2 + l * l * 2;
  300. GenerateMask (headerBuffer, maskOffset);
  301. // Since we are client only, we always mask the payload
  302. headerBuffer[1] |= 0x80;
  303. return maskOffset;
  304. }
  305. void GenerateMask (byte[] mask, int offset)
  306. {
  307. mask[offset + 0] = (byte)random.Next (0, 255);
  308. mask[offset + 1] = (byte)random.Next (0, 255);
  309. mask[offset + 2] = (byte)random.Next (0, 255);
  310. mask[offset + 3] = (byte)random.Next (0, 255);
  311. }
  312. void MaskData (ArraySegment<byte> buffer, int maskOffset)
  313. {
  314. var sendBufferOffset = maskOffset + 4;
  315. for (var i = 0; i < buffer.Count; i++)
  316. sendBuffer[i + sendBufferOffset] = (byte)(buffer.Array[buffer.Offset + i] ^ headerBuffer[maskOffset + (i % 4)]);
  317. }
  318. void EnsureWebSocketConnected ()
  319. {
  320. if (state < WebSocketState.Open)
  321. throw new InvalidOperationException ("The WebSocket is not connected");
  322. }
  323. void EnsureWebSocketState (params WebSocketState[] validStates)
  324. {
  325. foreach (var validState in validStates)
  326. if (state == validState)
  327. return;
  328. throw new WebSocketException ("The WebSocket is in an invalid state ('" + state + "') for this operation. Valid states are: " + string.Join (", ", validStates));
  329. }
  330. void ValidateArraySegment (ArraySegment<byte> segment)
  331. {
  332. if (segment.Array == null)
  333. throw new ArgumentNullException ("buffer.Array");
  334. if (segment.Offset < 0)
  335. throw new ArgumentOutOfRangeException ("buffer.Offset");
  336. if (segment.Offset + segment.Count > segment.Array.Length)
  337. throw new ArgumentOutOfRangeException ("buffer.Count");
  338. }
  339. }
  340. }
  341. #endif