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

realm / realm-core / 2210

09 Apr 2024 03:41PM UTC coverage: 92.601% (+0.5%) from 92.106%
2210

push

Evergreen

web-flow
Merge pull request #7300 from realm/tg/rework-metadata-storage

Rework sync user handling and metadata storage

102800 of 195548 branches covered (52.57%)

3051 of 3153 new or added lines in 46 files covered. (96.76%)

41 existing lines in 11 files now uncovered.

249129 of 269035 relevant lines covered (92.6%)

46864217.27 hits per line

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

82.06
/src/realm/sync/noinst/server/server.cpp
1
#include <realm/sync/noinst/server/server.hpp>
2

3
#include <realm/binary_data.hpp>
4
#include <realm/impl/simulated_failure.hpp>
5
#include <realm/object_id.hpp>
6
#include <realm/string_data.hpp>
7
#include <realm/sync/changeset.hpp>
8
#include <realm/sync/trigger.hpp>
9
#include <realm/sync/impl/clamped_hex_dump.hpp>
10
#include <realm/sync/impl/clock.hpp>
11
#include <realm/sync/network/http.hpp>
12
#include <realm/sync/network/network_ssl.hpp>
13
#include <realm/sync/network/websocket.hpp>
14
#include <realm/sync/noinst/client_history_impl.hpp>
15
#include <realm/sync/noinst/protocol_codec.hpp>
16
#include <realm/sync/noinst/server/access_control.hpp>
17
#include <realm/sync/noinst/server/server_dir.hpp>
18
#include <realm/sync/noinst/server/server_file_access_cache.hpp>
19
#include <realm/sync/noinst/server/server_impl_base.hpp>
20
#include <realm/sync/transform.hpp>
21
#include <realm/util/base64.hpp>
22
#include <realm/util/bind_ptr.hpp>
23
#include <realm/util/buffer_stream.hpp>
24
#include <realm/util/circular_buffer.hpp>
25
#include <realm/util/compression.hpp>
26
#include <realm/util/file.hpp>
27
#include <realm/util/json_parser.hpp>
28
#include <realm/util/load_file.hpp>
29
#include <realm/util/memory_stream.hpp>
30
#include <realm/util/optional.hpp>
31
#include <realm/util/platform_info.hpp>
32
#include <realm/util/random.hpp>
33
#include <realm/util/safe_int_ops.hpp>
34
#include <realm/util/scope_exit.hpp>
35
#include <realm/util/scratch_allocator.hpp>
36
#include <realm/util/thread.hpp>
37
#include <realm/util/thread_exec_guard.hpp>
38
#include <realm/util/value_reset_guard.hpp>
39
#include <realm/version.hpp>
40

41
#include <algorithm>
42
#include <atomic>
43
#include <cctype>
44
#include <chrono>
45
#include <cmath>
46
#include <condition_variable>
47
#include <cstdint>
48
#include <cstdio>
49
#include <cstring>
50
#include <functional>
51
#include <locale>
52
#include <map>
53
#include <memory>
54
#include <queue>
55
#include <sstream>
56
#include <stdexcept>
57
#include <thread>
58
#include <vector>
59

60
// NOTE: The protocol specification is in `/doc/protocol.md`
61

62

63
// FIXME: Verify that session identifier spoofing cannot be used to get access
64
// to sessions belonging to other network conections in any way.
65
// FIXME: Seems that server must close connection with zero sessions after a
66
// certain timeout.
67

68

69
using namespace realm;
70
using namespace realm::sync;
71
using namespace realm::util;
72

73
// clang-format off
74
using ServerHistory         = _impl::ServerHistory;
75
using ServerProtocol        = _impl::ServerProtocol;
76
using ServerFileAccessCache = _impl::ServerFileAccessCache;
77
using ServerImplBase = _impl::ServerImplBase;
78

79
using IntegratableChangeset = ServerHistory::IntegratableChangeset;
80
using IntegratableChangesetList = ServerHistory::IntegratableChangesetList;
81
using IntegratableChangesets = ServerHistory::IntegratableChangesets;
82
using IntegrationResult = ServerHistory::IntegrationResult;
83
using BootstrapError = ServerHistory::BootstrapError;
84
using ExtendedIntegrationError = ServerHistory::ExtendedIntegrationError;
85
using ClientType = ServerHistory::ClientType;
86
using FileIdentAllocSlot = ServerHistory::FileIdentAllocSlot;
87
using FileIdentAllocSlots = ServerHistory::FileIdentAllocSlots;
88

89
using UploadChangeset = ServerProtocol::UploadChangeset;
90
// clang-format on
91

92

93
using UploadChangesets = std::vector<UploadChangeset>;
94

95
using EventLoopMetricsHandler = network::Service::EventLoopMetricsHandler;
96

97

98
static_assert(std::numeric_limits<session_ident_type>::digits >= 63, "Bad session identifier type");
99
static_assert(std::numeric_limits<file_ident_type>::digits >= 63, "Bad file identifier type");
100
static_assert(std::numeric_limits<version_type>::digits >= 63, "Bad version type");
101
static_assert(std::numeric_limits<timestamp_type>::digits >= 63, "Bad timestamp type");
102

103

