Merge pull request #1496 from echampet/serializers
[mono.git] / mcs / class / System / System.Net.WebSockets / ClientWebSocket.cs
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
29
30 using System;
31 using System.Net;
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;
40 using System.Text;
41 using System.Security.Cryptography;
42
43 namespace System.Net.WebSockets
44 {
45         public class ClientWebSocket : WebSocket, IDisposable
46         {
47                 const string Magic = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
48                 const string VersionTag = "13";
49
50                 ClientWebSocketOptions options;
51                 WebSocketState state;
52                 string subProtocol;
53
54                 HttpWebRequest req;
55                 WebConnection connection;
56                 Socket underlyingSocket;
57
58                 Random random = new Random ();
59
60                 const int HeaderMaxLength = 14;
61                 byte[] headerBuffer;
62                 byte[] sendBuffer;
63                 long remaining;
64
65                 public ClientWebSocket ()
66                 {
67                         options = new ClientWebSocketOptions ();
68                         state = WebSocketState.None;
69                         headerBuffer = new byte[HeaderMaxLength];
70                 }
71
72                 public override void Dispose ()
73                 {
74                         if (connection != null)
75                                 connection.Close (false);
76                 }
77
78                 [MonoTODO]
79                 public override void Abort ()
80                 {
81                         throw new NotImplementedException ();
82                 }
83
84                 public ClientWebSocketOptions Options {
85                         get {
86                                 return options;
87                         }
88                 }
89
90                 public override WebSocketState State {
91                         get {
92                                 return state;
93                         }
94                 }
95
96                 public override WebSocketCloseStatus? CloseStatus {
97                         get {
98                                 if (state != WebSocketState.Closed)
99                                         return (WebSocketCloseStatus?)null;
100                                 return WebSocketCloseStatus.Empty;
101                         }
102                 }
103
104                 public override string CloseStatusDescription {
105                         get {
106                                 return null;
107                         }
108                 }
109
110                 public override string SubProtocol {
111                         get {
112                                 return subProtocol;
113                         }
114                 }
115
116                 public async Task ConnectAsync (Uri uri, CancellationToken cancellationToken)
117                 {
118                         state = WebSocketState.Connecting;
119                         var httpUri = new UriBuilder (uri);
120                         if (uri.Scheme == "wss")
121                                 httpUri.Scheme = "https";
122                         else
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;
128
129                         if (options.CustomRequestHeaders.Count > 0) {
130                                 foreach (var header in options.CustomRequestHeaders)
131                                         req.Headers[header.Key] = header.Value;
132                         }
133
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)));
136
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);
143
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";
152
153                         HttpWebResponse resp = null;
154                         try {
155                                 resp = (HttpWebResponse)(await req.GetResponseAsync ().ConfigureAwait (false));
156                         } catch (Exception e) {
157                                 throw new WebSocketException (WebSocketError.Success, e);
158                         }
159
160                         connection = req.StoredConnection;
161                         underlyingSocket = connection.socket;
162
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"];
173                         }
174
175                         state = WebSocketState.Open;
176                 }
177
178                 public override Task SendAsync (ArraySegment<byte> buffer, WebSocketMessageType messageType, bool endOfMessage, CancellationToken cancellationToken)
179                 {
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);
190
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);
197                         });
198                 }
199                 
200                 const int messageTypeText = 1;
201                 const int messageTypeBinary = 2;
202                 const int messageTypeClose = 8;
203
204                 static WebSocketMessageType WireToMessageType (byte msgType)
205                 {
206                         
207                         if (msgType == messageTypeText)
208                                 return WebSocketMessageType.Text;
209                         if (msgType == messageTypeBinary)
210                                 return WebSocketMessageType.Binary;
211                         return WebSocketMessageType.Close;
212                 }
213
214                 static byte MessageTypeToWire (WebSocketMessageType type)
215                 {
216                         if (type == WebSocketMessageType.Text)
217                                 return messageTypeText;
218                         if (type == WebSocketMessageType.Binary)
219                                 return messageTypeBinary;
220                         return messageTypeClose;
221                 }
222                 
223                 public override Task<WebSocketReceiveResult> ReceiveAsync (ArraySegment<byte> buffer, CancellationToken cancellationToken)
224                 {
225                         EnsureWebSocketConnected ();
226                         ValidateArraySegment (buffer);
227                         return Task.Run (() => {
228                                 EnsureWebSocketState (WebSocketState.Open, WebSocketState.CloseSent);
229
230                                 bool isLast;
231                                 WebSocketMessageType type;
232                                 long length;
233
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;
239                                         int mask = 0;
240                                         type = WireToMessageType ((byte)(headerBuffer[0] & 0xF));
241                                         length = headerBuffer[1] & 0x7F;
242                                         int offset = 0;
243                                         if (length == 126) {
244                                                 offset = 2;
245                                                 connection.Read (req, headerBuffer, 2, offset);
246                                         length = (headerBuffer[2] << 8) | headerBuffer[3];
247                                         } else if (length == 127) {
248                                                 offset = 8;
249                                                 connection.Read (req, headerBuffer, 2, offset);
250                                                 length = 0;
251                                                 for (int i = 2; i <= 9; i++)
252                                                         length = (length << 8) | headerBuffer[i];
253                                         }
254
255                                         if (isMasked) {
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];
260                                                 }
261                                         }
262                                 } else {
263                                         isLast = (headerBuffer[0] >> 7) > 0;
264                                         type = WireToMessageType ((byte)(headerBuffer[0] & 0xF));
265                                         length = remaining;
266                                 }
267
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);
275                                 } else {
276                                         var readLength = (int)(buffer.Count < length ? buffer.Count : length);
277                                         connection.Read (req, buffer.Array, buffer.Offset, readLength);
278                                         remaining = length - readLength;
279
280                                         return new WebSocketReceiveResult ((int)readLength, type, isLast && remaining == 0);
281                                 }
282                         });
283                 }
284
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.
287
288                 public async override Task CloseAsync (WebSocketCloseStatus closeStatus, string statusDescription, CancellationToken cancellationToken)
289                 {
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;
296                 }
297
298                 public async override Task CloseOutputAsync (WebSocketCloseStatus closeStatus, string statusDescription, CancellationToken cancellationToken)
299                 {
300                         EnsureWebSocketConnected ();
301                         await SendCloseFrame (closeStatus, statusDescription, cancellationToken).ConfigureAwait (false);
302                         state = WebSocketState.CloseSent;
303                 }
304
305                 async Task SendCloseFrame (WebSocketCloseStatus closeStatus, string statusDescription, CancellationToken cancellationToken)
306                 {
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);
313                 }
314
315                 int WriteHeader (WebSocketMessageType type, ArraySegment<byte> buffer, bool endOfMessage)
316                 {
317                         var opCode = MessageTypeToWire (type);
318                         var length = buffer.Count;
319
320                         headerBuffer[0] = (byte)(opCode | (endOfMessage ? 0x80 : 0));
321                         if (length < 126) {
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);
327                         } else {
328                                 headerBuffer[1] = (byte)127;
329
330                                 int left = length;
331                                 int unit = 256;
332
333                                 for (int i = 9; i > 1; i--) {
334                                         headerBuffer[i] = (byte)(left % unit);
335                                         left = left / unit;
336                                 }
337                         }
338
339                         var l = Math.Max (0, headerBuffer[1] - 125);
340                         var maskOffset = 2 + l * l * 2;
341                         GenerateMask (headerBuffer, maskOffset);
342
343                         // Since we are client only, we always mask the payload
344                         headerBuffer[1] |= 0x80;
345
346                         return maskOffset;
347                 }
348
349                 void GenerateMask (byte[] mask, int offset)
350                 {
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);
355                 }
356
357                 void MaskData (ArraySegment<byte> buffer, int maskOffset)
358                 {
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)]);
362                 }
363
364                 void EnsureWebSocketConnected ()
365                 {
366                         if (state < WebSocketState.Open)
367                                 throw new InvalidOperationException ("The WebSocket is not connected");
368                 }
369
370                 void EnsureWebSocketState (params WebSocketState[] validStates)
371                 {
372                         foreach (var validState in validStates)
373                                 if (state == validState)
374                                         return;
375                         throw new WebSocketException ("The WebSocket is in an invalid state ('" + state + "') for this operation. Valid states are: " + string.Join (", ", validStates));
376                 }
377
378                 void ValidateArraySegment (ArraySegment<byte> segment)
379                 {
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");
386                 }
387         }
388 }
389