import os
import tempfile
SOCKET_PATH_MAX = 107
DBUS_SOCKET_PATH_MAX = 99
DBUS_TMPDIR_SOCKET = 'dbus-' + 'X' * 10
INDICATOR_SOCKET = 'computer-use-linux-indicator.sock'
TEMPDIR_NAME = 'tmp' + 'X' * 8
def socket_tempdir(prefix, sockets, bus_dir=None, dir=None):
name = prefix + 'X' * 8
checks = [(path, SOCKET_PATH_MAX) for path in sockets]
if bus_dir is not None:
checks.append((os.path.join(bus_dir, DBUS_TMPDIR_SOCKET), DBUS_SOCKET_PATH_MAX))
def overflow(base):
for relative, limit in checks:
path = os.path.join(base, name, relative)
length = len(os.fsencode(path))
if length > limit:
return f'{path} is {length} bytes, over the {limit}-byte limit'
return None
base = tempfile.gettempdir() if dir is None else os.fspath(dir)
first = overflow(base)
if first is None:
return tempfile.TemporaryDirectory(prefix=prefix, dir=base)
runtime = os.environ.get('XDG_RUNTIME_DIR', '')
if os.path.isabs(runtime) and os.path.isdir(runtime):
second = overflow(runtime)
if second is None:
return tempfile.TemporaryDirectory(prefix=prefix, dir=runtime)
fallback = f'under XDG_RUNTIME_DIR, {second}'
elif runtime:
fallback = f'XDG_RUNTIME_DIR ({runtime}) is not an absolute directory'
else:
fallback = 'XDG_RUNTIME_DIR is unset'
remedy = 'Set TMPDIR' if dir is None else f'Move {base}'
raise SystemExit(f'Unix socket path too long: {first}; {fallback}. '
f'{remedy} or XDG_RUNTIME_DIR to a shorter path.')