104
namespace {
105

106
enum class SchedStatus { done = 0, pending, in_progress };
107

108
// Only used by the Sync Server to support older pbs sync clients (prior to protocol v8)
109
constexpr std::string_view get_old_pbs_websocket_protocol_prefix() noexcept
110
{
×
111
    return "com.mongodb.realm-sync/";
×
112
}
×
113

114
std::string short_token_fmt(const std::string& str, size_t cutoff = 30)
115
{
3,018✔
116
    if (str.size() > cutoff) {
3,018✔
117
        return "..." + str.substr(str.size() - cutoff);
×
118
    }
×
119
    else {
3,018✔
120
        return str;
3,018✔
121
    }
3,018✔
122
}
3,018✔
123

124

125
class HttpListHeaderValueParser {
126
public:
127
    HttpListHeaderValueParser(std::string_view string) noexcept
128
        : m_string{string}
129
    {
16,218✔
130
    }
16,218✔
131
    bool next(std::string_view& elem) noexcept
132
    {
194,648✔
133
        while (m_pos < m_string.size()) {
194,654✔
134
            size_type i = m_pos;
178,422✔
135
            size_type j = m_string.find(',', i);
178,422✔
136
            if (j != std::string_view::npos) {
178,422✔
137
                m_pos = j + 1;
162,204✔
138
            }
162,204✔
139
            else {
16,218✔
140
                j = m_string.size();
16,218✔
141
                m_pos = j;
16,218✔
142
            }
16,218✔
143

83,508✔
144
            // Exclude leading and trailing white space
83,508✔
145
            while (i < j && is_http_lws(m_string[i]))
340,632✔
146
                ++i;
162,202✔
147
            while (j > i && is_http_lws(m_string[j - 1]))
178,430✔
148
                --j;
×
149

83,508✔
150
            if (i != j) {
178,426✔
151
                elem = m_string.substr(i, j - i);
178,418✔
152
                return true;
178,418✔
153
            }
178,418✔
154
        }
178,422✔
155
        return false;
99,740✔
156
    }
194,648✔
157

158
private:
159
    using size_type = std::string_view::size_type;
160
    const std::string_view m_string;
161
    size_type m_pos = 0;
162
    static bool is_http_lws(char ch) noexcept
163
    {
519,004✔
164
        return (ch == '\t' || ch == '\n' || ch == '\r' || ch == ' ');
519,008✔
165
    }
519,004✔
166
};
167

168

169
using SteadyClock = std::conditional<std::chrono::high_resolution_clock::is_steady,
170
                                     std::chrono::high_resolution_clock, std::chrono::steady_clock>::type;
171
using SteadyTimePoint = SteadyClock::time_point;
172

173
SteadyTimePoint steady_clock_now() noexcept
174
{
1,336,620✔
175
    return SteadyClock::now();
1,336,620✔
176
}
1,336,620✔
177

178
milliseconds_type steady_duration(SteadyTimePoint start_time, SteadyTimePoint end_time = steady_clock_now()) noexcept
179
{
327,348✔
180
    auto duration = end_time - start_time;
327,348✔
181
    auto millis_duration = std::chrono::duration_cast<std::chrono::milliseconds>(duration).count();
327,348✔
182
    return milliseconds_type(millis_duration);
327,348✔
183
}
327,348✔
184

185

186
bool determine_try_again(ProtocolError error_code) noexcept
187
{
842✔
188
    return (error_code == ProtocolError::connection_closed);
842✔
189
}
842✔
190

191

192
class ServerFile;
193
class ServerImpl;
194
class HTTPConnection;
195
class SyncConnection;
196
class Session;
197

198

199
using Formatter = util::ResettableExpandableBufferOutputStream;
200
using OutputBuffer = util::ResettableExpandableBufferOutputStream;
201

202
using ProtocolVersionRange = std::pair<int, int>;
203

204
class MiscBuffers {
205
public:
206
    Formatter formatter;
207
    OutputBuffer download_message;
208

209
    using ProtocolVersionRanges = std::vector<ProtocolVersionRange>;
210
    ProtocolVersionRanges protocol_version_ranges;
211

212
    std::vector<char> compress;
213

214
    MiscBuffers()
215
    {
11,732✔
216
        formatter.imbue(std::locale::classic());
11,732✔
217
        download_message.imbue(std::locale::classic());
11,732✔
218
    }
11,732✔
219
};
220

221

222
struct DownloadCache {
223
    std::unique_ptr<char[]> body;
224
    std::size_t uncompressed_body_size;
225
    std::size_t compressed_body_size;
226
    bool body_is_compressed;
227
    version_type end_version;
228
    DownloadCursor download_progress;
229
    std::uint_fast64_t downloadable_bytes;
230
    std::size_t num_changesets;
231
    std::size_t accum_original_size;
232
    std::size_t accum_compacted_size;
233
};
234

235

236
// An unblocked work unit is comprised of one Work object for each of the files
237
// that contribute work to the work unit, generally one reference file and a
238
// number of partial files.
239
class Work {
240
public:
241
    // In general, primary work is all forms of modifying work, including file
242
    // deletion.
243
    bool has_primary_work = false;
244

245
    // Only for reference files
246
    bool might_produce_new_sync_version = false;
247

248
    bool produced_new_realm_version = false;
249
    bool produced_new_sync_version = false;
250
    bool expired_reference_version = false;
251

252
    // True if, and only if changesets_from_downstream contains at least one
253
    // changeset.
254
    bool have_changesets_from_downstream = false;
255

256
    FileIdentAllocSlots file_ident_alloc_slots;
257
    std::vector<std::unique_ptr<char[]>> changeset_buffers;
258
    IntegratableChangesets changesets_from_downstream;
259

260
    VersionInfo version_info;
261

262
    // Result of integration of changesets from downstream clients
263
    IntegrationResult integration_result;
264

265
    void reset() noexcept
266
    {
327,108✔
267
        has_primary_work = false;
327,108✔
268

153,136✔
269
        might_produce_new_sync_version = false;
327,108✔
270

153,136✔
271
        produced_new_realm_version = false;
327,108✔
272
        produced_new_sync_version = false;
327,108✔
273
        expired_reference_version = false;
327,108✔
274
        have_changesets_from_downstream = false;
327,108✔
275

153,136✔
276
        file_ident_alloc_slots.clear();
327,108✔
277
        changeset_buffers.clear();
327,108✔
278
        changesets_from_downstream.clear();
327,108✔
279

153,136✔
280
        version_info = {};
327,108✔
281
        integration_result = {};
327,108✔
282
    }
327,108✔
283
};
284

285

286
class WorkerState {
287
public:
288
    FileIdentAllocSlots file_ident_alloc_slots;
289
    util::ScratchMemory scratch_memory;
290
    bool use_file_cache = true;
291
    std::unique_ptr<ServerHistory> reference_hist;
292
    DBRef reference_sg;
293
};
294

295

296
// ============================ SessionQueue ============================
297

298
class SessionQueue {
299
public:
300
    void push_back(Session*) noexcept;
301
    Session* pop_front() noexcept;
302
    void clear() noexcept;
303

304
private:
305
    Session* m_back = nullptr;
306
};
307

308

309
// ============================ FileIdentReceiver ============================
310

311
class FileIdentReceiver {
312
public:
313
    virtual void receive_file_ident(SaltedFileIdent) = 0;
314

315
protected:
316
    ~FileIdentReceiver() {}
55,076✔
317
};
318

319

320
// ============================ WorkerBox =============================
321

322
class WorkerBox {
323
public:
324
    using JobType = util::UniqueFunction<void(WorkerState&)>;
325
    void add_work(WorkerState& state, JobType job)
326
    {
×
327
        std::unique_lock<std::mutex> lock(m_mutex);
×
328
        if (m_jobs.size() >= m_queue_limit) {
×
329
            // Once we have many queued jobs, it is better to use this thread to run a new job
×
330
            // than to queue it.
×
331
            run_a_job(lock, state, job);
×
332
        }
×
333
        else {
×
334
            // Create worker threads on demand (if all existing threads are active):
×
335
            if (m_threads.size() < m_max_num_threads && m_active >= m_threads.size()) {
×
336
                m_threads.emplace_back([this]() {
×
337
                    WorkerState state;
×
338
                    state.use_file_cache = false;
×
339
                    JobType the_job;
×
340
                    std::unique_lock<std::mutex> lock(m_mutex);
×
341
                    for (;;) {
×
342
                        while (m_jobs.empty() && !m_finish_up)
×
343
                            m_changes.wait(lock);
×
344
                        if (m_finish_up)
×
345
                            break; // terminate thread
×
346
                        the_job = std::move(m_jobs.back());
×
347
                        m_jobs.pop_back();
×
348
                        run_a_job(lock, state, the_job);
×
349
                        m_changes.notify_all();
×
350
                    }
×
351
                });
×
352
            }
×
353

×
354
            // Submit the job for execution:
×
355
            m_jobs.emplace_back(std::move(job));
×
356
            m_changes.notify_all();
×
357
        }
×
358
    }
×
359

360
    // You should call wait_completion() before trying to destroy a WorkerBox to get proper
361
    // propagation of exceptions.
362
    void wait_completion(WorkerState& state)
363
    {
×
364
        std::unique_lock<std::mutex> lock(m_mutex);
×
365
        while (!m_jobs.empty() || m_active > 0) {
×
366
            if (!m_jobs.empty()) { // if possible, make this thread participate in running m_jobs
×
367
                JobType the_job = std::move(m_jobs.back());
×
368
                m_jobs.pop_back();
×
369
                run_a_job(lock, state, the_job);
×
370
            }
×
371
            else {
×
372
                m_changes.wait(lock);
×
373
            }
×
374
        }
×
375
        if (m_epr) {
×
376
            std::rethrow_exception(m_epr);
×
377
        }
×
378
    }
×
379

380
    WorkerBox(unsigned int num_threads)
381
    {
×
382
        m_queue_limit = num_threads * 10; // fudge factor for job size variation
×
383
        m_max_num_threads = num_threads;
×
384
    }
×
385

386
    ~WorkerBox()
387
    {
×
388
        {
×
389
            std::unique_lock<std::mutex> lock(m_mutex);
×
390
            m_finish_up = true;
×
391
            m_changes.notify_all();
×
392
        }
×
393
        for (auto& e : m_threads)
×
394
            e.join();
×
395
    }
×
396

397
private:
398
    std::mutex m_mutex;
399
    std::condition_variable m_changes;
400
    std::vector<std::thread> m_threads;
401
    std::vector<JobType> m_jobs;
402
    unsigned int m_active = 0;
403
    bool m_finish_up = false;
404
    unsigned int m_queue_limit = 0;
405
    unsigned int m_max_num_threads = 0;
406
    std::exception_ptr m_epr;
407

408
    void run_a_job(std::unique_lock<std::mutex>& lock, WorkerState& state, JobType& job)
409
    {
×
410
        ++m_active;
×
411
        lock.unlock();
×
412
        try {
×
413
            job(state);
×
414
            lock.lock();
×
415
        }
×
416
        catch (...) {
×
417
            lock.lock();
×
418
            if (!m_epr)
×
419
                m_epr = std::current_exception();
×
420
        }
×
421
        --m_active;
×
422
    }
×
423
};
424

425

426
// ============================ ServerFile ============================
427

428
class ServerFile : public util::RefCountBase {
429
public:
430
    util::PrefixLogger logger;
431

432
    // Logger to be used by the worker thread
433
    util::PrefixLogger wlogger;
434

435
    ServerFile(ServerImpl& server, ServerFileAccessCache& cache, const std::string& virt_path, std::string real_path,
436
               bool disable_sync_to_disk);
437
    ~ServerFile() noexcept;
438

439
    void initialize();
440
    void activate();
441

442
    ServerImpl& get_server() noexcept
443
    {
341,456✔
444
        return m_server;
341,456✔
445
    }
341,456✔
446

447
    const std::string& get_real_path() const noexcept
448
    {
×
449
        return m_file.realm_path;
×
450
    }
×
451

452
    const std::string& get_virt_path() const noexcept
453
    {
×
454
        return m_file.virt_path;
×
455
    }
×
456

457
    ServerFileAccessCache::File& access()
458
    {
437,528✔
459
        return m_file.access(); // Throws
437,528✔
460
    }
437,528✔
461

462
    ServerFileAccessCache::File& worker_access()
463
    {
326,560✔
464
        return m_worker_file.access(); // Throws
326,560✔
465
    }
326,560✔
466

467
    version_type get_realm_version() const noexcept
468
    {
×
469
        return m_version_info.realm_version;
×
470
    }
×
471

472
    version_type get_sync_version() const noexcept
473
    {
×
474
        return m_version_info.sync_version.version;
×
475
    }
×
476

477
    SaltedVersion get_salted_sync_version() const noexcept
478
    {
892,146✔
479
        return m_version_info.sync_version;
892,146✔
480
    }
892,146✔
481

482
    DownloadCache& get_download_cache() noexcept;
483

484
    void register_client_access(file_ident_type client_file_ident);
485

486
    using file_ident_request_type = std::int_fast64_t;
487

488
    // Initiate a request for a new client file identifier.
489
    //
490
    // Unless the request is cancelled, the identifier will be delivered to the
491
    // receiver by way of an invocation of
492
    // FileIdentReceiver::receive_file_ident().
493
    //
494
    // FileIdentReceiver::receive_file_ident() is guaranteed to not be called
495
    // until after request_file_ident() has returned (no callback reentrance).
496
    //
497
    // New client file identifiers will be delivered to receivers in the order
498
    // that they were requested.
499
    //
500
    // The returned value is a nonzero integer that can be used to cancel the
501
    // request before the file identifier is delivered using
502
    // cancel_file_ident_request().
503
    auto request_file_ident(FileIdentReceiver&, file_ident_type proxy_file, ClientType) -> file_ident_request_type;
504

505
    // Cancel the specified file identifier request.
506
    //
507
    // It is an error to call this function after the identifier has been
508
    // delivered.
509
    void cancel_file_ident_request(file_ident_request_type) noexcept;
510

511
    void add_unidentified_session(Session*);
512
    void identify_session(Session*, file_ident_type client_file_ident);
513

514
    void remove_unidentified_session(Session*) noexcept;
515
    void remove_identified_session(file_ident_type client_file_ident) noexcept;
516

517
    Session* get_identified_session(file_ident_type client_file_ident) noexcept;
518

519
    bool can_add_changesets_from_downstream() const noexcept;
520
    void add_changesets_from_downstream(file_ident_type client_file_ident, UploadCursor upload_progress,
521
                                        version_type locked_server_version, const UploadChangeset*,
522
                                        std::size_t num_changesets);
523

524
    // bootstrap_client_session calls the function of same name in server_history
525
    // but corrects the upload_progress with information from pending
526
    // integratable changesets. A situation can occur where a client terminates
527
    // a session and starts a new session and re-uploads changesets that are known
528
    // by the ServerFile object but not by the ServerHistory.
529
    BootstrapError bootstrap_client_session(SaltedFileIdent client_file_ident, DownloadCursor download_progress,
530
                                            SaltedVersion server_version, ClientType client_type,
531
                                            UploadCursor& upload_progress, version_type& locked_server_version,
532
                                            Logger&);
533

534
    // NOTE: This function is executed by the worker thread
535
    void worker_process_work_unit(WorkerState&);
536

537
    void recognize_external_change();
538

539
private:
540
    ServerImpl& m_server;
541
    ServerFileAccessCache::Slot m_file;
542

543
    // In general, `m_version_info` refers to the last snapshot of the Realm
544
    // file that is supposed to be visible to remote peers engaging in regular
545
    // Realm file synchronization.
546
    VersionInfo m_version_info;
547

548
    file_ident_request_type m_last_file_ident_request = 0;
549

550
    // The set of sessions whose client file identifier is not yet known, i.e.,
551
    // those for which an IDENT message has not yet been received,
552
    std::set<Session*> m_unidentified_sessions;
553

554
    // A map of the sessions whose client file identifier is known, i.e, those
555
    // for which an IDENT message has been received.
556
    std::map<file_ident_type, Session*> m_identified_sessions;
557

558
    // Used when a file used as partial view wants to allocate a client file
559
    // identifier from the reference Realm.
560
    file_ident_request_type m_file_ident_request = 0;
561

562
    struct FileIdentRequestInfo {
563
        FileIdentReceiver* receiver;
564
        file_ident_type proxy_file;
565
        ClientType client_type;
566
    };
567

568
    // When nonempty, it counts towards outstanding blocked work (see
569
    // `m_has_blocked_work`).
570
    std::map<file_ident_request_type, FileIdentRequestInfo> m_file_ident_requests;
571

572
    // Changesets received from the downstream clients, and waiting to be
573
    // integrated, as well as information about the clients progress in terms of
574
    // integrating changesets received from the server. When nonempty, it counts
575
    // towards outstanding blocked work (see `m_has_blocked_work`).
576
    //
577
    // At any given time, the set of changesets from a particular client-side
578
    // file may be comprised of changesets received via distinct sessions.
579
    //
580
    // See also `m_num_changesets_from_downstream`.
581
    IntegratableChangesets m_changesets_from_downstream;
582

583
    // Keeps track of the number of changesets in `m_changesets_from_downstream`.
584
    //
585
    // Its purpose is also to initialize
586
    // `Work::have_changesets_from_downstream`.
587
    std::size_t m_num_changesets_from_downstream = 0;
588

589
    // The total size, in bytes, of the changesets that were received from
590
    // clients, are targeting this file, and are currently part of the blocked
591
    // work unit.
592
    //
593
    // Together with `m_unblocked_changesets_from_downstream_byte_size`, its
594
    // purpose is to allow the server to keep track of the accumulated size of
595
    // changesets being processed, or waiting to be processed (metric
596
    // `upload.pending.bytes`) (see
597
    // ServerImpl::inc_byte_size_for_pending_downstream_changesets()).
598
    //
599
    // Its purpose is also to enable the "very poor man's" backpressure solution
600
    // (see can_add_changesets_from_downstream()).
601
    std::size_t m_blocked_changesets_from_downstream_byte_size = 0;
602

603
    // Same as `m_blocked_changesets_from_downstream_byte_size` but for the
604
    // currently unblocked work unit.
605
    std::size_t m_unblocked_changesets_from_downstream_byte_size = 0;
606

607
    // When nonempty, it counts towards outstanding blocked work (see
608
    // `m_has_blocked_work`).
609
    std::vector<std::string> m_permission_changes;
610

611
    // True iff this file, or any of its associated partial files (when
612
    // applicable), has a nonzero amount of outstanding work that is currently
613
    // held back from being passed to the worker thread because a previously
614
    // accumulated chunk of work related to this file is currently in progress.
615
    bool m_has_blocked_work = false;
616

617
    // A file, that is not a partial file, is considered *exposed to the worker
618
    // thread* from the point in time where it is submitted to the worker
619
    // (Worker::enqueue()) and up until the point in time where
620
    // group_postprocess_stage_1() starts to execute. A partial file is
621
    // considered *exposed to the worker thread* precisely when the associated
622
    // reference file is exposed to the worker thread, but only if it was in
623
    // `m_reference_file->m_work.partial_files` at the point in time where the
624
    // reference file was passed to the worker.
625
    //
626
    // While this file is exposed to the worker thread, all members of `m_work`
627
    // other than `changesets_from_downstream` may be accessed and modified by
628
    // the worker thread only.
629
    //
630
    // While this file is exposed to the worker thread,
631
    // `m_work.changesets_from_downstream` may be accessed by all threads, but
632
    // must not be modified by any thread. This special status of
633
    // `m_work.changesets_from_downstream` is required to allow
634
    // ServerFile::bootstrap_client_session() to read from it at any time.
635
    Work m_work;
636

637
    // For reference files, set to true when work is unblocked, and reset back
638
    // to false when the work finalization process completes
639
    // (group_postprocess_stage_3()). Always zero for partial files.
640
    bool m_has_work_in_progress = 0;
641

642
    // This one must only be accessed by the worker thread.
643
    //
644
    // More specifically, `m_worker_file.access()` must only be called by the
645
    // worker thread, and if it was ever called, it must be closed by the worker
646
    // thread before the ServerFile object is destroyed, if destruction happens
647
    // before the destruction of the server object itself.
648
    ServerFileAccessCache::Slot m_worker_file;
649

650
    std::vector<std::int_fast64_t> m_deleting_connections;
651

652
    DownloadCache m_download_cache;
653

654
    void on_changesets_from_downstream_added(std::size_t num_changesets, std::size_t num_bytes);
655
    void on_work_added();
656
    void group_unblock_work();
657
    void unblock_work();
658

659
    /// Resume history scanning in all sessions bound to this file. To be called
660
    /// after a successfull integration of a changeset.
661
    void resume_download() noexcept;
662

663
    // NOTE: These functions are executed by the worker thread
664
    void worker_allocate_file_identifiers();
665
    bool worker_integrate_changes_from_downstream(WorkerState&);
666
    ServerHistory& get_client_file_history(WorkerState& state, std::unique_ptr<ServerHistory>& hist_ptr,
667
                                           DBRef& sg_ptr);
668
    ServerHistory& get_reference_file_history(WorkerState& state);
669
    void group_postprocess_stage_1();
670
    void group_postprocess_stage_2();
671
    void group_postprocess_stage_3();
672
    void group_finalize_work_stage_1();
673
    void group_finalize_work_stage_2();
674
    void finalize_work_stage_1();
675
    void finalize_work_stage_2();
676
};
677

678

679
inline DownloadCache& ServerFile::get_download_cache() noexcept
680
{
342,336✔
681
    return m_download_cache;
342,336✔
682
}
342,336✔
683

684
inline void ServerFile::group_finalize_work_stage_1()
685
{
323,388✔
686
    finalize_work_stage_1(); // Throws
323,388✔
687
}
323,388✔
688

689
inline void ServerFile::group_finalize_work_stage_2()
690
{
323,386✔
691
    finalize_work_stage_2(); // Throws
323,386✔
692
}
323,386✔
693

694

695
// ============================ Worker ============================
696

697
// All write transaction on server-side Realm files performed on behalf of the
698
// server, must be performed by the worker thread, not the network event loop
699
// thread. This is to ensure that the network event loop thread never gets
700
// blocked waiting for the worker thread to end a long running write
701
// transaction.
702
//
703
// FIXME: Currently, the event loop thread does perform a number of write
704
// transactions, but only on subtier nodes of a star topology server cluster.
705
class Worker : public ServerHistory::Context {
706
public:
707
    std::shared_ptr<util::Logger> logger_ptr;
708
    util::Logger& logger;
709

710
    explicit Worker(ServerImpl&);
711

712
    ServerFileAccessCache& get_file_access_cache() noexcept;
713

714
    void enqueue(ServerFile*);
715

716
    // Overriding members of ServerHistory::Context
717
    std::mt19937_64& server_history_get_random() noexcept override final;
718

719
private:
720
    ServerImpl& m_server;
721
    std::mt19937_64 m_random;
722
    ServerFileAccessCache m_file_access_cache;
723

724
    util::Mutex m_mutex;
725
    util::CondVar m_cond; // Protected by `m_mutex`
726

727
    bool m_stop = false; // Protected by `m_mutex`
728

729
    util::CircularBuffer<ServerFile*> m_queue; // Protected by `m_mutex`
730

731
    WorkerState m_state;
732

733
    void run();
734
    void stop() noexcept;
735

736
    friend class util::ThreadExecGuardWithParent<Worker, ServerImpl>;
737
};
738

739

740
inline ServerFileAccessCache& Worker::get_file_access_cache() noexcept
741
{
9,324✔
742
    return m_file_access_cache;
9,324✔
743
}
9,324✔
744

745

746
// ============================ ServerImpl ============================
747

748
class ServerImpl : public ServerImplBase, public ServerHistory::Context {
749
public:
750
    std::uint_fast64_t errors_seen = 0;
751

752
    std::atomic<milliseconds_type> m_par_time;
753
    std::atomic<milliseconds_type> m_seq_time;
754

755
    util::Mutex last_client_accesses_mutex;
756

757
    const std::shared_ptr<util::Logger> logger_ptr;
758
    util::Logger& logger;
759

760
    network::Service& get_service() noexcept
761
    {
448,044✔
762
        return m_service;
448,044✔
763
    }
448,044✔
764

765
    const network::Service& get_service() const noexcept
766
    {
×
767
        return m_service;
×
768
    }
×
769

770
    std::mt19937_64& get_random() noexcept
771
    {
572,102✔
772
        return m_random;
572,102✔
773
    }
572,102✔
774

775
    const Server::Config& get_config() const noexcept
776
    {
961,420✔
777
        return m_config;
961,420✔
778
    }
961,420✔
779

780
    std::size_t get_max_upload_backlog() const noexcept
781
    {
384,842✔
782
        return m_max_upload_backlog;
384,842✔
783
    }
384,842✔
784

785
    const std::string& get_root_dir() const noexcept
786
    {
55,074✔
787
        return m_root_dir;
55,074✔
788
    }
55,074✔
789

790
    network::ssl::Context& get_ssl_context() noexcept
791
    {
404✔
792
        return *m_ssl_context;
404✔
793
    }
404✔
794

795
    const AccessControl& get_access_control() const noexcept
796
    {
×
797
        return m_access_control;
×
798
    }
×
799

800
    ProtocolVersionRange get_protocol_version_range() const noexcept
801
    {
16,222✔
802
        return m_protocol_version_range;
16,222✔
803
    }
16,222✔
804

805
    ServerProtocol& get_server_protocol() noexcept
806
    {
1,196,594✔
807
        return m_server_protocol;
1,196,594✔
808
    }
1,196,594✔
809

810
    compression::CompressMemoryArena& get_compress_memory_arena() noexcept
811
    {
35,902✔
812
        return m_compress_memory_arena;
35,902✔
813
    }
35,902✔
814

815
    MiscBuffers& get_misc_buffers() noexcept
816
    {
394,454✔
817
        return m_misc_buffers;
394,454✔
818
    }
394,454✔
819

820
    int_fast64_t get_current_server_session_ident() const noexcept
821
    {
×
822
        return m_current_server_session_ident;
×
823
    }
×
824

825
    util::ScratchMemory& get_scratch_memory() noexcept
826
    {
×
827
        return m_scratch_memory;
×
828
    }
×
829

830
    Worker& get_worker() noexcept
831
    {
345,300✔
832
        return m_worker;
345,300✔
833
    }
345,300✔
834

835
    void get_workunit_timers(milliseconds_type& parallel_section, milliseconds_type& sequential_section)
836
    {
×
837
        parallel_section = m_par_time;
×
838
        sequential_section = m_seq_time;
×
839
    }
×
840

841
    ServerImpl(const std::string& root_dir, util::Optional<sync::PKey>, Server::Config);
842
    ~ServerImpl() noexcept;
843

844
    void start();
845

846
    void start(std::string listen_address, std::string listen_port, bool reuse_address)
847
    {
5,778✔
848
        m_config.listen_address = listen_address;
5,778✔
849
        m_config.listen_port = listen_port;
5,778✔
850
        m_config.reuse_address = reuse_address;
5,778✔
851

2,736✔
852
        start(); // Throws
5,778✔
853
    }
5,778✔
854

855
    network::Endpoint listen_endpoint() const
856
    {
11,794✔
857
        return m_acceptor.local_endpoint();
11,794✔
858
    }
11,794✔
859

860
    void run();
861
    void stop() noexcept;
862

863
    void remove_http_connection(std::int_fast64_t conn_id) noexcept;
864

865
    void add_sync_connection(int_fast64_t connection_id, std::unique_ptr<SyncConnection>&& sync_conn);
866
    void remove_sync_connection(int_fast64_t connection_id);
867

868
    size_t get_number_of_http_connections()
869
    {
×
870
        return m_http_connections.size();
×
871
    }
×
872

873
    size_t get_number_of_sync_connections()
874
    {
×
875
        return m_sync_connections.size();
×
876
    }
×
877

878
    bool is_sync_stopped()
879
    {
343,336✔
880
        return m_sync_stopped;
343,336✔
881
    }
343,336✔
882

883
    const std::set<std::string>& get_realm_names() const noexcept
884
    {
×
885
        return m_realm_names;
×
886
    }
×
887

888
    // virt_path must be valid when get_or_create_file() is called.
889
    util::bind_ptr<ServerFile> get_or_create_file(const std::string& virt_path)
890
    {
54,838✔
891
        util::bind_ptr<ServerFile> file = get_file(virt_path);
54,838✔
892
        if (REALM_LIKELY(file))
54,838✔
893
            return file;
48,940✔
894

3,430✔
895
        _impl::VirtualPathComponents virt_path_components =
9,328✔
896
            _impl::parse_virtual_path(m_root_dir, virt_path); // Throws
9,328✔
897
        REALM_ASSERT(virt_path_components.is_valid);
9,328✔
898

3,430✔
899
        _impl::make_dirs(m_root_dir, virt_path); // Throws
9,328✔
900
        m_realm_names.insert(virt_path);         // Throws
9,328✔
901
        {
9,328✔
902
            bool disable_sync_to_disk = m_config.disable_sync_to_disk;
9,328✔
903
            file.reset(new ServerFile(*this, m_file_access_cache, virt_path, virt_path_components.real_realm_path,
9,328✔
904
                                      disable_sync_to_disk)); // Throws
9,328✔
905
        }
9,328✔
906

3,430✔
907
        file->initialize();
9,328✔
908
        m_files[virt_path] = file; // Throws
9,328✔
909
        file->activate();          // Throws
9,328✔
910
        return file;
9,328✔
911
    }
9,328✔
912

913
    std::unique_ptr<ServerHistory> make_history_for_path()
914
    {
×
915
        return std::make_unique<ServerHistory>(*this);
×
916
    }
×
917

918
    util::bind_ptr<ServerFile> get_file(const std::string& virt_path) noexcept
919
    {
54,832✔
920
        auto i = m_files.find(virt_path);
54,832✔
921
        if (REALM_LIKELY(i != m_files.end()))
54,832✔
922
            return i->second;
48,938✔
923
        return {};
9,316✔
924
    }
9,316✔
925

926
    // Returns the number of seconds since the Epoch of
927
    // std::chrono::system_clock.
928
    std::chrono::system_clock::time_point token_expiration_clock_now() const noexcept
929
    {
×
930
        if (REALM_UNLIKELY(m_config.token_expiration_clock))
×
931
            return m_config.token_expiration_clock->now();
×
932
        return std::chrono::system_clock::now();
×
933
    }
×
934

935
    void set_connection_reaper_timeout(milliseconds_type);
936

937
    void close_connections();
938
    bool map_virtual_to_real_path(const std::string& virt_path, std::string& real_path);
939

940
    void recognize_external_change(const std::string& virt_path);
941

942
    void stop_sync_and_wait_for_backup_completion(util::UniqueFunction<void(bool did_backup)> completion_handler,
943
                                                  milliseconds_type timeout);
944

945
    // Server global outputbuffers that can be reused.
946
    // The server is single threaded, so there are no
947
    // synchronization issues.
948
    // output_buffers_count is equal to the
949
    // maximum number of buffers needed at any point.
950
    static constexpr int output_buffers_count = 1;
951
    OutputBuffer output_buffers[output_buffers_count];
952

953
    bool is_load_balancing_allowed() const
954
    {
×
955
        return m_allow_load_balancing;
×
956
    }
×
957

958
    // inc_byte_size_for_pending_downstream_changesets() must be called by
959
    // ServerFile objects when changesets from downstream clients have been
960
    // received.
961
    //
962
    // dec_byte_size_for_pending_downstream_changesets() must be called by
963
    // ServerFile objects when changesets from downstream clients have been
964
    // processed or discarded.
965
    //
966
    // ServerImpl uses this information to keep a running tally (metric
967
    // `upload.pending.bytes`) of the total byte size of pending changesets from
968
    // downstream clients.
969
    //
970
    // These functions must be called on the network thread.
971
    void inc_byte_size_for_pending_downstream_changesets(std::size_t byte_size);
972
    void dec_byte_size_for_pending_downstream_changesets(std::size_t byte_size);
973

974
    // Overriding member functions in _impl::ServerHistory::Context
975
    std::mt19937_64& server_history_get_random() noexcept override final;
976

977
private:
978
    Server::Config m_config;
979
    network::Service m_service;
980
    std::mt19937_64 m_random;
981
    const std::size_t m_max_upload_backlog;
982
    const std::string m_root_dir;
983
    const AccessControl m_access_control;
984
    const ProtocolVersionRange m_protocol_version_range;
985

986
    // The reserved files will be closed in situations where the server
987
    // runs out of file descriptors.
988
    std::unique_ptr<File> m_reserved_files[5];
989

990
    // The set of all Realm files known to this server, represented by their
991
    // virtual path.
992
    //
993
    // INVARIANT: If a Realm file is in the servers directory (i.e., it would be
994
    // reported by an invocation of _impl::get_realm_names()), then the
995
    // corresponding virtual path is in `m_realm_names`, assuming no external
996
    // file-system level intervention.
997
    std::set<std::string> m_realm_names;
998

999
    std::unique_ptr<network::ssl::Context> m_ssl_context;
1000
    ServerFileAccessCache m_file_access_cache;
1001
    Worker m_worker;
1002
    std::map<std::string, util::bind_ptr<ServerFile>> m_files; // Key is virtual path
1003
    network::Acceptor m_acceptor;
1004
    std::int_fast64_t m_next_conn_id = 0;
1005
    std::unique_ptr<HTTPConnection> m_next_http_conn;
1006
    network::Endpoint m_next_http_conn_endpoint;
1007
    std::map<std::int_fast64_t, std::unique_ptr<HTTPConnection>> m_http_connections;
1008
    std::map<std::int_fast64_t, std::unique_ptr<SyncConnection>> m_sync_connections;
1009
    ServerProtocol m_server_protocol;
1010
    compression::CompressMemoryArena m_compress_memory_arena;
1011
    MiscBuffers m_misc_buffers;
1012
    int_fast64_t m_current_server_session_ident;
1013
    Optional<network::DeadlineTimer> m_connection_reaper_timer;
1014
    bool m_allow_load_balancing = false;
1015

1016
    util::Mutex m_mutex;
1017

1018
    bool m_stopped = false; // Protected by `m_mutex`
1019

1020
    // m_sync_stopped is used by stop_sync_and_wait_for_backup_completion().
1021
    // When m_sync_stopped is true, the server does not perform any sync.
1022
    bool m_sync_stopped = false;
1023

1024
    std::atomic<bool> m_running{false}; // Debugging facility
1025

1026
    std::size_t m_pending_changesets_from_downstream_byte_size = 0;
1027

1028
    util::CondVar m_wait_or_service_stopped_cond; // Protected by `m_mutex`
1029

1030
    util::ScratchMemory m_scratch_memory;
1031

1032
    void listen();
1033
    void initiate_accept();
1034
    void handle_accept(std::error_code);
1035

1036
    void reap_connections();
1037
    void initiate_connection_reaper_timer(milliseconds_type timeout);
1038
    void do_close_connections();
1039

1040
    static std::size_t determine_max_upload_backlog(Server::Config& config) noexcept
1041
    {
11,732✔
1042
        if (config.max_upload_backlog == 0)
11,732✔
1043
            return 4294967295; // 4GiB - 1 (largest allowable number on a 32-bit platform)
11,732✔
1044
        return config.max_upload_backlog;
×
1045
    }
×
1046

1047
    static ProtocolVersionRange determine_protocol_version_range(Server::Config& config)
1048
    {
11,732✔
1049
        const int actual_min = ServerImplBase::get_oldest_supported_protocol_version();
11,732✔
1050
        const int actual_max = get_current_protocol_version();
11,732✔
1051
        static_assert(actual_min <= actual_max, "");
11,732✔
1052
        int min = actual_min;
11,732✔
1053
        int max = actual_max;
11,732✔
1054
        if (config.max_protocol_version != 0 && config.max_protocol_version < max) {
11,732!
1055
            if (config.max_protocol_version < min)
×
1056
                throw Server::NoSupportedProtocolVersions();
×
1057
            max = config.max_protocol_version;
×
1058
        }
×
1059
        return {min, max};
11,732✔
1060
    }
11,732✔
1061

1062
    void do_recognize_external_change(const std::string& virt_path);
1063

1064
    void do_stop_sync_and_wait_for_backup_completion(util::UniqueFunction<void(bool did_complete)> completion_handler,
1065
                                                     milliseconds_type timeout);
1066
};
1067

1068
// ============================ SyncConnection ============================
1069

1070
class SyncConnection : public websocket::Config {
1071
public:
1072
    const std::shared_ptr<util::Logger> logger_ptr;
1073
    util::Logger& logger;
1074

1075
    // Clients with sync protocol version 8 or greater support pbs->flx migration
1076
    static constexpr int PBS_FLX_MIGRATION_PROTOCOL_VERSION = 8;
1077
    // Clients with sync protocol version less than 10 do not support log messages
1078
    static constexpr int SERVER_LOG_PROTOCOL_VERSION = 10;
1079

1080
    SyncConnection(ServerImpl& serv, std::int_fast64_t id, std::unique_ptr<network::Socket>&& socket,
1081
                   std::unique_ptr<network::ssl::Stream>&& ssl_stream,
1082
                   std::unique_ptr<network::ReadAheadBuffer>&& read_ahead_buffer, int client_protocol_version,
1083
                   std::string client_user_agent, std::string remote_endpoint, std::string appservices_request_id)
1084
        : logger_ptr{std::make_shared<util::PrefixLogger>(util::LogCategory::server, make_logger_prefix(id),
1085
                                                          serv.logger_ptr)} // Throws
1086
        , logger{*logger_ptr}
1087
        , m_server{serv}
1088
        , m_id{id}
1089
        , m_socket{std::move(socket)}
1090
        , m_ssl_stream{std::move(ssl_stream)}
1091
        , m_read_ahead_buffer{std::move(read_ahead_buffer)}
1092
        , m_websocket{*this}
1093
        , m_client_protocol_version{client_protocol_version}
1094
        , m_client_user_agent{std::move(client_user_agent)}
1095
        , m_remote_endpoint{std::move(remote_endpoint)}
1096
        , m_appservices_request_id{std::move(appservices_request_id)}
1097
    {
16,222✔
1098
        // Make the output buffer stream throw std::bad_alloc if it fails to
7,592✔
1099
        // expand the buffer
7,592✔
1100
        m_output_buffer.exceptions(std::ios_base::badbit | std::ios_base::failbit);
16,222✔
1101

7,592✔
1102
        network::Service& service = m_server.get_service();
16,222✔
1103
        auto handler = [this](Status status) {
840,656✔
1104
            if (!status.is_ok())
840,656✔
1105
                return;
×
1106
            if (!m_is_sending)
840,656✔
1107
                send_next_message(); // Throws
366,988✔
1108
        };
840,656✔
1109
        m_send_trigger = std::make_unique<Trigger<network::Service>>(&service, std::move(handler)); // Throws
16,222✔
1110
    }
16,222✔
1111

1112
    ~SyncConnection() noexcept;
1113

1114
    ServerImpl& get_server() noexcept
1115
    {
992,206✔
1116
        return m_server;
992,206✔
1117
    }
992,206✔
1118

1119
    ServerProtocol& get_server_protocol() noexcept
1120
    {
1,196,598✔
1121
        return m_server.get_server_protocol();
1,196,598✔
1122
    }
1,196,598✔
1123

1124
    int get_client_protocol_version()
1125
    {
900,060✔
1126
        return m_client_protocol_version;
900,060✔
1127
    }
900,060✔
1128

1129
    const std::string& get_client_user_agent() const noexcept
1130
    {
54,834✔
1131
        return m_client_user_agent;
54,834✔
1132
    }
54,834✔
1133

1134
    const std::string& get_remote_endpoint() const noexcept
1135
    {
54,834✔
1136
        return m_remote_endpoint;
54,834✔
1137
    }
54,834✔
1138

1139
    const std::shared_ptr<util::Logger>& websocket_get_logger() noexcept final
1140
    {
16,220✔
1141
        return logger_ptr;
16,220✔
1142
    }
16,220✔
1143

1144
    std::mt19937_64& websocket_get_random() noexcept final override
1145
    {
562,778✔
1146
        return m_server.get_random();
562,778✔
1147
    }
562,778✔
1148

1149
    bool websocket_binary_message_received(const char* data, size_t size) final override
1150
    {
637,830✔
1151
        using sf = _impl::SimulatedFailure;
637,830✔
1152
        if (sf::check_trigger(sf::sync_server__read_head)) {
637,830✔
1153
            // Suicide
1,900✔
1154
            read_error(sf::sync_server__read_head);
3,850✔
1155
            return false;
3,850✔
1156
        }
3,850✔
1157
        // After a connection level error has occurred, all incoming messages
277,348✔
1158
        // will be ignored. By continuing to read until end of input, the server
277,348✔
1159
        // is able to know when the client closes the connection, which in
277,348✔
1160
        // general means that is has received the ERROR message.
277,348✔
1161
        if (REALM_LIKELY(!m_is_closing)) {
633,980✔
1162
            m_last_activity_at = steady_clock_now();
633,804✔
1163
            handle_message_received(data, size);
633,804✔
1164
        }
633,804✔
1165
        return true;
633,980✔
1166
    }
633,980✔
1167

1168
    bool websocket_ping_message_received(const char* data, size_t size) final override
1169
    {
×
1170
        if (REALM_LIKELY(!m_is_closing)) {
×
1171
            m_last_activity_at = steady_clock_now();
×
1172
            handle_ping_received(data, size);
×
1173
        }
×
1174
        return true;
×
1175
    }
×
1176

1177
    void async_write(const char* data, size_t size, websocket::WriteCompletionHandler handler) final override
1178
    {
562,786✔
1179
        if (m_ssl_stream) {
562,786✔
1180
            m_ssl_stream->async_write(data, size, std::move(handler)); // Throws
594✔
1181
        }
594✔
1182
        else {
562,192✔
1183
            m_socket->async_write(data, size, std::move(handler)); // Throws
562,192✔
1184
        }
562,192✔
1185
    }
562,786✔
1186

1187
    void async_read(char* buffer, size_t size, websocket::ReadCompletionHandler handler) final override
1188
    {
1,925,688✔
1189
        if (m_ssl_stream) {
1,925,688✔
1190
            m_ssl_stream->async_read(buffer, size, *m_read_ahead_buffer, std::move(handler)); // Throws
1,474✔
1191
        }
1,474✔
1192
        else {
1,924,214✔
1193
            m_socket->async_read(buffer, size, *m_read_ahead_buffer, std::move(handler)); // Throws
1,924,214✔
1194
        }
1,924,214✔
1195
    }
1,925,688✔
1196

1197
    void async_read_until(char* buffer, size_t size, char delim,
1198
                          websocket::ReadCompletionHandler handler) final override
1199
    {
×
1200
        if (m_ssl_stream) {
×
1201
            m_ssl_stream->async_read_until(buffer, size, delim, *m_read_ahead_buffer,
×
1202
                                           std::move(handler)); // Throws
×
1203
        }
×
1204
        else {
×
1205
            m_socket->async_read_until(buffer, size, delim, *m_read_ahead_buffer,
×
1206
                                       std::move(handler)); // Throws
×
1207
        }
×
1208
    }
×
1209

1210
    void websocket_read_error_handler(std::error_code ec) final override
1211
    {
5,308✔
1212
        read_error(ec);
5,308✔
1213
    }
5,308✔
1214

1215
    void websocket_write_error_handler(std::error_code ec) final override
1216
    {
×
1217
        write_error(ec);
×
1218
    }
×
1219

1220
    void websocket_handshake_error_handler(std::error_code ec, const HTTPHeaders*,
1221
                                           const std::string_view*) final override
1222
    {
1223
        // WebSocket class has already logged a message for this error
1224
        close_due_to_error(ec); // Throws
×
1225
    }
1226

1227
    void websocket_protocol_error_handler(std::error_code ec) final override
1228
    {
×
1229
        logger.error("WebSocket protocol error (%1): %2", ec, ec.message()); // Throws
×
1230
        close_due_to_error(ec);                                              // Throws
×
1231
    }
1232

1233
    void websocket_handshake_completion_handler(const HTTPHeaders&) final override
1234
    {
1235
        // This is not called since we handle HTTP request in handle_request_for_sync()
1236
        REALM_TERMINATE("websocket_handshake_completion_handler should not have been called");
1237
    }
1238

1239
    int_fast64_t get_id() const noexcept
1240
    {
×
1241
        return m_id;
×
1242
    }
1243

1244
    network::Socket& get_socket() noexcept
1245
    {
×
1246
        return *m_socket;
×
1247
    }
1248

1249
    void initiate();
1250

1251
    // Commits suicide
1252
    template <class... Params>
1253
    void terminate(Logger::Level, const char* log_message, Params... log_params);
1254

1255
    // Commits suicide
1256
    void terminate_if_dead(SteadyTimePoint now);
1257

1258
    void enlist_to_send(Session*) noexcept;
1259

1260
    // Sessions should get the output_buffer and insert a message, after which
1261
    // they call initiate_write_output_buffer().
1262
    OutputBuffer& get_output_buffer()
35,442✔
1263
    {
562,792✔
1264
        m_output_buffer.reset();
562,792✔
1265
        return m_output_buffer;
562,792✔
1266
    }
527,350✔
1267

1268
    // More advanced memory strategies can be implemented if needed.
35,362✔
1269
    void release_output_buffer() {}
525,824✔
1270

1271
    // When this function is called, the connection will initiate a write with
1272
    // its output_buffer. Sessions use this method.
1273
    void initiate_write_output_buffer();
1274

1275
    void initiate_pong_output_buffer();
1276

1277
    void handle_protocol_error(Status status);
1278

1279
    void receive_bind_message(session_ident_type, std::string path, std::string signed_user_token,
1280
                              bool need_client_file_ident, bool is_subserver);
1281

1282
    void receive_ident_message(session_ident_type, file_ident_type client_file_ident,
1283
                               salt_type client_file_ident_salt, version_type scan_server_version,
1284
                               version_type scan_client_version, version_type latest_server_version,
1285
                               salt_type latest_server_version_salt);
1286

1287
    void receive_upload_message(session_ident_type, version_type progress_client_version,
1288
                                version_type progress_server_version, version_type locked_server_version,
1289
                                const UploadChangesets&);
1290

1291
    void receive_mark_message(session_ident_type, request_ident_type);
1292

1293
    void receive_unbind_message(session_ident_type);
1294

1295
    void receive_ping(milliseconds_type timestamp, milliseconds_type rtt);
1296

1297
    void receive_error_message(session_ident_type, int error_code, std::string_view error_body);
1298

1299
    void protocol_error(ProtocolError, Session* = nullptr);
1300

1301
    void initiate_soft_close();
1302

1303
    void discard_session(session_ident_type) noexcept;
1304

1305
    void send_log_message(util::Logger::Level level, const std::string&& message, session_ident_type sess_ident = 0,
1306
                          std::optional<std::string> co_id = std::nullopt);
1307

1308
private:
1309
    ServerImpl& m_server;
1310
    const int_fast64_t m_id;
1311
    std::unique_ptr<network::Socket> m_socket;
1312
    std::unique_ptr<network::ssl::Stream> m_ssl_stream;
1313
    std::unique_ptr<network::ReadAheadBuffer> m_read_ahead_buffer;
1314

1315
    websocket::Socket m_websocket;
1316
    std::unique_ptr<char[]> m_input_body_buffer;
1317
    OutputBuffer m_output_buffer;
1318
    std::map<session_ident_type, std::unique_ptr<Session>> m_sessions;
1319

1320
    // The protocol version in use by the connected client.
1321
    const int m_client_protocol_version;
1322

1323
    // The user agent description passed by the client.
1324
    const std::string m_client_user_agent;
1325

1326
    const std::string m_remote_endpoint;
1327

1328
    const std::string m_appservices_request_id;
1329

1330
    // A queue of sessions that have enlisted for an opportunity to send a
1331
    // message. Sessions will be served in the order that they enlist. A session
1332
    // can only occur once in this queue (linked list). If the queue is not
1333
    // empty, and no message is currently being written to the socket, the first
1334
    // session is taken out of the queue, and then granted an opportunity to
1335
    // send a message.
1336
    //
1337
    // Sessions will never be destroyed while in this queue. This is ensured
1338
    // because the connection owns the sessions that are associated with it, and
1339
    // the connection only removes a session from m_sessions at points in time
1340
    // where that session is guaranteed to not be in m_sessions_enlisted_to_send
1341
    // (Connection::send_next_message() and Connection::~Connection()).
1342
    SessionQueue m_sessions_enlisted_to_send;
1343

1344
    Session* m_receiving_session = nullptr;
1345

1346
    bool m_is_sending = false;
1347
    bool m_is_closing = false;
1348

1349
    bool m_send_pong = false;
1350
    bool m_sending_pong = false;
1351

1352
    std::unique_ptr<Trigger<network::Service>> m_send_trigger;
1353

1354
    milliseconds_type m_last_ping_timestamp = 0;
1355

1356
    // If `m_is_closing` is true, this is the time at which `m_is_closing` was
1357
    // set to true (initiation of soft close). Otherwise, if no messages have
1358
    // been received from the client, this is the time at which the connection
1359
    // object was initiated (completion of WebSocket handshake). Otherwise this
1360
    // is the time at which the last message was received from the client.
1361
    SteadyTimePoint m_last_activity_at;
1362

1363
    // These are initialized by do_initiate_soft_close().
1364
    //
1365
    // With recent versions of the protocol (when the version is greater than,
1366
    // or equal to 23), `m_error_session_ident` is always zero.
1367
    ProtocolError m_error_code = {};
1368
    session_ident_type m_error_session_ident = 0;
1369

1370
    struct LogMessage {
1371
        session_ident_type sess_ident;
1372
        util::Logger::Level level;
1373
        std::string message;
1374
        std::optional<std::string> co_id;
1375
    };
1376

1377
    std::mutex m_log_mutex;
1378
    std::queue<LogMessage> m_log_messages;
1379

1380
    static std::string make_logger_prefix(int_fast64_t id)
940✔
1381
    {
16,220✔
1382
        std::ostringstream out;
16,220✔
1383
        out.imbue(std::locale::classic());
16,220✔
1384
        out << "Sync Connection[" << id << "]: "; // Throws
16,220✔
1385
        return out.str();                         // Throws
16,220✔
1386
    }
15,280✔
1387

1388
    // The return value of handle_message_received() designates whether
1389
    // message processing should continue. If the connection object is
1390
    // destroyed during execution of handle_message_received(), the return
1391
    // value must be false.
1392
    void handle_message_received(const char* data, size_t size);
1393

1394
    void handle_ping_received(const char* data, size_t size);
1395

1396
    void send_next_message();
1397
    void send_pong(milliseconds_type timestamp);
1398
    void send_log_message(const LogMessage& log_msg);
1399

1400
    void handle_write_output_buffer();
1401
    void handle_pong_output_buffer();
1402

1403
    void initiate_write_error(ProtocolError, session_ident_type);
1404
    void handle_write_error(std::error_code ec);
1405

1406
    void do_initiate_soft_close(ProtocolError, session_ident_type);
1407
    void read_error(std::error_code);
1408
    void write_error(std::error_code);
1409

1410
    void close_due_to_close_by_client(std::error_code);
1411
    void close_due_to_error(std::error_code);
1412

1413
    void terminate_sessions();
1414

1415
    void bad_session_ident(const char* message_type, session_ident_type);
1416
    void message_after_unbind(const char* message_type, session_ident_type);
1417
    void message_before_ident(const char* message_type, session_ident_type);
1418
};
1419

1420

1421
inline void SyncConnection::read_error(std::error_code ec)
466✔
1422
{
9,158✔
1423
    REALM_ASSERT(ec != util::error::operation_aborted);
9,158✔
1424
    if (ec == util::MiscExtErrors::end_of_input || ec == util::error::connection_reset) {
8,692✔
1425
        // Suicide
3,102✔
1426
        close_due_to_close_by_client(ec); // Throws
5,308✔
1427
        return;
5,308✔
1428
    }
5,266✔
1429
    if (ec == util::MiscExtErrors::delim_not_found) {
3,638✔
1430
        logger.error("Input message head delimited not found"); // Throws
×
1431
        protocol_error(ProtocolError::limits_exceeded);         // Throws
×
1432
        return;
×
1433
    }
1434

2,112✔
1435
    logger.error("Reading failed: %1", ec.message()); // Throws
3,638✔
1436

1,900✔
1437
    // Suicide
2,112✔
1438
    close_due_to_error(ec); // Throws
3,850✔
1439
}
3,638✔
1440

1441
inline void SyncConnection::write_error(std::error_code ec)
1442
{
×
1443
    REALM_ASSERT(ec != util::error::operation_aborted);
×
1444
    if (ec == util::error::broken_pipe || ec == util::error::connection_reset) {
×
1445
        // Suicide
1446
        close_due_to_close_by_client(ec); // Throws
×
1447
        return;
×
1448
    }
×
1449
    logger.error("Writing failed: %1", ec.message()); // Throws
1450

1451
    // Suicide
1452
    close_due_to_error(ec); // Throws
×
1453
}
1454

1455

1456
// ============================ HTTPConnection ============================
1457

1458
std::string g_user_agent = "User-Agent";
1459

1460
class HTTPConnection {
1461
public:
1462
    const std::shared_ptr<Logger> logger_ptr;
1463
    util::Logger& logger;
1464

1465
    HTTPConnection(ServerImpl& serv, int_fast64_t id, bool is_ssl)
1466
        : logger_ptr{std::make_shared<PrefixLogger>(util::LogCategory::server, make_logger_prefix(id),
1467
                                                    serv.logger_ptr)} // Throws
1468
        , logger{*logger_ptr}
1469
        , m_server{serv}
1470
        , m_id{id}
1471
        , m_socket{new network::Socket{serv.get_service()}} // Throws
1472
        , m_read_ahead_buffer{new network::ReadAheadBuffer} // Throws
1473
        , m_http_server{*this, logger_ptr}
1,586✔
1474
    {
26,678✔
1475
        // Make the output buffer stream throw std::bad_alloc if it fails to
12,862✔
1476
        // expand the buffer
14,448✔
1477
        m_output_buffer.exceptions(std::ios_base::badbit | std::ios_base::failbit);
26,678✔
1478

14,448✔
1479
        if (is_ssl) {
26,698✔
1480
            using namespace network::ssl;
404✔
1481
            Context& ssl_context = serv.get_ssl_context();
404✔
1482
            m_ssl_stream = std::make_unique<Stream>(*m_socket, ssl_context,
404✔
1483
                                                    Stream::server); // Throws
404✔
1484
        }
1,970✔
1485
    }
26,678✔
1486

1487
    ServerImpl& get_server() noexcept
1488
    {
×
1489
        return m_server;
×
1490
    }
1491

1492
    int_fast64_t get_id() const noexcept
960✔
1493
    {
16,536✔
1494
        return m_id;
16,536✔
1495
    }
15,576✔
1496

1497
    network::Socket& get_socket() noexcept
2,326✔
1498
    {
42,076✔
1499
        return *m_socket;
42,076✔
1500
    }
39,750✔
1501

1502
    template <class H>
1503
    void async_write(const char* data, size_t size, H handler)
950✔
1504
    {
16,390✔
1505
        if (m_ssl_stream) {
15,446✔
1506
            m_ssl_stream->async_write(data, size, std::move(handler)); // Throws
118✔
1507
        }
1,056✔
1508
        else {
16,272✔
1509
            m_socket->async_write(data, size, std::move(handler)); // Throws
16,272✔
1510
        }
16,278✔
1511
    }
15,440✔
1512

1513
    template <class H>
1514
    void async_read(char* buffer, size_t size, H handler)
4✔
1515
    {
68!
1516
        if (m_ssl_stream) {
64!
1517
            m_ssl_stream->async_read(buffer, size, *m_read_ahead_buffer,
×
1518
                                     std::move(handler)); // Throws
×
1519
        }
4✔
1520
        else {
68✔
1521
            m_socket->async_read(buffer, size, *m_read_ahead_buffer,
68✔
1522
                                 std::move(handler)); // Throws
68✔
1523
        }
68✔
1524
    }
64✔
1525

1526
    template <class H>
1527
    void async_read_until(char* buffer, size_t size, char delim, H handler)
8,494✔
1528
    {
146,556!
1529
        if (m_ssl_stream) {
138,116!
1530
            m_ssl_stream->async_read_until(buffer, size, delim, *m_read_ahead_buffer,
1,062✔
1531
                                           std::move(handler)); // Throws
1,062✔
1532
        }
9,448✔
1533
        else {
145,494✔
1534
            m_socket->async_read_until(buffer, size, delim, *m_read_ahead_buffer,
145,494✔
1535
                                       std::move(handler)); // Throws
145,494✔
1536
        }
145,548✔
1537
    }
138,062✔
1538

1539
    void initiate(std::string remote_endpoint)
960✔
1540
    {
16,534✔
1541
        m_last_activity_at = steady_clock_now();
16,534✔
1542
        m_remote_endpoint = std::move(remote_endpoint);
15,574✔
1543

8,686✔
1544
        logger.detail("Connection from %1", m_remote_endpoint); // Throws
15,574✔
1545

8,686✔
1546
        if (m_ssl_stream) {
15,584✔
1547
            initiate_ssl_handshake(); // Throws
202✔
1548
        }
1,142✔
1549
        else {
16,332✔
1550
            initiate_http(); // Throws
16,332✔
1551
        }
16,342✔
1552
    }
15,574✔
1553

1554
    void respond_200_ok()
1555
    {
×
1556
        handle_text_response(HTTPStatus::Ok, "OK"); // Throws
×
1557
    }
1558

1559
    void respond_404_not_found()
1560
    {
×
1561
        handle_text_response(HTTPStatus::NotFound, "Not found"); // Throws
×
1562
    }
1563

1564
    void respond_503_service_unavailable()
1565
    {
×
1566
        handle_text_response(HTTPStatus::ServiceUnavailable, "Service unavailable"); // Throws
×
1567
    }
1568

1569
    // Commits suicide
1570
    template <class... Params>
1571
    void terminate(Logger::Level log_level, const char* log_message, Params... log_params)
20✔
1572
    {
310✔
1573
        logger.log(log_level, log_message, log_params...); // Throws
310✔
1574
        m_ssl_stream.reset();
310✔
1575
        m_socket.reset();
310✔
1576
        m_server.remove_http_connection(m_id); // Suicide
310✔
1577
    }
290✔
1578

1579
    // Commits suicide
1580
    void terminate_if_dead(SteadyTimePoint now)
1581
    {
8✔
1582
        milliseconds_type time = steady_duration(m_last_activity_at, now);
8✔
1583
        const Server::Config& config = m_server.get_config();
8!
1584
        if (m_is_sending) {
8✔
1585
            if (time >= config.http_response_timeout) {
6✔
1586
                // Suicide
1587
                terminate(Logger::Level::detail,
×
1588
                          "HTTP connection closed (request timeout)"); // Throws
×
UNCOV
1589
            }
×
1590
        }
6✔
1591
        else {
2!
1592
            if (time >= config.http_request_timeout) {
2✔
1593
                // Suicide
1594
                terminate(Logger::Level::detail,
×
1595
                          "HTTP connection closed (response timeout)"); // Throws
×
UNCOV
1596
            }
×
1597
        }
2✔
1598
    }
8✔
1599

1600
    std::string get_appservices_request_id() const
950✔
1601
    {
16,386✔
1602
        return m_appservices_request_id.to_string();
16,386✔
1603
    }
15,436✔
1604

1605
private:
1606
    ServerImpl& m_server;
1607
    const int_fast64_t m_id;
1608
    const ObjectId m_appservices_request_id = ObjectId::gen();
1609
    std::unique_ptr<network::Socket> m_socket;
1610
    std::unique_ptr<network::ssl::Stream> m_ssl_stream;
1611
    std::unique_ptr<network::ReadAheadBuffer> m_read_ahead_buffer;
1612
    HTTPServer<HTTPConnection> m_http_server;
1613
    OutputBuffer m_output_buffer;
1614
    bool m_is_sending = false;
1615
    SteadyTimePoint m_last_activity_at;
1616
    std::string m_remote_endpoint;
1617
    int m_negotiated_protocol_version = 0;
1618

1619
    void initiate_ssl_handshake()
10✔
1620
    {
202✔
1621
        auto handler = [this](std::error_code ec) {
198✔
1622
            if (ec != util::error::operation_aborted)
198✔
1623
                handle_ssl_handshake(ec); // Throws
198✔
1624
        };
198✔
1625
        m_ssl_stream->async_handshake(std::move(handler)); // Throws
202✔
1626
    }
192✔
1627

1628
    void handle_ssl_handshake(std::error_code ec)
10✔
1629
    {
198✔
1630
        if (ec) {
192✔
1631
            logger.error("SSL handshake error (%1): %2", ec, ec.message()); // Throws
80✔
1632
            close_due_to_error(ec);                                         // Throws
80✔
1633
            return;
80✔
1634
        }
82✔
1635
        initiate_http(); // Throws
118✔
1636
    }
112✔
1637

1638
    void initiate_http()
956✔
1639
    {
16,452✔
1640
        logger.debug("Connection initiates HTTP receipt");
15,496✔
1641

8,634✔
1642
        auto handler = [this](HTTPRequest request, std::error_code ec) {
16,452✔
1643
            if (REALM_UNLIKELY(ec == util::error::operation_aborted))
15,496✔
1644
                return;
8,634✔
1645
            if (REALM_UNLIKELY(ec == HTTPParserError::MalformedRequest)) {
15,496✔
1646
                logger.error("Malformed HTTP request");
×
1647
                close_due_to_error(ec); // Throws
×
1648
                return;
×
1649
            }
956✔
1650
            if (REALM_UNLIKELY(ec == HTTPParserError::BadRequest)) {
15,500✔
1651
                logger.error("Bad HTTP request");
68✔
1652
                const char* body = "The HTTP request was corrupted";
68✔
1653
                handle_400_bad_request(body); // Throws
68✔
1654
                return;
68✔
1655
            }
1,016✔
1656
            if (REALM_UNLIKELY(ec)) {
15,438✔
1657
                read_error(ec); // Throws
60✔
1658
                return;
60✔
1659
            }
1,000✔
1660
            handle_http_request(std::move(request)); // Throws
16,324✔
1661
        };
16,334✔
1662
        m_http_server.async_receive_request(std::move(handler)); // Throws
16,452✔
1663
    }
15,496✔
1664

1665
    void handle_http_request(const HTTPRequest& request)
946✔
1666
    {
16,324✔
1667
        StringData path = request.path;
15,378✔
1668

8,586✔
1669
        logger.debug("HTTP request received, request = %1", request);
15,378✔
1670

8,586✔
1671
        m_is_sending = true;
16,324✔
1672
        m_last_activity_at = steady_clock_now();
15,378✔
1673

7,640✔
1674
        // FIXME: When thinking of this function as a switching device, it seem
7,640✔
1675
        // wrong that it requires a `%2F` after `/realm-sync/`. If `%2F` is
7,640✔
1676
        // supposed to be mandatory, then that check ought to be delegated to
7,640✔
1677
        // handle_request_for_sync(), as that will yield a sharper separation of
7,640✔
1678
        // concerns.
8,586✔
1679
        if (path == "/realm-sync" || path.begins_with("/realm-sync?") || path.begins_with("/realm-sync/%2F")) {
16,318✔
1680
            handle_request_for_sync(request); // Throws
16,222✔
1681
        }
15,288✔
1682
        else {
102✔
1683
            handle_404_not_found(request); // Throws
102✔
1684
        }
1,042✔
1685
    }
15,378✔
1686

1687
    void handle_request_for_sync(const HTTPRequest& request)
940✔
1688
    {
16,222✔
1689
        if (m_server.is_sync_stopped()) {
15,282✔
1690
            logger.debug("Attempt to create a sync connection to a server that has been "
×
1691
                         "stopped"); // Throws
×
1692
            handle_503_service_unavailable(request, "The server does not accept sync "
×
1693
                                                    "connections"); // Throws
×
1694
            return;
×
1695
        }
1696

8,532✔
1697
        util::Optional<std::string> sec_websocket_protocol = websocket::read_sec_websocket_protocol(request);
15,282✔
1698

7,592✔
1699
        // Figure out whether there are any protocol versions supported by both
7,592✔
1700
        // the client and the server, and if so, choose the newest one of them.
8,532✔
1701
        MiscBuffers& misc_buffers = m_server.get_misc_buffers();
16,222✔
1702
        using ProtocolVersionRanges = MiscBuffers::ProtocolVersionRanges;
16,222✔
1703
        ProtocolVersionRanges& protocol_version_ranges = misc_buffers.protocol_version_ranges;
16,222✔
1704
        {
16,222✔
1705
            protocol_version_ranges.clear();
16,222✔
1706
            util::MemoryInputStream in;
16,222✔
1707
            in.imbue(std::locale::classic());
16,222✔
1708
            in.unsetf(std::ios_base::skipws);
16,222✔
1709
            std::string_view value;
16,222✔
1710
            if (sec_websocket_protocol)
16,222✔
1711
                value = *sec_websocket_protocol;
16,220✔
1712
            HttpListHeaderValueParser parser{value};
16,222✔
1713
            std::string_view elem;
26,562✔
1714
            while (parser.next(elem)) {
183,374✔
1715
                // FIXME: Use std::string_view::begins_with() in C++20.
93,840✔
1716
                const StringData protocol{elem};
178,418✔
1717
                std::string_view prefix;
178,418✔
1718
                if (protocol.begins_with(get_pbs_websocket_protocol_prefix()))
178,418✔
1719
                    prefix = get_pbs_websocket_protocol_prefix();
168,082!
1720
                else if (protocol.begins_with(get_old_pbs_websocket_protocol_prefix()))
6,442,450,947✔
1721
                    prefix = get_old_pbs_websocket_protocol_prefix();
10,340✔
1722
                if (!prefix.empty()) {
178,428✔
1723
                    auto parse_version = [&](std::string_view str) {
178,426✔
1724
                        in.set_buffer(str.data(), str.data() + str.size());
178,426✔
1725
                        int version = 0;
178,426✔
1726
                        in >> version;
178,426✔
1727
                        if (REALM_LIKELY(in && in.eof() && version >= 0))
178,426✔
1728
                            return version;
168,094✔
1729
                        return -1;
8,589,934,596✔
1730
                    };
8,589,944,936✔
1731
                    int min, max;
178,418✔
1732
                    std::string_view range = elem.substr(prefix.size());
178,418✔
1733
                    auto i = range.find('-');
178,418✔
1734
                    if (i != std::string_view::npos) {
168,078✔
1735
                        min = parse_version(range.substr(0, i));
×
1736
                        max = parse_version(range.substr(i + 1));
×
1737
                    }
10,340✔
1738
                    else {
178,418✔
1739
                        min = parse_version(range);
178,418✔
1740
                        max = min;
178,418✔
1741
                    }
178,418✔
1742
                    if (REALM_LIKELY(min >= 0 && max >= 0 && min <= max)) {
178,432✔
1743
                        protocol_version_ranges.emplace_back(min, max); // Throws
178,432✔
1744
                        continue;
178,432✔
1745
                    }
168,092✔
1746
                    logger.error("Protocol version negotiation failed: Client sent malformed "
10,737,418,235✔
1747
                                 "specification of supported protocol versions: '%1'",
10,737,418,235✔
1748
                                 elem); // Throws
10,737,418,235✔
1749
                    handle_400_bad_request("Protocol version negotiation failed: Malformed "
10,737,418,235✔
1750
                                           "specification of supported protocol "
10,737,418,235✔
1751
                                           "versions\n"); // Throws
10,737,418,235✔
1752
                    return;
10,737,418,235✔
1753
                }
10,737,418,235✔
1754
                logger.warn("Unrecognized protocol token in HTTP response header "
6,442,450,951✔
1755
                            "Sec-WebSocket-Protocol: '%1'",
6,442,450,951✔
1756
                            elem); // Throws
6,442,450,951✔
1757
            }
6,442,451,891✔
1758
            if (protocol_version_ranges.empty()) {
15,296✔
1759
                logger.error("Protocol version negotiation failed: Client did not send a "
×
1760
                             "specification of supported protocol versions"); // Throws
×
1761
                handle_400_bad_request("Protocol version negotiation failed: Missing specification "
×
1762
                                       "of supported protocol versions\n"); // Throws
×
1763
                return;
×
1764
            }
940✔
1765
        }
16,236✔
1766
        {
16,236✔
1767
            ProtocolVersionRange server_range = m_server.get_protocol_version_range();
16,236✔
1768
            int server_min = server_range.first;
16,236✔
1769
            int server_max = server_range.second;
16,236✔
1770
            int best_match = 0;
16,236✔
1771
            int overall_client_min = std::numeric_limits<int>::max();
16,236✔
1772
            int overall_client_max = std::numeric_limits<int>::min();
25,636✔
1773
            for (const auto& range : protocol_version_ranges) {
178,398✔
1774
                int client_min = range.first;
178,398✔
1775
                int client_max = range.second;
178,398✔
1776
                if (client_max >= server_min && client_min <= server_max) {
168,058✔
1777
                    // Overlap
93,852✔
1778
                    int version = std::min(client_max, server_max);
178,398✔
1779
                    if (version > best_match) {
168,998✔
1780
                        best_match = version;
16,222✔
1781
                    }
25,622✔
1782
                }
178,398✔
1783
                if (client_min < overall_client_min)
178,398✔
1784
                    overall_client_min = client_min;
178,394✔
1785
                if (client_max > overall_client_max)
168,998✔
1786
                    overall_client_max = client_max;
25,622✔
1787
            }
168,998✔
1788
            Formatter& formatter = misc_buffers.formatter;
16,236✔
1789
            if (REALM_UNLIKELY(best_match == 0)) {
15,296✔
1790
                const char* elaboration = "No version supported by both client and server";
×
1791
                const char* identifier_hint = nullptr;
×
1792
                if (overall_client_max < server_min) {
×
1793
                    // Client is too old
1794
                    elaboration = "Client is too old for server";
×
1795
                    identifier_hint = "CLIENT_TOO_OLD";
×
1796
                }
×
1797
                else if (overall_client_min > server_max) {
×
1798
                    // Client is too new
1799
                    elaboration = "Client is too new for server";
×
1800
                    identifier_hint = "CLIENT_TOO_NEW";
×
1801
                }
×
1802
                auto format_ranges = [&](const auto& list) {
×
1803
                    bool nonfirst = false;
×
1804
                    for (auto range : list) {
×
1805
                        if (nonfirst)
×
1806
                            formatter << ", "; // Throws
×
1807
                        int min = range.first, max = range.second;
×
1808
                        REALM_ASSERT(min <= max);
×
1809
                        formatter << min;
×
1810
                        if (max != min)
×
1811
                            formatter << "-" << max;
×
1812
                        nonfirst = true;
×
1813
                    }
×
1814
                };
×
1815
                using Range = ProtocolVersionRange;
×
1816
                formatter.reset();
×
1817
                format_ranges(protocol_version_ranges); // Throws
×
1818
                logger.error("Protocol version negotiation failed: %1 "
×
1819
                             "(client supports: %2)",
×
1820
                             elaboration, std::string_view(formatter.data(), formatter.size())); // Throws
×
1821
                formatter.reset();
×
1822
                formatter << "Protocol version negotiation failed: "
×
1823
                             ""
×
1824
                          << elaboration << ".\n\n";                                   // Throws
×
1825
                formatter << "Server supports: ";                                      // Throws
×
1826
                format_ranges(std::initializer_list<Range>{{server_min, server_max}}); // Throws
×
1827
                formatter << "\n";                                                     // Throws
×
1828
                formatter << "Client supports: ";                                      // Throws
×
1829
                format_ranges(protocol_version_ranges);                                // Throws
×
1830
                formatter << "\n\n";                                                   // Throws
×
1831
                formatter << "REALM_SYNC_PROTOCOL_MISMATCH";                           // Throws
×
1832
                if (identifier_hint)
×
1833
                    formatter << ":" << identifier_hint;                      // Throws
×
1834
                formatter << "\n";                                            // Throws
×
1835
                handle_400_bad_request({formatter.data(), formatter.size()}); // Throws
×
1836
                return;
×
1837
            }
940✔
1838
            m_negotiated_protocol_version = best_match;
16,236✔
1839
            logger.debug("Received: Sync HTTP request (negotiated_protocol_version=%1)",
16,236✔
1840
                         m_negotiated_protocol_version); // Throws
16,236✔
1841
            formatter.reset();
16,236✔
1842
        }
15,296✔
1843

8,538✔
1844
        std::string sec_websocket_protocol_2;
16,236✔
1845
        {
16,236✔
1846
            std::string_view prefix =
16,236✔
1847
                m_negotiated_protocol_version < SyncConnection::PBS_FLX_MIGRATION_PROTOCOL_VERSION
15,296✔
1848
                    ? get_old_pbs_websocket_protocol_prefix()
8,538✔
1849
                    : get_pbs_websocket_protocol_prefix();
16,236✔
1850
            std::ostringstream out;
16,236✔
1851
            out.imbue(std::locale::classic());
16,236✔
1852
            out << prefix << m_negotiated_protocol_version; // Throws
16,236✔
1853
            sec_websocket_protocol_2 = std::move(out).str();
16,236✔
1854
        }
15,296✔
1855

8,538✔
1856
        std::error_code ec;
16,236✔
1857
        util::Optional<HTTPResponse> response =
16,236✔
1858
            websocket::make_http_response(request, sec_websocket_protocol_2, ec); // Throws
15,296✔
1859

8,538✔
1860
        if (ec) {
15,296✔
1861
            if (ec == websocket::HttpError::bad_request_header_upgrade) {
×
1862
                logger.error("There must be a header of the form 'Upgrade: websocket'");
×
1863
            }
×
1864
            else if (ec == websocket::HttpError::bad_request_header_connection) {
×
1865
                logger.error("There must be a header of the form 'Connection: Upgrade'");
×
1866
            }
×
1867
            else if (ec == websocket::HttpError::bad_request_header_websocket_version) {
×
1868
                logger.error("There must be a header of the form 'Sec-WebSocket-Version: 13'");
×
1869
            }
×
1870
            else if (ec == websocket::HttpError::bad_request_header_websocket_key) {
×
1871
                logger.error("The header Sec-WebSocket-Key is missing");
×
1872
            }
1873

1874
            logger.error("The HTTP request with the error is:\n%1", request);
×
1875
            logger.error("Check the proxy configuration and make sure that the "
×
1876
                         "HTTP request is a valid Websocket request.");
×
1877
            close_due_to_error(ec);
×
1878
            return;
×
1879
        }
940✔
1880
        REALM_ASSERT(response);
16,236✔
1881
        add_common_http_response_headers(*response);
15,296✔
1882

8,538✔
1883
        std::string user_agent;
16,236✔
1884
        {
16,236✔
1885
            auto i = request.headers.find(g_user_agent);
16,236✔
1886
            if (i != request.headers.end())
16,234✔
1887
                user_agent = i->second; // Throws (copy)
16,222✔
1888
        }
15,296✔
1889

8,538✔
1890
        auto handler = [protocol_version = m_negotiated_protocol_version, user_agent = std::move(user_agent),
16,236✔
1891
                        this](std::error_code ec) {
15,284✔
1892
            // If the operation is aborted, the socket object may have been destroyed.
8,532✔
1893
            if (ec != util::error::operation_aborted) {
16,218✔
1894
                if (ec) {
15,278✔
1895
                    write_error(ec);
×
1896
                    return;
×
1897
                }
1898

8,532✔
1899
                std::unique_ptr<SyncConnection> sync_conn = std::make_unique<SyncConnection>(
16,218✔
1900
                    m_server, m_id, std::move(m_socket), std::move(m_ssl_stream), std::move(m_read_ahead_buffer),
16,218✔
1901
                    protocol_version, std::move(user_agent), std::move(m_remote_endpoint),
16,218✔
1902
                    get_appservices_request_id()); // Throws
16,218✔
1903
                SyncConnection& sync_conn_ref = *sync_conn;
16,218✔
1904
                m_server.add_sync_connection(m_id, std::move(sync_conn));
16,218✔
1905
                m_server.remove_http_connection(m_id);
16,218✔
1906
                sync_conn_ref.initiate();
16,218✔
1907
            }
16,218✔
1908
        };
16,218✔
1909
        m_http_server.async_send_response(*response, std::move(handler));
16,236✔
1910
    }
15,296✔
1911

1912
    void handle_text_response(HTTPStatus http_status, std::string_view body)
10✔
1913
    {
170✔
1914
        std::string body_2 = std::string(body); // Throws
160✔
1915

90✔
1916
        HTTPResponse response;
170✔
1917
        response.status = http_status;
170✔
1918
        add_common_http_response_headers(response);
170✔
1919
        response.headers["Connection"] = "close";
160✔
1920

90✔
1921
        if (!body_2.empty()) {
170✔
1922
            response.headers["Content-Length"] = util::to_string(body_2.size());
170✔
1923
            response.body = std::move(body_2);
170✔
1924
        }
160✔
1925

90✔
1926
        auto handler = [this](std::error_code ec) {
170✔
1927
            if (REALM_UNLIKELY(ec == util::error::operation_aborted))
160✔
1928
                return;
90✔
1929
            if (REALM_UNLIKELY(ec)) {
160✔
1930
                write_error(ec);
×
1931
                return;
×
1932
            }
10✔
1933
            terminate(Logger::Level::detail, "HTTP connection closed"); // Throws
170✔
1934
        };
170✔
1935
        m_http_server.async_send_response(response, std::move(handler));
170✔
1936
    }
160✔
1937

1938
    void handle_400_bad_request(std::string_view body)
4✔
1939
    {
68✔
1940
        logger.detail("400 Bad Request");
68✔
1941
        handle_text_response(HTTPStatus::BadRequest, body); // Throws
68✔
1942
    }
64✔
1943

1944
    void handle_404_not_found(const HTTPRequest&)
6✔
1945
    {
102✔
1946
        logger.detail("404 Not Found"); // Throws
102✔
1947
        handle_text_response(HTTPStatus::NotFound,
102✔
1948
                             "Realm sync server\n\nPage not found\n"); // Throws
102✔
1949
    }
96✔
1950

1951
    void handle_503_service_unavailable(const HTTPRequest&, std::string_view message)
1952
    {
×
1953
        logger.debug("503 Service Unavailable");                       // Throws
×
1954
        handle_text_response(HTTPStatus::ServiceUnavailable, message); // Throws
×
1955
    }
1956

1957
    void add_common_http_response_headers(HTTPResponse& response)
950✔
1958
    {
16,390✔
1959
        response.headers["Server"] = "RealmSync/" REALM_VERSION_STRING; // Throws
16,390✔
1960
        if (m_negotiated_protocol_version < SyncConnection::SERVER_LOG_PROTOCOL_VERSION) {
15,440✔
1961
            // This isn't a real X-Appservices-Request-Id, but it should be enough to test with
90✔
1962
            response.headers["X-Appservices-Request-Id"] = get_appservices_request_id();
170✔
1963
        }
1,110✔
1964
    }
15,440✔
1965

1966
    void read_error(std::error_code ec)
6✔
1967
    {
60✔
1968
        REALM_ASSERT(ec != util::error::operation_aborted);
60!
1969
        if (ec == util::MiscExtErrors::end_of_input || ec == util::error::connection_reset) {
54!
1970
            // Suicide
12✔
1971
            close_due_to_close_by_client(ec); // Throws
60✔
1972
            return;
60✔
1973
        }
54!
1974
        if (ec == util::MiscExtErrors::delim_not_found) {
×
1975
            logger.error("Input message head delimited not found"); // Throws
×
1976
            close_due_to_error(ec);                                 // Throws
×
1977
            return;
×
1978
        }
1979

1980
        logger.error("Reading failed: %1", ec.message()); // Throws
1981

1982
        // Suicide
1983
        close_due_to_error(ec); // Throws
×
1984
    }
1985

1986
    void write_error(std::error_code ec)
1987
    {
×
1988
        REALM_ASSERT(ec != util::error::operation_aborted);
×
1989
        if (ec == util::error::broken_pipe || ec == util::error::connection_reset) {
×
1990
            // Suicide
1991
            close_due_to_close_by_client(ec); // Throws
×
1992
            return;
×
1993
        }
×
1994
        logger.error("Writing failed: %1", ec.message()); // Throws
1995

1996
        // Suicide
1997
        close_due_to_error(ec); // Throws
×
1998
    }
1999

2000
    void close_due_to_close_by_client(std::error_code ec)
6✔
2001
    {
60✔
2002
        auto log_level = (ec == util::MiscExtErrors::end_of_input ? Logger::Level::detail : Logger::Level::info);
54✔
2003
        // Suicide
12✔
2004
        terminate(log_level, "HTTP connection closed by client: %1", ec.message()); // Throws
60✔
2005
    }
54✔
2006

2007
    void close_due_to_error(std::error_code ec)
4✔
2008
    {
76✔
2009
        // Suicide
52✔
2010
        terminate(Logger::Level::error, "HTTP connection closed due to error: %1",
80✔
2011
                  ec.message()); // Throws
80✔
2012
    }
76✔
2013

2014
    static std::string make_logger_prefix(int_fast64_t id)
1,586✔
2015
    {
28,264✔
2016
        std::ostringstream out;
28,264✔
2017
        out.imbue(std::locale::classic());
28,264✔
2018
        out << "HTTP Connection[" << id << "]: "; // Throws
28,264✔
2019
        return out.str();                         // Throws
28,264✔
2020
    }
26,678✔
2021
};
2022

2023

2024
class DownloadHistoryEntryHandler : public ServerHistory::HistoryEntryHandler {
2025
public:
2026
    std::size_t num_changesets = 0;
2027
    std::size_t accum_original_size = 0;
2028
    std::size_t accum_compacted_size = 0;
2029

2030
    DownloadHistoryEntryHandler(ServerProtocol& protocol, OutputBuffer& buffer, util::Logger& logger) noexcept
2031
        : m_protocol{protocol}
2032
        , m_buffer{buffer}
2033
        , m_logger{logger}
19,646✔
2034
    {
342,324✔
2035
    }
322,678✔
2036

2037
    void handle(version_type server_version, const HistoryEntry& entry, size_t original_size) override
19,782✔
2038
    {
354,920✔
2039
        version_type client_version = entry.remote_version;
354,920✔
2040
        ServerProtocol::ChangesetInfo info{server_version, client_version, entry, original_size};
354,920✔
2041
        m_protocol.insert_single_changeset_download_message(m_buffer, info, m_logger); // Throws
354,920✔
2042
        ++num_changesets;
354,920✔
2043
        accum_original_size += original_size;
354,920✔
2044
        accum_compacted_size += entry.changeset.size();
354,920✔
2045
    }
335,138✔
2046

2047
private:
2048
    ServerProtocol& m_protocol;
2049
    OutputBuffer& m_buffer;
2050
    util::Logger& m_logger;
2051
};
2052

2053

2054
// ============================ Session ============================
2055

2056
//                        Need cli-   Send     IDENT     UNBIND              ERROR
2057
//   Protocol             ent file    IDENT    message   message   Error     message
2058
//   state                identifier  message  received  received  occurred  sent
2059
// ---------------------------------------------------------------------------------
2060
//   AllocatingIdent      yes         yes      no        no        no        no
2061
//   SendIdent            no          yes      no        no        no        no
2062
//   WaitForIdent         no          no       no        no        no        no
2063
//   WaitForUnbind        maybe       no       yes       no        no        no
2064
//   SendError            maybe       maybe    maybe     no        yes       no
2065
//   WaitForUnbindErr     maybe       maybe    maybe     no        yes       yes
2066
//   SendUnbound          maybe       maybe    maybe     yes       maybe     no
2067
//
2068
//
2069
//   Condition                      Expression
2070
// ----------------------------------------------------------
2071
//   Need client file identifier    need_client_file_ident()
2072
//   Send IDENT message             must_send_ident_message()
2073
//   IDENT message received         ident_message_received()
2074
//   UNBIND message received        unbind_message_received()
2075
//   Error occurred                 error_occurred()
2076
//   ERROR message sent             m_error_message_sent
2077
//
2078
//
2079
//   Protocol
2080
//   state                Will send              Can receive
2081
// -----------------------------------------------------------------------
2082
//   AllocatingIdent      none                   UNBIND
2083
//   SendIdent            IDENT                  UNBIND
2084
//   WaitForIdent         none                   IDENT, UNBIND
2085
//   WaitForUnbind        DOWNLOAD, TRANSACT,    UPLOAD, TRANSACT, MARK,
2086
//                        MARK, ALLOC            ALLOC, UNBIND
2087
//   SendError            ERROR                  any
2088
//   WaitForUnbindErr     none                   any
2089
//   SendUnbound          UNBOUND                none
2090
//
2091
class Session final : private FileIdentReceiver {
2092
public:
2093
    util::PrefixLogger logger;
2094

2095
    Session(SyncConnection& conn, session_ident_type session_ident)
2096
        : logger{util::LogCategory::server, make_logger_prefix(session_ident), conn.logger_ptr} // Throws
2097
        , m_connection{conn}
2098
        , m_session_ident{session_ident}
3,914✔
2099
    {
55,074✔
2100
    }
51,160✔
2101

2102
    ~Session() noexcept
3,914✔
2103
    {
55,078✔
2104
        REALM_ASSERT(!is_enlisted_to_send());
55,078✔
2105
        detach_from_server_file();
55,078✔
2106
    }
51,164✔
2107

2108
    SyncConnection& get_connection() noexcept
19,654✔
2109
    {
342,482✔
2110
        return m_connection;
342,482✔
2111
    }
322,828✔
2112

2113
    const Optional<std::array<char, 64>>& get_encryption_key()
2114
    {
×
2115
        return m_connection.get_server().get_config().encryption_key;
×
2116
    }
2117

2118
    session_ident_type get_session_ident() const noexcept
84✔
2119
    {
1,356✔
2120
        return m_session_ident;
1,356✔
2121
    }
1,272✔
2122

2123
    ServerProtocol& get_server_protocol() noexcept
30,824✔
2124
    {
500,234✔
2125
        return m_connection.get_server_protocol();
500,234✔
2126
    }
469,410✔
2127

2128
    bool need_client_file_ident() const noexcept
5,012✔
2129
    {
67,314✔
2130
        return (m_file_ident_request != 0);
67,314✔
2131
    }
62,302✔
2132

2133
    bool must_send_ident_message() const noexcept
3,592✔
2134
    {
45,272✔
2135
        return m_send_ident_message;
45,272✔
2136
    }
41,680✔
2137

2138
    bool ident_message_received() const noexcept
180,852✔
2139
    {
2,959,856✔
2140
        return m_client_file_ident != 0;
2,959,856✔
2141
    }
2,779,004✔
2142

2143
    bool unbind_message_received() const noexcept
185,176✔
2144
    {
3,005,218✔
2145
        return m_unbind_message_received;
3,005,218✔
2146
    }
2,820,042✔
2147

2148
    bool error_occurred() const noexcept
177,106✔
2149
    {
2,907,526✔
2150
        return int(m_error_code) != 0;
2,907,526✔
2151
    }
2,730,420✔
2152

2153
    bool relayed_alloc_request_in_progress() const noexcept
2154
    {
×
2155
        return (need_client_file_ident() || m_allocated_file_ident.ident != 0);
×
2156
    }
2157

2158
    // Returns the file identifier (always a nonzero value) of the client side
2159
    // file if ident_message_received() returns true. Otherwise it returns zero.
2160
    file_ident_type get_client_file_ident() const noexcept
2161
    {
×
2162
        return m_client_file_ident;
×
2163
    }
2164

2165
    void initiate()
3,914✔
2166
    {
55,076✔
2167
        logger.detail("Session initiated", m_session_ident); // Throws
55,076✔
2168
    }
51,162✔
2169

2170
    void terminate()
3,392✔
2171
    {
46,934✔
2172
        logger.detail("Session terminated", m_session_ident); // Throws
46,934✔
2173
    }
43,542✔
2174

2175
    // Initiate the deactivation process, if it has not been initiated already
2176
    // by the client.
2177
    //
2178
    // IMPORTANT: This function must not be called with protocol versions
2179
    // earlier than 23.
2180
    //
2181
    // The deactivation process will eventually lead to termination of the
2182
    // session.
2183
    //
2184
    // The session will detach itself from the server file when the deactivation
2185
    // process is initiated, regardless of whether it is initiated by the
2186
    // client, or by calling this function.
2187
    void initiate_deactivation(ProtocolError error_code)
42✔
2188
    {
678✔
2189
        REALM_ASSERT(is_session_level_error(error_code));
678✔
2190
        REALM_ASSERT(!error_occurred()); // Must only be called once
636✔
2191

310✔
2192
        // If the UNBIND message has been received, then the client has
310✔
2193
        // initiated the deactivation process already.
352✔
2194
        if (REALM_LIKELY(!unbind_message_received())) {
678✔
2195
            detach_from_server_file();
678✔
2196
            m_error_code = error_code;
636✔
2197
            // Protocol state is now SendError
352✔
2198
            ensure_enlisted_to_send();
678✔
2199
            return;
678✔
2200
        }
636✔
2201
        // Protocol state was SendUnbound, and remains unchanged
352✔
2202
    }
636✔
2203

2204
    bool is_enlisted_to_send() const noexcept
140,564✔
2205
    {
2,340,926✔
2206
        return m_next != nullptr;
2,340,926✔
2207
    }
2,200,362✔
2208

2209
    void ensure_enlisted_to_send() noexcept
27,300✔
2210
    {
456,084✔
2211
        if (!is_enlisted_to_send())
454,264✔
2212
            enlist_to_send();
438,572✔
2213
    }
428,784✔
2214

2215
    void enlist_to_send() noexcept
56,442✔
2216
    {
937,808✔
2217
        m_connection.enlist_to_send(this);
937,808✔
2218
    }
881,366✔
2219

2220
    // Overriding memeber function in FileIdentReceiver
2221
    void receive_file_ident(SaltedFileIdent file_ident) override final
710✔
2222
    {
10,312✔
2223
        // Protocol state must be AllocatingIdent or WaitForUnbind
5,260✔
2224
        if (!ident_message_received()) {
11,022✔
2225
            REALM_ASSERT(need_client_file_ident());
11,022✔
2226
            REALM_ASSERT(m_send_ident_message);
11,022✔
2227
        }
10,312✔
2228
        else {
×
2229
            REALM_ASSERT(!m_send_ident_message);
×
2230
        }
710✔
2231
        REALM_ASSERT(!unbind_message_received());
11,022✔
2232
        REALM_ASSERT(!error_occurred());
11,022✔
2233
        REALM_ASSERT(!m_error_message_sent);
10,312✔
2234

5,260✔
2235
        m_file_ident_request = 0;
11,022✔
2236
        m_allocated_file_ident = file_ident;
10,312✔
2237

4,550✔
2238
        // If the protocol state was AllocatingIdent, it is now SendIdent,
4,550✔
2239
        // otherwise it continues to be WaitForUnbind.
4,550✔
2240

5,260✔
2241
        logger.debug("Acquired outbound salted file identifier (%1, %2)", file_ident.ident,
11,022✔
2242
                     file_ident.salt); // Throws
10,312✔
2243

5,260✔
2244
        ensure_enlisted_to_send();
11,022✔
2245
    }
10,312✔
2246

2247
    // Called by the associated connection object when this session is granted
2248
    // an opportunity to initiate the sending of a message.
2249
    //
2250
    // This function may lead to the destruction of the session object
2251
    // (suicide).
2252
    void send_message()
56,358✔
2253
    {
936,292✔
2254
        if (REALM_LIKELY(!unbind_message_received())) {
933,612✔
2255
            if (REALM_LIKELY(!error_occurred())) {
903,800✔
2256
                if (REALM_LIKELY(ident_message_received())) {
849,534✔
2257
                    // State is WaitForUnbind.
487,504✔
2258
                    bool relayed_alloc = (m_allocated_file_ident.ident != 0);
892,140✔
2259
                    if (REALM_LIKELY(!relayed_alloc)) {
839,220✔
2260
                        // Send DOWNLOAD or MARK.
487,506✔
2261
                        continue_history_scan(); // Throws
839,218✔
2262
                        // Session object may have been
434,584✔
2263
                        // destroyed at this point (suicide)
487,506✔
2264
                        return;
892,140✔
2265
                    }
2,148,322,865✔
2266
                    send_alloc_message(); // Throws
4,294,967,296✔
2267
                    return;
4,294,967,296✔
2268
                }
2,147,483,649✔
2269
                // State is SendIdent
5,260✔
2270
                send_ident_message(); // Throws
11,028✔
2271
                return;
11,028✔
2272
            }
10,316✔
2273
            // State is SendError
356✔
2274
            send_error_message(); // Throws
680✔
2275
            return;
680✔
2276
        }
634✔
2277
        // State is SendUnbound
13,202✔
2278
        send_unbound_message(); // Throws
32,446✔
2279
        terminate();            // Throws
32,446✔
2280
        m_connection.discard_session(m_session_ident);
29,766✔
2281
        // This session is now destroyed!
13,202✔
2282
    }
29,766✔
2283

2284
    bool receive_bind_message(std::string path, std::string signed_user_token, bool need_client_file_ident,
2285
                              bool is_subserver, ProtocolError& error)
3,914✔
2286
    {
55,074✔
2287
        if (logger.would_log(util::Logger::Level::info)) {
51,440✔
2288
            logger.detail("Received: BIND(server_path=%1, signed_user_token='%2', "
2,780✔
2289
                          "need_client_file_ident=%3, is_subserver=%4)",
2,780✔
2290
                          path, short_token_fmt(signed_user_token), int(need_client_file_ident),
2,780✔
2291
                          int(is_subserver)); // Throws
2,780✔
2292
        }
2,500✔
2293

25,650✔
2294
        ServerImpl& server = m_connection.get_server();
55,074✔
2295
        _impl::VirtualPathComponents virt_path_components =
55,074✔
2296
            _impl::parse_virtual_path(server.get_root_dir(), path); // Throws
51,160✔
2297

25,650✔
2298
        if (!virt_path_components.is_valid) {
51,174✔
2299
            logger.error("Bad virtual path (message_type='bind', path='%1', "
238✔
2300
                         "signed_user_token='%2')",
238✔
2301
                         path,
238✔
2302
                         short_token_fmt(signed_user_token)); // Throws
238✔
2303
            error = ProtocolError::illegal_realm_path;
238✔
2304
            return false;
238✔
2305
        }
224✔
2306

21,624✔
2307
        // The user has proper permissions at this stage.
21,624✔
2308

25,524✔
2309
        m_server_file = server.get_or_create_file(path); // Throws
50,936✔
2310

25,524✔
2311
        m_server_file->add_unidentified_session(this); // Throws
50,936✔
2312

25,524✔
2313
        logger.info("Client info: (path='%1', from=%2, protocol=%3) %4", path, m_connection.get_remote_endpoint(),
54,836✔
2314
                    m_connection.get_client_protocol_version(),
54,836✔
2315
                    m_connection.get_client_user_agent()); // Throws
50,936✔
2316

25,524✔
2317
        m_is_subserver = is_subserver;
54,836✔
2318
        if (REALM_LIKELY(!need_client_file_ident)) {
50,936✔
2319
            // Protocol state is now WaitForUnbind
15,508✔
2320
            return true;
35,570✔
2321
        }
32,628✔
2322

9,058✔
2323
        // FIXME: We must make a choice about client file ident for read only
9,058✔
2324
        // sessions. They should have a special read-only client file ident.
10,016✔
2325
        file_ident_type proxy_file = 0; // No proxy
19,266✔
2326
        ClientType client_type = (is_subserver ? ClientType::subserver : ClientType::regular);
19,266✔
2327
        m_file_ident_request = m_server_file->request_file_ident(*this, proxy_file, client_type); // Throws
19,266✔
2328
        m_send_ident_message = true;
18,308✔
2329
        // Protocol state is now AllocatingIdent
9,058✔
2330

10,016✔
2331
        return true;
19,266✔
2332
    }
18,308✔
2333

2334
    bool receive_ident_message(file_ident_type client_file_ident, salt_type client_file_ident_salt,
2335
                               version_type scan_server_version, version_type scan_client_version,
2336
                               version_type latest_server_version, salt_type latest_server_version_salt,
2337
                               ProtocolError& error)
3,592✔
2338
    {
41,680✔
2339
        // Protocol state must be WaitForIdent
20,070✔
2340
        REALM_ASSERT(!need_client_file_ident());
45,272✔
2341
        REALM_ASSERT(!m_send_ident_message);
45,272✔
2342
        REALM_ASSERT(!ident_message_received());
45,272✔
2343
        REALM_ASSERT(!unbind_message_received());
45,272✔
2344
        REALM_ASSERT(!error_occurred());
45,272✔
2345
        REALM_ASSERT(!m_error_message_sent);
41,680✔
2346

20,070✔
2347
        logger.debug("Received: IDENT(client_file_ident=%1, client_file_ident_salt=%2, "
45,272✔
2348
                     "scan_server_version=%3, scan_client_version=%4, latest_server_version=%5, "
45,272✔
2349
                     "latest_server_version_salt=%6)",
45,272✔
2350
                     client_file_ident, client_file_ident_salt, scan_server_version, scan_client_version,
45,272✔
2351
                     latest_server_version, latest_server_version_salt); // Throws
41,680✔
2352

20,070✔
2353
        SaltedFileIdent client_file_ident_2 = {client_file_ident, client_file_ident_salt};
45,272✔
2354
        DownloadCursor download_progress = {scan_server_version, scan_client_version};
45,272✔
2355
        SaltedVersion server_version_2 = {latest_server_version, latest_server_version_salt};
45,272✔
2356
        ClientType client_type = (m_is_subserver ? ClientType::subserver : ClientType::regular);
45,272✔
2357
        UploadCursor upload_threshold = {0, 0};
45,272✔
2358
        version_type locked_server_version = 0;
45,272✔
2359
        BootstrapError error_2 =
45,272✔
2360
            m_server_file->bootstrap_client_session(client_file_ident_2, download_progress, server_version_2,
45,272✔
2361
                                                    client_type, upload_threshold, locked_server_version,
45,272✔
2362
                                                    logger); // Throws
45,272✔
2363
        switch (error_2) {
45,256✔
2364
            case BootstrapError::no_error:
45,000✔
2365
                break;
41,424✔
2366
            case BootstrapError::client_file_expired:
✔
2367
                logger.warn("Client (%1) expired", client_file_ident); // Throws
×
2368
                error = ProtocolError::client_file_expired;
×
2369
                return false;
✔
2370
            case BootstrapError::bad_client_file_ident:
✔
2371
                logger.error("Bad client file ident (%1) in IDENT message",
×
2372
                             client_file_ident); // Throws
×
2373
                error = ProtocolError::bad_client_file_ident;
×
2374
                return false;
2✔
2375
            case BootstrapError::bad_client_file_ident_salt:
34✔
2376
                logger.error("Bad client file identifier salt (%1) in IDENT message",
34✔
2377
                             client_file_ident_salt); // Throws
34✔
2378
                error = ProtocolError::diverging_histories;
34✔
2379
                return false;
32✔
2380
            case BootstrapError::bad_download_server_version:
✔
2381
                logger.error("Bad download progress server version in IDENT message"); // Throws
×
2382
                error = ProtocolError::bad_server_version;
×
2383
                return false;
2✔
2384
            case BootstrapError::bad_download_client_version:
34✔
2385
                logger.error("Bad download progress client version in IDENT message"); // Throws
34✔
2386
                error = ProtocolError::bad_client_version;
34✔
2387
                return false;
42✔
2388
            case BootstrapError::bad_server_version:
170✔
2389
                logger.error("Bad server version (message_type='ident')"); // Throws
170✔
2390
                error = ProtocolError::bad_server_version;
170✔
2391
                return false;
162✔
2392
            case BootstrapError::bad_server_version_salt:
34✔
2393
                logger.error("Bad server version salt in IDENT message"); // Throws
34✔
2394
                error = ProtocolError::diverging_histories;
34✔
2395
                return false;
32✔
2396
            case BootstrapError::bad_client_type:
✔
2397
                logger.error("Bad client type (%1) in IDENT message", int(client_type)); // Throws
×
2398
                error = ProtocolError::bad_client_file_ident; // FIXME: Introduce new protocol-level error
2399
                                                              // `bad_client_type`.
2400
                return false;
3,576✔
2401
        }
41,424✔
2402

16,350✔
2403
        // Make sure there is no other session currently associcated with the
16,350✔
2404
        // same client-side file
19,926✔
2405
        if (Session* other_sess = m_server_file->get_identified_session(client_file_ident)) {
41,424✔
2406
            SyncConnection& other_conn = other_sess->get_connection();
2407
            // It is a protocol violation if the other session is associated
2408
            // with the same connection
×
2409
            if (&other_conn == &m_connection) {
×
2410
                logger.error("Client file already bound in other session associated with "
×
2411
                             "the same connection"); // Throws
×
2412
                error = ProtocolError::bound_in_other_session;
×
2413
                return false;
×
2414
            }
2415
            // When the other session is associated with a different connection
2416
            // (`other_conn`), the clash may be due to the server not yet having
2417
            // realized that the other connection has been closed by the
2418
            // client. If so, the other connention is a "zombie". In the
2419
            // interest of getting rid of zombie connections as fast as
2420
            // possible, we shall assume that a clash with a session in another
2421
            // connection is always due to that other connection being a
2422
            // zombie. And when such a situation is detected, we want to close
2423
            // the zombie connection immediately.
2424
            auto log_level = Logger::Level::detail;
×
2425
            other_conn.terminate(log_level,
×
2426
                                 "Sync connection closed (superseded session)"); // Throws
×
2427
        }
2428

19,926✔
2429
        logger.info("Bound to client file (client_file_ident=%1)", client_file_ident); // Throws
41,424✔
2430

19,926✔
2431
        send_log_message(util::Logger::Level::debug, util::format("Session %1 bound to client file ident %2",
45,000✔
2432
                                                                  m_session_ident, client_file_ident));
41,424✔
2433

19,926✔
2434
        m_server_file->identify_session(this, client_file_ident); // Throws
41,424✔
2435

19,926✔
2436
        m_client_file_ident = client_file_ident;
45,000✔
2437
        m_download_progress = download_progress;
45,000✔
2438
        m_upload_threshold = upload_threshold;
45,000✔
2439
        m_locked_server_version = locked_server_version;
41,424✔
2440

19,926✔
2441
        ServerImpl& server = m_connection.get_server();
45,000✔
2442
        const Server::Config& config = server.get_config();
45,000✔
2443
        m_disable_download = (config.disable_download_for.count(client_file_ident) != 0);
41,424✔
2444

19,926✔
2445
        if (REALM_UNLIKELY(config.session_bootstrap_callback)) {
41,424✔
2446
            config.session_bootstrap_callback(m_server_file->get_virt_path(),
×
2447
                                              client_file_ident); // Throws
×
2448
        }
2449

16,350✔
2450
        // Protocol  state is now WaitForUnbind
19,926✔
2451
        enlist_to_send();
45,000✔
2452
        return true;
45,000✔
2453
    }
41,424✔
2454

2455
    bool receive_upload_message(version_type progress_client_version, version_type progress_server_version,
2456
                                version_type locked_server_version, const UploadChangesets& upload_changesets,
2457
                                ProtocolError& error)
23,152✔
2458
    {
361,688✔
2459
        // Protocol state must be WaitForUnbind
202,756✔
2460
        REALM_ASSERT(!m_send_ident_message);
384,840✔
2461
        REALM_ASSERT(ident_message_received());
384,840✔
2462
        REALM_ASSERT(!unbind_message_received());
384,840✔
2463
        REALM_ASSERT(!error_occurred());
384,840✔
2464
        REALM_ASSERT(!m_error_message_sent);
361,688✔
2465

202,756✔
2466
        logger.detail("Received: UPLOAD(progress_client_version=%1, progress_server_version=%2, "
384,840✔
2467
                      "locked_server_version=%3, num_changesets=%4)",
384,840✔
2468
                      progress_client_version, progress_server_version, locked_server_version,
384,840✔
2469
                      upload_changesets.size()); // Throws
361,688✔
2470

179,604✔
2471
        // We are unable to reproduce the cursor object for the upload progress
179,604✔
2472
        // when the protocol version is less than 29, because the client does
179,604✔
2473
        // not provide the required information. When the protocol version is
179,604✔
2474
        // less than 25, we can always get a consistent cursor by taking it from
179,604✔
2475
        // the changeset that was uploaded last, but in protocol versions 25,
179,604✔
2476
        // 26, 27, and 28, things are more complicated. Here, we receive new
179,604✔
2477
        // values for `last_integrated_server_version` which we cannot afford to
179,604✔
2478
        // ignore, but we do not know what client versions they correspond
179,604✔
2479
        // to. Fortunately, we can produce a cursor that works, and is mutually
179,604✔
2480
        // consistent with previous cursors, by simply bumping
179,604✔
2481
        // `upload_progress.client_version` when
179,604✔
2482
        // `upload_progress.last_intgerated_server_version` grows.
179,604✔
2483
        //
179,604✔
2484
        // To see that this scheme works, consider the last changeset, A, that
179,604✔
2485
        // will have already been uploaded and integrated at the beginning of
179,604✔
2486
        // the next session, and the first changeset, B, that follows A in the
179,604✔
2487
        // client side history, and is not upload skippable (of local origin and
179,604✔
2488
        // nonempty). We then need to show that A will be skipped, if uploaded
179,604✔
2489
        // in the next session, but B will not.
179,604✔
2490
        //
179,604✔
2491
        // Let V be the client version produced by A, and let T be the value of
179,604✔
2492
        // `upload_progress.client_version` as determined in this session, which
179,604✔
2493
        // is used as threshold in the next session. Then we know that A is
179,604✔
2494
        // skipped during the next session if V is less than, or equal to T. If
179,604✔
2495
        // the protocol version is at least 29, the protocol requires that T is
179,604✔
2496
        // greater than, or equal to V. If the protocol version is less than 25,
179,604✔
2497
        // T will be equal to V. Finally, if the protocol version is 25, 26, 27,
179,604✔
2498
        // or 28, we construct T such that it is always greater than, or equal
179,604✔
2499
        // to V, so in all cases, A will be skipped during the next session.
179,604✔
2500
        //
179,604✔
2501
        // Let W be the client version on which B is based. We then know that B
179,604✔
2502
        // will be retained if, and only if W is greater than, or equalto T. If
179,604✔
2503
        // the protocol version is at least 29, we know that T is less than, or
179,604✔
2504
        // equal to W, since B is not integrated until the next session. If the
179,604✔
2505
        // protocol version is less tahn 25, we know that T is V. Since V must
179,604✔
2506
        // be less than, or equal to W, we again know that T is less than, or
179,604✔
2507
        // equal to W. Finally, if the protocol version is 25, 26, 27, or 28, we
179,604✔
2508
        // construct T such that it is equal to V + N, where N is the number of
179,604✔
2509
        // observed increments in `last_integrated_server_version` since the
179,604✔
2510
        // client version prodiced by A. For each of these observed increments,
179,604✔
2511
        // there must have been a distinct new client version, but all these
179,604✔
2512
        // client versions must be less than, or equal to W, since B is not
179,604✔
2513
        // integrated until the next session. Therefore, we know that T = V + N
179,604✔
2514
        // is less than, or qual to W. So, in all cases, B will not skipped
179,604✔
2515
        // during the next session.
202,756✔
2516
        int protocol_version = m_connection.get_client_protocol_version();
384,840✔
2517
        static_cast<void>(protocol_version); // No protocol diversion (yet)
361,688✔
2518

202,756✔
2519
        UploadCursor upload_progress;
384,840✔
2520
        upload_progress = {progress_client_version, progress_server_version};
361,688✔
2521

179,604✔
2522
        // `upload_progress.client_version` must be nondecreasing across the
179,604✔
2523
        // session.
202,756✔
2524
        bool good_1 = (upload_progress.client_version >= m_upload_progress.client_version);
384,840✔
2525
        if (REALM_UNLIKELY(!good_1)) {
361,688✔
2526
            logger.error("Decreasing client version in upload progress (%1 < %2)", upload_progress.client_version,
×
2527
                         m_upload_progress.client_version); // Throws
×
2528
            error = ProtocolError::bad_client_version;
×
2529
            return false;
×
2530
        }
2531
        // `upload_progress.last_integrated_server_version` must be a version
179,604✔
2532
        // that the client can have heard about.
202,756✔
2533
        bool good_2 = (upload_progress.last_integrated_server_version <= m_download_progress.server_version);
384,840✔
2534
        if (REALM_UNLIKELY(!good_2)) {
361,688✔
2535
            logger.error("Bad last integrated server version in upload progress (%1 > %2)",
×
2536
                         upload_progress.last_integrated_server_version,
×
2537
                         m_download_progress.server_version); // Throws
×
2538
            error = ProtocolError::bad_server_version;
×
2539
            return false;
×
2540
        }
2541

179,604✔
2542
        // `upload_progress` must be consistent.
202,756✔
2543
        if (REALM_UNLIKELY(!is_consistent(upload_progress))) {
361,688✔
2544
            logger.error("Upload progress is inconsistent (%1, %2)", upload_progress.client_version,
×
2545
                         upload_progress.last_integrated_server_version); // Throws
×
2546
            error = ProtocolError::bad_server_version;
×
2547
            return false;
×
2548
        }
2549
        // `upload_progress` and `m_upload_threshold` must be mutually
179,604✔
2550
        // consistent.
202,756✔
2551
        if (REALM_UNLIKELY(!are_mutually_consistent(upload_progress, m_upload_threshold))) {
361,688✔
2552
            logger.error("Upload progress (%1, %2) is mutually inconsistent with "
×
2553
                         "threshold (%3, %4)",
×
2554
                         upload_progress.client_version, upload_progress.last_integrated_server_version,
×
2555
                         m_upload_threshold.client_version,
×
2556
                         m_upload_threshold.last_integrated_server_version); // Throws
×
2557
            error = ProtocolError::bad_server_version;
×
2558
            return false;
×
2559
        }
2560
        // `upload_progress` and `m_upload_progress` must be mutually
179,604✔
2561
        // consistent.
202,756✔
2562
        if (REALM_UNLIKELY(!are_mutually_consistent(upload_progress, m_upload_progress))) {
361,688✔
2563
            logger.error("Upload progress (%1, %2) is mutually inconsistent with previous "
×
2564
                         "upload progress (%3, %4)",
×
2565
                         upload_progress.client_version, upload_progress.last_integrated_server_version,
×
2566
                         m_upload_progress.client_version,
×
2567
                         m_upload_progress.last_integrated_server_version); // Throws
×
2568
            error = ProtocolError::bad_server_version;
×
2569
            return false;
×
2570
        }
2571

202,756✔
2572
        version_type locked_server_version_2 = locked_server_version;
361,688✔
2573

179,604✔
2574
        // `locked_server_version_2` must be nondecreasing over the lifetime of
179,604✔
2575
        // the client-side file.
202,756✔
2576
        if (REALM_UNLIKELY(locked_server_version_2 < m_locked_server_version)) {
361,688✔
2577
            logger.error("Decreasing locked server version (%1 < %2)", locked_server_version_2,
×
2578
                         m_locked_server_version); // Throws
×
2579
            error = ProtocolError::bad_server_version;
×
2580
            return false;
×
2581
        }
2582
        // `locked_server_version_2` must be a version that the client can have
179,604✔
2583
        // heard about.
202,756✔
2584
        if (REALM_UNLIKELY(locked_server_version_2 > m_download_progress.server_version)) {
361,688✔
2585
            logger.error("Bad locked server version (%1 > %2)", locked_server_version_2,
×
2586
                         m_download_progress.server_version); // Throws
×
2587
            error = ProtocolError::bad_server_version;
×
2588
            return false;
×
2589
        }
2590

202,756✔
2591
        std::size_t num_previously_integrated_changesets = 0;
384,840✔
2592
        if (!upload_changesets.empty()) {
372,906✔
2593
            UploadCursor up = m_upload_progress;
204,722✔
2594
            for (const ServerProtocol::UploadChangeset& uc : upload_changesets) {
294,818✔
2595
                // `uc.upload_cursor.client_version` must be increasing across
142,550✔
2596
                // all the changesets in this UPLOAD message, and all must be
142,550✔
2597
                // greater than upload_progress.client_version of previous
142,550✔
2598
                // UPLOAD message.
161,400✔
2599
                if (REALM_UNLIKELY(uc.upload_cursor.client_version <= up.client_version)) {
294,818✔
2600
                    logger.error("Nonincreasing client version in upload cursor of uploaded "
×
2601
                                 "changeset (%1 <= %2)",
×
2602
                                 uc.upload_cursor.client_version,
×
2603
                                 up.client_version); // Throws
×
2604
                    error = ProtocolError::bad_client_version;
×
2605
                    return false;
×
2606
                }
2607
                // `uc.upload_progress` must be consistent.
161,400✔
2608
                if (REALM_UNLIKELY(!is_consistent(uc.upload_cursor))) {
294,818✔
2609
                    logger.error("Upload cursor of uploaded changeset is inconsistent (%1, %2)",
×
2610
                                 uc.upload_cursor.client_version,
×
2611
                                 uc.upload_cursor.last_integrated_server_version); // Throws
×
2612
                    error = ProtocolError::bad_server_version;
×
2613
                    return false;
×
2614
                }
2615
                // `uc.upload_progress` must be mutually consistent with
142,550✔
2616
                // previous upload cursor.
161,400✔
2617
                if (REALM_UNLIKELY(!are_mutually_consistent(uc.upload_cursor, up))) {
294,818✔
2618
                    logger.error("Upload cursor of uploaded changeset (%1, %2) is mutually "
×
2619
                                 "inconsistent with previous upload cursor (%3, %4)",
×
2620
                                 uc.upload_cursor.client_version, uc.upload_cursor.last_integrated_server_version,
×
2621
                                 up.client_version, up.last_integrated_server_version); // Throws
×
2622
                    error = ProtocolError::bad_server_version;
×
2623
                    return false;
×
2624
                }
2625
                // `uc.upload_progress` must be mutually consistent with
142,550✔
2626
                // threshold, that is, for changesets that have not previously
142,550✔
2627
                // been integrated, it is important that the specified value of
142,550✔
2628
                // `last_integrated_server_version` is greater than, or equal to
142,550✔
2629
                // the reciprocal history base version.
161,400✔
2630
                bool consistent_with_threshold = are_mutually_consistent(uc.upload_cursor, m_upload_threshold);
313,668✔
2631
                if (REALM_UNLIKELY(!consistent_with_threshold)) {
294,818✔
2632
                    logger.error("Upload cursor of uploaded changeset (%1, %2) is mutually "
×
2633
                                 "inconsistent with threshold (%3, %4)",
×
2634
                                 uc.upload_cursor.client_version, uc.upload_cursor.last_integrated_server_version,
×
2635
                                 m_upload_threshold.client_version,
×
2636
                                 m_upload_threshold.last_integrated_server_version); // Throws
×
2637
                    error = ProtocolError::bad_server_version;
×
2638
                    return false;
×
2639
                }
18,850✔
2640
                bool previously_integrated = (uc.upload_cursor.client_version <= m_upload_threshold.client_version);
313,668✔
2641
                if (previously_integrated)
296,028✔
2642
                    ++num_previously_integrated_changesets;
37,804✔
2643
                up = uc.upload_cursor;
313,668✔
2644
            }
294,818✔
2645
            // `upload_progress.client_version` must be greater than, or equal
96,034✔
2646
            // to client versions produced by each of the changesets in this
96,034✔
2647
            // UPLOAD message.
107,252✔
2648
            if (REALM_UNLIKELY(up.client_version > upload_progress.client_version)) {
185,872✔
2649
                logger.error("Upload progress less than client version produced by uploaded "
×
2650
                             "changeset (%1 > %2)",
×
2651
                             up.client_version,
×
2652
                             upload_progress.client_version); // Throws
×
2653
                error = ProtocolError::bad_client_version;
×
2654
                return false;
×
2655
            }
2656
            // The upload cursor of last uploaded changeset must be mutually
96,034✔
2657
            // consistent with the reported upload progress.
107,252✔
2658
            if (REALM_UNLIKELY(!are_mutually_consistent(up, upload_progress))) {
185,872✔
2659
                logger.error("Upload cursor (%1, %2) of last uploaded changeset is mutually "
×
2660
                             "inconsistent with upload progress (%3, %4)",
×
2661
                             up.client_version, up.last_integrated_server_version, upload_progress.client_version,
×
2662
                             upload_progress.last_integrated_server_version); // Throws
×
2663
                error = ProtocolError::bad_server_version;
×
2664
                return false;
×
2665
            }
23,152✔
2666
        }
361,688✔
2667

179,604✔
2668
        // FIXME: Part of a very poor man's substitute for a proper backpressure
179,604✔
2669
        // scheme.
202,756✔
2670
        if (REALM_UNLIKELY(!m_server_file->can_add_changesets_from_downstream())) {
361,688✔
2671
            logger.debug("Terminating uploading session because buffer is full"); // Throws
2672
            // Using this exact error code, because it causes `try_again` flag
2673
            // to be set to true, which causes the client to wait for about 5
2674
            // minuites before trying to connect again.
2675
            error = ProtocolError::connection_closed;
×
2676
            return false;
×
2677
        }
2678

202,756✔
2679
        m_upload_progress = upload_progress;
361,688✔
2680

202,756✔
2681
        bool have_real_upload_progress = (upload_progress.client_version > m_upload_threshold.client_version);
384,840✔
2682
        bool bump_locked_server_version = (locked_server_version_2 > m_locked_server_version);
361,688✔
2683

202,756✔
2684
        std::size_t num_changesets_to_integrate = upload_changesets.size() - num_previously_integrated_changesets;
384,840✔
2685
        REALM_ASSERT(have_real_upload_progress || num_changesets_to_integrate == 0);
361,688✔
2686

202,756✔
2687
        bool have_anything_to_do = (have_real_upload_progress || bump_locked_server_version);
384,840✔
2688
        if (!have_anything_to_do)
361,772✔
2689
            return true;
1,670✔
2690

201,748✔
2691
        if (!have_real_upload_progress)
360,018✔
2692
            upload_progress = m_upload_threshold;
2693

201,748✔
2694
        if (num_previously_integrated_changesets > 0) {
360,324✔
2695
            logger.detail("Ignoring %1 previously integrated changesets",
6,050✔
2696
                          num_previously_integrated_changesets); // Throws
6,050✔
2697
        }
28,812✔
2698
        if (num_changesets_to_integrate > 0) {
371,108✔
2699
            logger.detail("Initiate integration of %1 remote changesets",
194,528✔
2700
                          num_changesets_to_integrate); // Throws
194,528✔
2701
        }
183,438✔
2702

201,748✔
2703
        REALM_ASSERT(m_server_file);
383,086✔
2704
        ServerFile& file = *m_server_file;
383,086✔
2705
        std::size_t offset = num_previously_integrated_changesets;
383,086✔
2706
        file.add_changesets_from_downstream(m_client_file_ident, upload_progress, locked_server_version_2,
383,086✔
2707
                                            upload_changesets.data() + offset, num_changesets_to_integrate); // Throws
360,018✔
2708

201,748✔
2709
        m_locked_server_version = locked_server_version_2;
383,086✔
2710
        return true;
383,086✔
2711
    }
360,018✔
2712

2713
    bool receive_mark_message(request_ident_type request_ident, ProtocolError&)
7,750✔
2714
    {
106,056✔
2715
        // Protocol state must be WaitForUnbind
55,696✔
2716
        REALM_ASSERT(!m_send_ident_message);
113,806✔
2717
        REALM_ASSERT(ident_message_received());
113,806✔
2718
        REALM_ASSERT(!unbind_message_received());
113,806✔
2719
        REALM_ASSERT(!error_occurred());
113,806✔
2720
        REALM_ASSERT(!m_error_message_sent);
106,056✔
2721

55,696✔
2722
        logger.debug("Received: MARK(request_ident=%1)", request_ident); // Throws
106,056✔
2723

55,696✔
2724
        m_download_completion_request = request_ident;
106,056✔
2725

55,696✔
2726
        ensure_enlisted_to_send();
113,806✔
2727
        return true;
113,806✔
2728
    }
106,056✔
2729

2730
    // Returns true if the deactivation process has been completed, at which
2731
    // point the caller (SyncConnection::receive_unbind_message()) should
2732
    // terminate the session.
2733
    //
2734
    // CAUTION: This function may commit suicide!
2735
    void receive_unbind_message()
2,702✔
2736
    {
30,066✔
2737
        // Protocol state may be anything but SendUnbound
13,376✔
2738
        REALM_ASSERT(!m_unbind_message_received);
30,066✔
2739

13,376✔
2740
        logger.detail("Received: UNBIND"); // Throws
30,066✔
2741

13,376✔
2742
        detach_from_server_file();
32,768✔
2743
        m_unbind_message_received = true;
30,066✔
2744

10,674✔
2745
        // Detect completion of the deactivation process
13,376✔
2746
        if (m_error_message_sent) {
30,066✔
2747
            // Deactivation process completed
128✔
2748
            terminate(); // Throws
236✔
2749
            m_connection.discard_session(m_session_ident);
220✔
2750
            // This session is now destroyed!
128✔
2751
            return;
236✔
2752
        }
220✔
2753

10,562✔
2754
        // Protocol state is now SendUnbound
13,248✔
2755
        ensure_enlisted_to_send();
32,532✔
2756
    }
29,846✔
2757

2758
    void receive_error_message(session_ident_type, int, std::string_view)
2759
    {
×
2760
        REALM_ASSERT(!m_unbind_message_received);
×
2761

2762
        logger.detail("Received: ERROR"); // Throws
×
2763
    }
2764

2765
private:
2766
    SyncConnection& m_connection;
2767

2768
    const session_ident_type m_session_ident;
2769

2770
    // Not null if, and only if this session is in
2771
    // m_connection.m_sessions_enlisted_to_send.
2772
    Session* m_next = nullptr;
2773

2774
    // Becomes nonnull when the BIND message is received, if no error occurs. Is
2775
    // reset to null when the deactivation process is initiated, either when the
2776
    // UNBIND message is recieved, or when initiate_deactivation() is called.
2777
    util::bind_ptr<ServerFile> m_server_file;
2778

2779
    bool m_disable_download = false;
2780
    bool m_is_subserver = false;
2781

2782
    using file_ident_request_type = ServerFile::file_ident_request_type;
2783

2784
    // When nonzero, this session has an outstanding request for a client file
2785
    // identifier.
2786
    file_ident_request_type m_file_ident_request = 0;
2787

2788
    // Payload for next outgoing ALLOC message.
2789
    SaltedFileIdent m_allocated_file_ident = {0, 0};
2790

2791
    // Zero until the session receives an IDENT message from the client.
2792
    file_ident_type m_client_file_ident = 0;
2793

2794
    // Zero until initiate_deactivation() is called.
2795
    ProtocolError m_error_code = {};
2796

2797
    // The current point of progression of the download process. Set to (<server
2798
    // version>, <client version>) of the IDENT message when the IDENT message
2799
    // is received. At the time of return from continue_history_scan(), it
2800
    // points to the latest server version such that all preceding changesets in
2801
    // the server-side history have been downloaded, are currently being
2802
    // downloaded, or are *download excluded*.
2803
    DownloadCursor m_download_progress = {0, 0};
2804

2805
    request_ident_type m_download_completion_request = 0;
2806

2807
    // Records the progress of the upload process. Used to check that the client
2808
    // uploads changesets in order. Also, when m_upload_progress >
2809
    // m_upload_threshold, m_upload_progress works as a cache of the persisted
2810
    // version of the upload progress.
2811
    UploadCursor m_upload_progress = {0, 0};
2812

2813
    // Initialized on reception of the IDENT message. Specifies the actual
2814
    // upload progress (as recorded on the server-side) at the beginning of the
2815
    // session, and it remains fixed throughout the session.
2816
    //
2817
    // m_upload_threshold includes the progress resulting from the received
2818
    // changesets that have not yet been integrated (only relevant for
2819
    // synchronous backup).
2820
    UploadCursor m_upload_threshold = {0, 0};
2821

2822
    // Works partially as a cache of the persisted value, and partially as a way
2823
    // of checking that the client respects that it can never decrease.
2824
    version_type m_locked_server_version = 0;
2825

2826
    bool m_send_ident_message = false;
2827
    bool m_unbind_message_received = false;
2828
    bool m_error_message_sent = false;
2829

2830
    /// m_one_download_message_sent denotes whether at least one DOWNLOAD message
2831
    /// has been sent in the current session. The variable is used to ensure
2832
    /// that a DOWNLOAD message is always sent in a session. The received
2833
    /// DOWNLOAD message is needed by the client to ensure that its current
2834
    /// download progress is up to date.
2835
    bool m_one_download_message_sent = false;
2836

2837
    static std::string make_logger_prefix(session_ident_type session_ident)
3,914✔
2838
    {
55,074✔
2839
        std::ostringstream out;
55,074✔
2840
        out.imbue(std::locale::classic());
55,074✔
2841
        out << "Session[" << session_ident << "]: "; // Throws
55,074✔
2842
        return out.str();                            // Throws
55,074✔
2843
    }
51,160✔
2844

2845
    // Scan the history for changesets to be downloaded.
2846
    // If the history is longer than the end point of the previous scan,
2847
    // a DOWNLOAD message will be sent.
2848
    // A MARK message is sent if no DOWNLOAD message is sent, and the client has
2849
    // requested to be notified about download completion.
2850
    // In case neither a DOWNLOAD nor a MARK is sent, no message is sent.
2851
    //
2852
    // This function may lead to the destruction of the session object
2853
    // (suicide).
2854
    void continue_history_scan()
52,920✔
2855
    {
839,230✔
2856
        // Protocol state must be WaitForUnbind
487,502✔
2857
        REALM_ASSERT(!m_send_ident_message);
892,150✔
2858
        REALM_ASSERT(ident_message_received());
892,150✔
2859
        REALM_ASSERT(!unbind_message_received());
892,150✔
2860
        REALM_ASSERT(!error_occurred());
892,150✔
2861
        REALM_ASSERT(!m_error_message_sent);
892,150✔
2862
        REALM_ASSERT(!is_enlisted_to_send());
839,230✔
2863

487,502✔
2864
        SaltedVersion last_server_version = m_server_file->get_salted_sync_version();
892,150✔
2865
        REALM_ASSERT(last_server_version.version >= m_download_progress.server_version);
839,230✔
2866

487,502✔
2867
        ServerImpl& server = m_connection.get_server();
892,150✔
2868
        const Server::Config& config = server.get_config();
892,150✔
2869
        if (REALM_UNLIKELY(m_disable_download))
839,230✔
2870
            return;
434,582✔
2871

487,502✔
2872
        bool have_more_to_scan =
892,150✔
2873
            (last_server_version.version > m_download_progress.server_version || !m_one_download_message_sent);
892,150✔
2874
        if (have_more_to_scan) {
858,874✔
2875
            m_server_file->register_client_access(m_client_file_ident);     // Throws
342,312✔
2876
            const ServerHistory& history = m_server_file->access().history; // Throws
342,312✔
2877
            const char* body;
342,312✔
2878
            std::size_t uncompressed_body_size;
342,312✔
2879
            std::size_t compressed_body_size = 0;
342,312✔
2880
            bool body_is_compressed = false;
342,312✔
2881
            version_type end_version = last_server_version.version;
342,312✔
2882
            DownloadCursor download_progress;
342,312✔
2883
            UploadCursor upload_progress = {0, 0};
342,312✔
2884
            std::uint_fast64_t downloadable_bytes = 0;
342,312✔
2885
            std::size_t num_changesets;
342,312✔
2886
            std::size_t accum_original_size;
342,312✔
2887
            std::size_t accum_compacted_size;
342,312✔
2888
            ServerProtocol& protocol = get_server_protocol();
342,312✔
2889
            bool disable_download_compaction = config.disable_download_compaction;
342,312!
2890
            bool enable_cache = (config.enable_download_bootstrap_cache && m_download_progress.server_version == 0 &&
322,668!
2891
                                 m_upload_progress.client_version == 0 && m_upload_threshold.client_version == 0);
191,592!
2892
            DownloadCache& cache = m_server_file->get_download_cache();
342,312!
2893
            bool fetch_from_cache = (enable_cache && cache.body && end_version == cache.end_version);
342,312!
2894
            if (fetch_from_cache) {
322,668✔
2895
                body = cache.body.get();
×
2896
                uncompressed_body_size = cache.uncompressed_body_size;
×
2897
                compressed_body_size = cache.compressed_body_size;
×
2898
                body_is_compressed = cache.body_is_compressed;
×
2899
                download_progress = cache.download_progress;
×
2900
                downloadable_bytes = cache.downloadable_bytes;
×
2901
                num_changesets = cache.num_changesets;
×
2902
                accum_original_size = cache.accum_original_size;
×
2903
                accum_compacted_size = cache.accum_compacted_size;
×
2904
            }
19,644✔
2905
            else {
322,668✔
2906
                // Discard the old cached DOWNLOAD body before generating a new
171,948✔
2907
                // one to be cached. This can make a big difference because the
171,948✔
2908
                // size of that body can be very large (10GiB has been seen in a
171,948✔
2909
                // real-world case).
191,592✔
2910
                if (enable_cache)
322,668✔
2911
                    cache.body = {};
2912

191,592✔
2913
                OutputBuffer& out = server.get_misc_buffers().download_message;
342,312✔
2914
                out.reset();
342,312✔
2915
                download_progress = m_download_progress;
342,314✔
2916
                auto fetch_and_compress = [&](std::size_t max_download_size) {
342,330✔
2917
                    DownloadHistoryEntryHandler handler{protocol, out, logger};
342,326✔
2918
                    std::uint_fast64_t cumulative_byte_size_current;
342,326✔
2919
                    std::uint_fast64_t cumulative_byte_size_total;
342,326✔
2920
                    bool not_expired = history.fetch_download_info(
342,326✔
2921
                        m_client_file_ident, download_progress, end_version, upload_progress, handler,
342,326✔
2922
                        cumulative_byte_size_current, cumulative_byte_size_total, disable_download_compaction,
342,326✔
2923
                        max_download_size); // Throws
342,326✔
2924
                    REALM_ASSERT(upload_progress.client_version >= download_progress.last_integrated_client_version);
342,326✔
2925
                    SyncConnection& conn = get_connection();
342,326✔
2926
                    if (REALM_UNLIKELY(!not_expired)) {
322,680✔
2927
                        logger.debug("History scanning failed: Client file entry "
×
2928
                                     "expired during session"); // Throws
×
2929
                        conn.protocol_error(ProtocolError::client_file_expired, this);
2930
                        // Session object may have been destroyed at this point
2931
                        // (suicide).
2932
                        return false;
×
2933
                    }
2934

191,594✔
2935
                    downloadable_bytes = cumulative_byte_size_total - cumulative_byte_size_current;
342,326✔
2936
                    uncompressed_body_size = out.size();
342,326✔
2937
                    BinaryData uncompressed = {out.data(), uncompressed_body_size};
342,326✔
2938
                    body = uncompressed.data();
342,326✔
2939
                    std::size_t max_uncompressed = 1024;
342,326✔
2940
                    if (uncompressed.size() > max_uncompressed) {
324,794✔
2941
                        compression::CompressMemoryArena& arena = server.get_compress_memory_arena();
35,902✔
2942
                        std::vector<char>& buffer = server.get_misc_buffers().compress;
35,902✔
2943
                        compression::allocate_and_compress(arena, uncompressed, buffer); // Throws
35,902✔
2944
                        if (buffer.size() < uncompressed.size()) {
35,902✔
2945
                            body = buffer.data();
35,902✔
2946
                            compressed_body_size = buffer.size();
35,902✔
2947
                            body_is_compressed = true;
35,902✔
2948
                        }
35,902✔
2949
                    }
53,434✔
2950
                    num_changesets = handler.num_changesets;
342,326✔
2951
                    accum_original_size = handler.accum_original_size;
342,326✔
2952
                    accum_compacted_size = handler.accum_compacted_size;
342,326✔
2953
                    return true;
342,326✔
2954
                };
342,324✔
2955
                if (enable_cache) {
322,668✔
2956
                    std::size_t max_download_size = std::numeric_limits<size_t>::max();
×
2957
                    if (!fetch_and_compress(max_download_size)) { // Throws
×
2958
                        // Session object may have been destroyed at this point
2959
                        // (suicide).
2960
                        return;
×
2961
                    }
×
2962
                    REALM_ASSERT(upload_progress.client_version == 0);
×
2963
                    std::size_t body_size = (body_is_compressed ? compressed_body_size : uncompressed_body_size);
×
2964
                    cache.body = std::make_unique<char[]>(body_size); // Throws
×
2965
                    std::copy(body, body + body_size, cache.body.get());
×
2966
                    cache.uncompressed_body_size = uncompressed_body_size;
×
2967
                    cache.compressed_body_size = compressed_body_size;
×
2968
                    cache.body_is_compressed = body_is_compressed;
×
2969
                    cache.end_version = end_version;
×
2970
                    cache.download_progress = download_progress;
×
2971
                    cache.downloadable_bytes = downloadable_bytes;
×
2972
                    cache.num_changesets = num_changesets;
×
2973
                    cache.accum_original_size = accum_original_size;
×
2974
                    cache.accum_compacted_size = accum_compacted_size;
×
2975
                }
19,644✔
2976
                else {
342,312✔
2977
                    std::size_t max_download_size = config.max_download_size;
342,312✔
2978
                    if (!fetch_and_compress(max_download_size)) { // Throws
322,668✔
2979
                        // Session object may have been destroyed at this point
2980
                        // (suicide).
2981
                        return;
×
2982
                    }
19,644✔
2983
                }
342,312✔
2984
            }
322,668✔
2985

191,592✔
2986
            OutputBuffer& out = m_connection.get_output_buffer();
342,312✔
2987
            protocol.make_download_message(
342,312✔
2988
                m_connection.get_client_protocol_version(), out, m_session_ident, download_progress.server_version,
342,312✔
2989
                download_progress.last_integrated_client_version, last_server_version.version,
342,312✔
2990
                last_server_version.salt, upload_progress.client_version,
342,312✔
2991
                upload_progress.last_integrated_server_version, downloadable_bytes, num_changesets, body,
342,312✔
2992
                uncompressed_body_size, compressed_body_size, body_is_compressed, logger); // Throws
322,668✔
2993

191,594✔
2994
            if (!disable_download_compaction) {
342,334✔
2995
                std::size_t saved = accum_original_size - accum_compacted_size;
332,978✔
2996
                double saved_2 = (accum_original_size == 0 ? 0 : std::round(saved * 100.0 / accum_original_size));
270,402✔
2997
                logger.detail("Download compaction: Saved %1 bytes (%2%%)", saved, saved_2); // Throws
342,328✔
2998
            }
322,682✔
2999

191,592✔
3000
            m_download_progress = download_progress;
342,312✔
3001
            logger.debug("Setting of m_download_progress.server_version = %1",
342,312✔
3002
                         m_download_progress.server_version); // Throws
342,312✔
3003
            send_download_message();
342,312✔
3004
            m_one_download_message_sent = true;
322,668✔
3005

191,592✔
3006
            enlist_to_send();
342,312✔
3007
        }
355,944✔
3008
        else if (m_download_completion_request) {
516,562✔
3009
            // Send a MARK message
55,658✔
3010
            request_ident_type request_ident = m_download_completion_request;
113,752✔
3011
            send_mark_message(request_ident);  // Throws
113,752✔
3012
            m_download_completion_request = 0; // Request handled
113,752✔
3013
            enlist_to_send();
113,752✔
3014
        }
158,928✔
3015
    }
839,230✔
3016

3017
    void send_ident_message()
710✔
3018
    {
10,312✔
3019
        // Protocol state must be SendIdent
5,260✔
3020
        REALM_ASSERT(!need_client_file_ident());
11,022✔
3021
        REALM_ASSERT(m_send_ident_message);
11,022✔
3022
        REALM_ASSERT(!ident_message_received());
11,022✔
3023
        REALM_ASSERT(!unbind_message_received());
11,022✔
3024
        REALM_ASSERT(!error_occurred());
11,022✔
3025
        REALM_ASSERT(!m_error_message_sent);
10,312✔
3026

5,260✔
3027
        REALM_ASSERT(m_allocated_file_ident.ident != 0);
10,312✔
3028

5,260✔
3029
        file_ident_type client_file_ident = m_allocated_file_ident.ident;
11,022✔
3030
        salt_type client_file_ident_salt = m_allocated_file_ident.salt;
10,312✔
3031

5,260✔
3032
        logger.debug("Sending: IDENT(client_file_ident=%1, client_file_ident_salt=%2)", client_file_ident,
11,022✔
3033
                     client_file_ident_salt); // Throws
10,312✔
3034

5,260✔
3035
        ServerProtocol& protocol = get_server_protocol();
11,022✔
3036
        OutputBuffer& out = m_connection.get_output_buffer();
11,022✔
3037
        int protocol_version = m_connection.get_client_protocol_version();
11,022✔
3038
        protocol.make_ident_message(protocol_version, out, m_session_ident, client_file_ident,
11,022✔
3039
                                    client_file_ident_salt); // Throws
11,022✔
3040
        m_connection.initiate_write_output_buffer();         // Throws
10,312✔
3041

5,260✔
3042
        m_allocated_file_ident.ident = 0; // Consumed
11,022✔
3043
        m_send_ident_message = false;
10,312✔
3044
        // Protocol state is now WaitForStateRequest or WaitForIdent
5,260✔
3045
    }
10,312✔
3046

3047
    void send_download_message()
19,646✔
3048
    {
342,330✔
3049
        m_connection.initiate_write_output_buffer(); // Throws
342,330✔
3050
    }
322,684✔
3051

3052
    void send_mark_message(request_ident_type request_ident)
7,744✔
3053
    {
113,752✔
3054
        logger.debug("Sending: MARK(request_ident=%1)", request_ident); // Throws
106,008✔
3055

55,658✔
3056
        ServerProtocol& protocol = get_server_protocol();
113,752✔
3057
        OutputBuffer& out = m_connection.get_output_buffer();
113,752✔
3058
        protocol.make_mark_message(out, m_session_ident, request_ident); // Throws
113,752✔
3059
        m_connection.initiate_write_output_buffer();                     // Throws
113,752✔
3060
    }
106,008✔
3061

3062
    void send_alloc_message()
3063
    {
3064
        // Protocol state must be WaitForUnbind
×
3065
        REALM_ASSERT(!m_send_ident_message);
×
3066
        REALM_ASSERT(ident_message_received());
×
3067
        REALM_ASSERT(!unbind_message_received());
×
3068
        REALM_ASSERT(!error_occurred());
×
3069
        REALM_ASSERT(!m_error_message_sent);
×
3070

×
3071
        REALM_ASSERT(m_allocated_file_ident.ident != 0);
×
3072

3073
        // Relayed allocations are only allowed from protocol version 23 (old protocol).
3074
        REALM_ASSERT(false);
3075

3076
        file_ident_type file_ident = m_allocated_file_ident.ident;
3077

3078
        logger.debug("Sending: ALLOC(file_ident=%1)", file_ident); // Throws
3079

3080
        ServerProtocol& protocol = get_server_protocol();
×
3081
        OutputBuffer& out = m_connection.get_output_buffer();
×
3082
        protocol.make_alloc_message(out, m_session_ident, file_ident); // Throws
×
3083
        m_connection.initiate_write_output_buffer();                   // Throws
3084

3085
        m_allocated_file_ident.ident = 0; // Consumed
3086

3087
        // Other messages may be waiting to be sent.
3088
        enlist_to_send();
×
3089
    }
3090

3091
    void send_unbound_message()
2,682✔
3092
    {
29,770✔
3093
        // Protocol state must be SendUnbound
13,208✔
3094
        REALM_ASSERT(unbind_message_received());
32,452✔
3095
        REALM_ASSERT(!m_error_message_sent);
29,770✔
3096

13,208✔
3097
        logger.debug("Sending: UNBOUND"); // Throws
29,770✔
3098

13,208✔
3099
        ServerProtocol& protocol = get_server_protocol();
32,452✔
3100
        OutputBuffer& out = m_connection.get_output_buffer();
32,452✔
3101
        protocol.make_unbound_message(out, m_session_ident); // Throws
32,452✔
3102
        m_connection.initiate_write_output_buffer();         // Throws
32,452✔
3103
    }
29,770✔
3104

3105
    void send_error_message()
42✔
3106
    {
630✔
3107
        // Protocol state must be SendError
350✔
3108
        REALM_ASSERT(!unbind_message_received());
672✔
3109
        REALM_ASSERT(error_occurred());
672✔
3110
        REALM_ASSERT(!m_error_message_sent);
630✔
3111

350✔
3112
        REALM_ASSERT(is_session_level_error(m_error_code));
630✔
3113

350✔
3114
        ProtocolError error_code = m_error_code;
672✔
3115
        const char* message = get_protocol_error_message(int(error_code));
672✔
3116
        std::size_t message_size = std::strlen(message);
672✔
3117
        bool try_again = determine_try_again(error_code);
630✔
3118

350✔
3119
        logger.detail("Sending: ERROR(error_code=%1, message_size=%2, try_again=%3)", int(error_code), message_size,
672✔
3120
                      try_again); // Throws
630✔
3121

350✔
3122
        ServerProtocol& protocol = get_server_protocol();
672✔
3123
        OutputBuffer& out = m_connection.get_output_buffer();
672✔
3124
        int protocol_version = m_connection.get_client_protocol_version();
672✔
3125
        protocol.make_error_message(protocol_version, out, error_code, message, message_size, try_again,
672✔
3126
                                    m_session_ident); // Throws
672✔
3127
        m_connection.initiate_write_output_buffer();  // Throws
630✔
3128

350✔
3129
        m_error_message_sent = true;
630✔
3130
        // Protocol state is now WaitForUnbindErr
350✔
3131
    }
630✔
3132

3133
    void send_log_message(util::Logger::Level level, const std::string&& message)
3,576✔
3134
    {
45,000✔
3135
        if (m_connection.get_client_protocol_version() < SyncConnection::SERVER_LOG_PROTOCOL_VERSION) {
41,424✔
3136
            return logger.log(level, message.c_str());
×
3137
        }
3138

19,926✔
3139
        m_connection.send_log_message(level, std::move(message), m_session_ident);
45,000✔
3140
    }
41,424✔
3141

3142
    // Idempotent
3143
    void detach_from_server_file() noexcept
6,658✔
3144
    {
88,526✔
3145
        if (!m_server_file)
84,626✔
3146
            return;
34,832✔
3147
        ServerFile& file = *m_server_file;
54,836✔
3148
        if (ident_message_received()) {
54,512✔
3149
            file.remove_identified_session(m_client_file_ident);
45,000✔
3150
        }
41,748✔
3151
        else {
9,836✔
3152
            file.remove_unidentified_session(this);
9,836✔
3153
        }
13,412✔
3154
        if (m_file_ident_request != 0)
51,184✔
3155
            file.cancel_file_ident_request(m_file_ident_request);
11,900✔
3156
        m_server_file.reset();
54,836✔
3157
    }
50,936✔
3158

3159
    friend class SessionQueue;
3160
};
3161

3162

3163
// ============================ SessionQueue implementation ============================
3164

3165
void SessionQueue::push_back(Session* sess) noexcept
56,442✔
3166
{
937,766✔
3167
    REALM_ASSERT(!sess->m_next);
937,766✔
3168
    if (m_back) {
898,228✔
3169
        sess->m_next = m_back->m_next;
320,202✔
3170
        m_back->m_next = sess;
320,202✔
3171
    }
342,836✔
3172
    else {
617,564✔
3173
        sess->m_next = sess;
617,564✔
3174
    }
634,468✔
3175
    m_back = sess;
937,766✔
3176
}
881,324✔
3177

3178

3179
Session* SessionQueue::pop_front() noexcept
83,558✔
3180
{
1,364,246✔
3181
    Session* sess = nullptr;
1,364,246✔
3182
    if (m_back) {
1,337,042✔
3183
        sess = m_back->m_next;
936,276✔
3184
        if (sess != m_back) {
896,786✔
3185
            m_back->m_next = sess->m_next;
319,600✔
3186
        }
342,226✔
3187
        else {
616,676✔
3188
            m_back = nullptr;
616,676✔
3189
        }
633,540✔
3190
        sess->m_next = nullptr;
936,276✔
3191
    }
963,480✔
3192
    return sess;
1,364,246✔
3193
}
1,280,688✔
3194

3195

3196
void SessionQueue::clear() noexcept
1,428✔
3197
{
25,754✔
3198
    if (m_back) {
24,376✔
3199
        Session* sess = m_back;
928✔
3200
        for (;;) {
1,482✔
3201
            Session* next = sess->m_next;
1,482✔
3202
            sess->m_next = nullptr;
1,482✔
3203
            if (next == m_back)
1,444✔
3204
                break;
878✔
3205
            sess = next;
592✔
3206
        }
604✔
3207
        m_back = nullptr;
890✔
3208
    }
2,268✔
3209
}
24,326✔
3210

3211

3212
// ============================ ServerFile implementation ============================
3213

3214
ServerFile::ServerFile(ServerImpl& server, ServerFileAccessCache& cache, const std::string& virt_path,
3215
                       std::string real_path, bool disable_sync_to_disk)
3216
    : logger{util::LogCategory::server, "ServerFile[" + virt_path + "]: ", server.logger_ptr}               // Throws
3217
    , wlogger{util::LogCategory::server, "ServerFile[" + virt_path + "]: ", server.get_worker().logger_ptr} // Throws
3218
    , m_server{server}
3219
    , m_file{cache, real_path, virt_path, false, disable_sync_to_disk} // Throws
3220
    , m_worker_file{server.get_worker().get_file_access_cache(), real_path, virt_path, true, disable_sync_to_disk}
656✔
3221
{
9,324✔
3222
}
8,668✔
3223

3224

3225
ServerFile::~ServerFile() noexcept
656✔
3226
{
9,324✔
3227
    REALM_ASSERT(m_unidentified_sessions.empty());
9,324✔
3228
    REALM_ASSERT(m_identified_sessions.empty());
9,324✔
3229
    REALM_ASSERT(m_file_ident_request == 0);
9,324✔
3230
}
8,668✔
3231

3232

3233
void ServerFile::initialize()
656✔
3234
{
9,324✔
3235
    const ServerHistory& history = access().history; // Throws
9,324✔
3236
    file_ident_type partial_file_ident = 0;
9,324✔
3237
    version_type partial_progress_reference_version = 0;
9,324✔
3238
    bool has_upstream_sync_status;
9,324✔
3239
    history.get_status(m_version_info, has_upstream_sync_status, partial_file_ident,
9,324✔
3240
                       partial_progress_reference_version); // Throws
9,324✔
3241
    REALM_ASSERT(!has_upstream_sync_status);
9,324✔
3242
    REALM_ASSERT(partial_file_ident == 0);
9,324✔
3243
}
8,668✔
3244

3245

656✔
3246
void ServerFile::activate() {}
8,668✔
3247

3248

3249
// This function must be called only after a completed invocation of
3250
// initialize(). Both functinos must only ever be called by the network event
3251
// loop thread.
46,286✔
3252
void ServerFile::register_client_access(file_ident_type) {}
724,082✔
3253

3254

3255
auto ServerFile::request_file_ident(FileIdentReceiver& receiver, file_ident_type proxy_file, ClientType client_type)
3256
    -> file_ident_request_type
958✔
3257
{
19,270✔
3258
    auto request = ++m_last_file_ident_request;
19,270✔
3259
    m_file_ident_requests[request] = {&receiver, proxy_file, client_type}; // Throws
18,312✔
3260

10,020✔
3261
    on_work_added(); // Throws
19,270✔
3262
    return request;
19,270✔
3263
}
18,312✔
3264

3265

3266
void ServerFile::cancel_file_ident_request(file_ident_request_type request) noexcept
248✔
3267
{
8,248✔
3268
    auto i = m_file_ident_requests.find(request);
8,248✔
3269
    REALM_ASSERT(i != m_file_ident_requests.end());
8,248✔
3270
    FileIdentRequestInfo& info = i->second;
8,248✔
3271
    REALM_ASSERT(info.receiver);
8,248✔
3272
    info.receiver = nullptr;
8,248✔
3273
}
8,000✔
3274

3275

3276
void ServerFile::add_unidentified_session(Session* sess)
3,900✔
3277
{
54,836✔
3278
    REALM_ASSERT(m_unidentified_sessions.count(sess) == 0);
54,836✔
3279
    m_unidentified_sessions.insert(sess); // Throws
54,836✔
3280
}
50,936✔
3281

3282

3283
void ServerFile::identify_session(Session* sess, file_ident_type client_file_ident)
3,576✔
3284
{
44,998✔
3285
    REALM_ASSERT(m_unidentified_sessions.count(sess) == 1);
44,998✔
3286
    REALM_ASSERT(m_identified_sessions.count(client_file_ident) == 0);
41,422✔
3287

19,924✔
3288
    m_identified_sessions[client_file_ident] = sess; // Throws
44,998✔
3289
    m_unidentified_sessions.erase(sess);
44,998✔
3290
}
41,422✔
3291

3292

3293
void ServerFile::remove_unidentified_session(Session* sess) noexcept
324✔
3294
{
9,840✔
3295
    REALM_ASSERT(m_unidentified_sessions.count(sess) == 1);
9,840✔
3296
    m_unidentified_sessions.erase(sess);
9,840✔
3297
}
9,516✔
3298

3299

3300
void ServerFile::remove_identified_session(file_ident_type client_file_ident) noexcept
3,576✔
3301
{
44,998✔
3302
    REALM_ASSERT(m_identified_sessions.count(client_file_ident) == 1);
44,998✔
3303
    m_identified_sessions.erase(client_file_ident);
44,998✔
3304
}
41,422✔
3305

3306

3307
Session* ServerFile::get_identified_session(file_ident_type client_file_ident) noexcept
3,576✔
3308
{
45,000✔
3309
    auto i = m_identified_sessions.find(client_file_ident);
45,000✔
3310
    if (i == m_identified_sessions.end())
45,000✔
3311
        return nullptr;
41,424✔
3312
    return i->second;
×
3313
}
3314

3315
bool ServerFile::can_add_changesets_from_downstream() const noexcept
23,154✔
3316
{
384,834✔
3317
    return (m_blocked_changesets_from_downstream_byte_size < m_server.get_max_upload_backlog());
384,834✔
3318
}
361,680✔
3319

3320

3321
void ServerFile::add_changesets_from_downstream(file_ident_type client_file_ident, UploadCursor upload_progress,
3322
                                                version_type locked_server_version, const UploadChangeset* changesets,
3323
                                                std::size_t num_changesets)
23,070✔
3324
{
383,082✔
3325
    register_client_access(client_file_ident); // Throws
360,012✔
3326

201,740✔
3327
    bool dirty = false;
360,012✔
3328

201,740✔
3329
    IntegratableChangesetList& list = m_changesets_from_downstream[client_file_ident]; // Throws
383,082✔
3330
    std::size_t num_bytes = 0;
400,722✔
3331
    for (std::size_t i = 0; i < num_changesets; ++i) {
653,506✔
3332
        const UploadChangeset& uc = changesets[i];
293,494✔
3333
        auto& changesets = list.changesets;
293,494✔
3334
        changesets.emplace_back(client_file_ident, uc.origin_timestamp, uc.origin_file_ident, uc.upload_cursor,
293,494✔
3335
                                uc.changeset); // Throws
293,494✔
3336
        num_bytes += uc.changeset.size();
293,494✔
3337
        dirty = true;
293,494✔
3338
    }
275,854✔
3339

201,740✔
3340
    REALM_ASSERT(upload_progress.client_version >= list.upload_progress.client_version);
383,082✔
3341
    REALM_ASSERT(are_mutually_consistent(upload_progress, list.upload_progress));
383,082✔
3342
    if (upload_progress.client_version > list.upload_progress.client_version) {
383,104✔
3343
        list.upload_progress = upload_progress;
383,098✔
3344
        dirty = true;
383,098✔
3345
    }
360,028✔
3346

201,740✔
3347
    REALM_ASSERT(locked_server_version >= list.locked_server_version);
383,082✔
3348
    if (locked_server_version > list.locked_server_version) {
378,910✔
3349
        list.locked_server_version = locked_server_version;
326,982✔
3350
        dirty = true;
326,982✔
3351
    }
308,084✔
3352

201,740✔
3353
    if (REALM_LIKELY(dirty)) {
383,106✔
3354
        if (num_changesets > 0) {
371,120✔
3355
            on_changesets_from_downstream_added(num_changesets, num_bytes); // Throws
194,526✔
3356
        }
195,416✔
3357
        else {
188,574✔
3358
            on_work_added(); // Throws
188,574✔
3359
        }
199,664✔
3360
    }
383,100✔
3361
}
360,012✔
3362

3363

3364
BootstrapError ServerFile::bootstrap_client_session(SaltedFileIdent client_file_ident,
3365
                                                    DownloadCursor download_progress, SaltedVersion server_version,
3366
                                                    ClientType client_type, UploadCursor& upload_progress,
3367
                                                    version_type& locked_server_version, Logger& logger)
3,592✔
3368
{
41,674✔
3369
    // The Realm file may contain a later snapshot than the one reflected by
16,472✔
3370
    // `m_sync_version`, but if so, the client cannot "legally" know about it.
20,064✔
3371
    if (server_version.version > m_version_info.sync_version.version)
41,684✔
3372
        return BootstrapError::bad_server_version;
160✔
3373

19,974✔
3374
    const ServerHistory& hist = access().history; // Throws
45,096✔
3375
    BootstrapError error = hist.bootstrap_client_session(client_file_ident, download_progress, server_version,
45,096✔
3376
                                                         client_type, upload_progress, locked_server_version,
45,096✔
3377
                                                         logger); // Throws
41,514✔
3378

16,392✔
3379
    // FIXME: Rather than taking previously buffered changesets from the same
16,392✔
3380
    // client file into account when determining the upload progress, and then
16,392✔
3381
    // allowing for an error during the integration of those changesets to be
16,392✔
3382
    // reported to, and terminate the new session, consider to instead postpone
16,392✔
3383
    // the bootstrapping of the new session until all previously buffered
16,392✔
3384
    // changesets from same client file have been fully processed.
16,392✔
3385

19,974✔
3386
    if (error == BootstrapError::no_error) {
45,090✔
3387
        register_client_access(client_file_ident.ident); // Throws
41,422✔
3388

16,348✔
3389
        // If upload, or releaseing of server versions progressed further during
16,348✔
3390
        // previous sessions than the persisted points, take that into account
19,924✔
3391
        auto i = m_work.changesets_from_downstream.find(client_file_ident.ident);
44,998✔
3392
        if (i != m_work.changesets_from_downstream.end()) {
43,594✔
3393
            const IntegratableChangesetList& list = i->second;
21,894✔
3394
            REALM_ASSERT(list.upload_progress.client_version >= upload_progress.client_version);
21,894✔
3395
            upload_progress = list.upload_progress;
21,894✔
3396
            REALM_ASSERT(list.locked_server_version >= locked_server_version);
21,894✔
3397
            locked_server_version = list.locked_server_version;
21,894✔
3398
        }
23,298✔
3399
        auto j = m_changesets_from_downstream.find(client_file_ident.ident);
44,998✔
3400
        if (j != m_changesets_from_downstream.end()) {
41,438✔
3401
            const IntegratableChangesetList& list = j->second;
1,232✔
3402
            REALM_ASSERT(list.upload_progress.client_version >= upload_progress.client_version);
1,232✔
3403
            upload_progress = list.upload_progress;
1,232✔
3404
            REALM_ASSERT(list.locked_server_version >= locked_server_version);
1,232✔
3405
            locked_server_version = list.locked_server_version;
1,232✔
3406
        }
4,792✔
3407
    }
41,422✔
3408

19,974✔
3409
    return error;
45,096✔
3410
}
41,514✔
3411

3412
// NOTE: This function is executed by the worker thread
3413
void ServerFile::worker_process_work_unit(WorkerState& state)
19,762✔
3414
{
326,516✔
3415
    SteadyTimePoint start_time = steady_clock_now();
326,516✔
3416
    milliseconds_type parallel_time = 0;
306,754✔
3417

172,846✔
3418
    Work& work = m_work;
326,516✔
3419
    wlogger.debug("Work unit execution started"); // Throws
306,754✔
3420

172,846✔
3421
    if (work.has_primary_work) {
326,530✔
3422
        if (REALM_UNLIKELY(!m_work.file_ident_alloc_slots.empty()))
307,654✔
3423
            worker_allocate_file_identifiers(); // Throws
161,284✔
3424

172,846✔
3425
        if (!m_work.changesets_from_downstream.empty())
325,630✔
3426
            worker_integrate_changes_from_downstream(state); // Throws
313,780✔
3427
    }
306,760✔
3428

172,846✔
3429
    wlogger.debug("Work unit execution completed"); // Throws
306,754✔
3430

172,846✔
3431
    milliseconds_type time = steady_duration(start_time);
326,516✔
3432
    milliseconds_type seq_time = time - parallel_time;
326,516✔
3433
    m_server.m_seq_time.fetch_add(seq_time, std::memory_order_relaxed);
326,516✔
3434
    m_server.m_par_time.fetch_add(parallel_time, std::memory_order_relaxed);
306,754✔
3435

153,084✔
3436
    // Pass control back to the network event loop thread
172,846✔
3437
    network::Service& service = m_server.get_service();
326,384✔
3438
    service.post([this](Status) {
305,678✔
3439
        // FIXME: The safety of capturing `this` here, relies on the fact
151,162✔
3440
        // that ServerFile objects currently are not destroyed until the
151,162✔
3441
        // server object is destroyed.
170,792✔
3442
        group_postprocess_stage_1(); // Throws
303,756✔
3443
        // Suicide may have happened at this point
170,792✔
3444
    }); // Throws
323,518✔
3445
}
306,754✔
3446

3447

3448
void ServerFile::on_changesets_from_downstream_added(std::size_t num_changesets, std::size_t num_bytes)
11,090✔
3449
{
194,524✔
3450
    m_num_changesets_from_downstream += num_changesets;
183,434✔
3451

105,776✔
3452
    if (num_bytes > 0) {
194,526✔
3453
        m_blocked_changesets_from_downstream_byte_size += num_bytes;
194,524✔
3454
        get_server().inc_byte_size_for_pending_downstream_changesets(num_bytes); // Throws
194,524✔
3455
    }
183,434✔
3456

105,776✔
3457
    on_work_added(); // Throws
194,524✔
3458
}
183,434✔
3459

3460

3461
void ServerFile::on_work_added()
24,028✔
3462
{
402,362✔
3463
    if (m_has_blocked_work)
382,566✔
3464
        return;
90,432✔
3465
    m_has_blocked_work = true;
307,698✔
3466
    // Reference file
173,212✔
3467
    if (m_has_work_in_progress)
313,046✔
3468
        return;
102,940✔
3469
    group_unblock_work(); // Throws
233,654✔
3470
}
219,206✔
3471

3472

3473
void ServerFile::group_unblock_work()
19,790✔
3474
{
327,114✔
3475
    REALM_ASSERT(!m_has_work_in_progress);
327,114✔
3476
    if (REALM_LIKELY(!m_server.is_sync_stopped())) {
327,124✔
3477
        unblock_work(); // Throws
327,106✔
3478
        const Work& work = m_work;
327,106✔
3479
        if (REALM_LIKELY(work.has_primary_work)) {
327,088✔
3480
            logger.trace("Work unit unblocked"); // Throws
326,620✔
3481
            m_has_work_in_progress = true;
326,620✔
3482
            Worker& worker = m_server.get_worker();
326,620✔
3483
            worker.enqueue(this); // Throws
326,620✔
3484
        }
326,640✔
3485
    }
327,106✔
3486
}
307,324✔
3487

3488

3489
void ServerFile::unblock_work()
19,790✔
3490
{
327,104✔
3491
    REALM_ASSERT(m_has_blocked_work);
307,314✔
3492

172,930✔
3493
    m_work.reset();
307,314✔
3494

153,140✔
3495
    // Discard requests for file identifiers whose receiver is no longer
153,140✔
3496
    // waiting.
172,930✔
3497
    {
327,104✔
3498
        auto i = m_file_ident_requests.begin();
327,104✔
3499
        auto end = m_file_ident_requests.end();
328,062✔
3500
        while (i != end) {
326,282✔
3501
            auto j = i++;
18,968✔
3502
            const FileIdentRequestInfo& info = j->second;
18,968✔
3503
            if (!info.receiver)
18,050✔
3504
                m_file_ident_requests.erase(j);
5,752✔
3505
        }
37,800✔
3506
    }
327,104✔
3507
    std::size_t n = m_file_ident_requests.size();
327,104✔
3508
    if (n > 0) {
308,212✔
3509
        m_work.file_ident_alloc_slots.resize(n); // Throws
13,704✔
3510
        std::size_t i = 0;
13,724✔
3511
        for (const auto& pair : m_file_ident_requests) {
14,136✔
3512
            const FileIdentRequestInfo& info = pair.second;
14,136✔
3513
            FileIdentAllocSlot& slot = m_work.file_ident_alloc_slots[i];
14,136✔
3514
            slot.proxy_file = info.proxy_file;
14,136✔
3515
            slot.client_type = info.client_type;
14,136✔
3516
            ++i;
14,136✔
3517
        }
14,116✔
3518
        m_work.has_primary_work = true;
13,704✔
3519
    }
12,806✔
3520

153,140✔
3521
    // FIXME: `ServerFile::m_changesets_from_downstream` and
153,140✔
3522
    // `Work::changesets_from_downstream` should be renamed to something else,
153,140✔
3523
    // as it may contain kinds of data other than changesets.
153,140✔
3524

172,930✔
3525
    using std::swap;
327,104✔
3526
    swap(m_changesets_from_downstream, m_work.changesets_from_downstream);
327,104✔
3527
    m_work.have_changesets_from_downstream = (m_num_changesets_from_downstream > 0);
327,104✔
3528
    bool has_changesets = !m_work.changesets_from_downstream.empty();
327,104✔
3529
    if (has_changesets) {
326,188✔
3530
        m_work.has_primary_work = true;
312,954✔
3531
    }
294,080✔
3532

153,140✔
3533
    // Keep track of the size of pending changesets
172,930✔
3534
    REALM_ASSERT(m_unblocked_changesets_from_downstream_byte_size == 0);
327,104✔
3535
    m_unblocked_changesets_from_downstream_byte_size = m_blocked_changesets_from_downstream_byte_size;
327,104✔
3536
    m_blocked_changesets_from_downstream_byte_size = 0;
307,314✔
3537

172,930✔
3538
    m_num_changesets_from_downstream = 0;
327,104✔
3539
    m_has_blocked_work = false;
327,104✔
3540
}
307,314✔
3541

3542

3543
void ServerFile::resume_download() noexcept
10,646✔
3544
{
193,018✔
3545
    for (const auto& entry : m_identified_sessions) {
298,050✔
3546
        Session& sess = *entry.second;
298,050✔
3547
        sess.ensure_enlisted_to_send();
298,050✔
3548
    }
292,580✔
3549
}
176,902✔
3550

3551

3552
void ServerFile::recognize_external_change()
2,398✔
3553
{
40,794✔
3554
    VersionInfo prev_version_info = m_version_info;
40,794✔
3555
    const ServerHistory& history = access().history;       // Throws
40,794✔
3556
    bool has_upstream_status;                              // Dummy
40,794✔
3557
    sync::file_ident_type partial_file_ident;              // Dummy
40,794✔
3558
    sync::version_type partial_progress_reference_version; // Dummy
40,794✔
3559
    history.get_status(m_version_info, has_upstream_status, partial_file_ident,
40,794✔
3560
                       partial_progress_reference_version); // Throws
38,396✔
3561

21,598✔
3562
    REALM_ASSERT(m_version_info.realm_version >= prev_version_info.realm_version);
40,794✔
3563
    REALM_ASSERT(m_version_info.sync_version.version >= prev_version_info.sync_version.version);
40,794✔
3564
    if (m_version_info.sync_version.version > prev_version_info.sync_version.version) {
40,794✔
3565
        REALM_ASSERT(m_version_info.realm_version > prev_version_info.realm_version);
40,784✔
3566
        resume_download();
40,784✔
3567
    }
40,784✔
3568
}
38,396✔
3569

3570

3571
// NOTE: This function is executed by the worker thread
3572
void ServerFile::worker_allocate_file_identifiers()
894✔
3573
{
13,662✔
3574
    Work& work = m_work;
13,662✔
3575
    REALM_ASSERT(!work.file_ident_alloc_slots.empty());
13,662✔
3576
    ServerHistory& hist = worker_access().history;                                      // Throws
13,662✔
3577
    hist.allocate_file_identifiers(m_work.file_ident_alloc_slots, m_work.version_info); // Throws
13,662✔
3578
    m_work.produced_new_realm_version = true;
13,662✔
3579
}
12,768✔
3580

3581

3582
// Returns true when, and only when this function produces a new sync version
3583
// (adds a new entry to the sync history).
3584
//
3585
// NOTE: This function is executed by the worker thread
3586
bool ServerFile::worker_integrate_changes_from_downstream(WorkerState& state)
18,870✔
3587
{
312,888✔
3588
    REALM_ASSERT(!m_work.changesets_from_downstream.empty());
294,018✔
3589

167,416✔
3590
    std::unique_ptr<ServerHistory> hist_ptr;
312,888✔
3591
    DBRef sg_ptr;
312,888✔
3592
    ServerHistory& hist = get_client_file_history(state, hist_ptr, sg_ptr);
312,888✔
3593
    bool backup_whole_realm = false;
312,888✔
3594
    bool produced_new_realm_version = hist.integrate_client_changesets(
312,888✔
3595
        m_work.changesets_from_downstream, m_work.version_info, backup_whole_realm, m_work.integration_result,
312,888✔
3596
        wlogger); // Throws
312,888✔
3597
    bool produced_new_sync_version = !m_work.integration_result.integrated_changesets.empty();
312,888✔
3598
    REALM_ASSERT(!produced_new_sync_version || produced_new_realm_version);
312,888✔
3599
    if (produced_new_realm_version) {
312,872✔
3600
        m_work.produced_new_realm_version = true;
312,708✔
3601
        if (produced_new_sync_version) {
302,102✔
3602
            m_work.produced_new_sync_version = true;
146,848✔
3603
        }
157,454✔
3604
    }
312,724✔
3605
    return produced_new_sync_version;
312,888✔
3606
}
294,018✔
3607

3608
ServerHistory& ServerFile::get_client_file_history(WorkerState& state, std::unique_ptr<ServerHistory>& hist_ptr,
3609
                                                   DBRef& sg_ptr)
18,870✔
3610
{
312,892✔
3611
    if (state.use_file_cache)
312,892✔
3612
        return worker_access().history; // Throws
294,028✔
3613
    const std::string& path = m_worker_file.realm_path;
6,442,450,943✔
3614
    hist_ptr = m_server.make_history_for_path();                   // Throws
6,442,450,943✔
3615
    DBOptions options = m_worker_file.make_shared_group_options(); // Throws
6,442,450,943✔
3616
    sg_ptr = DB::create(*hist_ptr, path, options);                 // Throws
6,442,450,943✔
3617
    sg_ptr->claim_sync_agent();                                    // Throws
6,442,450,943✔
3618
    return *hist_ptr;                                              // Throws
6,442,450,943✔
3619
}
6,442,450,943✔
3620

3621

3622
// When worker thread finishes work unit.
3623
void ServerFile::group_postprocess_stage_1()
19,630✔
3624
{
323,386✔
3625
    REALM_ASSERT(m_has_work_in_progress);
303,756✔
3626

170,792✔
3627
    group_finalize_work_stage_1(); // Throws
323,386✔
3628
    group_finalize_work_stage_2(); // Throws
323,386✔
3629
    group_postprocess_stage_2();   // Throws
323,386✔
3630
}
303,756✔
3631

3632

3633
void ServerFile::group_postprocess_stage_2()
19,630✔
3634
{
323,386✔
3635
    REALM_ASSERT(m_has_work_in_progress);
323,386✔
3636
    group_postprocess_stage_3(); // Throws
303,756✔
3637
    // Suicide may have happened at this point
170,796✔
3638
}
303,756✔
3639

3640

3641
// When all files, including the reference file, have been backed up.
3642
void ServerFile::group_postprocess_stage_3()
19,630✔
3643
{
323,382✔
3644
    REALM_ASSERT(m_has_work_in_progress);
323,382✔
3645
    m_has_work_in_progress = false;
303,752✔
3646

170,796✔
3647
    logger.trace("Work unit postprocessing complete"); // Throws
323,382✔
3648
    if (m_has_blocked_work)
309,094✔
3649
        group_unblock_work(); // Throws
107,742✔
3650
}
303,752✔
3651

3652

3653
void ServerFile::finalize_work_stage_1()
19,630✔
3654
{
323,390✔
3655
    if (m_unblocked_changesets_from_downstream_byte_size > 0) {
303,760✔
3656
        // Report the byte size of completed downstream changesets.
82,152✔
3657
        std::size_t byte_size = m_unblocked_changesets_from_downstream_byte_size;
146,938✔
3658
        get_server().dec_byte_size_for_pending_downstream_changesets(byte_size); // Throws
146,938✔
3659
        m_unblocked_changesets_from_downstream_byte_size = 0;
146,938✔
3660
    }
138,678✔
3661

151,164✔
3662
    // Deal with errors (bad changesets) pertaining to downstream clients
170,794✔
3663
    std::size_t num_changesets_removed = 0;
323,390✔
3664
    std::size_t num_bytes_removed = 0;
303,772✔
3665
    for (const auto& entry : m_work.integration_result.excluded_client_files) {
151,262✔
3666
        file_ident_type client_file_ident = entry.first;
168✔
3667
        ExtendedIntegrationError error = entry.second;
168✔
3668
        ProtocolError error_2 = ProtocolError::other_session_error;
168✔
3669
        switch (error) {
156✔
3670
            case ExtendedIntegrationError::client_file_expired:
✔
3671
                logger.debug("Changeset integration failed: Client file entry "
×
3672
                             "expired during session"); // Throws
×
3673
                error_2 = ProtocolError::client_file_expired;
×
3674
                break;
✔
3675
            case ExtendedIntegrationError::bad_origin_file_ident:
✔
3676
                error_2 = ProtocolError::bad_origin_file_ident;
×
3677
                break;
12✔
3678
            case ExtendedIntegrationError::bad_changeset:
168✔
3679
                error_2 = ProtocolError::bad_changeset;
168✔
3680
                break;
168✔
3681
        }
168✔
3682
        auto i = m_identified_sessions.find(client_file_ident);
168✔
3683
        if (i != m_identified_sessions.end()) {
168✔
3684
            Session& sess = *i->second;
168✔
3685
            SyncConnection& conn = sess.get_connection();
168✔
3686
            conn.protocol_error(error_2, &sess); // Throws
168✔
3687
        }
168✔
3688
        const IntegratableChangesetList& list = m_changesets_from_downstream[client_file_ident];
168✔
3689
        std::size_t num_changesets = list.changesets.size();
168✔
3690
        std::size_t num_bytes = 0;
168✔
3691
        for (const IntegratableChangeset& ic : list.changesets)
156✔
3692
            num_bytes += ic.changeset.size();
12✔
3693
        logger.info("Excluded %1 changesets of combined byte size %2 for client file %3", num_changesets, num_bytes,
168✔
3694
                    client_file_ident); // Throws
168✔
3695
        num_changesets_removed += num_changesets;
168✔
3696
        num_bytes_removed += num_bytes;
168✔
3697
        m_changesets_from_downstream.erase(client_file_ident);
168✔
3698
    }
156✔
3699

170,794✔
3700
    REALM_ASSERT(num_changesets_removed <= m_num_changesets_from_downstream);
323,390✔
3701
    REALM_ASSERT(num_bytes_removed <= m_blocked_changesets_from_downstream_byte_size);
303,760✔
3702

170,794✔
3703
    if (num_changesets_removed == 0)
323,390✔
3704
        return;
303,754✔
3705

4✔
3706
    m_num_changesets_from_downstream -= num_changesets_removed;
2,147,483,655✔
3707

4✔
3708
    // The byte size of the blocked changesets must be decremented.
4!
3709
    if (num_bytes_removed > 0) {
2,147,483,655✔
3710
        m_blocked_changesets_from_downstream_byte_size -= num_bytes_removed;
×
3711
        get_server().dec_byte_size_for_pending_downstream_changesets(num_bytes_removed); // Throws
×
UNCOV
3712
    }
×
3713
}
2,147,483,655✔
3714

3715

3716
void ServerFile::finalize_work_stage_2()
19,628✔
3717
{
303,752✔
3718
    // Expose new snapshot to remote peers
170,788✔
3719
    REALM_ASSERT(m_work.produced_new_realm_version || m_work.version_info.realm_version == 0);
323,380✔
3720
    if (m_work.version_info.realm_version > m_version_info.realm_version) {
323,354✔
3721
        REALM_ASSERT(m_work.version_info.sync_version.version >= m_version_info.sync_version.version);
323,050✔
3722
        m_version_info = m_work.version_info;
323,050✔
3723
    }
303,448✔
3724

170,788✔
3725
    bool resume_download_and_upload = m_work.produced_new_sync_version;
303,752✔
3726

151,160✔
3727
    // Deliver allocated file identifiers to requesters
170,788✔
3728
    REALM_ASSERT(m_file_ident_requests.size() >= m_work.file_ident_alloc_slots.size());
323,380✔
3729
    auto begin = m_file_ident_requests.begin();
323,380✔
3730
    auto i = begin;
304,656✔
3731
    for (const FileIdentAllocSlot& slot : m_work.file_ident_alloc_slots) {
160,332✔
3732
        FileIdentRequestInfo& info = i->second;
13,932✔
3733
        REALM_ASSERT(info.proxy_file == slot.proxy_file);
13,932✔
3734
        REALM_ASSERT(info.client_type == slot.client_type);
13,932✔
3735
        if (FileIdentReceiver* receiver = info.receiver) {
13,738✔
3736
            info.receiver = nullptr;
11,022✔
3737
            receiver->receive_file_ident(slot.file_ident); // Throws
11,022✔
3738
        }
11,216✔
3739
        ++i;
13,932✔
3740
    }
32,656✔
3741
    m_file_ident_requests.erase(begin, i);
303,752✔
3742

151,160✔
3743
    // Resume download to downstream clients
170,788✔
3744
    if (resume_download_and_upload) {
312,000✔
3745
        resume_download();
146,766✔
3746
    }
158,146✔
3747
}
303,752✔
3748

3749
// ============================ Worker implementation ============================
3750

3751
Worker::Worker(ServerImpl& server)
3752
    : logger_ptr{std::make_shared<util::PrefixLogger>(util::LogCategory::server, "Worker: ", server.logger_ptr)}
3753
    // Throws
3754
    , logger(*logger_ptr)
3755
    , m_server{server}
3756
    , m_file_access_cache{server.get_config().max_open_files, logger, *this, server.get_config().encryption_key}
628✔
3757
{
11,728✔
3758
    util::seed_prng_nondeterministically(m_random); // Throws
11,728✔
3759
}
11,100✔
3760

3761

3762
void Worker::enqueue(ServerFile* file)
19,772✔
3763
{
326,654✔
3764
    util::LockGuard lock{m_mutex};
326,654✔
3765
    m_queue.push_back(file); // Throws
326,654✔
3766
    m_cond.notify_all();
326,654✔
3767
}
306,882✔
3768

3769

3770
std::mt19937_64& Worker::server_history_get_random() noexcept
1,540✔
3771
{
22,860✔
3772
    return m_random;
22,860✔
3773
}
21,320✔
3774

3775

3776
void Worker::run()
600✔
3777
{
31,016✔
3778
    for (;;) {
337,782✔
3779
        ServerFile* file = nullptr;
337,782✔
3780
        {
337,782✔
3781
            util::LockGuard lock{m_mutex};
357,910✔
3782
            for (;;) {
670,412✔
3783
                if (REALM_UNLIKELY(m_stop))
630,524✔
3784
                    return;
358,680✔
3785
                if (!m_queue.empty()) {
639,030✔
3786
                    file = m_queue.front();
326,530✔
3787
                    m_queue.pop_front();
326,530✔
3788
                    break;
326,530✔
3789
                }
326,894✔
3790
                m_cond.wait(lock);
332,626✔
3791
            }
332,860✔
3792
        }
337,182✔
3793
        file->worker_process_work_unit(m_state); // Throws
331,438✔
3794
    }
307,366✔
3795
}
10,656✔
3796

3797

3798
void Worker::stop() noexcept
600✔
3799
{
11,256✔
3800
    util::LockGuard lock{m_mutex};
11,256✔
3801
    m_stop = true;
11,256✔
3802
    m_cond.notify_all();
11,256✔
3803
}
10,656✔
3804

3805

3806
// ============================ ServerImpl implementation ============================
3807

3808
ServerImpl::ServerImpl(const std::string& root_dir, util::Optional<sync::PKey> pkey, Server::Config config)
3809
    : logger_ptr{std::make_shared<util::CategoryLogger>(util::LogCategory::server, std::move(config.logger))}
3810
    , logger{*logger_ptr}
3811
    , m_config{std::move(config)}
3812
    , m_max_upload_backlog{determine_max_upload_backlog(config)}
3813
    , m_root_dir{root_dir} // Throws
3814
    , m_access_control{std::move(pkey)}
3815
    , m_protocol_version_range{determine_protocol_version_range(config)}                 // Throws
3816
    , m_file_access_cache{m_config.max_open_files, logger, *this, config.encryption_key} // Throws
3817
    , m_worker{*this}                                                                    // Throws
3818
    , m_acceptor{get_service()}
3819
    , m_server_protocol{}       // Throws
3820
    , m_compress_memory_arena{} // Throws
628✔
3821
{
11,730✔
3822
    if (m_config.ssl) {
11,112✔
3823
        m_ssl_context = std::make_unique<network::ssl::Context>();                // Throws
202✔
3824
        m_ssl_context->use_certificate_chain_file(m_config.ssl_certificate_path); // Throws
202✔
3825
        m_ssl_context->use_private_key_file(m_config.ssl_certificate_key_path);   // Throws
202✔
3826
    }
820✔
3827
}
11,102✔
3828

3829

3830
ServerImpl::~ServerImpl() noexcept
628✔
3831
{
11,732✔
3832
    bool server_destroyed_while_still_running = m_running;
11,732✔
3833
    REALM_ASSERT_RELEASE(!server_destroyed_while_still_running);
11,732✔
3834
}
11,104✔
3835

3836

3837
void ServerImpl::start()
628✔
3838
{
11,732✔
3839
    logger.info("Realm sync server started (%1)", REALM_VER_CHUNK); // Throws
11,732✔
3840
    logger.info("Supported protocol versions: %1-%2 (%3-%4 configured)",
11,732✔
3841
                ServerImplBase::get_oldest_supported_protocol_version(), get_current_protocol_version(),
11,732✔
3842
                m_protocol_version_range.first,
11,732✔
3843
                m_protocol_version_range.second); // Throws
11,732✔
3844
    logger.info("Platform: %1", util::get_platform_info());
11,732✔
3845
    bool is_debug_build = false;
11,732✔
3846
#if REALM_DEBUG
11,732✔
3847
    is_debug_build = true;
11,732✔
3848
#endif
11,732✔
3849
    {
11,732✔
3850
        const char* lead_text = "Build mode";
11,732✔
3851
        if (is_debug_build) {
11,732✔
3852
            logger.info("%1: Debug", lead_text); // Throws
11,732✔
3853
        }
11,104✔
3854
        else {
×
3855
            logger.info("%1: Release", lead_text); // Throws
×
3856
        }
628✔
3857
    }
11,732✔
3858
    if (is_debug_build) {
11,732✔
3859
        logger.warn("Build mode is Debug! CAN SEVERELY IMPACT PERFORMANCE - "
11,732✔
3860
                    "NOT RECOMMENDED FOR PRODUCTION"); // Throws
11,732✔
3861
    }
11,732✔
3862
    logger.info("Directory holding persistent state: %1", m_root_dir);        // Throws
11,732✔
3863
    logger.info("Maximum number of open files: %1", m_config.max_open_files); // Throws
11,732✔
3864
    {
11,732✔
3865
        const char* lead_text = "Encryption";
11,732✔
3866
        if (m_config.encryption_key) {
11,106✔
3867
            logger.info("%1: Yes", lead_text); // Throws
34✔
3868
        }
658✔
3869
        else {
11,698✔
3870
            logger.info("%1: No", lead_text); // Throws
11,698✔
3871
        }
11,700✔
3872
    }
11,732✔
3873
    logger.info("Log level: %1", logger.get_level_threshold()); // Throws
11,732✔
3874
    {
11,732✔
3875
        const char* lead_text = "Disable sync to disk";
11,732✔
3876
        if (m_config.disable_sync_to_disk) {
11,384✔
3877
            logger.info("%1: All files", lead_text); // Throws
5,784✔
3878
        }
5,852✔
3879
        else {
5,948✔
3880
            logger.info("%1: No", lead_text); // Throws
5,948✔
3881
        }
6,228✔
3882
    }
11,732✔
3883
    if (m_config.disable_sync_to_disk) {
11,384✔
3884
        logger.warn("Testing/debugging feature 'disable sync to disk' enabled - "
5,784✔
3885
                    "never do this in production!"); // Throws
5,784✔
3886
    }
6,132✔
3887
    logger.info("Download compaction: %1",
11,732✔
3888
                (m_config.disable_download_compaction ? "No" : "Yes")); // Throws
11,732✔
3889
    logger.info("Download bootstrap caching: %1",
11,732✔
3890
                (m_config.enable_download_bootstrap_cache ? "Yes" : "No"));                // Throws
11,732✔
3891
    logger.info("Max download size: %1 bytes", m_config.max_download_size);                // Throws
11,732✔
3892
    logger.info("Max upload backlog: %1 bytes", m_max_upload_backlog);                     // Throws
11,732✔
3893
    logger.info("HTTP request timeout: %1 ms", m_config.http_request_timeout);             // Throws
11,732✔
3894
    logger.info("HTTP response timeout: %1 ms", m_config.http_response_timeout);           // Throws
11,732✔
3895
    logger.info("Connection reaper timeout: %1 ms", m_config.connection_reaper_timeout);   // Throws
11,732✔
3896
    logger.info("Connection reaper interval: %1 ms", m_config.connection_reaper_interval); // Throws
11,732✔
3897
    logger.info("Connection soft close timeout: %1 ms", m_config.soft_close_timeout);      // Throws
11,732✔
3898
    logger.debug("Authorization header name: %1", m_config.authorization_header_name);     // Throws
11,104✔
3899

5,764✔
3900
    m_realm_names = _impl::find_realm_files(m_root_dir); // Throws
11,104✔
3901

5,764✔
3902
    initiate_connection_reaper_timer(m_config.connection_reaper_interval); // Throws
11,104✔
3903

5,764✔
3904
    listen(); // Throws
11,732✔
3905
}
11,104✔
3906

3907

3908
void ServerImpl::run()
600✔
3909
{
11,256✔
3910
    auto ta = util::make_temp_assign(m_running, true);
10,656✔
3911

5,512✔
3912
    {
11,256✔
3913
        auto worker_thread = util::make_thread_exec_guard(m_worker, *this); // Throws
11,256✔
3914
        std::string name;
11,256✔
3915
        if (util::Thread::get_name(name)) {
11,256✔
3916
            name += "-worker";
6,344✔
3917
            worker_thread.start_with_signals_blocked(name); // Throws
6,344✔
3918
        }
5,744✔
3919
        else {
4,912✔
3920
            worker_thread.start_with_signals_blocked(); // Throws
4,912✔
3921
        }
4,912✔
3922

5,512✔
3923
        m_service.run(); // Throws
10,656✔
3924

5,512✔
3925
        worker_thread.stop_and_rethrow(); // Throws
11,256✔
3926
    }
10,656✔
3927

5,512✔
3928
    logger.info("Realm sync server stopped");
11,256✔
3929
}
10,656✔
3930

3931

3932
void ServerImpl::stop() noexcept
1,100✔
3933
{
19,002✔
3934
    util::LockGuard lock{m_mutex};
19,002✔
3935
    if (m_stopped)
18,374✔
3936
        return;
7,428✔
3937
    m_stopped = true;
11,730✔
3938
    m_wait_or_service_stopped_cond.notify_all();
11,730✔
3939
    m_service.stop();
11,730✔
3940
}
11,102✔
3941

3942

3943
void ServerImpl::inc_byte_size_for_pending_downstream_changesets(std::size_t byte_size)
11,090✔
3944
{
194,520✔
3945
    m_pending_changesets_from_downstream_byte_size += byte_size;
194,520✔
3946
    logger.debug("Byte size for pending downstream changesets incremented by "
194,520✔
3947
                 "%1 to reach a total of %2",
194,520✔
3948
                 byte_size,
194,520✔
3949
                 m_pending_changesets_from_downstream_byte_size); // Throws
194,520✔
3950
}
183,430✔
3951

3952

3953
void ServerImpl::dec_byte_size_for_pending_downstream_changesets(std::size_t byte_size)
8,260✔
3954
{
146,936✔
3955
    REALM_ASSERT(byte_size <= m_pending_changesets_from_downstream_byte_size);
146,936✔
3956
    m_pending_changesets_from_downstream_byte_size -= byte_size;
146,936✔
3957
    logger.debug("Byte size for pending downstream changesets decremented by "
146,936✔
3958
                 "%1 to reach a total of %2",
146,936✔
3959
                 byte_size,
146,936✔
3960
                 m_pending_changesets_from_downstream_byte_size); // Throws
146,936✔
3961
}
138,676✔
3962

3963

3964
std::mt19937_64& ServerImpl::server_history_get_random() noexcept
656✔
3965
{
9,324✔
3966
    return get_random();
9,324✔
3967
}
8,668✔
3968

3969

3970
void ServerImpl::listen()
628✔
3971
{
11,728✔
3972
    network::Resolver resolver{get_service()};
11,728✔
3973
    network::Resolver::Query query(m_config.listen_address, m_config.listen_port,
11,728✔
3974
                                   network::Resolver::Query::passive | network::Resolver::Query::address_configured);
11,728✔
3975
    network::Endpoint::List endpoints = resolver.resolve(query); // Throws
11,100✔
3976

5,760✔
3977
    auto i = endpoints.begin();
11,728✔
3978
    auto end = endpoints.end();
11,728✔
3979
    for (;;) {
11,732✔
3980
        std::error_code ec;
11,732✔
3981
        m_acceptor.open(i->protocol(), ec);
11,732✔
3982
        if (!ec) {
11,732✔
3983
            using SocketBase = network::SocketBase;
11,732✔
3984
            m_acceptor.set_option(SocketBase::reuse_address(m_config.reuse_address), ec);
11,732✔
3985
            if (!ec) {
11,732✔
3986
                m_acceptor.bind(*i, ec);
11,730✔
3987
                if (!ec)
11,730✔
3988
                    break;
11,102✔
3989
            }
2✔
3990
            m_acceptor.close();
2✔
3991
        }
2!
3992
        if (i + 1 == end) {
5,136!
3993
            for (auto i2 = endpoints.begin(); i2 != i; ++i2) {
×
3994
                // FIXME: We don't have the error code for previous attempts, so
3995
                // can't print a nice message.
3996
                logger.error("Failed to bind to %1:%2", i2->address(),
×
3997
                             i2->port()); // Throws
×
3998
            }
×
3999
            logger.error("Failed to bind to %1:%2: %3", i->address(), i->port(),
×
4000
                         ec.message()); // Throws
×
4001
            throw std::runtime_error("Could not create a listening socket: All endpoints failed");
×
UNCOV
4002
        }
×
4003
    }
2✔
4004

5,760✔
4005
    m_acceptor.listen(m_config.listen_backlog);
11,100✔
4006

5,760✔
4007
    network::Endpoint local_endpoint = m_acceptor.local_endpoint();
11,718✔
4008
    const char* ssl_mode = (m_ssl_context ? "TLS" : "non-TLS");
11,648✔
4009
    logger.info("Listening on %1:%2 (max backlog is %3, %4)", local_endpoint.address(), local_endpoint.port(),
11,728✔
4010
                m_config.listen_backlog, ssl_mode); // Throws
11,100✔
4011

5,760✔
4012
    initiate_accept();
11,728✔
4013
}
11,100✔
4014

4015

4016
void ServerImpl::initiate_accept()
1,588✔
4017
{
27,640✔
4018
    auto handler = [this](std::error_code ec) {
21,670✔
4019
        if (ec != util::error::operation_aborted)
16,534✔
4020
            handle_accept(ec);
16,536✔
4021
    };
17,162✔
4022
    bool is_ssl = bool(m_ssl_context);
28,268✔
4023
    m_next_http_conn.reset(new HTTPConnection(*this, ++m_next_conn_id, is_ssl));                            // Throws
28,268✔
4024
    m_acceptor.async_accept(m_next_http_conn->get_socket(), m_next_http_conn_endpoint, std::move(handler)); // Throws
28,268✔
4025
}
26,680✔
4026

4027

4028
void ServerImpl::handle_accept(std::error_code ec)
960✔
4029
{
16,536✔
4030
    if (ec) {
15,576✔
4031
        if (ec != util::error::connection_aborted) {
×
4032
            REALM_ASSERT(ec != util::error::operation_aborted);
×
4033

4034
            // We close the reserved files to get a few extra file descriptors.
×
4035
            for (size_t i = 0; i < sizeof(m_reserved_files) / sizeof(m_reserved_files[0]); ++i) {
×
4036
                m_reserved_files[i].reset();
×
4037
            }
4038

4039
            // FIXME: There are probably errors that need to be treated
4040
            // specially, and not cause the server to "crash".
4041

×
4042
            if (ec == make_basic_system_error_code(EMFILE)) {
×
4043
                logger.error("Failed to accept a connection due to the file descriptor limit, "
×
4044
                             "consider increasing the limit in your system config"); // Throws
×
4045
                throw OutOfFilesError(ec);
×
4046
            }
×
4047
            else {
×
4048
                throw std::system_error(ec);
×
4049
            }
×
4050
        }
×
4051
        logger.debug("Skipping aborted connection"); // Throws
×
4052
    }
960✔
4053
    else {
16,536✔
4054
        HTTPConnection& conn = *m_next_http_conn;
16,536✔
4055
        if (m_config.tcp_no_delay)
16,314✔
4056
            conn.get_socket().set_option(network::SocketBase::no_delay(true));       // Throws
14,034✔
4057
        m_http_connections.emplace(conn.get_id(), std::move(m_next_http_conn));      // Throws
16,536✔
4058
        Formatter& formatter = m_misc_buffers.formatter;
16,536✔
4059
        formatter.reset();
16,536✔
4060
        formatter << "[" << m_next_http_conn_endpoint.address() << "]:" << m_next_http_conn_endpoint.port(); // Throws
16,536✔
4061
        std::string remote_endpoint = {formatter.data(), formatter.size()};                                  // Throws
16,536✔
4062
        conn.initiate(std::move(remote_endpoint));                                                           // Throws
16,536✔
4063
    }
16,536✔
4064
    initiate_accept(); // Throws
16,536✔
4065
}
15,576✔
4066

4067

4068
void ServerImpl::remove_http_connection(std::int_fast64_t conn_id) noexcept
960✔
4069
{
16,532✔
4070
    m_http_connections.erase(conn_id);
16,532✔
4071
}
15,572✔
4072

4073

4074
void ServerImpl::add_sync_connection(int_fast64_t connection_id, std::unique_ptr<SyncConnection>&& sync_conn)
940✔
4075
{
16,216✔
4076
    m_sync_connections.emplace(connection_id, std::move(sync_conn));
16,216✔
4077
}
15,276✔
4078

4079

4080
void ServerImpl::remove_sync_connection(int_fast64_t connection_id)
468✔
4081
{
9,192✔
4082
    m_sync_connections.erase(connection_id);
9,192✔
4083
}
8,724✔
4084

4085

4086
void ServerImpl::set_connection_reaper_timeout(milliseconds_type timeout)
2✔
4087
{
34✔
4088
    get_service().post([this, timeout](Status) {
34✔
4089
        m_config.connection_reaper_timeout = timeout;
34✔
4090
    });
34✔
4091
}
32✔
4092

4093

4094
void ServerImpl::close_connections()
10✔
4095
{
170✔
4096
    get_service().post([this](Status) {
170✔
4097
        do_close_connections(); // Throws
170✔
4098
    });
170✔
4099
}
160✔
4100

4101

4102
bool ServerImpl::map_virtual_to_real_path(const std::string& virt_path, std::string& real_path)
36✔
4103
{
612✔
4104
    return _impl::map_virt_to_real_realm_path(m_root_dir, virt_path, real_path); // Throws
612✔
4105
}
576✔
4106

4107

4108
void ServerImpl::recognize_external_change(const std::string& virt_path)
2,400✔
4109
{
40,800✔
4110
    std::string virt_path_2 = virt_path; // Throws (copy)
40,800✔
4111
    get_service().post([this, virt_path = std::move(virt_path_2)](Status) {
40,800✔
4112
        do_recognize_external_change(virt_path); // Throws
40,800✔
4113
    });                                          // Throws
40,800✔
4114
}
38,400✔
4115

4116

4117
void ServerImpl::stop_sync_and_wait_for_backup_completion(
4118
    util::UniqueFunction<void(bool did_backup)> completion_handler, milliseconds_type timeout)
4119
{
×
4120
    logger.info("stop_sync_and_wait_for_backup_completion() called with "
×
4121
                "timeout = %1",
×
4122
                timeout); // Throws
4123

4124
    get_service().post([this, completion_handler = std::move(completion_handler), timeout](Status) mutable {
×
4125
        do_stop_sync_and_wait_for_backup_completion(std::move(completion_handler),
×
4126
                                                    timeout); // Throws
×
4127
    });
×
4128
}
4129

4130

4131
void ServerImpl::initiate_connection_reaper_timer(milliseconds_type timeout)
636✔
4132
{
12,586✔
4133
    m_connection_reaper_timer.emplace(get_service());
11,958✔
4134
    m_connection_reaper_timer->async_wait(std::chrono::milliseconds(timeout), [this, timeout](Status status) {
5,992✔
4135
        if (status != ErrorCodes::OperationAborted) {
860✔
4136
            reap_connections();                        // Throws
860✔
4137
            initiate_connection_reaper_timer(timeout); // Throws
860✔
4138
        }
860✔
4139
    }); // Throws
1,488✔
4140
}
11,950✔
4141

4142

4143
void ServerImpl::reap_connections()
8✔
4144
{
860✔
4145
    logger.debug("Discarding dead connections"); // Throws
860✔
4146
    SteadyTimePoint now = steady_clock_now();
860✔
4147
    {
860✔
4148
        auto end = m_http_connections.end();
860✔
4149
        auto i = m_http_connections.begin();
860✔
4150
        while (i != end) {
860✔
4151
            HTTPConnection& conn = *i->second;
8✔
4152
            ++i;
8✔
4153
            // Suicide
4✔
4154
            conn.terminate_if_dead(now); // Throws
8✔
4155
        }
16✔
4156
    }
860✔
4157
    {
860✔
4158
        auto end = m_sync_connections.end();
860✔
4159
        auto i = m_sync_connections.begin();
866✔
4160
        while (i != end) {
1,666✔
4161
            SyncConnection& conn = *i->second;
814✔
4162
            ++i;
808✔
4163
            // Suicide
766✔
4164
            conn.terminate_if_dead(now); // Throws
814✔
4165
        }
816✔
4166
    }
860✔
4167
}
852✔
4168

4169

4170
void ServerImpl::do_close_connections()
10✔
4171
{
170✔
4172
    for (auto& entry : m_sync_connections) {
170✔
4173
        SyncConnection& conn = *entry.second;
170✔
4174
        conn.initiate_soft_close(); // Throws
170✔
4175
    }
170✔
4176
}
160✔
4177

4178

4179
void ServerImpl::do_recognize_external_change(const std::string& virt_path)
2,400✔
4180
{
40,800✔
4181
    auto i = m_files.find(virt_path);
40,800✔
4182
    if (i == m_files.end())
38,402✔
4183
        return;
2,402✔
4184
    ServerFile& file = *i->second;
40,794✔
4185
    file.recognize_external_change();
40,794✔
4186
}
38,396✔
4187

4188

4189
void ServerImpl::do_stop_sync_and_wait_for_backup_completion(
4190
    util::UniqueFunction<void(bool did_complete)> completion_handler, milliseconds_type timeout)
4191
{
×
4192
    static_cast<void>(timeout);
×
4193
    if (m_sync_stopped)
×
4194
        return;
×
4195
    do_close_connections(); // Throws
×
4196
    m_sync_stopped = true;
×
4197
    bool completion_reached = false;
×
4198
    completion_handler(completion_reached); // Throws
×
4199
}
4200

4201

4202
// ============================ SyncConnection implementation ============================
4203

4204
SyncConnection::~SyncConnection() noexcept
940✔
4205
{
16,222✔
4206
    m_sessions_enlisted_to_send.clear();
16,222✔
4207
    m_sessions.clear();
16,222✔
4208
}
15,282✔
4209

4210

4211
void SyncConnection::initiate()
940✔
4212
{
16,222✔
4213
    m_last_activity_at = steady_clock_now();
16,222✔
4214
    logger.debug("Sync Connection initiated");
16,222✔
4215
    m_websocket.initiate_server_websocket_after_handshake();
16,222✔
4216
    send_log_message(util::Logger::Level::info, "Client connection established with server", 0,
16,222✔
4217
                     m_appservices_request_id);
16,222✔
4218
}
15,282✔
4219

4220

4221
template <class... Params>
4222
void SyncConnection::terminate(Logger::Level log_level, const char* log_message, Params... log_params)
468✔
4223
{
9,192✔
4224
    terminate_sessions();                              // Throws
9,192✔
4225
    logger.log(log_level, log_message, log_params...); // Throws
9,192✔
4226
    m_websocket.stop();
9,192✔
4227
    m_ssl_stream.reset();
9,192✔
4228
    m_socket.reset();
8,724✔
4229
    // Suicide
5,232✔
4230
    m_server.remove_sync_connection(m_id);
9,192✔
4231
}
8,724✔
4232

4233

4234
void SyncConnection::terminate_if_dead(SteadyTimePoint now)
6✔
4235
{
814✔
4236
    milliseconds_type time = steady_duration(m_last_activity_at, now);
814✔
4237
    const Server::Config& config = m_server.get_config();
814✔
4238
    if (m_is_closing) {
808✔
4239
        if (time >= config.soft_close_timeout) {
×
4240
            // Suicide
4241
            terminate(Logger::Level::detail,
×
4242
                      "Sync connection closed (timeout during soft close)"); // Throws
×
4243
        }
×
4244
    }
6✔
4245
    else {
814✔
4246
        if (time >= config.connection_reaper_timeout) {
808✔
4247
            // Suicide
18✔
4248
            terminate(Logger::Level::detail,
34✔
4249
                      "Sync connection closed (no heartbeat)"); // Throws
34✔
4250
        }
38✔
4251
    }
814✔
4252
}
808✔
4253

4254

4255
void SyncConnection::enlist_to_send(Session* sess) noexcept
56,440✔
4256
{
937,814✔
4257
    REALM_ASSERT(m_send_trigger);
937,814✔
4258
    REALM_ASSERT(!m_is_closing);
937,814✔
4259
    REALM_ASSERT(!sess->is_enlisted_to_send());
937,814✔
4260
    m_sessions_enlisted_to_send.push_back(sess);
937,814✔
4261
    m_send_trigger->trigger();
937,814✔
4262
}
881,374✔
4263

4264

4265
void SyncConnection::handle_protocol_error(Status status)
4266
{
×
4267
    logger.error("%1", status);
×
4268
    switch (status.code()) {
×
4269
        case ErrorCodes::SyncProtocolInvariantFailed:
×
4270
            protocol_error(ProtocolError::bad_syntax); // Throws
×
4271
            break;
×
4272
        case ErrorCodes::LimitExceeded:
×
4273
            protocol_error(ProtocolError::limits_exceeded); // Throws
×
4274
            break;
×
4275
        default:
×
4276
            protocol_error(ProtocolError::other_error);
×
4277
            break;
×
4278
    }
×
4279
}
4280

4281
void SyncConnection::receive_bind_message(session_ident_type session_ident, std::string path,
4282
                                          std::string signed_user_token, bool need_client_file_ident,
4283
                                          bool is_subserver)
3,914✔
4284
{
55,068✔
4285
    auto p = m_sessions.emplace(session_ident, nullptr); // Throws
55,068✔
4286
    bool was_inserted = p.second;
55,068✔
4287
    if (REALM_UNLIKELY(!was_inserted)) {
51,154✔
4288
        logger.error("Overlapping reuse of session identifier %1 in BIND message",
×
4289
                     session_ident);                           // Throws
×
4290
        protocol_error(ProtocolError::reuse_of_session_ident); // Throws
×
4291
        return;
×
4292
    }
3,914✔
4293
    try {
55,068✔
4294
        p.first->second.reset(new Session(*this, session_ident)); // Throws
55,068✔
4295
    }
51,154✔
4296
    catch (...) {
21,730✔
4297
        m_sessions.erase(p.first);
×
4298
        throw;
×
4299
    }
4300

25,652✔
4301
    Session& sess = *p.first->second;
55,076✔
4302
    sess.initiate(); // Throws
55,076✔
4303
    ProtocolError error;
55,076✔
4304
    bool success =
55,076✔
4305
        sess.receive_bind_message(std::move(path), std::move(signed_user_token), need_client_file_ident, is_subserver,
55,076✔
4306
                                  error); // Throws
55,076✔
4307
    if (REALM_UNLIKELY(!success))         // Throws
51,176✔
4308
        protocol_error(error, &sess);     // Throws
25,764✔
4309
}
51,162✔
4310

4311

4312
void SyncConnection::receive_ident_message(session_ident_type session_ident, file_ident_type client_file_ident,
4313
                                           salt_type client_file_ident_salt, version_type scan_server_version,
4314
                                           version_type scan_client_version, version_type latest_server_version,
4315
                                           salt_type latest_server_version_salt)
3,600✔
4316
{
45,406✔
4317
    auto i = m_sessions.find(session_ident);
45,406✔
4318
    if (REALM_UNLIKELY(i == m_sessions.end())) {
41,806✔
4319
        bad_session_ident("IDENT", session_ident); // Throws
×
4320
        return;
×
4321
    }
3,600✔
4322
    Session& sess = *i->second;
45,406✔
4323
    if (REALM_UNLIKELY(sess.unbind_message_received())) {
41,806✔
4324
        message_after_unbind("IDENT", session_ident); // Throws
×
4325
        return;
×
4326
    }
3,600✔
4327
    if (REALM_UNLIKELY(sess.error_occurred())) {
41,806✔
4328
        // Protocol state is SendError or WaitForUnbindErr. In these states, all
64✔
4329
        // messages, other than UNBIND, must be ignored.
72✔
4330
        return;
136✔
4331
    }
3,720✔
4332
    if (REALM_UNLIKELY(sess.must_send_ident_message())) {
41,678✔
4333
        logger.error("Received IDENT message before IDENT message was sent"); // Throws
×
4334
        protocol_error(ProtocolError::bad_message_order);                     // Throws
×
4335
        return;
×
4336
    }
3,592✔
4337
    if (REALM_UNLIKELY(sess.ident_message_received())) {
41,678✔
4338
        logger.error("Received second IDENT message for session"); // Throws
×
4339
        protocol_error(ProtocolError::bad_message_order);          // Throws
×
4340
        return;
×
4341
    }
4342

20,068✔
4343
    ProtocolError error = {};
45,270✔
4344
    bool success = sess.receive_ident_message(client_file_ident, client_file_ident_salt, scan_server_version,
45,270✔
4345
                                              scan_client_version, latest_server_version, latest_server_version_salt,
45,270✔
4346
                                              error); // Throws
45,270✔
4347
    if (REALM_UNLIKELY(!success))                     // Throws
41,694✔
4348
        protocol_error(error, &sess);                 // Throws
20,196✔
4349
}
41,678✔
4350

4351
void SyncConnection::receive_upload_message(session_ident_type session_ident, version_type progress_client_version,
4352
                                            version_type progress_server_version, version_type locked_server_version,
4353
                                            const UploadChangesets& upload_changesets)
23,154✔
4354
{
384,840✔
4355
    auto i = m_sessions.find(session_ident);
384,840✔
4356
    if (REALM_UNLIKELY(i == m_sessions.end())) {
361,686✔
4357
        bad_session_ident("UPLOAD", session_ident); // Throws
×
4358
        return;
×
4359
    }
23,154✔
4360
    Session& sess = *i->second;
384,840✔
4361
    if (REALM_UNLIKELY(sess.unbind_message_received())) {
361,686✔
4362
        message_after_unbind("UPLOAD", session_ident); // Throws
×
4363
        return;
×
4364
    }
23,154✔
4365
    if (REALM_UNLIKELY(sess.error_occurred())) {
361,686✔
4366
        // Protocol state is SendError or WaitForUnbindErr. In these states, all
4367
        // messages, other than UNBIND, must be ignored.
4368
        return;
×
4369
    }
23,154✔
4370
    if (REALM_UNLIKELY(!sess.ident_message_received())) {
361,686✔
4371
        message_before_ident("UPLOAD", session_ident); // Throws
×
4372
        return;
×
4373
    }
4374

202,746✔
4375
    ProtocolError error = {};
384,840✔
4376
    bool success = sess.receive_upload_message(progress_client_version, progress_server_version,
384,840✔
4377
                                               locked_server_version, upload_changesets, error); // Throws
384,840✔
4378
    if (REALM_UNLIKELY(!success))                                                                // Throws
361,686✔
4379
        protocol_error(error, &sess);                                                            // Throws
202,746✔
4380
}
361,686✔
4381

4382

4383
void SyncConnection::receive_mark_message(session_ident_type session_ident, request_ident_type request_ident)
7,774✔
4384
{
114,216✔
4385
    auto i = m_sessions.find(session_ident);
114,216✔
4386
    if (REALM_UNLIKELY(i == m_sessions.end())) {
106,442✔
4387
        bad_session_ident("MARK", session_ident);
×
4388
        return;
×
4389
    }
7,774✔
4390
    Session& sess = *i->second;
114,216✔
4391
    if (REALM_UNLIKELY(sess.unbind_message_received())) {
106,442✔
4392
        message_after_unbind("MARK", session_ident); // Throws
×
4393
        return;
×
4394
    }
7,774✔
4395
    if (REALM_UNLIKELY(sess.error_occurred())) {
106,442✔
4396
        // Protocol state is SendError or WaitForUnbindErr. In these states, all
192✔
4397
        // messages, other than UNBIND, must be ignored.
216✔
4398
        return;
408✔
4399
    }
8,134✔
4400
    if (REALM_UNLIKELY(!sess.ident_message_received())) {
106,058✔
4401
        message_before_ident("MARK", session_ident); // Throws
×
4402
        return;
×
4403
    }
4404

55,696✔
4405
    ProtocolError error;
113,808✔
4406
    bool success = sess.receive_mark_message(request_ident, error); // Throws
113,808✔
4407
    if (REALM_UNLIKELY(!success))                                   // Throws
106,058✔
4408
        protocol_error(error, &sess);                               // Throws
55,696✔
4409
}
106,058✔
4410

4411

4412
void SyncConnection::receive_unbind_message(session_ident_type session_ident)
2,702✔
4413
{
32,772✔
4414
    auto i = m_sessions.find(session_ident); // Throws
32,772✔
4415
    if (REALM_UNLIKELY(i == m_sessions.end())) {
30,070✔
4416
        bad_session_ident("UNBIND", session_ident); // Throws
×
4417
        return;
×
4418
    }
2,702✔
4419
    Session& sess = *i->second;
32,772✔
4420
    if (REALM_UNLIKELY(sess.unbind_message_received())) {
30,070✔
4421
        message_after_unbind("UNBIND", session_ident); // Throws
×
4422
        return;
×
4423
    }
4424

13,380✔
4425
    sess.receive_unbind_message(); // Throws
30,070✔
4426
    // NOTE: The session might have gotten destroyed at this time!
13,380✔
4427
}
30,070✔
4428

4429

4430
void SyncConnection::receive_ping(milliseconds_type timestamp, milliseconds_type rtt)
104✔
4431
{
1,526✔
4432
    logger.debug("Received: PING(timestamp=%1, rtt=%2)", timestamp, rtt); // Throws
1,526✔
4433
    m_send_pong = true;
1,526✔
4434
    m_last_ping_timestamp = timestamp;
1,526✔
4435
    if (!m_is_sending)
1,526✔
4436
        send_next_message();
1,514✔
4437
}
1,422✔
4438

4439

4440
void SyncConnection::receive_error_message(session_ident_type session_ident, int error_code,
4441
                                           std::string_view error_body)
4442
{
×
4443
    logger.debug("Received: ERROR(error_code=%1, message_size=%2, session_ident=%3)", error_code, error_body.size(),
×
4444
                 session_ident); // Throws
×
4445
    auto i = m_sessions.find(session_ident);
×
4446
    if (REALM_UNLIKELY(i == m_sessions.end())) {
×
4447
        bad_session_ident("ERROR", session_ident);
×
4448
        return;
×
4449
    }
×
4450
    Session& sess = *i->second;
×
4451
    if (REALM_UNLIKELY(sess.unbind_message_received())) {
×
4452
        message_after_unbind("ERROR", session_ident); // Throws
×
4453
        return;
×
4454
    }
4455

4456
    sess.receive_error_message(session_ident, error_code, error_body); // Throws
×
4457
}
4458

4459
void SyncConnection::send_log_message(util::Logger::Level level, const std::string&& message,
4460
                                      session_ident_type sess_ident, std::optional<std::string> co_id)
4,516✔
4461
{
61,222✔
4462
    if (get_client_protocol_version() < SyncConnection::SERVER_LOG_PROTOCOL_VERSION) {
56,706✔
4463
        return logger.log(level, message.c_str());
×
4464
    }
4465

28,458✔
4466
    LogMessage log_msg{sess_ident, level, std::move(message), std::move(co_id)};
61,222✔
4467
    {
61,222✔
4468
        std::lock_guard lock(m_log_mutex);
61,222✔
4469
        m_log_messages.push(std::move(log_msg));
61,222✔
4470
    }
61,222✔
4471
    m_send_trigger->trigger();
61,222✔
4472
}
56,706✔
4473

4474

4475
void SyncConnection::bad_session_ident(const char* message_type, session_ident_type session_ident)
4476
{
×
4477
    logger.error("Bad session identifier in %1 message, session_ident = %2", message_type,
×
4478
                 session_ident);                      // Throws
×
4479
    protocol_error(ProtocolError::bad_session_ident); // Throws
×
4480
}
4481

4482

4483
void SyncConnection::message_after_unbind(const char* message_type, session_ident_type session_ident)
4484
{
×
4485
    logger.error("Received %1 message after UNBIND message, session_ident = %2", message_type,
×
4486
                 session_ident);                      // Throws
×
4487
    protocol_error(ProtocolError::bad_message_order); // Throws
×
4488
}
4489

4490

4491
void SyncConnection::message_before_ident(const char* message_type, session_ident_type session_ident)
4492
{
×
4493
    logger.error("Received %1 message before IDENT message, session_ident = %2", message_type,
×
4494
                 session_ident);                      // Throws
×
4495
    protocol_error(ProtocolError::bad_message_order); // Throws
×
4496
}
4497

4498

4499
void SyncConnection::handle_message_received(const char* data, size_t size)
41,248✔
4500
{
592,566✔
4501
    // parse_message_received() parses the message and calls the
277,272✔
4502
    // proper handler on the SyncConnection object (this).
318,520✔
4503
    get_server_protocol().parse_message_received<SyncConnection>(*this, std::string_view(data, size));
633,814✔
4504
    return;
633,814✔
4505
}
592,566✔
4506

4507

4508
void SyncConnection::handle_ping_received(const char* data, size_t size)
4509
{
4510
    // parse_message_received() parses the message and calls the
4511
    // proper handler on the SyncConnection object (this).
4512
    get_server_protocol().parse_ping_received<SyncConnection>(*this, std::string_view(data, size));
×
4513
    return;
×
4514
}
4515

4516

4517
void SyncConnection::send_next_message()
58,132✔
4518
{
929,676✔
4519
    REALM_ASSERT(!m_is_sending);
929,676✔
4520
    REALM_ASSERT(!m_sending_pong);
929,676✔
4521
    if (m_send_pong) {
871,648✔
4522
        send_pong(m_last_ping_timestamp);
1,526✔
4523
        if (m_sending_pong)
1,526✔
4524
            return;
59,450✔
4525
    }
953,682✔
4526
    for (;;) {
1,364,266✔
4527
        Session* sess = m_sessions_enlisted_to_send.pop_front();
1,364,266✔
4528
        if (!sess) {
1,280,706✔
4529
            // No sessions were enlisted to send
221,448✔
4530
            if (REALM_LIKELY(!m_is_closing))
427,994✔
4531
                break; // Check to see if there are any log messages to go out
400,714✔
4532
            // Send a connection level ERROR
90✔
4533
            REALM_ASSERT(!is_session_level_error(m_error_code));
170✔
4534
            initiate_write_error(m_error_code, m_error_session_ident); // Throws
170✔
4535
            return;
170✔
4536
        }
56,510✔
4537
        sess->send_message(); // Throws
879,912✔
4538
        // NOTE: The session might have gotten destroyed at this time!
449,942✔
4539

449,942✔
4540
        // At this point, `m_is_sending` is true if, and only if the session
449,942✔
4541
        // chose to send a message. If it chose to not send a message, we must
449,942✔
4542
        // loop back and give the next session in `m_sessions_enlisted_to_send`
449,942✔
4543
        // a chance.
506,292✔
4544
        if (m_is_sending)
910,734✔
4545
            return;
525,738✔
4546
    }
907,108✔
4547
    {
663,092✔
4548
        std::lock_guard lock(m_log_mutex);
427,770✔
4549
        if (!m_log_messages.empty()) {
405,082✔
4550
            send_log_message(m_log_messages.front());
60,894✔
4551
            m_log_messages.pop();
60,894✔
4552
        }
83,582✔
4553
    }
400,574✔
4554
    // Otherwise, nothing to do
221,330✔
4555
}
400,574✔
4556

4557

4558
void SyncConnection::initiate_write_output_buffer()
35,332✔
4559
{
561,092✔
4560
    auto handler = [this](std::error_code ec, size_t) {
560,846✔
4561
        if (!ec) {
560,784✔
4562
            handle_write_output_buffer();
559,676✔
4563
        }
559,728✔
4564
    };
525,524✔
4565

294,440✔
4566
    m_websocket.async_write_binary(m_output_buffer.data(), m_output_buffer.size(),
561,112✔
4567
                                   std::move(handler)); // Throws
561,112✔
4568
    m_is_sending = true;
561,112✔
4569
}
525,780✔
4570

4571

4572
void SyncConnection::initiate_pong_output_buffer()
104✔
4573
{
1,526✔
4574
    auto handler = [this](std::error_code ec, size_t) {
1,526✔
4575
        if (!ec) {
1,522✔
4576
            handle_pong_output_buffer();
1,522✔
4577
        }
1,522✔
4578
    };
1,418✔
4579

692✔
4580
    REALM_ASSERT(!m_is_sending);
1,526✔
4581
    REALM_ASSERT(!m_sending_pong);
1,526✔
4582
    m_websocket.async_write_binary(m_output_buffer.data(), m_output_buffer.size(),
1,526✔
4583
                                   std::move(handler)); // Throws
1,422✔
4584

692✔
4585
    m_is_sending = true;
1,526✔
4586
    m_sending_pong = true;
1,526✔
4587
}
1,422✔
4588

4589

4590
void SyncConnection::send_pong(milliseconds_type timestamp)
104✔
4591
{
1,526✔
4592
    REALM_ASSERT(m_send_pong);
1,526✔
4593
    REALM_ASSERT(!m_sending_pong);
1,526✔
4594
    m_send_pong = false;
1,526✔
4595
    logger.debug("Sending: PONG(timestamp=%1)", timestamp); // Throws
1,422✔
4596

692✔
4597
    OutputBuffer& out = get_output_buffer();
1,526✔
4598
    get_server_protocol().make_pong(out, timestamp); // Throws
1,422✔
4599

692✔
4600
    initiate_pong_output_buffer(); // Throws
1,526✔
4601
}
1,422✔
4602

4603
void SyncConnection::send_log_message(const LogMessage& log_msg)
4,508✔
4604
{
60,894✔
4605
    OutputBuffer& out = get_output_buffer();
60,894✔
4606
    get_server_protocol().make_log_message(out, log_msg.level, log_msg.message, log_msg.sess_ident,
60,894✔
4607
                                           log_msg.co_id); // Throws
56,386✔
4608

28,378✔
4609
    initiate_write_output_buffer(); // Throws
60,894✔
4610
}
56,386✔
4611

4612

4613
void SyncConnection::handle_write_output_buffer()
35,260✔
4614
{
559,678✔
4615
    release_output_buffer();
559,678✔
4616
    m_is_sending = false;
559,678✔
4617
    send_next_message(); // Throws
559,678✔
4618
}
524,418✔
4619

4620

4621
void SyncConnection::handle_pong_output_buffer()
104✔
4622
{
1,522✔
4623
    release_output_buffer();
1,522✔
4624
    REALM_ASSERT(m_is_sending);
1,522✔
4625
    REALM_ASSERT(m_sending_pong);
1,522✔
4626
    m_is_sending = false;
1,522✔
4627
    m_sending_pong = false;
1,522✔
4628
    send_next_message(); // Throws
1,522✔
4629
}
1,418✔
4630

4631

4632
void SyncConnection::initiate_write_error(ProtocolError error_code, session_ident_type session_ident)
10✔
4633
{
170✔
4634
    const char* message = get_protocol_error_message(int(error_code));
170✔
4635
    std::size_t message_size = std::strlen(message);
170✔
4636
    bool try_again = determine_try_again(error_code);
160✔
4637

90✔
4638
    logger.detail("Sending: ERROR(error_code=%1, message_size=%2, try_again=%3, session_ident=%4)", int(error_code),
170✔
4639
                  message_size, try_again, session_ident); // Throws
160✔
4640

90✔
4641
    OutputBuffer& out = get_output_buffer();
170✔
4642
    int protocol_version = get_client_protocol_version();
170✔
4643
    get_server_protocol().make_error_message(protocol_version, out, error_code, message, message_size, try_again,
170✔
4644
                                             session_ident); // Throws
160✔
4645

90✔
4646
    auto handler = [this](std::error_code ec, size_t) {
170✔
4647
        handle_write_error(ec); // Throws
170✔
4648
    };
170✔
4649
    m_websocket.async_write_binary(out.data(), out.size(), std::move(handler));
170✔
4650
    m_is_sending = true;
170✔
4651
}
160✔
4652

4653

4654
void SyncConnection::handle_write_error(std::error_code ec)
10✔
4655
{
170✔
4656
    m_is_sending = false;
170✔
4657
    REALM_ASSERT(m_is_closing);
170✔
4658
    if (!m_ssl_stream) {
170✔
4659
        m_socket->shutdown(network::Socket::shutdown_send, ec);
170!
4660
        if (ec && ec != make_basic_system_error_code(ENOTCONN))
160!
4661
            throw std::system_error(ec);
10✔
4662
    }
170✔
4663
}
160✔
4664

4665

4666
// For connection level errors, `sess` is ignored. For session level errors, a
4667
// session must be specified.
4668
//
4669
// If a session is specified, that session object will have been detached from
4670
// the ServerFile object (and possibly destroyed) upon return from
4671
// protocol_error().
4672
//
4673
// If a session is specified for a protocol level error, that session object
4674
// will have been destroyed upon return from protocol_error(). For session level
4675
// errors, the specified session will have been destroyed upon return from
4676
// protocol_error() if, and only if the negotiated protocol version is less than
4677
// 23.
4678
void SyncConnection::protocol_error(ProtocolError error_code, Session* sess)
42✔
4679
{
678✔
4680
    REALM_ASSERT(!m_is_closing);
678✔
4681
    bool session_level = is_session_level_error(error_code);
678✔
4682
    REALM_ASSERT(!session_level || sess);
678✔
4683
    REALM_ASSERT(!sess || m_sessions.count(sess->get_session_ident()) == 1);
678✔
4684
    if (logger.would_log(util::Logger::Level::debug)) {
636✔
4685
        const char* message = get_protocol_error_message(int(error_code));
×
4686
        Logger& logger_2 = (session_level ? sess->logger : logger);
×
4687
        logger_2.debug("Protocol error: %1 (error_code=%2)", message, int(error_code)); // Throws
×
4688
    }
42✔
4689
    session_ident_type session_ident = (session_level ? sess->get_session_ident() : 0);
678✔
4690
    if (session_level) {
678✔
4691
        sess->initiate_deactivation(error_code); // Throws
678✔
4692
        return;
678✔
4693
    }
636✔
4694
    do_initiate_soft_close(error_code, session_ident); // Throws
×
4695
}
4696

4697

4698
void SyncConnection::do_initiate_soft_close(ProtocolError error_code, session_ident_type session_ident)
10✔
4699
{
170✔
4700
    REALM_ASSERT(get_protocol_error_message(int(error_code)));
160✔
4701

80✔
4702
    // With recent versions of the protocol (when the version is greater than,
80✔
4703
    // or equal to 23), this function will only be called for connection level
80✔
4704
    // errors, never for session specific errors. However, for the purpose of
80✔
4705
    // emulating earlier protocol versions, this function might be called for
80✔
4706
    // session specific errors too.
90✔
4707
    REALM_ASSERT(is_session_level_error(error_code) == (session_ident != 0));
170✔
4708
    REALM_ASSERT(!is_session_level_error(error_code));
160✔
4709

90✔
4710
    REALM_ASSERT(m_send_trigger);
170✔
4711
    REALM_ASSERT(!m_is_closing);
170✔
4712
    m_is_closing = true;
160✔
4713

90✔
4714
    m_error_code = error_code;
170✔
4715
    m_error_session_ident = session_ident;
160✔
4716

80✔
4717
    // Don't waste time and effort sending any other messages
90✔
4718
    m_send_pong = false;
170✔
4719
    m_sessions_enlisted_to_send.clear();
160✔
4720

90✔
4721
    m_receiving_session = nullptr;
160✔
4722

90✔
4723
    terminate_sessions(); // Throws
160✔
4724

90✔
4725
    m_send_trigger->trigger();
170✔
4726
}
160✔
4727

4728

4729
void SyncConnection::close_due_to_close_by_client(std::error_code ec)
254✔
4730
{
5,262✔
4731
    auto log_level = (ec == util::MiscExtErrors::end_of_input ? Logger::Level::detail : Logger::Level::info);
4,466✔
4732
    // Suicide
3,102✔
4733
    terminate(log_level, "Sync connection closed by client: %1", ec.message()); // Throws
5,308✔
4734
}
5,054✔
4735

4736

4737
void SyncConnection::close_due_to_error(std::error_code ec)
212✔
4738
{
3,638✔
4739
    // Suicide
2,112✔
4740
    terminate(Logger::Level::error, "Sync connection closed due to error: %1",
3,850✔
4741
              ec.message()); // Throws
3,850✔
4742
}
3,638✔
4743

4744

4745
void SyncConnection::terminate_sessions()
478✔
4746
{
9,578✔
4747
    for (auto& entry : m_sessions) {
14,246✔
4748
        Session& sess = *entry.second;
14,246✔
4749
        sess.terminate(); // Throws
14,246✔
4750
    }
14,030✔
4751
    m_sessions_enlisted_to_send.clear();
9,362✔
4752
    m_sessions.clear();
9,362✔
4753
}
8,884✔
4754

4755

4756
void SyncConnection::initiate_soft_close()
10✔
4757
{
170✔
4758
    if (!m_is_closing) {
170✔
4759
        session_ident_type session_ident = 0;                                    // Not session specific
170✔
4760
        do_initiate_soft_close(ProtocolError::connection_closed, session_ident); // Throws
170✔
4761
    }
170✔
4762
}
160✔
4763

4764

4765
void SyncConnection::discard_session(session_ident_type session_ident) noexcept
2,698✔
4766
{
32,688✔
4767
    m_sessions.erase(session_ident);
32,688✔
4768
}
29,990✔
4769

4770
} // anonymous namespace
4771

