UdpServer.cs 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261
  1. using MediaBrowser.Controller;
  2. using MediaBrowser.Model.ApiClient;
  3. using MediaBrowser.Model.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, Task>>> _responders = new List<Tuple<string, bool, Func<string, IpEndPointInfo, Encoding, 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 EmbyServer?", true, RespondToV2Message);
  38. AddMessageResponder("who is MediaBrowserServer_v2?", false, RespondToV2Message);
  39. }
  40. private void AddMessageResponder(string message, bool isSubstring, Func<string, IpEndPointInfo, Encoding, Task> responder)
  41. {
  42. _responders.Add(new Tuple<string, bool, Func<string, IpEndPointInfo, Encoding, 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. try
  60. {
  61. await responder.Item2.Item3(responder.Item1, message.RemoteEndPoint, encoding).ConfigureAwait(false);
  62. }
  63. catch (Exception ex)
  64. {
  65. _logger.ErrorException("Error in OnMessageReceived", ex);
  66. }
  67. }
  68. }
  69. private Tuple<string, Tuple<string, bool, Func<string, IpEndPointInfo, Encoding, Task>>> GetResponder(byte[] buffer, int bytesReceived, Encoding encoding)
  70. {
  71. var text = encoding.GetString(buffer, 0, bytesReceived);
  72. var responder = _responders.FirstOrDefault(i =>
  73. {
  74. if (i.Item2)
  75. {
  76. return text.IndexOf(i.Item1, StringComparison.OrdinalIgnoreCase) != -1;
  77. }
  78. return string.Equals(i.Item1, text, StringComparison.OrdinalIgnoreCase);
  79. });
  80. if (responder == null)
  81. {
  82. return null;
  83. }
  84. return new Tuple<string, Tuple<string, bool, Func<string, IpEndPointInfo, Encoding, Task>>>(text, responder);
  85. }
  86. private async Task RespondToV2Message(string messageText, IpEndPointInfo endpoint, Encoding encoding)
  87. {
  88. var parts = messageText.Split('|');
  89. var localUrl = await _appHost.GetLocalApiUrl().ConfigureAwait(false);
  90. if (!string.IsNullOrEmpty(localUrl))
  91. {
  92. var response = new ServerDiscoveryInfo
  93. {
  94. Address = localUrl,
  95. Id = _appHost.SystemId,
  96. Name = _appHost.FriendlyName
  97. };
  98. await SendAsync(encoding.GetBytes(_json.SerializeToString(response)), endpoint).ConfigureAwait(false);
  99. if (parts.Length > 1)
  100. {
  101. _appHost.EnableLoopback(parts[1]);
  102. }
  103. }
  104. else
  105. {
  106. _logger.Warn("Unable to respond to udp request because the local ip address could not be determined.");
  107. }
  108. }
  109. /// <summary>
  110. /// The _udp client
  111. /// </summary>
  112. private IUdpSocket _udpClient;
  113. private readonly ISocketFactory _socketFactory;
  114. /// <summary>
  115. /// Starts the specified port.
  116. /// </summary>
  117. /// <param name="port">The port.</param>
  118. public void Start(int port)
  119. {
  120. _udpClient = _socketFactory.CreateUdpSocket(port);
  121. Task.Run(() => StartListening());
  122. }
  123. private async void StartListening()
  124. {
  125. while (!_isDisposed)
  126. {
  127. try
  128. {
  129. var result = await _udpClient.ReceiveAsync().ConfigureAwait(false);
  130. OnMessageReceived(result);
  131. }
  132. catch (ObjectDisposedException)
  133. {
  134. }
  135. catch (OperationCanceledException)
  136. {
  137. }
  138. catch (Exception ex)
  139. {
  140. _logger.ErrorException("Error receiving udp message", ex);
  141. }
  142. }
  143. }
  144. /// <summary>
  145. /// Called when [message received].
  146. /// </summary>
  147. /// <param name="message">The message.</param>
  148. private void OnMessageReceived(SocketReceiveResult message)
  149. {
  150. if (_isDisposed)
  151. {
  152. return;
  153. }
  154. if (message.RemoteEndPoint.Port == 0)
  155. {
  156. return;
  157. }
  158. try
  159. {
  160. OnMessageReceived(new GenericEventArgs<SocketReceiveResult>
  161. {
  162. Argument = message
  163. });
  164. }
  165. catch (Exception ex)
  166. {
  167. _logger.ErrorException("Error handling UDP message", ex);
  168. }
  169. }
  170. /// <summary>
  171. /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
  172. /// </summary>
  173. public void Dispose()
  174. {
  175. Dispose(true);
  176. GC.SuppressFinalize(this);
  177. }
  178. /// <summary>
  179. /// Stops this instance.
  180. /// </summary>
  181. public void Stop()
  182. {
  183. _isDisposed = true;
  184. if (_udpClient != null)
  185. {
  186. _udpClient.Dispose();
  187. }
  188. }
  189. /// <summary>
  190. /// Releases unmanaged and - optionally - managed resources.
  191. /// </summary>
  192. /// <param name="dispose"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
  193. protected virtual void Dispose(bool dispose)
  194. {
  195. if (dispose)
  196. {
  197. Stop();
  198. }
  199. }
  200. public async Task SendAsync(byte[] bytes, IpEndPointInfo remoteEndPoint)
  201. {
  202. if (_isDisposed)
  203. {
  204. throw new ObjectDisposedException(GetType().Name);
  205. }
  206. if (bytes == null)
  207. {
  208. throw new ArgumentNullException("bytes");
  209. }
  210. if (remoteEndPoint == null)
  211. {
  212. throw new ArgumentNullException("remoteEndPoint");
  213. }
  214. try
  215. {
  216. await _udpClient.SendAsync(bytes, bytes.Length, remoteEndPoint, CancellationToken.None).ConfigureAwait(false);
  217. _logger.Info("Udp message sent to {0}", remoteEndPoint);
  218. }
  219. catch (Exception ex)
  220. {
  221. _logger.ErrorException("Error sending message to {0}", ex, remoteEndPoint);
  222. }
  223. }
  224. }
  225. }