TcpMessageIO.cs 8.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298
  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. SendMessageStream (networkStream, data, requestHeaders, buffer, false);
  90. }
  91. public static void SendMessageStream (Stream networkStream, Stream data, ITransportHeaders requestHeaders, byte[] buffer, bool isOneWay)
  92. {
  93. if (buffer == null) buffer = new byte[DefaultStreamBufferSize];
  94. // Writes the message start header
  95. byte[] dotnetHeader = _msgHeaders[(int) MessageStatus.MethodMessage];
  96. networkStream.Write(dotnetHeader, 0, dotnetHeader.Length);
  97. // Writes the header tag
  98. // 0x0000 - request stream
  99. // 0x0001 - OneWay request stream
  100. // 0x0002 - response stream
  101. if(requestHeaders[CommonTransportKeys.RequestUri]!=null) {
  102. buffer [0] = isOneWay ? (byte) 1 : (byte) 0;
  103. }
  104. else {
  105. buffer[0] = (byte) 2;
  106. }
  107. buffer [1] = (byte) 0 ;
  108. // Writes ID
  109. buffer [2] = (byte) 0;
  110. // Writes assemblyID????
  111. buffer [3] = (byte) 0;
  112. // Writes the length of the stream being sent (not including the headers)
  113. int num = (int)data.Length;
  114. buffer [4] = (byte) num;
  115. buffer [5] = (byte) (num >> 8);
  116. buffer [6] = (byte) (num >> 16);
  117. buffer [7] = (byte) (num >> 24);
  118. networkStream.Write(buffer, 0, 8);
  119. // Writes the message headers
  120. SendHeaders (networkStream, requestHeaders, buffer);
  121. if (data.Length == 0)
  122. return;
  123. // Writes the stream
  124. if (data is MemoryStream)
  125. {
  126. // The copy of the stream can be optimized. The internal
  127. // buffer of MemoryStream can be used.
  128. MemoryStream memStream = (MemoryStream)data;
  129. networkStream.Write (memStream.GetBuffer(), 0, (int)memStream.Length);
  130. }
  131. else
  132. {
  133. int nread = data.Read (buffer, 0, buffer.Length);
  134. while (nread > 0)
  135. {
  136. networkStream.Write (buffer, 0, nread);
  137. nread = data.Read (buffer, 0, buffer.Length);
  138. }
  139. }
  140. }
  141. static byte[] msgUriTransportKey = new byte[] { 4, 0, 1, 1 };
  142. static byte[] msgContentTypeTransportKey = new byte[] { 6, 0, 1, 1 };
  143. static byte[] msgDefaultTransportKey = new byte[] { 1, 0, 1 };
  144. static byte[] msgHeaderTerminator = new byte[] { 0, 0 };
  145. private static void SendHeaders(Stream networkStream, ITransportHeaders requestHeaders, byte[] buffer)
  146. {
  147. // Writes the headers as a sequence of strings
  148. if (networkStream != null)
  149. {
  150. IEnumerator e = requestHeaders.GetEnumerator();
  151. while (e.MoveNext())
  152. {
  153. DictionaryEntry hdr = (DictionaryEntry)e.Current;
  154. switch (hdr.Key.ToString())
  155. {
  156. case CommonTransportKeys.RequestUri:
  157. networkStream.Write (msgUriTransportKey, 0, 4);
  158. break;
  159. case "Content-Type":
  160. networkStream.Write (msgContentTypeTransportKey, 0, 4);
  161. break;
  162. default:
  163. networkStream.Write (msgDefaultTransportKey, 0, 3);
  164. SendString (networkStream, hdr.Key.ToString(), buffer);
  165. networkStream.WriteByte (1);
  166. break;
  167. }
  168. SendString (networkStream, hdr.Value.ToString(), buffer);
  169. }
  170. }
  171. networkStream.Write (msgHeaderTerminator, 0, 2); // End of headers
  172. }
  173. public static ITransportHeaders ReceiveHeaders (Stream networkStream, byte[] buffer)
  174. {
  175. StreamRead (networkStream, buffer, 2);
  176. byte headerType = buffer [0];
  177. TransportHeaders headers = new TransportHeaders ();
  178. while (headerType != 0)
  179. {
  180. string key;
  181. StreamRead (networkStream, buffer, 1); // byte 1
  182. switch (headerType)
  183. {
  184. case 4: key = CommonTransportKeys.RequestUri; break;
  185. case 6: key = "Content-Type"; break;
  186. case 1: key = ReceiveString (networkStream, buffer); break;
  187. default: throw new NotSupportedException ("Unknown header code: " + headerType);
  188. }
  189. StreamRead (networkStream, buffer, 1); // byte 1
  190. headers[key] = ReceiveString (networkStream, buffer);
  191. StreamRead (networkStream, buffer, 2);
  192. headerType = buffer [0];
  193. }
  194. return headers;
  195. }
  196. public static Stream ReceiveMessageStream (Stream networkStream, out ITransportHeaders headers, byte[] buffer)
  197. {
  198. headers = null;
  199. if (buffer == null) buffer = new byte[DefaultStreamBufferSize];
  200. // Reads header tag: 0 -> Stream with headers or 2 -> Response Stream
  201. // +
  202. // Gets the length of the data stream
  203. StreamRead (networkStream, buffer, 8);
  204. int byteCount = (buffer [4] | (buffer [5] << 8) |
  205. (buffer [6] << 16) | (buffer [7] << 24));
  206. // Reads the headers
  207. headers = ReceiveHeaders (networkStream, buffer);
  208. if (byteCount > 0) {
  209. byte[] resultBuffer = new byte[byteCount];
  210. StreamRead (networkStream, resultBuffer, byteCount);
  211. return new MemoryStream (resultBuffer);
  212. } else {
  213. return new MemoryStream ();
  214. }
  215. }
  216. private static void SendString (Stream networkStream, string str, byte[] buffer)
  217. {
  218. // Allocates a buffer. Use the internal buffer if it is
  219. // big enough. If not, create a new one.
  220. int maxBytes = Encoding.UTF8.GetMaxByteCount(str.Length)+4; //+4 bytes for storing the string length
  221. if (maxBytes > buffer.Length)
  222. buffer = new byte[maxBytes];
  223. int num = Encoding.UTF8.GetBytes (str, 0, str.Length, buffer, 4);
  224. // store number of bytes (not number of chars!)
  225. buffer [0] = (byte) num;
  226. buffer [1] = (byte) (num >> 8);
  227. buffer [2] = (byte) (num >> 16);
  228. buffer [3] = (byte) (num >> 24);
  229. // Write the string bytes
  230. networkStream.Write (buffer, 0, num + 4);
  231. }
  232. private static string ReceiveString (Stream networkStream, byte[] buffer)
  233. {
  234. StreamRead (networkStream, buffer, 4);
  235. // Reads the number of bytes (not chars!)
  236. int byteCount = (buffer [0] | (buffer [1] << 8) |
  237. (buffer [2] << 16) | (buffer [3] << 24));
  238. if (byteCount == 0) return string.Empty;
  239. // Allocates a buffer of the correct size. Use the
  240. // internal buffer if it is big enough
  241. if (byteCount > buffer.Length)
  242. buffer = new byte[byteCount];
  243. // Reads the string
  244. StreamRead (networkStream, buffer, byteCount);
  245. char[] chars = Encoding.UTF8.GetChars (buffer, 0, byteCount);
  246. return new string (chars);
  247. }
  248. }
  249. }