Channel.cs 31 KB

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