UdpServer.cs 8.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285
  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 ISocket _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(() => BeginReceive());
  122. }
  123. private readonly byte[] _receiveBuffer = new byte[8192];
  124. private void BeginReceive()
  125. {
  126. if (_isDisposed)
  127. {
  128. return;
  129. }
  130. try
  131. {
  132. var result = _udpClient.BeginReceive(_receiveBuffer, 0, _receiveBuffer.Length, OnReceiveResult);
  133. if (result.CompletedSynchronously)
  134. {
  135. OnReceiveResult(result);
  136. }
  137. }
  138. catch (ObjectDisposedException)
  139. {
  140. }
  141. catch (Exception ex)
  142. {
  143. _logger.ErrorException("Error receiving udp message", ex);
  144. }
  145. }
  146. private void OnReceiveResult(IAsyncResult result)
  147. {
  148. if (_isDisposed)
  149. {
  150. return;
  151. }
  152. try
  153. {
  154. var socketResult = _udpClient.EndReceive(result);
  155. OnMessageReceived(socketResult);
  156. }
  157. catch (ObjectDisposedException)
  158. {
  159. }
  160. catch (Exception ex)
  161. {
  162. _logger.ErrorException("Error receiving udp message", ex);
  163. }
  164. BeginReceive();
  165. }
  166. /// <summary>
  167. /// Called when [message received].
  168. /// </summary>
  169. /// <param name="message">The message.</param>
  170. private void OnMessageReceived(SocketReceiveResult message)
  171. {
  172. if (_isDisposed)
  173. {
  174. return;
  175. }
  176. if (message.RemoteEndPoint.Port == 0)
  177. {
  178. return;
  179. }
  180. try
  181. {
  182. OnMessageReceived(new GenericEventArgs<SocketReceiveResult>
  183. {
  184. Argument = message
  185. });
  186. }
  187. catch (Exception ex)
  188. {
  189. _logger.ErrorException("Error handling UDP message", ex);
  190. }
  191. }
  192. /// <summary>
  193. /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
  194. /// </summary>
  195. public void Dispose()
  196. {
  197. Dispose(true);
  198. GC.SuppressFinalize(this);
  199. }
  200. /// <summary>
  201. /// Releases unmanaged and - optionally - managed resources.
  202. /// </summary>
  203. /// <param name="dispose"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
  204. protected virtual void Dispose(bool dispose)
  205. {
  206. if (dispose)
  207. {
  208. _isDisposed = true;
  209. if (_udpClient != null)
  210. {
  211. _udpClient.Dispose();
  212. }
  213. }
  214. }
  215. public async Task SendAsync(byte[] bytes, IpEndPointInfo remoteEndPoint)
  216. {
  217. if (_isDisposed)
  218. {
  219. throw new ObjectDisposedException(GetType().Name);
  220. }
  221. if (bytes == null)
  222. {
  223. throw new ArgumentNullException("bytes");
  224. }
  225. if (remoteEndPoint == null)
  226. {
  227. throw new ArgumentNullException("remoteEndPoint");
  228. }
  229. try
  230. {
  231. await _udpClient.SendToAsync(bytes, 0, bytes.Length, remoteEndPoint, CancellationToken.None).ConfigureAwait(false);
  232. _logger.Info("Udp message sent to {0}", remoteEndPoint);
  233. }
  234. catch (OperationCanceledException)
  235. {
  236. }
  237. catch (Exception ex)
  238. {
  239. _logger.ErrorException("Error sending message to {0}", ex, remoteEndPoint);
  240. }
  241. }
  242. }
  243. }