From c3dda0966a85343d5a2402620ae24e2f8d4158d5 Mon Sep 17 00:00:00 2001
From: JoveToo
Date: Wed, 9 Feb 2022 11:39:01 +0100
Subject: [PATCH] =?UTF-8?q?=E2=9C=A8=20Add=20(optional)=20support=20for=20?=
=?UTF-8?q?shutdown=20action=20command.=20(#4358)?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
* Adding shutdown action command.
* Add myself
* Add error handling.
* First attempt at systemcommands module
* Fix pre-commit issues
* Fix pre-commit issues
* Add log message.
* Update src/octoprint/systemcommands/__init__.py
* Renamed __call, simplified code.
* Inject systemcommands into plugins
* Use underscore between words in dict.
* ♻️ systemcommands -> system_command_manager
* ♻️ Switch places that make sense to system_commands_manager
Also switch SCM to use CommandlineCaller instead of
reinventing the wheel, same for other places.
* 🔒️ Don't enable support for action:shutdown by default
It could be abused by malicious firmware and/or GCODE
somehow tricked on the user, so let's play it safe
and make it something the user has to consciously enable.
* 📝 Add missing documentation
Co-authored-by: Gina Häußge
---
AUTHORS.md | 2 +
docs/configuration/config_yaml.rst | 4 +
docs/features/action_commands.rst | 12 ++-
.../plugins/softwareupdate/__init__.py | 36 +++----
src/octoprint/server/__init__.py | 3 +
src/octoprint/server/api/settings.py | 9 ++
src/octoprint/server/api/system.py | 32 +++---
src/octoprint/settings.py | 1 +
.../static/js/app/viewmodels/settings.js | 1 +
src/octoprint/systemcommands/__init__.py | 91 +++++++++++++++++
.../dialogs/settings/serialconnection.jinja2 | 9 ++
src/octoprint/util/comm.py | 70 ++++++++++---
src/octoprint/util/commandline.py | 97 ++++++++++---------
13 files changed, 267 insertions(+), 100 deletions(-)
create mode 100644 src/octoprint/systemcommands/__init__.py
diff --git a/AUTHORS.md b/AUTHORS.md
index ba98c28fd..b36e3a79b 100644
--- a/AUTHORS.md
+++ b/AUTHORS.md
@@ -160,7 +160,9 @@ date of first contribution):
* [Adam Wolf](https://github.com/adamwolf)
* [Didi Kohen](https://github.com/kohend)
* [Taylor Talkington](https://github.com/The-EG)
+ * [Carey Metcalfe](https://github.com/pR0Ps)
* [Shell M. Shrader](https://github.com/synman)
+ * [Johan Verrept](https://github.com/JoveToo)
OctoPrint started off as a fork of [Cura](https://github.com/daid/Cura) by
[Daid Braam](https://github.com/daid). Parts of its communication layer and
diff --git a/docs/configuration/config_yaml.rst b/docs/configuration/config_yaml.rst
index 838c5a9b8..23aeea573 100644
--- a/docs/configuration/config_yaml.rst
+++ b/docs/configuration/config_yaml.rst
@@ -814,6 +814,10 @@ Use the following settings to configure the serial connection to the printer:
# other values can be used: https://docs.python.org/3/library/codecs.html#standard-encodings
encoding: ascii
+ # Whether to enable support for the shutdown action command, allowing the printer to
+ # shut down OctoPrint and the system it's running on
+ enableShutdownActionCommand: false
+
# Whether to "manually" trigger an ok for M29 (a lot of versions of this command are buggy and
# the response skips on the ok)
triggerOkForM29: true
diff --git a/docs/features/action_commands.rst b/docs/features/action_commands.rst
index b3d298e2e..f9d264928 100644
--- a/docs/features/action_commands.rst
+++ b/docs/features/action_commands.rst
@@ -75,8 +75,18 @@ sd_updated
.. versionadded:: 1.6.0
+shutdown
+ When this command is received from the printer, **support for it is enabled in its settings**
+ and a working system shutdown command is configured, OctoPrint will immediately shutdown the system.
+ This command is not enabled by default due to the high risk of seeing it abused by malicious
+ firmware or manipulated GCODE, but can be enabled in the OctoPrint settings via Serial Connection >
+ Firmware & Protocol > Action Commands if so desired by the user.
+
+ .. versionadded:: 1.8.0
+
If the bundled :ref:`Action Command Prompt Support Plugin ` is enabled (which
-should be the case by default), OctoPrint will also interactive dialog creation through its :ref:`supported commands `.
+should be the case by default), OctoPrint will also support interactive dialog creation
+through its :ref:`supported commands `.
Support for additional commands may be added by plugins by implementing a handler for the
:ref:`octoprint.comm.protocol.action ` hook.
diff --git a/src/octoprint/plugins/softwareupdate/__init__.py b/src/octoprint/plugins/softwareupdate/__init__.py
index 1f854591b..2a5f875da 100644
--- a/src/octoprint/plugins/softwareupdate/__init__.py
+++ b/src/octoprint/plugins/softwareupdate/__init__.py
@@ -29,6 +29,7 @@ from octoprint.server.util.flask import (
with_revalidation_checking,
)
from octoprint.util import dict_merge, get_formatted_size, to_unicode, yaml
+from octoprint.util.commandline import CommandlineError
from octoprint.util.pip import create_pip_caller
from octoprint.util.version import (
get_comparable_version,
@@ -628,8 +629,7 @@ class SoftwareUpdatePlugin(
return False
restart_type = self._get_restart_type(check)
- restart_command = self._get_restart_command(restart_type)
- return restart_command is not None
+ return self._has_restart_command(restart_type)
def _get_restart_type(self, check):
if check.get("restart") in self.VALID_RESTART_TYPES:
@@ -641,17 +641,13 @@ class SoftwareUpdatePlugin(
return target_restart_type
- def _get_restart_command(self, restart_type):
+ def _has_restart_command(self, restart_type):
if restart_type == "octoprint":
- return self._settings.global_get(
- ["server", "commands", "serverRestartCommand"]
- )
+ return self._system_commands.has_server_restart_command()
elif restart_type == "environment":
- return self._settings.global_get(
- ["server", "commands", "systemRestartCommand"]
- )
+ return self._system_commands.has_system_restart_command()
else:
- return None
+ return False
# ~~ SettingsPlugin API
@@ -1947,14 +1943,13 @@ class SoftwareUpdatePlugin(
# one of our updates requires a restart of either type "octoprint" or "environment". Let's see if
# we can actually perform that
- restart_command = self._get_restart_command(restart_type)
- if restart_command:
+ if self._has_restart_command(restart_type):
self._send_client_message(
"restarting",
{"restart_type": restart_type, "results": target_results},
)
try:
- self._perform_restart(restart_command)
+ self._perform_restart(restart_type)
except exceptions.RestartFailed:
self._send_client_message(
"restart_failed",
@@ -2164,18 +2159,19 @@ class SoftwareUpdatePlugin(
check["current"] = current
- def _perform_restart(self, restart_command):
+ def _perform_restart(self, restart_type):
"""
- Performs a restart using the supplied restart_command.
+ Performs a restart using the supplied restart_type.
"""
self._logger.info("Restarting...")
try:
- util.execute(restart_command, evaluate_returncode=False, do_async=True)
- except exceptions.ScriptError as e:
- self._logger.exception(
- f"Error while restarting via command {restart_command}"
- )
+ if restart_type == "octoprint":
+ return self._system_commands.perform_server_restart()
+ elif restart_type == "environment":
+ return self._system_commands.perform_system_restart()
+ except CommandlineError as e:
+ self._logger.exception(f"Error while restarting of type {restart_type}")
self._logger.warning(f"Restart stdout:\n{e.stdout}")
self._logger.warning(f"Restart stderr:\n{e.stderr}")
raise exceptions.RestartFailed()
diff --git a/src/octoprint/server/__init__.py b/src/octoprint/server/__init__.py
index 664dca3c8..132ba55e8 100644
--- a/src/octoprint/server/__init__.py
+++ b/src/octoprint/server/__init__.py
@@ -43,6 +43,7 @@ from werkzeug.exceptions import HTTPException
import octoprint.util
import octoprint.util.net
from octoprint.server import util
+from octoprint.systemcommands import system_command_manager
from octoprint.util.json import JsonEncoding
from octoprint.vendor.flask_principal import ( # noqa: F401
AnonymousIdentity,
@@ -377,6 +378,7 @@ class Server:
###
### See also issues #2035 and #2090
+ systemCommandManager = system_command_manager()
printerProfileManager = PrinterProfileManager()
eventManager = self._event_manager
@@ -483,6 +485,7 @@ class Server:
"json_decoder": jsonDecoder,
"connectivity_checker": connectivityChecker,
"environment_detector": self._environment_detector,
+ "system_commands": systemCommandManager,
}
# ~~ setup access control
diff --git a/src/octoprint/server/api/settings.py b/src/octoprint/server/api/settings.py
index 58889d257..d5bc41cfe 100644
--- a/src/octoprint/server/api/settings.py
+++ b/src/octoprint/server/api/settings.py
@@ -262,6 +262,9 @@ def getSettings():
"resendRatioStart": s.getInt(["serial", "resendRatioStart"]),
"ignoreEmptyPorts": s.getBoolean(["serial", "ignoreEmptyPorts"]),
"encoding": s.get(["serial", "encoding"]),
+ "enableShutdownActionCommand": s.get(
+ ["serial", "enableShutdownActionCommand"]
+ ),
},
"folder": {
"uploads": s.getBaseFolder("uploads"),
@@ -968,6 +971,12 @@ def _saveSettings(data):
if "encoding" in data["serial"]:
s.set(["serial", "encoding"], data["serial"]["encoding"])
+ if "enableShutdownActionCommand" in data["serial"]:
+ s.setBoolean(
+ ["serial", "enableShutdownActionCommand"],
+ data["serial"]["enableShutdownActionCommand"],
+ )
+
oldLog = s.getBoolean(["serial", "log"])
if "log" in data["serial"]:
s.setBoolean(["serial", "log"], data["serial"]["log"])
diff --git a/src/octoprint/server/api/system.py b/src/octoprint/server/api/system.py
index 3f7180fab..2d927fd1a 100644
--- a/src/octoprint/server/api/system.py
+++ b/src/octoprint/server/api/system.py
@@ -7,7 +7,6 @@ import re
import threading
import psutil
-import sarge
from flask import abort, jsonify, request, url_for
from flask_babel import gettext
@@ -18,7 +17,8 @@ from octoprint.server import NO_CONTENT
from octoprint.server.api import api
from octoprint.server.util.flask import get_remote_address, no_firstrun_access
from octoprint.settings import settings as s
-from octoprint.util.platform import CLOSE_FDS
+from octoprint.systemcommands import system_command_manager
+from octoprint.util.commandline import CommandlineCaller
@api.route("/system/usage", methods=["GET"])
@@ -165,22 +165,14 @@ def executeSystemCommand(source, command):
# we run this with shell=True since we have to trust whatever
# our admin configured as command and since we want to allow
# shell-alike handling here...
- p = sarge.run(
- command_spec["command"],
- close_fds=CLOSE_FDS,
- stdout=sarge.Capture(),
- stderr=sarge.Capture(),
- shell=True,
+ return_code, stdout_lines, stderr_lines = CommandlineCaller().call(
+ command_spec["command"], shell=True
)
- if not do_ignore and p.returncode != 0:
- returncode = p.returncode
- stdout_text = p.stdout.text
- stderr_text = p.stderr.text
-
- error = "Command for {}:{} failed with return code {}:\nSTDOUT: {}\nSTDERR: {}".format(
- source, command, returncode, stdout_text, stderr_text
- )
+ if not do_ignore and return_code != 0:
+ stdout = "\n".join(stdout_lines)
+ stderr = "\n".join(stderr_lines)
+ error = f"Command for {source}:{command} failed with return code {return_code}:\n\nSTDOUT:\n{stdout}\n\nSTDERR:\n{stderr}"
logger.warning(prefix_multilines(error, prefix="! "))
if not do_async:
raise CommandFailed(error)
@@ -241,28 +233,28 @@ def _get_core_command_specs():
commands = collections.OrderedDict(
shutdown={
- "command": s().get(["server", "commands", "systemShutdownCommand"]),
+ "command": system_command_manager().get_system_shutdown_command(),
"name": gettext("Shutdown system"),
"confirm": gettext(
"You are about to shutdown the system.
This action may disrupt any ongoing print jobs (depending on your printer's controller and general setup that might also apply to prints run directly from your printer's internal storage)."
),
},
reboot={
- "command": s().get(["server", "commands", "systemRestartCommand"]),
+ "command": system_command_manager().get_system_restart_command(),
"name": gettext("Reboot system"),
"confirm": gettext(
"You are about to reboot the system.
This action may disrupt any ongoing print jobs (depending on your printer's controller and general setup that might also apply to prints run directly from your printer's internal storage)."
),
},
restart={
- "command": s().get(["server", "commands", "serverRestartCommand"]),
+ "command": system_command_manager().get_server_restart_command(),
"name": gettext("Restart OctoPrint"),
"confirm": gettext(
"You are about to restart the OctoPrint server.
This action may disrupt any ongoing print jobs (depending on your printer's controller and general setup that might also apply to prints run directly from your printer's internal storage)."
),
},
restart_safe={
- "command": s().get(["server", "commands", "serverRestartCommand"]),
+ "command": system_command_manager().get_server_restart_command(),
"name": gettext("Restart OctoPrint in safe mode"),
"confirm": gettext(
"You are about to restart the OctoPrint server in safe mode.
This action may disrupt any ongoing print jobs (depending on your printer's controller and general setup that might also apply to prints run directly from your printer's internal storage)."
diff --git a/src/octoprint/settings.py b/src/octoprint/settings.py
index 3483924dd..6496644a9 100644
--- a/src/octoprint/settings.py
+++ b/src/octoprint/settings.py
@@ -168,6 +168,7 @@ default_settings = {
"resendRatioStart": 100,
"ignoreEmptyPorts": False,
"encoding": "ascii",
+ "enableShutdownActionCommand": False,
# command specific flags
"triggerOkForM29": True,
},
diff --git a/src/octoprint/static/js/app/viewmodels/settings.js b/src/octoprint/static/js/app/viewmodels/settings.js
index d555982d4..1048de9d1 100644
--- a/src/octoprint/static/js/app/viewmodels/settings.js
+++ b/src/octoprint/static/js/app/viewmodels/settings.js
@@ -247,6 +247,7 @@ $(function () {
self.serial_ackMax = ko.observable(undefined);
self.serial_resendRatioThreshold = ko.observable(100);
self.serial_resendRatioStart = ko.observable(100);
+ self.serial_enableShutdownActionCommand = ko.observable(undefined);
self.folder_uploads = ko.observable(undefined);
self.folder_timelapse = ko.observable(undefined);
diff --git a/src/octoprint/systemcommands/__init__.py b/src/octoprint/systemcommands/__init__.py
new file mode 100644
index 000000000..cf91b9db3
--- /dev/null
+++ b/src/octoprint/systemcommands/__init__.py
@@ -0,0 +1,91 @@
+"""
+This module represents OctoPrint's system and server commands.
+"""
+
+__author__ = "Johan Verrept "
+__license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html"
+__copyright__ = "Copyright (C) 2022 The OctoPrint Project - Released under terms of the AGPLv3 License"
+
+import logging
+
+from octoprint.settings import settings
+from octoprint.util.commandline import CommandlineCaller, CommandlineError
+
+# singleton
+_instance = None
+
+
+def system_command_manager():
+ global _instance
+ if _instance is None:
+ _instance = SystemCommandManager()
+ return _instance
+
+
+class SystemCommandManager:
+
+ SERVER_RESTART_COMMAND = "serverRestartCommand"
+ SYSTEM_RESTART_COMMAND = "systemRestartCommand"
+ SYSTEM_SHUTDOWN_COMMAND = "systemShutdownCommand"
+
+ def __init__(self):
+ self._logger = logging.getLogger(__name__)
+ self._caller = CommandlineCaller()
+
+ def execute(self, command):
+ if not command:
+ return False
+
+ try:
+ # we run this with shell=True since we have to trust whatever
+ # our admin configured as command and since we want to allow
+ # shell-alike handling here...
+ p = self._caller.non_blocking_call(command, shell=True)
+
+ if p is None:
+ raise CommandlineError(None, "", "")
+
+ if p.returncode is not None:
+ stdout = p.stdout.text if p is not None and p.stdout is not None else ""
+ stderr = p.stderr.text if p is not None and p.stderr is not None else ""
+ raise CommandlineError(p.returncode, stdout, stderr)
+ except CommandlineError:
+ raise
+ except Exception:
+ self._logger.exception(f"Error while executing command: {command}")
+ raise CommandlineError(None, "", "")
+
+ return True
+
+ def get_command(self, cmd):
+ return settings().get(["server", "commands", cmd])
+
+ def has_command(self, cmd):
+ return self.get_command(cmd) is not None
+
+ def get_server_restart_command(self):
+ return self.get_command(self.SERVER_RESTART_COMMAND)
+
+ def get_system_restart_command(self):
+ return self.get_command(self.SYSTEM_RESTART_COMMAND)
+
+ def get_system_shutdown_command(self):
+ return self.get_command(self.SYSTEM_SHUTDOWN_COMMAND)
+
+ def has_server_restart_command(self):
+ return self.get_server_restart_command() is not None
+
+ def has_system_restart_command(self):
+ return self.get_system_restart_command() is not None
+
+ def has_system_shutdown_command(self):
+ return self.get_system_shutdown_command() is not None
+
+ def perform_server_restart(self):
+ return self.execute(self.get_server_restart_command())
+
+ def perform_system_restart(self):
+ return self.execute(self.get_system_restart_command())
+
+ def perform_system_shutdown(self):
+ return self.execute(self.get_system_shutdown_command())
diff --git a/src/octoprint/templates/dialogs/settings/serialconnection.jinja2 b/src/octoprint/templates/dialogs/settings/serialconnection.jinja2
index 98ef5315a..f9103694a 100644
--- a/src/octoprint/templates/dialogs/settings/serialconnection.jinja2
+++ b/src/octoprint/templates/dialogs/settings/serialconnection.jinja2
@@ -486,6 +486,15 @@
+