jellyfin/MediaBrowser.Server.Mono/SocketSharp/WebSocketSharpListener.cs

263 lines
8.4 KiB
C#
Raw Normal View History

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