TcpMessageIO.cs 8.3 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)
  46. {
  47. try
  48. {
  49. bool[] isOnTrack = new bool[_msgHeaders.Length];
  50. bool atLeastOneOnTrack = true;
  51. int i = 0;
  52. while (atLeastOneOnTrack)
  53. {
  54. atLeastOneOnTrack = false;
  55. byte c = (byte)networkStream.ReadByte();
  56. for (int n = 0; n<_msgHeaders.Length; n++)
  57. {
  58. if (i > 0 && !isOnTrack[n]) continue;
  59. isOnTrack[n] = (c == _msgHeaders[n][i]);
  60. if (isOnTrack[n] && (i == _msgHeaders[n].Length-1)) return (MessageStatus) n;
  61. atLeastOneOnTrack = atLeastOneOnTrack || isOnTrack[n];
  62. }
  63. i++;
  64. }
  65. return MessageStatus.Unknown;
  66. }
  67. catch (IOException)
  68. {
  69. // Stream closed
  70. return MessageStatus.CancelSignal;
  71. }
  72. }
  73. public static void SendMessageStream (Stream networkStream, Stream data, ITransportHeaders requestHeaders, byte[] buffer)
  74. {
  75. if (buffer == null) buffer = new byte[DefaultStreamBufferSize];
  76. // Writes the message start header
  77. byte[] dotnetHeader = _msgHeaders[(int) MessageStatus.MethodMessage];
  78. networkStream.Write(dotnetHeader, 0, dotnetHeader.Length);
  79. // Writes header tag (0x0000 if request stream, 0x0002 if response stream)
  80. if(requestHeaders[CommonTransportKeys.RequestUri]!=null) buffer [0] = (byte) 0;
  81. else buffer[0] = (byte) 2;
  82. buffer [1] = (byte) 0 ;
  83. // Writes ID
  84. buffer [2] = (byte) 0;
  85. // Writes assemblyID????
  86. buffer [3] = (byte) 0;
  87. // Writes the length of the stream being sent (not including the headers)
  88. int num = (int)data.Length;
  89. buffer [4] = (byte) num;
  90. buffer [5] = (byte) (num >> 8);
  91. buffer [6] = (byte) (num >> 16);
  92. buffer [7] = (byte) (num >> 24);
  93. networkStream.Write(buffer, 0, 8);
  94. // Writes the message headers
  95. SendHeaders (networkStream, requestHeaders, buffer);
  96. // Writes the stream
  97. if (data is MemoryStream)
  98. {
  99. // The copy of the stream can be optimized. The internal
  100. // buffer of MemoryStream can be used.
  101. MemoryStream memStream = (MemoryStream)data;
  102. networkStream.Write (memStream.GetBuffer(), 0, (int)memStream.Length);
  103. }
  104. else
  105. {
  106. int nread = data.Read (buffer, 0, buffer.Length);
  107. while (nread > 0)
  108. {
  109. networkStream.Write (buffer, 0, nread);
  110. nread = data.Read (buffer, 0, buffer.Length);
  111. }
  112. }
  113. }
  114. private static void SendHeaders(Stream networkStream, ITransportHeaders requestHeaders, byte[] buffer)
  115. {
  116. // Writes the headers as a sequence of strings
  117. if (networkStream != null)
  118. {
  119. IEnumerator e = requestHeaders.GetEnumerator();
  120. while (e.MoveNext())
  121. {
  122. DictionaryEntry hdr = (DictionaryEntry)e.Current;
  123. switch (hdr.Key.ToString())
  124. {
  125. case CommonTransportKeys.RequestUri:
  126. buffer[0] = 4; buffer[1] = 0; buffer[2] = 1;
  127. networkStream.Write(buffer, 0, 3);
  128. break;
  129. case "Content-Type":
  130. buffer[0] = 6; buffer[1] = 0; buffer[2] = 1;
  131. networkStream.Write(buffer, 0, 3);
  132. break;
  133. default:
  134. buffer[0] = 1; buffer[1] = 0; buffer[2] = 1;
  135. networkStream.Write(buffer, 0, 3);
  136. SendString (networkStream, hdr.Key.ToString(), buffer);
  137. break;
  138. }
  139. networkStream.WriteByte (1);
  140. SendString (networkStream, hdr.Value.ToString(), buffer);
  141. }
  142. }
  143. networkStream.WriteByte (0); // End of headers
  144. networkStream.WriteByte (0);
  145. }
  146. public static ITransportHeaders ReceiveHeaders (Stream networkStream, byte[] buffer)
  147. {
  148. byte headerType;
  149. headerType = (byte) networkStream.ReadByte ();
  150. networkStream.ReadByte ();
  151. TransportHeaders headers = new TransportHeaders ();
  152. while (headerType != 0)
  153. {
  154. string key;
  155. networkStream.ReadByte (); // byte 1
  156. switch (headerType)
  157. {
  158. case 4: key = CommonTransportKeys.RequestUri; break;
  159. case 6: key = "Content-Type"; break;
  160. case 1: key = ReceiveString (networkStream, buffer); break;
  161. default: throw new NotSupportedException ("Unknown header code: " + headerType);
  162. }
  163. networkStream.ReadByte (); // byte 1
  164. headers[key] = ReceiveString (networkStream, buffer);
  165. headerType = (byte) networkStream.ReadByte ();
  166. networkStream.ReadByte ();
  167. }
  168. return headers;
  169. }
  170. public static Stream ReceiveMessageStream (Stream networkStream, out ITransportHeaders headers, byte[] buffer)
  171. {
  172. headers = null;
  173. if (buffer == null) buffer = new byte[DefaultStreamBufferSize];
  174. // Reads header tag: 0 -> Stream with headers or 2 -> Response Stream
  175. byte head = (byte)networkStream.ReadByte();
  176. byte c = (byte)networkStream.ReadByte();
  177. c = (byte)networkStream.ReadByte();
  178. c = (byte)networkStream.ReadByte();
  179. // Gets the length of the data stream
  180. int nr = 0;
  181. while (nr < 4)
  182. nr += networkStream.Read (buffer, nr, 4 - nr);
  183. int byteCount = (buffer [0] | (buffer [1] << 8) |
  184. (buffer [2] << 16) | (buffer [3] << 24));
  185. // Reads the headers
  186. headers = ReceiveHeaders (networkStream, buffer);
  187. byte[] resultBuffer = new byte[byteCount];
  188. nr = 0;
  189. while (nr < byteCount)
  190. nr += networkStream.Read (resultBuffer, nr, byteCount - nr);
  191. return new MemoryStream(resultBuffer);
  192. }
  193. private static void SendString (Stream networkStream, string str, byte[] buffer)
  194. {
  195. // Allocates a buffer. Use the internal buffer if it is
  196. // big enough. If not, create a new one.
  197. int maxBytes = Encoding.UTF8.GetMaxByteCount(str.Length)+4; //+4 bytes for storing the string length
  198. if (maxBytes > buffer.Length)
  199. buffer = new byte[maxBytes];
  200. int num = Encoding.UTF8.GetBytes (str, 0, str.Length, buffer, 4);
  201. // store number of bytes (not number of chars!)
  202. buffer [0] = (byte) num;
  203. buffer [1] = (byte) (num >> 8);
  204. buffer [2] = (byte) (num >> 16);
  205. buffer [3] = (byte) (num >> 24);
  206. // Write the string bytes
  207. networkStream.Write (buffer, 0, num + 4);
  208. }
  209. private static string ReceiveString (Stream networkStream, byte[] buffer)
  210. {
  211. int nr = 0;
  212. while (nr < 4)
  213. nr += networkStream.Read (buffer, nr, 4 - nr);
  214. // Reads the number of bytes (not chars!)
  215. int byteCount = (buffer [0] | (buffer [1] << 8) |
  216. (buffer [2] << 16) | (buffer [3] << 24));
  217. if (byteCount == 0) return string.Empty;
  218. // Allocates a buffer of the correct size. Use the
  219. // internal buffer if it is big enough
  220. if (byteCount > buffer.Length)
  221. buffer = new byte[byteCount];
  222. // Reads the string
  223. nr = 0;
  224. while (nr < byteCount)
  225. nr += networkStream.Read (buffer, nr, byteCount - nr);
  226. char[] chars = Encoding.UTF8.GetChars(buffer, 0, byteCount);
  227. return new string(chars);
  228. }
  229. }
  230. }