jellyfin/Emby.Server.Implementations/Udp/UdpServer.cs

294 lines
9.2 KiB
C#
Raw Normal View History

using System;
2014-07-27 22:01:29 +00:00
using System.Collections.Generic;
using System.Linq;
using System.Text;
2017-02-05 20:44:08 +00:00
using System.Threading;
using System.Threading.Tasks;
using MediaBrowser.Controller;
using MediaBrowser.Model.ApiClient;
2016-11-04 18:56:47 +00:00
using MediaBrowser.Model.Events;
using MediaBrowser.Model.Net;
using MediaBrowser.Model.Serialization;
using Microsoft.Extensions.Logging;
2016-11-04 18:56:47 +00:00
namespace Emby.Server.Implementations.Udp
{
/// <summary>
/// Provides a Udp Server
/// </summary>
2013-03-27 22:13:46 +00:00
public class UdpServer : IDisposable
{
/// <summary>
2013-03-27 22:13:46 +00:00
/// The _logger
/// </summary>
2013-03-27 22:13:46 +00:00
private readonly ILogger _logger;
2013-12-07 15:52:38 +00:00
private bool _isDisposed;
2017-11-23 15:46:16 +00:00
private readonly List<Tuple<string, bool, Func<string, IpEndPointInfo, Encoding, CancellationToken, Task>>> _responders = new List<Tuple<string, bool, Func<string, IpEndPointInfo, Encoding, CancellationToken, Task>>>();
2014-07-27 22:01:29 +00:00
private readonly IServerApplicationHost _appHost;
private readonly IJsonSerializer _json;
/// <summary>
/// Initializes a new instance of the <see cref="UdpServer" /> class.
/// </summary>
2016-11-04 18:56:47 +00:00
public UdpServer(ILogger logger, IServerApplicationHost appHost, IJsonSerializer json, ISocketFactory socketFactory)
{
2013-03-27 22:13:46 +00:00
_logger = logger;
2014-07-27 22:01:29 +00:00
_appHost = appHost;
2014-07-30 03:31:35 +00:00
_json = json;
2016-11-04 18:56:47 +00:00
_socketFactory = socketFactory;
2014-07-27 22:01:29 +00:00
AddMessageResponder("who is JellyfinServer?", true, RespondToV2Message);
2016-09-03 17:16:36 +00:00
AddMessageResponder("who is EmbyServer?", true, RespondToV2Message);
AddMessageResponder("who is MediaBrowserServer_v2?", false, RespondToV2Message);
2014-07-27 22:01:29 +00:00
}
2017-11-23 15:46:16 +00:00
private void AddMessageResponder(string message, bool isSubstring, Func<string, IpEndPointInfo, Encoding, CancellationToken, Task> responder)
2014-07-27 22:01:29 +00:00
{
2017-11-23 15:46:16 +00:00
_responders.Add(new Tuple<string, bool, Func<string, IpEndPointInfo, Encoding, CancellationToken, Task>>(message, isSubstring, responder));
}
/// <summary>
/// Raises the <see cref="E:MessageReceived" /> event.
/// </summary>
2016-11-04 18:56:47 +00:00
private async void OnMessageReceived(GenericEventArgs<SocketReceiveResult> e)
{
2016-11-04 18:56:47 +00:00
var message = e.Argument;
2015-05-17 03:17:23 +00:00
var encoding = Encoding.UTF8;
2016-11-04 18:56:47 +00:00
var responder = GetResponder(message.Buffer, message.ReceivedBytes, encoding);
2015-05-17 03:17:23 +00:00
if (responder == null)
{
2016-09-03 17:16:36 +00:00
encoding = Encoding.Unicode;
2016-11-04 18:56:47 +00:00
responder = GetResponder(message.Buffer, message.ReceivedBytes, encoding);
2015-05-17 03:17:23 +00:00
}
2014-07-27 22:01:29 +00:00
if (responder != null)
{
2017-11-23 15:46:16 +00:00
var cancellationToken = CancellationToken.None;
2014-07-30 03:31:35 +00:00
try
{
2017-11-23 15:46:16 +00:00
await responder.Item2.Item3(responder.Item1, message.RemoteEndPoint, encoding, cancellationToken).ConfigureAwait(false);
}
catch (OperationCanceledException)
{
2014-07-30 03:31:35 +00:00
}
catch (Exception ex)
{
2018-12-20 12:11:26 +00:00
_logger.LogError(ex, "Error in OnMessageReceived");
2014-07-30 03:31:35 +00:00
}
2014-07-27 22:01:29 +00:00
}
}
2013-03-27 22:13:46 +00:00
2017-11-23 15:46:16 +00:00
private Tuple<string, Tuple<string, bool, Func<string, IpEndPointInfo, Encoding, CancellationToken, Task>>> GetResponder(byte[] buffer, int bytesReceived, Encoding encoding)
2016-09-03 17:16:36 +00:00
{
2016-11-04 18:56:47 +00:00
var text = encoding.GetString(buffer, 0, bytesReceived);
2016-09-03 17:16:36 +00:00
var responder = _responders.FirstOrDefault(i =>
{
if (i.Item2)
{
return text.IndexOf(i.Item1, StringComparison.OrdinalIgnoreCase) != -1;
}
return string.Equals(i.Item1, text, StringComparison.OrdinalIgnoreCase);
});
if (responder == null)
{
return null;
}
2017-11-23 15:46:16 +00:00
return new Tuple<string, Tuple<string, bool, Func<string, IpEndPointInfo, Encoding, CancellationToken, Task>>>(text, responder);
2016-09-03 17:16:36 +00:00
}
2017-11-23 15:46:16 +00:00
private async Task RespondToV2Message(string messageText, IpEndPointInfo endpoint, Encoding encoding, CancellationToken cancellationToken)
2014-07-27 22:01:29 +00:00
{
2016-09-03 17:16:36 +00:00
var parts = messageText.Split('|');
2017-11-23 15:46:16 +00:00
var localUrl = await _appHost.GetLocalApiUrl(cancellationToken).ConfigureAwait(false);
2013-03-27 22:13:46 +00:00
2015-01-24 19:03:55 +00:00
if (!string.IsNullOrEmpty(localUrl))
2014-07-27 22:01:29 +00:00
{
var response = new ServerDiscoveryInfo
{
2015-01-24 19:03:55 +00:00
Address = localUrl,
Id = _appHost.SystemId,
Name = _appHost.FriendlyName
2014-07-27 22:01:29 +00:00
};
2017-11-23 15:46:16 +00:00
await SendAsync(encoding.GetBytes(_json.SerializeToString(response)), endpoint, cancellationToken).ConfigureAwait(false);
2016-11-04 18:56:47 +00:00
2016-09-03 20:28:07 +00:00
if (parts.Length > 1)
{
_appHost.EnableLoopback(parts[1]);
}
2014-07-27 22:01:29 +00:00
}
else
{
_logger.LogWarning("Unable to respond to udp request because the local ip address could not be determined.");
2013-03-27 22:13:46 +00:00
}
}
/// <summary>
/// The _udp client
/// </summary>
2017-03-02 20:50:09 +00:00
private ISocket _udpClient;
2016-11-04 18:56:47 +00:00
private readonly ISocketFactory _socketFactory;
/// <summary>
/// Starts the specified port.
/// </summary>
/// <param name="port">The port.</param>
public void Start(int port)
{
2016-11-04 18:56:47 +00:00
_udpClient = _socketFactory.CreateUdpSocket(port);
2017-05-24 19:12:55 +00:00
Task.Run(() => BeginReceive());
}
2017-05-24 19:12:55 +00:00
private readonly byte[] _receiveBuffer = new byte[8192];
private void BeginReceive()
2013-12-07 15:52:38 +00:00
{
2017-05-24 19:12:55 +00:00
if (_isDisposed)
2013-12-07 15:52:38 +00:00
{
2017-05-24 19:12:55 +00:00
return;
}
2013-12-07 15:52:38 +00:00
2017-05-24 19:12:55 +00:00
try
{
var result = _udpClient.BeginReceive(_receiveBuffer, 0, _receiveBuffer.Length, OnReceiveResult);
if (result.CompletedSynchronously)
{
2017-05-24 19:12:55 +00:00
OnReceiveResult(result);
}
2013-12-07 15:52:38 +00:00
}
2017-05-24 19:12:55 +00:00
catch (ObjectDisposedException)
{
//TODO Investigate and properly fix.
2017-05-24 19:12:55 +00:00
}
catch (Exception ex)
{
2018-12-20 12:11:26 +00:00
_logger.LogError(ex, "Error receiving udp message");
2017-05-24 19:12:55 +00:00
}
}
private void OnReceiveResult(IAsyncResult result)
{
if (_isDisposed)
{
return;
}
2019-01-07 23:27:46 +00:00
2017-05-24 19:12:55 +00:00
try
{
var socketResult = _udpClient.EndReceive(result);
OnMessageReceived(socketResult);
}
catch (ObjectDisposedException)
{
//TODO Investigate and properly fix.
2017-05-24 19:12:55 +00:00
}
catch (Exception ex)
{
2018-12-20 12:11:26 +00:00
_logger.LogError(ex, "Error receiving udp message");
2017-05-24 19:12:55 +00:00
}
BeginReceive();
2013-12-07 15:52:38 +00:00
}
/// <summary>
/// Called when [message received].
/// </summary>
/// <param name="message">The message.</param>
2016-11-04 18:56:47 +00:00
private void OnMessageReceived(SocketReceiveResult message)
{
2016-12-28 06:08:18 +00:00
if (_isDisposed)
{
return;
}
if (message.RemoteEndPoint.Port == 0)
{
return;
}
2015-05-17 03:17:23 +00:00
try
{
2016-11-04 18:56:47 +00:00
OnMessageReceived(new GenericEventArgs<SocketReceiveResult>
2015-05-17 03:17:23 +00:00
{
2016-11-04 18:56:47 +00:00
Argument = message
2015-05-17 03:17:23 +00:00
});
}
catch (Exception ex)
{
2018-12-20 12:11:26 +00:00
_logger.LogError(ex, "Error handling UDP message");
2015-05-17 03:17:23 +00:00
}
}
/// <summary>
/// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
/// </summary>
public void Dispose()
{
Dispose(true);
}
/// <summary>
/// Releases unmanaged and - optionally - managed resources.
/// </summary>
/// <param name="dispose"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
protected virtual void Dispose(bool dispose)
{
if (dispose)
{
2017-03-26 19:00:35 +00:00
_isDisposed = true;
if (_udpClient != null)
{
_udpClient.Dispose();
}
}
}
2017-11-23 15:46:16 +00:00
public async Task SendAsync(byte[] bytes, IpEndPointInfo remoteEndPoint, CancellationToken cancellationToken)
{
2016-12-28 06:08:18 +00:00
if (_isDisposed)
{
throw new ObjectDisposedException(GetType().Name);
}
if (bytes == null)
{
throw new ArgumentNullException(nameof(bytes));
}
2016-11-04 18:56:47 +00:00
if (remoteEndPoint == null)
{
throw new ArgumentNullException(nameof(remoteEndPoint));
}
2014-05-27 14:30:21 +00:00
try
{
2017-11-23 15:46:16 +00:00
await _udpClient.SendToAsync(bytes, 0, bytes.Length, remoteEndPoint, cancellationToken).ConfigureAwait(false);
2013-03-12 22:51:10 +00:00
2018-12-20 12:11:26 +00:00
_logger.LogInformation("Udp message sent to {remoteEndPoint}", remoteEndPoint);
2017-03-26 19:00:35 +00:00
}
catch (OperationCanceledException)
{
2017-05-24 19:12:55 +00:00
2014-05-27 14:30:21 +00:00
}
catch (Exception ex)
{
2018-12-20 12:11:26 +00:00
_logger.LogError(ex, "Error sending message to {remoteEndPoint}", remoteEndPoint);
2014-05-27 14:30:21 +00:00
}
}
}
}