#!/usr/bin/python3
# SPDX-License-Identifier: MIT
"""waydroid-plinius-setup: what Waydroid needs on the Volla Phone Plinius besides its own set-up.

Runs before the container service starts (ExecStartPre of waydroid-container.service, after the
HAL bridges):

1. /etc/gbinder.d/60-waydroid-anbox.conf: the protocols of the container's binder for the
   Android version of the system image, as Waydroid picks them for itself (its
   tools/helpers/protocol.py). The bridges are libgbinder clients that read this file when they
   start; if it changes, the running bridges start again.
2. The container's vendor overlay: a VINTF entry for each bridge that runs (Android waits forever
   at boot for a declared service that never registers), display_settings.xml, so that apps are
   no free-form windows with a caption bar of their own on the phone, and the vendor's
   libnfc-nci.conf, the settings of the phone's NFC controller for Android's NFC stack.
3. Android's display in waydroid.cfg: each app in a window of its own, and the size of the
   phone's screen in logical pixels between Phosh's top bar and home bar (Waydroid multiplies it
   by the scale). A size set there already stays.
4. The devices Android needs: its processes run as the same uids on the host, where udev gives
   ashmem, the system DMA heaps and the DRM device to root and video only. They get the modes of
   Android's own ueventd.rc (a DRM device in waydroid.cfg, for graphics in software, opens for
   everybody, as Waydroid opens its render nodes). Waydroid's own chmod 777 of every device is
   off on Halium (0001); permissions are only added here, never taken.
5. Graphics on the GPU, when the vendor has its graphics HALs (an AIDL allocator, a stable-C
   mapper, an EGL driver): the image passes the vendor's allocator through from the host's binder
   (0004), loads the vendor's mapper and EGL libraries from /vendor_extra and the host's EGL
   directory, and needs what Waydroid's own vendor image lacks for them: the EGL properties of the
   vendor (Mali builds its configs from ro.vendor.arm.*), the mapper and the driver's platform
   file in its /vendor, and the libraries the vendor's libraries link against that the image does
   not give them (from Halium's VNDK APEX): the AIDL libraries of a newer Android, and, with an
   image without VNDK (Android 15 and later), every library of the system beyond its LLNDK.
   An image without host-AIDL passthrough (WayDroid-ATV's Android 16) gets the vendor's allocator
   as a service in the container instead; Android 14 and later also need the stable-C mapper
   declared in VINTF, the GPU's capabilities (/vendor/etc/gralloc) and shared memory as memfd
   (they look for ashmem at /dev/ashmem<boot id>, which the container lacks). A vendor without a 32-bit EGL driver gets no graphics
   preloading in the zygotes (the 32-bit one aborted on it). hosthals.xml sends only the mapper to
   the host: the image's list sent media.c2 there too, which the host does not have, and the
   codecs of Android waited for it forever.
6. The vendor's cameras: a VINTF entry for each AIDL camera provider of the vendor (Android finds
   AIDL providers only by their declaration; the image passes the provider itself through from
   the host's binder), and, with a newer Android on Halium than in the image, Halium's
   libcamera_metadata: the vendor's metadata carries the newer Android's tags, which the older
   library rejects as malformed, leaving every camera without characteristics. The provider takes
   a callback per client, so Linux keeps its cameras; one camera is used by one side at a time.
7. What Waydroid's vendor image declares and starts for a HAL one of the bridges serves is hidden
   in the overlay (whiteouts): two declarations of one instance at different versions leave
   Android without a device manifest, so that no vendor service can register (Android 16's vendor
   image has an example IHealth, for one).

Without an initialised Waydroid (no waydroid.cfg) it does nothing.

With --containment (before every lxc-start, 0005) it does only this: Android's root is the
phone's root in a privileged container, so what it wrote over its system and vendor images
(overlay_rw, shared by every user of the phone) goes, and the container's configuration gets a
device filter
(the device nodes Waydroid binds in and the few Android makes itself; never a block device, the
device-mapper or the memory devices), the AppArmor profile plinius.waydroid, and loses the mounts
Android does without (debugfs, the vibrator in sysfs) and the capabilities to set the clock. If
the configuration is missing or the kernel does not have the profile loaded, it fails (and says
so in the journal), and the container does not start: unconfined, Android's root would be the
phone's root.

With --bind UID KIND PATH (as the container starts a session, 0007, 0011) it checks a path of
the user's that the container binds in (KIND data: Android's /data, a directory in one of the
user's; metadata: Android's /metadata, a directory of the user's; wayland, pulse: a socket of the
user's), opened from / down without following a link, and binds what it opened, through its
descriptor, to a mount of root's own under /run/waydroid-plinius/session, whose path it prints
(nothing for a path that is not the user's). lxc-start binds that mount, never the user's path:
resolved only then, the path could lead elsewhere by a link the user swapped in after the check.
--unbind (as the container stops) takes these mounts away again.

With --android-dir UID DATA (as the container starts a session, 0008) it gives the user
Android's internal storage (DCIM, Download, Pictures …) as ~/Android and prints root's mount of
that directory (as with --bind), which the container binds back as Android's /data/media/0;
without it, Android keeps its storage in the user's Waydroid data. The storage moves there once, from DATA/media/0, the first time
Android has made it, and keeps Android's owners (media_rw, MediaProvider): the user gets read
and write access through an ACL, again at every start (Android's vold sets the directory anew),
except to the app data of Android in ~/Android/Android, which .hidden hides from file managers.
Nothing is linked with the user's folders and nothing of Linux is scanned into Android's media.
Only a real directory of media_rw is taken, with no symbolic link on its way, and only from the
user's own Waydroid data. Each directory below the home is opened from the home down without
following a link and moved and given its ACL through its descriptor (setfacl on /proc/self/fd),
so a name the user swaps for a link meanwhile changes nothing outside.
"""

import configparser
import contextlib
import ctypes
import errno
import glob
import os
import pwd
import re
import shutil
import stat
import struct
import subprocess
import sys
import syslog
import tempfile

WAYDROID_CFG = "/var/lib/waydroid/waydroid.cfg"
OVERLAY = "/var/lib/waydroid/overlay"
GBINDER_CONF = "/etc/gbinder.d/60-waydroid-anbox.conf"
DATA = "/usr/share/waydroid-plinius"
VENDOR_ETC = "/vendor/etc"
VENDOR = "/vendor"
# Halium's running Android container holds the VNDK APEX of the vendor's Android version
VNDK_GLOB = "/proc/[0-9]*/root/apex/com.android.vndk.v%s/lib64"
# What the graphics set-up put into the overlay, to take it away again
GRAPHICS_STATE = "/var/lib/waydroid/plinius-graphics.list"
# The files of the vendor image the overlay hides, to show them again
HIDDEN_STATE = "/var/lib/waydroid/plinius-hidden.list"
HOSTHALS_MAPPER = """<hosthals version="1.0">
    <hal>
        <name>android.hardware.graphics.mapper</name>
        <priority>true</priority>
    </hal>
</hosthals>
"""
HOSTHALS_NONE = '<hosthals version="1.0">\n</hosthals>\n'
# Halium's Android system (lxc-android), its libraries and build properties
HALIUM_SYSTEM = "/android/system"
CAMERA_PROVIDER = "android.hardware.camera.provider"

