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

realm / realm-core / 2274

29 Apr 2024 07:20PM UTC coverage: 90.709% (-0.04%) from 90.748%
2274

push

Evergreen

web-flow
Merge pull request #7645 from realm/mwb/fix-warning

Fix warning introduced by PR #7632

101872 of 180246 branches covered (56.52%)

212397 of 234153 relevant lines covered (90.71%)

5624274.76 hits per line

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

73.5
/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)
77,064✔
35
    {
159,146✔
36
    }
159,146✔
37

38
    template <typename T>
39
    T read_next(char expected_terminator = ' ')
40
    {
1,614,156✔
41
        const auto [tok, rest] = peek_token_impl<T>();
1,614,156✔
42
        if (rest.empty()) {
1,614,156✔
43
            throw ProtocolCodecException("header line ended prematurely without terminator");
×
44
        }
×
45
        if (rest.front() != expected_terminator) {
1,614,156✔
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,614,156✔
50
        return tok;
1,614,156✔
51
    }
1,614,156✔
52

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

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

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

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

76
    void advance(size_t size)
77
    {
105,318✔
78
        if (size > m_sv.size()) {
105,318✔
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);
105,318✔
83
    }
105,318✔
84

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

103
            return {m_sv.substr(0, delim_at), m_sv.substr(delim_at)};
150,026✔
104
        }
77,430✔
105
        else if constexpr (std::is_integral_v<T> && !std::is_same_v<T, bool>) {
1,410,060✔
106
            T cur_arg = {};
704,676✔
107
            auto parse_res = util::from_chars(m_sv.data(), m_sv.data() + m_sv.size(), cur_arg, 10);
704,676✔
108
            if (parse_res.ec != std::errc{}) {
1,352,026✔
109
                throw ProtocolCodecException(util::format("error parsing integer in header line: %1",
×
110
                                                          std::make_error_code(parse_res.ec).message()));
×
111
            }
×
112

113
            return {cur_arg, m_sv.substr(parse_res.ptr - m_sv.data())};
1,352,026✔
114
        }
705,322✔
115
        else if constexpr (std::is_same_v<T, bool>) {
110,296✔
116
            int cur_arg;
54,102✔
117
            auto parse_res = util::from_chars(m_sv.data(), m_sv.data() + m_sv.size(), cur_arg, 10);
54,102✔
118
            if (parse_res.ec != std::errc{}) {
108,518✔
119
                throw ProtocolCodecException(util::format("error parsing boolean in header line: %1",
×
120
                                                          std::make_error_code(parse_res.ec).message()));
×
121
            }
×
122

123
            return {(cur_arg != 0), m_sv.substr(parse_res.ptr - m_sv.data())};
108,518✔
124
        }
56,194✔
125
        else if constexpr (std::is_floating_point_v<T>) {
3,560✔
126
            // Currently all double are in the middle of the string delimited by a space.
127
            auto delim_at = m_sv.find(' ');
3,560✔
128
            if (delim_at == std::string_view::npos)
3,560✔
129
                throw ProtocolCodecException("reached end of header line prematurely for double value parsing");
×
130

131
            // FIXME use std::from_chars one day when it's availiable in every std lib
132
            T val = {};
3,560✔
133
            try {
3,560✔
134
                std::string str(m_sv.substr(0, delim_at));
3,560✔
135
                if constexpr (std::is_same_v<T, float>)
1,778✔
136
                    val = std::stof(str);
137
                else if constexpr (std::is_same_v<T, double>)
1,778✔
138
                    val = std::stod(str);
3,560✔
139
                else if constexpr (std::is_same_v<T, long double>)
1,778✔
140
                    val = std::stold(str);
1,778✔
141
            }
3,560✔
142
            catch (const std::exception& err) {
3,560✔
143
                throw ProtocolCodecException(
×
144
                    util::format("error parsing floating-point number in header line: %1", err.what()));
×
145
            }
×
146

147
            return {val, m_sv.substr(delim_at)};
3,560✔
148
        }
3,560✔
149
    }
1,614,186✔
150

151
    std::string_view m_sv;
152
};
153

