INHERIT_FD is needed for connect-drop to work
[tails.git] / config / chroot_local-includes / usr / lib / python3 / dist-packages / tailslib / userenv.py
blob3709d50ffc1e62f262599a842f116d2bc7e110b2
1 #!/usr/bin/python3
2 import sys
3 from functools import lru_cache
4 import os
5 from pathlib import Path
6 import pwd
7 from typing import Mapping
9 ENV_VARS_TO_DUMP = [
10 "DBUS_SESSION_BUS_ADDRESS",
11 "DISPLAY",
12 "LANG",
13 "WAYLAND_DISPLAY",
14 "XAUTHORITY",
15 "XDG_RUNTIME_DIR",
16 "XDG_CURRENT_DESKTOP",
19 ALLOWED_ENV_VARS = ENV_VARS_TO_DUMP + [
20 "DESKTOP_STARTUP_ID",
21 "INHERIT_FD",
24 USER_ENV_FILE_TEMPLATE = "/run/user/{uid}/user-env"
27 def user_env_file(uid):
28 return USER_ENV_FILE_TEMPLATE.format(uid=uid)
31 def allowed_env(env: Mapping) -> dict:
32 """
33 >>> allowed_env({"PATH": "/home/", "LANG": "en"})
34 {'LANG': 'en'}
35 """
36 return {key: value for key, value in env.items() if key in ALLOWED_ENV_VARS}
39 def read_allowed_env_from_file(envfile: str) -> dict:
40 env = dict()
42 for line in Path(envfile).read_text().split('\0'):
43 if not line:
44 continue
46 try:
47 key, value = line.split("=", 1)
48 except Exception as e:
49 print(f"Invalid environment variable: '{line}'", file=sys.stderr)
50 raise e
52 env[key] = value
54 return allowed_env(env)
57 @lru_cache(maxsize=1)
58 def read_user_env(user=None) -> dict:
59 if user is None:
60 uid = os.geteuid()
61 else:
62 uid = pwd.getpwnam(user).pw_uid
64 return read_allowed_env_from_file(user_env_file(uid))
67 def user_env_vars(user=None) -> list:
68 return [f"{key}={value}" for key, value in read_user_env(user).items()]