SsdpCommunicationsServer.cs 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400
  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. namespace Rssdp.Infrastructure
  9. {
  10. /// <summary>
  11. /// Provides the platform independent logic for publishing device existence and responding to search requests.
  12. /// </summary>
  13. public sealed class SsdpCommunicationsServer : DisposableManagedObjectBase, ISsdpCommunicationsServer
  14. {
  15. #region Fields
  16. /*
  17. We could technically use one socket listening on port 1900 for everything.
  18. This should get both multicast (notifications) and unicast (search response) messages, however
  19. this often doesn't work under Windows because the MS SSDP service is running. If that service
  20. is running then it will steal the unicast messages and we will never see search responses.
  21. Since stopping the service would be a bad idea (might not be allowed security wise and might
  22. break other apps running on the system) the only other work around is to use two sockets.
  23. We use one socket to listen for/receive notifications and search requests (_BroadcastListenSocket).
  24. We use a second socket, bound to a different local port, to send search requests and listen for
  25. responses (_SendSocket). The responses are sent to the local port this socket is bound to,
  26. which isn't port 1900 so the MS service doesn't steal them. While the caller can specify a local
  27. port to use, we will default to 0 which allows the underlying system to auto-assign a free port.
  28. */
  29. private object _BroadcastListenSocketSynchroniser = new object();
  30. private IUdpSocket _BroadcastListenSocket;
  31. private object _SendSocketSynchroniser = new object();
  32. private IUdpSocket _SendSocket;
  33. private HttpRequestParser _RequestParser;
  34. private HttpResponseParser _ResponseParser;
  35. private ISocketFactory _SocketFactory;
  36. private int _LocalPort;
  37. private int _MulticastTtl;
  38. private bool _IsShared;
  39. #endregion
  40. #region Events
  41. /// <summary>
  42. /// Raised when a HTTPU request message is received by a socket (unicast or multicast).
  43. /// </summary>
  44. public event EventHandler<RequestReceivedEventArgs> RequestReceived;
  45. /// <summary>
  46. /// Raised when an HTTPU response message is received by a socket (unicast or multicast).
  47. /// </summary>
  48. public event EventHandler<ResponseReceivedEventArgs> ResponseReceived;
  49. #endregion
  50. #region Constructors
  51. /// <summary>
  52. /// Minimum constructor.
  53. /// </summary>
  54. /// <param name="socketFactory">An implementation of the <see cref="ISocketFactory"/> interface that can be used to make new unicast and multicast sockets. Cannot be null.</param>
  55. /// <exception cref="System.ArgumentNullException">The <paramref name="socketFactory"/> argument is null.</exception>
  56. public SsdpCommunicationsServer(ISocketFactory socketFactory)
  57. : this(socketFactory, 0, SsdpConstants.SsdpDefaultMulticastTimeToLive)
  58. {
  59. }
  60. /// <summary>
  61. /// Partial constructor.
  62. /// </summary>
  63. /// <param name="socketFactory">An implementation of the <see cref="ISocketFactory"/> interface that can be used to make new unicast and multicast sockets. Cannot be null.</param>
  64. /// <param name="localPort">The specific local port to use for all sockets created by this instance. Specify zero to indicate the system should choose a free port itself.</param>
  65. /// <exception cref="System.ArgumentNullException">The <paramref name="socketFactory"/> argument is null.</exception>
  66. public SsdpCommunicationsServer(ISocketFactory socketFactory, int localPort)
  67. : this(socketFactory, localPort, SsdpConstants.SsdpDefaultMulticastTimeToLive)
  68. {
  69. }
  70. /// <summary>
  71. /// Full constructor.
  72. /// </summary>
  73. /// <param name="socketFactory">An implementation of the <see cref="ISocketFactory"/> interface that can be used to make new unicast and multicast sockets. Cannot be null.</param>
  74. /// <param name="localPort">The specific local port to use for all sockets created by this instance. Specify zero to indicate the system should choose a free port itself.</param>
  75. /// <param name="multicastTimeToLive">The multicast time to live value for multicast sockets. Technically this is a number of router hops, not a 'Time'. Must be greater than zero.</param>
  76. /// <exception cref="System.ArgumentNullException">The <paramref name="socketFactory"/> argument is null.</exception>
  77. /// <exception cref="System.ArgumentOutOfRangeException">The <paramref name="multicastTimeToLive"/> argument is less than or equal to zero.</exception>
  78. public SsdpCommunicationsServer(ISocketFactory socketFactory, int localPort, int multicastTimeToLive)
  79. {
  80. if (socketFactory == null) throw new ArgumentNullException("socketFactory");
  81. if (multicastTimeToLive <= 0) throw new ArgumentOutOfRangeException("multicastTimeToLive", "multicastTimeToLive must be greater than zero.");
  82. _BroadcastListenSocketSynchroniser = new object();
  83. _SendSocketSynchroniser = new object();
  84. _LocalPort = localPort;
  85. _SocketFactory = socketFactory;
  86. _RequestParser = new HttpRequestParser();
  87. _ResponseParser = new HttpResponseParser();
  88. _MulticastTtl = multicastTimeToLive;
  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="System.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. _BroadcastListenSocket = ListenForBroadcastsAsync();
  105. }
  106. }
  107. }
  108. /// <summary>
  109. /// Causes the server to stop listening for multicast messages, being SSDP search requests and notifications.
  110. /// </summary>
  111. /// <exception cref="System.ObjectDisposedException">Thrown if the <see cref="DisposableManagedObjectBase.IsDisposed"/> property is true (because <seealso cref="DisposableManagedObjectBase.Dispose()" /> has been called previously).</exception>
  112. public void StopListeningForBroadcasts()
  113. {
  114. ThrowIfDisposed();
  115. lock (_BroadcastListenSocketSynchroniser)
  116. {
  117. if (_BroadcastListenSocket != null)
  118. {
  119. _BroadcastListenSocket.Dispose();
  120. _BroadcastListenSocket = null;
  121. }
  122. }
  123. }
  124. /// <summary>
  125. /// Sends a message to a particular address (uni or multicast) and port.
  126. /// </summary>
  127. /// <param name="messageData">A byte array containing the data to send.</param>
  128. /// <param name="destination">A <see cref="UdpEndPoint"/> representing the destination address for the data. Can be either a multicast or unicast destination.</param>
  129. /// <exception cref="System.ArgumentNullException">Thrown if the <paramref name="messageData"/> argument is null.</exception>
  130. /// <exception cref="System.ObjectDisposedException">Thrown if the <see cref="DisposableManagedObjectBase.IsDisposed"/> property is true (because <seealso cref="DisposableManagedObjectBase.Dispose()" /> has been called previously).</exception>
  131. public async Task SendMessage(byte[] messageData, UdpEndPoint destination)
  132. {
  133. if (messageData == null) throw new ArgumentNullException("messageData");
  134. ThrowIfDisposed();
  135. EnsureSendSocketCreated();
  136. // SSDP spec recommends sending messages multiple times (not more than 3) to account for possible packet loss over UDP.
  137. await Repeat(SsdpConstants.UdpResendCount, TimeSpan.FromMilliseconds(100), () => SendMessageIfSocketNotDisposed(messageData, destination)).ConfigureAwait(false);
  138. }
  139. /// <summary>
  140. /// Sends a message to the SSDP multicast address and port.
  141. /// </summary>
  142. /// <param name="messageData">A byte array containing the data to send.</param>
  143. /// <exception cref="System.ArgumentNullException">Thrown if the <paramref name="messageData"/> argument is null.</exception>
  144. /// <exception cref="System.ObjectDisposedException">Thrown if the <see cref="DisposableManagedObjectBase.IsDisposed"/> property is true (because <seealso cref="DisposableManagedObjectBase.Dispose()" /> has been called previously).</exception>
  145. public async Task SendMulticastMessage(byte[] messageData)
  146. {
  147. if (messageData == null) throw new ArgumentNullException("messageData");
  148. ThrowIfDisposed();
  149. EnsureSendSocketCreated();
  150. // SSDP spec recommends sending messages multiple times (not more than 3) to account for possible packet loss over UDP.
  151. await Repeat(SsdpConstants.UdpResendCount, TimeSpan.FromMilliseconds(100),
  152. () => SendMessageIfSocketNotDisposed(messageData, new UdpEndPoint() { IPAddress = SsdpConstants.MulticastLocalAdminAddress, Port = SsdpConstants.MulticastPort })).ConfigureAwait(false);
  153. }
  154. /// <summary>
  155. /// Stops listening for search responses on the local, unicast socket.
  156. /// </summary>
  157. /// <exception cref="System.ObjectDisposedException">Thrown if the <see cref="DisposableManagedObjectBase.IsDisposed"/> property is true (because <seealso cref="DisposableManagedObjectBase.Dispose()" /> has been called previously).</exception>
  158. public void StopListeningForResponses()
  159. {
  160. ThrowIfDisposed();
  161. lock (_SendSocketSynchroniser)
  162. {
  163. var socket = _SendSocket;
  164. _SendSocket = null;
  165. if (socket != null)
  166. socket.Dispose();
  167. }
  168. }
  169. #endregion
  170. #region Public Properties
  171. /// <summary>
  172. /// 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.
  173. /// </summary>
  174. /// <remarks>
  175. /// <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>
  176. /// </remarks>
  177. public bool IsShared
  178. {
  179. get { return _IsShared; }
  180. set { _IsShared = value; }
  181. }
  182. #endregion
  183. #region Overrides
  184. /// <summary>
  185. /// Stops listening for requests, disposes this instance and all internal resources.
  186. /// </summary>
  187. /// <param name="disposing"></param>
  188. protected override void Dispose(bool disposing)
  189. {
  190. if (disposing)
  191. {
  192. lock (_BroadcastListenSocketSynchroniser)
  193. {
  194. if (_BroadcastListenSocket != null)
  195. _BroadcastListenSocket.Dispose();
  196. }
  197. lock (_SendSocketSynchroniser)
  198. {
  199. if (_SendSocket != null)
  200. _SendSocket.Dispose();
  201. }
  202. }
  203. }
  204. #endregion
  205. #region Private Methods
  206. private async Task SendMessageIfSocketNotDisposed(byte[] messageData, UdpEndPoint destination)
  207. {
  208. var socket = _SendSocket;
  209. if (socket != null)
  210. {
  211. await _SendSocket.SendTo(messageData, destination).ConfigureAwait(false);
  212. }
  213. else
  214. {
  215. ThrowIfDisposed();
  216. }
  217. }
  218. private static async Task Repeat(int repetitions, TimeSpan delay, Func<Task> work)
  219. {
  220. for (int cnt = 0; cnt < repetitions; cnt++)
  221. {
  222. await work().ConfigureAwait(false);
  223. if (delay != TimeSpan.Zero)
  224. await Task.Delay(delay).ConfigureAwait(false);
  225. }
  226. }
  227. private IUdpSocket ListenForBroadcastsAsync()
  228. {
  229. var socket = _SocketFactory.CreateUdpMulticastSocket(SsdpConstants.MulticastLocalAdminAddress, _MulticastTtl, SsdpConstants.MulticastPort);
  230. ListenToSocket(socket);
  231. return socket;
  232. }
  233. private IUdpSocket CreateSocketAndListenForResponsesAsync()
  234. {
  235. _SendSocket = _SocketFactory.CreateUdpSocket(_LocalPort);
  236. ListenToSocket(_SendSocket);
  237. return _SendSocket;
  238. }
  239. [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1804:RemoveUnusedLocals", MessageId = "t", Justification = "Capturing task to local variable removes compiler warning, task is not otherwise required.")]
  240. private void ListenToSocket(IUdpSocket socket)
  241. {
  242. // Tasks are captured to local variables even if we don't use them just to avoid compiler warnings.
  243. var t = Task.Run(async () =>
  244. {
  245. var cancelled = false;
  246. while (!cancelled)
  247. {
  248. try
  249. {
  250. var result = await socket.ReceiveAsync();
  251. if (result.ReceivedBytes > 0)
  252. {
  253. // Strange cannot convert compiler error here if I don't explicitly
  254. // assign or cast to Action first. Assignment is easier to read,
  255. // so went with that.
  256. Action processWork = () => ProcessMessage(System.Text.UTF8Encoding.UTF8.GetString(result.Buffer, 0, result.ReceivedBytes), result.ReceivedFrom);
  257. var processTask = Task.Run(processWork);
  258. }
  259. }
  260. catch (ObjectDisposedException)
  261. {
  262. cancelled = true;
  263. }
  264. catch (TaskCanceledException)
  265. {
  266. cancelled = true;
  267. }
  268. }
  269. });
  270. }
  271. private void EnsureSendSocketCreated()
  272. {
  273. if (_SendSocket == null)
  274. {
  275. lock (_SendSocketSynchroniser)
  276. {
  277. if (_SendSocket == null)
  278. _SendSocket = CreateSocketAndListenForResponsesAsync();
  279. }
  280. }
  281. }
  282. private void ProcessMessage(string data, UdpEndPoint endPoint)
  283. {
  284. //Responses start with the HTTP version, prefixed with HTTP/ while
  285. //requests start with a method which can vary and might be one we haven't
  286. //seen/don't know. We'll check if this message is a request or a response
  287. //by checking for the static HTTP/ prefix on the start of the message.
  288. if (data.StartsWith("HTTP/", StringComparison.OrdinalIgnoreCase))
  289. {
  290. HttpResponseMessage responseMessage = null;
  291. try
  292. {
  293. responseMessage = _ResponseParser.Parse(data);
  294. }
  295. catch (ArgumentException) { } // Ignore invalid packets.
  296. if (responseMessage != null)
  297. OnResponseReceived(responseMessage, endPoint);
  298. }
  299. else
  300. {
  301. HttpRequestMessage requestMessage = null;
  302. try
  303. {
  304. requestMessage = _RequestParser.Parse(data);
  305. }
  306. catch (ArgumentException) { } // Ignore invalid packets.
  307. if (requestMessage != null)
  308. OnRequestReceived(requestMessage, endPoint);
  309. }
  310. }
  311. private void OnRequestReceived(HttpRequestMessage data, UdpEndPoint endPoint)
  312. {
  313. //SSDP specification says only * is currently used but other uri's might
  314. //be implemented in the future and should be ignored unless understood.
  315. //Section 4.2 - http://tools.ietf.org/html/draft-cai-ssdp-v1-03#page-11
  316. if (data.RequestUri.ToString() != "*") return;
  317. var handlers = this.RequestReceived;
  318. if (handlers != null)
  319. handlers(this, new RequestReceivedEventArgs(data, endPoint));
  320. }
  321. private void OnResponseReceived(HttpResponseMessage data, UdpEndPoint endPoint)
  322. {
  323. var handlers = this.ResponseReceived;
  324. if (handlers != null)
  325. handlers(this, new ResponseReceivedEventArgs(data, endPoint));
  326. }
  327. #endregion
  328. }
  329. }