UdpServer.cs 4.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147
  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. : await _appHost.GetLocalApiUrl(cancellationToken).ConfigureAwait(false);
  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. var parts = messageText.Split('|');
  64. if (parts.Length > 1)
  65. {
  66. _appHost.EnableLoopback(parts[1]);
  67. }
  68. }
  69. else
  70. {
  71. _logger.LogWarning("Unable to respond to udp request because the local ip address could not be determined.");
  72. }
  73. }
  74. /// <summary>
  75. /// Starts the specified port.
  76. /// </summary>
  77. /// <param name="port">The port.</param>
  78. /// <param name="cancellationToken"></param>
  79. public void Start(int port, CancellationToken cancellationToken)
  80. {
  81. _endpoint = new IPEndPoint(IPAddress.Any, port);
  82. _udpSocket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
  83. _udpSocket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
  84. _udpSocket.Bind(_endpoint);
  85. _ = Task.Run(async () => await BeginReceiveAsync(cancellationToken).ConfigureAwait(false), cancellationToken).ConfigureAwait(false);
  86. }
  87. private async Task BeginReceiveAsync(CancellationToken cancellationToken)
  88. {
  89. while (!cancellationToken.IsCancellationRequested)
  90. {
  91. var infiniteTask = Task.Delay(-1, cancellationToken);
  92. try
  93. {
  94. var task = _udpSocket.ReceiveFromAsync(_receiveBuffer, SocketFlags.None, _endpoint);
  95. await Task.WhenAny(task, infiniteTask).ConfigureAwait(false);
  96. if (!task.IsCompleted)
  97. {
  98. return;
  99. }
  100. var result = task.Result;
  101. var text = Encoding.UTF8.GetString(_receiveBuffer, 0, result.ReceivedBytes);
  102. if (text.Contains("who is JellyfinServer?", StringComparison.OrdinalIgnoreCase))
  103. {
  104. await RespondToV2Message(text, result.RemoteEndPoint, cancellationToken).ConfigureAwait(false);
  105. }
  106. }
  107. catch (SocketException ex)
  108. {
  109. _logger.LogError(ex, "Failed to receive data from socket");
  110. }
  111. catch (OperationCanceledException)
  112. {
  113. // Don't throw
  114. }
  115. }
  116. }
  117. /// <inheritdoc />
  118. public void Dispose()
  119. {
  120. if (_disposed)
  121. {
  122. return;
  123. }
  124. _udpSocket?.Dispose();
  125. GC.SuppressFinalize(this);
  126. }
  127. }
  128. }