UdpServer.cs 4.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136
  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(localUrl, _appHost.SystemId, _appHost.FriendlyName);
  50. try
  51. {
  52. await _udpSocket.SendToAsync(JsonSerializer.SerializeToUtf8Bytes(response), SocketFlags.None, endpoint).ConfigureAwait(false);
  53. }
  54. catch (SocketException ex)
  55. {
  56. _logger.LogError(ex, "Error sending response message");
  57. }
  58. }
  59. else
  60. {
  61. _logger.LogWarning("Unable to respond to udp request because the local ip address could not be determined.");
  62. }
  63. }
  64. /// <summary>
  65. /// Starts the specified port.
  66. /// </summary>
  67. /// <param name="port">The port.</param>
  68. /// <param name="cancellationToken">The cancellation token to cancel operation.</param>
  69. public void Start(int port, CancellationToken cancellationToken)
  70. {
  71. _endpoint = new IPEndPoint(IPAddress.Any, port);
  72. _udpSocket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
  73. _udpSocket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
  74. _udpSocket.Bind(_endpoint);
  75. _ = Task.Run(async () => await BeginReceiveAsync(cancellationToken).ConfigureAwait(false), cancellationToken).ConfigureAwait(false);
  76. }
  77. private async Task BeginReceiveAsync(CancellationToken cancellationToken)
  78. {
  79. while (!cancellationToken.IsCancellationRequested)
  80. {
  81. var infiniteTask = Task.Delay(-1, cancellationToken);
  82. try
  83. {
  84. var task = _udpSocket.ReceiveFromAsync(_receiveBuffer, SocketFlags.None, _endpoint);
  85. await Task.WhenAny(task, infiniteTask).ConfigureAwait(false);
  86. if (!task.IsCompleted)
  87. {
  88. return;
  89. }
  90. var result = task.Result;
  91. var text = Encoding.UTF8.GetString(_receiveBuffer, 0, result.ReceivedBytes);
  92. if (text.Contains("who is JellyfinServer?", StringComparison.OrdinalIgnoreCase))
  93. {
  94. await RespondToV2Message(text, result.RemoteEndPoint, cancellationToken).ConfigureAwait(false);
  95. }
  96. }
  97. catch (SocketException ex)
  98. {
  99. _logger.LogError(ex, "Failed to receive data from socket");
  100. }
  101. catch (OperationCanceledException)
  102. {
  103. // Don't throw
  104. }
  105. }
  106. }
  107. /// <inheritdoc />
  108. public void Dispose()
  109. {
  110. if (_disposed)
  111. {
  112. return;
  113. }
  114. _udpSocket?.Dispose();
  115. GC.SuppressFinalize(this);
  116. }
  117. }
  118. }