# The bridges and the VINTF entry each one serves
BRIDGES = {
    "sensor-proxy-bridge.service": "plinius-sensors.xml",
    "gnss-nmea-bridge.service": "plinius-gnss.xml",
    "vibrator-ff-bridge.service": "plinius-vibrator.xml",
    "health-hal-bridge.service": "plinius-health.xml",
    "nfc-hal-bridge.service": "plinius-nfc.xml",
}

# Devices for Android and the mode bits it needs on them (AOSP's ueventd.rc)
DEVICE_MODES = {
    "/dev/ashmem": 0o666,  # shared memory of every Android process (the sensors' queues too)
    "/dev/dma_heap/system": 0o444,  # gralloc's buffers; opened read-only to allocate
    "/dev/dma_heap/system-uncached": 0o444,
}
# The DRM device of waydroid.cfg: SurfaceFlinger's and the apps' buffers (gbm)
DRM_MODE = 0o666

# The container's LXC configuration (Waydroid writes it on init and upgrade)
LXC_DIR = "/var/lib/waydroid/lxc/waydroid"
# The writable layer over Android's system and vendor images: shared by every user of the phone,
# so whatever Android's root wrote there in one session goes before the next one
OVERLAY_RW = "/var/lib/waydroid/overlay_rw"
# The profile that keeps Android's root inside the container (/usr/share/plinius-apparmor/
# profiles/plinius.waydroid) and the kernel's list of the loaded ones
APPARMOR_PROFILE = "plinius.waydroid"
APPARMOR_PROFILES = "/sys/kernel/security/apparmor/profiles"
# Mounts of Waydroid's list that Android does without: the kernel's debugfs (writable, the
# internals of the whole kernel) and the vibrator in sysfs (Android's vibrator is the bridge)
DROPPED_MOUNTS = {"sys/kernel/debug", "sys/class/leds/vibrator",
                  "sys/devices/virtual/timed_output/vibrator"}
# Capabilities of Waydroid's list that Android does without: setting the clock (seccomp turns it
# into a no-op already). Not syslog: without it vold failed and Android rebooted (measured
# 2026-11-28), so Android can read the phone's kernel log
DROPPED_CAPS = {"sys_time"}
# Devices Android makes in its own /dev and needs, besides the ones Waydroid binds in; every other
# device is closed to it (the device filter), block devices always: they are the phone's storage
FIXED_DEVICES = (
    "c 1:3 rwm",  # null
    "c 1:5 rwm",  # zero
    "c 1:7 rwm",  # full
    "c 1:8 rwm",  # random
    "c 1:9 rwm",  # urandom
    "c 1:11 wm",  # kmsg: Android's init and logd write to it; reading it shows the phone's kernel log
    "c 5:0 rwm",  # tty
    "c 5:2 rwm",  # ptmx
    "c 136:* rwm",  # the pseudo-terminals
)
# Character devices never given to Android, not even when bound in: they reach the phone's
# memory or storage (mem, kmem, port, device-mapper)
NEVER_DEVICES = {(1, 1), (1, 2), (1, 4), (10, 236)}
# Loop devices: Android 16 mounts its APEX modules through loop devices it sets up itself
# (loop-control, LOOP_CTL_GET_FREE, then /dev/block/loopN), so it gets loop-control and the
# lowest ANDROID_LOOPS loop devices that are free when the container starts, never one of the
# phone's own: those are set up by then (the phone's root file system, the modem's data, Halium's
# and Waydroid's images; Waydroid mounts its images before this runs), and some are writable.
# Android's ueventd makes the nodes of devices that were there before it only by writing "add" to
# their uevent files in sysfs, which the AppArmor profile refuses (it would replay every uevent of
# the phone), so loop-control and these loop devices come as bound nodes.
LOOP_CONTROL = "c 10:237 rwm"
LOOP_CONTROL_NODE = "/dev/loop-control"
LOOP_MAJOR = 7
ANDROID_LOOPS = 64
LOOP_CTL_ADD = 0x4C80
SYS_BLOCK = "/sys/block"
DEV = "/dev"

# The Plinius in portrait: 1080 x 2400 at Phosh's scale 2.265625 is 476 x 1059 logical pixels;
# the top bar takes 32 and the home bar 15 (PHOSH_TOP_BAR_HEIGHT, PHOSH_HOME_BAR_HEIGHT)
# Android's internal storage as ~/Android (--android-dir, 0008): Android's owner of it (media_rw),
# the user's Waydroid data it comes from, and the app data of Android inside it, which stay
# Android's own
AID_MEDIA_RW = 1023
ANDROID_DIR = "Android"
WAYDROID_DATA = ".local/share/waydroid/data"
ANDROID_APP_DATA = "Android"
SETFACL_BATCH = 200
# Root's own mounts of the paths of a session (--bind, --android-dir): what lxc-start binds into
# the container instead of the user's paths. Each kind of path once, made anew for every session.
SESSION_BINDS = "/run/waydroid-plinius/session"
# What each kind of path must be: "dir" or "socket", and whose it must be: "own" the user's,
# "parent" in a directory of the user's (Android's /data belongs to Android's system user)
BIND_KINDS = {
    "data": ("dir", "parent"),
    "metadata": ("dir", "own"),
    "wayland": ("socket", "own"),
    "pulse": ("socket", "own"),
}
MS_BIND = 0x1000
MS_REC = 0x4000
MNT_DETACH = 0x2
UMOUNT_NOFOLLOW = 0x8
DISPLAY_WIDTH = 476
DISPLAY_HEIGHT = 1059 - 32 - 15


def protocols(api):
    """(binder protocol, service manager protocol) for an Android API level, as Waydroid's
    set_aidl_version() picks them."""
    if api < 28:
        return "aidl", "aidl"
    if api < 30:
        return "aidl2", "aidl2"
    if api < 31:
        return "aidl3", "aidl3"
    if api < 33:
        return "aidl4", "aidl3"
    if api < 35:
        return "aidl3", "aidl3"
    if api < 36:
        return "aidl3", "aidl5"
    return "aidl3", "aidl6"


def load_cfg():
    cfg = configparser.ConfigParser()
    cfg.optionxform = str  # property names keep their case
    if not cfg.read(WAYDROID_CFG):
        return None
    return cfg


def read_prop(path, name):
    try:
        with open(path, errors="replace") as f:
            for line in f:
                key, sep, value = line.strip().partition("=")
                if sep and key == name:
                    return value
    except OSError:
        pass
    return None


@contextlib.contextmanager
def mounted(image):
    """An image of Waydroid's, mounted read-only; None if there is none or it cannot be mounted."""
    if not os.path.isfile(image):
        yield None
        return
    with tempfile.TemporaryDirectory(prefix="waydroid-plinius-") as mnt:
        if subprocess.run(["mount", "-o", "ro,loop", image, mnt], stderr=subprocess.DEVNULL).returncode:
            yield None
            return
        try:
            yield mnt
        finally:
            subprocess.run(["umount", mnt], stderr=subprocess.DEVNULL)


