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
33 using System.Net.Sockets;
34 using System.Security.Principal;
35 using System.Security.Cryptography.X509Certificates;
36 using System.Runtime.CompilerServices;
37 using System.Collections.Generic;
38 using System.Threading;
39 using System.Threading.Tasks;
40 using System.Globalization;
42 using System.Security.Cryptography;
44 namespace System.Net.WebSockets
46 public class ClientWebSocket : WebSocket, IDisposable
48 const string Magic = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
49 const string VersionTag = "13";
51 ClientWebSocketOptions options;
56 WebConnection connection;
57 Socket underlyingSocket;
59 Random random = new Random ();
61 const int HeaderMaxLength = 14;
66 public ClientWebSocket ()
68 options = new ClientWebSocketOptions ();
69 state = WebSocketState.None;
70 headerBuffer = new byte[HeaderMaxLength];
73 public override void Dispose ()
75 if (connection != null)
76 connection.Close (false);
80 public override void Abort ()
82 throw new NotImplementedException ();
85 public ClientWebSocketOptions Options {
91 public override WebSocketState State {
97 public override WebSocketCloseStatus? CloseStatus {
99 if (state != WebSocketState.Closed)
100 return (WebSocketCloseStatus?)null;
101 return WebSocketCloseStatus.Empty;
105 public override string CloseStatusDescription {
111 public override string SubProtocol {
117 public async Task ConnectAsync (Uri uri, CancellationToken cancellationToken)
119 state = WebSocketState.Connecting;
120 var httpUri = new UriBuilder (uri);
121 if (uri.Scheme == "wss")
122 httpUri.Scheme = "https";
124 httpUri.Scheme = "http";
125 req = (HttpWebRequest)WebRequest.Create (httpUri.Uri);
126 req.ReuseConnection = true;
127 if (options.Cookies != null)
128 req.CookieContainer = options.Cookies;
130 if (options.CustomRequestHeaders.Count > 0) {
131 foreach (var header in options.CustomRequestHeaders)
132 req.Headers[header.Key] = header.Value;
135 var secKey = Convert.ToBase64String (Encoding.ASCII.GetBytes (Guid.NewGuid ().ToString ().Substring (0, 16)));
136 string expectedAccept = Convert.ToBase64String (SHA1.Create ().ComputeHash (Encoding.ASCII.GetBytes (secKey + Magic)));
138 req.Headers["Upgrade"] = "WebSocket";
139 req.Headers["Sec-WebSocket-Version"] = VersionTag;
140 req.Headers["Sec-WebSocket-Key"] = secKey;
141 req.Headers["Sec-WebSocket-Origin"] = uri.Host;
142 if (options.SubProtocols.Count > 0)
143 req.Headers["Sec-WebSocket-Protocol"] = string.Join (",", options.SubProtocols);
145 if (options.Credentials != null)
146 req.Credentials = options.Credentials;
147 if (options.ClientCertificates != null)
148 req.ClientCertificates = options.ClientCertificates;
149 if (options.Proxy != null)
150 req.Proxy = options.Proxy;
151 req.UseDefaultCredentials = options.UseDefaultCredentials;
152 req.Connection = "Upgrade";
154 HttpWebResponse resp = null;
156 resp = (HttpWebResponse)(await req.GetResponseAsync ().ConfigureAwait (false));
157 } catch (Exception e) {
158 throw new WebSocketException (WebSocketError.Success, e);
161 connection = req.StoredConnection;
162 underlyingSocket = connection.socket;
164 if (resp.StatusCode != HttpStatusCode.SwitchingProtocols)
165 throw new WebSocketException ("The server returned status code '" + (int)resp.StatusCode + "' when status code '101' was expected");
166 if (!string.Equals (resp.Headers["Upgrade"], "WebSocket", StringComparison.OrdinalIgnoreCase)
167 || !string.Equals (resp.Headers["Connection"], "Upgrade", StringComparison.OrdinalIgnoreCase)
168 || !string.Equals (resp.Headers["Sec-WebSocket-Accept"], expectedAccept))
169 throw new WebSocketException ("HTTP header error during handshake");
170 if (resp.Headers["Sec-WebSocket-Protocol"] != null) {
171 if (!options.SubProtocols.Contains (resp.Headers["Sec-WebSocket-Protocol"]))
172 throw new WebSocketException (WebSocketError.UnsupportedProtocol);
173 subProtocol = resp.Headers["Sec-WebSocket-Protocol"];
176 state = WebSocketState.Open;
179 public override Task SendAsync (ArraySegment<byte> buffer, WebSocketMessageType messageType, bool endOfMessage, CancellationToken cancellationToken)
181 EnsureWebSocketConnected ();
182 ValidateArraySegment (buffer);
183 if (connection == null)
184 throw new WebSocketException (WebSocketError.Faulted);
185 var count = Math.Max (options.SendBufferSize, buffer.Count) + HeaderMaxLength;
186 if (sendBuffer == null || sendBuffer.Length != count)
187 sendBuffer = new byte[count];
188 return Task.Run (() => {
189 EnsureWebSocketState (WebSocketState.Open, WebSocketState.CloseReceived);
190 var maskOffset = WriteHeader (messageType, buffer, endOfMessage);
192 if (buffer.Count > 0)
193 MaskData (buffer, maskOffset);
194 //underlyingSocket.Send (headerBuffer, 0, maskOffset + 4, SocketFlags.None);
195 var headerLength = maskOffset + 4;
196 Array.Copy (headerBuffer, sendBuffer, headerLength);
197 underlyingSocket.Send (sendBuffer, 0, buffer.Count + headerLength, SocketFlags.None);
201 const int messageTypeText = 1;
202 const int messageTypeBinary = 2;
203 const int messageTypeClose = 8;
205 static WebSocketMessageType WireToMessageType (byte msgType)
208 if (msgType == messageTypeText)
209 return WebSocketMessageType.Text;
210 if (msgType == messageTypeBinary)
211 return WebSocketMessageType.Binary;
212 return WebSocketMessageType.Close;
215 static byte MessageTypeToWire (WebSocketMessageType type)
217 if (type == WebSocketMessageType.Text)
218 return messageTypeText;
219 if (type == WebSocketMessageType.Binary)
220 return messageTypeBinary;
221 return messageTypeClose;
224 public override Task<WebSocketReceiveResult> ReceiveAsync (ArraySegment<byte> buffer, CancellationToken cancellationToken)
226 EnsureWebSocketConnected ();
227 ValidateArraySegment (buffer);
228 return Task.Run (() => {
229 EnsureWebSocketState (WebSocketState.Open, WebSocketState.CloseSent);
232 WebSocketMessageType type;
235 if (remaining == 0) {
236 // First read the two first bytes to know what we are doing next
237 connection.Read (req, headerBuffer, 0, 2);
238 isLast = (headerBuffer[0] >> 7) > 0;
239 var isMasked = (headerBuffer[1] >> 7) > 0;
241 type = WireToMessageType ((byte)(headerBuffer[0] & 0xF));
242 length = headerBuffer[1] & 0x7F;
246 connection.Read (req, headerBuffer, 2, offset);
247 length = (headerBuffer[2] << 8) | headerBuffer[3];
248 } else if (length == 127) {
250 connection.Read (req, headerBuffer, 2, offset);
252 for (int i = 2; i <= 9; i++)
253 length = (length << 8) | headerBuffer[i];
257 connection.Read (req, headerBuffer, 2 + offset, 4);
258 for (int i = 0; i < 4; i++) {
259 var pos = i + offset + 2;
260 mask = (mask << 8) | headerBuffer[pos];
264 isLast = (headerBuffer[0] >> 7) > 0;
265 type = WireToMessageType ((byte)(headerBuffer[0] & 0xF));
269 if (type == WebSocketMessageType.Close) {
270 state = WebSocketState.Closed;
271 var tmpBuffer = new byte[length];
272 connection.Read (req, tmpBuffer, 0, tmpBuffer.Length);
273 var closeStatus = (WebSocketCloseStatus)(tmpBuffer[0] << 8 | tmpBuffer[1]);
274 var closeDesc = tmpBuffer.Length > 2 ? Encoding.UTF8.GetString (tmpBuffer, 2, tmpBuffer.Length - 2) : string.Empty;
275 return new WebSocketReceiveResult ((int)length, type, isLast, closeStatus, closeDesc);
277 var readLength = (int)(buffer.Count < length ? buffer.Count : length);
278 connection.Read (req, buffer.Array, buffer.Offset, readLength);
279 remaining = length - readLength;
281 return new WebSocketReceiveResult ((int)readLength, type, isLast && remaining == 0);
286 // The damn difference between those two methods is that CloseAsync will wait for server acknowledgement before completing
287 // while CloseOutputAsync will send the close packet and simply complete.
289 public async override Task CloseAsync (WebSocketCloseStatus closeStatus, string statusDescription, CancellationToken cancellationToken)
291 EnsureWebSocketConnected ();
292 await SendCloseFrame (closeStatus, statusDescription, cancellationToken).ConfigureAwait (false);
293 state = WebSocketState.CloseSent;
294 // TODO: figure what's exceptions are thrown if the server returns something faulty here
295 await ReceiveAsync (new ArraySegment<byte> (new byte[0]), cancellationToken).ConfigureAwait (false);
296 state = WebSocketState.Closed;
299 public async override Task CloseOutputAsync (WebSocketCloseStatus closeStatus, string statusDescription, CancellationToken cancellationToken)
301 EnsureWebSocketConnected ();
302 await SendCloseFrame (closeStatus, statusDescription, cancellationToken).ConfigureAwait (false);
303 state = WebSocketState.CloseSent;
306 async Task SendCloseFrame (WebSocketCloseStatus closeStatus, string statusDescription, CancellationToken cancellationToken)
308 var statusDescBuffer = string.IsNullOrEmpty (statusDescription) ? new byte[2] : new byte[2 + Encoding.UTF8.GetByteCount (statusDescription)];
309 statusDescBuffer[0] = (byte)(((ushort)closeStatus) >> 8);
310 statusDescBuffer[1] = (byte)(((ushort)closeStatus) & 0xFF);
311 if (!string.IsNullOrEmpty (statusDescription))
312 Encoding.UTF8.GetBytes (statusDescription, 0, statusDescription.Length, statusDescBuffer, 2);
313 await SendAsync (new ArraySegment<byte> (statusDescBuffer), WebSocketMessageType.Close, true, cancellationToken).ConfigureAwait (false);
316 int WriteHeader (WebSocketMessageType type, ArraySegment<byte> buffer, bool endOfMessage)
318 var opCode = MessageTypeToWire (type);
319 var length = buffer.Count;
321 headerBuffer[0] = (byte)(opCode | (endOfMessage ? 0 : 0x80));
323 headerBuffer[1] = (byte)length;
324 } else if (length <= ushort.MaxValue) {
325 headerBuffer[1] = (byte)126;
326 headerBuffer[2] = (byte)(length / 256);
327 headerBuffer[3] = (byte)(length % 256);
329 headerBuffer[1] = (byte)127;
334 for (int i = 9; i > 1; i--) {
335 headerBuffer[i] = (byte)(left % unit);
340 var l = Math.Max (0, headerBuffer[1] - 125);
341 var maskOffset = 2 + l * l * 2;
342 GenerateMask (headerBuffer, maskOffset);
344 // Since we are client only, we always mask the payload
345 headerBuffer[1] |= 0x80;
350 void GenerateMask (byte[] mask, int offset)
352 mask[offset + 0] = (byte)random.Next (0, 255);
353 mask[offset + 1] = (byte)random.Next (0, 255);
354 mask[offset + 2] = (byte)random.Next (0, 255);
355 mask[offset + 3] = (byte)random.Next (0, 255);
358 void MaskData (ArraySegment<byte> buffer, int maskOffset)
360 var sendBufferOffset = maskOffset + 4;
361 for (var i = 0; i < buffer.Count; i++)
362 sendBuffer[i + sendBufferOffset] = (byte)(buffer.Array[buffer.Offset + i] ^ headerBuffer[maskOffset + (i % 4)]);
365 void EnsureWebSocketConnected ()
367 if (state < WebSocketState.Open)
368 throw new InvalidOperationException ("The WebSocket is not connected");
371 void EnsureWebSocketState (params WebSocketState[] validStates)
373 foreach (var validState in validStates)
374 if (state == validState)
376 throw new WebSocketException ("The WebSocket is in an invalid state ('" + state + "') for this operation. Valid states are: " + string.Join (", ", validStates));
379 void ValidateArraySegment (ArraySegment<byte> segment)
381 if (segment.Array == null)
382 throw new ArgumentNullException ("buffer.Array");
383 if (segment.Offset < 0)
384 throw new ArgumentOutOfRangeException ("buffer.Offset");
385 if (segment.Offset + segment.Count > segment.Array.Length)
386 throw new ArgumentOutOfRangeException ("buffer.Count");