예제 #1
0
파일: ServiceHelper.cs 프로젝트: avs009/gsf
        private void ShowRequestHistory(ClientRequestInfo requestInfo)
        {
            if (requestInfo.Request.Arguments.ContainsHelpRequest)
            {
                StringBuilder helpMessage = new StringBuilder();

                helpMessage.Append("Displays a list of recent requests received from the clients.");
                helpMessage.AppendLine();
                helpMessage.AppendLine();
                helpMessage.Append("   Usage:");
                helpMessage.AppendLine();
                helpMessage.Append("       History -options");
                helpMessage.AppendLine();
                helpMessage.AppendLine();
                helpMessage.Append("   Options:");
                helpMessage.AppendLine();
                helpMessage.Append("       -".PadRight(20));
                helpMessage.Append("Displays this help message");

                UpdateStatus(requestInfo.Sender.ClientID, helpMessage.ToString(), UpdateCrlfCount);
            }
            else
            {
                StringBuilder responseMessage = new StringBuilder();

                responseMessage.AppendFormat("History of requests received by {0}:", Name);
                responseMessage.AppendLine();
                responseMessage.AppendLine();
                responseMessage.Append("Command".PadRight(20));
                responseMessage.Append(' ');
                responseMessage.Append("Received".PadRight(25));
                responseMessage.Append(' ');
                responseMessage.Append("Sender".PadRight(30));
                responseMessage.AppendLine();
                responseMessage.Append(new string('-', 20));
                responseMessage.Append(' ');
                responseMessage.Append(new string('-', 25));
                responseMessage.Append(' ');
                responseMessage.Append(new string('-', 30));

                foreach (ClientRequestInfo historicRequest in m_clientRequestHistory)
                {
                    responseMessage.AppendLine();
                    responseMessage.Append(historicRequest.Request.Command.PadRight(20));
                    responseMessage.Append(' ');
                    responseMessage.Append(historicRequest.ReceivedAt.ToString().PadRight(25));
                    responseMessage.Append(' ');
                    responseMessage.Append(string.Format("{0} from {1}", historicRequest.Sender.UserName, historicRequest.Sender.MachineName).PadRight(30));
                }

                UpdateStatus(requestInfo.Sender.ClientID, responseMessage.ToString(), UpdateCrlfCount);
            }
        }
예제 #2
0
파일: ServiceHelper.cs 프로젝트: avs009/gsf
        private void ShowRequestHelp(ClientRequestInfo requestInfo)
        {
            if (requestInfo.Request.Arguments.ContainsHelpRequest)
            {
                StringBuilder helpMessage = new StringBuilder();

                helpMessage.Append("Displays a list of commands supported by the service.");
                helpMessage.AppendLine();
                helpMessage.AppendLine();
                helpMessage.Append("   Usage:");
                helpMessage.AppendLine();
                helpMessage.Append("       Help -options");
                helpMessage.AppendLine();
                helpMessage.AppendLine();
                helpMessage.Append("   Options:");
                helpMessage.AppendLine();
                helpMessage.Append("       -".PadRight(20));
                helpMessage.Append("Displays this help message");

                UpdateStatus(requestInfo.Sender.ClientID, helpMessage.ToString(), UpdateCrlfCount);
            }
            else
            {
                bool showAdvancedHelp = requestInfo.Request.Arguments.Exists("advanced");

                StringBuilder responseMessage = new StringBuilder();

                responseMessage.AppendFormat("Commands supported by {0}:", Name);
                responseMessage.AppendLine();
                responseMessage.AppendLine();
                responseMessage.Append("Command".PadRight(20));
                responseMessage.Append(' ');
                responseMessage.Append("Description".PadRight(55));
                responseMessage.AppendLine();
                responseMessage.Append(new string('-', 20));
                responseMessage.Append(' ');
                responseMessage.Append(new string('-', 55));

                foreach (ClientRequestHandlerInfo handler in m_clientRequestHandlers)
                {
                    if (handler.IsAdvertised || showAdvancedHelp)
                    {
                        responseMessage.AppendLine();
                        responseMessage.Append(handler.Command.PadRight(20));
                        responseMessage.Append(' ');
                        responseMessage.Append(handler.CommandDescription.PadRight(55));
                    }
                }

                UpdateStatus(requestInfo.Sender.ClientID, responseMessage.ToString(), UpdateCrlfCount);
            }
        }
예제 #3
0
파일: ServiceHelper.cs 프로젝트: avs009/gsf
        private void LoadSchedules(ClientRequestInfo requestInfo)
        {
            if (requestInfo.Request.Arguments.ContainsHelpRequest)
            {
                StringBuilder helpMessage = new StringBuilder();

                helpMessage.Append("Loads all process schedules from the config file.");
                helpMessage.AppendLine();
                helpMessage.AppendLine();
                helpMessage.Append("   Usage:");
                helpMessage.AppendLine();
                helpMessage.Append("       LoadSchedules -options");
                helpMessage.AppendLine();
                helpMessage.AppendLine();
                helpMessage.Append("   Options:");
                helpMessage.AppendLine();
                helpMessage.Append("       -".PadRight(20));
                helpMessage.Append("Displays this help message");
                helpMessage.AppendLine();
                helpMessage.Append("       -list".PadRight(20));
                helpMessage.Append("Displays list of all process schedules");

                UpdateStatus(requestInfo.Sender.ClientID, helpMessage.ToString(), UpdateCrlfCount);
            }
            else
            {
                bool listSchedules = requestInfo.Request.Arguments.Exists("list");

                UpdateStatus(requestInfo.Sender.ClientID, "Attempting to load process schedules from the config file...", UpdateCrlfCount);
                m_scheduler.LoadSettings();
                UpdateStatus(requestInfo.Sender.ClientID, "Successfully loaded process schedules from the config file.", UpdateCrlfCount);

                if (listSchedules)
                {
                    requestInfo.Request = ClientRequest.Parse("Schedules");
                    ShowSchedules(requestInfo);
                }
            }
        }
예제 #4
0
파일: ServiceHelper.cs 프로젝트: avs009/gsf
        private void ShowSettings(ClientRequestInfo requestInfo)
        {
            if (requestInfo.Request.Arguments.ContainsHelpRequest)
            {
                StringBuilder helpMessage = new StringBuilder();

                helpMessage.Append("Displays a list of service settings from the config file.");
                helpMessage.AppendLine();
                helpMessage.AppendLine();
                helpMessage.Append("   Usage:");
                helpMessage.AppendLine();
                helpMessage.Append("       Settings -options");
                helpMessage.AppendLine();
                helpMessage.AppendLine();
                helpMessage.Append("   Options:");
                helpMessage.AppendLine();
                helpMessage.Append("       -?".PadRight(20));
                helpMessage.Append("Displays this help message");
                helpMessage.AppendLine();
                helpMessage.AppendLine();

                UpdateStatus(requestInfo.Sender.ClientID, UpdateType.Information, helpMessage.ToString());
            }
            else
            {
                StringBuilder responseMessage = new StringBuilder();
                responseMessage.AppendFormat("Settings for {0}:", Name);
                responseMessage.AppendLine();
                responseMessage.AppendLine();
                responseMessage.Append("Category".PadRight(20));
                responseMessage.Append(' ');
                responseMessage.Append("Name".PadRight(25));
                responseMessage.Append(' ');
                responseMessage.Append("Value".PadRight(30));
                responseMessage.AppendLine();
                responseMessage.Append(new string('-', 20));
                responseMessage.Append(' ');
                responseMessage.Append(new string('-', 25));
                responseMessage.Append(' ');
                responseMessage.Append(new string('-', 30));

                IPersistSettings typedComponent;
                lock (m_serviceComponents)
                {
                    foreach (object component in m_serviceComponents)
                    {
                        typedComponent = component as IPersistSettings;
                        if (typedComponent != null)
                        {
                            foreach (CategorizedSettingsElement setting in ConfigurationFile.Current.Settings[typedComponent.SettingsCategory])
                            {
                                // Skip encrypted settings for security purpose.
                                if (setting.Encrypted)
                                    continue;

                                responseMessage.AppendLine();
                                responseMessage.Append(typedComponent.SettingsCategory.PadRight(20));
                                responseMessage.Append(' ');
                                responseMessage.Append(setting.Name.PadRight(25));
                                responseMessage.Append(' ');

                                if (!string.IsNullOrEmpty(setting.Value))
                                    responseMessage.Append(setting.Value.PadRight(30));
                                else
                                    responseMessage.Append("[Not Set]".PadRight(30));
                            }
                        }
                    }
                }
                responseMessage.AppendLine();
                responseMessage.AppendLine();

                UpdateStatus(requestInfo.Sender.ClientID, UpdateType.Information, responseMessage.ToString());
            }
        }