def image_path(cfg, name):
    return os.path.join(cfg.get("waydroid", "images_path", fallback=""), name)


def image_api(cfg):
    """The API level of the system image (ro.build.version.sdk); None if it cannot be read."""
    with mounted(image_path(cfg, "system.img")) as mnt:
        value = read_prop(os.path.join(mnt, "system", "build.prop"), "ro.build.version.sdk") if mnt else None
    try:
        return int(value)
    except (TypeError, ValueError):
        return None


def gbinder_text(api):
    binder, sm = protocols(api)
    return ("# Written by waydroid-plinius-setup for the system image (Android API %d)\n"
            "[Protocol]\n/dev/anbox-binder = %s\n[ServiceManager]\n/dev/anbox-binder = %s\n" % (api, binder, sm))


def write_if_changed(path, text):
    """Writes text to path (atomically) unless it holds that already; True if it changed."""
    try:
        with open(path) as f:
            if f.read() == text:
                return False
    except OSError:
        pass
    os.makedirs(os.path.dirname(path), exist_ok=True)
    tmp = path + ".new"
    with open(tmp, "w") as f:
        f.write(text)
    os.chmod(tmp, 0o644)
    os.replace(tmp, path)
    return True


def is_active(unit):
    return subprocess.run(["systemctl", "is-active", "-q", unit]).returncode == 0


def setup_gbinder(api):
    if api is None:
        print("No readable system image: the binder protocols stay as they are")
        return
    if write_if_changed(GBINDER_CONF, gbinder_text(api)):
        print("Binder protocols for Android API %d: %s, %s" % ((api,) + protocols(api)))
        # The bridges read it when they start
        subprocess.run(["systemctl", "try-restart"] + list(BRIDGES))


def setup_overlay():
    manifests = os.path.join(OVERLAY, "vendor", "etc", "vintf", "manifest")
    os.makedirs(manifests, exist_ok=True)
    for unit, name in BRIDGES.items():
        target = os.path.join(manifests, name)
        if is_active(unit):
            shutil.copyfile(os.path.join(DATA, "vintf", name), target)
            os.chmod(target, 0o644)
        elif os.path.exists(target):
            os.unlink(target)
            print("%s does not run: %s left out" % (unit, name))
    target = os.path.join(OVERLAY, "vendor", "etc", "display_settings.xml")
    shutil.copyfile(os.path.join(DATA, "display_settings.xml"), target)
    os.chmod(target, 0o644)
    nfc = os.path.join(VENDOR_ETC, "libnfc-nci.conf")
    if os.path.isfile(nfc):
        target = os.path.join(OVERLAY, "vendor", "etc", "libnfc-nci.conf")
        shutil.copyfile(nfc, target)
        os.chmod(target, 0o644)


def aidl_hals(path):
    """The AIDL HALs a VINTF manifest declares: {(name, "IFoo/instance")}; empty if unreadable."""
    import xml.etree.ElementTree as ET
    try:
        root = ET.parse(path).getroot()
    except (OSError, ET.ParseError):
        return set()
    hals = set()
    for hal in root.iter("hal"):
        if hal.get("format") != "aidl":
            continue
        name = hal.findtext("name")
        for iface in hal.iter("interface"):
            for inst in iface.iter("instance"):
                hals.add((name, "%s/%s" % (iface.findtext("name"), inst.text)))
        for fq in hal.iter("fqname"):
            hals.add((name, fq.text))
    return hals


def rc_hals(path):
    """The AIDL HALs the services of an init script serve: {(name, "IFoo/instance")}."""
    hals = set()
    try:
        with open(path, errors="replace") as f:
            for line in f:
                m = re.match(r"\s*interface\s+aidl\s+(\S+)\.(I\w+)/(\S+)", line)
                if m:
                    hals.add((m.group(1), "%s/%s" % (m.group(2), m.group(3))))
    except OSError:
        pass
    return hals


def hide(path):
    """An overlayfs whiteout at path: the file of the image below is gone in the container."""
    os.makedirs(os.path.dirname(path), exist_ok=True)
    if os.path.lexists(path):
        os.unlink(path)
    os.mknod(path, stat.S_IFCHR | 0o644, os.makedev(0, 0))


def setup_conflicts(cfg):
    """Hides what Waydroid's vendor image declares and starts for a HAL one of our bridges serves
    (its VINTF fragment and its service): a second declaration of the same instance at another
    version leaves Android without a device manifest, and every vendor service fails to register
    (Android 16's vendor image has an example IHealth, for one)."""
    manifests = os.path.join(OVERLAY, "vendor", "etc", "vintf", "manifest")
    ours = set()
    for name in list(BRIDGES.values()) + ["plinius-camera.xml"]:
        ours |= aidl_hals(os.path.join(manifests, name))
    hidden = set()
    with mounted(image_path(cfg, "vendor.img")) as mnt:
        if mnt and ours:
            for path in sorted(glob.glob(os.path.join(mnt, "etc", "vintf", "manifest", "*.xml"))):
                declared = aidl_hals(path)
                if declared & ours:
                    if declared <= ours:
                        hidden.add(os.path.join("vendor", "etc", "vintf", "manifest", os.path.basename(path)))
                    else:
                        print("%s declares more than a bridge serves: kept" % os.path.basename(path))
            # A service names what it serves (interface aidl …), or its init script is named as
            # its manifest (AOSP's convention: android.hardware.health-service.example.rc)
            manifests_hidden = {os.path.splitext(os.path.basename(rel))[0] for rel in hidden}
            for path in sorted(glob.glob(os.path.join(mnt, "etc", "init", "*.rc"))):
                served = rc_hals(path)
                name = os.path.splitext(os.path.basename(path))[0]
                if (served and served <= ours) or (not served and name in manifests_hidden):
                    hidden.add(os.path.join("vendor", "etc", "init", os.path.basename(path)))
    try:
        with open(HIDDEN_STATE) as f:
            before = {line.strip() for line in f if line.strip()}
    except OSError:
        before = set()
    for rel in sorted(before - hidden):
        path = os.path.join(OVERLAY, rel)
        if os.path.lexists(path) and not os.path.isfile(path):
            os.unlink(path)
    for rel in sorted(hidden - before):
        hide(os.path.join(OVERLAY, rel))
        print("Hidden for a bridge: %s of the vendor image" % rel)
    with open(HIDDEN_STATE, "w") as f:
        f.write("".join(rel + "\n" for rel in sorted(hidden)))


def properties(cfg):
    if not cfg.has_section("properties"):
        cfg.add_section("properties")
    return cfg["properties"]


def setup_display(cfg):
    """Each app in a window of its own and the display size into the properties; True if they
    changed."""
    props = properties(cfg)
    changed = False
    if "persist.waydroid.multi_windows" not in props:
        props["persist.waydroid.multi_windows"] = "true"
        changed = True
    if "persist.waydroid.width" in props or "persist.waydroid.height" in props:
        return changed
    props["persist.waydroid.width"] = str(DISPLAY_WIDTH)
    props["persist.waydroid.height"] = str(DISPLAY_HEIGHT)
    print("Android's display: %d x %d logical pixels" % (DISPLAY_WIDTH, DISPLAY_HEIGHT))
    return True


