UdpServer.cs 11 KB

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