예제 #5
0
파일: ServiceHelper.cs 프로젝트: avs009/gsf
        private void StartProcess(ClientRequestInfo requestInfo)
        {
            if (requestInfo.Request.Arguments.ContainsHelpRequest || requestInfo.Request.Arguments.OrderedArgCount < 1)
            {
                bool showAdvancedHelp = requestInfo.Request.Arguments.Exists("advanced");

                StringBuilder helpMessage = new StringBuilder();

                helpMessage.Append("Starts execution of the specified service or system process.");
                helpMessage.AppendLine();
                helpMessage.AppendLine();
                helpMessage.Append("   Usage:");
                helpMessage.AppendLine();
                helpMessage.Append("       Start \"Process Name\" -options");
                helpMessage.AppendLine();
                helpMessage.AppendLine();
                helpMessage.Append("   Options:");
                helpMessage.AppendLine();
                helpMessage.Append("       -".PadRight(20));
                helpMessage.Append("Displays this help message");
                helpMessage.AppendLine();
                helpMessage.Append("       -restart".PadRight(20));
                helpMessage.Append("Aborts the process if executing and start it again");
                helpMessage.AppendLine();
                helpMessage.Append("       -list".PadRight(20));
                helpMessage.Append("Displays list of all service or system processes");
                if (showAdvancedHelp)
                {
                    helpMessage.AppendLine();
                    helpMessage.Append("       -system".PadRight(20));
                    helpMessage.Append("Treats the specified process as a system process");
                }

                UpdateStatus(requestInfo.Sender.ClientID, helpMessage.ToString(), UpdateCrlfCount);
            }
            else
            {
                string processName = requestInfo.Request.Arguments["orderedarg1"];
                bool systemProcess = requestInfo.Request.Arguments.Exists("system");
                bool restartProcess = requestInfo.Request.Arguments.Exists("restart");
                bool listProcesses = requestInfo.Request.Arguments.Exists("list");

                if (restartProcess)
                {
                    requestInfo.Request = ClientRequest.Parse(string.Format("Abort \"{0}\" {1}", processName, systemProcess ? "-system" : ""));
                    AbortProcess(requestInfo);
                }

                if (!systemProcess)
                {
                    ServiceProcess processToStart = GetProcess(processName);

                    if (processToStart != null)
                    {
                        if (processToStart.CurrentState != ProcessState.Processing)
                        {
                            UpdateStatus(requestInfo.Sender.ClientID, string.Format("Attempting to start service process \"{0}\"...", processName), UpdateCrlfCount);
                            processToStart.Start();
                            UpdateStatus(requestInfo.Sender.ClientID, string.Format("Successfully started service process \"{0}\".", processName), UpdateCrlfCount);
                        }
                        else
                        {
                            UpdateStatus(requestInfo.Sender.ClientID, string.Format("Failed to start process \"{0}\". Process is already executing.", processName), UpdateCrlfCount);
                        }
                    }
                    else
                    {
                        UpdateStatus(requestInfo.Sender.ClientID, string.Format("Failed to start service process \"{0}\". Process is not defined.", processName), UpdateCrlfCount);
                    }
                }
                else
                {
                    try
                    {
                        UpdateStatus(requestInfo.Sender.ClientID, string.Format("Attempting to start system process \"{0}\"...", processName), UpdateCrlfCount);
                        Process startedProcess = Process.Start(processName);

                        if (startedProcess != null)
                            UpdateStatus(requestInfo.Sender.ClientID, string.Format("Successfully started system process \"{0}\".", processName), UpdateCrlfCount);
                        else
                            UpdateStatus(requestInfo.Sender.ClientID, string.Format("Failed to start system process \"{0}\".", processName), UpdateCrlfCount);
                    }
                    catch (Exception ex)
                    {
                        UpdateStatus(requestInfo.Sender.ClientID, string.Format("Failed to start system process \"{0}\". {1}.", processName, ex.Message), UpdateCrlfCount);
                    }
                }

                if (listProcesses)
                {
                    requestInfo.Request = ClientRequest.Parse(string.Format("Processes {0}", systemProcess ? "-system" : ""));
                    ShowProcesses(requestInfo);
                }
            }
        }
예제 #6
0
파일: ServiceHelper.cs 프로젝트: avs009/gsf
        private void RescheduleProcess(ClientRequestInfo requestInfo)
        {
            if (requestInfo.Request.Arguments.ContainsHelpRequest || requestInfo.Request.Arguments.OrderedArgCount < 2)
            {
                StringBuilder helpMessage = new StringBuilder();

                helpMessage.Append("Schedules or re-schedules an existing process defined in the service.");
                helpMessage.AppendLine();
                helpMessage.AppendLine();
                helpMessage.Append("   Usage:");
                helpMessage.AppendLine();
                helpMessage.Append("       Reschedule \"Process Name\" \"Schedule Rule\" -options");
                helpMessage.AppendLine();
                helpMessage.AppendLine();
                helpMessage.Append("   Options:");
                helpMessage.AppendLine();
                helpMessage.Append("       -".PadRight(20));
                helpMessage.Append("Displays this help message");
                helpMessage.AppendLine();
                helpMessage.Append("       -save".PadRight(20));
                helpMessage.Append("Saves all process schedules to the config file");
                helpMessage.AppendLine();
                helpMessage.Append("       -list".PadRight(20));
                helpMessage.Append("Displays list of all process schedules");
                helpMessage.AppendLine();
                helpMessage.AppendLine();
                helpMessage.Append("NOTE: The schedule rule uses UNIX crontab syntax which consists of 5 parts (For example, \"* * * * *\"). ");
                helpMessage.Append("Following is a brief description of each of the 5 parts that make up the rule:");
                helpMessage.AppendLine();
                helpMessage.AppendLine();
                helpMessage.Append("   Part 1 - Minute part; value range 0 to 59. ");
                helpMessage.AppendLine();
                helpMessage.Append("   Part 2 - Hour part; value range 0 to 23. ");
                helpMessage.AppendLine();
                helpMessage.Append("   Part 3 - Day of month part; value range 1 to 31. ");
                helpMessage.AppendLine();
                helpMessage.Append("   Part 4 - Month part; value range 1 to 12. ");
                helpMessage.AppendLine();
                helpMessage.Append("   Part 5 - Day of week part; value range 0 to 6 (0 = Sunday). ");
                helpMessage.AppendLine();
                helpMessage.AppendLine();
                helpMessage.Append("Following is a description of valid syntax for all parts of the rule:");
                helpMessage.AppendLine();
                helpMessage.AppendLine();
                helpMessage.Append("   *       - Any value in the range for the date-time part.");
                helpMessage.AppendLine();
                helpMessage.Append("   */n     - Every nth value for the data-time part.");
                helpMessage.AppendLine();
                helpMessage.Append("   n1-n2   - Range of values (inclusive) for the date-time part.");
                helpMessage.AppendLine();
                helpMessage.Append("   n1,n2   - 1 or more specific values for the date-time part.");
                helpMessage.AppendLine();
                helpMessage.AppendLine();
                helpMessage.Append("Examples:");
                helpMessage.AppendLine();
                helpMessage.AppendLine();
                helpMessage.Append("   \"* * * * *\"       - Process executes every minute.");
                helpMessage.AppendLine();
                helpMessage.Append("   \"*/5 * * * *\"     - Process executes every 5 minutes.");
                helpMessage.AppendLine();
                helpMessage.Append("   \"5 * * * *\"       - Process executes 5 past every hour.");
                helpMessage.AppendLine();
                helpMessage.Append("   \"0 0 * * *\"       - Process executes every day at midnight.");
                helpMessage.AppendLine();
                helpMessage.Append("   \"0 0 1 * *\"       - Process executes 1st of every month at midnight.");
                helpMessage.AppendLine();
                helpMessage.Append("   \"0 0 * * 0\"       - Process executes every Sunday at midnight.");
                helpMessage.AppendLine();
                helpMessage.Append("   \"0 0 31 12 *\"     - Process executes on December 31 at midnight.");
                helpMessage.AppendLine();
                helpMessage.Append("   \"5,10 0-2 * * *\"  - Process executes 5 and 10 past hours 12am to 2am.");

                UpdateStatus(requestInfo.Sender.ClientID, helpMessage.ToString(), UpdateCrlfCount);
            }
            else
            {
                string processName = requestInfo.Request.Arguments["orderedarg1"];
                string scheduleRule = requestInfo.Request.Arguments["orderedarg2"];
                bool saveSchedules = requestInfo.Request.Arguments.Exists("save");
                bool listSchedules = requestInfo.Request.Arguments.Exists("list");

                try
                {
                    // Schedule the process if not scheduled or update its schedule if scheduled.
                    UpdateStatus(requestInfo.Sender.ClientID, string.Format("Attempting to schedule process \"{0}\" with rule \"{1}\"...", processName, scheduleRule), UpdateCrlfCount);
                    ScheduleProcess(processName, scheduleRule, true);
                    UpdateStatus(requestInfo.Sender.ClientID, string.Format("Successfully scheduled process \"{0}\" with rule \"{1}\".", processName, scheduleRule), UpdateCrlfCount);

                    if (saveSchedules)
                    {
                        requestInfo.Request = ClientRequest.Parse("SaveSchedules");
                        SaveSchedules(requestInfo);
                    }
                }
                catch (Exception ex)
                {
                    UpdateStatus(requestInfo.Sender.ClientID, string.Format("Failed to schedule process \"{0}\". {1}", processName, ex.Message), UpdateCrlfCount);
                }

                if (listSchedules)
                {
                    requestInfo.Request = ClientRequest.Parse("Schedules");
                    ShowSchedules(requestInfo);
                }
            }
        }
예제 #7
0
파일: ClientHelper.cs 프로젝트: avs009/gsf
        /// <summary>
        /// Returns an <see cref="ClientRequestInfo"/> object for the specified <paramref name="requestCommand"/> that can be used 
        /// to invoke <see cref="ServiceHelper.ClientRequestHandlers"/> manually as if the request was sent by a <see cref="ClientHelper"/> remotely.
        /// </summary>
        /// <param name="requestCommand">Command for which an <see cref="ClientRequestInfo"/> object is to be created.</param>
        /// <returns>An <see cref="ClientRequestInfo"/> object.</returns>
        public static ClientRequestInfo PretendRequest(string requestCommand)
        {
            ClientRequest request = ClientRequest.Parse(requestCommand);
            ClientRequestInfo requestInfo = new ClientRequestInfo(new ClientInfo(), request);

            return requestInfo;
        }
예제 #8
0
파일: ServiceHelper.cs 프로젝트: avs009/gsf
        private void ReloadSettings(ClientRequestInfo requestInfo)
        {
            if (requestInfo.Request.Arguments.ContainsHelpRequest || requestInfo.Request.Arguments.OrderedArgCount < 1)
            {
                StringBuilder helpMessage = new StringBuilder();

                helpMessage.Append("Reloads settings of the component whose settings are saved under the specified category in the config file.");
                helpMessage.AppendLine();
                helpMessage.AppendLine();
                helpMessage.Append("   Usage:");
                helpMessage.AppendLine();
                helpMessage.Append("       ReloadSettings \"Category Name\" -options");
                helpMessage.AppendLine();
                helpMessage.AppendLine();
                helpMessage.Append("   Options:");
                helpMessage.AppendLine();
                helpMessage.Append("       -".PadRight(20));
                helpMessage.Append("Displays this help message");
                helpMessage.AppendLine();
                helpMessage.AppendLine();
                helpMessage.Append("IMPORTANT: Category name must be defined as one of the queryable settings categories in the QueryableSettingsCategories property of ServiceHelper. ");
                helpMessage.Append("Also, category name is case sensitive so it must be the same case as it appears in the settings listing.");

                UpdateStatus(requestInfo.Sender.ClientID, helpMessage.ToString(), UpdateCrlfCount);
            }
            else
            {
                string settingsTarget = null;
                string categoryName = requestInfo.Request.Arguments["orderedarg1"];

                if (m_queryableSettingsCategories.IndexOf(categoryName) >= 0)
                {
                    if (m_settingsCategory == categoryName)
                    {
                        LoadSettings();
                        settingsTarget = categoryName;
                    }
                    else
                    {
                        if (settingsTarget != null)
                        {
                            // Check service components
                            foreach (IServiceComponent component in m_serviceComponents)
                            {
                                IPersistSettings reloadableComponent = component as IPersistSettings;
                                if (reloadableComponent != null && reloadableComponent.SettingsCategory == categoryName)
                                {
                                    reloadableComponent.LoadSettings();
                                    settingsTarget = component.Name;
                                    break;
                                }
                            }
                        }

                        if (settingsTarget != null)
                        {
                            // Check containter components
                            foreach (Component component in Container.Components)
                            {
                                IPersistSettings reloadableComponent = component as IPersistSettings;
                                if (reloadableComponent != null && reloadableComponent.SettingsCategory == categoryName)
                                {
                                    reloadableComponent.LoadSettings();
                                    settingsTarget = component.GetType().Name;
                                    break;
                                }
                            }
                        }
                    }

                    if (!string.IsNullOrEmpty(settingsTarget))
                    {
                        if (settingsTarget == categoryName)
                            UpdateStatus(requestInfo.Sender.ClientID, string.Format("Successfully loaded settings for category \"{1}\".", categoryName), UpdateCrlfCount);
                        else
                            UpdateStatus(requestInfo.Sender.ClientID, string.Format("Successfully loaded settings for component \"{0}\" from category \"{1}\".", settingsTarget, categoryName), UpdateCrlfCount);
                    }
                    else
                    {
                        UpdateStatus(requestInfo.Sender.ClientID, string.Format("Failed to load component settings from category \"{0}\". No corresponding settings category name found.", categoryName), UpdateCrlfCount);
                    }
                }
                else
                {
                    UpdateStatus(requestInfo.Sender.ClientID, string.Format("Failed to load component settings from category \"{0}\". Category is not one of the queryable settings categories.", categoryName), UpdateCrlfCount);
                }
            }
        }
