2
0

SocketFactory.cs 11 KB

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