TcpMessageIO.cs 8.8 KB

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