2
0
mirror of https://gitlab.com/apparmor/apparmor synced 2025-09-09 02:35:15 +00:00
Files
apparmor/lib/config.py

84 lines
2.9 KiB
Python
Raw Normal View History

2013-06-01 15:37:31 +05:30
import os
import re
import stat
confdir = '/etc/apparmor'
cfg = None
repo_cfg = None
def read_config(filename):
"""Reads the file and returns a double dictionary config[section][attribute]=property"""
config = dict()
regex_label = re.compile('^\[(\S+)\]')
regex_value = re.compile('^\s*(\S+)\s*=\s*(.*)\s*$')
filepath = confdir + '/' + filename
try:
conf_file = open(filepath, 'r', 1)
2013-06-01 15:56:56 +05:30
except IOError:
2013-06-01 15:37:31 +05:30
pass
else:
section = '' # The default section
for line in conf_file:
# Ignore the comment lines
if line.lstrip().startswith('#'):
continue
line = line.rstrip('\n')
# Search for a new section
label_match = regex_label.search(line)
if label_match:
section = label_match.groups()[0]
else:
# Search for a attribute value pair
value_match = regex_value.search(line)
if value_match:
attribute = value_match.groups()[0]
value = value_match.groups()[1]
# A doubly nested dictionary
config[section] = config.get(section, {})
config[section][attribute] = value
conf_file.close()
# LP: Bug #692406
# Explicitly disabled repository
if filename == "repository.conf":
2013-06-01 16:01:56 +05:30
config['repository'] = {'enabled':'no'}
2013-06-01 15:37:31 +05:30
return config
def write_config(filename, config):
"""Writes the given configuration to the specified file"""
filepath = confdir + '/' + filename
try:
conf_file = open(filepath, 'w')
2013-06-01 15:56:56 +05:30
except IOError:
2013-06-01 15:37:31 +05:30
raise IOError("Unable to write to %s"%filename)
else:
2013-06-01 16:10:00 +05:30
for section in sorted(config.keys()):
2013-06-01 15:37:31 +05:30
# Write the section and all attributes and values under the section
conf_file.write("[%s]\n"%section)
2013-06-01 16:10:00 +05:30
for attribute in sorted(config[section].keys()):
2013-06-01 15:37:31 +05:30
conf_file.write(" %s = %s\n"%(attribute, config[section][attribute]))
permission_600 = stat.S_IRUSR | stat.S_IWUSR # Owner read and write
# Set file permissions as 0600
os.chmod(filepath, permission_600)
conf_file.close()
def find_first_file(file_list):
"""Returns name of first matching file None otherwise"""
# I don't understand why it searches the CWD, maybe I'll find out about it in some module
filename = None
if len(file_list):
for file in file_list.split():
if os.path.isfile(file):
filename = file
break
return filename
def find_first_dir(dir_list):
"""Returns name of first matching directory None otherwise"""
dirname = None
if (len(dir_list)):
for direc in dir_list.split():
if os.path.isdir(direc):
dirname = direc
break
return dirname