Esempio n. 1
0
        private void KeepAlive(object sender, ElapsedEventArgs e)
        {
            try
            {
                _scpClient.SendKeepAlive();
                _sshClient.SendKeepAlive();
            }
            catch (Exception exception)
            {
#if DEBUG
                _logger(exception.Message); //TODO: add interactive reconnection routine
#endif
            }
        }
Esempio n. 2
0
        private bool ConnectToUnix()
        {
            string result = "", s;
            string passPhrase = null;

            try
            {
                if (string.IsNullOrEmpty(Host) || string.IsNullOrEmpty(Port.ToString()) || string.IsNullOrEmpty(UserName))
                {
                    Reporter.ToLog(eLogLevel.WARN, "One of Settings of Agent is Empty ");
                    throw new Exception("One of Settings of Agent is Empty ");
                }
                if (Password == null)
                {
                    Password = "";
                }
                try
                {
                    System.Net.Sockets.TcpClient client = new System.Net.Sockets.TcpClient(Host, Port);
                }
                catch (Exception)
                {
                    Reporter.ToLog(eLogLevel.WARN, "Error Connecting to Host: " + Host + " with Port: " + Port);
                    throw new Exception("Error Connecting to Host: " + Host + " with Port: " + Port);
                }

                ConnectionInfo connectionInfo = null;
                if (KeyboardIntractiveAuthentication)
                {
                    connectionInfo = KeyboardInteractiveAuthConnectionInfo();
                }
                else
                {
                    connectionInfo = new ConnectionInfo(Host, Port, UserName,
                                                        new PasswordAuthenticationMethod(UserName, Password)
                                                        );
                }


                if (!string.IsNullOrEmpty(PrivateKeyPassPhrase))
                {
                    passPhrase = PrivateKeyPassPhrase;
                }

                if (File.Exists(PrivateKey))
                {
                    connectionInfo = new ConnectionInfo(Host, Port, UserName,
                                                        new PasswordAuthenticationMethod(UserName, Password),
                                                        new PrivateKeyAuthenticationMethod(UserName,
                                                                                           new PrivateKeyFile(File.OpenRead(PrivateKey), passPhrase)
                                                                                           )
                                                        );
                }
                connectionInfo.Timeout = new TimeSpan(0, 0, SSHConnectionTimeout);
                UnixClient             = new SshClient(connectionInfo);

                Task task = Task.Factory.StartNew(() =>
                {
                    UnixClient.Connect();

                    if (UnixClient.IsConnected)
                    {
                        UnixClient.SendKeepAlive();
                        ss = UnixClient.CreateShellStream("dumb", 240, 24, 800, 600, 1024);
                    }
                });

                Stopwatch st = Stopwatch.StartNew();

                while (!task.IsCompleted && st.ElapsedMilliseconds < SSHConnectionTimeout * 1000)
                {
                    task.Wait(500);  // Give user feedback every 500ms
                    GingerCore.General.DoEvents();
                }

                if (UnixClient.IsConnected)
                {
                    mConsoleDriverWindow.ConsoleWriteText("Connected!");

                    s = ss.ReadLine(new TimeSpan(0, 0, 2));
                    while (!String.IsNullOrEmpty(s))
                    {
                        result = result + "\n" + s;

                        s = ss.ReadLine(new TimeSpan(0, 0, 2));
                    }
                    mConsoleDriverWindow.ConsoleWriteText(result);

                    return(true);
                }
                else
                {
                    Reporter.ToLog(eLogLevel.WARN, "Error connecting to UnixServer - " + Host);
                    throw new Exception("Error connecting to UnixServer - " + Host);
                }
            }
            catch (Exception e)
            {
                ErrorMessageFromDriver = e.Message;
                return(false);
            }
        }
Esempio n. 3
0
        private bool ConnectToUnix()
        {
            string result = "", s;
            string passPhrase = null;

            try
            {
                if (string.IsNullOrEmpty(Host) || string.IsNullOrEmpty(Port.ToString()) || string.IsNullOrEmpty(UserName))
                {
                    Reporter.ToLog(eLogLevel.INFO, "One of Settings of Agent is Empty ");
                    throw new Exception("One of Settings of Agent is Empty ");
                }
                if (Password == null)
                {
                    Password = "";
                }
                try
                {
                    System.Net.Sockets.TcpClient client = new System.Net.Sockets.TcpClient(Host, Port);
                }
                catch (Exception)
                {
                    Reporter.ToLog(eLogLevel.INFO, "Error Connecting to Host: " + Host + " with Port: " + Port);
                    throw new Exception("Error Connecting to Host: " + Host + " with Port: " + Port);
                }

                var connectionInfo = new ConnectionInfo(Host, Port, UserName,
                                                        new PasswordAuthenticationMethod(UserName, Password)
                                                        );

                if (!string.IsNullOrEmpty(PrivateKeyPassPhrase))
                {
                    passPhrase = PrivateKeyPassPhrase;
                }

                if (File.Exists(PrivateKey))
                {
                    connectionInfo = new ConnectionInfo(Host, Port, UserName,
                                                        new PasswordAuthenticationMethod(UserName, Password),
                                                        new PrivateKeyAuthenticationMethod(UserName,
                                                                                           new PrivateKeyFile(File.OpenRead(PrivateKey), passPhrase)
                                                                                           )
                                                        );
                }

                UnixClient = new SshClient(connectionInfo);

                UnixClient.Connect();

                if (UnixClient.IsConnected)
                {
                    UnixClient.SendKeepAlive();
                    ss = UnixClient.CreateShellStream("dumb", 240, 24, 800, 600, 1024);
                    mConsoleDriverWindow.ConsoleWriteText("Connected!");

                    s = ss.ReadLine(new TimeSpan(0, 0, 2));
                    while (!String.IsNullOrEmpty(s))
                    {
                        result = result + "\n" + s;

                        s = ss.ReadLine(new TimeSpan(0, 0, 2));
                    }
                    mConsoleDriverWindow.ConsoleWriteText(result);

                    return(true);
                }
                else
                {
                    Reporter.ToLog(eLogLevel.INFO, "Error connecting to UnixServer - " + Host);
                    throw new Exception("Error connecting to UnixServer - " + Host);
                }
            }
            catch (Exception e)
            {
                ErrorMessageFromDriver = e.Message;
                return(false);
            }
        }
