ADD : 스트림덱 플러그인 추가 업데이트 아이템 + 카메라 기능

This commit is contained in:
KINDNICK 2025-07-07 04:26:38 +09:00
parent 9f1af458fc
commit 8b6a06e90f
435 changed files with 56906 additions and 1392 deletions

8
Assets/External/websocket-sharp.meta vendored Normal file
View File

@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: 0b3c479ab08f10f42aaa9bcbad102a3a
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:

View File

@ -0,0 +1,26 @@
using System.Reflection;
using System.Runtime.CompilerServices;
// Information about this assembly is defined by the following attributes.
// Change them to the values specific to your project.
[assembly: AssemblyTitle("websocket-sharp")]
[assembly: AssemblyDescription("A C# implementation of the WebSocket protocol client and server")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("websocket-sharp.dll")]
[assembly: AssemblyCopyright("sta.blockhead")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// The assembly version has the format "{Major}.{Minor}.{Build}.{Revision}".
// The form "{Major}.{Minor}.*" will automatically update the build and revision,
// and "{Major}.{Minor}.{Build}.*" will update just the revision.
[assembly: AssemblyVersion("1.0.2.0")]
// The following attributes are used to specify the signing key for the assembly,
// if desired. See the Mono documentation for more information about signing.
//[assembly: AssemblyDelaySign(false)]
//[assembly: AssemblyKeyFile("")]

View File

@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: 39fd29427d0e18849a32d93c78615e9f

View File

@ -0,0 +1,47 @@
#region License
/*
* ByteOrder.cs
*
* The MIT License
*
* Copyright (c) 2012-2015 sta.blockhead
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
#endregion
using System;
namespace WebSocketSharp
{
/// <summary>
/// Specifies the byte order.
/// </summary>
public enum ByteOrder
{
/// <summary>
/// Specifies Little-endian.
/// </summary>
Little,
/// <summary>
/// Specifies Big-endian.
/// </summary>
Big
}
}

View File

@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: 87c28a16b5a541a46b5c738f453e85ea

View File

@ -0,0 +1,118 @@
#region License
/*
* CloseEventArgs.cs
*
* The MIT License
*
* Copyright (c) 2012-2024 sta.blockhead
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
#endregion
using System;
namespace WebSocketSharp
{
/// <summary>
/// Represents the event data for the <see cref="WebSocket.OnClose"/> event.
/// </summary>
/// <remarks>
/// <para>
/// The close event occurs when the WebSocket connection has been closed.
/// </para>
/// <para>
/// If you would like to get the reason for the connection close,
/// you should access the <see cref="Code"/> or <see cref="Reason"/>
/// property.
/// </para>
/// </remarks>
public class CloseEventArgs : EventArgs
{
#region Private Fields
private PayloadData _payloadData;
private bool _wasClean;
#endregion
#region Internal Constructors
internal CloseEventArgs (PayloadData payloadData, bool clean)
{
_payloadData = payloadData;
_wasClean = clean;
}
#endregion
#region Public Properties
/// <summary>
/// Gets the status code for the connection close.
/// </summary>
/// <value>
/// <para>
/// A <see cref="ushort"/> that represents the status code for
/// the connection close.
/// </para>
/// <para>
/// 1005 (no status) if not present.
/// </para>
/// </value>
public ushort Code {
get {
return _payloadData.Code;
}
}
/// <summary>
/// Gets the reason for the connection close.
/// </summary>
/// <value>
/// <para>
/// A <see cref="string"/> that represents the reason for
/// the connection close.
/// </para>
/// <para>
/// An empty string if not present.
/// </para>
/// </value>
public string Reason {
get {
return _payloadData.Reason;
}
}
/// <summary>
/// Gets a value indicating whether the connection has been closed cleanly.
/// </summary>
/// <value>
/// <c>true</c> if the connection has been closed cleanly; otherwise,
/// <c>false</c>.
/// </value>
public bool WasClean {
get {
return _wasClean;
}
}
#endregion
}
}

View File

@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: 1d2b6502961bce247ab494e4a6d127c2

View File

@ -0,0 +1,120 @@
#region License
/*
* CloseStatusCode.cs
*
* The MIT License
*
* Copyright (c) 2012-2016 sta.blockhead
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
#endregion
using System;
namespace WebSocketSharp
{
/// <summary>
/// Indicates the status code for the WebSocket connection close.
/// </summary>
/// <remarks>
/// <para>
/// The values of this enumeration are defined in
/// <see href="http://tools.ietf.org/html/rfc6455#section-7.4">
/// Section 7.4</see> of RFC 6455.
/// </para>
/// <para>
/// "Reserved value" cannot be sent as a status code in
/// closing handshake by an endpoint.
/// </para>
/// </remarks>
public enum CloseStatusCode : ushort
{
/// <summary>
/// Equivalent to close status 1000. Indicates normal close.
/// </summary>
Normal = 1000,
/// <summary>
/// Equivalent to close status 1001. Indicates that an endpoint is
/// going away.
/// </summary>
Away = 1001,
/// <summary>
/// Equivalent to close status 1002. Indicates that an endpoint is
/// terminating the connection due to a protocol error.
/// </summary>
ProtocolError = 1002,
/// <summary>
/// Equivalent to close status 1003. Indicates that an endpoint is
/// terminating the connection because it has received a type of
/// data that it cannot accept.
/// </summary>
UnsupportedData = 1003,
/// <summary>
/// Equivalent to close status 1004. Still undefined. A Reserved value.
/// </summary>
Undefined = 1004,
/// <summary>
/// Equivalent to close status 1005. Indicates that no status code was
/// actually present. A Reserved value.
/// </summary>
NoStatus = 1005,
/// <summary>
/// Equivalent to close status 1006. Indicates that the connection was
/// closed abnormally. A Reserved value.
/// </summary>
Abnormal = 1006,
/// <summary>
/// Equivalent to close status 1007. Indicates that an endpoint is
/// terminating the connection because it has received a message that
/// contains data that is not consistent with the type of the message.
/// </summary>
InvalidData = 1007,
/// <summary>
/// Equivalent to close status 1008. Indicates that an endpoint is
/// terminating the connection because it has received a message that
/// violates its policy.
/// </summary>
PolicyViolation = 1008,
/// <summary>
/// Equivalent to close status 1009. Indicates that an endpoint is
/// terminating the connection because it has received a message that
/// is too big to process.
/// </summary>
TooBig = 1009,
/// <summary>
/// Equivalent to close status 1010. Indicates that a client is
/// terminating the connection because it has expected the server to
/// negotiate one or more extension, but the server did not return
/// them in the handshake response.
/// </summary>
MandatoryExtension = 1010,
/// <summary>
/// Equivalent to close status 1011. Indicates that a server is
/// terminating the connection because it has encountered an unexpected
/// condition that prevented it from fulfilling the request.
/// </summary>
ServerError = 1011,
/// <summary>
/// Equivalent to close status 1015. Indicates that the connection was
/// closed due to a failure to perform a TLS handshake. A Reserved value.
/// </summary>
TlsHandshakeFailure = 1015
}
}

View File

@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: e8dc83dc35b69e140853c4e18b52b4a8

View File

@ -0,0 +1,52 @@
#region License
/*
* CompressionMethod.cs
*
* The MIT License
*
* Copyright (c) 2013-2017 sta.blockhead
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
#endregion
using System;
namespace WebSocketSharp
{
/// <summary>
/// Specifies the method for compression.
/// </summary>
/// <remarks>
/// The methods are defined in
/// <see href="https://tools.ietf.org/html/rfc7692">
/// Compression Extensions for WebSocket</see>.
/// </remarks>
public enum CompressionMethod : byte
{
/// <summary>
/// Specifies no compression.
/// </summary>
None,
/// <summary>
/// Specifies DEFLATE.
/// </summary>
Deflate
}
}

View File

@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: f388d1e288415ad45b4bf734a6232341

View File

@ -0,0 +1,115 @@
#region License
/*
* ErrorEventArgs.cs
*
* The MIT License
*
* Copyright (c) 2012-2022 sta.blockhead
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
#endregion
#region Contributors
/*
* Contributors:
* - Frank Razenberg <frank@zzattack.org>
*/
#endregion
using System;
namespace WebSocketSharp
{
/// <summary>
/// Represents the event data for the <see cref="WebSocket.OnError"/> event.
/// </summary>
/// <remarks>
/// <para>
/// The error event occurs when the <see cref="WebSocket"/> interface
/// gets an error.
/// </para>
/// <para>
/// If you would like to get the error message, you should access
/// the <see cref="ErrorEventArgs.Message"/> property.
/// </para>
/// <para>
/// If the error is due to an exception, you can get it by accessing
/// the <see cref="ErrorEventArgs.Exception"/> property.
/// </para>
/// </remarks>
public class ErrorEventArgs : EventArgs
{
#region Private Fields
private Exception _exception;
private string _message;
#endregion
#region Internal Constructors
internal ErrorEventArgs (string message)
: this (message, null)
{
}
internal ErrorEventArgs (string message, Exception exception)
{
_message = message;
_exception = exception;
}
#endregion
#region Public Properties
/// <summary>
/// Gets the exception that caused the error.
/// </summary>
/// <value>
/// <para>
/// An <see cref="System.Exception"/> instance that represents
/// the cause of the error.
/// </para>
/// <para>
/// <see langword="null"/> if not present.
/// </para>
/// </value>
public Exception Exception {
get {
return _exception;
}
}
/// <summary>
/// Gets the error message.
/// </summary>
/// <value>
/// A <see cref="string"/> that represents the error message.
/// </value>
public string Message {
get {
return _message;
}
}
#endregion
}
}

View File

@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: 58b5642169f4cce4d8717bd4c8070768

1902
Assets/External/websocket-sharp/Ext.cs vendored Normal file

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: 6c78a6051f0f6ab44806b2b480347ea4

52
Assets/External/websocket-sharp/Fin.cs vendored Normal file
View File

@ -0,0 +1,52 @@
#region License
/*
* Fin.cs
*
* The MIT License
*
* Copyright (c) 2012-2025 sta.blockhead
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
#endregion
using System;
namespace WebSocketSharp
{
/// <summary>
/// Indicates whether a WebSocket frame is the final frame of a message.
/// </summary>
/// <remarks>
/// The values of this enumeration are defined in
/// <see href="http://tools.ietf.org/html/rfc6455#section-5.2">
/// Section 5.2</see> of RFC 6455.
/// </remarks>
internal enum Fin
{
/// <summary>
/// Equivalent to numeric value 0. Indicates more frames of a message follow.
/// </summary>
More = 0x0,
/// <summary>
/// Equivalent to numeric value 1. Indicates the final frame of a message.
/// </summary>
Final = 0x1
}
}

View File

@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: 8581c072d74d61c469dc413061917da4

View File

@ -0,0 +1,317 @@
#region License
/*
* HttpBase.cs
*
* The MIT License
*
* Copyright (c) 2012-2024 sta.blockhead
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
#endregion
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using WebSocketSharp.Net;
namespace WebSocketSharp
{
internal abstract class HttpBase
{
#region Private Fields
private NameValueCollection _headers;
private static readonly int _maxMessageHeaderLength;
private string _messageBody;
private byte[] _messageBodyData;
private Version _version;
#endregion
#region Protected Fields
protected static readonly string CrLf;
protected static readonly string CrLfHt;
protected static readonly string CrLfSp;
#endregion
#region Static Constructor
static HttpBase ()
{
_maxMessageHeaderLength = 8192;
CrLf = "\r\n";
CrLfHt = "\r\n\t";
CrLfSp = "\r\n ";
}
#endregion
#region Protected Constructors
protected HttpBase (Version version, NameValueCollection headers)
{
_version = version;
_headers = headers;
}
#endregion
#region Internal Properties
internal byte[] MessageBodyData {
get {
return _messageBodyData;
}
}
#endregion
#region Protected Properties
protected string HeaderSection {
get {
var buff = new StringBuilder (64);
var fmt = "{0}: {1}{2}";
foreach (var key in _headers.AllKeys)
buff.AppendFormat (fmt, key, _headers[key], CrLf);
buff.Append (CrLf);
return buff.ToString ();
}
}
#endregion
#region Public Properties
public bool HasMessageBody {
get {
return _messageBodyData != null;
}
}
public NameValueCollection Headers {
get {
return _headers;
}
}
public string MessageBody {
get {
if (_messageBody == null)
_messageBody = getMessageBody ();
return _messageBody;
}
}
public abstract string MessageHeader { get; }
public Version ProtocolVersion {
get {
return _version;
}
}
#endregion
#region Private Methods
private string getMessageBody ()
{
if (_messageBodyData == null || _messageBodyData.LongLength == 0)
return String.Empty;
var contentType = _headers["Content-Type"];
var enc = contentType != null && contentType.Length > 0
? HttpUtility.GetEncoding (contentType)
: Encoding.UTF8;
return enc.GetString (_messageBodyData);
}
private static byte[] readMessageBodyFrom (Stream stream, string length)
{
long len;
if (!Int64.TryParse (length, out len)) {
var msg = "It could not be parsed.";
throw new ArgumentException (msg, "length");
}
if (len < 0) {
var msg = "Less than zero.";
throw new ArgumentOutOfRangeException ("length", msg);
}
return len > 1024
? stream.ReadBytes (len, 1024)
: len > 0
? stream.ReadBytes ((int) len)
: null;
}
private static string[] readMessageHeaderFrom (Stream stream)
{
var buff = new List<byte> ();
var cnt = 0;
Action<int> add =
i => {
if (i == -1) {
var msg = "The header could not be read from the data stream.";
throw new EndOfStreamException (msg);
}
buff.Add ((byte) i);
cnt++;
};
var end = false;
do {
end = stream.ReadByte ().IsEqualTo ('\r', add)
&& stream.ReadByte ().IsEqualTo ('\n', add)
&& stream.ReadByte ().IsEqualTo ('\r', add)
&& stream.ReadByte ().IsEqualTo ('\n', add);
if (cnt > _maxMessageHeaderLength) {
var msg = "The length of the header is greater than the max length.";
throw new InvalidOperationException (msg);
}
}
while (!end);
var bytes = buff.ToArray ();
return Encoding.UTF8.GetString (bytes)
.Replace (CrLfSp, " ")
.Replace (CrLfHt, " ")
.Split (new[] { CrLf }, StringSplitOptions.RemoveEmptyEntries);
}
#endregion
#region Internal Methods
internal void WriteTo (Stream stream)
{
var bytes = ToByteArray ();
stream.Write (bytes, 0, bytes.Length);
}
#endregion
#region Protected Methods
protected static T Read<T> (
Stream stream,
Func<string[], T> parser,
int millisecondsTimeout
)
where T : HttpBase
{
T ret = null;
var timeout = false;
var timer = new Timer (
state => {
timeout = true;
stream.Close ();
},
null,
millisecondsTimeout,
-1
);
Exception exception = null;
try {
var header = readMessageHeaderFrom (stream);
ret = parser (header);
var contentLen = ret.Headers["Content-Length"];
if (contentLen != null && contentLen.Length > 0)
ret._messageBodyData = readMessageBodyFrom (stream, contentLen);
}
catch (Exception ex) {
exception = ex;
}
finally {
timer.Change (-1, -1);
timer.Dispose ();
}
if (timeout) {
var msg = "A timeout has occurred.";
throw new WebSocketException (msg);
}
if (exception != null) {
var msg = "An exception has occurred.";
throw new WebSocketException (msg, exception);
}
return ret;
}
#endregion
#region Public Methods
public byte[] ToByteArray ()
{
var headerData = Encoding.UTF8.GetBytes (MessageHeader);
return _messageBodyData != null
? headerData.Concat (_messageBodyData).ToArray ()
: headerData;
}
public override string ToString ()
{
return _messageBodyData != null
? MessageHeader + MessageBody
: MessageHeader;
}
#endregion
}
}

View File

@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: 01336e40da8ed304fa4f40db4660af86

View File

@ -0,0 +1,253 @@
#region License
/*
* HttpRequest.cs
*
* The MIT License
*
* Copyright (c) 2012-2024 sta.blockhead
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
#endregion
#region Contributors
/*
* Contributors:
* - David Burhans
*/
#endregion
using System;
using System.Collections.Specialized;
using System.IO;
using System.Text;
using WebSocketSharp.Net;
namespace WebSocketSharp
{
internal class HttpRequest : HttpBase
{
#region Private Fields
private CookieCollection _cookies;
private string _method;
private string _target;
#endregion
#region Private Constructors
private HttpRequest (
string method,
string target,
Version version,
NameValueCollection headers
)
: base (version, headers)
{
_method = method;
_target = target;
}
#endregion
#region Internal Constructors
internal HttpRequest (string method, string target)
: this (method, target, HttpVersion.Version11, new NameValueCollection ())
{
Headers["User-Agent"] = "websocket-sharp/1.0";
}
#endregion
#region Internal Properties
internal string RequestLine {
get {
var fmt = "{0} {1} HTTP/{2}{3}";
return String.Format (fmt, _method, _target, ProtocolVersion, CrLf);
}
}
#endregion
#region Public Properties
public AuthenticationResponse AuthenticationResponse {
get {
var val = Headers["Authorization"];
return val != null && val.Length > 0
? AuthenticationResponse.Parse (val)
: null;
}
}
public CookieCollection Cookies {
get {
if (_cookies == null)
_cookies = Headers.GetCookies (false);
return _cookies;
}
}
public string HttpMethod {
get {
return _method;
}
}
public bool IsWebSocketRequest {
get {
return _method == "GET"
&& ProtocolVersion > HttpVersion.Version10
&& Headers.Upgrades ("websocket");
}
}
public override string MessageHeader {
get {
return RequestLine + HeaderSection;
}
}
public string RequestTarget {
get {
return _target;
}
}
#endregion
#region Internal Methods
internal static HttpRequest CreateConnectRequest (Uri targetUri)
{
var fmt = "{0}:{1}";
var host = targetUri.DnsSafeHost;
var port = targetUri.Port;
var authority = String.Format (fmt, host, port);
var ret = new HttpRequest ("CONNECT", authority);
ret.Headers["Host"] = port != 80 ? authority : host;
return ret;
}
internal static HttpRequest CreateWebSocketHandshakeRequest (Uri targetUri)
{
var ret = new HttpRequest ("GET", targetUri.PathAndQuery);
var headers = ret.Headers;
var port = targetUri.Port;
var schm = targetUri.Scheme;
var isDefaultPort = (port == 80 && schm == "ws")
|| (port == 443 && schm == "wss");
headers["Host"] = !isDefaultPort
? targetUri.Authority
: targetUri.DnsSafeHost;
headers["Upgrade"] = "websocket";
headers["Connection"] = "Upgrade";
return ret;
}
internal HttpResponse GetResponse (Stream stream, int millisecondsTimeout)
{
WriteTo (stream);
return HttpResponse.ReadResponse (stream, millisecondsTimeout);
}
internal static HttpRequest Parse (string[] messageHeader)
{
var len = messageHeader.Length;
if (len == 0) {
var msg = "An empty request header.";
throw new ArgumentException (msg);
}
var rlParts = messageHeader[0].Split (new[] { ' ' }, 3);
if (rlParts.Length != 3) {
var msg = "It includes an invalid request line.";
throw new ArgumentException (msg);
}
var method = rlParts[0];
var target = rlParts[1];
var ver = rlParts[2].Substring (5).ToVersion ();
var headers = new WebHeaderCollection ();
for (var i = 1; i < len; i++)
headers.InternalSet (messageHeader[i], false);
return new HttpRequest (method, target, ver, headers);
}
internal static HttpRequest ReadRequest (
Stream stream,
int millisecondsTimeout
)
{
return Read<HttpRequest> (stream, Parse, millisecondsTimeout);
}
#endregion
#region Public Methods
public void SetCookies (CookieCollection cookies)
{
if (cookies == null || cookies.Count == 0)
return;
var buff = new StringBuilder (64);
foreach (var cookie in cookies.Sorted) {
if (cookie.Expired)
continue;
buff.AppendFormat ("{0}; ", cookie);
}
var len = buff.Length;
if (len <= 2)
return;
buff.Length = len - 2;
Headers["Cookie"] = buff.ToString ();
}
#endregion
}
}

View File

@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: f38d7bd29af589740a8ee756fd3dce99

View File

@ -0,0 +1,274 @@
#region License
/*
* HttpResponse.cs
*
* The MIT License
*
* Copyright (c) 2012-2024 sta.blockhead
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
#endregion
using System;
using System.Collections.Specialized;
using System.IO;
using System.Text;
using WebSocketSharp.Net;
namespace WebSocketSharp
{
internal class HttpResponse : HttpBase
{
#region Private Fields
private int _code;
private string _reason;
#endregion
#region Private Constructors
private HttpResponse (
int code,
string reason,
Version version,
NameValueCollection headers
)
: base (version, headers)
{
_code = code;
_reason = reason;
}
#endregion
#region Internal Constructors
internal HttpResponse (int code)
: this (code, code.GetStatusDescription ())
{
}
internal HttpResponse (HttpStatusCode code)
: this ((int) code)
{
}
internal HttpResponse (int code, string reason)
: this (
code,
reason,
HttpVersion.Version11,
new NameValueCollection ()
)
{
Headers["Server"] = "websocket-sharp/1.0";
}
internal HttpResponse (HttpStatusCode code, string reason)
: this ((int) code, reason)
{
}
#endregion
#region Internal Properties
internal string StatusLine {
get {
return _reason != null
? String.Format (
"HTTP/{0} {1} {2}{3}",
ProtocolVersion,
_code,
_reason,
CrLf
)
: String.Format (
"HTTP/{0} {1}{2}",
ProtocolVersion,
_code,
CrLf
);
}
}
#endregion
#region Public Properties
public bool CloseConnection {
get {
var compType = StringComparison.OrdinalIgnoreCase;
return Headers.Contains ("Connection", "close", compType);
}
}
public CookieCollection Cookies {
get {
return Headers.GetCookies (true);
}
}
public bool IsProxyAuthenticationRequired {
get {
return _code == 407;
}
}
public bool IsRedirect {
get {
return _code == 301 || _code == 302;
}
}
public bool IsSuccess {
get {
return _code >= 200 && _code <= 299;
}
}
public bool IsUnauthorized {
get {
return _code == 401;
}
}
public bool IsWebSocketResponse {
get {
return ProtocolVersion > HttpVersion.Version10
&& _code == 101
&& Headers.Upgrades ("websocket");
}
}
public override string MessageHeader {
get {
return StatusLine + HeaderSection;
}
}
public string Reason {
get {
return _reason;
}
}
public int StatusCode {
get {
return _code;
}
}
#endregion
#region Internal Methods
internal static HttpResponse CreateCloseResponse (HttpStatusCode code)
{
var ret = new HttpResponse (code);
ret.Headers["Connection"] = "close";
return ret;
}
internal static HttpResponse CreateUnauthorizedResponse (string challenge)
{
var ret = new HttpResponse (HttpStatusCode.Unauthorized);
ret.Headers["WWW-Authenticate"] = challenge;
return ret;
}
internal static HttpResponse CreateWebSocketHandshakeResponse ()
{
var ret = new HttpResponse (HttpStatusCode.SwitchingProtocols);
var headers = ret.Headers;
headers["Upgrade"] = "websocket";
headers["Connection"] = "Upgrade";
return ret;
}
internal static HttpResponse Parse (string[] messageHeader)
{
var len = messageHeader.Length;
if (len == 0) {
var msg = "An empty response header.";
throw new ArgumentException (msg);
}
var slParts = messageHeader[0].Split (new[] { ' ' }, 3);
var plen = slParts.Length;
if (plen < 2) {
var msg = "It includes an invalid status line.";
throw new ArgumentException (msg);
}
var code = slParts[1].ToInt32 ();
var reason = plen == 3 ? slParts[2] : null;
var ver = slParts[0].Substring (5).ToVersion ();
var headers = new WebHeaderCollection ();
for (var i = 1; i < len; i++)
headers.InternalSet (messageHeader[i], true);
return new HttpResponse (code, reason, ver, headers);
}
internal static HttpResponse ReadResponse (
Stream stream,
int millisecondsTimeout
)
{
return Read<HttpResponse> (stream, Parse, millisecondsTimeout);
}
#endregion
#region Public Methods
public void SetCookies (CookieCollection cookies)
{
if (cookies == null || cookies.Count == 0)
return;
var headers = Headers;
foreach (var cookie in cookies.Sorted) {
var val = cookie.ToResponseString ();
headers.Add ("Set-Cookie", val);
}
}
#endregion
}
}

View File

@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: f3f90e85d078fa341af27ca4d173c389

View File

@ -0,0 +1,159 @@
#region License
/*
* LogData.cs
*
* The MIT License
*
* Copyright (c) 2013-2024 sta.blockhead
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
#endregion
using System;
using System.Diagnostics;
using System.Text;
namespace WebSocketSharp
{
/// <summary>
/// Represents a log data used by the <see cref="Logger"/> class.
/// </summary>
public class LogData
{
#region Private Fields
private StackFrame _caller;
private DateTime _date;
private LogLevel _level;
private string _message;
#endregion
#region Internal Constructors
internal LogData (LogLevel level, StackFrame caller, string message)
{
_level = level;
_caller = caller;
_message = message ?? String.Empty;
_date = DateTime.Now;
}
#endregion
#region Public Properties
/// <summary>
/// Gets the information of the logging method caller.
/// </summary>
/// <value>
/// A <see cref="StackFrame"/> that provides the information of
/// the logging method caller.
/// </value>
public StackFrame Caller {
get {
return _caller;
}
}
/// <summary>
/// Gets the date and time when the log data was created.
/// </summary>
/// <value>
/// A <see cref="DateTime"/> that represents the date and time when
/// the log data was created.
/// </value>
public DateTime Date {
get {
return _date;
}
}
/// <summary>
/// Gets the logging level of the log data.
/// </summary>
/// <value>
/// <para>
/// One of the <see cref="LogLevel"/> enum values.
/// </para>
/// <para>
/// It represents the logging level of the log data.
/// </para>
/// </value>
public LogLevel Level {
get {
return _level;
}
}
/// <summary>
/// Gets the message of the log data.
/// </summary>
/// <value>
/// A <see cref="string"/> that represents the message of the log data.
/// </value>
public string Message {
get {
return _message;
}
}
#endregion
#region Public Methods
/// <summary>
/// Returns a string that represents the current instance.
/// </summary>
/// <returns>
/// A <see cref="string"/> that represents the current instance.
/// </returns>
public override string ToString ()
{
var date = String.Format ("[{0}]", _date);
var level = String.Format ("{0,-5}", _level.ToString ().ToUpper ());
var method = _caller.GetMethod ();
var type = method.DeclaringType;
#if DEBUG
var num = _caller.GetFileLineNumber ();
var caller = String.Format ("{0}.{1}:{2}", type.Name, method.Name, num);
#else
var caller = String.Format ("{0}.{1}", type.Name, method.Name);
#endif
var msgs = _message.Replace ("\r\n", "\n").TrimEnd ('\n').Split ('\n');
if (msgs.Length <= 1)
return String.Format ("{0} {1} {2} {3}", date, level, caller, _message);
var buff = new StringBuilder (64);
buff.AppendFormat ("{0} {1} {2}\n\n", date, level, caller);
foreach (var msg in msgs)
buff.AppendFormat (" {0}\n", msg);
return buff.ToString ();
}
#endregion
}
}

View File

@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: 7baa1e0e1d5589a4cb5d7990896ccf5e

View File

@ -0,0 +1,67 @@
#region License
/*
* LogLevel.cs
*
* The MIT License
*
* Copyright (c) 2013-2022 sta.blockhead
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
#endregion
using System;
namespace WebSocketSharp
{
/// <summary>
/// Specifies the logging level.
/// </summary>
public enum LogLevel
{
/// <summary>
/// Specifies the bottom logging level.
/// </summary>
Trace,
/// <summary>
/// Specifies the 2nd logging level from the bottom.
/// </summary>
Debug,
/// <summary>
/// Specifies the 3rd logging level from the bottom.
/// </summary>
Info,
/// <summary>
/// Specifies the 3rd logging level from the top.
/// </summary>
Warn,
/// <summary>
/// Specifies the 2nd logging level from the top.
/// </summary>
Error,
/// <summary>
/// Specifies the top logging level.
/// </summary>
Fatal,
/// <summary>
/// Specifies not to output logs.
/// </summary>
None
}
}

View File

@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: 8684c3e3443c55b47b0a2ffe1d14909c

View File

@ -0,0 +1,345 @@
#region License
/*
* Logger.cs
*
* The MIT License
*
* Copyright (c) 2013-2024 sta.blockhead
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
#endregion
using System;
using System.Diagnostics;
using System.IO;
namespace WebSocketSharp
{
/// <summary>
/// Provides a set of methods and properties for logging.
/// </summary>
/// <remarks>
/// <para>
/// If you output a log with lower than the current logging level,
/// it cannot be outputted.
/// </para>
/// <para>
/// The default output method writes a log to the standard output
/// stream and the text file if it has a valid path.
/// </para>
/// <para>
/// If you would like to use the custom output method, you should
/// specify it with the constructor or the <see cref="Logger.Output"/>
/// property.
/// </para>
/// </remarks>
public class Logger
{
#region Private Fields
private volatile string _file;
private volatile LogLevel _level;
private Action<LogData, string> _output;
private object _sync;
#endregion
#region Public Constructors
/// <summary>
/// Initializes a new instance of the <see cref="Logger"/> class.
/// </summary>
/// <remarks>
/// This constructor initializes the logging level with the Error level.
/// </remarks>
public Logger ()
: this (LogLevel.Error, null, null)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="Logger"/> class with
/// the specified logging level.
/// </summary>
/// <param name="level">
/// One of the <see cref="LogLevel"/> enum values that specifies
/// the logging level.
/// </param>
public Logger (LogLevel level)
: this (level, null, null)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="Logger"/> class with
/// the specified logging level, path to the log file, and delegate
/// used to output a log.
/// </summary>
/// <param name="level">
/// One of the <see cref="LogLevel"/> enum values that specifies
/// the logging level.
/// </param>
/// <param name="file">
/// A <see cref="string"/> that specifies the path to the log file.
/// </param>
/// <param name="output">
/// An <see cref="T:System.Action{LogData, string}"/> that specifies
/// the delegate used to output a log.
/// </param>
public Logger (LogLevel level, string file, Action<LogData, string> output)
{
_level = level;
_file = file;
_output = output ?? defaultOutput;
_sync = new object ();
}
#endregion
#region Public Properties
/// <summary>
/// Gets or sets the path to the log file.
/// </summary>
/// <value>
/// A <see cref="string"/> that represents the path to the log file if any.
/// </value>
public string File {
get {
return _file;
}
set {
lock (_sync)
_file = value;
}
}
/// <summary>
/// Gets or sets the current logging level.
/// </summary>
/// <remarks>
/// A log with lower than the value of this property cannot be outputted.
/// </remarks>
/// <value>
/// <para>
/// One of the <see cref="LogLevel"/> enum values.
/// </para>
/// <para>
/// It represents the current logging level.
/// </para>
/// </value>
public LogLevel Level {
get {
return _level;
}
set {
lock (_sync)
_level = value;
}
}
/// <summary>
/// Gets or sets the delegate used to output a log.
/// </summary>
/// <value>
/// <para>
/// An <see cref="T:System.Action{LogData, string}"/> delegate.
/// </para>
/// <para>
/// It represents the delegate called when the logger outputs a log.
/// </para>
/// <para>
/// The string parameter passed to the delegate is the value of
/// the <see cref="Logger.File"/> property.
/// </para>
/// <para>
/// If the value to set is <see langword="null"/>, the default
/// output method is set.
/// </para>
/// </value>
public Action<LogData, string> Output {
get {
return _output;
}
set {
lock (_sync)
_output = value ?? defaultOutput;
}
}
#endregion
#region Private Methods
private static void defaultOutput (LogData data, string path)
{
var val = data.ToString ();
Console.WriteLine (val);
if (path != null && path.Length > 0)
writeToFile (val, path);
}
private void output (string message, LogLevel level)
{
lock (_sync) {
if (_level > level)
return;
try {
var data = new LogData (level, new StackFrame (2, true), message);
_output (data, _file);
}
catch (Exception ex) {
var data = new LogData (
LogLevel.Fatal,
new StackFrame (0, true),
ex.Message
);
Console.WriteLine (data.ToString ());
}
}
}
private static void writeToFile (string value, string path)
{
using (var writer = new StreamWriter (path, true))
using (var syncWriter = TextWriter.Synchronized (writer))
syncWriter.WriteLine (value);
}
#endregion
#region Public Methods
/// <summary>
/// Outputs the specified message as a log with the Debug level.
/// </summary>
/// <remarks>
/// If the current logging level is higher than the Debug level,
/// this method does not output the message as a log.
/// </remarks>
/// <param name="message">
/// A <see cref="string"/> that specifies the message to output.
/// </param>
public void Debug (string message)
{
if (_level > LogLevel.Debug)
return;
output (message, LogLevel.Debug);
}
/// <summary>
/// Outputs the specified message as a log with the Error level.
/// </summary>
/// <remarks>
/// If the current logging level is higher than the Error level,
/// this method does not output the message as a log.
/// </remarks>
/// <param name="message">
/// A <see cref="string"/> that specifies the message to output.
/// </param>
public void Error (string message)
{
if (_level > LogLevel.Error)
return;
output (message, LogLevel.Error);
}
/// <summary>
/// Outputs the specified message as a log with the Fatal level.
/// </summary>
/// <param name="message">
/// A <see cref="string"/> that specifies the message to output.
/// </param>
public void Fatal (string message)
{
if (_level > LogLevel.Fatal)
return;
output (message, LogLevel.Fatal);
}
/// <summary>
/// Outputs the specified message as a log with the Info level.
/// </summary>
/// <remarks>
/// If the current logging level is higher than the Info level,
/// this method does not output the message as a log.
/// </remarks>
/// <param name="message">
/// A <see cref="string"/> that specifies the message to output.
/// </param>
public void Info (string message)
{
if (_level > LogLevel.Info)
return;
output (message, LogLevel.Info);
}
/// <summary>
/// Outputs the specified message as a log with the Trace level.
/// </summary>
/// <remarks>
/// If the current logging level is higher than the Trace level,
/// this method does not output the message as a log.
/// </remarks>
/// <param name="message">
/// A <see cref="string"/> that specifies the message to output.
/// </param>
public void Trace (string message)
{
if (_level > LogLevel.Trace)
return;
output (message, LogLevel.Trace);
}
/// <summary>
/// Outputs the specified message as a log with the Warn level.
/// </summary>
/// <remarks>
/// If the current logging level is higher than the Warn level,
/// this method does not output the message as a log.
/// </remarks>
/// <param name="message">
/// A <see cref="string"/> that specifies the message to output.
/// </param>
public void Warn (string message)
{
if (_level > LogLevel.Warn)
return;
output (message, LogLevel.Warn);
}
#endregion
}
}

View File

@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: 3af5c1735c57c5944acd190ccf689365

52
Assets/External/websocket-sharp/Mask.cs vendored Normal file
View File

@ -0,0 +1,52 @@
#region License
/*
* Mask.cs
*
* The MIT License
*
* Copyright (c) 2012-2025 sta.blockhead
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
#endregion
using System;
namespace WebSocketSharp
{
/// <summary>
/// Indicates whether the payload data of a WebSocket frame is masked.
/// </summary>
/// <remarks>
/// The values of this enumeration are defined in
/// <see href="http://tools.ietf.org/html/rfc6455#section-5.2">
/// Section 5.2</see> of RFC 6455.
/// </remarks>
internal enum Mask
{
/// <summary>
/// Equivalent to numeric value 0. Indicates not masked.
/// </summary>
Off = 0x0,
/// <summary>
/// Equivalent to numeric value 1. Indicates masked.
/// </summary>
On = 0x1
}
}

View File

@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: e96ce8210fac01d43aab00d3ee6e24d9

View File

@ -0,0 +1,192 @@
#region License
/*
* MessageEventArgs.cs
*
* The MIT License
*
* Copyright (c) 2012-2022 sta.blockhead
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
#endregion
using System;
namespace WebSocketSharp
{
/// <summary>
/// Represents the event data for the <see cref="WebSocket.OnMessage"/> event.
/// </summary>
/// <remarks>
/// <para>
/// The message event occurs when the <see cref="WebSocket"/> interface
/// receives a message or a ping if the <see cref="WebSocket.EmitOnPing"/>
/// property is set to <c>true</c>.
/// </para>
/// <para>
/// If you would like to get the message data, you should access
/// the <see cref="Data"/> or <see cref="RawData"/> property.
/// </para>
/// </remarks>
public class MessageEventArgs : EventArgs
{
#region Private Fields
private string _data;
private bool _dataSet;
private Opcode _opcode;
private byte[] _rawData;
#endregion
#region Internal Constructors
internal MessageEventArgs (WebSocketFrame frame)
{
_opcode = frame.Opcode;
_rawData = frame.PayloadData.ApplicationData;
}
internal MessageEventArgs (Opcode opcode, byte[] rawData)
{
if ((ulong) rawData.LongLength > PayloadData.MaxLength)
throw new WebSocketException (CloseStatusCode.TooBig);
_opcode = opcode;
_rawData = rawData;
}
#endregion
#region Internal Properties
/// <summary>
/// Gets the opcode for the message.
/// </summary>
/// <value>
/// <see cref="Opcode.Text"/>, <see cref="Opcode.Binary"/>,
/// or <see cref="Opcode.Ping"/>.
/// </value>
internal Opcode Opcode {
get {
return _opcode;
}
}
#endregion
#region Public Properties
/// <summary>
/// Gets the message data as a <see cref="string"/>.
/// </summary>
/// <value>
/// <para>
/// A <see cref="string"/> that represents the message data
/// if the message type is text or ping.
/// </para>
/// <para>
/// <see langword="null"/> if the message type is binary or
/// the message data could not be UTF-8-decoded.
/// </para>
/// </value>
public string Data {
get {
setData ();
return _data;
}
}
/// <summary>
/// Gets a value indicating whether the message type is binary.
/// </summary>
/// <value>
/// <c>true</c> if the message type is binary; otherwise, <c>false</c>.
/// </value>
public bool IsBinary {
get {
return _opcode == Opcode.Binary;
}
}
/// <summary>
/// Gets a value indicating whether the message type is ping.
/// </summary>
/// <value>
/// <c>true</c> if the message type is ping; otherwise, <c>false</c>.
/// </value>
public bool IsPing {
get {
return _opcode == Opcode.Ping;
}
}
/// <summary>
/// Gets a value indicating whether the message type is text.
/// </summary>
/// <value>
/// <c>true</c> if the message type is text; otherwise, <c>false</c>.
/// </value>
public bool IsText {
get {
return _opcode == Opcode.Text;
}
}
/// <summary>
/// Gets the message data as an array of <see cref="byte"/>.
/// </summary>
/// <value>
/// An array of <see cref="byte"/> that represents the message data.
/// </value>
public byte[] RawData {
get {
setData ();
return _rawData;
}
}
#endregion
#region Private Methods
private void setData ()
{
if (_dataSet)
return;
if (_opcode == Opcode.Binary) {
_dataSet = true;
return;
}
string data;
if (_rawData.TryGetUTF8DecodedString (out data))
_data = data;
_dataSet = true;
}
#endregion
}
}

View File

@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: b9ecfe7845aca0f47b82eb3bf34eeebc

View File

@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: c24f6cb4d39821c41a0119a5c2052211
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:

View File

@ -0,0 +1,280 @@
#region License
/*
* AuthenticationChallenge.cs
*
* The MIT License
*
* Copyright (c) 2013-2024 sta.blockhead
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
#endregion
using System;
using System.Collections.Specialized;
using System.Text;
namespace WebSocketSharp.Net
{
internal class AuthenticationChallenge
{
#region Private Fields
private NameValueCollection _parameters;
private AuthenticationSchemes _scheme;
#endregion
#region Private Constructors
private AuthenticationChallenge (
AuthenticationSchemes scheme,
NameValueCollection parameters
)
{
_scheme = scheme;
_parameters = parameters;
}
#endregion
#region Internal Constructors
internal AuthenticationChallenge (
AuthenticationSchemes scheme,
string realm
)
: this (scheme, new NameValueCollection ())
{
_parameters["realm"] = realm;
if (scheme == AuthenticationSchemes.Digest) {
_parameters["nonce"] = CreateNonceValue ();
_parameters["algorithm"] = "MD5";
_parameters["qop"] = "auth";
}
}
#endregion
#region Internal Properties
internal NameValueCollection Parameters {
get {
return _parameters;
}
}
#endregion
#region Public Properties
public string Algorithm {
get {
return _parameters["algorithm"];
}
}
public string Domain {
get {
return _parameters["domain"];
}
}
public string Nonce {
get {
return _parameters["nonce"];
}
}
public string Opaque {
get {
return _parameters["opaque"];
}
}
public string Qop {
get {
return _parameters["qop"];
}
}
public string Realm {
get {
return _parameters["realm"];
}
}
public AuthenticationSchemes Scheme {
get {
return _scheme;
}
}
public string Stale {
get {
return _parameters["stale"];
}
}
#endregion
#region Internal Methods
internal static AuthenticationChallenge CreateBasicChallenge (string realm)
{
return new AuthenticationChallenge (AuthenticationSchemes.Basic, realm);
}
internal static AuthenticationChallenge CreateDigestChallenge (string realm)
{
return new AuthenticationChallenge (AuthenticationSchemes.Digest, realm);
}
internal static string CreateNonceValue ()
{
var rand = new Random ();
var bytes = new byte[16];
rand.NextBytes (bytes);
var buff = new StringBuilder (32);
foreach (var b in bytes)
buff.Append (b.ToString ("x2"));
return buff.ToString ();
}
internal static AuthenticationChallenge Parse (string value)
{
var chal = value.Split (new[] { ' ' }, 2);
if (chal.Length != 2)
return null;
var schm = chal[0].ToLower ();
if (schm == "basic") {
var parameters = ParseParameters (chal[1]);
return new AuthenticationChallenge (
AuthenticationSchemes.Basic,
parameters
);
}
if (schm == "digest") {
var parameters = ParseParameters (chal[1]);
return new AuthenticationChallenge (
AuthenticationSchemes.Digest,
parameters
);
}
return null;
}
internal static NameValueCollection ParseParameters (string value)
{
var ret = new NameValueCollection ();
foreach (var param in value.SplitHeaderValue (',')) {
var i = param.IndexOf ('=');
var name = i > 0 ? param.Substring (0, i).Trim () : null;
var val = i < 0
? param.Trim ().Trim ('"')
: i < param.Length - 1
? param.Substring (i + 1).Trim ().Trim ('"')
: String.Empty;
ret.Add (name, val);
}
return ret;
}
internal string ToBasicString ()
{
return String.Format ("Basic realm=\"{0}\"", _parameters["realm"]);
}
internal string ToDigestString ()
{
var buff = new StringBuilder (128);
var domain = _parameters["domain"];
var realm = _parameters["realm"];
var nonce = _parameters["nonce"];
if (domain != null) {
buff.AppendFormat (
"Digest realm=\"{0}\", domain=\"{1}\", nonce=\"{2}\"",
realm,
domain,
nonce
);
}
else {
buff.AppendFormat ("Digest realm=\"{0}\", nonce=\"{1}\"", realm, nonce);
}
var opaque = _parameters["opaque"];
if (opaque != null)
buff.AppendFormat (", opaque=\"{0}\"", opaque);
var stale = _parameters["stale"];
if (stale != null)
buff.AppendFormat (", stale={0}", stale);
var algo = _parameters["algorithm"];
if (algo != null)
buff.AppendFormat (", algorithm={0}", algo);
var qop = _parameters["qop"];
if (qop != null)
buff.AppendFormat (", qop=\"{0}\"", qop);
return buff.ToString ();
}
#endregion
#region Public Methods
public override string ToString ()
{
if (_scheme == AuthenticationSchemes.Basic)
return ToBasicString ();
if (_scheme == AuthenticationSchemes.Digest)
return ToDigestString ();
return String.Empty;
}
#endregion
}
}

View File

@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: 84c0bed85decb0b479b4e5b420f1285a

View File

@ -0,0 +1,464 @@
#region License
/*
* AuthenticationResponse.cs
*
* The ParseBasicCredentials method is derived from HttpListenerContext.cs
* (System.Net) of Mono (http://www.mono-project.com).
*
* The MIT License
*
* Copyright (c) 2005 Novell, Inc. (http://www.novell.com)
* Copyright (c) 2013-2024 sta.blockhead
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
#endregion
using System;
using System.Collections.Specialized;
using System.Security.Cryptography;
using System.Security.Principal;
using System.Text;
namespace WebSocketSharp.Net
{
internal class AuthenticationResponse
{
#region Private Fields
private uint _nonceCount;
private NameValueCollection _parameters;
private AuthenticationSchemes _scheme;
#endregion
#region Private Constructors
private AuthenticationResponse (
AuthenticationSchemes scheme,
NameValueCollection parameters
)
{
_scheme = scheme;
_parameters = parameters;
}
#endregion
#region Internal Constructors
internal AuthenticationResponse (NetworkCredential credentials)
: this (
AuthenticationSchemes.Basic,
new NameValueCollection (),
credentials,
0
)
{
}
internal AuthenticationResponse (
AuthenticationChallenge challenge,
NetworkCredential credentials,
uint nonceCount
)
: this (challenge.Scheme, challenge.Parameters, credentials, nonceCount)
{
}
internal AuthenticationResponse (
AuthenticationSchemes scheme,
NameValueCollection parameters,
NetworkCredential credentials,
uint nonceCount
)
: this (scheme, parameters)
{
_parameters["username"] = credentials.Username;
_parameters["password"] = credentials.Password;
_parameters["uri"] = credentials.Domain;
_nonceCount = nonceCount;
if (scheme == AuthenticationSchemes.Digest)
initAsDigest ();
}
#endregion
#region Internal Properties
internal uint NonceCount {
get {
return _nonceCount < UInt32.MaxValue ? _nonceCount : 0;
}
}
internal NameValueCollection Parameters {
get {
return _parameters;
}
}
#endregion
#region Public Properties
public string Algorithm {
get {
return _parameters["algorithm"];
}
}
public string Cnonce {
get {
return _parameters["cnonce"];
}
}
public string Nc {
get {
return _parameters["nc"];
}
}
public string Nonce {
get {
return _parameters["nonce"];
}
}
public string Opaque {
get {
return _parameters["opaque"];
}
}
public string Password {
get {
return _parameters["password"];
}
}
public string Qop {
get {
return _parameters["qop"];
}
}
public string Realm {
get {
return _parameters["realm"];
}
}
public string Response {
get {
return _parameters["response"];
}
}
public AuthenticationSchemes Scheme {
get {
return _scheme;
}
}
public string Uri {
get {
return _parameters["uri"];
}
}
public string UserName {
get {
return _parameters["username"];
}
}
#endregion
#region Private Methods
private static string createA1 (
string username,
string password,
string realm
)
{
return String.Format ("{0}:{1}:{2}", username, realm, password);
}
private static string createA1 (
string username,
string password,
string realm,
string nonce,
string cnonce
)
{
var a1 = createA1 (username, password, realm);
return String.Format ("{0}:{1}:{2}", hash (a1), nonce, cnonce);
}
private static string createA2 (string method, string uri)
{
return String.Format ("{0}:{1}", method, uri);
}
private static string createA2 (string method, string uri, string entity)
{
return String.Format ("{0}:{1}:{2}", method, uri, hash (entity));
}
private static string hash (string value)
{
var buff = new StringBuilder (64);
var md5 = MD5.Create ();
var bytes = Encoding.UTF8.GetBytes (value);
var res = md5.ComputeHash (bytes);
foreach (var b in res)
buff.Append (b.ToString ("x2"));
return buff.ToString ();
}
private void initAsDigest ()
{
var qops = _parameters["qop"];
if (qops != null) {
var hasAuth = qops.Split (',').Contains (
qop => qop.Trim ().ToLower () == "auth"
);
if (hasAuth) {
_parameters["qop"] = "auth";
_parameters["cnonce"] = AuthenticationChallenge.CreateNonceValue ();
_parameters["nc"] = String.Format ("{0:x8}", ++_nonceCount);
}
else {
_parameters["qop"] = null;
}
}
_parameters["method"] = "GET";
_parameters["response"] = CreateRequestDigest (_parameters);
}
#endregion
#region Internal Methods
internal static string CreateRequestDigest (NameValueCollection parameters)
{
var uname = parameters["username"];
var passwd = parameters["password"];
var realm = parameters["realm"];
var nonce = parameters["nonce"];
var uri = parameters["uri"];
var algo = parameters["algorithm"];
var qop = parameters["qop"];
var cnonce = parameters["cnonce"];
var nc = parameters["nc"];
var method = parameters["method"];
var a1 = algo != null && algo.ToLower () == "md5-sess"
? createA1 (uname, passwd, realm, nonce, cnonce)
: createA1 (uname, passwd, realm);
var a2 = qop != null && qop.ToLower () == "auth-int"
? createA2 (method, uri, parameters["entity"])
: createA2 (method, uri);
var secret = hash (a1);
var data = qop != null
? String.Format (
"{0}:{1}:{2}:{3}:{4}",
nonce,
nc,
cnonce,
qop,
hash (a2)
)
: String.Format ("{0}:{1}", nonce, hash (a2));
var keyed = String.Format ("{0}:{1}", secret, data);
return hash (keyed);
}
internal static AuthenticationResponse Parse (string value)
{
try {
var cred = value.Split (new[] { ' ' }, 2);
if (cred.Length != 2)
return null;
var schm = cred[0].ToLower ();
if (schm == "basic") {
var parameters = ParseBasicCredentials (cred[1]);
return new AuthenticationResponse (
AuthenticationSchemes.Basic,
parameters
);
}
if (schm == "digest") {
var parameters = AuthenticationChallenge.ParseParameters (cred[1]);
return new AuthenticationResponse (
AuthenticationSchemes.Digest,
parameters
);
}
return null;
}
catch {
return null;
}
}
internal static NameValueCollection ParseBasicCredentials (string value)
{
var ret = new NameValueCollection ();
// Decode the basic-credentials (a Base64 encoded string).
var bytes = Convert.FromBase64String (value);
var userPass = Encoding.UTF8.GetString (bytes);
// The format is [<domain>\]<username>:<password>.
var idx = userPass.IndexOf (':');
var uname = userPass.Substring (0, idx);
var passwd = idx < userPass.Length - 1
? userPass.Substring (idx + 1)
: String.Empty;
// Check if <domain> exists.
idx = uname.IndexOf ('\\');
if (idx > -1)
uname = uname.Substring (idx + 1);
ret["username"] = uname;
ret["password"] = passwd;
return ret;
}
internal string ToBasicString ()
{
var uname = _parameters["username"];
var passwd = _parameters["password"];
var userPass = String.Format ("{0}:{1}", uname, passwd);
var bytes = Encoding.UTF8.GetBytes (userPass);
var cred = Convert.ToBase64String (bytes);
return "Basic " + cred;
}
internal string ToDigestString ()
{
var buff = new StringBuilder (256);
var uname = _parameters["username"];
var realm = _parameters["realm"];
var nonce = _parameters["nonce"];
var uri = _parameters["uri"];
var res = _parameters["response"];
buff.AppendFormat (
"Digest username=\"{0}\", realm=\"{1}\", nonce=\"{2}\", uri=\"{3}\", response=\"{4}\"",
uname,
realm,
nonce,
uri,
res
);
var opaque = _parameters["opaque"];
if (opaque != null)
buff.AppendFormat (", opaque=\"{0}\"", opaque);
var algo = _parameters["algorithm"];
if (algo != null)
buff.AppendFormat (", algorithm={0}", algo);
var qop = _parameters["qop"];
if (qop != null) {
var cnonce = _parameters["cnonce"];
var nc = _parameters["nc"];
buff.AppendFormat (
", qop={0}, cnonce=\"{1}\", nc={2}",
qop,
cnonce,
nc
);
}
return buff.ToString ();
}
#endregion
#region Public Methods
public IIdentity ToIdentity ()
{
if (_scheme == AuthenticationSchemes.Basic) {
var uname = _parameters["username"];
var passwd = _parameters["password"];
return new HttpBasicIdentity (uname, passwd);
}
if (_scheme == AuthenticationSchemes.Digest)
return new HttpDigestIdentity (_parameters);
return null;
}
public override string ToString ()
{
if (_scheme == AuthenticationSchemes.Basic)
return ToBasicString ();
if (_scheme == AuthenticationSchemes.Digest)
return ToDigestString ();
return String.Empty;
}
#endregion
}
}

View File

@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: d47f8aed92f4d1d499acfb1f91908f39

View File

@ -0,0 +1,66 @@
#region License
/*
* AuthenticationSchemes.cs
*
* This code is derived from AuthenticationSchemes.cs (System.Net) of Mono
* (http://www.mono-project.com).
*
* The MIT License
*
* Copyright (c) 2005 Novell, Inc. (http://www.novell.com)
* Copyright (c) 2012-2016 sta.blockhead
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
#endregion
#region Authors
/*
* Authors:
* - Atsushi Enomoto <atsushi@ximian.com>
*/
#endregion
using System;
namespace WebSocketSharp.Net
{
/// <summary>
/// Specifies the scheme for authentication.
/// </summary>
public enum AuthenticationSchemes
{
/// <summary>
/// No authentication is allowed.
/// </summary>
None,
/// <summary>
/// Specifies digest authentication.
/// </summary>
Digest = 1,
/// <summary>
/// Specifies basic authentication.
/// </summary>
Basic = 8,
/// <summary>
/// Specifies anonymous authentication.
/// </summary>
Anonymous = 0x8000
}
}

View File

@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: d5a2c71d0b1e8a64ebd26b4420e70d3c

View File

@ -0,0 +1,93 @@
#region License
/*
* Chunk.cs
*
* This code is derived from ChunkStream.cs (System.Net) of Mono
* (http://www.mono-project.com).
*
* The MIT License
*
* Copyright (c) 2003 Ximian, Inc (http://www.ximian.com)
* Copyright (c) 2014-2021 sta.blockhead
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
#endregion
#region Authors
/*
* Authors:
* - Gonzalo Paniagua Javier <gonzalo@ximian.com>
*/
#endregion
using System;
namespace WebSocketSharp.Net
{
internal class Chunk
{
#region Private Fields
private byte[] _data;
private int _offset;
#endregion
#region Public Constructors
public Chunk (byte[] data)
{
_data = data;
}
#endregion
#region Public Properties
public int ReadLeft {
get {
return _data.Length - _offset;
}
}
#endregion
#region Public Methods
public int Read (byte[] buffer, int offset, int count)
{
var left = _data.Length - _offset;
if (left == 0)
return 0;
if (count > left)
count = left;
Buffer.BlockCopy (_data, _offset, buffer, offset, count);
_offset += count;
return count;
}
#endregion
}
}

View File

@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: 14a0fcae05dbbdc4ea0cdca9bc630d0f

View File

@ -0,0 +1,429 @@
#region License
/*
* ChunkStream.cs
*
* This code is derived from ChunkStream.cs (System.Net) of Mono
* (http://www.mono-project.com).
*
* The MIT License
*
* Copyright (c) 2003 Ximian, Inc (http://www.ximian.com)
* Copyright (c) 2012-2023 sta.blockhead
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
#endregion
#region Authors
/*
* Authors:
* - Gonzalo Paniagua Javier <gonzalo@ximian.com>
*/
#endregion
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Net;
using System.Text;
namespace WebSocketSharp.Net
{
internal class ChunkStream
{
#region Private Fields
private int _chunkRead;
private int _chunkSize;
private List<Chunk> _chunks;
private int _count;
private byte[] _endBuffer;
private bool _gotIt;
private WebHeaderCollection _headers;
private int _offset;
private StringBuilder _saved;
private bool _sawCr;
private InputChunkState _state;
private int _trailerState;
#endregion
#region Public Constructors
public ChunkStream (WebHeaderCollection headers)
{
_headers = headers;
_chunkSize = -1;
_chunks = new List<Chunk> ();
_saved = new StringBuilder ();
}
#endregion
#region Internal Properties
internal int Count {
get {
return _count;
}
}
internal byte[] EndBuffer {
get {
return _endBuffer;
}
}
internal int Offset {
get {
return _offset;
}
}
#endregion
#region Public Properties
public WebHeaderCollection Headers {
get {
return _headers;
}
}
public bool WantsMore {
get {
return _state < InputChunkState.End;
}
}
#endregion
#region Private Methods
private int read (byte[] buffer, int offset, int count)
{
var nread = 0;
var cnt = _chunks.Count;
for (var i = 0; i < cnt; i++) {
var chunk = _chunks[i];
if (chunk == null)
continue;
if (chunk.ReadLeft == 0) {
_chunks[i] = null;
continue;
}
nread += chunk.Read (buffer, offset + nread, count - nread);
if (nread == count)
break;
}
return nread;
}
private InputChunkState seekCrLf (byte[] buffer, ref int offset, int length)
{
if (!_sawCr) {
if (buffer[offset++] != 13)
throwProtocolViolation ("CR is expected.");
_sawCr = true;
if (offset == length)
return InputChunkState.DataEnded;
}
if (buffer[offset++] != 10)
throwProtocolViolation ("LF is expected.");
return InputChunkState.None;
}
private InputChunkState setChunkSize (
byte[] buffer,
ref int offset,
int length
)
{
byte b = 0;
while (offset < length) {
b = buffer[offset++];
if (_sawCr) {
if (b != 10)
throwProtocolViolation ("LF is expected.");
break;
}
if (b == 13) {
_sawCr = true;
continue;
}
if (b == 10)
throwProtocolViolation ("LF is unexpected.");
if (_gotIt)
continue;
if (b == 32 || b == 59) { // SP or ';'
_gotIt = true;
continue;
}
_saved.Append ((char) b);
}
if (_saved.Length > 20)
throwProtocolViolation ("The chunk size is too big.");
if (b != 10)
return InputChunkState.None;
var s = _saved.ToString ();
try {
_chunkSize = Int32.Parse (s, NumberStyles.HexNumber);
}
catch {
throwProtocolViolation ("The chunk size cannot be parsed.");
}
_chunkRead = 0;
if (_chunkSize == 0) {
_trailerState = 2;
return InputChunkState.Trailer;
}
return InputChunkState.Data;
}
private InputChunkState setTrailer (
byte[] buffer,
ref int offset,
int length
)
{
while (offset < length) {
if (_trailerState == 4) // CR LF CR LF
break;
var b = buffer[offset++];
_saved.Append ((char) b);
if (_trailerState == 1 || _trailerState == 3) { // CR or CR LF CR
if (b != 10)
throwProtocolViolation ("LF is expected.");
_trailerState++;
continue;
}
if (b == 13) {
_trailerState++;
continue;
}
if (b == 10)
throwProtocolViolation ("LF is unexpected.");
_trailerState = 0;
}
var len = _saved.Length;
if (len > 4196)
throwProtocolViolation ("The trailer is too long.");
if (_trailerState < 4)
return InputChunkState.Trailer;
if (len == 2)
return InputChunkState.End;
_saved.Length = len - 2;
var val = _saved.ToString ();
var reader = new StringReader (val);
while (true) {
var line = reader.ReadLine ();
if (line == null || line.Length == 0)
break;
_headers.Add (line);
}
return InputChunkState.End;
}
private static void throwProtocolViolation (string message)
{
throw new WebException (
message,
null,
WebExceptionStatus.ServerProtocolViolation,
null
);
}
private void write (byte[] buffer, int offset, int length)
{
if (_state == InputChunkState.End)
throwProtocolViolation ("The chunks were ended.");
if (_state == InputChunkState.None) {
_state = setChunkSize (buffer, ref offset, length);
if (_state == InputChunkState.None)
return;
_saved.Length = 0;
_sawCr = false;
_gotIt = false;
}
if (_state == InputChunkState.Data) {
if (offset >= length)
return;
_state = writeData (buffer, ref offset, length);
if (_state == InputChunkState.Data)
return;
}
if (_state == InputChunkState.DataEnded) {
if (offset >= length)
return;
_state = seekCrLf (buffer, ref offset, length);
if (_state == InputChunkState.DataEnded)
return;
_sawCr = false;
}
if (_state == InputChunkState.Trailer) {
if (offset >= length)
return;
_state = setTrailer (buffer, ref offset, length);
if (_state == InputChunkState.Trailer)
return;
_saved.Length = 0;
}
if (_state == InputChunkState.End) {
_endBuffer = buffer;
_offset = offset;
_count = length - offset;
return;
}
if (offset >= length)
return;
write (buffer, offset, length);
}
private InputChunkState writeData (
byte[] buffer,
ref int offset,
int length
)
{
var cnt = length - offset;
var left = _chunkSize - _chunkRead;
if (cnt > left)
cnt = left;
var data = new byte[cnt];
Buffer.BlockCopy (buffer, offset, data, 0, cnt);
var chunk = new Chunk (data);
_chunks.Add (chunk);
offset += cnt;
_chunkRead += cnt;
return _chunkRead == _chunkSize
? InputChunkState.DataEnded
: InputChunkState.Data;
}
#endregion
#region Internal Methods
internal void ResetChunkStore ()
{
_chunkRead = 0;
_chunkSize = -1;
_chunks.Clear ();
}
#endregion
#region Public Methods
public int Read (byte[] buffer, int offset, int count)
{
if (count <= 0)
return 0;
return read (buffer, offset, count);
}
public void Write (byte[] buffer, int offset, int count)
{
if (count <= 0)
return;
write (buffer, offset, offset + count);
}
#endregion
}
}

View File

@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: 1f64dddc3b0d0f049af97629c42dca44

View File

@ -0,0 +1,283 @@
#region License
/*
* ChunkedRequestStream.cs
*
* This code is derived from ChunkedInputStream.cs (System.Net) of Mono
* (http://www.mono-project.com).
*
* The MIT License
*
* Copyright (c) 2005 Novell, Inc. (http://www.novell.com)
* Copyright (c) 2012-2023 sta.blockhead
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
#endregion
#region Authors
/*
* Authors:
* - Gonzalo Paniagua Javier <gonzalo@novell.com>
*/
#endregion
using System;
using System.IO;
namespace WebSocketSharp.Net
{
internal class ChunkedRequestStream : RequestStream
{
#region Private Fields
private static readonly int _bufferLength;
private HttpListenerContext _context;
private ChunkStream _decoder;
private bool _disposed;
private bool _noMoreData;
#endregion
#region Static Constructor
static ChunkedRequestStream ()
{
_bufferLength = 8192;
}
#endregion
#region Internal Constructors
internal ChunkedRequestStream (
Stream innerStream,
byte[] initialBuffer,
int offset,
int count,
HttpListenerContext context
)
: base (innerStream, initialBuffer, offset, count, -1)
{
_context = context;
_decoder = new ChunkStream (
(WebHeaderCollection) context.Request.Headers
);
}
#endregion
#region Internal Properties
internal bool HasRemainingBuffer {
get {
return _decoder.Count + Count > 0;
}
}
internal byte[] RemainingBuffer {
get {
using (var buff = new MemoryStream ()) {
var cnt = _decoder.Count;
if (cnt > 0)
buff.Write (_decoder.EndBuffer, _decoder.Offset, cnt);
cnt = Count;
if (cnt > 0)
buff.Write (InitialBuffer, Offset, cnt);
buff.Close ();
return buff.ToArray ();
}
}
}
#endregion
#region Private Methods
private void onRead (IAsyncResult asyncResult)
{
var rstate = (ReadBufferState) asyncResult.AsyncState;
var ares = rstate.AsyncResult;
try {
var nread = base.EndRead (asyncResult);
_decoder.Write (ares.Buffer, ares.Offset, nread);
nread = _decoder.Read (rstate.Buffer, rstate.Offset, rstate.Count);
rstate.Offset += nread;
rstate.Count -= nread;
if (rstate.Count == 0 || !_decoder.WantsMore || nread == 0) {
_noMoreData = !_decoder.WantsMore && nread == 0;
ares.Count = rstate.InitialCount - rstate.Count;
ares.Complete ();
return;
}
base.BeginRead (ares.Buffer, ares.Offset, ares.Count, onRead, rstate);
}
catch (Exception ex) {
_context.ErrorMessage = "I/O operation aborted";
_context.SendError ();
ares.Complete (ex);
}
}
#endregion
#region Public Methods
public override IAsyncResult BeginRead (
byte[] buffer,
int offset,
int count,
AsyncCallback callback,
object state
)
{
if (_disposed)
throw new ObjectDisposedException (ObjectName);
if (buffer == null)
throw new ArgumentNullException ("buffer");
if (offset < 0) {
var msg = "A negative value.";
throw new ArgumentOutOfRangeException ("offset", msg);
}
if (count < 0) {
var msg = "A negative value.";
throw new ArgumentOutOfRangeException ("count", msg);
}
var len = buffer.Length;
if (offset + count > len) {
var msg = "The sum of offset and count is greater than the length of buffer.";
throw new ArgumentException (msg);
}
var ares = new HttpStreamAsyncResult (callback, state);
if (_noMoreData) {
ares.Complete ();
return ares;
}
var nread = _decoder.Read (buffer, offset, count);
offset += nread;
count -= nread;
if (count == 0) {
ares.Count = nread;
ares.Complete ();
return ares;
}
if (!_decoder.WantsMore) {
_noMoreData = nread == 0;
ares.Count = nread;
ares.Complete ();
return ares;
}
ares.Buffer = new byte[_bufferLength];
ares.Offset = 0;
ares.Count = _bufferLength;
var rstate = new ReadBufferState (buffer, offset, count, ares);
rstate.InitialCount += nread;
base.BeginRead (ares.Buffer, ares.Offset, ares.Count, onRead, rstate);
return ares;
}
public override void Close ()
{
if (_disposed)
return;
base.Close ();
_disposed = true;
}
public override int EndRead (IAsyncResult asyncResult)
{
if (_disposed)
throw new ObjectDisposedException (ObjectName);
if (asyncResult == null)
throw new ArgumentNullException ("asyncResult");
var ares = asyncResult as HttpStreamAsyncResult;
if (ares == null) {
var msg = "A wrong IAsyncResult instance.";
throw new ArgumentException (msg, "asyncResult");
}
if (!ares.IsCompleted)
ares.AsyncWaitHandle.WaitOne ();
if (ares.HasException) {
var msg = "The I/O operation has been aborted.";
throw new HttpListenerException (995, msg);
}
return ares.Count;
}
public override int Read (byte[] buffer, int offset, int count)
{
var ares = BeginRead (buffer, offset, count, null, null);
return EndRead (ares);
}
#endregion
}
}

View File

@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: 1580b5e2a58b77b45b5b49739b05e897

View File

@ -0,0 +1,311 @@
#region License
/*
* ClientSslConfiguration.cs
*
* The MIT License
*
* Copyright (c) 2014 liryna
* Copyright (c) 2014-2024 sta.blockhead
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
#endregion
#region Authors
/*
* Authors:
* - Liryna <liryna.stark@gmail.com>
*/
#endregion
using System;
using System.Net.Security;
using System.Security.Authentication;
using System.Security.Cryptography.X509Certificates;
namespace WebSocketSharp.Net
{
/// <summary>
/// Stores the parameters for an <see cref="SslStream"/> instance used by
/// a client.
/// </summary>
public class ClientSslConfiguration
{
#region Private Fields
private bool _checkCertRevocation;
private LocalCertificateSelectionCallback _clientCertSelectionCallback;
private X509CertificateCollection _clientCerts;
private SslProtocols _enabledSslProtocols;
private RemoteCertificateValidationCallback _serverCertValidationCallback;
private string _targetHost;
#endregion
#region Public Constructors
/// <summary>
/// Initializes a new instance of the <see cref="ClientSslConfiguration"/>
/// class with the specified target host name.
/// </summary>
/// <param name="targetHost">
/// A <see cref="string"/> that specifies the name of the server that
/// will share a secure connection with the client.
/// </param>
/// <exception cref="ArgumentException">
/// <paramref name="targetHost"/> is an empty string.
/// </exception>
/// <exception cref="ArgumentNullException">
/// <paramref name="targetHost"/> is <see langword="null"/>.
/// </exception>
public ClientSslConfiguration (string targetHost)
{
if (targetHost == null)
throw new ArgumentNullException ("targetHost");
if (targetHost.Length == 0)
throw new ArgumentException ("An empty string.", "targetHost");
_targetHost = targetHost;
_enabledSslProtocols = SslProtocols.None;
}
/// <summary>
/// Initializes a new instance of the <see cref="ClientSslConfiguration"/>
/// class copying from the specified configuration.
/// </summary>
/// <param name="configuration">
/// A <see cref="ClientSslConfiguration"/> from which to copy.
/// </param>
/// <exception cref="ArgumentNullException">
/// <paramref name="configuration"/> is <see langword="null"/>.
/// </exception>
public ClientSslConfiguration (ClientSslConfiguration configuration)
{
if (configuration == null)
throw new ArgumentNullException ("configuration");
_checkCertRevocation = configuration._checkCertRevocation;
_clientCertSelectionCallback = configuration._clientCertSelectionCallback;
_clientCerts = configuration._clientCerts;
_enabledSslProtocols = configuration._enabledSslProtocols;
_serverCertValidationCallback = configuration._serverCertValidationCallback;
_targetHost = configuration._targetHost;
}
#endregion
#region Public Properties
/// <summary>
/// Gets or sets a value indicating whether the certificate revocation
/// list is checked during authentication.
/// </summary>
/// <value>
/// <para>
/// <c>true</c> if the certificate revocation list is checked during
/// authentication; otherwise, <c>false</c>.
/// </para>
/// <para>
/// The default value is <c>false</c>.
/// </para>
/// </value>
public bool CheckCertificateRevocation {
get {
return _checkCertRevocation;
}
set {
_checkCertRevocation = value;
}
}
/// <summary>
/// Gets or sets the collection of the certificates from which to select
/// one to supply to the server.
/// </summary>
/// <value>
/// <para>
/// A <see cref="X509CertificateCollection"/> that contains
/// the certificates from which to select.
/// </para>
/// <para>
/// <see langword="null"/> if not present.
/// </para>
/// <para>
/// The default value is <see langword="null"/>.
/// </para>
/// </value>
public X509CertificateCollection ClientCertificates {
get {
return _clientCerts;
}
set {
_clientCerts = value;
}
}
/// <summary>
/// Gets or sets the callback used to select the certificate to supply to
/// the server.
/// </summary>
/// <remarks>
/// No certificate is supplied if the callback returns <see langword="null"/>.
/// </remarks>
/// <value>
/// <para>
/// A <see cref="LocalCertificateSelectionCallback"/> delegate.
/// </para>
/// <para>
/// It represents the delegate called when the client selects
/// the certificate.
/// </para>
/// <para>
/// The default value invokes a method that only returns
/// <see langword="null"/>.
/// </para>
/// </value>
public LocalCertificateSelectionCallback ClientCertificateSelectionCallback {
get {
if (_clientCertSelectionCallback == null)
_clientCertSelectionCallback = defaultSelectClientCertificate;
return _clientCertSelectionCallback;
}
set {
_clientCertSelectionCallback = value;
}
}
/// <summary>
/// Gets or sets the enabled versions of the SSL/TLS protocols.
/// </summary>
/// <value>
/// <para>
/// Any of the <see cref="SslProtocols"/> enum values.
/// </para>
/// <para>
/// It represents the enabled versions of the SSL/TLS protocols.
/// </para>
/// <para>
/// The default value is <see cref="SslProtocols.None"/>.
/// </para>
/// </value>
public SslProtocols EnabledSslProtocols {
get {
return _enabledSslProtocols;
}
set {
_enabledSslProtocols = value;
}
}
/// <summary>
/// Gets or sets the callback used to validate the certificate supplied by
/// the server.
/// </summary>
/// <remarks>
/// The certificate is valid if the callback returns <c>true</c>.
/// </remarks>
/// <value>
/// <para>
/// A <see cref="RemoteCertificateValidationCallback"/> delegate.
/// </para>
/// <para>
/// It represents the delegate called when the client validates
/// the certificate.
/// </para>
/// <para>
/// The default value invokes a method that only returns <c>true</c>.
/// </para>
/// </value>
public RemoteCertificateValidationCallback ServerCertificateValidationCallback {
get {
if (_serverCertValidationCallback == null)
_serverCertValidationCallback = defaultValidateServerCertificate;
return _serverCertValidationCallback;
}
set {
_serverCertValidationCallback = value;
}
}
/// <summary>
/// Gets or sets the target host name.
/// </summary>
/// <value>
/// A <see cref="string"/> that represents the name of the server that
/// will share a secure connection with the client.
/// </value>
/// <exception cref="ArgumentException">
/// The value specified for a set operation is an empty string.
/// </exception>
/// <exception cref="ArgumentNullException">
/// The value specified for a set operation is <see langword="null"/>.
/// </exception>
public string TargetHost {
get {
return _targetHost;
}
set {
if (value == null)
throw new ArgumentNullException ("value");
if (value.Length == 0)
throw new ArgumentException ("An empty string.", "value");
_targetHost = value;
}
}
#endregion
#region Private Methods
private static X509Certificate defaultSelectClientCertificate (
object sender,
string targetHost,
X509CertificateCollection clientCertificates,
X509Certificate serverCertificate,
string[] acceptableIssuers
)
{
return null;
}
private static bool defaultValidateServerCertificate (
object sender,
X509Certificate certificate,
X509Chain chain,
SslPolicyErrors sslPolicyErrors
)
{
return true;
}
#endregion
}
}

View File

@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: 60a0fec9d60bbcd428164ca7e1522355

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: 5ff89aabc6475184fa85a0cb73e53bcd

View File

@ -0,0 +1,882 @@
#region License
/*
* CookieCollection.cs
*
* This code is derived from CookieCollection.cs (System.Net) of Mono
* (http://www.mono-project.com).
*
* The MIT License
*
* Copyright (c) 2004,2009 Novell, Inc. (http://www.novell.com)
* Copyright (c) 2012-2024 sta.blockhead
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
#endregion
#region Authors
/*
* Authors:
* - Lawrence Pit <loz@cable.a2000.nl>
* - Gonzalo Paniagua Javier <gonzalo@ximian.com>
* - Sebastien Pouliot <sebastien@ximian.com>
*/
#endregion
using System;
using System.Collections;
using System.Collections.Generic;
using System.Globalization;
using System.Text;
namespace WebSocketSharp.Net
{
/// <summary>
/// Provides a collection of instances of the <see cref="Cookie"/> class.
/// </summary>
[Serializable]
public class CookieCollection : ICollection<Cookie>
{
#region Private Fields
private List<Cookie> _list;
private bool _readOnly;
private object _sync;
#endregion
#region Public Constructors
/// <summary>
/// Initializes a new instance of the <see cref="CookieCollection"/> class.
/// </summary>
public CookieCollection ()
{
_list = new List<Cookie> ();
_sync = ((ICollection) _list).SyncRoot;
}
#endregion
#region Internal Properties
internal IList<Cookie> List {
get {
return _list;
}
}
internal IEnumerable<Cookie> Sorted {
get {
var list = new List<Cookie> (_list);
if (list.Count > 1)
list.Sort (compareForSorted);
return list;
}
}
#endregion
#region Public Properties
/// <summary>
/// Gets the number of cookies in the collection.
/// </summary>
/// <value>
/// An <see cref="int"/> that represents the number of cookies in
/// the collection.
/// </value>
public int Count {
get {
return _list.Count;
}
}
/// <summary>
/// Gets a value indicating whether the collection is read-only.
/// </summary>
/// <value>
/// <para>
/// <c>true</c> if the collection is read-only; otherwise, <c>false</c>.
/// </para>
/// <para>
/// The default value is <c>false</c>.
/// </para>
/// </value>
public bool IsReadOnly {
get {
return _readOnly;
}
internal set {
_readOnly = value;
}
}
/// <summary>
/// Gets a value indicating whether the access to the collection is
/// thread safe.
/// </summary>
/// <value>
/// <para>
/// <c>true</c> if the access to the collection is thread safe;
/// otherwise, <c>false</c>.
/// </para>
/// <para>
/// The default value is <c>false</c>.
/// </para>
/// </value>
public bool IsSynchronized {
get {
return false;
}
}
/// <summary>
/// Gets the cookie at the specified index from the collection.
/// </summary>
/// <value>
/// A <see cref="Cookie"/> at the specified index in the collection.
/// </value>
/// <param name="index">
/// An <see cref="int"/> that specifies the zero-based index of the cookie
/// to find.
/// </param>
/// <exception cref="ArgumentOutOfRangeException">
/// <paramref name="index"/> is out of allowable range for the collection.
/// </exception>
public Cookie this[int index] {
get {
if (index < 0 || index >= _list.Count)
throw new ArgumentOutOfRangeException ("index");
return _list[index];
}
}
/// <summary>
/// Gets the cookie with the specified name from the collection.
/// </summary>
/// <value>
/// <para>
/// A <see cref="Cookie"/> with the specified name in the collection.
/// </para>
/// <para>
/// <see langword="null"/> if not found.
/// </para>
/// </value>
/// <param name="name">
/// A <see cref="string"/> that specifies the name of the cookie to find.
/// </param>
/// <exception cref="ArgumentNullException">
/// <paramref name="name"/> is <see langword="null"/>.
/// </exception>
public Cookie this[string name] {
get {
if (name == null)
throw new ArgumentNullException ("name");
var caseInsensitive = StringComparison.InvariantCultureIgnoreCase;
foreach (var cookie in Sorted) {
if (cookie.Name.Equals (name, caseInsensitive))
return cookie;
}
return null;
}
}
/// <summary>
/// Gets an object used to synchronize access to the collection.
/// </summary>
/// <value>
/// An <see cref="object"/> used to synchronize access to the collection.
/// </value>
public object SyncRoot {
get {
return _sync;
}
}
#endregion
#region Private Methods
private void add (Cookie cookie)
{
var idx = search (cookie);
if (idx == -1) {
_list.Add (cookie);
return;
}
_list[idx] = cookie;
}
private static int compareForSort (Cookie x, Cookie y)
{
return (x.Name.Length + x.Value.Length)
- (y.Name.Length + y.Value.Length);
}
private static int compareForSorted (Cookie x, Cookie y)
{
var ret = x.Version - y.Version;
if (ret != 0)
return ret;
ret = x.Name.CompareTo (y.Name);
if (ret != 0)
return ret;
return y.Path.Length - x.Path.Length;
}
private static CookieCollection parseRequest (string value)
{
var ret = new CookieCollection ();
Cookie cookie = null;
var ver = 0;
var caseInsensitive = StringComparison.InvariantCultureIgnoreCase;
var pairs = value.SplitHeaderValue (',', ';').ToList ();
for (var i = 0; i < pairs.Count; i++) {
var pair = pairs[i].Trim ();
if (pair.Length == 0)
continue;
var idx = pair.IndexOf ('=');
if (idx == -1) {
if (cookie == null)
continue;
if (pair.Equals ("$port", caseInsensitive)) {
cookie.Port = "\"\"";
continue;
}
continue;
}
if (idx == 0) {
if (cookie != null) {
ret.add (cookie);
cookie = null;
}
continue;
}
var name = pair.Substring (0, idx).TrimEnd (' ');
var val = idx < pair.Length - 1
? pair.Substring (idx + 1).TrimStart (' ')
: String.Empty;
if (name.Equals ("$version", caseInsensitive)) {
if (val.Length == 0)
continue;
var s = val.Unquote ();
int num;
if (!Int32.TryParse (s, out num))
continue;
ver = num;
continue;
}
if (name.Equals ("$path", caseInsensitive)) {
if (cookie == null)
continue;
if (val.Length == 0)
continue;
cookie.Path = val;
continue;
}
if (name.Equals ("$domain", caseInsensitive)) {
if (cookie == null)
continue;
if (val.Length == 0)
continue;
cookie.Domain = val;
continue;
}
if (name.Equals ("$port", caseInsensitive)) {
if (cookie == null)
continue;
if (val.Length == 0)
continue;
cookie.Port = val;
continue;
}
if (cookie != null)
ret.add (cookie);
if (!Cookie.TryCreate (name, val, out cookie))
continue;
if (ver != 0)
cookie.Version = ver;
}
if (cookie != null)
ret.add (cookie);
return ret;
}
private static CookieCollection parseResponse (string value)
{
var ret = new CookieCollection ();
Cookie cookie = null;
var caseInsensitive = StringComparison.InvariantCultureIgnoreCase;
var pairs = value.SplitHeaderValue (',', ';').ToList ();
for (var i = 0; i < pairs.Count; i++) {
var pair = pairs[i].Trim ();
if (pair.Length == 0)
continue;
var idx = pair.IndexOf ('=');
if (idx == -1) {
if (cookie == null)
continue;
if (pair.Equals ("port", caseInsensitive)) {
cookie.Port = "\"\"";
continue;
}
if (pair.Equals ("discard", caseInsensitive)) {
cookie.Discard = true;
continue;
}
if (pair.Equals ("secure", caseInsensitive)) {
cookie.Secure = true;
continue;
}
if (pair.Equals ("httponly", caseInsensitive)) {
cookie.HttpOnly = true;
continue;
}
continue;
}
if (idx == 0) {
if (cookie != null) {
ret.add (cookie);
cookie = null;
}
continue;
}
var name = pair.Substring (0, idx).TrimEnd (' ');
var val = idx < pair.Length - 1
? pair.Substring (idx + 1).TrimStart (' ')
: String.Empty;
if (name.Equals ("version", caseInsensitive)) {
if (cookie == null)
continue;
if (val.Length == 0)
continue;
var s = val.Unquote ();
int num;
if (!Int32.TryParse (s, out num))
continue;
cookie.Version = num;
continue;
}
if (name.Equals ("expires", caseInsensitive)) {
if (val.Length == 0)
continue;
if (i == pairs.Count - 1)
break;
i++;
if (cookie == null)
continue;
if (cookie.Expires != DateTime.MinValue)
continue;
var buff = new StringBuilder (val, 32);
buff.AppendFormat (", {0}", pairs[i].Trim ());
var s = buff.ToString ();
var fmts = new[] { "ddd, dd'-'MMM'-'yyyy HH':'mm':'ss 'GMT'", "r" };
var provider = CultureInfo.CreateSpecificCulture ("en-US");
var style = DateTimeStyles.AdjustToUniversal
| DateTimeStyles.AssumeUniversal;
DateTime expires;
var done = DateTime.TryParseExact (
s,
fmts,
provider,
style,
out expires
);
if (!done)
continue;
cookie.Expires = expires.ToLocalTime ();
continue;
}
if (name.Equals ("max-age", caseInsensitive)) {
if (cookie == null)
continue;
if (val.Length == 0)
continue;
var s = val.Unquote ();
int maxAge;
if (!Int32.TryParse (s, out maxAge))
continue;
cookie.MaxAge = maxAge;
continue;
}
if (name.Equals ("path", caseInsensitive)) {
if (cookie == null)
continue;
if (val.Length == 0)
continue;
cookie.Path = val;
continue;
}
if (name.Equals ("domain", caseInsensitive)) {
if (cookie == null)
continue;
if (val.Length == 0)
continue;
cookie.Domain = val;
continue;
}
if (name.Equals ("port", caseInsensitive)) {
if (cookie == null)
continue;
if (val.Length == 0)
continue;
cookie.Port = val;
continue;
}
if (name.Equals ("comment", caseInsensitive)) {
if (cookie == null)
continue;
if (val.Length == 0)
continue;
cookie.Comment = urlDecode (val, Encoding.UTF8);
continue;
}
if (name.Equals ("commenturl", caseInsensitive)) {
if (cookie == null)
continue;
if (val.Length == 0)
continue;
cookie.CommentUri = val.Unquote ().ToUri ();
continue;
}
if (name.Equals ("samesite", caseInsensitive)) {
if (cookie == null)
continue;
if (val.Length == 0)
continue;
cookie.SameSite = val.Unquote ();
continue;
}
if (cookie != null)
ret.add (cookie);
Cookie.TryCreate (name, val, out cookie);
}
if (cookie != null)
ret.add (cookie);
return ret;
}
private int search (Cookie cookie)
{
for (var i = _list.Count - 1; i >= 0; i--) {
if (_list[i].EqualsWithoutValue (cookie))
return i;
}
return -1;
}
private static string urlDecode (string s, Encoding encoding)
{
if (s.IndexOfAny (new[] { '%', '+' }) == -1)
return s;
try {
return HttpUtility.UrlDecode (s, encoding);
}
catch {
return null;
}
}
#endregion
#region Internal Methods
internal static CookieCollection Parse (string value, bool response)
{
try {
return response ? parseResponse (value) : parseRequest (value);
}
catch (Exception ex) {
throw new CookieException ("It could not be parsed.", ex);
}
}
internal void SetOrRemove (Cookie cookie)
{
var idx = search (cookie);
if (idx == -1) {
if (cookie.Expired)
return;
_list.Add (cookie);
return;
}
if (cookie.Expired) {
_list.RemoveAt (idx);
return;
}
_list[idx] = cookie;
}
internal void SetOrRemove (CookieCollection cookies)
{
foreach (var cookie in cookies._list)
SetOrRemove (cookie);
}
internal void Sort ()
{
if (_list.Count < 2)
return;
_list.Sort (compareForSort);
}
#endregion
#region Public Methods
/// <summary>
/// Adds the specified cookie to the collection.
/// </summary>
/// <param name="cookie">
/// A <see cref="Cookie"/> to add.
/// </param>
/// <exception cref="ArgumentNullException">
/// <paramref name="cookie"/> is <see langword="null"/>.
/// </exception>
/// <exception cref="InvalidOperationException">
/// The collection is read-only.
/// </exception>
public void Add (Cookie cookie)
{
if (_readOnly) {
var msg = "The collection is read-only.";
throw new InvalidOperationException (msg);
}
if (cookie == null)
throw new ArgumentNullException ("cookie");
add (cookie);
}
/// <summary>
/// Adds the specified cookies to the collection.
/// </summary>
/// <param name="cookies">
/// A <see cref="CookieCollection"/> that contains the cookies to add.
/// </param>
/// <exception cref="ArgumentNullException">
/// <paramref name="cookies"/> is <see langword="null"/>.
/// </exception>
/// <exception cref="InvalidOperationException">
/// The collection is read-only.
/// </exception>
public void Add (CookieCollection cookies)
{
if (_readOnly) {
var msg = "The collection is read-only.";
throw new InvalidOperationException (msg);
}
if (cookies == null)
throw new ArgumentNullException ("cookies");
foreach (var cookie in cookies._list)
add (cookie);
}
/// <summary>
/// Removes all cookies from the collection.
/// </summary>
/// <exception cref="InvalidOperationException">
/// The collection is read-only.
/// </exception>
public void Clear ()
{
if (_readOnly) {
var msg = "The collection is read-only.";
throw new InvalidOperationException (msg);
}
_list.Clear ();
}
/// <summary>
/// Determines whether the collection contains the specified cookie.
/// </summary>
/// <returns>
/// <c>true</c> if the cookie is found in the collection; otherwise,
/// <c>false</c>.
/// </returns>
/// <param name="cookie">
/// A <see cref="Cookie"/> to find.
/// </param>
/// <exception cref="ArgumentNullException">
/// <paramref name="cookie"/> is <see langword="null"/>.
/// </exception>
public bool Contains (Cookie cookie)
{
if (cookie == null)
throw new ArgumentNullException ("cookie");
return search (cookie) > -1;
}
/// <summary>
/// Copies the elements of the collection to the specified array,
/// starting at the specified index.
/// </summary>
/// <param name="array">
/// An array of <see cref="Cookie"/> that specifies the destination of
/// the elements copied from the collection.
/// </param>
/// <param name="index">
/// An <see cref="int"/> that specifies the zero-based index in
/// the array at which copying starts.
/// </param>
/// <exception cref="ArgumentException">
/// The space from <paramref name="index"/> to the end of
/// <paramref name="array"/> is not enough to copy to.
/// </exception>
/// <exception cref="ArgumentNullException">
/// <paramref name="array"/> is <see langword="null"/>.
/// </exception>
/// <exception cref="ArgumentOutOfRangeException">
/// <paramref name="index"/> is less than zero.
/// </exception>
public void CopyTo (Cookie[] array, int index)
{
if (array == null)
throw new ArgumentNullException ("array");
if (index < 0) {
var msg = "Less than zero.";
throw new ArgumentOutOfRangeException ("index", msg);
}
if (array.Length - index < _list.Count) {
var msg = "The available space of the array is not enough to copy to.";
throw new ArgumentException (msg);
}
_list.CopyTo (array, index);
}
/// <summary>
/// Gets the enumerator that iterates through the collection.
/// </summary>
/// <returns>
/// An <see cref="T:System.Collections.Generic.IEnumerator{Cookie}"/>
/// instance that can be used to iterate through the collection.
/// </returns>
public IEnumerator<Cookie> GetEnumerator ()
{
return _list.GetEnumerator ();
}
/// <summary>
/// Removes the specified cookie from the collection.
/// </summary>
/// <returns>
/// <para>
/// <c>true</c> if the cookie is successfully removed; otherwise,
/// <c>false</c>.
/// </para>
/// <para>
/// <c>false</c> if the cookie is not found in the collection.
/// </para>
/// </returns>
/// <param name="cookie">
/// A <see cref="Cookie"/> to remove.
/// </param>
/// <exception cref="ArgumentNullException">
/// <paramref name="cookie"/> is <see langword="null"/>.
/// </exception>
/// <exception cref="InvalidOperationException">
/// The collection is read-only.
/// </exception>
public bool Remove (Cookie cookie)
{
if (_readOnly) {
var msg = "The collection is read-only.";
throw new InvalidOperationException (msg);
}
if (cookie == null)
throw new ArgumentNullException ("cookie");
var idx = search (cookie);
if (idx == -1)
return false;
_list.RemoveAt (idx);
return true;
}
#endregion
#region Explicit Interface Implementations
/// <summary>
/// Gets the enumerator that iterates through the collection.
/// </summary>
/// <returns>
/// An <see cref="IEnumerator"/> instance that can be used to iterate
/// through the collection.
/// </returns>
IEnumerator IEnumerable.GetEnumerator ()
{
return _list.GetEnumerator ();
}
#endregion
}
}

View File

@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: 9324917a904d21243a764a5afcb4dde4

View File

@ -0,0 +1,169 @@
#region License
/*
* CookieException.cs
*
* This code is derived from CookieException.cs (System.Net) of Mono
* (http://www.mono-project.com).
*
* The MIT License
*
* Copyright (c) 2012-2024 sta.blockhead
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
#endregion
#region Authors
/*
* Authors:
* - Lawrence Pit <loz@cable.a2000.nl>
*/
#endregion
using System;
using System.Runtime.Serialization;
using System.Security.Permissions;
namespace WebSocketSharp.Net
{
/// <summary>
/// The exception that is thrown when a <see cref="Cookie"/> gets an error.
/// </summary>
[Serializable]
public class CookieException : FormatException, ISerializable
{
#region Internal Constructors
internal CookieException (string message)
: base (message)
{
}
internal CookieException (string message, Exception innerException)
: base (message, innerException)
{
}
#endregion
#region Protected Constructors
/// <summary>
/// Initializes a new instance of the <see cref="CookieException"/> class
/// with the specified serialized data.
/// </summary>
/// <param name="serializationInfo">
/// A <see cref="SerializationInfo"/> that contains the serialized
/// object data.
/// </param>
/// <param name="streamingContext">
/// A <see cref="StreamingContext"/> that specifies the source for
/// the deserialization.
/// </param>
/// <exception cref="ArgumentNullException">
/// <paramref name="serializationInfo"/> is <see langword="null"/>.
/// </exception>
protected CookieException (
SerializationInfo serializationInfo,
StreamingContext streamingContext
)
: base (serializationInfo, streamingContext)
{
}
#endregion
#region Public Constructors
/// <summary>
/// Initializes a new instance of the <see cref="CookieException"/> class.
/// </summary>
public CookieException ()
: base ()
{
}
#endregion
#region Public Methods
/// <summary>
/// Populates the specified <see cref="SerializationInfo"/> instance with
/// the data needed to serialize the current instance.
/// </summary>
/// <param name="serializationInfo">
/// A <see cref="SerializationInfo"/> that holds the serialized object data.
/// </param>
/// <param name="streamingContext">
/// A <see cref="StreamingContext"/> that specifies the destination for
/// the serialization.
/// </param>
/// <exception cref="ArgumentNullException">
/// <paramref name="serializationInfo"/> is <see langword="null"/>.
/// </exception>
[
SecurityPermission (
SecurityAction.LinkDemand,
Flags = SecurityPermissionFlag.SerializationFormatter
)
]
public override void GetObjectData (
SerializationInfo serializationInfo,
StreamingContext streamingContext
)
{
base.GetObjectData (serializationInfo, streamingContext);
}
#endregion
#region Explicit Interface Implementation
/// <summary>
/// Populates the specified <see cref="SerializationInfo"/> instance with
/// the data needed to serialize the current instance.
/// </summary>
/// <param name="serializationInfo">
/// A <see cref="SerializationInfo"/> that holds the serialized object data.
/// </param>
/// <param name="streamingContext">
/// A <see cref="StreamingContext"/> that specifies the destination for
/// the serialization.
/// </param>
/// <exception cref="ArgumentNullException">
/// <paramref name="serializationInfo"/> is <see langword="null"/>.
/// </exception>
[
SecurityPermission (
SecurityAction.LinkDemand,
Flags = SecurityPermissionFlag.SerializationFormatter,
SerializationFormatter = true
)
]
void ISerializable.GetObjectData (
SerializationInfo serializationInfo,
StreamingContext streamingContext
)
{
base.GetObjectData (serializationInfo, streamingContext);
}
#endregion
}
}

View File

@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: 00c4066ad16ffd145815887061f4c68d

View File

@ -0,0 +1,604 @@
#region License
/*
* EndPointListener.cs
*
* This code is derived from EndPointListener.cs (System.Net) of Mono
* (http://www.mono-project.com).
*
* The MIT License
*
* Copyright (c) 2005 Novell, Inc. (http://www.novell.com)
* Copyright (c) 2012-2023 sta.blockhead
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
#endregion
#region Authors
/*
* Authors:
* - Gonzalo Paniagua Javier <gonzalo@novell.com>
*/
#endregion
#region Contributors
/*
* Contributors:
* - Liryna <liryna.stark@gmail.com>
* - Nicholas Devenish
*/
#endregion
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Security.Cryptography;
using System.Security.Cryptography.X509Certificates;
using System.Threading;
namespace WebSocketSharp.Net
{
internal sealed class EndPointListener
{
#region Private Fields
private List<HttpListenerPrefix> _all; // host == '+'
private Dictionary<HttpConnection, HttpConnection> _connections;
private object _connectionsSync;
private static readonly string _defaultCertFolderPath;
private IPEndPoint _endpoint;
private List<HttpListenerPrefix> _prefixes;
private bool _secure;
private Socket _socket;
private ServerSslConfiguration _sslConfig;
private List<HttpListenerPrefix> _unhandled; // host == '*'
#endregion
#region Static Constructor
static EndPointListener ()
{
_defaultCertFolderPath = Environment.GetFolderPath (
Environment.SpecialFolder.ApplicationData
);
}
#endregion
#region Internal Constructors
internal EndPointListener (
IPEndPoint endpoint,
bool secure,
string certificateFolderPath,
ServerSslConfiguration sslConfig,
bool reuseAddress
)
{
_endpoint = endpoint;
if (secure) {
var cert = getCertificate (
endpoint.Port,
certificateFolderPath,
sslConfig.ServerCertificate
);
if (cert == null) {
var msg = "No server certificate could be found.";
throw new ArgumentException (msg);
}
_secure = true;
_sslConfig = new ServerSslConfiguration (sslConfig);
_sslConfig.ServerCertificate = cert;
}
_prefixes = new List<HttpListenerPrefix> ();
_connections = new Dictionary<HttpConnection, HttpConnection> ();
_connectionsSync = ((ICollection) _connections).SyncRoot;
_socket = new Socket (
endpoint.Address.AddressFamily,
SocketType.Stream,
ProtocolType.Tcp
);
if (reuseAddress) {
_socket.SetSocketOption (
SocketOptionLevel.Socket,
SocketOptionName.ReuseAddress,
true
);
}
_socket.Bind (endpoint);
_socket.Listen (500);
_socket.BeginAccept (onAccept, this);
}
#endregion
#region Public Properties
public IPAddress Address {
get {
return _endpoint.Address;
}
}
public bool IsSecure {
get {
return _secure;
}
}
public int Port {
get {
return _endpoint.Port;
}
}
public ServerSslConfiguration SslConfiguration {
get {
return _sslConfig;
}
}
#endregion
#region Private Methods
private static void addSpecial (
List<HttpListenerPrefix> prefixes,
HttpListenerPrefix prefix
)
{
var path = prefix.Path;
foreach (var pref in prefixes) {
if (pref.Path == path) {
var msg = "The prefix is already in use.";
throw new HttpListenerException (87, msg);
}
}
prefixes.Add (prefix);
}
private void clearConnections ()
{
HttpConnection[] conns = null;
lock (_connectionsSync) {
var cnt = _connections.Count;
if (cnt == 0)
return;
conns = new HttpConnection[cnt];
_connections.Values.CopyTo (conns, 0);
_connections.Clear ();
}
foreach (var conn in conns)
conn.Close (true);
}
private static RSACryptoServiceProvider createRSAFromFile (string path)
{
var rsa = new RSACryptoServiceProvider ();
var key = File.ReadAllBytes (path);
rsa.ImportCspBlob (key);
return rsa;
}
private static X509Certificate2 getCertificate (
int port,
string folderPath,
X509Certificate2 defaultCertificate
)
{
if (folderPath == null || folderPath.Length == 0)
folderPath = _defaultCertFolderPath;
try {
var cer = Path.Combine (folderPath, String.Format ("{0}.cer", port));
var key = Path.Combine (folderPath, String.Format ("{0}.key", port));
var exists = File.Exists (cer) && File.Exists (key);
if (!exists)
return defaultCertificate;
var cert = new X509Certificate2 (cer);
cert.PrivateKey = createRSAFromFile (key);
return cert;
}
catch {
return defaultCertificate;
}
}
private void leaveIfNoPrefix ()
{
if (_prefixes.Count > 0)
return;
var prefs = _unhandled;
if (prefs != null && prefs.Count > 0)
return;
prefs = _all;
if (prefs != null && prefs.Count > 0)
return;
Close ();
}
private static void onAccept (IAsyncResult asyncResult)
{
var lsnr = (EndPointListener) asyncResult.AsyncState;
Socket sock = null;
try {
sock = lsnr._socket.EndAccept (asyncResult);
}
catch (ObjectDisposedException) {
return;
}
catch (Exception) {
// TODO: Logging.
}
try {
lsnr._socket.BeginAccept (onAccept, lsnr);
}
catch (Exception) {
// TODO: Logging.
if (sock != null)
sock.Close ();
return;
}
if (sock == null)
return;
processAccepted (sock, lsnr);
}
private static void processAccepted (
Socket socket,
EndPointListener listener
)
{
HttpConnection conn = null;
try {
conn = new HttpConnection (socket, listener);
}
catch (Exception) {
// TODO: Logging.
socket.Close ();
return;
}
lock (listener._connectionsSync)
listener._connections.Add (conn, conn);
conn.BeginReadRequest ();
}
private static bool removeSpecial (
List<HttpListenerPrefix> prefixes,
HttpListenerPrefix prefix
)
{
var path = prefix.Path;
var cnt = prefixes.Count;
for (var i = 0; i < cnt; i++) {
if (prefixes[i].Path == path) {
prefixes.RemoveAt (i);
return true;
}
}
return false;
}
private static HttpListener searchHttpListenerFromSpecial (
string path,
List<HttpListenerPrefix> prefixes
)
{
if (prefixes == null)
return null;
HttpListener ret = null;
var bestLen = -1;
foreach (var pref in prefixes) {
var prefPath = pref.Path;
var len = prefPath.Length;
if (len < bestLen)
continue;
var match = path.StartsWith (prefPath, StringComparison.Ordinal);
if (!match)
continue;
bestLen = len;
ret = pref.Listener;
}
return ret;
}
#endregion
#region Internal Methods
internal static bool CertificateExists (int port, string folderPath)
{
if (folderPath == null || folderPath.Length == 0)
folderPath = _defaultCertFolderPath;
var cer = Path.Combine (folderPath, String.Format ("{0}.cer", port));
var key = Path.Combine (folderPath, String.Format ("{0}.key", port));
return File.Exists (cer) && File.Exists (key);
}
internal void RemoveConnection (HttpConnection connection)
{
lock (_connectionsSync)
_connections.Remove (connection);
}
internal bool TrySearchHttpListener (Uri uri, out HttpListener listener)
{
listener = null;
if (uri == null)
return false;
var host = uri.Host;
var dns = Uri.CheckHostName (host) == UriHostNameType.Dns;
var port = uri.Port.ToString ();
var path = HttpUtility.UrlDecode (uri.AbsolutePath);
if (path[path.Length - 1] != '/')
path += "/";
if (host != null && host.Length > 0) {
var prefs = _prefixes;
var bestLen = -1;
foreach (var pref in prefs) {
if (dns) {
var prefHost = pref.Host;
var prefDns = Uri.CheckHostName (prefHost) == UriHostNameType.Dns;
if (prefDns) {
if (prefHost != host)
continue;
}
}
if (pref.Port != port)
continue;
var prefPath = pref.Path;
var len = prefPath.Length;
if (len < bestLen)
continue;
var match = path.StartsWith (prefPath, StringComparison.Ordinal);
if (!match)
continue;
bestLen = len;
listener = pref.Listener;
}
if (bestLen != -1)
return true;
}
listener = searchHttpListenerFromSpecial (path, _unhandled);
if (listener != null)
return true;
listener = searchHttpListenerFromSpecial (path, _all);
return listener != null;
}
#endregion
#region Public Methods
public void AddPrefix (HttpListenerPrefix prefix)
{
List<HttpListenerPrefix> current, future;
if (prefix.Host == "*") {
do {
current = _unhandled;
future = current != null
? new List<HttpListenerPrefix> (current)
: new List<HttpListenerPrefix> ();
addSpecial (future, prefix);
}
while (
Interlocked.CompareExchange (ref _unhandled, future, current)
!= current
);
return;
}
if (prefix.Host == "+") {
do {
current = _all;
future = current != null
? new List<HttpListenerPrefix> (current)
: new List<HttpListenerPrefix> ();
addSpecial (future, prefix);
}
while (
Interlocked.CompareExchange (ref _all, future, current)
!= current
);
return;
}
do {
current = _prefixes;
var idx = current.IndexOf (prefix);
if (idx > -1) {
if (current[idx].Listener != prefix.Listener) {
var fmt = "There is another listener for {0}.";
var msg = String.Format (fmt, prefix);
throw new HttpListenerException (87, msg);
}
return;
}
future = new List<HttpListenerPrefix> (current);
future.Add (prefix);
}
while (
Interlocked.CompareExchange (ref _prefixes, future, current)
!= current
);
}
public void Close ()
{
_socket.Close ();
clearConnections ();
EndPointManager.RemoveEndPoint (_endpoint);
}
public void RemovePrefix (HttpListenerPrefix prefix)
{
List<HttpListenerPrefix> current, future;
if (prefix.Host == "*") {
do {
current = _unhandled;
if (current == null)
break;
future = new List<HttpListenerPrefix> (current);
if (!removeSpecial (future, prefix))
break;
}
while (
Interlocked.CompareExchange (ref _unhandled, future, current)
!= current
);
leaveIfNoPrefix ();
return;
}
if (prefix.Host == "+") {
do {
current = _all;
if (current == null)
break;
future = new List<HttpListenerPrefix> (current);
if (!removeSpecial (future, prefix))
break;
}
while (
Interlocked.CompareExchange (ref _all, future, current)
!= current
);
leaveIfNoPrefix ();
return;
}
do {
current = _prefixes;
if (!current.Contains (prefix))
break;
future = new List<HttpListenerPrefix> (current);
future.Remove (prefix);
}
while (
Interlocked.CompareExchange (ref _prefixes, future, current)
!= current
);
leaveIfNoPrefix ();
}
#endregion
}
}

View File

@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: 9545c19e60d2db24db67dfb6448ffb6b

View File

@ -0,0 +1,261 @@
#region License
/*
* EndPointManager.cs
*
* This code is derived from EndPointManager.cs (System.Net) of Mono
* (http://www.mono-project.com).
*
* The MIT License
*
* Copyright (c) 2005 Novell, Inc. (http://www.novell.com)
* Copyright (c) 2012-2020 sta.blockhead
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
#endregion
#region Authors
/*
* Authors:
* - Gonzalo Paniagua Javier <gonzalo@ximian.com>
*/
#endregion
#region Contributors
/*
* Contributors:
* - Liryna <liryna.stark@gmail.com>
*/
#endregion
using System;
using System.Collections;
using System.Collections.Generic;
using System.Net;
namespace WebSocketSharp.Net
{
internal sealed class EndPointManager
{
#region Private Fields
private static readonly Dictionary<IPEndPoint, EndPointListener> _endpoints;
#endregion
#region Static Constructor
static EndPointManager ()
{
_endpoints = new Dictionary<IPEndPoint, EndPointListener> ();
}
#endregion
#region Private Constructors
private EndPointManager ()
{
}
#endregion
#region Private Methods
private static void addPrefix (string uriPrefix, HttpListener listener)
{
var pref = new HttpListenerPrefix (uriPrefix, listener);
var addr = convertToIPAddress (pref.Host);
if (addr == null) {
var msg = "The URI prefix includes an invalid host.";
throw new HttpListenerException (87, msg);
}
if (!addr.IsLocal ()) {
var msg = "The URI prefix includes an invalid host.";
throw new HttpListenerException (87, msg);
}
int port;
if (!Int32.TryParse (pref.Port, out port)) {
var msg = "The URI prefix includes an invalid port.";
throw new HttpListenerException (87, msg);
}
if (!port.IsPortNumber ()) {
var msg = "The URI prefix includes an invalid port.";
throw new HttpListenerException (87, msg);
}
var path = pref.Path;
if (path.IndexOf ('%') != -1) {
var msg = "The URI prefix includes an invalid path.";
throw new HttpListenerException (87, msg);
}
if (path.IndexOf ("//", StringComparison.Ordinal) != -1) {
var msg = "The URI prefix includes an invalid path.";
throw new HttpListenerException (87, msg);
}
var endpoint = new IPEndPoint (addr, port);
EndPointListener lsnr;
if (_endpoints.TryGetValue (endpoint, out lsnr)) {
if (lsnr.IsSecure ^ pref.IsSecure) {
var msg = "The URI prefix includes an invalid scheme.";
throw new HttpListenerException (87, msg);
}
}
else {
lsnr = new EndPointListener (
endpoint,
pref.IsSecure,
listener.CertificateFolderPath,
listener.SslConfiguration,
listener.ReuseAddress
);
_endpoints.Add (endpoint, lsnr);
}
lsnr.AddPrefix (pref);
}
private static IPAddress convertToIPAddress (string hostname)
{
if (hostname == "*")
return IPAddress.Any;
if (hostname == "+")
return IPAddress.Any;
return hostname.ToIPAddress ();
}
private static void removePrefix (string uriPrefix, HttpListener listener)
{
var pref = new HttpListenerPrefix (uriPrefix, listener);
var addr = convertToIPAddress (pref.Host);
if (addr == null)
return;
if (!addr.IsLocal ())
return;
int port;
if (!Int32.TryParse (pref.Port, out port))
return;
if (!port.IsPortNumber ())
return;
var path = pref.Path;
if (path.IndexOf ('%') != -1)
return;
if (path.IndexOf ("//", StringComparison.Ordinal) != -1)
return;
var endpoint = new IPEndPoint (addr, port);
EndPointListener lsnr;
if (!_endpoints.TryGetValue (endpoint, out lsnr))
return;
if (lsnr.IsSecure ^ pref.IsSecure)
return;
lsnr.RemovePrefix (pref);
}
#endregion
#region Internal Methods
internal static bool RemoveEndPoint (IPEndPoint endpoint)
{
lock (((ICollection) _endpoints).SyncRoot)
return _endpoints.Remove (endpoint);
}
#endregion
#region Public Methods
public static void AddListener (HttpListener listener)
{
var added = new List<string> ();
lock (((ICollection) _endpoints).SyncRoot) {
try {
foreach (var pref in listener.Prefixes) {
addPrefix (pref, listener);
added.Add (pref);
}
}
catch {
foreach (var pref in added)
removePrefix (pref, listener);
throw;
}
}
}
public static void AddPrefix (string uriPrefix, HttpListener listener)
{
lock (((ICollection) _endpoints).SyncRoot)
addPrefix (uriPrefix, listener);
}
public static void RemoveListener (HttpListener listener)
{
lock (((ICollection) _endpoints).SyncRoot) {
foreach (var pref in listener.Prefixes)
removePrefix (pref, listener);
}
}
public static void RemovePrefix (string uriPrefix, HttpListener listener)
{
lock (((ICollection) _endpoints).SyncRoot)
removePrefix (uriPrefix, listener);
}
#endregion
}
}

View File

@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: 420d942fd863ffb48a7a0a77a21417ea

View File

@ -0,0 +1,82 @@
#region License
/*
* HttpBasicIdentity.cs
*
* This code is derived from HttpListenerBasicIdentity.cs (System.Net) of
* Mono (http://www.mono-project.com).
*
* The MIT License
*
* Copyright (c) 2005 Novell, Inc. (http://www.novell.com)
* Copyright (c) 2014-2017 sta.blockhead
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
#endregion
#region Authors
/*
* Authors:
* - Gonzalo Paniagua Javier <gonzalo@novell.com>
*/
#endregion
using System;
using System.Security.Principal;
namespace WebSocketSharp.Net
{
/// <summary>
/// Holds the username and password from an HTTP Basic authentication attempt.
/// </summary>
public class HttpBasicIdentity : GenericIdentity
{
#region Private Fields
private string _password;
#endregion
#region Internal Constructors
internal HttpBasicIdentity (string username, string password)
: base (username, "Basic")
{
_password = password;
}
#endregion
#region Public Properties
/// <summary>
/// Gets the password from a basic authentication attempt.
/// </summary>
/// <value>
/// A <see cref="string"/> that represents the password.
/// </value>
public virtual string Password {
get {
return _password;
}
}
#endregion
}
}

View File

@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: 8488c11ffdda6dc4cb98b844ec000b25

View File

@ -0,0 +1,653 @@
#region License
/*
* HttpConnection.cs
*
* This code is derived from HttpConnection.cs (System.Net) of Mono
* (http://www.mono-project.com).
*
* The MIT License
*
* Copyright (c) 2005 Novell, Inc. (http://www.novell.com)
* Copyright (c) 2012-2025 sta.blockhead
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
#endregion
#region Authors
/*
* Authors:
* - Gonzalo Paniagua Javier <gonzalo@novell.com>
*/
#endregion
#region Contributors
/*
* Contributors:
* - Liryna <liryna.stark@gmail.com>
* - Rohan Singh <rohan-singh@hotmail.com>
*/
#endregion
using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Net.Security;
using System.Net.Sockets;
using System.Text;
using System.Threading;
namespace WebSocketSharp.Net
{
internal sealed class HttpConnection
{
#region Private Fields
private int _attempts;
private byte[] _buffer;
private static readonly int _bufferLength;
private HttpListenerContext _context;
private StringBuilder _currentLine;
private EndPointListener _endPointListener;
private InputState _inputState;
private RequestStream _inputStream;
private bool _isSecure;
private LineState _lineState;
private EndPoint _localEndPoint;
private static readonly int _maxInputLength;
private ResponseStream _outputStream;
private int _position;
private EndPoint _remoteEndPoint;
private MemoryStream _requestBuffer;
private int _reuses;
private Socket _socket;
private Stream _stream;
private object _sync;
private int _timeout;
private Dictionary<int, bool> _timeoutCanceled;
private Timer _timer;
#endregion
#region Static Constructor
static HttpConnection ()
{
_bufferLength = 8192;
_maxInputLength = 32768;
}
#endregion
#region Internal Constructors
internal HttpConnection (Socket socket, EndPointListener listener)
{
_socket = socket;
_endPointListener = listener;
var netStream = new NetworkStream (socket, false);
if (listener.IsSecure) {
var sslConf = listener.SslConfiguration;
var sslStream = new SslStream (
netStream,
false,
sslConf.ClientCertificateValidationCallback
);
sslStream.AuthenticateAsServer (
sslConf.ServerCertificate,
sslConf.ClientCertificateRequired,
sslConf.EnabledSslProtocols,
sslConf.CheckCertificateRevocation
);
_isSecure = true;
_stream = sslStream;
}
else {
_stream = netStream;
}
_buffer = new byte[_bufferLength];
_localEndPoint = socket.LocalEndPoint;
_remoteEndPoint = socket.RemoteEndPoint;
_sync = new object ();
_timeoutCanceled = new Dictionary<int, bool> ();
_timer = new Timer (onTimeout, this, Timeout.Infinite, Timeout.Infinite);
// 90k ms for first request, 15k ms from then on.
init (new MemoryStream (), 90000);
}
#endregion
#region Public Properties
public bool IsClosed {
get {
return _socket == null;
}
}
public bool IsLocal {
get {
return ((IPEndPoint) _remoteEndPoint).Address.IsLocal ();
}
}
public bool IsSecure {
get {
return _isSecure;
}
}
public IPEndPoint LocalEndPoint {
get {
return (IPEndPoint) _localEndPoint;
}
}
public IPEndPoint RemoteEndPoint {
get {
return (IPEndPoint) _remoteEndPoint;
}
}
public int Reuses {
get {
return _reuses;
}
}
public Socket Socket {
get {
return _socket;
}
}
public Stream Stream {
get {
return _stream;
}
}
#endregion
#region Private Methods
private void close ()
{
lock (_sync) {
if (_socket == null)
return;
disposeTimer ();
disposeRequestBuffer ();
disposeStream ();
closeSocket ();
}
_context.Unregister ();
_endPointListener.RemoveConnection (this);
}
private void closeSocket ()
{
try {
_socket.Shutdown (SocketShutdown.Both);
}
catch {
}
_socket.Close ();
_socket = null;
}
private static MemoryStream createRequestBuffer (
RequestStream inputStream
)
{
var ret = new MemoryStream ();
if (inputStream is ChunkedRequestStream) {
var crs = (ChunkedRequestStream) inputStream;
if (crs.HasRemainingBuffer) {
var buff = crs.RemainingBuffer;
ret.Write (buff, 0, buff.Length);
}
return ret;
}
var cnt = inputStream.Count;
if (cnt > 0)
ret.Write (inputStream.InitialBuffer, inputStream.Offset, cnt);
return ret;
}
private void disposeRequestBuffer ()
{
if (_requestBuffer == null)
return;
_requestBuffer.Dispose ();
_requestBuffer = null;
}
private void disposeStream ()
{
if (_stream == null)
return;
_stream.Dispose ();
_stream = null;
}
private void disposeTimer ()
{
if (_timer == null)
return;
try {
_timer.Change (Timeout.Infinite, Timeout.Infinite);
}
catch {
}
_timer.Dispose ();
_timer = null;
}
private void init (MemoryStream requestBuffer, int timeout)
{
_requestBuffer = requestBuffer;
_timeout = timeout;
_context = new HttpListenerContext (this);
_currentLine = new StringBuilder (64);
_inputState = InputState.RequestLine;
_inputStream = null;
_lineState = LineState.None;
_outputStream = null;
_position = 0;
}
private static void onRead (IAsyncResult asyncResult)
{
var conn = (HttpConnection) asyncResult.AsyncState;
var current = conn._attempts;
if (conn._socket == null)
return;
lock (conn._sync) {
if (conn._socket == null)
return;
conn._timer.Change (Timeout.Infinite, Timeout.Infinite);
conn._timeoutCanceled[current] = true;
var nread = 0;
try {
nread = conn._stream.EndRead (asyncResult);
}
catch (Exception) {
// TODO: Logging.
conn.close ();
return;
}
if (nread <= 0) {
conn.close ();
return;
}
conn._requestBuffer.Write (conn._buffer, 0, nread);
if (conn.processRequestBuffer ())
return;
conn.BeginReadRequest ();
}
}
private static void onTimeout (object state)
{
var conn = (HttpConnection) state;
var current = conn._attempts;
if (conn._socket == null)
return;
lock (conn._sync) {
if (conn._socket == null)
return;
if (conn._timeoutCanceled[current])
return;
conn._context.SendError (408);
}
}
private bool processInput (byte[] data, int length)
{
// This method returns a bool:
// - true Done processing
// - false Need more input
var req = _context.Request;
try {
while (true) {
int nread;
var line = readLineFrom (data, _position, length, out nread);
_position += nread;
if (line == null)
break;
if (line.Length == 0) {
if (_inputState == InputState.RequestLine)
continue;
if (_position > _maxInputLength)
_context.ErrorMessage = "Headers too long";
return true;
}
if (_inputState == InputState.RequestLine) {
req.SetRequestLine (line);
_inputState = InputState.Headers;
}
else {
req.AddHeader (line);
}
if (_context.HasErrorMessage)
return true;
}
}
catch (Exception) {
// TODO: Logging.
_context.ErrorMessage = "Processing failure";
return true;
}
if (_position >= _maxInputLength) {
_context.ErrorMessage = "Headers too long";
return true;
}
return false;
}
private bool processRequestBuffer ()
{
// This method returns a bool:
// - true Done processing
// - false Need more write
var data = _requestBuffer.GetBuffer ();
var len = (int) _requestBuffer.Length;
if (!processInput (data, len))
return false;
var req = _context.Request;
if (!_context.HasErrorMessage)
req.FinishInitialization ();
if (_context.HasErrorMessage) {
_context.SendError ();
return true;
}
var uri = req.Url;
HttpListener httplsnr;
if (!_endPointListener.TrySearchHttpListener (uri, out httplsnr)) {
_context.SendError (404);
return true;
}
httplsnr.RegisterContext (_context);
return true;
}
private string readLineFrom (
byte[] buffer,
int offset,
int length,
out int nread
)
{
nread = 0;
for (var i = offset; i < length; i++) {
nread++;
var b = buffer[i];
if (b == 13) {
_lineState = LineState.Cr;
continue;
}
if (b == 10) {
_lineState = LineState.Lf;
break;
}
_currentLine.Append ((char) b);
}
if (_lineState != LineState.Lf)
return null;
var ret = _currentLine.ToString ();
_currentLine.Length = 0;
_lineState = LineState.None;
return ret;
}
private MemoryStream takeOverRequestBuffer ()
{
if (_inputStream != null)
return createRequestBuffer (_inputStream);
var ret = new MemoryStream ();
var buff = _requestBuffer.GetBuffer ();
var len = (int) _requestBuffer.Length;
var cnt = len - _position;
if (cnt > 0)
ret.Write (buff, _position, cnt);
disposeRequestBuffer ();
return ret;
}
#endregion
#region Internal Methods
internal void BeginReadRequest ()
{
_attempts++;
_timeoutCanceled.Add (_attempts, false);
_timer.Change (_timeout, Timeout.Infinite);
try {
_stream.BeginRead (_buffer, 0, _bufferLength, onRead, this);
}
catch (Exception) {
// TODO: Logging.
close ();
}
}
internal void Close (bool force)
{
if (_socket == null)
return;
lock (_sync) {
if (_socket == null)
return;
if (force) {
if (_outputStream != null)
_outputStream.Close (true);
close ();
return;
}
GetResponseStream ().Close (false);
if (_context.Response.CloseConnection) {
close ();
return;
}
if (!_context.Request.FlushInput ()) {
close ();
return;
}
_context.Unregister ();
_reuses++;
var buff = takeOverRequestBuffer ();
var len = buff.Length;
init (buff, 15000);
if (len > 0) {
if (processRequestBuffer ())
return;
}
BeginReadRequest ();
}
}
#endregion
#region Public Methods
public void Close ()
{
Close (false);
}
public RequestStream GetRequestStream (long contentLength, bool chunked)
{
lock (_sync) {
if (_socket == null)
return null;
if (_inputStream != null)
return _inputStream;
var buff = _requestBuffer.GetBuffer ();
var len = (int) _requestBuffer.Length;
var cnt = len - _position;
_inputStream = chunked
? new ChunkedRequestStream (
_stream,
buff,
_position,
cnt,
_context
)
: new RequestStream (
_stream,
buff,
_position,
cnt,
contentLength
);
disposeRequestBuffer ();
return _inputStream;
}
}
public ResponseStream GetResponseStream ()
{
lock (_sync) {
if (_socket == null)
return null;
if (_outputStream != null)
return _outputStream;
var lsnr = _context.Listener;
var ignore = lsnr != null ? lsnr.IgnoreWriteExceptions : true;
_outputStream = new ResponseStream (_stream, _context.Response, ignore);
return _outputStream;
}
}
#endregion
}
}

View File

@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: 08ab2f95b185d50488a0fe48f5dd5189

View File

@ -0,0 +1,192 @@
#region License
/*
* HttpDigestIdentity.cs
*
* The MIT License
*
* Copyright (c) 2014-2024 sta.blockhead
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
#endregion
using System;
using System.Collections.Specialized;
using System.Security.Principal;
namespace WebSocketSharp.Net
{
/// <summary>
/// Holds the username and other parameters from an HTTP Digest
/// authentication attempt.
/// </summary>
public class HttpDigestIdentity : GenericIdentity
{
#region Private Fields
private NameValueCollection _parameters;
#endregion
#region Internal Constructors
internal HttpDigestIdentity (NameValueCollection parameters)
: base (parameters["username"], "Digest")
{
_parameters = parameters;
}
#endregion
#region Public Properties
/// <summary>
/// Gets the algorithm parameter from a digest authentication attempt.
/// </summary>
/// <value>
/// A <see cref="string"/> that represents the algorithm parameter.
/// </value>
public string Algorithm {
get {
return _parameters["algorithm"];
}
}
/// <summary>
/// Gets the cnonce parameter from a digest authentication attempt.
/// </summary>
/// <value>
/// A <see cref="string"/> that represents the cnonce parameter.
/// </value>
public string Cnonce {
get {
return _parameters["cnonce"];
}
}
/// <summary>
/// Gets the nc parameter from a digest authentication attempt.
/// </summary>
/// <value>
/// A <see cref="string"/> that represents the nc parameter.
/// </value>
public string Nc {
get {
return _parameters["nc"];
}
}
/// <summary>
/// Gets the nonce parameter from a digest authentication attempt.
/// </summary>
/// <value>
/// A <see cref="string"/> that represents the nonce parameter.
/// </value>
public string Nonce {
get {
return _parameters["nonce"];
}
}
/// <summary>
/// Gets the opaque parameter from a digest authentication attempt.
/// </summary>
/// <value>
/// A <see cref="string"/> that represents the opaque parameter.
/// </value>
public string Opaque {
get {
return _parameters["opaque"];
}
}
/// <summary>
/// Gets the qop parameter from a digest authentication attempt.
/// </summary>
/// <value>
/// A <see cref="string"/> that represents the qop parameter.
/// </value>
public string Qop {
get {
return _parameters["qop"];
}
}
/// <summary>
/// Gets the realm parameter from a digest authentication attempt.
/// </summary>
/// <value>
/// A <see cref="string"/> that represents the realm parameter.
/// </value>
public string Realm {
get {
return _parameters["realm"];
}
}
/// <summary>
/// Gets the response parameter from a digest authentication attempt.
/// </summary>
/// <value>
/// A <see cref="string"/> that represents the response parameter.
/// </value>
public string Response {
get {
return _parameters["response"];
}
}
/// <summary>
/// Gets the uri parameter from a digest authentication attempt.
/// </summary>
/// <value>
/// A <see cref="string"/> that represents the uri parameter.
/// </value>
public string Uri {
get {
return _parameters["uri"];
}
}
#endregion
#region Internal Methods
internal bool IsValid (
string password,
string realm,
string method,
string entity
)
{
var parameters = new NameValueCollection (_parameters);
parameters["password"] = password;
parameters["realm"] = realm;
parameters["method"] = method;
parameters["entity"] = entity;
var expectedDigest = AuthenticationResponse.CreateRequestDigest (parameters);
return _parameters["response"] == expectedDigest;
}
#endregion
}
}

View File

@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: 7640330cbf592d14184f90eee16b8094

View File

@ -0,0 +1,128 @@
#region License
/*
* HttpHeaderInfo.cs
*
* The MIT License
*
* Copyright (c) 2013-2020 sta.blockhead
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
#endregion
using System;
namespace WebSocketSharp.Net
{
internal class HttpHeaderInfo
{
#region Private Fields
private string _headerName;
private HttpHeaderType _headerType;
#endregion
#region Internal Constructors
internal HttpHeaderInfo (string headerName, HttpHeaderType headerType)
{
_headerName = headerName;
_headerType = headerType;
}
#endregion
#region Internal Properties
internal bool IsMultiValueInRequest {
get {
var headerType = _headerType & HttpHeaderType.MultiValueInRequest;
return headerType == HttpHeaderType.MultiValueInRequest;
}
}
internal bool IsMultiValueInResponse {
get {
var headerType = _headerType & HttpHeaderType.MultiValueInResponse;
return headerType == HttpHeaderType.MultiValueInResponse;
}
}
#endregion
#region Public Properties
public string HeaderName {
get {
return _headerName;
}
}
public HttpHeaderType HeaderType {
get {
return _headerType;
}
}
public bool IsRequest {
get {
var headerType = _headerType & HttpHeaderType.Request;
return headerType == HttpHeaderType.Request;
}
}
public bool IsResponse {
get {
var headerType = _headerType & HttpHeaderType.Response;
return headerType == HttpHeaderType.Response;
}
}
#endregion
#region Public Methods
public bool IsMultiValue (bool response)
{
var headerType = _headerType & HttpHeaderType.MultiValue;
if (headerType != HttpHeaderType.MultiValue)
return response ? IsMultiValueInResponse : IsMultiValueInRequest;
return response ? IsResponse : IsRequest;
}
public bool IsRestricted (bool response)
{
var headerType = _headerType & HttpHeaderType.Restricted;
if (headerType != HttpHeaderType.Restricted)
return false;
return response ? IsResponse : IsRequest;
}
#endregion
}
}

View File

@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: 658e30bfa268d7e40a400018e371487b

View File

@ -0,0 +1,44 @@
#region License
/*
* HttpHeaderType.cs
*
* The MIT License
*
* Copyright (c) 2013-2014 sta.blockhead
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
#endregion
using System;
namespace WebSocketSharp.Net
{
[Flags]
internal enum HttpHeaderType
{
Unspecified = 0,
Request = 1,
Response = 1 << 1,
Restricted = 1 << 2,
MultiValue = 1 << 3,
MultiValueInRequest = 1 << 4,
MultiValueInResponse = 1 << 5
}
}

View File

@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: f1d86fad644dba148ae08c1ab9e638ee

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: bbec4555545c5a740b476dbc0ef4f52a

View File

@ -0,0 +1,202 @@
#region License
/*
* HttpListenerAsyncResult.cs
*
* This code is derived from ListenerAsyncResult.cs (System.Net) of Mono
* (http://www.mono-project.com).
*
* The MIT License
*
* Copyright (c) 2005 Ximian, Inc. (http://www.ximian.com)
* Copyright (c) 2012-2024 sta.blockhead
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
#endregion
#region Authors
/*
* Authors:
* - Gonzalo Paniagua Javier <gonzalo@ximian.com>
*/
#endregion
#region Contributors
/*
* Contributors:
* - Nicholas Devenish
*/
#endregion
using System;
using System.Threading;
namespace WebSocketSharp.Net
{
internal class HttpListenerAsyncResult : IAsyncResult
{
#region Private Fields
private AsyncCallback _callback;
private bool _completed;
private bool _completedSynchronously;
private HttpListenerContext _context;
private bool _endCalled;
private Exception _exception;
private Logger _log;
private object _state;
private object _sync;
private ManualResetEvent _waitHandle;
#endregion
#region Internal Constructors
internal HttpListenerAsyncResult (
AsyncCallback callback,
object state,
Logger log
)
{
_callback = callback;
_state = state;
_log = log;
_sync = new object ();
}
#endregion
#region Internal Properties
internal HttpListenerContext Context
{
get {
if (_exception != null)
throw _exception;
return _context;
}
}
internal bool EndCalled {
get {
return _endCalled;
}
set {
_endCalled = value;
}
}
internal object SyncRoot {
get {
return _sync;
}
}
#endregion
#region Public Properties
public object AsyncState {
get {
return _state;
}
}
public WaitHandle AsyncWaitHandle {
get {
lock (_sync) {
if (_waitHandle == null)
_waitHandle = new ManualResetEvent (_completed);
return _waitHandle;
}
}
}
public bool CompletedSynchronously {
get {
return _completedSynchronously;
}
}
public bool IsCompleted {
get {
lock (_sync)
return _completed;
}
}
#endregion
#region Private Methods
private void complete ()
{
lock (_sync) {
_completed = true;
if (_waitHandle != null)
_waitHandle.Set ();
}
if (_callback == null)
return;
ThreadPool.QueueUserWorkItem (
state => {
try {
_callback (this);
}
catch (Exception ex) {
_log.Error (ex.Message);
_log.Debug (ex.ToString ());
}
},
null
);
}
#endregion
#region Internal Methods
internal void Complete (Exception exception)
{
_exception = exception;
complete ();
}
internal void Complete (
HttpListenerContext context,
bool completedSynchronously
)
{
_context = context;
_completedSynchronously = completedSynchronously;
complete ();
}
#endregion
}
}

View File

@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: d785cd8b82ce78b4fab65e7330d18fe3

View File

@ -0,0 +1,452 @@
#region License
/*
* HttpListenerContext.cs
*
* This code is derived from HttpListenerContext.cs (System.Net) of Mono
* (http://www.mono-project.com).
*
* The MIT License
*
* Copyright (c) 2005 Novell, Inc. (http://www.novell.com)
* Copyright (c) 2012-2024 sta.blockhead
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
#endregion
#region Authors
/*
* Authors:
* - Gonzalo Paniagua Javier <gonzalo@novell.com>
*/
#endregion
using System;
using System.Security.Principal;
using System.Text;
using WebSocketSharp.Net.WebSockets;
namespace WebSocketSharp.Net
{
/// <summary>
/// Provides the access to the HTTP request and response objects used by
/// the <see cref="HttpListener"/> class.
/// </summary>
/// <remarks>
/// This class cannot be inherited.
/// </remarks>
public sealed class HttpListenerContext
{
#region Private Fields
private HttpConnection _connection;
private string _errorMessage;
private int _errorStatusCode;
private HttpListener _listener;
private HttpListenerRequest _request;
private HttpListenerResponse _response;
private IPrincipal _user;
private HttpListenerWebSocketContext _websocketContext;
#endregion
#region Internal Constructors
internal HttpListenerContext (HttpConnection connection)
{
_connection = connection;
_errorStatusCode = 400;
_request = new HttpListenerRequest (this);
_response = new HttpListenerResponse (this);
}
#endregion
#region Internal Properties
internal HttpConnection Connection {
get {
return _connection;
}
}
internal string ErrorMessage {
get {
return _errorMessage;
}
set {
_errorMessage = value;
}
}
internal int ErrorStatusCode {
get {
return _errorStatusCode;
}
set {
_errorStatusCode = value;
}
}
internal bool HasErrorMessage {
get {
return _errorMessage != null;
}
}
internal HttpListener Listener {
get {
return _listener;
}
set {
_listener = value;
}
}
#endregion
#region Public Properties
/// <summary>
/// Gets the HTTP request object that represents a client request.
/// </summary>
/// <value>
/// A <see cref="HttpListenerRequest"/> that represents the client request.
/// </value>
public HttpListenerRequest Request {
get {
return _request;
}
}
/// <summary>
/// Gets the HTTP response object used to send a response to the client.
/// </summary>
/// <value>
/// A <see cref="HttpListenerResponse"/> that represents a response to
/// the client request.
/// </value>
public HttpListenerResponse Response {
get {
return _response;
}
}
/// <summary>
/// Gets the client information.
/// </summary>
/// <value>
/// <para>
/// A <see cref="IPrincipal"/> instance that represents identity,
/// authentication, and security roles for the client.
/// </para>
/// <para>
/// <see langword="null"/> if the client is not authenticated.
/// </para>
/// </value>
public IPrincipal User {
get {
return _user;
}
}
#endregion
#region Private Methods
private static string createErrorContent (
int statusCode,
string statusDescription,
string message
)
{
return message != null && message.Length > 0
? String.Format (
"<html><body><h1>{0} {1} ({2})</h1></body></html>",
statusCode,
statusDescription,
message
)
: String.Format (
"<html><body><h1>{0} {1}</h1></body></html>",
statusCode,
statusDescription
);
}
#endregion
#region Internal Methods
internal HttpListenerWebSocketContext GetWebSocketContext (string protocol)
{
_websocketContext = new HttpListenerWebSocketContext (this, protocol);
return _websocketContext;
}
internal void SendAuthenticationChallenge (
AuthenticationSchemes scheme,
string realm
)
{
_response.StatusCode = 401;
var val = new AuthenticationChallenge (scheme, realm).ToString ();
_response.Headers.InternalSet ("WWW-Authenticate", val, true);
_response.Close ();
}
internal void SendError ()
{
try {
_response.StatusCode = _errorStatusCode;
_response.ContentType = "text/html";
var content = createErrorContent (
_errorStatusCode,
_response.StatusDescription,
_errorMessage
);
var enc = Encoding.UTF8;
var entity = enc.GetBytes (content);
_response.ContentEncoding = enc;
_response.ContentLength64 = entity.LongLength;
_response.Close (entity, true);
}
catch {
_connection.Close (true);
}
}
internal void SendError (int statusCode)
{
_errorStatusCode = statusCode;
SendError ();
}
internal void SendError (int statusCode, string message)
{
_errorStatusCode = statusCode;
_errorMessage = message;
SendError ();
}
internal bool SetUser (
AuthenticationSchemes scheme,
string realm,
Func<IIdentity, NetworkCredential> credentialsFinder
)
{
var user = HttpUtility.CreateUser (
_request.Headers["Authorization"],
scheme,
realm,
_request.HttpMethod,
credentialsFinder
);
if (user == null)
return false;
if (!user.Identity.IsAuthenticated)
return false;
_user = user;
return true;
}
internal void Unregister ()
{
if (_listener == null)
return;
_listener.UnregisterContext (this);
}
#endregion
#region Public Methods
/// <summary>
/// Accepts a WebSocket connection.
/// </summary>
/// <returns>
/// A <see cref="HttpListenerWebSocketContext"/> that represents
/// the WebSocket handshake request.
/// </returns>
/// <param name="protocol">
/// <para>
/// A <see cref="string"/> that specifies the name of the subprotocol
/// supported on the WebSocket connection.
/// </para>
/// <para>
/// <see langword="null"/> if not necessary.
/// </para>
/// </param>
/// <exception cref="ArgumentException">
/// <para>
/// <paramref name="protocol"/> is an empty string.
/// </para>
/// <para>
/// -or-
/// </para>
/// <para>
/// <paramref name="protocol"/> contains an invalid character.
/// </para>
/// </exception>
/// <exception cref="InvalidOperationException">
/// <para>
/// This method has already been done.
/// </para>
/// <para>
/// -or-
/// </para>
/// <para>
/// The client request is not a WebSocket handshake request.
/// </para>
/// </exception>
public HttpListenerWebSocketContext AcceptWebSocket (string protocol)
{
return AcceptWebSocket (protocol, null);
}
/// <summary>
/// Accepts a WebSocket connection with initializing the WebSocket
/// interface.
/// </summary>
/// <returns>
/// A <see cref="HttpListenerWebSocketContext"/> that represents
/// the WebSocket handshake request.
/// </returns>
/// <param name="protocol">
/// <para>
/// A <see cref="string"/> that specifies the name of the subprotocol
/// supported on the WebSocket connection.
/// </para>
/// <para>
/// <see langword="null"/> if not necessary.
/// </para>
/// </param>
/// <param name="initializer">
/// <para>
/// An <see cref="T:System.Action{WebSocket}"/> delegate.
/// </para>
/// <para>
/// It specifies the delegate called when a new WebSocket instance is
/// initialized.
/// </para>
/// </param>
/// <exception cref="ArgumentException">
/// <para>
/// <paramref name="protocol"/> is an empty string.
/// </para>
/// <para>
/// -or-
/// </para>
/// <para>
/// <paramref name="protocol"/> contains an invalid character.
/// </para>
/// <para>
/// -or-
/// </para>
/// <para>
/// <paramref name="initializer"/> caused an exception.
/// </para>
/// </exception>
/// <exception cref="InvalidOperationException">
/// <para>
/// This method has already been done.
/// </para>
/// <para>
/// -or-
/// </para>
/// <para>
/// The client request is not a WebSocket handshake request.
/// </para>
/// </exception>
public HttpListenerWebSocketContext AcceptWebSocket (
string protocol,
Action<WebSocket> initializer
)
{
if (_websocketContext != null) {
var msg = "The method has already been done.";
throw new InvalidOperationException (msg);
}
if (!_request.IsWebSocketRequest) {
var msg = "The request is not a WebSocket handshake request.";
throw new InvalidOperationException (msg);
}
if (protocol != null) {
if (protocol.Length == 0) {
var msg = "An empty string.";
throw new ArgumentException (msg, "protocol");
}
if (!protocol.IsToken ()) {
var msg = "It contains an invalid character.";
throw new ArgumentException (msg, "protocol");
}
}
var ret = GetWebSocketContext (protocol);
var ws = ret.WebSocket;
if (initializer != null) {
try {
initializer (ws);
}
catch (Exception ex) {
if (ws.ReadyState == WebSocketState.New)
_websocketContext = null;
var msg = "It caused an exception.";
throw new ArgumentException (msg, "initializer", ex);
}
}
ws.Accept ();
return ret;
}
#endregion
}
}

View File

@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: a273b442ff77f394d94e4c5c941c48d7

View File

@ -0,0 +1,140 @@
#region License
/*
* HttpListenerException.cs
*
* This code is derived from HttpListenerException.cs (System.Net) of Mono
* (http://www.mono-project.com).
*
* The MIT License
*
* Copyright (c) 2005 Novell, Inc. (http://www.novell.com)
* Copyright (c) 2012-2024 sta.blockhead
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
#endregion
#region Authors
/*
* Authors:
* - Gonzalo Paniagua Javier <gonzalo@novell.com>
*/
#endregion
using System;
using System.ComponentModel;
using System.Runtime.Serialization;
namespace WebSocketSharp.Net
{
/// <summary>
/// The exception that is thrown when an error occurs processing
/// an HTTP request.
/// </summary>
[Serializable]
public class HttpListenerException : Win32Exception
{
#region Protected Constructors
/// <summary>
/// Initializes a new instance of the <see cref="HttpListenerException"/>
/// class with the specified serialized data.
/// </summary>
/// <param name="serializationInfo">
/// A <see cref="SerializationInfo"/> that contains the serialized
/// object data.
/// </param>
/// <param name="streamingContext">
/// A <see cref="StreamingContext"/> that specifies the source for
/// the deserialization.
/// </param>
/// <exception cref="ArgumentNullException">
/// <paramref name="serializationInfo"/> is <see langword="null"/>.
/// </exception>
protected HttpListenerException (
SerializationInfo serializationInfo,
StreamingContext streamingContext
)
: base (serializationInfo, streamingContext)
{
}
#endregion
#region Public Constructors
/// <summary>
/// Initializes a new instance of the <see cref="HttpListenerException"/>
/// class.
/// </summary>
public HttpListenerException ()
{
}
/// <summary>
/// Initializes a new instance of the <see cref="HttpListenerException"/>
/// class with the specified error code.
/// </summary>
/// <param name="errorCode">
/// An <see cref="int"/> that specifies the error code.
/// </param>
public HttpListenerException (int errorCode)
: base (errorCode)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="HttpListenerException"/>
/// class with the specified error code and message.
/// </summary>
/// <param name="errorCode">
/// An <see cref="int"/> that specifies the error code.
/// </param>
/// <param name="message">
/// A <see cref="string"/> that specifies the message.
/// </param>
public HttpListenerException (int errorCode, string message)
: base (errorCode, message)
{
}
#endregion
#region Public Properties
/// <summary>
/// Gets the error code that identifies the error that occurred.
/// </summary>
/// <value>
/// <para>
/// An <see cref="int"/> that represents the error code.
/// </para>
/// <para>
/// It is any of the Win32 error codes.
/// </para>
/// </value>
public override int ErrorCode {
get {
return NativeErrorCode;
}
}
#endregion
}
}

View File

@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: 07dd63c18a8033d40a377a29d705ff58

View File

@ -0,0 +1,243 @@
#region License
/*
* HttpListenerPrefix.cs
*
* This code is derived from ListenerPrefix.cs (System.Net) of Mono
* (http://www.mono-project.com).
*
* The MIT License
*
* Copyright (c) 2005 Novell, Inc. (http://www.novell.com)
* Copyright (c) 2012-2024 sta.blockhead
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
#endregion
#region Authors
/*
* Authors:
* - Gonzalo Paniagua Javier <gonzalo@novell.com>
* - Oleg Mihailik <mihailik@gmail.com>
*/
#endregion
using System;
namespace WebSocketSharp.Net
{
internal sealed class HttpListenerPrefix
{
#region Private Fields
private string _host;
private bool _isSecure;
private HttpListener _listener;
private string _original;
private string _path;
private string _port;
private string _prefix;
private string _scheme;
#endregion
#region Internal Constructors
internal HttpListenerPrefix (string uriPrefix, HttpListener listener)
{
_original = uriPrefix;
_listener = listener;
parse (uriPrefix);
}
#endregion
#region Public Properties
public string Host {
get {
return _host;
}
}
public bool IsSecure {
get {
return _isSecure;
}
}
public HttpListener Listener {
get {
return _listener;
}
}
public string Original {
get {
return _original;
}
}
public string Path {
get {
return _path;
}
}
public string Port {
get {
return _port;
}
}
public string Scheme {
get {
return _scheme;
}
}
#endregion
#region Private Methods
private void parse (string uriPrefix)
{
var compType = StringComparison.Ordinal;
_isSecure = uriPrefix.StartsWith ("https", compType);
_scheme = _isSecure ? "https" : "http";
var hostStartIdx = uriPrefix.IndexOf (':') + 3;
var len = uriPrefix.Length;
var rootIdx = uriPrefix
.IndexOf ('/', hostStartIdx + 1, len - hostStartIdx - 1);
var colonIdx = uriPrefix
.LastIndexOf (':', rootIdx - 1, rootIdx - hostStartIdx - 1);
var hasPort = uriPrefix[rootIdx - 1] != ']' && colonIdx > hostStartIdx;
if (hasPort) {
_host = uriPrefix.Substring (hostStartIdx, colonIdx - hostStartIdx);
_port = uriPrefix.Substring (colonIdx + 1, rootIdx - colonIdx - 1);
}
else {
_host = uriPrefix.Substring (hostStartIdx, rootIdx - hostStartIdx);
_port = _isSecure ? "443" : "80";
}
_path = uriPrefix.Substring (rootIdx);
var fmt = "{0}://{1}:{2}{3}";
_prefix = String.Format (fmt, _scheme, _host, _port, _path);
}
#endregion
#region Public Methods
public static void CheckPrefix (string uriPrefix)
{
if (uriPrefix == null)
throw new ArgumentNullException ("uriPrefix");
var len = uriPrefix.Length;
if (len == 0) {
var msg = "An empty string.";
throw new ArgumentException (msg, "uriPrefix");
}
var compType = StringComparison.Ordinal;
var isHttpSchm = uriPrefix.StartsWith ("http://", compType)
|| uriPrefix.StartsWith ("https://", compType);
if (!isHttpSchm) {
var msg = "The scheme is not http or https.";
throw new ArgumentException (msg, "uriPrefix");
}
var endIdx = len - 1;
if (uriPrefix[endIdx] != '/') {
var msg = "It ends without a forward slash.";
throw new ArgumentException (msg, "uriPrefix");
}
var hostStartIdx = uriPrefix.IndexOf (':') + 3;
if (hostStartIdx >= endIdx) {
var msg = "No host is specified.";
throw new ArgumentException (msg, "uriPrefix");
}
if (uriPrefix[hostStartIdx] == ':') {
var msg = "No host is specified.";
throw new ArgumentException (msg, "uriPrefix");
}
var rootIdx = uriPrefix.IndexOf ('/', hostStartIdx, len - hostStartIdx);
if (rootIdx == hostStartIdx) {
var msg = "No host is specified.";
throw new ArgumentException (msg, "uriPrefix");
}
if (uriPrefix[rootIdx - 1] == ':') {
var msg = "No port is specified.";
throw new ArgumentException (msg, "uriPrefix");
}
if (rootIdx == endIdx - 1) {
var msg = "No path is specified.";
throw new ArgumentException (msg, "uriPrefix");
}
}
public override bool Equals (object obj)
{
var pref = obj as HttpListenerPrefix;
return pref != null && _prefix.Equals (pref._prefix);
}
public override int GetHashCode ()
{
return _prefix.GetHashCode ();
}
public override string ToString ()
{
return _prefix;
}
#endregion
}
}

View File

@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: 9da8d497d19f7f745826de72945261d6

View File

@ -0,0 +1,295 @@
#region License
/*
* HttpListenerPrefixCollection.cs
*
* This code is derived from HttpListenerPrefixCollection.cs (System.Net) of Mono
* (http://www.mono-project.com).
*
* The MIT License
*
* Copyright (c) 2005 Novell, Inc. (http://www.novell.com)
* Copyright (c) 2012-2024 sta.blockhead
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
#endregion
#region Authors
/*
* Authors:
* - Gonzalo Paniagua Javier <gonzalo@novell.com>
*/
#endregion
using System;
using System.Collections;
using System.Collections.Generic;
namespace WebSocketSharp.Net
{
/// <summary>
/// Provides a collection used to store the URI prefixes for a instance of
/// the <see cref="HttpListener"/> class.
/// </summary>
/// <remarks>
/// The <see cref="HttpListener"/> instance responds to the request which
/// has a requested URI that the prefixes most closely match.
/// </remarks>
public class HttpListenerPrefixCollection : ICollection<string>
{
#region Private Fields
private HttpListener _listener;
private List<string> _prefixes;
#endregion
#region Internal Constructors
internal HttpListenerPrefixCollection (HttpListener listener)
{
_listener = listener;
_prefixes = new List<string> ();
}
#endregion
#region Public Properties
/// <summary>
/// Gets the number of prefixes in the collection.
/// </summary>
/// <value>
/// An <see cref="int"/> that represents the number of prefixes.
/// </value>
public int Count {
get {
return _prefixes.Count;
}
}
/// <summary>
/// Gets a value indicating whether the access to the collection is
/// read-only.
/// </summary>
/// <value>
/// Always returns <c>false</c>.
/// </value>
public bool IsReadOnly {
get {
return false;
}
}
/// <summary>
/// Gets a value indicating whether the access to the collection is
/// synchronized.
/// </summary>
/// <value>
/// Always returns <c>false</c>.
/// </value>
public bool IsSynchronized {
get {
return false;
}
}
#endregion
#region Public Methods
/// <summary>
/// Adds the specified URI prefix to the collection.
/// </summary>
/// <param name="uriPrefix">
/// <para>
/// A <see cref="string"/> that specifies the URI prefix to add.
/// </para>
/// <para>
/// It must be a well-formed URI prefix with http or https scheme,
/// and must end with a forward slash (/).
/// </para>
/// </param>
/// <exception cref="ArgumentException">
/// <paramref name="uriPrefix"/> is invalid.
/// </exception>
/// <exception cref="ArgumentNullException">
/// <paramref name="uriPrefix"/> is <see langword="null"/>.
/// </exception>
/// <exception cref="ObjectDisposedException">
/// The <see cref="HttpListener"/> instance associated with this
/// collection is closed.
/// </exception>
public void Add (string uriPrefix)
{
_listener.CheckDisposed ();
HttpListenerPrefix.CheckPrefix (uriPrefix);
if (_prefixes.Contains (uriPrefix))
return;
if (_listener.IsListening)
EndPointManager.AddPrefix (uriPrefix, _listener);
_prefixes.Add (uriPrefix);
}
/// <summary>
/// Removes all URI prefixes from the collection.
/// </summary>
/// <exception cref="ObjectDisposedException">
/// The <see cref="HttpListener"/> instance associated with this
/// collection is closed.
/// </exception>
public void Clear ()
{
_listener.CheckDisposed ();
if (_listener.IsListening)
EndPointManager.RemoveListener (_listener);
_prefixes.Clear ();
}
/// <summary>
/// Returns a value indicating whether the collection contains the
/// specified URI prefix.
/// </summary>
/// <returns>
/// <c>true</c> if the collection contains the URI prefix; otherwise,
/// <c>false</c>.
/// </returns>
/// <param name="uriPrefix">
/// A <see cref="string"/> that specifies the URI prefix to test.
/// </param>
/// <exception cref="ArgumentNullException">
/// <paramref name="uriPrefix"/> is <see langword="null"/>.
/// </exception>
/// <exception cref="ObjectDisposedException">
/// The <see cref="HttpListener"/> instance associated with this
/// collection is closed.
/// </exception>
public bool Contains (string uriPrefix)
{
_listener.CheckDisposed ();
if (uriPrefix == null)
throw new ArgumentNullException ("uriPrefix");
return _prefixes.Contains (uriPrefix);
}
/// <summary>
/// Copies the contents of the collection to the specified array of string.
/// </summary>
/// <param name="array">
/// An array of <see cref="string"/> that specifies the destination of
/// the URI prefix strings copied from the collection.
/// </param>
/// <param name="offset">
/// An <see cref="int"/> that specifies the zero-based index in
/// the array at which copying begins.
/// </param>
/// <exception cref="ArgumentException">
/// The space from <paramref name="offset"/> to the end of
/// <paramref name="array"/> is not enough to copy to.
/// </exception>
/// <exception cref="ArgumentNullException">
/// <paramref name="array"/> is <see langword="null"/>.
/// </exception>
/// <exception cref="ArgumentOutOfRangeException">
/// <paramref name="offset"/> is less than zero.
/// </exception>
/// <exception cref="ObjectDisposedException">
/// The <see cref="HttpListener"/> instance associated with this
/// collection is closed.
/// </exception>
public void CopyTo (string[] array, int offset)
{
_listener.CheckDisposed ();
_prefixes.CopyTo (array, offset);
}
/// <summary>
/// Gets the enumerator that iterates through the collection.
/// </summary>
/// <returns>
/// An <see cref="T:System.Collections.Generic.IEnumerator{string}"/>
/// instance that can be used to iterate through the collection.
/// </returns>
public IEnumerator<string> GetEnumerator ()
{
return _prefixes.GetEnumerator ();
}
/// <summary>
/// Removes the specified URI prefix from the collection.
/// </summary>
/// <returns>
/// <c>true</c> if the URI prefix is successfully removed; otherwise,
/// <c>false</c>.
/// </returns>
/// <param name="uriPrefix">
/// A <see cref="string"/> that specifies the URI prefix to remove.
/// </param>
/// <exception cref="ArgumentNullException">
/// <paramref name="uriPrefix"/> is <see langword="null"/>.
/// </exception>
/// <exception cref="ObjectDisposedException">
/// The <see cref="HttpListener"/> instance associated with this
/// collection is closed.
/// </exception>
public bool Remove (string uriPrefix)
{
_listener.CheckDisposed ();
if (uriPrefix == null)
throw new ArgumentNullException ("uriPrefix");
if (!_prefixes.Contains (uriPrefix))
return false;
if (_listener.IsListening)
EndPointManager.RemovePrefix (uriPrefix, _listener);
return _prefixes.Remove (uriPrefix);
}
#endregion
#region Explicit Interface Implementations
/// <summary>
/// Gets the enumerator that iterates through the collection.
/// </summary>
/// <returns>
/// An <see cref="IEnumerator"/> instance that can be used to iterate
/// through the collection.
/// </returns>
IEnumerator IEnumerable.GetEnumerator ()
{
return _prefixes.GetEnumerator ();
}
#endregion
}
}

View File

@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: 9940f054c5d5b5240a1491e9c6c82159

View File

@ -0,0 +1,943 @@
#region License
/*
* HttpListenerRequest.cs
*
* This code is derived from HttpListenerRequest.cs (System.Net) of Mono
* (http://www.mono-project.com).
*
* The MIT License
*
* Copyright (c) 2005 Novell, Inc. (http://www.novell.com)
* Copyright (c) 2012-2024 sta.blockhead
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
#endregion
#region Authors
/*
* Authors:
* - Gonzalo Paniagua Javier <gonzalo@novell.com>
*/
#endregion
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Globalization;
using System.IO;
using System.Security.Cryptography.X509Certificates;
using System.Text;
namespace WebSocketSharp.Net
{
/// <summary>
/// Represents an incoming HTTP request to a <see cref="HttpListener"/>
/// instance.
/// </summary>
/// <remarks>
/// This class cannot be inherited.
/// </remarks>
public sealed class HttpListenerRequest
{
#region Private Fields
private static readonly byte[] _100continue;
private string[] _acceptTypes;
private bool _chunked;
private HttpConnection _connection;
private Encoding _contentEncoding;
private long _contentLength;
private HttpListenerContext _context;
private CookieCollection _cookies;
private static readonly Encoding _defaultEncoding;
private WebHeaderCollection _headers;
private string _httpMethod;
private Stream _inputStream;
private Version _protocolVersion;
private NameValueCollection _queryString;
private string _rawUrl;
private Guid _requestTraceIdentifier;
private Uri _url;
private Uri _urlReferrer;
private bool _urlSet;
private string _userHostName;
private string[] _userLanguages;
#endregion
#region Static Constructor
static HttpListenerRequest ()
{
_100continue = Encoding.ASCII.GetBytes ("HTTP/1.1 100 Continue\r\n\r\n");
_defaultEncoding = Encoding.UTF8;
}
#endregion
#region Internal Constructors
internal HttpListenerRequest (HttpListenerContext context)
{
_context = context;
_connection = context.Connection;
_contentLength = -1;
_headers = new WebHeaderCollection ();
_requestTraceIdentifier = Guid.NewGuid ();
}
#endregion
#region Public Properties
/// <summary>
/// Gets the media types that are acceptable for the client.
/// </summary>
/// <value>
/// <para>
/// An array of <see cref="string"/> that contains the names of
/// the media types specified in the value of the Accept header.
/// </para>
/// <para>
/// <see langword="null"/> if the header is not present.
/// </para>
/// </value>
public string[] AcceptTypes {
get {
var val = _headers["Accept"];
if (val == null)
return null;
if (_acceptTypes == null) {
_acceptTypes = val
.SplitHeaderValue (',')
.TrimEach ()
.ToList ()
.ToArray ();
}
return _acceptTypes;
}
}
/// <summary>
/// Gets an error code that identifies a problem with the certificate
/// provided by the client.
/// </summary>
/// <value>
/// An <see cref="int"/> that represents an error code.
/// </value>
/// <exception cref="NotSupportedException">
/// This property is not supported.
/// </exception>
public int ClientCertificateError {
get {
throw new NotSupportedException ();
}
}
/// <summary>
/// Gets the encoding for the entity body data included in the request.
/// </summary>
/// <value>
/// <para>
/// A <see cref="Encoding"/> converted from the charset value of the
/// Content-Type header.
/// </para>
/// <para>
/// <see cref="Encoding.UTF8"/> if the charset value is not available.
/// </para>
/// </value>
public Encoding ContentEncoding {
get {
if (_contentEncoding == null)
_contentEncoding = getContentEncoding ();
return _contentEncoding;
}
}
/// <summary>
/// Gets the length in bytes of the entity body data included in the
/// request.
/// </summary>
/// <value>
/// <para>
/// A <see cref="long"/> converted from the value of the Content-Length
/// header.
/// </para>
/// <para>
/// -1 if the header is not present.
/// </para>
/// </value>
public long ContentLength64 {
get {
return _contentLength;
}
}
/// <summary>
/// Gets the media type of the entity body data included in the request.
/// </summary>
/// <value>
/// <para>
/// A <see cref="string"/> that represents the value of the Content-Type
/// header.
/// </para>
/// <para>
/// <see langword="null"/> if the header is not present.
/// </para>
/// </value>
public string ContentType {
get {
return _headers["Content-Type"];
}
}
/// <summary>
/// Gets the HTTP cookies included in the request.
/// </summary>
/// <value>
/// <para>
/// A <see cref="CookieCollection"/> that contains the cookies.
/// </para>
/// <para>
/// An empty collection if not included.
/// </para>
/// </value>
public CookieCollection Cookies {
get {
if (_cookies == null)
_cookies = _headers.GetCookies (false);
return _cookies;
}
}
/// <summary>
/// Gets a value indicating whether the request has the entity body data.
/// </summary>
/// <value>
/// <c>true</c> if the request has the entity body data; otherwise,
/// <c>false</c>.
/// </value>
public bool HasEntityBody {
get {
return _contentLength > 0 || _chunked;
}
}
/// <summary>
/// Gets the HTTP headers included in the request.
/// </summary>
/// <value>
/// A <see cref="NameValueCollection"/> that contains the headers.
/// </value>
public NameValueCollection Headers {
get {
return _headers;
}
}
/// <summary>
/// Gets the HTTP method specified by the client.
/// </summary>
/// <value>
/// A <see cref="string"/> that represents the HTTP method specified in
/// the request line.
/// </value>
public string HttpMethod {
get {
return _httpMethod;
}
}
/// <summary>
/// Gets a stream that contains the entity body data included in
/// the request.
/// </summary>
/// <value>
/// <para>
/// A <see cref="Stream"/> that contains the entity body data.
/// </para>
/// <para>
/// <see cref="Stream.Null"/> if the entity body data is not available.
/// </para>
/// </value>
public Stream InputStream {
get {
if (_inputStream == null) {
_inputStream = _contentLength > 0 || _chunked
? _connection
.GetRequestStream (_contentLength, _chunked)
: Stream.Null;
}
return _inputStream;
}
}
/// <summary>
/// Gets a value indicating whether the client is authenticated.
/// </summary>
/// <value>
/// <c>true</c> if the client is authenticated; otherwise, <c>false</c>.
/// </value>
public bool IsAuthenticated {
get {
return _context.User != null;
}
}
/// <summary>
/// Gets a value indicating whether the request is sent from the
/// local computer.
/// </summary>
/// <value>
/// <c>true</c> if the request is sent from the same computer as
/// the server; otherwise, <c>false</c>.
/// </value>
public bool IsLocal {
get {
return _connection.IsLocal;
}
}
/// <summary>
/// Gets a value indicating whether a secure connection is used to send
/// the request.
/// </summary>
/// <value>
/// <c>true</c> if the connection is secure; otherwise, <c>false</c>.
/// </value>
public bool IsSecureConnection {
get {
return _connection.IsSecure;
}
}
/// <summary>
/// Gets a value indicating whether the request is a WebSocket handshake
/// request.
/// </summary>
/// <value>
/// <c>true</c> if the request is a WebSocket handshake request; otherwise,
/// <c>false</c>.
/// </value>
public bool IsWebSocketRequest {
get {
return _httpMethod == "GET" && _headers.Upgrades ("websocket");
}
}
/// <summary>
/// Gets a value indicating whether a persistent connection is requested.
/// </summary>
/// <value>
/// <c>true</c> if the request specifies that the connection is kept open;
/// otherwise, <c>false</c>.
/// </value>
public bool KeepAlive {
get {
return _headers.KeepsAlive (_protocolVersion);
}
}
/// <summary>
/// Gets the endpoint to which the request is sent.
/// </summary>
/// <value>
/// A <see cref="System.Net.IPEndPoint"/> that represents the server
/// IP address and port number.
/// </value>
public System.Net.IPEndPoint LocalEndPoint {
get {
return _connection.LocalEndPoint;
}
}
/// <summary>
/// Gets the HTTP version specified by the client.
/// </summary>
/// <value>
/// A <see cref="Version"/> that represents the HTTP version specified in
/// the request line.
/// </value>
public Version ProtocolVersion {
get {
return _protocolVersion;
}
}
/// <summary>
/// Gets the query string included in the request.
/// </summary>
/// <value>
/// <para>
/// A <see cref="NameValueCollection"/> that contains the query
/// parameters.
/// </para>
/// <para>
/// Each query parameter is decoded in UTF-8.
/// </para>
/// <para>
/// An empty collection if not included.
/// </para>
/// </value>
public NameValueCollection QueryString {
get {
if (_queryString == null) {
var url = Url;
var query = url != null ? url.Query : null;
_queryString = QueryStringCollection.Parse (query, _defaultEncoding);
}
return _queryString;
}
}
/// <summary>
/// Gets the raw URL specified by the client.
/// </summary>
/// <value>
/// A <see cref="string"/> that represents the request target specified in
/// the request line.
/// </value>
public string RawUrl {
get {
return _rawUrl;
}
}
/// <summary>
/// Gets the endpoint from which the request is sent.
/// </summary>
/// <value>
/// A <see cref="System.Net.IPEndPoint"/> that represents the client
/// IP address and port number.
/// </value>
public System.Net.IPEndPoint RemoteEndPoint {
get {
return _connection.RemoteEndPoint;
}
}
/// <summary>
/// Gets the trace identifier of the request.
/// </summary>
/// <value>
/// A <see cref="Guid"/> that represents the trace identifier.
/// </value>
public Guid RequestTraceIdentifier {
get {
return _requestTraceIdentifier;
}
}
/// <summary>
/// Gets the URL requested by the client.
/// </summary>
/// <value>
/// <para>
/// A <see cref="Uri"/> that represents the URL parsed from the request.
/// </para>
/// <para>
/// <see langword="null"/> if the URL cannot be parsed.
/// </para>
/// </value>
public Uri Url {
get {
if (!_urlSet) {
_url = HttpUtility
.CreateRequestUrl (
_rawUrl,
_userHostName,
IsWebSocketRequest,
IsSecureConnection
);
_urlSet = true;
}
return _url;
}
}
/// <summary>
/// Gets the URI of the resource from which the requested URL was obtained.
/// </summary>
/// <value>
/// <para>
/// A <see cref="Uri"/> that represents the value of the Referer header.
/// </para>
/// <para>
/// <see langword="null"/> if the header value is not available.
/// </para>
/// </value>
public Uri UrlReferrer {
get {
var val = _headers["Referer"];
if (val == null)
return null;
if (_urlReferrer == null)
_urlReferrer = val.ToUri ();
return _urlReferrer;
}
}
/// <summary>
/// Gets the user agent from which the request is originated.
/// </summary>
/// <value>
/// <para>
/// A <see cref="string"/> that represents the value of the User-Agent
/// header.
/// </para>
/// <para>
/// <see langword="null"/> if the header is not present.
/// </para>
/// </value>
public string UserAgent {
get {
return _headers["User-Agent"];
}
}
/// <summary>
/// Gets the IP address and port number to which the request is sent.
/// </summary>
/// <value>
/// A <see cref="string"/> that represents the server IP address and
/// port number.
/// </value>
public string UserHostAddress {
get {
return _connection.LocalEndPoint.ToString ();
}
}
/// <summary>
/// Gets the server host name requested by the client.
/// </summary>
/// <value>
/// <para>
/// A <see cref="string"/> that represents the value of the Host header.
/// </para>
/// <para>
/// It includes the port number if provided.
/// </para>
/// </value>
public string UserHostName {
get {
return _userHostName;
}
}
/// <summary>
/// Gets the natural languages that are acceptable for the client.
/// </summary>
/// <value>
/// <para>
/// An array of <see cref="string"/> that contains the names of the
/// natural languages specified in the value of the Accept-Language
/// header.
/// </para>
/// <para>
/// <see langword="null"/> if the header is not present.
/// </para>
/// </value>
public string[] UserLanguages {
get {
var val = _headers["Accept-Language"];
if (val == null)
return null;
if (_userLanguages == null)
_userLanguages = val.Split (',').TrimEach ().ToList ().ToArray ();
return _userLanguages;
}
}
#endregion
#region Private Methods
private Encoding getContentEncoding ()
{
var val = _headers["Content-Type"];
if (val == null)
return _defaultEncoding;
Encoding ret;
return HttpUtility.TryGetEncoding (val, out ret)
? ret
: _defaultEncoding;
}
#endregion
#region Internal Methods
internal void AddHeader (string headerField)
{
var start = headerField[0];
if (start == ' ' || start == '\t') {
_context.ErrorMessage = "Invalid header field";
return;
}
var colon = headerField.IndexOf (':');
if (colon < 1) {
_context.ErrorMessage = "Invalid header field";
return;
}
var name = headerField.Substring (0, colon).Trim ();
if (name.Length == 0 || !name.IsToken ()) {
_context.ErrorMessage = "Invalid header name";
return;
}
var val = colon < headerField.Length - 1
? headerField.Substring (colon + 1).Trim ()
: String.Empty;
_headers.InternalSet (name, val, false);
var lower = name.ToLower (CultureInfo.InvariantCulture);
if (lower == "host") {
if (_userHostName != null) {
_context.ErrorMessage = "Invalid Host header";
return;
}
if (val.Length == 0) {
_context.ErrorMessage = "Invalid Host header";
return;
}
_userHostName = val;
return;
}
if (lower == "content-length") {
if (_contentLength > -1) {
_context.ErrorMessage = "Invalid Content-Length header";
return;
}
long len;
if (!Int64.TryParse (val, out len)) {
_context.ErrorMessage = "Invalid Content-Length header";
return;
}
if (len < 0) {
_context.ErrorMessage = "Invalid Content-Length header";
return;
}
_contentLength = len;
return;
}
}
internal void FinishInitialization ()
{
if (_userHostName == null) {
_context.ErrorMessage = "Host header required";
return;
}
var transferEnc = _headers["Transfer-Encoding"];
if (transferEnc != null) {
var compType = StringComparison.OrdinalIgnoreCase;
if (!transferEnc.Equals ("chunked", compType)) {
_context.ErrorStatusCode = 501;
_context.ErrorMessage = "Invalid Transfer-Encoding header";
return;
}
_chunked = true;
}
if (_httpMethod == "POST" || _httpMethod == "PUT") {
if (_contentLength == -1 && !_chunked) {
_context.ErrorStatusCode = 411;
_context.ErrorMessage = "Content-Length header required";
return;
}
if (_contentLength == 0 && !_chunked) {
_context.ErrorStatusCode = 411;
_context.ErrorMessage = "Invalid Content-Length header";
return;
}
}
var expect = _headers["Expect"];
if (expect != null) {
var compType = StringComparison.OrdinalIgnoreCase;
if (!expect.Equals ("100-continue", compType)) {
_context.ErrorStatusCode = 417;
_context.ErrorMessage = "Invalid Expect header";
return;
}
var output = _connection.GetResponseStream ();
output.InternalWrite (_100continue, 0, _100continue.Length);
}
}
internal bool FlushInput ()
{
var input = InputStream;
if (input == Stream.Null)
return true;
var len = 2048;
if (_contentLength > 0 && _contentLength < len)
len = (int) _contentLength;
var buff = new byte[len];
while (true) {
try {
var ares = input.BeginRead (buff, 0, len, null, null);
if (!ares.IsCompleted) {
var timeout = 100;
if (!ares.AsyncWaitHandle.WaitOne (timeout))
return false;
}
if (input.EndRead (ares) <= 0)
return true;
}
catch {
return false;
}
}
}
internal bool IsUpgradeRequest (string protocol)
{
return _headers.Upgrades (protocol);
}
internal void SetRequestLine (string requestLine)
{
var parts = requestLine.Split (new[] { ' ' }, 3);
if (parts.Length < 3) {
_context.ErrorMessage = "Invalid request line (parts)";
return;
}
var method = parts[0];
if (method.Length == 0) {
_context.ErrorMessage = "Invalid request line (method)";
return;
}
if (!method.IsHttpMethod ()) {
_context.ErrorStatusCode = 501;
_context.ErrorMessage = "Invalid request line (method)";
return;
}
var target = parts[1];
if (target.Length == 0) {
_context.ErrorMessage = "Invalid request line (target)";
return;
}
var rawVer = parts[2];
if (rawVer.Length != 8) {
_context.ErrorMessage = "Invalid request line (version)";
return;
}
if (!rawVer.StartsWith ("HTTP/", StringComparison.Ordinal)) {
_context.ErrorMessage = "Invalid request line (version)";
return;
}
Version ver;
if (!rawVer.Substring (5).TryCreateVersion (out ver)) {
_context.ErrorMessage = "Invalid request line (version)";
return;
}
if (ver != HttpVersion.Version11) {
_context.ErrorStatusCode = 505;
_context.ErrorMessage = "Invalid request line (version)";
return;
}
_httpMethod = method;
_rawUrl = target;
_protocolVersion = ver;
}
#endregion
#region Public Methods
/// <summary>
/// Begins getting the certificate provided by the client asynchronously.
/// </summary>
/// <returns>
/// An <see cref="IAsyncResult"/> instance that represents the status of
/// the asynchronous operation.
/// </returns>
/// <param name="requestCallback">
/// <para>
/// An <see cref="AsyncCallback"/> delegate.
/// </para>
/// <para>
/// It specifies the delegate called when the asynchronous operation is
/// complete.
/// </para>
/// </param>
/// <param name="state">
/// An <see cref="object"/> that specifies a user defined object to pass to
/// <paramref name="requestCallback"/>.
/// </param>
/// <exception cref="NotSupportedException">
/// This method is not supported.
/// </exception>
public IAsyncResult BeginGetClientCertificate (
AsyncCallback requestCallback,
object state
)
{
throw new NotSupportedException ();
}
/// <summary>
/// Ends an asynchronous operation to get the certificate provided by
/// the client.
/// </summary>
/// <returns>
/// A <see cref="X509Certificate2"/> that represents an X.509 certificate
/// provided by the client.
/// </returns>
/// <param name="asyncResult">
/// An <see cref="IAsyncResult"/> instance obtained by calling
/// the <see cref="BeginGetClientCertificate"/> method.
/// </param>
/// <exception cref="NotSupportedException">
/// This method is not supported.
/// </exception>
public X509Certificate2 EndGetClientCertificate (IAsyncResult asyncResult)
{
throw new NotSupportedException ();
}
/// <summary>
/// Gets the certificate provided by the client.
/// </summary>
/// <returns>
/// A <see cref="X509Certificate2"/> that represents an X.509 certificate
/// provided by the client.
/// </returns>
/// <exception cref="NotSupportedException">
/// This method is not supported.
/// </exception>
public X509Certificate2 GetClientCertificate ()
{
throw new NotSupportedException ();
}
/// <summary>
/// Returns a string that represents the current instance.
/// </summary>
/// <returns>
/// A <see cref="string"/> that contains the request line and headers
/// included in the request.
/// </returns>
public override string ToString ()
{
var buff = new StringBuilder (64);
var fmt = "{0} {1} HTTP/{2}\r\n";
var headers = _headers.ToString ();
buff
.AppendFormat (fmt, _httpMethod, _rawUrl, _protocolVersion)
.Append (headers);
return buff.ToString ();
}
#endregion
}
}

View File

@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: 74456f8199f4b2c4aae6bd8089faf59a

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: 33da38aab487ebd449ffa8848b25d89f

View File

@ -0,0 +1,233 @@
#region License
/*
* HttpRequestHeader.cs
*
* This code is derived from HttpRequestHeader.cs (System.Net) of Mono
* (http://www.mono-project.com).
*
* The MIT License
*
* Copyright (c) 2005 Novell, Inc. (http://www.novell.com)
* Copyright (c) 2014-2020 sta.blockhead
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
#endregion
#region Authors
/*
* Authors:
* - Gonzalo Paniagua Javier <gonzalo@novell.com>
*/
#endregion
namespace WebSocketSharp.Net
{
/// <summary>
/// Indicates the HTTP header that may be specified in a client request.
/// </summary>
/// <remarks>
/// The headers of this enumeration are defined in
/// <see href="http://tools.ietf.org/html/rfc2616#section-14">RFC 2616</see> or
/// <see href="http://tools.ietf.org/html/rfc6455#section-11.3">RFC 6455</see>.
/// </remarks>
public enum HttpRequestHeader
{
/// <summary>
/// Indicates the Cache-Control header.
/// </summary>
CacheControl,
/// <summary>
/// Indicates the Connection header.
/// </summary>
Connection,
/// <summary>
/// Indicates the Date header.
/// </summary>
Date,
/// <summary>
/// Indicates the Keep-Alive header.
/// </summary>
KeepAlive,
/// <summary>
/// Indicates the Pragma header.
/// </summary>
Pragma,
/// <summary>
/// Indicates the Trailer header.
/// </summary>
Trailer,
/// <summary>
/// Indicates the Transfer-Encoding header.
/// </summary>
TransferEncoding,
/// <summary>
/// Indicates the Upgrade header.
/// </summary>
Upgrade,
/// <summary>
/// Indicates the Via header.
/// </summary>
Via,
/// <summary>
/// Indicates the Warning header.
/// </summary>
Warning,
/// <summary>
/// Indicates the Allow header.
/// </summary>
Allow,
/// <summary>
/// Indicates the Content-Length header.
/// </summary>
ContentLength,
/// <summary>
/// Indicates the Content-Type header.
/// </summary>
ContentType,
/// <summary>
/// Indicates the Content-Encoding header.
/// </summary>
ContentEncoding,
/// <summary>
/// Indicates the Content-Language header.
/// </summary>
ContentLanguage,
/// <summary>
/// Indicates the Content-Location header.
/// </summary>
ContentLocation,
/// <summary>
/// Indicates the Content-MD5 header.
/// </summary>
ContentMd5,
/// <summary>
/// Indicates the Content-Range header.
/// </summary>
ContentRange,
/// <summary>
/// Indicates the Expires header.
/// </summary>
Expires,
/// <summary>
/// Indicates the Last-Modified header.
/// </summary>
LastModified,
/// <summary>
/// Indicates the Accept header.
/// </summary>
Accept,
/// <summary>
/// Indicates the Accept-Charset header.
/// </summary>
AcceptCharset,
/// <summary>
/// Indicates the Accept-Encoding header.
/// </summary>
AcceptEncoding,
/// <summary>
/// Indicates the Accept-Language header.
/// </summary>
AcceptLanguage,
/// <summary>
/// Indicates the Authorization header.
/// </summary>
Authorization,
/// <summary>
/// Indicates the Cookie header.
/// </summary>
Cookie,
/// <summary>
/// Indicates the Expect header.
/// </summary>
Expect,
/// <summary>
/// Indicates the From header.
/// </summary>
From,
/// <summary>
/// Indicates the Host header.
/// </summary>
Host,
/// <summary>
/// Indicates the If-Match header.
/// </summary>
IfMatch,
/// <summary>
/// Indicates the If-Modified-Since header.
/// </summary>
IfModifiedSince,
/// <summary>
/// Indicates the If-None-Match header.
/// </summary>
IfNoneMatch,
/// <summary>
/// Indicates the If-Range header.
/// </summary>
IfRange,
/// <summary>
/// Indicates the If-Unmodified-Since header.
/// </summary>
IfUnmodifiedSince,
/// <summary>
/// Indicates the Max-Forwards header.
/// </summary>
MaxForwards,
/// <summary>
/// Indicates the Proxy-Authorization header.
/// </summary>
ProxyAuthorization,
/// <summary>
/// Indicates the Referer header.
/// </summary>
Referer,
/// <summary>
/// Indicates the Range header.
/// </summary>
Range,
/// <summary>
/// Indicates the TE header.
/// </summary>
Te,
/// <summary>
/// Indicates the Translate header.
/// </summary>
Translate,
/// <summary>
/// Indicates the User-Agent header.
/// </summary>
UserAgent,
/// <summary>
/// Indicates the Sec-WebSocket-Key header.
/// </summary>
SecWebSocketKey,
/// <summary>
/// Indicates the Sec-WebSocket-Extensions header.
/// </summary>
SecWebSocketExtensions,
/// <summary>
/// Indicates the Sec-WebSocket-Protocol header.
/// </summary>
SecWebSocketProtocol,
/// <summary>
/// Indicates the Sec-WebSocket-Version header.
/// </summary>
SecWebSocketVersion
}
}

View File

@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: ffdc665e7f1df3b41bf94a12cb43defd

View File

@ -0,0 +1,189 @@
#region License
/*
* HttpResponseHeader.cs
*
* This code is derived from HttpResponseHeader.cs (System.Net) of Mono
* (http://www.mono-project.com).
*
* The MIT License
*
* Copyright (c) 2005 Novell, Inc. (http://www.novell.com)
* Copyright (c) 2014-2020 sta.blockhead
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
#endregion
#region Authors
/*
* Authors:
* - Gonzalo Paniagua Javier <gonzalo@novell.com>
*/
#endregion
namespace WebSocketSharp.Net
{
/// <summary>
/// Indicates the HTTP header that can be specified in a server response.
/// </summary>
/// <remarks>
/// The headers of this enumeration are defined in
/// <see href="http://tools.ietf.org/html/rfc2616#section-14">RFC 2616</see> or
/// <see href="http://tools.ietf.org/html/rfc6455#section-11.3">RFC 6455</see>.
/// </remarks>
public enum HttpResponseHeader
{
/// <summary>
/// Indicates the Cache-Control header.
/// </summary>
CacheControl,
/// <summary>
/// Indicates the Connection header.
/// </summary>
Connection,
/// <summary>
/// Indicates the Date header.
/// </summary>
Date,
/// <summary>
/// Indicates the Keep-Alive header.
/// </summary>
KeepAlive,
/// <summary>
/// Indicates the Pragma header.
/// </summary>
Pragma,
/// <summary>
/// Indicates the Trailer header.
/// </summary>
Trailer,
/// <summary>
/// Indicates the Transfer-Encoding header.
/// </summary>
TransferEncoding,
/// <summary>
/// Indicates the Upgrade header.
/// </summary>
Upgrade,
/// <summary>
/// Indicates the Via header.
/// </summary>
Via,
/// <summary>
/// Indicates the Warning header.
/// </summary>
Warning,
/// <summary>
/// Indicates the Allow header.
/// </summary>
Allow,
/// <summary>
/// Indicates the Content-Length header.
/// </summary>
ContentLength,
/// <summary>
/// Indicates the Content-Type header.
/// </summary>
ContentType,
/// <summary>
/// Indicates the Content-Encoding header.
/// </summary>
ContentEncoding,
/// <summary>
/// Indicates the Content-Language header.
/// </summary>
ContentLanguage,
/// <summary>
/// Indicates the Content-Location header.
/// </summary>
ContentLocation,
/// <summary>
/// Indicates the Content-MD5 header.
/// </summary>
ContentMd5,
/// <summary>
/// Indicates the Content-Range header.
/// </summary>
ContentRange,
/// <summary>
/// Indicates the Expires header.
/// </summary>
Expires,
/// <summary>
/// Indicates the Last-Modified header.
/// </summary>
LastModified,
/// <summary>
/// Indicates the Accept-Ranges header.
/// </summary>
AcceptRanges,
/// <summary>
/// Indicates the Age header.
/// </summary>
Age,
/// <summary>
/// Indicates the ETag header.
/// </summary>
ETag,
/// <summary>
/// Indicates the Location header.
/// </summary>
Location,
/// <summary>
/// Indicates the Proxy-Authenticate header.
/// </summary>
ProxyAuthenticate,
/// <summary>
/// Indicates the Retry-After header.
/// </summary>
RetryAfter,
/// <summary>
/// Indicates the Server header.
/// </summary>
Server,
/// <summary>
/// Indicates the Set-Cookie header.
/// </summary>
SetCookie,
/// <summary>
/// Indicates the Vary header.
/// </summary>
Vary,
/// <summary>
/// Indicates the WWW-Authenticate header.
/// </summary>
WwwAuthenticate,
/// <summary>
/// Indicates the Sec-WebSocket-Extensions header.
/// </summary>
SecWebSocketExtensions,
/// <summary>
/// Indicates the Sec-WebSocket-Accept header.
/// </summary>
SecWebSocketAccept,
/// <summary>
/// Indicates the Sec-WebSocket-Protocol header.
/// </summary>
SecWebSocketProtocol,
/// <summary>
/// Indicates the Sec-WebSocket-Version header.
/// </summary>
SecWebSocketVersion
}
}

View File

@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: 273615a0fa5cbad40806a4188f12a253

View File

@ -0,0 +1,346 @@
#region License
/*
* HttpStatusCode.cs
*
* This code is derived from HttpStatusCode.cs (System.Net) of Mono
* (http://www.mono-project.com).
*
* It was automatically generated from ECMA CLI XML Library Specification.
* Generator: libgen.xsl [1.0; (C) Sergey Chaban (serge@wildwestsoftware.com)]
* Created: Wed, 5 Sep 2001 06:32:05 UTC
* Source file: AllTypes.xml
* URL: http://msdn.microsoft.com/net/ecma/AllTypes.xml
*
* The MIT License
*
* Copyright (c) 2001 Ximian, Inc. (http://www.ximian.com)
* Copyright (c) 2012-2020 sta.blockhead
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
#endregion
namespace WebSocketSharp.Net
{
/// <summary>
/// Indicates the HTTP status code that can be specified in a server response.
/// </summary>
/// <remarks>
/// The values of this enumeration are defined in
/// <see href="http://tools.ietf.org/html/rfc2616#section-10">RFC 2616</see>.
/// </remarks>
public enum HttpStatusCode
{
/// <summary>
/// Equivalent to status code 100. Indicates that the client should continue
/// with its request.
/// </summary>
Continue = 100,
/// <summary>
/// Equivalent to status code 101. Indicates that the server is switching
/// the HTTP version or protocol on the connection.
/// </summary>
SwitchingProtocols = 101,
/// <summary>
/// Equivalent to status code 200. Indicates that the client's request has
/// succeeded.
/// </summary>
OK = 200,
/// <summary>
/// Equivalent to status code 201. Indicates that the client's request has
/// been fulfilled and resulted in a new resource being created.
/// </summary>
Created = 201,
/// <summary>
/// Equivalent to status code 202. Indicates that the client's request has
/// been accepted for processing, but the processing has not been completed.
/// </summary>
Accepted = 202,
/// <summary>
/// Equivalent to status code 203. Indicates that the returned metainformation
/// is from a local or a third-party copy instead of the origin server.
/// </summary>
NonAuthoritativeInformation = 203,
/// <summary>
/// Equivalent to status code 204. Indicates that the server has fulfilled
/// the client's request but does not need to return an entity-body.
/// </summary>
NoContent = 204,
/// <summary>
/// Equivalent to status code 205. Indicates that the server has fulfilled
/// the client's request, and the user agent should reset the document view
/// which caused the request to be sent.
/// </summary>
ResetContent = 205,
/// <summary>
/// Equivalent to status code 206. Indicates that the server has fulfilled
/// the partial GET request for the resource.
/// </summary>
PartialContent = 206,
/// <summary>
/// <para>
/// Equivalent to status code 300. Indicates that the requested resource
/// corresponds to any of multiple representations.
/// </para>
/// <para>
/// MultipleChoices is a synonym for Ambiguous.
/// </para>
/// </summary>
MultipleChoices = 300,
/// <summary>
/// <para>
/// Equivalent to status code 300. Indicates that the requested resource
/// corresponds to any of multiple representations.
/// </para>
/// <para>
/// Ambiguous is a synonym for MultipleChoices.
/// </para>
/// </summary>
Ambiguous = 300,
/// <summary>
/// <para>
/// Equivalent to status code 301. Indicates that the requested resource
/// has been assigned a new permanent URI and any future references to
/// this resource should use one of the returned URIs.
/// </para>
/// <para>
/// MovedPermanently is a synonym for Moved.
/// </para>
/// </summary>
MovedPermanently = 301,
/// <summary>
/// <para>
/// Equivalent to status code 301. Indicates that the requested resource
/// has been assigned a new permanent URI and any future references to
/// this resource should use one of the returned URIs.
/// </para>
/// <para>
/// Moved is a synonym for MovedPermanently.
/// </para>
/// </summary>
Moved = 301,
/// <summary>
/// <para>
/// Equivalent to status code 302. Indicates that the requested resource
/// is located temporarily under a different URI.
/// </para>
/// <para>
/// Found is a synonym for Redirect.
/// </para>
/// </summary>
Found = 302,
/// <summary>
/// <para>
/// Equivalent to status code 302. Indicates that the requested resource
/// is located temporarily under a different URI.
/// </para>
/// <para>
/// Redirect is a synonym for Found.
/// </para>
/// </summary>
Redirect = 302,
/// <summary>
/// <para>
/// Equivalent to status code 303. Indicates that the response to
/// the request can be found under a different URI and should be
/// retrieved using a GET method on that resource.
/// </para>
/// <para>
/// SeeOther is a synonym for RedirectMethod.
/// </para>
/// </summary>
SeeOther = 303,
/// <summary>
/// <para>
/// Equivalent to status code 303. Indicates that the response to
/// the request can be found under a different URI and should be
/// retrieved using a GET method on that resource.
/// </para>
/// <para>
/// RedirectMethod is a synonym for SeeOther.
/// </para>
/// </summary>
RedirectMethod = 303,
/// <summary>
/// Equivalent to status code 304. Indicates that the client has performed
/// a conditional GET request and access is allowed, but the document has
/// not been modified.
/// </summary>
NotModified = 304,
/// <summary>
/// Equivalent to status code 305. Indicates that the requested resource
/// must be accessed through the proxy given by the Location field.
/// </summary>
UseProxy = 305,
/// <summary>
/// Equivalent to status code 306. This status code was used in a previous
/// version of the specification, is no longer used, and is reserved for
/// future use.
/// </summary>
Unused = 306,
/// <summary>
/// <para>
/// Equivalent to status code 307. Indicates that the requested resource
/// is located temporarily under a different URI.
/// </para>
/// <para>
/// TemporaryRedirect is a synonym for RedirectKeepVerb.
/// </para>
/// </summary>
TemporaryRedirect = 307,
/// <summary>
/// <para>
/// Equivalent to status code 307. Indicates that the requested resource
/// is located temporarily under a different URI.
/// </para>
/// <para>
/// RedirectKeepVerb is a synonym for TemporaryRedirect.
/// </para>
/// </summary>
RedirectKeepVerb = 307,
/// <summary>
/// Equivalent to status code 400. Indicates that the client's request could
/// not be understood by the server due to malformed syntax.
/// </summary>
BadRequest = 400,
/// <summary>
/// Equivalent to status code 401. Indicates that the client's request
/// requires user authentication.
/// </summary>
Unauthorized = 401,
/// <summary>
/// Equivalent to status code 402. This status code is reserved for future
/// use.
/// </summary>
PaymentRequired = 402,
/// <summary>
/// Equivalent to status code 403. Indicates that the server understood
/// the client's request but is refusing to fulfill it.
/// </summary>
Forbidden = 403,
/// <summary>
/// Equivalent to status code 404. Indicates that the server has not found
/// anything matching the request URI.
/// </summary>
NotFound = 404,
/// <summary>
/// Equivalent to status code 405. Indicates that the method specified
/// in the request line is not allowed for the resource identified by
/// the request URI.
/// </summary>
MethodNotAllowed = 405,
/// <summary>
/// Equivalent to status code 406. Indicates that the server does not
/// have the appropriate resource to respond to the Accept headers in
/// the client's request.
/// </summary>
NotAcceptable = 406,
/// <summary>
/// Equivalent to status code 407. Indicates that the client must first
/// authenticate itself with the proxy.
/// </summary>
ProxyAuthenticationRequired = 407,
/// <summary>
/// Equivalent to status code 408. Indicates that the client did not produce
/// a request within the time that the server was prepared to wait.
/// </summary>
RequestTimeout = 408,
/// <summary>
/// Equivalent to status code 409. Indicates that the client's request could
/// not be completed due to a conflict on the server.
/// </summary>
Conflict = 409,
/// <summary>
/// Equivalent to status code 410. Indicates that the requested resource is
/// no longer available at the server and no forwarding address is known.
/// </summary>
Gone = 410,
/// <summary>
/// Equivalent to status code 411. Indicates that the server refuses to
/// accept the client's request without a defined Content-Length.
/// </summary>
LengthRequired = 411,
/// <summary>
/// Equivalent to status code 412. Indicates that the precondition given in
/// one or more of the request headers evaluated to false when it was tested
/// on the server.
/// </summary>
PreconditionFailed = 412,
/// <summary>
/// Equivalent to status code 413. Indicates that the entity of the client's
/// request is larger than the server is willing or able to process.
/// </summary>
RequestEntityTooLarge = 413,
/// <summary>
/// Equivalent to status code 414. Indicates that the request URI is longer
/// than the server is willing to interpret.
/// </summary>
RequestUriTooLong = 414,
/// <summary>
/// Equivalent to status code 415. Indicates that the entity of the client's
/// request is in a format not supported by the requested resource for the
/// requested method.
/// </summary>
UnsupportedMediaType = 415,
/// <summary>
/// Equivalent to status code 416. Indicates that none of the range
/// specifier values in a Range request header overlap the current
/// extent of the selected resource.
/// </summary>
RequestedRangeNotSatisfiable = 416,
/// <summary>
/// Equivalent to status code 417. Indicates that the expectation given in
/// an Expect request header could not be met by the server.
/// </summary>
ExpectationFailed = 417,
/// <summary>
/// Equivalent to status code 500. Indicates that the server encountered
/// an unexpected condition which prevented it from fulfilling the client's
/// request.
/// </summary>
InternalServerError = 500,
/// <summary>
/// Equivalent to status code 501. Indicates that the server does not
/// support the functionality required to fulfill the client's request.
/// </summary>
NotImplemented = 501,
/// <summary>
/// Equivalent to status code 502. Indicates that a gateway or proxy server
/// received an invalid response from the upstream server.
/// </summary>
BadGateway = 502,
/// <summary>
/// Equivalent to status code 503. Indicates that the server is currently
/// unable to handle the client's request due to a temporary overloading
/// or maintenance of the server.
/// </summary>
ServiceUnavailable = 503,
/// <summary>
/// Equivalent to status code 504. Indicates that a gateway or proxy server
/// did not receive a timely response from the upstream server or some other
/// auxiliary server.
/// </summary>
GatewayTimeout = 504,
/// <summary>
/// Equivalent to status code 505. Indicates that the server does not
/// support the HTTP version used in the client's request.
/// </summary>
HttpVersionNotSupported = 505,
}
}

View File

@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: b0ab739b61e8c01498c39a4ab5289949

View File

@ -0,0 +1,201 @@
#region License
/*
* HttpStreamAsyncResult.cs
*
* This code is derived from HttpStreamAsyncResult.cs (System.Net) of Mono
* (http://www.mono-project.com).
*
* The MIT License
*
* Copyright (c) 2005 Novell, Inc. (http://www.novell.com)
* Copyright (c) 2012-2021 sta.blockhead
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
#endregion
#region Authors
/*
* Authors:
* - Gonzalo Paniagua Javier <gonzalo@novell.com>
*/
#endregion
using System;
using System.Threading;
namespace WebSocketSharp.Net
{
internal class HttpStreamAsyncResult : IAsyncResult
{
#region Private Fields
private byte[] _buffer;
private AsyncCallback _callback;
private bool _completed;
private int _count;
private Exception _exception;
private int _offset;
private object _state;
private object _sync;
private int _syncRead;
private ManualResetEvent _waitHandle;
#endregion
#region Internal Constructors
internal HttpStreamAsyncResult (AsyncCallback callback, object state)
{
_callback = callback;
_state = state;
_sync = new object ();
}
#endregion
#region Internal Properties
internal byte[] Buffer {
get {
return _buffer;
}
set {
_buffer = value;
}
}
internal int Count {
get {
return _count;
}
set {
_count = value;
}
}
internal Exception Exception {
get {
return _exception;
}
}
internal bool HasException {
get {
return _exception != null;
}
}
internal int Offset {
get {
return _offset;
}
set {
_offset = value;
}
}
internal int SyncRead {
get {
return _syncRead;
}
set {
_syncRead = value;
}
}
#endregion
#region Public Properties
public object AsyncState {
get {
return _state;
}
}
public WaitHandle AsyncWaitHandle {
get {
lock (_sync) {
if (_waitHandle == null)
_waitHandle = new ManualResetEvent (_completed);
return _waitHandle;
}
}
}
public bool CompletedSynchronously {
get {
return _syncRead == _count;
}
}
public bool IsCompleted {
get {
lock (_sync)
return _completed;
}
}
#endregion
#region Internal Methods
internal void Complete ()
{
lock (_sync) {
if (_completed)
return;
_completed = true;
if (_waitHandle != null)
_waitHandle.Set ();
if (_callback != null)
_callback.BeginInvoke (this, ar => _callback.EndInvoke (ar), null);
}
}
internal void Complete (Exception exception)
{
lock (_sync) {
if (_completed)
return;
_completed = true;
_exception = exception;
if (_waitHandle != null)
_waitHandle.Set ();
if (_callback != null)
_callback.BeginInvoke (this, ar => _callback.EndInvoke (ar), null);
}
}
#endregion
}
}

View File

@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: 7b214852a23637e46bd25b72af883f25

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: f570a1781ffb6184ea93696443806d33

View File

@ -0,0 +1,73 @@
#region License
/*
* HttpVersion.cs
*
* This code is derived from HttpVersion.cs (System.Net) of Mono
* (http://www.mono-project.com).
*
* The MIT License
*
* Copyright (c) 2012-2024 sta.blockhead
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
#endregion
#region Authors
/*
* Authors:
* - Lawrence Pit <loz@cable.a2000.nl>
*/
#endregion
using System;
namespace WebSocketSharp.Net
{
/// <summary>
/// Provides the HTTP version numbers.
/// </summary>
public class HttpVersion
{
#region Public Fields
/// <summary>
/// Provides a <see cref="Version"/> instance for the HTTP/1.0.
/// </summary>
public static readonly Version Version10 = new Version (1, 0);
/// <summary>
/// Provides a <see cref="Version"/> instance for the HTTP/1.1.
/// </summary>
public static readonly Version Version11 = new Version (1, 1);
#endregion
#region Public Constructors
/// <summary>
/// Initializes a new instance of the <see cref="HttpVersion"/> class.
/// </summary>
public HttpVersion ()
{
}
#endregion
}
}

View File

@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: 5b7b5bd46350c3642905967564402d63

View File

@ -0,0 +1,52 @@
#region License
/*
* InputChunkState.cs
*
* This code is derived from ChunkStream.cs (System.Net) of Mono
* (http://www.mono-project.com).
*
* The MIT License
*
* Copyright (c) 2003 Ximian, Inc (http://www.ximian.com)
* Copyright (c) 2014-2015 sta.blockhead
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
#endregion
#region Authors
/*
* Authors:
* - Gonzalo Paniagua Javier <gonzalo@ximian.com>
*/
#endregion
using System;
namespace WebSocketSharp.Net
{
internal enum InputChunkState
{
None,
Data,
DataEnded,
Trailer,
End
}
}

View File

@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: 823ae53558ee9e746a94dbdb388f4c17

View File

@ -0,0 +1,49 @@
#region License
/*
* InputState.cs
*
* This code is derived from HttpConnection.cs (System.Net) of Mono
* (http://www.mono-project.com).
*
* The MIT License
*
* Copyright (c) 2005 Novell, Inc. (http://www.novell.com)
* Copyright (c) 2014-2015 sta.blockhead
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
#endregion
#region Authors
/*
* Authors:
* - Gonzalo Paniagua Javier <gonzalo@novell.com>
*/
#endregion
using System;
namespace WebSocketSharp.Net
{
internal enum InputState
{
RequestLine,
Headers
}
}

View File

@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: c4bf22ee9c7cd2a44b73f930437c3a36

Some files were not shown because too many files have changed in this diff Show More