def vendor_props():
    """The build properties of the phone's vendor partition."""
    props = {}
    for path in [os.path.join(VENDOR, "build.prop"), os.path.join(VENDOR, "default.prop")] + \
            sorted(glob.glob(os.path.join(VENDOR, "etc", "*.prop"))):
        try:
            with open(path, errors="replace") as f:
                for line in f:
                    key, sep, value = line.strip().partition("=")
                    if sep and not key.startswith("#"):
                        props.setdefault(key, value)
        except OSError:
            pass
    return props


def elf_needed(path):
    """The DT_NEEDED entries of a 64-bit little-endian ELF file; [] if it is none."""
    try:
        with open(path, "rb") as f:
            data = f.read()
    except OSError:
        return []
    if data[:4] != b"\x7fELF" or data[4] != 2 or data[5] != 1:
        return []
    shoff, = struct.unpack_from("<Q", data, 0x28)
    shentsize, shnum = struct.unpack_from("<HH", data, 0x3a)
    sections = [struct.unpack_from("<IIQQQQIIQQ", data, shoff + i * shentsize) for i in range(shnum)]
    needed = []
    for _name, kind, _flags, _addr, offset, size, link, _info, _align, entsize in sections:
        if kind != 6 or not entsize:  # SHT_DYNAMIC
            continue
        strtab = sections[link][4]
        for pos in range(offset, offset + size, entsize):
            tag, value = struct.unpack_from("<qQ", data, pos)
            if tag == 0:
                break
            if tag == 1:  # DT_NEEDED
                end = data.index(b"\0", strtab + value)
                needed.append(data[strtab + value:end].decode())
    return needed


def vndk_lib64(vndk):
    """lib64 of Halium's VNDK APEX for the vendor's Android version; None if not to be found."""
    for path in sorted(glob.glob(VNDK_GLOB % vndk)):
        if os.path.isdir(path):
            return path
    return None


def image_libs(cfg):
    """The names of the libraries of Waydroid's images that the vendor's libraries may link
    against (64-bit): the vendor image's, and of the system image those of its VNDK APEX (with one,
    as up to Android 14: every library in system/lib64) or else only its LLNDK libraries (Android
    15 and later have no VNDK; a vendor library finds no other library of the system)."""
    names = set()
    with mounted(image_path(cfg, "vendor.img")) as mnt:
        if mnt:
            for _root, _dirs, files in os.walk(os.path.join(mnt, "lib64")):
                names.update(files)
    with mounted(image_path(cfg, "system.img")) as mnt:
        if mnt:
            llndk = os.path.join(mnt, "system", "etc", "llndk.libraries.txt")
            if glob.glob(os.path.join(mnt, "system", "apex", "com.android.vndk*")) or not os.path.isfile(llndk):
                for _root, _dirs, files in os.walk(os.path.join(mnt, "system", "lib64")):
                    names.update(files)
            else:
                with open(llndk) as f:
                    names.update(line.strip() for line in f if line.strip())
    return names


def vendor_lib(name):
    """A library of the phone's vendor by name (lib64 and its subdirectories); None if none."""
    for root, _dirs, files in os.walk(os.path.join(VENDOR, "lib64")):
        if name in files:
            return os.path.join(root, name)
    return None


def missing_libraries(cfg, roots, vndk_dir):
    """The libraries the vendor's graphics libraries need beyond the images and the vendor
    itself, found in Halium's VNDK APEX: {name: path}; and the names found nowhere."""
    have = image_libs(cfg)
    todo, seen, found, unknown = list(roots), set(), {}, []
    while todo:
        path = todo.pop()
        for name in elf_needed(path):
            if name in seen or name in have:
                continue
            seen.add(name)
            source = vendor_lib(name)
            if source is None and vndk_dir and os.path.isfile(os.path.join(vndk_dir, name)):
                source = found[name] = os.path.join(vndk_dir, name)
            if source:
                todo.append(source)
            else:
                unknown.append(name)
    return found, sorted(unknown)


def host_aidl(cfg):
    """Whether the system image passes AIDL services through from the host's binder (Waydroid's
    own images up to Android 13: /system/etc/hostaidls.conf); False if it cannot be read."""
    with mounted(image_path(cfg, "system.img")) as mnt:
        return bool(mnt) and os.path.isfile(os.path.join(mnt, "system", "etc", "hostaidls.conf"))


def vendor_allocator():
    """The vendor's AIDL allocator service of the highest version (its file), or None."""
    best = None
    for path in glob.glob(os.path.join(VENDOR, "bin", "hw", "android.hardware.graphics.allocator-V*-service*")):
        m = re.search(r"allocator-V(\d+)-service[^.]*$", os.path.basename(path))
        if m and (best is None or int(m.group(1)) > best[0]):
            best = (int(m.group(1)), path)
    return best[1] if best else None


def vendor_manifests(match):
    """The vendor's VINTF fragments for which match(path) holds."""
    return [path for path in sorted(glob.glob(os.path.join(VENDOR, "etc", "vintf", "manifest", "*.xml")))
            if match(path)]


def native_mapper(path):
    try:
        with open(path, errors="replace") as f:
            text = f.read()
    except OSError:
        return False
    return re.search(r'<hal\s+format="native">\s*<name>mapper</name>', text) is not None


ALLOCATOR_RC = """# Written by waydroid-plinius-setup: the vendor's graphics allocator in the container (the
# system image does not pass it through from the host)
service vendor.plinius-allocator /vendor/bin/hw/%s
    class hal animation
    user system
    group graphics drmrpc
    capabilities SYS_NICE
    onrestart restart surfaceflinger
"""


def graphics_libs():
    """The vendor's graphics libraries: EGL driver, mapper and their libraries; [] without an
    AIDL allocator, a stable-C mapper or an EGL driver."""
    allocators = glob.glob(os.path.join(VENDOR, "bin", "hw", "android.hardware.graphics.allocator-V*-service*"))
    mappers = sorted(glob.glob(os.path.join(VENDOR, "lib64", "hw", "mapper.*.so")))
    egl = sorted(glob.glob(os.path.join(VENDOR, "lib64", "egl", "**", "*.so"), recursive=True))
    if not (allocators and mappers and egl):
        return [], []
    return mappers, egl


def place(path, target=None, source=None):
    """A symbolic link to target or a copy of source at path in the overlay."""
    os.makedirs(os.path.dirname(path), exist_ok=True)
    if target is not None:
        if os.path.islink(path) and os.readlink(path) == target:
            return
        if os.path.lexists(path):
            os.unlink(path)
        os.symlink(target, path)
        return
    if os.path.islink(path):
        os.unlink(path)
    shutil.copyfile(source, path)
    os.chmod(path, 0o644)