Esempio n. 4
0
        private object SshCommsProcess(object userSpecific)
        {
            try
            {
                Thread.Sleep(1000);

                Debug.WriteInfo(string.Format("{0} attempting connection to {1}", GetType().Name, _address));

                var firstFail = false;

                while (!_client.IsConnected && _reconnect)
                {
                    try
                    {
                        ConnectionStatus = ClientStatus.AttemptingConnection;
                        _client.Connect();
                    }
                    catch
                    {
                        ConnectionStatus = ClientStatus.Disconnected;
                        if (!firstFail)
                        {
                            CloudLog.Warn("{0} could not connect to {1}, will retry every 30 seconds until connected",
                                          GetType().Name, _address);
                            firstFail = true;
                        }
                        Thread.Sleep(30000);
                    }
                }

                if (!_client.IsConnected && !_reconnect)
                {
                    _client.Dispose();
                    _client          = null;
                    ConnectionStatus = ClientStatus.Disconnected;
                    return(null);
                }

                CloudLog.Notice("{0} Connected to {1}", GetType().Name, _address);

                _shell = _client.CreateShellStream("terminal", 80, 24, 800, 600, BufferSize);

                var buffer    = new byte[BufferSize];
                var dataCount = 0;

                try
                {
                    while (_programRunning && _client.IsConnected)
                    {
                        while (_shell.CanRead && _shell.DataAvailable)
                        {
                            var incomingData      = new byte[BufferSize];
                            var incomingDataCount = _shell.Read(incomingData, 0, incomingData.Length);
#if DEBUG
                            _stopWatch.Start();
                            Debug.WriteSuccess("Tesira rx {0} bytes", incomingDataCount);
                            //Debug.WriteNormal(Debug.AnsiBlue +
                            //                  Tools.GetBytesAsReadableString(incomingData, 0, incomingDataCount, true) +
                            //                  Debug.AnsiReset);
#endif
                            if (!Connected &&
                                Encoding.ASCII.GetString(incomingData, 0, incomingDataCount)
                                .Contains("Welcome to the Tesira Text Protocol Server..."))
                            {
                                _requestsSent.Clear();
                                _requestsAwaiting.Clear();
                                _sendQueue.Enqueue("SESSION set verbose true");
                                ConnectionStatus = ClientStatus.Connected;
                                _keepAliveTimer  = new CTimer(specific =>
                                {
#if DEBUG
                                    Debug.WriteInfo(GetType().Name + " Sending KeepAlive");
#endif
                                    _client.SendKeepAlive();
                                }, null, KeepAliveTime, KeepAliveTime);
                            }
                            else if (Connected)
                            {
                                for (var i = 0; i < incomingDataCount; i++)
                                {
                                    buffer[dataCount] = incomingData[i];

                                    if (buffer[dataCount] == 10)
                                    {
                                        //skip
                                    }
                                    else if (buffer[dataCount] != 13)
                                    {
                                        dataCount++;
                                    }
                                    else
                                    {
                                        if (dataCount == 0)
                                        {
                                            continue;
                                        }

                                        var line = Encoding.UTF8.GetString(buffer, 0, dataCount);
                                        dataCount = 0;
#if DEBUG
                                        Debug.WriteSuccess("Tesira Rx Line", Debug.AnsiPurple + line + Debug.AnsiReset);
#endif
                                        TesiraMessage message = null;

                                        if (line == "+OK")
                                        {
                                            var request = _requestsAwaiting.TryToDequeue();
                                            if (request != null)
                                            {
#if DEBUG
                                                Debug.WriteInfo("Request Response Received", request);
                                                Debug.WriteSuccess(line);
#endif
                                                message = new TesiraResponse(request, null);
                                            }
                                        }
                                        else if (line.StartsWith("+OK "))
                                        {
                                            var request = _requestsAwaiting.TryToDequeue();
                                            if (request != null)
                                            {
#if DEBUG
                                                Debug.WriteInfo("Request Response Received", request);
                                                Debug.WriteSuccess(line);
#endif
                                                message = new TesiraResponse(request, line.Substring(4));
                                            }
                                        }
                                        else if (line.StartsWith("-ERR "))
                                        {
                                            var request = _requestsAwaiting.TryToDequeue();
                                            if (request != null)
                                            {
#if DEBUG
                                                Debug.WriteInfo("Request Response Received", request);
                                                Debug.WriteError(line);
#endif
                                                message = new TesiraErrorResponse(request, line.Substring(5));
                                            }
                                            else
                                            {
                                                Debug.WriteError("Error received and request queue returned null!");
                                                Debug.WriteError(line);
                                                Debug.WriteError("Clearing all queues!");
                                                _requestsSent.Clear();
                                                _requestsAwaiting.Clear();
                                            }
                                        }
                                        else if (line.StartsWith("! "))
                                        {
#if DEBUG
                                            Debug.WriteWarn("Notification Received");
                                            Debug.WriteWarn(line);
#endif
                                            message = new TesiraNotification(line.Substring(2));
                                        }
                                        else if (!_requestsSent.IsEmpty)
                                        {
                                            Debug.WriteWarn("Last sent request", _requestsSent.Peek());

                                            if (_requestsSent.Peek() == line)
                                            {
                                                _requestsAwaiting.Enqueue(_requestsSent.Dequeue());
#if DEBUG
                                                Debug.WriteNormal("Now awaiting for response for command", line);
#endif
                                            }
                                        }

                                        if (message != null && ReceivedData != null && message.Type != TesiraMessageType.ErrorResponse)
                                        {
                                            if (ReceivedData == null)
                                            {
                                                continue;
                                            }
                                            try
                                            {
                                                _timeOutCount = 0;

                                                ReceivedData(this, message);
                                            }
                                            catch (Exception e)
                                            {
                                                CloudLog.Exception(e, "Error calling event handler");
                                            }
                                        }
                                        else if (message != null && message.Type == TesiraMessageType.ErrorResponse)
                                        {
                                            _timeOutCount = 0;

                                            CloudLog.Error("Error message from Tesira: \"{0}\"", message.Message);
                                        }
                                    }
                                }
                            }
#if DEBUG
                            _stopWatch.Stop();
                            Debug.WriteNormal("Time to process: {0} ms", _stopWatch.ElapsedMilliseconds);
                            _stopWatch.Reset();
#endif
                            CrestronEnvironment.AllowOtherAppsToRun();
                        }

                        if (!_programRunning || !_client.IsConnected)
                        {
                            break;
                        }
#if DEBUG
                        //Debug.WriteNormal(Debug.AnsiBlue +
                        //                  string.Format(
                        //                      "Shell Can Write = {0}, _sendQueue = {1}, _requestsSent = {2}, _requestsAwaiting = {3}",
                        //                      _shell.CanWrite, _sendQueue.Count, _requestsSent.Count,
                        //                      _requestsAwaiting.Count) + Debug.AnsiReset);
#endif
                        if (_shell.CanWrite && !_sendQueue.IsEmpty && _requestsSent.IsEmpty && _requestsAwaiting.IsEmpty)
                        {
                            var s = _sendQueue.Dequeue();

                            if (_keepAliveTimer != null && !_keepAliveTimer.Disposed)
                            {
                                _keepAliveTimer.Reset(KeepAliveTime, KeepAliveTime);
                            }
#if DEBUG
                            Debug.WriteWarn("Tesira Tx", s);
#endif
                            _timeOutCount = 0;
                            _shell.WriteLine(s);
                            _requestsSent.Enqueue(s);
                            Thread.Sleep(20);
                        }
                        else if (!_requestsSent.IsEmpty || !_requestsAwaiting.IsEmpty)
                        {
                            _timeOutCount++;

                            if (_timeOutCount > 100)
                            {
                                CloudLog.Warn(
                                    "Error waiting to send requests in {0}, _requestsAwaiting.Count = {1}" +
                                    "and _requestsSent.Count = {2}. Clearing queues!",
                                    GetType().Name, _requestsAwaiting.Count, _requestsSent.Count);
                                _requestsAwaiting.Clear();
                                _requestsSent.Clear();
                                _timeOutCount = 0;
                            }

                            Thread.Sleep(20);
                        }
                    }
                }
                catch (Exception e)
                {
                    CloudLog.Exception(e);
                }

                _loggedIn = false;

                if (_keepAliveTimer != null && !_keepAliveTimer.Disposed)
                {
                    _keepAliveTimer.Stop();
                    _keepAliveTimer.Dispose();
                    _keepAliveTimer = null;
                }

                if (_client != null && _client.IsConnected)
                {
                    _client.Dispose();
                    _client = null;
                }

                CloudLog.Notice("{0} Disconnected from {1}", GetType().Name, _address);
            }
            catch (Exception e)
            {
                CloudLog.Exception(e, "Error in {0}.SshCommsProcess()", GetType().Name);
            }

            ConnectionStatus = ClientStatus.Disconnected;

            if (!_reconnect || !_programRunning)
            {
                return(null);
            }

            Thread.Sleep(1000);

            CloudLog.Notice("Attempting reconnect to Tesira at {0}", _address);
            ConnectionStatus = ClientStatus.AttemptingConnection;

            Connect();

            return(null);
        }