引入 websocket sharp
This commit is contained in:
151
websocket-sharp/Net/AuthenticationBase.cs
Normal file
151
websocket-sharp/Net/AuthenticationBase.cs
Normal file
@@ -0,0 +1,151 @@
|
||||
#region License
|
||||
/*
|
||||
* AuthenticationBase.cs
|
||||
*
|
||||
* The MIT License
|
||||
*
|
||||
* Copyright (c) 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;
|
||||
using System.Collections.Specialized;
|
||||
using System.Text;
|
||||
|
||||
namespace WebSocketSharp.Net
|
||||
{
|
||||
internal abstract class AuthenticationBase
|
||||
{
|
||||
#region Private Fields
|
||||
|
||||
private AuthenticationSchemes _scheme;
|
||||
|
||||
#endregion
|
||||
|
||||
#region Internal Fields
|
||||
|
||||
internal NameValueCollection Parameters;
|
||||
|
||||
#endregion
|
||||
|
||||
#region Protected Constructors
|
||||
|
||||
protected AuthenticationBase (AuthenticationSchemes scheme, NameValueCollection parameters)
|
||||
{
|
||||
_scheme = scheme;
|
||||
Parameters = parameters;
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
#region Public Properties
|
||||
|
||||
public string Algorithm {
|
||||
get {
|
||||
return Parameters["algorithm"];
|
||||
}
|
||||
}
|
||||
|
||||
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;
|
||||
}
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
#region Internal Methods
|
||||
|
||||
internal static string CreateNonceValue ()
|
||||
{
|
||||
var src = new byte[16];
|
||||
var rand = new Random ();
|
||||
rand.NextBytes (src);
|
||||
|
||||
var res = new StringBuilder (32);
|
||||
foreach (var b in src)
|
||||
res.Append (b.ToString ("x2"));
|
||||
|
||||
return res.ToString ();
|
||||
}
|
||||
|
||||
internal static NameValueCollection ParseParameters (string value)
|
||||
{
|
||||
var res = 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;
|
||||
|
||||
res.Add (name, val);
|
||||
}
|
||||
|
||||
return res;
|
||||
}
|
||||
|
||||
internal abstract string ToBasicString ();
|
||||
|
||||
internal abstract string ToDigestString ();
|
||||
|
||||
#endregion
|
||||
|
||||
#region Public Methods
|
||||
|
||||
public override string ToString ()
|
||||
{
|
||||
return _scheme == AuthenticationSchemes.Basic
|
||||
? ToBasicString ()
|
||||
: _scheme == AuthenticationSchemes.Digest
|
||||
? ToDigestString ()
|
||||
: String.Empty;
|
||||
}
|
||||
|
||||
#endregion
|
||||
}
|
||||
}
|
146
websocket-sharp/Net/AuthenticationChallenge.cs
Normal file
146
websocket-sharp/Net/AuthenticationChallenge.cs
Normal file
@@ -0,0 +1,146 @@
|
||||
#region License
|
||||
/*
|
||||
* AuthenticationChallenge.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;
|
||||
using System.Collections.Specialized;
|
||||
using System.Text;
|
||||
|
||||
namespace WebSocketSharp.Net
|
||||
{
|
||||
internal class AuthenticationChallenge : AuthenticationBase
|
||||
{
|
||||
#region Private Constructors
|
||||
|
||||
private AuthenticationChallenge (AuthenticationSchemes scheme, NameValueCollection parameters)
|
||||
: base (scheme, parameters)
|
||||
{
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
#region Internal Constructors
|
||||
|
||||
internal AuthenticationChallenge (AuthenticationSchemes scheme, string realm)
|
||||
: base (scheme, new NameValueCollection ())
|
||||
{
|
||||
Parameters["realm"] = realm;
|
||||
if (scheme == AuthenticationSchemes.Digest) {
|
||||
Parameters["nonce"] = CreateNonceValue ();
|
||||
Parameters["algorithm"] = "MD5";
|
||||
Parameters["qop"] = "auth";
|
||||
}
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
#region Public Properties
|
||||
|
||||
public string Domain {
|
||||
get {
|
||||
return Parameters["domain"];
|
||||
}
|
||||
}
|
||||
|
||||
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 AuthenticationChallenge Parse (string value)
|
||||
{
|
||||
var chal = value.Split (new[] { ' ' }, 2);
|
||||
if (chal.Length != 2)
|
||||
return null;
|
||||
|
||||
var schm = chal[0].ToLower ();
|
||||
return schm == "basic"
|
||||
? new AuthenticationChallenge (
|
||||
AuthenticationSchemes.Basic, ParseParameters (chal[1]))
|
||||
: schm == "digest"
|
||||
? new AuthenticationChallenge (
|
||||
AuthenticationSchemes.Digest, ParseParameters (chal[1]))
|
||||
: null;
|
||||
}
|
||||
|
||||
internal override string ToBasicString ()
|
||||
{
|
||||
return String.Format ("Basic realm=\"{0}\"", Parameters["realm"]);
|
||||
}
|
||||
|
||||
internal override string ToDigestString ()
|
||||
{
|
||||
var output = new StringBuilder (128);
|
||||
|
||||
var domain = Parameters["domain"];
|
||||
if (domain != null)
|
||||
output.AppendFormat (
|
||||
"Digest realm=\"{0}\", domain=\"{1}\", nonce=\"{2}\"",
|
||||
Parameters["realm"],
|
||||
domain,
|
||||
Parameters["nonce"]);
|
||||
else
|
||||
output.AppendFormat (
|
||||
"Digest realm=\"{0}\", nonce=\"{1}\"", Parameters["realm"], Parameters["nonce"]);
|
||||
|
||||
var opaque = Parameters["opaque"];
|
||||
if (opaque != null)
|
||||
output.AppendFormat (", opaque=\"{0}\"", opaque);
|
||||
|
||||
var stale = Parameters["stale"];
|
||||
if (stale != null)
|
||||
output.AppendFormat (", stale={0}", stale);
|
||||
|
||||
var algo = Parameters["algorithm"];
|
||||
if (algo != null)
|
||||
output.AppendFormat (", algorithm={0}", algo);
|
||||
|
||||
var qop = Parameters["qop"];
|
||||
if (qop != null)
|
||||
output.AppendFormat (", qop=\"{0}\"", qop);
|
||||
|
||||
return output.ToString ();
|
||||
}
|
||||
|
||||
#endregion
|
||||
}
|
||||
}
|
323
websocket-sharp/Net/AuthenticationResponse.cs
Normal file
323
websocket-sharp/Net/AuthenticationResponse.cs
Normal file
@@ -0,0 +1,323 @@
|
||||
#region License
|
||||
/*
|
||||
* AuthenticationResponse.cs
|
||||
*
|
||||
* ParseBasicCredentials is derived from System.Net.HttpListenerContext.cs of Mono
|
||||
* (http://www.mono-project.com).
|
||||
*
|
||||
* The MIT License
|
||||
*
|
||||
* Copyright (c) 2005 Novell, Inc. (http://www.novell.com)
|
||||
* 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;
|
||||
using System.Collections.Specialized;
|
||||
using System.Security.Cryptography;
|
||||
using System.Security.Principal;
|
||||
using System.Text;
|
||||
|
||||
namespace WebSocketSharp.Net
|
||||
{
|
||||
internal class AuthenticationResponse : AuthenticationBase
|
||||
{
|
||||
#region Private Fields
|
||||
|
||||
private uint _nonceCount;
|
||||
|
||||
#endregion
|
||||
|
||||
#region Private Constructors
|
||||
|
||||
private AuthenticationResponse (AuthenticationSchemes scheme, NameValueCollection parameters)
|
||||
: base (scheme, 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)
|
||||
: base (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;
|
||||
}
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
#region Public Properties
|
||||
|
||||
public string Cnonce {
|
||||
get {
|
||||
return Parameters["cnonce"];
|
||||
}
|
||||
}
|
||||
|
||||
public string Nc {
|
||||
get {
|
||||
return Parameters["nc"];
|
||||
}
|
||||
}
|
||||
|
||||
public string Password {
|
||||
get {
|
||||
return Parameters["password"];
|
||||
}
|
||||
}
|
||||
|
||||
public string Response {
|
||||
get {
|
||||
return Parameters["response"];
|
||||
}
|
||||
}
|
||||
|
||||
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)
|
||||
{
|
||||
return String.Format (
|
||||
"{0}:{1}:{2}", hash (createA1 (username, password, realm)), 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 src = Encoding.UTF8.GetBytes (value);
|
||||
var md5 = MD5.Create ();
|
||||
var hashed = md5.ComputeHash (src);
|
||||
|
||||
var res = new StringBuilder (64);
|
||||
foreach (var b in hashed)
|
||||
res.Append (b.ToString ("x2"));
|
||||
|
||||
return res.ToString ();
|
||||
}
|
||||
|
||||
private void initAsDigest ()
|
||||
{
|
||||
var qops = Parameters["qop"];
|
||||
if (qops != null) {
|
||||
if (qops.Split (',').Contains (qop => qop.Trim ().ToLower () == "auth")) {
|
||||
Parameters["qop"] = "auth";
|
||||
Parameters["cnonce"] = 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 user = parameters["username"];
|
||||
var pass = 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 (user, pass, realm, nonce, cnonce)
|
||||
: createA1 (user, pass, 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));
|
||||
|
||||
return hash (String.Format ("{0}:{1}", secret, data));
|
||||
}
|
||||
|
||||
internal static AuthenticationResponse Parse (string value)
|
||||
{
|
||||
try {
|
||||
var cred = value.Split (new[] { ' ' }, 2);
|
||||
if (cred.Length != 2)
|
||||
return null;
|
||||
|
||||
var schm = cred[0].ToLower ();
|
||||
return schm == "basic"
|
||||
? new AuthenticationResponse (
|
||||
AuthenticationSchemes.Basic, ParseBasicCredentials (cred[1]))
|
||||
: schm == "digest"
|
||||
? new AuthenticationResponse (
|
||||
AuthenticationSchemes.Digest, ParseParameters (cred[1]))
|
||||
: null;
|
||||
}
|
||||
catch {
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
internal static NameValueCollection ParseBasicCredentials (string value)
|
||||
{
|
||||
// Decode the basic-credentials (a Base64 encoded string).
|
||||
var userPass = Encoding.Default.GetString (Convert.FromBase64String (value));
|
||||
|
||||
// The format is [<domain>\]<username>:<password>.
|
||||
var i = userPass.IndexOf (':');
|
||||
var user = userPass.Substring (0, i);
|
||||
var pass = i < userPass.Length - 1 ? userPass.Substring (i + 1) : String.Empty;
|
||||
|
||||
// Check if 'domain' exists.
|
||||
i = user.IndexOf ('\\');
|
||||
if (i > -1)
|
||||
user = user.Substring (i + 1);
|
||||
|
||||
var res = new NameValueCollection ();
|
||||
res["username"] = user;
|
||||
res["password"] = pass;
|
||||
|
||||
return res;
|
||||
}
|
||||
|
||||
internal override string ToBasicString ()
|
||||
{
|
||||
var userPass = String.Format ("{0}:{1}", Parameters["username"], Parameters["password"]);
|
||||
var cred = Convert.ToBase64String (Encoding.UTF8.GetBytes (userPass));
|
||||
|
||||
return "Basic " + cred;
|
||||
}
|
||||
|
||||
internal override string ToDigestString ()
|
||||
{
|
||||
var output = new StringBuilder (256);
|
||||
output.AppendFormat (
|
||||
"Digest username=\"{0}\", realm=\"{1}\", nonce=\"{2}\", uri=\"{3}\", response=\"{4}\"",
|
||||
Parameters["username"],
|
||||
Parameters["realm"],
|
||||
Parameters["nonce"],
|
||||
Parameters["uri"],
|
||||
Parameters["response"]);
|
||||
|
||||
var opaque = Parameters["opaque"];
|
||||
if (opaque != null)
|
||||
output.AppendFormat (", opaque=\"{0}\"", opaque);
|
||||
|
||||
var algo = Parameters["algorithm"];
|
||||
if (algo != null)
|
||||
output.AppendFormat (", algorithm={0}", algo);
|
||||
|
||||
var qop = Parameters["qop"];
|
||||
if (qop != null)
|
||||
output.AppendFormat (
|
||||
", qop={0}, cnonce=\"{1}\", nc={2}", qop, Parameters["cnonce"], Parameters["nc"]);
|
||||
|
||||
return output.ToString ();
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
#region Public Methods
|
||||
|
||||
public IIdentity ToIdentity ()
|
||||
{
|
||||
var schm = Scheme;
|
||||
return schm == AuthenticationSchemes.Basic
|
||||
? new HttpBasicIdentity (Parameters["username"], Parameters["password"]) as IIdentity
|
||||
: schm == AuthenticationSchemes.Digest
|
||||
? new HttpDigestIdentity (Parameters)
|
||||
: null;
|
||||
}
|
||||
|
||||
#endregion
|
||||
}
|
||||
}
|
66
websocket-sharp/Net/AuthenticationSchemes.cs
Normal file
66
websocket-sharp/Net/AuthenticationSchemes.cs
Normal 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
|
||||
}
|
||||
}
|
93
websocket-sharp/Net/Chunk.cs
Normal file
93
websocket-sharp/Net/Chunk.cs
Normal 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
|
||||
}
|
||||
}
|
383
websocket-sharp/Net/ChunkStream.cs
Normal file
383
websocket-sharp/Net/ChunkStream.cs
Normal file
@@ -0,0 +1,383 @@
|
||||
#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-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;
|
||||
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 bool _gotIt;
|
||||
private WebHeaderCollection _headers;
|
||||
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 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 (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 ResetBuffer ()
|
||||
{
|
||||
_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
|
||||
}
|
||||
}
|
249
websocket-sharp/Net/ChunkedRequestStream.cs
Normal file
249
websocket-sharp/Net/ChunkedRequestStream.cs
Normal file
@@ -0,0 +1,249 @@
|
||||
#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-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.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 stream,
|
||||
byte[] buffer,
|
||||
int offset,
|
||||
int count,
|
||||
HttpListenerContext context
|
||||
)
|
||||
: base (stream, buffer, offset, count, -1)
|
||||
{
|
||||
_context = context;
|
||||
|
||||
_decoder = new ChunkStream (
|
||||
(WebHeaderCollection) context.Request.Headers
|
||||
);
|
||||
}
|
||||
|
||||
#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) {
|
||||
var name = GetType ().ToString ();
|
||||
|
||||
throw new ObjectDisposedException (name);
|
||||
}
|
||||
|
||||
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;
|
||||
|
||||
_disposed = true;
|
||||
|
||||
base.Close ();
|
||||
}
|
||||
|
||||
public override int EndRead (IAsyncResult asyncResult)
|
||||
{
|
||||
if (_disposed) {
|
||||
var name = GetType ().ToString ();
|
||||
|
||||
throw new ObjectDisposedException (name);
|
||||
}
|
||||
|
||||
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
|
||||
}
|
||||
}
|
303
websocket-sharp/Net/ClientSslConfiguration.cs
Normal file
303
websocket-sharp/Net/ClientSslConfiguration.cs
Normal file
@@ -0,0 +1,303 @@
|
||||
#region License
|
||||
/*
|
||||
* ClientSslConfiguration.cs
|
||||
*
|
||||
* The MIT License
|
||||
*
|
||||
* Copyright (c) 2014 liryna
|
||||
* 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:
|
||||
* - 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 the <see cref="SslStream"/> used by clients.
|
||||
/// </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 server name.
|
||||
/// </summary>
|
||||
/// <param name="targetHost">
|
||||
/// A <see cref="string"/> that specifies the target host server name.
|
||||
/// </param>
|
||||
/// <exception cref="ArgumentNullException">
|
||||
/// <paramref name="targetHost"/> is <see langword="null"/>.
|
||||
/// </exception>
|
||||
/// <exception cref="ArgumentException">
|
||||
/// <paramref name="targetHost"/> is an empty string.
|
||||
/// </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 that stores the parameters copied 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 client certificates from which to select
|
||||
/// one to supply to the server.
|
||||
/// </summary>
|
||||
/// <value>
|
||||
/// <para>
|
||||
/// A <see cref="X509CertificateCollection"/> or <see langword="null"/>.
|
||||
/// </para>
|
||||
/// <para>
|
||||
/// The collection contains client certificates from which to select.
|
||||
/// </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 that
|
||||
/// invokes the method called for selecting the certificate.
|
||||
/// </para>
|
||||
/// <para>
|
||||
/// The default value is a delegate that 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 protocols used for authentication.
|
||||
/// </summary>
|
||||
/// <value>
|
||||
/// <para>
|
||||
/// Any of the <see cref="SslProtocols"/> enum values.
|
||||
/// </para>
|
||||
/// <para>
|
||||
/// It represents the protocols used for authentication.
|
||||
/// </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 that
|
||||
/// invokes the method called for validating the certificate.
|
||||
/// </para>
|
||||
/// <para>
|
||||
/// The default value is a delegate that 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 server name.
|
||||
/// </summary>
|
||||
/// <value>
|
||||
/// A <see cref="string"/> that represents the name of the server that
|
||||
/// will share a secure connection with a client.
|
||||
/// </value>
|
||||
/// <exception cref="ArgumentNullException">
|
||||
/// The value specified for a set operation is <see langword="null"/>.
|
||||
/// </exception>
|
||||
/// <exception cref="ArgumentException">
|
||||
/// The value specified for a set operation is an empty string.
|
||||
/// </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
|
||||
}
|
||||
}
|
1016
websocket-sharp/Net/Cookie.cs
Normal file
1016
websocket-sharp/Net/Cookie.cs
Normal file
File diff suppressed because it is too large
Load Diff
821
websocket-sharp/Net/CookieCollection.cs
Normal file
821
websocket-sharp/Net/CookieCollection.cs
Normal file
@@ -0,0 +1,821 @@
|
||||
#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-2019 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;
|
||||
return ret != 0
|
||||
? ret
|
||||
: (ret = x.Name.CompareTo (y.Name)) != 0
|
||||
? ret
|
||||
: 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;
|
||||
|
||||
int num;
|
||||
if (!Int32.TryParse (val.Unquote (), 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;
|
||||
|
||||
int num;
|
||||
if (!Int32.TryParse (val.Unquote (), 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 ());
|
||||
|
||||
DateTime expires;
|
||||
if (
|
||||
!DateTime.TryParseExact (
|
||||
buff.ToString (),
|
||||
new[] { "ddd, dd'-'MMM'-'yyyy HH':'mm':'ss 'GMT'", "r" },
|
||||
CultureInfo.CreateSpecificCulture ("en-US"),
|
||||
DateTimeStyles.AdjustToUniversal
|
||||
| DateTimeStyles.AssumeUniversal,
|
||||
out expires
|
||||
)
|
||||
)
|
||||
continue;
|
||||
|
||||
cookie.Expires = expires.ToLocalTime ();
|
||||
continue;
|
||||
}
|
||||
|
||||
if (name.Equals ("max-age", caseInsensitive)) {
|
||||
if (cookie == null)
|
||||
continue;
|
||||
|
||||
if (val.Length == 0)
|
||||
continue;
|
||||
|
||||
int num;
|
||||
if (!Int32.TryParse (val.Unquote (), out num))
|
||||
continue;
|
||||
|
||||
cookie.MaxAge = 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 (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 > 1)
|
||||
_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="InvalidOperationException">
|
||||
/// The collection is read-only.
|
||||
/// </exception>
|
||||
/// <exception cref="ArgumentNullException">
|
||||
/// <paramref name="cookie"/> is <see langword="null"/>.
|
||||
/// </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="InvalidOperationException">
|
||||
/// The collection is read-only.
|
||||
/// </exception>
|
||||
/// <exception cref="ArgumentNullException">
|
||||
/// <paramref name="cookies"/> is <see langword="null"/>.
|
||||
/// </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="ArgumentNullException">
|
||||
/// <paramref name="array"/> is <see langword="null"/>.
|
||||
/// </exception>
|
||||
/// <exception cref="ArgumentOutOfRangeException">
|
||||
/// <paramref name="index"/> is less than zero.
|
||||
/// </exception>
|
||||
/// <exception cref="ArgumentException">
|
||||
/// The space from <paramref name="index"/> to the end of
|
||||
/// <paramref name="array"/> is not enough to copy to.
|
||||
/// </exception>
|
||||
public void CopyTo (Cookie[] array, int index)
|
||||
{
|
||||
if (array == null)
|
||||
throw new ArgumentNullException ("array");
|
||||
|
||||
if (index < 0)
|
||||
throw new ArgumentOutOfRangeException ("index", "Less than zero.");
|
||||
|
||||
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="InvalidOperationException">
|
||||
/// The collection is read-only.
|
||||
/// </exception>
|
||||
/// <exception cref="ArgumentNullException">
|
||||
/// <paramref name="cookie"/> is <see langword="null"/>.
|
||||
/// </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
|
||||
}
|
||||
}
|
165
websocket-sharp/Net/CookieException.cs
Normal file
165
websocket-sharp/Net/CookieException.cs
Normal file
@@ -0,0 +1,165 @@
|
||||
#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-2019 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 serialized data.
|
||||
/// </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 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
|
||||
}
|
||||
}
|
582
websocket-sharp/Net/EndPointListener.cs
Normal file
582
websocket-sharp/Net/EndPointListener.cs
Normal file
@@ -0,0 +1,582 @@
|
||||
#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-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
|
||||
|
||||
#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];
|
||||
|
||||
var vals = _connections.Values;
|
||||
vals.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));
|
||||
|
||||
if (File.Exists (cer) && File.Exists (key)) {
|
||||
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;
|
||||
|
||||
if (path.StartsWith (prefPath, StringComparison.Ordinal)) {
|
||||
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;
|
||||
|
||||
if (path.StartsWith (prefPath, StringComparison.Ordinal)) {
|
||||
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 msg = String.Format (
|
||||
"There is another listener for {0}.", 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
|
||||
}
|
||||
}
|
261
websocket-sharp/Net/EndPointManager.cs
Normal file
261
websocket-sharp/Net/EndPointManager.cs
Normal 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
|
||||
}
|
||||
}
|
82
websocket-sharp/Net/HttpBasicIdentity.cs
Normal file
82
websocket-sharp/Net/HttpBasicIdentity.cs
Normal 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
|
||||
}
|
||||
}
|
571
websocket-sharp/Net/HttpConnection.cs
Normal file
571
websocket-sharp/Net/HttpConnection.cs
Normal file
@@ -0,0 +1,571 @@
|
||||
#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-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
|
||||
|
||||
#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 InputState _inputState;
|
||||
private RequestStream _inputStream;
|
||||
private LineState _lineState;
|
||||
private EndPointListener _listener;
|
||||
private EndPoint _localEndPoint;
|
||||
private static readonly int _maxInputLength;
|
||||
private ResponseStream _outputStream;
|
||||
private int _position;
|
||||
private EndPoint _remoteEndPoint;
|
||||
private MemoryStream _requestBuffer;
|
||||
private int _reuses;
|
||||
private bool _secure;
|
||||
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;
|
||||
_listener = 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
|
||||
);
|
||||
|
||||
_secure = 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);
|
||||
|
||||
init (90000); // 90k ms for first request, 15k ms from then on.
|
||||
}
|
||||
|
||||
#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 _secure;
|
||||
}
|
||||
}
|
||||
|
||||
public IPEndPoint LocalEndPoint {
|
||||
get {
|
||||
return (IPEndPoint) _localEndPoint;
|
||||
}
|
||||
}
|
||||
|
||||
public IPEndPoint RemoteEndPoint {
|
||||
get {
|
||||
return (IPEndPoint) _remoteEndPoint;
|
||||
}
|
||||
}
|
||||
|
||||
public int Reuses {
|
||||
get {
|
||||
return _reuses;
|
||||
}
|
||||
}
|
||||
|
||||
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 ();
|
||||
_listener.RemoveConnection (this);
|
||||
}
|
||||
|
||||
private void closeSocket ()
|
||||
{
|
||||
try {
|
||||
_socket.Shutdown (SocketShutdown.Both);
|
||||
}
|
||||
catch {
|
||||
}
|
||||
|
||||
_socket.Close ();
|
||||
|
||||
_socket = null;
|
||||
}
|
||||
|
||||
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 (int timeout)
|
||||
{
|
||||
_timeout = timeout;
|
||||
|
||||
_context = new HttpListenerContext (this);
|
||||
_currentLine = new StringBuilder (64);
|
||||
_inputState = InputState.RequestLine;
|
||||
_inputStream = null;
|
||||
_lineState = LineState.None;
|
||||
_outputStream = null;
|
||||
_position = 0;
|
||||
_requestBuffer = new MemoryStream ();
|
||||
}
|
||||
|
||||
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);
|
||||
var len = (int) conn._requestBuffer.Length;
|
||||
|
||||
if (conn.processInput (conn._requestBuffer.GetBuffer (), len)) {
|
||||
if (!conn._context.HasErrorMessage)
|
||||
conn._context.Request.FinishInitialization ();
|
||||
|
||||
if (conn._context.HasErrorMessage) {
|
||||
conn._context.SendError ();
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
var url = conn._context.Request.Url;
|
||||
HttpListener lsnr;
|
||||
|
||||
if (conn._listener.TrySearchHttpListener (url, out lsnr)) {
|
||||
if (!lsnr.AuthenticateContext (conn._context))
|
||||
return;
|
||||
|
||||
if (!lsnr.RegisterContext (conn._context)) {
|
||||
conn._context.ErrorStatusCode = 503;
|
||||
conn._context.SendError ();
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
conn._context.ErrorStatusCode = 404;
|
||||
conn._context.SendError ();
|
||||
|
||||
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.ErrorStatusCode = 408;
|
||||
conn._context.SendError ();
|
||||
}
|
||||
}
|
||||
|
||||
private bool processInput (byte[] data, int length)
|
||||
{
|
||||
// This method returns a bool:
|
||||
// - true Done processing
|
||||
// - false Need more input
|
||||
|
||||
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) {
|
||||
_context.Request.SetRequestLine (line);
|
||||
_inputState = InputState.Headers;
|
||||
}
|
||||
else {
|
||||
_context.Request.AddHeader (line);
|
||||
}
|
||||
|
||||
if (_context.HasErrorMessage)
|
||||
return true;
|
||||
}
|
||||
}
|
||||
catch (Exception ex) {
|
||||
_context.ErrorMessage = ex.Message;
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
if (_position >= _maxInputLength) {
|
||||
_context.ErrorMessage = "Headers too long";
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
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;
|
||||
}
|
||||
|
||||
#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;
|
||||
}
|
||||
|
||||
disposeRequestBuffer ();
|
||||
_context.Unregister ();
|
||||
|
||||
_reuses++;
|
||||
|
||||
init (15000);
|
||||
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;
|
||||
|
||||
disposeRequestBuffer ();
|
||||
|
||||
_inputStream = chunked
|
||||
? new ChunkedRequestStream (
|
||||
_stream, buff, _position, cnt, _context
|
||||
)
|
||||
: new RequestStream (
|
||||
_stream, buff, _position, cnt, contentLength
|
||||
);
|
||||
|
||||
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
|
||||
}
|
||||
}
|
187
websocket-sharp/Net/HttpDigestIdentity.cs
Normal file
187
websocket-sharp/Net/HttpDigestIdentity.cs
Normal file
@@ -0,0 +1,187 @@
|
||||
#region License
|
||||
/*
|
||||
* HttpDigestIdentity.cs
|
||||
*
|
||||
* The MIT License
|
||||
*
|
||||
* 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
|
||||
|
||||
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 copied = new NameValueCollection (_parameters);
|
||||
copied["password"] = password;
|
||||
copied["realm"] = realm;
|
||||
copied["method"] = method;
|
||||
copied["entity"] = entity;
|
||||
|
||||
var expected = AuthenticationResponse.CreateRequestDigest (copied);
|
||||
return _parameters["response"] == expected;
|
||||
}
|
||||
|
||||
#endregion
|
||||
}
|
||||
}
|
128
websocket-sharp/Net/HttpHeaderInfo.cs
Normal file
128
websocket-sharp/Net/HttpHeaderInfo.cs
Normal 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
|
||||
}
|
||||
}
|
44
websocket-sharp/Net/HttpHeaderType.cs
Normal file
44
websocket-sharp/Net/HttpHeaderType.cs
Normal 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
|
||||
}
|
||||
}
|
973
websocket-sharp/Net/HttpListener.cs
Normal file
973
websocket-sharp/Net/HttpListener.cs
Normal file
@@ -0,0 +1,973 @@
|
||||
#region License
|
||||
/*
|
||||
* HttpListener.cs
|
||||
*
|
||||
* This code is derived from HttpListener.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
|
||||
|
||||
#region Contributors
|
||||
/*
|
||||
* Contributors:
|
||||
* - Liryna <liryna.stark@gmail.com>
|
||||
*/
|
||||
#endregion
|
||||
|
||||
using System;
|
||||
using System.Collections;
|
||||
using System.Collections.Generic;
|
||||
using System.Security.Cryptography.X509Certificates;
|
||||
using System.Security.Principal;
|
||||
using System.Threading;
|
||||
|
||||
// TODO: Logging.
|
||||
namespace WebSocketSharp.Net
|
||||
{
|
||||
/// <summary>
|
||||
/// Provides a simple, programmatically controlled HTTP listener.
|
||||
/// </summary>
|
||||
public sealed class HttpListener : IDisposable
|
||||
{
|
||||
#region Private Fields
|
||||
|
||||
private AuthenticationSchemes _authSchemes;
|
||||
private Func<HttpListenerRequest, AuthenticationSchemes> _authSchemeSelector;
|
||||
private string _certFolderPath;
|
||||
private Queue<HttpListenerContext> _contextQueue;
|
||||
private LinkedList<HttpListenerContext> _contextRegistry;
|
||||
private object _contextRegistrySync;
|
||||
private static readonly string _defaultRealm;
|
||||
private bool _disposed;
|
||||
private bool _ignoreWriteExceptions;
|
||||
private volatile bool _listening;
|
||||
private Logger _log;
|
||||
private string _objectName;
|
||||
private HttpListenerPrefixCollection _prefixes;
|
||||
private string _realm;
|
||||
private bool _reuseAddress;
|
||||
private ServerSslConfiguration _sslConfig;
|
||||
private Func<IIdentity, NetworkCredential> _userCredFinder;
|
||||
private Queue<HttpListenerAsyncResult> _waitQueue;
|
||||
|
||||
#endregion
|
||||
|
||||
#region Static Constructor
|
||||
|
||||
static HttpListener ()
|
||||
{
|
||||
_defaultRealm = "SECRET AREA";
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
#region Public Constructors
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="HttpListener"/> class.
|
||||
/// </summary>
|
||||
public HttpListener ()
|
||||
{
|
||||
_authSchemes = AuthenticationSchemes.Anonymous;
|
||||
_contextQueue = new Queue<HttpListenerContext> ();
|
||||
|
||||
_contextRegistry = new LinkedList<HttpListenerContext> ();
|
||||
_contextRegistrySync = ((ICollection) _contextRegistry).SyncRoot;
|
||||
|
||||
_log = new Logger ();
|
||||
_objectName = GetType ().ToString ();
|
||||
_prefixes = new HttpListenerPrefixCollection (this);
|
||||
_waitQueue = new Queue<HttpListenerAsyncResult> ();
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
#region Internal Properties
|
||||
|
||||
internal bool ReuseAddress {
|
||||
get {
|
||||
return _reuseAddress;
|
||||
}
|
||||
|
||||
set {
|
||||
_reuseAddress = value;
|
||||
}
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
#region Public Properties
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the scheme used to authenticate the clients.
|
||||
/// </summary>
|
||||
/// <value>
|
||||
/// <para>
|
||||
/// One of the <see cref="WebSocketSharp.Net.AuthenticationSchemes"/>
|
||||
/// enum values.
|
||||
/// </para>
|
||||
/// <para>
|
||||
/// It represents the scheme used to authenticate the clients.
|
||||
/// </para>
|
||||
/// <para>
|
||||
/// The default value is
|
||||
/// <see cref="WebSocketSharp.Net.AuthenticationSchemes.Anonymous"/>.
|
||||
/// </para>
|
||||
/// </value>
|
||||
/// <exception cref="ObjectDisposedException">
|
||||
/// This listener has been closed.
|
||||
/// </exception>
|
||||
public AuthenticationSchemes AuthenticationSchemes {
|
||||
get {
|
||||
if (_disposed)
|
||||
throw new ObjectDisposedException (_objectName);
|
||||
|
||||
return _authSchemes;
|
||||
}
|
||||
|
||||
set {
|
||||
if (_disposed)
|
||||
throw new ObjectDisposedException (_objectName);
|
||||
|
||||
_authSchemes = value;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the delegate called to select the scheme used to
|
||||
/// authenticate the clients.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// <para>
|
||||
/// If this property is set, the listener uses the authentication
|
||||
/// scheme selected by the delegate for each request.
|
||||
/// </para>
|
||||
/// <para>
|
||||
/// Or if this property is not set, the listener uses the value of
|
||||
/// the <see cref="HttpListener.AuthenticationSchemes"/> property
|
||||
/// as the authentication scheme for all requests.
|
||||
/// </para>
|
||||
/// </remarks>
|
||||
/// <value>
|
||||
/// <para>
|
||||
/// A <c>Func<<see cref="HttpListenerRequest"/>,
|
||||
/// <see cref="AuthenticationSchemes"/>></c> delegate or
|
||||
/// <see langword="null"/> if not needed.
|
||||
/// </para>
|
||||
/// <para>
|
||||
/// The delegate references the method used to select
|
||||
/// an authentication scheme.
|
||||
/// </para>
|
||||
/// <para>
|
||||
/// The default value is <see langword="null"/>.
|
||||
/// </para>
|
||||
/// </value>
|
||||
/// <exception cref="ObjectDisposedException">
|
||||
/// This listener has been closed.
|
||||
/// </exception>
|
||||
public Func<HttpListenerRequest, AuthenticationSchemes> AuthenticationSchemeSelector {
|
||||
get {
|
||||
if (_disposed)
|
||||
throw new ObjectDisposedException (_objectName);
|
||||
|
||||
return _authSchemeSelector;
|
||||
}
|
||||
|
||||
set {
|
||||
if (_disposed)
|
||||
throw new ObjectDisposedException (_objectName);
|
||||
|
||||
_authSchemeSelector = value;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the path to the folder in which stores the certificate
|
||||
/// files used to authenticate the server on the secure connection.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// <para>
|
||||
/// This property represents the path to the folder in which stores
|
||||
/// the certificate files associated with each port number of added
|
||||
/// URI prefixes.
|
||||
/// </para>
|
||||
/// <para>
|
||||
/// A set of the certificate files is a pair of <port number>.cer
|
||||
/// (DER) and <port number>.key (DER, RSA Private Key).
|
||||
/// </para>
|
||||
/// <para>
|
||||
/// If this property is <see langword="null"/> or an empty string,
|
||||
/// the result of <c>System.Environment.GetFolderPath (<see
|
||||
/// cref="Environment.SpecialFolder.ApplicationData"/>)</c>
|
||||
/// is used as the default path.
|
||||
/// </para>
|
||||
/// </remarks>
|
||||
/// <value>
|
||||
/// <para>
|
||||
/// A <see cref="string"/> that represents the path to the folder
|
||||
/// in which stores the certificate files.
|
||||
/// </para>
|
||||
/// <para>
|
||||
/// The default value is <see langword="null"/>.
|
||||
/// </para>
|
||||
/// </value>
|
||||
/// <exception cref="ObjectDisposedException">
|
||||
/// This listener has been closed.
|
||||
/// </exception>
|
||||
public string CertificateFolderPath {
|
||||
get {
|
||||
if (_disposed)
|
||||
throw new ObjectDisposedException (_objectName);
|
||||
|
||||
return _certFolderPath;
|
||||
}
|
||||
|
||||
set {
|
||||
if (_disposed)
|
||||
throw new ObjectDisposedException (_objectName);
|
||||
|
||||
_certFolderPath = value;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets a value indicating whether the listener returns
|
||||
/// exceptions that occur when sending the response to the client.
|
||||
/// </summary>
|
||||
/// <value>
|
||||
/// <para>
|
||||
/// <c>true</c> if the listener should not return those exceptions;
|
||||
/// otherwise, <c>false</c>.
|
||||
/// </para>
|
||||
/// <para>
|
||||
/// The default value is <c>false</c>.
|
||||
/// </para>
|
||||
/// </value>
|
||||
/// <exception cref="ObjectDisposedException">
|
||||
/// This listener has been closed.
|
||||
/// </exception>
|
||||
public bool IgnoreWriteExceptions {
|
||||
get {
|
||||
if (_disposed)
|
||||
throw new ObjectDisposedException (_objectName);
|
||||
|
||||
return _ignoreWriteExceptions;
|
||||
}
|
||||
|
||||
set {
|
||||
if (_disposed)
|
||||
throw new ObjectDisposedException (_objectName);
|
||||
|
||||
_ignoreWriteExceptions = value;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets a value indicating whether the listener has been started.
|
||||
/// </summary>
|
||||
/// <value>
|
||||
/// <c>true</c> if the listener has been started; otherwise, <c>false</c>.
|
||||
/// </value>
|
||||
public bool IsListening {
|
||||
get {
|
||||
return _listening;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets a value indicating whether the listener can be used with
|
||||
/// the current operating system.
|
||||
/// </summary>
|
||||
/// <value>
|
||||
/// <c>true</c>.
|
||||
/// </value>
|
||||
public static bool IsSupported {
|
||||
get {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the logging functions.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// <para>
|
||||
/// The default logging level is <see cref="LogLevel.Error"/>.
|
||||
/// </para>
|
||||
/// <para>
|
||||
/// If you would like to change it, you should set the <c>Log.Level</c>
|
||||
/// property to any of the <see cref="LogLevel"/> enum values.
|
||||
/// </para>
|
||||
/// </remarks>
|
||||
/// <value>
|
||||
/// A <see cref="Logger"/> that provides the logging functions.
|
||||
/// </value>
|
||||
public Logger Log {
|
||||
get {
|
||||
return _log;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the URI prefixes handled by the listener.
|
||||
/// </summary>
|
||||
/// <value>
|
||||
/// A <see cref="HttpListenerPrefixCollection"/> that contains the URI
|
||||
/// prefixes.
|
||||
/// </value>
|
||||
/// <exception cref="ObjectDisposedException">
|
||||
/// This listener has been closed.
|
||||
/// </exception>
|
||||
public HttpListenerPrefixCollection Prefixes {
|
||||
get {
|
||||
if (_disposed)
|
||||
throw new ObjectDisposedException (_objectName);
|
||||
|
||||
return _prefixes;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the name of the realm associated with the listener.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// If this property is <see langword="null"/> or an empty string,
|
||||
/// "SECRET AREA" will be used as the name of the realm.
|
||||
/// </remarks>
|
||||
/// <value>
|
||||
/// <para>
|
||||
/// A <see cref="string"/> that represents the name of the realm.
|
||||
/// </para>
|
||||
/// <para>
|
||||
/// The default value is <see langword="null"/>.
|
||||
/// </para>
|
||||
/// </value>
|
||||
/// <exception cref="ObjectDisposedException">
|
||||
/// This listener has been closed.
|
||||
/// </exception>
|
||||
public string Realm {
|
||||
get {
|
||||
if (_disposed)
|
||||
throw new ObjectDisposedException (_objectName);
|
||||
|
||||
return _realm;
|
||||
}
|
||||
|
||||
set {
|
||||
if (_disposed)
|
||||
throw new ObjectDisposedException (_objectName);
|
||||
|
||||
_realm = value;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the SSL configuration used to authenticate the server and
|
||||
/// optionally the client for secure connection.
|
||||
/// </summary>
|
||||
/// <value>
|
||||
/// A <see cref="ServerSslConfiguration"/> that represents the SSL
|
||||
/// configuration for secure connection.
|
||||
/// </value>
|
||||
/// <exception cref="ObjectDisposedException">
|
||||
/// This listener has been closed.
|
||||
/// </exception>
|
||||
public ServerSslConfiguration SslConfiguration {
|
||||
get {
|
||||
if (_disposed)
|
||||
throw new ObjectDisposedException (_objectName);
|
||||
|
||||
if (_sslConfig == null)
|
||||
_sslConfig = new ServerSslConfiguration ();
|
||||
|
||||
return _sslConfig;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets a value indicating whether, when NTLM authentication is used,
|
||||
/// the authentication information of first request is used to authenticate
|
||||
/// additional requests on the same connection.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// This property is not currently supported and always throws
|
||||
/// a <see cref="NotSupportedException"/>.
|
||||
/// </remarks>
|
||||
/// <value>
|
||||
/// <c>true</c> if the authentication information of first request is used;
|
||||
/// otherwise, <c>false</c>.
|
||||
/// </value>
|
||||
/// <exception cref="NotSupportedException">
|
||||
/// Any use of this property.
|
||||
/// </exception>
|
||||
public bool UnsafeConnectionNtlmAuthentication {
|
||||
get {
|
||||
throw new NotSupportedException ();
|
||||
}
|
||||
|
||||
set {
|
||||
throw new NotSupportedException ();
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the delegate called to find the credentials for
|
||||
/// an identity used to authenticate a client.
|
||||
/// </summary>
|
||||
/// <value>
|
||||
/// <para>
|
||||
/// A <c>Func<<see cref="IIdentity"/>,
|
||||
/// <see cref="NetworkCredential"/>></c> delegate or
|
||||
/// <see langword="null"/> if not needed.
|
||||
/// </para>
|
||||
/// <para>
|
||||
/// It references the method used to find the credentials.
|
||||
/// </para>
|
||||
/// <para>
|
||||
/// The default value is <see langword="null"/>.
|
||||
/// </para>
|
||||
/// </value>
|
||||
/// <exception cref="ObjectDisposedException">
|
||||
/// This listener has been closed.
|
||||
/// </exception>
|
||||
public Func<IIdentity, NetworkCredential> UserCredentialsFinder {
|
||||
get {
|
||||
if (_disposed)
|
||||
throw new ObjectDisposedException (_objectName);
|
||||
|
||||
return _userCredFinder;
|
||||
}
|
||||
|
||||
set {
|
||||
if (_disposed)
|
||||
throw new ObjectDisposedException (_objectName);
|
||||
|
||||
_userCredFinder = value;
|
||||
}
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
#region Private Methods
|
||||
|
||||
private HttpListenerAsyncResult beginGetContext (
|
||||
AsyncCallback callback, object state
|
||||
)
|
||||
{
|
||||
lock (_contextRegistrySync) {
|
||||
if (!_listening) {
|
||||
var msg = _disposed
|
||||
? "The listener is closed."
|
||||
: "The listener is stopped.";
|
||||
|
||||
throw new HttpListenerException (995, msg);
|
||||
}
|
||||
|
||||
var ares = new HttpListenerAsyncResult (callback, state);
|
||||
|
||||
if (_contextQueue.Count == 0) {
|
||||
_waitQueue.Enqueue (ares);
|
||||
}
|
||||
else {
|
||||
var ctx = _contextQueue.Dequeue ();
|
||||
ares.Complete (ctx, true);
|
||||
}
|
||||
|
||||
return ares;
|
||||
}
|
||||
}
|
||||
|
||||
private void cleanupContextQueue (bool force)
|
||||
{
|
||||
if (_contextQueue.Count == 0)
|
||||
return;
|
||||
|
||||
if (force) {
|
||||
_contextQueue.Clear ();
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
var ctxs = _contextQueue.ToArray ();
|
||||
|
||||
_contextQueue.Clear ();
|
||||
|
||||
foreach (var ctx in ctxs) {
|
||||
ctx.ErrorStatusCode = 503;
|
||||
ctx.SendError ();
|
||||
}
|
||||
}
|
||||
|
||||
private void cleanupContextRegistry ()
|
||||
{
|
||||
var cnt = _contextRegistry.Count;
|
||||
|
||||
if (cnt == 0)
|
||||
return;
|
||||
|
||||
var ctxs = new HttpListenerContext[cnt];
|
||||
_contextRegistry.CopyTo (ctxs, 0);
|
||||
|
||||
_contextRegistry.Clear ();
|
||||
|
||||
foreach (var ctx in ctxs)
|
||||
ctx.Connection.Close (true);
|
||||
}
|
||||
|
||||
private void cleanupWaitQueue (string message)
|
||||
{
|
||||
if (_waitQueue.Count == 0)
|
||||
return;
|
||||
|
||||
var aress = _waitQueue.ToArray ();
|
||||
|
||||
_waitQueue.Clear ();
|
||||
|
||||
foreach (var ares in aress) {
|
||||
var ex = new HttpListenerException (995, message);
|
||||
ares.Complete (ex);
|
||||
}
|
||||
}
|
||||
|
||||
private void close (bool force)
|
||||
{
|
||||
if (!_listening) {
|
||||
_disposed = true;
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
_listening = false;
|
||||
|
||||
cleanupContextQueue (force);
|
||||
cleanupContextRegistry ();
|
||||
|
||||
var msg = "The listener is closed.";
|
||||
cleanupWaitQueue (msg);
|
||||
|
||||
EndPointManager.RemoveListener (this);
|
||||
|
||||
_disposed = true;
|
||||
}
|
||||
|
||||
private string getRealm ()
|
||||
{
|
||||
var realm = _realm;
|
||||
|
||||
return realm != null && realm.Length > 0 ? realm : _defaultRealm;
|
||||
}
|
||||
|
||||
private AuthenticationSchemes selectAuthenticationScheme (
|
||||
HttpListenerRequest request
|
||||
)
|
||||
{
|
||||
var selector = _authSchemeSelector;
|
||||
|
||||
if (selector == null)
|
||||
return _authSchemes;
|
||||
|
||||
try {
|
||||
return selector (request);
|
||||
}
|
||||
catch {
|
||||
return AuthenticationSchemes.None;
|
||||
}
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
#region Internal Methods
|
||||
|
||||
internal bool AuthenticateContext (HttpListenerContext context)
|
||||
{
|
||||
var req = context.Request;
|
||||
var schm = selectAuthenticationScheme (req);
|
||||
|
||||
if (schm == AuthenticationSchemes.Anonymous)
|
||||
return true;
|
||||
|
||||
if (schm == AuthenticationSchemes.None) {
|
||||
context.ErrorStatusCode = 403;
|
||||
context.ErrorMessage = "Authentication not allowed";
|
||||
|
||||
context.SendError ();
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
var realm = getRealm ();
|
||||
var user = HttpUtility.CreateUser (
|
||||
req.Headers["Authorization"],
|
||||
schm,
|
||||
realm,
|
||||
req.HttpMethod,
|
||||
_userCredFinder
|
||||
);
|
||||
|
||||
var authenticated = user != null && user.Identity.IsAuthenticated;
|
||||
|
||||
if (!authenticated) {
|
||||
context.SendAuthenticationChallenge (schm, realm);
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
context.User = user;
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
internal void CheckDisposed ()
|
||||
{
|
||||
if (_disposed)
|
||||
throw new ObjectDisposedException (_objectName);
|
||||
}
|
||||
|
||||
internal bool RegisterContext (HttpListenerContext context)
|
||||
{
|
||||
if (!_listening)
|
||||
return false;
|
||||
|
||||
lock (_contextRegistrySync) {
|
||||
if (!_listening)
|
||||
return false;
|
||||
|
||||
context.Listener = this;
|
||||
|
||||
_contextRegistry.AddLast (context);
|
||||
|
||||
if (_waitQueue.Count == 0) {
|
||||
_contextQueue.Enqueue (context);
|
||||
}
|
||||
else {
|
||||
var ares = _waitQueue.Dequeue ();
|
||||
ares.Complete (context, false);
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
internal void UnregisterContext (HttpListenerContext context)
|
||||
{
|
||||
lock (_contextRegistrySync)
|
||||
_contextRegistry.Remove (context);
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
#region Public Methods
|
||||
|
||||
/// <summary>
|
||||
/// Shuts down the listener immediately.
|
||||
/// </summary>
|
||||
public void Abort ()
|
||||
{
|
||||
if (_disposed)
|
||||
return;
|
||||
|
||||
lock (_contextRegistrySync) {
|
||||
if (_disposed)
|
||||
return;
|
||||
|
||||
close (true);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Begins getting an incoming request asynchronously.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// <para>
|
||||
/// This asynchronous operation must be completed by calling
|
||||
/// the EndGetContext method.
|
||||
/// </para>
|
||||
/// <para>
|
||||
/// Typically, the EndGetContext method is called by
|
||||
/// <paramref name="callback"/>.
|
||||
/// </para>
|
||||
/// </remarks>
|
||||
/// <returns>
|
||||
/// An <see cref="IAsyncResult"/> that represents the status of
|
||||
/// the asynchronous operation.
|
||||
/// </returns>
|
||||
/// <param name="callback">
|
||||
/// An <see cref="AsyncCallback"/> delegate that references the method to
|
||||
/// invoke when the asynchronous operation completes.
|
||||
/// </param>
|
||||
/// <param name="state">
|
||||
/// An <see cref="object"/> that represents a user defined object to
|
||||
/// pass to <paramref name="callback"/>.
|
||||
/// </param>
|
||||
/// <exception cref="InvalidOperationException">
|
||||
/// <para>
|
||||
/// This listener has no URI prefix on which listens.
|
||||
/// </para>
|
||||
/// <para>
|
||||
/// -or-
|
||||
/// </para>
|
||||
/// <para>
|
||||
/// This listener has not been started or is currently stopped.
|
||||
/// </para>
|
||||
/// </exception>
|
||||
/// <exception cref="HttpListenerException">
|
||||
/// This method is canceled.
|
||||
/// </exception>
|
||||
/// <exception cref="ObjectDisposedException">
|
||||
/// This listener has been closed.
|
||||
/// </exception>
|
||||
public IAsyncResult BeginGetContext (AsyncCallback callback, object state)
|
||||
{
|
||||
if (_disposed)
|
||||
throw new ObjectDisposedException (_objectName);
|
||||
|
||||
if (_prefixes.Count == 0) {
|
||||
var msg = "The listener has no URI prefix on which listens.";
|
||||
|
||||
throw new InvalidOperationException (msg);
|
||||
}
|
||||
|
||||
if (!_listening) {
|
||||
var msg = "The listener has not been started.";
|
||||
|
||||
throw new InvalidOperationException (msg);
|
||||
}
|
||||
|
||||
return beginGetContext (callback, state);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Shuts down the listener.
|
||||
/// </summary>
|
||||
public void Close ()
|
||||
{
|
||||
if (_disposed)
|
||||
return;
|
||||
|
||||
lock (_contextRegistrySync) {
|
||||
if (_disposed)
|
||||
return;
|
||||
|
||||
close (false);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Ends an asynchronous operation to get an incoming request.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// This method completes an asynchronous operation started by calling
|
||||
/// the BeginGetContext method.
|
||||
/// </remarks>
|
||||
/// <returns>
|
||||
/// A <see cref="HttpListenerContext"/> that represents a request.
|
||||
/// </returns>
|
||||
/// <param name="asyncResult">
|
||||
/// An <see cref="IAsyncResult"/> instance obtained by calling
|
||||
/// the BeginGetContext method.
|
||||
/// </param>
|
||||
/// <exception cref="ArgumentNullException">
|
||||
/// <paramref name="asyncResult"/> is <see langword="null"/>.
|
||||
/// </exception>
|
||||
/// <exception cref="ArgumentException">
|
||||
/// <paramref name="asyncResult"/> was not obtained by calling
|
||||
/// the BeginGetContext method.
|
||||
/// </exception>
|
||||
/// <exception cref="InvalidOperationException">
|
||||
/// This method was already called for <paramref name="asyncResult"/>.
|
||||
/// </exception>
|
||||
/// <exception cref="HttpListenerException">
|
||||
/// This method is canceled.
|
||||
/// </exception>
|
||||
/// <exception cref="ObjectDisposedException">
|
||||
/// This listener has been closed.
|
||||
/// </exception>
|
||||
public HttpListenerContext EndGetContext (IAsyncResult asyncResult)
|
||||
{
|
||||
if (_disposed)
|
||||
throw new ObjectDisposedException (_objectName);
|
||||
|
||||
if (asyncResult == null)
|
||||
throw new ArgumentNullException ("asyncResult");
|
||||
|
||||
var ares = asyncResult as HttpListenerAsyncResult;
|
||||
|
||||
if (ares == null) {
|
||||
var msg = "A wrong IAsyncResult instance.";
|
||||
|
||||
throw new ArgumentException (msg, "asyncResult");
|
||||
}
|
||||
|
||||
lock (ares.SyncRoot) {
|
||||
if (ares.EndCalled) {
|
||||
var msg = "This IAsyncResult instance cannot be reused.";
|
||||
|
||||
throw new InvalidOperationException (msg);
|
||||
}
|
||||
|
||||
ares.EndCalled = true;
|
||||
}
|
||||
|
||||
if (!ares.IsCompleted)
|
||||
ares.AsyncWaitHandle.WaitOne ();
|
||||
|
||||
return ares.Context;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets an incoming request.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// This method waits for an incoming request and returns when a request is
|
||||
/// received.
|
||||
/// </remarks>
|
||||
/// <returns>
|
||||
/// A <see cref="HttpListenerContext"/> that represents a request.
|
||||
/// </returns>
|
||||
/// <exception cref="InvalidOperationException">
|
||||
/// <para>
|
||||
/// This listener has no URI prefix on which listens.
|
||||
/// </para>
|
||||
/// <para>
|
||||
/// -or-
|
||||
/// </para>
|
||||
/// <para>
|
||||
/// This listener has not been started or is currently stopped.
|
||||
/// </para>
|
||||
/// </exception>
|
||||
/// <exception cref="HttpListenerException">
|
||||
/// This method is canceled.
|
||||
/// </exception>
|
||||
/// <exception cref="ObjectDisposedException">
|
||||
/// This listener has been closed.
|
||||
/// </exception>
|
||||
public HttpListenerContext GetContext ()
|
||||
{
|
||||
if (_disposed)
|
||||
throw new ObjectDisposedException (_objectName);
|
||||
|
||||
if (_prefixes.Count == 0) {
|
||||
var msg = "The listener has no URI prefix on which listens.";
|
||||
|
||||
throw new InvalidOperationException (msg);
|
||||
}
|
||||
|
||||
if (!_listening) {
|
||||
var msg = "The listener has not been started.";
|
||||
|
||||
throw new InvalidOperationException (msg);
|
||||
}
|
||||
|
||||
var ares = beginGetContext (null, null);
|
||||
ares.EndCalled = true;
|
||||
|
||||
if (!ares.IsCompleted)
|
||||
ares.AsyncWaitHandle.WaitOne ();
|
||||
|
||||
return ares.Context;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Starts receiving incoming requests.
|
||||
/// </summary>
|
||||
/// <exception cref="ObjectDisposedException">
|
||||
/// This listener has been closed.
|
||||
/// </exception>
|
||||
public void Start ()
|
||||
{
|
||||
if (_disposed)
|
||||
throw new ObjectDisposedException (_objectName);
|
||||
|
||||
lock (_contextRegistrySync) {
|
||||
if (_disposed)
|
||||
throw new ObjectDisposedException (_objectName);
|
||||
|
||||
if (_listening)
|
||||
return;
|
||||
|
||||
EndPointManager.AddListener (this);
|
||||
|
||||
_listening = true;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Stops receiving incoming requests.
|
||||
/// </summary>
|
||||
/// <exception cref="ObjectDisposedException">
|
||||
/// This listener has been closed.
|
||||
/// </exception>
|
||||
public void Stop ()
|
||||
{
|
||||
if (_disposed)
|
||||
throw new ObjectDisposedException (_objectName);
|
||||
|
||||
lock (_contextRegistrySync) {
|
||||
if (!_listening)
|
||||
return;
|
||||
|
||||
_listening = false;
|
||||
|
||||
cleanupContextQueue (false);
|
||||
cleanupContextRegistry ();
|
||||
|
||||
var msg = "The listener is stopped.";
|
||||
cleanupWaitQueue (msg);
|
||||
|
||||
EndPointManager.RemoveListener (this);
|
||||
}
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
#region Explicit Interface Implementations
|
||||
|
||||
/// <summary>
|
||||
/// Releases all resources used by the listener.
|
||||
/// </summary>
|
||||
void IDisposable.Dispose ()
|
||||
{
|
||||
if (_disposed)
|
||||
return;
|
||||
|
||||
lock (_contextRegistrySync) {
|
||||
if (_disposed)
|
||||
return;
|
||||
|
||||
close (true);
|
||||
}
|
||||
}
|
||||
|
||||
#endregion
|
||||
}
|
||||
}
|
193
websocket-sharp/Net/HttpListenerAsyncResult.cs
Normal file
193
websocket-sharp/Net/HttpListenerAsyncResult.cs
Normal file
@@ -0,0 +1,193 @@
|
||||
#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-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
|
||||
|
||||
#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 object _state;
|
||||
private object _sync;
|
||||
private ManualResetEvent _waitHandle;
|
||||
|
||||
#endregion
|
||||
|
||||
#region Internal Constructors
|
||||
|
||||
internal HttpListenerAsyncResult (AsyncCallback callback, object state)
|
||||
{
|
||||
_callback = callback;
|
||||
_state = state;
|
||||
|
||||
_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 {
|
||||
}
|
||||
},
|
||||
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
|
||||
}
|
||||
}
|
311
websocket-sharp/Net/HttpListenerContext.cs
Normal file
311
websocket-sharp/Net/HttpListenerContext.cs
Normal file
@@ -0,0 +1,311 @@
|
||||
#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-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
|
||||
|
||||
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 (identity, authentication, and security
|
||||
/// roles).
|
||||
/// </summary>
|
||||
/// <value>
|
||||
/// <para>
|
||||
/// A <see cref="IPrincipal"/> instance or <see langword="null"/>
|
||||
/// if not authenticated.
|
||||
/// </para>
|
||||
/// <para>
|
||||
/// The instance describes the client.
|
||||
/// </para>
|
||||
/// </value>
|
||||
public IPrincipal User {
|
||||
get {
|
||||
return _user;
|
||||
}
|
||||
|
||||
internal set {
|
||||
_user = value;
|
||||
}
|
||||
}
|
||||
|
||||
#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
|
||||
)
|
||||
{
|
||||
var chal = new AuthenticationChallenge (scheme, realm).ToString ();
|
||||
|
||||
_response.StatusCode = 401;
|
||||
_response.Headers.InternalSet ("WWW-Authenticate", chal, 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 Unregister ()
|
||||
{
|
||||
if (_listener == null)
|
||||
return;
|
||||
|
||||
_listener.UnregisterContext (this);
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
#region Public Methods
|
||||
|
||||
/// <summary>
|
||||
/// Accepts a WebSocket handshake request.
|
||||
/// </summary>
|
||||
/// <returns>
|
||||
/// A <see cref="HttpListenerWebSocketContext"/> that represents
|
||||
/// the WebSocket handshake request.
|
||||
/// </returns>
|
||||
/// <param name="protocol">
|
||||
/// A <see cref="string"/> that specifies the subprotocol supported on
|
||||
/// the WebSocket connection.
|
||||
/// </param>
|
||||
/// <exception cref="ArgumentException">
|
||||
/// <para>
|
||||
/// <paramref name="protocol"/> is empty.
|
||||
/// </para>
|
||||
/// <para>
|
||||
/// -or-
|
||||
/// </para>
|
||||
/// <para>
|
||||
/// <paramref name="protocol"/> contains an invalid character.
|
||||
/// </para>
|
||||
/// </exception>
|
||||
/// <exception cref="InvalidOperationException">
|
||||
/// This method has already been called.
|
||||
/// </exception>
|
||||
public HttpListenerWebSocketContext AcceptWebSocket (string protocol)
|
||||
{
|
||||
if (_websocketContext != null) {
|
||||
var msg = "The accepting is already in progress.";
|
||||
|
||||
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");
|
||||
}
|
||||
}
|
||||
|
||||
return GetWebSocketContext (protocol);
|
||||
}
|
||||
|
||||
#endregion
|
||||
}
|
||||
}
|
137
websocket-sharp/Net/HttpListenerException.cs
Normal file
137
websocket-sharp/Net/HttpListenerException.cs
Normal file
@@ -0,0 +1,137 @@
|
||||
#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-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.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 from the specified instances of the <see cref="SerializationInfo"/>
|
||||
/// and <see cref="StreamingContext"/> classes.
|
||||
/// </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>
|
||||
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
|
||||
}
|
||||
}
|
273
websocket-sharp/Net/HttpListenerPrefix.cs
Normal file
273
websocket-sharp/Net/HttpListenerPrefix.cs
Normal file
@@ -0,0 +1,273 @@
|
||||
#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-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>
|
||||
* - Oleg Mihailik <mihailik@gmail.com>
|
||||
*/
|
||||
#endregion
|
||||
|
||||
using System;
|
||||
|
||||
namespace WebSocketSharp.Net
|
||||
{
|
||||
internal sealed class HttpListenerPrefix
|
||||
{
|
||||
#region Private Fields
|
||||
|
||||
private string _host;
|
||||
private HttpListener _listener;
|
||||
private string _original;
|
||||
private string _path;
|
||||
private string _port;
|
||||
private string _prefix;
|
||||
private bool _secure;
|
||||
|
||||
#endregion
|
||||
|
||||
#region Internal Constructors
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="HttpListenerPrefix"/> class
|
||||
/// with the specified URI prefix and HTTP listener.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// This constructor must be called after calling the CheckPrefix method.
|
||||
/// </remarks>
|
||||
/// <param name="uriPrefix">
|
||||
/// A <see cref="string"/> that specifies the URI prefix.
|
||||
/// </param>
|
||||
/// <param name="listener">
|
||||
/// A <see cref="HttpListener"/> that specifies the HTTP listener.
|
||||
/// </param>
|
||||
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 _secure;
|
||||
}
|
||||
}
|
||||
|
||||
public HttpListener Listener {
|
||||
get {
|
||||
return _listener;
|
||||
}
|
||||
}
|
||||
|
||||
public string Original {
|
||||
get {
|
||||
return _original;
|
||||
}
|
||||
}
|
||||
|
||||
public string Path {
|
||||
get {
|
||||
return _path;
|
||||
}
|
||||
}
|
||||
|
||||
public string Port {
|
||||
get {
|
||||
return _port;
|
||||
}
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
#region Private Methods
|
||||
|
||||
private void parse (string uriPrefix)
|
||||
{
|
||||
if (uriPrefix.StartsWith ("https"))
|
||||
_secure = true;
|
||||
|
||||
var len = uriPrefix.Length;
|
||||
var host = uriPrefix.IndexOf (':') + 3;
|
||||
var root = uriPrefix.IndexOf ('/', host + 1, len - host - 1);
|
||||
|
||||
var colon = uriPrefix.LastIndexOf (':', root - 1, root - host - 1);
|
||||
|
||||
if (uriPrefix[root - 1] != ']' && colon > host) {
|
||||
_host = uriPrefix.Substring (host, colon - host);
|
||||
_port = uriPrefix.Substring (colon + 1, root - colon - 1);
|
||||
}
|
||||
else {
|
||||
_host = uriPrefix.Substring (host, root - host);
|
||||
_port = _secure ? "443" : "80";
|
||||
}
|
||||
|
||||
_path = uriPrefix.Substring (root);
|
||||
|
||||
_prefix = String.Format (
|
||||
"{0}://{1}:{2}{3}",
|
||||
_secure ? "https" : "http",
|
||||
_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 schm = uriPrefix.StartsWith ("http://")
|
||||
|| uriPrefix.StartsWith ("https://");
|
||||
|
||||
if (!schm) {
|
||||
var msg = "The scheme is not 'http' or 'https'.";
|
||||
|
||||
throw new ArgumentException (msg, "uriPrefix");
|
||||
}
|
||||
|
||||
var end = len - 1;
|
||||
|
||||
if (uriPrefix[end] != '/') {
|
||||
var msg = "It ends without '/'.";
|
||||
|
||||
throw new ArgumentException (msg, "uriPrefix");
|
||||
}
|
||||
|
||||
var host = uriPrefix.IndexOf (':') + 3;
|
||||
|
||||
if (host >= end) {
|
||||
var msg = "No host is specified.";
|
||||
|
||||
throw new ArgumentException (msg, "uriPrefix");
|
||||
}
|
||||
|
||||
if (uriPrefix[host] == ':') {
|
||||
var msg = "No host is specified.";
|
||||
|
||||
throw new ArgumentException (msg, "uriPrefix");
|
||||
}
|
||||
|
||||
var root = uriPrefix.IndexOf ('/', host, len - host);
|
||||
|
||||
if (root == host) {
|
||||
var msg = "No host is specified.";
|
||||
|
||||
throw new ArgumentException (msg, "uriPrefix");
|
||||
}
|
||||
|
||||
if (uriPrefix[root - 1] == ':') {
|
||||
var msg = "No port is specified.";
|
||||
|
||||
throw new ArgumentException (msg, "uriPrefix");
|
||||
}
|
||||
|
||||
if (root == end - 1) {
|
||||
var msg = "No path is specified.";
|
||||
|
||||
throw new ArgumentException (msg, "uriPrefix");
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Determines whether the current instance is equal to the specified
|
||||
/// <see cref="object"/> instance.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// This method will be required to detect duplicates in any collection.
|
||||
/// </remarks>
|
||||
/// <param name="obj">
|
||||
/// <para>
|
||||
/// An <see cref="object"/> instance to compare to the current instance.
|
||||
/// </para>
|
||||
/// <para>
|
||||
/// An reference to a <see cref="HttpListenerPrefix"/> instance.
|
||||
/// </para>
|
||||
/// </param>
|
||||
/// <returns>
|
||||
/// <c>true</c> if the current instance and <paramref name="obj"/> have
|
||||
/// the same URI prefix; otherwise, <c>false</c>.
|
||||
/// </returns>
|
||||
public override bool Equals (object obj)
|
||||
{
|
||||
var pref = obj as HttpListenerPrefix;
|
||||
|
||||
return pref != null && _prefix.Equals (pref._prefix);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the hash code for the current instance.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// This method will be required to detect duplicates in any collection.
|
||||
/// </remarks>
|
||||
/// <returns>
|
||||
/// An <see cref="int"/> that represents the hash code.
|
||||
/// </returns>
|
||||
public override int GetHashCode ()
|
||||
{
|
||||
return _prefix.GetHashCode ();
|
||||
}
|
||||
|
||||
public override string ToString ()
|
||||
{
|
||||
return _prefix;
|
||||
}
|
||||
|
||||
#endregion
|
||||
}
|
||||
}
|
294
websocket-sharp/Net/HttpListenerPrefixCollection.cs
Normal file
294
websocket-sharp/Net/HttpListenerPrefixCollection.cs
Normal file
@@ -0,0 +1,294 @@
|
||||
#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-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
|
||||
|
||||
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 '/'.
|
||||
/// </para>
|
||||
/// </param>
|
||||
/// <exception cref="ArgumentNullException">
|
||||
/// <paramref name="uriPrefix"/> is <see langword="null"/>.
|
||||
/// </exception>
|
||||
/// <exception cref="ArgumentException">
|
||||
/// <paramref name="uriPrefix"/> is invalid.
|
||||
/// </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="ArgumentNullException">
|
||||
/// <paramref name="array"/> is <see langword="null"/>.
|
||||
/// </exception>
|
||||
/// <exception cref="ArgumentOutOfRangeException">
|
||||
/// <paramref name="offset"/> is less than zero.
|
||||
/// </exception>
|
||||
/// <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="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
|
||||
}
|
||||
}
|
928
websocket-sharp/Net/HttpListenerRequest.cs
Normal file
928
websocket-sharp/Net/HttpListenerRequest.cs
Normal file
@@ -0,0 +1,928 @@
|
||||
#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-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.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 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");
|
||||
}
|
||||
|
||||
#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 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 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>
|
||||
/// An empty collection if not included.
|
||||
/// </para>
|
||||
/// </value>
|
||||
public NameValueCollection QueryString {
|
||||
get {
|
||||
if (_queryString == null) {
|
||||
var url = Url;
|
||||
|
||||
_queryString = QueryStringCollection
|
||||
.Parse (
|
||||
url != null ? url.Query : null,
|
||||
Encoding.UTF8
|
||||
);
|
||||
}
|
||||
|
||||
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 ?? UserHostAddress,
|
||||
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"/> converted from 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>
|
||||
/// <para>
|
||||
/// <see langword="null"/> if the header is not present.
|
||||
/// </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 Encoding.UTF8;
|
||||
|
||||
Encoding ret;
|
||||
|
||||
return HttpUtility.TryGetEncoding (val, out ret)
|
||||
? ret
|
||||
: Encoding.UTF8;
|
||||
}
|
||||
|
||||
#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 comparison = StringComparison.OrdinalIgnoreCase;
|
||||
|
||||
if (!transferEnc.Equals ("chunked", comparison)) {
|
||||
_context.ErrorMessage = "Invalid Transfer-Encoding header";
|
||||
_context.ErrorStatusCode = 501;
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
_chunked = true;
|
||||
}
|
||||
|
||||
if (_httpMethod == "POST" || _httpMethod == "PUT") {
|
||||
if (_contentLength <= 0 && !_chunked) {
|
||||
_context.ErrorMessage = String.Empty;
|
||||
_context.ErrorStatusCode = 411;
|
||||
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
var expect = _headers["Expect"];
|
||||
|
||||
if (expect != null) {
|
||||
var comparison = StringComparison.OrdinalIgnoreCase;
|
||||
|
||||
if (!expect.Equals ("100-continue", comparison)) {
|
||||
_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;
|
||||
}
|
||||
|
||||
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.ErrorMessage = "Invalid request line (version)";
|
||||
_context.ErrorStatusCode = 505;
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
if (!method.IsHttpMethod (ver)) {
|
||||
_context.ErrorMessage = "Invalid request line (method)";
|
||||
_context.ErrorStatusCode = 501;
|
||||
|
||||
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 indicates the status of the
|
||||
/// operation.
|
||||
/// </returns>
|
||||
/// <param name="requestCallback">
|
||||
/// An <see cref="AsyncCallback"/> delegate that invokes the method called
|
||||
/// when the operation is complete.
|
||||
/// </param>
|
||||
/// <param name="state">
|
||||
/// An <see cref="object"/> that represents a user defined object to pass to
|
||||
/// the callback delegate.
|
||||
/// </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 returned when the operation
|
||||
/// started.
|
||||
/// </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);
|
||||
|
||||
buff
|
||||
.AppendFormat (
|
||||
"{0} {1} HTTP/{2}\r\n", _httpMethod, _rawUrl, _protocolVersion
|
||||
)
|
||||
.Append (_headers.ToString ());
|
||||
|
||||
return buff.ToString ();
|
||||
}
|
||||
|
||||
#endregion
|
||||
}
|
||||
}
|
1199
websocket-sharp/Net/HttpListenerResponse.cs
Normal file
1199
websocket-sharp/Net/HttpListenerResponse.cs
Normal file
File diff suppressed because it is too large
Load Diff
233
websocket-sharp/Net/HttpRequestHeader.cs
Normal file
233
websocket-sharp/Net/HttpRequestHeader.cs
Normal 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
|
||||
}
|
||||
}
|
189
websocket-sharp/Net/HttpResponseHeader.cs
Normal file
189
websocket-sharp/Net/HttpResponseHeader.cs
Normal 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
|
||||
}
|
||||
}
|
346
websocket-sharp/Net/HttpStatusCode.cs
Normal file
346
websocket-sharp/Net/HttpStatusCode.cs
Normal 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,
|
||||
}
|
||||
}
|
201
websocket-sharp/Net/HttpStreamAsyncResult.cs
Normal file
201
websocket-sharp/Net/HttpStreamAsyncResult.cs
Normal 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
|
||||
}
|
||||
}
|
1150
websocket-sharp/Net/HttpUtility.cs
Normal file
1150
websocket-sharp/Net/HttpUtility.cs
Normal file
File diff suppressed because it is too large
Load Diff
73
websocket-sharp/Net/HttpVersion.cs
Normal file
73
websocket-sharp/Net/HttpVersion.cs
Normal file
@@ -0,0 +1,73 @@
|
||||
#region License
|
||||
/*
|
||||
* HttpVersion.cs
|
||||
*
|
||||
* This code is derived from System.Net.HttpVersion.cs of Mono
|
||||
* (http://www.mono-project.com).
|
||||
*
|
||||
* The MIT License
|
||||
*
|
||||
* Copyright (c) 2012-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
|
||||
|
||||
#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
|
||||
}
|
||||
}
|
52
websocket-sharp/Net/InputChunkState.cs
Normal file
52
websocket-sharp/Net/InputChunkState.cs
Normal 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
|
||||
}
|
||||
}
|
49
websocket-sharp/Net/InputState.cs
Normal file
49
websocket-sharp/Net/InputState.cs
Normal 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
|
||||
}
|
||||
}
|
50
websocket-sharp/Net/LineState.cs
Normal file
50
websocket-sharp/Net/LineState.cs
Normal file
@@ -0,0 +1,50 @@
|
||||
#region License
|
||||
/*
|
||||
* LineState.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 LineState
|
||||
{
|
||||
None,
|
||||
Cr,
|
||||
Lf
|
||||
}
|
||||
}
|
209
websocket-sharp/Net/NetworkCredential.cs
Normal file
209
websocket-sharp/Net/NetworkCredential.cs
Normal file
@@ -0,0 +1,209 @@
|
||||
#region License
|
||||
/*
|
||||
* NetworkCredential.cs
|
||||
*
|
||||
* The MIT License
|
||||
*
|
||||
* 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
|
||||
|
||||
using System;
|
||||
|
||||
namespace WebSocketSharp.Net
|
||||
{
|
||||
/// <summary>
|
||||
/// Provides the credentials for the password-based authentication.
|
||||
/// </summary>
|
||||
public class NetworkCredential
|
||||
{
|
||||
#region Private Fields
|
||||
|
||||
private string _domain;
|
||||
private static readonly string[] _noRoles;
|
||||
private string _password;
|
||||
private string[] _roles;
|
||||
private string _username;
|
||||
|
||||
#endregion
|
||||
|
||||
#region Static Constructor
|
||||
|
||||
static NetworkCredential ()
|
||||
{
|
||||
_noRoles = new string[0];
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
#region Public Constructors
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="NetworkCredential"/> class with
|
||||
/// the specified <paramref name="username"/> and <paramref name="password"/>.
|
||||
/// </summary>
|
||||
/// <param name="username">
|
||||
/// A <see cref="string"/> that represents the username associated with
|
||||
/// the credentials.
|
||||
/// </param>
|
||||
/// <param name="password">
|
||||
/// A <see cref="string"/> that represents the password for the username
|
||||
/// associated with the credentials.
|
||||
/// </param>
|
||||
/// <exception cref="ArgumentNullException">
|
||||
/// <paramref name="username"/> is <see langword="null"/>.
|
||||
/// </exception>
|
||||
/// <exception cref="ArgumentException">
|
||||
/// <paramref name="username"/> is empty.
|
||||
/// </exception>
|
||||
public NetworkCredential (string username, string password)
|
||||
: this (username, password, null, null)
|
||||
{
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="NetworkCredential"/> class with
|
||||
/// the specified <paramref name="username"/>, <paramref name="password"/>,
|
||||
/// <paramref name="domain"/> and <paramref name="roles"/>.
|
||||
/// </summary>
|
||||
/// <param name="username">
|
||||
/// A <see cref="string"/> that represents the username associated with
|
||||
/// the credentials.
|
||||
/// </param>
|
||||
/// <param name="password">
|
||||
/// A <see cref="string"/> that represents the password for the username
|
||||
/// associated with the credentials.
|
||||
/// </param>
|
||||
/// <param name="domain">
|
||||
/// A <see cref="string"/> that represents the domain associated with
|
||||
/// the credentials.
|
||||
/// </param>
|
||||
/// <param name="roles">
|
||||
/// An array of <see cref="string"/> that represents the roles
|
||||
/// associated with the credentials if any.
|
||||
/// </param>
|
||||
/// <exception cref="ArgumentNullException">
|
||||
/// <paramref name="username"/> is <see langword="null"/>.
|
||||
/// </exception>
|
||||
/// <exception cref="ArgumentException">
|
||||
/// <paramref name="username"/> is empty.
|
||||
/// </exception>
|
||||
public NetworkCredential (
|
||||
string username, string password, string domain, params string[] roles
|
||||
)
|
||||
{
|
||||
if (username == null)
|
||||
throw new ArgumentNullException ("username");
|
||||
|
||||
if (username.Length == 0)
|
||||
throw new ArgumentException ("An empty string.", "username");
|
||||
|
||||
_username = username;
|
||||
_password = password;
|
||||
_domain = domain;
|
||||
_roles = roles;
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
#region Public Properties
|
||||
|
||||
/// <summary>
|
||||
/// Gets the domain associated with the credentials.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// This property returns an empty string if the domain was
|
||||
/// initialized with <see langword="null"/>.
|
||||
/// </remarks>
|
||||
/// <value>
|
||||
/// A <see cref="string"/> that represents the domain name
|
||||
/// to which the username belongs.
|
||||
/// </value>
|
||||
public string Domain {
|
||||
get {
|
||||
return _domain ?? String.Empty;
|
||||
}
|
||||
|
||||
internal set {
|
||||
_domain = value;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the password for the username associated with the credentials.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// This property returns an empty string if the password was
|
||||
/// initialized with <see langword="null"/>.
|
||||
/// </remarks>
|
||||
/// <value>
|
||||
/// A <see cref="string"/> that represents the password.
|
||||
/// </value>
|
||||
public string Password {
|
||||
get {
|
||||
return _password ?? String.Empty;
|
||||
}
|
||||
|
||||
internal set {
|
||||
_password = value;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the roles associated with the credentials.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// This property returns an empty array if the roles were
|
||||
/// initialized with <see langword="null"/>.
|
||||
/// </remarks>
|
||||
/// <value>
|
||||
/// An array of <see cref="string"/> that represents the role names
|
||||
/// to which the username belongs.
|
||||
/// </value>
|
||||
public string[] Roles {
|
||||
get {
|
||||
return _roles ?? _noRoles;
|
||||
}
|
||||
|
||||
internal set {
|
||||
_roles = value;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the username associated with the credentials.
|
||||
/// </summary>
|
||||
/// <value>
|
||||
/// A <see cref="string"/> that represents the username.
|
||||
/// </value>
|
||||
public string Username {
|
||||
get {
|
||||
return _username;
|
||||
}
|
||||
|
||||
internal set {
|
||||
_username = value;
|
||||
}
|
||||
}
|
||||
|
||||
#endregion
|
||||
}
|
||||
}
|
150
websocket-sharp/Net/QueryStringCollection.cs
Normal file
150
websocket-sharp/Net/QueryStringCollection.cs
Normal file
@@ -0,0 +1,150 @@
|
||||
#region License
|
||||
/*
|
||||
* QueryStringCollection.cs
|
||||
*
|
||||
* This code is derived from HttpUtility.cs (System.Net) of Mono
|
||||
* (http://www.mono-project.com).
|
||||
*
|
||||
* The MIT License
|
||||
*
|
||||
* Copyright (c) 2005-2009 Novell, Inc. (http://www.novell.com)
|
||||
* Copyright (c) 2018 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:
|
||||
* - Patrik Torstensson <Patrik.Torstensson@labs2.com>
|
||||
* - Wictor Wilén (decode/encode functions) <wictor@ibizkit.se>
|
||||
* - Tim Coleman <tim@timcoleman.com>
|
||||
* - Gonzalo Paniagua Javier <gonzalo@ximian.com>
|
||||
*/
|
||||
#endregion
|
||||
|
||||
using System;
|
||||
using System.Collections.Specialized;
|
||||
using System.Text;
|
||||
|
||||
namespace WebSocketSharp.Net
|
||||
{
|
||||
internal sealed class QueryStringCollection : NameValueCollection
|
||||
{
|
||||
#region Public Constructors
|
||||
|
||||
public QueryStringCollection ()
|
||||
{
|
||||
}
|
||||
|
||||
public QueryStringCollection (int capacity)
|
||||
: base (capacity)
|
||||
{
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
#region Private Methods
|
||||
|
||||
private static string urlDecode (string s, Encoding encoding)
|
||||
{
|
||||
return s.IndexOfAny (new[] { '%', '+' }) > -1
|
||||
? HttpUtility.UrlDecode (s, encoding)
|
||||
: s;
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
#region Public Methods
|
||||
|
||||
public static QueryStringCollection Parse (string query)
|
||||
{
|
||||
return Parse (query, Encoding.UTF8);
|
||||
}
|
||||
|
||||
public static QueryStringCollection Parse (string query, Encoding encoding)
|
||||
{
|
||||
if (query == null)
|
||||
return new QueryStringCollection (1);
|
||||
|
||||
var len = query.Length;
|
||||
if (len == 0)
|
||||
return new QueryStringCollection (1);
|
||||
|
||||
if (query == "?")
|
||||
return new QueryStringCollection (1);
|
||||
|
||||
if (query[0] == '?')
|
||||
query = query.Substring (1);
|
||||
|
||||
if (encoding == null)
|
||||
encoding = Encoding.UTF8;
|
||||
|
||||
var ret = new QueryStringCollection ();
|
||||
|
||||
var components = query.Split ('&');
|
||||
foreach (var component in components) {
|
||||
len = component.Length;
|
||||
if (len == 0)
|
||||
continue;
|
||||
|
||||
if (component == "=")
|
||||
continue;
|
||||
|
||||
var i = component.IndexOf ('=');
|
||||
if (i < 0) {
|
||||
ret.Add (null, urlDecode (component, encoding));
|
||||
continue;
|
||||
}
|
||||
|
||||
if (i == 0) {
|
||||
ret.Add (null, urlDecode (component.Substring (1), encoding));
|
||||
continue;
|
||||
}
|
||||
|
||||
var name = urlDecode (component.Substring (0, i), encoding);
|
||||
|
||||
var start = i + 1;
|
||||
var val = start < len
|
||||
? urlDecode (component.Substring (start), encoding)
|
||||
: String.Empty;
|
||||
|
||||
ret.Add (name, val);
|
||||
}
|
||||
|
||||
return ret;
|
||||
}
|
||||
|
||||
public override string ToString ()
|
||||
{
|
||||
var buff = new StringBuilder ();
|
||||
|
||||
foreach (var key in AllKeys)
|
||||
buff.AppendFormat ("{0}={1}&", key, this[key]);
|
||||
|
||||
if (buff.Length > 0)
|
||||
buff.Length--;
|
||||
|
||||
return buff.ToString ();
|
||||
}
|
||||
|
||||
#endregion
|
||||
}
|
||||
}
|
126
websocket-sharp/Net/ReadBufferState.cs
Normal file
126
websocket-sharp/Net/ReadBufferState.cs
Normal file
@@ -0,0 +1,126 @@
|
||||
#region License
|
||||
/*
|
||||
* ReadBufferState.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) 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@novell.com>
|
||||
*/
|
||||
#endregion
|
||||
|
||||
using System;
|
||||
|
||||
namespace WebSocketSharp.Net
|
||||
{
|
||||
internal class ReadBufferState
|
||||
{
|
||||
#region Private Fields
|
||||
|
||||
private HttpStreamAsyncResult _asyncResult;
|
||||
private byte[] _buffer;
|
||||
private int _count;
|
||||
private int _initialCount;
|
||||
private int _offset;
|
||||
|
||||
#endregion
|
||||
|
||||
#region Public Constructors
|
||||
|
||||
public ReadBufferState (
|
||||
byte[] buffer, int offset, int count, HttpStreamAsyncResult asyncResult
|
||||
)
|
||||
{
|
||||
_buffer = buffer;
|
||||
_offset = offset;
|
||||
_count = count;
|
||||
_asyncResult = asyncResult;
|
||||
|
||||
_initialCount = count;
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
#region Public Properties
|
||||
|
||||
public HttpStreamAsyncResult AsyncResult {
|
||||
get {
|
||||
return _asyncResult;
|
||||
}
|
||||
|
||||
set {
|
||||
_asyncResult = value;
|
||||
}
|
||||
}
|
||||
|
||||
public byte[] Buffer {
|
||||
get {
|
||||
return _buffer;
|
||||
}
|
||||
|
||||
set {
|
||||
_buffer = value;
|
||||
}
|
||||
}
|
||||
|
||||
public int Count {
|
||||
get {
|
||||
return _count;
|
||||
}
|
||||
|
||||
set {
|
||||
_count = value;
|
||||
}
|
||||
}
|
||||
|
||||
public int InitialCount {
|
||||
get {
|
||||
return _initialCount;
|
||||
}
|
||||
|
||||
set {
|
||||
_initialCount = value;
|
||||
}
|
||||
}
|
||||
|
||||
public int Offset {
|
||||
get {
|
||||
return _offset;
|
||||
}
|
||||
|
||||
set {
|
||||
_offset = value;
|
||||
}
|
||||
}
|
||||
|
||||
#endregion
|
||||
}
|
||||
}
|
318
websocket-sharp/Net/RequestStream.cs
Normal file
318
websocket-sharp/Net/RequestStream.cs
Normal file
@@ -0,0 +1,318 @@
|
||||
#region License
|
||||
/*
|
||||
* RequestStream.cs
|
||||
*
|
||||
* This code is derived from RequestStream.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.IO;
|
||||
|
||||
namespace WebSocketSharp.Net
|
||||
{
|
||||
internal class RequestStream : Stream
|
||||
{
|
||||
#region Private Fields
|
||||
|
||||
private long _bodyLeft;
|
||||
private byte[] _buffer;
|
||||
private int _count;
|
||||
private bool _disposed;
|
||||
private int _offset;
|
||||
private Stream _stream;
|
||||
|
||||
#endregion
|
||||
|
||||
#region Internal Constructors
|
||||
|
||||
internal RequestStream (
|
||||
Stream stream, byte[] buffer, int offset, int count, long contentLength
|
||||
)
|
||||
{
|
||||
_stream = stream;
|
||||
_buffer = buffer;
|
||||
_offset = offset;
|
||||
_count = count;
|
||||
_bodyLeft = contentLength;
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
#region Public Properties
|
||||
|
||||
public override bool CanRead {
|
||||
get {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
public override bool CanSeek {
|
||||
get {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
public override bool CanWrite {
|
||||
get {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
public override long Length {
|
||||
get {
|
||||
throw new NotSupportedException ();
|
||||
}
|
||||
}
|
||||
|
||||
public override long Position {
|
||||
get {
|
||||
throw new NotSupportedException ();
|
||||
}
|
||||
|
||||
set {
|
||||
throw new NotSupportedException ();
|
||||
}
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
#region Private Methods
|
||||
|
||||
private int fillFromBuffer (byte[] buffer, int offset, int count)
|
||||
{
|
||||
// This method returns a int:
|
||||
// - > 0 The number of bytes read from the internal buffer
|
||||
// - 0 No more bytes read from the internal buffer
|
||||
// - -1 No more content data
|
||||
|
||||
if (_bodyLeft == 0)
|
||||
return -1;
|
||||
|
||||
if (_count == 0)
|
||||
return 0;
|
||||
|
||||
if (count > _count)
|
||||
count = _count;
|
||||
|
||||
if (_bodyLeft > 0 && _bodyLeft < count)
|
||||
count = (int) _bodyLeft;
|
||||
|
||||
Buffer.BlockCopy (_buffer, _offset, buffer, offset, count);
|
||||
|
||||
_offset += count;
|
||||
_count -= count;
|
||||
|
||||
if (_bodyLeft > 0)
|
||||
_bodyLeft -= count;
|
||||
|
||||
return count;
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
#region Public Methods
|
||||
|
||||
public override IAsyncResult BeginRead (
|
||||
byte[] buffer, int offset, int count, AsyncCallback callback, object state
|
||||
)
|
||||
{
|
||||
if (_disposed) {
|
||||
var name = GetType ().ToString ();
|
||||
|
||||
throw new ObjectDisposedException (name);
|
||||
}
|
||||
|
||||
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);
|
||||
}
|
||||
|
||||
if (count == 0)
|
||||
return _stream.BeginRead (buffer, offset, 0, callback, state);
|
||||
|
||||
var nread = fillFromBuffer (buffer, offset, count);
|
||||
|
||||
if (nread != 0) {
|
||||
var ares = new HttpStreamAsyncResult (callback, state);
|
||||
ares.Buffer = buffer;
|
||||
ares.Offset = offset;
|
||||
ares.Count = count;
|
||||
ares.SyncRead = nread > 0 ? nread : 0;
|
||||
ares.Complete ();
|
||||
|
||||
return ares;
|
||||
}
|
||||
|
||||
if (_bodyLeft >= 0 && _bodyLeft < count)
|
||||
count = (int) _bodyLeft;
|
||||
|
||||
return _stream.BeginRead (buffer, offset, count, callback, state);
|
||||
}
|
||||
|
||||
public override IAsyncResult BeginWrite (
|
||||
byte[] buffer, int offset, int count, AsyncCallback callback, object state
|
||||
)
|
||||
{
|
||||
throw new NotSupportedException ();
|
||||
}
|
||||
|
||||
public override void Close ()
|
||||
{
|
||||
_disposed = true;
|
||||
}
|
||||
|
||||
public override int EndRead (IAsyncResult asyncResult)
|
||||
{
|
||||
if (_disposed) {
|
||||
var name = GetType ().ToString ();
|
||||
|
||||
throw new ObjectDisposedException (name);
|
||||
}
|
||||
|
||||
if (asyncResult == null)
|
||||
throw new ArgumentNullException ("asyncResult");
|
||||
|
||||
if (asyncResult is HttpStreamAsyncResult) {
|
||||
var ares = (HttpStreamAsyncResult) asyncResult;
|
||||
|
||||
if (!ares.IsCompleted)
|
||||
ares.AsyncWaitHandle.WaitOne ();
|
||||
|
||||
return ares.SyncRead;
|
||||
}
|
||||
|
||||
var nread = _stream.EndRead (asyncResult);
|
||||
|
||||
if (nread > 0 && _bodyLeft > 0)
|
||||
_bodyLeft -= nread;
|
||||
|
||||
return nread;
|
||||
}
|
||||
|
||||
public override void EndWrite (IAsyncResult asyncResult)
|
||||
{
|
||||
throw new NotSupportedException ();
|
||||
}
|
||||
|
||||
public override void Flush ()
|
||||
{
|
||||
}
|
||||
|
||||
public override int Read (byte[] buffer, int offset, int count)
|
||||
{
|
||||
if (_disposed) {
|
||||
var name = GetType ().ToString ();
|
||||
|
||||
throw new ObjectDisposedException (name);
|
||||
}
|
||||
|
||||
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);
|
||||
}
|
||||
|
||||
if (count == 0)
|
||||
return 0;
|
||||
|
||||
var nread = fillFromBuffer (buffer, offset, count);
|
||||
|
||||
if (nread == -1)
|
||||
return 0;
|
||||
|
||||
if (nread > 0)
|
||||
return nread;
|
||||
|
||||
nread = _stream.Read (buffer, offset, count);
|
||||
|
||||
if (nread > 0 && _bodyLeft > 0)
|
||||
_bodyLeft -= nread;
|
||||
|
||||
return nread;
|
||||
}
|
||||
|
||||
public override long Seek (long offset, SeekOrigin origin)
|
||||
{
|
||||
throw new NotSupportedException ();
|
||||
}
|
||||
|
||||
public override void SetLength (long value)
|
||||
{
|
||||
throw new NotSupportedException ();
|
||||
}
|
||||
|
||||
public override void Write (byte[] buffer, int offset, int count)
|
||||
{
|
||||
throw new NotSupportedException ();
|
||||
}
|
||||
|
||||
#endregion
|
||||
}
|
||||
}
|
403
websocket-sharp/Net/ResponseStream.cs
Normal file
403
websocket-sharp/Net/ResponseStream.cs
Normal file
@@ -0,0 +1,403 @@
|
||||
#region License
|
||||
/*
|
||||
* ResponseStream.cs
|
||||
*
|
||||
* This code is derived from ResponseStream.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@novell.com>
|
||||
*/
|
||||
#endregion
|
||||
|
||||
using System;
|
||||
using System.IO;
|
||||
using System.Text;
|
||||
|
||||
namespace WebSocketSharp.Net
|
||||
{
|
||||
internal class ResponseStream : Stream
|
||||
{
|
||||
#region Private Fields
|
||||
|
||||
private MemoryStream _bodyBuffer;
|
||||
private static readonly byte[] _crlf;
|
||||
private bool _disposed;
|
||||
private Stream _innerStream;
|
||||
private static readonly byte[] _lastChunk;
|
||||
private static readonly int _maxHeadersLength;
|
||||
private HttpListenerResponse _response;
|
||||
private bool _sendChunked;
|
||||
private Action<byte[], int, int> _write;
|
||||
private Action<byte[], int, int> _writeBody;
|
||||
private Action<byte[], int, int> _writeChunked;
|
||||
|
||||
#endregion
|
||||
|
||||
#region Static Constructor
|
||||
|
||||
static ResponseStream ()
|
||||
{
|
||||
_crlf = new byte[] { 13, 10 }; // "\r\n"
|
||||
_lastChunk = new byte[] { 48, 13, 10, 13, 10 }; // "0\r\n\r\n"
|
||||
_maxHeadersLength = 32768;
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
#region Internal Constructors
|
||||
|
||||
internal ResponseStream (
|
||||
Stream innerStream,
|
||||
HttpListenerResponse response,
|
||||
bool ignoreWriteExceptions
|
||||
)
|
||||
{
|
||||
_innerStream = innerStream;
|
||||
_response = response;
|
||||
|
||||
if (ignoreWriteExceptions) {
|
||||
_write = writeWithoutThrowingException;
|
||||
_writeChunked = writeChunkedWithoutThrowingException;
|
||||
}
|
||||
else {
|
||||
_write = innerStream.Write;
|
||||
_writeChunked = writeChunked;
|
||||
}
|
||||
|
||||
_bodyBuffer = new MemoryStream ();
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
#region Public Properties
|
||||
|
||||
public override bool CanRead {
|
||||
get {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
public override bool CanSeek {
|
||||
get {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
public override bool CanWrite {
|
||||
get {
|
||||
return !_disposed;
|
||||
}
|
||||
}
|
||||
|
||||
public override long Length {
|
||||
get {
|
||||
throw new NotSupportedException ();
|
||||
}
|
||||
}
|
||||
|
||||
public override long Position {
|
||||
get {
|
||||
throw new NotSupportedException ();
|
||||
}
|
||||
|
||||
set {
|
||||
throw new NotSupportedException ();
|
||||
}
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
#region Private Methods
|
||||
|
||||
private bool flush (bool closing)
|
||||
{
|
||||
if (!_response.HeadersSent) {
|
||||
if (!flushHeaders ())
|
||||
return false;
|
||||
|
||||
_response.HeadersSent = true;
|
||||
|
||||
_sendChunked = _response.SendChunked;
|
||||
_writeBody = _sendChunked ? _writeChunked : _write;
|
||||
}
|
||||
|
||||
flushBody (closing);
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
private void flushBody (bool closing)
|
||||
{
|
||||
using (_bodyBuffer) {
|
||||
var len = _bodyBuffer.Length;
|
||||
|
||||
if (len > Int32.MaxValue) {
|
||||
_bodyBuffer.Position = 0;
|
||||
|
||||
var buffLen = 1024;
|
||||
var buff = new byte[buffLen];
|
||||
var nread = 0;
|
||||
|
||||
while (true) {
|
||||
nread = _bodyBuffer.Read (buff, 0, buffLen);
|
||||
|
||||
if (nread <= 0)
|
||||
break;
|
||||
|
||||
_writeBody (buff, 0, nread);
|
||||
}
|
||||
}
|
||||
else if (len > 0) {
|
||||
_writeBody (_bodyBuffer.GetBuffer (), 0, (int) len);
|
||||
}
|
||||
}
|
||||
|
||||
if (!closing) {
|
||||
_bodyBuffer = new MemoryStream ();
|
||||
return;
|
||||
}
|
||||
|
||||
if (_sendChunked)
|
||||
_write (_lastChunk, 0, 5);
|
||||
|
||||
_bodyBuffer = null;
|
||||
}
|
||||
|
||||
private bool flushHeaders ()
|
||||
{
|
||||
if (!_response.SendChunked) {
|
||||
if (_response.ContentLength64 != _bodyBuffer.Length)
|
||||
return false;
|
||||
}
|
||||
|
||||
var statusLine = _response.StatusLine;
|
||||
var headers = _response.FullHeaders;
|
||||
|
||||
var buff = new MemoryStream ();
|
||||
var enc = Encoding.UTF8;
|
||||
|
||||
using (var writer = new StreamWriter (buff, enc, 256)) {
|
||||
writer.Write (statusLine);
|
||||
writer.Write (headers.ToStringMultiValue (true));
|
||||
writer.Flush ();
|
||||
|
||||
var start = enc.GetPreamble ().Length;
|
||||
var len = buff.Length - start;
|
||||
|
||||
if (len > _maxHeadersLength)
|
||||
return false;
|
||||
|
||||
_write (buff.GetBuffer (), start, (int) len);
|
||||
}
|
||||
|
||||
_response.CloseConnection = headers["Connection"] == "close";
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
private static byte[] getChunkSizeBytes (int size)
|
||||
{
|
||||
var chunkSize = String.Format ("{0:x}\r\n", size);
|
||||
|
||||
return Encoding.ASCII.GetBytes (chunkSize);
|
||||
}
|
||||
|
||||
private void writeChunked (byte[] buffer, int offset, int count)
|
||||
{
|
||||
var size = getChunkSizeBytes (count);
|
||||
|
||||
_innerStream.Write (size, 0, size.Length);
|
||||
_innerStream.Write (buffer, offset, count);
|
||||
_innerStream.Write (_crlf, 0, 2);
|
||||
}
|
||||
|
||||
private void writeChunkedWithoutThrowingException (
|
||||
byte[] buffer, int offset, int count
|
||||
)
|
||||
{
|
||||
try {
|
||||
writeChunked (buffer, offset, count);
|
||||
}
|
||||
catch {
|
||||
}
|
||||
}
|
||||
|
||||
private void writeWithoutThrowingException (
|
||||
byte[] buffer, int offset, int count
|
||||
)
|
||||
{
|
||||
try {
|
||||
_innerStream.Write (buffer, offset, count);
|
||||
}
|
||||
catch {
|
||||
}
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
#region Internal Methods
|
||||
|
||||
internal void Close (bool force)
|
||||
{
|
||||
if (_disposed)
|
||||
return;
|
||||
|
||||
_disposed = true;
|
||||
|
||||
if (!force) {
|
||||
if (flush (true)) {
|
||||
_response.Close ();
|
||||
|
||||
_response = null;
|
||||
_innerStream = null;
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
_response.CloseConnection = true;
|
||||
}
|
||||
|
||||
if (_sendChunked)
|
||||
_write (_lastChunk, 0, 5);
|
||||
|
||||
_bodyBuffer.Dispose ();
|
||||
_response.Abort ();
|
||||
|
||||
_bodyBuffer = null;
|
||||
_response = null;
|
||||
_innerStream = null;
|
||||
}
|
||||
|
||||
internal void InternalWrite (byte[] buffer, int offset, int count)
|
||||
{
|
||||
_write (buffer, offset, count);
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
#region Public Methods
|
||||
|
||||
public override IAsyncResult BeginRead (
|
||||
byte[] buffer,
|
||||
int offset,
|
||||
int count,
|
||||
AsyncCallback callback,
|
||||
object state
|
||||
)
|
||||
{
|
||||
throw new NotSupportedException ();
|
||||
}
|
||||
|
||||
public override IAsyncResult BeginWrite (
|
||||
byte[] buffer,
|
||||
int offset,
|
||||
int count,
|
||||
AsyncCallback callback,
|
||||
object state
|
||||
)
|
||||
{
|
||||
if (_disposed) {
|
||||
var name = GetType ().ToString ();
|
||||
|
||||
throw new ObjectDisposedException (name);
|
||||
}
|
||||
|
||||
return _bodyBuffer.BeginWrite (buffer, offset, count, callback, state);
|
||||
}
|
||||
|
||||
public override void Close ()
|
||||
{
|
||||
Close (false);
|
||||
}
|
||||
|
||||
protected override void Dispose (bool disposing)
|
||||
{
|
||||
Close (!disposing);
|
||||
}
|
||||
|
||||
public override int EndRead (IAsyncResult asyncResult)
|
||||
{
|
||||
throw new NotSupportedException ();
|
||||
}
|
||||
|
||||
public override void EndWrite (IAsyncResult asyncResult)
|
||||
{
|
||||
if (_disposed) {
|
||||
var name = GetType ().ToString ();
|
||||
|
||||
throw new ObjectDisposedException (name);
|
||||
}
|
||||
|
||||
_bodyBuffer.EndWrite (asyncResult);
|
||||
}
|
||||
|
||||
public override void Flush ()
|
||||
{
|
||||
if (_disposed)
|
||||
return;
|
||||
|
||||
var sendChunked = _sendChunked || _response.SendChunked;
|
||||
|
||||
if (!sendChunked)
|
||||
return;
|
||||
|
||||
flush (false);
|
||||
}
|
||||
|
||||
public override int Read (byte[] buffer, int offset, int count)
|
||||
{
|
||||
throw new NotSupportedException ();
|
||||
}
|
||||
|
||||
public override long Seek (long offset, SeekOrigin origin)
|
||||
{
|
||||
throw new NotSupportedException ();
|
||||
}
|
||||
|
||||
public override void SetLength (long value)
|
||||
{
|
||||
throw new NotSupportedException ();
|
||||
}
|
||||
|
||||
public override void Write (byte[] buffer, int offset, int count)
|
||||
{
|
||||
if (_disposed) {
|
||||
var name = GetType ().ToString ();
|
||||
|
||||
throw new ObjectDisposedException (name);
|
||||
}
|
||||
|
||||
_bodyBuffer.Write (buffer, offset, count);
|
||||
}
|
||||
|
||||
#endregion
|
||||
}
|
||||
}
|
236
websocket-sharp/Net/ServerSslConfiguration.cs
Normal file
236
websocket-sharp/Net/ServerSslConfiguration.cs
Normal file
@@ -0,0 +1,236 @@
|
||||
#region License
|
||||
/*
|
||||
* ServerSslConfiguration.cs
|
||||
*
|
||||
* The MIT License
|
||||
*
|
||||
* Copyright (c) 2014 liryna
|
||||
* 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:
|
||||
* - 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 the <see cref="SslStream"/> used by servers.
|
||||
/// </summary>
|
||||
public class ServerSslConfiguration
|
||||
{
|
||||
#region Private Fields
|
||||
|
||||
private bool _checkCertRevocation;
|
||||
private bool _clientCertRequired;
|
||||
private RemoteCertificateValidationCallback _clientCertValidationCallback;
|
||||
private SslProtocols _enabledSslProtocols;
|
||||
private X509Certificate2 _serverCert;
|
||||
|
||||
#endregion
|
||||
|
||||
#region Public Constructors
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="ServerSslConfiguration"/>
|
||||
/// class.
|
||||
/// </summary>
|
||||
public ServerSslConfiguration ()
|
||||
{
|
||||
_enabledSslProtocols = SslProtocols.None;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="ServerSslConfiguration"/>
|
||||
/// class that stores the parameters copied from the specified configuration.
|
||||
/// </summary>
|
||||
/// <param name="configuration">
|
||||
/// A <see cref="ServerSslConfiguration"/> from which to copy.
|
||||
/// </param>
|
||||
/// <exception cref="ArgumentNullException">
|
||||
/// <paramref name="configuration"/> is <see langword="null"/>.
|
||||
/// </exception>
|
||||
public ServerSslConfiguration (ServerSslConfiguration configuration)
|
||||
{
|
||||
if (configuration == null)
|
||||
throw new ArgumentNullException ("configuration");
|
||||
|
||||
_checkCertRevocation = configuration._checkCertRevocation;
|
||||
_clientCertRequired = configuration._clientCertRequired;
|
||||
_clientCertValidationCallback = configuration._clientCertValidationCallback;
|
||||
_enabledSslProtocols = configuration._enabledSslProtocols;
|
||||
_serverCert = configuration._serverCert;
|
||||
}
|
||||
|
||||
#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 a value indicating whether the client is asked for
|
||||
/// a certificate for authentication.
|
||||
/// </summary>
|
||||
/// <value>
|
||||
/// <para>
|
||||
/// <c>true</c> if the client is asked for a certificate for
|
||||
/// authentication; otherwise, <c>false</c>.
|
||||
/// </para>
|
||||
/// <para>
|
||||
/// The default value is <c>false</c>.
|
||||
/// </para>
|
||||
/// </value>
|
||||
public bool ClientCertificateRequired {
|
||||
get {
|
||||
return _clientCertRequired;
|
||||
}
|
||||
|
||||
set {
|
||||
_clientCertRequired = value;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the callback used to validate the certificate supplied by
|
||||
/// the client.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// The certificate is valid if the callback returns <c>true</c>.
|
||||
/// </remarks>
|
||||
/// <value>
|
||||
/// <para>
|
||||
/// A <see cref="RemoteCertificateValidationCallback"/> delegate that
|
||||
/// invokes the method called for validating the certificate.
|
||||
/// </para>
|
||||
/// <para>
|
||||
/// The default value is a delegate that invokes a method that only
|
||||
/// returns <c>true</c>.
|
||||
/// </para>
|
||||
/// </value>
|
||||
public RemoteCertificateValidationCallback ClientCertificateValidationCallback {
|
||||
get {
|
||||
if (_clientCertValidationCallback == null)
|
||||
_clientCertValidationCallback = defaultValidateClientCertificate;
|
||||
|
||||
return _clientCertValidationCallback;
|
||||
}
|
||||
|
||||
set {
|
||||
_clientCertValidationCallback = value;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the protocols used for authentication.
|
||||
/// </summary>
|
||||
/// <value>
|
||||
/// <para>
|
||||
/// Any of the <see cref="SslProtocols"/> enum values.
|
||||
/// </para>
|
||||
/// <para>
|
||||
/// It represents the protocols used for authentication.
|
||||
/// </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 certificate used to authenticate the server.
|
||||
/// </summary>
|
||||
/// <value>
|
||||
/// <para>
|
||||
/// A <see cref="X509Certificate2"/> or <see langword="null"/>.
|
||||
/// </para>
|
||||
/// <para>
|
||||
/// The certificate represents an X.509 certificate.
|
||||
/// </para>
|
||||
/// <para>
|
||||
/// The default value is <see langword="null"/>.
|
||||
/// </para>
|
||||
/// </value>
|
||||
public X509Certificate2 ServerCertificate {
|
||||
get {
|
||||
return _serverCert;
|
||||
}
|
||||
|
||||
set {
|
||||
_serverCert = value;
|
||||
}
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
#region Private Methods
|
||||
|
||||
private static bool defaultValidateClientCertificate (
|
||||
object sender,
|
||||
X509Certificate certificate,
|
||||
X509Chain chain,
|
||||
SslPolicyErrors sslPolicyErrors
|
||||
)
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
#endregion
|
||||
}
|
||||
}
|
1889
websocket-sharp/Net/WebHeaderCollection.cs
Normal file
1889
websocket-sharp/Net/WebHeaderCollection.cs
Normal file
File diff suppressed because it is too large
Load Diff
395
websocket-sharp/Net/WebSockets/HttpListenerWebSocketContext.cs
Normal file
395
websocket-sharp/Net/WebSockets/HttpListenerWebSocketContext.cs
Normal file
@@ -0,0 +1,395 @@
|
||||
#region License
|
||||
/*
|
||||
* HttpListenerWebSocketContext.cs
|
||||
*
|
||||
* The MIT License
|
||||
*
|
||||
* Copyright (c) 2012-2018 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.Security.Principal;
|
||||
|
||||
namespace WebSocketSharp.Net.WebSockets
|
||||
{
|
||||
/// <summary>
|
||||
/// Provides the access to the information in a WebSocket handshake request to
|
||||
/// a <see cref="HttpListener"/> instance.
|
||||
/// </summary>
|
||||
public class HttpListenerWebSocketContext : WebSocketContext
|
||||
{
|
||||
#region Private Fields
|
||||
|
||||
private HttpListenerContext _context;
|
||||
private WebSocket _websocket;
|
||||
|
||||
#endregion
|
||||
|
||||
#region Internal Constructors
|
||||
|
||||
internal HttpListenerWebSocketContext (
|
||||
HttpListenerContext context, string protocol
|
||||
)
|
||||
{
|
||||
_context = context;
|
||||
_websocket = new WebSocket (this, protocol);
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
#region Internal Properties
|
||||
|
||||
internal Logger Log {
|
||||
get {
|
||||
return _context.Listener.Log;
|
||||
}
|
||||
}
|
||||
|
||||
internal Stream Stream {
|
||||
get {
|
||||
return _context.Connection.Stream;
|
||||
}
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
#region Public Properties
|
||||
|
||||
/// <summary>
|
||||
/// Gets the HTTP cookies included in the handshake request.
|
||||
/// </summary>
|
||||
/// <value>
|
||||
/// <para>
|
||||
/// A <see cref="WebSocketSharp.Net.CookieCollection"/> that contains
|
||||
/// the cookies.
|
||||
/// </para>
|
||||
/// <para>
|
||||
/// An empty collection if not included.
|
||||
/// </para>
|
||||
/// </value>
|
||||
public override CookieCollection CookieCollection {
|
||||
get {
|
||||
return _context.Request.Cookies;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the HTTP headers included in the handshake request.
|
||||
/// </summary>
|
||||
/// <value>
|
||||
/// A <see cref="NameValueCollection"/> that contains the headers.
|
||||
/// </value>
|
||||
public override NameValueCollection Headers {
|
||||
get {
|
||||
return _context.Request.Headers;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the value of the Host header included in the handshake request.
|
||||
/// </summary>
|
||||
/// <value>
|
||||
/// <para>
|
||||
/// A <see cref="string"/> that represents the server host name requested
|
||||
/// by the client.
|
||||
/// </para>
|
||||
/// <para>
|
||||
/// It includes the port number if provided.
|
||||
/// </para>
|
||||
/// </value>
|
||||
public override string Host {
|
||||
get {
|
||||
return _context.Request.UserHostName;
|
||||
}
|
||||
}
|
||||
|
||||
/// <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 override bool IsAuthenticated {
|
||||
get {
|
||||
return _context.Request.IsAuthenticated;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets a value indicating whether the handshake request is sent from
|
||||
/// the local computer.
|
||||
/// </summary>
|
||||
/// <value>
|
||||
/// <c>true</c> if the handshake request is sent from the same computer
|
||||
/// as the server; otherwise, <c>false</c>.
|
||||
/// </value>
|
||||
public override bool IsLocal {
|
||||
get {
|
||||
return _context.Request.IsLocal;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets a value indicating whether a secure connection is used to send
|
||||
/// the handshake request.
|
||||
/// </summary>
|
||||
/// <value>
|
||||
/// <c>true</c> if the connection is secure; otherwise, <c>false</c>.
|
||||
/// </value>
|
||||
public override bool IsSecureConnection {
|
||||
get {
|
||||
return _context.Request.IsSecureConnection;
|
||||
}
|
||||
}
|
||||
|
||||
/// <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 override bool IsWebSocketRequest {
|
||||
get {
|
||||
return _context.Request.IsWebSocketRequest;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the value of the Origin header included in the handshake request.
|
||||
/// </summary>
|
||||
/// <value>
|
||||
/// <para>
|
||||
/// A <see cref="string"/> that represents the value of the Origin header.
|
||||
/// </para>
|
||||
/// <para>
|
||||
/// <see langword="null"/> if the header is not present.
|
||||
/// </para>
|
||||
/// </value>
|
||||
public override string Origin {
|
||||
get {
|
||||
return _context.Request.Headers["Origin"];
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the query string included in the handshake request.
|
||||
/// </summary>
|
||||
/// <value>
|
||||
/// <para>
|
||||
/// A <see cref="NameValueCollection"/> that contains the query
|
||||
/// parameters.
|
||||
/// </para>
|
||||
/// <para>
|
||||
/// An empty collection if not included.
|
||||
/// </para>
|
||||
/// </value>
|
||||
public override NameValueCollection QueryString {
|
||||
get {
|
||||
return _context.Request.QueryString;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the URI requested by the client.
|
||||
/// </summary>
|
||||
/// <value>
|
||||
/// <para>
|
||||
/// A <see cref="Uri"/> that represents the URI parsed from the request.
|
||||
/// </para>
|
||||
/// <para>
|
||||
/// <see langword="null"/> if the URI cannot be parsed.
|
||||
/// </para>
|
||||
/// </value>
|
||||
public override Uri RequestUri {
|
||||
get {
|
||||
return _context.Request.Url;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the value of the Sec-WebSocket-Key header included in
|
||||
/// the handshake request.
|
||||
/// </summary>
|
||||
/// <value>
|
||||
/// <para>
|
||||
/// A <see cref="string"/> that represents the value of
|
||||
/// the Sec-WebSocket-Key header.
|
||||
/// </para>
|
||||
/// <para>
|
||||
/// The value is used to prove that the server received
|
||||
/// a valid WebSocket handshake request.
|
||||
/// </para>
|
||||
/// <para>
|
||||
/// <see langword="null"/> if the header is not present.
|
||||
/// </para>
|
||||
/// </value>
|
||||
public override string SecWebSocketKey {
|
||||
get {
|
||||
return _context.Request.Headers["Sec-WebSocket-Key"];
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the names of the subprotocols from the Sec-WebSocket-Protocol
|
||||
/// header included in the handshake request.
|
||||
/// </summary>
|
||||
/// <value>
|
||||
/// <para>
|
||||
/// An <see cref="T:System.Collections.Generic.IEnumerable{string}"/>
|
||||
/// instance.
|
||||
/// </para>
|
||||
/// <para>
|
||||
/// It provides an enumerator which supports the iteration over
|
||||
/// the collection of the names of the subprotocols.
|
||||
/// </para>
|
||||
/// </value>
|
||||
public override IEnumerable<string> SecWebSocketProtocols {
|
||||
get {
|
||||
var val = _context.Request.Headers["Sec-WebSocket-Protocol"];
|
||||
if (val == null || val.Length == 0)
|
||||
yield break;
|
||||
|
||||
foreach (var elm in val.Split (',')) {
|
||||
var protocol = elm.Trim ();
|
||||
if (protocol.Length == 0)
|
||||
continue;
|
||||
|
||||
yield return protocol;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the value of the Sec-WebSocket-Version header included in
|
||||
/// the handshake request.
|
||||
/// </summary>
|
||||
/// <value>
|
||||
/// <para>
|
||||
/// A <see cref="string"/> that represents the WebSocket protocol
|
||||
/// version specified by the client.
|
||||
/// </para>
|
||||
/// <para>
|
||||
/// <see langword="null"/> if the header is not present.
|
||||
/// </para>
|
||||
/// </value>
|
||||
public override string SecWebSocketVersion {
|
||||
get {
|
||||
return _context.Request.Headers["Sec-WebSocket-Version"];
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the endpoint to which the handshake request is sent.
|
||||
/// </summary>
|
||||
/// <value>
|
||||
/// A <see cref="System.Net.IPEndPoint"/> that represents the server IP
|
||||
/// address and port number.
|
||||
/// </value>
|
||||
public override System.Net.IPEndPoint ServerEndPoint {
|
||||
get {
|
||||
return _context.Request.LocalEndPoint;
|
||||
}
|
||||
}
|
||||
|
||||
/// <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 override IPrincipal User {
|
||||
get {
|
||||
return _context.User;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the endpoint from which the handshake request is sent.
|
||||
/// </summary>
|
||||
/// <value>
|
||||
/// A <see cref="System.Net.IPEndPoint"/> that represents the client IP
|
||||
/// address and port number.
|
||||
/// </value>
|
||||
public override System.Net.IPEndPoint UserEndPoint {
|
||||
get {
|
||||
return _context.Request.RemoteEndPoint;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the WebSocket instance used for two-way communication between
|
||||
/// the client and server.
|
||||
/// </summary>
|
||||
/// <value>
|
||||
/// A <see cref="WebSocketSharp.WebSocket"/>.
|
||||
/// </value>
|
||||
public override WebSocket WebSocket {
|
||||
get {
|
||||
return _websocket;
|
||||
}
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
#region Internal Methods
|
||||
|
||||
internal void Close ()
|
||||
{
|
||||
_context.Connection.Close (true);
|
||||
}
|
||||
|
||||
internal void Close (HttpStatusCode code)
|
||||
{
|
||||
_context.Response.StatusCode = (int) code;
|
||||
_context.Response.Close ();
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
#region Public Methods
|
||||
|
||||
/// <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 handshake request.
|
||||
/// </returns>
|
||||
public override string ToString ()
|
||||
{
|
||||
return _context.Request.ToString ();
|
||||
}
|
||||
|
||||
#endregion
|
||||
}
|
||||
}
|
518
websocket-sharp/Net/WebSockets/TcpListenerWebSocketContext.cs
Normal file
518
websocket-sharp/Net/WebSockets/TcpListenerWebSocketContext.cs
Normal file
@@ -0,0 +1,518 @@
|
||||
#region License
|
||||
/*
|
||||
* TcpListenerWebSocketContext.cs
|
||||
*
|
||||
* The MIT License
|
||||
*
|
||||
* Copyright (c) 2012-2018 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:
|
||||
* - Liryna <liryna.stark@gmail.com>
|
||||
*/
|
||||
#endregion
|
||||
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Collections.Specialized;
|
||||
using System.IO;
|
||||
using System.Net.Security;
|
||||
using System.Net.Sockets;
|
||||
using System.Security.Principal;
|
||||
using System.Text;
|
||||
|
||||
namespace WebSocketSharp.Net.WebSockets
|
||||
{
|
||||
/// <summary>
|
||||
/// Provides the access to the information in a WebSocket handshake request to
|
||||
/// a <see cref="TcpListener"/> instance.
|
||||
/// </summary>
|
||||
internal class TcpListenerWebSocketContext : WebSocketContext
|
||||
{
|
||||
#region Private Fields
|
||||
|
||||
private Logger _log;
|
||||
private NameValueCollection _queryString;
|
||||
private HttpRequest _request;
|
||||
private Uri _requestUri;
|
||||
private bool _secure;
|
||||
private System.Net.EndPoint _serverEndPoint;
|
||||
private Stream _stream;
|
||||
private TcpClient _tcpClient;
|
||||
private IPrincipal _user;
|
||||
private System.Net.EndPoint _userEndPoint;
|
||||
private WebSocket _websocket;
|
||||
|
||||
#endregion
|
||||
|
||||
#region Internal Constructors
|
||||
|
||||
internal TcpListenerWebSocketContext (
|
||||
TcpClient tcpClient,
|
||||
string protocol,
|
||||
bool secure,
|
||||
ServerSslConfiguration sslConfig,
|
||||
Logger log
|
||||
)
|
||||
{
|
||||
_tcpClient = tcpClient;
|
||||
_secure = secure;
|
||||
_log = log;
|
||||
|
||||
var netStream = tcpClient.GetStream ();
|
||||
if (secure) {
|
||||
var sslStream = new SslStream (
|
||||
netStream,
|
||||
false,
|
||||
sslConfig.ClientCertificateValidationCallback
|
||||
);
|
||||
|
||||
sslStream.AuthenticateAsServer (
|
||||
sslConfig.ServerCertificate,
|
||||
sslConfig.ClientCertificateRequired,
|
||||
sslConfig.EnabledSslProtocols,
|
||||
sslConfig.CheckCertificateRevocation
|
||||
);
|
||||
|
||||
_stream = sslStream;
|
||||
}
|
||||
else {
|
||||
_stream = netStream;
|
||||
}
|
||||
|
||||
var sock = tcpClient.Client;
|
||||
_serverEndPoint = sock.LocalEndPoint;
|
||||
_userEndPoint = sock.RemoteEndPoint;
|
||||
|
||||
_request = HttpRequest.Read (_stream, 90000);
|
||||
_websocket = new WebSocket (this, protocol);
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
#region Internal Properties
|
||||
|
||||
internal Logger Log {
|
||||
get {
|
||||
return _log;
|
||||
}
|
||||
}
|
||||
|
||||
internal Stream Stream {
|
||||
get {
|
||||
return _stream;
|
||||
}
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
#region Public Properties
|
||||
|
||||
/// <summary>
|
||||
/// Gets the HTTP cookies included in the handshake request.
|
||||
/// </summary>
|
||||
/// <value>
|
||||
/// <para>
|
||||
/// A <see cref="WebSocketSharp.Net.CookieCollection"/> that contains
|
||||
/// the cookies.
|
||||
/// </para>
|
||||
/// <para>
|
||||
/// An empty collection if not included.
|
||||
/// </para>
|
||||
/// </value>
|
||||
public override CookieCollection CookieCollection {
|
||||
get {
|
||||
return _request.Cookies;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the HTTP headers included in the handshake request.
|
||||
/// </summary>
|
||||
/// <value>
|
||||
/// A <see cref="NameValueCollection"/> that contains the headers.
|
||||
/// </value>
|
||||
public override NameValueCollection Headers {
|
||||
get {
|
||||
return _request.Headers;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the value of the Host header included in the handshake request.
|
||||
/// </summary>
|
||||
/// <value>
|
||||
/// <para>
|
||||
/// A <see cref="string"/> that represents the server host name requested
|
||||
/// by the client.
|
||||
/// </para>
|
||||
/// <para>
|
||||
/// It includes the port number if provided.
|
||||
/// </para>
|
||||
/// </value>
|
||||
public override string Host {
|
||||
get {
|
||||
return _request.Headers["Host"];
|
||||
}
|
||||
}
|
||||
|
||||
/// <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 override bool IsAuthenticated {
|
||||
get {
|
||||
return _user != null;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets a value indicating whether the handshake request is sent from
|
||||
/// the local computer.
|
||||
/// </summary>
|
||||
/// <value>
|
||||
/// <c>true</c> if the handshake request is sent from the same computer
|
||||
/// as the server; otherwise, <c>false</c>.
|
||||
/// </value>
|
||||
public override bool IsLocal {
|
||||
get {
|
||||
return UserEndPoint.Address.IsLocal ();
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets a value indicating whether a secure connection is used to send
|
||||
/// the handshake request.
|
||||
/// </summary>
|
||||
/// <value>
|
||||
/// <c>true</c> if the connection is secure; otherwise, <c>false</c>.
|
||||
/// </value>
|
||||
public override bool IsSecureConnection {
|
||||
get {
|
||||
return _secure;
|
||||
}
|
||||
}
|
||||
|
||||
/// <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 override bool IsWebSocketRequest {
|
||||
get {
|
||||
return _request.IsWebSocketRequest;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the value of the Origin header included in the handshake request.
|
||||
/// </summary>
|
||||
/// <value>
|
||||
/// <para>
|
||||
/// A <see cref="string"/> that represents the value of the Origin header.
|
||||
/// </para>
|
||||
/// <para>
|
||||
/// <see langword="null"/> if the header is not present.
|
||||
/// </para>
|
||||
/// </value>
|
||||
public override string Origin {
|
||||
get {
|
||||
return _request.Headers["Origin"];
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the query string included in the handshake request.
|
||||
/// </summary>
|
||||
/// <value>
|
||||
/// <para>
|
||||
/// A <see cref="NameValueCollection"/> that contains the query
|
||||
/// parameters.
|
||||
/// </para>
|
||||
/// <para>
|
||||
/// An empty collection if not included.
|
||||
/// </para>
|
||||
/// </value>
|
||||
public override NameValueCollection QueryString {
|
||||
get {
|
||||
if (_queryString == null) {
|
||||
var uri = RequestUri;
|
||||
_queryString = QueryStringCollection.Parse (
|
||||
uri != null ? uri.Query : null,
|
||||
Encoding.UTF8
|
||||
);
|
||||
}
|
||||
|
||||
return _queryString;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the URI requested by the client.
|
||||
/// </summary>
|
||||
/// <value>
|
||||
/// <para>
|
||||
/// A <see cref="Uri"/> that represents the URI parsed from the request.
|
||||
/// </para>
|
||||
/// <para>
|
||||
/// <see langword="null"/> if the URI cannot be parsed.
|
||||
/// </para>
|
||||
/// </value>
|
||||
public override Uri RequestUri {
|
||||
get {
|
||||
if (_requestUri == null) {
|
||||
_requestUri = HttpUtility.CreateRequestUrl (
|
||||
_request.RequestUri,
|
||||
_request.Headers["Host"],
|
||||
_request.IsWebSocketRequest,
|
||||
_secure
|
||||
);
|
||||
}
|
||||
|
||||
return _requestUri;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the value of the Sec-WebSocket-Key header included in
|
||||
/// the handshake request.
|
||||
/// </summary>
|
||||
/// <value>
|
||||
/// <para>
|
||||
/// A <see cref="string"/> that represents the value of
|
||||
/// the Sec-WebSocket-Key header.
|
||||
/// </para>
|
||||
/// <para>
|
||||
/// The value is used to prove that the server received
|
||||
/// a valid WebSocket handshake request.
|
||||
/// </para>
|
||||
/// <para>
|
||||
/// <see langword="null"/> if the header is not present.
|
||||
/// </para>
|
||||
/// </value>
|
||||
public override string SecWebSocketKey {
|
||||
get {
|
||||
return _request.Headers["Sec-WebSocket-Key"];
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the names of the subprotocols from the Sec-WebSocket-Protocol
|
||||
/// header included in the handshake request.
|
||||
/// </summary>
|
||||
/// <value>
|
||||
/// <para>
|
||||
/// An <see cref="T:System.Collections.Generic.IEnumerable{string}"/>
|
||||
/// instance.
|
||||
/// </para>
|
||||
/// <para>
|
||||
/// It provides an enumerator which supports the iteration over
|
||||
/// the collection of the names of the subprotocols.
|
||||
/// </para>
|
||||
/// </value>
|
||||
public override IEnumerable<string> SecWebSocketProtocols {
|
||||
get {
|
||||
var val = _request.Headers["Sec-WebSocket-Protocol"];
|
||||
if (val == null || val.Length == 0)
|
||||
yield break;
|
||||
|
||||
foreach (var elm in val.Split (',')) {
|
||||
var protocol = elm.Trim ();
|
||||
if (protocol.Length == 0)
|
||||
continue;
|
||||
|
||||
yield return protocol;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the value of the Sec-WebSocket-Version header included in
|
||||
/// the handshake request.
|
||||
/// </summary>
|
||||
/// <value>
|
||||
/// <para>
|
||||
/// A <see cref="string"/> that represents the WebSocket protocol
|
||||
/// version specified by the client.
|
||||
/// </para>
|
||||
/// <para>
|
||||
/// <see langword="null"/> if the header is not present.
|
||||
/// </para>
|
||||
/// </value>
|
||||
public override string SecWebSocketVersion {
|
||||
get {
|
||||
return _request.Headers["Sec-WebSocket-Version"];
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the endpoint to which the handshake request is sent.
|
||||
/// </summary>
|
||||
/// <value>
|
||||
/// A <see cref="System.Net.IPEndPoint"/> that represents the server IP
|
||||
/// address and port number.
|
||||
/// </value>
|
||||
public override System.Net.IPEndPoint ServerEndPoint {
|
||||
get {
|
||||
return (System.Net.IPEndPoint) _serverEndPoint;
|
||||
}
|
||||
}
|
||||
|
||||
/// <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 override IPrincipal User {
|
||||
get {
|
||||
return _user;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the endpoint from which the handshake request is sent.
|
||||
/// </summary>
|
||||
/// <value>
|
||||
/// A <see cref="System.Net.IPEndPoint"/> that represents the client IP
|
||||
/// address and port number.
|
||||
/// </value>
|
||||
public override System.Net.IPEndPoint UserEndPoint {
|
||||
get {
|
||||
return (System.Net.IPEndPoint) _userEndPoint;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the WebSocket instance used for two-way communication between
|
||||
/// the client and server.
|
||||
/// </summary>
|
||||
/// <value>
|
||||
/// A <see cref="WebSocketSharp.WebSocket"/>.
|
||||
/// </value>
|
||||
public override WebSocket WebSocket {
|
||||
get {
|
||||
return _websocket;
|
||||
}
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
#region Private Methods
|
||||
|
||||
private HttpRequest sendAuthenticationChallenge (string challenge)
|
||||
{
|
||||
var res = HttpResponse.CreateUnauthorizedResponse (challenge);
|
||||
var bytes = res.ToByteArray ();
|
||||
_stream.Write (bytes, 0, bytes.Length);
|
||||
|
||||
return HttpRequest.Read (_stream, 15000);
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
#region Internal Methods
|
||||
|
||||
internal bool Authenticate (
|
||||
AuthenticationSchemes scheme,
|
||||
string realm,
|
||||
Func<IIdentity, NetworkCredential> credentialsFinder
|
||||
)
|
||||
{
|
||||
var chal = new AuthenticationChallenge (scheme, realm).ToString ();
|
||||
|
||||
var retry = -1;
|
||||
Func<bool> auth = null;
|
||||
auth =
|
||||
() => {
|
||||
retry++;
|
||||
if (retry > 99)
|
||||
return false;
|
||||
|
||||
var user = HttpUtility.CreateUser (
|
||||
_request.Headers["Authorization"],
|
||||
scheme,
|
||||
realm,
|
||||
_request.HttpMethod,
|
||||
credentialsFinder
|
||||
);
|
||||
|
||||
if (user != null && user.Identity.IsAuthenticated) {
|
||||
_user = user;
|
||||
return true;
|
||||
}
|
||||
|
||||
_request = sendAuthenticationChallenge (chal);
|
||||
return auth ();
|
||||
};
|
||||
|
||||
return auth ();
|
||||
}
|
||||
|
||||
internal void Close ()
|
||||
{
|
||||
_stream.Close ();
|
||||
_tcpClient.Close ();
|
||||
}
|
||||
|
||||
internal void Close (HttpStatusCode code)
|
||||
{
|
||||
var res = HttpResponse.CreateCloseResponse (code);
|
||||
var bytes = res.ToByteArray ();
|
||||
_stream.Write (bytes, 0, bytes.Length);
|
||||
|
||||
_stream.Close ();
|
||||
_tcpClient.Close ();
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
#region Public Methods
|
||||
|
||||
/// <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 handshake request.
|
||||
/// </returns>
|
||||
public override string ToString ()
|
||||
{
|
||||
return _request.ToString ();
|
||||
}
|
||||
|
||||
#endregion
|
||||
}
|
||||
}
|
224
websocket-sharp/Net/WebSockets/WebSocketContext.cs
Normal file
224
websocket-sharp/Net/WebSockets/WebSocketContext.cs
Normal file
@@ -0,0 +1,224 @@
|
||||
#region License
|
||||
/*
|
||||
* WebSocketContext.cs
|
||||
*
|
||||
* The MIT License
|
||||
*
|
||||
* Copyright (c) 2012-2018 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.Security.Principal;
|
||||
|
||||
namespace WebSocketSharp.Net.WebSockets
|
||||
{
|
||||
/// <summary>
|
||||
/// Exposes the access to the information in a WebSocket handshake request.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// This class is an abstract class.
|
||||
/// </remarks>
|
||||
public abstract class WebSocketContext
|
||||
{
|
||||
#region Protected Constructors
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="WebSocketContext"/> class.
|
||||
/// </summary>
|
||||
protected WebSocketContext ()
|
||||
{
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
#region Public Properties
|
||||
|
||||
/// <summary>
|
||||
/// Gets the HTTP cookies included in the handshake request.
|
||||
/// </summary>
|
||||
/// <value>
|
||||
/// A <see cref="WebSocketSharp.Net.CookieCollection"/> that contains
|
||||
/// the cookies.
|
||||
/// </value>
|
||||
public abstract CookieCollection CookieCollection { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets the HTTP headers included in the handshake request.
|
||||
/// </summary>
|
||||
/// <value>
|
||||
/// A <see cref="NameValueCollection"/> that contains the headers.
|
||||
/// </value>
|
||||
public abstract NameValueCollection Headers { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets the value of the Host header included in the handshake request.
|
||||
/// </summary>
|
||||
/// <value>
|
||||
/// A <see cref="string"/> that represents the server host name requested
|
||||
/// by the client.
|
||||
/// </value>
|
||||
public abstract string Host { get; }
|
||||
|
||||
/// <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 abstract bool IsAuthenticated { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets a value indicating whether the handshake request is sent from
|
||||
/// the local computer.
|
||||
/// </summary>
|
||||
/// <value>
|
||||
/// <c>true</c> if the handshake request is sent from the same computer
|
||||
/// as the server; otherwise, <c>false</c>.
|
||||
/// </value>
|
||||
public abstract bool IsLocal { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets a value indicating whether a secure connection is used to send
|
||||
/// the handshake request.
|
||||
/// </summary>
|
||||
/// <value>
|
||||
/// <c>true</c> if the connection is secure; otherwise, <c>false</c>.
|
||||
/// </value>
|
||||
public abstract bool IsSecureConnection { get; }
|
||||
|
||||
/// <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 abstract bool IsWebSocketRequest { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets the value of the Origin header included in the handshake request.
|
||||
/// </summary>
|
||||
/// <value>
|
||||
/// A <see cref="string"/> that represents the value of the Origin header.
|
||||
/// </value>
|
||||
public abstract string Origin { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets the query string included in the handshake request.
|
||||
/// </summary>
|
||||
/// <value>
|
||||
/// A <see cref="NameValueCollection"/> that contains the query parameters.
|
||||
/// </value>
|
||||
public abstract NameValueCollection QueryString { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets the URI requested by the client.
|
||||
/// </summary>
|
||||
/// <value>
|
||||
/// A <see cref="Uri"/> that represents the URI parsed from the request.
|
||||
/// </value>
|
||||
public abstract Uri RequestUri { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets the value of the Sec-WebSocket-Key header included in
|
||||
/// the handshake request.
|
||||
/// </summary>
|
||||
/// <value>
|
||||
/// <para>
|
||||
/// A <see cref="string"/> that represents the value of
|
||||
/// the Sec-WebSocket-Key header.
|
||||
/// </para>
|
||||
/// <para>
|
||||
/// The value is used to prove that the server received
|
||||
/// a valid WebSocket handshake request.
|
||||
/// </para>
|
||||
/// </value>
|
||||
public abstract string SecWebSocketKey { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets the names of the subprotocols from the Sec-WebSocket-Protocol
|
||||
/// header included in the handshake request.
|
||||
/// </summary>
|
||||
/// <value>
|
||||
/// <para>
|
||||
/// An <see cref="T:System.Collections.Generic.IEnumerable{string}"/>
|
||||
/// instance.
|
||||
/// </para>
|
||||
/// <para>
|
||||
/// It provides an enumerator which supports the iteration over
|
||||
/// the collection of the names of the subprotocols.
|
||||
/// </para>
|
||||
/// </value>
|
||||
public abstract IEnumerable<string> SecWebSocketProtocols { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets the value of the Sec-WebSocket-Version header included in
|
||||
/// the handshake request.
|
||||
/// </summary>
|
||||
/// <value>
|
||||
/// A <see cref="string"/> that represents the WebSocket protocol
|
||||
/// version specified by the client.
|
||||
/// </value>
|
||||
public abstract string SecWebSocketVersion { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets the endpoint to which the handshake request is sent.
|
||||
/// </summary>
|
||||
/// <value>
|
||||
/// A <see cref="System.Net.IPEndPoint"/> that represents the server IP
|
||||
/// address and port number.
|
||||
/// </value>
|
||||
public abstract System.Net.IPEndPoint ServerEndPoint { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets the client information.
|
||||
/// </summary>
|
||||
/// <value>
|
||||
/// A <see cref="IPrincipal"/> instance that represents identity,
|
||||
/// authentication, and security roles for the client.
|
||||
/// </value>
|
||||
public abstract IPrincipal User { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets the endpoint from which the handshake request is sent.
|
||||
/// </summary>
|
||||
/// <value>
|
||||
/// A <see cref="System.Net.IPEndPoint"/> that represents the client IP
|
||||
/// address and port number.
|
||||
/// </value>
|
||||
public abstract System.Net.IPEndPoint UserEndPoint { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets the WebSocket instance used for two-way communication between
|
||||
/// the client and server.
|
||||
/// </summary>
|
||||
/// <value>
|
||||
/// A <see cref="WebSocketSharp.WebSocket"/>.
|
||||
/// </value>
|
||||
public abstract WebSocket WebSocket { get; }
|
||||
|
||||
#endregion
|
||||
}
|
||||
}
|
Reference in New Issue
Block a user