def setup_graphics(cfg, api=0):
    """GPU graphics through the vendor's HALs (see above); True if waydroid.cfg changed."""
    try:
        with open(GRAPHICS_STATE) as f:
            before = set(f.read().split())
    except OSError:
        before = set()
    mappers, egl = graphics_libs()
    placed = set()
    hosthals = HOSTHALS_NONE
    changed = False
    if mappers:
        vprops = vendor_props()
        vndk_dir = vndk_lib64(vprops.get("ro.vndk.version", ""))
        allocator = None if host_aidl(cfg) else vendor_allocator()
        roots = mappers + egl + ([os.path.realpath(allocator)] if allocator else [])
        found, unknown = missing_libraries(cfg, roots, vndk_dir)
        for name, source in sorted(found.items()):
            rel = os.path.join("vendor", "lib64", name)
            place(os.path.join(OVERLAY, rel), source=source)
            placed.add(rel)
        if unknown:
            print("Libraries of the vendor's graphics found nowhere: %s" % " ".join(unknown))
        # The stable-C mapper and the driver's platform file, where the vendor's libraries look
        for mapper in mappers:
            rel = os.path.join("vendor", "lib64", "hw", os.path.basename(mapper))
            place(os.path.join(OVERLAY, rel), target=os.path.join("/vendor_extra", "lib64", "hw", os.path.basename(mapper)))
            placed.add(rel)
        if os.path.isfile(os.path.join(VENDOR, "etc", "mali_platform.config")):
            rel = os.path.join("vendor", "etc", "mali_platform.config")
            place(os.path.join(OVERLAY, rel), target="/vendor_extra/etc/mali_platform.config")
            placed.add(rel)
        # The capabilities of the GPU and the display the allocator and mapper read
        if os.path.isdir(os.path.join(VENDOR, "etc", "gralloc")):
            rel = os.path.join("vendor", "etc", "gralloc")
            place(os.path.join(OVERLAY, rel), target="/vendor_extra/etc/gralloc")
            placed.add(rel)
        # Android 14 and later load a stable-C mapper only if VINTF declares it
        for path in vendor_manifests(native_mapper):
            rel = os.path.join("vendor", "etc", "vintf", "manifest", "plinius-" + os.path.basename(path))
            place(os.path.join(OVERLAY, rel), source=path)
            placed.add(rel)
        # Without the host's allocator passed through, the vendor's runs in the container
        if allocator:
            name = os.path.basename(allocator)
            rel = os.path.join("vendor", "bin", "hw", name)
            place(os.path.join(OVERLAY, rel), source=os.path.realpath(allocator))
            os.chmod(os.path.join(OVERLAY, rel), 0o755)
            placed.add(rel)
            rel = os.path.join("vendor", "etc", "init", "plinius-allocator.rc")
            write_if_changed(os.path.join(OVERLAY, rel), ALLOCATOR_RC % name)
            placed.add(rel)
            for path in vendor_manifests(lambda p: any(n == "android.hardware.graphics.allocator"
                                                       for n, _i in aidl_hals(p))):
                rel = os.path.join("vendor", "etc", "vintf", "manifest", "plinius-" + os.path.basename(path))
                place(os.path.join(OVERLAY, rel), source=path)
                placed.add(rel)
        hosthals = HOSTHALS_MAPPER
        changed = graphics_cfg(cfg, vprops, api)
    for rel in before - placed:
        path = os.path.join(OVERLAY, rel)
        if os.path.lexists(path):
            os.unlink(path)
    write_if_changed(os.path.join(OVERLAY, "system", "etc", "hosthals.xml"), hosthals)
    write_if_changed(GRAPHICS_STATE, "".join(rel + "\n" for rel in sorted(placed)))
    return changed


def graphics_cfg(cfg, vprops, api=0):
    """waydroid.cfg for the vendor's GPU stack; True if it changed."""
    before = {s: dict(cfg[s]) for s in cfg.sections()}
    waydroid = cfg["waydroid"]
    waydroid["bind_host_egl"] = "True"
    waydroid.pop("drm_device", None)
    props = properties(cfg)
    props.pop("gralloc.gbm.device", None)
    props["ro.hardware.gralloc"] = "android"
    props["ro.hardware.egl"] = vprops.get("ro.hardware.egl", "")
    for key, value in vprops.items():
        if key.startswith("ro.vendor.arm."):
            props[key] = value
    if glob.glob(os.path.join(VENDOR, "lib", "egl", "lib*_%s.so" % vprops.get("ro.hardware.egl", ""))):
        props.pop("ro.zygote.disable_gl_preload", None)
    else:
        props["ro.zygote.disable_gl_preload"] = "true"
    # Shared memory as memfd: Android 14 and later look for ashmem at /dev/ashmem<boot id>, which
    # the container does not have (system_server dies at its start without it)
    if api > 33:
        props["sys.use_memfd"] = "true"
    else:
        props.pop("sys.use_memfd", None)
    after = {s: dict(cfg[s]) for s in cfg.sections()}
    if after != before:
        print("Graphics on the GPU: %s EGL, the vendor's allocator and mapper" % props["ro.hardware.egl"])
        return True
    return False


def add_mode(path, mode):
    """Adds the mode bits to a device node; True if it had them not all already."""
    try:
        old = os.stat(path).st_mode & 0o7777
    except OSError:
        return False
    if old | mode == old:
        return False
    try:
        os.chmod(path, old | mode)
    except OSError as e:
        print("%s: %s" % (path, e.strerror), file=sys.stderr)
        return False
    print("%s: %o -> %o" % (path, old, old | mode))
    return True


def setup_devices(cfg):
    for path, mode in DEVICE_MODES.items():
        add_mode(path, mode)
    drm = cfg.get("waydroid", "drm_device", fallback="")
    if drm:
        add_mode(drm, DRM_MODE)


def camera_instances():
    """The instances of the vendor's AIDL camera providers (internal/0), from its VINTF manifests."""
    import xml.etree.ElementTree as ET
    instances = []
    for path in [os.path.join(VENDOR, "etc", "vintf", "manifest.xml")] + \
            sorted(glob.glob(os.path.join(VENDOR, "etc", "vintf", "manifest", "*.xml"))):
        try:
            root = ET.parse(path).getroot()
        except (OSError, ET.ParseError):
            continue
        for hal in root.iter("hal"):
            if hal.get("format") != "aidl" or hal.findtext("name") != CAMERA_PROVIDER:
                continue
            for iface in hal.iter("interface"):
                for inst in iface.iter("instance"):
                    instances.append("%s/%s" % (iface.findtext("name"), inst.text))
            for fq in hal.iter("fqname"):
                instances.append(fq.text)
    return instances


def camera_manifest(instances):
    hal = "".join("        <fqname>%s</fqname>\n" % i for i in instances)
    return ('<manifest version="1.0" type="device">\n    <hal format="aidl">\n'
            "        <name>%s</name>\n        <version>1</version>\n%s    </hal>\n</manifest>\n"
            % (CAMERA_PROVIDER, hal))


def setup_camera(api):
    manifest = os.path.join(OVERLAY, "vendor", "etc", "vintf", "manifest", "plinius-camera.xml")
    metadata = os.path.join(OVERLAY, "system", "lib64", "libcamera_metadata.so")
    instances = camera_instances()
    if instances:
        write_if_changed(manifest, camera_manifest(instances))
    elif os.path.exists(manifest):
        os.unlink(manifest)
    halium = read_prop(os.path.join(HALIUM_SYSTEM, "build.prop"), "ro.build.version.sdk")
    source = os.path.join(HALIUM_SYSTEM, "lib64", "libcamera_metadata.so")
    try:
        newer = instances and api is not None and int(halium) > api and os.path.isfile(source)
    except (TypeError, ValueError):
        newer = False
    if newer:
        place(metadata, source=source)
    elif os.path.exists(metadata):
        os.unlink(metadata)


