UdpServer.cs 4.7 KB

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