UdpServer.cs 4.5 KB

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