SubsystemSession
Base class for SSH subsystem implementations.
using Microsoft.Extensions.Logging;
using Renci.SshNet.Channels;
using Renci.SshNet.Common;
using System;
using System.Globalization;
using System.Runtime.CompilerServices;
using System.Runtime.ExceptionServices;
using System.Threading;
using System.Threading.Tasks;
namespace Renci.SshNet
{
internal abstract class SubsystemSession : ISubsystemSession, IDisposable
{
private readonly struct RegisteredWait : IDisposable
{
private readonly RegisteredWaitHandle _handle;
public RegisteredWait(WaitHandle waitObject, WaitOrTimerCallback callback, object state)
{
_handle = ThreadPool.RegisterWaitForSingleObject(waitObject, callback, state, -1, true);
}
public void Dispose()
{
_handle.Unregister(null);
}
}
private const int SystemWaitHandleCount = 3;
private readonly string _subsystemName;
private readonly ILogger _logger;
private readonly ISession _session;
private IChannelSession _channel;
private Exception _exception;
private EventWaitHandle _errorOccurredWaitHandle = new ManualResetEvent(false);
private EventWaitHandle _sessionDisconnectedWaitHandle = new ManualResetEvent(false);
private EventWaitHandle _channelClosedWaitHandle = new ManualResetEvent(false);
private bool _isDisposed;
public int OperationTimeout { get; set; }
internal IChannelSession Channel {
get {
ThrowHelper.ThrowObjectDisposedIf(_isDisposed, this);
return _channel;
}
}
public bool IsOpen {
get {
if (_channel != null)
return _channel.IsOpen;
return false;
}
}
public ILoggerFactory SessionLoggerFactory => _session.SessionLoggerFactory;
public event EventHandler<ExceptionEventArgs> ErrorOccurred;
public event EventHandler<EventArgs> Disconnected;
protected SubsystemSession(ISession session, string subsystemName, int operationTimeout)
{
ThrowHelper.ThrowIfNull(session, "session");
ThrowHelper.ThrowIfNull(subsystemName, "subsystemName");
_session = session;
_subsystemName = subsystemName;
_logger = SessionLoggerFactory.CreateLogger(GetType());
OperationTimeout = operationTimeout;
}
public void Connect()
{
ThrowHelper.ThrowObjectDisposedIf(_isDisposed, this);
if (IsOpen)
throw new InvalidOperationException("The session is already connected.");
_errorOccurredWaitHandle.Reset();
_sessionDisconnectedWaitHandle.Reset();
_sessionDisconnectedWaitHandle.Reset();
_channelClosedWaitHandle.Reset();
_session.ErrorOccured += Session_ErrorOccurred;
_session.Disconnected += Session_Disconnected;
_channel = _session.CreateChannelSession();
_channel.DataReceived += Channel_DataReceived;
_channel.Exception += Channel_Exception;
_channel.Closed += Channel_Closed;
_channel.Open();
if (!_channel.SendSubsystemRequest(_subsystemName)) {
Disconnect();
throw new SshException(string.Format(CultureInfo.InvariantCulture, "Subsystem '{0}' could not be executed.", _subsystemName));
}
OnChannelOpen();
}
public void Disconnect()
{
UnsubscribeFromSessionEvents(_session);
IChannelSession channel = _channel;
if (channel != null) {
_channel = null;
channel.DataReceived -= Channel_DataReceived;
channel.Exception -= Channel_Exception;
channel.Closed -= Channel_Closed;
channel.Dispose();
}
}
public void SendData(byte[] data)
{
ThrowHelper.ThrowObjectDisposedIf(_isDisposed, this);
EnsureSessionIsOpen();
_channel.SendData(data);
}
protected abstract void OnChannelOpen();
protected abstract void OnDataReceived(ArraySegment<byte> data);
protected void RaiseError(Exception error)
{
_exception = error;
_logger.LogInformation(error, "Raised exception", Array.Empty<object>());
_errorOccurredWaitHandle?.Set();
SignalErrorOccurred(error);
}
private void Channel_DataReceived(object sender, ChannelDataEventArgs e)
{
try {
OnDataReceived(e.Data);
} catch (Exception error) {
RaiseError(error);
}
}
private void Channel_Exception(object sender, ExceptionEventArgs e)
{
RaiseError(e.Exception);
}
private void Channel_Closed(object sender, ChannelEventArgs e)
{
_channelClosedWaitHandle?.Set();
}
public void WaitOnHandle(WaitHandle waitHandle, int millisecondsTimeout)
{
int num = WaitHandle.WaitAny(new WaitHandle[4] {
_errorOccurredWaitHandle,
_sessionDisconnectedWaitHandle,
_channelClosedWaitHandle,
waitHandle
}, millisecondsTimeout);
switch (num) {
case 3:
break;
case 0:
ExceptionDispatchInfo.Capture(_exception).Throw();
break;
case 1:
throw new SshException("Connection was closed by the server.");
case 2:
throw new SshException("Channel was closed.");
case 258:
throw new SshOperationTimeoutException("Operation has timed out.");
default:
throw new NotImplementedException(string.Format(CultureInfo.InvariantCulture, "WaitAny return value '{0}' is not implemented.", num));
}
}
[AsyncStateMachine(typeof(<WaitOnHandleAsync>d__37))]
public Task WaitOnHandleAsync(WaitHandle waitHandle, int millisecondsTimeout, CancellationToken cancellationToken)
{
<WaitOnHandleAsync>d__37 stateMachine = default(<WaitOnHandleAsync>d__37);
stateMachine.<>t__builder = AsyncTaskMethodBuilder.Create();
stateMachine.<>4__this = this;
stateMachine.waitHandle = waitHandle;
stateMachine.millisecondsTimeout = millisecondsTimeout;
stateMachine.cancellationToken = cancellationToken;
stateMachine.<>1__state = -1;
stateMachine.<>t__builder.Start(ref stateMachine);
return stateMachine.<>t__builder.Task;
}
public Task<T> WaitOnHandleAsync<T>(TaskCompletionSource<T> tcs, int millisecondsTimeout, CancellationToken cancellationToken)
{
if (!tcs.Task.IsCompleted) {
if (!cancellationToken.IsCancellationRequested)
return <WaitOnHandleAsync>g__DoWaitAsync|38_0(tcs, millisecondsTimeout, cancellationToken);
return Task.FromCanceled<T>(cancellationToken);
}
return tcs.Task;
}
public int WaitAny(WaitHandle[] waitHandles, int millisecondsTimeout)
{
int num = WaitHandle.WaitAny(waitHandles, millisecondsTimeout);
switch (num) {
case 0:
ExceptionDispatchInfo.Capture(_exception).Throw();
return -1;
case 1:
throw new SshException("Connection was closed by the server.");
case 2:
throw new SshException("Channel was closed.");
case 258:
throw new SshOperationTimeoutException("Operation has timed out.");
default:
return num - 3;
}
}
public WaitHandle[] CreateWaitHandleArray(WaitHandle waitHandle1, WaitHandle waitHandle2)
{
return new WaitHandle[5] {
_errorOccurredWaitHandle,
_sessionDisconnectedWaitHandle,
_channelClosedWaitHandle,
waitHandle1,
waitHandle2
};
}
private void Session_Disconnected(object sender, EventArgs e)
{
_sessionDisconnectedWaitHandle?.Set();
SignalDisconnected();
}
private void Session_ErrorOccurred(object sender, ExceptionEventArgs e)
{
RaiseError(e.Exception);
}
private void SignalErrorOccurred(Exception error)
{
this.ErrorOccurred?.Invoke(this, new ExceptionEventArgs(error));
}
private void SignalDisconnected()
{
this.Disconnected?.Invoke(this, EventArgs.Empty);
}
private void EnsureSessionIsOpen()
{
if (!IsOpen)
throw new InvalidOperationException("The session is not open.");
}
private void UnsubscribeFromSessionEvents(ISession session)
{
session.Disconnected -= Session_Disconnected;
session.ErrorOccured -= Session_ErrorOccurred;
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposing)
{
if (!_isDisposed && disposing) {
Disconnect();
EventWaitHandle errorOccurredWaitHandle = _errorOccurredWaitHandle;
if (errorOccurredWaitHandle != null) {
_errorOccurredWaitHandle = null;
errorOccurredWaitHandle.Dispose();
}
EventWaitHandle sessionDisconnectedWaitHandle = _sessionDisconnectedWaitHandle;
if (sessionDisconnectedWaitHandle != null) {
_sessionDisconnectedWaitHandle = null;
sessionDisconnectedWaitHandle.Dispose();
}
EventWaitHandle channelClosedWaitHandle = _channelClosedWaitHandle;
if (channelClosedWaitHandle != null) {
_channelClosedWaitHandle = null;
channelClosedWaitHandle.Dispose();
}
_isDisposed = true;
}
}
}
}