UdpServer.cs 9.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Net;
  5. using System.Text;
  6. using System.Threading;
  7. using System.Threading.Tasks;
  8. using MediaBrowser.Controller;
  9. using MediaBrowser.Model.ApiClient;
  10. using MediaBrowser.Model.Events;
  11. using MediaBrowser.Model.Net;
  12. using MediaBrowser.Model.Serialization;
  13. using Microsoft.Extensions.Logging;
  14. namespace Emby.Server.Implementations.Udp
  15. {
  16. /// <summary>
  17. /// Provides a Udp Server
  18. /// </summary>
  19. public class UdpServer : IDisposable
  20. {
  21. /// <summary>
  22. /// The _logger
  23. /// </summary>
  24. private readonly ILogger _logger;
  25. private bool _isDisposed;
  26. private readonly List<Tuple<string, bool, Func<string, IPEndPoint, Encoding, CancellationToken, Task>>> _responders = new List<Tuple<string, bool, Func<string, IPEndPoint, Encoding, CancellationToken, Task>>>();
  27. private readonly IServerApplicationHost _appHost;
  28. private readonly IJsonSerializer _json;
  29. /// <summary>
  30. /// Initializes a new instance of the <see cref="UdpServer" /> class.
  31. /// </summary>
  32. public UdpServer(ILogger logger, IServerApplicationHost appHost, IJsonSerializer json, ISocketFactory socketFactory)
  33. {
  34. _logger = logger;
  35. _appHost = appHost;
  36. _json = json;
  37. _socketFactory = socketFactory;
  38. AddMessageResponder("who is JellyfinServer?", true, RespondToV2Message);
  39. }
  40. private void AddMessageResponder(string message, bool isSubstring, Func<string, IPEndPoint, Encoding, CancellationToken, Task> responder)
  41. {
  42. _responders.Add(new Tuple<string, bool, Func<string, IPEndPoint, Encoding, CancellationToken, Task>>(message, isSubstring, responder));
  43. }
  44. /// <summary>
  45. /// Raises the <see cref="E:MessageReceived" /> event.
  46. /// </summary>
  47. private async void OnMessageReceived(GenericEventArgs<SocketReceiveResult> e)
  48. {
  49. var message = e.Argument;
  50. var encoding = Encoding.UTF8;
  51. var responder = GetResponder(message.Buffer, message.ReceivedBytes, encoding);
  52. if (responder == null)
  53. {
  54. encoding = Encoding.Unicode;
  55. responder = GetResponder(message.Buffer, message.ReceivedBytes, encoding);
  56. }
  57. if (responder != null)
  58. {
  59. var cancellationToken = CancellationToken.None;
  60. try
  61. {
  62. await responder.Item2.Item3(responder.Item1, message.RemoteEndPoint, encoding, cancellationToken).ConfigureAwait(false);
  63. }
  64. catch (OperationCanceledException)
  65. {
  66. }
  67. catch (Exception ex)
  68. {
  69. _logger.LogError(ex, "Error in OnMessageReceived");
  70. }
  71. }
  72. }
  73. private Tuple<string, Tuple<string, bool, Func<string, IPEndPoint, Encoding, CancellationToken, Task>>> GetResponder(byte[] buffer, int bytesReceived, Encoding encoding)
  74. {
  75. var text = encoding.GetString(buffer, 0, bytesReceived);
  76. var responder = _responders.FirstOrDefault(i =>
  77. {
  78. if (i.Item2)
  79. {
  80. return text.IndexOf(i.Item1, StringComparison.OrdinalIgnoreCase) != -1;
  81. }
  82. return string.Equals(i.Item1, text, StringComparison.OrdinalIgnoreCase);
  83. });
  84. if (responder == null)
  85. {
  86. return null;
  87. }
  88. return new Tuple<string, Tuple<string, bool, Func<string, IPEndPoint, Encoding, CancellationToken, Task>>>(text, responder);
  89. }
  90. private async Task RespondToV2Message(string messageText, IPEndPoint endpoint, Encoding encoding, CancellationToken cancellationToken)
  91. {
  92. var parts = messageText.Split('|');
  93. var localUrl = await _appHost.GetLocalApiUrl(cancellationToken).ConfigureAwait(false);
  94. if (!string.IsNullOrEmpty(localUrl))
  95. {
  96. var response = new ServerDiscoveryInfo
  97. {
  98. Address = localUrl,
  99. Id = _appHost.SystemId,
  100. Name = _appHost.FriendlyName
  101. };
  102. await SendAsync(encoding.GetBytes(_json.SerializeToString(response)), endpoint, cancellationToken).ConfigureAwait(false);
  103. if (parts.Length > 1)
  104. {
  105. _appHost.EnableLoopback(parts[1]);
  106. }
  107. }
  108. else
  109. {
  110. _logger.LogWarning("Unable to respond to udp request because the local ip address could not be determined.");
  111. }
  112. }
  113. /// <summary>
  114. /// The _udp client
  115. /// </summary>
  116. private ISocket _udpClient;
  117. private readonly ISocketFactory _socketFactory;
  118. /// <summary>
  119. /// Starts the specified port.
  120. /// </summary>
  121. /// <param name="port">The port.</param>
  122. public void Start(int port)
  123. {
  124. _udpClient = _socketFactory.CreateUdpSocket(port);
  125. Task.Run(() => BeginReceive());
  126. }
  127. private readonly byte[] _receiveBuffer = new byte[8192];
  128. private void BeginReceive()
  129. {
  130. if (_isDisposed)
  131. {
  132. return;
  133. }
  134. try
  135. {
  136. var result = _udpClient.BeginReceive(_receiveBuffer, 0, _receiveBuffer.Length, OnReceiveResult);
  137. if (result.CompletedSynchronously)
  138. {
  139. OnReceiveResult(result);
  140. }
  141. }
  142. catch (ObjectDisposedException)
  143. {
  144. //TODO Investigate and properly fix.
  145. }
  146. catch (Exception ex)
  147. {
  148. _logger.LogError(ex, "Error receiving udp message");
  149. }
  150. }
  151. private void OnReceiveResult(IAsyncResult result)
  152. {
  153. if (_isDisposed)
  154. {
  155. return;
  156. }
  157. try
  158. {
  159. var socketResult = _udpClient.EndReceive(result);
  160. OnMessageReceived(socketResult);
  161. }
  162. catch (ObjectDisposedException)
  163. {
  164. //TODO Investigate and properly fix.
  165. }
  166. catch (Exception ex)
  167. {
  168. _logger.LogError(ex, "Error receiving udp message");
  169. }
  170. BeginReceive();
  171. }
  172. /// <summary>
  173. /// Called when [message received].
  174. /// </summary>
  175. /// <param name="message">The message.</param>
  176. private void OnMessageReceived(SocketReceiveResult message)
  177. {
  178. if (_isDisposed)
  179. {
  180. return;
  181. }
  182. if (message.RemoteEndPoint.Port == 0)
  183. {
  184. return;
  185. }
  186. try
  187. {
  188. OnMessageReceived(new GenericEventArgs<SocketReceiveResult>
  189. {
  190. Argument = message
  191. });
  192. }
  193. catch (Exception ex)
  194. {
  195. _logger.LogError(ex, "Error handling UDP message");
  196. }
  197. }
  198. /// <summary>
  199. /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
  200. /// </summary>
  201. public void Dispose()
  202. {
  203. Dispose(true);
  204. }
  205. /// <summary>
  206. /// Releases unmanaged and - optionally - managed resources.
  207. /// </summary>
  208. /// <param name="dispose"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
  209. protected virtual void Dispose(bool dispose)
  210. {
  211. if (dispose)
  212. {
  213. _isDisposed = true;
  214. if (_udpClient != null)
  215. {
  216. _udpClient.Dispose();
  217. }
  218. }
  219. }
  220. public async Task SendAsync(byte[] bytes, IPEndPoint remoteEndPoint, CancellationToken cancellationToken)
  221. {
  222. if (_isDisposed)
  223. {
  224. throw new ObjectDisposedException(GetType().Name);
  225. }
  226. if (bytes == null)
  227. {
  228. throw new ArgumentNullException(nameof(bytes));
  229. }
  230. if (remoteEndPoint == null)
  231. {
  232. throw new ArgumentNullException(nameof(remoteEndPoint));
  233. }
  234. try
  235. {
  236. await _udpClient.SendToAsync(bytes, 0, bytes.Length, remoteEndPoint, cancellationToken).ConfigureAwait(false);
  237. _logger.LogInformation("Udp message sent to {remoteEndPoint}", remoteEndPoint);
  238. }
  239. catch (OperationCanceledException)
  240. {
  241. }
  242. catch (Exception ex)
  243. {
  244. _logger.LogError(ex, "Error sending message to {remoteEndPoint}", remoteEndPoint);
  245. }
  246. }
  247. }
  248. }