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