예제 #9
0
파일: ServiceHelper.cs 프로젝트: avs009/gsf
        private void SaveSchedules(ClientRequestInfo requestInfo)
        {
            if (requestInfo.Request.Arguments.ContainsHelpRequest)
            {
                StringBuilder helpMessage = new StringBuilder();

                helpMessage.Append("Saves all process schedules to the config file.");
                helpMessage.AppendLine();
                helpMessage.AppendLine();
                helpMessage.Append("   Usage:");
                helpMessage.AppendLine();
                helpMessage.Append("       SaveSchedules -options");
                helpMessage.AppendLine();
                helpMessage.AppendLine();
                helpMessage.Append("   Options:");
                helpMessage.AppendLine();
                helpMessage.Append("       -?".PadRight(20));
                helpMessage.Append("Displays this help message");
                helpMessage.AppendLine();
                helpMessage.Append("       -list".PadRight(20));
                helpMessage.Append("Displays list of all process schedules");
                helpMessage.AppendLine();
                helpMessage.AppendLine();

                UpdateStatus(requestInfo.Sender.ClientID, UpdateType.Information, helpMessage.ToString());
            }
            else
            {
                bool listSchedules = requestInfo.Request.Arguments.Exists("list");

                UpdateStatus(requestInfo.Sender.ClientID, UpdateType.Information, "Attempting to save process schedules to the config file...\r\n\r\n");
                m_processScheduler.SaveSettings();
                UpdateStatus(requestInfo.Sender.ClientID, UpdateType.Information, "Successfully saved process schedules to the config file.\r\n\r\n");

                if (listSchedules)
                {
                    requestInfo.Request = ClientRequest.Parse("Schedules");
                    ShowSchedules(requestInfo);
                }
            }
        }
예제 #10
0
파일: ServiceHelper.cs 프로젝트: avs009/gsf
        private void RemoteTelnetSession(ClientRequestInfo requestinfo)
        {
            if (m_remoteCommandProcess == null && requestinfo.Request.Arguments.ContainsHelpRequest)
            {
                StringBuilder helpMessage = new StringBuilder();

                helpMessage.Append("Allows for a telnet session to the service server.");
                helpMessage.AppendLine();
                helpMessage.AppendLine();
                helpMessage.Append("   Usage:");
                helpMessage.AppendLine();
                helpMessage.Append("       Telnet -options");
                helpMessage.AppendLine();
                helpMessage.AppendLine();
                helpMessage.Append("   Options:");
                helpMessage.AppendLine();
                helpMessage.Append("       -?".PadRight(20));
                helpMessage.Append("Displays this help message");
                helpMessage.AppendLine();
                helpMessage.Append("       -connect".PadRight(20));
                helpMessage.Append("Establishes a telnet session (requires password)");
                helpMessage.AppendLine();
                helpMessage.Append("       -disconnect".PadRight(20));
                helpMessage.Append("Terminates established telnet session");
                helpMessage.AppendLine();
                helpMessage.AppendLine();

                UpdateStatus(requestinfo.Sender.ClientID, UpdateType.Information, helpMessage.ToString());
            }
            else
            {
                bool connectSession = requestinfo.Request.Arguments.Exists("connect");
                bool disconnectSession = requestinfo.Request.Arguments.Exists("disconnect");

                if (m_remoteCommandProcess == null && connectSession && !string.IsNullOrEmpty(requestinfo.Request.Arguments["connect"]))
                {
                    // User wants to establish a remote command session.
                    string password = requestinfo.Request.Arguments["connect"];

                    if (password == m_telnetSessionPassword)
                    {
                        // Establish remote command session
                        m_remoteCommandProcess = new Process();
                        m_remoteCommandProcess.ErrorDataReceived += RemoteCommandProcess_ErrorDataReceived;
                        m_remoteCommandProcess.OutputDataReceived += RemoteCommandProcess_OutputDataReceived;
                        m_remoteCommandProcess.StartInfo.FileName = "cmd.exe";
                        m_remoteCommandProcess.StartInfo.UseShellExecute = false;
                        m_remoteCommandProcess.StartInfo.RedirectStandardInput = true;
                        m_remoteCommandProcess.StartInfo.RedirectStandardOutput = true;
                        m_remoteCommandProcess.StartInfo.RedirectStandardError = true;
                        m_remoteCommandProcess.Start();
                        m_remoteCommandProcess.BeginOutputReadLine();
                        m_remoteCommandProcess.BeginErrorReadLine();

                        UpdateStatus(UpdateType.Information, "Remote command session established - status updates are suspended.\r\n\r\n");

                        m_remoteCommandClientID = requestinfo.Sender.ClientID;
                        SendResponse(requestinfo.Sender.ClientID, new ServiceResponse("TelnetSession", "Established"));
                    }
                    else
                    {
                        UpdateStatus(requestinfo.Sender.ClientID, UpdateType.Alarm, "Failed to establish remote command session - Password is invalid.\r\n\r\n");
                    }
                }
                else if (string.Compare(requestinfo.Request.Command, "Telnet", true) == 0 && m_remoteCommandProcess != null && disconnectSession)
                {
                    // User wants to terminate an established remote command session.                   
                    m_remoteCommandProcess.ErrorDataReceived -= RemoteCommandProcess_ErrorDataReceived;
                    m_remoteCommandProcess.OutputDataReceived -= RemoteCommandProcess_OutputDataReceived;

                    if (!m_remoteCommandProcess.HasExited)
                        m_remoteCommandProcess.Kill();

                    m_remoteCommandProcess.Dispose();
                    m_remoteCommandProcess = null;

                    m_remoteCommandClientID = Guid.Empty;
                    SendResponse(requestinfo.Sender.ClientID, new ServiceResponse("TelnetSession", "Terminated"));

                    UpdateStatus(UpdateType.Information, "Remote command session terminated - status updates are resumed.\r\n\r\n");
                }
                else if (m_remoteCommandProcess != null)
                {
                    // User has entered commands that must be redirected to the established command session.
                    string input = requestinfo.Request.Command + " " + requestinfo.Request.Arguments.ToString();
                    m_remoteCommandProcess.StandardInput.WriteLine(input);
                }
                else
                {
                    // User has provided insufficient information.
                    requestinfo.Request = ClientRequest.Parse("Telnet /?");
                    RemoteTelnetSession(requestinfo);
                }
            }
        }
예제 #11
0
파일: ServiceHelper.cs 프로젝트: avs009/gsf
        private void StartProcess(ClientRequestInfo requestInfo)
        {
            if (requestInfo.Request.Arguments.ContainsHelpRequest || requestInfo.Request.Arguments.OrderedArgCount < 1)
            {
                bool showAdvancedHelp = requestInfo.Request.Arguments.Exists("advanced");

                StringBuilder helpMessage = new StringBuilder();

                helpMessage.Append("Starts execution of the specified service or system process.");
                helpMessage.AppendLine();
                helpMessage.AppendLine();
                helpMessage.Append("   Usage:");
                helpMessage.AppendLine();
                helpMessage.Append("       Start \"Process Name\" -options");
                helpMessage.AppendLine();
                helpMessage.AppendLine();
                helpMessage.Append("   Options:");
                helpMessage.AppendLine();
                helpMessage.Append("       -?".PadRight(20));
                helpMessage.Append("Displays this help message");
                helpMessage.AppendLine();
                helpMessage.Append("       -args".PadRight(20));
                helpMessage.Append("Arguments to be passed in to the process");
                helpMessage.AppendLine();
                helpMessage.Append("       -restart".PadRight(20));
                helpMessage.Append("Aborts the process if executing and start it again");
                helpMessage.AppendLine();
                helpMessage.Append("       -list".PadRight(20));
                helpMessage.Append("Displays list of all service or system processes");
                if (showAdvancedHelp)
                {
                    helpMessage.AppendLine();
                    helpMessage.Append("       -system".PadRight(20));
                    helpMessage.Append("Treats the specified process as a system process");
                }
                helpMessage.AppendLine();
                helpMessage.AppendLine();

                UpdateStatus(requestInfo.Sender.ClientID, UpdateType.Information, helpMessage.ToString());
            }
            else
            {
                string processName = requestInfo.Request.Arguments["orderedarg1"];
                string processArgs = requestInfo.Request.Arguments["args"];
                bool systemProcess = requestInfo.Request.Arguments.Exists("system");
                bool restartProcess = requestInfo.Request.Arguments.Exists("restart");
                bool listProcesses = requestInfo.Request.Arguments.Exists("list");

                if (restartProcess)
                {
                    requestInfo.Request = ClientRequest.Parse(string.Format("Abort \"{0}\" {1}", processName, systemProcess ? "-system" : ""));
                    AbortProcess(requestInfo);
                }

                if (!systemProcess)
                {
                    ServiceProcess processToStart = FindProcess(processName);

                    if (processToStart != null)
                    {
                        if (processToStart.CurrentState != ServiceProcessState.Processing)
                        {
                            UpdateStatus(requestInfo.Sender.ClientID, UpdateType.Information, "Attempting to start service process \"{0}\"...\r\n\r\n", processName);
                            if (string.IsNullOrEmpty(processArgs))
                            {
                                processToStart.Start();
                            }
                            else
                            {
                                // Prepare the arguments.
                                string[] splitArgs = processArgs.Split(',');
                                Array.ForEach<string>(splitArgs, (string arg) => arg.Trim());

                                // Start the service process.
                                processToStart.Start(splitArgs);
                            }
                            UpdateStatus(requestInfo.Sender.ClientID, UpdateType.Information, "Successfully started service process \"{0}\".\r\n\r\n", processName);
                        }
                        else
                        {
                            UpdateStatus(requestInfo.Sender.ClientID, UpdateType.Alarm, "Failed to start process \"{0}\". Process is already executing.\r\n\r\n", processName);
                        }
                    }
                    else
                    {
                        UpdateStatus(requestInfo.Sender.ClientID, UpdateType.Alarm, "Failed to start service process \"{0}\". Process is not defined.\r\n\r\n", processName);
                    }
                }
                else
                {
                    try
                    {
                        UpdateStatus(requestInfo.Sender.ClientID, UpdateType.Information, "Attempting to start system process \"{0}\"...\r\n\r\n", processName);
                        Process startedProcess = Process.Start(processName, processArgs);

                        if (startedProcess != null)
                            UpdateStatus(requestInfo.Sender.ClientID, UpdateType.Information, "Successfully started system process \"{0}\".\r\n\r\n", processName);
                        else
                            UpdateStatus(requestInfo.Sender.ClientID, UpdateType.Alarm, "Failed to start system process \"{0}\".\r\n\r\n", processName);
                    }
                    catch (Exception ex)
                    {
                        m_errorLogger.Log(ex);
                        UpdateStatus(requestInfo.Sender.ClientID, UpdateType.Alarm, "Failed to start system process \"{0}\". {1}.\r\n\r\n", processName, ex.Message);
                    }
                }

                if (listProcesses)
                {
                    requestInfo.Request = ClientRequest.Parse(string.Format("Processes {0}", systemProcess ? "-system" : ""));
                    ShowProcesses(requestInfo);
                }
            }
        }
