Skip to content

Truly independent web browser

7.4 KB
Raw Blame
/*
 * Copyright (c) 2020, Andreas Kling <[email protected]>
 * Copyright (c) 2023-2025, Tim Flynn <[email protected]>
 *
 * SPDX-License-Identifier: BSD-2-Clause
 */

#pragma once

#include <AK/ByteString.h>
#include <AK/Concepts.h>
#include <AK/Forward.h>
#include <AK/MemoryStream.h>
#include <AK/NumericLimits.h>
#include <AK/Queue.h>
#include <AK/ScopeGuard.h>
#include <AK/StdLibExtras.h>
#include <AK/String.h>
#include <AK/Time.h>
#include <AK/Try.h>
#include <AK/TypeList.h>
#include <AK/Utf16FlyString.h>
#include <AK/Variant.h>
#include <LibCore/Forward.h>
#include <LibIPC/Attachment.h>
#include <LibIPC/Concepts.h>
#include <LibIPC/File.h>
#include <LibIPC/Forward.h>
#include <LibURL/Origin.h>
#include <LibURL/URL.h>

namespace IPC {

template<typename T>
inline ErrorOr<T> decode(Decoder&)
{
    static_assert(DependentFalse<T>, "Base IPC::decoder() instantiated");
    VERIFY_NOT_REACHED();
}

class Decoder {
public:
    Decoder(FixedMemoryStream& stream, Queue<Attachment>& attachments)
        : m_stream(stream)
        , m_attachments(attachments)
    {
    }

    template<typename T>
    ErrorOr<T> decode();

    // Decodes a string, byte buffer or vector, which goes as its size and then its contents, refusing one larger than
    // max_size before decoding its contents.
    template<typename T>
    ErrorOr<T> decode_with_max_size(size_t max_size);

    template<typename T>
    ErrorOr<void> decode_into(T& value)
    {
        value = TRY(m_stream.read_value<T>());
        return {};
    }

    ErrorOr<void> decode_into(Bytes bytes)
    {
        TRY(m_stream.read_until_filled(bytes));
        return {};
    }

    ErrorOr<size_t> decode_size();

