TcpDuplexSessionChannel.cs 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521
  1. //
  2. // TcpDuplexSessionChannel.cs
  3. //
  4. // Author:
  5. // Marcos Cobena ([email protected])
  6. // Atsushi Enomoto <[email protected]>
  7. //
  8. // Copyright 2007 Marcos Cobena (http://www.youcannoteatbits.org/)
  9. //
  10. // Copyright (C) 2009 Novell, Inc (http://www.novell.com)
  11. //
  12. // Permission is hereby granted, free of charge, to any person obtaining
  13. // a copy of this software and associated documentation files (the
  14. // "Software"), to deal in the Software without restriction, including
  15. // without limitation the rights to use, copy, modify, merge, publish,
  16. // distribute, sublicense, and/or sell copies of the Software, and to
  17. // permit persons to whom the Software is furnished to do so, subject to
  18. // the following conditions:
  19. //
  20. // The above copyright notice and this permission notice shall be
  21. // included in all copies or substantial portions of the Software.
  22. //
  23. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  24. // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  25. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
  26. // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
  27. // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
  28. // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
  29. // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  30. //
  31. using System;
  32. using System.Collections.Generic;
  33. using System.IO;
  34. using System.Net;
  35. using System.Net.Sockets;
  36. using System.Runtime.Serialization;
  37. using System.Runtime.Serialization.Formatters.Binary;
  38. using System.ServiceModel.Channels;
  39. using System.Text;
  40. using System.Xml;
  41. namespace System.ServiceModel.Channels
  42. {
  43. internal class TcpDuplexSessionChannel : DuplexChannelBase, IDuplexSessionChannel
  44. {
  45. TcpChannelInfo info;
  46. TcpClient client;
  47. bool is_service_side;
  48. EndpointAddress local_address;
  49. TcpListener tcp_listener;
  50. TimeSpan timeout;
  51. TcpBinaryFrameManager frame;
  52. public TcpDuplexSessionChannel (ChannelFactoryBase factory, TcpChannelInfo info, EndpointAddress address, Uri via)
  53. : base (factory, address, via)
  54. {
  55. is_service_side = false;
  56. this.info = info;
  57. }
  58. public TcpDuplexSessionChannel (ChannelListenerBase listener, TcpChannelInfo info, TcpListener tcpListener, TimeSpan timeout)
  59. : base (listener)
  60. {
  61. is_service_side = true;
  62. tcp_listener = tcpListener;
  63. this.info = info;
  64. this.timeout = timeout;
  65. }
  66. public MessageEncoder Encoder {
  67. get { return info.MessageEncoder; }
  68. }
  69. public override EndpointAddress LocalAddress {
  70. get { return local_address; }
  71. }
  72. // FIXME: implement
  73. public IDuplexSession Session {
  74. get { throw new NotImplementedException (); }
  75. }
  76. [MonoTODO]
  77. public override IAsyncResult BeginSend (Message message, AsyncCallback callback, object state)
  78. {
  79. throw new NotImplementedException ();
  80. }
  81. [MonoTODO]
  82. public override IAsyncResult BeginSend (Message message, TimeSpan timeout, AsyncCallback callback, object state)
  83. {
  84. throw new NotImplementedException ();
  85. }
  86. [MonoTODO]
  87. public override void EndSend (IAsyncResult result)
  88. {
  89. throw new NotImplementedException ();
  90. }
  91. public override void Send (Message message)
  92. {
  93. Send (message, DefaultSendTimeout);
  94. }
  95. public override void Send (Message message, TimeSpan timeout)
  96. {
  97. client.SendTimeout = (int) timeout.TotalMilliseconds;
  98. frame.WriteSizedMessage (message);
  99. // FIXME: should EndRecord be sent here?
  100. //if (is_service_side && client.Available > 0)
  101. // frame.ProcessEndRecordRecipient ();
  102. }
  103. [MonoTODO]
  104. public override IAsyncResult BeginReceive (AsyncCallback callback, object state)
  105. {
  106. throw new NotImplementedException ();
  107. }
  108. [MonoTODO]
  109. public override IAsyncResult BeginReceive (TimeSpan timeout, AsyncCallback callback, object state)
  110. {
  111. throw new NotImplementedException ();
  112. }
  113. [MonoTODO]
  114. public override IAsyncResult BeginTryReceive (TimeSpan timeout, AsyncCallback callback, object state)
  115. {
  116. throw new NotImplementedException ();
  117. }
  118. [MonoTODO]
  119. public override IAsyncResult BeginWaitForMessage (TimeSpan timeout, AsyncCallback callback, object state)
  120. {
  121. throw new NotImplementedException ();
  122. }
  123. [MonoTODO]
  124. public override Message EndReceive (IAsyncResult result)
  125. {
  126. throw new NotImplementedException ();
  127. }
  128. [MonoTODO]
  129. public override bool EndTryReceive (IAsyncResult result, out Message message)
  130. {
  131. throw new NotImplementedException ();
  132. }
  133. [MonoTODO]
  134. public override bool EndWaitForMessage (IAsyncResult result)
  135. {
  136. throw new NotImplementedException ();
  137. }
  138. public override Message Receive ()
  139. {
  140. return Receive (DefaultReceiveTimeout);
  141. }
  142. public override Message Receive (TimeSpan timeout)
  143. {
  144. client.ReceiveTimeout = (int) timeout.TotalMilliseconds;
  145. Stream s = client.GetStream ();
  146. return frame.ReadSizedMessage ();
  147. }
  148. public override bool TryReceive (TimeSpan timeout, out Message message)
  149. {
  150. try {
  151. message = Receive (timeout);
  152. return true;
  153. } catch (TimeoutException) {
  154. message = null;
  155. return false;
  156. }
  157. }
  158. public override bool WaitForMessage (TimeSpan timeout)
  159. {
  160. // FIXME: use timeout
  161. try {
  162. client = tcp_listener.AcceptTcpClient ();
  163. Stream s = client.GetStream ();
  164. frame = new TcpBinaryFrameManager (TcpBinaryFrameManager.DuplexMode, s) { Encoder = this.Encoder };
  165. frame.ProcessPreambleRecipient ();
  166. // FIXME: use retrieved record properties in the request processing.
  167. return true;
  168. } catch (TimeoutException) {
  169. return false;
  170. }
  171. }
  172. // CommunicationObject
  173. [MonoTODO]
  174. protected override void OnAbort ()
  175. {
  176. throw new NotImplementedException ();
  177. }
  178. [MonoTODO]
  179. protected override IAsyncResult OnBeginClose (TimeSpan timeout,
  180. AsyncCallback callback, object state)
  181. {
  182. throw new NotImplementedException ();
  183. }
  184. [MonoTODO]
  185. protected override IAsyncResult OnBeginOpen (TimeSpan timeout,
  186. AsyncCallback callback, object state)
  187. {
  188. throw new NotImplementedException ();
  189. }
  190. [MonoTODO]
  191. protected override void OnClose (TimeSpan timeout)
  192. {
  193. client.Close ();
  194. }
  195. [MonoTODO]
  196. protected override void OnEndClose (IAsyncResult result)
  197. {
  198. throw new NotImplementedException ();
  199. }
  200. [MonoTODO]
  201. protected override void OnEndOpen (IAsyncResult result)
  202. {
  203. throw new NotImplementedException ();
  204. }
  205. [MonoTODO]
  206. protected override void OnOpen (TimeSpan timeout)
  207. {
  208. if (! is_service_side) {
  209. int explicitPort = RemoteAddress.Uri.Port;
  210. client = new TcpClient (RemoteAddress.Uri.Host, explicitPort <= 0 ? TcpTransportBindingElement.DefaultPort : explicitPort);
  211. //RemoteAddress.Uri.Port);
  212. NetworkStream ns = client.GetStream ();
  213. frame = new TcpBinaryFrameManager (TcpBinaryFrameManager.DuplexMode, ns) {
  214. Encoder = this.Encoder,
  215. Via = RemoteAddress.Uri };
  216. frame.ProcessPreambleInitiator ();
  217. } else {
  218. // server side
  219. }
  220. }
  221. class MyBinaryWriter : BinaryWriter
  222. {
  223. public MyBinaryWriter (Stream s)
  224. : base (s)
  225. {
  226. }
  227. public void WriteBytes (byte [] bytes)
  228. {
  229. Write7BitEncodedInt (bytes.Length);
  230. Write (bytes);
  231. }
  232. }
  233. }
  234. // seealso: [MC-NMF] Windows Protocol document.
  235. class TcpBinaryFrameManager
  236. {
  237. class MyBinaryReader : BinaryReader
  238. {
  239. public MyBinaryReader (Stream s)
  240. : base (s)
  241. {
  242. }
  243. public int ReadVariableInt ()
  244. {
  245. return Read7BitEncodedInt ();
  246. }
  247. }
  248. class MyBinaryWriter : BinaryWriter
  249. {
  250. public MyBinaryWriter (Stream s)
  251. : base (s)
  252. {
  253. }
  254. public void WriteVariableInt (int value)
  255. {
  256. Write7BitEncodedInt (value);
  257. }
  258. }
  259. class MyXmlBinaryWriterSession : XmlBinaryWriterSession
  260. {
  261. public override bool TryAdd (XmlDictionaryString value, out int key)
  262. {
  263. if (!base.TryAdd (value, out key))
  264. return false;
  265. List.Add (value);
  266. return true;
  267. }
  268. public List<XmlDictionaryString> List = new List<XmlDictionaryString> ();
  269. }
  270. public const byte VersionRecord = 0;
  271. public const byte ModeRecord = 1;
  272. public const byte ViaRecord = 2;
  273. public const byte KnownEncodingRecord = 3;
  274. public const byte ExtendingEncodingRecord = 4;
  275. public const byte UnsizedEnvelopeRecord = 5;
  276. public const byte SizedEnvelopeRecord = 6;
  277. public const byte EndRecord = 7;
  278. public const byte FaultRecord = 8;
  279. public const byte UpgradeRequestRecord = 9;
  280. public const byte UpgradeResponseRecord = 0xA;
  281. public const byte PreambleAckRecord = 0xB;
  282. public const byte PreambleEndRecord = 0xC;
  283. public const byte SingletonUnsizedMode = 1;
  284. public const byte DuplexMode = 2;
  285. public const byte SimplexMode = 3;
  286. public const byte SingletonSizedMode = 4;
  287. MyBinaryReader reader;
  288. MyBinaryWriter writer;
  289. public TcpBinaryFrameManager (int mode, Stream s)
  290. {
  291. this.mode = mode;
  292. this.s = s;
  293. reader = new MyBinaryReader (s);
  294. writer = new MyBinaryWriter (s);
  295. EncodingRecord = 8; // FIXME: it should depend on mode.
  296. }
  297. Stream s;
  298. int mode;
  299. public byte EncodingRecord { get; set; }
  300. public Uri Via { get; set; }
  301. public MessageEncoder Encoder { get; set; }
  302. public byte [] ReadSizedChunk ()
  303. {
  304. int length = reader.ReadVariableInt ();
  305. if (length > 65536)
  306. throw new InvalidOperationException ("The message is too large.");
  307. byte [] buffer = new byte [length];
  308. reader.Read (buffer, 0, length);
  309. return buffer;
  310. }
  311. public void WriteSizedChunk (byte [] data)
  312. {
  313. writer.WriteVariableInt (data.Length);
  314. writer.Write (data, 0, data.Length);
  315. }
  316. public void ProcessPreambleInitiator ()
  317. {
  318. s.WriteByte (VersionRecord);
  319. s.WriteByte (1);
  320. s.WriteByte (0);
  321. s.WriteByte (ModeRecord);
  322. s.WriteByte ((byte) mode);
  323. s.WriteByte (ViaRecord);
  324. writer.Write (Via.ToString ());
  325. s.WriteByte (KnownEncodingRecord); // FIXME
  326. s.WriteByte ((byte) EncodingRecord);
  327. s.WriteByte (PreambleEndRecord);
  328. s.Flush ();
  329. int b = s.ReadByte ();
  330. switch (b) {
  331. case PreambleAckRecord:
  332. return; // success
  333. case FaultRecord:
  334. throw new FaultException (reader.ReadString ());
  335. default:
  336. throw new ProtocolException (String.Format ("Preamble Ack Record is expected, got {0:X}", b));
  337. }
  338. }
  339. public void ProcessPreambleRecipient ()
  340. {
  341. bool preambleEnd = false;
  342. while (!preambleEnd) {
  343. int b = s.ReadByte ();
  344. switch (b) {
  345. case VersionRecord:
  346. if (s.ReadByte () != 1)
  347. throw new ProtocolException ("Major version must be 1");
  348. if (s.ReadByte () != 0)
  349. throw new ProtocolException ("Minor version must be 0");
  350. break;
  351. case ModeRecord:
  352. if (s.ReadByte () != mode)
  353. throw new ProtocolException (String.Format ("Duplex mode is expected to be {0:X}", mode));
  354. break;
  355. case ViaRecord:
  356. Via = new Uri (reader.ReadString ());
  357. break;
  358. case KnownEncodingRecord:
  359. EncodingRecord = (byte) s.ReadByte ();
  360. break;
  361. case ExtendingEncodingRecord:
  362. throw new NotImplementedException ();
  363. case UpgradeRequestRecord:
  364. throw new NotImplementedException ();
  365. case UpgradeResponseRecord:
  366. throw new NotImplementedException ();
  367. case PreambleEndRecord:
  368. preambleEnd = true;
  369. break;
  370. default:
  371. throw new ProtocolException (String.Format ("Unexpected record type {0:X2}", b));
  372. }
  373. }
  374. s.WriteByte (PreambleAckRecord);
  375. }
  376. public Message ReadSizedMessage ()
  377. {
  378. // FIXME: implement [MC-NMF] correctly. Currently it is a guessed protocol hack.
  379. var packetType = s.ReadByte ();
  380. if (packetType != SizedEnvelopeRecord)
  381. throw new NotImplementedException (String.Format ("Packet type {0:X} is not implemented", packetType));
  382. byte [] buffer = ReadSizedChunk ();
  383. var ms = new MemoryStream (buffer, 0, buffer.Length);
  384. // FIXME: turned out that it could be either in-band dictionary ([MC-NBFSE]), or a mere xml body ([MC-NBFS]).
  385. if (EncodingRecord != 8)
  386. throw new NotImplementedException (String.Format ("Message encoding {0:X} is not implemented yet", EncodingRecord));
  387. // Encoding type 8:
  388. // the returned buffer consists of a serialized reader
  389. // session and the binary xml body.
  390. var session = new XmlBinaryReaderSession ();
  391. byte [] rsbuf = new TcpBinaryFrameManager (0, ms).ReadSizedChunk ();
  392. int count = 0;
  393. using (var rms = new MemoryStream (rsbuf, 0, rsbuf.Length)) {
  394. var rbr = new BinaryReader (rms, Encoding.UTF8);
  395. while (rms.Position < rms.Length)
  396. session.Add (count++, rbr.ReadString ());
  397. }
  398. var benc = Encoder as BinaryMessageEncoder;
  399. if (benc != null)
  400. benc.CurrentReaderSession = session;
  401. // FIXME: supply maxSizeOfHeaders.
  402. Message msg = Encoder.ReadMessage (ms, 0x10000);
  403. if (benc != null)
  404. benc.CurrentReaderSession = null;
  405. s.Flush ();
  406. return msg;
  407. }
  408. public void WriteSizedMessage (Message message)
  409. {
  410. // FIXME: implement full [MC-NMF] protocol.
  411. if (EncodingRecord != 8)
  412. throw new NotImplementedException (String.Format ("Message encoding {0:X} is not implemented yet", EncodingRecord));
  413. s.WriteByte (SizedEnvelopeRecord);
  414. MemoryStream ms = new MemoryStream ();
  415. var session = new MyXmlBinaryWriterSession ();
  416. var benc = Encoder as BinaryMessageEncoder;
  417. try {
  418. if (benc != null)
  419. benc.CurrentWriterSession = session;
  420. Encoder.WriteMessage (message, ms);
  421. } finally {
  422. benc.CurrentWriterSession = null;
  423. }
  424. // dictionary
  425. MemoryStream msd = new MemoryStream ();
  426. BinaryWriter dw = new BinaryWriter (msd);
  427. foreach (var ds in session.List)
  428. dw.Write (ds.Value);
  429. dw.Flush ();
  430. writer.WriteVariableInt ((int) (msd.Position + ms.Position));
  431. WriteSizedChunk (msd.ToArray ());
  432. // message body
  433. var arr = ms.GetBuffer ();
  434. writer.Write (arr, 0, (int) ms.Position);
  435. writer.Write (EndRecord);
  436. writer.Flush ();
  437. }
  438. public void ProcessEndRecordRecipient ()
  439. {
  440. int b;
  441. if ((b = s.ReadByte ()) != EndRecord)
  442. throw new ProtocolException (String.Format ("EndRequest message was expected, got {0:X}", b));
  443. }
  444. }
  445. }