2
0

SocketFactory.cs 9.9 KB

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