UdpServer.cs 4.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141
  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. /// The _logger.
  21. /// </summary>
  22. private readonly ILogger _logger;
  23. private readonly IServerApplicationHost _appHost;
  24. private readonly IConfiguration _config;
  25. /// <summary>
  26. /// Address Override Configuration Key.
  27. /// </summary>
  28. public const string AddressOverrideConfigKey = "PublishedServerUrl";
  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. public UdpServer(ILogger logger, IServerApplicationHost appHost, IConfiguration configuration)
  37. {
  38. _logger = logger;
  39. _appHost = appHost;
  40. _config = configuration;
  41. }
  42. private async Task RespondToV2Message(string messageText, EndPoint endpoint, CancellationToken cancellationToken)
  43. {
  44. string localUrl = !string.IsNullOrEmpty(_config[AddressOverrideConfigKey])
  45. ? _config[AddressOverrideConfigKey]
  46. : _appHost.GetSmartApiUrl(((IPEndPoint)endpoint).Address);
  47. if (!string.IsNullOrEmpty(localUrl))
  48. {
  49. var response = new ServerDiscoveryInfo
  50. {
  51. Address = localUrl,
  52. Id = _appHost.SystemId,
  53. Name = _appHost.FriendlyName
  54. };
  55. try
  56. {
  57. await _udpSocket.SendToAsync(JsonSerializer.SerializeToUtf8Bytes(response), SocketFlags.None, endpoint).ConfigureAwait(false);
  58. }
  59. catch (SocketException ex)
  60. {
  61. _logger.LogError(ex, "Error sending response message");
  62. }
  63. }
  64. else
  65. {
  66. _logger.LogWarning("Unable to respond to udp request because the local ip address could not be determined.");
  67. }
  68. }
  69. /// <summary>
  70. /// Starts the specified port.
  71. /// </summary>
  72. /// <param name="port">The port.</param>
  73. /// <param name="cancellationToken"></param>
  74. public void Start(int port, CancellationToken cancellationToken)
  75. {
  76. _endpoint = new IPEndPoint(IPAddress.Any, port);
  77. _udpSocket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
  78. _udpSocket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
  79. _udpSocket.Bind(_endpoint);
  80. _ = Task.Run(async () => await BeginReceiveAsync(cancellationToken).ConfigureAwait(false), cancellationToken).ConfigureAwait(false);
  81. }
  82. private async Task BeginReceiveAsync(CancellationToken cancellationToken)
  83. {
  84. while (!cancellationToken.IsCancellationRequested)
  85. {
  86. var infiniteTask = Task.Delay(-1, cancellationToken);
  87. try
  88. {
  89. var task = _udpSocket.ReceiveFromAsync(_receiveBuffer, SocketFlags.None, _endpoint);
  90. await Task.WhenAny(task, infiniteTask).ConfigureAwait(false);
  91. if (!task.IsCompleted)
  92. {
  93. return;
  94. }
  95. var result = task.Result;
  96. var text = Encoding.UTF8.GetString(_receiveBuffer, 0, result.ReceivedBytes);
  97. if (text.Contains("who is JellyfinServer?", StringComparison.OrdinalIgnoreCase))
  98. {
  99. await RespondToV2Message(text, result.RemoteEndPoint, cancellationToken).ConfigureAwait(false);
  100. }
  101. }
  102. catch (SocketException ex)
  103. {
  104. _logger.LogError(ex, "Failed to receive data from socket");
  105. }
  106. catch (OperationCanceledException)
  107. {
  108. // Don't throw
  109. }
  110. }
  111. }
  112. /// <inheritdoc />
  113. public void Dispose()
  114. {
  115. if (_disposed)
  116. {
  117. return;
  118. }
  119. _udpSocket?.Dispose();
  120. GC.SuppressFinalize(this);
  121. }
  122. }
  123. }