UdpServer.cs 9.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291
  1. using MediaBrowser.Controller;
  2. using MediaBrowser.Model.ApiClient;
  3. using Microsoft.Extensions.Logging;
  4. using MediaBrowser.Model.Serialization;
  5. using System;
  6. using System.Collections.Generic;
  7. using System.Linq;
  8. using System.Text;
  9. using System.Threading;
  10. using System.Threading.Tasks;
  11. using MediaBrowser.Model.Events;
  12. using MediaBrowser.Model.Net;
  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. }
  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. }
  165. catch (Exception ex)
  166. {
  167. _logger.LogError(ex, "Error receiving udp message");
  168. }
  169. BeginReceive();
  170. }
  171. /// <summary>
  172. /// Called when [message received].
  173. /// </summary>
  174. /// <param name="message">The message.</param>
  175. private void OnMessageReceived(SocketReceiveResult message)
  176. {
  177. if (_isDisposed)
  178. {
  179. return;
  180. }
  181. if (message.RemoteEndPoint.Port == 0)
  182. {
  183. return;
  184. }
  185. try
  186. {
  187. OnMessageReceived(new GenericEventArgs<SocketReceiveResult>
  188. {
  189. Argument = message
  190. });
  191. }
  192. catch (Exception ex)
  193. {
  194. _logger.LogError(ex, "Error handling UDP message");
  195. }
  196. }
  197. /// <summary>
  198. /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
  199. /// </summary>
  200. public void Dispose()
  201. {
  202. Dispose(true);
  203. }
  204. /// <summary>
  205. /// Releases unmanaged and - optionally - managed resources.
  206. /// </summary>
  207. /// <param name="dispose"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
  208. protected virtual void Dispose(bool dispose)
  209. {
  210. if (dispose)
  211. {
  212. _isDisposed = true;
  213. if (_udpClient != null)
  214. {
  215. _udpClient.Dispose();
  216. }
  217. }
  218. }
  219. public async Task SendAsync(byte[] bytes, IpEndPointInfo remoteEndPoint, CancellationToken cancellationToken)
  220. {
  221. if (_isDisposed)
  222. {
  223. throw new ObjectDisposedException(GetType().Name);
  224. }
  225. if (bytes == null)
  226. {
  227. throw new ArgumentNullException("bytes");
  228. }
  229. if (remoteEndPoint == null)
  230. {
  231. throw new ArgumentNullException("remoteEndPoint");
  232. }
  233. try
  234. {
  235. await _udpClient.SendToAsync(bytes, 0, bytes.Length, remoteEndPoint, cancellationToken).ConfigureAwait(false);
  236. _logger.LogInformation("Udp message sent to {remoteEndPoint}", remoteEndPoint);
  237. }
  238. catch (OperationCanceledException)
  239. {
  240. }
  241. catch (Exception ex)
  242. {
  243. _logger.LogError(ex, "Error sending message to {remoteEndPoint}", remoteEndPoint);
  244. }
  245. }
  246. }
  247. }