SocketFactory.cs 8.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Net;
  5. using System.Net.Sockets;
  6. using System.Threading.Tasks;
  7. using Emby.Common.Implementations.Networking;
  8. using MediaBrowser.Model.Logging;
  9. using MediaBrowser.Model.Net;
  10. namespace Emby.Common.Implementations.Net
  11. {
  12. public class SocketFactory : ISocketFactory
  13. {
  14. // THIS IS A LINKED FILE - SHARED AMONGST MULTIPLE PLATFORMS
  15. // Be careful to check any changes compile and work for all platform projects it is shared in.
  16. // Not entirely happy with this. Would have liked to have done something more generic/reusable,
  17. // but that wasn't really the point so kept to YAGNI principal for now, even if the
  18. // interfaces are a bit ugly, specific and make assumptions.
  19. private readonly ILogger _logger;
  20. public SocketFactory(ILogger logger)
  21. {
  22. if (logger == null)
  23. {
  24. throw new ArgumentNullException("logger");
  25. }
  26. _logger = logger;
  27. }
  28. public IAcceptSocket CreateSocket(IpAddressFamily family, MediaBrowser.Model.Net.SocketType socketType, MediaBrowser.Model.Net.ProtocolType protocolType, bool dualMode)
  29. {
  30. try
  31. {
  32. var addressFamily = family == IpAddressFamily.InterNetwork
  33. ? AddressFamily.InterNetwork
  34. : AddressFamily.InterNetworkV6;
  35. var socket = new Socket(addressFamily, System.Net.Sockets.SocketType.Stream, System.Net.Sockets.ProtocolType.Tcp);
  36. if (dualMode)
  37. {
  38. socket.DualMode = true;
  39. }
  40. return new NetAcceptSocket(socket, _logger, dualMode);
  41. }
  42. catch (SocketException ex)
  43. {
  44. throw new SocketCreateException(ex.SocketErrorCode.ToString(), ex);
  45. }
  46. catch (ArgumentException ex)
  47. {
  48. if (dualMode)
  49. {
  50. // Mono for BSD incorrectly throws ArgumentException instead of SocketException
  51. throw new SocketCreateException("AddressFamilyNotSupported", ex);
  52. }
  53. else
  54. {
  55. throw;
  56. }
  57. }
  58. }
  59. public ISocket CreateTcpSocket(IpAddressInfo remoteAddress, int remotePort)
  60. {
  61. if (remotePort < 0) throw new ArgumentException("remotePort cannot be less than zero.", "remotePort");
  62. var retVal = new Socket(AddressFamily.InterNetwork, System.Net.Sockets.SocketType.Stream, System.Net.Sockets.ProtocolType.Tcp);
  63. try
  64. {
  65. retVal.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
  66. }
  67. catch (SocketException)
  68. {
  69. // This is not supported on all operating systems (qnap)
  70. }
  71. try
  72. {
  73. return new UdpSocket(retVal, new IpEndPointInfo(remoteAddress, remotePort));
  74. }
  75. catch
  76. {
  77. if (retVal != null)
  78. retVal.Dispose();
  79. throw;
  80. }
  81. }
  82. /// <summary>
  83. /// Creates a new UDP acceptSocket and binds it to the specified local port.
  84. /// </summary>
  85. /// <param name="localPort">An integer specifying the local port to bind the acceptSocket to.</param>
  86. public ISocket CreateUdpSocket(int localPort)
  87. {
  88. if (localPort < 0) throw new ArgumentException("localPort cannot be less than zero.", "localPort");
  89. var retVal = new Socket(AddressFamily.InterNetwork, System.Net.Sockets.SocketType.Dgram, System.Net.Sockets.ProtocolType.Udp);
  90. try
  91. {
  92. retVal.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
  93. return new UdpSocket(retVal, localPort, IPAddress.Any);
  94. }
  95. catch
  96. {
  97. if (retVal != null)
  98. retVal.Dispose();
  99. throw;
  100. }
  101. }
  102. public ISocket CreateUdpBroadcastSocket(int localPort)
  103. {
  104. if (localPort < 0) throw new ArgumentException("localPort cannot be less than zero.", "localPort");
  105. var retVal = new Socket(AddressFamily.InterNetwork, System.Net.Sockets.SocketType.Dgram, System.Net.Sockets.ProtocolType.Udp);
  106. try
  107. {
  108. retVal.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
  109. retVal.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Broadcast, 1);
  110. return new UdpSocket(retVal, localPort, IPAddress.Any);
  111. }
  112. catch
  113. {
  114. if (retVal != null)
  115. retVal.Dispose();
  116. throw;
  117. }
  118. }
  119. /// <summary>
  120. /// Creates a new UDP acceptSocket that is a member of the SSDP multicast local admin group and binds it to the specified local port.
  121. /// </summary>
  122. /// <returns>An implementation of the <see cref="ISocket"/> interface used by RSSDP components to perform acceptSocket operations.</returns>
  123. public ISocket CreateSsdpUdpSocket(IpAddressInfo localIpAddress, int localPort)
  124. {
  125. if (localPort < 0) throw new ArgumentException("localPort cannot be less than zero.", "localPort");
  126. var retVal = new Socket(AddressFamily.InterNetwork, System.Net.Sockets.SocketType.Dgram, System.Net.Sockets.ProtocolType.Udp);
  127. try
  128. {
  129. retVal.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
  130. retVal.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.MulticastTimeToLive, 4);
  131. var localIp = NetworkManager.ToIPAddress(localIpAddress);
  132. retVal.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.AddMembership, new MulticastOption(IPAddress.Parse("239.255.255.250"), localIp));
  133. return new UdpSocket(retVal, localPort, localIp);
  134. }
  135. catch
  136. {
  137. if (retVal != null)
  138. retVal.Dispose();
  139. throw;
  140. }
  141. }
  142. /// <summary>
  143. /// Creates a new UDP acceptSocket that is a member of the specified multicast IP address, and binds it to the specified local port.
  144. /// </summary>
  145. /// <param name="ipAddress">The multicast IP address to make the acceptSocket a member of.</param>
  146. /// <param name="multicastTimeToLive">The multicast time to live value for the acceptSocket.</param>
  147. /// <param name="localPort">The number of the local port to bind to.</param>
  148. /// <returns></returns>
  149. public ISocket CreateUdpMulticastSocket(string ipAddress, int multicastTimeToLive, int localPort)
  150. {
  151. if (ipAddress == null) throw new ArgumentNullException("ipAddress");
  152. if (ipAddress.Length == 0) throw new ArgumentException("ipAddress cannot be an empty string.", "ipAddress");
  153. if (multicastTimeToLive <= 0) throw new ArgumentException("multicastTimeToLive cannot be zero or less.", "multicastTimeToLive");
  154. if (localPort < 0) throw new ArgumentException("localPort cannot be less than zero.", "localPort");
  155. var retVal = new Socket(AddressFamily.InterNetwork, System.Net.Sockets.SocketType.Dgram, System.Net.Sockets.ProtocolType.Udp);
  156. try
  157. {
  158. #if NET46
  159. retVal.ExclusiveAddressUse = false;
  160. #else
  161. // The ExclusiveAddressUse acceptSocket option is a Windows-specific option that, when set to "true," tells Windows not to allow another acceptSocket to use the same local address as this acceptSocket
  162. // See https://github.com/dotnet/corefx/pull/11509 for more details
  163. if (System.Runtime.InteropServices.RuntimeInformation.IsOSPlatform(System.Runtime.InteropServices.OSPlatform.Windows))
  164. {
  165. retVal.ExclusiveAddressUse = false;
  166. }
  167. #endif
  168. //retVal.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Broadcast, true);
  169. retVal.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
  170. retVal.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.MulticastTimeToLive, multicastTimeToLive);
  171. var localIp = IPAddress.Any;
  172. retVal.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.AddMembership, new MulticastOption(IPAddress.Parse(ipAddress), localIp));
  173. retVal.MulticastLoopback = true;
  174. return new UdpSocket(retVal, localPort, localIp);
  175. }
  176. catch
  177. {
  178. if (retVal != null)
  179. retVal.Dispose();
  180. throw;
  181. }
  182. }
  183. }
  184. }