예제 #12
0
파일: ServiceHelper.cs 프로젝트: avs009/gsf
        private void UpdateSettings(ClientRequestInfo requestInfo)
        {
            if (requestInfo.Request.Arguments.ContainsHelpRequest || requestInfo.Request.Arguments.OrderedArgCount < 3)
            {
                // We'll display help about the request since we either don't have the required arguments or the user
                // has explicitly requested for the help to be displayed for this request type.
                StringBuilder helpMessage = new StringBuilder();

                helpMessage.Append("Updates the specified setting under the specified category in the config file.");
                helpMessage.AppendLine();
                helpMessage.AppendLine();
                helpMessage.Append("   Usage:");
                helpMessage.AppendLine();
                helpMessage.Append("       UpdateSettings \"Category Name\" \"Setting Name\" \"Setting Value\" -options");
                helpMessage.AppendLine();
                helpMessage.AppendLine();
                helpMessage.Append("   Options:");
                helpMessage.AppendLine();
                helpMessage.Append("       -?".PadRight(20));
                helpMessage.Append("Displays this help message");
                helpMessage.AppendLine();
                helpMessage.Append("       -add".PadRight(20));
                helpMessage.Append("Adds specified setting to the specified category");
                helpMessage.AppendLine();
                helpMessage.Append("       -delete".PadRight(20));
                helpMessage.Append("Deletes specified setting from the specified category");
                helpMessage.AppendLine();
                helpMessage.Append("       -reload".PadRight(20));
                helpMessage.Append("Causes corresponding component to reload settings");
                helpMessage.AppendLine();
                helpMessage.Append("       -list".PadRight(20));
                helpMessage.Append("Displays list all of the queryable settings");
                helpMessage.AppendLine();
                helpMessage.AppendLine();
                helpMessage.Append("IMPORTANT: Only settings under the categories listed by the \"Settings\" command can be updated.");
                helpMessage.AppendLine();
                helpMessage.AppendLine();

                UpdateStatus(requestInfo.Sender.ClientID, UpdateType.Information, helpMessage.ToString());
            }
            else
            {
                string categoryName = requestInfo.Request.Arguments["orderedarg1"];
                string settingName = requestInfo.Request.Arguments["orderedarg2"];
                string settingValue = requestInfo.Request.Arguments["orderedarg3"];
                bool addSetting = requestInfo.Request.Arguments.Exists("add");
                bool deleteSetting = requestInfo.Request.Arguments.Exists("delete");
                bool reloadSettings = requestInfo.Request.Arguments.Exists("reload");
                bool listSettings = requestInfo.Request.Arguments.Exists("list");

                IPersistSettings typedComponent;
                lock (m_serviceComponents)
                {
                    foreach (object component in m_serviceComponents)
                    {
                        typedComponent = component as IPersistSettings;
                        if (typedComponent != null &&
                            string.Compare(categoryName, typedComponent.SettingsCategory, true) == 0)
                        {
                            ConfigurationFile config = ConfigurationFile.Current;
                            CategorizedSettingsElementCollection settings = config.Settings[categoryName];
                            CategorizedSettingsElement setting = settings[settingName];
                            if (addSetting)
                            {
                                // Add new setting.
                                if (setting == null)
                                {
                                    UpdateStatus(requestInfo.Sender.ClientID, UpdateType.Information, "Attempting to add setting \"{0}\" under category \"{1}\"...\r\n\r\n", settingName, categoryName);
                                    settings.Add(settingName, settingValue);
                                    config.Save();
                                    UpdateStatus(requestInfo.Sender.ClientID, UpdateType.Information, "Successfully added setting \"{0}\" under category \"{1}\".\r\n\r\n", settingName, categoryName);
                                }
                                else
                                {
                                    UpdateStatus(requestInfo.Sender.ClientID, UpdateType.Alarm, "Failed to add setting \"{0}\" under category \"{1}\". Setting already exists.\r\n\r\n", settingName, categoryName);
                                    return;
                                }
                            }
                            else if (deleteSetting)
                            {
                                // Delete existing setting.
                                if (setting != null)
                                {
                                    UpdateStatus(requestInfo.Sender.ClientID, UpdateType.Information, "Attempting to delete setting \"{0}\" under category \"{1}\"...\r\n\r\n", settingName, categoryName);
                                    settings.Remove(setting);
                                    config.Save();
                                    UpdateStatus(requestInfo.Sender.ClientID, UpdateType.Information, "Successfully deleted setting \"{0}\" under category \"{1}\".\r\n\r\n", settingName, categoryName);
                                }
                                else
                                {
                                    UpdateStatus(requestInfo.Sender.ClientID, UpdateType.Alarm, "Failed to delete setting \"{0}\" under category \"{1}\". Setting does not exist.\r\n\r\n", settingName, categoryName);
                                    return;
                                }
                            }
                            else
                            {
                                // Update existing setting.
                                if (setting != null)
                                {
                                    UpdateStatus(requestInfo.Sender.ClientID, UpdateType.Information, "Attempting to update setting \"{0}\" under category \"{1}\"...\r\n\r\n", settingName, categoryName);
                                    setting.Value = settingValue;
                                    config.Save();
                                    UpdateStatus(requestInfo.Sender.ClientID, UpdateType.Information, "Successfully updated setting \"{0}\" under category \"{1}\".\r\n\r\n", settingName, categoryName);
                                }
                                else
                                {
                                    UpdateStatus(requestInfo.Sender.ClientID, UpdateType.Alarm, "Failed to update value of setting \"{0}\" under category \"{1}\" . Setting does not exist.\r\n\r\n", settingName, categoryName);
                                    return;
                                }
                            }

                            if (reloadSettings)
                            {
                                // The user has requested to reload settings for all the components.
                                requestInfo.Request = ClientRequest.Parse(string.Format("ReloadSettings {0}", categoryName));
                                ReloadSettings(requestInfo);
                            }

                            if (listSettings)
                            {
                                // The user has requested to list all of the queryable settings.
                                requestInfo.Request = ClientRequest.Parse("Settings");
                                ShowSettings(requestInfo);
                            }

                            return;
                        }
                    }
                }

                UpdateStatus(requestInfo.Sender.ClientID, UpdateType.Alarm, "Failed to update settings under category \"{0}\". No corresponding component exists.\r\n\r\n", categoryName);
            }
        }
예제 #13
0
파일: ServiceHelper.cs 프로젝트: avs009/gsf
        private void ReloadSettings(ClientRequestInfo requestInfo)
        {
            if (requestInfo.Request.Arguments.ContainsHelpRequest || requestInfo.Request.Arguments.OrderedArgCount < 1)
            {
                StringBuilder helpMessage = new StringBuilder();

                helpMessage.Append("Reloads settings of the component whose settings are saved under the specified category in the config file.");
                helpMessage.AppendLine();
                helpMessage.AppendLine();
                helpMessage.Append("   Usage:");
                helpMessage.AppendLine();
                helpMessage.Append("       ReloadSettings \"Category Name\" -options");
                helpMessage.AppendLine();
                helpMessage.AppendLine();
                helpMessage.Append("   Options:");
                helpMessage.AppendLine();
                helpMessage.Append("       -?".PadRight(20));
                helpMessage.Append("Displays this help message");
                helpMessage.AppendLine();
                helpMessage.AppendLine();
                helpMessage.Append("IMPORTANT: Only settings under the categories listed by the \"Settings\" command can be reloaded.");
                helpMessage.AppendLine();
                helpMessage.AppendLine();

                UpdateStatus(requestInfo.Sender.ClientID, UpdateType.Information, helpMessage.ToString());
            }
            else
            {
                string categoryName = requestInfo.Request.Arguments["orderedarg1"];

                IPersistSettings typedComponent;
                lock (m_serviceComponents)
                {
                    foreach (object component in m_serviceComponents)
                    {
                        typedComponent = component as IPersistSettings;
                        if (typedComponent != null &&
                            string.Compare(categoryName, typedComponent.SettingsCategory, true) == 0)
                        {
                            typedComponent.LoadSettings();
                            UpdateStatus(requestInfo.Sender.ClientID, UpdateType.Information, "Successfully loaded settings from category \"{0}\".\r\n\r\n", categoryName);
                            return;
                        }
                    }
                }

                UpdateStatus(requestInfo.Sender.ClientID, UpdateType.Alarm, "Failed to load settings from category \"{0}\". No corresponding component exists.\r\n\r\n", categoryName);
            }
        }
