UdpServer.cs 4.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145
  1. using System;
  2. using System.Net;
  3. using System.Net.Sockets;
  4. using System.Text;
  5. using System.Text.Json;
  6. using System.Threading;
  7. using System.Threading.Tasks;
  8. using MediaBrowser.Controller;
  9. using MediaBrowser.Model.ApiClient;
  10. using Microsoft.Extensions.Configuration;
  11. using Microsoft.Extensions.Logging;
  12. namespace Emby.Server.Implementations.Udp
  13. {
  14. /// <summary>
  15. /// Provides a Udp Server.
  16. /// </summary>
  17. public sealed class UdpServer : IDisposable
  18. {
  19. /// <summary>
  20. /// Address Override Configuration Key.
  21. /// </summary>
  22. public const string AddressOverrideConfigKey = "PublishedServerUrl";
  23. /// <summary>
  24. /// The _logger.
  25. /// </summary>
  26. private readonly ILogger _logger;
  27. private readonly IServerApplicationHost _appHost;
  28. private readonly IConfiguration _config;
  29. private Socket _udpSocket;
  30. private IPEndPoint _endpoint;
  31. private readonly byte[] _receiveBuffer = new byte[8192];
  32. private bool _disposed = false;
  33. /// <summary>
  34. /// Initializes a new instance of the <see cref="UdpServer" /> class.
  35. /// </summary>
  36. /// <param name="logger">The logger.</param>
  37. /// <param name="appHost">The application host.</param>
  38. /// <param name="configuration">The configuration manager.</param>
  39. /// <param name="port">The port.</param>
  40. public UdpServer(
  41. ILogger logger,
  42. IServerApplicationHost appHost,
  43. IConfiguration configuration,
  44. int port)
  45. {
  46. _logger = logger;
  47. _appHost = appHost;
  48. _config = configuration;
  49. _endpoint = new IPEndPoint(IPAddress.Any, port);
  50. _udpSocket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
  51. _udpSocket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
  52. }
  53. private async Task RespondToV2Message(string messageText, EndPoint endpoint, CancellationToken cancellationToken)
  54. {
  55. string? localUrl = _config[AddressOverrideConfigKey];
  56. if (string.IsNullOrEmpty(localUrl))
  57. {
  58. localUrl = _appHost.GetSmartApiUrl(((IPEndPoint)endpoint).Address);
  59. }
  60. if (string.IsNullOrEmpty(localUrl))
  61. {
  62. _logger.LogWarning("Unable to respond to udp request because the local ip address could not be determined.");
  63. return;
  64. }
  65. var response = new ServerDiscoveryInfo(localUrl, _appHost.SystemId, _appHost.FriendlyName);
  66. try
  67. {
  68. await _udpSocket.SendToAsync(JsonSerializer.SerializeToUtf8Bytes(response), SocketFlags.None, endpoint).ConfigureAwait(false);
  69. }
  70. catch (SocketException ex)
  71. {
  72. _logger.LogError(ex, "Error sending response message");
  73. }
  74. }
  75. /// <summary>
  76. /// Starts the specified port.
  77. /// </summary>
  78. /// <param name="cancellationToken">The cancellation token to cancel operation.</param>
  79. public void Start(CancellationToken cancellationToken)
  80. {
  81. _udpSocket.Bind(_endpoint);
  82. _ = Task.Run(async () => await BeginReceiveAsync(cancellationToken).ConfigureAwait(false), cancellationToken).ConfigureAwait(false);
  83. }
  84. private async Task BeginReceiveAsync(CancellationToken cancellationToken)
  85. {
  86. var infiniteTask = Task.Delay(-1, cancellationToken);
  87. while (!cancellationToken.IsCancellationRequested)
  88. {
  89. try
  90. {
  91. var task = _udpSocket.ReceiveFromAsync(_receiveBuffer, SocketFlags.None, _endpoint);
  92. await Task.WhenAny(task, infiniteTask).ConfigureAwait(false);
  93. if (!task.IsCompleted)
  94. {
  95. return;
  96. }
  97. var result = task.Result;
  98. var text = Encoding.UTF8.GetString(_receiveBuffer, 0, result.ReceivedBytes);
  99. if (text.Contains("who is JellyfinServer?", StringComparison.OrdinalIgnoreCase))
  100. {
  101. await RespondToV2Message(text, result.RemoteEndPoint, cancellationToken).ConfigureAwait(false);
  102. }
  103. }
  104. catch (SocketException ex)
  105. {
  106. _logger.LogError(ex, "Failed to receive data from socket");
  107. }
  108. catch (OperationCanceledException)
  109. {
  110. // Don't throw
  111. }
  112. }
  113. }
  114. /// <inheritdoc />
  115. public void Dispose()
  116. {
  117. if (_disposed)
  118. {
  119. return;
  120. }
  121. _udpSocket?.Dispose();
  122. GC.SuppressFinalize(this);
  123. }
  124. }
  125. }