Channel.cs 37 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997
  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. #if TUNING
  264. SendData(data, 0, data.Length);
  265. #else
  266. SendMessage(new ChannelDataMessage(RemoteChannelNumber, data));
  267. #endif
  268. }
  269. #if TUNING
  270. /// <summary>
  271. /// Sends a SSH_MSG_CHANNEL_DATA message with the specified payload.
  272. /// </summary>
  273. /// <param name="data">An array of <see cref="byte"/> containing the payload to send.</param>
  274. /// <param name="offset">The zero-based offset in <paramref name="data"/> at which to begin taking data from.</param>
  275. /// <param name="size">The number of bytes of <paramref name="data"/> to send.</param>
  276. /// <remarks>
  277. /// <para>
  278. /// When the size of the data to send exceeds the maximum packet size or the remote window
  279. /// size does not allow the full data to be sent, then this method will send the data in
  280. /// multiple chunks and will wait for the remote window size to be adjusted when it's zero.
  281. /// </para>
  282. /// <para>
  283. /// This is done to support SSH servers will a small window size that do not agressively
  284. /// increase their window size. We need to take into account that there may be SSH servers
  285. /// that only increase their window size when it has reached zero.
  286. /// </para>
  287. /// </remarks>
  288. public void SendData(byte[] data, int offset, int size)
  289. {
  290. // send channel messages only while channel is open
  291. if (!IsOpen)
  292. return;
  293. var totalBytesToSend = size;
  294. while (totalBytesToSend > 0)
  295. {
  296. var sizeOfCurrentMessage = GetDataLengthThatCanBeSentInMessage(totalBytesToSend);
  297. var channelDataMessage = new ChannelDataMessage(
  298. RemoteChannelNumber,
  299. data,
  300. offset,
  301. sizeOfCurrentMessage);
  302. _session.SendMessage(channelDataMessage);
  303. totalBytesToSend -= sizeOfCurrentMessage;
  304. offset += sizeOfCurrentMessage;
  305. }
  306. }
  307. #endif
  308. /// <summary>
  309. /// Closes the channel.
  310. /// </summary>
  311. public void Close()
  312. {
  313. Close(true);
  314. }
  315. #region Channel virtual methods
  316. /// <summary>
  317. /// Called when channel window need to be adjust.
  318. /// </summary>
  319. /// <param name="bytesToAdd">The bytes to add.</param>
  320. protected virtual void OnWindowAdjust(uint bytesToAdd)
  321. {
  322. lock (_serverWindowSizeLock)
  323. {
  324. RemoteWindowSize += bytesToAdd;
  325. }
  326. _channelServerWindowAdjustWaitHandle.Set();
  327. }
  328. /// <summary>
  329. /// Called when channel data is received.
  330. /// </summary>
  331. /// <param name="data">The data.</param>
  332. protected virtual void OnData(byte[] data)
  333. {
  334. AdjustDataWindow(data);
  335. var dataReceived = DataReceived;
  336. if (dataReceived != null)
  337. dataReceived(this, new ChannelDataEventArgs(LocalChannelNumber, data));
  338. }
  339. /// <summary>
  340. /// Called when channel extended data is received.
  341. /// </summary>
  342. /// <param name="data">The data.</param>
  343. /// <param name="dataTypeCode">The data type code.</param>
  344. protected virtual void OnExtendedData(byte[] data, uint dataTypeCode)
  345. {
  346. AdjustDataWindow(data);
  347. var extendedDataReceived = ExtendedDataReceived;
  348. if (extendedDataReceived != null)
  349. extendedDataReceived(this, new ChannelExtendedDataEventArgs(LocalChannelNumber, data, dataTypeCode));
  350. }
  351. /// <summary>
  352. /// Called when channel has no more data to receive.
  353. /// </summary>
  354. protected virtual void OnEof()
  355. {
  356. _eofMessageReceived = true;
  357. var endOfData = EndOfData;
  358. if (endOfData != null)
  359. endOfData(this, new ChannelEventArgs(LocalChannelNumber));
  360. }
  361. /// <summary>
  362. /// Called when channel is closed by the server.
  363. /// </summary>
  364. protected virtual void OnClose()
  365. {
  366. _closeMessageReceived = true;
  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. #if !TUNING
  442. /// <summary>
  443. /// Sends channel 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(ChannelDataMessage 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 ChannelDataMessage(message.LocalChannelNumber, dataToSend));
  481. }
  482. totalDataSent += dataThatCanBeSentInMessage;
  483. totalBytesToSend -= dataThatCanBeSentInMessage;
  484. }
  485. }
  486. #endif
  487. /// <summary>
  488. /// Sends a SSH_MSG_CHANNEL_EOF message to the remote server.
  489. /// </summary>
  490. /// <exception cref="InvalidOperationException">The channel is closed.</exception>
  491. public void SendEof()
  492. {
  493. if (!IsOpen)
  494. throw CreateChannelClosedException();
  495. _session.SendMessage(new ChannelEofMessage(RemoteChannelNumber));
  496. _eofMessageSent = Sent;
  497. }
  498. /// <summary>
  499. /// Sends channel extended data message to the servers.
  500. /// </summary>
  501. /// <param name="message">Channel data message.</param>
  502. /// <remarks>
  503. /// <para>
  504. /// When the data of the message exceeds the maximum packet size or the remote window
  505. /// size does not allow the full message to be sent, then this method will send the
  506. /// data in multiple chunks and will only wait for the remote window size to be adjusted
  507. /// when its zero.
  508. /// </para>
  509. /// <para>
  510. /// This is done to support SSH servers will a small window size that do not agressively
  511. /// increase their window size. We need to take into account that there may be SSH
  512. /// servers that only increase their window size when it has reached zero.
  513. /// </para>
  514. /// </remarks>
  515. protected void SendMessage(ChannelExtendedDataMessage message)
  516. {
  517. // send channel messages only while channel is open
  518. if (!IsOpen)
  519. return;
  520. var totalDataLength = message.Data.Length;
  521. var totalDataSent = 0;
  522. var totalBytesToSend = totalDataLength;
  523. while (totalBytesToSend > 0)
  524. {
  525. var dataThatCanBeSentInMessage = GetDataLengthThatCanBeSentInMessage(totalBytesToSend);
  526. if (dataThatCanBeSentInMessage == totalDataLength)
  527. {
  528. // we can send the message in one chunk
  529. _session.SendMessage(message);
  530. }
  531. else
  532. {
  533. // we need to send the message in multiple chunks
  534. var dataToSend = new byte[dataThatCanBeSentInMessage];
  535. Array.Copy(message.Data, totalDataSent, dataToSend, 0, dataThatCanBeSentInMessage);
  536. _session.SendMessage(new ChannelExtendedDataMessage(message.LocalChannelNumber,
  537. message.DataTypeCode, dataToSend));
  538. }
  539. totalDataSent += dataThatCanBeSentInMessage;
  540. totalBytesToSend -= dataThatCanBeSentInMessage;
  541. }
  542. }
  543. /// <summary>
  544. /// Waits for the handle to be signaled or for an error to occurs.
  545. /// </summary>
  546. /// <param name="waitHandle">The wait handle.</param>
  547. protected void WaitOnHandle(WaitHandle waitHandle)
  548. {
  549. _session.WaitOnHandle(waitHandle);
  550. }
  551. /// <summary>
  552. /// Closes the channel, optionally waiting for the SSH_MSG_CHANNEL_CLOSE message to
  553. /// be received from the server.
  554. /// </summary>
  555. /// <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>
  556. protected virtual void Close(bool wait)
  557. {
  558. // send EOF message first when channel need to be closed, and the remote party has not already sent
  559. // a SSH_MSG_CHANNEL_EOF or SSH_MSG_CHANNEL_CLOSE message
  560. //
  561. // note that we might have had a race condition here when the remote party sends a SSH_MSG_CHANNEL_CLOSE
  562. // immediately after it has sent a SSH_MSG_CHANNEL_EOF message
  563. //
  564. // in that case, we would risk sending a SSH_MSG_CHANNEL_EOF message after the remote party has
  565. // closed its end of the channel
  566. //
  567. // as a solution for this issue we only send a SSH_MSG_CHANNEL_EOF message if we haven't received a
  568. // SSH_MSG_CHANNEL_EOF or SSH_MSG_CHANNEL_CLOSE message from the remote party
  569. if (Interlocked.CompareExchange(ref _eofMessageSent, Considered, Initial) == Initial)
  570. {
  571. if (!_closeMessageReceived && !_eofMessageReceived && IsOpen && IsConnected)
  572. {
  573. if (TrySendMessage(new ChannelEofMessage(RemoteChannelNumber)))
  574. _eofMessageSent = Sent;
  575. }
  576. }
  577. // send message to close the channel on the server
  578. if (Interlocked.CompareExchange(ref _closeMessageSent, Considered, Initial) == Initial)
  579. {
  580. // ignore sending close message when client is not connected or the channel is closed
  581. if (IsOpen && IsConnected)
  582. {
  583. if (TrySendMessage(new ChannelCloseMessage(RemoteChannelNumber)))
  584. _closeMessageSent = Sent;
  585. }
  586. }
  587. // mark the channel closed
  588. IsOpen = false;
  589. // wait for channel to be closed if we actually sent a close message (either to initiate closing
  590. // the channel, or as response to a SSH_MSG_CHANNEL_CLOSE message sent by the server
  591. if (wait && _closeMessageSent == Sent)
  592. {
  593. WaitOnHandle(_channelClosedWaitHandle);
  594. }
  595. // reset indicators in case we want to reopen the channel; these are safe to reset
  596. // since the channel is marked closed by now
  597. _eofMessageSent = Initial;
  598. _eofMessageReceived = false;
  599. _closeMessageReceived = false;
  600. _closeMessageSent = Initial;
  601. }
  602. protected virtual void OnDisconnected()
  603. {
  604. }
  605. protected virtual void OnErrorOccured(Exception exp)
  606. {
  607. }
  608. private void Session_Disconnected(object sender, EventArgs e)
  609. {
  610. IsOpen = false;
  611. try
  612. {
  613. OnDisconnected();
  614. }
  615. catch (Exception ex)
  616. {
  617. OnChannelException(ex);
  618. }
  619. }
  620. /// <summary>
  621. /// Called when an <see cref="Exception"/> occurs while processing a channel message.
  622. /// </summary>
  623. /// <param name="ex">The <see cref="Exception"/>.</param>
  624. /// <remarks>
  625. /// This method will in turn invoke <see cref="OnErrorOccured(System.Exception)"/>, and
  626. /// raise the <see cref="Exception"/> event.
  627. /// </remarks>
  628. protected void OnChannelException(Exception ex)
  629. {
  630. OnErrorOccured(ex);
  631. RaiseExceptionEvent(ex);
  632. }
  633. private void Session_ErrorOccured(object sender, ExceptionEventArgs e)
  634. {
  635. try
  636. {
  637. OnErrorOccured(e.Exception);
  638. var errorOccuredWaitHandle = _errorOccuredWaitHandle;
  639. if (errorOccuredWaitHandle != null)
  640. errorOccuredWaitHandle.Set();
  641. }
  642. catch (Exception ex)
  643. {
  644. RaiseExceptionEvent(ex);
  645. }
  646. }
  647. #region Channel message event handlers
  648. private void OnChannelWindowAdjust(object sender, MessageEventArgs<ChannelWindowAdjustMessage> e)
  649. {
  650. if (e.Message.LocalChannelNumber == LocalChannelNumber)
  651. {
  652. try
  653. {
  654. OnWindowAdjust(e.Message.BytesToAdd);
  655. }
  656. catch (Exception ex)
  657. {
  658. OnChannelException(ex);
  659. }
  660. }
  661. }
  662. private void OnChannelData(object sender, MessageEventArgs<ChannelDataMessage> e)
  663. {
  664. if (e.Message.LocalChannelNumber == LocalChannelNumber)
  665. {
  666. try
  667. {
  668. OnData(e.Message.Data);
  669. }
  670. catch (Exception ex)
  671. {
  672. OnChannelException(ex);
  673. }
  674. }
  675. }
  676. private void OnChannelExtendedData(object sender, MessageEventArgs<ChannelExtendedDataMessage> e)
  677. {
  678. if (e.Message.LocalChannelNumber == LocalChannelNumber)
  679. {
  680. try
  681. {
  682. OnExtendedData(e.Message.Data, e.Message.DataTypeCode);
  683. }
  684. catch (Exception ex)
  685. {
  686. OnChannelException(ex);
  687. }
  688. }
  689. }
  690. private void OnChannelEof(object sender, MessageEventArgs<ChannelEofMessage> e)
  691. {
  692. if (e.Message.LocalChannelNumber == LocalChannelNumber)
  693. {
  694. try
  695. {
  696. OnEof();
  697. }
  698. catch (Exception ex)
  699. {
  700. OnChannelException(ex);
  701. }
  702. }
  703. }
  704. private void OnChannelClose(object sender, MessageEventArgs<ChannelCloseMessage> e)
  705. {
  706. if (e.Message.LocalChannelNumber == LocalChannelNumber)
  707. {
  708. try
  709. {
  710. OnClose();
  711. }
  712. catch (Exception ex)
  713. {
  714. OnChannelException(ex);
  715. }
  716. var channelClosedWaitHandle = _channelClosedWaitHandle;
  717. if (channelClosedWaitHandle != null)
  718. channelClosedWaitHandle.Set();
  719. }
  720. }
  721. private void OnChannelRequest(object sender, MessageEventArgs<ChannelRequestMessage> e)
  722. {
  723. if (e.Message.LocalChannelNumber == LocalChannelNumber)
  724. {
  725. try
  726. {
  727. if (_session.ConnectionInfo.ChannelRequests.ContainsKey(e.Message.RequestName))
  728. {
  729. // Get request specific class
  730. var requestInfo = _session.ConnectionInfo.ChannelRequests[e.Message.RequestName];
  731. // Load request specific data
  732. requestInfo.Load(e.Message.RequestData);
  733. // Raise request specific event
  734. OnRequest(requestInfo);
  735. }
  736. else
  737. {
  738. // TODO: we should also send a SSH_MSG_CHANNEL_FAILURE message
  739. throw new NotSupportedException(string.Format(CultureInfo.CurrentCulture, "Request '{0}' is not supported.", e.Message.RequestName));
  740. }
  741. }
  742. catch (Exception ex)
  743. {
  744. OnChannelException(ex);
  745. }
  746. }
  747. }
  748. private void OnChannelSuccess(object sender, MessageEventArgs<ChannelSuccessMessage> e)
  749. {
  750. if (e.Message.LocalChannelNumber == LocalChannelNumber)
  751. {
  752. try
  753. {
  754. OnSuccess();
  755. }
  756. catch (Exception ex)
  757. {
  758. OnChannelException(ex);
  759. }
  760. }
  761. }
  762. private void OnChannelFailure(object sender, MessageEventArgs<ChannelFailureMessage> e)
  763. {
  764. if (e.Message.LocalChannelNumber == LocalChannelNumber)
  765. {
  766. try
  767. {
  768. OnFailure();
  769. }
  770. catch (Exception ex)
  771. {
  772. OnChannelException(ex);
  773. }
  774. }
  775. }
  776. #endregion
  777. private void AdjustDataWindow(byte[] messageData)
  778. {
  779. LocalWindowSize -= (uint)messageData.Length;
  780. // Adjust window if window size is too low
  781. if (LocalWindowSize < LocalPacketSize)
  782. {
  783. SendMessage(new ChannelWindowAdjustMessage(RemoteChannelNumber, _initialWindowSize - LocalWindowSize));
  784. LocalWindowSize = _initialWindowSize;
  785. }
  786. }
  787. /// <summary>
  788. /// Determines the length of data that currently can be sent in a single message.
  789. /// </summary>
  790. /// <param name="messageLength">The length of the message that must be sent.</param>
  791. /// <returns>
  792. /// The actual data length that currently can be sent.
  793. /// </returns>
  794. private int GetDataLengthThatCanBeSentInMessage(int messageLength)
  795. {
  796. do
  797. {
  798. lock (_serverWindowSizeLock)
  799. {
  800. var serverWindowSize = RemoteWindowSize;
  801. if (serverWindowSize == 0)
  802. {
  803. // allow us to be signal when remote window size is adjusted
  804. _channelServerWindowAdjustWaitHandle.Reset();
  805. }
  806. else
  807. {
  808. var bytesThatCanBeSent = Math.Min(Math.Min(RemotePacketSize, (uint) messageLength),
  809. serverWindowSize);
  810. RemoteWindowSize -= bytesThatCanBeSent;
  811. return (int) bytesThatCanBeSent;
  812. }
  813. }
  814. // wait for remote window size to change
  815. WaitOnHandle(_channelServerWindowAdjustWaitHandle);
  816. } while (true);
  817. }
  818. private InvalidOperationException CreateRemoteChannelInfoNotAvailableException()
  819. {
  820. throw new InvalidOperationException("The channel has not been opened, or the open has not yet been confirmed.");
  821. }
  822. private InvalidOperationException CreateChannelClosedException()
  823. {
  824. throw new InvalidOperationException("The channel is closed.");
  825. }
  826. #region IDisposable Members
  827. private bool _isDisposed;
  828. /// <summary>
  829. /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
  830. /// </summary>
  831. public void Dispose()
  832. {
  833. Dispose(true);
  834. GC.SuppressFinalize(this);
  835. }
  836. /// <summary>
  837. /// Releases unmanaged and - optionally - managed resources
  838. /// </summary>
  839. /// <param name="disposing"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
  840. protected virtual void Dispose(bool disposing)
  841. {
  842. if (!_isDisposed)
  843. {
  844. if (disposing)
  845. {
  846. Close(false);
  847. if (_session != null)
  848. {
  849. _session.ChannelWindowAdjustReceived -= OnChannelWindowAdjust;
  850. _session.ChannelDataReceived -= OnChannelData;
  851. _session.ChannelExtendedDataReceived -= OnChannelExtendedData;
  852. _session.ChannelEofReceived -= OnChannelEof;
  853. _session.ChannelCloseReceived -= OnChannelClose;
  854. _session.ChannelRequestReceived -= OnChannelRequest;
  855. _session.ChannelSuccessReceived -= OnChannelSuccess;
  856. _session.ChannelFailureReceived -= OnChannelFailure;
  857. _session.ErrorOccured -= Session_ErrorOccured;
  858. _session.Disconnected -= Session_Disconnected;
  859. _session = null;
  860. }
  861. if (_channelClosedWaitHandle != null)
  862. {
  863. _channelClosedWaitHandle.Dispose();
  864. _channelClosedWaitHandle = null;
  865. }
  866. if (_channelServerWindowAdjustWaitHandle != null)
  867. {
  868. _channelServerWindowAdjustWaitHandle.Dispose();
  869. _channelServerWindowAdjustWaitHandle = null;
  870. }
  871. if (_errorOccuredWaitHandle != null)
  872. {
  873. _errorOccuredWaitHandle.Dispose();
  874. _errorOccuredWaitHandle = null;
  875. }
  876. }
  877. _isDisposed = true;
  878. }
  879. }
  880. /// <summary>
  881. /// Releases unmanaged resources and performs other cleanup operations before the
  882. /// <see cref="Channel"/> is reclaimed by garbage collection.
  883. /// </summary>
  884. ~Channel()
  885. {
  886. // Do not re-create Dispose clean-up code here.
  887. // Calling Dispose(false) is optimal in terms of
  888. // readability and maintainability.
  889. Dispose(false);
  890. }
  891. #endregion
  892. }
  893. }