예제 #14
0
파일: ServiceHelper.cs 프로젝트: avs009/gsf
        private void ShowHealthReport(ClientRequestInfo requestInfo)
        {
            if (requestInfo.Request.Arguments.ContainsHelpRequest)
            {
                StringBuilder helpMessage = new StringBuilder();

                helpMessage.Append("Displays a resource utilization report for the service.");
                helpMessage.AppendLine();
                helpMessage.AppendLine();
                helpMessage.Append("   Usage:");
                helpMessage.AppendLine();
                helpMessage.Append("       Health -options");
                helpMessage.AppendLine();
                helpMessage.AppendLine();
                helpMessage.Append("   Options:");
                helpMessage.AppendLine();
                helpMessage.Append("       -".PadRight(20));
                helpMessage.Append("Displays this help message");

                UpdateStatus(requestInfo.Sender.ClientID, helpMessage.ToString(), UpdateCrlfCount);
            }
            else
            {
                if (m_performanceMonitor != null)
                    UpdateStatus(requestInfo.Sender.ClientID, m_performanceMonitor.Status, UpdateCrlfCount);
                else
                    UpdateStatus(requestInfo.Sender.ClientID, "Performance monitor is not available.", UpdateCrlfCount);
            }
        }
예제 #15
0
파일: ServiceHelper.cs 프로젝트: avs009/gsf
        private void m_remotingServer_ReceivedClientData(object sender, EventArgs<IdentifiableItem<Guid, byte[]>> e)
        {
            ClientInfo client = Serialization.GetObject<ClientInfo>(e.Argument.Item);
            ClientRequest request = Serialization.GetObject<ClientRequest>(e.Argument.Item);
            ClientInfo requestSender = GetConnectedClient(e.Argument.Source);

            if (client != null)
            {
                // We've received client information from a recently connected client.
                client.ConnectedAt = DateTime.Now;
                m_connectedClients.Add(client);
                UpdateStatus(string.Format("Remote client connected - {0} from {1}.", client.UserName, client.MachineName), UpdateCrlfCount);
            }
            else if (request != null)
            {
                try
                {
                    ClientRequestInfo requestInfo = new ClientRequestInfo(requestSender, request);

                    if (m_remoteCommandClientID == Guid.Empty || requestSender.ClientID != m_remoteCommandClientID)
                    {
                        // Log the received request.
                        m_clientRequestHistory.Add(requestInfo);

                        // We'll remove old request entries if we've exceeded the limit for request history.
                        if (m_clientRequestHistory.Count > m_requestHistoryLimit)
                            m_clientRequestHistory.RemoveRange(0, (m_clientRequestHistory.Count - m_requestHistoryLimit));

                        // Notify the consumer about the incoming request from client.
                        if (ReceivedClientRequest != null)
                            ReceivedClientRequest(this, new EventArgs<IdentifiableItem<Guid, ClientRequest>>(new IdentifiableItem<Guid, ClientRequest>(requestSender.ClientID, request)));

                        ClientRequestHandlerInfo requestHandler = GetClientRequestHandler(request.Command);

                        if (requestHandler != null)
                            requestHandler.HandlerMethod(requestInfo);
                        else
                            UpdateStatus(requestSender.ClientID, string.Format("Failed to process request \"{0}\". Request is invalid.", request.Command), UpdateCrlfCount);
                    }
                    else
                    {
                        RemoteCommandSession(requestInfo);
                    }
                }
                catch (Exception ex)
                {
                    m_errorLogger.Log(ex);
                    UpdateStatus(requestSender.ClientID, string.Format("Failed to process request \"{0}\". {1}.", request.Command, ex.Message), UpdateCrlfCount);
                }
            }
            else
            {
                UpdateStatus(requestSender.ClientID, "Failed to process request - Request could not be deserialized.", UpdateCrlfCount);
            }
        }
예제 #16
0
파일: ServiceHelper.cs 프로젝트: avs009/gsf
        private void ShowServiceStatus(ClientRequestInfo requestInfo)
        {
            if (requestInfo.Request.Arguments.ContainsHelpRequest)
            {
                StringBuilder helpMessage = new StringBuilder();

                helpMessage.Append("Displays status of this service and its components.");
                helpMessage.AppendLine();
                helpMessage.AppendLine();
                helpMessage.Append("   Usage:");
                helpMessage.AppendLine();
                helpMessage.Append("       Status -options");
                helpMessage.AppendLine();
                helpMessage.AppendLine();
                helpMessage.Append("   Options:");
                helpMessage.AppendLine();
                helpMessage.Append("       -".PadRight(20));
                helpMessage.Append("Displays this help message");

                UpdateStatus(requestInfo.Sender.ClientID, helpMessage.ToString(), UpdateCrlfCount);
            }
            else
            {
                UpdateStatus(requestInfo.Sender.ClientID, Status, UpdateCrlfCount);
            }
        }
예제 #17
0
파일: ServiceHelper.cs 프로젝트: avs009/gsf
        private void ShowClients(ClientRequestInfo requestInfo)
        {
            if (requestInfo.Request.Arguments.ContainsHelpRequest)
            {
                StringBuilder helpMessage = new StringBuilder();

                helpMessage.Append("Displays a list of clients currently connected to the service.");
                helpMessage.AppendLine();
                helpMessage.AppendLine();
                helpMessage.Append("   Usage:");
                helpMessage.AppendLine();
                helpMessage.Append("       Clients -options");
                helpMessage.AppendLine();
                helpMessage.AppendLine();
                helpMessage.Append("   Options:");
                helpMessage.AppendLine();
                helpMessage.Append("       -".PadRight(20));
                helpMessage.Append("Displays this help message");

                UpdateStatus(requestInfo.Sender.ClientID, helpMessage.ToString(), UpdateCrlfCount);
            }
            else
            {
                if (m_connectedClients.Count > 0)
                {
                    // Display info about all of the clients connected to the service.
                    StringBuilder responseMessage = new StringBuilder();

                    responseMessage.AppendFormat("Clients connected to {0}:", Name);
                    responseMessage.AppendLine();
                    responseMessage.AppendLine();
                    responseMessage.Append("Client".PadRight(25));
                    responseMessage.Append(' ');
                    responseMessage.Append("Machine".PadRight(15));
                    responseMessage.Append(' ');
                    responseMessage.Append("User".PadRight(15));
                    responseMessage.Append(' ');
                    responseMessage.Append("Connected".PadRight(20));
                    responseMessage.AppendLine();
                    responseMessage.Append(new string('-', 25));
                    responseMessage.Append(' ');
                    responseMessage.Append(new string('-', 15));
                    responseMessage.Append(' ');
                    responseMessage.Append(new string('-', 15));
                    responseMessage.Append(' ');
                    responseMessage.Append(new string('-', 20));

                    foreach (ClientInfo clientInfo in m_connectedClients)
                    {
                        responseMessage.AppendLine();

                        if (!string.IsNullOrEmpty(clientInfo.ClientName))
                            responseMessage.Append(clientInfo.ClientName.PadRight(25));
                        else
                            responseMessage.Append("[Not Available]".PadRight(25));

                        responseMessage.Append(' ');
                        if (!string.IsNullOrEmpty(clientInfo.MachineName))
                            responseMessage.Append(clientInfo.MachineName.PadRight(15));
                        else
                            responseMessage.Append("[Not Available]".PadRight(15));

                        responseMessage.Append(' ');
                        if (!string.IsNullOrEmpty(clientInfo.UserName))
                            responseMessage.Append(clientInfo.UserName.PadRight(15));
                        else
                            responseMessage.Append("[Not Available]".PadRight(15));

                        responseMessage.Append(' ');
                        responseMessage.Append(clientInfo.ConnectedAt.ToString("MM/dd/yy hh:mm:ss tt").PadRight(20));
                    }

                    UpdateStatus(requestInfo.Sender.ClientID, responseMessage.ToString(), UpdateCrlfCount);
                }
                else
                {
                    UpdateStatus(requestInfo.Sender.ClientID, string.Format("No clients are connected to {0}", Name), UpdateCrlfCount);
                }
            }
        }