def mount_entry(line):
    """(source, destination) of an lxc.mount.entry line, else None."""
    key, sep, value = line.partition("=")
    fields = value.split()
    if not sep or key.strip() != "lxc.mount.entry" or len(fields) < 2:
        return None
    return fields[0], fields[1]


def device_rule(source):
    """The device filter's rule for a device node Waydroid binds in, None for anything else (a
    directory, a file, a block device, a device that is never given)."""
    try:
        st = os.stat(source)
    except OSError:
        return None
    if not stat.S_ISCHR(st.st_mode):
        return None
    dev = (os.major(st.st_rdev), os.minor(st.st_rdev))
    if dev in NEVER_DEVICES:
        return None
    return "c %d:%d rwm" % dev


def loop_dev(number):
    """(major, minor) of loop device number from sysfs, None without it. The minor is not the
    number: with room for partitions loop1 is 7:8 on the phone."""
    try:
        with open(os.path.join(SYS_BLOCK, "loop%d" % number, "dev")) as f:
            major, minor = (int(x) for x in f.read().strip().split(":"))
    except (OSError, ValueError):
        return None
    return (major, minor) if major == LOOP_MAJOR else None


def existing_loops():
    """Numbers of the loop devices the kernel has (set up or not)."""
    numbers = set()
    for path in glob.glob(os.path.join(SYS_BLOCK, "loop*")):
        name = os.path.basename(path)[4:]
        if name.isdigit():
            numbers.add(int(name))
    return numbers


def phone_loops():
    """Numbers of the loop devices the phone has set up (they have a backing file)."""
    return {n for n in existing_loops()
            if os.path.exists(os.path.join(SYS_BLOCK, "loop%d" % n, "loop", "backing_file"))}


def add_loops(numbers):
    """Lets the kernel make the loop devices of numbers (LOOP_CTL_ADD), and udev their nodes."""
    import fcntl
    fd = os.open(LOOP_CONTROL_NODE, os.O_RDWR | os.O_CLOEXEC)
    try:
        for number in numbers:
            with contextlib.suppress(OSError):
                fcntl.ioctl(fd, LOOP_CTL_ADD, number)
    finally:
        os.close(fd)
    subprocess.run(["udevadm", "settle", "--timeout=10"], check=False)


def android_loops():
    """(number, major, minor) of the lowest ANDROID_LOOPS loop devices that are free now and have
    a node, made first if there are not as many."""
    taken = phone_loops()
    free = sorted(existing_loops() - taken)
    if len(free) < ANDROID_LOOPS:
        start = max(existing_loops() | {-1}) + 1
        add_loops(range(start, start + ANDROID_LOOPS - len(free)))
        free = sorted(existing_loops() - phone_loops())
    loops = []
    for number in free:
        dev = loop_dev(number)
        if dev and os.path.exists(os.path.join(DEV, "loop%d" % number)):
            loops.append((number,) + dev)
    return loops[:ANDROID_LOOPS]


def loaded_profiles():
    """Names of the AppArmor profiles in the kernel ("name (mode)" per line)."""
    try:
        with open(APPARMOR_PROFILES) as f:
            return {line.rsplit(" (", 1)[0] for line in f.read().splitlines()}
    except OSError:
        return set()


def containment_config(text, profile):
    """Waydroid's container configuration with the containment: no capability of DROPPED_CAPS,
    the AppArmor profile, the device filter of config_plinius included."""
    include = "lxc.include = %s" % os.path.join(LXC_DIR, "config_plinius")
    lines = []
    for line in text.splitlines():
        key = line.partition("=")[0].strip()
        if key == "lxc.cap.keep":
            caps = [c for c in line.partition("=")[2].split() if c not in DROPPED_CAPS]
            line = "lxc.cap.keep = " + " ".join(caps)
        elif key == "lxc.apparmor.profile":
            continue
        elif line.strip() == include:
            continue
        lines.append(line)
    lines += ["lxc.apparmor.profile = " + profile, include]
    return "\n".join(lines) + "\n"


def drop_overlay_rw():
    """Empties the writable layers (system, vendor) of the overlay; the layers themselves stay,
    Waydroid mounts them."""
    dropped = []
    for layer in sorted(glob.glob(os.path.join(OVERLAY_RW, "*"))):
        if os.path.islink(layer) or not os.path.isdir(layer):
            continue
        for name in sorted(os.listdir(layer)):
            path = os.path.join(layer, name)
            if os.path.isdir(path) and not os.path.islink(path):
                shutil.rmtree(path)
            else:
                os.unlink(path)
            dropped.append(os.path.join(os.path.basename(layer), name))
    if dropped:
        print("Dropped what Android wrote over its images: %s" % ", ".join(dropped))


def refuse(text):
    """An error that stops Android's start: on stderr, which lands in Waydroid's log, and in the
    journal itself (the service's output does not always reach it)."""
    print(text, file=sys.stderr)
    syslog.openlog("waydroid-plinius-setup", 0, syslog.LOG_DAEMON)
    syslog.syslog(syslog.LOG_ERR, text)
    syslog.closelog()


def setup_containment():
    """Keeps Android's root inside the container: the mounts of DROPPED_MOUNTS go, the device
    filter gets the devices Waydroid binds in and FIXED_DEVICES, and the configuration the
    capabilities without DROPPED_CAPS and the AppArmor profile. Runs before every start of the
    container (0005), so that it holds after Waydroid's upgrade as well; without the
    configuration or the profile loaded it fails, and the container does not start."""
    config = os.path.join(LXC_DIR, "config")
    nodes = os.path.join(LXC_DIR, "config_nodes")
    try:
        with open(config) as f:
            config_text = f.read()
        with open(nodes) as f:
            node_lines = f.read().splitlines()
    except OSError as e:
        print("The container's configuration is missing: %s" % e, file=sys.stderr)
        return 1
    if APPARMOR_PROFILE not in loaded_profiles():
        refuse("The AppArmor profile %s is not loaded: Android does not start without it "
               "(plinius-apparmor loads it at boot)" % APPARMOR_PROFILE)
        return 1
    kept, rules = [], list(FIXED_DEVICES)
    for line in node_lines:
        entry = mount_entry(line)
        if entry and entry[1].strip("/") in DROPPED_MOUNTS:
            print("Not given to Android: /%s" % entry[1].strip("/"))
            continue
        kept.append(line)
        rule = entry and device_rule(entry[0])
        if rule and rule not in rules:
            rules.append(rule)
    # Loop nodes of an earlier start go: which ones are free is decided anew
    kept = [l for l in kept if not (mount_entry(l) or ("", ""))[1].strip("/").startswith(
        ("dev/loop-control", "dev/block/loop"))]
    if os.path.exists(LOOP_CONTROL_NODE):
        kept.append("lxc.mount.entry = %s dev/loop-control none bind,create=file,optional 0 0"
                    % LOOP_CONTROL_NODE)
        rules.append(LOOP_CONTROL)
        for number, major, minor in android_loops():
            kept.append("lxc.mount.entry = %s dev/block/loop%d none bind,create=file,optional 0 0"
                        % (os.path.join(DEV, "loop%d" % number), number))
            rules.append("b %d:%d rwm" % (major, minor))
    write_if_changed(nodes, "\n".join(kept) + "\n")
    write_if_changed(os.path.join(LXC_DIR, "config_plinius"),
                     "# Written by waydroid-plinius-setup before every start of the container: the "
                     "devices Android may use\nlxc.cgroup2.devices.deny = a\n" +
                     "".join("lxc.cgroup2.devices.allow = %s\n" % r for r in dict.fromkeys(rules)))
    drop_overlay_rw()
    write_if_changed(config, containment_config(config_text, APPARMOR_PROFILE))
    return 0


