You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

WrappedSocket.cs 8.4 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273
  1. using System;
  2. using System.Net;
  3. using System.Net.Sockets;
  4. using System.Threading;
  5. namespace Shadowsocks.Util.Sockets
  6. {
  7. /*
  8. * A wrapped socket class which support both ipv4 and ipv6 based on the
  9. * connected remote endpoint.
  10. *
  11. * If the server address is host name, then it may have both ipv4 and ipv6 address
  12. * after resolving. The main idea is we don't want to resolve and choose the address
  13. * by ourself. Instead, Socket.ConnectAsync() do handle this thing internally by trying
  14. * each address and returning an established socket connection.
  15. */
  16. public class WrappedSocket
  17. {
  18. public EndPoint LocalEndPoint => _activeSocket?.LocalEndPoint;
  19. // Only used during connection and close, so it won't cost too much.
  20. private SpinLock _socketSyncLock = new SpinLock();
  21. private bool _disposed;
  22. private bool Connected => _activeSocket != null;
  23. private Socket _activeSocket;
  24. public WrappedSocket() { }
  25. public WrappedSocket(Socket socket)
  26. {
  27. _activeSocket = socket;
  28. }
  29. public void BeginConnect(EndPoint remoteEP, AsyncCallback callback, object state)
  30. {
  31. if (_disposed)
  32. {
  33. throw new ObjectDisposedException(GetType().FullName);
  34. }
  35. if (Connected)
  36. {
  37. throw new SocketException((int) SocketError.IsConnected);
  38. }
  39. var arg = new SocketAsyncEventArgs();
  40. arg.RemoteEndPoint = remoteEP;
  41. arg.Completed += OnTcpConnectCompleted;
  42. arg.UserToken = new TcpUserToken(callback, state);
  43. Socket.ConnectAsync(SocketType.Stream, ProtocolType.Tcp, arg);
  44. }
  45. private class FakeAsyncResult : IAsyncResult
  46. {
  47. public bool IsCompleted { get; } = true;
  48. public WaitHandle AsyncWaitHandle { get; } = null;
  49. public object AsyncState { get; set; }
  50. public bool CompletedSynchronously { get; } = true;
  51. public Exception InternalException { get; set; } = null;
  52. }
  53. private class TcpUserToken
  54. {
  55. public AsyncCallback Callback { get; }
  56. public object AsyncState { get; }
  57. public TcpUserToken(AsyncCallback callback, object state)
  58. {
  59. Callback = callback;
  60. AsyncState = state;
  61. }
  62. }
  63. private void OnTcpConnectCompleted(object sender, SocketAsyncEventArgs args)
  64. {
  65. using (args)
  66. {
  67. args.Completed -= OnTcpConnectCompleted;
  68. var token = (TcpUserToken) args.UserToken;
  69. if (args.SocketError != SocketError.Success)
  70. {
  71. var ex = args.ConnectByNameError ?? new SocketException((int) args.SocketError);
  72. var r = new FakeAsyncResult()
  73. {
  74. AsyncState = token.AsyncState,
  75. InternalException = ex
  76. };
  77. token.Callback(r);
  78. }
  79. else
  80. {
  81. var lockTaken = false;
  82. if (!_socketSyncLock.IsHeldByCurrentThread)
  83. {
  84. _socketSyncLock.TryEnter(ref lockTaken);
  85. }
  86. try
  87. {
  88. if (Connected)
  89. {
  90. args.ConnectSocket.FullClose();
  91. }
  92. else
  93. {
  94. _activeSocket = args.ConnectSocket;
  95. if (_disposed)
  96. {
  97. _activeSocket.FullClose();
  98. }
  99. var r = new FakeAsyncResult()
  100. {
  101. AsyncState = token.AsyncState
  102. };
  103. token.Callback(r);
  104. }
  105. }
  106. finally
  107. {
  108. if (lockTaken)
  109. {
  110. _socketSyncLock.Exit();
  111. }
  112. }
  113. }
  114. }
  115. }
  116. public void EndConnect(IAsyncResult asyncResult)
  117. {
  118. if (_disposed)
  119. {
  120. throw new ObjectDisposedException(GetType().FullName);
  121. }
  122. var r = asyncResult as FakeAsyncResult;
  123. if (r == null)
  124. {
  125. throw new ArgumentException("Invalid asyncResult.", nameof(asyncResult));
  126. }
  127. if (r.InternalException != null)
  128. {
  129. throw r.InternalException;
  130. }
  131. }
  132. public void Dispose()
  133. {
  134. if (_disposed)
  135. {
  136. return;
  137. }
  138. var lockTaken = false;
  139. if (!_socketSyncLock.IsHeldByCurrentThread)
  140. {
  141. _socketSyncLock.TryEnter(ref lockTaken);
  142. }
  143. try
  144. {
  145. _disposed = true;
  146. _activeSocket?.FullClose();
  147. }
  148. finally
  149. {
  150. if (lockTaken)
  151. {
  152. _socketSyncLock.Exit();
  153. }
  154. }
  155. }
  156. public IAsyncResult BeginSend(byte[] buffer, int offset, int size, SocketFlags socketFlags,
  157. AsyncCallback callback,
  158. object state)
  159. {
  160. if (_disposed)
  161. {
  162. throw new ObjectDisposedException(GetType().FullName);
  163. }
  164. if (!Connected)
  165. {
  166. throw new SocketException((int) SocketError.NotConnected);
  167. }
  168. return _activeSocket.BeginSend(buffer, offset, size, socketFlags, callback, state);
  169. }
  170. public int EndSend(IAsyncResult asyncResult)
  171. {
  172. if (_disposed)
  173. {
  174. throw new ObjectDisposedException(GetType().FullName);
  175. }
  176. if (!Connected)
  177. {
  178. throw new SocketException((int) SocketError.NotConnected);
  179. }
  180. return _activeSocket.EndSend(asyncResult);
  181. }
  182. public IAsyncResult BeginReceive(byte[] buffer, int offset, int size, SocketFlags socketFlags,
  183. AsyncCallback callback,
  184. object state)
  185. {
  186. if (_disposed)
  187. {
  188. throw new ObjectDisposedException(GetType().FullName);
  189. }
  190. if (!Connected)
  191. {
  192. throw new SocketException((int) SocketError.NotConnected);
  193. }
  194. return _activeSocket.BeginReceive(buffer, offset, size, socketFlags, callback, state);
  195. }
  196. public int EndReceive(IAsyncResult asyncResult)
  197. {
  198. if (_disposed)
  199. {
  200. throw new ObjectDisposedException(GetType().FullName);
  201. }
  202. if (!Connected)
  203. {
  204. throw new SocketException((int) SocketError.NotConnected);
  205. }
  206. return _activeSocket.EndReceive(asyncResult);
  207. }
  208. public void Shutdown(SocketShutdown how)
  209. {
  210. if (_disposed)
  211. {
  212. throw new ObjectDisposedException(GetType().FullName);
  213. }
  214. if (!Connected)
  215. {
  216. return;
  217. }
  218. _activeSocket.Shutdown(how);
  219. }
  220. public void SetSocketOption(SocketOptionLevel optionLevel, SocketOptionName optionName, bool optionValue)
  221. {
  222. SetSocketOption(optionLevel, optionName, optionValue ? 1 : 0);
  223. }
  224. public void SetSocketOption(SocketOptionLevel optionLevel, SocketOptionName optionName, int optionValue)
  225. {
  226. if (_disposed)
  227. {
  228. throw new ObjectDisposedException(GetType().FullName);
  229. }
  230. if (!Connected)
  231. {
  232. throw new SocketException((int)SocketError.NotConnected);
  233. }
  234. _activeSocket.SetSocketOption(optionLevel, optionName, optionValue);
  235. }
  236. }
  237. }