diff --git a/simple_backup/simple_backup.py b/simple_backup/simple_backup.py index b60732b..99b333f 100755 --- a/simple_backup/simple_backup.py +++ b/simple_backup/simple_backup.py @@ -12,8 +12,10 @@ Classes: """ # Import libraries +import traceback import sys import os +import pwd from typing import Callable, List, Optional, ParamSpec, TypeVar, Union import warnings from functools import wraps @@ -813,26 +815,46 @@ def _read_config(config_file, user: Optional[str] = None): return config_args -def _notify(text: str) -> None: +def _target_uid() -> int | None: euid = os.geteuid() - if euid == 0: - uid = os.getenv('SUDO_UID') - else: - uid = euid + if euid != 0: + return euid + + if (val := os.getenv('SUDO_UID')) is not None: + return int(val) + + if (name := os.getenv('DOAS_USER')) is not None: + try: + return pwd.getpwnam(name).pw_uid + except KeyError: + return None + + return None + + +def _notify(text: str) -> None: + euid = os.geteuid() + uid = _target_uid() if uid is None: + print('notify: no target uid (neither SUDO_UID nor DOAS_USER set)', file=sys.stderr) + return - os.seteuid(int(uid)) - os.environ['DBUS_SESSION_BUS_ADDRESS'] = f'unix:path=/run/user/{uid}/bus' + os.seteuid(uid) - obj = dbus.SessionBus().get_object('org.freedesktop.Notifications', - '/org/freedesktop/Notifications') - obj = dbus.Interface(obj, 'org.freedesktop.Notifications') - obj.Notify('', 0, '', 'simple_backup', text, [], {'urgency': 1}, 10000) + try: + os.environ['DBUS_SESSION_BUS_ADDRESS'] = f'unix:path=/run/user/{uid}/bus' - os.seteuid(int(euid)) + obj = dbus.SessionBus().get_object('org.freedesktop.Notifications', + '/org/freedesktop/Notifications') + obj = dbus.Interface(obj, 'org.freedesktop.Notifications') + obj.Notify('simple_backup', 0, '', 'simple_backup', text, [], {'urgency': dbus.Byte(1)}, 10000) + except Exception: + traceback.print_exc() + finally: + os.seteuid(euid) def simple_backup() -> int: