UdpServer.cs 4.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137
  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. using static MediaBrowser.Controller.Extensions.ConfigurationExtensions;
  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. private readonly byte[] _receiveBuffer = new byte[8192];
  27. private readonly Socket _udpSocket;
  28. private readonly IPEndPoint _endpoint;
  29. private bool _disposed;
  30. /// <summary>
  31. /// Initializes a new instance of the <see cref="UdpServer" /> class.
  32. /// </summary>
  33. /// <param name="logger">The logger.</param>
  34. /// <param name="appHost">The application host.</param>
  35. /// <param name="configuration">The configuration manager.</param>
  36. /// <param name="bindAddress"> The bind address.</param>
  37. /// <param name="port">The port.</param>
  38. public UdpServer(
  39. ILogger logger,
  40. IServerApplicationHost appHost,
  41. IConfiguration configuration,
  42. IPAddress bindAddress,
  43. int port)
  44. {
  45. _logger = logger;
  46. _appHost = appHost;
  47. _config = configuration;
  48. _endpoint = new IPEndPoint(bindAddress, port);
  49. _udpSocket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp)
  50. {
  51. MulticastLoopback = false,
  52. };
  53. _udpSocket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
  54. }
  55. private async Task RespondToV2Message(EndPoint endpoint, CancellationToken cancellationToken)
  56. {
  57. string? localUrl = _config[AddressOverrideKey];
  58. if (string.IsNullOrEmpty(localUrl))
  59. {
  60. localUrl = _appHost.GetSmartApiUrl(((IPEndPoint)endpoint).Address);
  61. }
  62. if (string.IsNullOrEmpty(localUrl))
  63. {
  64. _logger.LogWarning("Unable to respond to server discovery request because the local ip address could not be determined.");
  65. return;
  66. }
  67. var response = new ServerDiscoveryInfo(localUrl, _appHost.SystemId, _appHost.FriendlyName);
  68. try
  69. {
  70. _logger.LogDebug("Sending AutoDiscovery response");
  71. await _udpSocket.SendToAsync(JsonSerializer.SerializeToUtf8Bytes(response), SocketFlags.None, endpoint, cancellationToken).ConfigureAwait(false);
  72. }
  73. catch (SocketException ex)
  74. {
  75. _logger.LogError(ex, "Error sending response message");
  76. }
  77. }
  78. /// <summary>
  79. /// Starts the specified port.
  80. /// </summary>
  81. /// <param name="cancellationToken">The cancellation token to cancel operation.</param>
  82. public void Start(CancellationToken cancellationToken)
  83. {
  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. try
  92. {
  93. var endpoint = (EndPoint)new IPEndPoint(IPAddress.Any, 0);
  94. var result = await _udpSocket.ReceiveFromAsync(_receiveBuffer, endpoint, cancellationToken).ConfigureAwait(false);
  95. var text = Encoding.UTF8.GetString(_receiveBuffer, 0, result.ReceivedBytes);
  96. if (text.Contains("who is JellyfinServer?", StringComparison.OrdinalIgnoreCase))
  97. {
  98. await RespondToV2Message(result.RemoteEndPoint, cancellationToken).ConfigureAwait(false);
  99. }
  100. }
  101. catch (SocketException ex)
  102. {
  103. _logger.LogError(ex, "Failed to receive data from socket");
  104. }
  105. catch (OperationCanceledException)
  106. {
  107. _logger.LogDebug("Broadcast socket operation cancelled");
  108. }
  109. }
  110. }
  111. /// <inheritdoc />
  112. public void Dispose()
  113. {
  114. if (_disposed)
  115. {
  116. return;
  117. }
  118. _udpSocket.Dispose();
  119. _disposed = true;
  120. }
  121. }
  122. }