UdpServer.cs 7.8 KB

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