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.3 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265
  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 volatile bool _disposed;
  22. private bool Connected => _activeSocket != null;
  23. private Socket _activeSocket;
  24. public void BeginConnect(EndPoint remoteEP, AsyncCallback callback, object state)
  25. {
  26. if (_disposed)
  27. {
  28. throw new ObjectDisposedException(GetType().FullName);
  29. }
  30. if (Connected)
  31. {
  32. throw new SocketException((int) SocketError.IsConnected);
  33. }
  34. var arg = new SocketAsyncEventArgs();
  35. arg.RemoteEndPoint = remoteEP;
  36. arg.Completed += OnTcpConnectCompleted;
  37. arg.UserToken = new TcpUserToken(callback, state);
  38. Socket.ConnectAsync(SocketType.Stream, ProtocolType.Tcp, arg);
  39. }
  40. private class FakeAsyncResult : IAsyncResult
  41. {
  42. public bool IsCompleted { get; } = true;
  43. public WaitHandle AsyncWaitHandle { get; } = null;
  44. public object AsyncState { get; set; }
  45. public bool CompletedSynchronously { get; } = true;
  46. public Exception InternalException { get; set; } = null;
  47. }
  48. private class TcpUserToken
  49. {
  50. public AsyncCallback Callback { get; }
  51. public object AsyncState { get; }
  52. public TcpUserToken(AsyncCallback callback, object state)
  53. {
  54. Callback = callback;
  55. AsyncState = state;
  56. }
  57. }
  58. private void OnTcpConnectCompleted(object sender, SocketAsyncEventArgs args)
  59. {
  60. using (args)
  61. {
  62. args.Completed -= OnTcpConnectCompleted;
  63. var token = (TcpUserToken) args.UserToken;
  64. if (args.SocketError != SocketError.Success)
  65. {
  66. var ex = args.ConnectByNameError ?? new SocketException((int) args.SocketError);
  67. var r = new FakeAsyncResult()
  68. {
  69. AsyncState = token.AsyncState,
  70. InternalException = ex
  71. };
  72. token.Callback(r);
  73. }
  74. else
  75. {
  76. var lockTaken = false;
  77. if (!_socketSyncLock.IsHeldByCurrentThread)
  78. {
  79. _socketSyncLock.TryEnter(ref lockTaken);
  80. }
  81. try
  82. {
  83. if (Connected)
  84. {
  85. args.ConnectSocket.FullClose();
  86. }
  87. else
  88. {
  89. _activeSocket = args.ConnectSocket;
  90. if (_disposed)
  91. {
  92. _activeSocket.FullClose();
  93. }
  94. var r = new FakeAsyncResult()
  95. {
  96. AsyncState = token.AsyncState
  97. };
  98. token.Callback(r);
  99. }
  100. }
  101. finally
  102. {
  103. if (lockTaken)
  104. {
  105. _socketSyncLock.Exit();
  106. }
  107. }
  108. }
  109. }
  110. }
  111. public void EndConnect(IAsyncResult asyncResult)
  112. {
  113. if (_disposed)
  114. {
  115. throw new ObjectDisposedException(GetType().FullName);
  116. }
  117. var r = asyncResult as FakeAsyncResult;
  118. if (r == null)
  119. {
  120. throw new ArgumentException("Invalid asyncResult.", nameof(asyncResult));
  121. }
  122. if (r.InternalException != null)
  123. {
  124. throw r.InternalException;
  125. }
  126. }
  127. public void Dispose()
  128. {
  129. if (_disposed)
  130. {
  131. return;
  132. }
  133. var lockTaken = false;
  134. if (!_socketSyncLock.IsHeldByCurrentThread)
  135. {
  136. _socketSyncLock.TryEnter(ref lockTaken);
  137. }
  138. try
  139. {
  140. _disposed = true;
  141. _activeSocket?.FullClose();
  142. }
  143. finally
  144. {
  145. if (lockTaken)
  146. {
  147. _socketSyncLock.Exit();
  148. }
  149. }
  150. }
  151. public IAsyncResult BeginSend(byte[] buffer, int offset, int size, SocketFlags socketFlags,
  152. AsyncCallback callback,
  153. object state)
  154. {
  155. if (_disposed)
  156. {
  157. throw new ObjectDisposedException(GetType().FullName);
  158. }
  159. if (!Connected)
  160. {
  161. throw new SocketException((int) SocketError.NotConnected);
  162. }
  163. return _activeSocket.BeginSend(buffer, offset, size, socketFlags, callback, state);
  164. }
  165. public int EndSend(IAsyncResult asyncResult)
  166. {
  167. if (_disposed)
  168. {
  169. throw new ObjectDisposedException(GetType().FullName);
  170. }
  171. if (!Connected)
  172. {
  173. throw new SocketException((int) SocketError.NotConnected);
  174. }
  175. return _activeSocket.EndSend(asyncResult);
  176. }
  177. public IAsyncResult BeginReceive(byte[] buffer, int offset, int size, SocketFlags socketFlags,
  178. AsyncCallback callback,
  179. object state)
  180. {
  181. if (_disposed)
  182. {
  183. throw new ObjectDisposedException(GetType().FullName);
  184. }
  185. if (!Connected)
  186. {
  187. throw new SocketException((int) SocketError.NotConnected);
  188. }
  189. return _activeSocket.BeginReceive(buffer, offset, size, socketFlags, callback, state);
  190. }
  191. public int EndReceive(IAsyncResult asyncResult)
  192. {
  193. if (_disposed)
  194. {
  195. throw new ObjectDisposedException(GetType().FullName);
  196. }
  197. if (!Connected)
  198. {
  199. throw new SocketException((int) SocketError.NotConnected);
  200. }
  201. return _activeSocket.EndReceive(asyncResult);
  202. }
  203. public void Shutdown(SocketShutdown how)
  204. {
  205. if (_disposed)
  206. {
  207. throw new ObjectDisposedException(GetType().FullName);
  208. }
  209. if (!Connected)
  210. {
  211. return;
  212. }
  213. _activeSocket.Shutdown(how);
  214. }
  215. public void SetSocketOption(SocketOptionLevel optionLevel, SocketOptionName optionName, bool optionValue)
  216. {
  217. SetSocketOption(optionLevel, optionName, optionValue ? 1 : 0);
  218. }
  219. public void SetSocketOption(SocketOptionLevel optionLevel, SocketOptionName optionName, int optionValue)
  220. {
  221. if (_disposed)
  222. {
  223. throw new ObjectDisposedException(GetType().FullName);
  224. }
  225. if (!Connected)
  226. {
  227. throw new SocketException((int)SocketError.NotConnected);
  228. }
  229. _activeSocket.SetSocketOption(optionLevel, optionName, optionValue);
  230. }
  231. }
  232. }