SsdpCommunicationsServer.cs 20 KB

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