navid/veins / b8f7327bf194b843bd36e1a9bd5d6d3d5d123eea3f36bf4e780cc97678358890 / xveins/src/protocol.cpp

protocol.cpp

← xveins/src · 30236 bytes · raw · download

#include "protocol.h"

#include "auth.h"
#include "store.h"

#include <blake3.h>

#include <algorithm>
#include <array>
#include <cstring>

namespace vn::proto {

namespace {

std::string connect_error;

void put_u16_be(ByteWriter& writer, std::uint16_t value) {
    writer.u8(static_cast<std::uint8_t>((value >> 8) & 255u));
    writer.u8(static_cast<std::uint8_t>(value & 255u));
}

std::optional<std::uint16_t> read_u16_be(Reader& reader) {
    const auto high = reader.u8();
    if (!high)
        return std::nullopt;
    const auto low = reader.u8();
    if (!low)
        return std::nullopt;
    return static_cast<std::uint16_t>((static_cast<std::uint16_t>(*high) << 8) | *low);
}

std::vector<std::uint8_t> encode_string_list(const std::vector<std::string>& items) {
    ByteWriter writer(128);
    writer.varint(items.size());
    for (const auto& item : items)
        writer.length_prefixed(item);
    return writer.take();
}

std::optional<std::vector<std::string>> decode_string_list(Reader& reader, std::size_t max) {
    const auto count = reader.list_len(max);
    if (!count)
        return std::nullopt;
    std::vector<std::string> out;
    out.reserve(*count);
    for (std::size_t i = 0; i < *count; ++i) {
        const auto value = reader.bytes(4096);
        if (!value)
            return std::nullopt;
        out.emplace_back(str_of(*value));
    }
    return out;
}

std::string bytes_to_string(Bytes data) {
    return std::string(str_of(data));
}

void append_id(ByteWriter& writer, const Id& id) {
    writer.raw(Bytes(id.data(), id.size()));
}

std::optional<Id> read_id(Reader& reader) {
    const auto id = reader.id();
    if (!id)
        return std::nullopt;
    return *id;
}

std::size_t find_char(std::string_view text, char needle) {
    const auto at = text.find(needle);
    return at == std::string_view::npos ? std::string_view::npos : at;
}

struct Authority {
    std::string host;
    int port = 0;
};

Authority parse_authority(std::string_view authority, int default_port, bool strip_user) {
    if (strip_user) {
        const auto at = find_char(authority, '@');
        if (at != std::string_view::npos)
            authority.remove_prefix(at + 1);
    }
    Authority out;
    out.host = std::string(authority);
    out.port = default_port;
    const auto colon = find_char(authority, ':');
    if (colon != std::string_view::npos) {
        out.host = std::string(authority.substr(0, colon));
        const std::string_view port_text = authority.substr(colon + 1);
        if (!port_text.empty()) {
            int port = 0;
            bool numeric = true;
            for (char c : port_text) {
                if (c < '0' || c > '9') {
                    numeric = false;
                    break;
                }
                if (port > 1000000)
                    port = 1000000;
                port = port * 10 + (c - '0');
            }
            if (numeric)
                out.port = port;
        }
    }
    return out;
}

std::optional<net::Stream> connect_stream(const Url& url, std::string_view tls_pin,
                                          std::string& binding) {
    if (url.ssh) {
        std::vector<std::string> remote = {"vn", "serve", "-stdio", url.path};
        const std::string remote_command = net::build_shell_command(remote);
        std::vector<std::string> argv = {"ssh"};
        if (url.port != 22) {
            argv.push_back("-p");
            argv.push_back(std::to_string(url.port));
        }
        argv.push_back(url.host);
        argv.push_back(remote_command);
        auto stream = net::Stream::spawn_argv(argv);
        if (!stream)
            connect_error = "cannot start the SSH transport";
        return stream;
    }
    if (url.tls) {
        auto fd = net::tcp_connect(url.host, url.port);
        if (!fd) {
            connect_error = "cannot connect: host refused the connection or is unreachable";
            return std::nullopt;
        }
        void* ctx = net::tls_client_ctx(!tls_pin.empty());
        if (!ctx) {
            net::close_socket(*fd);
            connect_error = "cannot initialize TLS";
            return std::nullopt;
        }
        void* ssl = net::tls_connect(ctx, *fd, url.host);
        net::tls_ctx_free(ctx);
        if (!ssl) {
            net::close_socket(*fd);
            connect_error = "TLS handshake failed";
            return std::nullopt;
        }
        std::array<std::uint8_t, 32> exported{};
        if (net::tls_exporter(ssl, exported.data(), exported.size()))
            binding.assign(reinterpret_cast<const char*>(exported.data()), exported.size());
        if (!tls_pin.empty()) {
            std::array<std::uint8_t, 32> digest{};
            const bool got = net::tls_peer_sha256(ssl, digest.data());
            const std::string hex = net::to_hex(Bytes(digest.data(), digest.size()));
            if (!got || !net::hex_equal(hex, tls_pin)) {
                net::close_socket(*fd);
                net::tls_free(ssl);
                connect_error = "TLS certificate pin mismatch";
                return std::nullopt;
            }
        }
        return net::Stream::tls_stream(*fd, ssl);
    }
    std::vector<std::string> argv = {path_to_bytes(net::self_exe()), "serve", "-stdio", url.path};
    auto stream = net::Stream::spawn_argv(argv);
    if (!stream)
        connect_error = "cannot start the local vn server";
    return stream;
}

std::string id_text(const Id& id) {
    return hex_encode(id);
}

} // namespace

// ---------------------------------------------------------------------------
// Message codecs
// ---------------------------------------------------------------------------

std::vector<std::uint8_t> encode_hello(const Hello& hello) {
    ByteWriter writer(128);
    put_u16_be(writer, hello.min_version);
    put_u16_be(writer, hello.max_version);
    writer.raw(Bytes(encode_string_list(hello.capabilities)));
    writer.length_prefixed(hello.repo);
    writer.length_prefixed(hello.client_nonce);
    return writer.take();
}

std::optional<Hello> decode_hello(Bytes data) {
    Reader reader(data);
    const auto min_version = read_u16_be(reader);
    if (!min_version)
        return std::nullopt;
    const auto max_version = read_u16_be(reader);
    if (!max_version)
        return std::nullopt;
    auto capabilities = decode_string_list(reader, 64);
    if (!capabilities)
        return std::nullopt;
    const auto repo = reader.bytes(4096);
    if (!repo)
        return std::nullopt;
    const auto nonce = reader.bytes(64);
    if (!nonce)
        return std::nullopt;
    if (!reader.finish())
        return std::nullopt;
    Hello out;
    out.min_version = *min_version;
    out.max_version = *max_version;
    out.capabilities = std::move(*capabilities);
    out.repo = bytes_to_string(*repo);
    out.client_nonce = bytes_to_string(*nonce);
    return out;
}

std::vector<std::uint8_t> encode_hello_ok(const HelloOk& hello) {
    ByteWriter writer(128);
    put_u16_be(writer, hello.version);
    writer.raw(Bytes(encode_string_list(hello.capabilities)));
    writer.length_prefixed(hello.server_nonce);
    writer.u8(hello.auth_required);
    return writer.take();
}

std::optional<HelloOk> decode_hello_ok(Bytes data) {
    Reader reader(data);
    const auto version = read_u16_be(reader);
    if (!version)
        return std::nullopt;
    auto capabilities = decode_string_list(reader, 64);
    if (!capabilities)
        return std::nullopt;
    const auto nonce = reader.bytes(64);
    if (!nonce)
        return std::nullopt;
    const auto auth = reader.u8();
    if (!auth)
        return std::nullopt;
    if (!reader.finish())
        return std::nullopt;
    HelloOk out;
    out.version = *version;
    out.capabilities = std::move(*capabilities);
    out.server_nonce = bytes_to_string(*nonce);
    out.auth_required = *auth;
    return out;
}

std::vector<std::uint8_t> encode_auth(const Auth& auth) {
    ByteWriter writer(128);
    writer.length_prefixed(auth.public_key);
    writer.length_prefixed(auth.signature);
    return writer.take();
}

std::optional<Auth> decode_auth(Bytes data) {
    Reader reader(data);
    const auto public_key = reader.bytes(64);
    if (!public_key)
        return std::nullopt;
    const auto signature = reader.bytes(128);
    if (!signature)
        return std::nullopt;
    if (!reader.finish())
        return std::nullopt;
    return Auth{bytes_to_string(*public_key), bytes_to_string(*signature)};
}

std::vector<std::uint8_t> encode_auth_ok(const AuthOk& auth) {
    ByteWriter writer(64);
    writer.u8(auth.role);
    writer.length_prefixed(auth.fingerprint);
    return writer.take();
}

std::optional<AuthOk> decode_auth_ok(Bytes data) {
    Reader reader(data);
    const auto role = reader.u8();
    if (!role)
        return std::nullopt;
    const auto fingerprint = reader.bytes(64);
    if (!fingerprint)
        return std::nullopt;
    if (!reader.finish())
        return std::nullopt;
    return AuthOk{*role, bytes_to_string(*fingerprint)};
}

std::vector<std::uint8_t> encode_refs(const std::vector<RefInfo>& refs) {
    ByteWriter writer(256);
    writer.varint(refs.size());
    for (const auto& ref : refs) {
        writer.length_prefixed(ref.name);
        append_id(writer, ref.target);
        writer.length_prefixed(ref.change_id);
        writer.u8(ref.kind);
    }
    return writer.take();
}

std::optional<std::vector<RefInfo>> decode_refs(Bytes data) {
    Reader reader(data);
    const auto count = reader.list_len(1000000);
    if (!count)
        return std::nullopt;
    std::vector<RefInfo> out;
    out.reserve(*count);
    for (std::size_t i = 0; i < *count; ++i) {
        const auto name = reader.bytes(4096);
        if (!name)
            return std::nullopt;
        const auto target = read_id(reader);
        if (!target)
            return std::nullopt;
        const auto change_id = reader.bytes(64);
        if (!change_id)
            return std::nullopt;
        const auto kind = reader.u8();
        if (!kind)
            return std::nullopt;
        RefInfo ref;
        ref.name = bytes_to_string(*name);
        ref.target = *target;
        ref.change_id = bytes_to_string(*change_id);
        ref.kind = *kind;
        out.push_back(std::move(ref));
    }
    if (!reader.finish())
        return std::nullopt;
    return out;
}

std::vector<std::uint8_t> encode_ids(const std::vector<Id>& ids) {
    ByteWriter writer(ids.size() * 32 + 8);
    writer.varint(ids.size());
    for (const auto& id : ids)
        append_id(writer, id);
    return writer.take();
}

std::optional<std::vector<Id>> decode_ids(Bytes data, std::size_t max) {
    Reader reader(data);
    const auto count = reader.list_len(max);
    if (!count)
        return std::nullopt;
    std::vector<Id> out;
    out.reserve(*count);
    for (std::size_t i = 0; i < *count; ++i) {
        const auto id = read_id(reader);
        if (!id)
            return std::nullopt;
        out.push_back(*id);
    }
    if (!reader.finish())
        return std::nullopt;
    return out;
}

std::vector<std::uint8_t> encode_negotiate(const std::vector<Id>& wants,
                                           const std::vector<Id>& haves) {
    ByteWriter writer(256);
    writer.varint(wants.size());
    for (const auto& id : wants)
        append_id(writer, id);
    writer.varint(haves.size());
    for (const auto& id : haves)
        append_id(writer, id);
    return writer.take();
}

std::optional<Negotiate> decode_negotiate(Bytes data) {
    Reader reader(data);
    const auto want_count = reader.list_len(1000000);
    if (!want_count)
        return std::nullopt;
    Negotiate out;
    out.wants.reserve(*want_count);
    for (std::size_t i = 0; i < *want_count; ++i) {
        const auto id = read_id(reader);
        if (!id)
            return std::nullopt;
        out.wants.push_back(*id);
    }
    const auto have_count = reader.list_len(1000000);
    if (!have_count)
        return std::nullopt;
    out.haves.reserve(*have_count);
    for (std::size_t i = 0; i < *have_count; ++i) {
        const auto id = read_id(reader);
        if (!id)
            return std::nullopt;
        out.haves.push_back(*id);
    }
    if (!reader.finish())
        return std::nullopt;
    return out;
}

std::vector<std::uint8_t> encode_negotiate_ok(const std::vector<std::uint8_t>& known,
                                              std::uint8_t enough) {
    ByteWriter writer(known.size() + 16);
    writer.u8(enough);
    writer.varint(known.size());
    for (std::uint8_t bit : known)
        writer.u8(bit);
    return writer.take();
}

std::optional<std::vector<std::uint8_t>> decode_negotiate_ok(Bytes data) {
    Reader reader(data);
    const auto enough = reader.u8();
    if (!enough)
        return std::nullopt;
    const auto count = reader.list_len(1000000);
    if (!count)
        return std::nullopt;
    std::vector<std::uint8_t> out;
    out.reserve(*count);
    for (std::size_t i = 0; i < *count; ++i) {
        const auto bit = reader.u8();
        if (!bit)
            return std::nullopt;
        out.push_back(*bit);
    }
    if (!reader.finish())
        return std::nullopt;
    return out;
}

std::vector<std::uint8_t> encode_bitmap(const std::vector<std::uint8_t>& bits) {
    ByteWriter writer(bits.size() + 8);
    writer.varint(bits.size());
    for (std::uint8_t bit : bits)
        writer.u8(bit);
    return writer.take();
}

std::optional<std::vector<std::uint8_t>> decode_bitmap(Bytes data) {
    Reader reader(data);
    const auto count = reader.list_len(1000000);
    if (!count)
        return std::nullopt;
    std::vector<std::uint8_t> out;
    out.reserve(*count);
    for (std::size_t i = 0; i < *count; ++i) {
        const auto bit = reader.u8();
        if (!bit)
            return std::nullopt;
        out.push_back(*bit);
    }
    if (!reader.finish())
        return std::nullopt;
    return out;
}

std::vector<std::uint8_t> encode_update_refs(const std::vector<UpdateRef>& updates) {
    ByteWriter writer(256);
    writer.varint(updates.size());
    for (const auto& update : updates) {
        writer.length_prefixed(update.name);
        writer.opt_id(update.expected);
        writer.opt_id(update.target);
    }
    return writer.take();
}

std::optional<std::vector<UpdateRef>> decode_update_refs(Bytes data) {
    Reader reader(data);
    const auto count = reader.list_len(1000000);
    if (!count)
        return std::nullopt;
    std::vector<UpdateRef> out;
    out.reserve(*count);
    for (std::size_t i = 0; i < *count; ++i) {
        const auto name = reader.bytes(4096);
        if (!name)
            return std::nullopt;
        const auto expected = reader.opt_id();
        if (!expected)
            return std::nullopt;
        const auto target = reader.opt_id();
        if (!target)
            return std::nullopt;
        UpdateRef update;
        update.name = bytes_to_string(*name);
        update.expected = *expected;
        update.target = *target;
        out.push_back(std::move(update));
    }
    if (!reader.finish())
        return std::nullopt;
    return out;
}

std::string auth_message(std::uint16_t version, std::string_view repo, Bytes server_nonce,
                         Bytes client_nonce, Bytes binding) {
    ByteWriter writer(128);
    writer.raw(std::string_view("veins-auth/1"));
    writer.u8(0);
    writer.u8(static_cast<std::uint8_t>((version >> 8) & 255u));
    writer.u8(static_cast<std::uint8_t>(version & 255u));
    writer.length_prefixed(repo);
    writer.raw(server_nonce);
    writer.raw(client_nonce);
    writer.raw(binding);
    return std::string(str_of(writer.view()));
}

std::string_view role_name(std::uint8_t role) {
    if (role == 2)
        return "write";
    if (role == 1)
        return "read";
    return "anonymous";
}

// ---------------------------------------------------------------------------
// URLs
// ---------------------------------------------------------------------------

std::optional<Url> parse_url(std::string_view url) {
    constexpr std::string_view file_prefix = "file://";
    constexpr std::string_view ssh_prefix = "ssh://";
    constexpr std::string_view veins_prefix = "veins://";
    if (url.starts_with(file_prefix))
        return Url{false, false, {}, 0, std::string(url.substr(file_prefix.size()))};
    if (url.starts_with(ssh_prefix)) {
        std::string_view rest = url.substr(ssh_prefix.size());
        const auto slash = rest.find('/');
        if (slash == std::string_view::npos)
            return std::nullopt;
        const auto authority = parse_authority(rest.substr(0, slash), 22, true);
        return Url{false, true, authority.host, authority.port,
                   std::string(rest.substr(slash + 1))};
    }
    if (url.starts_with(veins_prefix)) {
        std::string_view rest = url.substr(veins_prefix.size());
        const auto slash = rest.find('/');
        if (slash == std::string_view::npos)
            return std::nullopt;
        const auto authority = parse_authority(rest.substr(0, slash), 7419, false);
        return Url{true, false, authority.host, authority.port,
                   std::string(rest.substr(slash + 1))};
    }
    return std::nullopt;
}

std::string url_repo_name(std::string_view url) {
    auto parsed = parse_url(url);
    if (!parsed || !parsed->tls)
        return {};
    return parsed->path;
}

// ---------------------------------------------------------------------------
// Client
// ---------------------------------------------------------------------------

void Client::set_error(std::string text) {
    last_error_ = std::move(text);
}

void Client::set_error_frame(const wire::Frame& frame) {
    const std::uint8_t code = wire::read_error(frame.payload);
    const std::string_view name = wire::error_code_name(code);
    const std::string message = wire::error_message(frame.payload);
    std::string text = "server error: ";
    text += name;
    if (!message.empty()) {
        text += ": ";
        text += message;
    }
    set_error(std::move(text));
}

std::optional<wire::Frame> Client::request(std::uint8_t kind, Bytes payload) {
    const std::uint32_t rid = static_cast<std::uint32_t>(unix_now_millis() & 0x7fffffff);
    if (!wire::write_frame(stream_, kind, rid, payload)) {
        set_error("connection closed while sending request");
        return std::nullopt;
    }
    auto frame = wire::read_frame(stream_);
    if (!frame) {
        set_error("connection closed while waiting for server response");
        return std::nullopt;
    }
    if (frame->kind == wire::ERROR) {
        set_error_frame(*frame);
        return std::nullopt;
    }
    return frame;
}

const std::string& Client::last_connect_error() {
    return connect_error;
}

std::optional<Client> Client::connect(std::string_view url, std::string_view key_name,
                                      std::string_view repo_name, std::string_view tls_pin) {
    connect_error.clear();
    auto parsed = parse_url(url);
    if (!parsed) {
        connect_error = "invalid remote URL";
        return std::nullopt;
    }
    std::string binding;
    auto stream = connect_stream(*parsed, tls_pin, binding);
    if (!stream) {
        if (connect_error.empty())
            connect_error = "cannot establish a connection";
        return std::nullopt;
    }

    const auto nonce_bytes = secure_random(32);
    if (nonce_bytes.size() != 32) {
        stream->close();
        connect_error = "cannot generate a secure nonce";
        return std::nullopt;
    }
    const std::string client_nonce(reinterpret_cast<const char*>(nonce_bytes.data()),
                                   nonce_bytes.size());

    Hello hello;
    hello.capabilities = {"zstd-records", "lazy-chunks", "push", "auth-ed25519"};
    hello.repo = std::string(repo_name);
    hello.client_nonce = client_nonce;
    const auto hello_body = encode_hello(hello);
    if (!wire::write_frame(*stream, wire::HELLO, 1, hello_body)) {
        stream->close();
        connect_error = "connection closed during the protocol handshake";
        return std::nullopt;
    }
    auto hello_frame = wire::read_frame(*stream);
    if (!hello_frame || hello_frame->kind != wire::HELLO_OK) {
        stream->close();
        connect_error = "server rejected the protocol handshake";
        return std::nullopt;
    }
    auto hello_ok = decode_hello_ok(hello_frame->payload);
    if (!hello_ok) {
        stream->close();
        connect_error = "server sent an invalid protocol handshake";
        return std::nullopt;
    }

    Client client;
    client.stream_ = std::move(*stream);
    client.binding_ = std::move(binding);
    client.version_ = hello_ok->version;

    std::string selected_key(key_name);
    if (selected_key.empty() && hello_ok->auth_required != 0)
        selected_key = "default";

    if (!selected_key.empty()) {
        auto key = auth::load_key(selected_key);
        if (key) {
            const std::string message = auth_message(
                hello_ok->version, repo_name,
                Bytes(reinterpret_cast<const std::uint8_t*>(hello_ok->server_nonce.data()),
                      hello_ok->server_nonce.size()),
                Bytes(reinterpret_cast<const std::uint8_t*>(client_nonce.data()),
                      client_nonce.size()),
                Bytes(reinterpret_cast<const std::uint8_t*>(client.binding_.data()),
                      client.binding_.size()));
            auto signature = ed25519_sign(
                Bytes(key->seed.data(), key->seed.size()),
                Bytes(reinterpret_cast<const std::uint8_t*>(message.data()), message.size()));
            if (signature) {
                Auth auth;
                auth.public_key.assign(reinterpret_cast<const char*>(key->public_key.data()),
                                       key->public_key.size());
                auth.signature.assign(reinterpret_cast<const char*>(signature->data()),
                                      signature->size());
                const auto body = encode_auth(auth);
                if (wire::write_frame(client.stream_, wire::AUTH, 2, body)) {
                    auto reply = wire::read_frame(client.stream_);
                    if (reply && reply->kind == wire::AUTH_OK) {
                        auto ok = decode_auth_ok(reply->payload);
                        if (ok) {
                            client.role_ = ok->role;
                            client.authed_ = true;
                            client.fingerprint_ = std::move(ok->fingerprint);
                        }
                    }
                }
            }
        }
    }

    if (hello_ok->auth_required != 0 && !client.authed_) {
        connect_error = selected_key.empty() ? "authentication required but no key is configured"
                                             : "authentication failed: the key is missing or not "
                                               "authorized";
        client.stream_.close();
        return std::nullopt;
    }
    connect_error.clear();
    return client;
}

bool Client::list_refs(std::vector<RefInfo>& refs) {
    auto frame = request(wire::LIST_REFS, Bytes{});
    if (!frame)
        return false;
    if (frame->kind != wire::REFS) {
        set_error("unexpected response to ref listing (message kind " +
                  std::to_string(frame->kind) + ")");
        return false;
    }
    auto decoded = decode_refs(frame->payload);
    if (!decoded)
        return false;
    refs = std::move(*decoded);
    return true;
}

bool Client::negotiate(const std::vector<Id>& wants, const std::vector<Id>& haves) {
    const auto body = encode_negotiate(wants, haves);
    auto frame = request(wire::NEGOTIATE, body);
    if (!frame)
        return false;
    if (frame->kind != wire::NEGOTIATE_OK) {
        set_error("unexpected response to negotiation (message kind " +
                  std::to_string(frame->kind) + ")");
        return false;
    }
    return true;
}

bool Client::receive_stream(const fs::path& repo) {
    blake3_hasher hasher;
    blake3_hasher_init(&hasher);
    Writer writer;
    bool good = true;

    for (;;) {
        auto frame = wire::read_frame(stream_);
        if (!frame) {
            set_error("connection closed while receiving data");
            return false;
        }
        if (frame->kind == wire::END) {
            std::array<std::uint8_t, 32> digest{};
            blake3_hasher_finalize(&hasher, digest.data(), digest.size());
            if (frame->payload.size() != digest.size() ||
                std::memcmp(frame->payload.data(), digest.data(), digest.size()) != 0) {
                set_error("server sent a corrupt transfer checksum");
                return false;
            }
            break;
        }
        if (frame->kind == wire::ERROR) {
            set_error_frame(*frame);
            return false;
        }
        if (frame->kind != wire::RECORDS) {
            set_error("unexpected message while receiving data (message kind " +
                      std::to_string(frame->kind) + ")");
            return false;
        }
        blake3_hasher_update(&hasher, frame->payload.data(), frame->payload.size());
        auto record = wire::parse_record(bytes_of(frame->payload));
        if (!record) {
            good = false;
        } else {
            const Id computed = object_id(record->kind, bytes_of(record->body));
            if (std::memcmp(computed.data(), record->id.data(), ID_LEN) != 0) {
                good = false;
            } else {
                writer.add_known(record->kind, record->id, std::move(record->body));
            }
        }
        if (!good)
            return false;
    }

    if (writer.finish(repo) != 0) {
        set_error("cannot write incoming objects to the store");
        return false;
    }
    return true;
}

bool Client::fetch_skeleton(const fs::path& repo, const std::vector<Id>& wants) {
    const auto body = encode_ids(wants);
    const std::uint32_t rid = static_cast<std::uint32_t>(unix_now_millis() & 0x7fffffff);
    if (!wire::write_frame(stream_, wire::FETCH_SKELETON, rid, body)) {
        set_error("connection closed while requesting objects");
        return false;
    }
    return receive_stream(repo);
}

bool Client::get_chunks(const fs::path& repo, const std::vector<Id>& ids) {
    if (ids.empty())
        return true;
    const auto body = encode_ids(ids);
    const std::uint32_t rid = static_cast<std::uint32_t>(unix_now_millis() & 0x7fffffff);
    if (!wire::write_frame(stream_, wire::GET_CHUNKS, rid, body)) {
        set_error("connection closed while requesting chunks");
        return false;
    }
    return receive_stream(repo);
}

bool Client::have_query(const std::vector<Id>& ids, std::vector<std::uint8_t>& bits) {
    const auto body = encode_ids(ids);
    auto frame = request(wire::HAVE_QUERY, body);
    if (!frame)
        return false;
    if (frame->kind != wire::HAVE_BITMAP)
        return false;
    auto decoded = decode_bitmap(frame->payload);
    if (!decoded)
        return false;
    bits = std::move(*decoded);
    return true;
}

bool Client::push_objects(const fs::path& repo, const std::vector<Id>& ids) {
    const std::uint32_t rid = static_cast<std::uint32_t>(unix_now_millis() & 0x7fffffff);
    if (!wire::write_frame(stream_, wire::PUT_RECORDS, rid, Bytes{})) {
        set_error("connection closed while starting push");
        return false;
    }
    Store store = Store::open_all(repo);
    blake3_hasher hasher;
    blake3_hasher_init(&hasher);
    bool good = true;
    for (const auto& id : ids) {
        const auto loc = store.find(id);
        if (!loc) {
            set_error("local object is missing from the store: " + id_text(id));
            good = false;
            break;
        }
        auto body = store.read_body(id, loc->kind);
        if (!body) {
            set_error("cannot read local object from the store: " + id_text(id));
            good = false;
            break;
        }
        const auto record = wire::make_record(id, loc->kind, bytes_of(*body));
        blake3_hasher_update(&hasher, record.data(), record.size());
        if (!wire::write_frame(stream_, wire::RECORDS, rid, Bytes(record.data(), record.size()))) {
            set_error("connection closed while sending object: " + id_text(id));
            good = false;
            break;
        }
    }
    std::array<std::uint8_t, 32> digest{};
    blake3_hasher_finalize(&hasher, digest.data(), digest.size());
    if (!good)
        return false;
    if (!wire::write_frame(stream_, wire::END, rid, Bytes(digest.data(), digest.size()))) {
        set_error("connection closed while finishing push");
        return false;
    }
    auto ack = wire::read_frame(stream_);
    if (!ack) {
        set_error("server closed the connection before acknowledging the push");
        return false;
    }
    if (ack->kind == wire::END)
        return true;
    if (ack->kind == wire::ERROR) {
        set_error_frame(*ack);
        return false;
    }
    set_error("unexpected response to object push (message kind " + std::to_string(ack->kind) +
              ")");
    return false;
}

bool Client::update_refs(const std::vector<UpdateRef>& updates) {
    const auto body = encode_update_refs(updates);
    auto frame = request(wire::UPDATE_REFS, body);
    if (!frame)
        return false;
    if (frame->kind != wire::UPDATE_REFS_OK) {
        set_error("unexpected response to ref update (message kind " + std::to_string(frame->kind) +
                  ")");
        return false;
    }
    return true;
}

bool Client::whoami(std::uint8_t& role, std::string& fingerprint) {
    auto frame = request(wire::WHOAMI, Bytes{});
    if (!frame)
        return false;
    if (frame->kind != wire::WHOAMI_OK)
        return false;
    Reader reader(frame->payload);
    const auto role_value = reader.u8();
    if (!role_value)
        return false;
    const auto fp = reader.bytes(64);
    if (!fp)
        return false;
    role = *role_value;
    fingerprint = bytes_to_string(*fp);
    return true;
}

} // namespace vn::proto