4772

4773
// ============================ sync::Server implementation ============================
4774

4775
class Server::Implementation : public ServerImpl {
4776
public:
4777
    Implementation(const std::string& root_dir, util::Optional<PKey> pkey, Server::Config config)
4778
        : ServerImpl{root_dir, std::move(pkey), std::move(config)} // Throws
628✔
4779
    {
11,728✔
4780
    }
11,728✔
4781
    virtual ~Implementation() {}
11,104✔
4782
};
4783

4784

4785
Server::Server(const std::string& root_dir, util::Optional<sync::PKey> pkey, Config config)
4786
    : m_impl{new Implementation{root_dir, std::move(pkey), std::move(config)}} // Throws
628✔
4787
{
11,722✔
4788
}
11,094✔
4789

4790

4791
Server::Server(Server&& serv) noexcept
4792
    : m_impl{std::move(serv.m_impl)}
4793
{
×
4794
}
4795

4796

628✔
4797
Server::~Server() noexcept {}
11,104✔
4798

4799

4800
void Server::start()
290✔
4801
{
5,954✔
4802
    m_impl->start(); // Throws
5,954✔
4803
}
5,664✔
4804

4805

4806
void Server::start(const std::string& listen_address, const std::string& listen_port, bool reuse_address)
338✔
4807
{
5,778✔
4808
    m_impl->start(listen_address, listen_port, reuse_address); // Throws
5,778✔
4809
}
5,440✔
4810

