SocketSession.cs 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663
  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. //if (SyncSend)
  231. //{
  232. // SendSync(queue);
  233. //}
  234. //else
  235. //{
  236. // SendAsync(queue);
  237. //}
  238. SendAsync(queue);
  239. }
  240. private void StartSend(SendingQueue queue, int sendingTrackID, bool initial)
  241. {
  242. if (initial)
  243. {
  244. if (!TryAddStateFlag(SocketState.InSending))
  245. {
  246. return;
  247. }
  248. var currentQueue = m_SendingQueue;
  249. if (currentQueue != queue || sendingTrackID != currentQueue.TrackID)
  250. {
  251. //Has been sent
  252. OnSendEnd();
  253. return;
  254. }
  255. }
  256. Socket client;
  257. if (IsInClosingOrClosed && TryValidateClosedBySocket(out client))
  258. {
  259. OnSendEnd(true);
  260. return;
  261. }
  262. SendingQueue newQueue;
  263. if (!m_SendingQueuePool.TryGet(out newQueue))
  264. {
  265. AppSession.Logger.LogError("There is no enougth sending queue can be used.");
  266. OnSendEnd(false);
  267. this.Close(CloseReason.InternalError);
  268. return;
  269. }
  270. var oldQueue = Interlocked.CompareExchange(ref m_SendingQueue, newQueue, queue);
  271. if (!ReferenceEquals(oldQueue, queue))
  272. {
  273. if (newQueue != null)
  274. m_SendingQueuePool.Push(newQueue);
  275. if (IsInClosingOrClosed)
  276. {
  277. OnSendEnd(true);
  278. }
  279. else
  280. {
  281. OnSendEnd(false);
  282. AppSession.Logger.LogError("Failed to switch the sending queue.");
  283. this.Close(CloseReason.InternalError);
  284. }
  285. return;
  286. }
  287. //Start to allow enqueue
  288. newQueue.StartEnqueue();
  289. queue.StopEnqueue();
  290. if (queue.Count == 0)
  291. {
  292. AppSession.Logger.LogError("There is no data to be sent in the queue.");
  293. m_SendingQueuePool.Push(queue);
  294. OnSendEnd(false);
  295. this.Close(CloseReason.InternalError);
  296. return;
  297. }
  298. Send(queue);
  299. }
  300. private void OnSendEnd()
  301. {
  302. OnSendEnd(IsInClosingOrClosed);
  303. }
  304. private void OnSendEnd(bool isInClosingOrClosed)
  305. {
  306. RemoveStateFlag(SocketState.InSending);
  307. if (isInClosingOrClosed)
  308. {
  309. Socket client;
  310. if (!TryValidateClosedBySocket(out client))
  311. {
  312. var sendingQueue = m_SendingQueue;
  313. //No data to be sent
  314. if (sendingQueue != null && sendingQueue.Count == 0)
  315. {
  316. if (client != null)// the socket instance is not closed yet, do it now
  317. InternalClose(client, GetCloseReasonFromState(), false);
  318. else// The UDP mode, the socket instance always is null, fire the closed event directly
  319. OnClosed(GetCloseReasonFromState());
  320. return;
  321. }
  322. return;
  323. }
  324. if (ValidateNotInSendingReceiving())
  325. {
  326. FireCloseEvent();
  327. }
  328. }
  329. }
  330. protected virtual void OnSendingCompleted(SendingQueue queue)
  331. {
  332. queue.Clear();
  333. m_SendingQueuePool.Push(queue);
  334. var newQueue = m_SendingQueue;
  335. if (IsInClosingOrClosed)
  336. {
  337. Socket client;
  338. //has data is being sent and the socket isn't closed
  339. if (newQueue.Count > 0 && !TryValidateClosedBySocket(out client))
  340. {
  341. StartSend(newQueue, newQueue.TrackID, false);
  342. return;
  343. }
  344. OnSendEnd(true);
  345. return;
  346. }
  347. if (newQueue.Count == 0)
  348. {
  349. OnSendEnd();
  350. if (newQueue.Count > 0)
  351. {
  352. StartSend(newQueue, newQueue.TrackID, true);
  353. }
  354. }
  355. else
  356. {
  357. StartSend(newQueue, newQueue.TrackID, false);
  358. }
  359. }
  360. public abstract void ApplySecureProtocol();
  361. public Stream GetUnderlyStream()
  362. {
  363. return new NetworkStream(Client);
  364. }
  365. private Socket m_Client;
  366. /// <summary>
  367. /// Gets or sets the client.
  368. /// </summary>
  369. /// <value>The client.</value>
  370. public Socket Client
  371. {
  372. get { return m_Client; }
  373. }
  374. protected bool IsInClosingOrClosed
  375. {
  376. get { return m_State >= SocketState.InClosing; }
  377. }
  378. protected bool IsClosed
  379. {
  380. get { return m_State >= SocketState.Closed; }
  381. }
  382. /// <summary>
  383. /// Gets the local end point.
  384. /// </summary>
  385. /// <value>The local end point.</value>
  386. public virtual IPEndPoint LocalEndPoint { get; protected set; }
  387. /// <summary>
  388. /// Gets the remote end point.
  389. /// </summary>
  390. /// <value>The remote end point.</value>
  391. public virtual IPEndPoint RemoteEndPoint { get; protected set; }
  392. /// <summary>
  393. /// Gets or sets the secure protocol.
  394. /// </summary>
  395. /// <value>The secure protocol.</value>
  396. public SslProtocols SecureProtocol { get; set; }
  397. protected virtual bool TryValidateClosedBySocket(out Socket socket)
  398. {
  399. socket = m_Client;
  400. //Already closed/closing
  401. return socket == null;
  402. }
  403. public virtual void Close(CloseReason reason)
  404. {
  405. //Already in closing procedure
  406. if (!TryAddStateFlag(SocketState.InClosing))
  407. return;
  408. Socket client;
  409. //No need to clean the socket instance
  410. if (TryValidateClosedBySocket(out client))
  411. return;
  412. //Some data is in sending
  413. if (CheckState(SocketState.InSending))
  414. {
  415. //Set closing reason only, don't close the socket directly
  416. AddStateFlag(GetCloseReasonValue(reason));
  417. return;
  418. }
  419. // In the udp mode, we needn't close the socket instance
  420. if (client != null)
  421. InternalClose(client, reason, true);
  422. else //In Udp mode, and the socket is not in the sending state, then fire the closed event directly
  423. OnClosed(reason);
  424. }
  425. private void InternalClose(Socket client, CloseReason reason, bool setCloseReason)
  426. {
  427. if (Interlocked.CompareExchange(ref m_Client, null, client) == client)
  428. {
  429. if (setCloseReason)
  430. AddStateFlag(GetCloseReasonValue(reason));
  431. client.SafeClose();
  432. if (ValidateNotInSendingReceiving())
  433. {
  434. OnClosed(reason);
  435. }
  436. }
  437. }
  438. protected void OnSendError(SendingQueue queue, CloseReason closeReason)
  439. {
  440. queue.Clear();
  441. m_SendingQueuePool.Push(queue);
  442. OnSendEnd();
  443. ValidateClosed(closeReason);
  444. }
  445. // the receive action won't be started for this connection any more
  446. protected void OnReceiveTerminated(CloseReason closeReason)
  447. {
  448. OnReceiveEnded();
  449. ValidateClosed(closeReason);
  450. }
  451. // return false if the connection has entered the closing procedure or has closed already
  452. protected bool OnReceiveStarted()
  453. {
  454. return AddStateFlag(SocketState.InReceiving, true);
  455. }
  456. protected void OnReceiveEnded()
  457. {
  458. RemoveStateFlag(SocketState.InReceiving);
  459. }
  460. /// <summary>
  461. /// Validates the socket is not in the sending or receiving operation.
  462. /// </summary>
  463. /// <returns></returns>
  464. private bool ValidateNotInSendingReceiving()
  465. {
  466. var oldState = m_State;
  467. if ((oldState & SocketState.InSendingReceivingMask) == oldState)
  468. {
  469. return true;
  470. }
  471. return false;
  472. }
  473. private const int m_CloseReasonMagic = 256;
  474. private int GetCloseReasonValue(CloseReason reason)
  475. {
  476. return ((int)reason + 1) * m_CloseReasonMagic;
  477. }
  478. private CloseReason GetCloseReasonFromState()
  479. {
  480. return (CloseReason)(m_State / m_CloseReasonMagic - 1);
  481. }
  482. private void FireCloseEvent()
  483. {
  484. OnClosed(GetCloseReasonFromState());
  485. }
  486. private void ValidateClosed(CloseReason closeReason)
  487. {
  488. if (IsClosed)
  489. return;
  490. if (CheckState(SocketState.InClosing))
  491. {
  492. if (ValidateNotInSendingReceiving())
  493. {
  494. FireCloseEvent();
  495. }
  496. }
  497. else
  498. {
  499. Close(closeReason);
  500. }
  501. }
  502. public abstract int OrigReceiveOffset { get; }
  503. protected virtual bool IsIgnorableSocketError(int socketErrorCode)
  504. {
  505. if (socketErrorCode == 10004 //Interrupted
  506. || socketErrorCode == 10053 //ConnectionAborted
  507. || socketErrorCode == 10054 //ConnectionReset
  508. || socketErrorCode == 10058 //Shutdown
  509. || socketErrorCode == 10060 //TimedOut
  510. || socketErrorCode == 995 //OperationAborted
  511. || socketErrorCode == -1073741299)
  512. {
  513. return true;
  514. }
  515. return false;
  516. }
  517. protected virtual bool IsIgnorableException(Exception e, out int socketErrorCode)
  518. {
  519. socketErrorCode = 0;
  520. if (e is ObjectDisposedException || e is NullReferenceException)
  521. return true;
  522. SocketException socketException = null;
  523. if (e is IOException)
  524. {
  525. if (e.InnerException is ObjectDisposedException || e.InnerException is NullReferenceException)
  526. return true;
  527. socketException = e.InnerException as SocketException;
  528. }
  529. else
  530. {
  531. socketException = e as SocketException;
  532. }
  533. if (socketException == null)
  534. return false;
  535. socketErrorCode = socketException.ErrorCode;
  536. if (Config.LogAllSocketException)
  537. return false;
  538. return IsIgnorableSocketError(socketErrorCode);
  539. }
  540. }
  541. }