SocketFactory.cs 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258
  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.Net;
  7. using Microsoft.Extensions.Logging;
  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. public ISocket CreateTcpSocket(IpAddressInfo remoteAddress, int remotePort)
  18. {
  19. if (remotePort < 0) throw new ArgumentException("remotePort cannot be less than zero.", nameof(remotePort));
  20. var addressFamily = remoteAddress.AddressFamily == IpAddressFamily.InterNetwork
  21. ? AddressFamily.InterNetwork
  22. : AddressFamily.InterNetworkV6;
  23. var retVal = new Socket(addressFamily, System.Net.Sockets.SocketType.Stream, System.Net.Sockets.ProtocolType.Tcp);
  24. try
  25. {
  26. retVal.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
  27. }
  28. catch (SocketException)
  29. {
  30. // This is not supported on all operating systems (qnap)
  31. }
  32. try
  33. {
  34. return new UdpSocket(retVal, new IpEndPointInfo(remoteAddress, remotePort));
  35. }
  36. catch
  37. {
  38. if (retVal != null)
  39. retVal.Dispose();
  40. throw;
  41. }
  42. }
  43. /// <summary>
  44. /// Creates a new UDP acceptSocket and binds it to the specified local port.
  45. /// </summary>
  46. /// <param name="localPort">An integer specifying the local port to bind the acceptSocket to.</param>
  47. public ISocket CreateUdpSocket(int localPort)
  48. {
  49. if (localPort < 0) throw new ArgumentException("localPort cannot be less than zero.", nameof(localPort));
  50. var retVal = new Socket(AddressFamily.InterNetwork, System.Net.Sockets.SocketType.Dgram, System.Net.Sockets.ProtocolType.Udp);
  51. try
  52. {
  53. retVal.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
  54. return new UdpSocket(retVal, localPort, IPAddress.Any);
  55. }
  56. catch
  57. {
  58. if (retVal != null)
  59. retVal.Dispose();
  60. throw;
  61. }
  62. }
  63. public ISocket CreateUdpBroadcastSocket(int localPort)
  64. {
  65. if (localPort < 0) throw new ArgumentException("localPort cannot be less than zero.", nameof(localPort));
  66. var retVal = new Socket(AddressFamily.InterNetwork, System.Net.Sockets.SocketType.Dgram, System.Net.Sockets.ProtocolType.Udp);
  67. try
  68. {
  69. retVal.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
  70. retVal.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Broadcast, 1);
  71. return new UdpSocket(retVal, localPort, IPAddress.Any);
  72. }
  73. catch
  74. {
  75. if (retVal != null)
  76. retVal.Dispose();
  77. throw;
  78. }
  79. }
  80. /// <summary>
  81. /// Creates a new UDP acceptSocket that is a member of the SSDP multicast local admin group and binds it to the specified local port.
  82. /// </summary>
  83. /// <returns>An implementation of the <see cref="ISocket"/> interface used by RSSDP components to perform acceptSocket operations.</returns>
  84. public ISocket CreateSsdpUdpSocket(IpAddressInfo localIpAddress, int localPort)
  85. {
  86. if (localPort < 0) throw new ArgumentException("localPort cannot be less than zero.", nameof(localPort));
  87. var retVal = new Socket(AddressFamily.InterNetwork, System.Net.Sockets.SocketType.Dgram, System.Net.Sockets.ProtocolType.Udp);
  88. try
  89. {
  90. retVal.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
  91. retVal.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.MulticastTimeToLive, 4);
  92. var localIp = NetworkManager.ToIPAddress(localIpAddress);
  93. retVal.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.AddMembership, new MulticastOption(IPAddress.Parse("239.255.255.250"), localIp));
  94. return new UdpSocket(retVal, localPort, localIp);
  95. }
  96. catch
  97. {
  98. if (retVal != null)
  99. retVal.Dispose();
  100. throw;
  101. }
  102. }
  103. /// <summary>
  104. /// Creates a new UDP acceptSocket that is a member of the specified multicast IP address, and binds it to the specified local port.
  105. /// </summary>
  106. /// <param name="ipAddress">The multicast IP address to make the acceptSocket a member of.</param>
  107. /// <param name="multicastTimeToLive">The multicast time to live value for the acceptSocket.</param>
  108. /// <param name="localPort">The number of the local port to bind to.</param>
  109. /// <returns></returns>
  110. public ISocket CreateUdpMulticastSocket(string ipAddress, int multicastTimeToLive, int localPort)
  111. {
  112. if (ipAddress == null) throw new ArgumentNullException(nameof(ipAddress));
  113. if (ipAddress.Length == 0) throw new ArgumentException("ipAddress cannot be an empty string.", nameof(ipAddress));
  114. if (multicastTimeToLive <= 0) throw new ArgumentException("multicastTimeToLive cannot be zero or less.", nameof(multicastTimeToLive));
  115. if (localPort < 0) throw new ArgumentException("localPort cannot be less than zero.", nameof(localPort));
  116. var retVal = new Socket(AddressFamily.InterNetwork, System.Net.Sockets.SocketType.Dgram, System.Net.Sockets.ProtocolType.Udp);
  117. try
  118. {
  119. // not supported on all platforms. throws on ubuntu with .net core 2.0
  120. retVal.ExclusiveAddressUse = false;
  121. }
  122. catch (SocketException)
  123. {
  124. }
  125. try
  126. {
  127. // seeing occasional exceptions thrown on qnap
  128. // System.Net.Sockets.SocketException (0x80004005): Protocol not available
  129. retVal.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
  130. }
  131. catch (SocketException)
  132. {
  133. }
  134. try
  135. {
  136. //retVal.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Broadcast, true);
  137. retVal.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.MulticastTimeToLive, multicastTimeToLive);
  138. var localIp = IPAddress.Any;
  139. retVal.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.AddMembership, new MulticastOption(IPAddress.Parse(ipAddress), localIp));
  140. retVal.MulticastLoopback = true;
  141. return new UdpSocket(retVal, localPort, localIp);
  142. }
  143. catch
  144. {
  145. if (retVal != null)
  146. retVal.Dispose();
  147. throw;
  148. }
  149. }
  150. public Stream CreateNetworkStream(ISocket socket, bool ownsSocket)
  151. {
  152. var netSocket = (UdpSocket)socket;
  153. return new SocketStream(netSocket.Socket, ownsSocket);
  154. }
  155. }
  156. public class SocketStream : Stream
  157. {
  158. private readonly Socket _socket;
  159. public SocketStream(Socket socket, bool ownsSocket)
  160. {
  161. _socket = socket;
  162. }
  163. public override void Flush()
  164. {
  165. }
  166. public override bool CanRead => true;
  167. public override bool CanSeek => false;
  168. public override bool CanWrite => true;
  169. public override long Length => throw new NotImplementedException();
  170. public override long Position
  171. {
  172. get => throw new NotImplementedException();
  173. set => throw new NotImplementedException();
  174. }
  175. public override void Write(byte[] buffer, int offset, int count)
  176. {
  177. _socket.Send(buffer, offset, count, SocketFlags.None);
  178. }
  179. public override IAsyncResult BeginWrite(byte[] buffer, int offset, int count, AsyncCallback callback, object state)
  180. {
  181. return _socket.BeginSend(buffer, offset, count, SocketFlags.None, callback, state);
  182. }
  183. public override void EndWrite(IAsyncResult asyncResult)
  184. {
  185. _socket.EndSend(asyncResult);
  186. }
  187. public override void SetLength(long value)
  188. {
  189. throw new NotImplementedException();
  190. }
  191. public override long Seek(long offset, SeekOrigin origin)
  192. {
  193. throw new NotImplementedException();
  194. }
  195. public override int Read(byte[] buffer, int offset, int count)
  196. {
  197. return _socket.Receive(buffer, offset, count, SocketFlags.None);
  198. }
  199. public override IAsyncResult BeginRead(byte[] buffer, int offset, int count, AsyncCallback callback, object state)
  200. {
  201. return _socket.BeginReceive(buffer, offset, count, SocketFlags.None, callback, state);
  202. }
  203. public override int EndRead(IAsyncResult asyncResult)
  204. {
  205. return _socket.EndReceive(asyncResult);
  206. }
  207. }
  208. }