SendLoop.cs 7.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225
  1. using System;
  2. using System.IO;
  3. using System.Net.Sockets;
  4. using System.Security.Cryptography;
  5. using System.Threading;
  6. using UnityEngine.Profiling;
  7. namespace Mirror.SimpleWeb
  8. {
  9. public static class SendLoopConfig
  10. {
  11. public static volatile bool batchSend = false;
  12. public static volatile bool sleepBeforeSend = false;
  13. }
  14. internal static class SendLoop
  15. {
  16. public struct Config
  17. {
  18. public readonly Connection conn;
  19. public readonly int bufferSize;
  20. public readonly bool setMask;
  21. public Config(Connection conn, int bufferSize, bool setMask)
  22. {
  23. this.conn = conn ?? throw new ArgumentNullException(nameof(conn));
  24. this.bufferSize = bufferSize;
  25. this.setMask = setMask;
  26. }
  27. public void Deconstruct(out Connection conn, out int bufferSize, out bool setMask)
  28. {
  29. conn = this.conn;
  30. bufferSize = this.bufferSize;
  31. setMask = this.setMask;
  32. }
  33. }
  34. public static void Loop(Config config)
  35. {
  36. (Connection conn, int bufferSize, bool setMask) = config;
  37. Profiler.BeginThreadProfiling("SimpleWeb", $"SendLoop {conn.connId}");
  38. // create write buffer for this thread
  39. byte[] writeBuffer = new byte[bufferSize];
  40. MaskHelper maskHelper = setMask ? new MaskHelper() : null;
  41. try
  42. {
  43. TcpClient client = conn.client;
  44. Stream stream = conn.stream;
  45. // null check in case disconnect while send thread is starting
  46. if (client == null)
  47. return;
  48. while (client.Connected)
  49. {
  50. // wait for message
  51. conn.sendPending.Wait();
  52. // wait for 1ms for mirror to send other messages
  53. if (SendLoopConfig.sleepBeforeSend)
  54. Thread.Sleep(1);
  55. conn.sendPending.Reset();
  56. if (SendLoopConfig.batchSend)
  57. {
  58. int offset = 0;
  59. while (conn.sendQueue.TryDequeue(out ArrayBuffer msg))
  60. {
  61. // check if connected before sending message
  62. if (!client.Connected)
  63. {
  64. Log.Verbose($"[SWT-SendLoop]: SendLoop {conn} not connected");
  65. msg.Release();
  66. return;
  67. }
  68. int maxLength = msg.count + Constants.HeaderSize + Constants.MaskSize;
  69. // if next writer could overflow, write to stream and clear buffer
  70. if (offset + maxLength > bufferSize)
  71. {
  72. stream.Write(writeBuffer, 0, offset);
  73. offset = 0;
  74. }
  75. offset = SendMessage(writeBuffer, offset, msg, setMask, maskHelper);
  76. msg.Release();
  77. }
  78. // after no message in queue, send remaining messages
  79. // don't need to check offset > 0 because last message in queue will always be sent here
  80. stream.Write(writeBuffer, 0, offset);
  81. }
  82. else
  83. {
  84. while (conn.sendQueue.TryDequeue(out ArrayBuffer msg))
  85. {
  86. // check if connected before sending message
  87. if (!client.Connected)
  88. {
  89. Log.Verbose($"[SWT-SendLoop]: SendLoop {conn} not connected");
  90. msg.Release();
  91. return;
  92. }
  93. int length = SendMessage(writeBuffer, 0, msg, setMask, maskHelper);
  94. stream.Write(writeBuffer, 0, length);
  95. msg.Release();
  96. }
  97. }
  98. }
  99. Log.Verbose($"[SWT-SendLoop]: {conn} Not Connected");
  100. }
  101. catch (ThreadInterruptedException e) { Log.InfoException(e); }
  102. catch (ThreadAbortException e) { Log.InfoException(e); }
  103. catch (Exception e)
  104. {
  105. Log.Exception(e);
  106. }
  107. finally
  108. {
  109. Profiler.EndThreadProfiling();
  110. conn.Dispose();
  111. maskHelper?.Dispose();
  112. }
  113. }
  114. /// <returns>new offset in buffer</returns>
  115. static int SendMessage(byte[] buffer, int startOffset, ArrayBuffer msg, bool setMask, MaskHelper maskHelper)
  116. {
  117. int msgLength = msg.count;
  118. int offset = WriteHeader(buffer, startOffset, msgLength, setMask);
  119. if (setMask)
  120. {
  121. offset = maskHelper.WriteMask(buffer, offset);
  122. }
  123. msg.CopyTo(buffer, offset);
  124. offset += msgLength;
  125. // dump before mask on
  126. Log.DumpBuffer("[SWT-SendLoop]: Send", buffer, startOffset, offset);
  127. if (setMask)
  128. {
  129. int messageOffset = offset - msgLength;
  130. MessageProcessor.ToggleMask(buffer, messageOffset, msgLength, buffer, messageOffset - Constants.MaskSize);
  131. }
  132. return offset;
  133. }
  134. public static int WriteHeader(byte[] buffer, int startOffset, int msgLength, bool setMask)
  135. {
  136. int sendLength = 0;
  137. const byte finished = 128;
  138. const byte byteOpCode = 2;
  139. buffer[startOffset + 0] = finished | byteOpCode;
  140. sendLength++;
  141. if (msgLength <= Constants.BytePayloadLength)
  142. {
  143. buffer[startOffset + 1] = (byte)msgLength;
  144. sendLength++;
  145. }
  146. else if (msgLength <= ushort.MaxValue)
  147. {
  148. buffer[startOffset + 1] = 126;
  149. buffer[startOffset + 2] = (byte)(msgLength >> 8);
  150. buffer[startOffset + 3] = (byte)msgLength;
  151. sendLength += 3;
  152. }
  153. else
  154. {
  155. buffer[startOffset + 1] = 127;
  156. // must be 64 bytes, but we only have 32 bit length, so first 4 bits are 0
  157. buffer[startOffset + 2] = 0;
  158. buffer[startOffset + 3] = 0;
  159. buffer[startOffset + 4] = 0;
  160. buffer[startOffset + 5] = 0;
  161. buffer[startOffset + 6] = (byte)(msgLength >> 24);
  162. buffer[startOffset + 7] = (byte)(msgLength >> 16);
  163. buffer[startOffset + 8] = (byte)(msgLength >> 8);
  164. buffer[startOffset + 9] = (byte)msgLength;
  165. sendLength += 9;
  166. }
  167. if (setMask)
  168. buffer[startOffset + 1] |= 0b1000_0000;
  169. return sendLength + startOffset;
  170. }
  171. }
  172. sealed class MaskHelper : IDisposable
  173. {
  174. readonly byte[] maskBuffer;
  175. readonly RNGCryptoServiceProvider random;
  176. public MaskHelper()
  177. {
  178. maskBuffer = new byte[4];
  179. random = new RNGCryptoServiceProvider();
  180. }
  181. public void Dispose()
  182. {
  183. random.Dispose();
  184. }
  185. public int WriteMask(byte[] buffer, int offset)
  186. {
  187. random.GetBytes(maskBuffer);
  188. Buffer.BlockCopy(maskBuffer, 0, buffer, offset, 4);
  189. return offset + 4;
  190. }
  191. }
  192. }