installutils: improve directive value parsing in get_directive

`get_directive` value parsing was improved in order to bring its logic
more in-line to changes in `set_directive`: a specified quoting
character is now unquoted and stripped from the retrieved value. The
function will now also error out when malformed directive is
encountered.

https://fedorahosted.org/freeipa/ticket/6460

Reviewed-By: Tomas Krizek <tkrizek@redhat.com>
Reviewed-By: Petr Spacek <pspacek@redhat.com>
This commit is contained in:
Martin Babinsky 2016-12-16 13:34:57 +01:00
parent e1ed8b5eff
commit 517d43e78b

View File

@ -436,16 +436,31 @@ def set_directive(filename, directive, value, quotes=True, separator=' ',
fd.close()
os.chown(filename, st.st_uid, st.st_gid) # reset perms
def get_directive(filename, directive, separator=' '):
"""
A rather inefficient way to get a configuration directive.
:param filename: input filename
:param directive: directive name
:param separator: separator between directive and value
:param quote_char: the characters that are used in this particular config
file to quote values. This character will be stripped and unescaped
from the raw value.
:returns: The (unquoted) value if the directive was found, None otherwise
"""
fd = open(filename, "r")
for line in fd:
if line.lstrip().startswith(directive):
line = line.strip()
result = line.split(separator, 1)[1]
result = result.strip('"')
(directive, sep, value) = line.partition(separator)
if not sep or not value:
raise ValueError("Malformed directive: {}".format(line))
result = value.strip().strip(quote_char)
result = ipautil.unescape_seq(quote_char, result)[0]
result = result.strip(' ')
fd.close()
return result