Passed
Pull Request — rhel9-branch (#189)
by Matěj
01:11
created

org_fedora_oscap.common   F

Complexity

Total Complexity 100

Size/Duplication

Total Lines 737
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
eloc 379
dl 0
loc 737
rs 2
c 0
b 0
f 0
wmc 100

24 Functions

Rating   Name   Duplication   Size   Complexity  
A _() 0 5 2
A N_() 0 1 1
C run_oscap_remediate() 0 63 9
A assert_scanner_works() 0 19 4
A do_chroot() 0 5 3
A get_fix_rules_pre() 0 15 1
B _run_oscap_gen_fix() 0 41 7
A get_postinst_tailoring_path() 0 12 3
A get_ssg_path() 0 2 1
A get_postinst_content_path() 0 15 3
A get_preinst_content_path() 0 12 3
A get_raw_preinst_content_path() 0 8 2
B _extract_tarball() 0 40 7
A get_packages_data() 0 12 2
A get_content_name() 0 15 5
A _schedule_firstboot_remediation() 0 20 5
A strip_content_dir() 0 22 4
A schedule_firstboot_remediation() 0 14 2
A get_preinst_tailoring_path() 0 8 2
D extract_data() 0 72 12
A get_payload_proxy() 0 12 2
A ssg_available() 0 9 1
D _extract_rpm() 0 69 12
A set_packages_data() 0 13 2

3 Methods

Rating   Name   Duplication   Size   Complexity  
A SubprocessLauncher.__init__() 0 6 1
A SubprocessLauncher.execute() 0 20 2
A SubprocessLauncher.log_messages() 0 3 2

How to fix   Complexity   

Complexity

Complex classes like org_fedora_oscap.common often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

1
#
2
# Copyright (C) 2013  Red Hat, Inc.
3
#
4
# This copyrighted material is made available to anyone wishing to use,
5
# modify, copy, or redistribute it subject to the terms and conditions of
6
# the GNU General Public License v.2, or (at your option) any later version.
7
# This program is distributed in the hope that it will be useful, but WITHOUT
8
# ANY WARRANTY expressed or implied, including the implied warranties of
9
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General
10
# Public License for more details.  You should have received a copy of the
11
# GNU General Public License along with this program; if not, write to the
12
# Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
13
# 02110-1301, USA.  Any Red Hat trademarks that are incorporated in the
14
# source code or documentation are not subject to the GNU General Public
15
# License and may only be used or replicated with the express permission of
16
# Red Hat, Inc.
17
#
18
# Red Hat Author(s): Vratislav Podzimek <[email protected]>
19
#
20
21
"""
22
Module with various classes and functions needed by the OSCAP addon that are
23
not specific to any installation mode (tui, gui, ks).
24
25
"""
26
27
import os
28
import tempfile
29
import subprocess
30
import zipfile
31
import tarfile
32
33
import re
34
import logging
35
36
from collections import namedtuple
37
import gettext
38
from functools import wraps
39
40
from dasbus.identifier import DBusServiceIdentifier
41
from pyanaconda.core import constants
42
from pyanaconda.core.dbus import DBus
43
from pyanaconda.core.constants import PAYLOAD_TYPE_DNF
44
from pyanaconda.modules.common.constants.namespaces import ADDONS_NAMESPACE
45
from pyanaconda.modules.common.constants.services import PAYLOADS
46
from pyanaconda.modules.common.structures.payload import PackagesConfigurationData
47
from pyanaconda.threading import threadMgr, AnacondaThread
48
49
from org_fedora_oscap import utils
50
from org_fedora_oscap import cpioarchive
51
52
53
log = logging.getLogger("anaconda")
54
55
56
# mimick pyanaconda/core/i18n.py
57
def _(string):
58
    if string:
59
        return gettext.translation("oscap-anaconda-addon", fallback=True).gettext(string)
60
    else:
61
        return ""
62
63
64
def N_(string): return string
65
66
67
# everything else should be private
68
__all__ = ["run_oscap_remediate", "get_fix_rules_pre",
69
           "extract_data", "strip_content_dir",
70
           "OSCAPaddonError", "get_payload_proxy", "get_packages_data",
71
           "set_packages_data"]
72
73
INSTALLATION_CONTENT_DIR = "/tmp/openscap_data/"
74
TARGET_CONTENT_DIR = "/root/openscap_data/"
75
76
SSG_DIR = "/usr/share/xml/scap/ssg/content/"
77
78
# Make it easy to change e.g. by sed substitution in spec files
79
# First name is the canonical addon name, rest are adapters
80
ADDON_NAMES = ["com_redhat_oscap", "org_fedora_oscap"]
81
82
COMPLAIN_ABOUT_NON_CANONICAL_NAMES = True
83
84
# Enable patches that set the content name at package-time
85
DEFAULT_SSG_CONTENT_NAME = ""
86
SSG_CONTENT = DEFAULT_SSG_CONTENT_NAME
87
if not SSG_CONTENT:
88
    if constants.shortProductName != 'anaconda':
89
        if constants.shortProductName == 'fedora':
90
            SSG_CONTENT = "ssg-fedora-ds.xml"
91
        else:
92
            SSG_CONTENT = (
93
                "ssg-{name}{version}-ds.xml"
94
                .format(
95
                    name=constants.shortProductName,
96
                    version=constants.productVersion.strip(".")[0]))
97
98
RESULTS_PATH = utils.join_paths(TARGET_CONTENT_DIR,
99
                                "eval_remediate_results.xml")
100
REPORT_PATH = utils.join_paths(TARGET_CONTENT_DIR,
101
                               "eval_remediate_report.html")
102
103
PRE_INSTALL_FIX_SYSTEM_ATTR = "urn:redhat:anaconda:pre"
104
105
THREAD_FETCH_DATA = "AnaOSCAPdataFetchThread"
106
107
SUPPORTED_ARCHIVES = (".zip", ".tar", ".tar.gz", ".tar.bz2", )
108
109
SUPPORTED_CONTENT_TYPES = (
110
    "datastream", "rpm", "archive", "scap-security-guide",
111
)
112
113
SUPPORTED_URL_PREFIXES = (
114
    "http://", "https://", "ftp://",  # LABEL:?, hdaX:?,
115
)
116
117
# buffer size for reading and writing out data (in bytes)
118
IO_BUF_SIZE = 2 * 1024 * 1024
119
120
# DBus constants
121
KDUMP = DBusServiceIdentifier(
122
    namespace=ADDONS_NAMESPACE,
123
    basename="Kdump",
124
    message_bus=DBus
125
)
126
127
128
class OSCAPaddonError(Exception):
129
    """Exception class for OSCAP addon related errors."""
130
131
    pass
132
133
134
class OSCAPaddonNetworkError(OSCAPaddonError):
135
    """Exception class for OSCAP addon related network errors."""
136
137
    pass
138
139
140
class ExtractionError(OSCAPaddonError):
141
    """Exception class for the extraction errors."""
142
143
    pass
144
145
146
MESSAGE_TYPE_FATAL = 0
147
MESSAGE_TYPE_WARNING = 1
148
MESSAGE_TYPE_INFO = 2
149
150
# namedtuple for messages returned from the rules evaluation
151
#   origin -- class (inherited from RuleHandler) that generated the message
152
#   type -- one of the MESSAGE_TYPE_* constants defined above
153
#   text -- the actual message that should be displayed, logged, ...
154
RuleMessage = namedtuple("RuleMessage", ["origin", "type", "text"])
155
156
157
class SubprocessLauncher(object):
158
    def __init__(self, args):
159
        self.args = args
160
        self.stdout = ""
161
        self.stderr = ""
162
        self.messages = []
163
        self.returncode = None
164
165
    def execute(self, ** kwargs):
166
        command_string = " ".join(self.args)
167
        log.info(
168
            "OSCAP addon: Executing subprocess: '{command_string}'"
169
            .format(command_string=command_string))
170
        try:
171
            proc = subprocess.Popen(self.args, stdout=subprocess.PIPE,
172
                                    stderr=subprocess.PIPE, ** kwargs)
173
        except OSError as oserr:
174
            msg = ("Failed to execute command '{command_string}': {oserr}"
175
                   .format(command_string=command_string, oserr=oserr))
176
            raise OSCAPaddonError(msg)
177
178
        (stdout, stderr) = proc.communicate()
179
        self.stdout = stdout.decode()
180
        self.stderr = stderr.decode(errors="replace")
181
        self.messages = re.findall(r'OpenSCAP Error:.*', self.stderr)
182
        self.messages = self.messages + re.findall(r'E: oscap:.*', self.stderr)
183
184
        self.returncode = proc.returncode
185
186
    def log_messages(self):
187
        for message in self.messages:
188
            log.warning("OSCAP addon: " + message)
189
190
191
def get_fix_rules_pre(profile, fpath, ds_id="", xccdf_id="", tailoring=""):
192
    """
193
    Get fix rules for the pre-installation environment for a given profile in a
194
    given datastream and checklist in a given file.
195
196
    :see: run_oscap_remediate
197
    :see: _run_oscap_gen_fix
198
    :return: fix rules for a given profile
199
    :rtype: str
200
201
    """
202
203
    return _run_oscap_gen_fix(profile, fpath, PRE_INSTALL_FIX_SYSTEM_ATTR,
204
                              ds_id=ds_id, xccdf_id=xccdf_id,
205
                              tailoring=tailoring)
206
207
208
def _run_oscap_gen_fix(profile, fpath, template, ds_id="", xccdf_id="",
209
                       tailoring=""):
210
    """
211
    Run oscap tool on a given file to get the contents of fix elements with the
212
    'system' attribute equal to a given template for a given datastream,
213
    checklist and profile.
214
215
    :see: run_oscap_remediate
216
    :param template: the value of the 'system' attribute of the fix elements
217
    :type template: str
218
    :return: oscap tool's stdout
219
    :rtype: str
220
221
    """
222
223
    if not profile:
224
        return ""
225
226
    args = ["oscap", "xccdf", "generate", "fix"]
227
    args.append("--template=%s" % template)
228
229
    # oscap uses the default profile by default
230
    if profile.lower() != "default":
231
        args.append("--profile=%s" % profile)
232
    if ds_id:
233
        args.append("--datastream-id=%s" % ds_id)
234
    if xccdf_id:
235
        args.append("--xccdf-id=%s" % xccdf_id)
236
    if tailoring:
237
        args.append("--tailoring-file=%s" % tailoring)
238
239
    args.append(fpath)
240
241
    proc = SubprocessLauncher(args)
242
    proc.execute()
243
    proc.log_messages()
244
    if proc.returncode != 0:
245
        msg = "Failed to generate fix rules with the oscap tool: %s" % proc.stderr
246
        raise OSCAPaddonError(msg)
247
248
    return proc.stdout
249
250
251
def do_chroot(chroot):
252
    """Helper function doing the chroot if requested."""
253
    if chroot and chroot != "/":
254
        os.chroot(chroot)
255
        os.chdir("/")
256
257
258
def assert_scanner_works(chroot, executable="oscap"):
259
    args = [executable, "--version"]
260
    command = " ".join(args)
261
262
    try:
263
        proc = subprocess.Popen(
264
            args, preexec_fn=lambda: do_chroot(chroot),
265
            stdout=subprocess.PIPE, stderr=subprocess.PIPE)
266
        (stdout, stderr) = proc.communicate()
267
        stderr = stderr.decode(errors="replace")
268
    except OSError as exc:
269
        msg = _(f"Basic invocation '{command}' fails: {str(exc)}")
270
        raise OSCAPaddonError(msg)
271
    if proc.returncode != 0:
272
        msg = _(
273
            f"Basic scanner invocation '{command}' exited "
274
            "with non-zero error code {proc.returncode}: {stderr}")
275
        raise OSCAPaddonError(msg)
276
    return True
277
278
279
def run_oscap_remediate(profile, fpath, ds_id="", xccdf_id="", tailoring="",
280
                        chroot=""):
281
    """
282
    Run the evaluation and remediation with the oscap tool on a given file,
283
    doing the remediation as defined in a given profile defined in a given
284
    checklist that is a part of a given datastream. If requested, run in
285
    chroot.
286
287
    :param profile: id of the profile that will drive the remediation
288
    :type profile: str
289
    :param fpath: path to a file with SCAP content
290
    :type fpath: str
291
    :param ds_id: ID of the datastream that contains the checklist defining
292
                  the profile
293
    :type ds_id: str
294
    :param xccdf_id: ID of the checklist that defines the profile
295
    :type xccdf_id: str
296
    :param tailoring: path to a tailoring file
297
    :type tailoring: str
298
    :param chroot: path to the root the oscap tool should be run in
299
    :type chroot: str
300
    :return: oscap tool's stdout (summary of the rules, checks and fixes)
301
    :rtype: str
302
303
    """
304
305
    if not profile:
306
        return ""
307
308
    # make sure the directory for the results exists
309
    results_dir = os.path.dirname(RESULTS_PATH)
310
    if chroot:
311
        results_dir = os.path.normpath(chroot + "/" + results_dir)
312
    utils.ensure_dir_exists(results_dir)
313
314
    args = ["oscap", "xccdf", "eval"]
315
    args.append("--remediate")
316
    args.append("--results=%s" % RESULTS_PATH)
317
    args.append("--report=%s" % REPORT_PATH)
318
319
    # oscap uses the default profile by default
320
    if profile.lower() != "default":
321
        args.append("--profile=%s" % profile)
322
    if ds_id:
323
        args.append("--datastream-id=%s" % ds_id)
324
    if xccdf_id:
325
        args.append("--xccdf-id=%s" % xccdf_id)
326
    if tailoring:
327
        args.append("--tailoring-file=%s" % tailoring)
328
329
    args.append(fpath)
330
331
    proc = SubprocessLauncher(args)
332
    proc.execute(preexec_fn=lambda: do_chroot(chroot))
333
    proc.log_messages()
334
335
    if proc.returncode not in (0, 2):
336
        # 0 -- success; 2 -- no error, but checks/remediation failed
337
        msg = "Content evaluation and remediation with the oscap tool "\
338
            "failed: %s" % proc.stderr
339
        raise OSCAPaddonError(msg)
340
341
    return proc.stdout
342
343
344
345
def _schedule_firstboot_remediation(
346
        chroot, profile, ds_path, results_path, report_path, ds_id, xccdf_id, tailoring_path):
347
    config = f"""
348
    OSCAP_REMEDIATE_DS={ds_path}
349
    OSCAP_REMEDIATE_PROFILE_ID={profile}
350
    OSCAP_REMEDIATE_ARF_RESULT={results_path}
351
    OSCAP_REMEDIATE_HTML_REPORT={report_path}
352
    """
353
    if ds_id:
354
        config += "OSCAP_REMEDIATE_DATASTREAM_ID={ds_id}\n"
355
    if xccdf_id:
356
        config += "OSCAP_REMEDIATE_XCCDF_ID={xccdf_id}\n"
357
    if tailoring_path:
358
        config += "OSCAP_REMEDIATE_TAILORING={tailoring_path}\n"
359
360
    local_config_filename = "/var/tmp/oscap-remediate-offline.conf.sh"
361
    with open(os.path.join(chroot, local_config_filename), "w") as f:
362
        f.write(config)
363
    os.symlink(os.path.join(chroot, local_config_filename),
364
               "/system-update")
365
366
367
def schedule_firstboot_remediation(chroot, profile, fpath, ds_id="", xccdf_id="", tailoring=""):
368
    if not profile:
369
        return ""
370
371
    # make sure the directory for the results exists
372
    results_dir = os.path.dirname(RESULTS_PATH)
373
    results_dir = os.path.normpath(chroot + "/" + results_dir)
374
    utils.ensure_dir_exists(results_dir)
375
376
    log.info("OSCAP addon: Scheduling firstboot remediation")
377
    _schedule_firstboot_remediation(
378
        chroot, profile, fpath, RESULTS_PATH, REPORT_PATH, ds_id, xccdf_id, tailoring)
379
380
    return ""
381
382
383
def extract_data(archive, out_dir, ensure_has_files=None):
384
    """
385
    Fuction that extracts the given archive to the given output directory. It
386
    tries to find out the archive type by the file name.
387
388
    :param archive: path to the archive file that should be extracted
389
    :type archive: str
390
    :param out_dir: output directory the archive should be extracted to
391
    :type out_dir: str
392
    :param ensure_has_files: relative paths to the files that must exist in the
393
                             archive
394
    :type ensure_has_files: iterable of strings or None
395
    :return: a list of files and directories extracted from the archive
396
    :rtype: [str]
397
398
    """
399
400
    if not ensure_has_files:
401
        ensure_has_files = []
402
403
    # get rid of empty file paths
404
    if not ensure_has_files:
405
        ensure_has_files = []
406
    else:
407
        ensure_has_files = [fpath for fpath in ensure_has_files if fpath]
408
409
    msg = "OSCAP addon: Extracting {archive}".format(archive=archive)
410
    if ensure_has_files:
411
        msg += ", expecting to find {files} there.".format(files=tuple(ensure_has_files))
412
    log.info(msg)
413
414
    result = []
415
    if archive.endswith(".zip"):
416
        # ZIP file
417
        try:
418
            zfile = zipfile.ZipFile(archive, "r")
419
        except Exception as exc:
420
            msg = _(f"Error extracting archive as a zipfile: {exc}")
421
            raise ExtractionError(msg)
422
423
        # generator for the paths of the files found in the archive (dirs end
424
        # with "/")
425
        files = set(info.filename for info in zfile.filelist
426
                    if not info.filename.endswith("/"))
427
        for fpath in ensure_has_files or ():
428
            if fpath not in files:
429
                msg = "File '%s' not found in the archive '%s'" % (fpath,
430
                                                                   archive)
431
                raise ExtractionError(msg)
432
433
        utils.ensure_dir_exists(out_dir)
434
        zfile.extractall(path=out_dir)
435
        result = [utils.join_paths(out_dir, info.filename) for info in zfile.filelist]
436
        zfile.close()
437
    elif archive.endswith(".tar"):
438
        # plain tarball
439
        result = _extract_tarball(archive, out_dir, ensure_has_files, None)
440
    elif archive.endswith(".tar.gz"):
441
        # gzipped tarball
442
        result = _extract_tarball(archive, out_dir, ensure_has_files, "gz")
443
    elif archive.endswith(".tar.bz2"):
444
        # bzipped tarball
445
        result = _extract_tarball(archive, out_dir, ensure_has_files, "bz2")
446
    elif archive.endswith(".rpm"):
447
        # RPM
448
        result = _extract_rpm(archive, out_dir, ensure_has_files)
449
    # elif other types of archives
450
    else:
451
        raise ExtractionError("Unsuported archive type")
452
    log.info("OSCAP addon: Extracted {files} from the supplied content"
453
             .format(files=result))
454
    return result
455
456
457
def _extract_tarball(archive, out_dir, ensure_has_files, alg):
458
    """
459
    Extract the given TAR archive to the given output directory and make sure
460
    the given file exists in the archive.
461
462
    :see: extract_data
463
    :param alg: compression algorithm used for the tarball
464
    :type alg: str (one of "gz", "bz2") or None
465
    :return: a list of files and directories extracted from the archive
466
    :rtype: [str]
467
468
    """
469
470
    if alg and alg not in ("gz", "bz2",):
471
        raise ExtractionError("Unsupported compression algorithm")
472
473
    mode = "r"
474
    if alg:
475
        mode += ":%s" % alg
476
477
    try:
478
        tfile = tarfile.TarFile.open(archive, mode)
479
    except tarfile.TarError as err:
480
        raise ExtractionError(str(err))
481
482
    # generator for the paths of the files found in the archive
483
    files = set(member.path for member in tfile.getmembers()
484
                if member.isfile())
485
486
    for fpath in ensure_has_files or ():
487
        if fpath not in files:
488
            msg = "File '%s' not found in the archive '%s'" % (fpath, archive)
489
            raise ExtractionError(msg)
490
491
    utils.ensure_dir_exists(out_dir)
492
    tfile.extractall(path=out_dir)
493
    result = [utils.join_paths(out_dir, member.path) for member in tfile.getmembers()]
494
    tfile.close()
495
496
    return result
497
498
499
def _extract_rpm(rpm_path, root="/", ensure_has_files=None):
500
    """
501
    Extract the given RPM into the directory tree given by the root argument
502
    and make sure the given file exists in the archive.
503
504
    :param rpm_path: path to the RPM file that should be extracted
505
    :type rpm_path: str
506
    :param root: root of the directory tree the RPM should be extracted into
507
    :type root: str
508
    :param ensure_has_files: relative paths to the files that must exist in the
509
                             RPM
510
    :type ensure_has_files: iterable of strings or None
511
    :return: a list of files and directories extracted from the archive
512
    :rtype: [str]
513
514
    """
515
516
    # run rpm2cpio and process the output with the cpioarchive module
517
    temp_fd, temp_path = tempfile.mkstemp(prefix="oscap_rpm")
518
    proc = subprocess.Popen(["rpm2cpio", rpm_path], stdout=temp_fd)
519
    proc.wait()
520
    if proc.returncode != 0:
521
        msg = "Failed to convert RPM '%s' to cpio archive" % rpm_path
522
        raise ExtractionError(msg)
523
524
    os.close(temp_fd)
525
526
    try:
527
        archive = cpioarchive.CpioArchive(temp_path)
528
    except cpioarchive.CpioError as err:
529
        raise ExtractionError(str(err))
530
531
    # get entries from the archive (supports only iteration over entries)
532
    entries = set(entry for entry in archive)
533
534
    # cpio entry names (paths) start with the dot
535
    entry_names = [entry.name.lstrip(".") for entry in entries]
536
537
    for fpath in ensure_has_files or ():
538
        # RPM->cpio entries have absolute paths
539
        if fpath not in entry_names and \
540
           os.path.join("/", fpath) not in entry_names:
541
            msg = "File '%s' not found in the archive '%s'" % (fpath, rpm_path)
542
            raise ExtractionError(msg)
543
544
    try:
545
        for entry in entries:
546
            if entry.size == 0:
547
                continue
548
            dirname = os.path.dirname(entry.name.lstrip("."))
549
            out_dir = os.path.normpath(root + dirname)
550
            utils.ensure_dir_exists(out_dir)
551
552
            out_fpath = os.path.normpath(root + entry.name.lstrip("."))
553
            if os.path.exists(out_fpath):
554
                continue
555
            with open(out_fpath, "wb") as out_file:
556
                buf = entry.read(IO_BUF_SIZE)
557
                while buf:
558
                    out_file.write(buf)
559
                    buf = entry.read(IO_BUF_SIZE)
560
    except (IOError, cpioarchive.CpioError) as e:
561
        raise ExtractionError(e)
562
563
    # cleanup
564
    archive.close()
565
    os.unlink(temp_path)
566
567
    return [os.path.normpath(root + name) for name in entry_names]
568
569
570
def strip_content_dir(fpaths, phase="preinst"):
571
    """
572
    Strip content directory prefix from the file paths for either
573
    pre-installation or post-installation phase.
574
575
    :param fpaths: iterable of file paths to strip content directory prefix
576
                   from
577
    :type fpaths: iterable of strings
578
    :param phase: specifies pre-installation or post-installation phase
579
    :type phase: "preinst" or "postinst"
580
    :return: the same iterable of file paths as given with the content
581
             directory prefix stripped
582
    :rtype: same type as fpaths
583
584
    """
585
586
    if phase == "preinst":
587
        remove_prefix = lambda x: x[len(INSTALLATION_CONTENT_DIR):]
588
    else:
589
        remove_prefix = lambda x: x[len(TARGET_CONTENT_DIR):]
590
591
    return utils.keep_type_map(remove_prefix, fpaths)
592
593
594
def get_ssg_path(root="/"):
595
    return utils.join_paths(root, SSG_DIR + SSG_CONTENT)
596
597
598
def ssg_available(root="/"):
599
    """
600
    Tries to find the SCAP Security Guide under the given root.
601
602
    :return: True if SSG was found under the given root, False otherwise
603
604
    """
605
606
    return os.path.exists(get_ssg_path(root))
607
608
609
def get_content_name(data):
610
    if data.content_type == "scap-security-guide":
611
        raise ValueError("Using scap-security-guide, no single content file")
612
613
    rest = "/anonymous_content"
614
    for prefix in SUPPORTED_URL_PREFIXES:
615
        if data.content_url.startswith(prefix):
616
            rest = data.content_url[len(prefix):]
617
            break
618
619
    parts = rest.rsplit("/", 1)
620
    if len(parts) != 2:
621
        raise ValueError("Unsupported url '%s'" % data.content_url)
622
623
    return parts[1]
624
625
626
def get_raw_preinst_content_path(data):
627
    """Path to the raw (unextracted, ...) pre-installation content file"""
628
    if data.content_type == "scap-security-guide":
629
        log.debug("OSCAP addon: Using scap-security-guide, no single content file")
630
        return None
631
632
    content_name = get_content_name(data)
633
    return utils.join_paths(INSTALLATION_CONTENT_DIR, content_name)
634
635
636
def get_preinst_content_path(data):
637
    """Path to the pre-installation content file"""
638
    if data.content_type == "scap-security-guide":
639
        # SSG is not copied to the standard place
640
        return data.content_path
641
642
    if data.content_type == "datastream":
643
        return get_raw_preinst_content_path(data)
644
645
    return utils.join_paths(
646
        INSTALLATION_CONTENT_DIR,
647
        data.content_path
648
    )
649
650
651
def get_postinst_content_path(data):
652
    """Path to the post-installation content file"""
653
    if data.content_type == "datastream":
654
        return utils.join_paths(
655
            TARGET_CONTENT_DIR,
656
            get_content_name(data)
657
        )
658
659
    if data.content_type in ("rpm", "scap-security-guide"):
660
        # no path magic in case of RPM (SSG is installed as an RPM)
661
        return data.content_path
662
663
    return utils.join_paths(
664
        TARGET_CONTENT_DIR,
665
        data.content_path
666
    )
667
668
669
def get_preinst_tailoring_path(data):
670
    """Path to the pre-installation tailoring file (if any)"""
671
    if not data.tailoring_path:
672
        return ""
673
674
    return utils.join_paths(
675
        INSTALLATION_CONTENT_DIR,
676
        data.tailoring_path
677
    )
678
679
680
def get_postinst_tailoring_path(data):
681
    """Path to the post-installation tailoring file (if any)"""
682
    if not data.tailoring_path:
683
        return ""
684
685
    if data.content_type == "rpm":
686
        # no path magic in case of RPM
687
        return data.tailoring_path
688
689
    return utils.join_paths(
690
        TARGET_CONTENT_DIR,
691
        data.tailoring_path
692
    )
693
694
695
def get_payload_proxy():
696
    """Get the DBus proxy of the active payload.
697
698
    :return: a DBus proxy
699
    """
700
    payloads_proxy = PAYLOADS.get_proxy()
701
    object_path = payloads_proxy.ActivePayload
702
703
    if not object_path:
704
        raise ValueError("Active payload is not set.")
705
706
    return PAYLOADS.get_proxy(object_path)
707
708
709
def get_packages_data() -> PackagesConfigurationData:
710
    """Get the DBus data with the packages configuration.
711
712
    :return: a packages configuration
713
    """
714
    payload_proxy = get_payload_proxy()
715
716
    if payload_proxy.Type != PAYLOAD_TYPE_DNF:
717
        return PackagesConfigurationData()
718
719
    return PackagesConfigurationData.from_structure(
720
        payload_proxy.Packages
721
    )
722
723
724
def set_packages_data(data: PackagesConfigurationData):
725
    """Set the DBus data with the packages configuration.
726
727
    :param data: a packages configuration
728
    """
729
    payload_proxy = get_payload_proxy()
730
731
    if payload_proxy.Type != PAYLOAD_TYPE_DNF:
732
        log.debug("OSCAP addon: The payload doesn't support packages.")
733
        return
734
735
    return payload_proxy.SetPackages(
736
        PackagesConfigurationData.to_structure(data)
737
    )
738