Refactored HttpServer.cs

This commit is contained in:
sta 2014-08-31 14:44:10 +09:00
parent 1a1b109508
commit e15cc63036

View File

@ -31,7 +31,7 @@
#region Contributors #region Contributors
/* /*
* Contributors: * Contributors:
* Juan Manuel Lallana <juan.manuel.lallana@gmail.com> * - Juan Manuel Lallana <juan.manuel.lallana@gmail.com>
*/ */
#endregion #endregion
@ -79,7 +79,7 @@ namespace WebSocketSharp.Server
/// An instance initialized by this constructor listens for the incoming requests on port 80. /// An instance initialized by this constructor listens for the incoming requests on port 80.
/// </remarks> /// </remarks>
public HttpServer () public HttpServer ()
: this (80) : this (80, false)
{ {
} }
@ -89,11 +89,11 @@ namespace WebSocketSharp.Server
/// </summary> /// </summary>
/// <remarks> /// <remarks>
/// <para> /// <para>
/// An instance initialized by this constructor listens for the incoming requests on /// An instance initialized by this constructor listens for the incoming requests
/// <paramref name="port"/>. /// on <paramref name="port"/>.
/// </para> /// </para>
/// <para> /// <para>
/// And if <paramref name="port"/> is 443, that instance provides a secure connection. /// If <paramref name="port"/> is 443, that instance provides a secure connection.
/// </para> /// </para>
/// </remarks> /// </remarks>
/// <param name="port"> /// <param name="port">
@ -112,30 +112,30 @@ namespace WebSocketSharp.Server
/// <paramref name="port"/> and <paramref name="secure"/>. /// <paramref name="port"/> and <paramref name="secure"/>.
/// </summary> /// </summary>
/// <remarks> /// <remarks>
/// An instance initialized by this constructor listens for the incoming requests on /// An instance initialized by this constructor listens for the incoming requests
/// <paramref name="port"/>. /// on <paramref name="port"/>.
/// </remarks> /// </remarks>
/// <param name="port"> /// <param name="port">
/// An <see cref="int"/> that represents the port number on which to listen. /// An <see cref="int"/> that represents the port number on which to listen.
/// </param> /// </param>
/// <param name="secure"> /// <param name="secure">
/// A <see cref="bool"/> that indicates providing a secure connection or not. (<c>true</c> /// A <see cref="bool"/> that indicates providing a secure connection or not.
/// indicates providing a secure connection.) /// (<c>true</c> indicates providing a secure connection.)
/// </param> /// </param>
/// <exception cref="ArgumentOutOfRangeException">
/// <paramref name="port"/> isn't between 1 and 65535.
/// </exception>
/// <exception cref="ArgumentException"> /// <exception cref="ArgumentException">
/// Pair of <paramref name="port"/> and <paramref name="secure"/> is invalid. /// Pair of <paramref name="port"/> and <paramref name="secure"/> is invalid.
/// </exception> /// </exception>
/// <exception cref="ArgumentOutOfRangeException">
/// <paramref name="port"/> isn't between 1 and 65535.
/// </exception>
public HttpServer (int port, bool secure) public HttpServer (int port, bool secure)
{ {
if (!port.IsPortNumber ()) if (!port.IsPortNumber ())
throw new ArgumentOutOfRangeException ("port", "Must be between 1 and 65535: " + port); throw new ArgumentOutOfRangeException ("port", "Not between 1 and 65535: " + port);
if ((port == 80 && secure) || (port == 443 && !secure)) if ((port == 80 && secure) || (port == 443 && !secure))
throw new ArgumentException ( throw new ArgumentException (
String.Format ("Invalid pair of 'port' and 'secure': {0}, {1}", port, secure)); String.Format ("An invalid pair of 'port' and 'secure': {0}, {1}", port, secure));
_port = port; _port = port;
_secure = secure; _secure = secure;
@ -146,8 +146,7 @@ namespace WebSocketSharp.Server
_sync = new object (); _sync = new object ();
var os = Environment.OSVersion; var os = Environment.OSVersion;
if (os.Platform != PlatformID.Unix && os.Platform != PlatformID.MacOSX) _windows = os.Platform != PlatformID.Unix && os.Platform != PlatformID.MacOSX;
_windows = true;
var prefix = String.Format ("http{0}://*:{1}/", _secure ? "s" : "", _port); var prefix = String.Format ("http{0}://*:{1}/", _secure ? "s" : "", _port);
_listener.Prefixes.Add (prefix); _listener.Prefixes.Add (prefix);
@ -161,9 +160,9 @@ namespace WebSocketSharp.Server
/// Gets or sets the scheme used to authenticate the clients. /// Gets or sets the scheme used to authenticate the clients.
/// </summary> /// </summary>
/// <value> /// <value>
/// One of the <see cref="WebSocketSharp.Net.AuthenticationSchemes"/> enum values, indicates /// One of the <see cref="WebSocketSharp.Net.AuthenticationSchemes"/> enum values,
/// the scheme used to authenticate the clients. /// indicates the scheme used to authenticate the clients. The default value is
/// The default value is <see cref="WebSocketSharp.Net.AuthenticationSchemes.Anonymous"/>. /// <see cref="WebSocketSharp.Net.AuthenticationSchemes.Anonymous"/>.
/// </value> /// </value>
public AuthenticationSchemes AuthenticationSchemes { public AuthenticationSchemes AuthenticationSchemes {
get { get {
@ -171,8 +170,11 @@ namespace WebSocketSharp.Server
} }
set { set {
if (!canSet ("AuthenticationSchemes")) var msg = _state.CheckIfStartable ();
if (msg != null) {
_logger.Error (msg);
return; return;
}
_listener.AuthenticationSchemes = value; _listener.AuthenticationSchemes = value;
} }
@ -182,7 +184,8 @@ namespace WebSocketSharp.Server
/// Gets or sets the certificate used to authenticate the server on the secure connection. /// Gets or sets the certificate used to authenticate the server on the secure connection.
/// </summary> /// </summary>
/// <value> /// <value>
/// A <see cref="X509Certificate2"/> used to authenticate the server. /// A <see cref="X509Certificate2"/> that represents the certificate used to authenticate
/// the server.
/// </value> /// </value>
public X509Certificate2 Certificate { public X509Certificate2 Certificate {
get { get {
@ -190,8 +193,11 @@ namespace WebSocketSharp.Server
} }
set { set {
if (!canSet ("Certificate")) var msg = _state.CheckIfStartable ();
if (msg != null) {
_logger.Error (msg);
return; return;
}
if (EndPointListener.CertificateExists (_port, _listener.CertificateFolderPath)) 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.");
@ -225,12 +231,12 @@ namespace WebSocketSharp.Server
} }
/// <summary> /// <summary>
/// Gets or sets a value indicating whether the server cleans up the inactive sessions in the /// Gets or sets a value indicating whether the server cleans up the inactive sessions
/// WebSocket services periodically. /// in the WebSocket services periodically.
/// </summary> /// </summary>
/// <value> /// <value>
/// <c>true</c> if the server cleans up the inactive sessions every 60 seconds; otherwise, /// <c>true</c> if the server cleans up the inactive sessions every 60 seconds;
/// <c>false</c>. The default value is <c>true</c>. /// otherwise, <c>false</c>. The default value is <c>true</c>.
/// </value> /// </value>
public bool KeepClean { public bool KeepClean {
get { get {
@ -275,8 +281,8 @@ namespace WebSocketSharp.Server
/// Gets or sets the name of the realm associated with the server. /// Gets or sets the name of the realm associated with the server.
/// </summary> /// </summary>
/// <value> /// <value>
/// A <see cref="string"/> that represents the name of the realm. The default value is /// A <see cref="string"/> that represents the name of the realm.
/// <c>SECRET AREA</c>. /// The default value is <c>"SECRET AREA"</c>.
/// </value> /// </value>
public string Realm { public string Realm {
get { get {
@ -284,8 +290,11 @@ namespace WebSocketSharp.Server
} }
set { set {
if (!canSet ("Realm")) var msg = _state.CheckIfStartable ();
if (msg != null) {
_logger.Error (msg);
return; return;
}
_listener.Realm = value; _listener.Realm = value;
} }
@ -295,19 +304,22 @@ namespace WebSocketSharp.Server
/// Gets or sets the document root path of the server. /// Gets or sets the document root path of the server.
/// </summary> /// </summary>
/// <value> /// <value>
/// A <see cref="string"/> that represents the document root path of the server. The default /// A <see cref="string"/> that represents the document root path of the server.
/// value is <c>./Public</c>. /// The default value is <c>"./Public"</c>.
/// </value> /// </value>
public string RootPath { public string RootPath {
get { get {
return _rootPath.IsNullOrEmpty () return _rootPath != null && _rootPath.Length > 0
? (_rootPath = "./Public") ? _rootPath
: _rootPath; : (_rootPath = "./Public");
} }
set { set {
if (!canSet ("RootPath")) var msg = _state.CheckIfStartable ();
if (msg != null) {
_logger.Error (msg);
return; return;
}
_rootPath = value; _rootPath = value;
} }
@ -328,8 +340,11 @@ namespace WebSocketSharp.Server
} }
set { set {
if (!canSet ("UserCredentialsFinder")) var msg = _state.CheckIfStartable ();
if (msg != null) {
_logger.Error (msg);
return; return;
}
_listener.UserCredentialsFinder = value; _listener.UserCredentialsFinder = value;
} }
@ -416,104 +431,6 @@ namespace WebSocketSharp.Server
_state = ServerState.Stop; _state = ServerState.Stop;
} }
private void acceptHttpRequest (HttpListenerContext context)
{
var args = new HttpRequestEventArgs (context);
var method = context.Request.HttpMethod;
if (method == "GET") {
if (OnGet != null) {
OnGet (this, args);
return;
}
}
else if (method == "HEAD") {
if (OnHead != null) {
OnHead (this, args);
return;
}
}
else if (method == "POST") {
if (OnPost != null) {
OnPost (this, args);
return;
}
}
else if (method == "PUT") {
if (OnPut != null) {
OnPut (this, args);
return;
}
}
else if (method == "DELETE") {
if (OnDelete != null) {
OnDelete (this, args);
return;
}
}
else if (method == "OPTIONS") {
if (OnOptions != null) {
OnOptions (this, args);
return;
}
}
else if (method == "TRACE") {
if (OnTrace != null) {
OnTrace (this, args);
return;
}
}
else if (method == "CONNECT") {
if (OnConnect != null) {
OnConnect (this, args);
return;
}
}
else if (method == "PATCH") {
if (OnPatch != null) {
OnPatch (this, args);
return;
}
}
context.Response.StatusCode = (int) 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 (null, _logger));
return;
}
acceptHttpRequest (context);
context.Response.Close ();
}
catch (Exception ex) {
_logger.Fatal (ex.ToString ());
context.Connection.Close (true);
}
});
}
private void acceptWebSocketRequest (HttpListenerWebSocketContext context)
{
WebSocketServiceHost host;
if (!_services.TryGetServiceHostInternally (context.RequestUri.AbsolutePath, out host)) {
context.Close (HttpStatusCode.NotImplemented);
return;
}
host.StartSession (context);
}
private bool authenticateRequest (AuthenticationSchemes scheme, HttpListenerContext context) private bool authenticateRequest (AuthenticationSchemes scheme, HttpListenerContext context)
{ {
if (context.Request.IsAuthenticated) if (context.Request.IsAuthenticated)
@ -531,34 +448,87 @@ namespace WebSocketSharp.Server
return false; return false;
} }
private bool canSet (string property) private string checkIfCertificateExists ()
{
if (_state == ServerState.Start || _state == ServerState.ShuttingDown) {
_logger.Error (
String.Format (
"Set operation of {0} isn't available because the server has already started.",
property));
return false;
}
return true;
}
private string checkIfCertExists ()
{ {
return _secure && return _secure &&
!EndPointListener.CertificateExists (_port, _listener.CertificateFolderPath) && !EndPointListener.CertificateExists (_port, _listener.CertificateFolderPath) &&
Certificate == null _listener.DefaultCertificate == null
? "The secure connection requires a server certificate." ? "The secure connection requires a server certificate."
: null; : null;
} }
private void processHttpRequest (HttpListenerContext context)
{
var method = context.Request.HttpMethod;
var evt = method == "GET"
? OnGet
: method == "HEAD"
? OnHead
: method == "POST"
? OnPost
: method == "PUT"
? OnPut
: method == "DELETE"
? OnDelete
: method == "OPTIONS"
? OnOptions
: method == "TRACE"
? OnTrace
: method == "CONNECT"
? OnConnect
: method == "PATCH"
? OnPatch
: null;
if (evt != null) {
evt (this, new HttpRequestEventArgs (context));
return;
}
context.Response.StatusCode = (int) HttpStatusCode.NotImplemented;
}
private void processRequestAsync (HttpListenerContext context)
{
ThreadPool.QueueUserWorkItem (
state => {
try {
var authScheme = _listener.SelectAuthenticationScheme (context);
if (authScheme != AuthenticationSchemes.Anonymous &&
!authenticateRequest (authScheme, context))
return;
if (context.Request.IsUpgradeTo ("websocket")) {
processWebSocketRequest (context.AcceptWebSocket (null, _logger));
return;
}
processHttpRequest (context);
context.Response.Close ();
}
catch (Exception ex) {
_logger.Fatal (ex.ToString ());
context.Connection.Close (true);
}
});
}
private void processWebSocketRequest (HttpListenerWebSocketContext context)
{
WebSocketServiceHost host;
if (!_services.TryGetServiceHostInternally (context.RequestUri.AbsolutePath, out host)) {
context.Close (HttpStatusCode.NotImplemented);
return;
}
host.StartSession (context);
}
private void receiveRequest () private void receiveRequest ()
{ {
while (true) { while (true) {
try { try {
acceptRequestAsync (_listener.GetContext ()); processRequestAsync (_listener.GetContext ());
} }
catch (HttpListenerException ex) { catch (HttpListenerException ex) {
_logger.Warn ("Receiving has been stopped.\nreason: " + ex.Message); _logger.Warn ("Receiving has been stopped.\nreason: " + ex.Message);
@ -602,9 +572,8 @@ namespace WebSocketSharp.Server
/// A <see cref="string"/> that represents the absolute path to the WebSocket service to add. /// A <see cref="string"/> that represents the absolute path to the WebSocket service to add.
/// </param> /// </param>
/// <typeparam name="TWithNew"> /// <typeparam name="TWithNew">
/// The type of the WebSocket service. /// The type of the WebSocket service. The TWithNew must inherit
/// The TWithNew must inherit the <see cref="WebSocketService"/> class and must have a public /// the <see cref="WebSocketService"/> class and must have a public parameterless constructor.
/// parameterless constructor.
/// </typeparam> /// </typeparam>
public void AddWebSocketService<TWithNew> (string path) public void AddWebSocketService<TWithNew> (string path)
where TWithNew : WebSocketService, new () where TWithNew : WebSocketService, new ()
@ -614,22 +583,22 @@ namespace WebSocketSharp.Server
/// <summary> /// <summary>
/// Adds the specified typed WebSocket service with the specified <paramref name="path"/> and /// Adds the specified typed WebSocket service with the specified <paramref name="path"/> and
/// <paramref name="constructor"/>. /// <paramref name="initializer"/>.
/// </summary> /// </summary>
/// <remarks> /// <remarks>
/// <para> /// <para>
/// This method converts <paramref name="path"/> to URL-decoded string and removes <c>'/'</c> /// This method converts <paramref name="path"/> to URL-decoded string and
/// from tail end of <paramref name="path"/>. /// removes <c>'/'</c> from tail end of <paramref name="path"/>.
/// </para> /// </para>
/// <para> /// <para>
/// <paramref name="constructor"/> returns a initialized specified typed /// <paramref name="initializer"/> returns an initialized specified typed
/// <see cref="WebSocketService"/> instance. /// <see cref="WebSocketService"/> instance.
/// </para> /// </para>
/// </remarks> /// </remarks>
/// <param name="path"> /// <param name="path">
/// A <see cref="string"/> that represents the absolute path to the WebSocket service to add. /// A <see cref="string"/> that represents the absolute path to the WebSocket service to add.
/// </param> /// </param>
/// <param name="constructor"> /// <param name="initializer">
/// A Func&lt;T&gt; delegate that references the method used to initialize a new specified /// A Func&lt;T&gt; delegate that references the method used to initialize a new specified
/// typed <see cref="WebSocketService"/> instance (a new <see cref="IWebSocketSession"/> /// typed <see cref="WebSocketService"/> instance (a new <see cref="IWebSocketSession"/>
/// instance). /// instance).
@ -638,18 +607,18 @@ namespace WebSocketSharp.Server
/// The type of the WebSocket service. The T must inherit the <see cref="WebSocketService"/> /// The type of the WebSocket service. The T must inherit the <see cref="WebSocketService"/>
/// class. /// class.
/// </typeparam> /// </typeparam>
public void AddWebSocketService<T> (string path, Func<T> constructor) public void AddWebSocketService<T> (string path, Func<T> initializer)
where T : WebSocketService where T : WebSocketService
{ {
var msg = path.CheckIfValidServicePath () ?? var msg = path.CheckIfValidServicePath () ??
(constructor == null ? "'constructor' must not be null." : null); (initializer == null ? "'initializer' is null." : null);
if (msg != null) { if (msg != null) {
_logger.Error (String.Format ("{0}\nservice path: {1}", msg, path)); _logger.Error (String.Format ("{0}\nservice path: {1}", msg, path));
return; return;
} }
var host = new WebSocketServiceHost<T> (path, constructor, _logger); var host = new WebSocketServiceHost<T> (path, initializer, _logger);
if (!KeepClean) if (!KeepClean)
host.KeepClean = false; host.KeepClean = false;
@ -660,13 +629,13 @@ namespace WebSocketSharp.Server
/// Gets the contents of the file with the specified <paramref name="path"/>. /// Gets the contents of the file with the specified <paramref name="path"/>.
/// </summary> /// </summary>
/// <returns> /// <returns>
/// An array of <see cref="byte"/> that receives the contents of the file if it exists; /// An array of <see cref="byte"/> that receives the contents of the file,
/// otherwise, <see langword="null"/>. /// or <see langword="null"/> if it doesn't exist.
/// </returns> /// </returns>
/// <param name="path"> /// <param name="path">
/// A <see cref="string"/> that represents the virtual path to the file to find. /// A <see cref="string"/> that represents the virtual path to the file to find.
/// </param> /// </param>
public byte [] GetFile (string path) public byte[] GetFile (string path)
{ {
var filePath = RootPath + path; var filePath = RootPath + path;
if (_windows) if (_windows)
@ -681,12 +650,12 @@ namespace WebSocketSharp.Server
/// Removes the WebSocket service with the specified <paramref name="path"/>. /// Removes the WebSocket service with the specified <paramref name="path"/>.
/// </summary> /// </summary>
/// <remarks> /// <remarks>
/// This method converts <paramref name="path"/> to URL-decoded string and removes <c>'/'</c> /// This method converts <paramref name="path"/> to URL-decoded string and
/// from tail end of <paramref name="path"/>. /// removes <c>'/'</c> from tail end of <paramref name="path"/>.
/// </remarks> /// </remarks>
/// <returns> /// <returns>
/// <c>true</c> if the WebSocket service is successfully found and removed; otherwise, /// <c>true</c> if the WebSocket service is successfully found and removed;
/// <c>false</c>. /// otherwise, <c>false</c>.
/// </returns> /// </returns>
/// <param name="path"> /// <param name="path">
/// A <see cref="string"/> that represents the absolute path to the WebSocket service to find. /// A <see cref="string"/> that represents the absolute path to the WebSocket service to find.
@ -708,7 +677,7 @@ namespace WebSocketSharp.Server
public void Start () public void Start ()
{ {
lock (_sync) { lock (_sync) {
var msg = _state.CheckIfStartable () ?? checkIfCertExists (); var msg = _state.CheckIfStartable () ?? checkIfCertificateExists ();
if (msg != null) { if (msg != null) {
_logger.Error (String.Format ("{0}\nstate: {1}\nsecure: {2}", msg, _state, _secure)); _logger.Error (String.Format ("{0}\nstate: {1}\nsecure: {2}", msg, _state, _secure));
return; return;
@ -737,7 +706,7 @@ namespace WebSocketSharp.Server
_state = ServerState.ShuttingDown; _state = ServerState.ShuttingDown;
} }
_services.Stop (new byte [0], true); _services.Stop (new byte[0], true);
stopListener (5000); stopListener (5000);
_state = ServerState.Stop; _state = ServerState.Stop;
@ -755,7 +724,7 @@ namespace WebSocketSharp.Server
/// </param> /// </param>
public void Stop (ushort code, string reason) public void Stop (ushort code, string reason)
{ {
byte [] data = null; byte[] data = null;
lock (_sync) { lock (_sync) {
var msg = _state.CheckIfStart () ?? var msg = _state.CheckIfStart () ??
code.CheckIfValidCloseStatusCode () ?? code.CheckIfValidCloseStatusCode () ??
@ -782,15 +751,15 @@ namespace WebSocketSharp.Server
/// <see cref="string"/> used to stop the WebSocket services. /// <see cref="string"/> used to stop the WebSocket services.
/// </summary> /// </summary>
/// <param name="code"> /// <param name="code">
/// One of the <see cref="CloseStatusCode"/> enum values, represents the status code indicating /// One of the <see cref="CloseStatusCode"/> enum values, represents the status code
/// the reasons for stop. /// indicating the reasons for stop.
/// </param> /// </param>
/// <param name="reason"> /// <param name="reason">
/// A <see cref="string"/> that represents the reason for stop. /// A <see cref="string"/> that represents the reason for stop.
/// </param> /// </param>
public void Stop (CloseStatusCode code, string reason) public void Stop (CloseStatusCode code, string reason)
{ {
byte [] data = null; byte[] data = null;
lock (_sync) { lock (_sync) {
var msg = _state.CheckIfStart () ?? var msg = _state.CheckIfStart () ??
(data = ((ushort) code).Append (reason)).CheckIfValidControlData ("reason"); (data = ((ushort) code).Append (reason)).CheckIfValidControlData ("reason");