5 // Jérémie Laval <jeremie dot laval at xamarin dot com>
7 // Copyright 2013 Xamarin Inc (http://www.xamarin.com).
9 // Lightly inspired from WebSocket4Net distributed under the Apache License 2.0
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:
18 // The above copyright notice and this permission notice shall be included in
19 // all copies or substantial portions of the Software.
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
32 using System.Net.Sockets;
33 using System.Security.Principal;
34 using System.Security.Cryptography.X509Certificates;
35 using System.Runtime.CompilerServices;
36 using System.Collections.Generic;
37 using System.Threading;
38 using System.Threading.Tasks;
39 using System.Globalization;
41 using System.Security.Cryptography;
43 namespace System.Net.WebSockets
45 public class ClientWebSocket : WebSocket, IDisposable
47 const string Magic = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
48 const string VersionTag = "13";
50 ClientWebSocketOptions options;
55 WebConnection connection;
56 Socket underlyingSocket;
58 Random random = new Random ();
60 const int HeaderMaxLength = 14;
65 public ClientWebSocket ()
67 options = new ClientWebSocketOptions ();
68 state = WebSocketState.None;
69 headerBuffer = new byte[HeaderMaxLength];
72 public override void Dispose ()
74 if (connection != null)
75 connection.Close (false);
79 public override void Abort ()
81 throw new NotImplementedException ();
84 public ClientWebSocketOptions Options {
90 public override WebSocketState State {
96 public override WebSocketCloseStatus? CloseStatus {
98 if (state != WebSocketState.Closed)
99 return (WebSocketCloseStatus?)null;
100 return WebSocketCloseStatus.Empty;
104 public override string CloseStatusDescription {
110 public override string SubProtocol {
116 public async Task ConnectAsync (Uri uri, CancellationToken cancellationToken)
118 state = WebSocketState.Connecting;
119 var httpUri = new UriBuilder (uri);
120 if (uri.Scheme == "wss")
121 httpUri.Scheme = "https";
123 httpUri.Scheme = "http";
124 req = (HttpWebRequest)WebRequest.Create (httpUri.Uri);
125 req.ReuseConnection = true;
126 if (options.Cookies != null)
127 req.CookieContainer = options.Cookies;
129 if (options.CustomRequestHeaders.Count > 0) {
130 foreach (var header in options.CustomRequestHeaders)
131 req.Headers[header.Key] = header.Value;
134 var secKey = Convert.ToBase64String (Encoding.ASCII.GetBytes (Guid.NewGuid ().ToString ().Substring (0, 16)));
135 string expectedAccept = Convert.ToBase64String (SHA1.Create ().ComputeHash (Encoding.ASCII.GetBytes (secKey + Magic)));
137 req.Headers["Upgrade"] = "WebSocket";
138 req.Headers["Sec-WebSocket-Version"] = VersionTag;
139 req.Headers["Sec-WebSocket-Key"] = secKey;
140 req.Headers["Sec-WebSocket-Origin"] = uri.Host;
141 if (options.SubProtocols.Count > 0)
142 req.Headers["Sec-WebSocket-Protocol"] = string.Join (",", options.SubProtocols);
144 if (options.Credentials != null)
145 req.Credentials = options.Credentials;
146 if (options.ClientCertificates != null)
147 req.ClientCertificates = options.ClientCertificates;
148 if (options.Proxy != null)
149 req.Proxy = options.Proxy;
150 req.UseDefaultCredentials = options.UseDefaultCredentials;
151 req.Connection = "Upgrade";
153 HttpWebResponse resp = null;
155 resp = (HttpWebResponse)(await req.GetResponseAsync ().ConfigureAwait (false));
156 } catch (Exception e) {
157 throw new WebSocketException (WebSocketError.Success, e);
160 connection = req.StoredConnection;
161 underlyingSocket = connection.socket;
163 if (resp.StatusCode != HttpStatusCode.SwitchingProtocols)
164 throw new WebSocketException ("The server returned status code '" + (int)resp.StatusCode + "' when status code '101' was expected");
165 if (!string.Equals (resp.Headers["Upgrade"], "WebSocket", StringComparison.OrdinalIgnoreCase)
166 || !string.Equals (resp.Headers["Connection"], "Upgrade", StringComparison.OrdinalIgnoreCase)
167 || !string.Equals (resp.Headers["Sec-WebSocket-Accept"], expectedAccept))
168 throw new WebSocketException ("HTTP header error during handshake");
169 if (resp.Headers["Sec-WebSocket-Protocol"] != null) {
170 if (!options.SubProtocols.Contains (resp.Headers["Sec-WebSocket-Protocol"]))
171 throw new WebSocketException (WebSocketError.UnsupportedProtocol);
172 subProtocol = resp.Headers["Sec-WebSocket-Protocol"];
175 state = WebSocketState.Open;
178 public override Task SendAsync (ArraySegment<byte> buffer, WebSocketMessageType messageType, bool endOfMessage, CancellationToken cancellationToken)
180 EnsureWebSocketConnected ();
181 ValidateArraySegment (buffer);
182 if (connection == null)
183 throw new WebSocketException (WebSocketError.Faulted);
184 var count = Math.Max (options.SendBufferSize, buffer.Count) + HeaderMaxLength;
185 if (sendBuffer == null || sendBuffer.Length != count)
186 sendBuffer = new byte[count];
187 return Task.Run (() => {
188 EnsureWebSocketState (WebSocketState.Open, WebSocketState.CloseReceived);
189 var maskOffset = WriteHeader (messageType, buffer, endOfMessage);
191 if (buffer.Count > 0)
192 MaskData (buffer, maskOffset);
193 //underlyingSocket.Send (headerBuffer, 0, maskOffset + 4, SocketFlags.None);
194 var headerLength = maskOffset + 4;
195 Array.Copy (headerBuffer, sendBuffer, headerLength);
196 underlyingSocket.Send (sendBuffer, 0, buffer.Count + headerLength, SocketFlags.None);
200 const int messageTypeText = 1;
201 const int messageTypeBinary = 2;
202 const int messageTypeClose = 8;
204 static WebSocketMessageType WireToMessageType (byte msgType)
207 if (msgType == messageTypeText)
208 return WebSocketMessageType.Text;
209 if (msgType == messageTypeBinary)
210 return WebSocketMessageType.Binary;
211 return WebSocketMessageType.Close;
214 static byte MessageTypeToWire (WebSocketMessageType type)
216 if (type == WebSocketMessageType.Text)
217 return messageTypeText;
218 if (type == WebSocketMessageType.Binary)
219 return messageTypeBinary;
220 return messageTypeClose;
223 public override Task<WebSocketReceiveResult> ReceiveAsync (ArraySegment<byte> buffer, CancellationToken cancellationToken)
225 EnsureWebSocketConnected ();
226 ValidateArraySegment (buffer);
227 return Task.Run (() => {
228 EnsureWebSocketState (WebSocketState.Open, WebSocketState.CloseSent);
231 WebSocketMessageType type;
234 if (remaining == 0) {
235 // First read the two first bytes to know what we are doing next
236 connection.Read (req, headerBuffer, 0, 2);
237 isLast = (headerBuffer[0] >> 7) > 0;
238 var isMasked = (headerBuffer[1] >> 7) > 0;
240 type = WireToMessageType ((byte)(headerBuffer[0] & 0xF));
241 length = headerBuffer[1] & 0x7F;
245 connection.Read (req, headerBuffer, 2, offset);
246 length = (headerBuffer[2] << 8) | headerBuffer[3];
247 } else if (length == 127) {
249 connection.Read (req, headerBuffer, 2, offset);
251 for (int i = 2; i <= 9; i++)
252 length = (length << 8) | headerBuffer[i];
256 connection.Read (req, headerBuffer, 2 + offset, 4);
257 for (int i = 0; i < 4; i++) {
258 var pos = i + offset + 2;
259 mask = (mask << 8) | headerBuffer[pos];
263 isLast = (headerBuffer[0] >> 7) > 0;
264 type = WireToMessageType ((byte)(headerBuffer[0] & 0xF));
268 if (type == WebSocketMessageType.Close) {
269 state = WebSocketState.Closed;
270 var tmpBuffer = new byte[length];
271 connection.Read (req, tmpBuffer, 0, tmpBuffer.Length);
272 var closeStatus = (WebSocketCloseStatus)(tmpBuffer[0] << 8 | tmpBuffer[1]);
273 var closeDesc = tmpBuffer.Length > 2 ? Encoding.UTF8.GetString (tmpBuffer, 2, tmpBuffer.Length - 2) : string.Empty;
274 return new WebSocketReceiveResult ((int)length, type, isLast, closeStatus, closeDesc);
276 var readLength = (int)(buffer.Count < length ? buffer.Count : length);
277 connection.Read (req, buffer.Array, buffer.Offset, readLength);
278 remaining = length - readLength;
280 return new WebSocketReceiveResult ((int)readLength, type, isLast && remaining == 0);
285 // The damn difference between those two methods is that CloseAsync will wait for server acknowledgement before completing
286 // while CloseOutputAsync will send the close packet and simply complete.
288 public async override Task CloseAsync (WebSocketCloseStatus closeStatus, string statusDescription, CancellationToken cancellationToken)
290 EnsureWebSocketConnected ();
291 await SendCloseFrame (closeStatus, statusDescription, cancellationToken).ConfigureAwait (false);
292 state = WebSocketState.CloseSent;
293 // TODO: figure what's exceptions are thrown if the server returns something faulty here
294 await ReceiveAsync (new ArraySegment<byte> (new byte[0]), cancellationToken).ConfigureAwait (false);
295 state = WebSocketState.Closed;
298 public async override Task CloseOutputAsync (WebSocketCloseStatus closeStatus, string statusDescription, CancellationToken cancellationToken)
300 EnsureWebSocketConnected ();
301 await SendCloseFrame (closeStatus, statusDescription, cancellationToken).ConfigureAwait (false);
302 state = WebSocketState.CloseSent;
305 async Task SendCloseFrame (WebSocketCloseStatus closeStatus, string statusDescription, CancellationToken cancellationToken)
307 var statusDescBuffer = string.IsNullOrEmpty (statusDescription) ? new byte[2] : new byte[2 + Encoding.UTF8.GetByteCount (statusDescription)];
308 statusDescBuffer[0] = (byte)(((ushort)closeStatus) >> 8);
309 statusDescBuffer[1] = (byte)(((ushort)closeStatus) & 0xFF);
310 if (!string.IsNullOrEmpty (statusDescription))
311 Encoding.UTF8.GetBytes (statusDescription, 0, statusDescription.Length, statusDescBuffer, 2);
312 await SendAsync (new ArraySegment<byte> (statusDescBuffer), WebSocketMessageType.Close, true, cancellationToken).ConfigureAwait (false);
315 int WriteHeader (WebSocketMessageType type, ArraySegment<byte> buffer, bool endOfMessage)
317 var opCode = MessageTypeToWire (type);
318 var length = buffer.Count;
320 headerBuffer[0] = (byte)(opCode | (endOfMessage ? 0x80 : 0));
322 headerBuffer[1] = (byte)length;
323 } else if (length <= ushort.MaxValue) {
324 headerBuffer[1] = (byte)126;
325 headerBuffer[2] = (byte)(length / 256);
326 headerBuffer[3] = (byte)(length % 256);
328 headerBuffer[1] = (byte)127;
333 for (int i = 9; i > 1; i--) {
334 headerBuffer[i] = (byte)(left % unit);
339 var l = Math.Max (0, headerBuffer[1] - 125);
340 var maskOffset = 2 + l * l * 2;
341 GenerateMask (headerBuffer, maskOffset);
343 // Since we are client only, we always mask the payload
344 headerBuffer[1] |= 0x80;
349 void GenerateMask (byte[] mask, int offset)
351 mask[offset + 0] = (byte)random.Next (0, 255);
352 mask[offset + 1] = (byte)random.Next (0, 255);
353 mask[offset + 2] = (byte)random.Next (0, 255);
354 mask[offset + 3] = (byte)random.Next (0, 255);
357 void MaskData (ArraySegment<byte> buffer, int maskOffset)
359 var sendBufferOffset = maskOffset + 4;
360 for (var i = 0; i < buffer.Count; i++)
361 sendBuffer[i + sendBufferOffset] = (byte)(buffer.Array[buffer.Offset + i] ^ headerBuffer[maskOffset + (i % 4)]);
364 void EnsureWebSocketConnected ()
366 if (state < WebSocketState.Open)
367 throw new InvalidOperationException ("The WebSocket is not connected");
370 void EnsureWebSocketState (params WebSocketState[] validStates)
372 foreach (var validState in validStates)
373 if (state == validState)
375 throw new WebSocketException ("The WebSocket is in an invalid state ('" + state + "') for this operation. Valid states are: " + string.Join (", ", validStates));
378 void ValidateArraySegment (ArraySegment<byte> segment)
380 if (segment.Array == null)
381 throw new ArgumentNullException ("buffer.Array");
382 if (segment.Offset < 0)
383 throw new ArgumentOutOfRangeException ("buffer.Offset");
384 if (segment.Offset + segment.Count > segment.Array.Length)
385 throw new ArgumentOutOfRangeException ("buffer.Count");