| 1 |
# |
| 2 |
# Copyright (C) 2018 FreeIPA Contributors see COPYING for license |
| 3 |
# |
| 4 |
|
| 5 |
import io |
| 6 |
import os |
| 7 |
import re |
| 8 |
import stat |
| 9 |
import tempfile |
| 10 |
|
| 11 |
from ipapython.ipautil import unescape_seq, escape_seq |
| 12 |
|
| 13 |
_SENTINEL = object() |
| 14 |
|
| 15 |
|
| 16 |
class DirectiveSetter: |
| 17 |
"""Safe directive setter |
| 18 |
|
| 19 |
with DirectiveSetter('/path/to/conf') as ds: |
| 20 |
ds.set(key, value) |
| 21 |
""" |
| 22 |
def __init__(self, filename, quotes=True, separator=' ', comment='#'): |
| 23 |
self.filename = os.path.abspath(filename) |
| 24 |
self.quotes = quotes |
| 25 |
self.separator = separator |
| 26 |
self.comment = comment |
| 27 |
self.lines = None |
| 28 |
self.stat = None |
| 29 |
|
| 30 |
def __enter__(self): |
| 31 |
with io.open(self.filename) as f: |
| 32 |
self.stat = os.fstat(f.fileno()) |
| 33 |
self.lines = list(f) |
| 34 |
return self |
| 35 |
|
| 36 |
def __exit__(self, exc_type, exc_val, exc_tb): |
| 37 |
if exc_type is not None: |
| 38 |
# something went wrong, reset |
| 39 |
self.lines = None |
| 40 |
self.stat = None |
| 41 |
return |
| 42 |
|
| 43 |
directory, prefix = os.path.split(self.filename) |
| 44 |
# use tempfile in same directory to have atomic rename |
| 45 |
fd, name = tempfile.mkstemp(prefix=prefix, dir=directory, text=True) |
| 46 |
with io.open(fd, mode='w', closefd=True) as f: |
| 47 |
for line in self.lines: |
| 48 |
if not isinstance(line, str): |
| 49 |
line = line.decode('utf-8') |
| 50 |
f.write(line) |
| 51 |
self.lines = None |
| 52 |
os.fchmod(f.fileno(), stat.S_IMODE(self.stat.st_mode)) |
| 53 |
os.fchown(f.fileno(), self.stat.st_uid, self.stat.st_gid) |
| 54 |
self.stat = None |
| 55 |
# flush and sync tempfile inode |
| 56 |
f.flush() |
| 57 |
os.fsync(f.fileno()) |
| 58 |
|
| 59 |
# rename file and sync directory inode |
| 60 |
os.rename(name, self.filename) |
| 61 |
dirfd = os.open(directory, os.O_RDONLY | os.O_DIRECTORY) |
| 62 |
try: |
| 63 |
os.fsync(dirfd) |
| 64 |
finally: |
| 65 |
os.close(dirfd) |
| 66 |
|
| 67 |
def set(self, directive, value, quotes=_SENTINEL, separator=_SENTINEL, |
| 68 |
comment=_SENTINEL): |
| 69 |
"""Set a single directive |
| 70 |
""" |
| 71 |
if quotes is _SENTINEL: |
| 72 |
quotes = self.quotes |
| 73 |
if separator is _SENTINEL: |
| 74 |
separator = self.separator |
| 75 |
if comment is _SENTINEL: |
| 76 |
comment = self.comment |
| 77 |
# materialize lines |
| 78 |
# set_directive_lines() modify item, shrink or enlage line count |
| 79 |
self.lines = list(set_directive_lines( |
| 80 |
quotes, separator, directive, value, self.lines, comment |
| 81 |
)) |
| 82 |
|
| 83 |
def setitems(self, items): |
| 84 |
"""Set multiple directives from a dict or list with key/value pairs |
| 85 |
""" |
| 86 |
if isinstance(items, dict): |
| 87 |
# dict-like, use sorted for stable order |
| 88 |
items = sorted(items.items()) |
| 89 |
for k, v in items: |
| 90 |
self.set(k, v) |
| 91 |
|
| 92 |
|
| 93 |
def set_directive(filename, directive, value, quotes=True, separator=' ', |
| 94 |
comment='#'): |
| 95 |
"""Set a name/value pair directive in a configuration file. |
| 96 |
|
| 97 |
A value of None means to drop the directive. |
| 98 |
|
| 99 |
Does not tolerate (or put) spaces around the separator. |
| 100 |
|
| 101 |
:param filename: input filename |
| 102 |
:param directive: directive name |
| 103 |
:param value: value of the directive |
| 104 |
:param quotes: whether to quote `value` in double quotes. If true, then |
| 105 |
any existing double quotes are first escaped to avoid |
| 106 |
unparseable directives. |
| 107 |
:param separator: character serving as separator between directive and |
| 108 |
value. Correct value required even when dropping a directive. |
| 109 |
:param comment: comment character for the file to keep new values near |
| 110 |
their commented-out counterpart |
| 111 |
""" |
| 112 |
st = os.stat(filename) |
| 113 |
with open(filename, 'r') as f: |
| 114 |
lines = list(f) # read the whole file |
| 115 |
# materialize new list |
| 116 |
new_lines = list(set_directive_lines( |
| 117 |
quotes, separator, directive, value, lines, comment |
| 118 |
)) |
| 119 |
with open(filename, 'w') as f: |
| 120 |
# don't construct the whole string; write line-wise |
| 121 |
for line in new_lines: |
| 122 |
f.write(line) |
| 123 |
os.chown(filename, st.st_uid, st.st_gid) # reset perms |
| 124 |
|
| 125 |
|
| 126 |
def set_directive_lines(quotes, separator, k, v, lines, comment): |
| 127 |
"""Set a name/value pair in a configuration (iterable of lines). |
| 128 |
|
| 129 |
Replaces the value of the key if found, otherwise adds it at |
| 130 |
end. If value is ``None``, remove the key if found. |
| 131 |
|
| 132 |
Takes an iterable of lines (with trailing newline). |
| 133 |
Yields lines (with trailing newline). |
| 134 |
|
| 135 |
""" |
| 136 |
new_line = "" |
| 137 |
if v is not None: |
| 138 |
v_quoted = quote_directive_value(v, '"') if quotes else v |
| 139 |
new_line = ''.join([k, separator, v_quoted, '\n']) |
| 140 |
|
| 141 |
# Special case: consider space as "whitespace" so tabs are allowed |
| 142 |
if separator == ' ': |
| 143 |
separator = '[ \t]+' |
| 144 |
|
| 145 |
found = False |
| 146 |
addnext = False # add on next line, found a comment |
| 147 |
matcher = re.compile(r'\s*{}\s*{}'.format(re.escape(k), separator)) |
| 148 |
cmatcher = re.compile(r'\s*{}\s*{}\s*{}'.format(comment, |
| 149 |
re.escape(k), separator)) |
| 150 |
for line in lines: |
| 151 |
if matcher.match(line): |
| 152 |
found = True |
| 153 |
addnext = False |
| 154 |
if v is not None: |
| 155 |
yield new_line |
| 156 |
elif addnext: |
| 157 |
found = True |
| 158 |
addnext = False |
| 159 |
yield new_line |
| 160 |
yield line |
| 161 |
elif cmatcher.match(line): |
| 162 |
addnext = True |
| 163 |
yield line |
| 164 |
else: |
| 165 |
yield line |
| 166 |
|
| 167 |
if not found and v is not None: |
| 168 |
yield new_line |
| 169 |
|
| 170 |
|
| 171 |
def get_directive(filename, directive, separator=' '): |
| 172 |
""" |
| 173 |
A rather inefficient way to get a configuration directive. |
| 174 |
|
| 175 |
:param filename: input filename |
| 176 |
:param directive: directive name |
| 177 |
:param separator: separator between directive and value |
| 178 |
|
| 179 |
:returns: The (unquoted) value if the directive was found, None otherwise |
| 180 |
""" |
| 181 |
# Special case: consider space as "whitespace" so tabs are allowed |
| 182 |
if separator == ' ': |
| 183 |
separator = '[ \t]+' |
| 184 |
|
| 185 |
if directive is None: |
| 186 |
return None |
| 187 |
|
| 188 |
result = None |
| 189 |
with open(filename, "r") as fd: |
| 190 |
for line in fd: |
| 191 |
if line.lstrip().startswith(directive): |
| 192 |
line = line.strip() |
| 193 |
|
| 194 |
match = re.match( |
| 195 |
r'{}\s*{}\s*(.*)'.format(directive, separator), line) |
| 196 |
if match: |
| 197 |
value = match.group(1) |
| 198 |
else: |
| 199 |
continue |
| 200 |
|
| 201 |
result = unquote_directive_value(value.strip(), '"') |
| 202 |
result = result.strip(' ') |
| 203 |
break |
| 204 |
return result |
| 205 |
|
| 206 |
|
| 207 |
def quote_directive_value(value, quote_char): |
| 208 |
"""Quote a directive value |
| 209 |
:param value: string to quote |
| 210 |
:param quote_char: character which is used for quoting. All prior |
| 211 |
occurences will be escaped before quoting to avoid unparseable value. |
| 212 |
:returns: processed value |
| 213 |
""" |
| 214 |
if value.startswith(quote_char) and value.endswith(quote_char): |
| 215 |
return value |
| 216 |
|
| 217 |
return "{quote}{value}{quote}".format( |
| 218 |
quote=quote_char, |
| 219 |
value="".join(escape_seq(quote_char, value)) |
| 220 |
) |
| 221 |
|
| 222 |
|
| 223 |
def unquote_directive_value(value, quote_char): |
| 224 |
"""Unquote a directive value |
| 225 |
:param value: string to unquote |
| 226 |
:param quote_char: character to strip. All escaped occurences of |
| 227 |
`quote_char` will be uncescaped during processing |
| 228 |
:returns: processed value |
| 229 |
""" |
| 230 |
unescaped_value = "".join(unescape_seq(quote_char, value)) |
| 231 |
if (unescaped_value.startswith(quote_char) and |
| 232 |
unescaped_value.endswith(quote_char)): |
| 233 |
return unescaped_value[1:-1] |
| 234 |
|
| 235 |
return unescaped_value |