Channel.cs 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848
  1.  using System;
  2. using System.Threading;
  3. using Renci.SshNet.Common;
  4. using Renci.SshNet.Messages;
  5. using Renci.SshNet.Messages.Connection;
  6. using System.Globalization;
  7. namespace Renci.SshNet.Channels
  8. {
  9. /// <summary>
  10. /// Represents base class for SSH channel implementations.
  11. /// </summary>
  12. internal abstract class Channel : IChannel
  13. {
  14. private EventWaitHandle _channelClosedWaitHandle = new ManualResetEvent(false);
  15. private EventWaitHandle _channelServerWindowAdjustWaitHandle = new ManualResetEvent(false);
  16. private EventWaitHandle _errorOccuredWaitHandle = new ManualResetEvent(false);
  17. private readonly object _serverWindowSizeLock = new object();
  18. private bool _closeMessageSent;
  19. private uint _initialWindowSize;
  20. private uint? _remoteWindowSize;
  21. private uint? _remoteChannelNumber;
  22. private uint? _remotePacketSize;
  23. private ISession _session;
  24. /// <summary>
  25. /// Occurs when an exception is thrown when processing channel messages.
  26. /// </summary>
  27. public event EventHandler<ExceptionEventArgs> Exception;
  28. /// <summary>
  29. /// Gets the session.
  30. /// </summary>
  31. /// <value>
  32. /// Thhe session.
  33. /// </value>
  34. protected ISession Session
  35. {
  36. get { return _session; }
  37. }
  38. /// <summary>
  39. /// Gets the type of the channel.
  40. /// </summary>
  41. /// <value>
  42. /// The type of the channel.
  43. /// </value>
  44. public abstract ChannelTypes ChannelType { get; }
  45. /// <summary>
  46. /// Gets the local channel number.
  47. /// </summary>
  48. /// <value>
  49. /// The local channel number.
  50. /// </value>
  51. public uint LocalChannelNumber { get; private set; }
  52. /// <summary>
  53. /// Gets the maximum size of a packet.
  54. /// </summary>
  55. /// <value>
  56. /// The maximum size of a packet.
  57. /// </value>
  58. public uint LocalPacketSize { get; private set; }
  59. /// <summary>
  60. /// Gets the size of the local window.
  61. /// </summary>
  62. /// <value>
  63. /// The size of the local window.
  64. /// </value>
  65. public uint LocalWindowSize { get; private set; }
  66. /// <summary>
  67. /// Gets the remote channel number.
  68. /// </summary>
  69. /// <value>
  70. /// The remote channel number.
  71. /// </value>
  72. public uint RemoteChannelNumber
  73. {
  74. get
  75. {
  76. if (!_remoteChannelNumber.HasValue)
  77. throw CreateRemoteChannelInfoNotAvailableException();
  78. return _remoteChannelNumber.Value;
  79. }
  80. private set
  81. {
  82. _remoteChannelNumber = value;
  83. }
  84. }
  85. /// <summary>
  86. /// Gets the maximum size of a data packet that we can send using the channel.
  87. /// </summary>
  88. /// <value>
  89. /// The maximum size of data that can be sent using a <see cref="ChannelDataMessage"/>
  90. /// on the current channel.
  91. /// </value>
  92. /// <exception cref="InvalidOperationException">The channel has not been opened, or the open has not yet been confirmed.</exception>
  93. public uint RemotePacketSize
  94. {
  95. get
  96. {
  97. if (!_remotePacketSize.HasValue)
  98. throw CreateRemoteChannelInfoNotAvailableException();
  99. return _remotePacketSize.Value;
  100. }
  101. private set
  102. {
  103. _remotePacketSize = value;
  104. }
  105. }
  106. /// <summary>
  107. /// Gets the window size of the remote server.
  108. /// </summary>
  109. /// <value>
  110. /// The size of the server window.
  111. /// </value>
  112. public uint RemoteWindowSize
  113. {
  114. get
  115. {
  116. if (!_remoteWindowSize.HasValue)
  117. throw CreateRemoteChannelInfoNotAvailableException();
  118. return _remoteWindowSize.Value;
  119. }
  120. private set
  121. {
  122. _remoteWindowSize = value;
  123. }
  124. }
  125. /// <summary>
  126. /// Gets a value indicating whether this channel is open.
  127. /// </summary>
  128. /// <value>
  129. /// <c>true</c> if this channel is open; otherwise, <c>false</c>.
  130. /// </value>
  131. public bool IsOpen { get; protected set; }
  132. #region Message events
  133. /// <summary>
  134. /// Occurs when <see cref="ChannelDataMessage"/> message received
  135. /// </summary>
  136. public event EventHandler<ChannelDataEventArgs> DataReceived;
  137. /// <summary>
  138. /// Occurs when <see cref="ChannelExtendedDataMessage"/> message received
  139. /// </summary>
  140. public event EventHandler<ChannelDataEventArgs> ExtendedDataReceived;
  141. /// <summary>
  142. /// Occurs when <see cref="ChannelEofMessage"/> message received
  143. /// </summary>
  144. public event EventHandler<ChannelEventArgs> EndOfData;
  145. /// <summary>
  146. /// Occurs when <see cref="ChannelCloseMessage"/> message received
  147. /// </summary>
  148. public event EventHandler<ChannelEventArgs> Closed;
  149. /// <summary>
  150. /// Occurs when <see cref="ChannelRequestMessage"/> message received
  151. /// </summary>
  152. public event EventHandler<ChannelRequestEventArgs> RequestReceived;
  153. /// <summary>
  154. /// Occurs when <see cref="ChannelSuccessMessage"/> message received
  155. /// </summary>
  156. public event EventHandler<ChannelEventArgs> RequestSucceeded;
  157. /// <summary>
  158. /// Occurs when <see cref="ChannelFailureMessage"/> message received
  159. /// </summary>
  160. public event EventHandler<ChannelEventArgs> RequestFailed;
  161. #endregion
  162. /// <summary>
  163. /// Gets a value indicating whether the session is connected.
  164. /// </summary>
  165. /// <value>
  166. /// <c>true</c> if the session is connected; otherwise, <c>false</c>.
  167. /// </value>
  168. protected bool IsConnected
  169. {
  170. get { return this._session.IsConnected; }
  171. }
  172. /// <summary>
  173. /// Gets the connection info.
  174. /// </summary>
  175. /// <value>The connection info.</value>
  176. protected IConnectionInfo ConnectionInfo
  177. {
  178. get { return this._session.ConnectionInfo; }
  179. }
  180. /// <summary>
  181. /// Gets the session semaphore to control number of session channels
  182. /// </summary>
  183. /// <value>The session semaphore.</value>
  184. protected SemaphoreLight SessionSemaphore
  185. {
  186. get { return this._session.SessionSemaphore; }
  187. }
  188. /// <summary>
  189. /// Initializes the channel.
  190. /// </summary>
  191. /// <param name="session">The session.</param>
  192. /// <param name="localWindowSize">Size of the window.</param>
  193. /// <param name="localPacketSize">Size of the packet.</param>
  194. internal virtual void Initialize(ISession session, uint localWindowSize, uint localPacketSize)
  195. {
  196. _session = session;
  197. _initialWindowSize = localWindowSize;
  198. LocalPacketSize = localPacketSize;
  199. LocalWindowSize = localWindowSize; // Initial window size
  200. LocalChannelNumber = session.NextChannelNumber;
  201. _session.ChannelWindowAdjustReceived += OnChannelWindowAdjust;
  202. _session.ChannelDataReceived += OnChannelData;
  203. _session.ChannelExtendedDataReceived += OnChannelExtendedData;
  204. _session.ChannelEofReceived += OnChannelEof;
  205. _session.ChannelCloseReceived += OnChannelClose;
  206. _session.ChannelRequestReceived += OnChannelRequest;
  207. _session.ChannelSuccessReceived += OnChannelSuccess;
  208. _session.ChannelFailureReceived += OnChannelFailure;
  209. _session.ErrorOccured += Session_ErrorOccured;
  210. _session.Disconnected += Session_Disconnected;
  211. }
  212. protected void InitializeRemoteInfo(uint remoteChannelNumber, uint remoteWindowSize, uint remotePacketSize)
  213. {
  214. RemoteChannelNumber = remoteChannelNumber;
  215. RemoteWindowSize = remoteWindowSize;
  216. RemotePacketSize = remotePacketSize;
  217. }
  218. /// <summary>
  219. /// Sends the SSH_MSG_CHANNEL_EOF message.
  220. /// </summary>
  221. public void SendEof()
  222. {
  223. // Send EOF message first when channel need to be closed
  224. this.SendMessage(new ChannelEofMessage(this.RemoteChannelNumber));
  225. }
  226. /// <summary>
  227. /// Sends a SSH_MSG_CHANNEL_DATA message with the specified payload.
  228. /// </summary>
  229. /// <param name="data">The payload to send.</param>
  230. public void SendData(byte[] data)
  231. {
  232. this.SendMessage(new ChannelDataMessage(this.RemoteChannelNumber, data));
  233. }
  234. /// <summary>
  235. /// Closes the channel.
  236. /// </summary>
  237. public void Close()
  238. {
  239. Close(true);
  240. }
  241. #region Channel virtual methods
  242. /// <summary>
  243. /// Called when channel window need to be adjust.
  244. /// </summary>
  245. /// <param name="bytesToAdd">The bytes to add.</param>
  246. protected virtual void OnWindowAdjust(uint bytesToAdd)
  247. {
  248. lock (this._serverWindowSizeLock)
  249. {
  250. this.RemoteWindowSize += bytesToAdd;
  251. }
  252. this._channelServerWindowAdjustWaitHandle.Set();
  253. }
  254. /// <summary>
  255. /// Called when channel data is received.
  256. /// </summary>
  257. /// <param name="data">The data.</param>
  258. protected virtual void OnData(byte[] data)
  259. {
  260. this.AdjustDataWindow(data);
  261. var dataReceived = DataReceived;
  262. if (dataReceived != null)
  263. dataReceived(this, new ChannelDataEventArgs(LocalChannelNumber, data));
  264. }
  265. /// <summary>
  266. /// Called when channel extended data is received.
  267. /// </summary>
  268. /// <param name="data">The data.</param>
  269. /// <param name="dataTypeCode">The data type code.</param>
  270. protected virtual void OnExtendedData(byte[] data, uint dataTypeCode)
  271. {
  272. this.AdjustDataWindow(data);
  273. var extendedDataReceived = ExtendedDataReceived;
  274. if (extendedDataReceived != null)
  275. extendedDataReceived(this, new ChannelDataEventArgs(LocalChannelNumber, data, dataTypeCode));
  276. }
  277. /// <summary>
  278. /// Called when channel has no more data to receive.
  279. /// </summary>
  280. protected virtual void OnEof()
  281. {
  282. var endOfData = EndOfData;
  283. if (endOfData != null)
  284. endOfData(this, new ChannelEventArgs(LocalChannelNumber));
  285. }
  286. /// <summary>
  287. /// Called when channel is closed by the server.
  288. /// </summary>
  289. protected virtual void OnClose()
  290. {
  291. this.Close(false);
  292. var closed = Closed;
  293. if (closed != null)
  294. closed(this, new ChannelEventArgs(LocalChannelNumber));
  295. }
  296. /// <summary>
  297. /// Called when channel request received.
  298. /// </summary>
  299. /// <param name="info">Channel request information.</param>
  300. protected virtual void OnRequest(RequestInfo info)
  301. {
  302. var requestReceived = RequestReceived;
  303. if (requestReceived != null)
  304. requestReceived(this, new ChannelRequestEventArgs(info));
  305. }
  306. /// <summary>
  307. /// Called when channel request was successful
  308. /// </summary>
  309. protected virtual void OnSuccess()
  310. {
  311. var requestSuccessed = RequestSucceeded;
  312. if (requestSuccessed != null)
  313. requestSuccessed(this, new ChannelEventArgs(LocalChannelNumber));
  314. }
  315. /// <summary>
  316. /// Called when channel request failed.
  317. /// </summary>
  318. protected virtual void OnFailure()
  319. {
  320. var requestFailed = RequestFailed;
  321. if (requestFailed != null)
  322. requestFailed(this, new ChannelEventArgs(LocalChannelNumber));
  323. }
  324. #endregion
  325. /// <summary>
  326. /// Raises <see cref="Channel.Exception"/> event.
  327. /// </summary>
  328. /// <param name="exception">The exception.</param>
  329. protected void RaiseExceptionEvent(Exception exception)
  330. {
  331. var handlers = Exception;
  332. if (handlers != null)
  333. {
  334. handlers(this, new ExceptionEventArgs(exception));
  335. }
  336. }
  337. /// <summary>
  338. /// Sends SSH message to the server.
  339. /// </summary>
  340. /// <param name="message">The message.</param>
  341. protected void SendMessage(Message message)
  342. {
  343. // send channel messages only while channel is open
  344. if (!this.IsOpen)
  345. return;
  346. this._session.SendMessage(message);
  347. }
  348. /// <summary>
  349. /// Sends close channel message to the server, and marks the channel closed.
  350. /// </summary>
  351. /// <param name="message">The message to send.</param>
  352. private void SendMessage(ChannelCloseMessage message)
  353. {
  354. this._session.SendMessage(message);
  355. }
  356. /// <summary>
  357. /// Sends channel data message to the servers.
  358. /// </summary>
  359. /// <param name="message">Channel data message.</param>
  360. /// <remarks>
  361. /// <para>
  362. /// When the data of the message exceeds the maximum packet size or the remote window
  363. /// size does not allow the full message to be sent, then this method will send the
  364. /// data in multiple chunks and will only wait for the remote window size to be adjusted
  365. /// when its zero.
  366. /// </para>
  367. /// <para>
  368. /// This is done to support SSH servers will a small window size that do not agressively
  369. /// increase their window size. We need to take into account that there may be SSH
  370. /// servers that only increase their window size when it has reached zero.
  371. /// </para>
  372. /// </remarks>
  373. protected void SendMessage(ChannelDataMessage message)
  374. {
  375. // send channel messages only while channel is open
  376. if (!this.IsOpen)
  377. return;
  378. var totalDataLength = message.Data.Length;
  379. var totalDataSent = 0;
  380. var totalBytesToSend = totalDataLength;
  381. while (totalBytesToSend > 0)
  382. {
  383. var dataThatCanBeSentInMessage = GetDataLengthThatCanBeSentInMessage(totalBytesToSend);
  384. if (dataThatCanBeSentInMessage == totalDataLength)
  385. {
  386. // we can send the message in one chunk
  387. this._session.SendMessage(message);
  388. }
  389. else
  390. {
  391. // we need to send the message in multiple chunks
  392. var dataToSend = new byte[dataThatCanBeSentInMessage];
  393. Array.Copy(message.Data, totalDataSent, dataToSend, 0, dataThatCanBeSentInMessage);
  394. this._session.SendMessage(new ChannelDataMessage(message.LocalChannelNumber, dataToSend));
  395. }
  396. totalDataSent += dataThatCanBeSentInMessage;
  397. totalBytesToSend -= dataThatCanBeSentInMessage;
  398. }
  399. }
  400. /// <summary>
  401. /// Sends channel extended data message to the servers.
  402. /// </summary>
  403. /// <param name="message">Channel data message.</param>
  404. /// <remarks>
  405. /// <para>
  406. /// When the data of the message exceeds the maximum packet size or the remote window
  407. /// size does not allow the full message to be sent, then this method will send the
  408. /// data in multiple chunks and will only wait for the remote window size to be adjusted
  409. /// when its zero.
  410. /// </para>
  411. /// <para>
  412. /// This is done to support SSH servers will a small window size that do not agressively
  413. /// increase their window size. We need to take into account that there may be SSH
  414. /// servers that only increase their window size when it has reached zero.
  415. /// </para>
  416. /// </remarks>
  417. protected void SendMessage(ChannelExtendedDataMessage message)
  418. {
  419. // send channel messages only while channel is open
  420. if (!this.IsOpen)
  421. return;
  422. var totalDataLength = message.Data.Length;
  423. var totalDataSent = 0;
  424. var totalBytesToSend = totalDataLength;
  425. while (totalBytesToSend > 0)
  426. {
  427. var dataThatCanBeSentInMessage = GetDataLengthThatCanBeSentInMessage(totalBytesToSend);
  428. if (dataThatCanBeSentInMessage == totalDataLength)
  429. {
  430. // we can send the message in one chunk
  431. this._session.SendMessage(message);
  432. }
  433. else
  434. {
  435. // we need to send the message in multiple chunks
  436. var dataToSend = new byte[dataThatCanBeSentInMessage];
  437. Array.Copy(message.Data, totalDataSent, dataToSend, 0, dataThatCanBeSentInMessage);
  438. this._session.SendMessage(new ChannelExtendedDataMessage(message.LocalChannelNumber,
  439. message.DataTypeCode, dataToSend));
  440. }
  441. totalDataSent += dataThatCanBeSentInMessage;
  442. totalBytesToSend -= dataThatCanBeSentInMessage;
  443. }
  444. }
  445. /// <summary>
  446. /// Waits for the handle to be signaled or for an error to occurs.
  447. /// </summary>
  448. /// <param name="waitHandle">The wait handle.</param>
  449. protected void WaitOnHandle(WaitHandle waitHandle)
  450. {
  451. this._session.WaitOnHandle(waitHandle);
  452. }
  453. /// <summary>
  454. /// Closes the channel, optionally waiting for the SSH_MSG_CHANNEL_CLOSE message to
  455. /// be received from the server.
  456. /// </summary>
  457. /// <param name="wait"><c>true</c> to wait for the SSH_MSG_CHANNEL_CLOSE message to be received from the server; otherwise, <c>false</c>.</param>
  458. protected virtual void Close(bool wait)
  459. {
  460. // send message to close the channel on the server
  461. // ignore sending close message when client not connected
  462. if (!_closeMessageSent && IsOpen && IsConnected)
  463. {
  464. lock (this)
  465. {
  466. if (!_closeMessageSent)
  467. {
  468. this.SendMessage(new ChannelCloseMessage(this.RemoteChannelNumber));
  469. this._closeMessageSent = true;
  470. }
  471. }
  472. }
  473. // mark the channel closed
  474. IsOpen = false;
  475. // wait for channel to be closed if we actually sent a close message (either to initiate closing
  476. // the channel, or as response to a SSH_MSG_CHANNEL_CLOSE message sent by the server
  477. if (wait && _closeMessageSent)
  478. {
  479. WaitOnHandle(this._channelClosedWaitHandle);
  480. }
  481. }
  482. protected virtual void OnDisconnected()
  483. {
  484. }
  485. protected virtual void OnErrorOccured(Exception exp)
  486. {
  487. }
  488. private void Session_Disconnected(object sender, EventArgs e)
  489. {
  490. IsOpen = false;
  491. try
  492. {
  493. this.OnDisconnected();
  494. }
  495. catch (Exception ex)
  496. {
  497. HandleChannelException(ex);
  498. }
  499. }
  500. private void HandleChannelException(Exception ex)
  501. {
  502. OnErrorOccured(ex);
  503. RaiseExceptionEvent(ex);
  504. }
  505. private void Session_ErrorOccured(object sender, ExceptionEventArgs e)
  506. {
  507. try
  508. {
  509. OnErrorOccured(e.Exception);
  510. var errorOccuredWaitHandle = _errorOccuredWaitHandle;
  511. if (errorOccuredWaitHandle != null)
  512. errorOccuredWaitHandle.Set();
  513. }
  514. catch (Exception ex)
  515. {
  516. RaiseExceptionEvent(ex);
  517. }
  518. }
  519. #region Channel message event handlers
  520. private void OnChannelWindowAdjust(object sender, MessageEventArgs<ChannelWindowAdjustMessage> e)
  521. {
  522. if (e.Message.LocalChannelNumber == this.LocalChannelNumber)
  523. {
  524. try
  525. {
  526. this.OnWindowAdjust(e.Message.BytesToAdd);
  527. }
  528. catch (Exception ex)
  529. {
  530. HandleChannelException(ex);
  531. }
  532. }
  533. }
  534. private void OnChannelData(object sender, MessageEventArgs<ChannelDataMessage> e)
  535. {
  536. if (e.Message.LocalChannelNumber == this.LocalChannelNumber)
  537. {
  538. try
  539. {
  540. OnData(e.Message.Data);
  541. }
  542. catch (Exception ex)
  543. {
  544. HandleChannelException(ex);
  545. }
  546. }
  547. }
  548. private void OnChannelExtendedData(object sender, MessageEventArgs<ChannelExtendedDataMessage> e)
  549. {
  550. if (e.Message.LocalChannelNumber == this.LocalChannelNumber)
  551. {
  552. try
  553. {
  554. OnExtendedData(e.Message.Data, e.Message.DataTypeCode);
  555. }
  556. catch (Exception ex)
  557. {
  558. HandleChannelException(ex);
  559. }
  560. }
  561. }
  562. private void OnChannelEof(object sender, MessageEventArgs<ChannelEofMessage> e)
  563. {
  564. if (e.Message.LocalChannelNumber == this.LocalChannelNumber)
  565. {
  566. try
  567. {
  568. OnEof();
  569. }
  570. catch (Exception ex)
  571. {
  572. HandleChannelException(ex);
  573. }
  574. }
  575. }
  576. private void OnChannelClose(object sender, MessageEventArgs<ChannelCloseMessage> e)
  577. {
  578. if (e.Message.LocalChannelNumber == this.LocalChannelNumber)
  579. {
  580. try
  581. {
  582. OnClose();
  583. }
  584. catch (Exception ex)
  585. {
  586. HandleChannelException(ex);
  587. }
  588. var channelClosedWaitHandle = _channelClosedWaitHandle;
  589. if (channelClosedWaitHandle != null)
  590. channelClosedWaitHandle.Set();
  591. }
  592. }
  593. private void OnChannelRequest(object sender, MessageEventArgs<ChannelRequestMessage> e)
  594. {
  595. if (e.Message.LocalChannelNumber == this.LocalChannelNumber)
  596. {
  597. try
  598. {
  599. if (this._session.ConnectionInfo.ChannelRequests.ContainsKey(e.Message.RequestName))
  600. {
  601. // Get request specific class
  602. var requestInfo = this._session.ConnectionInfo.ChannelRequests[e.Message.RequestName];
  603. // Load request specific data
  604. requestInfo.Load(e.Message.RequestData);
  605. // Raise request specific event
  606. this.OnRequest(requestInfo);
  607. }
  608. else
  609. {
  610. // TODO: we should also send a SSH_MSG_CHANNEL_FAILURE message
  611. throw new NotSupportedException(string.Format(CultureInfo.CurrentCulture, "Request '{0}' is not supported.", e.Message.RequestName));
  612. }
  613. }
  614. catch (Exception ex)
  615. {
  616. HandleChannelException(ex);
  617. }
  618. }
  619. }
  620. private void OnChannelSuccess(object sender, MessageEventArgs<ChannelSuccessMessage> e)
  621. {
  622. if (e.Message.LocalChannelNumber == this.LocalChannelNumber)
  623. {
  624. try
  625. {
  626. OnSuccess();
  627. }
  628. catch (Exception ex)
  629. {
  630. HandleChannelException(ex);
  631. }
  632. }
  633. }
  634. private void OnChannelFailure(object sender, MessageEventArgs<ChannelFailureMessage> e)
  635. {
  636. if (e.Message.LocalChannelNumber == this.LocalChannelNumber)
  637. {
  638. try
  639. {
  640. OnFailure();
  641. }
  642. catch (Exception ex)
  643. {
  644. HandleChannelException(ex);
  645. }
  646. }
  647. }
  648. #endregion
  649. private void AdjustDataWindow(byte[] messageData)
  650. {
  651. this.LocalWindowSize -= (uint)messageData.Length;
  652. // Adjust window if window size is too low
  653. if (this.LocalWindowSize < this.LocalPacketSize)
  654. {
  655. this.SendMessage(new ChannelWindowAdjustMessage(this.RemoteChannelNumber, this._initialWindowSize - this.LocalWindowSize));
  656. this.LocalWindowSize = this._initialWindowSize;
  657. }
  658. }
  659. /// <summary>
  660. /// Determines the length of data that currently can be sent in a single message.
  661. /// </summary>
  662. /// <param name="messageLength">The length of the message that must be sent.</param>
  663. /// <returns>
  664. /// The actual data length that currently can be sent.
  665. /// </returns>
  666. private int GetDataLengthThatCanBeSentInMessage(int messageLength)
  667. {
  668. do
  669. {
  670. lock (this._serverWindowSizeLock)
  671. {
  672. var serverWindowSize = RemoteWindowSize;
  673. if (serverWindowSize == 0)
  674. {
  675. // allow us to be signal when remote window size is adjusted
  676. this._channelServerWindowAdjustWaitHandle.Reset();
  677. }
  678. else
  679. {
  680. var bytesThatCanBeSent = Math.Min(Math.Min(RemotePacketSize, (uint) messageLength),
  681. serverWindowSize);
  682. this.RemoteWindowSize -= bytesThatCanBeSent;
  683. return (int) bytesThatCanBeSent;
  684. }
  685. }
  686. // wait for remote window size to change
  687. this.WaitOnHandle(this._channelServerWindowAdjustWaitHandle);
  688. } while (true);
  689. }
  690. private InvalidOperationException CreateRemoteChannelInfoNotAvailableException()
  691. {
  692. throw new InvalidOperationException("The channel has not been opened, or the open has not yet been confirmed.");
  693. }
  694. #region IDisposable Members
  695. private bool _isDisposed;
  696. /// <summary>
  697. /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
  698. /// </summary>
  699. public void Dispose()
  700. {
  701. this.Dispose(true);
  702. GC.SuppressFinalize(this);
  703. }
  704. /// <summary>
  705. /// Releases unmanaged and - optionally - managed resources
  706. /// </summary>
  707. /// <param name="disposing"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
  708. protected virtual void Dispose(bool disposing)
  709. {
  710. if (!this._isDisposed)
  711. {
  712. if (disposing)
  713. {
  714. this.Close(false);
  715. // Ensure that all events are detached from current instance
  716. this._session.ChannelWindowAdjustReceived -= OnChannelWindowAdjust;
  717. this._session.ChannelDataReceived -= OnChannelData;
  718. this._session.ChannelExtendedDataReceived -= OnChannelExtendedData;
  719. this._session.ChannelEofReceived -= OnChannelEof;
  720. this._session.ChannelCloseReceived -= OnChannelClose;
  721. this._session.ChannelRequestReceived -= OnChannelRequest;
  722. this._session.ChannelSuccessReceived -= OnChannelSuccess;
  723. this._session.ChannelFailureReceived -= OnChannelFailure;
  724. this._session.ErrorOccured -= Session_ErrorOccured;
  725. this._session.Disconnected -= Session_Disconnected;
  726. // Dispose managed resources.
  727. if (this._channelClosedWaitHandle != null)
  728. {
  729. this._channelClosedWaitHandle.Dispose();
  730. this._channelClosedWaitHandle = null;
  731. }
  732. if (this._channelServerWindowAdjustWaitHandle != null)
  733. {
  734. this._channelServerWindowAdjustWaitHandle.Dispose();
  735. this._channelServerWindowAdjustWaitHandle = null;
  736. }
  737. if (this._errorOccuredWaitHandle != null)
  738. {
  739. this._errorOccuredWaitHandle.Dispose();
  740. this._errorOccuredWaitHandle = null;
  741. }
  742. }
  743. this._isDisposed = true;
  744. }
  745. }
  746. /// <summary>
  747. /// Releases unmanaged resources and performs other cleanup operations before the
  748. /// <see cref="Channel"/> is reclaimed by garbage collection.
  749. /// </summary>
  750. ~Channel()
  751. {
  752. // Do not re-create Dispose clean-up code here.
  753. // Calling Dispose(false) is optimal in terms of
  754. // readability and maintainability.
  755. this.Dispose(false);
  756. }
  757. #endregion
  758. }
  759. }