UdpServer.cs 9.2 KB

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