TcpDuplexSessionChannel.cs 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560
  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. // FIXME: use timeout
  151. try {
  152. client = tcp_listener.AcceptTcpClient ();
  153. Stream s = client.GetStream ();
  154. frame = new TcpBinaryFrameManager (TcpBinaryFrameManager.DuplexMode, s, is_service_side) { Encoder = this.Encoder };
  155. // FIXME: use retrieved record properties in the request processing.
  156. return true;
  157. } catch (TimeoutException) {
  158. return false;
  159. }
  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. }
  208. }
  209. class MyBinaryWriter : BinaryWriter
  210. {
  211. public MyBinaryWriter (Stream s)
  212. : base (s)
  213. {
  214. }
  215. public void WriteBytes (byte [] bytes)
  216. {
  217. Write7BitEncodedInt (bytes.Length);
  218. Write (bytes);
  219. }
  220. }
  221. }
  222. // seealso: [MC-NMF] Windows Protocol document.
  223. class TcpBinaryFrameManager
  224. {
  225. class MyBinaryReader : BinaryReader
  226. {
  227. public MyBinaryReader (Stream s)
  228. : base (s)
  229. {
  230. }
  231. public int ReadVariableInt ()
  232. {
  233. return Read7BitEncodedInt ();
  234. }
  235. }
  236. class MyBinaryWriter : BinaryWriter
  237. {
  238. public MyBinaryWriter (Stream s)
  239. : base (s)
  240. {
  241. }
  242. public void WriteVariableInt (int value)
  243. {
  244. Write7BitEncodedInt (value);
  245. }
  246. public int GetSizeOfLength (int value)
  247. {
  248. int x = 0;
  249. do {
  250. value /= 0x100;
  251. x++;
  252. } while (value != 0);
  253. return x;
  254. }
  255. }
  256. class MyXmlBinaryWriterSession : XmlBinaryWriterSession
  257. {
  258. public override bool TryAdd (XmlDictionaryString value, out int key)
  259. {
  260. if (!base.TryAdd (value, out key))
  261. return false;
  262. List.Add (value);
  263. return true;
  264. }
  265. public List<XmlDictionaryString> List = new List<XmlDictionaryString> ();
  266. }
  267. public const byte VersionRecord = 0;
  268. public const byte ModeRecord = 1;
  269. public const byte ViaRecord = 2;
  270. public const byte KnownEncodingRecord = 3;
  271. public const byte ExtendingEncodingRecord = 4;
  272. public const byte UnsizedEnvelopeRecord = 5;
  273. public const byte SizedEnvelopeRecord = 6;
  274. public const byte EndRecord = 7;
  275. public const byte FaultRecord = 8;
  276. public const byte UpgradeRequestRecord = 9;
  277. public const byte UpgradeResponseRecord = 0xA;
  278. public const byte PreambleAckRecord = 0xB;
  279. public const byte PreambleEndRecord = 0xC;
  280. public const byte SingletonUnsizedMode = 1;
  281. public const byte DuplexMode = 2;
  282. public const byte SimplexMode = 3;
  283. public const byte SingletonSizedMode = 4;
  284. MyBinaryReader reader;
  285. MyBinaryWriter writer;
  286. public TcpBinaryFrameManager (int mode, Stream s, bool isServiceSide)
  287. {
  288. this.mode = mode;
  289. this.s = s;
  290. this.is_service_side = isServiceSide;
  291. reader = new MyBinaryReader (s);
  292. ResetWriteBuffer ();
  293. EncodingRecord = 8; // FIXME: it should depend on mode.
  294. }
  295. Stream s;
  296. MemoryStream buffer;
  297. bool is_service_side;
  298. int mode;
  299. public byte EncodingRecord { get; set; }
  300. public Uri Via { get; set; }
  301. public MessageEncoder Encoder { get; set; }
  302. void ResetWriteBuffer ()
  303. {
  304. this.buffer = new MemoryStream ();
  305. writer = new MyBinaryWriter (buffer);
  306. }
  307. public byte [] ReadSizedChunk ()
  308. {
  309. int length = reader.ReadVariableInt ();
  310. if (length > 65536)
  311. throw new InvalidOperationException ("The message is too large.");
  312. byte [] buffer = new byte [length];
  313. for (int readSize = 0; readSize < length; )
  314. readSize += reader.Read (buffer, readSize, length - readSize);
  315. return buffer;
  316. }
  317. public void WriteSizedChunk (byte [] data)
  318. {
  319. writer.WriteVariableInt (data.Length);
  320. writer.Write (data, 0, data.Length);
  321. }
  322. void ProcessPreambleInitiator ()
  323. {
  324. buffer.WriteByte (VersionRecord);
  325. buffer.WriteByte (1);
  326. buffer.WriteByte (0);
  327. buffer.WriteByte (ModeRecord);
  328. buffer.WriteByte ((byte) mode);
  329. buffer.WriteByte (ViaRecord);
  330. writer.Write (Via.ToString ());
  331. buffer.WriteByte (KnownEncodingRecord); // FIXME
  332. buffer.WriteByte ((byte) EncodingRecord);
  333. buffer.WriteByte (PreambleEndRecord);
  334. buffer.Flush ();
  335. }
  336. void ProcessPreambleAckInitiator ()
  337. {
  338. int b = s.ReadByte ();
  339. switch (b) {
  340. case PreambleAckRecord:
  341. return; // success
  342. case FaultRecord:
  343. throw new FaultException (reader.ReadString ());
  344. default:
  345. throw new ProtocolException (String.Format ("Preamble Ack Record is expected, got {0:X}", b));
  346. }
  347. }
  348. void ProcessPreambleAckRecipient ()
  349. {
  350. s.WriteByte (PreambleAckRecord);
  351. }
  352. void ProcessPreambleRecipient ()
  353. {
  354. bool preambleEnd = false;
  355. while (!preambleEnd) {
  356. int b = s.ReadByte ();
  357. switch (b) {
  358. case VersionRecord:
  359. if (s.ReadByte () != 1)
  360. throw new ProtocolException ("Major version must be 1");
  361. if (s.ReadByte () != 0)
  362. throw new ProtocolException ("Minor version must be 0");
  363. break;
  364. case ModeRecord:
  365. if (s.ReadByte () != mode)
  366. throw new ProtocolException (String.Format ("Duplex mode is expected to be {0:X}", mode));
  367. break;
  368. case ViaRecord:
  369. Via = new Uri (reader.ReadString ());
  370. break;
  371. case KnownEncodingRecord:
  372. EncodingRecord = (byte) s.ReadByte ();
  373. break;
  374. case ExtendingEncodingRecord:
  375. throw new NotImplementedException ();
  376. case UpgradeRequestRecord:
  377. throw new NotImplementedException ();
  378. case UpgradeResponseRecord:
  379. throw new NotImplementedException ();
  380. case PreambleEndRecord:
  381. preambleEnd = true;
  382. break;
  383. default:
  384. throw new ProtocolException (String.Format ("Unexpected record type {0:X2}", b));
  385. }
  386. }
  387. }
  388. public Message ReadSizedMessage ()
  389. {
  390. // FIXME: implement full [MC-NMF].
  391. if (is_service_side) {
  392. ProcessPreambleRecipient ();
  393. ProcessPreambleAckRecipient ();
  394. }
  395. var packetType = s.ReadByte ();
  396. if (packetType != SizedEnvelopeRecord)
  397. throw new NotImplementedException (String.Format ("Packet type {0:X} is not implemented", packetType));
  398. byte [] buffer = ReadSizedChunk ();
  399. var ms = new MemoryStream (buffer, 0, buffer.Length);
  400. // FIXME: turned out that it could be either in-band dictionary ([MC-NBFSE]), or a mere xml body ([MC-NBFS]).
  401. if (EncodingRecord != 8)
  402. throw new NotImplementedException (String.Format ("Message encoding {0:X} is not implemented yet", EncodingRecord));
  403. // Encoding type 8:
  404. // the returned buffer consists of a serialized reader
  405. // session and the binary xml body.
  406. var session = new XmlBinaryReaderSession ();
  407. byte [] rsbuf = new TcpBinaryFrameManager (0, ms, is_service_side).ReadSizedChunk ();
  408. int count = 0;
  409. using (var rms = new MemoryStream (rsbuf, 0, rsbuf.Length)) {
  410. var rbr = new BinaryReader (rms, Encoding.UTF8);
  411. while (rms.Position < rms.Length)
  412. session.Add (count++, rbr.ReadString ());
  413. }
  414. var benc = Encoder as BinaryMessageEncoder;
  415. if (benc != null)
  416. benc.CurrentReaderSession = session;
  417. // FIXME: supply maxSizeOfHeaders.
  418. Message msg = Encoder.ReadMessage (ms, 0x10000);
  419. if (benc != null)
  420. benc.CurrentReaderSession = null;
  421. if (s.Read (eof_buffer, 0, 1) == 1)
  422. if (eof_buffer [0] != EndRecord)
  423. throw new ProtocolException (String.Format ("Expected EndRecord message, got {0:X02}", eof_buffer [0]));
  424. return msg;
  425. }
  426. byte [] eof_buffer = new byte [1];
  427. public void WriteSizedMessage (Message message)
  428. {
  429. ResetWriteBuffer ();
  430. if (!is_service_side)
  431. ProcessPreambleInitiator ();
  432. // FIXME: implement full [MC-NMF] protocol.
  433. if (EncodingRecord != 8)
  434. throw new NotImplementedException (String.Format ("Message encoding {0:X} is not implemented yet", EncodingRecord));
  435. buffer.WriteByte (SizedEnvelopeRecord);
  436. MemoryStream ms = new MemoryStream ();
  437. var session = new MyXmlBinaryWriterSession ();
  438. var benc = Encoder as BinaryMessageEncoder;
  439. try {
  440. if (benc != null)
  441. benc.CurrentWriterSession = session;
  442. Encoder.WriteMessage (message, ms);
  443. } finally {
  444. benc.CurrentWriterSession = null;
  445. }
  446. // dictionary
  447. MemoryStream msd = new MemoryStream ();
  448. BinaryWriter dw = new BinaryWriter (msd);
  449. foreach (var ds in session.List)
  450. dw.Write (ds.Value);
  451. dw.Flush ();
  452. int length = (int) (msd.Position + ms.Position);
  453. var msda = msd.ToArray ();
  454. int sizeOfLength = writer.GetSizeOfLength (msda.Length);
  455. writer.WriteVariableInt (length + sizeOfLength); // dictionary array also involves the size of itself.
  456. WriteSizedChunk (msda);
  457. // message body
  458. var arr = ms.GetBuffer ();
  459. writer.Write (arr, 0, (int) ms.Position);
  460. writer.Flush ();
  461. s.Write (buffer.GetBuffer (), 0, (int) buffer.Position);
  462. s.Flush ();
  463. // It is processed at *this* late.
  464. if (!is_service_side)
  465. ProcessPreambleAckInitiator ();
  466. s.WriteByte (EndRecord); // it is required
  467. s.Flush ();
  468. }
  469. public void ProcessEndRecordRecipient ()
  470. {
  471. int b;
  472. if ((b = s.ReadByte ()) != EndRecord)
  473. throw new ProtocolException (String.Format ("EndRecord message was expected, got {0:X}", b));
  474. }
  475. }
  476. }