예제 #18
0
파일: ServiceHelper.cs 프로젝트: avs009/gsf
        private void UpdateSettings(ClientRequestInfo requestInfo)
        {
            if (requestInfo.Request.Arguments.ContainsHelpRequest || requestInfo.Request.Arguments.OrderedArgCount < 3)
            {
                // We'll display help about the request since we either don't have the required arguments or the user
                // has explicitly requested for the help to be displayed for this request type.
                StringBuilder helpMessage = new StringBuilder();

                helpMessage.Append("Updates the specified setting under the specified category in the config file.");
                helpMessage.AppendLine();
                helpMessage.AppendLine();
                helpMessage.Append("   Usage:");
                helpMessage.AppendLine();
                helpMessage.Append("       UpdateSettings \"Category Name\" \"Setting Name\" \"Setting Value\" -options");
                helpMessage.AppendLine();
                helpMessage.AppendLine();
                helpMessage.Append("   Options:");
                helpMessage.AppendLine();
                helpMessage.Append("       -".PadRight(20));
                helpMessage.Append("Displays this help message");
                helpMessage.AppendLine();
                helpMessage.Append("       -add".PadRight(20));
                helpMessage.Append("Adds specified setting to the specified category");
                helpMessage.AppendLine();
                helpMessage.Append("       -delete".PadRight(20));
                helpMessage.Append("Deletes specified setting from the specified category");
                helpMessage.AppendLine();
                helpMessage.Append("       -reload".PadRight(20));
                helpMessage.Append("Causes corresponding component to reload settings");
                helpMessage.AppendLine();
                helpMessage.Append("       -list".PadRight(20));
                helpMessage.Append("Displays list all of the queryable settings");
                helpMessage.AppendLine();
                helpMessage.AppendLine();
                helpMessage.Append("IMPORTANT: Category name must be defined as one of the queryable settings categories in the QueryableSettingsCategories property of ServiceHelper. ");
                helpMessage.Append("Also, category and setting names are case sensitive so they must be the same case as they appears in the settings listing.");

                UpdateStatus(requestInfo.Sender.ClientID, helpMessage.ToString(), UpdateCrlfCount);
            }
            else
            {
                string categoryName = requestInfo.Request.Arguments["orderedarg1"];
                string settingName = requestInfo.Request.Arguments["orderedarg2"];
                string settingValue = requestInfo.Request.Arguments["orderedarg3"];
                bool addSetting = requestInfo.Request.Arguments.Exists("add");
                bool deleteSetting = requestInfo.Request.Arguments.Exists("delete");
                bool reloadSettings = requestInfo.Request.Arguments.Exists("reload");
                bool listSettings = requestInfo.Request.Arguments.Exists("list");

                if (m_queryableSettingsCategories.IndexOf(categoryName) >= 0)
                {
                    CategorizedSettingsElementCollection settings = ConfigurationFile.Current.Settings[categoryName];
                    CategorizedSettingsElement setting;

                    if (settings != null)
                    {
                        // The specified category is one of the defined queryable categories.
                        if (true == addSetting)
                        {
                            UpdateStatus(requestInfo.Sender.ClientID, string.Format("Attempting to add setting \"{0}\" under category \"{1}\"...", settingName, categoryName), UpdateCrlfCount);
                            settings.Add(settingName, settingValue);
                            ConfigurationFile.Current.Save();
                            UpdateStatus(requestInfo.Sender.ClientID, string.Format("Successfully added setting \"{0}\" under category \"{1}\".", settingName, categoryName), UpdateCrlfCount);
                        }
                        else if (true == deleteSetting)
                        {
                            setting = settings[settingName];
                            if (setting != null)
                            {
                                UpdateStatus(requestInfo.Sender.ClientID, string.Format("Attempting to delete setting \"{0}\" under category \"{1}\"...", settingName, categoryName), UpdateCrlfCount);
                                settings.Remove(setting);
                                ConfigurationFile.Current.Save();
                                UpdateStatus(requestInfo.Sender.ClientID, string.Format("Successfully deleted setting \"{0}\" under category \"{1}\".", settingName, categoryName), UpdateCrlfCount);
                            }
                            else
                            {
                                UpdateStatus(requestInfo.Sender.ClientID, string.Format("Failed to delete setting \"{0}\" under category \"{1}\". Setting does not exist.", settingName, categoryName), UpdateCrlfCount);
                            }
                        }
                        else
                        {
                            setting = settings[settingName];
                            if (setting != null)
                            {
                                // The requested setting does exist under the specified category.
                                UpdateStatus(requestInfo.Sender.ClientID, string.Format("Attempting to update setting \"{0}\" under category \"{1}\"...", settingName, categoryName), UpdateCrlfCount);
                                setting.Value = settingValue;
                                ConfigurationFile.Current.Save();
                                UpdateStatus(requestInfo.Sender.ClientID, string.Format("Successfully updated setting \"{0}\" under category \"{1}\".", settingName, categoryName), UpdateCrlfCount);
                            }
                            else
                            {
                                // The requested setting does not exist under the specified category.
                                UpdateStatus(requestInfo.Sender.ClientID, string.Format("Failed to update value of setting \"{0}\" under category \"{1}\" . Setting does not exist.", settingName, categoryName), UpdateCrlfCount);
                            }
                        }

                        if (reloadSettings)
                        {
                            // The user has requested to reload settings for all the components.
                            requestInfo.Request = ClientRequest.Parse(string.Format("ReloadSettings {0}", categoryName));
                            ReloadSettings(requestInfo);
                        }

                        if (listSettings)
                        {
                            // The user has requested to list all of the queryable settings.
                            requestInfo.Request = ClientRequest.Parse("Settings");
                            ShowSettings(requestInfo);
                        }
                    }
                    else
                    {
                        // The specified category does not exist.
                        UpdateStatus(requestInfo.Sender.ClientID, string.Format("Failed to update value of setting \"{0}\" under category \"{1}\". Category does not exist.", settingName, categoryName), UpdateCrlfCount);
                    }
                }
                else
                {
                    // The specified category is not one of the defined queryable categories.
                    UpdateStatus(requestInfo.Sender.ClientID, string.Format("Failed to update value of setting \"{0}\" under category \"{1}\". Category is not one of the queryable categories.", settingName, categoryName), UpdateCrlfCount);
                }
            }
        }
예제 #19
0
파일: ServiceHelper.cs 프로젝트: avs009/gsf
        private void ShowSettings(ClientRequestInfo requestInfo)
        {
            if (requestInfo.Request.Arguments.ContainsHelpRequest)
            {
                StringBuilder helpMessage = new StringBuilder();

                helpMessage.Append("Displays a list of queryable settings of the service from the config file.");
                helpMessage.AppendLine();
                helpMessage.AppendLine();
                helpMessage.Append("   Usage:");
                helpMessage.AppendLine();
                helpMessage.Append("       Settings -options");
                helpMessage.AppendLine();
                helpMessage.AppendLine();
                helpMessage.Append("   Options:");
                helpMessage.AppendLine();
                helpMessage.Append("       -".PadRight(20));
                helpMessage.Append("Displays this help message");

                UpdateStatus(requestInfo.Sender.ClientID, helpMessage.ToString(), UpdateCrlfCount);
            }
            else
            {
                string[] settingsCategories = m_queryableSettingsCategories.Replace(" ", "").Split(',');

                if (settingsCategories.Length > 0)
                {
                    // Display info about all of the queryable settings defined in the service.
                    StringBuilder responseMessage = new StringBuilder();

                    responseMessage.AppendFormat("Queryable settings of {0}:", Name);
                    responseMessage.AppendLine();
                    responseMessage.AppendLine();
                    responseMessage.Append("Category".PadRight(25));
                    responseMessage.Append(' ');
                    responseMessage.Append("Name".PadRight(20));
                    responseMessage.Append(' ');
                    responseMessage.Append("Value".PadRight(30));
                    responseMessage.AppendLine();
                    responseMessage.Append(new string('-', 25));
                    responseMessage.Append(' ');
                    responseMessage.Append(new string('-', 20));
                    responseMessage.Append(' ');
                    responseMessage.Append(new string('-', 30));

                    foreach (string category in settingsCategories)
                    {
                        foreach (CategorizedSettingsElement setting in ConfigurationFile.Current.Settings[category])
                        {
                            responseMessage.AppendLine();
                            responseMessage.Append(category.PadRight(25));
                            responseMessage.Append(' ');
                            responseMessage.Append(setting.Name.PadRight(20));
                            responseMessage.Append(' ');

                            if (!string.IsNullOrEmpty(setting.Value))
                                responseMessage.Append(setting.Value.PadRight(30));
                            else
                                responseMessage.Append("[Not Set]".PadRight(30));
                        }
                    }

                    UpdateStatus(requestInfo.Sender.ClientID, responseMessage.ToString(), UpdateCrlfCount);
                }
                else
                {
                    // No queryable settings are defined in the service.
                    UpdateStatus(requestInfo.Sender.ClientID, string.Format("No queryable settings are defined in {0}.", Name), UpdateCrlfCount);
                }
            }
        }
예제 #20
0
파일: ServiceHelper.cs 프로젝트: avs009/gsf
        private void AbortProcess(ClientRequestInfo requestInfo)
        {
            if (requestInfo.Request.Arguments.ContainsHelpRequest || requestInfo.Request.Arguments.OrderedArgCount < 1)
            {
                bool showAdvancedHelp = requestInfo.Request.Arguments.Exists("advanced");

                StringBuilder helpMessage = new StringBuilder();

                helpMessage.Append("Aborts the specified service or system process if executing.");
                helpMessage.AppendLine();
                helpMessage.AppendLine();
                helpMessage.Append("   Usage:");
                helpMessage.AppendLine();
                helpMessage.Append("       Abort \"Process Name\" -options");
                helpMessage.AppendLine();
                helpMessage.AppendLine();
                helpMessage.Append("   Options:");
                helpMessage.AppendLine();
                helpMessage.Append("       -".PadRight(20));
                helpMessage.Append("Displays this help message");
                helpMessage.AppendLine();
                helpMessage.Append("       -list".PadRight(20));
                helpMessage.Append("Displays list of all service or system processes");

                if (showAdvancedHelp)
                {
                    helpMessage.AppendLine();
                    helpMessage.Append("       -system".PadRight(20));
                    helpMessage.Append("Treats the specified process as a system process");
                    helpMessage.AppendLine();
                    helpMessage.AppendLine();
                    helpMessage.Append("NOTE: Specify process name of \"Me\" to kill current service process. ");
                }

                UpdateStatus(requestInfo.Sender.ClientID, helpMessage.ToString(), UpdateCrlfCount);
            }
            else
            {
                string processName = requestInfo.Request.Arguments["orderedarg1"];
                bool systemProcess = requestInfo.Request.Arguments.Exists("system");
                bool listProcesses = requestInfo.Request.Arguments.Exists("list");

                if (!systemProcess)
                {
                    ServiceProcess processToAbort = GetProcess(processName);

                    if (processToAbort != null)
                    {
                        if (processToAbort.CurrentState == ProcessState.Processing)
                        {
                            UpdateStatus(requestInfo.Sender.ClientID, string.Format("Attempting to abort service process \"{0}\"...", processName), UpdateCrlfCount);
                            processToAbort.Abort();
                            UpdateStatus(requestInfo.Sender.ClientID, string.Format("Successfully aborted service process \"{0}\".", processName), UpdateCrlfCount);
                        }
                        else
                        {
                            UpdateStatus(requestInfo.Sender.ClientID, string.Format("Failed to abort service process \"{0}\". Process is not executing.", processName), UpdateCrlfCount);
                        }
                    }
                    else
                    {
                        UpdateStatus(requestInfo.Sender.ClientID, string.Format("Failed to abort service process \"{0}\". Process is not defined.", processName), UpdateCrlfCount);
                    }
                }
                else
                {
                    Process processToAbort = null;

                    if (string.Compare(processName, "Me", true) == 0)
                    {
                        processName = Process.GetCurrentProcess().ProcessName;
                    }

                    foreach (Process process in Process.GetProcessesByName(processName))
                    {
                        // Lookup for the system process by name.
                        processToAbort = process;
                        break;
                    }

                    if (processToAbort == null)
                    {
                        int processID;

                        if (int.TryParse(processName, out processID) && processID > 0)
                        {
                            processToAbort = Process.GetProcessById(processID);
                            processName = processToAbort.ProcessName;
                        }
                    }

                    if (processToAbort != null)
                    {
                        try
                        {
                            UpdateStatus(requestInfo.Sender.ClientID, string.Format("Attempting to abort system process \"{0}\"...", processName), UpdateCrlfCount);
                            processToAbort.Kill();
                            if (processToAbort.WaitForExit(10000))
                            {
                                UpdateStatus(requestInfo.Sender.ClientID, string.Format("Successfully aborted system process \"{0}\".", processName), UpdateCrlfCount);
                            }
                            else
                            {
                                UpdateStatus(requestInfo.Sender.ClientID, string.Format("Failed to abort system process \"{0}\". Process not responding.", processName), UpdateCrlfCount);
                            }
                        }
                        catch (Exception ex)
                        {
                            UpdateStatus(requestInfo.Sender.ClientID, string.Format("Failed to abort system process \"{0}\". {1}.", processName, ex.Message), UpdateCrlfCount);
                        }
                    }
                    else
                    {
                        UpdateStatus(requestInfo.Sender.ClientID, string.Format("Failed to abort system process \"{0}\". Process is not running.", processName), UpdateCrlfCount);
                    }
                }

                if (listProcesses)
                {
                    requestInfo.Request = ClientRequest.Parse(string.Format("Processes {0}", systemProcess ? "-system" : ""));
                    ShowProcesses(requestInfo);
                }
            }
        }
