Fix for HTTP Basic/Digest Authentication
This commit is contained in:
@@ -7,7 +7,7 @@
|
||||
* The MIT License
|
||||
*
|
||||
* Copyright (c) 2012-2013 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
|
||||
@@ -17,7 +17,7 @@
|
||||
*
|
||||
* 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
|
||||
@@ -40,16 +40,19 @@ using System.Collections.Generic;
|
||||
using System.Diagnostics;
|
||||
using System.IO;
|
||||
using System.Security.Cryptography.X509Certificates;
|
||||
using System.Security.Principal;
|
||||
using System.Threading;
|
||||
using WebSocketSharp.Net;
|
||||
using WebSocketSharp.Net.WebSockets;
|
||||
|
||||
namespace WebSocketSharp.Server
|
||||
{
|
||||
/// <summary>
|
||||
/// Provides a simple HTTP server that allows to accept the WebSocket connection requests.
|
||||
/// Provides a simple HTTP server that allows to accept the WebSocket
|
||||
/// connection requests.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// The HttpServer instance can provide the multi WebSocket services.
|
||||
/// The HttpServer class can provide the multi WebSocket services.
|
||||
/// </remarks>
|
||||
public class HttpServer
|
||||
{
|
||||
@@ -71,8 +74,8 @@ namespace WebSocketSharp.Server
|
||||
#region Public Constructors
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="HttpServer"/> class that listens for
|
||||
/// incoming requests on port 80.
|
||||
/// Initializes a new instance of the <see cref="HttpServer"/> class that
|
||||
/// listens for incoming requests on port 80.
|
||||
/// </summary>
|
||||
public HttpServer ()
|
||||
: this (80)
|
||||
@@ -80,8 +83,8 @@ namespace WebSocketSharp.Server
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="HttpServer"/> class that listens for
|
||||
/// incoming requests on the specified <paramref name="port"/>.
|
||||
/// Initializes a new instance of the <see cref="HttpServer"/> class that
|
||||
/// listens for incoming requests on the specified <paramref name="port"/>.
|
||||
/// </summary>
|
||||
/// <param name="port">
|
||||
/// An <see cref="int"/> that contains a port number.
|
||||
@@ -95,8 +98,9 @@ namespace WebSocketSharp.Server
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="HttpServer"/> class that listens for
|
||||
/// incoming requests on the specified <paramref name="port"/> and <paramref name="secure"/>.
|
||||
/// Initializes a new instance of the <see cref="HttpServer"/> class that
|
||||
/// listens for incoming requests on the specified <paramref name="port"/>
|
||||
/// and <paramref name="secure"/>.
|
||||
/// </summary>
|
||||
/// <param name="port">
|
||||
/// An <see cref="int"/> that contains a port number.
|
||||
@@ -114,16 +118,28 @@ namespace WebSocketSharp.Server
|
||||
public HttpServer (int port, bool secure)
|
||||
{
|
||||
if (!port.IsPortNumber ())
|
||||
throw new ArgumentOutOfRangeException ("port", "Must be between 1 and 65535: " + port);
|
||||
throw new ArgumentOutOfRangeException (
|
||||
"port", "Must be between 1 and 65535: " + port);
|
||||
|
||||
if ((port == 80 && secure) || (port == 443 && !secure))
|
||||
throw new ArgumentException (String.Format (
|
||||
"Invalid pair of 'port' and 'secure': {0}, {1}", port, secure));
|
||||
throw new ArgumentException (
|
||||
String.Format (
|
||||
"Invalid pair of 'port' and 'secure': {0}, {1}", port, secure));
|
||||
|
||||
_port = port;
|
||||
_secure = secure;
|
||||
_listener = new HttpListener ();
|
||||
_logger = new Logger ();
|
||||
_serviceHosts = new WebSocketServiceHostManager (_logger);
|
||||
_state = ServerState.READY;
|
||||
_sync = new object ();
|
||||
|
||||
init ();
|
||||
var os = Environment.OSVersion;
|
||||
if (os.Platform != PlatformID.Unix && os.Platform != PlatformID.MacOSX)
|
||||
_windows = true;
|
||||
|
||||
var prefix = String.Format ("http{0}://*:{1}/", _secure ? "s" : "", _port);
|
||||
_listener.Prefixes.Add (prefix);
|
||||
}
|
||||
|
||||
#endregion
|
||||
@@ -131,7 +147,29 @@ namespace WebSocketSharp.Server
|
||||
#region Public Properties
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the certificate used to authenticate the server on the secure connection.
|
||||
/// Gets or sets the scheme used to authenticate the clients.
|
||||
/// </summary>
|
||||
/// <value>
|
||||
/// One of the <see cref="WebSocketSharp.Net.AuthenticationSchemes"/> values
|
||||
/// that indicates the scheme used to authenticate the clients. The default
|
||||
/// value is <see cref="WebSocketSharp.Net.AuthenticationSchemes.Anonymous"/>.
|
||||
/// </value>
|
||||
public AuthenticationSchemes AuthenticationSchemes {
|
||||
get {
|
||||
return _listener.AuthenticationSchemes;
|
||||
}
|
||||
|
||||
set {
|
||||
if (!canSet ("AuthenticationSchemes"))
|
||||
return;
|
||||
|
||||
_listener.AuthenticationSchemes = value;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the certificate used to authenticate the server on the
|
||||
/// secure connection.
|
||||
/// </summary>
|
||||
/// <value>
|
||||
/// A <see cref="X509Certificate2"/> used to authenticate the server.
|
||||
@@ -142,16 +180,12 @@ namespace WebSocketSharp.Server
|
||||
}
|
||||
|
||||
set {
|
||||
if (_state == ServerState.START || _state == ServerState.SHUTDOWN)
|
||||
{
|
||||
_logger.Error (
|
||||
"The value of Certificate property cannot be changed because the server has already been started.");
|
||||
|
||||
if (!canSet ("Certificate"))
|
||||
return;
|
||||
}
|
||||
|
||||
if (EndPointListener.CertificateExists (_port, _listener.CertificateFolderPath))
|
||||
_logger.Warn ("The server certificate associated with the port number already exists.");
|
||||
_logger.Warn (
|
||||
"The server certificate associated with the port number already exists.");
|
||||
|
||||
_listener.DefaultCertificate = value;
|
||||
}
|
||||
@@ -173,7 +207,8 @@ namespace WebSocketSharp.Server
|
||||
/// Gets a value indicating whether the server provides secure connection.
|
||||
/// </summary>
|
||||
/// <value>
|
||||
/// <c>true</c> if the server provides secure connection; otherwise, <c>false</c>.
|
||||
/// <c>true</c> if the server provides secure connection; otherwise,
|
||||
/// <c>false</c>.
|
||||
/// </value>
|
||||
public bool IsSecure {
|
||||
get {
|
||||
@@ -182,12 +217,12 @@ namespace WebSocketSharp.Server
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets a value indicating whether the server cleans up the inactive WebSocket sessions
|
||||
/// periodically.
|
||||
/// Gets or sets a value indicating whether the server cleans up the inactive
|
||||
/// WebSocket sessions periodically.
|
||||
/// </summary>
|
||||
/// <value>
|
||||
/// <c>true</c> if the server cleans up the inactive WebSocket sessions every 60 seconds;
|
||||
/// otherwise, <c>false</c>. The default value is <c>true</c>.
|
||||
/// <c>true</c> if the server cleans up the inactive WebSocket sessions every
|
||||
/// 60 seconds; otherwise, <c>false</c>. The default value is <c>true</c>.
|
||||
/// </value>
|
||||
public bool KeepClean {
|
||||
get {
|
||||
@@ -203,9 +238,9 @@ namespace WebSocketSharp.Server
|
||||
/// Gets the logging functions.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// The default logging level is the <see cref="LogLevel.ERROR"/>.
|
||||
/// If you want to change the current logging level, you set the <c>Log.Level</c> property
|
||||
/// to one of the <see cref="LogLevel"/> values which you want.
|
||||
/// The default logging level is the <see cref="LogLevel.ERROR"/>. If you
|
||||
/// change the current logging level, you set the <c>Log.Level</c> property
|
||||
/// to any of the <see cref="LogLevel"/> values.
|
||||
/// </remarks>
|
||||
/// <value>
|
||||
/// A <see cref="Logger"/> that provides the logging functions.
|
||||
@@ -228,6 +263,27 @@ namespace WebSocketSharp.Server
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the name of the realm associated with the
|
||||
/// <see cref="HttpServer"/>.
|
||||
/// </summary>
|
||||
/// <value>
|
||||
/// A <see cref="string"/> that contains the name of the realm.
|
||||
/// The default value is <c>SECRET AREA</c>.
|
||||
/// </value>
|
||||
public string Realm {
|
||||
get {
|
||||
return _listener.Realm;
|
||||
}
|
||||
|
||||
set {
|
||||
if (!canSet ("Realm"))
|
||||
return;
|
||||
|
||||
_listener.Realm = value;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the document root path of server.
|
||||
/// </summary>
|
||||
@@ -243,23 +299,42 @@ namespace WebSocketSharp.Server
|
||||
}
|
||||
|
||||
set {
|
||||
if (_state == ServerState.START || _state == ServerState.SHUTDOWN)
|
||||
{
|
||||
_logger.Error (
|
||||
"The value of RootPath property cannot be changed because the server has already been started.");
|
||||
|
||||
if (!canSet ("RootPath"))
|
||||
return;
|
||||
}
|
||||
|
||||
_rootPath = value;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the functions for the WebSocket services that the server provides.
|
||||
/// Gets or sets the delegate called to find the credentials for an identity
|
||||
/// used to authenticate a client.
|
||||
/// </summary>
|
||||
/// <value>
|
||||
/// A <see cref="WebSocketServiceHostManager"/> that manages the WebSocket services.
|
||||
/// A Func<<see cref="IIdentity"/>, <see cref="NetworkCredential"/>>
|
||||
/// delegate that references the method(s) used to find the credentials. The
|
||||
/// default value is a function that only returns <see langword="null"/>.
|
||||
/// </value>
|
||||
public Func<IIdentity, NetworkCredential> UserCredentialsFinder {
|
||||
get {
|
||||
return _listener.UserCredentialsFinder;
|
||||
}
|
||||
|
||||
set {
|
||||
if (!canSet ("UserCredentialsFinder"))
|
||||
return;
|
||||
|
||||
_listener.UserCredentialsFinder = value;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the functions for the WebSocket services provided by the
|
||||
/// <see cref="HttpServer"/>.
|
||||
/// </summary>
|
||||
/// <value>
|
||||
/// A <see cref="WebSocketServiceHostManager"/> that manages the WebSocket
|
||||
/// services.
|
||||
/// </value>
|
||||
public WebSocketServiceHostManager WebSocketServices {
|
||||
get {
|
||||
@@ -322,8 +397,7 @@ namespace WebSocketSharp.Server
|
||||
|
||||
private void abort ()
|
||||
{
|
||||
lock (_sync)
|
||||
{
|
||||
lock (_sync) {
|
||||
if (!IsListening)
|
||||
return;
|
||||
|
||||
@@ -331,12 +405,136 @@ namespace WebSocketSharp.Server
|
||||
}
|
||||
|
||||
_serviceHosts.Stop (
|
||||
((ushort) CloseStatusCode.SERVER_ERROR).ToByteArrayInternally (ByteOrder.BIG), true);
|
||||
((ushort) CloseStatusCode.SERVER_ERROR).ToByteArrayInternally (ByteOrder.BIG),
|
||||
true);
|
||||
_listener.Abort ();
|
||||
|
||||
_state = ServerState.STOP;
|
||||
}
|
||||
|
||||
private void acceptHttpRequest (HttpListenerContext context)
|
||||
{
|
||||
var args = new HttpRequestEventArgs (context);
|
||||
var method = context.Request.HttpMethod;
|
||||
if (method == "GET" && OnGet != null) {
|
||||
OnGet (this, args);
|
||||
return;
|
||||
}
|
||||
|
||||
if (method == "HEAD" && OnHead != null) {
|
||||
OnHead (this, args);
|
||||
return;
|
||||
}
|
||||
|
||||
if (method == "POST" && OnPost != null) {
|
||||
OnPost (this, args);
|
||||
return;
|
||||
}
|
||||
|
||||
if (method == "PUT" && OnPut != null) {
|
||||
OnPut (this, args);
|
||||
return;
|
||||
}
|
||||
|
||||
if (method == "DELETE" && OnDelete != null) {
|
||||
OnDelete (this, args);
|
||||
return;
|
||||
}
|
||||
|
||||
if (method == "OPTIONS" && OnOptions != null) {
|
||||
OnOptions (this, args);
|
||||
return;
|
||||
}
|
||||
|
||||
if (method == "TRACE" && OnTrace != null) {
|
||||
OnTrace (this, args);
|
||||
return;
|
||||
}
|
||||
|
||||
if (method == "CONNECT" && OnConnect != null) {
|
||||
OnConnect (this, args);
|
||||
return;
|
||||
}
|
||||
|
||||
if (method == "PATCH" && OnPatch != null) {
|
||||
OnPatch (this, args);
|
||||
return;
|
||||
}
|
||||
|
||||
context.Response.Close (HttpStatusCode.NotImplemented);
|
||||
}
|
||||
|
||||
private void acceptRequestAsync (HttpListenerContext context)
|
||||
{
|
||||
ThreadPool.QueueUserWorkItem (
|
||||
state => {
|
||||
try {
|
||||
var authScheme = _listener.SelectAuthenticationScheme (context);
|
||||
if (authScheme != AuthenticationSchemes.Anonymous &&
|
||||
!authenticateRequest (authScheme, context))
|
||||
return;
|
||||
|
||||
if (context.Request.IsUpgradeTo ("websocket")) {
|
||||
acceptWebSocketRequest (context.AcceptWebSocket (_logger));
|
||||
return;
|
||||
}
|
||||
|
||||
acceptHttpRequest (context);
|
||||
context.Response.Close ();
|
||||
}
|
||||
catch (Exception ex) {
|
||||
_logger.Fatal (ex.ToString ());
|
||||
context.Connection.Close (true);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
private void acceptWebSocketRequest (HttpListenerWebSocketContext context)
|
||||
{
|
||||
var path = context.Path;
|
||||
|
||||
WebSocketServiceHost host;
|
||||
if (path == null ||
|
||||
!_serviceHosts.TryGetServiceHostInternally (path, out host)) {
|
||||
context.Close (HttpStatusCode.NotImplemented);
|
||||
return;
|
||||
}
|
||||
|
||||
host.StartSession (context);
|
||||
}
|
||||
|
||||
private bool authenticateRequest (
|
||||
AuthenticationSchemes scheme, HttpListenerContext context)
|
||||
{
|
||||
if (context.Request.IsAuthenticated)
|
||||
return true;
|
||||
|
||||
if (scheme == AuthenticationSchemes.Basic)
|
||||
context.Response.CloseWithAuthChallenge (
|
||||
HttpUtility.CreateBasicAuthChallenge (_listener.Realm));
|
||||
else if (scheme == AuthenticationSchemes.Digest)
|
||||
context.Response.CloseWithAuthChallenge (
|
||||
HttpUtility.CreateDigestAuthChallenge (_listener.Realm));
|
||||
else
|
||||
context.Response.Close (HttpStatusCode.Forbidden);
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
private bool canSet (string property)
|
||||
{
|
||||
if (_state == ServerState.START || _state == ServerState.SHUTDOWN) {
|
||||
_logger.Error (
|
||||
String.Format (
|
||||
"The '{0}' property cannot set a value because the server has already been started.",
|
||||
property));
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
private string checkIfCertExists ()
|
||||
{
|
||||
return _secure &&
|
||||
@@ -346,137 +544,17 @@ namespace WebSocketSharp.Server
|
||||
: null;
|
||||
}
|
||||
|
||||
private void init ()
|
||||
{
|
||||
_listener = new HttpListener ();
|
||||
_logger = new Logger ();
|
||||
_serviceHosts = new WebSocketServiceHostManager (_logger);
|
||||
_state = ServerState.READY;
|
||||
_sync = new object ();
|
||||
|
||||
_windows = false;
|
||||
var os = Environment.OSVersion;
|
||||
if (os.Platform != PlatformID.Unix && os.Platform != PlatformID.MacOSX)
|
||||
_windows = true;
|
||||
|
||||
var prefix = String.Format ("http{0}://*:{1}/", _secure ? "s" : "", _port);
|
||||
_listener.Prefixes.Add (prefix);
|
||||
}
|
||||
|
||||
private void processHttpRequest (HttpListenerContext context)
|
||||
{
|
||||
var args = new HttpRequestEventArgs (context);
|
||||
var method = context.Request.HttpMethod;
|
||||
if (method == "GET" && OnGet != null)
|
||||
{
|
||||
OnGet (this, args);
|
||||
return;
|
||||
}
|
||||
|
||||
if (method == "HEAD" && OnHead != null)
|
||||
{
|
||||
OnHead (this, args);
|
||||
return;
|
||||
}
|
||||
|
||||
if (method == "POST" && OnPost != null)
|
||||
{
|
||||
OnPost (this, args);
|
||||
return;
|
||||
}
|
||||
|
||||
if (method == "PUT" && OnPut != null)
|
||||
{
|
||||
OnPut (this, args);
|
||||
return;
|
||||
}
|
||||
|
||||
if (method == "DELETE" && OnDelete != null)
|
||||
{
|
||||
OnDelete (this, args);
|
||||
return;
|
||||
}
|
||||
|
||||
if (method == "OPTIONS" && OnOptions != null)
|
||||
{
|
||||
OnOptions (this, args);
|
||||
return;
|
||||
}
|
||||
|
||||
if (method == "TRACE" && OnTrace != null)
|
||||
{
|
||||
OnTrace (this, args);
|
||||
return;
|
||||
}
|
||||
|
||||
if (method == "CONNECT" && OnConnect != null)
|
||||
{
|
||||
OnConnect (this, args);
|
||||
return;
|
||||
}
|
||||
|
||||
if (method == "PATCH" && OnPatch != null)
|
||||
{
|
||||
OnPatch (this, args);
|
||||
return;
|
||||
}
|
||||
|
||||
context.Response.StatusCode = (int) HttpStatusCode.NotImplemented;
|
||||
}
|
||||
|
||||
private bool processWebSocketRequest (HttpListenerContext context)
|
||||
{
|
||||
var wsContext = context.AcceptWebSocket ();
|
||||
|
||||
var path = wsContext.Path;
|
||||
WebSocketServiceHost host;
|
||||
if (path == null || !_serviceHosts.TryGetServiceHostInternally (path, out host))
|
||||
{
|
||||
context.Response.StatusCode = (int) HttpStatusCode.NotImplemented;
|
||||
return false;
|
||||
}
|
||||
|
||||
wsContext.WebSocket.Log = _logger;
|
||||
host.StartSession (wsContext);
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
private void processRequestAsync (HttpListenerContext context)
|
||||
{
|
||||
WaitCallback callback = state =>
|
||||
{
|
||||
try {
|
||||
if (context.Request.IsUpgradeTo ("websocket"))
|
||||
{
|
||||
if (processWebSocketRequest (context))
|
||||
return;
|
||||
}
|
||||
else
|
||||
{
|
||||
processHttpRequest (context);
|
||||
}
|
||||
|
||||
context.Response.Close ();
|
||||
}
|
||||
catch (Exception ex) {
|
||||
_logger.Fatal (ex.ToString ());
|
||||
context.Connection.Close (true);
|
||||
}
|
||||
};
|
||||
|
||||
ThreadPool.QueueUserWorkItem (callback);
|
||||
}
|
||||
|
||||
private void receiveRequest ()
|
||||
{
|
||||
while (true)
|
||||
{
|
||||
while (true) {
|
||||
try {
|
||||
processRequestAsync (_listener.GetContext ());
|
||||
acceptRequestAsync (_listener.GetContext ());
|
||||
}
|
||||
catch (HttpListenerException ex) {
|
||||
_logger.Warn (String.Format ("Receiving has been stopped.\nreason: {0}.", ex.Message));
|
||||
_logger.Warn (
|
||||
String.Format (
|
||||
"Receiving has been stopped.\nreason: {0}.", ex.Message));
|
||||
|
||||
break;
|
||||
}
|
||||
catch (Exception ex) {
|
||||
@@ -489,9 +567,9 @@ namespace WebSocketSharp.Server
|
||||
abort ();
|
||||
}
|
||||
|
||||
private void startReceiveRequestThread ()
|
||||
private void startReceiving ()
|
||||
{
|
||||
_receiveRequestThread = new Thread (new ThreadStart (receiveRequest));
|
||||
_receiveRequestThread = new Thread (new ThreadStart (receiveRequest));
|
||||
_receiveRequestThread.IsBackground = true;
|
||||
_receiveRequestThread.Start ();
|
||||
}
|
||||
@@ -507,18 +585,21 @@ namespace WebSocketSharp.Server
|
||||
#region Public Methods
|
||||
|
||||
/// <summary>
|
||||
/// Adds the specified typed WebSocket service with the specified <paramref name="servicePath"/>.
|
||||
/// Adds the specified typed WebSocket service with the specified
|
||||
/// <paramref name="servicePath"/>.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// This method converts <paramref name="servicePath"/> to URL-decoded string and
|
||||
/// removes <c>'/'</c> from tail end of <paramref name="servicePath"/>.
|
||||
/// This method converts <paramref name="servicePath"/> to URL-decoded string
|
||||
/// and removes <c>'/'</c> from tail end of <paramref name="servicePath"/>.
|
||||
/// </remarks>
|
||||
/// <param name="servicePath">
|
||||
/// A <see cref="string"/> that contains an absolute path to the WebSocket service.
|
||||
/// A <see cref="string"/> that contains an absolute path to the WebSocket
|
||||
/// service.
|
||||
/// </param>
|
||||
/// <typeparam name="TWithNew">
|
||||
/// The type of the WebSocket service. The TWithNew must inherit the <see cref="WebSocketService"/> class and
|
||||
/// must have a public parameterless constructor.
|
||||
/// The type of the WebSocket service. The TWithNew must inherit the
|
||||
/// <see cref="WebSocketService"/> class and must have a public parameterless
|
||||
/// constructor.
|
||||
/// </typeparam>
|
||||
public void AddWebSocketService<TWithNew> (string servicePath)
|
||||
where TWithNew : WebSocketService, new ()
|
||||
@@ -527,42 +608,50 @@ namespace WebSocketSharp.Server
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Adds the specified typed WebSocket service with the specified <paramref name="servicePath"/> and
|
||||
/// <paramref name="serviceConstructor"/>.
|
||||
/// Adds the specified typed WebSocket service with the specified
|
||||
/// <paramref name="servicePath"/> and <paramref name="serviceConstructor"/>.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// <para>
|
||||
/// This method converts <paramref name="servicePath"/> to URL-decoded string and
|
||||
/// removes <c>'/'</c> from tail end of <paramref name="servicePath"/>.
|
||||
/// This method converts <paramref name="servicePath"/> to URL-decoded
|
||||
/// string and removes <c>'/'</c> from tail end of
|
||||
/// <paramref name="servicePath"/>.
|
||||
/// </para>
|
||||
/// <para>
|
||||
/// <paramref name="serviceConstructor"/> returns a initialized specified typed WebSocket service
|
||||
/// instance.
|
||||
/// <paramref name="serviceConstructor"/> returns a initialized specified
|
||||
/// typed WebSocket service instance.
|
||||
/// </para>
|
||||
/// </remarks>
|
||||
/// <param name="servicePath">
|
||||
/// A <see cref="string"/> that contains an absolute path to the WebSocket service.
|
||||
/// A <see cref="string"/> that contains an absolute path to the WebSocket
|
||||
/// service.
|
||||
/// </param>
|
||||
/// <param name="serviceConstructor">
|
||||
/// A Func<T> delegate that references the method used to initialize a new WebSocket service
|
||||
/// instance (a new WebSocket session).
|
||||
/// A Func<T> delegate that references the method used to initialize
|
||||
/// a new WebSocket service instance (a new WebSocket session).
|
||||
/// </param>
|
||||
/// <typeparam name="T">
|
||||
/// The type of the WebSocket service. The T must inherit the <see cref="WebSocketService"/> class.
|
||||
/// The type of the WebSocket service. The T must inherit the
|
||||
/// <see cref="WebSocketService"/> class.
|
||||
/// </typeparam>
|
||||
public void AddWebSocketService<T> (string servicePath, Func<T> serviceConstructor)
|
||||
where T : WebSocketService
|
||||
{
|
||||
var msg = servicePath.CheckIfValidServicePath () ??
|
||||
(serviceConstructor == null ? "'serviceConstructor' must not be null." : null);
|
||||
(serviceConstructor == null
|
||||
? "'serviceConstructor' must not be null."
|
||||
: null);
|
||||
|
||||
if (msg != null) {
|
||||
_logger.Error (
|
||||
String.Format ("{0}\nservice path: {1}", msg, servicePath ?? ""));
|
||||
|
||||
if (msg != null)
|
||||
{
|
||||
_logger.Error (String.Format ("{0}\nservice path: {1}", msg, servicePath ?? ""));
|
||||
return;
|
||||
}
|
||||
|
||||
var host = new WebSocketServiceHost<T> (servicePath, serviceConstructor, _logger);
|
||||
var host = new WebSocketServiceHost<T> (
|
||||
servicePath, serviceConstructor, _logger);
|
||||
|
||||
if (!KeepClean)
|
||||
host.KeepClean = false;
|
||||
|
||||
@@ -573,8 +662,8 @@ namespace WebSocketSharp.Server
|
||||
/// Gets the contents of the file with the specified <paramref name="path"/>.
|
||||
/// </summary>
|
||||
/// <returns>
|
||||
/// An array of <see cref="byte"/> that contains the contents of the file if exists;
|
||||
/// otherwise, <see langword="null"/>.
|
||||
/// An array of <see cref="byte"/> that contains the contents of the file if
|
||||
/// it exists; otherwise, <see langword="null"/>.
|
||||
/// </returns>
|
||||
/// <param name="path">
|
||||
/// A <see cref="string"/> that contains a virtual path to the file to get.
|
||||
@@ -591,24 +680,28 @@ namespace WebSocketSharp.Server
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Removes the WebSocket service with the specified <paramref name="servicePath"/>.
|
||||
/// Removes the WebSocket service with the specified
|
||||
/// <paramref name="servicePath"/>.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// This method converts <paramref name="servicePath"/> to URL-decoded string and
|
||||
/// removes <c>'/'</c> from tail end of <paramref name="servicePath"/>.
|
||||
/// This method converts <paramref name="servicePath"/> to URL-decoded string
|
||||
/// and removes <c>'/'</c> from tail end of <paramref name="servicePath"/>.
|
||||
/// </remarks>
|
||||
/// <returns>
|
||||
/// <c>true</c> if the WebSocket service is successfully found and removed; otherwise, <c>false</c>.
|
||||
/// <c>true</c> if the WebSocket service is successfully found and removed;
|
||||
/// otherwise, <c>false</c>.
|
||||
/// </returns>
|
||||
/// <param name="servicePath">
|
||||
/// A <see cref="string"/> that contains an absolute path to the WebSocket service to find.
|
||||
/// A <see cref="string"/> that contains an absolute path to the WebSocket
|
||||
/// service to find.
|
||||
/// </param>
|
||||
public bool RemoveWebSocketService (string servicePath)
|
||||
{
|
||||
var msg = servicePath.CheckIfValidServicePath ();
|
||||
if (msg != null)
|
||||
{
|
||||
_logger.Error (String.Format ("{0}\nservice path: {1}", msg, servicePath ?? ""));
|
||||
if (msg != null) {
|
||||
_logger.Error (
|
||||
String.Format ("{0}\nservice path: {1}", msg, servicePath));
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
@@ -616,22 +709,23 @@ namespace WebSocketSharp.Server
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Starts to receive the HTTP requests.
|
||||
/// Starts receiving the HTTP requests.
|
||||
/// </summary>
|
||||
public void Start ()
|
||||
{
|
||||
lock (_sync)
|
||||
{
|
||||
lock (_sync) {
|
||||
var msg = _state.CheckIfStopped () ?? checkIfCertExists ();
|
||||
if (msg != null)
|
||||
{
|
||||
_logger.Error (String.Format ("{0}\nstate: {1}\nsecure: {2}", msg, _state, _secure));
|
||||
if (msg != null) {
|
||||
_logger.Error (
|
||||
String.Format (
|
||||
"{0}\nstate: {1}\nsecure: {2}", msg, _state, _secure));
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
_serviceHosts.Start ();
|
||||
_listener.Start ();
|
||||
startReceiveRequestThread ();
|
||||
startReceiving ();
|
||||
|
||||
_state = ServerState.START;
|
||||
}
|
||||
@@ -642,11 +736,9 @@ namespace WebSocketSharp.Server
|
||||
/// </summary>
|
||||
public void Stop ()
|
||||
{
|
||||
lock (_sync)
|
||||
{
|
||||
lock (_sync) {
|
||||
var msg = _state.CheckIfStarted ();
|
||||
if (msg != null)
|
||||
{
|
||||
if (msg != null) {
|
||||
_logger.Error (String.Format ("{0}\nstate: {1}", msg, _state));
|
||||
return;
|
||||
}
|
||||
@@ -654,18 +746,19 @@ namespace WebSocketSharp.Server
|
||||
_state = ServerState.SHUTDOWN;
|
||||
}
|
||||
|
||||
_serviceHosts.Stop (new byte []{}, true);
|
||||
_serviceHosts.Stop (new byte [0], true);
|
||||
stopListener (5000);
|
||||
|
||||
_state = ServerState.STOP;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Stops receiving the HTTP requests with the specified <see cref="ushort"/> and
|
||||
/// <see cref="string"/> used to stop the WebSocket services.
|
||||
/// Stops receiving the HTTP requests with the specified <see cref="ushort"/>
|
||||
/// and <see cref="string"/> used to stop the WebSocket services.
|
||||
/// </summary>
|
||||
/// <param name="code">
|
||||
/// A <see cref="ushort"/> that contains a status code indicating the reason for stop.
|
||||
/// A <see cref="ushort"/> that contains a status code indicating the reason
|
||||
/// for stop.
|
||||
/// </param>
|
||||
/// <param name="reason">
|
||||
/// A <see cref="string"/> that contains the reason for stop.
|
||||
@@ -673,16 +766,15 @@ namespace WebSocketSharp.Server
|
||||
public void Stop (ushort code, string reason)
|
||||
{
|
||||
byte [] data = null;
|
||||
lock (_sync)
|
||||
{
|
||||
lock (_sync) {
|
||||
var msg = _state.CheckIfStarted () ??
|
||||
code.CheckIfValidCloseStatusCode () ??
|
||||
(data = code.Append (reason)).CheckIfValidCloseData ();
|
||||
|
||||
if (msg != null)
|
||||
{
|
||||
_logger.Error (String.Format (
|
||||
"{0}\nstate: {1}\ncode: {2}\nreason: {3}", msg, _state, code, reason));
|
||||
if (msg != null) {
|
||||
_logger.Error (
|
||||
String.Format (
|
||||
"{0}\nstate: {1}\ncode: {2}\nreason: {3}", msg, _state, code, reason));
|
||||
|
||||
return;
|
||||
}
|
||||
@@ -697,12 +789,13 @@ namespace WebSocketSharp.Server
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Stops receiving the HTTP requests with the specified <see cref="CloseStatusCode"/>
|
||||
/// and <see cref="string"/> used to stop the WebSocket services.
|
||||
/// Stops receiving the HTTP requests with the specified
|
||||
/// <see cref="CloseStatusCode"/> and <see cref="string"/> used to stop the
|
||||
/// WebSocket services.
|
||||
/// </summary>
|
||||
/// <param name="code">
|
||||
/// One of the <see cref="CloseStatusCode"/> values that represent the status codes indicating
|
||||
/// the reasons for stop.
|
||||
/// One of the <see cref="CloseStatusCode"/> values that represent the status
|
||||
/// codes indicating the reasons for stop.
|
||||
/// </param>
|
||||
/// <param name="reason">
|
||||
/// A <see cref="string"/> that contains the reason for stop.
|
||||
@@ -710,14 +803,14 @@ namespace WebSocketSharp.Server
|
||||
public void Stop (CloseStatusCode code, string reason)
|
||||
{
|
||||
byte [] data = null;
|
||||
lock (_sync)
|
||||
{
|
||||
lock (_sync) {
|
||||
var msg = _state.CheckIfStarted () ??
|
||||
(data = ((ushort) code).Append (reason)).CheckIfValidCloseData ();
|
||||
|
||||
if (msg != null)
|
||||
{
|
||||
_logger.Error (String.Format ("{0}\nstate: {1}\nreason: {2}", msg, _state, reason));
|
||||
if (msg != null) {
|
||||
_logger.Error (
|
||||
String.Format ("{0}\nstate: {1}\nreason: {2}", msg, _state, reason));
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
|
@@ -7,7 +7,7 @@
|
||||
* The MIT License
|
||||
*
|
||||
* Copyright (c) 2012-2013 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
|
||||
@@ -17,7 +17,7 @@
|
||||
*
|
||||
* 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
|
||||
@@ -39,6 +39,7 @@ using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Net.Sockets;
|
||||
using System.Security.Cryptography.X509Certificates;
|
||||
using System.Security.Principal;
|
||||
using System.Text;
|
||||
using System.Threading;
|
||||
using WebSocketSharp.Net;
|
||||
@@ -47,7 +48,8 @@ using WebSocketSharp.Net.WebSockets;
|
||||
namespace WebSocketSharp.Server
|
||||
{
|
||||
/// <summary>
|
||||
/// Provides the functions of the server that receives the WebSocket connection requests.
|
||||
/// Provides the functions of the server that receives the WebSocket connection
|
||||
/// requests.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// The WebSocketServer class provides the multi WebSocket service.
|
||||
@@ -56,25 +58,28 @@ namespace WebSocketSharp.Server
|
||||
{
|
||||
#region Private Fields
|
||||
|
||||
private System.Net.IPAddress _address;
|
||||
private X509Certificate2 _cert;
|
||||
private TcpListener _listener;
|
||||
private Logger _logger;
|
||||
private int _port;
|
||||
private Thread _receiveRequestThread;
|
||||
private bool _secure;
|
||||
private WebSocketServiceHostManager _serviceHosts;
|
||||
private volatile ServerState _state;
|
||||
private object _sync;
|
||||
private Uri _uri;
|
||||
private System.Net.IPAddress _address;
|
||||
private AuthenticationSchemes _authSchemes;
|
||||
private X509Certificate2 _cert;
|
||||
private Func<IIdentity, NetworkCredential> _credentialsFinder;
|
||||
private TcpListener _listener;
|
||||
private Logger _logger;
|
||||
private int _port;
|
||||
private string _realm;
|
||||
private Thread _receiveRequestThread;
|
||||
private bool _secure;
|
||||
private WebSocketServiceHostManager _serviceHosts;
|
||||
private volatile ServerState _state;
|
||||
private object _sync;
|
||||
private Uri _uri;
|
||||
|
||||
#endregion
|
||||
|
||||
#region Public Constructors
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="WebSocketServer"/> class that listens for
|
||||
/// incoming requests on port 80.
|
||||
/// Initializes a new instance of the <see cref="WebSocketServer"/> class
|
||||
/// that listens for incoming requests on port 80.
|
||||
/// </summary>
|
||||
public WebSocketServer ()
|
||||
: this (80)
|
||||
@@ -82,8 +87,9 @@ namespace WebSocketSharp.Server
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="WebSocketServer"/> class that listens for
|
||||
/// incoming connection attempts on the specified <paramref name="port"/>.
|
||||
/// Initializes a new instance of the <see cref="WebSocketServer"/> class
|
||||
/// that listens for incoming connection attempts on the specified
|
||||
/// <paramref name="port"/>.
|
||||
/// </summary>
|
||||
/// <param name="port">
|
||||
/// An <see cref="int"/> that contains a port number.
|
||||
@@ -97,8 +103,9 @@ namespace WebSocketSharp.Server
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="WebSocketServer"/> class that listens for
|
||||
/// incoming connection attempts on the specified WebSocket URL.
|
||||
/// Initializes a new instance of the <see cref="WebSocketServer"/> class
|
||||
/// that listens for incoming connection attempts on the specified WebSocket
|
||||
/// URL.
|
||||
/// </summary>
|
||||
/// <param name="url">
|
||||
/// A <see cref="string"/> that contains a WebSocket URL.
|
||||
@@ -121,8 +128,9 @@ namespace WebSocketSharp.Server
|
||||
var host = _uri.DnsSafeHost;
|
||||
_address = host.ToIPAddress ();
|
||||
if (_address == null || !_address.IsLocal ())
|
||||
throw new ArgumentException (String.Format (
|
||||
"The host part must be the local host name: {0}", host), "url");
|
||||
throw new ArgumentException (
|
||||
String.Format (
|
||||
"The host part must be the local host name: {0}", host), "url");
|
||||
|
||||
_port = _uri.Port;
|
||||
_secure = _uri.Scheme == "wss" ? true : false;
|
||||
@@ -131,8 +139,9 @@ namespace WebSocketSharp.Server
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="WebSocketServer"/> class that listens for
|
||||
/// incoming connection attempts on the specified <paramref name="port"/> and <paramref name="secure"/>.
|
||||
/// Initializes a new instance of the <see cref="WebSocketServer"/> class
|
||||
/// that listens for incoming connection attempts on the specified
|
||||
/// <paramref name="port"/> and <paramref name="secure"/>.
|
||||
/// </summary>
|
||||
/// <param name="port">
|
||||
/// An <see cref="int"/> that contains a port number.
|
||||
@@ -153,11 +162,13 @@ namespace WebSocketSharp.Server
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="WebSocketServer"/> class that listens for
|
||||
/// incoming connection attempts on the specified <paramref name="address"/> and <paramref name="port"/>.
|
||||
/// Initializes a new instance of the <see cref="WebSocketServer"/> class
|
||||
/// that listens for incoming connection attempts on the specified
|
||||
/// <paramref name="address"/> and <paramref name="port"/>.
|
||||
/// </summary>
|
||||
/// <param name="address">
|
||||
/// A <see cref="System.Net.IPAddress"/> that represents the local IP address.
|
||||
/// A <see cref="System.Net.IPAddress"/> that represents the local IP
|
||||
/// address.
|
||||
/// </param>
|
||||
/// <param name="port">
|
||||
/// An <see cref="int"/> that contains a port number.
|
||||
@@ -177,12 +188,14 @@ namespace WebSocketSharp.Server
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="WebSocketServer"/> class that listens for
|
||||
/// incoming connection attempts on the specified <paramref name="address"/>, <paramref name="port"/>
|
||||
/// and <paramref name="secure"/>.
|
||||
/// Initializes a new instance of the <see cref="WebSocketServer"/> class
|
||||
/// that listens for incoming connection attempts on the specified
|
||||
/// <paramref name="address"/>, <paramref name="port"/> and
|
||||
/// <paramref name="secure"/>.
|
||||
/// </summary>
|
||||
/// <param name="address">
|
||||
/// A <see cref="System.Net.IPAddress"/> that represents the local IP address.
|
||||
/// A <see cref="System.Net.IPAddress"/> that represents the local IP
|
||||
/// address.
|
||||
/// </param>
|
||||
/// <param name="port">
|
||||
/// An <see cref="int"/> that contains a port number.
|
||||
@@ -205,21 +218,25 @@ namespace WebSocketSharp.Server
|
||||
/// -or-
|
||||
/// </para>
|
||||
/// <para>
|
||||
/// Pair of <paramref name="port"/> and <paramref name="secure"/> is invalid.
|
||||
/// Pair of <paramref name="port"/> and <paramref name="secure"/> is
|
||||
/// invalid.
|
||||
/// </para>
|
||||
/// </exception>
|
||||
public WebSocketServer (System.Net.IPAddress address, int port, bool secure)
|
||||
{
|
||||
if (!address.IsLocal ())
|
||||
throw new ArgumentException (String.Format (
|
||||
"Must be the local IP address: {0}", address), "address");
|
||||
throw new ArgumentException (
|
||||
String.Format (
|
||||
"Must be the local IP address: {0}", address), "address");
|
||||
|
||||
if (!port.IsPortNumber ())
|
||||
throw new ArgumentOutOfRangeException ("port", "Must be between 1 and 65535: " + port);
|
||||
throw new ArgumentOutOfRangeException (
|
||||
"port", "Must be between 1 and 65535: " + port);
|
||||
|
||||
if ((port == 80 && secure) || (port == 443 && !secure))
|
||||
throw new ArgumentException (String.Format (
|
||||
"Invalid pair of 'port' and 'secure': {0}, {1}", port, secure));
|
||||
throw new ArgumentException (
|
||||
String.Format (
|
||||
"Invalid pair of 'port' and 'secure': {0}, {1}", port, secure));
|
||||
|
||||
_address = address;
|
||||
_port = port;
|
||||
@@ -234,10 +251,12 @@ namespace WebSocketSharp.Server
|
||||
#region Public Properties
|
||||
|
||||
/// <summary>
|
||||
/// Gets the local IP address on which to listen for incoming connection attempts.
|
||||
/// Gets the local IP address on which to listen for incoming connection
|
||||
/// attempts.
|
||||
/// </summary>
|
||||
/// <value>
|
||||
/// A <see cref="System.Net.IPAddress"/> that represents the local IP address.
|
||||
/// A <see cref="System.Net.IPAddress"/> that represents the local IP
|
||||
/// address.
|
||||
/// </value>
|
||||
public System.Net.IPAddress Address {
|
||||
get {
|
||||
@@ -246,7 +265,29 @@ namespace WebSocketSharp.Server
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the certificate used to authenticate the server on the secure connection.
|
||||
/// Gets or sets the scheme used to authenticate the clients.
|
||||
/// </summary>
|
||||
/// <value>
|
||||
/// One of the <see cref="WebSocketSharp.Net.AuthenticationSchemes"/> values
|
||||
/// that indicates the scheme used to authenticate the clients. The default
|
||||
/// value is <see cref="WebSocketSharp.Net.AuthenticationSchemes.Anonymous"/>.
|
||||
/// </value>
|
||||
public AuthenticationSchemes AuthenticationSchemes {
|
||||
get {
|
||||
return _authSchemes;
|
||||
}
|
||||
|
||||
set {
|
||||
if (!canSet ("AuthenticationSchemes"))
|
||||
return;
|
||||
|
||||
_authSchemes = value;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the certificate used to authenticate the server on the
|
||||
/// secure connection.
|
||||
/// </summary>
|
||||
/// <value>
|
||||
/// A <see cref="X509Certificate2"/> used to authenticate the server.
|
||||
@@ -257,13 +298,8 @@ namespace WebSocketSharp.Server
|
||||
}
|
||||
|
||||
set {
|
||||
if (_state == ServerState.START || _state == ServerState.SHUTDOWN)
|
||||
{
|
||||
_logger.Error (
|
||||
"The value of Certificate property cannot be changed because the server has already been started.");
|
||||
|
||||
if (!canSet ("Certificate"))
|
||||
return;
|
||||
}
|
||||
|
||||
_cert = value;
|
||||
}
|
||||
@@ -285,7 +321,8 @@ namespace WebSocketSharp.Server
|
||||
/// Gets a value indicating whether the server provides secure connection.
|
||||
/// </summary>
|
||||
/// <value>
|
||||
/// <c>true</c> if the server provides secure connection; otherwise, <c>false</c>.
|
||||
/// <c>true</c> if the server provides secure connection; otherwise,
|
||||
/// <c>false</c>.
|
||||
/// </value>
|
||||
public bool IsSecure {
|
||||
get {
|
||||
@@ -294,11 +331,12 @@ namespace WebSocketSharp.Server
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets a value indicating whether the server cleans up the inactive sessions periodically.
|
||||
/// Gets or sets a value indicating whether the server cleans up the inactive
|
||||
/// sessions periodically.
|
||||
/// </summary>
|
||||
/// <value>
|
||||
/// <c>true</c> if the server cleans up the inactive sessions every 60 seconds;
|
||||
/// otherwise, <c>false</c>. The default value is <c>true</c>.
|
||||
/// <c>true</c> if the server cleans up the inactive sessions every 60
|
||||
/// seconds; otherwise, <c>false</c>. The default value is <c>true</c>.
|
||||
/// </value>
|
||||
public bool KeepClean {
|
||||
get {
|
||||
@@ -314,9 +352,9 @@ namespace WebSocketSharp.Server
|
||||
/// Gets the logging functions.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// The default logging level is the <see cref="LogLevel.ERROR"/>.
|
||||
/// If you want to change the current logging level, you set the <c>Log.Level</c> property
|
||||
/// to one of the <see cref="LogLevel"/> values which you want.
|
||||
/// The default logging level is the <see cref="LogLevel.ERROR"/>. If you
|
||||
/// change the current logging level, you set the <c>Log.Level</c> property
|
||||
/// to any of the <see cref="LogLevel"/> values.
|
||||
/// </remarks>
|
||||
/// <value>
|
||||
/// A <see cref="Logger"/> that provides the logging functions.
|
||||
@@ -340,10 +378,55 @@ namespace WebSocketSharp.Server
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the functions for the WebSocket services provided by the server.
|
||||
/// Gets or sets the name of the realm associated with the
|
||||
/// <see cref="WebSocketServer"/>.
|
||||
/// </summary>
|
||||
/// <value>
|
||||
/// A <see cref="WebSocketServiceHostManager"/> that manages the WebSocket services.
|
||||
/// A <see cref="string"/> that contains the name of the realm.
|
||||
/// The default value is <c>SECRET AREA</c>.
|
||||
/// </value>
|
||||
public string Realm {
|
||||
get {
|
||||
return _realm ?? (_realm = "SECRET AREA");
|
||||
}
|
||||
|
||||
set {
|
||||
if (!canSet ("Realm"))
|
||||
return;
|
||||
|
||||
_realm = value;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the delegate called to find the credentials for an identity
|
||||
/// used to authenticate a client.
|
||||
/// </summary>
|
||||
/// <value>
|
||||
/// A Func<<see cref="IIdentity"/>, <see cref="NetworkCredential"/>>
|
||||
/// delegate that references the method(s) used to find the credentials. The
|
||||
/// default value is a function that only returns <see langword="null"/>.
|
||||
/// </value>
|
||||
public Func<IIdentity, NetworkCredential> UserCredentialsFinder {
|
||||
get {
|
||||
return _credentialsFinder ?? (_credentialsFinder = identity => null);
|
||||
}
|
||||
|
||||
set {
|
||||
if (!canSet ("UserCredentialsFinder"))
|
||||
return;
|
||||
|
||||
_credentialsFinder = value;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the functions for the WebSocket services provided by the
|
||||
/// <see cref="WebSocketServer"/>.
|
||||
/// </summary>
|
||||
/// <value>
|
||||
/// A <see cref="WebSocketServiceHostManager"/> that manages the WebSocket
|
||||
/// services.
|
||||
/// </value>
|
||||
public WebSocketServiceHostManager WebSocketServices {
|
||||
get {
|
||||
@@ -357,8 +440,7 @@ namespace WebSocketSharp.Server
|
||||
|
||||
private void abort ()
|
||||
{
|
||||
lock (_sync)
|
||||
{
|
||||
lock (_sync) {
|
||||
if (!IsListening)
|
||||
return;
|
||||
|
||||
@@ -367,30 +449,103 @@ namespace WebSocketSharp.Server
|
||||
|
||||
_listener.Stop ();
|
||||
_serviceHosts.Stop (
|
||||
((ushort) CloseStatusCode.SERVER_ERROR).ToByteArrayInternally (ByteOrder.BIG), true);
|
||||
((ushort) CloseStatusCode.SERVER_ERROR).ToByteArrayInternally (ByteOrder.BIG),
|
||||
true);
|
||||
|
||||
_state = ServerState.STOP;
|
||||
}
|
||||
|
||||
private void acceptRequestAsync (TcpClient client)
|
||||
{
|
||||
ThreadPool.QueueUserWorkItem (
|
||||
state => {
|
||||
try {
|
||||
var context = client.GetWebSocketContext (_cert, _secure, _logger);
|
||||
if (_authSchemes != AuthenticationSchemes.Anonymous &&
|
||||
!authenticateRequest (_authSchemes, context))
|
||||
return;
|
||||
|
||||
acceptWebSocket (context);
|
||||
}
|
||||
catch (Exception ex) {
|
||||
_logger.Fatal (ex.ToString ());
|
||||
client.Close ();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
private void acceptWebSocket (TcpListenerWebSocketContext context)
|
||||
{
|
||||
var websocket = context.WebSocket;
|
||||
websocket.Log = _logger;
|
||||
|
||||
var path = context.Path;
|
||||
|
||||
WebSocketServiceHost host;
|
||||
if (path == null || !_serviceHosts.TryGetServiceHostInternally (path, out host))
|
||||
{
|
||||
websocket.Close (HttpStatusCode.NotImplemented);
|
||||
if (path == null ||
|
||||
!_serviceHosts.TryGetServiceHostInternally (path, out host)) {
|
||||
context.Close (HttpStatusCode.NotImplemented);
|
||||
return;
|
||||
}
|
||||
|
||||
if (_uri.IsAbsoluteUri)
|
||||
websocket.Url = new Uri (_uri, path);
|
||||
|
||||
host.StartSession (context);
|
||||
}
|
||||
|
||||
private bool authenticateRequest (
|
||||
AuthenticationSchemes authScheme, TcpListenerWebSocketContext context)
|
||||
{
|
||||
var challenge = authScheme == AuthenticationSchemes.Basic
|
||||
? HttpUtility.CreateBasicAuthChallenge (Realm)
|
||||
: authScheme == AuthenticationSchemes.Digest
|
||||
? HttpUtility.CreateDigestAuthChallenge (Realm)
|
||||
: null;
|
||||
|
||||
if (challenge == null) {
|
||||
context.Close (HttpStatusCode.Forbidden);
|
||||
return false;
|
||||
}
|
||||
|
||||
var retry = -1;
|
||||
var expected = authScheme.ToString ();
|
||||
var realm = Realm;
|
||||
var credentialsFinder = UserCredentialsFinder;
|
||||
Func<bool> auth = null;
|
||||
auth = () => {
|
||||
retry++;
|
||||
if (retry > 99) {
|
||||
context.Close (HttpStatusCode.Forbidden);
|
||||
return false;
|
||||
}
|
||||
|
||||
var header = context.Headers ["Authorization"];
|
||||
if (header == null ||
|
||||
!header.StartsWith (expected, StringComparison.OrdinalIgnoreCase)) {
|
||||
context.SendAuthChallenge (challenge);
|
||||
return auth ();
|
||||
}
|
||||
|
||||
context.SetUser (authScheme, realm, credentialsFinder);
|
||||
if (context.IsAuthenticated)
|
||||
return true;
|
||||
|
||||
context.SendAuthChallenge (challenge);
|
||||
return auth ();
|
||||
};
|
||||
|
||||
return auth ();
|
||||
}
|
||||
|
||||
private bool canSet (string property)
|
||||
{
|
||||
if (_state == ServerState.START || _state == ServerState.SHUTDOWN) {
|
||||
_logger.Error (
|
||||
String.Format (
|
||||
"The '{0}' property cannot set a value because the server has already been started.",
|
||||
property));
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
private string checkIfCertExists ()
|
||||
{
|
||||
return _secure && _cert == null
|
||||
@@ -400,6 +555,7 @@ namespace WebSocketSharp.Server
|
||||
|
||||
private void init ()
|
||||
{
|
||||
_authSchemes = AuthenticationSchemes.Anonymous;
|
||||
_listener = new TcpListener (_address, _port);
|
||||
_logger = new Logger ();
|
||||
_serviceHosts = new WebSocketServiceHostManager (_logger);
|
||||
@@ -407,32 +563,17 @@ namespace WebSocketSharp.Server
|
||||
_sync = new object ();
|
||||
}
|
||||
|
||||
private void processRequestAsync (TcpClient client)
|
||||
{
|
||||
WaitCallback callback = state =>
|
||||
{
|
||||
try {
|
||||
acceptWebSocket (client.GetWebSocketContext (_secure, _cert));
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.Fatal (ex.ToString ());
|
||||
client.Close ();
|
||||
}
|
||||
};
|
||||
|
||||
ThreadPool.QueueUserWorkItem (callback);
|
||||
}
|
||||
|
||||
private void receiveRequest ()
|
||||
{
|
||||
while (true)
|
||||
{
|
||||
while (true) {
|
||||
try {
|
||||
processRequestAsync (_listener.AcceptTcpClient ());
|
||||
acceptRequestAsync (_listener.AcceptTcpClient ());
|
||||
}
|
||||
catch (SocketException ex) {
|
||||
_logger.Warn (String.Format ("Receiving has been stopped.\nreason: {0}.", ex.Message));
|
||||
_logger.Warn (
|
||||
String.Format (
|
||||
"Receiving has been stopped.\nreason: {0}.", ex.Message));
|
||||
|
||||
break;
|
||||
}
|
||||
catch (Exception ex) {
|
||||
@@ -445,7 +586,7 @@ namespace WebSocketSharp.Server
|
||||
abort ();
|
||||
}
|
||||
|
||||
private void startReceiveRequestThread ()
|
||||
private void startReceiving ()
|
||||
{
|
||||
_receiveRequestThread = new Thread (new ThreadStart (receiveRequest));
|
||||
_receiveRequestThread.IsBackground = true;
|
||||
@@ -463,8 +604,7 @@ namespace WebSocketSharp.Server
|
||||
if (!uriString.TryCreateWebSocketUri (out result, out message))
|
||||
return false;
|
||||
|
||||
if (result.PathAndQuery != "/")
|
||||
{
|
||||
if (result.PathAndQuery != "/") {
|
||||
result = null;
|
||||
message = "Must not contain the path or query component: " + uriString;
|
||||
|
||||
@@ -479,18 +619,21 @@ namespace WebSocketSharp.Server
|
||||
#region Public Methods
|
||||
|
||||
/// <summary>
|
||||
/// Adds the specified typed WebSocket service with the specified <paramref name="servicePath"/>.
|
||||
/// Adds the specified typed WebSocket service with the specified
|
||||
/// <paramref name="servicePath"/>.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// This method converts <paramref name="servicePath"/> to URL-decoded string and
|
||||
/// removes <c>'/'</c> from tail end of <paramref name="servicePath"/>.
|
||||
/// This method converts <paramref name="servicePath"/> to URL-decoded string
|
||||
/// and removes <c>'/'</c> from tail end of <paramref name="servicePath"/>.
|
||||
/// </remarks>
|
||||
/// <param name="servicePath">
|
||||
/// A <see cref="string"/> that contains an absolute path to the WebSocket service.
|
||||
/// A <see cref="string"/> that contains an absolute path to the WebSocket
|
||||
/// service.
|
||||
/// </param>
|
||||
/// <typeparam name="TWithNew">
|
||||
/// The type of the WebSocket service. The TWithNew must inherit the <see cref="WebSocketService"/>
|
||||
/// class and must have a public parameterless constructor.
|
||||
/// The type of the WebSocket service. The TWithNew must inherit the
|
||||
/// <see cref="WebSocketService"/> class and must have a public parameterless
|
||||
/// constructor.
|
||||
/// </typeparam>
|
||||
public void AddWebSocketService<TWithNew> (string servicePath)
|
||||
where TWithNew : WebSocketService, new ()
|
||||
@@ -499,42 +642,50 @@ namespace WebSocketSharp.Server
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Adds the specified typed WebSocket service with the specified <paramref name="servicePath"/> and
|
||||
/// <paramref name="serviceConstructor"/>.
|
||||
/// Adds the specified typed WebSocket service with the specified
|
||||
/// <paramref name="servicePath"/> and <paramref name="serviceConstructor"/>.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// <para>
|
||||
/// This method converts <paramref name="servicePath"/> to URL-decoded string and
|
||||
/// removes <c>'/'</c> from tail end of <paramref name="servicePath"/>.
|
||||
/// This method converts <paramref name="servicePath"/> to URL-decoded
|
||||
/// string and removes <c>'/'</c> from tail end of
|
||||
/// <paramref name="servicePath"/>.
|
||||
/// </para>
|
||||
/// <para>
|
||||
/// <paramref name="serviceConstructor"/> returns a initialized specified typed WebSocket service
|
||||
/// instance.
|
||||
/// <paramref name="serviceConstructor"/> returns a initialized specified
|
||||
/// typed WebSocket service instance.
|
||||
/// </para>
|
||||
/// </remarks>
|
||||
/// <param name="servicePath">
|
||||
/// A <see cref="string"/> that contains an absolute path to the WebSocket service.
|
||||
/// A <see cref="string"/> that contains an absolute path to the WebSocket
|
||||
/// service.
|
||||
/// </param>
|
||||
/// <param name="serviceConstructor">
|
||||
/// A Func<T> delegate that references the method used to initialize a new WebSocket service
|
||||
/// instance (a new WebSocket session).
|
||||
/// A Func<T> delegate that references the method used to initialize
|
||||
/// a new WebSocket service instance (a new WebSocket session).
|
||||
/// </param>
|
||||
/// <typeparam name="T">
|
||||
/// The type of the WebSocket service. The T must inherit the <see cref="WebSocketService"/> class.
|
||||
/// The type of the WebSocket service. The T must inherit the
|
||||
/// <see cref="WebSocketService"/> class.
|
||||
/// </typeparam>
|
||||
public void AddWebSocketService<T> (string servicePath, Func<T> serviceConstructor)
|
||||
where T : WebSocketService
|
||||
{
|
||||
var msg = servicePath.CheckIfValidServicePath () ??
|
||||
(serviceConstructor == null ? "'serviceConstructor' must not be null." : null);
|
||||
(serviceConstructor == null
|
||||
? "'serviceConstructor' must not be null."
|
||||
: null);
|
||||
|
||||
if (msg != null) {
|
||||
_logger.Error (
|
||||
String.Format ("{0}\nservice path: {1}", msg, servicePath ?? ""));
|
||||
|
||||
if (msg != null)
|
||||
{
|
||||
_logger.Error (String.Format ("{0}\nservice path: {1}", msg, servicePath ?? ""));
|
||||
return;
|
||||
}
|
||||
|
||||
var host = new WebSocketServiceHost<T> (servicePath, serviceConstructor, _logger);
|
||||
var host = new WebSocketServiceHost<T> (
|
||||
servicePath, serviceConstructor, _logger);
|
||||
|
||||
if (!KeepClean)
|
||||
host.KeepClean = false;
|
||||
|
||||
@@ -542,24 +693,28 @@ namespace WebSocketSharp.Server
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Removes the WebSocket service with the specified <paramref name="servicePath"/>.
|
||||
/// Removes the WebSocket service with the specified
|
||||
/// <paramref name="servicePath"/>.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// This method converts <paramref name="servicePath"/> to URL-decoded string and
|
||||
/// removes <c>'/'</c> from tail end of <paramref name="servicePath"/>.
|
||||
/// This method converts <paramref name="servicePath"/> to URL-decoded string
|
||||
/// and removes <c>'/'</c> from tail end of <paramref name="servicePath"/>.
|
||||
/// </remarks>
|
||||
/// <returns>
|
||||
/// <c>true</c> if the WebSocket service is successfully found and removed; otherwise, <c>false</c>.
|
||||
/// <c>true</c> if the WebSocket service is successfully found and removed;
|
||||
/// otherwise, <c>false</c>.
|
||||
/// </returns>
|
||||
/// <param name="servicePath">
|
||||
/// A <see cref="string"/> that contains an absolute path to the WebSocket service to find.
|
||||
/// A <see cref="string"/> that contains an absolute path to the WebSocket
|
||||
/// service to find.
|
||||
/// </param>
|
||||
public bool RemoveWebSocketService (string servicePath)
|
||||
{
|
||||
var msg = servicePath.CheckIfValidServicePath ();
|
||||
if (msg != null)
|
||||
{
|
||||
_logger.Error (String.Format ("{0}\nservice path: {1}", msg, servicePath ?? ""));
|
||||
if (msg != null) {
|
||||
_logger.Error (
|
||||
String.Format ("{0}\nservice path: {1}", msg, servicePath));
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
@@ -567,22 +722,23 @@ namespace WebSocketSharp.Server
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Starts to receive the WebSocket connection requests.
|
||||
/// Starts receiving the WebSocket connection requests.
|
||||
/// </summary>
|
||||
public void Start ()
|
||||
{
|
||||
lock (_sync)
|
||||
{
|
||||
lock (_sync) {
|
||||
var msg = _state.CheckIfStopped () ?? checkIfCertExists ();
|
||||
if (msg != null)
|
||||
{
|
||||
_logger.Error (String.Format ("{0}\nstate: {1}\nsecure: {2}", msg, _state, _secure));
|
||||
if (msg != null) {
|
||||
_logger.Error (
|
||||
String.Format (
|
||||
"{0}\nstate: {1}\nsecure: {2}", msg, _state, _secure));
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
_serviceHosts.Start ();
|
||||
_listener.Start ();
|
||||
startReceiveRequestThread ();
|
||||
startReceiving ();
|
||||
|
||||
_state = ServerState.START;
|
||||
}
|
||||
@@ -593,11 +749,9 @@ namespace WebSocketSharp.Server
|
||||
/// </summary>
|
||||
public void Stop ()
|
||||
{
|
||||
lock (_sync)
|
||||
{
|
||||
lock (_sync) {
|
||||
var msg = _state.CheckIfStarted ();
|
||||
if (msg != null)
|
||||
{
|
||||
if (msg != null) {
|
||||
_logger.Error (String.Format ("{0}\nstate: {1}", msg, _state));
|
||||
return;
|
||||
}
|
||||
@@ -606,17 +760,18 @@ namespace WebSocketSharp.Server
|
||||
}
|
||||
|
||||
stopListener (5000);
|
||||
_serviceHosts.Stop (new byte []{}, true);
|
||||
_serviceHosts.Stop (new byte [0], true);
|
||||
|
||||
_state = ServerState.STOP;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Stops receiving the WebSocket connection requests with the specified <see cref="ushort"/> and
|
||||
/// <see cref="string"/>.
|
||||
/// Stops receiving the WebSocket connection requests with the specified
|
||||
/// <see cref="ushort"/> and <see cref="string"/>.
|
||||
/// </summary>
|
||||
/// <param name="code">
|
||||
/// A <see cref="ushort"/> that contains a status code indicating the reason for stop.
|
||||
/// A <see cref="ushort"/> that contains a status code indicating the reason
|
||||
/// for stop.
|
||||
/// </param>
|
||||
/// <param name="reason">
|
||||
/// A <see cref="string"/> that contains the reason for stop.
|
||||
@@ -624,16 +779,15 @@ namespace WebSocketSharp.Server
|
||||
public void Stop (ushort code, string reason)
|
||||
{
|
||||
byte [] data = null;
|
||||
lock (_sync)
|
||||
{
|
||||
lock (_sync) {
|
||||
var msg = _state.CheckIfStarted () ??
|
||||
code.CheckIfValidCloseStatusCode () ??
|
||||
(data = code.Append (reason)).CheckIfValidCloseData ();
|
||||
|
||||
if (msg != null)
|
||||
{
|
||||
_logger.Error (String.Format (
|
||||
"{0}\nstate: {1}\ncode: {2}\nreason: {3}", msg, _state, code, reason));
|
||||
if (msg != null) {
|
||||
_logger.Error (
|
||||
String.Format (
|
||||
"{0}\nstate: {1}\ncode: {2}\nreason: {3}", msg, _state, code, reason));
|
||||
|
||||
return;
|
||||
}
|
||||
@@ -648,12 +802,12 @@ namespace WebSocketSharp.Server
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Stops receiving the WebSocket connection requests with the specified <see cref="CloseStatusCode"/>
|
||||
/// and <see cref="string"/>.
|
||||
/// Stops receiving the WebSocket connection requests with the specified
|
||||
/// <see cref="CloseStatusCode"/> and <see cref="string"/>.
|
||||
/// </summary>
|
||||
/// <param name="code">
|
||||
/// One of the <see cref="CloseStatusCode"/> values that represent the status codes indicating
|
||||
/// the reasons for stop.
|
||||
/// One of the <see cref="CloseStatusCode"/> values that represent the status
|
||||
/// codes indicating the reasons for stop.
|
||||
/// </param>
|
||||
/// <param name="reason">
|
||||
/// A <see cref="string"/> that contains the reason for stop.
|
||||
@@ -661,14 +815,14 @@ namespace WebSocketSharp.Server
|
||||
public void Stop (CloseStatusCode code, string reason)
|
||||
{
|
||||
byte [] data = null;
|
||||
lock (_sync)
|
||||
{
|
||||
lock (_sync) {
|
||||
var msg = _state.CheckIfStarted () ??
|
||||
(data = ((ushort) code).Append (reason)).CheckIfValidCloseData ();
|
||||
|
||||
if (msg != null)
|
||||
{
|
||||
_logger.Error (String.Format ("{0}\nstate: {1}\nreason: {2}", msg, _state, reason));
|
||||
if (msg != null) {
|
||||
_logger.Error (
|
||||
String.Format ("{0}\nstate: {1}\nreason: {2}", msg, _state, reason));
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
|
Reference in New Issue
Block a user