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

131 lines
4.3 KiB
C#
Raw Normal View History

using System;
using System.Net;
2020-01-12 10:59:10 -07:00
using System.Net.Sockets;
using System.Text;
2020-01-12 10:59:10 -07:00
using System.Text.Json;
2017-02-05 13:44:08 -07:00
using System.Threading;
using System.Threading.Tasks;
using MediaBrowser.Controller;
using MediaBrowser.Model.ApiClient;
using Microsoft.Extensions.Logging;
2016-11-04 11:56:47 -07:00
namespace Emby.Server.Implementations.Udp
{
/// <summary>
2020-01-12 10:59:10 -07:00
/// Provides a Udp Server.
/// </summary>
2020-01-12 10:59:10 -07:00
public sealed class UdpServer : IDisposable
{
/// <summary>
2013-03-27 15:13:46 -07:00
/// The _logger
/// </summary>
2013-03-27 15:13:46 -07:00
private readonly ILogger _logger;
2014-07-27 15:01:29 -07:00
private readonly IServerApplicationHost _appHost;
2020-01-12 10:59:10 -07:00
private Socket _udpSocket;
private IPEndPoint _endpoint;
private readonly byte[] _receiveBuffer = new byte[8192];
2014-07-27 15:01:29 -07:00
2020-01-12 10:59:10 -07:00
private bool _disposed = false;
/// <summary>
2020-01-12 10:59:10 -07:00
/// Initializes a new instance of the <see cref="UdpServer" /> class.
/// </summary>
2020-01-12 10:59:10 -07:00
public UdpServer(ILogger logger, IServerApplicationHost appHost)
2016-09-03 10:16:36 -07:00
{
2020-01-12 10:59:10 -07:00
_logger = logger;
_appHost = appHost;
2016-09-03 10:16:36 -07:00
}
2020-01-12 10:59:10 -07:00
private async Task RespondToV2Message(string messageText, EndPoint endpoint, CancellationToken cancellationToken)
2014-07-27 15:01:29 -07:00
{
2017-11-23 08:46:16 -07:00
var localUrl = await _appHost.GetLocalApiUrl(cancellationToken).ConfigureAwait(false);
2013-03-27 15:13:46 -07:00
2015-01-24 12:03:55 -07:00
if (!string.IsNullOrEmpty(localUrl))
2014-07-27 15:01:29 -07:00
{
var response = new ServerDiscoveryInfo
{
2015-01-24 12:03:55 -07:00
Address = localUrl,
Id = _appHost.SystemId,
Name = _appHost.FriendlyName
2014-07-27 15:01:29 -07:00
};
2020-01-12 10:59:10 -07:00
try
{
await _udpSocket.SendToAsync(JsonSerializer.SerializeToUtf8Bytes(response), SocketFlags.None, endpoint).ConfigureAwait(false);
}
catch (SocketException ex)
{
_logger.LogError(ex, "Error sending response message");
}
2016-11-04 11:56:47 -07:00
2020-01-12 10:59:10 -07:00
var parts = messageText.Split('|');
2016-09-03 13:28:07 -07:00
if (parts.Length > 1)
{
_appHost.EnableLoopback(parts[1]);
}
2014-07-27 15:01:29 -07:00
}
else
{
_logger.LogWarning("Unable to respond to udp request because the local ip address could not be determined.");
2013-03-27 15:13:46 -07:00
}
}
/// <summary>
/// Starts the specified port.
/// </summary>
/// <param name="port">The port.</param>
2020-01-12 10:59:10 -07:00
/// <param name="cancellationToken"></param>
public void Start(int port, CancellationToken cancellationToken)
2013-12-07 08:52:38 -07:00
{
2020-01-12 10:59:10 -07:00
_endpoint = new IPEndPoint(IPAddress.Any, port);
2013-12-07 08:52:38 -07:00
2020-01-12 10:59:10 -07:00
_udpSocket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
_udpSocket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
_udpSocket.Bind(_endpoint);
2017-05-24 12:12:55 -07:00
2020-01-12 10:59:10 -07:00
_ = Task.Run(async () => await BeginReceiveAsync(cancellationToken).ConfigureAwait(false), cancellationToken).ConfigureAwait(false);
2013-12-07 08:52:38 -07:00
}
2020-01-12 10:59:10 -07:00
private async Task BeginReceiveAsync(CancellationToken cancellationToken)
{
2020-01-12 10:59:10 -07:00
while (!cancellationToken.IsCancellationRequested)
{
2020-01-12 10:59:10 -07:00
try
2015-05-16 20:17:23 -07:00
{
2020-01-12 10:59:10 -07:00
var result = await _udpSocket.ReceiveFromAsync(_receiveBuffer, SocketFlags.None, _endpoint).ConfigureAwait(false);
2020-01-12 10:59:10 -07:00
cancellationToken.ThrowIfCancellationRequested();
2017-03-26 12:00:35 -07:00
2020-01-12 10:59:10 -07:00
var text = Encoding.UTF8.GetString(_receiveBuffer, 0, result.ReceivedBytes);
if (text.Contains("who is JellyfinServer?", StringComparison.OrdinalIgnoreCase))
{
await RespondToV2Message(text, result.RemoteEndPoint, cancellationToken).ConfigureAwait(false);
}
}
catch (SocketException ex)
2017-03-26 12:00:35 -07:00
{
2020-01-12 10:59:10 -07:00
_logger.LogError(ex, "Failed to receive data drom socket");
}
catch (OperationCanceledException)
{
// Don't throw
2017-03-26 12:00:35 -07:00
}
}
}
2020-01-12 10:59:10 -07:00
/// <inheritdoc />
public void Dispose()
{
2020-01-12 10:59:10 -07:00
if (_disposed)
2016-12-27 23:08:18 -07:00
{
2020-01-12 10:59:10 -07:00
return;
}
2020-01-12 10:59:10 -07:00
_udpSocket?.Dispose();
2013-03-12 15:51:10 -07:00
2020-01-12 10:59:10 -07:00
GC.SuppressFinalize(this);
}
}
}