예제 #21
0
파일: ServiceHelper.cs 프로젝트: avs009/gsf
        private void ShowProcesses(ClientRequestInfo requestInfo)
        {
            if (requestInfo.Request.Arguments.ContainsHelpRequest)
            {
                bool showAdvancedHelp = requestInfo.Request.Arguments.Exists("advanced");

                StringBuilder helpMessage = new StringBuilder();

                helpMessage.Append("Displays a list of defined service processes or running system processes.");
                helpMessage.AppendLine();
                helpMessage.AppendLine();
                helpMessage.Append("   Usage:");
                helpMessage.AppendLine();
                helpMessage.Append("       Processes -options");
                helpMessage.AppendLine();
                helpMessage.AppendLine();
                helpMessage.Append("   Options:");
                helpMessage.AppendLine();
                helpMessage.Append("       -".PadRight(20));
                helpMessage.Append("Displays this help message");

                if (showAdvancedHelp)
                {
                    helpMessage.AppendLine();
                    helpMessage.Append("       -system".PadRight(20));
                    helpMessage.Append("Displays system processes instead of service processes");
                }

                UpdateStatus(requestInfo.Sender.ClientID, helpMessage.ToString(), UpdateCrlfCount);
            }
            else
            {
                bool listSystemProcesses = requestInfo.Request.Arguments.Exists("system");

                if (!listSystemProcesses)
                {
                    if (m_processes.Count > 0)
                    {
                        // Display info about all the processes defined in the service.
                        StringBuilder responseMessage = new StringBuilder();

                        responseMessage.AppendFormat("Processes defined in {0}:", Name);
                        responseMessage.AppendLine();
                        responseMessage.AppendLine();
                        responseMessage.Append("Name".PadRight(20));
                        responseMessage.Append(' ');
                        responseMessage.Append("State".PadRight(15));
                        responseMessage.Append(' ');
                        responseMessage.Append("Last Exec. Start".PadRight(20));
                        responseMessage.Append(' ');
                        responseMessage.Append("Last Exec. Stop".PadRight(20));
                        responseMessage.AppendLine();
                        responseMessage.Append(new string('-', 20));
                        responseMessage.Append(' ');
                        responseMessage.Append(new string('-', 15));
                        responseMessage.Append(' ');
                        responseMessage.Append(new string('-', 20));
                        responseMessage.Append(' ');
                        responseMessage.Append(new string('-', 20));

                        foreach (ServiceProcess process in m_processes)
                        {
                            responseMessage.AppendLine();
                            responseMessage.Append(process.Name.PadRight(20));
                            responseMessage.Append(' ');
                            responseMessage.Append(process.CurrentState.ToString().PadRight(15));
                            responseMessage.Append(' ');

                            if (process.ExecutionStartTime != DateTime.MinValue)
                                responseMessage.Append(process.ExecutionStartTime.ToString("MM/dd/yy hh:mm:ss tt").PadRight(20));
                            else
                                responseMessage.Append("[Not Executed]".PadRight(20));

                            responseMessage.Append(' ');

                            if (process.ExecutionStopTime != DateTime.MinValue)
                            {
                                responseMessage.Append(process.ExecutionStopTime.ToString("MM/dd/yy hh:mm:ss tt").PadRight(20));
                            }
                            else
                            {
                                if (process.ExecutionStartTime != DateTime.MinValue)
                                    responseMessage.Append("[Executing]".PadRight(20));
                                else
                                    responseMessage.Append("[Not Executed]".PadRight(20));
                            }
                        }

                        UpdateStatus(requestInfo.Sender.ClientID, responseMessage.ToString(), UpdateCrlfCount);
                    }
                    else
                    {
                        // No processes defined in the service to be displayed.
                        UpdateStatus(requestInfo.Sender.ClientID, string.Format("No processes are defined in {0}.", Name), UpdateCrlfCount);
                    }
                }
                else
                {
                    // We enumerate "system" processes when -system parameter is specified
                    StringBuilder responseMessage = new StringBuilder();

                    responseMessage.AppendFormat("Processes running on {0}:", Environment.MachineName);
                    responseMessage.AppendLine();
                    responseMessage.AppendLine();
                    responseMessage.Append("ID".PadRight(5));
                    responseMessage.Append(' ');
                    responseMessage.Append("Name".PadRight(25));
                    responseMessage.Append(' ');
                    responseMessage.Append("Priority".PadRight(15));
                    responseMessage.Append(' ');
                    responseMessage.Append("Responding".PadRight(10));
                    responseMessage.Append(' ');
                    responseMessage.Append("Start Time".PadRight(20));
                    responseMessage.AppendLine();
                    responseMessage.Append(new string('-', 5));
                    responseMessage.Append(' ');
                    responseMessage.Append(new string('-', 25));
                    responseMessage.Append(' ');
                    responseMessage.Append(new string('-', 15));
                    responseMessage.Append(' ');
                    responseMessage.Append(new string('-', 10));
                    responseMessage.Append(' ');
                    responseMessage.Append(new string('-', 20));

                    foreach (Process process in Process.GetProcesses())
                    {
                        try
                        {
                            responseMessage.Append(process.StartInfo.UserName);
                            responseMessage.AppendLine();
                            responseMessage.Append(process.Id.ToString().PadRight(5));
                            responseMessage.Append(' ');
                            responseMessage.Append(process.ProcessName.PadRight(25));
                            responseMessage.Append(' ');
                            responseMessage.Append(process.PriorityClass.ToString().PadRight(15));
                            responseMessage.Append(' ');
                            responseMessage.Append((process.Responding ? "Yes" : "No").PadRight(10));
                            responseMessage.Append(' ');
                            responseMessage.Append(process.StartTime.ToString("MM/dd/yy hh:mm:ss tt").PadRight(20));
                        }
                        catch
                        {
                        }
                    }

                    UpdateStatus(requestInfo.Sender.ClientID, responseMessage.ToString(), UpdateCrlfCount);
                }
            }
        }
예제 #22
0
파일: ServiceHelper.cs 프로젝트: avs009/gsf
        private void UnscheduleProcess(ClientRequestInfo requestInfo)
        {
            if (requestInfo.Request.Arguments.ContainsHelpRequest || requestInfo.Request.Arguments.OrderedArgCount < 1)
            {
                StringBuilder helpMessage = new StringBuilder();

                helpMessage.Append("Unschedules a scheduled process defined in the service.");
                helpMessage.AppendLine();
                helpMessage.AppendLine();
                helpMessage.Append("   Usage:");
                helpMessage.AppendLine();
                helpMessage.Append("       Unschedule \"Process Name\" -options");
                helpMessage.AppendLine();
                helpMessage.AppendLine();
                helpMessage.Append("   Options:");
                helpMessage.AppendLine();
                helpMessage.Append("       -".PadRight(20));
                helpMessage.Append("Displays this help message");
                helpMessage.AppendLine();
                helpMessage.Append("       -save".PadRight(20));
                helpMessage.Append("Saves all process schedules to the config file");
                helpMessage.AppendLine();
                helpMessage.Append("       -list".PadRight(20));
                helpMessage.Append("Displays list of all process schedules");

                UpdateStatus(requestInfo.Sender.ClientID, helpMessage.ToString(), UpdateCrlfCount);
            }
            else
            {
                string processName = requestInfo.Request.Arguments["orderedarg1"];
                bool saveSchedules = requestInfo.Request.Arguments.Exists("save");
                bool listSchedules = requestInfo.Request.Arguments.Exists("list");

                Schedule scheduleToRemove = m_scheduler.GetSchedule(processName);

                if (scheduleToRemove != null)
                {
                    UpdateStatus(requestInfo.Sender.ClientID, string.Format("Attempting to unschedule process \"{0}\"...", processName), UpdateCrlfCount);
                    m_scheduler.Schedules.Remove(scheduleToRemove);
                    UpdateStatus(requestInfo.Sender.ClientID, string.Format("Successfully unscheduled process \"{0}\".", processName), UpdateCrlfCount);

                    if (saveSchedules)
                    {
                        requestInfo.Request = ClientRequest.Parse("SaveSchedules");
                        SaveSchedules(requestInfo);
                    }
                }
                else
                {
                    UpdateStatus(requestInfo.Sender.ClientID, string.Format("Failed to unschedule process \"{0}\". Process is not scheduled.", null), UpdateCrlfCount);
                }

                if (listSchedules)
                {
                    requestInfo.Request = ClientRequest.Parse("Schedules");
                    ShowSchedules(requestInfo);
                }
            }
        }
예제 #23
0
파일: ServiceHelper.cs 프로젝트: avs009/gsf
        private void ShowSchedules(ClientRequestInfo requestInfo)
        {
            if (requestInfo.Request.Arguments.ContainsHelpRequest)
            {
                StringBuilder helpMessage = new StringBuilder();

                helpMessage.Append("Displays a list of schedules for processes defined in the service.");
                helpMessage.AppendLine();
                helpMessage.AppendLine();
                helpMessage.Append("   Usage:");
                helpMessage.AppendLine();
                helpMessage.Append("       Schedules -options");
                helpMessage.AppendLine();
                helpMessage.AppendLine();
                helpMessage.Append("   Options:");
                helpMessage.AppendLine();
                helpMessage.Append("       -".PadRight(20));
                helpMessage.Append("Displays this help message");

                UpdateStatus(requestInfo.Sender.ClientID, helpMessage.ToString(), UpdateCrlfCount);
            }
            else
            {
                if (m_scheduler.Schedules.Count > 0)
                {
                    // Display info about all the process schedules defined in the service.
                    StringBuilder responseMessage = new StringBuilder();

                    responseMessage.AppendFormat("Process schedules defined in {0}:", Name);
                    responseMessage.AppendLine();
                    responseMessage.AppendLine();
                    responseMessage.Append("Name".PadRight(20));
                    responseMessage.Append(' ');
                    responseMessage.Append("Rule".PadRight(20));
                    responseMessage.Append(' ');
                    responseMessage.Append("Last Due".PadRight(30));
                    responseMessage.AppendLine();
                    responseMessage.Append(new string('-', 20));
                    responseMessage.Append(' ');
                    responseMessage.Append(new string('-', 20));
                    responseMessage.Append(' ');
                    responseMessage.Append(new string('-', 30));

                    foreach (Schedule schedule in m_scheduler.Schedules)
                    {
                        responseMessage.AppendLine();
                        responseMessage.Append(schedule.Name.PadRight(20));
                        responseMessage.Append(' ');
                        responseMessage.Append(schedule.Rule.PadRight(20));
                        responseMessage.Append(' ');

                        if (schedule.LastDueAt != DateTime.MinValue)
                            responseMessage.Append(schedule.LastDueAt.ToString().PadRight(30));
                        else
                            responseMessage.Append("[Never]".PadRight(30));
                    }

                    UpdateStatus(requestInfo.Sender.ClientID, responseMessage.ToString(), UpdateCrlfCount);
                }
                else
                {
                    UpdateStatus(requestInfo.Sender.ClientID, string.Format("No process schedules are defined in {0}.", Name), UpdateCrlfCount);
                }
            }
        }
