summaryrefslogtreecommitdiff
path: root/targetcli/ui_root.py
diff options
context:
space:
mode:
Diffstat (limited to 'targetcli/ui_root.py')
-rw-r--r--targetcli/ui_root.py34
1 files changed, 28 insertions, 6 deletions
diff --git a/targetcli/ui_root.py b/targetcli/ui_root.py
index 26815bd..39e5ee9 100644
--- a/targetcli/ui_root.py
+++ b/targetcli/ui_root.py
@@ -95,6 +95,26 @@ class UIRoot(UINode):
else:
return False
+ def _create_dir(self, dirname):
+ '''
+ create directory with permissions 0o600 set
+ if directory already exists, set right perms
+ '''
+ mode = stat.S_IRUSR | stat.S_IWUSR # 0o600
+ if not os.path.exists(dirname):
+ umask = 0o777 ^ mode # Prevents always downgrading umask to 0
+ umask_original = os.umask(umask)
+ try:
+ os.makedirs(dirname, mode)
+ except OSError as exe:
+ raise ExecutionError("Cannot create directory [%s] %s."
+ % (dirname, exe.strerror))
+ finally:
+ os.umask(umask_original)
+ else:
+ if (os.stat(dirname).st_mode & 0o777) != mode:
+ os.chmod(dirname, mode)
+
def _save_backups(self, savefile):
'''
Take backup of config-file if needed.
@@ -109,12 +129,7 @@ class UIRoot(UINode):
backupfile = backup_dir + backup_name
backup_error = None
- if not os.path.exists(backup_dir):
- try:
- os.makedirs(backup_dir)
- except OSError as exe:
- raise ExecutionError("Cannot create backup directory [%s] %s."
- % (backup_dir, exe.strerror))
+ self._create_dir(backup_dir)
# Only save backups if savefile exits
if not os.path.exists(savefile):
@@ -125,12 +140,17 @@ class UIRoot(UINode):
# Save backup if backup dir is empty, or savefile is differnt from recent backup copy
if not backed_files_list or not self._compare_files(backed_files_list[-1], savefile):
+ mode = stat.S_IRUSR | stat.S_IWUSR # 0o600
+ umask = 0o777 ^ mode # Prevents always downgrading umask to 0
+ umask_original = os.umask(umask)
try:
with open(savefile, 'rb') as f_in, gzip.open(backupfile, 'wb') as f_out:
shutil.copyfileobj(f_in, f_out)
f_out.flush()
except IOError as ioe:
backup_error = ioe.strerror or "Unknown error"
+ finally:
+ os.umask(umask_original)
if backup_error == None:
# remove excess backups
@@ -167,6 +187,8 @@ class UIRoot(UINode):
savefile = os.path.expanduser(savefile)
+ save_dir = os.path.dirname(savefile)
+ self._create_dir(save_dir)
self._save_backups(savefile)
self.rtsroot.save_to_file(savefile)