mirror of
https://github.com/PepperDash/PepperDashCore.git
synced 2026-02-16 13:14:49 +00:00
fix: moved ssh changes back into the original file
This commit is contained in:
@@ -1,5 +1,5 @@
|
|||||||
using System;
|
using System;
|
||||||
using System.Linq;
|
using System.Collections.Generic;
|
||||||
using System.Text;
|
using System.Text;
|
||||||
using Crestron.SimplSharp;
|
using Crestron.SimplSharp;
|
||||||
using Crestron.SimplSharp.CrestronSockets;
|
using Crestron.SimplSharp.CrestronSockets;
|
||||||
@@ -8,37 +8,25 @@ using Crestron.SimplSharp.Ssh.Common;
|
|||||||
|
|
||||||
namespace PepperDash.Core
|
namespace PepperDash.Core
|
||||||
{
|
{
|
||||||
/*
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
///
|
/// Generic ssh client
|
||||||
/// </summary>
|
/// </summary>
|
||||||
public class GenericSshClient : Device, ISocketStatusWithStreamDebugging, IAutoReconnect
|
public class GenericSshClient : Device, IStreamDebugging, ISocketStatus, IAutoReconnect, IDisposable
|
||||||
{
|
{
|
||||||
private const string SPlusKey = "Uninitialized SshClient";
|
private static class ConnectionProgress
|
||||||
/// <summary>
|
{
|
||||||
/// Object to enable stream debugging
|
public const int Idle = 0;
|
||||||
/// </summary>
|
public const int InProgress = 1;
|
||||||
public CommunicationStreamDebugging StreamDebugging { get; private set; }
|
}
|
||||||
|
|
||||||
/// <summary>
|
private SshClient client;
|
||||||
/// Event that fires when data is received. Delivers args with byte array
|
private ShellStream stream;
|
||||||
/// </summary>
|
private CTimer connectTimer;
|
||||||
public event EventHandler<GenericCommMethodReceiveBytesArgs> BytesReceived;
|
private CTimer disconnectTimer;
|
||||||
|
private int connectionProgress = ConnectionProgress.Idle;
|
||||||
/// <summary>
|
private KeyboardInteractiveAuthenticationMethod keyboardAuth;
|
||||||
/// Event that fires when data is received. Delivered as text.
|
private PasswordAuthenticationMethod passwordAuth;
|
||||||
/// </summary>
|
private SocketStatus socketSatus;
|
||||||
public event EventHandler<GenericCommMethodReceiveTextArgs> TextReceived;
|
|
||||||
|
|
||||||
/// <summary>
|
|
||||||
/// Event when the connection status changes.
|
|
||||||
/// </summary>
|
|
||||||
public event EventHandler<GenericSocketStatusChageEventArgs> ConnectionChange;
|
|
||||||
|
|
||||||
///// <summary>
|
|
||||||
/////
|
|
||||||
///// </summary>
|
|
||||||
//public event GenericSocketStatusChangeEventDelegate SocketStatusChange;
|
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Address of server
|
/// Address of server
|
||||||
@@ -61,100 +49,33 @@ namespace PepperDash.Core
|
|||||||
public string Password { get; set; }
|
public string Password { get; set; }
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// True when the server is connected - when status == 2.
|
/// Client socket status
|
||||||
/// </summary>
|
|
||||||
public bool IsConnected
|
|
||||||
{
|
|
||||||
// returns false if no client or not connected
|
|
||||||
get { return ClientStatus == SocketStatus.SOCKET_STATUS_CONNECTED; }
|
|
||||||
}
|
|
||||||
|
|
||||||
private bool IsConnecting = false;
|
|
||||||
|
|
||||||
/// <summary>
|
|
||||||
/// S+ helper for IsConnected
|
|
||||||
/// </summary>
|
|
||||||
public ushort UIsConnected
|
|
||||||
{
|
|
||||||
get { return (ushort)(IsConnected ? 1 : 0); }
|
|
||||||
}
|
|
||||||
|
|
||||||
/// <summary>
|
|
||||||
///
|
|
||||||
/// </summary>
|
/// </summary>
|
||||||
public SocketStatus ClientStatus
|
public SocketStatus ClientStatus
|
||||||
{
|
{
|
||||||
get { return _ClientStatus; }
|
get { return socketSatus; }
|
||||||
private set
|
private set
|
||||||
{
|
{
|
||||||
if (_ClientStatus == value)
|
if (socketSatus == value)
|
||||||
return;
|
return;
|
||||||
_ClientStatus = value;
|
socketSatus = value;
|
||||||
OnConnectionChange();
|
OnConnectionChange();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
SocketStatus _ClientStatus;
|
|
||||||
|
|
||||||
/// <summary>
|
|
||||||
/// Contains the familiar Simpl analog status values. This drives the ConnectionChange event
|
|
||||||
/// and IsConnected with be true when this == 2.
|
|
||||||
/// </summary>
|
|
||||||
public ushort UStatus
|
|
||||||
{
|
|
||||||
get { return (ushort)_ClientStatus; }
|
|
||||||
}
|
|
||||||
|
|
||||||
/// <summary>
|
|
||||||
/// Determines whether client will attempt reconnection on failure. Default is true
|
|
||||||
/// </summary>
|
|
||||||
public bool AutoReconnect { get; set; }
|
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Will be set and unset by connect and disconnect only
|
/// Will be set and unset by connect and disconnect only
|
||||||
/// </summary>
|
/// </summary>
|
||||||
public bool ConnectEnabled { get; private set; }
|
public bool ConnectEnabled { get; private set; }
|
||||||
|
|
||||||
/// <summary>
|
private void OnConnectionChange()
|
||||||
/// S+ helper for AutoReconnect
|
|
||||||
/// </summary>
|
|
||||||
public ushort UAutoReconnect
|
|
||||||
{
|
{
|
||||||
get { return (ushort)(AutoReconnect ? 1 : 0); }
|
var handler = ConnectionChange;
|
||||||
set { AutoReconnect = value == 1; }
|
if (handler != null)
|
||||||
|
handler(this, new GenericSocketStatusChageEventArgs(this));
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>
|
private const string SPlusKey = "Uninitialized SshClient";
|
||||||
/// Millisecond value, determines the timeout period in between reconnect attempts.
|
|
||||||
/// Set to 5000 by default
|
|
||||||
/// </summary>
|
|
||||||
public int AutoReconnectIntervalMs { get; set; }
|
|
||||||
|
|
||||||
SshClient Client;
|
|
||||||
|
|
||||||
ShellStream TheStream;
|
|
||||||
|
|
||||||
CTimer ReconnectTimer;
|
|
||||||
|
|
||||||
//string PreviousHostname;
|
|
||||||
//int PreviousPort;
|
|
||||||
//string PreviousUsername;
|
|
||||||
//string PreviousPassword;
|
|
||||||
|
|
||||||
/// <summary>
|
|
||||||
/// Typical constructor.
|
|
||||||
/// </summary>
|
|
||||||
public GenericSshClient(string key, string hostname, int port, string username, string password) :
|
|
||||||
base(key)
|
|
||||||
{
|
|
||||||
StreamDebugging = new CommunicationStreamDebugging(key);
|
|
||||||
CrestronEnvironment.ProgramStatusEventHandler += new ProgramStatusEventHandler(CrestronEnvironment_ProgramStatusEventHandler);
|
|
||||||
Key = key;
|
|
||||||
Hostname = hostname;
|
|
||||||
Port = port;
|
|
||||||
Username = username;
|
|
||||||
Password = password;
|
|
||||||
AutoReconnectIntervalMs = 5000;
|
|
||||||
}
|
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// S+ Constructor - Must set all properties before calling Connect
|
/// S+ Constructor - Must set all properties before calling Connect
|
||||||
@@ -163,8 +84,63 @@ namespace PepperDash.Core
|
|||||||
: base(SPlusKey)
|
: base(SPlusKey)
|
||||||
{
|
{
|
||||||
StreamDebugging = new CommunicationStreamDebugging(SPlusKey);
|
StreamDebugging = new CommunicationStreamDebugging(SPlusKey);
|
||||||
CrestronEnvironment.ProgramStatusEventHandler += new ProgramStatusEventHandler(CrestronEnvironment_ProgramStatusEventHandler);
|
AutoReconnectIntervalMs = 10000;
|
||||||
AutoReconnectIntervalMs = 5000;
|
|
||||||
|
connectTimer = new CTimer(_ =>
|
||||||
|
{
|
||||||
|
Debug.Console(1, this, "Attempting to reconnect");
|
||||||
|
Connect();
|
||||||
|
}, Timeout.Infinite);
|
||||||
|
|
||||||
|
disconnectTimer = new CTimer(_ =>
|
||||||
|
{
|
||||||
|
Debug.Console(1, this, "Attempting to disconnect");
|
||||||
|
Disconnect();
|
||||||
|
}, Timeout.Infinite);
|
||||||
|
|
||||||
|
CrestronEnvironment.ProgramStatusEventHandler += OnProgramShutdown;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Typical constructor.
|
||||||
|
/// </summary>
|
||||||
|
public GenericSshClient(string key, string hostname, int port, string username, string password)
|
||||||
|
: base(key)
|
||||||
|
{
|
||||||
|
Key = key;
|
||||||
|
Hostname = hostname;
|
||||||
|
Port = port;
|
||||||
|
Username = username;
|
||||||
|
Password = password;
|
||||||
|
AutoReconnectIntervalMs = 10000;
|
||||||
|
|
||||||
|
connectTimer = new CTimer(_ =>
|
||||||
|
{
|
||||||
|
Debug.Console(1, this, "Attempting to reconnect");
|
||||||
|
Connect();
|
||||||
|
}, Timeout.Infinite);
|
||||||
|
|
||||||
|
disconnectTimer = new CTimer(_ =>
|
||||||
|
{
|
||||||
|
Debug.Console(1, this, "Attempting to disconnect");
|
||||||
|
Disconnect();
|
||||||
|
}, Timeout.Infinite);
|
||||||
|
|
||||||
|
StreamDebugging = new CommunicationStreamDebugging(key);
|
||||||
|
CrestronEnvironment.ProgramStatusEventHandler += OnProgramShutdown;
|
||||||
|
}
|
||||||
|
|
||||||
|
private void OnProgramShutdown(eProgramStatusEventType type)
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
if (type == eProgramStatusEventType.Stopping)
|
||||||
|
Disconnect();
|
||||||
|
}
|
||||||
|
catch (Exception ex)
|
||||||
|
{
|
||||||
|
Debug.Console(1, this, Debug.ErrorLogLevel.Notice, "Error at shutdown:{0}", ex);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
@@ -176,18 +152,73 @@ namespace PepperDash.Core
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Handles closing this up when the program shuts down
|
/// True when the server is connected - when status == 2.
|
||||||
/// </summary>
|
/// </summary>
|
||||||
void CrestronEnvironment_ProgramStatusEventHandler(eProgramStatusEventType programEventType)
|
public bool IsConnected
|
||||||
{
|
{
|
||||||
if (programEventType == eProgramStatusEventType.Stopping)
|
get { return client != null && client.IsConnected; }
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// S+ helper for IsConnected
|
||||||
|
/// </summary>
|
||||||
|
public ushort UIsConnected
|
||||||
{
|
{
|
||||||
if (Client != null)
|
get { return (ushort)(IsConnected ? 1 : 0); }
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Event fired when bytes are received on the shell
|
||||||
|
/// </summary>
|
||||||
|
public event EventHandler<GenericCommMethodReceiveBytesArgs> BytesReceived;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Event fired when test is received on the shell
|
||||||
|
/// </summary>
|
||||||
|
public event EventHandler<GenericCommMethodReceiveTextArgs> TextReceived;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Sends text to the server
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="text"></param>
|
||||||
|
public void SendText(string text)
|
||||||
{
|
{
|
||||||
Debug.Console(1, this, "Program stopping. Closing connection");
|
if (CanSend())
|
||||||
Disconnect();
|
{
|
||||||
|
if (StreamDebugging.TxStreamDebuggingIsEnabled)
|
||||||
|
Debug.Console(0, this, "Sending {0} characters of text: '{1}'", text.Length, ComTextHelper.GetDebugText(text.Trim()));
|
||||||
|
|
||||||
|
stream.WriteLine(text);
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
Debug.Console(1, this, "SendText() called but not connected");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Sends bytes to the server
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="bytes"></param>
|
||||||
|
public void SendBytes(byte[] bytes)
|
||||||
|
{
|
||||||
|
if (CanSend())
|
||||||
|
{
|
||||||
|
if (StreamDebugging.TxStreamDebuggingIsEnabled)
|
||||||
|
Debug.Console(0, this, "Sending {0} bytes: '{1}'", bytes.Length, ComTextHelper.GetEscapedText(bytes));
|
||||||
|
|
||||||
|
stream.Write(bytes, 0, bytes.Length);
|
||||||
|
stream.Flush();
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
Debug.Console(1, this, "SendText() called but not connected");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private bool CanSend()
|
||||||
|
{
|
||||||
|
return client != null && stream != null && client.IsConnected;
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
@@ -195,75 +226,106 @@ namespace PepperDash.Core
|
|||||||
/// </summary>
|
/// </summary>
|
||||||
public void Connect()
|
public void Connect()
|
||||||
{
|
{
|
||||||
if (IsConnecting)
|
|
||||||
{
|
|
||||||
Debug.Console(0, this, Debug.ErrorLogLevel.Warning, "Connection attempt in progress. Exiting Connect()");
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
IsConnecting = true;
|
|
||||||
ConnectEnabled = true;
|
ConnectEnabled = true;
|
||||||
Debug.Console(1, this, "attempting connect");
|
DisposeOfTimer(disconnectTimer);
|
||||||
|
|
||||||
// Cancel reconnect if running.
|
if (
|
||||||
if (ReconnectTimer != null)
|
Interlocked.CompareExchange(ref connectionProgress, ConnectionProgress.InProgress,
|
||||||
|
ConnectionProgress.Idle) == ConnectionProgress.Idle)
|
||||||
{
|
{
|
||||||
ReconnectTimer.Stop();
|
if (client != null && client.IsConnected)
|
||||||
ReconnectTimer = null;
|
|
||||||
}
|
|
||||||
|
|
||||||
// Don't try to connect if already
|
|
||||||
if (IsConnected)
|
|
||||||
return;
|
|
||||||
|
|
||||||
// Don't go unless everything is here
|
|
||||||
if (string.IsNullOrEmpty(Hostname) || Port < 1 || Port > 65535
|
|
||||||
|| Username == null || Password == null)
|
|
||||||
{
|
{
|
||||||
Debug.Console(1, this, Debug.ErrorLogLevel.Error, "Connect failed. Check hostname, port, username and password are set or not null");
|
Debug.Console(1, this, "Ignoring connection request... already connected");
|
||||||
|
Interlocked.Exchange(ref connectionProgress, ConnectionProgress.Idle);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Cleanup the old client if it already exists
|
CrestronInvoke.BeginInvoke(_ =>
|
||||||
if (Client != null)
|
|
||||||
{
|
{
|
||||||
Debug.Console(1, this, "Cleaning up disconnected client");
|
const int defaultPort = 22;
|
||||||
Client.ErrorOccurred -= Client_ErrorOccurred;
|
var p = Port == default(int) ? defaultPort : Port;
|
||||||
KillClient(SocketStatus.SOCKET_STATUS_BROKEN_LOCALLY);
|
|
||||||
|
if (keyboardAuth != null)
|
||||||
|
{
|
||||||
|
keyboardAuth.AuthenticationPrompt -= AuthenticationPromptHandler;
|
||||||
|
keyboardAuth.Dispose();
|
||||||
}
|
}
|
||||||
|
|
||||||
// This handles both password and keyboard-interactive (like on OS-X, 'nixes)
|
if (passwordAuth != null)
|
||||||
KeyboardInteractiveAuthenticationMethod kauth = new KeyboardInteractiveAuthenticationMethod(Username);
|
{
|
||||||
kauth.AuthenticationPrompt += new EventHandler<AuthenticationPromptEventArgs>(kauth_AuthenticationPrompt);
|
passwordAuth.Dispose();
|
||||||
PasswordAuthenticationMethod pauth = new PasswordAuthenticationMethod(Username, Password);
|
}
|
||||||
|
|
||||||
Debug.Console(1, this, "Creating new SshClient");
|
keyboardAuth = new KeyboardInteractiveAuthenticationMethod(Username);
|
||||||
ConnectionInfo connectionInfo = new ConnectionInfo(Hostname, Port, Username, pauth, kauth);
|
passwordAuth = new PasswordAuthenticationMethod(Username, Password);
|
||||||
Client = new SshClient(connectionInfo);
|
keyboardAuth.AuthenticationPrompt += AuthenticationPromptHandler;
|
||||||
|
|
||||||
Client.ErrorOccurred -= Client_ErrorOccurred;
|
var connectionInfo = new ConnectionInfo(Hostname, p, Username, passwordAuth, keyboardAuth);
|
||||||
Client.ErrorOccurred += Client_ErrorOccurred;
|
|
||||||
|
|
||||||
//Attempt to connect
|
if (connectTimer.Disposed && AutoReconnect)
|
||||||
ClientStatus = SocketStatus.SOCKET_STATUS_WAITING;
|
{
|
||||||
|
connectTimer = new CTimer(obj =>
|
||||||
|
{
|
||||||
|
Debug.Console(1, this, "Attempting to reconnect");
|
||||||
|
Connect();
|
||||||
|
}, Timeout.Infinite);
|
||||||
|
}
|
||||||
|
|
||||||
|
ConnectInternal(connectionInfo);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
|
||||||
|
Debug.Console(1, this, "Ignoring connection request while connect/disconnect in progress...");
|
||||||
|
if (!connectTimer.Disposed && AutoReconnect)
|
||||||
|
connectTimer.Reset(AutoReconnectIntervalMs);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private void ConnectInternal(ConnectionInfo connectionInfo)
|
||||||
|
{
|
||||||
|
Debug.Console(1, this, "Attempting connection to: " + Hostname);
|
||||||
try
|
try
|
||||||
{
|
{
|
||||||
Client.Connect();
|
// Debug.Console(1, this, Debug.ErrorLogLevel.Notice, "Creating new client...");
|
||||||
TheStream = Client.CreateShellStream("PDTShell", 100, 80, 100, 200, 65534);
|
client = new SshClient(connectionInfo);
|
||||||
TheStream.DataReceived += Stream_DataReceived;
|
client.ErrorOccurred += ClientErrorHandler;
|
||||||
//TheStream.ErrorOccurred += TheStream_ErrorOccurred;
|
client.HostKeyReceived += HostKeyReceivedHandler;
|
||||||
|
ClientStatus = SocketStatus.SOCKET_STATUS_WAITING;
|
||||||
|
|
||||||
|
// Debug.Console(1, this, Debug.ErrorLogLevel.Notice, "Connecting...");
|
||||||
|
client.Connect();
|
||||||
|
|
||||||
|
// Debug.Console(1, this, Debug.ErrorLogLevel.Notice, "Creating shell...");
|
||||||
|
stream = client.CreateShellStream("PDTShell", 100, 80, 100, 200, 65534);
|
||||||
|
stream.DataReceived += StreamDataReceivedHandler;
|
||||||
|
stream.ErrorOccurred += StreamErrorOccurredHandler;
|
||||||
|
// Debug.Console(1, this, Debug.ErrorLogLevel.Notice, "Shell created");
|
||||||
|
|
||||||
|
if (client.IsConnected)
|
||||||
|
{
|
||||||
Debug.Console(1, this, Debug.ErrorLogLevel.Notice, "Connected");
|
Debug.Console(1, this, Debug.ErrorLogLevel.Notice, "Connected");
|
||||||
|
connectTimer.Stop();
|
||||||
ClientStatus = SocketStatus.SOCKET_STATUS_CONNECTED;
|
ClientStatus = SocketStatus.SOCKET_STATUS_CONNECTED;
|
||||||
IsConnecting = false;
|
Interlocked.Exchange(ref connectionProgress, ConnectionProgress.Idle);
|
||||||
return; // Success will not pass here
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
throw new Exception("Unknown connection error");
|
||||||
|
}
|
||||||
}
|
}
|
||||||
catch (SshConnectionException e)
|
catch (SshConnectionException e)
|
||||||
{
|
{
|
||||||
var ie = e.InnerException; // The details are inside!!
|
var ie = e.InnerException; // The details are inside!!
|
||||||
|
|
||||||
if (ie is SocketException)
|
if (ie is SocketException)
|
||||||
Debug.Console(1, this, Debug.ErrorLogLevel.Error, "'{0}' CONNECTION failure: Cannot reach host, ({1})", Key, ie.Message);
|
Debug.Console(1, this, Debug.ErrorLogLevel.Error,
|
||||||
|
"'{0}' CONNECTION failure: Cannot reach host, ({1})",
|
||||||
|
Key, ie.Message);
|
||||||
else if (ie is System.Net.Sockets.SocketException)
|
else if (ie is System.Net.Sockets.SocketException)
|
||||||
Debug.Console(1, this, Debug.ErrorLogLevel.Error, "'{0}' Connection failure: Cannot reach host '{1}' on port {2}, ({3})",
|
Debug.Console(1, this, Debug.ErrorLogLevel.Error,
|
||||||
|
"'{0}' Connection failure: Cannot reach host '{1}' on port {2}, ({3})",
|
||||||
Key, Hostname, Port, ie.GetType());
|
Key, Hostname, Port, ie.GetType());
|
||||||
else if (ie is SshAuthenticationException)
|
else if (ie is SshAuthenticationException)
|
||||||
{
|
{
|
||||||
@@ -271,115 +333,150 @@ namespace PepperDash.Core
|
|||||||
Username, ie.Message);
|
Username, ie.Message);
|
||||||
}
|
}
|
||||||
else
|
else
|
||||||
Debug.Console(1, this, Debug.ErrorLogLevel.Error, "Error on connect:\r({0})", e);
|
Debug.Console(1, this, Debug.ErrorLogLevel.Error, "Error on connect:({0})", ie.Message);
|
||||||
|
|
||||||
ClientStatus = SocketStatus.SOCKET_STATUS_CONNECT_FAILED;
|
DisconnectInternal(SocketStatus.SOCKET_STATUS_CONNECT_FAILED);
|
||||||
HandleConnectionFailure();
|
|
||||||
}
|
}
|
||||||
catch (Exception e)
|
catch (Exception e)
|
||||||
{
|
{
|
||||||
Debug.Console(1, this, Debug.ErrorLogLevel.Error, "Unhandled exception on connect:\r({0})", e);
|
Debug.Console(1, this, Debug.ErrorLogLevel.Notice, "Connection error: " + e.Message);
|
||||||
ClientStatus = SocketStatus.SOCKET_STATUS_CONNECT_FAILED;
|
DisconnectInternal(SocketStatus.SOCKET_STATUS_CONNECT_FAILED);
|
||||||
HandleConnectionFailure();
|
|
||||||
}
|
}
|
||||||
|
|
||||||
ClientStatus = SocketStatus.SOCKET_STATUS_CONNECT_FAILED;
|
|
||||||
HandleConnectionFailure();
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Disconnect the clients and put away it's resources.
|
/// Disconnect the clients and put away it's resources.
|
||||||
/// </summary>
|
/// </summary>
|
||||||
public void Disconnect()
|
public void Disconnect()
|
||||||
{
|
{
|
||||||
ConnectEnabled = false;
|
ConnectEnabled = false;
|
||||||
// Stop trying reconnects, if we are
|
Disconnect(SocketStatus.SOCKET_STATUS_BROKEN_LOCALLY);
|
||||||
if (ReconnectTimer != null)
|
|
||||||
{
|
|
||||||
ReconnectTimer.Stop();
|
|
||||||
ReconnectTimer = null;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
KillClient(SocketStatus.SOCKET_STATUS_BROKEN_LOCALLY);
|
private void Disconnect(SocketStatus status)
|
||||||
}
|
{
|
||||||
|
// kill the reconnect timer if we are disconnecting locally
|
||||||
|
if (status == SocketStatus.SOCKET_STATUS_BROKEN_LOCALLY)
|
||||||
|
DisposeOfTimer(connectTimer);
|
||||||
|
|
||||||
/// <summary>
|
if (
|
||||||
/// Kills the stream, cleans up the client and sets it to null
|
Interlocked.CompareExchange(ref connectionProgress, ConnectionProgress.InProgress,
|
||||||
/// </summary>
|
ConnectionProgress.Idle) == ConnectionProgress.Idle)
|
||||||
private void KillClient(SocketStatus status)
|
|
||||||
{
|
{
|
||||||
KillStream();
|
Debug.Console(1, this, "Disconnecting...");
|
||||||
|
CrestronInvoke.BeginInvoke(_ => DisconnectInternal(status));
|
||||||
if (Client != null)
|
|
||||||
{
|
|
||||||
IsConnecting = false;
|
|
||||||
Client.Disconnect();
|
|
||||||
Client = null;
|
|
||||||
ClientStatus = status;
|
|
||||||
Debug.Console(1, this, "Disconnected");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// <summary>
|
|
||||||
/// Anything to do with reestablishing connection on failures
|
|
||||||
/// </summary>
|
|
||||||
void HandleConnectionFailure()
|
|
||||||
{
|
|
||||||
KillClient(SocketStatus.SOCKET_STATUS_CONNECT_FAILED);
|
|
||||||
|
|
||||||
Debug.Console(1, this, "Client nulled due to connection failure. AutoReconnect: {0}, ConnectEnabled: {1}", AutoReconnect, ConnectEnabled);
|
|
||||||
if (AutoReconnect && ConnectEnabled)
|
|
||||||
{
|
|
||||||
Debug.Console(1, this, "Checking autoreconnect: {0}, {1}ms", AutoReconnect, AutoReconnectIntervalMs);
|
|
||||||
if (ReconnectTimer == null)
|
|
||||||
{
|
|
||||||
ReconnectTimer = new CTimer(o =>
|
|
||||||
{
|
|
||||||
Connect();
|
|
||||||
}, AutoReconnectIntervalMs);
|
|
||||||
Debug.Console(1, this, Debug.ErrorLogLevel.Notice, "Attempting connection in {0} seconds",
|
|
||||||
(float) (AutoReconnectIntervalMs/1000));
|
|
||||||
}
|
}
|
||||||
else
|
else
|
||||||
{
|
{
|
||||||
Debug.Console(1, this, "{0} second reconnect cycle running",
|
if (!disconnectTimer.Disposed)
|
||||||
(float) (AutoReconnectIntervalMs/1000));
|
DisposeOfTimer(disconnectTimer);
|
||||||
}
|
|
||||||
|
disconnectTimer = new CTimer(_ => Disconnect(status), 10000);
|
||||||
|
Debug.Console(1, this, "Ignoring disconnect request while connect/disconnect in progress... will try again soon");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>
|
private void DisconnectInternal(SocketStatus status)
|
||||||
/// Kills the stream
|
|
||||||
/// </summary>
|
|
||||||
void KillStream()
|
|
||||||
{
|
{
|
||||||
if (TheStream != null)
|
try
|
||||||
{
|
{
|
||||||
TheStream.DataReceived -= Stream_DataReceived;
|
DisposeOfStream();
|
||||||
TheStream.Close();
|
DisposeOfClient();
|
||||||
TheStream.Dispose();
|
DisposeOfAuthMethods();
|
||||||
TheStream = null;
|
|
||||||
|
Debug.Console(1, this, Debug.ErrorLogLevel.Notice, "Disconnect Complete");
|
||||||
|
ClientStatus = status;
|
||||||
|
|
||||||
|
DisposeOfTimer(disconnectTimer);
|
||||||
|
if (!connectTimer.Disposed && AutoReconnect)
|
||||||
|
{
|
||||||
|
Debug.Console(1, this, "Autoreconnect try again soon");
|
||||||
|
connectTimer.Reset(AutoReconnectIntervalMs);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
catch (Exception ex)
|
||||||
|
{
|
||||||
|
Debug.Console(1, this, Debug.ErrorLogLevel.Notice, "Caught a general exception in disconnect:{0}", ex);
|
||||||
|
}
|
||||||
|
finally
|
||||||
|
{
|
||||||
|
Interlocked.Exchange(ref connectionProgress, ConnectionProgress.Idle);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>
|
private void DisposeOfAuthMethods()
|
||||||
/// Handles the keyboard interactive authentication, should it be required.
|
|
||||||
/// </summary>
|
|
||||||
void kauth_AuthenticationPrompt(object sender, AuthenticationPromptEventArgs e)
|
|
||||||
{
|
{
|
||||||
foreach (AuthenticationPrompt prompt in e.Prompts)
|
try
|
||||||
if (prompt.Request.IndexOf("Password:", StringComparison.InvariantCultureIgnoreCase) != -1)
|
{
|
||||||
prompt.Response = Password;
|
if (keyboardAuth != null)
|
||||||
|
{
|
||||||
|
keyboardAuth.AuthenticationPrompt -= AuthenticationPromptHandler;
|
||||||
|
keyboardAuth.Dispose();
|
||||||
|
keyboardAuth = null;
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>
|
if (passwordAuth != null)
|
||||||
/// Handler for data receive on ShellStream. Passes data across to queue for line parsing.
|
|
||||||
/// </summary>
|
|
||||||
void Stream_DataReceived(object sender, Crestron.SimplSharp.Ssh.Common.ShellDataEventArgs e)
|
|
||||||
{
|
{
|
||||||
|
passwordAuth.Dispose();
|
||||||
|
passwordAuth = null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
catch (Exception e)
|
||||||
|
{
|
||||||
|
Debug.Console(1, this, Debug.ErrorLogLevel.Notice,
|
||||||
|
"Disconnect() Exception occured freeing auth: " + e.Message);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private void DisposeOfClient()
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
if (client != null)
|
||||||
|
{
|
||||||
|
if (client.IsConnected)
|
||||||
|
client.Disconnect();
|
||||||
|
|
||||||
|
client.ErrorOccurred -= ClientErrorHandler;
|
||||||
|
client.HostKeyReceived -= HostKeyReceivedHandler;
|
||||||
|
client.Dispose();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
catch (Exception e)
|
||||||
|
{
|
||||||
|
Debug.Console(1, this, Debug.ErrorLogLevel.Notice,
|
||||||
|
"Disconnect() Exception occured freeing client: " + e.Message);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private void DisposeOfStream()
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
if (stream != null)
|
||||||
|
{
|
||||||
|
stream.DataReceived -= StreamDataReceivedHandler;
|
||||||
|
stream.ErrorOccurred -= StreamErrorOccurredHandler;
|
||||||
|
stream.Close();
|
||||||
|
stream.Dispose();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
catch (Exception e)
|
||||||
|
{
|
||||||
|
Debug.Console(1, this, Debug.ErrorLogLevel.Notice,
|
||||||
|
"Disconnect() exception occured freeing stream: " + e.Message);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void DisposeOfTimer(CTimer timer)
|
||||||
|
{
|
||||||
|
if (timer == null || timer.Disposed) return;
|
||||||
|
timer.Stop();
|
||||||
|
timer.Dispose();
|
||||||
|
}
|
||||||
|
|
||||||
|
private void StreamDataReceivedHandler(object sender, ShellDataEventArgs e)
|
||||||
|
{
|
||||||
var bytes = e.Data;
|
var bytes = e.Data;
|
||||||
if (bytes.Length > 0)
|
if (bytes.Length > 0)
|
||||||
{
|
{
|
||||||
@@ -390,6 +487,7 @@ namespace PepperDash.Core
|
|||||||
{
|
{
|
||||||
Debug.Console(0, this, "Received {1} bytes: '{0}'", ComTextHelper.GetEscapedText(bytes), bytes.Length);
|
Debug.Console(0, this, "Received {1} bytes: '{0}'", ComTextHelper.GetEscapedText(bytes), bytes.Length);
|
||||||
}
|
}
|
||||||
|
|
||||||
bytesHandler(this, new GenericCommMethodReceiveBytesArgs(bytes));
|
bytesHandler(this, new GenericCommMethodReceiveBytesArgs(bytes));
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -405,139 +503,75 @@ namespace PepperDash.Core
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private void ClientErrorHandler(object sender, ExceptionEventArgs e)
|
||||||
/// <summary>
|
|
||||||
/// Error event handler for client events - disconnect, etc. Will forward those events via ConnectionChange
|
|
||||||
/// event
|
|
||||||
/// </summary>
|
|
||||||
void Client_ErrorOccurred(object sender, Crestron.SimplSharp.Ssh.Common.ExceptionEventArgs e)
|
|
||||||
{
|
{
|
||||||
if (e.Exception is SshConnectionException || e.Exception is System.Net.Sockets.SocketException)
|
Debug.Console(1, this, "SSH client error:{0}", e.Exception);
|
||||||
Debug.Console(1, this, Debug.ErrorLogLevel.Error, "Disconnected by remote");
|
Disconnect(SocketStatus.SOCKET_STATUS_BROKEN_REMOTELY);
|
||||||
else
|
|
||||||
Debug.Console(1, this, Debug.ErrorLogLevel.Error, "Unhandled SSH client error: {0}", e.Exception);
|
|
||||||
|
|
||||||
ClientStatus = SocketStatus.SOCKET_STATUS_BROKEN_REMOTELY;
|
|
||||||
HandleConnectionFailure();
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>
|
private void StreamErrorOccurredHandler(object sender, EventArgs e)
|
||||||
/// Helper for ConnectionChange event
|
|
||||||
/// </summary>
|
|
||||||
void OnConnectionChange()
|
|
||||||
{
|
{
|
||||||
if (ConnectionChange != null)
|
Debug.Console(1, this, "SSH Shellstream error");
|
||||||
ConnectionChange(this, new GenericSocketStatusChageEventArgs(this));
|
Disconnect(SocketStatus.SOCKET_STATUS_BROKEN_REMOTELY);
|
||||||
}
|
}
|
||||||
|
|
||||||
#region IBasicCommunication Members
|
private void AuthenticationPromptHandler(object sender, AuthenticationPromptEventArgs e)
|
||||||
|
|
||||||
/// <summary>
|
|
||||||
/// Sends text to the server
|
|
||||||
/// </summary>
|
|
||||||
/// <param name="text"></param>
|
|
||||||
public void SendText(string text)
|
|
||||||
{
|
{
|
||||||
try
|
foreach (var prompt in e.Prompts)
|
||||||
{
|
if (prompt.Request.IndexOf("Password:", StringComparison.InvariantCultureIgnoreCase) != -1)
|
||||||
if (Client != null && TheStream != null && IsConnected)
|
prompt.Response = Password;
|
||||||
{
|
|
||||||
if (StreamDebugging.TxStreamDebuggingIsEnabled)
|
|
||||||
Debug.Console(0, this, "Sending {0} characters of text: '{1}'", text.Length, ComTextHelper.GetDebugText(text));
|
|
||||||
|
|
||||||
TheStream.Write(text);
|
|
||||||
TheStream.Flush();
|
|
||||||
|
|
||||||
}
|
}
|
||||||
else
|
|
||||||
{
|
|
||||||
Debug.Console(1, this, "Client is null or disconnected. Cannot Send Text");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
catch (Exception ex)
|
|
||||||
{
|
|
||||||
Debug.Console(0, "Exception: {0}", ex.Message);
|
|
||||||
Debug.Console(0, "Stack Trace: {0}", ex.StackTrace);
|
|
||||||
|
|
||||||
Debug.Console(1, this, Debug.ErrorLogLevel.Error, "Stream write failed. Disconnected, closing");
|
private void HostKeyReceivedHandler(object sender, HostKeyEventArgs e)
|
||||||
ClientStatus = SocketStatus.SOCKET_STATUS_BROKEN_REMOTELY;
|
{
|
||||||
HandleConnectionFailure();
|
e.CanTrust = true;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static IEnumerable<string> SplitDataReceived(string str, int maxChunkSize)
|
||||||
|
{
|
||||||
|
for (var i = 0; i < str.Length; i += maxChunkSize)
|
||||||
|
{
|
||||||
|
yield return str.Substring(i, Math.Min(maxChunkSize, str.Length - i));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Sends Bytes to the server
|
/// Stream debugging properties
|
||||||
/// </summary>
|
/// </summary>
|
||||||
/// <param name="bytes"></param>
|
public CommunicationStreamDebugging StreamDebugging { get; private set; }
|
||||||
public void SendBytes(byte[] bytes)
|
|
||||||
{
|
|
||||||
try
|
|
||||||
{
|
|
||||||
if (Client != null && TheStream != null && IsConnected)
|
|
||||||
{
|
|
||||||
if (StreamDebugging.TxStreamDebuggingIsEnabled)
|
|
||||||
Debug.Console(0, this, "Sending {0} bytes: '{1}'", bytes.Length, ComTextHelper.GetEscapedText(bytes));
|
|
||||||
|
|
||||||
TheStream.Write(bytes, 0, bytes.Length);
|
|
||||||
TheStream.Flush();
|
|
||||||
}
|
|
||||||
else
|
|
||||||
{
|
|
||||||
Debug.Console(1, this, "Client is null or disconnected. Cannot Send Bytes");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
catch
|
|
||||||
{
|
|
||||||
Debug.Console(1, this, Debug.ErrorLogLevel.Error, "Stream write failed. Disconnected, closing");
|
|
||||||
ClientStatus = SocketStatus.SOCKET_STATUS_BROKEN_REMOTELY;
|
|
||||||
HandleConnectionFailure();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#endregion
|
|
||||||
}
|
|
||||||
|
|
||||||
//*****************************************************************************************************
|
|
||||||
//*****************************************************************************************************
|
|
||||||
/// <summary>
|
|
||||||
/// Fired when connection changes
|
|
||||||
/// </summary>
|
|
||||||
public class SshConnectionChangeEventArgs : EventArgs
|
|
||||||
{
|
|
||||||
/// <summary>
|
|
||||||
/// Connection State
|
|
||||||
/// </summary>
|
|
||||||
public bool IsConnected { get; private set; }
|
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Connection Status represented as a ushort
|
/// Event fired on a connection status change
|
||||||
/// </summary>
|
/// </summary>
|
||||||
public ushort UIsConnected { get { return (ushort)(Client.IsConnected ? 1 : 0); } }
|
public event EventHandler<GenericSocketStatusChageEventArgs> ConnectionChange;
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// The client
|
/// Determines if autoreconnect is enabled
|
||||||
/// </summary>
|
/// </summary>
|
||||||
public GenericSshClient Client { get; private set; }
|
public bool AutoReconnect { get; set; }
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Socket Status as represented by
|
/// Millisecond value, determines the timeout period in between reconnect attempts.
|
||||||
|
/// Set to 10000 by default
|
||||||
/// </summary>
|
/// </summary>
|
||||||
public ushort Status { get { return Client.UStatus; } }
|
public int AutoReconnectIntervalMs { get; set; }
|
||||||
|
|
||||||
/// <summary>
|
private bool disposed;
|
||||||
/// S+ Constructor
|
public void Dispose()
|
||||||
/// </summary>
|
|
||||||
public SshConnectionChangeEventArgs() { }
|
|
||||||
|
|
||||||
/// <summary>
|
|
||||||
/// EventArgs class
|
|
||||||
/// </summary>
|
|
||||||
/// <param name="isConnected">Connection State</param>
|
|
||||||
/// <param name="client">The Client</param>
|
|
||||||
public SshConnectionChangeEventArgs(bool isConnected, GenericSshClient client)
|
|
||||||
{
|
{
|
||||||
IsConnected = isConnected;
|
Dispose(true);
|
||||||
Client = client;
|
CrestronEnvironment.GC.SuppressFinalize(this);
|
||||||
|
}
|
||||||
|
|
||||||
|
protected virtual void Dispose(bool disposing)
|
||||||
|
{
|
||||||
|
if (disposed)
|
||||||
|
return;
|
||||||
|
|
||||||
|
if (disposing)
|
||||||
|
Disconnect();
|
||||||
|
|
||||||
|
disposed = true;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}*/
|
|
||||||
}
|
}
|
||||||
@@ -1,577 +0,0 @@
|
|||||||
using System;
|
|
||||||
using System.Collections.Generic;
|
|
||||||
using System.Linq;
|
|
||||||
using System.Text;
|
|
||||||
using Crestron.SimplSharp;
|
|
||||||
using Crestron.SimplSharp.CrestronSockets;
|
|
||||||
using Crestron.SimplSharp.Ssh;
|
|
||||||
using Crestron.SimplSharp.Ssh.Common;
|
|
||||||
|
|
||||||
namespace PepperDash.Core
|
|
||||||
{
|
|
||||||
/// <summary>
|
|
||||||
/// Generic ssh client
|
|
||||||
/// </summary>
|
|
||||||
public class GenericSshClient : Device, IStreamDebugging, ISocketStatus, IAutoReconnect, IDisposable
|
|
||||||
{
|
|
||||||
private static class ConnectionProgress
|
|
||||||
{
|
|
||||||
public const int Idle = 0;
|
|
||||||
public const int InProgress = 1;
|
|
||||||
}
|
|
||||||
|
|
||||||
private SshClient client;
|
|
||||||
private ShellStream stream;
|
|
||||||
private CTimer connectTimer;
|
|
||||||
private CTimer disconnectTimer;
|
|
||||||
private int connectionProgress = ConnectionProgress.Idle;
|
|
||||||
private KeyboardInteractiveAuthenticationMethod keyboardAuth;
|
|
||||||
private PasswordAuthenticationMethod passwordAuth;
|
|
||||||
private SocketStatus socketSatus;
|
|
||||||
|
|
||||||
/// <summary>
|
|
||||||
/// Address of server
|
|
||||||
/// </summary>
|
|
||||||
public string Hostname { get; set; }
|
|
||||||
|
|
||||||
/// <summary>
|
|
||||||
/// Port on server
|
|
||||||
/// </summary>
|
|
||||||
public int Port { get; set; }
|
|
||||||
|
|
||||||
/// <summary>
|
|
||||||
/// Username for server
|
|
||||||
/// </summary>
|
|
||||||
public string Username { get; set; }
|
|
||||||
|
|
||||||
/// <summary>
|
|
||||||
/// And... Password for server. That was worth documenting!
|
|
||||||
/// </summary>
|
|
||||||
public string Password { get; set; }
|
|
||||||
|
|
||||||
/// <summary>
|
|
||||||
/// Client socket status
|
|
||||||
/// </summary>
|
|
||||||
public SocketStatus ClientStatus
|
|
||||||
{
|
|
||||||
get { return socketSatus; }
|
|
||||||
private set
|
|
||||||
{
|
|
||||||
if (socketSatus == value)
|
|
||||||
return;
|
|
||||||
socketSatus = value;
|
|
||||||
OnConnectionChange();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// <summary>
|
|
||||||
/// Will be set and unset by connect and disconnect only
|
|
||||||
/// </summary>
|
|
||||||
public bool ConnectEnabled { get; private set; }
|
|
||||||
|
|
||||||
private void OnConnectionChange()
|
|
||||||
{
|
|
||||||
var handler = ConnectionChange;
|
|
||||||
if (handler != null)
|
|
||||||
handler(this, new GenericSocketStatusChageEventArgs(this));
|
|
||||||
}
|
|
||||||
|
|
||||||
private const string SPlusKey = "Uninitialized SshClient";
|
|
||||||
|
|
||||||
/// <summary>
|
|
||||||
/// S+ Constructor - Must set all properties before calling Connect
|
|
||||||
/// </summary>
|
|
||||||
public GenericSshClient()
|
|
||||||
: base(SPlusKey)
|
|
||||||
{
|
|
||||||
StreamDebugging = new CommunicationStreamDebugging(SPlusKey);
|
|
||||||
AutoReconnectIntervalMs = 10000;
|
|
||||||
|
|
||||||
connectTimer = new CTimer(_ =>
|
|
||||||
{
|
|
||||||
Debug.Console(1, this, "Attempting to reconnect");
|
|
||||||
Connect();
|
|
||||||
}, Timeout.Infinite);
|
|
||||||
|
|
||||||
disconnectTimer = new CTimer(_ =>
|
|
||||||
{
|
|
||||||
Debug.Console(1, this, "Attempting to disconnect");
|
|
||||||
Disconnect();
|
|
||||||
}, Timeout.Infinite);
|
|
||||||
|
|
||||||
CrestronEnvironment.ProgramStatusEventHandler += OnProgramShutdown;
|
|
||||||
}
|
|
||||||
|
|
||||||
/// <summary>
|
|
||||||
/// Typical constructor.
|
|
||||||
/// </summary>
|
|
||||||
public GenericSshClient(string key, string hostname, int port, string username, string password) : base(key)
|
|
||||||
{
|
|
||||||
Key = key;
|
|
||||||
Hostname = hostname;
|
|
||||||
Port = port;
|
|
||||||
Username = username;
|
|
||||||
Password = password;
|
|
||||||
AutoReconnectIntervalMs = 10000;
|
|
||||||
|
|
||||||
connectTimer = new CTimer(_ =>
|
|
||||||
{
|
|
||||||
Debug.Console(1, this, "Attempting to reconnect");
|
|
||||||
Connect();
|
|
||||||
}, Timeout.Infinite);
|
|
||||||
|
|
||||||
disconnectTimer = new CTimer(_ =>
|
|
||||||
{
|
|
||||||
Debug.Console(1, this, "Attempting to disconnect");
|
|
||||||
Disconnect();
|
|
||||||
}, Timeout.Infinite);
|
|
||||||
|
|
||||||
StreamDebugging = new CommunicationStreamDebugging(key);
|
|
||||||
CrestronEnvironment.ProgramStatusEventHandler += OnProgramShutdown;
|
|
||||||
}
|
|
||||||
|
|
||||||
private void OnProgramShutdown(eProgramStatusEventType type)
|
|
||||||
{
|
|
||||||
try
|
|
||||||
{
|
|
||||||
if (type == eProgramStatusEventType.Stopping)
|
|
||||||
Disconnect();
|
|
||||||
}
|
|
||||||
catch (Exception ex)
|
|
||||||
{
|
|
||||||
Debug.Console(1, this, Debug.ErrorLogLevel.Notice, "Error at shutdown:{0}", ex);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// <summary>
|
|
||||||
/// Just to help S+ set the key
|
|
||||||
/// </summary>
|
|
||||||
public void Initialize(string key)
|
|
||||||
{
|
|
||||||
Key = key;
|
|
||||||
}
|
|
||||||
|
|
||||||
/// <summary>
|
|
||||||
/// True when the server is connected - when status == 2.
|
|
||||||
/// </summary>
|
|
||||||
public bool IsConnected
|
|
||||||
{
|
|
||||||
get { return client != null && client.IsConnected; }
|
|
||||||
}
|
|
||||||
|
|
||||||
/// <summary>
|
|
||||||
/// S+ helper for IsConnected
|
|
||||||
/// </summary>
|
|
||||||
public ushort UIsConnected
|
|
||||||
{
|
|
||||||
get { return (ushort)(IsConnected ? 1 : 0); }
|
|
||||||
}
|
|
||||||
|
|
||||||
/// <summary>
|
|
||||||
/// Event fired when bytes are received on the shell
|
|
||||||
/// </summary>
|
|
||||||
public event EventHandler<GenericCommMethodReceiveBytesArgs> BytesReceived;
|
|
||||||
|
|
||||||
/// <summary>
|
|
||||||
/// Event fired when test is received on the shell
|
|
||||||
/// </summary>
|
|
||||||
public event EventHandler<GenericCommMethodReceiveTextArgs> TextReceived;
|
|
||||||
|
|
||||||
/// <summary>
|
|
||||||
/// Sends text to the server
|
|
||||||
/// </summary>
|
|
||||||
/// <param name="text"></param>
|
|
||||||
public void SendText(string text)
|
|
||||||
{
|
|
||||||
if (CanSend())
|
|
||||||
{
|
|
||||||
if (StreamDebugging.TxStreamDebuggingIsEnabled)
|
|
||||||
Debug.Console(0, this, "Sending {0} characters of text: '{1}'", text.Length, ComTextHelper.GetDebugText(text.Trim()));
|
|
||||||
|
|
||||||
stream.WriteLine(text);
|
|
||||||
}
|
|
||||||
else
|
|
||||||
{
|
|
||||||
Debug.Console(1, this, "SendText() called but not connected");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// <summary>
|
|
||||||
/// Sends bytes to the server
|
|
||||||
/// </summary>
|
|
||||||
/// <param name="bytes"></param>
|
|
||||||
public void SendBytes(byte[] bytes)
|
|
||||||
{
|
|
||||||
if (CanSend())
|
|
||||||
{
|
|
||||||
if (StreamDebugging.TxStreamDebuggingIsEnabled)
|
|
||||||
Debug.Console(0, this, "Sending {0} bytes: '{1}'", bytes.Length, ComTextHelper.GetEscapedText(bytes));
|
|
||||||
|
|
||||||
stream.Write(bytes, 0, bytes.Length);
|
|
||||||
stream.Flush();
|
|
||||||
}
|
|
||||||
else
|
|
||||||
{
|
|
||||||
Debug.Console(1, this, "SendText() called but not connected");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private bool CanSend()
|
|
||||||
{
|
|
||||||
return client != null && stream != null && client.IsConnected;
|
|
||||||
}
|
|
||||||
|
|
||||||
/// <summary>
|
|
||||||
/// Connect to the server, using the provided properties.
|
|
||||||
/// </summary>
|
|
||||||
public void Connect()
|
|
||||||
{
|
|
||||||
ConnectEnabled = true;
|
|
||||||
DisposeOfTimer(disconnectTimer);
|
|
||||||
|
|
||||||
if (
|
|
||||||
Interlocked.CompareExchange(ref connectionProgress, ConnectionProgress.InProgress,
|
|
||||||
ConnectionProgress.Idle) == ConnectionProgress.Idle)
|
|
||||||
{
|
|
||||||
if (client != null && client.IsConnected)
|
|
||||||
{
|
|
||||||
Debug.Console(1, this, "Ignoring connection request... already connected");
|
|
||||||
Interlocked.Exchange(ref connectionProgress, ConnectionProgress.Idle);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
CrestronInvoke.BeginInvoke(_ =>
|
|
||||||
{
|
|
||||||
const int defaultPort = 22;
|
|
||||||
var p = Port == default(int) ? defaultPort : Port;
|
|
||||||
|
|
||||||
if (keyboardAuth != null)
|
|
||||||
{
|
|
||||||
keyboardAuth.AuthenticationPrompt -= AuthenticationPromptHandler;
|
|
||||||
keyboardAuth.Dispose();
|
|
||||||
}
|
|
||||||
|
|
||||||
if (passwordAuth != null)
|
|
||||||
{
|
|
||||||
passwordAuth.Dispose();
|
|
||||||
}
|
|
||||||
|
|
||||||
keyboardAuth = new KeyboardInteractiveAuthenticationMethod(Username);
|
|
||||||
passwordAuth = new PasswordAuthenticationMethod(Username, Password);
|
|
||||||
keyboardAuth.AuthenticationPrompt += AuthenticationPromptHandler;
|
|
||||||
|
|
||||||
var connectionInfo = new ConnectionInfo(Hostname, p, Username, passwordAuth, keyboardAuth);
|
|
||||||
|
|
||||||
if (connectTimer.Disposed && AutoReconnect)
|
|
||||||
{
|
|
||||||
connectTimer = new CTimer(obj =>
|
|
||||||
{
|
|
||||||
Debug.Console(1, this, "Attempting to reconnect");
|
|
||||||
Connect();
|
|
||||||
}, Timeout.Infinite);
|
|
||||||
}
|
|
||||||
|
|
||||||
ConnectInternal(connectionInfo);
|
|
||||||
});
|
|
||||||
}
|
|
||||||
else
|
|
||||||
{
|
|
||||||
|
|
||||||
Debug.Console(1, this, "Ignoring connection request while connect/disconnect in progress...");
|
|
||||||
if (!connectTimer.Disposed && AutoReconnect)
|
|
||||||
connectTimer.Reset(AutoReconnectIntervalMs);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private void ConnectInternal(ConnectionInfo connectionInfo)
|
|
||||||
{
|
|
||||||
Debug.Console(1, this, "Attempting connection to: " + Hostname);
|
|
||||||
try
|
|
||||||
{
|
|
||||||
// Debug.Console(1, this, Debug.ErrorLogLevel.Notice, "Creating new client...");
|
|
||||||
client = new SshClient(connectionInfo);
|
|
||||||
client.ErrorOccurred += ClientErrorHandler;
|
|
||||||
client.HostKeyReceived += HostKeyReceivedHandler;
|
|
||||||
ClientStatus = SocketStatus.SOCKET_STATUS_WAITING;
|
|
||||||
|
|
||||||
// Debug.Console(1, this, Debug.ErrorLogLevel.Notice, "Connecting...");
|
|
||||||
client.Connect();
|
|
||||||
|
|
||||||
// Debug.Console(1, this, Debug.ErrorLogLevel.Notice, "Creating shell...");
|
|
||||||
stream = client.CreateShellStream("PDTShell", 100, 80, 100, 200, 65534);
|
|
||||||
stream.DataReceived += StreamDataReceivedHandler;
|
|
||||||
stream.ErrorOccurred += StreamErrorOccurredHandler;
|
|
||||||
// Debug.Console(1, this, Debug.ErrorLogLevel.Notice, "Shell created");
|
|
||||||
|
|
||||||
if (client.IsConnected)
|
|
||||||
{
|
|
||||||
Debug.Console(1, this, Debug.ErrorLogLevel.Notice, "Connected");
|
|
||||||
connectTimer.Stop();
|
|
||||||
ClientStatus = SocketStatus.SOCKET_STATUS_CONNECTED;
|
|
||||||
Interlocked.Exchange(ref connectionProgress, ConnectionProgress.Idle);
|
|
||||||
}
|
|
||||||
else
|
|
||||||
{
|
|
||||||
throw new Exception("Unknown connection error");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
catch (SshConnectionException e)
|
|
||||||
{
|
|
||||||
var ie = e.InnerException; // The details are inside!!
|
|
||||||
|
|
||||||
if (ie is SocketException)
|
|
||||||
Debug.Console(1, this, Debug.ErrorLogLevel.Error,
|
|
||||||
"'{0}' CONNECTION failure: Cannot reach host, ({1})",
|
|
||||||
Key, ie.Message);
|
|
||||||
else if (ie is System.Net.Sockets.SocketException)
|
|
||||||
Debug.Console(1, this, Debug.ErrorLogLevel.Error,
|
|
||||||
"'{0}' Connection failure: Cannot reach host '{1}' on port {2}, ({3})",
|
|
||||||
Key, Hostname, Port, ie.GetType());
|
|
||||||
else if (ie is SshAuthenticationException)
|
|
||||||
{
|
|
||||||
Debug.Console(1, this, Debug.ErrorLogLevel.Error, "Authentication failure for username '{0}', ({1})",
|
|
||||||
Username, ie.Message);
|
|
||||||
}
|
|
||||||
else
|
|
||||||
Debug.Console(1, this, Debug.ErrorLogLevel.Error, "Error on connect:({0})", ie.Message);
|
|
||||||
|
|
||||||
DisconnectInternal(SocketStatus.SOCKET_STATUS_CONNECT_FAILED);
|
|
||||||
}
|
|
||||||
catch (Exception e)
|
|
||||||
{
|
|
||||||
Debug.Console(1, this, Debug.ErrorLogLevel.Notice, "Connection error: " + e.Message);
|
|
||||||
DisconnectInternal(SocketStatus.SOCKET_STATUS_CONNECT_FAILED);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// <summary>
|
|
||||||
/// Disconnect the clients and put away it's resources.
|
|
||||||
/// </summary>
|
|
||||||
public void Disconnect()
|
|
||||||
{
|
|
||||||
ConnectEnabled = false;
|
|
||||||
Disconnect(SocketStatus.SOCKET_STATUS_BROKEN_LOCALLY);
|
|
||||||
}
|
|
||||||
|
|
||||||
private void Disconnect(SocketStatus status)
|
|
||||||
{
|
|
||||||
// kill the reconnect timer if we are disconnecting locally
|
|
||||||
if (status == SocketStatus.SOCKET_STATUS_BROKEN_LOCALLY)
|
|
||||||
DisposeOfTimer(connectTimer);
|
|
||||||
|
|
||||||
if (
|
|
||||||
Interlocked.CompareExchange(ref connectionProgress, ConnectionProgress.InProgress,
|
|
||||||
ConnectionProgress.Idle) == ConnectionProgress.Idle)
|
|
||||||
{
|
|
||||||
Debug.Console(1, this, "Disconnecting...");
|
|
||||||
CrestronInvoke.BeginInvoke(_ => DisconnectInternal(status));
|
|
||||||
}
|
|
||||||
else
|
|
||||||
{
|
|
||||||
if (!disconnectTimer.Disposed)
|
|
||||||
DisposeOfTimer(disconnectTimer);
|
|
||||||
|
|
||||||
disconnectTimer = new CTimer(_ => Disconnect(status), 10000);
|
|
||||||
Debug.Console(1, this, "Ignoring disconnect request while connect/disconnect in progress... will try again soon");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private void DisconnectInternal(SocketStatus status)
|
|
||||||
{
|
|
||||||
try
|
|
||||||
{
|
|
||||||
DisposeOfStream();
|
|
||||||
DisposeOfClient();
|
|
||||||
DisposeOfAuthMethods();
|
|
||||||
|
|
||||||
Debug.Console(1, this, Debug.ErrorLogLevel.Notice, "Disconnect Complete");
|
|
||||||
ClientStatus = status;
|
|
||||||
|
|
||||||
DisposeOfTimer(disconnectTimer);
|
|
||||||
if (!connectTimer.Disposed && AutoReconnect)
|
|
||||||
{
|
|
||||||
Debug.Console(1, this, "Autoreconnect try again soon");
|
|
||||||
connectTimer.Reset(AutoReconnectIntervalMs);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
catch (Exception ex)
|
|
||||||
{
|
|
||||||
Debug.Console(1, this, Debug.ErrorLogLevel.Notice, "Caught a general exception in disconnect:{0}", ex);
|
|
||||||
}
|
|
||||||
finally
|
|
||||||
{
|
|
||||||
Interlocked.Exchange(ref connectionProgress, ConnectionProgress.Idle);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private void DisposeOfAuthMethods()
|
|
||||||
{
|
|
||||||
try
|
|
||||||
{
|
|
||||||
if (keyboardAuth != null)
|
|
||||||
{
|
|
||||||
keyboardAuth.AuthenticationPrompt -= AuthenticationPromptHandler;
|
|
||||||
keyboardAuth.Dispose();
|
|
||||||
keyboardAuth = null;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (passwordAuth != null)
|
|
||||||
{
|
|
||||||
passwordAuth.Dispose();
|
|
||||||
passwordAuth = null;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
catch (Exception e)
|
|
||||||
{
|
|
||||||
Debug.Console(1, this, Debug.ErrorLogLevel.Notice,
|
|
||||||
"Disconnect() Exception occured freeing auth: " + e.Message);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private void DisposeOfClient()
|
|
||||||
{
|
|
||||||
try
|
|
||||||
{
|
|
||||||
if (client != null)
|
|
||||||
{
|
|
||||||
if (client.IsConnected)
|
|
||||||
client.Disconnect();
|
|
||||||
|
|
||||||
client.ErrorOccurred -= ClientErrorHandler;
|
|
||||||
client.HostKeyReceived -= HostKeyReceivedHandler;
|
|
||||||
client.Dispose();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
catch (Exception e)
|
|
||||||
{
|
|
||||||
Debug.Console(1, this, Debug.ErrorLogLevel.Notice,
|
|
||||||
"Disconnect() Exception occured freeing client: " + e.Message);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private void DisposeOfStream()
|
|
||||||
{
|
|
||||||
try
|
|
||||||
{
|
|
||||||
if (stream != null)
|
|
||||||
{
|
|
||||||
stream.DataReceived -= StreamDataReceivedHandler;
|
|
||||||
stream.ErrorOccurred -= StreamErrorOccurredHandler;
|
|
||||||
stream.Close();
|
|
||||||
stream.Dispose();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
catch (Exception e)
|
|
||||||
{
|
|
||||||
Debug.Console(1, this, Debug.ErrorLogLevel.Notice,
|
|
||||||
"Disconnect() exception occured freeing stream: " + e.Message);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private static void DisposeOfTimer(CTimer timer)
|
|
||||||
{
|
|
||||||
if (timer == null || timer.Disposed) return;
|
|
||||||
timer.Stop();
|
|
||||||
timer.Dispose();
|
|
||||||
}
|
|
||||||
|
|
||||||
private void StreamDataReceivedHandler(object sender, ShellDataEventArgs e)
|
|
||||||
{
|
|
||||||
var bytes = e.Data;
|
|
||||||
if (bytes.Length > 0)
|
|
||||||
{
|
|
||||||
var bytesHandler = BytesReceived;
|
|
||||||
if (bytesHandler != null)
|
|
||||||
{
|
|
||||||
if (StreamDebugging.RxStreamDebuggingIsEnabled)
|
|
||||||
{
|
|
||||||
Debug.Console(0, this, "Received {1} bytes: '{0}'", ComTextHelper.GetEscapedText(bytes), bytes.Length);
|
|
||||||
}
|
|
||||||
|
|
||||||
bytesHandler(this, new GenericCommMethodReceiveBytesArgs(bytes));
|
|
||||||
}
|
|
||||||
|
|
||||||
var textHandler = TextReceived;
|
|
||||||
if (textHandler != null)
|
|
||||||
{
|
|
||||||
var str = Encoding.GetEncoding(28591).GetString(bytes, 0, bytes.Length);
|
|
||||||
if (StreamDebugging.RxStreamDebuggingIsEnabled)
|
|
||||||
Debug.Console(0, this, "Received: '{0}'", ComTextHelper.GetDebugText(str));
|
|
||||||
|
|
||||||
textHandler(this, new GenericCommMethodReceiveTextArgs(str));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private void ClientErrorHandler(object sender, ExceptionEventArgs e)
|
|
||||||
{
|
|
||||||
Debug.Console(1, this, "SSH client error:{0}", e.Exception);
|
|
||||||
Disconnect(SocketStatus.SOCKET_STATUS_BROKEN_REMOTELY);
|
|
||||||
}
|
|
||||||
|
|
||||||
private void StreamErrorOccurredHandler(object sender, EventArgs e)
|
|
||||||
{
|
|
||||||
Debug.Console(1, this, "SSH Shellstream error");
|
|
||||||
Disconnect(SocketStatus.SOCKET_STATUS_BROKEN_REMOTELY);
|
|
||||||
}
|
|
||||||
|
|
||||||
private void AuthenticationPromptHandler(object sender, AuthenticationPromptEventArgs e)
|
|
||||||
{
|
|
||||||
foreach (var prompt in e.Prompts)
|
|
||||||
if (prompt.Request.IndexOf("Password:", StringComparison.InvariantCultureIgnoreCase) != -1)
|
|
||||||
prompt.Response = Password;
|
|
||||||
}
|
|
||||||
|
|
||||||
private void HostKeyReceivedHandler(object sender, HostKeyEventArgs e)
|
|
||||||
{
|
|
||||||
e.CanTrust = true;
|
|
||||||
}
|
|
||||||
|
|
||||||
private static IEnumerable<string> SplitDataReceived(string str, int maxChunkSize)
|
|
||||||
{
|
|
||||||
for (var i = 0; i < str.Length; i += maxChunkSize)
|
|
||||||
{
|
|
||||||
yield return str.Substring(i, Math.Min(maxChunkSize, str.Length - i));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// <summary>
|
|
||||||
/// Stream debugging properties
|
|
||||||
/// </summary>
|
|
||||||
public CommunicationStreamDebugging StreamDebugging { get; private set; }
|
|
||||||
|
|
||||||
/// <summary>
|
|
||||||
/// Event fired on a connection status change
|
|
||||||
/// </summary>
|
|
||||||
public event EventHandler<GenericSocketStatusChageEventArgs> ConnectionChange;
|
|
||||||
|
|
||||||
/// <summary>
|
|
||||||
/// Determines if autoreconnect is enabled
|
|
||||||
/// </summary>
|
|
||||||
public bool AutoReconnect { get; set; }
|
|
||||||
|
|
||||||
/// <summary>
|
|
||||||
/// Millisecond value, determines the timeout period in between reconnect attempts.
|
|
||||||
/// Set to 10000 by default
|
|
||||||
/// </summary>
|
|
||||||
public int AutoReconnectIntervalMs { get; set; }
|
|
||||||
|
|
||||||
private bool disposed;
|
|
||||||
public void Dispose()
|
|
||||||
{
|
|
||||||
Dispose(true);
|
|
||||||
CrestronEnvironment.GC.SuppressFinalize(this);
|
|
||||||
}
|
|
||||||
|
|
||||||
protected virtual void Dispose(bool disposing)
|
|
||||||
{
|
|
||||||
if (disposed)
|
|
||||||
return;
|
|
||||||
|
|
||||||
if (disposing)
|
|
||||||
Disconnect();
|
|
||||||
|
|
||||||
disposed = true;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -72,7 +72,6 @@
|
|||||||
<Compile Include="Comm\CommunicationStreamDebugging.cs" />
|
<Compile Include="Comm\CommunicationStreamDebugging.cs" />
|
||||||
<Compile Include="Comm\ControlPropertiesConfig.cs" />
|
<Compile Include="Comm\ControlPropertiesConfig.cs" />
|
||||||
<Compile Include="Comm\GenericSecureTcpIpClient.cs" />
|
<Compile Include="Comm\GenericSecureTcpIpClient.cs" />
|
||||||
<Compile Include="Comm\GenericSshClientV2.cs" />
|
|
||||||
<Compile Include="Comm\GenericTcpIpClient_ForServer.cs" />
|
<Compile Include="Comm\GenericTcpIpClient_ForServer.cs" />
|
||||||
<Compile Include="Comm\GenericHttpSseClient.cs" />
|
<Compile Include="Comm\GenericHttpSseClient.cs" />
|
||||||
<Compile Include="Comm\GenericSecureTcpIpServer.cs" />
|
<Compile Include="Comm\GenericSecureTcpIpServer.cs" />
|
||||||
|
|||||||
Reference in New Issue
Block a user