Channel.cs 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930
  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<ChannelDataEventArgs> 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. SendMessage(new ChannelDataMessage(RemoteChannelNumber, data));
  264. }
  265. /// <summary>
  266. /// Closes the channel.
  267. /// </summary>
  268. public void Close()
  269. {
  270. Close(true);
  271. }
  272. #region Channel virtual methods
  273. /// <summary>
  274. /// Called when channel window need to be adjust.
  275. /// </summary>
  276. /// <param name="bytesToAdd">The bytes to add.</param>
  277. protected virtual void OnWindowAdjust(uint bytesToAdd)
  278. {
  279. lock (_serverWindowSizeLock)
  280. {
  281. RemoteWindowSize += bytesToAdd;
  282. }
  283. _channelServerWindowAdjustWaitHandle.Set();
  284. }
  285. /// <summary>
  286. /// Called when channel data is received.
  287. /// </summary>
  288. /// <param name="data">The data.</param>
  289. protected virtual void OnData(byte[] data)
  290. {
  291. AdjustDataWindow(data);
  292. var dataReceived = DataReceived;
  293. if (dataReceived != null)
  294. dataReceived(this, new ChannelDataEventArgs(LocalChannelNumber, data));
  295. }
  296. /// <summary>
  297. /// Called when channel extended data is received.
  298. /// </summary>
  299. /// <param name="data">The data.</param>
  300. /// <param name="dataTypeCode">The data type code.</param>
  301. protected virtual void OnExtendedData(byte[] data, uint dataTypeCode)
  302. {
  303. AdjustDataWindow(data);
  304. var extendedDataReceived = ExtendedDataReceived;
  305. if (extendedDataReceived != null)
  306. extendedDataReceived(this, new ChannelDataEventArgs(LocalChannelNumber, data, dataTypeCode));
  307. }
  308. /// <summary>
  309. /// Called when channel has no more data to receive.
  310. /// </summary>
  311. protected virtual void OnEof()
  312. {
  313. _eofMessageReceived = true;
  314. var endOfData = EndOfData;
  315. if (endOfData != null)
  316. endOfData(this, new ChannelEventArgs(LocalChannelNumber));
  317. }
  318. /// <summary>
  319. /// Called when channel is closed by the server.
  320. /// </summary>
  321. protected virtual void OnClose()
  322. {
  323. _closeMessageReceived = true;
  324. // close the channel
  325. Close(false);
  326. var closed = Closed;
  327. if (closed != null)
  328. closed(this, new ChannelEventArgs(LocalChannelNumber));
  329. }
  330. /// <summary>
  331. /// Called when channel request received.
  332. /// </summary>
  333. /// <param name="info">Channel request information.</param>
  334. protected virtual void OnRequest(RequestInfo info)
  335. {
  336. var requestReceived = RequestReceived;
  337. if (requestReceived != null)
  338. requestReceived(this, new ChannelRequestEventArgs(info));
  339. }
  340. /// <summary>
  341. /// Called when channel request was successful
  342. /// </summary>
  343. protected virtual void OnSuccess()
  344. {
  345. var requestSuccessed = RequestSucceeded;
  346. if (requestSuccessed != null)
  347. requestSuccessed(this, new ChannelEventArgs(LocalChannelNumber));
  348. }
  349. /// <summary>
  350. /// Called when channel request failed.
  351. /// </summary>
  352. protected virtual void OnFailure()
  353. {
  354. var requestFailed = RequestFailed;
  355. if (requestFailed != null)
  356. requestFailed(this, new ChannelEventArgs(LocalChannelNumber));
  357. }
  358. #endregion
  359. /// <summary>
  360. /// Raises <see cref="Channel.Exception"/> event.
  361. /// </summary>
  362. /// <param name="exception">The exception.</param>
  363. protected void RaiseExceptionEvent(Exception exception)
  364. {
  365. var handlers = Exception;
  366. if (handlers != null)
  367. {
  368. handlers(this, new ExceptionEventArgs(exception));
  369. }
  370. }
  371. /// <summary>
  372. /// Sends a message to the server.
  373. /// </summary>
  374. /// <param name="message">The message to send.</param>
  375. /// <returns>
  376. /// <c>true</c> if the message was sent to the server; otherwise, <c>false</c>.
  377. /// </returns>
  378. /// <exception cref="InvalidOperationException">The size of the packet exceeds the maximum size defined by the protocol.</exception>
  379. /// <remarks>
  380. /// This methods returns <c>false</c> when the attempt to send the message results in a
  381. /// <see cref="SocketException"/> or a <see cref="SshException"/>.
  382. /// </remarks>
  383. private bool TrySendMessage(Message message)
  384. {
  385. return _session.TrySendMessage(message);
  386. }
  387. /// <summary>
  388. /// Sends SSH message to the server.
  389. /// </summary>
  390. /// <param name="message">The message.</param>
  391. protected void SendMessage(Message message)
  392. {
  393. // send channel messages only while channel is open
  394. if (!IsOpen)
  395. return;
  396. _session.SendMessage(message);
  397. }
  398. /// <summary>
  399. /// Sends channel data message to the servers.
  400. /// </summary>
  401. /// <param name="message">Channel data message.</param>
  402. /// <remarks>
  403. /// <para>
  404. /// When the data of the message exceeds the maximum packet size or the remote window
  405. /// size does not allow the full message to be sent, then this method will send the
  406. /// data in multiple chunks and will only wait for the remote window size to be adjusted
  407. /// when its zero.
  408. /// </para>
  409. /// <para>
  410. /// This is done to support SSH servers will a small window size that do not agressively
  411. /// increase their window size. We need to take into account that there may be SSH
  412. /// servers that only increase their window size when it has reached zero.
  413. /// </para>
  414. /// </remarks>
  415. protected void SendMessage(ChannelDataMessage message)
  416. {
  417. // send channel messages only while channel is open
  418. if (!IsOpen)
  419. return;
  420. var totalDataLength = message.Data.Length;
  421. var totalDataSent = 0;
  422. var totalBytesToSend = totalDataLength;
  423. while (totalBytesToSend > 0)
  424. {
  425. var dataThatCanBeSentInMessage = GetDataLengthThatCanBeSentInMessage(totalBytesToSend);
  426. if (dataThatCanBeSentInMessage == totalDataLength)
  427. {
  428. // we can send the message in one chunk
  429. _session.SendMessage(message);
  430. }
  431. else
  432. {
  433. // we need to send the message in multiple chunks
  434. var dataToSend = new byte[dataThatCanBeSentInMessage];
  435. Array.Copy(message.Data, totalDataSent, dataToSend, 0, dataThatCanBeSentInMessage);
  436. _session.SendMessage(new ChannelDataMessage(message.LocalChannelNumber, dataToSend));
  437. }
  438. totalDataSent += dataThatCanBeSentInMessage;
  439. totalBytesToSend -= dataThatCanBeSentInMessage;
  440. }
  441. }
  442. /// <summary>
  443. /// Sends channel extended data message to the servers.
  444. /// </summary>
  445. /// <param name="message">Channel data message.</param>
  446. /// <remarks>
  447. /// <para>
  448. /// When the data of the message exceeds the maximum packet size or the remote window
  449. /// size does not allow the full message to be sent, then this method will send the
  450. /// data in multiple chunks and will only wait for the remote window size to be adjusted
  451. /// when its zero.
  452. /// </para>
  453. /// <para>
  454. /// This is done to support SSH servers will a small window size that do not agressively
  455. /// increase their window size. We need to take into account that there may be SSH
  456. /// servers that only increase their window size when it has reached zero.
  457. /// </para>
  458. /// </remarks>
  459. protected void SendMessage(ChannelExtendedDataMessage message)
  460. {
  461. // send channel messages only while channel is open
  462. if (!IsOpen)
  463. return;
  464. var totalDataLength = message.Data.Length;
  465. var totalDataSent = 0;
  466. var totalBytesToSend = totalDataLength;
  467. while (totalBytesToSend > 0)
  468. {
  469. var dataThatCanBeSentInMessage = GetDataLengthThatCanBeSentInMessage(totalBytesToSend);
  470. if (dataThatCanBeSentInMessage == totalDataLength)
  471. {
  472. // we can send the message in one chunk
  473. _session.SendMessage(message);
  474. }
  475. else
  476. {
  477. // we need to send the message in multiple chunks
  478. var dataToSend = new byte[dataThatCanBeSentInMessage];
  479. Array.Copy(message.Data, totalDataSent, dataToSend, 0, dataThatCanBeSentInMessage);
  480. _session.SendMessage(new ChannelExtendedDataMessage(message.LocalChannelNumber,
  481. message.DataTypeCode, dataToSend));
  482. }
  483. totalDataSent += dataThatCanBeSentInMessage;
  484. totalBytesToSend -= dataThatCanBeSentInMessage;
  485. }
  486. }
  487. /// <summary>
  488. /// Waits for the handle to be signaled or for an error to occurs.
  489. /// </summary>
  490. /// <param name="waitHandle">The wait handle.</param>
  491. protected void WaitOnHandle(WaitHandle waitHandle)
  492. {
  493. _session.WaitOnHandle(waitHandle);
  494. }
  495. /// <summary>
  496. /// Closes the channel, optionally waiting for the SSH_MSG_CHANNEL_CLOSE message to
  497. /// be received from the server.
  498. /// </summary>
  499. /// <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>
  500. protected virtual void Close(bool wait)
  501. {
  502. // send EOF message first when channel need to be closed, and the remote party has not already sent
  503. // a SSH_MSG_CHANNEL_EOF or SSH_MSG_CHANNEL_CLOSE message
  504. //
  505. // note that we might have had a race condition here when the remote party sends a SSH_MSG_CHANNEL_CLOSE
  506. // immediately after it has sent a SSH_MSG_CHANNEL_EOF message
  507. //
  508. // in that case, we would risk sending a SSH_MSG_CHANNEL_EOF message after the remote party has
  509. // closed its end of the channel
  510. //
  511. // as a solution for this issue we only send a SSH_MSG_CHANNEL_EOF message if we haven't received a
  512. // SSH_MSG_CHANNEL_EOF or SSH_MSG_CHANNEL_CLOSE message from the remote party
  513. if (Interlocked.CompareExchange(ref _eofMessageSent, Considered, Initial) == Initial)
  514. {
  515. if (!_closeMessageReceived && !_eofMessageReceived && IsOpen && IsConnected)
  516. {
  517. if (TrySendMessage(new ChannelEofMessage(RemoteChannelNumber)))
  518. _eofMessageSent = Sent;
  519. }
  520. }
  521. // send message to close the channel on the server
  522. if (Interlocked.CompareExchange(ref _closeMessageSent, Considered, Initial) == Initial)
  523. {
  524. // ignore sending close message when client is not connected or the channel is closed
  525. if (IsOpen && IsConnected)
  526. {
  527. if (TrySendMessage(new ChannelCloseMessage(RemoteChannelNumber)))
  528. _closeMessageSent = Sent;
  529. }
  530. }
  531. // mark the channel closed
  532. IsOpen = false;
  533. // wait for channel to be closed if we actually sent a close message (either to initiate closing
  534. // the channel, or as response to a SSH_MSG_CHANNEL_CLOSE message sent by the server
  535. if (wait && _closeMessageSent == Sent)
  536. {
  537. WaitOnHandle(_channelClosedWaitHandle);
  538. }
  539. // reset indicators in case we want to reopen the channel; these are safe to reset
  540. // since the channel is marked closed by now
  541. _eofMessageSent = Initial;
  542. _eofMessageReceived = false;
  543. _closeMessageReceived = false;
  544. _closeMessageSent = Initial;
  545. }
  546. protected virtual void OnDisconnected()
  547. {
  548. }
  549. protected virtual void OnErrorOccured(Exception exp)
  550. {
  551. }
  552. private void Session_Disconnected(object sender, EventArgs e)
  553. {
  554. IsOpen = false;
  555. try
  556. {
  557. OnDisconnected();
  558. }
  559. catch (Exception ex)
  560. {
  561. OnChannelException(ex);
  562. }
  563. }
  564. /// <summary>
  565. /// Called when an <see cref="Exception"/> occurs while processing a channel message.
  566. /// </summary>
  567. /// <param name="ex">The <see cref="Exception"/>.</param>
  568. /// <remarks>
  569. /// This method will in turn invoke <see cref="OnErrorOccured(System.Exception)"/>, and
  570. /// raise the <see cref="Exception"/> event.
  571. /// </remarks>
  572. protected void OnChannelException(Exception ex)
  573. {
  574. OnErrorOccured(ex);
  575. RaiseExceptionEvent(ex);
  576. }
  577. private void Session_ErrorOccured(object sender, ExceptionEventArgs e)
  578. {
  579. try
  580. {
  581. OnErrorOccured(e.Exception);
  582. var errorOccuredWaitHandle = _errorOccuredWaitHandle;
  583. if (errorOccuredWaitHandle != null)
  584. errorOccuredWaitHandle.Set();
  585. }
  586. catch (Exception ex)
  587. {
  588. RaiseExceptionEvent(ex);
  589. }
  590. }
  591. #region Channel message event handlers
  592. private void OnChannelWindowAdjust(object sender, MessageEventArgs<ChannelWindowAdjustMessage> e)
  593. {
  594. if (e.Message.LocalChannelNumber == LocalChannelNumber)
  595. {
  596. try
  597. {
  598. OnWindowAdjust(e.Message.BytesToAdd);
  599. }
  600. catch (Exception ex)
  601. {
  602. OnChannelException(ex);
  603. }
  604. }
  605. }
  606. private void OnChannelData(object sender, MessageEventArgs<ChannelDataMessage> e)
  607. {
  608. if (e.Message.LocalChannelNumber == LocalChannelNumber)
  609. {
  610. try
  611. {
  612. OnData(e.Message.Data);
  613. }
  614. catch (Exception ex)
  615. {
  616. OnChannelException(ex);
  617. }
  618. }
  619. }
  620. private void OnChannelExtendedData(object sender, MessageEventArgs<ChannelExtendedDataMessage> e)
  621. {
  622. if (e.Message.LocalChannelNumber == LocalChannelNumber)
  623. {
  624. try
  625. {
  626. OnExtendedData(e.Message.Data, e.Message.DataTypeCode);
  627. }
  628. catch (Exception ex)
  629. {
  630. OnChannelException(ex);
  631. }
  632. }
  633. }
  634. private void OnChannelEof(object sender, MessageEventArgs<ChannelEofMessage> e)
  635. {
  636. if (e.Message.LocalChannelNumber == LocalChannelNumber)
  637. {
  638. try
  639. {
  640. OnEof();
  641. }
  642. catch (Exception ex)
  643. {
  644. OnChannelException(ex);
  645. }
  646. }
  647. }
  648. private void OnChannelClose(object sender, MessageEventArgs<ChannelCloseMessage> e)
  649. {
  650. if (e.Message.LocalChannelNumber == LocalChannelNumber)
  651. {
  652. try
  653. {
  654. OnClose();
  655. }
  656. catch (Exception ex)
  657. {
  658. OnChannelException(ex);
  659. }
  660. var channelClosedWaitHandle = _channelClosedWaitHandle;
  661. if (channelClosedWaitHandle != null)
  662. channelClosedWaitHandle.Set();
  663. }
  664. }
  665. private void OnChannelRequest(object sender, MessageEventArgs<ChannelRequestMessage> e)
  666. {
  667. if (e.Message.LocalChannelNumber == LocalChannelNumber)
  668. {
  669. try
  670. {
  671. if (_session.ConnectionInfo.ChannelRequests.ContainsKey(e.Message.RequestName))
  672. {
  673. // Get request specific class
  674. var requestInfo = _session.ConnectionInfo.ChannelRequests[e.Message.RequestName];
  675. // Load request specific data
  676. requestInfo.Load(e.Message.RequestData);
  677. // Raise request specific event
  678. OnRequest(requestInfo);
  679. }
  680. else
  681. {
  682. // TODO: we should also send a SSH_MSG_CHANNEL_FAILURE message
  683. throw new NotSupportedException(string.Format(CultureInfo.CurrentCulture, "Request '{0}' is not supported.", e.Message.RequestName));
  684. }
  685. }
  686. catch (Exception ex)
  687. {
  688. OnChannelException(ex);
  689. }
  690. }
  691. }
  692. private void OnChannelSuccess(object sender, MessageEventArgs<ChannelSuccessMessage> e)
  693. {
  694. if (e.Message.LocalChannelNumber == LocalChannelNumber)
  695. {
  696. try
  697. {
  698. OnSuccess();
  699. }
  700. catch (Exception ex)
  701. {
  702. OnChannelException(ex);
  703. }
  704. }
  705. }
  706. private void OnChannelFailure(object sender, MessageEventArgs<ChannelFailureMessage> e)
  707. {
  708. if (e.Message.LocalChannelNumber == LocalChannelNumber)
  709. {
  710. try
  711. {
  712. OnFailure();
  713. }
  714. catch (Exception ex)
  715. {
  716. OnChannelException(ex);
  717. }
  718. }
  719. }
  720. #endregion
  721. private void AdjustDataWindow(byte[] messageData)
  722. {
  723. LocalWindowSize -= (uint)messageData.Length;
  724. // Adjust window if window size is too low
  725. if (LocalWindowSize < LocalPacketSize)
  726. {
  727. SendMessage(new ChannelWindowAdjustMessage(RemoteChannelNumber, _initialWindowSize - LocalWindowSize));
  728. LocalWindowSize = _initialWindowSize;
  729. }
  730. }
  731. /// <summary>
  732. /// Determines the length of data that currently can be sent in a single message.
  733. /// </summary>
  734. /// <param name="messageLength">The length of the message that must be sent.</param>
  735. /// <returns>
  736. /// The actual data length that currently can be sent.
  737. /// </returns>
  738. private int GetDataLengthThatCanBeSentInMessage(int messageLength)
  739. {
  740. do
  741. {
  742. lock (_serverWindowSizeLock)
  743. {
  744. var serverWindowSize = RemoteWindowSize;
  745. if (serverWindowSize == 0)
  746. {
  747. // allow us to be signal when remote window size is adjusted
  748. _channelServerWindowAdjustWaitHandle.Reset();
  749. }
  750. else
  751. {
  752. var bytesThatCanBeSent = Math.Min(Math.Min(RemotePacketSize, (uint) messageLength),
  753. serverWindowSize);
  754. RemoteWindowSize -= bytesThatCanBeSent;
  755. return (int) bytesThatCanBeSent;
  756. }
  757. }
  758. // wait for remote window size to change
  759. WaitOnHandle(_channelServerWindowAdjustWaitHandle);
  760. } while (true);
  761. }
  762. private InvalidOperationException CreateRemoteChannelInfoNotAvailableException()
  763. {
  764. throw new InvalidOperationException("The channel has not been opened, or the open has not yet been confirmed.");
  765. }
  766. #region IDisposable Members
  767. private bool _isDisposed;
  768. /// <summary>
  769. /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
  770. /// </summary>
  771. public void Dispose()
  772. {
  773. Dispose(true);
  774. GC.SuppressFinalize(this);
  775. }
  776. /// <summary>
  777. /// Releases unmanaged and - optionally - managed resources
  778. /// </summary>
  779. /// <param name="disposing"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
  780. protected virtual void Dispose(bool disposing)
  781. {
  782. if (!_isDisposed)
  783. {
  784. if (disposing)
  785. {
  786. Close(false);
  787. if (_session != null)
  788. {
  789. _session.ChannelWindowAdjustReceived -= OnChannelWindowAdjust;
  790. _session.ChannelDataReceived -= OnChannelData;
  791. _session.ChannelExtendedDataReceived -= OnChannelExtendedData;
  792. _session.ChannelEofReceived -= OnChannelEof;
  793. _session.ChannelCloseReceived -= OnChannelClose;
  794. _session.ChannelRequestReceived -= OnChannelRequest;
  795. _session.ChannelSuccessReceived -= OnChannelSuccess;
  796. _session.ChannelFailureReceived -= OnChannelFailure;
  797. _session.ErrorOccured -= Session_ErrorOccured;
  798. _session.Disconnected -= Session_Disconnected;
  799. _session = null;
  800. }
  801. if (_channelClosedWaitHandle != null)
  802. {
  803. _channelClosedWaitHandle.Dispose();
  804. _channelClosedWaitHandle = null;
  805. }
  806. if (_channelServerWindowAdjustWaitHandle != null)
  807. {
  808. _channelServerWindowAdjustWaitHandle.Dispose();
  809. _channelServerWindowAdjustWaitHandle = null;
  810. }
  811. if (_errorOccuredWaitHandle != null)
  812. {
  813. _errorOccuredWaitHandle.Dispose();
  814. _errorOccuredWaitHandle = null;
  815. }
  816. }
  817. _isDisposed = true;
  818. }
  819. }
  820. /// <summary>
  821. /// Releases unmanaged resources and performs other cleanup operations before the
  822. /// <see cref="Channel"/> is reclaimed by garbage collection.
  823. /// </summary>
  824. ~Channel()
  825. {
  826. // Do not re-create Dispose clean-up code here.
  827. // Calling Dispose(false) is optimal in terms of
  828. // readability and maintainability.
  829. Dispose(false);
  830. }
  831. #endregion
  832. }
  833. }