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.

LineReader.cs 7.8 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238
  1. using System;
  2. using System.Net.Sockets;
  3. using System.Text;
  4. using System.Threading.Tasks;
  5. namespace Shadowsocks.Net.Proxy
  6. {
  7. public class LineReader
  8. {
  9. private readonly Socket _socket;
  10. private readonly Func<string, object, bool> _onLineRead;
  11. private readonly Action<Exception, object> _onException;
  12. private readonly Action<byte[], int, int, object> _onFinish;
  13. private readonly Encoding _encoding;
  14. // private readonly string _delimiter;
  15. private readonly byte[] _delimiterBytes;
  16. private readonly int[] _delimiterSearchCharTable;
  17. private readonly int[] _delimiterSearchOffsetTable;
  18. private readonly object _state;
  19. private readonly byte[] _lineBuffer;
  20. private int _bufferIndex;
  21. private readonly TaskCompletionSource<int> finishPromise = new TaskCompletionSource<int>();
  22. public Task Finished => finishPromise.Task;
  23. public LineReader(Socket socket, Func<string, object, bool> onLineRead, Action<Exception, object> onException,
  24. Action<byte[], int, int, object> onFinish, Encoding encoding, string delimiter, int maxLineBytes, object state)
  25. {
  26. if (socket == null)
  27. {
  28. throw new ArgumentNullException(nameof(socket));
  29. }
  30. if (onLineRead == null)
  31. {
  32. throw new ArgumentNullException(nameof(onLineRead));
  33. }
  34. if (encoding == null)
  35. {
  36. throw new ArgumentNullException(nameof(encoding));
  37. }
  38. if (delimiter == null)
  39. {
  40. throw new ArgumentNullException(nameof(delimiter));
  41. }
  42. _socket = socket;
  43. _onLineRead = onLineRead;
  44. _onException = onException;
  45. _onFinish = onFinish;
  46. _encoding = encoding;
  47. // _delimiter = delimiter;
  48. _state = state;
  49. // decode delimiter
  50. _delimiterBytes = encoding.GetBytes(delimiter);
  51. if (_delimiterBytes.Length == 0)
  52. {
  53. throw new ArgumentException("Too short!", nameof(delimiter));
  54. }
  55. if (maxLineBytes < _delimiterBytes.Length)
  56. {
  57. throw new ArgumentException("Too small!", nameof(maxLineBytes));
  58. }
  59. _delimiterSearchCharTable = MakeCharTable(_delimiterBytes);
  60. _delimiterSearchOffsetTable = MakeOffsetTable(_delimiterBytes);
  61. _lineBuffer = new byte[maxLineBytes];
  62. // start reading
  63. socket.BeginReceive(_lineBuffer, 0, maxLineBytes, 0, ReceiveCallback, 0);
  64. }
  65. private void ReceiveCallback(IAsyncResult ar)
  66. {
  67. int length = (int)ar.AsyncState;
  68. try
  69. {
  70. var bytesRead = _socket.EndReceive(ar);
  71. if (bytesRead == 0)
  72. {
  73. OnFinish(length);
  74. finishPromise.TrySetResult(0);
  75. return;
  76. }
  77. length += bytesRead;
  78. int i;
  79. while ((i = IndexOf(_lineBuffer, _bufferIndex, length, _delimiterBytes, _delimiterSearchOffsetTable,
  80. _delimiterSearchCharTable)) != -1)
  81. {
  82. var decodeLen = i - _bufferIndex;
  83. string line = _encoding.GetString(_lineBuffer, _bufferIndex, decodeLen);
  84. _bufferIndex = i + _delimiterBytes.Length;
  85. length -= decodeLen;
  86. length -= _delimiterBytes.Length;
  87. var stop = _onLineRead(line, _state);
  88. if (stop)
  89. {
  90. OnFinish(length);
  91. return;
  92. }
  93. }
  94. if (length == _lineBuffer.Length)
  95. {
  96. OnException(new IndexOutOfRangeException("LineBuffer full! Try increace maxLineBytes!"));
  97. OnFinish(length);
  98. return;
  99. }
  100. if (_bufferIndex > 0)
  101. {
  102. Buffer.BlockCopy(_lineBuffer, _bufferIndex, _lineBuffer, 0, length);
  103. _bufferIndex = 0;
  104. }
  105. _socket.BeginReceive(_lineBuffer, length, _lineBuffer.Length - length, 0, ReceiveCallback, length);
  106. }
  107. catch (Exception ex)
  108. {
  109. OnException(ex);
  110. OnFinish(length);
  111. }
  112. }
  113. private void OnException(Exception ex)
  114. {
  115. finishPromise.TrySetException(ex);
  116. _onException?.Invoke(ex, _state);
  117. }
  118. private void OnFinish(int length)
  119. {
  120. _onFinish?.Invoke(_lineBuffer, _bufferIndex, length, _state);
  121. }
  122. #region Boyer-Moore string search
  123. public static int IndexOf(byte[] haystack, int index, int length, byte[] needle, int[] offsetTable, int[] charTable)
  124. {
  125. var end = index + length;
  126. for (int i = needle.Length - 1 + index, j; i < end;)
  127. {
  128. for (j = needle.Length - 1; needle[j] == haystack[i]; --i, --j)
  129. {
  130. if (j == 0)
  131. {
  132. return i;
  133. }
  134. }
  135. // i += needle.length - j; // For naive method
  136. i += Math.Max(offsetTable[needle.Length - 1 - j], charTable[haystack[i]]);
  137. }
  138. return -1;
  139. }
  140. /**
  141. * Makes the jump table based on the mismatched character information.
  142. */
  143. private static int[] MakeCharTable(byte[] needle)
  144. {
  145. const int ALPHABET_SIZE = 256;
  146. int[] table = new int[ALPHABET_SIZE];
  147. for (int i = 0; i < table.Length; ++i)
  148. {
  149. table[i] = needle.Length;
  150. }
  151. for (int i = 0; i < needle.Length - 1; ++i)
  152. {
  153. table[needle[i]] = needle.Length - 1 - i;
  154. }
  155. return table;
  156. }
  157. /**
  158. * Makes the jump table based on the scan offset which mismatch occurs.
  159. */
  160. private static int[] MakeOffsetTable(byte[] needle)
  161. {
  162. int[] table = new int[needle.Length];
  163. int lastPrefixPosition = needle.Length;
  164. for (int i = needle.Length - 1; i >= 0; --i)
  165. {
  166. if (IsPrefix(needle, i + 1))
  167. {
  168. lastPrefixPosition = i + 1;
  169. }
  170. table[needle.Length - 1 - i] = lastPrefixPosition - i + needle.Length - 1;
  171. }
  172. for (int i = 0; i < needle.Length - 1; ++i)
  173. {
  174. int slen = SuffixLength(needle, i);
  175. table[slen] = needle.Length - 1 - i + slen;
  176. }
  177. return table;
  178. }
  179. /**
  180. * Is needle[p:end] a prefix of needle?
  181. */
  182. private static bool IsPrefix(byte[] needle, int p)
  183. {
  184. for (int i = p, j = 0; i < needle.Length; ++i, ++j)
  185. {
  186. if (needle[i] != needle[j])
  187. {
  188. return false;
  189. }
  190. }
  191. return true;
  192. }
  193. /**
  194. * Returns the maximum length of the substring ends at p and is a suffix.
  195. */
  196. private static int SuffixLength(byte[] needle, int p)
  197. {
  198. int len = 0;
  199. for (int i = p, j = needle.Length - 1;
  200. i >= 0 && needle[i] == needle[j]; --i, --j)
  201. {
  202. len += 1;
  203. }
  204. return len;
  205. }
  206. #endregion
  207. }
  208. }