    FixedMemoryStream& stream() { return m_stream; }
    Queue<Attachment>& attachments() { return m_attachments; }

private:
    FixedMemoryStream& m_stream;
    Queue<Attachment>& m_attachments;
    size_t m_max_size_of_next_value { NumericLimits<size_t>::max() };
};

template<Arithmetic T>
requires(!IsSame<T, bool>)
ErrorOr<T> decode(Decoder& decoder)
{
    T value { 0 };
    TRY(decoder.decode_into(value));
    return value;
}

template<SameAs<bool> T>
ErrorOr<T> decode(Decoder& decoder)
{
    // Only 0 and 1 are valid representations of a bool, so read the byte as an integer first.
    u8 byte { 0 };
    TRY(decoder.decode_into(byte));
    if (byte > 1)
        return Error::from_string_literal("IPC decode: Invalid bool value");
    return byte == 1;
}

template<Enum T>
ErrorOr<T> decode(Decoder& decoder)
{
    auto value = TRY(decoder.decode<UnderlyingType<T>>());
    return static_cast<T>(value);
}

template<Concepts::DistinctNumeric T>
ErrorOr<T> decode(Decoder& decoder)
{
    return T { TRY(decoder.decode<typename T::Type>()) };
}

template<>
ErrorOr<String> decode(Decoder&);

template<>
ErrorOr<Utf16String> decode(Decoder&);

template<>
ErrorOr<Utf16FlyString> decode(Decoder&);

template<>
ErrorOr<ByteString> decode(Decoder&);

template<>
ErrorOr<ByteBuffer> decode(Decoder&);

template<>
ErrorOr<JsonValue> decode(Decoder&);

template<>
ErrorOr<AK::Duration> decode(Decoder&);

template<>
ErrorOr<UnixDateTime> decode(Decoder&);

template<>
ErrorOr<IPv4Address> decode(Decoder&);

template<>
ErrorOr<IPv6Address> decode(Decoder&);

template<>
ErrorOr<URL::URL> decode(Decoder&);

template<>
ErrorOr<URL::Origin> decode(Decoder&);

template<>
ErrorOr<URL::Host> decode(Decoder&);

template<>
ErrorOr<URL::OpaqueHost> decode(Decoder&);

template<>
ErrorOr<File> decode(Decoder&);

template<>
ErrorOr<TransportHandle> decode(Decoder&);

template<>
ErrorOr<Empty> decode(Decoder&);

template<>
ErrorOr<Core::AnonymousBuffer> decode(Decoder&);

template<>
ErrorOr<URL::BlobURLEntry> decode(Decoder&);

template<Concepts::Array T>
ErrorOr<T> decode(Decoder& decoder)
{
    T array {};
    auto size = TRY(decoder.decode_size());
    if (size != array.size())
        return Error::from_string_literal("Array size mismatch");
    for (size_t i = 0; i < array.size(); ++i)
        array[i] = TRY(decoder.decode<typename T::ValueType>());
    return array;
}

template<Concepts::Vector T>
requires(!IsArithmetic<typename T::ValueType>)
ErrorOr<T> decode(Decoder& decoder)
{
    T vector;

    auto size = TRY(decoder.decode_size());
    TRY(vector.try_ensure_capacity(size));

    for (size_t i = 0; i < size; ++i) {
        auto value = TRY(decoder.decode<typename T::ValueType>());
        vector.unchecked_append(move(value));
    }

    return vector;
}

template<Concepts::Vector T>
requires(IsArithmetic<typename T::ValueType>)
ErrorOr<T> decode(Decoder& decoder)
{
    T vector;
    auto size = TRY(decoder.decode_size());
    if (Checked<size_t>::multiplication_would_overflow(size, sizeof(typename T::ValueType)))
        return Error::from_string_literal("IPC decode: Vector size would overflow");
    TRY(vector.try_resize(size));
    TRY(decoder.decode_into({ reinterpret_cast<u8*>(vector.data()), size * sizeof(typename T::ValueType) }));
    if constexpr (IsSame<typename T::ValueType, bool>) {
        for (auto byte : ReadonlyBytes { reinterpret_cast<u8 const*>(vector.data()), size }) {
            if (byte > 1)
                return Error::from_string_literal("IPC decode: Invalid bool value");
        }
    }
    return vector;
}

template<Concepts::HashMap T>
ErrorOr<T> decode(Decoder& decoder)
{
    T hashmap;

    auto size = TRY(decoder.decode_size());
    TRY(hashmap.try_ensure_capacity(size));

    for (size_t i = 0; i < size; ++i) {
        auto key = TRY(decoder.decode<typename T::KeyType>());
        auto value = TRY(decoder.decode<typename T::ValueType>());
        TRY(hashmap.try_set(move(key), move(value)));
    }

    return hashmap;
}

template<Concepts::Optional T>
ErrorOr<T> decode(Decoder& decoder)
{
    if (auto has_value = TRY(decoder.decode<bool>()); !has_value)
        return T {};
    return T { TRY(decoder.decode<typename T::ValueType>()) };
}

namespace Detail {

template<Concepts::Variant T, size_t Index = 0>
ErrorOr<T> decode_variant(Decoder& decoder, size_t index)
{
    using ElementList = TypeList<T>;

    if constexpr (Index < ElementList::size) {
        if (index == Index) {
            using ElementType = typename ElementList::template Type<Index>;
            return T { TRY(decoder.decode<ElementType>()) };
        }

        return decode_variant<T, Index + 1>(decoder, index);
    } else {
        // Index was validated before calling decode_variant
        VERIFY_NOT_REACHED();
    }
}

}

template<Concepts::Variant T>
ErrorOr<T> decode(Decoder& decoder)
{
    auto index = TRY(decoder.decode<typename T::IndexType>());
    if (index >= TypeList<T>::size)
        return Error::from_string_literal("IPC decode: Invalid variant index");
    return Detail::decode_variant<T>(decoder, index);
}

template<Concepts::Encoded T>
ErrorOr<T> decode(Decoder& decoder)
{
    return T::from_bytes(TRY(decoder.decode<ByteBuffer>()));
}

// This must be last so that it knows about the above specializations.
template<typename T>
ErrorOr<T> Decoder::decode()
{
    return IPC::decode<T>(*this);
}

template<typename T>
ErrorOr<T> Decoder::decode_with_max_size(size_t max_size)
{
    // NB: Decoding a string, byte buffer or vector starts with decode_size(), which checks the size against this. The
    //     bound ends with the value, so it never applies to anything decoded after it.
    m_max_size_of_next_value = max_size;
    ScopeGuard reset_max_size = [&] { m_max_size_of_next_value = NumericLimits<size_t>::max(); };
    return decode<T>();
}

}