SsdpCommunicationsServer.cs 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Net;
  5. using System.Net.Http;
  6. using System.Text;
  7. using System.Threading.Tasks;
  8. using MediaBrowser.Common.Net;
  9. using MediaBrowser.Model.Logging;
  10. using MediaBrowser.Model.Net;
  11. namespace Rssdp.Infrastructure
  12. {
  13. /// <summary>
  14. /// Provides the platform independent logic for publishing device existence and responding to search requests.
  15. /// </summary>
  16. public sealed class SsdpCommunicationsServer : DisposableManagedObjectBase, ISsdpCommunicationsServer
  17. {
  18. #region Fields
  19. /*
  20. We could technically use one socket listening on port 1900 for everything.
  21. This should get both multicast (notifications) and unicast (search response) messages, however
  22. this often doesn't work under Windows because the MS SSDP service is running. If that service
  23. is running then it will steal the unicast messages and we will never see search responses.
  24. Since stopping the service would be a bad idea (might not be allowed security wise and might
  25. break other apps running on the system) the only other work around is to use two sockets.
  26. We use one socket to listen for/receive notifications and search requests (_BroadcastListenSocket).
  27. We use a second socket, bound to a different local port, to send search requests and listen for
  28. responses (_SendSocket). The responses are sent to the local port this socket is bound to,
  29. which isn't port 1900 so the MS service doesn't steal them. While the caller can specify a local
  30. port to use, we will default to 0 which allows the underlying system to auto-assign a free port.
  31. */
  32. private object _BroadcastListenSocketSynchroniser = new object();
  33. private IUdpSocket _BroadcastListenSocket;
  34. private object _SendSocketSynchroniser = new object();
  35. private List<IUdpSocket> _sendSockets;
  36. private HttpRequestParser _RequestParser;
  37. private HttpResponseParser _ResponseParser;
  38. private readonly ILogger _logger;
  39. private ISocketFactory _SocketFactory;
  40. private readonly INetworkManager _networkManager;
  41. private int _LocalPort;
  42. private int _MulticastTtl;
  43. private bool _IsShared;
  44. private readonly bool _enableMultiSocketBinding;
  45. #endregion
  46. #region Events
  47. /// <summary>
  48. /// Raised when a HTTPU request message is received by a socket (unicast or multicast).
  49. /// </summary>
  50. public event EventHandler<RequestReceivedEventArgs> RequestReceived;
  51. /// <summary>
  52. /// Raised when an HTTPU response message is received by a socket (unicast or multicast).
  53. /// </summary>
  54. public event EventHandler<ResponseReceivedEventArgs> ResponseReceived;
  55. #endregion
  56. #region Constructors
  57. /// <summary>
  58. /// Minimum constructor.
  59. /// </summary>
  60. /// <exception cref="System.ArgumentNullException">The <paramref name="socketFactory"/> argument is null.</exception>
  61. public SsdpCommunicationsServer(ISocketFactory socketFactory, INetworkManager networkManager, ILogger logger, bool enableMultiSocketBinding)
  62. : this(socketFactory, 0, SsdpConstants.SsdpDefaultMulticastTimeToLive, networkManager, logger, enableMultiSocketBinding)
  63. {
  64. }
  65. /// <summary>
  66. /// Full constructor.
  67. /// </summary>
  68. /// <exception cref="System.ArgumentNullException">The <paramref name="socketFactory"/> argument is null.</exception>
  69. /// <exception cref="System.ArgumentOutOfRangeException">The <paramref name="multicastTimeToLive"/> argument is less than or equal to zero.</exception>
  70. public SsdpCommunicationsServer(ISocketFactory socketFactory, int localPort, int multicastTimeToLive, INetworkManager networkManager, ILogger logger, bool enableMultiSocketBinding)
  71. {
  72. if (socketFactory == null) throw new ArgumentNullException("socketFactory");
  73. if (multicastTimeToLive <= 0) throw new ArgumentOutOfRangeException("multicastTimeToLive", "multicastTimeToLive must be greater than zero.");
  74. _BroadcastListenSocketSynchroniser = new object();
  75. _SendSocketSynchroniser = new object();
  76. _LocalPort = localPort;
  77. _SocketFactory = socketFactory;
  78. _RequestParser = new HttpRequestParser();
  79. _ResponseParser = new HttpResponseParser();
  80. _MulticastTtl = multicastTimeToLive;
  81. _networkManager = networkManager;
  82. _logger = logger;
  83. _enableMultiSocketBinding = enableMultiSocketBinding;
  84. }
  85. #endregion
  86. #region Public Methods
  87. /// <summary>
  88. /// Causes the server to begin listening for multicast messages, being SSDP search requests and notifications.
  89. /// </summary>
  90. /// <exception cref="System.ObjectDisposedException">Thrown if the <see cref="DisposableManagedObjectBase.IsDisposed"/> property is true (because <seealso cref="DisposableManagedObjectBase.Dispose()" /> has been called previously).</exception>
  91. public void BeginListeningForBroadcasts()
  92. {
  93. ThrowIfDisposed();
  94. if (_BroadcastListenSocket == null)
  95. {
  96. lock (_BroadcastListenSocketSynchroniser)
  97. {
  98. if (_BroadcastListenSocket == null)
  99. _BroadcastListenSocket = ListenForBroadcastsAsync();
  100. }
  101. }
  102. }
  103. /// <summary>
  104. /// Causes the server to stop listening for multicast messages, being SSDP search requests and notifications.
  105. /// </summary>
  106. /// <exception cref="System.ObjectDisposedException">Thrown if the <see cref="DisposableManagedObjectBase.IsDisposed"/> property is true (because <seealso cref="DisposableManagedObjectBase.Dispose()" /> has been called previously).</exception>
  107. public void StopListeningForBroadcasts()
  108. {
  109. ThrowIfDisposed();
  110. lock (_BroadcastListenSocketSynchroniser)
  111. {
  112. if (_BroadcastListenSocket != null)
  113. {
  114. _BroadcastListenSocket.Dispose();
  115. _BroadcastListenSocket = null;
  116. }
  117. }
  118. }
  119. /// <summary>
  120. /// Sends a message to a particular address (uni or multicast) and port.
  121. /// </summary>
  122. /// <param name="messageData">A byte array containing the data to send.</param>
  123. /// <param name="destination">A <see cref="IpEndPointInfo"/> representing the destination address for the data. Can be either a multicast or unicast destination.</param>
  124. /// <param name="fromLocalIpAddress">A <see cref="IpEndPointInfo"/> The local ip address to send from, or .Any if sending from all available</param>
  125. /// <exception cref="System.ArgumentNullException">Thrown if the <paramref name="messageData"/> argument is null.</exception>
  126. /// <exception cref="System.ObjectDisposedException">Thrown if the <see cref="DisposableManagedObjectBase.IsDisposed"/> property is true (because <seealso cref="DisposableManagedObjectBase.Dispose()" /> has been called previously).</exception>
  127. public async Task SendMessage(byte[] messageData, IpEndPointInfo destination, IpAddressInfo fromLocalIpAddress)
  128. {
  129. if (messageData == null) throw new ArgumentNullException("messageData");
  130. ThrowIfDisposed();
  131. var sockets = GetSendSockets(fromLocalIpAddress, destination);
  132. if (sockets.Count == 0)
  133. {
  134. return;
  135. }
  136. // SSDP spec recommends sending messages multiple times (not more than 3) to account for possible packet loss over UDP.
  137. for (var i = 0; i < SsdpConstants.UdpResendCount; i++)
  138. {
  139. var tasks = sockets.Select(s => SendFromSocket(s, messageData, destination)).ToArray();
  140. await Task.WhenAll(tasks).ConfigureAwait(false);
  141. await Task.Delay(100).ConfigureAwait(false);
  142. }
  143. }
  144. private async Task SendFromSocket(IUdpSocket socket, byte[] messageData, IpEndPointInfo destination)
  145. {
  146. try
  147. {
  148. await socket.SendAsync(messageData, messageData.Length, destination).ConfigureAwait(false);
  149. }
  150. catch (ObjectDisposedException)
  151. {
  152. }
  153. catch (Exception ex)
  154. {
  155. _logger.ErrorException("Error sending socket message from {0} to {1}", ex, socket.LocalIPAddress.ToString(), destination.ToString());
  156. }
  157. }
  158. private List<IUdpSocket> GetSendSockets(IpAddressInfo fromLocalIpAddress, IpEndPointInfo destination)
  159. {
  160. EnsureSendSocketCreated();
  161. lock (_SendSocketSynchroniser)
  162. {
  163. var sockets = _sendSockets.Where(i => i.LocalIPAddress.AddressFamily == fromLocalIpAddress.AddressFamily);
  164. // Send from the Any socket and the socket with the matching address
  165. if (fromLocalIpAddress.AddressFamily == IpAddressFamily.InterNetwork)
  166. {
  167. sockets = sockets.Where(i => i.LocalIPAddress.Equals(IpAddressInfo.Any) || fromLocalIpAddress.Equals(i.LocalIPAddress));
  168. // If sending to the loopback address, filter the socket list as well
  169. if (destination.IpAddress.Equals(IpAddressInfo.Loopback))
  170. {
  171. sockets = sockets.Where(i => i.LocalIPAddress.Equals(IpAddressInfo.Any) || i.LocalIPAddress.Equals(IpAddressInfo.Loopback));
  172. }
  173. }
  174. else if (fromLocalIpAddress.AddressFamily == IpAddressFamily.InterNetworkV6)
  175. {
  176. sockets = sockets.Where(i => i.LocalIPAddress.Equals(IpAddressInfo.IPv6Any) || fromLocalIpAddress.Equals(i.LocalIPAddress));
  177. // If sending to the loopback address, filter the socket list as well
  178. if (destination.IpAddress.Equals(IpAddressInfo.IPv6Loopback))
  179. {
  180. sockets = sockets.Where(i => i.LocalIPAddress.Equals(IpAddressInfo.IPv6Any) || i.LocalIPAddress.Equals(IpAddressInfo.IPv6Loopback));
  181. }
  182. }
  183. return sockets.ToList();
  184. }
  185. }
  186. /// <summary>
  187. /// Sends a message to the SSDP multicast address and port.
  188. /// </summary>
  189. public async Task SendMulticastMessage(string message)
  190. {
  191. if (message == null) throw new ArgumentNullException("messageData");
  192. byte[] messageData = Encoding.UTF8.GetBytes(message);
  193. ThrowIfDisposed();
  194. EnsureSendSocketCreated();
  195. // SSDP spec recommends sending messages multiple times (not more than 3) to account for possible packet loss over UDP.
  196. for (var i = 0; i < SsdpConstants.UdpResendCount; i++)
  197. {
  198. await SendMessageIfSocketNotDisposed(messageData, new IpEndPointInfo
  199. {
  200. IpAddress = new IpAddressInfo
  201. {
  202. Address = SsdpConstants.MulticastLocalAdminAddress
  203. },
  204. Port = SsdpConstants.MulticastPort
  205. }).ConfigureAwait(false);
  206. await Task.Delay(100).ConfigureAwait(false);
  207. }
  208. }
  209. /// <summary>
  210. /// Stops listening for search responses on the local, unicast socket.
  211. /// </summary>
  212. /// <exception cref="System.ObjectDisposedException">Thrown if the <see cref="DisposableManagedObjectBase.IsDisposed"/> property is true (because <seealso cref="DisposableManagedObjectBase.Dispose()" /> has been called previously).</exception>
  213. public void StopListeningForResponses()
  214. {
  215. ThrowIfDisposed();
  216. lock (_SendSocketSynchroniser)
  217. {
  218. if (_sendSockets != null)
  219. {
  220. var sockets = _sendSockets.ToList();
  221. _sendSockets = null;
  222. foreach (var socket in sockets)
  223. {
  224. socket.Dispose();
  225. }
  226. }
  227. }
  228. }
  229. #endregion
  230. #region Public Properties
  231. /// <summary>
  232. /// Gets or sets a boolean value indicating whether or not this instance is shared amongst multiple <see cref="SsdpDeviceLocatorBase"/> and/or <see cref="ISsdpDevicePublisher"/> instances.
  233. /// </summary>
  234. /// <remarks>
  235. /// <para>If true, disposing an instance of a <see cref="SsdpDeviceLocatorBase"/>or a <see cref="ISsdpDevicePublisher"/> will not dispose this comms server instance. The calling code is responsible for managing the lifetime of the server.</para>
  236. /// </remarks>
  237. public bool IsShared
  238. {
  239. get { return _IsShared; }
  240. set { _IsShared = value; }
  241. }
  242. #endregion
  243. #region Overrides
  244. /// <summary>
  245. /// Stops listening for requests, disposes this instance and all internal resources.
  246. /// </summary>
  247. /// <param name="disposing"></param>
  248. protected override void Dispose(bool disposing)
  249. {
  250. if (disposing)
  251. {
  252. lock (_BroadcastListenSocketSynchroniser)
  253. {
  254. if (_BroadcastListenSocket != null)
  255. _BroadcastListenSocket.Dispose();
  256. }
  257. lock (_SendSocketSynchroniser)
  258. {
  259. if (_sendSockets != null)
  260. {
  261. var sockets = _sendSockets.ToList();
  262. _sendSockets = null;
  263. foreach (var socket in sockets)
  264. {
  265. socket.Dispose();
  266. }
  267. }
  268. }
  269. }
  270. }
  271. #endregion
  272. #region Private Methods
  273. private async Task SendMessageIfSocketNotDisposed(byte[] messageData, IpEndPointInfo destination)
  274. {
  275. var sockets = _sendSockets;
  276. if (sockets != null)
  277. {
  278. sockets = sockets.ToList();
  279. foreach (var socket in sockets)
  280. {
  281. await socket.SendAsync(messageData, messageData.Length, destination).ConfigureAwait(false);
  282. }
  283. }
  284. ThrowIfDisposed();
  285. }
  286. private IUdpSocket ListenForBroadcastsAsync()
  287. {
  288. var socket = _SocketFactory.CreateUdpMulticastSocket(SsdpConstants.MulticastLocalAdminAddress, _MulticastTtl, SsdpConstants.MulticastPort);
  289. ListenToSocket(socket);
  290. return socket;
  291. }
  292. private List<IUdpSocket> CreateSocketAndListenForResponsesAsync()
  293. {
  294. var sockets = new List<IUdpSocket>();
  295. sockets.Add(_SocketFactory.CreateSsdpUdpSocket(IpAddressInfo.Any, _LocalPort));
  296. if (_enableMultiSocketBinding)
  297. {
  298. foreach (var address in _networkManager.GetLocalIpAddresses().ToList())
  299. {
  300. try
  301. {
  302. sockets.Add(_SocketFactory.CreateSsdpUdpSocket(address, _LocalPort));
  303. }
  304. catch (Exception ex)
  305. {
  306. _logger.ErrorException("Error in CreateSsdpUdpSocket. IPAddress: {0}", ex, address);
  307. }
  308. }
  309. }
  310. foreach (var socket in sockets)
  311. {
  312. ListenToSocket(socket);
  313. }
  314. return sockets;
  315. }
  316. [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1804:RemoveUnusedLocals", MessageId = "t", Justification = "Capturing task to local variable removes compiler warning, task is not otherwise required.")]
  317. private void ListenToSocket(IUdpSocket socket)
  318. {
  319. // Tasks are captured to local variables even if we don't use them just to avoid compiler warnings.
  320. var t = Task.Run(async () =>
  321. {
  322. var cancelled = false;
  323. while (!cancelled)
  324. {
  325. try
  326. {
  327. var result = await socket.ReceiveAsync().ConfigureAwait(false);
  328. if (result.ReceivedBytes > 0)
  329. {
  330. // Strange cannot convert compiler error here if I don't explicitly
  331. // assign or cast to Action first. Assignment is easier to read,
  332. // so went with that.
  333. ProcessMessage(System.Text.UTF8Encoding.UTF8.GetString(result.Buffer, 0, result.ReceivedBytes), result.RemoteEndPoint, result.LocalIPAddress);
  334. }
  335. }
  336. catch (ObjectDisposedException)
  337. {
  338. cancelled = true;
  339. }
  340. catch (TaskCanceledException)
  341. {
  342. cancelled = true;
  343. }
  344. }
  345. });
  346. }
  347. private void EnsureSendSocketCreated()
  348. {
  349. if (_sendSockets == null)
  350. {
  351. lock (_SendSocketSynchroniser)
  352. {
  353. if (_sendSockets == null)
  354. {
  355. _sendSockets = CreateSocketAndListenForResponsesAsync();
  356. }
  357. }
  358. }
  359. }
  360. private void ProcessMessage(string data, IpEndPointInfo endPoint, IpAddressInfo receivedOnLocalIpAddress)
  361. {
  362. //Responses start with the HTTP version, prefixed with HTTP/ while
  363. //requests start with a method which can vary and might be one we haven't
  364. //seen/don't know. We'll check if this message is a request or a response
  365. //by checking for the static HTTP/ prefix on the start of the message.
  366. if (data.StartsWith("HTTP/", StringComparison.OrdinalIgnoreCase))
  367. {
  368. HttpResponseMessage responseMessage = null;
  369. try
  370. {
  371. responseMessage = _ResponseParser.Parse(data);
  372. }
  373. catch (ArgumentException ex)
  374. {
  375. // Ignore invalid packets.
  376. }
  377. if (responseMessage != null)
  378. OnResponseReceived(responseMessage, endPoint);
  379. }
  380. else
  381. {
  382. HttpRequestMessage requestMessage = null;
  383. try
  384. {
  385. requestMessage = _RequestParser.Parse(data);
  386. }
  387. catch (ArgumentException ex)
  388. {
  389. // Ignore invalid packets.
  390. }
  391. if (requestMessage != null)
  392. {
  393. OnRequestReceived(requestMessage, endPoint, receivedOnLocalIpAddress);
  394. }
  395. }
  396. }
  397. private void OnRequestReceived(HttpRequestMessage data, IpEndPointInfo remoteEndPoint, IpAddressInfo receivedOnLocalIpAddress)
  398. {
  399. //SSDP specification says only * is currently used but other uri's might
  400. //be implemented in the future and should be ignored unless understood.
  401. //Section 4.2 - http://tools.ietf.org/html/draft-cai-ssdp-v1-03#page-11
  402. if (data.RequestUri.ToString() != "*")
  403. {
  404. return;
  405. }
  406. var handlers = this.RequestReceived;
  407. if (handlers != null)
  408. handlers(this, new RequestReceivedEventArgs(data, remoteEndPoint, receivedOnLocalIpAddress));
  409. }
  410. private void OnResponseReceived(HttpResponseMessage data, IpEndPointInfo endPoint)
  411. {
  412. var handlers = this.ResponseReceived;
  413. if (handlers != null)
  414. handlers(this, new ResponseReceivedEventArgs(data, endPoint));
  415. }
  416. #endregion
  417. }
  418. }