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

332 lines
11 KiB
C#
Raw Normal View History

2014-04-10 15:06:54 +00:00
using MediaBrowser.Common.Net;
2014-07-27 22:01:29 +00:00
using MediaBrowser.Controller;
using MediaBrowser.Model.ApiClient;
using MediaBrowser.Model.Logging;
2014-07-27 22:01:29 +00:00
using MediaBrowser.Model.Serialization;
using System;
2014-07-27 22:01:29 +00:00
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;
2013-03-07 05:34:00 +00:00
namespace MediaBrowser.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;
/// <summary>
/// The _network manager
/// </summary>
2013-03-27 22:13:46 +00:00
private readonly INetworkManager _networkManager;
2013-12-07 15:52:38 +00:00
private bool _isDisposed;
2015-05-17 03:17:23 +00:00
private readonly List<Tuple<string, byte[], Action<string, Encoding>>> _responders = new List<Tuple<string, byte[], Action<string, Encoding>>>();
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>
/// <param name="logger">The logger.</param>
2013-03-27 22:13:46 +00:00
/// <param name="networkManager">The network manager.</param>
2014-07-27 22:01:29 +00:00
/// <param name="appHost">The application host.</param>
2014-08-19 22:28:35 +00:00
/// <param name="json">The json.</param>
public UdpServer(ILogger logger, INetworkManager networkManager, IServerApplicationHost appHost, IJsonSerializer json)
{
2013-03-27 22:13:46 +00:00
_logger = logger;
_networkManager = networkManager;
2014-07-27 22:01:29 +00:00
_appHost = appHost;
2014-07-30 03:31:35 +00:00
_json = json;
2014-07-27 22:01:29 +00:00
2015-03-27 00:24:36 +00:00
AddMessageResponder("who is EmbyServer?", RespondToV2Message);
2015-05-17 03:17:23 +00:00
AddMessageResponder("who is MediaBrowserServer_v2?", RespondToV2Message);
AddMessageResponder("who is MediaBrowserServer?", RespondToV1Message);
2014-07-27 22:01:29 +00:00
}
2015-05-17 03:17:23 +00:00
private void AddMessageResponder(string message, Action<string, Encoding> responder)
2014-07-27 22:01:29 +00:00
{
var expectedMessageBytes = Encoding.UTF8.GetBytes(message);
2015-05-17 03:17:23 +00:00
_responders.Add(new Tuple<string, byte[], Action<string, Encoding>>(message, expectedMessageBytes, responder));
}
/// <summary>
/// Raises the <see cref="E:MessageReceived" /> event.
/// </summary>
/// <param name="e">The <see cref="UdpMessageReceivedEventArgs"/> instance containing the event data.</param>
2014-07-30 03:31:35 +00:00
private void OnMessageReceived(UdpMessageReceivedEventArgs e)
{
2015-05-17 03:17:23 +00:00
var responder = _responders.FirstOrDefault(i => i.Item2.SequenceEqual(e.Bytes));
var encoding = Encoding.UTF8;
if (responder == null)
{
var text = Encoding.Unicode.GetString(e.Bytes);
responder = _responders.FirstOrDefault(i => string.Equals(i.Item1, text, StringComparison.OrdinalIgnoreCase));
if (responder != null)
{
encoding = Encoding.Unicode;
}
}
2014-07-27 22:01:29 +00:00
if (responder != null)
{
2014-07-30 03:31:35 +00:00
try
{
2015-05-17 03:17:23 +00:00
responder.Item3(e.RemoteEndPoint, encoding);
2014-07-30 03:31:35 +00:00
}
catch (Exception ex)
{
_logger.ErrorException("Error in OnMessageReceived", ex);
}
2014-07-27 22:01:29 +00:00
}
}
2013-03-27 22:13:46 +00:00
2015-05-17 03:17:23 +00:00
private async void RespondToV1Message(string endpoint, Encoding encoding)
2014-07-27 22:01:29 +00:00
{
2015-01-24 19:03:55 +00:00
var localAddress = _appHost.LocalApiUrl;
2013-03-27 22:13:46 +00:00
2014-07-27 22:01:29 +00:00
if (!string.IsNullOrEmpty(localAddress))
2013-03-27 22:13:46 +00:00
{
2014-08-19 22:28:35 +00:00
// This is how we did the old v1 search, so need to strip off the protocol
var index = localAddress.IndexOf("://", StringComparison.OrdinalIgnoreCase);
if (index != -1)
{
localAddress = localAddress.Substring(index + 3);
}
2014-07-27 22:01:29 +00:00
// Send a response back with our ip address and port
2014-08-19 22:28:35 +00:00
var response = String.Format("MediaBrowserServer|{0}", localAddress);
2013-03-27 22:13:46 +00:00
2014-07-27 22:01:29 +00:00
await SendAsync(Encoding.UTF8.GetBytes(response), endpoint);
}
else
{
_logger.Warn("Unable to respond to udp request because the local ip address could not be determined.");
}
}
2015-05-17 03:17:23 +00:00
private async void RespondToV2Message(string endpoint, Encoding encoding)
2014-07-27 22:01:29 +00:00
{
2015-01-24 19:03:55 +00:00
var localUrl = _appHost.LocalApiUrl;
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
};
2015-05-17 03:17:23 +00:00
await SendAsync(encoding.GetBytes(_json.SerializeToString(response)), endpoint);
2014-07-27 22:01:29 +00:00
}
else
{
_logger.Warn("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>
private UdpClient _udpClient;
/// <summary>
/// Starts the specified port.
/// </summary>
/// <param name="port">The port.</param>
public void Start(int port)
{
_udpClient = new UdpClient(new IPEndPoint(IPAddress.Any, port));
_udpClient.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
2013-12-07 15:52:38 +00:00
Task.Run(() => StartListening());
}
2013-12-07 15:52:38 +00:00
private async void StartListening()
{
while (!_isDisposed)
{
try
{
var result = await GetResult().ConfigureAwait(false);
OnMessageReceived(result);
}
catch (ObjectDisposedException)
{
break;
}
catch (Exception ex)
{
_logger.ErrorException("Error in StartListening", ex);
}
2013-12-07 15:52:38 +00:00
}
}
private Task<UdpReceiveResult> GetResult()
{
2013-12-07 15:52:38 +00:00
try
{
return _udpClient.ReceiveAsync();
}
catch (ObjectDisposedException)
{
return Task.FromResult(new UdpReceiveResult(new byte[] { }, new IPEndPoint(IPAddress.Any, 0)));
}
catch (Exception ex)
{
_logger.ErrorException("Error receiving udp message", ex);
return Task.FromResult(new UdpReceiveResult(new byte[] { }, new IPEndPoint(IPAddress.Any, 0)));
}
}
/// <summary>
/// Called when [message received].
/// </summary>
/// <param name="message">The message.</param>
private void OnMessageReceived(UdpReceiveResult message)
{
if (message.RemoteEndPoint.Port == 0)
{
return;
}
var bytes = message.Buffer;
2015-05-17 03:17:23 +00:00
try
{
OnMessageReceived(new UdpMessageReceivedEventArgs
{
Bytes = bytes,
RemoteEndPoint = message.RemoteEndPoint.ToString()
});
}
catch (Exception ex)
{
2015-05-17 03:17:23 +00:00
_logger.ErrorException("Error handling UDP message", ex);
}
}
/// <summary>
/// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
/// </summary>
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
/// <summary>
/// Stops this instance.
/// </summary>
public void Stop()
{
2013-12-07 15:52:38 +00:00
_isDisposed = true;
2013-03-10 06:45:16 +00:00
if (_udpClient != null)
{
_udpClient.Close();
}
}
/// <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)
{
Stop();
}
}
/// <summary>
/// Sends the async.
/// </summary>
/// <param name="data">The data.</param>
/// <param name="ipAddress">The ip address.</param>
/// <param name="port">The port.</param>
/// <returns>Task{System.Int32}.</returns>
/// <exception cref="System.ArgumentNullException">data</exception>
public Task SendAsync(string data, string ipAddress, int port)
{
return SendAsync(Encoding.UTF8.GetBytes(data), ipAddress, port);
}
/// <summary>
/// Sends the async.
/// </summary>
/// <param name="bytes">The bytes.</param>
/// <param name="ipAddress">The ip address.</param>
/// <param name="port">The port.</param>
/// <returns>Task{System.Int32}.</returns>
/// <exception cref="System.ArgumentNullException">bytes</exception>
public Task SendAsync(byte[] bytes, string ipAddress, int port)
{
if (bytes == null)
{
throw new ArgumentNullException("bytes");
}
if (string.IsNullOrEmpty(ipAddress))
{
throw new ArgumentNullException("ipAddress");
}
return _udpClient.SendAsync(bytes, bytes.Length, ipAddress, port);
}
/// <summary>
/// Sends the async.
/// </summary>
/// <param name="bytes">The bytes.</param>
/// <param name="remoteEndPoint">The remote end point.</param>
/// <returns>Task.</returns>
/// <exception cref="System.ArgumentNullException">
/// bytes
/// or
/// remoteEndPoint
/// </exception>
2013-03-12 22:51:10 +00:00
public async Task SendAsync(byte[] bytes, string remoteEndPoint)
{
if (bytes == null)
{
throw new ArgumentNullException("bytes");
}
if (string.IsNullOrEmpty(remoteEndPoint))
{
throw new ArgumentNullException("remoteEndPoint");
}
2014-05-27 14:30:21 +00:00
try
{
await _udpClient.SendAsync(bytes, bytes.Length, _networkManager.Parse(remoteEndPoint)).ConfigureAwait(false);
2013-03-12 22:51:10 +00:00
2014-05-27 14:30:21 +00:00
_logger.Info("Udp message sent to {0}", remoteEndPoint);
}
catch (Exception ex)
{
_logger.ErrorException("Error sending message to {0}", ex, remoteEndPoint);
}
}
}
}