예제 #24
0
파일: ServiceHelper.cs 프로젝트: avs009/gsf
        private void RemoteCommandSession(ClientRequestInfo requestinfo)
        {
            if (m_remoteCommandProcess == null && requestinfo.Request.Arguments.ContainsHelpRequest)
            {
                StringBuilder helpMessage = new StringBuilder();

                helpMessage.Append("Allows for a telnet-like remote command session.");
                helpMessage.AppendLine();
                helpMessage.AppendLine();
                helpMessage.Append("   Usage:");
                helpMessage.AppendLine();
                helpMessage.Append("       Command -options");
                helpMessage.AppendLine();
                helpMessage.AppendLine();
                helpMessage.Append("   Options:");
                helpMessage.AppendLine();
                helpMessage.Append("       -".PadRight(20));
                helpMessage.Append("Displays this help message");
                helpMessage.AppendLine();
                helpMessage.Append("       -connect".PadRight(20));
                helpMessage.Append("Established a remote command session");
                helpMessage.AppendLine();
                helpMessage.Append("       -disconnect".PadRight(20));
                helpMessage.Append("Terminates established remote command session");
                helpMessage.AppendLine();
                helpMessage.Append("       -password=\"Command Session Password\"".PadRight(20));
                helpMessage.Append("Password required to establish a remote command session");

                UpdateStatus(requestinfo.Sender.ClientID, helpMessage.ToString(), UpdateCrlfCount);
            }
            else
            {
                bool connectSession = requestinfo.Request.Arguments.Exists("connect");
                bool disconnectSession = requestinfo.Request.Arguments.Exists("disconnect");
                bool passwordProvided = requestinfo.Request.Arguments.Exists("password");

                if (string.Compare(requestinfo.Request.Command, "Command", true) == 0 && m_remoteCommandProcess == null && connectSession && passwordProvided)
                {
                    // User wants to establish a remote command session.
                    string password = requestinfo.Request.Arguments["password"];

                    if (password == m_pursip)
                    {
                        // Establish remote command session
                        m_remoteCommandProcess = new Process();
                        m_remoteCommandProcess.ErrorDataReceived += m_remoteCommandProcess_ErrorDataReceived;
                        m_remoteCommandProcess.OutputDataReceived += m_remoteCommandProcess_OutputDataReceived;
                        m_remoteCommandProcess.StartInfo.FileName = "cmd.exe";
                        m_remoteCommandProcess.StartInfo.UseShellExecute = false;
                        m_remoteCommandProcess.StartInfo.RedirectStandardInput = true;
                        m_remoteCommandProcess.StartInfo.RedirectStandardOutput = true;
                        m_remoteCommandProcess.StartInfo.RedirectStandardError = true;
                        m_remoteCommandProcess.Start();
                        m_remoteCommandProcess.BeginOutputReadLine();
                        m_remoteCommandProcess.BeginErrorReadLine();

                        m_remoteCommandClientID = requestinfo.Sender.ClientID;

                        UpdateStatus(requestinfo.Sender.ClientID, "Remote command session established - all entry will now be redirected to command session.", UpdateCrlfCount);

                        SendResponse(requestinfo.Sender.ClientID, new ServiceResponse("CommandSession", "Established"));
                    }
                    else
                    {
                        UpdateStatus(requestinfo.Sender.ClientID, "Failed to establish remote command session - Password is invalid.", UpdateCrlfCount);
                    }
                }
                else if (string.Compare(requestinfo.Request.Command, "Command", true) == 0 && m_remoteCommandProcess != null && disconnectSession)
                {
                    // User wants to terminate an established remote command session.                   
                    m_remoteCommandProcess.ErrorDataReceived -= m_remoteCommandProcess_ErrorDataReceived;
                    m_remoteCommandProcess.OutputDataReceived -= m_remoteCommandProcess_OutputDataReceived;
                    
                    if (!m_remoteCommandProcess.HasExited)
                        m_remoteCommandProcess.Kill();

                    m_remoteCommandProcess.Dispose();
                    m_remoteCommandProcess = null;
                    
                    m_remoteCommandClientID = Guid.Empty;

                    UpdateStatus(requestinfo.Sender.ClientID, "Remote command session terminated - all entry will now be redirected back to service session.", UpdateCrlfCount);

                    SendResponse(requestinfo.Sender.ClientID, new ServiceResponse("CommandSession", "Terminated"));
                }
                else if (m_remoteCommandProcess != null)
                {
                    // User has entered commands that must be redirected to the established command session.
                    string input = requestinfo.Request.Command + " " + requestinfo.Request.Arguments.ToString();
                    m_remoteCommandProcess.StandardInput.WriteLine(input);
                }
                else
                {
                    // User has provided insufficient information.
                    requestinfo.Request = ClientRequest.Parse("Command /");
                    RemoteCommandSession(requestinfo);
                }
            }
        }
예제 #25
0
파일: ServiceHelper.cs 프로젝트: avs009/gsf
        private void RemotingServer_ReceiveClientDataComplete(object sender, EventArgs<Guid, byte[], int> e)
        {
            // Set thread principal to current windows principal.
            Thread.CurrentPrincipal = new WindowsPrincipal(WindowsIdentity.GetCurrent());

            ClientInfo requestSender = FindConnectedClient(e.Argument1);
            if (requestSender == null)
            {
                // First message from a remote client should be its info.
                ClientInfo client = null;
                Serialization.TryGetObject<ClientInfo>(e.Argument2.BlockCopy(0, e.Argument3), out client);
                try
                {
                    if (client != null)
                    {
                        client.ClientID = e.Argument1;
                        client.ConnectedAt = DateTime.Now;

                        // Engage security for the remote client connection if configured.
                        if (!m_secureRemoteInteractions || (m_secureRemoteInteractions && VerifySecurity(client)))
                        {
                            lock (m_remoteClients)
                            {
                                m_remoteClients.Add(client);
                            }
                            SendAuthenticationSuccessResponse(client.ClientID);
                            UpdateStatus(UpdateType.Information, "Remote client connected - {0} from {1}.\r\n\r\n", client.ClientUser.Identity.Name, client.MachineName);
                        }
                        else
                        {
                            throw new SecurityException(string.Format("Authentication failed for user '{0}'", Thread.CurrentPrincipal.Identity.Name));
                        }
                    }
                    else
                    {
                        // Required client information is missing.
                        throw new SecurityException("Remote client failed to transmit the required information");
                    }
                }
                catch (Exception ex)
                {
                    try
                    {
                        SendResponse(e.Argument1, new ServiceResponse("AuthenticationFailure"));
                        m_remotingServer.DisconnectOne(e.Argument1);

                        UpdateStatus(UpdateType.Warning, "Remote client connection rejected - {0} from {1}.\r\n\r\n", client.ClientUser.Identity.Name, client.MachineName);
                        m_errorLogger.Log(ex);
                    }
                    catch
                    {
                    }
                }
            }
            else
            {
                // All subsequest messages from a remote client would be requests.
                ClientRequest request = null;
                Serialization.TryGetObject<ClientRequest>(e.Argument2.BlockCopy(0, e.Argument3), out request);
                if (request != null)
                {
                    try
                    {
                        ClientRequestInfo requestInfo = new ClientRequestInfo(requestSender, request);

                        if (m_remoteCommandClientID == Guid.Empty)
                        {
                            // Process incoming requests when remote command session is not in progress.
                            lock (m_clientRequestHistory)
                            {
                                m_clientRequestHistory.Add(requestInfo);
                                if (m_clientRequestHistory.Count > m_requestHistoryLimit)
                                    m_clientRequestHistory.RemoveRange(0, (m_clientRequestHistory.Count - m_requestHistoryLimit));
                            }

                            // Check if remote client has permission to invoke the requested command.
                            if (m_secureRemoteInteractions && VerifySecurity(requestInfo.Sender) &&
                                SecurityProviderUtility.IsResourceSecurable(requestInfo.Request.Command) &&
                                !SecurityProviderUtility.IsResourceAccessible(requestInfo.Request.Command))
                                throw new SecurityException(string.Format("Access to '{0}' is denied", requestInfo.Request.Command));

                            // Notify the consumer about the incoming request from client.
                            OnReceivedClientRequest(request, requestSender);

                            ClientRequestHandler requestHandler = FindClientRequestHandler(request.Command);
                            if (requestHandler != null)
                            {
                                // Request handler exists.
                                requestHandler.HandlerMethod(requestInfo);
                            }
                            else
                            {
                                // No request handler exists.
                                throw new InvalidOperationException("Request is not supported");
                            }
                        }
                        else if (requestSender.ClientID == m_remoteCommandClientID)
                        {
                            // Redirect requests to remote command session if requests are from its originator.
                            RemoteTelnetSession(requestInfo);
                        }
                        else
                        {
                            // Reject all request from other clients since remote command session is in progress.
                            throw new InvalidOperationException("Remote telnet session is in progress");
                        }
                    }
                    catch (Exception ex)
                    {
                        m_errorLogger.Log(ex);
                        UpdateStatus(requestSender.ClientID, UpdateType.Alarm, "Failed to process request \"{0}\" - {1}.\r\n\r\n", request.Command, ex.Message);
                    }
                }
                else
                {
                    UpdateStatus(requestSender.ClientID, UpdateType.Alarm, "Failed to process request - Request could not be deserialized.\r\n\r\n");
                }
            }
        }