TcpDuplexSessionChannel.cs 15 KB

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