SocketFactory.cs 9.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221
  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 addressFamily = remoteAddress.AddressFamily == IpAddressFamily.InterNetwork
  63. ? AddressFamily.InterNetwork
  64. : AddressFamily.InterNetworkV6;
  65. var retVal = new Socket(addressFamily, System.Net.Sockets.SocketType.Stream, System.Net.Sockets.ProtocolType.Tcp);
  66. try
  67. {
  68. retVal.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
  69. }
  70. catch (SocketException)
  71. {
  72. // This is not supported on all operating systems (qnap)
  73. }
  74. try
  75. {
  76. return new UdpSocket(retVal, new IpEndPointInfo(remoteAddress, remotePort));
  77. }
  78. catch
  79. {
  80. if (retVal != null)
  81. retVal.Dispose();
  82. throw;
  83. }
  84. }
  85. /// <summary>
  86. /// Creates a new UDP acceptSocket and binds it to the specified local port.
  87. /// </summary>
  88. /// <param name="localPort">An integer specifying the local port to bind the acceptSocket to.</param>
  89. public ISocket CreateUdpSocket(int localPort)
  90. {
  91. if (localPort < 0) throw new ArgumentException("localPort cannot be less than zero.", "localPort");
  92. var retVal = new Socket(AddressFamily.InterNetwork, System.Net.Sockets.SocketType.Dgram, System.Net.Sockets.ProtocolType.Udp);
  93. try
  94. {
  95. retVal.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
  96. return new UdpSocket(retVal, localPort, IPAddress.Any);
  97. }
  98. catch
  99. {
  100. if (retVal != null)
  101. retVal.Dispose();
  102. throw;
  103. }
  104. }
  105. public ISocket CreateUdpBroadcastSocket(int localPort)
  106. {
  107. if (localPort < 0) throw new ArgumentException("localPort cannot be less than zero.", "localPort");
  108. var retVal = new Socket(AddressFamily.InterNetwork, System.Net.Sockets.SocketType.Dgram, System.Net.Sockets.ProtocolType.Udp);
  109. try
  110. {
  111. retVal.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
  112. retVal.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Broadcast, 1);
  113. return new UdpSocket(retVal, localPort, IPAddress.Any);
  114. }
  115. catch
  116. {
  117. if (retVal != null)
  118. retVal.Dispose();
  119. throw;
  120. }
  121. }
  122. /// <summary>
  123. /// Creates a new UDP acceptSocket that is a member of the SSDP multicast local admin group and binds it to the specified local port.
  124. /// </summary>
  125. /// <returns>An implementation of the <see cref="ISocket"/> interface used by RSSDP components to perform acceptSocket operations.</returns>
  126. public ISocket CreateSsdpUdpSocket(IpAddressInfo localIpAddress, int localPort)
  127. {
  128. if (localPort < 0) throw new ArgumentException("localPort cannot be less than zero.", "localPort");
  129. var retVal = new Socket(AddressFamily.InterNetwork, System.Net.Sockets.SocketType.Dgram, System.Net.Sockets.ProtocolType.Udp);
  130. try
  131. {
  132. retVal.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
  133. retVal.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.MulticastTimeToLive, 4);
  134. var localIp = NetworkManager.ToIPAddress(localIpAddress);
  135. retVal.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.AddMembership, new MulticastOption(IPAddress.Parse("239.255.255.250"), localIp));
  136. return new UdpSocket(retVal, localPort, localIp);
  137. }
  138. catch
  139. {
  140. if (retVal != null)
  141. retVal.Dispose();
  142. throw;
  143. }
  144. }
  145. /// <summary>
  146. /// Creates a new UDP acceptSocket that is a member of the specified multicast IP address, and binds it to the specified local port.
  147. /// </summary>
  148. /// <param name="ipAddress">The multicast IP address to make the acceptSocket a member of.</param>
  149. /// <param name="multicastTimeToLive">The multicast time to live value for the acceptSocket.</param>
  150. /// <param name="localPort">The number of the local port to bind to.</param>
  151. /// <returns></returns>
  152. public ISocket CreateUdpMulticastSocket(string ipAddress, int multicastTimeToLive, int localPort)
  153. {
  154. if (ipAddress == null) throw new ArgumentNullException("ipAddress");
  155. if (ipAddress.Length == 0) throw new ArgumentException("ipAddress cannot be an empty string.", "ipAddress");
  156. if (multicastTimeToLive <= 0) throw new ArgumentException("multicastTimeToLive cannot be zero or less.", "multicastTimeToLive");
  157. if (localPort < 0) throw new ArgumentException("localPort cannot be less than zero.", "localPort");
  158. var retVal = new Socket(AddressFamily.InterNetwork, System.Net.Sockets.SocketType.Dgram, System.Net.Sockets.ProtocolType.Udp);
  159. try
  160. {
  161. #if NET46
  162. retVal.ExclusiveAddressUse = false;
  163. #else
  164. // 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
  165. // See https://github.com/dotnet/corefx/pull/11509 for more details
  166. if (System.Runtime.InteropServices.RuntimeInformation.IsOSPlatform(System.Runtime.InteropServices.OSPlatform.Windows))
  167. {
  168. retVal.ExclusiveAddressUse = false;
  169. }
  170. #endif
  171. //retVal.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Broadcast, true);
  172. retVal.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
  173. retVal.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.MulticastTimeToLive, multicastTimeToLive);
  174. var localIp = IPAddress.Any;
  175. retVal.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.AddMembership, new MulticastOption(IPAddress.Parse(ipAddress), localIp));
  176. retVal.MulticastLoopback = true;
  177. return new UdpSocket(retVal, localPort, localIp);
  178. }
  179. catch
  180. {
  181. if (retVal != null)
  182. retVal.Dispose();
  183. throw;
  184. }
  185. }
  186. }
  187. }