• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

realm / realm-core / github_pull_request_281750

30 Oct 2023 03:37PM UTC coverage: 90.528% (-1.0%) from 91.571%
github_pull_request_281750

Pull #6073

Evergreen

jedelbo
Log free space and history sizes when opening file
Pull Request #6073: Merge next-major

95488 of 175952 branches covered (0.0%)

8973 of 12277 new or added lines in 149 files covered. (73.09%)

622 existing lines in 51 files now uncovered.

233503 of 257934 relevant lines covered (90.53%)

6533720.56 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

76.71
/src/realm/sync/noinst/protocol_codec.hpp
1
#ifndef REALM_NOINST_PROTOCOL_CODEC_HPP
2
#define REALM_NOINST_PROTOCOL_CODEC_HPP
3

4
#include <cstdint>
5
#include <algorithm>
6
#include <memory>
7
#include <vector>
8
#include <string>
9

10
#include <realm/util/buffer_stream.hpp>
11
#include <realm/util/compression.hpp>
12
#include <realm/util/from_chars.hpp>
13
#include <realm/util/logger.hpp>
14
#include <realm/util/memory_stream.hpp>
15
#include <realm/util/optional.hpp>
16
#include <realm/binary_data.hpp>
17
#include <realm/chunked_binary.hpp>
18
#include <realm/sync/changeset_parser.hpp>
19
#include <realm/sync/history.hpp>
20
#include <realm/sync/impl/clamped_hex_dump.hpp>
21
#include <realm/sync/noinst/integer_codec.hpp>
22
#include <realm/sync/protocol.hpp>
23
#include <realm/sync/transform.hpp>
24

25
#include <external/json/json.hpp>
26

