# Copyright (c) TuxCare, Inc. All rights reserved.
# Licensed under TUXCARE LICENSE AGREEMENT
# https://tuxcare.com/legal/

import errno
import os
import shutil
import stat
import tempfile

from . import log_utils, process_utils

if False:  # pragma: no cover
    from typing import Any, Optional, Tuple, Union  # noqa: F401


def _remove_quietly(path):
    # type: (str) -> None
    """Remove the file at path, if it can be. In a function of its own, so that on Python 2 the
    OSError it swallows does not replace the exception an except block re-raises."""
    try:
        os.unlink(path)
    except OSError:
        pass


def atomic_write(
    fname, content, ensure_dir=False, mode='w', create_mode=0o644, preserve_attrs=False, force_mode=None, tmp_prefix=None
):
    # type: (str, Union[str, bytes], bool, str, int, bool, Optional[int], Optional[str]) -> None
    """Replace fname with content so that after a reset it has either the old or the new content.

    The rename gives fname a new inode. preserve_attrs also keeps what an admin may have set
    on the old one (owner, ACLs, xattrs, SELinux label) and writes through a symlink that
    only root could have placed. Hard links can't survive a rename.

    The file keeps the mode of the one it replaces, or gets create_mode when there is none.
    force_mode sets the mode whatever the old file had: for a secret that an earlier version
    left readable (create_mode alone would never tighten it). The temp file is created 0600 and gets the final
    mode before the content is written; with preserve_attrs the old file's attributes are copied
    onto it first, so it carries them (the old mode, if wider) until that fchmod.

    A failure of the directory fsync after the rename still raises: the new content is in place, but
    the rename may not survive a reset.

    The temp file is named fname's base name, a dot and a random suffix, or tmp_prefix and the suffix:
    for a directory where a name matters, such as next to shim, which loads every shim_certificate* file.
    With tmp_prefix, the temp files an earlier run left there under it, killed before its rename, are
    removed first.
    """
    if preserve_attrs:
        fname = resolve_trusted_link(fname)
    dname = os.path.dirname(fname)
    if ensure_dir and not os.path.exists(dname):
        os.makedirs(dname)
    if force_mode is not None:
        st_mode = force_mode
    else:
        try:
            st_mode = os.stat(fname).st_mode
        except Exception:
            st_mode = create_mode
    prefix = os.path.basename(fname) + '.' if tmp_prefix is None else tmp_prefix
    if tmp_prefix is not None:
        for name in os.listdir(dname):
            if name.startswith(tmp_prefix):
                # an entry that is not a file, such as a directory, stays: the write needs none of them gone
                _remove_quietly(os.path.join(dname, name))
    tmp_file = tempfile.NamedTemporaryFile(mode=mode, dir=dname, prefix=prefix, delete=False)
    try:
        with tmp_file as f:
            # in a directory others can write, they could swap the temp file for a link that cp follows
            if preserve_attrs and os.path.isfile(fname) and is_trusted_dir(dname):
                copy_attrs(fname, tmp_file.name)
            os.fchmod(f.fileno(), st_mode)
            f.write(content)
            f.flush()
            os.fsync(f.fileno())
        os.rename(tmp_file.name, fname)
    except Exception:
        # already gone, if another run removed it: the error to raise is the one that got us here
        _remove_quietly(tmp_file.name)
        raise

    # ensure folder is also updated, so the rename itself is on disk too.
    # If this fails, the new content is in place but may not survive a reset, so it still raises
    # https://www.quora.com/When-should-you-fsync-the-containing-directory-in-addition-to-the-file-itself
    # https://www.reddit.com/r/kernel/comments/1du6ot8/comment/lbgu46i/?utm_source=share&utm_medium=web3x&utm_name=web3xcss&utm_term=1&utm_content=share_button
    fsync_path(dname)


MAX_SYMLINKS = 40  # as the kernel, so a loop of links ends


def _is_trusted_owner(st):
    # type: (os.stat_result) -> bool
    return st.st_uid in (0, os.geteuid())


def is_trusted_dir(path, follow_links=True, sticky_ok=False):
    # type: (str, bool, bool) -> bool
    """Is path a directory owned by root, or the user running us, that nobody else can add to,
    remove from or rename in?

    That is: not writable by group or others, or (sticky_ok, for a crash root such as /var/crash,
    1777 on Ubuntu) sticky, where only the owner of an entry can remove or rename it. A link is
    followed only if follow_links. Only path itself is checked: its ancestors are assumed to be
    root-controlled.
    """
    try:
        st = os.stat(path) if follow_links else os.lstat(path)
    except OSError:
        # can't tell, so don't trust it
        return False
    if not stat.S_ISDIR(st.st_mode) or not _is_trusted_owner(st):
        return False
    return not st.st_mode & (stat.S_IWGRP | stat.S_IWOTH) or (sticky_ok and bool(st.st_mode & stat.S_ISVTX))


def resolve_trusted_dir(path):
    # type: (str) -> Optional[str]
    """The real directory path leads to, if files can be read from it safely; None otherwise.

    path may be a link only root, or the user running us, could have placed (an admin may have
    moved the directory: resolve_trusted_link). The real directory and its parent must be trusted,
    sticky or not, so nobody else can swap the directory, or rename or remove what is in it, after
    this check; what others add to a sticky one is the caller's to refuse, file by file. Read
    through the returned path, not through path: that link is not looked at again.
    """
    try:
        # a trailing slash would make lstat follow the last link
        real = resolve_trusted_link(path).rstrip('/')
    except OSError:
        # can't tell, so don't trust it
        return None
    if is_trusted_dir(os.path.dirname(real), sticky_ok=True) and is_trusted_dir(real, follow_links=False, sticky_ok=True):
        return real
    return None


def open_trusted_file(path):
    # type: (str) -> Optional[Tuple[int, os.stat_result]]
    """(descriptor, fstat) of path opened for reading, or None if it is not a regular file owned by
    root, or the user running us, with a single name (no hard link to some other file).

    Opened with O_NOFOLLOW (a link is refused) and O_NONBLOCK (a FIFO planted under the name
    cannot block the open), and checked through that one descriptor, so what was checked is what
    is read. Raises OSError if path cannot be opened. The directories above it are the caller's
    business.
    """
    fd = os.open(path, os.O_RDONLY | os.O_NOFOLLOW | os.O_NONBLOCK)
    try:
        st = os.fstat(fd)
    except BaseException:
        os.close(fd)
        raise
    if stat.S_ISREG(st.st_mode) and _is_trusted_owner(st) and st.st_nlink == 1:
        return fd, st
    os.close(fd)
    return None


def resolve_trusted_link(path):
    # type: (str) -> str
    """Follow path through symlinks that only root, or the user running us, could have placed.

    Writing through a link as root lands wherever the link points, so a link that someone
    else could plant (they own it, or own or can write to its directory) is not followed:
    the rename then replaces the link itself.
    """
    for _ in range(MAX_SYMLINKS):
        if not os.path.islink(path):
            return path
        dname = os.path.dirname(path)
        if not _is_trusted_owner(os.lstat(path)) or not is_trusted_dir(dname):
            return path
        path = os.path.join(dname, os.readlink(path))
    return path


def copy_attrs(src, dst):
    # type: (str, str) -> None
    """Copy src's owner, mode, ACLs, xattrs and SELinux label to dst, where cp can.

    cp is the one way to copy all of them on every supported Python. With --preserve=all
    it doesn't fail on an xattr or a label the filesystem can't hold. If cp itself fails,
    dst keeps the attributes it has and the write goes on.
    """
    # system directories only, never PATH, so root doesn't run a planted cp;
    # a split-/usr host (debian up to 11, ubuntu up to 18.04) keeps cp in /bin
    cp = process_utils.find_cmd('cp', ('/usr/bin', '/bin'), raise_exc=False)
    code, stderr = None, 'cp not found'  # type: Optional[int], str
    if cp:
        cmd = [cp, '--attributes-only', '--preserve=all', '--', src, dst]
        try:
            code, _, stderr = process_utils.run_command(cmd, catch_stdout=True, catch_stderr=True)  # type: ignore[no-untyped-call]
        except OSError as e:
            stderr = str(e)
    if code != 0:
        log_utils.logwarn('Failed to keep the attributes of {0}: {1}'.format(src, stderr), print_msg=False)


def fsync_path(path, raise_exc=True):
    # type: (str, bool) -> None
    """fsync path. With raise_exc=False a failure is only logged, as a warning.

    Only for a sync whose failure must not undo or misreport what already happened: the manifest
    and signature swap of install_manifest (both renames are done). Everywhere else a failure
    (EIO on a failing disk) raises.
    """
    try:
        fd = os.open(path, os.O_RDONLY)
        try:
            os.fsync(fd)
        finally:
            os.close(fd)
    except OSError as e:
        if e.errno in (errno.EINVAL, errno.ENOTSUP, errno.EOPNOTSUPP):
            # the filesystem has no fsync for it (a directory on CIFS, some FUSE): name it, so it can be moved
            log_utils.logwarn(
                'Failed to sync {0}: the filesystem mounted at {1} does not support fsync, so changes there '
                'may not survive a power loss'.format(path, mount_of(path))
            )
        elif not raise_exc:
            log_utils.logwarn('Failed to sync {0}: {1}'.format(path, e))
        if raise_exc:
            raise


def mount_of(path):
    # type: (str) -> str
    """The mount point of the filesystem that holds path.

    For a bind mount of a directory, it is the mount point of the filesystem the directory comes from.
    """
    mount = os.path.realpath(path)
    while not os.path.ismount(mount):
        mount = os.path.dirname(mount)
    return mount


def sync_rename(src, dst):
    # type: (str, str) -> None
    """Move a fully written src over dst, so after a reset dst has either its old or its new content.

    The data fsync, the rename and the directory fsync after it raise on failure.
    """
    # a symlink holds no data to sync, and opening one would sync its target instead
    if not os.path.islink(src):
        fsync_path(src)
    os.rename(src, dst)
    fsync_path(os.path.dirname(dst) or os.curdir)


def fsync_tree(path):
    # type: (str) -> None
    """fsync path and every file and directory under it, e.g. after an external tool unpacked files there.

    A regular file is a tree of one. Anything else at path, such as a FIFO or a device, is skipped, as
    it is under a directory. It raises on the first failure; the caller decides what that means.
    fetch_userspace_patch only logs it: the patches work now, and the next update unpacks them again.
    """

    def _raise(err):  # type: (OSError) -> None
        # by default os.walk skips a directory it can't list, which would pass a partial sync as complete
        raise err

    mode = os.stat(path).st_mode
    if not stat.S_ISDIR(mode):
        if stat.S_ISREG(mode):
            fsync_path(path)
        return
    for root, _, names in os.walk(path, onerror=_raise):
        for name in names:
            name_path = os.path.join(root, name)
            # regular files only: a symlink's target may be missing, and opening a FIFO blocks
            if stat.S_ISREG(os.lstat(name_path).st_mode):
                fsync_path(name_path)
        fsync_path(root)


def save_to_file(response, dst):
    # type: (Any, str) -> None
    parent_dir = os.path.dirname(dst)
    if not os.path.exists(parent_dir):
        os.makedirs(parent_dir)
    with open(dst, 'wb') as f:
        shutil.copyfileobj(response, f)
        f.flush()
        os.fsync(f.fileno())
