UdpServer.cs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328
  1. using MediaBrowser.Common.Net;
  2. using MediaBrowser.Controller;
  3. using MediaBrowser.Model.ApiClient;
  4. using MediaBrowser.Model.Logging;
  5. using MediaBrowser.Model.Serialization;
  6. using System;
  7. using System.Collections.Generic;
  8. using System.Linq;
  9. using System.Net;
  10. using System.Net.Sockets;
  11. using System.Text;
  12. using System.Threading.Tasks;
  13. using Emby.Common.Implementations.Networking;
  14. namespace MediaBrowser.Server.Implementations.Udp
  15. {
  16. /// <summary>
  17. /// Provides a Udp Server
  18. /// </summary>
  19. public class UdpServer : IDisposable
  20. {
  21. /// <summary>
  22. /// The _logger
  23. /// </summary>
  24. private readonly ILogger _logger;
  25. /// <summary>
  26. /// The _network manager
  27. /// </summary>
  28. private readonly INetworkManager _networkManager;
  29. private bool _isDisposed;
  30. private readonly List<Tuple<string, bool, Func<string, string, Encoding, Task>>> _responders = new List<Tuple<string, bool, Func<string, string, Encoding, Task>>>();
  31. private readonly IServerApplicationHost _appHost;
  32. private readonly IJsonSerializer _json;
  33. /// <summary>
  34. /// Initializes a new instance of the <see cref="UdpServer" /> class.
  35. /// </summary>
  36. /// <param name="logger">The logger.</param>
  37. /// <param name="networkManager">The network manager.</param>
  38. /// <param name="appHost">The application host.</param>
  39. /// <param name="json">The json.</param>
  40. public UdpServer(ILogger logger, INetworkManager networkManager, IServerApplicationHost appHost, IJsonSerializer json)
  41. {
  42. _logger = logger;
  43. _networkManager = networkManager;
  44. _appHost = appHost;
  45. _json = json;
  46. AddMessageResponder("who is EmbyServer?", true, RespondToV2Message);
  47. AddMessageResponder("who is MediaBrowserServer_v2?", false, RespondToV2Message);
  48. }
  49. private void AddMessageResponder(string message, bool isSubstring, Func<string, string, Encoding, Task> responder)
  50. {
  51. _responders.Add(new Tuple<string, bool, Func<string, string, Encoding, Task>>(message, isSubstring, responder));
  52. }
  53. /// <summary>
  54. /// Raises the <see cref="E:MessageReceived" /> event.
  55. /// </summary>
  56. /// <param name="e">The <see cref="UdpMessageReceivedEventArgs"/> instance containing the event data.</param>
  57. private async void OnMessageReceived(UdpMessageReceivedEventArgs e)
  58. {
  59. var encoding = Encoding.UTF8;
  60. var responder = GetResponder(e.Bytes, encoding);
  61. if (responder == null)
  62. {
  63. encoding = Encoding.Unicode;
  64. responder = GetResponder(e.Bytes, encoding);
  65. }
  66. if (responder != null)
  67. {
  68. try
  69. {
  70. await responder.Item2.Item3(responder.Item1, e.RemoteEndPoint, encoding).ConfigureAwait(false);
  71. }
  72. catch (Exception ex)
  73. {
  74. _logger.ErrorException("Error in OnMessageReceived", ex);
  75. }
  76. }
  77. }
  78. private Tuple<string, Tuple<string, bool, Func<string, string, Encoding, Task>>> GetResponder(byte[] bytes, Encoding encoding)
  79. {
  80. var text = encoding.GetString(bytes);
  81. var responder = _responders.FirstOrDefault(i =>
  82. {
  83. if (i.Item2)
  84. {
  85. return text.IndexOf(i.Item1, StringComparison.OrdinalIgnoreCase) != -1;
  86. }
  87. return string.Equals(i.Item1, text, StringComparison.OrdinalIgnoreCase);
  88. });
  89. if (responder == null)
  90. {
  91. return null;
  92. }
  93. return new Tuple<string, Tuple<string, bool, Func<string, string, Encoding, Task>>>(text, responder);
  94. }
  95. private async Task RespondToV2Message(string messageText, string endpoint, Encoding encoding)
  96. {
  97. var parts = messageText.Split('|');
  98. var localUrl = await _appHost.GetLocalApiUrl().ConfigureAwait(false);
  99. if (!string.IsNullOrEmpty(localUrl))
  100. {
  101. var response = new ServerDiscoveryInfo
  102. {
  103. Address = localUrl,
  104. Id = _appHost.SystemId,
  105. Name = _appHost.FriendlyName
  106. };
  107. await SendAsync(encoding.GetBytes(_json.SerializeToString(response)), endpoint).ConfigureAwait(false);
  108. if (parts.Length > 1)
  109. {
  110. _appHost.EnableLoopback(parts[1]);
  111. }
  112. }
  113. else
  114. {
  115. _logger.Warn("Unable to respond to udp request because the local ip address could not be determined.");
  116. }
  117. }
  118. /// <summary>
  119. /// The _udp client
  120. /// </summary>
  121. private UdpClient _udpClient;
  122. /// <summary>
  123. /// Starts the specified port.
  124. /// </summary>
  125. /// <param name="port">The port.</param>
  126. public void Start(int port)
  127. {
  128. _udpClient = new UdpClient(new IPEndPoint(IPAddress.Any, port));
  129. _udpClient.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
  130. Task.Run(() => StartListening());
  131. }
  132. private async void StartListening()
  133. {
  134. while (!_isDisposed)
  135. {
  136. try
  137. {
  138. var result = await GetResult().ConfigureAwait(false);
  139. OnMessageReceived(result);
  140. }
  141. catch (ObjectDisposedException)
  142. {
  143. break;
  144. }
  145. catch (Exception ex)
  146. {
  147. _logger.ErrorException("Error in StartListening", ex);
  148. }
  149. }
  150. }
  151. private Task<UdpReceiveResult> GetResult()
  152. {
  153. try
  154. {
  155. return _udpClient.ReceiveAsync();
  156. }
  157. catch (ObjectDisposedException)
  158. {
  159. return Task.FromResult(new UdpReceiveResult(new byte[] { }, new IPEndPoint(IPAddress.Any, 0)));
  160. }
  161. catch (Exception ex)
  162. {
  163. _logger.ErrorException("Error receiving udp message", ex);
  164. return Task.FromResult(new UdpReceiveResult(new byte[] { }, new IPEndPoint(IPAddress.Any, 0)));
  165. }
  166. }
  167. /// <summary>
  168. /// Called when [message received].
  169. /// </summary>
  170. /// <param name="message">The message.</param>
  171. private void OnMessageReceived(UdpReceiveResult message)
  172. {
  173. if (message.RemoteEndPoint.Port == 0)
  174. {
  175. return;
  176. }
  177. var bytes = message.Buffer;
  178. try
  179. {
  180. OnMessageReceived(new UdpMessageReceivedEventArgs
  181. {
  182. Bytes = bytes,
  183. RemoteEndPoint = message.RemoteEndPoint.ToString()
  184. });
  185. }
  186. catch (Exception ex)
  187. {
  188. _logger.ErrorException("Error handling UDP message", ex);
  189. }
  190. }
  191. /// <summary>
  192. /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
  193. /// </summary>
  194. public void Dispose()
  195. {
  196. Dispose(true);
  197. GC.SuppressFinalize(this);
  198. }
  199. /// <summary>
  200. /// Stops this instance.
  201. /// </summary>
  202. public void Stop()
  203. {
  204. _isDisposed = true;
  205. if (_udpClient != null)
  206. {
  207. _udpClient.Close();
  208. }
  209. }
  210. /// <summary>
  211. /// Releases unmanaged and - optionally - managed resources.
  212. /// </summary>
  213. /// <param name="dispose"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
  214. protected virtual void Dispose(bool dispose)
  215. {
  216. if (dispose)
  217. {
  218. Stop();
  219. }
  220. }
  221. /// <summary>
  222. /// Sends the async.
  223. /// </summary>
  224. /// <param name="data">The data.</param>
  225. /// <param name="ipAddress">The ip address.</param>
  226. /// <param name="port">The port.</param>
  227. /// <returns>Task{System.Int32}.</returns>
  228. /// <exception cref="System.ArgumentNullException">data</exception>
  229. public Task SendAsync(string data, string ipAddress, int port)
  230. {
  231. return SendAsync(Encoding.UTF8.GetBytes(data), ipAddress, port);
  232. }
  233. /// <summary>
  234. /// Sends the async.
  235. /// </summary>
  236. /// <param name="bytes">The bytes.</param>
  237. /// <param name="ipAddress">The ip address.</param>
  238. /// <param name="port">The port.</param>
  239. /// <returns>Task{System.Int32}.</returns>
  240. /// <exception cref="System.ArgumentNullException">bytes</exception>
  241. public Task SendAsync(byte[] bytes, string ipAddress, int port)
  242. {
  243. if (bytes == null)
  244. {
  245. throw new ArgumentNullException("bytes");
  246. }
  247. if (string.IsNullOrEmpty(ipAddress))
  248. {
  249. throw new ArgumentNullException("ipAddress");
  250. }
  251. return _udpClient.SendAsync(bytes, bytes.Length, ipAddress, port);
  252. }
  253. /// <summary>
  254. /// Sends the async.
  255. /// </summary>
  256. /// <param name="bytes">The bytes.</param>
  257. /// <param name="remoteEndPoint">The remote end point.</param>
  258. /// <returns>Task.</returns>
  259. /// <exception cref="System.ArgumentNullException">
  260. /// bytes
  261. /// or
  262. /// remoteEndPoint
  263. /// </exception>
  264. public async Task SendAsync(byte[] bytes, string remoteEndPoint)
  265. {
  266. if (bytes == null)
  267. {
  268. throw new ArgumentNullException("bytes");
  269. }
  270. if (string.IsNullOrEmpty(remoteEndPoint))
  271. {
  272. throw new ArgumentNullException("remoteEndPoint");
  273. }
  274. try
  275. {
  276. // Need to do this until Common will compile with this method
  277. var nativeNetworkManager = (BaseNetworkManager) _networkManager;
  278. await _udpClient.SendAsync(bytes, bytes.Length, nativeNetworkManager.Parse(remoteEndPoint)).ConfigureAwait(false);
  279. _logger.Info("Udp message sent to {0}", remoteEndPoint);
  280. }
  281. catch (Exception ex)
  282. {
  283. _logger.ErrorException("Error sending message to {0}", ex, remoteEndPoint);
  284. }
  285. }
  286. }
  287. }