+def drop_priviledges(dir, log_file):
+ """
+ Checks if we are running as root. If we are, attempt to drop
+ priviledges to the user who owns ``dir``, by re-calling
+ itself using sudo with exec, such that the new process subsumes our
+ current one. If ``log_file`` is passed, the file is chown'ed
+ to the user we are dropping priviledges to, so the subprocess
+ can write to it.
+ """
+ if os.getuid():
+ return
+ uid = util.get_dir_uid(dir)
+ if not uid:
+ return
+ args = []
+ for k,v in os.environ.items():
+ if k.startswith('WIZARD_') or k == "SSH_GSSAPI_NAME":
+ args.append("%s=%s" % (k,v))
+ args += sys.argv
+ logging.debug("Dropping priviledges")
+ if log_file: os.chown(log_file, uid, -1)
+ os.execlp('sudo', 'sudo', '-u', '#' + str(uid), *args)
+