TcpMessageIO.cs 8.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280
  1. // System.Runtime.Remoting.Channels.Tcp.TcpMessageIO.cs
  2. //
  3. // Author: Lluis Sanchez Gual ([email protected])
  4. //
  5. // (C) 2002 Lluis Sanchez Gual
  6. //
  7. // Permission is hereby granted, free of charge, to any person obtaining
  8. // a copy of this software and associated documentation files (the
  9. // "Software"), to deal in the Software without restriction, including
  10. // without limitation the rights to use, copy, modify, merge, publish,
  11. // distribute, sublicense, and/or sell copies of the Software, and to
  12. // permit persons to whom the Software is furnished to do so, subject to
  13. // the following conditions:
  14. //
  15. // The above copyright notice and this permission notice shall be
  16. // included in all copies or substantial portions of the Software.
  17. //
  18. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  19. // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  20. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
  21. // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
  22. // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
  23. // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
  24. // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  25. //
  26. using System;
  27. using System.Runtime.Serialization;
  28. using System.Runtime.Serialization.Formatters.Binary;
  29. using System.Collections;
  30. using System.IO;
  31. using System.Text;
  32. using System.Net.Sockets;
  33. namespace System.Runtime.Remoting.Channels.Tcp
  34. {
  35. enum MessageStatus { MethodMessage = 0, CancelSignal = 1, Unknown = 10}
  36. internal class TcpMessageIO
  37. {
  38. static byte[][] _msgHeaders =
  39. {
  40. new byte[] { (byte)'.', (byte)'N', (byte)'E', (byte)'T', 1, 0 },
  41. new byte[] { 255, 255, 255, 255, 255, 255 }
  42. };
  43. public static int DefaultStreamBufferSize = 1000;
  44. // Identifies an incoming message
  45. public static MessageStatus ReceiveMessageStatus (Stream networkStream, byte[] buffer)
  46. {
  47. try {
  48. StreamRead (networkStream, buffer, 6);
  49. } catch (Exception ex) {
  50. throw new RemotingException ("Tcp transport error.", ex);
  51. }
  52. try
  53. {
  54. bool[] isOnTrack = new bool[_msgHeaders.Length];
  55. bool atLeastOneOnTrack = true;
  56. int i = 0;
  57. while (atLeastOneOnTrack)
  58. {
  59. atLeastOneOnTrack = false;
  60. byte c = buffer [i];
  61. for (int n = 0; n<_msgHeaders.Length; n++)
  62. {
  63. if (i > 0 && !isOnTrack[n]) continue;
  64. isOnTrack[n] = (c == _msgHeaders[n][i]);
  65. if (isOnTrack[n] && (i == _msgHeaders[n].Length-1)) return (MessageStatus) n;
  66. atLeastOneOnTrack = atLeastOneOnTrack || isOnTrack[n];
  67. }
  68. i++;
  69. }
  70. return MessageStatus.Unknown;
  71. }
  72. catch (Exception ex) {
  73. throw new RemotingException ("Tcp transport error.", ex);
  74. }
  75. }
  76. static bool StreamRead (Stream networkStream, byte[] buffer, int count)
  77. {
  78. int nr = 0;
  79. do {
  80. int pr = networkStream.Read (buffer, nr, count - nr);
  81. if (pr == 0)
  82. throw new RemotingException ("Connection closed");
  83. nr += pr;
  84. } while (nr < count);
  85. return true;
  86. }
  87. public static void SendMessageStream (Stream networkStream, Stream data, ITransportHeaders requestHeaders, byte[] buffer)
  88. {
  89. if (buffer == null) buffer = new byte[DefaultStreamBufferSize];
  90. // Writes the message start header
  91. byte[] dotnetHeader = _msgHeaders[(int) MessageStatus.MethodMessage];
  92. networkStream.Write(dotnetHeader, 0, dotnetHeader.Length);
  93. // Writes header tag (0x0000 if request stream, 0x0002 if response stream)
  94. if(requestHeaders[CommonTransportKeys.RequestUri]!=null) buffer [0] = (byte) 0;
  95. else buffer[0] = (byte) 2;
  96. buffer [1] = (byte) 0 ;
  97. // Writes ID
  98. buffer [2] = (byte) 0;
  99. // Writes assemblyID????
  100. buffer [3] = (byte) 0;
  101. // Writes the length of the stream being sent (not including the headers)
  102. int num = (int)data.Length;
  103. buffer [4] = (byte) num;
  104. buffer [5] = (byte) (num >> 8);
  105. buffer [6] = (byte) (num >> 16);
  106. buffer [7] = (byte) (num >> 24);
  107. networkStream.Write(buffer, 0, 8);
  108. // Writes the message headers
  109. SendHeaders (networkStream, requestHeaders, buffer);
  110. // Writes the stream
  111. if (data is MemoryStream)
  112. {
  113. // The copy of the stream can be optimized. The internal
  114. // buffer of MemoryStream can be used.
  115. MemoryStream memStream = (MemoryStream)data;
  116. networkStream.Write (memStream.GetBuffer(), 0, (int)memStream.Length);
  117. }
  118. else
  119. {
  120. int nread = data.Read (buffer, 0, buffer.Length);
  121. while (nread > 0)
  122. {
  123. networkStream.Write (buffer, 0, nread);
  124. nread = data.Read (buffer, 0, buffer.Length);
  125. }
  126. }
  127. }
  128. static byte[] msgUriTransportKey = new byte[] { 4, 0, 1, 1 };
  129. static byte[] msgContentTypeTransportKey = new byte[] { 6, 0, 1, 1 };
  130. static byte[] msgDefaultTransportKey = new byte[] { 1, 0, 1 };
  131. static byte[] msgHeaderTerminator = new byte[] { 0, 0 };
  132. private static void SendHeaders(Stream networkStream, ITransportHeaders requestHeaders, byte[] buffer)
  133. {
  134. // Writes the headers as a sequence of strings
  135. if (networkStream != null)
  136. {
  137. IEnumerator e = requestHeaders.GetEnumerator();
  138. while (e.MoveNext())
  139. {
  140. DictionaryEntry hdr = (DictionaryEntry)e.Current;
  141. switch (hdr.Key.ToString())
  142. {
  143. case CommonTransportKeys.RequestUri:
  144. networkStream.Write (msgUriTransportKey, 0, 4);
  145. break;
  146. case "Content-Type":
  147. networkStream.Write (msgContentTypeTransportKey, 0, 4);
  148. break;
  149. default:
  150. networkStream.Write (msgDefaultTransportKey, 0, 3);
  151. SendString (networkStream, hdr.Key.ToString(), buffer);
  152. networkStream.WriteByte (1);
  153. break;
  154. }
  155. SendString (networkStream, hdr.Value.ToString(), buffer);
  156. }
  157. }
  158. networkStream.Write (msgHeaderTerminator, 0, 2); // End of headers
  159. }
  160. public static ITransportHeaders ReceiveHeaders (Stream networkStream, byte[] buffer)
  161. {
  162. StreamRead (networkStream, buffer, 2);
  163. byte headerType = buffer [0];
  164. TransportHeaders headers = new TransportHeaders ();
  165. while (headerType != 0)
  166. {
  167. string key;
  168. StreamRead (networkStream, buffer, 1); // byte 1
  169. switch (headerType)
  170. {
  171. case 4: key = CommonTransportKeys.RequestUri; break;
  172. case 6: key = "Content-Type"; break;
  173. case 1: key = ReceiveString (networkStream, buffer); break;
  174. default: throw new NotSupportedException ("Unknown header code: " + headerType);
  175. }
  176. StreamRead (networkStream, buffer, 1); // byte 1
  177. headers[key] = ReceiveString (networkStream, buffer);
  178. StreamRead (networkStream, buffer, 2);
  179. headerType = buffer [0];
  180. }
  181. return headers;
  182. }
  183. public static Stream ReceiveMessageStream (Stream networkStream, out ITransportHeaders headers, byte[] buffer)
  184. {
  185. headers = null;
  186. if (buffer == null) buffer = new byte[DefaultStreamBufferSize];
  187. // Reads header tag: 0 -> Stream with headers or 2 -> Response Stream
  188. // +
  189. // Gets the length of the data stream
  190. StreamRead (networkStream, buffer, 8);
  191. int byteCount = (buffer [4] | (buffer [5] << 8) |
  192. (buffer [6] << 16) | (buffer [7] << 24));
  193. // Reads the headers
  194. headers = ReceiveHeaders (networkStream, buffer);
  195. byte[] resultBuffer = new byte[byteCount];
  196. StreamRead (networkStream, resultBuffer, byteCount);
  197. return new MemoryStream (resultBuffer);
  198. }
  199. private static void SendString (Stream networkStream, string str, byte[] buffer)
  200. {
  201. // Allocates a buffer. Use the internal buffer if it is
  202. // big enough. If not, create a new one.
  203. int maxBytes = Encoding.UTF8.GetMaxByteCount(str.Length)+4; //+4 bytes for storing the string length
  204. if (maxBytes > buffer.Length)
  205. buffer = new byte[maxBytes];
  206. int num = Encoding.UTF8.GetBytes (str, 0, str.Length, buffer, 4);
  207. // store number of bytes (not number of chars!)
  208. buffer [0] = (byte) num;
  209. buffer [1] = (byte) (num >> 8);
  210. buffer [2] = (byte) (num >> 16);
  211. buffer [3] = (byte) (num >> 24);
  212. // Write the string bytes
  213. networkStream.Write (buffer, 0, num + 4);
  214. }
  215. private static string ReceiveString (Stream networkStream, byte[] buffer)
  216. {
  217. StreamRead (networkStream, buffer, 4);
  218. // Reads the number of bytes (not chars!)
  219. int byteCount = (buffer [0] | (buffer [1] << 8) |
  220. (buffer [2] << 16) | (buffer [3] << 24));
  221. if (byteCount == 0) return string.Empty;
  222. // Allocates a buffer of the correct size. Use the
  223. // internal buffer if it is big enough
  224. if (byteCount > buffer.Length)
  225. buffer = new byte[byteCount];
  226. // Reads the string
  227. StreamRead (networkStream, buffer, byteCount);
  228. char[] chars = Encoding.UTF8.GetChars (buffer, 0, byteCount);
  229. return new string (chars);
  230. }
  231. }
  232. }