def real_path(path):
    """No symbolic link anywhere on the path."""
    return os.path.realpath(path) == os.path.normpath(path)


def open_dir(parent_fd, name):
    """The directory name below parent_fd (name itself with None), never through a symbolic link;
    None if it is not one."""
    try:
        return os.open(name, os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW | os.O_CLOEXEC, dir_fd=parent_fd)
    except (FileNotFoundError, NotADirectoryError):
        # With O_DIRECTORY a symbolic link is "not a directory" (ENOTDIR), not ELOOP
        return None


def open_below(fds, fd, path):
    """The directory at the relative path below fd, opened part by part without following a link
    (each closed with the ExitStack fds); None if a part is no directory or fd is None."""
    for name in path.split("/"):
        if fd is None:
            return None
        fd = open_dir(fd, name)
        if fd is not None:
            fds.callback(os.close, fd)
    return fd


def exists(dir_fd, name):
    """Whether there is anything named name in dir_fd (a symbolic link too)."""
    try:
        os.lstat(name, dir_fd=dir_fd)
    except FileNotFoundError:
        return False
    return True


def media_dir(fd):
    """The stat of Android's storage open at fd: a directory of media_rw, else None."""
    if fd is None:
        return None
    st = os.fstat(fd)
    if stat.S_ISDIR(st.st_mode) and st.st_uid == AID_MEDIA_RW:
        return st
    return None


def mount_point(parent_fd, name, uid, gid, mode):
    """The directory name made in parent_fd with these owners and mode, set through its descriptor."""
    os.mkdir(name, 0o700, dir_fd=parent_fd)
    fd = os.open(name, os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW | os.O_CLOEXEC, dir_fd=parent_fd)
    try:
        os.chown(fd, uid, gid)
        os.chmod(fd, mode)
    finally:
        os.close(fd)


def grant(fds, spec):
    """setfacl on open files, through /proc/self/fd: a name swapped for a link after the file was
    opened leads nowhere else."""
    fds = list(fds)
    for i in range(0, len(fds), SETFACL_BATCH):
        batch = fds[i:i + SETFACL_BATCH]
        subprocess.run(["setfacl", "-m", spec, "--", *("/proc/self/fd/%d" % fd for fd in batch)],
                       pass_fds=batch, check=True)


def grant_tree(top_fd, uid):
    """Read and write for the user in Android's storage open at top_fd, Android's app data left
    out; symbolic links are neither followed nor changed, every name is opened in the directory
    it is in."""
    dirs, files = "u:%d:rwx,d:u:%d:rwx" % (uid, uid), "u:%d:rw" % uid
    pending = {dirs: [], files: []}

    def flush(spec):
        try:
            grant(pending[spec], spec)
        finally:
            for fd in pending[spec]:
                os.close(fd)
            pending[spec] = []

    def add(spec, fd):
        pending[spec].append(fd)
        if len(pending[spec]) >= SETFACL_BATCH:
            flush(spec)

    try:
        for root, dnames, fnames, dir_fd in os.fwalk(".", dir_fd=top_fd, follow_symlinks=False):
            if root == "." and ANDROID_APP_DATA in dnames:
                dnames.remove(ANDROID_APP_DATA)
            add(dirs, os.dup(dir_fd))
            for name in fnames:
                # O_PATH: a device or a pipe is not opened for real
                fd = os.open(name, os.O_PATH | os.O_NOFOLLOW | os.O_CLOEXEC, dir_fd=dir_fd)
                if stat.S_ISREG(os.fstat(fd).st_mode):
                    add(files, fd)
                else:
                    os.close(fd)
        flush(dirs)
        flush(files)
    finally:
        for fd in pending[dirs] + pending[files]:
            os.close(fd)


def hide_app_data(top_fd):
    """Android's app data out of sight in file managers (.hidden), Android's like the rest."""
    if exists(top_fd, ".hidden"):
        return
    fd = os.open(".hidden", os.O_WRONLY | os.O_CREAT | os.O_EXCL | os.O_NOFOLLOW | os.O_CLOEXEC, 0o660,
                 dir_fd=top_fd)
    with os.fdopen(fd, "w") as f:
        f.write(ANDROID_APP_DATA + "\n")
        os.chown(f.fileno(), AID_MEDIA_RW, AID_MEDIA_RW)


def android_dir(uid, data):
    """~/Android of the user as Android's storage (see the top); root's mount of it to bind
    (bind_session), or None. The home belongs to the user, who may swap any directory below it
    for a link at any time: each one is opened from the home down without following a link and
    used only through its descriptor, the bind too."""
    try:
        home = pwd.getpwuid(uid).pw_dir
    except KeyError:
        return None
    if os.path.normpath(data) != os.path.join(home, WAYDROID_DATA) or not real_path(data):
        print("Not the Waydroid data of user %d: %s" % (uid, data), file=sys.stderr)
        return None
    target = os.path.join(home, ANDROID_DIR)
    with contextlib.ExitStack() as fds:
        home_fd = open_dir(None, home)
        if home_fd is None:
            return None
        fds.callback(os.close, home_fd)
        media_parent = open_below(fds, home_fd, WAYDROID_DATA + "/media")
        media = open_below(fds, media_parent, "0")
        if not exists(home_fd, ANDROID_DIR):
            st = media_dir(media)
            if st is None:
                # Android makes its storage at its first start; it moves at the next one
                return None
            os.rename("0", ANDROID_DIR, src_dir_fd=media_parent, dst_dir_fd=home_fd)
            # Where Android looks for its storage: the bind's mount point, as Android made it
            mount_point(media_parent, "0", st.st_uid, st.st_gid, stat.S_IMODE(st.st_mode))
            print("Android's storage moved to " + target, file=sys.stderr)
            try:
                # media is still the directory moved, wherever its name is by now
                hide_app_data(media)
                grant_tree(media, uid)
            except (OSError, subprocess.CalledProcessError) as e:
                print("No access for user %d to %s: %s" % (uid, target, e), file=sys.stderr)
            return bind_session("android", media)
        android = open_below(fds, home_fd, ANDROID_DIR)
        if media_dir(android) is None:
            print(target + " is not Android's storage: Android keeps its own", file=sys.stderr)
            return None
        if media is None:
            # Android's data made anew (reset): the mount point in it, as Android makes it
            if media_dir(media_parent) is None or exists(media_parent, "0"):
                return None
            mount_point(media_parent, "0", AID_MEDIA_RW, AID_MEDIA_RW, 0o2770)
        elif media_dir(media) is None:
            return None
        try:
            grant([android], "u:%d:rwx,d:u:%d:rwx" % (uid, uid))
        except (OSError, subprocess.CalledProcessError) as e:
            print("No access for user %d to %s: %s" % (uid, target, e), file=sys.stderr)
        return bind_session("android", android)


