|
13 | 13 | from cryptography.hazmat.primitives.asymmetric import rsa |
14 | 14 | from typing import Union |
15 | 15 | from pathlib import Path |
| 16 | +from configparser import ConfigParser |
| 17 | +from io import TextIOWrapper |
16 | 18 |
|
17 | 19 | from SCAutolib import run, logger, TEMPLATES_DIR, LIB_BACKUP |
18 | 20 |
|
19 | 21 |
|
| 22 | +class MultiEntryDict(dict): |
| 23 | + """ |
| 24 | + A dictionary subclass that merges list values for duplicate keys. |
| 25 | +
|
| 26 | + This dictionary is customized for use with `ConfigParser` where multi-line |
| 27 | + or duplicate options may be processed as lists. Instead of |
| 28 | + overwriting an existing list value, it appends new list items to the |
| 29 | + existing ones. |
| 30 | + """ |
| 31 | + |
| 32 | + def __setitem__(self, key: str, value: list[str]): |
| 33 | + """ |
| 34 | + Set the value for a given key, merging lists if the key already exists. |
| 35 | +
|
| 36 | + If both the existing value and the incoming value are lists, they are |
| 37 | + concatenated. Otherwise, the standard dictionary assignment is used. |
| 38 | +
|
| 39 | + :param key: The key to set. |
| 40 | + :type key: str |
| 41 | + :param value: The value to associate with the key. |
| 42 | + :type value: list[str] |
| 43 | + :return: None |
| 44 | + :rtype: None |
| 45 | + """ |
| 46 | + # ConfigParser temporarily stores values as a list of lines during |
| 47 | + # parsing. If the key already exists, we merge the lists instead of |
| 48 | + # overwriting. |
| 49 | + if ( |
| 50 | + key in self and |
| 51 | + isinstance(value, list) and |
| 52 | + isinstance(self[key], list) |
| 53 | + ): |
| 54 | + super().__setitem__(key, self[key] + value) |
| 55 | + else: |
| 56 | + super().__setitem__(key, value) |
| 57 | + |
| 58 | + |
| 59 | +class CustomConfigParser(ConfigParser): |
| 60 | + """ |
| 61 | + A custom ConfigParser that supports duplicate keys and continuations. |
| 62 | +
|
| 63 | + By utilizing `MultiEntryDict` as its internal dictionary type and disabling |
| 64 | + strict mode, this parser handles configuration files containing multiple |
| 65 | + identical keys within a single section without overwriting them. |
| 66 | + """ |
| 67 | + |
| 68 | + def __init__(self, *args, **kwargs): |
| 69 | + """ |
| 70 | + Initialize the CustomConfigParser with non-strict multi-entry support. |
| 71 | +
|
| 72 | + :param args: Positional arguments passed to the parent `ConfigParser`. |
| 73 | + :type args: list |
| 74 | + :param kwargs: Keyword arguments passed to the parent `ConfigParser`. |
| 75 | + :type kwargs: dict |
| 76 | + :return: None |
| 77 | + :rtype: None |
| 78 | + """ |
| 79 | + super().__init__( |
| 80 | + *args, **kwargs, dict_type=MultiEntryDict, strict=False, |
| 81 | + ) |
| 82 | + |
| 83 | + def _write_section( |
| 84 | + self, fp: TextIOWrapper, section_name: str, section_items: list[str], |
| 85 | + delimiter: str |
| 86 | + ): |
| 87 | + r""" |
| 88 | + Write a single section and its items to a file-like object. |
| 89 | +
|
| 90 | + This overrides the default section writing behavior to match formats |
| 91 | + like systemd configuration files. It duplicates key names for |
| 92 | + multi-line entries unless a line explicitly ends with a backslash |
| 93 | + (`\\`), which triggers a standard indented continuation line. |
| 94 | +
|
| 95 | + :param fp: A file-like object open for writing. |
| 96 | + :type fp: TextIOWrapper |
| 97 | + :param section_name: The name of the section being written. |
| 98 | + :type section_name: str |
| 99 | + :param section_items: An iterable of (key, value) pairs to write. |
| 100 | + :type section_items: list[str] |
| 101 | + :param delimiter: The delimiter string separating keys and values. |
| 102 | + :type delimiter: str |
| 103 | + :return: None |
| 104 | + :rtype: None |
| 105 | + """ |
| 106 | + fp.write("[{}]\n".format(section_name)) |
| 107 | + for key, value in section_items: |
| 108 | + value = self._interpolation.before_write( |
| 109 | + self, section_name, key, value) |
| 110 | + if value is not None: |
| 111 | + lines = str(value).split('\n') |
| 112 | + is_continuation = False |
| 113 | + |
| 114 | + for line in lines: |
| 115 | + if is_continuation: |
| 116 | + # Keep it as an indented continuation line if the |
| 117 | + # previous line ended in \ |
| 118 | + fp.write("\t{}\n".format(line.strip())) |
| 119 | + else: |
| 120 | + # Otherwise, repeat the key name for duplicate options |
| 121 | + fp.write("{}{}{}\n".format(key, delimiter, line)) |
| 122 | + |
| 123 | + # Systemd uses a trailing backslash to denote a split |
| 124 | + # single line |
| 125 | + if line.strip().endswith('\\'): |
| 126 | + is_continuation = True |
| 127 | + else: |
| 128 | + is_continuation = False |
| 129 | + elif not self._allow_no_value: |
| 130 | + fp.write("{}{}\n".format(key, delimiter)) |
| 131 | + else: |
| 132 | + fp.write("{}\n".format(key)) |
| 133 | + fp.write("\n") |
| 134 | + |
| 135 | + |
20 | 136 | def _check_selinux(): |
21 | 137 | """ |
22 | 138 | Check if the 'virtcacard' SELinux module is active. |
|
0 commit comments