154
class ClientProtocol {
155
public:
156
    // clang-format off
157
    using file_ident_type    = sync::file_ident_type;
158
    using version_type       = sync::version_type;
159
    using salt_type          = sync::salt_type;
160
    using timestamp_type     = sync::timestamp_type;
161
    using session_ident_type = sync::session_ident_type;
162
    using request_ident_type = sync::request_ident_type;
163
    using milliseconds_type  = sync::milliseconds_type;
164
    using SaltedFileIdent    = sync::SaltedFileIdent;
165
    using SaltedVersion      = sync::SaltedVersion;
166
    using DownloadCursor     = sync::DownloadCursor;
167
    using UploadCursor       = sync::UploadCursor;
168
    using SyncProgress       = sync::SyncProgress;
169
    // clang-format on
170

171
    using OutputBuffer = util::ResettableExpandableBufferOutputStream;
172
    using RemoteChangeset = sync::RemoteChangeset;
173
    using ReceivedChangesets = std::vector<RemoteChangeset>;
174

175
    /// Messages sent by the client.
176

177
    void make_pbs_bind_message(int protocol_version, OutputBuffer&, session_ident_type session_ident,
178
                               const std::string& server_path, const std::string& signed_user_token,
179
                               bool need_client_file_ident, bool is_subserver);
180

181
    void make_flx_bind_message(int protocol_version, OutputBuffer& out, session_ident_type session_ident,
182
                               const nlohmann::json& json_data, const std::string& signed_user_token,
183
                               bool need_client_file_ident, bool is_subserver);
184

185
    void make_pbs_ident_message(OutputBuffer&, session_ident_type session_ident, SaltedFileIdent client_file_ident,
186
                                const SyncProgress& progress);
187

188
    void make_flx_ident_message(OutputBuffer&, session_ident_type session_ident, SaltedFileIdent client_file_ident,
189
                                const SyncProgress& progress, int64_t query_version, std::string_view query_body);
190

191
    void make_query_change_message(OutputBuffer&, session_ident_type, int64_t version, std::string_view query_body);
192

193
    void make_json_error_message(OutputBuffer&, session_ident_type, int error_code, std::string_view error_body);
194

195
    void make_test_command_message(OutputBuffer&, session_ident_type session, request_ident_type request_ident,
196
                                   std::string_view body);
197

198
    class UploadMessageBuilder {
199
    public:
200
        UploadMessageBuilder(OutputBuffer& body_buffer, std::vector<char>& compression_buffer,
201
                             util::compression::CompressMemoryArena& compress_memory_arena);
202

203
        void add_changeset(version_type client_version, version_type server_version, timestamp_type origin_timestamp,
204
                           file_ident_type origin_file_ident, ChunkedBinaryData changeset);
205

206
        void make_upload_message(int protocol_version, OutputBuffer&, session_ident_type session_ident,
207
                                 version_type progress_client_version, version_type progress_server_version,
208
                                 version_type locked_server_version);
209

210
    private:
211
        std::size_t m_num_changesets = 0;
212
        OutputBuffer& m_body_buffer;
213
        std::vector<char>& m_compression_buffer;
214
        util::compression::CompressMemoryArena& m_compress_memory_arena;
215
    };
216

217
    UploadMessageBuilder make_upload_message_builder();
218

219
    void make_unbind_message(OutputBuffer&, session_ident_type session_ident);
220

221
    void make_mark_message(OutputBuffer&, session_ident_type session_ident, request_ident_type request_ident);
222

223
    void make_ping(OutputBuffer&, milliseconds_type timestamp, milliseconds_type rtt);
224

225
    std::string compressed_hex_dump(BinaryData blob);
226

227
    // Messages received by the client.
228

229
    // parse_message_received takes a (WebSocket) message and parses it.
230
    // The result of the parsing is handled by an object of type Connection.
231
    // Typically, Connection would be the Connection class from client.cpp
232
    template <class Connection>
233
    void parse_message_received(Connection& connection, std::string_view msg_data)
234
    {
79,216✔
235
        util::Logger& logger = connection.logger;
79,216✔
236
        auto report_error = [&](const auto fmt, auto&&... args) {
79,216✔
237
            auto msg = util::format(fmt, std::forward<decltype(args)>(args)...);
×
238
            connection.handle_protocol_error(Status{ErrorCodes::SyncProtocolInvariantFailed, std::move(msg)});
×
239
        };
×
240

241
        HeaderLineParser msg(msg_data);
79,216✔
242
        std::string_view message_type;
79,216✔
243
        try {
79,216✔
244
            message_type = msg.read_next<std::string_view>();
79,216✔
245
        }
79,216✔
246
        catch (const ProtocolCodecException& e) {
79,216✔
247
            return report_error("Could not find message type in message: %1", e.what());
×
248
        }
×
249

250
        try {
79,216✔
251
            if (message_type == "download") {
79,216✔
252
                parse_download_message(connection, msg);
47,830✔
253
            }
47,830✔
254
            else if (message_type == "pong") {
31,386✔
255
                auto timestamp = msg.read_next<milliseconds_type>('\n');
160✔
256
                connection.receive_pong(timestamp);
160✔
257
            }
160✔
258
            else if (message_type == "unbound") {
31,226✔
259
                auto session_ident = msg.read_next<session_ident_type>('\n');
4,146✔
260
                connection.receive_unbound_message(session_ident); // Throws
4,146✔
261
            }
4,146✔
262
            else if (message_type == "error") {
27,080✔
263
                auto error_code = msg.read_next<int>();
84✔
264
                auto message_size = msg.read_next<size_t>();
84✔
265
                auto is_fatal = sync::IsFatal{!msg.read_next<bool>()};
84✔
266
                auto session_ident = msg.read_next<session_ident_type>('\n');
84✔
267
                auto message = msg.read_sized_data<StringData>(message_size);
84✔
268

269
                connection.receive_error_message(sync::ProtocolErrorInfo{error_code, message, is_fatal},
84✔
270
                                                 session_ident); // Throws
84✔
271
            }
84✔
272
            else if (message_type == "log_message") { // introduced in protocol version 10
26,996✔
273
                parse_log_message(connection, msg);
6,004✔
274
            }
6,004✔
275
            else if (message_type == "json_error") { // introduced in protocol 4
20,992✔
276
                sync::ProtocolErrorInfo info{};
674✔
277
                info.raw_error_code = msg.read_next<int>();
674✔
278
                auto message_size = msg.read_next<size_t>();
674✔
279
                auto session_ident = msg.read_next<session_ident_type>('\n');
674✔
280
                auto json_raw = msg.read_sized_data<std::string_view>(message_size);
674✔
281
                try {
674✔
282
                    auto json = nlohmann::json::parse(json_raw);
674✔
283
                    logger.trace(util::LogCategory::session, "Error message encoded as json: %1", json_raw);
674✔
284
                    info.client_reset_recovery_is_disabled = json["isRecoveryModeDisabled"];
674✔
285
                    info.is_fatal = sync::IsFatal{!json["tryAgain"]};
674✔
286
                    info.message = json["message"];
674✔
287
                    info.log_url = std::make_optional<std::string>(json["logURL"]);
674✔
288
                    info.should_client_reset = std::make_optional<bool>(json["shouldClientReset"]);
674✔
289
                    info.server_requests_action = string_to_action(json["action"]); // Throws
674✔
290

291
                    if (auto backoff_interval = json.find("backoffIntervalSec"); backoff_interval != json.end()) {
674✔
292
                        info.resumption_delay_interval.emplace();
538✔
293
                        info.resumption_delay_interval->resumption_delay_interval =
538✔
294
                            std::chrono::seconds{backoff_interval->get<int>()};
538✔
295
                        info.resumption_delay_interval->max_resumption_delay_interval =
538✔
296
                            std::chrono::seconds{json.at("backoffMaxDelaySec").get<int>()};
538✔
297
                        info.resumption_delay_interval->resumption_delay_backoff_multiplier =
538✔
298
                            json.at("backoffMultiplier").get<int>();
538✔
299
                    }
538✔
300

301
                    if (info.raw_error_code == static_cast<int>(sync::ProtocolError::migrate_to_flx)) {
674✔
302
                        auto query_string = json.find("partitionQuery");
36✔
303
                        if (query_string == json.end() || !query_string->is_string() ||
36✔
304
                            query_string->get<std::string_view>().empty()) {
36✔
305
                            return report_error(
×
306
                                "Missing/invalid partition query string in migrate to flexible sync error response");
×
307
                        }
×
308

309
                        info.migration_query_string.emplace(query_string->get<std::string_view>());
36✔
310
                    }
36✔
311

312
                    if (info.raw_error_code == static_cast<int>(sync::ProtocolError::schema_version_changed)) {
674✔
313
                        auto schema_version = json.find("previousSchemaVersion");
68✔
314
                        if (schema_version == json.end() || !schema_version->is_number_unsigned()) {
68✔
315
                            return report_error(
×
316
                                "Missing/invalid previous schema version in schema migration error response");
×
317
                        }
×
318

319
                        info.previous_schema_version.emplace(schema_version->get<uint64_t>());
68✔
320
                    }
68✔
321

322
                    if (auto rejected_updates = json.find("rejectedUpdates"); rejected_updates != json.end()) {
674✔
323
                        if (!rejected_updates->is_array()) {
52✔
324
                            return report_error(
×
325
                                "Compensating writes error list is not stored in an array as expected");
×
326
                        }
×
327

328
                        for (const auto& rejected_update : *rejected_updates) {
60✔
329
                            if (!rejected_update.is_object()) {
60✔
330
                                return report_error(
×
331
                                    "Compensating write error information is not stored in an object as expected");
×
332
                            }
×
333

334
                            sync::CompensatingWriteErrorInfo cwei;
60✔
335
                            cwei.reason = rejected_update["reason"];
60✔
336
                            cwei.object_name = rejected_update["table"];
60✔
337
                            std::string_view pk = rejected_update["pk"].get<std::string_view>();
60✔
338
                            cwei.primary_key = sync::parse_base64_encoded_primary_key(pk);
60✔
339
                            info.compensating_writes.push_back(std::move(cwei));
60✔
340
                        }
60✔
341

342
                        // Not provided when 'write_not_allowed' (230) error is received from the server.
343
                        if (auto server_version = json.find("compensatingWriteServerVersion");
52✔
344
                            server_version != json.end()) {
52✔
345
                            info.compensating_write_server_version =
48✔
346
                                std::make_optional<version_type>(server_version->get<int64_t>());
48✔
347
                        }
48✔
348
                        info.compensating_write_rejected_client_version =
52✔
349
                            json.at("rejectedClientVersion").get<int64_t>();
52✔
350
                    }
52✔
351
                }
674✔
352
                catch (const nlohmann::json::exception& e) {
674✔
353
                    // If any of the above json fields are not present, this is a fatal error
354
                    // however, additional optional fields may be added in the future.
355
                    return report_error("Failed to parse 'json_error' with error_code %1: '%2'", info.raw_error_code,
×
356
                                        e.what());
×
357
                }
×
358
                connection.receive_error_message(info, session_ident); // Throws
674✔
359
            }
674✔
360
            else if (message_type == "query_error") {
20,318✔
361
                auto error_code = msg.read_next<int>();
20✔
362
                auto message_size = msg.read_next<size_t>();
20✔
363
                auto session_ident = msg.read_next<session_ident_type>();
20✔
364
                auto query_version = msg.read_next<int64_t>('\n');
20✔
365

366
                auto message = msg.read_sized_data<std::string_view>(message_size);
20✔
367

368
                connection.receive_query_error_message(error_code, message, query_version, session_ident); // throws
20✔
369
            }
20✔
370
            else if (message_type == "mark") {
20,298✔
371
                auto session_ident = msg.read_next<session_ident_type>();
16,556✔
372
                auto request_ident = msg.read_next<request_ident_type>('\n');
16,556✔
373

374
                connection.receive_mark_message(session_ident, request_ident); // Throws
16,556✔
375
            }
16,556✔
376
            else if (message_type == "ident") {
3,742✔
377
                session_ident_type session_ident = msg.read_next<session_ident_type>();
3,690✔
378
                SaltedFileIdent client_file_ident;
3,690✔
379
                client_file_ident.ident = msg.read_next<file_ident_type>();
3,690✔
380
                client_file_ident.salt = msg.read_next<salt_type>('\n');
3,690✔
381

382
                connection.receive_ident_message(session_ident, client_file_ident); // Throws
3,690✔
383
            }
3,690✔
384
            else if (message_type == "test_command") {
52✔
385
                session_ident_type session_ident = msg.read_next<session_ident_type>();
52✔
386
                request_ident_type request_ident = msg.read_next<request_ident_type>();
52✔
387
                auto body_size = msg.read_next<size_t>('\n');
52✔
388
                auto body = msg.read_sized_data<std::string_view>(body_size);
52✔
389

390
                connection.receive_test_command_response(session_ident, request_ident, body);
52✔
391
            }
52✔
392
            else {
×
393
                return report_error("Unknown input message type '%1'", msg_data);
×
394
            }
×
395
        }
79,216✔
396
        catch (const ProtocolCodecException& e) {
79,216✔
397
            return report_error("Bad syntax in %1 message: %2", message_type, e.what());
×
398
        }
×
399
        if (!msg.at_end()) {
79,214✔
400
            return report_error("wire protocol message had leftover data after being parsed");
×
401
        }
×
402
    }
79,214✔
403

404
    struct DownloadMessage {
405
        SyncProgress progress;
406
        std::optional<int64_t> query_version;
407
        std::optional<bool> last_in_batch;
408
        union {
409
            uint64_t downloadable_bytes = 0;
410
            double progress_estimate;
411
        };
412
        ReceivedChangesets changesets;
413
    };
414

415
private:
416
    template <typename Connection>
417
    void parse_download_message(Connection& connection, HeaderLineParser& msg)
418
    {
47,830✔
419
        bool is_flx = connection.is_flx_sync_connection();
47,830✔
420

421
        util::Logger& logger = connection.logger;
47,830✔
422
        auto report_error = [&](ErrorCodes::Error code, const auto fmt, auto&&... args) {
47,830✔
423
            auto msg = util::format(fmt, std::forward<decltype(args)>(args)...);
×
424
            connection.handle_protocol_error(Status{code, std::move(msg)});
×
425
        };
×
426

427
        auto msg_with_header = msg.remaining();
47,830✔
428
        auto session_ident = msg.read_next<session_ident_type>();
47,830✔
429

430
        DownloadMessage message;
47,830✔
431
        auto&& progress = message.progress;
47,830✔
432
        progress.download.server_version = msg.read_next<version_type>();
47,830✔
433
        progress.download.last_integrated_client_version = msg.read_next<version_type>();
47,830✔
434
        progress.latest_server_version.version = msg.read_next<version_type>();
47,830✔
435
        progress.latest_server_version.salt = msg.read_next<salt_type>();
47,830✔
436
        progress.upload.client_version = msg.read_next<version_type>();
47,830✔
437
        progress.upload.last_integrated_server_version = msg.read_next<version_type>();
47,830✔
438

439
        if (is_flx) {
47,830✔
440
            message.query_version = msg.read_next<int64_t>();
3,560✔
441
            if (message.query_version < 0)
3,560✔
442
                return report_error(ErrorCodes::SyncProtocolInvariantFailed, "Bad query version",
×
443
                                    message.query_version);
×
444

445
            message.last_in_batch = msg.read_next<bool>();
3,560✔
446

447
            message.progress_estimate = msg.read_next<double>();
3,560✔
448
            if (message.progress_estimate < 0 || message.progress_estimate > 1)
3,560✔
449
                return report_error(ErrorCodes::SyncProtocolInvariantFailed, "Bad progress value: %1",
×
450
                                    message.progress_estimate);
×
451
        }
3,560✔
452
        else
44,270✔
453
            message.downloadable_bytes = msg.read_next<int64_t>();
44,270✔
454

455
        auto is_body_compressed = msg.read_next<bool>();
47,830✔
456
        auto uncompressed_body_size = msg.read_next<size_t>();
47,830✔
457
        auto compressed_body_size = msg.read_next<size_t>('\n');
47,830✔
458

459
        if (uncompressed_body_size > s_max_body_size) {
47,830✔
460
            auto header = msg_with_header.substr(0, msg_with_header.size() - msg.remaining().size());
×
461
            return report_error(ErrorCodes::LimitExceeded, "Limits exceeded in input message '%1'", header);
×
462
        }
×
463

464
        std::unique_ptr<char[]> uncompressed_body_buffer;
47,830✔
465
        // if is_body_compressed == true, we must decompress the received body.
466
        if (is_body_compressed) {
47,830✔
467
            uncompressed_body_buffer = std::make_unique<char[]>(uncompressed_body_size);
4,658✔
468
            std::error_code ec =
4,658✔
469
                util::compression::decompress({msg.remaining().data(), compressed_body_size},
4,658✔
470
                                              {uncompressed_body_buffer.get(), uncompressed_body_size});
4,658✔
471

472
            if (ec) {
4,658✔
473
                return report_error(ErrorCodes::RuntimeError, "compression::inflate: %1", ec.message());
×
474
            }
×
475

476
            msg = HeaderLineParser(std::string_view(uncompressed_body_buffer.get(), uncompressed_body_size));
4,658✔
477
        }
4,658✔
478

479
        logger.debug(util::LogCategory::changeset,
47,830✔
480
                     "Download message compression: session_ident=%1, is_body_compressed=%2, "
47,830✔
481
                     "compressed_body_size=%3, uncompressed_body_size=%4",
47,830✔
482
                     session_ident, is_body_compressed, compressed_body_size, uncompressed_body_size);
47,830✔
483

484
        // Loop through the body and find the changesets.
485
        while (!msg.at_end()) {
94,132✔
486
            RemoteChangeset cur_changeset;
46,302✔
487
            cur_changeset.remote_version = msg.read_next<version_type>();
46,302✔
488
            cur_changeset.last_integrated_local_version = msg.read_next<version_type>();
46,302✔
489
            cur_changeset.origin_timestamp = msg.read_next<timestamp_type>();
46,302✔
490
            cur_changeset.origin_file_ident = msg.read_next<file_ident_type>();
46,302✔
491
            cur_changeset.original_changeset_size = msg.read_next<size_t>();
46,302✔
492
            auto changeset_size = msg.read_next<size_t>();
46,302✔
493

494
            if (changeset_size > msg.bytes_remaining()) {
46,302✔
495
                return report_error(ErrorCodes::SyncProtocolInvariantFailed, "Bad changeset size %1 > %2",
×
496
                                    changeset_size, msg.bytes_remaining());
×
497
            }
×
498
            if (cur_changeset.remote_version == 0) {
46,302✔
499
                return report_error(ErrorCodes::SyncProtocolInvariantFailed,
×
500
                                    "Server version in downloaded changeset cannot be zero");
×
501
            }
×
502
            auto changeset_data = msg.read_sized_data<BinaryData>(changeset_size);
46,302✔
503
            logger.debug(util::LogCategory::changeset,
46,302✔
504
                         "Received: DOWNLOAD CHANGESET(session_ident=%1, server_version=%2, "
46,302✔
505
                         "client_version=%3, origin_timestamp=%4, origin_file_ident=%5, "
46,302✔
506
                         "original_changeset_size=%6, changeset_size=%7)",
46,302✔
507
                         session_ident, cur_changeset.remote_version, cur_changeset.last_integrated_local_version,
46,302✔
508
                         cur_changeset.origin_timestamp, cur_changeset.origin_file_ident,
46,302✔
509
                         cur_changeset.original_changeset_size, changeset_size); // Throws
46,302✔
510
            if (logger.would_log(util::LogCategory::changeset, util::Logger::Level::trace)) {
46,302✔
511
                if (changeset_data.size() < 1056) {
×
512
                    logger.trace(util::LogCategory::changeset, "Changeset: %1",
×
513
                                 clamped_hex_dump(changeset_data)); // Throws
×
514
                }
×
515
                else {
×
516
                    logger.trace(util::LogCategory::changeset, "Changeset(comp): %1 %2", changeset_data.size(),
×
517
                                 compressed_hex_dump(changeset_data)); // Throws
×
518
                }
×
519
#if REALM_DEBUG
×
520
                ChunkedBinaryInputStream in{changeset_data};
×
521
                sync::Changeset log;
×
522
                sync::parse_changeset(in, log);
×
523
                std::stringstream ss;
×
524
                log.print(ss);
×
525
                logger.trace(util::LogCategory::changeset, "Changeset (parsed):\n%1", ss.str());
×
526
#endif
×
527
            }
×
528

529
            cur_changeset.data = changeset_data;
46,302✔
530
            message.changesets.push_back(std::move(cur_changeset)); // Throws
46,302✔
531
        }
46,302✔
532

533
        connection.receive_download_message(session_ident, message); // Throws
47,830✔
534
    }
47,830✔
535

536
    static sync::ProtocolErrorInfo::Action string_to_action(const std::string& action_string)
537
    {
674✔
538
        using action = sync::ProtocolErrorInfo::Action;
674✔
539
        static const std::unordered_map<std::string, action> mapping{
674✔
540
            {"ProtocolViolation", action::ProtocolViolation},
674✔
541
            {"ApplicationBug", action::ApplicationBug},
674✔
542
            {"Warning", action::Warning},
674✔
543
            {"Transient", action::Transient},
674✔
544
            {"DeleteRealm", action::DeleteRealm},
674✔
545
            {"ClientReset", action::ClientReset},
674✔
546
            {"ClientResetNoRecovery", action::ClientResetNoRecovery},
674✔
547
            {"MigrateToFLX", action::MigrateToFLX},
674✔
548
            {"RevertToPBS", action::RevertToPBS},
674✔
549
            {"RefreshUser", action::RefreshUser},
674✔
550
            {"RefreshLocation", action::RefreshLocation},
674✔
551
            {"LogOutUser", action::LogOutUser},
674✔
552
            {"MigrateSchema", action::MigrateSchema},
674✔
553
        };
674✔
554

555
        if (auto action_it = mapping.find(action_string); action_it != mapping.end()) {
674✔
556
            return action_it->second;
666✔
557
        }
666✔
558
        return action::ApplicationBug;
8✔
559
    }
674✔
560

561
    template <typename Connection>
562
    void parse_log_message(Connection& connection, HeaderLineParser& msg)
563
    {
6,004✔
564
        auto report_error = [&](const auto fmt, auto&&... args) {
6,004✔
565
            auto msg = util::format(fmt, std::forward<decltype(args)>(args)...);
×
566
            connection.handle_protocol_error(Status{ErrorCodes::SyncProtocolInvariantFailed, std::move(msg)});
×
567
        };
×
568

569
        auto session_ident = msg.read_next<session_ident_type>();
6,004✔
570
        auto message_length = msg.read_next<size_t>('\n');
6,004✔
571
        auto message_body_str = msg.read_sized_data<std::string_view>(message_length);
6,004✔
572
        nlohmann::json message_body;
6,004✔
573
        try {
6,004✔
574
            message_body = nlohmann::json::parse(message_body_str);
6,004✔
575
        }
6,004✔
576
        catch (const nlohmann::json::exception& e) {
6,004✔
577
            return report_error("Malformed json in log_message message: \"%1\": %2", message_body_str, e.what());
×
578
        }
×
579
        static const std::unordered_map<std::string_view, util::Logger::Level> name_to_level = {
6,004✔
580
            {"fatal", util::Logger::Level::fatal},   {"error", util::Logger::Level::error},
6,004✔
581
            {"warn", util::Logger::Level::warn},     {"info", util::Logger::Level::info},
6,004✔
582
            {"detail", util::Logger::Level::detail}, {"debug", util::Logger::Level::debug},
6,004✔
583
            {"trace", util::Logger::Level::trace},
6,004✔
584
        };
6,004✔
585

586
        // See if the log_message contains the appservices_request_id
587
        if (auto it = message_body.find("co_id"); it != message_body.end() && it->is_string()) {
6,004✔
588
            connection.receive_appservices_request_id(it->get<std::string_view>());
1,988✔
589
        }
1,988✔
590

591
        std::string_view log_level;
6,004✔
592
        bool has_level = false;
6,004✔
593
        if (auto it = message_body.find("level"); it != message_body.end() && it->is_string()) {
6,004✔
594
            log_level = it->get<std::string_view>();
6,004✔
595
            has_level = !log_level.empty();
6,004✔
596
        }
6,004✔
597

598
        std::string_view msg_text;
6,004✔
599
        if (auto it = message_body.find("msg"); it != message_body.end() && it->is_string()) {
6,004✔
600
            msg_text = it->get<std::string_view>();
6,004✔
601
        }
6,004✔
602

603
        // If there is no message text, then we're done
604
        if (msg_text.empty()) {
6,004✔
605
            return;
×
606
        }
×
607

608
        // If a log level wasn't provided, default to debug
609
        util::Logger::Level parsed_level = util::Logger::Level::debug;
6,004✔
610
        if (has_level) {
6,004✔
611
            if (auto it = name_to_level.find(log_level); it != name_to_level.end()) {
6,004✔
612
                parsed_level = it->second;
6,004✔
613
            }
6,004✔
614
            else {
×
615
                return report_error("Unknown log level found in log_message: \"%1\"", log_level);
×
616
            }
×
617
        }
6,004✔
618
        connection.receive_server_log_message(session_ident, parsed_level, msg_text);
6,004✔
619
    }
6,004✔
620

621
    static constexpr std::size_t s_max_body_size = std::numeric_limits<std::size_t>::max();
622

623
    // Permanent buffer to use for building messages.
624
    OutputBuffer m_output_buffer;
625

626
    // Permanent buffers to use for internal purposes such as compression.
627
    std::vector<char> m_buffer;
628

629
    util::compression::CompressMemoryArena m_compress_memory_arena;
630
};
631

