TcpDuplexSessionChannel.cs 16 KB

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