4811

4812
network::Endpoint Server::listen_endpoint() const
642✔
4813
{
11,792✔
4814
    return m_impl->listen_endpoint(); // Throws
11,792✔
4815
}
11,150✔
4816

4817

4818
void Server::run()
600✔
4819
{
11,256✔
4820
    m_impl->run(); // Throws
11,256✔
4821
}
10,656✔
4822

4823

4824
void Server::stop() noexcept
1,100✔
4825
{
19,004✔
4826
    m_impl->stop();
19,004✔
4827
}
17,904✔
4828

4829

4830
uint_fast64_t Server::errors_seen() const noexcept
338✔
4831
{
5,778✔
4832
    return m_impl->errors_seen;
5,778✔
4833
}
5,440✔
4834

4835

4836
void Server::stop_sync_and_wait_for_backup_completion(util::UniqueFunction<void(bool did_backup)> completion_handler,
4837
                                                      milliseconds_type timeout)
4838
{
×
4839
    m_impl->stop_sync_and_wait_for_backup_completion(std::move(completion_handler), timeout); // Throws
×
4840
}
4841

4842

4843
void Server::set_connection_reaper_timeout(milliseconds_type timeout)
2✔
4844
{
34✔
4845
    m_impl->set_connection_reaper_timeout(timeout);
34✔
4846
}
32✔
4847

4848

4849
void Server::close_connections()
10✔
4850
{
170✔
4851
    m_impl->close_connections();
170✔
4852
}
160✔
4853

4854

4855
bool Server::map_virtual_to_real_path(const std::string& virt_path, std::string& real_path)
36✔
4856
{
612✔
4857
    return m_impl->map_virtual_to_real_path(virt_path, real_path); // Throws
612✔
4858
}
576✔
4859

4860

4861
void Server::recognize_external_change(const std::string& virt_path)
2,400✔
4862
{
40,800✔
4863
    m_impl->recognize_external_change(virt_path); // Throws
40,800✔
4864
}
38,400✔
4865

4866

4867
void Server::get_workunit_timers(milliseconds_type& parallel_section, milliseconds_type& sequential_section)
4868
{
×
4869
    m_impl->get_workunit_timers(parallel_section, sequential_section);
×
4870
}
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