632

633
class ServerProtocol {
634
public:
635
    // clang-format off
636
    using file_ident_type    = sync::file_ident_type;
637
    using version_type       = sync::version_type;
638
    using salt_type          = sync::salt_type;
639
    using timestamp_type     = sync::timestamp_type;
640
    using session_ident_type = sync::session_ident_type;
641
    using request_ident_type = sync::request_ident_type;
642
    using SaltedFileIdent    = sync::SaltedFileIdent;
643
    using SaltedVersion      = sync::SaltedVersion;
644
    using milliseconds_type  = sync::milliseconds_type;
645
    using UploadCursor       = sync::UploadCursor;
646
    // clang-format on
647

648
    using OutputBuffer = util::ResettableExpandableBufferOutputStream;
649

650
    // Messages sent by the server to the client
651

652
    void make_ident_message(int protocol_version, OutputBuffer&, session_ident_type session_ident,
653
                            file_ident_type client_file_ident, salt_type client_file_ident_salt);
654

655
    void make_alloc_message(OutputBuffer&, session_ident_type session_ident, file_ident_type file_ident);
656

657
    void make_unbound_message(OutputBuffer&, session_ident_type session_ident);
658

659

660
    struct ChangesetInfo {
661
        version_type server_version;
662
        version_type client_version;
663
        sync::HistoryEntry entry;
664
        std::size_t original_size;
665
    };
666

667
    void make_download_message(int protocol_version, OutputBuffer&, session_ident_type session_ident,
668
                               version_type download_server_version, version_type download_client_version,
669
                               version_type latest_server_version, salt_type latest_server_version_salt,
670
                               version_type upload_client_version, version_type upload_server_version,
671
                               std::uint_fast64_t downloadable_bytes, std::size_t num_changesets, const char* body,
672
                               std::size_t uncompressed_body_size, std::size_t compressed_body_size,
673
                               bool body_is_compressed, util::Logger&);
674

675
    void make_mark_message(OutputBuffer&, session_ident_type session_ident, request_ident_type request_ident);
676

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

680
    void make_pong(OutputBuffer&, milliseconds_type timestamp);
681

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

685
    // Messages received by the server.
686

687
    // parse_ping_received takes a (WebSocket) ping and parses it.
688
    // The result of the parsing is handled by an object of type Connection.
689
    // Typically, Connection would be the Connection class from server.cpp
690
    template <typename Connection>
691
    void parse_ping_received(Connection& connection, std::string_view msg_data)
692
    {
×
693
        try {
×
694
            HeaderLineParser msg(msg_data);
×
695
            auto timestamp = msg.read_next<milliseconds_type>();
×
696
            auto rtt = msg.read_next<milliseconds_type>('\n');
×
697

698
            connection.receive_ping(timestamp, rtt);
×
699
        }
×
700
        catch (const ProtocolCodecException& e) {
×
701
            connection.handle_protocol_error(Status{ErrorCodes::SyncProtocolInvariantFailed,
×
702
                                                    util::format("Bad syntax in PING message: %1", e.what())});
×
703
        }
×
704
    }
×
705

706
    // UploadChangeset is used to store received changesets in
707
    // the UPLOAD message.
708
    struct UploadChangeset {
709
        UploadCursor upload_cursor;
710
        timestamp_type origin_timestamp;
711
        file_ident_type origin_file_ident; // Zero when originating from connected client file
712
        BinaryData changeset;
713
    };
714

715
    // parse_message_received takes a (WebSocket) message and parses it.
716
    // The result of the parsing is handled by an object of type Connection.
717
    // Typically, Connection would be the Connection class from server.cpp
718
    template <class Connection>
719
    void parse_message_received(Connection& connection, std::string_view msg_data)
720
    {
70,862✔
721
        auto& logger = connection.logger;
70,862✔
722

723
        auto report_error = [&](ErrorCodes::Error err, const auto fmt, auto&&... args) {
70,862✔
724
            auto msg = util::format(fmt, std::forward<decltype(args)>(args)...);
×
725
            connection.handle_protocol_error(Status{err, std::move(msg)});
×
726
        };
×
727

728
        HeaderLineParser msg(msg_data);
70,862✔
729
        std::string_view message_type;
70,862✔
730
        try {
70,862✔
731
            message_type = msg.read_next<std::string_view>();
70,862✔
732
        }
70,862✔
733
        catch (const ProtocolCodecException& e) {
70,862✔
734
            return report_error(ErrorCodes::SyncProtocolInvariantFailed, "Could not find message type in message: %1",
×
735
                                e.what());
×
736
        }
×
737

738
        try {
70,862✔
739
            if (message_type == "upload") {
70,862✔
740
                auto msg_with_header = msg.remaining();
46,380✔
741
                auto session_ident = msg.read_next<session_ident_type>();
46,380✔
742
                auto is_body_compressed = msg.read_next<bool>();
46,380✔
743
                auto uncompressed_body_size = msg.read_next<size_t>();
46,380✔
744
                auto compressed_body_size = msg.read_next<size_t>();
46,380✔
745
                auto progress_client_version = msg.read_next<version_type>();
46,380✔
746
                auto progress_server_version = msg.read_next<version_type>();
46,380✔
747
                auto locked_server_version = msg.read_next<version_type>('\n');
46,380✔
748

749
                std::size_t body_size = (is_body_compressed ? compressed_body_size : uncompressed_body_size);
46,380✔
750
                if (body_size > s_max_body_size) {
46,380✔
751
                    auto header = msg_with_header.substr(0, msg_with_header.size() - msg.bytes_remaining());
×
752

753
                    return report_error(ErrorCodes::LimitExceeded,
×
754
                                        "Body size of upload message is too large. Raw header: %1", header);
×
755
                }
×
756

757

758
                std::unique_ptr<char[]> uncompressed_body_buffer;
46,380✔
759
                // if is_body_compressed == true, we must decompress the received body.
760
                if (is_body_compressed) {
46,380✔
761
                    uncompressed_body_buffer = std::make_unique<char[]>(uncompressed_body_size);
4,436✔
762
                    auto compressed_body = msg.read_sized_data<BinaryData>(compressed_body_size);
4,436✔
763

764
                    std::error_code ec = util::compression::decompress(
4,436✔
765
                        compressed_body, {uncompressed_body_buffer.get(), uncompressed_body_size});
4,436✔
766

767
                    if (ec) {
4,436✔
768
                        return report_error(ErrorCodes::RuntimeError, "compression::inflate: %1", ec.message());
×
769
                    }
×
770

771
                    msg = HeaderLineParser(std::string_view(uncompressed_body_buffer.get(), uncompressed_body_size));
4,436✔
772
                }
4,436✔
773

774
                logger.debug(util::LogCategory::changeset,
46,380✔
775
                             "Upload message compression: is_body_compressed = %1, "
46,380✔
776
                             "compressed_body_size=%2, uncompressed_body_size=%3, "
46,380✔
777
                             "progress_client_version=%4, progress_server_version=%5, "
46,380✔
778
                             "locked_server_version=%6",
46,380✔
779
                             is_body_compressed, compressed_body_size, uncompressed_body_size,
46,380✔
780
                             progress_client_version, progress_server_version, locked_server_version); // Throws
46,380✔
781

782

783
                std::vector<UploadChangeset> upload_changesets;
46,380✔
784

785
                // Loop through the body and find the changesets.
786
                while (!msg.at_end()) {
83,522✔
787
                    UploadChangeset upload_changeset;
37,142✔
788
                    size_t changeset_size;
37,142✔
789
                    try {
37,142✔
790
                        upload_changeset.upload_cursor.client_version = msg.read_next<version_type>();
37,142✔
791
                        upload_changeset.upload_cursor.last_integrated_server_version = msg.read_next<version_type>();
37,142✔
792
                        upload_changeset.origin_timestamp = msg.read_next<timestamp_type>();
37,142✔
793
                        upload_changeset.origin_file_ident = msg.read_next<file_ident_type>();
37,142✔
794
                        changeset_size = msg.read_next<size_t>();
37,142✔
795
                    }
37,142✔
796
                    catch (const ProtocolCodecException& e) {
37,142✔
797
                        return report_error(ErrorCodes::SyncProtocolInvariantFailed,
×
798
                                            "Bad changeset header syntax: %1", e.what());
×
799
                    }
×
800

801
                    if (changeset_size > msg.bytes_remaining()) {
37,142✔
802
                        return report_error(ErrorCodes::SyncProtocolInvariantFailed, "Bad changeset size");
×
803
                    }
×
804

805
                    upload_changeset.changeset = msg.read_sized_data<BinaryData>(changeset_size);
37,142✔
806

807
                    if (logger.would_log(util::Logger::Level::trace)) {
37,142✔
808
                        logger.trace(util::LogCategory::changeset,
×
809
                                     "Received: UPLOAD CHANGESET(client_version=%1, server_version=%2, "
×
810
                                     "origin_timestamp=%3, origin_file_ident=%4, changeset_size=%5)",
×
811
                                     upload_changeset.upload_cursor.client_version,
×
812
                                     upload_changeset.upload_cursor.last_integrated_server_version,
×
813
                                     upload_changeset.origin_timestamp, upload_changeset.origin_file_ident,
×
814
                                     changeset_size); // Throws
×
815
                        logger.trace(util::LogCategory::changeset, "Changeset: %1",
×
816
                                     clamped_hex_dump(upload_changeset.changeset)); // Throws
×
817
                    }
×
818
                    upload_changesets.push_back(std::move(upload_changeset)); // Throws
37,142✔
819
                }
37,142✔
820

821
                connection.receive_upload_message(session_ident, progress_client_version, progress_server_version,
46,380✔
822
                                                  locked_server_version,
46,380✔
823
                                                  upload_changesets); // Throws
46,380✔
824
            }
46,380✔
825
            else if (message_type == "mark") {
24,482✔
826
                auto session_ident = msg.read_next<session_ident_type>();
12,200✔
827
                auto request_ident = msg.read_next<request_ident_type>('\n');
12,200✔
828

829
                connection.receive_mark_message(session_ident, request_ident); // Throws
12,200✔
830
            }
12,200✔
831
            else if (message_type == "ping") {
12,282✔
832
                auto timestamp = msg.read_next<milliseconds_type>();
112✔
833
                auto rtt = msg.read_next<milliseconds_type>('\n');
112✔
834

835
                connection.receive_ping(timestamp, rtt);
112✔
836
            }
112✔
837
            else if (message_type == "bind") {
12,170✔
838
                auto session_ident = msg.read_next<session_ident_type>();
5,340✔
839
                auto path_size = msg.read_next<size_t>();
5,340✔
840
                auto signed_user_token_size = msg.read_next<size_t>();
5,340✔
841
                auto need_client_file_ident = msg.read_next<bool>();
5,340✔
842
                auto is_subserver = msg.read_next<bool>('\n');
5,340✔
843

844
                if (path_size == 0) {
5,340✔
845
                    return report_error(ErrorCodes::SyncProtocolInvariantFailed, "Path size in BIND message is zero");
×
846
                }
×
847
                if (path_size > s_max_path_size) {
5,340✔
848
                    return report_error(ErrorCodes::SyncProtocolInvariantFailed,
×
849
                                        "Path size in BIND message is too large");
×
850
                }
×
851
                if (signed_user_token_size > s_max_signed_user_token_size) {
5,340✔
852
                    return report_error(ErrorCodes::SyncProtocolInvariantFailed,
×
853
                                        "Signed user token size in BIND message is too large");
×
854
                }
×
855

856
                auto path = msg.read_sized_data<std::string>(path_size);
5,340✔
857
                auto signed_user_token = msg.read_sized_data<std::string>(signed_user_token_size);
5,340✔
858

859
                connection.receive_bind_message(session_ident, std::move(path), std::move(signed_user_token),
5,340✔
860
                                                need_client_file_ident, is_subserver); // Throws
5,340✔
861
            }
5,340✔
862
            else if (message_type == "ident") {
6,830✔
863
                auto session_ident = msg.read_next<session_ident_type>();
4,362✔
864
                auto client_file_ident = msg.read_next<file_ident_type>();
4,362✔
865
                auto client_file_ident_salt = msg.read_next<salt_type>();
4,362✔
866
                auto scan_server_version = msg.read_next<version_type>();
4,362✔
867
                auto scan_client_version = msg.read_next<version_type>();
4,362✔
868
                auto latest_server_version = msg.read_next<version_type>();
4,362✔
869
                auto latest_server_version_salt = msg.read_next<salt_type>('\n');
4,362✔
870

871
                connection.receive_ident_message(session_ident, client_file_ident, client_file_ident_salt,
4,362✔
872
                                                 scan_server_version, scan_client_version, latest_server_version,
4,362✔
873
                                                 latest_server_version_salt); // Throws
4,362✔
874
            }
4,362✔
875
            else if (message_type == "unbind") {
2,470✔
876
                auto session_ident = msg.read_next<session_ident_type>('\n');
2,468✔
877

878
                connection.receive_unbind_message(session_ident); // Throws
2,468✔
879
            }
2,468✔
880
            else if (message_type == "json_error") {
2,147,483,649✔
881
                auto error_code = msg.read_next<int>();
×
882
                auto message_size = msg.read_next<size_t>();
×
883
                auto session_ident = msg.read_next<session_ident_type>('\n');
×
884
                auto json_raw = msg.read_sized_data<std::string_view>(message_size);
×
885

886
                connection.receive_error_message(session_ident, error_code, json_raw);
×
887
            }
×
888
            else {
2,147,483,649✔
889
                return report_error(ErrorCodes::SyncProtocolInvariantFailed, "unknown message type %1", message_type);
2,147,483,649✔
890
            }
2,147,483,649✔
891
        }
70,862✔
892
        catch (const ProtocolCodecException& e) {
70,862✔
893
            return report_error(ErrorCodes::SyncProtocolInvariantFailed, "bad syntax in %1 message: %2", message_type,
×
894
                                e.what());
×
895
        }
×
896
    }
70,862✔
897

898
    void insert_single_changeset_download_message(OutputBuffer&, const ChangesetInfo&, util::Logger&);
899

900
private:
901
    // clang-format off
902
    static constexpr std::size_t s_max_head_size              =  256;
903
    static constexpr std::size_t s_max_signed_user_token_size = 2048;
904
    static constexpr std::size_t s_max_client_info_size       = 1024;
905
    static constexpr std::size_t s_max_path_size              = 1024;
906
    static constexpr std::size_t s_max_changeset_size         = std::numeric_limits<std::size_t>::max(); // FIXME: What is a reasonable value here?
907
    static constexpr std::size_t s_max_body_size              = std::numeric_limits<std::size_t>::max();
908
    // clang-format on
909
};
910

911
// make_authorization_header() makes the value of the Authorization header used in the
912
// sync Websocket handshake.
913
std::string make_authorization_header(const std::string& signed_user_token);
914

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

919
} // namespace realm::_impl
920

921
#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