SocketFactory.cs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303
  1. using System;
  2. using System.IO;
  3. using System.Net;
  4. using System.Net.Sockets;
  5. using Emby.Server.Implementations.Networking;
  6. using MediaBrowser.Model.Logging;
  7. using MediaBrowser.Model.Net;
  8. namespace Emby.Server.Implementations.Net
  9. {
  10. public class SocketFactory : ISocketFactory
  11. {
  12. // THIS IS A LINKED FILE - SHARED AMONGST MULTIPLE PLATFORMS
  13. // Be careful to check any changes compile and work for all platform projects it is shared in.
  14. // Not entirely happy with this. Would have liked to have done something more generic/reusable,
  15. // but that wasn't really the point so kept to YAGNI principal for now, even if the
  16. // interfaces are a bit ugly, specific and make assumptions.
  17. private readonly ILogger _logger;
  18. public SocketFactory(ILogger logger)
  19. {
  20. if (logger == null)
  21. {
  22. throw new ArgumentNullException("logger");
  23. }
  24. _logger = logger;
  25. }
  26. public IAcceptSocket CreateSocket(IpAddressFamily family, MediaBrowser.Model.Net.SocketType socketType, MediaBrowser.Model.Net.ProtocolType protocolType, bool dualMode)
  27. {
  28. try
  29. {
  30. var addressFamily = family == IpAddressFamily.InterNetwork
  31. ? AddressFamily.InterNetwork
  32. : AddressFamily.InterNetworkV6;
  33. var socket = new Socket(addressFamily, System.Net.Sockets.SocketType.Stream, System.Net.Sockets.ProtocolType.Tcp);
  34. if (dualMode)
  35. {
  36. socket.DualMode = true;
  37. }
  38. return new NetAcceptSocket(socket, _logger, dualMode);
  39. }
  40. catch (SocketException ex)
  41. {
  42. throw new SocketCreateException(ex.SocketErrorCode.ToString(), ex);
  43. }
  44. catch (ArgumentException ex)
  45. {
  46. if (dualMode)
  47. {
  48. // Mono for BSD incorrectly throws ArgumentException instead of SocketException
  49. throw new SocketCreateException("AddressFamilyNotSupported", ex);
  50. }
  51. else
  52. {
  53. throw;
  54. }
  55. }
  56. }
  57. public ISocket CreateTcpSocket(IpAddressInfo remoteAddress, int remotePort)
  58. {
  59. if (remotePort < 0) throw new ArgumentException("remotePort cannot be less than zero.", "remotePort");
  60. var addressFamily = remoteAddress.AddressFamily == IpAddressFamily.InterNetwork
  61. ? AddressFamily.InterNetwork
  62. : AddressFamily.InterNetworkV6;
  63. var retVal = new Socket(addressFamily, System.Net.Sockets.SocketType.Stream, System.Net.Sockets.ProtocolType.Tcp);
  64. try
  65. {
  66. retVal.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
  67. }
  68. catch (SocketException)
  69. {
  70. // This is not supported on all operating systems (qnap)
  71. }
  72. try
  73. {
  74. return new UdpSocket(retVal, new IpEndPointInfo(remoteAddress, remotePort));
  75. }
  76. catch
  77. {
  78. if (retVal != null)
  79. retVal.Dispose();
  80. throw;
  81. }
  82. }
  83. /// <summary>
  84. /// Creates a new UDP acceptSocket and binds it to the specified local port.
  85. /// </summary>
  86. /// <param name="localPort">An integer specifying the local port to bind the acceptSocket to.</param>
  87. public ISocket CreateUdpSocket(int localPort)
  88. {
  89. if (localPort < 0) throw new ArgumentException("localPort cannot be less than zero.", "localPort");
  90. var retVal = new Socket(AddressFamily.InterNetwork, System.Net.Sockets.SocketType.Dgram, System.Net.Sockets.ProtocolType.Udp);
  91. try
  92. {
  93. retVal.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
  94. return new UdpSocket(retVal, localPort, IPAddress.Any);
  95. }
  96. catch
  97. {
  98. if (retVal != null)
  99. retVal.Dispose();
  100. throw;
  101. }
  102. }
  103. public ISocket CreateUdpBroadcastSocket(int localPort)
  104. {
  105. if (localPort < 0) throw new ArgumentException("localPort cannot be less than zero.", "localPort");
  106. var retVal = new Socket(AddressFamily.InterNetwork, System.Net.Sockets.SocketType.Dgram, System.Net.Sockets.ProtocolType.Udp);
  107. try
  108. {
  109. retVal.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
  110. retVal.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Broadcast, 1);
  111. return new UdpSocket(retVal, localPort, IPAddress.Any);
  112. }
  113. catch
  114. {
  115. if (retVal != null)
  116. retVal.Dispose();
  117. throw;
  118. }
  119. }
  120. /// <summary>
  121. /// Creates a new UDP acceptSocket that is a member of the SSDP multicast local admin group and binds it to the specified local port.
  122. /// </summary>
  123. /// <returns>An implementation of the <see cref="ISocket"/> interface used by RSSDP components to perform acceptSocket operations.</returns>
  124. public ISocket CreateSsdpUdpSocket(IpAddressInfo localIpAddress, int localPort)
  125. {
  126. if (localPort < 0) throw new ArgumentException("localPort cannot be less than zero.", "localPort");
  127. var retVal = new Socket(AddressFamily.InterNetwork, System.Net.Sockets.SocketType.Dgram, System.Net.Sockets.ProtocolType.Udp);
  128. try
  129. {
  130. retVal.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
  131. retVal.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.MulticastTimeToLive, 4);
  132. var localIp = NetworkManager.ToIPAddress(localIpAddress);
  133. retVal.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.AddMembership, new MulticastOption(IPAddress.Parse("239.255.255.250"), localIp));
  134. return new UdpSocket(retVal, localPort, localIp);
  135. }
  136. catch
  137. {
  138. if (retVal != null)
  139. retVal.Dispose();
  140. throw;
  141. }
  142. }
  143. /// <summary>
  144. /// Creates a new UDP acceptSocket that is a member of the specified multicast IP address, and binds it to the specified local port.
  145. /// </summary>
  146. /// <param name="ipAddress">The multicast IP address to make the acceptSocket a member of.</param>
  147. /// <param name="multicastTimeToLive">The multicast time to live value for the acceptSocket.</param>
  148. /// <param name="localPort">The number of the local port to bind to.</param>
  149. /// <returns></returns>
  150. public ISocket CreateUdpMulticastSocket(string ipAddress, int multicastTimeToLive, int localPort)
  151. {
  152. if (ipAddress == null) throw new ArgumentNullException("ipAddress");
  153. if (ipAddress.Length == 0) throw new ArgumentException("ipAddress cannot be an empty string.", "ipAddress");
  154. if (multicastTimeToLive <= 0) throw new ArgumentException("multicastTimeToLive cannot be zero or less.", "multicastTimeToLive");
  155. if (localPort < 0) throw new ArgumentException("localPort cannot be less than zero.", "localPort");
  156. var retVal = new Socket(AddressFamily.InterNetwork, System.Net.Sockets.SocketType.Dgram, System.Net.Sockets.ProtocolType.Udp);
  157. try
  158. {
  159. // not supported on all platforms. throws on ubuntu with .net core 2.0
  160. retVal.ExclusiveAddressUse = false;
  161. }
  162. catch (SocketException)
  163. {
  164. }
  165. try
  166. {
  167. //retVal.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Broadcast, true);
  168. retVal.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
  169. retVal.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.MulticastTimeToLive, multicastTimeToLive);
  170. var localIp = IPAddress.Any;
  171. retVal.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.AddMembership, new MulticastOption(IPAddress.Parse(ipAddress), localIp));
  172. retVal.MulticastLoopback = true;
  173. return new UdpSocket(retVal, localPort, localIp);
  174. }
  175. catch
  176. {
  177. if (retVal != null)
  178. retVal.Dispose();
  179. throw;
  180. }
  181. }
  182. public Stream CreateNetworkStream(ISocket socket, bool ownsSocket)
  183. {
  184. var netSocket = (UdpSocket)socket;
  185. return new SocketStream(netSocket.Socket, ownsSocket);
  186. }
  187. }
  188. public class SocketStream : Stream
  189. {
  190. private readonly Socket _socket;
  191. public SocketStream(Socket socket, bool ownsSocket)
  192. {
  193. _socket = socket;
  194. }
  195. public override void Flush()
  196. {
  197. }
  198. public override bool CanRead
  199. {
  200. get { return true; }
  201. }
  202. public override bool CanSeek
  203. {
  204. get { return false; }
  205. }
  206. public override bool CanWrite
  207. {
  208. get { return true; }
  209. }
  210. public override long Length
  211. {
  212. get { throw new NotImplementedException(); }
  213. }
  214. public override long Position
  215. {
  216. get { throw new NotImplementedException(); }
  217. set { throw new NotImplementedException(); }
  218. }
  219. public override void Write(byte[] buffer, int offset, int count)
  220. {
  221. _socket.Send(buffer, offset, count, SocketFlags.None);
  222. }
  223. public override IAsyncResult BeginWrite(byte[] buffer, int offset, int count, AsyncCallback callback, object state)
  224. {
  225. return _socket.BeginSend(buffer, offset, count, SocketFlags.None, callback, state);
  226. }
  227. public override void EndWrite(IAsyncResult asyncResult)
  228. {
  229. _socket.EndSend(asyncResult);
  230. }
  231. public override void SetLength(long value)
  232. {
  233. throw new NotImplementedException();
  234. }
  235. public override long Seek(long offset, SeekOrigin origin)
  236. {
  237. throw new NotImplementedException();
  238. }
  239. public override int Read(byte[] buffer, int offset, int count)
  240. {
  241. return _socket.Receive(buffer, offset, count, SocketFlags.None);
  242. }
  243. public override IAsyncResult BeginRead(byte[] buffer, int offset, int count, AsyncCallback callback, object state)
  244. {
  245. return _socket.BeginReceive(buffer, offset, count, SocketFlags.None, callback, state);
  246. }
  247. public override int EndRead(IAsyncResult asyncResult)
  248. {
  249. return _socket.EndReceive(asyncResult);
  250. }
  251. }
  252. }