Skip to content
This repository was archived by the owner on Jan 23, 2023. It is now read-only.

Commit 898b984

Browse files
dotnet-botpgavlin
authored andcommitted
Initial commit of System.Net.WebSockets
1 parent 0774384 commit 898b984

18 files changed

+2269
-0
lines changed
Lines changed: 111 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,111 @@
1+
// Copyright (c) Microsoft. All rights reserved.
2+
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
3+
4+
using System.Diagnostics.CodeAnalysis;
5+
using System.Globalization;
6+
using System.IO;
7+
using System.Text;
8+
using System.Threading;
9+
using System.Threading.Tasks;
10+
11+
using Microsoft.Win32;
12+
13+
namespace System.Net.WebSockets
14+
{
15+
internal static class WebSocketValidate
16+
{
17+
internal const int MaxControlFramePayloadLength = 123;
18+
19+
private const int CloseStatusCodeAbort = 1006;
20+
private const int CloseStatusCodeFailedTLSHandshake = 1015;
21+
private const int InvalidCloseStatusCodesFrom = 0;
22+
private const int InvalidCloseStatusCodesTo = 999;
23+
private const string Separators = "()<>@,;:\\\"/[]?={} ";
24+
25+
internal static void ValidateSubprotocol(string subProtocol)
26+
{
27+
if (string.IsNullOrWhiteSpace(subProtocol))
28+
{
29+
throw new ArgumentException(SR.net_WebSockets_InvalidEmptySubProtocol, "subProtocol");
30+
}
31+
32+
string invalidChar = null;
33+
int i = 0;
34+
while (i < subProtocol.Length)
35+
{
36+
char ch = subProtocol[i];
37+
if (ch < 0x21 || ch > 0x7e)
38+
{
39+
invalidChar = string.Format(CultureInfo.InvariantCulture, "[{0}]", (int)ch);
40+
break;
41+
}
42+
43+
if (!char.IsLetterOrDigit(ch) &&
44+
Separators.IndexOf(ch) >= 0)
45+
{
46+
invalidChar = ch.ToString();
47+
break;
48+
}
49+
50+
i++;
51+
}
52+
53+
if (invalidChar != null)
54+
{
55+
throw new ArgumentException(SR.Format(SR.net_WebSockets_InvalidCharInProtocolString, subProtocol, invalidChar),
56+
"subProtocol");
57+
}
58+
}
59+
60+
internal static void ValidateCloseStatus(WebSocketCloseStatus closeStatus, string statusDescription)
61+
{
62+
if (closeStatus == WebSocketCloseStatus.Empty && !string.IsNullOrEmpty(statusDescription))
63+
{
64+
throw new ArgumentException(SR.Format(SR.net_WebSockets_ReasonNotNull,
65+
statusDescription,
66+
WebSocketCloseStatus.Empty),
67+
"statusDescription");
68+
}
69+
70+
int closeStatusCode = (int)closeStatus;
71+
72+
if ((closeStatusCode >= InvalidCloseStatusCodesFrom &&
73+
closeStatusCode <= InvalidCloseStatusCodesTo) ||
74+
closeStatusCode == CloseStatusCodeAbort ||
75+
closeStatusCode == CloseStatusCodeFailedTLSHandshake)
76+
{
77+
// CloseStatus 1006 means Aborted - this will never appear on the wire and is reflected by calling WebSocket.Abort
78+
throw new ArgumentException(SR.Format(SR.net_WebSockets_InvalidCloseStatusCode,
79+
closeStatusCode),
80+
"closeStatus");
81+
}
82+
83+
int length = 0;
84+
if (!string.IsNullOrEmpty(statusDescription))
85+
{
86+
length = Encoding.UTF8.GetByteCount(statusDescription);
87+
}
88+
89+
if (length > WebSocketValidate.MaxControlFramePayloadLength)
90+
{
91+
throw new ArgumentException(SR.Format(SR.net_WebSockets_InvalidCloseStatusDescription,
92+
statusDescription,
93+
WebSocketValidate.MaxControlFramePayloadLength),
94+
"statusDescription");
95+
}
96+
}
97+
98+
internal static void ThrowPlatformNotSupportedException()
99+
{
100+
throw new PlatformNotSupportedException(SR.net_WebSockets_UnsupportedPlatform);
101+
}
102+
103+
internal static void ValidateArraySegment<T>(ArraySegment<T> arraySegment, string parameterName)
104+
{
105+
if (arraySegment.Array == null)
106+
{
107+
throw new ArgumentNullException(parameterName + ".Array");
108+
}
109+
}
110+
}
111+
}
Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
2+
Microsoft Visual Studio Solution File, Format Version 12.00
3+
# Visual Studio 14
4+
VisualStudioVersion = 14.0.22823.1
5+
MinimumVisualStudioVersion = 10.0.40219.1
6+
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "System.Net.WebSockets", "src\System.Net.WebSockets.csproj", "{B0C83201-EC32-4E8D-9DE4-EEF41E052DA1}"
7+
EndProject
8+
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "System.Net.WebSockets.Tests", "tests\System.Net.WebSockets.Tests.csproj", "{7C395A91-D955-444C-98BF-D3F809A56CE1}"
9+
EndProject
10+
Global
11+
GlobalSection(SolutionConfigurationPlatforms) = preSolution
12+
Debug|Any CPU = Debug|Any CPU
13+
Release|Any CPU = Release|Any CPU
14+
EndGlobalSection
15+
GlobalSection(ProjectConfigurationPlatforms) = postSolution
16+
{B0C83201-EC32-4E8D-9DE4-EEF41E052DA1}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
17+
{B0C83201-EC32-4E8D-9DE4-EEF41E052DA1}.Debug|Any CPU.Build.0 = Debug|Any CPU
18+
{B0C83201-EC32-4E8D-9DE4-EEF41E052DA1}.Release|Any CPU.ActiveCfg = Release|Any CPU
19+
{B0C83201-EC32-4E8D-9DE4-EEF41E052DA1}.Release|Any CPU.Build.0 = Release|Any CPU
20+
{7C395A91-D955-444C-98BF-D3F809A56CE1}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
21+
{7C395A91-D955-444C-98BF-D3F809A56CE1}.Debug|Any CPU.Build.0 = Debug|Any CPU
22+
{7C395A91-D955-444C-98BF-D3F809A56CE1}.Release|Any CPU.ActiveCfg = Release|Any CPU
23+
{7C395A91-D955-444C-98BF-D3F809A56CE1}.Release|Any CPU.Build.0 = Release|Any CPU
24+
EndGlobalSection
25+
GlobalSection(SolutionProperties) = preSolution
26+
HideSolutionNode = FALSE
27+
EndGlobalSection
28+
EndGlobal
Lines changed: 150 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,150 @@
1+
<?xml version="1.0" encoding="utf-8"?>
2+
<root>
3+
<!--
4+
Microsoft ResX Schema
5+
6+
Version 2.0
7+
8+
The primary goals of this format is to allow a simple XML format
9+
that is mostly human readable. The generation and parsing of the
10+
various data types are done through the TypeConverter classes
11+
associated with the data types.
12+
13+
Example:
14+
15+
... ado.net/XML headers & schema ...
16+
<resheader name="resmimetype">text/microsoft-resx</resheader>
17+
<resheader name="version">2.0</resheader>
18+
<resheader name="reader">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader>
19+
<resheader name="writer">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader>
20+
<data name="Name1"><value>this is my long string</value><comment>this is a comment</comment></data>
21+
<data name="Color1" type="System.Drawing.Color, System.Drawing">Blue</data>
22+
<data name="Bitmap1" mimetype="application/x-microsoft.net.object.binary.base64">
23+
<value>[base64 mime encoded serialized .NET Framework object]</value>
24+
</data>
25+
<data name="Icon1" type="System.Drawing.Icon, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64">
26+
<value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value>
27+
<comment>This is a comment</comment>
28+
</data>
29+
30+
There are any number of "resheader" rows that contain simple
31+
name/value pairs.
32+
33+
Each data row contains a name, and value. The row also contains a
34+
type or mimetype. Type corresponds to a .NET class that support
35+
text/value conversion through the TypeConverter architecture.
36+
Classes that don't support this are serialized and stored with the
37+
mimetype set.
38+
39+
The mimetype is used for serialized objects, and tells the
40+
ResXResourceReader how to depersist the object. This is currently not
41+
extensible. For a given mimetype the value must be set accordingly:
42+
43+
Note - application/x-microsoft.net.object.binary.base64 is the format
44+
that the ResXResourceWriter will generate, however the reader can
45+
read any of the formats listed below.
46+
47+
mimetype: application/x-microsoft.net.object.binary.base64
48+
value : The object must be serialized with
49+
: System.Runtime.Serialization.Formatters.Binary.BinaryFormatter
50+
: and then encoded with base64 encoding.
51+
52+
mimetype: application/x-microsoft.net.object.soap.base64
53+
value : The object must be serialized with
54+
: System.Runtime.Serialization.Formatters.Soap.SoapFormatter
55+
: and then encoded with base64 encoding.
56+
57+
mimetype: application/x-microsoft.net.object.bytearray.base64
58+
value : The object must be serialized into a byte array
59+
: using a System.ComponentModel.TypeConverter
60+
: and then encoded with base64 encoding.
61+
-->
62+
<xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
63+
<xsd:import namespace="http://www.w3.org/XML/1998/namespace" />
64+
<xsd:element name="root" msdata:IsDataSet="true">
65+
<xsd:complexType>
66+
<xsd:choice maxOccurs="unbounded">
67+
<xsd:element name="metadata">
68+
<xsd:complexType>
69+
<xsd:sequence>
70+
<xsd:element name="value" type="xsd:string" minOccurs="0" />
71+
</xsd:sequence>
72+
<xsd:attribute name="name" use="required" type="xsd:string" />
73+
<xsd:attribute name="type" type="xsd:string" />
74+
<xsd:attribute name="mimetype" type="xsd:string" />
75+
<xsd:attribute ref="xml:space" />
76+
</xsd:complexType>
77+
</xsd:element>
78+
<xsd:element name="assembly">
79+
<xsd:complexType>
80+
<xsd:attribute name="alias" type="xsd:string" />
81+
<xsd:attribute name="name" type="xsd:string" />
82+
</xsd:complexType>
83+
</xsd:element>
84+
<xsd:element name="data">
85+
<xsd:complexType>
86+
<xsd:sequence>
87+
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
88+
<xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" />
89+
</xsd:sequence>
90+
<xsd:attribute name="name" type="xsd:string" use="required" msdata:Ordinal="1" />
91+
<xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" />
92+
<xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" />
93+
<xsd:attribute ref="xml:space" />
94+
</xsd:complexType>
95+
</xsd:element>
96+
<xsd:element name="resheader">
97+
<xsd:complexType>
98+
<xsd:sequence>
99+
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
100+
</xsd:sequence>
101+
<xsd:attribute name="name" type="xsd:string" use="required" />
102+
</xsd:complexType>
103+
</xsd:element>
104+
</xsd:choice>
105+
</xsd:complexType>
106+
</xsd:element>
107+
</xsd:schema>
108+
<resheader name="resmimetype">
109+
<value>text/microsoft-resx</value>
110+
</resheader>
111+
<resheader name="version">
112+
<value>2.0</value>
113+
</resheader>
114+
<resheader name="reader">
115+
<value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
116+
</resheader>
117+
<resheader name="writer">
118+
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
119+
</resheader>
120+
<data name="net_WebSockets_InvalidState" xml:space="preserve">
121+
<value>The WebSocket is in an invalid state ('{0}') for this operation. Valid states are: '{1}'</value>
122+
</data>
123+
<data name="net_WebSockets_Generic" xml:space="preserve">
124+
<value>An internal WebSocket error occurred. Please see the innerException, if present, for more details. </value>
125+
</data>
126+
<data name="net_WebSockets_InvalidMessageType_Generic" xml:space="preserve">
127+
<value>The received message type is invalid after calling {0}. {0} should only be used if no more data is expected from the remote endpoint. Use '{1}' instead to keep being able to receive data but close the output channel.</value>
128+
</data>
129+
<data name="net_Websockets_WebSocketBaseFaulted" xml:space="preserve">
130+
<value>An exception caused the WebSocket to enter the Aborted state. Please see the InnerException, if present, for more details.</value>
131+
</data>
132+
<data name="net_WebSockets_NotAWebSocket_Generic" xml:space="preserve">
133+
<value>A WebSocket operation was called on a request or response that is not a WebSocket.</value>
134+
</data>
135+
<data name="net_WebSockets_UnsupportedWebSocketVersion_Generic" xml:space="preserve">
136+
<value>Unsupported WebSocket version.</value>
137+
</data>
138+
<data name="net_WebSockets_UnsupportedProtocol_Generic" xml:space="preserve">
139+
<value>The WebSocket request or response operation was called with unsupported protocol(s). </value>
140+
</data>
141+
<data name="net_WebSockets_HeaderError_Generic" xml:space="preserve">
142+
<value>The WebSocket request or response contained unsupported header(s). </value>
143+
</data>
144+
<data name="net_WebSockets_ConnectionClosedPrematurely_Generic" xml:space="preserve">
145+
<value>The remote party closed the WebSocket connection without completing the close handshake.</value>
146+
</data>
147+
<data name="net_WebSockets_InvalidState_Generic" xml:space="preserve">
148+
<value>The WebSocket instance cannot be used for communication because it has been transitioned into an invalid state.</value>
149+
</data>
150+
</root>
Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
<?xml version="1.0" encoding="utf-8"?>
2+
<Project ToolsVersion="12.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003" DefaultTargets="Build">
3+
<Import Project="$([MSBuild]::GetDirectoryNameOfFileAbove($(MSBuildThisFileDirectory), dir.props))\dir.props" />
4+
<PropertyGroup>
5+
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
6+
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
7+
<ProjectGuid>{B0C83201-EC32-4E8D-9DE4-EEF41E052DA1}</ProjectGuid>
8+
<OutputType>Library</OutputType>
9+
</PropertyGroup>
10+
11+
<!-- Help VS understand available configurations -->
12+
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' " />
13+
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' " />
14+
15+
<ItemGroup>
16+
<Compile Include="System\Net\WebSockets\WebSocket.cs" />
17+
<Compile Include="System\Net\WebSockets\WebSocketCloseStatus.cs" />
18+
<Compile Include="System\Net\WebSockets\WebSocketError.cs" />
19+
<Compile Include="System\Net\WebSockets\WebSocketException.cs" />
20+
<Compile Include="System\Net\WebSockets\WebSocketMessageType.cs" />
21+
<Compile Include="System\Net\WebSockets\WebSocketReceiveResult.cs" />
22+
<Compile Include="System\Net\WebSockets\WebSocketState.cs" />
23+
</ItemGroup>
24+
25+
<ItemGroup>
26+
<None Include="project.json" />
27+
</ItemGroup>
28+
<Import Project="$([MSBuild]::GetDirectoryNameOfFileAbove($(MSBuildThisFileDirectory), dir.targets))\dir.targets" />
29+
</Project>
Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
// Copyright (c) Microsoft. All rights reserved.
2+
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
3+
4+
using System;
5+
using System.IO;
6+
using System.Net;
7+
using System.Threading;
8+
using System.Threading.Tasks;
9+
10+
namespace System.Net.WebSockets
11+
{
12+
public abstract class WebSocket : IDisposable
13+
{
14+
public abstract WebSocketCloseStatus? CloseStatus { get; }
15+
public abstract string CloseStatusDescription { get; }
16+
public abstract string SubProtocol { get; }
17+
public abstract WebSocketState State { get; }
18+
19+
public abstract void Abort();
20+
public abstract Task CloseAsync(WebSocketCloseStatus closeStatus,
21+
string statusDescription,
22+
CancellationToken cancellationToken);
23+
public abstract Task CloseOutputAsync(WebSocketCloseStatus closeStatus,
24+
string statusDescription,
25+
CancellationToken cancellationToken);
26+
public abstract void Dispose();
27+
public abstract Task<WebSocketReceiveResult> ReceiveAsync(ArraySegment<byte> buffer,
28+
CancellationToken cancellationToken);
29+
public abstract Task SendAsync(ArraySegment<byte> buffer,
30+
WebSocketMessageType messageType,
31+
bool endOfMessage,
32+
CancellationToken cancellationToken);
33+
}
34+
}
Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
// Copyright (c) Microsoft. All rights reserved.
2+
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
3+
4+
using System.Diagnostics.CodeAnalysis;
5+
6+
namespace System.Net.WebSockets
7+
{
8+
[SuppressMessage("Microsoft.Design",
9+
"CA1008:EnumsShouldHaveZeroValue",
10+
Justification = "This enum is reflecting the IETF's WebSocket specification. " +
11+
"'0' is a disallowed value for the close status code")]
12+
public enum WebSocketCloseStatus
13+
{
14+
NormalClosure = 1000,
15+
EndpointUnavailable = 1001,
16+
ProtocolError = 1002,
17+
InvalidMessageType = 1003,
18+
Empty = 1005,
19+
// AbnormalClosure = 1006, // 1006 is reserved and should never be used by user
20+
InvalidPayloadData = 1007,
21+
PolicyViolation = 1008,
22+
MessageTooBig = 1009,
23+
MandatoryExtension = 1010,
24+
InternalServerError = 1011
25+
// TLSHandshakeFailed = 1015, // 1015 is reserved and should never be used by user
26+
27+
// 0 - 999 Status codes in the range 0-999 are not used.
28+
// 1000 - 1999 Status codes in the range 1000-1999 are reserved for definition by this protocol.
29+
// 2000 - 2999 Status codes in the range 2000-2999 are reserved for use by extensions.
30+
// 3000 - 3999 Status codes in the range 3000-3999 MAY be used by libraries and frameworks. The
31+
// interpretation of these codes is undefined by this protocol. End applications MUST
32+
// NOT use status codes in this range.
33+
// 4000 - 4999 Status codes in the range 4000-4999 MAY be used by application code. The interpretaion
34+
// of these codes is undefined by this protocol.
35+
}
36+
}

0 commit comments

Comments
 (0)