jellyfin-server/Jellyfin.Server/SocketSharp/WebSocketSharpListener.cs

261 lines
8.3 KiB
C#
Raw Normal View History

using System;
2014-07-19 01:28:40 +00:00
using System.Collections.Generic;
2017-09-03 02:42:13 +00:00
using System.Security.Cryptography.X509Certificates;
2017-05-22 04:54:02 +00:00
using System.Threading;
2014-07-19 01:28:40 +00:00
using System.Threading.Tasks;
2019-01-01 15:27:11 +00:00
using Emby.Server.Implementations.HttpServer;
using Emby.Server.Implementations.Net;
2016-11-08 18:44:23 +00:00
using MediaBrowser.Common.Net;
2019-01-01 15:27:11 +00:00
using MediaBrowser.Controller.Net;
2016-11-08 18:44:23 +00:00
using MediaBrowser.Model.Cryptography;
using MediaBrowser.Model.IO;
2016-11-08 18:44:23 +00:00
using MediaBrowser.Model.Net;
2016-10-25 19:02:04 +00:00
using MediaBrowser.Model.Services;
2017-05-09 18:51:26 +00:00
using MediaBrowser.Model.System;
2019-01-01 15:27:11 +00:00
using Microsoft.Extensions.Logging;
using SocketHttpListener.Net;
2014-07-19 01:28:40 +00:00
2019-01-01 15:27:11 +00:00
namespace Jellyfin.SocketSharp
2014-07-19 01:28:40 +00:00
{
public class WebSocketSharpListener : IHttpListener
{
2014-09-09 01:15:31 +00:00
private HttpListener _listener;
2014-07-19 01:28:40 +00:00
private readonly ILogger _logger;
2017-09-03 02:42:13 +00:00
private readonly X509Certificate _certificate;
2018-09-12 17:26:21 +00:00
private readonly IStreamHelper _streamHelper;
2016-11-08 18:44:23 +00:00
private readonly INetworkManager _networkManager;
private readonly ISocketFactory _socketFactory;
private readonly ICryptoProvider _cryptoProvider;
2017-03-12 19:27:26 +00:00
private readonly IFileSystem _fileSystem;
2016-11-08 19:50:39 +00:00
private readonly bool _enableDualMode;
2017-05-09 18:51:26 +00:00
private readonly IEnvironmentInfo _environment;
2016-11-08 18:44:23 +00:00
2017-05-26 06:48:54 +00:00
private CancellationTokenSource _disposeCancellationTokenSource = new CancellationTokenSource();
private CancellationToken _disposeCancellationToken;
public WebSocketSharpListener(ILogger logger, X509Certificate certificate, IStreamHelper streamHelper,
INetworkManager networkManager, ISocketFactory socketFactory, ICryptoProvider cryptoProvider,
bool enableDualMode, IFileSystem fileSystem, IEnvironmentInfo environment)
2014-07-19 01:28:40 +00:00
{
_logger = logger;
2016-11-08 18:44:23 +00:00
_certificate = certificate;
2018-09-12 17:26:21 +00:00
_streamHelper = streamHelper;
2016-11-08 18:44:23 +00:00
_networkManager = networkManager;
_socketFactory = socketFactory;
_cryptoProvider = cryptoProvider;
2016-11-08 19:50:39 +00:00
_enableDualMode = enableDualMode;
2017-03-12 19:27:26 +00:00
_fileSystem = fileSystem;
2017-05-09 18:51:26 +00:00
_environment = environment;
2017-05-26 06:48:54 +00:00
_disposeCancellationToken = _disposeCancellationTokenSource.Token;
2014-07-19 01:28:40 +00:00
}
2018-09-12 17:26:21 +00:00
public Func<Exception, IRequest, bool, bool, Task> ErrorHandler { get; set; }
2017-09-03 07:28:58 +00:00
public Func<IHttpRequest, string, string, string, CancellationToken, Task> RequestHandler { get; set; }
2014-07-19 01:28:40 +00:00
2015-03-08 19:48:30 +00:00
public Action<WebSocketConnectingEventArgs> WebSocketConnecting { get; set; }
public Action<WebSocketConnectEventArgs> WebSocketConnected { get; set; }
2014-07-19 01:28:40 +00:00
public void Start(IEnumerable<string> urlPrefixes)
{
2014-08-14 13:24:30 +00:00
if (_listener == null)
_listener = new HttpListener(_logger, _cryptoProvider, _socketFactory, _networkManager, _streamHelper, _fileSystem, _environment);
2016-11-08 18:44:23 +00:00
2016-11-08 19:50:39 +00:00
_listener.EnableDualMode = _enableDualMode;
2016-11-08 18:44:23 +00:00
if (_certificate != null)
{
_listener.LoadCert(_certificate);
}
2014-07-19 01:28:40 +00:00
2014-08-14 13:24:30 +00:00
foreach (var prefix in urlPrefixes)
{
_logger.LogInformation("Adding HttpListener prefix " + prefix);
2014-08-14 13:24:30 +00:00
_listener.Prefixes.Add(prefix);
}
2014-12-30 16:36:49 +00:00
_listener.OnContext = ProcessContext;
2014-07-19 01:28:40 +00:00
2014-12-30 16:36:49 +00:00
_listener.Start();
2014-08-14 13:24:30 +00:00
}
2014-12-30 16:36:49 +00:00
private void ProcessContext(HttpListenerContext context)
2014-08-14 13:24:30 +00:00
{
var _ = Task.Run(async () => await InitTask(context, _disposeCancellationToken));
2014-07-19 01:28:40 +00:00
}
private static void LogRequest(ILogger logger, HttpListenerRequest request)
2018-09-12 17:26:21 +00:00
{
var url = request.Url.ToString();
logger.LogInformation("{0} {1}. UserAgent: {2}",
request.IsWebSocketRequest ? "WS" : "HTTP " + request.HttpMethod, url, request.UserAgent ?? string.Empty);
2018-09-12 17:26:21 +00:00
}
2017-05-22 04:54:02 +00:00
private Task InitTask(HttpListenerContext context, CancellationToken cancellationToken)
2014-07-19 01:28:40 +00:00
{
2016-11-08 18:44:23 +00:00
IHttpRequest httpReq = null;
var request = context.Request;
2014-07-19 01:28:40 +00:00
try
{
2016-11-08 18:44:23 +00:00
if (request.IsWebSocketRequest)
{
2018-09-12 17:26:21 +00:00
LogRequest(_logger, request);
2014-07-19 01:28:40 +00:00
2018-09-12 17:26:21 +00:00
return ProcessWebSocketRequest(context);
2016-11-08 18:44:23 +00:00
}
httpReq = GetRequest(context);
2014-07-19 01:28:40 +00:00
}
catch (Exception ex)
{
2018-12-20 12:11:26 +00:00
_logger.LogError(ex, "Error processing request");
2016-01-23 03:10:21 +00:00
2016-11-08 18:44:23 +00:00
httpReq = httpReq ?? GetRequest(context);
2018-09-12 17:26:21 +00:00
return ErrorHandler(ex, httpReq, true, true);
2014-07-19 01:28:40 +00:00
}
2017-09-03 07:28:58 +00:00
var uri = request.Url;
return RequestHandler(httpReq, uri.OriginalString, uri.Host, uri.LocalPath, cancellationToken);
2014-07-19 01:28:40 +00:00
}
2018-09-12 17:26:21 +00:00
private async Task ProcessWebSocketRequest(HttpListenerContext ctx)
2014-07-19 01:28:40 +00:00
{
try
{
2015-03-08 19:48:30 +00:00
var endpoint = ctx.Request.RemoteEndPoint.ToString();
var url = ctx.Request.RawUrl;
2018-09-12 17:26:21 +00:00
var queryString = ctx.Request.QueryString;
2015-03-08 19:48:30 +00:00
var connectingArgs = new WebSocketConnectingEventArgs
{
Url = url,
2018-09-12 17:26:21 +00:00
QueryString = queryString,
2015-03-08 19:48:30 +00:00
Endpoint = endpoint
};
if (WebSocketConnecting != null)
{
WebSocketConnecting(connectingArgs);
}
2014-07-19 01:28:40 +00:00
2015-03-08 19:48:30 +00:00
if (connectingArgs.AllowConnection)
2014-07-19 01:28:40 +00:00
{
_logger.LogDebug("Web socket connection allowed");
2015-03-08 19:48:30 +00:00
2018-09-12 17:26:21 +00:00
var webSocketContext = await ctx.AcceptWebSocketAsync(null).ConfigureAwait(false);
2015-03-08 19:48:30 +00:00
if (WebSocketConnected != null)
2014-07-19 01:28:40 +00:00
{
2018-09-12 17:26:21 +00:00
var socket = new SharpWebSocket(webSocketContext.WebSocket, _logger);
2015-03-08 19:48:30 +00:00
WebSocketConnected(new WebSocketConnectEventArgs
{
Url = url,
2018-09-12 17:26:21 +00:00
QueryString = queryString,
WebSocket = socket,
2015-03-08 19:48:30 +00:00
Endpoint = endpoint
});
2018-09-12 17:26:21 +00:00
await ReceiveWebSocket(ctx, socket).ConfigureAwait(false);
2015-03-08 19:48:30 +00:00
}
}
else
{
_logger.LogWarning("Web socket connection not allowed");
2015-03-09 00:04:06 +00:00
ctx.Response.StatusCode = 401;
2015-03-08 19:48:30 +00:00
ctx.Response.Close();
2014-07-19 01:28:40 +00:00
}
}
catch (Exception ex)
{
2018-12-20 12:11:26 +00:00
_logger.LogError(ex, "AcceptWebSocketAsync error");
2014-07-19 01:28:40 +00:00
ctx.Response.StatusCode = 500;
ctx.Response.Close();
}
}
2018-09-12 17:26:21 +00:00
private async Task ReceiveWebSocket(HttpListenerContext ctx, SharpWebSocket socket)
{
try
{
await socket.StartReceive().ConfigureAwait(false);
}
finally
{
TryClose(ctx, 200);
}
}
private void TryClose(HttpListenerContext ctx, int statusCode)
{
try
{
ctx.Response.StatusCode = statusCode;
2018-09-12 17:26:21 +00:00
ctx.Response.Close();
}
catch (ObjectDisposedException)
{
//TODO Investigate and properly fix.
2018-09-12 17:26:21 +00:00
}
catch (Exception ex)
{
2018-12-20 12:11:26 +00:00
_logger.LogError(ex, "Error closing web socket response");
2018-09-12 17:26:21 +00:00
}
}
2014-07-19 01:28:40 +00:00
private IHttpRequest GetRequest(HttpListenerContext httpContext)
{
2018-09-12 17:26:21 +00:00
var urlSegments = httpContext.Request.Url.Segments;
var operationName = urlSegments[urlSegments.Length - 1];
2017-09-03 02:46:21 +00:00
2018-09-12 17:26:21 +00:00
var req = new WebSocketSharpRequest(httpContext, operationName, _logger);
2017-09-03 02:46:21 +00:00
return req;
2014-07-19 01:28:40 +00:00
}
2017-09-03 07:28:58 +00:00
public Task Stop()
2014-07-19 01:28:40 +00:00
{
2017-05-26 06:48:54 +00:00
_disposeCancellationTokenSource.Cancel();
2014-08-14 13:24:30 +00:00
if (_listener != null)
{
_listener.Close();
}
2017-09-03 07:28:58 +00:00
2018-09-12 17:26:21 +00:00
return Task.CompletedTask;
2014-07-19 01:28:40 +00:00
}
public void Dispose()
{
2014-08-14 13:24:30 +00:00
Dispose(true);
}
private bool _disposed;
private readonly object _disposeLock = new object();
protected virtual void Dispose(bool disposing)
{
if (_disposed) return;
2014-07-19 01:28:40 +00:00
lock (_disposeLock)
{
2014-08-14 13:24:30 +00:00
if (_disposed) return;
if (disposing)
2014-07-19 01:28:40 +00:00
{
2014-08-14 13:24:30 +00:00
Stop();
2014-07-19 01:28:40 +00:00
}
2014-08-14 13:24:30 +00:00
//release unmanaged resources here...
_disposed = true;
2014-07-19 01:28:40 +00:00
}
}
}
}