Channel.cs 33 KB

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