UdpServer.cs 11 KB

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