27
namespace realm::_impl {
28
struct ProtocolCodecException : public std::runtime_error {
29
    using std::runtime_error::runtime_error;
30
};
31
class HeaderLineParser {
32
public:
33
    explicit HeaderLineParser(std::string_view line)
34
        : m_sv(line)
35
    {
152,272✔
36
    }
152,272✔
37

38
    template <typename T>
39
    T read_next(char expected_terminator = ' ')
40
    {
1,534,276✔
41
        const auto [tok, rest] = peek_token_impl<T>();
1,534,276✔
42
        if (rest.empty()) {
1,534,276✔
43
            throw ProtocolCodecException("header line ended prematurely without terminator");
×
44
        }
×
45
        if (rest.front() != expected_terminator) {
1,534,276✔
46
            throw ProtocolCodecException(util::format(
×
47
                "expected to find delimeter '%1' in header line, but found '%2'", expected_terminator, rest.front()));
×
48
        }
×
49
        m_sv = rest.substr(1);
1,534,276✔
50
        return tok;
1,534,276✔
51
    }
1,534,276✔
52

53
    template <typename T>
54
    T read_sized_data(size_t size)
55
    {
102,794✔
56
        auto ret = m_sv;
102,794✔
57
        advance(size);
102,794✔
58
        return T(ret.data(), size);
102,794✔
59
    }
102,794✔
60

61
    size_t bytes_remaining() const noexcept
62
    {
80,712✔
63
        return m_sv.size();
80,712✔
64
    }
80,712✔
65

66
    std::string_view remaining() const noexcept
67
    {
93,256✔
68
        return m_sv;
93,256✔
69
    }
93,256✔
70

71
    bool at_end() const noexcept
72
    {
1,774,368✔
73
        return m_sv.empty();
1,774,368✔
74
    }
1,774,368✔
75

76
    void advance(size_t size)
77
    {
102,838✔
78
        if (size > m_sv.size()) {
102,838✔
79
            throw ProtocolCodecException(
×
80
                util::format("cannot advance header by %1 characters, only %2 characters left", size, m_sv.size()));
×
81
        }
×
82
        m_sv.remove_prefix(size);
102,838✔
83
    }
102,838✔
84

85
private:
86
    template <typename T>
87
    std::pair<T, std::string_view> peek_token_impl() const
88
    {
1,534,026✔
89
        // We currently only support numeric, string, and boolean values in header lines.
789,772✔
90
        static_assert(std::is_integral_v<T> || is_any_v<T, std::string_view, std::string>);
1,534,026✔
91
        if (at_end()) {
1,534,026✔
92
            throw ProtocolCodecException("reached end of header line prematurely");
×
93
        }
×
94
        if constexpr (is_any_v<T, std::string_view, std::string>) {
1,534,026✔
95
            // Currently all string fields in wire protocol header lines appear at the beginning of the line and
716,914✔
96
            // should be delimited by a space.
716,914✔
97
            auto delim_at = m_sv.find(' ');
1,390,600✔
98
            if (delim_at == std::string_view::npos) {
787,478✔
99
                throw ProtocolCodecException("reached end of header line prematurely");
×
100
            }
×
101

72,850✔
102
            return {m_sv.substr(0, delim_at), m_sv.substr(delim_at)};
143,414✔
103
        }
143,414✔
104
        else if constexpr (std::is_integral_v<T> && !std::is_same_v<T, bool>) {
1,390,600✔
105
            T cur_arg = {};
102,450✔
106
            auto parse_res = util::from_chars(m_sv.data(), m_sv.data() + m_sv.size(), cur_arg, 10);
102,450✔
107
            if (parse_res.ec != std::errc{}) {
1,287,726✔
108
                throw ProtocolCodecException(util::format("error parsing integer in header line: %1",
×
109
                                                          std::make_error_code(parse_res.ec).message()));
×
110
            }
×
111

663,876✔
112
            return {cur_arg, m_sv.substr(parse_res.ptr - m_sv.data())};
1,287,726✔
113
        }
1,287,726✔
114
        else if constexpr (std::is_same_v<T, bool>) {
102,456✔
115
            int cur_arg;
102,456✔
116
            auto parse_res = util::from_chars(m_sv.data(), m_sv.data() + m_sv.size(), cur_arg, 10);
102,456✔
117
            if (parse_res.ec != std::errc{}) {
102,456✔
118
                throw ProtocolCodecException(util::format("error parsing boolean in header line: %1",
×
119
                                                          std::make_error_code(parse_res.ec).message()));
×
120
            }
×
121

52,912✔
122
            return {(cur_arg != 0), m_sv.substr(parse_res.ptr - m_sv.data())};
102,456✔
123
        }
102,456✔
124
    }
1,534,026✔
125

126
    std::string_view m_sv;
127
};
128

129
class ClientProtocol {
130
public:
131
    // clang-format off
132
    using file_ident_type    = sync::file_ident_type;
133
    using version_type       = sync::version_type;
134
    using salt_type          = sync::salt_type;
135
    using timestamp_type     = sync::timestamp_type;
136
    using session_ident_type = sync::session_ident_type;
137
    using request_ident_type = sync::request_ident_type;
138
    using milliseconds_type  = sync::milliseconds_type;
139
    using SaltedFileIdent    = sync::SaltedFileIdent;
140
    using SaltedVersion      = sync::SaltedVersion;
141
    using DownloadCursor     = sync::DownloadCursor;
142
    using UploadCursor       = sync::UploadCursor;
143
    using SyncProgress       = sync::SyncProgress;
144
    // clang-format on
145

146
    using OutputBuffer = util::ResettableExpandableBufferOutputStream;
147
    using RemoteChangeset = sync::Transformer::RemoteChangeset;
148
    using ReceivedChangesets = std::vector<RemoteChangeset>;
149

150
    /// Messages sent by the client.
151

152
    void make_pbs_bind_message(int protocol_version, OutputBuffer&, session_ident_type session_ident,
153
                               const std::string& server_path, const std::string& signed_user_token,
154
                               bool need_client_file_ident, bool is_subserver);
155

156
    void make_flx_bind_message(int protocol_version, OutputBuffer& out, session_ident_type session_ident,
157
                               const nlohmann::json& json_data, const std::string& signed_user_token,
158
                               bool need_client_file_ident, bool is_subserver);
159

160
    void make_pbs_ident_message(OutputBuffer&, session_ident_type session_ident, SaltedFileIdent client_file_ident,
161
                                const SyncProgress& progress);
162

163
    void make_flx_ident_message(OutputBuffer&, session_ident_type session_ident, SaltedFileIdent client_file_ident,
164
                                const SyncProgress& progress, int64_t query_version, std::string_view query_body);
165

166
    void make_query_change_message(OutputBuffer&, session_ident_type, int64_t version, std::string_view query_body);
167

168
    void make_json_error_message(OutputBuffer&, session_ident_type, int error_code, std::string_view error_body);
169

170
    void make_test_command_message(OutputBuffer&, session_ident_type session, request_ident_type request_ident,
171
                                   std::string_view body);
172

173
    class UploadMessageBuilder {
174
    public:
175
        UploadMessageBuilder(OutputBuffer& body_buffer, std::vector<char>& compression_buffer,
176
                             util::compression::CompressMemoryArena& compress_memory_arena);
177

178
        void add_changeset(version_type client_version, version_type server_version, timestamp_type origin_timestamp,
179
                           file_ident_type origin_file_ident, ChunkedBinaryData changeset);
180

181
        void make_upload_message(int protocol_version, OutputBuffer&, session_ident_type session_ident,
182
                                 version_type progress_client_version, version_type progress_server_version,
183
                                 version_type locked_server_version);
184

185
    private:
186
        std::size_t m_num_changesets = 0;
187
        OutputBuffer& m_body_buffer;
188
        std::vector<char>& m_compression_buffer;
189
        util::compression::CompressMemoryArena& m_compress_memory_arena;
190
    };
191

192
    UploadMessageBuilder make_upload_message_builder();
193

194
    void make_unbind_message(OutputBuffer&, session_ident_type session_ident);
195

196
    void make_mark_message(OutputBuffer&, session_ident_type session_ident, request_ident_type request_ident);
197

198
    void make_ping(OutputBuffer&, milliseconds_type timestamp, milliseconds_type rtt);
199

200
    std::string compressed_hex_dump(BinaryData blob);
201

202
    // Messages received by the client.
203

204
    // parse_message_received takes a (WebSocket) message and parses it.
205
    // The result of the parsing is handled by an object of type Connection.
206
    // Typically, Connection would be the Connection class from client.cpp
207
    template <class Connection>
208
    void parse_message_received(Connection& connection, std::string_view msg_data)
209
    {
74,010✔
210
        util::Logger& logger = connection.logger;
74,010✔
211
        auto report_error = [&](const auto fmt, auto&&... args) {
38,380✔
212
            auto msg = util::format(fmt, std::forward<decltype(args)>(args)...);
×
213
            connection.handle_protocol_error(Status{ErrorCodes::SyncProtocolInvariantFailed, std::move(msg)});
×
214
        };
×
215

38,380✔
216
        HeaderLineParser msg(msg_data);
74,010✔
217
        std::string_view message_type;
74,010✔
218
        try {
74,010✔
219
            message_type = msg.read_next<std::string_view>();
74,010✔
220
        }
74,010✔
221
        catch (const ProtocolCodecException& e) {
38,380✔
222
            return report_error("Could not find message type in message: %1", e.what());
×
223
        }
×
224

38,384✔
225
        try {
74,012✔
226
            if (message_type == "download") {
74,012✔
227
                parse_download_message(connection, msg);
44,054✔
228
            }
44,054✔
229
            else if (message_type == "pong") {
29,958✔
230
                auto timestamp = msg.read_next<milliseconds_type>('\n');
186✔
231
                connection.receive_pong(timestamp);
186✔
232
            }
186✔
233
            else if (message_type == "unbound") {
29,772✔
234
                auto session_ident = msg.read_next<session_ident_type>('\n');
4,110✔
235
                connection.receive_unbound_message(session_ident); // Throws
4,110✔
236
            }
4,110✔
237
            else if (message_type == "error") {
25,662✔
238
                auto error_code = msg.read_next<int>();
84✔
239
                auto message_size = msg.read_next<size_t>();
84✔
240
                auto is_fatal = sync::IsFatal{!msg.read_next<bool>()};
84✔
241
                auto session_ident = msg.read_next<session_ident_type>('\n');
84✔
242
                auto message = msg.read_sized_data<StringData>(message_size);
84✔
243

42✔
244
                connection.receive_error_message(sync::ProtocolErrorInfo{error_code, message, is_fatal},
84✔
245
                                                 session_ident); // Throws
84✔
246
            }
84✔
247
            else if (message_type == "log_message") { // introduced in protocol version 10
25,578✔
248
                parse_log_message(connection, msg);
5,726✔
249
            }
5,726✔
250
            else if (message_type == "json_error") { // introduced in protocol 4
19,852✔
251
                sync::ProtocolErrorInfo info{};
894✔
252
                info.raw_error_code = msg.read_next<int>();
894✔
253
                auto message_size = msg.read_next<size_t>();
894✔
254
                auto session_ident = msg.read_next<session_ident_type>('\n');
894✔
255
                auto json_raw = msg.read_sized_data<std::string_view>(message_size);
894✔
256
                try {
894✔
257
                    auto json = nlohmann::json::parse(json_raw);
894✔
258
                    logger.trace(util::LogCategory::session, "Error message encoded as json: %1", json_raw);
894✔
259
                    info.client_reset_recovery_is_disabled = json["isRecoveryModeDisabled"];
894✔
260
                    info.is_fatal = sync::IsFatal{!json["tryAgain"]};
894✔
261
                    info.message = json["message"];
894✔
262
                    info.log_url = std::make_optional<std::string>(json["logURL"]);
894✔
263
                    info.should_client_reset = std::make_optional<bool>(json["shouldClientReset"]);
894✔
264
                    info.server_requests_action = string_to_action(json["action"]); // Throws
894✔
265

464✔
266
                    if (auto backoff_interval = json.find("backoffIntervalSec"); backoff_interval != json.end()) {
894✔
267
                        info.resumption_delay_interval.emplace();
762✔
268
                        info.resumption_delay_interval->resumption_delay_interval =
762✔
269
                            std::chrono::seconds{backoff_interval->get<int>()};
762✔
270
                        info.resumption_delay_interval->max_resumption_delay_interval =
762✔
271
                            std::chrono::seconds{json.at("backoffMaxDelaySec").get<int>()};
762✔
272
                        info.resumption_delay_interval->resumption_delay_backoff_multiplier =
762✔
273
                            json.at("backoffMultiplier").get<int>();
762✔
274
                    }
762✔
275

464✔
276
                    if (info.raw_error_code == static_cast<int>(sync::ProtocolError::migrate_to_flx)) {
894✔
277
                        auto query_string = json.find("partitionQuery");
36✔
278
                        if (query_string == json.end() || !query_string->is_string() ||
36✔
279
                            query_string->get<std::string_view>().empty()) {
36✔
280
                            return report_error(
×
281
                                "Missing/invalid partition query string in migrate to flexible sync error response");
×
282
                        }
×
283

18✔
284
                        info.migration_query_string.emplace(query_string->get<std::string_view>());
36✔
285
                    }
36✔
286

464✔
287
                    if (auto rejected_updates = json.find("rejectedUpdates"); rejected_updates != json.end()) {
894✔
288
                        if (!rejected_updates->is_array()) {
48✔
289
                            return report_error(
×
290
                                "Compensating writes error list is not stored in an array as expected");
×
291
                        }
×
292

24✔
293
                        for (const auto& rejected_update : *rejected_updates) {
52✔
294
                            if (!rejected_update.is_object()) {
52✔
295
                                return report_error(
×
296
                                    "Compensating write error information is not stored in an object as expected");
×
297
                            }
×
298

26✔
299
                            sync::CompensatingWriteErrorInfo cwei;
52✔
300
                            cwei.reason = rejected_update["reason"];
52✔
301
                            cwei.object_name = rejected_update["table"];
52✔
302
                            std::string_view pk = rejected_update["pk"].get<std::string_view>();
52✔
303
                            cwei.primary_key = sync::parse_base64_encoded_primary_key(pk);
52✔
304
                            info.compensating_writes.push_back(std::move(cwei));
52✔
305
                        }
52✔
306

24✔
307
                        // Not provided when 'write_not_allowed' (230) error is received from the server.
24✔
308
                        if (auto server_version = json.find("compensatingWriteServerVersion");
48✔
309
                            server_version != json.end()) {
48✔
310
                            info.compensating_write_server_version =
44✔
311
                                std::make_optional<version_type>(server_version->get<int64_t>());
44✔
312
                        }
44✔
313
                        info.compensating_write_rejected_client_version =
48✔
314
                            json.at("rejectedClientVersion").get<int64_t>();
48✔
315
                    }
48✔
316
                }
894✔
317
                catch (const nlohmann::json::exception& e) {
464✔
318
                    // If any of the above json fields are not present, this is a fatal error
319
                    // however, additional optional fields may be added in the future.
320
                    return report_error("Failed to parse 'json_error' with error_code %1: '%2'", info.raw_error_code,
×
321
                                        e.what());
×
322
                }
×
323
                connection.receive_error_message(info, session_ident); // Throws
894✔
324
            }
894✔
325
            else if (message_type == "query_error") {
18,958✔
326
                auto error_code = msg.read_next<int>();
16✔
327
                auto message_size = msg.read_next<size_t>();
16✔
328
                auto session_ident = msg.read_next<session_ident_type>();
16✔
329
                auto query_version = msg.read_next<int64_t>('\n');
16✔
330

8✔
331
                auto message = msg.read_sized_data<std::string_view>(message_size);
16✔
332

8✔
333
                connection.receive_query_error_message(error_code, message, query_version, session_ident); // throws
16✔
334
            }
16✔
335
            else if (message_type == "mark") {
18,942✔
336
                auto session_ident = msg.read_next<session_ident_type>();
15,660✔
337
                auto request_ident = msg.read_next<request_ident_type>('\n');
15,660✔
338

7,744✔
339
                connection.receive_mark_message(session_ident, request_ident); // Throws
15,660✔
340
            }
15,660✔
341
            else if (message_type == "ident") {
3,282✔
342
                session_ident_type session_ident = msg.read_next<session_ident_type>();
3,240✔
343
                SaltedFileIdent client_file_ident;
3,240✔
344
                client_file_ident.ident = msg.read_next<file_ident_type>();
3,240✔
345
                client_file_ident.salt = msg.read_next<salt_type>('\n');
3,240✔
346

1,504✔
347
                connection.receive_ident_message(session_ident, client_file_ident); // Throws
3,240✔
348
            }
3,240✔
349
            else if (message_type == "test_command") {
44✔
350
                session_ident_type session_ident = msg.read_next<session_ident_type>();
44✔
351
                request_ident_type request_ident = msg.read_next<request_ident_type>();
44✔
352
                auto body_size = msg.read_next<size_t>('\n');
44✔
353
                auto body = msg.read_sized_data<std::string_view>(body_size);
44✔
354

22✔
355
                connection.receive_test_command_response(session_ident, request_ident, body);
44✔
356
            }
44✔
357
            else {
2,147,483,647✔
358
                return report_error("Unknown input message type '%1'", msg_data);
2,147,483,647✔
359
            }
2,147,483,647✔
360
        }
×
361
        catch (const ProtocolCodecException& e) {
×
362
            return report_error("Bad syntax in %1 message: %2", message_type, e.what());
×
363
        }
×
364
        if (!msg.at_end()) {
74,014✔
365
            return report_error("wire protocol message had leftover data after being parsed");
×
366
        }
×
367
    }
74,014✔
368

369
private:
370
    template <typename Connection>
371
    void parse_download_message(Connection& connection, HeaderLineParser& msg)
372
    {
44,052✔
373
        util::Logger& logger = connection.logger;
44,052✔
374
        auto report_error = [&](ErrorCodes::Error code, const auto fmt, auto&&... args) {
23,790✔
375
            auto msg = util::format(fmt, std::forward<decltype(args)>(args)...);
×
376
            connection.handle_protocol_error(Status{code, std::move(msg)});
×
377
        };
×
378

23,790✔
379
        auto msg_with_header = msg.remaining();
44,052✔
380
        auto session_ident = msg.read_next<session_ident_type>();
44,052✔
381
        SyncProgress progress;
44,052✔
382
        progress.download.server_version = msg.read_next<version_type>();
44,052✔
383
        progress.download.last_integrated_client_version = msg.read_next<version_type>();
44,052✔
384
        progress.latest_server_version.version = msg.read_next<version_type>();
44,052✔
385
        progress.latest_server_version.salt = msg.read_next<salt_type>();
44,052✔
386
        progress.upload.client_version = msg.read_next<version_type>();
44,052✔
387
        progress.upload.last_integrated_server_version = msg.read_next<version_type>();
44,052✔
388
        auto query_version = connection.is_flx_sync_connection() ? msg.read_next<int64_t>() : 0;
42,756✔
389

23,790✔
390
        // If this is a PBS connection, then every download message is its own complete batch.
23,790✔
391
        auto last_in_batch = connection.is_flx_sync_connection() ? msg.read_next<bool>() : true;
42,756✔
392
        auto downloadable_bytes = msg.read_next<int64_t>();
44,052✔
393
        auto is_body_compressed = msg.read_next<bool>();
44,052✔
394
        auto uncompressed_body_size = msg.read_next<size_t>();
44,052✔
395
        auto compressed_body_size = msg.read_next<size_t>('\n');
44,052✔
396

23,790✔
397
        if (uncompressed_body_size > s_max_body_size) {
44,052✔
398
            auto header = msg_with_header.substr(0, msg_with_header.size() - msg.remaining().size());
×
399
            return report_error(ErrorCodes::LimitExceeded, "Limits exceeded in input message '%1'", header);
×
400
        }
×
401

23,790✔
402
        std::unique_ptr<char[]> uncompressed_body_buffer;
44,052✔
403
        // if is_body_compressed == true, we must decompress the received body.
23,790✔
404
        if (is_body_compressed) {
44,052✔
405
            uncompressed_body_buffer = std::make_unique<char[]>(uncompressed_body_size);
4,398✔
406
            std::error_code ec =
4,398✔
407
                util::compression::decompress({msg.remaining().data(), compressed_body_size},
4,398✔
408
                                              {uncompressed_body_buffer.get(), uncompressed_body_size});
4,398✔
409

2,186✔
410
            if (ec) {
4,398✔
411
                return report_error(ErrorCodes::RuntimeError, "compression::inflate: %1", ec.message());
×
412
            }
×
413

2,186✔
414
            msg = HeaderLineParser(std::string_view(uncompressed_body_buffer.get(), uncompressed_body_size));
4,398✔
415
        }
4,398✔
416

23,790✔
417
        logger.debug(util::LogCategory::changeset,
44,052✔
418
                     "Download message compression: session_ident=%1, is_body_compressed=%2, "
44,052✔
419
                     "compressed_body_size=%3, uncompressed_body_size=%4",
44,052✔
420
                     session_ident, is_body_compressed, compressed_body_size, uncompressed_body_size);
44,052✔
421

23,790✔
422
        ReceivedChangesets received_changesets;
44,052✔
423

23,790✔
424
        // Loop through the body and find the changesets.
23,790✔
425
        while (!msg.at_end()) {
88,098✔
426
            realm::sync::Transformer::RemoteChangeset cur_changeset;
44,046✔
427
            cur_changeset.remote_version = msg.read_next<version_type>();
44,046✔
428
            cur_changeset.last_integrated_local_version = msg.read_next<version_type>();
44,046✔
429
            cur_changeset.origin_timestamp = msg.read_next<timestamp_type>();
44,046✔
430
            cur_changeset.origin_file_ident = msg.read_next<file_ident_type>();
44,046✔
431
            cur_changeset.original_changeset_size = msg.read_next<size_t>();
44,046✔
432
            auto changeset_size = msg.read_next<size_t>();
44,046✔
433

23,228✔
434
            if (changeset_size > msg.bytes_remaining()) {
44,046✔
435
                return report_error(ErrorCodes::SyncProtocolInvariantFailed, "Bad changeset size %1 > %2",
×
436
                                    changeset_size, msg.bytes_remaining());
×
437
            }
×
438
            if (cur_changeset.remote_version == 0) {
44,046✔
439
                return report_error(ErrorCodes::SyncProtocolInvariantFailed,
×
440
                                    "Server version in downloaded changeset cannot be zero");
×
441
            }
×
442
            auto changeset_data = msg.read_sized_data<BinaryData>(changeset_size);
44,046✔
443
            logger.debug(util::LogCategory::changeset,
44,046✔
444
                         "Received: DOWNLOAD CHANGESET(session_ident=%1, server_version=%2, "
44,046✔
445
                         "client_version=%3, origin_timestamp=%4, origin_file_ident=%5, "
44,046✔
446
                         "original_changeset_size=%6, changeset_size=%7)",
44,046✔
447
                         session_ident, cur_changeset.remote_version, cur_changeset.last_integrated_local_version,
44,046✔
448
                         cur_changeset.origin_timestamp, cur_changeset.origin_file_ident,
44,046✔
449
                         cur_changeset.original_changeset_size, changeset_size); // Throws
44,046✔
450
            if (logger.would_log(util::LogCategory::changeset, util::Logger::Level::trace)) {
44,046✔
451
                if (changeset_data.size() < 1056) {
×
NEW
452
                    logger.trace(util::LogCategory::changeset, "Changeset: %1",
×
453
                                 clamped_hex_dump(changeset_data)); // Throws
×
454
                }
×
455
                else {
×
NEW
456
                    logger.trace(util::LogCategory::changeset, "Changeset(comp): %1 %2", changeset_data.size(),
×
457
                                 compressed_hex_dump(changeset_data)); // Throws
×
458
                }
×
459
#if REALM_DEBUG
×
460
                ChunkedBinaryInputStream in{changeset_data};
×
461
                sync::Changeset log;
×
462
                sync::parse_changeset(in, log);
×
463
                std::stringstream ss;
×
464
                log.print(ss);
×
NEW
465
                logger.trace(util::LogCategory::changeset, "Changeset (parsed):\n%1", ss.str());
×
466
#endif
×
467
            }
×
468

23,228✔
469
            cur_changeset.data = changeset_data;
44,046✔
470
            received_changesets.push_back(std::move(cur_changeset)); // Throws
44,046✔
471
        }
44,046✔
472

23,790✔
473
        auto batch_state =
44,052✔
474
            last_in_batch ? sync::DownloadBatchState::LastInBatch : sync::DownloadBatchState::MoreToCome;
43,970✔
475
        connection.receive_download_message(session_ident, progress, downloadable_bytes, query_version, batch_state,
44,052✔
476
                                            received_changesets); // Throws
44,052✔
477
    }
44,052✔
478

479
    static sync::ProtocolErrorInfo::Action string_to_action(const std::string& action_string)
480
    {
894✔
481
        using action = sync::ProtocolErrorInfo::Action;
894✔
482
        static const std::unordered_map<std::string, action> mapping{
894✔
483
            {"ProtocolViolation", action::ProtocolViolation},
894✔
484
            {"ApplicationBug", action::ApplicationBug},
894✔
485
            {"Warning", action::Warning},
894✔
486
            {"Transient", action::Transient},
894✔
487
            {"DeleteRealm", action::DeleteRealm},
894✔
488
            {"ClientReset", action::ClientReset},
894✔
489
            {"ClientResetNoRecovery", action::ClientResetNoRecovery},
894✔
490
            {"MigrateToFLX", action::MigrateToFLX},
894✔
491
            {"RevertToPBS", action::RevertToPBS},
894✔
492
            {"RefreshUser", action::RefreshUser},
894✔
493
            {"RefreshLocation", action::RefreshLocation},
894✔
494
            {"LogOutUser", action::LogOutUser},
894✔
495
        };
894✔
496

464✔
497
        if (auto action_it = mapping.find(action_string); action_it != mapping.end()) {
894✔
498
            return action_it->second;
886✔
499
        }
886✔
500
        return action::ApplicationBug;
8✔
501
    }
8✔
502

503
    template <typename Connection>
504
    void parse_log_message(Connection& connection, HeaderLineParser& msg)
505
    {
5,726✔
506
        auto report_error = [&](const auto fmt, auto&&... args) {
2,916✔
507
            auto msg = util::format(fmt, std::forward<decltype(args)>(args)...);
×
508
            connection.handle_protocol_error(Status{ErrorCodes::SyncProtocolInvariantFailed, std::move(msg)});
×
509
        };
×
510

2,916✔
511
        auto session_ident = msg.read_next<session_ident_type>();
5,726✔
512
        auto message_length = msg.read_next<size_t>('\n');
5,726✔
513
        auto message_body_str = msg.read_sized_data<std::string_view>(message_length);
5,726✔
514
        nlohmann::json message_body;
5,726✔
515
        try {
5,726✔
516
            message_body = nlohmann::json::parse(message_body_str);
5,726✔
517
        }
5,726✔
518
        catch (const nlohmann::json::exception& e) {
2,916✔
519
            return report_error("Malformed json in log_message message: \"%1\": %2", message_body_str, e.what());
×
520
        }
×
521
        static const std::unordered_map<std::string_view, util::Logger::Level> name_to_level = {
5,726✔
522
            {"fatal", util::Logger::Level::fatal},   {"error", util::Logger::Level::error},
5,726✔
523
            {"warn", util::Logger::Level::warn},     {"info", util::Logger::Level::info},
5,726✔
524
            {"detail", util::Logger::Level::detail}, {"debug", util::Logger::Level::debug},
5,726✔
525
            {"trace", util::Logger::Level::trace},
5,726✔
526
        };
5,726✔
527

2,916✔
528
        // See if the log_message contains the appservices_request_id
2,916✔
529
        if (auto it = message_body.find("co_id"); it != message_body.end() && it->is_string()) {
5,726✔
530
            connection.receive_appservices_request_id(it->get<std::string_view>());
1,860✔
531
        }
1,860✔
532

2,916✔
533
        std::string_view log_level;
5,726✔
534
        bool has_level = false;
5,726✔
535
        if (auto it = message_body.find("level"); it != message_body.end() && it->is_string()) {
5,726✔
536
            log_level = it->get<std::string_view>();
5,726✔
537
            has_level = !log_level.empty();
5,726✔
538
        }
5,726✔
539

2,916✔
540
        std::string_view msg_text;
5,726✔
541
        if (auto it = message_body.find("msg"); it != message_body.end() && it->is_string()) {
5,726✔
542
            msg_text = it->get<std::string_view>();
5,726✔
543
        }
5,726✔
544

2,916✔
545
        // If there is no message text, then we're done
2,916✔
546
        if (msg_text.empty()) {
5,726✔
547
            return;
×
548
        }
×
549

2,916✔
550
        // If a log level wasn't provided, default to debug
2,916✔
551
        util::Logger::Level parsed_level = util::Logger::Level::debug;
5,726✔
552
        if (has_level) {
5,726✔
553
            if (auto it = name_to_level.find(log_level); it != name_to_level.end()) {
5,726✔
554
                parsed_level = it->second;
5,726✔
555
            }
5,726✔
556
            else {
×
557
                return report_error("Unknown log level found in log_message: \"%1\"", log_level);
×
558
            }
×
559
        }
5,726✔
560
        connection.receive_server_log_message(session_ident, parsed_level, msg_text);
5,726✔
561
    }
5,726✔
562

563
    static constexpr std::size_t s_max_body_size = std::numeric_limits<std::size_t>::max();
564

565
    // Permanent buffer to use for building messages.
566
    OutputBuffer m_output_buffer;
567

568
    // Permanent buffers to use for internal purposes such as compression.
569
    std::vector<char> m_buffer;
570

571
    util::compression::CompressMemoryArena m_compress_memory_arena;
572
};
573

574

575
class ServerProtocol {
576
public:
577
    // clang-format off
578
    using file_ident_type    = sync::file_ident_type;
579
    using version_type       = sync::version_type;
580
    using salt_type          = sync::salt_type;
581
    using timestamp_type     = sync::timestamp_type;
582
    using session_ident_type = sync::session_ident_type;
583
    using request_ident_type = sync::request_ident_type;
584
    using SaltedFileIdent    = sync::SaltedFileIdent;
585
    using SaltedVersion      = sync::SaltedVersion;
586
    using milliseconds_type  = sync::milliseconds_type;
587
    using UploadCursor       = sync::UploadCursor;
588
    // clang-format on
589

590
    using OutputBuffer = util::ResettableExpandableBufferOutputStream;
591

592
    // Messages sent by the server to the client
593

594
    void make_ident_message(int protocol_version, OutputBuffer&, session_ident_type session_ident,
595
                            file_ident_type client_file_ident, salt_type client_file_ident_salt);
596

597
    void make_alloc_message(OutputBuffer&, session_ident_type session_ident, file_ident_type file_ident);
598

599
    void make_unbound_message(OutputBuffer&, session_ident_type session_ident);
600

601

602
    struct ChangesetInfo {
603
        version_type server_version;
604
        version_type client_version;
605
        sync::HistoryEntry entry;
606
        std::size_t original_size;
607
    };
608

609
    void make_download_message(int protocol_version, OutputBuffer&, session_ident_type session_ident,
610
                               version_type download_server_version, version_type download_client_version,
611
                               version_type latest_server_version, salt_type latest_server_version_salt,
612
                               version_type upload_client_version, version_type upload_server_version,
613
                               std::uint_fast64_t downloadable_bytes, std::size_t num_changesets, const char* body,
614
                               std::size_t uncompressed_body_size, std::size_t compressed_body_size,
615
                               bool body_is_compressed, util::Logger&);
616

617
    void make_mark_message(OutputBuffer&, session_ident_type session_ident, request_ident_type request_ident);
618

619
    void make_error_message(int protocol_version, OutputBuffer&, sync::ProtocolError error_code, const char* message,
620
                            std::size_t message_size, bool try_again, session_ident_type session_ident);
621

622
    void make_pong(OutputBuffer&, milliseconds_type timestamp);
623

624
    void make_log_message(OutputBuffer& out, util::Logger::Level level, std::string message,
625
                          session_ident_type sess_id = 0, std::optional<std::string> co_id = std::nullopt);
626

627
    // Messages received by the server.
628

629
    // parse_ping_received takes a (WebSocket) ping and parses it.
630
    // The result of the parsing is handled by an object of type Connection.
631
    // Typically, Connection would be the Connection class from server.cpp
632
    template <typename Connection>
633
    void parse_ping_received(Connection& connection, std::string_view msg_data)
634
    {
×
635
        try {
×
636
            HeaderLineParser msg(msg_data);
×
637
            auto timestamp = msg.read_next<milliseconds_type>();
×
638
            auto rtt = msg.read_next<milliseconds_type>('\n');
×
639

640
            connection.receive_ping(timestamp, rtt);
×
641
        }
×
642
        catch (const ProtocolCodecException& e) {
×
643
            connection.handle_protocol_error(Status{ErrorCodes::SyncProtocolInvariantFailed,
×
644
                                                    util::format("Bad syntax in PING message: %1", e.what())});
×
645
        }
×
646
    }
×
647

648
    // UploadChangeset is used to store received changesets in
649
    // the UPLOAD message.
650
    struct UploadChangeset {
651
        UploadCursor upload_cursor;
652
        timestamp_type origin_timestamp;
653
        file_ident_type origin_file_ident; // Zero when originating from connected client file
654
        BinaryData changeset;
655
    };
656

657
    // parse_message_received takes a (WebSocket) message and parses it.
658
    // The result of the parsing is handled by an object of type Connection.
659
    // Typically, Connection would be the Connection class from server.cpp
660
    template <class Connection>
661
    void parse_message_received(Connection& connection, std::string_view msg_data)
662
    {
69,432✔
663
        auto& logger = connection.logger;
69,432✔
664

34,482✔
665
        auto report_error = [&](ErrorCodes::Error err, const auto fmt, auto&&... args) {
34,482✔
666
            auto msg = util::format(fmt, std::forward<decltype(args)>(args)...);
×
667
            connection.handle_protocol_error(Status{err, std::move(msg)});
×
668
        };
×
669

34,482✔
670
        HeaderLineParser msg(msg_data);
69,432✔
671
        std::string_view message_type;
69,432✔
672
        try {
69,432✔
673
            message_type = msg.read_next<std::string_view>();
69,432✔
674
        }
69,432✔
675
        catch (const ProtocolCodecException& e) {
34,482✔
676
            return report_error(ErrorCodes::SyncProtocolInvariantFailed, "Could not find message type in message: %1",
×
677
                                e.what());
×
678
        }
×
679

34,484✔
680
        try {
69,436✔
681
            if (message_type == "upload") {
69,436✔
682
                auto msg_with_header = msg.remaining();
44,824✔
683
                auto session_ident = msg.read_next<session_ident_type>();
44,824✔
684
                auto is_body_compressed = msg.read_next<bool>();
44,824✔
685
                auto uncompressed_body_size = msg.read_next<size_t>();
44,824✔
686
                auto compressed_body_size = msg.read_next<size_t>();
44,824✔
687
                auto progress_client_version = msg.read_next<version_type>();
44,824✔
688
                auto progress_server_version = msg.read_next<version_type>();
44,824✔
689
                auto locked_server_version = msg.read_next<version_type>('\n');
44,824✔
690

22,554✔
691
                std::size_t body_size = (is_body_compressed ? compressed_body_size : uncompressed_body_size);
42,476✔
692
                if (body_size > s_max_body_size) {
44,824✔
693
                    auto header = msg_with_header.substr(0, msg_with_header.size() - msg.bytes_remaining());
×
694

695
                    return report_error(ErrorCodes::LimitExceeded,
×
696
                                        "Body size of upload message is too large. Raw header: %1", header);
×
697
                }
×
698

22,554✔
699

22,554✔
700
                std::unique_ptr<char[]> uncompressed_body_buffer;
44,824✔
701
                // if is_body_compressed == true, we must decompress the received body.
22,554✔
702
                if (is_body_compressed) {
44,824✔
703
                    uncompressed_body_buffer = std::make_unique<char[]>(uncompressed_body_size);
4,442✔
704
                    auto compressed_body = msg.read_sized_data<BinaryData>(compressed_body_size);
4,442✔
705

2,094✔
706
                    std::error_code ec = util::compression::decompress(
4,442✔
707
                        compressed_body, {uncompressed_body_buffer.get(), uncompressed_body_size});
4,442✔
708

2,094✔
709
                    if (ec) {
4,442✔
710
                        return report_error(ErrorCodes::RuntimeError, "compression::inflate: %1", ec.message());
×
711
                    }
×
712

2,094✔
713
                    msg = HeaderLineParser(std::string_view(uncompressed_body_buffer.get(), uncompressed_body_size));
4,442✔
714
                }
4,442✔
715

22,554✔
716
                logger.debug(util::LogCategory::changeset,
44,824✔
717
                             "Upload message compression: is_body_compressed = %1, "
44,824✔
718
                             "compressed_body_size=%2, uncompressed_body_size=%3, "
44,824✔
719
                             "progress_client_version=%4, progress_server_version=%5, "
44,824✔
720
                             "locked_server_version=%6",
44,824✔
721
                             is_body_compressed, compressed_body_size, uncompressed_body_size,
44,824✔
722
                             progress_client_version, progress_server_version, locked_server_version); // Throws
44,824✔
723

22,554✔
724

22,554✔
725
                std::vector<UploadChangeset> upload_changesets;
44,824✔
726

22,554✔
727
                // Loop through the body and find the changesets.
22,554✔
728
                while (!msg.at_end()) {
81,504✔
729
                    UploadChangeset upload_changeset;
36,680✔
730
                    size_t changeset_size;
36,680✔
731
                    try {
36,680✔
732
                        upload_changeset.upload_cursor.client_version = msg.read_next<version_type>();
36,680✔
733
                        upload_changeset.upload_cursor.last_integrated_server_version = msg.read_next<version_type>();
36,680✔
734
                        upload_changeset.origin_timestamp = msg.read_next<timestamp_type>();
36,680✔
735
                        upload_changeset.origin_file_ident = msg.read_next<file_ident_type>();
36,680✔
736
                        changeset_size = msg.read_next<size_t>();
36,680✔
737
                    }
36,680✔
738
                    catch (const ProtocolCodecException& e) {
17,710✔
739
                        return report_error(ErrorCodes::SyncProtocolInvariantFailed,
×
740
                                            "Bad changeset header syntax: %1", e.what());
×
741
                    }
×
742

17,708✔
743
                    if (changeset_size > msg.bytes_remaining()) {
36,680✔
744
                        return report_error(ErrorCodes::SyncProtocolInvariantFailed, "Bad changeset size");
×
745
                    }
×
746

17,708✔
747
                    upload_changeset.changeset = msg.read_sized_data<BinaryData>(changeset_size);
36,680✔
748

17,708✔
749
                    if (logger.would_log(util::Logger::Level::trace)) {
36,680✔
NEW
750
                        logger.trace(util::LogCategory::changeset,
×
NEW
751
                                     "Received: UPLOAD CHANGESET(client_version=%1, server_version=%2, "
×
752
                                     "origin_timestamp=%3, origin_file_ident=%4, changeset_size=%5)",
×
753
                                     upload_changeset.upload_cursor.client_version,
×
754
                                     upload_changeset.upload_cursor.last_integrated_server_version,
×
755
                                     upload_changeset.origin_timestamp, upload_changeset.origin_file_ident,
×
756
                                     changeset_size); // Throws
×
NEW
757
                        logger.trace(util::LogCategory::changeset, "Changeset: %1",
×
758
                                     clamped_hex_dump(upload_changeset.changeset)); // Throws
×
759
                    }
×
760
                    upload_changesets.push_back(std::move(upload_changeset)); // Throws
36,680✔
761
                }
36,680✔
762

22,554✔
763
                connection.receive_upload_message(session_ident, progress_client_version, progress_server_version,
44,826✔
764
                                                  locked_server_version,
44,824✔
765
                                                  upload_changesets); // Throws
44,824✔
766
            }
44,824✔
767
            else if (message_type == "mark") {
24,612✔
768
                auto session_ident = msg.read_next<session_ident_type>();
12,122✔
769
                auto request_ident = msg.read_next<request_ident_type>('\n');
12,122✔
770

5,994✔
771
                connection.receive_mark_message(session_ident, request_ident); // Throws
12,122✔
772
            }
12,122✔
773
            else if (message_type == "ping") {
12,490✔
774
                auto timestamp = msg.read_next<milliseconds_type>();
156✔
775
                auto rtt = msg.read_next<milliseconds_type>('\n');
156✔
776

52✔
777
                connection.receive_ping(timestamp, rtt);
156✔
778
            }
156✔
779
            else if (message_type == "bind") {
12,334✔
780
                auto session_ident = msg.read_next<session_ident_type>();
5,444✔
781
                auto path_size = msg.read_next<size_t>();
5,444✔
782
                auto signed_user_token_size = msg.read_next<size_t>();
5,444✔
783
                auto need_client_file_ident = msg.read_next<bool>();
5,444✔
784
                auto is_subserver = msg.read_next<bool>('\n');
5,444✔
785

2,606✔
786
                if (path_size == 0) {
5,444✔
787
                    return report_error(ErrorCodes::SyncProtocolInvariantFailed, "Path size in BIND message is zero");
×
788
                }
×
789
                if (path_size > s_max_path_size) {
5,444✔
790
                    return report_error(ErrorCodes::SyncProtocolInvariantFailed,
×
791
                                        "Path size in BIND message is too large");
×
792
                }
×
793
                if (signed_user_token_size > s_max_signed_user_token_size) {
5,444✔
794
                    return report_error(ErrorCodes::SyncProtocolInvariantFailed,
×
795
                                        "Signed user token size in BIND message is too large");
×
796
                }
×
797

2,606✔
798
                auto path = msg.read_sized_data<std::string>(path_size);
5,444✔
799
                auto signed_user_token = msg.read_sized_data<std::string>(signed_user_token_size);
5,444✔
800

2,606✔
801
                connection.receive_bind_message(session_ident, std::move(path), std::move(signed_user_token),
5,444✔
802
                                                need_client_file_ident, is_subserver); // Throws
5,444✔
803
            }
5,444✔
804
            else if (message_type == "ident") {
6,890✔
805
                auto session_ident = msg.read_next<session_ident_type>();
4,076✔
806
                auto client_file_ident = msg.read_next<file_ident_type>();
4,076✔
807
                auto client_file_ident_salt = msg.read_next<salt_type>();
4,076✔
808
                auto scan_server_version = msg.read_next<version_type>();
4,076✔
809
                auto scan_client_version = msg.read_next<version_type>();
4,076✔
810
                auto latest_server_version = msg.read_next<version_type>();
4,076✔
811
                auto latest_server_version_salt = msg.read_next<salt_type>('\n');
4,076✔
812

2,092✔
813
                connection.receive_ident_message(session_ident, client_file_ident, client_file_ident_salt,
4,076✔
814
                                                 scan_server_version, scan_client_version, latest_server_version,
4,076✔
815
                                                 latest_server_version_salt); // Throws
4,076✔
816
            }
4,076✔
817
            else if (message_type == "unbind") {
2,816✔
818
                auto session_ident = msg.read_next<session_ident_type>('\n');
2,814✔
819

1,184✔
820
                connection.receive_unbind_message(session_ident); // Throws
2,814✔
821
            }
2,814✔
822
            else if (message_type == "json_error") {
2,147,483,649✔
823
                auto error_code = msg.read_next<int>();
×
824
                auto message_size = msg.read_next<size_t>();
×
825
                auto session_ident = msg.read_next<session_ident_type>('\n');
×
826
                auto json_raw = msg.read_sized_data<std::string_view>(message_size);
×
827

828
                connection.receive_error_message(session_ident, error_code, json_raw);
×
829
            }
×
830
            else {
2,147,483,649✔
831
                return report_error(ErrorCodes::SyncProtocolInvariantFailed, "unknown message type %1", message_type);
2,147,483,649✔
832
            }
2,147,483,649✔
833
        }
×
834
        catch (const ProtocolCodecException& e) {
×
835
            return report_error(ErrorCodes::SyncProtocolInvariantFailed, "bad syntax in %1 message: %2", message_type,
×
836
                                e.what());
×
837
        }
×
838
    }
69,436✔
839

840
    void insert_single_changeset_download_message(OutputBuffer&, const ChangesetInfo&, util::Logger&);
841

842
private:
843
    // clang-format off
844
    static constexpr std::size_t s_max_head_size              =  256;
845
    static constexpr std::size_t s_max_signed_user_token_size = 2048;
846
    static constexpr std::size_t s_max_client_info_size       = 1024;
847
    static constexpr std::size_t s_max_path_size              = 1024;
848
    static constexpr std::size_t s_max_changeset_size         = std::numeric_limits<std::size_t>::max(); // FIXME: What is a reasonable value here?
849
    static constexpr std::size_t s_max_body_size              = std::numeric_limits<std::size_t>::max();
850
    // clang-format on
851
};
852

853
// make_authorization_header() makes the value of the Authorization header used in the
854
// sync Websocket handshake.
855
std::string make_authorization_header(const std::string& signed_user_token);
856

857
// parse_authorization_header() parses the value of the Authorization header and returns
858
// the signed_user_token. None is returned in case of syntax error.
859
util::Optional<StringData> parse_authorization_header(const std::string& authorization_header);
860

861
} // namespace realm::_impl
862

863
#endif // REALM_NOINST_PROTOCOL_CODEC_HPP
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc