/*
    Copyright 2016-2022 Gleb Popov <6yearold@gmail.com>
    Copyright (c) 2023 Serenity Cyber Security, LLC <license@futurecrew.ru>
                Author: Alexey Yushkin <x636808@gmail.com>

    Redistribution and use in source and binary forms, with or without modification,
    are permitted provided that the following conditions are met:
    1. Redistributions of source code must retain the above copyright notice,
    this list of conditions and the following disclaimer.
    2. Redistributions in binary form must reproduce the above copyright notice,
    this list of conditions and the following disclaimer in the documentation
    and/or other materials provided with the distribution.
    3. Neither the name of the copyright holder nor the names of its contributors may
    be used to endorse or promote products derived from this software without specific
    prior written permission.

    THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
    ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
    WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
    IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
    INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
    BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
    DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
    LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
    OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
    ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/

#include "bsdisks.h"
#include "blockfilesystem.h"
#include "block.h"
#include "objectmanager.h"

#include <QDBusConnection>
#include <QDBusConnectionInterface>
#include <QDBusMessage>
#include <QProcess>
#include <QStandardPaths>
#include <QDir>

#include <algorithm>
#include <ranges>
#include <span>

#include <sys/param.h>
#include <sys/ucred.h>
#include <sys/mount.h>

#include <unistd.h>
#include <errno.h>

namespace ranges = std::ranges;
namespace views = std::views;

static bool alreadyMounted(QDir d)
{
    struct statfs* buf;
    int count = ::getmntinfo(&buf, MNT_NOWAIT);

    if(!count)
    {
        QString error = QString::fromLocal8Bit(::strerror(errno));
        qDebug() << "alreadyMounted: getmntinfo failed: " << error;
        return false;
    }

    for(const auto b : std::span(buf, count))
    {
        auto mntOn = QString::fromLocal8Bit(b.f_mntonname);
        if(d == QDir(mntOn))
            return true;
    }

    return false;
}

static QString createMountPoint(QString id, uid_t uid, int suff = 0)
{
    auto mp = suff == 0 ? QStringLiteral("/media/") + id
                        : QStringLiteral("/media/") + id + QString::number(suff);
    QDir mpDir(mp);

    if(mpDir.exists() && alreadyMounted(mpDir))
        return createMountPoint(id, uid, ++suff);

    mpDir.mkpath(".");

    qDebug() << "chown of " << mpDir.absolutePath() << " to " << QString::number(uid);
    if(::chown(mpDir.absolutePath().toLocal8Bit().constData(), uid, -1))
    {
        QString error = QString::fromLocal8Bit(::strerror(errno));
        qDebug() << "createMountPoint: " << error;
    }

    return mp;
}

static void removeMountPoint(QString mp, bool checkIfEmpty = false)
{
    if(!mp.startsWith(QStringLiteral("/media")))
        return;

    QDir mpDir(mp);

    if(checkIfEmpty && mpDir.entryList().count() > 2) // '.' and '..' also counts
        return;

    auto dirName = mpDir.dirName();
    mpDir.cdUp();
    mpDir.rmdir(dirName);
}

QString BlockFilesystem::Mount(const QVariantMap& options)
{
    auto context = parentBlock();

    // Prefer the device's filesystem label if one exists
    QString id = parentBlock()->idLabel();
    // Otherwise fallback using the device ID.
    if (id.isEmpty()) {
        id = parentBlock()->id();
    }

    // fail if already mounted
    if(mountPoints.count() > 0)
    {
        QString error = "Mount: device " + id + "already mounted";
        qDebug() << error;
        DBUS_THROW_CONTEXT_IMPL("org.freedesktop.UDisks2.Error.AlreadyMounted", error, parentBlock());
    }

    // https://dbus.freedesktop.org/doc/dbus-specification.html#bus-messages-get-connection-credentials
    auto uidReply = context->connection().interface()->serviceUid(context->message().service());
    if(!uidReply.isValid()) {
        QString error = "Mount: interface.serviceUid() failed";
        DBUS_RETHROW_CONTEXT(uidReply);
    }

    ObjectManager::Instance().CheckAuth(QStringLiteral("org.freedesktop.udisks2.filesystem-mount"), parentBlock(),
                                 [this, id, uid = uidReply.value()](auto result, auto context) mutable
    {
        if (result != PolkitQt1::Authority::Result::Yes)
            DBUS_THROW_CONTEXT_VOID("org.freedesktop.UDisks2.Error.NotAuthorized", "Not authorized");

        QProcess mount;
        QString mountPoint = filesystem == "zfs"
            ? zfsDataset
            : createMountPoint(id.replace(' ', '_'), uid);
        QStringList args;

        auto mountProg = QStringLiteral("/sbin/mount");
        if(filesystem == "msdosfs")
        {
            mountProg = QStringLiteral("/sbin/mount_msdosfs");

            if(!BsdisksConfig::get().MountMsdosfsFlags.isEmpty())
                args << BsdisksConfig::get().MountMsdosfsFlags.split(' ');
        }
        else if(filesystem == "ntfs")
        {
            mountProg = QStandardPaths::findExecutable("ntfs-3g");
        }
        else if(filesystem == "cd9660")
        {
            mountProg = QStringLiteral("/sbin/mount_cd9660");

            if(!BsdisksConfig::get().MountCd9660Flags.isEmpty())
                args << BsdisksConfig::get().MountCd9660Flags.split(' ');
        }
        else if(filesystem == "ext2fs")
        {
            mountProg = QStandardPaths::findExecutable("fuse-ext2");

            if (BsdisksConfig::get().PreferNativeExt2 || mountProg.isEmpty())
            {
                mountProg = QStringLiteral("/sbin/mount");
                args << QStringLiteral("-t") << QStringLiteral("ext2fs");
                args << QStringLiteral("-o") << QStringLiteral("async");
            }
            else
            {
                args << QStringLiteral("-o") << (QStringLiteral("uid=") + QString::number(uid));
                args << QStringLiteral("-o") << QStringLiteral("allow_other");
            }
        }
        else if(filesystem == "exfat")
        {
            mountProg = QStringLiteral("mount.exfat-fuse");

            args << QStringLiteral("-o") << (QStringLiteral("uid=") + QString::number(uid));
            args << QStringLiteral("-o") << QStringLiteral("allow_other");
        }
        else if(filesystem == "ufs")
        {
            args << QStringLiteral("-o") << QStringLiteral("nosuid,untrusted");
        }

        if(filesystem == "zfs")
        {
            mountProg = QStringLiteral("/sbin/zfs");

            args << QStringLiteral("mount") << mountPoint;
        }
        else
            args << parentBlock()->device() << mountPoint;

        mount.setProgram(mountProg);
        mount.setArguments(args);

        mount.start();
        mount.waitForFinished(-1);

        if(mount.exitCode())
        {
            QString error = "Mount: failed with " + mount.readAllStandardError();
            removeMountPoint(mountPoint);

            DBUS_THROW_CONTEXT_VOID("org.freedesktop.UDisks2.Error.Failed", error);
        }

        QByteArray incomingMount = filesystem == "zfs"
            ? zfsMountpoint.toLocal8Bit() // For ZFS, this value contains the dataset name
            : mountPoint.toLocal8Bit();

        mountPoints << qMakePair(incomingMount, uid);

        context->sendReply(mountPoint);

        signalMountPointsChanged();
    });

    return QString();
}

void BlockFilesystem::unmountImplementation(QList<QPair<QByteArray, uid_t>>::iterator it, bool force, bool changed, std::shared_ptr<DBusSavedContext> context)
{
    if (it == mountPoints.end())
    {
        context->sendReply();
        unmounting = false;
        if (changed)
            signalMountPointsChanged();
        return;
    }

    QProcess* umount = new QProcess();

    QProcessEnvironment umountEnv;
    umountEnv.insert("LANG", QStringLiteral("C.UTF-8"));
    umountEnv.insert("LANGUAGE", QStringLiteral("C.UTF-8"));
    umount->setProcessEnvironment(umountEnv);

    QStringList args;
    if(force)
        args << QStringLiteral("-f");
    args << it->first;

    // TODO: handle timeouts
    QObject::connect(umount, QOverload<int, QProcess::ExitStatus>::of(&QProcess::finished),
                     [this, umount, it, force, changed, context](int exitCode, QProcess::ExitStatus exitStatus)
    {
        if(exitCode == 0) {
            removeMountPoint(QString::fromLocal8Bit(it->first), /*checkIfEmpty = */ true);
            unmountImplementation(mountPoints.erase(it), force, true, context);
        } else {
            QString errorMessage = umount->readAllStandardError();
            QString udisksError = QStringLiteral("org.freedesktop.UDisks2.Error.Failed");

            if (errorMessage.contains("Device busy"))
                udisksError = QStringLiteral("org.freedesktop.UDisks2.Error.DeviceBusy");

            context->sendErrorReply(udisksError, errorMessage);
            unmounting = false;
            qDebug() << errorMessage;
            if (changed)
                signalMountPointsChanged();
        }
    });

    unmounting = true;
    umount->start(QStringLiteral("/sbin/umount"), args);
}

void BlockFilesystem::Unmount(const QVariantMap& options)
{
    auto context = parentBlock();

    if(mountPoints.empty()) {
        QString error = QStringLiteral("Unmount: requested filesystem is not mounted");
        qDebug() << error;
        DBUS_THROW_CONTEXT_VOID("org.freedesktop.UDisks2.Error.NotMounted", error);
    }

    auto uidReply = context->connection().interface()->serviceUid(context->message().service());
    if(!uidReply.isValid())
        DBUS_RETHROW_CONTEXT_VOID(uidReply);

    uid_t callerUid = uidReply.value();
    bool needAuthorization = std::any_of(mountPoints.begin(), mountPoints.end(), [callerUid](const auto& mountPair)
    {
        return callerUid != mountPair.second;
    });
    bool force = options["force"].toBool();

    if (needAuthorization)
    {
        ObjectManager::Instance().CheckAuth(QStringLiteral("org.freedesktop.udisks2.filesystem-unmount-others"), parentBlock(),
                        [this, force](auto result, auto context)
        {
            if (result != PolkitQt1::Authority::Result::Yes)
                DBUS_THROW_CONTEXT_VOID("org.freedesktop.UDisks2.Error.NotAuthorized", "Not authorized");

            BlockFilesystem::unmountImplementation(mountPoints.begin(), force, false, context);
        });
    }
    else
    {
        BlockFilesystem::unmountImplementation(mountPoints.begin(), force, false, std::make_shared<DBusSavedContext>(context));
    }
}

void BlockFilesystem::signalMountPointsChanged()
{
    // TODO: this probably need a less hacky fix
    // See https://foss.heptapod.net/bsdutils/bsdisks/-/issues/12
    auto mounts = mountPoints
        | views::transform([](const auto& pair) { return pair.first + '\0'; });
    auto mps = QByteArrayList(mounts.begin(), mounts.end());

    QVariantMap props;
    props.insert(QStringLiteral("MountPoints"), QVariant::fromValue(mps));

    QDBusMessage signal = QDBusMessage::createSignal(
                                parentBlock()->dbusPath.path(),
                                QStringLiteral("org.freedesktop.DBus.Properties"),
                                QStringLiteral("PropertiesChanged"));

    signal << QStringLiteral("org.freedesktop.UDisks2.Filesystem")
           << props
           << QStringList();
    QDBusConnection::systemBus().send(signal);
}

void BlockFilesystem::tryAddMountPoint(QString mountDevice, QString mountPoint)
{
    bool match = !mountDevice.toLocal8Bit().compare(parentBlock()->device().chopped(1));
    if(!match) {
        for(const auto& label : parentBlock()->labels)
        {
            match = !label.toLocal8Bit().compare(parentBlock()->device().chopped(1));
            if(match)
                break;
        }
    }

    if(match) {
        auto exists = [mountPoint](const auto& mountPair) { return mountPoint == mountPair.first; };
        if (ranges::any_of(mountPoints, exists))
            return;

        mountPoints << qMakePair(mountPoint.toLocal8Bit(), 0);

        signalMountPointsChanged();
    }
}

void BlockFilesystem::tryRemoveMountPoint(QString mountPoint)
{
    // ignore unmounting notifications if we are already
    // in the Unmount() call chain
    if (unmounting)
        return;

    for (const auto& mountPair : mountPoints)
    {
        QByteArray mp = mountPair.first;

        if(mp == mountPoint.toLocal8Bit()) {
            mountPoints.removeAll(mountPair);
            signalMountPointsChanged();
            break;
        }
    }
}

BlockFilesystem::~BlockFilesystem()
{
}

Block* BlockFilesystem::parentBlock()
{
    return qobject_cast<Block*>(parent());
}

BlockFilesystem::BlockFilesystem(Block* parent)
    : QObject(parent)
{
}
