TcpDuplexSessionChannel.cs 15 KB

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