SocketSession.cs 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668
  1. using System;
  2. using System.Collections.Concurrent;
  3. using System.Collections.Generic;
  4. using System.Collections.ObjectModel;
  5. using System.Diagnostics;
  6. using System.IO;
  7. using System.Net;
  8. using System.Net.Sockets;
  9. using System.Security.Authentication;
  10. using System.Text;
  11. using System.Threading;
  12. using Microsoft.Extensions.Logging;
  13. using SuperSocket.Common;
  14. using SuperSocket.SocketBase;
  15. using SuperSocket.SocketBase.Command;
  16. using SuperSocket.SocketBase.Config;
  17. using SuperSocket.SocketBase.Protocol;
  18. namespace SuperSocket.SocketEngine
  19. {
  20. static class SocketState
  21. {
  22. public const int Normal = 0;//0000 0000
  23. public const int InClosing = 16;//0001 0000 >= 16
  24. public const int Closed = 16777216;//256 * 256 * 256; 0x01 0x00 0x00 0x00
  25. public const int InSending = 1;//0000 0001 > 1
  26. public const int InReceiving = 2;//0000 0010 > 2
  27. public const int InSendingReceivingMask = -4;// ~(InSending | InReceiving); 0xf0 0xff 0xff 0xff
  28. }
  29. /// <summary>
  30. /// Socket Session, all application session should base on this class
  31. /// </summary>
  32. abstract partial class SocketSession : ISocketSession
  33. {
  34. public IAppSession AppSession { get; private set; }
  35. protected readonly object SyncRoot = new object();
  36. //0x00 0x00 0x00 0x00
  37. //1st byte: Closed(Y/N) - 0x01
  38. //2nd byte: N/A
  39. //3th byte: CloseReason
  40. //Last byte: 0000 0000 - normal state
  41. //0000 0001: in sending
  42. //0000 0010: in receiving
  43. //0001 0000: in closing
  44. private int m_State = 0;
  45. private void AddStateFlag(int stateValue)
  46. {
  47. AddStateFlag(stateValue, false);
  48. }
  49. private bool AddStateFlag(int stateValue, bool notClosing)
  50. {
  51. while(true)
  52. {
  53. var oldState = m_State;
  54. if (notClosing)
  55. {
  56. // don't update the state if the connection has entered the closing procedure
  57. if (oldState >= SocketState.InClosing)
  58. {
  59. return false;
  60. }
  61. }
  62. var newState = m_State | stateValue;
  63. if(Interlocked.CompareExchange(ref m_State, newState, oldState) == oldState)
  64. return true;
  65. }
  66. }
  67. private bool TryAddStateFlag(int stateValue)
  68. {
  69. while (true)
  70. {
  71. var oldState = m_State;
  72. var newState = m_State | stateValue;
  73. //Already marked
  74. if (oldState == newState)
  75. {
  76. return false;
  77. }
  78. var compareState = Interlocked.CompareExchange(ref m_State, newState, oldState);
  79. if (compareState == oldState)
  80. return true;
  81. }
  82. }
  83. private void RemoveStateFlag(int stateValue)
  84. {
  85. while(true)
  86. {
  87. var oldState = m_State;
  88. var newState = m_State & (~stateValue);
  89. if(Interlocked.CompareExchange(ref m_State, newState, oldState) == oldState)
  90. return;
  91. }
  92. }
  93. private bool CheckState(int stateValue)
  94. {
  95. return (m_State & stateValue) == stateValue;
  96. }
  97. protected bool SyncSend { get; private set; }
  98. private ISmartPool<SendingQueue> m_SendingQueuePool;
  99. public SocketSession(Socket client)
  100. : this(Guid.NewGuid().ToString())
  101. {
  102. if (client == null)
  103. throw new ArgumentNullException("client");
  104. m_Client = client;
  105. LocalEndPoint = (IPEndPoint)client.LocalEndPoint;
  106. RemoteEndPoint = (IPEndPoint)client.RemoteEndPoint;
  107. }
  108. public SocketSession(string sessionID)
  109. {
  110. SessionID = sessionID;
  111. }
  112. public virtual void Initialize(IAppSession appSession)
  113. {
  114. AppSession = appSession;
  115. Config = appSession.Config;
  116. SyncSend = Config.SyncSend;
  117. if (m_SendingQueuePool == null)
  118. m_SendingQueuePool = ((SocketServerBase)((ISocketServerAccessor)appSession.AppServer).SocketServer).SendingQueuePool;
  119. SendingQueue queue;
  120. if (m_SendingQueuePool.TryGet(out queue))
  121. {
  122. m_SendingQueue = queue;
  123. queue.StartEnqueue();
  124. }
  125. }
  126. /// <summary>
  127. /// Gets or sets the session ID.
  128. /// </summary>
  129. /// <value>The session ID.</value>
  130. public string SessionID { get; private set; }
  131. /// <summary>
  132. /// Gets or sets the config.
  133. /// </summary>
  134. /// <value>
  135. /// The config.
  136. /// </value>
  137. public IServerConfig Config { get; set; }
  138. /// <summary>
  139. /// Starts this session.
  140. /// </summary>
  141. public abstract void Start();
  142. /// <summary>
  143. /// Says the welcome information when a client connectted.
  144. /// </summary>
  145. protected virtual void StartSession()
  146. {
  147. AppSession.StartSession();
  148. }
  149. /// <summary>
  150. /// Called when [close].
  151. /// </summary>
  152. protected virtual void OnClosed(CloseReason reason)
  153. {
  154. //Already closed
  155. if (!TryAddStateFlag(SocketState.Closed))
  156. return;
  157. //Before changing m_SendingQueue, must check m_IsClosed
  158. while (true)
  159. {
  160. var sendingQueue = m_SendingQueue;
  161. if (sendingQueue == null)
  162. break;
  163. //There is no sending was started after the m_Closed ws set to 'true'
  164. if (Interlocked.CompareExchange(ref m_SendingQueue, null, sendingQueue) == sendingQueue)
  165. {
  166. sendingQueue.Clear();
  167. m_SendingQueuePool.Push(sendingQueue);
  168. break;
  169. }
  170. }
  171. var closedHandler = Closed;
  172. if (closedHandler != null)
  173. {
  174. closedHandler(this, reason);
  175. }
  176. }
  177. /// <summary>
  178. /// Occurs when [closed].
  179. /// </summary>
  180. public Action<ISocketSession, CloseReason> Closed { get; set; }
  181. private SendingQueue m_SendingQueue;
  182. /// <summary>
  183. /// Tries to send array segment.
  184. /// </summary>
  185. /// <param name="segments">The segments.</param>
  186. /// <returns></returns>
  187. public bool TrySend(IList<ArraySegment<byte>> segments)
  188. {
  189. if (IsClosed)
  190. return false;
  191. var queue = m_SendingQueue;
  192. if (queue == null)
  193. return false;
  194. var trackID = queue.TrackID;
  195. if (!queue.Enqueue(segments, trackID))
  196. return false;
  197. StartSend(queue, trackID, true);
  198. return true;
  199. }
  200. /// <summary>
  201. /// Tries to send array segment.
  202. /// </summary>
  203. /// <param name="segment">The segment.</param>
  204. /// <returns></returns>
  205. public bool TrySend(ArraySegment<byte> segment)
  206. {
  207. if (IsClosed)
  208. return false;
  209. var queue = m_SendingQueue;
  210. if (queue == null)
  211. return false;
  212. var trackID = queue.TrackID;
  213. if (!queue.Enqueue(segment, trackID))
  214. return false;
  215. StartSend(queue, trackID, true);
  216. return true;
  217. }
  218. /// <summary>
  219. /// Sends in async mode.
  220. /// </summary>
  221. /// <param name="queue">The queue.</param>
  222. protected abstract void SendAsync(SendingQueue queue);
  223. /// <summary>
  224. /// Sends in sync mode.
  225. /// </summary>
  226. /// <param name="queue">The queue.</param>
  227. protected abstract void SendSync(SendingQueue queue);
  228. private void Send(SendingQueue queue)
  229. {
  230. var stopwatch = Stopwatch.StartNew();
  231. if (SyncSend)
  232. {
  233. SendSync(queue);
  234. }
  235. else
  236. {
  237. SendAsync(queue);
  238. }
  239. stopwatch.Stop();
  240. if(stopwatch.ElapsedMilliseconds/1000 > 1)
  241. {
  242. Console.WriteLine($"SocketSession Send take {stopwatch.ElapsedMilliseconds / 1000} sec");
  243. }
  244. }
  245. private void StartSend(SendingQueue queue, int sendingTrackID, bool initial)
  246. {
  247. if (initial)
  248. {
  249. if (!TryAddStateFlag(SocketState.InSending))
  250. {
  251. return;
  252. }
  253. var currentQueue = m_SendingQueue;
  254. if (currentQueue != queue || sendingTrackID != currentQueue.TrackID)
  255. {
  256. //Has been sent
  257. OnSendEnd();
  258. return;
  259. }
  260. }
  261. Socket client;
  262. if (IsInClosingOrClosed && TryValidateClosedBySocket(out client))
  263. {
  264. OnSendEnd(true);
  265. return;
  266. }
  267. SendingQueue newQueue;
  268. if (!m_SendingQueuePool.TryGet(out newQueue))
  269. {
  270. AppSession.Logger.LogError("There is no enougth sending queue can be used.");
  271. OnSendEnd(false);
  272. this.Close(CloseReason.InternalError);
  273. return;
  274. }
  275. var oldQueue = Interlocked.CompareExchange(ref m_SendingQueue, newQueue, queue);
  276. if (!ReferenceEquals(oldQueue, queue))
  277. {
  278. if (newQueue != null)
  279. m_SendingQueuePool.Push(newQueue);
  280. if (IsInClosingOrClosed)
  281. {
  282. OnSendEnd(true);
  283. }
  284. else
  285. {
  286. OnSendEnd(false);
  287. AppSession.Logger.LogError("Failed to switch the sending queue.");
  288. this.Close(CloseReason.InternalError);
  289. }
  290. return;
  291. }
  292. //Start to allow enqueue
  293. newQueue.StartEnqueue();
  294. queue.StopEnqueue();
  295. if (queue.Count == 0)
  296. {
  297. AppSession.Logger.LogError("There is no data to be sent in the queue.");
  298. m_SendingQueuePool.Push(queue);
  299. OnSendEnd(false);
  300. this.Close(CloseReason.InternalError);
  301. return;
  302. }
  303. Send(queue);
  304. }
  305. private void OnSendEnd()
  306. {
  307. OnSendEnd(IsInClosingOrClosed);
  308. }
  309. private void OnSendEnd(bool isInClosingOrClosed)
  310. {
  311. RemoveStateFlag(SocketState.InSending);
  312. if (isInClosingOrClosed)
  313. {
  314. Socket client;
  315. if (!TryValidateClosedBySocket(out client))
  316. {
  317. var sendingQueue = m_SendingQueue;
  318. //No data to be sent
  319. if (sendingQueue != null && sendingQueue.Count == 0)
  320. {
  321. if (client != null)// the socket instance is not closed yet, do it now
  322. InternalClose(client, GetCloseReasonFromState(), false);
  323. else// The UDP mode, the socket instance always is null, fire the closed event directly
  324. OnClosed(GetCloseReasonFromState());
  325. return;
  326. }
  327. return;
  328. }
  329. if (ValidateNotInSendingReceiving())
  330. {
  331. FireCloseEvent();
  332. }
  333. }
  334. }
  335. protected virtual void OnSendingCompleted(SendingQueue queue)
  336. {
  337. queue.Clear();
  338. m_SendingQueuePool.Push(queue);
  339. var newQueue = m_SendingQueue;
  340. if (IsInClosingOrClosed)
  341. {
  342. Socket client;
  343. //has data is being sent and the socket isn't closed
  344. if (newQueue.Count > 0 && !TryValidateClosedBySocket(out client))
  345. {
  346. StartSend(newQueue, newQueue.TrackID, false);
  347. return;
  348. }
  349. OnSendEnd(true);
  350. return;
  351. }
  352. if (newQueue.Count == 0)
  353. {
  354. OnSendEnd();
  355. if (newQueue.Count > 0)
  356. {
  357. StartSend(newQueue, newQueue.TrackID, true);
  358. }
  359. }
  360. else
  361. {
  362. StartSend(newQueue, newQueue.TrackID, false);
  363. }
  364. }
  365. public abstract void ApplySecureProtocol();
  366. public Stream GetUnderlyStream()
  367. {
  368. return new NetworkStream(Client);
  369. }
  370. private Socket m_Client;
  371. /// <summary>
  372. /// Gets or sets the client.
  373. /// </summary>
  374. /// <value>The client.</value>
  375. public Socket Client
  376. {
  377. get { return m_Client; }
  378. }
  379. protected bool IsInClosingOrClosed
  380. {
  381. get { return m_State >= SocketState.InClosing; }
  382. }
  383. protected bool IsClosed
  384. {
  385. get { return m_State >= SocketState.Closed; }
  386. }
  387. /// <summary>
  388. /// Gets the local end point.
  389. /// </summary>
  390. /// <value>The local end point.</value>
  391. public virtual IPEndPoint LocalEndPoint { get; protected set; }
  392. /// <summary>
  393. /// Gets the remote end point.
  394. /// </summary>
  395. /// <value>The remote end point.</value>
  396. public virtual IPEndPoint RemoteEndPoint { get; protected set; }
  397. /// <summary>
  398. /// Gets or sets the secure protocol.
  399. /// </summary>
  400. /// <value>The secure protocol.</value>
  401. public SslProtocols SecureProtocol { get; set; }
  402. protected virtual bool TryValidateClosedBySocket(out Socket socket)
  403. {
  404. socket = m_Client;
  405. //Already closed/closing
  406. return socket == null;
  407. }
  408. public virtual void Close(CloseReason reason)
  409. {
  410. //Already in closing procedure
  411. if (!TryAddStateFlag(SocketState.InClosing))
  412. return;
  413. Socket client;
  414. //No need to clean the socket instance
  415. if (TryValidateClosedBySocket(out client))
  416. return;
  417. //Some data is in sending
  418. if (CheckState(SocketState.InSending))
  419. {
  420. //Set closing reason only, don't close the socket directly
  421. AddStateFlag(GetCloseReasonValue(reason));
  422. return;
  423. }
  424. // In the udp mode, we needn't close the socket instance
  425. if (client != null)
  426. InternalClose(client, reason, true);
  427. else //In Udp mode, and the socket is not in the sending state, then fire the closed event directly
  428. OnClosed(reason);
  429. }
  430. private void InternalClose(Socket client, CloseReason reason, bool setCloseReason)
  431. {
  432. if (Interlocked.CompareExchange(ref m_Client, null, client) == client)
  433. {
  434. if (setCloseReason)
  435. AddStateFlag(GetCloseReasonValue(reason));
  436. client.SafeClose();
  437. if (ValidateNotInSendingReceiving())
  438. {
  439. OnClosed(reason);
  440. }
  441. }
  442. }
  443. protected void OnSendError(SendingQueue queue, CloseReason closeReason)
  444. {
  445. queue.Clear();
  446. m_SendingQueuePool.Push(queue);
  447. OnSendEnd();
  448. ValidateClosed(closeReason);
  449. }
  450. // the receive action won't be started for this connection any more
  451. protected void OnReceiveTerminated(CloseReason closeReason)
  452. {
  453. OnReceiveEnded();
  454. ValidateClosed(closeReason);
  455. }
  456. // return false if the connection has entered the closing procedure or has closed already
  457. protected bool OnReceiveStarted()
  458. {
  459. return AddStateFlag(SocketState.InReceiving, true);
  460. }
  461. protected void OnReceiveEnded()
  462. {
  463. RemoveStateFlag(SocketState.InReceiving);
  464. }
  465. /// <summary>
  466. /// Validates the socket is not in the sending or receiving operation.
  467. /// </summary>
  468. /// <returns></returns>
  469. private bool ValidateNotInSendingReceiving()
  470. {
  471. var oldState = m_State;
  472. if ((oldState & SocketState.InSendingReceivingMask) == oldState)
  473. {
  474. return true;
  475. }
  476. return false;
  477. }
  478. private const int m_CloseReasonMagic = 256;
  479. private int GetCloseReasonValue(CloseReason reason)
  480. {
  481. return ((int)reason + 1) * m_CloseReasonMagic;
  482. }
  483. private CloseReason GetCloseReasonFromState()
  484. {
  485. return (CloseReason)(m_State / m_CloseReasonMagic - 1);
  486. }
  487. private void FireCloseEvent()
  488. {
  489. OnClosed(GetCloseReasonFromState());
  490. }
  491. private void ValidateClosed(CloseReason closeReason)
  492. {
  493. if (IsClosed)
  494. return;
  495. if (CheckState(SocketState.InClosing))
  496. {
  497. if (ValidateNotInSendingReceiving())
  498. {
  499. FireCloseEvent();
  500. }
  501. }
  502. else
  503. {
  504. Close(closeReason);
  505. }
  506. }
  507. public abstract int OrigReceiveOffset { get; }
  508. protected virtual bool IsIgnorableSocketError(int socketErrorCode)
  509. {
  510. if (socketErrorCode == 10004 //Interrupted
  511. || socketErrorCode == 10053 //ConnectionAborted
  512. || socketErrorCode == 10054 //ConnectionReset
  513. || socketErrorCode == 10058 //Shutdown
  514. || socketErrorCode == 10060 //TimedOut
  515. || socketErrorCode == 995 //OperationAborted
  516. || socketErrorCode == -1073741299)
  517. {
  518. return true;
  519. }
  520. return false;
  521. }
  522. protected virtual bool IsIgnorableException(Exception e, out int socketErrorCode)
  523. {
  524. socketErrorCode = 0;
  525. if (e is ObjectDisposedException || e is NullReferenceException)
  526. return true;
  527. SocketException socketException = null;
  528. if (e is IOException)
  529. {
  530. if (e.InnerException is ObjectDisposedException || e.InnerException is NullReferenceException)
  531. return true;
  532. socketException = e.InnerException as SocketException;
  533. }
  534. else
  535. {
  536. socketException = e as SocketException;
  537. }
  538. if (socketException == null)
  539. return false;
  540. socketErrorCode = socketException.ErrorCode;
  541. if (Config.LogAllSocketException)
  542. return false;
  543. return IsIgnorableSocketError(socketErrorCode);
  544. }
  545. }
  546. }