SsdpCommunicationsServer.cs 21 KB

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