Fix fallout from WebSocketMessageType change.
[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
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                                 // First read the two first bytes to know what we are doing next
230                                 connection.Read (req, headerBuffer, 0, 2);
231                                 var isLast = (headerBuffer[0] >> 7) > 0;
232                                 var isMasked = (headerBuffer[1] >> 7) > 0;
233                                 int mask = 0;
234                                 var type = WireToMessageType ((byte)(headerBuffer[0] & 0xF));
235                                 long length = headerBuffer[1] & 0x7F;
236                                 int offset = 0;
237                                 if (length == 126) {
238                                         offset = 2;
239                                         connection.Read (req, headerBuffer, 2, offset);
240                                         length = (headerBuffer[2] << 8) | headerBuffer[3];
241                                 } else if (length == 127) {
242                                         offset = 8;
243                                         connection.Read (req, headerBuffer, 2, offset);
244                                         length = 0;
245                                         for (int i = 2; i <= 9; i++)
246                                                 length = (length << 8) | headerBuffer[i];
247                                 }
248
249                                 if (isMasked) {
250                                         connection.Read (req, headerBuffer, 2 + offset, 4);
251                                         for (int i = 0; i < 4; i++) {
252                                                 var pos = i + offset + 2;
253                                                 mask = (mask << 8) | headerBuffer[pos];
254                                         }
255                                 }
256
257                                 if (type == WebSocketMessageType.Close) {
258                                         state = WebSocketState.Closed;
259                                         var tmpBuffer = new byte[length];
260                                         connection.Read (req, tmpBuffer, 0, tmpBuffer.Length);
261                                         var closeStatus = (WebSocketCloseStatus)(tmpBuffer[0] << 8 | tmpBuffer[1]);
262                                         var closeDesc = tmpBuffer.Length > 2 ? Encoding.UTF8.GetString (tmpBuffer, 2, tmpBuffer.Length - 2) : string.Empty;
263                                         return new WebSocketReceiveResult ((int)length, type, isLast, closeStatus, closeDesc);
264                                 } else {
265                                         var readLength = (int)(buffer.Count < length ? buffer.Count : length);
266                                         connection.Read (req, buffer.Array, buffer.Offset, readLength);
267
268                                         return new WebSocketReceiveResult ((int)length, type, isLast);
269                                 }
270                         });
271                 }
272
273                 // The damn difference between those two methods is that CloseAsync will wait for server acknowledgement before completing
274                 // while CloseOutputAsync will send the close packet and simply complete.
275
276                 public async override Task CloseAsync (WebSocketCloseStatus closeStatus, string statusDescription, CancellationToken cancellationToken)
277                 {
278                         EnsureWebSocketConnected ();
279                         await SendCloseFrame (closeStatus, statusDescription, cancellationToken).ConfigureAwait (false);
280                         state = WebSocketState.CloseSent;
281                         // TODO: figure what's exceptions are thrown if the server returns something faulty here
282                         await ReceiveAsync (new ArraySegment<byte> (new byte[0]), cancellationToken).ConfigureAwait (false);
283                         state = WebSocketState.Closed;
284                 }
285
286                 public async override Task CloseOutputAsync (WebSocketCloseStatus closeStatus, string statusDescription, CancellationToken cancellationToken)
287                 {
288                         EnsureWebSocketConnected ();
289                         await SendCloseFrame (closeStatus, statusDescription, cancellationToken).ConfigureAwait (false);
290                         state = WebSocketState.CloseSent;
291                 }
292
293                 async Task SendCloseFrame (WebSocketCloseStatus closeStatus, string statusDescription, CancellationToken cancellationToken)
294                 {
295                         var statusDescBuffer = string.IsNullOrEmpty (statusDescription) ? new byte[2] : new byte[2 + Encoding.UTF8.GetByteCount (statusDescription)];
296                         statusDescBuffer[0] = (byte)(((ushort)closeStatus) >> 8);
297                         statusDescBuffer[1] = (byte)(((ushort)closeStatus) & 0xFF);
298                         if (!string.IsNullOrEmpty (statusDescription))
299                                 Encoding.UTF8.GetBytes (statusDescription, 0, statusDescription.Length, statusDescBuffer, 2);
300                         await SendAsync (new ArraySegment<byte> (statusDescBuffer), WebSocketMessageType.Close, true, cancellationToken).ConfigureAwait (false);
301                 }
302
303                 int WriteHeader (WebSocketMessageType type, ArraySegment<byte> buffer, bool endOfMessage)
304                 {
305                         var opCode = MessageTypeToWire (type);
306                         var length = buffer.Count;
307
308                         headerBuffer[0] = (byte)(opCode | (endOfMessage ? 0 : 0x80));
309                         if (length < 126) {
310                                 headerBuffer[1] = (byte)length;
311                         } else if (length <= ushort.MaxValue) {
312                                 headerBuffer[1] = (byte)126;
313                                 headerBuffer[2] = (byte)(length / 256);
314                                 headerBuffer[3] = (byte)(length % 256);
315                         } else {
316                                 headerBuffer[1] = (byte)127;
317
318                                 int left = length;
319                                 int unit = 256;
320
321                                 for (int i = 9; i > 1; i--) {
322                                         headerBuffer[i] = (byte)(left % unit);
323                                         left = left / unit;
324                                 }
325                         }
326
327                         var l = Math.Max (0, headerBuffer[1] - 125);
328                         var maskOffset = 2 + l * l * 2;
329                         GenerateMask (headerBuffer, maskOffset);
330
331                         // Since we are client only, we always mask the payload
332                         headerBuffer[1] |= 0x80;
333
334                         return maskOffset;
335                 }
336
337                 void GenerateMask (byte[] mask, int offset)
338                 {
339                         mask[offset + 0] = (byte)random.Next (0, 255);
340                         mask[offset + 1] = (byte)random.Next (0, 255);
341                         mask[offset + 2] = (byte)random.Next (0, 255);
342                         mask[offset + 3] = (byte)random.Next (0, 255);
343                 }
344
345                 void MaskData (ArraySegment<byte> buffer, int maskOffset)
346                 {
347                         var sendBufferOffset = maskOffset + 4;
348                         for (var i = 0; i < buffer.Count; i++)
349                                 sendBuffer[i + sendBufferOffset] = (byte)(buffer.Array[buffer.Offset + i] ^ headerBuffer[maskOffset + (i % 4)]);
350                 }
351
352                 void EnsureWebSocketConnected ()
353                 {
354                         if (state < WebSocketState.Open)
355                                 throw new InvalidOperationException ("The WebSocket is not connected");
356                 }
357
358                 void EnsureWebSocketState (params WebSocketState[] validStates)
359                 {
360                         foreach (var validState in validStates)
361                                 if (state == validState)
362                                         return;
363                         throw new WebSocketException ("The WebSocket is in an invalid state ('" + state + "') for this operation. Valid states are: " + string.Join (", ", validStates));
364                 }
365
366                 void ValidateArraySegment (ArraySegment<byte> segment)
367                 {
368                         if (segment.Array == null)
369                                 throw new ArgumentNullException ("buffer.Array");
370                         if (segment.Offset < 0)
371                                 throw new ArgumentOutOfRangeException ("buffer.Offset");
372                         if (segment.Offset + segment.Count > segment.Array.Length)
373                                 throw new ArgumentOutOfRangeException ("buffer.Count");
374                 }
375         }
376 }
377
378 #endif