@@ -33,6 +33,9 @@ optional arguments:
--keep-names Store encrypted artifacts under their name, without
the suffix .enc in the SWU and in sw-description
-y, --no-hash Do not store sha256 hash in sw-description
+ --embedded-script EMBEDDED_SCRIPT
+ Lua file put into sw-description as embedded-script,
+ can be repeated: the files are joined in the given order
-k SIGN, --sign SIGN RSA key or certificate to sign the SWU
-s SW_DESCRIPTION, --sw-description SW_DESCRIPTION
sw-description template for the create command
@@ -101,6 +104,20 @@ Only the files that sw-description uses are packed. ``--add-file <name>`` (can b
repeated) adds a file found in the artifactory as it is, even if sw-description does
not use it; a file already in the SWU is not added twice.
+Embedded script
+---------------
+
+``--embedded-script <file.lua>`` (can be repeated) puts Lua code into sw-description
+as ``embedded-script``, so it is written as a normal Lua file and not escaped by
+hand. The files are joined in the given order into one script, double quotes and
+backslashes are escaped as libconfig and JSON require. The script is set in the
+``software`` block; a template that has already an ``embedded-script`` is refused::
+
+ swugenerator -o output.swu -a . -s sw-description.in \
+ --embedded-script common.lua --embedded-script board.lua create
+
+Variables of the configuration file are not replaced in the Lua files.
+
Files of 4 GiB and more
-----------------------
@@ -37,6 +37,7 @@ class SWUGenerator:
no_hash=False,
extra_files=None,
keep_names=False,
+ embedded_scripts=None,
):
self.swdescription = template
# encrypted artifacts keep their name, without .enc
@@ -60,6 +61,8 @@ class SWUGenerator:
self.nohash = no_hash
# files packed as they are, even if sw-description does not use them
self.extra_files = list(extra_files or [])
+ # Lua files joined into the embedded-script of sw-description
+ self.embedded_scripts = list(embedded_scripts or [])
self.is_json = False
@staticmethod
@@ -288,6 +291,41 @@ class SWUGenerator:
logging.debug("Extra file %s", name)
self.artifacts.append(extra)
+ @staticmethod
+ def _has_key(node, key):
+ if isinstance(node, dict):
+ return key in node or any(
+ SWUGenerator._has_key(v, key) for v in node.values()
+ )
+ if isinstance(node, (tuple, list)):
+ return any(SWUGenerator._has_key(v, key) for v in node)
+ return False
+
+ def add_embedded_script(self):
+ """Joins the Lua files into the embedded-script of sw-description"""
+ if not self.embedded_scripts:
+ return
+ # SWUpdate takes one script only: do not hide one of the template
+ if self._has_key(self.conf, "embedded-script"):
+ logging.critical(
+ "sw-description has already an embedded-script, "
+ "it cannot be added from files"
+ )
+ sys.exit(1)
+ script = ""
+ for name in self.embedded_scripts:
+ try:
+ with open(name, "r", encoding="utf-8") as f:
+ code = f.read()
+ except (OSError, UnicodeDecodeError) as error:
+ logging.critical("Cannot read embedded script %s: %s", name, error)
+ sys.exit(1)
+ if code and not code.endswith("\n"):
+ code += "\n"
+ script += code
+ # quotes and backslashes are escaped when sw-description is written
+ self.conf["software"]["embedded-script"] = script
+
def save_swdescription(self, filename, contents):
with open(filename, "w", encoding="utf-8") as swd:
swd.write(contents)
@@ -313,6 +351,7 @@ class SWUGenerator:
if "software" not in self.conf:
logging.critical("sw-description has no software block")
sys.exit(1)
+ self.add_embedded_script()
self.find_files_in_swdesc(self.conf["software"])
sw = Artifact("sw-description")
@@ -261,6 +261,7 @@ def create_swu(args: argparse.Namespace) -> None:
args.no_hash,
args.add_file,
args.keep_names,
+ args.embedded_script,
)
try:
swu.process()
@@ -424,6 +425,15 @@ def parse_args(args: List[str]) -> None:
"even if sw-description does not use it, can be repeated",
)
+ parser.add_argument(
+ "--embedded-script",
+ action="append",
+ default=[],
+ type=lambda p: Path(p).resolve(),
+ help="Lua file put into sw-description as embedded-script, can be "
+ "repeated: the files are joined in the given order",
+ )
+
parser.add_argument(
"-s",
"--sw-description",
@@ -1,5 +1,7 @@
# pylint: disable=C0114,C0116,W0621
"""Tests of the processing of sw-description"""
+import json
+
import libconf
import pytest
@@ -40,7 +42,7 @@ def test_functions_missing_artifact(generator, function):
generator._exec_functions() # pylint: disable=protected-access
-def build(tmp_path, images, dirs=None, extra=""):
+def build(tmp_path, images, dirs=None, scripts=None, extra=""):
"""Builds a SWU with the images and returns its files and sw-description"""
(tmp_path / "sw-description").write_text(
'software = { version = "1.0"; ' + extra
@@ -48,7 +50,7 @@ def build(tmp_path, images, dirs=None, extra=""):
)
gen = SWUGenerator(
tmp_path / "sw-description", tmp_path / "out.swu", {}, dirs or [tmp_path],
- None, None, None
+ None, None, None, embedded_scripts=scripts
)
try:
gen.process()
@@ -86,6 +88,48 @@ def test_plain_filename(tmp_path):
assert swdesc.software.images[0].filename == "image.bin.zlib"
+LUA_A = """-- "quotes" and 'single'
+function set_version(image)
+\tprint("path: C:\\\\dir\\n\\tnext \\"q\\"")
+\treturn true, image
+end
+"""
+LUA_B = 'local s = "no newline at the end \\t \u00fc"'
+
+
+def test_embedded_script(tmp_path):
+ (tmp_path / "image.bin").write_bytes(b"0123456789")
+ (tmp_path / "a.lua").write_text(LUA_A)
+ (tmp_path / "b.lua").write_text(LUA_B)
+ _, swdesc = build(
+ tmp_path, ['{ filename = "image.bin"; hook = "set_version"; }'],
+ scripts=[tmp_path / "a.lua", tmp_path / "b.lua"],
+ )
+ # joined in order, each file ends with a newline
+ assert swdesc.software["embedded-script"] == LUA_A + LUA_B + "\n"
+ # newlines and tabs are written as they are, not as \\n and \\t
+ text = (tmp_path / "extracted" / "sw-description").read_text()
+ assert "function set_version(image)\n\tprint(" in text
+
+
+def test_embedded_script_json(tmp_path):
+ (tmp_path / "image.bin").write_bytes(b"0123456789")
+ (tmp_path / "a.lua").write_text(LUA_A)
+ (tmp_path / "sw-description").write_text(
+ '{ "software": { "version": "1.0", "images": [ { "filename": "image.bin" } ] } }'
+ )
+ gen = SWUGenerator(
+ tmp_path / "sw-description", tmp_path / "out.swu", {}, [tmp_path],
+ None, None, None, embedded_scripts=[tmp_path / "a.lua"]
+ )
+ gen.process()
+ gen.close()
+ with open(tmp_path / "out.swu", "rb") as swu:
+ SWUFile(swu).extract(tmp_path / "extracted")
+ swdesc = json.loads((tmp_path / "extracted" / "sw-description").read_text())
+ assert swdesc["software"]["embedded-script"] == LUA_A
+
+
def test_escaped_backslash_in_template(tmp_path):
# an escaped backslash before n or t is kept, \t after it is a tab
(tmp_path / "image.bin").write_bytes(b"0123456789")
@@ -94,3 +138,23 @@ def test_escaped_backslash_in_template(tmp_path):
extra=r'embedded-script = "print(\"a\\nb\\\\\tc\")";',
)
assert swdesc.software["embedded-script"] == r'print("a\nb\\' + "\t" + r'c")'
+
+
+@pytest.mark.parametrize(
+ "extra", ['embedded-script = "x";', 'board = { embedded-script = "x"; };']
+)
+def test_embedded_script_already_in_template(tmp_path, extra):
+ (tmp_path / "image.bin").write_bytes(b"0123456789")
+ (tmp_path / "a.lua").write_text(LUA_A)
+ with pytest.raises(SystemExit):
+ build(tmp_path, ['{ filename = "image.bin"; }'],
+ scripts=[tmp_path / "a.lua"], extra=extra)
+ assert not (tmp_path / "out.swu").exists()
+
+
+def test_embedded_script_missing(tmp_path):
+ (tmp_path / "image.bin").write_bytes(b"0123456789")
+ with pytest.raises(SystemExit):
+ build(tmp_path, ['{ filename = "image.bin"; }'],
+ scripts=[tmp_path / "missing.lua"])
+ assert not (tmp_path / "out.swu").exists()
@@ -317,6 +317,8 @@ VALID_COMMANDS = [
"create",
]
),
+ (["-s", "sw-description", "-o", "test.swu", "--embedded-script", "a.lua",
+ "--embedded-script", "b.lua", "create"]),
(["-k", "CUSTOM,foo", "-o", "test.swu", "sign", "-i", "in.swu"]),
(["-o", "test.mender", "mender", "-i", "in.swu", "-D", "board"]),
(["-o", "test.mender", "mender", "-i", "in.swu", "-D", "a", "-D", "b",
@@ -350,6 +352,7 @@ INVALID_COMMANDS = [
(["-i", "in.swu", "-o", "test.swu", "sign"]),
(["-o", "test.swu", "sign", "-i", "in.swu"]),
(["-o", "test.swu", "create"]),
+ (["-s", "sw-description", "-o", "test.swu", "--embedded-script", "create"]),
(["-o", "sign", "-i", "in.swu"]),
(["-o", "test.mender", "mender"]),
(["-o", "test.mender", "mender", "-i", "in.swu"]),
An embedded-script must be written inside sw-description as a string, with every double quote and backslash escaped by hand, and the Lua code cannot be checked or edited as a normal file. --embedded-script takes a Lua file and can be repeated: the files are joined in the given order and set as embedded-script in the software block. Quotes and backslashes are escaped when sw-description is written, in libconfig as in JSON. As SWUpdate takes one script only, a template that has already an embedded-script is refused. Signed-off-by: Stefano Babic <stefano.babic@swupdate.org> --- README.rst | 17 ++++++++++ swugenerator/generator.py | 39 ++++++++++++++++++++++ swugenerator/main.py | 10 ++++++ tests/test_generator.py | 68 +++++++++++++++++++++++++++++++++++++-- tests/test_main.py | 3 ++ 5 files changed, 135 insertions(+), 2 deletions(-)