TcpDuplexSessionChannel.cs 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578
  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.Threading;
  41. using System.Xml;
  42. namespace System.ServiceModel.Channels
  43. {
  44. internal class TcpDuplexSessionChannel : DuplexChannelBase, IDuplexSessionChannel
  45. {
  46. class TcpDuplexSession : DuplexSessionBase
  47. {
  48. TcpDuplexSessionChannel owner;
  49. internal TcpDuplexSession (TcpDuplexSessionChannel owner)
  50. {
  51. this.owner = owner;
  52. }
  53. public override TimeSpan DefaultCloseTimeout {
  54. get { return owner.DefaultCloseTimeout; }
  55. }
  56. public override void Close (TimeSpan timeout)
  57. {
  58. owner.DiscardSession ();
  59. }
  60. }
  61. TcpChannelInfo info;
  62. TcpClient client;
  63. bool is_service_side;
  64. EndpointAddress local_address;
  65. TcpBinaryFrameManager frame;
  66. TcpDuplexSession session; // do not use this directly. Use Session instead.
  67. public TcpDuplexSessionChannel (ChannelFactoryBase factory, TcpChannelInfo info, EndpointAddress address, Uri via)
  68. : base (factory, address, via)
  69. {
  70. is_service_side = false;
  71. this.info = info;
  72. }
  73. public TcpDuplexSessionChannel (ChannelListenerBase listener, TcpChannelInfo info, TcpClient client)
  74. : base (listener)
  75. {
  76. is_service_side = true;
  77. this.client = client;
  78. this.info = info;
  79. }
  80. public MessageEncoder Encoder {
  81. get { return info.MessageEncoder; }
  82. }
  83. public override EndpointAddress LocalAddress {
  84. get { return local_address; }
  85. }
  86. public IDuplexSession Session {
  87. get {
  88. if (session == null)
  89. session = new TcpDuplexSession (this);
  90. return session;
  91. }
  92. }
  93. void DiscardSession ()
  94. {
  95. frame.ProcessEndRecordInitiator ();
  96. session = null;
  97. }
  98. public override void Send (Message message)
  99. {
  100. Send (message, DefaultSendTimeout);
  101. }
  102. public override void Send (Message message, TimeSpan timeout)
  103. {
  104. if (timeout <= TimeSpan.Zero)
  105. throw new ArgumentException (String.Format ("Timeout value must be positive value. It was {0}", timeout));
  106. if (!is_service_side) {
  107. if (message.Headers.To == null)
  108. message.Headers.To = RemoteAddress.Uri;
  109. if (message.Headers.ReplyTo == null)
  110. message.Headers.ReplyTo = new EndpointAddress (Constants.WsaAnonymousUri);
  111. } else {
  112. if (message.Headers.RelatesTo == null)
  113. message.Headers.RelatesTo = OperationContext.Current.IncomingMessageHeaders.MessageId;
  114. }
  115. client.SendTimeout = (int) timeout.TotalMilliseconds;
  116. frame.WriteSizedMessage (message);
  117. // FIXME: should EndRecord be sent here?
  118. //if (is_service_side && client.Available > 0)
  119. // frame.ProcessEndRecordRecipient ();
  120. }
  121. public override Message Receive ()
  122. {
  123. return Receive (DefaultReceiveTimeout);
  124. }
  125. public override Message Receive (TimeSpan timeout)
  126. {
  127. if (timeout <= TimeSpan.Zero)
  128. throw new ArgumentException (String.Format ("Timeout value must be positive value. It was {0}", timeout));
  129. client.ReceiveTimeout = (int) timeout.TotalMilliseconds;
  130. return frame.ReadSizedMessage ();
  131. }
  132. public override bool TryReceive (TimeSpan timeout, out Message message)
  133. {
  134. try {
  135. DateTime start = DateTime.Now;
  136. message = Receive (timeout);
  137. if (message != null)
  138. return true;
  139. // received EndRecord, so close the session and return false instead.
  140. // (Closing channel here might not be a good idea, but right now I have no better way.)
  141. Close (timeout - (DateTime.Now - start));
  142. return false;
  143. } catch (TimeoutException) {
  144. message = null;
  145. return false;
  146. }
  147. }
  148. public override bool WaitForMessage (TimeSpan timeout)
  149. {
  150. if (client.Available > 0)
  151. return true;
  152. DateTime start = DateTime.Now;
  153. do {
  154. Thread.Sleep (50);
  155. if (client.Available > 0)
  156. return true;
  157. } while (DateTime.Now - start < timeout);
  158. return false;
  159. }
  160. // CommunicationObject
  161. [MonoTODO]
  162. protected override void OnAbort ()
  163. {
  164. Close (TimeSpan.FromTicks (1));
  165. }
  166. [MonoTODO]
  167. protected override IAsyncResult OnBeginClose (TimeSpan timeout,
  168. AsyncCallback callback, object state)
  169. {
  170. throw new NotImplementedException ();
  171. }
  172. [MonoTODO]
  173. protected override IAsyncResult OnBeginOpen (TimeSpan timeout,
  174. AsyncCallback callback, object state)
  175. {
  176. throw new NotImplementedException ();
  177. }
  178. [MonoTODO]
  179. protected override void OnClose (TimeSpan timeout)
  180. {
  181. if (!is_service_side)
  182. if (session != null)
  183. session.Close (timeout);
  184. if (client != null)
  185. client.Close ();
  186. }
  187. [MonoTODO]
  188. protected override void OnEndClose (IAsyncResult result)
  189. {
  190. throw new NotImplementedException ();
  191. }
  192. [MonoTODO]
  193. protected override void OnEndOpen (IAsyncResult result)
  194. {
  195. throw new NotImplementedException ();
  196. }
  197. [MonoTODO]
  198. protected override void OnOpen (TimeSpan timeout)
  199. {
  200. if (! is_service_side) {
  201. int explicitPort = RemoteAddress.Uri.Port;
  202. client = new TcpClient (RemoteAddress.Uri.Host, explicitPort <= 0 ? TcpTransportBindingElement.DefaultPort : explicitPort);
  203. //RemoteAddress.Uri.Port);
  204. NetworkStream ns = client.GetStream ();
  205. frame = new TcpBinaryFrameManager (TcpBinaryFrameManager.DuplexMode, ns, is_service_side) {
  206. Encoder = this.Encoder,
  207. Via = RemoteAddress.Uri };
  208. frame.ProcessPreambleInitiator ();
  209. frame.ProcessPreambleAckInitiator ();
  210. } else {
  211. // server side
  212. Stream s = client.GetStream ();
  213. frame = new TcpBinaryFrameManager (TcpBinaryFrameManager.DuplexMode, s, is_service_side) { Encoder = this.Encoder };
  214. // FIXME: use retrieved record properties in the request processing.
  215. frame.ProcessPreambleRecipient ();
  216. frame.ProcessPreambleAckRecipient ();
  217. }
  218. }
  219. class MyBinaryWriter : BinaryWriter
  220. {
  221. public MyBinaryWriter (Stream s)
  222. : base (s)
  223. {
  224. }
  225. public void WriteBytes (byte [] bytes)
  226. {
  227. Write7BitEncodedInt (bytes.Length);
  228. Write (bytes);
  229. }
  230. }
  231. }
  232. // seealso: [MC-NMF] Windows Protocol document.
  233. class TcpBinaryFrameManager
  234. {
  235. class MyBinaryReader : BinaryReader
  236. {
  237. public MyBinaryReader (Stream s)
  238. : base (s)
  239. {
  240. }
  241. public int ReadVariableInt ()
  242. {
  243. return Read7BitEncodedInt ();
  244. }
  245. }
  246. class MyBinaryWriter : BinaryWriter
  247. {
  248. public MyBinaryWriter (Stream s)
  249. : base (s)
  250. {
  251. }
  252. public void WriteVariableInt (int value)
  253. {
  254. Write7BitEncodedInt (value);
  255. }
  256. public int GetSizeOfLength (int value)
  257. {
  258. int x = 0;
  259. do {
  260. value /= 0x100;
  261. x++;
  262. } while (value != 0);
  263. return x;
  264. }
  265. }
  266. class MyXmlBinaryWriterSession : XmlBinaryWriterSession
  267. {
  268. public override bool TryAdd (XmlDictionaryString value, out int key)
  269. {
  270. if (!base.TryAdd (value, out key))
  271. return false;
  272. List.Add (value);
  273. return true;
  274. }
  275. public List<XmlDictionaryString> List = new List<XmlDictionaryString> ();
  276. }
  277. public const byte VersionRecord = 0;
  278. public const byte ModeRecord = 1;
  279. public const byte ViaRecord = 2;
  280. public const byte KnownEncodingRecord = 3;
  281. public const byte ExtendingEncodingRecord = 4;
  282. public const byte UnsizedEnvelopeRecord = 5;
  283. public const byte SizedEnvelopeRecord = 6;
  284. public const byte EndRecord = 7;
  285. public const byte FaultRecord = 8;
  286. public const byte UpgradeRequestRecord = 9;
  287. public const byte UpgradeResponseRecord = 0xA;
  288. public const byte PreambleAckRecord = 0xB;
  289. public const byte PreambleEndRecord = 0xC;
  290. public const byte SingletonUnsizedMode = 1;
  291. public const byte DuplexMode = 2;
  292. public const byte SimplexMode = 3;
  293. public const byte SingletonSizedMode = 4;
  294. MyBinaryReader reader;
  295. MyBinaryWriter writer;
  296. public TcpBinaryFrameManager (int mode, Stream s, bool isServiceSide)
  297. {
  298. this.mode = mode;
  299. this.s = s;
  300. this.is_service_side = isServiceSide;
  301. reader = new MyBinaryReader (s);
  302. ResetWriteBuffer ();
  303. EncodingRecord = 8; // FIXME: it should depend on mode.
  304. }
  305. Stream s;
  306. MemoryStream buffer;
  307. bool is_service_side;
  308. int mode;
  309. public byte EncodingRecord { get; set; }
  310. public Uri Via { get; set; }
  311. public MessageEncoder Encoder { get; set; }
  312. void ResetWriteBuffer ()
  313. {
  314. this.buffer = new MemoryStream ();
  315. writer = new MyBinaryWriter (buffer);
  316. }
  317. public byte [] ReadSizedChunk ()
  318. {
  319. int length = reader.ReadVariableInt ();
  320. if (length > 65536)
  321. throw new InvalidOperationException ("The message is too large.");
  322. byte [] buffer = new byte [length];
  323. for (int readSize = 0; readSize < length; )
  324. readSize += reader.Read (buffer, readSize, length - readSize);
  325. return buffer;
  326. }
  327. public void WriteSizedChunk (byte [] data)
  328. {
  329. writer.WriteVariableInt (data.Length);
  330. writer.Write (data, 0, data.Length);
  331. }
  332. public void ProcessPreambleInitiator ()
  333. {
  334. ResetWriteBuffer ();
  335. buffer.WriteByte (VersionRecord);
  336. buffer.WriteByte (1);
  337. buffer.WriteByte (0);
  338. buffer.WriteByte (ModeRecord);
  339. buffer.WriteByte ((byte) mode);
  340. buffer.WriteByte (ViaRecord);
  341. writer.Write (Via.ToString ());
  342. buffer.WriteByte (KnownEncodingRecord); // FIXME
  343. buffer.WriteByte ((byte) EncodingRecord);
  344. buffer.WriteByte (PreambleEndRecord);
  345. buffer.Flush ();
  346. s.Write (buffer.GetBuffer (), 0, (int) buffer.Position);
  347. s.Flush ();
  348. }
  349. public void ProcessPreambleAckInitiator ()
  350. {
  351. int b = s.ReadByte ();
  352. switch (b) {
  353. case PreambleAckRecord:
  354. return; // success
  355. case FaultRecord:
  356. throw new FaultException (reader.ReadString ());
  357. default:
  358. throw new ProtocolException (String.Format ("Preamble Ack Record is expected, got {0:X}", b));
  359. }
  360. }
  361. public void ProcessPreambleAckRecipient ()
  362. {
  363. s.WriteByte (PreambleAckRecord);
  364. }
  365. public void ProcessPreambleRecipient ()
  366. {
  367. bool preambleEnd = false;
  368. while (!preambleEnd) {
  369. int b = s.ReadByte ();
  370. switch (b) {
  371. case VersionRecord:
  372. if (s.ReadByte () != 1)
  373. throw new ProtocolException ("Major version must be 1");
  374. if (s.ReadByte () != 0)
  375. throw new ProtocolException ("Minor version must be 0");
  376. break;
  377. case ModeRecord:
  378. if (s.ReadByte () != mode)
  379. throw new ProtocolException (String.Format ("Duplex mode is expected to be {0:X}", mode));
  380. break;
  381. case ViaRecord:
  382. Via = new Uri (reader.ReadString ());
  383. break;
  384. case KnownEncodingRecord:
  385. EncodingRecord = (byte) s.ReadByte ();
  386. break;
  387. case ExtendingEncodingRecord:
  388. throw new NotImplementedException ("ExtendingEncodingRecord");
  389. case UpgradeRequestRecord:
  390. throw new NotImplementedException ("UpgradeRequetRecord");
  391. case UpgradeResponseRecord:
  392. throw new NotImplementedException ("UpgradeResponseRecord");
  393. case PreambleEndRecord:
  394. preambleEnd = true;
  395. break;
  396. default:
  397. throw new ProtocolException (String.Format ("Unexpected record type {0:X2}", b));
  398. }
  399. }
  400. }
  401. XmlBinaryReaderSession reader_session;
  402. int reader_session_items;
  403. public Message ReadSizedMessage ()
  404. {
  405. // FIXME: implement full [MC-NMF].
  406. var packetType = s.ReadByte ();
  407. if (packetType == EndRecord)
  408. return null;
  409. if (packetType != SizedEnvelopeRecord)
  410. throw new NotImplementedException (String.Format ("Packet type {0:X} is not implemented", packetType));
  411. byte [] buffer = ReadSizedChunk ();
  412. var ms = new MemoryStream (buffer, 0, buffer.Length);
  413. // FIXME: turned out that it could be either in-band dictionary ([MC-NBFSE]), or a mere xml body ([MC-NBFS]).
  414. if (EncodingRecord != 8)
  415. throw new NotImplementedException (String.Format ("Message encoding {0:X} is not implemented yet", EncodingRecord));
  416. // Encoding type 8:
  417. // the returned buffer consists of a serialized reader
  418. // session and the binary xml body.
  419. var session = reader_session ?? new XmlBinaryReaderSession ();
  420. reader_session = session;
  421. byte [] rsbuf = new TcpBinaryFrameManager (0, ms, is_service_side).ReadSizedChunk ();
  422. using (var rms = new MemoryStream (rsbuf, 0, rsbuf.Length)) {
  423. var rbr = new BinaryReader (rms, Encoding.UTF8);
  424. while (rms.Position < rms.Length)
  425. session.Add (reader_session_items++, rbr.ReadString ());
  426. }
  427. var benc = Encoder as BinaryMessageEncoder;
  428. if (benc != null)
  429. benc.CurrentReaderSession = session;
  430. // FIXME: supply maxSizeOfHeaders.
  431. Message msg = Encoder.ReadMessage (ms, 0x10000);
  432. if (benc != null)
  433. benc.CurrentReaderSession = null;
  434. // if (!is_service_side)
  435. // if (s.Read (eof_buffer, 0, 1) == 1)
  436. // if (eof_buffer [0] != EndRecord)
  437. // throw new ProtocolException (String.Format ("Expected EndRecord message, got {0:X02}", eof_buffer [0]));
  438. //
  439. return msg;
  440. }
  441. byte [] eof_buffer = new byte [1];
  442. MyXmlBinaryWriterSession writer_session;
  443. public void WriteSizedMessage (Message message)
  444. {
  445. ResetWriteBuffer ();
  446. // FIXME: implement full [MC-NMF] protocol.
  447. if (EncodingRecord != 8)
  448. throw new NotImplementedException (String.Format ("Message encoding {0:X} is not implemented yet", EncodingRecord));
  449. buffer.WriteByte (SizedEnvelopeRecord);
  450. MemoryStream ms = new MemoryStream ();
  451. var session = writer_session ?? new MyXmlBinaryWriterSession ();
  452. writer_session = session;
  453. int writer_session_count = session.List.Count;
  454. var benc = Encoder as BinaryMessageEncoder;
  455. try {
  456. if (benc != null)
  457. benc.CurrentWriterSession = session;
  458. Encoder.WriteMessage (message, ms);
  459. } finally {
  460. benc.CurrentWriterSession = null;
  461. }
  462. // dictionary
  463. MemoryStream msd = new MemoryStream ();
  464. BinaryWriter dw = new BinaryWriter (msd);
  465. for (int i = writer_session_count; i < session.List.Count; i++)
  466. dw.Write (session.List [i].Value);
  467. dw.Flush ();
  468. int length = (int) (msd.Position + ms.Position);
  469. var msda = msd.ToArray ();
  470. int sizeOfLength = writer.GetSizeOfLength (msda.Length);
  471. writer.WriteVariableInt (length + sizeOfLength); // dictionary array also involves the size of itself.
  472. WriteSizedChunk (msda);
  473. // message body
  474. var arr = ms.GetBuffer ();
  475. writer.Write (arr, 0, (int) ms.Position);
  476. writer.Flush ();
  477. s.Write (buffer.GetBuffer (), 0, (int) buffer.Position);
  478. s.Flush ();
  479. }
  480. public void ProcessEndRecordInitiator ()
  481. {
  482. s.WriteByte (EndRecord); // it is required
  483. s.Flush ();
  484. }
  485. public void ProcessEndRecordRecipient ()
  486. {
  487. int b;
  488. if ((b = s.ReadByte ()) != EndRecord)
  489. throw new ProtocolException (String.Format ("EndRecord message was expected, got {0:X}", b));
  490. }
  491. }
  492. }