def libc_call(name, *args):
    """A call of the C library that returns -1 and sets errno on failure; the errno or 0."""
    libc = ctypes.CDLL(None, use_errno=True)
    if getattr(libc, name)(*args) == 0:
        return 0
    return ctypes.get_errno() or errno.EIO


def mount_fd(fd, target):
    """What is open at fd bound (recursively) onto target: the kernel follows /proc/self/fd/N to
    the file opened, never to whatever has its name by now."""
    err = libc_call("mount", b"/proc/self/fd/%d" % fd, os.fsencode(target), None,
                    ctypes.c_ulong(MS_BIND | MS_REC), None)
    if err:
        raise OSError(err, os.strerror(err), target)


def release(target):
    """Every mount on target taken away (lazily: the container keeps its own), then target."""
    while True:
        err = libc_call("umount2", os.fsencode(target), MNT_DETACH | UMOUNT_NOFOLLOW)
        if err in (errno.EINVAL, errno.ENOENT):
            break
        if err:
            raise OSError(err, os.strerror(err), target)
    try:
        st = os.lstat(target)
    except FileNotFoundError:
        return
    if stat.S_ISDIR(st.st_mode):
        os.rmdir(target)
    else:
        os.unlink(target)


def session_dir():
    """SESSION_BINDS and the directory it is in (in /run), made if need be: root's own and
    closed to everyone else (0700), no link."""
    for path in (os.path.dirname(SESSION_BINDS), SESSION_BINDS):
        try:
            os.mkdir(path, 0o700)
        except FileExistsError:
            pass
        st = os.lstat(path)
        if not stat.S_ISDIR(st.st_mode) or st.st_uid != os.geteuid() or st.st_mode & 0o077:
            raise OSError(errno.EPERM, "not a directory of root's own", path)
    return SESSION_BINDS


def bind_session(kind, fd):
    """What is open at fd as root's mount SESSION_BINDS/kind (made anew); its path."""
    target = os.path.join(session_dir(), kind)
    release(target)
    if stat.S_ISDIR(os.fstat(fd).st_mode):
        os.mkdir(target, 0o700)
    else:
        os.close(os.open(target, os.O_WRONLY | os.O_CREAT | os.O_EXCL | os.O_NOFOLLOW | os.O_CLOEXEC, 0o600))
    try:
        mount_fd(fd, target)
    except OSError:
        release(target)
        raise
    return target


def unbind_session():
    """Every mount of SESSION_BINDS taken away (as the container stops)."""
    try:
        names = sorted(os.listdir(SESSION_BINDS))
    except FileNotFoundError:
        return 0
    code = 0
    for name in names:
        try:
            release(os.path.join(SESSION_BINDS, name))
        except OSError as e:
            print("Still mounted for Android: %s" % e, file=sys.stderr)
            code = 1
    return code


def open_source(fds, path):
    """(directory fd, fd) of the absolute path opened from / down, no part through a symbolic
    link, the last part O_PATH (a socket or a pipe is not opened for real); None for a part that
    is missing, a link or no directory. Each fd is closed with the ExitStack fds."""
    parts = [p for p in os.path.normpath(path).split("/") if p]
    if not os.path.isabs(path) or not parts:
        return None
    parent = open_dir(None, "/")
    fds.callback(os.close, parent)
    parent = open_below(fds, parent, "/".join(parts[:-1])) if parts[:-1] else parent
    if parent is None:
        return None
    try:
        fd = os.open(parts[-1], os.O_PATH | os.O_NOFOLLOW | os.O_CLOEXEC, dir_fd=parent)
    except FileNotFoundError:
        return None
    fds.callback(os.close, fd)
    return parent, fd


def session_bind(uid, kind, path):
    """The user's path of a kind of BIND_KINDS, checked through its descriptor and bound as root's
    mount (bind_session); that mount's path, or None (said why on stderr)."""
    want, owner = BIND_KINDS[kind]
    with contextlib.ExitStack() as fds:
        opened = open_source(fds, path)
        if opened is None:
            print("Not bound into Android: %s is missing or has a symbolic link on its way" % path, file=sys.stderr)
            return None
        parent, fd = opened
        st = os.fstat(fd)
        if stat.S_ISLNK(st.st_mode):
            print("Not bound into Android: %s is a symbolic link" % path, file=sys.stderr)
            return None
        if not (stat.S_ISDIR(st.st_mode) if want == "dir" else stat.S_ISSOCK(st.st_mode)):
            print("Not bound into Android: %s is no %s" % (path, "directory" if want == "dir" else "socket"),
                  file=sys.stderr)
            return None
        whose = os.fstat(parent) if owner == "parent" else st
        if whose.st_uid != uid:
            print("Not bound into Android: %s is not user %d's" % (path, uid), file=sys.stderr)
            return None
        return bind_session(kind, fd)


def main():
    if sys.argv[1:] == ["--containment"]:
        return setup_containment()
    if sys.argv[1:] == ["--unbind"]:
        return unbind_session()
    if len(sys.argv) == 5 and sys.argv[1] == "--bind" and sys.argv[2].isdigit() and sys.argv[3] in BIND_KINDS:
        try:
            path = session_bind(int(sys.argv[2]), sys.argv[3], sys.argv[4])
        except OSError as e:
            print("Not bound into Android: %s: %s" % (sys.argv[4], e), file=sys.stderr)
            path = None
        if path:
            print(path)
        return 0
    if len(sys.argv) == 4 and sys.argv[1] == "--android-dir" and sys.argv[2].isdigit():
        try:
            path = android_dir(int(sys.argv[2]), sys.argv[3])
        except OSError as e:
            print("Android keeps its storage: %s" % e, file=sys.stderr)
            path = None
        if path:
            print(path)
        return 0
    if sys.argv[1:2] in (["--containment"], ["--unbind"], ["--bind"], ["--android-dir"]):
        print("usage: waydroid-plinius-setup [--containment | --unbind | --bind UID KIND PATH | "
              "--android-dir UID DATA]", file=sys.stderr)
        return 2
    cfg = load_cfg()
    if cfg is None:
        print("Waydroid is not initialised")
        return 0
    api = image_api(cfg)
    setup_gbinder(api)
    setup_overlay()
    setup_camera(api)
    setup_conflicts(cfg)
    changed = setup_graphics(cfg, api)
    changed = setup_display(cfg) or changed
    if changed:
        with open(WAYDROID_CFG, "w") as f:
            cfg.write(f)
        # Waydroid makes its properties from waydroid.cfg only on init and upgrade
        subprocess.run(["waydroid", "upgrade", "--offline"])
    setup_devices(cfg)
    return 0


if __name__ == "__main__":
    sys.exit(main())
